fix(public): 공개 화면 이동 뒤 초점·해시·뒤로 가기 스크롤을 맞춘다
TechLog 공개 화면은 화면에 도착했을 때 할 일을 아무도 하지 않는다. - 초점: 템플릿은 라우터가 #main-content에, PageHeader가 h1에 초점을 준다. 이 제품은 9월 동기화 때 라우터의 초점 이동을 빼며 「shell이 맡는다」고 적었지만, Public shell에는 그 처리가 없다. TechLog 화면은 PageHeader를 쓰지 않는다. 그래서 이동 뒤에도 초점이 누른 링크(모바일 메뉴에서는 닫힌 details 안의 링크)에 남는다. - 해시: /cases/...#section으로 열면 맨 위에 머문다. 본문은 데이터를 받은 뒤에 그려져, 브라우저의 기본 앵커 이동이 일어날 때 대상이 없다. - 뒤로 가기: 브라우저 기본 복원은 돌아갈 화면이 그려지기 전에 일어난다. firefox는 0으로, webkit은 가끔 0으로 돌아간다. Public shell에 useRouteArrival을 둔다. 템플릿의 PageHeader 방식을 따른다. - 새 경로에 도착하면, 화면이 그려진 뒤(#main-content의 h1이 있고 aria-busy가 없을 때, 최대 5초) 해시 대상을 보이게 스크롤한다. 그다음 초점을 받을 수 있는 해시 대상, 아니면 h1(tabindex -1)에 초점을 준다(preventScroll). 첫 로드에서는 아무것도 초점을 갖지 않았을 때만 옮긴다. - 뒤로·앞으로 가기: history entry(location.key)마다 떠날 때의 위치를 기억하고, 화면이 그만큼 길어지면 그 위치로 돌린다. Public shell이 떠 있는 동안 history.scrollRestoration을 manual로 둔다. 새로고침은 mount 전이라 브라우저 복원을 그대로 쓴다. 떠나는 위치는 새 entry를 렌더할 때 기록한다. 짧은 화면이 commit되면 window.scrollY가 그 순간 줄어들기 때문이다. - 쿼리만 바뀌거나 같은 화면의 # 링크는 도착이 아니다. - jsdom에서는 라우터의 스크롤 처리와 같이 아무것도 하지 않는다. 버린 대안: - 라우터(템플릿 소유 app-router.tsx)에 되살리기. Studio 화면들은 자기 초점 처리를 따로 갖고 있어 영향이 넓다. 이번 결함은 Public 화면이다. - 공개 화면 14개의 h1마다 PageHeader 같은 컴포넌트를 씌우기. 같은 일을 화면마다 반복하게 된다. - 위치를 sessionStorage에 두기. 저장소 API는 adapter 소유라 lint가 막는다. 메모리 Map으로 충분하다(새로고침은 브라우저가 복원한다). 위험: 화면이 5초 안에 그려지지 않으면 그때의 h1이나 대상에 맞춘다. Studio 경로는 바뀌지 않는다. 검증: - 이 커밋 전에는 app-shell drawer 초점, scroll-restoration 해시가 chromium에서 실패한다. 뒤로 가기는 firefox·webkit에서 실패한다. - 이 커밋 뒤에는 app-shell, scroll-restoration, production-csp가 chromium·firefox·webkit에서 통과한다. webkit scroll-restoration은 3회 연속 통과했다. - 공개 화면 단위 시험 5파일과 router 시험(합쳐 86건) 통과. check:types, lint rc=0.
This commit is contained in:
@@ -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 (
|
||||
<div className="site-frame">
|
||||
<a className="skip-link" href="#main-content">
|
||||
|
||||
@@ -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<string, number>();
|
||||
|
||||
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<HTMLElement>("#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]);
|
||||
}
|
||||
Reference in New Issue
Block a user