Skip to content

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

TypeScript

feat: ratio-based type scale system with typeScale in defineTheme (#638)

ernestt42de61a78a6e
diff --git a/apps/storybook/stories/FontWrapper.stories.tsx b/apps/storybook/stories/FontWrapper.stories.tsx
index 6231be3df8..81741f14d0 100644
--- a/apps/storybook/stories/FontWrapper.stories.tsx
+++ b/apps/storybook/stories/FontWrapper.stories.tsx
@@ -1,282 +1,129 @@
import type {Meta, StoryObj} from '@storybook/react';
-import * as stylex from '@stylexjs/stylex';
-import {XDSFontWrapper, useXDSFontWrapperStyles} from '@xds/core';
+import {XDSFontWrapper} from '@xds/core/Text';
+import {XDSText} from '@xds/core/Text';
-const meta = {
+const meta: Meta<typeof XDSFontWrapper> = {
title: 'Typography/XDSFontWrapper',
component: XDSFontWrapper,
- parameters: {
- layout: 'padded',
- },
tags: ['autodocs'],
- argTypes: {
- variant: {
- control: 'radio',
- options: ['default', 'editorial'],
- },
- },
-} satisfies Meta<typeof XDSFontWrapper>;
+};
export default meta;
-type Story = StoryObj<typeof meta>;
+type Story = StoryObj<typeof XDSFontWrapper>;
+
+// =============================================================================
+// Basic Usage
+// =============================================================================
-/**
- * XDSFontWrapper applies base typography styles to native HTML elements.
- * Uses typography.css which references theme CSS custom properties.
- */
export const Default: Story = {
- args: {
- variant: 'default',
- children: (
- <>
- <h1>Heading 1 (20px)</h1>
- <p>
- XDSFontWrapper automatically styles native HTML elements using the
- reset.css stylesheet. The styles use CSS custom properties from the
- theme, so they adapt automatically when you switch themes.
- </p>
- <h2>Heading 2 (18px)</h2>
- <p>
- This is body text at 14px. The default variant uses a dense heading
- scale optimized for internal tools and applications.
- </p>
- </>
- ),
- },
+ 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>
+ ),
};
-/**
- * Editorial variant uses larger heading sizes for content-heavy pages
- */
-export const Editorial: Story = {
- args: {
- variant: 'editorial',
- children: (
- <>
- <h1>Article Title (32px)</h1>
- <p>
- The editorial variant uses a larger heading scale designed for
- documentation, blog posts, and other long-form content where
- readability is the primary concern.
- </p>
- <h2>Section Heading (24px)</h2>
+// =============================================================================
+// Prose Content
+// =============================================================================
+
+export const ProseContent: Story = {
+ render: () => (
+ <div style={{maxWidth: '600px'}}>
+ <XDSFontWrapper>
+ <h1>The Art of Typography</h1>
<p>
- Body text remains at 14px for consistency, but headings are
- significantly larger to create clear visual hierarchy.
+ 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>
- </>
- ),
- },
-};
-
-/**
- * Demonstrates all prose elements with default styling
- */
-export const AllElements: Story = {
- args: {
- variant: 'default',
- children: (
- <>
- <h1>Heading 1</h1>
- <h2>Heading 2</h2>
- <h3>Heading 3</h3>
- <h4>Heading 4</h4>
- <h5>Heading 5</h5>
- <h6>Heading 6</h6>
-
+ <h2>Hierarchy Through Scale</h2>
<p>
- This is a paragraph with <strong>strong text</strong> and{' '}
- <em>italic text</em>. You can also include <a href="#">links</a> and{' '}
- <code>inline code</code>.
+ 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>
-
- <h3>Lists</h3>
- <ul>
- <li>Unordered list item 1</li>
- <li>Unordered list item 2</li>
- <li>Unordered list item 3</li>
- </ul>
-
- <ol>
- <li>Ordered list item 1</li>
- <li>Ordered list item 2</li>
- <li>Ordered list item 3</li>
- </ol>
-
- <h3>Blockquote</h3>
<blockquote>
- Design systems are a set of interconnected patterns and shared
- practices coherently organized to achieve the purpose of digital
- products.
+ <p>
+ "The details are not the details. They make the design." — Charles
+ Eames
+ </p>
</blockquote>
-
- <h3>Code Block</h3>
+ <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>{`function greet(name: string) {
- return \`Hello, \${name}!\`;
-}`}</code>
+ <code>
+ {`const theme = defineTheme({
+ name: 'custom',
+ typeScale: { base: 16, ratio: 1.25 },
+});`}
+ </code>
</pre>
-
<hr />
-
- <p>Content after a horizontal rule.</p>
- </>
- ),
- },
+ <p>
+ For different density regions, nest <code>&lt;XDSTheme&gt;</code> with
+ a different <code>typeScale</code> configuration.
+ </p>
+ </XDSFontWrapper>
+ </div>
+ ),
};
-/**
- * Comparison of default vs editorial heading scales
- */
-export const VariantComparison: Story = {
- args: {children: ''},
+// =============================================================================
+// Markdown Rendering
+// =============================================================================
+
+export const MarkdownRendering: Story = {
render: () => (
- <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32}}>
- <div>
- <p style={{marginBottom: 16, fontWeight: 600}}>Default Variant</p>
- <XDSFontWrapper variant="default">
- <h1>Heading 1</h1>
- <h2>Heading 2</h2>
- <h3>Heading 3</h3>
- <h4>Heading 4</h4>
- <p>Body text paragraph</p>
- </XDSFontWrapper>
- </div>
- <div>
- <p style={{marginBottom: 16, fontWeight: 600}}>Editorial Variant</p>
- <XDSFontWrapper variant="editorial">
- <h1>Heading 1</h1>
- <h2>Heading 2</h2>
- <h3>Heading 3</h3>
- <h4>Heading 4</h4>
- <p>Body text paragraph</p>
+ <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>
),
};
-
-/**
- * Example markdown-like content (typical CMS output)
- */
-export const MarkdownContent: Story = {
- args: {
- variant: 'editorial',
- children: (
- <>
- <h1>Getting Started with XDS</h1>
- <p>
- XDS is a design system for building internal tools and products. This
- guide will help you get up and running quickly.
- </p>
-
- <h2>Installation</h2>
- <p>Install the package using your preferred package manager:</p>
- <pre>
- <code>npm install @xds/core</code>
- </pre>
-
- <h2>Basic Usage</h2>
- <p>
- Import the components you need and wrap your app in the XDSTheme
- provider:
- </p>
- <pre>
- <code>{`import { XDSTheme, XDSButton } from '@xds/core';
-import { defaultTheme } from '@xds/theme-default';
-
-function App() {
- return (
- <XDSTheme theme={defaultTheme}>
- <XDSButton label="Click me" onPress={() => alert('Hello!')} />
- </XDSTheme>
- );
-}`}</code>
- </pre>
-
- <h2>Available Components</h2>
- <p>XDS provides the following component categories:</p>
- <ul>
- <li>
- <strong>Typography</strong> — XDSText, XDSHeading, XDSFontWrapper
- </li>
- <li>
- <strong>Inputs</strong> — XDSButton, XDSTextInput, XDSCheckboxInput
- </li>
- <li>
- <strong>Layout</strong> — XDSHStack, XDSVStack, XDSCard, XDSSection
- </li>
- <li>
- <strong>Feedback</strong> — XDSTooltip, XDSHoverCard
- </li>
- </ul>
-
- <h2>Theming</h2>
- <blockquote>
- Pro tip: The reset.css styles use CSS custom properties from the
- theme, so they automatically adapt when you switch themes.
- </blockquote>
-
- <hr />
-
- <h2>Next Steps</h2>
- <ol>
- <li>Explore the component documentation in Storybook</li>
- <li>Check out the example applications</li>
- <li>Join our Slack channel for support</li>
- </ol>
- </>
- ),
- },
-};
-
-/**
- * Alternative approach: Using StyleX styles programmatically via useFontWrapperStyles hook.
- * This is useful when you need more control over individual elements.
- */
-function StyleXApproachDemo() {
- const {headingStyles, proseStyles} = useXDSFontWrapperStyles();
-
- return (
- <XDSFontWrapper>
- <p {...stylex.props(proseStyles?.p)}>
- While XDSFontWrapper automatically styles native elements via CSS, you
- can also use the{' '}
- <code {...stylex.props(proseStyles?.code)}>
- useXDSFontWrapperStyles
- </code>{' '}
- hook to access theme styles programmatically for StyleX-based styling:
- </p>
-
- <h2 {...stylex.props(headingStyles?.h2)}>Styled with StyleX</h2>
- <p {...stylex.props(proseStyles?.p)}>
- This approach gives you more control and type safety, but requires
- applying styles to each element individually.
- </p>
-
- <pre {...stylex.props(proseStyles?.pre)}>
- <code
- {...stylex.props(
- proseStyles?.preCode,
- )}>{`import { useFontWrapperStyles } 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>
- );
-}`}</code>
- </pre>
- </XDSFontWrapper>
- );
-}
-
-export const StyleXApproach: Story = {
- args: {children: ''},
- render: () => <StyleXApproachDemo />,
-};
diff --git a/apps/storybook/stories/Heading.stories.tsx b/apps/storybook/stories/Heading.stories.tsx
index f4c5f6ee82..127b1a0b73 100644
--- a/apps/storybook/stories/Heading.stories.tsx
+++ b/apps/storybook/stories/Heading.stories.tsx
@@ -12,11 +12,6 @@ const meta: Meta<typeof XDSHeading> = {
options: [1, 2, 3, 4, 5, 6],
description: 'Visual heading level (1-6)',
},
- variant: {
- control: 'select',
- options: ['default', 'editorial'],
- description: 'Heading scale variant',
- },
color: {
control: 'select',
options: [
@@ -68,48 +63,48 @@ export default meta;
type Story = StoryObj<typeof XDSHeading>;
// =============================================================================
-// Heading Levels - Default Variant
+// Heading Levels
// =============================================================================
export const Level1: Story = {
args: {
level: 1,
- children: 'Heading Level 1 (20px)',
+ children: 'Heading Level 1 (24px)',
},
};
export const Level2: Story = {
args: {
level: 2,
- children: 'Heading Level 2 (18px)',
+ children: 'Heading Level 2 (20px)',
},
};
export const Level3: Story = {
args: {
level: 3,
- children: 'Heading Level 3 (16px)',
+ children: 'Heading Level 3 (17px)',
},
};
export const Level4: Story = {
args: {
level: 4,
- children: 'Heading Level 4 (14px)',
+ children: 'Heading Level 4 (14px — base)',
},
};
export const Level5: Story = {
args: {
level: 5,
- children: 'Heading Level 5 (14px)',
+ children: 'Heading Level 5 (12px)',
},
};
export const Level6: Story = {
args: {
level: 6,
- children: 'Heading Level 6 (12px)',
+ children: 'Heading Level 6 (10px)',
},
};
@@ -120,94 +115,24 @@ export const Level6: Story = {
export const AllLevels: Story = {
render: () => (
<div style={{display: 'flex', flexDirection: 'column', gap: '16px'}}>
- <div>
- <XDSText type="label" display="block">
- Default Variant (Internal Tools):
- </XDSText>
- <div
- style={{
- display: 'flex',
- flexDirection: 'column',
- gap: '8px',
- marginTop: '8px',
- }}>
- <XDSHeading level={1}>Heading 1 - 20px</XDSHeading>
- <XDSHeading level={2}>Heading 2 - 18px</XDSHeading>
- <XDSHeading level={3}>Heading 3 - 16px</XDSHeading>
- <XDSHeading level={4}>Heading 4 - 14px</XDSHeading>
- <XDSHeading level={5}>Heading 5 - 14px</XDSHeading>
- <XDSHeading level={6}>Heading 6 - 12px</XDSHeading>
- </div>
- </div>
- <div style={{marginTop: '24px'}}>
- <XDSText type="label" display="block">
- Editorial Variant (Content-Heavy Pages):
- </XDSText>
- <div
- style={{
- display: 'flex',
- flexDirection: 'column',
- gap: '8px',
- marginTop: '8px',
- }}>
- <XDSHeading level={1} variant="editorial">
- Heading 1 - 32px
- </XDSHeading>
- <XDSHeading level={2} variant="editorial">
- Heading 2 - 24px
- </XDSHeading>
- <XDSHeading level={3} variant="editorial">
- Heading 3 - 20px
- </XDSHeading>
- <XDSHeading level={4} variant="editorial">
- Heading 4 - 16px
- </XDSHeading>
- <XDSHeading level={5} variant="editorial">
- Heading 5 - 14px
- </XDSHeading>
- <XDSHeading level={6} variant="editorial">
- Heading 6 - 12px
- </XDSHeading>
- </div>
- </div>
- </div>
- ),
-};
-
-// =============================================================================
-// Variants
-// =============================================================================
-
-export const DefaultVariant: Story = {
- render: () => (
- <div style={{display: 'flex', flexDirection: 'column', gap: '8px'}}>
<XDSText type="supporting" display="block">
- Default variant uses a denser scale suitable for internal tools and
- dashboards
+ Type scale: base=14px, ratio=1.2, h4 anchored to base. Sizes are
+ computed from the geometric progression: size = base × ratio^step
</XDSText>
- <XDSHeading level={1}>Page Title (20px)</XDSHeading>
- <XDSHeading level={2}>Section Title (18px)</XDSHeading>
- <XDSHeading level={3}>Subsection Title (16px)</XDSHeading>
- </div>
- ),
-};
-
-export const EditorialVariant: Story = {
- render: () => (
- <div style={{display: 'flex', flexDirection: 'column', gap: '8px'}}>
- <XDSText type="supporting" display="block">
- Editorial variant uses a larger scale for content-heavy pages like
- articles
- </XDSText>
- <XDSHeading level={1} variant="editorial">
- Article Title (32px)
- </XDSHeading>
- <XDSHeading level={2} variant="editorial">
- Section Title (24px)
- </XDSHeading>
- <XDSHeading level={3} variant="editorial">
- Subsection Title (20px)
- </XDSHeading>
+ <div
+ style={{
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '8px',
+ marginTop: '8px',
+ }}>
+ <XDSHeading level={1}>Heading 1 — 24px</XDSHeading>
+ <XDSHeading level={2}>Heading 2 — 20px</XDSHeading>
+ <XDSHeading level={3}>Heading 3 — 17px</XDSHeading>
+ <XDSHeading level={4}>Heading 4 — 14px (base)</XDSHeading>
+ <XDSHeading level={5}>Heading 5 — 12px</XDSHeading>
+ <XDSHeading level={6}>Heading 6 — 10px</XDSHeading>
+ </div>
</div>
),
};
@@ -298,16 +223,6 @@ export const MultiLineTruncation: Story = {
),
};
-export const TruncationWithoutTooltip: Story = {
- render: () => (
- <div style={{width: '300px', border: '1px solid #ccc', padding: '12px'}}>
- <XDSHeading level={2} maxLines={1} hasTruncateTooltip={false}>
- Truncated Heading Without Tooltip On Hover
- </XDSHeading>
- </div>
- ),
-};
-
// =============================================================================
// Accessibility Level Override
// =============================================================================
@@ -334,78 +249,6 @@ export const AccessibilityLevel: Story = {
),
};
-// =============================================================================
-// Text Wrap
-// =============================================================================
-
-export const TextWrapVariants: Story = {
- render: () => (
- <div
- style={{
- display: 'flex',
- flexDirection: 'column',
- gap: '16px',
- maxWidth: '300px',
- }}>
- <div>
- <XDSText type="label" display="block">
- wrap (default):
- </XDSText>
- <XDSHeading level={2} textWrap="wrap">
- This Heading Wraps Normally At Word Boundaries
- </XDSHeading>
- </div>
- <div>
- <XDSText type="label" display="block">
- balance:
- </XDSText>
- <XDSHeading level={2} textWrap="balance">
- This Heading Is Balanced For Better Visual Appearance
- </XDSHeading>
- </div>
- <div>
- <XDSText type="label" display="block">
- pretty:
- </XDSText>
- <XDSHeading level={2} textWrap="pretty">
- This Heading Uses Pretty Wrap To Avoid Orphans
- </XDSHeading>
- </div>
- </div>
- ),
-};
-
-// =============================================================================
-// Word Break
-// =============================================================================
-
-export const WordBreakVariants: Story = {
- render: () => (
- <div style={{display: 'flex', gap: '16px'}}>
- <div style={{flex: 1, maxWidth: '200px'}}>
- <XDSText type="label" display="block">
- break-word:
- </XDSText>
- <div style={{border: '1px solid #ccc', padding: '8px'}}>
- <XDSHeading level={3} maxLines={2} wordBreak="break-word">
- Supercalifragilisticexpialidocious
- </XDSHeading>
- </div>
- </div>
- <div style={{flex: 1, maxWidth: '200px'}}>
- <XDSText type="label" display="block">
- break-all:
- </XDSText>
- <div style={{border: '1px solid #ccc', padding: '8px'}}>
- <XDSHeading level={3} maxLines={2} wordBreak="break-all">
- Supercalifragilisticexpialidocious
- </XDSHeading>
- </div>
- </div>
- </div>
- ),
-};
-
// =============================================================================
// Decorations
// =============================================================================
@@ -471,16 +314,6 @@ export const PageLayout: Story = {
<br />• Task completed
</XDSText>
</div>
-
- <div style={{marginTop: '24px'}}>
- <XDSHeading level={3}>Yesterday</XDSHeading>
- <XDSText type="body" display="block">
- • Meeting scheduled
- <br />
- • Document shared
- <br />• Status update posted
- </XDSText>
- </div>
</div>
),
};
@@ -521,115 +354,3 @@ export const CardGrid: Story = {
</div>
),
};
-
-export const ArticleLayout: Story = {
- render: () => (
- <div style={{maxWidth: '600px'}}>
- <XDSHeading level={1} variant="editorial">
- The Future of Design Systems
- </XDSHeading>
- <XDSText type="supporting" display="block">
- Published on January 28, 2026 by Jane Doe
- </XDSText>
-
- <div style={{marginTop: '24px'}}>
- <XDSText type="large" display="block">
- Design systems are evolving rapidly, and understanding these changes
- is crucial for modern product development.
- </XDSText>
- </div>
-
- <div style={{marginTop: '32px'}}>
- <XDSHeading level={2} variant="editorial">
- Introduction
- </XDSHeading>
- <XDSText type="body" display="block">
- In this article, we'll explore the key trends shaping design systems
- in 2026 and beyond.
- </XDSText>
- </div>
-
- <div style={{marginTop: '24px'}}>
- <XDSHeading level={3} variant="editorial">
- Component Architecture
- </XDSHeading>
- <XDSText type="body" display="block">
- Modern component architecture prioritizes flexibility and consistency.
- </XDSText>
- </div>
-
- <div style={{marginTop: '24px'}}>
- <XDSHeading level={3} variant="editorial">
- Token-Based Theming
- </XDSHeading>
- <XDSText type="body" display="block">
- Design tokens enable scalable theming across platforms and products.
- </XDSText>
- </div>
- </div>
- ),
-};
-
-export const SidebarLayout: Story = {
- render: () => (
- <div style={{display: 'flex', gap: '24px', maxWidth: '800px'}}>
- <div style={{flex: 1}}>
- <XDSHeading level={1}>Main Content</XDSHeading>
- <XDSText type="body" display="block">
- This is the main page content with a proper document outline.
- </XDSText>
-
- <div style={{marginTop: '24px'}}>
- <XDSHeading level={2}>Section 1</XDSHeading>
- <XDSText type="body" display="block">
- Content for section 1.
- </XDSText>
- </div>
-
- <div style={{marginTop: '24px'}}>
- <XDSHeading level={2}>Section 2</XDSHeading>
- <XDSText type="body" display="block">
- Content for section 2.
- </XDSText>
- </div>
- </div>
-
- <div
- style={{
- width: '200px',
- padding: '16px',
- backgroundColor: '#f5f5f5',
- borderRadius: '8px',
- }}>
- <XDSHeading level={2} accessibilityLevel={3}>
- Sidebar Info
- </XDSHeading>
- <XDSText type="supporting" display="block">
- This heading looks like H2 but is semantically H3 so it doesn't
- disrupt the main content outline.
- </XDSText>
- </div>
- </div>
- ),
-};
-
-export const ErrorState: Story = {
- render: () => (
- <div
- style={{
- padding: '24px',
- borderRadius: '8px',
- backgroundColor: '#fff5f5',
- border: '1px solid #feb2b2',
- maxWidth: '400px',
- }}>
- <XDSHeading level={2} color="active">
- Error: Connection Failed
- </XDSHeading>
- <XDSText type="body" display="block">
- We couldn't connect to the server. Please check your internet connection
- and try again.
- </XDSText>
- </div>
- ),
-};
diff --git a/apps/storybook/stories/ThemeEditor.stories.tsx b/apps/storybook/stories/ThemeEditor.stories.tsx
index 2f3835ccd1..77d2bbb849 100644
--- a/apps/storybook/stories/ThemeEditor.stories.tsx
+++ b/apps/storybook/stories/ThemeEditor.stories.tsx
@@ -13,13 +13,16 @@ import {XDSTabList} from '@xds/core/TabList';
import {XDSDialog} from '@xds/core/Dialog';
import {XDSToken} from '@xds/core/Token';
import {XDSSlider} from '@xds/core/Slider';
+import {XDSSelector} from '@xds/core/Selector';
+import {XDSNumberInput} from '@xds/core/NumberInput';
import {XDSProgressBar} from '@xds/core/ProgressBar';
import {XDSCheckboxInput} from '@xds/core/CheckboxInput';
import {XDSRadioList, XDSRadioListItem} from '@xds/core/RadioList';
import {XDSTable} from '@xds/core/Table';
import type {XDSTableColumn} from '@xds/core/Table';
import {XDSDivider} from '@xds/core/Divider';
-import {XDSTheme, defineTheme} from '@xds/core/theme';
+import {XDSTheme, defineTheme, expandTypeScale} from '@xds/core/theme';
+import {XDSFontWrapper} from '@xds/core/Text';
import {
colorDefaults,
spacingDefaults,
@@ -28,11 +31,12 @@ import {
textSizeDefaults,
lineHeightDefaults,
fontWeightDefaults,
+ typeScaleDefaults,
sizeDefaults,
elevationDefaults,
transitionDefaults,
} from '@xds/core/theme';
-import {defaultIconRegistry} from '@xds/theme-default/icons';
+import {defaultIconRegistry} from '@xds/theme-default';
// =============================================================================
// Token Groups for the Editor
@@ -217,48 +221,60 @@ const COLOR_CATEGORIES = {
const TYPOGRAPHY_CATEGORIES = {
'Font Families': ['--font-body', '--font-heading', '--font-code'],
'Heading 1': {
- description: 'Primary page title',
- tokens: ['--text-2xl', '--font-weight-semibold', '--leading-tight'],
+ description: 'Primary page title (24px default)',
+ tokens: ['--heading-1-size', '--heading-1-weight', '--heading-1-leading'],
},
'Heading 2': {
- description: 'Section title',
- tokens: ['--text-xl', '--font-weight-semibold', '--leading-snug'],
+ description: 'Section title (20px default)',
+ tokens: ['--heading-2-size', '--heading-2-weight', '--heading-2-leading'],
},
'Heading 3': {
- description: 'Subsection title',
- tokens: ['--text-lg', '--font-weight-semibold', '--leading-tight'],
+ description: 'Subsection title (17px default)',
+ tokens: ['--heading-3-size', '--heading-3-weight', '--heading-3-leading'],
},
'Heading 4': {
- description: 'Card/component title',
- tokens: ['--text-base', '--font-weight-semibold', '--leading-base'],
+ description: 'Card/component title (14px — base anchor)',
+ tokens: ['--heading-4-size', '--heading-4-weight', '--heading-4-leading'],
},
'Heading 5': {
- description: 'Minor heading',
- tokens: ['--text-base', '--font-weight-semibold', '--leading-base'],
+ description: 'Minor heading (12px default)',
+ tokens: ['--heading-5-size', '--heading-5-weight', '--heading-5-leading'],
},
'Heading 6': {
- description: 'Smallest heading',
- tokens: ['--text-xsm', '--font-weight-semibold', '--leading-snug'],
+ description: 'Smallest heading (10px default)',
+ tokens: ['--heading-6-size', '--heading-6-weight', '--heading-6-leading'],
},
'Body Text': {
description: 'Default paragraph text',
- tokens: ['--text-base', '--font-weight-normal', '--leading-base'],
+ tokens: ['--text-body-size', '--text-body-weight', '--text-body-leading'],
},
'Large Text': {
description: 'Intro/lead paragraphs',
- tokens: ['--text-lg', '--font-weight-normal', '--leading-normal'],
+ tokens: [
+ '--text-large-size',
+ '--text-large-weight',
+ '--text-large-leading',
+ ],
},
'Label Text': {
description: 'Form labels, UI labels',
- tokens: ['--text-base', '--font-weight-medium', '--leading-base'],
+ tokens: [
+ '--text-label-size',
+ '--text-label-weight',
+ '--text-label-leading',
+ ],
},
'Supporting Text': {
description: 'Captions, helper text',
- tokens: ['--text-xsm', '--font-weight-normal', '--leading-snug'],
+ tokens: [
+ '--text-supporting-size',
+ '--text-supporting-weight',
+ '--text-supporting-leading',
+ ],
},
'Code Text': {
description: 'Inline code, code blocks',
- tokens: ['--text-base', '--font-weight-normal', '--leading-base'],
+ tokens: ['--text-code-size', '--text-code-weight', '--text-code-leading'],
},
'All Text Sizes': [
'--text-4xs',
@@ -1208,16 +1224,31 @@ function generateThemeCode(
themeName: string,
tokens: Record<string, string>,
defaults: Record<string, string>,
+ typeScaleBase?: number,
+ typeScaleRatio?: number,
): string {
const changedTokens: Record<string, string> = {};
+ // Check if type scale is non-default
+ const hasCustomTypeScale =
+ typeScaleBase !== undefined &&
+ typeScaleRatio !== undefined &&
+ (typeScaleBase !== 14 || typeScaleRatio !== 1.2);
+
+ // If type scale is custom, exclude the generated type scale tokens from explicit tokens
+ const typeScaleTokenKeys = new Set(Object.keys(typeScaleDefaults));
+
for (const [key, value] of Object.entries(tokens)) {
if (value !== defaults[key]) {
+ // Skip type scale tokens if they'll be generated by typeScale config
+ if (hasCustomTypeScale && typeScaleTokenKeys.has(key)) continue;
changedTokens[key] = value;
}
}
- if (Object.keys(changedTokens).length === 0) {
+ const hasTokenOverrides = Object.keys(changedTokens).length > 0;
+
+ if (!hasTokenOverrides && !hasCustomTypeScale) {
return `import { defineTheme } from '@xds/core/theme';
export const ${themeName}Theme = defineTheme({
@@ -1226,23 +1257,34 @@ export const ${themeName}Theme = defineTheme({
});`;
}
- const tokenEntries = Object.entries(changedTokens)
- .map(([key, value]) => {
- const parsed = parseLightDark(value);
- if (parsed) {
- return ` '${key}': ['${parsed.light}', '${parsed.dark}'],`;
- }
- return ` '${key}': '${value}',`;
- })
- .join('\n');
+ const parts: string[] = [];
+
+ if (hasCustomTypeScale) {
+ parts.push(
+ ` typeScale: { base: ${typeScaleBase}, ratio: ${typeScaleRatio} },`,
+ );
+ }
+
+ if (hasTokenOverrides) {
+ const tokenEntries = Object.entries(changedTokens)
+ .map(([key, value]) => {
+ const parsed = parseLightDark(value);
+ if (parsed) {
+ return ` '${key}': ['${parsed.light}', '${parsed.dark}'],`;
+ }
+ return ` '${key}': '${value}',`;
+ })
+ .join('\n');
+ parts.push(` tokens: {\n${tokenEntries}\n },`);
+ } else {
+ parts.push(` tokens: {},`);
+ }
return `import { defineTheme } from '@xds/core/theme';
export const ${themeName}Theme = defineTheme({
name: '${themeName}',
- tokens: {
-${tokenEntries}
- },
+${parts.join('\n')}
});`;
}
@@ -1256,8 +1298,9 @@ function ThemeEditorComponent() {
React.useState<string>('Core Semantic');
const [activeTypographyCategory, setActiveTypographyCategory] =
React.useState<string>('Heading 1');
+ const [themeName] = React.useState('custom');
+
const [mode, setMode] = React.useState<'light' | 'dark'>('light');
- const [themeName, setThemeName] = React.useState('custom');
const [showCode, setShowCode] = React.useState(false);
// Collect all defaults
@@ -1270,6 +1313,7 @@ function ThemeEditorComponent() {
...textSizeDefaults,
...lineHeightDefaults,
...fontWeightDefaults,
+ ...typeScaleDefaults,
...sizeDefaults,
...elevationDefaults,
...transitionDefaults,
@@ -1277,6 +1321,10 @@ function ThemeEditorComponent() {
[],
);
+ // Type scale state — base and ratio for the interactive type scale editor
+ const [typeScaleBase, setTypeScaleBase] = React.useState(14);
+ const [typeScaleRatio, setTypeScaleRatio] = React.useState(1.2);
+
const [tokens, setTokens] =
React.useState<Record<string, string>>(allDefaults);
@@ -1289,18 +1337,35 @@ function ThemeEditorComponent() {
const handleReset = React.useCallback(() => {
setTokens(allDefaults);
+ setTypeScaleBase(14);
+ setTypeScaleRatio(1.2);
}, [allDefaults]);
- // Create a theme from current tokens
+ // Create a theme from current tokens.
+ // Uses defaultTheme's component overrides so that type scale tokens
+ // (--heading-1-size, --text-body-size, etc.) are consumed by the
+ // heading/text CSS rules in the preview.
+ //
+ // Type scale tokens are ALWAYS included (even at default values) because
+ // the component overrides reference var(--heading-1-size) etc., and those
+ // unhashed CSS custom properties only exist when the theme explicitly sets them.
+ const typeScaleKeys = React.useMemo(
+ () => new Set(Object.keys(typeScaleDefaults)),
+ [],
+ );
+
const currentTheme = React.useMemo(() => {
const tokenOverrides: Record<string, string> = {};
for (const [key, value] of Object.entries(tokens)) {
- if (value !== allDefaults[key]) {
+ // Always include type scale tokens — the component CSS rules reference
+ // var(--heading-1-size) etc. which only exist when the theme sets them.
+ if (typeScaleKeys.has(key) || value !== allDefaults[key]) {
tokenOverrides[key] = value;
}
}
return defineTheme({
name: themeName,
+ typeScale: {base: typeScaleBase, ratio: typeScaleRatio},
tokens: tokenOverrides as Partial<Record<string, string>>,
icons: defaultIconRegistry,
});
@@ -1318,26 +1383,16 @@ function ThemeEditorComponent() {
return (
<div style={{display: 'flex', flexDirection: 'column', gap: '8px'}}>
{/* Color category selector */}
- <div style={{marginBottom: '8px'}}>
- <select
- value={activeColorCategory}
- onChange={e => setActiveColorCategory(e.target.value)}
- style={{
- width: '100%',
- padding: '8px 12px',
- fontSize: '14px',
- border: '1px solid var(--color-divider-emphasized)',
- borderRadius: '8px',
- backgroundColor: 'var(--color-surface)',
- color: 'var(--color-text-primary)',
- }}>
- {Object.keys(COLOR_CATEGORIES).map(category => (
- <option key={category} value={category}>
- {category}
- </option>
- ))}
- </select>
- </div>
+ <XDSSelector
+ label="Color Category"
+ isLabelHidden
+ options={Object.keys(COLOR_CATEGORIES).map(category => ({
+ value: category,
+ label: category,
+ }))}
+ value={activeColorCategory}
+ onChange={v => setActiveColorCategory(v)}
+ />
{categoryTokens.map(tokenName => (
<ColorSwatch
@@ -1383,6 +1438,181 @@ function ThemeEditorComponent() {
}
if (activeGroup === 'typography') {
+ // Type scale controls
+ const applyTypeScale = (base: number, ratio: number) => {
+ setTypeScaleBase(base);
+ setTypeScaleRatio(ratio);
+ setTokens(prev => ({...prev, ...expandTypeScale({base, ratio})}));
+ };
+
+ // Named ratio options from musical/mathematical intervals
+ const RATIO_OPTIONS = [
+ {value: 1.067, label: '1.067 — Minor Second'},
+ {value: 1.125, label: '1.125 — Major Second'},
+ {value: 1.2, label: '1.200 — Minor Third'},
+ {value: 1.25, label: '1.250 — Major Third'},
+ {value: 1.333, label: '1.333 — Perfect Fourth'},
+ {value: 1.414, label: '1.414 — Augmented Fourth'},
+ {value: 1.5, label: '1.500 — Perfect Fifth'},
+ {value: 1.618, label: '1.618 — Golden Ratio'},
+ ];
+ const isCustomRatio = !RATIO_OPTIONS.some(
+ o => Math.abs(o.value - typeScaleRatio) < 0.001,
+ );
+
+ const typeScaleSection = (
+ <div
+ style={{
+ padding: '12px',
+ borderRadius: '8px',
+ backgroundColor: 'var(--color-wash)',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '10px',
+ marginBottom: '16px',
+ }}>
+ <XDSText type="label" color="secondary">
+ Type Scale
+ </XDSText>
+ <XDSSlider
+ label="Base Size"
+ min={10}
+ max={24}
+ step={1}
+ value={typeScaleBase}
+ onChange={v => applyTypeScale(v, typeScaleRatio)}
+ formatValue={v => `${v}px`}
+ valueDisplay="text"
+ />
+ <XDSSelector
+ label="Scale Ratio"
+ options={[
+ ...RATIO_OPTIONS.map(opt => ({
+ value: String(opt.value),
+ label: opt.label,
+ })),
+ {
+ value: 'custom',
+ label: isCustomRatio
+ ? `Custom — ${typeScaleRatio.toFixed(3)}`
+ : 'Custom…',
+ },
+ ]}
+ value={isCustomRatio ? 'custom' : String(typeScaleRatio)}
+ onChange={v => {
+ if (v === 'custom') return;
+ applyTypeScale(typeScaleBase, Number(v));
+ }}
+ />
+ {isCustomRatio && (
+ <XDSSlider
+ label="Custom Ratio"
+ isLabelHidden
+ min={1050}
+ max={1700}
+ step={1}
+ value={Math.round(typeScaleRatio * 1000)}
+ onChange={v => applyTypeScale(typeScaleBase, v / 1000)}
+ formatValue={v => (v / 1000).toFixed(3)}
+ valueDisplay="text"
+ />
+ )}
+ <div>
+ <XDSText
+ type="supporting"
+ display="block"
+ style={{marginBottom: '4px'}}>
+ Recommended values
+ </XDSText>
+ <div style={{display: 'flex', gap: '4px', flexWrap: 'wrap'}}>
+ <XDSButton
+ label="Functional"
+ variant={
+ typeScaleBase === 12 && typeScaleRatio === 1.125
+ ? 'primary'
+ : 'ghost'
+ }
+ size="sm"
+ onClick={() => applyTypeScale(12, 1.125)}
+ />
+ <XDSButton
+ label="Default"
+ variant={
+ typeScaleBase === 14 && typeScaleRatio === 1.2
+ ? 'primary'
+ : 'ghost'
+ }
+ size="sm"
+ onClick={() => applyTypeScale(14, 1.2)}
+ />
+ <XDSButton
+ label="Editorial"
+ variant={
+ typeScaleBase === 16 && typeScaleRatio === 1.25
+ ? 'primary'
+ : 'ghost'
+ }
+ size="sm"
+ onClick={() => applyTypeScale(16, 1.25)}
+ />
+ </div>
+ </div>
+ {/* Compact heading preview */}
+ <div
+ style={{
+ padding: '8px 12px',
+ borderRadius: '6px',
+ border: '1px solid var(--color-divider)',
+ backgroundColor: 'var(--color-surface)',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '2px',
+ }}>
+ {[1, 2, 3, 4, 5, 6].map(level => {
+ const size = tokens[`--heading-${level}-size`] || '';
+ return (
+ <div
+ key={level}
+ style={{
+ display: 'flex',
+ alignItems: 'baseline',
+ gap: '8px',
+ }}>
+ <XDSText
+ type="code"
+ color="secondary"
+ style={{width: '18px', flexShrink: 0}}>
+ h{level}
+ </XDSText>
+ <span
+ style={{
+ fontSize: size,
+ fontWeight: 600,
+ lineHeight: 1.3,
+ color: 'var(--color-text-primary)',
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ }}>
+ Heading
+ </span>
+ <XDSText
+ type="code"
+ color="secondary"
+ style={{marginLeft: 'auto', flexShrink: 0}}>
+ {size}
+ </XDSText>
+ </div>
+ );
+ })}
+ </div>
+ <XDSText type="code" color="secondary">
+ size = {typeScaleBase} × {typeScaleRatio.toFixed(3)}^step · h4 =
+ anchor
+ </XDSText>
+ </div>
+ );
+
const categoryValue = TYPOGRAPHY_CATEGORIES[
activeTypographyCategory as keyof typeof TYPOGRAPHY_CATEGORIES
] as TypographyCategoryValue | undefined;
@@ -1404,64 +1634,53 @@ function ThemeEditorComponent() {
return (
<div style={{display: 'flex', flexDirection: 'column', gap: '8px'}}>
+ {typeScaleSection}
+
{/* Typography category selector */}
- <div style={{marginBottom: '8px'}}>
- <select
- value={activeTypographyCategory}
- onChange={e => setActiveTypographyCategory(e.target.value)}
- style={{
- width: '100%',
- padding: '8px 12px',
- fontSize: '14px',
- border: '1px solid var(--color-divider-emphasized)',
- borderRadius: '8px',
- backgroundColor: 'var(--color-surface)',
- color: 'var(--color-text-primary)',
- }}>
- <optgroup label="Semantic Styles">
- {Object.keys(TYPOGRAPHY_CATEGORIES)
- .filter(k => {
- const v = TYPOGRAPHY_CATEGORIES[
- k as keyof typeof TYPOGRAPHY_CATEGORIES
- ] as TypographyCategoryValue;
- return !Array.isArray(v);
- })
- .map(category => (
- <option key={category} value={category}>
- {category}
- </option>
- ))}
- </optgroup>
- <optgroup label="Raw Tokens">
- {Object.keys(TYPOGRAPHY_CATEGORIES)
- .filter(k => {
- const v = TYPOGRAPHY_CATEGORIES[
- k as keyof typeof TYPOGRAPHY_CATEGORIES
- ] as TypographyCategoryValue;
- return Array.isArray(v);
- })
- .map(category => (
- <option key={category} value={category}>
- {category}
- </option>
- ))}
- </optgroup>
- </select>
- </div>
+ <XDSSelector
+ label="Typography Category"
+ isLabelHidden
+ options={[
+ {
+ type: 'section' as const,
+ title: 'Semantic Styles',
+ options: Object.keys(TYPOGRAPHY_CATEGORIES)
+ .filter(
+ k =>
+ !Array.isArray(
+ TYPOGRAPHY_CATEGORIES[
+ k as keyof typeof TYPOGRAPHY_CATEGORIES
+ ],
+ ),
+ )
+ .map(category => ({value: category, label: category})),
+ },
+ {
+ type: 'section' as const,
+ title: 'Raw Tokens',
+ options: Object.keys(TYPOGRAPHY_CATEGORIES)
+ .filter(k =>
+ Array.isArray(
+ TYPOGRAPHY_CATEGORIES[
+ k as keyof typeof TYPOGRAPHY_CATEGORIES
+ ],
+ ),
+ )
+ .map(category => ({value: category, label: category})),
+ },
+ ]}
+ value={activeTypographyCategory}
+ onChange={v => setActiveTypographyCategory(v)}
+ />
{/* Description for semantic styles */}
{categoryDescription && (
- <div
- style={{
- padding: '8px 12px',
- borderRadius: '8px',
- backgroundColor: 'var(--color-accent-deemphasized)',
- fontSize: '12px',
- color: 'var(--color-text-secondary)',
- marginBottom: '4px',
- }}>
+ <XDSText
+ type="supporting"
+ display="block"
+ style={{marginBottom: '4px'}}>
{categoryDescription}
- </div>
+ </XDSText>
)}
{/* Sample text preview for semantic styles */}
@@ -1559,7 +1778,9 @@ function ThemeEditorComponent() {
<div
style={{
display: 'flex',
- height: '100vh',
+ position: 'fixed',
+ inset: 0,
+ overflow: 'hidden',
backgroundColor: 'var(--color-wash)',
}}>
{/* Left Panel - Token Editor */}
@@ -1571,62 +1792,10 @@ function ThemeEditorComponent() {
flexDirection: 'column',
backgroundColor: 'var(--color-surface)',
}}>
- {/* Header */}
- <div
- style={{
- padding: '16px',
- borderBottom: '1px solid var(--color-divider)',
- }}>
- <XDSHeading level={3}>Theme Editor</XDSHeading>
- <XDSText type="supporting" style={{marginTop: '4px'}}>
- Customize XDS design tokens
- </XDSText>
- </div>
-
- {/* Theme name input */}
- <div
- style={{
- padding: '12px 16px',
- borderBottom: '1px solid var(--color-divider)',
- }}>
- <XDSTextInput
- label="Theme Name"
- value={themeName}
- onChange={setThemeName}
- size="sm"
- />
- </div>
-
- {/* Mode toggle */}
- <div
- style={{
- padding: '12px 16px',
- borderBottom: '1px solid var(--color-divider)',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- }}>
- <XDSText type="label">Edit Mode</XDSText>
- <div style={{display: 'flex', gap: '8px'}}>
- <XDSButton
- label="Light"
- variant={mode === 'light' ? 'primary' : 'ghost'}
- size="sm"
- onClick={() => setMode('light')}
- />
- <XDSButton
- label="Dark"
- variant={mode === 'dark' ? 'primary' : 'ghost'}
- size="sm"
- onClick={() => setMode('dark')}
- />
- </div>
- </div>
-
{/* Token group tabs */}
<div
style={{
- padding: '12px 16px',
+ padding: '16px 16px 12px',
borderBottom: '1px solid var(--color-divider)',
display: 'flex',
gap: '4px',
@@ -1692,16 +1861,27 @@ function ThemeEditorComponent() {
{/* Preview header */}
<div
style={{
- padding: '16px 24px',
+ padding: '12px 24px',
borderBottom: '1px solid var(--color-divider)',
backgroundColor: 'var(--color-surface)',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}>
- <div>
- <XDSHeading level={4}>Live Preview</XDSHeading>
- <XDSText type="supporting">See your changes in real-time</XDSText>
+ <XDSHeading level={4}>Live Preview</XDSHeading>
+ <div style={{display: 'flex', gap: '4px'}}>
+ <XDSButton
+ label="Light"
+ variant={mode === 'light' ? 'primary' : 'ghost'}
+ size="sm"
+ onClick={() => setMode('light')}
+ />
+ <XDSButton
+ label="Dark"
+ variant={mode === 'dark' ? 'primary' : 'ghost'}
+ size="sm"
+ onClick={() => setMode('dark')}
+ />
</div>
</div>
@@ -1732,7 +1912,13 @@ function ThemeEditorComponent() {
margin: 0,
color: 'var(--color-text-primary)',
}}>
- {generateThemeCode(themeName, tokens, allDefaults)}
+ {generateThemeCode(
+ themeName,
+ tokens,
+ allDefaults,
+ typeScaleBase,
+ typeScaleRatio,
+ )}
</pre>
</div>
)}
@@ -1742,15 +1928,12 @@ function ThemeEditorComponent() {
style={{
flex: 1,
overflow: 'auto',
- padding: '24px',
}}>
<XDSTheme theme={currentTheme} mode={mode}>
<div
style={{
backgroundColor: 'var(--color-surface)',
- borderRadius: '12px',
padding: '24px',
- minHeight: '100%',
}}>
<ComponentPreview />
</div>
@@ -1782,7 +1965,8 @@ type Story = StoryObj;
export const ThemeEditor: Story = {
render: () => <ThemeEditorComponent />,
parameters: {
- // Disable the theme decorator for this story since we manage our own theme
- xdsTheme: 'none',
+ // Use default theme for the editor chrome (left panel).
+ // The preview panel wraps its own <XDSTheme theme={currentTheme}>.
+ xdsTheme: 'default',
},
};
diff --git a/packages/core/src/Text/Text.doc.mjs b/packages/core/src/Text/Text.doc.mjs
index 2079235804..986095186a 100644
--- a/packages/core/src/Text/Text.doc.mjs
+++ b/packages/core/src/Text/Text.doc.mjs
@@ -17,17 +17,13 @@ export const docs = {
label: 'Heading',
code: '<XDSHeading level={1}>Page Title</XDSHeading>',
},
- {
- label: 'Editorial heading',
- code: '<XDSHeading level={1} variant="editorial">Article Title</XDSHeading>',
- },
{
label: 'Truncated text with tooltip',
code: '<XDSText type="body" maxLines={2}>Very long text that will be clamped after two lines and show a tooltip on hover.</XDSText>',
},
{
label: 'Font wrapper for native HTML',
- code: `<XDSFontWrapper variant="editorial">
+ code: `<XDSFontWrapper>
<article dangerouslySetInnerHTML={{__html: markdownContent}} />
</XDSFontWrapper>`,
},
@@ -44,7 +40,7 @@ export const docs = {
],
theming: {
targets: [
- {className: 'xds-heading', visualProps: ['level', 'variant']},
+ {className: 'xds-heading', visualProps: ['level']},
{className: 'xds-text', visualProps: ['type']},
],
},
@@ -189,16 +185,12 @@ export const docs = {
{
name: 'XDSHeading',
description:
- 'Semantic heading component that renders h1–h6 elements with themed styling, optional editorial scale, and line-clamp truncation.',
+ 'Semantic heading component that renders h1–h6 elements with themed styling, themed sizing via type scale tokens, and line-clamp truncation.',
examples: [
{
label: 'Basic',
code: '<XDSHeading level={1}>Page Title</XDSHeading>',
},
- {
- label: 'Editorial scale',
- code: '<XDSHeading level={1} variant="editorial">Article Title</XDSHeading>',
- },
{
label: 'Accessibility level override',
code: '<XDSHeading level={2} accessibilityLevel={3}>Sidebar Section</XDSHeading>',
@@ -232,13 +224,6 @@ export const docs = {
description:
'Accessibility level override. When set and different from `level`, applies `aria-level` so the document outline differs from the visual style.',
},
- {
- name: 'variant',
- type: "'default' | 'editorial'",
- description:
- "Visual variant. 'default' uses a dense scale for internal tools (h1: 20px); 'editorial' uses a larger scale for content-heavy pages (h1: 32px).",
- default: "'default'",
- },
{
name: 'color',
type: "'primary' | 'secondary' | 'disabled' | 'placeholder' | 'active' | 'inherit'",
@@ -302,23 +287,7 @@ export const docs = {
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: [
- {
- label: 'Default variant',
- 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: 'Editorial variant',
- code: `<XDSFontWrapper variant="editorial">
- <article dangerouslySetInnerHTML={{__html: markdownContent}} />
-</XDSFontWrapper>`,
- },
+
],
props: [
{
@@ -327,13 +296,6 @@ export const docs = {
description: 'Content to style with XDS typography.',
required: true,
},
- {
- name: 'variant',
- type: "'default' | 'editorial'",
- description:
- "Heading scale variant. 'default' uses a dense scale for internal tools; 'editorial' uses a larger scale for content-heavy pages.",
- default: "'default'",
- },
],
},
{
@@ -383,7 +345,7 @@ export const docsZh = {
},
{
label: '编辑风格标题',
- code: '<XDSHeading level={1} variant="editorial">Article Title</XDSHeading>',
+ code: '<XDSHeading level={1}>Page Title</XDSHeading>',
},
{
label: '带工具提示的截断文本',
@@ -391,7 +353,7 @@ export const docsZh = {
},
{
label: '原生 HTML 字体包装器',
- code: `<XDSFontWrapper variant="editorial">
+ code: `<XDSFontWrapper>
<article dangerouslySetInnerHTML={{__html: markdownContent}} />
</XDSFontWrapper>`,
},
@@ -408,7 +370,7 @@ export const docsZh = {
],
theming: {
targets: [
- {className: 'xds-heading', visualProps: ['level', 'variant']},
+ {className: 'xds-heading', visualProps: ['level']},
{className: 'xds-text', visualProps: ['type']},
],
},
@@ -561,7 +523,7 @@ export const docsZh = {
},
{
label: '编辑风格比例',
- code: '<XDSHeading level={1} variant="editorial">Article Title</XDSHeading>',
+ code: '<XDSHeading level={1}>Page Title</XDSHeading>',
},
{
label: '无障碍级别覆盖',
@@ -596,13 +558,6 @@ export const docsZh = {
description:
'无障碍级别覆盖。当设置且与 `level` 不同时,应用 `aria-level` 使文档大纲与视觉样式不同。',
},
- {
- name: 'variant',
- type: "'default' | 'editorial'",
- description:
- "视觉变体。'default' 使用紧凑比例用于内部工具(h1: 20px);'editorial' 使用更大比例用于内容密集页面(h1: 32px)。",
- default: "'default'",
- },
{
name: 'color',
type: "'primary' | 'secondary' | 'disabled' | 'placeholder' | 'active' | 'inherit'",
@@ -679,7 +634,7 @@ export const docsZh = {
},
{
label: '编辑风格变体',
- code: `<XDSFontWrapper variant="editorial">
+ code: `<XDSFontWrapper>
<article dangerouslySetInnerHTML={{__html: markdownContent}} />
</XDSFontWrapper>`,
},
@@ -691,13 +646,6 @@ export const docsZh = {
description: '要应用 XDS 排版样式的内容。',
required: true,
},
- {
- name: 'variant',
- type: "'default' | 'editorial'",
- description:
- "标题比例变体。'default' 使用紧凑比例用于内部工具;'editorial' 使用更大比例用于内容密集页面。",
- default: "'default'",
- },
],
},
{
@@ -770,12 +718,12 @@ export const docsDense = {
},
{
name: 'XDSHeading',
- description: 'Semantic h1\u20136 w/ themed styling, optional editorial scale, line-clamp truncation.',
+ description: 'Semantic h1\u20136 w/ themed styling, themed sizing via type scale tokens, line-clamp truncation.',
propDescriptions: {
level: 'Visual heading level; determines HTML element + styling from theme.',
children: 'Heading content.',
accessibilityLevel: 'aria-level override when different from level for document outline.',
- variant: "Visual variant; 'default'=dense scale (h1:20px), 'editorial'=larger (h1:32px).",
+
color: 'Text color.',
display: "Display type; overridden to 'block' when maxLines>0 or hasCapsize.",
maxLines: 'Max lines before truncation; 0=none. Shows tooltip if truncated.',
@@ -792,7 +740,7 @@ export const docsDense = {
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.',
- variant: "Heading scale; 'default'=dense for tools, 'editorial'=larger for content pages.",
+
},
},
{
diff --git a/packages/core/src/Text/XDSFontWrapper.test.tsx b/packages/core/src/Text/XDSFontWrapper.test.tsx
index 6916ab3fd7..10fc3c2864 100644
--- a/packages/core/src/Text/XDSFontWrapper.test.tsx
+++ b/packages/core/src/Text/XDSFontWrapper.test.tsx
@@ -21,7 +21,7 @@ describe('XDSFontWrapper', () => {
expect(screen.getByText('Test paragraph')).toBeInTheDocument();
});
- it('applies default variant classes', () => {
+ it('applies typography class', () => {
render(
<XDSFontWrapper data-testid="wrapper">
<p>Content</p>
@@ -31,20 +31,18 @@ describe('XDSFontWrapper', () => {
const wrapper = screen.getByTestId('wrapper');
expect(wrapper).toBeInTheDocument();
expect(wrapper).toHaveClass('xds-typography');
- expect(wrapper).toHaveClass('xds-typography--default');
});
- it('applies editorial variant classes', () => {
+ it('does not include variant classes', () => {
render(
- <XDSFontWrapper variant="editorial" data-testid="wrapper">
+ <XDSFontWrapper data-testid="wrapper">
<p>Content</p>
</XDSFontWrapper>,
);
const wrapper = screen.getByTestId('wrapper');
- expect(wrapper).toBeInTheDocument();
- expect(wrapper).toHaveClass('xds-typography');
- expect(wrapper).toHaveClass('xds-typography--editorial');
+ expect(wrapper.className).not.toContain('--default');
+ expect(wrapper.className).not.toContain('--editorial');
});
it('renders all prose elements', () => {
diff --git a/packages/core/src/Text/XDSFontWrapper.tsx b/packages/core/src/Text/XDSFontWrapper.tsx
index 892517ab92..f7a57152b4 100644
--- a/packages/core/src/Text/XDSFontWrapper.tsx
+++ b/packages/core/src/Text/XDSFontWrapper.tsx
@@ -1,8 +1,15 @@
/**
* @file XDSFontWrapper.tsx
- * @input Uses React, reset.css
+ * @input Uses React, typography.css
* @output Exports XDSFontWrapper component
- * @position Typography component; provides base styles for wrapped content
+ * @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
@@ -12,23 +19,10 @@
import * as React from 'react';
import '../typography.css';
-/**
- * Heading scale variant
- */
-export type XDSFontWrapperVariant = 'default' | 'editorial';
-
/**
* Props for XDSFontWrapper
*/
export interface XDSFontWrapperProps {
- /**
- * Heading scale variant
- * - 'default': Dense scale for internal tools (h1: 20px)
- * - 'editorial': Larger scale for content-heavy pages (h1: 32px)
- * @default 'default'
- */
- variant?: XDSFontWrapperVariant;
-
/**
* Children to render
*/
@@ -44,7 +38,11 @@ export interface XDSFontWrapperProps {
* XDSFontWrapper
*
* Applies base typography styles to native HTML elements within its scope.
- * Uses the reset.css stylesheet which references theme CSS custom properties.
+ * 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
* ```
@@ -56,25 +54,14 @@ export interface XDSFontWrapperProps {
* <li>List item 2</li>
* </ul>
* </XDSFontWrapper>
- * <XDSFontWrapper variant="editorial">
- * <h1>Article Title</h1>
- * <p>Body text for long-form content.</p>
- * </XDSFontWrapper>
* ```
*/
export function XDSFontWrapper({
- variant = 'default',
children,
'data-testid': testId,
}: XDSFontWrapperProps): React.ReactElement {
- // Combine CSS typography class for prose styling
- const typographyClass =
- variant === 'editorial'
- ? 'xds-typography xds-typography--editorial'
- : 'xds-typography xds-typography--default';
-
return (
- <div className={typographyClass} data-testid={testId}>
+ <div className="xds-typography" data-testid={testId}>
{children}
</div>
);
@@ -92,7 +79,6 @@ export function useXDSFontWrapperStyles() {
return {
base: undefined,
headingStyles: undefined,
- editorialHeadingStyles: undefined,
proseStyles: undefined,
};
}
diff --git a/packages/core/src/Text/XDSHeading.test.tsx b/packages/core/src/Text/XDSHeading.test.tsx
index 42784a04f3..d56100be7c 100644
--- a/packages/core/src/Text/XDSHeading.test.tsx
+++ b/packages/core/src/Text/XDSHeading.test.tsx
@@ -51,22 +51,6 @@ describe('XDSHeading', () => {
});
});
- describe('variants', () => {
- it('uses default variant by default', () => {
- render(<XDSHeading level={1}>Default Heading</XDSHeading>);
- expect(screen.getByText('Default Heading')).toBeInTheDocument();
- });
-
- it('supports editorial variant', () => {
- render(
- <XDSHeading level={1} variant="editorial">
- Editorial Heading
- </XDSHeading>,
- );
- expect(screen.getByText('Editorial Heading')).toBeInTheDocument();
- });
- });
-
describe('props', () => {
it('forwards additional props', () => {
render(
@@ -179,4 +163,11 @@ describe('XDSHeading', () => {
expect(element.className).toContain('xds-heading');
expect(element.className).toContain('level-2');
});
+
+ it('does not include variant in class names', () => {
+ render(<XDSHeading level={1}>No Variant</XDSHeading>);
+ const element = screen.getByText('No Variant');
+ expect(element.className).not.toContain('default');
+ expect(element.className).not.toContain('editorial');
+ });
});
diff --git a/packages/core/src/Text/XDSHeading.tsx b/packages/core/src/Text/XDSHeading.tsx
index 60c89354c3..82e1a76597 100644
--- a/packages/core/src/Text/XDSHeading.tsx
+++ b/packages/core/src/Text/XDSHeading.tsx
@@ -1,7 +1,7 @@
/**
* @file XDSHeading.tsx
* @input Uses React, HTMLAttributes, ReactNode
- * @output Exports XDSHeading component, XDSHeadingProps, XDSHeadingLevel, XDSHeadingVariant types
+ * @output Exports XDSHeading component, XDSHeadingProps, XDSHeadingLevel types
* @position Core implementation; consumed by index.ts, tested by XDSHeading.test.tsx
*
* SYNC: When modified, update these files to stay in sync:
@@ -45,11 +45,6 @@ const LazyXDSTooltip = lazy(() =>
*/
export type XDSHeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
-/**
- * Heading variant determines the size scale used
- */
-export type XDSHeadingVariant = 'default' | 'editorial';
-
export interface XDSHeadingProps {
/** Ref forwarded to the root element */
ref?: React.Ref<HTMLHeadingElement>;
@@ -73,14 +68,6 @@ export interface XDSHeadingProps {
*/
accessibilityLevel?: XDSHeadingLevel;
- /**
- * Visual variant. Themes define different scales for each variant.
- * - 'default': Dense scale for internal tools (h1: 20px)
- * - 'editorial': Larger scale for content-heavy pages (h1: 32px)
- * @default 'default'
- */
- variant?: XDSHeadingVariant;
-
/**
* Text color.
* @default 'primary'
@@ -183,7 +170,6 @@ const levelToTag = {
* ```
* <XDSHeading level={1}>Page Title</XDSHeading>
* <XDSHeading level={2}>Section</XDSHeading>
- * <XDSHeading level={1} variant="editorial">Article Title</XDSHeading>
* <XDSHeading level={2} accessibilityLevel={3}>Sidebar Section</XDSHeading>
* <XDSHeading level={2} maxLines={1}>Very Long Section Title...</XDSHeading>
* <XDSHeading level={3} color="secondary">Muted Heading</XDSHeading>
@@ -192,7 +178,6 @@ const levelToTag = {
export function XDSHeading({
level,
accessibilityLevel,
- variant = 'default',
color = 'primary',
display = 'block',
maxLines = 0,
@@ -262,7 +247,7 @@ export function XDSHeading({
<Component
ref={mergedRef}
{...mergeProps(
- xdsClassName('heading', {variant, level}),
+ xdsClassName('heading', {level}),
stylex.props(
colorStyles[color],
// Display: use truncation styles when maxLines > 0
diff --git a/packages/core/src/Text/index.ts b/packages/core/src/Text/index.ts
index 4368aa7157..5f47c2e9e0 100644
--- a/packages/core/src/Text/index.ts
+++ b/packages/core/src/Text/index.ts
@@ -13,13 +13,11 @@ export {
XDSHeading,
type XDSHeadingProps,
type XDSHeadingLevel,
- type XDSHeadingVariant,
} from './XDSHeading';
export {
XDSFontWrapper,
useXDSFontWrapperStyles,
type XDSFontWrapperProps,
- type XDSFontWrapperVariant,
} from './XDSFontWrapper';
// Re-export shared types from theme for convenience
diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.ts
index 6928e594e9..c728e5e6d1 100644
--- a/packages/core/src/theme/defineTheme.test.ts
+++ b/packages/core/src/theme/defineTheme.test.ts
@@ -229,3 +229,141 @@ describe('generateThemeCSS with components', () => {
expect(css).toContain('border-width: 1px');
});
});
+
+describe('typeScale', () => {
+ it('generates typography token overrides when typeScale is provided', () => {
+ const theme = defineTheme({
+ name: 'dense',
+ typeScale: {base: 12, ratio: 1.125},
+ });
+ expect(theme.tokens['--heading-4-size']).toBe('12px');
+ expect(theme.tokens['--text-body-size']).toBe('12px');
+ });
+
+ it('generates all 33 type scale tokens', () => {
+ const theme = defineTheme({
+ name: 'custom',
+ typeScale: {base: 14, ratio: 1.2},
+ });
+ // 6 heading levels × 3 props + 5 text types × 3 props = 33
+ const typeScaleKeys = Object.keys(theme.tokens).filter(
+ k => k.startsWith('--heading-') || k.startsWith('--text-'),
+ );
+ expect(typeScaleKeys).toHaveLength(33);
+ });
+
+ it('explicit tokens override typeScale-generated values', () => {
+ const theme = defineTheme({
+ name: 'override-test',
+ typeScale: {base: 14, ratio: 1.2},
+ tokens: {
+ '--heading-1-size': '40px',
+ },
+ });
+ // 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');
+ });
+
+ it('works without typeScale (backwards compatible)', () => {
+ const theme = defineTheme({name: 'no-scale'});
+ // No type scale tokens should be present
+ expect(theme.tokens['--heading-1-size']).toBeUndefined();
+ });
+
+ it('combines typeScale with other token overrides', () => {
+ const theme = defineTheme({
+ name: 'combo',
+ typeScale: {base: 16, ratio: 1.25},
+ tokens: {
+ '--color-accent': '#FF0000',
+ },
+ });
+ expect(theme.tokens['--color-accent']).toBe('#FF0000');
+ expect(theme.tokens['--heading-4-size']).toBe('16px');
+ });
+});
+
+describe('typeScale component auto-generation', () => {
+ it('auto-generates heading component overrides when typeScale is provided', () => {
+ const theme = defineTheme({
+ name: 'auto',
+ typeScale: {base: 14, ratio: 1.2},
+ });
+ expect(theme.components?.heading?.['level:1']).toBeDefined();
+ expect(theme.components?.heading?.['level:1']?.fontSize).toBe(
+ 'var(--heading-1-size)',
+ );
+ });
+
+ it('auto-generates text component overrides when typeScale is provided', () => {
+ const theme = defineTheme({
+ name: 'auto',
+ typeScale: {base: 14, ratio: 1.2},
+ });
+ expect(theme.components?.text?.['type:body']).toBeDefined();
+ expect(theme.components?.text?.['type:body']?.fontSize).toBe(
+ 'var(--text-body-size)',
+ );
+ });
+
+ it('does not include color in auto-generated rules', () => {
+ const theme = defineTheme({
+ name: 'auto',
+ typeScale: {base: 14, ratio: 1.2},
+ });
+ expect(theme.components?.heading?.['level:1']?.color).toBeUndefined();
+ expect(theme.components?.text?.['type:supporting']?.color).toBeUndefined();
+ });
+
+ it('explicit components deep-merge on top of auto-generated', () => {
+ const theme = defineTheme({
+ name: 'custom',
+ typeScale: {base: 14, ratio: 1.2},
+ components: {
+ heading: {
+ 'level:1': {letterSpacing: '-0.02em'},
+ },
+ button: {
+ base: {borderRadius: '999px'},
+ },
+ },
+ });
+ // Auto-generated heading props still present
+ expect(theme.components?.heading?.['level:1']?.fontSize).toBe(
+ 'var(--heading-1-size)',
+ );
+ // Explicit override merged on top
+ expect(theme.components?.heading?.['level:1']?.letterSpacing).toBe(
+ '-0.02em',
+ );
+ // Non-typography component preserved
+ expect(theme.components?.button?.base?.borderRadius).toBe('999px');
+ });
+
+ it('does not generate components when typeScale is absent', () => {
+ const theme = defineTheme({name: 'bare'});
+ expect(theme.components).toBeUndefined();
+ });
+
+ it('explicit heading overrides win over auto-generated', () => {
+ const theme = defineTheme({
+ name: 'override',
+ typeScale: {base: 14, ratio: 1.2},
+ components: {
+ heading: {
+ 'level:1': {fontFamily: '"Playfair Display", serif'},
+ },
+ },
+ });
+ // Explicit fontFamily wins
+ expect(theme.components?.heading?.['level:1']?.fontFamily).toBe(
+ '"Playfair Display", serif',
+ );
+ // Auto-generated fontSize still present
+ expect(theme.components?.heading?.['level:1']?.fontSize).toBe(
+ 'var(--heading-1-size)',
+ );
+ });
+});
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index 5852eb8c52..a16d88f368 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -41,7 +41,13 @@ import {
textSizeDefaults,
lineHeightDefaults,
fontWeightDefaults,
+ typeScaleDefaults,
} from './tokens.stylex';
+import {
+ expandTypeScale,
+ generateTypeScaleComponents,
+ type XDSTypeScaleConfig,
+} from './expandTypeScale';
// =============================================================================
// Types
@@ -58,7 +64,8 @@ export type XDSTokenName =
| keyof typeof typographyDefaults
| keyof typeof textSizeDefaults
| keyof typeof lineHeightDefaults
- | keyof typeof fontWeightDefaults;
+ | keyof typeof fontWeightDefaults
+ | keyof typeof typeScaleDefaults;
/**
* Token value — either a single string or a [light, dark] tuple.
@@ -106,6 +113,27 @@ export type XDSComponentStyleMap = Record<
export interface XDSDefineThemeInput {
/** Theme name — used for data-xds-theme attribute and identification */
name: string;
+ /**
+ * Optional type scale configuration. Generates typography token overrides
+ * from a base size and scaling ratio using a geometric progression.
+ *
+ * h4 is anchored to `base`. Headings h1–h3 scale up, h5–h6 scale down.
+ * Text types: body/label/code at base, large one step up, supporting one step down.
+ *
+ * When omitted, themes use the hardcoded defaults (base=14, ratio=1.2).
+ * Explicit `tokens` overrides take precedence over typeScale-generated values.
+ *
+ * @example
+ * ```tsx
+ * typeScale: { base: 14, ratio: 1.2 }
+ *
+ * // Suggested starting points:
+ * // Dense/functional: { base: 12, ratio: 1.125 }
+ * // Default: { base: 14, ratio: 1.2 }
+ * // Airy/editorial: { base: 16, ratio: 1.25 }
+ * ```
+ */
+ typeScale?: XDSTypeScaleConfig;
/** Token overrides — flat map of CSS custom property names to values.
* Values can be a string or [light, dark] tuple.
* Only include tokens you want to override; defaults fill the rest. */
@@ -165,6 +193,7 @@ export const xdsTokenDefaults: Record<string, string> = {
...textSizeDefaults,
...lineHeightDefaults,
...fontWeightDefaults,
+ ...typeScaleDefaults,
};
// =============================================================================
@@ -183,15 +212,65 @@ function resolveTokenValue(value: XDSTokenValue): string {
return value;
}
+/**
+ * Deep-merge two component style maps.
+ * Properties in `overrides` take precedence over `base`.
+ * This allows typeScale-generated rules to be overridden by explicit components.
+ */
+function deepMergeComponents(
+ base?: XDSComponentStyleMap,
+ overrides?: XDSComponentStyleMap,
+): XDSComponentStyleMap | undefined {
+ if (!base && !overrides) return undefined;
+ if (!base) return overrides;
+ if (!overrides) return base;
+
+ const result: XDSComponentStyleMap = {};
+
+ // Start with all base entries
+ for (const [component, rules] of Object.entries(base)) {
+ result[component] = {...rules};
+ }
+
+ // Merge overrides on top
+ for (const [component, rules] of Object.entries(overrides)) {
+ if (!result[component]) {
+ result[component] = {...rules};
+ } else {
+ for (const [key, styles] of Object.entries(rules)) {
+ result[component][key] = {
+ ...result[component][key],
+ ...styles,
+ };
+ }
+ }
+ }
+
+ return result;
+}
+
/**
* Create an XDS theme.
*
* Pass only the tokens you want to override — everything else
* inherits from the XDS defaults.
+ *
+ * When `typeScale` is provided, it generates typography token overrides
+ * that are merged into the token map. Explicit `tokens` entries take
+ * precedence over typeScale-generated values.
*/
export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {
const tokens: Record<string, string> = {};
+ // 1. Apply typeScale-generated tokens first (lowest precedence)
+ if (input.typeScale) {
+ const typeScaleTokens = expandTypeScale(input.typeScale);
+ for (const [key, value] of Object.entries(typeScaleTokens)) {
+ tokens[key] = value;
+ }
+ }
+
+ // 2. Apply explicit token overrides (highest precedence — overwrites typeScale)
if (input.tokens) {
for (const [key, value] of Object.entries(input.tokens)) {
if (value !== undefined) {
@@ -206,10 +285,17 @@ export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {
}
}
+ // 3. Generate component overrides: typeScale-generated (lowest) + explicit (highest)
+ let components = input.components;
+ if (input.typeScale) {
+ const generated = generateTypeScaleComponents(input.typeScale);
+ components = deepMergeComponents(generated, input.components);
+ }
+
return {
name: input.name,
tokens,
- components: input.components,
+ components,
icons: input.icons,
};
}
diff --git a/packages/core/src/theme/expandTypeScale.test.ts b/packages/core/src/theme/expandTypeScale.test.ts
new file mode 100644
index 0000000000..1a70fb1340
--- /dev/null
+++ b/packages/core/src/theme/expandTypeScale.test.ts
@@ -0,0 +1,266 @@
+/**
+ * @file expandTypeScale.test.ts
+ * Tests for the type scale computation function.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {expandTypeScale, generateTypeScaleComponents} from './expandTypeScale';
+
+describe('expandTypeScale', () => {
+ describe('default scale (base=14, ratio=1.2)', () => {
+ const tokens = expandTypeScale({base: 14, ratio: 1.2});
+
+ it('generates 33 tokens', () => {
+ expect(Object.keys(tokens)).toHaveLength(33);
+ });
+
+ it('anchors h4 to base size', () => {
+ expect(tokens['--heading-4-size']).toBe('14px');
+ });
+
+ 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');
+ });
+
+ 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');
+ });
+
+ it('computes large text one step up', () => {
+ // 14 × 1.2¹ ≈ 16.8 → 17px
+ expect(tokens['--text-large-size']).toBe('17px');
+ });
+
+ it('computes supporting text one step down', () => {
+ // 14 × 1.2⁻¹ ≈ 11.67 → 12px
+ expect(tokens['--text-supporting-size']).toBe('12px');
+ });
+
+ it('emits unitless line-height ratios', () => {
+ // Line heights should be unitless numbers, not px values
+ for (const [key, value] of Object.entries(tokens)) {
+ if (key.endsWith('-leading')) {
+ expect(value).not.toContain('px');
+ const num = parseFloat(value);
+ expect(num).toBeGreaterThan(1);
+ expect(num).toBeLessThan(2);
+ }
+ }
+ });
+
+ it('snaps line heights to 4px grid', () => {
+ // Each leading ratio × font size should be divisible by 4
+ for (const [key, value] of Object.entries(tokens)) {
+ if (key.endsWith('-leading')) {
+ const sizeKey = key.replace('-leading', '-size');
+ const fontSize = parseInt(tokens[sizeKey]);
+ const ratio = parseFloat(value);
+ const computedLh = Math.round(fontSize * ratio);
+ expect(computedLh % 4).toBe(0);
+ }
+ }
+ });
+
+ it('ensures computed line height is at least fontSize + 4', () => {
+ for (const [key, value] of Object.entries(tokens)) {
+ if (key.endsWith('-leading')) {
+ const sizeKey = key.replace('-leading', '-size');
+ const fontSize = parseInt(tokens[sizeKey]);
+ const ratio = parseFloat(value);
+ const computedLh = Math.round(fontSize * ratio);
+ expect(computedLh).toBeGreaterThanOrEqual(fontSize + 4);
+ }
+ }
+ });
+
+ it('assigns semibold weight to all headings', () => {
+ for (let level = 1; level <= 6; level++) {
+ expect(tokens[`--heading-${level}-weight`]).toBe(
+ 'var(--font-weight-semibold)',
+ );
+ }
+ });
+
+ it('assigns correct weights to text types', () => {
+ expect(tokens['--text-body-weight']).toBe('var(--font-weight-normal)');
+ expect(tokens['--text-large-weight']).toBe('var(--font-weight-semibold)');
+ expect(tokens['--text-label-weight']).toBe('var(--font-weight-medium)');
+ expect(tokens['--text-code-weight']).toBe('var(--font-weight-normal)');
+ expect(tokens['--text-supporting-weight']).toBe(
+ 'var(--font-weight-normal)',
+ );
+ });
+ });
+
+ describe('dense scale (base=12, ratio=1.125)', () => {
+ const tokens = expandTypeScale({base: 12, ratio: 1.125});
+
+ it('anchors h4 to base 12px', () => {
+ expect(tokens['--heading-4-size']).toBe('12px');
+ });
+
+ 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');
+ });
+
+ it('keeps body at base', () => {
+ expect(tokens['--text-body-size']).toBe('12px');
+ });
+ });
+
+ describe('airy scale (base=16, ratio=1.25)', () => {
+ const tokens = expandTypeScale({base: 16, ratio: 1.25});
+
+ it('anchors h4 to base 16px', () => {
+ expect(tokens['--heading-4-size']).toBe('16px');
+ });
+
+ 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');
+ });
+
+ it('keeps body at base', () => {
+ expect(tokens['--text-body-size']).toBe('16px');
+ });
+ });
+
+ describe('weight overrides', () => {
+ it('applies heading weight overrides', () => {
+ const tokens = expandTypeScale({
+ base: 14,
+ ratio: 1.2,
+ weights: {
+ heading: {1: 'var(--font-weight-bold)', 3: 'var(--font-weight-bold)'},
+ },
+ });
+ expect(tokens['--heading-1-weight']).toBe('var(--font-weight-bold)');
+ expect(tokens['--heading-2-weight']).toBe('var(--font-weight-semibold)');
+ expect(tokens['--heading-3-weight']).toBe('var(--font-weight-bold)');
+ });
+
+ it('applies text weight overrides', () => {
+ const tokens = expandTypeScale({
+ base: 14,
+ ratio: 1.2,
+ weights: {
+ text: {large: 'var(--font-weight-normal)'},
+ },
+ });
+ expect(tokens['--text-large-weight']).toBe('var(--font-weight-normal)');
+ expect(tokens['--text-body-weight']).toBe('var(--font-weight-normal)');
+ });
+
+ it('applies both heading and text weight overrides', () => {
+ const tokens = expandTypeScale({
+ base: 14,
+ ratio: 1.2,
+ weights: {
+ heading: {1: '700'},
+ text: {body: '500'},
+ },
+ });
+ expect(tokens['--heading-1-weight']).toBe('700');
+ expect(tokens['--text-body-weight']).toBe('500');
+ });
+
+ it('uses defaults for unspecified weights', () => {
+ const tokens = expandTypeScale({
+ base: 14,
+ ratio: 1.2,
+ weights: {heading: {1: '700'}},
+ });
+ // Only h1 is overridden, rest use defaults
+ expect(tokens['--heading-2-weight']).toBe('var(--font-weight-semibold)');
+ expect(tokens['--text-body-weight']).toBe('var(--font-weight-normal)');
+ });
+ });
+
+ describe('token naming', () => {
+ const tokens = expandTypeScale({base: 14, ratio: 1.2});
+
+ it('uses --heading-{level}-{prop} for headings', () => {
+ for (let level = 1; level <= 6; level++) {
+ expect(tokens).toHaveProperty(`--heading-${level}-size`);
+ expect(tokens).toHaveProperty(`--heading-${level}-weight`);
+ expect(tokens).toHaveProperty(`--heading-${level}-leading`);
+ }
+ });
+
+ it('uses --text-{type}-{prop} for text', () => {
+ for (const type of ['body', 'large', 'label', 'code', 'supporting']) {
+ expect(tokens).toHaveProperty(`--text-${type}-size`);
+ expect(tokens).toHaveProperty(`--text-${type}-weight`);
+ expect(tokens).toHaveProperty(`--text-${type}-leading`);
+ }
+ });
+ });
+});
+
+describe('generateTypeScaleComponents', () => {
+ it('generates heading and text component keys', () => {
+ const components = generateTypeScaleComponents({base: 14, ratio: 1.2});
+ expect(components).toHaveProperty('heading');
+ expect(components).toHaveProperty('text');
+ });
+
+ it('generates rules for all 6 heading levels', () => {
+ const components = generateTypeScaleComponents({base: 14, ratio: 1.2});
+ for (let level = 1; level <= 6; level++) {
+ expect(components.heading).toHaveProperty(`level:${level}`);
+ }
+ });
+
+ it('generates rules for all 5 text types', () => {
+ const components = generateTypeScaleComponents({base: 14, ratio: 1.2});
+ for (const type of ['body', 'large', 'label', 'code', 'supporting']) {
+ expect(components.text).toHaveProperty(`type:${type}`);
+ }
+ });
+
+ it('heading rules include fontFamily, fontSize, fontWeight, lineHeight', () => {
+ const components = generateTypeScaleComponents({base: 14, ratio: 1.2});
+ const h1 = components.heading['level:1'];
+ expect(h1.fontFamily).toBe('var(--font-heading)');
+ expect(h1.fontSize).toBe('var(--heading-1-size)');
+ expect(h1.fontWeight).toBe('var(--heading-1-weight)');
+ expect(h1.lineHeight).toBe('var(--heading-1-leading)');
+ });
+
+ it('text rules include fontFamily, fontSize, fontWeight, lineHeight', () => {
+ const components = generateTypeScaleComponents({base: 14, ratio: 1.2});
+ const body = components.text['type:body'];
+ expect(body.fontFamily).toBe('var(--font-body)');
+ expect(body.fontSize).toBe('var(--text-body-size)');
+ expect(body.fontWeight).toBe('var(--text-body-weight)');
+ expect(body.lineHeight).toBe('var(--text-body-leading)');
+ });
+
+ it('code text uses font-code family', () => {
+ const components = generateTypeScaleComponents({base: 14, ratio: 1.2});
+ expect(components.text['type:code'].fontFamily).toBe('var(--font-code)');
+ });
+
+ it('does NOT include color (handled by component internals)', () => {
+ const components = generateTypeScaleComponents({base: 14, ratio: 1.2});
+ expect(components.heading['level:1'].color).toBeUndefined();
+ expect(components.text['type:body'].color).toBeUndefined();
+ expect(components.text['type:supporting'].color).toBeUndefined();
+ });
+});
diff --git a/packages/core/src/theme/expandTypeScale.ts b/packages/core/src/theme/expandTypeScale.ts
new file mode 100644
index 0000000000..04f2a31a70
--- /dev/null
+++ b/packages/core/src/theme/expandTypeScale.ts
@@ -0,0 +1,301 @@
+/**
+ * @file expandTypeScale.ts
+ * @input Type scale configuration { base, ratio, weights? }
+ * @output Token overrides for heading and text typography
+ * @position Theme utility; consumed by defineTheme.ts
+ *
+ * Computes font sizes, weights, and line heights from a base size and
+ * scaling ratio using a geometric progression: size = base × ratio^step.
+ *
+ * The heading scale is anchored at h4 = base. Headings h1–h3 scale up,
+ * h5–h6 scale down. Text types are mapped to fixed steps relative to base.
+ *
+ * Line heights are unitless ratios, snapped so the computed px value
+ * aligns to a 4px grid for visual rhythm.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/theme/expandTypeScale.test.ts
+ * - /packages/core/src/theme/defineTheme.ts
+ */
+
+// =============================================================================
+// Types
+// =============================================================================
+
+/** Font weight value — either a CSS string or a var() reference. */
+export type FontWeightValue = string;
+
+/**
+ * Weight overrides for heading levels.
+ * Keys are heading levels 1–6, values are CSS font-weight values
+ * (e.g. '600', 'var(--font-weight-bold)').
+ */
+export type HeadingWeightOverrides = Partial<
+ Record<1 | 2 | 3 | 4 | 5 | 6, FontWeightValue>
+>;
+
+/**
+ * Weight overrides for text types.
+ * Keys are text type names, values are CSS font-weight values.
+ */
+export type TextWeightOverrides = Partial<
+ Record<'body' | 'large' | 'label' | 'code' | 'supporting', FontWeightValue>
+>;
+
+/**
+ * Type scale configuration.
+ *
+ * @example
+ * ```
+ * // Default XDS type scale
+ * { base: 14, ratio: 1.2 }
+ *
+ * // With custom weights
+ * {
+ * base: 14,
+ * ratio: 1.2,
+ * weights: {
+ * heading: { 1: 'var(--font-weight-bold)', 3: 'var(--font-weight-bold)' },
+ * text: { large: 'var(--font-weight-normal)' },
+ * },
+ * }
+ *
+ * // Suggested starting points:
+ * // Dense/functional: { base: 12, ratio: 1.125 }
+ * // Default: { base: 14, ratio: 1.2 }
+ * // Airy/editorial: { base: 16, ratio: 1.25 }
+ * ```
+ */
+export interface XDSTypeScaleConfig {
+ /** Base font size in px. Anchored to h4 and body text. */
+ base: number;
+ /** Scaling ratio for the geometric progression. */
+ ratio: number;
+ /** Optional weight overrides for headings and text types. */
+ weights?: {
+ /** Per-level heading weight overrides. Unset levels use the defaults. */
+ heading?: HeadingWeightOverrides;
+ /** Per-type text weight overrides. Unset types use the defaults. */
+ text?: TextWeightOverrides;
+ };
+}
+
+/**
+ * Generated typography token overrides.
+ * Keys are CSS custom property names, values are CSS strings.
+ */
+export type TypeScaleTokens = Record<string, string>;
+
+// =============================================================================
+// Constants
+// =============================================================================
+
+/**
+ * Heading level → step offset from base (h4 = 0).
+ * h1 is 3 steps above base, h6 is 2 steps below.
+ */
+const HEADING_STEPS: Record<number, number> = {
+ 1: 3,
+ 2: 2,
+ 3: 1,
+ 4: 0,
+ 5: -1,
+ 6: -2,
+};
+
+/**
+ * Text type → step offset from base.
+ * body/label/code are at base, large is one step up, supporting one step down.
+ */
+const TEXT_STEPS: Record<string, number> = {
+ body: 0,
+ large: 1,
+ label: 0,
+ code: 0,
+ supporting: -1,
+};
+
+/**
+ * Default font weights per heading level.
+ * Themes can override individual levels via weights.heading in the config.
+ */
+const DEFAULT_HEADING_WEIGHTS: Record<number, string> = {
+ 1: 'var(--font-weight-semibold)',
+ 2: 'var(--font-weight-semibold)',
+ 3: 'var(--font-weight-semibold)',
+ 4: 'var(--font-weight-semibold)',
+ 5: 'var(--font-weight-semibold)',
+ 6: 'var(--font-weight-semibold)',
+};
+
+/**
+ * Default font weights per text type.
+ * Themes can override individual types via weights.text in the config.
+ */
+const DEFAULT_TEXT_WEIGHTS: Record<string, string> = {
+ body: 'var(--font-weight-normal)',
+ large: 'var(--font-weight-semibold)',
+ label: 'var(--font-weight-medium)',
+ code: 'var(--font-weight-normal)',
+ supporting: 'var(--font-weight-normal)',
+};
+
+/**
+ * Line-height target ratios. Headings are tighter, body text is more generous.
+ */
+const HEADING_LH_RATIO = 1.3;
+const TEXT_LH_RATIOS: Record<string, number> = {
+ body: 1.5,
+ large: 1.45,
+ label: 1.4,
+ code: 1.5,
+ supporting: 1.5,
+};
+
+// =============================================================================
+// Computation
+// =============================================================================
+
+/**
+ * Compute a font size from the geometric progression and round to nearest integer.
+ */
+function computeSize(base: number, ratio: number, step: number): number {
+ return Math.round(base * Math.pow(ratio, step));
+}
+
+/**
+ * Compute a unitless line-height ratio, snapped so the computed px value
+ * aligns to a 4px grid. Ensures a minimum of fontSize + 4px for readability.
+ *
+ * Returns a unitless number (e.g. 1.3333) — not a px value — so line-height
+ * scales proportionally when StyleX converts font sizes to relative units.
+ */
+function computeLeading(fontSize: number, targetRatio: number): number {
+ const rawLh = fontSize * targetRatio;
+ const snappedLh = Math.max(Math.ceil(rawLh / 4) * 4, fontSize + 4);
+ // Round to 4 decimal places for clean CSS output
+ return Math.round((snappedLh / fontSize) * 10000) / 10000;
+}
+
+/**
+ * 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').
+ * 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-leading'] === '1.3333'
+ * // tokens['--heading-4-size'] === '14px' (anchor)
+ * // tokens['--text-body-size'] === '14px'
+ * ```
+ */
+export function expandTypeScale(config: XDSTypeScaleConfig): TypeScaleTokens {
+ const {base, ratio, weights} = config;
+ const tokens: TypeScaleTokens = {};
+
+ // Merge weight overrides with defaults
+ const headingWeights = {
+ ...DEFAULT_HEADING_WEIGHTS,
+ ...(weights?.heading as Record<number, string> | undefined),
+ };
+ const textWeights = {
+ ...DEFAULT_TEXT_WEIGHTS,
+ ...(weights?.text as Record<string, string> | undefined),
+ };
+
+ // Heading tokens
+ for (const [levelStr, step] of Object.entries(HEADING_STEPS)) {
+ const level = Number(levelStr);
+ const size = computeSize(base, ratio, step);
+ const leading = computeLeading(size, HEADING_LH_RATIO);
+
+ tokens[`--heading-${level}-size`] = `${size}px`;
+ tokens[`--heading-${level}-weight`] = headingWeights[level];
+ tokens[`--heading-${level}-leading`] = `${leading}`;
+ }
+
+ // Text tokens
+ for (const [type, step] of Object.entries(TEXT_STEPS)) {
+ const size = computeSize(base, ratio, step);
+ const leading = computeLeading(size, TEXT_LH_RATIOS[type]);
+
+ tokens[`--text-${type}-size`] = `${size}px`;
+ tokens[`--text-${type}-weight`] = textWeights[type];
+ tokens[`--text-${type}-leading`] = `${leading}`;
+ }
+
+ return tokens;
+}
+
+// =============================================================================
+// Component override generation
+// =============================================================================
+
+/**
+ * Font family mapping for auto-generated component overrides.
+ * Code text uses the code font; everything else uses the heading/body font.
+ */
+const TEXT_FONT_FAMILIES: Record<string, string> = {
+ body: 'var(--font-body)',
+ large: 'var(--font-body)',
+ label: 'var(--font-body)',
+ code: 'var(--font-code)',
+ supporting: 'var(--font-body)',
+};
+
+/**
+ * Generate component style overrides for heading and text components
+ * from a type scale configuration.
+ *
+ * Produces rules like:
+ * heading: { 'level:1': { fontFamily, fontSize, fontWeight, lineHeight } }
+ * text: { 'type:body': { fontFamily, fontSize, fontWeight, lineHeight } }
+ *
+ * Color is intentionally excluded — it's handled by component internals
+ * (XDSHeading defaults to primary, XDSText has per-type defaults).
+ * Including color here would duplicate component logic and risk specificity
+ * conflicts with the color prop.
+ *
+ * @example
+ * ```
+ * const components = generateTypeScaleComponents({ base: 14, ratio: 1.2 });
+ * // components.heading['level:1'].fontSize === 'var(--heading-1-size)'
+ * ```
+ */
+export function generateTypeScaleComponents(
+ config: XDSTypeScaleConfig,
+): Record<string, Record<string, Record<string, string>>> {
+ const components: Record<string, Record<string, Record<string, string>>> = {};
+
+ // Heading overrides
+ const headingRules: Record<string, Record<string, string>> = {};
+ for (const level of [1, 2, 3, 4, 5, 6]) {
+ headingRules[`level:${level}`] = {
+ fontFamily: 'var(--font-heading)',
+ fontSize: `var(--heading-${level}-size)`,
+ fontWeight: `var(--heading-${level}-weight)`,
+ lineHeight: `var(--heading-${level}-leading)`,
+ };
+ }
+ components.heading = headingRules;
+
+ // Text overrides
+ const textRules: Record<string, Record<string, string>> = {};
+ for (const type of ['body', 'large', 'label', 'code', 'supporting']) {
+ textRules[`type:${type}`] = {
+ fontFamily: TEXT_FONT_FAMILIES[type],
+ fontSize: `var(--text-${type}-size)`,
+ fontWeight: `var(--text-${type}-weight)`,
+ lineHeight: `var(--text-${type}-leading)`,
+ };
+ }
+ components.text = textRules;
+
+ return components;
+}
diff --git a/packages/core/src/theme/index.ts b/packages/core/src/theme/index.ts
index ae9b8759aa..094b28ed70 100644
--- a/packages/core/src/theme/index.ts
+++ b/packages/core/src/theme/index.ts
@@ -27,6 +27,9 @@ export type {
XDSStyleOverrides,
} from './defineTheme';
+export {expandTypeScale, generateTypeScaleComponents} from './expandTypeScale';
+export type {XDSTypeScaleConfig, TypeScaleTokens} from './expandTypeScale';
+
// Export token defaults and vars for use in custom components and themes
export {
colorDefaults,
@@ -39,6 +42,7 @@ export {
textSizeDefaults,
lineHeightDefaults,
fontWeightDefaults,
+ typeScaleDefaults,
colorVars,
spacingVars,
sizeVars,
@@ -49,6 +53,7 @@ export {
textSizeVars,
lineHeightVars,
fontWeightVars,
+ typeScaleVars,
} from './tokens.stylex';
// Export token key types for theme authoring
@@ -63,6 +68,7 @@ export type {
TextSizeVarName,
LineHeightVarName,
FontWeightVarName,
+ TypeScaleVarName,
} from './tokens.stylex';
export type {
diff --git a/packages/core/src/theme/tokens.stylex.ts b/packages/core/src/theme/tokens.stylex.ts
index a0234150bc..ef2a92d80d 100644
--- a/packages/core/src/theme/tokens.stylex.ts
+++ b/packages/core/src/theme/tokens.stylex.ts
@@ -328,3 +328,62 @@ export type TypographyVarName = keyof typeof typographyDefaults;
export type TextSizeVarName = keyof typeof textSizeDefaults;
export type LineHeightVarName = keyof typeof lineHeightDefaults;
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
+// can override them via typeScale in defineTheme.
+//
+// Default scale: base=14px, ratio=1.2, h4 anchored to base.
+// Suggested starting points:
+// Dense/functional: { base: 12, ratio: 1.125 }
+// Default: { base: 14, ratio: 1.2 }
+// Airy/editorial: { base: 16, ratio: 1.25 }
+
+export const typeScaleDefaults = {
+ // Heading tokens — h4 is the anchor at base (14px)
+ // Sizes reference --text-* vars where possible so base values compose.
+ // When typeScale is used in defineTheme, these are overridden with computed px values.
+ // Line heights are unitless ratios (snapped to 4px grid at computed size).
+ '--heading-1-size': 'var(--text-3xl)', // 24px (14 × 1.2³)
+ '--heading-1-weight': 'var(--font-weight-semibold)',
+ '--heading-1-leading': '1.3333',
+ '--heading-2-size': 'var(--text-2xl)', // 20px (14 × 1.2²)
+ '--heading-2-weight': 'var(--font-weight-semibold)',
+ '--heading-2-leading': '1.4',
+ '--heading-3-size': '17px', // 14 × 1.2¹ (no matching --text-* token)
+ '--heading-3-weight': 'var(--font-weight-semibold)',
+ '--heading-3-leading': '1.4118',
+ '--heading-4-size': 'var(--text-base)', // 14px — base anchor
+ '--heading-4-weight': 'var(--font-weight-semibold)',
+ '--heading-4-leading': '1.4286',
+ '--heading-5-size': 'var(--text-xsm)', // 12px (14 × 1.2⁻¹)
+ '--heading-5-weight': 'var(--font-weight-semibold)',
+ '--heading-5-leading': '1.3333',
+ '--heading-6-size': 'var(--text-3xs)', // 10px (14 × 1.2⁻²)
+ '--heading-6-weight': 'var(--font-weight-semibold)',
+ '--heading-6-leading': '1.6',
+
+ // Text tokens — body/label/code at base, large one step up, supporting one step down
+ '--text-body-size': 'var(--text-base)', // 14px
+ '--text-body-weight': 'var(--font-weight-normal)',
+ '--text-body-leading': '1.7143',
+ '--text-large-size': '17px', // 14 × 1.2¹ (no matching --text-* token)
+ '--text-large-weight': 'var(--font-weight-semibold)',
+ '--text-large-leading': '1.6471',
+ '--text-label-size': 'var(--text-base)', // 14px
+ '--text-label-weight': 'var(--font-weight-medium)',
+ '--text-label-leading': '1.4286',
+ '--text-code-size': 'var(--text-base)', // 14px
+ '--text-code-weight': 'var(--font-weight-normal)',
+ '--text-code-leading': '1.7143',
+ '--text-supporting-size': 'var(--text-xsm)', // 12px
+ '--text-supporting-weight': 'var(--font-weight-normal)',
+ '--text-supporting-leading': '1.6667',
+} as const;
+
+export const typeScaleVars = stylex.defineVars(typeScaleDefaults);
+
+export type TypeScaleVarName = keyof typeof typeScaleDefaults;
diff --git a/packages/core/src/typography.css b/packages/core/src/typography.css
index 841ed6f663..85f5ef8164 100644
--- a/packages/core/src/typography.css
+++ b/packages/core/src/typography.css
@@ -1,8 +1,12 @@
/**
* XDS Typography Styles
*
- * Base typography styles for native HTML elements using CSS custom properties
- * from the XDS theme. Styles automatically adapt to the current theme.
+ * 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:
*
@@ -16,11 +20,6 @@
* <body className="xds-typography">
*
* Requires a parent <Theme> component to set the CSS custom properties.
- *
- * Similar to:
- * - Tailwind's @tailwindcss/typography plugin
- * - GitHub Primer's primer-typography
- * - Radix Themes' prose styles
*/
@layer typography {
@@ -29,141 +28,71 @@
=========================================================================== */
.xds-typography {
- font-size: var(--text-base);
+ font-size: var(--text-body-size);
font-family: var(--font-body);
- line-height: 1.4285714285714286;
+ line-height: var(--text-body-leading);
color: var(--color-text-primary);
}
/* ===========================================================================
- Heading Styles - Default Scale
+ Heading Styles — driven by type scale tokens
=========================================================================== */
- .xds-typography h1,
- .xds-typography--default h1 {
+ .xds-typography h1 {
font-family: var(--font-heading);
- font-size: var(--text-2xl);
- font-weight: var(--font-weight-semibold);
- line-height: 1.2;
+ 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,
- .xds-typography--default h2 {
+ .xds-typography h2 {
font-family: var(--font-heading);
- font-size: var(--text-xl);
- font-weight: var(--font-weight-semibold);
- line-height: 1.333;
+ 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,
- .xds-typography--default h3 {
+ .xds-typography h3 {
font-family: var(--font-heading);
- font-size: var(--text-lg);
- font-weight: var(--font-weight-semibold);
- line-height: 1.25;
+ 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,
- .xds-typography--default h4 {
+ .xds-typography h4 {
font-family: var(--font-heading);
- font-size: var(--text-base);
- font-weight: var(--font-weight-semibold);
- line-height: 1.428;
+ 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,
- .xds-typography--default h5 {
+ .xds-typography h5 {
font-family: var(--font-heading);
- font-size: var(--text-base);
- font-weight: var(--font-weight-semibold);
- line-height: 1.428;
+ 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,
- .xds-typography--default h6 {
+ .xds-typography h6 {
font-family: var(--font-heading);
- font-size: var(--text-xsm);
- font-weight: var(--font-weight-semibold);
- line-height: 1.333;
- color: var(--color-text-primary);
- margin-top: var(--spacing-3);
- margin-bottom: var(--spacing-2);
- }
-
- /* ===========================================================================
- Heading Styles - Editorial Scale
- =========================================================================== */
-
- .xds-typography--editorial h1 {
- font-family: var(--font-heading);
- font-size: var(--text-4xl);
- font-weight: var(--font-weight-semibold);
- line-height: 1.5;
- color: var(--color-text-primary);
- margin-top: var(--spacing-7);
- margin-bottom: var(--spacing-4);
- }
-
- .xds-typography--editorial h2 {
- font-family: var(--font-heading);
- font-size: var(--text-3xl);
- font-weight: var(--font-weight-semibold);
- line-height: 1.333;
- color: var(--color-text-primary);
- margin-top: var(--spacing-6);
- margin-bottom: var(--spacing-3);
- }
-
- .xds-typography--editorial h3 {
- font-family: var(--font-heading);
- font-size: var(--text-2xl);
- font-weight: var(--font-weight-semibold);
- line-height: 1.4;
- color: var(--color-text-primary);
- margin-top: var(--spacing-5);
- margin-bottom: var(--spacing-3);
- }
-
- .xds-typography--editorial h4 {
- font-family: var(--font-heading);
- font-size: var(--text-lg);
- font-weight: var(--font-weight-semibold);
- line-height: 1.5;
- color: var(--color-text-primary);
- margin-top: var(--spacing-4);
- margin-bottom: var(--spacing-2);
- }
-
- .xds-typography--editorial h5 {
- font-family: var(--font-heading);
- font-size: var(--text-base);
- font-weight: var(--font-weight-semibold);
- line-height: 1.428;
- color: var(--color-text-primary);
- margin-top: var(--spacing-4);
- margin-bottom: var(--spacing-2);
- }
-
- .xds-typography--editorial h6 {
- font-family: var(--font-heading);
- font-size: var(--text-xsm);
- font-weight: var(--font-weight-semibold);
- line-height: 1.333;
+ 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);
@@ -215,7 +144,7 @@
.xds-typography pre {
font-family: var(--font-code);
- font-size: var(--text-sm);
+ font-size: var(--text-supporting-size);
line-height: 1.5;
margin-top: 0;
margin-bottom: var(--spacing-3);
diff --git a/packages/themes/default/src/defaultTheme.ts b/packages/themes/default/src/defaultTheme.ts
index 11e7d43cab..6ed6b5f8a1 100644
--- a/packages/themes/default/src/defaultTheme.ts
+++ b/packages/themes/default/src/defaultTheme.ts
@@ -4,13 +4,11 @@
* The reference theme — provides the standard XDS visual language.
* Uses defineTheme for CSS-based theming (no StyleX build required for consumers).
*
- * Token values use [light, dark] tuples for automatic light-dark() conversion.
- * Only tokens that differ from the built-in defaults need to be specified,
- * but the default theme is explicit as a reference.
+ * Typography sizing is driven by typeScale, which auto-generates both
+ * the token values (--heading-1-size, --text-body-size, etc.) and the
+ * component override rules (.xds-heading.level-1 { font-size: ... }).
*
- * Component overrides use CSS class selectors:
- * .xds-button.secondary { ... }
- * .xds-heading.level-1 { ... }
+ * Only non-typography component overrides need to be specified manually.
*/
import {defineTheme} from '@xds/core/theme';
@@ -19,9 +17,12 @@ import {defaultIconRegistry} from './icons';
export const defaultTheme = defineTheme({
name: 'default',
+ // Type scale: base=14px, ratio=1.2, h4 anchored to base.
+ // Generates all heading + text tokens AND component overrides automatically.
+ typeScale: {base: 14, ratio: 1.2},
+
// The default theme uses the built-in token defaults from tokens.stylex.ts.
- // No token overrides needed — defineTheme fills in defaults automatically.
- // See packages/core/src/theme/tokens.stylex.ts for all token values.
+ // No additional token overrides needed.
tokens: {},
components: {
@@ -35,137 +36,8 @@ export const defaultTheme = defineTheme({
},
},
- // =========================================================================
- // Heading — default variant (dense scale for internal tools)
- // =========================================================================
- heading: {
- 'level:1': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-2xl)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: '1.2',
- color: 'var(--color-text-primary)',
- },
- 'level:2': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-xl)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: '1.333',
- color: 'var(--color-text-primary)',
- },
- 'level:3': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-lg)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: '1.25',
- color: 'var(--color-text-primary)',
- },
- 'level:4': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-base)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: 'var(--leading-base)',
- color: 'var(--color-text-primary)',
- },
- 'level:5': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-base)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: 'var(--leading-base)',
- color: 'var(--color-text-primary)',
- },
- 'level:6': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-xsm)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: '1.333',
- color: 'var(--color-text-primary)',
- },
- // Editorial variant — larger scale for content-heavy pages
- 'variant:editorial+level:1': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-4xl)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: '1.5',
- color: 'var(--color-text-primary)',
- },
- 'variant:editorial+level:2': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-3xl)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: '1.333',
- color: 'var(--color-text-primary)',
- },
- 'variant:editorial+level:3': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-2xl)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: '1.4',
- color: 'var(--color-text-primary)',
- },
- 'variant:editorial+level:4': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-lg)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: '1.5',
- color: 'var(--color-text-primary)',
- },
- 'variant:editorial+level:5': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-base)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: 'var(--leading-base)',
- color: 'var(--color-text-primary)',
- },
- 'variant:editorial+level:6': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-xsm)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: '1.333',
- color: 'var(--color-text-primary)',
- },
- },
-
- // =========================================================================
- // Text — semantic text styles
- // =========================================================================
- text: {
- 'type:body': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-base)',
- fontWeight: 'var(--font-weight-normal)',
- lineHeight: 'var(--leading-base)',
- color: 'var(--color-text-primary)',
- },
- 'type:large': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-lg)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: '1.5',
- color: 'var(--color-text-primary)',
- },
- 'type:label': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-base)',
- fontWeight: 'var(--font-weight-medium)',
- lineHeight: 'var(--leading-base)',
- color: 'var(--color-text-primary)',
- },
- 'type:supporting': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-xsm)',
- fontWeight: 'var(--font-weight-normal)',
- lineHeight: '1.333',
- color: 'var(--color-text-secondary)',
- },
- 'type:code': {
- fontFamily: 'var(--font-code)',
- fontSize: 'var(--text-base)',
- fontWeight: 'var(--font-weight-normal)',
- lineHeight: 'var(--leading-base)',
- color: 'var(--color-text-primary)',
- },
- },
+ // Heading and text component overrides are auto-generated by typeScale.
+ // No manual heading: { ... } or text: { ... } blocks needed.
},
icons: defaultIconRegistry,
diff --git a/packages/themes/neutral/src/neutralTheme.ts b/packages/themes/neutral/src/neutralTheme.ts
index eea6700640..2542515f79 100644
--- a/packages/themes/neutral/src/neutralTheme.ts
+++ b/packages/themes/neutral/src/neutralTheme.ts
@@ -16,6 +16,19 @@ import {neutralIconRegistry} from './icons';
export const neutralTheme = defineTheme({
name: 'neutral',
+ // Type scale: same as default (base=14, ratio=1.2).
+ // Neutral uses bold weights on h3/h4 for stronger subsection hierarchy.
+ typeScale: {
+ base: 14,
+ ratio: 1.2,
+ weights: {
+ heading: {
+ 3: 'var(--font-weight-bold)',
+ 4: 'var(--font-weight-bold)',
+ },
+ },
+ },
+
tokens: {
// =========================================================================
// Colors — neutral grayscale palette using oklch
@@ -324,154 +337,8 @@ export const neutralTheme = defineTheme({
},
},
- // =========================================================================
- // Heading — Geist font, same dense scale
- // =========================================================================
- heading: {
- 'level:1': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-2xl)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: '1.2',
- color: 'var(--color-text-primary)',
- margin: '0',
- },
- 'level:2': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-xl)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: '1.333',
- color: 'var(--color-text-primary)',
- margin: '0',
- },
- 'level:3': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-lg)',
- fontWeight: 'var(--font-weight-bold)',
- lineHeight: '1.25',
- color: 'var(--color-text-primary)',
- margin: '0',
- },
- 'level:4': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-base)',
- fontWeight: 'var(--font-weight-bold)',
- lineHeight: 'var(--leading-base)',
- color: 'var(--color-text-primary)',
- margin: '0',
- },
- 'level:5': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-base)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: 'var(--leading-base)',
- color: 'var(--color-text-primary)',
- margin: '0',
- },
- 'level:6': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-xsm)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: '1.333',
- color: 'var(--color-text-primary)',
- margin: '0',
- },
- // Editorial variant
- 'variant:editorial+level:1': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-4xl)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: '1.5',
- color: 'var(--color-text-primary)',
- margin: '0',
- },
- 'variant:editorial+level:2': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-3xl)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: '1.333',
- color: 'var(--color-text-primary)',
- margin: '0',
- },
- 'variant:editorial+level:3': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-2xl)',
- fontWeight: 'var(--font-weight-bold)',
- lineHeight: '1.4',
- color: 'var(--color-text-primary)',
- margin: '0',
- },
- 'variant:editorial+level:4': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-lg)',
- fontWeight: 'var(--font-weight-bold)',
- lineHeight: '1.5',
- color: 'var(--color-text-primary)',
- margin: '0',
- },
- 'variant:editorial+level:5': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-base)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: 'var(--leading-base)',
- color: 'var(--color-text-primary)',
- margin: '0',
- },
- 'variant:editorial+level:6': {
- fontFamily: 'var(--font-heading)',
- fontSize: 'var(--text-xsm)',
- fontWeight: 'var(--font-weight-semibold)',
- lineHeight: '1.333',
- color: 'var(--color-text-primary)',
- margin: '0',
- },
- },
-
- // =========================================================================
- // Text — Geist body font
- // =========================================================================
- text: {
- 'type:body': {
- fontFamily: 'var(--font-body)',
- fontSize: 'var(--text-base)',
- fontWeight: 'var(--font-weight-normal)',
- lineHeight: 'var(--leading-base)',
- color: 'var(--color-text-primary)',
- margin: '0',
- },
- 'type:large': {
- fontFamily: 'var(--font-body)',
- fontSize: 'var(--text-lg)',
- fontWeight: 'var(--font-weight-normal)',
- lineHeight: '1.5',
- color: 'var(--color-text-primary)',
- margin: '0',
- },
- 'type:label': {
- fontFamily: 'var(--font-body)',
- fontSize: 'var(--text-base)',
- fontWeight: 'var(--font-weight-medium)',
- lineHeight: 'var(--leading-base)',
- color: 'var(--color-text-primary)',
- margin: '0',
- },
- 'type:supporting': {
- fontFamily: 'var(--font-body)',
- fontSize: 'var(--text-xsm)',
- fontWeight: 'var(--font-weight-normal)',
- lineHeight: '1.333',
- color: 'var(--color-text-secondary)',
- margin: '0',
- },
- 'type:code': {
- fontFamily: 'var(--font-code)',
- fontSize: 'var(--text-base)',
- fontWeight: 'var(--font-weight-normal)',
- lineHeight: 'var(--leading-base)',
- color: 'var(--color-text-primary)',
- margin: '0',
- },
- },
+ // Heading and text component overrides are auto-generated by typeScale.
+ // h3/h4 bold weights come from typeScale.weights.heading above.
},
icons: neutralIconRegistry,