@astryxdesign/cli 0.7.15 → 0.7.16-canary.g3aa244b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/README.md +5 -3
  2. package/api/build/_adapter.d.mts +1 -0
  3. package/api/build/blocks/blocks.d.mts +1 -0
  4. package/api/build/blocks/blocks.mjs +18 -1
  5. package/api/component/_adapter.d.mts +1 -1
  6. package/api/component/_adapter.mjs +28 -1
  7. package/api/doctor/_adapter.d.mts +35 -0
  8. package/api/doctor/_adapter.mjs +69 -0
  9. package/api/doctor/built-checks.mjs +1 -1
  10. package/api/doctor/doctor.d.mts +18 -0
  11. package/api/doctor/doctor.doc.mjs +1 -1
  12. package/api/doctor/doctor.mjs +104 -4
  13. package/api/doctor/theme-checks.mjs +6 -10
  14. package/api/integration/add-contribution.mjs +3 -3
  15. package/api/integration/pack-check.mjs +14 -8
  16. package/api/integration/validate-integration.mjs +1 -1
  17. package/api/search/_adapter.mjs +15 -16
  18. package/api/search/_entries.d.mts +2 -1
  19. package/api/search/_entries.mjs +28 -1
  20. package/api/swizzle/_moduleGraph.mjs +1 -1
  21. package/api/theme/_adapter.d.mts +5 -2
  22. package/api/theme/_adapter.mjs +43 -12
  23. package/api/theme/_fork.mjs +1 -1
  24. package/api/theme/build/build.d.mts +116 -32
  25. package/api/theme/build/build.mjs +449 -102
  26. package/api/theme/eject/eject.mjs +22 -1
  27. package/api/theme/template/template.d.mts +19 -0
  28. package/api/theme/template/template.mjs +102 -25
  29. package/api/theme/theme.type.d.mts +5 -1
  30. package/api/theme/theme.type.mjs +2 -1
  31. package/api/theme/themeBuild.doc.mjs +3 -3
  32. package/api/theme/themeEject.doc.mjs +1 -1
  33. package/api/theme/themeTemplate.doc.mjs +9 -3
  34. package/api/theme-edit/_adapter.d.mts +32 -2
  35. package/api/theme-edit/_adapter.mjs +264 -40
  36. package/api/theme-edit/_check.d.mts +93 -4
  37. package/api/theme-edit/_check.mjs +1727 -223
  38. package/api/theme-edit/_color.d.mts +2 -8
  39. package/api/theme-edit/_color.mjs +292 -219
  40. package/api/theme-edit/_compiler.d.mts +1 -0
  41. package/api/theme-edit/_compiler.mjs +20 -1
  42. package/api/theme-edit/_context.d.mts +31 -1
  43. package/api/theme-edit/_context.mjs +445 -41
  44. package/api/theme-edit/_css.d.mts +60 -1
  45. package/api/theme-edit/_css.mjs +404 -28
  46. package/api/theme-edit/_edit.d.mts +25 -0
  47. package/api/theme-edit/_edit.mjs +1532 -149
  48. package/api/theme-edit/_how-commands.d.mts +11 -26
  49. package/api/theme-edit/_how-commands.mjs +30 -2
  50. package/api/theme-edit/_how-question.d.mts +7 -0
  51. package/api/theme-edit/_how-question.mjs +1304 -176
  52. package/api/theme-edit/_how.mjs +144 -30
  53. package/api/theme-edit/_overview.mjs +2 -0
  54. package/api/theme-edit/_palette.d.mts +38 -0
  55. package/api/theme-edit/_palette.mjs +305 -71
  56. package/api/theme-edit/_parts.d.mts +33 -0
  57. package/api/theme-edit/_parts.mjs +138 -9
  58. package/api/theme-edit/_png.d.mts +18 -0
  59. package/api/theme-edit/_png.mjs +95 -14
  60. package/api/theme-edit/_preview-app.d.mts +36 -1
  61. package/api/theme-edit/_preview-app.mjs +1415 -96
  62. package/api/theme-edit/_preview.d.mts +64 -3
  63. package/api/theme-edit/_preview.mjs +514 -31
  64. package/api/theme-edit/_project.d.mts +11 -0
  65. package/api/theme-edit/_project.mjs +46 -12
  66. package/api/theme-edit/_settings.d.mts +278 -5
  67. package/api/theme-edit/_settings.mjs +2741 -195
  68. package/api/theme-edit/_tables.d.mts +24 -0
  69. package/api/theme-edit/_tables.mjs +211 -149
  70. package/api/theme-edit/_vet.d.mts +42 -0
  71. package/api/theme-edit/_vet.mjs +144 -0
  72. package/api/theme-edit/theme-edit.type.d.mts +20 -2
  73. package/api/theme-edit/theme-edit.type.mjs +6 -2
  74. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  75. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  76. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  77. package/api/upgrade/registry/registry.mjs +6 -1
  78. package/assets/codemods/parse.mjs +2 -2
  79. package/assets/docs/tree/single-component.doc.mjs +11 -2
  80. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  81. package/assets/docs.generated.json +2 -2
  82. package/assets/preview-app/next.config.mjs +7 -1
  83. package/assets/preview-app/package.json +1 -0
  84. package/assets/preview-app/src/app/globals.css +1 -0
  85. package/assets/self-audit.generated.json +1 -1
  86. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  87. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  88. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  89. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  90. package/assets/templates/components.generated.json +1 -1
  91. package/assets/templates/pages/dashboard/page.tsx +1 -1
  92. package/authoring/doctypes/_schema.d.mts +52 -5
  93. package/authoring/doctypes/_schema.mjs +62 -7
  94. package/authoring/doctypes/base/type.ts +10 -0
  95. package/authoring/doctypes/component/component.doc.mjs +1 -1
  96. package/authoring/doctypes/function/function.doc.mjs +6 -0
  97. package/authoring/doctypes/function/type.ts +3 -0
  98. package/authoring/doctypes/legacy.mjs +5 -1
  99. package/authoring/index.d.ts +1 -0
  100. package/authoring/shadcn/source-variants.d.mts +1 -1
  101. package/authoring/shadcn/source-variants.mjs +32 -10
  102. package/clients/cli/build-id.generated.json +1 -1
  103. package/clients/cli/commands/doctor.doc.mjs +2 -2
  104. package/clients/cli/commands/experimental/theme.mjs +239 -45
  105. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  106. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +2 -2
  107. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +2 -2
  108. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +3 -3
  109. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  110. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  111. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  112. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  113. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  114. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  115. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  116. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  117. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  118. package/clients/cli/commands/theme.mjs +190 -46
  119. package/clients/cli/formatters/index.mjs +7 -4
  120. package/clients/cli/lib/cli-error.mjs +9 -3
  121. package/clients/cli/lib/component-format.mjs +27 -9
  122. package/clients/cli/lib/json-shim.mjs +72 -2
  123. package/clients/cli/manifest.generated.json +1 -1
  124. package/clients/cli/run.mjs +49 -0
  125. package/foundation/agent-docs/agent-docs-target.d.mts +2 -6
  126. package/foundation/agent-docs/agent-docs-target.mjs +9 -17
  127. package/foundation/agent-docs/agent-docs.mjs +3 -2
  128. package/foundation/config/config-writer.mjs +2 -2
  129. package/foundation/config/project.mjs +60 -14
  130. package/foundation/discovery/component-discovery.mjs +5 -17
  131. package/foundation/discovery/icon-set-writer.mjs +1 -1
  132. package/foundation/discovery/module-exports.mjs +1 -15
  133. package/foundation/discovery/template-adapter.mjs +44 -19
  134. package/foundation/discovery/template-source-tree.mjs +3 -16
  135. package/foundation/discovery/theme-discovery.d.mts +5 -1
  136. package/foundation/discovery/theme-discovery.mjs +61 -43
  137. package/foundation/fs/exact-codec.d.mts +35 -0
  138. package/foundation/fs/exact-codec.mjs +148 -0
  139. package/foundation/fs/gather-cache.d.mts +15 -5
  140. package/foundation/fs/gather-cache.mjs +129 -31
  141. package/foundation/fs/paths.d.mts +39 -0
  142. package/foundation/fs/paths.mjs +44 -11
  143. package/foundation/fs/read-record.mjs +11 -1
  144. package/foundation/integrations/contribution-fixes.mjs +1 -16
  145. package/foundation/integrations/may-have-integrations.mjs +3 -2
  146. package/foundation/integrations/public-imports.mjs +1 -1
  147. package/foundation/render/embedded-imports.mjs +1 -1
  148. package/foundation/render/host-exit.d.mts +8 -0
  149. package/foundation/render/host-exit.mjs +11 -0
  150. package/foundation/render/page-host.mjs +56 -10
  151. package/foundation/render/page-worker.mjs +14 -0
  152. package/foundation/render/render-page.mjs +37 -2
  153. package/foundation/response/error-codes.d.mts +2 -1
  154. package/foundation/response/error-codes.d.ts +1 -0
  155. package/foundation/response/error-codes.doc.mjs +5 -0
  156. package/foundation/response/error-codes.mjs +3 -0
  157. package/foundation/response/json.d.mts +15 -0
  158. package/foundation/response/json.mjs +52 -1
  159. package/foundation/response/response-types.doc.mjs +1 -1
  160. package/foundation/runtime/lazy-dependencies.d.mts +14 -0
  161. package/foundation/runtime/lazy-dependencies.mjs +82 -0
  162. package/foundation/xle/browser.d.mts +2 -2
  163. package/package.json +7 -6
@@ -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,8 +70,28 @@ import {
60
70
  slugFor,
61
71
  themeSource,
62
72
  themeSourceProblem,
73
+ refuseThemeParse,
74
+ ownSourceTokens,
75
+ ownSourceTokenValues,
76
+ ownPartTokens,
77
+ PHONE_TYPE,
78
+ refreshSourceStamp,
79
+ sourceChangedReason,
80
+ builtPairs,
81
+ ownPairMessage,
82
+ freeThemeName,
83
+ refuseLinks,
84
+ usableNewName,
85
+ FOLDER_JUNK,
86
+ dialValueFits,
87
+ holdAfterBuild,
63
88
  } from './_settings.mjs';
64
- import {checkSetting, exampleOf, storedProblems} from './_check.mjs';
89
+ import {
90
+ checkSetting,
91
+ exampleOf,
92
+ normalizeEntry,
93
+ storedProblems,
94
+ } from './_check.mjs';
65
95
  import {MODAL} from './_compiler.mjs';
66
96
  import {
67
97
  PALETTE_DIALS,
@@ -73,12 +103,20 @@ import {
73
103
  lockHeld,
74
104
  refuseIfLockLost,
75
105
  writeWhole,
106
+ isGraySeed,
107
+ seedOf,
76
108
  } from './_palette.mjs';
77
- import {renderPreview, renderSheet} from './_preview.mjs';
78
- import {refreshPreviewRoute} from './_preview-app.mjs';
79
- import {baseResolved, installLine} from './_project.mjs';
109
+ import {
110
+ renderPreview,
111
+ renderSheet,
112
+ takeFirstAppCopy,
113
+ writeAppCopy,
114
+ } from './_preview.mjs';
115
+ import {appWiring, refreshPreviewRoute} from './_preview-app.mjs';
116
+ import {baseInstalled, baseResolved, installLine} from './_project.mjs';
80
117
  import {reactMissing} from './_parts.mjs';
81
118
  import {
119
+ renderCause,
82
120
  requireProject,
83
121
  context,
84
122
  pictures,
@@ -86,9 +124,13 @@ import {
86
124
  styledChanges,
87
125
  previewAfter,
88
126
  checkSection,
127
+ stampSheet,
89
128
  } from './_context.mjs';
90
129
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
91
- import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
130
+ import {
131
+ getCliInvocation,
132
+ quoteCommandArgument,
133
+ } from '../../foundation/env/package-manager.mjs';
92
134
 
93
135
  const E = ERROR_CODES;
94
136
 
@@ -97,9 +139,6 @@ const E = ERROR_CODES;
97
139
  */
98
140
  /** The marker a `new` writes first and removes last. */
99
141
 
100
- /** Files a system or a tool puts in any folder; a folder of only these is empty. */
101
- const FOLDER_JUNK = new Set(['.DS_Store', '.gitkeep', 'Thumbs.db']);
102
-
103
142
  /**
104
143
  * A folder the editor made but that has no settings: a stopped `new` left
105
144
  * its marker, or the settings were removed beside the editor's generated
@@ -177,6 +216,40 @@ function readableJson(file) {
177
216
  }
178
217
  }
179
218
 
219
+ /**
220
+ * A physical padding side as its logical side (left-to-right), so a later
221
+ * `padding-inline` replaces an earlier `padding-left` as it does
222
+ * `padding-inline-start`.
223
+ * @param {string} prop
224
+ */
225
+ const logicalSide = prop =>
226
+ /** @type {Record<string, string>} */ ({
227
+ 'padding-left': 'padding-inline-start',
228
+ 'padding-right': 'padding-inline-end',
229
+ 'padding-top': 'padding-block-start',
230
+ 'padding-bottom': 'padding-block-end',
231
+ })[prop] ?? prop;
232
+
233
+ /**
234
+ * Put back every recorded file: its bytes, or removed when it was not
235
+ * there; a palette file the build made new in tokens/ goes too.
236
+ * @param {Map<string, Buffer | null>} kept
237
+ * @param {string} tokensDir
238
+ */
239
+ function putBack(kept, tokensDir) {
240
+ for (const [file, bytes] of kept)
241
+ if (bytes) writeWhole(file, bytes);
242
+ else if (!fs.existsSync(file) || fs.lstatSync(file).isFile())
243
+ fs.rmSync(file, {force: true});
244
+ if (kept.size && fs.existsSync(tokensDir))
245
+ for (const n of fs.readdirSync(tokensDir)) {
246
+ const file = path.join(tokensDir, n);
247
+ // Only a file the build made new; a folder the user put there stays.
248
+ if (!kept.has(file) && fs.lstatSync(file).isFile())
249
+ fs.rmSync(file, {force: true});
250
+ }
251
+ }
252
+
180
253
  /**
181
254
  * Start a theme in themes/<name>/, optionally on a built-in theme, with any
182
255
  * dial settings applied in the same build. Each setting is checked as `set`
@@ -186,19 +259,104 @@ function readableJson(file) {
186
259
  * @param {import('./theme-edit.type.mjs').ThemeEditNewOptions} [options]
187
260
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditNewResponse>}
188
261
  */
262
+
189
263
  export async function themeEditNew(name, options = {}) {
190
264
  const {cwd = process.cwd(), png = false, settings = {}} = options;
191
265
  // `--like none` builds on no base, as `set <theme> base none` does.
192
266
  const like = options.like === 'none' ? undefined : options.like;
193
267
  requireProject(cwd);
268
+ // A corrected `new` keeps every option given, fixing only the bad one.
269
+ // A --like in another case is the built-in theme it names.
270
+ // A --like that names no built-in theme is the nearest one, or none: a
271
+ // corrected command never repeats a --like that is refused below.
272
+ // A guess (the nearest base to a word that names none) is only a base the
273
+ // project has installed: another would be refused in turn. A base named
274
+ // in other letters is the one meant, installed or not (its refusal then
275
+ // offers the install, or the same new on no base).
276
+ const have = LIKE.filter(b => baseInstalled(cwd, b));
277
+ // `@astryxdesign/theme-butter`, `theme-butter`, `Butter`: butter.
278
+ const baseName = (/** @type {unknown} */ v) =>
279
+ String(v)
280
+ .trim()
281
+ .toLowerCase()
282
+ .replace(/^@astryxdesign\/theme-/, '')
283
+ .replace(/^theme-/, '');
284
+ const likeFixed =
285
+ like == null
286
+ ? options.like === 'none'
287
+ ? 'none'
288
+ : undefined
289
+ : LIKE.includes(baseName(like))
290
+ ? baseName(like)
291
+ : (nearest(baseName(like), have)[0] ?? null);
292
+ // A dial value the dial does not take is left out of a suggested `new`
293
+ // (a corrected name must not repeat it), and the refusal says so.
294
+ /** @type {Array<[string, string]>} */
295
+ const badValue = Object.entries(settings).flatMap(([k, v]) =>
296
+ (Array.isArray(v) ? v : v == null ? [] : [v])
297
+ .map(x => /** @type {[string, string]} */ ([k, String(x)]))
298
+ .filter(([dial, x]) => DIALS[dial] && !dialValueFits(dial, x)),
299
+ );
300
+ // Refused for no effect as new refuses it: vibrancy with no color given
301
+ // that is not a gray (a new theme has no other color to saturate).
302
+ const colorGiven = Object.entries(settings).some(
303
+ ([k, v]) =>
304
+ PALETTE_DIALS.includes(k) &&
305
+ (Array.isArray(v) ? v : v == null ? [] : [v]).some(
306
+ x =>
307
+ !badValue.some(([a, b]) => a === k && b === String(x)) &&
308
+ !isGraySeed(seedOf(String(x))),
309
+ ),
310
+ );
311
+ /** @type {Array<[string, string]>} */
312
+ const noEffect =
313
+ settings.vibrancy != null && !colorGiven
314
+ ? (Array.isArray(settings.vibrancy)
315
+ ? settings.vibrancy
316
+ : [settings.vibrancy]
317
+ ).map(x => /** @type {[string, string]} */ (['vibrancy', String(x)]))
318
+ : [];
319
+ const unfit = [...badValue, ...noEffect];
320
+ const isUnfit = (/** @type {string} */ k, /** @type {unknown} */ x) =>
321
+ unfit.some(([a, b]) => a === k && b === String(x));
322
+ /** @type {Record<string, string | string[] | undefined>} */
323
+ const fitSettings = Object.fromEntries(
324
+ Object.entries(settings).map(([k, v]) => [
325
+ k,
326
+ Array.isArray(v)
327
+ ? v.filter(x => !isUnfit(k, x))
328
+ : isUnfit(k, v)
329
+ ? undefined
330
+ : v,
331
+ ]),
332
+ );
333
+ const flag = (/** @type {[string, string]} */ [k, x]) =>
334
+ `--${k} ${quoteCommandArgument(x)}`;
335
+ const dropped = [
336
+ badValue.length
337
+ ? ` The suggestion leaves out ${badValue.map(flag).join(', ')}: not ${badValue.length === 1 ? 'a value its dial takes' : 'values their dials take'} (${[...new Set(badValue.map(([k]) => `${k} takes ${DIALS[k].values}`))].join('; ')}).`
338
+ : '',
339
+ noEffect.length
340
+ ? ` The suggestion leaves out ${noEffect.map(flag).join(', ')}: vibrancy saturates the theme's colors, and no color that is not a gray is given, so it would change nothing.`
341
+ : '',
342
+ ].join('');
343
+ const again = (
344
+ /** @type {string} */ newName,
345
+ /** @type {string | null | undefined} */ likeValue = likeFixed,
346
+ ) => `${P} new ${newName}${newFlags(likeValue, fitSettings, png)}`;
194
347
  if (!slugOk(name)) {
195
348
  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);
349
+ // Only a name typed in another case is the theme here already.
350
+ const sameName = String(name ?? '').toLowerCase() === fixed;
351
+ const exists = sameName && fs.existsSync(themeFiles(cwd, fixed).settings);
198
352
  refuse(
199
353
  E.ERR_INVALID_ARGUMENT,
200
- `"${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}`]},
354
+ `"${String(name ?? '').slice(0, 80)}" is not a theme name (${NAME_RULE})${exists ? `; ${fixed} is a theme here already` : ''}.${dropped}`,
355
+ {
356
+ run: exists
357
+ ? [`${P} show ${fixed}`]
358
+ : [again(usableNewName(cwd, fixed))],
359
+ },
202
360
  );
203
361
  }
204
362
  // A built-in theme's name would collide with the theme of that name the
@@ -206,8 +364,19 @@ export async function themeEditNew(name, options = {}) {
206
364
  if (LIKE.includes(name))
207
365
  refuse(
208
366
  E.ERR_FILE_EXISTS,
209
- `${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}`]},
367
+ `${name} is a built-in theme; an editor theme needs a name of its own. To start from ${name}, build on it.${dropped}`,
368
+ {
369
+ run: [
370
+ again(
371
+ fs.existsSync(themeFiles(cwd, `my-${name}`).dir)
372
+ ? freeThemeName(cwd, `my-${name}`)
373
+ : `my-${name}`,
374
+ // Built on the theme named when it is installed, unless another
375
+ // base (or none) was given.
376
+ likeFixed ?? name,
377
+ ),
378
+ ],
379
+ },
211
380
  );
212
381
  const f = themeFiles(cwd, name);
213
382
  // A link or a file where the theme goes is never written through or
@@ -218,22 +387,33 @@ export async function themeEditNew(name, options = {}) {
218
387
  refuse(
219
388
  E.ERR_FILE_EXISTS,
220
389
  `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']},
390
+ // A look that changes nothing: what is in the way.
391
+ {
392
+ run: [
393
+ `ls -la ${quoteCommandArgument(path.relative(cwd, f.root) || 'themes')}`,
394
+ ],
395
+ },
223
396
  );
224
397
  const dirSt = fs.lstatSync(f.dir, {throwIfNoEntry: false});
225
398
  if (dirSt && (dirSt.isSymbolicLink() || !dirSt.isDirectory()))
226
399
  refuse(
227
400
  E.ERR_FILE_EXISTS,
228
- `themes/${name} is ${dirSt.isSymbolicLink() ? 'a link' : 'a file'}, so a theme is not made there.`,
229
- {run: [`${P} new ${name}-copy`]},
401
+ `themes/${name} is ${dirSt.isSymbolicLink() ? 'a link' : 'a file'}, so a theme is not made there.${dropped}`,
402
+ {run: [again(freeThemeName(cwd, name))]},
230
403
  );
231
404
  // Settings that are not valid JSON are kept aside, and the theme is
232
405
  // made again beside them.
233
406
  const damaged = fs.existsSync(f.settings) && !readableJson(f.settings);
234
407
  if (fs.existsSync(f.settings) && !damaged)
235
- refuse(E.ERR_FILE_EXISTS, `Theme "${name}" already exists.`, {
236
- run: [`${P} show ${name}`, `${P} set ${name} base neutral`],
408
+ refuse(E.ERR_FILE_EXISTS, `Theme "${name}" already exists.${dropped}`, {
409
+ // What the command asked for, on the theme that exists or as a new one.
410
+ run: [
411
+ `${P} show ${name}`,
412
+ ...(likeFixed && LIKE.includes(likeFixed)
413
+ ? [`${P} set ${name} base ${likeFixed}`]
414
+ : []),
415
+ again(freeThemeName(cwd, name)),
416
+ ],
237
417
  });
238
418
  // A `new` stopped part way (killed, out of memory) leaves its own marker
239
419
  // beside the files it wrote: only such a folder is cleared, and only
@@ -249,29 +429,46 @@ export async function themeEditNew(name, options = {}) {
249
429
  if (holdsOther)
250
430
  refuse(
251
431
  E.ERR_FILE_EXISTS,
252
- `themes/${name}/ already holds files this command did not make; choose another name.`,
253
- {run: [`${P} new ${name}-copy`]},
432
+ `themes/${name}/ already holds files this command did not make; choose another name.${dropped}`,
433
+ {run: [again(freeThemeName(cwd, name))]},
254
434
  );
255
435
  if (like != null && !LIKE.includes(like))
256
436
  refuse(
257
437
  E.ERR_THEME_BAD_VALUE,
258
438
  `--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
439
  {
260
- didYouMean: nearest(String(like).toLowerCase(), LIKE),
261
- run: [`${P} new ${name}`],
440
+ // The built-in theme it names in another case, or the nearest
441
+ // installed one, else none: the did-you-mean and the run agree.
442
+ didYouMean: likeFixed ? [likeFixed] : [],
443
+ // A built-in base that is not installed: install it, then the same
444
+ // new on it.
445
+ run: [
446
+ ...(likeFixed && likeFixed !== 'none' && !have.includes(likeFixed)
447
+ ? [installLine(cwd, [`@astryxdesign/theme-${likeFixed}`])]
448
+ : []),
449
+ again(name, likeFixed ?? null),
450
+ ],
262
451
  },
263
452
  );
264
453
  const ctx = await context(cwd);
265
454
  /** @type {import('./_settings.mjs').ThemeData} */
266
455
  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
- );
456
+ try {
457
+ /** @type {import('./_settings.mjs').Ctx} */ (ctx).base =
458
+ await baseResolved(ctx.project, data.like);
459
+ } catch (e) {
460
+ // A base that is not installed: install it, or the same new on no base.
461
+ if (e instanceof AstryxError && e.code === E.ERR_UNKNOWN_THEME)
462
+ e.suggestions = [
463
+ ...(e.suggestions ?? []),
464
+ {name: again(name, null), reason: 'build on no theme'},
465
+ ];
466
+ throw e;
467
+ }
271
468
  // Every check comes before the first change to the folder: the settings,
272
469
  // and a source of the user's own kept from before (it must still extend
273
470
  // the settings, or the build fails after the folder was cleared).
274
- applyNewSettings(ctx, name, data, settings);
471
+ applyNewSettings(ctx, name, data, settings, png, likeFixed ?? undefined);
275
472
  if (left?.keep.some(p => path.basename(p) === `${name}.theme.ts`))
276
473
  refuseThemeSource(cwd, name);
277
474
  /** @type {string[]} */
@@ -290,7 +487,7 @@ export async function themeEditNew(name, options = {}) {
290
487
  );
291
488
  if (left?.keep.some(p => path.basename(p) === `${name}.history.json`))
292
489
  leftNotes.push(
293
- `the earlier settings are kept in ${name}.history.json: \`${P} undo ${name}\` steps back to them`,
490
+ `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
491
  );
295
492
  // The marker goes first and comes off last: a `new` stopped between
296
493
  // leaves a folder the next `new` can prove it made. The damaged settings
@@ -406,6 +603,8 @@ export async function themeEditNew(name, options = {}) {
406
603
  notes,
407
604
  problems: r.problems,
408
605
  ...p,
606
+ // How to use the theme in this app: theme add <theme> for its app copy.
607
+ wiring: appWiring(ctx, name, data),
409
608
  },
410
609
  };
411
610
  }
@@ -417,8 +616,17 @@ export async function themeEditNew(name, options = {}) {
417
616
  * @param {string} slug
418
617
  * @param {import('./_settings.mjs').ThemeData} data
419
618
  * @param {Record<string, string | string[] | undefined>} settings
619
+ * @param {boolean} [png] kept in a corrected `new` a refusal suggests
620
+ * @param {string} [likeFlag] the --like a corrected `new` keeps (`none` too)
420
621
  */
421
- function applyNewSettings(ctx, slug, data, settings) {
622
+ function applyNewSettings(
623
+ ctx,
624
+ slug,
625
+ data,
626
+ settings,
627
+ png = false,
628
+ likeFlag = data.like,
629
+ ) {
422
630
  const given = Object.entries(settings).filter(([, v]) => v != null);
423
631
  for (const [thing] of given)
424
632
  if (!DIALS[thing] || thing === 'base')
@@ -441,13 +649,21 @@ function applyNewSettings(ctx, slug, data, settings) {
441
649
  const given = settings[thing];
442
650
  if (given == null) continue;
443
651
  // `headings` takes a weight and a tracking: one value per axis.
444
- for (const value of Array.isArray(given) ? given : [given]) {
652
+ const values = Array.isArray(given) ? given : [given];
653
+ for (const [index, value] of values.entries()) {
445
654
  /** @type {import('./_settings.mjs').Setting} */
446
655
  let s;
447
656
  try {
448
657
  s = checkSetting(ctx, slug, data, thing, String(value), {}, false);
449
658
  } catch (e) {
450
- throw asNewRefusal(e, slug, settings);
659
+ throw asNewRefusal(
660
+ vetSuggestions(e, ctx, slug, data),
661
+ slug,
662
+ settings,
663
+ likeFlag,
664
+ png,
665
+ {thing, index},
666
+ );
451
667
  }
452
668
  if (thing === 'mode')
453
669
  data.mode = /** @type {'both' | 'light-only' | 'dark-only'} */ (
@@ -460,8 +676,14 @@ function applyNewSettings(ctx, slug, data, settings) {
460
676
  E.ERR_INVALID_ARGUMENT,
461
677
  `--${thing} was given two values for the same thing (${data.settings[same].value}, ${s.value}); give one.`,
462
678
  {
679
+ // Every other option given stays, and the first value on each
680
+ // axis: every later value for an axis already given goes.
463
681
  run: [
464
- `${P} new ${slug} --${thing} ${quoteCommandArgument(s.value)}`,
682
+ `${P} new ${slug}${newFlags(
683
+ likeFlag,
684
+ {...settings, [thing]: firstPerAxis(values)},
685
+ png,
686
+ )}`,
465
687
  ],
466
688
  },
467
689
  );
@@ -471,36 +693,117 @@ function applyNewSettings(ctx, slug, data, settings) {
471
693
  }
472
694
  }
473
695
 
696
+ /**
697
+ * The options of a `new` as flags, in the order given (`new --help`'s order
698
+ * for the command): `--like`, each dial setting, then `--png`.
699
+ * @param {string | null | undefined} like none when null or undefined
700
+ * @param {Record<string, string | string[] | undefined>} settings
701
+ * @param {boolean} [png]
702
+ * @returns {string[]}
703
+ */
704
+ export function newFlagList(like, settings, png = false) {
705
+ return [
706
+ ...(like ? [`--like ${quoteCommandArgument(like)}`] : []),
707
+ ...Object.entries(settings)
708
+ .filter(([, v]) => v != null)
709
+ .flatMap(([k, v]) => (Array.isArray(v) ? v : [v]).map(x => [k, x]))
710
+ .map(([k, v]) => `--${k} ${quoteCommandArgument(String(v))}`),
711
+ ...(png ? ['--png'] : []),
712
+ ];
713
+ }
714
+
715
+ /**
716
+ * The options of a `new` as one flag line, with its leading space.
717
+ * @param {string | null | undefined} like
718
+ * @param {Record<string, string | string[] | undefined>} settings
719
+ * @param {boolean} png
720
+ */
721
+ function newFlags(like, settings, png) {
722
+ const parts = newFlagList(like, settings, png);
723
+ return parts.length ? ` ${parts.join(' ')}` : '';
724
+ }
725
+
474
726
  /**
475
727
  * A refusal from a setting `new` was given, with its suggestions turned
476
728
  * into `new` commands: the theme does not exist yet, so a `set` would fail.
477
729
  * @param {unknown} e
478
730
  * @param {string} slug
479
731
  * @param {Record<string, string | string[] | undefined>} settings
732
+ * @param {string} [like] the --like given, kept in a corrected command
733
+ * @param {boolean} [png] --png, kept in a corrected command
734
+ * @param {{thing: string, index: number} | null} [at] the value refused
480
735
  */
481
- function asNewRefusal(e, slug, settings) {
736
+ function asNewRefusal(e, slug, settings, like, png = false, at = null) {
482
737
  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
738
  const setPrefix = `${P} set ${slug} `;
488
739
  e.suggestions = (e.suggestions ?? []).map(s => {
489
740
  if (s.name === `${P} set --help`) return {...s, name: `${P} new --help`};
490
741
  if (!s.name.startsWith(setPrefix)) return s;
491
742
  const [thing, ...rest] = s.name.slice(setPrefix.length).split(' ');
492
743
  if (thing.startsWith('--') || !DIALS[thing]) return s;
493
- const keep = flags.filter(f => !f.startsWith(`--${thing} `));
744
+ const fixed = unquoteWord(rest.join(' '));
745
+ // Only the refused value changes: a dial given several values
746
+ // (--headings tight --headings BOLD) keeps the others, in order.
747
+ const given = settings[thing];
748
+ const values = Array.isArray(given) ? [...given] : null;
749
+ const next =
750
+ values && at && at.thing === thing
751
+ ? firstPerAxis(values.map((v, i) => (i === at.index ? fixed : v)))
752
+ : fixed;
494
753
  return {
495
754
  ...s,
496
- name: [`${P} new ${slug}`, ...keep, `--${thing} ${rest.join(' ')}`].join(
497
- ' ',
498
- ),
755
+ name: `${P} new ${slug}${newFlags(like, {...settings, [thing]: next}, png)}`,
499
756
  };
500
757
  });
758
+ // A refused value with nothing to put in its place: the same new
759
+ // without it, every other option kept.
760
+ if (at && !e.suggestions.some(x => x.name.startsWith(`${P} new `))) {
761
+ const given = settings[at.thing];
762
+ const rest = Array.isArray(given)
763
+ ? given.filter((_, i) => i !== at.index)
764
+ : undefined;
765
+ e.suggestions.push({
766
+ name: `${P} new ${slug}${newFlags(like, {...settings, [at.thing]: rest?.length ? rest : undefined}, png)}`,
767
+ reason: `without --${at.thing} ${quoteCommandArgument(String(Array.isArray(given) ? given[at.index] : given))}`,
768
+ });
769
+ }
501
770
  return e;
502
771
  }
503
772
 
773
+ /**
774
+ * Headings values with every later value for an axis already given left
775
+ * out (the first weight and the first tracking stay); a word of neither
776
+ * axis stays, for its own refusal.
777
+ * @param {string[]} values
778
+ * @returns {string[]}
779
+ */
780
+ function firstPerAxis(values) {
781
+ const seen = new Set();
782
+ return values.filter(v => {
783
+ const w = String(v).trim().toLowerCase();
784
+ const axis =
785
+ HEADING_WEIGHTS[w] !== undefined
786
+ ? 'weight'
787
+ : HEADING_TRACKING[w] !== undefined
788
+ ? 'tracking'
789
+ : null;
790
+ if (!axis) return true;
791
+ if (seen.has(axis)) return false;
792
+ seen.add(axis);
793
+ return true;
794
+ });
795
+ }
796
+
797
+ /**
798
+ * A word as a suggested command writes it, without the quotes
799
+ * quoteCommandArgument adds.
800
+ * @param {string} word
801
+ */
802
+ function unquoteWord(word) {
803
+ const m = /^'(.*)'$/s.exec(word);
804
+ return m ? m[1].replace(/'\\''/g, "'") : word;
805
+ }
806
+
504
807
  /**
505
808
  * The preview after a change, with the in-app preview route kept in step:
506
809
  * its imports follow the theme, such as the stylesheet of a font package
@@ -512,7 +815,13 @@ function asNewRefusal(e, slug, settings) {
512
815
  */
513
816
  async function previewAndRoute(ctx, slug, data, png) {
514
817
  const p = await previewAfter(ctx, slug, data, png);
515
- return {...p, previewStale: await keepPreviewRoute(ctx, slug)};
818
+ const wrote = takeFirstAppCopy(ctx.project.cwd, slug);
819
+ return {
820
+ ...p,
821
+ previewStale: await keepPreviewRoute(ctx, slug),
822
+ // The first time the theme's app copy is written, its files are named.
823
+ ...(wrote ? {appCopy: {wrote}} : {}),
824
+ };
516
825
  }
517
826
 
518
827
  /**
@@ -552,12 +861,36 @@ export async function themeEditSet(theme, thing, value, options = {}) {
552
861
  * @param {import('./_settings.mjs').Ctx} ctx
553
862
  * @param {string} slug
554
863
  * @param {import('./_settings.mjs').ThemeData} data
555
- * @param {string} [skip]
864
+ * @param {string | {thing: string, on?: string, when?: string, state?: string, mode?: string}} [skip]
556
865
  */
557
866
  function refuseStoredTokens(ctx, slug, data, skip) {
558
867
  const bad = storedProblems(ctx, slug, data, skip);
559
868
  if (!bad.length) return;
560
- const one = bad.length === 1 ? bad[0] : null;
869
+ const found = bad.length === 1 ? bad[0] : null;
870
+ // A clean value is offered only when set takes it, so the line works.
871
+ const takes = (/** @type {typeof found} */ b) => {
872
+ if (!b?.fix) return true;
873
+ try {
874
+ checkSetting(
875
+ ctx,
876
+ slug,
877
+ {...data, settings: data.settings.filter(x => x !== b.setting)},
878
+ b.setting.thing,
879
+ b.fix,
880
+ {
881
+ on: b.setting.on,
882
+ when: b.setting.when,
883
+ state: b.setting.state,
884
+ mode: b.setting.mode,
885
+ },
886
+ false,
887
+ );
888
+ return true;
889
+ } catch {
890
+ return false;
891
+ }
892
+ };
893
+ const one = found && takes(found) ? found : null;
561
894
  refuse(
562
895
  E.ERR_THEME_INVALID,
563
896
  `themes/${slug}/${slug}.settings.json: ${bad
@@ -571,16 +904,68 @@ function refuseStoredTokens(ctx, slug, data, skip) {
571
904
  // setting is never refused for another.
572
905
  run: [
573
906
  ...bad.slice(0, 5).map(b => `${P} undo ${slug} ${undoArgs(b.setting)}`),
574
- ...(one && !one.scope
907
+ // A value to set only for a token whose stored value has the wrong
908
+ // type; any other thing `set` would refuse, or read as a dial.
909
+ ...(one &&
910
+ !one.scope &&
911
+ one.setting.source === 'token' &&
912
+ ctx.C.isToken(one.setting.thing)
575
913
  ? [
576
- `${P} set ${slug} ${one.setting.thing} ${quoteCommandArgument(exampleOf(ctx.C.typeOf(one.setting.thing), one.setting.thing))}`,
914
+ // The value the check suggests for this value, else a stock
915
+ // one of the token's type.
916
+ `${P} set ${slug} ${one.setting.thing} ${quoteCommandArgument(one.fix ?? exampleOf(ctx.C.typeOf(one.setting.thing), one.setting.thing))}`,
577
917
  ]
578
- : []),
918
+ : one && one.fix && one.setting.source === 'dial'
919
+ ? [
920
+ `${P} set ${slug} ${one.setting.thing} ${quoteCommandArgument(one.fix)}`,
921
+ ]
922
+ : []),
579
923
  ],
580
924
  },
581
925
  );
582
926
  }
583
927
 
928
+ /**
929
+ * For `compile`: the refusal `show` gives for saved settings the editor no
930
+ * longer accepts (naming the undo that removes each), or null.
931
+ * @param {string} root
932
+ * @param {string} slug
933
+ * @returns {Promise<import('../error.mjs').AstryxError | null>}
934
+ */
935
+ export async function editorStoredRefusal(root, slug) {
936
+ try {
937
+ const ctx = await context(root);
938
+ refuseStoredTokens(ctx, slug, loadTheme(root, slug));
939
+ return null;
940
+ } catch (e) {
941
+ if (e instanceof AstryxError) return e;
942
+ throw e;
943
+ }
944
+ }
945
+
946
+ /**
947
+ * For `compile`: the refusal of [light, dark] pairs on tokens that are not
948
+ * colors in what the theme builds now, or null.
949
+ * @param {string} root
950
+ * @param {string} slug
951
+ * @returns {Promise<import('../error.mjs').AstryxError | null>}
952
+ */
953
+ export async function editorPairRefusal(root, slug) {
954
+ const ctx = await context(root);
955
+ const names = await builtPairs(ctx, slug);
956
+ if (!names.length) return null;
957
+ return new AstryxError(
958
+ ownPairMessage(slug, names),
959
+ [
960
+ {
961
+ name: `grep -n -- ${quoteCommandArgument(names[0])} ${quoteCommandArgument(`themes/${slug}/${slug}.theme.ts`)}`,
962
+ reason: 'see where the file sets it',
963
+ },
964
+ ],
965
+ ERROR_CODES.ERR_THEME_INVALID,
966
+ );
967
+ }
968
+
584
969
  /**
585
970
  * A note for type scale steps that land outside 9 to 200 pixels.
586
971
  * @param {Record<string, string>} res resolved light tokens
@@ -611,12 +996,79 @@ function extremeSteps(res) {
611
996
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
612
997
  */
613
998
  async function change(sub, slug, thing, value, options) {
999
+ // As typed: an undo of a saved entry written in a form the cleanup below
1000
+ // repairs (`Corners`, `var(--radius-page)`) removes that exact entry.
1001
+ const typedThing = thing;
1002
+ // How it was typed, put right before anything reads it (a pasted
1003
+ // declaration, a dash, a var(), invisible spaces).
1004
+ if (typeof thing === 'string') {
1005
+ const entry = normalizeEntry(thing, value);
1006
+ thing = entry.thing;
1007
+ value = entry.value;
1008
+ }
1009
+ /** @type {{ctx?: import('./_settings.mjs').Ctx, data?: import('./_settings.mjs').ThemeData}} */
1010
+ const seen = {};
1011
+ try {
1012
+ return await changeOnce(sub, slug, thing, value, options, seen, typedThing);
1013
+ } catch (e) {
1014
+ // A theme name one letter off an existing theme: the same command with
1015
+ // that name comes first, before making a theme of the typo.
1016
+ if (e instanceof AstryxError && e.code === E.ERR_UNKNOWN_THEME) {
1017
+ const near = (e.suggestions ?? []).find(x => x.reason === 'did you mean');
1018
+ if (near && slugOk(near.name)) {
1019
+ const flags = [
1020
+ ...(options.on ? ['--on', options.on] : []),
1021
+ ...(options.when ? ['--when', options.when] : []),
1022
+ ...(options.state ? ['--state', options.state] : []),
1023
+ ...(options.mode ? ['--mode', options.mode] : []),
1024
+ ...(options.only ? ['--only'] : []),
1025
+ ];
1026
+ const words = [thing, ...(value == null ? [] : [value]), ...flags]
1027
+ .filter(w => w != null && w !== '')
1028
+ .map(w =>
1029
+ String(w).startsWith('--') ? w : quoteCommandArgument(String(w)),
1030
+ );
1031
+ e.suggestions = [
1032
+ {
1033
+ name: `${P} ${sub} ${near.name}${words.length ? ` ${words.join(' ')}` : ''}`,
1034
+ reason: `do this instead: ${near.name} is a theme here`,
1035
+ },
1036
+ ...(e.suggestions ?? []).filter(x => x !== near),
1037
+ ];
1038
+ }
1039
+ throw e;
1040
+ }
1041
+ // Every `set` the refusal suggests is checked as `set` checks it.
1042
+ throw vetSuggestions(e, seen.ctx, slug, seen.data);
1043
+ }
1044
+ }
1045
+
1046
+ /**
1047
+ * @param {'set' | 'undo'} sub
1048
+ * @param {string} slug
1049
+ * @param {string} thing
1050
+ * @param {string | undefined} value
1051
+ * @param {ChangeOptions} options
1052
+ * @param {{ctx?: import('./_settings.mjs').Ctx, data?: import('./_settings.mjs').ThemeData}} seen
1053
+ * the context and the theme as loaded, for checking a refusal's suggestions
1054
+ * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
1055
+ */
1056
+ async function changeOnce(
1057
+ sub,
1058
+ slug,
1059
+ thing,
1060
+ value,
1061
+ options,
1062
+ seen,
1063
+ typedThing = thing,
1064
+ ) {
614
1065
  const {cwd = process.cwd(), png = false} = options;
615
1066
  requireProject(cwd);
616
1067
  // The setting this command changes or removes may be the bad one; any
617
1068
  // other bad setting still refuses (or is left out when this fixes one).
618
1069
  const target = /** @type {Partial<import('./_settings.mjs').Setting>} */ ({
619
- thing,
1070
+ // An undo may name a saved entry exactly as written.
1071
+ thing: sub === 'undo' ? typedThing : thing,
620
1072
  on: options.on,
621
1073
  when: options.when,
622
1074
  state: options.state,
@@ -643,7 +1095,14 @@ async function change(sub, slug, thing, value, options) {
643
1095
  const ctx = await context(cwd);
644
1096
  // An undo of one setting only removes it, so it never waits on the
645
1097
  // others being fixed.
646
- if (sub !== 'undo') refuseStoredTokens(ctx, slug, data, thing);
1098
+ if (sub !== 'undo')
1099
+ refuseStoredTokens(ctx, slug, data, {
1100
+ thing,
1101
+ on: options.on,
1102
+ when: options.when,
1103
+ state: options.state,
1104
+ mode: options.mode,
1105
+ });
647
1106
  const flags = {
648
1107
  on: options.on,
649
1108
  when: options.when,
@@ -664,10 +1123,65 @@ async function change(sub, slug, thing, value, options) {
664
1123
  );
665
1124
  }
666
1125
  /** @type {import('./_settings.mjs').Ctx} */ (ctx).base = base;
1126
+ seen.ctx = ctx;
1127
+ seen.data = structuredClone(data);
1128
+ // The saved entry an undo names exactly as written (thing and scope, in
1129
+ // their own letters), when the editor would read it as another setting
1130
+ // or refuse it: that entry is removed, never a valid neighbor the
1131
+ // cleaned name also matches.
1132
+ const exactIdx =
1133
+ sub === 'undo'
1134
+ ? data.settings.findIndex(
1135
+ x =>
1136
+ x.thing === typedThing &&
1137
+ (x.on ?? null) === (flags.on ?? null) &&
1138
+ (x.when ?? null) === (flags.when ?? null) &&
1139
+ (x.state ?? null) === (flags.state ?? null) &&
1140
+ (x.mode ?? null) === (flags.mode ?? null) &&
1141
+ Boolean(x.only) === Boolean(flags.only),
1142
+ )
1143
+ : -1;
1144
+ let rawIdx = -1;
1145
+ if (exactIdx >= 0) {
1146
+ // Only an entry the editor would not save as written: one it refuses,
1147
+ // or reads as another name, part or state.
1148
+ const entry = data.settings[exactIdx];
1149
+ let read = null;
1150
+ try {
1151
+ read = checkSetting(
1152
+ ctx,
1153
+ slug,
1154
+ data,
1155
+ normalizeEntry(entry.thing, '').thing,
1156
+ undefined,
1157
+ {
1158
+ on: entry.on,
1159
+ when: entry.when,
1160
+ state: entry.state,
1161
+ mode: entry.mode,
1162
+ only: entry.only,
1163
+ },
1164
+ true,
1165
+ );
1166
+ } catch {
1167
+ // Refused as written.
1168
+ }
1169
+ if (
1170
+ !read ||
1171
+ read.thing !== entry.thing ||
1172
+ (read.on ?? null) !== (entry.on ?? null) ||
1173
+ (read.state ?? null) !== (entry.state ?? null) ||
1174
+ (read.when ?? null) !== (entry.when ?? null)
1175
+ )
1176
+ rawIdx = exactIdx;
1177
+ }
667
1178
  /** @type {import('./_settings.mjs').Setting} */
668
1179
  let s;
669
1180
  try {
670
- s = checkSetting(ctx, slug, data, thing, value, flags, sub === 'undo');
1181
+ s =
1182
+ rawIdx >= 0
1183
+ ? data.settings[rawIdx]
1184
+ : checkSetting(ctx, slug, data, thing, value, flags, sub === 'undo');
671
1185
  } catch (e) {
672
1186
  // A stored setting this Core no longer knows (a renamed part or
673
1187
  // property, or a hand edit) can still be removed.
@@ -675,11 +1189,13 @@ async function change(sub, slug, thing, value, options) {
675
1189
  sub === 'undo'
676
1190
  ? data.settings.find(
677
1191
  x =>
678
- x.thing === thing &&
1192
+ x.thing.toLowerCase() === String(thing).toLowerCase() &&
679
1193
  (x.on ?? null) === (flags.on ?? null) &&
680
1194
  (x.when ?? null) === (flags.when ?? null) &&
681
1195
  (x.state ?? null) === (flags.state ?? null) &&
682
- (x.mode ?? null) === (flags.mode ?? null),
1196
+ (x.mode ?? null) === (flags.mode ?? null) &&
1197
+ // --only names a setting made with it; it is never dropped.
1198
+ Boolean(x.only) === Boolean(flags.only),
683
1199
  )
684
1200
  : null;
685
1201
  if (!stored) {
@@ -687,13 +1203,50 @@ async function change(sub, slug, thing, value, options) {
687
1203
  // what it named (or of the dial its refusal names), else the last
688
1204
  // step.
689
1205
  if (sub === 'undo' && e instanceof AstryxError) {
1206
+ // Setting names are matched in any case, and a near name of a
1207
+ // setting the theme has counts: `undo t Corners`, `undo t corner`.
1208
+ const typed = String(thing).toLowerCase();
1209
+ // A token named without its dashes (radius-element) is the token.
1210
+ const dashed = typed.startsWith('--') ? typed : `--${typed}`;
690
1211
  const named = new Set([
691
- thing,
1212
+ typed,
1213
+ dashed,
1214
+ ...(e.suggestions ?? [])
1215
+ .filter(x => x.reason === 'did you mean')
1216
+ .map(x => x.name.toLowerCase()),
692
1217
  ...(e.suggestions ?? [])
693
- .map(x => new RegExp(` set ${slug} (\\S+)`).exec(x.name)?.[1])
1218
+ .map(
1219
+ x => new RegExp(` (?:set|undo) ${slug} (\\S+)`).exec(x.name)?.[1],
1220
+ )
694
1221
  .filter(Boolean),
1222
+ ...nearest(
1223
+ typed,
1224
+ data.settings.map(x => x.thing.toLowerCase()),
1225
+ ),
695
1226
  ]);
696
- const matches = data.settings.filter(x => named.has(x.thing));
1227
+ const matches = data.settings.filter(x =>
1228
+ named.has(x.thing.toLowerCase()),
1229
+ );
1230
+ // A word that is near a setting name (a typo, another case) is never
1231
+ // answered with a bare step back, which would undo another change;
1232
+ // any other word (`all`) may mean the last step.
1233
+ // A token or a property named (radius-element, padding) is a named
1234
+ // thing too: never answered with a step back.
1235
+ const namesThing =
1236
+ ctx.C.isToken(dashed) ||
1237
+ data.settings.some(
1238
+ x => x.source === 'property' && x.thing.toLowerCase() === typed,
1239
+ ) ||
1240
+ /^[a-z]+(-[a-z]+)+$|^(padding|margin|color|background|border|gap|width|height|opacity)$/.test(
1241
+ typed,
1242
+ );
1243
+ const nearSetting =
1244
+ namesThing ||
1245
+ named.size > (dashed === typed ? 1 : 2) ||
1246
+ nearest(typed, [
1247
+ ...Object.keys(DIALS),
1248
+ ...data.settings.map(x => x.thing.toLowerCase()),
1249
+ ]).length > 0;
697
1250
  const steps = readHistory(themeFiles(cwd, slug).history).steps.length;
698
1251
  throw new AstryxError(
699
1252
  e.message,
@@ -703,7 +1256,7 @@ async function change(sub, slug, thing, value, options) {
703
1256
  reason: 'do this instead',
704
1257
  }))
705
1258
  : [
706
- steps
1259
+ steps && !nearSetting
707
1260
  ? {name: `${P} undo ${slug}`, reason: 'step back one change'}
708
1261
  : {name: `${P} show ${slug}`, reason: 'see what it sets'},
709
1262
  ],
@@ -734,7 +1287,11 @@ async function change(sub, slug, thing, value, options) {
734
1287
  .trim()
735
1288
  .toLowerCase()
736
1289
  .replace(/\s+/g, ' ')
737
- .replace(/^["']|["']$/g, '');
1290
+ // Spacing around commas, slashes and parentheses, and the quote
1291
+ // style, are not part of a value.
1292
+ .replace(/\s*([,()/])\s*/g, '$1')
1293
+ .replace(/'/g, '"')
1294
+ .replace(/^"|"$/g, '');
738
1295
  const half =
739
1296
  s.thing === 'headings' && ['weight', 'tracking'].includes(norm(value));
740
1297
  if (
@@ -786,6 +1343,13 @@ async function change(sub, slug, thing, value, options) {
786
1343
  ]
787
1344
  : []),
788
1345
  ...otherModeNotes(data),
1346
+ // Core has no mode inside a theme: the app's <Theme> is given it.
1347
+ ...(s.thing === 'mode' &&
1348
+ (data.mode === 'light-only' || data.mode === 'dark-only')
1349
+ ? [
1350
+ `the app shows ${slug} in ${data.mode === 'light-only' ? 'light' : 'dark'} mode when its <Theme> is given mode="${data.mode === 'light-only' ? 'light' : 'dark'}" (<Theme theme={…} mode="${data.mode === 'light-only' ? 'light' : 'dark'}">), as the preview does; the theme keeps both halves of its colors, so a toast or a lightbox Core draws in the other mode stays readable`,
1351
+ ]
1352
+ : []),
789
1353
  // The colors are made again for the new base or mode: their
790
1354
  // shade notes follow.
791
1355
  ...data.settings
@@ -812,16 +1376,24 @@ async function change(sub, slug, thing, value, options) {
812
1376
  };
813
1377
  }
814
1378
  const k = keyOf(s);
815
- const prevIdx = data.settings.findIndex(x => keyOf(x) === k);
1379
+ const prevIdx =
1380
+ rawIdx >= 0 ? rawIdx : data.settings.findIndex(x => keyOf(x) === k);
816
1381
  /** @type {string | null} */
817
1382
  let vibrancyGone = null;
818
1383
  const prev = prevIdx >= 0 ? data.settings[prevIdx] : null;
819
1384
  if (sub === 'undo') {
820
1385
  if (!prev) {
821
1386
  const near = data.settings.filter(x => x.thing === s.thing).map(describe);
1387
+ // headings has two halves: name the one that is set.
1388
+ const otherHalf =
1389
+ s.thing === 'headings'
1390
+ ? data.settings.find(x => x.thing === 'headings' && x.axis !== s.axis)
1391
+ : null;
822
1392
  refuse(
823
1393
  E.ERR_THEME_NOT_SET,
824
- `The theme does not set ${describe({...s, value: '?'}).replace(' = ?', '')}.`,
1394
+ otherHalf
1395
+ ? `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.`
1396
+ : `The theme does not set ${describe({...s, value: '?'}).replace(' = ?', '')}.`,
825
1397
  {
826
1398
  also: near.length
827
1399
  ? [`settings for ${s.thing}: ${near.join('; ')}`]
@@ -837,6 +1409,8 @@ async function change(sub, slug, thing, value, options) {
837
1409
  );
838
1410
  }
839
1411
  data.settings.splice(prevIdx, 1);
1412
+ // A setting listed twice by hand goes in full.
1413
+ data.settings = data.settings.filter(x => keyOf(x) !== k);
840
1414
  // Vibrancy needs a color: undoing the last one takes it along, so the
841
1415
  // theme never holds a state `set` refuses.
842
1416
  if (
@@ -872,6 +1446,13 @@ async function change(sub, slug, thing, value, options) {
872
1446
  if (prev) data.settings.splice(prevIdx, 1);
873
1447
  data.settings.push(s);
874
1448
  }
1449
+ // A setting listed twice by hand keeps only the entry this command left.
1450
+ if (sub === 'set') {
1451
+ const last = data.settings.map(x => keyOf(x)).lastIndexOf(k);
1452
+ data.settings = data.settings.filter(
1453
+ (x, i) => keyOf(x) !== k || i === last,
1454
+ );
1455
+ }
875
1456
  // A setting for both modes replaces the ones made for one mode, which it
876
1457
  // would otherwise sit under.
877
1458
  /** @type {import('./_settings.mjs').Setting[]} */
@@ -889,16 +1470,24 @@ async function change(sub, slug, thing, value, options) {
889
1470
  x =>
890
1471
  x !== s &&
891
1472
  x.source === 'property' &&
892
- x.on === s.on &&
1473
+ // On the same part, or on a member of the group it is set on:
1474
+ // the later setting wins, whichever way Core writes it.
1475
+ (x.on === s.on ||
1476
+ (s.on != null &&
1477
+ (FAMILIES[s.on] ?? []).includes(
1478
+ /** @type {string} */ (x.on),
1479
+ ))) &&
893
1480
  x.when === s.when &&
894
1481
  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
- ),
1482
+ // A longhand the shorthand really sets (MDN's data), never a
1483
+ // property that only shares its name (overflow-wrap).
1484
+ (coversProperty(s.thing, x.thing) ||
1485
+ coversProperty(logicalSide(s.thing), logicalSide(x.thing))),
900
1486
  )
901
1487
  : [];
1488
+ // They go, as the note says: Core writes each side to its own variable,
1489
+ // where a later shorthand would not win over them (undo brings them back).
1490
+ data.settings = data.settings.filter(x => !longhands.includes(x));
902
1491
  // A group setting covers part settings made before it for its members.
903
1492
  const covers =
904
1493
  sub === 'set' && s.source === 'dial' && s.on && FAMILIES[s.on]
@@ -913,42 +1502,37 @@ async function change(sub, slug, thing, value, options) {
913
1502
  )
914
1503
  : [];
915
1504
  const r = await commitTheme(ctx, slug, data, {history: true});
916
- const styled = styledChanges(compiledBefore, compileTheme(ctx, data, base));
1505
+ const compiledAfter = compileTheme(ctx, data, base);
1506
+ const styled = styledChanges(compiledBefore, compiledAfter, base);
917
1507
  const parts = partsOf(ctx, s);
918
1508
  // Exact whole-theme tokens that win over what this dial writes: the dial
919
1509
  // 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
1510
  /** @type {import('./_settings.mjs').Setting[]} */
926
1511
  let exactWins = [];
1512
+ /** Tokens this whole-theme dial changes. */
1513
+ let dialTokens = new Set();
927
1514
  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);
1515
+ const touched = dialTouched(ctx, data, s, base);
948
1516
  exactWins = data.settings.filter(
949
1517
  x => x.source === 'token' && !x.on && !x.when && touched.has(x.thing),
950
1518
  );
1519
+ dialTokens = touched;
951
1520
  }
1521
+ // A role font (font X --on heading) writes --font-family-<role>: an exact
1522
+ // setting of that token wins over it.
1523
+ if (sub === 'set' && s.thing === 'font' && s.on && FONT_ROLES.includes(s.on))
1524
+ exactWins = data.settings.filter(
1525
+ x =>
1526
+ x.source === 'token' &&
1527
+ !x.on &&
1528
+ !x.when &&
1529
+ x.thing === `--font-family-${s.on}`,
1530
+ );
1531
+ // The theme's own source wins over an exact setting, as the exact
1532
+ // setting does over a dial: an exact token the file also sets is named
1533
+ // as the file's below, never as the one that shows after an undo.
1534
+ const ownFirst = new Set(ownSourceTokens(cwd, slug));
1535
+ exactWins = exactWins.filter(x => !ownFirst.has(x.thing));
952
1536
  const kept =
953
1537
  sub === 'set' && s.source === 'dial' && !s.on
954
1538
  ? [
@@ -956,13 +1540,62 @@ async function change(sub, slug, thing, value, options) {
956
1540
  ...exactWins,
957
1541
  ].map(describe)
958
1542
  : [];
1543
+ // The role fonts a whole-theme font sits under.
1544
+ // An exact --font-family-<role> wins over both: that role is named by
1545
+ // the exact note instead.
1546
+ /** @param {string} role */
1547
+ const exactFamily = role =>
1548
+ data.settings.find(
1549
+ x =>
1550
+ x.source === 'token' &&
1551
+ !x.on &&
1552
+ !x.when &&
1553
+ x.thing === `--font-family-${role}`,
1554
+ );
1555
+ const roleOver =
1556
+ sub === 'set' && s.thing === 'font' && !s.on
1557
+ ? data.settings.filter(
1558
+ x =>
1559
+ x.thing === 'font' &&
1560
+ x.on &&
1561
+ ['body', 'heading'].includes(x.on) &&
1562
+ !exactFamily(x.on),
1563
+ )
1564
+ : [];
1565
+ if (sub === 'set' && s.thing === 'font' && !s.on)
1566
+ for (const role of FONT_ROLES) {
1567
+ const exact = exactFamily(role);
1568
+ if (exact && !exactWins.includes(exact)) exactWins.push(exact);
1569
+ }
959
1570
  // 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
- });
1571
+ const DIAL_PROPERTY = wordTable(
1572
+ /** @type {Record<string, RegExp>} */ ({
1573
+ corners: /radius$/,
1574
+ spacing: /^(padding|gap)(-|$)/,
1575
+ }),
1576
+ );
1577
+ // A whole-theme look dial (buttons, surfaces) writes part properties
1578
+ // too: an exact property on one of them wins there, read from the build.
1579
+ const looksOver =
1580
+ sub === 'set' && s.source === 'dial' && !DIAL_PROPERTY[s.thing]
1581
+ ? (() => {
1582
+ const writes = dialWrites(ctx, data, s, base);
1583
+ if (!writes.size) return null;
1584
+ return (
1585
+ data.settings.find(
1586
+ x =>
1587
+ x.source === 'property' &&
1588
+ x.on &&
1589
+ !x.when &&
1590
+ !x.state &&
1591
+ partsOf(ctx, x).some(t => writes.has(`${t}\0${x.thing}`)),
1592
+ ) ?? null
1593
+ );
1594
+ })()
1595
+ : null;
964
1596
  const exactOver =
965
- sub === 'set' && s.source === 'dial' && s.on && DIAL_PROPERTY[s.thing]
1597
+ looksOver ??
1598
+ (sub === 'set' && s.source === 'dial' && s.on && DIAL_PROPERTY[s.thing]
966
1599
  ? (data.settings.find(
967
1600
  x =>
968
1601
  x.source === 'property' &&
@@ -972,13 +1605,126 @@ async function change(sub, slug, thing, value, options) {
972
1605
  (x.when ?? '') === (s.when ?? '') &&
973
1606
  (x.state ?? '') === (s.state ?? ''),
974
1607
  ) ?? null)
975
- : null;
1608
+ : null);
1609
+ // An exact token the theme's own source also sets: the file's value
1610
+ // shows (read from what the build made of it), not the setting.
1611
+ // On parts: every property or token this change writes on a part's
1612
+ // plain or variant rule (a dial's too, and each member of a group) that
1613
+ // the own source sets on that same rule.
1614
+ /** @type {Array<{target: string, key: string, state?: string | null, prop: string, value: string | null}>} */
1615
+ const ownPartHits = [];
1616
+ if (sub === 'set' && s.on) {
1617
+ const a = /** @type {any} */ (compiledBefore)?.components ?? {};
1618
+ const b = /** @type {any} */ (compiledAfter)?.components ?? {};
1619
+ for (const target of new Set([...Object.keys(a), ...Object.keys(b)]))
1620
+ for (const key of new Set([
1621
+ ...Object.keys(a[target] ?? {}),
1622
+ ...Object.keys(b[target] ?? {}),
1623
+ ])) {
1624
+ if (key !== 'base' && !key.startsWith('variant:')) continue;
1625
+ const x = a[target]?.[key] ?? {};
1626
+ const y = b[target]?.[key] ?? {};
1627
+ /**
1628
+ * The changed properties of one rule (or a state block in it)
1629
+ * the own source sets there too.
1630
+ * @param {any} xs @param {any} ys @param {string | null} state
1631
+ */
1632
+ const compare = (xs, ys, state) => {
1633
+ /** @type {Map<string, string | null> | null} */
1634
+ let own = null;
1635
+ for (const prop of new Set([
1636
+ ...Object.keys(xs ?? {}),
1637
+ ...Object.keys(ys ?? {}),
1638
+ ])) {
1639
+ if (JSON.stringify(xs?.[prop]) === JSON.stringify(ys?.[prop]))
1640
+ continue;
1641
+ if (prop.startsWith(':')) {
1642
+ // A state block (`:hover`) in the rule.
1643
+ if (!state) compare(xs?.[prop], ys?.[prop], prop);
1644
+ continue;
1645
+ }
1646
+ const css = prop.startsWith('--')
1647
+ ? prop
1648
+ : prop.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`);
1649
+ own ??= ownPartTokens(cwd, slug, target, key, state);
1650
+ if (own.has(css))
1651
+ ownPartHits.push({
1652
+ target,
1653
+ key,
1654
+ state,
1655
+ prop: css,
1656
+ value: own.get(css) ?? null,
1657
+ });
1658
+ }
1659
+ };
1660
+ compare(x, y, null);
1661
+ }
1662
+ }
1663
+ // A part dial writes its property on each part it reaches: the own
1664
+ // source setting it there wins, whatever else wins over the dial.
1665
+ if (
1666
+ sub === 'set' &&
1667
+ s.source === 'dial' &&
1668
+ s.on &&
1669
+ !s.state &&
1670
+ DIAL_PROPERTY[s.thing]
1671
+ )
1672
+ for (const target of partsOf(ctx, s))
1673
+ for (const [prop, value] of ownPartTokens(
1674
+ cwd,
1675
+ slug,
1676
+ target,
1677
+ s.when ?? 'base',
1678
+ ))
1679
+ if (
1680
+ DIAL_PROPERTY[s.thing].test(prop) &&
1681
+ !ownPartHits.some(h => h.target === target && h.prop === prop)
1682
+ )
1683
+ ownPartHits.push({target, key: s.when ?? 'base', prop, value});
1684
+ // A direct setting on exactly the rule the own source sets: its undo
1685
+ // takes it back (anything else the file wins over either way).
1686
+ const ownHitDirect =
1687
+ ownPartHits.length === 1 &&
1688
+ (s.source === 'token' || s.source === 'property') &&
1689
+ ownPartHits[0].target === s.on &&
1690
+ ownPartHits[0].prop === s.thing &&
1691
+ ownPartHits[0].key === (s.when ?? 'base') &&
1692
+ (ownPartHits[0].state ?? null) === (s.state ? `:${s.state}` : null);
1693
+ const ownOverToken =
1694
+ sub !== 'set' || s.when || s.state || s.on
1695
+ ? null
1696
+ : s.source === 'token'
1697
+ ? (Object.entries(ownSourceTokenValues(cwd, slug)).find(
1698
+ ([k]) => k === s.thing,
1699
+ ) ??
1700
+ (ownSourceTokens(cwd, slug).includes(s.thing)
1701
+ ? [s.thing, null]
1702
+ : null))
1703
+ : null;
976
1704
  /** @type {string[]} */
977
1705
  const notes = [
978
1706
  ...(covered.length ? [`replaces ${covered.map(describe).join(', ')}`] : []),
1707
+ ...(ownPartHits.length
1708
+ ? [
1709
+ `${slug}.theme.ts sets ${ownPartHits
1710
+ .slice(0, 3)
1711
+ .map(
1712
+ h =>
1713
+ `${h.prop} on ${h.target}${h.state ? ` ${h.state}` : ''}${h.key === 'base' ? '' : ` when ${h.key}`} itself${h.value != null ? ` (${h.value})` : ''}`,
1714
+ )
1715
+ .join(
1716
+ ', ',
1717
+ )}${ownPartHits.length > 3 ? ` and ${ownPartHits.length - 3} more` : ''}, and your own source wins over the settings, so this does not show there; change it in ${slug}.theme.ts${ownHitDirect ? `, or take this back with \`${P} undo ${slug} ${undoArgs(s)}\`` : ''}`,
1718
+ ]
1719
+ : []),
1720
+ ...(ownOverToken
1721
+ ? [
1722
+ `${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${PHONE_TYPE.test(s.thing) ? ` on wide screens (on ${PHONES} this setting shows: the editor repeats exact font settings after the base theme's type there)` : ''}; change it in ${slug}.theme.ts, or take this back with \`${P} undo ${slug} ${undoArgs(s)}\``,
1723
+ ]
1724
+ : []),
979
1725
  ...(exactWins.length
980
1726
  ? [
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`,
1727
+ `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
1728
  ]
983
1729
  : []),
984
1730
  ...(covers.length
@@ -986,6 +1732,29 @@ async function change(sub, slug, thing, value, options) {
986
1732
  `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
1733
  ]
988
1734
  : []),
1735
+ // Core writes a part's derived variables (a button's or card's radius
1736
+ // variable, read by what is drawn inside it) from plain declarations
1737
+ // only: in a state they keep the plain value, and the result says so.
1738
+ ...(sub === 'set' && s.state && s.on
1739
+ ? (() => {
1740
+ const prop =
1741
+ s.thing === 'corners' || /radius$/.test(s.thing)
1742
+ ? 'borderRadius'
1743
+ : s.thing === 'padding' || s.thing === 'spacing'
1744
+ ? 'padding'
1745
+ : s.thing.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
1746
+ const vars = parts.flatMap(t =>
1747
+ (ctx.derived?.[t] ?? [])
1748
+ .filter(d => d.property === prop)
1749
+ .flatMap(d => d.vars ?? []),
1750
+ );
1751
+ return vars.length
1752
+ ? [
1753
+ `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`,
1754
+ ]
1755
+ : [];
1756
+ })()
1757
+ : []),
989
1758
  // Phones keep the base theme's reading sizes (a coarse pointer below
990
1759
  // the lg width), so a size change says where it applies.
991
1760
  ...(sub === 'set' &&
@@ -1003,14 +1772,30 @@ async function change(sub, slug, thing, value, options) {
1003
1772
  // An exact property on the same part wins over a dial there.
1004
1773
  ...(exactOver
1005
1774
  ? [
1006
- `${describe(exactOver)} is an exact property and wins over ${s.thing} there, so this shows only after \`${P} undo ${slug} ${undoArgs(exactOver)}\``,
1775
+ ownPartHits.length
1776
+ ? `${describe(exactOver)} is an exact property and wins over ${s.thing} there too; undoing it does not make ${s.thing} show on ${[...new Set(ownPartHits.map(h => h.target))].join(', ')}, where ${slug}.theme.ts wins`
1777
+ : `${describe(exactOver)} is an exact property and wins over ${s.thing} there, so this shows only after \`${P} undo ${slug} ${undoArgs(exactOver)}\``,
1778
+ ]
1779
+ : []),
1780
+ // A whole-theme font under fonts set for each role shows only where no
1781
+ // role font is set.
1782
+ ...(roleOver.length
1783
+ ? [
1784
+ `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 ')}`,
1007
1785
  ]
1008
1786
  : []),
1009
1787
  // An accepted change that the theme already showed says so.
1010
1788
  ...(sub === 'set' &&
1011
1789
  !exactOver &&
1012
- // With the last build unreadable, nothing was compared.
1013
- !r.notes.some(n => n.includes('could not be read')) &&
1790
+ !roleOver.length &&
1791
+ !ownOverToken &&
1792
+ !ownPartHits.length &&
1793
+ // With the last build unreadable or missing, nothing was compared.
1794
+ !r.notes.some(
1795
+ n =>
1796
+ n.includes('could not be read') ||
1797
+ n.includes('there was no last build'),
1798
+ ) &&
1014
1799
  !r.unchanged &&
1015
1800
  !r.changed.length &&
1016
1801
  !styled.length &&
@@ -1019,6 +1804,23 @@ async function change(sub, slug, thing, value, options) {
1019
1804
  `this changes nothing you see: the theme already shows ${describe(s)} (it is saved, and stays when the base theme changes)`,
1020
1805
  ]
1021
1806
  : []),
1807
+ // A card's content takes one radius from Core, whatever its corners.
1808
+ ...(sub === 'set' &&
1809
+ s.source === 'property' &&
1810
+ s.thing === 'border-radius' &&
1811
+ s.on &&
1812
+ (ctx.derived?.[s.on] ?? []).some(
1813
+ d => d.property === 'borderRadius' && d.vars?.length,
1814
+ ) &&
1815
+ /\s|\//.test(String(s.value).trim())
1816
+ ? [
1817
+ `each corner of ${s.on} takes its own radius; the content that reaches its edges takes one, ${
1818
+ String(s.value)
1819
+ .trim()
1820
+ .split(/[\s/]+/)[0]
1821
+ }, for every corner (Core gives it a single radius)`,
1822
+ ]
1823
+ : []),
1022
1824
  ...(longhands.length
1023
1825
  ? [
1024
1826
  `${s.thing} comes after ${longhands.map(x => x.thing).join(', ')} on ${s.on}, so it replaces them there`,
@@ -1039,6 +1841,20 @@ async function change(sub, slug, thing, value, options) {
1039
1841
  : null
1040
1842
  : null;
1041
1843
  if (s.note) notes.push(s.note);
1844
+ // A token the theme's own source sets itself wins over what this dial
1845
+ // writes, as an exact setting does.
1846
+ const ownWins = ownSourceTokens(cwd, slug).filter(
1847
+ k =>
1848
+ (dialTokens.has(k) ||
1849
+ // A role font writes --font-family-<role>.
1850
+ (s.thing === 'font' && s.on && k === `--font-family-${s.on}`)) &&
1851
+ !exactWins.some(x => x.thing === k),
1852
+ );
1853
+ const ownSet = new Set(ownSourceTokens(cwd, slug));
1854
+ if (ownWins.length)
1855
+ notes.push(
1856
+ `${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; ${ownTakeOut(slug, s.thing, ownWins, data)}`,
1857
+ );
1042
1858
  if (PALETTE_DIALS.includes(s.thing) && sub === 'set')
1043
1859
  notes.push(
1044
1860
  ...paletteNotes(
@@ -1046,7 +1862,31 @@ async function change(sub, slug, thing, value, options) {
1046
1862
  s.thing,
1047
1863
  slug,
1048
1864
  modesOf(data),
1049
- ),
1865
+ )
1866
+ // A shade the mapping would pick for a token the theme's own source
1867
+ // sets never shows: the file's value does (named once above).
1868
+ .filter(n => {
1869
+ const subject = /^(?:in (?:light|dark), )?(--[a-z0-9-]+) /.exec(
1870
+ n,
1871
+ )?.[1];
1872
+ return (
1873
+ !subject ||
1874
+ !ownSet.has(subject) ||
1875
+ / uses your exact setting \(/.test(n)
1876
+ );
1877
+ })
1878
+ .map(n => {
1879
+ // The exact color is the one the theme's own source sets: named so.
1880
+ const token = n.split(' ')[0];
1881
+ return ownSet.has(token) && / uses your exact setting \(/.test(n)
1882
+ ? n
1883
+ .replace(
1884
+ ' uses your exact setting (',
1885
+ ` uses the value ${slug}.theme.ts sets (`,
1886
+ )
1887
+ .replace('an exact setting wins', 'your own source wins')
1888
+ : n;
1889
+ }),
1050
1890
  );
1051
1891
  // An exact color the mapping reads (a fill, a tint, text on a fill)
1052
1892
  // changes what it picks around it: say what, as the dial does.
@@ -1104,8 +1944,13 @@ async function change(sub, slug, thing, value, options) {
1104
1944
  if (s.thing === 'font' && sub === 'set')
1105
1945
  notes.unshift(...fontNotes(ctx, {...data, settings: [s]}));
1106
1946
  if (s.thing === 'type' || s.thing === 'headings')
1107
- for (const [m, why] of maskedSettings(data))
1947
+ for (const [m, why] of maskedSettings(data, ctx))
1108
1948
  notes.push(`${describe(m)}: ${why}`);
1949
+ // An earlier setting this one now covers (through a spread too) is named.
1950
+ else if (sub === 'set')
1951
+ for (const [m, why] of maskedSettings(data, ctx))
1952
+ if (m !== s && why.startsWith(describe(s)))
1953
+ notes.push(`${describe(m)} no longer shows: ${why}`);
1109
1954
  if (s.thing === 'type' && sub === 'set' && TYPE_STYLES[s.value].ratio > 1.2)
1110
1955
  notes.push(
1111
1956
  'text below the base size keeps its standard sizes, so small text stays readable',
@@ -1212,6 +2057,9 @@ export async function themeEditShow(theme, options = {}) {
1212
2057
  const section = checkSection(options.section, theme);
1213
2058
  const data = loadTheme(cwd, theme);
1214
2059
  const ctx = await context(cwd);
2060
+ // The app copy is written once show succeeds (at its end), never by a
2061
+ // build a later refusal puts back.
2062
+ holdAfterBuild(ctx);
1215
2063
  refuseStoredTokens(ctx, theme, data);
1216
2064
  // Without React, show still lists the settings and builds the theme, as
1217
2065
  // set does; only the pages, pictures and the checks that render are
@@ -1235,26 +2083,125 @@ export async function themeEditShow(theme, options = {}) {
1235
2083
  ? [installLine(cwd, ['react', 'react-dom'])]
1236
2084
  : // Two copies of React and other install problems are named by
1237
2085
  // doctor; the same show would fail the same way.
1238
- ['astryx doctor'],
2086
+ [`${getCliInvocation(cwd)} doctor`],
1239
2087
  },
1240
2088
  );
1241
2089
  const f = themeFiles(cwd, theme);
1242
2090
  // A build that does not match the settings (a command stopped mid-build,
1243
2091
  // a hand edit, another CLI) is made again from the settings, and said.
1244
- const stale = staleBuild(cwd, theme, data);
2092
+ // An own source that does not parse is refused before anything is
2093
+ // built, written or removed (the build would fail part way).
2094
+ if (!readOnly) refuseThemeParse(cwd, theme);
1245
2095
  const brokenSource = themeSourceProblem(cwd, theme);
1246
- if (stale && !brokenSource && !readOnly) await buildTheme(ctx, theme, data);
2096
+ // Every output, as `compile --check` reads them: one missing or edited by
2097
+ // hand is built again too.
2098
+ let stale = staleBuild(cwd, theme, data);
2099
+ // An own source changed since the editor's build, whose outputs a build
2100
+ // of it now makes as they are (it was compiled since): current, as
2101
+ // `compile --check` reads it, so the editor records the source it was
2102
+ // built with instead of building again. One rule for both.
2103
+ if (
2104
+ stale === sourceChangedReason(theme) &&
2105
+ !brokenSource &&
2106
+ !(await outputsDrift(ctx, theme))
2107
+ ) {
2108
+ if (!readOnly) refreshSourceStamp(cwd, theme);
2109
+ stale = readOnly ? stale : staleBuild(cwd, theme, data);
2110
+ }
2111
+ stale ||= brokenSource ? null : await outputsDrift(ctx, theme);
2112
+ // Every file the build may rewrite or remove (the settings module, the
2113
+ // built outputs, the variants types, section sheets, pictures), so a
2114
+ // theme source that does not build, or builds a value that is not text,
2115
+ // leaves the folder exactly as it was.
2116
+ // An output that was not there is recorded as absent (null), so putting
2117
+ // the folder back removes what the build made new; the palette files in
2118
+ // tokens/ are recorded the same way.
2119
+ /** @type {Map<string, Buffer | null>} */
2120
+ let kept = new Map();
2121
+ const tokensDir = path.join(f.dir, 'tokens');
2122
+ if (stale && !brokenSource && !readOnly) {
2123
+ kept = new Map(
2124
+ fs
2125
+ .readdirSync(f.dir)
2126
+ .filter(
2127
+ n =>
2128
+ n === path.basename(f.settingsTs) ||
2129
+ (n.startsWith(`${theme}.`) &&
2130
+ /\.(css|js|d\.ts|css\.d\.ts|variants\.d\.ts)$/.test(n)) ||
2131
+ /^(sheet-[a-z-]+\.html|(sheet|preview)(-[a-z-]+)?\.png)$/.test(n),
2132
+ )
2133
+ .map(n => [path.join(f.dir, n), fs.readFileSync(path.join(f.dir, n))]),
2134
+ );
2135
+ for (const n of [
2136
+ path.basename(f.settingsTs),
2137
+ `${theme}.css`,
2138
+ `${theme}.js`,
2139
+ `${theme}.d.ts`,
2140
+ `${theme}.css.d.ts`,
2141
+ `${theme}.variants.d.ts`,
2142
+ ])
2143
+ if (!kept.has(path.join(f.dir, n))) kept.set(path.join(f.dir, n), null);
2144
+ if (fs.existsSync(tokensDir))
2145
+ for (const n of fs.readdirSync(tokensDir)) {
2146
+ const file = path.join(tokensDir, n);
2147
+ if (fs.statSync(file).isFile()) kept.set(file, fs.readFileSync(file));
2148
+ }
2149
+ const refs = path.join(tokensDir, `${theme}.palette-refs.ts`);
2150
+ if (!kept.has(refs)) kept.set(refs, null);
2151
+ try {
2152
+ await buildTheme(ctx, theme, data);
2153
+ } catch (e) {
2154
+ putBack(kept, tokensDir);
2155
+ if (e instanceof AstryxError && e.code !== E.ERR_THEME_LOAD) throw e;
2156
+ // An own theme source that no longer builds is named, as `set` names
2157
+ // it; the old build is never shown as current.
2158
+ const why = (e instanceof Error ? e.message : String(e))
2159
+ .split(`${cwd}${path.sep}`)
2160
+ .join('')
2161
+ .replace(/\s*Make sure all imports[^|]*$/s, '')
2162
+ .split('\n')
2163
+ .slice(0, 3)
2164
+ .join(' | ');
2165
+ refuse(
2166
+ E.ERR_THEME_INVALID,
2167
+ `${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)` : ''}`,
2168
+ {run: [`${P} how --list dials`]},
2169
+ );
2170
+ }
2171
+ }
1247
2172
  // The settings loaded whole: a `new` marker beside them is stale.
1248
2173
  if (!readOnly) clearNewMarker(f.dir);
1249
2174
  // A built module that cannot be read (damaged by hand) is built again.
1250
2175
  /** @type {string | null} */
1251
2176
  let unreadable = null;
1252
2177
  const res = await resolvedTokens(ctx, theme).catch(async e => {
2178
+ if (
2179
+ e instanceof AstryxError &&
2180
+ e.code === E.ERR_THEME_INVALID &&
2181
+ kept.size
2182
+ ) {
2183
+ // What this show just built goes back with the refusal.
2184
+ putBack(kept, tokensDir);
2185
+ throw e;
2186
+ }
1253
2187
  if (e instanceof AstryxError || readOnly) throw e;
2188
+ // The source lines the settings need are missing too: the build cannot
2189
+ // be made again until they are back, and show says so (never a run of
2190
+ // show itself).
2191
+ if (brokenSource)
2192
+ refuse(
2193
+ E.ERR_THEME_INVALID,
2194
+ `${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.`,
2195
+ {
2196
+ run: [`cat ${quoteCommandArgument(shown(cwd, f.ts))}`],
2197
+ },
2198
+ );
1254
2199
  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
2200
  await buildTheme(ctx, theme, data);
1256
2201
  return resolvedTokens(ctx, theme);
1257
2202
  });
2203
+ const ownOverNotes = ownOverSettingNotes(cwd, theme, data);
2204
+ const ownMasked = ownOverNotes.map(n => n.slice(0, n.indexOf(': ')));
1258
2205
  const checked = await contrastProblems(ctx, data, res);
1259
2206
  // What cannot be measured is a note, not a problem.
1260
2207
  const problems = checked.filter(x => !x.startsWith('not checked'));
@@ -1265,13 +2212,40 @@ export async function themeEditShow(theme, options = {}) {
1265
2212
  await baseResolved(ctx.project, data.like),
1266
2213
  ctx.project.core.tokenDefaults,
1267
2214
  );
2215
+ // A render that fails here (two copies of React, a component that
2216
+ // throws) is refused as the one above: what this show built goes back,
2217
+ // and the result says so.
2218
+ const rendering = async (/** @type {() => Promise<any>} */ run) => {
2219
+ try {
2220
+ return await run();
2221
+ } catch (e) {
2222
+ if (!(e instanceof Error)) throw e;
2223
+ if (e instanceof AstryxError && e.code !== E.ERR_RENDER_FAILED) throw e;
2224
+ putBack(kept, tokensDir);
2225
+ return refuse(
2226
+ E.ERR_RENDER_FAILED,
2227
+ `${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.`,
2228
+ {run: [`${getCliInvocation(cwd)} doctor`]},
2229
+ );
2230
+ }
2231
+ };
1268
2232
  const preview = noPages
1269
2233
  ? shown(cwd, f.preview)
1270
- : await renderPreview(ctx, theme, data);
1271
- const previewStale = noPages ? [] : await keepPreviewRoute(ctx, theme);
2234
+ : await rendering(() => renderPreview(ctx, theme, data));
2235
+ const previewStale = noPages
2236
+ ? []
2237
+ : await rendering(() => keepPreviewRoute(ctx, theme));
1272
2238
  const sheet = noPages
1273
2239
  ? {file: shown(cwd, f.sheet), components: 0, skipped: []}
1274
- : await renderSheet(ctx, theme, data, {group: section});
2240
+ : await rendering(() => renderSheet(ctx, theme, data, {group: section}));
2241
+ // The full sheet records the build it shows, so a later change tells a
2242
+ // sheet that still matches (after an undo) from one that does not.
2243
+ if (!noPages)
2244
+ stampSheet(
2245
+ section ? path.join(f.dir, `sheet-${section}.html`) : f.sheet,
2246
+ theme,
2247
+ cwd,
2248
+ );
1275
2249
  const modes = modesOf(data);
1276
2250
  const shots =
1277
2251
  png && !noPages
@@ -1290,16 +2264,46 @@ export async function themeEditShow(theme, options = {}) {
1290
2264
  modes,
1291
2265
  )
1292
2266
  : {files: [], problem: null};
2267
+ // The app copy follows the build there now, also when the build was
2268
+ // current and only the copy is missing (a theme made before it existed).
2269
+ if (!readOnly)
2270
+ try {
2271
+ writeAppCopy(ctx, theme, data);
2272
+ } catch (e) {
2273
+ if (/** @type {any} */ (e)?.lockLost) throw e;
2274
+ }
1293
2275
  return {
1294
2276
  type: 'themeEdit.show',
1295
2277
  data: {
1296
2278
  theme,
1297
2279
  like: data.like ?? null,
1298
2280
  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
- }),
2281
+ settings: await (async () => {
2282
+ const looksBase = await baseResolved(ctx.project, data.like).catch(
2283
+ () => null,
2284
+ );
2285
+ return data.settings.map(s => {
2286
+ let masked = maskedSettings(data, ctx).get(s);
2287
+ // A look dial (buttons, surfaces) under an exact property on a
2288
+ // part it writes: named, as corners under border-radius is.
2289
+ if (!masked && looksBase && s.source === 'dial' && !s.on) {
2290
+ const writes = dialWrites(ctx, data, s, looksBase);
2291
+ const exact = writes.size
2292
+ ? data.settings.find(
2293
+ x =>
2294
+ x.source === 'property' &&
2295
+ x.on &&
2296
+ !x.when &&
2297
+ !x.state &&
2298
+ partsOf(ctx, x).some(t => writes.has(`${t}\0${x.thing}`)),
2299
+ )
2300
+ : undefined;
2301
+ if (exact)
2302
+ masked = `${describe(exact)} is an exact property and wins over ${s.thing} on ${exact.on}`;
2303
+ }
2304
+ return {...s, parts: partsOf(ctx, s), ...(masked ? {masked} : {})};
2305
+ });
2306
+ })(),
1303
2307
  notes: [
1304
2308
  ...(noReact
1305
2309
  ? [
@@ -1310,19 +2314,38 @@ export async function themeEditShow(theme, options = {}) {
1310
2314
  ? [
1311
2315
  `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
2316
  ]
1313
- : stale
2317
+ : stale && !brokenSource
1314
2318
  ? [
1315
- `the build did not match ${theme}.settings.json (${stale}), so it was built again from the settings`,
2319
+ `the build was not current (${stale}), so it was built again from the settings`,
1316
2320
  ]
1317
- : []),
2321
+ : stale
2322
+ ? [
2323
+ `the build is not current (${stale}), and it was not built again: the theme source cannot carry the settings`,
2324
+ ]
2325
+ : []),
1318
2326
  ...(unreadable ? [unreadable] : []),
1319
2327
  ...(brokenSource
1320
2328
  ? [
1321
- `${brokenSource}, so settings cannot take effect; put back the import, extends and name lines in ${theme}.theme.ts`,
2329
+ `${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
2330
  ]
1323
2331
  : []),
1324
- ...checked.filter(x => x.startsWith('not checked')),
2332
+ // A setting the theme file wins over is not live: no contrast
2333
+ // caveat for it (its own note says it does not show).
2334
+ ...checked.filter(
2335
+ x =>
2336
+ x.startsWith('not checked') &&
2337
+ !ownMasked.some(d => x.includes(` for ${d},`)),
2338
+ ),
1325
2339
  ...fontNotes(ctx, data),
2340
+ ...ownSourceMaskNotes(
2341
+ ctx,
2342
+ cwd,
2343
+ theme,
2344
+ data,
2345
+ await baseResolved(ctx.project, data.like),
2346
+ ),
2347
+ ...ownOverNotes,
2348
+ ...ownPhoneNotes(cwd, theme, data),
1326
2349
  ],
1327
2350
  // A size, number or font is the same in both modes: one value.
1328
2351
  resolved: Object.fromEntries(
@@ -1339,7 +2362,7 @@ export async function themeEditShow(theme, options = {}) {
1339
2362
  res,
1340
2363
  modes[0],
1341
2364
  ),
1342
- ...colorsReport(pal, data),
2365
+ ...colorsReport(pal, data, res, theme),
1343
2366
  problems,
1344
2367
  preview,
1345
2368
  previewStale,
@@ -1348,11 +2371,51 @@ export async function themeEditShow(theme, options = {}) {
1348
2371
  skipped: sheet.skipped,
1349
2372
  pictures: shots.files,
1350
2373
  pictureProblem: shots.problem,
2374
+ // How to use the theme in this app: theme add <theme> for its app copy.
2375
+ wiring: appWiring(ctx, theme, data),
2376
+ ...(() => {
2377
+ // The first time the theme's app copy is written, its files.
2378
+ const wrote = takeFirstAppCopy(cwd, theme);
2379
+ return wrote ? {appCopy: {wrote}} : {};
2380
+ })(),
1351
2381
  colorFiles: pal ? colorFiles(theme) : null,
1352
2382
  },
1353
2383
  };
1354
2384
  }
1355
2385
 
2386
+ /**
2387
+ * The part properties a dial writes, read from what the build writes with
2388
+ * it and without it (so a dial's outputs are never listed by hand), as
2389
+ * `target\0css-property` keys.
2390
+ * @param {import('./_settings.mjs').Ctx} ctx
2391
+ * @param {import('./_settings.mjs').ThemeData} data
2392
+ * @param {import('./_settings.mjs').Setting} dial
2393
+ * @param {{light: Record<string, string>, dark: Record<string, string>}} base
2394
+ * @returns {Set<string>}
2395
+ */
2396
+ function dialWrites(ctx, data, dial, base) {
2397
+ /** @type {Set<string>} */
2398
+ const out = new Set();
2399
+ const comps = (/** @type {import('./_settings.mjs').Setting[]} */ settings) =>
2400
+ /** @type {Record<string, Record<string, Record<string, unknown>>>} */ (
2401
+ compileTheme(ctx, {...data, settings}, base).components ?? {}
2402
+ );
2403
+ let plain;
2404
+ let withDial;
2405
+ try {
2406
+ plain = comps([]);
2407
+ withDial = comps([dial]);
2408
+ } catch {
2409
+ return out;
2410
+ }
2411
+ for (const [target, keys] of Object.entries(withDial))
2412
+ for (const [key, block] of Object.entries(keys ?? {}))
2413
+ for (const [prop, value] of Object.entries(block ?? {}))
2414
+ if (typeof value === 'string' && plain[target]?.[key]?.[prop] !== value)
2415
+ out.add(`${target}\0${kebab(prop)}`);
2416
+ return out;
2417
+ }
2418
+
1356
2419
  /**
1357
2420
  * What applies once `removed` is gone: a whole-theme setting of the same
1358
2421
  * thing for a part setting, a dial that still writes the token, or the
@@ -1364,6 +2427,44 @@ export async function themeEditShow(theme, options = {}) {
1364
2427
  * @returns {string}
1365
2428
  */
1366
2429
  function nowApplies(ctx, data, removed, base) {
2430
+ // A token the theme's own source sets shows its value, whatever else
2431
+ // the settings give it.
2432
+ if (removed.source === 'token' && !removed.on && !removed.when) {
2433
+ const own = ownSourceTokenValues(ctx.project.cwd, data.name)[removed.thing];
2434
+ if (own != null)
2435
+ return `${removed.thing} = ${own} (set in ${data.name}.theme.ts)`;
2436
+ }
2437
+ // On a part, the same for what the own source sets on that part's rule.
2438
+ if (
2439
+ (removed.source === 'token' || removed.source === 'property') &&
2440
+ removed.on
2441
+ ) {
2442
+ const own = ownPartTokens(
2443
+ ctx.project.cwd,
2444
+ data.name,
2445
+ removed.on,
2446
+ removed.when ?? 'base',
2447
+ removed.state ? `:${removed.state}` : null,
2448
+ );
2449
+ if (own.has(removed.thing))
2450
+ return `${removed.thing} = ${own.get(removed.thing) ?? 'its value'} on ${removed.on}${removed.state ? ` :${removed.state}` : ''}${removed.when ? ` when ${removed.when}` : ''} (set in ${data.name}.theme.ts)`;
2451
+ }
2452
+ // A role font removed under an exact --font-family-<role>: that token is
2453
+ // what shows there.
2454
+ if (
2455
+ removed.thing === 'font' &&
2456
+ removed.on &&
2457
+ FONT_ROLES.includes(removed.on)
2458
+ ) {
2459
+ const exact = data.settings.find(
2460
+ x =>
2461
+ x.source === 'token' &&
2462
+ !x.on &&
2463
+ !x.when &&
2464
+ x.thing === `--font-family-${removed.on}`,
2465
+ );
2466
+ if (exact) return describe(exact);
2467
+ }
1367
2468
  // A token a dial still writes (an accent color feeds --color-accent):
1368
2469
  // name that dial.
1369
2470
  if (removed.source === 'token' && !removed.on) {
@@ -1387,21 +2488,35 @@ function nowApplies(ctx, data, removed, base) {
1387
2488
  // exact property on the part that this dial would have competed with.
1388
2489
  if (removed.on) {
1389
2490
  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
- );
2491
+ // The part's or its group's setting for the same variant and state
2492
+ // first (a group's hover after the part's hover goes), then a plain one.
2493
+ /** @param {(x: import('./_settings.mjs').Setting) => boolean} scoped */
2494
+ const find = scoped =>
2495
+ [...data.settings]
2496
+ .reverse()
2497
+ .find(
2498
+ x =>
2499
+ x.thing === removed.thing &&
2500
+ x !== removed &&
2501
+ (!x.mode || x.mode === removed.mode) &&
2502
+ (x.on === removed.on || (fam != null && x.on === fam)) &&
2503
+ scoped(x),
2504
+ );
2505
+ const reaches =
2506
+ (removed.when || removed.state
2507
+ ? find(
2508
+ x =>
2509
+ (x.when ?? '') === (removed.when ?? '') &&
2510
+ (x.state ?? '') === (removed.state ?? ''),
2511
+ )
2512
+ : undefined) ?? find(x => !x.when && !x.state);
1400
2513
  if (reaches) return describe(reaches);
1401
- const DIAL_PROPERTY = /** @type {Record<string, RegExp>} */ ({
1402
- corners: /radius$/,
1403
- spacing: /^(padding|gap)(-|$)/,
1404
- });
2514
+ const DIAL_PROPERTY = wordTable(
2515
+ /** @type {Record<string, RegExp>} */ ({
2516
+ corners: /radius$/,
2517
+ spacing: /^(padding|gap)(-|$)/,
2518
+ }),
2519
+ );
1405
2520
  const exact =
1406
2521
  removed.source === 'dial' && DIAL_PROPERTY[removed.thing]
1407
2522
  ? data.settings.find(
@@ -1412,8 +2527,25 @@ function nowApplies(ctx, data, removed, base) {
1412
2527
  )
1413
2528
  : null;
1414
2529
  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.
2530
+ // A removed exact property leaves the dial whose build writes it there
2531
+ // (buttons, surfaces: read from the build), on the part, its group, or
2532
+ // the whole theme.
2533
+ if (removed.source === 'property') {
2534
+ const targets = partsOf(ctx, removed);
2535
+ const writer = [...data.settings].reverse().find(
2536
+ x =>
2537
+ x.source === 'dial' &&
2538
+ x !== removed &&
2539
+ (!x.on || x.on === removed.on || (fam != null && x.on === fam)) &&
2540
+ (x.when ?? '') === (removed.when ?? '') &&
2541
+ (x.state ?? '') === (removed.state ?? '') &&
2542
+ [...dialWrites(ctx, data, x, base)].some(k => {
2543
+ const [t, prop] = k.split('\0');
2544
+ return targets.includes(t) && prop === removed.thing;
2545
+ }),
2546
+ );
2547
+ if (writer) return describe(writer);
2548
+ }
1417
2549
  if (removed.source === 'property') {
1418
2550
  const dial = Object.entries(DIAL_PROPERTY).find(([, re]) =>
1419
2551
  re.test(removed.thing),
@@ -1469,6 +2601,169 @@ function otherModeNotes(data) {
1469
2601
  ];
1470
2602
  }
1471
2603
 
2604
+ /**
2605
+ * The tokens a whole-theme dial setting writes: those that differ between
2606
+ * the theme's dials with it and without it (a font role's family, and every
2607
+ * text size when the scale moves).
2608
+ * @param {import('./_settings.mjs').Ctx} ctx
2609
+ * @param {import('./_settings.mjs').ThemeData} data
2610
+ * @param {import('./_settings.mjs').Setting} s
2611
+ * @param {any} base
2612
+ * @returns {Set<string>}
2613
+ */
2614
+ function dialTouched(ctx, data, s, base) {
2615
+ /** @param {import('./_settings.mjs').Setting[]} list */
2616
+ const dialsOnly = list => ({
2617
+ ...data,
2618
+ settings: list.filter(x => x.source === 'dial'),
2619
+ });
2620
+ const withDial = compileTheme(ctx, dialsOnly(data.settings), base);
2621
+ const without = compileTheme(
2622
+ ctx,
2623
+ dialsOnly(data.settings.filter(x => x !== s)),
2624
+ base,
2625
+ );
2626
+ const differs = (/** @type {unknown} */ a, /** @type {unknown} */ b) =>
2627
+ JSON.stringify(a) !== JSON.stringify(b);
2628
+ const touched = new Set(
2629
+ [
2630
+ ...Object.keys(withDial.tokens ?? {}),
2631
+ ...Object.keys(without.tokens ?? {}),
2632
+ ].filter(k => differs(withDial.tokens?.[k], without.tokens?.[k])),
2633
+ );
2634
+ for (const r of FONT_ROLES)
2635
+ if (differs(withDial.typography?.[r], without.typography?.[r]))
2636
+ touched.add(`--font-family-${r}`);
2637
+ // The type scale feeds every font size and every role size (body,
2638
+ // headings, labels): an exact one of those keeps its text as it is.
2639
+ if (differs(withDial.typography?.scale, without.typography?.scale))
2640
+ for (const k of Object.keys(ctx.project.core.tokenDefaults ?? {}))
2641
+ if (/^--(font-size-|text-[a-z0-9-]+-size$)/.test(k)) touched.add(k);
2642
+ return touched;
2643
+ }
2644
+
2645
+ /**
2646
+ * The family and weight tokens the theme's own source sets as plain tokens
2647
+ * that phones do not show: on top of a base theme, its rule for those
2648
+ * screens sets its type again (a rule wins over plain tokens, by Core's
2649
+ * contract), unless an exact setting is repeated after it. The note names
2650
+ * the fix within that contract: the theme's typography, or a same-screens
2651
+ * rule.
2652
+ * @param {string} cwd
2653
+ * @param {string} slug
2654
+ * @param {import('./_settings.mjs').ThemeData} data
2655
+ * @returns {string[]}
2656
+ */
2657
+ function ownPhoneNotes(cwd, slug, data) {
2658
+ if (!data.like) return [];
2659
+ const exact = new Set(
2660
+ data.settings
2661
+ .filter(x => x.source === 'token' && !x.on && !x.when && !x.state)
2662
+ .map(x => x.thing),
2663
+ );
2664
+ const lost = ownSourceTokens(cwd, slug).filter(
2665
+ k => PHONE_TYPE.test(k) && !exact.has(k),
2666
+ );
2667
+ if (!lost.length) return [];
2668
+ const families = lost.filter(k => /^--font-family-/.test(k));
2669
+ const role =
2670
+ /^--font-family-([a-z]+)$/.exec(families[0] ?? '')?.[1] ?? 'body';
2671
+ return [
2672
+ `on ${PHONES}, the base theme's type shows for ${lost.slice(0, 4).join(', ')}${lost.length > 4 ? ` and ${lost.length - 4} more` : ''}, which ${slug}.theme.ts sets as plain tokens: the base theme's rule for those screens sets its type again, and a rule wins over plain tokens there. To keep yours on every screen, set ${lost.length > 1 ? 'them' : 'it'} on the theme's typography in ${slug}.theme.ts (such as typography: {${role}: {family: ...}}, which that rule then keeps), or in a rule for the same screens`,
2673
+ ];
2674
+ }
2675
+
2676
+ /**
2677
+ * Notes for the exact settings the theme's own source sets itself (a
2678
+ * whole-theme token, or a token or property on a part's plain or variant
2679
+ * rule): the file's value shows, not the setting.
2680
+ * @param {string} cwd
2681
+ * @param {string} slug
2682
+ * @param {import('./_settings.mjs').ThemeData} data
2683
+ * @returns {string[]}
2684
+ */
2685
+ function ownOverSettingNotes(cwd, slug, data) {
2686
+ const top = ownSourceTokenValues(cwd, slug);
2687
+ const topKeys = new Set(ownSourceTokens(cwd, slug));
2688
+ /** @type {Map<string, Map<string, string | null>>} */
2689
+ const parts = new Map();
2690
+ /** @type {string[]} */
2691
+ const out = [];
2692
+ for (const x of data.settings) {
2693
+ if (x.source !== 'token' && x.source !== 'property') continue;
2694
+ if (!x.on) {
2695
+ if (x.source === 'token' && !x.when && topKeys.has(x.thing))
2696
+ out.push(
2697
+ `${describe(x)}: ${slug}.theme.ts sets ${x.thing} itself${top[x.thing] != null ? ` (${top[x.thing]})` : ''}, so this setting does not show${PHONE_TYPE.test(x.thing) ? ` on wide screens (on ${PHONES} it does: the editor repeats exact font settings there)` : ''}`,
2698
+ );
2699
+ continue;
2700
+ }
2701
+ const state = x.state ? `:${x.state}` : null;
2702
+ const key = `${x.on}\0${x.when ?? 'base'}\0${state ?? ''}`;
2703
+ if (!parts.has(key))
2704
+ parts.set(key, ownPartTokens(cwd, slug, x.on, x.when ?? 'base', state));
2705
+ const own = /** @type {Map<string, string | null>} */ (parts.get(key));
2706
+ if (own.has(x.thing))
2707
+ out.push(
2708
+ `${describe(x)}: ${slug}.theme.ts sets ${x.thing} on ${x.on}${state ? ` ${state}` : ''}${x.when ? ` when ${x.when}` : ''} itself${own.get(x.thing) != null ? ` (${own.get(x.thing)})` : ''}, so this setting does not show there`,
2709
+ );
2710
+ }
2711
+ return out;
2712
+ }
2713
+
2714
+ /** Phones, as the base themes' type rule names them. */
2715
+ const PHONES = 'phones (touch screens below 1024px)';
2716
+
2717
+ /**
2718
+ * What taking tokens out of the theme file lets show: the dial, or an
2719
+ * exact setting of a token first (file > exact > dial), with its undo.
2720
+ * @param {string} slug
2721
+ * @param {string} dial the dial's name
2722
+ * @param {string[]} tokens
2723
+ * @param {import('./_settings.mjs').ThemeData} data
2724
+ */
2725
+ function ownTakeOut(slug, dial, tokens, data) {
2726
+ const it = tokens.length > 1 ? 'them' : 'it';
2727
+ const exact = data.settings.filter(
2728
+ x =>
2729
+ x.source === 'token' &&
2730
+ !x.on &&
2731
+ !x.when &&
2732
+ !x.state &&
2733
+ tokens.includes(x.thing),
2734
+ );
2735
+ if (!exact.length)
2736
+ return `take ${it} out of ${slug}.theme.ts to let ${dial} set ${it}`;
2737
+ return `taking ${it} out of ${slug}.theme.ts shows your exact ${exact.map(describe).join(', ')}, which win${exact.length > 1 ? '' : 's'} over ${dial}; after that, ${exact.map(x => `\`${P} undo ${slug} ${undoArgs(x)}\``).join(' and ')} lets ${dial} set ${it}`;
2738
+ }
2739
+
2740
+ /**
2741
+ * Notes for the tokens the theme's own source sets that a whole-theme dial
2742
+ * also writes: the source wins, so the dial does not change them.
2743
+ * @param {import('./_settings.mjs').Ctx} ctx
2744
+ * @param {string} cwd
2745
+ * @param {string} slug
2746
+ * @param {import('./_settings.mjs').ThemeData} data
2747
+ * @param {any} base
2748
+ * @returns {string[]}
2749
+ */
2750
+ function ownSourceMaskNotes(ctx, cwd, slug, data, base) {
2751
+ const own = ownSourceTokens(cwd, slug);
2752
+ if (!own.length) return [];
2753
+ /** @type {string[]} */
2754
+ const notes = [];
2755
+ for (const s of data.settings) {
2756
+ if (s.source !== 'dial' || s.on || s.when || s.state) continue;
2757
+ const touched = dialTouched(ctx, data, s, base);
2758
+ const wins = own.filter(k => touched.has(k));
2759
+ if (wins.length)
2760
+ notes.push(
2761
+ `${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'}; ${ownTakeOut(slug, s.thing, wins, data)}`,
2762
+ );
2763
+ }
2764
+ return notes;
2765
+ }
2766
+
1472
2767
  /**
1473
2768
  * Each corners or spacing dial set on a part or group, with what its parts
1474
2769
  * get, beside the whole-theme value: `corners large on containers ->
@@ -1481,7 +2776,7 @@ function otherModeNotes(data) {
1481
2776
  * @returns {string[]}
1482
2777
  */
1483
2778
  function partValues(ctx, data, res, mode) {
1484
- const masked = maskedSettings(data);
2779
+ const masked = maskedSettings(data, ctx);
1485
2780
  return data.settings
1486
2781
  .filter(
1487
2782
  s =>
@@ -1554,9 +2849,13 @@ function partValues(ctx, data, res, mode) {
1554
2849
  * says so), and the contrast moves behind the shade choices.
1555
2850
  * @param {import('./_palette.mjs').PaletteMapping | null} pal
1556
2851
  * @param {import('./_settings.mjs').ThemeData} data
2852
+ * @param {Record<'light' | 'dark', Record<string, string>>} [built] the
2853
+ * built theme's resolved values: where one differs from the generated
2854
+ * shade with no exact setting, the theme's own source changed it
2855
+ * @param {string} [slug]
1557
2856
  * @returns {{vibrancy: number | null, colors: import('./theme-edit.type.mjs').ThemeEditColor[], colorNotes: string[]}}
1558
2857
  */
1559
- function colorsReport(pal, data) {
2858
+ function colorsReport(pal, data, built, slug = '') {
1560
2859
  if (!pal) return {vibrancy: null, colors: [], colorNotes: []};
1561
2860
  /** What the user set for each token exactly, in each mode. */
1562
2861
  const exactBy =
@@ -1566,6 +2865,19 @@ function colorsReport(pal, data) {
1566
2865
  for (const m of s.mode ? [s.mode] : ['light', 'dark'])
1567
2866
  (exactBy[s.thing] ??= {})[/** @type {'light' | 'dark'} */ (m)] =
1568
2867
  s.value;
2868
+ /** Tokens the theme's own source sets to another value than generated. */
2869
+ const ownBy =
2870
+ /** @type {Record<string, {light?: string, dark?: string}>} */ ({});
2871
+ for (const [k, v] of Object.entries(pal.tokens))
2872
+ for (const m of /** @type {const} */ (['light', 'dark'])) {
2873
+ const now = built?.[m]?.[k];
2874
+ if (
2875
+ now &&
2876
+ !exactBy[k]?.[m] &&
2877
+ now.trim().toLowerCase() !== String(v[m].color).trim().toLowerCase()
2878
+ )
2879
+ (ownBy[k] ??= {})[m] = now;
2880
+ }
1569
2881
  /** @param {import('./_palette.mjs').StopRef} r */
1570
2882
  const shade = r =>
1571
2883
  r.family === 'black' || r.family === 'white'
@@ -1587,12 +2899,14 @@ function colorsReport(pal, data) {
1587
2899
  k,
1588
2900
  // Each mode says what it shows: the exact setting where one is
1589
2901
  // made for it, else the generated shade.
1590
- exactBy[k]
2902
+ exactBy[k] || ownBy[k]
1591
2903
  ? modes
1592
2904
  .map(m =>
1593
- exactBy[k][m] != null
2905
+ exactBy[k]?.[m] != null
1594
2906
  ? `${m} ${exactBy[k][m]} (your exact setting wins over the generated ${shade(v[m])})`
1595
- : `${m} ${shade(v[m])}`,
2907
+ : ownBy[k]?.[m] != null
2908
+ ? `${m} ${ownBy[k][m]} (your change in ${slug}.theme.ts wins over the generated ${shade(v[m])})`
2909
+ : `${m} ${shade(v[m])}`,
1596
2910
  )
1597
2911
  .join(', ')
1598
2912
  : shades(v),
@@ -1600,9 +2914,22 @@ function colorsReport(pal, data) {
1600
2914
  ),
1601
2915
  })),
1602
2916
  colorNotes: [
1603
- ...pal.notes,
2917
+ // A note about a token the theme's own source changed is dropped:
2918
+ // what it says no longer holds.
2919
+ ...pal.notes.filter(
2920
+ n =>
2921
+ !Object.keys(ownBy).some(k =>
2922
+ new RegExp(`${k.replace(/[-]/g, '\\-')}(?![\\w-])`).test(n),
2923
+ ),
2924
+ ),
1604
2925
  ...pal.contrast
1605
2926
  .filter(c => modes.includes(c.mode))
2927
+ // A pairing the theme's own source changed no longer holds.
2928
+ .filter(
2929
+ c =>
2930
+ !ownBy[c.token]?.[/** @type {'light' | 'dark'} */ (c.mode)] &&
2931
+ !ownBy[c.against]?.[/** @type {'light' | 'dark'} */ (c.mode)],
2932
+ )
1606
2933
  .filter(c => c.note || !c.pass || c.stop !== c.preferred)
1607
2934
  .map(c =>
1608
2935
  c.note
@@ -1611,7 +2938,12 @@ function colorsReport(pal, data) {
1611
2938
  ? `${c.token} ${c.mode}: shade ${c.stop}, not ${c.preferred}, so it reads at ${c.ratio}:1 on ${c.against}`
1612
2939
  : `${c.token} ${c.mode}: only ${c.ratio}:1 on ${c.against} at shade ${c.stop} (needs ${c.needs}:1)`,
1613
2940
  ),
1614
- ],
2941
+ ].filter(
2942
+ n =>
2943
+ !Object.keys(ownBy).some(k =>
2944
+ new RegExp(`${k.replace(/[-]/g, '\\-')}(?![\\w-])`).test(n),
2945
+ ),
2946
+ ),
1615
2947
  };
1616
2948
  }
1617
2949
 
@@ -1640,7 +2972,16 @@ export async function themeEditUndo(theme, options = {}) {
1640
2972
  if (thing === 'base' || thing === 'mode') {
1641
2973
  requireProject(cwd);
1642
2974
  const now = loadTheme(cwd, theme, thing);
1643
- const [first] = readHistory(themeFiles(cwd, theme).history).steps;
2975
+ const historyFile = themeFiles(cwd, theme).history;
2976
+ const {steps, dropped} = readHistory(historyFile);
2977
+ const [first] = steps;
2978
+ // `new` writes no history: with none, no change is saved (a new theme,
2979
+ // or a history deleted). An empty one is every step undone, back to how
2980
+ // the theme was made. A full one may have lost its oldest steps.
2981
+ const noHistory = !fs.existsSync(historyFile);
2982
+ const reachesStart =
2983
+ (steps.length > 0 && steps.length < HISTORY_STEPS) ||
2984
+ (!noHistory && steps.length === 0 && dropped === 0);
1644
2985
  /** @type {any} */
1645
2986
  let made = now;
1646
2987
  try {
@@ -1650,10 +2991,24 @@ export async function themeEditUndo(theme, options = {}) {
1650
2991
  }
1651
2992
  const of = (/** @type {any} */ d) =>
1652
2993
  thing === 'base' ? (d?.like ?? 'none') : (d?.mode ?? 'both');
2994
+ // A step in between that had another value: changed and changed back.
2995
+ const changedBack = steps.some(step => {
2996
+ try {
2997
+ return of(JSON.parse(step.replace(/^\uFEFF/, ''))) !== of(now);
2998
+ } catch {
2999
+ return false;
3000
+ }
3001
+ });
1653
3002
  if (of(made) === of(now))
1654
3003
  refuse(
1655
3004
  E.ERR_THEME_NOT_SET,
1656
- `${thing} was never changed: it is ${of(now)}, as ${theme} was made.`,
3005
+ reachesStart && changedBack
3006
+ ? `${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.`
3007
+ : reachesStart
3008
+ ? `${thing} was never changed: it is ${of(now)}, as ${theme} was made.`
3009
+ : noHistory
3010
+ ? `${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.`
3011
+ : `${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
3012
  {run: [`${P} show ${theme}`]},
1658
3013
  );
1659
3014
  return change('set', theme, thing, of(made), options);
@@ -1695,6 +3050,12 @@ export async function themeEditUndo(theme, options = {}) {
1695
3050
  // entry replaces it without the current file being read.
1696
3051
  /** @type {import('./_settings.mjs').ThemeData | null} */
1697
3052
  let current = null;
3053
+ // A file in the theme that is a folder or cannot be read is named first;
3054
+ // the damaged-settings path below never sees it.
3055
+ if (slugOk(theme)) refuseUnreadableFiles(cwd, theme);
3056
+ // A link in the theme is refused as set refuses it, never read as an
3057
+ // empty history.
3058
+ if (slugOk(theme)) refuseLinks(cwd, theme);
1698
3059
  try {
1699
3060
  current = loadTheme(cwd, theme);
1700
3061
  } catch (e) {
@@ -1707,7 +3068,7 @@ export async function themeEditUndo(theme, options = {}) {
1707
3068
  E.ERR_THEME_INVALID,
1708
3069
  `${theme}.history.json is damaged, so there is no step to go back to.`,
1709
3070
  {
1710
- fix: `delete ${shown(cwd, f.history)}: the next change starts a new history, and your settings stay as they are`,
3071
+ 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
3072
  run: [`${P} show ${theme}`],
1712
3073
  },
1713
3074
  );
@@ -1783,13 +3144,35 @@ export async function themeEditUndo(theme, options = {}) {
1783
3144
  E.ERR_THEME_INVALID,
1784
3145
  `The settings before the last change, in ${theme}.history.json, are damaged: ${still}.`,
1785
3146
  {
1786
- fix: `delete ${shown(cwd, f.history)}: the next change starts a new history, and your settings stay as they are`,
3147
+ 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
3148
  run: [`${P} show ${theme}`],
1788
3149
  },
1789
3150
  );
1790
3151
  prev = repaired.data;
1791
3152
  leftOut = repaired.dropped;
1792
3153
  }
3154
+ // The checks that need this Core too (a token's type, a part, a state,
3155
+ // a name that is no token or property): what they refuse is left out of
3156
+ // the step, with the same note, so the build stays valid.
3157
+ {
3158
+ const bad = new Set(storedProblems(ctx, theme, prev).map(p => p.setting));
3159
+ if (bad.size) {
3160
+ leftOut = [...leftOut, ...prev.settings.filter(s => bad.has(s))];
3161
+ prev = {...prev, settings: prev.settings.filter(s => !bad.has(s))};
3162
+ }
3163
+ }
3164
+ // The steps a later undo can still go back to: one equal to the settings
3165
+ // it would leave (a step this undo left a setting out of may then equal
3166
+ // the next one) is skipped, as undo skips it.
3167
+ let stepsLeft = 0;
3168
+ {
3169
+ let at = JSON.stringify(prev);
3170
+ for (let i = history.length - 1; i >= 0; i--)
3171
+ if (!same(history[i], at)) {
3172
+ stepsLeft++;
3173
+ at = history[i];
3174
+ }
3175
+ }
1793
3176
  // The popped history is written with the change, inside its rollback.
1794
3177
  const committed = await commitTheme(ctx, theme, prev, {
1795
3178
  history: false,
@@ -1833,7 +3216,7 @@ export async function themeEditUndo(theme, options = {}) {
1833
3216
  action: 'step',
1834
3217
  undone,
1835
3218
  settings: prev.settings.length,
1836
- stepsLeft: history.length,
3219
+ stepsLeft: stepsLeft,
1837
3220
  // What the step back changed, as a change reports it.
1838
3221
  changedTokens: committed.changed,
1839
3222
  problems: committed.problems,