@astryxdesign/cli 0.7.15 → 0.7.16-canary.g54dd64e

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 (123) 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/pack-check.mjs +13 -7
  8. package/api/integration/validate-integration.mjs +1 -1
  9. package/api/theme/_adapter.d.mts +5 -2
  10. package/api/theme/_adapter.mjs +43 -12
  11. package/api/theme/build/build.d.mts +64 -27
  12. package/api/theme/build/build.mjs +341 -69
  13. package/api/theme/eject/eject.mjs +22 -1
  14. package/api/theme/template/template.d.mts +19 -0
  15. package/api/theme/template/template.mjs +102 -25
  16. package/api/theme/theme.type.d.mts +5 -1
  17. package/api/theme/theme.type.mjs +2 -1
  18. package/api/theme/themeBuild.doc.mjs +3 -3
  19. package/api/theme/themeEject.doc.mjs +1 -1
  20. package/api/theme/themeTemplate.doc.mjs +9 -3
  21. package/api/theme-edit/_adapter.d.mts +33 -0
  22. package/api/theme-edit/_adapter.mjs +208 -31
  23. package/api/theme-edit/_check.d.mts +38 -0
  24. package/api/theme-edit/_check.mjs +1326 -211
  25. package/api/theme-edit/_color.d.mts +2 -8
  26. package/api/theme-edit/_color.mjs +292 -219
  27. package/api/theme-edit/_compiler.d.mts +1 -0
  28. package/api/theme-edit/_compiler.mjs +20 -1
  29. package/api/theme-edit/_context.d.mts +29 -0
  30. package/api/theme-edit/_context.mjs +329 -30
  31. package/api/theme-edit/_css.d.mts +60 -1
  32. package/api/theme-edit/_css.mjs +404 -28
  33. package/api/theme-edit/_edit.d.mts +9 -0
  34. package/api/theme-edit/_edit.mjs +1025 -126
  35. package/api/theme-edit/_how-commands.d.mts +11 -26
  36. package/api/theme-edit/_how-commands.mjs +30 -2
  37. package/api/theme-edit/_how-question.d.mts +7 -0
  38. package/api/theme-edit/_how-question.mjs +1304 -176
  39. package/api/theme-edit/_how.mjs +144 -30
  40. package/api/theme-edit/_overview.mjs +2 -0
  41. package/api/theme-edit/_palette.d.mts +11 -0
  42. package/api/theme-edit/_palette.mjs +194 -65
  43. package/api/theme-edit/_parts.d.mts +16 -0
  44. package/api/theme-edit/_parts.mjs +59 -7
  45. package/api/theme-edit/_png.mjs +19 -14
  46. package/api/theme-edit/_preview-app.d.mts +3 -0
  47. package/api/theme-edit/_preview-app.mjs +843 -45
  48. package/api/theme-edit/_preview.d.mts +16 -3
  49. package/api/theme-edit/_preview.mjs +310 -29
  50. package/api/theme-edit/_project.d.mts +11 -0
  51. package/api/theme-edit/_project.mjs +46 -12
  52. package/api/theme-edit/_settings.d.mts +178 -5
  53. package/api/theme-edit/_settings.mjs +2035 -86
  54. package/api/theme-edit/_tables.d.mts +24 -0
  55. package/api/theme-edit/_tables.mjs +211 -149
  56. package/api/theme-edit/_vet.d.mts +42 -0
  57. package/api/theme-edit/_vet.mjs +144 -0
  58. package/api/theme-edit/theme-edit.type.d.mts +2 -1
  59. package/api/theme-edit/theme-edit.type.mjs +1 -1
  60. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  61. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  62. package/api/upgrade/registry/registry.mjs +6 -1
  63. package/assets/docs/tree/single-component.doc.mjs +11 -2
  64. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  65. package/assets/docs.generated.json +2 -2
  66. package/assets/preview-app/next.config.mjs +7 -1
  67. package/assets/preview-app/package.json +1 -0
  68. package/assets/preview-app/src/app/globals.css +1 -0
  69. package/assets/self-audit.generated.json +1 -1
  70. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  71. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  72. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  73. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  74. package/assets/templates/components.generated.json +1 -1
  75. package/assets/templates/pages/dashboard/page.tsx +1 -1
  76. package/authoring/doctypes/_schema.d.mts +52 -5
  77. package/authoring/doctypes/_schema.mjs +62 -7
  78. package/authoring/doctypes/base/type.ts +10 -0
  79. package/authoring/doctypes/component/component.doc.mjs +1 -1
  80. package/authoring/doctypes/function/function.doc.mjs +6 -0
  81. package/authoring/doctypes/function/type.ts +3 -0
  82. package/authoring/doctypes/legacy.mjs +5 -1
  83. package/authoring/index.d.ts +1 -0
  84. package/clients/cli/build-id.generated.json +1 -1
  85. package/clients/cli/commands/doctor.doc.mjs +2 -2
  86. package/clients/cli/commands/experimental/theme.mjs +190 -37
  87. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  88. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +1 -1
  89. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +2 -2
  90. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  91. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  92. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  93. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  94. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  95. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  96. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  97. package/clients/cli/commands/theme.mjs +168 -45
  98. package/clients/cli/formatters/index.mjs +7 -4
  99. package/clients/cli/lib/cli-error.mjs +9 -3
  100. package/clients/cli/lib/component-format.mjs +27 -9
  101. package/clients/cli/lib/json-shim.mjs +40 -2
  102. package/clients/cli/manifest.generated.json +1 -1
  103. package/clients/cli/run.mjs +49 -0
  104. package/foundation/config/project.mjs +50 -14
  105. package/foundation/discovery/theme-discovery.d.mts +5 -1
  106. package/foundation/discovery/theme-discovery.mjs +24 -3
  107. package/foundation/fs/gather-cache.d.mts +9 -2
  108. package/foundation/fs/gather-cache.mjs +79 -15
  109. package/foundation/fs/paths.d.mts +31 -0
  110. package/foundation/fs/paths.mjs +43 -10
  111. package/foundation/render/host-exit.d.mts +8 -0
  112. package/foundation/render/host-exit.mjs +11 -0
  113. package/foundation/render/page-host.mjs +56 -10
  114. package/foundation/render/page-worker.mjs +14 -0
  115. package/foundation/render/render-page.mjs +37 -2
  116. package/foundation/response/error-codes.d.mts +2 -1
  117. package/foundation/response/error-codes.d.ts +1 -0
  118. package/foundation/response/error-codes.doc.mjs +5 -0
  119. package/foundation/response/error-codes.mjs +3 -0
  120. package/foundation/response/json.d.mts +15 -0
  121. package/foundation/response/json.mjs +52 -1
  122. package/foundation/response/response-types.doc.mjs +1 -1
  123. 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,12 @@ import {
60
70
  slugFor,
61
71
  themeSource,
62
72
  themeSourceProblem,
73
+ refuseThemeParse,
74
+ ownSourceTokens,
75
+ ownSourceTokenValues,
76
+ ownPartTokens,
77
+ freeThemeName,
78
+ usableNewName,
63
79
  } from './_settings.mjs';
64
80
  import {checkSetting, exampleOf, storedProblems} from './_check.mjs';
65
81
  import {MODAL} from './_compiler.mjs';
@@ -76,9 +92,10 @@ import {
76
92
  } from './_palette.mjs';
77
93
  import {renderPreview, renderSheet} from './_preview.mjs';
78
94
  import {refreshPreviewRoute} from './_preview-app.mjs';
79
- import {baseResolved, installLine} from './_project.mjs';
95
+ import {baseInstalled, baseResolved, installLine} from './_project.mjs';
80
96
  import {reactMissing} from './_parts.mjs';
81
97
  import {
98
+ renderCause,
82
99
  requireProject,
83
100
  context,
84
101
  pictures,
@@ -86,9 +103,13 @@ import {
86
103
  styledChanges,
87
104
  previewAfter,
88
105
  checkSection,
106
+ stampSheet,
89
107
  } from './_context.mjs';
90
108
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
91
- import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
109
+ import {
110
+ getCliInvocation,
111
+ quoteCommandArgument,
112
+ } from '../../foundation/env/package-manager.mjs';
92
113
 
93
114
  const E = ERROR_CODES;
94
115
 
@@ -177,6 +198,40 @@ function readableJson(file) {
177
198
  }
178
199
  }
179
200
 
201
+ /**
202
+ * A physical padding side as its logical side (left-to-right), so a later
203
+ * `padding-inline` replaces an earlier `padding-left` as it does
204
+ * `padding-inline-start`.
205
+ * @param {string} prop
206
+ */
207
+ const logicalSide = prop =>
208
+ /** @type {Record<string, string>} */ ({
209
+ 'padding-left': 'padding-inline-start',
210
+ 'padding-right': 'padding-inline-end',
211
+ 'padding-top': 'padding-block-start',
212
+ 'padding-bottom': 'padding-block-end',
213
+ })[prop] ?? prop;
214
+
215
+ /**
216
+ * Put back every recorded file: its bytes, or removed when it was not
217
+ * there; a palette file the build made new in tokens/ goes too.
218
+ * @param {Map<string, Buffer | null>} kept
219
+ * @param {string} tokensDir
220
+ */
221
+ function putBack(kept, tokensDir) {
222
+ for (const [file, bytes] of kept)
223
+ if (bytes) writeWhole(file, bytes);
224
+ else if (!fs.existsSync(file) || fs.lstatSync(file).isFile())
225
+ fs.rmSync(file, {force: true});
226
+ if (kept.size && fs.existsSync(tokensDir))
227
+ for (const n of fs.readdirSync(tokensDir)) {
228
+ const file = path.join(tokensDir, n);
229
+ // Only a file the build made new; a folder the user put there stays.
230
+ if (!kept.has(file) && fs.lstatSync(file).isFile())
231
+ fs.rmSync(file, {force: true});
232
+ }
233
+ }
234
+
180
235
  /**
181
236
  * Start a theme in themes/<name>/, optionally on a built-in theme, with any
182
237
  * dial settings applied in the same build. Each setting is checked as `set`
@@ -186,19 +241,53 @@ function readableJson(file) {
186
241
  * @param {import('./theme-edit.type.mjs').ThemeEditNewOptions} [options]
187
242
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditNewResponse>}
188
243
  */
244
+
189
245
  export async function themeEditNew(name, options = {}) {
190
246
  const {cwd = process.cwd(), png = false, settings = {}} = options;
191
247
  // `--like none` builds on no base, as `set <theme> base none` does.
192
248
  const like = options.like === 'none' ? undefined : options.like;
193
249
  requireProject(cwd);
250
+ // A corrected `new` keeps every option given, fixing only the bad one.
251
+ // A --like in another case is the built-in theme it names.
252
+ // A --like that names no built-in theme is the nearest one, or none: a
253
+ // corrected command never repeats a --like that is refused below.
254
+ // A guess (the nearest base to a word that names none) is only a base the
255
+ // project has installed: another would be refused in turn. A base named
256
+ // in other letters is the one meant, installed or not (its refusal then
257
+ // offers the install, or the same new on no base).
258
+ const have = LIKE.filter(b => baseInstalled(cwd, b));
259
+ // `@astryxdesign/theme-butter`, `theme-butter`, `Butter`: butter.
260
+ const baseName = (/** @type {unknown} */ v) =>
261
+ String(v)
262
+ .trim()
263
+ .toLowerCase()
264
+ .replace(/^@astryxdesign\/theme-/, '')
265
+ .replace(/^theme-/, '');
266
+ const likeFixed =
267
+ like == null
268
+ ? options.like === 'none'
269
+ ? 'none'
270
+ : undefined
271
+ : LIKE.includes(baseName(like))
272
+ ? baseName(like)
273
+ : (nearest(baseName(like), have)[0] ?? null);
274
+ const again = (
275
+ /** @type {string} */ newName,
276
+ /** @type {string | null | undefined} */ likeValue = likeFixed,
277
+ ) => `${P} new ${newName}${newFlags(likeValue, settings, png)}`;
194
278
  if (!slugOk(name)) {
195
279
  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);
280
+ // Only a name typed in another case is the theme here already.
281
+ const sameName = String(name ?? '').toLowerCase() === fixed;
282
+ const exists = sameName && fs.existsSync(themeFiles(cwd, fixed).settings);
198
283
  refuse(
199
284
  E.ERR_INVALID_ARGUMENT,
200
285
  `"${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}`]},
286
+ {
287
+ run: exists
288
+ ? [`${P} show ${fixed}`]
289
+ : [again(usableNewName(cwd, fixed))],
290
+ },
202
291
  );
203
292
  }
204
293
  // A built-in theme's name would collide with the theme of that name the
@@ -207,7 +296,18 @@ export async function themeEditNew(name, options = {}) {
207
296
  refuse(
208
297
  E.ERR_FILE_EXISTS,
209
298
  `${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}`]},
299
+ {
300
+ run: [
301
+ again(
302
+ fs.existsSync(themeFiles(cwd, `my-${name}`).dir)
303
+ ? freeThemeName(cwd, `my-${name}`)
304
+ : `my-${name}`,
305
+ // Built on the theme named when it is installed, unless another
306
+ // base (or none) was given.
307
+ likeFixed ?? name,
308
+ ),
309
+ ],
310
+ },
211
311
  );
212
312
  const f = themeFiles(cwd, name);
213
313
  // A link or a file where the theme goes is never written through or
@@ -218,22 +318,33 @@ export async function themeEditNew(name, options = {}) {
218
318
  refuse(
219
319
  E.ERR_FILE_EXISTS,
220
320
  `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']},
321
+ // A look that changes nothing: what is in the way.
322
+ {
323
+ run: [
324
+ `ls -la ${quoteCommandArgument(path.relative(cwd, f.root) || 'themes')}`,
325
+ ],
326
+ },
223
327
  );
224
328
  const dirSt = fs.lstatSync(f.dir, {throwIfNoEntry: false});
225
329
  if (dirSt && (dirSt.isSymbolicLink() || !dirSt.isDirectory()))
226
330
  refuse(
227
331
  E.ERR_FILE_EXISTS,
228
332
  `themes/${name} is ${dirSt.isSymbolicLink() ? 'a link' : 'a file'}, so a theme is not made there.`,
229
- {run: [`${P} new ${name}-copy`]},
333
+ {run: [again(freeThemeName(cwd, name))]},
230
334
  );
231
335
  // Settings that are not valid JSON are kept aside, and the theme is
232
336
  // made again beside them.
233
337
  const damaged = fs.existsSync(f.settings) && !readableJson(f.settings);
234
338
  if (fs.existsSync(f.settings) && !damaged)
235
339
  refuse(E.ERR_FILE_EXISTS, `Theme "${name}" already exists.`, {
236
- run: [`${P} show ${name}`, `${P} set ${name} base neutral`],
340
+ // What the command asked for, on the theme that exists or as a new one.
341
+ run: [
342
+ `${P} show ${name}`,
343
+ ...(likeFixed && LIKE.includes(likeFixed)
344
+ ? [`${P} set ${name} base ${likeFixed}`]
345
+ : []),
346
+ again(freeThemeName(cwd, name)),
347
+ ],
237
348
  });
238
349
  // A `new` stopped part way (killed, out of memory) leaves its own marker
239
350
  // beside the files it wrote: only such a folder is cleared, and only
@@ -250,28 +361,45 @@ export async function themeEditNew(name, options = {}) {
250
361
  refuse(
251
362
  E.ERR_FILE_EXISTS,
252
363
  `themes/${name}/ already holds files this command did not make; choose another name.`,
253
- {run: [`${P} new ${name}-copy`]},
364
+ {run: [again(freeThemeName(cwd, name))]},
254
365
  );
255
366
  if (like != null && !LIKE.includes(like))
256
367
  refuse(
257
368
  E.ERR_THEME_BAD_VALUE,
258
369
  `--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
370
  {
260
- didYouMean: nearest(String(like).toLowerCase(), LIKE),
261
- run: [`${P} new ${name}`],
371
+ // The built-in theme it names in another case, or the nearest
372
+ // installed one, else none: the did-you-mean and the run agree.
373
+ didYouMean: likeFixed ? [likeFixed] : [],
374
+ // A built-in base that is not installed: install it, then the same
375
+ // new on it.
376
+ run: [
377
+ ...(likeFixed && likeFixed !== 'none' && !have.includes(likeFixed)
378
+ ? [installLine(cwd, [`@astryxdesign/theme-${likeFixed}`])]
379
+ : []),
380
+ again(name, likeFixed ?? null),
381
+ ],
262
382
  },
263
383
  );
264
384
  const ctx = await context(cwd);
265
385
  /** @type {import('./_settings.mjs').ThemeData} */
266
386
  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
- );
387
+ try {
388
+ /** @type {import('./_settings.mjs').Ctx} */ (ctx).base =
389
+ await baseResolved(ctx.project, data.like);
390
+ } catch (e) {
391
+ // A base that is not installed: install it, or the same new on no base.
392
+ if (e instanceof AstryxError && e.code === E.ERR_UNKNOWN_THEME)
393
+ e.suggestions = [
394
+ ...(e.suggestions ?? []),
395
+ {name: again(name, null), reason: 'build on no theme'},
396
+ ];
397
+ throw e;
398
+ }
271
399
  // Every check comes before the first change to the folder: the settings,
272
400
  // and a source of the user's own kept from before (it must still extend
273
401
  // the settings, or the build fails after the folder was cleared).
274
- applyNewSettings(ctx, name, data, settings);
402
+ applyNewSettings(ctx, name, data, settings, png, likeFixed ?? undefined);
275
403
  if (left?.keep.some(p => path.basename(p) === `${name}.theme.ts`))
276
404
  refuseThemeSource(cwd, name);
277
405
  /** @type {string[]} */
@@ -290,7 +418,7 @@ export async function themeEditNew(name, options = {}) {
290
418
  );
291
419
  if (left?.keep.some(p => path.basename(p) === `${name}.history.json`))
292
420
  leftNotes.push(
293
- `the earlier settings are kept in ${name}.history.json: \`${P} undo ${name}\` steps back to them`,
421
+ `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
422
  );
295
423
  // The marker goes first and comes off last: a `new` stopped between
296
424
  // leaves a folder the next `new` can prove it made. The damaged settings
@@ -417,8 +545,17 @@ export async function themeEditNew(name, options = {}) {
417
545
  * @param {string} slug
418
546
  * @param {import('./_settings.mjs').ThemeData} data
419
547
  * @param {Record<string, string | string[] | undefined>} settings
548
+ * @param {boolean} [png] kept in a corrected `new` a refusal suggests
549
+ * @param {string} [likeFlag] the --like a corrected `new` keeps (`none` too)
420
550
  */
421
- function applyNewSettings(ctx, slug, data, settings) {
551
+ function applyNewSettings(
552
+ ctx,
553
+ slug,
554
+ data,
555
+ settings,
556
+ png = false,
557
+ likeFlag = data.like,
558
+ ) {
422
559
  const given = Object.entries(settings).filter(([, v]) => v != null);
423
560
  for (const [thing] of given)
424
561
  if (!DIALS[thing] || thing === 'base')
@@ -441,13 +578,21 @@ function applyNewSettings(ctx, slug, data, settings) {
441
578
  const given = settings[thing];
442
579
  if (given == null) continue;
443
580
  // `headings` takes a weight and a tracking: one value per axis.
444
- for (const value of Array.isArray(given) ? given : [given]) {
581
+ const values = Array.isArray(given) ? given : [given];
582
+ for (const [index, value] of values.entries()) {
445
583
  /** @type {import('./_settings.mjs').Setting} */
446
584
  let s;
447
585
  try {
448
586
  s = checkSetting(ctx, slug, data, thing, String(value), {}, false);
449
587
  } catch (e) {
450
- throw asNewRefusal(e, slug, settings);
588
+ throw asNewRefusal(
589
+ vetSuggestions(e, ctx, slug, data),
590
+ slug,
591
+ settings,
592
+ likeFlag,
593
+ png,
594
+ {thing, index},
595
+ );
451
596
  }
452
597
  if (thing === 'mode')
453
598
  data.mode = /** @type {'both' | 'light-only' | 'dark-only'} */ (
@@ -460,8 +605,14 @@ function applyNewSettings(ctx, slug, data, settings) {
460
605
  E.ERR_INVALID_ARGUMENT,
461
606
  `--${thing} was given two values for the same thing (${data.settings[same].value}, ${s.value}); give one.`,
462
607
  {
608
+ // Every other option given stays, and the first value on each
609
+ // axis: every later value for an axis already given goes.
463
610
  run: [
464
- `${P} new ${slug} --${thing} ${quoteCommandArgument(s.value)}`,
611
+ `${P} new ${slug}${newFlags(
612
+ likeFlag,
613
+ {...settings, [thing]: firstPerAxis(values)},
614
+ png,
615
+ )}`,
465
616
  ],
466
617
  },
467
618
  );
@@ -471,36 +622,117 @@ function applyNewSettings(ctx, slug, data, settings) {
471
622
  }
472
623
  }
473
624
 
625
+ /**
626
+ * The options of a `new` as flags, in the order given (`new --help`'s order
627
+ * for the command): `--like`, each dial setting, then `--png`.
628
+ * @param {string | null | undefined} like none when null or undefined
629
+ * @param {Record<string, string | string[] | undefined>} settings
630
+ * @param {boolean} [png]
631
+ * @returns {string[]}
632
+ */
633
+ export function newFlagList(like, settings, png = false) {
634
+ return [
635
+ ...(like ? [`--like ${quoteCommandArgument(like)}`] : []),
636
+ ...Object.entries(settings)
637
+ .filter(([, v]) => v != null)
638
+ .flatMap(([k, v]) => (Array.isArray(v) ? v : [v]).map(x => [k, x]))
639
+ .map(([k, v]) => `--${k} ${quoteCommandArgument(String(v))}`),
640
+ ...(png ? ['--png'] : []),
641
+ ];
642
+ }
643
+
644
+ /**
645
+ * The options of a `new` as one flag line, with its leading space.
646
+ * @param {string | null | undefined} like
647
+ * @param {Record<string, string | string[] | undefined>} settings
648
+ * @param {boolean} png
649
+ */
650
+ function newFlags(like, settings, png) {
651
+ const parts = newFlagList(like, settings, png);
652
+ return parts.length ? ` ${parts.join(' ')}` : '';
653
+ }
654
+
474
655
  /**
475
656
  * A refusal from a setting `new` was given, with its suggestions turned
476
657
  * into `new` commands: the theme does not exist yet, so a `set` would fail.
477
658
  * @param {unknown} e
478
659
  * @param {string} slug
479
660
  * @param {Record<string, string | string[] | undefined>} settings
661
+ * @param {string} [like] the --like given, kept in a corrected command
662
+ * @param {boolean} [png] --png, kept in a corrected command
663
+ * @param {{thing: string, index: number} | null} [at] the value refused
480
664
  */
481
- function asNewRefusal(e, slug, settings) {
665
+ function asNewRefusal(e, slug, settings, like, png = false, at = null) {
482
666
  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
667
  const setPrefix = `${P} set ${slug} `;
488
668
  e.suggestions = (e.suggestions ?? []).map(s => {
489
669
  if (s.name === `${P} set --help`) return {...s, name: `${P} new --help`};
490
670
  if (!s.name.startsWith(setPrefix)) return s;
491
671
  const [thing, ...rest] = s.name.slice(setPrefix.length).split(' ');
492
672
  if (thing.startsWith('--') || !DIALS[thing]) return s;
493
- const keep = flags.filter(f => !f.startsWith(`--${thing} `));
673
+ const fixed = unquoteWord(rest.join(' '));
674
+ // Only the refused value changes: a dial given several values
675
+ // (--headings tight --headings BOLD) keeps the others, in order.
676
+ const given = settings[thing];
677
+ const values = Array.isArray(given) ? [...given] : null;
678
+ const next =
679
+ values && at && at.thing === thing
680
+ ? firstPerAxis(values.map((v, i) => (i === at.index ? fixed : v)))
681
+ : fixed;
494
682
  return {
495
683
  ...s,
496
- name: [`${P} new ${slug}`, ...keep, `--${thing} ${rest.join(' ')}`].join(
497
- ' ',
498
- ),
684
+ name: `${P} new ${slug}${newFlags(like, {...settings, [thing]: next}, png)}`,
499
685
  };
500
686
  });
687
+ // A refused value with nothing to put in its place: the same new
688
+ // without it, every other option kept.
689
+ if (at && !e.suggestions.some(x => x.name.startsWith(`${P} new `))) {
690
+ const given = settings[at.thing];
691
+ const rest = Array.isArray(given)
692
+ ? given.filter((_, i) => i !== at.index)
693
+ : undefined;
694
+ e.suggestions.push({
695
+ name: `${P} new ${slug}${newFlags(like, {...settings, [at.thing]: rest?.length ? rest : undefined}, png)}`,
696
+ reason: `without --${at.thing} ${quoteCommandArgument(String(Array.isArray(given) ? given[at.index] : given))}`,
697
+ });
698
+ }
501
699
  return e;
502
700
  }
503
701
 
702
+ /**
703
+ * Headings values with every later value for an axis already given left
704
+ * out (the first weight and the first tracking stay); a word of neither
705
+ * axis stays, for its own refusal.
706
+ * @param {string[]} values
707
+ * @returns {string[]}
708
+ */
709
+ function firstPerAxis(values) {
710
+ const seen = new Set();
711
+ return values.filter(v => {
712
+ const w = String(v).trim().toLowerCase();
713
+ const axis =
714
+ HEADING_WEIGHTS[w] !== undefined
715
+ ? 'weight'
716
+ : HEADING_TRACKING[w] !== undefined
717
+ ? 'tracking'
718
+ : null;
719
+ if (!axis) return true;
720
+ if (seen.has(axis)) return false;
721
+ seen.add(axis);
722
+ return true;
723
+ });
724
+ }
725
+
726
+ /**
727
+ * A word as a suggested command writes it, without the quotes
728
+ * quoteCommandArgument adds.
729
+ * @param {string} word
730
+ */
731
+ function unquoteWord(word) {
732
+ const m = /^'(.*)'$/s.exec(word);
733
+ return m ? m[1].replace(/'\\''/g, "'") : word;
734
+ }
735
+
504
736
  /**
505
737
  * The preview after a change, with the in-app preview route kept in step:
506
738
  * its imports follow the theme, such as the stylesheet of a font package
@@ -571,7 +803,12 @@ function refuseStoredTokens(ctx, slug, data, skip) {
571
803
  // setting is never refused for another.
572
804
  run: [
573
805
  ...bad.slice(0, 5).map(b => `${P} undo ${slug} ${undoArgs(b.setting)}`),
574
- ...(one && !one.scope
806
+ // A value to set only for a token whose stored value has the wrong
807
+ // type; any other thing `set` would refuse, or read as a dial.
808
+ ...(one &&
809
+ !one.scope &&
810
+ one.setting.source === 'token' &&
811
+ ctx.C.isToken(one.setting.thing)
575
812
  ? [
576
813
  `${P} set ${slug} ${one.setting.thing} ${quoteCommandArgument(exampleOf(ctx.C.typeOf(one.setting.thing), one.setting.thing))}`,
577
814
  ]
@@ -611,6 +848,54 @@ function extremeSteps(res) {
611
848
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
612
849
  */
613
850
  async function change(sub, slug, thing, value, options) {
851
+ /** @type {{ctx?: import('./_settings.mjs').Ctx, data?: import('./_settings.mjs').ThemeData}} */
852
+ const seen = {};
853
+ try {
854
+ return await changeOnce(sub, slug, thing, value, options, seen);
855
+ } catch (e) {
856
+ // A theme name one letter off an existing theme: the same command with
857
+ // that name comes first, before making a theme of the typo.
858
+ if (e instanceof AstryxError && e.code === E.ERR_UNKNOWN_THEME) {
859
+ const near = (e.suggestions ?? []).find(x => x.reason === 'did you mean');
860
+ if (near && slugOk(near.name)) {
861
+ const flags = [
862
+ ...(options.on ? ['--on', options.on] : []),
863
+ ...(options.when ? ['--when', options.when] : []),
864
+ ...(options.state ? ['--state', options.state] : []),
865
+ ...(options.mode ? ['--mode', options.mode] : []),
866
+ ...(options.only ? ['--only'] : []),
867
+ ];
868
+ const words = [thing, ...(value == null ? [] : [value]), ...flags]
869
+ .filter(w => w != null && w !== '')
870
+ .map(w =>
871
+ String(w).startsWith('--') ? w : quoteCommandArgument(String(w)),
872
+ );
873
+ e.suggestions = [
874
+ {
875
+ name: `${P} ${sub} ${near.name}${words.length ? ` ${words.join(' ')}` : ''}`,
876
+ reason: `do this instead: ${near.name} is a theme here`,
877
+ },
878
+ ...(e.suggestions ?? []).filter(x => x !== near),
879
+ ];
880
+ }
881
+ throw e;
882
+ }
883
+ // Every `set` the refusal suggests is checked as `set` checks it.
884
+ throw vetSuggestions(e, seen.ctx, slug, seen.data);
885
+ }
886
+ }
887
+
888
+ /**
889
+ * @param {'set' | 'undo'} sub
890
+ * @param {string} slug
891
+ * @param {string} thing
892
+ * @param {string | undefined} value
893
+ * @param {ChangeOptions} options
894
+ * @param {{ctx?: import('./_settings.mjs').Ctx, data?: import('./_settings.mjs').ThemeData}} seen
895
+ * the context and the theme as loaded, for checking a refusal's suggestions
896
+ * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
897
+ */
898
+ async function changeOnce(sub, slug, thing, value, options, seen) {
614
899
  const {cwd = process.cwd(), png = false} = options;
615
900
  requireProject(cwd);
616
901
  // The setting this command changes or removes may be the bad one; any
@@ -664,6 +949,8 @@ async function change(sub, slug, thing, value, options) {
664
949
  );
665
950
  }
666
951
  /** @type {import('./_settings.mjs').Ctx} */ (ctx).base = base;
952
+ seen.ctx = ctx;
953
+ seen.data = structuredClone(data);
667
954
  /** @type {import('./_settings.mjs').Setting} */
668
955
  let s;
669
956
  try {
@@ -675,11 +962,13 @@ async function change(sub, slug, thing, value, options) {
675
962
  sub === 'undo'
676
963
  ? data.settings.find(
677
964
  x =>
678
- x.thing === thing &&
965
+ x.thing.toLowerCase() === String(thing).toLowerCase() &&
679
966
  (x.on ?? null) === (flags.on ?? null) &&
680
967
  (x.when ?? null) === (flags.when ?? null) &&
681
968
  (x.state ?? null) === (flags.state ?? null) &&
682
- (x.mode ?? null) === (flags.mode ?? null),
969
+ (x.mode ?? null) === (flags.mode ?? null) &&
970
+ // --only names a setting made with it; it is never dropped.
971
+ Boolean(x.only) === Boolean(flags.only),
683
972
  )
684
973
  : null;
685
974
  if (!stored) {
@@ -687,13 +976,50 @@ async function change(sub, slug, thing, value, options) {
687
976
  // what it named (or of the dial its refusal names), else the last
688
977
  // step.
689
978
  if (sub === 'undo' && e instanceof AstryxError) {
979
+ // Setting names are matched in any case, and a near name of a
980
+ // setting the theme has counts: `undo t Corners`, `undo t corner`.
981
+ const typed = String(thing).toLowerCase();
982
+ // A token named without its dashes (radius-element) is the token.
983
+ const dashed = typed.startsWith('--') ? typed : `--${typed}`;
690
984
  const named = new Set([
691
- thing,
985
+ typed,
986
+ dashed,
692
987
  ...(e.suggestions ?? [])
693
- .map(x => new RegExp(` set ${slug} (\\S+)`).exec(x.name)?.[1])
988
+ .filter(x => x.reason === 'did you mean')
989
+ .map(x => x.name.toLowerCase()),
990
+ ...(e.suggestions ?? [])
991
+ .map(
992
+ x => new RegExp(` (?:set|undo) ${slug} (\\S+)`).exec(x.name)?.[1],
993
+ )
694
994
  .filter(Boolean),
995
+ ...nearest(
996
+ typed,
997
+ data.settings.map(x => x.thing.toLowerCase()),
998
+ ),
695
999
  ]);
696
- const matches = data.settings.filter(x => named.has(x.thing));
1000
+ const matches = data.settings.filter(x =>
1001
+ named.has(x.thing.toLowerCase()),
1002
+ );
1003
+ // A word that is near a setting name (a typo, another case) is never
1004
+ // answered with a bare step back, which would undo another change;
1005
+ // any other word (`all`) may mean the last step.
1006
+ // A token or a property named (radius-element, padding) is a named
1007
+ // thing too: never answered with a step back.
1008
+ const namesThing =
1009
+ ctx.C.isToken(dashed) ||
1010
+ data.settings.some(
1011
+ x => x.source === 'property' && x.thing.toLowerCase() === typed,
1012
+ ) ||
1013
+ /^[a-z]+(-[a-z]+)+$|^(padding|margin|color|background|border|gap|width|height|opacity)$/.test(
1014
+ typed,
1015
+ );
1016
+ const nearSetting =
1017
+ namesThing ||
1018
+ named.size > (dashed === typed ? 1 : 2) ||
1019
+ nearest(typed, [
1020
+ ...Object.keys(DIALS),
1021
+ ...data.settings.map(x => x.thing.toLowerCase()),
1022
+ ]).length > 0;
697
1023
  const steps = readHistory(themeFiles(cwd, slug).history).steps.length;
698
1024
  throw new AstryxError(
699
1025
  e.message,
@@ -703,7 +1029,7 @@ async function change(sub, slug, thing, value, options) {
703
1029
  reason: 'do this instead',
704
1030
  }))
705
1031
  : [
706
- steps
1032
+ steps && !nearSetting
707
1033
  ? {name: `${P} undo ${slug}`, reason: 'step back one change'}
708
1034
  : {name: `${P} show ${slug}`, reason: 'see what it sets'},
709
1035
  ],
@@ -734,7 +1060,11 @@ async function change(sub, slug, thing, value, options) {
734
1060
  .trim()
735
1061
  .toLowerCase()
736
1062
  .replace(/\s+/g, ' ')
737
- .replace(/^["']|["']$/g, '');
1063
+ // Spacing around commas, slashes and parentheses, and the quote
1064
+ // style, are not part of a value.
1065
+ .replace(/\s*([,()/])\s*/g, '$1')
1066
+ .replace(/'/g, '"')
1067
+ .replace(/^"|"$/g, '');
738
1068
  const half =
739
1069
  s.thing === 'headings' && ['weight', 'tracking'].includes(norm(value));
740
1070
  if (
@@ -819,9 +1149,16 @@ async function change(sub, slug, thing, value, options) {
819
1149
  if (sub === 'undo') {
820
1150
  if (!prev) {
821
1151
  const near = data.settings.filter(x => x.thing === s.thing).map(describe);
1152
+ // headings has two halves: name the one that is set.
1153
+ const otherHalf =
1154
+ s.thing === 'headings'
1155
+ ? data.settings.find(x => x.thing === 'headings' && x.axis !== s.axis)
1156
+ : null;
822
1157
  refuse(
823
1158
  E.ERR_THEME_NOT_SET,
824
- `The theme does not set ${describe({...s, value: '?'}).replace(' = ?', '')}.`,
1159
+ otherHalf
1160
+ ? `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.`
1161
+ : `The theme does not set ${describe({...s, value: '?'}).replace(' = ?', '')}.`,
825
1162
  {
826
1163
  also: near.length
827
1164
  ? [`settings for ${s.thing}: ${near.join('; ')}`]
@@ -837,6 +1174,8 @@ async function change(sub, slug, thing, value, options) {
837
1174
  );
838
1175
  }
839
1176
  data.settings.splice(prevIdx, 1);
1177
+ // A setting listed twice by hand goes in full.
1178
+ data.settings = data.settings.filter(x => keyOf(x) !== k);
840
1179
  // Vibrancy needs a color: undoing the last one takes it along, so the
841
1180
  // theme never holds a state `set` refuses.
842
1181
  if (
@@ -872,6 +1211,13 @@ async function change(sub, slug, thing, value, options) {
872
1211
  if (prev) data.settings.splice(prevIdx, 1);
873
1212
  data.settings.push(s);
874
1213
  }
1214
+ // A setting listed twice by hand keeps only the entry this command left.
1215
+ if (sub === 'set') {
1216
+ const last = data.settings.map(x => keyOf(x)).lastIndexOf(k);
1217
+ data.settings = data.settings.filter(
1218
+ (x, i) => keyOf(x) !== k || i === last,
1219
+ );
1220
+ }
875
1221
  // A setting for both modes replaces the ones made for one mode, which it
876
1222
  // would otherwise sit under.
877
1223
  /** @type {import('./_settings.mjs').Setting[]} */
@@ -889,16 +1235,24 @@ async function change(sub, slug, thing, value, options) {
889
1235
  x =>
890
1236
  x !== s &&
891
1237
  x.source === 'property' &&
892
- x.on === s.on &&
1238
+ // On the same part, or on a member of the group it is set on:
1239
+ // the later setting wins, whichever way Core writes it.
1240
+ (x.on === s.on ||
1241
+ (s.on != null &&
1242
+ (FAMILIES[s.on] ?? []).includes(
1243
+ /** @type {string} */ (x.on),
1244
+ ))) &&
893
1245
  x.when === s.when &&
894
1246
  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
- ),
1247
+ // A longhand the shorthand really sets (MDN's data), never a
1248
+ // property that only shares its name (overflow-wrap).
1249
+ (coversProperty(s.thing, x.thing) ||
1250
+ coversProperty(logicalSide(s.thing), logicalSide(x.thing))),
900
1251
  )
901
1252
  : [];
1253
+ // They go, as the note says: Core writes each side to its own variable,
1254
+ // where a later shorthand would not win over them (undo brings them back).
1255
+ data.settings = data.settings.filter(x => !longhands.includes(x));
902
1256
  // A group setting covers part settings made before it for its members.
903
1257
  const covers =
904
1258
  sub === 'set' && s.source === 'dial' && s.on && FAMILIES[s.on]
@@ -917,38 +1271,32 @@ async function change(sub, slug, thing, value, options) {
917
1271
  const parts = partsOf(ctx, s);
918
1272
  // Exact whole-theme tokens that win over what this dial writes: the dial
919
1273
  // 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
1274
  /** @type {import('./_settings.mjs').Setting[]} */
926
1275
  let exactWins = [];
1276
+ /** Tokens this whole-theme dial changes. */
1277
+ let dialTokens = new Set();
927
1278
  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);
1279
+ const touched = dialTouched(ctx, data, s, base);
948
1280
  exactWins = data.settings.filter(
949
1281
  x => x.source === 'token' && !x.on && !x.when && touched.has(x.thing),
950
1282
  );
1283
+ dialTokens = touched;
951
1284
  }
1285
+ // A role font (font X --on heading) writes --font-family-<role>: an exact
1286
+ // setting of that token wins over it.
1287
+ if (sub === 'set' && s.thing === 'font' && s.on && FONT_ROLES.includes(s.on))
1288
+ exactWins = data.settings.filter(
1289
+ x =>
1290
+ x.source === 'token' &&
1291
+ !x.on &&
1292
+ !x.when &&
1293
+ x.thing === `--font-family-${s.on}`,
1294
+ );
1295
+ // The theme's own source wins over an exact setting, as the exact
1296
+ // setting does over a dial: an exact token the file also sets is named
1297
+ // as the file's below, never as the one that shows after an undo.
1298
+ const ownFirst = new Set(ownSourceTokens(cwd, slug));
1299
+ exactWins = exactWins.filter(x => !ownFirst.has(x.thing));
952
1300
  const kept =
953
1301
  sub === 'set' && s.source === 'dial' && !s.on
954
1302
  ? [
@@ -956,13 +1304,62 @@ async function change(sub, slug, thing, value, options) {
956
1304
  ...exactWins,
957
1305
  ].map(describe)
958
1306
  : [];
1307
+ // The role fonts a whole-theme font sits under.
1308
+ // An exact --font-family-<role> wins over both: that role is named by
1309
+ // the exact note instead.
1310
+ /** @param {string} role */
1311
+ const exactFamily = role =>
1312
+ data.settings.find(
1313
+ x =>
1314
+ x.source === 'token' &&
1315
+ !x.on &&
1316
+ !x.when &&
1317
+ x.thing === `--font-family-${role}`,
1318
+ );
1319
+ const roleOver =
1320
+ sub === 'set' && s.thing === 'font' && !s.on
1321
+ ? data.settings.filter(
1322
+ x =>
1323
+ x.thing === 'font' &&
1324
+ x.on &&
1325
+ ['body', 'heading'].includes(x.on) &&
1326
+ !exactFamily(x.on),
1327
+ )
1328
+ : [];
1329
+ if (sub === 'set' && s.thing === 'font' && !s.on)
1330
+ for (const role of FONT_ROLES) {
1331
+ const exact = exactFamily(role);
1332
+ if (exact && !exactWins.includes(exact)) exactWins.push(exact);
1333
+ }
959
1334
  // 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
- });
1335
+ const DIAL_PROPERTY = wordTable(
1336
+ /** @type {Record<string, RegExp>} */ ({
1337
+ corners: /radius$/,
1338
+ spacing: /^(padding|gap)(-|$)/,
1339
+ }),
1340
+ );
1341
+ // A whole-theme look dial (buttons, surfaces) writes part properties
1342
+ // too: an exact property on one of them wins there, read from the build.
1343
+ const looksOver =
1344
+ sub === 'set' && s.source === 'dial' && !DIAL_PROPERTY[s.thing]
1345
+ ? (() => {
1346
+ const writes = dialWrites(ctx, data, s, base);
1347
+ if (!writes.size) return null;
1348
+ return (
1349
+ data.settings.find(
1350
+ x =>
1351
+ x.source === 'property' &&
1352
+ x.on &&
1353
+ !x.when &&
1354
+ !x.state &&
1355
+ partsOf(ctx, x).some(t => writes.has(`${t}\0${x.thing}`)),
1356
+ ) ?? null
1357
+ );
1358
+ })()
1359
+ : null;
964
1360
  const exactOver =
965
- sub === 'set' && s.source === 'dial' && s.on && DIAL_PROPERTY[s.thing]
1361
+ looksOver ??
1362
+ (sub === 'set' && s.source === 'dial' && s.on && DIAL_PROPERTY[s.thing]
966
1363
  ? (data.settings.find(
967
1364
  x =>
968
1365
  x.source === 'property' &&
@@ -972,13 +1369,38 @@ async function change(sub, slug, thing, value, options) {
972
1369
  (x.when ?? '') === (s.when ?? '') &&
973
1370
  (x.state ?? '') === (s.state ?? ''),
974
1371
  ) ?? null)
975
- : null;
1372
+ : null);
1373
+ // An exact token the theme's own source also sets: the file's value
1374
+ // shows (read from what the build made of it), not the setting.
1375
+ const ownOverToken =
1376
+ sub !== 'set' || s.when || s.state
1377
+ ? null
1378
+ : s.on
1379
+ ? // On a part: a token or property the own source sets on its
1380
+ // plain rule.
1381
+ (s.source === 'token' || s.source === 'property') &&
1382
+ ownPartTokens(cwd, slug, s.on).has(s.thing)
1383
+ ? [s.thing, ownPartTokens(cwd, slug, s.on).get(s.thing) ?? null]
1384
+ : null
1385
+ : s.source === 'token'
1386
+ ? (Object.entries(ownSourceTokenValues(cwd, slug)).find(
1387
+ ([k]) => k === s.thing,
1388
+ ) ??
1389
+ (ownSourceTokens(cwd, slug).includes(s.thing)
1390
+ ? [s.thing, null]
1391
+ : null))
1392
+ : null;
976
1393
  /** @type {string[]} */
977
1394
  const notes = [
978
1395
  ...(covered.length ? [`replaces ${covered.map(describe).join(', ')}`] : []),
1396
+ ...(ownOverToken
1397
+ ? [
1398
+ `${slug}.theme.ts sets ${s.thing}${s.on ? ` on ${s.on}` : ''} itself${ownOverToken[1] != null ? ` (${ownOverToken[1]})` : ''}, and your own source wins over the settings, so this does not show; change it in ${slug}.theme.ts, or take this back with \`${P} undo ${slug} ${undoArgs(s)}\``,
1399
+ ]
1400
+ : []),
979
1401
  ...(exactWins.length
980
1402
  ? [
981
- `keeps your exact ${exactWins.map(describe).join(', ')}: an exact setting wins over a dial, so ${exactWins.length > 1 ? 'those do' : 'that does'} not change`,
1403
+ `keeps your exact ${exactWins.map(describe).join(', ')}: an exact setting wins over a dial, so ${exactWins.length > 1 ? 'those do' : 'that does'} not change; this shows after \`${P} undo ${slug} ${exactWins.map(x => undoArgs(x)).join(`\` and \`${P} undo ${slug} `)}\``,
982
1404
  ]
983
1405
  : []),
984
1406
  ...(covers.length
@@ -986,6 +1408,29 @@ async function change(sub, slug, thing, value, options) {
986
1408
  `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
1409
  ]
988
1410
  : []),
1411
+ // Core writes a part's derived variables (a button's or card's radius
1412
+ // variable, read by what is drawn inside it) from plain declarations
1413
+ // only: in a state they keep the plain value, and the result says so.
1414
+ ...(sub === 'set' && s.state && s.on
1415
+ ? (() => {
1416
+ const prop =
1417
+ s.thing === 'corners' || /radius$/.test(s.thing)
1418
+ ? 'borderRadius'
1419
+ : s.thing === 'padding' || s.thing === 'spacing'
1420
+ ? 'padding'
1421
+ : s.thing.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
1422
+ const vars = parts.flatMap(t =>
1423
+ (ctx.derived?.[t] ?? [])
1424
+ .filter(d => d.property === prop)
1425
+ .flatMap(d => d.vars ?? []),
1426
+ );
1427
+ return vars.length
1428
+ ? [
1429
+ `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`,
1430
+ ]
1431
+ : [];
1432
+ })()
1433
+ : []),
989
1434
  // Phones keep the base theme's reading sizes (a coarse pointer below
990
1435
  // the lg width), so a size change says where it applies.
991
1436
  ...(sub === 'set' &&
@@ -1006,11 +1451,24 @@ async function change(sub, slug, thing, value, options) {
1006
1451
  `${describe(exactOver)} is an exact property and wins over ${s.thing} there, so this shows only after \`${P} undo ${slug} ${undoArgs(exactOver)}\``,
1007
1452
  ]
1008
1453
  : []),
1454
+ // A whole-theme font under fonts set for each role shows only where no
1455
+ // role font is set.
1456
+ ...(roleOver.length
1457
+ ? [
1458
+ `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 ')}`,
1459
+ ]
1460
+ : []),
1009
1461
  // An accepted change that the theme already showed says so.
1010
1462
  ...(sub === 'set' &&
1011
1463
  !exactOver &&
1012
- // With the last build unreadable, nothing was compared.
1013
- !r.notes.some(n => n.includes('could not be read')) &&
1464
+ !roleOver.length &&
1465
+ !ownOverToken &&
1466
+ // With the last build unreadable or missing, nothing was compared.
1467
+ !r.notes.some(
1468
+ n =>
1469
+ n.includes('could not be read') ||
1470
+ n.includes('there was no last build'),
1471
+ ) &&
1014
1472
  !r.unchanged &&
1015
1473
  !r.changed.length &&
1016
1474
  !styled.length &&
@@ -1019,6 +1477,23 @@ async function change(sub, slug, thing, value, options) {
1019
1477
  `this changes nothing you see: the theme already shows ${describe(s)} (it is saved, and stays when the base theme changes)`,
1020
1478
  ]
1021
1479
  : []),
1480
+ // A card's content takes one radius from Core, whatever its corners.
1481
+ ...(sub === 'set' &&
1482
+ s.source === 'property' &&
1483
+ s.thing === 'border-radius' &&
1484
+ s.on &&
1485
+ (ctx.derived?.[s.on] ?? []).some(
1486
+ d => d.property === 'borderRadius' && d.vars?.length,
1487
+ ) &&
1488
+ /\s|\//.test(String(s.value).trim())
1489
+ ? [
1490
+ `each corner of ${s.on} takes its own radius; the content that reaches its edges takes one, ${
1491
+ String(s.value)
1492
+ .trim()
1493
+ .split(/[\s/]+/)[0]
1494
+ }, for every corner (Core gives it a single radius)`,
1495
+ ]
1496
+ : []),
1022
1497
  ...(longhands.length
1023
1498
  ? [
1024
1499
  `${s.thing} comes after ${longhands.map(x => x.thing).join(', ')} on ${s.on}, so it replaces them there`,
@@ -1039,6 +1514,20 @@ async function change(sub, slug, thing, value, options) {
1039
1514
  : null
1040
1515
  : null;
1041
1516
  if (s.note) notes.push(s.note);
1517
+ // A token the theme's own source sets itself wins over what this dial
1518
+ // writes, as an exact setting does.
1519
+ const ownWins = ownSourceTokens(cwd, slug).filter(
1520
+ k =>
1521
+ (dialTokens.has(k) ||
1522
+ // A role font writes --font-family-<role>.
1523
+ (s.thing === 'font' && s.on && k === `--font-family-${s.on}`)) &&
1524
+ !exactWins.some(x => x.thing === k),
1525
+ );
1526
+ const ownSet = new Set(ownSourceTokens(cwd, slug));
1527
+ if (ownWins.length)
1528
+ notes.push(
1529
+ `${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'}`,
1530
+ );
1042
1531
  if (PALETTE_DIALS.includes(s.thing) && sub === 'set')
1043
1532
  notes.push(
1044
1533
  ...paletteNotes(
@@ -1046,7 +1535,31 @@ async function change(sub, slug, thing, value, options) {
1046
1535
  s.thing,
1047
1536
  slug,
1048
1537
  modesOf(data),
1049
- ),
1538
+ )
1539
+ // A shade the mapping would pick for a token the theme's own source
1540
+ // sets never shows: the file's value does (named once above).
1541
+ .filter(n => {
1542
+ const subject = /^(?:in (?:light|dark), )?(--[a-z0-9-]+) /.exec(
1543
+ n,
1544
+ )?.[1];
1545
+ return (
1546
+ !subject ||
1547
+ !ownSet.has(subject) ||
1548
+ / uses your exact setting \(/.test(n)
1549
+ );
1550
+ })
1551
+ .map(n => {
1552
+ // The exact color is the one the theme's own source sets: named so.
1553
+ const token = n.split(' ')[0];
1554
+ return ownSet.has(token) && / uses your exact setting \(/.test(n)
1555
+ ? n
1556
+ .replace(
1557
+ ' uses your exact setting (',
1558
+ ` uses the value ${slug}.theme.ts sets (`,
1559
+ )
1560
+ .replace('an exact setting wins', 'your own source wins')
1561
+ : n;
1562
+ }),
1050
1563
  );
1051
1564
  // An exact color the mapping reads (a fill, a tint, text on a fill)
1052
1565
  // changes what it picks around it: say what, as the dial does.
@@ -1104,8 +1617,13 @@ async function change(sub, slug, thing, value, options) {
1104
1617
  if (s.thing === 'font' && sub === 'set')
1105
1618
  notes.unshift(...fontNotes(ctx, {...data, settings: [s]}));
1106
1619
  if (s.thing === 'type' || s.thing === 'headings')
1107
- for (const [m, why] of maskedSettings(data))
1620
+ for (const [m, why] of maskedSettings(data, ctx))
1108
1621
  notes.push(`${describe(m)}: ${why}`);
1622
+ // An earlier setting this one now covers (through a spread too) is named.
1623
+ else if (sub === 'set')
1624
+ for (const [m, why] of maskedSettings(data, ctx))
1625
+ if (m !== s && why.startsWith(describe(s)))
1626
+ notes.push(`${describe(m)} no longer shows: ${why}`);
1109
1627
  if (s.thing === 'type' && sub === 'set' && TYPE_STYLES[s.value].ratio > 1.2)
1110
1628
  notes.push(
1111
1629
  'text below the base size keeps its standard sizes, so small text stays readable',
@@ -1235,22 +1753,108 @@ export async function themeEditShow(theme, options = {}) {
1235
1753
  ? [installLine(cwd, ['react', 'react-dom'])]
1236
1754
  : // Two copies of React and other install problems are named by
1237
1755
  // doctor; the same show would fail the same way.
1238
- ['astryx doctor'],
1756
+ [`${getCliInvocation(cwd)} doctor`],
1239
1757
  },
1240
1758
  );
1241
1759
  const f = themeFiles(cwd, theme);
1242
1760
  // A build that does not match the settings (a command stopped mid-build,
1243
1761
  // a hand edit, another CLI) is made again from the settings, and said.
1244
- const stale = staleBuild(cwd, theme, data);
1762
+ // An own source that does not parse is refused before anything is
1763
+ // built, written or removed (the build would fail part way).
1764
+ if (!readOnly) refuseThemeParse(cwd, theme);
1245
1765
  const brokenSource = themeSourceProblem(cwd, theme);
1246
- if (stale && !brokenSource && !readOnly) await buildTheme(ctx, theme, data);
1766
+ // Every output, as `compile --check` reads them: one missing or edited by
1767
+ // hand is built again too.
1768
+ const stale =
1769
+ staleBuild(cwd, theme, data) ||
1770
+ (brokenSource ? null : await outputsDrift(ctx, theme));
1771
+ // Every file the build may rewrite or remove (the settings module, the
1772
+ // built outputs, the variants types, section sheets, pictures), so a
1773
+ // theme source that does not build, or builds a value that is not text,
1774
+ // leaves the folder exactly as it was.
1775
+ // An output that was not there is recorded as absent (null), so putting
1776
+ // the folder back removes what the build made new; the palette files in
1777
+ // tokens/ are recorded the same way.
1778
+ /** @type {Map<string, Buffer | null>} */
1779
+ let kept = new Map();
1780
+ const tokensDir = path.join(f.dir, 'tokens');
1781
+ if (stale && !brokenSource && !readOnly) {
1782
+ kept = new Map(
1783
+ fs
1784
+ .readdirSync(f.dir)
1785
+ .filter(
1786
+ n =>
1787
+ n === path.basename(f.settingsTs) ||
1788
+ (n.startsWith(`${theme}.`) &&
1789
+ /\.(css|js|d\.ts|css\.d\.ts|variants\.d\.ts)$/.test(n)) ||
1790
+ /^(sheet-[a-z-]+\.html|(sheet|preview)(-[a-z-]+)?\.png)$/.test(n),
1791
+ )
1792
+ .map(n => [path.join(f.dir, n), fs.readFileSync(path.join(f.dir, n))]),
1793
+ );
1794
+ for (const n of [
1795
+ path.basename(f.settingsTs),
1796
+ `${theme}.css`,
1797
+ `${theme}.js`,
1798
+ `${theme}.d.ts`,
1799
+ `${theme}.css.d.ts`,
1800
+ `${theme}.variants.d.ts`,
1801
+ ])
1802
+ if (!kept.has(path.join(f.dir, n))) kept.set(path.join(f.dir, n), null);
1803
+ if (fs.existsSync(tokensDir))
1804
+ for (const n of fs.readdirSync(tokensDir)) {
1805
+ const file = path.join(tokensDir, n);
1806
+ if (fs.statSync(file).isFile()) kept.set(file, fs.readFileSync(file));
1807
+ }
1808
+ const refs = path.join(tokensDir, `${theme}.palette-refs.ts`);
1809
+ if (!kept.has(refs)) kept.set(refs, null);
1810
+ try {
1811
+ await buildTheme(ctx, theme, data);
1812
+ } catch (e) {
1813
+ putBack(kept, tokensDir);
1814
+ if (e instanceof AstryxError && e.code !== E.ERR_THEME_LOAD) throw e;
1815
+ // An own theme source that no longer builds is named, as `set` names
1816
+ // it; the old build is never shown as current.
1817
+ const why = (e instanceof Error ? e.message : String(e))
1818
+ .split(`${cwd}${path.sep}`)
1819
+ .join('')
1820
+ .replace(/\s*Make sure all imports[^|]*$/s, '')
1821
+ .split('\n')
1822
+ .slice(0, 3)
1823
+ .join(' | ');
1824
+ refuse(
1825
+ E.ERR_THEME_INVALID,
1826
+ `${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)` : ''}`,
1827
+ {run: [`${P} how --list dials`]},
1828
+ );
1829
+ }
1830
+ }
1247
1831
  // The settings loaded whole: a `new` marker beside them is stale.
1248
1832
  if (!readOnly) clearNewMarker(f.dir);
1249
1833
  // A built module that cannot be read (damaged by hand) is built again.
1250
1834
  /** @type {string | null} */
1251
1835
  let unreadable = null;
1252
1836
  const res = await resolvedTokens(ctx, theme).catch(async e => {
1837
+ if (
1838
+ e instanceof AstryxError &&
1839
+ e.code === E.ERR_THEME_INVALID &&
1840
+ kept.size
1841
+ ) {
1842
+ // What this show just built goes back with the refusal.
1843
+ putBack(kept, tokensDir);
1844
+ throw e;
1845
+ }
1253
1846
  if (e instanceof AstryxError || readOnly) throw e;
1847
+ // The source lines the settings need are missing too: the build cannot
1848
+ // be made again until they are back, and show says so (never a run of
1849
+ // show itself).
1850
+ if (brokenSource)
1851
+ refuse(
1852
+ E.ERR_THEME_INVALID,
1853
+ `${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.`,
1854
+ {
1855
+ run: [`cat ${quoteCommandArgument(shown(cwd, f.ts))}`],
1856
+ },
1857
+ );
1254
1858
  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
1859
  await buildTheme(ctx, theme, data);
1256
1860
  return resolvedTokens(ctx, theme);
@@ -1265,13 +1869,35 @@ export async function themeEditShow(theme, options = {}) {
1265
1869
  await baseResolved(ctx.project, data.like),
1266
1870
  ctx.project.core.tokenDefaults,
1267
1871
  );
1872
+ // A render that fails here (two copies of React, a component that
1873
+ // throws) is refused as the one above: what this show built goes back,
1874
+ // and the result says so.
1875
+ const rendering = async (/** @type {() => Promise<any>} */ run) => {
1876
+ try {
1877
+ return await run();
1878
+ } catch (e) {
1879
+ if (!(e instanceof Error)) throw e;
1880
+ if (e instanceof AstryxError && e.code !== E.ERR_RENDER_FAILED) throw e;
1881
+ putBack(kept, tokensDir);
1882
+ return refuse(
1883
+ E.ERR_RENDER_FAILED,
1884
+ `${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.`,
1885
+ {run: [`${getCliInvocation(cwd)} doctor`]},
1886
+ );
1887
+ }
1888
+ };
1268
1889
  const preview = noPages
1269
1890
  ? shown(cwd, f.preview)
1270
- : await renderPreview(ctx, theme, data);
1271
- const previewStale = noPages ? [] : await keepPreviewRoute(ctx, theme);
1891
+ : await rendering(() => renderPreview(ctx, theme, data));
1892
+ const previewStale = noPages
1893
+ ? []
1894
+ : await rendering(() => keepPreviewRoute(ctx, theme));
1272
1895
  const sheet = noPages
1273
1896
  ? {file: shown(cwd, f.sheet), components: 0, skipped: []}
1274
- : await renderSheet(ctx, theme, data, {group: section});
1897
+ : await rendering(() => renderSheet(ctx, theme, data, {group: section}));
1898
+ // The full sheet records the build it shows, so a later change tells a
1899
+ // sheet that still matches (after an undo) from one that does not.
1900
+ if (!noPages && !section) stampSheet(f.sheet, theme, cwd);
1275
1901
  const modes = modesOf(data);
1276
1902
  const shots =
1277
1903
  png && !noPages
@@ -1296,10 +1922,32 @@ export async function themeEditShow(theme, options = {}) {
1296
1922
  theme,
1297
1923
  like: data.like ?? null,
1298
1924
  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
- }),
1925
+ settings: await (async () => {
1926
+ const looksBase = await baseResolved(ctx.project, data.like).catch(
1927
+ () => null,
1928
+ );
1929
+ return data.settings.map(s => {
1930
+ let masked = maskedSettings(data, ctx).get(s);
1931
+ // A look dial (buttons, surfaces) under an exact property on a
1932
+ // part it writes: named, as corners under border-radius is.
1933
+ if (!masked && looksBase && s.source === 'dial' && !s.on) {
1934
+ const writes = dialWrites(ctx, data, s, looksBase);
1935
+ const exact = writes.size
1936
+ ? data.settings.find(
1937
+ x =>
1938
+ x.source === 'property' &&
1939
+ x.on &&
1940
+ !x.when &&
1941
+ !x.state &&
1942
+ partsOf(ctx, x).some(t => writes.has(`${t}\0${x.thing}`)),
1943
+ )
1944
+ : undefined;
1945
+ if (exact)
1946
+ masked = `${describe(exact)} is an exact property and wins over ${s.thing} on ${exact.on}`;
1947
+ }
1948
+ return {...s, parts: partsOf(ctx, s), ...(masked ? {masked} : {})};
1949
+ });
1950
+ })(),
1303
1951
  notes: [
1304
1952
  ...(noReact
1305
1953
  ? [
@@ -1310,19 +1958,30 @@ export async function themeEditShow(theme, options = {}) {
1310
1958
  ? [
1311
1959
  `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
1960
  ]
1313
- : stale
1961
+ : stale && !brokenSource
1314
1962
  ? [
1315
- `the build did not match ${theme}.settings.json (${stale}), so it was built again from the settings`,
1963
+ `the build was not current (${stale}), so it was built again from the settings`,
1316
1964
  ]
1317
- : []),
1965
+ : stale
1966
+ ? [
1967
+ `the build is not current (${stale}), and it was not built again: the theme source cannot carry the settings`,
1968
+ ]
1969
+ : []),
1318
1970
  ...(unreadable ? [unreadable] : []),
1319
1971
  ...(brokenSource
1320
1972
  ? [
1321
- `${brokenSource}, so settings cannot take effect; put back the import, extends and name lines in ${theme}.theme.ts`,
1973
+ `${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
1974
  ]
1323
1975
  : []),
1324
1976
  ...checked.filter(x => x.startsWith('not checked')),
1325
1977
  ...fontNotes(ctx, data),
1978
+ ...ownSourceMaskNotes(
1979
+ ctx,
1980
+ cwd,
1981
+ theme,
1982
+ data,
1983
+ await baseResolved(ctx.project, data.like),
1984
+ ),
1326
1985
  ],
1327
1986
  // A size, number or font is the same in both modes: one value.
1328
1987
  resolved: Object.fromEntries(
@@ -1339,7 +1998,7 @@ export async function themeEditShow(theme, options = {}) {
1339
1998
  res,
1340
1999
  modes[0],
1341
2000
  ),
1342
- ...colorsReport(pal, data),
2001
+ ...colorsReport(pal, data, res, theme),
1343
2002
  problems,
1344
2003
  preview,
1345
2004
  previewStale,
@@ -1353,6 +2012,39 @@ export async function themeEditShow(theme, options = {}) {
1353
2012
  };
1354
2013
  }
1355
2014
 
2015
+ /**
2016
+ * The part properties a dial writes, read from what the build writes with
2017
+ * it and without it (so a dial's outputs are never listed by hand), as
2018
+ * `target\0css-property` keys.
2019
+ * @param {import('./_settings.mjs').Ctx} ctx
2020
+ * @param {import('./_settings.mjs').ThemeData} data
2021
+ * @param {import('./_settings.mjs').Setting} dial
2022
+ * @param {{light: Record<string, string>, dark: Record<string, string>}} base
2023
+ * @returns {Set<string>}
2024
+ */
2025
+ function dialWrites(ctx, data, dial, base) {
2026
+ /** @type {Set<string>} */
2027
+ const out = new Set();
2028
+ const comps = (/** @type {import('./_settings.mjs').Setting[]} */ settings) =>
2029
+ /** @type {Record<string, Record<string, Record<string, unknown>>>} */ (
2030
+ compileTheme(ctx, {...data, settings}, base).components ?? {}
2031
+ );
2032
+ let plain;
2033
+ let withDial;
2034
+ try {
2035
+ plain = comps([]);
2036
+ withDial = comps([dial]);
2037
+ } catch {
2038
+ return out;
2039
+ }
2040
+ for (const [target, keys] of Object.entries(withDial))
2041
+ for (const [key, block] of Object.entries(keys ?? {}))
2042
+ for (const [prop, value] of Object.entries(block ?? {}))
2043
+ if (typeof value === 'string' && plain[target]?.[key]?.[prop] !== value)
2044
+ out.add(`${target}\0${kebab(prop)}`);
2045
+ return out;
2046
+ }
2047
+
1356
2048
  /**
1357
2049
  * What applies once `removed` is gone: a whole-theme setting of the same
1358
2050
  * thing for a part setting, a dial that still writes the token, or the
@@ -1364,6 +2056,29 @@ export async function themeEditShow(theme, options = {}) {
1364
2056
  * @returns {string}
1365
2057
  */
1366
2058
  function nowApplies(ctx, data, removed, base) {
2059
+ // A token the theme's own source sets shows its value, whatever else
2060
+ // the settings give it.
2061
+ if (removed.source === 'token' && !removed.on && !removed.when) {
2062
+ const own = ownSourceTokenValues(ctx.project.cwd, data.name)[removed.thing];
2063
+ if (own != null)
2064
+ return `${removed.thing} = ${own} (set in ${data.name}.theme.ts)`;
2065
+ }
2066
+ // A role font removed under an exact --font-family-<role>: that token is
2067
+ // what shows there.
2068
+ if (
2069
+ removed.thing === 'font' &&
2070
+ removed.on &&
2071
+ FONT_ROLES.includes(removed.on)
2072
+ ) {
2073
+ const exact = data.settings.find(
2074
+ x =>
2075
+ x.source === 'token' &&
2076
+ !x.on &&
2077
+ !x.when &&
2078
+ x.thing === `--font-family-${removed.on}`,
2079
+ );
2080
+ if (exact) return describe(exact);
2081
+ }
1367
2082
  // A token a dial still writes (an accent color feeds --color-accent):
1368
2083
  // name that dial.
1369
2084
  if (removed.source === 'token' && !removed.on) {
@@ -1387,21 +2102,35 @@ function nowApplies(ctx, data, removed, base) {
1387
2102
  // exact property on the part that this dial would have competed with.
1388
2103
  if (removed.on) {
1389
2104
  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
- );
2105
+ // The part's or its group's setting for the same variant and state
2106
+ // first (a group's hover after the part's hover goes), then a plain one.
2107
+ /** @param {(x: import('./_settings.mjs').Setting) => boolean} scoped */
2108
+ const find = scoped =>
2109
+ [...data.settings]
2110
+ .reverse()
2111
+ .find(
2112
+ x =>
2113
+ x.thing === removed.thing &&
2114
+ x !== removed &&
2115
+ (!x.mode || x.mode === removed.mode) &&
2116
+ (x.on === removed.on || (fam != null && x.on === fam)) &&
2117
+ scoped(x),
2118
+ );
2119
+ const reaches =
2120
+ (removed.when || removed.state
2121
+ ? find(
2122
+ x =>
2123
+ (x.when ?? '') === (removed.when ?? '') &&
2124
+ (x.state ?? '') === (removed.state ?? ''),
2125
+ )
2126
+ : undefined) ?? find(x => !x.when && !x.state);
1400
2127
  if (reaches) return describe(reaches);
1401
- const DIAL_PROPERTY = /** @type {Record<string, RegExp>} */ ({
1402
- corners: /radius$/,
1403
- spacing: /^(padding|gap)(-|$)/,
1404
- });
2128
+ const DIAL_PROPERTY = wordTable(
2129
+ /** @type {Record<string, RegExp>} */ ({
2130
+ corners: /radius$/,
2131
+ spacing: /^(padding|gap)(-|$)/,
2132
+ }),
2133
+ );
1405
2134
  const exact =
1406
2135
  removed.source === 'dial' && DIAL_PROPERTY[removed.thing]
1407
2136
  ? data.settings.find(
@@ -1412,8 +2141,25 @@ function nowApplies(ctx, data, removed, base) {
1412
2141
  )
1413
2142
  : null;
1414
2143
  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.
2144
+ // A removed exact property leaves the dial whose build writes it there
2145
+ // (buttons, surfaces: read from the build), on the part, its group, or
2146
+ // the whole theme.
2147
+ if (removed.source === 'property') {
2148
+ const targets = partsOf(ctx, removed);
2149
+ const writer = [...data.settings].reverse().find(
2150
+ x =>
2151
+ x.source === 'dial' &&
2152
+ x !== removed &&
2153
+ (!x.on || x.on === removed.on || (fam != null && x.on === fam)) &&
2154
+ (x.when ?? '') === (removed.when ?? '') &&
2155
+ (x.state ?? '') === (removed.state ?? '') &&
2156
+ [...dialWrites(ctx, data, x, base)].some(k => {
2157
+ const [t, prop] = k.split('\0');
2158
+ return targets.includes(t) && prop === removed.thing;
2159
+ }),
2160
+ );
2161
+ if (writer) return describe(writer);
2162
+ }
1417
2163
  if (removed.source === 'property') {
1418
2164
  const dial = Object.entries(DIAL_PROPERTY).find(([, re]) =>
1419
2165
  re.test(removed.thing),
@@ -1469,6 +2215,74 @@ function otherModeNotes(data) {
1469
2215
  ];
1470
2216
  }
1471
2217
 
2218
+ /**
2219
+ * The tokens a whole-theme dial setting writes: those that differ between
2220
+ * the theme's dials with it and without it (a font role's family, and every
2221
+ * text size when the scale moves).
2222
+ * @param {import('./_settings.mjs').Ctx} ctx
2223
+ * @param {import('./_settings.mjs').ThemeData} data
2224
+ * @param {import('./_settings.mjs').Setting} s
2225
+ * @param {any} base
2226
+ * @returns {Set<string>}
2227
+ */
2228
+ function dialTouched(ctx, data, s, base) {
2229
+ /** @param {import('./_settings.mjs').Setting[]} list */
2230
+ const dialsOnly = list => ({
2231
+ ...data,
2232
+ settings: list.filter(x => x.source === 'dial'),
2233
+ });
2234
+ const withDial = compileTheme(ctx, dialsOnly(data.settings), base);
2235
+ const without = compileTheme(
2236
+ ctx,
2237
+ dialsOnly(data.settings.filter(x => x !== s)),
2238
+ base,
2239
+ );
2240
+ const differs = (/** @type {unknown} */ a, /** @type {unknown} */ b) =>
2241
+ JSON.stringify(a) !== JSON.stringify(b);
2242
+ const touched = new Set(
2243
+ [
2244
+ ...Object.keys(withDial.tokens ?? {}),
2245
+ ...Object.keys(without.tokens ?? {}),
2246
+ ].filter(k => differs(withDial.tokens?.[k], without.tokens?.[k])),
2247
+ );
2248
+ for (const r of FONT_ROLES)
2249
+ if (differs(withDial.typography?.[r], without.typography?.[r]))
2250
+ touched.add(`--font-family-${r}`);
2251
+ // The type scale feeds every font size and every role size (body,
2252
+ // headings, labels): an exact one of those keeps its text as it is.
2253
+ if (differs(withDial.typography?.scale, without.typography?.scale))
2254
+ for (const k of Object.keys(ctx.project.core.tokenDefaults ?? {}))
2255
+ if (/^--(font-size-|text-[a-z0-9-]+-size$)/.test(k)) touched.add(k);
2256
+ return touched;
2257
+ }
2258
+
2259
+ /**
2260
+ * Notes for the tokens the theme's own source sets that a whole-theme dial
2261
+ * also writes: the source wins, so the dial does not change them.
2262
+ * @param {import('./_settings.mjs').Ctx} ctx
2263
+ * @param {string} cwd
2264
+ * @param {string} slug
2265
+ * @param {import('./_settings.mjs').ThemeData} data
2266
+ * @param {any} base
2267
+ * @returns {string[]}
2268
+ */
2269
+ function ownSourceMaskNotes(ctx, cwd, slug, data, base) {
2270
+ const own = ownSourceTokens(cwd, slug);
2271
+ if (!own.length) return [];
2272
+ /** @type {string[]} */
2273
+ const notes = [];
2274
+ for (const s of data.settings) {
2275
+ if (s.source !== 'dial' || s.on || s.when || s.state) continue;
2276
+ const touched = dialTouched(ctx, data, s, base);
2277
+ const wins = own.filter(k => touched.has(k));
2278
+ if (wins.length)
2279
+ notes.push(
2280
+ `${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'}`,
2281
+ );
2282
+ }
2283
+ return notes;
2284
+ }
2285
+
1472
2286
  /**
1473
2287
  * Each corners or spacing dial set on a part or group, with what its parts
1474
2288
  * get, beside the whole-theme value: `corners large on containers ->
@@ -1481,7 +2295,7 @@ function otherModeNotes(data) {
1481
2295
  * @returns {string[]}
1482
2296
  */
1483
2297
  function partValues(ctx, data, res, mode) {
1484
- const masked = maskedSettings(data);
2298
+ const masked = maskedSettings(data, ctx);
1485
2299
  return data.settings
1486
2300
  .filter(
1487
2301
  s =>
@@ -1554,9 +2368,13 @@ function partValues(ctx, data, res, mode) {
1554
2368
  * says so), and the contrast moves behind the shade choices.
1555
2369
  * @param {import('./_palette.mjs').PaletteMapping | null} pal
1556
2370
  * @param {import('./_settings.mjs').ThemeData} data
2371
+ * @param {Record<'light' | 'dark', Record<string, string>>} [built] the
2372
+ * built theme's resolved values: where one differs from the generated
2373
+ * shade with no exact setting, the theme's own source changed it
2374
+ * @param {string} [slug]
1557
2375
  * @returns {{vibrancy: number | null, colors: import('./theme-edit.type.mjs').ThemeEditColor[], colorNotes: string[]}}
1558
2376
  */
1559
- function colorsReport(pal, data) {
2377
+ function colorsReport(pal, data, built, slug = '') {
1560
2378
  if (!pal) return {vibrancy: null, colors: [], colorNotes: []};
1561
2379
  /** What the user set for each token exactly, in each mode. */
1562
2380
  const exactBy =
@@ -1566,6 +2384,19 @@ function colorsReport(pal, data) {
1566
2384
  for (const m of s.mode ? [s.mode] : ['light', 'dark'])
1567
2385
  (exactBy[s.thing] ??= {})[/** @type {'light' | 'dark'} */ (m)] =
1568
2386
  s.value;
2387
+ /** Tokens the theme's own source sets to another value than generated. */
2388
+ const ownBy =
2389
+ /** @type {Record<string, {light?: string, dark?: string}>} */ ({});
2390
+ for (const [k, v] of Object.entries(pal.tokens))
2391
+ for (const m of /** @type {const} */ (['light', 'dark'])) {
2392
+ const now = built?.[m]?.[k];
2393
+ if (
2394
+ now &&
2395
+ !exactBy[k]?.[m] &&
2396
+ now.trim().toLowerCase() !== String(v[m].color).trim().toLowerCase()
2397
+ )
2398
+ (ownBy[k] ??= {})[m] = now;
2399
+ }
1569
2400
  /** @param {import('./_palette.mjs').StopRef} r */
1570
2401
  const shade = r =>
1571
2402
  r.family === 'black' || r.family === 'white'
@@ -1587,12 +2418,14 @@ function colorsReport(pal, data) {
1587
2418
  k,
1588
2419
  // Each mode says what it shows: the exact setting where one is
1589
2420
  // made for it, else the generated shade.
1590
- exactBy[k]
2421
+ exactBy[k] || ownBy[k]
1591
2422
  ? modes
1592
2423
  .map(m =>
1593
- exactBy[k][m] != null
2424
+ exactBy[k]?.[m] != null
1594
2425
  ? `${m} ${exactBy[k][m]} (your exact setting wins over the generated ${shade(v[m])})`
1595
- : `${m} ${shade(v[m])}`,
2426
+ : ownBy[k]?.[m] != null
2427
+ ? `${m} ${ownBy[k][m]} (your change in ${slug}.theme.ts wins over the generated ${shade(v[m])})`
2428
+ : `${m} ${shade(v[m])}`,
1596
2429
  )
1597
2430
  .join(', ')
1598
2431
  : shades(v),
@@ -1600,9 +2433,22 @@ function colorsReport(pal, data) {
1600
2433
  ),
1601
2434
  })),
1602
2435
  colorNotes: [
1603
- ...pal.notes,
2436
+ // A note about a token the theme's own source changed is dropped:
2437
+ // what it says no longer holds.
2438
+ ...pal.notes.filter(
2439
+ n =>
2440
+ !Object.keys(ownBy).some(k =>
2441
+ new RegExp(`${k.replace(/[-]/g, '\\-')}(?![\\w-])`).test(n),
2442
+ ),
2443
+ ),
1604
2444
  ...pal.contrast
1605
2445
  .filter(c => modes.includes(c.mode))
2446
+ // A pairing the theme's own source changed no longer holds.
2447
+ .filter(
2448
+ c =>
2449
+ !ownBy[c.token]?.[/** @type {'light' | 'dark'} */ (c.mode)] &&
2450
+ !ownBy[c.against]?.[/** @type {'light' | 'dark'} */ (c.mode)],
2451
+ )
1606
2452
  .filter(c => c.note || !c.pass || c.stop !== c.preferred)
1607
2453
  .map(c =>
1608
2454
  c.note
@@ -1611,7 +2457,12 @@ function colorsReport(pal, data) {
1611
2457
  ? `${c.token} ${c.mode}: shade ${c.stop}, not ${c.preferred}, so it reads at ${c.ratio}:1 on ${c.against}`
1612
2458
  : `${c.token} ${c.mode}: only ${c.ratio}:1 on ${c.against} at shade ${c.stop} (needs ${c.needs}:1)`,
1613
2459
  ),
1614
- ],
2460
+ ].filter(
2461
+ n =>
2462
+ !Object.keys(ownBy).some(k =>
2463
+ new RegExp(`${k.replace(/[-]/g, '\\-')}(?![\\w-])`).test(n),
2464
+ ),
2465
+ ),
1615
2466
  };
1616
2467
  }
1617
2468
 
@@ -1640,7 +2491,16 @@ export async function themeEditUndo(theme, options = {}) {
1640
2491
  if (thing === 'base' || thing === 'mode') {
1641
2492
  requireProject(cwd);
1642
2493
  const now = loadTheme(cwd, theme, thing);
1643
- const [first] = readHistory(themeFiles(cwd, theme).history).steps;
2494
+ const historyFile = themeFiles(cwd, theme).history;
2495
+ const {steps, dropped} = readHistory(historyFile);
2496
+ const [first] = steps;
2497
+ // `new` writes no history: with none, no change is saved (a new theme,
2498
+ // or a history deleted). An empty one is every step undone, back to how
2499
+ // the theme was made. A full one may have lost its oldest steps.
2500
+ const noHistory = !fs.existsSync(historyFile);
2501
+ const reachesStart =
2502
+ (steps.length > 0 && steps.length < HISTORY_STEPS) ||
2503
+ (!noHistory && steps.length === 0 && dropped === 0);
1644
2504
  /** @type {any} */
1645
2505
  let made = now;
1646
2506
  try {
@@ -1650,10 +2510,24 @@ export async function themeEditUndo(theme, options = {}) {
1650
2510
  }
1651
2511
  const of = (/** @type {any} */ d) =>
1652
2512
  thing === 'base' ? (d?.like ?? 'none') : (d?.mode ?? 'both');
2513
+ // A step in between that had another value: changed and changed back.
2514
+ const changedBack = steps.some(step => {
2515
+ try {
2516
+ return of(JSON.parse(step.replace(/^\uFEFF/, ''))) !== of(now);
2517
+ } catch {
2518
+ return false;
2519
+ }
2520
+ });
1653
2521
  if (of(made) === of(now))
1654
2522
  refuse(
1655
2523
  E.ERR_THEME_NOT_SET,
1656
- `${thing} was never changed: it is ${of(now)}, as ${theme} was made.`,
2524
+ reachesStart && changedBack
2525
+ ? `${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.`
2526
+ : reachesStart
2527
+ ? `${thing} was never changed: it is ${of(now)}, as ${theme} was made.`
2528
+ : noHistory
2529
+ ? `${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.`
2530
+ : `${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
2531
  {run: [`${P} show ${theme}`]},
1658
2532
  );
1659
2533
  return change('set', theme, thing, of(made), options);
@@ -1695,6 +2569,9 @@ export async function themeEditUndo(theme, options = {}) {
1695
2569
  // entry replaces it without the current file being read.
1696
2570
  /** @type {import('./_settings.mjs').ThemeData | null} */
1697
2571
  let current = null;
2572
+ // A file in the theme that is a folder or cannot be read is named first;
2573
+ // the damaged-settings path below never sees it.
2574
+ if (slugOk(theme)) refuseUnreadableFiles(cwd, theme);
1698
2575
  try {
1699
2576
  current = loadTheme(cwd, theme);
1700
2577
  } catch (e) {
@@ -1707,7 +2584,7 @@ export async function themeEditUndo(theme, options = {}) {
1707
2584
  E.ERR_THEME_INVALID,
1708
2585
  `${theme}.history.json is damaged, so there is no step to go back to.`,
1709
2586
  {
1710
- fix: `delete ${shown(cwd, f.history)}: the next change starts a new history, and your settings stay as they are`,
2587
+ 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
2588
  run: [`${P} show ${theme}`],
1712
2589
  },
1713
2590
  );
@@ -1783,13 +2660,35 @@ export async function themeEditUndo(theme, options = {}) {
1783
2660
  E.ERR_THEME_INVALID,
1784
2661
  `The settings before the last change, in ${theme}.history.json, are damaged: ${still}.`,
1785
2662
  {
1786
- fix: `delete ${shown(cwd, f.history)}: the next change starts a new history, and your settings stay as they are`,
2663
+ 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
2664
  run: [`${P} show ${theme}`],
1788
2665
  },
1789
2666
  );
1790
2667
  prev = repaired.data;
1791
2668
  leftOut = repaired.dropped;
1792
2669
  }
2670
+ // The checks that need this Core too (a token's type, a part, a state,
2671
+ // a name that is no token or property): what they refuse is left out of
2672
+ // the step, with the same note, so the build stays valid.
2673
+ {
2674
+ const bad = new Set(storedProblems(ctx, theme, prev).map(p => p.setting));
2675
+ if (bad.size) {
2676
+ leftOut = [...leftOut, ...prev.settings.filter(s => bad.has(s))];
2677
+ prev = {...prev, settings: prev.settings.filter(s => !bad.has(s))};
2678
+ }
2679
+ }
2680
+ // The steps a later undo can still go back to: one equal to the settings
2681
+ // it would leave (a step this undo left a setting out of may then equal
2682
+ // the next one) is skipped, as undo skips it.
2683
+ let stepsLeft = 0;
2684
+ {
2685
+ let at = JSON.stringify(prev);
2686
+ for (let i = history.length - 1; i >= 0; i--)
2687
+ if (!same(history[i], at)) {
2688
+ stepsLeft++;
2689
+ at = history[i];
2690
+ }
2691
+ }
1793
2692
  // The popped history is written with the change, inside its rollback.
1794
2693
  const committed = await commitTheme(ctx, theme, prev, {
1795
2694
  history: false,
@@ -1833,7 +2732,7 @@ export async function themeEditUndo(theme, options = {}) {
1833
2732
  action: 'step',
1834
2733
  undone,
1835
2734
  settings: prev.settings.length,
1836
- stepsLeft: history.length,
2735
+ stepsLeft: stepsLeft,
1837
2736
  // What the step back changed, as a change reports it.
1838
2737
  changedTokens: committed.changed,
1839
2738
  problems: committed.problems,