- add --color-primary-text for lime used as text or icon color - stop dimming the idle refresh label with opacity - darken the light danger button and lighten the dark danger hover - define syntax highlighting colors per theme as --hl-* tokens - darken light muted text slightly - add a storybook contrast page, fail storybook tests on a11y violations and show live token values in the colors story - bump version to 1.20.2
331 lines
11 KiB
TypeScript
331 lines
11 KiB
TypeScript
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<Rgba>((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<string>();
|
|
const results: Measurement[] = [];
|
|
for (const el of Array.from(root.querySelectorAll<HTMLElement>('*'))) {
|
|
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 (
|
|
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12, marginTop: 8 }}>
|
|
<tbody>
|
|
{items.map((m) => {
|
|
const pass = m.ratio >= m.required;
|
|
return (
|
|
<tr
|
|
key={`${m.fg}${m.bg}${m.required}`}
|
|
style={{ borderTop: '1px solid var(--color-border)' }}
|
|
>
|
|
<td style={{ padding: '4px 6px' }}>
|
|
<span
|
|
style={{
|
|
display: 'inline-block',
|
|
padding: '1px 6px',
|
|
borderRadius: 3,
|
|
background: m.bg,
|
|
color: m.fg,
|
|
fontFamily: 'monospace',
|
|
}}
|
|
>
|
|
{m.text}
|
|
</span>
|
|
</td>
|
|
<td
|
|
style={{
|
|
padding: '4px 6px',
|
|
fontFamily: 'monospace',
|
|
color: 'var(--color-text-muted)',
|
|
}}
|
|
>
|
|
{m.fg} on {m.bg}
|
|
</td>
|
|
<td
|
|
style={{
|
|
padding: '4px 6px',
|
|
textAlign: 'right',
|
|
fontWeight: 700,
|
|
whiteSpace: 'nowrap',
|
|
color: pass ? 'var(--color-text)' : 'var(--color-danger)',
|
|
}}
|
|
>
|
|
{m.ratio.toFixed(2)}:1 {pass ? '✓' : `✗ needs ${m.required}:1`}
|
|
</td>
|
|
</tr>
|
|
);
|
|
})}
|
|
</tbody>
|
|
</table>
|
|
);
|
|
}
|
|
|
|
/** Renders a sample and measures its text contrast after layout. */
|
|
function Sample({ children }: { children: React.ReactNode }) {
|
|
const ref = useRef<HTMLDivElement>(null);
|
|
const [items, setItems] = useState<Measurement[]>([]);
|
|
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 (
|
|
<div>
|
|
<div ref={ref}>{children}</div>
|
|
<Readout items={items} />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// ── 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: () => (
|
|
<div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
|
|
<AutoRefreshIndicator active pulseKey={1} />
|
|
<AutoRefreshIndicator active={false} />
|
|
<AutoRefreshIndicator active={false} error />
|
|
</div>
|
|
),
|
|
},
|
|
{
|
|
title: 'Danger button',
|
|
note: 'Danger, primary and secondary buttons (text on colored backgrounds).',
|
|
render: () => (
|
|
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
|
<Button variant="danger">Delete</Button>
|
|
<Button variant="danger" size="sm">
|
|
Delete
|
|
</Button>
|
|
<Button variant="primary">Run</Button>
|
|
<Button variant="secondary">Cancel</Button>
|
|
</div>
|
|
),
|
|
},
|
|
{
|
|
title: 'Code highlighting - JavaScript',
|
|
note: 'All --hl-* syntax colors on the page background (step code, snippets).',
|
|
render: () => <CodeBlock language="javascript" code={JS_CODE} />,
|
|
},
|
|
{
|
|
title: 'Code highlighting - JSON',
|
|
note: 'Keys, strings, numbers and literals in JSON step outputs.',
|
|
render: () => <CodeBlock language="json" code={JSON_CODE} />,
|
|
},
|
|
{
|
|
title: 'Muted text',
|
|
note: '--color-text-muted on both background shades (hints, table headers, descriptions).',
|
|
render: () => (
|
|
<div style={{ display: 'flex', gap: 8 }}>
|
|
{['var(--color-bg)', 'var(--color-bg-subtle)'].map((bg) => (
|
|
<span
|
|
key={bg}
|
|
style={{
|
|
background: bg,
|
|
color: 'var(--color-text-muted)',
|
|
padding: '4px 8px',
|
|
fontSize: 13,
|
|
}}
|
|
>
|
|
Last run 2 minutes ago
|
|
</span>
|
|
))}
|
|
</div>
|
|
),
|
|
},
|
|
];
|
|
|
|
function Panel({ theme }: { theme: 'light' | 'dark' }) {
|
|
return (
|
|
<section
|
|
// The dark tokens apply under [data-theme="dark"]; light is the page default
|
|
data-theme={theme === 'dark' ? 'dark' : undefined}
|
|
style={{
|
|
flex: '1 1 420px',
|
|
minWidth: 0,
|
|
padding: 16,
|
|
borderRadius: 8,
|
|
background: 'var(--color-bg)',
|
|
color: 'var(--color-text)',
|
|
border: '1px solid var(--color-border)',
|
|
}}
|
|
>
|
|
<h2 style={{ margin: '0 0 12px', fontSize: 16 }}>
|
|
{theme === 'dark' ? 'Dark theme' : 'Light theme'}
|
|
</h2>
|
|
{ISSUES.map((issue) => (
|
|
<div key={issue.title} style={{ marginBottom: 24 }}>
|
|
<h3 style={{ margin: '0 0 2px', fontSize: 14 }}>{issue.title}</h3>
|
|
<p style={{ margin: '0 0 8px', fontSize: 12, color: 'var(--color-text-muted)' }}>
|
|
{issue.note}
|
|
</p>
|
|
<Sample>{issue.render()}</Sample>
|
|
</div>
|
|
))}
|
|
</section>
|
|
);
|
|
}
|
|
|
|
function ContrastPage() {
|
|
return (
|
|
<div style={{ padding: 16 }}>
|
|
<p
|
|
style={{
|
|
margin: '0 0 16px',
|
|
fontSize: 13,
|
|
color: 'var(--color-text-muted)',
|
|
maxWidth: 820,
|
|
}}
|
|
>
|
|
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.
|
|
</p>
|
|
<div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'flex-start' }}>
|
|
<Panel theme="light" />
|
|
<Panel theme="dark" />
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
const meta: Meta<typeof ContrastPage> = {
|
|
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<typeof ContrastPage>;
|
|
|
|
export const Overview: Story = {};
|