diff --git a/docs/architecture/routing-pages-and-patterns.md b/docs/architecture/routing-pages-and-patterns.md index 3358a594..89515500 100644 --- a/docs/architecture/routing-pages-and-patterns.md +++ b/docs/architecture/routing-pages-and-patterns.md @@ -301,9 +301,15 @@ custom fallback을 넘겨 retry/reset 기능을 잃지 않게 한다. boundary - mouse 사용자가 불필요한 focus ring을 보지 않게 할 수는 있지만 keyboard focus indication을 전역으로 제거하지 않음 - modal/drawer가 닫히면 opener에 focus 복원 -- backward/forward navigation은 저장한 scroll 복원 +- backward/forward navigation은 저장한 scroll 복원. 복원은 브라우저가 하고, + `RouteLifecycle`은 POP이 아닐 때만 top으로 보낸다(`app-router.tsx`). + `PageHeader`의 heading focus는 `preventScroll`이라 복원된 위치를 옮기지 않는다 - 새 primary route는 top으로 이동 -- hash target은 fixed header offset과 focus 가능 여부를 처리 +- hash target은 fixed header offset과 focus 가능 여부를 처리. 페이지가 그려진 뒤 + `PageHeader`가 대상으로 스크롤하고, 대상이 focus 가능하면 대상에, 아니면 + heading에 focus한다(`page-header.tsx`). header 높이는 `html`의 + `scroll-padding-top`으로 뺀다(`shell.css`). 브라우저 검증은 + `tests/e2e/scroll-restoration.spec.ts` - screen reader용 route title/live announcement는 중복 발표를 피함 ### 6.4 취소와 dirty form diff --git a/src/presentation/components/page-header.tsx b/src/presentation/components/page-header.tsx index 1eb3addd..870d02de 100644 --- a/src/presentation/components/page-header.tsx +++ b/src/presentation/components/page-header.tsx @@ -6,6 +6,15 @@ export type PageHeaderProps = Readonly<{ eyebrow?: string; }>; +function hashTarget(): HTMLElement | null { + try { + const id = decodeURIComponent(window.location.hash.slice(1)); + return id ? document.getElementById(id) : null; + } catch { + return null; + } +} + export function PageHeader({ title, description, @@ -21,9 +30,15 @@ export function PageHeader({ activeElement === document.body || activeElement === document.documentElement || activeElement === main; - if (routeOwnsFocus) { - headingRef.current?.focus(); - } + if (!routeOwnsFocus) return; + // 08-08. A hash names a target in this page, which exists only once the + // page has rendered. Focus never scrolls: back navigation keeps the + // position the browser restored. + const target = hashTarget(); + target?.scrollIntoView?.(); + (target && target.tabIndex >= 0 ? target : headingRef.current)?.focus({ + preventScroll: true, + }); }, [title]); return ( diff --git a/src/presentation/routes/app-router.tsx b/src/presentation/routes/app-router.tsx index 5a333654..9b3236f7 100644 --- a/src/presentation/routes/app-router.tsx +++ b/src/presentation/routes/app-router.tsx @@ -13,6 +13,7 @@ import { type RouteObject, useLocation, useNavigate, + useNavigationType, useParams, useSearchParams, } from "react-router-dom"; @@ -165,6 +166,7 @@ function RouteLifecycle({ buildId: string; }) { const { pathname, search } = useLocation(); + const navigationType = useNavigationType(); const { message, resolve } = useLocale(); const diagnostics = useApplicationDiagnostics(); // A locale change re-renders the title only; it is not a route change. @@ -178,7 +180,12 @@ function RouteLifecycle({ const main = document.getElementById("main-content"); main?.focus({ preventScroll: true }); try { - if (!navigator.userAgent.toLowerCase().includes("jsdom")) { + // 08-08. Back and forward leave the scroll to the browser, which + // restores the position it saved for that entry. + if ( + navigationType !== "POP" && + !navigator.userAgent.toLowerCase().includes("jsdom") + ) { window.scrollTo({ top: 0, left: 0, behavior: "auto" }); } } catch { @@ -188,7 +195,7 @@ function RouteLifecycle({ routeId: definition.routeId, buildId, }); - }, [buildId, definition, diagnostics, pathname, search]); + }, [buildId, definition, diagnostics, navigationType, pathname, search]); return null; } diff --git a/src/presentation/styles/theme/shell.css b/src/presentation/styles/theme/shell.css index 2d2afee3..c3398a66 100644 --- a/src/presentation/styles/theme/shell.css +++ b/src/presentation/styles/theme/shell.css @@ -27,6 +27,11 @@ transform: translateY(0); } + /* 08-08. Hash targets land below the sticky 4.5rem header. */ + html { + scroll-padding-top: 4.5rem; + } + .app-shell { display: grid; min-height: 100vh; diff --git a/tests/e2e/scroll-restoration.spec.ts b/tests/e2e/scroll-restoration.spec.ts new file mode 100644 index 00000000..f4f99d81 --- /dev/null +++ b/tests/e2e/scroll-restoration.spec.ts @@ -0,0 +1,39 @@ +import { expect, test, type Page } from "../support/browser/strict-browser-test.ts"; + +const scrollY = (page: Page) => page.evaluate(() => Math.round(window.scrollY)); + +// 08-08. Back restores where the user was; a new route starts at the top. +test("restores the scroll position when navigating back", async ({ page }) => { + const heading = page.getByRole("heading", { level: 1 }); + await page.goto("/examples/ui"); + await expect(heading).toHaveText("UI 구성요소"); + await page.evaluate(() => window.scrollTo(0, 900)); + await expect.poll(() => scrollY(page)).toBe(900); + + await page + .getByRole("navigation", { name: "주요 탐색" }) + .getByRole("link", { name: "화면 상태" }) + .click(); + await expect(heading).toHaveText("화면 상태"); + await expect.poll(() => scrollY(page)).toBe(0); + + await page.goBack(); + await expect(heading).toHaveText("UI 구성요소"); + await expect.poll(() => scrollY(page)).toBe(900); +}); + +test("opens a hash link at its target below the sticky header", async ({ + page, +}) => { + await page.goto("/examples/ui#tokens-title"); + const target = page.locator("#tokens-title"); + await expect(target).toBeInViewport(); + const top = await target.evaluate((element) => + Math.round(element.getBoundingClientRect().top), + ); + const headerBottom = await page + .locator(".app-shell__header") + .evaluate((element) => Math.round(element.getBoundingClientRect().bottom)); + expect(top).toBeGreaterThanOrEqual(headerBottom); + expect(await scrollY(page)).toBeGreaterThan(0); +});