Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(theme-neutral): lift an unselected SegmentedControl label to 4.5:1 on the dark track (#10881)

Cindy Zhang0b5663f2b32a
diff --git a/.changeset/neutral-segmented-control-label-contrast.md b/.changeset/neutral-segmented-control-label-contrast.md
new file mode 100644
index 0000000000..dfb5734401
--- /dev/null
+++ b/.changeset/neutral-segmented-control-label-contrast.md
@@ -0,0 +1,8 @@
+---
+'@astryxdesign/theme-neutral': patch
+'@astryxdesign/cli': patch
+---
+
+[fix] Neutral: an unselected SegmentedControl label meets 4.5:1 in dark mode on AppShell's surface. The track is translucent, so it lightens the surface under the label: `#9e9e9e` on `#3c3c3c` measured 4.11:1. The label now takes `neutral.dark[80]` (6.46:1), the same lift Neutral already gives secondary text on its selected rows and pills. Light mode is unchanged, and the CLI's Neutral theme template matches.
+
+@cixzhang
diff --git a/packages/cli/assets/templates/themes/neutral/neutralTheme.ts b/packages/cli/assets/templates/themes/neutral/neutralTheme.ts
index bbb4d2ffe2..7fac56f150 100644
--- a/packages/cli/assets/templates/themes/neutral/neutralTheme.ts
+++ b/packages/cli/assets/templates/themes/neutral/neutralTheme.ts
@@ -361,7 +361,13 @@ export const neutralTheme = defineTheme({
padding: 'var(--spacing-1)',
},
},
+ // An unselected label sits on the translucent track, which lifts the
+ // page under it. In dark mode secondary text falls under 4.5:1 on the
+ // track over the surface, so it takes the same next stop.
'segmented-control-item': {
+ base: {
+ '--color-text-secondary': `light-dark(${neutral.light[30]}, ${neutral.dark[80]})`,
+ },
'size:sm': {
height: 'calc(var(--size-element-sm) - 8px)',
},
diff --git a/packages/core/src/SegmentedControl/__tests__/SegmentedControlLabelContrast.a11y.chromium.spec.ts b/packages/core/src/SegmentedControl/__tests__/SegmentedControlLabelContrast.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..4cb1d96541
--- /dev/null
+++ b/packages/core/src/SegmentedControl/__tests__/SegmentedControlLabelContrast.a11y.chromium.spec.ts
@@ -0,0 +1,70 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope ^packages/core/src/SegmentedControl/ ^packages/themes/neutral/ ^apps/storybook/stories/SegmentedControl
+
+/**
+ * @file SegmentedControlLabelContrast.a11y.chromium.spec.ts
+ * @input The built SegmentedControl "Default" story in real Chromium, in the
+ * Neutral theme, light and dark, over each page background a control sits
+ * on (AppShell's surface, the body, a Card), and axe
+ * @output Browser evidence that unselected labels on the translucent track
+ * meet 4.5:1 text contrast over every page background
+ * @position Regression proof for the Neutral `segmented-control-item` lift;
+ * scripts/check-segmented-control-label-contrast.test.mjs measures every
+ * shipped theme from its tokens
+ */
+
+import AxeBuilder from '@axe-core/playwright';
+import {expect, test} from '@astryxdesign/a11y-spec/playwright';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+const PAGES = [
+ '--color-background-surface',
+ '--color-background-body',
+ '--color-background-card',
+] as const;
+
+for (const mode of ['light', 'dark'] as const) {
+ for (const page of PAGES) {
+ test(`unselected labels meet 4.5:1 in Neutral ${mode} over ${page}`, async ({
+ page: browserPage,
+ }) => {
+ await browserPage.goto(
+ `${storybook.origin}/iframe.html?id=core-segmentedcontrol--default&viewMode=story&globals=colorMode:${mode};astryxTheme:neutral`,
+ );
+ const control = browserPage.locator('.astryx-segmented-control').first();
+ await control.waitFor();
+ // Paint the page background the control sits on, as AppShell or a Card
+ // would, on every ancestor up to the root.
+ await browserPage.addStyleTag({
+ content: `html, body, #storybook-root, #storybook-root :has(.astryx-segmented-control) { background: var(${page}) !important; }`,
+ });
+ const results = await new AxeBuilder({page: browserPage})
+ .include('.astryx-segmented-control')
+ .withRules(['color-contrast'])
+ .analyze();
+ expect(
+ results.violations.flatMap(violation =>
+ violation.nodes.map(node => node.failureSummary ?? ''),
+ ),
+ ).toEqual([]);
+ // The rule checked the labels rather than finding nothing to check.
+ expect(results.passes.some(pass => pass.id === 'color-contrast')).toBe(
+ true,
+ );
+ });
+ }
+}
diff --git a/packages/themes/neutral/neutral.spec.md b/packages/themes/neutral/neutral.spec.md
index 53e1a4a72f..a962263333 100644
--- a/packages/themes/neutral/neutral.spec.md
+++ b/packages/themes/neutral/neutral.spec.md
@@ -11,6 +11,8 @@ review_triggers:
verified_by:
[
scripts/check-badge-contrast.test.mjs,
+ scripts/check-segmented-control-label-contrast.test.mjs,
+ packages/core/src/SegmentedControl/__tests__/SegmentedControlLabelContrast.a11y.chromium.spec.ts,
packages/themes/neutral/src/neutralTheme.test.ts,
]
package: '@astryxdesign/theme-neutral'
@@ -105,9 +107,10 @@ Neutral's selected fill, `--color-accent-muted`, is `neutral.light[85]` /
in both modes. In dark mode Neutral lifts `--color-text-secondary` to
`neutral.dark[80]` on a selected `item` or `tree-list-item` (a checked
CheckboxListItem row reflects `selected` on its `item` target), on a
-`citation` with `variant:number`, and on a `file-input` with `mode:dropzone`,
-whose drag-over fill has no state target, so that text clears 4.5:1 at rest
-and under the hover overlay. Neutral's syntax `comment`, `operator` and
+`citation` with `variant:number`, on a `file-input` with `mode:dropzone`,
+whose drag-over fill has no state target, and on every `segmented-control-item`,
+whose unselected label sits on the translucent track over the page surface, so
+that text clears 4.5:1 at rest and under the hover overlay. Neutral's syntax `comment`, `operator` and
`punctuation` colours are `neutral.light[35]` / `neutral.dark[75]`, so they
read on a highlighted code line.
diff --git a/packages/themes/neutral/src/neutralTheme.test.ts b/packages/themes/neutral/src/neutralTheme.test.ts
index 18978572a4..4f74d6f372 100644
--- a/packages/themes/neutral/src/neutralTheme.test.ts
+++ b/packages/themes/neutral/src/neutralTheme.test.ts
@@ -604,6 +604,12 @@ describe('neutral theme component overrides', () => {
base: {padding: 'var(--spacing-1)'},
});
expect(neutralTheme.components?.['segmented-control-item']).toEqual({
+ base: {
+ '--color-text-secondary': lightDark(
+ neutralPalettes.neutral.light[30],
+ neutralPalettes.neutral.dark[80],
+ ),
+ },
'size:sm': {height: 'calc(var(--size-element-sm) - 8px)'},
'size:md': {height: 'calc(var(--size-element-md) - 8px)'},
'size:lg': {height: 'calc(var(--size-element-lg) - 8px)'},
diff --git a/packages/themes/neutral/src/neutralTheme.ts b/packages/themes/neutral/src/neutralTheme.ts
index bbb4d2ffe2..7fac56f150 100644
--- a/packages/themes/neutral/src/neutralTheme.ts
+++ b/packages/themes/neutral/src/neutralTheme.ts
@@ -361,7 +361,13 @@ export const neutralTheme = defineTheme({
padding: 'var(--spacing-1)',
},
},
+ // An unselected label sits on the translucent track, which lifts the
+ // page under it. In dark mode secondary text falls under 4.5:1 on the
+ // track over the surface, so it takes the same next stop.
'segmented-control-item': {
+ base: {
+ '--color-text-secondary': `light-dark(${neutral.light[30]}, ${neutral.dark[80]})`,
+ },
'size:sm': {
height: 'calc(var(--size-element-sm) - 8px)',
},
diff --git a/scripts/check-segmented-control-label-contrast.test.mjs b/scripts/check-segmented-control-label-contrast.test.mjs
new file mode 100644
index 0000000000..3e39d1f709
--- /dev/null
+++ b/scripts/check-segmented-control-label-contrast.test.mjs
@@ -0,0 +1,206 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SegmentedControl unselected-label contrast guard.
+ *
+ * An unselected SegmentedControl label is `--color-text-secondary` on the
+ * control's track, a `--color-neutral` fill. That fill is often translucent,
+ * so the track takes the page behind it: AppShell's surface, the body, or a
+ * Card. This flattens the track over each of those backgrounds and resolves
+ * the label after the theme's own `segmented-control-item` overrides.
+ *
+ * @input The first-party theme objects and their `segmented-control-item`
+ * overrides.
+ * @output Fails when an unselected label drops below 4.5:1 on any track.
+ * @position Repo-level theme contrast guard, sibling of the other scripts/check-*.
+ */
+
+import {describe, expect, it} from 'vitest';
+import {butterTheme} from '../packages/themes/butter/src/butterTheme.ts';
+import {chocolateTheme} from '../packages/themes/chocolate/src/chocolateTheme.ts';
+import {gothicTheme} from '../packages/themes/gothic/src/gothicTheme.ts';
+import {matchaTheme} from '../packages/themes/matcha/src/matchaTheme.ts';
+import {neutralTheme} from '../packages/themes/neutral/src/neutralTheme.ts';
+import {stoneTheme} from '../packages/themes/stone/src/stoneTheme.ts';
+import {y2kTheme} from '../packages/themes/y2k/src/y2kTheme.ts';
+
+const THEMES = {
+ butter: butterTheme,
+ chocolate: chocolateTheme,
+ gothic: gothicTheme,
+ matcha: matchaTheme,
+ neutral: neutralTheme,
+ stone: stoneTheme,
+ y2k: y2kTheme,
+};
+const MODES = ['light', 'dark'];
+const AA_NORMAL = 4.5;
+const PAGE_BACKGROUNDS = [
+ '--color-background-surface',
+ '--color-background-body',
+ '--color-background-card',
+];
+
+function splitArgs(input) {
+ const out = [];
+ let depth = 0;
+ let current = '';
+ for (const ch of input) {
+ if (ch === '(') depth++;
+ if (ch === ')') depth--;
+ if (ch === ',' && depth === 0) {
+ out.push(current.trim());
+ current = '';
+ continue;
+ }
+ current += ch;
+ }
+ out.push(current.trim());
+ return out;
+}
+
+function resolve(value, tokens, modeIndex, seen = new Set()) {
+ if (Array.isArray(value)) {
+ return resolve(value[modeIndex], tokens, modeIndex, seen);
+ }
+ if (typeof value !== 'string') return null;
+ const v = value.trim();
+ if (v.startsWith('light-dark(')) {
+ const args = splitArgs(v.slice('light-dark('.length, -1));
+ return resolve(args[modeIndex], tokens, modeIndex, seen);
+ }
+ if (v.startsWith('var(')) {
+ const [name, fallback] = splitArgs(v.slice('var('.length, -1));
+ if (seen.has(name)) return null;
+ const next = tokens[name];
+ if (next == null) {
+ return fallback ? resolve(fallback, tokens, modeIndex, seen) : null;
+ }
+ return resolve(next, tokens, modeIndex, new Set([...seen, name]));
+ }
+ return /^#[0-9a-f]{3,8}$/i.test(v) ? v : null;
+}
+
+function parseHex(hex) {
+ let h = hex.slice(1);
+ if (h.length === 3 || h.length === 4) h = [...h].map(c => c + c).join('');
+ const n = i => parseInt(h.slice(i, i + 2), 16);
+ return {r: n(0), g: n(2), b: n(4), a: h.length === 8 ? n(6) / 255 : 1};
+}
+
+function flatten(top, base) {
+ if (top.a >= 1) return top;
+ const mix = (t, b) => Math.round(t * top.a + b * (1 - top.a));
+ return {
+ r: mix(top.r, base.r),
+ g: mix(top.g, base.g),
+ b: mix(top.b, base.b),
+ 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(fg, bg) {
+ const [hi, lo] = [luminance(fg), luminance(bg)].sort((a, b) => b - a);
+ return (hi + 0.05) / (lo + 0.05);
+}
+
+/** The theme's tokens with its `segmented-control-item` base overrides on top. */
+function itemTokens(theme) {
+ const base = theme.components?.['segmented-control-item']?.base ?? {};
+ return {
+ ...theme.localTokens,
+ ...theme.tokens,
+ ...Object.fromEntries(
+ Object.entries(base).filter(([key]) => key.startsWith('--')),
+ ),
+ };
+}
+
+function measurements() {
+ const rows = [];
+ for (const [themeName, theme] of Object.entries(THEMES)) {
+ const pageTokens = {...theme.localTokens, ...theme.tokens};
+ const labelTokens = itemTokens(theme);
+ for (let modeIndex = 0; modeIndex < MODES.length; modeIndex++) {
+ const labelHex = resolve(
+ 'var(--color-text-secondary)',
+ labelTokens,
+ modeIndex,
+ );
+ const trackHex = resolve('var(--color-neutral)', pageTokens, modeIndex);
+ for (const page of PAGE_BACKGROUNDS) {
+ const pageHex = resolve(`var(${page})`, pageTokens, modeIndex);
+ const row = {
+ theme: themeName,
+ mode: MODES[modeIndex],
+ page,
+ ratio: null,
+ };
+ if (labelHex && trackHex && pageHex) {
+ const pageColor = flatten(
+ parseHex(pageHex),
+ modeIndex === 0
+ ? {r: 255, g: 255, b: 255, a: 1}
+ : {r: 0, g: 0, b: 0, a: 1},
+ );
+ const track = flatten(parseHex(trackHex), pageColor);
+ row.ratio = contrast(flatten(parseHex(labelHex), track), track);
+ }
+ rows.push(row);
+ }
+ }
+ }
+ return rows;
+}
+
+// Known gaps, each for its own theme fix. A pair leaves this list when it
+// passes, and the last test fails until it does.
+const KNOWN_GAPS = new Set([
+ // The track lifts the dark card under secondary text (5.99:1 on the card).
+ 'butter dark on --color-background-card',
+ // Secondary text already falls under 4.5:1 on the plain page background.
+ 'chocolate light on --color-background-surface',
+ 'chocolate light on --color-background-body',
+ 'chocolate light on --color-background-card',
+ 'matcha light on --color-background-surface',
+ 'matcha light on --color-background-body',
+ 'matcha light on --color-background-card',
+ 'y2k light on --color-background-body',
+]);
+
+const pairName = row => `${row.theme} ${row.mode} on ${row.page}`;
+
+describe('SegmentedControl unselected-label contrast', () => {
+ const rows = measurements();
+
+ it('resolves every theme, mode, and page background', () => {
+ expect(rows.filter(row => row.ratio == null)).toEqual([]);
+ });
+
+ it('meets WCAG AA for normal text on the track over every page background', () => {
+ const failures = rows
+ .filter(row => !KNOWN_GAPS.has(pairName(row)))
+ .filter(row => row.ratio != null && row.ratio < AA_NORMAL)
+ .map(
+ row =>
+ `${row.theme} ${row.mode} on ${row.page}: ${row.ratio.toFixed(2)}:1`,
+ );
+ expect(failures).toEqual([]);
+ });
+
+ it('lists only gaps that still fail', () => {
+ const fixed = rows
+ .filter(row => KNOWN_GAPS.has(pairName(row)))
+ .filter(row => row.ratio != null && row.ratio >= AA_NORMAL)
+ .map(pairName);
+ expect(fixed).toEqual([]);
+ });
+});