An open source design system that's fully customizable and agent ready
TypeScript
fix(theme): move data defaults out of theme output (#6834)
Cindy Zhang4aec44c86d69
diff --git a/.changeset/data-vars-stylex-ownership.md b/.changeset/data-vars-stylex-ownership.mdnew file mode 100644index 0000000000..513cc2f4c1--- /dev/null+++ b/.changeset/data-vars-stylex-ownership.md@@ -0,0 +1,22 @@+---+'@astryxdesign/core': minor+'@astryxdesign/cli': minor+---++[breaking] Move canonical data-color defaults from generated theme CSS to the public StyleX `dataVars` group.++Import `dataVars` from `@astryxdesign/core/theme/dataTokens.stylex` for CSS-capable code. Canvas and other non-CSS APIs continue to use `resolveThemeToken()` or `useTheme().token()`. Rebuild committed theme CSS with `astryx theme build`; concrete themes now emit only explicitly authored data-color overrides.++@cixzhang++Old usage:+Generated theme CSS owned the canonical `--color-data-*` root defaults.++Replacement:+The public StyleX `dataVars` group in `@astryxdesign/core/theme/dataTokens.stylex` owns the defaults; concrete themes emit only explicitly authored data-color overrides.++Migration:+Import `dataVars` from `@astryxdesign/core/theme/dataTokens.stylex` for CSS-capable code. Canvas and other non-CSS APIs continue to use `resolveThemeToken()` or `useTheme().token()`. Rebuild committed theme CSS with `astryx theme build`.++Codemod:+`astryx upgrade` runs `validate-data-token-ownership`, which rewrites nothing and reports fallback-less `var(--color-data-*)` uses (whole or embedded source strings, and stylesheets) and stale generated theme CSS for manual migration.diff --git a/packages/cli/api/integration/pack-check.test.mjs b/packages/cli/api/integration/pack-check.test.mjsindex 4223058f53..61b5e3f010 100644--- a/packages/cli/api/integration/pack-check.test.mjs+++ b/packages/cli/api/integration/pack-check.test.mjs@@ -504,6 +504,14 @@ describe('integrationPackCheck', () => {message:'Theme "ocean" exports @acme/widgets/theme.css without a complete built module and stylesheet pair. Missing partner exports alone do not block packing; add the matching export when the theme should be importable. Every declared export must resolve. Staleness is a warning until the complete importable pair is declared.',},+ // A 0.6.5-built stylesheet still carries the root data-color defaults+ // that theme output no longer emits, so it no longer matches its source.+ {+ code: 'theme_stylesheet_stale',+ severity: 'warning',+ message:+ 'Theme "ocean" stylesheet does not match themes/ocean/oceanTheme.ts. This incomplete export remains packable, but run `astryx theme build themes/ocean/oceanTheme.ts` before adding its matching export.',+ },]);const cli = runCliVerify();expect(cli.status, cli.stderr).toBe(0);diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjsindex 54c2710bef..3e331248cd 100644--- a/packages/cli/api/theme/build/build.mjs+++ b/packages/cli/api/theme/build/build.mjs@@ -99,14 +99,12 @@ import {resolveIconImports} from './icon-imports.mjs';// capability instead, required only by a theme that actually uses it:// requiring it unconditionally made every theme build — adaptations or not —// fail against an older published core. This is a targeted allowance for that-// one capability, not a general scheme; the other two optional reads below-// (`generateOnMediaCSS`, `dataTokenDefaults`) both exist in every core that-// ships adaptations' predecessor surface.+// one capability, not a general scheme; `generateOnMediaCSS` exists in every+// core that ships adaptations' predecessor surface./** @type {any} */ let _defineTheme = null;/** @type {any} */ let _generateThemeRulesSplit = null;/** @type {any} */ let _generateOnMediaCSS = null;/** @type {any} */ let _generateAdaptationCSS = null;-/** @type {any} */ let _dataTokenDefaults = null;/*** The whole `@astryxdesign/core/theme` namespace. A theme file handed a* wrapped core must still get every export the installed one has, including@@ -129,7 +127,6 @@ try {_generateThemeRulesSplit = coreTheme.generateThemeRulesSplit;_generateOnMediaCSS = coreTheme.generateOnMediaCSS;_generateAdaptationCSS = coreTheme.generateAdaptationCSS;- _dataTokenDefaults = coreTheme.dataTokenDefaults;try {_coreRootModule = await import('@astryxdesign/core');} catch {@@ -156,7 +153,6 @@ try {* generateThemeRulesSplit: any,* generateOnMediaCSS: any,* generateAdaptationCSS: any,- * dataTokenDefaults: any,* }} CoreBindings*/@@ -173,7 +169,6 @@ const _cliCore = {generateThemeRulesSplit: _generateThemeRulesSplit,generateOnMediaCSS: _generateOnMediaCSS,generateAdaptationCSS: _generateAdaptationCSS,- dataTokenDefaults: _dataTokenDefaults,};/**@@ -188,7 +183,6 @@ function setCore(core) {_generateThemeRulesSplit = core.generateThemeRulesSplit;_generateOnMediaCSS = core.generateOnMediaCSS;_generateAdaptationCSS = core.generateAdaptationCSS;- _dataTokenDefaults = core.dataTokenDefaults;}/**@@ -295,7 +289,6 @@ async function loadProjectCore(cwd) {generateThemeRulesSplit: themeModule.generateThemeRulesSplit,generateOnMediaCSS: themeModule.generateOnMediaCSS,generateAdaptationCSS: themeModule.generateAdaptationCSS,- dataTokenDefaults: themeModule.dataTokenDefaults,};}@@ -2739,26 +2732,8 @@ async function themeBuildInternal(logger.log(`${source}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. Formatted here from the- // public `dataTokenDefaults` export, byte for byte as the `<Theme>`- // runtime emits it — build-theme.data-tokens.test.mjs is the drift guard.- // 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 = _dataTokenDefaults- ? `:root {\n${Object.entries(_dataTokenDefaults)- .map(([name, value]) => ` ${name}: ${value};`)- .join('\n')}\n}`- : '';- if (baseCss) {- cssParts.splice(- prose.length > 0 ? 1 : 0,- 0,- `@layer astryx-base {\n${baseCss}\n}`,- );- }+ cssParts.unshift('@layer reset, astryx-base, astryx-theme;');+ const baseCss = '';cssPlan = {base: baseCss,prose,diff --git a/packages/cli/api/theme/build/family.mjs b/packages/cli/api/theme/build/family.mjsindex dadf0f1c6e..730a0aacaa 100644--- a/packages/cli/api/theme/build/family.mjs+++ b/packages/cli/api/theme/build/family.mjs@@ -438,5 +438,5 @@ export function generateFamilyCSS(members) {parts.push(`@layer astryx-base {\n${base.join('\n\n')}\n}`);if (themed.length > 0)parts.push(`@layer astryx-theme {\n${themed.join('\n\n')}\n}`);- return `${parts.join('\n\n')}\n`;+ return `@layer reset, astryx-base, astryx-theme;\n\n${parts.join('\n\n')}\n`;}diff --git a/packages/cli/assets/codemods/transforms/next/__tests__/validate-data-token-ownership.test.mjs b/packages/cli/assets/codemods/transforms/next/__tests__/validate-data-token-ownership.test.mjsnew file mode 100644index 0000000000..ffc31eafa0--- /dev/null+++ b/packages/cli/assets/codemods/transforms/next/__tests__/validate-data-token-ownership.test.mjs@@ -0,0 +1,84 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import transform from '../validate-data-token-ownership.mjs';++async function run(source, file = 'test.tsx') {+ const jscodeshift = (await import('jscodeshift')).default;+ const parser =+ file.endsWith('.ts') || file.endsWith('.tsx') ? 'tsx' : 'babel';+ const api = {+ jscodeshift: jscodeshift.withParser(parser),+ stats: () => {},+ report: () => {},+ };+ return transform({source, path: file}, api);+}++describe('validate-data-token-ownership', () => {+ it('reports direct string and static-template consumers with both migration paths', async () => {+ for (const source of [+ `const fill = 'var(--color-data-categorical-green)';`,+ 'const fill = `var(--color-data-categorical-green)`;',+ `const border = '1px solid var(--color-data-categorical-green)';`,+ 'const border = `${width}px solid var(--color-data-categorical-green)`;',+ ]) {+ await expect(run(source)).rejects.toThrow(+ /CSS-capable code imports dataVars.*Canvas.*resolveThemeToken/s,+ );+ }+ });++ it('leaves fallbacks, dataVars access, and comments unchanged', async () => {+ const source = `+// var(--color-data-categorical-green)+const fallback = 'var(--color-data-categorical-green, #008000)';+const fill = dataVars['--color-data-categorical-green'];+`;+ expect(await run(source)).toBeUndefined();+ });++ it('reports stale generated theme CSS with root data defaults', async () => {+ const source = `/* @generated by \`astryx theme build\` */+@layer astryx-base {+ :root { --color-data-categorical-green: #008000; }+}`;+ await expect(run(source, 'theme.css')).rejects.toThrow(+ /Rebuild it with `astryx theme build`/,+ );+ });++ it('reports raw stylesheet uses without a fallback', async () => {+ await expect(+ run('.bar { fill: var(--color-data-categorical-green); }', 'chart.css'),+ ).rejects.toThrow(/Raw var\(--color-data-categorical-green\).*line 1/s);+ });++ it('leaves stylesheet uses with a fallback, and comments, unchanged', async () => {+ expect(+ await run(+ `/* var(--color-data-categorical-green) */+.bar { fill: var(--color-data-categorical-green, #008000); }`,+ 'chart.css',+ ),+ ).toBeUndefined();+ });++ it('does not claim ownership of hand-authored CSS or sparse theme overrides', async () => {+ expect(+ await run(+ ':root { --color-data-categorical-green: #008000; }',+ 'app.css',+ ),+ ).toBeUndefined();+ expect(+ await run(+ `/* @generated by \`astryx theme build\` */+@scope ([data-astryx-theme="ocean"]) {+ :scope { --color-data-categorical-green: #008000; }+}`,+ 'theme.css',+ ),+ ).toBeUndefined();+ });+});diff --git a/packages/cli/assets/codemods/transforms/next/index.mjs b/packages/cli/assets/codemods/transforms/next/index.mjsindex db5cf9c6eb..d89dc5fcbb 100644--- a/packages/cli/assets/codemods/transforms/next/index.mjs+++ b/packages/cli/assets/codemods/transforms/next/index.mjs@@ -10,6 +10,9 @@import migrateDeprecatedThemeSurface, {meta as migrateDeprecatedThemeSurfaceMeta,} from './migrate-deprecated-theme-surface.mjs';+import validateDataTokenOwnership, {+ meta as validateDataTokenOwnershipMeta,+} from './validate-data-token-ownership.mjs';export default [{@@ -17,4 +20,9 @@ export default [transform: migrateDeprecatedThemeSurface,meta: migrateDeprecatedThemeSurfaceMeta,},+ {+ name: 'validate-data-token-ownership',+ transform: validateDataTokenOwnership,+ meta: validateDataTokenOwnershipMeta,+ },];diff --git a/packages/cli/assets/codemods/transforms/next/validate-data-token-ownership.mjs b/packages/cli/assets/codemods/transforms/next/validate-data-token-ownership.mjsnew file mode 100644index 0000000000..9164f6fedd--- /dev/null+++ b/packages/cli/assets/codemods/transforms/next/validate-data-token-ownership.mjs@@ -0,0 +1,102 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Report data-token consumers that need an ownership migration.+ *+ * @input Consumer JavaScript/TypeScript source and generated theme CSS+ * @output No rewritten source; actionable upgrade errors for fallback-less+ * `var(--color-data-*)` uses (in JS strings, embedded or whole, and in CSS)+ * and stale generated root-default artifacts+ * @position Next-release upgrade validation for spec:AST-066+ */++import * as path from 'node:path';++export const meta = {+ title: 'Validate data-token ownership',+ description:+ 'Reports fallback-less data-token var() uses in source strings and stylesheets for manual CSS/non-CSS migration, and stale generated theme CSS that still owns root defaults.',+ fileExtensions: ['.tsx', '.ts', '.jsx', '.js', '.mjs', '.cjs', '.css'],+};++// A use without a fallback; `var(--color-data-x, <fallback>)` stays valid.+const DIRECT_DATA_VAR = /var\(\s*(--color-data-[a-z0-9-]+)\s*\)/u;+const CSS_COMMENT = /\/\*[\s\S]*?\*\//gu;+const GENERATED_THEME_HEADER = '@generated by `astryx theme build`';+const ROOT_DATA_DECLARATION = /:root\s*\{[^}]*--color-data-/su;++/** @param {any} node */+function staticString(node) {+ if (+ (node?.type === 'StringLiteral' || node?.type === 'Literal') &&+ typeof node.value === 'string'+ ) {+ return node.value;+ }+ if (node?.type === 'TemplateLiteral') {+ // Each static chunk of the template; a use can sit between expressions.+ return (node.quasis ?? [])+ .map((/** @type {any} */ q) => q?.value?.cooked ?? q?.value?.raw ?? '')+ .join('\u0000');+ }+ return undefined;+}++/**+ * @param {import('../../../../authoring/codemod/type').AstryxCodemodFile} file+ * @param {import('../../../../authoring/codemod/type').CodemodTransformApi} api+ * @returns {undefined}+ */+export default function validateDataTokenOwnership(file, api) {+ if (!file.source.includes('--color-data-')) return undefined;++ if (path.extname(file.path) === '.css') {+ if (+ file.source.includes(GENERATED_THEME_HEADER) &&+ ROOT_DATA_DECLARATION.test(file.source)+ ) {+ throw new Error(+ 'This generated theme CSS still emits canonical data defaults at :root. Rebuild it with `astryx theme build`; defaults now come from compiled dataVars consumers.',+ );+ }+ const uncommented = file.source.replace(CSS_COMMENT, comment =>+ comment.replace(/[^\n]/gu, ' '),+ );+ const cssMatch = DIRECT_DATA_VAR.exec(uncommented);+ if (cssMatch) {+ const line = uncommented.slice(0, cssMatch.index).split('\n').length;+ throw new Error(+ `Raw var(${cssMatch[1]}) without a fallback at line ${line} needs manual migration: compiled dataVars output is not guaranteed in this stylesheet, so add an explicit fallback or style the element from code that imports dataVars from @astryxdesign/core/theme/dataTokens.stylex.`,+ );+ }+ return undefined;+ }++ const j = api.jscodeshift;+ const root = j(file.source);+ /** @type {{token: string, line: number|null}|null} */+ let found = null;+ const inspect = (/** @type {any} */ node) => {+ if (found) return;+ const value = staticString(node);+ const match =+ typeof value === 'string' ? value.match(DIRECT_DATA_VAR) : null;+ if (match) {+ found = {token: match[1], line: node.loc?.start?.line ?? null};+ }+ };++ /** @param {any} nodePath */+ const inspectPath = nodePath => inspect(nodePath.node);+ root.find(j.StringLiteral).forEach(inspectPath);+ root.find(j.Literal).forEach(inspectPath);+ root.find(j.TemplateLiteral).forEach(inspectPath);++ if (found) {+ const {token, line} = found;+ throw new Error(+ `Direct var(${token})${line == null ? '' : ` at line ${line}`} needs manual migration: CSS-capable code imports dataVars from @astryxdesign/core/theme/dataTokens.stylex; Canvas and other non-CSS APIs use resolveThemeToken() or useTheme().token().`,+ );+ }+ return undefined;+}diff --git a/packages/cli/assets/docs/author-a-theme.doc.mjs b/packages/cli/assets/docs/author-a-theme.doc.mjsindex a3186808fe..9b7c8f5667 100644--- a/packages/cli/assets/docs/author-a-theme.doc.mjs+++ b/packages/cli/assets/docs/author-a-theme.doc.mjs@@ -157,7 +157,7 @@ export const docs = {{title: 'useTheme Hook',content: [- {type: 'prose', text: '`useTheme()` reads the nearest Theme and effective color mode from React context. Use it inside client components for SVG, canvas, charts, maps, and third-party configuration objects that need token values in JavaScript.'},+ {type: 'prose', text: '`useTheme()` reads the nearest Theme and effective color mode from React context. Prefer `dataVars` for CSS-capable SVG and DOM values. Use this hook for canvas, charts, maps, third-party configuration objects, or an SVG API that requires a concrete JavaScript color instead of a `var(...)` reference.'},{type: 'code', lang: 'tsx', label: 'Access resolved token values in React', code: "import {useMemo} from 'react';\nimport {useTheme} from '@astryxdesign/core/theme';\n\nfunction ChartConfig() {\n const {mode, tokens} = useTheme();\n const options = useMemo(() => ({\n mode,\n textColor: tokens['--color-text-primary'],\n gridColor: tokens['--color-border'],\n seriesColor: tokens['--color-data-categorical-blue'],\n }), [mode, tokens]);\n return <Chart options={options} />;\n}"},{type: 'prose', text: 'Prefer CSS variables for ordinary styling. See {@link generic:use-a-theme} for the provider setup, and {@link namespace:tokens} for the full token reference.'},],diff --git a/packages/cli/assets/docs/tree/tokens-data.doc.mjs b/packages/cli/assets/docs/tree/tokens-data.doc.mjsindex 0e0ba1e883..afc0d0c656 100644--- a/packages/cli/assets/docs/tree/tokens-data.doc.mjs+++ b/packages/cli/assets/docs/tree/tokens-data.doc.mjs@@ -17,14 +17,14 @@ export const docs = {"order": 20},"category": "foundations",- "description": "Colors for charts and graphs: one categorical accent per series, a neutral for labels and reference lines, and sequential ramps from 5 (darkest) to 1 (lightest) for ordered scales and heatmaps. Import their public StyleX variables from @astryxdesign/core/theme/dataTokens.stylex.",+ "description": "Colors for charts and graphs: one categorical accent per series, a neutral for labels and reference lines, and sequential ramps from 5 (darkest) to 1 (lightest) for ordered scales and heatmaps. Import dataVars from @astryxdesign/core/theme/dataTokens.stylex for CSS-capable code. Retaining any member emits the complete 56-variable group; an unused graph emits none.","sections": [{"title": "Data Visualization Tokens","content": [{"type": "prose",- "text": "Colors for charts and graphs: one categorical accent per series, a neutral for labels and reference lines, and sequential ramps from 5 (darkest) to 1 (lightest) for ordered scales and heatmaps. Import their public StyleX variables from @astryxdesign/core/theme/dataTokens.stylex."+ "text": "Colors for charts and graphs: one categorical accent per series, a neutral for labels and reference lines, and sequential ramps from 5 (darkest) to 1 (lightest) for ordered scales and heatmaps. Import dataVars from @astryxdesign/core/theme/dataTokens.stylex for CSS-capable code. Retaining any member emits the complete 56-variable group; an unused graph emits none."},{"type": "table",diff --git a/packages/cli/assets/docs/tree/tokens-usage.doc.mjs b/packages/cli/assets/docs/tree/tokens-usage.doc.mjsindex 35e3924c23..6d9808c07d 100644--- a/packages/cli/assets/docs/tree/tokens-usage.doc.mjs+++ b/packages/cli/assets/docs/tree/tokens-usage.doc.mjs@@ -28,7 +28,7 @@ export const docs = {},{"type": "prose",- "text": "See {@link namespace:styling} for how to apply tokens via xstyle, className, and compound component patterns. See {@link generic:author-a-theme} for overriding tokens with defineTheme."+ "text": "Use `dataVars` for StyleX, DOM styles, and SVG presentation attributes. Canvas and other APIs that require concrete mode-resolved values use `resolveThemeToken()` or `useTheme().token()` instead. Raw CSS may use the stable custom-property names only when compiled dataVars output is guaranteed or the declaration carries an explicit fallback. See {@link namespace:styling} for xstyle, className, and compound component patterns, and {@link generic:author-a-theme} for overriding tokens with defineTheme."}]}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.mjsindex a105af0d33..fc314f4cbc 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,9 +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 — the- * generated CSS still carries the `--color-data-*` defaults, which are- * `light-dark()` pairs, so the decision reads the theme's own values.+ * resolve, so none of the three rules should be emitted for them. Canonical data+ * defaults come from StyleX rather than theme output, so this decision continues+ * to read only the theme's authored 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@@ -35,8 +35,10 @@ import {ensureCoreBuilt} from './ensure-core-built.mjs';import {runCli} from '../../../test-utils/run-cli.mjs';const COLOR_SCHEME_ROOT_DECL = ':root { color-scheme: light dark; }';-const COLOR_SCHEME_LIGHT_DECL = 'html[data-theme="light"] { color-scheme: light; }';-const COLOR_SCHEME_DARK_DECL = 'html[data-theme="dark"] { color-scheme: dark; }';+const COLOR_SCHEME_LIGHT_DECL =+ 'html[data-theme="light"] { color-scheme: light; }';+const COLOR_SCHEME_DARK_DECL =+ 'html[data-theme="dark"] { color-scheme: dark; }';function writeTheme(dir, name, tokens) {fs.mkdirSync(dir, {recursive: true});@@ -58,7 +60,9 @@ beforeAll(() => {let tmpDir;beforeEach(() => {- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-build-theme-color-scheme-'));+ tmpDir = fs.mkdtempSync(+ path.join(os.tmpdir(), 'astryx-build-theme-color-scheme-'),+ );});afterEach(() => {fs.rmSync(tmpDir, {recursive: true, force: true});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.mjsindex e0739d41af..799e8fc4ad 100644--- a/packages/cli/clients/cli/commands/build-theme.data-tokens.test.mjs+++ b/packages/cli/clients/cli/commands/build-theme.data-tokens.test.mjs@@ -1,32 +1,17 @@// 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.- *- * The build formats the defaults block itself, from the public- * `dataTokenDefaults` export; core formats it for the runtime. This suite is- * what keeps those two independent formattings byte-identical.+ * @file Verifies `astryx theme build` emits sparse data overrides and no+ * canonical root defaults while preserving explicit cascade-layer order.+ * @input Temporary standalone theme modules compiled through the public CLI+ * @output Structural assertions for AST-066 data-token ownership+ * @position Regression suite for theme-build CSS ownership*/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';-// Core's own generator, imported from source rather than from the package: it-// is deliberately not part of `@astryxdesign/core/theme`'s public surface, and-// this suite is the guard that the build's independent formatting matches it.-import {generateDataTokenDefaultsCSS} from '../../../../core/src/theme/generateThemeRules';-import {dataTokenDefaults as sourceDataTokenDefaults} from '../../../../core/src/theme/domainTokens/dataTokens';import {ensureCoreBuilt} from './ensure-core-built.mjs';import {runCli} from '../../../test-utils/run-cli.mjs';@@ -67,78 +52,41 @@ afterEach(() => {});describe('theme build data token output', () => {- it('emits the defaults once, at :root, in @layer astryx-base', async () => {+ it('emits no canonical data defaults or raw root data block', 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);+ expect(css).not.toContain('--color-data-');+ expect(css).not.toMatch(/:root\s*\{[^}]*--color-data-/s);+ expect(css).not.toContain('@layer astryx-base {\n:root {');});- it('declares astryx-base after reset and before astryx-theme', async () => {+ it('registers layer order before every emitted layer block', 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');+ const order = css.indexOf('@layer reset, astryx-base, astryx-theme;');+ const reset = css.indexOf('@layer reset {');+ const theme = css.indexOf('@layer astryx-theme {');- expect(reset).toBeGreaterThanOrEqual(0);- expect(base).toBeGreaterThan(reset);- expect(theme).toBeGreaterThan(base);+ expect(order).toBeGreaterThanOrEqual(0);+ expect(reset).toBeGreaterThan(order);+ expect(theme).toBeGreaterThan(order);});- it("puts only the theme's own data token in its scope block", async () => {+ it("puts only the theme's authored data token in its donut", 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 css = await buildTheme(tmpDir, 'charts-parity', {- tokens: {'--color-accent': '#0077B6'},- });-- // The expectation below comes from core's SOURCE; the stylesheet came from- // core's dist. ensureCoreBuilt() only checks that dist exists, never that- // it is current, so a dist older than the source would fail the byte- // comparison with a colour mismatch that reads as formatter drift. Name- // that case first.- const {dataTokenDefaults: builtDataTokenDefaults} = await import(- '@astryxdesign/core/theme'- );- expect(- builtDataTokenDefaults,- 'packages/core/dist is stale — run `pnpm -F @astryxdesign/core build`',- ).toEqual(sourceDataTokenDefaults);-- // The build formats this block itself, from the public `dataTokenDefaults`- // export; the runtime formats it in core. Nothing else holds the two- // together, so compare the bytes — a changed indent or separator in either- // one fails here.- const runtimeBase = generateDataTokenDefaultsCSS();- const marker = '@layer astryx-base {\n';- const start = css.indexOf(marker);- expect(start).toBeGreaterThanOrEqual(0);-- const bodyStart = start + marker.length;- expect(css.slice(bodyStart, bodyStart + runtimeBase.length)).toBe(- runtimeBase,+ expect(css).toContain(+ '@scope ([data-astryx-theme="charts-override"]) to ([data-astryx-theme])',);- expect(css.slice(bodyStart + runtimeBase.length)).toMatch(/^\n\}/);+ expect(css).toContain('--color-data-categorical-blue: #00A3FF;');+ expect(css.match(/--color-data-/g)).toHaveLength(1);+ expect(css).not.toContain('--color-data-categorical-orange');+ expect(css).not.toContain('--color-data-gray-1');});});diff --git a/packages/core/src/theme/Theme.test.tsx b/packages/core/src/theme/Theme.test.tsxindex 41644c0756..2cab9d19f6 100644--- a/packages/core/src/theme/Theme.test.tsx+++ b/packages/core/src/theme/Theme.test.tsx@@ -5,7 +5,6 @@ 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(() => ({@@ -215,67 +214,75 @@ describe('Theme', () => {});// =========================================================================- // Data token defaults — one shared :root block, not one per theme scope+ // Data token ownership — StyleX defaults, sparse Theme overrides// =========================================================================- const baseTags = () =>- Array.from(document.head.querySelectorAll('style[data-astryx-theme-base]'));-- it('injects the data token defaults into @layer astryx-base', () => {+ it('does not inject canonical data defaults', () => {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']};`,- );+ expect(+ document.head.querySelector('style[data-astryx-theme-base]'),+ ).toBeNull();+ const injected = Array.from(document.head.querySelectorAll('style'))+ .map(tag => tag.textContent ?? '')+ .join('\n');+ expect(injected).not.toContain('--color-data-');+ expect(injected).not.toContain(':root {');});- it('injects one shared block for nested themes, not one per scope', () => {+ it('injects only an authored data override inside the theme donut', () => {+ const theme = defineTheme({+ name: 'data-override',+ tokens: {'--color-data-categorical-blue': '#00A3FF'},+ });render(- <Theme theme={testTheme}>- <Theme theme={altTheme}>- <span>nested</span>- </Theme>+ <Theme theme={theme}>+ <span>child</span></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]'),+ const css = Array.from(+ document.head.querySelectorAll(+ 'style[data-astryx-theme="data-override"]',+ ),+ )+ .map(tag => tag.textContent ?? '')+ .join('\n');+ expect(css).toContain('@layer reset, astryx-base, astryx-theme;');+ expect(css).toContain(+ '@scope ([data-astryx-theme="data-override"]) to ([data-astryx-theme])',);- for (const tag of themeTags) {- expect(tag.textContent).not.toContain('--color-data-');- }+ expect(css).toContain('--color-data-categorical-blue: #00A3FF;');+ expect(css.match(/--color-data-/g)).toHaveLength(1);+ expect(css).not.toContain(':root {');});- it('keeps the defaults while any theme is still mounted', () => {- const outer = render(- <Theme theme={testTheme}>- <span>a</span>- </Theme>,- );+ it('lets a nested theme inherit an unspecified parent data override', () => {+ const parent = defineTheme({+ name: 'data-parent',+ tokens: {'--color-data-categorical-blue': '#00A3FF'},+ });+ const child = defineTheme({name: 'data-child'});render(- <Theme theme={altTheme}>- <span>b</span>+ <Theme theme={parent}>+ <Theme theme={child}>+ <span>nested</span>+ </Theme></Theme>,);- outer.unmount();- expect(baseTags()).toHaveLength(1);-- cleanup();- expect(baseTags()).toHaveLength(0);+ const parentCss = document.head.querySelector(+ 'style[data-astryx-theme="data-parent"]',+ )?.textContent;+ const childCss = document.head.querySelector(+ 'style[data-astryx-theme="data-child"]',+ )?.textContent;+ expect(parentCss).toContain('--color-data-categorical-blue: #00A3FF;');+ expect(childCss ?? '').not.toContain('--color-data-');});it('generates a theme once across nested and sibling mounts', () => {@@ -293,11 +300,10 @@ describe('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);+ expect(injected).toContain('@layer reset, astryx-base, astryx-theme;');+ expect(injected).not.toContain(':root {');});});diff --git a/packages/core/src/theme/Theme.tsx b/packages/core/src/theme/Theme.tsxindex e625fd0bcc..4038421c37 100644--- a/packages/core/src/theme/Theme.tsx+++ b/packages/core/src/theme/Theme.tsx@@ -41,7 +41,6 @@ import * as stylex from '@stylexjs/stylex';import type {ThemeMode} from './types';import {colorVars, typographyVars} from './tokens.stylex';import {generateThemeCSS, type DefinedTheme} from './defineTheme';-import {generateDataTokenDefaultsCSS} from './generateThemeRules';import {registerTheme} from './themeRegistry';import {dataAttr} from '../naming';import {ThemeContext} from './useTheme';@@ -97,16 +96,7 @@ 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;+const THEME_LAYER_ORDER = '@layer reset, astryx-base, astryx-theme;';/*** Hook to inject theme CSS into the document.@@ -142,35 +132,16 @@ function useThemeStyleInjection(theme: DefinedTheme): void {);const {prose, component} = generateThemeCSS(theme);- const base = generateDataTokenDefaultsCSS();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// the theme region. Any class-based style (StyleX, .xds-*) wins.if (prose) {const proseStyle = document.createElement('style');proseStyle.setAttribute(dataAttr('theme-prose'), theme.name);proseStyle.setAttribute(dataAttr('id'), id);- proseStyle.textContent = `@layer reset {\n${prose}\n}`;+ proseStyle.textContent = `${THEME_LAYER_ORDER}\n@layer reset {\n${prose}\n}`;document.head.appendChild(proseStyle);}@@ -180,7 +151,7 @@ function useThemeStyleInjection(theme: DefinedTheme): void {const compStyle = document.createElement('style');compStyle.setAttribute(dataAttr('theme'), theme.name);compStyle.setAttribute(dataAttr('id'), id);- compStyle.textContent = `@layer astryx-theme {\n${component}\n}`;+ compStyle.textContent = `${THEME_LAYER_ORDER}\n@layer astryx-theme {\n${component}\n}`;document.head.appendChild(compStyle);}diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.tsindex 3de6afde45..9b99f1da55 100644--- a/packages/core/src/theme/defineTheme.test.ts+++ b/packages/core/src/theme/defineTheme.test.ts@@ -246,9 +246,8 @@ describe('generateThemeCSS', () => {});it('keeps the data palette out of a theme that never mentions it', () => {- // That the palette IS declared is covered by `seeds the whole palette- // once, at :root` in generateThemeRules.test.ts. It is theme-independent,- // so there is nothing about it a theme can be used to assert.+ // Canonical defaults come from the public StyleX dataVars group, so a+ // theme that never authors data colors has nothing to serialize.const {component} = generateThemeCSS(defineTheme({name: 'chartless'}));expect(component).not.toContain('--color-data-');});@@ -263,8 +262,8 @@ describe('generateThemeCSS', () => {// Leaving the siblings out of the theme's own block is what lets a nested// theme inherit a parent's override instead of shadowing it.expect(component).not.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.+ // Defaults reach compiled consumer CSS without entering the theme's own+ // tokens, which are what `astryx theme build` reports as overrides.expect(theme.tokens['--color-data-categorical-orange']).toBeUndefined();});diff --git a/packages/core/src/theme/generateThemeRules.test.ts b/packages/core/src/theme/generateThemeRules.test.tsindex 6131c763d2..956dcefd1f 100644--- a/packages/core/src/theme/generateThemeRules.test.ts+++ b/packages/core/src/theme/generateThemeRules.test.ts@@ -8,7 +8,6 @@import {describe, it, expect, vi} from 'vitest';import {- dataTokenDefaults,defineTheme,generateAdaptationCSS,generateThemeCSS,@@ -16,7 +15,6 @@ import {generateThemeRules,type DefinedTheme,} from './index';-import {generateDataTokenDefaultsCSS} from './generateThemeRules';function topLevelCSSBlocks(css: string): string[] {const blocks: string[] = [];@@ -1365,16 +1363,7 @@ 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', () => {+ it('leaves canonical 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();@@ -1395,9 +1384,9 @@ describe('data visualization tokens', () => {expect(block).not.toContain('--color-data-categorical-orange');});- it('keeps the palette out of the scoped stylesheet', () => {- // The palette's own contents are asserted once, against- // `dataTokenDefaults`, in `seeds the whole palette once, at :root` above.+ it('keeps canonical defaults out of the theme stylesheet', () => {+ // The public StyleX dataVars group owns canonical CSS defaults; this+ // generator serializes only values explicitly authored by the theme.const {component, prose} = generateThemeCSS(defineTheme({name: 'data-css'}),);@@ -1407,9 +1396,8 @@ describe('data visualization tokens', () => {});it('keeps generateThemeCSS to its two scoped blocks', () => {- // The defaults are theme-independent, so they are not part of the theme- // CSS contract: `astryx theme build` formats them from the public- // `dataTokenDefaults` export instead.+ // Canonical defaults come from public StyleX output, not a third theme+ // generator block.expect(Object.keys(generateThemeCSS(defineTheme({name: 'data-shape'}))).sort(),).toEqual(['component', 'prose']);diff --git a/packages/core/src/theme/generateThemeRules.ts b/packages/core/src/theme/generateThemeRules.tsindex 8eef9c1b8d..b7c2c81b16 100644--- a/packages/core/src/theme/generateThemeRules.ts+++ b/packages/core/src/theme/generateThemeRules.ts@@ -32,7 +32,6 @@ import {} from './themeAdaptations';import {parseStyleKey} from '../utils/parseStyleKey';import {getDerivedVars} from './derivedVarRegistry';-import {dataTokenDefaults} from './domainTokens/dataTokens';import {cssVar, classPrefix, dataAttrNamespace} from '../naming';import {checkDeclarationName,@@ -1215,30 +1214,6 @@ function indentRule(rule: string): string {return ` ${rule}`;}-/**- * 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 Not exported from `@astryxdesign/core/theme`: the `<Theme>`- * runtime is the only caller. `astryx theme build` formats the same block from- * the public `dataTokenDefaults` export, and a CLI test asserts the two are- * byte-identical.- */-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.*@@ -1250,8 +1225,8 @@ export function generateDataTokenDefaultsCSS(): string {* sit at reset-layer priority where any class-based style wins, while component* overrides sit above StyleX so themes can restyle components intentionally.*- * The theme-independent `--color-data-*` defaults are not part of this output:- * see `generateDataTokenDefaultsCSS`.+ * Data-token defaults are owned by the public StyleX `dataVars` group. This+ * generator emits only a theme's explicitly authored token overrides.*/export function generateThemeCSS(theme: DefinedTheme,diff --git a/scripts/generate-token-docs.mjs b/scripts/generate-token-docs.mjsindex ead4d4d878..c71fc2198b 100644--- a/scripts/generate-token-docs.mjs+++ b/scripts/generate-token-docs.mjs@@ -130,7 +130,7 @@ const groups = [file: DATA_TOKENS_SRC,title: 'Data Visualization Tokens',description:- 'Colors for charts and graphs: one categorical accent per series, a neutral for labels and reference lines, and sequential ramps from 5 (darkest) to 1 (lightest) for ordered scales and heatmaps. Import their public StyleX variables from @astryxdesign/core/theme/dataTokens.stylex.',+ 'Colors for charts and graphs: one categorical accent per series, a neutral for labels and reference lines, and sequential ramps from 5 (darkest) to 1 (lightest) for ordered scales and heatmaps. Import dataVars from @astryxdesign/core/theme/dataTokens.stylex for CSS-capable code. Retaining any member emits the complete 56-variable group; an unused graph emits none.',headers: ['Token', 'Light', 'Dark'],formatRow: lightDarkRow,},@@ -394,7 +394,7 @@ const styles = stylex.create({},{type: 'prose',- text: 'See {@link namespace:styling} for how to apply tokens via xstyle, className, and compound component patterns. See {@link generic:author-a-theme} for overriding tokens with defineTheme.',+ text: 'Use `dataVars` for StyleX, DOM styles, and SVG presentation attributes. Canvas and other APIs that require concrete mode-resolved values use `resolveThemeToken()` or `useTheme().token()` instead. Raw CSS may use the stable custom-property names only when compiled dataVars output is guaranteed or the declaration carries an explicit fallback. See {@link namespace:styling} for xstyle, className, and compound component patterns, and {@link generic:author-a-theme} for overriding tokens with defineTheme.',},],},