diff --git a/.changeset/2577-android-back-close-requests.md b/.changeset/2577-android-back-close-requests.md new file mode 100644 index 0000000000..d064ee8677 --- /dev/null +++ b/.changeset/2577-android-back-close-requests.md @@ -0,0 +1,6 @@ +--- +"@schlessera/brain-ui-kit": patch +"@schlessera/brain-ui-react": patch +--- + +Android back now closes an open panel instead of leaving the app. The phone destination drawers (Sessions, Files, Settings), the Settings and Files panes from 900px, and the dictation field each take a close request (Escape, the back gesture) through one shared `CloseWatcher` helper, close once and return focus to their opener. Where `CloseWatcher` is missing, Escape still closes them. A modal opened over a panel still closes first. A dictation take that is finishing, or a panel that cannot be dismissed, ignores the request. Escape in the share menu or the passkey rename field inside a panel now closes only that menu or field. diff --git a/api-report/ui-kit.txt b/api-report/ui-kit.txt index 72c392ed21..1971aae4f7 100644 --- a/api-report/ui-kit.txt +++ b/api-report/ui-kit.txt @@ -447,6 +447,8 @@ export "./brand" (./src/brand.ts) export "./brand/*" (./assets/brand/*) [asset] export "./internal" (./src/internal.ts) + type CloseRequestOptions + type CloseRequestWatch LIGHT_TOKENS PRINT_TOKENS TOKENS @@ -458,6 +460,7 @@ export "./internal" (./src/internal.ts) canvas mapViewBounds printThemeCss + watchCloseRequests export "./links" (./src/links.ts) LINK_URL_MAX diff --git a/packages/ui-kit/src/chrome/Overlay.tsx b/packages/ui-kit/src/chrome/Overlay.tsx index 6044dd8cb9..48899e4d99 100644 --- a/packages/ui-kit/src/chrome/Overlay.tsx +++ b/packages/ui-kit/src/chrome/Overlay.tsx @@ -88,10 +88,15 @@ export function Overlay(p: OverlayProps) { openingFocus.current ??= { opener: doc.activeElement as HTMLElement | null }; const { opener } = openingFocus.current; let active = true; - const request = (reason: OverlayCloseReason) => { + /** Returns whether the overlay was asked to close; `closedBy="none"` and a covered overlay stay. */ + const request = (reason: OverlayCloseReason): boolean => { cancelSwipe(); - if (active && isTopmost(doc, id.current) && latest.current.closedBy !== "none") latest.current.onClose(reason); + if (!active || !isTopmost(doc, id.current) || latest.current.closedBy === "none") return false; + latest.current.onClose(reason); + return true; }; + // A non-modal overlay's close request is its watcher's (#2577): Escape or + // Android back alike, reported with Escape's reason. const unregister = registerOverlay(doc, { id: id.current, modal, escape: () => request("escape") }); const focusInitial = () => { const body = surface.current?.querySelector(".bk-overlay-body"); diff --git a/packages/ui-kit/src/internal.ts b/packages/ui-kit/src/internal.ts index fb93dc57e9..caef2ae57d 100644 --- a/packages/ui-kit/src/internal.ts +++ b/packages/ui-kit/src/internal.ts @@ -4,5 +4,6 @@ * version. See docs/decisions/public-export-boundary.md. */ export { mapViewBounds } from "./blocks/MapView.js"; +export { watchCloseRequests, type CloseRequestOptions, type CloseRequestWatch } from "./internal/close-request.js"; export { LIGHT_TOKENS, PRINT_TOKENS, TOKENS, canvas, printThemeCss, type TokenName } from "./tokens.js"; export { TranscriptQualifiers, TranscriptSymbols, TranscriptReadingScope, type TranscriptQualifiersProps } from "./conversation/TranscriptQualifiers.js"; diff --git a/packages/ui-kit/src/internal/close-request.ts b/packages/ui-kit/src/internal/close-request.ts new file mode 100644 index 0000000000..8b1a890fa3 --- /dev/null +++ b/packages/ui-kit/src/internal/close-request.ts @@ -0,0 +1,152 @@ +/** + * Close requests for a non-modal surface (#2577): Escape, Android back and + * the other platform close gestures, as D52 N2 asks ("Esc, back, or the + * Close control closes a panel and returns focus to its opener"). + * + * A native modal `` already receives close requests. A non-modal + * panel does not: the platform mechanism is `CloseWatcher` (Chrome Android + * 126, Samsung 28, Firefox Android 149). While armed, this keeps one watcher + * for the surface and hands its `close` to `request`. Without `CloseWatcher`, + * or while disarmed, an Escape keydown stands in for it. + * + * `request` returns whether the surface closed. When it stays open + * (`closedBy="none"`, a dictation take that is finishing), the watcher has + * already been spent by the platform, so a new one is armed in its place and + * the next close request reaches this surface again. + * + * Arm and disarm are for drill-in history (#2582): while a panel has drill-in + * entries above its root, its watcher is disarmed, so Android back reaches + * `popstate` and pops one entry; at the root it is armed again. Escape keeps + * closing the panel at every depth (D52 N2), through the keydown fallback. + * + * DOM coordination only, shared first-party through `/internal`: not + * supported API. + */ + +/** The platform close watcher, as far as this helper uses it. */ +interface PlatformCloseWatcher { + onclose: ((event: Event) => void) | null; + destroy(): void; +} +type CloseWatcherConstructor = new () => PlatformCloseWatcher; + +export interface CloseRequestWatch { + /** Route close requests to the surface. A no-op while already armed. */ + arm(): void; + /** + * Let close requests pass to the page (Android back reaches `popstate`). + * Escape still closes the surface through the keydown fallback. + */ + disarm(): void; + /** Whether close requests currently reach the surface through a watcher. */ + readonly watching: boolean; + /** Whether this is the document's topmost open surface: the only one that takes close requests. */ + readonly topmost: boolean; + /** Stop for good: the watcher and the keydown fallback are removed. */ + destroy(): void; +} + +export interface CloseRequestOptions { + /** + * Handle Escape when no watcher is armed (default true). The overlay stack + * passes false: it keeps one document listener that hands Escape to its + * topmost entry only, so stacked surfaces never each take it. + */ + escape?: boolean; + /** Start disarmed (default armed). */ + armed?: boolean; +} + +/** + * Each document's open surfaces, in opening order. Only the topmost one holds + * a platform watcher, and only its Escape fallback acts: + * - a surface opened above another takes the watcher: the one beneath + * releases its own (`sleep`) and stays armed, and arms again (`wake`) once + * the surfaces above it close; + * - so a close request always reaches the topmost surface or, when that + * surface is disarmed (drilled in, #2582), the page, never a surface + * beneath: one Back is one step, innermost first; + * - and a surface beneath never takes the Escape that is the upper one's. + */ +interface Opened { id: symbol; wake: () => void; sleep: () => void } +const opened = new WeakMap(); + +function watcherConstructor(view: Window | null): CloseWatcherConstructor | null { + const candidate = (view as (Window & { CloseWatcher?: unknown }) | null)?.CloseWatcher; + return typeof candidate === "function" ? (candidate as CloseWatcherConstructor) : null; +} + +/** Watch close requests for one open surface in `document`; destroy it on close or unmount. */ +export function watchCloseRequests(document: Document, request: () => boolean, options: CloseRequestOptions = {}): CloseRequestWatch { + const Watcher = watcherConstructor(document.defaultView); + const id = Symbol("close-request"); + const order = opened.get(document) ?? []; + opened.set(document, order); + const topmost = () => order.at(-1)?.id === id; + let armed = options.armed ?? true; + let destroyed = false; + let watcher: PlatformCloseWatcher | null = null; + + const create = () => { + if (!Watcher || !armed || destroyed || watcher || !topmost()) return; + const created = new Watcher(); + created.onclose = () => { + // The platform destroys a watcher once it closes; drop our reference + // first, so the surface's request can re-enter arm() or destroy(). + if (watcher === created) watcher = null; + if (destroyed) return; + const closed = request(); + if (!closed) create(); + }; + watcher = created; + }; + const release = () => { + const current = watcher; + watcher = null; + if (current) { + current.onclose = null; + current.destroy(); + } + }; + const keys = (event: KeyboardEvent) => { + // With an armed watcher, Escape is the platform's close request and + // arrives through the watcher; handling it here too would close twice. + if (watcher || destroyed || event.key !== "Escape" || event.defaultPrevented || event.isComposing || !topmost()) return; + // Prevented only when the surface closed. A refusal (a modal over it, + // closedBy="none", a finishing take) leaves the keydown for whatever + // takes it next: a dialog above needs it for its own cancel. + if (request()) event.preventDefault(); + }; + // The surface beneath gives up its watcher to this one. + order.at(-1)?.sleep(); + order.push({ id, wake: () => create(), sleep: () => release() }); + if (options.escape ?? true) document.addEventListener("keydown", keys); + create(); + + return { + arm() { + armed = true; + create(); + }, + disarm() { + armed = false; + release(); + }, + get watching() { + return watcher !== null; + }, + get topmost() { + return !destroyed && topmost(); + }, + destroy() { + if (destroyed) return; + destroyed = true; + release(); + const index = order.findIndex((entry) => entry.id === id); + if (index !== -1) order.splice(index, 1); + document.removeEventListener("keydown", keys); + // The surface now on top may have an arming waiting on this one. + order.at(-1)?.wake(); + }, + }; +} diff --git a/packages/ui-kit/src/internal/overlay-stack.ts b/packages/ui-kit/src/internal/overlay-stack.ts index 1539694125..021eee2cc8 100644 --- a/packages/ui-kit/src/internal/overlay-stack.ts +++ b/packages/ui-kit/src/internal/overlay-stack.ts @@ -1,18 +1,32 @@ +import { watchCloseRequests, type CloseRequestWatch } from "./close-request.js"; + /** DOM coordination only: each document owns one ordered overlay registry. */ interface Entry { id: symbol; modal: boolean; - escape: () => void; + /** A close request (Escape, Android back) for this entry; returns whether it closed. */ + escape: () => boolean; +} +interface Registered extends Entry { + /** + * A non-modal entry's close watcher (#2577). A modal `` receives + * close requests natively; a non-modal surface needs one of its own. + */ + watch: CloseRequestWatch | null; } -const stacks = new WeakMap void }>(); +const stacks = new WeakMap void }>(); export function registerOverlay(document: Document, entry: Entry): () => void { let stack = stacks.get(document); if (!stack) { - const entries: Entry[] = []; + const entries: Registered[] = []; const keys = (event: KeyboardEvent) => { const top = entries.at(-1); - if (event.key !== "Escape" || event.defaultPrevented || event.isComposing || !top || top.modal) return; + // A watching top entry receives Escape as the platform's close request, + // through its watcher: taking it here as well would close twice. An + // entry with a surface opened above it (a dictation field over a + // drawer) is not the topmost surface, so the Escape is that surface's. + if (event.key !== "Escape" || event.defaultPrevented || event.isComposing || !top || top.modal || top.watch?.watching || top.watch?.topmost === false) return; event.preventDefault(); event.stopPropagation(); top.escape(); @@ -23,12 +37,16 @@ export function registerOverlay(document: Document, entry: Entry): () => void { } // Nested layout effects run child-first when opened in one commit. Keep // this same order as showModal(): the parent opens last and owns the top layer. - stack.entries.push(entry); + // One document listener hands Escape to the topmost entry only, so the + // watcher brings no keydown fallback of its own (`escape: false`). + const registered: Registered = { ...entry, watch: entry.modal ? null : watchCloseRequests(document, entry.escape, { escape: false }) }; + stack.entries.push(registered); let removed = false; return () => { if (removed) return; removed = true; - const index = stack.entries.indexOf(entry); + registered.watch?.destroy(); + const index = stack.entries.indexOf(registered); if (index !== -1) stack.entries.splice(index, 1); if (!stack.entries.length) { document.removeEventListener("keydown", stack.keys); diff --git a/packages/ui-kit/tests/overlay-stack.test.ts b/packages/ui-kit/tests/overlay-stack.test.ts index b110746fb7..d47e8bc938 100644 --- a/packages/ui-kit/tests/overlay-stack.test.ts +++ b/packages/ui-kit/tests/overlay-stack.test.ts @@ -8,8 +8,8 @@ test("only the last open entry receives document Escape; removal restores the pr const doc = win.document as unknown as Document; const first = Symbol(); const second = Symbol(); let a = 0; let b = 0; - const removeA = registerOverlay(doc, { id: first, modal: false, escape: () => a++ }); - const removeB = registerOverlay(doc, { id: second, modal: false, escape: () => b++ }); + const removeA = registerOverlay(doc, { id: first, modal: false, escape: () => (a++, true) }); + const removeB = registerOverlay(doc, { id: second, modal: false, escape: () => (b++, true) }); const escape = () => win.document.dispatchEvent(new win.KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true })); expect(isTopmost(doc, second)).toBe(true); escape(); @@ -22,8 +22,8 @@ test("a modal above a panel and a consumed Escape leave the panel alone", () => // Mutation: remove top.modal check → modal blocks panel assertion. const win = new Window(); const doc = win.document as unknown as Document; let calls = 0; - const remove = registerOverlay(doc, { id: Symbol(), modal: false, escape: () => calls++ }); - const removeModal = registerOverlay(doc, { id: Symbol(), modal: true, escape: () => calls++ }); + const remove = registerOverlay(doc, { id: Symbol(), modal: false, escape: () => (calls++, true) }); + const removeModal = registerOverlay(doc, { id: Symbol(), modal: true, escape: () => (calls++, true) }); win.document.dispatchEvent(new win.KeyboardEvent("keydown", { key: "Escape", cancelable: true })); expect(calls, "modal blocks panel").toBe(0); removeModal(); diff --git a/packages/ui-kit/vitest.config.ts b/packages/ui-kit/vitest.config.ts index 3c73ed6cfc..55e4aaaa1a 100644 --- a/packages/ui-kit/vitest.config.ts +++ b/packages/ui-kit/vitest.config.ts @@ -102,7 +102,7 @@ const railProject = (mode: "fine" | "coarse" | "mixed") => ({ // contrast (#974) and the palette's reason rows (#1106) are measured // under all three pointers as well, and so is FilterRow's default reach // (#4086). - include: ["tests/visual/native-buttons.visual.tsx", "tests/visual/filter-row-targets.visual.tsx", "tests/visual/side-rail-targets.visual.tsx", "tests/visual/button-hover-contrast.visual.tsx", "tests/visual/overlay-targets.visual.tsx", "tests/visual/session-strip.visual.tsx", "tests/visual/pending-follow-ups.visual.tsx", "tests/visual/palette-reasons.visual.tsx", "tests/visual/status-indicator-targets.visual.tsx", "../ui-react/tests/browser/desktop-navigation.pointer.tsx", "../ui-react/tests/browser/keyboard-hints.pointer.tsx", "../ui-react/tests/browser/phone-navigation.pointer.tsx", "../ui-react/tests/browser/destination-press.pointer.tsx", "../ui-react/tests/browser/working-sessions.pointer.tsx", "../ui-react/tests/browser/session-drafts.pointer.tsx", "../ui-react/tests/browser/navigation-reach.*.pointer.tsx", "../ui-react/tests/browser/hit-reach.*.pointer.tsx", "../ui-react/tests/browser/recordings-tray.offline.tsx", "../ui-react/tests/browser/dictation-notice.pointer.tsx", "../ui-react/tests/browser/attach-tooltip.pointer.tsx", "../ui-react/tests/browser/composer-mic.pointer.tsx", "../ui-react/tests/browser/overlay-stacking.pointer.tsx", "../ui-react/tests/browser/session-profile.pointer.tsx", "../ui-react/tests/browser/turn-budget.pointer.tsx"], + include: ["tests/visual/native-buttons.visual.tsx", "tests/visual/filter-row-targets.visual.tsx", "tests/visual/side-rail-targets.visual.tsx", "tests/visual/button-hover-contrast.visual.tsx", "tests/visual/overlay-targets.visual.tsx", "tests/visual/session-strip.visual.tsx", "tests/visual/pending-follow-ups.visual.tsx", "tests/visual/palette-reasons.visual.tsx", "tests/visual/status-indicator-targets.visual.tsx", "../ui-react/tests/browser/desktop-navigation.pointer.tsx", "../ui-react/tests/browser/keyboard-hints.pointer.tsx", "../ui-react/tests/browser/phone-navigation.pointer.tsx", "../ui-react/tests/browser/destination-press.pointer.tsx", "../ui-react/tests/browser/working-sessions.pointer.tsx", "../ui-react/tests/browser/session-drafts.pointer.tsx", "../ui-react/tests/browser/navigation-reach.*.pointer.tsx", "../ui-react/tests/browser/hit-reach.*.pointer.tsx", "../ui-react/tests/browser/recordings-tray.offline.tsx", "../ui-react/tests/browser/dictation-notice.pointer.tsx", "../ui-react/tests/browser/attach-tooltip.pointer.tsx", "../ui-react/tests/browser/composer-mic.pointer.tsx", "../ui-react/tests/browser/overlay-stacking.pointer.tsx", "../ui-react/tests/browser/close-requests.pointer.tsx", "../ui-react/tests/browser/session-profile.pointer.tsx", "../ui-react/tests/browser/turn-budget.pointer.tsx"], provide: { railPointer: mode, keyboardHintsLive: false }, browser: { enabled: true, diff --git a/packages/ui-react/src/components/files/file-panel.tsx b/packages/ui-react/src/components/files/file-panel.tsx index c1e4a29c7d..f14af4ee98 100644 --- a/packages/ui-react/src/components/files/file-panel.tsx +++ b/packages/ui-react/src/components/files/file-panel.tsx @@ -4,6 +4,7 @@ import type { ReceiptRow } from "@schlessera/brain-ui-kit"; import { ChevronDown, ChevronRight } from "lucide-react"; import { useFileStore } from "../../stores/file-store.js"; import { singleKey } from "../../lib/single-key.js"; +import { useCloseRequest } from "../../lib/use-close-request.js"; import { useUIStore } from "../../stores/ui-store.js"; import { useFinePointer } from "../../hooks/use-fine-pointer.js"; import { useMediaQuery } from "../../hooks/use-media-query.js"; @@ -73,16 +74,13 @@ export function FilePanel({ open, onClose }: { open: boolean; onClose: () => voi wasOpen.current = open; }, [open, panes, root, closeFile]); - useEffect(() => { - if (!open || !panes) return; - const onKey = (event: KeyboardEvent) => { - if (event.key !== "Escape" || event.defaultPrevented || openModal()) return; - event.preventDefault(); - dismiss(); - }; - document.addEventListener("keydown", onKey); - return () => document.removeEventListener("keydown", onKey); - }, [open, panes, dismiss]); + // The panes are no dialog: Escape and Android back reach them through the + // kit's close-request helper (#2577). The phone drawer is an Overlay. + useCloseRequest(open && panes, () => { + if (openModal()) return false; + dismiss(); + return true; + }); // Sync hash route to current file. When the panel closes, strip the // `#/files*` segment entirely so a reload doesn't reopen it. diff --git a/packages/ui-react/src/components/graph/graph-scene.tsx b/packages/ui-react/src/components/graph/graph-scene.tsx index bc1c6fee73..6bb446fa43 100644 --- a/packages/ui-react/src/components/graph/graph-scene.tsx +++ b/packages/ui-react/src/components/graph/graph-scene.tsx @@ -243,7 +243,7 @@ export function SceneBody() { {/* Accessible / mobile-friendly node list — the canvas itself is aria-hidden */} + {children(close)} + ; + } + const ui = createBrainUiRoot({ storage: null, request: async () => Response.json({}) }); + const renderer = createRoot(host); + ctx.onTestFinished(() => { flushSync(() => renderer.unmount()); ui.dispose(); host.remove(); }); + flushSync(() => renderer.render()); + await userEvent.click(host.querySelector("[data-test-open]")!); await frame(); + return { host, closes }; +} + +test("Escape in the share menu inside a pane closes only the menu", async ctx => { + spyCloseWatcher(ctx); + const s = await pane(ctx, () => true }, { id: "save", label: "Save the chart", run: async () => true }]} />); + await userEvent.click(s.host.querySelector('[aria-label="Share the chart"]')!); await frame(); + // The menu may draw in a portal: read the whole document. + await expect.poll(() => document.body.textContent, { message: "the menu is open" }).toContain("Copy the chart"); + await userEvent.keyboard("{Escape}"); await frame(); + expect(document.body.textContent, "the menu closed").not.toContain("Copy the chart"); + expect(s.closes, "PREVENTED_INNER_ESCAPE: the pane stays open").toEqual([]); + await userEvent.keyboard("{Escape}"); await frame(); + expect(s.closes, "the next Escape closes the pane").toHaveLength(1); +}); + +test("a pane that cannot be dismissed takes each close request and stays open, re-armed", async ctx => { + const seen = spyCloseWatcher(ctx); + const s = await pane(ctx, () =>

The suitors wait.

, "none"); + expect(seen.created, "a closedBy=none pane still holds a close watcher").toBeGreaterThan(0); + for (let i = 1; i <= 3; i++) { + await userEvent.keyboard("{Escape}"); await frame(); + expect(seen.closed, `request ${i} reached the pane's watcher`).toBe(i); + expect(s.closes, "the pane stays open").toEqual([]); + } + expect(document.querySelector('section[aria-label="Ithaca"]'), "still drawn").not.toBeNull(); +}); + +for (const watcher of [true, false]) test(`a modal opened over a pane takes Escape first${watcher ? "" : " (without CloseWatcher)"}, the pane the next`, async ctx => { + if (watcher) spyCloseWatcher(ctx); else withoutCloseWatcher(ctx); + const s = await pane(ctx, () =>

Penelope's loom.

); + const dialog = document.createElement("dialog"); + dialog.textContent = "The suitors' demands"; + document.body.append(dialog); + ctx.onTestFinished(() => dialog.remove()); + const open = document.createElement("button"); + open.textContent = "Show demands"; + open.onclick = () => dialog.showModal(); + document.body.append(open); + ctx.onTestFinished(() => open.remove()); + await userEvent.click(open); + expect(dialog.open).toBe(true); + await userEvent.keyboard("{Escape}"); await frame(); + expect(dialog.open, "the modal closed first").toBe(false); + expect(s.closes, "the pane stays open under it").toEqual([]); + await userEvent.keyboard("{Escape}"); await frame(); + expect(s.closes, "the next Escape closes the pane").toHaveLength(1); +}); + +test("Escape in the passkey rename field inside a pane cancels only the rename", async ctx => { + spyCloseWatcher(ctx); + const keys = [{ id: "bow", label: "Odysseus’s bow", rpId: "localhost", createdAt: Date.UTC(2026, 6, 1), lastUsedAt: null, backedUp: false, deviceType: null, transports: null, aaguid: null }]; + const s = await pane(ctx, () => {}} onRename={() => {}} onDelete={() => {}} onSignOut={() => {}} />); + await userEvent.click(s.host.querySelector('[aria-label^="Rename"]')!); await frame(); + const field = s.host.querySelector("input")!; + expect(field, "the rename field is open").toBeTruthy(); + field.focus(); + await userEvent.keyboard("{Escape}"); await frame(); + expect(s.host.querySelector("input"), "the rename was cancelled").toBeNull(); + expect(s.closes, "PREVENTED_INNER_ESCAPE: the pane stays open").toEqual([]); +}); + +test("a dictation take that is finishing survives a close request; once it is not, the next one cancels it once", async ctx => { + const seen = spyCloseWatcher(ctx); + const host = document.createElement("div"); + document.body.append(host); + const voice = useVoiceStore.getState(); + ctx.onTestFinished(() => { useVoiceStore.setState(voice, true); }); + const cancels: number[] = []; + useVoiceStore.setState({ mode: "dictate", dictationGate: null, draining: true }); + const renderer = createRoot(host); + ctx.onTestFinished(() => { flushSync(() => renderer.unmount()); host.remove(); }); + // Mounted from a real press, as a take starts from the mic. + const start = document.createElement("button"); + start.textContent = "Dictate"; + start.onclick = () => flushSync(() => renderer.render( {}} onCancel={() => cancels.push(1)} />)); + host.append(start); + await userEvent.click(start); await frame(); + expect(host.querySelector('[data-dictation-field="D5"]'), "the take is finishing").not.toBeNull(); + await userEvent.keyboard("{Escape}"); await frame(); + expect(seen.closed, "the close request reached the field's watcher").toBe(1); + expect(cancels, "a finishing take is not cancelled").toEqual([]); + flushSync(() => useVoiceStore.setState({ draining: false })); + await frame(); + await userEvent.keyboard("{Escape}"); await frame(); + expect(cancels, "the re-armed watcher cancels the take once").toEqual([1]); + expect(seen.closed).toBe(2); +}); + +test("without CloseWatcher, Escape still cancels a take once, and a finishing take refuses it", async ctx => { + withoutCloseWatcher(ctx); + const host = document.createElement("div"); + document.body.append(host); + const voice = useVoiceStore.getState(); + ctx.onTestFinished(() => { useVoiceStore.setState(voice, true); }); + const cancels: number[] = []; + useVoiceStore.setState({ mode: "dictate", dictationGate: null, draining: true }); + const renderer = createRoot(host); + ctx.onTestFinished(() => { flushSync(() => renderer.unmount()); host.remove(); }); + flushSync(() => renderer.render( {}} onCancel={() => cancels.push(1)} />)); + await frame(); + await userEvent.keyboard("{Escape}"); await frame(); + expect(cancels, "D5 refuses the fallback's Escape").toEqual([]); + flushSync(() => useVoiceStore.setState({ draining: false })); + await frame(); + await userEvent.keyboard("{Escape}"); await frame(); + expect(cancels, "then Escape cancels the take once").toEqual([1]); +}); + +test("without CloseWatcher, Escape on a dictation gate notice is Cancel, once", async ctx => { + withoutCloseWatcher(ctx); + const host = document.createElement("div"); + document.body.append(host); + const voice = useVoiceStore.getState(); + ctx.onTestFinished(() => { useVoiceStore.setState(voice, true); }); + const cancels: number[] = []; + useVoiceStore.setState({ dictationGate: { kind: "blocked", reason: "choose", saved: null } }); + const renderer = createRoot(host); + ctx.onTestFinished(() => { flushSync(() => renderer.unmount()); host.remove(); }); + flushSync(() => renderer.render( {}} onCancel={() => { cancels.push(1); useVoiceStore.setState({ dictationGate: null }); }} onOpenSettings={() => {}} onRetry={() => {}} onDismiss={() => {}} />)); + await frame(); + expect(host.querySelector('[data-dictation-notice="Dx1"]')).not.toBeNull(); + await userEvent.keyboard("{Escape}"); await frame(); + expect(cancels, "Cancel, once").toEqual([1]); +}); + +test("a disarmed surface beneath an armed one leaves Escape to the surface above", async ctx => { + spyCloseWatcher(ctx); + let lower = 0, upper = 0; + const openLower = document.createElement("button"); openLower.textContent = "Open the pane"; + const openUpper = document.createElement("button"); openUpper.textContent = "Start the take"; + document.body.append(openLower, openUpper); + let a: ReturnType | null = null, b: ReturnType | null = null; + // The pane keeps its Escape fallback (it is disarmed, as #2582 will do when drilled in). + openLower.onclick = () => { a = watchCloseRequests(document, () => { lower++; return true; }); a.disarm(); }; + openUpper.onclick = () => { b = watchCloseRequests(document, () => { upper++; return true; }); }; + ctx.onTestFinished(() => { a?.destroy(); b?.destroy(); openLower.remove(); openUpper.remove(); }); + await userEvent.click(openLower); await userEvent.click(openUpper); + await userEvent.keyboard("{Escape}"); await frame(); + expect([upper, lower], "the armed surface above closes; the disarmed pane beneath does not").toEqual([1, 0]); + b!.destroy(); + await userEvent.keyboard("{Escape}"); await frame(); + expect([upper, lower], "with the upper gone, Escape reaches the pane's fallback").toEqual([1, 1]); +}); + +test("re-arming a surface beneath another waits until the upper one closes", async ctx => { + const seen = spyCloseWatcher(ctx); + let lower = 0, upper = 0; + const openLower = document.createElement("button"); openLower.textContent = "Open the pane"; + const openUpper = document.createElement("button"); openUpper.textContent = "Start the take"; + document.body.append(openLower, openUpper); + let a: ReturnType | null = null, b: ReturnType | null = null; + openLower.onclick = () => { a = watchCloseRequests(document, () => { lower++; return true; }, { escape: false }); }; + openUpper.onclick = () => { b = watchCloseRequests(document, () => { upper++; return false; }, { escape: false }); }; + ctx.onTestFinished(() => { a?.destroy(); b?.destroy(); openLower.remove(); openUpper.remove(); }); + await userEvent.click(openLower); + // Drilled in (#2582): the pane is disarmed. Then a take opens above it. + a!.disarm(); + await userEvent.click(openUpper); + // Back at the pane's root while the take is still open: the pane re-arms. + a!.arm(); + expect(a!.watching, "the pane's arming waits beneath the take").toBe(false); + await userEvent.keyboard("{Escape}"); await frame(); + expect([upper, lower], "the take, on top, takes the request").toEqual([1, 0]); + b!.destroy(); + expect(a!.watching, "with the take gone, the pane's watcher is armed").toBe(true); + await userEvent.keyboard("{Escape}"); await frame(); + expect([upper, lower], "the next request reaches the pane").toEqual([1, 1]); + expect(seen.closed).toBe(2); +}); + +test("a disarmed surface above an armed one lets the close request reach the page, not the surface beneath", async ctx => { + spyCloseWatcher(ctx); + type Watcher = EventTarget & { destroy(): void }; + const Native = (window as unknown as { CloseWatcher: new () => Watcher }).CloseWatcher; + let reachedPage = 0; + let pageWatcher: Watcher | null = null; + const armPage = () => { pageWatcher = new Native(); pageWatcher.addEventListener("close", () => { reachedPage++; armPage(); }); }; + armPage(); + ctx.onTestFinished(() => pageWatcher?.destroy()); + let take = 0, pane = 0; + const startTake = document.createElement("button"); startTake.textContent = "Start the take"; + const openPane = document.createElement("button"); openPane.textContent = "Open the pane"; + document.body.append(startTake, openPane); + let a: ReturnType | null = null, b: ReturnType | null = null; + startTake.onclick = () => { a = watchCloseRequests(document, () => { take++; return true; }, { escape: false }); }; + openPane.onclick = () => { b = watchCloseRequests(document, () => { pane++; return true; }, { escape: false }); }; + ctx.onTestFinished(() => { a?.destroy(); b?.destroy(); startTake.remove(); openPane.remove(); }); + // A take is live, then a pane opens above it and drills in (#2582 disarms it). + await userEvent.click(startTake); await userEvent.click(openPane); + expect([a!.watching, b!.watching], "only the topmost surface holds a watcher").toEqual([false, true]); + b!.disarm(); + await userEvent.keyboard("{Escape}"); await frame(); + expect([take, pane, reachedPage], "Back pops the pane's drill-in: the page takes it, not the take beneath").toEqual([0, 0, 1]); + // Back at the pane's root: the pane closes on the next request, then the take. + b!.arm(); + await userEvent.keyboard("{Escape}"); await frame(); + expect([take, pane, reachedPage], "the pane closes").toEqual([0, 1, 1]); + b!.destroy(); + expect(a!.watching, "the take holds the watcher again").toBe(true); + await userEvent.keyboard("{Escape}"); await frame(); + expect([take, pane, reachedPage], "then the take").toEqual([1, 1, 1]); +}); + +for (const watcher of [true, false]) test(`a surface opened over a phone drawer takes Escape, not the drawer beneath${watcher ? "" : " (without CloseWatcher)"}`, async ctx => { + if (watcher) spyCloseWatcher(ctx); else withoutCloseWatcher(ctx); + await page.viewport(390, 800); + const host = document.createElement("div"); + document.body.append(host); + let drawerCloses = 0, surfaceCloses = 0; + function Drawer() { + const [open, setOpen] = useState(false); + return <> + + { drawerCloses++; setOpen(false); }}> +

Ithaca sessions

+
+ ; + } + const renderer = createRoot(host); + ctx.onTestFinished(() => { flushSync(() => renderer.unmount()); host.remove(); }); + flushSync(() => renderer.render()); + await userEvent.click(host.querySelector("[data-test-drawer]")!); await frame(); + expect(document.querySelector('[data-panel], [data-bk-overlay="panel"]'), "the drawer is open").not.toBeNull(); + // A surface opens above the drawer (a dictation notice arriving), from script. + let surface: ReturnType | null = watchCloseRequests(document, () => { surfaceCloses++; queueMicrotask(() => { surface?.destroy(); surface = null; }); return true; }); + ctx.onTestFinished(() => surface?.destroy()); + await userEvent.keyboard("{Escape}"); await frame(); + expect([surfaceCloses, drawerCloses], "the surface on top closes; the drawer beneath stays").toEqual([1, 0]); + await userEvent.keyboard("{Escape}"); await frame(); + expect([surfaceCloses, drawerCloses], "then the drawer").toEqual([1, 1]); +}); + +test("a dictation gate notice takes a close request as Cancel, once", async ctx => { + const seen = spyCloseWatcher(ctx); + const host = document.createElement("div"); + document.body.append(host); + const voice = useVoiceStore.getState(); + ctx.onTestFinished(() => { useVoiceStore.setState(voice, true); }); + const cancels: number[] = []; + const renderer = createRoot(host); + ctx.onTestFinished(() => { flushSync(() => renderer.unmount()); host.remove(); }); + flushSync(() => renderer.render( {}} onCancel={() => { cancels.push(1); useVoiceStore.setState({ dictationGate: null }); }} onOpenSettings={() => {}} onRetry={() => {}} onDismiss={() => {}} />)); + // A blocked take's notice (Dx1: choose a service) opens from the mic press. + const start = document.createElement("button"); + start.textContent = "Dictate"; + start.onclick = () => flushSync(() => useVoiceStore.setState({ dictationGate: { kind: "blocked", reason: "choose", saved: null } })); + host.append(start); + await userEvent.click(start); await frame(); + expect(host.querySelector('[data-dictation-notice="Dx1"]'), "the blocked-take notice shows").not.toBeNull(); + expect(seen.created, "the notice holds a close watcher").toBeGreaterThan(0); + await userEvent.keyboard("{Escape}"); await frame(); + expect(cancels, "Cancel, once").toEqual([1]); + expect(seen.closed, "through the notice's watcher").toBe(1); + expect(host.querySelector('[data-dictation-notice="Dx1"]')).toBeNull(); +}); + +test("arm and disarm: a disarmed surface lets the close request reach the page, re-arming restores exactly one dismissal per request", async ctx => { + const seen = spyCloseWatcher(ctx); + type Watcher = EventTarget & { destroy(): void }; + const Native = (window as unknown as { CloseWatcher: new () => Watcher }).CloseWatcher; + // The page beneath the surface, as #2582's history helper will be: it takes + // a close request (Android back reaching popstate) and arms itself again in + // that same handler, with no user activation. It stays beneath throughout, + // so a re-armed surface watcher that joined its group would show here. + let reachedPage = 0; + let pageWatcher: Watcher | null = null; + const armPage = () => { + pageWatcher = new Native(); + pageWatcher.addEventListener("close", () => { reachedPage++; armPage(); }); + }; + armPage(); + ctx.onTestFinished(() => pageWatcher?.destroy()); + // The surface opens from a real press, as a panel does. It stays open on + // every request (closedBy="none" style), so each request is counted. + let dismissals = 0; + let watch: ReturnType | null = null; + const open = document.createElement("button"); + open.textContent = "Open the surface"; + open.onclick = () => { watch = watchCloseRequests(document, () => { dismissals++; return false; }, { escape: false }); }; + document.body.append(open); + ctx.onTestFinished(() => { watch?.destroy(); open.remove(); }); + await userEvent.click(open); + expect(watch!.watching).toBe(true); + + watch!.disarm(); + expect(watch!.watching, "disarmed").toBe(false); + await userEvent.keyboard("{Escape}"); await frame(); + expect(dismissals, "a disarmed surface ignores the close request").toBe(0); + expect(reachedPage, "it reached the page instead").toBe(1); + + // Re-armed from script with no user activation, as #2582 will re-arm from + // popstate when the depth returns to the root. Then two requests: one + // dismissal each, the page beneath never, nothing grouped or skipped. + watch!.arm(); + expect(watch!.watching, "re-armed").toBe(true); + await userEvent.keyboard("{Escape}"); await frame(); + expect([dismissals, reachedPage], "first request after re-arming: the surface only").toEqual([1, 1]); + await userEvent.keyboard("{Escape}"); await frame(); + expect([dismissals, reachedPage], "second request: the surface only, not grouped with the page").toEqual([2, 1]); + // Disarm again: the page, still armed beneath, takes the next request alone. + watch!.disarm(); + await userEvent.keyboard("{Escape}"); await frame(); + expect([dismissals, reachedPage], "disarmed again: the page only").toEqual([2, 2]); + expect(seen.created, "a watcher per arming and re-arming").toBeGreaterThanOrEqual(4); +}); + +test("repeated refusals re-arm without joining the surface beneath: one action per request", async ctx => { + // A surface that refuses (a finishing take, closedBy="none") re-arms with a + // watcher created inside the close event, with no new user activation. It + // must stay its own step: the surface beneath (a pane under the take) is + // never closed along with it, however many requests it refuses. + spyCloseWatcher(ctx); + let lower = 0, upper = 0, upperCloses = false; + const openLower = document.createElement("button"); openLower.textContent = "Open the pane"; + const openUpper = document.createElement("button"); openUpper.textContent = "Start the take"; + document.body.append(openLower, openUpper); + let a: ReturnType | null = null, b: ReturnType | null = null; + openLower.onclick = () => { a = watchCloseRequests(document, () => { lower++; return true; }, { escape: false }); }; + // When the upper surface closes, its owner destroys the watch, as an unmount does. + openUpper.onclick = () => { b = watchCloseRequests(document, () => { upper++; if (upperCloses) queueMicrotask(() => b!.destroy()); return upperCloses; }, { escape: false }); }; + ctx.onTestFinished(() => { a?.destroy(); b?.destroy(); openLower.remove(); openUpper.remove(); }); + await userEvent.click(openLower); await userEvent.click(openUpper); + for (let i = 1; i <= 8; i++) { + await userEvent.keyboard("{Escape}"); await frame(); + expect([upper, lower], `refusal ${i} reached only the upper surface`).toEqual([i, 0]); + } + upperCloses = true; + await userEvent.keyboard("{Escape}"); await frame(); + expect([upper, lower], "the upper surface closes on its own").toEqual([9, 0]); + await userEvent.keyboard("{Escape}"); await frame(); + expect([upper, lower], "the next request reaches the surface beneath").toEqual([9, 1]); +}); + +test("a disarmed surface with the Escape fallback still closes on Escape, and the page does not also take it", async ctx => { + spyCloseWatcher(ctx); + const pageWatcher = new (window as unknown as { CloseWatcher: new () => EventTarget & { destroy(): void } }).CloseWatcher(); + let reachedPage = 0; + pageWatcher.addEventListener("close", () => { reachedPage++; }); + ctx.onTestFinished(() => pageWatcher.destroy()); + let dismissals = 0; + const watch = watchCloseRequests(document, () => { dismissals++; return true; }, { armed: false }); + ctx.onTestFinished(() => watch.destroy()); + await userEvent.keyboard("{Escape}"); await frame(); + expect(dismissals, "Escape closes it at any depth (D52 N2)").toBe(1); + expect(reachedPage, "one gesture, one action").toBe(0); +}); diff --git a/packages/ui-react/tests/browser/overlay-stacking.pointer.tsx b/packages/ui-react/tests/browser/overlay-stacking.pointer.tsx index 6e0189f7d8..fd3f324800 100644 --- a/packages/ui-react/tests/browser/overlay-stacking.pointer.tsx +++ b/packages/ui-react/tests/browser/overlay-stacking.pointer.tsx @@ -342,6 +342,13 @@ test("subagent Escape pops one level without remounting and focuses the new Back for (const destination of ["files", "settings"] as const) test(`${destination} pane: Escape respects inner prevention and modal stacking`, async ctx => { // Mutations: delete the pane listener, ignore defaultPrevented, or ignore openModal. + // The guards below are dispatched as synthetic (untrusted) Escapes, which + // never raise a close request: they are the keydown fallback's guards, so + // the test runs where that fallback is the path, without CloseWatcher + // (#2577). The watcher path's guards are in close-requests.pointer.tsx. + const closeWatcher = Object.getOwnPropertyDescriptor(window, "CloseWatcher"); + Reflect.deleteProperty(window, "CloseWatcher"); + ctx.onTestFinished(() => { if (closeWatcher) Object.defineProperty(window, "CloseWatcher", closeWatcher); }); const s = await mount(ctx, 1280); flushSync(() => { if (destination === "settings") s.ui.stores.ui.getState().setSettingsTab("appearance");