An open source design system that's fully customizable and agent ready
TypeScript
fix(theme): make `extends` reach the CSS (#5067)
Cindy Zhang356d2f935c32
diff --git a/.changeset/theme-extends-flatten.md b/.changeset/theme-extends-flatten.mdnew file mode 100644index 0000000000..8b77a9bcf5--- /dev/null+++ b/.changeset/theme-extends-flatten.md@@ -0,0 +1,14 @@+---+'@astryxdesign/cli': patch+'@astryxdesign/core': patch+---++[fix] `extends` now reaches the CSS. A theme that extended another built a stylesheet holding only the declarations it stated itself: the base's tokens, component overrides and surface rules were all absent, and because each theme is `@scope`d to its own `data-astryx-theme` value, loading the base's stylesheet alongside could not fill the gap either. Every consumer of an inheritance chain silently got stock geometry, elevation and type with a new palette painted over it (#5067). Nothing warned; the loss only showed up by diffing two generated stylesheets token by token.++The cause was `theme build` shadowing its own inputs. It writes `<name>.js` next to `<name>.ts`, and the loader resolved a plain `./<name>` specifier to that generated artifact before the source — so the second build of a family read the artifact, which carries no `components` and exports `<name>Theme` rather than whatever the source exports. A named import that missed became `extends: undefined`, and `defineTheme` treated an absent base as no base at all. The loader now resolves source extensions first, which is also the resolution the author's TypeScript sees, so the CSS a build emits matches the theme that type-checked.++Three things behind it are fixed too, so the failure cannot come back by another route. `defineTheme` **throws** when `extends` is present but is not a theme, naming the likely cause, instead of inheriting nothing — the one behavior change here, and it turns a silent stylesheet into a build error. A theme's `onDark`/`onLight` surfaces and its `__inputTokens` are now inherited like its tokens and components were, so a child no longer reverts its base's inverted-surface customizations to the defaults or loses its `[light, dark]` tuples. And a built theme module now carries the resolved `components` and surfaces alongside its tokens, so extending one — the `./built` subpath every shipped theme exposes — is no longer lossy. `theme build` also stopped hand-picking fields when it re-resolves a plain object theme file, which dropped `extends`, `color` and `syntax` on the way in.++An extended theme is flat: everything it inherits is resolved into its own output, and its stylesheet stands alone. Measured on a 14-theme family (one base, 13 palettes extending it): each palette went from 25 custom properties and no component rules to the base's full 175 and 70, with its own colours still winning.++@cixzhangdiff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjsindex 4f9cc85da7..b2991d1a77 100644--- a/packages/cli/api/theme/build/build.mjs+++ b/packages/cli/api/theme/build/build.mjs@@ -591,6 +591,30 @@ const themeScopeStart = (/** @type {string} */ name) =>`[data-astryx-theme="${name}"]`;const THEME_SCOPE_TO = `[data-astryx-theme]`;+/**+ * Module extensions the theme loader resolves, source before artifact.+ *+ * `theme build` writes `<name>.js` next to `<name>.ts`, and jiti's default+ * order tries `.js` first — so once a base theme had been built, every sibling+ * theme that `extends` it resolved to that generated artifact instead of the+ * source. The artifact carries no `components` and exports a different name,+ * so the inheritance silently evaporated. Resolving source first is also what+ * the author's TypeScript sees, which is the point: the CSS the build emits+ * matches the theme they type-checked.+ */+const THEME_MODULE_EXTENSIONS = [+ '.ts',+ '.tsx',+ '.mts',+ '.cts',+ '.mtsx',+ '.ctsx',+ '.mjs',+ '.cjs',+ '.js',+ '.json',+];+/*** Import a theme module using jiti and find the defineTheme() result.* Returns the resolved DefinedTheme object.@@ -601,6 +625,7 @@ async function importThemeModule(filePath) {const jiti = createJiti(import.meta.url, {moduleCache: false,jsx: true,+ extensions: THEME_MODULE_EXTENSIONS,});const mod = await jiti.import(filePath, {default: true});@@ -733,6 +758,13 @@ function extractIconInfo(filePath) {* Includes the theme name, marker, and re-exports the icon registry.* All styling is in the CSS file.*+ * The module carries the theme's resolved `components` and on-media surfaces+ * alongside its tokens. They are not needed to apply the theme — the CSS holds+ * all of that — but a built theme is a legitimate base for `extends` (the+ * shipped themes expose one as their `./built` subpath), and a base that+ * carries only tokens makes its children silently lose every component+ * override it had.+ ** The icon registry is imported rather than inlined because it holds React* elements, which cannot be serialized. `extractIconInfo` lifts the specifier* out of the TypeScript source, where an extensionless `./icons` is resolved by@@ -774,6 +806,27 @@ function generateBuiltModule(themeDef, iconInfo, iconsSpecifier) {.map((line, i) => (i === 0 ? line : ' ' + line)).join('\n');+ /**+ * Serialize a resolved theme field as an indented object literal, or '' when+ * there is nothing to emit.+ * @param {string} field+ * @param {unknown} value+ * @returns {string}+ */+ const serializeField = (field, value) => {+ if (!value || Object.keys(value).length === 0) return '';+ const body = JSON.stringify(value, null, 2)+ .split('\n')+ .map((line, i) => (i === 0 ? line : ' ' + line))+ .join('\n');+ return ` ${field}: ${body},\n`;+ };++ const inheritableFields =+ serializeField('components', themeDef.components) ++ serializeField('__onDark', themeDef.__onDark) ++ serializeField('__onLight', themeDef.__onLight);+return `${iconImport}/*** ${themeDef.name} theme — built by \`${getCliInvocation()} theme build\`* Import the CSS file alongside this module:@@ -785,7 +838,7 @@ export const ${toIdentifier(themeDef.name)}Theme = {name: '${themeDef.name}',__built: true,tokens: ${tokensStr},-${iconsField}+${inheritableFields}${iconsField}};${iconReExport}`;}@@ -1099,20 +1152,29 @@ export async function themeBuild(let css;let resolvedTheme;{- // jiti returns an already-resolved theme; legacy eval returns raw input.- const isAlreadyResolved =- !themeDef.typography && !themeDef.motion && !themeDef.radius;- if (isAlreadyResolved) {- resolvedTheme = themeDef;+ // jiti returns an already-resolved theme; a plain object literal (or the+ // legacy eval path) returns raw defineTheme input, which still has to go+ // through the resolver. Detect that by the input-only fields — a resolved+ // theme has none of them — and hand the WHOLE object over: picking fields+ // by name is how `extends` (and `color`, and `syntax`) used to be dropped+ // on the way in.+ const INPUT_ONLY_FIELDS = [+ 'extends',+ 'typography',+ 'motion',+ 'radius',+ 'color',+ 'syntax',+ 'onDark',+ 'onLight',+ ];+ const needsResolution = INPUT_ONLY_FIELDS.some(+ field => themeDef[field] !== undefined,+ );+ if (needsResolution) {+ resolvedTheme = _defineTheme({...themeDef});} else {- resolvedTheme = _defineTheme({- name: themeDef.name,- typography: themeDef.typography,- motion: themeDef.motion,- radius: themeDef.radius,- tokens: themeDef.tokens,- components: themeDef.components,- });+ resolvedTheme = themeDef;}const scopeSelector = themeScopeStart(themeDef.name);const scopeTo = THEME_SCOPE_TO;diff --git a/packages/cli/api/theme/build/build.test.mjs b/packages/cli/api/theme/build/build.test.mjsindex 6018f83443..47b469d20f 100644--- a/packages/cli/api/theme/build/build.test.mjs+++ b/packages/cli/api/theme/build/build.test.mjs@@ -323,6 +323,180 @@ describe('themeBuild() — the shipped theme template', () => {expect(fs.existsSync(path.join(tmpDir, 'my-theme.css'))).toBe(true);// The template teaches custom variants; the augmentation it promises the// reader has to actually be generated.- expect(fs.existsSync(path.join(tmpDir, 'my-theme.variants.d.ts'))).toBe(true);+ expect(fs.existsSync(path.join(tmpDir, 'my-theme.variants.d.ts'))).toBe(+ true,+ );+ });+});++describe('themeBuild() — extends', () => {+ // These fixtures `import {defineTheme} from '@astryxdesign/core/theme'` the+ // way a real theme file does, so they have to sit somewhere that specifier+ // resolves — an OS temp dir has no node_modules above it.+ let extDir;+ beforeEach(() => {+ extDir = fs.mkdtempSync(+ path.join(path.resolve(import.meta.dirname, '../../..'), '.tmp-extends-'),+ );+ });+ afterEach(() => {+ fs.rmSync(extDir, {recursive: true, force: true});+ });++ /**+ * Every `prop: value` a generated stylesheet actually applies. Header+ * comments and scope wrappers are ignored — two themes never share those.+ */+ function declarations(css) {+ return new Set(+ css+ .split('\n')+ .map(l => l.trim())+ .filter(l => /^[-a-z][^{}]*:.+;$/.test(l)),+ );+ }+ /** Every component rule a stylesheet opens, e.g. `.astryx-switch {`. */+ function selectors(css) {+ return new Set(+ css+ .split('\n')+ .map(l => l.trim())+ .filter(l => l.endsWith('{') && l.startsWith('.')),+ );+ }++ /** A base theme with geometry, elevation and a component override. */+ const BASE_SOURCE = `export const brandTheme = {+ name: 'ext-base',+ tokens: {+ '--radius-element': '6px',+ '--shadow-low': '0 1px 3px rgb(0 0 0 / 0.1)',+ '--color-border-emphasized': '#D4D4D4',+ },+ components: {+ switch: {base: {backgroundColor: 'var(--color-border-emphasized)'}},+ },+ };\n`;++ /**+ * The child names its base with a plain relative specifier, exactly as a+ * generated palette does. `theme build` writes `ext-base.js` next to+ * `ext-base.mjs`, so `./ext-base` is ambiguous — and the artifact, which+ * exports `extBaseTheme` rather than `brandTheme`, is the wrong answer.+ */+ const CHILD_SOURCE = `import {defineTheme} from '@astryxdesign/core/theme';+ import {brandTheme} from './ext-base';+ export const paletteTheme = defineTheme({+ name: 'ext-child',+ extends: brandTheme,+ tokens: {'--color-accent': 'hsl(220 88% 72%)'},+ });\n`;++ it('emits every declaration its base emits (the child stylesheet is self-contained)', async () => {+ fs.writeFileSync(path.join(extDir, 'ext-base.mjs'), BASE_SOURCE);+ fs.writeFileSync(path.join(extDir, 'ext-child.mjs'), CHILD_SOURCE);++ // Build the base FIRST, as any real project does — that write is what+ // used to poison the child's build.+ await themeBuild('ext-base.mjs', {}, {cwd: extDir});+ await themeBuild('ext-child.mjs', {}, {cwd: extDir});++ const baseCss = fs.readFileSync(path.join(extDir, 'ext-base.css'), 'utf8');+ const childCss = fs.readFileSync(+ path.join(extDir, 'ext-child.css'),+ 'utf8',+ );++ const childDecls = declarations(childCss);+ expect([...declarations(baseCss)].filter(d => !childDecls.has(d))).toEqual(+ [],+ );++ const childSelectors = selectors(childCss);+ expect([...selectors(baseCss)].filter(s => !childSelectors.has(s))).toEqual(+ [],+ );++ // …and the child's own override still wins.+ expect(childCss).toContain('--color-accent: hsl(220 88% 72%);');+ });++ it('resolves the base from its source, not from the generated sibling artifact', async () => {+ fs.writeFileSync(path.join(extDir, 'ext-base.mjs'), BASE_SOURCE);+ fs.writeFileSync(path.join(extDir, 'ext-child.mjs'), CHILD_SOURCE);++ await themeBuild('ext-base.mjs', {}, {cwd: extDir});+ const result = await themeBuild('ext-child.mjs', {}, {cwd: extDir});++ expect(result?.data.componentCount).toBe(1);+ expect(result?.data.tokenCount).toBe(4);+ });++ it('inherits component overrides when the base IS a built theme module', async () => {+ fs.writeFileSync(path.join(extDir, 'ext-base.mjs'), BASE_SOURCE);+ await themeBuild('ext-base.mjs', {}, {cwd: extDir});++ // Extending a package's pre-built theme module (e.g. the `./built`+ // subpath the shipped themes expose) must not silently drop its+ // component overrides.+ fs.writeFileSync(+ path.join(extDir, 'ext-built-child.mjs'),+ `import {defineTheme} from '@astryxdesign/core/theme';+ import {extBaseTheme} from './ext-base.js';+ export const builtChildTheme = defineTheme({+ name: 'ext-built-child',+ extends: extBaseTheme,+ });\n`,+ );++ await themeBuild('ext-built-child.mjs', {}, {cwd: extDir});+ const css = fs.readFileSync(+ path.join(extDir, 'ext-built-child.css'),+ 'utf8',+ );++ expect(css).toContain('.astryx-switch {');+ expect(css).toContain('--radius-element: 6px;');+ });++ it('resolves extends on a plain object theme file (no defineTheme call)', async () => {+ fs.writeFileSync(path.join(extDir, 'ext-base.mjs'), BASE_SOURCE);+ fs.writeFileSync(+ path.join(extDir, 'ext-plain.mjs'),+ `import {brandTheme} from './ext-base.mjs';+ export default {+ name: 'ext-plain',+ extends: brandTheme,+ tokens: {'--color-accent': '#ff0000'},+ };\n`,+ );++ await themeBuild('ext-base.mjs', {}, {cwd: extDir});+ await themeBuild('ext-plain.mjs', {}, {cwd: extDir});++ const css = fs.readFileSync(path.join(extDir, 'ext-plain.css'), 'utf8');+ expect(css).toContain('--radius-element: 6px;');+ expect(css).toContain('.astryx-switch {');+ });++ it('fails loudly when the base import resolved to nothing', async () => {+ fs.writeFileSync(+ path.join(extDir, 'ext-broken.mjs'),+ `import {defineTheme} from '@astryxdesign/core/theme';+ import {notAThing} from './ext-missing.mjs';+ export const brokenTheme = defineTheme({+ name: 'ext-broken',+ extends: notAThing,+ tokens: {'--color-accent': '#ff0000'},+ });\n`,+ );+ fs.writeFileSync(+ path.join(extDir, 'ext-missing.mjs'),+ `export const somethingElse = 1;\n`,+ );++ await expect(+ themeBuild('ext-broken.mjs', {}, {cwd: extDir}),+ ).rejects.toThrow(/extends/);});});diff --git a/packages/cli/assets/docs/theme.doc.mjs b/packages/cli/assets/docs/theme.doc.mjsindex 7a11c647d2..db5ed1e3f5 100644--- a/packages/cli/assets/docs/theme.doc.mjs+++ b/packages/cli/assets/docs/theme.doc.mjs@@ -253,10 +253,15 @@ const brandTheme = defineTheme({['tokens', 'Base tokens are copied first, then child tokens override on top.'],['components', 'Deep-merged: child component rules override matching keys from the base.'],['icons', 'Shallow-merged: child icons override matching names from the base.'],- ['fonts', 'Base fonts included first, then child fonts appended.'],+ ['indicators', 'Shallow-merged: child indicators override matching names from the base.'],+ ['onDark, onLight', "Deep-merged per surface: the base's resolved surface first, then the child's overrides."],['typography, motion, radius, color', 'Child config replaces base entirely (these are scale inputs, not additive).'],],},+ {+ type: 'prose',+ text: 'Inheritance is resolved when the theme is defined, so an extended theme is flat: `astryx theme build` emits one self-contained stylesheet holding everything the child inherited, and the base theme\'s CSS does not need to be loaded next to it. A base that is not a theme — most often an import that missed — is a build error rather than a theme that silently inherits nothing.',+ },],},{diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.tsindex 75540401ea..dbf0c1c7e8 100644--- a/packages/core/src/theme/defineTheme.test.ts+++ b/packages/core/src/theme/defineTheme.test.ts@@ -2,6 +2,7 @@import {describe, it, expect, vi} from 'vitest';import type {IconRegistry} from '../Icon/globalIconRegistry';+import type {DefinedTheme} from './defineTheme';import {defineTheme, generateThemeCSS, isDefinedTheme} from './defineTheme';function generateThemeTestCSS(theme: Parameters<typeof generateThemeCSS>[0]) {@@ -1126,4 +1127,130 @@ describe('defineTheme extends', () => {base.tokens['--font-size-base'],);});++ it('inherits indicators when the child has none', () => {+ const indicator = (() => null) as unknown as NonNullable<+ DefinedTheme['indicators']+ >['check'];+ const base = defineTheme({name: 'base', indicators: {check: indicator}});+ const child = defineTheme({name: 'child', extends: base});+ expect(child.indicators?.check).toBe(indicator);+ });++ it('inherits onDark token overrides from base theme', () => {+ const base = defineTheme({+ name: 'base',+ onDark: {tokens: {'--color-border': '#ffffff'}},+ });+ const child = defineTheme({name: 'child', extends: base});+ expect(child.__onDark?.tokens['--color-border']).toBe('#ffffff');+ });++ it('inherits onLight token overrides from base theme', () => {+ const base = defineTheme({+ name: 'base',+ onLight: {tokens: {'--color-border': '#000000'}},+ });+ const child = defineTheme({name: 'child', extends: base});+ expect(child.__onLight?.tokens['--color-border']).toBe('#000000');+ });++ it('lets the child override an inherited onDark token', () => {+ const base = defineTheme({+ name: 'base',+ onDark: {tokens: {'--color-border': '#ffffff', '--color-track': '#eee'}},+ });+ const child = defineTheme({+ name: 'child',+ extends: base,+ onDark: {tokens: {'--color-border': '#cccccc'}},+ });+ expect(child.__onDark?.tokens['--color-border']).toBe('#cccccc');+ expect(child.__onDark?.tokens['--color-track']).toBe('#eee');+ });++ it('inherits and deep-merges onDark component overrides', () => {+ const base = defineTheme({+ name: 'base',+ onDark: {+ components: {+ card: {base: {borderColor: '#fff', backgroundColor: '#111'}},+ badge: {base: {color: '#fff'}},+ },+ },+ });+ const child = defineTheme({+ name: 'child',+ extends: base,+ onDark: {components: {card: {base: {borderColor: '#ccc'}}}},+ });+ expect(child.__onDark?.components?.card?.base).toEqual({+ borderColor: '#ccc',+ backgroundColor: '#111',+ });+ expect(child.__onDark?.components?.badge?.base).toEqual({color: '#fff'});+ });++ it('inherits __inputTokens so inherited [light, dark] tuples survive', () => {+ const base = defineTheme({+ name: 'base',+ tokens: {'--color-accent': ['#111111', '#eeeeee']},+ });+ const child = defineTheme({+ name: 'child',+ extends: base,+ tokens: {'--color-border': '#cccccc'},+ });+ expect(child.__inputTokens?.['--color-accent']).toEqual([+ '#111111',+ '#eeeeee',+ ]);+ expect(child.__inputTokens?.['--color-border']).toBe('#cccccc');+ });++ it('__inputTokens from the child win over the base', () => {+ const base = defineTheme({+ name: 'base',+ tokens: {'--color-accent': ['#111111', '#eeeeee']},+ });+ const child = defineTheme({+ name: 'child',+ extends: base,+ tokens: {'--color-accent': '#ff0000'},+ });+ expect(child.__inputTokens?.['--color-accent']).toBe('#ff0000');+ });++ // The failure that motivated these: `extends` resolving to `undefined` (a+ // named import that silently missed — see the theme-build resolution tests)+ // used to inherit nothing and build a stylesheet that looked fine.+ it('throws when extends is present but undefined', () => {+ expect(() =>+ defineTheme({+ name: 'child',+ extends: undefined,+ tokens: {'--color-accent': '#ff0000'},+ }),+ ).toThrow(/extends/);+ });++ it('throws when extends is not a theme', () => {+ expect(() =>+ defineTheme({+ name: 'child',+ // A module namespace object is the shape a bad import hands over.+ extends: {foo: 'bar'} as unknown as DefinedTheme,+ }),+ ).toThrow(/extends/);+ });++ it('accepts a pre-built theme module as a base', () => {+ const built = {+ name: 'built-base',+ __built: true,+ tokens: {'--color-accent': '#111111'},+ } as DefinedTheme;+ const child = defineTheme({name: 'child', extends: built});+ expect(child.tokens['--color-accent']).toBe('#111111');+ });});diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.tsindex dcdd91ca56..6fe7c7aea7 100644--- a/packages/core/src/theme/defineTheme.ts+++ b/packages/core/src/theme/defineTheme.ts@@ -72,6 +72,7 @@ import type {DomainTokenName} from './domainTokens';import {domainTokenDefaults} from './domainTokens';import type {SyntaxThemeDefinition} from './syntax';import {registerTheme} from './themeRegistry';+import {deepMergeComponents} from './mergeComponents';// =============================================================================// Types@@ -165,9 +166,14 @@ export interface DefineThemeInput {name: string;/**- * Base theme to extend. When provided, the new theme starts with the- * base theme's tokens, components, and fonts, then applies overrides- * from this input on top. The base theme's values have lowest precedence.+ * Base theme to extend. When provided, the new theme starts with everything+ * the base resolved to — tokens, component overrides, icons, indicators, and+ * its `onDark`/`onLight` surfaces — then applies this input on top. The base+ * theme's values have lowest precedence.+ *+ * The result is flat: an extended theme carries its inheritance in its own+ * resolved output, so `astryx theme build` emits one self-contained+ * stylesheet and the base's CSS does not need to be loaded alongside it.** Use this to create variant themes that customize only a few aspects* (e.g. icons, accent color) without re-specifying the full theme.@@ -416,49 +422,6 @@ function resolveTokenValue(value: TokenValue): string {return value;}-/**- * Deep-merge two component style maps.- * Properties in `overrides` take precedence over `base`.- * This allows typeScale-generated rules to be overridden by explicit components.- */-function deepMergeComponents(- base?: ComponentStyleMap,- overrides?: ComponentStyleMap,-): ComponentStyleMap | undefined {- if (!base && !overrides) {- return undefined;- }- if (!base) {- return overrides;- }- if (!overrides) {- return base;- }-- const result: ComponentStyleMap = {};-- // Start with all base entries- for (const [component, rules] of Object.entries(base)) {- result[component] = {...rules};- }-- // Merge overrides on top- for (const [component, rules] of Object.entries(overrides)) {- if (!result[component]) {- result[component] = {...rules};- } else {- for (const [key, styles] of Object.entries(rules)) {- result[component][key] = {- ...result[component][key],- ...styles,- };- }- }- }-- return result;-}-/*** Resolve a FontWeight name to a var() reference.* Named weights map to var(--font-weight-*); raw values pass through.@@ -491,6 +454,24 @@ function buildFontFamily(return quoted;}+/**+ * Describe a rejected `extends` value for the error message — enough to tell a+ * missed import (`undefined`) from a module namespace or a plain object.+ */+function describeBadBase(value: unknown): string {+ if (value === undefined) {+ return 'undefined';+ }+ if (value === null) {+ return 'null';+ }+ if (typeof value !== 'object') {+ return typeof value;+ }+ const keys = Object.keys(value);+ return `an object with keys [${keys.slice(0, 4).join(', ')}${keys.length > 4 ? ', …' : ''}]`;+}+/*** Create an Astryx theme.*@@ -504,7 +485,19 @@ function buildFontFamily(export function defineTheme(input: DefineThemeInput): DefinedTheme {const tokens: Record<string, string> = {};- // 0. Pre-seed from base theme when `extends` is provided (lowest precedence)+ // 0. Pre-seed from base theme when `extends` is provided (lowest precedence).+ // A base that is not a theme is refused rather than ignored: `extends` used+ // to inherit nothing when its value was undefined, which is what a named+ // import silently resolving to the wrong module hands over, and the theme+ // then built into a plausible-looking stylesheet missing everything it was+ // supposed to inherit.+ if ('extends' in input && !isDefinedTheme(input.extends)) {+ throw new Error(+ `defineTheme("${input.name}"): \`extends\` must be a theme from defineTheme(), got ${describeBadBase(input.extends)}. ` ++ `Check that the import naming your base theme resolves to its source and exports that name — ` ++ `a generated \`<theme>.js\` artifact sitting next to the source exports \`<name>Theme\`, not the source's own export.`,+ );+ }const base = input.extends;if (base) {for (const [key, value] of Object.entries(base.tokens)) {@@ -640,9 +633,10 @@ export function defineTheme(input: DefineThemeInput): DefinedTheme {components = deepMergeComponents(base.components, components);}- // 4. Resolve on-media token overrides (defaults + user overrides)- const __onDark = resolveOnMedia('dark', input.onDark);- const __onLight = resolveOnMedia('light', input.onLight);+ // 4. Resolve on-media token overrides (base's resolved surface, then+ // defaults, then this theme's own overrides)+ const __onDark = resolveOnMedia('dark', input.onDark, base?.__onDark);+ const __onLight = resolveOnMedia('light', input.onLight, base?.__onLight);// 5. Merge icons — input icons override base iconsconst icons =@@ -663,7 +657,10 @@ export function defineTheme(input: DefineThemeInput): DefinedTheme {components,icons,indicators,- __inputTokens: input.tokens,+ __inputTokens:+ base?.__inputTokens || input.tokens+ ? {...base?.__inputTokens, ...input.tokens}+ : undefined,__onDark,__onLight,};diff --git a/packages/core/src/theme/mergeComponents.ts b/packages/core/src/theme/mergeComponents.tsnew file mode 100644index 0000000000..cf52d56530--- /dev/null+++ b/packages/core/src/theme/mergeComponents.ts@@ -0,0 +1,59 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Component style-map merging+ *+ * One merge rule for component overrides, shared by every layer that composes+ * them: `extends` inheritance, generated type-scale rules, and the on-media+ * (`onDark`/`onLight`) surfaces. Merging is per style key, so a child that+ * restates one property of `button.base` keeps the rest of the base's.+ *+ * @input two ComponentStyleMaps — the base and the overrides that win+ * @output a merged ComponentStyleMap+ * @position packages/core/src/theme/mergeComponents.ts+ */++import type {ComponentStyleMap} from './defineTheme';++/**+ * Deep-merge component style maps: `overrides` wins per style key, and every+ * component and key the base declared that the overrides do not mention is+ * carried through untouched.+ */+export function deepMergeComponents(+ base?: ComponentStyleMap,+ overrides?: ComponentStyleMap,+): ComponentStyleMap | undefined {+ if (!base && !overrides) {+ return undefined;+ }+ if (!base) {+ return overrides;+ }+ if (!overrides) {+ return base;+ }++ const result: ComponentStyleMap = {};++ // Start with all base entries+ for (const [component, rules] of Object.entries(base)) {+ result[component] = {...rules};+ }++ // Merge overrides on top+ for (const [component, rules] of Object.entries(overrides)) {+ if (!result[component]) {+ result[component] = {...rules};+ } else {+ for (const [key, styles] of Object.entries(rules)) {+ result[component][key] = {+ ...result[component][key],+ ...styles,+ };+ }+ }+ }++ return result;+}diff --git a/packages/core/src/theme/onMediaTokens.ts b/packages/core/src/theme/onMediaTokens.tsindex 4496e14e06..12010e9b48 100644--- a/packages/core/src/theme/onMediaTokens.ts+++ b/packages/core/src/theme/onMediaTokens.ts@@ -21,6 +21,7 @@*/import type {TokenValue, ComponentStyleMap} from './defineTheme';+import {deepMergeComponents} from './mergeComponents';/*** On-media theme overrides — same shape as the main theme but scoped@@ -89,15 +90,21 @@ function resolveValue(value: TokenValue): string {/*** Resolve on-media overrides: merge user tokens with defaults,* pass through component overrides.+ *+ * `base` is the already-resolved surface of a theme being extended. It sits+ * between the defaults and this theme's own input, so a child theme inherits+ * the surface customizations of the theme it extends instead of silently+ * reverting them to the defaults.*/export function resolveOnMedia(surface: 'dark' | 'light',input?: OnMediaOverrides,+ base?: ResolvedOnMedia,): ResolvedOnMedia {const defaults =surface === 'dark' ? defaultOnDarkTokens : defaultOnLightTokens;- const tokens = {...defaults};+ const tokens = {...defaults, ...base?.tokens};if (input?.tokens) {for (const [key, value] of Object.entries(input.tokens)) {@@ -109,6 +116,6 @@ export function resolveOnMedia(return {tokens,- components: input?.components,+ components: deepMergeComponents(base?.components, input?.components),};}