import React, { useLayoutEffect, useRef, useState } from 'react'; import type { Meta, StoryObj } from '@storybook/react-vite'; import { AutoRefreshIndicator } from '../../src/ui/AutoRefreshIndicator/AutoRefreshIndicator'; import { Button } from '../../src/ui/Button/Button'; import { CodeBlock } from '../../src/ui/CodeBlock/CodeBlock'; /* * Text contrast review page (WCAG AA: 4.5:1 for normal text, 3:1 for large * text) for the components where contrast is easiest to get wrong: light * brand colors used as text, dimmed labels, colored buttons and syntax * highlighting. Every sample is the real component, shown in both themes, and * the contrast of each piece of text is measured live from the rendered * colors - so this page stays accurate as the design tokens change. */ // ── Contrast measurement ───────────────────────────────────────────────────── type Rgba = [number, number, number, number]; function parseColor(value: string): Rgba { const parts = value.match(/[\d.]+/g)?.map(Number) ?? [0, 0, 0]; return [parts[0], parts[1], parts[2], parts[3] ?? 1]; } function luminance([r, g, b]: Rgba): number { const channel = (c: number) => { const s = c / 255; return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; }; return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b); } function contrast(a: Rgba, b: Rgba): number { const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x); return (hi + 0.05) / (lo + 0.05); } /** Blends `top` over an opaque `bottom`. */ function blend(top: Rgba, bottom: Rgba): Rgba { const a = top[3]; return [0, 1, 2].map((i) => top[i] * a + bottom[i] * (1 - a)).concat(1) as Rgba; } /** Product of the `opacity` of `el` and its ancestors (e.g. a dimmed idle label). */ function opacityChain(el: Element): number { let opacity = 1; for (let node: Element | null = el; node; node = node.parentElement) { opacity *= parseFloat(getComputedStyle(node).opacity); } return opacity; } /** The opaque color behind `el`, from its own and its ancestors' backgrounds. */ function effectiveBackground(el: Element): Rgba { const layers: Rgba[] = []; for (let node: Element | null = el; node; node = node.parentElement) { const bg = parseColor(getComputedStyle(node).backgroundColor); bg[3] *= opacityChain(node); if (bg[3] > 0) layers.push(bg); if (bg[3] >= 1) break; } return layers.reduceRight((under, layer) => blend(layer, under), [255, 255, 255, 1]); } const hex = ([r, g, b]: Rgba) => '#' + [r, g, b].map((c) => Math.round(c).toString(16).padStart(2, '0')).join(''); interface Measurement { text: string; fg: string; bg: string; ratio: number; required: number; } /** Measures every element that directly contains visible text. */ function measure(root: HTMLElement): Measurement[] { const seen = new Set(); const results: Measurement[] = []; for (const el of Array.from(root.querySelectorAll('*'))) { const text = Array.from(el.childNodes) .filter((n) => n.nodeType === Node.TEXT_NODE) .map((n) => n.textContent ?? '') .join('') .trim(); if (!text || el.closest('[aria-hidden="true"]')) continue; const style = getComputedStyle(el); const fontSize = parseFloat(style.fontSize); const bold = Number(style.fontWeight) >= 700; // WCAG "large text": at least 24px, or 18.66px bold const required = fontSize >= 24 || (bold && fontSize >= 18.66) ? 3 : 4.5; const bgColor = effectiveBackground(el); const fg = parseColor(style.color); fg[3] *= opacityChain(el); const fgColor = blend(fg, bgColor); const key = `${hex(fgColor)}|${hex(bgColor)}|${required}`; if (seen.has(key)) continue; seen.add(key); results.push({ text: text.length > 28 ? `${text.slice(0, 28)}…` : text, fg: hex(fgColor), bg: hex(bgColor), ratio: contrast(fgColor, bgColor), required, }); } return results.sort((a, b) => a.ratio / a.required - b.ratio / b.required); } function Readout({ items }: { items: Measurement[] }) { return ( {items.map((m) => { const pass = m.ratio >= m.required; return ( ); })}
{m.text} {m.fg} on {m.bg} {m.ratio.toFixed(2)}:1 {pass ? '✓' : `✗ needs ${m.required}:1`}
); } /** Renders a sample and measures its text contrast after layout. */ function Sample({ children }: { children: React.ReactNode }) { const ref = useRef(null); const [items, setItems] = useState([]); useLayoutEffect(() => { const el = ref.current; if (!el) return; // Measure after the theme/styles have applied const frame = requestAnimationFrame(() => setItems(measure(el))); return () => cancelAnimationFrame(frame); }, []); return (
{children}
); } // ── Page ───────────────────────────────────────────────────────────────────── // Covers every syntax color: comment, keyword, string, number, function // (title), params, property const JS_CODE = [ '// Open the app and wait for the dashboard', 'async function openDashboard(context, timeoutMs) {', " const url = context.getEnv('BASE_URL');", ' await context.page.goto(url, { timeout: timeoutMs ?? 30000 });', ' return context.page.title();', '}', ].join('\n'); const JSON_CODE = JSON.stringify( { status: 'pass', attempts: 2, cached: false, output: { title: 'Dashboard' } }, null, 2, ); interface Issue { title: string; note: string; render: () => React.ReactNode; } const ISSUES: Issue[] = [ { title: 'AutoRefreshIndicator label', note: 'Active ("Live", --color-primary-text), idle and error labels (runs pages).', render: () => (
), }, { title: 'Danger button', note: 'Danger, primary and secondary buttons (text on colored backgrounds).', render: () => (
), }, { title: 'Code highlighting - JavaScript', note: 'All --hl-* syntax colors on the page background (step code, snippets).', render: () => , }, { title: 'Code highlighting - JSON', note: 'Keys, strings, numbers and literals in JSON step outputs.', render: () => , }, { title: 'Muted text', note: '--color-text-muted on both background shades (hints, table headers, descriptions).', render: () => (
{['var(--color-bg)', 'var(--color-bg-subtle)'].map((bg) => ( Last run 2 minutes ago ))}
), }, ]; function Panel({ theme }: { theme: 'light' | 'dark' }) { return (

{theme === 'dark' ? 'Dark theme' : 'Light theme'}

{ISSUES.map((issue) => (

{issue.title}

{issue.note}

{issue.render()}
))}
); } function ContrastPage() { return (

Text contrast of the components where it's easiest to get wrong (WCAG AA: 4.5:1 for normal text, 3:1 for large text). Each row is a piece of text in the sample, measured from its rendered colors, worst first.

); } const meta: Meta = { title: 'Accessibility/Contrast', component: ContrastPage, // a11y checks use the project default ('error' in preview.tsx) parameters: { layout: 'fullscreen' }, // The light panel relies on the page default (light) theme globals: { theme: 'light' }, }; export default meta; type Story = StoryObj; export const Overview: Story = {};