commit 0db14837db18a79a4bee3ca81c0137bc20c01f92
parent c1ee0c1022645200e605a3f36ab4910a3750c180
Author: Florian Dold <dold@taler.net>
Date: Fri, 13 Nov 2026 01:06:14 +0100
web-util: restore dialog openers and coordinate nested dialogs
DialogFocusScope adds Escape handling and opener restoration to a focus
scope. Hooks provide the same behavior for existing wrappers. Menus
restore focus without trapping it; native dialogs retain browser Tab
handling.
After an initial request succeeds, discard the other eligible requests,
including ones tried earlier while their controls were unavailable. Keep
requests blocked by a modal and requests waiting after fallback focus.
Issue: https://bugs.taler.net/n/12002
Issue: https://bugs.taler.net/n/12024
Issue: https://bugs.taler.net/n/12034
Assisted-by: LLM
Diffstat:
3 files changed, 425 insertions(+), 27 deletions(-)
diff --git a/packages/web-util/src/components/FocusScope.test.tsx b/packages/web-util/src/components/FocusScope.test.tsx
@@ -17,10 +17,17 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { h, Fragment, render } from "preact";
+import { createPortal } from "preact/compat";
import { useRef } from "preact/hooks";
import { Window } from "happy-dom";
import { firstEditableField } from "./focus-dom.js";
-import { FocusScope, useFocusScope, useFocusTarget } from "./FocusScope.js";
+import {
+ FocusScope,
+ useFocusScope,
+ useFocusTarget,
+ DialogFocusScope,
+ useDialogFocus,
+} from "./FocusScope.js";
const window = new Window();
Object.assign(globalThis, {
window,
@@ -79,6 +86,154 @@ test("late requests are cancelled by deliberate focus movement", async () => {
assert.equal(document.activeElement?.id, "other");
await reset();
});
+test("a successful request cancels competing requests tried before it", async () => {
+ function Field({ id, disabled = false }: { id: string; disabled?: boolean }) {
+ const target = useFocusTarget<HTMLInputElement>();
+ useFocusScope({ initialFocus: target.get });
+ return <input ref={target.ref} id={id} disabled={disabled} />;
+ }
+ function Form({ disabled }: { disabled: boolean }) {
+ return (
+ <>
+ <Field id="available" />
+ <Field id="waiting" disabled={disabled} />
+ </>
+ );
+ }
+ await show(<Form disabled />);
+ assert.equal(document.activeElement?.id, "available");
+ await show(<Form disabled={false} />);
+ assert.equal(document.activeElement?.id, "available");
+ await reset();
+});
+test("fallback focus preserves a waiting request until the user interacts", async () => {
+ function Form({ ready }: { ready: boolean }) {
+ const field = useFocusTarget<HTMLInputElement>();
+ const fallback = useRef<HTMLButtonElement>(null);
+ useFocusScope({
+ ready,
+ initialFocus: field.get,
+ fallbackFocus: () => fallback.current,
+ });
+ return (
+ <>
+ <button ref={fallback} id="fallback">
+ Loading
+ </button>
+ <button id="elsewhere">Elsewhere</button>
+ <input ref={field.ref} id="ready-field" />
+ </>
+ );
+ }
+ await show(<Form ready={false} />);
+ assert.equal(document.activeElement?.id, "fallback");
+ await show(<Form ready />);
+ assert.equal(document.activeElement?.id, "ready-field");
+ await reset();
+ await show(<Form ready={false} />);
+ document.getElementById("elsewhere")!.focus();
+ await show(<Form ready />);
+ assert.equal(document.activeElement?.id, "elsewhere");
+ await reset();
+});
+test("a modal's initial focus preserves requests blocked behind it", async () => {
+ function Dialog() {
+ const dialog = useRef<HTMLDivElement>(null);
+ useDialogFocus({
+ root: () => dialog.current,
+ initialFocus: () => dialog.current?.querySelector("button"),
+ });
+ return (
+ <div ref={dialog}>
+ <button id="modal-field">Modal</button>
+ </div>
+ );
+ }
+ function Scene({ open }: { open: boolean }) {
+ const background = useFocusTarget<HTMLInputElement>();
+ useFocusScope({ initialFocus: background.get });
+ return (
+ <>
+ <input ref={background.ref} id="background-field" />
+ {open && <Dialog />}
+ </>
+ );
+ }
+ await show(<Scene open />);
+ assert.equal(document.activeElement?.id, "modal-field");
+ await show(<Scene open={false} />);
+ assert.equal(document.activeElement?.id, "background-field");
+ await reset();
+});
+test("nested portalled scopes isolate, contain, handle Escape once and restore", async () => {
+ const opener = document.createElement("button");
+ document.body.append(opener);
+ opener.focus();
+ let escaped = "";
+ function Dialogs({ child }: { child: boolean }) {
+ const parent = useRef<HTMLDivElement>(null),
+ nested = useRef<HTMLDivElement>(null);
+ return (
+ <DialogFocusScope
+ root={() => parent.current}
+ initialFocus={() => parent.current?.querySelector("button")}
+ onEscape={() => {
+ escaped = "parent";
+ }}
+ >
+ {createPortal(
+ <div ref={parent}>
+ <button id="parent">Parent</button>
+ <button id="last">Last</button>
+ </div>,
+ document.body,
+ )}
+ {child && (
+ <DialogFocusScope
+ root={() => nested.current}
+ initialFocus={() => nested.current?.querySelector("button")}
+ onEscape={() => {
+ escaped = "child";
+ }}
+ >
+ {createPortal(
+ <div ref={nested}>
+ <button id="child">Child</button>
+ </div>,
+ document.body,
+ )}
+ </DialogFocusScope>
+ )}
+ </DialogFocusScope>
+ );
+ }
+ await show(<Dialogs child={false} />);
+ assert.equal(document.activeElement?.id, "parent");
+ assert.equal(opener.inert, true);
+ await show(<Dialogs child />);
+ assert.equal(document.activeElement?.id, "child");
+ document.activeElement?.dispatchEvent(
+ new window.KeyboardEvent("keydown", {
+ key: "Escape",
+ bubbles: true,
+ }) as unknown as KeyboardEvent,
+ );
+ assert.equal(escaped, "child");
+ document.activeElement?.dispatchEvent(
+ new window.KeyboardEvent("keydown", {
+ key: "Tab",
+ bubbles: true,
+ }) as unknown as KeyboardEvent,
+ );
+ assert.equal(document.activeElement?.id, "child");
+ await show(<Dialogs child={false} />);
+ assert.equal(document.activeElement?.id, "parent");
+ assert.equal(opener.inert, true);
+ await reset();
+ assert.ok(document.activeElement === opener);
+ assert.equal(opener.inert, false);
+ opener.remove();
+});
test("eligibility skips hidden, readonly and inherited-disabled fields", async () => {
await show(
<div id="fields">
@@ -98,6 +253,82 @@ test("eligibility skips hidden, readonly and inherited-disabled fields", async (
);
await reset();
});
+test("closing a scope preserves focus deliberately moved elsewhere", async () => {
+ const outside = document.createElement("button");
+ document.body.append(outside);
+ function Panel() {
+ const input = useFocusTarget<HTMLInputElement>();
+ return (
+ <DialogFocusScope root={input.get} initialFocus={input.get} kind="menu">
+ <input ref={input.ref} />
+ </DialogFocusScope>
+ );
+ }
+ await show(<Panel />);
+ outside.focus();
+ await show(null);
+ assert.ok(document.activeElement === outside);
+ outside.remove();
+});
+test("step activation preserves the original opener for restoration", async () => {
+ const opener = document.createElement("button");
+ document.body.append(opener);
+ opener.focus();
+ function Steps({ step }: { step: string }) {
+ const input = useFocusTarget<HTMLInputElement>();
+ return (
+ <DialogFocusScope
+ root={input.get}
+ initialFocus={input.get}
+ activationKey={step}
+ kind="menu"
+ >
+ <input ref={input.ref} id={step} />
+ </DialogFocusScope>
+ );
+ }
+ await show(<Steps step="email" />);
+ await show(<Steps step="sms" />);
+ assert.equal(document.activeElement?.id, "sms");
+ await show(null);
+ assert.ok(document.activeElement === opener);
+ opener.remove();
+});
+test("reopening resets restoration after an earlier outside-focus dismissal", async () => {
+ const opener = document.createElement("button"),
+ outside = document.createElement("button");
+ document.body.append(opener, outside);
+ function Reusable({ active }: { active: boolean }) {
+ const input = useFocusTarget<HTMLInputElement>();
+ useDialogFocus({
+ active,
+ root: input.get,
+ initialFocus: input.get,
+ returnFocus: () => opener,
+ kind: "menu",
+ });
+ return active ? <input ref={input.ref} id="reopened" /> : null;
+ }
+ try {
+ opener.focus();
+ await show(<Reusable active />);
+ outside.focus();
+ await show(<Reusable active={false} />);
+ assert.ok(document.activeElement === outside);
+ opener.focus();
+ await show(<Reusable active />);
+ assert.equal(document.activeElement?.id, "reopened");
+ await show(<Reusable active={false} />);
+ assert.ok(
+ document.activeElement === opener,
+ "the second close restores the opener",
+ );
+ } finally {
+ await reset();
+ opener.remove();
+ outside.remove();
+ }
+});
test("history restoration wins over form defaults and waits for readiness", async () => {
function Page({ ready }: { ready: boolean }) {
const page = useRef<HTMLDivElement>(null);
@@ -127,6 +358,43 @@ test("history restoration wins over form defaults and waits for readiness", asyn
assert.equal(document.activeElement?.id, "saved-control");
await reset();
});
+test("ordinary dialog renders do not rewrite background isolation", async () => {
+ function Dialog({ value }: { value: string }) {
+ const dialog = useRef<HTMLDivElement>(null);
+ return (
+ <DialogFocusScope
+ root={() => dialog.current}
+ initialFocus={() => dialog.current?.querySelector("input")}
+ >
+ {createPortal(
+ <div ref={dialog}>
+ <input value={value} />
+ </div>,
+ document.body,
+ )}
+ </DialogFocusScope>
+ );
+ }
+ let changes = 0;
+ const observer = new window.MutationObserver((records) => {
+ changes += records.length;
+ });
+ observer.observe(window.document.body, {
+ attributes: true,
+ subtree: true,
+ attributeFilter: ["inert"],
+ });
+ await show(<Dialog value="first" />);
+ assert.equal(root.inert, true);
+ await Promise.resolve();
+ changes = 0;
+ await show(<Dialog value="typed" />);
+ await Promise.resolve();
+ assert.equal(changes, 0);
+ await reset();
+ assert.equal(root.inert, false);
+ observer.disconnect();
+});
test("an unavailable explicit target is not deferred into a later interaction", async () => {
let result: boolean | undefined;
function Form({ ready }: { ready: boolean }) {
diff --git a/packages/web-util/src/components/FocusScope.tsx b/packages/web-util/src/components/FocusScope.tsx
@@ -16,7 +16,8 @@
import { createContext, h, type ComponentChildren } from "preact";
import { useCallback, useContext, useLayoutEffect, useRef } from "preact/hooks";
-import { focusElement } from "./focus-dom.js";
+import { DialogStack, type DialogKind } from "./dialog-focus.js";
+import { focusElement, initialDialogFocus } from "./focus-dom.js";
export type FocusTarget = () => HTMLElement | null | undefined;
export interface FocusOptions {
@@ -39,12 +40,26 @@ export interface FocusScopeOptions extends FocusOptions {
/** Browser-history restoration takes precedence over initial page/form focus. */
restoreTarget?: FocusTarget;
}
-
+/**
+ * Also restore the opener on close and handle Escape. Custom modals trap Tab
+ * and make the background inert; native dialogs use the browser's Tab handling.
+ * Menus restore focus without trapping it.
+ */
+export interface DialogFocusOptions extends FocusScopeOptions {
+ root: FocusTarget;
+ kind?: DialogKind;
+ returnFocus?: FocusTarget;
+ onEscape?: () => void;
+}
interface Scope {
options: FocusScopeOptions;
+ dialog?: DialogFocusOptions;
parent: Scope | null;
pending: boolean;
+ previous: HTMLElement | null;
+ order: number;
fallbackTaken: boolean;
+ restoreAllowed: boolean;
}
const ScopeContext = createContext<Scope | null>(null);
const coordinators = new WeakMap<Document, Coordinator>();
@@ -68,32 +83,103 @@ function childrenFirst(scopes: Scope[]): Scope[] {
}
return result;
}
-
class Coordinator {
scopes = new Set<Scope>();
private queued = false;
private moving = false;
+ private sequence = 0;
+ private restored: {
+ order: number;
+ scope: Scope;
+ target: HTMLElement | null;
+ }[] = [];
+ private dialogs: DialogStack;
constructor(readonly doc: Document) {
+ this.dialogs = new DialogStack(doc, (target) => this.move(target));
doc.addEventListener("focusin", this.onFocus, true);
- doc.addEventListener("pointerdown", this.cancelPending, true);
+ doc.addEventListener("pointerdown", this.onPointer, true);
doc.addEventListener("keydown", this.onKey, true);
}
+ private inside(scope: Scope, target: Node | null): boolean {
+ return (
+ !!target &&
+ [...this.scopes].some(
+ (s) => (s === scope || owns(scope, s)) && rootOf(s)?.contains(target),
+ )
+ );
+ }
+ private refreshDialogs() {
+ const layers = childrenFirst(
+ [...this.scopes].reverse().filter((s) => s.dialog),
+ );
+ this.dialogs.update(
+ layers.map((scope) => {
+ const all = [...this.scopes]
+ .filter((s) => s === scope || owns(scope, s))
+ .map(rootOf)
+ .filter((r): r is HTMLElement => !!r?.isConnected);
+ return {
+ kind: scope.dialog!.kind ?? "modal",
+ roots: [...new Set(all)].filter(
+ (root) =>
+ !all.some((other) => other !== root && other.contains(root)),
+ ),
+ onEscape: scope.dialog!.onEscape,
+ fallback: () =>
+ scope.options.fallbackFocus?.() ??
+ initialDialogFocus(rootOf(scope)),
+ };
+ }),
+ );
+ }
add(scope: Scope) {
+ scope.previous = this.doc.activeElement as HTMLElement | null;
+ // An earlier opening may have ended with focus outside the dialog.
+ scope.restoreAllowed = true;
+ scope.order = ++this.sequence;
this.scopes.add(scope);
}
remove(scope: Scope) {
this.scopes.delete(scope);
scope.pending = false;
+ if (scope.dialog && scope.restoreAllowed)
+ this.restored.push({
+ order: scope.order,
+ scope,
+ target: scope.dialog.returnFocus?.() ?? scope.previous,
+ });
this.schedule();
}
- private cancelPending = () => {
- for (const scope of this.scopes) scope.pending = false;
+ private cancelPending() {
+ for (const scope of this.scopes) {
+ scope.pending = false;
+ }
+ }
+ private onPointer = (event: Event) => {
+ this.cancelPending();
};
- private onFocus = () => {
- if (!this.moving) this.cancelPending();
+ private onFocus = (event: Event) => {
+ if (this.moving) return;
+ this.refreshDialogs();
+ if (this.dialogs.redirect(event.target as Node)) return;
+ // showModal() may focus its default target before our initial request runs.
+ if (
+ [...this.scopes].some(
+ (s) =>
+ s.pending &&
+ s.dialog?.kind === "native" &&
+ this.inside(s, event.target as Node),
+ )
+ )
+ return;
+ for (const scope of this.scopes)
+ scope.restoreAllowed = this.inside(scope, event.target as Node);
+ this.cancelPending();
};
private onKey = (event: KeyboardEvent) => {
if (event.key === "Tab") this.cancelPending();
+ this.refreshDialogs();
+ this.dialogs.key(event);
};
private move(
target: HTMLElement | null | undefined,
@@ -110,7 +196,9 @@ class Coordinator {
target: HTMLElement | null | undefined,
options: FocusOptions,
): boolean {
- if (!this.move(target, options)) return false;
+ this.refreshDialogs();
+ if (!this.dialogs.allows(target) || !this.move(target, options))
+ return false;
this.cancelPending();
return true;
}
@@ -121,24 +209,26 @@ class Coordinator {
}
private flush() {
this.queued = false;
+ this.refreshDialogs();
const candidates = [...this.scopes]
.reverse()
- .filter((scope) => scope.pending);
+ .filter((s) => s.pending && this.dialogs.allows(rootOf(s)));
// Restore a history entry before applying the new page's default focus.
const pending = [
- ...childrenFirst(
- candidates.filter((scope) => scope.options.restoreTarget),
- ),
- ...childrenFirst(
- candidates.filter((scope) => !scope.options.restoreTarget),
- ),
+ ...childrenFirst(candidates.filter((s) => s.options.restoreTarget)),
+ ...childrenFirst(candidates.filter((s) => !s.options.restoreTarget)),
];
+ for (const scope of this.scopes)
+ if (!scope.previous?.isConnected || scope.previous === this.doc.body) {
+ scope.previous =
+ this.restored
+ .filter((item) => item.order < scope.order)
+ .map((item) => item.target)
+ .reverse()
+ .find((target) => target?.isConnected) ?? scope.previous;
+ }
let claimed = false;
for (const scope of pending) {
- if (claimed) {
- scope.pending = false;
- continue;
- }
const ready =
typeof scope.options.ready === "function"
? scope.options.ready()
@@ -147,10 +237,12 @@ class Coordinator {
? (scope.options.restoreTarget?.() ?? scope.options.initialFocus?.())
: null;
if (this.move(target, scope.options)) {
- scope.pending = false;
claimed = true;
+ // Failed candidates must not take focus later when they become ready.
+ for (const candidate of pending) candidate.pending = false;
for (const parent of this.scopes)
if (owns(parent, scope)) parent.pending = false;
+ break;
} else if (
!scope.fallbackTaken &&
this.move(scope.options.fallbackFocus?.())
@@ -158,9 +250,20 @@ class Coordinator {
scope.fallbackTaken = true;
if (!ready && scope.options.restoreTarget) break;
}
+ if (!claimed)
+ for (const { order, scope, target } of this.restored.slice().reverse()) {
+ if (pending.some((s) => s.order > order)) break;
+ if (!this.dialogs.allows(target)) continue;
+ if (
+ this.move(target) ||
+ this.move(scope.parent?.options.fallbackFocus?.())
+ )
+ break;
+ }
+ this.restored = [];
if (!this.scopes.size) {
this.doc.removeEventListener("focusin", this.onFocus, true);
- this.doc.removeEventListener("pointerdown", this.cancelPending, true);
+ this.doc.removeEventListener("pointerdown", this.onPointer, true);
this.doc.removeEventListener("keydown", this.onKey, true);
coordinators.delete(this.doc);
}
@@ -182,16 +285,23 @@ export function useFocusTarget<T extends HTMLElement>() {
const get = useCallback(() => current.current, []);
return { ref, get };
}
-
-function useScope(options: FocusScopeOptions) {
+function useScope(options: FocusScopeOptions, dialog?: DialogFocusOptions) {
const parent = useContext(ScopeContext);
const node = useRef<Scope>({
options,
+ dialog,
parent,
pending: false,
+ previous: null,
+ order: 0,
fallbackTaken: false,
+ restoreAllowed: true,
+ });
+ Object.assign(node.current, {
+ options,
+ dialog,
+ parent,
});
- Object.assign(node.current, { options, parent });
const owner = useRef<Coordinator>();
const activation = useRef(options.activationKey);
useLayoutEffect(() => {
@@ -235,6 +345,11 @@ export function useFocusScope(options: FocusScopeOptions) {
const { requestFocus } = useScope(options);
return { requestFocus };
}
+/** Hook version for existing dialog and menu wrappers. */
+export function useDialogFocus(options: DialogFocusOptions) {
+ const { requestFocus } = useScope(options, options);
+ return { requestFocus };
+}
/** Give child components the same focus owner, including through portals. */
export function FocusScope({
children,
@@ -243,3 +358,11 @@ export function FocusScope({
const { node } = useScope(options);
return <ScopeContext.Provider value={node}>{children}</ScopeContext.Provider>;
}
+/** FocusScope with dialog behavior; kind defaults to "modal". */
+export function DialogFocusScope({
+ children,
+ ...options
+}: DialogFocusOptions & { children: ComponentChildren }) {
+ const { node } = useScope(options, options);
+ return <ScopeContext.Provider value={node}>{children}</ScopeContext.Provider>;
+}
diff --git a/packages/web-util/src/components/index.ts b/packages/web-util/src/components/index.ts
@@ -21,9 +21,16 @@ export {
initialDialogFocus,
} from "./focus-dom.js";
-export { FocusScope, useFocusScope, useFocusTarget } from "./FocusScope.js";
+export {
+ FocusScope,
+ DialogFocusScope,
+ useFocusScope,
+ useDialogFocus,
+ useFocusTarget,
+} from "./FocusScope.js";
export type {
FocusScopeOptions,
+ DialogFocusOptions,
FocusTarget,
FocusOptions,
} from "./FocusScope.js";