An open source design system that's fully customizable and agent ready
TypeScript
fix(theme): preserve component overrides in type-scale adaptations (#6710)
Xinzi Zhou039a67ea5391
diff --git a/.changeset/adaptation-component-defaults.md b/.changeset/adaptation-component-defaults.mdnew file mode 100644index 0000000000..15137d835f--- /dev/null+++ b/.changeset/adaptation-component-defaults.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Preserve authored heading and text component styles when theme adaptations change the type scale (#6710)+@imdreamrunnerdiff --git a/docs/specs/AST-012/spec.md b/docs/specs/AST-012/spec.mdindex cc913d1cdd..f527988f07 100644--- a/docs/specs/AST-012/spec.md+++ b/docs/specs/AST-012/spec.md@@ -119,7 +119,10 @@ A breakpoint map alone emits no CSS. Only rules with adaptation values do.indicators, media-surface fields, and adaptations remain root-owned. Within onerule, values use the root expansion, deep-merge, and kind precedence. Agenerative axis expands against the root axis metadata, and every produced leaf- counts as a write by that rule. Missing required scale fields MUST be supplied+ counts as a write by that rule except invariant type-scale component defaults+ at exact leaf paths already declared on the effective root `components`.+ Generated tokens and rule-authored component leaves remain writes.+ Missing required scale fields MUST be suppliedrather than synthesized from approximate built-in defaults. Component writes inrules MUST use the same target, axis, value-domain, and extension validation asroot `components`; adaptations define no separate component-value validation@@ -140,7 +143,9 @@ A breakpoint map alone emits no CSS. Only rules with adaptation values do.cascade in declaration order and the last matching write to each resolved tokenor component leaf wins. Condition shape creates no independent specificityscore. Duplicate `when` objects are valid. Reordering overlapping rules is an- intentional behavior change.+ intentional behavior change. A later scale-only rule preserves an earlier+ authored component leaf when its exact path exists at root; when absent at+ root, the generated component leaf remains a write and wins if both rules match.- **FR7 — Theme extension preserves cascade order.** A child inherits the basewidth-breakpoint overrides and ordered rules. Breakpoints merge by name.Inherited rules keep their relative order and resolve against the child'sdiff --git a/packages/cli/clients/cli/commands/build-theme.adaptations.test.mjs b/packages/cli/clients/cli/commands/build-theme.adaptations.test.mjsindex 5f16d5f21b..e30e24927c 100644--- a/packages/cli/clients/cli/commands/build-theme.adaptations.test.mjs+++ b/packages/cli/clients/cli/commands/build-theme.adaptations.test.mjs@@ -3,7 +3,8 @@/*** @file Ensures `astryx theme build` preserves AST-012 adaptation semantics.* Runtime and static output share core's compiler; this suite guards the CLI- * loading, diagnostics, serialization, and extension boundaries around it.+ * loading, diagnostics, serialization, and extension boundaries around it,+ * including root component overrides underneath adapted typography scales.*/import {afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';@@ -94,6 +95,104 @@ describe('theme build adaptations', () => {);});+ it.each([+ ['defined', writeTheme],+ ['plain', writePlainTheme],+ ])(+ 'preserves component pins in %s themes and built extensions',+ async (_kind, write) => {+ const {defineTheme, generateAdaptationCSS, generateThemeCSS} =+ await import('@astryxdesign/core/theme');+ const project = path.join(tmpDir, 'project');+ const themesDir = path.join(project, 'themes');+ const displayFamily =+ 'Sarina, "Brush Script MT", "Snell Roundhand", cursive';+ const input = {+ name: 'adaptive-display',+ typography: {+ scale: {base: 16, ratio: 1.25},+ body: {family: 'Outfit', fallbacks: 'sans-serif'},+ },+ components: {+ text: Object.fromEntries(+ ['display-1', 'display-2', 'display-3'].map(type => [+ `type:${type}`,+ {fontFamily: displayFamily},+ ]),+ ),+ button: {base: {borderRadius: '12px'}},+ },+ adaptations: {+ rules: [+ {+ when: {width: {below: 'md'}, pointer: 'coarse'},+ value: {typography: {scale: {base: 14, ratio: 1.2}}},+ },+ {+ when: {contrast: 'more'},+ value: {+ typography: {scale: {base: 15}},+ components: {+ text: {'type:display-1': {fontFamily: 'monospace'}},+ },+ },+ },+ ],+ },+ };+ const themeFile = write(themesDir, input.name, JSON.stringify(input));+ const result = await build(project, themeFile);+ expect(result.code, result.stderr).toBe(0);+ const css = fs.readFileSync(+ path.join(themesDir, 'adaptive-display.css'),+ 'utf8',+ );+ const compact = value => value.replace(/\s+/g, ' ').trim();+ const source = defineTheme(input);+ const runtime = generateThemeCSS(source);+ // The CLI wraps root, adaptation, and surface CSS in separate @layer+ // blocks; their contents and order must still match runtime output.+ const adaptationCSS = generateAdaptationCSS(source).component;+ const [rootCSS, surfaceCSS] = runtime.component.split(adaptationCSS);+ const blocks = [rootCSS, adaptationCSS, surfaceCSS].map(compact);+ let previousIndex = -1;+ for (const block of blocks) {+ expect(compact(css)).toContain(block);+ const index = compact(css).indexOf(block);+ expect(index).toBeGreaterThan(previousIndex);+ previousIndex = index;+ }+ expect(compact(css)).toContain(compact(runtime.prose));+ const scaleBlock = css.slice(+ css.indexOf('@media (width < 768px) and (pointer: coarse)'),+ css.indexOf('@media (prefers-contrast: more)'),+ );+ expect(scaleBlock).toContain('--font-size-base: 0.875rem');+ expect(scaleBlock).not.toContain('.astryx-text');+ expect(scaleBlock).not.toContain('.astryx-heading');+ expect(scaleBlock).not.toContain('.astryx-button');+ expect(css).toContain(`font-family: ${displayFamily};`);+ expect(css).toContain('font-family: monospace;');++ const {adaptiveDisplayTheme: builtTheme} = await import(+ pathToFileURL(path.join(themesDir, 'adaptive-display.js')).href+ );+ expect(builtTheme.__adaptationRules).toBeUndefined();+ expect(generateThemeCSS(builtTheme)).toEqual(runtime);+ const childInput = {+ name: 'display-child',+ components: {text: {'type:display-2': {fontFamily: 'serif'}}},+ };+ const fromSource = defineTheme({...childInput, extends: source});+ const fromBuilt = defineTheme({...childInput, extends: builtTheme});+ expect(generateThemeCSS(fromBuilt)).toEqual(generateThemeCSS(fromSource));+ expect(fromBuilt.__adaptationRules[0].components).toBeUndefined();+ expect(fromBuilt.components.text['type:display-2'].fontFamily).toBe(+ 'serif',+ );+ },+ );+it('resolves a plain object whose only input-only field is adaptations', async () => {const project = path.join(tmpDir, 'project');const themesDir = path.join(project, 'themes');diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.tsindex 91933917ae..72423a3338 100644--- a/packages/core/src/theme/defineTheme.ts+++ b/packages/core/src/theme/defineTheme.ts@@ -3,6 +3,9 @@/*** defineTheme — Create an Astryx theme from a flat token map.*+ * Adaptations resolve against the effective root axes and components, retaining+ * authored component pins without repeating root typography defaults.+ ** Two distribution modes:* - Unbuilt: Theme generates CSS and injects a <style> tag at runtime* - Built: `astryx theme build` pre-compiles to a CSS file; Theme just@@ -595,6 +598,7 @@ export function defineTheme(input: DefineThemeInput): ResolvedDefinedTheme {__axes,tokens,localTokenContract?.localTokens,+ components,);// Icons — input icons override base iconsdiff --git a/packages/core/src/theme/generateThemeRules.ts b/packages/core/src/theme/generateThemeRules.tsindex 7d35640be4..8eef9c1b8d 100644--- a/packages/core/src/theme/generateThemeRules.ts+++ b/packages/core/src/theme/generateThemeRules.ts@@ -6,6 +6,8 @@* Shared logic for generating CSS rules from a resolved theme definition,* including one component-leaf lowering path for root, adaptation, and* media-surface values plus condition-correct Heading weight precedence guards.+ * Built adaptation metadata resolves against the same root component defaults+ * as defineTheme, so scale-only rules do not reset authored component styles.* Used by both the runtime path (Theme injects <style>) and the build* path (`astryx theme build` pre-compiles to CSS files).*@@ -1139,6 +1141,7 @@ export function generateAdaptationCSS(theme.__axes ?? {},theme.tokens,theme.localTokens,+ theme.components,): undefined);if (!rules || rules.length === 0) {diff --git a/packages/core/src/theme/themeAdaptations.test.ts b/packages/core/src/theme/themeAdaptations.test.tsindex 6de8e42575..c1e671c30b 100644--- a/packages/core/src/theme/themeAdaptations.test.ts+++ b/packages/core/src/theme/themeAdaptations.test.ts@@ -3,7 +3,8 @@/*** @file themeAdaptations.test.ts* Tests AST-012's ordered, closed, CSS-first theme adaptation contract,- * including normalization and final reachable-cascade validation.+ * including normalization, root-dependent type-scale component writes, and final+ * reachable-cascade validation.*/import {describe, expect, it} from 'vitest';@@ -378,6 +379,215 @@ describe('rule order and writes', () => {});});+describe('adapted type-scale component defaults', () => {+ const displayFamily = 'Sarina, "Brush Script MT", "Snell Roundhand", cursive';+ const butterShapedInput: DefineThemeInput = {+ name: 'butter-shaped',+ typography: {+ scale: {base: 16, ratio: 1.25},+ body: {family: 'Outfit', fallbacks: 'sans-serif'},+ },+ components: {+ text: Object.fromEntries(+ ['display-1', 'display-2', 'display-3'].map(type => [+ `type:${type}`,+ {fontFamily: displayFamily},+ ]),+ ),+ button: {base: {borderRadius: '12px'}},+ },+ adaptations: {+ rules: [+ {+ when: {width: {below: 'md'}, pointer: 'coarse'},+ value: {typography: {scale: {base: 14, ratio: 1.2}}},+ },+ ],+ },+ };++ it('keeps butter-shaped display families while adapting scale tokens only', () => {+ const theme = defineTheme(butterShapedInput);+ const rule = theme.__adaptationRules![0];+ const css = generateThemeCSS(theme).component;+ const adaptiveCSS = generateAdaptationCSS(theme).component;++ expect(rule.query).toBe('(width < 768px) and (pointer: coarse)');+ expect(theme.tokens['--font-size-base']).toBe('1rem');+ expect(rule.tokens['--font-size-base']).toBe('0.875rem');+ expect(rule.tokens['--font-size-5xl']).not.toBe(+ theme.tokens['--font-size-5xl'],+ );+ expect(adaptiveCSS).toContain('--font-size-base: 0.875rem');+ // The root owns the var() wiring and its authored overrides. Re-emitting+ // either would turn an unrelated scale change into a component write.+ expect(rule.components).toBeUndefined();+ expect(adaptiveCSS).not.toContain('.astryx-text');+ expect(adaptiveCSS).not.toContain('.astryx-heading');+ expect(adaptiveCSS).not.toContain('.astryx-button');+ for (const type of ['display-1', 'display-2', 'display-3']) {+ expect(theme.components?.text[`type:${type}`].fontFamily).toBe(+ displayFamily,+ );+ expect(count(css, `.astryx-text[data-type="${type}"] {`)).toBe(1);+ }+ expect(count(css, `font-family: ${displayFamily};`)).toBe(3);+ // Built modules retain root components + intent, not resolved rule layers.+ expect(generateThemeCSS({...theme, __adaptationRules: undefined})).toEqual(+ generateThemeCSS(theme),+ );+ });++ it('fills only missing generated leaves when the root has no scale', () => {+ const components = {+ heading: {+ 'level:1': {fontFamily: 'serif', fontWeight: '900'},+ 'type:display-1': {fontSize: '5rem'},+ },+ text: {+ 'type:display-1': {fontFamily: displayFamily, lineHeight: '1.1'},+ 'type:body': {fontSize: '18px'},+ 'type:custom': {fontFamily: 'monospace'},+ },+ button: {base: {borderRadius: '12px'}},+ };+ const before = structuredClone(components);+ const theme = defineTheme({+ ...butterShapedInput,+ typography: undefined,+ components,+ });+ const generated = theme.__adaptationRules![0].components!;++ expect(generated.heading['level:1']).toEqual({+ fontSize: 'var(--text-heading-1-size)',+ lineHeight: 'var(--text-heading-1-leading)',+ });+ expect(generated.heading['type:display-1']).toEqual({+ fontFamily: 'var(--font-family-heading)',+ lineHeight: 'var(--text-display-1-leading)',+ });+ expect(generated.text['type:display-1']).toEqual({+ fontSize: 'var(--text-display-1-size)',+ });+ expect(generated.text['type:body']).toEqual({+ fontFamily: 'var(--font-family-body)',+ lineHeight: 'var(--text-body-leading)',+ });+ expect(generated.text['type:custom']).toBeUndefined();+ expect(generated.button).toBeUndefined();+ expect(components).toEqual(before);+ expect(theme.components).toEqual(before);+ });++ it('preserves explicit rule writes, including a later root-restoring value', () => {+ const theme = defineTheme({+ ...butterShapedInput,+ adaptations: {+ rules: [+ {+ when: {pointer: 'coarse'},+ value: {+ typography: {scale: {base: 15}},+ components: {+ text: {'type:display-1': {fontFamily: 'monospace'}},+ heading: {'level:1': {fontWeight: '300'}},+ },+ },+ },+ ...butterShapedInput.adaptations!.rules!,+ {+ when: {contrast: 'more'},+ value: {+ typography: {scale: {base: 14}},+ components: {+ text: {'type:display-1': {fontFamily: displayFamily}},+ },+ },+ },+ ],+ },+ });+ const [first, scaleOnly, restore] = theme.__adaptationRules!;+ expect(first.components).toEqual({+ text: {'type:display-1': {fontFamily: 'monospace'}},+ heading: {'level:1': {fontWeight: '300'}},+ });+ expect(scaleOnly.components).toBeUndefined();+ expect(restore.components).toEqual({+ text: {'type:display-1': {fontFamily: displayFamily}},+ });+ const css = generateAdaptationCSS(theme).component;+ expect(css.indexOf('font-family: monospace')).toBeLessThan(+ css.indexOf(`font-family: ${displayFamily}`),+ );+ // Explicit heading defaults still trigger the public weight-prop guard.+ expect(css).toContain(+ '.astryx-heading[data-weight="bold"] { font-weight: var(--font-weight-bold); }',+ );+ });++ it('lets a later generated component leaf win when its root path is absent', () => {+ const theme = defineTheme(+ adaptationInput([+ {+ when: {pointer: 'coarse'},+ value: {components: {text: {'type:body': {fontSize: '2rem'}}}},+ },+ {+ when: {pointer: 'coarse'},+ value: {typography: {scale: {base: 14, ratio: 1.2}}},+ },+ ]),+ );+ expect(theme.__axes.typography).toBeUndefined();+ expect(theme.components).toBeUndefined();+ const [authored, generated] = theme.__adaptationRules!;+ expect(authored.components?.text['type:body'].fontSize).toBe('2rem');+ expect(generated.components?.text['type:body'].fontSize).toBe(+ 'var(--text-body-size)',+ );++ // FR4/FR6: only existing root paths suppress generated defaults. Without+ // root wiring, the later scale produces a component write, so it beats the+ // earlier authored leaf when both conditions match (unlike the case above).+ const css = generateAdaptationCSS(theme).component;+ const bodyRules = [+ ...css.matchAll(/\.astryx-text\[data-type="body"\] \{([^}]+)\}/g),+ ].map(match => match[1]);+ expect(bodyRules).toHaveLength(2);+ expect(bodyRules[0]).toContain('font-size: 2rem;');+ expect(bodyRules[1]).toContain('font-size: var(--text-body-size);');+ expect(mediaPreludes(css)).toEqual([+ '(pointer: coarse)',+ '(pointer: coarse)',+ ]);+ expect(generateThemeCSS({...theme, __adaptationRules: undefined})).toEqual(+ generateThemeCSS(theme),+ );+ });++ it('uses the effective child root without mutating inherited components', () => {+ const base = defineTheme(butterShapedInput);+ const before = structuredClone(base.components);+ const child = defineTheme({+ name: 'child-display',+ extends: base,+ components: {+ text: {'type:display-2': {fontFamily: 'serif'}},+ heading: {'level:2': {fontFamily: 'monospace'}},+ },+ });+ expect(child.__adaptationRules![0].components).toBeUndefined();+ expect(child.components?.text['type:display-1'].fontFamily).toBe(+ displayFamily,+ );+ expect(child.components?.text['type:display-2'].fontFamily).toBe('serif');+ expect(child.components?.heading['level:2'].fontFamily).toBe('monospace');+ expect(base.components).toEqual(before);+ });+});+describe('theme-local adaptation values', () => {const localName = '--astryx-theme-local-root-control-height';diff --git a/packages/core/src/theme/themeAdaptations.ts b/packages/core/src/theme/themeAdaptations.tsindex b6e5316ea7..9e43095154 100644--- a/packages/core/src/theme/themeAdaptations.ts+++ b/packages/core/src/theme/themeAdaptations.ts@@ -9,8 +9,10 @@* Adaptations are deliberately closed and ordered. Width points are fixed names,* sparse rules and reserved token routing are rejected during normalization,* condition fields are ANDed, and rule order is the precedence model: every- * matching rule writes after the root theme and later matching writes win. Token- * cycles are judged only after each reachable ordered cascade is complete.+ * matching rule writes after the root theme and later matching writes win.+ * Invariant type-scale component defaults already declared at root are omitted;+ * authored rule leaves and generated token writes retain their cascade order.+ * Token cycles are judged after each reachable ordered cascade is complete.** SYNC: When modified, update:* - /packages/core/src/theme/defineTheme.ts (`DefineThemeInput.adaptations`)@@ -888,6 +890,42 @@ export function resolveThemeGenerativeAxes(};}+/**+ * Type-scale component generation is invariant var() wiring, not scale values.+ * Keep root declarations (including authored pins) in the root cascade instead+ * of resetting them in a rule that only changes tokens. Fill missing root paths+ * for rule-only scales, and retain every authored rule leaf, even when it equals+ * the root: that write may intentionally undo an earlier matching rule.+ *+ * SYNC: expandTypeScale.ts (generateTypeScaleComponents)+ */+function omitRootTypeScaleDefaults(+ resolved: ComponentStyleMap | undefined,+ root: ComponentStyleMap | undefined,+ authored: ComponentStyleMap | undefined,+): ComponentStyleMap | undefined {+ if (!resolved || !root) {+ return resolved;+ }++ const components: ComponentStyleMap = {};+ for (const [component, rules] of Object.entries(resolved)) {+ for (const [key, styles] of Object.entries(rules)) {+ const writes = Object.fromEntries(+ Object.entries(styles).filter(+ ([property]) =>+ root[component]?.[key]?.[property] === undefined ||+ Object.hasOwn(authored?.[component]?.[key] ?? {}, property),+ ),+ );+ if (Object.keys(writes).length > 0) {+ (components[component] ??= {})[key] = writes;+ }+ }+ }+ return Object.keys(components).length > 0 ? components : undefined;+}+/** Lower ordered normalized rules to concrete CSS writes. */export function resolveThemeAdaptationRules(themeName: string,@@ -895,14 +933,16 @@ export function resolveThemeAdaptationRules(axes: ThemeGenerativeAxes,rootTokens: Record<string, string>,rootLocalTokens: Record<string, string> | undefined,+ rootComponents?: ComponentStyleMap,): ResolvedThemeAdaptationRule[] | undefined {if (adaptations.rules.length === 0) {return undefined;}const resolvedRules = adaptations.rules.map((rule, index) => {+ const input = valueToThemeInput(themeName, index, rule.value, axes);const resolved = resolveThemeValues(- valueToThemeInput(themeName, index, rule.value, axes),+ input,undefined,// Authored adaptation values are a new surface with no legacy// acceptance to preserve, so a malformed token is rejected here rather@@ -951,7 +991,13 @@ export function resolveThemeAdaptationRules(),tokens: resolved.tokens,localTokens,- components: resolved.components,+ components: input.typography?.scale+ ? omitRootTypeScaleDefaults(+ resolved.components,+ rootComponents,+ rule.value.components,+ )+ : resolved.components,};});