Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions e2e/accessibility.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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('/#/');

Expand Down
5 changes: 3 additions & 2 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<!-- color-scheme on :root/.dark in index.css pins UA surfaces (scrollbars)
to the in-app theme; this meta opts the UA into both schemes first. -->
<!-- color-scheme on :root + html.light/html.dark in index.css pins UA
surfaces (scrollbars etc.) to the in-app theme; this meta opts the UA
into both schemes first. -->
<meta name="color-scheme" content="light dark" />

<!-- HashRouter has no crawlable per-route URLs, so one site-level canonical is correct. -->
Expand Down
15 changes: 14 additions & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<main className={isSwipeMode ? '' : 'pt-14 md:pt-0'}>
<main id="main" tabIndex={-1} className={isSwipeMode ? '' : 'pt-14 md:pt-0'}>
{children}
</main>
);
Expand Down Expand Up @@ -213,6 +213,19 @@ function App() {
<HashRouter>
<LocationAwareErrorBoundary>
<div className="min-h-screen bg-background text-foreground">
<a
href="#main"
className="skip-link"
onClick={(e) => {
// Move focus to <main> 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
</a>
<Header />
<NetworkStatusBar />
<MainContent>
Expand Down
11 changes: 9 additions & 2 deletions src/components/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
}
};

Expand Down
5 changes: 3 additions & 2 deletions src/context/ThemeContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <html>: 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');
Expand Down
20 changes: 20 additions & 0 deletions src/hooks/useSwipeScroll.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });

Expand Down
13 changes: 11 additions & 2 deletions src/hooks/useSwipeScroll.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useState, useRef, useEffect, useLayoutEffect, useCallback } from 'react';
import { useScrollContainer } from './useScrollContainer';
import { prefersReducedMotion } from '../utils/prefersReducedMotion';

const noop = () => undefined;

Expand Down Expand Up @@ -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<typeof setTimeout>[] = [];
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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;
Expand Down
75 changes: 72 additions & 3 deletions src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -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, <html> 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 <meta name="color-scheme"> 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 */
Expand Down Expand Up @@ -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 */
Expand All @@ -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 <html>; 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);
Expand Down Expand Up @@ -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 <main> 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);
Expand Down
34 changes: 34 additions & 0 deletions src/utils/prefersReducedMotion.test.ts
Original file line number Diff line number Diff line change
@@ -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)');
});
});
9 changes: 9 additions & 0 deletions src/utils/prefersReducedMotion.ts
Original file line number Diff line number Diff line change
@@ -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;
}