commit 88ab3b1df4d96da97cccecc935c5f25047db414f parent 10db8ad6d183a3adc89525e6a261606adf63c8f9 Author: Florian Dold <dold@taler.net> Date: Fri, 13 Nov 2026 01:06:16 +0100 bank web UI: focus forms and authentication dialogs Focus the first field that still needs input, including linked transfers and password changes. Use dialog focus handling for MFA and native withdrawal confirmations. Choose the withdrawal field after showModal(), so loading account details does not determine when the field receives focus. Issue: https://bugs.taler.net/n/12024 Issue: https://bugs.taler.net/n/12034 Issue: https://bugs.taler.net/n/12042 Assisted-by: LLM Diffstat:
13 files changed, 221 insertions(+), 14 deletions(-)
diff --git a/packages/libeufin-bank-webui/src/Routing.tsx b/packages/libeufin-bank-webui/src/Routing.tsx @@ -401,6 +401,7 @@ function PrivatePageRouting({ case "accountDelete": { return ( <RemoveAccount + focus account={location.values.account} onUpdateSuccess={() => navigateTo(privatePages.adminAccounts.url({}))} routeCancel={privatePages.adminAccounts} @@ -420,6 +421,7 @@ function PrivatePageRouting({ case "myAccountDelete": { return ( <RemoveAccount + focus account={username} onUpdateSuccess={() => navigateTo(privatePages.home.url({}))} routeCancel={privatePages.home} diff --git a/packages/libeufin-bank-webui/src/pages/NewConversionRateClass.tsx b/packages/libeufin-bank-webui/src/pages/NewConversionRateClass.tsx @@ -97,7 +97,7 @@ export function NewConversionRateClass({ </i18n.Translate> </p> - <ConversionRateClassForm onChange={setSubmitData}> + <ConversionRateClassForm focus onChange={setSubmitData}> <div class="border-t border-onBackground/10 bg-background/60 px-5 py-4 sm:px-8"> <OperationError class="mb-4" /> <div class="flex items-center justify-between gap-x-6"> diff --git a/packages/libeufin-bank-webui/src/pages/OperationState/views.test.tsx b/packages/libeufin-bank-webui/src/pages/OperationState/views.test.tsx @@ -0,0 +1,136 @@ +/* + 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 { afterEach, beforeEach, test } from "node:test"; +import { Window } from "happy-dom"; +import { type ComponentChildren, h, render, options } from "preact"; +import { Amounts, Paytos, setupI18n } from "@gnu-taler/taler-util"; +import { + BankApiProviderTesting, + useBankCoreApiContext, +} from "@gnu-taler/web-util/browser"; +import { BankStoryContext } from "../../stories-context.js"; +import { NeedConfirmationView } from "./views.js"; + +let dom: Window; +let root: HTMLDivElement; +const previousFrame = options.requestAnimationFrame; +beforeEach(() => { + dom = new Window({ url: "http://bank.example/" }); + for (const [key, value] of Object.entries({ + window: dom, + document: dom.document, + navigator: dom.navigator, + Node: dom.Node, + HTMLElement: dom.HTMLElement, + Element: dom.Element, + Event: dom.Event, + })) + Object.defineProperty(globalThis, key, { + configurable: true, + writable: true, + value, + }); + setupI18n("en", {}); + options.requestAnimationFrame = (callback) => setTimeout(callback, 0); + root = dom.document.createElement("div") as unknown as HTMLDivElement; + document.body.append(root); + const style = dom.document.createElement("style"); + style.textContent = "dialog:not([open]) { display: none; }"; + dom.document.head.append(style); + // Native dialogs initially focus the heading; the application must then + // choose the input without waiting for an account-details response. + dom.HTMLDialogElement.prototype.showModal = function () { + this.open = true; + this.querySelector("h2")!.focus(); + }; + dom.HTMLDialogElement.prototype.close = function () { + this.open = false; + }; +}); +afterEach(async () => { + render(null, root); + root.remove(); + options.requestAnimationFrame = previousFrame; + await dom.happyDOM.abort(); +}); + +function PendingAccount({ children }: { children: ComponentChildren }) { + const original = useBankCoreApiContext(); + return ( + <BankApiProviderTesting + value={{ + ...original, + lib: { + ...original.lib, + bank: Object.assign(Object.create(original.lib.bank), { + getAccount: () => new Promise(() => {}), + }), + }, + }} + > + {children} + </BankApiProviderTesting> + ); +} + +for (const variant of ["password", "cash", "fixed"] as const) { + test(`withdrawal confirmation focuses ${variant} without account details`, async () => { + const exchange = Paytos.fromString( + "payto://iban/DE02120300000000202051?receiver-name=Exchange", + ); + assert.equal(exchange.tag, "ok"); + if (exchange.tag !== "ok") throw Error("Invalid test account"); + render( + <BankStoryContext + loggedIn={variant !== "password"} + config={{ currency: "EUR", wire_type: "IBAN" }} + > + <PendingAccount> + <NeedConfirmationView + status="need-confirmation" + error={undefined} + account="alice" + operationId="focus-test" + progressMode="amount-first" + cashAcceptor={variant === "cash"} + onAbort={() => {}} + details={{ + account: exchange.value, + reserve: "reserve-pub", + username: "alice", + amount: + variant === "cash" + ? { mode: "bank-selected" } + : { mode: "fixed", value: Amounts.parseOrThrow("EUR:5") }, + }} + /> + </PendingAccount> + </BankStoryContext>, + root, + ); + await new Promise((resolve) => setTimeout(resolve, 50)); + const expected = + variant === "password" + ? "#password" + : variant === "cash" + ? "#amount" + : "#withdrawal-confirmation-title"; + assert.equal(dom.document.activeElement?.id, expected.slice(1)); + assert.equal(root.querySelector("dialog")?.open, true); + }); +} diff --git a/packages/libeufin-bank-webui/src/pages/OperationState/views.tsx b/packages/libeufin-bank-webui/src/pages/OperationState/views.tsx @@ -14,6 +14,8 @@ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> */ +import { useDialogFocus } from "@gnu-taler/web-util/browser"; +import { firstEditableField } from "@gnu-taler/web-util/browser"; import { AmountJson, AmountString, @@ -157,6 +159,12 @@ export function NeedConfirmationView({ setConfirmingAbort(false); }, [initialAmount, operationId]); + const { requestFocus } = useDialogFocus({ + active: !mfa.pending, + root: () => dialogRef.current, + fallbackFocus: () => titleRef.current, + kind: "native", + }); useEffect(() => { const dialog = dialogRef.current; if (!dialog) return; @@ -175,7 +183,8 @@ export function NeedConfirmationView({ return; } if (!dialog.open) dialog.showModal(); - titleRef.current?.focus(); + // The fields cannot receive focus until the native dialog is open. + requestFocus(() => firstEditableField(dialog) ?? titleRef.current); }; openDialog(); return () => { @@ -184,7 +193,7 @@ export function NeedConfirmationView({ dialog.removeEventListener("cancel", preventCancel); if (dialog.open) dialog.close(); }; - }, [mfa.pending]); + }, [mfa.pending, requestFocus]); useEffect(() => { if (confirmingAbort) { diff --git a/packages/libeufin-bank-webui/src/pages/PaytoWireTransferForm.tsx b/packages/libeufin-bank-webui/src/pages/PaytoWireTransferForm.tsx @@ -14,6 +14,7 @@ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> */ +import { useFocusTarget, useFocusScope } from "@gnu-taler/web-util/browser"; import { AmountJson, AmountString, @@ -75,6 +76,9 @@ export function PaytoWireTransferForm({ limit, debtLimit, }: Props): VNode { + const scopeTarget = useFocusTarget<HTMLElement>(); + useFocusScope({ active: !!focus, initialFocus: scopeTarget.get }); + const [inputType, setInputType] = useState<"form" | "payto">("form"); const isRawPayto = inputType === "payto"; @@ -426,7 +430,7 @@ export function PaytoWireTransferForm({ onChange={setAccount} value={account} placeholder={i18n.str`username`} - focus={focus} + focus={focus && !sendingToFixedAccount} disabled={sendingToFixedAccount} /> ); @@ -441,7 +445,7 @@ export function PaytoWireTransferForm({ error={errorsWire?.account} onChange={(value) => setAccount(value.toUpperCase())} value={account} - focus={focus} + focus={focus && !sendingToFixedAccount} disabled={sendingToFixedAccount} /> ); @@ -460,6 +464,13 @@ export function PaytoWireTransferForm({ </label> <div class="mt-2"> <textarea + // The recipient is locked when it came with the link, so + // the reference is the first thing left to fill in. + ref={ + focus && sendingToFixedAccount + ? scopeTarget.ref + : undefined + } rows={2} class="block w-full rounded-md border-0 py-1.5 text-onBackground shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6" name="subject" @@ -515,7 +526,7 @@ export function PaytoWireTransferForm({ </p> <div class="mt-2"> <textarea - ref={focus ? doAutoFocus : undefined} + ref={focus ? scopeTarget.ref : undefined} name="address" id="address" rows={5} @@ -633,10 +644,13 @@ export function doAutoFocus(element: HTMLElement | null) { if (element) { setTimeout(() => { element.focus({ preventScroll: true }); + // Scroll only when the element is out of view: the forms are near the + // top of their own pages, and centering them would push the page + // heading off screen. element.scrollIntoView({ behavior: "smooth", - block: "center", - inline: "center", + block: "nearest", + inline: "nearest", }); }, 100); } @@ -828,6 +842,9 @@ export function TextField({ value, error, }: PaytoFieldProps): VNode { + const scopeTarget = useFocusTarget<HTMLElement>(); + useFocusScope({ active: !!focus, initialFocus: scopeTarget.get }); + return ( <div class="sm:col-span-5"> <label @@ -840,7 +857,7 @@ export function TextField({ <div class="mt-2"> <Wrapper withIcon={rightIcons !== undefined}> <input - ref={focus ? doAutoFocus : undefined} + ref={focus ? scopeTarget.ref : undefined} type="text" class="block w-full disabled:bg-gray-200 rounded-md border-0 py-1.5 text-onBackground shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6" name={id} diff --git a/packages/libeufin-bank-webui/src/pages/SolveMFA.tsx b/packages/libeufin-bank-webui/src/pages/SolveMFA.tsx @@ -1,3 +1,6 @@ +import { useDialogFocus } from "@gnu-taler/web-util/browser"; +import { initialDialogFocus } from "@gnu-taler/web-util/browser"; +import { useFocusTarget, useFocusScope } from "@gnu-taler/web-util/browser"; import { AbsoluteTime, assertUnreachable, @@ -27,7 +30,6 @@ import { useCallback, useEffect, useRef, useState } from "preact/hooks"; import { useBankChallengeHandlerContext } from "../context/challenge.js"; import { AuthAlert } from "./AuthForm.js"; import { OperationError } from "../components/OperationError.js"; -import { doAutoFocus } from "./PaytoWireTransferForm.js"; export interface Props { onCompleted: AsyncAction<[challenges: string[]]>; @@ -53,6 +55,9 @@ function SolveChallenge({ username: string; onTerminal: (manual?: boolean) => Promise<boolean>; }): VNode { + const scopeTarget = useFocusTarget<HTMLElement>(); + useFocusScope({ initialFocus: scopeTarget.get }); + const { i18n } = useTranslationContext(); const [tanCode, setTanCode] = useState<string>(); const [submitted, setSubmitted] = useState(false); @@ -205,7 +210,7 @@ function SolveChallenge({ </label> <div class="mt-2"> <input - ref={doAutoFocus} + ref={scopeTarget.ref} type="text" name="authentication-code" id={`tan-${challenge.challenge_id}`} @@ -301,9 +306,17 @@ export function SolveChallengeDialog({ }): VNode { const mfa = useBankChallengeHandlerContext(); + const mfaDialog = useRef<HTMLDialogElement>(null); + useDialogFocus({ + active: mfa.pending !== undefined, + root: () => mfaDialog.current, + onEscape: () => mfa.cancel(), + initialFocus: () => initialDialogFocus(mfaDialog.current), + }); return ( <Fragment> <dialog + ref={mfaDialog} id="dialog" tabIndex={-1} // open @@ -478,6 +491,10 @@ function SolveMFAChallenges({ const hasSolvedEnough = currentChallenge.combi_and ? currentSolved.length === currentChallenge.challenges.length : currentSolved.length > 0; + // The dialog opens while keyboard focus is still on the button that + // started the operation, behind the overlay, where Enter would submit it + // again. Move focus to the first challenge that still has to be done. + let focusPending = !!focus; return ( <Fragment> @@ -543,6 +560,8 @@ function SolveMFAChallenges({ solved.indexOf(challenge.challenge_id) !== -1 || (currentChallenge.combi_and && nextAndChallenge?.challenge_id !== challenge.challenge_id); + const focusHere = focusPending && !noNeedToComplete; + if (focusHere) focusPending = false; return ( <div @@ -576,15 +595,21 @@ function SolveMFAChallenges({ name="cancel" class="text-sm font-semibold leading-6 text-onBackground" disabled={noNeedToComplete} + focus={focusHere && alreadySent} onClick={() => selectChallenge.run(challenge)} > <i18n.Translate>I have a code</i18n.Translate> </AsyncButton> + {/* Not tied to alreadySent: focusing the disabled + button does nothing, while a ref that changes + when the retransmission wait ends would steal + focus later. */} <AsyncButton submit name="send again" class="disabled:opacity-50 disabled:cursor-default cursor-pointer rounded-md bg-primary px-3 py-2 text-sm font-semibold text-onPrimary shadow-sm hover:bg-primaryHover hover:text-white focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary" + focus={focusHere} disabled={alreadySent || noNeedToComplete} onClick={() => sendMessage.run(challenge)} > diff --git a/packages/libeufin-bank-webui/src/pages/WalletWithdrawal.tsx b/packages/libeufin-bank-webui/src/pages/WalletWithdrawal.tsx @@ -83,6 +83,7 @@ export function WalletWithdrawal({ <i18n.Translate>Back to overview</i18n.Translate> </a> <WalletWithdrawForm + focus limit={limit} debtLimit={debtLimit} onOperationCreated={onOperationCreated} diff --git a/packages/libeufin-bank-webui/src/pages/WireTransfer.tsx b/packages/libeufin-bank-webui/src/pages/WireTransfer.tsx @@ -109,6 +109,7 @@ export function WireTransfer({ </i18n.Translate> </p> <PaytoWireTransferForm + focus withAccount={toAccount} withAmount={withAmount} withSubject={withSubject} diff --git a/packages/libeufin-bank-webui/src/pages/account/UpdateAccountPassword.tsx b/packages/libeufin-bank-webui/src/pages/account/UpdateAccountPassword.tsx @@ -13,6 +13,8 @@ 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 { useFocusTarget, useFocusScope } from "@gnu-taler/web-util/browser"; import { AccessToken, assertUnreachable, @@ -35,6 +37,7 @@ import { useBankChallengeHandlerContext } from "../../context/challenge.js"; import { useSessionState } from "../../hooks/session.js"; import { OperationError } from "../../components/OperationError.js"; import { undefinedIfEmpty } from "../../utils.js"; + import { ProfileNavigation } from "../ProfileNavigation.js"; export function UpdateAccountPassword({ @@ -54,6 +57,9 @@ export function UpdateAccountPassword({ onUpdateSuccess: () => void; account: string; }): VNode { + const scopeTarget = useFocusTarget<HTMLElement>(); + useFocusScope({ initialFocus: scopeTarget.get }); + const { i18n } = useTranslationContext(); const { state: credentials } = useSessionState(); const token = @@ -202,6 +208,7 @@ export function UpdateAccountPassword({ </label> <div class="mt-2"> <input + ref={scopeTarget.ref} type="password" class="block w-full rounded-md border-0 py-1.5 text-onBackground shadow-sm ring-1 ring-inset ring-gray-300 data-[error=true]:ring-red-500 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6" name="current" @@ -236,6 +243,9 @@ export function UpdateAccountPassword({ </label> <div class="mt-2"> <input + // An administrator resetting another account's password + // is not asked for the current one. + ref={accountIsTheCurrentUser ? undefined : scopeTarget.ref} type="password" class="block w-full rounded-md border-0 py-1.5 text-onBackground shadow-sm ring-1 ring-inset ring-gray-300 data-[error=true]:ring-red-500 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6" name="password" diff --git a/packages/libeufin-bank-webui/src/pages/admin/ConversionRateClassForm.tsx b/packages/libeufin-bank-webui/src/pages/admin/ConversionRateClassForm.tsx @@ -249,7 +249,6 @@ export function ConversionRateClassForm( </label> <div class="mt-2"> <input - ref={focus ? doAutoFocus : undefined} type="text" class="block w-full disabled:bg-gray-100 rounded-md border-0 py-1.5 text-onBackground shadow-sm ring-1 ring-inset ring-gray-300 data-[error=true]:ring-red-500 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6" name="class-description" diff --git a/packages/libeufin-bank-webui/src/pages/admin/CreateNewAccount.tsx b/packages/libeufin-bank-webui/src/pages/admin/CreateNewAccount.tsx @@ -144,6 +144,7 @@ export function CreateNewAccount({ </p> <div class="mt-6"> <AccountForm + focus template={undefined} purpose="create" onChange={(a) => { diff --git a/packages/libeufin-bank-webui/src/pages/regional/CashoutCreatePage.tsx b/packages/libeufin-bank-webui/src/pages/regional/CashoutCreatePage.tsx @@ -57,6 +57,7 @@ export function CashoutCreatePage({ </a> </div> <CreateCashout + focus account={account} routeClose={routeClose} onCashout={onCashout} diff --git a/packages/libeufin-bank-webui/src/pages/regional/CreateCashout.tsx b/packages/libeufin-bank-webui/src/pages/regional/CreateCashout.tsx @@ -13,6 +13,8 @@ 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 { useFocusTarget, useFocusScope } from "@gnu-taler/web-util/browser"; import { AmountJson, Amounts, @@ -63,7 +65,7 @@ import { import { LoggedIn, useSessionState } from "../../hooks/session.js"; import { TanChannel, undefinedIfEmpty } from "../../utils.js"; import { LoginForm } from "../LoginForm.js"; -import { InputAmount, doAutoFocus } from "../PaytoWireTransferForm.js"; +import { InputAmount } from "../PaytoWireTransferForm.js"; import { RetryableError } from "../../components/RetryableError.js"; import { OperationError } from "../../components/OperationError.js"; @@ -246,6 +248,9 @@ function CreateCashoutInternal({ session: LoggedIn; accountData: TalerCorebankApi.AccountData; }): VNode { + const scopeTarget = useFocusTarget<HTMLElement>(); + useFocusScope({ active: !!focus, initialFocus: scopeTarget.get }); + const { estimateByCredit: calculateFromCredit, estimateByDebit: calculateFromDebit, @@ -625,7 +630,7 @@ function CreateCashoutInternal({ </label> <div class="mt-2"> <input - ref={focus ? doAutoFocus : undefined} + ref={focus ? scopeTarget.ref : undefined} type="text" class="block w-full rounded-md disabled:bg-gray-200 border-0 py-1.5 text-onBackground shadow-sm ring-1 ring-inset ring-gray-300 data-[error=true]:ring-red-500 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6" name="subject"