diff --git a/docs/plans/2026-11-07-issue-7-contrast-and-target-size.md b/docs/plans/2026-11-07-issue-7-contrast-and-target-size.md new file mode 100644 index 0000000..d7b0dde --- /dev/null +++ b/docs/plans/2026-11-07-issue-7-contrast-and-target-size.md @@ -0,0 +1,89 @@ +# Plan: Secondary text fails WCAG contrast (2.48:1) and controls are below 24px target size (issue #7) + +Risk tier: Medium. CSS-only presentation change (colors, control sizes, a reduced-motion block) plus a token test. Rendered contrast, hit areas, and emulated reduced motion cannot be proven in jsdom, so a live browser drive is required, and it alters existing visuals that #4 and #5 tuned (focus rings, 375/768/1440 layout). No API, store, data, or security code is touched. + +Domain skills: +- superpowers:test-driven-development: invoke. +- chrome-devtools-mcp:a11y-debugging: invoke for the live drive (contrast, tap targets, reduced motion). If the chrome-devtools MCP fails (locked profile), use Playwright via npx instead. +- frontend-design: not applicable because the user fixed the visual direction: keep the dark HUD identity and make the smallest color and size change that passes. +- vercel-react-best-practices: not applicable because no React logic changes. +- dataviz, django, fastapi, expo, payments, email: not applicable because none of that is touched. + +## Acceptance criteria + +1. Every text color/background pair actually used in `src/index.css` meets 4.5:1 (all text here is under 18.66px bold / 24px, so the large-text 3:1 exception never applies). Backgrounds are modeled as rendered: + - Header (`.app-header`, not over the map): `--bg-panel` composited over `--bg-void`. + - Layer panel, GPU panel, popup rows (all float over the map canvas, which can show anything): `--bg-panel` composited over `#ffffff`, the worst case. + - Hovered layer row (every text inside a `.layer-row`, and the off dot at 3:1): `--accent-glow` (the `.layer-row:hover` background) composited over `--bg-panel` over `#ffffff`. + - Popup header (opaque): `--bg-deep`. + - Classification badge: `--bg-void` text on `--accent`. + - Text with `opacity` is composited at that opacity before measuring. +2. Non-text UI parts that identify a control or its state meet 3:1 (WCAG 1.4.11) against the same worst-case panel background: the slider track, the slider thumb, the off-state layer dot. +3. Every interactive target is at least 24x24 CSS px (WCAG 2.5.8): popup Close button at least 24x24; stress slider input box at least 24px tall (full width); slider thumb box at least 24x24 in both WebKit and Firefox pseudo-elements; layer rows, the narrow "Sensor layers" toggle, and MapLibre's attribution button measured in the browser and at least 24x24. +4. With `prefers-reduced-motion: reduce`, no CSS animation or transition runs: `.panel-indicator` (blink-pulse), `.feature-popup` (slide-up on wide, fade-in on narrow from #5), and the hover transitions all compute `animation-name: none` and zero transition duration. Without the preference, the animations still run as before. +5. A unit test computes WCAG contrast from the `:root` token values parsed out of `src/index.css` for every pair in criteria 1 and 2, and fails if any `color:` declaration in `src/index.css` is not covered by that pair table (so a new text color cannot slip in unmeasured). It also asserts criterion 3's CSS sizes and criterion 4's reduced-motion block. +6. The #4 and #5 work is preserved: all existing tests pass unchanged; focus rings unchanged; at 375x812, 768x1024, and 1440x900 the #5 checks still hold (header elements do not overlap pairwise; `.app-header`, `.layer-panel`, `.gpu-info-panel`, and an open `.feature-popup` stay inside the viewport; the popup and GPU panel do not overlap at 768; `.stress-count` fits "5.0M PTS"). +7. Dark HUD identity kept: hues unchanged; `--text-dim` stays visibly dimmer than `--text-primary`. + +## Decisions + +- `--text-dim`: `#2d5a42` -> `#5aa37f`. It is the smallest step along the line from the original value toward `--text-primary` (`#6ec49a`, same hue family, t=0.69) that clears 4.5:1 on every background once the hover state is in scope. The first value, `#4f9170`, passed the resting pairs (4.66:1 on `--bg-panel` over white) but review found a hovered OFF row puts `.layer-toggle.off` on `--accent-glow` over the panel, which is 3.72:1 over white. A token step was chosen over a new hover `color:` rule, which the coverage check in `src/styles.test.js` would (correctly) reject without a table entry. Numbers for `#5aa37f`: hovered row over white 4.62:1, `--bg-panel` over white 5.79:1, `--bg-deep` 6.53:1, header 6.55:1; `--text-primary` is still 1.44:1 brighter. (The issue's suggested `#5f9c7c` gives about 6.1:1 on the panel.) +- Side effect on non-text uses of `--text-dim` (delta review): the lighter token narrows two luminance cues that now rest on hue. The sparkline's history bars against the latest `--blue` bar drop from 3.09:1 to 1.17:1, and an off layer dot against the on colors drops (heatmap `#ff44ff` 2.84 to 1.08, airports 4.15 to 1.58, ports 5.91 to 2.25). Neither is a WCAG failure: the ON/OFF text states the layer state (1.4.1), and the sparkline is a decorative trend whose value is printed as text. Accepted to keep the change to one token; noted in the PR. +- MapLibre attribution: no change. Review raised the non-compact bar (50% white, links `rgba(0, 0, 0, 0.75)`, about 4.1:1 over black), but MapLibre 6 defaults `compact: true` (`defaultAttributionControlOptions` in `maplibre-gl-dev.mjs`), so with this app's config only the compact control renders: opaque `#fff`, text `#000` (21:1), links `rgba(0, 0, 0, 0.75)` (10.4:1), confirmed in the live drive at 1440 and 375. +- `.gpu-info-sep` loses `opacity: 0.5`: at half opacity even the new dim is about 2.3:1. It shows only above 1024px. +- No other text color changes: `--text-primary`, `--text-bright`, `--accent`, `--amber`, `--red` (about 4.8:1 worst case), `--blue` all already pass; the test proves it. +- 12px minimum font size (the issue's "consider"): not done. Raising the 8 to 11px text (badge, status, GPU panel, panel labels) would undo the 641px header spacing and the GPU panel widths that #5 tuned. Noted in the PR as a follow-up. + +## Files that change + +- `src/index.css`: + - `:root`: `--text-dim: #5aa37f` (first `#4f9170`; stepped further for the hovered row, see Decisions). + - `.gpu-info-sep`: remove `opacity: 0.5`. + - `.popup-close`: `width: 24px; height: 24px` (was 20). Nothing else in the rule changes. + - `.stress-slider`: `height: 24px; background: transparent` (the input box becomes the 24px-tall hit area). Draw the visible track with `::-webkit-slider-runnable-track { height: 4px; background: var(--text-dim) }` and `::-moz-range-track { height: 4px; background: var(--text-dim) }` (4px, up from 2px, for visibility). + - Thumbs (`::-webkit-slider-thumb` and `::-moz-range-thumb`): 24x24 box, `border: none`, transparent base, with the visible square and its glow painted by backgrounds so the look stays close to today: `background: linear-gradient(var(--blue), var(--blue)) center / 12px 12px no-repeat, radial-gradient(closest-side, rgba(0, 170, 255, 0.45), transparent)`; drop `box-shadow` (it would glow around the 24px box). WebKit thumb needs `margin-top: -10px` to center on the 4px track ((4 - 24) / 2). The `:focus-visible` outline on the input stays. + - New last block: + ```css + @media (prefers-reduced-motion: reduce) { + *, *::before, *::after { + animation: none !important; + transition: none !important; + } + } + ``` + `!important` is needed to beat the narrow block's later `animation-name: fade-in` and any library animation. `.panel-indicator` then sits at its base `opacity: 1`. +- `src/styles.test.js` (new): reads `src/index.css` with `readFileSync` (pattern from `src/manifest.test.js`), strips comments, parses `:root` custom properties (hex and `rgba()`), implements WCAG relative luminance and contrast, alpha compositing, and asserts: + - the pair table for criteria 1 and 2 (selector, foreground token, background model, required ratio), each pair at or above its ratio, with the computed ratio in the assertion message; + - coverage: every innermost rule in the file with a `color:` declaration has its selector in the pair table; + - `.popup-close` width and height >= 24px; `.stress-slider` height >= 24px; both thumb pseudo-element rules width and height >= 24px; + - the `@media (prefers-reduced-motion: reduce)` block exists and sets `animation: none !important` and `transition: none !important` on `*`; + - a sanity check of the contrast function itself: black on white is 21:1, and the old `#2d5a42` on `#020c18` is about 2.48:1 (matches the issue). +- `src/styles.states.test.js` (new, added after review; `src/styles.test.js` stays unchanged): models the hovered-row background and asserts every text inside a `.layer-row` (`.layer-label`, `.layer-row.active .layer-label`, `.layer-toggle.on`, `.layer-toggle.off`, each with any hover override) at 4.5:1 and the off dot at 3:1; fails if any rule whose selector has `:hover`, `:focus`, `:focus-visible`, `:active`, or `:has(` sets `background`/`background-color` without being in its state-background table. +- `README.md`: only if a line becomes false (none expected). Phase 8 checks. + +## Order of work + +1. Write `src/styles.test.js`; run it red against current CSS (contrast for dim pairs, close size, thumb size, slider height, reduced-motion block all fail). Commit it alone red: `test: add failing contrast, target size, and reduced motion checks (#7)`. +2. CSS changes; test green. Commit `fix: raise secondary text contrast, enlarge close and slider targets, honor reduced motion (#7)`. +3. Full gate. +4. Live drive (below); tune only inside the named selectors; rerun the gate after any tuning. + +## Risks + +- Range input styling differs per engine: with `appearance: none`, Chrome needs the runnable-track pseudo or the input's own background becomes the track; Firefox uses `::-moz-range-track`. Verify the thumb centers on the track and that dragging and clicking the track still work. +- The 24px slider grows the layer panel by about 22px; on narrow screens the panel is capped and scrolls (#5), so check 375x812 expanded and the 768 and 1440 layouts. +- The 24px Close grows the sticky popup header by a few px; check Close is still topmost and inside the viewport at 375. +- A universal reduced-motion rule also stops MapLibre's own CSS animations and transitions; that is the user's stated preference. JS camera motion is not involved: the app has no `flyTo`/`easeTo`. +- Lighthouse (axe) can mark contrast over the map canvas as "incomplete" rather than failed, so its color-contrast audit may pass before and after; that is why the token test and the drive's computed checks are the primary proof. +- Choosing not to: restructure markup (for example `aria-hidden` on separators), change fonts or sizes beyond the targets, or change any token other than `--text-dim`. + +## Proof + +- `src/styles.test.js` covers criteria 1, 2, 3 (CSS sizes), 4 (CSS block), and 5. Red output before the fix is the commit of step 1. +- Existing suites unchanged and passing: criterion 6 (#4 behavior). +- Live drive against `npm run build` + `npm run preview` (dev server only if needed to open the popup, for example by `await import('/src/store/mapStore.js')` in the page and calling `setSelectedFeature`), headless Chrome via Playwright run with npx: + - criterion 3: `getBoundingClientRect()` of `.popup-close`, `.stress-slider`, each `.layer-row`, the narrow `.panel-toggle`, and `.maplibregl-ctrl-attrib-button` if present; thumb size from the drive (for example a screenshot crop or computed style where the engine exposes it); clicking the track and dragging the thumb still change the value. + - criterion 1 in the browser: computed `color` of the dim-text elements equals the new token; MapLibre attribution text contrast computed from its computed styles. + - criterion 4: with `reducedMotion: 'reduce'`, computed `animationName` of `.panel-indicator` and an open `.feature-popup` at 1440 and 375 is `none`, and `transitionDuration` of `.layer-row` is `0s`; without it, `blink-pulse`, `slide-up`, and `fade-in` respectively. + - criterion 6: the #5 geometry checks at 375x812, 768x1024, 1440x900 (with popup open at each, and layer panel expanded at 375). + - Lighthouse: `npx lighthouse@12 --only-categories=accessibility` headless, desktop preset and default mobile, recording score, `color-contrast`, and `target-size`. Baseline on `origin/main` (0131dc1), recorded by the coordinator: score 1 on both, `color-contrast` pass and `target-size` pass with no items on both, which is the "incomplete over canvas" limitation in Risks. diff --git a/src/index.css b/src/index.css index c6b00c2..dca8cff 100644 --- a/src/index.css +++ b/src/index.css @@ -15,7 +15,7 @@ --green: #00ff8c; --text-bright: #d4fce8; --text-primary: #6ec49a; - --text-dim: #2d5a42; + --text-dim: #5aa37f; --border: rgba(0, 255, 136, 0.14); --border-active: rgba(0, 255, 136, 0.38); --font-mono: 'Share Tech Mono', 'Courier New', monospace; @@ -406,8 +406,10 @@ body::before { width: 100%; -webkit-appearance: none; appearance: none; - height: 2px; - background: var(--text-dim); + /* The input box is the 24px-tall hit area; the visible track is drawn by + the track pseudo-elements below. */ + height: 24px; + background: transparent; cursor: pointer; } @@ -416,23 +418,39 @@ body::before { outline-offset: 4px; } +.stress-slider::-webkit-slider-runnable-track { + height: 4px; + background: var(--text-dim); +} + +.stress-slider::-moz-range-track { + height: 4px; + background: var(--text-dim); +} + +/* 24x24 thumb box for the hit area; the visible 12px square and its glow are + painted by backgrounds so the look stays small. */ .stress-slider::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; - width: 10px; - height: 10px; - background: var(--blue); + width: 24px; + height: 24px; + margin-top: -10px; + border: none; + background: + linear-gradient(var(--blue), var(--blue)) center / 12px 12px no-repeat, + radial-gradient(closest-side, rgba(0, 170, 255, 0.45), transparent); cursor: pointer; - box-shadow: 0 0 6px var(--blue); } .stress-slider::-moz-range-thumb { - width: 10px; - height: 10px; - background: var(--blue); + width: 24px; + height: 24px; border: none; + background: + linear-gradient(var(--blue), var(--blue)) center / 12px 12px no-repeat, + radial-gradient(closest-side, rgba(0, 170, 255, 0.45), transparent); cursor: pointer; - box-shadow: 0 0 6px var(--blue); } .stress-count { @@ -509,8 +527,8 @@ body::before { color: var(--text-dim); cursor: pointer; font-size: 11px; - width: 20px; - height: 20px; + width: 24px; + height: 24px; display: flex; align-items: center; justify-content: center; @@ -621,7 +639,6 @@ body::before { .gpu-info-sep { color: var(--text-dim); - opacity: 0.5; } /* ─── RESPONSIVE ─── */ @@ -748,3 +765,14 @@ body::before { white-space: nowrap; border: 0; } + +/* ─── REDUCED MOTION ─── */ + +/* !important beats the narrow block's later animation-name and any library + animation. */ +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { + animation: none !important; + transition: none !important; + } +} diff --git a/src/styles.states.test.js b/src/styles.states.test.js new file mode 100644 index 0000000..2da6727 --- /dev/null +++ b/src/styles.states.test.js @@ -0,0 +1,160 @@ +import { describe, it, expect } from 'vitest' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { dirname, resolve } from 'node:path' + +// Contrast in interactive states (hover, focus, active, :has()). The resting +// state is covered by styles.test.js. + +const here = dirname(fileURLToPath(import.meta.url)) +const css = readFileSync(resolve(here, 'index.css'), 'utf8').replace(/\/\*[\s\S]*?\*\//g, '') + +function innermostRules(source) { + const rules = [] + const re = /([^{}]+)\{([^{}]*)\}/g + let m + while ((m = re.exec(source)) !== null) { + rules.push({ selector: m[1].trim().replace(/\s+/g, ' '), body: m[2] }) + } + return rules +} + +function declarations(body) { + const decls = {} + for (const part of body.split(';')) { + const idx = part.indexOf(':') + if (idx === -1) continue + const prop = part.slice(0, idx).trim() + if (prop) decls[prop] = part.slice(idx + 1).trim() + } + return decls +} + +const RULES = innermostRules(css) + +function rule(selector) { + const found = RULES.filter((r) => r.selector === selector) + if (found.length === 0) throw new Error(`rule not found: ${selector}`) + return found.map((r) => declarations(r.body)).reduce((a, b) => ({ ...a, ...b }), {}) +} + +function parseColor(value) { + const v = value.trim() + const hex = v.match(/^#([0-9a-f]{6})$/i) + if (hex) { + const n = parseInt(hex[1], 16) + return { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255, a: 1 } + } + const rgba = v.match(/^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*(?:,\s*([\d.]+)\s*)?\)$/i) + if (rgba) { + return { + r: Number(rgba[1]), + g: Number(rgba[2]), + b: Number(rgba[3]), + a: rgba[4] === undefined ? 1 : Number(rgba[4]), + } + } + throw new Error(`unsupported color: ${value}`) +} + +function token(name) { + const value = rule(':root')[name] + if (!value) throw new Error(`token not found: ${name}`) + return parseColor(value) +} + +function varName(value) { + const m = value && value.match(/var\((--[\w-]+)\)/) + return m ? m[1] : null +} + +function composite(fg, bg) { + const a = fg.a + return { + r: fg.r * a + bg.r * (1 - a), + g: fg.g * a + bg.g * (1 - a), + b: fg.b * a + bg.b * (1 - a), + a: 1, + } +} + +function luminance({ r, g, b }) { + const lin = (c) => { + const s = c / 255 + return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4 + } + return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b) +} + +function contrast(a, b) { + const la = luminance(a) + const lb = luminance(b) + return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05) +} + +const WHITE = { r: 255, g: 255, b: 255, a: 1 } + +// Hovered layer row: the :hover background over the panel over the worst-case +// white map. +function hoveredRowBackground() { + const hoverBg = varName(rule('.layer-row:hover').background) + if (!hoverBg) throw new Error('.layer-row:hover background is not a token') + return composite(token(hoverBg), composite(token('--bg-panel'), WHITE)) +} + +// Every rule with a state selector that sets a background, and how it is modeled. +const STATE_BACKGROUNDS = { + '.layer-row:hover': hoveredRowBackground, +} + +// Text inside a .layer-row. The first selector found wins, so a hover-specific +// override (if one is ever added) is measured in place of the base rule. +const HOVERED_ROW_TEXT = [ + { name: 'layer label', selectors: ['.layer-row:hover .layer-label', '.layer-label'] }, + { + name: 'active layer label', + selectors: ['.layer-row.active:hover .layer-label', '.layer-row.active .layer-label'], + }, + { name: 'ON toggle', selectors: ['.layer-row:hover .layer-toggle.on', '.layer-toggle.on'] }, + { name: 'OFF toggle', selectors: ['.layer-row:hover .layer-toggle.off', '.layer-toggle.off'] }, +] + +function effectiveColorToken(selectors) { + for (const s of selectors) { + if (!RULES.some((r) => r.selector === s)) continue + const color = rule(s).color + if (color) return { selector: s, token: varName(color) } + } + throw new Error(`no color rule for ${selectors.join(' | ')}`) +} + +describe('hovered layer row contrast', () => { + it.each(HOVERED_ROW_TEXT)('$name meets 4.5:1 on the hovered row', ({ name, selectors }) => { + const bg = hoveredRowBackground() + const { selector, token: t } = effectiveColorToken(selectors) + expect(t, `${selector}: color is not a token`).toBeTruthy() + const ratio = contrast(composite(token(t), bg), bg) + expect(ratio, `${name} (${selector}, ${t}) on hovered row is ${ratio.toFixed(2)}:1`).toBeGreaterThanOrEqual(4.5) + }) + + it('off-state dot meets 3:1 on the hovered row', () => { + // Off-state dot color is set inline in LayerPanel.jsx. + const bg = hoveredRowBackground() + const ratio = contrast(composite(token('--text-dim'), bg), bg) + expect(ratio, `--text-dim dot on hovered row is ${ratio.toFixed(2)}:1`).toBeGreaterThanOrEqual(3) + }) +}) + +describe('state background coverage', () => { + it('models every state rule that sets a background', () => { + const STATE = /:hover|:focus|:focus-visible|:active|:has\(/ + const uncovered = RULES.filter((r) => STATE.test(r.selector)) + .filter((r) => { + const d = declarations(r.body) + return 'background' in d || 'background-color' in d + }) + .map((r) => r.selector) + .filter((s) => !(s in STATE_BACKGROUNDS)) + expect(uncovered).toEqual([]) + }) +}) diff --git a/src/styles.test.js b/src/styles.test.js new file mode 100644 index 0000000..106856a --- /dev/null +++ b/src/styles.test.js @@ -0,0 +1,289 @@ +import { describe, it, expect } from 'vitest' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { dirname, resolve } from 'node:path' + +const here = dirname(fileURLToPath(import.meta.url)) +const css = readFileSync(resolve(here, 'index.css'), 'utf8').replace(/\/\*[\s\S]*?\*\//g, '') + +// ─── CSS parsing ─── + +function normalizeSelector(sel) { + return sel.trim().replace(/\s+/g, ' ') +} + +// Innermost rules: a selector followed by a body that contains no braces. +function innermostRules(source) { + const rules = [] + const re = /([^{}]+)\{([^{}]*)\}/g + let m + while ((m = re.exec(source)) !== null) { + rules.push({ selector: normalizeSelector(m[1]), body: m[2] }) + } + return rules +} + +function declarations(body) { + const decls = {} + for (const part of body.split(';')) { + const idx = part.indexOf(':') + if (idx === -1) continue + const prop = part.slice(0, idx).trim() + const value = part.slice(idx + 1).trim() + if (prop) decls[prop] = value + } + return decls +} + +const RULES = innermostRules(css) + +function rule(selector) { + const found = RULES.filter((r) => r.selector === selector) + if (found.length === 0) throw new Error(`rule not found: ${selector}`) + return found.map((r) => declarations(r.body)).reduce((a, b) => ({ ...a, ...b }), {}) +} + +function parseColor(value) { + const v = value.trim() + const hex = v.match(/^#([0-9a-f]{6})$/i) + if (hex) { + const n = parseInt(hex[1], 16) + return { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255, a: 1 } + } + const rgba = v.match(/^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*(?:,\s*([\d.]+)\s*)?\)$/i) + if (rgba) { + return { + r: Number(rgba[1]), + g: Number(rgba[2]), + b: Number(rgba[3]), + a: rgba[4] === undefined ? 1 : Number(rgba[4]), + } + } + throw new Error(`unsupported color: ${value}`) +} + +const TOKENS = (() => { + const root = rule(':root') + const tokens = {} + for (const [prop, value] of Object.entries(root)) { + if (!prop.startsWith('--')) continue + try { + tokens[prop] = parseColor(value) + } catch { + // non-color token (fonts) + } + } + return tokens +})() + +function token(name) { + const c = TOKENS[name] + if (!c) throw new Error(`token not found: ${name}`) + return c +} + +function varName(value) { + const m = value.match(/var\((--[\w-]+)\)/) + return m ? m[1] : null +} + +// ─── WCAG math ─── + +function composite(fg, bg, extraAlpha = 1) { + const a = fg.a * extraAlpha + return { + r: fg.r * a + bg.r * (1 - a), + g: fg.g * a + bg.g * (1 - a), + b: fg.b * a + bg.b * (1 - a), + a: 1, + } +} + +function luminance({ r, g, b }) { + const lin = (c) => { + const s = c / 255 + return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4 + } + return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b) +} + +function contrast(a, b) { + const la = luminance(a) + const lb = luminance(b) + return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05) +} + +const WHITE = { r: 255, g: 255, b: 255, a: 1 } + +// Background models, as rendered. +const BACKGROUNDS = { + // .app-header sits above the map, over the page background. + header: () => composite(token('--bg-panel'), token('--bg-void')), + // Layer panel, GPU panel, popup rows float over the map canvas: worst case white. + overMap: () => composite(token('--bg-panel'), WHITE), + // Opaque sticky popup header. + popupHeader: () => token('--bg-deep'), + // Classification badge fill. + accent: () => token('--accent'), + // Page background. + void: () => token('--bg-void'), +} + +// Every rule in index.css that declares color:, with the background it renders on. +// fg is the token the text resolves to (for inherit, the inherited token). +const TEXT_PAIRS = [ + { selector: 'html, body, #root', bg: 'void' }, + { selector: '.app-title', bg: 'header' }, + { selector: '.classification-badge', bg: 'accent' }, + { selector: '.header-sep', bg: 'header' }, + { selector: '.header-status', bg: 'header' }, + { selector: '.header-status .ok', bg: 'header' }, + { selector: '.header-status .warn', bg: 'header' }, + { selector: '.coord-display', bg: 'header' }, + { selector: '.time-display', bg: 'header' }, + { selector: '.panel-title', bg: 'overMap' }, + { selector: '.panel-toggle', bg: 'overMap', fg: '--text-primary' }, + { selector: '.panel-chevron', bg: 'overMap' }, + { selector: '.layer-label', bg: 'overMap' }, + { selector: '.layer-row.active .layer-label', bg: 'overMap' }, + { selector: '.layer-toggle.on', bg: 'overMap' }, + { selector: '.layer-toggle.off', bg: 'overMap' }, + { selector: '.footer-stat', bg: 'overMap' }, + { selector: '.stress-count', bg: 'overMap' }, + { selector: '.popup-title', bg: 'popupHeader' }, + { selector: '.popup-close', bg: 'popupHeader' }, + { selector: '.popup-close:hover', bg: 'popupHeader' }, + { selector: '.prop-key', bg: 'overMap' }, + { selector: '.prop-val', bg: 'overMap' }, + { selector: '.gpu-info-key', bg: 'overMap' }, + { selector: '.gpu-info-val', bg: 'overMap' }, + { selector: '.gpu-info-val.ok', bg: 'overMap' }, + { selector: '.gpu-info-val.warn', bg: 'overMap' }, + { selector: '.gpu-info-val.err', bg: 'overMap' }, + { selector: '.gpu-info-sep', bg: 'overMap' }, +] + +function textRatio({ selector, bg, fg }) { + const decls = rule(selector) + const fgName = fg || varName(decls.color) + if (!fgName) throw new Error(`${selector}: color is not a token (${decls.color})`) + const opacity = decls.opacity === undefined ? 1 : Number(decls.opacity) + const background = BACKGROUNDS[bg]() + const rendered = composite(token(fgName), background, opacity) + return { ratio: contrast(rendered, background), fgName, opacity } +} + +function px(value) { + const m = value && value.match(/^([\d.]+)px$/) + return m ? Number(m[1]) : NaN +} + +function mediaBlock(prelude) { + const start = css.indexOf(prelude) + if (start === -1) return null + const open = css.indexOf('{', start) + let depth = 0 + for (let i = open; i < css.length; i++) { + if (css[i] === '{') depth++ + else if (css[i] === '}') { + depth-- + if (depth === 0) return css.slice(open + 1, i) + } + } + return null +} + +// ─── Tests ─── + +describe('contrast math', () => { + it('computes black on white as 21:1', () => { + expect(contrast({ r: 0, g: 0, b: 0, a: 1 }, WHITE)).toBeCloseTo(21, 5) + }) + + it('computes the old #2d5a42 on #020c18 as about 2.48:1 (issue #7)', () => { + expect(contrast(parseColor('#2d5a42'), parseColor('#020c18'))).toBeCloseTo(2.48, 2) + }) +}) + +describe('text contrast (WCAG 1.4.3, 4.5:1)', () => { + it.each(TEXT_PAIRS)('$selector on $bg', (pair) => { + const { ratio, fgName, opacity } = textRatio(pair) + expect( + ratio, + `${pair.selector}: ${fgName} at opacity ${opacity} on ${pair.bg} is ${ratio.toFixed(2)}:1` + ).toBeGreaterThanOrEqual(4.5) + }) + + it('covers every rule that declares color:', () => { + const covered = new Set(TEXT_PAIRS.map((p) => p.selector)) + const uncovered = RULES.filter((r) => /(?:^|[;\s])color\s*:/.test(r.body)) + .map((r) => r.selector) + .filter((s) => !covered.has(s)) + expect(uncovered).toEqual([]) + }) +}) + +describe('non-text contrast (WCAG 1.4.11, 3:1)', () => { + const overMap = BACKGROUNDS.overMap() + + const cases = [ + { + name: 'slider track (webkit)', + tokenName: () => varName(rule('.stress-slider::-webkit-slider-runnable-track').background), + }, + { + name: 'slider track (moz)', + tokenName: () => varName(rule('.stress-slider::-moz-range-track').background), + }, + { + name: 'slider thumb (webkit)', + tokenName: () => varName(rule('.stress-slider::-webkit-slider-thumb').background), + }, + { + name: 'slider thumb (moz)', + tokenName: () => varName(rule('.stress-slider::-moz-range-thumb').background), + }, + // Off-state dot color is set inline in LayerPanel.jsx. + { name: 'off-state layer dot', tokenName: () => '--text-dim' }, + ] + + it.each(cases)('$name', ({ name, tokenName }) => { + const t = tokenName() + expect(t, `${name}: no token found`).toBeTruthy() + const ratio = contrast(composite(token(t), overMap), overMap) + expect(ratio, `${name}: ${t} on overMap is ${ratio.toFixed(2)}:1`).toBeGreaterThanOrEqual(3) + }) +}) + +describe('target size (WCAG 2.5.8, 24x24)', () => { + it('popup Close is at least 24x24', () => { + const d = rule('.popup-close') + expect(px(d.width)).toBeGreaterThanOrEqual(24) + expect(px(d.height)).toBeGreaterThanOrEqual(24) + }) + + it('stress slider input is at least 24px tall', () => { + expect(px(rule('.stress-slider').height)).toBeGreaterThanOrEqual(24) + }) + + it.each(['.stress-slider::-webkit-slider-thumb', '.stress-slider::-moz-range-thumb'])( + '%s is at least 24x24', + (selector) => { + const d = rule(selector) + expect(px(d.width)).toBeGreaterThanOrEqual(24) + expect(px(d.height)).toBeGreaterThanOrEqual(24) + } + ) +}) + +describe('reduced motion (WCAG 2.3.3)', () => { + it('disables animations and transitions under prefers-reduced-motion: reduce', () => { + const block = mediaBlock('@media (prefers-reduced-motion: reduce)') + expect(block, 'no @media (prefers-reduced-motion: reduce) block').not.toBeNull() + const universal = innermostRules(block).find((r) => r.selector === '*, *::before, *::after') + expect(universal, 'no universal rule in the reduced-motion block').toBeTruthy() + const d = declarations(universal.body) + expect(d.animation).toBe('none !important') + expect(d.transition).toBe('none !important') + }) +})