commit 77059d755ede815e5d14a5f0c77d8e487023b864
parent 88ab3b1df4d96da97cccecc935c5f25047db414f
Author: Florian Dold <dold@taler.net>
Date: Fri, 13 Nov 2026 01:06:16 +0100
wallet web UI: focus active forms, menus and confirmations
Focus amount and account fields when their forms are ready. Restore menu
and dialog openers, and leave focus alone during background updates.
Confirmations start on an editable field, including acknowledgement
checkboxes and selects, or Cancel when there is no field to fill in.
Issue: https://bugs.taler.net/n/12024
Issue: https://bugs.taler.net/n/12054
Assisted-by: LLM
Diffstat:
11 files changed, 204 insertions(+), 66 deletions(-)
diff --git a/packages/wallet-webui/src/screens/BankAccountsScreen.tsx b/packages/wallet-webui/src/screens/BankAccountsScreen.tsx
@@ -1,3 +1,4 @@
+import { useFocusScope } from "@gnu-taler/web-util/browser";
import { useEffect, useMemo, useRef, useState } from "preact/hooks";
import { Button } from "../ui/Button.js";
import { Card } from "../ui/Card.js";
@@ -114,6 +115,18 @@ export function BankAccountsScreen(props: {
setPaytoUri(props.editing?.paytoUri ?? "");
setMethod(props.editing ? "advanced" : (guidedMethods[0] ?? "advanced"));
}, [guidedMethods, props.editing]);
+ // Opening the form or starting an edit moves focus to its first text field,
+ // which also brings the form into view below the account list. An edit
+ // shows the payto URI field only once the reset above has switched to it.
+ const form = useRef<HTMLFormElement>(null);
+ useFocusScope({
+ active: formOpen,
+ activationKey: props.editing?.id,
+ ready: !props.editing || method === "advanced",
+ root: () => form.current,
+ initialFocus: () => form.current?.querySelector<HTMLInputElement>("input"),
+ scroll: true,
+ });
const wireType = props.wireTypes?.find(
(entry) => entry.paymentTargetType === method,
);
@@ -272,7 +285,9 @@ export function BankAccountsScreen(props: {
type="button"
aria-expanded={formOpen}
aria-controls="bank-account-form"
- onClick={() => setFormOpen((open) => !open)}
+ onClick={() => {
+ setFormOpen((open) => !open);
+ }}
class="flex min-h-12 w-full items-center gap-3 px-4 py-3 text-left text-primary transition hover:bg-secondaryContainer focus:outline-none focus:ring-2 focus:ring-inset focus:ring-primary"
>
<span
@@ -291,6 +306,7 @@ export function BankAccountsScreen(props: {
)}
{(formOpen || props.editing) && (
<form
+ ref={form}
id="bank-account-form"
class={`form-field-stack space-y-5 p-5 sm:p-6 ${props.editing ? "" : "border-t border-outlineVariant"}`}
onSubmit={(event) => {
diff --git a/packages/wallet-webui/src/screens/DepositScreen.tsx b/packages/wallet-webui/src/screens/DepositScreen.tsx
@@ -1,4 +1,5 @@
-import { useEffect, useMemo, useState } from "preact/hooks";
+import { useFocusScope } from "@gnu-taler/web-util/browser";
+import { useEffect, useMemo, useRef, useState } from "preact/hooks";
import { Button } from "../ui/Button.js";
import { Card } from "../ui/Card.js";
import { ErrorCard } from "../ui/ErrorCard.js";
@@ -114,6 +115,15 @@ export function DepositScreen(props: {
const paytoUri = selected?.paytoUri ?? props.initialPaytoUri ?? "";
const destination = selected?.destination ?? props.initialDestination;
const normalizedAmount = positiveAmountValue(currency, amount);
+ const amountInput = useRef<HTMLInputElement>(null);
+ // Once the accounts have loaded (and again when returning from review), the
+ // amount is the first thing to enter. Without a destination the user has to
+ // add a bank account first, so focus is left alone then.
+ const amountFirst = !props.loading && !props.review && Boolean(destination);
+ useFocusScope({
+ active: amountFirst,
+ initialFocus: () => amountInput.current,
+ });
return (
<FocusedPage class="space-y-6">
<div class="flex items-center gap-4">
@@ -187,6 +197,7 @@ export function DepositScreen(props: {
</select>
</label>
<MoneyAmountInput
+ inputRef={amountInput}
label={i18n.str`Amount`}
value={amount}
currency={currency}
diff --git a/packages/wallet-webui/src/screens/DonauSettingsScreen.tsx b/packages/wallet-webui/src/screens/DonauSettingsScreen.tsx
@@ -1,4 +1,5 @@
-import { useEffect, useState } from "preact/hooks";
+import { useFocusScope } from "@gnu-taler/web-util/browser";
+import { useEffect, useRef, useState } from "preact/hooks";
import { Button } from "../ui/Button.js";
import { Card } from "../ui/Card.js";
import { ErrorCard } from "../ui/ErrorCard.js";
@@ -47,6 +48,22 @@ export function DonauSettingsScreen(props: {
props.initialDonauBaseUrl,
]);
const valid = donauBaseUrl.trim() !== "" && taxPayerId.trim() !== "";
+ const urlInput = useRef<HTMLInputElement>(null);
+ const taxPayerInput = useRef<HTMLInputElement>(null);
+ const settingUp =
+ !props.loading &&
+ (props.configuration === undefined ||
+ props.initialDonauBaseUrl !== undefined);
+ const urlKnown = Boolean(
+ props.initialDonauBaseUrl ?? props.configuration?.donauBaseUrl,
+ );
+ // While nothing is configured, or when a payment sent the user here to set
+ // up a suggested authority, the form is the purpose of the page: focus the
+ // first field that still needs to be entered.
+ useFocusScope({
+ active: settingUp,
+ initialFocus: () => (urlKnown ? taxPayerInput.current : urlInput.current),
+ });
return (
<div class="space-y-5">
<div>
@@ -83,6 +100,7 @@ export function DonauSettingsScreen(props: {
i18n.str`Donation authority URL`
}</label>
<input
+ ref={urlInput}
id="donau-url"
type="url"
required
@@ -98,6 +116,7 @@ export function DonauSettingsScreen(props: {
i18n.str`Taxpayer identifier`
}</label>
<input
+ ref={taxPayerInput}
id="tax-payer-id"
type="text"
required
diff --git a/packages/wallet-webui/src/screens/PaymentTemplateScreen.tsx b/packages/wallet-webui/src/screens/PaymentTemplateScreen.tsx
@@ -1,4 +1,5 @@
-import { useEffect, useState } from "preact/hooks";
+import { useFocusScope } from "@gnu-taler/web-util/browser";
+import { useEffect, useRef, useState } from "preact/hooks";
import { Button } from "../ui/Button.js";
import { Card } from "../ui/Card.js";
import { ErrorCard } from "../ui/ErrorCard.js";
@@ -37,6 +38,20 @@ export function PaymentTemplateScreen(props: {
}, [props.initialAmount, props.initialCurrency, props.initialSummary]);
const normalizedAmount = positiveAmountValue(currency, amount);
const valid = Boolean(normalizedAmount) && Boolean(summary.trim());
+ const amountInput = useRef<HTMLInputElement>(null);
+ const summaryInput = useRef<HTMLInputElement>(null);
+ const formShown = !props.loading && !props.error;
+ // Focus the first field the merchant left for the payer to fill in; the
+ // form only appears once the template has loaded.
+ useFocusScope({
+ active: formShown,
+ initialFocus: () =>
+ props.amountEditable
+ ? amountInput.current
+ : props.summaryEditable
+ ? summaryInput.current
+ : null,
+ });
return (
<div class="mx-auto w-full max-w-2xl space-y-6">
<div class="flex items-center gap-4">
@@ -67,7 +82,7 @@ export function PaymentTemplateScreen(props: {
</Card>
)}
{props.error && <ErrorCard error={props.error} />}
- {!props.loading && !props.error && (
+ {formShown && (
<form
class="space-y-5"
onSubmit={(event) => {
@@ -102,6 +117,7 @@ export function PaymentTemplateScreen(props: {
<span class="mb-1 block text-sm font-medium">{i18n.str`Amount`}</span>
<div class="flex rounded-xl border border-outline bg-surface focus-within:ring-2 focus-within:ring-primary">
<input
+ ref={amountInput}
inputMode="decimal"
disabled={!props.amountEditable}
value={amount}
@@ -124,6 +140,7 @@ export function PaymentTemplateScreen(props: {
}
</span>
<input
+ ref={summaryInput}
disabled={!props.summaryEditable}
value={summary}
onInput={(event) => setSummary(event.currentTarget.value)}
diff --git a/packages/wallet-webui/src/screens/PeerCreateScreen.tsx b/packages/wallet-webui/src/screens/PeerCreateScreen.tsx
@@ -1,3 +1,4 @@
+import { useFocusScope } from "@gnu-taler/web-util/browser";
import { useEffect, useMemo, useRef, useState } from "preact/hooks";
import type { ScopeInfo, TalerProtocolTimestamp } from "@gnu-taler/taler-util";
import { Button } from "../ui/Button.js";
@@ -189,6 +190,14 @@ export function PeerCreateScreen(props: {
: { kind: "days", days: Number(expirationMode) as 1 | 7 | 30 };
const validExpiration =
expiration.kind !== "custom" || Boolean(expiration.value);
+ const amountInput = useRef<HTMLInputElement>(null);
+ const formVisible = !props.review && !props.loading && !scopeUnavailable;
+ // The form appears only after the scopes have loaded, and again when
+ // returning from the review step; the amount is what the user enters first.
+ useFocusScope({
+ active: formVisible,
+ initialFocus: () => amountInput.current,
+ });
useEffect(() => {
const sequence = ++previewSequence.current;
const resolveDefaultExpiration = props.onResolveDefaultExpiration;
@@ -291,7 +300,7 @@ export function PeerCreateScreen(props: {
</Card>
)}
{props.error && <ErrorCard error={props.error} />}
- {!props.review && !props.loading && !scopeUnavailable && (
+ {formVisible && (
<form
class="space-y-6"
onSubmit={(event) => {
@@ -336,6 +345,7 @@ export function PeerCreateScreen(props: {
</select>
</label>
<MoneyAmountInput
+ inputRef={amountInput}
// Translators: %1$s is an ISO-style currency code.
label={i18n.str`Amount (${currency})`}
value={amount}
diff --git a/packages/wallet-webui/src/screens/UriInputScreen.tsx b/packages/wallet-webui/src/screens/UriInputScreen.tsx
@@ -1,3 +1,5 @@
+import { useFocusScope } from "@gnu-taler/web-util/browser";
+import { useRef } from "preact/hooks";
import { Button } from "../ui/Button.js";
import { Card } from "../ui/Card.js";
import { i18n } from "../i18n/runtime.js";
@@ -13,6 +15,9 @@ export function UriInputScreen(props: {
onScan: () => void;
onBack: () => void;
}) {
+ const input = useRef<HTMLInputElement>(null);
+ // The link is the only thing to enter on this page.
+ useFocusScope({ initialFocus: () => input.current });
return (
<FocusedPage class="space-y-6">
<div class="flex items-center gap-4">
@@ -43,6 +48,7 @@ export function UriInputScreen(props: {
class="text-sm font-semibold"
>{i18n.str`Wallet link`}</label>
<input
+ ref={input}
id="taler-uri"
type="text"
value={props.value}
diff --git a/packages/wallet-webui/src/screens/WithdrawalScreen.tsx b/packages/wallet-webui/src/screens/WithdrawalScreen.tsx
@@ -1,3 +1,4 @@
+import { useFocusScope } from "@gnu-taler/web-util/browser";
import { useEffect, useMemo, useRef, useState } from "preact/hooks";
import { Button } from "../ui/Button.js";
import { Card } from "../ui/Card.js";
@@ -60,9 +61,15 @@ export function WithdrawalScreen(props: {
useEffect(() => {
if (!amount && props.initialAmount) setAmount(props.initialAmount);
}, [amount, props.initialAmount]);
- useEffect(() => {
- if (props.amountEditable !== false) amountInput.current?.focus();
- }, [props.amountEditable]);
+ // The amount field is only rendered once the exchanges have loaded, which
+ // is usually after the first render. It sits at the top of the page, so
+ // focusing it need not scroll; scrolling would also make the story
+ // catalogue, which shows many screens at once, jump to this one.
+ const amountShown = provider !== undefined && !props.cashAcceptor;
+ useFocusScope({
+ active: amountShown && props.amountEditable !== false,
+ initialFocus: () => amountInput.current,
+ });
const enteredAmount = positiveAmountValue(provider?.currency ?? "", amount);
const normalizedAmount = positiveAmountValue(
provider?.currency ?? "",
diff --git a/packages/wallet-webui/src/ui/ConfirmationDialog.tsx b/packages/wallet-webui/src/ui/ConfirmationDialog.tsx
@@ -1,16 +1,10 @@
+import { useDialogFocus } from "@gnu-taler/web-util/browser";
+import { isFocusEligible } from "@gnu-taler/web-util/browser";
import type { ComponentChildren } from "preact";
import { useEffect, useRef } from "preact/hooks";
import { Button } from "./Button.js";
import { Card } from "./Card.js";
-function focusableElements(container: HTMLElement): HTMLElement[] {
- return Array.from(
- container.querySelectorAll<HTMLElement>(
- 'button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [href], [tabindex]:not([tabindex="-1"])',
- ),
- );
-}
-
/** Shared confirmation surface for every destructive or sensitive wallet action. */
export function ConfirmationDialog(props: {
title: string;
@@ -25,49 +19,28 @@ export function ConfirmationDialog(props: {
onConfirm: () => void;
}) {
const dialogRef = useRef<HTMLDivElement>(null);
- const previousFocus = useRef<HTMLElement | null>(null);
- const onCancel = useRef(props.onCancel);
- const working = useRef(props.working);
- onCancel.current = props.onCancel;
- working.current = props.working;
+ const actionsRef = useRef<HTMLDivElement>(null);
+
+ useDialogFocus({
+ root: () => dialogRef.current,
+ initialFocus: () =>
+ Array.from(
+ dialogRef.current?.querySelectorAll<HTMLElement>(
+ 'input:not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="image"]), select, textarea',
+ ) ?? [],
+ ).find(
+ (field) => !field.hasAttribute("readonly") && isFocusEligible(field),
+ ) ?? actionsRef.current?.querySelector<HTMLElement>("button"),
+ fallbackFocus: () => dialogRef.current,
+ onEscape: () => {
+ if (!props.working) props.onCancel();
+ },
+ });
useEffect(() => {
const previousOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";
- previousFocus.current =
- document.activeElement instanceof HTMLElement
- ? document.activeElement
- : null;
- const dialog = dialogRef.current;
- const first = dialog ? focusableElements(dialog)[0] : undefined;
- first?.focus();
- const onKeyDown = (event: KeyboardEvent) => {
- if (event.key === "Escape" && !working.current) {
- event.preventDefault();
- onCancel.current();
- return;
- }
- if (event.key !== "Tab" || !dialog) return;
- const focusable = focusableElements(dialog);
- if (focusable.length === 0) {
- event.preventDefault();
- dialog.focus();
- return;
- }
- const firstElement = focusable[0];
- const lastElement = focusable[focusable.length - 1];
- if (event.shiftKey && document.activeElement === firstElement) {
- event.preventDefault();
- lastElement.focus();
- } else if (!event.shiftKey && document.activeElement === lastElement) {
- event.preventDefault();
- firstElement.focus();
- }
- };
- document.addEventListener("keydown", onKeyDown);
return () => {
- document.removeEventListener("keydown", onKeyDown);
document.body.style.overflow = previousOverflow;
- previousFocus.current?.focus();
};
}, []);
@@ -98,7 +71,7 @@ export function ConfirmationDialog(props: {
{props.description}
</div>
{props.children}
- <div class="mt-6 flex flex-wrap justify-end gap-3">
+ <div ref={actionsRef} class="mt-6 flex flex-wrap justify-end gap-3">
<Button
tone="secondary"
onClick={props.onCancel}
diff --git a/packages/wallet-webui/src/ui/DemoBanner.tsx b/packages/wallet-webui/src/ui/DemoBanner.tsx
@@ -1,3 +1,5 @@
+import { useDialogFocus } from "@gnu-taler/web-util/browser";
+
import { useEffect, useRef, useState } from "preact/hooks";
import type { DemoScenario, DemoScenarioId } from "../routes/context.js";
import { ConfirmationDialog } from "./ConfirmationDialog.js";
@@ -12,19 +14,28 @@ export function DemoBanner(props: {
const [open, setOpen] = useState(false);
const [confirmReset, setConfirmReset] = useState(false);
const menuRef = useRef<HTMLDivElement>(null);
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ useDialogFocus({
+ active: open,
+ root: () => menuRef.current,
+ initialFocus: () =>
+ menuRef.current?.querySelector<HTMLElement>('[role="menuitem"]'),
+ returnFocus: () => triggerRef.current,
+ onEscape: () => setOpen(false),
+ kind: "menu",
+ });
useEffect(() => {
if (!open) return;
- const close = (event: KeyboardEvent) => {
- if (event.key === "Escape") setOpen(false);
- };
+ // Move into the menu when it opens and back to its button when it closes
+ // from the keyboard or a choice, so focus is not lost with the items.
+
const outside = (event: PointerEvent) => {
if (!menuRef.current?.contains(event.target as Node)) setOpen(false);
};
- document.addEventListener("keydown", close);
+
document.addEventListener("pointerdown", outside);
return () => {
- document.removeEventListener("keydown", close);
document.removeEventListener("pointerdown", outside);
};
}, [open]);
@@ -56,6 +67,7 @@ export function DemoBanner(props: {
)}
<div class="relative" ref={menuRef}>
<button
+ ref={triggerRef}
type="button"
aria-expanded={open}
aria-haspopup="menu"
@@ -79,6 +91,7 @@ export function DemoBanner(props: {
role="menuitem"
onClick={() => {
setOpen(false);
+ triggerRef.current?.focus();
props.onScenario(scenario.id);
}}
class="block w-full rounded-lg px-3 py-2 text-left font-medium hover:bg-secondaryContainer focus:outline-none focus:ring-2 focus:ring-primary"
diff --git a/packages/wallet-webui/src/ui/OverflowMenu.tsx b/packages/wallet-webui/src/ui/OverflowMenu.tsx
@@ -1,3 +1,5 @@
+import { useDialogFocus } from "@gnu-taler/web-util/browser";
+
import { useEffect, useRef, useState } from "preact/hooks";
export interface OverflowMenuItem {
@@ -12,19 +14,30 @@ export function OverflowMenu(props: {
}) {
const [open, setOpen] = useState(false);
const container = useRef<HTMLDivElement>(null);
+ const trigger = useRef<HTMLButtonElement>(null);
+ const menu = useRef<HTMLDivElement>(null);
+ useDialogFocus({
+ active: open,
+ root: () => menu.current,
+ initialFocus: () =>
+ menu.current?.querySelector<HTMLElement>('[role="menuitem"]'),
+ returnFocus: () => trigger.current,
+ onEscape: () => setOpen(false),
+ kind: "menu",
+ });
useEffect(() => {
if (!open) return;
- const closeOnEscape = (event: KeyboardEvent) => {
- if (event.key === "Escape") setOpen(false);
- };
+ // A menu takes focus when it opens and hands it back to its button when
+ // it closes from the keyboard or a choice, so focus is never lost with
+ // the removed items.
+
const closeOutside = (event: PointerEvent) => {
if (!container.current?.contains(event.target as Node)) setOpen(false);
};
- document.addEventListener("keydown", closeOnEscape);
+
document.addEventListener("pointerdown", closeOutside);
return () => {
- document.removeEventListener("keydown", closeOnEscape);
document.removeEventListener("pointerdown", closeOutside);
};
}, [open]);
@@ -32,6 +45,7 @@ export function OverflowMenu(props: {
return (
<div class="relative shrink-0" ref={container}>
<button
+ ref={trigger}
type="button"
aria-label={props.label}
aria-haspopup="menu"
@@ -43,6 +57,7 @@ export function OverflowMenu(props: {
</button>
{open && (
<div
+ ref={menu}
role="menu"
aria-label={props.label}
class="absolute right-0 z-10 mt-1 min-w-48 rounded-xl border border-outlineVariant bg-surface p-1 shadow-lg"
@@ -54,6 +69,7 @@ export function OverflowMenu(props: {
role="menuitem"
onClick={() => {
setOpen(false);
+ trigger.current?.focus();
item.onSelect();
}}
class="min-h-11 w-full rounded-lg px-3 py-2 text-left text-sm font-semibold text-primary hover:bg-primaryContainer focus:outline-none focus:ring-2 focus:ring-primary"
diff --git a/packages/wallet-webui/test/screens.test.tsx b/packages/wallet-webui/test/screens.test.tsx
@@ -32,6 +32,7 @@ import { DonauSettingsScreen } from "../src/screens/DonauSettingsScreen.js";
import { DonauStatementsScreen } from "../src/screens/DonauStatementsScreen.js";
import { ShoppingScreen } from "../src/screens/ShoppingScreen.js";
import { Shell } from "../src/ui/Shell.js";
+import { ConfirmationDialog } from "../src/ui/ConfirmationDialog.js";
import { RequestProgressPanel } from "../src/ui/RequestProgress.js";
import { MAX_QR_CONTENT_BYTES, QrFrame } from "../src/ui/QrFrame.js";
import { StorybookScreen } from "../src/screens/StorybookScreen.js";
@@ -77,6 +78,55 @@ function installDom() {
return window;
}
+test("confirmations focus an eligible field before Cancel, skipping body actions", async () => {
+ const window = installDom();
+ const { render, cleanup } = await import("@testing-library/preact");
+ const cases = [
+ <input key="checkbox" id="confirmation-field" type="checkbox" />,
+ <input key="text" id="confirmation-field" type="text" />,
+ <select key="select" id="confirmation-field">
+ <option>One</option>
+ </select>,
+ <textarea key="textarea" id="confirmation-field" />,
+ null,
+ ];
+ try {
+ for (const field of cases) {
+ const view = render(
+ <ConfirmationDialog
+ title="Confirm"
+ description="Review this action"
+ cancelLabel="Cancel"
+ confirmLabel="Confirm"
+ onCancel={() => {}}
+ onConfirm={() => {}}
+ >
+ <button>Extra action</button>
+ <input readOnly value="Read only" />
+ <input type="hidden" />
+ <input disabled />
+ <fieldset disabled>
+ <input />
+ </fieldset>
+ {field}
+ </ConfirmationDialog>,
+ );
+ await Promise.resolve();
+ const expected = field
+ ? view.container.querySelector("#confirmation-field")
+ : view.getByRole("button", { name: "Cancel" });
+ assert.ok(
+ window.document.activeElement === expected,
+ "focus the field, or Cancel when there is no field",
+ );
+ cleanup();
+ }
+ } finally {
+ cleanup();
+ await window.happyDOM.abort();
+ }
+});
+
test("terms language selection preserves every ordered choice", async () => {
const window = installDom();
const { render, cleanup } = await import("@testing-library/preact");