Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(core): support custom Heading visual types (#6026)

rubyycheungb1fcbeedb655
diff --git a/.changeset/extensible-heading-types.md b/.changeset/extensible-heading-types.md
new file mode 100644
index 0000000000..3772931b85
--- /dev/null
+++ b/.changeset/extensible-heading-types.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/core': patch
+'@astryxdesign/cli': patch
+---
+
+[feature] Let themes add typed Heading visual roles with a safe semantic-level
+fallback when the owning theme styles are unavailable.
+
+@rubyycheung
diff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.json
index 3fb4b0453c..d2c8e62916 100644
--- a/apps/storybook/rtl-audit/verified-not-applicable.json
+++ b/apps/storybook/rtl-audit/verified-not-applicable.json
@@ -11,6 +11,10 @@
"component": "core/FieldStatus",
"reason": "FieldStatus uses block-flow message layout and logical padding and corner radii. Its status glyphs are non-directional, and it has no side-specific placement, order, scrolling, dragging, overlays, or directional keyboard behavior."
},
+ {
+ "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."
+ },
{
"component": "core/Spinner",
"reason": "No direction-sensitive visual, layout, or behavior. The ring is a concentric SVG — two <circle> elements sharing one center, sized by diameter and stroke, with no physical inset, offset, or asymmetry to mirror. Its only layout is the optional label wrapper, which is flexDirection: column + alignItems: center, so the label stacks below the ring on both axes' terms rather than beside it. The rotation keyframe (0deg to 360deg) is deliberately absolute: a loading spinner turns the same way in every locale, and mirroring it would be a bug, not RTL support."
diff --git a/apps/storybook/stories/Heading.stories.tsx b/apps/storybook/stories/Heading.stories.tsx
index 5c6982ad5b..6b8903bb2d 100644
--- a/apps/storybook/stories/Heading.stories.tsx
+++ b/apps/storybook/stories/Heading.stories.tsx
@@ -1,7 +1,7 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import type {Meta, StoryObj} from '@storybook/react';
-import {Heading} from '@astryxdesign/core/Text';
+import {Heading} from '@astryxdesign/core/Heading';
import {Text} from '@astryxdesign/core/Text';
const meta: Meta<typeof Heading> = {
diff --git a/packages/cli/api/theme/build/build.heading-core-compat.test.mjs b/packages/cli/api/theme/build/build.heading-core-compat.test.mjs
new file mode 100644
index 0000000000..ec90798758
--- /dev/null
+++ b/packages/cli/api/theme/build/build.heading-core-compat.test.mjs
@@ -0,0 +1,68 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+const coreDeclarationMock = vi.hoisted(() => ({useLegacyHeading: false}));
+
+vi.mock('node:fs', async importActual => {
+ const actual = await importActual();
+ return {
+ ...actual,
+ readFileSync(file, ...args) {
+ if (
+ coreDeclarationMock.useLegacyHeading &&
+ /[\\/]dist[\\/]Heading[\\/]index\.d\.ts$/.test(String(file))
+ ) {
+ return `export { Heading, type HeadingProps, type HeadingLevel, type HeadingType } from './Heading';\n`;
+ }
+ return actual.readFileSync(file, ...args);
+ },
+ };
+});
+
+const {themeBuild} = await import('./build.mjs');
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'astryx-heading-core-compat-'),
+ );
+});
+afterEach(() => {
+ coreDeclarationMock.useLegacyHeading = false;
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('theme build Heading compatibility guard', () => {
+ it('rejects a surface custom type when the installed Core predates HeadingTypeMap', async () => {
+ const themeFile = path.join(tmpDir, 'legacy-core-theme.mjs');
+ fs.writeFileSync(
+ themeFile,
+ `export default {
+ name: 'legacy-core-theme',
+ tokens: { '--color-bg': '#fff' },
+ onDark: {
+ components: {
+ heading: { 'type:hero': { fontSize: '80px' } },
+ },
+ },
+ };\n`,
+ );
+ coreDeclarationMock.useLegacyHeading = true;
+
+ await expect(
+ themeBuild('legacy-core-theme.mjs', {}, {cwd: tmpDir}),
+ ).rejects.toThrow(
+ 'Custom Heading types require an installed @astryxdesign/core that exports HeadingTypeMap',
+ );
+ expect(fs.existsSync(path.join(tmpDir, 'legacy-core-theme.css'))).toBe(
+ false,
+ );
+ expect(
+ fs.existsSync(path.join(tmpDir, 'legacy-core-theme.variants.d.ts')),
+ ).toBe(false);
+ });
+});
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index c6d7786ad5..3718fae0a8 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -47,10 +47,7 @@ import {
collectThemingTargets,
targetsByKey,
} from '../../../foundation/discovery/theming-targets.mjs';
-import {
- collectUnloadedFonts,
- formatFontLoadingHelp,
-} from './font-warning.mjs';
+import {collectUnloadedFonts, formatFontLoadingHelp} from './font-warning.mjs';
// Import shared theme processing from core. `astryx theme build` MUST produce the
// exact same CSS as the `<Theme>` runtime, so it has exactly one generation
@@ -343,7 +340,6 @@ function readComponentDeclarations(pascalName) {
return contents;
}
-
/** @type {Map<string, Array<{moduleName: string, interfacePrefix: string}>>} */
const _augmentationTargetCache = new Map();
@@ -402,7 +398,8 @@ async function resolveAugmentationTargetCandidates(componentName) {
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
- if (entry.name === 'node_modules' || entry.name === '__tests__') continue;
+ if (entry.name === 'node_modules' || entry.name === '__tests__')
+ continue;
await scan(full);
continue;
}
@@ -445,7 +442,15 @@ async function resolveAugmentationTargetCandidates(componentName) {
}
await scan(coreSrc);
- const resolved = matches.length > 0 ? matches : fallback;
+ // A target documented by a parent component may also have its own public
+ // subpath and augmentation interface (Heading is documented under Text but
+ // owns @astryxdesign/core/Heading). Keep the direct-name candidate after
+ // discovered owners so both shapes are reachable without guessing which one
+ // the source tree uses.
+ for (const candidate of fallback) {
+ addCandidate(candidate.moduleName, candidate.interfacePrefix);
+ }
+ const resolved = matches;
_augmentationTargetCache.set(componentName, resolved);
return resolved;
}
@@ -493,7 +498,8 @@ function componentHasAugmentableInterface(pascalName, interfaceName) {
* @returns {Promise<string|null>} TypeScript declaration content, or null if no augmentations needed
*/
async function generateVariantDeclarationsAsync(themeDef) {
- if (!themeDef.components || Object.keys(themeDef.components).length === 0) {
+ const componentLayers = getThemeComponentLayers(themeDef);
+ if (componentLayers.length === 0) {
return null;
}
@@ -501,27 +507,29 @@ async function generateVariantDeclarationsAsync(themeDef) {
/** @type {Record<string, Record<string, Set<string>>>} */
const customValues = {};
- for (const [component, rules] of Object.entries(themeDef.components)) {
- const knownForComponent = await getKnownValues(component);
+ for (const {components} of componentLayers) {
+ for (const [component, rules] of Object.entries(components)) {
+ const knownForComponent = await getKnownValues(component);
- for (const key of Object.keys(rules)) {
- if (key === 'base') continue;
+ for (const key of Object.keys(rules)) {
+ if (key === 'base') continue;
- const pairs = key.split('+');
- for (const pair of pairs) {
- const colonIdx = pair.indexOf(':');
- if (colonIdx === -1) continue;
- const prop = pair.slice(0, colonIdx);
- const value = pair.slice(colonIdx + 1);
-
- // Skip known built-in values
- const knownForProp = knownForComponent[prop];
- if (knownForProp && knownForProp.includes(value)) continue;
-
- if (!customValues[component]) customValues[component] = {};
- if (!customValues[component][prop])
- customValues[component][prop] = new Set();
- customValues[component][prop].add(value);
+ const pairs = key.split('+');
+ for (const pair of pairs) {
+ const colonIdx = pair.indexOf(':');
+ if (colonIdx === -1) continue;
+ const prop = pair.slice(0, colonIdx);
+ const value = pair.slice(colonIdx + 1);
+
+ // Skip known built-in values
+ const knownForProp = knownForComponent[prop];
+ if (knownForProp && knownForProp.includes(value)) continue;
+
+ if (!customValues[component]) customValues[component] = {};
+ if (!customValues[component][prop])
+ customValues[component][prop] = new Set();
+ customValues[component][prop].add(value);
+ }
}
}
}
@@ -539,12 +547,13 @@ async function generateVariantDeclarationsAsync(themeDef) {
if (values.size === 0) continue;
const propPascal = prop.charAt(0).toUpperCase() + prop.slice(1);
- const target = (await resolveAugmentationTargetCandidates(component)).find(
- candidate =>
- componentHasAugmentableInterface(
- candidate.moduleName,
- `${candidate.interfacePrefix}${propPascal}Map`,
- ),
+ const target = (
+ await resolveAugmentationTargetCandidates(component)
+ ).find(candidate =>
+ componentHasAugmentableInterface(
+ candidate.moduleName,
+ `${candidate.interfacePrefix}${propPascal}Map`,
+ ),
);
// Only augment interfaces that actually exist as an extension point in
@@ -1031,6 +1040,156 @@ function validatePrivateVars(themeDef) {
return errors;
}
+const BUILTIN_HEADING_TYPES = new Set(['display-1', 'display-2', 'display-3']);
+
+/**
+ * Return every component-rule layer that can emit CSS for a theme. Raw theme
+ * input stores media-surface overrides in `onDark`/`onLight`; a theme already
+ * resolved by defineTheme stores them in `__onDark`/`__onLight` instead.
+ *
+ * @param {{components?: Record<string, Record<string, unknown>>, onDark?: {components?: Record<string, Record<string, unknown>>}, onLight?: {components?: Record<string, Record<string, unknown>>}, __onDark?: {components?: Record<string, Record<string, unknown>>}, __onLight?: {components?: Record<string, Record<string, unknown>>}}} themeDef
+ * @returns {{name: 'base'|'onDark'|'onLight', components: Record<string, Record<string, unknown>>}[]}
+ */
+function getThemeComponentLayers(themeDef) {
+ /** @type {{name: 'base'|'onDark'|'onLight', components: Record<string, Record<string, unknown>>}[]} */
+ const layers = [];
+ /**
+ * @param {'base'|'onDark'|'onLight'} name
+ * @param {{components?: Record<string, Record<string, unknown>>}|undefined} surface
+ */
+ const addLayer = (name, surface) => {
+ if (
+ surface?.components &&
+ typeof surface.components === 'object' &&
+ Object.keys(surface.components).length > 0
+ ) {
+ layers.push({name, components: surface.components});
+ }
+ };
+
+ addLayer('base', themeDef);
+ addLayer('onDark', themeDef.__onDark ?? themeDef.onDark);
+ addLayer('onLight', themeDef.__onLight ?? themeDef.onLight);
+ return layers;
+}
+
+/**
+ * A generated type augmentation makes a custom Heading type callable with the
+ * type prop, so that name needs a standalone visual rule of its own. A value
+ * that appears only in a combined selector (or has an empty rule) would
+ * type-check but fall back for ordinary `type="name"` use.
+ *
+ * @param {{components?: Record<string, Record<string, unknown>>}} themeDef
+ * @returns {string[]}
+ */
+function validateCustomHeadingTypes(themeDef) {
+ const layers = getThemeComponentLayers(themeDef);
+ const customTypes = new Set();
+ for (const {components} of layers) {
+ const headingRules = components.heading;
+ if (!headingRules || typeof headingRules !== 'object') continue;
+
+ for (const key of Object.keys(headingRules)) {
+ for (const pair of key.split('+')) {
+ const colon = pair.indexOf(':');
+ if (colon === -1 || pair.slice(0, colon) !== 'type') continue;
+ const value = pair.slice(colon + 1);
+ if (value && !BUILTIN_HEADING_TYPES.has(value)) customTypes.add(value);
+ }
+ }
+ }
+
+ const errors = [];
+ for (const type of customTypes) {
+ const hasStandalone = layers.some(({components}) => {
+ const headingRules = components.heading;
+ if (!headingRules || typeof headingRules !== 'object') return false;
+ const standalone = headingRules[`type:${type}`];
+ return (
+ standalone != null &&
+ typeof standalone === 'object' &&
+ !Array.isArray(standalone) &&
+ hasUsableStyleDeclaration(standalone)
+ );
+ });
+ if (!hasStandalone) {
+ errors.push(
+ `Custom Heading type "${type}" needs a non-empty standalone ` +
+ `components.heading["type:${type}"], ` +
+ `onDark.components.heading["type:${type}"], or ` +
+ `onLight.components.heading["type:${type}"] rule.`,
+ );
+ }
+ }
+ return errors;
+}
+
+/**
+ * Return true when a style object contains a declaration that the theme
+ * generator can emit. Empty pseudo blocks do not count: they produce no CSS
+ * and would leave the generated type augmentation without a usable rule.
+ *
+ * @param {unknown} styles
+ * @returns {boolean}
+ */
+function hasUsableStyleDeclaration(styles) {
+ if (!styles || typeof styles !== 'object' || Array.isArray(styles)) {
+ return false;
+ }
+ for (const [property, value] of Object.entries(styles)) {
+ if (property.startsWith(':')) {
+ if (hasUsableStyleDeclaration(value)) return true;
+ continue;
+ }
+ if (value !== undefined && value !== null && typeof value !== 'object') {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Custom Heading types are only useful when the installed Core package exposes
+ * the public map that the generated declaration augments. The CLI and Core
+ * are optional peers and can be upgraded independently, so fail explicitly
+ * instead of emitting CSS that application TypeScript cannot consume.
+ *
+ * @param {{components?: Record<string, Record<string, unknown>>}} themeDef
+ * @returns {string[]}
+ */
+function validateHeadingTypeAugmentationSupport(themeDef) {
+ const hasCustomType = getThemeComponentLayers(themeDef).some(
+ ({components}) => {
+ const headingRules = components.heading;
+ return (
+ headingRules &&
+ typeof headingRules === 'object' &&
+ Object.keys(headingRules).some(key =>
+ key.split('+').some(pair => {
+ const colon = pair.indexOf(':');
+ return (
+ colon !== -1 &&
+ pair.slice(0, colon) === 'type' &&
+ pair.slice(colon + 1) &&
+ !BUILTIN_HEADING_TYPES.has(pair.slice(colon + 1))
+ );
+ }),
+ )
+ );
+ },
+ );
+ if (!hasCustomType) return [];
+
+ if (!componentHasAugmentableInterface('Heading', 'HeadingTypeMap')) {
+ return [
+ 'Custom Heading types require an installed @astryxdesign/core that ' +
+ 'exports HeadingTypeMap from the public Heading subpath. Upgrade Core ' +
+ 'before building this theme.',
+ ];
+ }
+ return [];
+}
+
/**
* Compile a defineTheme file to CSS + JS + .d.ts (and an optional
* `.variants.d.ts`). Performs the writes and returns a `theme.build` receipt,
@@ -1120,6 +1279,16 @@ export async function themeBuild(
);
}
+ const customHeadingErrors = validateCustomHeadingTypes(themeDef);
+ customHeadingErrors.push(...validateHeadingTypeAugmentationSupport(themeDef));
+ if (customHeadingErrors.length > 0) {
+ throw new AstryxError(
+ customHeadingErrors.join('\n'),
+ undefined,
+ ERROR_CODES.ERR_THEME_INVALID,
+ );
+ }
+
// Generate CSS via core's shared generator — the SINGLE source of truth.
// `astryx theme build` and the `<Theme>` runtime MUST emit identical CSS, so
// there is exactly one generation path: @astryxdesign/core/theme. If core could not
diff --git a/packages/cli/clients/cli/commands/build-theme.variants.test.mjs b/packages/cli/clients/cli/commands/build-theme.variants.test.mjs
index a7ad2a82f2..3958362593 100644
--- a/packages/cli/clients/cli/commands/build-theme.variants.test.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.variants.test.mjs
@@ -55,7 +55,9 @@ beforeAll(() => {
let tmpDir;
beforeEach(() => {
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-build-theme-variants-'));
+ tmpDir = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'astryx-build-theme-variants-'),
+ );
});
afterEach(() => {
fs.rmSync(tmpDir, {recursive: true, force: true});
@@ -92,7 +94,7 @@ describe('theme build custom-variant augmentations', () => {
expect(dts).not.toMatch(/XDSButtonVariantMap/);
});
- it('skips props with no augmentation point (Button size, Heading type)', async () => {
+ it('emits Heading custom types and skips props with no augmentation point', async () => {
const themeFile = writeTheme(
tmpDir,
`export default {
@@ -118,12 +120,108 @@ describe('theme build custom-variant augmentations', () => {
expect(fs.existsSync(variantsPath)).toBe(true);
const dts = fs.readFileSync(variantsPath, 'utf-8');
- // The augmentable variant is emitted…
+ // The augmentable values are emitted…
expect(dts).toMatch(/interface ButtonVariantMap\b/);
- // …but closed literal-union props get no dead augmentation.
+ expect(dts).toMatch(/interface HeadingTypeMap\b/);
+ expect(dts).toContain("'hero': true;");
+ expect(dts).toContain("declare module '@astryxdesign/core/Heading'");
+ // …but closed literal-union props still get no dead augmentation.
expect(dts).not.toMatch(/ButtonSizeMap/);
- expect(dts).not.toMatch(/HeadingTypeMap/);
- expect(dts).not.toContain("declare module '@astryxdesign/core/Heading'");
+ });
+
+ it('unions custom Heading types from onDark and onLight into the public type contract', async () => {
+ const themeFile = writeTheme(
+ tmpDir,
+ `export default {
+ name: 'variants-theme',
+ tokens: { '--color-bg': '#fff' },
+ components: {
+ heading: { 'type:shared': { fontWeight: 600 } },
+ },
+ onDark: {
+ components: {
+ heading: {
+ 'type:hero': { fontSize: '80px' },
+ 'type:shared+level:1': { lineHeight: 1 },
+ },
+ },
+ },
+ onLight: {
+ components: {
+ heading: { 'type:editorial': { letterSpacing: '-0.02em' } },
+ },
+ },
+ };\n`,
+ );
+
+ const result = await runCli(
+ ['theme', 'build', path.relative(tmpDir, themeFile)],
+ tmpDir,
+ );
+ expect(result.code).toBe(0);
+
+ const variantsPath = path.join(tmpDir, 'variants-theme.variants.d.ts');
+ expect(fs.existsSync(variantsPath)).toBe(true);
+ const variantsDts = fs.readFileSync(variantsPath, 'utf-8');
+ expect(variantsDts).toMatch(/interface HeadingTypeMap\b/);
+ expect(variantsDts).toContain("'hero': true;");
+ expect(variantsDts).toContain("'editorial': true;");
+ expect(variantsDts).toContain("'shared': true;");
+
+ const projectDir = path.join(
+ CLI_ROOT,
+ `.tmp-surface-heading-consumer-${process.pid}`,
+ );
+ fs.rmSync(projectDir, {recursive: true, force: true});
+ fs.mkdirSync(projectDir);
+ fs.copyFileSync(
+ path.join(tmpDir, 'variants-theme.d.ts'),
+ path.join(projectDir, 'variants-theme.d.ts'),
+ );
+ fs.copyFileSync(
+ variantsPath,
+ path.join(projectDir, 'variants-theme.variants.d.ts'),
+ );
+ fs.writeFileSync(
+ path.join(projectDir, 'probe.tsx'),
+ `import './variants-theme';\n` +
+ `import {Heading} from '@astryxdesign/core/Heading';\n\n` +
+ `export const Probe = () => (\n` +
+ ` <>\n` +
+ ` <Heading level={1} type="hero">Hero</Heading>\n` +
+ ` <Heading level={2} type="editorial">Editorial</Heading>\n` +
+ ` <Heading level={3} type="shared">Shared</Heading>\n` +
+ ` </>\n` +
+ `);\n`,
+ );
+ fs.writeFileSync(
+ path.join(projectDir, 'tsconfig.json'),
+ JSON.stringify(
+ {
+ compilerOptions: {
+ module: 'esnext',
+ target: 'es2022',
+ jsx: 'react-jsx',
+ moduleResolution: 'bundler',
+ strict: true,
+ skipLibCheck: true,
+ },
+ include: ['*.tsx', '*.d.ts'],
+ },
+ null,
+ 2,
+ ),
+ );
+
+ try {
+ execFileSync(
+ 'pnpm',
+ ['exec', 'tsc', '--project', 'tsconfig.json', '--noEmit'],
+ {cwd: projectDir, stdio: 'pipe'},
+ );
+ } finally {
+ fs.rmSync(projectDir, {recursive: true, force: true});
+ }
});
it('does not emit a .variants.d.ts when every custom value is non-augmentable', async () => {
@@ -148,6 +246,45 @@ describe('theme build custom-variant augmentations', () => {
).toBe(false);
});
+ it('rejects an empty or combination-only custom Heading type', async () => {
+ const themeFile = writeTheme(
+ tmpDir,
+ `export default {
+ name: 'variants-theme',
+ tokens: { '--color-bg': '#fff' },
+ onDark: {
+ components: {
+ heading: { 'type:hero': { ':hover': {} } },
+ },
+ },
+ onLight: {
+ components: {
+ heading: {
+ 'type:eyebrow+color:accent': { letterSpacing: '0.08em' },
+ },
+ },
+ },
+ };\n`,
+ );
+
+ const result = await runCli(
+ ['theme', 'build', path.relative(tmpDir, themeFile)],
+ tmpDir,
+ );
+
+ expect(result.code).toBe(1);
+ expect(result.stderr).toContain(
+ 'Custom Heading type "hero" needs a non-empty standalone',
+ );
+ expect(result.stderr).toContain(
+ 'Custom Heading type "eyebrow" needs a non-empty standalone',
+ );
+ expect(result.stderr).toContain('onDark.components.heading["type:hero"]');
+ expect(result.stderr).toContain(
+ 'onLight.components.heading["type:eyebrow"]',
+ );
+ });
+
it('makes generated custom component prop values type-check through public subpaths', async () => {
const themeFile = writeTheme(
tmpDir,
@@ -172,6 +309,7 @@ describe('theme build custom-variant augmentations', () => {
progressbar: { 'variant:customProgressBar': { backgroundColor: 'transparent' } },
section: { 'variant:customSection': { backgroundColor: 'transparent' } },
statusdot: { 'variant:customStatusDot': { backgroundColor: 'transparent' } },
+ heading: { 'type:customHeading': { fontSize: '3rem' } },
text: { 'color:customTextColor': { color: 'currentColor' } },
token: { 'color:customTokenColor': { backgroundColor: 'transparent' } },
},
@@ -185,7 +323,10 @@ describe('theme build custom-variant augmentations', () => {
);
expect(result.code).toBe(0);
- const projectDir = path.join(CLI_ROOT, `.tmp-variant-consumer-${process.pid}`);
+ const projectDir = path.join(
+ CLI_ROOT,
+ `.tmp-variant-consumer-${process.pid}`,
+ );
fs.rmSync(projectDir, {recursive: true, force: true});
fs.mkdirSync(projectDir);
fs.copyFileSync(
@@ -213,6 +354,7 @@ describe('theme build custom-variant augmentations', () => {
`import {ProgressBar} from '@astryxdesign/core/ProgressBar';\n` +
`import {Section} from '@astryxdesign/core/Section';\n` +
`import {StatusDot} from '@astryxdesign/core/StatusDot';\n` +
+ `import {Heading} from '@astryxdesign/core/Heading';\n` +
`import {Text} from '@astryxdesign/core/Text';\n` +
`import {Token} from '@astryxdesign/core/Token';\n\n` +
`export function Probe() {\n` +
@@ -232,6 +374,7 @@ describe('theme build custom-variant augmentations', () => {
` <ProgressBar label="Progress" value={50} variant="customProgressBar" />\n` +
` <Section variant="customSection">Section</Section>\n` +
` <StatusDot label="Status" variant="customStatusDot" />\n` +
+ ` <Heading level={2} type="customHeading">Heading</Heading>\n` +
` <Text color="customTextColor">Text</Text>\n` +
` <Token label="Token" color="customTokenColor" />\n` +
` </>\n` +
@@ -258,10 +401,14 @@ describe('theme build custom-variant augmentations', () => {
);
try {
- execFileSync('pnpm', ['exec', 'tsc', '--project', 'tsconfig.json', '--noEmit'], {
- cwd: projectDir,
- stdio: 'pipe',
- });
+ execFileSync(
+ 'pnpm',
+ ['exec', 'tsc', '--project', 'tsconfig.json', '--noEmit'],
+ {
+ cwd: projectDir,
+ stdio: 'pipe',
+ },
+ );
} finally {
fs.rmSync(projectDir, {recursive: true, force: true});
}
diff --git a/packages/core/src/Heading/Heading.test.tsx b/packages/core/src/Heading/Heading.test.tsx
index e1158fa6c1..fc3edd4e70 100644
--- a/packages/core/src/Heading/Heading.test.tsx
+++ b/packages/core/src/Heading/Heading.test.tsx
@@ -9,6 +9,12 @@ import {render, screen} from '@testing-library/react';
import {describe, it, expect, vi} from 'vitest';
import {Heading} from './Heading';
+declare module './index' {
+ interface HeadingTypeMap {
+ hero: true;
+ }
+}
+
describe('Heading', () => {
describe('rendering', () => {
it('renders children correctly', () => {
@@ -209,6 +215,28 @@ describe('Heading', () => {
const element = screen.getByText('Display Heading');
expect(element.className).toContain('display-1');
});
+
+ it('reflects a theme-augmented visual type and keeps the level baseline', () => {
+ const baseline = render(<Heading level={2}>Baseline</Heading>);
+ const baselineClasses = screen
+ .getByText('Baseline')
+ .className.split(/\s+/)
+ .filter(Boolean);
+ baseline.unmount();
+
+ render(
+ <Heading level={2} type="hero">
+ Custom visual role
+ </Heading>,
+ );
+ const element = screen.getByText('Custom visual role');
+
+ expect(element).toHaveAttribute('data-type', 'hero');
+ expect(element.className).toContain('hero');
+ for (const className of baselineClasses) {
+ expect(element.className).toContain(className);
+ }
+ });
});
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.tsx
index d503981584..3583df753d 100644
--- a/packages/core/src/Heading/Heading.tsx
+++ b/packages/core/src/Heading/Heading.tsx
@@ -47,6 +47,7 @@ import {mergeProps} from '../utils';
import {useMergedRefs} from '../hooks/useMergedRefs';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
+import type {HeadingTypeMap} from './index';
const LazyXDSTooltip = lazy(async () =>
import('../Tooltip/Tooltip').then(mod => ({default: mod.Tooltip})),
@@ -61,7 +62,13 @@ export type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
* Display type variants for headings. Applies display-scale sizing
* (larger, lighter) while preserving the semantic heading element.
*/
-export type HeadingType = 'display-1' | 'display-2' | 'display-3';
+export type HeadingType = keyof HeadingTypeMap;
+
+type BuiltinHeadingType = 'display-1' | 'display-2' | 'display-3';
+
+function isBuiltinHeadingType(type: HeadingType): type is BuiltinHeadingType {
+ return type === 'display-1' || type === 'display-2' || type === 'display-3';
+}
export interface HeadingProps extends Omit<
BaseProps<HTMLHeadingElement>,
@@ -231,6 +238,11 @@ export function Heading({
// Resolve display - force block when maxLines > 0 or hasCapsize
const resolvedDisplay = maxLines > 0 || hasCapsize ? 'block' : display;
+ // A custom type receives its visual treatment from theme CSS. Keep the
+ // semantic level's baseline until that CSS is available instead of indexing
+ // the closed built-in StyleX maps with an unknown name.
+ const builtinType = type && isBuiltinHeadingType(type) ? type : undefined;
+
// Truncation detection
const truncation = useTruncation({maxLines});
@@ -254,11 +266,13 @@ export function Heading({
<Component
ref={mergedRef}
{...mergeProps(
- themeProps('heading', {level, color, ...(type && {type})}),
+ themeProps('heading', {level, color, type}),
stylex.props(
colorStyles[resolveStyleColor(color)],
- type ? sizeByTypeStyles[type] : sizeByLevelStyles[level],
- type && defaultWeightByTypeStyles[type],
+ builtinType
+ ? sizeByTypeStyles[builtinType]
+ : sizeByLevelStyles[level],
+ builtinType && defaultWeightByTypeStyles[builtinType],
// Display: use truncation styles when maxLines > 0
maxLines === 1
? truncationStyles.singleLine
diff --git a/packages/core/src/Heading/index.ts b/packages/core/src/Heading/index.ts
index be1d9eeb62..114a14ae75 100644
--- a/packages/core/src/Heading/index.ts
+++ b/packages/core/src/Heading/index.ts
@@ -3,10 +3,29 @@
/**
* @file index.ts
* @input Heading component source
- * @output Exports Heading and its props/types
+ * @output Exports Heading, its props/types, and the extensible HeadingTypeMap
* @position Entry point for @astryxdesign/core/Heading subpath export
*/
+/**
+ * Extensible visual-type map for Heading.
+ *
+ * Theme builds add custom visual roles through module augmentation:
+ * @example
+ * ```ts
+ * declare module '@astryxdesign/core/Heading' {
+ * interface HeadingTypeMap {
+ * hero: true;
+ * }
+ * }
+ * ```
+ */
+export interface HeadingTypeMap {
+ 'display-1': true;
+ 'display-2': true;
+ 'display-3': true;
+}
+
export {
Heading,
type HeadingProps,
diff --git a/packages/core/src/Text/Heading.doc.mjs b/packages/core/src/Text/Heading.doc.mjs
index b12c6d67cb..5ab9bb4d3a 100644
--- a/packages/core/src/Text/Heading.doc.mjs
+++ b/packages/core/src/Text/Heading.doc.mjs
@@ -6,18 +6,26 @@ export const docs = {
name: 'Heading',
subComponentOf: 'Text',
displayName: 'Heading',
- description: 'Semantic heading component that renders h1-h6 elements with themed styling, themed sizing via type scale tokens, and line-clamp truncation.',
+ description:
+ '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']},
+ ],
+ },
props: [
{
name: 'level',
type: '1 | 2 | 3 | 4 | 5 | 6',
- description: 'Heading level. Determines the semantic HTML element (h1-h6) and the visual styling from the theme (unless `type` is set).',
+ description:
+ 'Heading level. Determines the semantic HTML element (h1-h6) and the visual styling from the theme (unless `type` is set).',
required: true,
},
{
name: 'type',
type: "'display-1' | 'display-2' | 'display-3'",
- description: 'Display type variant. Overrides the visual styling from `level` with display-scale sizing (larger, lighter weight, tighter line-height). The `level` still determines the HTML element for accessibility. Use for hero banners, marketing headlines, and data callouts.',
+ 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: 'children',
@@ -28,7 +36,8 @@ export const docs = {
{
name: 'accessibilityLevel',
type: '1 | 2 | 3 | 4 | 5 | 6',
- description: 'Accessibility level override. When set and different from `level`, applies `aria-level` so the document outline differs from the visual style.',
+ description:
+ 'Accessibility level override. When set and different from `level`, applies `aria-level` so the document outline differs from the visual style.',
},
{
name: 'color',
@@ -39,25 +48,29 @@ export const docs = {
{
name: 'display',
type: "'inline' | 'block'",
- description: "Display type. Silently overridden to 'block' when maxLines > 0 or hasCapsize is true.",
+ description:
+ "Display type. Silently overridden to 'block' when maxLines > 0 or hasCapsize is true.",
default: "'block'",
},
{
name: 'maxLines',
type: 'number',
- description: 'Maximum lines before truncation. 0 means no truncation. When set, shows a tooltip on hover if content is truncated.',
+ description:
+ 'Maximum lines before truncation. 0 means no truncation. When set, shows a tooltip on hover if content is truncated.',
default: '0',
},
{
name: 'hasTruncateTooltip',
type: "boolean | 'above' | 'below' | 'start' | 'end'",
- description: "Controls tooltip behavior for truncated text. true shows the tooltip at the default position, false disables it, or a placement string ('above' | 'below' | 'start' | 'end') sets a specific position.",
+ description:
+ "Controls tooltip behavior for truncated text. true shows the tooltip at the default position, false disables it, or a placement string ('above' | 'below' | 'start' | 'end') sets a specific position.",
default: 'true',
},
{
name: 'wordBreak',
type: "'break-word' | 'break-all'",
- description: "Word break behavior when truncating. Defaults to 'break-all' for single-line truncation, 'break-word' otherwise.",
+ description:
+ "Word break behavior when truncating. Defaults to 'break-all' for single-line truncation, 'break-word' otherwise.",
},
{
name: 'textWrap',
@@ -67,13 +80,15 @@ export const docs = {
{
name: 'justify',
type: "'start' | 'center' | 'end'",
- description: 'Text alignment (justification). Uses logical values (start/end) for i18n/RTL compatibility.',
+ description:
+ 'Text alignment (justification). Uses logical values (start/end) for i18n/RTL compatibility.',
default: "'start'",
},
{
name: 'hasCapsize',
type: 'boolean',
- description: 'Enable optical alignment using text-box-trim. Forces block display.',
+ description:
+ 'Enable optical alignment using text-box-trim. Forces block display.',
default: 'false',
},
{
@@ -93,18 +108,21 @@ export const docs = {
export const docsZh = {
name: 'Heading',
displayName: 'Heading',
- description: '语义化标题组件,渲染带主题样式的 h1–h6 元素,支持可选的编辑风格比例和行截断。',
+ description:
+ '语义化标题组件,渲染带主题样式的 h1–h6 元素,支持可选的编辑风格比例和行截断。',
props: [
{
name: 'level',
type: '1 | 2 | 3 | 4 | 5 | 6',
- description: '标题级别。决定语义 HTML 元素(h1–h6)和来自主题的样式(除非设置了 `type`)。',
+ description:
+ '标题级别。决定语义 HTML 元素(h1–h6)和来自主题的样式(除非设置了 `type`)。',
required: true,
},
{
name: 'type',
type: "'display-1' | 'display-2' | 'display-3'",
- description: '展示类型变体。用展示级别的大小(更大、更轻的字重、更紧的行高)覆盖来自 `level` 的视觉样式。`level` 仍然决定用于无障碍的 HTML 元素。用于英雄横幅、营销标题和数据提示。',
+ description:
+ '展示类型变体。用展示级别的大小(更大、更轻的字重、更紧的行高)覆盖来自 `level` 的视觉样式。主题可以添加自定义视觉类型。`level` 仍然决定用于无障碍的 HTML 元素。用于英雄横幅、营销标题和数据提示。',
},
{
name: 'children',
@@ -115,7 +133,8 @@ export const docsZh = {
{
name: 'accessibilityLevel',
type: '1 | 2 | 3 | 4 | 5 | 6',
- description: '无障碍级别覆盖。当设置且与 `level` 不同时,应用 `aria-level` 使文档大纲与视觉样式不同。',
+ description:
+ '无障碍级别覆盖。当设置且与 `level` 不同时,应用 `aria-level` 使文档大纲与视觉样式不同。',
},
{
name: 'color',
@@ -126,25 +145,29 @@ export const docsZh = {
{
name: 'display',
type: "'inline' | 'block'",
- description: "显示类型。当 maxLines > 0 或 hasCapsize 为 true 时,会静默覆盖为 'block'。",
+ description:
+ "显示类型。当 maxLines > 0 或 hasCapsize 为 true 时,会静默覆盖为 'block'。",
default: "'block'",
},
{
name: 'maxLines',
type: 'number',
- description: '截断前的最大行数。0 表示不截断。设置后,如果内容被截断,悬停时会显示工具提示。',
+ description:
+ '截断前的最大行数。0 表示不截断。设置后,如果内容被截断,悬停时会显示工具提示。',
default: '0',
},
{
name: 'hasTruncateTooltip',
type: "boolean | 'above' | 'below' | 'start' | 'end'",
- description: "控制截断文本的工具提示行为。true 在默认位置显示工具提示,false 禁用它,或者放置字符串 ('above' | 'below' | 'start' | 'end') 设置特定位置。",
+ description:
+ "控制截断文本的工具提示行为。true 在默认位置显示工具提示,false 禁用它,或者放置字符串 ('above' | 'below' | 'start' | 'end') 设置特定位置。",
default: 'true',
},
{
name: 'wordBreak',
type: "'break-word' | 'break-all'",
- description: "截断时的断词行为。单行截断默认为 'break-all',其他情况默认为 'break-word'。",
+ description:
+ "截断时的断词行为。单行截断默认为 'break-all',其他情况默认为 'break-word'。",
},
{
name: 'textWrap',
@@ -154,7 +177,8 @@ export const docsZh = {
{
name: 'justify',
type: "'start' | 'center' | 'end'",
- description: '文本对齐(两端对齐)。使用逻辑值(start/end)以兼容 i18n/RTL。',
+ description:
+ '文本对齐(两端对齐)。使用逻辑值(start/end)以兼容 i18n/RTL。',
default: "'start'",
},
{
@@ -180,19 +204,27 @@ export const docsZh = {
export const docsDense = {
name: 'Heading',
displayName: 'Heading',
- description: 'Semantic h1–6 w/ themed styling, themed sizing via type scale tokens, line-clamp truncation.',
+ description:
+ 'Semantic h1–6 w/ themed styling, themed sizing via type scale tokens, line-clamp truncation.',
propDescriptions: {
- level: 'Heading level; determines HTML element + styling from theme (unless type is set).',
- type: 'Display variant (display-1/2/3); overrides visual styling from level with display-scale sizing.',
+ 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.',
children: 'Heading content.',
- accessibilityLevel: 'aria-level override when different from level for document outline.',
+ accessibilityLevel:
+ 'aria-level override when different from level for document outline.',
color: 'Text color. Themes may add custom colors.',
- display: "Display type; overridden to 'block' when maxLines>0 or hasCapsize.",
- maxLines: 'Max lines before truncation; 0=none. Shows tooltip if truncated.',
- hasTruncateTooltip: "Tooltip for truncated text; true=default position, false=disabled, or a placement ('above' | 'below' | 'start' | 'end').",
- wordBreak: "Word break behavior; defaults 'break-all' for single-line, 'break-word' otherwise.",
+ display:
+ "Display type; overridden to 'block' when maxLines>0 or hasCapsize.",
+ maxLines:
+ 'Max lines before truncation; 0=none. Shows tooltip if truncated.',
+ hasTruncateTooltip:
+ "Tooltip for truncated text; true=default position, false=disabled, or a placement ('above' | 'below' | 'start' | 'end').",
+ wordBreak:
+ "Word break behavior; defaults 'break-all' for single-line, 'break-word' otherwise.",
textWrap: 'Text wrapping behavior.',
- justify: "Text alignment (justification); logical values 'start' | 'center' | 'end' for RTL.",
+ justify:
+ "Text alignment (justification); logical values 'start' | 'center' | 'end' for RTL.",
hasCapsize: 'Optical alignment via text-box-trim; forces block display.',
hasStrikethrough: 'Strikethrough text decoration.',
id: 'HTML id attribute.',
diff --git a/packages/core/src/Text/index.ts b/packages/core/src/Text/index.ts
index 5862de5160..3c9f430bae 100644
--- a/packages/core/src/Text/index.ts
+++ b/packages/core/src/Text/index.ts
@@ -44,6 +44,7 @@ export {
type HeadingProps,
type HeadingLevel,
type HeadingType,
+ type HeadingTypeMap,
} from '../Heading';
// Re-export shared types from theme for convenience
diff --git a/packages/core/src/theme/extensibleAxes.test.ts b/packages/core/src/theme/extensibleAxes.test.ts
index f68221d06b..85af3ccb2b 100644
--- a/packages/core/src/theme/extensibleAxes.test.ts
+++ b/packages/core/src/theme/extensibleAxes.test.ts
@@ -35,7 +35,7 @@
*/
import {describe, it, expect} from 'vitest';
-import {readdirSync, readFileSync, existsSync} from 'node:fs';
+import {readdirSync, readFileSync} from 'node:fs';
import {join, relative} from 'node:path';
import ts from 'typescript';
import {stableClassName} from '../naming';
@@ -277,13 +277,18 @@ function collectDocTargets(dir: string): Map<string, DocTarget[]> {
}
walk(full);
} else if (entry.name.endsWith('.doc.mjs')) {
- const componentDir = relative(SRC_DIR, full).split('/')[0];
+ const fallbackDir = relative(SRC_DIR, full).split('/')[0];
let doc;
try {
doc = require(full).docs;
} catch {
continue;
}
+ // Subcomponent docs can live in their parent's directory (for example,
+ // Text/Heading.doc.mjs). Attribute them to the component they document,
+ // not merely the first path segment.
+ const componentDir =
+ typeof doc?.name === 'string' ? doc.name : fallbackDir;
const targets = (doc?.theming?.targets ?? [])
.filter(
(t: unknown): t is {className: string} =>