Skip to content

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

TypeScript

fix(theme): inject prose rules into reset layer, not xds-theme (#1140)

Cindy Zhang03e1dcc723bd
diff --git a/apps/example-vite/vite.config.ts b/apps/example-vite/vite.config.ts
index 82efe2e384..04af39b787 100644
--- a/apps/example-vite/vite.config.ts
+++ b/apps/example-vite/vite.config.ts
@@ -23,10 +23,9 @@ const lightningcssTargets = {
// https://vite.dev/config/
export default defineConfig({
plugins: [
- // Declare CSS layer order so theme overrides beat component base styles.
- // Without this, layers are ordered by first appearance — and the StyleX
- // priority layers (component styles) would come after xds.theme,
- // preventing theme overrides from taking effect.
+ // Declare CSS layer order. xds-theme is last (highest priority among
+ // declared layers) so theme component overrides beat StyleX styles.
+ // Prose defaults inject into @layer reset (lowest priority).
{
name: 'xds-css-layer-order',
transformIndexHtml() {
@@ -34,7 +33,7 @@ export default defineConfig({
{
tag: 'style',
children:
- '@layer reset, priority1, priority2, priority3, priority4, priority5, priority6, priority7, priority8, priority9, xds.theme;',
+ '@layer reset, priority1, priority2, priority3, priority4, priority5, priority6, priority7, priority8, priority9, xds-theme;',
injectTo: 'head-prepend',
},
];
diff --git a/packages/cli/src/commands/build-theme.mjs b/packages/cli/src/commands/build-theme.mjs
index d0bdefb6bc..1a1c714cc9 100644
--- a/packages/cli/src/commands/build-theme.mjs
+++ b/packages/cli/src/commands/build-theme.mjs
@@ -21,10 +21,12 @@ import {getRunPrefix} from '../utils/package-manager.mjs';
const _require = createRequire(import.meta.url);
let _defineTheme = null;
let _generateThemeRules = null;
+let _generateThemeRulesSplit = null;
try {
const coreTheme = _require('@xds/core/theme');
_defineTheme = coreTheme.defineTheme;
_generateThemeRules = coreTheme.generateThemeRules;
+ _generateThemeRulesSplit = coreTheme.generateThemeRulesSplit;
} catch {
// Core not available — fall back to legacy generation
}
@@ -783,18 +785,42 @@ export function registerTheme(program) {
tokens: themeDef.tokens,
components: themeDef.components,
});
- const rules = _generateThemeRules(resolvedTheme);
- if (rules.length === 0) {
- console.log('No overrides found — nothing to build.');
- return;
- }
const scopeSelector = `[data-xds-theme="${themeDef.name}"]`;
- const inner = rules.join('\n\n');
- const scopeBlock = `@scope (${scopeSelector}) to ([data-xds-theme]) {\n${inner}\n}`;
- const colorSchemeDecl = scopeBlock.includes('light-dark(')
- ? ' :root { color-scheme: light dark; }\n\n'
- : '';
- css = `@layer xds-theme {\n${colorSchemeDecl}${scopeBlock}\n}\n`;
+ const scopeTo = `[data-xds-theme]`;
+
+ if (_generateThemeRulesSplit) {
+ const {component, prose} = _generateThemeRulesSplit(resolvedTheme);
+ if (component.length === 0 && prose.length === 0) {
+ console.log('No overrides found — nothing to build.');
+ return;
+ }
+ const cssParts = [];
+ if (prose.length > 0) {
+ const proseInner = prose.join('\n\n');
+ cssParts.push(`@layer reset {\n@scope (${scopeSelector}) to (${scopeTo}) {\n${proseInner}\n}\n}`);
+ }
+ if (component.length > 0) {
+ const componentInner = component.join('\n\n');
+ const componentScope = `@scope (${scopeSelector}) to (${scopeTo}) {\n${componentInner}\n}`;
+ const colorSchemeDecl = componentScope.includes('light-dark(')
+ ? ' :root { color-scheme: light dark; }\n\n'
+ : '';
+ cssParts.push(`@layer xds-theme {\n${colorSchemeDecl}${componentScope}\n}`);
+ }
+ css = cssParts.join('\n\n') + '\n';
+ } else {
+ const rules = _generateThemeRules(resolvedTheme);
+ if (rules.length === 0) {
+ console.log('No overrides found — nothing to build.');
+ return;
+ }
+ const inner = rules.join('\n\n');
+ const scopeBlock = `@scope (${scopeSelector}) to (${scopeTo}) {\n${inner}\n}`;
+ const colorSchemeDecl = scopeBlock.includes('light-dark(')
+ ? ' :root { color-scheme: light dark; }\n\n'
+ : '';
+ css = `@layer xds-theme {\n${colorSchemeDecl}${scopeBlock}\n}\n`;
+ }
} else {
// Legacy fallback when core isn't built yet
const scopeBlocks = [];
diff --git a/packages/core/src/theme/XDSTheme.tsx b/packages/core/src/theme/XDSTheme.tsx
index 82d70df96a..6dd91137c5 100644
--- a/packages/core/src/theme/XDSTheme.tsx
+++ b/packages/core/src/theme/XDSTheme.tsx
@@ -88,24 +88,42 @@ function useThemeStyleInjection(theme: XDSDefinedTheme): void {
const themeKey = `xds-theme-${theme.name}`;
if (injectedThemes.has(themeKey)) return;
- const css = generateThemeCSS(theme);
- if (!css) return;
-
- const style = document.createElement('style');
- style.setAttribute('data-xds-theme', theme.name);
- style.setAttribute('data-xds-id', id);
- style.textContent = `@layer xds-theme {\n${css}\n}`;
- document.head.appendChild(style);
+ const {prose, component} = generateThemeCSS(theme);
+ if (!prose && !component) return;
+
+ // 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('data-xds-theme-prose', theme.name);
+ proseStyle.setAttribute('data-xds-id', id);
+ proseStyle.textContent = `@layer reset {\n${prose}\n}`;
+ document.head.appendChild(proseStyle);
+ }
+
+ // Component overrides go into @layer xds-theme — above StyleX layers
+ // so themes can intentionally restyle components.
+ if (component) {
+ const compStyle = document.createElement('style');
+ compStyle.setAttribute('data-xds-theme', theme.name);
+ compStyle.setAttribute('data-xds-id', id);
+ compStyle.textContent = `@layer xds-theme {\n${component}\n}`;
+ document.head.appendChild(compStyle);
+ }
+
injectedThemes.add(themeKey);
return () => {
- const existing = document.querySelector(
+ // Remove both prose and component style tags
+ const proseEl = document.querySelector(
+ `style[data-xds-theme-prose="${theme.name}"][data-xds-id="${id}"]`,
+ );
+ const compEl = document.querySelector(
`style[data-xds-theme="${theme.name}"][data-xds-id="${id}"]`,
);
- if (existing) {
- existing.remove();
- injectedThemes.delete(themeKey);
- }
+ proseEl?.remove();
+ compEl?.remove();
+ injectedThemes.delete(themeKey);
};
}, [theme, id]);
}
diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.ts
index 36cdba834a..ba77f538e5 100644
--- a/packages/core/src/theme/defineTheme.test.ts
+++ b/packages/core/src/theme/defineTheme.test.ts
@@ -1,5 +1,10 @@
import {describe, it, expect, vi} from 'vitest';
-import {defineTheme, generateThemeCSS, isDefinedTheme} from './defineTheme';
+import {
+ defineTheme,
+ generateThemeCSS,
+ generateThemeCSSFlat,
+ isDefinedTheme,
+} from './defineTheme';
describe('defineTheme', () => {
it('creates a theme with name', () => {
@@ -93,7 +98,7 @@ describe('generateThemeCSS', () => {
'--radius-container': '16px',
},
});
- const css = generateThemeCSS(theme);
+ const css = generateThemeCSSFlat(theme);
expect(css).toContain('@scope');
expect(css).toContain('--color-accent: light-dark(#0077B6, #48CAE4)');
expect(css).toContain('--radius-container: 16px');
@@ -103,11 +108,32 @@ describe('generateThemeCSS', () => {
it('includes prose rules even with no overrides', () => {
const theme = defineTheme({name: 'empty'});
- const css = generateThemeCSS(theme);
+ const css = generateThemeCSSFlat(theme);
expect(css).toContain('@scope');
- expect(css).toContain(':is(h1, h2, h3, h4, h5, h6)');
+ expect(css).toContain(':where(h1, h2, h3, h4, h5, h6)');
expect(css).toContain('font-family: var(--font-family-heading)');
});
+
+ it('splits prose into reset layer and components into xds-theme', () => {
+ const theme = defineTheme({
+ name: 'split-test',
+ components: {
+ button: {'variant:secondary': {backgroundColor: 'red'}},
+ },
+ });
+ const {prose, component} = generateThemeCSS(theme);
+ // Prose block should contain element defaults
+ expect(prose).toContain(':where(p)');
+ expect(prose).toContain(':where(h1, h2, h3, h4, h5, h6)');
+ expect(prose).toContain('@scope');
+ // Prose should NOT contain component overrides
+ expect(prose).not.toContain('.xds-button');
+ // Component block should contain overrides
+ expect(component).toContain('.xds-button');
+ expect(component).toContain('@scope');
+ // Component should NOT contain prose element rules
+ expect(component).not.toContain(':where(p)');
+ });
});
describe('isDefinedTheme', () => {
@@ -164,7 +190,7 @@ describe('generateThemeCSS with components', () => {
},
},
});
- const css = generateThemeCSS(theme);
+ const css = generateThemeCSSFlat(theme);
expect(css).toContain('.xds-card {');
expect(css).toContain('border-width: 2px');
expect(css).toContain('border-color: var(--color-accent)');
@@ -183,7 +209,7 @@ describe('generateThemeCSS with components', () => {
},
},
});
- const css = generateThemeCSS(theme);
+ const css = generateThemeCSSFlat(theme);
expect(css).toContain('.xds-button.secondary');
expect(css).toContain('background-color: rgba(0,0,0,0.06)');
});
@@ -199,7 +225,7 @@ describe('generateThemeCSS with components', () => {
},
},
});
- const css = generateThemeCSS(theme);
+ const css = generateThemeCSSFlat(theme);
expect(css).toContain('.xds-button.destructive.sm');
expect(css).toContain('padding: 2px 6px');
});
@@ -213,7 +239,7 @@ describe('generateThemeCSS with components', () => {
},
},
});
- const css = generateThemeCSS(theme);
+ const css = generateThemeCSSFlat(theme);
expect(css).toContain('font-family: "Playfair Display", serif');
expect(css).not.toContain('fontFamily');
});
@@ -226,7 +252,7 @@ describe('generateThemeCSS with components', () => {
card: {base: {borderWidth: '1px'}},
},
});
- const css = generateThemeCSS(theme);
+ const css = generateThemeCSSFlat(theme);
expect(css).toContain('@scope');
expect(css).toContain('--radius-container: 20px');
expect(css).toContain('.xds-card {');
@@ -460,7 +486,7 @@ describe('custom status via components', () => {
},
},
});
- const css = generateThemeCSS(theme);
+ const css = generateThemeCSSFlat(theme);
// parseStyleKey('status:neutral') → '.neutral', so CSS should have .xds-banner.neutral
expect(css).toContain('.xds-banner.neutral');
expect(css).toContain('background-color: var(--color-background-muted)');
@@ -493,7 +519,7 @@ describe('custom status via components', () => {
},
},
});
- const css = generateThemeCSS(theme);
+ const css = generateThemeCSSFlat(theme);
expect(css).toContain('.xds-button.primary-muted');
expect(css).toContain('background-color: #ECF5FF');
});
@@ -760,7 +786,7 @@ describe('pseudo-class overrides in components', () => {
},
},
});
- const css = generateThemeCSS(theme);
+ const css = generateThemeCSSFlat(theme);
// Base rule
expect(css).toContain('.xds-radio {');
expect(css).toContain('border-color: #8F9296');
@@ -788,7 +814,7 @@ describe('pseudo-class overrides in components', () => {
},
},
});
- const css = generateThemeCSS(theme);
+ const css = generateThemeCSSFlat(theme);
expect(css).toContain('.xds-button.primary-muted {');
expect(css).toContain('background-color: #ECF5FF');
expect(css).toContain('.xds-button.primary-muted:hover {');
@@ -810,7 +836,7 @@ describe('pseudo-class overrides in components', () => {
},
},
});
- const css = generateThemeCSS(theme);
+ const css = generateThemeCSSFlat(theme);
// Should NOT emit an empty base rule
expect(css).not.toMatch(/\.xds-switch\s*\{\s*\}/);
// Should emit the pseudo rule
@@ -829,7 +855,7 @@ describe('pseudo-class overrides in components', () => {
},
},
});
- const css = generateThemeCSS(theme);
+ const css = generateThemeCSSFlat(theme);
expect(css).toContain('.xds-card {');
expect(css).toContain('border-width: 2px');
expect(css).toContain('border-color: var(--color-accent)');
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index 1328501789..7ad41d9ff5 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -601,20 +601,26 @@ export function generateThemeRules(theme: XDSDefinedTheme): string[] {
}
// 3. Prose HTML element rules (h1-h6, p, small, code, hr)
- parts.push(` :is(h1, h2, h3, h4, h5, h6) {
+ //
+ // Default styles for bare HTML elements inside a themed scope.
+ // Wrapped in :where() for zero specificity — these are defaults that
+ // any class-based style (StyleX, .xds-* overrides) should beat.
+ // The caller places these in the reset layer (not xds-theme) so they
+ // sit below all component styles in the cascade.
+ parts.push(` :where(h1, h2, h3, h4, h5, h6) {
font-family: var(--font-family-heading);
color: var(--color-text-primary);
}`);
for (let level = 1; level <= 6; level++) {
- parts.push(` h${level} {
+ parts.push(` :where(h${level}) {
font-size: ${val(`--text-heading-${level}-size`)};
font-weight: ${val(`--text-heading-${level}-weight`)};
line-height: ${val(`--text-heading-${level}-leading`)};
}`);
}
- parts.push(` p {
+ parts.push(` :where(p) {
font-family: var(--font-family-heading);
font-size: ${val('--text-body-size')};
font-weight: ${val('--text-body-weight')};
@@ -622,20 +628,20 @@ export function generateThemeRules(theme: XDSDefinedTheme): string[] {
color: var(--color-text-primary);
}`);
- parts.push(` small {
+ parts.push(` :where(small) {
font-size: ${val('--text-supporting-size')};
font-weight: ${val('--text-supporting-weight')};
line-height: ${val('--text-supporting-leading')};
color: var(--color-text-secondary);
}`);
- parts.push(` code, pre {
+ parts.push(` :where(code, pre) {
font-family: var(--font-family-code);
font-size: ${val('--text-code-size')};
line-height: ${val('--text-code-leading')};
}`);
- parts.push(` hr {
+ parts.push(` :where(hr) {
border: none;
border-top: 1px solid var(--color-border);
}`);
@@ -671,11 +677,113 @@ export function generateThemeRules(theme: XDSDefinedTheme): string[] {
return parts;
}
+/**
+ * Structured output from generateThemeRulesSplit.
+ * Separates prose element defaults from component/token overrides
+ * so callers can place them in different CSS layers.
+ */
+export interface ThemeRulesSplit {
+ /** Token overrides + component .xds-* overrides + prop-level color rules */
+ component: string[];
+ /** Prose element defaults (h1-h6, p, small, code, hr) — belongs in reset layer */
+ prose: string[];
+}
+
+/**
+ * Generate theme rules split into component and prose groups.
+ *
+ * Prose element rules (h1-h6, p, small, code, hr) style bare HTML elements
+ * as themed defaults — conceptually the same tier as the CSS reset. They
+ * belong in the reset layer so any class-based style wins.
+ *
+ * Component rules (tokens, .xds-* overrides) are intentional theme overrides
+ * that need to beat StyleX — they stay in xds-theme (above StyleX layers).
+ */
+export function generateThemeRulesSplit(
+ theme: XDSDefinedTheme,
+): ThemeRulesSplit {
+ const allRules = generateThemeRules(theme);
+
+ const prose: string[] = [];
+ const component: string[] = [];
+
+ for (const rule of allRules) {
+ if (rule.trimStart().startsWith(':where(')) {
+ prose.push(rule);
+ } else {
+ component.push(rule);
+ }
+ }
+
+ return {component, prose};
+}
+
/**
* Generate the full CSS string for a theme — runtime path.
- * Wraps rules in @scope (no @layer — runtime injects into <style> tag).
+ *
+ * Produces two layer blocks:
+ * - `@layer reset`: Prose element defaults (p, h1-h6, small, code, hr) scoped
+ * to the theme. These sit at reset-layer priority so any class-based style
+ * (StyleX, .xds-* overrides) wins. Uses :where() for zero specificity.
+ * - Unlayered: Token overrides + component .xds-* overrides. The caller
+ * (XDSTheme.tsx) wraps this in @layer xds-theme, which sits above StyleX
+ * layers so theme component overrides take effect.
+ */
+/**
+ * Output from generateThemeCSS — two CSS blocks for different layers.
+ */
+export interface ThemeCSSOutput {
+ /**
+ * Prose element defaults (p, h1-h6, small, code, hr) scoped to the theme.
+ * Should be injected into @layer reset — lowest priority, any class wins.
+ * Empty string if no prose rules.
+ */
+ prose: string;
+ /**
+ * Token overrides + component .xds-* overrides scoped to the theme.
+ * Should be injected into @layer xds-theme — above StyleX layers so
+ * theme component overrides take effect. Empty string if no rules.
+ */
+ component: string;
+}
+
+/**
+ * Generate layered CSS for a theme — runtime path.
+ *
+ * Returns two CSS blocks for injection into different layers:
+ * - `prose`: @scope'd element defaults → inject into @layer reset
+ * - `component`: @scope'd token + .xds-* overrides → inject into @layer xds-theme
+ *
+ * This separation ensures prose defaults (what bare HTML looks like in a theme)
+ * sit at reset-layer priority where any class-based style wins, while component
+ * overrides sit above StyleX so themes can restyle components intentionally.
+ */
+export function generateThemeCSS(theme: XDSDefinedTheme): ThemeCSSOutput {
+ const {component, prose} = generateThemeRulesSplit(theme);
+ const scopeSelector = `[data-xds-theme="${theme.name}"]`;
+ const scopeTo = `[data-xds-theme]`;
+
+ let proseCss = '';
+ if (prose.length > 0) {
+ const proseInner = prose.join('\n\n');
+ proseCss = `@scope (${scopeSelector}) to (${scopeTo}) {\n${proseInner}\n}`;
+ }
+
+ let componentCss = '';
+ if (component.length > 0) {
+ const componentInner = component.join('\n\n');
+ componentCss = `@scope (${scopeSelector}) to (${scopeTo}) {\n${componentInner}\n}`;
+ }
+
+ return {prose: proseCss, component: componentCss};
+}
+
+/**
+ * Generate the full CSS string for a theme as a single string.
+ * @deprecated Use generateThemeCSS() which returns { prose, component } for proper layering.
+ * This flat version is kept for backwards compatibility with tests and simple cases.
*/
-export function generateThemeCSS(theme: XDSDefinedTheme): string {
+export function generateThemeCSSFlat(theme: XDSDefinedTheme): string {
const rules = generateThemeRules(theme);
if (rules.length === 0) return '';
const scopeSelector = `[data-xds-theme="${theme.name}"]`;
diff --git a/packages/core/src/theme/generateThemeRules.test.ts b/packages/core/src/theme/generateThemeRules.test.ts
index 4a598ee076..1ac3be51cc 100644
--- a/packages/core/src/theme/generateThemeRules.test.ts
+++ b/packages/core/src/theme/generateThemeRules.test.ts
@@ -126,7 +126,7 @@ describe('generateThemeRules', () => {
it('includes prose heading rules with computed values', () => {
const h1Rule = rules.find(
- r => r.trimStart().startsWith('h1 {') || r.includes('\n h1 {'),
+ r => r.trimStart().startsWith(':where(h1)') || r.includes(':where(h1)'),
);
expect(h1Rule).toBeDefined();
// Prose rules use val() helper which resolves to the token value (now a var ref)
@@ -136,7 +136,7 @@ describe('generateThemeRules', () => {
it('includes prose p rule with computed values', () => {
const pRule = rules.find(
- r => r.trimStart().startsWith('p {') || r.includes('\n p {'),
+ r => r.trimStart().startsWith(':where(p)') || r.includes(':where(p)'),
);
expect(pRule).toBeDefined();
expect(pRule).toContain('var(--font-size-base)');
@@ -144,9 +144,9 @@ describe('generateThemeRules', () => {
});
it('includes prose small, code, hr rules', () => {
- expect(rules.some(r => r.includes('small {'))).toBe(true);
- expect(rules.some(r => r.includes('code, pre {'))).toBe(true);
- expect(rules.some(r => r.includes('hr {'))).toBe(true);
+ expect(rules.some(r => r.includes(':where(small)'))).toBe(true);
+ expect(rules.some(r => r.includes(':where(code, pre)'))).toBe(true);
+ expect(rules.some(r => r.includes(':where(hr)'))).toBe(true);
});
// --- Prop-level color overrides ---
@@ -161,13 +161,14 @@ describe('generateThemeRules', () => {
// --- Consistency ---
- it('generateThemeCSS wraps rules in @scope', () => {
- const css = generateThemeCSS(theme);
- expect(css).toContain('@scope ([data-xds-theme="default"])');
- expect(css).toContain('to ([data-xds-theme])');
- // Every rule from generateThemeRules should appear in generateThemeCSS
+ it('generateThemeCSS returns prose and component blocks with @scope', () => {
+ const {prose, component} = generateThemeCSS(theme);
+ const combined = prose + component;
+ expect(combined).toContain('@scope ([data-xds-theme="default"])');
+ expect(combined).toContain('to ([data-xds-theme])');
+ // Every rule from generateThemeRules should appear in one of the blocks
for (const rule of rules) {
- expect(css).toContain(rule);
+ expect(combined).toContain(rule);
}
});
});
@@ -197,7 +198,7 @@ describe('generateThemeRules with weight overrides', () => {
it('reflects weight override in prose h3', () => {
const h3Rule = rules.find(
- r => r.trimStart().startsWith('h3 {') || r.includes('\n h3 {'),
+ r => r.trimStart().startsWith(':where(h3)') || r.includes(':where(h3)'),
);
expect(h3Rule).toBeDefined();
expect(h3Rule).toContain('var(--font-weight-bold)');
diff --git a/packages/core/src/theme/index.ts b/packages/core/src/theme/index.ts
index 2e13d96080..1ca24a174a 100644
--- a/packages/core/src/theme/index.ts
+++ b/packages/core/src/theme/index.ts
@@ -17,7 +17,11 @@ export {XDSTheme} from './XDSTheme';
export {
defineTheme,
generateThemeCSS,
+ generateThemeCSSFlat,
generateThemeRules,
+ generateThemeRulesSplit,
+ type ThemeCSSOutput,
+ type ThemeRulesSplit,
isDefinedTheme,
xdsTokenDefaults,
} from './defineTheme';