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(community): give mobile Back to one active overlay (#993)
Gener3b3bb16d4ef7
diff --git a/scripts/ci/native-mobile-back.test.ts b/scripts/ci/native-mobile-back.test.tsnew file mode 100644index 000000000..acb42d72e--- /dev/null+++ b/scripts/ci/native-mobile-back.test.ts@@ -0,0 +1,40 @@+import { readFileSync } from "node:fs"+import { resolve } from "node:path"+import { describe, expect, it } from "vitest"++const root = resolve(import.meta.dirname, "../../src/desktop/src-tauri")+const read = (path: string) => JSON.parse(readFileSync(resolve(root, path), "utf8"))+const production = read("tauri.conf.json")+const development = read("tauri.dev.conf.json")+const capability = read("capabilities/native-back-mobile.json")+const listenerPermissions = ["core:app:allow-register-listener", "core:app:allow-remove-listener"]++describe("native Android Back listener capability", () => {+ it("restricts production listener commands to the trusted Android main document", () => {+ expect(production.app.withGlobalTauri).toBe(true)+ expect(production.app.security.capabilities).toContain("native-back-mobile")+ expect(capability).toMatchObject({+ identifier: "native-back-mobile",+ windows: ["main"],+ platforms: ["android"],+ local: false,+ remote: { urls: ["https://alook.ai"] },+ permissions: listenerPermissions,+ })+ })++ it("keeps development origin access separate and preserves the same command boundary", () => {+ const dev = development.app.security.capabilities.find((entry: { identifier?: string } | string) => (+ typeof entry !== "string" && entry.identifier === "native-back-dev"+ ))+ expect(dev).toMatchObject({+ windows: ["main"],+ platforms: ["android"],+ local: true,+ remote: { urls: ["http://localhost:3000"] },+ permissions: listenerPermissions,+ })+ expect(production.app.security.capabilities).not.toContain("native-back-dev")+ expect(development.app.security.capabilities).not.toContain("native-back-mobile")+ })+})diff --git a/scripts/ci/workflow-contract.test.ts b/scripts/ci/workflow-contract.test.tsindex e38951f05..92c9f67bf 100644--- a/scripts/ci/workflow-contract.test.ts+++ b/scripts/ci/workflow-contract.test.ts@@ -1310,6 +1310,14 @@ describe("Desktop image clipboard", () => {remote: { urls: ["http://localhost:3000"] },permissions: ["mobile-system-notification"],}),+ expect.objectContaining({+ identifier: "native-back-dev",+ local: true,+ windows: ["main"],+ platforms: ["android"],+ remote: { urls: ["http://localhost:3000"] },+ permissions: ["core:app:allow-register-listener", "core:app:allow-remove-listener"],+ }),"file-save",expect.objectContaining({identifier: "file-save-dev",diff --git a/src/desktop/src-tauri/capabilities/native-back-mobile.json b/src/desktop/src-tauri/capabilities/native-back-mobile.jsonnew file mode 100644index 000000000..8c474b76f--- /dev/null+++ b/src/desktop/src-tauri/capabilities/native-back-mobile.json@@ -0,0 +1,15 @@+{+ "$schema": "../gen/schemas/mobile-schema.json",+ "identifier": "native-back-mobile",+ "description": "Android Back listener for the trusted main WebView",+ "windows": ["main"],+ "platforms": ["android"],+ "local": false,+ "remote": {+ "urls": ["https://alook.ai"]+ },+ "permissions": [+ "core:app:allow-register-listener",+ "core:app:allow-remove-listener"+ ]+}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 3980e7e5a..1c78027bb 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@@ -6,7 +6,6 @@ import android.os.Bundleimport 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@@ -23,8 +22,6 @@ class MainActivity : TauriActivity() {private var isReady = falseprivate var mainWebView: WebView? = nullprivate var startupAttachListener: View.OnAttachStateChangeListener? = null- private lateinit var nativeBackCallback: OnBackPressedCallback- private lateinit var nativeBackDispatcher: NativeBackDispatcherprivate val mobileShareImageDocumentOwner = MobileShareImageDocumentOwner(this)companion object {@@ -53,20 +50,6 @@ 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)splashScreen.setKeepOnScreenCondition { !isReady }@@ -100,7 +83,6 @@ class MainActivity : TauriActivity() {}override fun onDestroy() {- nativeBackDispatcher.close()clearStartupAttachListener()mainWebView = nullmobileShareImageDocumentOwner.detach()@@ -136,15 +118,6 @@ class MainActivity : TauriActivity() {startupAttachListener = null}- 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.ktdeleted file mode 100644index de2128c50..000000000--- a/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/NativeBackDispatcher.kt+++ /dev/null@@ -1,46 +0,0 @@-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.ktdeleted file mode 100644index d9022628d..000000000--- a/src/desktop/src-tauri/gen/android/app/src/test/java/ai/alook/android/NativeBackDispatcherTest.kt+++ /dev/null@@ -1,72 +0,0 @@-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/tauri.conf.json b/src/desktop/src-tauri/tauri.conf.jsonindex 8e5d5aee4..a6171a447 100644--- a/src/desktop/src-tauri/tauri.conf.json+++ b/src/desktop/src-tauri/tauri.conf.json@@ -51,6 +51,7 @@"native-oauth-mobile","mobile-share-image-mobile","mobile-system-notification-mobile",+ "native-back-mobile","file-save"]}diff --git a/src/desktop/src-tauri/tauri.dev.conf.json b/src/desktop/src-tauri/tauri.dev.conf.jsonindex 24161d70b..d91c34afb 100644--- a/src/desktop/src-tauri/tauri.dev.conf.json+++ b/src/desktop/src-tauri/tauri.dev.conf.json@@ -72,6 +72,21 @@"mobile-system-notification"]},+ {+ "$schema": "../gen/schemas/desktop-schema.json",+ "identifier": "native-back-dev",+ "description": "Android Back listener for the trusted development WebView",+ "windows": ["main"],+ "platforms": ["android"],+ "local": true,+ "remote": {+ "urls": ["http://localhost:3000"]+ },+ "permissions": [+ "core:app:allow-register-listener",+ "core:app:allow-remove-listener"+ ]+ },"file-save",{"identifier": "file-save-dev",diff --git a/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx b/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsxindex c9b4db704..f969e27f2 100644--- a/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx+++ b/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx@@ -10,6 +10,7 @@ import { CommunityMentionList, ChannelRefList } from "./composer-suggestion-popuimport type { ComposerHandle, ComposerProps } from "./composer-types"import { useComposerController } from "./use-composer-controller"import { TextChannelSurface } from "../channels/text-channel-surface"+import { NATIVE_MOBILE_BACK_EVENT, useNativeMobileBack } from "@/hooks/community/use-native-mobile-back"import type { MessageChannelControllerValue } from "./message-channel-controller"const files = vi.hoisted(() => ({@@ -108,6 +109,11 @@ function dispatchDeletion(editor: Editor, key: "Delete" | "Backspace", options:return event}+function BackListener({ replacePath }: { replacePath: (path: string) => void }) {+ useNativeMobileBack({ dismissShellOverlay: () => false, parentPath: "/c/me", replacePath })+ return null+}+describe("composer suggestion focus with installed TipTap", () => {beforeEach(() => {localStorage.clear()@@ -124,6 +130,59 @@ describe("composer suggestion focus with installed TipTap", () => {vi.restoreAllMocks()})+ it.each(["@", "/"])("native Back closes the active %s suggestion without leaving the draft", async (trigger) => {+ const probeRef: Probe = { current: null }+ const replacePath = vi.fn()+ render(<><BackListener replacePath={replacePath} /><Harness {...props} probeRef={probeRef} draftKey="native-back" /></>)+ const editor = await editorOf(probeRef)+ await type(editor, trigger)+ await screen.findByTestId(trigger === "@" ? "community-mention-popup" : "community-channel-ref-popup")+ const draft = editor.getJSON()+ const event = new Event(NATIVE_MOBILE_BACK_EVENT, { cancelable: true })+ act(() => { window.dispatchEvent(event) })+ expect(event.defaultPrevented).toBe(true)+ expect(probeRef.current!.mentionPopup.command).toBeNull()+ expect(probeRef.current!.channelRefPopup.command).toBeNull()+ expect(editor.getJSON()).toEqual(draft)+ expect(readComposerDraft("viewer:native-back")).toEqual(draft)+ expect(replacePath).not.toHaveBeenCalled()+ })++ it("native Back remains with a composing editor", async () => {+ const probeRef: Probe = { current: null }+ const replacePath = vi.fn()+ render(<><BackListener replacePath={replacePath} /><Harness {...props} probeRef={probeRef} /></>)+ const editor = await editorOf(probeRef)+ await type(editor, "test")+ act(() => { fireEvent.compositionStart(editor.view.dom) })+ const draft = editor.getJSON()+ act(() => { window.dispatchEvent(new Event(NATIVE_MOBILE_BACK_EVENT, { cancelable: true })) })+ expect(editor.getJSON()).toEqual(draft)+ expect(replacePath).not.toHaveBeenCalled()+ act(() => { fireEvent.compositionEnd(editor.view.dom) })+ })++ it("retires a destroyed editor owner and gives a rebuilt editor its own Back", async () => {+ const first: Probe = { current: null }, second: Probe = { current: null }+ const replacePath = vi.fn()+ const listener = <BackListener replacePath={replacePath} />+ const view = render(<>{listener}<Harness key="first" {...props} probeRef={first} draftKey="retiring-editor" /></>)+ const oldEditor = await editorOf(first)+ await type(oldEditor, "@a")+ await screen.findByTestId("community-mention-popup")+ view.rerender(<>{listener}<Harness key="second" {...props} probeRef={second} draftKey="rebuilt-editor" /></>)+ await waitFor(() => { expect(oldEditor.isDestroyed).toBe(true) })+ const editor = await editorOf(second)+ await type(editor, "/g")+ await screen.findByTestId("community-channel-ref-popup")+ act(() => { window.dispatchEvent(new Event(NATIVE_MOBILE_BACK_EVENT, { cancelable: true })) })+ expect(second.current!.channelRefPopup.command).toBeNull()+ expect(editor.getText()).toBe("/g")+ expect(replacePath).not.toHaveBeenCalled()+ act(() => { window.dispatchEvent(new Event(NATIVE_MOBILE_BACK_EVENT, { cancelable: true })) })+ expect(replacePath).toHaveBeenCalledExactlyOnceWith("/c/me")+ })+it("keeps the current thread edit and candidate when an embedded parent mounts late, then accepts a parent click", async () => {const probeRef: Probe = { current: null }const thread = <Harness key="thread" {...props} context="thread" draftKey="late-thread" probeRef={probeRef} autoFocus />diff --git a/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.ts b/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.tsindex e3610f7c6..34d2075d6 100644--- a/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.ts+++ b/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.ts@@ -98,7 +98,7 @@ describe("Composer committed send lifecycle", () => {state: { tr: {} },isFocused: true,isDestroyed: false,- view: { dispatch: vi.fn() },+ view: { dispatch: vi.fn(), dom: document.createElement("div"), hasFocus: () => true, composing: false },isEmpty: false,getText: vi.fn(() => "latest draft"),getJSON: vi.fn(() => ({})),diff --git a/src/web/src/components/community/messages/use-composer-suggestions.dom.test.ts b/src/web/src/components/community/messages/use-composer-suggestions.dom.test.tsindex 0ee0f2e0d..b5c74cdb0 100644--- a/src/web/src/components/community/messages/use-composer-suggestions.dom.test.ts+++ b/src/web/src/components/community/messages/use-composer-suggestions.dom.test.ts@@ -43,7 +43,13 @@ import type { Member } from "@/lib/community/models/people"type Options = Omit<Parameters<typeof useComposerSuggestions>[0], "editorRef" | "canSuggest" | "scope">type Result = ReturnType<typeof useComposerSuggestions>-const editor = { isFocused: true, isDestroyed: false } as import("@tiptap/react").Editor+const editor = {+ isFocused: true,+ isDestroyed: false,+ on: vi.fn(),+ off: vi.fn(),+ view: { dom: document.createElement("div"), hasFocus: () => editor.isFocused, composing: false },+} as import("@tiptap/react").Editorconst editorRef = { current: editor }const canSuggest = (candidate: import("@tiptap/react").Editor) => candidate === editor && candidate.isFocuseddiff --git a/src/web/src/components/community/messages/use-composer-suggestions.ts b/src/web/src/components/community/messages/use-composer-suggestions.tsindex e2b9b0306..9683f295b 100644--- a/src/web/src/components/community/messages/use-composer-suggestions.ts+++ b/src/web/src/components/community/messages/use-composer-suggestions.ts@@ -2,6 +2,7 @@ import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"import type { Editor } from "@tiptap/react"import { exitSuggestion } from "@tiptap/suggestion"+import { useNativeBackOwner } from "@/components/ui/native-back-layer"import {buildCommunityMentionExtension,EMPTY_MENTION_STATE,@@ -196,6 +197,69 @@ export function useComposerSuggestions({exitSuggestion(editor.view, mentionExtension.options.suggestion.pluginKey)exitSuggestion(editor.view, channelRefExtension.options.suggestion.pluginKey)}, [editorRef, mentionExtension, channelRefExtension, publishMention, publishChannelRef])++ const composingEditor = useRef<Editor | null>(null)+ const retiredBackEditor = useRef<Editor | null>(null)+ const readBackEditor = useCallback(() => {+ const editor = editorRef.current+ if (!editor || retiredBackEditor.current === editor || editor.isDestroyed || !eligible(editor) || !editor.view.hasFocus()) return null+ return mentionPopupRef.current.command || channelRefPopupRef.current.command+ || composingEditor.current === editor || editor.view.composing ? editor : null+ }, [editorRef, eligible])+ const backElement = useCallback(() => readBackEditor()?.view.dom ?? null, [readBackEditor])+ const requestBack = useCallback(() => {+ const editor = readBackEditor()+ if (!editor) return "none"+ if (composingEditor.current === editor || editor.view.composing) return "blocked"+ resetPopups(editor)+ return "requested"+ }, [readBackEditor, resetPopups])+ const refreshBackOwner = useNativeBackOwner(backElement, requestBack)+ useEffect(() => {+ const editor = editorRef.current+ refreshBackOwner()+ if (!editor || editor.isDestroyed) return+ const retire = () => {+ if (composingEditor.current === editor) composingEditor.current = null+ refreshBackOwner()+ }+ const destroy = () => {+ retiredBackEditor.current = editor+ retire()+ }+ editor.on("destroy", destroy)+ editor.on("blur", retire)+ return () => {+ editor.off("destroy", destroy)+ editor.off("blur", retire)+ }+ })+ useLayoutEffect(() => {+ composingEditor.current = null+ refreshBackOwner()+ }, [scope, refreshBackOwner])+ useEffect(() => {+ const start = (event: CompositionEvent) => {+ const editor = editorRef.current+ if (!editor || editor.isDestroyed || event.target !== editor.view.dom) return+ composingEditor.current = editor+ refreshBackOwner()+ }+ const end = (event: Event) => {+ const editor = composingEditor.current+ if (!editor || editor.isDestroyed || event.target !== editor.view.dom) return+ composingEditor.current = null+ refreshBackOwner()+ }+ document.addEventListener("compositionstart", start)+ document.addEventListener("compositionend", end)+ document.addEventListener("focusout", end)+ return () => {+ document.removeEventListener("compositionstart", start)+ document.removeEventListener("compositionend", end)+ document.removeEventListener("focusout", end)+ }+ }, [editorRef, refreshBackOwner])useLayoutEffect(() => { resetPopups() }, [scope, resetPopups])useLayoutEffect(() => {contextRef.current = contextdiff --git a/src/web/src/components/ui/alert-dialog.tsx b/src/web/src/components/ui/alert-dialog.tsxindex 77ccd3b6a..0bad2b100 100644--- a/src/web/src/components/ui/alert-dialog.tsx+++ b/src/web/src/components/ui/alert-dialog.tsx@@ -5,9 +5,11 @@ import { AlertDialog as AlertDialogPrimitive } from "@base-ui/react/alert-dialogimport { cn } from "@/lib/utils"import { Button } from "@/components/ui/button"+import { NativeBackRoot, useNativeBackPopupRender, useNativeBackRoot } from "./native-back-layer"function AlertDialog({ ...props }: AlertDialogPrimitive.Root.Props) {- return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />+ const back = useNativeBackRoot(props.onOpenChangeComplete)+ return <NativeBackRoot value={back.owner}><AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} onOpenChangeComplete={back.complete} /></NativeBackRoot>}function AlertDialogTrigger({ ...props }: AlertDialogPrimitive.Trigger.Props) {@@ -41,10 +43,12 @@ function AlertDialogOverlay({function AlertDialogContent({className,size = "default",+ render,...props}: AlertDialogPrimitive.Popup.Props & {size?: "default" | "sm"}) {+ const renderPopup = useNativeBackPopupRender<AlertDialogPrimitive.Popup.State>(render)return (<AlertDialogPortal><AlertDialogOverlay />@@ -56,6 +60,7 @@ function AlertDialogContent({className)}{...props}+ render={renderPopup}/></AlertDialogPortal>)diff --git a/src/web/src/components/ui/context-menu.tsx b/src/web/src/components/ui/context-menu.tsxindex f967df000..97a4b8eaa 100644--- a/src/web/src/components/ui/context-menu.tsx+++ b/src/web/src/components/ui/context-menu.tsx@@ -7,6 +7,7 @@ import { ContextMenu as ContextMenuPrimitive } from "@base-ui/react/context-menuimport { cn } from "@/lib/utils"import { ChevronRightIcon, CheckIcon } from "lucide-react"import { useAuthenticatedContextMenuPolicy } from "@/components/authenticated-context-menu-boundary"+import { NativeBackRoot, useNativeBackPopupRender, useNativeBackRoot } from "./native-back-layer"type NativeContextGesture = {token: number@@ -53,6 +54,7 @@ export function nativeContextGestureMatches(}function ContextMenu({ disabled, ...props }: ContextMenuPrimitive.Root.Props) {+ const back = useNativeBackRoot(props.onOpenChangeComplete)const policy = useAuthenticatedContextMenuPolicy()const nextTokenRef = React.useRef(0)const gestureRef = React.useRef<NativeContextGesture | null>(null)@@ -111,13 +113,14 @@ function ContextMenu({ disabled, ...props }: ContextMenuPrimitive.Root.Props) {}), [arm, clear])return (- <NativeContextGestureContext.Provider value={controller}>+ <NativeBackRoot value={back.owner}><NativeContextGestureContext.Provider value={controller}><ContextMenuPrimitive.Rootdata-slot="context-menu"disabled={disabled || gesture !== null}{...props}+ onOpenChangeComplete={back.complete}/>- </NativeContextGestureContext.Provider>+ </NativeContextGestureContext.Provider></NativeBackRoot>)}@@ -184,6 +187,7 @@ function ContextMenuTrigger({function ContextMenuContent({className,+ render,align = "start",alignOffset = 4,side = "right",@@ -194,6 +198,7 @@ function ContextMenuContent({ContextMenuPrimitive.Positioner.Props,"align" | "alignOffset" | "side" | "sideOffset">) {+ const renderPopup = useNativeBackPopupRender<ContextMenuPrimitive.Popup.State>(render)return (<ContextMenuPrimitive.Portal><ContextMenuPrimitive.Positioner@@ -207,6 +212,7 @@ function ContextMenuContent({data-slot="context-menu-content"className={cn("z-50 max-h-(--available-height) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-2 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}{...props}+ render={renderPopup}/></ContextMenuPrimitive.Positioner></ContextMenuPrimitive.Portal>@@ -263,8 +269,9 @@ function ContextMenuItem({}function ContextMenuSub({ ...props }: ContextMenuPrimitive.SubmenuRoot.Props) {+ const back = useNativeBackRoot(props.onOpenChangeComplete)return (- <ContextMenuPrimitive.SubmenuRoot data-slot="context-menu-sub" {...props} />+ <NativeBackRoot value={back.owner}><ContextMenuPrimitive.SubmenuRoot data-slot="context-menu-sub" {...props} onOpenChangeComplete={back.complete} /></NativeBackRoot>)}diff --git a/src/web/src/components/ui/dialog.tsx b/src/web/src/components/ui/dialog.tsxindex f37e4b1f6..1a80e753e 100644--- a/src/web/src/components/ui/dialog.tsx+++ b/src/web/src/components/ui/dialog.tsx@@ -6,6 +6,7 @@ import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"import { cn } from "@/lib/utils"import { Button } from "@/components/ui/button"import { XIcon } from "lucide-react"+import { NativeBackRoot, useNativeBackPopupRender, useNativeBackRoot } from "./native-back-layer"function stopPropagationAfter<Event extends React.SyntheticEvent>(handler: ((event: Event) => void) | undefined,@@ -17,7 +18,8 @@ function stopPropagationAfter<Event extends React.SyntheticEvent>(}function Dialog({ ...props }: DialogPrimitive.Root.Props) {- return <DialogPrimitive.Root data-slot="dialog" {...props} />+ const back = useNativeBackRoot(props.onOpenChangeComplete)+ return <NativeBackRoot value={back.owner}><DialogPrimitive.Root data-slot="dialog" {...props} onOpenChangeComplete={back.complete} /></NativeBackRoot>}function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {@@ -63,11 +65,13 @@ function DialogContent({onTouchEnd,onTouchMove,onTouchStart,+ render,...props}: DialogPrimitive.Popup.Props & {showCloseButton?: booleanoverlayClassName?: string}) {+ const renderPopup = useNativeBackPopupRender<DialogPrimitive.Popup.State>(render)return (<DialogPortal><DialogOverlay className={overlayClassName} forceRender />@@ -78,6 +82,7 @@ function DialogContent({className)}{...props}+ render={renderPopup}onClick={stopPropagationAfter(onClick)}onContextMenu={stopPropagationAfter(onContextMenu)}onPointerCancel={stopPropagationAfter(onPointerCancel)}diff --git a/src/web/src/components/ui/dropdown-menu.tsx b/src/web/src/components/ui/dropdown-menu.tsxindex 6c85f3ac3..65c7dd759 100644--- a/src/web/src/components/ui/dropdown-menu.tsx+++ b/src/web/src/components/ui/dropdown-menu.tsx@@ -5,9 +5,11 @@ import { Menu as MenuPrimitive } from "@base-ui/react/menu"import { cn } from "@/lib/utils"import { ChevronRightIcon, CheckIcon } from "lucide-react"+import { NativeBackRoot, useNativeBackPopupRender, useNativeBackRoot } from "./native-back-layer"function DropdownMenu({ ...props }: MenuPrimitive.Root.Props) {- return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />+ const back = useNativeBackRoot(props.onOpenChangeComplete)+ return <NativeBackRoot value={back.owner}><MenuPrimitive.Root data-slot="dropdown-menu" {...props} onOpenChangeComplete={back.complete} /></NativeBackRoot>}function DropdownMenuPortal({ ...props }: MenuPrimitive.Portal.Props) {@@ -28,6 +30,7 @@ function DropdownMenuContent({collisionPadding,collisionAvoidance,className,+ render,...props}: MenuPrimitive.Popup.Props &Pick<@@ -41,6 +44,7 @@ function DropdownMenuContent({| "collisionPadding"| "collisionAvoidance">) {+ const renderPopup = useNativeBackPopupRender<MenuPrimitive.Popup.State>(render)return (<MenuPrimitive.Portal><MenuPrimitive.Positioner@@ -58,6 +62,7 @@ function DropdownMenuContent({data-slot="dropdown-menu-content"className={cn("z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-2 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95", className )}{...props}+ render={renderPopup}/></MenuPrimitive.Positioner></MenuPrimitive.Portal>@@ -112,7 +117,8 @@ function DropdownMenuItem({}function DropdownMenuSub({ ...props }: MenuPrimitive.SubmenuRoot.Props) {- return <MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} />+ const back = useNativeBackRoot(props.onOpenChangeComplete)+ return <NativeBackRoot value={back.owner}><MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} onOpenChangeComplete={back.complete} /></NativeBackRoot>}function DropdownMenuSubTrigger({diff --git a/src/web/src/components/ui/native-back-layer.tsx b/src/web/src/components/ui/native-back-layer.tsxnew file mode 100644index 000000000..faeca7d08--- /dev/null+++ b/src/web/src/components/ui/native-back-layer.tsx@@ -0,0 +1,160 @@+"use client"++import * as React from "react"+import { useRender } from "@base-ui/react/use-render"++type BackResult = "requested" | "blocked" | "none"+type BackOwner = {+ parent: BackOwner | null+}+type Registration = {+ owner: BackOwner+ element: HTMLElement+ phase: "open" | "closing"+ order: number+ request: () => BackResult+}++const NativeBackContext = React.createContext<BackOwner | null>(null)+const owners = new WeakMap<Document, Set<Registration>>()+const registrations = new WeakMap<BackOwner, Registration>()+let order = 0++function release(owner: BackOwner, element?: HTMLElement) {+ const current = registrations.get(owner)+ if (!current || (element && current.element !== element)) return+ owners.get(current.element.ownerDocument)?.delete(current)+ registrations.delete(owner)+}++function activate(owner: BackOwner, element: HTMLElement, request: () => BackResult) {+ const current = registrations.get(owner)+ if (current?.element === element && current.phase === "open") {+ current.request = request+ return+ }+ release(owner)+ const registration: Registration = { owner, element, phase: "open", order: ++order, request }+ registrations.set(owner, registration)+ let active = owners.get(element.ownerDocument)+ if (!active) {+ active = new Set()+ owners.set(element.ownerDocument, active)+ }+ active.add(registration)+}++function startClosing(owner: BackOwner, element: HTMLElement) {+ const current = registrations.get(owner)+ if (!current) return+ if (current.element.ownerDocument !== element.ownerDocument) {+ owners.get(current.element.ownerDocument)?.delete(current)+ let active = owners.get(element.ownerDocument)+ if (!active) {+ active = new Set()+ owners.set(element.ownerDocument, active)+ }+ active.add(current)+ }+ current.element = element+ current.phase = "closing"+}++function isDescendant(owner: BackOwner, parent: BackOwner) {+ for (let current = owner.parent; current; current = current.parent) {+ if (current === parent) return true+ }+ return false+}++export function requestNativeBack(document: Document): BackResult {+ const active = Array.from(owners.get(document) ?? []).filter((current) => {+ if (current.element.isConnected) return true+ release(current.owner)+ return false+ })+ let top: Registration | null = null+ let topOrder = -1+ for (const current of active) {+ if (active.some((other) => isDescendant(other.owner, current.owner))) continue+ let branchOrder = current.order+ for (let parent = current.owner.parent; parent; parent = parent.parent) {+ branchOrder = Math.max(branchOrder, registrations.get(parent)?.order ?? 0)+ }+ if (branchOrder > topOrder || (branchOrder === topOrder && current.order > (top?.order ?? -1))) {+ top = current+ topOrder = branchOrder+ }+ }+ if (!top) return "none"+ if (top.phase === "closing") return "blocked"+ const result = top.request()+ if (result !== "none") return result+ release(top.owner)+ return requestNativeBack(document)+}++function requestEscape(element: HTMLElement): BackResult {+ const focused = element.ownerDocument.activeElement+ const target = focused && element.contains(focused) ? focused : element+ const event = new KeyboardEvent("keydown", { key: "Escape", code: "Escape", bubbles: true, cancelable: true })+ target.dispatchEvent(event)+ return event.defaultPrevented ? "requested" : "blocked"+}++export function useNativeBackRoot(onOpenChangeComplete?: (open: boolean) => void) {+ const parent = React.useContext(NativeBackContext)+ const owner = React.useMemo<BackOwner>(() => ({ parent }), [parent])+ React.useLayoutEffect(() => () => { release(owner) }, [owner])+ const complete = React.useCallback((open: boolean) => {+ if (!open && registrations.get(owner)?.phase === "closing") release(owner)+ onOpenChangeComplete?.(open)+ }, [owner, onOpenChangeComplete])+ return { owner, complete }+}++export const NativeBackRoot = NativeBackContext.Provider++function NativeBackPopup<State extends { open: boolean }>({ elementProps, state, render }: {+ elementProps: React.ComponentPropsWithRef<"div">+ state: State+ render: useRender.RenderProp<State> | undefined+}) {+ const owner = React.useContext(NativeBackContext)+ const ref = React.useRef<HTMLDivElement>(null)+ React.useLayoutEffect(() => {+ const element = ref.current+ if (!owner || !element) return+ if (state.open) activate(owner, element, () => requestEscape(element))+ else startClosing(owner, element)+ })+ React.useLayoutEffect(() => {+ return () => { if (owner) release(owner) }+ }, [owner])+ return useRender({+ render,+ state,+ props: { ...elementProps },+ ref: [ref, elementProps.ref ?? null],+ })+}++export function useNativeBackPopupRender<State extends { open: boolean }>(render?: useRender.RenderProp<State>) {+ return React.useCallback((elementProps: React.ComponentPropsWithRef<"div">, state: State) => (+ <NativeBackPopup elementProps={elementProps} state={state} render={render} />+ ), [render])+}++export function useNativeBackOwner(getElement: () => HTMLElement | null, request: () => BackResult) {+ const { owner } = useNativeBackRoot()+ const refresh = React.useCallback(() => {+ const element = getElement()+ if (!element) {+ release(owner)+ return+ }+ activate(owner, element, request)+ }, [getElement, owner, request])+ React.useLayoutEffect(() => { refresh() })+ return refresh+}diff --git a/src/web/src/components/ui/popover.tsx b/src/web/src/components/ui/popover.tsxindex 66546fd14..dd70f7ab0 100644--- a/src/web/src/components/ui/popover.tsx+++ b/src/web/src/components/ui/popover.tsx@@ -4,9 +4,11 @@ import * as React from "react"import { Popover as PopoverPrimitive } from "@base-ui/react/popover"import { cn } from "@/lib/utils"+import { NativeBackRoot, useNativeBackPopupRender, useNativeBackRoot } from "./native-back-layer"function Popover({ ...props }: PopoverPrimitive.Root.Props) {- return <PopoverPrimitive.Root data-slot="popover" {...props} />+ const back = useNativeBackRoot(props.onOpenChangeComplete)+ return <NativeBackRoot value={back.owner}><PopoverPrimitive.Root data-slot="popover" {...props} onOpenChangeComplete={back.complete} /></NativeBackRoot>}function PopoverTrigger({ ...props }: PopoverPrimitive.Trigger.Props) {@@ -56,8 +58,10 @@ function PopoverPositioner({function PopoverPopup({className,+ render,...props}: PopoverPrimitive.Popup.Props) {+ const renderPopup = useNativeBackPopupRender<PopoverPrimitive.Popup.State>(render)return (<PopoverPrimitive.Popupdata-slot="popover-content"@@ -68,6 +72,7 @@ function PopoverPopup({className,)}{...props}+ render={renderPopup}/>)}@@ -95,12 +100,14 @@ function PopoverContent({side,sideOffset = 6,align = "start",+ render,...props}: PopoverPrimitive.Popup.Props & {side?: "top" | "bottom" | "left" | "right" | "inline-end" | "inline-start"sideOffset?: numberalign?: "start" | "center" | "end"}) {+ const renderPopup = useNativeBackPopupRender<PopoverPrimitive.Popup.State>(render)// Always portal to document.body so popovers escape parent portals// (e.g. Sheet/Dialog). Without this, base-ui's FloatingPortal falls back to// the nearest parentPortalNode, which inherits the Sheet's width constraint@@ -124,6 +131,7 @@ function PopoverContent({className)}{...props}+ render={renderPopup}>{children}</PopoverPrimitive.Popup>diff --git a/src/web/src/components/ui/select.tsx b/src/web/src/components/ui/select.tsxindex e599e8240..d3d265bb2 100644--- a/src/web/src/components/ui/select.tsx+++ b/src/web/src/components/ui/select.tsx@@ -5,8 +5,12 @@ import { Select as SelectPrimitive } from "@base-ui/react/select"import { cn } from "@/lib/utils"import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from "lucide-react"+import { NativeBackRoot, useNativeBackPopupRender, useNativeBackRoot } from "./native-back-layer"-const Select = SelectPrimitive.Root+function Select<Value, Multiple extends boolean | undefined = false>({ ...props }: SelectPrimitive.Root.Props<Value, Multiple>) {+ const back = useNativeBackRoot(props.onOpenChangeComplete)+ return <NativeBackRoot value={back.owner}><SelectPrimitive.Root {...props} onOpenChangeComplete={back.complete} /></NativeBackRoot>+}function SelectGroup({ className, ...props }: SelectPrimitive.Group.Props) {return (@@ -64,12 +68,14 @@ function SelectContent({align = "center",alignOffset = 0,alignItemWithTrigger = true,+ render,...props}: SelectPrimitive.Popup.Props &Pick<SelectPrimitive.Positioner.Props,"align" | "alignOffset" | "side" | "sideOffset" | "alignItemWithTrigger">) {+ const renderPopup = useNativeBackPopupRender<SelectPrimitive.Popup.State>(render)return (<SelectPrimitive.Portal><SelectPrimitive.Positioner@@ -85,6 +91,7 @@ function SelectContent({data-align-trigger={alignItemWithTrigger}className={cn("thin-scrollbar relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}{...props}+ render={renderPopup}><SelectScrollUpButton /><SelectPrimitive.List>{children}</SelectPrimitive.List>diff --git a/src/web/src/components/ui/sheet.tsx b/src/web/src/components/ui/sheet.tsxindex cbe888607..c0388481e 100644--- a/src/web/src/components/ui/sheet.tsx+++ b/src/web/src/components/ui/sheet.tsx@@ -6,9 +6,11 @@ import { Dialog as SheetPrimitive } from "@base-ui/react/dialog"import { cn } from "@/lib/utils"import { Button } from "@/components/ui/button"import { XIcon } from "lucide-react"+import { NativeBackRoot, useNativeBackPopupRender, useNativeBackRoot } from "./native-back-layer"function Sheet({ ...props }: SheetPrimitive.Root.Props) {- return <SheetPrimitive.Root data-slot="sheet" {...props} />+ const back = useNativeBackRoot(props.onOpenChangeComplete)+ return <NativeBackRoot value={back.owner}><SheetPrimitive.Root data-slot="sheet" {...props} onOpenChangeComplete={back.complete} /></NativeBackRoot>}function SheetTrigger({ ...props }: SheetPrimitive.Trigger.Props) {@@ -42,12 +44,14 @@ function SheetContent({side = "right",showCloseButton = true,showOverlay = true,+ render,...props}: SheetPrimitive.Popup.Props & {side?: "top" | "right" | "bottom" | "left"showCloseButton?: booleanshowOverlay?: boolean}) {+ const renderPopup = useNativeBackPopupRender<SheetPrimitive.Popup.State>(render)return (<SheetPortal>{showOverlay && <SheetOverlay forceRender />}@@ -63,6 +67,7 @@ function SheetContent({className)}{...props}+ render={renderPopup}>{children}{showCloseButton && (diff --git a/src/web/src/hooks/community/use-native-mobile-back-layers.dom.test.tsx b/src/web/src/hooks/community/use-native-mobile-back-layers.dom.test.tsxnew file mode 100644index 000000000..182a50255--- /dev/null+++ b/src/web/src/hooks/community/use-native-mobile-back-layers.dom.test.tsx@@ -0,0 +1,356 @@+import { createRef, useState } from "react"+import { describe, expect, it, vi } from "vitest"+import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"+import { act, fireEvent, render, screen, setupUser, waitFor } from "@/test/react-dom-harness"+import { Dialog, DialogContent, DialogDescription, DialogTitle, DialogTrigger } from "@/components/ui/dialog"+import { Popover, PopoverContent, PopoverPopup, PopoverPortal, PopoverPositioner, PopoverTitle, PopoverTrigger } from "@/components/ui/popover"+import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogTitle } from "@/components/ui/alert-dialog"+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"+import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from "@/components/ui/context-menu"+import { NATIVE_MOBILE_BACK_EVENT, useNativeMobileBack } from "./use-native-mobile-back"++function BackListener({ replacePath }: { replacePath: (path: string) => void }) {+ useNativeMobileBack({ dismissShellOverlay: () => false, parentPath: "/c/me", replacePath })+ return null+}++function back() {+ const event = new Event(NATIVE_MOBILE_BACK_EVENT, { cancelable: true })+ act(() => { window.dispatchEvent(event) })+ expect(event.defaultPrevented).toBe(true)+}++function escapeAtFocus() {+ act(() => {+ document.activeElement?.dispatchEvent(new KeyboardEvent("keydown", {+ key: "Escape", code: "Escape", bubbles: true, cancelable: true,+ }))+ })+}++function Modal({ name, onClose, children }: {+ name: string+ onClose: () => void+ children?: React.ReactNode+}) {+ const [open, setOpen] = useState(true)+ return (+ <Dialog open={open} onOpenChange={(value) => { setOpen(value); if (!value) onClose() }}>+ <DialogContent>+ <DialogTitle>{name}</DialogTitle>+ <DialogDescription>Test content</DialogDescription>+ {children}+ </DialogContent>+ </Dialog>+ )+}++describe("native Back with real Base UI layers", () => {+ it("closes one modal without page navigation", async () => {+ const close = vi.fn()+ const replacePath = vi.fn()+ render(<><BackListener replacePath={replacePath} /><Modal name="Single" onClose={close} /></>)+ await screen.findByRole("dialog", { name: "Single" })+ back()+ await waitFor(() => { expect(close).toHaveBeenCalledOnce() })+ expect(replacePath).not.toHaveBeenCalled()+ })++ it("uses native nesting to close only the child modal", async () => {+ const parentClose = vi.fn()+ const childClose = vi.fn()+ const replacePath = vi.fn()+ render(<><BackListener replacePath={replacePath} /><Modal name="Parent" onClose={parentClose}><Modal name="Child" onClose={childClose} /></Modal></>)+ await screen.findByRole("dialog", { name: "Child" })+ back()+ await waitFor(() => { expect(childClose).toHaveBeenCalledOnce() })+ expect(parentClose).not.toHaveBeenCalled()+ expect(replacePath).not.toHaveBeenCalled()+ })++ it.each(["native Back", "focused Escape"])("%s closes only the newly opened independent sibling modal", async (input) => {+ const parentClose = vi.fn()+ const childClose = vi.fn()+ const replacePath = vi.fn()+ function Siblings() {+ const [childOpen, setChildOpen] = useState(false)+ return <><Modal name="First" onClose={parentClose}><button onClick={() => setChildOpen(true)}>Open second</button></Modal>{childOpen && <Modal name="Second" onClose={childClose} />}</>+ }+ const user = setupUser()+ render(<><BackListener replacePath={replacePath} /><Siblings /></>)+ await user.click(await screen.findByRole("button", { name: "Open second" }))+ const second = await screen.findByRole("dialog", { name: "Second" })+ await waitFor(() => { expect(second.contains(document.activeElement)).toBe(true) })+ if (input === "native Back") back()+ else escapeAtFocus()+ await waitFor(() => { expect(childClose).toHaveBeenCalledOnce() })+ expect(parentClose).not.toHaveBeenCalled()+ expect(replacePath).not.toHaveBeenCalled()+ })++ it.each(["native Back", "focused Escape"])("%s closes a standalone popover before page navigation", async (input) => {+ const close = vi.fn()+ const replacePath = vi.fn()+ function StandalonePopover() {+ const [open, setOpen] = useState(false)+ return <Popover open={open} onOpenChange={(value) => { setOpen(value); if (!value) close() }}><PopoverTrigger>Open popover</PopoverTrigger><PopoverContent><PopoverTitle>Popover content</PopoverTitle></PopoverContent></Popover>+ }+ const user = setupUser()+ render(<><BackListener replacePath={replacePath} /><StandalonePopover /></>)+ await user.click(screen.getByRole("button", { name: "Open popover" }))+ const popup = await screen.findByRole("dialog", { name: "Popover content" })+ await waitFor(() => { expect(popup.contains(document.activeElement)).toBe(true) })+ if (input === "native Back") back()+ else escapeAtFocus()+ expect(close).toHaveBeenCalledOnce()+ expect(replacePath).not.toHaveBeenCalled()+ })++ it.each(["menu", "select"])("closes standalone %s before page navigation", async (kind) => {+ const close = vi.fn()+ const replacePath = vi.fn()+ const user = setupUser()+ function Popup() {+ const [open, setOpen] = useState(false)+ const onOpenChange = (value: boolean) => { setOpen(value); if (!value) close() }+ return kind === "menu"+ ? <DropdownMenu open={open} onOpenChange={onOpenChange}><DropdownMenuTrigger>Open choices</DropdownMenuTrigger><DropdownMenuContent><DropdownMenuItem>Choice</DropdownMenuItem></DropdownMenuContent></DropdownMenu>+ : <Select open={open} onOpenChange={onOpenChange}><SelectTrigger aria-label="Open choices"><SelectValue placeholder="Choose" /></SelectTrigger><SelectContent><SelectItem value="one">Choice</SelectItem></SelectContent></Select>+ }+ render(<><BackListener replacePath={replacePath} /><Popup /></>)+ await user.click(screen.getByRole(kind === "menu" ? "button" : "combobox", { name: "Open choices" }))+ await screen.findByRole(kind === "menu" ? "menuitem" : "option", { name: "Choice" })+ back()+ expect(close).toHaveBeenCalledOnce()+ expect(replacePath).not.toHaveBeenCalled()+ })++ it("keeps a controlled locked owner without navigating beneath it", async () => {+ const replacePath = vi.fn()+ const attemptedClose = vi.fn()+ render(<><BackListener replacePath={replacePath} /><Dialog open onOpenChange={attemptedClose}><DialogContent showCloseButton={false}><DialogTitle>Locked</DialogTitle><DialogDescription>Test content</DialogDescription></DialogContent></Dialog></>)+ await screen.findByRole("dialog", { name: "Locked" })+ back()+ expect(attemptedClose).toHaveBeenCalledOnce()+ expect(screen.getByRole("dialog", { name: "Locked" })).toBeVisible()+ expect(replacePath).not.toHaveBeenCalled()+ })++ it("keeps ownership through an externally held closing phase", async () => {+ const replacePath = vi.fn()+ const parentClose = vi.fn()+ const close = vi.fn()+ const actions = createRef<{ close: () => void; unmount: () => void }>()+ function ClosingChild() {+ const [open, setOpen] = useState(true)+ return <Dialog open={open} actionsRef={actions} onOpenChange={(value, details) => { if (!value) { details.preventUnmountOnClose(); close() }; setOpen(value) }}><DialogContent><DialogTitle>Closing child</DialogTitle><DialogDescription>Test content</DialogDescription></DialogContent></Dialog>+ }+ render(<><BackListener replacePath={replacePath} /><Modal name="Parent" onClose={parentClose}><ClosingChild /></Modal></>)+ const child = await screen.findByRole("dialog", { name: "Closing child" })+ await waitFor(() => { expect(child.contains(document.activeElement)).toBe(true) })+ back()+ expect(close).toHaveBeenCalledOnce()+ back()+ expect(parentClose).not.toHaveBeenCalled()+ expect(replacePath).not.toHaveBeenCalled()+ act(() => { actions.current?.unmount() })+ back()+ expect(parentClose).toHaveBeenCalledOnce()+ })++ it("selects the nested child when its independent branch mounts after another modal", async () => {+ const replacePath = vi.fn()+ const otherClose = vi.fn(), parentClose = vi.fn(), childClose = vi.fn()+ render(<><BackListener replacePath={replacePath} /><Modal name="Other" onClose={otherClose} /><Modal name="Branch" onClose={parentClose}><Modal name="Branch child" onClose={childClose} /></Modal></>)+ await screen.findByText("Branch child")+ back()+ expect(childClose).toHaveBeenCalledOnce()+ expect(parentClose).not.toHaveBeenCalled()+ expect(otherClose).not.toHaveBeenCalled()+ expect(replacePath).not.toHaveBeenCalled()+ })++ it("releases a closed keepMounted popup and registers each reopen", async () => {+ const replacePath = vi.fn()+ const completed = vi.fn()+ const user = setupUser()+ render(<><BackListener replacePath={replacePath} /><Popover onOpenChangeComplete={completed}><PopoverTrigger>Open kept popup</PopoverTrigger><PopoverPortal keepMounted><PopoverPositioner><PopoverPopup><PopoverTitle>Kept popup</PopoverTitle></PopoverPopup></PopoverPositioner></PopoverPortal></Popover></>)+ for (let index = 0; index < 2; index++) {+ await user.click(screen.getByRole("button", { name: "Open kept popup" }))+ await screen.findByRole("dialog", { name: "Kept popup" })+ back()+ await waitFor(() => { expect(completed.mock.calls.filter(([open]) => !open)).toHaveLength(index + 1) })+ expect(document.querySelector('[data-slot="popover-content"]')).toBeTruthy()+ expect(screen.queryByRole("dialog", { name: "Kept popup" })).toBeNull()+ back()+ expect(replacePath).toHaveBeenCalledTimes(index + 1)+ }+ })++ it("retains detached handle triggers and the original render function", async () => {+ const handle = DialogPrimitive.createHandle()+ const replacePath = vi.fn(), close = vi.fn()+ const user = setupUser()+ const ref = createRef<HTMLDivElement>()+ render(<><BackListener replacePath={replacePath} /><DialogTrigger handle={handle}>Open detached</DialogTrigger><Dialog handle={handle} onOpenChange={(open) => { if (!open) close() }}><DialogContent ref={ref} render={(props, state) => <section {...props} data-render-open={state.open} />}><DialogTitle>Detached</DialogTitle><DialogDescription>Test content</DialogDescription></DialogContent></Dialog></>)+ for (let index = 0; index < 2; index++) {+ await user.click(screen.getByRole("button", { name: "Open detached" }))+ const popup = await screen.findByRole("dialog", { name: "Detached" })+ expect(popup.tagName).toBe("SECTION")+ expect(popup).toHaveAttribute("data-render-open", "true")+ expect(ref.current).toBe(popup)+ back()+ expect(close).toHaveBeenCalledTimes(index + 1)+ await waitFor(() => { expect(screen.queryByRole("dialog", { name: "Detached" })).toBeNull() })+ }+ expect(replacePath).not.toHaveBeenCalled()+ })++ it("gives a cancel-owned unsaved confirmation its own next Back", async () => {+ const replacePath = vi.fn(), attempts = vi.fn(), confirmClose = vi.fn()+ function Unsaved() {+ const [confirm, setConfirm] = useState(false)+ return <><Dialog open onOpenChange={(open, details) => { if (!open) { attempts(); details.cancel(); setConfirm(true) } }}><DialogContent><DialogTitle>Unsaved form</DialogTitle><DialogDescription>Test content</DialogDescription></DialogContent></Dialog><AlertDialog open={confirm} onOpenChange={(open) => { setConfirm(open); if (!open) confirmClose() }}><AlertDialogContent><AlertDialogTitle>Discard changes?</AlertDialogTitle><AlertDialogDescription>Test content</AlertDialogDescription><AlertDialogCancel>Keep editing</AlertDialogCancel></AlertDialogContent></AlertDialog></>+ }+ render(<><BackListener replacePath={replacePath} /><Unsaved /></>)+ await screen.findByRole("dialog", { name: "Unsaved form" })+ back()+ const confirmation = await screen.findByRole("alertdialog", { name: "Discard changes?" })+ await waitFor(() => { expect(confirmation.contains(document.activeElement)).toBe(true) })+ expect(attempts).toHaveBeenCalledOnce()+ back()+ expect(confirmClose).toHaveBeenCalledOnce()+ expect(attempts).toHaveBeenCalledOnce()+ expect(replacePath).not.toHaveBeenCalled()+ })++ it("keeps a composing modal input, then uses the same native close callback", async () => {+ const replacePath = vi.fn(), close = vi.fn()+ render(<><BackListener replacePath={replacePath} /><Modal name="Composing" onClose={close}><input aria-label="Test input" /></Modal></>)+ const input = await screen.findByRole("textbox", { name: "Test input" })+ act(() => { input.focus(); fireEvent.compositionStart(input) })+ back()+ expect(close).not.toHaveBeenCalled()+ expect(replacePath).not.toHaveBeenCalled()+ await act(async () => {+ fireEvent.compositionEnd(input)+ await new Promise((resolve) => setTimeout(resolve, 0))+ })+ back()+ expect(close).toHaveBeenCalledOnce()+ expect(replacePath).not.toHaveBeenCalled()+ })++ it.each(["popover", "menu", "select", "context menu"])("gives a nested %s one Back before its modal", async (kind) => {+ const replacePath = vi.fn(), parentClose = vi.fn(), close = vi.fn()+ function Popup() {+ const [open, setOpen] = useState(false)+ const change = (value: boolean) => { setOpen(value); if (!value) close() }+ if (kind === "popover") return <Popover open={open} onOpenChange={change}><PopoverTrigger>Open nested</PopoverTrigger><PopoverContent><PopoverTitle>Nested choices</PopoverTitle></PopoverContent></Popover>+ if (kind === "menu") return <DropdownMenu open={open} onOpenChange={change}><DropdownMenuTrigger>Open nested</DropdownMenuTrigger><DropdownMenuContent><DropdownMenuItem>Nested choice</DropdownMenuItem></DropdownMenuContent></DropdownMenu>+ if (kind === "select") return <Select open={open} onOpenChange={change}><SelectTrigger aria-label="Open nested"><SelectValue placeholder="Choose" /></SelectTrigger><SelectContent><SelectItem value="one">Nested choice</SelectItem></SelectContent></Select>+ return <ContextMenu open={open} onOpenChange={change}><ContextMenuTrigger>Open nested</ContextMenuTrigger><ContextMenuContent><ContextMenuItem>Nested choice</ContextMenuItem></ContextMenuContent></ContextMenu>+ }+ render(<><BackListener replacePath={replacePath} /><Modal name="Modal behind popup" onClose={parentClose}><Popup /></Modal></>)+ const trigger = kind === "select"+ ? await screen.findByRole("combobox", { name: "Open nested" })+ : await screen.findByText("Open nested")+ if (kind === "context menu") fireEvent.contextMenu(trigger, { button: 2, clientX: 20, clientY: 30 })+ else await setupUser().click(trigger)+ await screen.findByRole(kind === "popover" ? "dialog" : kind === "select" ? "option" : "menuitem", {+ name: kind === "popover" ? "Nested choices" : "Nested choice",+ })+ back()+ expect(close).toHaveBeenCalledOnce()+ expect(parentClose).not.toHaveBeenCalled()+ expect(replacePath).not.toHaveBeenCalled()+ })++ it("uses the open popup owner when focus stays outside it", async () => {+ const replacePath = vi.fn(), close = vi.fn()+ function Popup() {+ const [open, setOpen] = useState(false)+ return <Popover open={open} onOpenChange={(value, details) => {+ if (details.reason === "focus-out") { details.cancel(); return }+ setOpen(value)+ if (!value) close()+ }}><PopoverTrigger>Open without focus</PopoverTrigger><PopoverContent initialFocus={false}><PopoverTitle>Unfocused popup</PopoverTitle></PopoverContent></Popover>+ }+ render(<><BackListener replacePath={replacePath} /><input aria-label="Outside" /><Popup /></>)+ await setupUser().click(screen.getByRole("button", { name: "Open without focus" }))+ await screen.findByRole("dialog", { name: "Unfocused popup" })+ act(() => { screen.getByRole("textbox", { name: "Outside" }).focus() })+ expect(document.activeElement).toBe(screen.getByRole("textbox", { name: "Outside" }))+ back()+ expect(close).toHaveBeenCalledOnce()+ expect(replacePath).not.toHaveBeenCalled()+ })++ it("releases an unmounted root before registering a fresh instance", async () => {+ const replacePath = vi.fn(), close = vi.fn()+ const listener = <BackListener replacePath={replacePath} />+ const view = render(<>{listener}<Modal name="Retiring" onClose={close} /></>)+ await screen.findByRole("dialog", { name: "Retiring" })+ view.rerender(listener)+ back()+ expect(replacePath).toHaveBeenCalledOnce()+ view.rerender(<>{listener}<Modal name="Fresh" onClose={close} /></>)+ await screen.findByRole("dialog", { name: "Fresh" })+ back()+ expect(close).toHaveBeenCalledOnce()+ expect(replacePath).toHaveBeenCalledOnce()+ })++ it("closes a native submenu before the root menu", async () => {+ const replacePath = vi.fn(), parentClose = vi.fn(), childClose = vi.fn()+ render(<><BackListener replacePath={replacePath} /><DropdownMenu defaultOpen onOpenChange={(open) => { if (!open) parentClose() }}><DropdownMenuTrigger>Parent menu</DropdownMenuTrigger><DropdownMenuContent><DropdownMenuSub defaultOpen onOpenChange={(open) => { if (!open) childClose() }}><DropdownMenuSubTrigger>Submenu</DropdownMenuSubTrigger><DropdownMenuSubContent><DropdownMenuItem>Child item</DropdownMenuItem></DropdownMenuSubContent></DropdownMenuSub></DropdownMenuContent></DropdownMenu></>)+ await screen.findByRole("menuitem", { name: "Child item" })+ back()+ expect(childClose).toHaveBeenCalledOnce()+ expect(parentClose).not.toHaveBeenCalled()+ expect(replacePath).not.toHaveBeenCalled()+ })++ it("keeps ownership when a custom render replaces its DOM element", async () => {+ const replacePath = vi.fn(), close = vi.fn()+ function CustomPopup() {+ const [section, setSection] = useState(false)+ return <Dialog defaultOpen onOpenChange={(open) => { if (!open) close() }}><DialogContent render={section ? <section /> : <article />}><DialogTitle>Custom node</DialogTitle><DialogDescription>Test content</DialogDescription><button onClick={() => setSection(true)}>Replace node</button></DialogContent></Dialog>+ }+ render(<><BackListener replacePath={replacePath} /><CustomPopup /></>)+ const first = await screen.findByRole("dialog", { name: "Custom node" })+ expect(first.tagName).toBe("ARTICLE")+ await setupUser().click(screen.getByRole("button", { name: "Replace node" }))+ const second = await screen.findByRole("dialog", { name: "Custom node" })+ expect(second.tagName).toBe("SECTION")+ expect(first.isConnected).toBe(false)+ back()+ expect(close).toHaveBeenCalledOnce()+ expect(replacePath).not.toHaveBeenCalled()+ })++ it("holds the same closing owner when custom render replaces the DOM on close", async () => {+ const replacePath = vi.fn(), parentClose = vi.fn(), childClose = vi.fn()+ const actions = createRef<{ close: () => void; unmount: () => void }>()+ function ClosingPopup() {+ const [open, setOpen] = useState(true)+ return <Dialog open={open} actionsRef={actions} onOpenChange={(value, details) => {+ if (!value) { details.preventUnmountOnClose(); childClose() }+ setOpen(value)+ }}><DialogContent render={(props, state) => state.open ? <article {...props} /> : <section {...props} data-closing-replacement="true" />}><DialogTitle>Changing closing node</DialogTitle><DialogDescription>Test content</DialogDescription></DialogContent></Dialog>+ }+ render(<><BackListener replacePath={replacePath} /><Modal name="Parent with closing child" onClose={parentClose}><ClosingPopup /></Modal></>)+ const first = await screen.findByRole("dialog", { name: "Changing closing node" })+ back()+ expect(childClose).toHaveBeenCalledOnce()+ expect(first.isConnected).toBe(false)+ expect(document.querySelector('[data-closing-replacement="true"]')).toBeTruthy()+ back()+ expect(parentClose).not.toHaveBeenCalled()+ expect(replacePath).not.toHaveBeenCalled()+ act(() => { actions.current?.unmount() })+ back()+ expect(parentClose).toHaveBeenCalledOnce()+ })+})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.tsindex 713a7b980..d9ad044fc 100644--- 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.ts@@ -1,6 +1,7 @@-import { createElement } from "react"+import { createElement, StrictMode } from "react"import { afterEach, describe, expect, it, vi } from "vitest"-import { render } from "@/test/react-dom-harness"+import { act, render, screen, waitFor } from "@/test/react-dom-harness"+import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog"import {NATIVE_MOBILE_BACK_EVENT,useNativeMobileBack,@@ -17,13 +18,207 @@ function dispatchBack() {return event}+describe("Tauri public Android Back entry", () => {+ afterEach(() => {+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+ })++ function installBridge(pending: Array<Promise<{ unregister: () => Promise<void> }>> = []) {+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue("Android WebView")+ const callbacks: Array<(payload: { canGoBack: boolean }) => void> = []+ const unregister = vi.fn(async () => {})+ const register = vi.fn((callback: (payload: { canGoBack: boolean }) => void) => {+ callbacks.push(callback)+ return pending.shift() ?? Promise.resolve({ unregister })+ })+ vi.stubGlobal("__TAURI__", { app: { onBackButtonPress: register } })+ return { callbacks, unregister, register }+ }++ it("registers once and uses the current structural parent and consumed root policy", async () => {+ const { callbacks, unregister, register } = installBridge()+ expect("__TAURI__" in window).toBe(true)+ const replacePath = vi.fn()+ const props = { dismissShellOverlay: () => false, parentPath: "/c/channels/s1", replacePath }+ const renderer = render(createElement(Harness, props))+ await waitFor(() => { expect(register).toHaveBeenCalledOnce() })+ act(() => { callbacks[0]({ canGoBack: true }) })+ expect(replacePath).toHaveBeenCalledExactlyOnceWith("/c/channels/s1")++ renderer.rerender(createElement(Harness, { ...props, parentPath: "/c/me" }))+ act(() => { callbacks[0]({ canGoBack: false }) })+ expect(replacePath).toHaveBeenLastCalledWith("/c/me")+ renderer.rerender(createElement(Harness, { ...props, parentPath: null }))+ act(() => { callbacks[0]({ canGoBack: true }) })+ expect(replacePath).toHaveBeenCalledTimes(2)+ expect(register).toHaveBeenCalledOnce()++ renderer.unmount()+ await waitFor(() => { expect(unregister).toHaveBeenCalledOnce() })+ act(() => { callbacks[0]({ canGoBack: true }) })+ expect(replacePath).toHaveBeenCalledTimes(2)+ })++ it("gives the public callback to a real top Dialog before the page", async () => {+ const { callbacks } = installBridge()+ const replacePath = vi.fn()+ const close = vi.fn()+ const renderer = render(createElement("div", null,+ createElement(Harness, { dismissShellOverlay: () => false, parentPath: "/c/me", replacePath }),+ createElement(Dialog, { defaultOpen: true, onOpenChange: (open) => { if (!open) close() } },+ createElement(DialogContent, null,+ createElement(DialogTitle, null, "Public native owner"),+ createElement(DialogDescription, null, "Test content"),+ ),+ ),+ ))+ await screen.findByRole("dialog", { name: "Public native owner" })+ act(() => { callbacks[0]({ canGoBack: true }) })+ await waitFor(() => { expect(screen.queryByRole("dialog")).toBeNull() })+ expect(close).toHaveBeenCalledOnce()+ expect(replacePath).not.toHaveBeenCalled()+ renderer.unmount()+ })++ it("releases a late registration and fences its callback from the next scope", async () => {+ const pending = Promise.withResolvers<{ unregister: () => Promise<void> }>()+ const { callbacks, register, unregister } = installBridge([pending.promise])+ const oldReplace = vi.fn()+ const first = render(createElement(Harness, { dismissShellOverlay: () => false, parentPath: "/c/me", replacePath: oldReplace }))+ first.unmount()+ const nextReplace = vi.fn()+ const next = render(createElement(Harness, { dismissShellOverlay: () => false, parentPath: "/c/channels/new", replacePath: nextReplace }))+ expect(register).toHaveBeenCalledTimes(2)+ act(() => { callbacks[0]({ canGoBack: true }) })+ expect(oldReplace).not.toHaveBeenCalled()+ expect(nextReplace).not.toHaveBeenCalled()+ const lateUnregister = vi.fn(async () => {})+ await act(async () => { pending.resolve({ unregister: lateUnregister }); await pending.promise })+ expect(lateUnregister).toHaveBeenCalledOnce()+ act(() => { callbacks[1]({ canGoBack: true }) })+ expect(nextReplace).toHaveBeenCalledExactlyOnceWith("/c/channels/new")+ next.unmount()+ expect(unregister).toHaveBeenCalledOnce()+ })++ it("fences the retired StrictMode setup and unregisters each resolved handle once", async () => {+ const first = Promise.withResolvers<{ unregister: () => Promise<void> }>()+ const second = Promise.withResolvers<{ unregister: () => Promise<void> }>()+ const { callbacks, register } = installBridge([first.promise, second.promise])+ const replacePath = vi.fn()+ const renderer = render(createElement(StrictMode, null,+ createElement(Harness, { dismissShellOverlay: () => false, parentPath: "/c/me", replacePath }),+ ))+ expect(register).toHaveBeenCalledTimes(2)+ act(() => { callbacks[0]({ canGoBack: true }); callbacks[1]({ canGoBack: true }) })+ expect(replacePath).toHaveBeenCalledExactlyOnceWith("/c/me")+ const firstUnregister = vi.fn(async () => {})+ const secondUnregister = vi.fn(async () => {})+ await act(async () => {+ first.resolve({ unregister: firstUnregister })+ second.resolve({ unregister: secondUnregister })+ await Promise.all([first.promise, second.promise])+ })+ expect(firstUnregister).toHaveBeenCalledOnce()+ expect(secondUnregister).not.toHaveBeenCalled()+ renderer.unmount()+ expect(secondUnregister).toHaveBeenCalledOnce()+ act(() => { callbacks[0]({ canGoBack: true }); callbacks[1]({ canGoBack: true }) })+ expect(replacePath).toHaveBeenCalledOnce()+ })++ it.each([false, true])("retires on pagehide persisted=%s without relying on React unmount", async (persisted) => {+ const { callbacks, register, unregister } = installBridge()+ const replacePath = vi.fn()+ const renderer = render(createElement(Harness, { dismissShellOverlay: () => false, parentPath: "/c/me", replacePath }))+ await act(async () => {})+ act(() => { window.dispatchEvent(new PageTransitionEvent("pagehide", { persisted })) })+ expect(unregister).toHaveBeenCalledOnce()+ act(() => { callbacks[0]({ canGoBack: true }) })+ expect(replacePath).not.toHaveBeenCalled()+ renderer.unmount()+ act(() => { window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true })) })+ expect(register).toHaveBeenCalledOnce()+ expect(unregister).toHaveBeenCalledOnce()+ })++ it("restores a new BFCache subscription after pagehide and retires a late old handle", async () => {+ const pending = Promise.withResolvers<{ unregister: () => Promise<void> }>()+ const { callbacks, register, unregister } = installBridge([pending.promise])+ const replacePath = vi.fn()+ const renderer = render(createElement(Harness, { dismissShellOverlay: () => false, parentPath: "/c/me", replacePath }))+ act(() => { window.dispatchEvent(new PageTransitionEvent("pagehide", { persisted: true })) })+ act(() => { window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: false })) })+ expect(register).toHaveBeenCalledOnce()+ act(() => { window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true })) })+ expect(register).toHaveBeenCalledTimes(2)+ const lateUnregister = vi.fn(async () => {})+ await act(async () => { pending.resolve({ unregister: lateUnregister }); await pending.promise })+ expect(lateUnregister).toHaveBeenCalledOnce()+ expect(unregister).not.toHaveBeenCalled()+ act(() => { callbacks[0]({ canGoBack: true }); callbacks[1]({ canGoBack: true }) })+ expect(replacePath).toHaveBeenCalledExactlyOnceWith("/c/me")+ act(() => { window.dispatchEvent(new PageTransitionEvent("pagehide", { persisted: true })) })+ expect(unregister).toHaveBeenCalledOnce()+ renderer.unmount()+ expect(unregister).toHaveBeenCalledOnce()+ })++ it.each(["iPhone", "Macintosh", "Linux desktop"])("does not register Android Back on %s", (userAgent) => {+ const { register } = installBridge()+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(userAgent)+ const replacePath = vi.fn()+ const renderer = render(createElement(Harness, { dismissShellOverlay: () => false, parentPath: "/c/me", replacePath }))+ expect(register).not.toHaveBeenCalled()+ act(() => { dispatchBack() })+ expect(replacePath).toHaveBeenCalledExactlyOnceWith("/c/me")+ renderer.unmount()+ })++ it.each([undefined, { app: {} }])("preserves the existing event path without a public API: %s", (bridge) => {+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue("Android WebView")+ vi.stubGlobal("__TAURI__", bridge)+ const replacePath = vi.fn()+ const renderer = render(createElement(Harness, { dismissShellOverlay: () => false, parentPath: "/c/me", replacePath }))+ act(() => { dispatchBack() })+ expect(replacePath).toHaveBeenCalledExactlyOnceWith("/c/me")+ renderer.unmount()+ })++ it("reports a rejected registration without retry or an unhandled rejection", async () => {+ const error = new Error("registration denied")+ const report = vi.spyOn(console, "error").mockImplementation(() => {})+ const { register } = installBridge([Promise.reject(error)])+ const renderer = render(createElement(Harness, { dismissShellOverlay: () => false, parentPath: null, replacePath: vi.fn() }))+ await waitFor(() => { expect(report).toHaveBeenCalledWith("Native Back listener failed", error) })+ expect(register).toHaveBeenCalledOnce()+ renderer.unmount()+ })++ it("reports unregister rejection and keeps the retired callback inert", async () => {+ const error = new Error("removal denied")+ const report = vi.spyOn(console, "error").mockImplementation(() => {})+ const unregister = vi.fn(async () => { throw error })+ const { callbacks } = installBridge([Promise.resolve({ unregister })])+ const replacePath = vi.fn()+ const renderer = render(createElement(Harness, { dismissShellOverlay: () => false, parentPath: "/c/me", replacePath }))+ await act(async () => {})+ renderer.unmount()+ await waitFor(() => { expect(report).toHaveBeenCalledWith("Native Back listener failed", error) })+ act(() => { callbacks[0]({ canGoBack: true }) })+ expect(replacePath).not.toHaveBeenCalled()+ expect(unregister).toHaveBeenCalledOnce()+ })+})+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)+ it("does not treat arbitrary dialog-slot markup as a Back owner", () => {+ const dismissShellOverlay = vi.fn(() => false)const replacePath = vi.fn()const keydown = vi.fn()document.addEventListener("keydown", keydown, { once: true })@@ -40,9 +235,10 @@ describe("useNativeMobileBack", () => {const event = dispatchBack()expect(event.defaultPrevented).toBe(true)- expect(keydown).toHaveBeenCalledWith(expect.objectContaining({ key: "Escape" }))- expect(dismissShellOverlay).not.toHaveBeenCalled()- expect(replacePath).not.toHaveBeenCalled()+ expect(keydown).not.toHaveBeenCalled()+ expect(dismissShellOverlay).toHaveBeenCalledOnce()+ expect(replacePath).toHaveBeenCalledExactlyOnceWith("/c/me")+ document.removeEventListener("keydown", keydown)renderer.unmount()})diff --git a/src/web/src/hooks/community/use-native-mobile-back.ts b/src/web/src/hooks/community/use-native-mobile-back.tsindex 24f7e8c41..c222681ea 100644--- a/src/web/src/hooks/community/use-native-mobile-back.ts+++ b/src/web/src/hooks/community/use-native-mobile-back.ts@@ -1,25 +1,16 @@-import { useEffect } from "react"+import { useEffect, useRef } from "react"+import { isMobile } from "@alook/shared"+import { requestNativeBack } from "@/components/ui/native-back-layer"export const MOBILE_BACK_EDGE_PX = 24export 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+type NativeBackListener = { unregister: () => Promise<void> }+type TauriBackWindow = Window & {+ __TAURI__?: {+ app?: { onBackButtonPress?: (callback: () => void) => Promise<NativeBackListener> }+ }}export function useNativeMobileBack({@@ -35,11 +26,62 @@ export function useNativeMobileBack({parentPath: string | nullreplacePath: (href: string) => void}) {+ const composing = useRef<EventTarget | null>(null)+ useEffect(() => {+ if (!isMobile() || !/android/i.test(navigator.userAgent)) return+ const app = (window as TauriBackWindow).__TAURI__?.app+ if (!app?.onBackButtonPress) return+ const register = app.onBackButtonPress.bind(app)+ const report = (error: unknown) => { console.error("Native Back listener failed", error) }+ const subscribe = () => {+ let active = true+ let listener: NativeBackListener | undefined+ void register(() => {+ if (active) window.dispatchEvent(new Event(NATIVE_MOBILE_BACK_EVENT, { cancelable: true }))+ }).then((registered) => {+ if (active) listener = registered+ else void registered.unregister().catch(report)+ }).catch(report)+ return () => {+ if (!active) return+ active = false+ if (listener) void listener.unregister().catch(report)+ }+ }+ let stop = subscribe()+ const hide = () => { stop() }+ const show = (event: PageTransitionEvent) => {+ if (!event.persisted) return+ stop()+ stop = subscribe()+ }+ window.addEventListener("pagehide", hide)+ window.addEventListener("pageshow", show)+ return () => {+ window.removeEventListener("pagehide", hide)+ window.removeEventListener("pageshow", show)+ stop()+ }+ }, [])+ useEffect(() => {+ const start = (event: CompositionEvent) => { composing.current = event.target }+ const end = () => { composing.current = null }+ document.addEventListener("compositionstart", start)+ document.addEventListener("compositionend", end)+ document.addEventListener("focusout", end)+ return () => {+ end()+ document.removeEventListener("compositionstart", start)+ document.removeEventListener("compositionend", end)+ document.removeEventListener("focusout", end)+ }+ }, [])useEffect(() => {const handleBack = (event: Event) => {if (!event.cancelable) returnevent.preventDefault()- if (dismissTopDocumentLayer() || dismissShellOverlay()) return+ if (composing.current === document.activeElement) return+ if (requestNativeBack(document) !== "none" || dismissShellOverlay()) returnif (parentPath) replacePath(parentPath)}