diff --git a/e2e/accessibility.spec.ts b/e2e/accessibility.spec.ts index 45276a4..ceee1d6 100644 --- a/e2e/accessibility.spec.ts +++ b/e2e/accessibility.spec.ts @@ -138,6 +138,25 @@ test.describe('Accessibility', () => { expect(secondIdentity).not.toEqual(firstIdentity); }); + test('skip link is first focusable and jumps to main without routing', async ({ page, browserName }) => { + test.skip(browserName === 'webkit', 'Tab navigation not supported on mobile webkit'); + + await page.goto('/#/'); + // Wait for first render so the React-rendered link exists; the assertions + // below confirm its onClick (focus #main) runs instead of the native + // `#main` jump, which HashRouter would treat as a 404 route. + await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + + await page.keyboard.press('Tab'); + const skipLink = page.getByRole('link', { name: 'Skip to main content' }); + await expect(skipLink).toBeFocused(); + + await skipLink.press('Enter'); + await expect(page.locator('main#main')).toBeFocused(); + expect(page.url()).toContain('#/'); + await expect(page.getByText('Lost in the feed')).toHaveCount(0); + }); + test('external links have valid URLs', async ({ page }) => { await page.goto('/#/'); diff --git a/index.html b/index.html index 5778758..f6ba38f 100644 --- a/index.html +++ b/index.html @@ -4,8 +4,9 @@ - + diff --git a/src/App.tsx b/src/App.tsx index 18040b6..8682179 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -177,7 +177,7 @@ function MainContent({ children }: { children: React.ReactNode }) { // In swipe mode: document scrolls naturally (no height constraint needed). // Without h-dvh, ancestor chain grows with panel content. return ( -
+
{children}
); @@ -213,6 +213,19 @@ function App() {
+ { + // Move focus to
without mutating the route hash — + // a bare `#main` jump would make HashRouter navigate to a + // non-existent `main` route and render the 404 page. + e.preventDefault(); + document.getElementById('main')?.focus(); + }} + > + Skip to main content +
diff --git a/src/components/Header.tsx b/src/components/Header.tsx index 847a984..1fe0ced 100644 --- a/src/components/Header.tsx +++ b/src/components/Header.tsx @@ -21,6 +21,7 @@ import { useScrollContainer } from '../hooks/useScrollContainer'; import { useIsMobile } from '../hooks/useIsMobile'; import { usePackedNav } from '../hooks/usePackedNav'; import { clearListSessionState } from '../utils/itemCache'; +import { prefersReducedMotion } from '../utils/prefersReducedMotion'; import { deriveHeaderState, type ContextualKey, @@ -81,6 +82,12 @@ const NAV_GAP = 4; // object and read it straight off the result without a key-based lookup. type PackableNavItem = NavItemSpec & { width: number }; +// An explicit `behavior: 'smooth'` overrides CSS `scroll-behavior`, so the +// global reduced-motion rule in index.css can't neutralize it — gate it here. +function scrollToTop() { + window.scrollTo({ top: 0, behavior: prefersReducedMotion() ? 'auto' : 'smooth' }); +} + export function Header() { const maskId = useId(); const { scrollDirection, isAtTop } = useScrollDirection(); @@ -127,14 +134,14 @@ export function Header() { clearListSessionState('show'); clearListSessionState('ask'); if (location.pathname === '/') { - window.scrollTo({ top: 0, behavior: 'smooth' }); + scrollToTop(); } }; const handleNavClick = (feed: FeedType) => { clearListSessionState(feed); if (location.pathname === `/${feed}`) { - window.scrollTo({ top: 0, behavior: 'smooth' }); + scrollToTop(); } }; diff --git a/src/context/ThemeContext.tsx b/src/context/ThemeContext.tsx index a72f98e..0bb57e9 100644 --- a/src/context/ThemeContext.tsx +++ b/src/context/ThemeContext.tsx @@ -25,8 +25,9 @@ function resolveTheme(mode: ThemeMode): Theme { return mode === 'system' ? getSystemTheme() : mode; } -// Apply the resolved theme to the document: toggle the `.dark` class (drives -// the CSS tokens) AND update the theme-color meta so the PWA status bar follows. +// Apply the resolved theme to : swap the `light`/`dark` class (which +// drives the design tokens and the UA color-scheme) AND update the theme-color +// meta so the PWA status bar follows. function applyTheme(theme: Theme) { const root = window.document.documentElement; root.classList.remove('light', 'dark'); diff --git a/src/hooks/useSwipeScroll.test.ts b/src/hooks/useSwipeScroll.test.ts index cab03b0..a506be9 100644 --- a/src/hooks/useSwipeScroll.test.ts +++ b/src/hooks/useSwipeScroll.test.ts @@ -555,6 +555,26 @@ describe('useSwipeScroll', () => { expect(Element.prototype.animate).toHaveBeenCalled(); }); + it('short slow drag snaps back instantly without animating (reduced motion)', () => { + reducedMotionValue = true; + render(createElement(TestHarness), { wrapper: Wrapper }); + + const container = getContainer(); + + dispatchTouch(container, 'touchstart', CENTER_X, CENTER_Y); + // Same sub-threshold + low-velocity drag as the test above, but reduced + // motion: the cancel must be instant (cleanSlate), with no WAAPI slide — + // CSS reduced-motion rules can't neutralize an element.animate() call. + vi.advanceTimersByTime(1000); + dispatchTouch(container, 'touchmove', CENTER_X - 20, CENTER_Y); + dispatchTouch(container, 'touchend', CENTER_X - 20, CENTER_Y); + + expect(hasActive(0)).toBe(true); + expect(hookResult.currentIndex).toBe(0); + expect(Element.prototype.animate).not.toHaveBeenCalled(); + expect(getPanel(0).style.transform).toBe(''); + }); + it('boundary: swipe backward on first panel stays', () => { render(createElement(TestHarness), { wrapper: Wrapper }); diff --git a/src/hooks/useSwipeScroll.ts b/src/hooks/useSwipeScroll.ts index 97cde68..5a6effb 100644 --- a/src/hooks/useSwipeScroll.ts +++ b/src/hooks/useSwipeScroll.ts @@ -1,5 +1,6 @@ import { useState, useRef, useEffect, useLayoutEffect, useCallback } from 'react'; import { useScrollContainer } from './useScrollContainer'; +import { prefersReducedMotion } from '../utils/prefersReducedMotion'; const noop = () => undefined; @@ -204,8 +205,6 @@ export function useSwipeScroll({ // Initial activation activatePanel(currentIndexRef.current); - const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches; - // --- Animation lifecycle --- let runningAnimations: Animation[] = []; let pendingTimeouts: ReturnType[] = []; @@ -523,6 +522,10 @@ export function useSwipeScroll({ return; } + // Read live (not cached at effect setup) so a mid-session OS toggle is + // honored on the very next gesture, matching the CSS media query. + const reducedMotion = prefersReducedMotion(); + flushDragFrame(); touchActive = false; @@ -636,6 +639,12 @@ export function useSwipeScroll({ // Safety timeout in case onfinish doesn't fire pendingTimeouts.push(setTimeout(finishCommit, duration + 100)); } + } else if (reducedMotion) { + // --- Cancel (reduced motion): instant snap back, no slide --- + // The WAAPI slide is invisible to the CSS reduced-motion rule, so the + // cancel must be gated in JS too (mirrors the commit path). + cleanSlate(); + isDraggingRef.current = false; } else { // --- Cancel: snap back --- const duration = 200; diff --git a/src/index.css b/src/index.css index 6622c2c..b4909ff 100644 --- a/src/index.css +++ b/src/index.css @@ -12,8 +12,12 @@ button { /* ── Design Tokens ──────────────────────────────────────────────────── */ /* Light mode (default) — warm stone/taupe palette */ :root { - /* Pins UA surfaces (scrollbars etc.) to the in-app theme: .dark tracks the - app theme, not the OS. Pairs with the color-scheme meta in index.html. */ + /* Resolved-light default. Before React hydrates, has no theme class + in the light cases (the index.html bootstrap only adds .dark), so a bare + `light dark` here would let a dark OS paint dark UA surfaces (scrollbars, + form controls) under a light-pinned app until ThemeContext runs. Defaulting + to light avoids that flash; html.light / html.dark below pin the scheme to + the JS-applied theme, and still advertises both. */ color-scheme: light; --background: oklch(0.98 0.006 60); /* warm cream */ --foreground: oklch(0.22 0.01 60); /* warm near-black */ @@ -50,7 +54,6 @@ button { /* Dark mode — soft dark, warm tones */ .dark { - color-scheme: dark; --background: oklch(0.20 0.012 60); /* soft dark with warm tint */ --foreground: oklch(0.92 0.005 60); /* warm light text */ --card: oklch(0.24 0.012 60); /* slightly lighter than bg */ @@ -63,6 +66,14 @@ button { --viewed: oklch(0.62 0.01 60); /* dimmed for read stories */ } +/* Keep the UA color-scheme in sync with the resolved theme. ThemeContext and + the index.html bootstrap script toggle .light / .dark on ; mirror that + so native widgets match the painted theme even when the OS scheme differs + from the in-app pin. html.* (0,1,1) beats the :root default regardless of + source order. */ +html.light { color-scheme: light; } +html.dark { color-scheme: dark; } + /* Wire CSS variables into Tailwind utility classes */ @theme inline { --color-background: var(--background); @@ -197,6 +208,64 @@ button { outline-offset: 2px; } +/* Skip link (WCAG 2.4.1 Bypass Blocks): the first focusable element, kept + offscreen until focused so keyboard/switch users can jump past the header + straight to the main content. Offscreen (not display:none) so it stays in + the accessibility tree and reachable by Tab. */ +.skip-link { + position: fixed; + inset-inline-start: 0.5rem; + inset-block-start: -4rem; + z-index: 100; + /* Match the header nav pills (px-2.5 py-1) so the chip reads as part of the + same UI rather than an oversized bolt-on. */ + padding: 0.25rem 0.625rem; + border-radius: 0.5rem; + background: var(--accent); + color: var(--accent-foreground); + font-size: 0.875rem; + font-weight: 500; + box-shadow: 0 2px 8px rgb(0 0 0 / 0.2); + transition: inset-block-start 0.15s ease; +} + +.skip-link:focus { + inset-block-start: 0.5rem; +} + +/* The skip link focuses
programmatically; suppress the global + :focus-visible ring so it doesn't paint a box around the whole content. */ +#main:focus { + outline: none; +} + +/* ── Reduced motion: global baseline ────────────────────────────────── + Belt-and-suspenders catch-all for prefers-reduced-motion. The app already + ships tested per-component reduced-motion contracts further down (network + bar, StateView scene, PageStage cascade, skeleton overlay); those use + higher specificity and/or !important, so they still win where they apply. + This universal rule (lowest specificity) only governs incidental + transitions/animations that lack a dedicated rule. + + We near-zero the *duration* rather than setting `animation: none` so that + animationend/transitionend listeners still fire — components that unmount + on those events keep working instead of hanging. + + We deliberately leave `animation-timeline` alone: the only scroll-driven + animation is the user-controlled swipe scroll indicator (`body.swipe-mode + ::after`) — WCAG-exempt like a scrollbar, and forcing it off would pin the + thumb at its end keyframe instead of disabling it. */ +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + scroll-behavior: auto !important; + } +} + /* Tree trunk: vertical line under › marker */ .tree-trunk { --tree-line: color-mix(in oklch, var(--accent) 20%, transparent); diff --git a/src/utils/prefersReducedMotion.test.ts b/src/utils/prefersReducedMotion.test.ts new file mode 100644 index 0000000..226252d --- /dev/null +++ b/src/utils/prefersReducedMotion.test.ts @@ -0,0 +1,34 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { prefersReducedMotion } from './prefersReducedMotion'; + +const realMatchMedia = window.matchMedia; + +function stubMatchMedia(matches: boolean) { + const mm = vi.fn((query: string) => ({ matches, media: query })); + window.matchMedia = mm as unknown as typeof window.matchMedia; + return mm; +} + +describe('prefersReducedMotion', () => { + afterEach(() => { + window.matchMedia = realMatchMedia; + }); + + it('returns true when the user prefers reduced motion', () => { + stubMatchMedia(true); + expect(prefersReducedMotion()).toBe(true); + }); + + it('returns false when the user has no reduced-motion preference', () => { + stubMatchMedia(false); + expect(prefersReducedMotion()).toBe(false); + }); + + it('queries the prefers-reduced-motion: reduce feature each call (live read)', () => { + const mm = stubMatchMedia(false); + prefersReducedMotion(); + prefersReducedMotion(); + expect(mm).toHaveBeenCalledTimes(2); + expect(mm).toHaveBeenCalledWith('(prefers-reduced-motion: reduce)'); + }); +}); diff --git a/src/utils/prefersReducedMotion.ts b/src/utils/prefersReducedMotion.ts new file mode 100644 index 0000000..4438eb9 --- /dev/null +++ b/src/utils/prefersReducedMotion.ts @@ -0,0 +1,9 @@ +/** + * Live read of the user's reduced-motion preference. Call this per action (per + * click, per gesture) instead of caching the result, so JS-driven motion honors + * the current OS setting even if it's toggled mid-session — matching how the CSS + * `prefers-reduced-motion` media query reacts. + */ +export function prefersReducedMotion(): boolean { + return window.matchMedia('(prefers-reduced-motion: reduce)').matches; +}