Skip to content

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

TypeScript

feat(lint): catch raw colours anywhere in component source, not just in `stylex.create()` (#5446)

Cindy Zhang57e7a70180f5
diff --git a/eslint.config.js b/eslint.config.js
index e985824391..6321cf3884 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -290,6 +290,29 @@ export default defineConfig(
'@astryx/no-light-dark-outside-theme': 'warn',
},
},
+ // A colour written into a component is the colour every theme gets — a theme
+ // can retint any token a component reads, but it cannot reach inside a
+ // literal. Core is covered by the token-enforcement block above (which
+ // already excludes packages/core/src/theme/**); this reaches the other
+ // packages that ship component styling, for the same reason the rules above
+ // do. Warn everywhere for now: the 23 violations on main are 20 in lab
+ // (LogStream's console palette, Sankey's var() fallbacks), 2 in core and 1
+ // in charts, and each wants a token decision rather than a mechanical
+ // substitution. Promote to 'error' per package as each reaches zero.
+ {
+ files: [
+ "packages/lab/src/**/*.{ts,tsx}",
+ "packages/charts/src/**/*.{ts,tsx}",
+ "packages/richtext/src/**/*.{ts,tsx}",
+ "packages/vega/src/**/*.{ts,tsx}",
+ ],
+ plugins: {
+ '@astryx': astryxEslintPlugin,
+ },
+ rules: {
+ '@astryx/no-raw-color': 'warn',
+ },
+ },
// The i18n runtime itself defines the message strings the rest of the
// package resolves against; a "hardcoded string" check against it would be
// circular. Turn off @astryx/no-hardcoded-i18n-string just for this dir.
diff --git a/internal/eslint-plugin-astryx/README.md b/internal/eslint-plugin-astryx/README.md
index 02c905d4eb..d2fb52b71c 100644
--- a/internal/eslint-plugin-astryx/README.md
+++ b/internal/eslint-plugin-astryx/README.md
@@ -205,6 +205,10 @@ const styles = stylex.create({
});
```
+Colour is only half-covered here: this rule reads the property name, so it sees
+a literal on `color`/`backgroundColor`/`borderColor` inside `stylex.create()`
+and nothing else. `@astryx/no-raw-color` covers the rest.
+
### `@astryx/no-style-only-wrapper`
Flags a `<div>`/`<span>` that exists only to style a single Astryx component.
@@ -846,3 +850,142 @@ says nothing about either. `light-dark()` is where the pattern actually shows up
in this repo; the others can be added if they start to.
See: https://github.com/facebook/astryx/pull/5321
+
+### `@astryx/no-raw-color`
+
+Flags a raw colour value — hex, `rgb()`, `hsl()`, `hwb()`, `lab()`, `lch()`,
+`oklab()`, `oklch()`, `color()` — anywhere in component source.
+
+A theme can retint every token a component reads. It cannot reach inside a
+literal. So a colour written into a component is the colour every theme gets,
+including a consumer's own, and the only way to change it is to edit the
+component.
+
+**Bad** — this grey is the same grey in all seven themes:
+
+```ts
+const TINT = '#6b7280';
+boxShadow: `0 1px 2px rgba(0, 0, 0, 0.12)`;
+```
+
+**Good** — the theme decides:
+
+```ts
+const TINT = colorVars['--color-text-secondary'];
+boxShadow: shadowVars['--shadow-sm'];
+```
+
+If no token fits, the value belongs in the theme layer, where `defineTheme`
+gives every theme a way to override it.
+
+#### Why this is not `@astryx/no-hardcoded-styles`
+
+That rule is keyed on the **property name** and only reads values sitting
+directly inside `stylex.create()`, against an anchored pattern. It covers
+`color`, `backgroundColor` and `borderColor`, and nothing else. This one walks
+the literal text instead, so the hiding place stops mattering — these are all
+shapes it catches and the older rule does not:
+
+| shape | example |
+| ------------------------------------------------- | ------------------------------------------------------- |
+| an argument to another CSS function | `'light-dark(#fff, #000)'`, `color-mix(…, #1c1c1e 20%)` |
+| behind a `const`, one hop from the style object | `const TINT = '#00000020'` |
+| inside a template literal, `boxShadow` especially | `` `0 1px 2px rgba(0,0,0,.12)` `` |
+| a `var()` fallback | `'var(--color-text-disabled, #999)'` |
+| a JSX attribute | `<circle fill="#fff" />` |
+| any other colour property | `outlineColor`, `fill`, `stroke`, `caretColor` |
+| `hsl()` and the modern notations | `'oklch(0.7 0.1 200)'` |
+
+The two rules are complementary and both stay on: `no-hardcoded-styles` also
+covers spacing, radius and type, which this one says nothing about.
+
+#### What it stays quiet about
+
+The rule is colour-shaped, so it structurally cannot reach the sanctioned
+non-token values — `0`, `none`, `transparent`, `inherit`, `currentColor` — or
+layout values like `width: '100%'` and a dropdown's `maxHeight: '300px'`. Beyond
+that:
+
+| Location or shape | Reported? |
+| ------------------------------------------------------------------------- | --------- |
+| Component source under `packages/{core,lab,charts,richtext,vega}/src` | ✅ yes |
+| A `theme/` or `themes/` directory (`tokens.stylex`, `defineTheme`) | ❌ no |
+| `*.test.*`, `*.spec.*`, `*.stories.*`, `*.doc.*`, `__tests__/` | ❌ no |
+| A comment (the rule reads literals, never comments) | ❌ no |
+| A colour assembled from values passed in — `rgba(${r}, ${g}, ${b}, ${a})` | ❌ no |
+| Every channel from a token — `rgb(var(--r) var(--g) var(--b))` | ❌ no |
+| `'rgb('` with no closing parenthesis (a parser's prefix) | ❌ no |
+| `mask`/`maskImage` and friends — the colour resolves through alpha | ❌ no |
+
+Two of those are worth the detail. A **colour function only counts when its
+arguments carry a literal digit** — that separates authoring a colour from
+building one out of channels handed in, which is how `utils/color.ts` serializes
+and `getChartColors` parses. One literal channel is enough, so
+`hsl(var(--accent-hue), 80%, 50%)` is still a colour this file chose. And a
+**mask** is the one place a colour is not paint: `mask-image` resolves a
+gradient through its alpha channel, so `rgba(0, 0, 0, 0.3)` in one of its stops
+is a 30% opacity stop and the black is discarded — `backgroundImage`, which
+paints the same gradient, is not exempt.
+
+Path exemptions live in the rule source rather than only in `eslint.config.js`,
+so they are testable and a config edit cannot quietly turn the theme layer into
+a violation. That layer has ~200 colour literals and defining them is its job.
+
+#### On `eslint-disable`
+
+**A disable suppresses this rule, deliberately.** The only mechanism that would
+close the door is `noInlineConfig`, and it **cannot be scoped to one rule** —
+verified: under `linterOptions: {noInlineConfig: true}`, a file disabling both
+`@astryx/no-raw-color` and `no-unused-vars` reports both again. It _is_ scopable
+by `files` glob, so the choice on offer is never "harden this rule" but "void
+every inline disable in this directory", which takes the sanctioned ones with it
+— the deliberately unwrapped row `require-table-section` documents, and the
+`no-nullish-jsx-guard` migration sites.
+
+So the escape hatch stays open and stays _visible_. A disable on this rule means
+someone knowingly wrote a raw colour: it is greppable
+(`git grep no-raw-color -- packages`), it is permanent in the diff, and it is a
+review signal rather than a resolution. A rule with no escape hatch gets evaded
+by moving the literal somewhere the rule cannot see, which is worse — that is
+invisible. The reviewer still owes the finding.
+
+The hatch also covers the rule's one known over-reach: a hex-shaped fragment in a
+string that is not a colour (`'#abc'` as a fragment identifier). There are none
+in the repo today.
+
+**Known limitations (intentional false-negatives).** Each was probed rather than
+assumed, and none has an instance in the repo except the last:
+
+- **Named CSS colours** (`red`, `rebeccapurple`). A bare word is
+ indistinguishable from any other string and the false-positive cost is far
+ higher than the rate at which they appear here.
+- **A colour assembled at runtime from parts** (`'#' + hex`), which would mean
+ evaluating expressions rather than reading literals.
+- **A percent-encoded colour inside a data URI** —
+ `url("data:image/svg+xml,%3Csvg fill=%22%23ff0000%22/%3E")`. Decoding URIs to
+ look for colours is a different rule.
+- **A `.css` file**, which ESLint never parses. There is one live instance:
+ `packages/core/src/reset.css:291` reads
+ `var(--color-text-secondary, #9ca3af)` — the same defensive-fallback shape as
+ the `Sankey` hits, and it rides with them.
+
+Everything else the rule reaches, and a probe confirms it: a `const`, an object
+property, an array element, an enum member, a computed key, a template
+`boxShadow` in modern space-separated syntax, and an inline `style={{}}` — which
+sits at the very top of the cascade, where a theme has no answer at all.
+
+**Scope:** `warn` in `packages/{core,lab,charts,richtext,vega}/src`. There are 23
+violations on `main` — 20 in lab (`LogStream`'s console palette, `Sankey`'s
+`var()` fallbacks), 2 in core, 1 in charts.
+
+**Not in scope, deliberately:** `packages/cli/assets/templates/**`, which the
+CLI scaffolds into a consumer's app. The rule finds **194** there (102 in
+`blocks`, 92 in `pages`) if pointed at it. A raw colour in a template a consumer
+copies is a real finding — the rubric calls a literal _presented as the
+recommended way to style a component_ a docs-quality problem — but many of those
+194 are showcase content demonstrating a colour on purpose, so turning it on
+there is a triage decision of its own rather than a consequence of this rule
+existing. Each wants a token decision rather
+than a mechanical substitution, so they are tracked separately; promote a
+package to `error` once it reaches zero, the same path
+`no-physical-properties` took.
diff --git a/internal/eslint-plugin-astryx/index.js b/internal/eslint-plugin-astryx/index.js
index aeecd0d8aa..8a1049ed8a 100644
--- a/internal/eslint-plugin-astryx/index.js
+++ b/internal/eslint-plugin-astryx/index.js
@@ -19,6 +19,7 @@
* - disabled-cursor: Flags a cursor that promises an interaction without giving way to not-allowed on a disabled element
* - no-unstable-merged-refs: Flags render-time mergeRefs callbacks and unstable callback inputs to useMergedRefs
* - no-light-dark-outside-theme: Flags CSS light-dark() in component source (a light/dark decision belongs to the theme layer, where a token pair reaches both schemes in every theme)
+ * - no-raw-color: Flags a raw colour value (hex, rgb(), hsl(), oklch(), …) anywhere in component source, including inside light-dark()/color-mix(), behind a const, in a template literal, or as a var() fallback — the shapes no-hardcoded-styles cannot see
*
* Philosophy: Strict for agents (CI), lenient for humans (local dev)
* - "strict" config: All rules as errors - use in CI/agent environments
@@ -54,6 +55,7 @@ import noHardcodedI18nStringRule from './no-hardcoded-i18n-string.js';
import i18nKeyFormatRule from './i18n-key-format.js';
import requireTableSectionRule from './require-table-section.js';
import noLightDarkOutsideThemeRule from './no-light-dark-outside-theme.js';
+import noRawColorRule from './no-raw-color.js';
// =============================================================================
// Rule: no-hardcoded-styles
@@ -353,6 +355,7 @@ const plugin = {
'i18n-key-format': i18nKeyFormatRule,
'require-table-section': requireTableSectionRule,
'no-light-dark-outside-theme': noLightDarkOutsideThemeRule,
+ 'no-raw-color': noRawColorRule,
},
configs: {},
};
@@ -428,6 +431,14 @@ plugin.configs.strict = {
// sticky-column fix in this commit, so it errors in both tiers. (Lab
// warns — see the lab block in eslint.config.js.)
'@astryx/no-light-dark-outside-theme': 'error',
+ // A colour a theme cannot reach is the colour every theme gets. This is
+ // the whole of T1 where `no-hardcoded-styles` only reaches literals sitting
+ // directly on `color`/`backgroundColor`/`borderColor` inside
+ // `stylex.create()`. Warn in both tiers while the 23 existing violations
+ // are cleaned up (2 in core, 1 in charts, 20 in lab — see the plugin
+ // README); promote to 'error' per package as each one reaches zero, the
+ // same path no-physical-properties took.
+ '@astryx/no-raw-color': 'warn',
},
};
@@ -491,6 +502,14 @@ plugin.configs.recommended = {
// sticky-column fix in this commit, so it errors in both tiers. (Lab
// warns — see the lab block in eslint.config.js.)
'@astryx/no-light-dark-outside-theme': 'error',
+ // A colour a theme cannot reach is the colour every theme gets. This is
+ // the whole of T1 where `no-hardcoded-styles` only reaches literals sitting
+ // directly on `color`/`backgroundColor`/`borderColor` inside
+ // `stylex.create()`. Warn in both tiers while the 23 existing violations
+ // are cleaned up (2 in core, 1 in charts, 20 in lab — see the plugin
+ // README); promote to 'error' per package as each one reaches zero, the
+ // same path no-physical-properties took.
+ '@astryx/no-raw-color': 'warn',
},
};
diff --git a/internal/eslint-plugin-astryx/no-raw-color.js b/internal/eslint-plugin-astryx/no-raw-color.js
new file mode 100644
index 0000000000..8425246f8b
--- /dev/null
+++ b/internal/eslint-plugin-astryx/no-raw-color.js
@@ -0,0 +1,282 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file no-raw-color.js
+ * @description Disallow raw colour values — hex, `rgb()`, `hsl()` and the
+ * other CSS colour notations — anywhere in component source.
+ *
+ * A theme can retint every token a component reads. It cannot reach inside a
+ * literal. So a colour written into a component is the one colour every theme
+ * gets, and the only way to change it is to edit the component — which a
+ * consumer cannot do. That is the whole reason the token layer exists.
+ *
+ * Bad — this grey is the same grey in all seven themes and in a custom one:
+ * const TINT = '#6b7280';
+ * boxShadow: `0 1px 2px rgba(0, 0, 0, 0.12)`
+ *
+ * Good — the theme decides:
+ * colorVars['--color-text-secondary']
+ * shadowVars['--shadow-sm']
+ *
+ * WHY A SEPARATE RULE FROM `no-hardcoded-styles`. That rule is keyed on the
+ * property name and only reads values directly inside `stylex.create()`, with
+ * an anchored pattern. It covers `color`/`backgroundColor`/`borderColor` and
+ * nothing else, which leaves out every shape a colour actually hides in: an
+ * argument to `light-dark()` or `color-mix()`, a `const` one hop above the
+ * style object, a `boxShadow` template string, a `var()` fallback, a JSX
+ * attribute, `fill`/`stroke`/`outlineColor`/`caretColor`. This rule walks the
+ * literal text instead of the property, so the hiding place stops mattering.
+ *
+ * SCOPE — what this rule can and cannot see. Like its `no-light-dark-outside-theme`
+ * sibling it reads string and template literals, so a comment is invisible to
+ * it (which is what keeps the ~90 `#1234` issue references in this repo's
+ * comments out of the results), as is a `.css` file, which ESLint never parses.
+ * Path exemptions live here rather than only in `eslint.config.js` so they are
+ * testable, and so a config edit cannot quietly turn the theme layer into a
+ * violation.
+ *
+ * A functional notation is only a colour when it is a complete call carrying a
+ * literal number of its own. `rgba(${r}, ${g}, ${b}, ${a})` builds a colour
+ * from values it was handed and holds none — that is a colour utility, not a
+ * styling decision, and `utils/color.ts` and `getChartColors` are both written
+ * that way. One literal channel is enough to count, so
+ * `hsl(var(--h), 80%, 50%)` is still a colour this file chose. A bare `'rgb('`
+ * with no closing parenthesis is a parser's prefix for the same reason.
+ *
+ * A mask is the one place a colour is not paint: `mask-image` resolves a
+ * gradient through its ALPHA channel, so `rgba(0, 0, 0, 0.3)` there is a 30%
+ * opacity stop and the black is discarded. No theme author expects to retint
+ * it, so mask properties are exempt — `backgroundImage`, which paints the same
+ * gradient, is not.
+ *
+ * KNOWN LIMITATIONS, both deliberate:
+ * - Named CSS colours (`red`, `rebeccapurple`) are not flagged. A bare word
+ * is indistinguishable from any other string, and the false-positive cost
+ * is far higher than the ~zero rate at which they appear here.
+ * - A colour assembled at runtime from parts (`'#' + hex`) is not flagged.
+ * Nothing in this repo does it, and catching it means evaluating
+ * expressions rather than reading literals.
+ */
+
+import path from 'node:path';
+
+/**
+ * The theme layer, matched by POSITION rather than by directory name. A
+ * `theme/` anywhere would exempt any file a component happened to put in one,
+ * in a rule whose whole claim is that a colour cannot hide — so this anchors to
+ * the two places the layer actually is: a package's own `src/theme/**`
+ * (`tokens.stylex.ts`, `defineTheme`, the expanders) and the shipped theme
+ * packages under `packages/themes/**`. A `themes/` directory inside a CLI
+ * template is a third, and is matched for the same reason: its job is to
+ * demonstrate theme values.
+ */
+const THEME_LAYER = [
+ /(^|\/)packages\/themes\//,
+ /(^|\/)src\/theme\//,
+ /(^|\/)templates\/[^/]*\/?themes?\//,
+];
+
+/**
+ * File kinds that demonstrate or assert on colour rather than shipping it. A
+ * theming story MUST use literals — a theme author writes literals, and that is
+ * precisely what the story is showing.
+ */
+const NON_SHIPPING_FILE = /\.(test|spec|stories|doc|sandbox)\./;
+
+const TEST_DIRECTORIES = new Set(['__tests__', '__mocks__']);
+
+function isExemptFile(filename) {
+ if (!filename || filename === '<input>' || filename === '<text>') {
+ return false;
+ }
+ const normalized = filename.split(path.sep).join('/');
+ const segments = normalized.split('/');
+ const basename = segments.pop() ?? '';
+ if (NON_SHIPPING_FILE.test(basename)) {
+ return true;
+ }
+ if (segments.some(segment => TEST_DIRECTORIES.has(segment))) {
+ return true;
+ }
+ return THEME_LAYER.some(pattern => pattern.test(normalized));
+}
+
+/**
+ * `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa` — bounded on both sides so `#ff` and
+ * `#1234567` are not colours, and neither is the tail of a longer word.
+ */
+const HEX = /(?<![\w#])#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})(?![\w#])/;
+
+/**
+ * Every CSS colour notation that takes arguments. `color()` and the lab/lch
+ * family are here for the same reason as `rgb()`: they are a raw colour with a
+ * different spelling, and leaving them out makes the rule a lint against one
+ * syntax rather than against the defect.
+ */
+const COLOR_FUNCTION = /(?<![\w-])(rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\(/gi;
+
+/**
+ * The index just past the parenthesis opened at `from - 1`, or -1 if it never
+ * closes. Nesting counts, so `rgb(calc(1 + 2), 0, 0)` closes on its own.
+ */
+function endOfCall(text, from) {
+ let depth = 1;
+ for (let i = from; i < text.length; i++) {
+ if (text[i] === '(') {
+ depth++;
+ } else if (text[i] === ')' && --depth === 0) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+/**
+ * Does `text` hold a raw colour?
+ *
+ * A colour function counts only when its arguments carry a literal digit. An
+ * argument list made of interpolations or `var()` reads is a colour being
+ * assembled from values chosen elsewhere — `rgba(${r}, ${g}, ${b}, ${a})` in a
+ * colour utility, `rgb(var(--r) var(--g) var(--b))` from tokens. One literal
+ * channel is a channel this file chose, and that is enough.
+ */
+function hasRawColor(text) {
+ if (HEX.test(text)) {
+ return true;
+ }
+ COLOR_FUNCTION.lastIndex = 0;
+ let match;
+ while ((match = COLOR_FUNCTION.exec(text)) !== null) {
+ const argsStart = match.index + match[0].length;
+ const argsEnd = endOfCall(text, argsStart);
+ if (argsEnd !== -1 && /\d/.test(text.slice(argsStart, argsEnd))) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Style properties whose colour channel is discarded. `mask-image` resolves a
+ * gradient through alpha, so the RGB in one of its stops never paints.
+ */
+const ALPHA_ONLY_PROPERTIES = new Set([
+ 'mask',
+ 'maskImage',
+ 'maskBorderSource',
+ 'WebkitMask',
+ 'WebkitMaskImage',
+ 'WebkitMaskBoxImage',
+]);
+
+/**
+ * Is the object holding this property the argument to `stylex.create()`?
+ *
+ * Its keys are style-RULE names — `nav`, `fadeStart` — not CSS properties, so a
+ * rule someone names `mask` must not exempt the declarations inside it.
+ */
+function isStyleRuleName(property) {
+ const object = property.parent;
+ const call = object?.parent;
+ return (
+ object?.type === 'ObjectExpression' &&
+ call?.type === 'CallExpression' &&
+ call.arguments.includes(object) &&
+ call.callee?.type === 'MemberExpression' &&
+ call.callee.object?.name === 'stylex' &&
+ call.callee.property?.name === 'create'
+ );
+}
+
+/**
+ * Is this literal a value of a property whose colour channel is discarded?
+ *
+ * The walk climbs to the nearest CSS property rather than the nearest property,
+ * because a value can sit several nodes below the one that names it: a ternary
+ * picking one of two gradients, a `??` default, and — the shape this repo
+ * writes — StyleX's conditional object, where the gradient is the value of
+ * `default` inside the value of `maskImage` (`TabList.tsx:261`,
+ * `Carousel.tsx:187`). Everything under a `maskImage` key is a mask value, so
+ * finding that key anywhere up the chain is the answer.
+ *
+ * Two things a match must not be: a style-RULE named `mask`, whose contents are
+ * ordinary declarations, and a computed key, whose identifier is a variable
+ * name rather than the property it resolves to. Only the node types a value can
+ * nest inside are traversed, so the walk stops at the first thing that is not
+ * one and can never leave the style object.
+ */
+function isAlphaOnlyValue(node) {
+ let current = node;
+ for (let parent = current.parent; parent; parent = current.parent) {
+ if (parent.type === 'Property' && parent.value === current) {
+ const key = parent.computed ? undefined : parent.key?.name ?? parent.key?.value;
+ if (ALPHA_ONLY_PROPERTIES.has(key) && !isStyleRuleName(parent)) {
+ return true;
+ }
+ current = parent;
+ continue;
+ }
+ const nests =
+ parent.type === 'ObjectExpression' ||
+ (parent.type === 'ArrayExpression' && parent.elements.includes(current)) ||
+ (parent.type === 'ConditionalExpression' &&
+ (parent.consequent === current || parent.alternate === current)) ||
+ (parent.type === 'LogicalExpression' && parent.right === current);
+ if (!nests) {
+ return false;
+ }
+ current = parent;
+ }
+ return false;
+}
+
+const PLACEHOLDER = '\u0000';
+
+const rule = {
+ meta: {
+ type: 'problem',
+ docs: {
+ description:
+ 'Disallow raw colour values (hex, rgb(), hsl() and the other CSS ' +
+ 'colour notations) in component source — a colour a theme cannot ' +
+ 'reach is the same colour in every theme',
+ category: 'Best Practices',
+ recommended: true,
+ },
+ messages: {
+ rawColor:
+ 'Raw colour in component source. A theme can retint any token this ' +
+ 'component reads, but it cannot reach inside a literal — so this is ' +
+ 'the colour every theme gets, including a consumer\'s own. Read a ' +
+ "token instead (`colorVars['--color-…']`, `shadowVars['--shadow-…']`), " +
+ 'or derive one with `color-mix()` on token vars. If no token fits, the ' +
+ 'value belongs in the theme layer, not here.',
+ },
+ schema: [],
+ },
+ create(context) {
+ if (isExemptFile(context.filename)) {
+ return {};
+ }
+
+ return {
+ Literal(node) {
+ if (
+ typeof node.value === 'string' &&
+ hasRawColor(node.value) &&
+ !isAlphaOnlyValue(node)
+ ) {
+ context.report({node, messageId: 'rawColor'});
+ }
+ },
+ TemplateLiteral(node) {
+ const text = node.quasis.map(quasi => quasi.value.raw).join(PLACEHOLDER);
+ if (hasRawColor(text) && !isAlphaOnlyValue(node)) {
+ context.report({node, messageId: 'rawColor'});
+ }
+ },
+ };
+ },
+};
+
+export default rule;
diff --git a/internal/eslint-plugin-astryx/no-raw-color.test.mjs b/internal/eslint-plugin-astryx/no-raw-color.test.mjs
new file mode 100644
index 0000000000..7b75d818a4
--- /dev/null
+++ b/internal/eslint-plugin-astryx/no-raw-color.test.mjs
@@ -0,0 +1,338 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file no-raw-color.test.mjs
+ *
+ * One invalid case per shape a raw colour has actually taken in this repo, and
+ * one valid case per thing the rule must stay quiet about. Every invalid case
+ * below was watched failing against the rule before the rule handled it.
+ */
+
+import {RuleTester, Linter} from 'eslint';
+import {expect, test} from 'vitest';
+import rule from './no-raw-color.js';
+
+const ruleTester = new RuleTester({
+ languageOptions: {
+ ecmaVersion: 2022,
+ sourceType: 'module',
+ parserOptions: {ecmaFeatures: {jsx: true}},
+ },
+});
+
+const IN_COMPONENT = 'packages/core/src/Widget/Widget.tsx';
+const one = [{messageId: 'rawColor'}];
+
+ruleTester.run('no-raw-color', rule, {
+ valid: [
+ // T2b — the sanctioned non-token values.
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {
+ borderWidth: 0,
+ borderStyle: 'none',
+ backgroundColor: 'transparent',
+ color: 'inherit',
+ fill: 'currentColor',
+ }});`,
+ },
+ // T2b — layout values are not theme values, and a colour rule structurally
+ // cannot reach them.
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {
+ width: '100%',
+ flex: 1,
+ maxHeight: '300px',
+ maxWidth: '360px',
+ minWidth: '120px',
+ }});`,
+ },
+ // Reading a token is the whole point.
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {color: colorVars['--color-text-primary']}});`,
+ },
+ // Derived from tokens: color-mix on vars, and the percentage is a mix
+ // ratio, not a channel.
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {
+ backgroundColor: 'color-mix(in oklab, var(--color-accent), var(--color-surface) 50%)',
+ }});`,
+ },
+ // A colour assembled from channels it was handed is a utility, not a
+ // decision — this is how packages/core/src/utils/color.ts serializes.
+ {
+ filename: IN_COMPONENT,
+ code: 'const out = `rgba(${r}, ${g}, ${b}, ${a})`;',
+ },
+ // A prefix with no closing parenthesis is how a parser detects a notation.
+ {
+ filename: IN_COMPONENT,
+ code: `const isRgb = raw.startsWith('rgb(');`,
+ },
+ // Every channel from a token.
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {color: 'rgb(var(--r) var(--g) var(--b))'}});`,
+ },
+ // A mask resolves its gradient through alpha, so the black never paints.
+ {
+ filename: IN_COMPONENT,
+ code: 'const s = stylex.create({a: {maskImage: `linear-gradient(to right, transparent, rgba(0,0,0,0.3) 2px, black)`}});',
+ },
+ // Still the mask's value when it is picked by a ternary or defaulted with
+ // `??` — the exemption follows the value, not its syntactic position.
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {
+ maskImage: isStart
+ ? 'linear-gradient(to right, transparent, rgba(0,0,0,0.3))'
+ : 'linear-gradient(to left, transparent, rgba(0,0,0,0.3))',
+ WebkitMaskImage: custom ?? 'linear-gradient(to right, rgba(0,0,0,0.3), black)',
+ }});`,
+ },
+ // StyleX's conditional object, which is how TabList.tsx:261 writes its
+ // fade — the gradient is the value of `default` inside the value of
+ // `maskImage`, two levels below the key that names it.
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {
+ maskImage: {
+ default: 'linear-gradient(to right, transparent, rgba(0,0,0,0.3))',
+ ':is([dir="rtl"] *)': 'linear-gradient(to left, transparent, rgba(0,0,0,0.3))',
+ },
+ }});`,
+ },
+ // The other mask spellings, each pinned so dropping one fails something.
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {
+ mask: 'linear-gradient(rgba(0,0,0,0.3), black)',
+ WebkitMask: 'linear-gradient(rgba(0,0,0,0.3), black)',
+ maskBorderSource: 'linear-gradient(rgba(0,0,0,0.3), black)',
+ WebkitMaskBoxImage: 'linear-gradient(rgba(0,0,0,0.3), black)',
+ }});`,
+ },
+ // A sandbox page demonstrates a theme, exactly as a story does — named in
+ // the rubric's own exceptions note.
+ {
+ filename: 'packages/core/src/Widget/Widget.sandbox.tsx',
+ code: `const demo = defineTheme({tokens: {'--color-accent': '#7c3aed'}});`,
+ },
+ // The theme layer is where a colour value is written.
+ {
+ filename: 'packages/core/src/theme/tokens.stylex.ts',
+ code: `export const colorVars = stylex.defineVars({'--color-accent': '#0064e0'});`,
+ },
+ {
+ filename: 'packages/themes/chocolate/src/index.ts',
+ code: `export default defineTheme({tokens: {'--color-shadow': '#4a35201A'}});`,
+ },
+ // A CLI template's theme is a theme author's own input, which is the thing
+ // the template exists to demonstrate.
+ {
+ filename: 'packages/cli/assets/templates/app/themes/brand.ts',
+ code: `export default defineTheme({tokens: {'--color-accent': '#7c3aed'}});`,
+ },
+ // A theming story MUST use literals — a theme author writes literals, and
+ // that is precisely what the story demonstrates.
+ {
+ filename: 'packages/core/src/Widget/Widget.stories.tsx',
+ code: `const custom = defineTheme({tokens: {'--color-accent': '#7c3aed'}});`,
+ },
+ {
+ filename: 'packages/core/src/Widget/Widget.test.tsx',
+ code: `expect(style.color).toBe('#ff0000');`,
+ },
+ {
+ filename: 'packages/core/src/Widget/Widget.doc.mjs',
+ code: `export const theming = {example: 'color: #7c3aed'};`,
+ },
+ {
+ filename: 'packages/core/src/__tests__/helpers.ts',
+ code: `export const RED = '#ff0000';`,
+ },
+ // Not colour-shaped: too few digits, too many, and a word that merely
+ // starts with hex characters.
+ {
+ filename: IN_COMPONENT,
+ code: `const a = '#ff'; const b = '#1234567'; const c = '#facade1';`,
+ },
+ ],
+
+ invalid: [
+ // The plain case the old rule already caught, kept so this rule is a
+ // superset of it.
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {color: '#ff0000'}});`,
+ errors: one,
+ },
+ // Short hex.
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {backgroundColor: '#fff'}});`,
+ errors: one,
+ },
+ // rgb()/rgba().
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {borderColor: 'rgba(0, 0, 0, 0.5)'}});`,
+ errors: one,
+ },
+ // hsl()/hsla() — never covered by the property-keyed rule at all.
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {color: 'hsl(210, 80%, 50%)'}});`,
+ errors: one,
+ },
+ // Inside light-dark(). The motivating shape: an anchored top-level
+ // pattern sees a string starting with `light-dark(` and passes it.
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {color: 'light-dark(#fff, #000)'}});`,
+ errors: one,
+ },
+ // Inside color-mix(), where only one side is a token.
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {
+ backgroundColor: 'color-mix(in oklab, var(--color-accent), #1c1c1e 20%)',
+ }});`,
+ errors: one,
+ },
+ // Behind a const — the literal is one hop from the style object.
+ {
+ filename: IN_COMPONENT,
+ code: `const SHADOW_TINT = '#00000020';
+ const s = stylex.create({a: {boxShadow: SHADOW_TINT}});`,
+ errors: one,
+ },
+ // In a template literal, and boxShadow specifically — the property the
+ // rubric records as not lint-covered.
+ {
+ filename: IN_COMPONENT,
+ code: 'const s = stylex.create({a: {boxShadow: `0 1px 2px ${spacingVars["--spacing-1"]} rgba(0, 0, 0, 0.12)`}});',
+ errors: one,
+ },
+ // One literal channel is enough, even when the rest is interpolated.
+ {
+ filename: IN_COMPONENT,
+ code: 'const bar = `hsl(calc(var(--accent-hue, 210) + ${shift}), 80%, 50%)`;',
+ errors: one,
+ },
+ // A var() fallback is a colour that paints when the token is missing.
+ {
+ filename: IN_COMPONENT,
+ code: `el.style.color = 'var(--color-text-disabled, #999)';`,
+ errors: one,
+ },
+ // A JSX attribute is styling too.
+ {
+ filename: IN_COMPONENT,
+ code: `const el = <circle fill="var(--color-background-surface, #fff)" />;`,
+ errors: one,
+ },
+ // A modern notation is the same defect with a different spelling.
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {color: 'oklch(0.7 0.1 200)'}});`,
+ errors: one,
+ },
+ // Colour reaches far past the three properties the property-keyed rule
+ // knows about.
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {
+ outlineColor: '#0064e0',
+ fill: '#ff6166',
+ caretColor: 'rgb(28, 28, 30)',
+ }});`,
+ errors: [{messageId: 'rawColor'}, {messageId: 'rawColor'}, {messageId: 'rawColor'}],
+ },
+ // A style RULE named `mask` is not the CSS property — `stylex.create()`'s
+ // top-level keys are rule names, and the declarations inside one are
+ // ordinary paint.
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({mask: {backgroundColor: 'rgba(0, 0, 0, 0.5)'}});`,
+ errors: one,
+ },
+ // A computed key's identifier is a variable name, not the property it
+ // resolves to.
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {[maskImage]: '#f00'}});`,
+ errors: one,
+ },
+ // The theme exemption is matched by POSITION, not by directory name: a
+ // `theme/` a component happens to nest inside itself is component source.
+ // This is the boundary, and it is pinned from both sides — the two valid
+ // cases above are the real theme layer.
+ {
+ filename: 'packages/core/src/Chat/theme/bubbleColors.ts',
+ code: `export const BUBBLE_TINT = '#1c1c1e';`,
+ errors: one,
+ },
+ {
+ filename: 'packages/core/src/Widget/themes/local.ts',
+ code: `export const LOCAL = '#1c1c1e';`,
+ errors: one,
+ },
+ // backgroundImage paints the same gradient a mask discards — including
+ // through the same conditional object and the same ternary, so the walk
+ // cannot be exempting on shape rather than on the property it lands on.
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {
+ backgroundImage: 'linear-gradient(to right, transparent, rgba(0, 0, 0, 0.3))',
+ }});`,
+ errors: one,
+ },
+ {
+ filename: IN_COMPONENT,
+ code: `const s = stylex.create({a: {
+ backgroundImage: {
+ default: 'linear-gradient(to right, transparent, rgba(0, 0, 0, 0.3))',
+ ':hover': isOn ? 'linear-gradient(#fff, #000)' : 'none',
+ },
+ }});`,
+ errors: [{messageId: 'rawColor'}, {messageId: 'rawColor'}],
+ },
+ ],
+});
+
+/**
+ * The escape hatch is deliberately left open, so this asserts the decision
+ * rather than an accident. T1 says a disable is not an exception to the RULE —
+ * a reviewer still owes the finding — but suppression stays available, because
+ * the only way to close it is `--no-inline-config`, which is process-wide and
+ * would also void the sanctioned disables other rules in this plugin rely on.
+ * A disable here is a signal a reviewer can grep for, not a loophole.
+ */
+test('an eslint-disable suppresses it, and that is on purpose', () => {
+ const linter = new Linter();
+ const config = {
+ files: ['**/*.tsx'],
+ plugins: {'@astryx': {rules: {'no-raw-color': rule}}},
+ rules: {'@astryx/no-raw-color': 'error'},
+ };
+ const options = {filename: IN_COMPONENT};
+
+ const reported = linter.verify(
+ `const s = stylex.create({a: {color: '#ff0000'}});`,
+ config,
+ options,
+ );
+ expect(reported.map(m => m.messageId)).toEqual(['rawColor']);
+
+ const suppressed = linter.verify(
+ `// eslint-disable-next-line @astryx/no-raw-color
+const s = stylex.create({a: {color: '#ff0000'}});`,
+ config,
+ options,
+ );
+ expect(suppressed).toEqual([]);
+});