8000 fix: do not round contrast up to the WCAG threshold by jangtrinh · Pull Request #462 · jangtrinh/design-os · GitHub
[go: up one dir, main page]

Skip to content
Open
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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changelog

## 2026-12-04

### Fixed
- **Contrast pass/fail no longer rounds up to a WCAG threshold.** `ui ds a11y`, rendered contrast, DESIGN.md contrast audit, persona foreground picking, and `ui color` classification compare the unrounded ratio. A pair at about 4.499:1 no longer passes AA for normal text when two-decimal display would show 4.50. Display rounding stays presentation-only and does not cross 3:1, 4.5:1, or 7:1 when the true ratio is below that threshold.

## 2026-11-17 - ease-design 0.8.0

Dual-dialect Stitch `DESIGN.md` support, multi-framework `--project` token discovery, self-contained & live CDP HTML snapshots, active-DS prompt-plan raw-hex protection, and Codex plugin capabilities. Each item is described in full in its dated entry below.
Expand Down
2 changes: 2 additions & 0 deletions knowledge/color-science.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ Conformance bands the binary reports back:
- **AA-large** — ratio ≥ 3 (passes for large text and UI components only)
- **fail** — ratio < 3

A band is met only by the unrounded ratio. 4.499:1 does not meet 4.5:1 for normal text, even when two-decimal display would show 4.50. The same rule applies at 3:1 and 7:1.

### How to reason with contrast

- **Default to AA.** 4.5:1 for body copy, 3:1 for large text and interactive
Expand Down
12 changes: 7 additions & 5 deletions src/commands/color-format.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
/**
* Text rendering helpers for `ui color` subcommand output.
*
* Pure string transforms — no I/O, no color math. Kept separate from
* color.ts to respect the ~200-line file guideline.
* String transforms for `ui color`. The WCAG band comes from `measureContrast`
* (the unrounded ratio); this file does not re-derive it from the rounded number.
* Kept separate from color.ts to respect the ~200-line file guideline.
*/
import { STOPS } from "../core/color-scale.js";
import { STOPS, measureContrast } from "../core/color-scale.js";
import type { ColorScale, ContrastLevel } from "../core/color-scale.js";
import type { OKLCH } from "../core/color-convert.js";
import type { SemanticPalette } from "../core/color-roles.js";
Expand Down Expand Up @@ -36,8 +37,9 @@ export function formatScale(scale: ColorScale): string {
for (const stop of STOPS) {
const key = String(stop);
const hex = scale.shades[key] ?? "?";
const ratio = scale.contrast[key] ?? 0;
const level = ratio >= 7 ? "AAA" : ratio >= 4.5 ? "AA" : ratio >= 3 ? "AA-large" : "fail";
const measured = /^#[0-9A-Fa-f]{6}$/.test(hex) ? measureContrast(hex, "#FFFFFF") : undefined;
const ratio = measured?.displayRatio ?? scale.contrast[key] ?? 0;
const level: ContrastLevel = measured?.level ?? "fail";
const anchor = stop === scale.anchorStop ? " ◀ anchor" : "";
lines.push(
`${String(stop).padEnd(6)} ${hex.padEnd(10)} ${ratio.toFixed(2).padEnd(10)} ${WCAG_LABEL[level]}${anchor}`,
Expand Down
28 changes: 16 additions & 12 deletions src/commands/color.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ import { errText, errJson, ok, okJson } from "../core/output.js";
import { hexToOKLCH, oklchToHex, ColorError } from "../core/color-convert.js";
import {
generatePalette,
contrastRatio,
classifyContrast,
measureContrast,
STOPS,
} from "../core/color-scale.js";
import type { ContrastLevel } from "../core/color-scale.js";
import { generateSemanticPalette } from "../core/color-roles.js";
import {
formatConvert,
Expand All @@ -25,6 +25,12 @@ import {

const CMD = "color";

/** Contrast of one scale stop against white. The band uses the unrounded ratio. */
function contrastOnWhite(hex: string): { contrastWhite: number; wcag: ContrastLevel } {
const measured = measureContrast(hex, "#FFFFFF");
return { contrastWhite: measured.displayRatio, wcag: measured.level };
}

export const COLOR_HELP = `ui color — OKLCH color math

Usage:
Expand Down Expand Up @@ -121,12 +127,10 @@ function runScale(parsed: ParsedArgs): CommandResult {
try {
const scale = generatePalette(hex);
if (useJson) {
const stops = STOPS.map((stop) => ({
stop,
hex: scale.shades[String(stop)] ?? "",
contrastWhite: scale.contrast[String(stop)] ?? 0,
wcag: classifyContrast(scale.contrast[String(stop)] ?? 0),
}));
const stops = STOPS.map((stop) => {
const hex = scale.shades[String(stop)] ?? "";
return { stop, hex, ...contrastOnWhite(hex) };
});
return okJson(cmd, {
baseHex: scale.baseHex,
anchorStop: scale.anchorStop,
Expand Down Expand Up @@ -160,8 +164,9 @@ function runContrast(parsed: ParsedArgs): CommandResult {
// Validate both colors exist before computing
hexToOKLCH(hex1);
hexToOKLCH(hex2);
const ratio = Math.round(contrastRatio(hex1, hex2) * 100) / 100;
const level = classifyContrast(ratio);
const measured = measureContrast(hex1, hex2);
const ratio = measured.displayRatio;
const level = measured.level;
if (useJson) {
return okJson(cmd, { fg: hex1, bg: hex2, ratio, wcag: level });
}
Expand Down Expand Up @@ -210,8 +215,7 @@ function runSemantic(parsed: ParsedArgs): CommandResult {
stops: STOPS.map((stop) => ({
stop,
hex: entry.scale.shades[String(stop)] ?? "",
contrastWhite: entry.scale.contrast[String(stop)] ?? 0,
wcag: classifyContrast(entry.scale.contrast[String(stop)] ?? 0),
...contrastOnWhite(entry.scale.shades[String(stop)] ?? ""),
})),
}));
return okJson(cmd, { entries });
Expand Down
12 changes: 7 additions & 5 deletions src/core/a11y-checks-contrast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@
* COMPUTABLE. The check self-silences and the document is reported partially
* evaluated — never passed.
*/
import { contrastRatio } from "./color-scale.js";
import { measureContrast, CONTRAST_AA_LARGE } from "./color-scale.js";
import { AA_NORMAL } from "./ds-a11y.js";
import type { DesignFact } from "./design-facts/index.js";
import { atLeast } from "./design-facts/index.js";
import type { FloorFindingBase } from "./finding-schema.js";
import { thr } from "./tell-thresholds.js";

/** AA for large text: >= 24px, or >= 18.66px when bold. */
export const AA_LARGE = 3;
/** AA for large text: >= 24px, or >= 18.66px when bold. Compared against the unrounded ratio. */
export const AA_LARGE: 3 = CONTRAST_AA_LARGE;

/**
* A type alias, not an `interface extends`: FloorFindingBase intersects a
Expand Down Expand Up @@ -202,8 +202,10 @@ export function checkComputedContrast(

const type = typography.find((t) => t.at.nodeRef === ref) ?? typography.find((t) => t.at.line === f.at.line);
const required = isLargeText(type?.sizePx, type?.weight) ? AA_LARGE : AA_NORMAL;
const ratio = Math.round(contrastRatio(`#${f.hex}`, `#${bg.hex}`) * 100) / 100;
if (ratio >= required) continue;
const measured = measureContrast(`#${f.hex}`, `#${bg.hex}`);
// Display rounding is not the decision. 4.499:1 prints near 4.50 and still fails 4.5:1.
if (measured.ratio >= required) continue;
const ratio = measured.displayRatio;

// Built as two shapes, not one spread: RepairTarget's union REQUIRES a
// nodeRef alongside a "nodes" scope, and a conditional spread erases that
Expand Down
62 changes: 54 additions & 8 deletions src/core/color-scale.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,20 @@ function targetL(stop: number): number {

export type ContrastLevel = "AAA" | "AA" | "AA-large" | "fail";

/**
* WCAG 2.2 contrast thresholds. Pass/fail compares the unrounded ratio to these.
* Understanding SC 1.4.3: 4.499:1 does not meet 4.5:1, and the same for 3:1.
*/
export const CONTRAST_AAA = 7;
export const CONTRAST_AA_NORMAL = 4.5;
export const CONTRAST_AA_LARGE = 3;

export interface ColorScale {
baseName: string;
baseHex: string;
anchorStop: number;
shades: Record<string, string>; // "50"–"950" → hex
contrast: Record<string, number>; // "50"–"950" → WCAG ratio vs white
contrast: Record<string, number>; // "50"–"950" → WCAG ratio vs white, 2 dp for display
}

// ─── WCAG contrast ────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -89,14 +97,52 @@ export function contrastRatio(hex1: string, hex2: string): number {
return (lighter + 0.05) / (darker + 0.05);
}

/** Classify a contrast ratio into a WCAG 2.2 conformance band. */
/**
* WCAG 2.2 band for an unrounded contrast ratio.
* Do not pass a display-rounded ratio: 4.499 rounds to 4.50 and would be reported as AA.
*/
export function classifyContrast(ratio: number): ContrastLevel {
if (ratio >= 7) return "AAA";
if (ratio >= 4.5) return "AA";
if (ratio >= 3) return "AA-large";
if (ratio >= CONTRAST_AAA) return "AAA";
if (ratio >= CONTRAST_AA_NORMAL) return "AA";
if (ratio >= CONTRAST_AA_LARGE) return "AA-large";
return "fail";
}

/**
* Two-decimal presentation of a contrast ratio.
* Never an input to pass/fail. When half-up rounding would cross 3:1, 4.5:1, or 7:1
* and the true ratio does not, the displayed value stays below that threshold.
*/
export function displayContrastRatio(ratio: number): number {
const rounded = Math.round(ratio * 100) / 100;
for (const threshold of [CONTRAST_AA_LARGE, CONTRAST_AA_NORMAL, CONTRAST_AAA]) {
if (ratio < threshold && rounded >= threshold) return Math.floor(ratio * 100) / 100;
}
return rounded;
}

export interface MeasuredContrast {
/** Unrounded WCAG ratio. Pass/fail reads this. */
ratio: number;
/** Two-decimal presentation. Never feed this back into classifyContrast. */
displayRatio: number;
level: ContrastLevel;
/** True when the unrounded ratio meets AA for normal text (4.5:1). */
passesNormalText: boolean;
}

/** Measure one pair. Decisions use `ratio` / `level` / `passesNormalText`, never `displayRatio`. */
export function measureContrast(foreground: string, background: string): MeasuredContrast {
const ratio = contrastRatio(foreground, background);
const level = classifyContrast(ratio);
return {
ratio,
displayRatio: displayContrastRatio(ratio),
level,
passesNormalText: level === "AA" || level === "AAA",
};
}

// ─── Palette generation ───────────────────────────────────────────────────────

/**
Expand All @@ -109,7 +155,7 @@ export function classifyContrast(ratio: number): ContrastLevel {
* 3. Gaussian chroma tapering — chroma falls off symmetrically around the anchor
* (sigma = 350 in stop-space, matching the 0–950 range).
* 4. Gamut clamp — binary-search max chroma that stays in sRGB.
* 5. Contrast — WCAG ratio vs white, rounded to 2 dp.
* 5. Contrast — WCAG ratio vs white, stored at 2 dp for display only.
*/
export function generatePalette(baseHex: string): ColorScale {
const base = hexToOKLCH(baseHex);
Expand Down Expand Up @@ -152,8 +198,8 @@ export function generatePalette(baseHex: string): ColorScale {
const hex = oklchToHex(newL, newC, newH);
shades[String(stop)] = hex;

// 5. Contrast vs white
contrast[String(stop)] = Math.round(contrastRatio(hex, "#FFFFFF") * 100) / 100;
// 5. Contrast vs white — display rounding only. Bands are classified from the unrounded ratio.
contrast[String(stop)] = displayContrastRatio(contrastRatio(hex, "#FFFFFF"));
}

return {
Expand Down
13 changes: 7 additions & 6 deletions src/core/designmd-audit-accessibility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@
* Google-Labs alpha YAML doesn't expose intent. We classify a pair as
* "body" by default; future refinement can read a `--treat-as` hint.
*/
import { contrastRatio } from "./color-scale.js";
import { measureContrast, CONTRAST_AA_NORMAL, CONTRAST_AA_LARGE } from "./color-scale.js";
import type { DesignMdDocument, YamlNode } from "./designmd-parser.js";
import type { AuditRow } from "./designmd-audit-types.js";

const HEX_RE = /^#[0-9a-fA-F]{6}$/;
const WCAG_BODY = 4.5;
const WCAG_LARGE = 3.0;
const WCAG_BODY = CONTRAST_AA_NORMAL;
const WCAG_LARGE = CONTRAST_AA_LARGE;

interface ContrastPair {
component: string;
Expand Down Expand Up @@ -92,10 +92,11 @@ function evaluatePairs(pairs: ContrastPair[], subjectLabel: string): AuditRow[]
const warnings: { component: string; fg: string; bg: string; ratio: number }[] = [];

for (const p of pairs) {
const ratio = Math.round(contrastRatio(p.fg, p.bg) * 100) / 100;
if (ratio < WCAG_LARGE) {
const measured = measureContrast(p.fg, p.bg);
const ratio = measured.displayRatio;
if (measured.ratio < WCAG_LARGE) {
failures.push({ ...p, ratio });
} else if (ratio < WCAG_BODY) {
} else if (measured.ratio < WCAG_BODY) {
warnings.push({ ...p, ratio });
}
}
Expand Down
22 changes: 16 additions & 6 deletions src/core/ds-a11y.ts
Original f 10BC8 ile line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
* Roles are inferred from token names unless `--pairs` pins them. The impl must never
* emit the word "accessible" from this check. Pure: no fs, no network.
*/
import { contrastRatio, classifyContrast } from "./color-scale.js";
import { measureContrast, CONTRAST_AA_NORMAL } from "./color-scale.js";
import type { ResolvedToken } from "./token-model.js";
import { inferForegroundPairs } from "./token-pairs.js";

Expand All @@ -21,12 +21,17 @@ const SURFACE_RE = /(?:^|[.\-_/])(bg|background|surface|base|canvas|paper|card|p
/** Contrast SC 1.4.3 / 1.4.11 explicitly exempt disabled/inactive controls. */
const EXEMPT_RE = /(?:^|[.\-_/])(disabled|inactive|readonly)(?:[.\-_/]|$)/i;

/** AA for normal-size text. */
export const AA_NORMAL = 4.5;
/** AA for normal-size text. Compared against the unrounded ratio. */
export const AA_NORMAL: 4.5 = CONTRAST_AA_NORMAL;

export interface ContrastPair {
text: string;
surface: string;
/**
* Contrast ratio at 2 decimal places for display.
* `passesNormalText` and `level` are decided from the unrounded ratio, so a
* value that would print as 4.50 can still fail AA.
*/
ratio: number;
level: string; // AAA | AA | AA-large | fail
passesNormalText: boolean;
Expand Down Expand Up @@ -77,9 +82,14 @@ export function parsePairs(raw: string): [string, string][] {
}

function pairFor(textPath: string, tv: string, surfacePath: string, sv: string): ContrastPair {
const ratio = Math.round(contrastRatio(tv, sv) * 100) / 100;
const level = classifyContrast(ratio);
return { text: textPath, surface: surfacePath, ratio, level, passesNormalText: ratio >= AA_NORMAL };
const measured = measureContrast(tv, sv);
return {
text: textPath,
surface: surfacePath,
ratio: measured.displayRatio,
level: measured.level,
passesNormalText: measured.passesNormalText,
};
}

export function checkTokenContrast(
Expand Down
14 changes: 6 additions & 8 deletions src/core/persona-expand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* tested with golden assertions. Do not reorder sections without updating
* the test golden counts.
*/
import { generatePalette, STOPS, contrastRatio } from "./color-scale.js";
import { generatePalette, STOPS, contrastRatio, measureContrast, CONTRAST_AA_LARGE } from "./color-scale.js";
import { hexToOKLCH, oklchToHex } from "./color-convert.js";
import { createEmptyRegistry } from "./registry-store.js";
import type { PersonaRecord } from "./persona-loader.js";
Expand Down Expand Up @@ -146,8 +146,6 @@ function buildColorCategory(hex: string): Record<string, { $value: string; $type

type ColorCat = Record<string, { $value: string; $type: "color" }>;

/** AA contrast for normal text. */
const AA_NORMAL = 4.5;
const PURE_WHITE = "#FFFFFF";

/** Resolved hex of a stop in a built color category (all STOPS are present post-generation). */
Expand All @@ -156,12 +154,12 @@ function stopHex(cat: ColorCat, stop: number): string {
}

/**
* Does `fg` clear AA on `bg`? Rounds the ratio to 2 dp FIRST, matching `ds a11y`'s
* own comparison exactly (ds-a11y.ts rounds before the ≥4.5 test), so the picker
* and the auditor never disagree on a borderline pair.
* Does `fg` clear AA for normal text on `bg`?
* Same decision as `ui ds a11y`: the unrounded ratio. A pair that prints as 4.50
* is not selected when its true ratio is under 4.5, so the picker and the audit agree.
*/
function clearsAA(fg: string, bg: string): boolean {
return Math.round(contrastRatio(fg, bg) * 100) / 100 >= AA_NORMAL;
return measureContrast(fg, bg).passesNormalText;
}

/**
Expand Down Expand Up @@ -264,7 +262,7 @@ export function pickAccentFg(
* non-text affordances. Lower than the 4.5 text floor because these are not read as
* glyphs; they only need to be perceivable against their surface.
*/
const AA_NONTEXT = 3;
const AA_NONTEXT = CONTRAST_AA_LARGE;

/**
* Pick a focus-ring primary stop (returns `{primary.NNN}`) that is visible on `surfaceHex`.
Expand Down
13 changes: 13 additions & 0 deletions tests/cmd-color.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,19 @@ describe("ui color scale", () => {
});

describe("ui color contrast", () => {
it("does not report AA for a pair just under 4.5:1, and does for a pair at or above 4.5:1", () => {
const under = captureRun(["color", "contrast", "#5A7C87", "#FFFFFF", "--json"]);
expect(under.code).toBe(0);
const underJson = JSON.parse(under.out) as { data: { ratio: number; wcag: string } };
expect(underJson.data.ratio).toBeLessThan(4.5);
expect(underJson.data.wcag).toBe("AA-large");

const over = captureRun(["color", "contrast", "#5A7E73", "#FFFFFF", "--json"]);
expect(over.code).toBe(0);
const overJson = JSON.parse(over.out) as { data: { wcag: string } };
expect(overJson.data.wcag).toBe("AA");
});

it("--json: black on white ≈ 21, AAA", () => {
const { code, out } = captureRun(["color", "contrast", "#000000", "#FFFFFF", "--json"]);
expect(code).toBe(0);
Expand Down
Loading
Loading
0