An open source design system that's fully customizable and agent ready
TypeScript
feat(core): add Heading weight override (#6027)
rubyycheung9fdb3819f91b
diff --git a/.changeset/heading-weight-override.md b/.changeset/heading-weight-override.mdnew file mode 100644index 0000000000..a9966ebfdc--- /dev/null+++ b/.changeset/heading-weight-override.md@@ -0,0 +1,8 @@+---+'@astryxdesign/core': patch+---++[feature] Add a named font-weight override to Heading with precedence over its+visual type and semantic-level defaults.++@rubyycheungdiff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.jsonindex 1a1a4c3f70..1ccb13226e 100644--- a/apps/storybook/rtl-audit/verified-not-applicable.json+++ b/apps/storybook/rtl-audit/verified-not-applicable.json@@ -22,7 +22,7 @@},{"component": "core/Heading",- "reason": "Heading is typography-only. Its level, type, color, wrapping, truncation, and decoration styles do not position or reorder content on the inline axis; justify uses logical start/end values, and the optional truncation tooltip uses logical placement vocabulary. It renders no directional glyph, separator, control, physical inset, transform, drag, scroll, overlay, or directional keyboard behavior."+ "reason": "Heading is typography-only. Its level, type, weight, color, wrapping, truncation, and decoration styles do not position or reorder content on the inline axis; justify uses logical start/end values, and the optional truncation tooltip uses logical placement vocabulary. It renders no directional glyph, separator, control, physical inset, transform, drag, scroll, overlay, or directional keyboard behavior."},{"component": "core/Spinner",diff --git a/packages/cli/clients/cli/commands/build-theme.variants.test.mjs b/packages/cli/clients/cli/commands/build-theme.variants.test.mjsindex 3958362593..1be0495d38 100644--- a/packages/cli/clients/cli/commands/build-theme.variants.test.mjs+++ b/packages/cli/clients/cli/commands/build-theme.variants.test.mjs@@ -105,7 +105,18 @@ describe('theme build custom-variant augmentations', () => {'variant:accentOutline': { backgroundColor: 'transparent' },'size:jumbo': { paddingBlock: '40px' },},- heading: { 'type:hero': { fontSize: '80px' } },+ heading: {+ 'weight:bold': { fontWeight: '900' },+ 'type:hero': { fontSize: '80px', fontWeight: '300' },+ },+ },+ onDark: {+ components: {+ heading: {+ 'weight:bold': { fontWeight: '800' },+ 'type:hero': { fontWeight: '350' },+ },+ },},};\n`,);@@ -127,6 +138,17 @@ describe('theme build custom-variant augmentations', () => {expect(dts).toContain("declare module '@astryxdesign/core/Heading'");// …but closed literal-union props still get no dead augmentation.expect(dts).not.toMatch(/ButtonSizeMap/);++ const css = fs.readFileSync(+ path.join(tmpDir, 'variants-theme.css'),+ 'utf-8',+ );+ const mainTypeIndex = css.indexOf('.astryx-heading.hero');+ const mainWeightIndex = css.indexOf('font-weight: 900;', mainTypeIndex);+ const mediaTypeIndex = css.lastIndexOf('.astryx-heading.hero');+ const mediaWeightIndex = css.indexOf('font-weight: 800;', mediaTypeIndex);+ expect(mainWeightIndex).toBeGreaterThan(mainTypeIndex);+ expect(mediaWeightIndex).toBeGreaterThan(mediaTypeIndex);});it('unions custom Heading types from onDark and onLight into the public type contract', async () => {diff --git a/packages/core/src/Heading/Heading.test.tsx b/packages/core/src/Heading/Heading.test.tsxindex fc3edd4e70..5d23f7c11a 100644--- a/packages/core/src/Heading/Heading.test.tsx+++ b/packages/core/src/Heading/Heading.test.tsx@@ -237,6 +237,19 @@ describe('Heading', () => {expect(element.className).toContain(className);}});++ it('reflects an explicit weight for theme-layer precedence', () => {+ render(+ <Heading level={2} type="hero" weight="bold">+ Bold custom visual role+ </Heading>,+ );+ const element = screen.getByText('Bold custom visual role');++ expect(element).toHaveAttribute('data-weight', 'bold');+ expect(element.className).toContain('bold');+ expect(element.tagName).toBe('H2');+ });});it('renders astryx-* classes and data attributes for theme targeting', () => {diff --git a/packages/core/src/Heading/Heading.tsx b/packages/core/src/Heading/Heading.tsxindex 3583df753d..8e16c032e6 100644--- a/packages/core/src/Heading/Heading.tsx+++ b/packages/core/src/Heading/Heading.tsx@@ -25,12 +25,14 @@ import type {TextJustify,WordBreak,TextWrap,+ TextWeight,} from '../theme/types';import {colorStyles,sizeByLevelStyles,sizeByTypeStyles,defaultWeightByTypeStyles,+ weightStyles,displayStyles,justifyStyles,truncationStyles,@@ -98,6 +100,13 @@ export interface HeadingProps extends Omit<*/type?: HeadingType;+ /**+ * Explicit font-weight override. The active theme controls the numeric value+ * behind each name. When omitted, the selected visual type or heading level+ * supplies the default.+ */+ weight?: TextWeight;+/*** Accessibility level override. When set, the `aria-level` will differ* from the visual `level`. Use this when the visual hierarchy doesn't@@ -206,6 +215,7 @@ const levelToTag = {export function Heading({level,type,+ weight,accessibilityLevel,color = 'primary',display = 'block',@@ -266,13 +276,19 @@ export function Heading({<Componentref={mergedRef}{...mergeProps(- themeProps('heading', {level, color, type}),+ themeProps('heading', {+ level,+ color,+ type,+ weight,+ }),stylex.props(colorStyles[resolveStyleColor(color)],builtinType? sizeByTypeStyles[builtinType]: sizeByLevelStyles[level],builtinType && defaultWeightByTypeStyles[builtinType],+ weight && weightStyles[weight],// Display: use truncation styles when maxLines > 0maxLines === 1? truncationStyles.singleLinediff --git a/packages/core/src/Text/Heading.doc.mjs b/packages/core/src/Text/Heading.doc.mjsindex 5ab9bb4d3a..daf20cdd25 100644--- a/packages/core/src/Text/Heading.doc.mjs+++ b/packages/core/src/Text/Heading.doc.mjs@@ -10,7 +10,10 @@ export const docs = {'Semantic heading component that renders h1-h6 elements with themed styling, themed sizing via type scale tokens, and line-clamp truncation.',theming: {targets: [- {className: 'astryx-heading', visualProps: ['level', 'color', 'type']},+ {+ className: 'astryx-heading',+ visualProps: ['level', 'color', 'type', 'weight'],+ },],},props: [@@ -27,6 +30,12 @@ export const docs = {description:'Display type variant. Overrides the visual styling from `level` with display-scale sizing (larger, lighter weight, tighter line-height). Themes may add custom visual types. The `level` still determines the HTML element for accessibility. Use for hero banners, marketing headlines, and data callouts.',},+ {+ name: 'weight',+ type: "'normal' | 'medium' | 'semibold' | 'bold'",+ description:+ 'Explicit font-weight override. Wins over the selected visual type or heading-level default.',+ },{name: 'children',type: 'ReactNode',@@ -124,6 +133,11 @@ export const docsZh = {description:'展示类型变体。用展示级别的大小(更大、更轻的字重、更紧的行高)覆盖来自 `level` 的视觉样式。主题可以添加自定义视觉类型。`level` 仍然决定用于无障碍的 HTML 元素。用于英雄横幅、营销标题和数据提示。',},+ {+ name: 'weight',+ type: "'normal' | 'medium' | 'semibold' | 'bold'",+ description: '显式字重覆盖。优先于所选视觉类型或标题级别的默认值。',+ },{name: 'children',type: 'ReactNode',@@ -210,6 +224,8 @@ export const docsDense = {level:'Heading level; determines HTML element + styling from theme (unless type is set).',type: 'Display variant (display-1/2/3 or a theme-owned custom type); overrides visual styling from level.',+ weight:+ 'Explicit font weight; wins over the visual type or heading-level default.',children: 'Heading content.',accessibilityLevel:'aria-level override when different from level for document outline.',diff --git a/packages/core/src/Text/Text.doc.mjs b/packages/core/src/Text/Text.doc.mjsindex 533b5d7e23..e92a066012 100644--- a/packages/core/src/Text/Text.doc.mjs+++ b/packages/core/src/Text/Text.doc.mjs@@ -47,7 +47,10 @@ export const docs = {},theming: {targets: [- {className: 'astryx-heading', visualProps: ['level', 'color', 'type']},+ {+ className: 'astryx-heading',+ visualProps: ['level', 'color', 'type', 'weight'],+ },{className: 'astryx-text', visualProps: ['type', 'size', 'color']},],},diff --git a/packages/core/src/theme/generateThemeRules.test.ts b/packages/core/src/theme/generateThemeRules.test.tsindex a5cc05e5f9..9ad017c21c 100644--- a/packages/core/src/theme/generateThemeRules.test.ts+++ b/packages/core/src/theme/generateThemeRules.test.ts@@ -11,6 +11,7 @@ import {dataTokenDefaults,defineTheme,generateThemeCSS,+ generateOnMediaCSS,generateThemeRules,} from './index';import {generateDataTokenDefaultsCSS} from './generateThemeRules';@@ -363,6 +364,157 @@ describe('generateThemeRules with weight overrides', () => {});});+describe('generateThemeRules with an explicit Heading weight prop', () => {+ const theme = defineTheme({+ name: 'custom-heading-type',+ components: {+ heading: {+ 'type:hero': {+ fontSize: '4rem',+ fontWeight: 'var(--font-weight-normal)',+ },+ },+ },+ });+ const rules = generateThemeRules(theme);++ it('emits named weight rules after the custom type default', () => {+ const typeIndex = rules.findIndex(rule =>+ rule.includes('.astryx-heading.hero'),+ );+ const boldIndex = rules.findIndex(rule =>+ rule.includes('.astryx-heading.bold'),+ );++ expect(typeIndex).toBeGreaterThanOrEqual(0);+ expect(boldIndex).toBeGreaterThan(typeIndex);+ expect(rules[boldIndex]).toContain('font-weight: var(--font-weight-bold)');+ });++ it('keeps explicit weight rules in the component theme layer', () => {+ const {component, prose} = generateThemeCSS(theme);+ expect(component).toContain('.astryx-heading.bold');+ expect(prose).not.toContain('.astryx-heading.bold');+ });++ it('keeps a targeted theme weight rule authoritative', () => {+ const authored = defineTheme({+ name: 'authored-heading-weight',+ components: {+ heading: {+ 'weight:bold': {fontWeight: '900'},+ 'type:hero': {fontWeight: 'var(--font-weight-normal)'},+ },+ },+ });+ const rules = generateThemeRules(authored);+ const typeIndex = rules.findIndex(rule =>+ rule.includes('.astryx-heading.hero'),+ );+ const boldRules = rules.filter(rule =>+ rule.includes('.astryx-heading.bold'),+ );+ const lastBoldIndex = rules.lastIndexOf(boldRules.at(-1) ?? '');++ expect(boldRules.at(-1)).toContain('font-weight: 900');+ expect(boldRules.at(-1)).not.toContain('var(--font-weight-bold)');+ expect(lastBoldIndex).toBeGreaterThan(typeIndex);+ });++ it('does not let a combined selector suppress the generic weight override', () => {+ const authored = defineTheme({+ name: 'combined-heading-weight',+ components: {+ heading: {+ 'type:hero': {fontWeight: 'var(--font-weight-normal)'},+ 'type:hero+weight:bold': {fontWeight: '900'},+ },+ },+ });+ const rules = generateThemeRules(authored);++ expect(+ rules.some(+ rule =>+ rule.includes('.astryx-heading.bold') &&+ rule.includes('font-weight: var(--font-weight-bold)'),+ ),+ ).toBe(true);+ });++ it('fills in font weight when a standalone weight rule only styles another property', () => {+ const authored = defineTheme({+ name: 'partial-heading-weight',+ components: {+ heading: {+ 'type:hero': {fontWeight: 'var(--font-weight-normal)'},+ 'weight:bold': {color: 'red'},+ },+ },+ });+ const rules = generateThemeRules(authored);++ expect(+ rules.some(+ rule =>+ rule.includes('.astryx-heading.bold') &&+ rule.includes('font-weight: var(--font-weight-bold)'),+ ),+ ).toBe(true);+ });++ it('re-emits explicit weight overrides after media-specific type rules', () => {+ const themed = defineTheme({+ name: 'media-heading-weight',+ components: {+ heading: {+ 'weight:bold': {fontWeight: '900'},+ },+ },+ onDark: {+ components: {+ heading: {+ 'weight:bold': {fontWeight: '800'},+ 'type:hero': {fontWeight: '350'},+ },+ },+ },+ });+ const css = generateOnMediaCSS(themed);+ const typeIndex = css.indexOf('.astryx-heading.hero');+ const boldIndex = css.lastIndexOf('.astryx-heading.bold');++ expect(typeIndex).toBeGreaterThanOrEqual(0);+ expect(boldIndex).toBeGreaterThan(typeIndex);+ expect(css.slice(boldIndex)).toContain('font-weight: 800');+ });++ it('carries an authored main weight past a media-specific type rule', () => {+ const themed = defineTheme({+ name: 'inherited-media-heading-weight',+ components: {+ heading: {+ 'weight:bold': {fontWeight: '900'},+ },+ },+ onDark: {+ components: {+ heading: {+ 'type:hero': {fontWeight: '350'},+ },+ },+ },+ });+ const css = generateOnMediaCSS(themed);+ const typeIndex = css.indexOf('.astryx-heading.hero');+ const boldIndex = css.lastIndexOf('.astryx-heading.bold');++ expect(typeIndex).toBeGreaterThanOrEqual(0);+ expect(boldIndex).toBeGreaterThan(typeIndex);+ expect(css.slice(boldIndex)).toContain('font-weight: 900');+ });+});+// =============================================================================// Derived var expansion// =============================================================================diff --git a/packages/core/src/theme/generateThemeRules.ts b/packages/core/src/theme/generateThemeRules.tsindex b84303685a..03eb1bf087 100644--- a/packages/core/src/theme/generateThemeRules.ts+++ b/packages/core/src/theme/generateThemeRules.ts@@ -372,11 +372,78 @@ export function generateThemeRules(theme: DefinedTheme): string[] {// themed type's font-size across the astryx-base → astryx-theme layers)generateSizeOverrides(theme.components || {}, parts);+ // 6. Heading `weight`-prop overrides. These are emitted after authored type+ // rules in the same layer so an explicit prop remains an override even+ // when a custom visual type declares its own default weight.+ generateHeadingWeightOverrides(theme.components || {}, parts);+// (on-media rules are generated separately — see generateOnMediaCSS)return parts;}+/** Named Heading/Text weight props and their theme-owned token values. */+const HEADING_WEIGHT_TOKEN_MAP: Record<string, string> = {+ normal: 'var(--font-weight-normal)',+ medium: 'var(--font-weight-medium)',+ semibold: 'var(--font-weight-semibold)',+ bold: 'var(--font-weight-bold)',+};++/**+ * Re-emit Heading's explicit weight choices in the theme layer.+ *+ * Component and type overrides live above the StyleX base layer, so the+ * component's ordinary weight class cannot win there by itself. Emitting the+ * reflected weight classes after authored component rules makes the public+ * `weight` prop a dependable override of a type or level default.+ */+function generateHeadingWeightOverrides(+ components: Record<string, unknown>,+ parts: string[],+ surface?: 'dark' | 'light',+ inheritedComponents?: Record<string, unknown>,+): void {+ const headingRules = components.heading;+ if (!headingRules || typeof headingRules !== 'object') {+ return;+ }+ const headingRuleMap = headingRules as Record<string, unknown>;+ const inheritedHeadingRules = inheritedComponents?.heading;+ const inheritedHeadingRuleMap =+ inheritedHeadingRules && typeof inheritedHeadingRules === 'object'+ ? (inheritedHeadingRules as Record<string, unknown>)+ : undefined;++ for (const [weightName, weightValue] of Object.entries(+ HEADING_WEIGHT_TOKEN_MAP,+ )) {+ const styleKey = `weight:${weightName}`;+ const authoredWeight = getAuthoredHeadingWeight(headingRuleMap, styleKey);+ const inheritedWeight = inheritedHeadingRuleMap+ ? getAuthoredHeadingWeight(inheritedHeadingRuleMap, styleKey)+ : undefined;+ const effectiveWeight = authoredWeight ?? inheritedWeight ?? weightValue;+ const suffix = parseStyleKey(`weight:${weightName}`);+ const selector = surface+ ? `:is(${mediaSelector(surface)}) :is(${componentClassSelector('heading', suffix)})`+ : componentClassSelector('heading', suffix);+ parts.push(` ${selector} { font-weight: ${effectiveWeight}; }`);+ }+}++function getAuthoredHeadingWeight(+ headingRuleMap: Record<string, unknown>,+ styleKey: string,+): string | undefined {+ const rule = headingRuleMap[styleKey];+ if (rule == null || typeof rule !== 'object' || Array.isArray(rule)) {+ return undefined;+ }+ const fontWeight = (rule as Record<string, unknown>).fontWeight;+ return typeof fontWeight === 'string' ? fontWeight : undefined;+}+/*** Generate component override rules using the .astryx-* class selector* format. Runtime components also emit matching data-* prop reflections; the@@ -751,6 +818,16 @@ export function generateOnMediaCSS(theme: DefinedTheme): string {}}}++ // Apply the effective explicit Heading weight after media-specific type+ // rules. A surface-authored target wins, followed by the inherited main+ // target and then the built-in token fallback.+ generateHeadingWeightOverrides(+ onMedia.components,+ parts,+ surface,+ theme.components,+ );}}diff --git a/packages/core/src/theme/themingTargets.test.ts b/packages/core/src/theme/themingTargets.test.tsindex 39a22f7373..4ee7900a7d 100644--- a/packages/core/src/theme/themingTargets.test.ts+++ b/packages/core/src/theme/themingTargets.test.ts@@ -281,11 +281,11 @@ describe('extractThemeTargets', () => {});it('reads the keys of a conditional spread', () => {- // Heading's real call site: `{level, color, ...(type && {type})}`.+ // Heading's reflected visual props, including conditional type/weight.const [site] = extractThemeTargets(- `themeProps('heading', {level, color, ...(type && {type})})`,+ `themeProps('heading', {level, color, ...(type && {type}), ...(weight && {weight})})`,);- expect(site.propKeys).toEqual(['level', 'color', 'type']);+ expect(site.propKeys).toEqual(['level', 'color', 'type', 'weight']);expect(site.isOpaque).toBe(false);});