An open source design system that's fully customizable and agent ready
TypeScript
feat(lint): forbid light-dark() in component source (#5445)
Cindy Zhang63c4c0920201
diff --git a/.changeset/sticky-column-shadow-theme-token.md b/.changeset/sticky-column-shadow-theme-token.mdnew file mode 100644index 0000000000..a9ac06cccd--- /dev/null+++ b/.changeset/sticky-column-shadow-theme-token.md@@ -0,0 +1,11 @@+---+'@astryxdesign/core': patch+---++[fix] Table sticky columns: the pinned-column shadow now reads the theme's `--color-shadow` token instead of a hardcoded `light-dark()` tint, so a theme can retint it.++The tint was `light-dark(rgba(0, 0, 0, 0.12), rgba(0, 0, 0, 0.32))` written in the component, chosen because `--color-shadow` (10%/30% alpha) read as slightly too faint. A literal in a component is the one place a theme cannot reach: every theme got this exact black regardless of its own shadow colour, and the two-point alpha difference bought nothing for it — rendered, the token version differs by at most 5/255 on any channel in light mode and 1/255 in dark, over the ~0.4% of the frame the two shadow strips occupy.++Reading the token instead means the seven bundled themes each tint this shadow with the value they already declare for every other shadow (`chocolate` `#4a35201A`, `stone` `#25252a1a`, and so on), and a custom theme gets the same reach.++@cixzhangdiff --git a/eslint.config.js b/eslint.config.jsindex 2824ddf1be..e985824391 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -271,6 +271,25 @@ export default defineConfig('@astryx/disabled-cursor': 'error',},},+ // `light-dark()` is the theme layer's mechanism, and reaches lab for the+ // same reason the two rules above do: a component that hardcodes a+ // light/dark decision is unreachable by every theme, and lab is where the+ // next core component comes from. Core is covered by the token-enforcement+ // block above (which already excludes `packages/core/src/theme/**`) and is+ // clean, so it errors there. Lab warns for now: LogStream's `levelWarn`/+ // `levelError` are a WCAG contrast fix written per scheme, and moving them+ // to the theme layer means deciding which contrast-tuned status-text token+ // they should read — a token decision, not a mechanical one. Flip to+ // 'error' once that lands.+ {+ files: ["packages/lab/src/**/*.{ts,tsx}"],+ plugins: {+ '@astryx': astryxEslintPlugin,+ },+ rules: {+ '@astryx/no-light-dark-outside-theme': '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.mdindex 091c922f81..02c905d4eb 100644--- a/internal/eslint-plugin-astryx/README.md+++ b/internal/eslint-plugin-astryx/README.md@@ -780,3 +780,69 @@ unwrapped row (the contract test in `Table.test.tsx`) opts out with an`eslint-disable-next-line` and a reason.See: https://github.com/facebook/astryx/issues/5277++### `@astryx/no-light-dark-outside-theme`++Flags the CSS `light-dark()` function written in component source.++`light-dark(a, b)` picks a value from the resolved `color-scheme`. In a+component that hardcodes both halves of the choice at the one place a theme+cannot reach: a theme can retint every token a component consumes, but it+cannot reach inside a literal.++That is why the same defect keeps coming back. A dark-mode contrast failure+patched with a component-level `light-dark()` fixes exactly the scheme the+author was looking at; the element still fails on the light side in every theme+whose palette lands differently, and no theme can do anything about it. A token+pair fixed once in the theme layer reaches both schemes in every theme.++**Bad** — the component decides, and only for the scheme it was written for:++```ts+const SHADOW_TINT = 'light-dark(rgba(0, 0, 0, 0.12), rgba(0, 0, 0, 0.32))';+```++**Good** — the theme decides, and every theme gets to:++```ts+const SHADOW_TINT = colorVars['--color-shadow'];+```++If no token fits, add the `[light, dark]` pair in the theme layer, where+`defineTheme` generates the `light-dark()` for every theme at once.++**Scope:** `packages/core/src/**` (error) and `packages/lab/src/**` (warn).+Core is clean. Lab has one violation — `LogStream`'s `levelWarn`/`levelError`,+a WCAG contrast fix written per scheme — and moving it to the theme layer means+choosing which contrast-tuned status-text token those levels should read; until+that is decided lab warns rather than blocks.++**Exemptions**, kept 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:++| Location | Reported? |+| ------------------------------------------------------------------ | --------- |+| Component source under `packages/core/src`, `packages/lab/src` | ✅ yes |+| A `theme/` or `themes/` directory (`defineTheme`, `tokens.stylex`) | ❌ no |+| `*.test.*`, `*.spec.*`, `*.stories.*`, `*.doc.*`, `__tests__/` | ❌ no |+| A comment (the rule reads literals, never comments) | ❌ no |+| A `.css` file (ESLint never parses one) | ❌ no |+| `'light-dark('` with no closing parenthesis (a parser's prefix) | ❌ no |++That last one is the interesting case: a resolver detecting a token it has to+parse writes the opening text only (`raw.startsWith('light-dark(')` in+`getChartColors`), never a complete call, so requiring a balanced closing+parenthesis separates authoring a value from recognising one. Nesting counts,+so `light-dark(color-mix(…), …)` closes on its own parenthesis. Template+literals are checked across their quasis with interpolations replaced by a+placeholder, so an expression carrying a stray parenthesis cannot skew the+balance. Matching is case-insensitive, like CSS.++**Known limitation (intentional false-negative):** the sibling mechanisms are+not covered — a `@media (prefers-color-scheme: …)` block or a+`:is([data-theme='dark'] *)` selector hardcodes the same decision and this rule+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/5321diff --git a/internal/eslint-plugin-astryx/index.js b/internal/eslint-plugin-astryx/index.jsindex 4f19bb3f21..aeecd0d8aa 100644--- a/internal/eslint-plugin-astryx/index.js+++ b/internal/eslint-plugin-astryx/index.js@@ -18,6 +18,7 @@* - require-table-section: Requires TableRow/tr to sit inside TableHeader/TableBody/TableFooter (a row directly inside a table emits <table><tr>, which browsers repair on parse and React does not)* - 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)** Philosophy: Strict for agents (CI), lenient for humans (local dev)* - "strict" config: All rules as errors - use in CI/agent environments@@ -52,6 +53,7 @@ import requireRefPropRule from './require-ref-prop.js';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';// =============================================================================// Rule: no-hardcoded-styles@@ -350,6 +352,7 @@ const plugin = {'no-hardcoded-i18n-string': noHardcodedI18nStringRule,'i18n-key-format': i18nKeyFormatRule,'require-table-section': requireTableSectionRule,+ 'no-light-dark-outside-theme': noLightDarkOutsideThemeRule,},configs: {},};@@ -420,6 +423,11 @@ plugin.configs.strict = {// A row directly inside a table is invalid DOM and hydration-unsafe, and// the repo is clean — error in both tiers so it stays that way (#5277).'@astryx/require-table-section': 'error',+ // A component-level light-dark() is a light/dark decision no theme can+ // override; the pair belongs in the theme layer. Core is clean after the+ // 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',},};@@ -478,6 +486,11 @@ plugin.configs.recommended = {// A row directly inside a table is invalid DOM and hydration-unsafe, and// the repo is clean — error in both tiers so it stays that way (#5277).'@astryx/require-table-section': 'error',+ // A component-level light-dark() is a light/dark decision no theme can+ // override; the pair belongs in the theme layer. Core is clean after the+ // 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',},};diff --git a/internal/eslint-plugin-astryx/no-light-dark-outside-theme.js b/internal/eslint-plugin-astryx/no-light-dark-outside-theme.jsnew file mode 100644index 0000000000..c15b074239--- /dev/null+++ b/internal/eslint-plugin-astryx/no-light-dark-outside-theme.js@@ -0,0 +1,163 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file no-light-dark-outside-theme.js+ * @description Disallow the CSS `light-dark()` function in component source.+ * A light/dark decision belongs to the theme layer, not to a component.+ *+ * `light-dark(a, b)` picks a value from the resolved `color-scheme`. Written+ * in a component, it hardcodes both halves of that choice at the one place a+ * theme cannot reach: a theme can retint every token a component consumes, but+ * it cannot reach inside the component to change a literal.+ *+ * That is not a style preference — it is why the same defect keeps coming+ * back. A dark-mode contrast failure fixed with a component-level+ * `light-dark()` fixes exactly the scheme the author was looking at. The+ * element still fails on the other side in every theme whose palette lands+ * differently, and no theme can do anything about it. A token pair fixed once+ * in the theme layer reaches both schemes in every theme.+ *+ * Bad — the component decides, and only for the scheme it was written for:+ * const TINT = 'light-dark(rgba(0, 0, 0, 0.12), rgba(0, 0, 0, 0.32))';+ *+ * Good — the theme decides, and every theme gets to:+ * colorVars['--color-shadow']+ *+ * The theme layer is where the pair is written, so it is exempt: `defineTheme`+ * generates `light-dark()` strings from `[light, dark]` tuples, and+ * `tokens.stylex.ts` states the defaults those tuples override. Both are the+ * sanctioned path this rule points authors back to.+ *+ * SCOPE — what this rule can and cannot see. It reads string and template+ * literals, so a comment mentioning `light-dark()` is invisible to it, as is a+ * `.css` file (ESLint never parses one) and a `.doc.mjs` prose file (unlinted+ * outside the CLI). Path exemptions are kept here rather than only in+ * eslint.config.js so they are testable, and so a future config edit cannot+ * quietly turn the theme layer into a violation.+ *+ * A bare `'light-dark('` with no closing parenthesis is a PREFIX, not a value:+ * that is how a resolver detects a token it has to parse (`getChartColors`+ * does exactly this). Only a complete, balanced call is reported.+ *+ * KNOWN LIMITATION: the sibling mechanisms are not covered — a+ * `@media (prefers-color-scheme: …)` block or a `:is([data-theme='dark'] *)`+ * selector hardcodes the same decision and this rule says nothing. `light-dark()`+ * is where the pattern actually shows up in this repo; the others can be added+ * to this rule if they start to.+ */++import path from 'node:path';++/**+ * Directory names that ARE the theme layer. A `light-dark()` written in one of+ * these is the token pair itself, which is the whole point of the mechanism:+ * `packages/core/src/theme/**` (defineTheme, tokens.stylex, the expanders) and+ * the shipped theme packages under `packages/themes/**`.+ */+const THEME_DIRECTORIES = new Set(['theme', 'themes']);++/**+ * File kinds that quote CSS rather than ship it: tests asserting on generated+ * theme output, stories, and doc sources. Matched on the basename.+ */+const NON_SHIPPING_FILE = /\.(test|spec|stories|doc)\./;++const TEST_DIRECTORIES = new Set(['__tests__', '__mocks__']);++/** Is this file part of the theme layer, or otherwise not shipped CSS? */+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;+ }+ return segments.some(+ segment => THEME_DIRECTORIES.has(segment) || TEST_DIRECTORIES.has(segment),+ );+}++/**+ * Does the parenthesis opened at `from - 1` ever close within `text`?+ *+ * Distinguishes a `light-dark()` VALUE from a `'light-dark('` prefix used to+ * detect one. Nested calls count, so `light-dark(color-mix(…), …)` closes on+ * its own final parenthesis rather than color-mix's.+ */+function closes(text, from) {+ let depth = 1;+ for (let i = from; i < text.length; i++) {+ if (text[i] === '(') {+ depth++;+ } else if (text[i] === ')' && --depth === 0) {+ return true;+ }+ }+ return false;+}++/** Does `text` contain a complete `light-dark(…)` call? (CSS is case-insensitive.) */+function hasLightDarkCall(text) {+ const opener = /light-dark\(/gi;+ let match;+ while ((match = opener.exec(text)) !== null) {+ if (closes(text, match.index + match[0].length)) {+ return true;+ }+ }+ return false;+}++const rule = {+ meta: {+ type: 'problem',+ docs: {+ description:+ 'Disallow the CSS light-dark() function in component source — a ' ++ 'light/dark decision belongs to the theme layer, where a token pair ' ++ 'reaches both schemes in every theme, not to a component literal no ' ++ 'theme can override',+ category: 'Best Practices',+ recommended: true,+ },+ messages: {+ lightDarkInComponent:+ '`light-dark()` in a component hardcodes a light/dark decision that ' ++ 'belongs to the theme. A theme can retint any token this component ' ++ 'reads, but it cannot reach inside a literal — so this value fixes ' ++ 'the one scheme it was written for and leaves every other theme ' ++ 'failing on the other side. Read a token instead ' ++ "(`colorVars['--color-…']`), and if none fits, add the `[light, dark]` " ++ 'pair in the theme layer, where `defineTheme` generates the ' ++ '`light-dark()` for every theme at once.',+ },+ schema: [],+ },+ create(context) {+ if (isExemptFile(context.filename)) {+ return {};+ }++ return {+ Literal(node) {+ if (typeof node.value === 'string' && hasLightDarkCall(node.value)) {+ context.report({node, messageId: 'lightDarkInComponent'});+ }+ },+ TemplateLiteral(node) {+ // Interpolations are opaque: replace each with a placeholder so the+ // parenthesis balance is computed from the literal text alone, and an+ // expression carrying a stray parenthesis cannot skew it.+ const text = node.quasis.map(quasi => quasi.value.raw).join('\u0000');+ if (hasLightDarkCall(text)) {+ context.report({node, messageId: 'lightDarkInComponent'});+ }+ },+ };+ },+};++export default rule;diff --git a/internal/eslint-plugin-astryx/no-light-dark-outside-theme.test.mjs b/internal/eslint-plugin-astryx/no-light-dark-outside-theme.test.mjsnew file mode 100644index 0000000000..b6e67ff750--- /dev/null+++ b/internal/eslint-plugin-astryx/no-light-dark-outside-theme.test.mjs@@ -0,0 +1,187 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file no-light-dark-outside-theme.test.mjs+ * @description Tests for the no-light-dark-outside-theme ESLint rule. Most of+ * these are the exemption list: the repo's legitimate `light-dark()` all lives+ * in the theme layer or in files that quote CSS rather than ship it, and a+ * rule that flagged those would be turned off within a day. The invalid cases+ * are the two shapes that actually occur in component source — a module-level+ * tint constant and an interpolated template literal.+ */++import {RuleTester} from 'eslint';+import tseslint from 'typescript-eslint';+import noLightDarkOutsideThemeRule from './no-light-dark-outside-theme.js';++const ruleTester = new RuleTester({+ languageOptions: {+ parser: tseslint.parser,+ parserOptions: {+ ecmaFeatures: {jsx: true},+ },+ },+});++const COMPONENT = 'packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx';++// RuleTester registers its own describe/it blocks internally, so it+// must run at the top level. Vitest 4 forbids calling suite functions+// (describe/it) from inside another it() callback.+ruleTester.run('no-light-dark-outside-theme', noLightDarkOutsideThemeRule, {+ valid: [+ // The path this rule points at: read a token, let the theme own the pair.+ {+ code: "const TINT = colorVars['--color-shadow'];",+ filename: COMPONENT,+ },+ {+ code: "const bg = `linear-gradient(to right, ${colorVars['--color-shadow']}, transparent)`;",+ filename: COMPONENT,+ },++ // THE THEME LAYER — where the pair is written. defineTheme generates these+ // strings from [light, dark] tuples; tokens.stylex states the defaults.+ {+ code: "export const colorDefaults = {'--color-shadow': 'light-dark(rgba(5, 54, 89, 0.1), rgba(0, 0, 0, 0.3))'};",+ filename: 'packages/core/src/theme/tokens.stylex.ts',+ },+ {+ code: "const ld = (light, dark) => `light-dark(${light}, ${dark})`;",+ filename: 'packages/core/src/theme/defineTheme.ts',+ },+ {+ code: "const t = {'--color-data-1': 'light-dark(#0064E0, #2694FE)'};",+ filename: 'packages/core/src/theme/domainTokens/dataTokens.ts',+ },+ // Nested under the theme layer (syntax themes) — still the theme layer.+ {+ code: "const punctuation = 'light-dark(#6e6e6e, #a0a0a0)';",+ filename: 'packages/core/src/theme/syntax/defineSyntaxTheme.ts',+ },+ // A shipped theme package is the theme layer too.+ {+ code: "export const stoneTheme = {'--color-shadow': 'light-dark(#25252a1a, #0000004d)'};",+ filename: 'packages/themes/stone/src/stoneTheme.ts',+ },++ // FILES THAT QUOTE CSS RATHER THAN SHIP IT.+ // A test asserting on what the theme layer generated.+ {+ code: "expect(rules['--color-shadow']).toBe('light-dark(#000, #fff)');",+ filename: 'packages/core/src/theme/generateThemeRules.test.ts',+ },+ // ...including one outside the theme directory.+ {+ code: "expect(style.color).toBe('light-dark(red, blue)');",+ filename: 'packages/core/src/Table/Table.test.tsx',+ },+ {+ code: "const probe = 'light-dark(red, blue)';",+ filename: 'packages/core/src/hooks/__tests__/useAutoMediaMode.test.ts',+ },+ // Prose docs, which show the generated output to the reader.+ {+ code: "export default {body: 'Tokens resolve to light-dark(a, b) pairs.'};",+ filename: 'packages/core/src/theme/MediaTheme.doc.mjs',+ },+ // A story demonstrating the mechanism.+ {+ code: "const demo = 'light-dark(#fff, #000)';",+ filename: 'apps/storybook/stories/MediaTheme.stories.tsx',+ },++ // A PREFIX, NOT A VALUE. A resolver detecting a token it has to parse+ // never writes a complete call — this is getChartColors' actual shape.+ {+ code: "if (raw.startsWith('light-dark(') && raw.endsWith(')')) { return raw.slice(11, -1); }",+ filename: 'packages/lab/src/Chart/getChartColors.ts',+ },+ {+ code: "const OPENER = 'light-dark(';",+ filename: COMPONENT,+ },++ // Comments are not literals, so the rule never sees them — the mechanism+ // is discussed all over core and none of that is a violation.+ {+ code: '// Astryx tokens are light-dark(a, b) pairs that resolve when used.\nconst x = 1;',+ filename: 'packages/core/src/hooks/useAutoMediaMode.ts',+ },+ {+ code: '/** Pages pinning color-scheme resolve light-dark() by OS preference. */\nconst y = 2;',+ filename: 'packages/core/src/Toast/useToast.tsx',+ },++ // Near-misses: the name has to be the CSS function, called.+ {+ code: "const mode = 'light-dark';",+ filename: COMPONENT,+ },+ {+ code: "const label = 'Light / Dark';",+ filename: COMPONENT,+ },+ // Not a functional notation — CSS forbids the space, so this is prose.+ {+ code: "const note = 'light-dark (a, b)';",+ filename: COMPONENT,+ },+ ],++ invalid: [+ // THE REAL ONE (#5321's ruling, found on main): a module-level tint+ // constant deciding both schemes inside a component.+ {+ code: "const SHADOW_TINT = 'light-dark(rgba(0, 0, 0, 0.12), rgba(0, 0, 0, 0.32))';",+ filename: COMPONENT,+ errors: [{messageId: 'lightDarkInComponent'}],+ },+ // Interpolated over tokens: still the component choosing per scheme.+ {+ code: 'const c = `light-dark(${colorVars["--color-error"]}, color-mix(in srgb, ${colorVars["--color-error"]} 82%, white))`;',+ filename: 'packages/lab/src/LogStream/LogStream.tsx',+ errors: [{messageId: 'lightDarkInComponent'}],+ },+ // A nested call must not be mistaken for the closing parenthesis.+ {+ code: "const c = 'light-dark(color-mix(in srgb, #fff 58%, black), #000)';",+ filename: 'packages/lab/src/LogStream/LogStream.tsx',+ errors: [{messageId: 'lightDarkInComponent'}],+ },+ // Inside stylex.create, which is where component CSS actually lives.+ {+ code: "const styles = stylex.create({strip: {backgroundImage: 'linear-gradient(to right, light-dark(#0002, #0005), transparent)'}});",+ filename: COMPONENT,+ errors: [{messageId: 'lightDarkInComponent'}],+ },+ // An inline style prop is the same decision in a different place.+ {+ code: "const el = <div style={{color: 'light-dark(#000, #fff)'}} />;",+ filename: 'packages/core/src/Avatar/Avatar.tsx',+ errors: [{messageId: 'lightDarkInComponent'}],+ },+ // CSS function names are case-insensitive; the rule is too.+ {+ code: "const c = 'LIGHT-DARK(#000, #fff)';",+ filename: COMPONENT,+ errors: [{messageId: 'lightDarkInComponent'}],+ },+ // `theme` exempts a DIRECTORY, not a filename that merely mentions one —+ // a component is a component wherever its name points.+ {+ code: "const c = 'light-dark(#000, #fff)';",+ filename: 'packages/core/src/Callout/ThemeBadge.tsx',+ errors: [{messageId: 'lightDarkInComponent'}],+ },+ // Two independent calls in one file are two reports.+ {+ code: "const a = 'light-dark(#000, #fff)';\nconst b = 'light-dark(#111, #eee)';",+ filename: COMPONENT,+ errors: [+ {messageId: 'lightDarkInComponent'},+ {messageId: 'lightDarkInComponent'},+ ],+ },+ ],+});diff --git a/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsxindex d3caf7fcb0..a4f1cf708a 100644--- a/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx+++ b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx@@ -210,8 +210,7 @@ const stickyStyles = stylex.create({// ::after gradient strip just past the pinned edge (visible thanks to the cell's// overflow: visible). Opacity is gated by the scroll-state variable above.const SHADOW_WIDTH = '6px';-// --color-shadow is only ~10% alpha (too faint here); use a slightly stronger soft tint.-const SHADOW_TINT = 'light-dark(rgba(0, 0, 0, 0.12), rgba(0, 0, 0, 0.32))';+const SHADOW_TINT = colorVars['--color-shadow'];const shadowStyles = stylex.create({// start-pinned: shadow falls toward inline-end (over scrolled content).// insetInlineEnd anchors the strip to the column's inline-end edge; the strip