commit be277f9e6cb0db916464e05020eb757b74ea3e23
parent bee154f5ddb07d01986a5ddf830a5105fbf0ae1f
Author: Florian Dold <dold@taler.net>
Date: Fri, 13 Nov 2026 01:06:16 +0100
web-util: manage focus in the calendar, terms and settings dialogs
Use dialog focus handling for entry, Escape and opener restoration.
Start the calendar on the selected day and the terms reader on Close.
Issue: https://bugs.taler.net/n/12058
Issue: https://bugs.taler.net/n/12059
Issue: https://bugs.taler.net/n/12060
Assisted-by: LLM
Diffstat:
4 files changed, 46 insertions(+), 58 deletions(-)
diff --git a/packages/web-util/src/components/Header.tsx b/packages/web-util/src/components/Header.tsx
@@ -1,5 +1,7 @@
+import { useDialogFocus } from "./FocusScope.js";
+
import { ComponentChildren, Fragment, VNode, h } from "preact";
-import { useEffect, useRef, useState } from "preact/hooks";
+import { useRef, useState } from "preact/hooks";
import logo from "../assets/taler-logo-white.png";
import { useTranslationContext } from "../context/translation.js";
import { LangSelector } from "./LangSelector.js";
@@ -35,18 +37,14 @@ export function Header({
const [open, setOpen] = useState(false);
const menuButton = useRef<HTMLButtonElement>(null);
const closeButton = useRef<HTMLButtonElement>(null);
- useEffect(() => {
- if (!open) return;
- closeButton.current?.focus();
- function closeOnEscape(event: KeyboardEvent): void {
- if (event.key === "Escape") {
- setOpen(false);
- menuButton.current?.focus();
- }
- }
- document.addEventListener("keydown", closeOnEscape);
- return () => document.removeEventListener("keydown", closeOnEscape);
- }, [open]);
+ useDialogFocus({
+ active: open,
+ root: () => closeButton.current?.closest<HTMLElement>('[role="dialog"]'),
+ returnFocus: () => menuButton.current,
+ initialFocus: () => closeButton.current,
+ onEscape: () => setOpen(false),
+ });
+
// const ns = useNotifications();
return (
<Fragment>
diff --git a/packages/web-util/src/forms/AcceptTosForm.tsx b/packages/web-util/src/forms/AcceptTosForm.tsx
@@ -1,6 +1,9 @@
+import { useDialogFocus } from "../components/FocusScope.js";
+
import { TalerFormAttributes } from "@gnu-taler/taler-util";
import { Fragment, type ComponentChildren, h, type VNode } from "preact";
import { useEffect, useRef, useState } from "preact/hooks";
+import { useAutoFocus } from "../components/utils.js";
import { useTranslationContext } from "../context/translation.js";
import type { FormModel } from "../hooks/useForm.js";
import {
@@ -89,14 +92,6 @@ function mediaType(contentType: string | null): string {
return contentType?.split(";", 1)[0].trim().toLowerCase() ?? "";
}
-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"])',
- ),
- );
-}
-
function safePdfFileName(providerName: string | undefined): string {
const provider = providerName
?.normalize("NFKD")
@@ -117,7 +112,7 @@ function TermsReaderDialog(props: {
const { i18n } = useTranslationContext();
const dialogRef = useRef<HTMLDivElement>(null);
const closeButtonRef = useRef<HTMLButtonElement>(null);
- const previousFocus = useRef<HTMLElement | null>(null);
+
const [downloadState, setDownloadState] = useState<
"idle" | "loading" | "error"
>("idle");
@@ -131,46 +126,19 @@ function TermsReaderDialog(props: {
// terms.
const doneLabel = i18n.str`Done`;
+ useDialogFocus({
+ root: () => dialogRef.current,
+ initialFocus: () => closeButtonRef.current,
+ fallbackFocus: () => dialogRef.current,
+ onEscape: onClose,
+ });
useEffect(() => {
const previousOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";
- previousFocus.current =
- document.activeElement instanceof HTMLElement
- ? document.activeElement
- : null;
- closeButtonRef.current?.focus();
-
- const onKeyDown = (event: KeyboardEvent) => {
- if (event.key === "Escape") {
- event.preventDefault();
- onClose();
- return;
- }
- const dialog = dialogRef.current;
- if (event.key !== "Tab" || !dialog) return;
- const focusable = focusableElements(dialog);
- if (focusable.length === 0) {
- event.preventDefault();
- dialog.focus();
- return;
- }
- const first = focusable[0];
- const last = focusable[focusable.length - 1];
- if (event.shiftKey && document.activeElement === first) {
- event.preventDefault();
- last.focus();
- } else if (!event.shiftKey && document.activeElement === last) {
- event.preventDefault();
- first.focus();
- }
- };
- document.addEventListener("keydown", onKeyDown);
return () => {
- document.removeEventListener("keydown", onKeyDown);
document.body.style.overflow = previousOverflow;
- previousFocus.current?.focus();
};
- }, [onClose]);
+ }, []);
async function downloadPdf(): Promise<void> {
setDownloadState("loading");
@@ -358,6 +326,7 @@ export function AcceptTosForm(props: {
const [error, setError] = useState<ReaderError>();
const request = useRef<AbortController>();
const readButton = useRef<HTMLButtonElement>(null);
+ useAutoFocus(props.focus, () => readButton.current);
useEffect(
() => () => {
@@ -460,7 +429,6 @@ export function AcceptTosForm(props: {
disabled={props.disabled}
class="mt-5 inline-flex min-h-11 items-center justify-center rounded-md bg-indigo-600 px-4 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 disabled:cursor-default disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
onClick={openReader}
- autofocus={props.focus}
>
{hasRead ? readAgainLabel : readLabel}
</button>
diff --git a/packages/web-util/src/forms/Calendar.tsx b/packages/web-util/src/forms/Calendar.tsx
@@ -1,3 +1,4 @@
+import { useFocusScope } from "../components/FocusScope.js";
import { AbsoluteTime } from "@gnu-taler/taler-util";
import {
add as dateAdd,
@@ -47,6 +48,13 @@ export function Calendar({
if (input.current === document.activeElement) return;
input.current.value = !year ? "" : String(year);
}, [year]);
+ // The calendar is a picker the user has just opened: start on the selected
+ // day so that Enter keeps it and Tab moves on through the month.
+ const days = useRef<HTMLDivElement>(null);
+ useFocusScope({
+ initialFocus: () =>
+ days.current?.querySelector<HTMLElement>('[data-selected="true"]'),
+ });
const start = startOfWeek(startOfMonth(showingDate), { weekStartsOn: 1 });
const end = endOfWeek(endOfMonth(showingDate), { weekStartsOn: 1 });
@@ -183,7 +191,10 @@ export function Calendar({
))}
</div>
<div class="isolate mt-2">
- <div class="grid grid-cols-7 gap-px rounded-lg bg-gray-200 text-sm shadow ring-1 ring-gray-200">
+ <div
+ ref={days}
+ class="grid grid-cols-7 gap-px rounded-lg bg-gray-200 text-sm shadow ring-1 ring-gray-200"
+ >
{daysInMonth.map((current, idx) => (
<button
type="button"
diff --git a/packages/web-util/src/forms/Dialog.tsx b/packages/web-util/src/forms/Dialog.tsx
@@ -1,4 +1,7 @@
+import { useDialogFocus } from "../components/FocusScope.js";
+import { initialDialogFocus } from "../components/focus-dom.js";
import { ComponentChildren, VNode, h } from "preact";
+import { useRef } from "preact/hooks";
import { useTranslationContext } from "../context/translation.js";
export function Dialog({
@@ -9,8 +12,16 @@ export function Dialog({
children: ComponentChildren;
}): VNode {
const { i18n } = useTranslationContext();
+ const root = useRef<HTMLDivElement>(null);
+ useDialogFocus({
+ root: () => root.current,
+ initialFocus: () => initialDialogFocus(root.current),
+ onEscape: onClose,
+ });
return (
<div
+ ref={root}
+ tabIndex={-1}
class="relative z-10"
aria-labelledby="modal-title"
role="dialog"