An open source design system that's fully customizable and agent ready
TypeScript
fix(type-scale): drive raw tokens from base+ratio, semantic tokens as var() refs (#682)
Ernest553025809907
diff --git a/apps/storybook/stories/ThemeEditor.stories.tsx b/apps/storybook/stories/ThemeEditor.stories.tsxindex 095620de0b..cbe05a7ad4 100644--- a/apps/storybook/stories/ThemeEditor.stories.tsx+++ b/apps/storybook/stories/ThemeEditor.stories.tsx@@ -9,7 +9,7 @@ import {XDSText, XDSHeading} from '@xds/core/Text';import {XDSSwitch} from '@xds/core/Switch';import {XDSAvatar} from '@xds/core/Avatar';import {XDSBanner} from '@xds/core/Banner';-import {XDSTabList} from '@xds/core/TabList';+import {XDSTabList, XDSTab} from '@xds/core/TabList';import {XDSDialog} from '@xds/core/Dialog';import {XDSToken} from '@xds/core/Token';import {XDSSlider} from '@xds/core/Slider';@@ -1093,15 +1093,11 @@ const styles = stylex.create({<XDSText type="label" style={{marginBottom: '12px', display: 'block'}}>Tabs</XDSText>- <XDSTabList- tabs={[- {id: 'overview', label: 'Overview'},- {id: 'details', label: 'Details'},- {id: 'settings', label: 'Settings'},- ]}- selectedId={selectedTab}- onSelect={setSelectedTab}- />+ <XDSTabList value={selectedTab} onChange={setSelectedTab}>+ <XDSTab value="overview" label="Overview" />+ <XDSTab value="details" label="Details" />+ <XDSTab value="settings" label="Settings" />+ </XDSTabList></div>{/* Avatar */}@@ -1214,6 +1210,348 @@ const styles = stylex.create({);}+// =============================================================================+// Landing Page Preview+// =============================================================================++function LandingPagePreview() {+ return (+ <div style={{display: 'flex', flexDirection: 'column', gap: '48px'}}>+ {/* Hero */}+ <div style={{textAlign: 'center', padding: '48px 24px'}}>+ <XDSBadge variant="accent">New Release</XDSBadge>+ <XDSHeading level={1} style={{marginTop: 16, marginBottom: 12}}>+ Ship faster with XDS+ </XDSHeading>+ <XDSText+ type="large"+ color="secondary"+ display="block"+ style={{+ marginBottom: 24,+ maxWidth: 520,+ marginLeft: 'auto',+ marginRight: 'auto',+ }}>+ A design system for building internal tools. Open internals, plugin+ architecture, and automatic spacing.+ </XDSText>+ <div style={{display: 'flex', gap: '8px', justifyContent: 'center'}}>+ <XDSButton label="Get Started" />+ <XDSButton label="Documentation" variant="secondary" />+ </div>+ </div>++ <XDSDivider />++ {/* Features */}+ <div>+ <XDSHeading level={2} style={{marginBottom: 16}}>+ Features+ </XDSHeading>+ <div+ style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(3, 1fr)',+ gap: '16px',+ }}>+ {[+ {+ title: 'Open Internals',+ desc: 'All primitives exported and composable. No black boxes.',+ },+ {+ title: 'Plugin Architecture',+ desc: 'Transform and extend components through a unified plugin system.',+ },+ {+ title: 'AI-Ready',+ desc: 'JSDoc annotations with composition hints for LLM-assisted development.',+ },+ ].map(f => (+ <XDSCard key={f.title} padding="md">+ <XDSHeading level={3} style={{marginBottom: 8}}>+ {f.title}+ </XDSHeading>+ <XDSText type="body" color="secondary">+ {f.desc}+ </XDSText>+ </XDSCard>+ ))}+ </div>+ </div>++ {/* Testimonial */}+ <XDSCard padding="lg">+ <XDSText type="large" display="block" style={{marginBottom: 12}}>+ “XDS cut our dev time in half. The type scale system alone saved+ us weeks of bikeshedding.”+ </XDSText>+ <div style={{display: 'flex', alignItems: 'center', gap: '8px'}}>+ <XDSAvatar size="sm" name="Alex Chen" />+ <div>+ <XDSText type="label">Alex Chen</XDSText>+ <XDSText type="supporting" color="secondary">+ {' '}+ · Engineering Lead+ </XDSText>+ </div>+ </div>+ </XDSCard>++ {/* CTA */}+ <div style={{textAlign: 'center', padding: '32px 0'}}>+ <XDSHeading level={2} style={{marginBottom: 8}}>+ Ready to build?+ </XDSHeading>+ <XDSText+ type="body"+ color="secondary"+ display="block"+ style={{marginBottom: 16}}>+ Get started with XDS in under 5 minutes.+ </XDSText>+ <XDSButton label="Start Building" />+ </div>+ </div>+ );+}++// =============================================================================+// Dashboard Preview+// =============================================================================++interface MetricRow extends Record<string, unknown> {+ metric: string;+ value: string;+ change: string;+ trend: 'up' | 'down' | 'flat';+}++const dashboardColumns: XDSTableColumn<MetricRow>[] = [+ {key: 'metric', header: 'Metric'},+ {key: 'value', header: 'Value'},+ {key: 'change', header: 'Change'},+];++function DashboardPreview() {+ const [tab, setTab] = React.useState('overview');++ const metrics: MetricRow[] = [+ {metric: 'Total Users', value: '12,847', change: '+12.3%', trend: 'up'},+ {metric: 'Active Sessions', value: '3,421', change: '+8.1%', trend: 'up'},+ {+ metric: 'Avg Response Time',+ value: '142ms',+ change: '-5.2%',+ trend: 'down',+ },+ {metric: 'Error Rate', value: '0.03%', change: '-18.7%', trend: 'down'},+ {metric: 'API Calls (24h)', value: '2.4M', change: '+3.1%', trend: 'up'},+ {metric: 'Storage Used', value: '847 GB', change: '+1.2%', trend: 'flat'},+ ];++ return (+ <div style={{display: 'flex', flexDirection: 'column', gap: '24px'}}>+ {/* Header */}+ <div+ style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ }}>+ <div>+ <XDSHeading level={1}>Dashboard</XDSHeading>+ <XDSText type="supporting" color="secondary">+ Last updated 2 minutes ago+ </XDSText>+ </div>+ <div style={{display: 'flex', gap: '8px'}}>+ <XDSButton label="Export" variant="secondary" size="sm" />+ <XDSButton label="Refresh" size="sm" />+ </div>+ </div>++ {/* KPI Cards */}+ <div+ style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(4, 1fr)',+ gap: '12px',+ }}>+ {[+ {label: 'Revenue', value: '$48.2K', delta: '+12%'},+ {label: 'Users', value: '12,847', delta: '+8%'},+ {label: 'Uptime', value: '99.97%', delta: '—'},+ {label: 'NPS', value: '72', delta: '+3'},+ ].map(kpi => (+ <XDSCard key={kpi.label} padding="md">+ <XDSText type="supporting" color="secondary" display="block">+ {kpi.label}+ </XDSText>+ <XDSHeading level={2} style={{marginTop: 4}}>+ {kpi.value}+ </XDSHeading>+ <XDSText+ type="supporting"+ color={kpi.delta.startsWith('+') ? 'active' : 'secondary'}>+ {kpi.delta}+ </XDSText>+ </XDSCard>+ ))}+ </div>++ {/* Tabs + Table */}+ <div>+ <XDSTabList value={tab} onChange={setTab}>+ <XDSTab value="overview" label="Overview" />+ <XDSTab value="performance" label="Performance" />+ <XDSTab value="errors" label="Errors" />+ </XDSTabList>+ <div style={{marginTop: '16px'}}>+ <XDSTable columns={dashboardColumns} data={metrics} size="sm" />+ </div>+ </div>++ {/* Activity Banner */}+ <XDSBanner+ variant="educational"+ title="System Update"+ description="A new version of the API is available. Review the changelog for breaking changes."+ action={+ <XDSButton label="View Changelog" variant="secondary" size="sm" />+ }+ />++ {/* Bottom section */}+ <div+ style={{display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '16px'}}>+ <XDSCard padding="md">+ <XDSHeading level={3} style={{marginBottom: 12}}>+ Recent Activity+ </XDSHeading>+ {[+ {+ user: 'Sarah K.',+ action: 'deployed v2.4.1 to production',+ time: '5 min ago',+ },+ {+ user: 'Mike R.',+ action: 'merged PR #247: fix auth flow',+ time: '23 min ago',+ },+ {+ user: 'Cindy Z.',+ action: 'created issue #312: token audit',+ time: '1 hr ago',+ },+ {+ user: 'Alex C.',+ action: 'updated dashboard metrics query',+ time: '2 hr ago',+ },+ ].map((item, i) => (+ <div+ key={i}+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ padding: '8px 0',+ borderBottom: i < 3 ? '1px solid var(--color-divider)' : 'none',+ }}>+ <XDSAvatar size="sm" name={item.user} />+ <div style={{flex: 1}}>+ <XDSText type="label">{item.user}</XDSText>+ <XDSText type="body" color="secondary">+ {' '}+ {item.action}+ </XDSText>+ </div>+ <XDSText type="supporting" color="secondary">+ {item.time}+ </XDSText>+ </div>+ ))}+ </XDSCard>+ <XDSCard padding="md">+ <XDSHeading level={3} style={{marginBottom: 12}}>+ Quick Stats+ </XDSHeading>+ <div style={{display: 'flex', flexDirection: 'column', gap: '12px'}}>+ <div>+ <div+ style={{+ display: 'flex',+ justifyContent: 'space-between',+ marginBottom: '4px',+ }}>+ <XDSText type="supporting">CPU Usage</XDSText>+ <XDSText type="supporting" color="secondary">+ 43%+ </XDSText>+ </div>+ <XDSProgressBar value={43} />+ </div>+ <div>+ <div+ style={{+ display: 'flex',+ justifyContent: 'space-between',+ marginBottom: '4px',+ }}>+ <XDSText type="supporting">Memory</XDSText>+ <XDSText type="supporting" color="secondary">+ 67%+ </XDSText>+ </div>+ <XDSProgressBar value={67} />+ </div>+ <div>+ <div+ style={{+ display: 'flex',+ justifyContent: 'space-between',+ marginBottom: '4px',+ }}>+ <XDSText type="supporting">Storage</XDSText>+ <XDSText type="supporting" color="secondary">+ 82%+ </XDSText>+ </div>+ <XDSProgressBar value={82} />+ </div>+ </div>+ </XDSCard>+ </div>+ </div>+ );+}++// =============================================================================+// Preview Tabs (wraps all three preview modes)+// =============================================================================++function PreviewTabs() {+ const [activePreview, setActivePreview] = React.useState('preview');++ return (+ <div>+ <XDSTabList value={activePreview} onChange={setActivePreview}>+ <XDSTab value="preview" label="Preview" />+ <XDSTab value="landing" label="Landing Page" />+ <XDSTab value="dashboard" label="Dashboard" />+ </XDSTabList>+ <div style={{marginTop: '24px'}}>+ {activePreview === 'preview' && <ComponentPreview />}+ {activePreview === 'landing' && <LandingPagePreview />}+ {activePreview === 'dashboard' && <DashboardPreview />}+ </div>+ </div>+ );+}+// =============================================================================// Code Generator// =============================================================================@@ -1569,7 +1907,15 @@ function ThemeEditorComponent() {gap: '2px',}}>{[1, 2, 3, 4, 5, 6].map(level => {- const size = tokens[`--heading-${level}-size`] || '';+ const sizeRaw = tokens[`--heading-${level}-size`] || '';+ // Resolve var() refs: "var(--text-2xl)" → look up --text-2xl in tokens+ const resolvedSize = sizeRaw.startsWith('var(')+ ? tokens[sizeRaw.slice(4, -1)] || sizeRaw+ : sizeRaw;+ // Convert rem to px for display: "1.5rem" → "24px"+ const displayPx = resolvedSize.endsWith('rem')+ ? `${Math.round(parseFloat(resolvedSize) * 16)}px`+ : resolvedSize;return (<divkey={level}@@ -1586,7 +1932,7 @@ function ThemeEditorComponent() {</XDSText><spanstyle={{- fontSize: size,+ fontSize: resolvedSize,fontWeight: 600,lineHeight: 1.3,color: 'var(--color-text-primary)',@@ -1600,11 +1946,64 @@ function ThemeEditorComponent() {type="code"color="secondary"style={{marginLeft: 'auto', flexShrink: 0}}>- {size}+ {displayPx}</XDSText></div>);})}+ <div+ style={{+ borderTop: '1px solid var(--color-divider)',+ marginTop: '4px',+ paddingTop: '4px',+ }}>+ {(['large', 'body', 'supporting'] as const).map(type => {+ const sizeRaw = tokens[`--text-${type}-size`] || '';+ const resolvedSize = sizeRaw.startsWith('var(')+ ? tokens[sizeRaw.slice(4, -1)] || sizeRaw+ : sizeRaw;+ const displayPx = resolvedSize.endsWith('rem')+ ? `${Math.round(parseFloat(resolvedSize) * 16)}px`+ : resolvedSize;+ return (+ <div+ key={type}+ style={{+ display: 'flex',+ alignItems: 'baseline',+ gap: '8px',+ }}>+ <XDSText+ type="code"+ color="secondary"+ style={{width: '60px', flexShrink: 0}}>+ {type}+ </XDSText>+ <span+ style={{+ fontSize: resolvedSize,+ fontWeight: type === 'large' ? 600 : 400,+ lineHeight: 1.4,+ color:+ type === 'supporting'+ ? 'var(--color-text-secondary)'+ : 'var(--color-text-primary)',+ whiteSpace: 'nowrap',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ }}>+ Sample text+ </span>+ <XDSText+ type="code"+ color="secondary"+ style={{marginLeft: 'auto', flexShrink: 0}}>+ {displayPx}+ </XDSText>+ </div>+ );+ })}+ </div></div><XDSText type="code" color="secondary">size = {typeScaleBase} × {typeScaleRatio.toFixed(3)}^step · h4 =@@ -1935,7 +2334,7 @@ function ThemeEditorComponent() {backgroundColor: 'var(--color-surface)',padding: '24px',}}>- <ComponentPreview />+ <PreviewTabs /></div></XDSTheme></div>diff --git a/packages/cli/docs/tokens.md b/packages/cli/docs/tokens.mdindex 7c499efe37..b6eb2a4b03 100644--- a/packages/cli/docs/tokens.md+++ b/packages/cli/docs/tokens.md@@ -129,19 +129,72 @@ const sharpTheme = defineTheme({### Text Sizes-| Token | Value |-| ----------- | -------------- |-| --text-4xs | 8px |-| --text-3xs | 10px |-| --text-2xs | 11px |-| --text-xsm | 12px |-| --text-sm | 13px |-| --text-base | 14px (default) |-| --text-lg | 16px |-| --text-xl | 18px |-| --text-2xl | 20px |-| --text-3xl | 24px |-| --text-4xl | 32px |+Computed from a geometric scale: `round(base × ratio^step)`.+Default: base=14px, ratio=1.2.++| Token | Step | Default | Usage |+| ----------- | ---- | ------- | --------------- |+| --text-4xs | -5 | 6px | Citation, micro |+| --text-3xs | -4 | 7px | Micro labels |+| --text-2xs | -3 | 8px | Small micro |+| --text-xsm | -2 | 10px | Extra small |+| --text-sm | -1 | 12px | Small text |+| --text-base | 0 | 14px | Body (anchor) |+| --text-lg | +1 | 17px | Large text |+| --text-xl | +2 | 20px | Extra large |+| --text-2xl | +3 | 24px | 2× large |+| --text-3xl | +4 | 29px | 3× large |+| --text-4xl | +5 | 35px | 4× large |++### Type Scale (Semantic Tokens)++Semantic tokens map headings and text types to the raw size scale.+Sizes are `var()` references; line heights are 4px-grid-snapped computed values.++Override the entire scale with `typeScale: { base, ratio }` in `defineTheme()`.++#### Heading Tokens++| Token | Maps to | Default | Leading |+| ------------------- | ---------------- | ------- | ------- |+| --heading-1-size | var(--text-2xl) | 24px | |+| --heading-1-weight | semibold | | |+| --heading-1-leading | | | 1.3333 |+| --heading-2-size | var(--text-xl) | 20px | |+| --heading-2-weight | semibold | | |+| --heading-2-leading | | | 1.4 |+| --heading-3-size | var(--text-lg) | 17px | |+| --heading-3-weight | semibold | | |+| --heading-3-leading | | | 1.4118 |+| --heading-4-size | var(--text-base) | 14px | |+| --heading-4-weight | semibold | | |+| --heading-4-leading | | | 1.4286 |+| --heading-5-size | var(--text-sm) | 12px | |+| --heading-5-weight | semibold | | |+| --heading-5-leading | | | 1.6667 |+| --heading-6-size | var(--text-xsm) | 10px | |+| --heading-6-weight | semibold | | |+| --heading-6-leading | | | 1.6 |++#### Text Type Tokens++| Token | Maps to | Default | Leading | Weight |+| ------------------------- | ---------------- | ------- | ------- | -------- |+| --text-body-size | var(--text-base) | 14px | | |+| --text-body-weight | | | | normal |+| --text-body-leading | | | 1.4286 | |+| --text-large-size | var(--text-lg) | 17px | | |+| --text-large-weight | | | | semibold |+| --text-large-leading | | | 1.4118 | |+| --text-label-size | var(--text-base) | 14px | | |+| --text-label-weight | | | | medium |+| --text-label-leading | | | 1.4286 | |+| --text-code-size | var(--text-base) | 14px | | |+| --text-code-weight | | | | normal |+| --text-code-leading | | | 1.4286 | |+| --text-supporting-size | var(--text-sm) | 12px | | |+| --text-supporting-weight | | | | normal |+| --text-supporting-leading | | | 1.6667 | |### Font Weights@@ -150,7 +203,9 @@ const sharpTheme = defineTheme({- `--font-weight-semibold`: 600- `--font-weight-bold`: 700-### Line Heights (Leading)+### Line Heights (Named Leading)++Intent-based ratios for component use. Not modified by `typeScale`.| Token | Value | Usage || ----------------- | ------ | ---------------------------- |diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.tsindex ae7dcb94a2..b7c6307d05 100644--- a/packages/core/src/theme/defineTheme.test.ts+++ b/packages/core/src/theme/defineTheme.test.ts@@ -239,20 +239,23 @@ describe('typeScale', () => {name: 'dense',typeScale: {base: 12, ratio: 1.125},});- expect(theme.tokens['--heading-4-size']).toBe('0.75rem');- expect(theme.tokens['--text-body-size']).toBe('0.75rem');+ // Semantic tokens are now var() refs; raw token has the computed value+ expect(theme.tokens['--heading-4-size']).toBe('var(--text-base)');+ expect(theme.tokens['--text-base']).toBe('0.75rem');+ expect(theme.tokens['--text-body-size']).toBe('var(--text-base)');});- it('generates all 33 type scale tokens', () => {+ it('generates 44 tokens (11 raw size + 33 semantic)', () => {const theme = defineTheme({name: 'custom',typeScale: {base: 14, ratio: 1.2},});- // 6 heading levels × 3 props + 5 text types × 3 props = 33+ // 11 raw size (--text-4xs…--text-4xl) + 33 semantic = 44+ // Filtering for --heading- or --text- captures raw + semantic = 11 + 15 + 18 = 44const typeScaleKeys = Object.keys(theme.tokens).filter(k => k.startsWith('--heading-') || k.startsWith('--text-'),);- expect(typeScaleKeys).toHaveLength(33);+ expect(typeScaleKeys).toHaveLength(44);});it('explicit tokens override typeScale-generated values', () => {@@ -265,8 +268,8 @@ describe('typeScale', () => {});// Explicit token should win over typeScaleexpect(theme.tokens['--heading-1-size']).toBe('40px');- // Non-overridden typeScale token should still be present- expect(theme.tokens['--heading-4-size']).toBe('0.875rem');+ // Non-overridden typeScale token should still be a var() ref+ expect(theme.tokens['--heading-4-size']).toBe('var(--text-base)');});it('works without typeScale (backwards compatible)', () => {@@ -284,7 +287,8 @@ describe('typeScale', () => {},});expect(theme.tokens['--color-accent']).toBe('#FF0000');- expect(theme.tokens['--heading-4-size']).toBe('1rem');+ expect(theme.tokens['--heading-4-size']).toBe('var(--text-base)');+ expect(theme.tokens['--text-base']).toBe('1rem');});});@@ -423,7 +427,7 @@ describe('radiusScale', () => {},});expect(theme.tokens['--color-accent']).toBe('#FF0000');- expect(theme.tokens['--heading-4-size']).toBe('1rem');+ expect(theme.tokens['--heading-4-size']).toBe('var(--text-base)');expect(theme.tokens['--radius-2']).toBe('8px');});});diff --git a/packages/core/src/theme/expandTypeScale.test.ts b/packages/core/src/theme/expandTypeScale.test.tsindex 05db8a0449..03a3015948 100644--- a/packages/core/src/theme/expandTypeScale.test.ts+++ b/packages/core/src/theme/expandTypeScale.test.ts@@ -1,143 +1,153 @@/*** @file expandTypeScale.test.ts- * Tests for the type scale computation function.+ * Tests for the two-layer type scale computation.*/import {describe, it, expect} from 'vitest';import {expandTypeScale, generateTypeScaleComponents} from './expandTypeScale';describe('expandTypeScale', () => {- describe('default scale (base=14, ratio=1.2)', () => {+ describe('Layer 1: raw size tokens', () => {const tokens = expandTypeScale({base: 14, ratio: 1.2});- it('generates 33 tokens', () => {- expect(Object.keys(tokens)).toHaveLength(33);+ it('emits 11 raw size tokens in rem', () => {+ const sizeTokens = [+ '--text-4xs',+ '--text-3xs',+ '--text-2xs',+ '--text-xsm',+ '--text-sm',+ '--text-base',+ '--text-lg',+ '--text-xl',+ '--text-2xl',+ '--text-3xl',+ '--text-4xl',+ ];+ for (const name of sizeTokens) {+ expect(tokens[name]).toBeDefined();+ expect(tokens[name]).toMatch(/rem$/);+ }});- it('anchors h4 to base size', () => {- expect(tokens['--heading-4-size']).toBe('0.875rem');+ it('anchors --text-base to the base size', () => {+ expect(tokens['--text-base']).toBe('0.875rem'); // 14/16});- it('computes heading sizes from geometric progression', () => {- // h1 = 14 × 1.2³ ≈ 24.19 → 1.5rem- expect(tokens['--heading-1-size']).toBe('1.5rem');- // h2 = 14 × 1.2² ≈ 20.16 → 1.25rem- expect(tokens['--heading-2-size']).toBe('1.25rem');- // h3 = 14 × 1.2¹ ≈ 16.8 → 1.0625rem- expect(tokens['--heading-3-size']).toBe('1.0625rem');- // h5 = 14 × 1.2⁻¹ ≈ 11.67 → 0.75rem- expect(tokens['--heading-5-size']).toBe('0.75rem');- // h6 = 14 × 1.2⁻² ≈ 9.72 → 0.625rem- expect(tokens['--heading-6-size']).toBe('0.625rem');+ it('computes geometric progression for sub-scale tokens', () => {+ expect(tokens['--text-4xs']).toBe('0.375rem'); // 6/16+ expect(tokens['--text-3xs']).toBe('0.4375rem'); // 7/16+ expect(tokens['--text-2xs']).toBe('0.5rem'); // 8/16});- it('computes body text at base size', () => {- expect(tokens['--text-body-size']).toBe('0.875rem');- expect(tokens['--text-label-size']).toBe('0.875rem');- expect(tokens['--text-code-size']).toBe('0.875rem');+ it('computes geometric progression', () => {+ expect(tokens['--text-xsm']).toBe('0.625rem'); // 10/16+ expect(tokens['--text-sm']).toBe('0.75rem'); // 12/16+ expect(tokens['--text-lg']).toBe('1.0625rem'); // 17/16+ expect(tokens['--text-xl']).toBe('1.25rem'); // 20/16+ expect(tokens['--text-2xl']).toBe('1.5rem'); // 24/16+ expect(tokens['--text-3xl']).toBe('1.8125rem'); // 29/16+ expect(tokens['--text-4xl']).toBe('2.1875rem'); // 35/16});+ });- it('computes large text one step up', () => {- // 14 × 1.2¹ ≈ 16.8 → 1.0625rem- expect(tokens['--text-large-size']).toBe('1.0625rem');- });+ describe('Layer 2: semantic tokens', () => {+ const tokens = expandTypeScale({base: 14, ratio: 1.2});- it('computes supporting text one step down', () => {- // 14 × 1.2⁻¹ ≈ 11.67 → 0.75rem- expect(tokens['--text-supporting-size']).toBe('0.75rem');+ it('heading sizes are var() references to raw tokens', () => {+ expect(tokens['--heading-1-size']).toBe('var(--text-2xl)');+ expect(tokens['--heading-2-size']).toBe('var(--text-xl)');+ expect(tokens['--heading-3-size']).toBe('var(--text-lg)');+ expect(tokens['--heading-4-size']).toBe('var(--text-base)');+ expect(tokens['--heading-5-size']).toBe('var(--text-sm)');+ expect(tokens['--heading-6-size']).toBe('var(--text-xsm)');});- 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('heading leadings are hardcoded computed values', () => {+ expect(tokens['--heading-1-leading']).toBe('1.3333'); // 24px → 32px+ expect(tokens['--heading-2-leading']).toBe('1.4'); // 20px → 28px+ expect(tokens['--heading-3-leading']).toBe('1.4118'); // 17px → 24px+ expect(tokens['--heading-4-leading']).toBe('1.4286'); // 14px → 20px+ expect(tokens['--heading-5-leading']).toBe('1.6667'); // 12px → 20px+ expect(tokens['--heading-6-leading']).toBe('1.6'); // 10px → 16px});- 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 = Math.round(parseFloat(tokens[sizeKey]) * 16);- const ratio = parseFloat(value);- const computedLh = Math.round(fontSize * ratio);- expect(computedLh % 4).toBe(0);- }- }+ it('text type sizes are var() references', () => {+ expect(tokens['--text-body-size']).toBe('var(--text-base)');+ expect(tokens['--text-large-size']).toBe('var(--text-lg)');+ expect(tokens['--text-label-size']).toBe('var(--text-base)');+ expect(tokens['--text-code-size']).toBe('var(--text-base)');+ expect(tokens['--text-supporting-size']).toBe('var(--text-sm)');});- 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 = Math.round(parseFloat(tokens[sizeKey]) * 16);- const ratio = parseFloat(value);- const computedLh = Math.round(fontSize * ratio);- expect(computedLh).toBeGreaterThanOrEqual(fontSize + 4);- }- }+ it('text type leadings are hardcoded computed values', () => {+ expect(tokens['--text-body-leading']).toBe('1.4286'); // 14px → 20px+ expect(tokens['--text-large-leading']).toBe('1.4118'); // 17px → 24px+ expect(tokens['--text-label-leading']).toBe('1.4286');+ expect(tokens['--text-code-leading']).toBe('1.4286');+ expect(tokens['--text-supporting-leading']).toBe('1.6667'); // 12px → 16px});- 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', () => {+ it('weight tokens are var() references (unchanged)', () => {+ expect(tokens['--heading-1-weight']).toBe('var(--font-weight-semibold)');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('0.75rem');});- it('produces smaller heading sizes', () => {- // h1 = 12 × 1.125³ ≈ 17.09 → 1.0625rem- expect(tokens['--heading-1-size']).toBe('1.0625rem');- // h2 = 12 × 1.125² ≈ 15.19 → 0.9375rem- expect(tokens['--heading-2-size']).toBe('0.9375rem');+ it('all line heights snap to 4px grid', () => {+ // Map semantic leading tokens to their font sizes (px)+ const pairs: [string, number][] = [+ ['--heading-1-leading', 24],+ ['--heading-2-leading', 20],+ ['--heading-3-leading', 17],+ ['--heading-4-leading', 14],+ ['--heading-5-leading', 12],+ ['--heading-6-leading', 10],+ ['--text-body-leading', 14],+ ['--text-large-leading', 17],+ ['--text-supporting-leading', 12],+ ];+ for (const [token, fontSize] of pairs) {+ const ratio = parseFloat(tokens[token]);+ const lhPx = Math.round(fontSize * ratio);+ expect(lhPx % 4).toBe(0);+ expect(lhPx).toBeGreaterThanOrEqual(fontSize + 4);+ }});- it('keeps body at base', () => {- expect(tokens['--text-body-size']).toBe('0.75rem');+ it('uses tiered target ratio based on font size', () => {+ // < 20px target 1.5: 14px → 20px line+ expect(Math.round(14 * parseFloat(tokens['--heading-4-leading']))).toBe(+ 20,+ );+ // 20-31px target 1.4: 20px → 28px line+ expect(Math.round(20 * parseFloat(tokens['--heading-2-leading']))).toBe(+ 28,+ );+ // 20-31px target 1.4: 24px → 32px line+ expect(Math.round(24 * parseFloat(tokens['--heading-1-leading']))).toBe(+ 32,+ );});});- describe('airy scale (base=16, ratio=1.25)', () => {- const tokens = expandTypeScale({base: 16, ratio: 1.25});+ describe('does not touch named leading tokens', () => {+ const tokens = expandTypeScale({base: 14, ratio: 1.2});- it('anchors h4 to base 16px', () => {- expect(tokens['--heading-4-size']).toBe('1rem');+ it('does not emit --leading-* tokens', () => {+ const leadingKeys = Object.keys(tokens).filter(k =>+ k.startsWith('--leading-'),+ );+ expect(leadingKeys).toHaveLength(0);});+ });- it('produces larger heading sizes', () => {- // h1 = 16 × 1.25³ ≈ 31.25 → 1.9375rem- expect(tokens['--heading-1-size']).toBe('1.9375rem');- // h2 = 16 × 1.25² = 25 → 1.5625rem- expect(tokens['--heading-2-size']).toBe('1.5625rem');- });+ describe('total token count', () => {+ const tokens = expandTypeScale({base: 14, ratio: 1.2});- it('keeps body at base', () => {- expect(tokens['--text-body-size']).toBe('1rem');+ it('generates 44 tokens (11 size + 33 semantic)', () => {+ expect(Object.keys(tokens)).toHaveLength(44);});});@@ -146,121 +156,83 @@ describe('expandTypeScale', () => {const tokens = expandTypeScale({base: 14,ratio: 1.2,- weights: {- heading: {1: 'var(--font-weight-bold)', 3: 'var(--font-weight-bold)'},- },+ weights: {heading: {1: '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)'},- },+ 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('alternate scales', () => {+ it('dense scale (base=12, ratio=1.125)', () => {+ const tokens = expandTypeScale({base: 12, ratio: 1.125});+ expect(tokens['--text-base']).toBe('0.75rem'); // 12/16+ expect(tokens['--heading-4-size']).toBe('var(--text-base)');+ });++ it('airy scale (base=16, ratio=1.25)', () => {+ const tokens = expandTypeScale({base: 16, ratio: 1.25});+ expect(tokens['--text-base']).toBe('1rem'); // 16/16+ expect(tokens['--text-lg']).toBe('1.25rem'); // 20/16+ expect(tokens['--heading-1-size']).toBe('var(--text-2xl)');+ });++ it('all scales produce 4px-grid-aligned line heights', () => {+ const scales = [+ {base: 12, ratio: 1.125},+ {base: 14, ratio: 1.2},+ {base: 16, ratio: 1.25},+ {base: 18, ratio: 1.333},+ ];+ for (const config of scales) {+ const tokens = expandTypeScale(config);+ for (let level = 1; level <= 6; level++) {+ const step = {1: 3, 2: 2, 3: 1, 4: 0, 5: -1, 6: -2}[level]!;+ const fontSize = Math.round(+ config.base * Math.pow(config.ratio, step),+ );+ const ratio = parseFloat(tokens[`--heading-${level}-leading`]);+ const lhPx = Math.round(fontSize * ratio);+ expect(lhPx % 4).toBe(0);+ expect(lhPx).toBeGreaterThanOrEqual(fontSize + 4);+ }}});});});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', () => {+ it('generates heading and text component overrides', () => {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)');+ expect(components.heading).toBeDefined();+ expect(components.text).toBeDefined();});- it('code text uses font-code family', () => {+ it('heading overrides reference semantic tokens', () => {const components = generateTypeScaleComponents({base: 14, ratio: 1.2});- expect(components.text['type:code'].fontFamily).toBe('var(--font-code)');+ expect(components.heading['level:1'].fontSize).toBe(+ 'var(--heading-1-size)',+ );+ expect(components.heading['level:1'].lineHeight).toBe(+ 'var(--heading-1-leading)',+ );});- it('does NOT include color (handled by component internals)', () => {+ it('text overrides reference semantic tokens', () => {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();+ expect(components.text['type:body'].fontSize).toBe('var(--text-body-size)');+ expect(components.text['type:body'].lineHeight).toBe(+ 'var(--text-body-leading)',+ );});});diff --git a/packages/core/src/theme/expandTypeScale.ts b/packages/core/src/theme/expandTypeScale.tsindex dd4ec65540..bbadf1d394 100644--- a/packages/core/src/theme/expandTypeScale.ts+++ b/packages/core/src/theme/expandTypeScale.ts@@ -1,17 +1,43 @@/*** @file expandTypeScale.ts* @input Type scale configuration { base, ratio, weights? }- * @output Token overrides for heading and text typography+ * @output Token overrides for raw size tokens and semantic typography tokens* @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.+ * Computes a complete typography token set 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.+ * Two-layer architecture:+ * Layer 1: Raw size tokens (--text-4xs … --text-4xl)+ * Geometric progression in rem.+ * Layer 2: Semantic tokens (--heading-*, --text-*-size/leading/weight)+ * Sizes are var() references to Layer 1.+ * Line heights are hardcoded computed values (4px grid snapped).+ * Weights are var() references to font-weight tokens.*- * Line heights are unitless ratios, snapped so the computed px value- * aligns to a 4px grid for visual rhythm.+ * The named leading tokens (--leading-tight … --leading-relaxed) are NOT+ * modified by the type scale — they remain as intent-based ratios for+ * component use.+ *+ * Step mapping:+ * step -5 → --text-4xs (sub-scale)+ * step -4 → --text-3xs (sub-scale)+ * step -3 → --text-2xs (sub-scale)+ * step -2 → --text-xsm (h6)+ * step -1 → --text-sm (h5, supporting)+ * step 0 → --text-base (h4, body, label, code)+ * step +1 → --text-lg (h3, large)+ * step +2 → --text-xl (h2)+ * step +3 → --text-2xl (h1)+ * step +4 → --text-3xl+ * step +5 → --text-4xl+ *+ * Line heights use a tiered target ratio based on font size:+ * < 20px → 1.5 (body text, small UI)+ * 20–31px → 1.4 (medium headings)+ * ≥ 32px → 1.25 (large display headings)+ *+ * Then 4px-grid-snapped with Math.round and a minimum of fontSize + 4.** SYNC: When modified, update:* - /packages/core/src/theme/expandTypeScale.test.ts@@ -90,6 +116,37 @@ export type TypeScaleTokens = Record<string, string>;// Constants// =============================================================================+/**+ * Step → raw size token name.+ * These tokens form the geometric font size scale.+ *+ * The full scale spans steps -5 to +5:+ * -5 → --text-4xs (sub-scale)+ * -4 → --text-3xs (sub-scale)+ * -3 → --text-2xs (sub-scale)+ * -2 → --text-xsm+ * -1 → --text-sm+ * 0 → --text-base (anchor)+ * +1 → --text-lg+ * +2 → --text-xl+ * +3 → --text-2xl+ * +4 → --text-3xl+ * +5 → --text-4xl+ */+const STEP_TO_SIZE_TOKEN: Record<number, string> = {+ [-5]: '--text-4xs',+ [-4]: '--text-3xs',+ [-3]: '--text-2xs',+ [-2]: '--text-xsm',+ [-1]: '--text-sm',+ [0]: '--text-base',+ [1]: '--text-lg',+ [2]: '--text-xl',+ [3]: '--text-2xl',+ [4]: '--text-3xl',+ [5]: '--text-4xl',+};+/*** Heading level → step offset from base (h4 = 0).* h1 is 3 steps above base, h6 is 2 steps below.@@ -117,7 +174,6 @@ const TEXT_STEPS: Record<string, number> = {/*** 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)',@@ -130,7 +186,6 @@ const DEFAULT_HEADING_WEIGHTS: Record<number, string> = {/*** 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)',@@ -140,18 +195,6 @@ const DEFAULT_TEXT_WEIGHTS: Record<string, string> = {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// =============================================================================@@ -163,45 +206,59 @@ function computeSize(base: number, ratio: number, step: number): number {return Math.round(base * Math.pow(ratio, step));}+/** Convert px to rem based on the standard 16px root font size. */+function pxToRem(px: number): string {+ const rem = Math.round((px / 16) * 10000) / 10000;+ return `${rem}rem`;+}++/**+ * Tiered target line-height ratio based on font size.+ *+ * < 20px → 1.5 (body text, small UI elements)+ * 20–31px → 1.4 (medium headings, transitional)+ * ≥ 32px → 1.25 (large display headings)+ */+function targetLeadingRatio(fontSize: number): number {+ return fontSize < 20 ? 1.5 : fontSize < 32 ? 1.4 : 1.25;+}+/*** 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.+ * aligns to a 4px grid. Ensures a minimum gap of fontSize + 4px.*- * 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.+ * Uses a tiered target ratio — see `targetLeadingRatio`.*/-function computeLeading(fontSize: number, targetRatio: number): number {- const rawLh = fontSize * targetRatio;+function computeLeading(fontSize: number): number {+ const target = targetLeadingRatio(fontSize);+ const rawLh = fontSize * target;const snappedLh = Math.max(Math.round(rawLh / 4) * 4,Math.ceil((fontSize + 4) / 4) * 4,);- // Round to 4 decimal places for clean CSS outputreturn Math.round((snappedLh / fontSize) * 10000) / 10000;}-/** Convert px to rem based on the standard 16px root font size. */-function pxToRem(px: number): string {- const rem = Math.round((px / 16) * 10000) / 10000;- return `${rem}rem`;-}-/*** Expand a type scale configuration into typography token overrides.*- * Generates 33 tokens: 6 heading levels × 3 properties + 5 text types × 3 properties.- *- * Font sizes are emitted as rem values (e.g. '1.5rem') based on 16px root.- * Line heights are emitted as unitless ratios (e.g. '1.3333').- * Font weights are emitted as var() references (e.g. 'var(--font-weight-semibold)').+ * Generates two layers of tokens:+ * - Layer 1: 11 raw size tokens (--text-4xs … --text-4xl) in rem+ * - Layer 2: 33 semantic tokens using var() refs for sizes and+ * hardcoded computed values for line heights** @example* ```* const tokens = expandTypeScale({ base: 14, ratio: 1.2 });- * // tokens['--heading-1-size'] === '1.5rem'+ * // Layer 1 — raw sizes+ * // tokens['--text-base'] === '0.875rem'+ * // tokens['--text-2xl'] === '1.5rem'+ * //+ * // Layer 2 — semantic+ * // tokens['--heading-1-size'] === 'var(--text-2xl)'* // tokens['--heading-1-leading'] === '1.3333'- * // tokens['--heading-4-size'] === '0.875rem' (anchor)- * // tokens['--text-body-size'] === '0.875rem'+ * // tokens['--text-body-size'] === 'var(--text-base)'+ * // tokens['--text-body-leading'] === '1.4286'* ```*/export function expandTypeScale(config: XDSTypeScaleConfig): TypeScaleTokens {@@ -218,13 +275,24 @@ export function expandTypeScale(config: XDSTypeScaleConfig): TypeScaleTokens {...(weights?.text as Record<string, string> | undefined),};+ // ── Layer 1: Raw size tokens (rem) ────────────────────────────────────────+ for (let step = -5; step <= 5; step++) {+ const size = computeSize(base, ratio, step);+ tokens[STEP_TO_SIZE_TOKEN[step]] = pxToRem(size);+ }++ // ── Layer 2: Semantic tokens ──────────────────────────────────────────────+ // Sizes → var() refs to Layer 1+ // Line heights → hardcoded computed values (4px grid snapped)+ // Weights → var() refs (unchanged)+// Heading tokensfor (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);+ const leading = computeLeading(size);- tokens[`--heading-${level}-size`] = pxToRem(size);+ tokens[`--heading-${level}-size`] = `var(${STEP_TO_SIZE_TOKEN[step]})`;tokens[`--heading-${level}-weight`] = headingWeights[level];tokens[`--heading-${level}-leading`] = `${leading}`;}@@ -232,9 +300,9 @@ export function expandTypeScale(config: XDSTypeScaleConfig): TypeScaleTokens {// Text tokensfor (const [type, step] of Object.entries(TEXT_STEPS)) {const size = computeSize(base, ratio, step);- const leading = computeLeading(size, TEXT_LH_RATIOS[type]);+ const leading = computeLeading(size);- tokens[`--text-${type}-size`] = pxToRem(size);+ tokens[`--text-${type}-size`] = `var(${STEP_TO_SIZE_TOKEN[step]})`;tokens[`--text-${type}-weight`] = textWeights[type];tokens[`--text-${type}-leading`] = `${leading}`;}@@ -246,10 +314,6 @@ export function expandTypeScale(config: XDSTypeScaleConfig): TypeScaleTokens {// 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)',@@ -259,30 +323,13 @@ const TEXT_FONT_FAMILIES: Record<string, string> = {};/**- * 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)'- * ```+ * Generate component style overrides for heading and text components.*/export function generateTypeScaleComponents(config: XDSTypeScaleConfig,): Record<string, Record<string, Record<string, string>>> {const components: Record<string, Record<string, Record<string, string>>> = {};- // Heading overridesconst headingRules: Record<string, Record<string, string>> = {};for (const level of [1, 2, 3, 4, 5, 6]) {headingRules[`level:${level}`] = {@@ -294,7 +341,6 @@ export function generateTypeScaleComponents(}components.heading = headingRules;- // Text overridesconst textRules: Record<string, Record<string, string>> = {};for (const type of ['body', 'large', 'label', 'code', 'supporting']) {textRules[`type:${type}`] = {diff --git a/packages/core/src/theme/generateThemeRules.test.ts b/packages/core/src/theme/generateThemeRules.test.tsindex 2d820b06a8..3d94a75a49 100644--- a/packages/core/src/theme/generateThemeRules.test.ts+++ b/packages/core/src/theme/generateThemeRules.test.ts@@ -28,37 +28,65 @@ describe('generateThemeRules', () => {it('produces an array of CSS rule strings', () => {expect(Array.isArray(rules)).toBe(true);expect(rules.length).toBeGreaterThan(0);- rules.forEach((r) => expect(typeof r).toBe('string'));+ rules.forEach(r => expect(typeof r).toBe('string'));});// --- Token block ---it('includes :scope token block with type scale tokens', () => {- const scopeRule = rules.find((r) => r.includes(':scope'));+ const scopeRule = rules.find(r => r.includes(':scope'));expect(scopeRule).toBeDefined();- expect(scopeRule).toContain('--heading-1-size: 1.5rem');- expect(scopeRule).toContain('--heading-4-size: 0.875rem');- expect(scopeRule).toContain('--text-body-size: 0.875rem');- expect(scopeRule).toContain('--text-supporting-size: 0.75rem');- });-- it('emits font sizes in rem', () => {- const scopeRule = rules.find((r) => r.includes(':scope'))!;- const sizeMatches = scopeRule.match(/--(?:heading|text)-\w+-size: [^;]+/g);- expect(sizeMatches).not.toBeNull();- sizeMatches!.forEach((m) => {- expect(m).toMatch(/rem$/);- expect(m).not.toContain('px');+ // Raw size tokens are rem values+ expect(scopeRule).toContain('--text-base: 0.875rem');+ expect(scopeRule).toContain('--text-2xl: 1.5rem');+ // Semantic tokens are var() refs+ expect(scopeRule).toContain('--heading-1-size: var(--text-2xl)');+ expect(scopeRule).toContain('--heading-4-size: var(--text-base)');+ expect(scopeRule).toContain('--text-body-size: var(--text-base)');+ expect(scopeRule).toContain('--text-supporting-size: var(--text-sm)');+ });++ it('emits raw size tokens in rem', () => {+ const scopeRule = rules.find(r => r.includes(':scope'))!;+ // Raw tokens (--text-4xs through --text-4xl) should be in rem+ const rawSizeTokens = [+ '--text-4xs',+ '--text-3xs',+ '--text-2xs',+ '--text-xsm',+ '--text-sm',+ '--text-base',+ '--text-lg',+ '--text-xl',+ '--text-2xl',+ '--text-3xl',+ '--text-4xl',+ ];+ for (const token of rawSizeTokens) {+ const match = scopeRule.match(new RegExp(`${token}: ([^;]+)`));+ expect(match).not.toBeNull();+ expect(match![1]).toMatch(/rem$/);+ }+ });++ it('emits semantic size tokens as var() refs', () => {+ const scopeRule = rules.find(r => r.includes(':scope'))!;+ const semanticSizeTokens = scopeRule.match(+ /--(?:heading-\d|text-(?:body|large|label|code|supporting))-size: [^;]+/g,+ );+ expect(semanticSizeTokens).not.toBeNull();+ semanticSizeTokens!.forEach(m => {+ expect(m).toContain('var(--text-');});});it('emits line heights as unitless ratios', () => {- const scopeRule = rules.find((r) => r.includes(':scope'))!;+ const scopeRule = rules.find(r => r.includes(':scope'))!;const leadingMatches = scopeRule.match(/--(?:heading|text)-\w+-leading: [^;]+/g,);expect(leadingMatches).not.toBeNull();- leadingMatches!.forEach((m) => {+ leadingMatches!.forEach(m => {expect(m).not.toContain('px');expect(m).not.toContain('rem');const val = parseFloat(m.split(': ')[1]);@@ -71,9 +99,7 @@ describe('generateThemeRules', () => {it('includes .xds-heading.level-* rules for all 6 levels', () => {for (let level = 1; level <= 6; level++) {- const rule = rules.find((r) =>- r.includes(`.xds-heading.level-${level}`),- );+ const rule = rules.find(r => r.includes(`.xds-heading.level-${level}`));expect(rule).toBeDefined();expect(rule).toContain('font-family');expect(rule).toContain(`var(--heading-${level}-size)`);@@ -84,16 +110,14 @@ describe('generateThemeRules', () => {it('includes .xds-text.* rules for all 5 types', () => {for (const type of ['body', 'large', 'label', 'code', 'supporting']) {- const rule = rules.find((r) => r.includes(`.xds-text.${type}`));+ const rule = rules.find(r => r.includes(`.xds-text.${type}`));expect(rule).toBeDefined();expect(rule).toContain(`var(--text-${type}-size)`);}});it('includes explicit component overrides', () => {- const buttonRule = rules.find((r) =>- r.includes('.xds-button.secondary'),- );+ const buttonRule = rules.find(r => r.includes('.xds-button.secondary'));expect(buttonRule).toBeDefined();expect(buttonRule).toContain('light-dark(rgba(5, 54, 89, 0.1)');});@@ -102,36 +126,37 @@ describe('generateThemeRules', () => {it('includes prose heading rules with computed values', () => {const h1Rule = rules.find(- (r) => r.trimStart().startsWith('h1 {') || r.includes('\n h1 {'),+ r => r.trimStart().startsWith('h1 {') || r.includes('\n h1 {'),);expect(h1Rule).toBeDefined();- expect(h1Rule).toContain('1.5rem');+ // Prose rules use val() helper which resolves to the token value (now a var ref)+ expect(h1Rule).toContain('var(--text-2xl)');expect(h1Rule).toContain('var(--font-weight-semibold)');});it('includes prose p rule with computed values', () => {const pRule = rules.find(- (r) => r.trimStart().startsWith('p {') || r.includes('\n p {'),+ r => r.trimStart().startsWith('p {') || r.includes('\n p {'),);expect(pRule).toBeDefined();- expect(pRule).toContain('0.875rem');+ expect(pRule).toContain('var(--text-base)');expect(pRule).toContain('var(--color-text-primary)');});it('includes prose small, code, hr rules', () => {- expect(rules.some((r) => r.includes('small {'))).toBe(true);- expect(rules.some((r) => r.includes('code, pre {'))).toBe(true);- expect(rules.some((r) => r.includes('hr {'))).toBe(true);+ expect(rules.some(r => r.includes('small {'))).toBe(true);+ expect(rules.some(r => r.includes('code, pre {'))).toBe(true);+ expect(rules.some(r => r.includes('hr {'))).toBe(true);});// --- Prop-level color overrides ---it('includes color prop overrides for text and heading', () => {- expect(rules.some((r) => r.includes('.xds-text.primary'))).toBe(true);- expect(rules.some((r) => r.includes('.xds-text.secondary'))).toBe(true);- expect(rules.some((r) => r.includes('.xds-heading.primary'))).toBe(true);- expect(rules.some((r) => r.includes('.xds-heading.disabled'))).toBe(true);- expect(rules.some((r) => r.includes('.xds-text.active'))).toBe(true);+ expect(rules.some(r => r.includes('.xds-text.primary'))).toBe(true);+ expect(rules.some(r => r.includes('.xds-text.secondary'))).toBe(true);+ expect(rules.some(r => r.includes('.xds-heading.primary'))).toBe(true);+ expect(rules.some(r => r.includes('.xds-heading.disabled'))).toBe(true);+ expect(rules.some(r => r.includes('.xds-text.active'))).toBe(true);});// --- Consistency ---@@ -163,10 +188,8 @@ describe('generateThemeRules with weight overrides', () => {const rules = generateThemeRules(theme);it('reflects weight override in tokens', () => {- const scopeRule = rules.find((r) => r.includes(':scope'))!;- expect(scopeRule).toContain(- '--heading-3-weight: var(--font-weight-bold)',- );+ const scopeRule = rules.find(r => r.includes(':scope'))!;+ expect(scopeRule).toContain('--heading-3-weight: var(--font-weight-bold)');// Other levels keep defaultexpect(scopeRule).toContain('--heading-1-weight: var(--font-weight-semibold)',@@ -175,7 +198,7 @@ describe('generateThemeRules with weight overrides', () => {it('reflects weight override in prose h3', () => {const h3Rule = rules.find(- (r) => r.trimStart().startsWith('h3 {') || r.includes('\n h3 {'),+ r => r.trimStart().startsWith('h3 {') || r.includes('\n h3 {'),);expect(h3Rule).toBeDefined();expect(h3Rule).toContain('var(--font-weight-bold)');diff --git a/packages/core/src/theme/tokens.stylex.ts b/packages/core/src/theme/tokens.stylex.tsindex 7b933603da..afd6d7622e 100644--- a/packages/core/src/theme/tokens.stylex.ts+++ b/packages/core/src/theme/tokens.stylex.ts@@ -298,17 +298,18 @@ export const typographyVars = stylex.defineVars(typographyDefaults);// =============================================================================export const textSizeDefaults = {- '--text-4xs': '0.5rem', // 8px - citation- '--text-3xs': '0.625rem', // 10px - micro- '--text-2xs': '0.6875rem', // 11px - small micro- '--text-xsm': '0.75rem', // 12px - supporting, badge- '--text-sm': '0.8125rem', // 13px - secondary text- '--text-base': '0.875rem', // 14px - body text (XDS default)- '--text-lg': '1rem', // 16px - large body- '--text-xl': '1.125rem', // 18px - h2- '--text-2xl': '1.25rem', // 20px - h1- '--text-3xl': '1.5rem', // 24px - editorial h2- '--text-4xl': '2rem', // 32px - editorial h1, data viz+ // Full geometric scale: round(14 × 1.2^step) / 16, default base=14, ratio=1.2+ '--text-4xs': '0.375rem', // step -5: 6px (14 × 1.2⁻⁵ ≈ 5.63 → 6)+ '--text-3xs': '0.4375rem', // step -4: 7px (14 × 1.2⁻⁴ ≈ 6.75 → 7)+ '--text-2xs': '0.5rem', // step -3: 8px (14 × 1.2⁻³ ≈ 8.10 → 8)+ '--text-xsm': '0.625rem', // step -2: 10px (14 × 1.2⁻² ≈ 9.72 → 10)+ '--text-sm': '0.75rem', // step -1: 12px (14 × 1.2⁻¹ ≈ 11.67 → 12)+ '--text-base': '0.875rem', // step 0: 14px — base anchor+ '--text-lg': '1.0625rem', // step +1: 17px (14 × 1.2¹ ≈ 16.8 → 17)+ '--text-xl': '1.25rem', // step +2: 20px (14 × 1.2² ≈ 20.16 → 20)+ '--text-2xl': '1.5rem', // step +3: 24px (14 × 1.2³ ≈ 24.19 → 24)+ '--text-3xl': '1.8125rem', // step +4: 29px (14 × 1.2⁴ ≈ 29.03 → 29)+ '--text-4xl': '2.1875rem', // step +5: 35px (14 × 1.2⁵ ≈ 34.84 → 35)} as const;/** @deprecated Use textSizeDefaults */@@ -379,45 +380,49 @@ export type FontWeightVarName = keyof typeof fontWeightDefaults;// 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³)+ // Sizes are var() references to raw size tokens.+ // Line heights are hardcoded computed values (4px grid snapped, tiered target).+ // When typeScale is used in defineTheme, both raw tokens AND these semantic+ // tokens are overridden together.+ //+ // Step mapping: h6=-2, h5=-1, h4=0(base), h3=+1, h2=+2, h1=+3+ //+ // Heading tokens+ '--heading-1-size': 'var(--text-2xl)', // step +3: 24px'--heading-1-weight': 'var(--font-weight-semibold)',- '--heading-1-leading': '1.3333',- '--heading-2-size': 'var(--text-2xl)', // 20px (14 × 1.2²)+ '--heading-1-leading': '1.3333', // 24px → 32px (target 1.4, 4px snap)+ '--heading-2-size': 'var(--text-xl)', // step +2: 20px'--heading-2-weight': 'var(--font-weight-semibold)',- '--heading-2-leading': '1.4',- '--heading-3-size': '17px', // 14 × 1.2¹ (no matching --text-* token)+ '--heading-2-leading': '1.4', // 20px → 28px (target 1.4, 4px snap)+ '--heading-3-size': 'var(--text-lg)', // step +1: 17px'--heading-3-weight': 'var(--font-weight-semibold)',- '--heading-3-leading': '1.4118',- '--heading-4-size': 'var(--text-base)', // 14px — base anchor+ '--heading-3-leading': '1.4118', // 17px → 24px (target 1.5, 4px snap)+ '--heading-4-size': 'var(--text-base)', // step 0: 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-4-leading': '1.4286', // 14px → 20px (target 1.5, 4px snap)+ '--heading-5-size': 'var(--text-sm)', // step -1: 12px'--heading-5-weight': 'var(--font-weight-semibold)',- '--heading-5-leading': '1.3333',- '--heading-6-size': 'var(--text-3xs)', // 10px (14 × 1.2⁻²)+ '--heading-5-leading': '1.6667', // 12px → 20px (target 1.5, 4px snap)+ '--heading-6-size': 'var(--text-xsm)', // step -2: 10px'--heading-6-weight': 'var(--font-weight-semibold)',- '--heading-6-leading': '1.6',+ '--heading-6-leading': '1.6', // 10px → 16px (target 1.5, min dominated)- // Text tokens — body/label/code at base, large one step up, supporting one step down+ // Text tokens — body/label/code at base(0), large at +1, supporting at -1'--text-body-size': 'var(--text-base)', // 14px'--text-body-weight': 'var(--font-weight-normal)',- '--text-body-leading': '1.4286',- '--text-large-size': '17px', // 14 × 1.2¹ (no matching --text-* token)+ '--text-body-leading': '1.4286', // 14px → 20px+ '--text-large-size': 'var(--text-lg)', // 17px'--text-large-weight': 'var(--font-weight-semibold)',- '--text-large-leading': '1.4118',+ '--text-large-leading': '1.4118', // 17px → 24px'--text-label-size': 'var(--text-base)', // 14px'--text-label-weight': 'var(--font-weight-medium)',- '--text-label-leading': '1.4286',+ '--text-label-leading': '1.4286', // 14px → 20px'--text-code-size': 'var(--text-base)', // 14px'--text-code-weight': 'var(--font-weight-normal)',- '--text-code-leading': '1.4286',- '--text-supporting-size': 'var(--text-xsm)', // 12px+ '--text-code-leading': '1.4286', // 14px → 20px+ '--text-supporting-size': 'var(--text-sm)', // 12px'--text-supporting-weight': 'var(--font-weight-normal)',- '--text-supporting-leading': '1.6667',+ '--text-supporting-leading': '1.6667', // 12px → 20px} as const;export const typeScaleVars = stylex.defineVars(typeScaleDefaults);