commit d8eedea1529d070bd176c70e365ac963615a5d56
parent 0db14837db18a79a4bee3ca81c0137bc20c01f92
Author: Florian Dold <dold@taler.net>
Date: Fri, 13 Nov 2026 01:06:16 +0100
web UIs: keep previews from taking keyboard focus
FocusPolicy blocks automatic focus until the reader interacts with a
preview. The policy follows components through portals.
Issue: https://bugs.taler.net/n/12002
Issue: https://bugs.taler.net/n/12024
Assisted-by: LLM
Diffstat:
5 files changed, 283 insertions(+), 128 deletions(-)
diff --git a/packages/taler-merchant-webui/src/tutorial/LiveComponentPreview.tsx b/packages/taler-merchant-webui/src/tutorial/LiveComponentPreview.tsx
@@ -14,6 +14,7 @@
GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
+import { FocusPolicy } from "@gnu-taler/web-util/browser";
import type { VNode, ComponentChildren } from "preact";
import { useId, useState } from "preact/hooks";
import { Router } from "wouter-preact";
@@ -234,128 +235,132 @@ export function LiveComponentPreview({
t`Default`;
return (
- <div
- data-live-preview="true"
- class={`my-6 border-2 border-gray-300 rounded-xl overflow-hidden shadow-md bg-white ${maxWidthClass} mx-auto`}
- onClickCapture={containNavigation}
- onSubmitCapture={containNavigation}
- >
- {/* Browser Window Mockup Top Header */}
- <div class="bg-gray-100 border-b border-gray-200 px-3.5 py-2 flex items-center justify-between gap-2 flex-wrap relative z-30">
- <div class="flex items-center space-x-2 min-w-0">
- <div class="flex space-x-1.5 shrink-0">
- <div class="w-3 h-3 rounded-full bg-red-400"></div>
- <div class="w-3 h-3 rounded-full bg-amber-400"></div>
- <div class="w-3 h-3 rounded-full bg-emerald-400"></div>
- </div>
- {title && (
- <span class="text-xs font-semibold text-gray-600 ml-2 truncate">
- {title}
- </span>
- )}
- </div>
-
- {/* Interactive Data Set Switcher Dropdown */}
- {dataSets && dataSets.length > 0 && (
- <div class="relative inline-block text-left shrink-0">
- <button
- type="button"
- id={switcherId}
- data-dataset-switcher="true"
- aria-haspopup="menu"
- aria-expanded={isDropdownOpen}
- onClick={() => setIsDropdownOpen(!isDropdownOpen)}
- onKeyDown={(e) => {
- if (e.key === "Escape") setIsDropdownOpen(false);
- }}
- class="inline-flex items-center space-x-1 px-2 py-0.5 rounded text-[11px] font-medium bg-gray-200/60 hover:bg-gray-200 text-gray-700 transition-colors cursor-pointer border border-gray-300/60"
- >
- <span>
- {t`Data:`}{" "}
- <strong class="font-bold text-gray-900">
- {currentDataSetLabel}
- </strong>
+ <FocusPolicy automatic={false}>
+ <div
+ data-live-preview="true"
+ class={`my-6 border-2 border-gray-300 rounded-xl overflow-hidden shadow-md bg-white ${maxWidthClass} mx-auto`}
+ onClickCapture={containNavigation}
+ onSubmitCapture={containNavigation}
+ >
+ {/* Browser Window Mockup Top Header */}
+ <div class="bg-gray-100 border-b border-gray-200 px-3.5 py-2 flex items-center justify-between gap-2 flex-wrap relative z-30">
+ <div class="flex items-center space-x-2 min-w-0">
+ <div class="flex space-x-1.5 shrink-0">
+ <div class="w-3 h-3 rounded-full bg-red-400"></div>
+ <div class="w-3 h-3 rounded-full bg-amber-400"></div>
+ <div class="w-3 h-3 rounded-full bg-emerald-400"></div>
+ </div>
+ {title && (
+ <span class="text-xs font-semibold text-gray-600 ml-2 truncate">
+ {title}
</span>
- <span class="text-[9px] text-gray-500">▼</span>
- </button>
+ )}
+ </div>
- {isDropdownOpen && (
- <div
- role="menu"
- tabIndex={-1}
- aria-label={t`Choose sample data`}
- class="absolute right-0 mt-1 w-56 rounded-xl shadow-xl bg-white border border-gray-200 ring-1 ring-black/5 z-50 overflow-hidden divide-y divide-gray-100"
+ {/* Interactive Data Set Switcher Dropdown */}
+ {dataSets && dataSets.length > 0 && (
+ <div class="relative inline-block text-left shrink-0">
+ <button
+ type="button"
+ id={switcherId}
+ data-dataset-switcher="true"
+ aria-haspopup="menu"
+ aria-expanded={isDropdownOpen}
+ onClick={() => setIsDropdownOpen(!isDropdownOpen)}
onKeyDown={(e) => {
- if (e.key === "Escape") {
- setIsDropdownOpen(false);
- document.getElementById(switcherId)?.focus();
- }
+ if (e.key === "Escape") setIsDropdownOpen(false);
}}
+ class="inline-flex items-center space-x-1 px-2 py-0.5 rounded text-[11px] font-medium bg-gray-200/60 hover:bg-gray-200 text-gray-700 transition-colors cursor-pointer border border-gray-300/60"
>
- <div class="p-1">
- {dataSets.map((ds) => (
- <button
- key={ds.id}
- type="button"
- role="menuitemradio"
- aria-checked={
- ds.id === activeDataSetId ||
- (!activeDataSetId && ds === dataSets[0])
- }
- onClick={() => {
- onSelectDataSet?.(ds.id);
- setIsDropdownOpen(false);
- }}
- class={`w-full text-left px-3 py-1.5 rounded-lg text-2xs font-semibold flex items-center justify-between transition-colors cursor-pointer ${
- ds.id === activeDataSetId ||
- (!activeDataSetId && ds === dataSets[0])
- ? "text-taler-brand font-extrabold bg-blue-50"
- : "text-gray-700 hover:bg-gray-100"
- }`}
- >
- <span>{ds.label}</span>
- {(ds.id === activeDataSetId ||
- (!activeDataSetId && ds === dataSets[0])) && (
- <span>✓</span>
- )}
- </button>
- ))}
+ <span>
+ {t`Data:`}{" "}
+ <strong class="font-bold text-gray-900">
+ {currentDataSetLabel}
+ </strong>
+ </span>
+ <span class="text-[9px] text-gray-500">▼</span>
+ </button>
+
+ {isDropdownOpen && (
+ <div
+ role="menu"
+ tabIndex={-1}
+ aria-label={t`Choose sample data`}
+ class="absolute right-0 mt-1 w-56 rounded-xl shadow-xl bg-white border border-gray-200 ring-1 ring-black/5 z-50 overflow-hidden divide-y divide-gray-100"
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ setIsDropdownOpen(false);
+ document.getElementById(switcherId)?.focus();
+ }
+ }}
+ >
+ <div class="p-1">
+ {dataSets.map((ds) => (
+ <button
+ key={ds.id}
+ type="button"
+ role="menuitemradio"
+ aria-checked={
+ ds.id === activeDataSetId ||
+ (!activeDataSetId && ds === dataSets[0])
+ }
+ onClick={() => {
+ onSelectDataSet?.(ds.id);
+ setIsDropdownOpen(false);
+ }}
+ class={`w-full text-left px-3 py-1.5 rounded-lg text-2xs font-semibold flex items-center justify-between transition-colors cursor-pointer ${
+ ds.id === activeDataSetId ||
+ (!activeDataSetId && ds === dataSets[0])
+ ? "text-taler-brand font-extrabold bg-blue-50"
+ : "text-gray-700 hover:bg-gray-100"
+ }`}
+ >
+ <span>{ds.label}</span>
+ {(ds.id === activeDataSetId ||
+ (!activeDataSetId && ds === dataSets[0])) && (
+ <span>✓</span>
+ )}
+ </button>
+ ))}
+ </div>
</div>
- </div>
- )}
- </div>
- )}
- </div>
+ )}
+ </div>
+ )}
+ </div>
- {/* Sandboxed Live Preact Component Container (with Optional Tiny Mock Sidebar) */}
- <div class="flex bg-gray-50/50">
- {(activeSidebarItem !== undefined || highlightSignOut) && (
- <MockSidebar
- activeItem={activeSidebarItem ?? ""}
- signOutActive={highlightSignOut}
- />
- )}
+ {/* Sandboxed Live Preact Component Container (with Optional Tiny Mock Sidebar) */}
+ <div class="flex bg-gray-50/50">
+ {(activeSidebarItem !== undefined || highlightSignOut) && (
+ <MockSidebar
+ activeItem={activeSidebarItem ?? ""}
+ signOutActive={highlightSignOut}
+ />
+ )}
- <div
- class={`flex-1 min-w-0 p-3 sm:p-4 ${maxHeightClass} overflow-y-auto preview-scrollbar transition-all ${
- isContentBlurred ? "opacity-35 blur-[1px] pointer-events-none" : ""
- }`}
- inert={isContentBlurred ? true : undefined}
- aria-hidden={isContentBlurred ? "true" : undefined}
- >
<div
- class={`filter opacity-95 transform-gpu ${
- // Blurred content is backdrop, not illustration: leave it out of
- // the tab order too. Re-enabling pointer events here would undo
- // the `pointer-events-none` the parent sets for that case.
- isContentBlurred ? "" : "pointer-events-auto"
+ class={`flex-1 min-w-0 p-3 sm:p-4 ${maxHeightClass} overflow-y-auto preview-scrollbar transition-all ${
+ isContentBlurred
+ ? "opacity-35 blur-[1px] pointer-events-none"
+ : ""
}`}
- style={{ zoom: scaleFactor, transformOrigin: "top center" }}
+ inert={isContentBlurred ? true : undefined}
+ aria-hidden={isContentBlurred ? "true" : undefined}
>
- <Router hook={inertLocationHook}>{children}</Router>
+ <div
+ class={`filter opacity-95 transform-gpu ${
+ // Blurred content is backdrop, not illustration: leave it out of
+ // the tab order too. Re-enabling pointer events here would undo
+ // the `pointer-events-none` the parent sets for that case.
+ isContentBlurred ? "" : "pointer-events-auto"
+ }`}
+ style={{ zoom: scaleFactor, transformOrigin: "top center" }}
+ >
+ <Router hook={inertLocationHook}>{children}</Router>
+ </div>
</div>
</div>
</div>
- </div>
+ </FocusPolicy>
);
}
diff --git a/packages/web-util/src/components/FocusScope.test.tsx b/packages/web-util/src/components/FocusScope.test.tsx
@@ -14,20 +14,22 @@
GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
+import { firstEditableField } from "./focus-dom.js";
+import { useDialogFocus, DialogFocusScope } from "./FocusScope.js";
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,
+ FocusPolicy,
useFocusScope,
useFocusTarget,
- DialogFocusScope,
- useDialogFocus,
} from "./FocusScope.js";
+
const window = new Window();
Object.assign(globalThis, {
window,
@@ -253,6 +255,44 @@ test("eligibility skips hidden, readonly and inherited-disabled fields", async (
);
await reset();
});
+test("previews suppress automatic focus, including portalled children", async () => {
+ function Preview() {
+ const target = useFocusTarget<HTMLInputElement>();
+ useFocusScope({ initialFocus: target.get });
+ return createPortal(<input ref={target.ref} id="preview" />, document.body);
+ }
+ await show(
+ <FocusPolicy automatic={false}>
+ <Preview />
+ </FocusPolicy>,
+ );
+ assert.notEqual(document.activeElement?.id, "preview");
+ await reset();
+});
+test("explicit requests work under automatic-focus suppression", async () => {
+ function Example() {
+ const target = useFocusTarget<HTMLInputElement>();
+ const scope = useFocusScope({ initialFocus: target.get });
+ return (
+ <>
+ <input ref={target.ref} id="explicit" />
+ <button id="request" onClick={() => scope.requestFocus(target.get)}>
+ Focus
+ </button>
+ </>
+ );
+ }
+ await show(
+ <FocusPolicy automatic={false}>
+ <Example />
+ </FocusPolicy>,
+ );
+ (document.getElementById("request") as HTMLElement).click();
+ await Promise.resolve();
+ assert.equal(document.activeElement?.id, "explicit");
+ await reset();
+});
+
test("closing a scope preserves focus deliberately moved elsewhere", async () => {
const outside = document.createElement("button");
document.body.append(outside);
@@ -270,6 +310,7 @@ test("closing a scope preserves focus deliberately moved elsewhere", async () =>
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);
@@ -294,6 +335,49 @@ test("step activation preserves the original opener for restoration", async () =
assert.ok(document.activeElement === opener);
opener.remove();
});
+
+test("deliberate interaction enables keyboard handling in portalled previews", async () => {
+ let escaped = false;
+ function Preview() {
+ const target = useFocusTarget<HTMLButtonElement>();
+ return (
+ <DialogFocusScope
+ root={target.get}
+ initialFocus={target.get}
+ onEscape={() => {
+ escaped = true;
+ }}
+ kind="menu"
+ >
+ {createPortal(
+ <button ref={target.ref} id="portal-action">
+ Action
+ </button>,
+ document.body,
+ )}
+ </DialogFocusScope>
+ );
+ }
+ await show(
+ <FocusPolicy automatic={false}>
+ <Preview />
+ </FocusPolicy>,
+ );
+ const target = document.getElementById("portal-action")!;
+ target.dispatchEvent(
+ new window.Event("pointerdown", { bubbles: true }) as unknown as Event,
+ );
+ target.focus();
+ target.dispatchEvent(
+ new window.KeyboardEvent("keydown", {
+ key: "Escape",
+ bubbles: true,
+ }) as unknown as KeyboardEvent,
+ );
+ assert.equal(escaped, true);
+ await reset();
+});
+
test("reopening resets restoration after an earlier outside-focus dismissal", async () => {
const opener = document.createElement("button"),
outside = document.createElement("button");
@@ -329,6 +413,7 @@ test("reopening resets restoration after an earlier outside-focus dismissal", as
outside.remove();
}
});
+
test("history restoration wins over form defaults and waits for readiness", async () => {
function Page({ ready }: { ready: boolean }) {
const page = useRef<HTMLDivElement>(null);
@@ -395,6 +480,7 @@ test("ordinary dialog renders do not rewrite background isolation", async () =>
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
@@ -15,7 +15,13 @@
*/
import { createContext, h, type ComponentChildren } from "preact";
-import { useCallback, useContext, useLayoutEffect, useRef } from "preact/hooks";
+import {
+ useCallback,
+ useContext,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "preact/hooks";
import { DialogStack, type DialogKind } from "./dialog-focus.js";
import { focusElement, initialDialogFocus } from "./focus-dom.js";
@@ -55,6 +61,8 @@ interface Scope {
options: FocusScopeOptions;
dialog?: DialogFocusOptions;
parent: Scope | null;
+ automatic: boolean;
+ activatePolicy?: (() => void) | null;
pending: boolean;
previous: HTMLElement | null;
order: number;
@@ -62,6 +70,10 @@ interface Scope {
restoreAllowed: boolean;
}
const ScopeContext = createContext<Scope | null>(null);
+const PolicyContext = createContext<{
+ automatic: boolean;
+ activate?: () => void;
+}>({ automatic: true });
const coordinators = new WeakMap<Document, Coordinator>();
const rootOf = (scope: Scope) =>
scope.options.root?.() ?? scope.options.initialFocus?.();
@@ -110,7 +122,7 @@ class Coordinator {
}
private refreshDialogs() {
const layers = childrenFirst(
- [...this.scopes].reverse().filter((s) => s.dialog),
+ [...this.scopes].reverse().filter((s) => s.dialog && s.automatic),
);
this.dialogs.update(
layers.map((scope) => {
@@ -142,7 +154,7 @@ class Coordinator {
remove(scope: Scope) {
this.scopes.delete(scope);
scope.pending = false;
- if (scope.dialog && scope.restoreAllowed)
+ if (scope.dialog && scope.automatic && scope.restoreAllowed)
this.restored.push({
order: scope.order,
scope,
@@ -155,7 +167,15 @@ class Coordinator {
scope.pending = false;
}
}
+ private activatePolicy(event: Event) {
+ for (const scope of this.scopes)
+ if (!scope.automatic && this.inside(scope, event.target as Node)) {
+ scope.activatePolicy?.();
+ scope.automatic = true;
+ }
+ }
private onPointer = (event: Event) => {
+ this.activatePolicy(event);
this.cancelPending();
};
private onFocus = (event: Event) => {
@@ -177,6 +197,7 @@ class Coordinator {
this.cancelPending();
};
private onKey = (event: KeyboardEvent) => {
+ this.activatePolicy(event);
if (event.key === "Tab") this.cancelPending();
this.refreshDialogs();
this.dialogs.key(event);
@@ -212,7 +233,9 @@ class Coordinator {
this.refreshDialogs();
const candidates = [...this.scopes]
.reverse()
- .filter((s) => s.pending && this.dialogs.allows(rootOf(s)));
+ .filter(
+ (s) => s.pending && s.automatic && this.dialogs.allows(rootOf(s)),
+ );
// Restore a history entry before applying the new page's default focus.
const pending = [
...childrenFirst(candidates.filter((s) => s.options.restoreTarget)),
@@ -286,11 +309,13 @@ export function useFocusTarget<T extends HTMLElement>() {
return { ref, get };
}
function useScope(options: FocusScopeOptions, dialog?: DialogFocusOptions) {
- const parent = useContext(ScopeContext);
+ const { automatic, activate: activatePolicy } = useContext(PolicyContext),
+ parent = useContext(ScopeContext);
const node = useRef<Scope>({
options,
dialog,
parent,
+ automatic,
pending: false,
previous: null,
order: 0,
@@ -301,6 +326,8 @@ function useScope(options: FocusScopeOptions, dialog?: DialogFocusOptions) {
options,
dialog,
parent,
+ automatic,
+ activatePolicy,
});
const owner = useRef<Coordinator>();
const activation = useRef(options.activationKey);
@@ -319,7 +346,7 @@ function useScope(options: FocusScopeOptions, dialog?: DialogFocusOptions) {
owner.current.add(node.current);
}
if (fresh || !Object.is(activation.current, options.activationKey)) {
- node.current.pending = true;
+ node.current.pending = automatic;
node.current.fallbackTaken = false;
activation.current = options.activationKey;
}
@@ -366,3 +393,36 @@ export function DialogFocusScope({
const { node } = useScope(options, options);
return <ScopeContext.Provider value={node}>{children}</ScopeContext.Provider>;
}
+
+/** Suppress autofocus in previews until the reader interacts with them. */
+export function FocusPolicy({
+ automatic,
+ children,
+}: {
+ automatic: boolean;
+ children: ComponentChildren;
+}) {
+ const { automatic: inheritedAutomatic, activate: activateParent } =
+ useContext(PolicyContext);
+ const [interacting, setInteracting] = useState(false);
+ const activate = useCallback(() => {
+ activateParent?.();
+ setInteracting(true);
+ }, [activateParent]);
+ return (
+ <PolicyContext.Provider
+ value={{
+ automatic: inheritedAutomatic && (automatic || interacting),
+ activate,
+ }}
+ >
+ <div
+ style="display: contents"
+ onPointerDownCapture={activate}
+ onKeyDownCapture={activate}
+ >
+ {children}
+ </div>
+ </PolicyContext.Provider>
+ );
+}
diff --git a/packages/web-util/src/components/index.ts b/packages/web-util/src/components/index.ts
@@ -15,15 +15,11 @@ export * from "./TalerQrCode.js";
export * from "./RenderAmount.js";
export * from "./Pagination.js";
export * from "./SafeMarkdown.js";
-export {
- isFocusEligible,
- firstEditableField,
- initialDialogFocus,
-} from "./focus-dom.js";
export {
FocusScope,
DialogFocusScope,
+ FocusPolicy,
useFocusScope,
useDialogFocus,
useFocusTarget,
@@ -34,3 +30,8 @@ export type {
FocusTarget,
FocusOptions,
} from "./FocusScope.js";
+export {
+ isFocusEligible,
+ firstEditableField,
+ initialDialogFocus,
+} from "./focus-dom.js";
diff --git a/packages/web-util/src/stories-utils.tsx b/packages/web-util/src/stories-utils.tsx
@@ -14,6 +14,7 @@
GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
+import { FocusPolicy } from "./components/FocusScope.js";
/**
*
* @author Sebastian Javier Marchano (sebasjm)
@@ -1121,11 +1122,13 @@ export function renderStories(
);
}
render(
- <Application
- examplesInGroups={examples}
- getWrapperForGroup={options.getWrapperForGroup ?? (() => Fragment)}
- langs={options.strings ?? { en: {} }}
- />,
+ <FocusPolicy automatic={false}>
+ <Application
+ examplesInGroups={examples}
+ getWrapperForGroup={options.getWrapperForGroup ?? (() => Fragment)}
+ langs={options.strings ?? { en: {} }}
+ />
+ </FocusPolicy>,
container,
);
} catch (e) {