@astryxdesign/cli 0.7.16-canary.ge95b87c → 0.7.16

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 (120) hide show
  1. package/CHANGELOG.md +369 -0
  2. package/README.md +1 -1
  3. package/api/build/_adapter.d.mts +9 -0
  4. package/api/build/_adapter.mjs +24 -0
  5. package/api/build/kit/shell.weights.json +1 -0
  6. package/api/build/kit/shellcall.d.mts +26 -0
  7. package/api/build/kit/shellcall.mjs +87 -0
  8. package/api/build/kit/start.mjs +67 -4
  9. package/api/build/kit/weights.d.mts +15 -0
  10. package/api/build/kit/weights.mjs +27 -0
  11. package/api/component/__fixtures__/resolutions/modules.txt +1 -1
  12. package/api/doctor/_adapter.d.mts +3 -2
  13. package/api/doctor/_adapter.mjs +7 -1
  14. package/api/doctor/doctor.d.mts +8 -0
  15. package/api/doctor/doctor.mjs +53 -8
  16. package/api/doctor/theme-checks.mjs +157 -8
  17. package/api/icon/_adapter.d.mts +7 -3
  18. package/api/icon/_adapter.mjs +12 -3
  19. package/api/icon/icon.type.d.mts +15 -0
  20. package/api/icon/icon.type.mjs +10 -3
  21. package/api/icon/iconUse.doc.mjs +19 -5
  22. package/api/icon/list/list.mjs +7 -1
  23. package/api/icon/use/use.d.mts +8 -5
  24. package/api/icon/use/use.mjs +95 -13
  25. package/api/init/run/run.mjs +1 -0
  26. package/api/template/template.type.d.mts +6 -2
  27. package/api/template/template.type.mjs +2 -1
  28. package/api/theme/_adapter.mjs +16 -2
  29. package/api/theme/build/build.d.mts +10 -6
  30. package/api/theme/build/build.mjs +42 -29
  31. package/api/theme/generateTonalPalette.doc.mjs +2 -2
  32. package/api/theme/palette/generate/generator.mjs +141 -2
  33. package/api/theme/theme.type.d.mts +39 -0
  34. package/api/theme/theme.type.mjs +21 -0
  35. package/api/theme/themeBuild.doc.mjs +1 -1
  36. package/api/theme/themePaletteGenerate.doc.mjs +1 -1
  37. package/api/theme-edit/_adapter.d.mts +1 -0
  38. package/api/theme-edit/_adapter.mjs +79 -21
  39. package/api/theme-edit/_check.d.mts +25 -2
  40. package/api/theme-edit/_check.mjs +251 -61
  41. package/api/theme-edit/_context.d.mts +2 -1
  42. package/api/theme-edit/_context.mjs +19 -1
  43. package/api/theme-edit/_edit.d.mts +16 -0
  44. package/api/theme-edit/_edit.mjs +360 -59
  45. package/api/theme-edit/_how-question.d.mts +8 -0
  46. package/api/theme-edit/_how-question.mjs +169 -22
  47. package/api/theme-edit/_marks.d.mts +13 -0
  48. package/api/theme-edit/_marks.mjs +15 -0
  49. package/api/theme-edit/_palette.d.mts +27 -0
  50. package/api/theme-edit/_palette.mjs +112 -8
  51. package/api/theme-edit/_preview-app.d.mts +46 -1
  52. package/api/theme-edit/_preview-app.mjs +367 -36
  53. package/api/theme-edit/_preview.d.mts +55 -0
  54. package/api/theme-edit/_preview.mjs +231 -6
  55. package/api/theme-edit/_project.d.mts +4 -0
  56. package/api/theme-edit/_project.mjs +27 -6
  57. package/api/theme-edit/_settings.d.mts +61 -2
  58. package/api/theme-edit/_settings.mjs +317 -115
  59. package/api/theme-edit/_tables.mjs +1 -1
  60. package/api/theme-edit/theme-edit.type.d.mts +30 -2
  61. package/api/theme-edit/theme-edit.type.mjs +10 -2
  62. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  63. package/assets/docs/author-a-theme.doc.mjs +1 -1
  64. package/assets/docs/theme.doc.dense.mjs +1 -1
  65. package/assets/docs/theme.doc.mjs +1 -1
  66. package/assets/docs/theme.doc.zh.mjs +4 -3
  67. package/assets/docs/tree/define-the-theme.doc.mjs +1 -1
  68. package/assets/docs/tree/icon-sets.doc.mjs +63 -8
  69. package/assets/docs.generated.json +2 -2
  70. package/assets/self-audit.generated.json +1 -1
  71. package/assets/templates/blocks/components/Outline/useOutlineFromDOMHookUsage.doc.mjs +21 -0
  72. package/assets/templates/blocks/components/Outline/useOutlineFromDOMHookUsage.tsx +62 -0
  73. package/assets/templates/components.generated.json +1 -1
  74. package/assets/templates/pages/ai-chat/page.tsx +20 -2
  75. package/assets/templates/themes/neutral/neutralPalettes.generated.receipt.json +2 -0
  76. package/authoring/config/config.doc.mjs +8 -0
  77. package/authoring/config/parse.d.mts +1 -0
  78. package/authoring/config/parse.mjs +12 -0
  79. package/authoring/config/type.ts +8 -0
  80. package/authoring/doctypes/icon-set/icon-set-data.doc.mjs +3 -3
  81. package/clients/cli/build-id.generated.json +1 -1
  82. package/clients/cli/commands/experimental/icon.mjs +61 -6
  83. package/clients/cli/commands/experimental/theme.mjs +9 -2
  84. package/clients/cli/commands/experimental-icon-use.doc.mjs +12 -5
  85. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +2 -2
  86. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -1
  87. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +2 -2
  88. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  89. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  90. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  91. package/clients/cli/commands/theme.doc.mjs +7 -2
  92. package/clients/cli/commands/theme.mjs +41 -18
  93. package/clients/cli/commands.generated.json +1 -1
  94. package/clients/cli/index.mjs +25 -5
  95. package/clients/cli/manifest.generated.json +1 -1
  96. package/foundation/agent-docs/agent-docs.mjs +1 -1
  97. package/foundation/config/config-writer.d.mts +23 -0
  98. package/foundation/config/config-writer.mjs +150 -56
  99. package/foundation/config/project.mjs +43 -2
  100. package/foundation/discovery/component-discovery.mjs +6 -5
  101. package/foundation/discovery/icon-set-checks.mjs +164 -48
  102. package/foundation/discovery/icon-set-discovery.d.mts +38 -5
  103. package/foundation/discovery/icon-set-discovery.mjs +50 -6
  104. package/foundation/discovery/icon-set-theme-maps.d.mts +59 -0
  105. package/foundation/discovery/icon-set-theme-maps.mjs +95 -0
  106. package/foundation/discovery/icon-set-writer.d.mts +2 -3
  107. package/foundation/discovery/icon-set-writer.mjs +57 -16
  108. package/foundation/discovery/template-icons.d.mts +27 -10
  109. package/foundation/discovery/template-icons.mjs +142 -26
  110. package/foundation/discovery/theme-discovery.d.mts +25 -0
  111. package/foundation/discovery/theme-discovery.mjs +48 -7
  112. package/foundation/fs/gather-cache.mjs +6 -2
  113. package/foundation/integrations/autolink.d.mts +4 -2
  114. package/foundation/integrations/autolink.mjs +4 -2
  115. package/foundation/integrations/cli-requirement.d.mts +16 -5
  116. package/foundation/integrations/cli-requirement.mjs +27 -6
  117. package/foundation/integrations/may-have-integrations.mjs +5 -2
  118. package/foundation/integrations/missing-dependency.d.mts +9 -0
  119. package/foundation/integrations/missing-dependency.mjs +100 -0
  120. package/package.json +6 -6
@@ -10,6 +10,7 @@
10
10
  * @position api/theme-edit — storage and compile for the theme commands
11
11
  */
12
12
 
13
+ import {EDITOR_GENERATED_MARK} from './_marks.mjs';
13
14
  import {parse as parseModule} from '@babel/parser';
14
15
  import {createHash} from 'node:crypto';
15
16
  import * as fs from 'node:fs';
@@ -70,6 +71,8 @@ import {
70
71
  removeEmptyFolder,
71
72
  writeWhole,
72
73
  setOwnTokenReader,
74
+ readWrittenRecord,
75
+ writeWrittenRecord,
73
76
  } from './_palette.mjs';
74
77
  import {EDITOR_STAMP, pngTexts} from './_png.mjs';
75
78
  import {MODAL, isColorToken} from './_compiler.mjs';
@@ -193,6 +196,27 @@ export function themeFiles(cwd, slug) {
193
196
  };
194
197
  }
195
198
 
199
+ /** Files a system or a tool puts in any folder; a folder of only these is empty. */
200
+ export const FOLDER_JUNK = new Set(['.DS_Store', '.gitkeep', 'Thumbs.db']);
201
+
202
+ /**
203
+ * Whether `dir` holds nothing of anyone's: absent, empty, or only system
204
+ * files (what `git rm -r` or a branch switch leaves). A path that is not a
205
+ * folder, or one that does not read, is not empty.
206
+ * @param {string} dir
207
+ */
208
+ export function folderIsEmpty(dir) {
209
+ if (!fs.existsSync(dir)) return true;
210
+ try {
211
+ return (
212
+ fs.lstatSync(dir).isDirectory() &&
213
+ fs.readdirSync(dir).every(n => FOLDER_JUNK.has(n))
214
+ );
215
+ } catch {
216
+ return false;
217
+ }
218
+ }
219
+
196
220
  /**
197
221
  * Whether a value fits what a dial takes, read from the dial's own list of
198
222
  * values: a named rung in any case, or a value of the kind it names (a size,
@@ -219,18 +243,6 @@ export function dialValueFits(dial, value) {
219
243
  });
220
244
  }
221
245
 
222
- /**
223
- * Where the editor records the pictures it wrote into a theme folder: a
224
- * file of the theme's own beside its settings and history, each picture by
225
- * its name with the hash of what was written, so the record moves and is
226
- * copied with the theme.
227
- * @param {string} cwd
228
- * @param {string} slug
229
- */
230
- function writtenRecord(cwd, slug) {
231
- return themeFiles(cwd, slug).pictures;
232
- }
233
-
234
246
  /** @param {string} file @returns {string | null} */
235
247
  const contentHash = file => {
236
248
  try {
@@ -240,26 +252,6 @@ const contentHash = file => {
240
252
  }
241
253
  };
242
254
 
243
- /** @param {string} rec @returns {Record<string, string>} */
244
- const readRecord = rec => {
245
- try {
246
- const json = JSON.parse(fs.readFileSync(rec, 'utf8'));
247
- return json && typeof json === 'object' && !Array.isArray(json) ? json : {};
248
- } catch {
249
- return {};
250
- }
251
- };
252
-
253
- /** @param {string} rec @param {Record<string, string>} map */
254
- const writeRecord = (rec, map) => {
255
- try {
256
- if (!Object.keys(map).length) fs.rmSync(rec, {force: true});
257
- else writeWhole(rec, `${JSON.stringify(map, null, 2)}\n`);
258
- } catch {
259
- // Without a record nothing is removed later: the safe way round.
260
- }
261
- };
262
-
263
255
  /**
264
256
  * Record files the editor just wrote into a theme folder.
265
257
  * @param {string} cwd
@@ -267,13 +259,12 @@ const writeRecord = (rec, map) => {
267
259
  * @param {string[]} files
268
260
  */
269
261
  export function recordWritten(cwd, slug, files) {
270
- const rec = writtenRecord(cwd, slug);
271
- const map = readRecord(rec);
262
+ const map = readWrittenRecord(cwd, slug);
272
263
  for (const file of files) {
273
264
  const hash = contentHash(file);
274
265
  if (hash) map[path.basename(file)] = hash;
275
266
  }
276
- writeRecord(rec, map);
267
+ writeWrittenRecord(cwd, slug, map);
277
268
  }
278
269
 
279
270
  /**
@@ -284,7 +275,7 @@ export function recordWritten(cwd, slug, files) {
284
275
  * @param {string} file
285
276
  */
286
277
  export function editorWrote(cwd, slug, file) {
287
- const map = readRecord(writtenRecord(cwd, slug));
278
+ const map = readWrittenRecord(cwd, slug);
288
279
  const was = map[path.basename(file)];
289
280
  // A recorded picture is the editor's only while it is as it wrote it: a
290
281
  // picture changed after (re-saved by another tool, stamp and all) is the
@@ -337,10 +328,9 @@ export function adoptOlderPicture(cwd, slug, file) {
337
328
  */
338
329
  function forgetWritten(cwd, slug, names) {
339
330
  if (!names.length) return;
340
- const rec = writtenRecord(cwd, slug);
341
- const map = readRecord(rec);
331
+ const map = readWrittenRecord(cwd, slug);
342
332
  for (const n of names) delete map[n];
343
- writeRecord(rec, map);
333
+ writeWrittenRecord(cwd, slug, map);
344
334
  }
345
335
 
346
336
  /**
@@ -542,17 +532,39 @@ export function refuse(code, message, extra = {}) {
542
532
  throw new AstryxError(`${message} ${tail}`, suggestions, code);
543
533
  }
544
534
 
535
+ /**
536
+ * A theme name without a pasted label: `theme: t`, `name=t`, `--theme t`
537
+ * and `slug: "t"` name t; quotes and backticks around it go. Case is kept.
538
+ * A space is no label separator without dashes: "Theme Park" stays.
539
+ * The one reader of such labels, for --theme and every editor command.
540
+ * @param {unknown} s
541
+ * @returns {string}
542
+ */
543
+ export function unlabeledThemeName(s) {
544
+ return (
545
+ String(s ?? '')
546
+ .trim()
547
+ // A space ends a label only after dashes (`--theme t`): "Theme Park"
548
+ // is one name.
549
+ .replace(
550
+ /^(?:-+(?:theme|name|slug)(?:\s*[:=]\s*|\s+)|(?:theme|name|slug)\s*[:=]\s*)(?=\S)/i,
551
+ '',
552
+ )
553
+ .replace(/^['"`]+|['"`]+$/g, '')
554
+ .trim()
555
+ );
556
+ }
557
+
545
558
  /**
546
559
  * A theme name as typed, read the way the editor reads it: a path to its
547
560
  * folder or a file in it (t.theme.ts, Brand.settings.json), in any case,
548
- * names the theme. The result may still need slugFor.
561
+ * or a pasted label (`theme: t`, `name: t`), names the theme. The result may still need slugFor.
549
562
  * @param {unknown} s
550
563
  * @returns {string}
551
564
  */
552
565
  export function typedThemeName(s) {
553
566
  return (
554
- String(s ?? '')
555
- .trim()
567
+ unlabeledThemeName(s)
556
568
  .toLowerCase()
557
569
  // ./t and .\t name the theme t.
558
570
  .replace(/^(\.[\\/])+/, '')
@@ -584,8 +596,18 @@ export function loadTheme(
584
596
  // A path or a capital letter typed for a theme that exists names it.
585
597
  // A file name typed for the theme (t.theme.ts, Brand.settings.json)
586
598
  // names the theme.
599
+ // The name a pasted label gives ("theme: park" is park) when its theme
600
+ // exists; else the whole name as typed ("Theme Park" is theme-park).
601
+ const whole = slugFor(
602
+ String(slug ?? '')
603
+ .trim()
604
+ .toLowerCase(),
605
+ );
587
606
  const plain = typedThemeName(slug);
588
- const fixed = slugFor(plain);
607
+ const named = slugFor(plain);
608
+ const exists = (/** @type {string} */ n) =>
609
+ Boolean(n) && fs.existsSync(themeFiles(cwd, n).settings);
610
+ const fixed = !exists(named) && exists(whole) ? whole : named;
589
611
  const same = fs.existsSync(themeFiles(cwd, fixed).settings) ? fixed : null;
590
612
  // A list where one theme goes (t,u or "t;u"): one theme at a time,
591
613
  // each that exists named; never a new theme made of the list. A name
@@ -704,6 +726,21 @@ export function loadTheme(
704
726
  },
705
727
  );
706
728
  }
729
+ // An empty theme folder (or one of system files only) holds no theme
730
+ // yet: `new` makes one there.
731
+ if (
732
+ !same &&
733
+ other &&
734
+ other[0] === f.dir &&
735
+ !LIKE.includes(slug) &&
736
+ fs.lstatSync(f.dir).isDirectory() &&
737
+ folderIsEmpty(f.dir)
738
+ )
739
+ refuse(
740
+ ERROR_CODES.ERR_UNKNOWN_THEME,
741
+ `themes/${slug} is an empty folder: there is no theme ${slug} yet. new makes it there.`,
742
+ {run: [`${P} new ${slug}`]},
743
+ );
707
744
  if (!same && (other || LIKE.includes(slug)))
708
745
  refuse(
709
746
  ERROR_CODES.ERR_UNKNOWN_THEME,
@@ -1514,9 +1551,11 @@ export function partRuleTokens(cwd, slug, like, part) {
1514
1551
  * @param {string} part
1515
1552
  * @param {string} [scope] the rule: `base` (the plain one), or a variant
1516
1553
  * such as `variant:primary`
1554
+ * @param {string | null} [state] a state block inside that rule (`:hover`)
1517
1555
  * @returns {Map<string, string | null>}
1518
1556
  */
1519
- export function ownPartTokens(cwd, slug, part, scope = 'base') {
1557
+ export function ownPartTokens(cwd, slug, part, scope = 'base', state = null) {
1558
+ const at = ['components', part, scope, ...(state ? [state] : [])];
1520
1559
  /** @type {Map<string, string | null>} */
1521
1560
  const out = new Map();
1522
1561
  const f = themeFiles(cwd, slug);
@@ -1530,28 +1569,27 @@ export function ownPartTokens(cwd, slug, part, scope = 'base') {
1530
1569
  const stamp = /\/\/ Built with \S+\.theme\.ts ([0-9a-f]{16})\./.exec(
1531
1570
  module,
1532
1571
  )?.[1];
1533
- if (!stamp || stamp !== themeSourceHash(cwd, slug)) return out;
1572
+ /** @param {string} k */
1573
+ const css = k =>
1574
+ k.startsWith('--')
1575
+ ? k
1576
+ : k.replace(/[A-Z]/g, (/** @type {string} */ c) => `-${c.toLowerCase()}`);
1577
+ // With no build made from the source as it is now (an edit since the last
1578
+ // build), the file is read as written, as ownTokens reads page tokens.
1579
+ if (!stamp || stamp !== themeSourceHash(cwd, slug)) {
1580
+ for (const [k, v] of blockOf(f.ts, at)) out.set(css(k), v);
1581
+ return out;
1582
+ }
1534
1583
  const like = /\/\/ Built on @astryxdesign\/theme-([a-z0-9-]+) /.exec(
1535
1584
  module,
1536
1585
  )?.[1];
1537
1586
  const baseFile = like ? baseModule(cwd, like) : null;
1538
- const base = baseFile
1539
- ? blockOf(baseFile, ['components', part, scope])
1540
- : new Map();
1541
- const settings = blockOf(f.settingsTs, ['components', part, scope]);
1587
+ const base = baseFile ? blockOf(baseFile, at) : new Map();
1588
+ const settings = blockOf(f.settingsTs, at);
1542
1589
  const named = namedInOwnSource(cwd, slug);
1543
- for (const [k, v] of blockOf(f.js, ['components', part, scope])) {
1590
+ for (const [k, v] of blockOf(f.js, at)) {
1544
1591
  const given = settings.has(k) ? settings.get(k) : base.get(k);
1545
- if (given !== v && named(k))
1546
- out.set(
1547
- k.startsWith('--')
1548
- ? k
1549
- : k.replace(
1550
- /[A-Z]/g,
1551
- (/** @type {string} */ c) => `-${c.toLowerCase()}`,
1552
- ),
1553
- v,
1554
- );
1592
+ if (given !== v && named(k)) out.set(css(k), v);
1555
1593
  }
1556
1594
  return out;
1557
1595
  }
@@ -2063,6 +2101,39 @@ function keepShades(pal, kept) {
2063
2101
  return {...pal, tokens, lift: kept['lifted parts'] ? pal.lift : null};
2064
2102
  }
2065
2103
 
2104
+ /**
2105
+ * Control heights scaled with the spacing dial (a denser theme has shorter
2106
+ * controls), each kept distinct and in order: smallest to largest, a
2107
+ * control never under 24px (the smallest target a pointer can use
2108
+ * comfortably, unless the theme starts below it), each the plain scaled
2109
+ * value unless it would meet the one below, which then keeps its own step
2110
+ * scaled above it.
2111
+ * @param {Array<[string, string]>} sizes token name and the theme's value
2112
+ * @param {number} f the spacing rung's factor
2113
+ * @returns {Array<[string, string]>} the tokens it writes, in px
2114
+ */
2115
+ export function controlSizes(sizes, f) {
2116
+ const px = sizes
2117
+ .filter(([, v]) => /^[\d.]+px$/.test(String(v).trim()))
2118
+ .map(([k, v]) => /** @type {[string, number]} */ ([k, parseFloat(v)]))
2119
+ .sort((a, b) => a[1] - b[1]);
2120
+ /** @type {Array<[string, string]>} */
2121
+ const out = [];
2122
+ let prev = null;
2123
+ let prevOwn = null;
2124
+ for (const [k, v] of px) {
2125
+ let n = Math.max(Math.min(24, v), Math.round(v * f));
2126
+ // Only a size that would meet (or pass) the one below moves: the plain
2127
+ // scaled value otherwise.
2128
+ if (prev != null && prevOwn != null && n <= prev)
2129
+ n = prev + Math.max(1, Math.round((v - prevOwn) * f));
2130
+ out.push([k, `${n}px`]);
2131
+ prev = n;
2132
+ prevOwn = v;
2133
+ }
2134
+ return out;
2135
+ }
2136
+
2066
2137
  /**
2067
2138
  * The settings, as a `defineTheme` object.
2068
2139
  * @param {Ctx} ctx
@@ -2098,11 +2169,9 @@ export function compileTheme(ctx, data, base) {
2098
2169
  /** @param {string} name @param {string | [string, string]} v @param {string} [mode] */
2099
2170
  const putTok = (name, v, mode) => {
2100
2171
  const t = (tok[name] ??= {});
2101
- // A one-mode theme writes the value of its mode to both sides.
2102
- if (Array.isArray(v) && modeOnly) {
2103
- t.light = t.dark = v[modeOnly === 'light' ? 0 : 1];
2104
- return;
2105
- }
2172
+ // A one-mode theme keeps both halves of a pair: its mode is the one the
2173
+ // app's <Theme> is given, and a region Core draws in the other mode
2174
+ // (a toast, a lightbox) still reads the other half.
2106
2175
  if (Array.isArray(v)) {
2107
2176
  if (!mode || mode === 'light') t.light = v[0];
2108
2177
  if (!mode || mode === 'dark') t.dark = v[1];
@@ -2263,12 +2332,15 @@ export function compileTheme(ctx, data, base) {
2263
2332
  const v = down?.length ? four(down) : null;
2264
2333
  const corner = (/** @type {number} */ i) =>
2265
2334
  v && v[i] !== h[i] ? `${h[i]} ${v[i]}` : h[i];
2335
+ // The whole radius as one value first, which Core turns into the
2336
+ // part's inner-corner variable itself (a theme writes no private
2337
+ // variable), then each corner, which the box shows.
2266
2338
  return {
2339
+ borderRadius: h[0],
2267
2340
  borderTopLeftRadius: corner(0),
2268
2341
  borderTopRightRadius: corner(1),
2269
2342
  borderBottomRightRadius: corner(2),
2270
2343
  borderBottomLeftRadius: corner(3),
2271
- ...Object.fromEntries(vars.map(name => [name, h[0]])),
2272
2344
  };
2273
2345
  };
2274
2346
  /**
@@ -2341,7 +2413,10 @@ export function compileTheme(ctx, data, base) {
2341
2413
  const name = (ctx.derived?.[target] ?? []).find(
2342
2414
  d => d.property === 'padding' && d.vars?.length,
2343
2415
  )?.vars?.[0];
2344
- return name ? {[name]: String(s.value).trim()} : null;
2416
+ // The box reads only Core's own variable, which a theme may not write,
2417
+ // and a padding property would pad the wrapper: nothing is written (a
2418
+ // saved one is refused, as set refuses it).
2419
+ return name ? {} : null;
2345
2420
  };
2346
2421
  /**
2347
2422
  * The prefix of the padding variables a part's box reads, for a part whose
@@ -2396,6 +2471,9 @@ export function compileTheme(ctx, data, base) {
2396
2471
  return n && n.unit === '' && n.value === 0 ? '0px' : v;
2397
2472
  };
2398
2473
  for (const {target, s, list} of padQueue.values()) {
2474
+ // The own source's padding on the same rule wins over the editor's:
2475
+ // nothing is written there (the result says so).
2476
+ if (ownPads(target, s)) continue;
2399
2477
  const prefix = /** @type {string} */ (padVars(target));
2400
2478
  const owner = prefix.slice('--astryx-'.length, -'-padding'.length);
2401
2479
  const scoped = target !== owner || s.when != null || s.state != null;
@@ -2406,7 +2484,9 @@ export function compileTheme(ctx, data, base) {
2406
2484
  const raw = String(x.value).trim();
2407
2485
  // initial and unset leave the variable without a value, so the part
2408
2486
  // takes Core's own default for it.
2409
- const value = /^(initial|unset)$/i.test(raw) ? 'initial' : raw;
2487
+ const value = /^(initial|unset|inherit|revert|revert-layer)$/i.test(raw)
2488
+ ? 'initial'
2489
+ : raw;
2410
2490
  const w = splitTop(value, ' ').map(y => length(y.trim()));
2411
2491
  const one = length(value);
2412
2492
  for (const dir of /** @type {const} */ (['ltr', 'rtl'])) {
@@ -2587,6 +2667,26 @@ export function compileTheme(ctx, data, base) {
2587
2667
  }
2588
2668
  return out;
2589
2669
  };
2670
+ /**
2671
+ * Whether the theme's own source sets a padding on a part's rule for a
2672
+ * scope (its plain rule, a variant, a state).
2673
+ * @param {string} target @param {Setting} s
2674
+ */
2675
+ const ownPads = (target, s) => {
2676
+ try {
2677
+ return [
2678
+ ...ownPartTokens(
2679
+ ctx.project.cwd,
2680
+ data.name,
2681
+ target,
2682
+ s.when ?? 'base',
2683
+ s.state ? `:${s.state}` : null,
2684
+ ).keys(),
2685
+ ].some(k => /^padding(-|$)/.test(k));
2686
+ } catch {
2687
+ return false;
2688
+ }
2689
+ };
2590
2690
  /**
2591
2691
  * The selector a narrower padding scope is written with (a clickable
2592
2692
  * card's class, a variant's attribute, a state's pseudo-class), or null
@@ -2611,8 +2711,10 @@ export function compileTheme(ctx, data, base) {
2611
2711
  const dirFirst = b => {
2612
2712
  const keys = Object.keys(b);
2613
2713
  const plain = keys.filter(k => !k.startsWith(':'));
2614
- const dirs = keys.filter(k => /^:dir\(/.test(k));
2615
- const rest = keys.filter(k => k.startsWith(':') && !/^:dir\(/.test(k));
2714
+ const dirs = keys.filter(k => /^:(where\()?dir\(/.test(k));
2715
+ const rest = keys.filter(
2716
+ k => k.startsWith(':') && !/^:(where\()?dir\(/.test(k),
2717
+ );
2616
2718
  return Object.fromEntries(
2617
2719
  [...plain, ...dirs, ...rest].map(k => [
2618
2720
  k,
@@ -2656,6 +2758,10 @@ export function compileTheme(ctx, data, base) {
2656
2758
  */
2657
2759
  const dirBlock = (s, target, dir) => {
2658
2760
  const tg = ctx.project.target.get(target);
2761
+ // On the plain rule, a direction's rule keeps the plain rule's weight
2762
+ // (:where), so any variant, the own source's included, out-ranks it as
2763
+ // it out-ranks the plain rule.
2764
+ if (!s.state && !s.when) return [block(s, target), `:where(${dir})`];
2659
2765
  if (!s.state || tg?.states.includes(s.state))
2660
2766
  return [block(s, target), dir];
2661
2767
  const parent = block({...s, state: undefined}, target);
@@ -2752,7 +2858,7 @@ export function compileTheme(ctx, data, base) {
2752
2858
  for (const m of /** @type {const} */ (['light', 'dark']))
2753
2859
  if (!x.mode || x.mode === m) value[m] = {color: x.value};
2754
2860
  ((theme.components[target] ??= {})[key] ??= {})['--color-text-secondary'] =
2755
- liftValue(value, modeOnly);
2861
+ liftValue(value, null);
2756
2862
  }
2757
2863
  // `headings` owns heading weight and tracking whatever the order: `type`
2758
2864
  // sets them only where no `headings` setting does.
@@ -2893,21 +2999,25 @@ export function compileTheme(ctx, data, base) {
2893
2999
  } else if (s.thing === 'spacing') {
2894
3000
  const f = SPACING.find(([n]) => n === s.value)?.[1] ?? 1;
2895
3001
  // The rungs scale the spacing the base theme starts from.
3002
+ /** @param {string} k @param {string} nv */
3003
+ const put = (k, nv) => {
3004
+ if (parts.length) for (const t of parts) block(s, t)[k] = nv;
3005
+ else putTok(k, nv);
3006
+ };
2896
3007
  for (const [k, core] of Object.entries(
2897
3008
  /** @type {Record<string, string>} */ (TOKENS),
2898
3009
  )) {
2899
3010
  const v = base.light[k] ?? core;
2900
- let nv = null;
2901
3011
  if (/^--spacing-/.test(k) && /rem$/.test(v))
2902
- nv = `${Number((parseFloat(v) * f).toFixed(3))}rem`;
2903
- // A control never gets smaller than 24px, the smallest target a
2904
- // pointer can use comfortably.
2905
- if (/^--size-element-/.test(k) && /px$/.test(v))
2906
- nv = `${Math.max(Math.min(24, parseFloat(v)), Math.round(parseFloat(v) * f))}px`;
2907
- if (nv === null) continue;
2908
- if (parts.length) for (const t of parts) block(s, t)[k] = nv;
2909
- else putTok(k, nv);
3012
+ put(k, `${Number((parseFloat(v) * f).toFixed(3))}rem`);
2910
3013
  }
3014
+ for (const [k, nv] of controlSizes(
3015
+ Object.keys(/** @type {Record<string, string>} */ (TOKENS))
3016
+ .filter(k => /^--size-element-/.test(k))
3017
+ .map(k => [k, base.light[k] ?? TOKENS[k]]),
3018
+ f,
3019
+ ))
3020
+ put(k, nv);
2911
3021
  }
2912
3022
  } else if (s.source === 'token') {
2913
3023
  if (parts.length) for (const t of parts) putComp(s, t, s.thing, s.value);
@@ -2987,10 +3097,14 @@ export function compileTheme(ctx, data, base) {
2987
3097
  }
2988
3098
  }
2989
3099
  // A part's own corner radii replace a single radius a group or an
2990
- // earlier setting left in the same block, which Core would copy into
2991
- // the content's radius after the editor's own.
2992
- if (sides && 'borderTopLeftRadius' in sides)
2993
- delete block(s, t).borderRadius;
3100
+ // earlier setting left in the same block, in their own order: the
3101
+ // whole radius (which Core turns into the content's radius) before
3102
+ // the corners, which the box shows.
3103
+ if (sides && 'borderTopLeftRadius' in sides) {
3104
+ const b = block(s, t);
3105
+ for (const k of Object.keys(sides)) delete b[k];
3106
+ Object.assign(b, sides);
3107
+ }
2994
3108
  }
2995
3109
  }
2996
3110
  }
@@ -3005,15 +3119,6 @@ export function compileTheme(ctx, data, base) {
3005
3119
  theme.typography.heading = {family: f.family, fallbacks: f.fallbacks};
3006
3120
  }
3007
3121
  }
3008
- // A one-mode theme looks the same whatever the system asks for: every
3009
- // color the theme does not set takes its mode's value from the base (or
3010
- // Core) on both sides.
3011
- if (modeOnly)
3012
- for (const k of Object.keys(/** @type {Record<string, string>} */ (TOKENS)))
3013
- if (MODAL.has(ctx.C.typeOf(k)) && !tok[k]) {
3014
- const v = base[modeOnly]?.[k];
3015
- if (v && !/var\(/.test(v)) putTok(k, v);
3016
- }
3017
3122
  // A scale steeper or flatter than the standard one changes the headings;
3018
3123
  // the steps below the base text size keep the standard ratio, so small
3019
3124
  // text stays as it was. An exact token setting still wins.
@@ -3064,7 +3169,7 @@ export function compileTheme(ctx, data, base) {
3064
3169
  // dial's weights, are written there too, so they apply on every screen.
3065
3170
  // Sizes are not: phones keep their reading base. (What the theme's own
3066
3171
  // source sets is not repeated: on phones the base theme's type comes
3067
- // back for it, a Core limit the notes name.)
3172
+ // back for it, by Core contract; the notes name the fix.)
3068
3173
  const phone = Object.fromEntries([
3069
3174
  ...data.settings
3070
3175
  .filter(
@@ -3289,22 +3394,11 @@ function settingsSource(slug, data, theme, pal, cwd = '') {
3289
3394
  ? `${REF}${r.family}`
3290
3395
  : `${REF}${r.family ?? family}.${m}.${r.stop}${r.alpha ? `+${r.alpha}` : ''}`;
3291
3396
  const out = {...theme, name: `${slug}-settings`};
3292
- const only =
3293
- data.mode === 'light-only'
3294
- ? 'light'
3295
- : data.mode === 'dark-only'
3296
- ? 'dark'
3297
- : null;
3397
+ // A one-mode theme keeps both halves too (see compileTheme).
3298
3398
  if (pal && theme.tokens) {
3299
3399
  out.tokens = {...theme.tokens};
3300
3400
  for (const [k, v] of Object.entries(pal.tokens)) {
3301
3401
  const now = theme.tokens[k];
3302
- // A one-mode theme reads one shade, its mode's, on both sides.
3303
- if (only) {
3304
- if (now === v[only].color)
3305
- out.tokens[k] = refOf(v.family, only, v[only]);
3306
- continue;
3307
- }
3308
3402
  const [l, d] = Array.isArray(now) ? now : [now, now];
3309
3403
  if (l !== v.light.color || d !== v.dark.color) continue;
3310
3404
  out.tokens[k] = [
@@ -3319,15 +3413,13 @@ function settingsSource(slug, data, theme, pal, cwd = '') {
3319
3413
  for (const [target, key, ground] of LIFT_PARTS) {
3320
3414
  const lift = pal.lift[ground];
3321
3415
  if (!lift) continue;
3322
- const literal = liftValue(lift, only);
3416
+ const literal = liftValue(lift, null);
3323
3417
  /** A shade of the neutral palette as a reference; a color as it is. @param {'light' | 'dark'} m */
3324
3418
  const one = m => {
3325
3419
  const r = /** @type {any} */ (lift[m]);
3326
3420
  return r.family === 'literal' ? r.color : refOf('neutral', m, r);
3327
3421
  };
3328
- const refs = only
3329
- ? one(only)
3330
- : `light-dark(${one('light')}, ${one('dark')})`;
3422
+ const refs = `light-dark(${one('light')}, ${one('dark')})`;
3331
3423
  const block = out.components[target]?.[key];
3332
3424
  if (block?.['--color-text-secondary'] !== literal) continue;
3333
3425
  out.components[target] = {
@@ -3680,7 +3772,7 @@ function refuseOwnPairs(ctx, cwd, slug) {
3680
3772
  (/** @type {any} */ e) =>
3681
3773
  e?.type === 'StringLiteral' && /^\d*\.?\d+$/.test(e.value.trim()),
3682
3774
  );
3683
- if (!MODAL.has(type) && !unitless) bad.push(k);
3775
+ if (type !== 'color' && !unitless) bad.push(k);
3684
3776
  }
3685
3777
  for (const v of Object.values(node))
3686
3778
  if (Array.isArray(v)) v.forEach(visit);
@@ -3692,7 +3784,7 @@ function refuseOwnPairs(ctx, cwd, slug) {
3692
3784
  }
3693
3785
  if (bad.length)
3694
3786
  throw new AstryxError(
3695
- `themes/${slug}/${slug}.theme.ts gives ${[...new Set(bad)].join(', ')} a [light, dark] pair, but only colors differ by mode: the build would write light-dark(), which browsers take only for colors. Give ${bad.length > 1 ? 'each' : 'it'} one value in ${slug}.theme.ts. Nothing was changed.`,
3787
+ ownPairMessage(slug, [...new Set(bad)]),
3696
3788
  [
3697
3789
  {
3698
3790
  name: `grep -n -- ${quoteCommandArgument(bad[0])} ${quoteCommandArgument(`themes/${slug}/${slug}.theme.ts`)}`,
@@ -3703,6 +3795,93 @@ function refuseOwnPairs(ctx, cwd, slug) {
3703
3795
  );
3704
3796
  }
3705
3797
 
3798
+ /**
3799
+ * The tokens that are not colors the theme as it builds now gives a
3800
+ * [light, dark] pair (light-dark()), however its file writes them (a
3801
+ * constant, `as const`, `satisfies`, a spread from an imported module):
3802
+ * read from a build made into the project's cache folder, never beside the
3803
+ * theme. Empty when it does not build there (the build names that itself).
3804
+ * @param {Ctx} ctx
3805
+ * @param {string} slug
3806
+ * @returns {Promise<string[]>}
3807
+ */
3808
+ export async function builtPairs(ctx, slug) {
3809
+ const {cwd} = ctx.project;
3810
+ const f = themeFiles(cwd, slug);
3811
+ // The build writes only inside the project: the cache folder when it is
3812
+ // there, else a hidden folder in the theme's (removed after).
3813
+ const name = `.${slug}.pairs-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
3814
+ const inside = !path.relative(cwd, ctx.project.cacheDir).startsWith('..');
3815
+ const dir = path.join(inside ? ctx.project.cacheDir : f.dir, name);
3816
+ const silent = logger.silent;
3817
+ logger.setSilent(true);
3818
+ try {
3819
+ fs.mkdirSync(dir, {recursive: true});
3820
+ await themeBuildForReport(
3821
+ shown(cwd, f.ts),
3822
+ {out: path.relative(cwd, path.join(dir, `${slug}.css`))},
3823
+ {cwd},
3824
+ {compact: true},
3825
+ );
3826
+ const js = fs
3827
+ .readdirSync(dir)
3828
+ .find(n => n.endsWith('.js') && !n.endsWith('.d.js'));
3829
+ if (!js) return [];
3830
+ return [...topTokensOf(path.join(dir, js))]
3831
+ .filter(
3832
+ ([k, v]) =>
3833
+ /^light-dark\(/.test(String(v ?? '')) && ctx.C.typeOf(k) !== 'color',
3834
+ )
3835
+ .map(([k]) => k);
3836
+ } catch {
3837
+ return [];
3838
+ } finally {
3839
+ logger.setSilent(silent);
3840
+ fs.rmSync(dir, {recursive: true, force: true});
3841
+ }
3842
+ }
3843
+
3844
+ /**
3845
+ * The refusal of a [light, dark] pair on tokens that are not colors.
3846
+ * @param {string} slug
3847
+ * @param {string[]} names
3848
+ */
3849
+ export function ownPairMessage(slug, names) {
3850
+ return `themes/${slug}/${slug}.theme.ts gives ${names.join(', ')} a [light, dark] pair, but only colors differ by mode: the build would write light-dark(), which browsers take only for colors. Give ${names.length > 1 ? 'each' : 'it'} one value in ${slug}.theme.ts. Nothing was changed.`;
3851
+ }
3852
+
3853
+ /**
3854
+ * What runs after every build of a theme, set by the adapter (the app copy
3855
+ * of the theme): null until it is set.
3856
+ * @type {((ctx: Ctx, slug: string, data: ThemeData) => void) | null}
3857
+ */
3858
+ let afterBuild = null;
3859
+
3860
+ /**
3861
+ * Set what runs after every build of a theme.
3862
+ * @param {((ctx: Ctx, slug: string, data: ThemeData) => void) | null} fn
3863
+ */
3864
+ export function setAfterBuild(fn) {
3865
+ afterBuild = fn;
3866
+ }
3867
+
3868
+ /**
3869
+ * Builds whose after-build hook waits for the change to be saved: a change
3870
+ * that fails after its build puts its theme folder back, and its app copy
3871
+ * was never written.
3872
+ * @type {WeakSet<Ctx>}
3873
+ */
3874
+ const afterSave = new WeakSet();
3875
+
3876
+ /**
3877
+ * Hold the after-build hook for this command's builds: the command writes
3878
+ * the app copy itself once it succeeds (show).
3879
+ * @param {Ctx} ctx
3880
+ */
3881
+ export function holdAfterBuild(ctx) {
3882
+ afterSave.add(ctx);
3883
+ }
3884
+
3706
3885
  /**
3707
3886
  * Generate the theme source, build it with the theme build, then repeat any
3708
3887
  * part setting a more specific rule would beat and build again.
@@ -3817,6 +3996,12 @@ export async function buildTheme(ctx, slug, data) {
3817
3996
  ]
3818
3997
  .map(String)
3819
3998
  .filter(w => !/^Font "/.test(w));
3999
+ // The app's copy, a standard local theme `theme add` reads, follows the
4000
+ // build (written by the hook the adapter sets: it owns that write).
4001
+ if (afterBuild && !afterSave.has(ctx))
4002
+ await step(() => {
4003
+ afterBuild?.(ctx, slug, data);
4004
+ });
3820
4005
  return {warnings, lifted, notes};
3821
4006
  }
3822
4007
 
@@ -3983,7 +4168,7 @@ export async function resolvedTokens(ctx, slug) {
3983
4168
  * in a [light, dark] pair, or null.
3984
4169
  * @param {any} t
3985
4170
  * @param {(name: string) => string} [typeOf] a token's type (size, color…)
3986
- * @returns {[string, unknown, 'object' | 'pair' | 'unit' | 'value'] | null}
4171
+ * @returns {[string, unknown, 'object' | 'pair' | 'unit' | 'value' | 'mode'] | null}
3987
4172
  */
3988
4173
  function nonTextToken(t, typeOf = (/** @type {string} */ _k) => 'other') {
3989
4174
  for (const [k, raw] of Object.entries(t?.tokens ?? {})) {
@@ -4018,11 +4203,16 @@ function nonTextToken(t, typeOf = (/** @type {string} */ _k) => 'other') {
4018
4203
  : x;
4019
4204
  return [k, [half(parts[0]), half(parts[1])], missing ? 'pair' : 'unit'];
4020
4205
  }
4206
+ // light-dark() takes only colors: a pair on any other token (a size,
4207
+ // a font, a shadow) is dropped by the browser, however the theme
4208
+ // file wrote it (a constant, `as const`, an imported module).
4209
+ if (typeOf(k) !== 'color') return [k, parts, 'mode'];
4021
4210
  continue;
4022
4211
  }
4023
4212
  if (Array.isArray(raw)) {
4024
4213
  if (raw.length !== 2 || raw.some(x => typeof x !== 'string'))
4025
4214
  return [k, raw, 'pair'];
4215
+ if (typeOf(k) !== 'color') return [k, raw, 'mode'];
4026
4216
  continue;
4027
4217
  }
4028
4218
  if (typeof raw !== 'string') return [k, raw, 'value'];
@@ -4035,10 +4225,11 @@ function nonTextToken(t, typeOf = (/** @type {string} */ _k) => 'other') {
4035
4225
  * write instead (a size in px, a weight as a number in quotes), or none.
4036
4226
  * @param {Ctx} ctx
4037
4227
  * @param {string} slug
4038
- * @param {[string, unknown, ('object' | 'pair' | 'unit' | 'value')?]} bad
4228
+ * @param {[string, unknown, ('object' | 'pair' | 'unit' | 'value' | 'mode')?]} bad
4039
4229
  */
4040
4230
  function nonTextMessage(ctx, slug, [name, value, kind = 'value']) {
4041
4231
  const type = ctx.C.typeOf(name);
4232
+ if (kind === 'mode') return ownPairMessage(slug, [name]);
4042
4233
  if (kind === 'object')
4043
4234
  return `${slug}.theme.ts gives ${name} an object (${JSON.stringify(value)}); a token value is a CSS value in quotes, such as '8px' (only a color takes a [light, dark] pair).`;
4044
4235
  if (kind === 'unit') {
@@ -4523,7 +4714,7 @@ export function madeByEditor(file) {
4523
4714
  try {
4524
4715
  return fs
4525
4716
  .readFileSync(file, 'utf8')
4526
- .startsWith('// Generated by `astryx experimental theme editor`');
4717
+ .startsWith(`// ${EDITOR_GENERATED_MARK}`);
4527
4718
  } catch {
4528
4719
  return false;
4529
4720
  }
@@ -5139,6 +5330,8 @@ export async function commitTheme(
5139
5330
  // tokens the own source sets in a way no read of the file follows) is
5140
5331
  // refused once the build shows it.
5141
5332
  const loopsBefore = new Set(builtLoops(cwd, slug).map(l => l.key));
5333
+ // The app copy is written once the change is saved, never before.
5334
+ afterSave.add(ctx);
5142
5335
  try {
5143
5336
  refuseIfLockLost();
5144
5337
  try {
@@ -5185,7 +5378,16 @@ export async function commitTheme(
5185
5378
  // Settings written whole: a `new` marker left beside them (a `new`
5186
5379
  // stopped after its theme was made) has nothing left to finish.
5187
5380
  clearNewMarker(f.dir);
5381
+ afterSave.delete(ctx);
5382
+ // The change is saved: its app copy follows. A copy that cannot be
5383
+ // written leaves the copy as it was; the change stands.
5384
+ try {
5385
+ afterBuild?.(ctx, slug, data);
5386
+ } catch (e) {
5387
+ if (/** @type {any} */ (e)?.lockLost) throw e;
5388
+ }
5188
5389
  } catch (e) {
5390
+ afterSave.delete(ctx);
5189
5391
  // A command that lost its lock while stopped owns none of these files
5190
5392
  // now: it puts nothing back and deletes nothing (that would undo the
5191
5393
  // other command's change).