commit c58cf2ae54417fe5d5cab9075ff3d88e52f3796b
parent be277f9e6cb0db916464e05020eb757b74ea3e23
Author: Florian Dold <dold@taler.net>
Date: Fri, 13 Nov 2026 01:06:16 +0100
merchant web UI: share dialog and menu focus handling
Let Modal choose its initial target and use DialogFocusScope for Tab,
Escape and restoration. Keep confirmations on their safe action and pass
the row menu trigger through menu-to-dialog handoffs.
Issue: https://bugs.taler.net/n/12004
Assisted-by: LLM
Diffstat:
5 files changed, 236 insertions(+), 133 deletions(-)
diff --git a/packages/taler-merchant-webui/src/ui/ConfirmDeleteModal.tsx b/packages/taler-merchant-webui/src/ui/ConfirmDeleteModal.tsx
@@ -60,7 +60,12 @@ export function ConfirmDeleteModal({
title={t`Could not delete this item`}
/>
<div class="flex items-center justify-end space-x-3 pt-2">
- <Button variant="secondary" onClick={onClose} disabled={isPending}>
+ <Button
+ data-focus-initial
+ variant="secondary"
+ onClick={onClose}
+ disabled={isPending}
+ >
{cancelLabel || t`Cancel`}
</Button>
<Button
diff --git a/packages/taler-merchant-webui/src/ui/Modal.test.tsx b/packages/taler-merchant-webui/src/ui/Modal.test.tsx
@@ -9,7 +9,7 @@
import assert from "node:assert/strict";
import { test } from "node:test";
-import { render } from "preact";
+import { render, type ComponentChildren } from "preact";
import { useState } from "preact/hooks";
import { act } from "preact/test-utils";
import { Modal } from "./Modal.js";
@@ -45,22 +45,30 @@ test("typing preserves modal focus and Escape uses the latest callback", async (
await act(() => render(<CategoryDialog />, container));
const dialog = document.querySelector('[role="dialog"]')!;
const input = dialog.querySelector("input")!;
- assert.equal(document.activeElement, dialog.querySelector("button"));
- input.focus();
+ assert.ok(
+ document.activeElement === input,
+ "Unexpected focus: " + document.activeElement?.outerHTML,
+ );
for (const character of "Coffee") {
await act(() => {
input.value += character;
input.dispatchEvent(new Event("input", { bubbles: true }));
});
- assert.equal(document.activeElement, input);
+ assert.ok(
+ document.activeElement === input,
+ "Unexpected focus: " + document.activeElement?.outerHTML,
+ );
}
assert.equal(input.value, "Coffee");
await act(() => {
- window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
});
assert.equal(closedValue, "Coffee");
assert.equal(document.querySelector('[role="dialog"]'), null);
- assert.equal(document.activeElement, trigger);
+ assert.ok(
+ document.activeElement === trigger,
+ "Unexpected focus: " + document.activeElement?.outerHTML,
+ );
} finally {
await act(() => render(null, container));
container.remove();
@@ -68,6 +76,60 @@ test("typing preserves modal focus and Escape uses the latest callback", async (
}
});
+test("an opened dialog starts in its field, never on a destructive option", async () => {
+ const container = document.createElement("div");
+ document.body.append(container);
+ const open = (content: ComponentChildren) =>
+ act(() =>
+ render(
+ <Modal isOpen title="Dialog" onClose={() => {}}>
+ {content}
+ </Modal>,
+ container,
+ ),
+ );
+ const close = () => act(() => render(null, container));
+ try {
+ await open(
+ <>
+ <input type="checkbox" />
+ <input readOnly value="fixed" />
+ <select>
+ <option>EUR</option>
+ </select>
+ <input id="amount" type="number" />
+ </>,
+ );
+ assert.equal(document.activeElement?.id, "amount");
+ await close();
+ await open(
+ <>
+ <input id="name" />
+ {/* eslint-disable-next-line jsx-a11y/no-autofocus -- the marker under test */}
+ <input id="code" autoFocus />
+ </>,
+ );
+ assert.equal(document.activeElement?.id, "code");
+ await close();
+ await open(
+ <>
+ <label>
+ <input type="checkbox" /> Force deletion
+ </label>
+ <button>Delete</button>
+ </>,
+ );
+ assert.ok(
+ document.activeElement ===
+ document.querySelector('[role="dialog"] button'),
+ "Unexpected focus: " + document.activeElement?.outerHTML,
+ );
+ } finally {
+ await close();
+ container.remove();
+ }
+});
+
test("closed modals leave focus alone and restore each actual opener", async () => {
const container = document.createElement("div");
const first = document.createElement("button");
@@ -95,26 +157,38 @@ test("closed modals leave focus alone and restore each actual opener", async ()
const close = buttons[0]!;
const last = buttons[1]!;
last.focus();
- window.dispatchEvent(
+ document.dispatchEvent(
new KeyboardEvent("keydown", { key: "Tab", cancelable: true }),
);
- assert.equal(document.activeElement, close);
- window.dispatchEvent(
+ assert.ok(
+ document.activeElement === close,
+ "Unexpected focus: " + document.activeElement?.outerHTML,
+ );
+ document.dispatchEvent(
new KeyboardEvent("keydown", {
key: "Tab",
shiftKey: true,
cancelable: true,
}),
);
- assert.equal(document.activeElement, last);
+ assert.ok(
+ document.activeElement === last,
+ "Unexpected focus: " + document.activeElement?.outerHTML,
+ );
await show(false);
- assert.equal(document.activeElement, opener);
+ assert.ok(
+ document.activeElement === opener,
+ "Unexpected focus: " + document.activeElement?.outerHTML,
+ );
assert.equal(container.inert, false);
assert.equal(container.hasAttribute("aria-hidden"), false);
}
second.focus();
await act(() => render(null, container));
- assert.equal(document.activeElement, second);
+ assert.ok(
+ document.activeElement === second,
+ "Unexpected focus: " + document.activeElement?.outerHTML,
+ );
} finally {
await act(() => render(null, container));
container.remove();
@@ -162,22 +236,29 @@ test("obsolete modal initialization cannot affect a reopened dialog", () => {
container,
),
);
- assert.equal(queued.length, 2);
+ assert.equal(queued.length, 1);
queued[0]!();
- assert.equal(document.activeElement, opener);
- assert.notEqual(container.inert, true);
- queued[1]!();
const close = document.querySelector<HTMLButtonElement>(
'[role="dialog"] button',
)!;
- assert.equal(document.activeElement, close);
+ assert.ok(
+ document.activeElement === close,
+ "Unexpected focus: " + document.activeElement?.outerHTML,
+ );
// Disabled fieldset descendants must not become focus-trap endpoints.
const tab = new KeyboardEvent("keydown", { key: "Tab", cancelable: true });
- window.dispatchEvent(tab);
+ document.dispatchEvent(tab);
assert.equal(tab.defaultPrevented, true);
- assert.equal(document.activeElement, close);
+ assert.ok(
+ document.activeElement === close,
+ "Unexpected focus: " + document.activeElement?.outerHTML,
+ );
act(() => render(null, container));
- assert.equal(document.activeElement, opener);
+ queued.at(-1)!();
+ assert.ok(
+ document.activeElement === opener,
+ "Unexpected focus: " + document.activeElement?.outerHTML,
+ );
assert.equal(container.hasAttribute("aria-hidden"), false);
assert.notEqual(container.inert, true);
} finally {
@@ -187,3 +268,36 @@ test("obsolete modal initialization cannot affect a reopened dialog", () => {
opener.remove();
}
});
+
+test("bare dialogs retain opt-in backdrop dismissal", async () => {
+ const container = document.createElement("div");
+ document.body.append(container);
+ let closed = 0;
+ const show = (dismissOnBackdrop: boolean) =>
+ act(() =>
+ render(
+ <Modal
+ isOpen
+ bare
+ dismissOnBackdrop={dismissOnBackdrop}
+ onClose={() => {
+ closed++;
+ }}
+ >
+ <button>Inside</button>
+ </Modal>,
+ container,
+ ),
+ );
+ try {
+ await show(false);
+ (container.querySelector('[role="dialog"]') as HTMLElement).click();
+ assert.equal(closed, 0);
+ await show(true);
+ (container.querySelector('[role="dialog"]') as HTMLElement).click();
+ assert.equal(closed, 1);
+ } finally {
+ await act(() => render(null, container));
+ container.remove();
+ }
+});
diff --git a/packages/taler-merchant-webui/src/ui/Modal.tsx b/packages/taler-merchant-webui/src/ui/Modal.tsx
@@ -14,9 +14,11 @@
GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
+import { DialogFocusScope } from "@gnu-taler/web-util/browser";
+import { initialDialogFocus } from "@gnu-taler/web-util/browser";
import type { ComponentChildren } from "preact";
import { createPortal } from "preact/compat";
-import { useEffect, useId, useRef } from "preact/hooks";
+import { useId, useRef } from "preact/hooks";
import { useTranslation } from "../context/translation.js";
export interface ModalProps {
@@ -26,6 +28,13 @@ export interface ModalProps {
ariaLabel?: string;
maxWidth?: "sm" | "md" | "lg" | "xl" | "2xl" | "3xl" | "4xl";
children: ComponentChildren;
+ bare?: boolean;
+ dismissOnBackdrop?: boolean;
+ activationKey?: string;
+ ready?: boolean;
+ fallbackFocus?: () => HTMLElement | null | undefined;
+ overlayClass?: string;
+ initialFocus?: () => HTMLElement | null | undefined;
}
const maxWidthMap = {
@@ -45,121 +54,86 @@ export function Modal({
ariaLabel,
maxWidth = "md",
children,
+ initialFocus,
+ bare = false,
+ dismissOnBackdrop = !bare,
+ activationKey,
+ ready = true,
+ fallbackFocus,
+ overlayClass,
}: ModalProps) {
const { t } = useTranslation();
const titleId = useId();
const overlayRef = useRef<HTMLDivElement>(null);
- // Keep Escape current without restarting focus management on parent renders.
- const onCloseRef = useRef(onClose);
- onCloseRef.current = onClose;
- useEffect(() => {
- if (!isOpen) return;
- let cancelled = false;
- const handleKeyDown = (e: KeyboardEvent) => {
- if (e.key === "Escape" && isOpen) {
- onCloseRef.current();
- }
- if (e.key === "Tab" && isOpen) {
- const focusable = Array.from(
- overlayRef.current?.querySelectorAll<HTMLElement>(
- 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',
- ) ?? [],
- ).filter(
- (element) =>
- !element.matches(":disabled") &&
- !element.closest("fieldset[disabled]"),
- );
- if (focusable.length === 0) {
- e.preventDefault();
- overlayRef.current?.focus();
- } else if (e.shiftKey && document.activeElement === focusable[0]) {
- e.preventDefault();
- focusable[focusable.length - 1]?.focus();
- } else if (
- !e.shiftKey &&
- document.activeElement === focusable[focusable.length - 1]
- ) {
- e.preventDefault();
- focusable[0]?.focus();
- }
- }
- };
- const previousFocus = document.activeElement as HTMLElement | null;
- const changed: Array<{
- element: HTMLElement;
- inert: boolean;
- hidden: string | null;
- }> = [];
- if (isOpen) {
- window.addEventListener("keydown", handleKeyDown);
- queueMicrotask(() => {
- const overlay = overlayRef.current;
- if (cancelled || !overlay) return;
- for (const child of Array.from(document.body.children)) {
- if (child === overlay || !(child instanceof HTMLElement)) continue;
- changed.push({
- element: child,
- inert: child.inert,
- hidden: child.getAttribute("aria-hidden"),
- });
- child.inert = true;
- child.setAttribute("aria-hidden", "true");
- }
- overlay
- .querySelector<HTMLElement>(
- '[autofocus], button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',
- )
- ?.focus();
- });
- }
- return () => {
- cancelled = true;
- window.removeEventListener("keydown", handleKeyDown);
- for (const item of changed) {
- item.element.inert = item.inert;
- if (item.hidden === null) item.element.removeAttribute("aria-hidden");
- else item.element.setAttribute("aria-hidden", item.hidden);
- }
- if (previousFocus?.isConnected) previousFocus.focus();
- };
- }, [isOpen]);
if (!isOpen) return null;
const modal = (
+ // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-noninteractive-element-interactions -- DialogFocusScope handles Escape; clicking the backdrop is an additional dismissal action.
<div
ref={overlayRef}
+ onClick={(event) => {
+ if (dismissOnBackdrop && event.target === event.currentTarget)
+ onClose();
+ }}
tabIndex={-1}
- class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-xs animate-fade-in"
+ class={
+ overlayClass ??
+ "fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-xs animate-fade-in"
+ }
role="dialog"
aria-modal="true"
aria-labelledby={title ? titleId : undefined}
aria-label={title ? undefined : (ariaLabel ?? t`Dialog`)}
>
- <div class="fixed inset-0" onClick={onClose} aria-hidden="true" />
- <div
- class={`modal-scroll-content relative z-10 w-full ${maxWidthMap[maxWidth]} bg-white rounded-xl shadow-xl border border-gray-100 p-6 space-y-4 max-h-[90vh] overflow-y-auto`}
- >
- {title && (
- <div class="flex items-center justify-between border-b border-gray-100 pb-3">
- <h3 id={titleId} class="text-base font-bold text-gray-900">
- {title}
- </h3>
- <button
- type="button"
- onClick={onClose}
- class="text-gray-400 hover:text-gray-600 rounded-md p-1 cursor-pointer transition-colors"
- aria-label={t`Close`}
- >
- ✕
- </button>
+ {bare ? (
+ children
+ ) : (
+ <>
+ <div
+ class="fixed inset-0"
+ onClick={dismissOnBackdrop ? onClose : undefined}
+ aria-hidden="true"
+ />
+ <div
+ class={`modal-scroll-content relative z-10 w-full ${maxWidthMap[maxWidth]} bg-white rounded-xl shadow-xl border border-gray-100 p-6 space-y-4 max-h-[90vh] overflow-y-auto`}
+ >
+ {title && (
+ <div class="flex items-center justify-between border-b border-gray-100 pb-3">
+ <h3 id={titleId} class="text-base font-bold text-gray-900">
+ {title}
+ </h3>
+ <button
+ type="button"
+ onClick={onClose}
+ class="text-gray-400 hover:text-gray-600 rounded-md p-1 cursor-pointer transition-colors"
+ aria-label={t`Close`}
+ >
+ ✕
+ </button>
+ </div>
+ )}
+ <div>{children}</div>
</div>
- )}
- <div>{children}</div>
- </div>
+ </>
+ )}
</div>
);
- return typeof document === "undefined"
- ? modal
- : createPortal(modal, document.body);
+ return (
+ <DialogFocusScope
+ root={() => overlayRef.current}
+ active={isOpen}
+ activationKey={activationKey}
+ ready={ready}
+ initialFocus={() =>
+ initialFocus?.() ?? initialDialogFocus(overlayRef.current)
+ }
+ fallbackFocus={() => fallbackFocus?.() ?? overlayRef.current}
+ onEscape={onClose}
+ >
+ {bare || typeof document === "undefined"
+ ? modal
+ : createPortal(modal, document.body)}
+ </DialogFocusScope>
+ );
}
diff --git a/packages/taler-merchant-webui/src/ui/RowActions.test.tsx b/packages/taler-merchant-webui/src/ui/RowActions.test.tsx
@@ -148,16 +148,20 @@ test("opening another RowActions menu leaves exactly that menu open", () => {
fixture.unmount();
});
-test("Escape closes RowActions and restores focus to its trigger", () => {
+test("Escape closes RowActions and restores focus to its trigger", async () => {
const fixture = mountRowActions();
const trigger = fixture.triggers[0]!;
open(trigger);
+ await Promise.resolve();
- act(() => {
+ await act(() => {
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
});
assert.strictEqual(trigger.getAttribute("aria-expanded"), "false");
- assert.strictEqual(document.activeElement, trigger);
+ assert.ok(
+ document.activeElement === trigger,
+ "Focus returns to the menu trigger",
+ );
fixture.unmount();
});
diff --git a/packages/taler-merchant-webui/src/ui/RowActions.tsx b/packages/taler-merchant-webui/src/ui/RowActions.tsx
@@ -7,6 +7,8 @@
Foundation; either version 3, or (at your option) any later version.
*/
+import { useDialogFocus } from "@gnu-taler/web-util/browser";
+
import type { ComponentChildren, VNode } from "preact";
import { createPortal } from "preact/compat";
import {
@@ -73,9 +75,17 @@ export function RowActions({
item.setAttribute("role", "menuitem");
item.tabIndex = -1;
});
- items?.[0]?.focus();
}, [isOpen, positionMenu]);
+ useDialogFocus({
+ active: isOpen,
+ root: () => menuRef.current,
+ initialFocus: () =>
+ menuRef.current?.querySelector<HTMLElement>('[role="menuitem"]'),
+ returnFocus: () => triggerRef.current,
+ onEscape: () => setIsOpen(false),
+ kind: "menu",
+ });
useEffect(() => {
if (!isOpen) return;
@@ -87,16 +97,10 @@ export function RowActions({
setIsOpen(false);
}
};
- const closeWhenEscaped = (event: KeyboardEvent) => {
- if (event.key === "Escape") {
- setIsOpen(false);
- triggerRef.current?.focus();
- }
- };
+
const closeAfterAction = (event: MouseEvent) => {
if (menuRef.current?.contains(event.target as Node)) {
setIsOpen(false);
- triggerRef.current?.focus();
}
};
// Capture the pointer before application controls can stop propagation.
@@ -104,7 +108,7 @@ export function RowActions({
// silently misses otherwise ordinary outside clicks in such controls.
document.addEventListener("pointerdown", closeWhenClickedOutside, true);
document.addEventListener("click", closeAfterAction);
- document.addEventListener("keydown", closeWhenEscaped);
+
window.addEventListener("resize", positionMenu);
window.addEventListener("scroll", positionMenu, true);
return () => {
@@ -114,7 +118,7 @@ export function RowActions({
true,
);
document.removeEventListener("click", closeAfterAction);
- document.removeEventListener("keydown", closeWhenEscaped);
+
window.removeEventListener("resize", positionMenu);
window.removeEventListener("scroll", positionMenu, true);
};
@@ -126,6 +130,7 @@ export function RowActions({
ref={triggerRef}
type="button"
aria-label={label}
+ data-focus-key={label}
aria-expanded={isOpen}
aria-haspopup="menu"
aria-controls={isOpen ? menuId : undefined}
@@ -146,6 +151,7 @@ export function RowActions({
role="menu"
tabIndex={-1}
aria-label={label}
+ data-focus-key={label}
onKeyDown={(event) => {
const items = Array.from(
menuRef.current?.querySelectorAll<HTMLElement>(