Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(mobile): keep native back navigation in app (#805)
Gener4d8eb4946c95
diff --git a/src/desktop/src-tauri/gen/android/app/build.gradle.kts b/src/desktop/src-tauri/gen/android/app/build.gradle.ktsindex 54a513250..7d16f8092 100644--- a/src/desktop/src-tauri/gen/android/app/build.gradle.kts+++ b/src/desktop/src-tauri/gen/android/app/build.gradle.kts@@ -1,4 +1,5 @@import java.util.Properties+import org.gradle.api.GradleExceptionplugins {id("com.android.application")@@ -6,6 +7,88 @@ plugins {id("rust")}+val generatedWebViewClient = file("src/main/java/ai/alook/android/generated/RustWebViewClient.kt")+val modernErrorMethod = """+ override fun onReceivedError(+ view: WebView,+ request: WebResourceRequest,+ error: WebResourceError+ ) {+""".trim('\n')+val modernRecoveryDispatch = """+ if (+ request.isForMainFrame &&+ WebviewRecovery.handleError(+ view,+ error.errorCode,+ currentUrl,+ request.url.toString(),+ )+ ) {+ return+ }++""".trim('\n')+val legacyAndSslRecoveryDispatch = "\n\n" + """+ @Suppress("DEPRECATION")+ override fun onReceivedError(+ view: WebView,+ errorCode: Int,+ description: String?,+ failingUrl: String?+ ) {+ if (!WebviewRecovery.handleError(view, errorCode, currentUrl, failingUrl)) {+ super.onReceivedError(view, errorCode, description, failingUrl)+ }+ }++ override fun onReceivedSslError(+ view: WebView,+ handler: SslErrorHandler,+ error: android.net.http.SslError+ ) {+ handler.cancel()+ WebviewRecovery.handleSslError(view, currentUrl, error.url)+ }+""".trim('\n')++fun String.occurrencesOf(value: String): Int = windowed(value.length).count { it == value }++fun wireGeneratedWebViewRecovery(sourceFile: File) {+ var source = sourceFile.readText()+ if (!source.contains(modernRecoveryDispatch)) {+ if (source.occurrencesOf(modernErrorMethod) != 1) {+ throw GradleException("Wry RustWebViewClient modern error callback changed")+ }+ source = source.replace(modernErrorMethod, modernErrorMethod + "\n" + modernRecoveryDispatch)+ }+ if (!source.contains("WebviewRecovery.handleError(view, errorCode, currentUrl, failingUrl)")) {+ val classEnd = source.lastIndexOf("\n}")+ if (classEnd < 0) {+ throw GradleException("Wry RustWebViewClient class boundary is missing")+ }+ source = source.substring(0, classEnd) + legacyAndSslRecoveryDispatch + source.substring(classEnd)+ }+ sourceFile.writeText(source)+}++fun verifyGeneratedWebViewRecovery(sourceFile: File) {+ val source = sourceFile.readText()+ val required = listOf(+ "modern main-frame recovery dispatch" to+ (modernErrorMethod + "\n" + modernRecoveryDispatch),+ "legacy recovery dispatch" to+ "WebviewRecovery.handleError(view, errorCode, currentUrl, failingUrl)",+ "SSL recovery dispatch" to+ "WebviewRecovery.handleSslError(view, currentUrl, error.url)",+ "Wry fallback" to "super.onReceivedError(view, request, error)",+ )+ val missing = required.filterNot { source.contains(it.second) }.map { it.first }+ if (missing.isNotEmpty()) {+ throw GradleException("Generated RustWebViewClient recovery gate failed: ${missing.joinToString()}")+ }+}+val tauriProperties = Properties().apply {val propFile = file("tauri.properties")if (propFile.exists()) {@@ -45,6 +128,7 @@ android {}buildTypes {getByName("debug") {+ applicationIdSuffix = ".qa.madox.nav112v2local"manifestPlaceholders["usesCleartextTraffic"] = "true"isDebuggable = trueisJniDebuggable = true@@ -91,6 +175,36 @@ dependencies {apply(from = "tauri.build.gradle.kts")+listOf(+ "UniversalDebug",+ "UniversalRelease",+ "Arm64Debug",+ "Arm64Release",+ "ArmDebug",+ "ArmRelease",+ "X86Debug",+ "X86Release",+ "X86_64Debug",+ "X86_64Release",+).forEach { variant ->+ tasks.matching { it.name == "rustBuild$variant" }.configureEach {+ doLast {+ synchronized(project) {+ wireGeneratedWebViewRecovery(generatedWebViewClient)+ }+ }+ }+ val verify = tasks.register("verify${variant}WebviewRecovery") {+ mustRunAfter("rustBuild$variant")+ doLast {+ verifyGeneratedWebViewRecovery(generatedWebViewClient)+ }+ }+ tasks.matching { it.name == "compile${variant}Kotlin" }.configureEach {+ dependsOn(verify)+ }+}+if (file("google-services.json").exists()) {apply(plugin = "com.google.gms.google-services")}diff --git a/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/MainActivity.kt b/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/MainActivity.ktindex 1566c54ff..73632c528 100644--- a/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/MainActivity.kt+++ b/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/MainActivity.kt@@ -8,6 +8,7 @@ import android.os.Looperimport android.view.Viewimport android.webkit.JavascriptInterfaceimport android.webkit.WebView+import androidx.activity.OnBackPressedCallbackimport androidx.activity.enableEdgeToEdgeimport androidx.core.graphics.Insetsimport androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen@@ -20,7 +21,12 @@ import ai.alook.plugin.mobileshareimage.MobileShareImageDocumentOwnerimport ai.alook.plugin.filesave.FileSaveDocumentOwnerclass MainActivity : TauriActivity() {+ override val handleBackNavigation: Boolean = false+private var isReady = false+ private var mainWebView: WebView? = null+ private lateinit var nativeBackCallback: OnBackPressedCallback+ private lateinit var nativeBackDispatcher: NativeBackDispatcherprivate val fileSaveDocumentOwner = FileSaveDocumentOwner(this)private val mobileShareImageDocumentOwner = MobileShareImageDocumentOwner(this)@@ -50,6 +56,20 @@ class MainActivity : TauriActivity() {val splashScreen = installSplashScreen()enableEdgeToEdge()super.onCreate(savedInstanceState)+ nativeBackCallback = object : OnBackPressedCallback(true) {+ override fun handleOnBackPressed() {+ val webView = mainWebView+ if (webView == null) {+ delegateBackToSystem()+ return+ }+ nativeBackDispatcher.dispatch { script, complete ->+ webView.evaluateJavascript(script, complete)+ }+ }+ }+ nativeBackDispatcher = NativeBackDispatcher(::delegateBackToSystem)+ onBackPressedDispatcher.addCallback(this, nativeBackCallback)mobileShareImageDocumentOwner.attach(savedInstanceState)fileSaveDocumentOwner.attach(savedInstanceState)@@ -85,6 +105,8 @@ class MainActivity : TauriActivity() {}override fun onDestroy() {+ nativeBackDispatcher.close()+ mainWebView = nullmobileShareImageDocumentOwner.detach()fileSaveDocumentOwner.detach()super.onDestroy()@@ -92,6 +114,7 @@ class MainActivity : TauriActivity() {override fun onWebViewCreate(webView: WebView) {super.onWebViewCreate(webView)+ mainWebView = webViewwebView.addJavascriptInterface(ThemeBridge(this), "AlookNative")if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {@@ -99,6 +122,15 @@ class MainActivity : TauriActivity() {}}+ private fun delegateBackToSystem() {+ nativeBackCallback.isEnabled = false+ try {+ onBackPressedDispatcher.onBackPressed()+ } finally {+ nativeBackCallback.isEnabled = true+ }+ }+private fun applyWindowTheme(dark: Boolean) {val color = if (dark) Color.parseColor(COLOR_DARK) else Color.parseColor(COLOR_LIGHT)runOnUiThread {diff --git a/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/NativeBackDispatcher.kt b/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/NativeBackDispatcher.ktnew file mode 100644index 000000000..de2128c50--- /dev/null+++ b/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/NativeBackDispatcher.kt@@ -0,0 +1,46 @@+package ai.alook.android++internal class NativeBackDispatcher(+ private val delegateToSystem: () -> Unit,+) {+ private var generation = 0L+ private var inFlight = false+ private var closed = false++ fun dispatch(evaluate: (String, (String?) -> Unit) -> Unit) {+ if (closed || inFlight) return+ inFlight = true+ val currentGeneration = ++generation+ try {+ evaluate(SCRIPT) { result -> complete(currentGeneration, result == "true") }+ } catch (_: RuntimeException) {+ complete(currentGeneration, false)+ }+ }++ fun close() {+ closed = true+ inFlight = false+ generation += 1+ }++ private fun complete(currentGeneration: Long, handled: Boolean) {+ if (closed || !inFlight || currentGeneration != generation) return+ inFlight = false+ if (!handled) delegateToSystem()+ }++ companion object {+ const val SCRIPT = """+ (function() {+ try {+ var event = new Event('alook:native-back', { cancelable: true });+ window.dispatchEvent(event);+ return event.defaultPrevented;+ } catch (_error) {+ return false;+ }+ })();+ """+ }+}diff --git a/src/desktop/src-tauri/gen/android/app/src/test/java/ai/alook/android/NativeBackDispatcherTest.kt b/src/desktop/src-tauri/gen/android/app/src/test/java/ai/alook/android/NativeBackDispatcherTest.ktnew file mode 100644index 000000000..d9022628d--- /dev/null+++ b/src/desktop/src-tauri/gen/android/app/src/test/java/ai/alook/android/NativeBackDispatcherTest.kt@@ -0,0 +1,72 @@+package ai.alook.android++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class NativeBackDispatcherTest {+ @Test+ fun handledBackDoesNotDelegateToSystem() {+ var fallbacks = 0+ var script = ""+ val dispatcher = NativeBackDispatcher { fallbacks += 1 }++ dispatcher.dispatch { source, complete ->+ script = source+ complete("true")+ }++ assertTrue(script.contains("alook:native-back"))+ assertTrue(script.contains("event.defaultPrevented"))+ assertEquals(0, fallbacks)+ }++ @Test+ fun unhandledNullAndEvaluationFailureDelegateToSystem() {+ var fallbacks = 0+ val dispatcher = NativeBackDispatcher { fallbacks += 1 }++ dispatcher.dispatch { _, complete -> complete("false") }+ dispatcher.dispatch { _, complete -> complete(null) }+ dispatcher.dispatch { _, _ -> throw IllegalStateException("unavailable") }++ assertEquals(3, fallbacks)+ }++ @Test+ fun duplicateDispatchIsIgnoredWhileEvaluationIsInFlight() {+ var fallbacks = 0+ var evaluations = 0+ var completeFirst: ((String?) -> Unit)? = null+ val dispatcher = NativeBackDispatcher { fallbacks += 1 }++ dispatcher.dispatch { _, complete ->+ evaluations += 1+ completeFirst = complete+ }+ dispatcher.dispatch { _, _ -> evaluations += 1 }+ completeFirst?.invoke("false")++ assertEquals(1, evaluations)+ assertEquals(1, fallbacks)+ }++ @Test+ fun closeFencesLateEvaluationAndFutureDispatches() {+ var fallbacks = 0+ var evaluations = 0+ var completeFirst: ((String?) -> Unit)? = null+ val dispatcher = NativeBackDispatcher { fallbacks += 1 }++ dispatcher.dispatch { _, complete ->+ evaluations += 1+ completeFirst = complete+ }+ dispatcher.close()+ completeFirst?.invoke("false")+ dispatcher.dispatch { _, _ -> evaluations += 1 }++ assertEquals(1, evaluations)+ assertEquals(0, fallbacks)+ }+}diff --git a/src/desktop/src-tauri/src/webview_recovery.rs b/src/desktop/src-tauri/src/webview_recovery.rsindex 72a2136d8..ff861cb18 100644--- a/src/desktop/src-tauri/src/webview_recovery.rs+++ b/src/desktop/src-tauri/src/webview_recovery.rs@@ -48,7 +48,39 @@ impl StartupRendezvous {}pub fn register_protocol(builder: tauri::Builder<tauri::Wry>) -> tauri::Builder<tauri::Wry> {- builder.register_uri_scheme_protocol(SCHEME, |_context, request| response(request))+ builder+ .register_uri_scheme_protocol(SCHEME, |_context, request| response(request))+ .plugin(+ tauri::plugin::Builder::<tauri::Wry>::new("main-navigation-boundary")+ .on_navigation(|webview, url| {+ webview.label() != "main" || navigation_allowed(url, tauri::is_dev())+ })+ .build(),+ )+}++fn navigation_allowed(url: &Url, development: bool) -> bool {+ if !url.username().is_empty() || url.password().is_some() {+ return false;+ }++ let production = url.scheme() == "https"+ && url.host_str() == Some("alook.ai")+ && url.port_or_known_default() == Some(443);+ let recovery = url.query().is_none()+ && matches!(url.path(), BOOTSTRAP_PATH | RECOVERY_PATH)+ && ((url.scheme() == SCHEME+ && url.host_str() == Some("localhost")+ && url.port().is_none())+ || (url.scheme() == "http"+ && url.host_str() == Some(HOST)+ && url.port_or_known_default() == Some(80)));+ let local_development = development+ && url.scheme() == "http"+ && url.host_str() == Some("localhost")+ && url.port() == Some(3000);++ production || recovery || local_development}fn response(request: Request<Vec<u8>>) -> Response<Vec<u8>> {@@ -161,7 +193,7 @@ pub fn attach(window: &tauri::WebviewWindow) {let startup_window = window.clone();if let Err(error) = window.with_webview(move |webview| match platform::attach(webview) {Ok(()) if !tauri::is_dev() && STARTUP.signal_hooks_ready() => {- navigate_window_to_production(&startup_window)+ replace_window_with_production(&startup_window)}Ok(()) => {}Err(error) => eprintln!("webview recovery unavailable: {error}"),@@ -182,22 +214,24 @@ pub fn on_page_load<R: tauri::Runtime>(return;}if STARTUP.signal_bootstrap_finished() {- navigate_webview_to_production(webview);+ replace_webview_with_production(webview);}}-fn production_target() -> Url {- Url::parse(PRODUCTION_TARGET).expect("production target must be a valid URL")+fn production_replace_script() -> String {+ let target = serde_json::to_string(PRODUCTION_TARGET)+ .expect("production target must serialize as JavaScript string");+ format!("location.replace({target})")}-fn navigate_window_to_production(window: &tauri::WebviewWindow) {- if let Err(error) = window.navigate(production_target()) {+fn replace_window_with_production(window: &tauri::WebviewWindow) {+ if let Err(error) = window.eval(production_replace_script()) {eprintln!("webview recovery initial navigation unavailable: {error}");}}-fn navigate_webview_to_production<R: tauri::Runtime>(webview: &tauri::Webview<R>) {- if let Err(error) = webview.navigate(production_target()) {+fn replace_webview_with_production<R: tauri::Runtime>(webview: &tauri::Webview<R>) {+ if let Err(error) = webview.eval(production_replace_script()) {eprintln!("webview recovery initial navigation unavailable: {error}");}}@@ -240,6 +274,8 @@ mod platform {let delegate_class = delegate.class() as *const AnyClass as *mut AnyClass;unsafe {+ #[cfg(target_os = "ios")]+ let _: () = msg_send![webview, setAllowsBackForwardNavigationGestures: false];objc_setAssociatedObject(webview as *const AnyObject as *mut AnyObject,marker_key(),@@ -758,6 +794,51 @@ mod tests {));}+ #[test]+ fn main_navigation_policy_is_fail_closed() {+ for target in [+ "https://alook.ai/",+ "https://alook.ai/c/channel?after=1#message-2",+ "https://alook.ai:443/c",+ "alook-recovery://localhost/bootstrap",+ "alook-recovery://localhost/network-error#target=https%3A%2F%2Falook.ai%2Fc",+ "http://alook-recovery.localhost/network-error#target=https%3A%2F%2Falook.ai%2Fc",+ ] {+ assert!(+ navigation_allowed(&Url::parse(target).unwrap(), false),+ "rejected {target}"+ );+ }++ for target in [+ "http://alook.ai/c",+ "https://alook.ai.evil.test/c",+ "https://[email protected]/c",+ "https://alook.ai:444/c",+ "javascript:alert(1)",+ "about:blank",+ "alook-recovery://evil.test/bootstrap",+ "alook-recovery://localhost/unknown",+ "alook-recovery://localhost/bootstrap?spoof=1",+ "https://alook-recovery.localhost/network-error",+ "http://localhost:3000/c",+ ] {+ assert!(+ !navigation_allowed(&Url::parse(target).unwrap(), false),+ "accepted {target}"+ );+ }++ assert!(navigation_allowed(+ &Url::parse("http://localhost:3000/c").unwrap(),+ true,+ ));+ assert!(!navigation_allowed(+ &Url::parse("http://127.0.0.1:3000/c").unwrap(),+ true,+ ));+ }+#[test]fn invalid_fragment_fails_closed() {let html = recovery_html();@@ -828,10 +909,13 @@ mod tests {);assert!(source.contains("STARTUP.signal_hooks_ready()"));assert!(source.contains("STARTUP.signal_bootstrap_finished()"));- assert!(source.contains("navigate_window_to_production(&startup_window)"));- assert!(source.contains("navigate_webview_to_production(webview)"));- let initial_navigation = ["Url::parse(", "PRODUCTION_TARGET)"].concat();- assert_eq!(source.matches(&initial_navigation).count(), 1);+ assert!(source.contains("replace_window_with_production(&startup_window)"));+ assert!(source.contains("replace_webview_with_production(webview)"));+ assert_eq!(+ production_replace_script(),+ "location.replace(\"https://alook.ai/c\")"+ );+ assert!(source.contains("setAllowsBackForwardNavigationGestures: false"));assert!(!source.contains(&["window", ".url()"].concat()));}@@ -894,5 +978,39 @@ mod tests {assert!(wry.contains("request: WebResourceRequest"));assert!(wry.contains("request.isForMainFrame"));assert!(wry.contains("super.onReceivedError(view, request, error)"));++ let gradle = include_str!("../gen/android/app/build.gradle.kts");+ assert_order(+ gradle,+ &[+ "request.isForMainFrame &&",+ "WebviewRecovery.handleError(",+ "error.errorCode",+ "request.url.toString()",+ "super.onReceivedError(view, request, error)",+ ],+ );+ assert!(+ gradle.contains("WebviewRecovery.handleError(view, errorCode, currentUrl, failingUrl)")+ );+ assert!(gradle.contains("WebviewRecovery.handleSslError(view, currentUrl, error.url)"));+ assert!(gradle.contains("wireGeneratedWebViewRecovery"));+ assert!(gradle.contains("verifyGeneratedWebViewRecovery"));+ assert!(gradle.contains("it.name == \"rustBuild$variant\""));+ assert!(gradle.contains("mustRunAfter(\"rustBuild$variant\")"));+ assert!(gradle.contains("dependsOn(verify)"));++ let activity =+ include_str!("../gen/android/app/src/main/java/ai/alook/android/MainActivity.kt");+ assert!(activity.contains("override val handleBackNavigation: Boolean = false"));+ assert!(activity.contains("NativeBackDispatcher(::delegateBackToSystem)"));+ assert!(!activity.contains(&["can", "GoBack()"].concat()));+ assert!(!activity.contains(&[".", "goBack()"].concat()));++ let dispatcher = include_str!(+ "../gen/android/app/src/main/java/ai/alook/android/NativeBackDispatcher.kt"+ );+ assert!(dispatcher.contains("alook:native-back"));+ assert!(dispatcher.contains("if (closed || inFlight) return"));}}diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsxindex 6f5206d4b..85ceec60a 100644--- a/src/web/src/components/community/shell/shell-frame.tsx+++ b/src/web/src/components/community/shell/shell-frame.tsx@@ -35,6 +35,7 @@ import {observeOwnerServerDeleteRouteCommit,registerOwnerServerDeleteRoute,} from "@/lib/community/eject-server"+import { useNativeMobileBack } from "@/hooks/community/use-native-mobile-back"/** Shared community shell orchestration for the server and DM layouts. */export function ShellFrame(props: ShellFrameProps) {@@ -192,10 +193,21 @@ export function ShellFrame(props: ShellFrameProps) {extension: userBarExtension.active,})}, [daemonUpdate, inbox, profile, userBarExtension.active])+ const dismissNativeBackShellOverlay = useCallback(() => {+ if (userBarExtension.active === "none") return false+ dismissUserBarExtension()+ return true+ }, [dismissUserBarExtension, userBarExtension.active])const goBackMobile = useCallback(() => {if (route.parentPath) navigation.replace(route.parentPath)}, [navigation, route.parentPath])+ useNativeMobileBack({+ dismissShellOverlay: dismissNativeBackShellOverlay,+ parentPath: route.parentPath,+ replacePath,+ })+useEffect(() => {if (userBarExtension.active === "inbox" && !inbox.open) {dispatchUserBarExtension({ type: "extension.close", extension: "inbox" })diff --git a/src/web/src/hooks/community/use-native-mobile-back.dom.test.ts b/src/web/src/hooks/community/use-native-mobile-back.dom.test.tsnew file mode 100644index 000000000..a01e79929--- /dev/null+++ b/src/web/src/hooks/community/use-native-mobile-back.dom.test.ts@@ -0,0 +1,85 @@+import { createElement } from "react"+import { afterEach, describe, expect, it, vi } from "vitest"+import { render } from "@/test/react-dom-harness"+import {+ NATIVE_MOBILE_BACK_EVENT,+ useNativeMobileBack,+} from "./use-native-mobile-back"++function Harness(props: Parameters<typeof useNativeMobileBack>[0]) {+ useNativeMobileBack(props)+ return null+}++function dispatchBack() {+ const event = new Event(NATIVE_MOBILE_BACK_EVENT, { cancelable: true })+ window.dispatchEvent(event)+ return event+}++describe("useNativeMobileBack", () => {+ afterEach(() => {+ document.querySelectorAll('[data-native-back-test-layer]').forEach((node) => node.remove())+ })++ it("dismisses the top document layer before shell or route navigation", () => {+ const dismissShellOverlay = vi.fn(() => true)+ const replacePath = vi.fn()+ const keydown = vi.fn()+ document.addEventListener("keydown", keydown, { once: true })+ const layer = document.createElement("div")+ layer.dataset.slot = "dialog-content"+ layer.dataset.nativeBackTestLayer = "true"+ document.body.append(layer)+ const renderer = render(createElement(Harness, {+ dismissShellOverlay,+ parentPath: "/c/me",+ replacePath,+ }))++ const event = dispatchBack()++ expect(event.defaultPrevented).toBe(true)+ expect(keydown).toHaveBeenCalledWith(expect.objectContaining({ key: "Escape" }))+ expect(dismissShellOverlay).not.toHaveBeenCalled()+ expect(replacePath).not.toHaveBeenCalled()+ renderer.unmount()+ })++ it("dismisses a shell overlay before replacing a detail route", () => {+ const dismissShellOverlay = vi.fn(() => true)+ const replacePath = vi.fn()+ const renderer = render(createElement(Harness, {+ dismissShellOverlay,+ parentPath: "/c/me",+ replacePath,+ }))++ expect(dispatchBack().defaultPrevented).toBe(true)+ expect(dismissShellOverlay).toHaveBeenCalledOnce()+ expect(replacePath).not.toHaveBeenCalled()+ renderer.unmount()+ })++ it("replaces a detail route and leaves a root route to the system", () => {+ const dismissShellOverlay = vi.fn(() => false)+ const replacePath = vi.fn()+ const renderer = render(createElement(Harness, {+ dismissShellOverlay,+ parentPath: "/c/channels/s1",+ replacePath,+ }))++ expect(dispatchBack().defaultPrevented).toBe(true)+ expect(replacePath).toHaveBeenCalledWith("/c/channels/s1")++ renderer.rerender(createElement(Harness, {+ dismissShellOverlay,+ parentPath: null,+ replacePath,+ }))+ expect(dispatchBack().defaultPrevented).toBe(false)+ renderer.unmount()+ expect(dispatchBack().defaultPrevented).toBe(false)+ })+})diff --git a/src/web/src/hooks/community/use-native-mobile-back.ts b/src/web/src/hooks/community/use-native-mobile-back.tsnew file mode 100644index 000000000..d24937ec2--- /dev/null+++ b/src/web/src/hooks/community/use-native-mobile-back.ts@@ -0,0 +1,47 @@+import { useEffect } from "react"++export const NATIVE_MOBILE_BACK_EVENT = "alook:native-back"++const dismissibleLayerSelector = [+ '[data-slot="dialog-content"]',+ '[data-slot="alert-dialog-content"]',+ '[data-slot="sheet-content"]',+].join(",")++function dismissTopDocumentLayer(): boolean {+ const layers = document.querySelectorAll(dismissibleLayerSelector)+ if (layers.length === 0) return false+ document.dispatchEvent(new KeyboardEvent("keydown", {+ key: "Escape",+ code: "Escape",+ bubbles: true,+ cancelable: true,+ }))+ return true+}++export function useNativeMobileBack({+ dismissShellOverlay,+ parentPath,+ replacePath,+}: {+ dismissShellOverlay: () => boolean+ parentPath: string | null+ replacePath: (href: string) => void+}) {+ useEffect(() => {+ const handleBack = (event: Event) => {+ if (!event.cancelable) return+ if (dismissTopDocumentLayer() || dismissShellOverlay()) {+ event.preventDefault()+ return+ }+ if (!parentPath) return+ event.preventDefault()+ replacePath(parentPath)+ }++ window.addEventListener(NATIVE_MOBILE_BACK_EVENT, handleBack)+ return () => window.removeEventListener(NATIVE_MOBILE_BACK_EVENT, handleBack)+ }, [dismissShellOverlay, parentPath, replacePath])+}