taler-typescript-core

Wallet core logic and WebUIs for various components
Log | Files | Refs | Submodules | README | LICENSE

commit c1ee0c1022645200e605a3f36ab4910a3750c180
parent fdb0b892c5ea5e4869edcc8b83fb43a707be2126
Author: Florian Dold <dold@taler.net>
Date:   Fri, 13 Nov 2026 01:06:11 +0100

web-util: focus pages and form steps when their controls are ready

FocusScope queues one initial focus request when a page, form or step
opens. It waits for loading and cancels the request if the user moves
focus. useFocusTarget retries pending focus when a control mounts.

Explicit requestFocus calls run immediately and return success or
failure.

Issue: https://bugs.taler.net/n/12002
Issue: https://bugs.taler.net/n/12024
Assisted-by: LLM

Diffstat:
Mpackages/web-util/src/components/FocusScope.test.tsx | 101++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Apackages/web-util/src/components/FocusScope.tsx | 245+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/web-util/src/components/index.ts | 7+++++++
3 files changed, 352 insertions(+), 1 deletion(-)

diff --git a/packages/web-util/src/components/FocusScope.test.tsx b/packages/web-util/src/components/FocusScope.test.tsx @@ -16,9 +16,11 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { h, render } from "preact"; +import { h, Fragment, render } from "preact"; +import { useRef } from "preact/hooks"; import { Window } from "happy-dom"; import { firstEditableField } from "./focus-dom.js"; +import { FocusScope, useFocusScope, useFocusTarget } from "./FocusScope.js"; const window = new Window(); Object.assign(globalThis, { window, @@ -37,6 +39,46 @@ const reset = async () => { document.querySelectorAll("[data-probe]").forEach((e) => e.remove()); }; +test("activation focuses once, readiness does not reactivate a completed request", async () => { + function Form({ step, ready }: { step: string; ready: boolean }) { + const input = useFocusTarget<HTMLInputElement>(); + const second = useRef<HTMLInputElement>(null); + useFocusScope({ activationKey: step, ready, initialFocus: input.get }); + return ( + <> + <input ref={input.ref} id="first" /> + <input ref={second} id="second" /> + </> + ); + } + await show(<Form step="email" ready={false} />); + assert.notEqual(document.activeElement?.id, "first"); + await show(<Form step="email" ready />); + assert.equal(document.activeElement?.id, "first"); + (document.getElementById("second") as HTMLElement).focus(); + await show(<Form step="email" ready />); + assert.equal(document.activeElement?.id, "second"); + await show(<Form step="sms" ready />); + assert.equal(document.activeElement?.id, "first"); + await reset(); +}); +test("late requests are cancelled by deliberate focus movement", async () => { + function Form({ ready }: { ready: boolean }) { + const input = useFocusTarget<HTMLInputElement>(); + useFocusScope({ ready, initialFocus: input.get }); + return ( + <> + <input ref={input.ref} id="late" /> + <button id="other">Other</button> + </> + ); + } + await show(<Form ready={false} />); + (document.getElementById("other") as HTMLElement).focus(); + await show(<Form ready />); + assert.equal(document.activeElement?.id, "other"); + await reset(); +}); test("eligibility skips hidden, readonly and inherited-disabled fields", async () => { await show( <div id="fields"> @@ -56,3 +98,60 @@ test("eligibility skips hidden, readonly and inherited-disabled fields", async ( ); await reset(); }); +test("history restoration wins over form defaults and waits for readiness", async () => { + function Page({ ready }: { ready: boolean }) { + const page = useRef<HTMLDivElement>(null); + function Form() { + const field = useFocusTarget<HTMLInputElement>(); + useFocusScope({ initialFocus: field.get }); + return <input ref={field.ref} id="default-field" />; + } + return ( + <FocusScope + root={() => page.current} + ready={ready} + restoreTarget={() => + page.current?.querySelector<HTMLElement>("#saved-control") + } + > + <div ref={page}> + <button id="saved-control">Saved</button> + <Form /> + </div> + </FocusScope> + ); + } + await show(<Page ready={false} />); + assert.notEqual(document.activeElement?.id, "default-field"); + await show(<Page ready />); + assert.equal(document.activeElement?.id, "saved-control"); + await reset(); +}); +test("an unavailable explicit target is not deferred into a later interaction", async () => { + let result: boolean | undefined; + function Form({ ready }: { ready: boolean }) { + const field = useFocusTarget<HTMLInputElement>(); + const { requestFocus } = useFocusScope({}); + return ( + <> + <button + id="command" + onClick={() => { + result = requestFocus(field.get); + }} + > + Focus + </button> + {ready && <input ref={field.ref} id="future" />} + </> + ); + } + await show(<Form ready={false} />); + const command = document.getElementById("command")!; + command.focus(); + command.click(); + assert.equal(result, false); + await show(<Form ready />); + assert.equal(document.activeElement?.id, "command"); + await reset(); +}); diff --git a/packages/web-util/src/components/FocusScope.tsx b/packages/web-util/src/components/FocusScope.tsx @@ -0,0 +1,245 @@ +/* + This file is part of GNU Taler + (C) 2026 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +import { createContext, h, type ComponentChildren } from "preact"; +import { useCallback, useContext, useLayoutEffect, useRef } from "preact/hooks"; +import { focusElement } from "./focus-dom.js"; + +export type FocusTarget = () => HTMLElement | null | undefined; +export interface FocusOptions { + selectText?: boolean; + scroll?: boolean; +} +/** + * Focus once when a page, form or step opens. Wait for its target if needed; + * cancel the request if the user moves focus before the target is ready. + */ +export interface FocusScopeOptions extends FocusOptions { + root?: FocusTarget; + active?: boolean; + /** Change this when a mounted component starts a new step. */ + activationKey?: string | number | boolean; + /** Pending focus waits here while controls are loading or disabled. */ + ready?: boolean | (() => boolean); + initialFocus?: FocusTarget; + fallbackFocus?: FocusTarget; + /** Browser-history restoration takes precedence over initial page/form focus. */ + restoreTarget?: FocusTarget; +} + +interface Scope { + options: FocusScopeOptions; + parent: Scope | null; + pending: boolean; + fallbackTaken: boolean; +} +const ScopeContext = createContext<Scope | null>(null); +const coordinators = new WeakMap<Document, Coordinator>(); +const rootOf = (scope: Scope) => + scope.options.root?.() ?? scope.options.initialFocus?.(); +function owns(parent: Scope, child: Scope): boolean { + for (let scope = child.parent; scope; scope = scope.parent) + if (scope === parent) return true; + const a = rootOf(parent), + b = rootOf(child); + return !!a && !!b && a !== b && a.contains(b); +} +/** Try a child before its parent, then the most recently opened sibling. */ +function childrenFirst(scopes: Scope[]): Scope[] { + const result: Scope[] = []; + while (scopes.length) { + const leaf = scopes.findIndex( + (scope) => !scopes.some((child) => child !== scope && owns(scope, child)), + ); + result.push(scopes.splice(Math.max(leaf, 0), 1)[0]); + } + return result; +} + +class Coordinator { + scopes = new Set<Scope>(); + private queued = false; + private moving = false; + constructor(readonly doc: Document) { + doc.addEventListener("focusin", this.onFocus, true); + doc.addEventListener("pointerdown", this.cancelPending, true); + doc.addEventListener("keydown", this.onKey, true); + } + add(scope: Scope) { + this.scopes.add(scope); + } + remove(scope: Scope) { + this.scopes.delete(scope); + scope.pending = false; + this.schedule(); + } + private cancelPending = () => { + for (const scope of this.scopes) scope.pending = false; + }; + private onFocus = () => { + if (!this.moving) this.cancelPending(); + }; + private onKey = (event: KeyboardEvent) => { + if (event.key === "Tab") this.cancelPending(); + }; + private move( + target: HTMLElement | null | undefined, + options: FocusOptions = {}, + ) { + this.moving = true; + try { + return focusElement(target, options); + } finally { + this.moving = false; + } + } + request( + target: HTMLElement | null | undefined, + options: FocusOptions, + ): boolean { + if (!this.move(target, options)) return false; + this.cancelPending(); + return true; + } + schedule() { + if (this.queued) return; + this.queued = true; + queueMicrotask(() => this.flush()); + } + private flush() { + this.queued = false; + const candidates = [...this.scopes] + .reverse() + .filter((scope) => scope.pending); + // 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), + ), + ]; + let claimed = false; + for (const scope of pending) { + if (claimed) { + scope.pending = false; + continue; + } + const ready = + typeof scope.options.ready === "function" + ? scope.options.ready() + : scope.options.ready !== false; + const target = ready + ? (scope.options.restoreTarget?.() ?? scope.options.initialFocus?.()) + : null; + if (this.move(target, scope.options)) { + scope.pending = false; + claimed = true; + for (const parent of this.scopes) + if (owns(parent, scope)) parent.pending = false; + } else if ( + !scope.fallbackTaken && + this.move(scope.options.fallbackFocus?.()) + ) + scope.fallbackTaken = true; + if (!ready && scope.options.restoreTarget) break; + } + if (!this.scopes.size) { + this.doc.removeEventListener("focusin", this.onFocus, true); + this.doc.removeEventListener("pointerdown", this.cancelPending, true); + this.doc.removeEventListener("keydown", this.onKey, true); + coordinators.delete(this.doc); + } + } +} +function coordinator(doc: Document) { + let owner = coordinators.get(doc); + if (!owner) coordinators.set(doc, (owner = new Coordinator(doc))); + return owner; +} +/** A callback ref that retries pending focus on attach and detach. */ +export function useFocusTarget<T extends HTMLElement>() { + const current = useRef<T | null>(null); + const ref = useCallback((element: T | null) => { + const doc = element?.ownerDocument ?? current.current?.ownerDocument; + current.current = element; + if (doc) coordinators.get(doc)?.schedule(); + }, []); + const get = useCallback(() => current.current, []); + return { ref, get }; +} + +function useScope(options: FocusScopeOptions) { + const parent = useContext(ScopeContext); + const node = useRef<Scope>({ + options, + parent, + pending: false, + fallbackTaken: false, + }); + Object.assign(node.current, { options, parent }); + const owner = useRef<Coordinator>(); + const activation = useRef(options.activationKey); + useLayoutEffect(() => { + if (typeof document === "undefined") return; + if (options.active === false) { + owner.current?.remove(node.current); + owner.current = undefined; + return; + } + const fresh = !owner.current; + if (fresh) { + owner.current = coordinator( + rootOf(node.current)?.ownerDocument ?? document, + ); + owner.current.add(node.current); + } + if (fresh || !Object.is(activation.current, options.activationKey)) { + node.current.pending = true; + node.current.fallbackTaken = false; + activation.current = options.activationKey; + } + owner.current!.schedule(); + }); + useLayoutEffect(() => () => owner.current?.remove(node.current), []); + const requestFocus = useCallback( + (target: FocusTarget, focusOptions: FocusOptions = {}) => { + return ( + node.current.options.active !== false && + (owner.current?.request(target(), focusOptions) ?? false) + ); + }, + [], + ); + return { node: node.current, requestFocus }; +} +/** + * Use in a component that owns the fields. requestFocus() is immediate and + * returns false if its target cannot be focused; it never queues a later move. + */ +export function useFocusScope(options: FocusScopeOptions) { + const { requestFocus } = useScope(options); + return { requestFocus }; +} +/** Give child components the same focus owner, including through portals. */ +export function FocusScope({ + children, + ...options +}: FocusScopeOptions & { children: ComponentChildren }) { + const { node } = useScope(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 @@ -20,3 +20,10 @@ export { firstEditableField, initialDialogFocus, } from "./focus-dom.js"; + +export { FocusScope, useFocusScope, useFocusTarget } from "./FocusScope.js"; +export type { + FocusScopeOptions, + FocusTarget, + FocusOptions, +} from "./FocusScope.js";