@astryxdesign/cli 0.7.15 → 0.7.16-canary.g8514aae

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 (116) hide show
  1. package/README.md +5 -3
  2. package/api/component/_adapter.d.mts +1 -1
  3. package/api/component/_adapter.mjs +28 -1
  4. package/api/doctor/_adapter.d.mts +17 -0
  5. package/api/doctor/_adapter.mjs +35 -0
  6. package/api/doctor/doctor.mjs +18 -4
  7. package/api/integration/validate-integration.mjs +1 -1
  8. package/api/theme/_adapter.d.mts +5 -2
  9. package/api/theme/_adapter.mjs +43 -12
  10. package/api/theme/build/build.d.mts +1 -21
  11. package/api/theme/build/build.mjs +149 -37
  12. package/api/theme/eject/eject.mjs +22 -1
  13. package/api/theme/template/template.d.mts +19 -0
  14. package/api/theme/template/template.mjs +91 -19
  15. package/api/theme/theme.type.d.mts +5 -1
  16. package/api/theme/theme.type.mjs +2 -1
  17. package/api/theme/themeBuild.doc.mjs +3 -3
  18. package/api/theme/themeEject.doc.mjs +1 -1
  19. package/api/theme/themeTemplate.doc.mjs +9 -3
  20. package/api/theme-edit/_adapter.d.mts +21 -0
  21. package/api/theme-edit/_adapter.mjs +176 -22
  22. package/api/theme-edit/_check.d.mts +7 -0
  23. package/api/theme-edit/_check.mjs +1050 -173
  24. package/api/theme-edit/_color.d.mts +2 -8
  25. package/api/theme-edit/_color.mjs +292 -219
  26. package/api/theme-edit/_compiler.d.mts +1 -0
  27. package/api/theme-edit/_compiler.mjs +20 -1
  28. package/api/theme-edit/_context.d.mts +21 -0
  29. package/api/theme-edit/_context.mjs +235 -12
  30. package/api/theme-edit/_css.d.mts +50 -1
  31. package/api/theme-edit/_css.mjs +310 -28
  32. package/api/theme-edit/_edit.d.mts +9 -0
  33. package/api/theme-edit/_edit.mjs +907 -123
  34. package/api/theme-edit/_how-commands.d.mts +11 -26
  35. package/api/theme-edit/_how-commands.mjs +30 -2
  36. package/api/theme-edit/_how-question.d.mts +7 -0
  37. package/api/theme-edit/_how-question.mjs +1304 -176
  38. package/api/theme-edit/_how.mjs +144 -30
  39. package/api/theme-edit/_palette.d.mts +6 -0
  40. package/api/theme-edit/_palette.mjs +164 -62
  41. package/api/theme-edit/_parts.d.mts +16 -0
  42. package/api/theme-edit/_parts.mjs +49 -1
  43. package/api/theme-edit/_png.mjs +19 -14
  44. package/api/theme-edit/_preview-app.mjs +514 -27
  45. package/api/theme-edit/_preview.d.mts +11 -0
  46. package/api/theme-edit/_preview.mjs +245 -24
  47. package/api/theme-edit/_project.d.mts +11 -0
  48. package/api/theme-edit/_project.mjs +35 -9
  49. package/api/theme-edit/_settings.d.mts +122 -5
  50. package/api/theme-edit/_settings.mjs +1363 -71
  51. package/api/theme-edit/_tables.d.mts +19 -0
  52. package/api/theme-edit/_tables.mjs +205 -149
  53. package/api/theme-edit/_vet.d.mts +42 -0
  54. package/api/theme-edit/_vet.mjs +144 -0
  55. package/api/theme-edit/theme-edit.type.d.mts +2 -1
  56. package/api/theme-edit/theme-edit.type.mjs +1 -1
  57. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  58. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  59. package/assets/docs/tree/single-component.doc.mjs +11 -2
  60. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  61. package/assets/docs.generated.json +2 -2
  62. package/assets/preview-app/next.config.mjs +7 -1
  63. package/assets/preview-app/src/app/globals.css +1 -0
  64. package/assets/self-audit.generated.json +1 -1
  65. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  66. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  67. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  68. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  69. package/assets/templates/components.generated.json +1 -1
  70. package/authoring/doctypes/_schema.d.mts +52 -5
  71. package/authoring/doctypes/_schema.mjs +62 -7
  72. package/authoring/doctypes/base/type.ts +10 -0
  73. package/authoring/doctypes/component/component.doc.mjs +1 -1
  74. package/authoring/doctypes/function/function.doc.mjs +6 -0
  75. package/authoring/doctypes/function/type.ts +3 -0
  76. package/authoring/doctypes/legacy.mjs +5 -1
  77. package/authoring/index.d.ts +1 -0
  78. package/clients/cli/build-id.generated.json +1 -1
  79. package/clients/cli/commands/doctor.doc.mjs +2 -2
  80. package/clients/cli/commands/experimental/theme.mjs +188 -37
  81. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  82. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +1 -1
  83. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +2 -2
  84. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  85. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  86. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  87. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  88. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  89. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  90. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  91. package/clients/cli/commands/theme.mjs +89 -6
  92. package/clients/cli/formatters/index.mjs +7 -4
  93. package/clients/cli/lib/cli-error.mjs +9 -3
  94. package/clients/cli/lib/component-format.mjs +27 -9
  95. package/clients/cli/lib/json-shim.mjs +40 -2
  96. package/clients/cli/manifest.generated.json +1 -1
  97. package/foundation/config/project.mjs +50 -14
  98. package/foundation/discovery/theme-discovery.d.mts +5 -1
  99. package/foundation/discovery/theme-discovery.mjs +24 -3
  100. package/foundation/fs/gather-cache.d.mts +9 -2
  101. package/foundation/fs/gather-cache.mjs +36 -10
  102. package/foundation/fs/paths.d.mts +16 -0
  103. package/foundation/fs/paths.mjs +25 -0
  104. package/foundation/render/host-exit.d.mts +8 -0
  105. package/foundation/render/host-exit.mjs +11 -0
  106. package/foundation/render/page-host.mjs +56 -10
  107. package/foundation/render/page-worker.mjs +14 -0
  108. package/foundation/render/render-page.mjs +37 -2
  109. package/foundation/response/error-codes.d.mts +2 -1
  110. package/foundation/response/error-codes.d.ts +1 -0
  111. package/foundation/response/error-codes.doc.mjs +5 -0
  112. package/foundation/response/error-codes.mjs +3 -0
  113. package/foundation/response/json.d.mts +15 -0
  114. package/foundation/response/json.mjs +52 -1
  115. package/foundation/response/response-types.doc.mjs +1 -1
  116. package/package.json +7 -6
@@ -10,20 +10,25 @@
10
10
  */
11
11
 
12
12
  import * as fs from 'node:fs';
13
+ import {coversProperty} from './_css.mjs';
13
14
  import * as path from 'node:path';
14
15
  import {AstryxError} from '../error.mjs';
16
+ import {vetSuggestions} from './_vet.mjs';
15
17
  import {
16
18
  AUTO_SPREAD,
17
19
  CORNERS,
18
20
  DIALS,
19
21
  FAMILIES,
20
22
  FONT_ROLES,
23
+ HEADING_TRACKING,
24
+ HEADING_WEIGHTS,
21
25
  KEY_TOKENS,
22
26
  LIKE,
23
27
  P,
24
28
  SPACING,
25
29
  TYPE_STYLES,
26
30
  familyOf,
31
+ wordTable,
27
32
  } from './_tables.mjs';
28
33
  import {
29
34
  commitTheme,
@@ -42,7 +47,9 @@ import {
42
47
  undoArgs,
43
48
  withoutBadValues,
44
49
  NAME_RULE,
50
+ HISTORY_STEPS,
45
51
  readHistory,
52
+ refuseUnreadableFiles,
46
53
  refuse,
47
54
  settingsProblem,
48
55
  resolvedTokens,
@@ -53,6 +60,9 @@ import {
53
60
  staleBuild,
54
61
  EDITOR_SUFFIXES,
55
62
  madeByEditor,
63
+ outputsDrift,
64
+ kebab,
65
+ camel,
56
66
  NEW_MARKER,
57
67
  clearNewMarker,
58
68
  refuseThemeSource,
@@ -60,6 +70,8 @@ import {
60
70
  slugFor,
61
71
  themeSource,
62
72
  themeSourceProblem,
73
+ refuseThemeParse,
74
+ ownSourceTokens,
63
75
  } from './_settings.mjs';
64
76
  import {checkSetting, exampleOf, storedProblems} from './_check.mjs';
65
77
  import {MODAL} from './_compiler.mjs';
@@ -76,9 +88,10 @@ import {
76
88
  } from './_palette.mjs';
77
89
  import {renderPreview, renderSheet} from './_preview.mjs';
78
90
  import {refreshPreviewRoute} from './_preview-app.mjs';
79
- import {baseResolved, installLine} from './_project.mjs';
91
+ import {baseInstalled, baseResolved, installLine} from './_project.mjs';
80
92
  import {reactMissing} from './_parts.mjs';
81
93
  import {
94
+ renderCause,
82
95
  requireProject,
83
96
  context,
84
97
  pictures,
@@ -86,9 +99,13 @@ import {
86
99
  styledChanges,
87
100
  previewAfter,
88
101
  checkSection,
102
+ stampSheet,
89
103
  } from './_context.mjs';
90
104
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
91
- import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
105
+ import {
106
+ getCliInvocation,
107
+ quoteCommandArgument,
108
+ } from '../../foundation/env/package-manager.mjs';
92
109
 
93
110
  const E = ERROR_CODES;
94
111
 
@@ -177,6 +194,40 @@ function readableJson(file) {
177
194
  }
178
195
  }
179
196
 
197
+ /**
198
+ * A physical padding side as its logical side (left-to-right), so a later
199
+ * `padding-inline` replaces an earlier `padding-left` as it does
200
+ * `padding-inline-start`.
201
+ * @param {string} prop
202
+ */
203
+ const logicalSide = prop =>
204
+ /** @type {Record<string, string>} */ ({
205
+ 'padding-left': 'padding-inline-start',
206
+ 'padding-right': 'padding-inline-end',
207
+ 'padding-top': 'padding-block-start',
208
+ 'padding-bottom': 'padding-block-end',
209
+ })[prop] ?? prop;
210
+
211
+ /**
212
+ * Put back every recorded file: its bytes, or removed when it was not
213
+ * there; a palette file the build made new in tokens/ goes too.
214
+ * @param {Map<string, Buffer | null>} kept
215
+ * @param {string} tokensDir
216
+ */
217
+ function putBack(kept, tokensDir) {
218
+ for (const [file, bytes] of kept)
219
+ if (bytes) writeWhole(file, bytes);
220
+ else if (!fs.existsSync(file) || fs.lstatSync(file).isFile())
221
+ fs.rmSync(file, {force: true});
222
+ if (kept.size && fs.existsSync(tokensDir))
223
+ for (const n of fs.readdirSync(tokensDir)) {
224
+ const file = path.join(tokensDir, n);
225
+ // Only a file the build made new; a folder the user put there stays.
226
+ if (!kept.has(file) && fs.lstatSync(file).isFile())
227
+ fs.rmSync(file, {force: true});
228
+ }
229
+ }
230
+
180
231
  /**
181
232
  * Start a theme in themes/<name>/, optionally on a built-in theme, with any
182
233
  * dial settings applied in the same build. Each setting is checked as `set`
@@ -186,19 +237,46 @@ function readableJson(file) {
186
237
  * @param {import('./theme-edit.type.mjs').ThemeEditNewOptions} [options]
187
238
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditNewResponse>}
188
239
  */
240
+
189
241
  export async function themeEditNew(name, options = {}) {
190
242
  const {cwd = process.cwd(), png = false, settings = {}} = options;
191
243
  // `--like none` builds on no base, as `set <theme> base none` does.
192
244
  const like = options.like === 'none' ? undefined : options.like;
193
245
  requireProject(cwd);
246
+ // A corrected `new` keeps every option given, fixing only the bad one.
247
+ // A --like in another case is the built-in theme it names.
248
+ // A --like that names no built-in theme is the nearest one, or none: a
249
+ // corrected command never repeats a --like that is refused below.
250
+ // A guess (the nearest base to a word that names none) is only a base the
251
+ // project has installed: another would be refused in turn. A base named
252
+ // in other letters is the one meant, installed or not (its refusal then
253
+ // offers the install, or the same new on no base).
254
+ const have = LIKE.filter(b => baseInstalled(cwd, b));
255
+ const likeFixed =
256
+ like == null
257
+ ? options.like === 'none'
258
+ ? 'none'
259
+ : undefined
260
+ : LIKE.includes(String(like).toLowerCase())
261
+ ? String(like).toLowerCase()
262
+ : (nearest(String(like).toLowerCase(), have)[0] ?? null);
263
+ const again = (
264
+ /** @type {string} */ newName,
265
+ /** @type {string | null | undefined} */ likeValue = likeFixed,
266
+ ) => `${P} new ${newName}${newFlags(likeValue, settings, png)}`;
194
267
  if (!slugOk(name)) {
195
268
  const fixed = slugFor(name);
196
- // The name as typed may be a theme that exists in another case.
197
- const exists = fs.existsSync(themeFiles(cwd, fixed).settings);
269
+ // Only a name typed in another case is the theme here already.
270
+ const sameName = String(name ?? '').toLowerCase() === fixed;
271
+ const exists = sameName && fs.existsSync(themeFiles(cwd, fixed).settings);
198
272
  refuse(
199
273
  E.ERR_INVALID_ARGUMENT,
200
274
  `"${String(name ?? '').slice(0, 80)}" is not a theme name (${NAME_RULE})${exists ? `; ${fixed} is a theme here already` : ''}.`,
201
- {run: exists ? [`${P} show ${fixed}`] : [`${P} new ${fixed}`]},
275
+ {
276
+ run: exists
277
+ ? [`${P} show ${fixed}`]
278
+ : [again(usableNewName(cwd, fixed))],
279
+ },
202
280
  );
203
281
  }
204
282
  // A built-in theme's name would collide with the theme of that name the
@@ -207,7 +285,18 @@ export async function themeEditNew(name, options = {}) {
207
285
  refuse(
208
286
  E.ERR_FILE_EXISTS,
209
287
  `${name} is a built-in theme; an editor theme needs a name of its own. To start from ${name}, build on it.`,
210
- {run: [`${P} new my-${name} --like ${name}`]},
288
+ {
289
+ run: [
290
+ again(
291
+ fs.existsSync(themeFiles(cwd, `my-${name}`).dir)
292
+ ? freeThemeName(cwd, `my-${name}`)
293
+ : `my-${name}`,
294
+ // Built on the theme named when it is installed, unless another
295
+ // base (or none) was given.
296
+ likeFixed ?? name,
297
+ ),
298
+ ],
299
+ },
211
300
  );
212
301
  const f = themeFiles(cwd, name);
213
302
  // A link or a file where the theme goes is never written through or
@@ -218,22 +307,33 @@ export async function themeEditNew(name, options = {}) {
218
307
  refuse(
219
308
  E.ERR_FILE_EXISTS,
220
309
  `themes in this app is ${rootSt.isSymbolicLink() ? `a link (to ${fs.readlinkSync(f.root)})` : 'a file'}, not a folder, so no editor theme can be made: every theme goes in themes/<name>/. Rename or move it, then run new again.`,
221
- // A look that changes nothing: the themes the app can use now.
222
- {run: ['astryx theme list']},
310
+ // A look that changes nothing: what is in the way.
311
+ {
312
+ run: [
313
+ `ls -la ${quoteCommandArgument(path.relative(cwd, f.root) || 'themes')}`,
314
+ ],
315
+ },
223
316
  );
224
317
  const dirSt = fs.lstatSync(f.dir, {throwIfNoEntry: false});
225
318
  if (dirSt && (dirSt.isSymbolicLink() || !dirSt.isDirectory()))
226
319
  refuse(
227
320
  E.ERR_FILE_EXISTS,
228
321
  `themes/${name} is ${dirSt.isSymbolicLink() ? 'a link' : 'a file'}, so a theme is not made there.`,
229
- {run: [`${P} new ${name}-copy`]},
322
+ {run: [again(freeThemeName(cwd, name))]},
230
323
  );
231
324
  // Settings that are not valid JSON are kept aside, and the theme is
232
325
  // made again beside them.
233
326
  const damaged = fs.existsSync(f.settings) && !readableJson(f.settings);
234
327
  if (fs.existsSync(f.settings) && !damaged)
235
328
  refuse(E.ERR_FILE_EXISTS, `Theme "${name}" already exists.`, {
236
- run: [`${P} show ${name}`, `${P} set ${name} base neutral`],
329
+ // What the command asked for, on the theme that exists or as a new one.
330
+ run: [
331
+ `${P} show ${name}`,
332
+ ...(likeFixed && LIKE.includes(likeFixed)
333
+ ? [`${P} set ${name} base ${likeFixed}`]
334
+ : []),
335
+ again(freeThemeName(cwd, name)),
336
+ ],
237
337
  });
238
338
  // A `new` stopped part way (killed, out of memory) leaves its own marker
239
339
  // beside the files it wrote: only such a folder is cleared, and only
@@ -250,28 +350,38 @@ export async function themeEditNew(name, options = {}) {
250
350
  refuse(
251
351
  E.ERR_FILE_EXISTS,
252
352
  `themes/${name}/ already holds files this command did not make; choose another name.`,
253
- {run: [`${P} new ${name}-copy`]},
353
+ {run: [again(freeThemeName(cwd, name))]},
254
354
  );
255
355
  if (like != null && !LIKE.includes(like))
256
356
  refuse(
257
357
  E.ERR_THEME_BAD_VALUE,
258
358
  `--like takes a built-in theme (${LIKE.join(', ')}), not "${like}"${fs.existsSync(themeFiles(cwd, String(like)).settings) ? `; ${like} is a theme made here, and a new theme builds only on a built-in one` : ''}.`,
259
359
  {
260
- didYouMean: nearest(String(like).toLowerCase(), LIKE),
261
- run: [`${P} new ${name}`],
360
+ // The built-in theme it names in another case, or the nearest
361
+ // installed one, else none: the did-you-mean and the run agree.
362
+ didYouMean: likeFixed ? [likeFixed] : [],
363
+ run: [again(name, likeFixed ?? null)],
262
364
  },
263
365
  );
264
366
  const ctx = await context(cwd);
265
367
  /** @type {import('./_settings.mjs').ThemeData} */
266
368
  const data = {name, ...(like ? {like} : {}), mode: 'both', settings: []};
267
- /** @type {import('./_settings.mjs').Ctx} */ (ctx).base = await baseResolved(
268
- ctx.project,
269
- data.like,
270
- );
369
+ try {
370
+ /** @type {import('./_settings.mjs').Ctx} */ (ctx).base =
371
+ await baseResolved(ctx.project, data.like);
372
+ } catch (e) {
373
+ // A base that is not installed: install it, or the same new on no base.
374
+ if (e instanceof AstryxError && e.code === E.ERR_UNKNOWN_THEME)
375
+ e.suggestions = [
376
+ ...(e.suggestions ?? []),
377
+ {name: again(name, null), reason: 'build on no theme'},
378
+ ];
379
+ throw e;
380
+ }
271
381
  // Every check comes before the first change to the folder: the settings,
272
382
  // and a source of the user's own kept from before (it must still extend
273
383
  // the settings, or the build fails after the folder was cleared).
274
- applyNewSettings(ctx, name, data, settings);
384
+ applyNewSettings(ctx, name, data, settings, png, likeFixed ?? undefined);
275
385
  if (left?.keep.some(p => path.basename(p) === `${name}.theme.ts`))
276
386
  refuseThemeSource(cwd, name);
277
387
  /** @type {string[]} */
@@ -290,7 +400,7 @@ export async function themeEditNew(name, options = {}) {
290
400
  );
291
401
  if (left?.keep.some(p => path.basename(p) === `${name}.history.json`))
292
402
  leftNotes.push(
293
- `the earlier settings are kept in ${name}.history.json: \`${P} undo ${name}\` steps back to them`,
403
+ `the history is kept in ${name}.history.json: \`${P} undo ${name}\` steps back to the settings from before the last change, and the last change itself is not kept`,
294
404
  );
295
405
  // The marker goes first and comes off last: a `new` stopped between
296
406
  // leaves a folder the next `new` can prove it made. The damaged settings
@@ -417,8 +527,17 @@ export async function themeEditNew(name, options = {}) {
417
527
  * @param {string} slug
418
528
  * @param {import('./_settings.mjs').ThemeData} data
419
529
  * @param {Record<string, string | string[] | undefined>} settings
530
+ * @param {boolean} [png] kept in a corrected `new` a refusal suggests
531
+ * @param {string} [likeFlag] the --like a corrected `new` keeps (`none` too)
420
532
  */
421
- function applyNewSettings(ctx, slug, data, settings) {
533
+ function applyNewSettings(
534
+ ctx,
535
+ slug,
536
+ data,
537
+ settings,
538
+ png = false,
539
+ likeFlag = data.like,
540
+ ) {
422
541
  const given = Object.entries(settings).filter(([, v]) => v != null);
423
542
  for (const [thing] of given)
424
543
  if (!DIALS[thing] || thing === 'base')
@@ -441,13 +560,21 @@ function applyNewSettings(ctx, slug, data, settings) {
441
560
  const given = settings[thing];
442
561
  if (given == null) continue;
443
562
  // `headings` takes a weight and a tracking: one value per axis.
444
- for (const value of Array.isArray(given) ? given : [given]) {
563
+ const values = Array.isArray(given) ? given : [given];
564
+ for (const [index, value] of values.entries()) {
445
565
  /** @type {import('./_settings.mjs').Setting} */
446
566
  let s;
447
567
  try {
448
568
  s = checkSetting(ctx, slug, data, thing, String(value), {}, false);
449
569
  } catch (e) {
450
- throw asNewRefusal(e, slug, settings);
570
+ throw asNewRefusal(
571
+ vetSuggestions(e, ctx, slug, data),
572
+ slug,
573
+ settings,
574
+ likeFlag,
575
+ png,
576
+ {thing, index},
577
+ );
451
578
  }
452
579
  if (thing === 'mode')
453
580
  data.mode = /** @type {'both' | 'light-only' | 'dark-only'} */ (
@@ -460,8 +587,14 @@ function applyNewSettings(ctx, slug, data, settings) {
460
587
  E.ERR_INVALID_ARGUMENT,
461
588
  `--${thing} was given two values for the same thing (${data.settings[same].value}, ${s.value}); give one.`,
462
589
  {
590
+ // Every other option given stays, and the first value on each
591
+ // axis: every later value for an axis already given goes.
463
592
  run: [
464
- `${P} new ${slug} --${thing} ${quoteCommandArgument(s.value)}`,
593
+ `${P} new ${slug}${newFlags(
594
+ likeFlag,
595
+ {...settings, [thing]: firstPerAxis(values)},
596
+ png,
597
+ )}`,
465
598
  ],
466
599
  },
467
600
  );
@@ -471,36 +604,117 @@ function applyNewSettings(ctx, slug, data, settings) {
471
604
  }
472
605
  }
473
606
 
607
+ /**
608
+ * The options of a `new` as flags, in the order given (`new --help`'s order
609
+ * for the command): `--like`, each dial setting, then `--png`.
610
+ * @param {string | null | undefined} like none when null or undefined
611
+ * @param {Record<string, string | string[] | undefined>} settings
612
+ * @param {boolean} [png]
613
+ * @returns {string[]}
614
+ */
615
+ export function newFlagList(like, settings, png = false) {
616
+ return [
617
+ ...(like ? [`--like ${quoteCommandArgument(like)}`] : []),
618
+ ...Object.entries(settings)
619
+ .filter(([, v]) => v != null)
620
+ .flatMap(([k, v]) => (Array.isArray(v) ? v : [v]).map(x => [k, x]))
621
+ .map(([k, v]) => `--${k} ${quoteCommandArgument(String(v))}`),
622
+ ...(png ? ['--png'] : []),
623
+ ];
624
+ }
625
+
626
+ /**
627
+ * The options of a `new` as one flag line, with its leading space.
628
+ * @param {string | null | undefined} like
629
+ * @param {Record<string, string | string[] | undefined>} settings
630
+ * @param {boolean} png
631
+ */
632
+ function newFlags(like, settings, png) {
633
+ const parts = newFlagList(like, settings, png);
634
+ return parts.length ? ` ${parts.join(' ')}` : '';
635
+ }
636
+
474
637
  /**
475
638
  * A refusal from a setting `new` was given, with its suggestions turned
476
639
  * into `new` commands: the theme does not exist yet, so a `set` would fail.
477
640
  * @param {unknown} e
478
641
  * @param {string} slug
479
642
  * @param {Record<string, string | string[] | undefined>} settings
643
+ * @param {string} [like] the --like given, kept in a corrected command
644
+ * @param {boolean} [png] --png, kept in a corrected command
645
+ * @param {{thing: string, index: number} | null} [at] the value refused
480
646
  */
481
- function asNewRefusal(e, slug, settings) {
647
+ function asNewRefusal(e, slug, settings, like, png = false, at = null) {
482
648
  if (!(e instanceof AstryxError)) return e;
483
- const flags = Object.entries(settings)
484
- .filter(([, v]) => v != null)
485
- .flatMap(([k, v]) => (Array.isArray(v) ? v : [v]).map(x => [k, x]))
486
- .map(([k, v]) => `--${k} ${quoteCommandArgument(String(v))}`);
487
649
  const setPrefix = `${P} set ${slug} `;
488
650
  e.suggestions = (e.suggestions ?? []).map(s => {
489
651
  if (s.name === `${P} set --help`) return {...s, name: `${P} new --help`};
490
652
  if (!s.name.startsWith(setPrefix)) return s;
491
653
  const [thing, ...rest] = s.name.slice(setPrefix.length).split(' ');
492
654
  if (thing.startsWith('--') || !DIALS[thing]) return s;
493
- const keep = flags.filter(f => !f.startsWith(`--${thing} `));
655
+ const fixed = unquoteWord(rest.join(' '));
656
+ // Only the refused value changes: a dial given several values
657
+ // (--headings tight --headings BOLD) keeps the others, in order.
658
+ const given = settings[thing];
659
+ const values = Array.isArray(given) ? [...given] : null;
660
+ const next =
661
+ values && at && at.thing === thing
662
+ ? firstPerAxis(values.map((v, i) => (i === at.index ? fixed : v)))
663
+ : fixed;
494
664
  return {
495
665
  ...s,
496
- name: [`${P} new ${slug}`, ...keep, `--${thing} ${rest.join(' ')}`].join(
497
- ' ',
498
- ),
666
+ name: `${P} new ${slug}${newFlags(like, {...settings, [thing]: next}, png)}`,
499
667
  };
500
668
  });
669
+ // A refused value with nothing to put in its place: the same new
670
+ // without it, every other option kept.
671
+ if (at && !e.suggestions.some(x => x.name.startsWith(`${P} new `))) {
672
+ const given = settings[at.thing];
673
+ const rest = Array.isArray(given)
674
+ ? given.filter((_, i) => i !== at.index)
675
+ : undefined;
676
+ e.suggestions.push({
677
+ name: `${P} new ${slug}${newFlags(like, {...settings, [at.thing]: rest?.length ? rest : undefined}, png)}`,
678
+ reason: `without --${at.thing} ${quoteCommandArgument(String(Array.isArray(given) ? given[at.index] : given))}`,
679
+ });
680
+ }
501
681
  return e;
502
682
  }
503
683
 
684
+ /**
685
+ * Headings values with every later value for an axis already given left
686
+ * out (the first weight and the first tracking stay); a word of neither
687
+ * axis stays, for its own refusal.
688
+ * @param {string[]} values
689
+ * @returns {string[]}
690
+ */
691
+ function firstPerAxis(values) {
692
+ const seen = new Set();
693
+ return values.filter(v => {
694
+ const w = String(v).trim().toLowerCase();
695
+ const axis =
696
+ HEADING_WEIGHTS[w] !== undefined
697
+ ? 'weight'
698
+ : HEADING_TRACKING[w] !== undefined
699
+ ? 'tracking'
700
+ : null;
701
+ if (!axis) return true;
702
+ if (seen.has(axis)) return false;
703
+ seen.add(axis);
704
+ return true;
705
+ });
706
+ }
707
+
708
+ /**
709
+ * A word as a suggested command writes it, without the quotes
710
+ * quoteCommandArgument adds.
711
+ * @param {string} word
712
+ */
713
+ function unquoteWord(word) {
714
+ const m = /^'(.*)'$/s.exec(word);
715
+ return m ? m[1].replace(/'\\''/g, "'") : word;
716
+ }
717
+
504
718
  /**
505
719
  * The preview after a change, with the in-app preview route kept in step:
506
720
  * its imports follow the theme, such as the stylesheet of a font package
@@ -571,7 +785,12 @@ function refuseStoredTokens(ctx, slug, data, skip) {
571
785
  // setting is never refused for another.
572
786
  run: [
573
787
  ...bad.slice(0, 5).map(b => `${P} undo ${slug} ${undoArgs(b.setting)}`),
574
- ...(one && !one.scope
788
+ // A value to set only for a token whose stored value has the wrong
789
+ // type; any other thing `set` would refuse, or read as a dial.
790
+ ...(one &&
791
+ !one.scope &&
792
+ one.setting.source === 'token' &&
793
+ ctx.C.isToken(one.setting.thing)
575
794
  ? [
576
795
  `${P} set ${slug} ${one.setting.thing} ${quoteCommandArgument(exampleOf(ctx.C.typeOf(one.setting.thing), one.setting.thing))}`,
577
796
  ]
@@ -581,6 +800,36 @@ function refuseStoredTokens(ctx, slug, data, skip) {
581
800
  );
582
801
  }
583
802
 
803
+ /**
804
+ * A name `new` takes, for a suggestion: `name` itself when it is valid, not a
805
+ * built-in theme and its folder is free; `my-<name>` for a built-in theme's
806
+ * name; else the first free numbered name.
807
+ * @param {string} cwd
808
+ * @param {string} name
809
+ */
810
+ function usableNewName(cwd, name) {
811
+ const base = LIKE.includes(name) ? `my-${name}` : name;
812
+ return slugOk(base) && !fs.existsSync(themeFiles(cwd, base).dir)
813
+ ? base
814
+ : freeThemeName(cwd, base);
815
+ }
816
+
817
+ /**
818
+ * A theme name near `name` that is valid and whose folder is free: `name-2`,
819
+ * `name-3`, …, shortened to fit the name's length limit.
820
+ * @param {string} cwd
821
+ * @param {string} name
822
+ */
823
+ function freeThemeName(cwd, name) {
824
+ for (let n = 2; n < 1000; n += 1) {
825
+ const suffix = `-${n}`;
826
+ const candidate = `${name.slice(0, 64 - suffix.length).replace(/-+$/, '')}${suffix}`;
827
+ if (slugOk(candidate) && !fs.existsSync(themeFiles(cwd, candidate).dir))
828
+ return candidate;
829
+ }
830
+ return '<another name>';
831
+ }
832
+
584
833
  /**
585
834
  * A note for type scale steps that land outside 9 to 200 pixels.
586
835
  * @param {Record<string, string>} res resolved light tokens
@@ -611,6 +860,54 @@ function extremeSteps(res) {
611
860
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
612
861
  */
613
862
  async function change(sub, slug, thing, value, options) {
863
+ /** @type {{ctx?: import('./_settings.mjs').Ctx, data?: import('./_settings.mjs').ThemeData}} */
864
+ const seen = {};
865
+ try {
866
+ return await changeOnce(sub, slug, thing, value, options, seen);
867
+ } catch (e) {
868
+ // A theme name one letter off an existing theme: the same command with
869
+ // that name comes first, before making a theme of the typo.
870
+ if (e instanceof AstryxError && e.code === E.ERR_UNKNOWN_THEME) {
871
+ const near = (e.suggestions ?? []).find(x => x.reason === 'did you mean');
872
+ if (near && slugOk(near.name)) {
873
+ const flags = [
874
+ ...(options.on ? ['--on', options.on] : []),
875
+ ...(options.when ? ['--when', options.when] : []),
876
+ ...(options.state ? ['--state', options.state] : []),
877
+ ...(options.mode ? ['--mode', options.mode] : []),
878
+ ...(options.only ? ['--only'] : []),
879
+ ];
880
+ const words = [thing, ...(value == null ? [] : [value]), ...flags]
881
+ .filter(w => w != null && w !== '')
882
+ .map(w =>
883
+ String(w).startsWith('--') ? w : quoteCommandArgument(String(w)),
884
+ );
885
+ e.suggestions = [
886
+ {
887
+ name: `${P} ${sub} ${near.name}${words.length ? ` ${words.join(' ')}` : ''}`,
888
+ reason: `do this instead: ${near.name} is a theme here`,
889
+ },
890
+ ...(e.suggestions ?? []).filter(x => x !== near),
891
+ ];
892
+ }
893
+ throw e;
894
+ }
895
+ // Every `set` the refusal suggests is checked as `set` checks it.
896
+ throw vetSuggestions(e, seen.ctx, slug, seen.data);
897
+ }
898
+ }
899
+
900
+ /**
901
+ * @param {'set' | 'undo'} sub
902
+ * @param {string} slug
903
+ * @param {string} thing
904
+ * @param {string | undefined} value
905
+ * @param {ChangeOptions} options
906
+ * @param {{ctx?: import('./_settings.mjs').Ctx, data?: import('./_settings.mjs').ThemeData}} seen
907
+ * the context and the theme as loaded, for checking a refusal's suggestions
908
+ * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
909
+ */
910
+ async function changeOnce(sub, slug, thing, value, options, seen) {
614
911
  const {cwd = process.cwd(), png = false} = options;
615
912
  requireProject(cwd);
616
913
  // The setting this command changes or removes may be the bad one; any
@@ -664,6 +961,8 @@ async function change(sub, slug, thing, value, options) {
664
961
  );
665
962
  }
666
963
  /** @type {import('./_settings.mjs').Ctx} */ (ctx).base = base;
964
+ seen.ctx = ctx;
965
+ seen.data = structuredClone(data);
667
966
  /** @type {import('./_settings.mjs').Setting} */
668
967
  let s;
669
968
  try {
@@ -675,11 +974,13 @@ async function change(sub, slug, thing, value, options) {
675
974
  sub === 'undo'
676
975
  ? data.settings.find(
677
976
  x =>
678
- x.thing === thing &&
977
+ x.thing.toLowerCase() === String(thing).toLowerCase() &&
679
978
  (x.on ?? null) === (flags.on ?? null) &&
680
979
  (x.when ?? null) === (flags.when ?? null) &&
681
980
  (x.state ?? null) === (flags.state ?? null) &&
682
- (x.mode ?? null) === (flags.mode ?? null),
981
+ (x.mode ?? null) === (flags.mode ?? null) &&
982
+ // --only names a setting made with it; it is never dropped.
983
+ Boolean(x.only) === Boolean(flags.only),
683
984
  )
684
985
  : null;
685
986
  if (!stored) {
@@ -687,13 +988,50 @@ async function change(sub, slug, thing, value, options) {
687
988
  // what it named (or of the dial its refusal names), else the last
688
989
  // step.
689
990
  if (sub === 'undo' && e instanceof AstryxError) {
991
+ // Setting names are matched in any case, and a near name of a
992
+ // setting the theme has counts: `undo t Corners`, `undo t corner`.
993
+ const typed = String(thing).toLowerCase();
994
+ // A token named without its dashes (radius-element) is the token.
995
+ const dashed = typed.startsWith('--') ? typed : `--${typed}`;
690
996
  const named = new Set([
691
- thing,
997
+ typed,
998
+ dashed,
692
999
  ...(e.suggestions ?? [])
693
- .map(x => new RegExp(` set ${slug} (\\S+)`).exec(x.name)?.[1])
1000
+ .filter(x => x.reason === 'did you mean')
1001
+ .map(x => x.name.toLowerCase()),
1002
+ ...(e.suggestions ?? [])
1003
+ .map(
1004
+ x => new RegExp(` (?:set|undo) ${slug} (\\S+)`).exec(x.name)?.[1],
1005
+ )
694
1006
  .filter(Boolean),
1007
+ ...nearest(
1008
+ typed,
1009
+ data.settings.map(x => x.thing.toLowerCase()),
1010
+ ),
695
1011
  ]);
696
- const matches = data.settings.filter(x => named.has(x.thing));
1012
+ const matches = data.settings.filter(x =>
1013
+ named.has(x.thing.toLowerCase()),
1014
+ );
1015
+ // A word that is near a setting name (a typo, another case) is never
1016
+ // answered with a bare step back, which would undo another change;
1017
+ // any other word (`all`) may mean the last step.
1018
+ // A token or a property named (radius-element, padding) is a named
1019
+ // thing too: never answered with a step back.
1020
+ const namesThing =
1021
+ ctx.C.isToken(dashed) ||
1022
+ data.settings.some(
1023
+ x => x.source === 'property' && x.thing.toLowerCase() === typed,
1024
+ ) ||
1025
+ /^[a-z]+(-[a-z]+)+$|^(padding|margin|color|background|border|gap|width|height|opacity)$/.test(
1026
+ typed,
1027
+ );
1028
+ const nearSetting =
1029
+ namesThing ||
1030
+ named.size > (dashed === typed ? 1 : 2) ||
1031
+ nearest(typed, [
1032
+ ...Object.keys(DIALS),
1033
+ ...data.settings.map(x => x.thing.toLowerCase()),
1034
+ ]).length > 0;
697
1035
  const steps = readHistory(themeFiles(cwd, slug).history).steps.length;
698
1036
  throw new AstryxError(
699
1037
  e.message,
@@ -703,7 +1041,7 @@ async function change(sub, slug, thing, value, options) {
703
1041
  reason: 'do this instead',
704
1042
  }))
705
1043
  : [
706
- steps
1044
+ steps && !nearSetting
707
1045
  ? {name: `${P} undo ${slug}`, reason: 'step back one change'}
708
1046
  : {name: `${P} show ${slug}`, reason: 'see what it sets'},
709
1047
  ],
@@ -734,7 +1072,11 @@ async function change(sub, slug, thing, value, options) {
734
1072
  .trim()
735
1073
  .toLowerCase()
736
1074
  .replace(/\s+/g, ' ')
737
- .replace(/^["']|["']$/g, '');
1075
+ // Spacing around commas, slashes and parentheses, and the quote
1076
+ // style, are not part of a value.
1077
+ .replace(/\s*([,()/])\s*/g, '$1')
1078
+ .replace(/'/g, '"')
1079
+ .replace(/^"|"$/g, '');
738
1080
  const half =
739
1081
  s.thing === 'headings' && ['weight', 'tracking'].includes(norm(value));
740
1082
  if (
@@ -819,9 +1161,16 @@ async function change(sub, slug, thing, value, options) {
819
1161
  if (sub === 'undo') {
820
1162
  if (!prev) {
821
1163
  const near = data.settings.filter(x => x.thing === s.thing).map(describe);
1164
+ // headings has two halves: name the one that is set.
1165
+ const otherHalf =
1166
+ s.thing === 'headings'
1167
+ ? data.settings.find(x => x.thing === 'headings' && x.axis !== s.axis)
1168
+ : null;
822
1169
  refuse(
823
1170
  E.ERR_THEME_NOT_SET,
824
- `The theme does not set ${describe({...s, value: '?'}).replace(' = ?', '')}.`,
1171
+ otherHalf
1172
+ ? `The theme sets only the headings ${otherHalf.axis ?? 'weight'} half (${describe(otherHalf)}), not its ${s.axis ?? 'weight'}; \`${P} undo ${slug} ${undoArgs(otherHalf)}\` removes the one that is set.`
1173
+ : `The theme does not set ${describe({...s, value: '?'}).replace(' = ?', '')}.`,
825
1174
  {
826
1175
  also: near.length
827
1176
  ? [`settings for ${s.thing}: ${near.join('; ')}`]
@@ -837,6 +1186,8 @@ async function change(sub, slug, thing, value, options) {
837
1186
  );
838
1187
  }
839
1188
  data.settings.splice(prevIdx, 1);
1189
+ // A setting listed twice by hand goes in full.
1190
+ data.settings = data.settings.filter(x => keyOf(x) !== k);
840
1191
  // Vibrancy needs a color: undoing the last one takes it along, so the
841
1192
  // theme never holds a state `set` refuses.
842
1193
  if (
@@ -872,6 +1223,13 @@ async function change(sub, slug, thing, value, options) {
872
1223
  if (prev) data.settings.splice(prevIdx, 1);
873
1224
  data.settings.push(s);
874
1225
  }
1226
+ // A setting listed twice by hand keeps only the entry this command left.
1227
+ if (sub === 'set') {
1228
+ const last = data.settings.map(x => keyOf(x)).lastIndexOf(k);
1229
+ data.settings = data.settings.filter(
1230
+ (x, i) => keyOf(x) !== k || i === last,
1231
+ );
1232
+ }
875
1233
  // A setting for both modes replaces the ones made for one mode, which it
876
1234
  // would otherwise sit under.
877
1235
  /** @type {import('./_settings.mjs').Setting[]} */
@@ -889,16 +1247,24 @@ async function change(sub, slug, thing, value, options) {
889
1247
  x =>
890
1248
  x !== s &&
891
1249
  x.source === 'property' &&
892
- x.on === s.on &&
1250
+ // On the same part, or on a member of the group it is set on:
1251
+ // the later setting wins, whichever way Core writes it.
1252
+ (x.on === s.on ||
1253
+ (s.on != null &&
1254
+ (FAMILIES[s.on] ?? []).includes(
1255
+ /** @type {string} */ (x.on),
1256
+ ))) &&
893
1257
  x.when === s.when &&
894
1258
  x.state === s.state &&
895
- x.thing.startsWith(`${s.thing}-`) &&
896
- // Not part of border: its radius, collapse and spacing.
897
- !/^border-(radius|collapse|spacing)$|^border-[a-z]+-radius$/.test(
898
- x.thing,
899
- ),
1259
+ // A longhand the shorthand really sets (MDN's data), never a
1260
+ // property that only shares its name (overflow-wrap).
1261
+ (coversProperty(s.thing, x.thing) ||
1262
+ coversProperty(logicalSide(s.thing), logicalSide(x.thing))),
900
1263
  )
901
1264
  : [];
1265
+ // They go, as the note says: Core writes each side to its own variable,
1266
+ // where a later shorthand would not win over them (undo brings them back).
1267
+ data.settings = data.settings.filter(x => !longhands.includes(x));
902
1268
  // A group setting covers part settings made before it for its members.
903
1269
  const covers =
904
1270
  sub === 'set' && s.source === 'dial' && s.on && FAMILIES[s.on]
@@ -917,37 +1283,16 @@ async function change(sub, slug, thing, value, options) {
917
1283
  const parts = partsOf(ctx, s);
918
1284
  // Exact whole-theme tokens that win over what this dial writes: the dial
919
1285
  // changes them only in a theme without them.
920
- /** @param {import('./_settings.mjs').Setting[]} list */
921
- const dialsOnly = list => ({
922
- ...data,
923
- settings: list.filter(x => x.source === 'dial'),
924
- });
925
1286
  /** @type {import('./_settings.mjs').Setting[]} */
926
1287
  let exactWins = [];
1288
+ /** Tokens this whole-theme dial changes. */
1289
+ let dialTokens = new Set();
927
1290
  if (sub === 'set' && s.source === 'dial' && !s.on) {
928
- const withDial = compileTheme(ctx, dialsOnly(data.settings), base);
929
- const without = compileTheme(
930
- ctx,
931
- dialsOnly(data.settings.filter(x => x !== s)),
932
- base,
933
- );
934
- const differs = (/** @type {unknown} */ a, /** @type {unknown} */ b) =>
935
- JSON.stringify(a) !== JSON.stringify(b);
936
- const touched = new Set(
937
- [
938
- ...Object.keys(withDial.tokens ?? {}),
939
- ...Object.keys(without.tokens ?? {}),
940
- ].filter(k => differs(withDial.tokens?.[k], without.tokens?.[k])),
941
- );
942
- for (const r of FONT_ROLES)
943
- if (differs(withDial.typography?.[r], without.typography?.[r]))
944
- touched.add(`--font-family-${r}`);
945
- if (differs(withDial.typography?.scale, without.typography?.scale))
946
- for (const k of Object.keys(ctx.project.core.tokenDefaults ?? {}))
947
- if (/^--font-size-/.test(k)) touched.add(k);
1291
+ const touched = dialTouched(ctx, data, s, base);
948
1292
  exactWins = data.settings.filter(
949
1293
  x => x.source === 'token' && !x.on && !x.when && touched.has(x.thing),
950
1294
  );
1295
+ dialTokens = touched;
951
1296
  }
952
1297
  const kept =
953
1298
  sub === 'set' && s.source === 'dial' && !s.on
@@ -956,13 +1301,42 @@ async function change(sub, slug, thing, value, options) {
956
1301
  ...exactWins,
957
1302
  ].map(describe)
958
1303
  : [];
1304
+ // The role fonts a whole-theme font sits under.
1305
+ const roleOver =
1306
+ sub === 'set' && s.thing === 'font' && !s.on
1307
+ ? data.settings.filter(
1308
+ x => x.thing === 'font' && x.on && ['body', 'heading'].includes(x.on),
1309
+ )
1310
+ : [];
959
1311
  // The exact property a dial on a part competes with there.
960
- const DIAL_PROPERTY = /** @type {Record<string, RegExp>} */ ({
961
- corners: /radius$/,
962
- spacing: /^(padding|gap)(-|$)/,
963
- });
1312
+ const DIAL_PROPERTY = wordTable(
1313
+ /** @type {Record<string, RegExp>} */ ({
1314
+ corners: /radius$/,
1315
+ spacing: /^(padding|gap)(-|$)/,
1316
+ }),
1317
+ );
1318
+ // A whole-theme look dial (buttons, surfaces) writes part properties
1319
+ // too: an exact property on one of them wins there, read from the build.
1320
+ const looksOver =
1321
+ sub === 'set' && s.source === 'dial' && !DIAL_PROPERTY[s.thing]
1322
+ ? (() => {
1323
+ const writes = dialWrites(ctx, data, s, base);
1324
+ if (!writes.size) return null;
1325
+ return (
1326
+ data.settings.find(
1327
+ x =>
1328
+ x.source === 'property' &&
1329
+ x.on &&
1330
+ !x.when &&
1331
+ !x.state &&
1332
+ partsOf(ctx, x).some(t => writes.has(`${t}\0${x.thing}`)),
1333
+ ) ?? null
1334
+ );
1335
+ })()
1336
+ : null;
964
1337
  const exactOver =
965
- sub === 'set' && s.source === 'dial' && s.on && DIAL_PROPERTY[s.thing]
1338
+ looksOver ??
1339
+ (sub === 'set' && s.source === 'dial' && s.on && DIAL_PROPERTY[s.thing]
966
1340
  ? (data.settings.find(
967
1341
  x =>
968
1342
  x.source === 'property' &&
@@ -972,7 +1346,7 @@ async function change(sub, slug, thing, value, options) {
972
1346
  (x.when ?? '') === (s.when ?? '') &&
973
1347
  (x.state ?? '') === (s.state ?? ''),
974
1348
  ) ?? null)
975
- : null;
1349
+ : null);
976
1350
  /** @type {string[]} */
977
1351
  const notes = [
978
1352
  ...(covered.length ? [`replaces ${covered.map(describe).join(', ')}`] : []),
@@ -986,6 +1360,29 @@ async function change(sub, slug, thing, value, options) {
986
1360
  `comes after ${covers.map(describe).join(', ')}, so ${covers.length > 1 ? 'those parts show' : `${covers[0].on} shows`} this value now; set ${covers.length > 1 ? 'one' : 'it'} again to make it win`,
987
1361
  ]
988
1362
  : []),
1363
+ // Core writes a part's derived variables (a button's or card's radius
1364
+ // variable, read by what is drawn inside it) from plain declarations
1365
+ // only: in a state they keep the plain value, and the result says so.
1366
+ ...(sub === 'set' && s.state && s.on
1367
+ ? (() => {
1368
+ const prop =
1369
+ s.thing === 'corners' || /radius$/.test(s.thing)
1370
+ ? 'borderRadius'
1371
+ : s.thing === 'padding' || s.thing === 'spacing'
1372
+ ? 'padding'
1373
+ : s.thing.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
1374
+ const vars = parts.flatMap(t =>
1375
+ (ctx.derived?.[t] ?? [])
1376
+ .filter(d => d.property === prop)
1377
+ .flatMap(d => d.vars ?? []),
1378
+ );
1379
+ return vars.length
1380
+ ? [
1381
+ `in the ${s.state} state, ${[...new Set(vars)].join(', ')} (which Core sets from the plain value, for what is drawn inside the part) keeps the plain value`,
1382
+ ]
1383
+ : [];
1384
+ })()
1385
+ : []),
989
1386
  // Phones keep the base theme's reading sizes (a coarse pointer below
990
1387
  // the lg width), so a size change says where it applies.
991
1388
  ...(sub === 'set' &&
@@ -1006,11 +1403,23 @@ async function change(sub, slug, thing, value, options) {
1006
1403
  `${describe(exactOver)} is an exact property and wins over ${s.thing} there, so this shows only after \`${P} undo ${slug} ${undoArgs(exactOver)}\``,
1007
1404
  ]
1008
1405
  : []),
1406
+ // A whole-theme font under fonts set for each role shows only where no
1407
+ // role font is set.
1408
+ ...(roleOver.length
1409
+ ? [
1410
+ `keeps your ${roleOver.map(describe).join(', ')}: a font for one role wins over the whole-theme font, so ${s.value} shows there only after ${roleOver.map(x => `\`${P} undo ${slug} ${undoArgs(x)}\``).join(' and ')}`,
1411
+ ]
1412
+ : []),
1009
1413
  // An accepted change that the theme already showed says so.
1010
1414
  ...(sub === 'set' &&
1011
1415
  !exactOver &&
1012
- // With the last build unreadable, nothing was compared.
1013
- !r.notes.some(n => n.includes('could not be read')) &&
1416
+ !roleOver.length &&
1417
+ // With the last build unreadable or missing, nothing was compared.
1418
+ !r.notes.some(
1419
+ n =>
1420
+ n.includes('could not be read') ||
1421
+ n.includes('there was no last build'),
1422
+ ) &&
1014
1423
  !r.unchanged &&
1015
1424
  !r.changed.length &&
1016
1425
  !styled.length &&
@@ -1019,6 +1428,23 @@ async function change(sub, slug, thing, value, options) {
1019
1428
  `this changes nothing you see: the theme already shows ${describe(s)} (it is saved, and stays when the base theme changes)`,
1020
1429
  ]
1021
1430
  : []),
1431
+ // A card's content takes one radius from Core, whatever its corners.
1432
+ ...(sub === 'set' &&
1433
+ s.source === 'property' &&
1434
+ s.thing === 'border-radius' &&
1435
+ s.on &&
1436
+ (ctx.derived?.[s.on] ?? []).some(
1437
+ d => d.property === 'borderRadius' && d.vars?.length,
1438
+ ) &&
1439
+ /\s|\//.test(String(s.value).trim())
1440
+ ? [
1441
+ `each corner of ${s.on} takes its own radius; the content that reaches its edges takes one, ${
1442
+ String(s.value)
1443
+ .trim()
1444
+ .split(/[\s/]+/)[0]
1445
+ }, for every corner (Core gives it a single radius)`,
1446
+ ]
1447
+ : []),
1022
1448
  ...(longhands.length
1023
1449
  ? [
1024
1450
  `${s.thing} comes after ${longhands.map(x => x.thing).join(', ')} on ${s.on}, so it replaces them there`,
@@ -1039,6 +1465,15 @@ async function change(sub, slug, thing, value, options) {
1039
1465
  : null
1040
1466
  : null;
1041
1467
  if (s.note) notes.push(s.note);
1468
+ // A token the theme's own source sets itself wins over what this dial
1469
+ // writes, as an exact setting does.
1470
+ const ownWins = ownSourceTokens(cwd, slug).filter(
1471
+ k => dialTokens.has(k) && !exactWins.some(x => x.thing === k),
1472
+ );
1473
+ if (ownWins.length)
1474
+ notes.push(
1475
+ `${slug}.theme.ts sets ${ownWins.slice(0, 4).join(', ')}${ownWins.length > 4 ? ` and ${ownWins.length - 4} more` : ''} itself, and your own source wins over the settings, so ${ownWins.length > 1 ? 'those do' : 'that does'} not change; take ${ownWins.length > 1 ? 'them' : 'it'} out of ${slug}.theme.ts to let ${s.thing} set ${ownWins.length > 1 ? 'them' : 'it'}`,
1476
+ );
1042
1477
  if (PALETTE_DIALS.includes(s.thing) && sub === 'set')
1043
1478
  notes.push(
1044
1479
  ...paletteNotes(
@@ -1104,8 +1539,13 @@ async function change(sub, slug, thing, value, options) {
1104
1539
  if (s.thing === 'font' && sub === 'set')
1105
1540
  notes.unshift(...fontNotes(ctx, {...data, settings: [s]}));
1106
1541
  if (s.thing === 'type' || s.thing === 'headings')
1107
- for (const [m, why] of maskedSettings(data))
1542
+ for (const [m, why] of maskedSettings(data, ctx))
1108
1543
  notes.push(`${describe(m)}: ${why}`);
1544
+ // An earlier setting this one now covers (through a spread too) is named.
1545
+ else if (sub === 'set')
1546
+ for (const [m, why] of maskedSettings(data, ctx))
1547
+ if (m !== s && why.startsWith(describe(s)))
1548
+ notes.push(`${describe(m)} no longer shows: ${why}`);
1109
1549
  if (s.thing === 'type' && sub === 'set' && TYPE_STYLES[s.value].ratio > 1.2)
1110
1550
  notes.push(
1111
1551
  'text below the base size keeps its standard sizes, so small text stays readable',
@@ -1235,22 +1675,108 @@ export async function themeEditShow(theme, options = {}) {
1235
1675
  ? [installLine(cwd, ['react', 'react-dom'])]
1236
1676
  : // Two copies of React and other install problems are named by
1237
1677
  // doctor; the same show would fail the same way.
1238
- ['astryx doctor'],
1678
+ [`${getCliInvocation(cwd)} doctor`],
1239
1679
  },
1240
1680
  );
1241
1681
  const f = themeFiles(cwd, theme);
1242
1682
  // A build that does not match the settings (a command stopped mid-build,
1243
1683
  // a hand edit, another CLI) is made again from the settings, and said.
1244
- const stale = staleBuild(cwd, theme, data);
1684
+ // An own source that does not parse is refused before anything is
1685
+ // built, written or removed (the build would fail part way).
1686
+ if (!readOnly) refuseThemeParse(cwd, theme);
1245
1687
  const brokenSource = themeSourceProblem(cwd, theme);
1246
- if (stale && !brokenSource && !readOnly) await buildTheme(ctx, theme, data);
1688
+ // Every output, as `compile --check` reads them: one missing or edited by
1689
+ // hand is built again too.
1690
+ const stale =
1691
+ staleBuild(cwd, theme, data) ||
1692
+ (brokenSource ? null : await outputsDrift(ctx, theme));
1693
+ // Every file the build may rewrite or remove (the settings module, the
1694
+ // built outputs, the variants types, section sheets, pictures), so a
1695
+ // theme source that does not build, or builds a value that is not text,
1696
+ // leaves the folder exactly as it was.
1697
+ // An output that was not there is recorded as absent (null), so putting
1698
+ // the folder back removes what the build made new; the palette files in
1699
+ // tokens/ are recorded the same way.
1700
+ /** @type {Map<string, Buffer | null>} */
1701
+ let kept = new Map();
1702
+ const tokensDir = path.join(f.dir, 'tokens');
1703
+ if (stale && !brokenSource && !readOnly) {
1704
+ kept = new Map(
1705
+ fs
1706
+ .readdirSync(f.dir)
1707
+ .filter(
1708
+ n =>
1709
+ n === path.basename(f.settingsTs) ||
1710
+ (n.startsWith(`${theme}.`) &&
1711
+ /\.(css|js|d\.ts|css\.d\.ts|variants\.d\.ts)$/.test(n)) ||
1712
+ /^(sheet-[a-z-]+\.html|(sheet|preview)(-[a-z-]+)?\.png)$/.test(n),
1713
+ )
1714
+ .map(n => [path.join(f.dir, n), fs.readFileSync(path.join(f.dir, n))]),
1715
+ );
1716
+ for (const n of [
1717
+ path.basename(f.settingsTs),
1718
+ `${theme}.css`,
1719
+ `${theme}.js`,
1720
+ `${theme}.d.ts`,
1721
+ `${theme}.css.d.ts`,
1722
+ `${theme}.variants.d.ts`,
1723
+ ])
1724
+ if (!kept.has(path.join(f.dir, n))) kept.set(path.join(f.dir, n), null);
1725
+ if (fs.existsSync(tokensDir))
1726
+ for (const n of fs.readdirSync(tokensDir)) {
1727
+ const file = path.join(tokensDir, n);
1728
+ if (fs.statSync(file).isFile()) kept.set(file, fs.readFileSync(file));
1729
+ }
1730
+ const refs = path.join(tokensDir, `${theme}.palette-refs.ts`);
1731
+ if (!kept.has(refs)) kept.set(refs, null);
1732
+ try {
1733
+ await buildTheme(ctx, theme, data);
1734
+ } catch (e) {
1735
+ putBack(kept, tokensDir);
1736
+ if (e instanceof AstryxError && e.code !== E.ERR_THEME_LOAD) throw e;
1737
+ // An own theme source that no longer builds is named, as `set` names
1738
+ // it; the old build is never shown as current.
1739
+ const why = (e instanceof Error ? e.message : String(e))
1740
+ .split(`${cwd}${path.sep}`)
1741
+ .join('')
1742
+ .replace(/\s*Make sure all imports[^|]*$/s, '')
1743
+ .split('\n')
1744
+ .slice(0, 3)
1745
+ .join(' | ');
1746
+ refuse(
1747
+ E.ERR_THEME_INVALID,
1748
+ `${theme} did not build: ${why}${why.includes(path.basename(f.ts)) ? ` (${shown(cwd, f.ts)} is your own file: fix it, then run show again)` : ''}`,
1749
+ {run: [`${P} how --list dials`]},
1750
+ );
1751
+ }
1752
+ }
1247
1753
  // The settings loaded whole: a `new` marker beside them is stale.
1248
1754
  if (!readOnly) clearNewMarker(f.dir);
1249
1755
  // A built module that cannot be read (damaged by hand) is built again.
1250
1756
  /** @type {string | null} */
1251
1757
  let unreadable = null;
1252
1758
  const res = await resolvedTokens(ctx, theme).catch(async e => {
1759
+ if (
1760
+ e instanceof AstryxError &&
1761
+ e.code === E.ERR_THEME_INVALID &&
1762
+ kept.size
1763
+ ) {
1764
+ // What this show just built goes back with the refusal.
1765
+ putBack(kept, tokensDir);
1766
+ throw e;
1767
+ }
1253
1768
  if (e instanceof AstryxError || readOnly) throw e;
1769
+ // The source lines the settings need are missing too: the build cannot
1770
+ // be made again until they are back, and show says so (never a run of
1771
+ // show itself).
1772
+ if (brokenSource)
1773
+ refuse(
1774
+ E.ERR_THEME_INVALID,
1775
+ `${theme}.js could not be read, and it cannot be built again: ${brokenSource}. Put back the import of ${camel(theme)}Settings from './${theme}.settings', extends: ${camel(theme)}Settings and name: '${theme}' in ${shown(cwd, f.ts)}, then run show again.`,
1776
+ {
1777
+ run: [`cat ${quoteCommandArgument(shown(cwd, f.ts))}`],
1778
+ },
1779
+ );
1254
1780
  unreadable = `${theme}.js could not be read (${e instanceof Error ? e.message.split('\n')[0] : String(e)}), so it was built again from the settings`;
1255
1781
  await buildTheme(ctx, theme, data);
1256
1782
  return resolvedTokens(ctx, theme);
@@ -1265,13 +1791,35 @@ export async function themeEditShow(theme, options = {}) {
1265
1791
  await baseResolved(ctx.project, data.like),
1266
1792
  ctx.project.core.tokenDefaults,
1267
1793
  );
1794
+ // A render that fails here (two copies of React, a component that
1795
+ // throws) is refused as the one above: what this show built goes back,
1796
+ // and the result says so.
1797
+ const rendering = async (/** @type {() => Promise<any>} */ run) => {
1798
+ try {
1799
+ return await run();
1800
+ } catch (e) {
1801
+ if (!(e instanceof Error)) throw e;
1802
+ if (e instanceof AstryxError && e.code !== E.ERR_RENDER_FAILED) throw e;
1803
+ putBack(kept, tokensDir);
1804
+ return refuse(
1805
+ E.ERR_RENDER_FAILED,
1806
+ `${theme} cannot be shown: ${renderCause(ctx.project, e.message)} ${[...kept.values()].some(Boolean) ? 'The build this show made again was put back as it was. ' : ''}Nothing was written.`,
1807
+ {run: [`${getCliInvocation(cwd)} doctor`]},
1808
+ );
1809
+ }
1810
+ };
1268
1811
  const preview = noPages
1269
1812
  ? shown(cwd, f.preview)
1270
- : await renderPreview(ctx, theme, data);
1271
- const previewStale = noPages ? [] : await keepPreviewRoute(ctx, theme);
1813
+ : await rendering(() => renderPreview(ctx, theme, data));
1814
+ const previewStale = noPages
1815
+ ? []
1816
+ : await rendering(() => keepPreviewRoute(ctx, theme));
1272
1817
  const sheet = noPages
1273
1818
  ? {file: shown(cwd, f.sheet), components: 0, skipped: []}
1274
- : await renderSheet(ctx, theme, data, {group: section});
1819
+ : await rendering(() => renderSheet(ctx, theme, data, {group: section}));
1820
+ // The full sheet records the build it shows, so a later change tells a
1821
+ // sheet that still matches (after an undo) from one that does not.
1822
+ if (!noPages && !section) stampSheet(f.sheet, theme, cwd);
1275
1823
  const modes = modesOf(data);
1276
1824
  const shots =
1277
1825
  png && !noPages
@@ -1296,10 +1844,32 @@ export async function themeEditShow(theme, options = {}) {
1296
1844
  theme,
1297
1845
  like: data.like ?? null,
1298
1846
  mode: data.mode,
1299
- settings: data.settings.map(s => {
1300
- const masked = maskedSettings(data).get(s);
1301
- return {...s, parts: partsOf(ctx, s), ...(masked ? {masked} : {})};
1302
- }),
1847
+ settings: await (async () => {
1848
+ const looksBase = await baseResolved(ctx.project, data.like).catch(
1849
+ () => null,
1850
+ );
1851
+ return data.settings.map(s => {
1852
+ let masked = maskedSettings(data, ctx).get(s);
1853
+ // A look dial (buttons, surfaces) under an exact property on a
1854
+ // part it writes: named, as corners under border-radius is.
1855
+ if (!masked && looksBase && s.source === 'dial' && !s.on) {
1856
+ const writes = dialWrites(ctx, data, s, looksBase);
1857
+ const exact = writes.size
1858
+ ? data.settings.find(
1859
+ x =>
1860
+ x.source === 'property' &&
1861
+ x.on &&
1862
+ !x.when &&
1863
+ !x.state &&
1864
+ partsOf(ctx, x).some(t => writes.has(`${t}\0${x.thing}`)),
1865
+ )
1866
+ : undefined;
1867
+ if (exact)
1868
+ masked = `${describe(exact)} is an exact property and wins over ${s.thing} on ${exact.on}`;
1869
+ }
1870
+ return {...s, parts: partsOf(ctx, s), ...(masked ? {masked} : {})};
1871
+ });
1872
+ })(),
1303
1873
  notes: [
1304
1874
  ...(noReact
1305
1875
  ? [
@@ -1310,19 +1880,30 @@ export async function themeEditShow(theme, options = {}) {
1310
1880
  ? [
1311
1881
  `the theme lock could not be taken, so nothing was written: this is the last build as it is${stale ? ` (it does not match the settings: ${stale})` : ''}, and the pages were not made again`,
1312
1882
  ]
1313
- : stale
1883
+ : stale && !brokenSource
1314
1884
  ? [
1315
- `the build did not match ${theme}.settings.json (${stale}), so it was built again from the settings`,
1885
+ `the build was not current (${stale}), so it was built again from the settings`,
1316
1886
  ]
1317
- : []),
1887
+ : stale
1888
+ ? [
1889
+ `the build is not current (${stale}), and it was not built again: the theme source cannot carry the settings`,
1890
+ ]
1891
+ : []),
1318
1892
  ...(unreadable ? [unreadable] : []),
1319
1893
  ...(brokenSource
1320
1894
  ? [
1321
- `${brokenSource}, so settings cannot take effect; put back the import, extends and name lines in ${theme}.theme.ts`,
1895
+ `${brokenSource}, so settings cannot take effect; put back the import, extends and name lines in ${theme}.theme.ts${/no longer names the theme/.test(brokenSource) ? ` (a copy of another theme's source still names that theme: change its name to '${theme}')` : ''}`,
1322
1896
  ]
1323
1897
  : []),
1324
1898
  ...checked.filter(x => x.startsWith('not checked')),
1325
1899
  ...fontNotes(ctx, data),
1900
+ ...ownSourceMaskNotes(
1901
+ ctx,
1902
+ cwd,
1903
+ theme,
1904
+ data,
1905
+ await baseResolved(ctx.project, data.like),
1906
+ ),
1326
1907
  ],
1327
1908
  // A size, number or font is the same in both modes: one value.
1328
1909
  resolved: Object.fromEntries(
@@ -1339,7 +1920,7 @@ export async function themeEditShow(theme, options = {}) {
1339
1920
  res,
1340
1921
  modes[0],
1341
1922
  ),
1342
- ...colorsReport(pal, data),
1923
+ ...colorsReport(pal, data, res, theme),
1343
1924
  problems,
1344
1925
  preview,
1345
1926
  previewStale,
@@ -1353,6 +1934,39 @@ export async function themeEditShow(theme, options = {}) {
1353
1934
  };
1354
1935
  }
1355
1936
 
1937
+ /**
1938
+ * The part properties a dial writes, read from what the build writes with
1939
+ * it and without it (so a dial's outputs are never listed by hand), as
1940
+ * `target\0css-property` keys.
1941
+ * @param {import('./_settings.mjs').Ctx} ctx
1942
+ * @param {import('./_settings.mjs').ThemeData} data
1943
+ * @param {import('./_settings.mjs').Setting} dial
1944
+ * @param {{light: Record<string, string>, dark: Record<string, string>}} base
1945
+ * @returns {Set<string>}
1946
+ */
1947
+ function dialWrites(ctx, data, dial, base) {
1948
+ /** @type {Set<string>} */
1949
+ const out = new Set();
1950
+ const comps = (/** @type {import('./_settings.mjs').Setting[]} */ settings) =>
1951
+ /** @type {Record<string, Record<string, Record<string, unknown>>>} */ (
1952
+ compileTheme(ctx, {...data, settings}, base).components ?? {}
1953
+ );
1954
+ let plain;
1955
+ let withDial;
1956
+ try {
1957
+ plain = comps([]);
1958
+ withDial = comps([dial]);
1959
+ } catch {
1960
+ return out;
1961
+ }
1962
+ for (const [target, keys] of Object.entries(withDial))
1963
+ for (const [key, block] of Object.entries(keys ?? {}))
1964
+ for (const [prop, value] of Object.entries(block ?? {}))
1965
+ if (typeof value === 'string' && plain[target]?.[key]?.[prop] !== value)
1966
+ out.add(`${target}\0${kebab(prop)}`);
1967
+ return out;
1968
+ }
1969
+
1356
1970
  /**
1357
1971
  * What applies once `removed` is gone: a whole-theme setting of the same
1358
1972
  * thing for a part setting, a dial that still writes the token, or the
@@ -1387,21 +2001,35 @@ function nowApplies(ctx, data, removed, base) {
1387
2001
  // exact property on the part that this dial would have competed with.
1388
2002
  if (removed.on) {
1389
2003
  const fam = familyOf(removed.on);
1390
- const reaches = [...data.settings]
1391
- .reverse()
1392
- .find(
1393
- x =>
1394
- x.thing === removed.thing &&
1395
- x !== removed &&
1396
- (!x.mode || x.mode === removed.mode) &&
1397
- ((x.on === removed.on && !x.when && !x.state) ||
1398
- (fam && x.on === fam && !x.when && !x.state)),
1399
- );
2004
+ // The part's or its group's setting for the same variant and state
2005
+ // first (a group's hover after the part's hover goes), then a plain one.
2006
+ /** @param {(x: import('./_settings.mjs').Setting) => boolean} scoped */
2007
+ const find = scoped =>
2008
+ [...data.settings]
2009
+ .reverse()
2010
+ .find(
2011
+ x =>
2012
+ x.thing === removed.thing &&
2013
+ x !== removed &&
2014
+ (!x.mode || x.mode === removed.mode) &&
2015
+ (x.on === removed.on || (fam != null && x.on === fam)) &&
2016
+ scoped(x),
2017
+ );
2018
+ const reaches =
2019
+ (removed.when || removed.state
2020
+ ? find(
2021
+ x =>
2022
+ (x.when ?? '') === (removed.when ?? '') &&
2023
+ (x.state ?? '') === (removed.state ?? ''),
2024
+ )
2025
+ : undefined) ?? find(x => !x.when && !x.state);
1400
2026
  if (reaches) return describe(reaches);
1401
- const DIAL_PROPERTY = /** @type {Record<string, RegExp>} */ ({
1402
- corners: /radius$/,
1403
- spacing: /^(padding|gap)(-|$)/,
1404
- });
2027
+ const DIAL_PROPERTY = wordTable(
2028
+ /** @type {Record<string, RegExp>} */ ({
2029
+ corners: /radius$/,
2030
+ spacing: /^(padding|gap)(-|$)/,
2031
+ }),
2032
+ );
1405
2033
  const exact =
1406
2034
  removed.source === 'dial' && DIAL_PROPERTY[removed.thing]
1407
2035
  ? data.settings.find(
@@ -1412,8 +2040,25 @@ function nowApplies(ctx, data, removed, base) {
1412
2040
  )
1413
2041
  : null;
1414
2042
  if (exact) return describe(exact);
1415
- // A removed exact property leaves the dial that writes it: on the part,
1416
- // its group, or the whole theme.
2043
+ // A removed exact property leaves the dial whose build writes it there
2044
+ // (buttons, surfaces: read from the build), on the part, its group, or
2045
+ // the whole theme.
2046
+ if (removed.source === 'property') {
2047
+ const targets = partsOf(ctx, removed);
2048
+ const writer = [...data.settings].reverse().find(
2049
+ x =>
2050
+ x.source === 'dial' &&
2051
+ x !== removed &&
2052
+ (!x.on || x.on === removed.on || (fam != null && x.on === fam)) &&
2053
+ (x.when ?? '') === (removed.when ?? '') &&
2054
+ (x.state ?? '') === (removed.state ?? '') &&
2055
+ [...dialWrites(ctx, data, x, base)].some(k => {
2056
+ const [t, prop] = k.split('\0');
2057
+ return targets.includes(t) && prop === removed.thing;
2058
+ }),
2059
+ );
2060
+ if (writer) return describe(writer);
2061
+ }
1417
2062
  if (removed.source === 'property') {
1418
2063
  const dial = Object.entries(DIAL_PROPERTY).find(([, re]) =>
1419
2064
  re.test(removed.thing),
@@ -1469,6 +2114,72 @@ function otherModeNotes(data) {
1469
2114
  ];
1470
2115
  }
1471
2116
 
2117
+ /**
2118
+ * The tokens a whole-theme dial setting writes: those that differ between
2119
+ * the theme's dials with it and without it (a font role's family, and every
2120
+ * text size when the scale moves).
2121
+ * @param {import('./_settings.mjs').Ctx} ctx
2122
+ * @param {import('./_settings.mjs').ThemeData} data
2123
+ * @param {import('./_settings.mjs').Setting} s
2124
+ * @param {any} base
2125
+ * @returns {Set<string>}
2126
+ */
2127
+ function dialTouched(ctx, data, s, base) {
2128
+ /** @param {import('./_settings.mjs').Setting[]} list */
2129
+ const dialsOnly = list => ({
2130
+ ...data,
2131
+ settings: list.filter(x => x.source === 'dial'),
2132
+ });
2133
+ const withDial = compileTheme(ctx, dialsOnly(data.settings), base);
2134
+ const without = compileTheme(
2135
+ ctx,
2136
+ dialsOnly(data.settings.filter(x => x !== s)),
2137
+ base,
2138
+ );
2139
+ const differs = (/** @type {unknown} */ a, /** @type {unknown} */ b) =>
2140
+ JSON.stringify(a) !== JSON.stringify(b);
2141
+ const touched = new Set(
2142
+ [
2143
+ ...Object.keys(withDial.tokens ?? {}),
2144
+ ...Object.keys(without.tokens ?? {}),
2145
+ ].filter(k => differs(withDial.tokens?.[k], without.tokens?.[k])),
2146
+ );
2147
+ for (const r of FONT_ROLES)
2148
+ if (differs(withDial.typography?.[r], without.typography?.[r]))
2149
+ touched.add(`--font-family-${r}`);
2150
+ if (differs(withDial.typography?.scale, without.typography?.scale))
2151
+ for (const k of Object.keys(ctx.project.core.tokenDefaults ?? {}))
2152
+ if (/^--font-size-/.test(k)) touched.add(k);
2153
+ return touched;
2154
+ }
2155
+
2156
+ /**
2157
+ * Notes for the tokens the theme's own source sets that a whole-theme dial
2158
+ * also writes: the source wins, so the dial does not change them.
2159
+ * @param {import('./_settings.mjs').Ctx} ctx
2160
+ * @param {string} cwd
2161
+ * @param {string} slug
2162
+ * @param {import('./_settings.mjs').ThemeData} data
2163
+ * @param {any} base
2164
+ * @returns {string[]}
2165
+ */
2166
+ function ownSourceMaskNotes(ctx, cwd, slug, data, base) {
2167
+ const own = ownSourceTokens(cwd, slug);
2168
+ if (!own.length) return [];
2169
+ /** @type {string[]} */
2170
+ const notes = [];
2171
+ for (const s of data.settings) {
2172
+ if (s.source !== 'dial' || s.on || s.when || s.state) continue;
2173
+ const touched = dialTouched(ctx, data, s, base);
2174
+ const wins = own.filter(k => touched.has(k));
2175
+ if (wins.length)
2176
+ notes.push(
2177
+ `${slug}.theme.ts sets ${wins.slice(0, 4).join(', ')}${wins.length > 4 ? ` and ${wins.length - 4} more` : ''} itself, and your own source wins over the settings, so ${s.thing} = ${s.value} does not change ${wins.length > 1 ? 'them' : 'it'}; take ${wins.length > 1 ? 'them' : 'it'} out of ${slug}.theme.ts to let ${s.thing} set ${wins.length > 1 ? 'them' : 'it'}`,
2178
+ );
2179
+ }
2180
+ return notes;
2181
+ }
2182
+
1472
2183
  /**
1473
2184
  * Each corners or spacing dial set on a part or group, with what its parts
1474
2185
  * get, beside the whole-theme value: `corners large on containers ->
@@ -1481,7 +2192,7 @@ function otherModeNotes(data) {
1481
2192
  * @returns {string[]}
1482
2193
  */
1483
2194
  function partValues(ctx, data, res, mode) {
1484
- const masked = maskedSettings(data);
2195
+ const masked = maskedSettings(data, ctx);
1485
2196
  return data.settings
1486
2197
  .filter(
1487
2198
  s =>
@@ -1554,9 +2265,13 @@ function partValues(ctx, data, res, mode) {
1554
2265
  * says so), and the contrast moves behind the shade choices.
1555
2266
  * @param {import('./_palette.mjs').PaletteMapping | null} pal
1556
2267
  * @param {import('./_settings.mjs').ThemeData} data
2268
+ * @param {Record<'light' | 'dark', Record<string, string>>} [built] the
2269
+ * built theme's resolved values: where one differs from the generated
2270
+ * shade with no exact setting, the theme's own source changed it
2271
+ * @param {string} [slug]
1557
2272
  * @returns {{vibrancy: number | null, colors: import('./theme-edit.type.mjs').ThemeEditColor[], colorNotes: string[]}}
1558
2273
  */
1559
- function colorsReport(pal, data) {
2274
+ function colorsReport(pal, data, built, slug = '') {
1560
2275
  if (!pal) return {vibrancy: null, colors: [], colorNotes: []};
1561
2276
  /** What the user set for each token exactly, in each mode. */
1562
2277
  const exactBy =
@@ -1566,6 +2281,19 @@ function colorsReport(pal, data) {
1566
2281
  for (const m of s.mode ? [s.mode] : ['light', 'dark'])
1567
2282
  (exactBy[s.thing] ??= {})[/** @type {'light' | 'dark'} */ (m)] =
1568
2283
  s.value;
2284
+ /** Tokens the theme's own source sets to another value than generated. */
2285
+ const ownBy =
2286
+ /** @type {Record<string, {light?: string, dark?: string}>} */ ({});
2287
+ for (const [k, v] of Object.entries(pal.tokens))
2288
+ for (const m of /** @type {const} */ (['light', 'dark'])) {
2289
+ const now = built?.[m]?.[k];
2290
+ if (
2291
+ now &&
2292
+ !exactBy[k]?.[m] &&
2293
+ now.trim().toLowerCase() !== String(v[m].color).trim().toLowerCase()
2294
+ )
2295
+ (ownBy[k] ??= {})[m] = now;
2296
+ }
1569
2297
  /** @param {import('./_palette.mjs').StopRef} r */
1570
2298
  const shade = r =>
1571
2299
  r.family === 'black' || r.family === 'white'
@@ -1587,12 +2315,14 @@ function colorsReport(pal, data) {
1587
2315
  k,
1588
2316
  // Each mode says what it shows: the exact setting where one is
1589
2317
  // made for it, else the generated shade.
1590
- exactBy[k]
2318
+ exactBy[k] || ownBy[k]
1591
2319
  ? modes
1592
2320
  .map(m =>
1593
- exactBy[k][m] != null
2321
+ exactBy[k]?.[m] != null
1594
2322
  ? `${m} ${exactBy[k][m]} (your exact setting wins over the generated ${shade(v[m])})`
1595
- : `${m} ${shade(v[m])}`,
2323
+ : ownBy[k]?.[m] != null
2324
+ ? `${m} ${ownBy[k][m]} (your change in ${slug}.theme.ts wins over the generated ${shade(v[m])})`
2325
+ : `${m} ${shade(v[m])}`,
1596
2326
  )
1597
2327
  .join(', ')
1598
2328
  : shades(v),
@@ -1600,9 +2330,22 @@ function colorsReport(pal, data) {
1600
2330
  ),
1601
2331
  })),
1602
2332
  colorNotes: [
1603
- ...pal.notes,
2333
+ // A note about a token the theme's own source changed is dropped:
2334
+ // what it says no longer holds.
2335
+ ...pal.notes.filter(
2336
+ n =>
2337
+ !Object.keys(ownBy).some(k =>
2338
+ new RegExp(`${k.replace(/[-]/g, '\\-')}(?![\\w-])`).test(n),
2339
+ ),
2340
+ ),
1604
2341
  ...pal.contrast
1605
2342
  .filter(c => modes.includes(c.mode))
2343
+ // A pairing the theme's own source changed no longer holds.
2344
+ .filter(
2345
+ c =>
2346
+ !ownBy[c.token]?.[/** @type {'light' | 'dark'} */ (c.mode)] &&
2347
+ !ownBy[c.against]?.[/** @type {'light' | 'dark'} */ (c.mode)],
2348
+ )
1606
2349
  .filter(c => c.note || !c.pass || c.stop !== c.preferred)
1607
2350
  .map(c =>
1608
2351
  c.note
@@ -1611,7 +2354,12 @@ function colorsReport(pal, data) {
1611
2354
  ? `${c.token} ${c.mode}: shade ${c.stop}, not ${c.preferred}, so it reads at ${c.ratio}:1 on ${c.against}`
1612
2355
  : `${c.token} ${c.mode}: only ${c.ratio}:1 on ${c.against} at shade ${c.stop} (needs ${c.needs}:1)`,
1613
2356
  ),
1614
- ],
2357
+ ].filter(
2358
+ n =>
2359
+ !Object.keys(ownBy).some(k =>
2360
+ new RegExp(`${k.replace(/[-]/g, '\\-')}(?![\\w-])`).test(n),
2361
+ ),
2362
+ ),
1615
2363
  };
1616
2364
  }
1617
2365
 
@@ -1640,7 +2388,16 @@ export async function themeEditUndo(theme, options = {}) {
1640
2388
  if (thing === 'base' || thing === 'mode') {
1641
2389
  requireProject(cwd);
1642
2390
  const now = loadTheme(cwd, theme, thing);
1643
- const [first] = readHistory(themeFiles(cwd, theme).history).steps;
2391
+ const historyFile = themeFiles(cwd, theme).history;
2392
+ const {steps, dropped} = readHistory(historyFile);
2393
+ const [first] = steps;
2394
+ // `new` writes no history: with none, no change is saved (a new theme,
2395
+ // or a history deleted). An empty one is every step undone, back to how
2396
+ // the theme was made. A full one may have lost its oldest steps.
2397
+ const noHistory = !fs.existsSync(historyFile);
2398
+ const reachesStart =
2399
+ (steps.length > 0 && steps.length < HISTORY_STEPS) ||
2400
+ (!noHistory && steps.length === 0 && dropped === 0);
1644
2401
  /** @type {any} */
1645
2402
  let made = now;
1646
2403
  try {
@@ -1650,10 +2407,24 @@ export async function themeEditUndo(theme, options = {}) {
1650
2407
  }
1651
2408
  const of = (/** @type {any} */ d) =>
1652
2409
  thing === 'base' ? (d?.like ?? 'none') : (d?.mode ?? 'both');
2410
+ // A step in between that had another value: changed and changed back.
2411
+ const changedBack = steps.some(step => {
2412
+ try {
2413
+ return of(JSON.parse(step.replace(/^\uFEFF/, ''))) !== of(now);
2414
+ } catch {
2415
+ return false;
2416
+ }
2417
+ });
1653
2418
  if (of(made) === of(now))
1654
2419
  refuse(
1655
2420
  E.ERR_THEME_NOT_SET,
1656
- `${thing} was never changed: it is ${of(now)}, as ${theme} was made.`,
2421
+ reachesStart && changedBack
2422
+ ? `${thing} is back at ${of(now)}, the ${thing} ${theme} was made with (it was changed and changed back), so there is nothing to undo for it.`
2423
+ : reachesStart
2424
+ ? `${thing} was never changed: it is ${of(now)}, as ${theme} was made.`
2425
+ : noHistory
2426
+ ? `${thing} is ${of(now)}, and ${theme} has no saved change (it has had none since it was made, or its history was deleted), so there is no earlier ${thing} to go back to.`
2427
+ : `${thing} is ${of(now)}, and ${theme}'s history does not reach back to how it was made, so there is no earlier ${thing} to go back to. Set the ${thing} you want with \`${P} set ${theme} ${thing} …\` instead.`,
1657
2428
  {run: [`${P} show ${theme}`]},
1658
2429
  );
1659
2430
  return change('set', theme, thing, of(made), options);
@@ -1695,6 +2466,9 @@ export async function themeEditUndo(theme, options = {}) {
1695
2466
  // entry replaces it without the current file being read.
1696
2467
  /** @type {import('./_settings.mjs').ThemeData | null} */
1697
2468
  let current = null;
2469
+ // A file in the theme that is a folder or cannot be read is named first;
2470
+ // the damaged-settings path below never sees it.
2471
+ if (slugOk(theme)) refuseUnreadableFiles(cwd, theme);
1698
2472
  try {
1699
2473
  current = loadTheme(cwd, theme);
1700
2474
  } catch (e) {
@@ -1707,7 +2481,7 @@ export async function themeEditUndo(theme, options = {}) {
1707
2481
  E.ERR_THEME_INVALID,
1708
2482
  `${theme}.history.json is damaged, so there is no step to go back to.`,
1709
2483
  {
1710
- fix: `delete ${shown(cwd, f.history)}: the next change starts a new history, and your settings stay as they are`,
2484
+ fix: `move ${shown(cwd, f.history)} out of the theme folder (it is kept as it is): the next change starts a new history, and your settings stay as they are`,
1711
2485
  run: [`${P} show ${theme}`],
1712
2486
  },
1713
2487
  );
@@ -1783,13 +2557,23 @@ export async function themeEditUndo(theme, options = {}) {
1783
2557
  E.ERR_THEME_INVALID,
1784
2558
  `The settings before the last change, in ${theme}.history.json, are damaged: ${still}.`,
1785
2559
  {
1786
- fix: `delete ${shown(cwd, f.history)}: the next change starts a new history, and your settings stay as they are`,
2560
+ fix: `move ${shown(cwd, f.history)} out of the theme folder (it is kept as it is): the next change starts a new history, and your settings stay as they are`,
1787
2561
  run: [`${P} show ${theme}`],
1788
2562
  },
1789
2563
  );
1790
2564
  prev = repaired.data;
1791
2565
  leftOut = repaired.dropped;
1792
2566
  }
2567
+ // The checks that need this Core too (a token's type, a part, a state,
2568
+ // a name that is no token or property): what they refuse is left out of
2569
+ // the step, with the same note, so the build stays valid.
2570
+ {
2571
+ const bad = new Set(storedProblems(ctx, theme, prev).map(p => p.setting));
2572
+ if (bad.size) {
2573
+ leftOut = [...leftOut, ...prev.settings.filter(s => bad.has(s))];
2574
+ prev = {...prev, settings: prev.settings.filter(s => !bad.has(s))};
2575
+ }
2576
+ }
1793
2577
  // The popped history is written with the change, inside its rollback.
1794
2578
  const committed = await commitTheme(ctx, theme, prev, {
1795
2579
  history: false,