Skip to content

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

🎨 refactor: Route Stylesheet Colours Through Theme Variables (#16823)

Marco Beretta3ca084a6cf3a
diff --git a/.github/workflows/static-checks.yml b/.github/workflows/static-checks.yml
index 64fd631e62..755e9a51f1 100644
--- a/.github/workflows/static-checks.yml
+++ b/.github/workflows/static-checks.yml
@@ -94,6 +94,15 @@ jobs:
- 'scripts/static-checks.mts'
- '.github/workflows/static-checks.yml'
- '!**.md'
+ # Stylesheets are outside the design lint, which reads JSX.
+ css_colors:
+ - 'client/src/**/*.css'
+ - 'packages/client/src/**/*.css'
+ - 'packages/client/src/theme/allowlist.md'
+ - 'scripts/css-colors.mts'
+ - 'scripts/css-colors.test.mts'
+ - 'scripts/static-checks.mts'
+ - '.github/workflows/static-checks.yml'
config:
- 'api/**'
- 'config/**'
@@ -310,6 +319,14 @@ jobs:
BASE_SHA=$(jq --raw-output .pull_request.base.sha "$GITHUB_EVENT_PATH")
node scripts/static-checks.mts --against "$BASE_SHA" --only suppressions
+ - name: Check CSS colour literals
+ id: css_colors
+ if: always() && steps.paths.outputs.css_colors == 'true'
+ continue-on-error: true
+ run: |
+ BASE_SHA=$(jq --raw-output .pull_request.base.sha "$GITHUB_EVENT_PATH")
+ node scripts/static-checks.mts --against "$BASE_SHA" --only css-colors
+
- name: Restore data-provider build cache
if: always() && steps.paths.outputs.config == 'true'
id: cache-data-provider
@@ -653,6 +670,7 @@ jobs:
ESLINT_CONFIG_OUTCOME: ${{ steps.eslint_config.outcome }}
DESIGN_RULES_BUILD_OUTCOME: ${{ steps.design_rules_build.outcome }}
SUPPRESSIONS_OUTCOME: ${{ steps.suppressions.outcome }}
+ CSS_COLORS_OUTCOME: ${{ steps.css_colors.outcome }}
PRETTIER_OUTCOME: ${{ steps.prettier.outcome }}
IMPORT_SORT_OUTCOME: ${{ steps.import_sort.outcome }}
RUNNER_OUTCOME: ${{ steps.runner.outcome }}
@@ -692,6 +710,7 @@ jobs:
record_failure "ESLint config validation" "$ESLINT_CONFIG_OUTCOME"
record_failure "Client-package build for the design rules" "$DESIGN_RULES_BUILD_OUTCOME"
record_failure "Design-rule suppressions" "$SUPPRESSIONS_OUTCOME"
+ record_failure "CSS colour literals" "$CSS_COLORS_OUTCOME"
record_failure "Prettier" "$PRETTIER_OUTCOME"
record_failure "Import sorting" "$IMPORT_SORT_OUTCOME"
record_failure "Local static-checks runner" "$RUNNER_OUTCOME"
diff --git a/client/src/mobile.css b/client/src/mobile.css
index be3775f33d..14e0716ffe 100644
--- a/client/src/mobile.css
+++ b/client/src/mobile.css
@@ -182,14 +182,14 @@
* v4's layers it would beat every utility instead — `no-underline` on a link inside a list stopped
* working. Layered, it loses to a utility again and still styles an unclassed list link. */
p.whitespace-pre-wrap a {
- color: #0066cc;
+ color: rgb(var(--link-inline));
text-decoration: underline;
font-weight: bold;
}
@layer base {
li a {
- color: #0066cc;
+ color: rgb(var(--link-inline));
text-decoration: underline;
font-weight: bold;
}
@@ -197,5 +197,5 @@ p.whitespace-pre-wrap a {
.dark p.whitespace-pre-wrap a,
.dark li a {
- color: #52a0ff;
+ color: rgb(var(--link-inline));
}
diff --git a/client/src/style.css b/client/src/style.css
index d479ecb8d7..86d0bd4360 100644
--- a/client/src/style.css
+++ b/client/src/style.css
@@ -377,8 +377,8 @@ html.high-contrast.dark .btn-neutral:hover {
background-repeat: no-repeat;
background-size: 1.5em 1.5em;
padding-right: 2.5rem;
- background-color: #fff;
- border-color: #8e8ea0;
+ background-color: rgb(var(--select-fill));
+ border-color: rgb(var(--select-edge));
border-radius: 0;
border-width: 1px;
font-size: 1rem;
@@ -998,68 +998,13 @@ pre[class*='language-'] {
cursor: not-allowed;
opacity: 0.5;
}
-.btn-primary {
- --tw-bg-opacity: 1;
- --tw-text-opacity: 1;
- background-color: rgba(16, 163, 127, var(--tw-bg-opacity));
- color: rgba(255, 255, 255, var(--tw-text-opacity));
-}
-.btn-primary:hover {
- --tw-bg-opacity: 1;
- background-color: rgba(26, 127, 100, var(--tw-bg-opacity));
-}
-.btn-primary:focus {
- --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width)
- var(--tw-ring-offset-color);
- --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width))
- var(--tw-ring-color);
- --tw-ring-offset-width: 2px;
- box-shadow:
- var(--tw-ring-offset-shadow),
- var(--tw-ring-shadow),
- 0 0 transparent;
- box-shadow:
- var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 transparent);
-}
-.btn-primary.focus-visible {
- --tw-ring-opacity: 1;
- --tw-ring-color: rgba(25, 195, 125, var(--tw-ring-opacity));
-}
-.btn-primary:focus-visible {
- --tw-ring-opacity: 1;
- --tw-ring-color: rgba(25, 195, 125, var(--tw-ring-opacity));
-}
-.btn-primary:disabled:hover {
- --tw-bg-opacity: 1;
- background-color: rgba(16, 163, 127, var(--tw-bg-opacity));
-}
-.btn-secondary {
- --tw-border-opacity: 1;
- --tw-bg-opacity: 1;
- --tw-text-opacity: 1;
- background-color: transparent;
- background-color: rgba(16, 163, 156, var(--tw-bg-opacity));
- color: rgba(255, 255, 255, var(--tw-text-opacity));
-}
-.btn-secondary:hover {
- --tw-bg-opacity: 1;
- border-color: rgba(0, 0, 0, 0.1);
- color: rgba(64, 65, 79, var(--tw-text-opacity));
- background-color: rgba(236, 236, 241, var(--tw-bg-opacity));
-}
-.dark .btn-secondary:hover {
- --tw-bg-opacity: 1;
- border-color: rgba(8, 82, 78, var(--tw-border-opacity));
- color: rgba(255, 255, 240, var(--tw-text-opacity));
- background-color: rgba(8, 82, 78, var(--tw-bg-opacity));
-}
.btn-neutral {
--tw-bg-opacity: 1;
--tw-text-opacity: 1;
background-color: rgb(var(--surface-secondary));
- border-color: rgba(0, 0, 0, 0.1);
+ border-color: rgb(var(--button-neutral-border) / var(--button-neutral-border-alpha, 1));
border-width: 1px;
- color: rgba(64, 65, 79, var(--tw-text-opacity));
+ color: rgb(var(--button-neutral-text) / var(--tw-text-opacity));
font-size: 0.875rem;
line-height: 1.25rem;
transition: all 0.1s ease-in-out;
@@ -1067,7 +1012,7 @@ pre[class*='language-'] {
.btn-neutral:hover {
--tw-bg-opacity: 1;
- background-color: rgba(236, 236, 241, var(--tw-bg-opacity));
+ background-color: rgb(var(--button-neutral-hover) / var(--tw-bg-opacity));
}
.btn-neutral:focus {
@@ -1080,13 +1025,13 @@ pre[class*='language-'] {
--tw-bg-opacity: 1;
--tw-text-opacity: 1;
background-color: transparent;
- border-color: rgba(66, 66, 66, var(--tw-border-opacity));
- color: rgba(255, 255, 240, var(--tw-text-opacity));
+ border-color: rgb(var(--button-neutral-border) / var(--tw-border-opacity));
+ color: rgb(var(--button-neutral-text) / var(--tw-text-opacity));
}
.dark .btn-neutral:hover {
--tw-bg-opacity: 1;
- background-color: rgba(66, 66, 66, var(--tw-bg-opacity));
+ background-color: rgb(var(--button-neutral-hover) / var(--tw-bg-opacity));
}
.dark .btn-neutral:focus {
@@ -1110,12 +1055,12 @@ pre[class*='language-'] {
}
::-webkit-scrollbar-thumb {
- background-color: rgba(0, 0, 0, 0.1);
+ background-color: rgb(var(--scrollbar-thumb) / var(--scrollbar-thumb-alpha));
border-radius: 9999px;
}
.dark ::-webkit-scrollbar-thumb {
- background-color: hsla(0, 0%, 100%, 0.1);
+ background-color: rgb(var(--scrollbar-thumb) / var(--scrollbar-thumb-alpha));
}
::-webkit-scrollbar-track {
@@ -1184,7 +1129,7 @@ html[data-drawer-nav] body {
.dark body,
.dark html {
--tw-bg-opacity: 1;
- background-color: rgba(23, 23, 23, var(--tw-bg-opacity));
+ background-color: rgb(var(--page-canvas) / var(--tw-bg-opacity));
}
#__next,
@@ -1316,19 +1261,6 @@ html:not(.high-contrast) .markdown :is(th, td):last-child {
.group:hover .group-hover\:visible {
visibility: visible;
}
-.group:hover .group-hover\:from-\[\#2A2B32\] {
- --tw-gradient-from: #2a2b32;
- --tw-gradient-to: rgba(42, 43, 50, 0);
- --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to);
-}
-.group:hover .group-hover\:text-gray-500 {
- --tw-text-opacity: 1;
- color: rgba(142, 142, 160, var(--tw-text-opacity));
-}
-.group:hover .group-hover\:text-gray-700 {
- --tw-text-opacity: 1;
- color: rgba(64, 65, 79, var(--tw-text-opacity));
-}
.dark .prose {
--tw-prose-body: var(--tw-prose-invert-body);
--tw-prose-headings: var(--tw-prose-invert-headings);
@@ -1473,8 +1405,8 @@ html {
}
.toast-root .alert-root {
box-shadow:
- 0 0 1px rgba(67, 90, 111, 0.3),
- 0 5px 8px -4px rgba(67, 90, 111, 0.3);
+ 0 0 1px rgb(var(--toast-edge) / 0.3),
+ 0 5px 8px -4px rgb(var(--toast-edge) / 0.3);
flex-shrink: 0;
pointer-events: all;
}
@@ -1566,7 +1498,7 @@ html {
}
.avatar-stroke:after,
.shadow-stroke:after {
- --tw-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.1);
+ --tw-shadow: inset 0 0 0 1px rgb(var(--stroke-ink) / var(--stroke-ink-alpha));
--tw-shadow-colored: inset 0 0 0 1px var(--tw-shadow-color);
border-radius: 9999px;
bottom: 0;
@@ -1590,7 +1522,7 @@ html {
}
.dark .avatar-stroke:after,
.dark .shadow-stroke:after {
- --tw-shadow: inset 0 0 0 1px hsla(0, 0%, 100%, 0.3);
+ --tw-shadow: inset 0 0 0 1px rgb(var(--stroke-ink) / var(--stroke-ink-alpha));
--tw-shadow-colored: inset 0 0 0 1px var(--tw-shadow-color);
}
@@ -1608,7 +1540,7 @@ html {
}
.assistant-item:after {
- --tw-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.25);
+ --tw-shadow: inset 0 0 0 1px rgb(var(--black) / 0.25);
--tw-shadow-colored: inset 0 0 0 1px var(--tw-shadow-color);
border-radius: 9999px;
bottom: 0;
@@ -1627,7 +1559,7 @@ html {
}
.dark .assistant-item:after {
- --tw-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.25);
+ --tw-shadow: inset 0 0 0 1px rgb(var(--black) / 0.25);
--tw-shadow-colored: inset 0 0 0 0 1px var(--tw-shadow-color);
}
@@ -1999,11 +1931,11 @@ html {
font-size: var(--theme-tooltip-text-size, 1rem);
line-height: 1.5;
color: rgb(var(--text-tooltip, var(--text-primary)));
- box-shadow: var(--theme-tooltip-shadow, 0 2px 4px 0 rgb(0 0 0 / 0.25));
+ box-shadow: var(--theme-tooltip-shadow, 0 2px 4px 0 rgb(var(--black) / 0.25));
}
.tooltip:where(.dark, .dark *) {
- box-shadow: var(--theme-tooltip-shadow, 0 1px 2px 0 rgb(0 0 0 / 0.35));
+ box-shadow: var(--theme-tooltip-shadow, 0 1px 2px 0 rgb(var(--black) / 0.35));
}
@layer base {
@@ -2091,8 +2023,8 @@ html[data-input-modality='keyboard']
/* The `menuShadow` role, whose light default is this literal. */
box-shadow: var(
--theme-menu-shadow,
- 0 10px 15px -3px rgb(0 0 0 / 0.1),
- 0 4px 6px -4px rgb(0 0 0 / 0.1)
+ 0 10px 15px -3px rgb(var(--black) / 0.1),
+ 0 4px 6px -4px rgb(var(--black) / 0.1)
);
transform-origin: var(--popover-transform-origin, top);
opacity: 0;
@@ -2127,8 +2059,8 @@ html[data-input-modality='keyboard']
color: rgb(var(--text-secondary));
box-shadow: var(
--theme-menu-shadow,
- 0 10px 15px -3px rgb(0 0 0 / 0.25),
- 0 4px 6px -4px rgb(0 0 0 / 0.1)
+ 0 10px 15px -3px rgb(var(--black) / 0.25),
+ 0 4px 6px -4px rgb(var(--black) / 0.1)
);
}
diff --git a/packages/client/src/components/Dropdown.css b/packages/client/src/components/Dropdown.css
index 3ecb80481b..e559b0f8cc 100644
--- a/packages/client/src/components/Dropdown.css
+++ b/packages/client/src/components/Dropdown.css
@@ -15,8 +15,8 @@
/* The `menuShadow` role, whose light default is this literal. */
box-shadow: var(
--theme-menu-shadow,
- 0 10px 15px -3px rgb(0 0 0 / 0.1),
- 0 4px 6px -4px rgb(0 0 0 / 0.1)
+ 0 10px 15px -3px rgb(var(--black) / 0.1),
+ 0 4px 6px -4px rgb(var(--black) / 0.1)
);
transform-origin: var(--popover-transform-origin, top);
opacity: 0;
@@ -59,8 +59,8 @@ html.high-contrast .popover-ui {
color: rgb(var(--text-secondary));
box-shadow: var(
--theme-menu-shadow,
- 0 10px 15px -3px rgb(0 0 0 / 0.25),
- 0 4px 6px -4px rgb(0 0 0 / 0.1)
+ 0 10px 15px -3px rgb(var(--black) / 0.25),
+ 0 4px 6px -4px rgb(var(--black) / 0.1)
);
}
diff --git a/packages/client/src/components/Tooltip.css b/packages/client/src/components/Tooltip.css
index e66a27400c..87b793734b 100644
--- a/packages/client/src/components/Tooltip.css
+++ b/packages/client/src/components/Tooltip.css
@@ -11,7 +11,7 @@
font-size: var(--theme-tooltip-text-size, 1rem);
line-height: 1.5;
color: rgb(var(--text-tooltip, var(--text-primary)));
- box-shadow: var(--theme-tooltip-shadow, 0 2px 4px 0 rgb(0 0 0 / 0.25));
+ box-shadow: var(--theme-tooltip-shadow, 0 2px 4px 0 rgb(var(--black) / 0.25));
/* Enhanced layout for longer descriptions */
max-width: 320px;
word-wrap: break-word;
@@ -25,7 +25,7 @@
}
.tooltip:where(.dark, .dark *) {
- box-shadow: var(--theme-tooltip-shadow, 0 1px 2px 0 rgb(0 0 0 / 0.35));
+ box-shadow: var(--theme-tooltip-shadow, 0 1px 2px 0 rgb(var(--black) / 0.35));
}
/* The contrast edge ships with the primitive: the app stylesheet is not part of
diff --git a/packages/client/src/theme/allowlist.md b/packages/client/src/theme/allowlist.md
index 1405b0267b..a377f41ae3 100644
--- a/packages/client/src/theme/allowlist.md
+++ b/packages/client/src/theme/allowlist.md
@@ -2,10 +2,14 @@
Every colour in `client/src` and `packages/client/src` comes from a semantic theme role, except the entries below. Each entry is one kind of colour that must not follow the theme, with the files that hold it and why the theme does not own it. Scrims, chips and progress drawn over the user's own media are not exceptions: they read `surface-media-overlay` and `text-on-media`, which every bundled theme keeps black and white. The drop zone's artwork reads the `illustration` roles, file-type tiles the `file-*` roles, the default avatar's hairline `avatar-edge`, and a dragged badge's lift `elevationDrag`.
-A literal the design lint can see stays recorded in `eslint-suppressions.json` (inline disables
-of the design rules are rejected by the static checks), so its count there is the exception, not
-debt; the file-scoped allow entry for these paths belongs in `eslint.config.mjs`. Everything else
-is invisible to the lint (CSS, strings passed to a canvas or an iframe), so this list is the record.
+A literal the design lint can see is covered either by a per-file `shadcn/no-raw-colors` allow
+block in `eslint.config.mjs` (the brand and decorative marks named below) or by a count in
+`eslint-suppressions.json` (inline disables of the design rules are rejected by the static
+checks), so the count there is the exception, not debt. Everything else
+is 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).
Adding an entry needs the same bar: if a theme author would reasonably want to recolour it, it
is a role, not an exception. Keep the list to ten entries or fewer; a new kind of exception that
@@ -20,5 +24,5 @@ does not fit an entry below is a sign it should be a role.
| 5 | Documents that leave the app | `client/src/utils/markdown.ts`, `client/src/utils/richtext.ts` | The downloaded HTML document's GitHub Primer stylesheet, and inline styles on HTML copied to the clipboard; both are read outside the app, where no theme variables exist and the sender's theme must not travel. The markdown high-contrast branch reads the roles. |
| 6 | Sandboxed iframe documents | `client/src/utils/mermaid.ts`, `client/src/utils/artifacts.ts` | The mermaid document and its zoom controls, and the artifact document's scrollbar thumb, render in their own iframe without theme variables; the token reads' fallbacks and the luminance repair ink are literals by necessity. |
| 7 | Third-party surfaces | `client/src/hooks/Files/useSharePointPicker.ts`, `client/src/components/Artifacts/ArtifactCodeEditor.tsx` | Background of Microsoft's SharePoint file picker iframe, matched to that third party's own surface, and the canvas of Monaco's built-in `vs-dark` editor theme, painted behind the editor while it loads so the Code tab does not flash; Monaco owns that colour, and the high-contrast editor themes already read the roles. |
-| 8 | Library stylesheet elevation | `packages/client/src/components/Dropdown.css`, `packages/client/src/components/Tooltip.css` | Popover and tooltip shadows in black alpha. The app paints `.popover-ui` from its own copy of the Dropdown rules in `client/src/style.css`, so both copies move to `--theme-shadow-lg` together; the tooltip shadow is smaller than any shadow step. |
-| 9 | Fallbacks for a role read at runtime | `client/src/utils/officePreview.ts`, `client/src/hooks/ScreenshotContext.tsx` | Used only when the role's variable is unset; the value painted otherwise is the role, read with `readThemeColor` or from the bundled palette. |
+| 8 | Fallbacks for a role read at runtime | `client/src/utils/officePreview.ts`, `client/src/hooks/ScreenshotContext.tsx` | Used only when the role's variable is unset; the value painted otherwise is the role, read with `readThemeColor` or from the bundled palette. |
+| 9 | Inline image in a base rule | `client/src/style.css` (the `select` rule) | The select arrow is an inline SVG data image, which cannot read a theme variable; its stroke is a fixed neutral gray. The rule's own colours read the `--select-*` roles. |
diff --git a/packages/client/src/theme/defaults.css b/packages/client/src/theme/defaults.css
index d4d145cc46..fb33f31fb9 100644
--- a/packages/client/src/theme/defaults.css
+++ b/packages/client/src/theme/defaults.css
@@ -104,6 +104,18 @@ html {
--text-destructive: var(--red-600);
--link: var(--blue-600);
--link-hover: var(--blue-700);
+ --scrollbar-thumb: var(--black);
+ --scrollbar-thumb-alpha: 0.1;
+ --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;
+ --toast-edge: 67 90 111;
+ --stroke-ink: var(--black);
+ --stroke-ink-alpha: 0.1;
--link-visited: 147 51 234;
--link-prose: var(--link);
--accent-primary: 18 110 107;
@@ -389,6 +401,15 @@ html {
--text-warning: var(--amber-500);
--text-destructive: var(--red-400);
--link: var(--blue-400);
+ --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;
+ --stroke-ink: var(--white);
+ --stroke-ink-alpha: 0.3;
--link-hover: var(--blue-300);
--link-visited: 192 132 252;
--link-prose: var(--text-primary);
diff --git a/scripts/css-colors.mts b/scripts/css-colors.mts
new file mode 100644
index 0000000000..4fc513253d
--- /dev/null
+++ b/scripts/css-colors.mts
@@ -0,0 +1,159 @@
+/**
+ * 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.
+ */
+
+import { readFileSync, readdirSync } from 'node:fs';
+import { join, relative, resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import postcss from 'postcss';
+
+export interface CssColorFinding {
+ line: number;
+ literal: string;
+}
+
+export const CSS_ROOTS = ['client/src', 'packages/client/src'];
+
+/** Theme token sources (allowlist.md entry 1). */
+export const CSS_COLOR_ALLOWED_FILES = [
+ 'packages/client/src/theme/defaults.css',
+ 'packages/client/src/theme/tokens.css',
+];
+
+/** Rules that may hold a literal in an otherwise checked file: the Azure brand gradient (entry 2) and the select arrow's inline SVG (entry 9). */
+export interface AllowedRule {
+ selector: string;
+ /** Limits the exception to one property of the rule; every other declaration is still checked. */
+ property?: string;
+}
+
+export const CSS_COLOR_ALLOWED_RULES: Record<string, AllowedRule[]> = {
+ 'client/src/mobile.css': [{ selector: '.azure-bg-color' }],
+ 'client/src/style.css': [{ selector: 'select', property: 'background-image' }],
+};
+
+const SKIPPED_DIRECTORIES = new Set(['node_modules', 'dist', 'locales']);
+
+const NAMED_COLORS =
+ 'aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkgrey darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkslategrey darkturquoise darkviolet deeppink deepskyblue dimgray dimgrey dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow grey honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightgrey lightpink lightsalmon lightseagreen lightskyblue lightslategray lightslategrey lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray slategrey snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen'.split(
+ ' ',
+ );
+
+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;
+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 =
+ /^(?:font|animation|transition|grid|counter|content|will-change|view-transition|container|src|list-style|quotes|cursor|appearance|mask-(?:mode|type|composite|repeat|clip|origin|position|size)|clip|anchor|position-anchor|scroll-timeline|view-timeline|timeline-scope)/i;
+
+const blank = (match: string): string => match.replace(/[^\n]/g, ' ');
+
+const URL_FUNCTION = /url\(\s*(?:"(?:[^"\\]|\\[\s\S])*"|'(?:[^'\\]|\\[\s\S])*'|[^)]*)\)/gi;
+const STRING = /"(?:[^"\\\n]|\\[\s\S])*"|'(?:[^'\\\n]|\\[\s\S])*'/g;
+
+function decodePayload(payload: string): string {
+ const separator = payload.indexOf(',');
+ const header = payload.slice(0, separator);
+ const body = payload.slice(separator + 1);
+ if (/;base64$/i.test(header)) return Buffer.from(body, 'base64').toString('utf8');
+ try {
+ return decodeURIComponent(body);
+ } catch {
+ return body;
+ }
+}
+
+/** An inline image keeps its payload, decoded, because it cannot read a theme variable. */
+function inlineImagePayload(url: string): string {
+ const payload = url.replace(/^url\(\s*["']?/i, '').replace(/["']?\s*\)$/, '');
+ if (!/^data:image\/svg\+xml/i.test(payload)) return blank(url);
+ return decodePayload(payload).replace(/["';]/g, ' ');
+}
+
+/** The value with strings and external urls blanked; newlines survive so offsets keep their line. */
+function colourText(value: string): string {
+ return value
+ .replace(/\/\*[\s\S]*?\*\//g, blank)
+ .replace(URL_FUNCTION, inlineImagePayload)
+ .replace(STRING, blank);
+}
+
+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,
+ })),
+ );
+}
+
+const isAllowed = (allowedRules: AllowedRule[], selector: string, property: string): boolean =>
+ allowedRules.some(
+ (rule) =>
+ rule.selector === selector && (rule.property === undefined || rule.property === property),
+ );
+
+/** Parses the stylesheet so a declaration is read whole, whatever lines it spans or shares. */
+export function findCssColorLiterals(
+ css: string,
+ allowedRules: AllowedRule[] = [],
+): CssColorFinding[] {
+ const findings: CssColorFinding[] = [];
+ postcss.parse(css).walkDecls((declaration) => {
+ 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;
+ 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 });
+ });
+ });
+ return findings;
+}
+
+function listCssFiles(directory: string): string[] {
+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
+ if (SKIPPED_DIRECTORIES.has(entry.name)) return [];
+ const path = join(directory, entry.name);
+ if (entry.isDirectory()) return listCssFiles(path);
+ return entry.name.endsWith('.css') ? [path] : [];
+ });
+}
+
+/** Every finding outside the allowed files, as `path:line literal` lines. */
+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],
+ ).map(({ line, literal }) => `${path}:${line} ${literal}`),
+ );
+}
+
+/** `node scripts/css-colors.mts`: prints each finding and exits 1 when there is one. */
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const findings = scanCssColors(resolve(dirname(fileURLToPath(import.meta.url)), '..'));
+ if (findings.length > 0) {
+ const rules = Object.entries(CSS_COLOR_ALLOWED_RULES)
+ .map(([file, allowed]) => `${allowed.map(({ selector }) => selector).join(', ')} in ${file}`)
+ .join(', ');
+ console.error(findings.join('\n'));
+ console.error(
+ 'Use a theme variable, for example rgb(var(--black) / 0.1), instead of a colour literal.',
+ );
+ console.error(
+ `Only ${CSS_COLOR_ALLOWED_FILES.join(', ')} and ${rules} may hold one; see packages/client/src/theme/allowlist.md.`,
+ );
+ process.exit(1);
+ }
+}
diff --git a/scripts/css-colors.test.mts b/scripts/css-colors.test.mts
new file mode 100644
index 0000000000..5ef0e1c144
--- /dev/null
+++ b/scripts/css-colors.test.mts
@@ -0,0 +1,157 @@
+import { test } from 'node:test';
+import { strict as assert } from 'node:assert';
+import { findCssColorLiterals } from './css-colors.mts';
+
+const literals = (css: string): string[] => findCssColorLiterals(css).map(({ literal }) => literal);
+
+test('reports hex, numeric colour functions and named colours in values', () => {
+ const css = [
+ 'a {',
+ ' color: #0066cc;',
+ ' background-color: rgba(0, 0, 0, 0.1);',
+ ' border-color: hsl(10 20% 30%);',
+ ' outline: 1px solid white;',
+ ' --accent: #FFF;',
+ '}',
+ ].join('\n');
+ assert.deepEqual(literals(css), ['#0066cc', 'rgba(0', 'hsl(1', 'white', '#FFF']);
+});
+
+test('accepts theme variables, channel triplets, 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');",
+ " content: 'white';",
+ ' transition: color 150ms ease;',
+ '}',
+ ].join('\n');
+ assert.deepEqual(literals(css), []);
+});
+
+test('reports the line of each finding', () => {
+ assert.deepEqual(findCssColorLiterals('a {\n color: red;\n}\n'), [{ line: 2, literal: 'red' }]);
+});
+
+test('exempts only the named rule, not the rest of its file', () => {
+ const css = [
+ '.azure-bg-color {',
+ ' background: linear-gradient(0.375turn, #61bde2, #4389d0);',
+ '}',
+ '.other {',
+ ' color: #0066cc;',
+ '}',
+ ].join('\n');
+ assert.deepEqual(literals(css), ['#61bde2', '#4389d0', '#0066cc']);
+ assert.deepEqual(findCssColorLiterals(css, [{ selector: '.azure-bg-color' }]), [
+ { line: 5, literal: '#0066cc' },
+ ]);
+});
+
+test('reads declarations that share a line with a selector or continue onto another line', () => {
+ assert.deepEqual(literals('.alert { color: #fff; }'), ['#fff']);
+ assert.deepEqual(literals('a{box-shadow:0 1px 2px\n rgb(0 0 0 / 0.1)}'), ['rgb(0']);
+ assert.deepEqual(literals('@media (min-width: 1px) { a { color: red } }'), ['red']);
+});
+
+test('matches colour functions case-insensitively, including color()', () => {
+ assert.deepEqual(literals('a { color: color(srgb 1 0 0); }'), ['color(srgb 1']);
+ assert.deepEqual(literals('a { background: RGB(255 0 0); }'), ['RGB(2']);
+ assert.deepEqual(literals('a { color: color(from var(--x) srgb r g b); }'), []);
+});
+
+test('covers the full named-colour set and upper-case property names', () => {
+ assert.deepEqual(literals('a { color: rebeccapurple; }'), ['rebeccapurple']);
+ assert.deepEqual(literals('a { COLOR: red; }'), ['red']);
+ assert.deepEqual(literals('a { transition: tan 1s; }'), []);
+});
+
+test('reads signed and keyword components and names in any colour-bearing shorthand', () => {
+ assert.deepEqual(literals('a { color: hsl(-10 20% 30%); }'), ['hsl(-']);
+ assert.deepEqual(literals('a { color: rgb(none 0 0); }'), ['rgb(none']);
+ assert.deepEqual(literals('a { filter: drop-shadow(0 0 1px red); }'), ['red']);
+ assert.deepEqual(literals('a { text-decoration: underline red; }'), ['red']);
+ assert.deepEqual(literals('a { transition: color 1s; animation: white 1s; }'), []);
+});
+
+test('strips URL functions and escaped strings whole, and reads mixed variable components', () => {
+ assert.deepEqual(literals('a { background-image: URL(#fff); }'), []);
+ assert.deepEqual(literals('a { content: "a\\"; color: #fff;"; }'), []);
+ assert.deepEqual(literals('a { color: hsl(var(--hue) 100% 50%); }'), ['hsl(var(--hue) 1']);
+ assert.deepEqual(literals('a { color: hsl(var(--h) var(--s) var(--l)); }'), []);
+});
+
+test('reports each occurrence on its own line and reads calc() and mask gradients', () => {
+ assert.deepEqual(
+ findCssColorLiterals('a {\n background: linear-gradient(\n red,\n red\n );\n}'),
+ [
+ { line: 3, literal: 'red' },
+ { line: 4, literal: 'red' },
+ ],
+ );
+ assert.deepEqual(literals('a { color: rgb(calc(255) 0 0); }'), ['rgb(calc(']);
+ assert.deepEqual(literals('a { mask: linear-gradient(red, blue); }'), ['red', 'blue']);
+});
+
+test('reads colours inside inline data images but not external urls', () => {
+ const arrow =
+ 'a { background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg stroke=\'%238e8ea0\'/%3E"); }';
+ assert.deepEqual(literals(arrow), ['#8e8ea0']);
+ assert.deepEqual(literals('a { background-image: url(sprite.svg#fff); }'), []);
+});
+
+test('limits an exception to one property and decodes base64 images', () => {
+ const css =
+ "select { background-image: url('data:image/svg+xml;base64,PHN2ZyBzdHJva2U9JyNmZmYnLz4='); color: red; }";
+ const allowed = [{ selector: 'select', property: 'background-image' }];
+ assert.deepEqual(literals(css), ['#fff', 'red']);
+ assert.deepEqual(findCssColorLiterals(css, allowed), [{ line: 1, literal: 'red' }]);
+});
+
+test('reads comma-separated components after var() and ignores comments inside values', () => {
+ assert.deepEqual(literals('a { color: hsl(var(--h), 100%, 50%); }'), ['hsl(var(--h), 1']);
+ assert.deepEqual(literals('a { color: var(--text) /* fallback: #fff */; }'), []);
+});
+
+test('reads every CSS math function as a colour channel', () => {
+ assert.deepEqual(literals('a { color: rgb(min(255, 300) 0 0); }'), ['rgb(min(']);
+ assert.deepEqual(literals('a { color: hsl(clamp(0, 120, 360) 100% 50%); }'), ['hsl(clamp(']);
+});
+
+test('reads numeric colour profiles, whole function names and later channels after variables', () => {
+ assert.deepEqual(literals('a { color: color(display-p3 1 0 0); }'), ['color(display-p3 1']);
+ assert.deepEqual(literals('a { --value: my-rgb(0); }'), []);
+ assert.deepEqual(literals('a { color: rgb(var(--r) var(--g) 0); }'), ['rgb(var(--r) var(--g) 0']);
+ assert.deepEqual(literals('a { color: rgb(var(--c) / 0.5); }'), []);
+});
+
+test('reads later channels in color() and inspects only SVG data images', () => {
+ assert.deepEqual(literals('a { color: color(display-p3 var(--r) 0 0); }'), [
+ 'color(display-p3 var(--r) 0',
+ ]);
+ assert.deepEqual(literals("a { background: url('data:image/png;base64,cmVk'); }"), []);
+});
+
+test('blanks comments embedded in values', () => {
+ assert.deepEqual(
+ literals('a { background: linear-gradient(/* red to blue */ var(--a), var(--b)); }'),
+ [],
+ );
+ assert.equal(literals('a { color: rgb(/* note */ 255 0 0); }').length, 1);
+});
+
+test('reads fixed channels in relative colours but not pure relative forms', () => {
+ assert.equal(literals('a { color: rgb(from var(--base) 255 g b); }').length, 1);
+ assert.deepEqual(literals('a { color: rgb(from var(--base) r g b / 0.5); }'), []);
+});
+
+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)); }'), []);
+});
diff --git a/scripts/static-checks.mts b/scripts/static-checks.mts
index f6caff49f7..dd3c3b54bc 100644
--- a/scripts/static-checks.mts
+++ b/scripts/static-checks.mts
@@ -35,7 +35,7 @@
*
* Flags: --staged, --full, --fast, --only <ids>, --skip <ids>, --verbose,
* --list. Check ids: eslint, prettier, imports, eslint-config, json,
- * suppressions, circular-deps, typecheck, config-tests, i18n, depcheck.
+ * suppressions, css-colors, circular-deps, typecheck, config-tests, i18n, depcheck.
*/
import { fileURLToPath } from 'node:url';
@@ -108,6 +108,18 @@ const FILTERS = {
'.github/workflows/static-checks.yml',
'!**.md',
],
+ // Stylesheets are outside the design lint, which reads JSX.
+ css_colors: [
+ 'client/src/*.css',
+ 'packages/client/src/*.css',
+ 'client/src/**/*.css',
+ 'packages/client/src/**/*.css',
+ 'packages/client/src/theme/allowlist.md',
+ 'scripts/css-colors.test.mts',
+ 'scripts/css-colors.mts',
+ 'scripts/static-checks.mts',
+ '.github/workflows/static-checks.yml',
+ ],
config: ['api/**', 'config/**', 'packages/**', '.github/workflows/static-checks.yml', '!**.md'],
i18n: [
'scripts/i18n*.mts',
@@ -1813,6 +1825,26 @@ async function findUnusedI18nKeys(): Promise<CheckOutcome> {
};
}
+// --------------------------------------------------------------- CSS colours
+
+function checkCssColors(): CheckOutcome {
+ const script = resolve(ROOT, 'scripts/css-colors.mts');
+ if (!existsSync(script)) {
+ return { ok: false, output: 'scripts/css-colors.mts is missing' };
+ }
+ const scan = runCommand({ command: process.execPath, args: [script] }, []);
+ const scannerTests = runCommand(
+ { command: process.execPath, args: ['--test', resolve(ROOT, 'scripts/css-colors.test.mts')] },
+ [],
+ );
+ return {
+ ok: scan.status === 0 && scannerTests.status === 0,
+ output: [scan.output, scannerTests.status === 0 ? '' : scannerTests.output]
+ .filter(Boolean)
+ .join('\n'),
+ };
+}
+
// --------------------------------------------------------------- circular dependencies
function findCircularDependencies(): CheckOutcome {
@@ -2132,6 +2164,13 @@ const CHECKS: Check[] = [
group: 'suppressions',
run: validateSuppressions,
},
+ {
+ id: 'css-colors',
+ title: 'CSS colour literals',
+ tier: 'fast',
+ group: 'css_colors',
+ run: checkCssColors,
+ },
{
id: 'circular-deps',
title: 'Circular dependencies',