Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
ci(studio): ratchet colour contrast of timeline tokens (#4257)
Miguel Ángel86e27b00f602
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 62f2cf24bf..6a3b826674 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -343,6 +343,7 @@ jobs:- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4with:lfs: true+ fetch-depth: 0- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4with:diff --git a/package.json b/package.jsonindex d812a90a72..60a8f9d598 100644--- a/package.json+++ b/package.json@@ -51,7 +51,7 @@"player:perf": "bun run --filter @hyperframes/player perf","format:check": "oxfmt --check .","knip": "knip",- "test:scripts": "node --import tsx --test scripts/animejs-v4-guidance.test.mjs scripts/check-tracked-artifacts.test.mjs scripts/check-no-main-deletions.test.mjs scripts/check-pr-captures.test.mjs scripts/check-docs-snippet-motion.test.mjs scripts/registry-target-paths.test.mjs scripts/check-workspace-contracts.test.mjs scripts/check-media-use-copy-parity.test.mjs scripts/check-package-cycles.test.mjs scripts/check-cli-process-ownership.test.mjs scripts/check-large-files.test.mjs scripts/package-subpaths.test.mjs scripts/validate-release-channel.test.mjs scripts/publish-workflow.test.mjs scripts/install-workspace-dependencies.test.mjs scripts/draft-changelog.test.ts scripts/set-version.test.ts scripts/release-prepare.test.ts scripts/cli-options.test.ts scripts/changelog-weekly.test.ts scripts/claude-plugin-compression.test.ts scripts/catalog-payload-assets.test.ts scripts/host-registry-assets.test.ts scripts/catalog-preview-temp.test.ts scripts/catalog-hosted-files.test.ts scripts/player-cdn-pin.test.ts scripts/studio-runtime-smoke.test.mjs scripts/verify-packed-manifests.test.mjs scripts/lint-skills.test.mjs scripts/creator-editing-recipes.test.mjs packages/gcp-cloud-run/check-dockerfile-workspaces.test.mjs packages/core/scripts/writeGeneratedFile.test.ts scripts/catalog-drift.test.ts scripts/catalog-fetch-mirror.test.ts scripts/catalog-script-inlining.test.ts scripts/catalog-detail.test.ts scripts/generate-catalog-pages.test.ts scripts/verify-catalog-payloads.test.ts scripts/registry-skill-files.test.ts && vitest run scripts/catalog/",+ "test:scripts": "node --import tsx --test scripts/animejs-v4-guidance.test.mjs scripts/check-tracked-artifacts.test.mjs scripts/check-no-main-deletions.test.mjs scripts/check-pr-captures.test.mjs scripts/check-docs-snippet-motion.test.mjs scripts/registry-target-paths.test.mjs scripts/check-workspace-contracts.test.mjs scripts/check-media-use-copy-parity.test.mjs scripts/check-package-cycles.test.mjs scripts/check-cli-process-ownership.test.mjs scripts/check-large-files.test.mjs scripts/package-subpaths.test.mjs scripts/validate-release-channel.test.mjs scripts/publish-workflow.test.mjs scripts/install-workspace-dependencies.test.mjs scripts/draft-changelog.test.ts scripts/set-version.test.ts scripts/release-prepare.test.ts scripts/cli-options.test.ts scripts/changelog-weekly.test.ts scripts/claude-plugin-compression.test.ts scripts/catalog-payload-assets.test.ts scripts/host-registry-assets.test.ts scripts/catalog-preview-temp.test.ts scripts/catalog-hosted-files.test.ts scripts/player-cdn-pin.test.ts scripts/studio-runtime-smoke.test.mjs scripts/verify-packed-manifests.test.mjs scripts/lint-skills.test.mjs scripts/creator-editing-recipes.test.mjs packages/gcp-cloud-run/check-dockerfile-workspaces.test.mjs packages/core/scripts/writeGeneratedFile.test.ts scripts/catalog-drift.test.ts scripts/catalog-fetch-mirror.test.ts scripts/catalog-script-inlining.test.ts scripts/catalog-detail.test.ts scripts/generate-catalog-pages.test.ts scripts/verify-catalog-payloads.test.ts scripts/registry-skill-files.test.ts && vitest run scripts/catalog/ scripts/contrastRatchet.test.ts","typecheck:scripts": "tsc --noEmit -p scripts/tsconfig.json","test:skills": "node --test 'skills/**/*.test.mjs' 'packages/cli/src/media-use/**/*.test.mjs'","generate:previews": "tsx scripts/generate-template-previews.ts",diff --git a/scripts/contrast-baseline.json b/scripts/contrast-baseline.jsonnew file mode 100644index 0000000000..5394a12341--- /dev/null+++ b/scripts/contrast-baseline.json@@ -0,0 +1,15 @@+{+ "dark/ruler-ticks": 3.0215661841856103,+ "dark/pending-track-label": 2.2095660952157443,+ "dark/clip-timecode": 2.9640400066983745,+ "dark/active-clip-timecode": 2.44310754684879,+ "dark/clip-border-exterior": 2.8019036818215706,+ "dark/selected-handle": 2.3925236869074467,+ "dark/active-selected-handle": 2.0618519389873913,+ "dark/hovered-handle": 2.1777784316890663,+ "dark/active-hovered-handle": 1.8873389821795008,+ "dark/dragging-handle": 2.7718581542466456,+ "dark/active-dragging-handle": 2.3310570156777346,+ "dark/quiet-waveform": 2.1687299852625723,+ "dark/active-quiet-waveform": 1.7915634653703223+}diff --git a/scripts/contrast-pairs.json b/scripts/contrast-pairs.jsonnew file mode 100644index 0000000000..11f7ecb67f--- /dev/null+++ b/scripts/contrast-pairs.json@@ -0,0 +1,262 @@+{+ "themes": [+ {+ "id": "dark",+ "selector": "@theme static",+ "canvas": "--timeline-shell-bg",+ "pairs": [+ {+ "id": "ruler-ticks",+ "foreground": "--timeline-tick-text",+ "background": ["--timeline-shell-bg"],+ "role": "text",+ "minimum": 4.5,+ "sources": [+ "packages/studio/src/player/components/TimelineRuler.tsx:105",+ "packages/studio/src/player/components/TimelineRuler.tsx:133"+ ]+ },+ {+ "id": "group-secondary-label",+ "foreground": "--timeline-text-secondary",+ "background": ["--timeline-gutter-bg"],+ "role": "text",+ "minimum": 4.5,+ "sources": [+ "packages/studio/src/player/components/TimelineLayerGroupHeader.tsx:62",+ "packages/studio/src/player/components/TimelineLayerGroupHeader.tsx:86"+ ]+ },+ {+ "id": "pending-track-label",+ "foreground": "--timeline-track-label",+ "background": ["--timeline-row-bg"],+ "role": "text",+ "minimum": 4.5,+ "sources": [+ "packages/studio/src/player/components/TimelineLanes.tsx:270",+ "packages/studio/src/player/components/TimelineLanes.tsx:353",+ "packages/studio/src/player/components/TimelineLanes.tsx:357"+ ],+ "opacity": 0.5+ },+ {+ "id": "clip-label",+ "foreground": "--timeline-track-label",+ "background": ["--timeline-row-bg", "--timeline-clip-bg"],+ "role": "text",+ "minimum": 4.5,+ "sources": [+ "packages/studio/src/styles/studio.css:203",+ "packages/studio/src/styles/studio.css:286"+ ]+ },+ {+ "id": "active-clip-label",+ "foreground": "--timeline-clip-label-active",+ "background": ["--timeline-row-bg", "--timeline-clip-bg", "--timeline-clip-bg-active"],+ "role": "text",+ "minimum": 4.5,+ "sources": [+ "packages/studio/src/styles/studio.css:203",+ "packages/studio/src/styles/studio.css:213",+ "packages/studio/src/styles/studio.css:223",+ "packages/studio/src/styles/studio.css:297"+ ]+ },+ {+ "id": "clip-timecode",+ "foreground": "--timeline-tick-text",+ "background": ["--timeline-row-bg", "--timeline-clip-bg"],+ "role": "text",+ "minimum": 4.5,+ "sources": [+ "packages/studio/src/styles/studio.css:203",+ "packages/studio/src/styles/studio.css:305"+ ]+ },+ {+ "id": "active-clip-timecode",+ "foreground": "--timeline-tick-text",+ "background": ["--timeline-row-bg", "--timeline-clip-bg", "--timeline-clip-bg-active"],+ "role": "text",+ "minimum": 4.5,+ "sources": [+ "packages/studio/src/styles/studio.css:203",+ "packages/studio/src/styles/studio.css:213",+ "packages/studio/src/styles/studio.css:305"+ ]+ },+ {+ "id": "clip-border-exterior",+ "foreground": "--timeline-clip-border",+ "background": ["--timeline-row-bg"],+ "role": "graphic",+ "minimum": 3,+ "sources": [+ "packages/studio/src/styles/studio.css:203",+ "packages/studio/src/styles/studio.css:204",+ "packages/studio/src/player/components/TimelineLanes.tsx:270"+ ],+ "paintBacking": ["--timeline-row-bg", "--timeline-clip-bg"]+ },+ {+ "id": "active-border-exterior",+ "foreground": "--timeline-clip-border-active",+ "background": ["--timeline-row-bg"],+ "role": "graphic",+ "minimum": 3,+ "sources": [+ "packages/studio/src/styles/studio.css:203",+ "packages/studio/src/styles/studio.css:219",+ "packages/studio/src/player/components/TimelineLanes.tsx:270"+ ],+ "paintBacking": ["--timeline-row-bg", "--timeline-clip-bg"]+ },+ {+ "id": "selected-outline",+ "foreground": "--timeline-clip-selection",+ "background": ["--timeline-row-bg"],+ "role": "graphic",+ "minimum": 3,+ "sources": [+ "packages/studio/src/styles/studio.css:251",+ "packages/studio/src/player/components/TimelineLanes.tsx:270"+ ]+ },+ {+ "id": "selected-handle",+ "foreground": "--timeline-handle",+ "background": ["--timeline-row-bg", "--timeline-clip-bg"],+ "role": "graphic",+ "minimum": 3,+ "sources": [+ "packages/studio/src/player/components/TimelineClip.tsx:160",+ "packages/studio/src/player/components/TimelineClip.tsx:161",+ "packages/studio/src/player/components/timelineTheme.ts:86",+ "packages/studio/src/styles/studio.css:203"+ ],+ "opacity": 0.492+ },+ {+ "id": "active-selected-handle",+ "foreground": "--timeline-handle",+ "background": ["--timeline-row-bg", "--timeline-clip-bg", "--timeline-clip-bg-active"],+ "role": "graphic",+ "minimum": 3,+ "sources": [+ "packages/studio/src/player/components/TimelineClip.tsx:160",+ "packages/studio/src/player/components/TimelineClip.tsx:161",+ "packages/studio/src/player/components/timelineTheme.ts:86",+ "packages/studio/src/styles/studio.css:203",+ "packages/studio/src/styles/studio.css:213",+ "packages/studio/src/styles/studio.css:223"+ ],+ "opacity": 0.492+ },+ {+ "id": "hovered-handle",+ "foreground": "--timeline-handle",+ "background": ["--timeline-row-bg", "--timeline-clip-bg-hover"],+ "role": "graphic",+ "minimum": 3,+ "sources": [+ "packages/studio/src/player/components/TimelineClip.tsx:160",+ "packages/studio/src/player/components/TimelineClip.tsx:161",+ "packages/studio/src/player/components/timelineTheme.ts:87",+ "packages/studio/src/styles/studio.css:243"+ ],+ "opacity": 0.456+ },+ {+ "id": "active-hovered-handle",+ "foreground": "--timeline-handle",+ "background": [+ "--timeline-row-bg",+ "--timeline-clip-bg-hover",+ "--timeline-clip-bg-active"+ ],+ "role": "graphic",+ "minimum": 3,+ "sources": [+ "packages/studio/src/player/components/TimelineClip.tsx:160",+ "packages/studio/src/player/components/TimelineClip.tsx:161",+ "packages/studio/src/player/components/timelineTheme.ts:87",+ "packages/studio/src/styles/studio.css:243",+ "packages/studio/src/styles/studio.css:213",+ "packages/studio/src/styles/studio.css:223"+ ],+ "opacity": 0.456+ },+ {+ "id": "dragging-handle",+ "foreground": "--timeline-handle",+ "background": ["--timeline-row-bg", "--timeline-clip-bg-dragging"],+ "role": "graphic",+ "minimum": 3,+ "sources": [+ "packages/studio/src/player/components/TimelineClip.tsx:160",+ "packages/studio/src/player/components/TimelineClip.tsx:161",+ "packages/studio/src/player/components/timelineTheme.ts:85",+ "packages/studio/src/styles/studio.css:261"+ ],+ "opacity": 0.57+ },+ {+ "id": "active-dragging-handle",+ "foreground": "--timeline-handle",+ "background": [+ "--timeline-row-bg",+ "--timeline-clip-bg-dragging",+ "--timeline-clip-bg-active"+ ],+ "role": "graphic",+ "minimum": 3,+ "sources": [+ "packages/studio/src/player/components/TimelineClip.tsx:160",+ "packages/studio/src/player/components/TimelineClip.tsx:161",+ "packages/studio/src/player/components/timelineTheme.ts:85",+ "packages/studio/src/styles/studio.css:261",+ "packages/studio/src/styles/studio.css:213",+ "packages/studio/src/styles/studio.css:223"+ ],+ "opacity": 0.57+ },+ {+ "id": "quiet-waveform",+ "foreground": "--timeline-waveform-bar-rgb",+ "background": ["--timeline-row-bg", "--timeline-clip-audio-bg"],+ "role": "graphic",+ "minimum": 3,+ "sources": [+ "packages/studio/src/styles/studio.css:230",+ "packages/studio/src/styles/studio.css:213",+ "packages/studio/src/player/components/AudioWaveform.tsx:139",+ "packages/studio/src/player/components/AudioWaveform.tsx:145"+ ],+ "opacity": 0.45,+ "format": "rgb-channels"+ },+ {+ "id": "active-quiet-waveform",+ "foreground": "--timeline-waveform-bar-rgb",+ "background": [+ "--timeline-row-bg",+ "--timeline-clip-audio-bg",+ "--timeline-clip-bg-active"+ ],+ "role": "graphic",+ "minimum": 3,+ "sources": [+ "packages/studio/src/styles/studio.css:230",+ "packages/studio/src/styles/studio.css:213",+ "packages/studio/src/player/components/AudioWaveform.tsx:139",+ "packages/studio/src/player/components/AudioWaveform.tsx:145"+ ],+ "opacity": 0.45,+ "format": "rgb-channels"+ }+ ]+ }+ ]+}diff --git a/scripts/contrast.ts b/scripts/contrast.tsnew file mode 100644index 0000000000..77393aae3a--- /dev/null+++ b/scripts/contrast.ts@@ -0,0 +1,232 @@+type Color = readonly [number, number, number, number];+type Role = "text" | "large-text" | "graphic";+export interface ContrastPair {+ id: string;+ foreground: string;+ background: string[];+ paintBacking: string[];+ opacity: number;+ format: "color" | "rgb-channels";+ role: Role;+ minimum: number;+ sources: string[];+}+export interface ContrastTheme {+ id: string;+ selector: string;+ canvas: string;+ pairs: ContrastPair[];+}+export interface Measurement {+ id: string;+ ratio: number;+ minimum: number;+}+export type ContrastBaseline = Record<string, number>;++function record(value: unknown): Record<string, unknown> {+ if (typeof value !== "object" || value === null || Array.isArray(value))+ throw new Error("Expected object");+ return value as Record<string, unknown>;+}+function string(value: unknown): string {+ if (typeof value !== "string" || !value.trim()) throw new Error("Expected nonempty string");+ return value;+}+function array(value: unknown): unknown[] {+ if (!Array.isArray(value)) throw new Error("Expected array");+ return value;+}+function number(value: unknown): number {+ if (typeof value !== "number" || !Number.isFinite(value))+ throw new Error("Expected finite number");+ return value;+}+function opacity(value: unknown): number {+ const result = number(value);+ if (result < 0 || result > 1) throw new Error("Opacity outside 0..1");+ return result;+}+function role(value: unknown): Role {+ if (value === "text" || value === "large-text" || value === "graphic") return value;+ throw new Error("Unknown contrast role");+}+function roleMinimum(row: Record<string, unknown>) {+ const kind = role(row.role);+ const minimum = number(row.minimum);+ if (minimum !== (kind === "text" ? 4.5 : 3)) throw new Error("Minimum must match WCAG AA role");+ return { role: kind, minimum };+}+function format(value: unknown): ContrastPair["format"] {+ if (value === undefined) return "color";+ if (value === "color" || value === "rgb-channels") return value;+ throw new Error("Unknown color format");+}+function strings(value: unknown): string[] {+ const entries = array(value).map(string);+ if (!entries.length) throw new Error("Expected nonempty list");+ return entries;+}+function parsePair(input: unknown): ContrastPair {+ const row = record(input);+ return {+ id: string(row.id),+ foreground: string(row.foreground),+ background: strings(row.background),+ paintBacking: strings(row.paintBacking ?? row.background),+ opacity: opacity(row.opacity ?? 1),+ format: format(row.format),+ ...roleMinimum(row),+ sources: strings(row.sources),+ };+}+export function parseManifest(text: string): ContrastTheme[] {+ const themes = array(record(JSON.parse(text)).themes).map((input) => {+ const theme = record(input);+ return {+ id: string(theme.id),+ selector: string(theme.selector),+ canvas: string(theme.canvas),+ pairs: array(theme.pairs).map(parsePair),+ };+ });+ const ids = themes.flatMap((theme) => theme.pairs.map((pair) => `${theme.id}/${pair.id}`));+ if (!ids.length || new Set(ids).size !== ids.length)+ throw new Error("Empty or duplicate contrast pairs");+ return themes;+}+export function parseBaseline(text: string): ContrastBaseline {+ return Object.fromEntries(+ Object.entries(record(JSON.parse(text))).map(([key, value]) => [key, number(value)]),+ );+}++function hexColor(hex: string): Color {+ const expanded = hex.length < 5 ? [...hex].map((digit) => digit + digit).join("") : hex;+ const rgba = expanded.padEnd(8, "f");+ const part = (at: number) => parseInt(rgba.slice(at, at + 2), 16) / 255;+ return [part(0), part(2), part(4), part(6)];+}+function channel(value: string, divisor: number): number {+ const numeric = value.endsWith("%") ? Number(value.slice(0, -1)) / 100 : Number(value) / divisor;+ if (![Number.isFinite(numeric), numeric >= 0, numeric <= 1].every(Boolean))+ throw new Error(`Invalid color channel ${value}`);+ return numeric;+}+function rgbColor(value: string): Color {+ const parts = value.trim().split(/[\s,/]+/);+ if (![3, 4].includes(parts.length)) throw new Error(`Invalid RGB color: ${value}`);+ return [+ channel(parts[0]!, 255),+ channel(parts[1]!, 255),+ channel(parts[2]!, 255),+ channel(parts[3] ?? "1", 1),+ ];+}+export function parseColor(value: string): Color {+ const hex = value.match(/^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i);+ if (hex) return hexColor(hex[1]!);+ const rgb = value.match(/^rgba?\(([^)]+)\)$/);+ if (!rgb) throw new Error(`Unsupported sRGB color: ${value}`);+ return rgbColor(rgb[1]!);+}+export function composite(foreground: Color, background: Color): Color {+ if (background[3] !== 1) throw new Error("Compositing requires an opaque backing");+ const mix = (at: 0 | 1 | 2) =>+ foreground[at] * foreground[3] + background[at] * (1 - foreground[3]);+ return [mix(0), mix(1), mix(2), 1];+}+function linear(channel: number): number {+ return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;+}+function luminance(color: Color): number {+ return 0.2126 * linear(color[0]) + 0.7152 * linear(color[1]) + 0.0722 * linear(color[2]);+}+export function contrast(a: Color, b: Color): number {+ const x = luminance(a);+ const y = luminance(b);+ return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05);+}+function tokensFor(css: string, selector: string): Map<string, string> {+ const clean = css.replace(/\/\*[\s\S]*?\*\//g, "");+ const blocks = [...clean.matchAll(/([^{}]+)\{([^{}]*)\}/g)].filter(+ (match) => match[1]!.trim() === selector,+ );+ if (blocks.length !== 1) throw new Error(`Expected exactly one theme block: ${selector}`);+ const entries = [...blocks[0]![2]!.matchAll(/(--[\w-]+)\s*:\s*([^;]+);/g)].map(+ (match) => [match[1]!, match[2]!.trim()] as const,+ );+ const tokens = new Map(entries);+ if (tokens.size !== entries.length) throw new Error("Duplicate token declaration");+ return tokens;+}+function tokenValue(name: string, tokens: Map<string, string>, seen: string[] = []): string {+ if (seen.includes(name)) throw new Error(`Token cycle: ${name}`);+ const value = tokens.get(name);+ if (value === undefined) throw new Error(`Missing token: ${name}`);+ const alias = value.match(/^var\((--[\w-]+)\)$/);+ return alias ? tokenValue(alias[1]!, tokens, [...seen, name]) : value;+}+function surface(layers: string[], canvas: Color, tokens: Map<string, string>): Color {+ return layers.reduce(+ (backing, name) => composite(parseColor(tokenValue(name, tokens)), backing),+ canvas,+ );+}+function measurePair(+ pair: ContrastPair,+ theme: ContrastTheme,+ tokens: Map<string, string>,+): Measurement {+ const canvas = parseColor(tokenValue(theme.canvas, tokens));+ if (canvas[3] !== 1) throw new Error("Theme canvas must be opaque");+ const value = tokenValue(pair.foreground, tokens);+ const fg = pair.format === "rgb-channels" ? rgbColor(value) : parseColor(value);+ const paint: Color = [fg[0], fg[1], fg[2], fg[3] * pair.opacity];+ const backing = surface(pair.paintBacking, canvas, tokens);+ const background = surface(pair.background, canvas, tokens);+ return {+ id: `${theme.id}/${pair.id}`,+ minimum: pair.minimum,+ ratio: contrast(composite(paint, backing), background),+ };+}+export function measure(css: string, themes: ContrastTheme[]): Measurement[] {+ return themes.flatMap((theme) => {+ const tokens = tokensFor(css, theme.selector);+ return theme.pairs.map((pair) => measurePair(pair, theme, tokens));+ });+}+function newDebt(row: Measurement): string[] {+ return row.ratio < row.minimum ? [`${row.id}: new contrast debt ${row.ratio}`] : [];+}+function debtIssue(row: Measurement, baseline: ContrastBaseline): string[] {+ const previous = baseline[row.id];+ if (previous === undefined) return newDebt(row);+ if (previous === 0) return [`${row.id}: remove zero entry from baseline`];+ if (row.ratio >= row.minimum) return [`${row.id}: remove passing pair from baseline`];+ return changedRatioIssue(row, previous);+}+function changedRatioIssue(row: Measurement, previous: number): string[] {+ if (Math.abs(row.ratio - previous) > 1e-10)+ return [+ `${row.id}: ratio ${row.ratio}, baseline ${previous}; bank improvements, reject regressions`,+ ];+ return [];+}+function baselineDirection(id: string, ratio: number, previous: ContrastBaseline): string[] {+ return ratio < (previous[id] ?? Infinity) ? [`${id}: baseline may only improve`] : [];+}+export function verdict(+ rows: Measurement[],+ baseline: ContrastBaseline,+ previous = baseline,+): string[] {+ const issues = rows.flatMap((row) => debtIssue(row, baseline));+ const ids = new Set(rows.map((row) => row.id));+ for (const [id, ratio] of Object.entries(baseline)) {+ if (!ids.has(id)) issues.push(`${id}: stale baseline pair`);+ issues.push(...baselineDirection(id, ratio, previous));+ }+ return issues;+}diff --git a/scripts/contrastRatchet.test.ts b/scripts/contrastRatchet.test.tsnew file mode 100644index 0000000000..7bf2aaec3f--- /dev/null+++ b/scripts/contrastRatchet.test.ts@@ -0,0 +1,147 @@+// guards: packages/studio/src/styles/**+import { readFileSync } from "node:fs";+import { execFileSync } from "node:child_process";+import { describe, expect, it } from "vitest";+import {+ composite,+ contrast,+ measure,+ parseBaseline,+ parseColor,+ parseManifest,+ verdict,+} from "./contrast";++const read = (file: string) => readFileSync(new URL(file, import.meta.url), "utf8");+const pair = {+ id: "label",+ foreground: "--fg",+ background: ["--bg"],+ role: "text",+ minimum: 4.5,+ sources: ["fixture.css:1"],+};+const themes = (pairs: unknown[] = [pair]) =>+ parseManifest(+ JSON.stringify({ themes: [{ id: "dark", selector: ":root", canvas: "--bg", pairs }] }),+ );+const css = (fg: string) => `:root { --fg: ${fg}; --bg: #000; }`;++function previousBaseline(fallback: ReturnType<typeof parseBaseline>, base = "origin/main") {+ const path = "scripts/contrast-baseline.json";+ const files = execFileSync("git", ["ls-tree", "--full-tree", "--name-only", base, "--", path], {+ encoding: "utf8",+ });+ if (!files.trim()) return fallback;+ return parseBaseline(execFileSync("git", ["show", `${base}:${path}`], { encoding: "utf8" }));+}++describe("WCAG contrast calculation", () => {+ it("matches the independent black/white reference ratio of 21", () => {+ expect(contrast(parseColor("#fff"), parseColor("#000"))).toBe(21);+ expect(contrast(parseColor("#000"), parseColor("#000"))).toBe(1);+ });+ it("normalizes short hex, alpha hex and percentage RGB without rounding", () => {+ expect(parseColor("#fff3")).toEqual([1, 1, 1, 0.2]);+ expect(parseColor("rgb(100% 0% 0% / 20%)")).toEqual([1, 0, 0, 0.2]);+ expect(parseColor("rgba(255, 0, 0, 0.101)")[3]).toBe(0.101);+ });+ it("parses channel tokens directly and rejects incomplete triplets", () => {+ const config = themes([{ ...pair, format: "rgb-channels" }]);+ expect(measure(css("255, 255, 255"), config)[0]!.ratio).toBe(21);+ expect(() => measure(css("255, 255"), config)).toThrow("Invalid RGB");+ });+ it("composites a translucent foreground after all backdrop layers", () => {+ expect(composite(parseColor("rgba(255,255,255,0.5)"), parseColor("#000"))).toEqual([+ 0.5, 0.5, 0.5, 1,+ ]);+ const config = themes([{ ...pair, background: ["--layer"], opacity: 0.5 }]);+ const source = ":root { --bg: #000; --layer: rgba(255,255,255,0.5); --fg: #fff; }";+ const expected = contrast([0.75, 0.75, 0.75, 1], [0.5, 0.5, 0.5, 1]);+ expect(measure(source, config)[0]!.ratio).toBe(expected);+ });+ it("compares border paint on clip fill against the adjacent exterior", () => {+ const config = themes([{ ...pair, paintBacking: ["--fill"] }]);+ const source = ":root { --bg: #000; --fill: #fff; --fg: rgba(0,0,0,0.5); }";+ expect(measure(source, config)[0]!.ratio).toBeCloseTo(5.2808228096, 9);+ });+ it("resolves aliases and rejects missing or cyclic tokens", () => {+ expect(measure(":root {--fg:var(--white);--white:#fff;--bg:#000;}", themes())[0]!.ratio).toBe(+ 21,+ );+ expect(() => measure(":root {--bg:#000;}", themes())).toThrow("Missing token");+ expect(() => measure(":root {--fg:var(--fg);--bg:#000;}", themes())).toThrow("cycle");+ });+ it("rejects unsupported colors and invalid channels instead of guessing", () => {+ expect(() => parseColor("currentColor")).toThrow("Unsupported");+ expect(() => parseColor("rgb(300,0,0)")).toThrow("Invalid");+ expect(() => measure(":root {--bg:rgba(0,0,0,.5);--fg:#fff;}", themes())).toThrow("opaque");+ });+ it("keeps themes isolated in one manifest", () => {+ const config = parseManifest(+ JSON.stringify({+ themes: [+ { id: "dark", selector: ":root", canvas: "--bg", pairs: [pair] },+ { id: "light", selector: ".light", canvas: "--bg", pairs: [pair] },+ ],+ }),+ );+ expect(+ measure(":root{--bg:#000;--fg:#fff;} .light{--bg:#fff;--fg:#000;}", config).map(+ (row) => row.ratio,+ ),+ ).toEqual([21, 21]);+ });+ it("rejects lowered role thresholds and duplicate manifest ids", () => {+ expect(() => themes([{ ...pair, minimum: 3 }])).toThrow("WCAG");+ expect(() => themes([pair, pair])).toThrow("duplicate");+ });+});++describe("contrast ratchet", () => {+ it("reads a committed baseline using repository paths", () => {+ expect(previousBaseline({}, "HEAD")).toEqual(parseBaseline(read("contrast-baseline.json")));+ });++ it("rejects a planted low-contrast value and passes after restoring contrast", () => {+ expect(verdict(measure(css("#111"), themes()), {}).join("\n")).toContain("new contrast debt");+ expect(verdict(measure(css("#fff"), themes()), {})).toEqual([]);+ });+ it("banks improvements and never lowers a committed ratio", () => {+ const row = { id: "dark/label", ratio: 2, minimum: 4.5 };+ expect(verdict([row], { "dark/label": 2 })).toEqual([]);+ expect(verdict([{ ...row, ratio: 1.5 }], { "dark/label": 2 }).join("\n")).toContain(+ "reject regressions",+ );+ expect(verdict([{ ...row, ratio: 3 }], { "dark/label": 2 }).join("\n")).toContain(+ "bank improvements",+ );+ expect(verdict([{ ...row, ratio: 3 }], { "dark/label": 3 }, { "dark/label": 2 })).toEqual([]);+ expect(verdict([row], { "dark/label": 2 }, { "dark/label": 3 }).join("\n")).toContain(+ "only improve",+ );+ });+ it("removes passing and stale baseline entries and forbids fresh debt allowances", () => {+ const row = { id: "dark/label", ratio: 4.5, minimum: 4.5 };+ expect(verdict([row], { "dark/label": 2 }).join("\n")).toContain("remove passing");+ expect(verdict([], { "dark/label": 2 }).join("\n")).toContain("stale");+ expect(verdict([{ ...row, ratio: 2 }], { "dark/label": 2 }, {}).join("\n")).toContain(+ "only improve",+ );+ });+ it("requires a zero baseline entry to be removed", () => {+ const row = { id: "dark/label", ratio: 2, minimum: 4.5 };+ expect(verdict([row], { "dark/label": 0 })).toEqual([+ "dark/label: remove zero entry from baseline",+ ]);+ });+ it("holds every declared timeline state at its committed contrast", () => {+ const manifest = parseManifest(read("contrast-pairs.json"));+ const baseline = parseBaseline(read("contrast-baseline.json"));+ const rows = measure(read("../packages/studio/src/styles/theme.css"), manifest);+ expect(verdict(rows, baseline, previousBaseline(baseline))).toEqual([]);+ console.log(+ `Contrast ratchet verified: ${rows.length} pairs, ${Object.keys(baseline).length} baseline debts.`,+ );+ });+});