taler-typescript-core

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

commit bee154f5ddb07d01986a5ddf830a5105fbf0ae1f
parent d8eedea1529d070bd176c70e365ac963615a5d56
Author: Florian Dold <dold@taler.net>
Date:   Fri, 13 Nov 2026 01:06:16 +0100

web-util: honour form focus on one editable control

FormUI chooses one field across all visible sections. Each field exposes
its primary control to the form; standalone fields keep their focus
flag.

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

Diffstat:
Mpackages/web-util/src/components/Button.tsx | 6++++--
Mpackages/web-util/src/components/FocusScope.tsx | 17+++++++++++++++++
Mpackages/web-util/src/components/utils.ts | 25++++++++++++++++++++++++-
Mpackages/web-util/src/forms/fields/InputArray.tsx | 2++
Mpackages/web-util/src/forms/fields/InputChoiceHorizontal.tsx | 18++++++++++++++++--
Mpackages/web-util/src/forms/fields/InputChoiceStacked.tsx | 15+++++++++++++--
Mpackages/web-util/src/forms/fields/InputDrilldown.tsx | 1+
Mpackages/web-util/src/forms/fields/InputDuration.tsx | 2++
Mpackages/web-util/src/forms/fields/InputFile.tsx | 6+++++-
Mpackages/web-util/src/forms/fields/InputLine.tsx | 6+++---
Mpackages/web-util/src/forms/fields/InputSelectMultiple.tsx | 2++
Mpackages/web-util/src/forms/fields/InputSelectOne.tsx | 2++
Mpackages/web-util/src/forms/fields/InputToggle.tsx | 6+++++-
Mpackages/web-util/src/forms/forms-ui.test.tsx | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/web-util/src/forms/forms-ui.tsx | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
15 files changed, 229 insertions(+), 16 deletions(-)

diff --git a/packages/web-util/src/components/Button.tsx b/packages/web-util/src/components/Button.tsx @@ -10,7 +10,7 @@ import { h, JSX, VNode } from "preact"; import { CSSProperties, useEffect, useRef, useState } from "preact/compat"; import { useTranslationContext } from "../context/translation.js"; -import { doAutoFocus } from "./utils.js"; +import { useFocusScope, useFocusTarget } from "./FocusScope.js"; export type ButtonProps = Omit< JSX.ButtonHTMLAttributes<HTMLButtonElement>, @@ -23,10 +23,12 @@ export type ButtonProps = Omit< /** A plain button. Notifications and asynchronous state belong to callers. */ export function Button({ focus, submit, type, ...rest }: ButtonProps): VNode { + const target = useFocusTarget<HTMLButtonElement>(); + useFocusScope({ active: !!focus, initialFocus: target.get }); return ( <button {...rest} - ref={focus ? doAutoFocus : undefined} + ref={target.ref} type={type ?? (submit ? "submit" : "button")} /> ); diff --git a/packages/web-util/src/components/FocusScope.tsx b/packages/web-util/src/components/FocusScope.tsx @@ -426,3 +426,20 @@ export function FocusPolicy({ </PolicyContext.Provider> ); } + +/** Form fields mark their primary control; the form picks one target. */ +export function useFieldAutoFocus( + enabled: boolean | undefined, + getElement: FocusTarget, +): void { + const parent = useContext(ScopeContext); + useFocusScope({ active: !!enabled && !parent, initialFocus: getElement }); + useLayoutEffect(() => { + if (!enabled || !parent) return; + const element = getElement(); + if (!element) return; + element.setAttribute("data-focus-initial", ""); + coordinators.get(element.ownerDocument)?.schedule(); + return () => element.removeAttribute("data-focus-initial"); + }); +} diff --git a/packages/web-util/src/components/utils.ts b/packages/web-util/src/components/utils.ts @@ -1,3 +1,4 @@ +import { useFieldAutoFocus } from "./FocusScope.js"; import { createElement, VNode } from "preact"; import { MutableRef, useEffect, useRef } from "preact/hooks"; @@ -39,7 +40,9 @@ export function compose<SType extends { status: string }, PType>( export function recursive<PType>( hook: (p: PType) => RecursiveState<VNode<any>>, ): (p: PType) => VNode<any> { - function withHook(stateHook: () => RecursiveState<VNode<any>>): () => VNode<any> { + function withHook( + stateHook: () => RecursiveState<VNode<any>>, + ): () => VNode<any> { function ComposedComponent(): VNode<any> { const state = stateHook(); @@ -107,7 +110,27 @@ export function doAutoFocus<T extends HTMLElement>( ) { if (element) { setTimeout(() => { + // The view may have moved on (step change, dialog closed) meanwhile. + if (!element.isConnected) return; element.focus({ preventScroll: true }); }, 100); } } + +/** + * Focus an element once, when the component mounts with `focus` set. + * + * Use this instead of `ref={doAutoFocus}` when the element's ref callback is + * created inline: a new ref callback on every render would focus the element + * again on each render and pull the cursor back while the user is typing + * elsewhere. + * + * @param focus whether the component should start with focus + * @param element returns the element to focus, read after mounting + */ +export function useAutoFocus( + focus: boolean | undefined, + element: () => HTMLElement | null | undefined, +): void { + useFieldAutoFocus(focus, element); +} diff --git a/packages/web-util/src/forms/fields/InputArray.tsx b/packages/web-util/src/forms/fields/InputArray.tsx @@ -6,6 +6,7 @@ import { RecursivePartial, useForm, } from "../../hooks/useForm.js"; +import { useAutoFocus } from "../../components/utils.js"; import { useTranslationContext } from "../../context/translation.js"; import { RenderAllFieldsByUiConfig } from "../forms-ui.js"; import { resolveFieldHandler, UIFormProps } from "../FormProvider.js"; @@ -146,6 +147,7 @@ export function InputArray( const [editor, setEditor] = useState<Editor | undefined>(); const returnFocusRef = useRef<HTMLButtonElement | null>(null); const addButtonRef = useRef<HTMLButtonElement | null>(null); + useAutoFocus(props.focus, () => addButtonRef.current); const generatedId = useId(); const fieldId = `array-${generatedId}`; const labelId = `${fieldId}-label`; diff --git a/packages/web-util/src/forms/fields/InputChoiceHorizontal.tsx b/packages/web-util/src/forms/fields/InputChoiceHorizontal.tsx @@ -1,5 +1,7 @@ import { TranslatedString } from "@gnu-taler/taler-util"; import { Fragment, VNode, h } from "preact"; +import { useRef } from "preact/hooks"; +import { useAutoFocus } from "../../components/utils.js"; import { resolveFieldHandler, UIFormProps } from "../FormProvider.js"; import { LabelWithTooltipMaybeRequired } from "./InputLine.js"; @@ -15,6 +17,15 @@ export function InputChoiceHorizontal<ChoiceVal>( ): VNode { const { hidden, choices, label, tooltip, help, required, converter } = props; const { value, onChange } = resolveFieldHandler(props.handler, props.name); + const fieldset = useRef<HTMLFieldSetElement>(null); + useAutoFocus( + props.focus, + () => + fieldset.current?.querySelector<HTMLElement>( + 'button[aria-pressed="true"]:not([disabled])', + ) ?? + fieldset.current?.querySelector<HTMLElement>("button:not([disabled])"), + ); if (hidden) { return <Fragment />; } @@ -28,15 +39,17 @@ export function InputChoiceHorizontal<ChoiceVal>( tooltip={tooltip} name={props.name as string} /> - <fieldset class="mt-2 min-w-0 max-w-full overflow-x-auto"> + <fieldset ref={fieldset} class="mt-2 min-w-0 max-w-full overflow-x-auto"> <div class="isolate inline-flex rounded-md shadow-sm"> {choices.map((choice, idx) => { const convertedValue = converter?.fromStringUI(choice.value as any); + const isSelected = + convertedValue !== undefined && convertedValue === value; const isFirst = idx === 0; const isLast = idx === choices.length - 1; let clazz = "relative inline-flex items-center px-3 py-2 text-sm font-semibold text-gray-900 ring-1 ring-inset ring-gray-300 focus:z-10"; - if (convertedValue !== undefined && convertedValue === value) { + if (isSelected) { clazz += " text-white bg-indigo-600 hover:bg-indigo-500 ring-2 ring-indigo-600 hover:ring-indigo-500"; } else { @@ -54,6 +67,7 @@ export function InputChoiceHorizontal<ChoiceVal>( <button type="button" key={idx} + aria-pressed={isSelected} disabled={props.disabled} class={clazz} onClick={(e) => { diff --git a/packages/web-util/src/forms/fields/InputChoiceStacked.tsx b/packages/web-util/src/forms/fields/InputChoiceStacked.tsx @@ -1,6 +1,7 @@ import { TranslatedString } from "@gnu-taler/taler-util"; import { Fragment, VNode, h } from "preact"; -import { useEffect, useId } from "preact/hooks"; +import { useEffect, useId, useRef } from "preact/hooks"; +import { useAutoFocus } from "../../components/utils.js"; import { resolveFieldHandler, UIFormProps } from "../FormProvider.js"; import { LabelWithTooltipMaybeRequired } from "./InputLine.js"; @@ -40,6 +41,16 @@ export function InputChoiceStacked<Choices>( if (value !== undefined) onChange(undefined); }, [choices, onChange, value]); + const fieldset = useRef<HTMLFieldSetElement>(null); + useAutoFocus( + props.focus, + () => + fieldset.current?.querySelector<HTMLElement>( + "input:checked:not([disabled])", + ) ?? + fieldset.current?.querySelector<HTMLElement>("input:not([disabled])"), + ); + if (hidden) { return <Fragment />; } @@ -53,7 +64,7 @@ export function InputChoiceStacked<Choices>( tooltip={tooltip} name={props.name as string} /> - <fieldset class="mt-2"> + <fieldset ref={fieldset} class="mt-2"> <div class="space-y-4"> {choices.map((choice, idx) => { const optionId = `${groupName}-${idx}`; diff --git a/packages/web-util/src/forms/fields/InputDrilldown.tsx b/packages/web-util/src/forms/fields/InputDrilldown.tsx @@ -32,6 +32,7 @@ export function InputDrilldown( <InputSelectOne name={props.name} label={localI18n.str`${props.label} (Classification level ${lvl + 1})`} + focus={props.focus && lvl === 0} required={required} disabled={props.disabled} handler={{ diff --git a/packages/web-util/src/forms/fields/InputDuration.tsx b/packages/web-util/src/forms/fields/InputDuration.tsx @@ -1,6 +1,7 @@ import { Duration } from "@gnu-taler/taler-util"; import { Fragment, VNode, h } from "preact"; import { useEffect, useRef } from "preact/hooks"; +import { useAutoFocus } from "../../components/utils.js"; import { useTranslationContext } from "../../context/translation.js"; import { resolveFieldHandler, UIFormProps } from "../FormProvider.js"; import { InputWrapper } from "./InputLine.js"; @@ -35,6 +36,7 @@ export function InputDuration(props: UIFormProps<Duration>): VNode { const daysRef = useRef<HTMLInputElement>(null); const monthsRef = useRef<HTMLInputElement>(null); const yearsRef = useRef<HTMLInputElement>(null); + useAutoFocus(props.focus, () => yearsRef.current); // useEffect(() => { // onChange( diff --git a/packages/web-util/src/forms/fields/InputFile.tsx b/packages/web-util/src/forms/fields/InputFile.tsx @@ -8,7 +8,8 @@ */ import { Fragment, VNode, h } from "preact"; -import { useState } from "preact/hooks"; +import { useRef, useState } from "preact/hooks"; +import { useAutoFocus } from "../../components/utils.js"; import { useTranslationContext } from "../../context/translation.js"; import { resolveFieldHandler, UIFormProps } from "../FormProvider.js"; import { FileFieldData } from "../forms-types.js"; @@ -25,6 +26,8 @@ export function InputFile( props.name, ); const [fileError, setFileError] = useState<string>(); + const fileInput = useRef<HTMLInputElement>(null); + useAutoFocus(props.focus, () => fileInput.current); if (hidden) return <Fragment />; @@ -100,6 +103,7 @@ export function InputFile( > <span>{i18n.str`Upload a file`}</span> <input + ref={fileInput} id={String(props.name)} type="file" class="sr-only" diff --git a/packages/web-util/src/forms/fields/InputLine.tsx b/packages/web-util/src/forms/fields/InputLine.tsx @@ -1,7 +1,7 @@ import { TranslatedString } from "@gnu-taler/taler-util"; import { ComponentChildren, Fragment, VNode, h } from "preact"; import { useEffect, useId, useRef } from "preact/hooks"; -import { composeRef, saveRef } from "../../components/utils.js"; +import { composeRef, saveRef, useAutoFocus } from "../../components/utils.js"; import { Addon, resolveFieldHandler, UIFormProps } from "../FormProvider.js"; //@ts-ignore @@ -213,6 +213,8 @@ export function InputLine<Value = string>( value === undefined || value === null ? "" : toString(value); }, [toString, value]); + useAutoFocus(props.focus, () => input.current); + // useHiddenHandler(name as string, hidden ?? false, value, onChange); if (hidden) { return <Fragment />; @@ -274,7 +276,6 @@ export function InputLine<Value = string>( id={inputId} rows={4} ref={composeRef(saveRef(input))} - // ref={composeRef(saveRef(input), doAutoFocus)} FIXME: enable autofocus when form has focus name={String(name)} onInput={(e) => { updateFromString(e.currentTarget.value); @@ -307,7 +308,6 @@ export function InputLine<Value = string>( id={inputId} name={String(name)} ref={composeRef(saveRef(input))} - // ref={composeRef(saveRef(input), doAutoFocus)} FIXME: enable autofocus when form has focus type={type} onInput={(e) => { updateFromString(e.currentTarget.value); diff --git a/packages/web-util/src/forms/fields/InputSelectMultiple.tsx b/packages/web-util/src/forms/fields/InputSelectMultiple.tsx @@ -10,6 +10,7 @@ import { Fragment, VNode, h } from "preact"; import { useId, useRef, useState } from "preact/hooks"; +import { useAutoFocus } from "../../components/utils.js"; import { useTranslationContext } from "../../context/translation.js"; import { resolveFieldHandler, UIFormProps } from "../FormProvider.js"; import { ChoiceS } from "./InputChoiceStacked.js"; @@ -44,6 +45,7 @@ export function InputSelectMultiple<ChoiceVal>( const [dirty, setDirty] = useState<boolean>(); const id = `select-many-${useId()}`; const inputRef = useRef<HTMLInputElement>(null); + useAutoFocus(props.focus, () => inputRef.current); const normalizedFilter = (filter ?? "").toLocaleLowerCase(); const list = (value ?? []) as string[]; const choiceMap = new Map( diff --git a/packages/web-util/src/forms/fields/InputSelectOne.tsx b/packages/web-util/src/forms/fields/InputSelectOne.tsx @@ -2,6 +2,7 @@ import { i18n } from "@gnu-taler/taler-util"; import { Fragment, VNode, h } from "preact"; import { useId, useRef, useState } from "preact/hooks"; +import { useAutoFocus } from "../../components/utils.js"; import { resolveFieldHandler, UIFormProps } from "../FormProvider.js"; import { ChoiceS } from "./InputChoiceStacked.js"; import { LabelWithTooltipMaybeRequired } from "./InputLine.js"; @@ -26,6 +27,7 @@ export function InputSelectOne<Choices>( const [dirty, setDirty] = useState<boolean>(); // FIXME: dirty state should come from handler const id = `select-one-${useId()}`; const inputRef = useRef<HTMLInputElement>(null); + useAutoFocus(props.focus, () => inputRef.current); const normalizedFilter = (filter ?? "").toLocaleLowerCase(); const choiceMap = choices.reduce( (prev, curr) => { diff --git a/packages/web-util/src/forms/fields/InputToggle.tsx b/packages/web-util/src/forms/fields/InputToggle.tsx @@ -1,5 +1,6 @@ import { Fragment, VNode, h } from "preact"; -import { useState } from "preact/hooks"; +import { useRef, useState } from "preact/hooks"; +import { useAutoFocus } from "../../components/utils.js"; import { resolveFieldHandler, UIFormProps } from "../FormProvider.js"; import { LabelWithTooltipMaybeRequired } from "./InputLine.js"; @@ -33,6 +34,8 @@ export function InputToggle( props.name, ); const [dirty, setDirty] = useState<boolean>(); + const toggle = useRef<HTMLButtonElement>(null); + useAutoFocus(props.focus, () => toggle.current); const isOn = trueValue === value; @@ -51,6 +54,7 @@ export function InputToggle( name={props.name as string} /> <button + ref={toggle} type="button" data-state={isOn ? "on" : value === undefined ? "undefined" : "off"} class="bg-indigo-600 data-[state=off]:bg-gray-200 data-[state=undefined]:bg-gray-200 relative inline-flex h-6 w-12 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-indigo-600 focus:ring-offset-2" diff --git a/packages/web-util/src/forms/forms-ui.test.tsx b/packages/web-util/src/forms/forms-ui.test.tsx @@ -229,3 +229,66 @@ test("form fields show untranslated technical names below their labels", async ( cleanup(); await window.happyDOM.abort(); }); + +test("a form with focus starts on its first fillable field only once", async () => { + const window = installDom(); + const { cleanup, render } = await import("@testing-library/preact"); + const focusDesign: FormDesign = { + type: "double-column", + sections: [ + { + title: "Account" as TranslatedString, + fields: [ + { type: "caption", label: "Introduction" as TranslatedString }, + { + type: "text", + id: "skipped", + label: "Hidden field" as TranslatedString, + hidden: true, + }, + { + type: "text", + id: "first", + label: "First field" as TranslatedString, + }, + { + type: "text", + id: "second", + label: "Second field" as TranslatedString, + }, + ], + }, + { + title: "Details" as TranslatedString, + fields: [ + { + type: "text", + id: "third", + label: "Third field" as TranslatedString, + }, + ], + }, + ], + }; + const settle = () => new Promise((resolve) => setTimeout(resolve, 150)); + + function Harness() { + const form = useForm(focusDesign, {}); + return <FormUI design={focusDesign} model={form.model} focus />; + } + + const view = render(<Harness />); + await settle(); + assert.equal(document.activeElement, view.getByLabelText("First field")); + + // Typing elsewhere re-renders the form; that must not pull focus back. + const second = view.getByLabelText("Second field") as HTMLInputElement; + second.focus(); + second.value = "typed"; + second.dispatchEvent(new Event("input", { bubbles: true })); + await settle(); + assert.equal(document.activeElement, second); + + cleanup(); + await window.happyDOM.abort(); +}); diff --git a/packages/web-util/src/forms/forms-ui.tsx b/packages/web-util/src/forms/forms-ui.tsx @@ -1,3 +1,5 @@ +import { FocusScope } from "../components/FocusScope.js"; +import { isFocusEligible } from "../components/focus-dom.js"; import { h as create, Fragment, h, VNode } from "preact"; import { ErrorAndLabel, @@ -6,7 +8,7 @@ import { useForm, } from "../hooks/useForm.js"; // import { getConverterById, useTranslationContext } from "../index.browser.js"; -import { useState } from "preact/hooks"; +import { useRef, useState } from "preact/hooks"; import { useTranslationContext } from "../context/translation.js"; import { FieldComponentFunction, @@ -19,6 +21,7 @@ import { UIFormElementConfig, } from "./forms-types.js"; import { convertFormConfigToUiField } from "./forms-utils.js"; +import { UIFormProps } from "./FormProvider.js"; import { AcceptTosForm, AcceptTosFormValues } from "./AcceptTosForm.js"; import { Attention } from "../components/Attention.js"; import { FormLanguagePolicy } from "./forms-types.js"; @@ -185,7 +188,29 @@ export const DEFAULT_FORM_UI_NAME = "form-ui"; /** * FIXME: formDesign should be embedded in formHandler */ -export function FormUI<T>({ +export function FormUI<T>( + props: Parameters<typeof FormUIContent<T>>[0], +): VNode { + const root = useRef<HTMLDivElement>(null); + return ( + <FocusScope + active={!!props.focus} + root={() => root.current} + initialFocus={() => + Array.from( + root.current?.querySelectorAll<HTMLElement>("[data-focus-initial]") ?? + [], + ).find(isFocusEligible) + } + > + <div ref={root} style="display: contents"> + <FormUIContent {...props} /> + </div> + </FocusScope> + ); +} + +function FormUIContent<T>({ name = DEFAULT_FORM_UI_NAME, design, model, @@ -200,6 +225,7 @@ export function FormUI<T>({ disabled?: boolean; onSubmit?: () => void; }): VNode { + const { i18n } = useTranslationContext(); const languageNotice = <FormLanguageNotice policy={design.languagePolicy} />; switch (design.type) { case "accept-tos": { @@ -218,6 +244,28 @@ export function FormUI<T>({ ); } case "double-column": { + // Only one field can start with focus: the first one of the first + // section that is shown. + const focusSection = !focus + ? -1 + : design.sections.findIndex( + (section, i) => + !!section && + !model.isSectionHidden(`${i}`) && + convertFormConfigToUiField( + i18n, + `${i}`, + section.fields, + model, + ).some((field) => { + const props = field.properties as UIFormProps<unknown>; + return ( + !NOT_FILLABLE_FIELDS.includes(field.type) && + !props.hidden && + !(disabled ?? props.disabled) + ); + }), + ); const ui = design.sections.map((section, i) => { if (!section) return <Fragment key={i} />; return ( @@ -227,7 +275,7 @@ export function FormUI<T>({ name={name} section={section} model={model} - focus={focus} + focus={i === focusSection} disabled={disabled} onSubmit={onSubmit} /> @@ -395,6 +443,14 @@ export function SingleColumnFormSectionUI<T>({ ); } +const NOT_FILLABLE_FIELDS: UIFormField["type"][] = [ + "caption", + "group", + "htmlIframe", + "external-link", + "download-link", +]; + export function RenderAllFieldsByUiConfig({ focus, fields, @@ -406,6 +462,16 @@ export function RenderAllFieldsByUiConfig({ disabled?: boolean; hidden?: boolean; }): VNode { + // Give focus to the first field the user can fill in, skipping captions, + // groups, links, embedded documents and hidden or disabled fields. + const focusIndex = + !focus || hidden + ? -1 + : fields.findIndex((field) => { + if (NOT_FILLABLE_FIELDS.includes(field.type)) return false; + const props = field.properties as UIFormProps<unknown>; + return !props.hidden && !(disabled ?? props.disabled); + }); return create( Fragment, {}, @@ -415,7 +481,7 @@ export function RenderAllFieldsByUiConfig({ ] as FieldComponentFunction<any>; const p: Record<string, any> = { ...field.properties, - focus: !!focus && i === 0, + focus: i === focusIndex, hidden: hidden || ("hidden" in field.properties && field.properties.hidden), };