An open source design system that's fully customizable and agent ready
TypeScript
feat(theme): unified typography config + defineTheme API cleanup (#804)
Cindy Zhang586068b69502
diff --git a/packages/cli/docs/theme.doc.mjs b/packages/cli/docs/theme.doc.mjsindex 3051b279d9..b98217b805 100644--- a/packages/cli/docs/theme.doc.mjs+++ b/packages/cli/docs/theme.doc.mjs@@ -129,8 +129,12 @@ export const myTheme: Theme = {const myTheme = defineTheme({name: 'my-theme',- typeScale: { base: 14, ratio: 1.2 }, // generates heading + text tokens- radiusScale: { base: 4, multiplier: 1 }, // generates radius tokens+ typography: {+ scale: { base: 14, ratio: 1.2 }, // generates heading + text tokens+ body: { family: 'Inter', fallbacks: '-apple-system, sans-serif' },+ },+ radius: { base: 4, multiplier: 1 }, // generates radius tokens+ motion: { fast: 175, medium: 410, ratio: 0.75 },tokens: {'--color-accent': ['#7B61FF', '#9B85FF'], // explicit overrides win},@@ -143,8 +147,10 @@ const myTheme = defineTheme({type: 'table',headers: ['Config', 'Generates', 'Parameters'],rows: [- ['typeScale', '--heading-*-size/weight/leading, --text-*-size/weight/leading', 'base (px), ratio, weights?'],- ['radiusScale', '--radius-0 through --radius-4, --radius-rounded', 'base (px), multiplier (0–2)'],+ ['typography.scale', '--heading-*-size/weight/leading, --text-*-size/weight/leading', 'base (px), ratio'],+ ['typography.body/heading/code', '--font-body, --font-heading, --font-code', 'family, fallbacks?, url?, weight?'],+ ['radius', '--radius-0 through --radius-4, --radius-rounded', 'base (px), multiplier (0–2)'],+ ['motion', '--duration-fast-*, --duration-medium-*, --ease-*', 'fast (ms), medium (ms), ratio, easing?'],],},],diff --git a/packages/cli/docs/theme.md b/packages/cli/docs/theme.mdindex c76717b374..02e4ea4a53 100644--- a/packages/cli/docs/theme.md+++ b/packages/cli/docs/theme.md@@ -133,10 +133,10 @@ const myTheme = defineTheme({name: 'my-theme',// Type scale — generates heading and text tokens from base size + ratio- typeScale: {base: 14, ratio: 1.2},+ typography: {scale: {base: 14, ratio: 1.2}},// Radius scale — generates radius tokens from base unit + multiplier- radiusScale: {base: 4, multiplier: 1},+ radius: {base: 4, multiplier: 1},// Explicit token overrides (highest precedence — overrides scale values)tokens: {@@ -154,10 +154,10 @@ const myTheme = defineTheme({**Scale configs:**-| Config | What it generates | Parameters |-| ------------- | ----------------------------------------------------------------- | -------------------------------- |-| `typeScale` | `--heading-*-size/weight/leading`, `--text-*-size/weight/leading` | `base` (px), `ratio`, `weights?` |-| `radiusScale` | `--radius-0` through `--radius-4`, `--radius-rounded` | `base` (px), `multiplier` (0–2) |+| Config | What it generates | Parameters |+| ------------------ | ----------------------------------------------------------------- | -------------------------------- |+| `typography.scale` | `--heading-*-size/weight/leading`, `--text-*-size/weight/leading` | `base` (px), `ratio`, `weights?` |+| `radius` | `--radius-0` through `--radius-4`, `--radius-rounded` | `base` (px), `multiplier` (0–2) |Explicit `tokens` overrides always take precedence over scale-generated values.diff --git a/packages/cli/docs/tokens.doc.mjs b/packages/cli/docs/tokens.doc.mjsindex 9fefea4e4b..3cda919de4 100644--- a/packages/cli/docs/tokens.doc.mjs+++ b/packages/cli/docs/tokens.doc.mjs@@ -98,7 +98,7 @@ export const docs = {content: [{type: 'prose',- text: 'Numeric scale based on a 4dp base unit. Tokens 1–4 scale with the theme\'s radiusScale multiplier; tokens 0 and rounded are fixed.',+ text: 'Numeric scale based on a 4dp base unit. Tokens 1–4 scale with the theme\'s radius multiplier; tokens 0 and rounded are fixed.',},{type: 'table',@@ -114,24 +114,24 @@ export const docs = {},{type: 'prose',- text: 'Use radiusScale in defineTheme to generate all radius tokens from a base unit and multiplier: defineTheme({ radiusScale: { base: 4, multiplier: 1.5 } }). Multiplier 0 = sharp, 1 = default, 1.5 = rounded, 2 = pill-like. Explicit token overrides take precedence over radiusScale values.',+ text: 'Use radius in defineTheme to generate all radius tokens from a base unit and multiplier: defineTheme({ radius: { base: 4, multiplier: 1.5 } }). Multiplier 0 = sharp, 1 = default, 1.5 = rounded, 2 = pill-like. Explicit token overrides take precedence over radius values.',},{type: 'code',lang: 'tsx',- label: 'radiusScale example',+ label: 'radius example',code: `import {defineTheme} from '@xds/core/theme';// Rounded theme — all scalable radii increased by 50%const roundedTheme = defineTheme({name: 'rounded',- radiusScale: { base: 4, multiplier: 1.5 },+ radius: { base: 4, multiplier: 1.5 },});// Sharp/brutalist theme — all scalable radii become 0const sharpTheme = defineTheme({name: 'sharp',- radiusScale: { base: 4, multiplier: 0 },+ radius: { base: 4, multiplier: 0 },tokens: { '--radius-rounded': '0px' }, // even pills are sharp});`,},diff --git a/packages/cli/docs/tokens.md b/packages/cli/docs/tokens.mdindex b6eb2a4b03..b23c1a7a88 100644--- a/packages/cli/docs/tokens.md+++ b/packages/cli/docs/tokens.md@@ -65,7 +65,7 @@ Control heights for consistent sizing across buttons, inputs, and selectors.## Radius Tokens-Numeric scale based on a 4dp base unit. Tokens 1–4 scale with the theme's `radiusScale` multiplier; tokens 0 and rounded are fixed.+Numeric scale based on a 4dp base unit. Tokens 1–4 scale with the theme's `radius` multiplier; tokens 0 and rounded are fixed.| Token | Value | Usage | Scales || ---------------- | ------ | ------------------------------------- | ------ |@@ -76,7 +76,7 @@ Numeric scale based on a 4dp base unit. Tokens 1–4 scale with the theme's `rad| --radius-4 | 16px | Page sections, large containers | Yes || --radius-rounded | 9999px | Badges, avatars, status dots, toggles | No |-### radiusScale (via defineTheme)+### radius (via defineTheme)Generate all radius tokens from a base unit and multiplier:@@ -85,14 +85,14 @@ import {defineTheme} from '@xds/core/theme';const roundedTheme = defineTheme({name: 'rounded',- radiusScale: {base: 4, multiplier: 1.5},+ radius: {base: 4, multiplier: 1.5},// Produces: radius-1=6px, radius-2=12px, radius-3=18px, radius-4=24px// radius-0 stays 0px, radius-rounded stays 9999px});const sharpTheme = defineTheme({name: 'sharp',- radiusScale: {base: 4, multiplier: 0},+ radius: {base: 4, multiplier: 0},// All scalable radii become 0px});```@@ -151,7 +151,7 @@ Default: base=14px, ratio=1.2.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()`.+Override the entire scale with `typography.scale: { base, ratio }` in `defineTheme()`.#### Heading Tokens@@ -205,7 +205,7 @@ Override the entire scale with `typeScale: { base, ratio }` in `defineTheme()`.### Line Heights (Named Leading)-Intent-based ratios for component use. Not modified by `typeScale`.+Intent-based ratios for component use. Not modified by `typography.scale`.| Token | Value | Usage || ----------------- | ------ | ---------------------------- |diff --git a/packages/cli/src/commands/build-theme.mjs b/packages/cli/src/commands/build-theme.mjsindex 2c991ff447..f7ac192a90 100644--- a/packages/cli/src/commands/build-theme.mjs+++ b/packages/cli/src/commands/build-theme.mjs@@ -15,7 +15,7 @@ import * as path from 'node:path';import {createRequire} from 'node:module';// Import shared theme processing from core — ensures build and runtime-// use the same logic for typeScale expansion, prose, and component rules.+// use the same logic for typography.scale expansion, prose, and component rules.const _require = createRequire(import.meta.url);let _defineTheme = null;let _generateThemeRules = null;@@ -592,15 +592,19 @@ export function registerTheme(program) {// Generate CSS using the shared generateThemeRules from core.// This ensures build and runtime produce identical rule sets.let css;+ let resolvedTheme;if (_defineTheme && _generateThemeRules) {- // Shared path: run through defineTheme (expands typeScale, merges+ // Shared path: run through defineTheme (expands typography.scale, merges// components) then generateThemeRules with computedValues for// self-contained CSS output.- const resolvedTheme = _defineTheme({+ resolvedTheme = _defineTheme({name: themeDef.name,- typeScale: themeDef.typeScale,+ typography: themeDef.typography,+ motion: themeDef.motion,+ radius: themeDef.radius,tokens: themeDef.tokens,components: themeDef.components,+ variants: themeDef.variants,});const rules = _generateThemeRules(resolvedTheme);if (rules.length === 0) {@@ -698,10 +702,10 @@ Or with a <link> tag:</XDSTheme>`);- // Print font declaration warnings- if (themeDef.fonts && themeDef.fonts.length > 0) {+ // Print font declaration warnings (derived from typography roles)+ if (resolvedTheme && resolvedTheme.fonts && resolvedTheme.fonts.length > 0) {console.log(`\n⚠ Theme "${themeDef.name}" requires fonts not included in the build:`);- for (const font of themeDef.fonts) {+ for (const font of resolvedTheme.fonts) {console.log(` ${font.family} — add to your document <head>:`);console.log(` <link rel="stylesheet" href="${font.url}" />`);}diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.tsindex 096562d078..0476a4e241 100644--- a/packages/core/src/theme/defineTheme.test.ts+++ b/packages/core/src/theme/defineTheme.test.ts@@ -234,11 +234,11 @@ describe('generateThemeCSS with components', () => {});});-describe('typeScale', () => {- it('generates typography token overrides when typeScale is provided', () => {+describe('typography.scale', () => {+ it('generates typography token overrides when typography.scale is provided', () => {const theme = defineTheme({name: 'dense',- typeScale: {base: 12, ratio: 1.125},+ typography: {scale: {base: 12, ratio: 1.125}},});// Semantic tokens are now var() refs; raw token has the computed valueexpect(theme.tokens['--heading-4-size']).toBe('var(--text-base)');@@ -249,7 +249,7 @@ describe('typeScale', () => {it('generates 44 tokens (11 raw size + 33 semantic)', () => {const theme = defineTheme({name: 'custom',- typeScale: {base: 14, ratio: 1.2},+ typography: {scale: {base: 14, ratio: 1.2}},});// 11 raw size (--text-4xs…--text-4xl) + 33 semantic = 44// Filtering for --heading- or --text- captures raw + semantic = 11 + 15 + 18 = 44@@ -259,30 +259,30 @@ describe('typeScale', () => {expect(typeScaleKeys).toHaveLength(54);});- it('explicit tokens override typeScale-generated values', () => {+ it('explicit tokens override scale-generated values', () => {const theme = defineTheme({name: 'override-test',- typeScale: {base: 14, ratio: 1.2},+ typography: {scale: {base: 14, ratio: 1.2}},tokens: {'--heading-1-size': '40px',},});- // Explicit token should win over typeScale+ // Explicit token should win over typography.scaleexpect(theme.tokens['--heading-1-size']).toBe('40px');- // Non-overridden typeScale token should still be a var() ref+ // Non-overridden scale token should still be a var() refexpect(theme.tokens['--heading-4-size']).toBe('var(--text-base)');});- it('works without typeScale (backwards compatible)', () => {+ it('works without typography.scale (backwards compatible)', () => {const theme = defineTheme({name: 'no-scale'});// No type scale tokens should be presentexpect(theme.tokens['--heading-1-size']).toBeUndefined();});- it('combines typeScale with other token overrides', () => {+ it('combines typography.scale with other token overrides', () => {const theme = defineTheme({name: 'combo',- typeScale: {base: 16, ratio: 1.25},+ typography: {scale: {base: 16, ratio: 1.25}},tokens: {'--color-accent': '#FF0000',},@@ -293,11 +293,11 @@ describe('typeScale', () => {});});-describe('typeScale component auto-generation', () => {- it('auto-generates heading component overrides when typeScale is provided', () => {+describe('typography.scale component auto-generation', () => {+ it('auto-generates heading component overrides when typography.scale is provided', () => {const theme = defineTheme({name: 'auto',- typeScale: {base: 14, ratio: 1.2},+ typography: {scale: {base: 14, ratio: 1.2}},});expect(theme.components?.heading?.['level:1']).toBeDefined();expect(theme.components?.heading?.['level:1']?.fontSize).toBe(@@ -305,10 +305,10 @@ describe('typeScale component auto-generation', () => {);});- it('auto-generates text component overrides when typeScale is provided', () => {+ it('auto-generates text component overrides when typography.scale is provided', () => {const theme = defineTheme({name: 'auto',- typeScale: {base: 14, ratio: 1.2},+ typography: {scale: {base: 14, ratio: 1.2}},});expect(theme.components?.text?.['type:body']).toBeDefined();expect(theme.components?.text?.['type:body']?.fontSize).toBe(@@ -319,7 +319,7 @@ describe('typeScale component auto-generation', () => {it('does not include color in auto-generated rules', () => {const theme = defineTheme({name: 'auto',- typeScale: {base: 14, ratio: 1.2},+ typography: {scale: {base: 14, ratio: 1.2}},});expect(theme.components?.heading?.['level:1']?.color).toBeUndefined();expect(theme.components?.text?.['type:supporting']?.color).toBeUndefined();@@ -328,7 +328,7 @@ describe('typeScale component auto-generation', () => {it('explicit components deep-merge on top of auto-generated', () => {const theme = defineTheme({name: 'custom',- typeScale: {base: 14, ratio: 1.2},+ typography: {scale: {base: 14, ratio: 1.2}},components: {heading: {'level:1': {letterSpacing: '-0.02em'},@@ -350,7 +350,7 @@ describe('typeScale component auto-generation', () => {expect(theme.components?.button?.base?.borderRadius).toBe('999px');});- it('does not generate components when typeScale is absent', () => {+ it('does not generate components when typography.scale is absent', () => {const theme = defineTheme({name: 'bare'});expect(theme.components).toBeUndefined();});@@ -358,7 +358,7 @@ describe('typeScale component auto-generation', () => {it('explicit heading overrides win over auto-generated', () => {const theme = defineTheme({name: 'override',- typeScale: {base: 14, ratio: 1.2},+ typography: {scale: {base: 14, ratio: 1.2}},components: {heading: {'level:1': {fontFamily: '"Playfair Display", serif'},@@ -376,11 +376,11 @@ describe('typeScale component auto-generation', () => {});});-describe('radiusScale', () => {- it('generates radius tokens from radiusScale', () => {+describe('radius', () => {+ it('generates radius tokens from radius', () => {const theme = defineTheme({name: 'rounded',- radiusScale: {base: 4, multiplier: 1.5},+ radius: {base: 4, multiplier: 1.5},});expect(theme.tokens['--radius-1']).toBe('6px');expect(theme.tokens['--radius-2']).toBe('12px');@@ -390,20 +390,20 @@ describe('radiusScale', () => {expect(theme.tokens['--radius-rounded']).toBe('9999px');});- it('explicit tokens override radiusScale', () => {+ it('explicit tokens override radius', () => {const theme = defineTheme({name: 'custom',- radiusScale: {base: 4, multiplier: 1},+ radius: {base: 4, multiplier: 1},tokens: {'--radius-3': '20px'},});expect(theme.tokens['--radius-3']).toBe('20px');- expect(theme.tokens['--radius-2']).toBe('8px'); // from radiusScale+ expect(theme.tokens['--radius-2']).toBe('8px'); // from radius});- it('radiusScale with multiplier 0 produces sharp theme', () => {+ it('radius with multiplier 0 produces sharp theme', () => {const theme = defineTheme({name: 'sharp',- radiusScale: {base: 4, multiplier: 0},+ radius: {base: 4, multiplier: 0},});expect(theme.tokens['--radius-1']).toBe('0px');expect(theme.tokens['--radius-2']).toBe('0px');@@ -413,16 +413,16 @@ describe('radiusScale', () => {expect(theme.tokens['--radius-rounded']).toBe('9999px');});- it('works without radiusScale (backwards compatible)', () => {+ it('works without radius (backwards compatible)', () => {const theme = defineTheme({name: 'no-scale'});expect(theme.tokens['--radius-0']).toBeUndefined();});- it('combines radiusScale with typeScale and other tokens', () => {+ it('combines radius with typography.scale and other tokens', () => {const theme = defineTheme({name: 'combo',- typeScale: {base: 16, ratio: 1.25},- radiusScale: {base: 4, multiplier: 1},+ typography: {scale: {base: 16, ratio: 1.25}},+ radius: {base: 4, multiplier: 1},tokens: {'--color-accent': '#FF0000',},@@ -546,52 +546,204 @@ describe('variants', () => {});});-describe('defineTheme fonts', () => {- it('passes through fonts array from input', () => {- const fonts = [- {- family: 'Figtree',- url: 'https://fonts.googleapis.com/css2?family=Figtree:wght@400;500;600;700',- },- {- family: 'JetBrains Mono',- url: 'https://fonts.googleapis.com/css2?family=JetBrains+Mono',+describe('typography fonts derivation', () => {+ it('derives fonts array from typography roles with urls', () => {+ const theme = defineTheme({+ name: 'font-test',+ typography: {+ body: {+ family: 'Figtree',+ fallbacks: 'sans-serif',+ url: 'https://fonts.googleapis.com/css2?family=Figtree:wght@400;500;600;700',+ },+ code: {+ family: 'JetBrains Mono',+ fallbacks: 'monospace',+ url: 'https://fonts.googleapis.com/css2?family=JetBrains+Mono',+ },},- ];- const theme = defineTheme({name: 'font-test', fonts});- expect(theme.fonts).toEqual(fonts);+ });expect(theme.fonts).toHaveLength(2);expect(theme.fonts![0].family).toBe('Figtree');+ expect(theme.fonts![1].family).toBe('JetBrains Mono');expect(theme.fonts![1].url).toContain('JetBrains');});- it('returns undefined fonts when not specified', () => {+ it('returns undefined fonts when no typography specified', () => {const theme = defineTheme({name: 'no-fonts'});expect(theme.fonts).toBeUndefined();});- it('handles empty fonts array', () => {- const theme = defineTheme({name: 'empty-fonts', fonts: []});- expect(theme.fonts).toEqual([]);- expect(theme.fonts).toHaveLength(0);+ it('returns undefined fonts when typography has no urls', () => {+ const theme = defineTheme({+ name: 'no-urls',+ typography: {+ body: {family: 'Courier New', fallbacks: 'monospace'},+ },+ });+ expect(theme.fonts).toBeUndefined();});- it('combines fonts with tokens and other features', () => {+ it('deduplicates fonts when heading inherits from body', () => {const theme = defineTheme({- name: 'combo-fonts',- tokens: {'--font-heading': '"Figtree", sans-serif'},- fonts: [- {+ name: 'dedup',+ typography: {+ body: {+ family: 'Geist',+ fallbacks: 'sans-serif',+ url: 'https://example.com/geist.css',+ },+ // heading inherits body — same font, should not duplicate+ },+ });+ expect(theme.fonts).toHaveLength(1);+ expect(theme.fonts![0].family).toBe('Geist');+ });++ it('derives font family tokens from typography roles', () => {+ const theme = defineTheme({+ name: 'family-tokens',+ typography: {+ body: {family: 'Geist', fallbacks: '-apple-system, sans-serif'},+ code: {family: 'Geist Mono', fallbacks: '"SF Mono", monospace'},+ },+ });+ expect(theme.tokens['--font-body']).toBe(+ 'Geist, -apple-system, sans-serif',+ );+ expect(theme.tokens['--font-heading']).toBe(+ 'Geist, -apple-system, sans-serif',+ ); // inherited from body+ expect(theme.tokens['--font-code']).toBe(+ '"Geist Mono", "SF Mono", monospace',+ );+ });++ it('heading family overrides body when specified', () => {+ const theme = defineTheme({+ name: 'heading-override',+ typography: {+ body: {family: 'Inter', fallbacks: 'sans-serif'},+ heading: {family: 'Playfair Display', fallbacks: 'serif'},+ },+ });+ expect(theme.tokens['--font-body']).toBe('Inter, sans-serif');+ expect(theme.tokens['--font-heading']).toBe('"Playfair Display", serif');+ });++ it('explicit tokens override typography-derived font tokens', () => {+ const theme = defineTheme({+ name: 'token-wins',+ typography: {+ body: {family: 'Geist', fallbacks: 'sans-serif'},+ },+ tokens: {'--font-heading': '"Custom", serif'},+ });+ // Explicit token wins over typography-derived+ expect(theme.tokens['--font-heading']).toBe('"Custom", serif');+ // Body still comes from typography+ expect(theme.tokens['--font-body']).toBe('Geist, sans-serif');+ });++ it('combines typography with scale and tokens', () => {+ const theme = defineTheme({+ name: 'combo',+ typography: {+ scale: {base: 14, ratio: 1.2},+ body: {family: 'Figtree',+ fallbacks: 'sans-serif',url: 'https://fonts.googleapis.com/css2?family=Figtree',},- ],- typeScale: {base: 14, ratio: 1.2},+ },});- expect(theme.name).toBe('combo-fonts');+ expect(theme.name).toBe('combo');expect(theme.fonts).toHaveLength(1);- expect(theme.tokens['--font-heading']).toBe('"Figtree", sans-serif');- // typeScale tokens should still be present+ expect(theme.tokens['--font-body']).toBe('Figtree, sans-serif');+ // scale tokens should still be presentexpect(theme.tokens['--heading-4-size']).toBeDefined();});});++describe('typography weight derivation', () => {+ it('applies heading weight from typography role', () => {+ const theme = defineTheme({+ name: 'heading-weight',+ typography: {+ scale: {base: 14, ratio: 1.2},+ heading: {weight: 'bold'},+ },+ });+ // All heading levels should get bold weight+ expect(theme.tokens['--heading-1-weight']).toBe('var(--font-weight-bold)');+ expect(theme.tokens['--heading-4-weight']).toBe('var(--font-weight-bold)');+ });++ it('per-level heading weights override default heading weight', () => {+ const theme = defineTheme({+ name: 'per-level',+ typography: {+ scale: {base: 14, ratio: 1.2},+ heading: {+ weight: 'semibold',+ weights: {3: 'bold', 4: 'bold'},+ },+ },+ });+ expect(theme.tokens['--heading-1-weight']).toBe(+ 'var(--font-weight-semibold)',+ );+ expect(theme.tokens['--heading-3-weight']).toBe('var(--font-weight-bold)');+ expect(theme.tokens['--heading-4-weight']).toBe('var(--font-weight-bold)');+ });++ it('body weight flows to text body token', () => {+ const theme = defineTheme({+ name: 'body-weight',+ typography: {+ scale: {base: 14, ratio: 1.2},+ body: {weight: 'medium'},+ },+ });+ expect(theme.tokens['--text-body-weight']).toBe(+ 'var(--font-weight-medium)',+ );+ });++ it('code weight flows to text code token', () => {+ const theme = defineTheme({+ name: 'code-weight',+ typography: {+ scale: {base: 14, ratio: 1.2},+ code: {weight: 'medium'},+ },+ });+ expect(theme.tokens['--text-code-weight']).toBe(+ 'var(--font-weight-medium)',+ );+ });++ it('named weight maps to var reference', () => {+ const theme = defineTheme({+ name: 'named-weight',+ typography: {+ scale: {base: 14, ratio: 1.2},+ heading: {weight: 'normal'},+ },+ });+ expect(theme.tokens['--heading-1-weight']).toBe(+ 'var(--font-weight-normal)',+ );+ });++ it('raw CSS weight value passes through', () => {+ const theme = defineTheme({+ name: 'raw-weight',+ typography: {+ scale: {base: 14, ratio: 1.2},+ heading: {weight: '900'},+ },+ });+ expect(theme.tokens['--heading-1-weight']).toBe('900');+ });+});diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.tsindex 3eee2f3013..f49c33363c 100644--- a/packages/core/src/theme/defineTheme.ts+++ b/packages/core/src/theme/defineTheme.ts@@ -29,7 +29,7 @@*/import type {XDSIconRegistry} from '../Icon/globalIconRegistry';-import type {ThemeFontSource} from './types';+import type {ThemeFontSource, TypographyConfig, FontWeight} from './types';import {parseStyleKey} from '../utils/parseStyleKey';import {colorDefaults,@@ -133,35 +133,32 @@ 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.+ * Unified typography configuration — fonts, scale, and weights.*- * 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.+ * Replaces the separate `typeScale` and `fonts` fields with a single+ * config. Scale controls sizing; roles (body, heading, code) declare+ * fonts, fallbacks, and weights. Heading inherits from body if omitted.** @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 }+ * typography: {+ * scale: { base: 14, ratio: 1.2 },+ * body: { family: 'Geist', fallbacks: '-apple-system, sans-serif', url: '...' },+ * heading: { weight: 'semibold', weights: { 3: 'bold', 4: 'bold' } },+ * code: { family: 'Geist Mono', fallbacks: '"SF Mono", monospace', url: '...' },+ * }* ```*/- typeScale?: XDSTypeScaleConfig;+ typography?: TypographyConfig;/**- * Motion scale configuration. Computes duration min/max variants from+ * Motion configuration. Computes duration min/max variants from* base values and a scaling ratio: min = base × ratio, max = base / ratio.*- * Explicit `tokens` overrides take precedence over motionScale-generated values.+ * Explicit `tokens` overrides take precedence over motion-generated values.** @example* ```- * motionScale: { fast: 175, medium: 410, ratio: 0.75 }+ * motion: { fast: 175, medium: 410, ratio: 0.75 }** // Suggested starting points:* // Snappy: { fast: 100, medium: 250, ratio: 0.75 }@@ -169,26 +166,26 @@ export interface XDSDefineThemeInput {* // Cinematic: { fast: 200, medium: 500, ratio: 0.7 }* ```*/- motionScale?: XDSMotionScaleConfig;+ motion?: XDSMotionScaleConfig;/**- * Optional radius scale configuration. Generates radius token overrides+ * Radius configuration. Generates radius token overrides* from a base unit and multiplier.** radius-0 and radius-rounded are always fixed (never affected by multiplier).* radius-1 through radius-4 = base * step * multiplier.** When omitted, themes use the hardcoded defaults (base=4, multiplier=1).- * Explicit `tokens` overrides take precedence over radiusScale-generated values.+ * Explicit `tokens` overrides take precedence over radius-generated values.** @example* ```tsx- * radiusScale: { base: 4, multiplier: 1 }+ * radius: { base: 4, multiplier: 1 }** // Sharp/brutalist — all radii become 0- * radiusScale: { base: 4, multiplier: 0 }+ * radius: { base: 4, multiplier: 0 }* ```*/- radiusScale?: XDSRadiusScaleConfig;+ radius?: XDSRadiusScaleConfig;/** 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. */@@ -254,22 +251,6 @@ export interface XDSDefineThemeInput {* ```*/variants?: Record<string, Record<string, Record<string, string>>>;- /**- * Font declarations — fonts this theme requires.- *- * These are not bundled by the build — instead:- * - **Best**: Add `<link rel="stylesheet" href="...">` to your document `<head>` for preloading- * - **Build**: `npx xds theme build` prints instructions for any declared fonts- * - **Runtime**: `XDSTheme` loads missing fonts automatically as a fallback- *- * @example- * ```- * fonts: [- * { family: 'Figtree', url: 'https://fonts.googleapis.com/css2?family=Figtree:wght@400;500;600;700' },- * ]- * ```- */- fonts?: ThemeFontSource[];}/** A defined theme — ready to pass to <XDSTheme> */@@ -368,44 +349,131 @@ function deepMergeComponents(return result;}+/**+ * Resolve a FontWeight name to a var() reference.+ * Named weights map to var(--font-weight-*); raw values pass through.+ */+function resolveFontWeight(weight: FontWeight): string {+ const named: Record<string, string> = {+ normal: 'var(--font-weight-normal)',+ medium: 'var(--font-weight-medium)',+ semibold: 'var(--font-weight-semibold)',+ bold: 'var(--font-weight-bold)',+ };+ return named[weight] ?? weight;+}++/**+ * Build the full CSS font-family value from family + fallbacks.+ * Quotes the family name if it contains spaces.+ */+function buildFontFamily(+ family?: string,+ fallbacks?: string,+): string | undefined {+ if (!family) return undefined;+ const quoted = family.includes(' ') ? `"${family}"` : family;+ if (fallbacks) return `${quoted}, ${fallbacks}`;+ return quoted;+}+/*** 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+ * When `typography.scale` is provided, it generates typography token overrides* that are merged into the token map. Explicit `tokens` entries take- * precedence over typeScale-generated values.+ * precedence over generated values.*/export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {const tokens: Record<string, string> = {};+ // Build typeScale config from typography if present+ const typo = input.typography;+ let typeScaleConfig: XDSTypeScaleConfig | undefined;+ if (typo?.scale) {+ // Collect weight overrides from typography roles+ const headingWeights: Partial<Record<1 | 2 | 3 | 4 | 5 | 6, string>> = {};+ const headingRole = typo.heading;+ if (headingRole?.weights) {+ for (const [level, w] of Object.entries(headingRole.weights)) {+ if (w)+ headingWeights[Number(level) as 1 | 2 | 3 | 4 | 5 | 6] =+ resolveFontWeight(w);+ }+ }+ // Default heading weight from role+ const defaultHeadingWeight = headingRole?.weight+ ? resolveFontWeight(headingRole.weight)+ : undefined;+ if (defaultHeadingWeight) {+ for (let i = 1; i <= 6; i++) {+ if (!(i in headingWeights)) {+ headingWeights[i as 1 | 2 | 3 | 4 | 5 | 6] = defaultHeadingWeight;+ }+ }+ }++ // Text weight overrides from roles+ const textWeights: Partial<Record<string, string>> = {};+ if (typo.body?.weight)+ textWeights.body = resolveFontWeight(typo.body.weight);+ if (typo.code?.weight)+ textWeights.code = resolveFontWeight(typo.code.weight);++ typeScaleConfig = {+ base: typo.scale.base,+ ratio: typo.scale.ratio,+ weights: {+ ...(Object.keys(headingWeights).length > 0+ ? {heading: headingWeights}+ : {}),+ ...(Object.keys(textWeights).length > 0 ? {text: textWeights} : {}),+ },+ };+ }+// 1. Apply typeScale-generated tokens first (lowest precedence)- if (input.typeScale) {- const typeScaleTokens = expandTypeScale(input.typeScale);+ if (typeScaleConfig) {+ const typeScaleTokens = expandTypeScale(typeScaleConfig);for (const [key, value] of Object.entries(typeScaleTokens)) {tokens[key] = value;}}- // 1b. Apply radiusScale-generated tokens (lowest precedence for radius)- if (input.radiusScale) {- const radiusTokens = expandRadiusScale(input.radiusScale);+ // 1b. Apply radius-generated tokens (lowest precedence for radius)+ if (input.radius) {+ const radiusTokens = expandRadiusScale(input.radius);for (const [key, value] of Object.entries(radiusTokens)) {tokens[key] = value;}}- // 1c. Apply motionScale-generated tokens (same precedence as typeScale)- if (input.motionScale) {- const motionTokens = expandMotionScale(input.motionScale);+ // 1c. Apply motion-generated tokens (same precedence as typeScale)+ if (input.motion) {+ const motionTokens = expandMotionScale(input.motion);for (const [key, value] of Object.entries(motionTokens)) {tokens[key] = value;}}- // 2. Apply explicit token overrides (highest precedence — overwrites typeScale/radiusScale/motionScale)+ // 1d. Apply typography font family tokens+ if (typo) {+ // Heading inherits from body if not specified+ const bodyFamily = buildFontFamily(typo.body?.family, typo.body?.fallbacks);+ const headingFamily =+ buildFontFamily(typo.heading?.family, typo.heading?.fallbacks) ??+ bodyFamily;+ const codeFamily = buildFontFamily(typo.code?.family, typo.code?.fallbacks);++ if (bodyFamily) tokens['--font-body'] = bodyFamily;+ if (headingFamily) tokens['--font-heading'] = headingFamily;+ if (codeFamily) tokens['--font-code'] = codeFamily;+ }++ // 2. Apply explicit token overrides (highest precedence — overwrites generated tokens)if (input.tokens) {for (const [key, value] of Object.entries(input.tokens)) {if (value !== undefined) {@@ -416,8 +484,8 @@ 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);+ if (typeScaleConfig) {+ const generated = generateTypeScaleComponents(typeScaleConfig);components = deepMergeComponents(generated, input.components);}@@ -448,13 +516,29 @@ export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {}}+ // 5. Derive fonts array from typography roles (for runtime loading)+ let fonts: ThemeFontSource[] | undefined;+ if (typo) {+ const seen = new Set<string>();+ const fontList: ThemeFontSource[] = [];+ // Heading inherits from body — collect body first, then heading (may be same), then code+ for (const role of [typo.body, typo.heading, typo.code]) {+ if (role?.family && role.url && !seen.has(role.family)) {+ seen.add(role.family);+ fontList.push({family: role.family, url: role.url});+ }+ }+ // If heading has no family/url but body does, body is already in the list+ if (fontList.length > 0) fonts = fontList;+ }+return {name: input.name,tokens,components,icons: input.icons,variants: variantNames,- fonts: input.fonts,+ fonts,};}diff --git a/packages/core/src/theme/generateThemeRules.test.ts b/packages/core/src/theme/generateThemeRules.test.tsindex 3d94a75a49..aa3b3bf871 100644--- a/packages/core/src/theme/generateThemeRules.test.ts+++ b/packages/core/src/theme/generateThemeRules.test.ts@@ -9,7 +9,7 @@ import {defineTheme, generateThemeCSS, generateThemeRules} from './index';const defaultInput = {name: 'default',- typeScale: {base: 14, ratio: 1.2} as const,+ typography: {scale: {base: 14, ratio: 1.2}},tokens: {},components: {button: {@@ -175,12 +175,9 @@ describe('generateThemeRules', () => {describe('generateThemeRules with weight overrides', () => {const theme = defineTheme({name: 'custom-weights',- typeScale: {- base: 14,- ratio: 1.2,- weights: {- heading: {3: 'var(--font-weight-bold)'},- },+ typography: {+ scale: {base: 14, ratio: 1.2},+ heading: {weights: {3: 'bold'}},},tokens: {},components: {},diff --git a/packages/core/src/theme/index.ts b/packages/core/src/theme/index.tsindex 1817b26f59..7706b45a72 100644--- a/packages/core/src/theme/index.ts+++ b/packages/core/src/theme/index.ts@@ -103,4 +103,7 @@ export type {XDSTextWeight,XDSTextColor,ThemeFontSource,+ TypographyConfig,+ TypographyRole,+ FontWeight,} from './types';diff --git a/packages/core/src/theme/tokens.stylex.ts b/packages/core/src/theme/tokens.stylex.tsindex d29e539734..9dd81cf26b 100644--- a/packages/core/src/theme/tokens.stylex.ts+++ b/packages/core/src/theme/tokens.stylex.ts@@ -235,7 +235,7 @@ export const shadowVars = stylex.defineVars(shadowDefaults);// =============================================================================// Duration primitives: pick a duration that matches the visual weight.// min/max variants derive from base × ratio (default ratio ≈ 0.75).-// See motionScale in defineTheme for computed generation.+// See motion in defineTheme for computed generation.export const durationDefaults = {'--duration-fast-min': '130ms',@@ -374,7 +374,7 @@ export type FontWeightVarName = keyof typeof fontWeightDefaults;// =============================================================================// These tokens are the source of truth for heading and text sizing.// Components reference these tokens so that themes-// can override them via typeScale in defineTheme.+// can override them via typography.scale in defineTheme.//// Default scale: base=14px, ratio=1.2, h4 anchored to base.// Suggested starting points:@@ -385,7 +385,7 @@ export type FontWeightVarName = keyof typeof fontWeightDefaults;export const typeScaleDefaults = {// 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+ // When typography.scale 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=+3diff --git a/packages/core/src/theme/types.ts b/packages/core/src/theme/types.tsindex 120c044519..c2940e1b22 100644--- a/packages/core/src/theme/types.ts+++ b/packages/core/src/theme/types.ts@@ -23,6 +23,78 @@ export interface ThemeFontSource {url: string;}+// =============================================================================+// Typography config types+// =============================================================================++/**+ * Named font weight — maps to var(--font-weight-*) at the token layer.+ * Raw CSS values (e.g. '800') are accepted as an escape hatch.+ */+export type FontWeight =+ | 'normal'+ | 'medium'+ | 'semibold'+ | 'bold'+ | (string & {});++/**+ * A typography role declaration (body, heading, or code).+ *+ * @example+ * ```+ * body: {+ * family: 'Geist',+ * fallbacks: '"Geist Fallback", -apple-system, sans-serif',+ * url: 'https://cdn.jsdelivr.net/npm/geist@1/dist/fonts/geist-sans/style.css',+ * weight: 'normal',+ * }+ * ```+ */+export interface TypographyRole {+ /** Primary font name — used for font loading detection via document.fonts.check() */+ family?: string;+ /** CSS fallback font stack (appended after family in the computed --font-* token) */+ fallbacks?: string;+ /** Stylesheet URL for runtime font loading. Omit for system fonts. */+ url?: string;+ /** Default font weight for this role */+ weight?: FontWeight;+ /** Per-level weight overrides (heading only: keys are heading levels 1–6) */+ weights?: Partial<Record<1 | 2 | 3 | 4 | 5 | 6, FontWeight>>;+}++/**+ * Unified typography configuration.+ *+ * Replaces the separate `typeScale`, `fonts`, and font token overrides+ * with a single config object.+ *+ * - `scale` controls the geometric type scale (base size + ratio)+ * - `body`, `heading`, `code` declare fonts, fallbacks, weights per role+ * - `heading` inherits family/fallbacks/url from `body` if not specified+ *+ * @example+ * ```+ * typography: {+ * scale: { base: 14, ratio: 1.2 },+ * body: { family: 'Geist', fallbacks: '-apple-system, sans-serif', url: '...' },+ * heading: { weight: 'semibold', weights: { 3: 'bold', 4: 'bold' } },+ * code: { family: 'Geist Mono', fallbacks: '"SF Mono", monospace', url: '...' },+ * }+ * ```+ */+export interface TypographyConfig {+ /** Type scale: generates text size tokens from base + ratio */+ scale?: {base: number; ratio: number};+ /** Body text font configuration */+ body?: TypographyRole;+ /** Heading font configuration. Inherits family/fallbacks/url from body if omitted. */+ heading?: TypographyRole;+ /** Code/monospace font configuration */+ code?: TypographyRole;+}+// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport type StyleXStyles = any;diff --git a/packages/themes/brutalist/src/index.ts b/packages/themes/brutalist/src/index.tsindex 97bdc58fb1..aea6732212 100644--- a/packages/themes/brutalist/src/index.ts+++ b/packages/themes/brutalist/src/index.ts@@ -1,8 +1,8 @@/*** Brutalist theme for XDS*- * Zero radius, monospace headings, hot pink accent, heavy borders.- * Demonstrates the full power of defineTheme: token overrides,+ * Zero radius, monospace everything, hot pink accent, heavy borders.+ * Demonstrates the full power of defineTheme: typography roles,* component-level style overrides, and variant targeting.*/@@ -11,14 +11,19 @@ import {defineTheme} from '@xds/core/theme';export const brutalistTheme = defineTheme({name: 'brutalist',+ // Monospace everything — body sets Courier, heading inherits+ typography: {+ body: {family: 'Courier New', fallbacks: '"Courier", monospace'},+ },+// Zero radius everywhere — multiplier 0 makes all scalable radii 0px- radiusScale: {base: 4, multiplier: 0},+ radius: {base: 4, multiplier: 0},- // Motion scale: near-instant — brutalism doesn't wait.+ // Motion: near-instant — brutalism doesn't wait.// Produces: fast-min=50ms, fast=65ms, fast-max=85ms,// medium-min=115ms, medium=150ms, medium-max=200ms.// Linear easing — no curves, no polish, just movement.- motionScale: {fast: 65, medium: 150, ratio: 0.75, easing: 'linear'},+ motion: {fast: 65, medium: 150, ratio: 0.75, easing: 'linear'},tokens: {// Colors — high contrast, no subtlety@@ -30,9 +35,6 @@ export const brutalistTheme = defineTheme({// Even pills are sharp in brutalist'--radius-rounded': '0px',-- // Monospace headings- '--font-heading': '"Courier New", "Courier", monospace',},components: {// Cards get heavy borders@@ -78,11 +80,8 @@ export const brutalistTheme = defineTheme({letterSpacing: '0.05em',},},- // Body text is monospace too+ // Code gets a backgroundtext: {- base: {- fontFamily: '"Courier New", "Courier", monospace',- },'type:code': {backgroundColor: 'var(--color-wash)',padding: '2px 4px',diff --git a/packages/themes/default/src/defaultTheme.ts b/packages/themes/default/src/defaultTheme.tsindex 0ebfd9efeb..3855d6bc4e 100644--- a/packages/themes/default/src/defaultTheme.ts+++ b/packages/themes/default/src/defaultTheme.ts@@ -4,7 +4,7 @@* The reference theme — provides the standard XDS visual language.* Uses defineTheme for CSS-based theming (no StyleX build required for consumers).*- * Typography sizing is driven by typeScale, which auto-generates both+ * Typography sizing is driven by typography.scale, 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: ... }).*@@ -17,14 +17,14 @@ import {defaultIconRegistry} from './icons';export const defaultTheme = defineTheme({name: 'default',- // Type scale: base=14px, ratio=1.2, h4 anchored to base.+ // Typography: base=14px, ratio=1.2, h4 anchored to base.// Generates all heading + text tokens AND component overrides automatically.- typeScale: {base: 14, ratio: 1.2},+ typography: {scale: {base: 14, ratio: 1.2}},- // Motion scale: base durations from Ted's proposal (#674), ratio=0.75.+ // Motion: base durations from Ted's proposal (#674), ratio=0.75.// Generates: fast-min=130ms, fast=175ms, fast-max=235ms,// medium-min=310ms, medium=410ms, medium-max=545ms.- motionScale: {fast: 175, medium: 410, ratio: 0.75},+ motion: {fast: 175, medium: 410, ratio: 0.75},// The default theme uses the built-in token defaults from tokens.stylex.ts.// No additional token overrides needed.@@ -41,7 +41,7 @@ export const defaultTheme = defineTheme({},},- // Heading and text component overrides are auto-generated by typeScale.+ // Heading and text component overrides are auto-generated by typography.scale.// No manual heading: { ... } or text: { ... } blocks needed.},diff --git a/packages/themes/neutral/src/neutralTheme.ts b/packages/themes/neutral/src/neutralTheme.tsindex b417303b95..74d7a89d7a 100644--- a/packages/themes/neutral/src/neutralTheme.ts+++ b/packages/themes/neutral/src/neutralTheme.ts@@ -16,23 +16,29 @@ import {neutralIconRegistry} from './icons';export const neutralTheme = defineTheme({name: 'neutral',- // Type scale: same as default (base=14, ratio=1.2).+ // Typography: same scale as default (base=14, ratio=1.2).+ // Geist fonts for body/heading, Geist Mono for code.// 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)',- },+ typography: {+ scale: {base: 14, ratio: 1.2},+ body: {+ family: 'Geist',+ fallbacks:+ '"Geist Fallback", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',+ },+ heading: {+ weights: {3: 'bold', 4: 'bold'},+ },+ code: {+ family: 'Geist Mono',+ fallbacks: '"SF Mono", Monaco, Consolas, monospace',},},- // Motion scale: snappier than default to match shadcn/Tailwind conventions.+ // Motion: snappier than default to match shadcn/Tailwind conventions.// Produces: fast-min=95ms, fast=125ms, fast-max=165ms,// medium-min=225ms, medium=300ms, medium-max=400ms.- motionScale: {fast: 125, medium: 300, ratio: 0.75},+ motion: {fast: 125, medium: 300, ratio: 0.75},tokens: {// =========================================================================@@ -280,15 +286,6 @@ export const neutralTheme = defineTheme({'inset 0px 0px 0px 2px rgba(226, 164, 0, 0.3)','--inset-shadow-border-negative':'inset 0px 0px 0px 2px rgba(227, 25, 59, 0.3)',-- // =========================================================================- // Typography — Geist font family- // =========================================================================- '--font-body':- 'Geist, "Geist Fallback", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',- '--font-code': '"Geist Mono", "SF Mono", Monaco, Consolas, monospace',- '--font-heading':- 'Geist, "Geist Fallback", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',},components: {@@ -330,8 +327,8 @@ export const neutralTheme = defineTheme({},},- // Heading and text component overrides are auto-generated by typeScale.- // h3/h4 bold weights come from typeScale.weights.heading above.+ // Heading and text component overrides are auto-generated by typography.scale.+ // h3/h4 bold weights come from typography.heading.weights above.},icons: neutralIconRegistry,