@astryxdesign/cli 0.7.5-canary.67dc45f → 0.7.5-canary.6906beb

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/api/template/tokenizer-showcase.test.mjs +47 -0
  2. package/api/theme/build/build.adaptation-enrollment.test.mjs +4 -0
  3. package/api/theme/build/build.icon-entry-variants.test.mjs +134 -0
  4. package/api/theme/build/build.icon-variants.test.mjs +105 -0
  5. package/api/theme/build/build.mjs +134 -75
  6. package/api/theme/build/build.test.mjs +77 -0
  7. package/assets/codemods/transforms/next/__tests__/migrate-codeblock-tokenizer-to-language.test.mjs +130 -0
  8. package/assets/codemods/transforms/next/index.mjs +11 -1
  9. package/assets/codemods/transforms/next/migrate-codeblock-tokenizer-to-language.mjs +315 -0
  10. package/assets/docs/author-a-theme.doc.mjs +3 -1
  11. package/assets/docs/icons.doc.mjs +82 -1
  12. package/assets/docs/theme.doc.dense.mjs +8 -0
  13. package/assets/docs/theme.doc.mjs +16 -0
  14. package/assets/docs/theme.doc.zh.mjs +11 -0
  15. package/assets/docs/tree/template-styles.doc.mjs +1 -1
  16. package/assets/docs/tree/tokens-color.doc.mjs +145 -1
  17. package/assets/docs/tree/tokens.doc.mjs +1 -1
  18. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjs +6 -4
  19. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.tsx +61 -55
  20. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.doc.mjs +6 -4
  21. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.tsx +68 -37
  22. package/assets/templates/blocks/components/Thumbnail/ThumbnailDisabled.doc.mjs +1 -1
  23. package/assets/templates/blocks/components/Tokenizer/TokenizerShowcase.tsx +13 -6
  24. package/assets/templates/pages/dashboard-alert-rail/page.tsx +3 -3
  25. package/assets/templates/pages/table-comparison/page.tsx +12 -3
  26. package/assets/templates/themes/butter/butterPaletteRefs.generated.ts +3 -2
  27. package/assets/templates/themes/butter/butterTheme.ts +47 -44
  28. package/assets/templates/themes/chocolate/chocolateTheme.ts +15 -2
  29. package/assets/templates/themes/gothic/gothicTheme.ts +21 -16
  30. package/assets/templates/themes/matcha/matchaPaletteRefs.generated.ts +1 -1
  31. package/assets/templates/themes/matcha/matchaTheme.ts +15 -2
  32. package/assets/templates/themes/neutral/neutralPaletteRefs.generated.ts +4 -4
  33. package/assets/templates/themes/neutral/neutralTheme.ts +24 -119
  34. package/assets/templates/themes/stone/stoneTheme.ts +46 -21
  35. package/assets/templates/themes/y2k/y2kTheme.ts +20 -16
  36. package/assets/theme.template.ts +18 -5
  37. package/clients/cli/commands/build-theme.adaptations.test.mjs +110 -0
  38. package/clients/cli/commands/build-theme.outside-project.test.mjs +140 -0
  39. package/foundation/agent-docs/agent-docs.mjs +1 -0
  40. package/foundation/agent-docs/agent-docs.test.mjs +5 -0
  41. package/foundation/doc-compiler/doc-loads.test.mjs +2 -6
  42. package/package.json +9 -9
@@ -27,6 +27,7 @@ import {
27
27
  import {
28
28
  themeBuild,
29
29
  validateComponentOverridesAgainstRegistry,
30
+ validateThemePrivateInputs,
30
31
  } from './build.mjs';
31
32
 
32
33
  // `themeBuild` captures core's generator once at module load. Wrap the two
@@ -212,6 +213,55 @@ describe('themeBuild() — receipt', () => {
212
213
  });
213
214
  });
214
215
 
216
+ describe.each(['mjs', 'ts'])('a .%s theme module with no theme export', ext => {
217
+ beforeEach(() => {
218
+ fs.writeFileSync(
219
+ path.join(tmpDir, `none.${ext}`),
220
+ 'export const notATheme = 42;\n',
221
+ );
222
+ });
223
+
224
+ it('fails the build as a module that does not load a theme', async () => {
225
+ const build = themeBuild(`none.${ext}`, {}, {cwd: tmpDir});
226
+ await expect(build).rejects.toThrow(
227
+ /Could not find a defineTheme\(\) result/,
228
+ );
229
+ await expect(build).rejects.toMatchObject({code: 'ERR_THEME_LOAD'});
230
+ });
231
+
232
+ it("fails doctor's private-input check the same way, rather than read its exports as a theme", async () => {
233
+ await expect(
234
+ validateThemePrivateInputs(`none.${ext}`, {cwd: tmpDir}),
235
+ ).rejects.toThrow(/Could not find a defineTheme\(\) result/);
236
+ });
237
+ });
238
+
239
+ describe('themeBuild() — a theme module that does not load', () => {
240
+ it('fails with the import error, rather than build the theme from the file text', async () => {
241
+ fs.writeFileSync(
242
+ path.join(tmpDir, 'unresolved.mjs'),
243
+ "import './missing-helper.mjs';\nexport default {name: 'unresolved', tokens: {'--color-bg': '#000'}};\n",
244
+ );
245
+ await expect(
246
+ themeBuild('unresolved.mjs', {}, {cwd: tmpDir}),
247
+ ).rejects.toThrow(
248
+ /Failed to load theme from .*unresolved\.mjs: .*missing-helper\.mjs/s,
249
+ );
250
+ expect(fs.existsSync(path.join(tmpDir, 'unresolved.css'))).toBe(false);
251
+ });
252
+
253
+ it('fails with the error the module throws, rather than build the theme from the file text', async () => {
254
+ fs.writeFileSync(
255
+ path.join(tmpDir, 'throws.mjs'),
256
+ "throw new Error('the theme module failed');\nexport default {name: 'throws', tokens: {'--color-bg': '#000'}};\n",
257
+ );
258
+ await expect(themeBuild('throws.mjs', {}, {cwd: tmpDir})).rejects.toThrow(
259
+ /the theme module failed/,
260
+ );
261
+ expect(fs.existsSync(path.join(tmpDir, 'throws.css'))).toBe(false);
262
+ });
263
+ });
264
+
215
265
  describe('themeBuild() — dropped declarations reach the receipt', () => {
216
266
  // Core's generator refuses a declaration whose value would end it early
217
267
  // (an unquoted `;` or brace, an unclosed string/comment/url). The runtime
@@ -599,6 +649,33 @@ describe('themeBuild() — component override validation', () => {
599
649
  });
600
650
  });
601
651
 
652
+ describe('themeBuild() — Icon size dimensions', () => {
653
+ it('writes width and height on an icon size into the vars the glyph reads, with no warnings', async () => {
654
+ // spec:AST-087 FR10: a built theme sets an Icon size's glyph dimension the
655
+ // way the runtime provider does, through the shared compiler's derived
656
+ // vars. Raw width/height would lose to a consumer's unlayered StyleX.
657
+ const themeFile = path.join(tmpDir, 'iconsizes.mjs');
658
+ fs.writeFileSync(
659
+ themeFile,
660
+ `export default {
661
+ name: 'iconsizes',
662
+ tokens: {'--color-bg': '#0a0a0a'},
663
+ components: {icon: {'size:sm': {width: '18px', height: '22px'}}},
664
+ };\n`,
665
+ );
666
+
667
+ const result = await themeBuild('iconsizes.mjs', {}, {cwd: tmpDir});
668
+
669
+ expect(result?.data.warnings).toEqual([]);
670
+ const css = fs.readFileSync(path.join(tmpDir, 'iconsizes.css'), 'utf8');
671
+ const rule =
672
+ css.match(/\.astryx-icon\[data-size="sm"\]\s*\{([^}]*)\}/)?.[1] ?? '';
673
+ expect(rule).toMatch(/--_icon-width:\s*18px/);
674
+ expect(rule).toMatch(/--_icon-height:\s*22px/);
675
+ expect(rule).not.toMatch(/(^|[\s;])(width|height)\s*:/);
676
+ });
677
+ });
678
+
602
679
  describe('themeBuild() — the shipped theme template', () => {
603
680
  // `assets/theme.template.ts` is what `astryx theme template` puts in a
604
681
  // consumer's project. It is the one theme file we hand out, so it has to
@@ -0,0 +1,130 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ import {describe, expect, it} from 'vitest';
4
+ import transform from '../migrate-codeblock-tokenizer-to-language.mjs';
5
+
6
+ async function applyTransform(source) {
7
+ const jscodeshift = (await import('jscodeshift')).default;
8
+ const j = jscodeshift.withParser('tsx');
9
+ const api = {jscodeshift: j, stats: () => {}, report: () => {}};
10
+ return transform({source, path: 'test.tsx'}, api) ?? source;
11
+ }
12
+
13
+ /** Collapse whitespace so assertions ignore the printer's line breaks. */
14
+ const flat = text => text.replace(/\s+/g, ' ');
15
+
16
+ describe('migrate-codeblock-tokenizer-to-language', () => {
17
+ it('rewrites tokenizer beside a static language to a custom language', async () => {
18
+ const output = flat(
19
+ await applyTransform(`import {CodeBlock} from '@astryxdesign/core/CodeBlock';
20
+ const a = <CodeBlock code={src} language="zig" tokenizer={zigTokens} />;
21
+ const b = <CodeBlock code={src} language={'nim'} tokenizer={(c) => tokens(c)} />;`),
22
+ );
23
+
24
+ expect(output).not.toContain('tokenizer=');
25
+ expect(output).toContain(
26
+ "import { CodeBlock, createCodeLanguage } from '@astryxdesign/core/CodeBlock';",
27
+ );
28
+ expect(output).toContain(
29
+ "language={zigTokens ? createCodeLanguage({ name: 'zig', identifiers: ['zig'], tokenize: zigTokens }) : 'zig'}",
30
+ );
31
+ expect(output).toContain(
32
+ "language={createCodeLanguage({ name: 'nim', identifiers: ['nim'], tokenize: (c) => tokens(c) })}",
33
+ );
34
+ });
35
+
36
+ it('adds the import beside a root-package import and follows aliases', async () => {
37
+ const output = flat(
38
+ await applyTransform(`import {CodeBlock as Code} from '@astryxdesign/core';
39
+ const a = <Code code={src} language="zig" tokenizer={zigTokens} />;`),
40
+ );
41
+
42
+ expect(output).toContain(
43
+ "import { createCodeLanguage } from '@astryxdesign/core/CodeBlock';",
44
+ );
45
+ expect(output).toContain("createCodeLanguage({ name: 'zig'");
46
+ });
47
+
48
+ it('adds a separate import beside a namespace import', async () => {
49
+ const output =
50
+ await applyTransform(`import * as CB from '@astryxdesign/core/CodeBlock';
51
+ const a = <CB.CodeBlock code={src} language="zig" tokenizer={zigTokens} />;`);
52
+ expect(output).toContain(
53
+ "import * as CB from '@astryxdesign/core/CodeBlock';",
54
+ );
55
+ expect(flat(output)).toContain(
56
+ "import { createCodeLanguage } from '@astryxdesign/core/CodeBlock';",
57
+ );
58
+ const jscodeshift = (await import('jscodeshift')).default;
59
+ expect(() => jscodeshift.withParser('tsx')(output)).not.toThrow();
60
+ });
61
+
62
+ it('guards a name or property that may be undefined', async () => {
63
+ const output = flat(
64
+ await applyTransform(`import {CodeBlock} from '@astryxdesign/core/CodeBlock';
65
+ const a = <CodeBlock code={src} language="zig" tokenizer={props.tokenizer} />;`),
66
+ );
67
+ expect(output).toContain(
68
+ "language={props.tokenizer ? createCodeLanguage({ name: 'zig', identifiers: ['zig'], tokenize: props.tokenizer }) : 'zig'}",
69
+ );
70
+ });
71
+
72
+ it('imports under a free alias when the file binds the name already', async () => {
73
+ const fromLocal = flat(
74
+ await applyTransform(`import {CodeBlock} from '@astryxdesign/core/CodeBlock';
75
+ import {createCodeLanguage} from './my-languages';
76
+ const a = <CodeBlock code={src} language="zig" tokenizer={(c) => t(c)} />;`),
77
+ );
78
+ expect(fromLocal).toContain(
79
+ "import { CodeBlock, createCodeLanguage as createCodeLanguage2 } from '@astryxdesign/core/CodeBlock';",
80
+ );
81
+ expect(fromLocal).toContain(
82
+ "import {createCodeLanguage} from './my-languages';",
83
+ );
84
+ expect(fromLocal).toContain("language={createCodeLanguage2({ name: 'zig'");
85
+
86
+ const fromFunction = flat(
87
+ await applyTransform(`import {CodeBlock} from '@astryxdesign/core/CodeBlock';
88
+ function createCodeLanguage() {}
89
+ const a = <CodeBlock code={src} language="zig" tokenizer={(c) => t(c)} />;`),
90
+ );
91
+ expect(fromFunction).toContain('createCodeLanguage as createCodeLanguage2');
92
+ const jscodeshift = (await import('jscodeshift')).default;
93
+ const parse = jscodeshift.withParser('tsx');
94
+ expect(() => parse(fromLocal)).not.toThrow();
95
+ });
96
+
97
+ it('reports a tokenizer value it cannot read twice, naming the tokenizer', async () => {
98
+ const output =
99
+ await applyTransform(`import {CodeBlock} from '@astryxdesign/core/CodeBlock';
100
+ const a = <CodeBlock code={src} language="zig" tokenizer={registry.get('zig').tokenize} />;
101
+ const b = <CodeBlock code={src} language="zig" tokenizer={enabled ? t : undefined} />;`);
102
+ expect(output.match(/this tokenizer value is computed/g)).toHaveLength(2);
103
+ expect(output).not.toContain('the language here is computed');
104
+ expect(output).toContain("tokenizer={registry.get('zig').tokenize}");
105
+ });
106
+
107
+ it('reports what it cannot prove and leaves it unchanged', async () => {
108
+ const source = `import {CodeBlock} from '@astryxdesign/core/CodeBlock';
109
+ const a = <CodeBlock code={src} language={lang} tokenizer={t} />;
110
+ const b = <CodeBlock code={src} tokenizer={t} />;
111
+ const c = <CodeBlock code={src} language="plaintext" tokenizer={t} />;
112
+ const d = <CodeBlock {...rest} code={src} language="zig" tokenizer={t} />;
113
+ const e = <CodeBlock code={src} language="zig" tokenizer={enabled ? t : undefined} />;
114
+ const f = <CodeBlock code={src} language="zig" tokenizer={enabled && t} />;`;
115
+ const output = await applyTransform(source);
116
+
117
+ expect(output.match(/TODO\(astryx upgrade\)/g)).toHaveLength(6);
118
+ expect(output.match(/tokenizer=\{t\}/g)).toHaveLength(4);
119
+ expect(output).toContain('tokenizer={enabled ? t : undefined}');
120
+ expect(output).toContain('tokenizer={enabled && t}');
121
+ expect(output).not.toMatch(/import \{[^}]*createCodeLanguage/);
122
+ expect(await applyTransform(output)).toBe(output);
123
+ });
124
+
125
+ it('leaves files without CodeBlock tokenizer alone', async () => {
126
+ const source = `import {CodeBlock} from '@astryxdesign/core/CodeBlock';
127
+ const a = <CodeBlock code={src} language="ts" />;`;
128
+ expect(await applyTransform(source)).toBe(source);
129
+ });
130
+ });
@@ -7,4 +7,14 @@
7
7
  * this file into the resolved version folder.
8
8
  */
9
9
 
10
- export default [];
10
+ import migrateCodeBlockTokenizerToLanguage, {
11
+ meta as migrateCodeBlockTokenizerToLanguageMeta,
12
+ } from './migrate-codeblock-tokenizer-to-language.mjs';
13
+
14
+ export default [
15
+ {
16
+ name: 'migrate-codeblock-tokenizer-to-language',
17
+ transform: migrateCodeBlockTokenizerToLanguage,
18
+ meta: migrateCodeBlockTokenizerToLanguageMeta,
19
+ },
20
+ ];
@@ -0,0 +1,315 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Codemod: migrate CodeBlock tokenizer to a custom language value
5
+ *
6
+ * `tokenizer={fn}` beside a static `language="x"` other than `plaintext`
7
+ * becomes `language={createCodeLanguage({name: 'x', identifiers: ['x'],
8
+ * tokenize: fn})}` (`component:CodeBlock` FR13). The custom language paints
9
+ * with the same function, labels `x`, and reflects `data-language="x"`, so the
10
+ * block looks the same. `createCodeLanguage` is imported from
11
+ * `@astryxdesign/core/CodeBlock` when the file does not import it yet, under
12
+ * a free alias when the file already binds the name to something else. A
13
+ * `tokenizer` that is a name or a call-free property may be undefined at run
14
+ * time, so it is guarded: `fn ? createCodeLanguage({...}) : 'x'`.
15
+ *
16
+ * Built on the shared `transformProp` helper, so it does not follow
17
+ * variables, helpers, wrappers, or types. Where a CodeBlock writes
18
+ * `tokenizer` but the codemod cannot prove the result, it keeps the old prop
19
+ * and leaves a TODO instead of guessing: a computed or missing `language`, a
20
+ * `tokenizer` value that is neither a function literal nor a name or property
21
+ * (a name or property is guarded with `fn ? createCodeLanguage(...) : 'x'`,
22
+ * since it may be undefined), a
23
+ * `plaintext` language (which shows no label today, while a language value
24
+ * does), and any CodeBlock that also spreads props. The deprecated prop keeps
25
+ * working there. Comments are the codemod's only report channel, and each is
26
+ * added once, so a second run changes nothing.
27
+ */
28
+
29
+ import {transformProp} from '../../transform-prop.mjs';
30
+
31
+ export const meta = {
32
+ title: 'Migrate CodeBlock tokenizer to a custom language',
33
+ description:
34
+ 'Replaces `tokenizer={fn}` beside a static `language="x"` with ' +
35
+ "`language={createCodeLanguage({name: 'x', identifiers: ['x'], tokenize: fn})}`. " +
36
+ 'Keeps the old prop with a TODO where the language is computed, missing, ' +
37
+ 'or `plaintext`, and where the CodeBlock also spreads props; the ' +
38
+ 'deprecated prop still works there.',
39
+ };
40
+
41
+ const OLD_NAME = 'tokenizer';
42
+ const CORE_IMPORT_RE = /^@(astryxdesign|xds)\/core(?:\/|$)/;
43
+ const CODEBLOCK_SOURCE = '@astryxdesign/core/CodeBlock';
44
+ const COMPONENT_PROPS = new Map([['CodeBlock', new Set([OLD_NAME])]]);
45
+
46
+ const UNPROVEN_COMMENT =
47
+ ' TODO(astryx upgrade): tokenizer is deprecated. Pass ' +
48
+ 'language={createCodeLanguage({name, identifiers, tokenize})} instead, ' +
49
+ 'with this function as tokenize; the language here is computed, missing, ' +
50
+ 'or plaintext, so it was left unchanged. ';
51
+ const VALUE_COMMENT =
52
+ ' TODO(astryx upgrade): tokenizer is deprecated. Pass ' +
53
+ 'language={createCodeLanguage({name, identifiers, tokenize})} instead; ' +
54
+ 'this tokenizer value is computed (not a function, a name, or a ' +
55
+ 'call-free property), so it was left unchanged. ';
56
+ const SPREAD_COMMENT =
57
+ ' TODO(astryx upgrade): tokenizer is deprecated, but this CodeBlock also ' +
58
+ 'spreads props that may set language or tokenizer, so it was left ' +
59
+ 'unchanged. Pass language={createCodeLanguage({name, identifiers, ' +
60
+ 'tokenize})} by hand. ';
61
+
62
+ const TYPE_WRAPPERS = new Set([
63
+ 'TSAsExpression',
64
+ 'TSSatisfiesExpression',
65
+ 'TSTypeAssertion',
66
+ 'TSNonNullExpression',
67
+ 'TypeCastExpression',
68
+ 'ParenthesizedExpression',
69
+ ]);
70
+
71
+ /** @param {any} node */
72
+ function unwrap(node) {
73
+ let current = node;
74
+ while (current && TYPE_WRAPPERS.has(current.type)) {
75
+ current = current.expression;
76
+ }
77
+ return current;
78
+ }
79
+
80
+ /** @param {any} attribute */
81
+ function attributeValue(attribute) {
82
+ return attribute.value?.type === 'JSXExpressionContainer'
83
+ ? attribute.value.expression
84
+ : attribute.value;
85
+ }
86
+
87
+ /** The static string of a node, or null. @param {any} node */
88
+ function staticString(node) {
89
+ const value = unwrap(node);
90
+ if (
91
+ value != null &&
92
+ (value.type === 'StringLiteral' || value.type === 'Literal') &&
93
+ typeof value.value === 'string'
94
+ ) {
95
+ return value.value;
96
+ }
97
+ if (
98
+ value?.type === 'TemplateLiteral' &&
99
+ value.expressions.length === 0 &&
100
+ value.quasis.length === 1
101
+ ) {
102
+ return value.quasis[0].value.cooked;
103
+ }
104
+ return null;
105
+ }
106
+
107
+ /**
108
+ * A name, or a property chain on one with no call and no computed key other
109
+ * than a literal: safe to read twice, and narrowed by a `?:` guard.
110
+ * @param {any} node
111
+ * @returns {boolean}
112
+ */
113
+ function isCallFreeChain(node) {
114
+ const value = unwrap(node);
115
+ if (value == null) {
116
+ return false;
117
+ }
118
+ if (value.type === 'Identifier' || value.type === 'ThisExpression') {
119
+ return true;
120
+ }
121
+ if (value.type === 'MemberExpression') {
122
+ const key = value.property;
123
+ const literalKey =
124
+ !value.computed ||
125
+ key.type === 'StringLiteral' ||
126
+ key.type === 'NumericLiteral' ||
127
+ key.type === 'Literal';
128
+ return (
129
+ literalKey && value.optional !== true && isCallFreeChain(value.object)
130
+ );
131
+ }
132
+ return false;
133
+ }
134
+
135
+ /** @param {any} j @param {any} node @param {string} text */
136
+ function addComment(j, node, text) {
137
+ node.comments ??= [];
138
+ if (node.comments.some((/** @type {any} */ c) => c.value === text)) {
139
+ return false;
140
+ }
141
+ node.comments.push(j.commentBlock(text, true, false));
142
+ return true;
143
+ }
144
+
145
+ /**
146
+ * The local name `createCodeLanguage` is imported under, adding the import
147
+ * when the file has none.
148
+ * @param {any} j @param {any} root
149
+ */
150
+ function ensureCreateImport(j, root) {
151
+ let local = null;
152
+ root
153
+ .find(j.ImportDeclaration)
154
+ .filter((/** @type {any} */ p) => CORE_IMPORT_RE.test(p.node.source.value))
155
+ .forEach((/** @type {any} */ p) => {
156
+ for (const specifier of p.node.specifiers ?? []) {
157
+ if (
158
+ specifier.type === 'ImportSpecifier' &&
159
+ specifier.imported.name === 'createCodeLanguage'
160
+ ) {
161
+ local = specifier.local?.name ?? 'createCodeLanguage';
162
+ }
163
+ }
164
+ });
165
+ if (local != null) {
166
+ return local;
167
+ }
168
+ // Any other binding of the name (a local import or function) would clash,
169
+ // so the import takes the first free alias instead.
170
+ const name = freeName(j, root, 'createCodeLanguage');
171
+ const specifier =
172
+ name === 'createCodeLanguage'
173
+ ? j.importSpecifier(j.identifier('createCodeLanguage'))
174
+ : j.importSpecifier(
175
+ j.identifier('createCodeLanguage'),
176
+ j.identifier(name),
177
+ );
178
+ const existing = root.find(j.ImportDeclaration).filter(
179
+ (/** @type {any} */ p) =>
180
+ p.node.source.value === CODEBLOCK_SOURCE &&
181
+ p.node.importKind !== 'type' &&
182
+ // A namespace import cannot take a named specifier beside it.
183
+ !(p.node.specifiers ?? []).some(
184
+ (/** @type {any} */ s) => s.type === 'ImportNamespaceSpecifier',
185
+ ),
186
+ );
187
+ if (existing.size() > 0) {
188
+ existing.get().node.specifiers.push(specifier);
189
+ } else {
190
+ const declaration = j.importDeclaration(
191
+ [specifier],
192
+ j.stringLiteral(CODEBLOCK_SOURCE),
193
+ );
194
+ const imports = root.find(j.ImportDeclaration);
195
+ if (imports.size() > 0) {
196
+ imports.at(imports.size() - 1).insertAfter(declaration);
197
+ } else {
198
+ root.get().node.program.body.unshift(declaration);
199
+ }
200
+ }
201
+ return name;
202
+ }
203
+
204
+ /**
205
+ * `preferred`, or `preferred` with a numeric suffix, whichever no binding or
206
+ * reference in the file already uses.
207
+ * @param {any} j @param {any} root @param {string} preferred
208
+ */
209
+ function freeName(j, root, preferred) {
210
+ const used = new Set();
211
+ root.find(j.Identifier).forEach((/** @type {any} */ p) => {
212
+ used.add(p.node.name);
213
+ });
214
+ if (!used.has(preferred)) {
215
+ return preferred;
216
+ }
217
+ let n = 2;
218
+ while (used.has(`${preferred}${n}`)) {
219
+ n++;
220
+ }
221
+ return `${preferred}${n}`;
222
+ }
223
+
224
+ /**
225
+ * @param {import('../../../../authoring/codemod/type').AstryxCodemodFile} file
226
+ * @param {import('../../../../authoring/codemod/type').CodemodTransformApi} api
227
+ * @returns {string | null | undefined}
228
+ */
229
+ export default function transformer(file, api) {
230
+ const j = api.jscodeshift;
231
+ const root = j(file.source);
232
+ let hasChanges = false;
233
+ /** @type {Array<() => void>} */
234
+ const rewrites = [];
235
+
236
+ transformProp(
237
+ root,
238
+ j,
239
+ {
240
+ matchesImport: source => CORE_IMPORT_RE.test(source),
241
+ components: COMPONENT_PROPS,
242
+ },
243
+ propPath => {
244
+ const opening = propPath.parent?.node;
245
+ const attributes = opening?.attributes ?? [];
246
+ const prop = propPath.node;
247
+ if (
248
+ attributes.some(
249
+ (/** @type {any} */ a) => a.type === 'JSXSpreadAttribute',
250
+ )
251
+ ) {
252
+ hasChanges = addComment(j, prop, SPREAD_COMMENT) || hasChanges;
253
+ return;
254
+ }
255
+ const languageAttribute = attributes.find(
256
+ (/** @type {any} */ a) =>
257
+ a.type === 'JSXAttribute' && a.name?.name === 'language',
258
+ );
259
+ const language =
260
+ languageAttribute == null
261
+ ? null
262
+ : staticString(attributeValue(languageAttribute));
263
+ const tokenize = attributeValue(prop);
264
+ const tokenizeNode = unwrap(tokenize);
265
+ // A function literal is always a function. A name or property may be
266
+ // undefined at run time (a forwarded optional prop), so it is guarded:
267
+ // `fn ? createCodeLanguage({...}) : 'x'` keeps the plain block the
268
+ // released prop drew without one. Anything else is reported.
269
+ const isFunction =
270
+ tokenizeNode?.type === 'ArrowFunctionExpression' ||
271
+ tokenizeNode?.type === 'FunctionExpression';
272
+ const isGuardable = isCallFreeChain(tokenizeNode);
273
+ if (language == null || language === '' || language === 'plaintext') {
274
+ hasChanges = addComment(j, prop, UNPROVEN_COMMENT) || hasChanges;
275
+ return;
276
+ }
277
+ if (!(isFunction || isGuardable)) {
278
+ hasChanges = addComment(j, prop, VALUE_COMMENT) || hasChanges;
279
+ return;
280
+ }
281
+ rewrites.push(() => {
282
+ const create = ensureCreateImport(j, root);
283
+ const value = j.callExpression(j.identifier(create), [
284
+ j.objectExpression([
285
+ j.objectProperty(j.identifier('name'), j.stringLiteral(language)),
286
+ j.objectProperty(
287
+ j.identifier('identifiers'),
288
+ j.arrayExpression([j.stringLiteral(language)]),
289
+ ),
290
+ j.objectProperty(j.identifier('tokenize'), tokenize),
291
+ ]),
292
+ ]);
293
+ languageAttribute.value = j.jsxExpressionContainer(
294
+ isFunction
295
+ ? value
296
+ : j.conditionalExpression(
297
+ tokenize,
298
+ value,
299
+ j.stringLiteral(language),
300
+ ),
301
+ );
302
+ opening.attributes = opening.attributes.filter(
303
+ (/** @type {any} */ a) => a !== prop,
304
+ );
305
+ });
306
+ },
307
+ );
308
+
309
+ for (const rewrite of rewrites) {
310
+ rewrite();
311
+ hasChanges = true;
312
+ }
313
+ if (!hasChanges) return undefined;
314
+ return root.toSource({quote: 'single'});
315
+ }
@@ -55,9 +55,11 @@ export const docs = {
55
55
  ['tokens', 'Base tokens are copied first, then child tokens override on top.'],
56
56
  ['components', 'Deep-merged: child component rules override matching keys from the base.'],
57
57
  ['icons', 'Shallow-merged: child icons override matching names from the base.'],
58
+ ['iconVariants', 'Replaced, never merged: a child that sets iconVariants replaces the base list; a child that omits it inherits the list.'],
58
59
  ['indicators', 'Shallow-merged: child indicators override matching names from the base.'],
59
60
  ['onDark, onLight', "Deep-merged per surface: the base's resolved surface first, then the child's overrides."],
60
- ['typography, motion, radius, color', 'Child config replaces base entirely (these are scale inputs, not additive).'],
61
+ ['motion', "Field by field: the child's `fast`, `medium` and `ratio` regenerate the fast and medium duration tokens; `slow` and `easing` left unset keep the base theme's tokens, so an inherited slow band stays at the base's ratio."],
62
+ ['typography, radius, color', 'Child config replaces base entirely (these are scale inputs, not additive).'],
61
63
  ['adaptations', 'Width-breakpoint overrides merge by fixed name. Inherited ordered rules keep their relative order; child rules append and re-resolve against the child root axes.'],
62
64
  ]},
63
65
  {type: 'prose', text: "Inheritance is resolved when the theme is defined, so an extended theme is flat: `{@command theme build}` emits one self-contained stylesheet holding everything the child inherited, and the base theme's CSS does not need to be loaded next to it. A base that is not a theme (most often an import that missed) throws when `defineTheme` runs, rather than producing a theme that silently inherits nothing."},
@@ -101,11 +101,92 @@ export const brandTheme = defineTheme({
101
101
  },
102
102
  });`,
103
103
  },
104
+ {
105
+ type: 'prose',
106
+ text: "An entry can also be a function of the request, so the theme maps Icon's size to its icon library's own props or artwork. `Icon` calls it with `{size, variant}`, where `size` is the size it renders at (`xsm`, `sm`, `md`, or `lg`: an explicit `size`, else the owning component's default, else `md`). Reads that return one node — `getIcon()`, `useIcon()`, `getIconRegistry()`, and the theme's `icons` field — call it with `{size: 'md'}`. The same entry shape works in `registerIcons()`.",
107
+ },
108
+ {
109
+ type: 'code',
110
+ lang: 'tsx',
111
+ label: 'A size-aware icon entry',
112
+ code: `import {defineTheme} from '@astryxdesign/core/theme';
113
+ import {Info} from 'lucide-react';
114
+
115
+ export const brandTheme = defineTheme({
116
+ name: 'brand',
117
+ icons: {
118
+ // A heavier stroke keeps the small size legible.
119
+ info: ({size}) => <Info strokeWidth={size === 'sm' || size === 'xsm' ? 2.5 : 2} />,
120
+ },
121
+ });`,
122
+ },
123
+ {
124
+ type: 'prose',
125
+ text: 'Keep the function pure and synchronous: it computes its result from the request only, with no hooks, DOM or SVG measurement, browser globals, network access, mutable module state, or side effects. Its result is final. Returning `null` draws no glyph instead of falling back to a registered or built-in icon, while a `null` or `undefined` node entry still falls back. A child theme that sets an entry for a key replaces the inherited entry for that key.',
126
+ },
104
127
  ],
105
128
  },
106
129
  {
107
- title: 'Component and Library Icons',
130
+ title: 'Icon Variants',
108
131
  category: 'foundations',
132
+ content: [
133
+ {
134
+ type: 'prose',
135
+ text: "A theme lists the icon variant names it supports once, with `iconVariants` in `defineTheme()`. The list belongs to the whole theme, never to one icon, and Astryx defines no names of its own. Inside `defineTheme`, an entry function receives `variant` typed as the listed names, or `undefined`, so a misspelled name is a type error. An entry that receives `undefined` draws its normal artwork.",
136
+ },
137
+ {
138
+ type: 'code',
139
+ lang: 'tsx',
140
+ label: 'Listing variants and mapping them to artwork',
141
+ code: `import {defineTheme} from '@astryxdesign/core/theme';
142
+ import {InfoFilledIcon, InfoIcon} from './brand-icons';
143
+
144
+ export const brandTheme = defineTheme({
145
+ name: 'brand',
146
+ iconVariants: ['outline', 'filled'],
147
+ icons: {
148
+ info: ({size, variant}) =>
149
+ variant === 'filled' ? <InfoFilledIcon /> : <InfoIcon bold={size === 'sm'} />,
150
+ },
151
+ });
152
+
153
+ brandTheme.iconVariants; // ['outline', 'filled']`,
154
+ },
155
+ {
156
+ type: 'prose',
157
+ text: 'A theme that `extends` another inherits its list unless it sets its own; a list it sets replaces the inherited one instead of merging with it.',
158
+ },
159
+ {
160
+ type: 'prose',
161
+ text: "Request a variant with `Icon`'s `variant` prop. The entry receives it only when the active theme lists it; an entry the theme inherited also needs the theme that defined it to list it. Otherwise the entry receives `undefined` and draws its normal artwork, so an unlisted variant never breaks rendering. A `registerIcons()` entry receives the variants the active theme lists, and a node entry draws the same node for every variant. An icon component passed directly to `Icon` never receives `variant`, and `variant` is never written to the DOM: it selects artwork, so there is no theming selector for it.",
162
+ },
163
+ {
164
+ type: 'code',
165
+ lang: 'tsx',
166
+ label: 'Requesting a variant',
167
+ code: `<Icon icon="info" variant="filled" /> // brandTheme: the filled artwork
168
+ <Icon icon="info" /> // the normal artwork`,
169
+ },
170
+ {
171
+ type: 'prose',
172
+ text: 'An application declares the variant names it uses by augmenting `IconVariantMap` from `@astryxdesign/core/Icon`. `IconVariant` is those names, and an entry passed to `registerIcons()` receives `variant` typed as `IconVariant`.',
173
+ },
174
+ {
175
+ type: 'code',
176
+ lang: 'ts',
177
+ label: 'Declaring the variant names an application uses',
178
+ code: `declare module '@astryxdesign/core/Icon' {
179
+ interface IconVariantMap {
180
+ outline: true;
181
+ filled: true;
182
+ }
183
+ }`,
184
+ },
185
+ ],
186
+ },
187
+ {
188
+ title: 'Component and Library Icons',
189
+ category: 'foundations',
109
190
  content: [
110
191
  {
111
192
  type: 'prose',