@astryxdesign/cli 0.7.13 → 0.7.14-canary.d08ce65

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 (146) hide show
  1. package/README.md +18 -18
  2. package/api/component/__fixtures__/resolutions/modules.txt +1 -1
  3. package/api/doctor/doctor.mjs +3 -7
  4. package/api/experimental.d.mts +2 -0
  5. package/api/experimental.mjs +10 -0
  6. package/api/icon/_adapter.d.mts +10 -0
  7. package/api/icon/_adapter.mjs +31 -2
  8. package/api/icon/_authoring.d.mts +2 -1
  9. package/api/icon/_authoring.mjs +91 -6
  10. package/api/icon/_options.mjs +1 -0
  11. package/api/icon/_records.d.mts +18 -0
  12. package/api/icon/_records.mjs +26 -0
  13. package/api/icon/add/add.mjs +7 -1
  14. package/api/icon/definitions/definitions.d.mts +12 -0
  15. package/api/icon/definitions/definitions.mjs +83 -0
  16. package/api/icon/icon.doc.mjs +5 -4
  17. package/api/icon/icon.mjs +5 -16
  18. package/api/icon/icon.type.d.mts +29 -2
  19. package/api/icon/icon.type.mjs +17 -3
  20. package/api/icon/iconAdd.doc.mjs +1 -1
  21. package/api/icon/iconMap.doc.mjs +2 -2
  22. package/api/icon/iconNewSet.doc.mjs +8 -2
  23. package/api/icon/map/map.mjs +21 -2
  24. package/api/icon/new-set/new-set.mjs +14 -2
  25. package/api/icon/search/search.mjs +2 -15
  26. package/api/icon/use/use.mjs +4 -3
  27. package/api/integration/validate-integration.mjs +6 -1
  28. package/api/integration/validate-integration.type.d.mts +12 -0
  29. package/api/integration/validate-integration.type.mjs +5 -0
  30. package/api/theme-edit/_adapter.d.mts +96 -0
  31. package/api/theme-edit/_adapter.mjs +1039 -0
  32. package/api/theme-edit/_catalog.d.mts +59 -0
  33. package/api/theme-edit/_catalog.mjs +564 -0
  34. package/api/theme-edit/_check.d.mts +49 -0
  35. package/api/theme-edit/_check.mjs +842 -0
  36. package/api/theme-edit/_color.d.mts +35 -0
  37. package/api/theme-edit/_color.mjs +125 -0
  38. package/api/theme-edit/_compiler.d.mts +61 -0
  39. package/api/theme-edit/_compiler.mjs +522 -0
  40. package/api/theme-edit/_css-properties.d.mts +10 -0
  41. package/api/theme-edit/_css-properties.mjs +556 -0
  42. package/api/theme-edit/_parts.d.mts +111 -0
  43. package/api/theme-edit/_parts.mjs +409 -0
  44. package/api/theme-edit/_png.d.mts +40 -0
  45. package/api/theme-edit/_png.mjs +187 -0
  46. package/api/theme-edit/_preview.d.mts +86 -0
  47. package/api/theme-edit/_preview.mjs +564 -0
  48. package/api/theme-edit/_project.d.mts +83 -0
  49. package/api/theme-edit/_project.mjs +289 -0
  50. package/api/theme-edit/_settings.d.mts +222 -0
  51. package/api/theme-edit/_settings.mjs +848 -0
  52. package/api/theme-edit/_tables.d.mts +130 -0
  53. package/api/theme-edit/_tables.mjs +697 -0
  54. package/api/theme-edit/theme-edit.d.mts +89 -0
  55. package/api/theme-edit/theme-edit.mjs +119 -0
  56. package/api/theme-edit/theme-edit.type.d.mts +270 -0
  57. package/api/theme-edit/theme-edit.type.mjs +155 -0
  58. package/api/theme-edit/themeEditExplain.doc.d.mts +6 -0
  59. package/api/theme-edit/themeEditExplain.doc.mjs +88 -0
  60. package/api/theme-edit/themeEditNew.doc.d.mts +6 -0
  61. package/api/theme-edit/themeEditNew.doc.mjs +89 -0
  62. package/api/theme-edit/themeEditPreview.doc.d.mts +6 -0
  63. package/api/theme-edit/themeEditPreview.doc.mjs +96 -0
  64. package/api/theme-edit/themeEditReset.doc.d.mts +6 -0
  65. package/api/theme-edit/themeEditReset.doc.mjs +161 -0
  66. package/api/theme-edit/themeEditSet.doc.d.mts +6 -0
  67. package/api/theme-edit/themeEditSet.doc.mjs +165 -0
  68. package/api/theme-edit/themeEditShow.doc.d.mts +6 -0
  69. package/api/theme-edit/themeEditShow.doc.mjs +86 -0
  70. package/api/theme-edit/themeEditUndo.doc.d.mts +6 -0
  71. package/api/theme-edit/themeEditUndo.doc.mjs +80 -0
  72. package/assets/docs/color.doc.mjs +5 -5
  73. package/assets/docs/tree/icon-sets.doc.mjs +6 -2
  74. package/assets/docs/tree/tokens-border.doc.mjs +1 -1
  75. package/assets/docs/tree/tokens-color.doc.mjs +2 -2
  76. package/assets/docs/tree/tokens-data.doc.mjs +2 -2
  77. package/assets/docs/tree/tokens-duration.doc.mjs +1 -1
  78. package/assets/docs/tree/tokens-ease.doc.mjs +1 -1
  79. package/assets/docs/tree/tokens-focus.doc.mjs +1 -1
  80. package/assets/docs/tree/tokens-font-weight.doc.mjs +1 -1
  81. package/assets/docs/tree/tokens-radius.doc.mjs +1 -1
  82. package/assets/docs/tree/tokens-shadow.doc.mjs +1 -1
  83. package/assets/docs/tree/tokens-size.doc.mjs +1 -1
  84. package/assets/docs/tree/tokens-spacing.doc.mjs +1 -1
  85. package/assets/docs/tree/tokens-syntax.doc.mjs +1 -1
  86. package/assets/docs/tree/tokens-text-size.doc.mjs +1 -1
  87. package/assets/docs/tree/tokens-type-scale.doc.mjs +1 -1
  88. package/assets/docs/tree/tokens-typography.doc.mjs +1 -1
  89. package/assets/icons/definitions/bank.doc.mjs +1 -1
  90. package/assets/icons/definitions/save.doc.mjs +1 -1
  91. package/assets/templates/blocks/components/InternationalizationProvider/InternationalizationProvider01ShippedLocale.doc.mjs +2 -1
  92. package/assets/templates/blocks/components/InternationalizationProvider/InternationalizationProvider02Overrides.doc.mjs +2 -1
  93. package/assets/templates/blocks/components/InternationalizationProvider/InternationalizationProvider03RtlDirection.doc.mjs +2 -1
  94. package/assets/templates/blocks/components/InternationalizationProvider/InternationalizationProvider04Calendar.doc.mjs +2 -1
  95. package/assets/templates/blocks/components/Text/useTruncationHookUsage.doc.mjs +14 -0
  96. package/assets/templates/blocks/components/Text/useTruncationHookUsage.tsx +112 -0
  97. package/authoring/doctypes/_schema.d.mts +1 -0
  98. package/authoring/doctypes/_schema.mjs +1 -0
  99. package/authoring/doctypes/command/command.doc.mjs +7 -0
  100. package/authoring/doctypes/command/type.ts +3 -0
  101. package/authoring/doctypes/icon-set/parse.d.mts +7 -0
  102. package/authoring/doctypes/icon-set/parse.mjs +18 -8
  103. package/clients/cli/commands/doctor.mjs +33 -3
  104. package/clients/cli/commands/experimental/icon.mjs +67 -14
  105. package/clients/cli/commands/experimental/index.mjs +2 -0
  106. package/clients/cli/commands/experimental/theme.mjs +542 -0
  107. package/clients/cli/commands/experimental-icon-new-set.doc.mjs +7 -1
  108. package/clients/cli/commands/experimental-icon.doc.mjs +3 -2
  109. package/clients/cli/commands/experimental-theme-add.doc.mjs +78 -0
  110. package/clients/cli/commands/experimental-theme-compile.doc.mjs +97 -0
  111. package/clients/cli/commands/experimental-theme-eject.doc.mjs +71 -0
  112. package/clients/cli/commands/experimental-theme-explain.doc.mjs +84 -0
  113. package/clients/cli/commands/experimental-theme-list.doc.mjs +49 -0
  114. package/clients/cli/commands/experimental-theme-new.doc.mjs +66 -0
  115. package/clients/cli/commands/experimental-theme-palette-generate.doc.mjs +73 -0
  116. package/clients/cli/commands/experimental-theme-palette.doc.mjs +37 -0
  117. package/clients/cli/commands/experimental-theme-preview.doc.mjs +76 -0
  118. package/clients/cli/commands/experimental-theme-remove.doc.mjs +55 -0
  119. package/clients/cli/commands/experimental-theme-reset.doc.mjs +103 -0
  120. package/clients/cli/commands/experimental-theme-set.doc.mjs +121 -0
  121. package/clients/cli/commands/experimental-theme-show.doc.mjs +66 -0
  122. package/clients/cli/commands/experimental-theme-targets.doc.mjs +61 -0
  123. package/clients/cli/commands/experimental-theme-template.doc.mjs +61 -0
  124. package/clients/cli/commands/experimental-theme-undo.doc.mjs +55 -0
  125. package/clients/cli/commands/experimental-theme-use.doc.mjs +55 -0
  126. package/clients/cli/commands/experimental-theme.doc.mjs +66 -0
  127. package/clients/cli/commands/experimental.doc.mjs +10 -3
  128. package/clients/cli/commands/theme.mjs +101 -34
  129. package/clients/cli/index.mjs +16 -0
  130. package/clients/cli/lib/define-command.mjs +3 -0
  131. package/foundation/discovery/icon-set-checks.d.mts +16 -1
  132. package/foundation/discovery/icon-set-checks.mjs +68 -7
  133. package/foundation/discovery/icon-set-discovery.d.mts +21 -6
  134. package/foundation/discovery/icon-set-discovery.mjs +17 -8
  135. package/foundation/discovery/template-icon-meanings.d.mts +39 -0
  136. package/foundation/discovery/template-icon-meanings.mjs +95 -0
  137. package/foundation/discovery/theming-targets.d.mts +6 -0
  138. package/foundation/discovery/theming-targets.mjs +33 -0
  139. package/foundation/response/error-codes.d.mts +12 -1
  140. package/foundation/response/error-codes.doc.mjs +66 -0
  141. package/foundation/response/error-codes.mjs +55 -0
  142. package/foundation/response/response-types.doc.mjs +43 -0
  143. package/foundation/text/template-meanings-line.d.mts +16 -0
  144. package/foundation/text/template-meanings-line.mjs +37 -0
  145. package/foundation/xle/browser.d.mts +2 -2
  146. package/package.json +6 -6
@@ -0,0 +1,86 @@
1
+ // @generated by scripts/sync-api-types.mjs from the JSDoc in api/**/*.mjs.
2
+ // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
+
4
+ /**
5
+ * Items of the theme-building page: each component once per variant, the
6
+ * hand-made extras, overlays open, the sample page, and template pages
7
+ * whose packages the project has.
8
+ * @param {import('./_project.mjs').ThemeProject} project
9
+ * @param {string | undefined} group only this group
10
+ * @returns {{items: import('./_catalog.mjs').CatalogItem[], imports: Record<string, string>, skipped: string[]}}
11
+ */
12
+ export function showcaseItems(project: import("./_project.mjs").ThemeProject, group: string | undefined): {
13
+ items: import("./_catalog.mjs").CatalogItem[];
14
+ imports: Record<string, string>;
15
+ skipped: string[];
16
+ };
17
+ /**
18
+ * Render the sample app page with the theme to themes/<slug>/preview.html.
19
+ * @param {import('./_settings.mjs').Ctx} ctx
20
+ * @param {string} slug
21
+ * @param {import('./_settings.mjs').ThemeData} data
22
+ * @returns {Promise<string>} the file written, as shown
23
+ */
24
+ export function renderPreview(ctx: import("./_settings.mjs").Ctx, slug: string, data: import("./_settings.mjs").ThemeData): Promise<string>;
25
+ /**
26
+ * Render the theme-building page with the theme to one HTML file.
27
+ * @param {import('./_settings.mjs').Ctx} ctx
28
+ * @param {string} slug
29
+ * @param {import('./_settings.mjs').ThemeData} data
30
+ * @param {{group?: string, out?: string}} [options]
31
+ * @returns {Promise<{file: string, components: number, skipped: string[]}>}
32
+ */
33
+ export function renderSheet(ctx: import("./_settings.mjs").Ctx, slug: string, data: import("./_settings.mjs").ThemeData, options?: {
34
+ group?: string;
35
+ out?: string;
36
+ }): Promise<{
37
+ file: string;
38
+ components: number;
39
+ skipped: string[];
40
+ }>;
41
+ /**
42
+ * Write the theme-building page into the app: a page module that uses the
43
+ * app's own Astryx, with a light and dark switch, plus the template pages
44
+ * it shows, beside it.
45
+ * @param {import('./_settings.mjs').Ctx} ctx
46
+ * @param {string} slug
47
+ * @param {import('./_settings.mjs').ThemeData} data
48
+ * @param {string} dir absolute folder to write into
49
+ * @param {string | undefined} group
50
+ * @returns {{files: string[], components: number, skipped: string[]}}
51
+ */
52
+ export function writeShowcase(ctx: import("./_settings.mjs").Ctx, slug: string, data: import("./_settings.mjs").ThemeData, dir: string, group: string | undefined): {
53
+ files: string[];
54
+ components: number;
55
+ skipped: string[];
56
+ };
57
+ /**
58
+ * A PNG of an HTML file, with a Playwright the project has installed, else
59
+ * a Chrome or Chromium found on the machine. Null with a reason when neither
60
+ * is there.
61
+ * @param {import('./_project.mjs').ThemeProject} project
62
+ * @param {string} html absolute
63
+ * @param {string} png absolute
64
+ * @param {'light' | 'dark'} mode
65
+ * @returns {Promise<{ok: true, file: string} | {ok: false, reason: string}>}
66
+ */
67
+ export function screenshot(project: import("./_project.mjs").ThemeProject, html: string, png: string, mode: "light" | "dark"): Promise<{
68
+ ok: true;
69
+ file: string;
70
+ } | {
71
+ ok: false;
72
+ reason: string;
73
+ }>;
74
+ /** The groups of the theme-building page, in order. */
75
+ export const SHOWCASE_GROUPS: string[];
76
+ export namespace SHOWCASE_GROUP_HELP {
77
+ let actions: string;
78
+ let inputs: string;
79
+ let selection: string;
80
+ let navigation: string;
81
+ let feedback: string;
82
+ let data: string;
83
+ let containers: string;
84
+ let overlays: string;
85
+ let pages: string;
86
+ }
@@ -0,0 +1,564 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Previews for `astryx experimental theme`: the sample app page and
5
+ * the theme-building page (every component grouped, overlays open, and real
6
+ * template pages), rendered with the theme to self-contained HTML by the
7
+ * render machinery, or written into the app as a page module. PNG pictures
8
+ * are made only on request, with a Playwright or Chrome installed on the
9
+ * machine.
10
+ *
11
+ * @position api/theme-edit — previews and pictures
12
+ */
13
+
14
+ import * as fs from 'node:fs';
15
+ import * as path from 'node:path';
16
+ import {spawnSync} from 'node:child_process';
17
+ import {fileURLToPath, pathToFileURL} from 'node:url';
18
+ import {
19
+ EXTRA,
20
+ OPEN_OVERLAYS,
21
+ SAMPLE_PAGE,
22
+ SHEET_ORDER,
23
+ elementNames,
24
+ pageSource,
25
+ } from './_catalog.mjs';
26
+ import {renderDir, renderGenerated} from './_parts.mjs';
27
+ import {fontPackages, modesOf, themeFiles, shown} from './_settings.mjs';
28
+ import {importPathOf, installLine} from './_project.mjs';
29
+
30
+ const TEMPLATES_DIR = path.resolve(
31
+ path.dirname(fileURLToPath(import.meta.url)),
32
+ '../../assets/templates/pages',
33
+ );
34
+
35
+ /** The groups of the theme-building page, in order. */
36
+ export const SHOWCASE_GROUPS = [
37
+ 'actions',
38
+ 'inputs',
39
+ 'selection',
40
+ 'navigation',
41
+ 'feedback',
42
+ 'data',
43
+ 'containers',
44
+ 'overlays',
45
+ 'pages',
46
+ ];
47
+
48
+ /** What each group holds, for help and `--group`. */
49
+ export const SHOWCASE_GROUP_HELP = {
50
+ actions: 'buttons and links',
51
+ inputs: 'text, number, date and time fields, forms',
52
+ selection: 'selectors, checkboxes, radios, switches, segmented controls',
53
+ navigation: 'top and side navigation, tabs, breadcrumbs, pagination',
54
+ feedback: 'banners, badges, progress, status dots, toasts',
55
+ data: 'text, headings, tables, lists, code, content',
56
+ containers: 'cards and layout',
57
+ overlays: 'dialogs, popovers, menus and tooltips, shown open',
58
+ pages:
59
+ 'the sample app page and real template pages (dashboard, form, settings)',
60
+ };
61
+
62
+ /** Real template pages the theme-building page shows in full. */
63
+ const PAGE_TEMPLATES = ['dashboard', 'contact-form', 'settings'];
64
+
65
+ const SELECTION =
66
+ /Select|Checkbox|Radio|Switch|Segmented|Toggle|Slider|Typeahead|Tokenizer/;
67
+
68
+ /**
69
+ * The group a component belongs to on the theme-building page.
70
+ * @param {string} name
71
+ * @param {string} category
72
+ * @returns {string | null}
73
+ */
74
+ function groupOf(name, category) {
75
+ if (SELECTION.test(name)) return 'selection';
76
+ const c = category.toLowerCase();
77
+ if (c === 'action') return 'actions';
78
+ if (c === 'form controls') return 'inputs';
79
+ if (c === 'navigation') return 'navigation';
80
+ if (c === 'feedback & status') return 'feedback';
81
+ if (c === 'content' || c === 'table & list' || c === 'text' || c === 'media')
82
+ return 'data';
83
+ if (c === 'container' || c === 'layout') return 'containers';
84
+ if (c === 'overlay') return 'overlays';
85
+ return null;
86
+ }
87
+
88
+ /**
89
+ * Items of the theme-building page: each component once per variant, the
90
+ * hand-made extras, overlays open, the sample page, and template pages
91
+ * whose packages the project has.
92
+ * @param {import('./_project.mjs').ThemeProject} project
93
+ * @param {string | undefined} group only this group
94
+ * @returns {{items: import('./_catalog.mjs').CatalogItem[], imports: Record<string, string>, skipped: string[]}}
95
+ */
96
+ export function showcaseItems(project, group) {
97
+ /** @type {import('./_catalog.mjs').CatalogItem[]} */
98
+ const items = [];
99
+ /** @param {string} name */
100
+ const groupFor = name =>
101
+ groupOf(name, project.components[name]?.category ?? '');
102
+ const extraNames = new Set([...EXTRA, ...OPEN_OVERLAYS].map(([n]) => n));
103
+ for (const [name, list] of [...EXTRA, ...OPEN_OVERLAYS]) {
104
+ const g = groupFor(name);
105
+ if (g)
106
+ for (const [label, tree] of list)
107
+ items.push({group: g, name, label, tree});
108
+ }
109
+ for (const [name, info] of Object.entries(project.components)) {
110
+ const defaults = /** @type {any} */ (info.defaults);
111
+ const g = groupFor(name);
112
+ if (!g || !defaults || typeof defaults !== 'object' || extraNames.has(name))
113
+ continue;
114
+ const values = info.targets[0]?.values ?? {};
115
+ /** @type {Array<Record<string, string>>} */
116
+ const variants = [{}];
117
+ for (const p of ['variant', 'status', 'color'])
118
+ for (const v of values[p] ?? []) variants.push({[p]: v});
119
+ for (const v of variants.slice(0, 12))
120
+ items.push({
121
+ group: g,
122
+ name,
123
+ label: Object.values(v).join(' '),
124
+ tree: {__element: name, props: {...defaults, ...v}},
125
+ });
126
+ }
127
+ items.push({
128
+ group: 'pages',
129
+ name: 'Sample app',
130
+ label: '',
131
+ tree: SAMPLE_PAGE,
132
+ });
133
+ /** @type {string[]} */
134
+ const skipped = [];
135
+ /** @type {Record<string, string>} */
136
+ const templateImports = {};
137
+ for (const t of PAGE_TEMPLATES) {
138
+ const file = path.join(TEMPLATES_DIR, t, 'page.tsx');
139
+ if (!fs.existsSync(file)) continue;
140
+ const src = fs.readFileSync(file, 'utf8');
141
+ const missing = [
142
+ ...src.matchAll(/^\s*(?:import|\})[^'"\n]*from\s+['"]([^'"]+)['"]/gm),
143
+ ]
144
+ .map(m => m[1])
145
+ .filter(spec => !spec.startsWith('.') && !resolves(project, spec));
146
+ if (missing.length) {
147
+ const pkgs = [
148
+ ...new Set(
149
+ missing.map(s =>
150
+ s.startsWith('@')
151
+ ? s.split('/').slice(0, 2).join('/')
152
+ : s.split('/')[0],
153
+ ),
154
+ ),
155
+ ];
156
+ skipped.push(
157
+ `the ${t} page needs ${pkgs.join(', ')} (${installLine(project.cwd, pkgs)})`,
158
+ );
159
+ continue;
160
+ }
161
+ const local = `Template_${t.replace(/-/g, '_')}`;
162
+ templateImports[local] = `./templates/${t}.tsx`;
163
+ items.push({
164
+ group: 'pages',
165
+ name: `${t} template`,
166
+ label: '',
167
+ tree: {__element: local, props: {}},
168
+ });
169
+ }
170
+ const order = (/** @type {import('./_catalog.mjs').CatalogItem} */ it) => {
171
+ const i = SHEET_ORDER.indexOf(it.name);
172
+ return SHOWCASE_GROUPS.indexOf(it.group ?? '') * 1000 + (i < 0 ? 500 : i);
173
+ };
174
+ const chosen = items
175
+ .filter(it => !group || it.group === group)
176
+ .sort((a, b) => order(a) - order(b) || a.name.localeCompare(b.name));
177
+ /** @type {Record<string, string>} */
178
+ const imports = {};
179
+ for (const n of elementNames(chosen.map(i => i.tree))) {
180
+ if (templateImports[n]) {
181
+ imports[n] = templateImports[n];
182
+ continue;
183
+ }
184
+ const spec = importPathOf(project, n);
185
+ if (spec) imports[n] = spec;
186
+ }
187
+ return {
188
+ items: chosen,
189
+ imports,
190
+ skipped: !group || group === 'pages' ? skipped : [],
191
+ };
192
+ }
193
+
194
+ /** @param {import('./_project.mjs').ThemeProject} project @param {string} spec */
195
+ function resolves(project, spec) {
196
+ try {
197
+ project.req.resolve(spec);
198
+ return true;
199
+ } catch {
200
+ return false;
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Template page modules the theme-building page imports, copied beside it.
206
+ * @param {Record<string, string>} imports
207
+ * @returns {Array<{name: string, from: string}>}
208
+ */
209
+ function templateFiles(imports) {
210
+ return Object.values(imports).flatMap(spec => {
211
+ const m = /^\.\/templates\/([a-z0-9-]+)\.tsx$/.exec(spec);
212
+ return m
213
+ ? [
214
+ {
215
+ name: `templates/${m[1]}.tsx`,
216
+ from: path.join(TEMPLATES_DIR, m[1], 'page.tsx'),
217
+ },
218
+ ]
219
+ : [];
220
+ });
221
+ }
222
+
223
+ /**
224
+ * How a generated page imports the theme: its built module, its stylesheet,
225
+ * and the stylesheets of open fonts the project has installed.
226
+ * @param {import('./_settings.mjs').Ctx} ctx
227
+ * @param {string} slug
228
+ * @param {import('./_settings.mjs').ThemeData} data
229
+ * @param {string} fromDir the folder of the page
230
+ */
231
+ function themeImports(ctx, slug, data, fromDir) {
232
+ const f = themeFiles(ctx.project.cwd, slug);
233
+ /** @param {string} file */
234
+ const rel = file => {
235
+ const r = path.relative(fromDir, file).split(path.sep).join('/');
236
+ return r.startsWith('.') ? r : `./${r}`;
237
+ };
238
+ const modes = modesOf(data);
239
+ const fonts = fontPackages(ctx, data)
240
+ .filter(x => x.installed)
241
+ .map(x => `${x.pkg}/index.css`);
242
+ return {
243
+ module: rel(f.js),
244
+ css: [rel(f.css), ...fonts],
245
+ mode: /** @type {'system' | 'light' | 'dark'} */ (
246
+ modes.length > 1 ? 'system' : modes[0]
247
+ ),
248
+ };
249
+ }
250
+
251
+ /**
252
+ * Render the sample app page with the theme to themes/<slug>/preview.html.
253
+ * @param {import('./_settings.mjs').Ctx} ctx
254
+ * @param {string} slug
255
+ * @param {import('./_settings.mjs').ThemeData} data
256
+ * @returns {Promise<string>} the file written, as shown
257
+ */
258
+ export async function renderPreview(ctx, slug, data) {
259
+ const {project} = ctx;
260
+ const imports = /** @type {Record<string, string>} */ ({});
261
+ for (const n of elementNames(SAMPLE_PAGE)) {
262
+ const spec = importPathOf(project, n);
263
+ if (spec) imports[n] = spec;
264
+ }
265
+ const source = pageSource({
266
+ items: [{name: 'page', label: '', tree: SAMPLE_PAGE}],
267
+ imports,
268
+ theme: themeImports(ctx, slug, data, renderDir(project)),
269
+ layout: 'page',
270
+ title: `${slug}: sample page`,
271
+ });
272
+ const {html} = await renderGenerated(project, `preview-${slug}.mjs`, source);
273
+ const out = themeFiles(project.cwd, slug).preview;
274
+ fs.writeFileSync(out, html);
275
+ return shown(project.cwd, out);
276
+ }
277
+
278
+ /**
279
+ * Render the theme-building page with the theme to one HTML file.
280
+ * @param {import('./_settings.mjs').Ctx} ctx
281
+ * @param {string} slug
282
+ * @param {import('./_settings.mjs').ThemeData} data
283
+ * @param {{group?: string, out?: string}} [options]
284
+ * @returns {Promise<{file: string, components: number, skipped: string[]}>}
285
+ */
286
+ export async function renderSheet(ctx, slug, data, options = {}) {
287
+ const {project} = ctx;
288
+ const {items, imports, skipped} = showcaseItems(project, options.group);
289
+ const source = pageSource({
290
+ items,
291
+ imports,
292
+ theme: themeImports(ctx, slug, data, renderDir(project)),
293
+ layout: 'sheet',
294
+ title: `${slug}: every component${options.group ? ` (${options.group})` : ''}`,
295
+ });
296
+ const {html} = await renderGenerated(
297
+ project,
298
+ `sheet-${slug}.mjs`,
299
+ source,
300
+ templateFiles(imports),
301
+ );
302
+ const out = options.out ?? themeFiles(project.cwd, slug).sheet;
303
+ fs.mkdirSync(path.dirname(out), {recursive: true});
304
+ fs.writeFileSync(out, html);
305
+ return {
306
+ file: shown(project.cwd, out),
307
+ components: new Set(items.map(i => i.name)).size,
308
+ skipped,
309
+ };
310
+ }
311
+
312
+ /** @param {unknown} v @param {number} depth @returns {string} */
313
+ function jsxValue(v, depth) {
314
+ if (
315
+ v &&
316
+ typeof v === 'object' &&
317
+ !Array.isArray(v) &&
318
+ /** @type {any} */ (v).__element
319
+ )
320
+ return jsx(/** @type {any} */ (v), depth);
321
+ return JSON.stringify(v);
322
+ }
323
+
324
+ /**
325
+ * JSX source for an element tree.
326
+ * @param {import('./_catalog.mjs').Tree} tree
327
+ * @param {number} depth
328
+ * @returns {string}
329
+ */
330
+ function jsx(tree, depth) {
331
+ const pad = ' '.repeat(depth);
332
+ const props = Object.entries(tree.props ?? {}).map(([k, v]) =>
333
+ typeof v === 'string' && !/[{}"\n]/.test(v)
334
+ ? `${k}="${v}"`
335
+ : v === true
336
+ ? k
337
+ : `${k}={${jsxValue(v, depth + 1)}}`,
338
+ );
339
+ const kids = /** @type {unknown[]} */ (
340
+ [].concat(/** @type {any} */ (tree.children ?? []))
341
+ );
342
+ const open = `<${tree.__element}${props.length ? ` ${props.join(' ')}` : ''}`;
343
+ if (!kids.length) return `${open} />`;
344
+ const inner = kids
345
+ .map(k =>
346
+ k && typeof k === 'object'
347
+ ? `${pad} ${jsx(/** @type {any} */ (k), depth + 1)}`
348
+ : `${pad} {${JSON.stringify(k)}}`,
349
+ )
350
+ .join('\n');
351
+ return `${open}>\n${inner}\n${pad}</${tree.__element}>`;
352
+ }
353
+
354
+ /**
355
+ * Write the theme-building page into the app: a page module that uses the
356
+ * app's own Astryx, with a light and dark switch, plus the template pages
357
+ * it shows, beside it.
358
+ * @param {import('./_settings.mjs').Ctx} ctx
359
+ * @param {string} slug
360
+ * @param {import('./_settings.mjs').ThemeData} data
361
+ * @param {string} dir absolute folder to write into
362
+ * @param {string | undefined} group
363
+ * @returns {{files: string[], components: number, skipped: string[]}}
364
+ */
365
+ export function writeShowcase(ctx, slug, data, dir, group) {
366
+ const {project} = ctx;
367
+ const {items, imports, skipped} = showcaseItems(project, group);
368
+ const ti = themeImports(ctx, slug, data, dir);
369
+ /** @type {Map<string, string[]>} */
370
+ const byModule = new Map();
371
+ /** @type {string[]} */
372
+ const files = [];
373
+ for (const [name, spec] of Object.entries(imports)) {
374
+ const m = /^\.\/templates\/([a-z0-9-]+)\.tsx$/.exec(spec);
375
+ if (m) {
376
+ const file = path.join(dir, `theme-preview-${m[1]}.tsx`);
377
+ fs.mkdirSync(dir, {recursive: true});
378
+ fs.copyFileSync(path.join(TEMPLATES_DIR, m[1], 'page.tsx'), file);
379
+ files.push(shown(project.cwd, file));
380
+ byModule.set(`./theme-preview-${m[1]}`, [`default as ${name}`]);
381
+ continue;
382
+ }
383
+ const list = byModule.get(spec) ?? [];
384
+ list.push(name);
385
+ byModule.set(spec, list);
386
+ }
387
+ const modeOnly = ti.mode === 'system' ? null : ti.mode;
388
+ /** @type {Map<string, Map<string, import('./_catalog.mjs').CatalogItem[]>>} */
389
+ const groups = new Map();
390
+ for (const it of items) {
391
+ const g = groups.get(it.group ?? '') ?? new Map();
392
+ const list = /** @type {import('./_catalog.mjs').CatalogItem[]} */ (
393
+ g.get(it.name) ?? []
394
+ );
395
+ if (!list.some(x => x.label === it.label)) list.push(it);
396
+ g.set(it.name, list);
397
+ groups.set(it.group ?? '', g);
398
+ }
399
+ const sections = [...groups]
400
+ .map(([g, comps]) => {
401
+ const cells = [...comps]
402
+ .map(([name, list]) => {
403
+ const body = list
404
+ .map(
405
+ it =>
406
+ ` <div className="tp-item">${it.label ? `\n <div className="tp-label">${it.label}</div>` : ''}\n <Safe>\n ${jsx(/** @type {any} */ (it.tree), 7)}\n </Safe>\n </div>`,
407
+ )
408
+ .join('\n');
409
+ return ` <div className="tp-cell">\n <div className="tp-name">${name}</div>\n <div className="tp-row">\n${body}\n </div>\n </div>`;
410
+ })
411
+ .join('\n');
412
+ return ` <section>\n <h2 className="tp-group">${g}</h2>\n <div className="${g === 'pages' ? 'tp-pages' : 'tp-grid'}">\n${cells}\n </div>\n </section>`;
413
+ })
414
+ .join('\n');
415
+ const css = `.tp-bar{position:sticky;top:0;z-index:100;display:flex;gap:14px;align-items:center;padding:8px 14px;font:12px ui-monospace,monospace;border-bottom:1px solid #8884;background:var(--color-background-body)}.tp-group{font:600 14px ui-monospace,monospace;margin:16px 14px 0;opacity:.75}.tp-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px;padding:14px}.tp-pages{display:grid;gap:14px;padding:14px}.tp-cell{border:1px dashed #8885;padding:10px;overflow:hidden}.tp-name{font:600 12px ui-monospace,monospace;opacity:.6;margin-bottom:8px}.tp-row{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-start}.tp-label{font:10px ui-monospace,monospace;opacity:.5}`;
416
+ const source = [
417
+ `// Written by \`astryx experimental theme preview ${slug}\`: a page for building the ${slug} theme.`,
418
+ '// Every component grouped, each variant side by side, overlays open, and full template pages.',
419
+ "'use client';",
420
+ '',
421
+ "import * as React from 'react';",
422
+ "import {Theme} from '@astryxdesign/core/theme';",
423
+ `import {${slug.replace(/-([a-z])/g, (_, c) => c.toUpperCase())}Theme as theme} from ${JSON.stringify(ti.module.replace(/\.js$/, ''))};`,
424
+ ...ti.css.map(c => `import ${JSON.stringify(c)};`),
425
+ ...[...byModule].map(
426
+ ([spec, names]) =>
427
+ `import {${names.join(', ')}} from ${JSON.stringify(spec)};`,
428
+ ),
429
+ '',
430
+ 'const noop = () => {};',
431
+ '',
432
+ '/** Shows nothing for a component that throws, so the rest of the page renders. */',
433
+ 'class Safe extends React.Component<{children: React.ReactNode}, {failed: boolean}> {',
434
+ ' state = {failed: false};',
435
+ ' static getDerivedStateFromError() {',
436
+ ' return {failed: true};',
437
+ ' }',
438
+ ' render() {',
439
+ ' return this.state.failed ? null : this.props.children;',
440
+ ' }',
441
+ '}',
442
+ '',
443
+ 'export default function ThemePreviewPage() {',
444
+ ` const [mode, setMode] = React.useState<'light' | 'dark'>(${JSON.stringify(modeOnly ?? 'light')});`,
445
+ ' return (',
446
+ ' <Theme theme={theme} mode={mode}>',
447
+ ` <style>{${JSON.stringify(css)}}</style>`,
448
+ " <div style={{background: 'var(--color-background-body)', color: 'var(--color-text-primary)', minHeight: '100vh'}}>",
449
+ ' <div className="tp-bar">',
450
+ ` <strong>${slug}</strong>`,
451
+ modeOnly
452
+ ? ` <span>${modeOnly} only</span>`
453
+ : " {(['light', 'dark'] as const).map(m => (\n <label key={m}>\n <input type=\"radio\" checked={mode === m} onChange={() => setMode(m)} /> {m}\n </label>\n ))}",
454
+ ' </div>',
455
+ sections,
456
+ ' </div>',
457
+ ' </Theme>',
458
+ ' );',
459
+ '}',
460
+ '',
461
+ ].join('\n');
462
+ fs.mkdirSync(dir, {recursive: true});
463
+ const main = path.join(dir, 'theme-preview.tsx');
464
+ fs.writeFileSync(
465
+ main,
466
+ source.replace(/onChange=\{noop\}/g, 'onChange={noop}'),
467
+ );
468
+ void SHOWCASE_GROUP_HELP;
469
+ return {
470
+ files: [shown(project.cwd, main), ...files],
471
+ components: new Set(items.map(i => i.name)).size,
472
+ skipped,
473
+ };
474
+ }
475
+
476
+ /**
477
+ * A PNG of an HTML file, with a Playwright the project has installed, else
478
+ * a Chrome or Chromium found on the machine. Null with a reason when neither
479
+ * is there.
480
+ * @param {import('./_project.mjs').ThemeProject} project
481
+ * @param {string} html absolute
482
+ * @param {string} png absolute
483
+ * @param {'light' | 'dark'} mode
484
+ * @returns {Promise<{ok: true, file: string} | {ok: false, reason: string}>}
485
+ */
486
+ export async function screenshot(project, html, png, mode) {
487
+ for (const pkg of ['playwright', 'playwright-core']) {
488
+ /** @type {string} */
489
+ let entry;
490
+ try {
491
+ entry = project.req.resolve(pkg);
492
+ } catch {
493
+ continue;
494
+ }
495
+ try {
496
+ const pw = await import(pathToFileURL(entry).href);
497
+ const chromium = pw.chromium ?? pw.default?.chromium;
498
+ const browser = await chromium.launch(
499
+ chromeBinary() ? {executablePath: chromeBinary()} : {},
500
+ );
501
+ try {
502
+ const page = await browser.newPage({
503
+ viewport: {width: 1280, height: 900},
504
+ colorScheme: mode,
505
+ });
506
+ await page.goto(pathToFileURL(html).href, {waitUntil: 'load'});
507
+ await page.screenshot({path: png, fullPage: true});
508
+ } finally {
509
+ await browser.close();
510
+ }
511
+ return {ok: true, file: shown(project.cwd, png)};
512
+ } catch {
513
+ // This Playwright has no browser to launch: try Chrome directly.
514
+ }
515
+ }
516
+ const chrome = chromeBinary();
517
+ if (chrome) {
518
+ const r = spawnSync(
519
+ chrome,
520
+ [
521
+ '--headless=new',
522
+ '--disable-gpu',
523
+ '--no-sandbox',
524
+ '--hide-scrollbars',
525
+ `--screenshot=${png}`,
526
+ '--window-size=1280,2400',
527
+ ...(mode === 'dark' ? ['--force-dark-mode'] : []),
528
+ pathToFileURL(html).href,
529
+ ],
530
+ {encoding: 'utf8', timeout: 60_000},
531
+ );
532
+ if (r.status === 0 && fs.existsSync(png))
533
+ return {ok: true, file: shown(project.cwd, png)};
534
+ }
535
+ return {
536
+ ok: false,
537
+ reason: `No browser was found to take the picture. Install Playwright with its browser (${installLine(project.cwd, ['playwright'])}, then npx playwright install chromium), or install Google Chrome or Chromium. The HTML preview needs neither.`,
538
+ };
539
+ }
540
+
541
+ /** A Chrome or Chromium on this machine, at a usual place or on PATH. */
542
+ function chromeBinary() {
543
+ const names = [
544
+ 'google-chrome',
545
+ 'google-chrome-stable',
546
+ 'chromium',
547
+ 'chromium-browser',
548
+ 'chrome',
549
+ ];
550
+ const fixed = [
551
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
552
+ '/Applications/Chromium.app/Contents/MacOS/Chromium',
553
+ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
554
+ 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
555
+ ];
556
+ for (const f of fixed) if (fs.existsSync(f)) return f;
557
+ for (const dir of (process.env.PATH ?? '').split(path.delimiter)) {
558
+ for (const n of names) {
559
+ const f = path.join(dir, n);
560
+ if (dir && fs.existsSync(f)) return f;
561
+ }
562
+ }
563
+ return null;
564
+ }