Skip to content

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

TypeScript

fix(theme): document heading's type target and stop teaching a var that does not exist (#5016)

Cindy Zhang1ce0b4c7fa9a
diff --git a/.changeset/heading-type-theming-target.md b/.changeset/heading-type-theming-target.md
new file mode 100644
index 0000000000..e28722a6db
--- /dev/null
+++ b/.changeset/heading-type-theming-target.md
@@ -0,0 +1,12 @@
+---
+'@astryxdesign/core': patch
+'@astryxdesign/cli': patch
+---
+
+[fix] Heading's `type` is a documented theming target, and the docs stop teaching a CSS variable that does not exist.
+
+`Heading` reflects `type` as a theme selector — `typography.scale` generates `heading: {'type:display-1' …}` rules for it — but `theming.targets` listed only `level` and `color`, so `astryx theme build` warned `Unknown prop "type" on component "heading"` on every theme that sets a type scale, including the shipped `neutralTheme`. The drift guard missed it twice over: it read a conditional spread (`{level, color, ...(type && {type})}`) as an unknown bag, and it only checked a component against a doc file in its own directory, so `Heading/` — documented from `Text/Text.doc.mjs` — was never checked at all. Both are fixed, which brings three more previously unchecked directories under the guard.
+
+Separately, the theme docs' component-override example set `--button-press-scale`, which no component defines: copying it produces CSS that silently never applies. It now sets a real public var, and the example no longer declares the same `button` key twice.
+
+@cixzhang
diff --git a/packages/cli/api/theme/build/build.test.mjs b/packages/cli/api/theme/build/build.test.mjs
index 905226a8c3..31b957db58 100644
--- a/packages/cli/api/theme/build/build.test.mjs
+++ b/packages/cli/api/theme/build/build.test.mjs
@@ -254,6 +254,28 @@ describe('themeBuild() — component override validation', () => {
expect(result?.data.warnings).toEqual([]);
});
+ it('accepts the heading type rules a type scale generates', async () => {
+ // `typography.scale` makes defineTheme emit `heading: {'type:display-1' …}`
+ // (Heading renders a `type:` class alongside `level:`), so any theme with a
+ // type scale carried override keys the validator called unknown — including
+ // the shipped neutralTheme.
+ const themeFile = path.join(tmpDir, 'typescale.mjs');
+ fs.writeFileSync(
+ themeFile,
+ `export default {
+ name: 'typescale',
+ tokens: {'--color-bg': '#0a0a0a'},
+ components: {
+ heading: {'type:display-1': {letterSpacing: '0.01em'}},
+ },
+ };\n`,
+ );
+
+ const result = await themeBuild('typescale.mjs', {}, {cwd: tmpDir});
+
+ expect(result?.data.warnings).toEqual([]);
+ });
+
it('still warns on a key that is neither a visual prop nor a state', async () => {
// Widening the known set to states must not turn the guard off.
const themeFile = path.join(tmpDir, 'bogus.mjs');
diff --git a/packages/cli/assets/docs/theme.doc.dense.mjs b/packages/cli/assets/docs/theme.doc.dense.mjs
index f90cc68d52..6a20b78928 100644
--- a/packages/cli/assets/docs/theme.doc.dense.mjs
+++ b/packages/cli/assets/docs/theme.doc.dense.mjs
@@ -10,7 +10,7 @@ export const docsDense = {
{ section: 'Theme Props', title: 'Props', content: [null] },
{ section: 'Creating a Custom Theme', title: 'Custom Theme', content: [{ type: 'prose', text: 'CLI wizard or manual defineTheme. only override tokens that differ.' }, null] },
{ section: 'defineTheme', title: 'defineTheme', content: [{ type: 'prose', text: 'scale configs (color, typography, radius, motion) + explicit token overrides + component overrides. color derives full palette from accent hex via HCT.' }, null, null] },
- { section: 'Component Style Overrides', title: 'Component Overrides', content: [{ type: 'prose', text: 'components field uses semantic component keys + style keys (base, variant:value, stateName), not raw selectors. for external CSS, prefer data-* selectors from `astryx docs styling`. write standard CSS (borderRadius, padding) — pipeline expands to internal vars. public vars (--button-press-scale etc) set directly. private vars (--_*) cannot be set — use CSS properties. run `astryx component <Name>` for details.' }, null, null, null, null] },
+ { section: 'Component Style Overrides', title: 'Component Overrides', content: [{ type: 'prose', text: 'components field uses semantic component keys + style keys (base, variant:value, stateName), not raw selectors. for external CSS, prefer data-* selectors from `astryx docs styling`. write standard CSS (borderRadius, padding) — pipeline expands to internal vars. public vars (--button-focus-offset etc) set directly. private vars (--_*) cannot be set — use CSS properties. run `astryx component <Name>` for details.' }, null, null, null, null] },
{ section: 'Custom Variants', title: 'Custom Variants', content: [{ type: 'prose', text: 'any unknown prop:value in components becomes a new variant. astryx theme build generates TS augmentations. works on any extensible prop axis (variant, status, etc).' }, null, null, null, null] },
{ section: 'Building Themes for Production', title: 'Build for Production', content: [{ type: 'prose', text: 'astryx theme build compiles defineTheme to static CSS. outputs .css + .js (__built:true) + .d.ts.' }, null, null, null, null] },
{ section: 'Runtime vs Built Themes', title: 'Runtime vs Built', content: [{ type: 'prose', text: 'runtime: useInsertionEffect injects styles client-side. built: static CSS on first paint. USE /built + theme.css FOR SSR.' }, null, null, null] },
diff --git a/packages/cli/assets/docs/theme.doc.mjs b/packages/cli/assets/docs/theme.doc.mjs
index f2b8e509c3..9a08a62619 100644
--- a/packages/cli/assets/docs/theme.doc.mjs
+++ b/packages/cli/assets/docs/theme.doc.mjs
@@ -275,14 +275,17 @@ const brandTheme = defineTheme({
base: { borderRadius: '20px', padding: '24px' },
},
button: {
- base: { borderRadius: '9999px', textTransform: 'uppercase' },
+ base: {
+ borderRadius: '9999px',
+ textTransform: 'uppercase',
+ // Some components have public CSS vars for properties that don't map
+ // to standard CSS. Set these directly. Take the name from
+ // \`astryx component <Name>\` — a var the component does not define
+ // compiles to CSS that never applies.
+ '--button-focus-offset': '3px',
+ },
'variant:ghost': { borderWidth: '2px', borderStyle: 'solid' },
},
- // Some components have public CSS vars for properties that don't map
- // to standard CSS. Set these directly.
- button: {
- base: { '--button-press-scale': 'scale(0.95)' },
- },
}`,
},
{
diff --git a/packages/cli/authoring/doctypes/base/type.ts b/packages/cli/authoring/doctypes/base/type.ts
index 5275c8097d..ae23938c5f 100644
--- a/packages/cli/authoring/doctypes/base/type.ts
+++ b/packages/cli/authoring/doctypes/base/type.ts
@@ -339,7 +339,7 @@ export interface ComponentThemingTarget {
* ```
*/
export interface ComponentThemingVar {
- /** CSS custom property name, e.g. '--_card-radius' or '--button-press-scale' */
+ /** CSS custom property name, e.g. '--_card-radius' or '--button-focus-offset' */
name: string;
/** What this var controls */
description: string;
diff --git a/packages/core/src/Text/Text.doc.mjs b/packages/core/src/Text/Text.doc.mjs
index c903ed451d..89d3c654cc 100644
--- a/packages/core/src/Text/Text.doc.mjs
+++ b/packages/core/src/Text/Text.doc.mjs
@@ -15,7 +15,7 @@ export const docs = {
},
theming: {
targets: [
- {className: 'astryx-heading', visualProps: ['level', 'color']},
+ {className: 'astryx-heading', visualProps: ['level', 'color', 'type']},
{className: 'astryx-text', visualProps: ['type', 'size', 'color']},
],
},
diff --git a/packages/core/src/theme/themingTargets.test.ts b/packages/core/src/theme/themingTargets.test.ts
index f5aeb6a0d5..11ba11453a 100644
--- a/packages/core/src/theme/themingTargets.test.ts
+++ b/packages/core/src/theme/themingTargets.test.ts
@@ -26,7 +26,7 @@
import {describe, it, expect} from 'vitest';
import {readdirSync, readFileSync} from 'node:fs';
-import {join} from 'node:path';
+import {join, relative} from 'node:path';
import ts from 'typescript';
import {stableClassName} from '../naming';
@@ -45,6 +45,61 @@ interface ThemeTargetSite {
isOpaque: boolean;
}
+/**
+ * Keys of a spread whose operand is a conditional object literal:
+ * `...(cond && {a})`, `...(cond ? {a} : null)`, `...(cond || {a})`.
+ * Returns null when the operand is anything else (a bag like `...rest`, or an
+ * object with a computed key), which the caller treats as opaque.
+ */
+function conditionalSpreadKeys(expression: ts.Expression): string[] | null {
+ const unwrap = (node: ts.Expression): ts.Expression =>
+ ts.isParenthesizedExpression(node) ? unwrap(node.expression) : node;
+
+ const expr = unwrap(expression);
+ const branches: ts.Expression[] = [];
+ if (
+ ts.isBinaryExpression(expr) &&
+ (expr.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ||
+ expr.operatorToken.kind === ts.SyntaxKind.BarBarToken)
+ ) {
+ branches.push(expr.right);
+ } else if (ts.isConditionalExpression(expr)) {
+ branches.push(expr.whenTrue, expr.whenFalse);
+ } else if (ts.isObjectLiteralExpression(expr)) {
+ branches.push(expr);
+ } else {
+ return null;
+ }
+
+ const keys: string[] = [];
+ for (const branch of branches) {
+ const object = unwrap(branch);
+ // A falsy filler arm (`null`, `undefined`) contributes no keys; anything
+ // else that is not an object literal hides its keys, so give up.
+ if (
+ object.kind === ts.SyntaxKind.NullKeyword ||
+ (ts.isIdentifier(object) && object.text === 'undefined')
+ ) {
+ continue;
+ }
+ if (!ts.isObjectLiteralExpression(object)) {
+ return null;
+ }
+ for (const prop of object.properties) {
+ const name = prop.name;
+ if (
+ name != null &&
+ (ts.isIdentifier(name) || ts.isStringLiteralLike(name))
+ ) {
+ keys.push(name.text);
+ } else {
+ return null;
+ }
+ }
+ }
+ return keys;
+}
+
/**
* Extract every `themeProps('name', {...})` call from a source file.
*
@@ -88,8 +143,16 @@ function extractThemeTargets(
if (ts.isObjectLiteralExpression(propsArg)) {
for (const prop of propsArg.properties) {
if (ts.isSpreadAssignment(prop)) {
- // {...rest} — keys unknown at parse time.
- site.isOpaque = true;
+ // A conditional spread of an object literal — `...(type &&
+ // {type})` — has statically known keys. Treating it as opaque
+ // is how `astryx-heading`'s `type` stayed undocumented: the
+ // same drift this file exists to catch (#3652, #3680).
+ const spreadKeys = conditionalSpreadKeys(prop.expression);
+ if (spreadKeys == null) {
+ site.isOpaque = true;
+ } else {
+ site.propKeys.push(...spreadKeys);
+ }
continue;
}
const name = prop.name;
@@ -194,12 +257,35 @@ describe('extractThemeTargets', () => {
]);
});
+ it('reads the keys of a conditional spread', () => {
+ // Heading's real call site: `{level, color, ...(type && {type})}`.
+ const [site] = extractThemeTargets(
+ `themeProps('heading', {level, color, ...(type && {type})})`,
+ );
+ expect(site.propKeys).toEqual(['level', 'color', 'type']);
+ expect(site.isOpaque).toBe(false);
+ });
+
+ it('reads both arms of a ternary spread', () => {
+ const [site] = extractThemeTargets(
+ `themeProps('card', {...(isOpen ? {expanded} : {collapsed})})`,
+ );
+ expect(site.propKeys).toEqual(['expanded', 'collapsed']);
+ expect(site.isOpaque).toBe(false);
+ });
+
it('marks a spread props bag opaque rather than guessing its keys', () => {
const [site] = extractThemeTargets(`themeProps('card', {...rest})`);
expect(site.isOpaque).toBe(true);
expect(site.propKeys).toEqual([]);
});
+ it('marks a conditional spread of a non-literal opaque', () => {
+ const [site] = extractThemeTargets(`themeProps('card', {...(on && rest)})`);
+ expect(site.isOpaque).toBe(true);
+ expect(site.propKeys).toEqual([]);
+ });
+
it('marks a non-literal props bag opaque', () => {
const [site] = extractThemeTargets(`themeProps('card', visualProps)`);
expect(site.isOpaque).toBe(true);
@@ -231,7 +317,37 @@ interface ComponentInfo {
dir: string;
sites: ThemeTargetSite[];
/** The doc blocks that carry theming.targets, by the key they live under. */
- docBlocks: {key: 'docs' | 'docsZh'; targets: DocTarget[]}[];
+ docBlocks: {key: 'docs' | 'docsZh'; file: string; targets: DocTarget[]}[];
+}
+
+/**
+ * Every `*.doc.mjs` under src that declares a theming target for one of
+ * `classNames`. Lets a component be checked against the doc that documents it,
+ * wherever that file lives.
+ *
+ * Reads the file as text rather than requiring it: this runs for directories
+ * that have no doc of their own, so most candidates are misses.
+ */
+function docFilesDocumenting(classNames: Set<string>): string[] {
+ const matches: string[] = [];
+ const walk = (dir: string): void => {
+ for (const entry of readdirSync(dir, {withFileTypes: true})) {
+ const p = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ walk(p);
+ } else if (entry.name.endsWith('.doc.mjs')) {
+ const source = readFileSync(p, 'utf-8');
+ for (const className of classNames) {
+ if (source.includes(`'${className}'`)) {
+ matches.push(p);
+ break;
+ }
+ }
+ }
+ }
+ };
+ walk(SRC_DIR);
+ return matches;
}
function discoverComponents(): ComponentInfo[] {
@@ -262,27 +378,37 @@ function discoverComponents(): ComponentInfo[] {
continue;
}
- // Match the on-disk listing rather than existsSync: on case-insensitive
- // filesystems existsSync would match a differently-cased doc file that CI
- // never checks. (Same guard as derivedVarRegistry.test.ts.)
- if (!dirEntries.includes(`${dir}.doc.mjs`)) {
- continue;
- }
-
- let mod: ComponentDocModule;
- try {
- mod = require(join(dirPath, `${dir}.doc.mjs`)) as ComponentDocModule;
- } catch {
+ // A component's doc file usually sits beside its source, but not always:
+ // `Heading/Heading.tsx` is documented by `Text/Text.doc.mjs`. Requiring a
+ // same-directory doc silently exempted every such component — Heading
+ // among them. Fall back to whichever doc file documents the classes this
+ // directory renders.
+ //
+ // Both paths match the on-disk listing rather than existsSync: on
+ // case-insensitive filesystems existsSync would match a differently-cased
+ // doc file that CI never checks. (Same guard as derivedVarRegistry.test.ts.)
+ const docFiles = dirEntries.includes(`${dir}.doc.mjs`)
+ ? [join(dirPath, `${dir}.doc.mjs`)]
+ : docFilesDocumenting(new Set(sites.map(s => s.className)));
+ if (docFiles.length === 0) {
continue;
}
const docBlocks: ComponentInfo['docBlocks'] = [];
- for (const key of ['docs', 'docsZh'] as const) {
- const targets = mod[key]?.theming?.targets;
- // Only blocks that already document a theming surface are held to it —
- // a doc with no theming block at all is a separate (documentation) gap.
- if (targets != null) {
- docBlocks.push({key, targets});
+ for (const docFile of docFiles) {
+ let mod: ComponentDocModule;
+ try {
+ mod = require(docFile) as ComponentDocModule;
+ } catch {
+ continue;
+ }
+ for (const key of ['docs', 'docsZh'] as const) {
+ const targets = mod[key]?.theming?.targets;
+ // Only blocks that already document a theming surface are held to it —
+ // a doc with no theming block at all is a separate (documentation) gap.
+ if (targets != null) {
+ docBlocks.push({key, file: relative(SRC_DIR, docFile), targets});
+ }
}
}
if (docBlocks.length === 0) {
@@ -309,22 +435,22 @@ describe('theming.targets matches the themeProps() call sites', () => {
for (const {dir, sites, docBlocks} of components) {
const renderedClasses = [...new Set(sites.map(s => s.className))].sort();
- for (const {key, targets} of docBlocks) {
+ for (const {key, file, targets} of docBlocks) {
const documented = new Set(targets.map(t => t.className));
- it(`${dir} (${key}): every rendered class is documented`, () => {
+ it(`${dir} (${file} ${key}): every rendered class is documented`, () => {
const undocumented = renderedClasses.filter(c => !documented.has(c));
expect(
undocumented,
`${dir} renders ${undocumented.length} astryx-* class(es) that ` +
- `${dir}.doc.mjs ${key}.theming.targets does not document: ` +
+ `${file} ${key}.theming.targets does not document: ` +
`${undocumented.join(', ')}. An undocumented class is an ` +
`unthemeable element — theme authors and codegen read targets[] ` +
`to learn which selectors exist. Add {className: '...'} entries.`,
).toEqual([]);
});
- it(`${dir} (${key}): every visual prop passed to themeProps is documented`, () => {
+ it(`${dir} (${file} ${key}): every visual prop passed to themeProps is documented`, () => {
const missing: string[] = [];
for (const site of sites) {
const target = targets.find(t => t.className === site.className);
@@ -343,7 +469,7 @@ describe('theming.targets matches the themeProps() call sites', () => {
}
expect(
[...new Set(missing)],
- `${dir} passes prop keys to themeProps() that ${dir}.doc.mjs ` +
+ `${dir} passes prop keys to themeProps() that ${file} ` +
`${key}.theming.targets does not list under visualProps/states. ` +
`Each one is a [data-*] selector consumers cannot discover.`,
).toEqual([]);