Skip to content

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

TypeScript

fix(theme): emit the --color-data-* defaults so the tokens reach CSS (#5562)

Cindy Zhang6447c5eceb71
diff --git a/.changeset/data-tokens-reach-css.md b/.changeset/data-tokens-reach-css.md
new file mode 100644
index 0000000000..d5436d83d6
--- /dev/null
+++ b/.changeset/data-tokens-reach-css.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] The 56 `--color-data-*` tokens now reach CSS. They were declared in `domainTokens/dataTokens.ts` and resolvable from JS through `useTheme().token()` and `resolveThemeTokens()`, but nothing emitted them as custom properties, so `var(--color-data-categorical-blue)` resolved to nothing and only a token a theme happened to override by name ever landed. The defaults are now emitted once as a `:root` block in `@layer astryx-base` — the same place and layer StyleX puts the core token defaults — so the palette resolves, a theme's `--color-data-*` override outranks it by layer, and a nested `<Theme>` that names no data token inherits its parent's override instead of shadowing it with the default.
+
+**Visual change.** Anything reading `var(--color-data-*)` without a fallback painted nothing before and now paints the palette value; anything reading it with a hex fallback now takes the token value instead of the fallback. Pin a colour explicitly if you were relying on either.
+
+@cixzhang
diff --git a/.changeset/template-data-token-fallbacks.md b/.changeset/template-data-token-fallbacks.md
new file mode 100644
index 0000000000..4a5d6285f8
--- /dev/null
+++ b/.changeset/template-data-token-fallbacks.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] Eight `var(--color-data-*, <hex>)` fallbacks in the dashboard templates named a colour their own token does not have, so the same chart series painted one colour with a theme and another without one. All eight now match the token default: `#22c55e` → `#0B991F` (categorical-green, portfolio), `#E5484D` → `#F5394F` (categorical-red, portfolio), `#008E80` → `#08A3A3` (categorical-teal, service-monitoring, cohort-funnel and data).
+
+**Visual change.** Those series shift to the token colour in a generated template. Copy the old hex in if you were relying on it.
+
+@cixzhang
diff --git a/.changeset/theme-build-color-scheme-gate.md b/.changeset/theme-build-color-scheme-gate.md
new file mode 100644
index 0000000000..b63173d464
--- /dev/null
+++ b/.changeset/theme-build-color-scheme-gate.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] `astryx theme build` decides its `color-scheme` block from the theme's own token and component values rather than a substring scan of the generated CSS, and emits the `--color-data-*` defaults in `@layer astryx-base` so a built theme matches what the `<Theme>` runtime injects. Every built theme now carries those defaults, which are `light-dark()` pairs, so the old scan would have fired for every theme. The `color-scheme` output is unchanged.
+
+@cixzhang
diff --git a/.github/scripts/theme-layer-cascade.js b/.github/scripts/theme-layer-cascade.js
index 4a94a77d35..981f42b6d0 100644
--- a/.github/scripts/theme-layer-cascade.js
+++ b/.github/scripts/theme-layer-cascade.js
@@ -47,6 +47,13 @@ const CORE_SRC = path.join(REPO_ROOT, 'packages/core/src');
const THEME_COLOR = 'rgb(0, 120, 255)';
const PRODUCT_COLOR = 'rgb(255, 140, 0)';
+/** The fixture theme's `--color-data-categorical-blue`, light and dark side. */
+const DATA_OVERRIDE_LIGHT = 'rgb(1, 2, 3)';
+const DATA_OVERRIDE_DARK = 'rgb(4, 5, 6)';
+/** Untouched defaults: --color-data-categorical-orange, --color-data-neutral. */
+const DATA_DEFAULT = 'rgb(235, 110, 0)';
+const DATA_DEFAULT_DARK_SIDE = 'rgb(140, 147, 155)';
+
const CONTENT_TYPES = {
'.html': 'text/html',
'.js': 'application/javascript',
@@ -132,14 +139,25 @@ async function run() {
timeout: 60000,
});
await page.waitForSelector('#library-only', {timeout: 20000});
+ await page.waitForSelector('#data-dark-default', {timeout: 20000});
- const seen = await page.evaluate(() => ({
- themed: getComputedStyle(document.getElementById('library-only'))
- .backgroundColor,
- product: getComputedStyle(document.getElementById('product-wins'))
- .backgroundColor,
- padding: getComputedStyle(document.getElementById('product-box')).padding,
- }));
+ const seen = await page.evaluate(() => {
+ const color = id => getComputedStyle(document.getElementById(id)).color;
+ return {
+ themed: getComputedStyle(document.getElementById('library-only'))
+ .backgroundColor,
+ product: getComputedStyle(document.getElementById('product-wins'))
+ .backgroundColor,
+ padding: getComputedStyle(document.getElementById('product-box'))
+ .padding,
+ dataDefault: color('data-default'),
+ dataOverride: color('data-override'),
+ dataNested: color('data-nested'),
+ dataNestedDefault: color('data-nested-default'),
+ dataDark: color('data-dark'),
+ dataDarkDefault: color('data-dark-default'),
+ };
+ });
const check = (label, actual, expected, why) => {
if (actual === expected) {
@@ -170,6 +188,44 @@ async function run() {
'11px',
'the product layer is not reaching the page',
);
+ check(
+ 'a data token default reaches an element',
+ seen.dataDefault,
+ DATA_DEFAULT,
+ 'nothing declares --color-data-*, so var() resolves to nothing',
+ );
+ check(
+ "a theme's data token override beats the default",
+ seen.dataOverride,
+ DATA_OVERRIDE_LIGHT,
+ 'the :root defaults are outranking @layer astryx-theme — they are ' +
+ 'unlayered, or in a layer that sorts above it',
+ );
+ check(
+ "a nested theme inherits the parent's data token override",
+ seen.dataNested,
+ DATA_OVERRIDE_LIGHT,
+ 'the nested theme re-declares the default in its own scope block and ' +
+ 'shadows the parent override — no other token family does that',
+ );
+ check(
+ 'a nested theme still gets the untouched defaults',
+ seen.dataNestedDefault,
+ DATA_DEFAULT,
+ 'the defaults do not reach inside a nested theme',
+ );
+ check(
+ "a nested dark theme inherits the parent's override, dark side",
+ seen.dataDark,
+ DATA_OVERRIDE_DARK,
+ 'light-dark() is not resolving against the nested theme color-scheme',
+ );
+ check(
+ 'a data token default resolves on the dark side',
+ seen.dataDarkDefault,
+ DATA_DEFAULT_DARK_SIDE,
+ 'the :root defaults resolve to their light side inside a dark theme',
+ );
} finally {
if (browser) await browser.close();
if (server) server.close();
@@ -183,7 +239,10 @@ async function run() {
);
return 1;
}
- console.log('\nAstryx < theme < product holds in a production build.');
+ console.log(
+ '\nAstryx < theme < product holds in a production build, and the ' +
+ 'data token defaults sit under a theme override.',
+ );
return 0;
}
diff --git a/packages/build/__fixtures__/layer-split/App.tsx b/packages/build/__fixtures__/layer-split/App.tsx
index 1cf5eba474..9d6191552d 100644
--- a/packages/build/__fixtures__/layer-split/App.tsx
+++ b/packages/build/__fixtures__/layer-split/App.tsx
@@ -8,10 +8,17 @@
* `themedButton` deliberately sets the same property the fixture theme
* overrides on the same element, so the built stylesheet answers which layer
* wins rather than only which rules were emitted.
+ *
+ * The `data-*` swatches read `--color-data-*` custom properties, whose defaults
+ * are declared once at `:root`. Each one is a different cascade question: does
+ * the default reach an element, does a theme's override beat it, and does a
+ * nested theme inherit that override instead of shadowing it.
*/
import * as stylex from '@stylexjs/stylex';
import {Button} from '@astryxdesign/core/Button';
+import {Theme} from '@astryxdesign/core/theme';
+import {nestedTheme, nestedDarkTheme} from './theme';
const styles = stylex.create({
productBox: {
@@ -33,6 +40,40 @@ export function App() {
variant="destructive"
xstyle={styles.themedButton}
/>
+ <span
+ id="data-default"
+ style={{color: 'var(--color-data-categorical-orange)'}}>
+ default
+ </span>
+ <span
+ id="data-override"
+ style={{color: 'var(--color-data-categorical-blue)'}}>
+ overridden
+ </span>
+ <Theme theme={nestedTheme}>
+ <span
+ id="data-nested"
+ style={{color: 'var(--color-data-categorical-blue)'}}>
+ nested, inherited
+ </span>
+ <span
+ id="data-nested-default"
+ style={{color: 'var(--color-data-categorical-orange)'}}>
+ nested, default
+ </span>
+ </Theme>
+ <Theme theme={nestedDarkTheme} mode="dark">
+ <span
+ id="data-dark"
+ style={{color: 'var(--color-data-categorical-blue)'}}>
+ dark, inherited
+ </span>
+ <span
+ id="data-dark-default"
+ style={{color: 'var(--color-data-neutral)'}}>
+ dark, default
+ </span>
+ </Theme>
</div>
);
}
diff --git a/packages/build/__fixtures__/layer-split/theme.ts b/packages/build/__fixtures__/layer-split/theme.ts
index 6c007e34f6..227b2a5f03 100644
--- a/packages/build/__fixtures__/layer-split/theme.ts
+++ b/packages/build/__fixtures__/layer-split/theme.ts
@@ -6,12 +6,32 @@ import {defineTheme} from '@astryxdesign/core/theme';
* Overrides the same declaration Button's own StyleX rule sets, so the built
* stylesheet answers "does @layer astryx-theme outrank the library layer?"
* rather than only "did the rule get emitted?".
+ *
+ * It also overrides one `--color-data-*` token, whose defaults are declared
+ * once at `:root`: an override that loses to that block, or a nested theme
+ * that re-declares the default over it, are both cascade facts and neither is
+ * visible in the generated CSS text.
*/
export const fixtureTheme = defineTheme({
name: 'layersplitfixture',
+ tokens: {
+ '--color-data-categorical-blue': ['rgb(1, 2, 3)', 'rgb(4, 5, 6)'],
+ },
components: {
button: {
'variant:destructive': {backgroundColor: 'rgb(0, 120, 255)'},
},
},
});
+
+/** A nested theme that names no data token — it must inherit the parent's. */
+export const nestedTheme = defineTheme({
+ name: 'layersplitnested',
+ tokens: {'--color-accent': '#123456'},
+});
+
+/** Nested and dark, so `light-dark()` has to resolve on the dark side. */
+export const nestedDarkTheme = defineTheme({
+ name: 'layersplitnesteddark',
+ tokens: {'--color-accent': '#654321'},
+});
diff --git a/packages/cli/api/template/data-token-fallbacks.test.mjs b/packages/cli/api/template/data-token-fallbacks.test.mjs
new file mode 100644
index 0000000000..94a02d8761
--- /dev/null
+++ b/packages/cli/api/template/data-token-fallbacks.test.mjs
@@ -0,0 +1,85 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Asserts every `var(--color-data-*, <hex>)` fallback in the dashboard
+ * templates equals the token's own default.
+ *
+ * The fallback is what paints when the token does not resolve, so a fallback
+ * that differs from its token makes the same chart series two different colours
+ * depending on whether a theme is present. Three of them had drifted
+ * (`#22c55e`, `#E5484D`, `#008E80`), which is also why "the defaults are
+ * byte-identical to the template fallbacks" was not true.
+ */
+
+import {describe, it, expect} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {dataTokenDefaults} from '@astryxdesign/core/theme';
+
+const TEMPLATES_DIR = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '../../assets/templates',
+);
+const CALL_SITE = /var\(\s*(--color-data-[a-z0-9-]+)\s*,\s*([^)]+?)\s*\)/g;
+
+/** The light side of a `light-dark(a, b)` pair — what a template falls back to. */
+function lightSide(value) {
+ const match = /^light-dark\(\s*([^,]+?)\s*,/.exec(value);
+ return match ? match[1] : value;
+}
+
+function walk(dir) {
+ return fs.readdirSync(dir, {withFileTypes: true}).flatMap(entry => {
+ const full = path.join(dir, entry.name);
+ return entry.isDirectory() ? walk(full) : [full];
+ });
+}
+
+function callSites() {
+ const sites = [];
+ for (const file of walk(TEMPLATES_DIR)) {
+ if (!/\.(tsx|ts|jsx|js|mjs|css)$/.test(file)) {
+ continue;
+ }
+ fs.readFileSync(file, 'utf-8')
+ .split('\n')
+ .forEach((line, index) => {
+ for (const match of line.matchAll(CALL_SITE)) {
+ sites.push({
+ where: `${path.relative(TEMPLATES_DIR, file)}:${index + 1}`,
+ token: match[1],
+ fallback: match[2],
+ });
+ }
+ });
+ }
+ return sites;
+}
+
+describe('template --color-data-* fallbacks', () => {
+ const sites = callSites();
+
+ it('finds the call sites at all', () => {
+ expect(sites.length).toBeGreaterThan(40);
+ });
+
+ it('names a real token at every call site', () => {
+ const unknown = sites.filter(site => !dataTokenDefaults[site.token]);
+ expect(unknown.map(site => `${site.where} ${site.token}`)).toEqual([]);
+ });
+
+ it('matches each token default exactly', () => {
+ const drifted = sites
+ .filter(site => dataTokenDefaults[site.token])
+ .filter(
+ site => site.fallback !== lightSide(dataTokenDefaults[site.token]),
+ )
+ .map(
+ site =>
+ `${site.where} ${site.token}: ${site.fallback} != ${lightSide(dataTokenDefaults[site.token])}`,
+ );
+
+ expect(drifted).toEqual([]);
+ });
+});
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index f701280765..be7edacb65 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -62,12 +62,14 @@ import {
/** @type {any} */ let _defineTheme = null;
/** @type {any} */ let _generateThemeRulesSplit = null;
/** @type {any} */ let _generateOnMediaCSS = null;
+/** @type {any} */ let _generateThemeCSS = null;
/** @type {any} */ let _coreImportError = null;
try {
const coreTheme = await import('@astryxdesign/core/theme');
_defineTheme = coreTheme.defineTheme;
_generateThemeRulesSplit = coreTheme.generateThemeRulesSplit;
_generateOnMediaCSS = coreTheme.generateOnMediaCSS;
+ _generateThemeCSS = coreTheme.generateThemeCSS;
} catch (e) {
// Capture the reason so the theme action can surface a precise, actionable
// error. We don't throw here: this module is imported eagerly by the CLI
@@ -1166,8 +1168,15 @@ export async function themeBuild(
if (component.length > 0) {
const componentInner = component.join('\n\n');
const componentScope = `@scope (${scopeSelector}) to (${scopeTo}) {\n${componentInner}\n}`;
- // #3658: also emit attribute-specific rules so <Theme mode> can override color-scheme
- const colorSchemeDecl = componentScope.includes('light-dark(')
+ // #3658: also emit attribute-specific rules so <Theme mode> can override color-scheme.
+ // Decided from the theme's own values, not the generated CSS: that CSS
+ // also carries the data-token defaults, which are light-dark() pairs, so
+ // a substring check on it would fire for every theme.
+ const themeOwnValues = JSON.stringify([
+ resolvedTheme.tokens ?? {},
+ resolvedTheme.components ?? {},
+ ]);
+ const colorSchemeDecl = themeOwnValues.includes('light-dark(')
? ' :root { color-scheme: light dark; }\n html[data-theme="light"] { color-scheme: light; }\n html[data-theme="dark"] { color-scheme: dark; }\n\n'
: '';
cssParts.push(
@@ -1185,6 +1194,23 @@ export async function themeBuild(
logger.log('No overrides found — nothing to build.');
return null;
}
+ // The data-token defaults are theme-independent and go in @layer
+ // astryx-base, below the theme's own overrides. Taken from the runtime's
+ // own generator so the two paths cannot emit different bytes.
+ // Placed after the reset block and before the theme block: a layer's order
+ // is fixed by where it is first declared, so emitting it anywhere else in
+ // the file would invert reset < astryx-base < astryx-theme for a consumer
+ // who imports this stylesheet on its own.
+ const baseCss = _generateThemeCSS
+ ? _generateThemeCSS(resolvedTheme).base
+ : '';
+ if (baseCss) {
+ cssParts.splice(
+ prose.length > 0 ? 1 : 0,
+ 0,
+ `@layer astryx-base {\n${baseCss}\n}`,
+ );
+ }
css = cssParts.join('\n\n') + '\n';
}
diff --git a/packages/cli/assets/templates/pages/dashboard-cohort-funnel/page.tsx b/packages/cli/assets/templates/pages/dashboard-cohort-funnel/page.tsx
index a6401bf105..a99f4a9918 100644
--- a/packages/cli/assets/templates/pages/dashboard-cohort-funnel/page.tsx
+++ b/packages/cli/assets/templates/pages/dashboard-cohort-funnel/page.tsx
@@ -79,7 +79,7 @@ const COLORS = {
green: 'var(--color-data-categorical-green, #0B991F)',
orange: 'var(--color-data-categorical-orange, #EB6E00)',
purple: 'var(--color-data-categorical-purple, #6B1EFD)',
- teal: 'var(--color-data-categorical-teal, #008E80)',
+ teal: 'var(--color-data-categorical-teal, #08A3A3)',
};
const GRID_STROKE = 'var(--color-border, rgba(5, 54, 89, 0.1))';
const AXIS_TICK = {
diff --git a/packages/cli/assets/templates/pages/dashboard-data/page.tsx b/packages/cli/assets/templates/pages/dashboard-data/page.tsx
index 1687fd1c5a..91ecde4a64 100644
--- a/packages/cli/assets/templates/pages/dashboard-data/page.tsx
+++ b/packages/cli/assets/templates/pages/dashboard-data/page.tsx
@@ -98,7 +98,7 @@ const COLORS = {
green: 'var(--color-data-categorical-green, #0B991F)',
orange: 'var(--color-data-categorical-orange, #EB6E00)',
purple: 'var(--color-data-categorical-purple, #6B1EFD)',
- teal: 'var(--color-data-categorical-teal, #008E80)',
+ teal: 'var(--color-data-categorical-teal, #08A3A3)',
neutral: 'var(--color-data-neutral, #8494A3)',
};
const GRID_STROKE = 'var(--color-border, rgba(5, 54, 89, 0.1))';
diff --git a/packages/cli/assets/templates/pages/dashboard-portfolio/page.tsx b/packages/cli/assets/templates/pages/dashboard-portfolio/page.tsx
index 60e2ae90fe..363a15895c 100644
--- a/packages/cli/assets/templates/pages/dashboard-portfolio/page.tsx
+++ b/packages/cli/assets/templates/pages/dashboard-portfolio/page.tsx
@@ -370,12 +370,12 @@ function PortfolioChart() {
<linearGradient id="portfolioGradient" x1="0" y1="0" x2="0" y2="1">
<stop
offset="5%"
- stopColor="var(--color-data-categorical-green, #22c55e)"
+ stopColor="var(--color-data-categorical-green, #0B991F)"
stopOpacity={0.3}
/>
<stop
offset="95%"
- stopColor="var(--color-data-categorical-green, #22c55e)"
+ stopColor="var(--color-data-categorical-green, #0B991F)"
stopOpacity={0.05}
/>
</linearGradient>
@@ -417,7 +417,7 @@ function PortfolioChart() {
<Area
type="linear"
dataKey="value"
- stroke="var(--color-data-categorical-green, #22c55e)"
+ stroke="var(--color-data-categorical-green, #0B991F)"
strokeWidth={1.5}
fill="url(#portfolioGradient)"
dot={false}
@@ -434,7 +434,7 @@ function Sparkline({data, positive}: {data: number[]; positive: boolean}) {
const chartData = data.map((v, i) => ({i, v}));
const color = positive
? 'var(--color-data-categorical-green, #0B991F)'
- : 'var(--color-data-categorical-red, #E5484D)';
+ : 'var(--color-data-categorical-red, #F5394F)';
return (
<ResponsiveContainer width="100%" height={40}>
<LineChart
@@ -503,7 +503,7 @@ function TrendSparkline({data, positive}: {data: number[]; positive: boolean}) {
const chartData = data.map((v, i) => ({i, v}));
const color = positive
? 'var(--color-data-categorical-green, #0B991F)'
- : 'var(--color-data-categorical-red, #E5484D)';
+ : 'var(--color-data-categorical-red, #F5394F)';
return (
<ResponsiveContainer width="100%" height={24}>
<LineChart
diff --git a/packages/cli/assets/templates/pages/dashboard-service-monitoring/page.tsx b/packages/cli/assets/templates/pages/dashboard-service-monitoring/page.tsx
index 98108dda0e..d8de5cbf81 100644
--- a/packages/cli/assets/templates/pages/dashboard-service-monitoring/page.tsx
+++ b/packages/cli/assets/templates/pages/dashboard-service-monitoring/page.tsx
@@ -727,7 +727,7 @@ interface ChartLine {
const BLUE = 'var(--color-data-categorical-blue, #0171E3)';
const ORANGE = 'var(--color-data-categorical-orange, #EB6E00)';
const PURPLE = 'var(--color-data-categorical-purple, #6B1EFD)';
-const TEAL = 'var(--color-data-categorical-teal, #008E80)';
+const TEAL = 'var(--color-data-categorical-teal, #08A3A3)';
const LATENCY_LINES: ChartLine[] = [
{key: 'p50', name: 'p50', color: BLUE},
diff --git a/packages/cli/clients/cli/commands/build-theme.color-scheme.test.mjs b/packages/cli/clients/cli/commands/build-theme.color-scheme.test.mjs
index 4692abf6b4..a105af0d33 100644
--- a/packages/cli/clients/cli/commands/build-theme.color-scheme.test.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.color-scheme.test.mjs
@@ -17,7 +17,9 @@
* html[data-theme="dark"] { color-scheme: dark; }
*
* Themes that never use `light-dark()` have no `color-scheme` ambiguity to
- * resolve, so none of the three rules should be emitted for them.
+ * resolve, so none of the three rules should be emitted for them — the
+ * generated CSS still carries the `--color-data-*` defaults, which are
+ * `light-dark()` pairs, so the decision reads the theme's own values.
*
* Building `astryx theme build` requires a compiled @astryxdesign/core (there is no in-CLI
* fallback generator), so this suite builds core once in beforeAll via the
@@ -67,10 +69,9 @@ describe('theme build color-scheme output', () => {
const project = path.join(tmpDir, 'project');
const themesDir = path.join(project, 'themes');
// A raw light-dark() token value is what triggers the color-scheme
- // injection in build-theme.mjs (it checks the generated CSS for the
- // literal substring). `defineTheme.test.ts` already covers the separate
- // [light, dark] tuple -> light-dark() conversion; this fixture writes
- // the string directly so this test stays focused on the CLI's own
+ // injection in build-theme.mjs. `defineTheme.test.ts` already covers the
+ // separate [light, dark] tuple -> light-dark() conversion; this fixture
+ // writes the string directly so this test stays focused on the CLI's own
// color-scheme decision, not on that conversion.
const themeFile = writeTheme(themesDir, 'with-light-dark', {
'--color-accent': 'light-dark(#0077B6, #48CAE4)',
@@ -123,7 +124,7 @@ describe('theme build color-scheme output', () => {
expect(fs.existsSync(cssPath)).toBe(true);
const css = fs.readFileSync(cssPath, 'utf-8');
- expect(css).not.toContain('light-dark(');
+ expect(css).toContain('--color-accent: #0077B6');
expect(css).not.toContain(COLOR_SCHEME_ROOT_DECL);
expect(css).not.toContain(COLOR_SCHEME_LIGHT_DECL);
expect(css).not.toContain(COLOR_SCHEME_DARK_DECL);
diff --git a/packages/cli/clients/cli/commands/build-theme.data-tokens.test.mjs b/packages/cli/clients/cli/commands/build-theme.data-tokens.test.mjs
new file mode 100644
index 0000000000..f1b848ed55
--- /dev/null
+++ b/packages/cli/clients/cli/commands/build-theme.data-tokens.test.mjs
@@ -0,0 +1,115 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Asserts `astryx theme build` emits the `--color-data-*` defaults the
+ * way the `<Theme>` runtime does — once, at `:root`, in `@layer astryx-base`.
+ *
+ * Seeding them into the theme's own `@scope` block instead makes every nested
+ * `<Theme>` re-declare the default and shadow a parent theme's override, which
+ * no other token family does. Layer order is fixed by first declaration, so
+ * the base block also has to sit after `@layer reset` and before
+ * `@layer astryx-theme` for a consumer who imports this stylesheet alone.
+ *
+ * Building requires a compiled @astryxdesign/core, so this suite builds core
+ * once in beforeAll via the shared ensureCoreBuilt() helper.
+ */
+
+import {describe, it, expect, beforeAll, beforeEach, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {ensureCoreBuilt} from './ensure-core-built.mjs';
+import {runCli} from '../../../test-utils/run-cli.mjs';
+
+function writeTheme(dir, name, theme) {
+ fs.mkdirSync(dir, {recursive: true});
+ const file = path.join(dir, `${name}.mjs`);
+ fs.writeFileSync(
+ file,
+ `export default ${JSON.stringify({name, ...theme})};\n`,
+ );
+ return file;
+}
+
+async function buildTheme(tmpDir, name, theme) {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+ const themeFile = writeTheme(themesDir, name, theme);
+
+ const result = await runCli(
+ ['theme', 'build', path.relative(project, themeFile)],
+ project,
+ );
+ expect(result.code).toBe(0);
+
+ return fs.readFileSync(path.join(themesDir, `${name}.css`), 'utf-8');
+}
+
+beforeAll(() => {
+ ensureCoreBuilt();
+}, 200_000);
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-build-theme-data-'));
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('theme build data token output', () => {
+ it('emits the defaults once, at :root, in @layer astryx-base', async () => {
+ const css = await buildTheme(tmpDir, 'charts-untouched', {
+ tokens: {'--color-accent': '#0077B6'},
+ });
+
+ const baseStart = css.indexOf('@layer astryx-base');
+ expect(baseStart).toBeGreaterThanOrEqual(0);
+
+ const baseBlock = css.slice(baseStart, css.indexOf('@layer astryx-theme'));
+ expect(baseBlock).toContain(':root {');
+ expect(baseBlock).toContain('--color-data-categorical-blue:');
+ expect(baseBlock).toContain('--color-data-gray-1:');
+ expect(css.match(/--color-data-categorical-blue:/g)).toHaveLength(1);
+ expect(css.match(/@layer astryx-base/g)).toHaveLength(1);
+ });
+
+ it('declares astryx-base after reset and before astryx-theme', async () => {
+ const css = await buildTheme(tmpDir, 'charts-order', {
+ tokens: {'--color-accent': '#0077B6'},
+ });
+
+ const reset = css.indexOf('@layer reset');
+ const base = css.indexOf('@layer astryx-base');
+ const theme = css.indexOf('@layer astryx-theme');
+
+ expect(reset).toBeGreaterThanOrEqual(0);
+ expect(base).toBeGreaterThan(reset);
+ expect(theme).toBeGreaterThan(base);
+ });
+
+ it("puts only the theme's own data token in its scope block", async () => {
+ const css = await buildTheme(tmpDir, 'charts-override', {
+ tokens: {'--color-data-categorical-blue': '#00A3FF'},
+ });
+
+ const themeBlock = css.slice(css.indexOf('@layer astryx-theme'));
+ expect(themeBlock).toContain('--color-data-categorical-blue: #00A3FF;');
+ expect(themeBlock).not.toContain('--color-data-categorical-orange');
+ expect(themeBlock).not.toContain('--color-data-gray-1');
+ });
+
+ it('emits the bytes the runtime generator emits', async () => {
+ const tokens = {'--color-accent': '#0077B6'};
+ const css = await buildTheme(tmpDir, 'charts-parity', {tokens});
+
+ const {defineTheme, generateThemeCSS} = await import(
+ '@astryxdesign/core/theme'
+ );
+ const {base} = generateThemeCSS(
+ defineTheme({name: 'charts-parity', tokens}),
+ );
+
+ expect(css).toContain(`@layer astryx-base {\n${base}\n}`);
+ });
+});
diff --git a/packages/core/src/theme/Theme.test.tsx b/packages/core/src/theme/Theme.test.tsx
index a96e50634f..9edad9d38f 100644
--- a/packages/core/src/theme/Theme.test.tsx
+++ b/packages/core/src/theme/Theme.test.tsx
@@ -1,10 +1,22 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, it, expect, beforeEach, afterEach} from 'vitest';
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
import {render, cleanup} from '@testing-library/react';
import React from 'react';
import {Theme} from './Theme';
import {defineTheme} from './defineTheme';
+import {dataTokenDefaults} from './domainTokens';
+import type * as DefineThemeModule from './defineTheme';
+
+const {generateThemeCSSSpy} = vi.hoisted(() => ({
+ generateThemeCSSSpy: vi.fn(),
+}));
+
+vi.mock('./defineTheme', async importOriginal => {
+ const actual = await importOriginal<typeof DefineThemeModule>();
+ generateThemeCSSSpy.mockImplementation(actual.generateThemeCSS);
+ return {...actual, generateThemeCSS: generateThemeCSSSpy};
+});
const testTheme = defineTheme({
name: 'test',
@@ -25,6 +37,7 @@ describe('Theme', () => {
// Clean up documentElement state before each test
document.documentElement.removeAttribute('data-theme');
document.documentElement.removeAttribute('data-astryx-theme');
+ generateThemeCSSSpy.mockClear();
});
afterEach(() => {
@@ -120,7 +133,9 @@ describe('Theme', () => {
'test',
);
unmount();
- expect(document.documentElement.hasAttribute('data-astryx-theme')).toBe(false);
+ expect(document.documentElement.hasAttribute('data-astryx-theme')).toBe(
+ false,
+ );
});
// =========================================================================
@@ -166,4 +181,91 @@ describe('Theme', () => {
expect(nestedWrapper).toBeTruthy();
expect(nestedWrapper?.getAttribute('data-theme')).toBe('light');
});
+
+ // =========================================================================
+ // Data token defaults — one shared :root block, not one per theme scope
+ // =========================================================================
+
+ const baseTags = () =>
+ Array.from(document.head.querySelectorAll('style[data-astryx-theme-base]'));
+
+ it('injects the data token defaults into @layer astryx-base', () => {
+ render(
+ <Theme theme={testTheme}>
+ <span>child</span>
+ </Theme>,
+ );
+
+ expect(baseTags()).toHaveLength(1);
+ const css = baseTags()[0].textContent ?? '';
+ expect(css).toContain('@layer astryx-base {');
+ expect(css).toContain(':root {');
+ expect(css).toContain(
+ `--color-data-categorical-blue: ${dataTokenDefaults['--color-data-categorical-blue']};`,
+ );
+ });
+
+ it('injects one shared block for nested themes, not one per scope', () => {
+ render(
+ <Theme theme={testTheme}>
+ <Theme theme={altTheme}>
+ <span>nested</span>
+ </Theme>
+ </Theme>,
+ );
+
+ expect(baseTags()).toHaveLength(1);
+
+ // The nested theme declares no --color-data-* of its own, so nothing
+ // shadows a value the parent theme set: that is what lets the override
+ // inherit through the ordinary cascade.
+ const themeTags = Array.from(
+ document.head.querySelectorAll('style[data-astryx-theme]'),
+ );
+ for (const tag of themeTags) {
+ expect(tag.textContent).not.toContain('--color-data-');
+ }
+ });
+
+ it('keeps the defaults while any theme is still mounted', () => {
+ const outer = render(
+ <Theme theme={testTheme}>
+ <span>a</span>
+ </Theme>,
+ );
+ render(
+ <Theme theme={altTheme}>
+ <span>b</span>
+ </Theme>,
+ );
+
+ outer.unmount();
+ expect(baseTags()).toHaveLength(1);
+
+ cleanup();
+ expect(baseTags()).toHaveLength(0);
+ });
+
+ it('generates a theme once across nested and sibling mounts', () => {
+ render(
+ <Theme theme={testTheme}>
+ <Theme theme={testTheme}>
+ <span>nested</span>
+ </Theme>
+ </Theme>,
+ );
+ render(
+ <Theme theme={testTheme}>
+ <span>sibling</span>
+ </Theme>,
+ );
+
+ expect(generateThemeCSSSpy).toHaveBeenCalledTimes(1);
+ expect(baseTags()).toHaveLength(1);
+
+ const injected = Array.from(document.querySelectorAll('style'))
+ .map(tag => tag.textContent ?? '')
+ .join('\n');
+ expect(injected.match(/:root\s*\{/g)).toHaveLength(1);
+ });
});
diff --git a/packages/core/src/theme/Theme.tsx b/packages/core/src/theme/Theme.tsx
index 547762ef8e..3faecf5334 100644
--- a/packages/core/src/theme/Theme.tsx
+++ b/packages/core/src/theme/Theme.tsx
@@ -98,6 +98,16 @@ ThemeNestingContext.displayName = 'ThemeNestingContext';
/** Track which themes have already been injected */
const injectedThemes = new Set<string>();
+/**
+ * How many mounted `Theme`s are relying on the injected data-token defaults.
+ *
+ * The defaults are one document-wide `:root` block, shared by every theme, so
+ * they are injected once and removed only when the last theme that took a
+ * reference unmounts — tearing them down with whichever provider happened to
+ * inject them would strip the palette from the providers still mounted.
+ */
+let dataTokenDefaultsRefCount = 0;
+
/**
* Hook to inject theme CSS into the document.
* Built themes (from `astryx theme build`) skip injection — their CSS
@@ -112,6 +122,8 @@ function useThemeStyleInjection(theme: DefinedTheme): void {
return;
}
+ // Second and later `Theme`s using this theme do no work at all —
+ // generation included. Its CSS is document-wide and identical for each.
const themeKey = `astryx-theme-${theme.name}`;
if (injectedThemes.has(themeKey)) {
return;
@@ -129,9 +141,26 @@ function useThemeStyleInjection(theme: DefinedTheme): void {
`the built artifacts.`,
);
- const {prose, component} = generateThemeCSS(theme);
- if (!prose && !component) {
- return;
+ const {prose, component, base} = generateThemeCSS(theme);
+ injectedThemes.add(themeKey);
+ const cleanups: (() => void)[] = [() => injectedThemes.delete(themeKey)];
+
+ // Data token defaults go into @layer astryx-base, where StyleX puts the
+ // core token defaults, so a theme's own `--color-data-*` outranks them by
+ // layer. Appended (never prepended) so it cannot register `astryx-base`
+ // ahead of `reset` and invert the layer order.
+ if (base) {
+ if (dataTokenDefaultsRefCount++ === 0) {
+ const baseStyle = document.createElement('style');
+ baseStyle.setAttribute(dataAttr('theme-base'), '');
+ baseStyle.textContent = `@layer astryx-base {\n${base}\n}`;
+ document.head.appendChild(baseStyle);
+ }
+ cleanups.push(() => {
+ if (--dataTokenDefaultsRefCount === 0) {
+ document.querySelector(`style[${dataAttr('theme-base')}]`)?.remove();
+ }
+ });
}
// Prose defaults go into @layer reset — lowest priority, scoped to
@@ -154,20 +183,24 @@ function useThemeStyleInjection(theme: DefinedTheme): void {
document.head.appendChild(compStyle);
}
- injectedThemes.add(themeKey);
+ if (prose || component) {
+ cleanups.push(() => {
+ // Matched by the astryx id marker, which is always written above.
+ const proseEl = document.querySelector(
+ `style[${dataAttr('theme-prose')}="${theme.name}"][${dataAttr('id')}="${id}"]`,
+ );
+ const compEl = document.querySelector(
+ `style[${dataAttr('theme')}="${theme.name}"][${dataAttr('id')}="${id}"]`,
+ );
+ proseEl?.remove();
+ compEl?.remove();
+ });
+ }
return () => {
- // Remove both prose and component style tags (matched by the new
- // astryx id marker, which is always written above).
- const proseEl = document.querySelector(
- `style[${dataAttr('theme-prose')}="${theme.name}"][${dataAttr('id')}="${id}"]`,
- );
- const compEl = document.querySelector(
- `style[${dataAttr('theme')}="${theme.name}"][${dataAttr('id')}="${id}"]`,
- );
- proseEl?.remove();
- compEl?.remove();
- injectedThemes.delete(themeKey);
+ for (const cleanup of cleanups) {
+ cleanup();
+ }
};
}, [theme, id]);
}
diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.ts
index 4e36af26c9..0c4fd668dd 100644
--- a/packages/core/src/theme/defineTheme.test.ts
+++ b/packages/core/src/theme/defineTheme.test.ts
@@ -116,6 +116,31 @@ describe('generateThemeCSS', () => {
expect(css).toContain('font-family: var(--font-family-heading)');
});
+ it('declares the data palette for a theme that never mentions it', () => {
+ const {base, component} = generateThemeCSS(
+ defineTheme({name: 'chartless'}),
+ );
+ expect(base).toContain('--color-data-categorical-blue:');
+ expect(base).toContain('--color-data-gray-1:');
+ expect(component).not.toContain('--color-data-');
+ });
+
+ it('keeps the rest of the data palette when one data token is overridden', () => {
+ const theme = defineTheme({
+ name: 'brand-charts',
+ tokens: {'--color-data-categorical-blue': '#00A3FF'},
+ });
+ const {base, component} = generateThemeCSS(theme);
+ expect(component).toContain('--color-data-categorical-blue: #00A3FF;');
+ // The siblings the theme did not name stay in the shared base block, so a
+ // nested theme inherits the parent's override instead of the default.
+ expect(component).not.toContain('--color-data-categorical-orange');
+ expect(base).toContain('--color-data-categorical-orange:');
+ // Defaults reach the stylesheet without entering the theme's own tokens,
+ // which are what `astryx theme build` reports as overrides.
+ expect(theme.tokens['--color-data-categorical-orange']).toBeUndefined();
+ });
+
it('splits prose into reset layer and components into astryx-theme', () => {
const theme = defineTheme({
name: 'split-test',
diff --git a/packages/core/src/theme/generateThemeRules.test.ts b/packages/core/src/theme/generateThemeRules.test.ts
index 335252c55f..766e2e8288 100644
--- a/packages/core/src/theme/generateThemeRules.test.ts
+++ b/packages/core/src/theme/generateThemeRules.test.ts
@@ -7,7 +7,13 @@
*/
import {describe, it, expect} from 'vitest';
-import {defineTheme, generateThemeCSS, generateThemeRules} from './index';
+import {
+ dataTokenDefaults,
+ defineTheme,
+ generateThemeCSS,
+ generateThemeRules,
+} from './index';
+import {generateDataTokenDefaultsCSS} from './generateThemeRules';
const defaultInput = {
name: 'default',
@@ -739,3 +745,60 @@ describe('renamed theme targets', () => {
);
});
});
+
+describe('data visualization tokens', () => {
+ const scopeBlock = (theme: Parameters<typeof generateThemeRules>[0]) =>
+ generateThemeRules(theme).find(r => r.includes(':scope'));
+
+ it('seeds the whole palette once, at :root', () => {
+ const css = generateDataTokenDefaultsCSS();
+
+ expect(css.startsWith(':root {')).toBe(true);
+ for (const [name, value] of Object.entries(dataTokenDefaults)) {
+ expect(css).toContain(`${name}: ${value};`);
+ }
+ });
+
+ it('leaves the defaults out of a theme scope block', () => {
+ // A scope block that re-declared them would shadow a parent theme's
+ // override in every nested <Theme>, which no other token family does.
+ expect(scopeBlock(defineTheme({name: 'data-bare'}))).toBeUndefined();
+ });
+
+ it("puts only the theme's own data token in its scope block", () => {
+ const block = scopeBlock(
+ defineTheme({
+ name: 'data-override',
+ tokens: {'--color-data-categorical-blue': ['#123456', '#654321']},
+ }),
+ )!;
+
+ expect(block).toContain(
+ '--color-data-categorical-blue: light-dark(#123456, #654321);',
+ );
+ expect(block.match(/--color-data-/g)).toHaveLength(1);
+ expect(block).not.toContain('--color-data-categorical-orange');
+ });
+
+ it('carries the palette in the base block, not the scoped stylesheet', () => {
+ const {base, component, prose} = generateThemeCSS(
+ defineTheme({name: 'data-css'}),
+ );
+
+ expect(base).toContain('--color-data-neutral:');
+ expect(base).toContain('--color-data-blue-3:');
+ expect(component).not.toContain('--color-data-');
+ expect(prose).not.toContain('--color-data-');
+ });
+
+ it('gives every theme the same base block', () => {
+ expect(generateThemeCSS(defineTheme({name: 'data-a'})).base).toBe(
+ generateThemeCSS(
+ defineTheme({
+ name: 'data-b',
+ tokens: {'--color-data-categorical-blue': '#00A3FF'},
+ }),
+ ).base,
+ );
+ });
+});
diff --git a/packages/core/src/theme/generateThemeRules.ts b/packages/core/src/theme/generateThemeRules.ts
index 3424971431..9d239b3f05 100644
--- a/packages/core/src/theme/generateThemeRules.ts
+++ b/packages/core/src/theme/generateThemeRules.ts
@@ -18,6 +18,7 @@
import type {DefinedTheme} from './defineTheme';
import {parseStyleKey} from '../utils/parseStyleKey';
import {getDerivedVars} from './derivedVarRegistry';
+import {dataTokenDefaults} from './domainTokens/dataTokens';
import {cssVar, classPrefix, dataAttrNamespace} from '../naming';
/**
@@ -124,7 +125,7 @@ export interface ThemeRulesSplit {
}
/**
- * Output from generateThemeCSS — two CSS blocks for different layers.
+ * Output from generateThemeCSS — three CSS blocks for different layers.
*/
export interface ThemeCSSOutput {
/**
@@ -139,6 +140,13 @@ export interface ThemeCSSOutput {
* theme component overrides take effect. Empty string if no rules.
*/
component: string;
+ /**
+ * The `--color-data-*` defaults at `:root`, identical for every theme.
+ * Should be injected into @layer astryx-base — where StyleX puts the core
+ * token defaults — so a theme's own value outranks it and a nested theme
+ * inherits its parent's override.
+ */
+ base: string;
}
// =============================================================================
@@ -758,11 +766,33 @@ export function generateOnMediaCSS(theme: DefinedTheme): string {
return `@scope (${scopeSelector}) to (${THEME_SCOPE_TO}) {\n${inner}\n}`;
}
+/**
+ * The `--color-data-*` defaults as one unscoped `:root` block.
+ *
+ * Core tokens reach CSS once, at `:root`, from StyleX's `defineVars` output in
+ * `@layer astryx-base`; a theme's own scope block then carries only the tokens
+ * that theme overrides, which is why a nested theme inherits its parent's
+ * override instead of shadowing it. Data tokens are not StyleX vars, so nothing
+ * declares them — this is their equivalent, and callers put it in
+ * `@layer astryx-base` so a theme's override wins by layer rather than by
+ * specificity. Seeding it per theme scope instead re-declares the default
+ * inside every nested theme, which is the shadowing this shape avoids.
+ *
+ * @internal Reached from outside `packages/core` as `generateThemeCSS().base`.
+ */
+export function generateDataTokenDefaultsCSS(): string {
+ const declarations = Object.entries(dataTokenDefaults)
+ .map(([prop, value]) => ` ${prop}: ${value};`)
+ .join('\n');
+ return `:root {\n${declarations}\n}`;
+}
+
/**
* Generate layered CSS for a theme — runtime path.
*
- * Returns two CSS blocks for injection into different layers:
+ * Returns three CSS blocks for injection into different layers:
* - `prose`: @scope'd element defaults → inject into @layer reset
+ * - `base`: the `:root` data-token defaults → inject into @layer astryx-base
* - `component`: @scope'd token + .astryx-* overrides → inject into @layer astryx-theme
*
* This separation ensures prose defaults (what bare HTML looks like in a theme)
@@ -795,5 +825,9 @@ export function generateThemeCSS(theme: DefinedTheme): ThemeCSSOutput {
: onMediaCss;
}
- return {prose: proseCss, component: componentCss};
+ return {
+ prose: proseCss,
+ component: componentCss,
+ base: generateDataTokenDefaultsCSS(),
+ };
}