Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🎚️ feat: Promote Stylesheet Colour Roles to Registry Colours (#16864)
Marco Beretta945a8853943f
diff --git a/.github/workflows/static-checks.yml b/.github/workflows/static-checks.ymlindex 755e9a51f1..b46cc86c16 100644--- a/.github/workflows/static-checks.yml+++ b/.github/workflows/static-checks.yml@@ -99,6 +99,9 @@ jobs:- 'client/src/**/*.css'- 'packages/client/src/**/*.css'- 'packages/client/src/theme/allowlist.md'+ # The scanner parses with postcss: an upgrade changes what it reads.+ - 'package.json'+ - 'package-lock.json'- 'scripts/css-colors.mts'- 'scripts/css-colors.test.mts'- 'scripts/static-checks.mts'diff --git a/client/src/style.css b/client/src/style.cssindex 89ed621a19..49789b72d5 100644--- a/client/src/style.css+++ b/client/src/style.css@@ -39,9 +39,6 @@/* Custom Variables */:root {- --gizmo-gray-500: 153 153 153;- --gizmo-gray-600: 102 102 102;- --gizmo-gray-950: 15 15 15;--font-size-xs: 0.75rem;--font-size-sm: 0.875rem;--font-size-base: 1rem;@@ -124,41 +121,6 @@ html {}}-.gizmo {- --text-primary: var(--gizmo-gray-950);- --text-secondary: var(--gizmo-gray-600);- --text-tertiary: var(--gizmo-gray-500);- --text-muted: 105 110 121; /* Click UI global.color.text.muted #696e79 */- --surface-primary: var(--white);- --chart-widget-surface: 255 255 255; /* Click UI dashboards.chartWidget.color.background.default #ffffff */- --chart-widget-stroke: 230 231 233; /* Click UI dashboards.chartWidget.color.stroke.default #e6e7e9 */- --surface-secondary: var(--gray-50);- --surface-tertiary: var(--gray-100);- --border-light: 0 0 0;- --border-light-alpha: 0.1;- --border-medium: 0 0 0;- --border-medium-alpha: 0.15;- --border-heavy: 0 0 0;- --border-heavy-alpha: 0.2;- --border-xheavy: 0 0 0;- --border-xheavy-alpha: 0.25;-}-.gizmo.dark {- --text-primary: var(--gray-100);- --text-secondary: var(--gray-300);- --text-tertiary: var(--gizmo-gray-500);- --text-muted: 179 182 189; /* Click UI global.color.text.muted #b3b6bd */- --surface-primary: var(--gray-900);- --chart-widget-surface: 40 40 40; /* Click UI dashboards.chartWidget.color.background.default #282828 */- --chart-widget-stroke: 50 50 50; /* Click UI dashboards.chartWidget.color.stroke.default #323232 */- --surface-secondary: var(--gray-800);- --surface-tertiary: var(--gray-700);- --border-light: 217 217 227;- --border-medium: 217 217 227;- --border-heavy: 217 217 227;- --border-xheavy: 217 217 227;-}-/* High contrast appearance modes.** Every `IThemeRGB` token is delivered by the theme registry as an inline custom@@ -992,7 +954,7 @@ pre[class*='language-'] {--tw-bg-opacity: 1;--tw-text-opacity: 1;background-color: rgb(var(--surface-secondary));- border-color: rgb(var(--button-neutral-border) / var(--button-neutral-border-alpha, 1));+ border-color: rgb(var(--button-neutral-border) / var(--theme-button-neutral-border-opacity, 0.1));border-width: 1px;color: rgb(var(--button-neutral-text) / var(--tw-text-opacity));font-size: 0.875rem;@@ -1011,11 +973,10 @@ pre[class*='language-'] {}.dark .btn-neutral {- --tw-border-opacity: 1;--tw-bg-opacity: 1;--tw-text-opacity: 1;background-color: transparent;- border-color: rgb(var(--button-neutral-border) / var(--tw-border-opacity));+ border-color: rgb(var(--button-neutral-border) / var(--theme-button-neutral-border-opacity, 1));color: rgb(var(--button-neutral-text) / var(--tw-text-opacity));}@@ -1116,12 +1077,6 @@ html[data-drawer-nav] body {overscroll-behavior: none;}-.dark body,-.dark html {- --tw-bg-opacity: 1;- background-color: rgb(var(--page-canvas) / var(--tw-bg-opacity));-}-#__next,#root {height: 100%;@@ -1289,7 +1244,7 @@ html {}.dark body,.dark html {- background-color: rgb(var(--surface-primary-alt));+ background-color: rgb(var(--page-canvas));}#__next,#root {diff --git a/e2e/specs/mock/scenarios/stylesheet-roles-theme.spec.ts b/e2e/specs/mock/scenarios/stylesheet-roles-theme.spec.tsnew file mode 100644index 0000000000..ad5610c804--- /dev/null+++ b/e2e/specs/mock/scenarios/stylesheet-roles-theme.spec.ts@@ -0,0 +1,155 @@+import { expect, test } from '@playwright/test';+import type { Page } from '@playwright/test';+import { clickHouseTheme } from '../../../../packages/client/src/theme/themes/clickhouse';+import { NEW_CHAT_PATH } from '../helpers';++/**+ * The stylesheet-level roles (`select-fill`, `select-edge`, `button-neutral-*`, `link-inline`,+ * `page-canvas`) are registry colours. Without a theme they paint exactly the values the+ * stylesheet held; the ClickHouse definition repaints them from Click UI.+ */++type Mode = 'light' | 'dark';++const MODES: Mode[] = ['light', 'dark'];+const THEME_PARAM = 'e2eThemeMode';++test.use({ viewport: { width: 1280, height: 800 } });++async function installThemeBridge(page: Page, definition: unknown) {+ await page.addInitScript((stored) => {+ const mode = new URL(location.href).searchParams.get('e2eThemeMode');+ if (mode) {+ localStorage.setItem('color-theme', mode);+ }+ localStorage.setItem('navVisible', 'true');+ localStorage.removeItem('theme-colors');+ localStorage.removeItem('theme-name');+ if (stored) {+ localStorage.setItem('theme-definition', JSON.stringify(stored));+ localStorage.setItem('theme-source', 'definition');+ } else {+ localStorage.removeItem('theme-definition');+ localStorage.removeItem('theme-source');+ }+ }, definition ?? null);+}++interface Painted {+ selectFill: string;+ selectEdge: string;+ neutralBorder: string;+ neutralText: string;+ canvas: string;+}++/** Mounts a native select and a `.btn-neutral` probe and reads what each paints. */+async function paintedRoles(page: Page): Promise<Painted> {+ await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible({+ timeout: 20000,+ });+ return page.evaluate(() => {+ const select = document.createElement('select');+ const button = document.createElement('button');+ button.className = 'btn-neutral';+ document.body.append(select, button);+ const selectStyle = getComputedStyle(select);+ const buttonStyle = getComputedStyle(button);+ const result = {+ selectFill: selectStyle.backgroundColor,+ selectEdge: selectStyle.borderTopColor,+ neutralBorder: buttonStyle.borderTopColor,+ neutralText: buttonStyle.color,+ canvas: getComputedStyle(document.body).backgroundColor,+ };+ select.remove();+ button.remove();+ return result;+ });+}++/** The RGBA a colour paints, whatever syntax the browser serialises it in. */+const rgba = (page: Page, color: string): Promise<number[]> =>+ page.evaluate((value) => {+ const canvas = document.createElement('canvas');+ canvas.width = 1;+ canvas.height = 1;+ const context = canvas.getContext('2d');+ if (!context) {+ return [];+ }+ context.fillStyle = value;+ context.fillRect(0, 0, 1, 1);+ return Array.from(context.getImageData(0, 0, 1, 1).data);+ }, color);++const STOCK: Record<Mode, Record<keyof Painted, string>> = {+ light: {+ selectFill: 'rgb(255 255 255)',+ selectEdge: 'rgb(142 142 160)',+ neutralBorder: 'rgb(0 0 0 / 0.1)',+ neutralText: 'rgb(64 65 79)',+ canvas: '',+ },+ dark: {+ selectFill: 'rgb(255 255 255)',+ selectEdge: 'rgb(142 142 160)',+ neutralBorder: 'rgb(66 66 66)',+ neutralText: 'rgb(255 255 240)',+ canvas: 'rgb(23 23 23)',+ },+};++const triplet = (value: string | undefined) => `rgb(${value ?? ''})`;++test.describe('stylesheet roles', () => {+ test('stock stylesheet roles keep their values in both modes @scenario:stylesheet-roles-keep-stock-values', async ({+ page,+ }) => {+ test.setTimeout(60000);+ await installThemeBridge(page, null);+ for (const mode of MODES) {+ await page.goto(`${NEW_CHAT_PATH}?${THEME_PARAM}=${mode}`);+ const got = await paintedRoles(page);+ for (const key of Object.keys(STOCK[mode]) as Array<keyof Painted>) {+ if (STOCK[mode][key] === '') {+ continue;+ }+ expect([mode, key, await rgba(page, got[key])]).toEqual([+ mode,+ key,+ await rgba(page, STOCK[mode][key]),+ ]);+ }+ }+ });++ test('the ClickHouse theme repaints the stylesheet roles from Click UI @scenario:stylesheet-roles-follow-clickhouse', async ({+ page,+ }) => {+ test.setTimeout(60000);+ await installThemeBridge(page, clickHouseTheme);+ for (const mode of MODES) {+ await page.goto(`${NEW_CHAT_PATH}?${THEME_PARAM}=${mode}`);+ const colors = clickHouseTheme.modes[mode]?.colors ?? {};+ const got = await paintedRoles(page);+ const want: Painted = {+ selectFill: triplet(colors['rgb-select-fill']),+ selectEdge: triplet(colors['rgb-select-edge']),+ neutralBorder: triplet(colors['rgb-button-neutral-border']),+ neutralText: triplet(colors['rgb-button-neutral-text']),+ canvas: mode === 'dark' ? triplet(colors['rgb-page-canvas']) : '',+ };+ for (const key of Object.keys(want) as Array<keyof Painted>) {+ if (want[key] === '') {+ continue;+ }+ expect([mode, key, await rgba(page, got[key])]).toEqual([+ mode,+ key,+ await rgba(page, want[key]),+ ]);+ }+ }+ });+});diff --git a/packages/client/src/theme/README.md b/packages/client/src/theme/README.mdindex b7d353108b..f889bdfd1c 100644--- a/packages/client/src/theme/README.md+++ b/packages/client/src/theme/README.md@@ -311,6 +311,7 @@ function MyComponent() {- `fill-illustration-subtle`, `fill-illustration`, `fill-illustration-strong` - The three tones of in-app artwork, such as the file drop zone's illustration- `fill-file-document`, `fill-file-sheet`, `fill-file-code`, `fill-file-artifact`, `fill-file-audio`, `fill-file-video`, `fill-file-generic` - File-type tile fills; `stroke-file-ink` and `fill-file-ink` draw the glyph on them- `bg-surface-qr` - Backdrop behind a QR code, kept light in every mode so it scans+- `scrollbar-thumb`, `page-canvas`, `select-fill`, `select-edge`, `button-neutral-border`, `button-neutral-text`, `button-neutral-hover`, `link-inline`, `toast-edge`, `stroke-ink` - The stylesheet-level colour roles, read by the stylesheet as `rgb(var(--name))`: the scrollbar thumb, the dark page behind the app, a native `select`, the legacy `.btn-neutral`, inline links on mobile, the toast's shadow tint and the avatar's translucent ring. Their opacities stay in CSS, except the neutral border's, which is the `buttonNeutralBorderOpacity` appearance role (10% in light, solid in dark)### Border Colorsdiff --git a/packages/client/src/theme/allowlist.md b/packages/client/src/theme/allowlist.mdindex 46f88327eb..47444c0593 100644--- a/packages/client/src/theme/allowlist.md+++ b/packages/client/src/theme/allowlist.md@@ -8,8 +8,9 @@ block in `eslint.config.mjs` (the brand and decorative marks named below) or bychecks), so the count there is the exception, not debt. Everything elseis invisible to the lint (strings passed to a canvas or an iframe), so this list is the record.Stylesheets are the exception: `scripts/css-colors.mts` fails `npm run static-checks` on a colour-literal in any `.css` under `client/src` or `packages/client/src` except `defaults.css` and `tokens.css`-(entry 1) the `.azure-bg-color` rule in `client/src/mobile.css` (entry 2) and the `select` rule in `client/src/style.css` (entry 9).+literal, or a bare channel triplet in a custom property, in any `.css` under `client/src` or+`packages/client/src`, except in the custom properties of `defaults.css` and `tokens.css`+(entry 1), the `.azure-bg-color` rule in `client/src/mobile.css` (entry 2) and the `select` rule in `client/src/style.css` (entry 9).Adding an entry needs the same bar: if a theme author would reasonably want to recolour it, itis a role, not an exception. Keep the list to ten entries or fewer; a new kind of exception thatdiff --git a/packages/client/src/theme/defaults.css b/packages/client/src/theme/defaults.cssindex f7fd3eea1f..e730e862f7 100644--- a/packages/client/src/theme/defaults.css+++ b/packages/client/src/theme/defaults.css@@ -106,10 +106,10 @@ html {--link-hover: var(--blue-700);--scrollbar-thumb: var(--black);--scrollbar-thumb-alpha: 0.1;+ --page-canvas: var(--surface-primary-alt);--select-fill: var(--white);--select-edge: 142 142 160;--button-neutral-border: var(--black);- --button-neutral-border-alpha: 0.1;--button-neutral-text: 64 65 79;--button-neutral-hover: var(--gray-20);--link-inline: 0 102 204;@@ -311,6 +311,7 @@ html {--theme-scrim-opacity: 0.8;--theme-alert-scrim-opacity: 0.9;--theme-modal-scrim-opacity: 0.65;+ --theme-button-neutral-border-opacity: 0.1;--theme-font-family: Inter, sans-serif;--theme-display-font-family: Inter, sans-serif;--theme-text-xs: 0.75rem;@@ -408,7 +409,6 @@ html {--scrollbar-thumb: var(--white);--page-canvas: var(--gray-850);--button-neutral-border: var(--gray-600);- --button-neutral-border-alpha: 1;--button-neutral-text: 255 255 240;--button-neutral-hover: var(--gray-600);--link-inline: 82 160 255;@@ -551,6 +551,7 @@ html {/* The appearance defaults that differ in dark mode (`darkAppearanceDefaults`). */--theme-menu-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.25), 0 4px 6px -4px rgb(0 0 0 / 0.1);--theme-tooltip-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.35);+ --theme-button-neutral-border-opacity: 1;}/* A root other than the document one that a legacy palette themes (`THEME_SCOPE_ATTRIBUTE` indiff --git a/packages/client/src/theme/defaults.spec.ts b/packages/client/src/theme/defaults.spec.tsindex a636432f43..339a881ff3 100644--- a/packages/client/src/theme/defaults.spec.ts+++ b/packages/client/src/theme/defaults.spec.ts@@ -68,7 +68,7 @@ describe.each([const tokens = Object.keys(theme) as Array<keyof IThemeRGB>;it('covers every registry color', () => {- expect(tokens).toHaveLength(152);+ expect(tokens).toHaveLength(162);});it('resolves every registry color to the runtime theme value', () => {diff --git a/packages/client/src/theme/registry.spec.ts b/packages/client/src/theme/registry.spec.tsindex 463dc5cc39..fa07a27d60 100644--- a/packages/client/src/theme/registry.spec.ts+++ b/packages/client/src/theme/registry.spec.ts@@ -519,6 +519,27 @@ describe('theme registry', () => {expect(resolveTheme(theme, 'light').colors['rgb-drawer-edge']).toBe('40 41 42');});+ it('keeps the page canvas on the surface a theme repaints, unless it sets the role', () => {+ const colors = { 'rgb-surface-primary-alt': '20 21 22' };+ const theme = {+ version: 1 as const,+ name: 'legacy-page-canvas',+ modes: { light: { colors }, dark: { colors } },+ };+ const explicit = resolveTheme(+ {+ version: 1,+ name: 'explicit-page-canvas',+ modes: { dark: { colors: { ...colors, 'rgb-page-canvas': '1 2 3' } } },+ },+ 'dark',+ );++ expect(resolveTheme(theme, 'dark').colors['rgb-page-canvas']).toBe('20 21 22');+ expect(resolveTheme(theme, 'light').colors['rgb-page-canvas']).toBe('20 21 22');+ expect(explicit.colors['rgb-page-canvas']).toBe('1 2 3');+ });+it('inks the default avatar in the primary text a theme sets, unless it sets the role', () => {const inherited = resolveTheme({@@ -1131,6 +1152,7 @@ describe('theme registry', () => {it('names the legacy surface of each layer outright', () => {const legacy: Record<string, [string, string]> = {'rgb-surface-canvas': ['rgb-surface-primary-alt', 'rgb-surface-primary-alt'],+ 'rgb-page-canvas': ['rgb-surface-primary-alt', 'rgb-surface-primary-alt'],'rgb-surface-user-message': ['rgb-surface-tertiary', 'rgb-surface-tertiary'],'rgb-surface-card': ['rgb-surface-secondary', 'rgb-surface-secondary'],'rgb-surface-card-hover': ['rgb-surface-tertiary', 'rgb-surface-tertiary'],diff --git a/packages/client/src/theme/registry.ts b/packages/client/src/theme/registry.tsindex 76ef5d75c8..b94e0b543e 100644--- a/packages/client/src/theme/registry.ts+++ b/packages/client/src/theme/registry.ts@@ -127,6 +127,7 @@ export const layerRoleSources: ReadonlyArray<readonly [keyof IThemeRGB, keyof IThemeRGB, keyof IThemeRGB]> = [['rgb-surface-canvas', 'rgb-surface-primary-alt', 'rgb-surface-primary-alt'],+ ['rgb-page-canvas', 'rgb-surface-primary-alt', 'rgb-surface-primary-alt'],['rgb-surface-user-message', 'rgb-surface-tertiary', 'rgb-surface-tertiary'],['rgb-surface-card', 'rgb-surface-secondary', 'rgb-surface-secondary'],['rgb-surface-card-hover', 'rgb-surface-tertiary', 'rgb-surface-tertiary'],@@ -296,6 +297,7 @@ export const themeAppearanceProperties: Readonly<scrimOpacity: '--theme-scrim-opacity',alertScrimOpacity: '--theme-alert-scrim-opacity',modalScrimOpacity: '--theme-modal-scrim-opacity',+ buttonNeutralBorderOpacity: '--theme-button-neutral-border-opacity',elevationSurface: '--theme-elevation-surface',elevationDrag: '--theme-elevation-drag',shadow2xs: '--theme-shadow-2xs',@@ -401,6 +403,7 @@ export const defaultAppearance: IThemeAppearance = Object.freeze({scrimOpacity: '0.8',alertScrimOpacity: '0.9',modalScrimOpacity: '0.65',+ buttonNeutralBorderOpacity: '0.1',elevationSurface: '0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)',elevationDrag: '0 10px 25px rgb(0 0 0 / 0.1)',shadow2xs: '0 1px rgb(0 0 0 / 0.05)',@@ -427,6 +430,7 @@ export const defaultAppearance: IThemeAppearance = Object.freeze({export const darkAppearanceDefaults: Readonly<Partial<IThemeAppearance>> = Object.freeze({menuShadow: '0 10px 15px -3px rgb(0 0 0 / 0.25), 0 4px 6px -4px rgb(0 0 0 / 0.1)',tooltipShadow: '0 1px 2px 0 rgb(0 0 0 / 0.35)',+ buttonNeutralBorderOpacity: '1',});/** Every appearance default in `mode`. */diff --git a/packages/client/src/theme/themes/clickhouse.ts b/packages/client/src/theme/themes/clickhouse.tsindex c8899a2134..64c9c4226e 100644--- a/packages/client/src/theme/themes/clickhouse.ts+++ b/packages/client/src/theme/themes/clickhouse.ts@@ -170,6 +170,16 @@ export const clickHouseLightTheme: IThemeRGB = {'rgb-illustration-subtle': '161 190 247', // #a1bef7 (palette.info.200)'rgb-illustration': '67 126 239', // #437eef (palette.info.400)'rgb-illustration-strong': '16 78 198', // #104ec6 (palette.info.600)+ 'rgb-scrollbar-thumb': '0 0 0', // #000000 (no Click UI counterpart; the stock role)+ 'rgb-page-canvas': '246 247 250', // #f6f7fa (background.split)+ 'rgb-select-fill': '251 252 255', // #fbfcff (field.color.background.default)+ 'rgb-select-edge': '230 231 233', // #e6e7e9 (field.color.stroke.default)+ 'rgb-button-neutral-border': '230 231 233', // #e6e7e9 (button.basic.color.secondary.stroke.default)+ 'rgb-button-neutral-text': '22 21 23', // #161517 (text.default, matching text-primary)+ 'rgb-button-neutral-hover': '230 231 233', // #e6e7e9 (matching surface-hover)+ 'rgb-link-inline': '67 126 239', // #437eef (text.link.default, matching link)+ 'rgb-toast-edge': '67 90 111', // #435a6f (no Click UI counterpart; the stock role)+ 'rgb-stroke-ink': '0 0 0', // #000000 at 10% (no Click UI counterpart; the stock role)'rgb-file-document': '16 78 198', // #104ec6 (palette.info.600)'rgb-file-sheet': '0 138 11', // #008a0b (palette.success.700)'rgb-file-code': '214 79 0', // #d64f00 (palette.warning.600)@@ -351,6 +361,16 @@ export const clickHouseDarkTheme: IThemeRGB = {'rgb-illustration-subtle': '161 190 247', // #a1bef7 (palette.info.200)'rgb-illustration': '67 126 239', // #437eef (palette.info.400)'rgb-illustration-strong': '16 78 198', // #104ec6 (palette.info.600)+ 'rgb-scrollbar-thumb': '255 255 255', // #ffffff (no Click UI counterpart; the stock role)+ 'rgb-page-canvas': '40 40 40', // #282828 (background.split, the dark canvas the page already paints)+ 'rgb-select-fill': '45 45 45', // #2d2d2d (field.color.background.default)+ 'rgb-select-edge': '60 60 60', // #3c3c3c (field.color.stroke.default)+ 'rgb-button-neutral-border': '65 65 65', // #414141 (button.basic.color.secondary.stroke.default)+ 'rgb-button-neutral-text': '255 255 255', // #ffffff (text.default, matching text-primary)+ 'rgb-button-neutral-hover': '50 50 50', // #323232 (matching surface-hover)+ 'rgb-link-inline': '250 255 105', // #faff69 (text.link.default)+ 'rgb-toast-edge': '67 90 111', // #435a6f (no Click UI counterpart; the stock role)+ 'rgb-stroke-ink': '255 255 255', // #ffffff at 30% (no Click UI counterpart; the stock role)'rgb-file-document': '16 78 198', // #104ec6 (palette.info.600)'rgb-file-sheet': '0 138 11', // #008a0b (palette.success.700)'rgb-file-code': '214 79 0', // #d64f00 (palette.warning.600)@@ -517,6 +537,7 @@ const clickHouseShape = {scrimOpacity: '0.75', // dialog.color.opaqueBackground alphaalertScrimOpacity: '0.75', // dialog.color.opaqueBackground alphamodalScrimOpacity: '0.75', // dialog.color.opaqueBackground alpha+ buttonNeutralBorderOpacity: '1', // button.basic.color.secondary.stroke.default is opaque/** Click UI paints disabled controls in fixed fills (`#dfdfdf` / `#414141`) rather than fading them. */disabledStyle: 'fill' as const,switchWidth: '2rem', // switch.size.widthdiff --git a/packages/client/src/theme/themes/clickui.spec.ts b/packages/client/src/theme/themes/clickui.spec.tsindex 1ba1c34971..4630bc591f 100644--- a/packages/client/src/theme/themes/clickui.spec.ts+++ b/packages/client/src/theme/themes/clickui.spec.ts@@ -176,6 +176,12 @@ const colorSources: Record<ThemeMode, Partial<Record<keyof IThemeRGB, string>>>'rgb-illustration-subtle': 'palette.info.200','rgb-illustration': 'palette.info.400','rgb-illustration-strong': 'palette.info.600',+ 'rgb-page-canvas': 'global.color.background.split',+ 'rgb-select-fill': 'click.field.color.background.default',+ 'rgb-select-edge': 'click.field.color.stroke.default',+ 'rgb-button-neutral-border': 'click.button.basic.color.secondary.stroke.default',+ 'rgb-button-neutral-text': 'global.color.text.default',+ 'rgb-link-inline': 'global.color.text.link.default','rgb-file-document': 'palette.info.600','rgb-file-sheet': 'palette.success.700','rgb-file-code': 'palette.warning.600',@@ -329,6 +335,12 @@ const colorSources: Record<ThemeMode, Partial<Record<keyof IThemeRGB, string>>>'rgb-illustration-subtle': 'palette.info.200','rgb-illustration': 'palette.info.400','rgb-illustration-strong': 'palette.info.600',+ 'rgb-page-canvas': 'global.color.background.split',+ 'rgb-select-fill': 'click.field.color.background.default',+ 'rgb-select-edge': 'click.field.color.stroke.default',+ 'rgb-button-neutral-border': 'click.button.basic.color.secondary.stroke.default',+ 'rgb-button-neutral-text': 'global.color.text.default',+ 'rgb-link-inline': 'global.color.text.link.default','rgb-file-document': 'palette.info.600','rgb-file-sheet': 'palette.success.700','rgb-file-code': 'palette.warning.600',@@ -366,10 +378,22 @@ const colorSources: Record<ThemeMode, Partial<Record<keyof IThemeRGB, string>>>/** Values the theme sets on purpose without a Click UI source, and why. */const MEDIA_OVERLAY_REASON ='Click UI has no media scrim; the image frame stays black in both modes';+const STYLESHEET_ROLE_REASON =+ 'Click UI has no scrollbar, secondary button fill or toast edge; the theme keeps the stock role';+const STROKE_INK_REASON =+ 'Click UI avatars draw no edge ink of their own; the theme keeps the stock ring tint';++const STYLESHEET_ROLES: Partial<Record<keyof IThemeRGB, string>> = {+ 'rgb-surface-media-overlay': MEDIA_OVERLAY_REASON,+ 'rgb-scrollbar-thumb': STYLESHEET_ROLE_REASON,+ 'rgb-button-neutral-hover': STYLESHEET_ROLE_REASON,+ 'rgb-toast-edge': STYLESHEET_ROLE_REASON,+ 'rgb-stroke-ink': STROKE_INK_REASON,+};const unsourcedColors: Record<ThemeMode, Partial<Record<keyof IThemeRGB, string>>> = {- light: { 'rgb-surface-media-overlay': MEDIA_OVERLAY_REASON },- dark: { 'rgb-surface-media-overlay': MEDIA_OVERLAY_REASON },+ light: STYLESHEET_ROLES,+ dark: STYLESHEET_ROLES,};/**@@ -609,6 +633,7 @@ const appearanceSources: Partial<Record<keyof IThemeAppearance, string>> = {scrimOpacity: 'click.dialog.color.opaqueBackground.default',alertScrimOpacity: 'click.dialog.color.opaqueBackground.default',modalScrimOpacity: 'click.dialog.color.opaqueBackground.default',+ buttonNeutralBorderOpacity: 'click.button.basic.color.secondary.stroke.default',switchWidth: 'click.switch.size.width',switchHeight: 'click.switch.size.height',checkboxSize: 'click.checkbox.size.all',@@ -806,6 +831,7 @@ const scrimKeys: ReadonlySet<keyof IThemeAppearance> = new Set(['scrimOpacity','alertScrimOpacity','modalScrimOpacity',+ 'buttonNeutralBorderOpacity',]);/** Roles read out of a Click UI `font` shorthand, and the part each one is. */diff --git a/packages/client/src/theme/themes/dark.ts b/packages/client/src/theme/themes/dark.tsindex cd01c6699d..3f802d2b9a 100644--- a/packages/client/src/theme/themes/dark.ts+++ b/packages/client/src/theme/themes/dark.ts@@ -156,6 +156,16 @@ export const darkTheme: IThemeRGB = {'rgb-illustration-subtle': '175 193 255', // #afc1ff'rgb-illustration': '121 137 255', // #7989ff'rgb-illustration-strong': '60 70 255', // #3c46ff+ 'rgb-scrollbar-thumb': '255 255 255', // #ffffff+ 'rgb-page-canvas': '23 23 23', // #171717 (gray-850)+ 'rgb-select-fill': '255 255 255', // #ffffff+ 'rgb-select-edge': '142 142 160', // #8e8ea0+ 'rgb-button-neutral-border': '66 66 66', // #424242 (gray-600)+ 'rgb-button-neutral-text': '255 255 240', // #fffff0+ 'rgb-button-neutral-hover': '66 66 66', // #424242 (gray-600)+ 'rgb-link-inline': '82 160 255', // #52a0ff+ 'rgb-toast-edge': '67 90 111', // #435a6f+ 'rgb-stroke-ink': '255 255 255', // #ffffff at 30%'rgb-file-document': '255 85 136', // #ff5588'rgb-file-sheet': '16 163 127', // #10a37f'rgb-file-code': '255 110 60', // #ff6e3cdiff --git a/packages/client/src/theme/themes/default.ts b/packages/client/src/theme/themes/default.tsindex e53f9e9394..2940635b8d 100644--- a/packages/client/src/theme/themes/default.ts+++ b/packages/client/src/theme/themes/default.ts@@ -146,6 +146,16 @@ export const defaultTheme: IThemeRGB = {'rgb-illustration-subtle': '175 193 255', // #afc1ff'rgb-illustration': '121 137 255', // #7989ff'rgb-illustration-strong': '60 70 255', // #3c46ff+ 'rgb-scrollbar-thumb': '0 0 0', // #000000+ 'rgb-page-canvas': '247 247 248', // #f7f7f8 (gray-50, matching surface-primary-alt)+ 'rgb-select-fill': '255 255 255', // #ffffff+ 'rgb-select-edge': '142 142 160', // #8e8ea0+ 'rgb-button-neutral-border': '0 0 0', // #000000 at 10%+ 'rgb-button-neutral-text': '64 65 79', // #40414f+ 'rgb-button-neutral-hover': '236 236 241', // #ececf1 (gray-20)+ 'rgb-link-inline': '0 102 204', // #0066cc+ 'rgb-toast-edge': '67 90 111', // #435a6f+ 'rgb-stroke-ink': '0 0 0', // #000000 at 10%'rgb-file-document': '255 85 136', // #ff5588'rgb-file-sheet': '16 163 127', // #10a37f'rgb-file-code': '255 110 60', // #ff6e3cdiff --git a/packages/client/src/theme/themes/highContrast.spec.ts b/packages/client/src/theme/themes/highContrast.spec.tsindex f2a0c61875..031cab17aa 100644--- a/packages/client/src/theme/themes/highContrast.spec.ts+++ b/packages/client/src/theme/themes/highContrast.spec.ts@@ -182,6 +182,13 @@ describe.each([expect(theme['rgb-surface-code']).toBe(source);});+ it('paints the page canvas in the mode canvas, black in dark and white in light', () => {+ const expected = theme === highContrastDarkTheme ? '0 0 0' : '255 255 255';++ expect(theme['rgb-page-canvas']).toBe(expected);+ expect(theme['rgb-page-canvas']).toBe(theme['rgb-surface-primary']);+ });+it('keeps neutral text at WCAG AAA on every canvas and hover fill', () => {expect(below(theme, WCAG_AAA_NORMAL, textTokens, surfaces)).toEqual([]);});diff --git a/packages/client/src/theme/themes/highContrast.ts b/packages/client/src/theme/themes/highContrast.tsindex 15ff324da7..37cb78c1e8 100644--- a/packages/client/src/theme/themes/highContrast.ts+++ b/packages/client/src/theme/themes/highContrast.ts@@ -181,6 +181,16 @@ export const highContrastLightTheme: IThemeRGB = {'rgb-illustration-subtle': '175 193 255', // #afc1ff'rgb-illustration': '121 137 255', // #7989ff'rgb-illustration-strong': '60 70 255', // #3c46ff+ 'rgb-scrollbar-thumb': '0 0 0', // #000000+ 'rgb-page-canvas': '255 255 255', // #ffffff (matching surface-primary)+ 'rgb-select-fill': '255 255 255', // #ffffff+ 'rgb-select-edge': '142 142 160', // #8e8ea0+ 'rgb-button-neutral-border': '0 0 0', // #000000 at 10%+ 'rgb-button-neutral-text': '64 65 79', // #40414f+ 'rgb-button-neutral-hover': '236 236 241', // #ececf1 (gray-20)+ 'rgb-link-inline': '0 102 204', // #0066cc+ 'rgb-toast-edge': '67 90 111', // #435a6f+ 'rgb-stroke-ink': '0 0 0', // #000000 at 10%/** File-type tiles: each hue stepped so the glyph clears 6.5:1 on it (white glyph). */'rgb-file-document': '176 0 78', // #b0004e'rgb-file-sheet': '0 107 79', // #006b4f@@ -382,6 +392,16 @@ export const highContrastDarkTheme: IThemeRGB = {'rgb-illustration-subtle': '175 193 255', // #afc1ff'rgb-illustration': '121 137 255', // #7989ff'rgb-illustration-strong': '60 70 255', // #3c46ff+ 'rgb-scrollbar-thumb': '255 255 255', // #ffffff+ 'rgb-page-canvas': '0 0 0', // #000000 (matching surface-primary)+ 'rgb-select-fill': '255 255 255', // #ffffff+ 'rgb-select-edge': '142 142 160', // #8e8ea0+ 'rgb-button-neutral-border': '66 66 66', // #424242 (gray-600)+ 'rgb-button-neutral-text': '255 255 240', // #fffff0+ 'rgb-button-neutral-hover': '66 66 66', // #424242 (gray-600)+ 'rgb-link-inline': '82 160 255', // #52a0ff+ 'rgb-toast-edge': '67 90 111', // #435a6f+ 'rgb-stroke-ink': '255 255 255', // #ffffff at 30%/** File-type tiles: each hue stepped so the glyph clears 6.5:1 on it (black glyph, light tiles on the black canvas). */'rgb-file-document': '255 158 194', // #ff9ec2'rgb-file-sheet': '95 224 184', // #5fe0b8diff --git a/packages/client/src/theme/tokens.css b/packages/client/src/theme/tokens.cssindex b10794a92a..1567e1bec5 100644--- a/packages/client/src/theme/tokens.css+++ b/packages/client/src/theme/tokens.css@@ -29,6 +29,16 @@--color-illustration-subtle: rgb(var(--illustration-subtle));--color-illustration: rgb(var(--illustration));--color-illustration-strong: rgb(var(--illustration-strong));+ --color-scrollbar-thumb: rgb(var(--scrollbar-thumb));+ --color-page-canvas: rgb(var(--page-canvas));+ --color-select-fill: rgb(var(--select-fill));+ --color-select-edge: rgb(var(--select-edge));+ --color-button-neutral-border: rgb(var(--button-neutral-border));+ --color-button-neutral-text: rgb(var(--button-neutral-text));+ --color-button-neutral-hover: rgb(var(--button-neutral-hover));+ --color-link-inline: rgb(var(--link-inline));+ --color-toast-edge: rgb(var(--toast-edge));+ --color-stroke-ink: rgb(var(--stroke-ink));--color-file-document: rgb(var(--file-document));--color-file-sheet: rgb(var(--file-sheet));--color-file-code: rgb(var(--file-code));diff --git a/packages/client/src/theme/types/index.ts b/packages/client/src/theme/types/index.tsindex b954b5c63a..36fd642795 100644--- a/packages/client/src/theme/types/index.ts+++ b/packages/client/src/theme/types/index.ts@@ -195,6 +195,20 @@ export interface IThemeRGB {'rgb-illustration-subtle'?: string;'rgb-illustration'?: string;'rgb-illustration-strong'?: string;+ /** The stylesheet-level roles: the webkit scrollbar thumb, the dark page behind the app, a native+ * `select`'s fill and edge, the legacy `.btn-neutral` border, ink and hover fill, inline links in+ * mobile.css, the toast's shadow tint, and the ink of the avatar's translucent ring. The opacities+ * of the thumb and ring stay in CSS; the neutral border's is `buttonNeutralBorderOpacity`. */+ 'rgb-scrollbar-thumb'?: string;+ 'rgb-page-canvas'?: string;+ 'rgb-select-fill'?: string;+ 'rgb-select-edge'?: string;+ 'rgb-button-neutral-border'?: string;+ 'rgb-button-neutral-text'?: string;+ 'rgb-button-neutral-hover'?: string;+ 'rgb-link-inline'?: string;+ 'rgb-toast-edge'?: string;+ 'rgb-stroke-ink'?: string;/** File-type tiles: one fill per kind of file and the ink of the glyph drawn on them. */'rgb-file-document'?: string;'rgb-file-sheet'?: string;@@ -382,6 +396,16 @@ export interface IThemeVariables {'--illustration-subtle': string;'--illustration': string;'--illustration-strong': string;+ '--scrollbar-thumb': string;+ '--page-canvas': string;+ '--select-fill': string;+ '--select-edge': string;+ '--button-neutral-border': string;+ '--button-neutral-text': string;+ '--button-neutral-hover': string;+ '--link-inline': string;+ '--toast-edge': string;+ '--stroke-ink': string;'--file-document': string;'--file-sheet': string;'--file-code': string;@@ -542,6 +566,16 @@ export interface IThemeColors {'illustration-subtle'?: string;illustration?: string;'illustration-strong'?: string;+ 'scrollbar-thumb'?: string;+ 'page-canvas'?: string;+ 'select-fill'?: string;+ 'select-edge'?: string;+ 'button-neutral-border'?: string;+ 'button-neutral-text'?: string;+ 'button-neutral-hover'?: string;+ 'link-inline'?: string;+ 'toast-edge'?: string;+ 'stroke-ink'?: string;'file-document'?: string;'file-sheet'?: string;'file-code'?: string;@@ -711,6 +745,8 @@ export interface IThemeAppearance {scrimOpacity: string;alertScrimOpacity: string;modalScrimOpacity: string;+ /** Opacity of the `.btn-neutral` border ink: a hairline tint by default, solid where a theme names its stroke. */+ buttonNeutralBorderOpacity: string;elevationSurface: string;/** The lift a dragged badge takes while it is held. */elevationDrag: string;diff --git a/packages/client/src/theme/utils/applyTheme.spec.ts b/packages/client/src/theme/utils/applyTheme.spec.tsindex 3b60f49446..2f2d172cf1 100644--- a/packages/client/src/theme/utils/applyTheme.spec.ts+++ b/packages/client/src/theme/utils/applyTheme.spec.ts@@ -328,6 +328,16 @@ describe('applyTheme', () => {expect(root.style.getPropertyValue('--shimmer-base')).toBe('90 80 70');});+ it('carries a legacy theme without a page canvas onto its alternate surface', () => {+ const root = document.documentElement;++ applyTheme({ 'rgb-surface-primary-alt': '12 13 14' }, root);+ expect(root.style.getPropertyValue('--page-canvas')).toBe('12 13 14');++ applyTheme({ 'rgb-surface-primary-alt': '12 13 14', 'rgb-page-canvas': '1 2 3' }, root);+ expect(root.style.getPropertyValue('--page-canvas')).toBe('1 2 3');+ });+it('carries a legacy theme without muted text onto its tertiary text color', () => {const root = document.documentElement;diff --git a/packages/client/src/theme/utils/applyTheme.ts b/packages/client/src/theme/utils/applyTheme.tsindex b010c818f0..c3dc3ae536 100644--- a/packages/client/src/theme/utils/applyTheme.ts+++ b/packages/client/src/theme/utils/applyTheme.ts@@ -62,6 +62,11 @@ function mapColors(colors: IThemeRGB, base?: IThemeRGB): Array<[string, string]>variables.push(['--shimmer-base', colors['rgb-text-primary']]);}+ /** The dark page was `surface-primary-alt` before it had a role, as in `resolveTheme`. */+ if (colors['rgb-page-canvas'] === undefined && colors['rgb-surface-primary-alt'] !== undefined) {+ variables.push(['--page-canvas', colors['rgb-surface-primary-alt']]);+ }+if (colors['rgb-text-muted'] === undefined && colors['rgb-text-tertiary'] !== undefined) {variables.push(['--text-muted', colors['rgb-text-tertiary']]);}diff --git a/packages/data-provider/src/theme.ts b/packages/data-provider/src/theme.tsindex 04932c2ae3..ab31d708fe 100644--- a/packages/data-provider/src/theme.ts+++ b/packages/data-provider/src/theme.ts@@ -137,6 +137,16 @@ export const themeColorTokens = Object.freeze(['rgb-illustration-subtle','rgb-illustration','rgb-illustration-strong',+ 'rgb-scrollbar-thumb',+ 'rgb-page-canvas',+ 'rgb-select-fill',+ 'rgb-select-edge',+ 'rgb-button-neutral-border',+ 'rgb-button-neutral-text',+ 'rgb-button-neutral-hover',+ 'rgb-link-inline',+ 'rgb-toast-edge',+ 'rgb-stroke-ink','rgb-file-document','rgb-file-sheet','rgb-file-code',@@ -497,6 +507,7 @@ const appearanceValidators = {scrimOpacity: isOpacity,alertScrimOpacity: isOpacity,modalScrimOpacity: isOpacity,+ buttonNeutralBorderOpacity: isOpacity,/** Released themes may hold `var()` here, so this role keeps its original, looser check. */elevationSurface: (value: unknown) =>typeof value === 'string' && value.trim().length > 0 && !/[;{}]|url\s*\(/i.test(value),diff --git a/scripts/css-colors.mts b/scripts/css-colors.mtsindex 4fc513253d..4cca31a00a 100644--- a/scripts/css-colors.mts+++ b/scripts/css-colors.mts@@ -1,8 +1,9 @@/*** Finds colour literals in CSS. The design lint reads JSX, so a stylesheet under* `client/src` or `packages/client/src` is outside it; this is the gate for those files.- * A colour belongs to a theme role (`rgb(var(--black) / 0.1)`), so only the theme token- * sources and the files `packages/client/src/theme/allowlist.md` records may hold a literal.+ * A colour belongs to a theme role (`rgb(var(--black) / 0.1)`), so only the custom properties of the theme+ * token sources and the rules `packages/client/src/theme/allowlist.md` records may hold a literal, and a+ * channel triplet (`--x: 255 0 0`) is a literal in a custom property, so it lives in those sources too.*/import { readFileSync, readdirSync } from 'node:fs';@@ -17,7 +18,7 @@ export interface CssColorFinding {export const CSS_ROOTS = ['client/src', 'packages/client/src'];-/** Theme token sources (allowlist.md entry 1). */+/** Theme token sources (allowlist.md entry 1): their custom property declarations may hold a literal or a channel triplet. */export const CSS_COLOR_ALLOWED_FILES = ['packages/client/src/theme/defaults.css','packages/client/src/theme/tokens.css',@@ -44,7 +45,18 @@ const NAMED_COLORS =const HEX = /#[0-9a-fA-F]{3,8}(?![\w-])/g;const FUNCTION =- /(?<![\w-])(?:(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\(\s*var\(\s*--[\w-]+\s*,\s*[\d.+-]|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\(\s*from\s+(?:var\([^)]*\)|[^\s)]+)\s+[\d.+-]|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\(\s*(?:[\d.+-]|none\b|(?:calc|min|max|clamp|abs|sign|round|mod|rem|sin|cos|tan|asin|acos|atan2?|pow|sqrt|hypot|log|exp)\(|(?:var\([^)]*\)\s*,?\s*)+[\d.+-])|color\(\s*(?!from\b)[a-z0-9-]+\s+(?:(?:var\([^)]*\)\s*,?\s*)*[\d.+-]|none\b))/gi;+ /(?<![\w-])(?:(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\(\s*var\(\s*--[\w-]+\s*,\s*[\d.+-]|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\(\s*(?:[\d.+-]|none\b|(?:calc|min|max|clamp|abs|sign|round|mod|rem|sin|cos|tan|asin|acos|atan2?|pow|sqrt|hypot|log|exp)\(|(?:var\([^)]*\)\s*,?\s*)+[\d.+-])|color\(\s*(?!from\b)[a-z0-9-]+\s+(?:(?:var\([^)]*\)\s*,?\s*)*[\d.+-]|none\b))/gi;+const RELATIVE_COLOR = /(?<![\w-])(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\(\s*from\s+/gi;+const CHANNEL_KEYWORD = /(?<![\w-])(?:[rgbhslwcaxyz]|alpha)(?![\w-])/i;+const CHANNEL = '[+-]?(?:\\d+\\.?\\d*|\\.\\d+)%?';+const SEPARATOR = '(?:\\s*,\\s*|\\s+)';+const BARE_TRIPLET = `${CHANNEL}${SEPARATOR}${CHANNEL}${SEPARATOR}${CHANNEL}(?:\\s*/\\s*(?:${CHANNEL}|var\\([^)]*\\)))?`;+/** The whole value is three bare channels, or one is the fallback of a `var()`. */+const TRIPLET = new RegExp(+ `^\\s*${BARE_TRIPLET}\\s*$|var\\(\\s*--[\\w-]+\\s*,\\s*${BARE_TRIPLET}\\s*\\)`,+ 'i',+);+const TRIPLET_FALLBACK = new RegExp(`^var\\(\\s*--[\\w-]+\\s*,\\s*${BARE_TRIPLET}\\s*\\)$`, 'i');const NAMED = new RegExp(`(?<![\\w.-])(?:${NAMED_COLORS.join('|')})(?![\\w.-])`, 'gi');/** Properties whose values are identifiers or names, where a colour keyword is not a colour. */const NON_COLOR_PROPERTY =@@ -82,15 +94,84 @@ function colourText(value: string): string {.replace(STRING, blank);}+interface Token {+ text: string;+ end: number;+}++/** The top-level, space-separated tokens of a function body, up to its closing parenthesis or the alpha slash. */+function relativeTokens(text: string, start: number): Token[] {+ const tokens: Token[] = [];+ let depth = 0;+ let tokenStart = -1;+ const close = (end: number): void => {+ if (tokenStart >= 0) tokens.push({ text: text.slice(tokenStart, end), end });+ tokenStart = -1;+ };+ for (let i = start; i < text.length; i++) {+ const char = text[i];+ if (depth === 0 && (char === ')' || char === '/')) {+ close(i);+ return tokens;+ }+ if (depth === 0 && /[\s,]/.test(char)) {+ close(i);+ continue;+ }+ if (tokenStart < 0) tokenStart = i;+ if (char === '(') depth++;+ if (char === ')') depth--;+ }+ close(text.length);+ return tokens;+}++const isFixedFallback = (channel: string): boolean => {+ const fallback = /^var\(\s*--[\w-]+\s*,\s*([\s\S]*)\)$/i.exec(channel)?.[1];+ return fallback !== undefined && isFixedChannel(fallback.trim());+};++function isFixedChannel(channel: string): boolean {+ return (+ /^[\d.+-]/.test(channel) ||+ /^none$/i.test(channel) ||+ isFixedFallback(channel) ||+ (/^[\w-]+\(/.test(channel) && !/^var\(/i.test(channel) && !CHANNEL_KEYWORD.test(channel))+ );+}++/**+ * A relative colour keeps its origin's channels by name (`r g b`); a number, `none` or a function+ * that names no channel replaces one with a fixed value, so the colour no longer follows the theme.+ * The alpha after the slash is not a colour channel.+ */+function relativeLiterals(text: string): Array<{ literal: string; offset: number }> {+ return Array.from(text.matchAll(RELATIVE_COLOR)).flatMap((match) => {+ const offset = match.index ?? 0;+ const bodyStart = offset + match[0].length;+ const isColorFunction = /^color\(/i.test(match[0]);+ const [origin, ...rest] = relativeTokens(text, bodyStart);+ if (origin && TRIPLET_FALLBACK.test(origin.text)) {+ return [{ literal: text.slice(offset, origin.end), offset }];+ }+ const channels = rest.slice(isColorFunction ? 1 : 0, isColorFunction ? 4 : 3);+ const fixed = channels.find((channel) => isFixedChannel(channel.text));+ return fixed ? [{ literal: text.slice(offset, fixed.end), offset }] : [];+ });+}+function literalsIn(property: string, value: string): Array<{ literal: string; offset: number }> {const text = colourText(value);const patterns = NON_COLOR_PROPERTY.test(property) ? [HEX, FUNCTION] : [HEX, FUNCTION, NAMED];- return patterns.flatMap((pattern) =>- Array.from(text.matchAll(pattern), (match) => ({- literal: match[0],- offset: match.index ?? 0,- })),- );+ return [+ ...patterns.flatMap((pattern) =>+ Array.from(text.matchAll(pattern), (match) => ({+ literal: match[0],+ offset: match.index ?? 0,+ })),+ ),+ ...relativeLiterals(text),+ ];}const isAllowed = (allowedRules: AllowedRule[], selector: string, property: string): boolean =>@@ -99,17 +180,28 @@ const isAllowed = (allowedRules: AllowedRule[], selector: string, property: strirule.selector === selector && (rule.property === undefined || rule.property === property),);-/** Parses the stylesheet so a declaration is read whole, whatever lines it spans or shares. */+/**+ * Parses the stylesheet so a declaration is read whole, whatever lines it spans or shares.+ * A token source may declare custom properties with literals and channel triplets, so+ * `tokenSource` skips those declarations and still checks every other one.+ */export function findCssColorLiterals(css: string,allowedRules: AllowedRule[] = [],+ tokenSource = false,): CssColorFinding[] {const findings: CssColorFinding[] = [];postcss.parse(css).walkDecls((declaration) => {+ const isCustomProperty = declaration.prop.startsWith('--');+ if (tokenSource && isCustomProperty) return;const parent = declaration.parent;const selector = parent?.type === 'rule' ? parent.selector : '';if (isAllowed(allowedRules, selector, declaration.prop)) return;const line = declaration.source?.start?.line ?? 1;+ if (isCustomProperty && TRIPLET.test(colourText(declaration.value))) {+ findings.push({ line, literal: declaration.value.trim() });+ return;+ }literalsIn(declaration.prop, declaration.value).forEach(({ literal, offset }) => {const before = colourText(declaration.value).slice(0, offset);findings.push({ line: line + before.split('\n').length - 1, literal });@@ -127,15 +219,15 @@ function listCssFiles(directory: string): string[] {});}-/** Every finding outside the allowed files, as `path:line literal` lines. */+/** Every finding, as `path:line literal` lines; the token sources are read for everything but their custom properties. */export function scanCssColors(root: string): string[] {return CSS_ROOTS.flatMap((directory) => listCssFiles(join(root, directory))).map((path) => relative(root, path).split('\\').join('/'))- .filter((path) => !CSS_COLOR_ALLOWED_FILES.includes(path)).flatMap((path) =>findCssColorLiterals(readFileSync(join(root, path), 'utf8'),CSS_COLOR_ALLOWED_RULES[path],+ CSS_COLOR_ALLOWED_FILES.includes(path),).map(({ line, literal }) => `${path}:${line} ${literal}`),);}diff --git a/scripts/css-colors.test.mts b/scripts/css-colors.test.mtsindex 5ef0e1c144..8fc8768138 100644--- a/scripts/css-colors.test.mts+++ b/scripts/css-colors.test.mts@@ -17,14 +17,13 @@ test('reports hex, numeric colour functions and named colours in values', () =>assert.deepEqual(literals(css), ['#0066cc', 'rgba(0', 'hsl(1', 'white', '#FFF']);});-test('accepts theme variables, channel triplets, comments, urls and selectors', () => {+test('accepts theme variables, comments, urls and selectors', () => {const css = ['/* was #0066cc and rgba(0, 0, 0, 0.1) */','#fade, #root { color: rgb(var(--text-primary)); }','a {',' background: rgb(var(--black) / 0.1);',' box-shadow: 0 1px 2px rgb(var(--slate-ink) / 0.3);',- ' --text-muted: 105 110 121;',' --on-white: var(--white);',' border-color: theme(colors.gray.200);'," background-image: url('sprite.svg#fff');",@@ -155,3 +154,54 @@ test('reads numeric fallbacks inside a colour function var()', () => {assert.equal(literals('a { color: rgb(var(--brand, 255 0 0)); }').length, 1);assert.deepEqual(literals('a { color: rgb(var(--c) / var(--a, 1)); }'), []);});++test('reads fixed channels in color(from) and every colour channel of a relative function', () => {+ assert.equal(literals('a { color: color(from var(--base) srgb r g 0); }').length, 1);+ assert.equal(literals('a { color: rgb(from var(--base) r 128 b); }').length, 1);+ assert.equal(literals('a { color: hsl(from var(--base) h none l); }').length, 1);+ assert.equal(literals('a { color: rgb(from var(--base) r g calc(255)); }').length, 1);+ assert.deepEqual(literals('a { color: color(from var(--base) srgb r g b / 0.5); }'), []);+ assert.deepEqual(literals('a { color: rgb(from var(--base) calc(r + 10) g b / 0.5); }'), []);+});++test('reads a channel triplet in a custom property', () => {+ assert.deepEqual(literals('a { --x: 255 0 0; }'), ['255 0 0']);+ assert.deepEqual(literals('a { --x: 0.5 0.2 1 / 0.4; }'), ['0.5 0.2 1 / 0.4']);+ assert.deepEqual(literals('a { --x: var(--a); --y: 1 2; --z: 0.5; }'), []);+ assert.deepEqual(literals('a { margin: 1 2 3; }'), []);+});++test('a token source exempts its custom properties only', () => {+ const css = ':root { --x: 255 0 0; --y: #fff; }\na { color: #fff; width: calc(1 * 2); }';+ assert.deepEqual(findCssColorLiterals(css, [], true), [{ line: 2, literal: '#fff' }]);+});++test('reads literal origins and fallbacks of a relative colour', () => {+ assert.deepEqual(literals('a { color: rgb(from #ff0000 r g b); }'), ['#ff0000']);+ assert.deepEqual(literals('a { color: color(from #fff srgb r g b); }'), ['#fff']);+ assert.deepEqual(literals('a { color: rgb(from var(--base, #fff) r g b); }'), ['#fff']);+ assert.deepEqual(literals('a { color: rgb(from var(--base) r g b); }'), []);+ assert.deepEqual(literals('a { color: rgb(from var(--base) r g var(--channel, 255)); }'), [+ 'rgb(from var(--base) r g var(--channel, 255)',+ ]);+ assert.deepEqual(literals('a { color: rgb(from var(--base) r g var(--channel)); }'), []);+ assert.deepEqual(literals('a { color: rgb(from var(--base, 255 0 0) r g b); }'), [+ 'rgb(from var(--base, 255 0 0)',+ ]);+ assert.deepEqual(literals('a { color: rgb(from var(--base) r g var(--channel, none)); }'), [+ 'rgb(from var(--base) r g var(--channel, none)',+ ]);+ assert.deepEqual(literals('a { --brand: 255 0 0 / var(--alpha); }'), ['255 0 0 / var(--alpha)']);+});++test('reads percentage channels and triplets inside a var() fallback', () => {+ assert.deepEqual(literals('a { --brand: 100% 0% 0%; }'), ['100% 0% 0%']);+ assert.deepEqual(literals('a { --brand: var(--configured, 255 0 0); }'), [+ 'var(--configured, 255 0 0)',+ ]);+ assert.deepEqual(literals('a { --brand: 255, 0, 0; }'), ['255, 0, 0']);+ assert.deepEqual(literals('a { --brand: VAR(--configured, 255 0 0); }'), [+ 'VAR(--configured, 255 0 0)',+ ]);+ assert.deepEqual(literals('a { --offset: 0 1px 2px; --size: 1.5rem 2rem 3rem; }'), []);+});diff --git a/scripts/static-checks.mts b/scripts/static-checks.mtsindex dd3c3b54bc..8b94544e32 100644--- a/scripts/static-checks.mts+++ b/scripts/static-checks.mts@@ -115,6 +115,9 @@ const FILTERS = {'client/src/**/*.css','packages/client/src/**/*.css','packages/client/src/theme/allowlist.md',+ /** The scanner parses with postcss: an upgrade changes what it reads. */+ 'package.json',+ 'package-lock.json','scripts/css-colors.test.mts','scripts/css-colors.mts','scripts/static-checks.mts',