Skip to content

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

TypeScript

refactor: shared theme CSS generation + remove XDSFontWrapper (#665)

Cindy Zhangd23fbf4c9e73
diff --git a/apps/example-nextjs-tailwind/src/app/globals.css b/apps/example-nextjs-tailwind/src/app/globals.css
index 428ed6b3ed..ee1eb28f6a 100644
--- a/apps/example-nextjs-tailwind/src/app/globals.css
+++ b/apps/example-nextjs-tailwind/src/app/globals.css
@@ -1,5 +1,4 @@
@import "tailwindcss";
@import "@xds/core/reset.css";
-@import "@xds/core/typography.css";
@import "@xds/core/xds.css";
@import "@xds/theme-default/theme.css";
diff --git a/apps/example-nextjs/src/app/layout.tsx b/apps/example-nextjs/src/app/layout.tsx
index 9736981013..5a05df40c3 100644
--- a/apps/example-nextjs/src/app/layout.tsx
+++ b/apps/example-nextjs/src/app/layout.tsx
@@ -1,6 +1,5 @@
import type {Metadata} from 'next';
import '@xds/core/reset.css';
-import '@xds/core/typography.css';
import '@xds/theme-default/theme.css';
import './globals.css';
import {Providers} from './providers';
diff --git a/apps/example-vite/src/main.tsx b/apps/example-vite/src/main.tsx
index c528e506d9..641303704b 100644
--- a/apps/example-vite/src/main.tsx
+++ b/apps/example-vite/src/main.tsx
@@ -1,7 +1,6 @@
import {StrictMode} from 'react';
import {createRoot} from 'react-dom/client';
import '@xds/core/reset.css';
-import '@xds/core/typography.css';
import '@xds/theme-default/theme.css';
import './index.css';
import App from './App';
diff --git a/apps/sandbox/src/app/layout.tsx b/apps/sandbox/src/app/layout.tsx
index ae74431294..f324d4fde1 100644
--- a/apps/sandbox/src/app/layout.tsx
+++ b/apps/sandbox/src/app/layout.tsx
@@ -1,6 +1,5 @@
import type {Metadata} from 'next';
import '@xds/core/reset.css';
-import '@xds/core/typography.css';
import '@xds/core/xds.css';
import '@xds/theme-default/theme.css';
import {Providers} from './providers';
diff --git a/apps/storybook/.storybook/preview.tsx b/apps/storybook/.storybook/preview.tsx
index 0509e3e459..6a43ce8948 100644
--- a/apps/storybook/.storybook/preview.tsx
+++ b/apps/storybook/.storybook/preview.tsx
@@ -7,11 +7,7 @@ import {brutalistTheme} from '@xds/theme-brutalist';
// Import the base reset and typography stylesheets
import '@xds/core/reset.css';
-import '@xds/core/typography.css';
-// Import the pre-built StyleX CSS from the core package
-// Use relative path since @xds/core alias points to source, not dist
-import '../../../packages/core/dist/index.css';
/**
* Map of available themes
diff --git a/apps/storybook/stories/FontWrapper.stories.tsx b/apps/storybook/stories/FontWrapper.stories.tsx
deleted file mode 100644
index 81741f14d0..0000000000
--- a/apps/storybook/stories/FontWrapper.stories.tsx
+++ /dev/null
@@ -1,129 +0,0 @@
-import type {Meta, StoryObj} from '@storybook/react';
-import {XDSFontWrapper} from '@xds/core/Text';
-import {XDSText} from '@xds/core/Text';
-
-const meta: Meta<typeof XDSFontWrapper> = {
- title: 'Typography/XDSFontWrapper',
- component: XDSFontWrapper,
- tags: ['autodocs'],
-};
-
-export default meta;
-type Story = StoryObj<typeof XDSFontWrapper>;
-
-// =============================================================================
-// Basic Usage
-// =============================================================================
-
-export const Default: Story = {
- render: () => (
- <XDSFontWrapper>
- <h1>Heading 1 (24px)</h1>
- <h2>Heading 2 (20px)</h2>
- <h3>Heading 3 (17px)</h3>
- <h4>Heading 4 (14px — base)</h4>
- <h5>Heading 5 (12px)</h5>
- <h6>Heading 6 (10px)</h6>
- <p>
- Body text with <strong>bold</strong> and <em>italic</em> styles.
- Typography sizing is controlled by the theme's type scale tokens.
- </p>
- </XDSFontWrapper>
- ),
-};
-
-// =============================================================================
-// Prose Content
-// =============================================================================
-
-export const ProseContent: Story = {
- render: () => (
- <div style={{maxWidth: '600px'}}>
- <XDSFontWrapper>
- <h1>The Art of Typography</h1>
- <p>
- Good typography is invisible. It creates a seamless reading experience
- that guides users through content without friction. The type scale
- establishes visual hierarchy — each heading level has a deliberate
- size relationship to the next.
- </p>
- <h2>Hierarchy Through Scale</h2>
- <p>
- XDS uses a ratio-based type scale (base=14px, ratio=1.2) where each
- step is a geometric progression from the base size. This creates
- natural visual harmony between heading levels.
- </p>
- <blockquote>
- <p>
- "The details are not the details. They make the design." — Charles
- Eames
- </p>
- </blockquote>
- <h3>Lists and Structure</h3>
- <p>Key principles:</p>
- <ul>
- <li>h4 anchors to the base font size (14px)</li>
- <li>Headings above h4 scale up by the ratio</li>
- <li>Headings below h4 scale down by the ratio</li>
- <li>Line heights snap to a 4px grid</li>
- </ul>
- <h3>Code Examples</h3>
- <p>
- Inline <code>code</code> uses a monospace font at 0.9em. Block code
- uses the supporting text size:
- </p>
- <pre>
- <code>
- {`const theme = defineTheme({
- name: 'custom',
- typeScale: { base: 16, ratio: 1.25 },
-});`}
- </code>
- </pre>
- <hr />
- <p>
- For different density regions, nest <code>&lt;XDSTheme&gt;</code> with
- a different <code>typeScale</code> configuration.
- </p>
- </XDSFontWrapper>
- </div>
- ),
-};
-
-// =============================================================================
-// Markdown Rendering
-// =============================================================================
-
-export const MarkdownRendering: Story = {
- render: () => (
- <div style={{maxWidth: '600px'}}>
- <XDSText type="supporting" display="block" color="secondary">
- XDSFontWrapper is ideal for rendering markdown or CMS content where you
- don't control the HTML structure.
- </XDSText>
- <div style={{marginTop: '16px'}}>
- <XDSFontWrapper>
- <h2>Getting Started</h2>
- <p>Follow these steps to set up your project:</p>
- <ol>
- <li>Install the dependencies</li>
- <li>Configure the theme</li>
- <li>Wrap your app in XDSTheme</li>
- </ol>
- <h3>Installation</h3>
- <pre>
- <code>npm install @xds/core @xds/theme-default</code>
- </pre>
- <h3>Configuration</h3>
- <p>
- Import the theme and wrap your app. Typography will automatically
- use the theme's type scale tokens for consistent sizing.
- </p>
- <p>
- <a href="#">Read the full documentation →</a>
- </p>
- </XDSFontWrapper>
- </div>
- </div>
- ),
-};
diff --git a/apps/storybook/stories/ThemeEditor.stories.tsx b/apps/storybook/stories/ThemeEditor.stories.tsx
index 77d2bbb849..22c9920500 100644
--- a/apps/storybook/stories/ThemeEditor.stories.tsx
+++ b/apps/storybook/stories/ThemeEditor.stories.tsx
@@ -22,7 +22,6 @@ import {XDSTable} from '@xds/core/Table';
import type {XDSTableColumn} from '@xds/core/Table';
import {XDSDivider} from '@xds/core/Divider';
import {XDSTheme, defineTheme, expandTypeScale} from '@xds/core/theme';
-import {XDSFontWrapper} from '@xds/core/Text';
import {
colorDefaults,
spacingDefaults,
diff --git a/packages/cli/src/commands/build-theme.mjs b/packages/cli/src/commands/build-theme.mjs
index e6864e4cb8..6b1ada0b9d 100644
--- a/packages/cli/src/commands/build-theme.mjs
+++ b/packages/cli/src/commands/build-theme.mjs
@@ -12,6 +12,20 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
+import {createRequire} from 'node:module';
+
+// Import shared theme processing from core — ensures build and runtime
+// use the same logic for typeScale expansion, prose, and component rules.
+const _require = createRequire(import.meta.url);
+let _defineTheme = null;
+let _generateThemeRules = null;
+try {
+ const coreTheme = _require('@xds/core/theme');
+ _defineTheme = coreTheme.defineTheme;
+ _generateThemeRules = coreTheme.generateThemeRules;
+} catch {
+ // Core not available — fall back to legacy generation
+}
/**
* Convert camelCase CSS property to kebab-case
@@ -634,36 +648,49 @@ export function registerTheme(program) {
console.warn(` ⚠ ${w}`);
}
- // Generate CSS
- const noProse = options.prose === false;
- const scopeBlocks = [];
-
- // Prose defaults first — baseline HTML element styles from tokens.
- // These come before component overrides so overrides win by source order.
- if (!noProse) {
+ // Generate CSS using the shared generateThemeRules from core.
+ // This ensures build and runtime produce identical rule sets.
+ let css;
+ if (_defineTheme && _generateThemeRules) {
+ // Shared path: run through defineTheme (expands typeScale, merges
+ // components) then generateThemeRules with computedValues for
+ // self-contained CSS output.
+ const resolvedTheme = _defineTheme({
+ name: themeDef.name,
+ typeScale: themeDef.typeScale,
+ 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`;
+ } else {
+ // Legacy fallback when core isn't built yet
+ const scopeBlocks = [];
const proseCss = generateProseCSS(themeDef);
if (proseCss) scopeBlocks.push(proseCss);
+ const mainCss = generateCSS(themeDef);
+ if (mainCss) scopeBlocks.push(mainCss);
+ if (scopeBlocks.length === 0) {
+ console.log('No overrides found — nothing to build.');
+ return;
+ }
+ const joined = scopeBlocks.join('\n\n');
+ const colorSchemeDecl = joined.includes('light-dark(')
+ ? ' :root { color-scheme: light dark; }\n\n'
+ : '';
+ css = `@layer xds.theme {\n${colorSchemeDecl}${joined}\n}\n`;
}
- // Tokens + component overrides (with prose co-selection) come after
- const mainCss = generateCSS(themeDef, {prose: !noProse});
- if (mainCss) scopeBlocks.push(mainCss);
-
- if (scopeBlocks.length === 0) {
- console.log('No overrides found — nothing to build.');
- return;
- }
-
- // If any scope block uses light-dark(), include a color-scheme declaration
- // so that CSS tools that lower light-dark() (e.g. LightningCSS) can inject
- // their polyfill toggle variables in the same file. Without this, the
- // polyfill vars are used but never defined, silently breaking all colors.
- const joined = scopeBlocks.join('\n\n');
- const colorSchemeDecl = joined.includes('light-dark(')
- ? ' :root { color-scheme: light dark; }\n\n'
- : '';
- const css = `@layer xds.theme {\n${colorSchemeDecl}${joined}\n}\n`;
-
// Determine output path
const outPath = options.out
? path.resolve(process.cwd(), options.out)
diff --git a/packages/core/package.json b/packages/core/package.json
index 541fa6b20d..af71e0150c 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -20,7 +20,6 @@
"require": "./dist/index.js"
},
"./reset.css": "./src/reset.css",
- "./typography.css": "./src/typography.css",
"./xds.css": "./dist/xds.css",
"./theme/tokens.stylex": {
"source": "./src/theme/tokens.stylex.ts",
@@ -421,4 +420,4 @@
"esbuild-plugin-babel": "^0.2.3",
"@stylexjs/stylex": "^0.17.4"
}
-}
+}
\ No newline at end of file
diff --git a/packages/core/src/Text/Text.doc.mjs b/packages/core/src/Text/Text.doc.mjs
index 986095186a..7ed36f6163 100644
--- a/packages/core/src/Text/Text.doc.mjs
+++ b/packages/core/src/Text/Text.doc.mjs
@@ -23,9 +23,9 @@ export const docs = {
},
{
label: 'Font wrapper for native HTML',
- code: `<XDSFontWrapper>
+ code: `<div className="xds-typography">
<article dangerouslySetInnerHTML={{__html: markdownContent}} />
-</XDSFontWrapper>`,
+</div>`,
},
],
features: [
@@ -33,8 +33,6 @@ export const docs = {
'Headings use native h1–h6 elements with optional aria-level override for decoupled visual vs document hierarchy',
'Line-clamp truncation with automatic overflow-detecting tooltip',
'Optical alignment (text-box-trim / capsize) for precise vertical rhythm',
- 'XDSFontWrapper applies typography styles to native HTML — useful for user-generated content and markdown output',
- 'useXDSFontWrapperStyles hook for programmatic StyleX access to heading and prose styles',
'Tabular number support for aligned numeric data',
'All typography driven by CSS custom properties — fully themeable per-component',
],
@@ -282,46 +280,6 @@ export const docs = {
},
],
},
- {
- name: 'XDSFontWrapper',
- description:
- 'Wrapper that applies XDS typography styles to native HTML elements within its scope. Useful for user-generated content, markdown output, and other scenarios where XDSText and XDSHeading cannot be used directly.',
- examples: [
-
- ],
- props: [
- {
- name: 'children',
- type: 'ReactNode',
- description: 'Content to style with XDS typography.',
- required: true,
- },
- ],
- },
- {
- name: 'useXDSFontWrapperStyles',
- description:
- 'Hook that returns StyleX style objects from the current theme for headings and prose elements, for use when applying typography styles to native HTML programmatically.',
- examples: [
- {
- label: 'Basic usage',
- code: `import {useXDSFontWrapperStyles} from '@xds/core';
-import * as stylex from '@stylexjs/stylex';
-
-function Article() {
- const {headingStyles, proseStyles} = useXDSFontWrapperStyles();
-
- return (
- <article>
- <h1 {...stylex.props(headingStyles?.h1)}>Title</h1>
- <p {...stylex.props(proseStyles?.p)}>Content...</p>
- </article>
- );
-}`,
- },
- ],
- props: [],
- },
],
};
@@ -353,9 +311,9 @@ export const docsZh = {
},
{
label: '原生 HTML 字体包装器',
- code: `<XDSFontWrapper>
+ code: `<div className="xds-typography">
<article dangerouslySetInnerHTML={{__html: markdownContent}} />
-</XDSFontWrapper>`,
+</div>`,
},
],
features: [
@@ -363,8 +321,6 @@ export const docsZh = {
'标题使用原生 h1–h6 元素,支持可选的 aria-level 覆盖,实现视觉层级与文档层级的解耦',
'行截断,带自动溢出检测工具提示',
'光学对齐(text-box-trim / capsize),实现精确的垂直节奏',
- 'XDSFontWrapper 将排版样式应用于原生 HTML — 适用于用户生成内容和 Markdown 输出',
- 'useXDSFontWrapperStyles hook 用于以编程方式通过 StyleX 访问标题和散文样式',
'表格数字支持,用于对齐的数值数据',
'所有排版由 CSS 自定义属性驱动 — 每个组件均可完全主题化',
],
@@ -616,62 +572,6 @@ export const docsZh = {
},
],
},
- {
- name: 'XDSFontWrapper',
- description:
- '将 XDS 排版样式应用于其作用域内原生 HTML 元素的包装器。适用于用户生成内容、Markdown 输出以及无法直接使用 XDSText 和 XDSHeading 的其他场景。',
- examples: [
- {
- label: '默认变体',
- code: `<XDSFontWrapper>
- <h1>Page Title</h1>
- <p>Body text with <strong>bold</strong> and <em>italic</em>.</p>
- <ul>
- <li>List item 1</li>
- <li>List item 2</li>
- </ul>
-</XDSFontWrapper>`,
- },
- {
- label: '编辑风格变体',
- code: `<XDSFontWrapper>
- <article dangerouslySetInnerHTML={{__html: markdownContent}} />
-</XDSFontWrapper>`,
- },
- ],
- props: [
- {
- name: 'children',
- type: 'ReactNode',
- description: '要应用 XDS 排版样式的内容。',
- required: true,
- },
- ],
- },
- {
- name: 'useXDSFontWrapperStyles',
- description:
- '返回当前主题中标题和散文元素的 StyleX 样式对象的 Hook,用于以编程方式将排版样式应用于原生 HTML。',
- examples: [
- {
- label: '基础用法',
- code: `import {useXDSFontWrapperStyles} from '@xds/core';
-import * as stylex from '@stylexjs/stylex';
-
-function Article() {
- const {headingStyles, proseStyles} = useXDSFontWrapperStyles();
-
- return (
- <article>
- <h1 {...stylex.props(headingStyles?.h1)}>Title</h1>
- <p {...stylex.props(proseStyles?.p)}>Content...</p>
- </article>
- );
-}`,
- },
- ],
- props: [],
- },
],
};
@@ -683,8 +583,6 @@ export const docsDense = {
'Headings use native h1\u20136 w/ optional aria-level override for decoupled visual vs document hierarchy',
'Line-clamp truncation w/ automatic overflow-detecting tooltip',
'Optical alignment (text-box-trim / capsize) for precise vertical rhythm',
- 'XDSFontWrapper applies typography styles to native HTML; useful for UGC + markdown output',
- 'useXDSFontWrapperStyles hook for programmatic StyleX access to heading + prose styles',
'Tabular number support for aligned numeric data',
'All typography driven by CSS custom properties; fully themeable per-component',
],
@@ -735,17 +633,5 @@ export const docsDense = {
id: 'HTML id attribute.',
},
},
- {
- name: 'XDSFontWrapper',
- description: 'Wrapper applying XDS typography to native HTML scope; for UGC, markdown, cases where XDSText/XDSHeading cannot be used directly.',
- propDescriptions: {
- children: 'Content to style w/ XDS typography.',
-
- },
- },
- {
- name: 'useXDSFontWrapperStyles',
- description: 'Hook returning StyleX style objects for headings + prose from current theme, for programmatic typography on native HTML.',
- },
],
};
\ No newline at end of file
diff --git a/packages/core/src/Text/XDSFontWrapper.test.tsx b/packages/core/src/Text/XDSFontWrapper.test.tsx
deleted file mode 100644
index 10fc3c2864..0000000000
--- a/packages/core/src/Text/XDSFontWrapper.test.tsx
+++ /dev/null
@@ -1,85 +0,0 @@
-/**
- * @file XDSFontWrapper.test.tsx
- * @input Uses Vitest, React Testing Library
- * @output Tests for XDSFontWrapper component
- */
-
-import {describe, it, expect} from 'vitest';
-import {render, screen} from '@testing-library/react';
-import {XDSFontWrapper} from './XDSFontWrapper';
-
-describe('XDSFontWrapper', () => {
- it('renders children', () => {
- render(
- <XDSFontWrapper>
- <h1>Test Heading</h1>
- <p>Test paragraph</p>
- </XDSFontWrapper>,
- );
-
- expect(screen.getByText('Test Heading')).toBeInTheDocument();
- expect(screen.getByText('Test paragraph')).toBeInTheDocument();
- });
-
- it('applies typography class', () => {
- render(
- <XDSFontWrapper data-testid="wrapper">
- <p>Content</p>
- </XDSFontWrapper>,
- );
-
- const wrapper = screen.getByTestId('wrapper');
- expect(wrapper).toBeInTheDocument();
- expect(wrapper).toHaveClass('xds-typography');
- });
-
- it('does not include variant classes', () => {
- render(
- <XDSFontWrapper data-testid="wrapper">
- <p>Content</p>
- </XDSFontWrapper>,
- );
-
- const wrapper = screen.getByTestId('wrapper');
- expect(wrapper.className).not.toContain('--default');
- expect(wrapper.className).not.toContain('--editorial');
- });
-
- it('renders all prose elements', () => {
- render(
- <XDSFontWrapper>
- <h1>Heading 1</h1>
- <h2>Heading 2</h2>
- <h3>Heading 3</h3>
- <h4>Heading 4</h4>
- <h5>Heading 5</h5>
- <h6>Heading 6</h6>
- <p>Paragraph</p>
- <ul>
- <li>List item</li>
- </ul>
- <ol>
- <li>Ordered item</li>
- </ol>
- <blockquote>Quote</blockquote>
- <pre>
- <code>code block</code>
- </pre>
- <hr />
- </XDSFontWrapper>,
- );
-
- expect(screen.getByRole('heading', {level: 1})).toBeInTheDocument();
- expect(screen.getByRole('heading', {level: 2})).toBeInTheDocument();
- expect(screen.getByRole('heading', {level: 3})).toBeInTheDocument();
- expect(screen.getByRole('heading', {level: 4})).toBeInTheDocument();
- expect(screen.getByRole('heading', {level: 5})).toBeInTheDocument();
- expect(screen.getByRole('heading', {level: 6})).toBeInTheDocument();
- expect(screen.getByText('Paragraph')).toBeInTheDocument();
- expect(screen.getByText('List item')).toBeInTheDocument();
- expect(screen.getByText('Ordered item')).toBeInTheDocument();
- expect(screen.getByText('Quote')).toBeInTheDocument();
- expect(screen.getByText('code block')).toBeInTheDocument();
- expect(screen.getByRole('separator')).toBeInTheDocument();
- });
-});
diff --git a/packages/core/src/Text/XDSFontWrapper.tsx b/packages/core/src/Text/XDSFontWrapper.tsx
deleted file mode 100644
index f7a57152b4..0000000000
--- a/packages/core/src/Text/XDSFontWrapper.tsx
+++ /dev/null
@@ -1,84 +0,0 @@
-/**
- * @file XDSFontWrapper.tsx
- * @input Uses React, typography.css
- * @output Exports XDSFontWrapper component
- * @position Typography component; provides prose styles for wrapped HTML content
- *
- * XDSFontWrapper applies base typography styles to native HTML elements
- * (h1-h6, p, ul, ol, blockquote, code, etc.) within its scope. Sizing is
- * driven by type scale tokens set by the theme's typeScale configuration.
- *
- * For different density regions, nest <XDSTheme> with a different typeScale
- * rather than using a variant prop.
- *
- * SYNC: When modified, update:
- * - /packages/core/src/Text/Text.doc.mjs
- * - /packages/core/src/Text/index.ts
- */
-
-import * as React from 'react';
-import '../typography.css';
-
-/**
- * Props for XDSFontWrapper
- */
-export interface XDSFontWrapperProps {
- /**
- * Children to render
- */
- children: React.ReactNode;
-
- /**
- * Test ID for testing
- */
- 'data-testid'?: string;
-}
-
-/**
- * XDSFontWrapper
- *
- * Applies base typography styles to native HTML elements within its scope.
- * Uses typography.css which references theme CSS custom properties (type scale tokens).
- *
- * Typography sizing is controlled by the theme's `typeScale` configuration.
- * For mixed density regions, nest a `<XDSTheme>` with a different `typeScale`
- * instead of using a variant prop.
- *
- * @example
- * ```
- * <XDSFontWrapper>
- * <h1>Page Title</h1>
- * <p>Body text with <strong>bold</strong> and <em>italic</em>.</p>
- * <ul>
- * <li>List item 1</li>
- * <li>List item 2</li>
- * </ul>
- * </XDSFontWrapper>
- * ```
- */
-export function XDSFontWrapper({
- children,
- 'data-testid': testId,
-}: XDSFontWrapperProps): React.ReactElement {
- return (
- <div className="xds-typography" data-testid={testId}>
- {children}
- </div>
- );
-}
-
-XDSFontWrapper.displayName = 'XDSFontWrapper';
-
-/**
- * Hook to access font wrapper styles from the current theme.
- *
- * @deprecated Theme component styles are now applied via CSS classes.
- * Use the `.xds-typography` class instead of reading styles from context.
- */
-export function useXDSFontWrapperStyles() {
- return {
- base: undefined,
- headingStyles: undefined,
- proseStyles: undefined,
- };
-}
diff --git a/packages/core/src/Text/XDSHeading.tsx b/packages/core/src/Text/XDSHeading.tsx
index 82e1a76597..db55738cc0 100644
--- a/packages/core/src/Text/XDSHeading.tsx
+++ b/packages/core/src/Text/XDSHeading.tsx
@@ -247,7 +247,7 @@ export function XDSHeading({
<Component
ref={mergedRef}
{...mergeProps(
- xdsClassName('heading', {level}),
+ xdsClassName('heading', {level, color}),
stylex.props(
colorStyles[color],
// Display: use truncation styles when maxLines > 0
diff --git a/packages/core/src/Text/XDSText.tsx b/packages/core/src/Text/XDSText.tsx
index fd8d2988d8..736c36bd67 100644
--- a/packages/core/src/Text/XDSText.tsx
+++ b/packages/core/src/Text/XDSText.tsx
@@ -258,7 +258,7 @@ export function XDSText({
<Component
ref={mergedRef}
{...mergeProps(
- xdsClassName('text', {type}),
+ xdsClassName('text', {type, color: resolvedColor}),
stylex.props(
colorStyles[resolvedColor],
weight && weightStyles[weight],
diff --git a/packages/core/src/Text/index.ts b/packages/core/src/Text/index.ts
index 5f47c2e9e0..71c458a1f2 100644
--- a/packages/core/src/Text/index.ts
+++ b/packages/core/src/Text/index.ts
@@ -14,11 +14,6 @@ export {
type XDSHeadingProps,
type XDSHeadingLevel,
} from './XDSHeading';
-export {
- XDSFontWrapper,
- useXDSFontWrapperStyles,
- type XDSFontWrapperProps,
-} from './XDSFontWrapper';
// Re-export shared types from theme for convenience
export type {
diff --git a/packages/core/src/reset.css b/packages/core/src/reset.css
index 51b3f7dcc4..d90eca4563 100644
--- a/packages/core/src/reset.css
+++ b/packages/core/src/reset.css
@@ -20,7 +20,6 @@
*
* 2. Combine with theme and typography:
* import '@xds/core/reset.css'; // @layer reset — clean slate
- * import '@xds/core/typography.css'; // @layer typography — prose styles
* import '@xds/core/xds.css'; // @layer xds.core.base — component styles
* import '@xds/theme-default/theme.css'; // @layer xds.theme — theme overrides
*
@@ -169,7 +168,7 @@
/*
* Remove default list styles, margin, and padding. Lists used for
* navigation or layout shouldn't carry prose styling by default.
- * Use typography.css or explicit styles for prose lists.
+ * Use explicit styles for prose lists.
*/
:where(ol, ul, menu) {
list-style: none;
diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.ts
index c728e5e6d1..bd5f690962 100644
--- a/packages/core/src/theme/defineTheme.test.ts
+++ b/packages/core/src/theme/defineTheme.test.ts
@@ -96,13 +96,16 @@ describe('generateThemeCSS', () => {
expect(css).toContain('@scope');
expect(css).toContain('--color-accent: light-dark(#0077B6, #48CAE4)');
expect(css).toContain('--radius-container: 16px');
- // Should NOT contain non-overridden tokens
- expect(css).not.toContain('--color-surface');
+ // :scope should NOT contain non-overridden tokens
+ expect(css).not.toContain('--color-surface:');
});
- it('returns empty string for no overrides', () => {
+ it('includes prose rules even with no overrides', () => {
const theme = defineTheme({name: 'empty'});
- expect(generateThemeCSS(theme)).toBe('');
+ const css = generateThemeCSS(theme);
+ expect(css).toContain('@scope');
+ expect(css).toContain(':is(h1, h2, h3, h4, h5, h6)');
+ expect(css).toContain('font-family: var(--font-heading)');
});
});
@@ -236,8 +239,8 @@ describe('typeScale', () => {
name: 'dense',
typeScale: {base: 12, ratio: 1.125},
});
- expect(theme.tokens['--heading-4-size']).toBe('12px');
- expect(theme.tokens['--text-body-size']).toBe('12px');
+ expect(theme.tokens['--heading-4-size']).toBe('0.75rem');
+ expect(theme.tokens['--text-body-size']).toBe('0.75rem');
});
it('generates all 33 type scale tokens', () => {
@@ -263,7 +266,7 @@ describe('typeScale', () => {
// Explicit token should win over typeScale
expect(theme.tokens['--heading-1-size']).toBe('40px');
// Non-overridden typeScale token should still be present
- expect(theme.tokens['--heading-4-size']).toBe('14px');
+ expect(theme.tokens['--heading-4-size']).toBe('0.875rem');
});
it('works without typeScale (backwards compatible)', () => {
@@ -281,7 +284,7 @@ describe('typeScale', () => {
},
});
expect(theme.tokens['--color-accent']).toBe('#FF0000');
- expect(theme.tokens['--heading-4-size']).toBe('16px');
+ expect(theme.tokens['--heading-4-size']).toBe('1rem');
});
});
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index a16d88f368..b46f4ea362 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -316,12 +316,30 @@ function toKebabCase(str: string): string {
* Generate CSS rules for a defined theme.
* Includes token overrides and component style overrides.
*/
-export function generateThemeCSS(theme: XDSDefinedTheme): string {
+/**
+ * Generate the intermediary CSS rules for a theme.
+ *
+ * Returns an array of CSS rule strings — the shared format used by both
+ * the runtime path (useInsertionEffect) and the build path (xds theme build).
+ *
+ * Options:
+ * - computedValues: when true, prose rules use computed px values from tokens
+ * (for the build path where CSS must be self-contained).
+ * When false (default), prose rules use var() references to token custom properties
+ * (for the runtime path where tokens are set on :scope).
+ */
+export function generateThemeRules(
+ theme: XDSDefinedTheme,
+): string[] {
const parts: string[] = [];
- const scopeSelector = `[data-xds-theme="${theme.name}"]`;
+ const tokens = theme.tokens;
- // Token overrides — applied to the scope root itself
- const tokenEntries = Object.entries(theme.tokens);
+ // Helper: resolve a token value — tokens always have computed values
+ // since defineTheme runs expandTypeScale to produce them.
+ const val = (key: string): string => tokens[key] || `var(${key})`;
+
+ // 1. Token block — CSS custom properties on :scope
+ const tokenEntries = Object.entries(tokens);
if (tokenEntries.length > 0) {
const declarations = tokenEntries
.map(([prop, value]) => ` ${prop}: ${value};`)
@@ -329,10 +347,10 @@ export function generateThemeCSS(theme: XDSDefinedTheme): string {
parts.push(` :scope {\n${declarations}\n }`);
}
- // Component overrides
+ // 2. Component overrides (.xds-* class rules)
if (theme.components) {
for (const [component, rules] of Object.entries(theme.components)) {
- for (const [key, styles] of Object.entries(rules)) {
+ for (const [key, styles] of Object.entries(rules as Record<string, Record<string, string>>)) {
const entries = Object.entries(styles);
if (entries.length > 0) {
const suffix = parseStyleKey(key);
@@ -345,9 +363,86 @@ export function generateThemeCSS(theme: XDSDefinedTheme): string {
}
}
- if (parts.length === 0) return '';
+ // 3. Prose HTML element rules (h1-h6, p, small, code, hr)
+ parts.push(` :is(h1, h2, h3, h4, h5, h6) {
+ font-family: var(--font-heading);
+ color: var(--color-text-primary);
+ }`);
- const inner = parts.join('\n\n');
+ for (let level = 1; level <= 6; level++) {
+ parts.push(` h${level} {
+ font-size: ${val(`--heading-${level}-size`)};
+ font-weight: ${val(`--heading-${level}-weight`)};
+ line-height: ${val(`--heading-${level}-leading`)};
+ }`);
+ }
+
+ parts.push(` p {
+ font-family: var(--font-heading);
+ font-size: ${val('--text-body-size')};
+ font-weight: ${val('--text-body-weight')};
+ line-height: ${val('--text-body-leading')};
+ color: var(--color-text-primary);
+ }`);
+
+ parts.push(` 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 {
+ font-family: var(--font-code);
+ font-size: ${val('--text-code-size')};
+ line-height: ${val('--text-code-leading')};
+ }`);
+
+ parts.push(` hr {
+ border: none;
+ border-top: 1px solid var(--color-divider);
+ }`);
+
+ // 4. Prop-level color overrides (for text/heading/link specificity)
+ const TEXT_COLOR_MAP: Record<string, string> = {
+ primary: 'var(--color-text-primary)',
+ secondary: 'var(--color-text-secondary)',
+ disabled: 'var(--color-text-disabled)',
+ placeholder: 'var(--color-text-placeholder)',
+ active: 'var(--color-accent)',
+ };
+
+ const components = theme.components || {};
+ const touchesText = 'text' in components;
+ const touchesHeading = 'heading' in components;
+ const touchesLink = 'link' in components;
+
+ if (touchesText || touchesHeading || touchesLink) {
+ for (const [colorName, colorValue] of Object.entries(TEXT_COLOR_MAP)) {
+ if (touchesText) {
+ parts.push(` .xds-text.${colorName} { color: ${colorValue}; }`);
+ }
+ if (touchesHeading) {
+ parts.push(` .xds-heading.${colorName} { color: ${colorValue}; }`);
+ }
+ if (touchesLink) {
+ parts.push(` .xds-link.${colorName} { color: ${colorValue}; }`);
+ }
+ }
+ }
+
+ return parts;
+}
+
+/**
+ * Generate the full CSS string for a theme — runtime path.
+ * Wraps rules in @scope (no @layer — runtime injects into <style> tag).
+ */
+export function generateThemeCSS(theme: XDSDefinedTheme): string {
+ const rules = generateThemeRules(theme);
+ if (rules.length === 0) return '';
+ const scopeSelector = `[data-xds-theme="${theme.name}"]`;
+ const inner = rules.join('\n\n');
return `@scope (${scopeSelector}) to ([data-xds-theme]) {\n${inner}\n}`;
}
diff --git a/packages/core/src/theme/expandTypeScale.test.ts b/packages/core/src/theme/expandTypeScale.test.ts
index 1a70fb1340..05db8a0449 100644
--- a/packages/core/src/theme/expandTypeScale.test.ts
+++ b/packages/core/src/theme/expandTypeScale.test.ts
@@ -15,36 +15,36 @@ describe('expandTypeScale', () => {
});
it('anchors h4 to base size', () => {
- expect(tokens['--heading-4-size']).toBe('14px');
+ expect(tokens['--heading-4-size']).toBe('0.875rem');
});
it('computes heading sizes from geometric progression', () => {
- // h1 = 14 × 1.2³ ≈ 24.19 → 24px
- expect(tokens['--heading-1-size']).toBe('24px');
- // h2 = 14 × 1.2² ≈ 20.16 → 20px
- expect(tokens['--heading-2-size']).toBe('20px');
- // h3 = 14 × 1.2¹ ≈ 16.8 → 17px
- expect(tokens['--heading-3-size']).toBe('17px');
- // h5 = 14 × 1.2⁻¹ ≈ 11.67 → 12px
- expect(tokens['--heading-5-size']).toBe('12px');
- // h6 = 14 × 1.2⁻² ≈ 9.72 → 10px
- expect(tokens['--heading-6-size']).toBe('10px');
+ // h1 = 14 × 1.2³ ≈ 24.19 → 1.5rem
+ expect(tokens['--heading-1-size']).toBe('1.5rem');
+ // h2 = 14 × 1.2² ≈ 20.16 → 1.25rem
+ expect(tokens['--heading-2-size']).toBe('1.25rem');
+ // h3 = 14 × 1.2¹ ≈ 16.8 → 1.0625rem
+ expect(tokens['--heading-3-size']).toBe('1.0625rem');
+ // h5 = 14 × 1.2⁻¹ ≈ 11.67 → 0.75rem
+ expect(tokens['--heading-5-size']).toBe('0.75rem');
+ // h6 = 14 × 1.2⁻² ≈ 9.72 → 0.625rem
+ expect(tokens['--heading-6-size']).toBe('0.625rem');
});
it('computes body text at base size', () => {
- expect(tokens['--text-body-size']).toBe('14px');
- expect(tokens['--text-label-size']).toBe('14px');
- expect(tokens['--text-code-size']).toBe('14px');
+ expect(tokens['--text-body-size']).toBe('0.875rem');
+ expect(tokens['--text-label-size']).toBe('0.875rem');
+ expect(tokens['--text-code-size']).toBe('0.875rem');
});
it('computes large text one step up', () => {
- // 14 × 1.2¹ ≈ 16.8 → 17px
- expect(tokens['--text-large-size']).toBe('17px');
+ // 14 × 1.2¹ ≈ 16.8 → 1.0625rem
+ expect(tokens['--text-large-size']).toBe('1.0625rem');
});
it('computes supporting text one step down', () => {
- // 14 × 1.2⁻¹ ≈ 11.67 → 12px
- expect(tokens['--text-supporting-size']).toBe('12px');
+ // 14 × 1.2⁻¹ ≈ 11.67 → 0.75rem
+ expect(tokens['--text-supporting-size']).toBe('0.75rem');
});
it('emits unitless line-height ratios', () => {
@@ -64,7 +64,7 @@ describe('expandTypeScale', () => {
for (const [key, value] of Object.entries(tokens)) {
if (key.endsWith('-leading')) {
const sizeKey = key.replace('-leading', '-size');
- const fontSize = parseInt(tokens[sizeKey]);
+ const fontSize = Math.round(parseFloat(tokens[sizeKey]) * 16);
const ratio = parseFloat(value);
const computedLh = Math.round(fontSize * ratio);
expect(computedLh % 4).toBe(0);
@@ -76,7 +76,7 @@ describe('expandTypeScale', () => {
for (const [key, value] of Object.entries(tokens)) {
if (key.endsWith('-leading')) {
const sizeKey = key.replace('-leading', '-size');
- const fontSize = parseInt(tokens[sizeKey]);
+ const fontSize = Math.round(parseFloat(tokens[sizeKey]) * 16);
const ratio = parseFloat(value);
const computedLh = Math.round(fontSize * ratio);
expect(computedLh).toBeGreaterThanOrEqual(fontSize + 4);
@@ -107,18 +107,18 @@ describe('expandTypeScale', () => {
const tokens = expandTypeScale({base: 12, ratio: 1.125});
it('anchors h4 to base 12px', () => {
- expect(tokens['--heading-4-size']).toBe('12px');
+ expect(tokens['--heading-4-size']).toBe('0.75rem');
});
it('produces smaller heading sizes', () => {
- // h1 = 12 × 1.125³ ≈ 17.09 → 17px
- expect(tokens['--heading-1-size']).toBe('17px');
- // h2 = 12 × 1.125² ≈ 15.19 → 15px
- expect(tokens['--heading-2-size']).toBe('15px');
+ // h1 = 12 × 1.125³ ≈ 17.09 → 1.0625rem
+ expect(tokens['--heading-1-size']).toBe('1.0625rem');
+ // h2 = 12 × 1.125² ≈ 15.19 → 0.9375rem
+ expect(tokens['--heading-2-size']).toBe('0.9375rem');
});
it('keeps body at base', () => {
- expect(tokens['--text-body-size']).toBe('12px');
+ expect(tokens['--text-body-size']).toBe('0.75rem');
});
});
@@ -126,18 +126,18 @@ describe('expandTypeScale', () => {
const tokens = expandTypeScale({base: 16, ratio: 1.25});
it('anchors h4 to base 16px', () => {
- expect(tokens['--heading-4-size']).toBe('16px');
+ expect(tokens['--heading-4-size']).toBe('1rem');
});
it('produces larger heading sizes', () => {
- // h1 = 16 × 1.25³ ≈ 31.25 → 31px
- expect(tokens['--heading-1-size']).toBe('31px');
- // h2 = 16 × 1.25² = 25 → 25px
- expect(tokens['--heading-2-size']).toBe('25px');
+ // h1 = 16 × 1.25³ ≈ 31.25 → 1.9375rem
+ expect(tokens['--heading-1-size']).toBe('1.9375rem');
+ // h2 = 16 × 1.25² = 25 → 1.5625rem
+ expect(tokens['--heading-2-size']).toBe('1.5625rem');
});
it('keeps body at base', () => {
- expect(tokens['--text-body-size']).toBe('16px');
+ expect(tokens['--text-body-size']).toBe('1rem');
});
});
diff --git a/packages/core/src/theme/expandTypeScale.ts b/packages/core/src/theme/expandTypeScale.ts
index eacd8021bf..dd4ec65540 100644
--- a/packages/core/src/theme/expandTypeScale.ts
+++ b/packages/core/src/theme/expandTypeScale.ts
@@ -180,22 +180,28 @@ function computeLeading(fontSize: number, targetRatio: number): number {
return Math.round((snappedLh / fontSize) * 10000) / 10000;
}
+/** Convert px to rem based on the standard 16px root font size. */
+function pxToRem(px: number): string {
+ const rem = Math.round((px / 16) * 10000) / 10000;
+ return `${rem}rem`;
+}
+
/**
* Expand a type scale configuration into typography token overrides.
*
* Generates 33 tokens: 6 heading levels × 3 properties + 5 text types × 3 properties.
*
- * Font sizes are emitted as px values (e.g. '24px').
+ * Font sizes are emitted as rem values (e.g. '1.5rem') based on 16px root.
* Line heights are emitted as unitless ratios (e.g. '1.3333').
* Font weights are emitted as var() references (e.g. 'var(--font-weight-semibold)').
*
* @example
* ```
* const tokens = expandTypeScale({ base: 14, ratio: 1.2 });
- * // tokens['--heading-1-size'] === '24px'
+ * // tokens['--heading-1-size'] === '1.5rem'
* // tokens['--heading-1-leading'] === '1.3333'
- * // tokens['--heading-4-size'] === '14px' (anchor)
- * // tokens['--text-body-size'] === '14px'
+ * // tokens['--heading-4-size'] === '0.875rem' (anchor)
+ * // tokens['--text-body-size'] === '0.875rem'
* ```
*/
export function expandTypeScale(config: XDSTypeScaleConfig): TypeScaleTokens {
@@ -218,7 +224,7 @@ export function expandTypeScale(config: XDSTypeScaleConfig): TypeScaleTokens {
const size = computeSize(base, ratio, step);
const leading = computeLeading(size, HEADING_LH_RATIO);
- tokens[`--heading-${level}-size`] = `${size}px`;
+ tokens[`--heading-${level}-size`] = pxToRem(size);
tokens[`--heading-${level}-weight`] = headingWeights[level];
tokens[`--heading-${level}-leading`] = `${leading}`;
}
@@ -228,7 +234,7 @@ export function expandTypeScale(config: XDSTypeScaleConfig): TypeScaleTokens {
const size = computeSize(base, ratio, step);
const leading = computeLeading(size, TEXT_LH_RATIOS[type]);
- tokens[`--text-${type}-size`] = `${size}px`;
+ tokens[`--text-${type}-size`] = pxToRem(size);
tokens[`--text-${type}-weight`] = textWeights[type];
tokens[`--text-${type}-leading`] = `${leading}`;
}
diff --git a/packages/core/src/theme/generateThemeRules.test.ts b/packages/core/src/theme/generateThemeRules.test.ts
new file mode 100644
index 0000000000..2d820b06a8
--- /dev/null
+++ b/packages/core/src/theme/generateThemeRules.test.ts
@@ -0,0 +1,183 @@
+/**
+ * @file generateThemeRules.test.ts
+ * Tests that generateThemeRules produces correct, consistent CSS rules
+ * for both runtime and build paths.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {defineTheme, generateThemeCSS, generateThemeRules} from './index';
+
+const defaultInput = {
+ name: 'default',
+ typeScale: {base: 14, ratio: 1.2} as const,
+ tokens: {},
+ components: {
+ button: {
+ 'variant:secondary': {
+ backgroundColor:
+ 'light-dark(rgba(5, 54, 89, 0.1), rgba(223, 226, 229, 0.2))',
+ },
+ },
+ },
+};
+
+describe('generateThemeRules', () => {
+ const theme = defineTheme(defaultInput);
+ const rules = generateThemeRules(theme);
+
+ it('produces an array of CSS rule strings', () => {
+ expect(Array.isArray(rules)).toBe(true);
+ expect(rules.length).toBeGreaterThan(0);
+ rules.forEach((r) => expect(typeof r).toBe('string'));
+ });
+
+ // --- Token block ---
+
+ it('includes :scope token block with type scale tokens', () => {
+ const scopeRule = rules.find((r) => r.includes(':scope'));
+ expect(scopeRule).toBeDefined();
+ expect(scopeRule).toContain('--heading-1-size: 1.5rem');
+ expect(scopeRule).toContain('--heading-4-size: 0.875rem');
+ expect(scopeRule).toContain('--text-body-size: 0.875rem');
+ expect(scopeRule).toContain('--text-supporting-size: 0.75rem');
+ });
+
+ it('emits font sizes in rem', () => {
+ const scopeRule = rules.find((r) => r.includes(':scope'))!;
+ const sizeMatches = scopeRule.match(/--(?:heading|text)-\w+-size: [^;]+/g);
+ expect(sizeMatches).not.toBeNull();
+ sizeMatches!.forEach((m) => {
+ expect(m).toMatch(/rem$/);
+ expect(m).not.toContain('px');
+ });
+ });
+
+ it('emits line heights as unitless ratios', () => {
+ const scopeRule = rules.find((r) => r.includes(':scope'))!;
+ const leadingMatches = scopeRule.match(
+ /--(?:heading|text)-\w+-leading: [^;]+/g,
+ );
+ expect(leadingMatches).not.toBeNull();
+ leadingMatches!.forEach((m) => {
+ expect(m).not.toContain('px');
+ expect(m).not.toContain('rem');
+ const val = parseFloat(m.split(': ')[1]);
+ expect(val).toBeGreaterThan(1);
+ expect(val).toBeLessThan(2);
+ });
+ });
+
+ // --- Component overrides ---
+
+ it('includes .xds-heading.level-* rules for all 6 levels', () => {
+ for (let level = 1; level <= 6; level++) {
+ const rule = rules.find((r) =>
+ r.includes(`.xds-heading.level-${level}`),
+ );
+ expect(rule).toBeDefined();
+ expect(rule).toContain('font-family');
+ expect(rule).toContain(`var(--heading-${level}-size)`);
+ expect(rule).toContain(`var(--heading-${level}-weight)`);
+ expect(rule).toContain(`var(--heading-${level}-leading)`);
+ }
+ });
+
+ it('includes .xds-text.* rules for all 5 types', () => {
+ for (const type of ['body', 'large', 'label', 'code', 'supporting']) {
+ const rule = rules.find((r) => r.includes(`.xds-text.${type}`));
+ expect(rule).toBeDefined();
+ expect(rule).toContain(`var(--text-${type}-size)`);
+ }
+ });
+
+ it('includes explicit component overrides', () => {
+ const buttonRule = rules.find((r) =>
+ r.includes('.xds-button.secondary'),
+ );
+ expect(buttonRule).toBeDefined();
+ expect(buttonRule).toContain('light-dark(rgba(5, 54, 89, 0.1)');
+ });
+
+ // --- Prose rules ---
+
+ it('includes prose heading rules with computed values', () => {
+ const h1Rule = rules.find(
+ (r) => r.trimStart().startsWith('h1 {') || r.includes('\n h1 {'),
+ );
+ expect(h1Rule).toBeDefined();
+ expect(h1Rule).toContain('1.5rem');
+ expect(h1Rule).toContain('var(--font-weight-semibold)');
+ });
+
+ it('includes prose p rule with computed values', () => {
+ const pRule = rules.find(
+ (r) => r.trimStart().startsWith('p {') || r.includes('\n p {'),
+ );
+ expect(pRule).toBeDefined();
+ expect(pRule).toContain('0.875rem');
+ expect(pRule).toContain('var(--color-text-primary)');
+ });
+
+ 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);
+ });
+
+ // --- Prop-level color overrides ---
+
+ it('includes color prop overrides for text and heading', () => {
+ expect(rules.some((r) => r.includes('.xds-text.primary'))).toBe(true);
+ expect(rules.some((r) => r.includes('.xds-text.secondary'))).toBe(true);
+ expect(rules.some((r) => r.includes('.xds-heading.primary'))).toBe(true);
+ expect(rules.some((r) => r.includes('.xds-heading.disabled'))).toBe(true);
+ expect(rules.some((r) => r.includes('.xds-text.active'))).toBe(true);
+ });
+
+ // --- 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
+ for (const rule of rules) {
+ expect(css).toContain(rule);
+ }
+ });
+});
+
+describe('generateThemeRules with weight overrides', () => {
+ const theme = defineTheme({
+ name: 'custom-weights',
+ typeScale: {
+ base: 14,
+ ratio: 1.2,
+ weights: {
+ heading: {3: 'var(--font-weight-bold)'},
+ },
+ },
+ tokens: {},
+ components: {},
+ });
+ const rules = generateThemeRules(theme);
+
+ it('reflects weight override in tokens', () => {
+ const scopeRule = rules.find((r) => r.includes(':scope'))!;
+ expect(scopeRule).toContain(
+ '--heading-3-weight: var(--font-weight-bold)',
+ );
+ // Other levels keep default
+ expect(scopeRule).toContain(
+ '--heading-1-weight: var(--font-weight-semibold)',
+ );
+ });
+
+ it('reflects weight override in prose h3', () => {
+ const h3Rule = rules.find(
+ (r) => r.trimStart().startsWith('h3 {') || r.includes('\n 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 094b28ed70..47fe255a20 100644
--- a/packages/core/src/theme/index.ts
+++ b/packages/core/src/theme/index.ts
@@ -15,6 +15,7 @@ export {XDSTheme} from './XDSTheme';
export {
defineTheme,
generateThemeCSS,
+ generateThemeRules,
isDefinedTheme,
xdsTokenDefaults,
} from './defineTheme';
diff --git a/packages/core/src/theme/tokens.stylex.ts b/packages/core/src/theme/tokens.stylex.ts
index 9e4145f7a4..a3881c3086 100644
--- a/packages/core/src/theme/tokens.stylex.ts
+++ b/packages/core/src/theme/tokens.stylex.ts
@@ -333,7 +333,7 @@ export type FontWeightVarName = keyof typeof fontWeightDefaults;
// Typography Tokens - Type Scale (computed from base=14, ratio=1.2)
// =============================================================================
// These tokens are the source of truth for heading and text sizing.
-// Components and typography.css reference these tokens so that themes
+// Components reference these tokens so that themes
// can override them via typeScale in defineTheme.
//
// Default scale: base=14px, ratio=1.2, h4 anchored to base.
diff --git a/packages/core/src/theme/types.ts b/packages/core/src/theme/types.ts
index 848160852e..58616d4e17 100644
--- a/packages/core/src/theme/types.ts
+++ b/packages/core/src/theme/types.ts
@@ -109,7 +109,7 @@ export type XDSTextXStyleAllowed = {
};
/**
- * Prose element types for XDSFontWrapper
+ * Prose element types for typography CSS
*/
export type ProseElement =
| 'p'
diff --git a/packages/core/src/typography.css b/packages/core/src/typography.css
deleted file mode 100644
index 85f5ef8164..0000000000
--- a/packages/core/src/typography.css
+++ /dev/null
@@ -1,199 +0,0 @@
-/**
- * XDS Typography Styles
- *
- * Base typography styles for native HTML elements using type scale tokens.
- * Styles automatically adapt to the current theme's typeScale configuration.
- *
- * Token reference (set by theme or defaults from tokens.stylex.ts):
- * --heading-{1-6}-{size|weight|leading}
- * --text-{body|large|label|code|supporting}-{size|weight|leading}
- *
- * Usage:
- *
- * 1. Scoped (via XDSFontWrapper component):
- * <XDSFontWrapper>
- * <article dangerouslySetInnerHTML={{ __html: content }} />
- * </XDSFontWrapper>
- *
- * 2. Global (apply to body):
- * import '@xds/core/typography.css';
- * <body className="xds-typography">
- *
- * Requires a parent <Theme> component to set the CSS custom properties.
- */
-
-@layer typography {
- /* ===========================================================================
- Base Styles
- =========================================================================== */
-
- .xds-typography {
- font-size: var(--text-body-size);
- font-family: var(--font-body);
- line-height: var(--text-body-leading);
- color: var(--color-text-primary);
- }
-
- /* ===========================================================================
- Heading Styles — driven by type scale tokens
- =========================================================================== */
-
- .xds-typography h1 {
- font-family: var(--font-heading);
- font-size: var(--heading-1-size);
- font-weight: var(--heading-1-weight);
- line-height: var(--heading-1-leading);
- color: var(--color-text-primary);
- margin-top: var(--spacing-6);
- margin-bottom: var(--spacing-3);
- }
-
- .xds-typography h2 {
- font-family: var(--font-heading);
- font-size: var(--heading-2-size);
- font-weight: var(--heading-2-weight);
- line-height: var(--heading-2-leading);
- color: var(--color-text-primary);
- margin-top: var(--spacing-5);
- margin-bottom: var(--spacing-3);
- }
-
- .xds-typography h3 {
- font-family: var(--font-heading);
- font-size: var(--heading-3-size);
- font-weight: var(--heading-3-weight);
- line-height: var(--heading-3-leading);
- color: var(--color-text-primary);
- margin-top: var(--spacing-4);
- margin-bottom: var(--spacing-2);
- }
-
- .xds-typography h4 {
- font-family: var(--font-heading);
- font-size: var(--heading-4-size);
- font-weight: var(--heading-4-weight);
- line-height: var(--heading-4-leading);
- color: var(--color-text-primary);
- margin-top: var(--spacing-4);
- margin-bottom: var(--spacing-2);
- }
-
- .xds-typography h5 {
- font-family: var(--font-heading);
- font-size: var(--heading-5-size);
- font-weight: var(--heading-5-weight);
- line-height: var(--heading-5-leading);
- color: var(--color-text-primary);
- margin-top: var(--spacing-3);
- margin-bottom: var(--spacing-2);
- }
-
- .xds-typography h6 {
- font-family: var(--font-heading);
- font-size: var(--heading-6-size);
- font-weight: var(--heading-6-weight);
- line-height: var(--heading-6-leading);
- color: var(--color-text-primary);
- margin-top: var(--spacing-3);
- margin-bottom: var(--spacing-2);
- }
-
- /* ===========================================================================
- Prose Styles
- =========================================================================== */
-
- .xds-typography p {
- margin-top: 0;
- margin-bottom: var(--spacing-3);
- }
-
- .xds-typography ul,
- .xds-typography ol {
- margin-top: 0;
- margin-bottom: var(--spacing-3);
- padding-inline-start: var(--spacing-5);
- }
-
- .xds-typography li {
- margin-bottom: var(--spacing-1);
- }
-
- .xds-typography li:last-child {
- margin-bottom: 0;
- }
-
- .xds-typography blockquote {
- margin-top: 0;
- margin-bottom: var(--spacing-3);
- margin-inline-start: 0;
- margin-inline-end: 0;
- padding-inline-start: var(--spacing-4);
- border-inline-start: 3px solid var(--color-divider-emphasized);
- color: var(--color-text-secondary);
- font-style: italic;
- }
-
- .xds-typography code {
- font-family: var(--font-code);
- font-size: 0.9em;
- background-color: var(--color-wash);
- padding-block: var(--spacing-0-5);
- padding-inline: var(--spacing-1);
- border-radius: var(--radius-content);
- }
-
- .xds-typography pre {
- font-family: var(--font-code);
- font-size: var(--text-supporting-size);
- line-height: 1.5;
- margin-top: 0;
- margin-bottom: var(--spacing-3);
- padding: var(--spacing-3);
- background-color: var(--color-wash);
- border-radius: var(--radius-element);
- overflow: auto;
- white-space: pre;
- }
-
- .xds-typography pre code {
- background-color: transparent;
- padding: 0;
- border-radius: 0;
- font-size: inherit;
- }
-
- .xds-typography hr {
- margin-block: var(--spacing-4);
- border: none;
- border-top: 1px solid var(--color-divider);
- }
-
- .xds-typography strong,
- .xds-typography b {
- font-weight: var(--font-weight-semibold);
- }
-
- .xds-typography a {
- color: var(--color-text-link);
- text-decoration: underline;
- text-underline-offset: 2px;
- }
-
- .xds-typography a:hover {
- text-decoration-thickness: 2px;
- }
-
- /* ===========================================================================
- Spacing Utilities
- =========================================================================== */
-
- /* Remove top margin from first child */
- .xds-typography > :first-child {
- margin-top: 0;
- }
-
- /* Remove bottom margin from last child */
- .xds-typography > :last-child {
- margin-bottom: 0;
- }
-}