taler-typescript-core

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

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

web-util: add helpers for initial focus and modal keyboard handling

Find controls that can receive focus, skipping hidden, disabled and
inert elements. Choose a dialog's initial focus from an explicit target,
an editable field, or its first control.

Handle Escape on the active dialog. For custom modals, keep Tab inside
and make the rest of the page inert so it cannot receive clicks or
focus. Restore the previous inert state on close. Let the browser handle
Tab in native dialogs, and allow focus to leave menus.

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

Diffstat:
Apackages/web-util/src/components/FocusScope.test.tsx | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Apackages/web-util/src/components/dialog-focus.ts | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Apackages/web-util/src/components/focus-dom.ts | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/web-util/src/components/index.ts | 5+++++
4 files changed, 260 insertions(+), 0 deletions(-)

diff --git a/packages/web-util/src/components/FocusScope.test.tsx b/packages/web-util/src/components/FocusScope.test.tsx @@ -0,0 +1,58 @@ +/* + 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 assert from "node:assert/strict"; +import { test } from "node:test"; +import { h, render } from "preact"; +import { Window } from "happy-dom"; +import { firstEditableField } from "./focus-dom.js"; +const window = new Window(); +Object.assign(globalThis, { + window, + document: window.document, + HTMLElement: window.HTMLElement, + Node: window.Node, +}); +const root = document.createElement("div"); +document.body.append(root); +const show = async (content: any) => { + render(content, root); + await Promise.resolve(); +}; +const reset = async () => { + await show(null); + document.querySelectorAll("[data-probe]").forEach((e) => e.remove()); +}; + +test("eligibility skips hidden, readonly and inherited-disabled fields", async () => { + await show( + <div id="fields"> + <fieldset disabled> + <input /> + </fieldset> + <input readOnly /> + <div hidden> + <input /> + </div> + <input id="eligible" /> + </div>, + ); + assert.equal( + firstEditableField(document.getElementById("fields"))?.id, + "eligible", + ); + await reset(); +}); diff --git a/packages/web-util/src/components/dialog-focus.ts b/packages/web-util/src/components/dialog-focus.ts @@ -0,0 +1,110 @@ +/* + 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 { focusableElements } from "./focus-dom.js"; + +export type DialogKind = "modal" | "native" | "menu"; +export interface DialogLayer { + kind: DialogKind; + roots: HTMLElement[]; + fallback: () => HTMLElement | null | undefined; + onEscape?: () => void; +} +const contains = (layer: DialogLayer, target: Node | null) => + !!target && layer.roots.some((root) => root.contains(target)); + +/** Handle Escape, Tab containment and background inertness for open dialogs. */ +export class DialogStack { + private layers: DialogLayer[] = []; + private roots: HTMLElement[] = []; + private isolated = new Map<HTMLElement, boolean>(); + constructor( + private doc: Document, + private move: (target: HTMLElement | null | undefined) => boolean, + ) {} + allows(target: HTMLElement | null | undefined) { + const modal = this.layers.find((layer) => layer.kind !== "menu"); + return !modal || contains(modal, target ?? null); + } + redirect(target: Node | null): boolean { + const modal = this.layers.find((layer) => layer.kind !== "menu"); + if (!modal || contains(modal, target)) return false; + this.move(modal.fallback()); + return true; + } + key(event: KeyboardEvent) { + const layer = this.layers.find( + (layer) => + layer.kind !== "menu" || + (layer.onEscape && contains(layer, this.doc.activeElement)), + ); + if (!layer) return; + if (event.key === "Escape" && layer.onEscape) { + event.preventDefault(); + event.stopImmediatePropagation(); + layer.onEscape(); + } else if (event.key === "Tab" && layer.kind === "modal") { + const elements = [...new Set(layer.roots.flatMap(focusableElements))]; + const index = elements.indexOf(this.doc.activeElement as HTMLElement); + if ( + !elements.length || + index < 0 || + (event.shiftKey ? index === 0 : index === elements.length - 1) + ) { + event.preventDefault(); + this.move( + (event.shiftKey ? elements.at(-1) : elements[0]) ?? layer.fallback(), + ); + } + } + } + update(layers: DialogLayer[]) { + this.layers = layers; + const modal = layers.find((layer) => layer.kind !== "menu"); + const roots = modal?.kind === "modal" ? modal.roots : []; + // Update inertness only when the active dialog or its portal roots change. + if ( + roots.length === this.roots.length && + roots.every((root) => this.roots.includes(root)) + ) + return; + this.roots = roots; + const outside = new Set<HTMLElement>(); + const visit = (parent: HTMLElement) => { + for (const child of Array.from(parent.children)) { + if ( + !(child instanceof this.doc.defaultView!.HTMLElement) || + roots.includes(child) + ) + continue; + if (roots.some((root) => child.contains(root))) visit(child); + else outside.add(child); + } + }; + if (roots.length) visit(this.doc.body); + for (const [element, inert] of this.isolated) { + if (!outside.has(element)) { + element.inert = inert; + this.isolated.delete(element); + } + } + for (const element of outside) + if (!this.isolated.has(element)) { + this.isolated.set(element, element.inert); + element.inert = true; + } + } +} diff --git a/packages/web-util/src/components/focus-dom.ts b/packages/web-util/src/components/focus-dom.ts @@ -0,0 +1,87 @@ +/* + 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/> + */ + +/** Ignore detached, hidden, inert and disabled elements. */ +export function isFocusEligible( + element: HTMLElement | null | undefined, +): element is HTMLElement { + if ( + !element?.isConnected || + element.matches(":disabled") || + element.closest( + '[inert], [hidden], [aria-hidden="true"], fieldset[disabled]', + ) + ) + return false; + for ( + let current: HTMLElement | null = element; + current; + current = current.parentElement + ) { + const style = current.ownerDocument.defaultView?.getComputedStyle(current); + if (style?.display === "none" || style?.visibility === "hidden") + return false; + } + return element.getAttribute("type") !== "hidden"; +} +export function focusableElements(root: HTMLElement): HTMLElement[] { + return Array.from( + root.querySelectorAll<HTMLElement>( + 'button, input, select, textarea, a[href], [tabindex], [contenteditable="true"]', + ), + ).filter((e) => e.tabIndex >= 0 && isFocusEligible(e)); +} +/** Optionally prefer an empty text field over a prefilled one. */ +export function firstEditableField( + root: ParentNode | null | undefined, + preferEmpty = false, +): HTMLElement | undefined { + const fields = Array.from( + root?.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>( + 'input:not([type="checkbox"]):not([type="radio"]):not([type="hidden"]):not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="file"]), textarea', + ) ?? [], + ).filter((e) => !e.readOnly && isFocusEligible(e)); + return (preferEmpty ? fields.find((e) => !e.value) : undefined) ?? fields[0]; +} +/** Prefer an explicit target, then a text field, then the first control. */ +export function initialDialogFocus( + root: HTMLElement | null | undefined, +): HTMLElement | undefined { + if (!root) return undefined; + return ( + Array.from( + root.querySelectorAll<HTMLElement>("[autofocus], [data-focus-initial]"), + ).find(isFocusEligible) ?? + firstEditableField(root) ?? + focusableElements(root)[0] ?? + root + ); +} + +export function focusElement( + target: HTMLElement | null | undefined, + options: { selectText?: boolean; scroll?: boolean } = {}, +): boolean { + if (!isFocusEligible(target)) return false; + if (target.tabIndex < 0 && !target.hasAttribute("tabindex")) + target.tabIndex = -1; + target.focus({ preventScroll: true }); + if (target.ownerDocument.activeElement !== target) return false; + if (options.selectText && "select" in target) + (target as HTMLInputElement).select(); + if (options.scroll) target.scrollIntoView?.({ block: "nearest" }); + return true; +} diff --git a/packages/web-util/src/components/index.ts b/packages/web-util/src/components/index.ts @@ -15,3 +15,8 @@ export * from "./TalerQrCode.js"; export * from "./RenderAmount.js"; export * from "./Pagination.js"; export * from "./SafeMarkdown.js"; +export { + isFocusEligible, + firstEditableField, + initialDialogFocus, +} from "./focus-dom.js";