diff --git a/src/features/tech-log/presentation/public/public-shell.tsx b/src/features/tech-log/presentation/public/public-shell.tsx index 1f7dd8f..bdcc3c2 100644 --- a/src/features/tech-log/presentation/public/public-shell.tsx +++ b/src/features/tech-log/presentation/public/public-shell.tsx @@ -3,6 +3,7 @@ import { Link } from "react-router-dom"; import { publicSiteConfig } from "../../contracts/public-site-config.ts"; import { SiteHeader } from "./components/site-header.tsx"; +import { useRouteArrival } from "./use-route-arrival.ts"; import { TechLogMessage } from "../tech-log-message.tsx"; type PublicShellProps = { @@ -11,6 +12,7 @@ type PublicShellProps = { }; export function PublicShell({ children, currentPath }: PublicShellProps) { + useRouteArrival(); return (
diff --git a/src/features/tech-log/presentation/public/use-route-arrival.ts b/src/features/tech-log/presentation/public/use-route-arrival.ts new file mode 100644 index 0000000..bf7d19b --- /dev/null +++ b/src/features/tech-log/presentation/public/use-route-arrival.ts @@ -0,0 +1,154 @@ +import { useEffect, useRef } from "react"; +import { useLocation, useNavigationType } from "react-router-dom"; + +/** + * What a Public page does when the reader arrives on it: focus, hash target + * and, on back/forward, the scroll position the reader left it at. + * + * The template does this with its router (focus `#main-content`) and its + * `PageHeader` (move focus to the h1, or to the hash target). TechLog's Public + * pages draw their own headings and fill in after their data arrives, so + * nothing did any of it: after a navigation focus stayed on the link that was + * clicked (or on a link inside the closed mobile menu), a link with `#section` + * opened at the top, and Back opened at the top because the browser restores + * the scroll before the page it returns to has drawn. + * + * - On a new path, once the page has drawn (an h1 in `#main-content`, nothing + * `aria-busy`): scroll the hash target into view, then focus it if it takes + * focus, otherwise the h1 (tabindex -1 and `data-route-heading`, so no + * focus ring, as PageHeader's). Focus never scrolls. On the first load, focus moves only if nothing has it yet. + * - Back/forward: the position saved for that history entry is restored once + * the page is tall enough for it. The browser's own restoration is off while + * the Public shell is mounted, since it runs before the page exists. A reload + * keeps the browser's restoration: the mode is set after the page mounts. + * - A query-only change or an in-page `#` link is not an arrival. + * + * jsdom implements no scrolling or layout, so, like the router's scroll reset, + * this does nothing there. + */ + +const SETTLE_TIMEOUT_MS = 5_000; + +/** Scroll position per history entry (`location.key`), for this tab's session. */ +const positions = new Map(); + +const inBrowser = () => + typeof navigator !== "undefined" && + !navigator.userAgent.toLowerCase().includes("jsdom"); + +function hashTarget(hash: string): HTMLElement | null { + if (hash.length < 2) return null; + try { + return document.getElementById(decodeURIComponent(hash.slice(1))); + } catch { + return null; + } +} + +function pageHeading(): HTMLElement | null { + return document.querySelector("#main-content h1"); +} + +function pageDrawn(hash: string): boolean { + if (document.querySelector('.site-frame [aria-busy="true"]')) return false; + return pageHeading() !== null && (hash.length < 2 || hashTarget(hash) !== null); +} + +/** Calls `ready` once `done()` holds, or when it gives up waiting. */ +function waitFor(done: () => boolean, signal: AbortSignal, ready: () => void): void { + const deadline = performance.now() + SETTLE_TIMEOUT_MS; + const check = () => { + if (signal.aborted) return; + if (done() || performance.now() > deadline) { + ready(); + return; + } + requestAnimationFrame(check); + }; + check(); +} + +function focusOwnedByRoute(): boolean { + const active = document.activeElement; + return ( + active === null || + active === document.body || + active === document.documentElement || + active === document.getElementById("main-content") + ); +} + +export function useRouteArrival(): void { + const { pathname, hash, key } = useLocation(); + const navigationType = useNavigationType(); + const firstArrival = useRef(true); + const lastScroll = useRef(0); + const lastKey = useRef(key); + + // The entry being left keeps the position the reader last scrolled to. It + // is taken while rendering the new entry, before its DOM replaces the old + // page: a shorter page clamps window.scrollY as soon as it is committed. + if (lastKey.current !== key) { + positions.set(lastKey.current, lastScroll.current); + lastKey.current = key; + } + + useEffect(() => { + if (!inBrowser()) return undefined; + const { history } = window; + const previous = history.scrollRestoration; + history.scrollRestoration = "manual"; + lastScroll.current = window.scrollY; + const onScroll = () => { + lastScroll.current = window.scrollY; + }; + window.addEventListener("scroll", onScroll, { passive: true }); + return () => { + window.removeEventListener("scroll", onScroll); + history.scrollRestoration = previous; + }; + }, []); + + useEffect(() => { + if (!inBrowser()) return undefined; + const first = firstArrival.current; + firstArrival.current = false; + const controller = new AbortController(); + const restoreTo = navigationType === "POP" ? positions.get(key) : undefined; + if (restoreTo !== undefined) { + // A reader who scrolls, types or taps while the page fills in has + // chosen a position; the saved one no longer applies. + for (const type of ["wheel", "touchstart", "keydown", "pointerdown"] as const) { + window.addEventListener(type, () => controller.abort(), { + passive: true, + once: true, + signal: controller.signal, + }); + } + } + waitFor(() => pageDrawn(hash), controller.signal, () => { + if (restoreTo !== undefined) { + waitFor( + () => document.documentElement.scrollHeight - window.innerHeight >= restoreTo, + controller.signal, + () => window.scrollTo({ top: restoreTo, left: 0, behavior: "auto" }), + ); + } + const target = hashTarget(hash); + if (target && restoreTo === undefined) target.scrollIntoView(); + if (first && !focusOwnedByRoute()) return; + const heading = pageHeading(); + const focusTarget = target && target.tabIndex >= 0 ? target : heading; + if (!focusTarget) return; + if (focusTarget === heading) { + // As PageHeader's: reachable by script only, and `[data-route-heading]` + // draws no focus ring (globals.css, 3374f28) since it cannot be tabbed to. + if (!heading.hasAttribute("tabindex")) heading.tabIndex = -1; + heading.setAttribute("data-route-heading", ""); + } + focusTarget.focus({ preventScroll: true }); + }); + return () => controller.abort(); + // eslint-disable-next-line react-hooks/exhaustive-deps -- only a new path (or the first load) is an arrival; see above + }, [pathname]); +}