commit 10db8ad6d183a3adc89525e6a261606adf63c8f9
parent 8447cc2a3d1725364327ef9331628f7c59dd3968
Author: Florian Dold <dold@taler.net>
Date: Fri, 13 Nov 2026 01:06:16 +0100
merchant web UI: restore page focus on browser history navigation
Focus the destination heading or task field on navigation. Save stable
control keys in history entries and use restoreTarget on Back/Forward.
Query-only changes leave focus where it is.
Assisted-by: LLM
Diffstat:
3 files changed, 147 insertions(+), 1 deletion(-)
diff --git a/packages/taler-merchant-webui/src/App.tsx b/packages/taler-merchant-webui/src/App.tsx
@@ -14,6 +14,7 @@
GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
+import { PageFocus } from "./routing/PageFocus.js";
import type { VNode } from "preact";
import { useEffect, useState } from "preact/hooks";
import { Route, Router, Switch, Redirect, useLocation } from "wouter-preact";
@@ -1190,7 +1191,9 @@ export function App(): VNode {
return (
<TranslationProvider>
<Router hook={useHashLocation}>
- <AppRoute />
+ <PageFocus>
+ <AppRoute />
+ </PageFocus>
</Router>
</TranslationProvider>
);
diff --git a/packages/taler-merchant-webui/src/routing/PageFocus.tsx b/packages/taler-merchant-webui/src/routing/PageFocus.tsx
@@ -0,0 +1,139 @@
+/*
+ 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 { type ComponentChildren } from "preact";
+import { useEffect, useRef } from "preact/hooks";
+import { useLocation } from "wouter-preact";
+import {
+ FocusScope,
+ FocusPolicy,
+ isFocusEligible,
+} from "@gnu-taler/web-util/browser";
+
+const stateKey = "talerMerchantFocus";
+let nextEntry = 0;
+interface Entry {
+ id: string;
+ path: string;
+ target?: string;
+}
+function entry(): Entry {
+ const saved = history.state?.[stateKey] as Entry | undefined;
+ if (saved?.path === location.hash) return saved;
+ const value = {
+ id: globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${++nextEntry}`,
+ path: location.hash,
+ };
+ history.replaceState({ ...history.state, [stateKey]: value }, "");
+ return value;
+}
+function keyOf(element: HTMLElement): string | undefined {
+ if (element.dataset.focusKey) return "key:" + element.dataset.focusKey;
+ if (element.id) return "id:" + element.id;
+ if (element instanceof HTMLAnchorElement && element.getAttribute("href"))
+ return "href:" + element.getAttribute("href");
+ return undefined;
+}
+function savedTarget(
+ root: HTMLElement | null,
+ key: string | undefined,
+): HTMLElement | undefined {
+ if (!root || !key) return undefined;
+ return Array.from(
+ root.querySelectorAll<HTMLElement>("[id], [data-focus-key], a[href]"),
+ ).find((element) => keyOf(element) === key && isFocusEligible(element));
+}
+
+/** Focus new pages and restore their last focused control on Back/Forward. */
+export function PageFocus({ children }: { children: ComponentChildren }) {
+ const [path] = useLocation();
+ const root = useRef<HTMLDivElement>(null);
+ const navigation = useRef({
+ path,
+ activated: false,
+ entry: typeof window === "undefined" ? undefined : entry(),
+ });
+ // Read history metadata in the same render as the destination. Router hooks
+ // can render synchronously before later popstate listeners are called.
+ if (navigation.current.path !== path) {
+ navigation.current = { path, activated: true, entry: entry() };
+ }
+ const destination = navigation.current;
+ const restoring = !!destination.entry?.target;
+ useEffect(() => {
+ const remember = (event: FocusEvent) => {
+ const element = event.target;
+ if (!(element instanceof HTMLElement) || !root.current?.contains(element))
+ return;
+ // Overlay targets are restored by their scopes, not by page history.
+ if (element.closest('[role="dialog"], dialog')) return;
+ const target = keyOf(element);
+ if (!target) return;
+ const current = entry();
+ history.replaceState(
+ { ...history.state, [stateKey]: { ...current, target } },
+ "",
+ );
+ };
+ document.addEventListener("focusin", remember);
+ return () => document.removeEventListener("focusin", remember);
+ }, []);
+ const heading = () =>
+ root.current?.querySelector<HTMLElement>("main h1, main h2, h1, h2") ??
+ root.current?.querySelector<HTMLElement>("main") ??
+ root.current;
+ const fragment = () => {
+ const value = new URLSearchParams(location.hash.split("?")[1] ?? "").get(
+ "anchor",
+ );
+ return value
+ ? root.current?.querySelector<HTMLElement>(`[id="${CSS.escape(value)}"]`)
+ : undefined;
+ };
+ const task = () =>
+ root.current?.querySelector<HTMLElement>("[data-focus-initial]");
+ // Query changes keep the same activation. A restored target wins over task defaults.
+ return (
+ <FocusScope
+ root={() => root.current}
+ active={destination.activated}
+ activationKey={path}
+ restoreTarget={
+ restoring
+ ? () => savedTarget(root.current, destination.entry?.target)
+ : undefined
+ }
+ ready={() => !root.current?.querySelector("[data-focus-loading]")}
+ fallbackFocus={heading}
+ initialFocus={() => fragment() ?? task() ?? heading()}
+ scroll={!restoring}
+ >
+ <div
+ ref={root}
+ tabIndex={-1}
+ aria-label="Taler Merchant Portal"
+ role="region"
+ class="min-w-0"
+ >
+ {path.startsWith("/stor") ? (
+ <FocusPolicy automatic={false}>{children}</FocusPolicy>
+ ) : (
+ children
+ )}
+ </div>
+ </FocusScope>
+ );
+}
diff --git a/packages/taler-merchant-webui/src/ui/InitialLoadingState.tsx b/packages/taler-merchant-webui/src/ui/InitialLoadingState.tsx
@@ -14,6 +14,7 @@
GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
+import { useFocusTarget } from "@gnu-taler/web-util/browser";
import type { ComponentChildren, VNode } from "preact";
import { LoadingSpinner } from "./LoadingSpinner.js";
@@ -27,8 +28,11 @@ export function InitialLoadingState({
children,
className = "",
}: InitialLoadingStateProps): VNode {
+ const loading = useFocusTarget<HTMLDivElement>();
return (
<div
+ ref={loading.ref}
+ data-focus-loading
class={`rounded-xl border border-gray-200 bg-white p-8 text-center text-sm text-gray-500 ${className}`}
aria-live="polite"
>