Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/2577-android-back-close-requests.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 3 additions & 0 deletions api-report/ui-kit.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -458,6 +460,7 @@ export "./internal" (./src/internal.ts)
canvas
mapViewBounds
printThemeCss
watchCloseRequests

export "./links" (./src/links.ts)
LINK_URL_MAX
Expand Down
9 changes: 7 additions & 2 deletions packages/ui-kit/src/chrome/Overlay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLElement>(".bk-overlay-body");
Expand Down
1 change: 1 addition & 0 deletions packages/ui-kit/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
152 changes: 152 additions & 0 deletions packages/ui-kit/src/internal/close-request.ts
Original file line number Diff line number Diff line change
@@ -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 `<dialog>` 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<Document, Opened[]>();

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();
},
};
}
30 changes: 24 additions & 6 deletions packages/ui-kit/src/internal/overlay-stack.ts
Original file line number Diff line number Diff line change
@@ -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 `<dialog>` receives
* close requests natively; a non-modal surface needs one of its own.
*/
watch: CloseRequestWatch | null;
}
const stacks = new WeakMap<Document, { entries: Entry[]; keys: (event: KeyboardEvent) => void }>();
const stacks = new WeakMap<Document, { entries: Registered[]; keys: (event: KeyboardEvent) => 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();
Expand All @@ -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);
Expand Down
8 changes: 4 additions & 4 deletions packages/ui-kit/tests/overlay-stack.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion packages/ui-kit/vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
18 changes: 8 additions & 10 deletions packages/ui-react/src/components/files/file-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
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";
Expand Down Expand Up @@ -59,7 +60,7 @@
return () => queueMicrotask(() => {
// Effect replay is not navigation away from the file. A real unmount
// or root replacement drops only that root's pending work and entry.
if (generation === lifetime.current || root !== latestRoot.current) {

Check warning on line 63 in packages/ui-react/src/components/files/file-panel.tsx

View workflow job for this annotation

GitHub Actions / changeset

react-hooks(exhaustive-deps)

packages/ui-react/src/components/files/file-panel.tsx:63:26: The ref's value `.current` is accessed directly in the effect cleanup function.
forgetFileEntry(root);
root.stores.file.getState().closeFile();
}
Expand All @@ -68,21 +69,18 @@
useEffect(() => {
if (wasOpen.current && !open) {
closeFile();
if (panes) queueMicrotask(() => { if (!latestOpen.current) returnTarget()?.focus({ preventScroll: true }); });

Check warning on line 72 in packages/ui-react/src/components/files/file-panel.tsx

View workflow job for this annotation

GitHub Actions / changeset

react-hooks(exhaustive-deps)

packages/ui-react/src/components/files/file-panel.tsx:72:66: React Hook useEffect has a missing dependency: 'returnTarget'
}
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.
Expand Down
4 changes: 2 additions & 2 deletions packages/ui-react/src/components/graph/graph-scene.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ export function SceneBody() {
{/* Accessible / mobile-friendly node list — the canvas itself is aria-hidden */}
<button /* raw-button: canvas — Floating graph canvas node-list control. */
ref={listButton}
onKeyDown={event => { if (event.key === "Escape" && listOpen) { event.stopPropagation(); closeList(); } }}
onKeyDown={event => { if (event.key === "Escape" && listOpen) { event.preventDefault(); event.stopPropagation(); closeList(); } }}
onClick={() => setListOpen((v) => !v)}
className="absolute bottom-3 right-3 z-10 flex h-11 w-11 items-center justify-center rounded-full border border-border bg-surface-overlay text-foreground shadow-lg"
title="Node list"
Expand Down Expand Up @@ -679,7 +679,7 @@ function NodeList({ onClose }: { onClose: () => void }) {
return (
<nav
aria-label="Graph nodes"
onKeyDown={event => { if (event.key === "Escape") { event.stopPropagation(); onClose(); } }}
onKeyDown={event => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); onClose(); } }}
className="absolute bottom-16 right-3 z-10 flex max-h-[55dvh] w-72 max-w-[calc(100vw-1.5rem)] flex-col overflow-hidden rounded-xl border border-border bg-surface-overlay/95 shadow-2xl backdrop-blur"
>
<div className="flex items-center justify-between border-b border-border px-3 py-2">
Expand Down
Loading
Loading