@astryxdesign/cli 0.7.15 → 0.7.16-canary.g3aa244b

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 (163) hide show
  1. package/README.md +5 -3
  2. package/api/build/_adapter.d.mts +1 -0
  3. package/api/build/blocks/blocks.d.mts +1 -0
  4. package/api/build/blocks/blocks.mjs +18 -1
  5. package/api/component/_adapter.d.mts +1 -1
  6. package/api/component/_adapter.mjs +28 -1
  7. package/api/doctor/_adapter.d.mts +35 -0
  8. package/api/doctor/_adapter.mjs +69 -0
  9. package/api/doctor/built-checks.mjs +1 -1
  10. package/api/doctor/doctor.d.mts +18 -0
  11. package/api/doctor/doctor.doc.mjs +1 -1
  12. package/api/doctor/doctor.mjs +104 -4
  13. package/api/doctor/theme-checks.mjs +6 -10
  14. package/api/integration/add-contribution.mjs +3 -3
  15. package/api/integration/pack-check.mjs +14 -8
  16. package/api/integration/validate-integration.mjs +1 -1
  17. package/api/search/_adapter.mjs +15 -16
  18. package/api/search/_entries.d.mts +2 -1
  19. package/api/search/_entries.mjs +28 -1
  20. package/api/swizzle/_moduleGraph.mjs +1 -1
  21. package/api/theme/_adapter.d.mts +5 -2
  22. package/api/theme/_adapter.mjs +43 -12
  23. package/api/theme/_fork.mjs +1 -1
  24. package/api/theme/build/build.d.mts +116 -32
  25. package/api/theme/build/build.mjs +449 -102
  26. package/api/theme/eject/eject.mjs +22 -1
  27. package/api/theme/template/template.d.mts +19 -0
  28. package/api/theme/template/template.mjs +102 -25
  29. package/api/theme/theme.type.d.mts +5 -1
  30. package/api/theme/theme.type.mjs +2 -1
  31. package/api/theme/themeBuild.doc.mjs +3 -3
  32. package/api/theme/themeEject.doc.mjs +1 -1
  33. package/api/theme/themeTemplate.doc.mjs +9 -3
  34. package/api/theme-edit/_adapter.d.mts +32 -2
  35. package/api/theme-edit/_adapter.mjs +264 -40
  36. package/api/theme-edit/_check.d.mts +93 -4
  37. package/api/theme-edit/_check.mjs +1727 -223
  38. package/api/theme-edit/_color.d.mts +2 -8
  39. package/api/theme-edit/_color.mjs +292 -219
  40. package/api/theme-edit/_compiler.d.mts +1 -0
  41. package/api/theme-edit/_compiler.mjs +20 -1
  42. package/api/theme-edit/_context.d.mts +31 -1
  43. package/api/theme-edit/_context.mjs +445 -41
  44. package/api/theme-edit/_css.d.mts +60 -1
  45. package/api/theme-edit/_css.mjs +404 -28
  46. package/api/theme-edit/_edit.d.mts +25 -0
  47. package/api/theme-edit/_edit.mjs +1532 -149
  48. package/api/theme-edit/_how-commands.d.mts +11 -26
  49. package/api/theme-edit/_how-commands.mjs +30 -2
  50. package/api/theme-edit/_how-question.d.mts +7 -0
  51. package/api/theme-edit/_how-question.mjs +1304 -176
  52. package/api/theme-edit/_how.mjs +144 -30
  53. package/api/theme-edit/_overview.mjs +2 -0
  54. package/api/theme-edit/_palette.d.mts +38 -0
  55. package/api/theme-edit/_palette.mjs +305 -71
  56. package/api/theme-edit/_parts.d.mts +33 -0
  57. package/api/theme-edit/_parts.mjs +138 -9
  58. package/api/theme-edit/_png.d.mts +18 -0
  59. package/api/theme-edit/_png.mjs +95 -14
  60. package/api/theme-edit/_preview-app.d.mts +36 -1
  61. package/api/theme-edit/_preview-app.mjs +1415 -96
  62. package/api/theme-edit/_preview.d.mts +64 -3
  63. package/api/theme-edit/_preview.mjs +514 -31
  64. package/api/theme-edit/_project.d.mts +11 -0
  65. package/api/theme-edit/_project.mjs +46 -12
  66. package/api/theme-edit/_settings.d.mts +278 -5
  67. package/api/theme-edit/_settings.mjs +2741 -195
  68. package/api/theme-edit/_tables.d.mts +24 -0
  69. package/api/theme-edit/_tables.mjs +211 -149
  70. package/api/theme-edit/_vet.d.mts +42 -0
  71. package/api/theme-edit/_vet.mjs +144 -0
  72. package/api/theme-edit/theme-edit.type.d.mts +20 -2
  73. package/api/theme-edit/theme-edit.type.mjs +6 -2
  74. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  75. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  76. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  77. package/api/upgrade/registry/registry.mjs +6 -1
  78. package/assets/codemods/parse.mjs +2 -2
  79. package/assets/docs/tree/single-component.doc.mjs +11 -2
  80. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  81. package/assets/docs.generated.json +2 -2
  82. package/assets/preview-app/next.config.mjs +7 -1
  83. package/assets/preview-app/package.json +1 -0
  84. package/assets/preview-app/src/app/globals.css +1 -0
  85. package/assets/self-audit.generated.json +1 -1
  86. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  87. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  88. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  89. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  90. package/assets/templates/components.generated.json +1 -1
  91. package/assets/templates/pages/dashboard/page.tsx +1 -1
  92. package/authoring/doctypes/_schema.d.mts +52 -5
  93. package/authoring/doctypes/_schema.mjs +62 -7
  94. package/authoring/doctypes/base/type.ts +10 -0
  95. package/authoring/doctypes/component/component.doc.mjs +1 -1
  96. package/authoring/doctypes/function/function.doc.mjs +6 -0
  97. package/authoring/doctypes/function/type.ts +3 -0
  98. package/authoring/doctypes/legacy.mjs +5 -1
  99. package/authoring/index.d.ts +1 -0
  100. package/authoring/shadcn/source-variants.d.mts +1 -1
  101. package/authoring/shadcn/source-variants.mjs +32 -10
  102. package/clients/cli/build-id.generated.json +1 -1
  103. package/clients/cli/commands/doctor.doc.mjs +2 -2
  104. package/clients/cli/commands/experimental/theme.mjs +239 -45
  105. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  106. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +2 -2
  107. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +2 -2
  108. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +3 -3
  109. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  110. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  111. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  112. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  113. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  114. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  115. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  116. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  117. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  118. package/clients/cli/commands/theme.mjs +190 -46
  119. package/clients/cli/formatters/index.mjs +7 -4
  120. package/clients/cli/lib/cli-error.mjs +9 -3
  121. package/clients/cli/lib/component-format.mjs +27 -9
  122. package/clients/cli/lib/json-shim.mjs +72 -2
  123. package/clients/cli/manifest.generated.json +1 -1
  124. package/clients/cli/run.mjs +49 -0
  125. package/foundation/agent-docs/agent-docs-target.d.mts +2 -6
  126. package/foundation/agent-docs/agent-docs-target.mjs +9 -17
  127. package/foundation/agent-docs/agent-docs.mjs +3 -2
  128. package/foundation/config/config-writer.mjs +2 -2
  129. package/foundation/config/project.mjs +60 -14
  130. package/foundation/discovery/component-discovery.mjs +5 -17
  131. package/foundation/discovery/icon-set-writer.mjs +1 -1
  132. package/foundation/discovery/module-exports.mjs +1 -15
  133. package/foundation/discovery/template-adapter.mjs +44 -19
  134. package/foundation/discovery/template-source-tree.mjs +3 -16
  135. package/foundation/discovery/theme-discovery.d.mts +5 -1
  136. package/foundation/discovery/theme-discovery.mjs +61 -43
  137. package/foundation/fs/exact-codec.d.mts +35 -0
  138. package/foundation/fs/exact-codec.mjs +148 -0
  139. package/foundation/fs/gather-cache.d.mts +15 -5
  140. package/foundation/fs/gather-cache.mjs +129 -31
  141. package/foundation/fs/paths.d.mts +39 -0
  142. package/foundation/fs/paths.mjs +44 -11
  143. package/foundation/fs/read-record.mjs +11 -1
  144. package/foundation/integrations/contribution-fixes.mjs +1 -16
  145. package/foundation/integrations/may-have-integrations.mjs +3 -2
  146. package/foundation/integrations/public-imports.mjs +1 -1
  147. package/foundation/render/embedded-imports.mjs +1 -1
  148. package/foundation/render/host-exit.d.mts +8 -0
  149. package/foundation/render/host-exit.mjs +11 -0
  150. package/foundation/render/page-host.mjs +56 -10
  151. package/foundation/render/page-worker.mjs +14 -0
  152. package/foundation/render/render-page.mjs +37 -2
  153. package/foundation/response/error-codes.d.mts +2 -1
  154. package/foundation/response/error-codes.d.ts +1 -0
  155. package/foundation/response/error-codes.doc.mjs +5 -0
  156. package/foundation/response/error-codes.mjs +3 -0
  157. package/foundation/response/json.d.mts +15 -0
  158. package/foundation/response/json.mjs +52 -1
  159. package/foundation/response/response-types.doc.mjs +1 -1
  160. package/foundation/runtime/lazy-dependencies.d.mts +14 -0
  161. package/foundation/runtime/lazy-dependencies.mjs +82 -0
  162. package/foundation/xle/browser.d.mts +2 -2
  163. package/package.json +7 -6
@@ -12,6 +12,7 @@
12
12
  * @position api/theme-edit — previews and pictures
13
13
  */
14
14
 
15
+ import {createHash} from 'node:crypto';
15
16
  import * as fs from 'node:fs';
16
17
  import * as path from 'node:path';
17
18
  import {spawnSync} from 'node:child_process';
@@ -24,17 +25,28 @@ import {
24
25
  } from './_catalog.mjs';
25
26
  import {
26
27
  catalogVariants,
27
- isItemOf,
28
+ demoProps,
29
+ needsParent,
28
30
  renderDir,
29
31
  renderGenerated,
30
32
  } from './_parts.mjs';
31
33
  import {OVERVIEW_SECTIONS} from './_overview.mjs';
32
- import {camel, fontPackages, modesOf, themeFiles, shown} from './_settings.mjs';
34
+ import {
35
+ FOLDER_JUNK,
36
+ folderIsEmpty,
37
+ camel,
38
+ fontPackages,
39
+ modesOf,
40
+ themeFiles,
41
+ shown,
42
+ } from './_settings.mjs';
33
43
  import {writeWhole} from './_palette.mjs';
44
+ import {cliVersion} from '../../foundation/release/run-context.mjs';
34
45
  import {importPathOf, installLine} from './_project.mjs';
35
- import {COLOR_PROP_PARTS, DIRECT, P} from './_tables.mjs';
46
+ import {COLOR_PROP_PARTS, DIRECT, P, wordTable} from './_tables.mjs';
36
47
  import {extractImportedPackages} from '../../foundation/discovery/template-needs.mjs';
37
48
  import {findNodeModulesPackage} from '../../foundation/fs/paths.mjs';
49
+ import {withListingCache} from '../../foundation/fs/listing-cache.mjs';
38
50
 
39
51
  const TEMPLATES_DIR = path.resolve(
40
52
  path.dirname(fileURLToPath(import.meta.url)),
@@ -185,9 +197,26 @@ function inParentOf(project, name) {
185
197
  const info = project.components[name];
186
198
  if (!info?.subComponentOf) return tree => tree;
187
199
  const wrapper = info.wrapper;
200
+ // A part of a parent that shows inline (a dialog's header) renders inside
201
+ // that parent shown open and inline, as Core's docs show it: alone, it
202
+ // acts as in a modal one (a dialog header takes focus as it mounts).
203
+ const of = info.subComponentOf;
204
+ const parent = project.components[of];
205
+ if (!wrapper && parent?.props?.isInline && parent.props.isOpen) {
206
+ const props = Object.fromEntries(
207
+ Object.entries(demoProps(project, of) ?? {}).filter(
208
+ ([k]) => k !== 'children',
209
+ ),
210
+ );
211
+ return tree => ({
212
+ __element: of,
213
+ props: {...props, isOpen: true, isInline: true},
214
+ children: [tree],
215
+ });
216
+ }
188
217
  // A part its parent does not list as an item, such as a heading of the
189
218
  // text family, renders on its own.
190
- if (!wrapper) return isItemOf(project, name) ? null : tree => tree;
219
+ if (!wrapper) return needsParent(project, name) ? null : tree => tree;
191
220
  if (project.components[wrapper.component]?.wrapper) return null;
192
221
  const props = Object.fromEntries(
193
222
  Object.entries(wrapper.props).filter(([k]) => !OPEN_PROPS.includes(k)),
@@ -214,6 +243,59 @@ function templateFiles(imports) {
214
243
  });
215
244
  }
216
245
 
246
+ /**
247
+ * The fonts stylesheet of the theme a theme is built on, when its package
248
+ * ships one (`@astryxdesign/theme-neutral/fonts.css` loads Figtree): naming
249
+ * a family does not load it, and the base theme's families apply until the
250
+ * theme sets its own. Once the theme's build names none of the families the
251
+ * sheet loads, it is left out.
252
+ * @param {import('./_settings.mjs').Ctx} ctx
253
+ * @param {import('./_settings.mjs').ThemeData} data
254
+ * @returns {string[]}
255
+ */
256
+ export function baseFontsCss(ctx, data) {
257
+ if (!data.like) return [];
258
+ const pkg = `@astryxdesign/theme-${data.like}`;
259
+ const sheet = `${pkg}/fonts.css`;
260
+ // Read off disk: the package must export the sheet for an app to import
261
+ // it.
262
+ const found = findNodeModulesPackage(ctx.project.cwd, pkg);
263
+ /** @type {string} */
264
+ let text;
265
+ try {
266
+ if (!found) return [];
267
+ const exportsMap = JSON.parse(
268
+ fs.readFileSync(path.join(found.packageDir, 'package.json'), 'utf8'),
269
+ ).exports;
270
+ if (
271
+ !exportsMap ||
272
+ typeof exportsMap !== 'object' ||
273
+ !('./fonts.css' in exportsMap)
274
+ )
275
+ return [];
276
+ text = fs.readFileSync(path.join(found.packageDir, 'fonts.css'), 'utf8');
277
+ } catch {
278
+ return [];
279
+ }
280
+ // The families the sheet loads; with the theme's build at hand, the sheet
281
+ // is imported only while the build still names one of them.
282
+ const families = [...text.matchAll(/family=([^:&'")]+)/g)].map(m =>
283
+ decodeURIComponent(m[1].replace(/\+/g, ' ')),
284
+ );
285
+ /** @type {string | null} */
286
+ let built = null;
287
+ try {
288
+ built = fs.readFileSync(themeFiles(ctx.project.cwd, data.name).css, 'utf8');
289
+ } catch {
290
+ // Not built yet: the base families may still apply.
291
+ }
292
+ if (built != null && families.length) {
293
+ const css = built;
294
+ if (!families.some(f => css.includes(f))) return [];
295
+ }
296
+ return [sheet];
297
+ }
298
+
217
299
  /**
218
300
  * How a generated page imports the theme: its built module, its stylesheet,
219
301
  * and the stylesheets of open fonts the project has installed.
@@ -235,13 +317,162 @@ export function themeImports(ctx, slug, data, fromDir) {
235
317
  .map(x => `${x.pkg}/index.css`);
236
318
  return {
237
319
  module: rel(f.js),
238
- css: [rel(f.css), ...fonts],
320
+ css: [rel(f.css), ...baseFontsCss(ctx, data), ...fonts],
239
321
  mode: /** @type {'system' | 'light' | 'dark'} */ (
240
322
  modes.length > 1 ? 'system' : modes[0]
241
323
  ),
242
324
  };
243
325
  }
244
326
 
327
+ /**
328
+ * The inputs a page was rendered from and a hash of the page above it,
329
+ * recorded at the end of the page.
330
+ */
331
+ const RENDER_STAMP = /<!-- astryx: render of ([0-9a-f]{24}) ([0-9a-f]{16}) -->/;
332
+
333
+ /** @type {Map<string, string>} */
334
+ const treeKeys = new Map();
335
+
336
+ /**
337
+ * A cheap fingerprint of the files a package runs from: each file's path,
338
+ * size and modification time under its folder (node_modules left out), so a
339
+ * linked or patched copy with the same version reads as another. Once per
340
+ * process for each folder.
341
+ * @param {string | null | undefined} dir
342
+ * @returns {string}
343
+ */
344
+ function treeKey(dir) {
345
+ if (!dir) return 'none';
346
+ const known = treeKeys.get(dir);
347
+ if (known) return known;
348
+ const h = createHash('sha256');
349
+ /** @param {string} d */
350
+ const walk = d => {
351
+ let entries;
352
+ try {
353
+ entries = fs.readdirSync(d, {withFileTypes: true});
354
+ } catch {
355
+ return;
356
+ }
357
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
358
+ for (const e of entries) {
359
+ if (e.name === 'node_modules' || e.name.startsWith('.')) continue;
360
+ const p = path.join(d, e.name);
361
+ if (e.isDirectory()) walk(p);
362
+ else if (e.isFile()) {
363
+ try {
364
+ const st = fs.statSync(p);
365
+ h.update(`${path.relative(dir, p)}\0${st.size}\0${st.mtimeMs}\0`);
366
+ } catch {
367
+ // Gone meanwhile.
368
+ }
369
+ }
370
+ }
371
+ };
372
+ walk(dir);
373
+ const key = h.digest('hex').slice(0, 16);
374
+ treeKeys.set(dir, key);
375
+ return key;
376
+ }
377
+
378
+ /**
379
+ * The folder of an installed package, resolved from the project, or null.
380
+ * @param {string} cwd
381
+ * @param {string} name
382
+ */
383
+ function packageDirOf(cwd, name) {
384
+ try {
385
+ return findNodeModulesPackage(cwd, name)?.packageDir ?? null;
386
+ } catch {
387
+ return null;
388
+ }
389
+ }
390
+
391
+ /** @param {string} text */
392
+ const bodyHash = text =>
393
+ createHash('sha256').update(text).digest('hex').slice(0, 16);
394
+
395
+ /**
396
+ * A key for everything a page render reads: the CLI, Core (its version and
397
+ * stylesheet, and the files it runs from), the base theme package's files,
398
+ * the generated page source, and the theme's built stylesheet and module.
399
+ * The same key means the same page.
400
+ * @param {import('./_project.mjs').ThemeProject} project
401
+ * @param {string} slug
402
+ * @param {string} source
403
+ * @param {string | null | undefined} [like] the base theme
404
+ * @returns {string}
405
+ */
406
+ function renderKey(project, slug, source, like) {
407
+ const f = themeFiles(project.cwd, slug);
408
+ const h = createHash('sha256')
409
+ .update(cliVersion())
410
+ .update('\0')
411
+ .update(String(project.coreKey ?? ''))
412
+ .update('\0')
413
+ .update(treeKey(path.join(project.coreDir, 'dist')))
414
+ .update('\0')
415
+ .update(
416
+ like
417
+ ? treeKey(packageDirOf(project.cwd, `@astryxdesign/theme-${like}`))
418
+ : 'none',
419
+ )
420
+ .update('\0')
421
+ .update(source);
422
+ for (const file of [f.css, f.js]) {
423
+ h.update('\0');
424
+ try {
425
+ h.update(fs.readFileSync(file));
426
+ } catch {
427
+ h.update('missing');
428
+ }
429
+ }
430
+ return h.digest('hex').slice(0, 24);
431
+ }
432
+
433
+ /**
434
+ * Whether `out` is a page rendered from `key` (a no-op show renders
435
+ * nothing again).
436
+ * @param {string} out
437
+ * @param {string} key
438
+ */
439
+ function renderedFrom(out, key) {
440
+ try {
441
+ const st = fs.lstatSync(out);
442
+ if (!st.isFile()) return false;
443
+ const text = fs.readFileSync(out, 'utf8');
444
+ const m = RENDER_STAMP.exec(text);
445
+ // The page above the comment is the one rendered: an edit by hand, or
446
+ // a comment pasted under another page, is rendered again.
447
+ // Nothing may follow the comment but the sheet's own build stamp
448
+ // (written after it by show): text added after it is rendered over.
449
+ const after = m
450
+ ? text
451
+ .slice(m.index + m[0].length)
452
+ .replace(/<!-- astryx: sheet of build [0-9a-f]{16} -->/, '')
453
+ : '';
454
+ return (
455
+ m != null &&
456
+ m[1] === key &&
457
+ after.trim() === '' &&
458
+ m[2] === bodyHash(text.slice(0, m.index).trimEnd())
459
+ );
460
+ } catch {
461
+ return false;
462
+ }
463
+ }
464
+
465
+ /**
466
+ * The page with its render key recorded at its end (after the closing tag:
467
+ * a comment before the doctype would put it in quirks mode).
468
+ * @param {string} html
469
+ * @param {string} key
470
+ */
471
+ const withRenderKey = (html, key) => {
472
+ const body = html.replace(RENDER_STAMP, '').trimEnd();
473
+ return `${body}\n<!-- astryx: render of ${key} ${bodyHash(body)} -->\n`;
474
+ };
475
+
245
476
  /**
246
477
  * Render the sample app page with the theme to themes/<slug>/preview.html.
247
478
  * @param {import('./_settings.mjs').Ctx} ctx
@@ -263,10 +494,13 @@ export async function renderPreview(ctx, slug, data) {
263
494
  layout: 'page',
264
495
  title: `${slug}: sample page`,
265
496
  });
266
- const {html} = await renderGenerated(project, `preview-${slug}.mjs`, source);
267
497
  const out = themeFiles(project.cwd, slug).preview;
498
+ // Rendered from the same inputs before: the page is as it would be.
499
+ const key = renderKey(project, slug, source, data.like);
500
+ if (renderedFrom(out, key)) return shown(project.cwd, out);
501
+ const {html} = await renderGenerated(project, `preview-${slug}.mjs`, source);
268
502
  // Written whole and renamed in, never through a link.
269
- writeWhole(out, html);
503
+ writeWhole(out, withRenderKey(html, key));
270
504
  return shown(project.cwd, out);
271
505
  }
272
506
 
@@ -288,12 +522,6 @@ export async function renderSheet(ctx, slug, data, options = {}) {
288
522
  layout: 'sheet',
289
523
  title: `${slug}: every component${options.group ? ` (${options.group})` : ''}`,
290
524
  });
291
- const {html} = await renderGenerated(
292
- project,
293
- `sheet-${slug}.mjs`,
294
- source,
295
- templateFiles(imports),
296
- );
297
525
  // One section goes to its own file, so the full sheet stays whole.
298
526
  const full = themeFiles(project.cwd, slug).sheet;
299
527
  const out =
@@ -301,9 +529,23 @@ export async function renderSheet(ctx, slug, data, options = {}) {
301
529
  (options.group
302
530
  ? path.join(path.dirname(full), `sheet-${options.group}.html`)
303
531
  : full);
532
+ const key = renderKey(project, slug, source, data.like);
533
+ const result = {
534
+ file: shown(project.cwd, out),
535
+ components: new Set(items.map(i => i.name)).size,
536
+ skipped,
537
+ };
538
+ // Rendered from the same inputs before: the sheet is as it would be.
539
+ if (renderedFrom(out, key)) return result;
540
+ const {html} = await renderGenerated(
541
+ project,
542
+ `sheet-${slug}.mjs`,
543
+ source,
544
+ templateFiles(imports),
545
+ );
304
546
  fs.mkdirSync(path.dirname(out), {recursive: true});
305
547
  // Written whole and renamed in, never through a link.
306
- writeWhole(out, html);
548
+ writeWhole(out, withRenderKey(html, key));
307
549
  return {
308
550
  file: shown(project.cwd, out),
309
551
  components: new Set(items.map(i => i.name)).size,
@@ -460,11 +702,11 @@ function componentTable(project, trees) {
460
702
  const SAFE = [
461
703
  '/** Shows a short note for a component that throws, so the rest of the page renders. */',
462
704
  'class Safe extends React.Component<{name: string, children: React.ReactNode}, {failed: boolean}> {',
463
- ' state = {failed: false};',
705
+ ' override state = {failed: false};',
464
706
  ' static getDerivedStateFromError() {',
465
707
  ' return {failed: true};',
466
708
  ' }',
467
- ' render() {',
709
+ ' override render() {',
468
710
  ' return this.state.failed ? <div className="tp-note">{this.props.name} could not render here</div> : this.props.children;',
469
711
  ' }',
470
712
  '}',
@@ -567,10 +809,12 @@ const usesSource = v =>
567
809
  Object.values(/** @type {object} */ (v)).some(usesSource);
568
810
 
569
811
  /** The heading of each group on the components page. */
570
- const GROUP_TITLES = /** @type {Record<string, string>} */ ({
571
- data: 'data display',
572
- overlays: 'overlays (shown open)',
573
- });
812
+ const GROUP_TITLES = wordTable(
813
+ /** @type {Record<string, string>} */ ({
814
+ data: 'data display',
815
+ overlays: 'overlays (shown open)',
816
+ }),
817
+ );
574
818
 
575
819
  /**
576
820
  * A cell with the component's name. A cell whose parts show nothing on
@@ -650,7 +894,19 @@ const PAGE_SKIP = new Set([
650
894
  * @param {{theme?: string | null, C?: import('./_compiler.mjs').Compiler}} [options]
651
895
  * @returns {{source: string, components: number}}
652
896
  */
653
- export function componentsPageSource(project, {theme = null, C} = {}) {
897
+ export function componentsPageSource(project, options = {}) {
898
+ // A name that Core's docs lack resolves by walking Core's source tree. One
899
+ // listing cache reads each folder once for the page, not once per name.
900
+ return withListingCache(() => componentsPage(project, options));
901
+ }
902
+
903
+ /**
904
+ * {@link componentsPageSource}'s work, inside its listing cache.
905
+ * @param {import('./_project.mjs').ThemeProject} project
906
+ * @param {{theme?: string | null, C?: import('./_compiler.mjs').Compiler}} options
907
+ * @returns {{source: string, components: number}}
908
+ */
909
+ function componentsPage(project, {theme = null, C}) {
654
910
  const items = showcaseItems(project, undefined)
655
911
  .items.filter(
656
912
  it =>
@@ -727,10 +983,22 @@ export function componentsPageSource(project, {theme = null, C} = {}) {
727
983
  * boundary, so one part that throws never blanks the page. The preview
728
984
  * route is the app shell, so the page has no shell of its own.
729
985
  * @param {import('./_project.mjs').ThemeProject} project
730
- * @param {{theme?: string | null}} [options]
986
+ * @param {{theme?: string | null, colors?: boolean}} [options] `colors`:
987
+ * the preview has a Colors page, so the header points to it
988
+ * @returns {string}
989
+ */
990
+ export function overviewPageSource(project, options = {}) {
991
+ // One listing cache for the page's names, as componentsPageSource holds.
992
+ return withListingCache(() => overviewPage(project, options));
993
+ }
994
+
995
+ /**
996
+ * {@link overviewPageSource}'s work, inside its listing cache.
997
+ * @param {import('./_project.mjs').ThemeProject} project
998
+ * @param {{theme?: string | null, colors?: boolean}} options
731
999
  * @returns {string}
732
1000
  */
733
- export function overviewPageSource(project, {theme = null} = {}) {
1001
+ function overviewPage(project, {theme = null, colors = false}) {
734
1002
  const sections = OVERVIEW_SECTIONS.map(x => ({
735
1003
  title: x.title,
736
1004
  tree: /** @type {import('./_catalog.mjs').Tree | undefined} */ (
@@ -786,8 +1054,38 @@ export function overviewPageSource(project, {theme = null} = {}) {
786
1054
  ' React.useEffect(() => {',
787
1055
  ' if (!ref.current) return;',
788
1056
  ' const style = getComputedStyle(ref.current);',
789
- " const first = (token: string) => style.getPropertyValue(token).split(',')[0].replace(/[\"']/g, '').trim() || 'default';",
790
- " setFonts(`Body: ${first('--font-family-body')}. Headings: ${first('--font-family-heading')}.`);",
1057
+ " const first = (token: string) => (style.getPropertyValue(token).split(',')[0] ?? '').replace(/[\"']/g, '').trim() || 'default';",
1058
+ ' // A family the browser does not have measures as its fallback does.',
1059
+ ' const GENERIC = /^(default|serif|sans-serif|monospace|cursive|fantasy|system-ui|ui-[a-z-]+|math|emoji|fangsong)$/i;',
1060
+ ' const missing = (family: string) => {',
1061
+ ' if (GENERIC.test(family)) return false;',
1062
+ " const ctx = document.createElement('canvas').getContext('2d');",
1063
+ ' if (!ctx) return false;',
1064
+ " const sample = 'mmmmmmmmmwwwwwww1234567890';",
1065
+ " return ['monospace', 'serif'].every(fallback => {",
1066
+ ' ctx.font = `48px ${fallback}`;',
1067
+ ' const plain = ctx.measureText(sample).width;',
1068
+ ' ctx.font = `48px "${family}", ${fallback}`;',
1069
+ ' return ctx.measureText(sample).width === plain;',
1070
+ ' });',
1071
+ ' };',
1072
+ ' const shown = (token: string) => { const f = first(token); return missing(f) ? `${f} (not installed here)` : f; };',
1073
+ " const write = () => setFonts(`Body: ${shown('--font-family-body')}. Headings: ${shown('--font-family-heading')}.`);",
1074
+ ' write();',
1075
+ ' // Read again when the theme changes live (a stylesheet or theme',
1076
+ ' // update while the page is open) and when a font finishes loading.',
1077
+ ' document.fonts?.ready.then(write);',
1078
+ " document.fonts?.addEventListener?.('loadingdone', write);",
1079
+ ' let queued = 0;',
1080
+ ' const soon = () => { if (!queued) queued = requestAnimationFrame(() => { queued = 0; write(); }); };',
1081
+ ' const watch = new MutationObserver(soon);',
1082
+ ' watch.observe(document.head, {childList: true, subtree: true, characterData: true});',
1083
+ " watch.observe(document.documentElement, {attributes: true, subtree: true, attributeFilter: ['style', 'class', 'data-theme']});",
1084
+ ' return () => {',
1085
+ ' watch.disconnect();',
1086
+ ' cancelAnimationFrame(queued);',
1087
+ " document.fonts?.removeEventListener?.('loadingdone', write);",
1088
+ ' };',
791
1089
  ' }, []);',
792
1090
  ' return (',
793
1091
  " <div ref={ref} style={{color: 'var(--color-text-secondary)', fontSize: 13}}>",
@@ -812,7 +1110,12 @@ export function overviewPageSource(project, {theme = null} = {}) {
812
1110
  ' {s.name}',
813
1111
  ' </div>',
814
1112
  ' ))}',
815
- ' <div className="tp-swatch" style={{alignSelf: \'center\'}}>Every shade: the Colors page</div>',
1113
+ // The Colors page is there only for a theme with generated colors.
1114
+ ...(colors
1115
+ ? [
1116
+ ' <div className="tp-swatch" style={{alignSelf: \'center\'}}>Every shade: the Colors page</div>',
1117
+ ]
1118
+ : []),
816
1119
  ' </div>',
817
1120
  ' </header>',
818
1121
  body,
@@ -839,7 +1142,6 @@ export function colorsPageSource({slug, module, seeds, uses}) {
839
1142
  '// `astryx experimental theme editor set` rewrites it with every change.',
840
1143
  "'use client';",
841
1144
  '',
842
- "import * as React from 'react';",
843
1145
  ];
844
1146
  const text = {color: 'var(--color-text-primary)'};
845
1147
  const page = {
@@ -891,7 +1193,7 @@ export function colorsPageSource({slug, module, seeds, uses}) {
891
1193
  " <h2 style={{margin: 0, fontSize: 20, textTransform: 'capitalize'}}>",
892
1194
  ' {name}',
893
1195
  ' {SEEDS[name] ? (',
894
- " <span style={{marginLeft: 8, fontSize: 14, fontWeight: 400, color: 'var(--color-text-secondary)'}}>",
1196
+ " <span style={{marginLeft: 8, fontSize: 14, fontWeight: 400, textTransform: 'none', color: 'var(--color-text-secondary)'}}>",
895
1197
  ' from {SEEDS[name]}',
896
1198
  ' </span>',
897
1199
  ' ) : null}',
@@ -984,7 +1286,7 @@ export function previewRouteSource({
984
1286
  ' ))}',
985
1287
  ' </SideNav>',
986
1288
  ' }>',
987
- ' <current.Page />',
1289
+ ' {ready ? <current.Page /> : null}',
988
1290
  ' </AppShell>',
989
1291
  ' </div>',
990
1292
  ];
@@ -999,7 +1301,13 @@ export function previewRouteSource({
999
1301
  "import {TopNav} from '@astryxdesign/core/TopNav';",
1000
1302
  ...(theme
1001
1303
  ? [
1002
- "import {SegmentedControl, SegmentedControlItem} from '@astryxdesign/core/SegmentedControl';",
1304
+ // The mode switch only for a theme with both modes: an import the
1305
+ // route does not draw fails an app with noUnusedLocals.
1306
+ ...(mode.length
1307
+ ? [
1308
+ "import {SegmentedControl, SegmentedControlItem} from '@astryxdesign/core/SegmentedControl';",
1309
+ ]
1310
+ : []),
1003
1311
  "import {Theme} from '@astryxdesign/core/theme';",
1004
1312
  `import {${camelName(theme.name)}Theme as theme} from ${JSON.stringify(theme.module.replace(/\.js$/, ''))};`,
1005
1313
  ...theme.css.map(c => `import ${JSON.stringify(c)};`),
@@ -1028,6 +1336,10 @@ export function previewRouteSource({
1028
1336
  '',
1029
1337
  'export default function ThemePreviewPage() {',
1030
1338
  ' const [page, setPage] = React.useState(PAGES[0]?.id);',
1339
+ // Pages render only in the browser: some components crash a server
1340
+ // render, and Next prerenders a client page's first state.
1341
+ ' const [ready, setReady] = React.useState(false);',
1342
+ ' React.useEffect(() => setReady(true), []);',
1031
1343
  ...(theme
1032
1344
  ? [
1033
1345
  oneMode
@@ -1035,7 +1347,8 @@ export function previewRouteSource({
1035
1347
  : " const [mode, setMode] = React.useState<Mode>('system');",
1036
1348
  ]
1037
1349
  : []),
1038
- ' const current = PAGES.find(p => p.id === page) ?? PAGES[0];',
1350
+ // The route always has a page; the cast keeps noUncheckedIndexedAccess apps building.
1351
+ ' const current = (PAGES.find(p => p.id === page) ?? PAGES[0]) as (typeof PAGES)[number];',
1039
1352
  ' return (',
1040
1353
  ...(theme
1041
1354
  ? [' <Theme theme={theme} mode={mode}>', ...shell, ' </Theme>']
@@ -1165,3 +1478,173 @@ function chromeBinary() {
1165
1478
  }
1166
1479
  return null;
1167
1480
  }
1481
+
1482
+ /** The first line of every file the editor writes into a theme's app copy. */
1483
+ export const APP_COPY_MARK = 'Written by `astryx experimental theme editor`';
1484
+
1485
+ /**
1486
+ * The app's copy of an editor theme: a standard local theme in
1487
+ * src/themes/<theme>/ (a descriptor, a source that re-exports the built
1488
+ * module, the built module, its stylesheet and font stylesheet), the shape
1489
+ * `astryx theme add <theme>` reads, so the theme goes into the app with the
1490
+ * stable theme commands. It is written again after every build of the
1491
+ * theme, never edited by hand. A folder there that is not the editor's own
1492
+ * copy is left alone: returns null then, else the folder.
1493
+ * The built module and stylesheet are written whole: a local theme's source
1494
+ * may import only files inside its own folder.
1495
+ * @param {import('./_settings.mjs').Ctx} ctx
1496
+ * @param {string} slug
1497
+ * @param {import('./_settings.mjs').ThemeData} data
1498
+ * @returns {string | null}
1499
+ */
1500
+ export function writeAppCopy(ctx, slug, data) {
1501
+ return writeAppCopyAt(
1502
+ ctx.project.cwd,
1503
+ slug,
1504
+ themeImports(
1505
+ ctx,
1506
+ slug,
1507
+ data,
1508
+ path.join(ctx.project.cwd, 'src', 'themes', slug),
1509
+ ).css.slice(1),
1510
+ );
1511
+ }
1512
+
1513
+ /**
1514
+ * {@link writeAppCopy} with the font stylesheets given, or null to keep the
1515
+ * copy's own (a compile, which changes no setting).
1516
+ * @param {string} cwd
1517
+ * @param {string} slug
1518
+ * @param {string[] | null} fontsCss
1519
+ * @returns {string | null}
1520
+ */
1521
+ export function writeAppCopyAt(cwd, slug, fontsCss) {
1522
+ const f = themeFiles(cwd, slug);
1523
+ const dir = path.join(cwd, 'src', 'themes', slug);
1524
+ const name = `${camel(slug)}Theme`;
1525
+ const first = !fs.existsSync(path.join(dir, `${name}.doc.mjs`));
1526
+ if (!fs.existsSync(f.js) || !fs.existsSync(f.css)) return null;
1527
+ // The copy's source, as the stable build's header names it.
1528
+ const source = `src/themes/${slug}/${name}.ts`;
1529
+ // Only the editor's own copy is written over.
1530
+ if (appCopyBlocker(cwd, slug) !== null) return null;
1531
+ const head = (/** @type {string} */ open, /** @type {string} */ close) =>
1532
+ `${open} ${APP_COPY_MARK} after every build of themes/${slug}/; do not edit it here. Change the theme with the editor. ${close}\n`;
1533
+ const keptFonts = path.join(dir, `${slug}.fonts.css`);
1534
+ const fonts =
1535
+ fontsCss ??
1536
+ (fs.existsSync(keptFonts)
1537
+ ? [
1538
+ ...fs.readFileSync(keptFonts, 'utf8').matchAll(/@import "([^"]+)";/g),
1539
+ ].map(m => m[1])
1540
+ : []);
1541
+ // A built file as `theme build` of the copy's source writes it: the
1542
+ // editor's build of the same theme, with the header naming that source.
1543
+ const asBuilt = (/** @type {string} */ text) =>
1544
+ text
1545
+ .replace(/^( \* Source: ).*$/m, `$1${source}`)
1546
+ .replace(/^( \* Command: ).*$/m, `$1astryx theme build ${source}`);
1547
+ /** @type {Record<string, string>} */
1548
+ const built = {};
1549
+ for (const ext of APP_COPY_BUILT) {
1550
+ const from = path.join(f.dir, `${slug}${ext}`);
1551
+ if (fs.existsSync(from))
1552
+ built[`${slug}${ext}`] = asBuilt(fs.readFileSync(from, 'utf8'));
1553
+ }
1554
+ const files = {
1555
+ [`${name}.doc.mjs`]: `${head('//', '')}\n/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {\n type: 'theme',\n name: ${JSON.stringify(slug)},\n displayName: ${JSON.stringify(slug)},\n description: ${JSON.stringify(`The ${slug} theme, made with the theme editor (themes/${slug}/).`)},\n maintained: false,\n};\n`,
1556
+ [`${name}.ts`]: `${head('//', '')}export {${name}} from './${slug}';\n`,
1557
+ ...built,
1558
+ ...(fonts.length
1559
+ ? {
1560
+ [`${slug}.fonts.css`]: `${head('/*', '*/')}${fonts.map(c => `@import ${JSON.stringify(c)};`).join('\n')}\n`,
1561
+ }
1562
+ : {}),
1563
+ };
1564
+ fs.mkdirSync(dir, {recursive: true});
1565
+ for (const [n, text] of Object.entries(files)) {
1566
+ const file = path.join(dir, n);
1567
+ if (fs.existsSync(file) && fs.readFileSync(file, 'utf8') === text) continue;
1568
+ writeWhole(file, text);
1569
+ }
1570
+ // A file an earlier copy had (a font stylesheet no longer needed) goes;
1571
+ // system files stay.
1572
+ for (const n of fs.readdirSync(dir))
1573
+ if (!(n in files) && !FOLDER_JUNK.has(n))
1574
+ fs.rmSync(path.join(dir, n), {force: true});
1575
+ // The first write is named in the command's result; later ones are not.
1576
+ if (first)
1577
+ FIRST_COPIES.set(
1578
+ `${path.resolve(cwd)}\0${slug}`,
1579
+ Object.keys(files)
1580
+ .sort()
1581
+ .map(n =>
1582
+ path.relative(cwd, path.join(dir, n)).split(path.sep).join('/'),
1583
+ ),
1584
+ );
1585
+ return dir;
1586
+ }
1587
+
1588
+ /**
1589
+ * Why the editor will not write a theme's app copy, or null when it will:
1590
+ * the folder is not there yet, or its descriptor carries the editor's mark
1591
+ * and it holds only the copy's own files (system files such as .DS_Store
1592
+ * aside). Otherwise the name of what is in the way (a file of yours), or
1593
+ * the folder itself when it is not the editor's copy. Built bytes are not
1594
+ * compared, so a stable rebuild of the copy leaves it the editor's. The one
1595
+ * test the copy's writer and `wiring` both use.
1596
+ * @param {string} cwd
1597
+ * @param {string} slug
1598
+ * @returns {string | null}
1599
+ */
1600
+ export function appCopyBlocker(cwd, slug) {
1601
+ const dir = path.join(cwd, 'src', 'themes', slug);
1602
+ const name = `${camel(slug)}Theme`;
1603
+ const rel = path.relative(cwd, dir).split(path.sep).join('/');
1604
+ if (folderIsEmpty(dir)) return null;
1605
+ /** @type {string[]} */
1606
+ let names;
1607
+ try {
1608
+ names = fs.readdirSync(dir);
1609
+ } catch {
1610
+ return rel;
1611
+ }
1612
+ /** @type {boolean} */
1613
+ let marked;
1614
+ try {
1615
+ marked = fs
1616
+ .readFileSync(path.join(dir, `${name}.doc.mjs`), 'utf8')
1617
+ .includes(APP_COPY_MARK);
1618
+ } catch {
1619
+ marked = false;
1620
+ }
1621
+ if (!marked) return rel;
1622
+ const own = new Set([
1623
+ `${name}.doc.mjs`,
1624
+ `${name}.ts`,
1625
+ `${slug}.fonts.css`,
1626
+ ...APP_COPY_BUILT.map(ext => `${slug}${ext}`),
1627
+ ]);
1628
+ const other = names.find(n => !own.has(n) && !FOLDER_JUNK.has(n));
1629
+ return other ? `${rel}/${other}` : null;
1630
+ }
1631
+
1632
+ /** The build outputs of a theme, by their ending after `<theme>`. */
1633
+ const APP_COPY_BUILT = ['.css', '.css.d.ts', '.js', '.d.ts', '.variants.d.ts'];
1634
+
1635
+ /** App copies written for the first time in this process, by app and theme. @type {Map<string, string[]>} */
1636
+ const FIRST_COPIES = new Map();
1637
+
1638
+ /**
1639
+ * The files of a theme's app copy when this command wrote it for the first
1640
+ * time (then forgotten, so one result names them), else null.
1641
+ * @param {string} cwd
1642
+ * @param {string} slug
1643
+ * @returns {string[] | null}
1644
+ */
1645
+ export function takeFirstAppCopy(cwd, slug) {
1646
+ const key = `${path.resolve(cwd)}\0${slug}`;
1647
+ const wrote = FIRST_COPIES.get(key) ?? null;
1648
+ FIRST_COPIES.delete(key);
1649
+ return wrote;
1650
+ }