@astryxdesign/cli 0.7.15 → 0.7.16-canary.g07c77c0

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 (159) 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 +17 -0
  8. package/api/doctor/_adapter.mjs +43 -0
  9. package/api/doctor/built-checks.mjs +1 -1
  10. package/api/doctor/doctor.mjs +18 -4
  11. package/api/doctor/theme-checks.mjs +1 -1
  12. package/api/integration/add-contribution.mjs +3 -3
  13. package/api/integration/pack-check.mjs +14 -8
  14. package/api/integration/validate-integration.mjs +1 -1
  15. package/api/search/_adapter.mjs +15 -16
  16. package/api/search/_entries.d.mts +2 -1
  17. package/api/search/_entries.mjs +28 -1
  18. package/api/swizzle/_moduleGraph.mjs +1 -1
  19. package/api/theme/_adapter.d.mts +5 -2
  20. package/api/theme/_adapter.mjs +43 -12
  21. package/api/theme/_fork.mjs +1 -1
  22. package/api/theme/build/build.d.mts +116 -32
  23. package/api/theme/build/build.mjs +449 -102
  24. package/api/theme/eject/eject.mjs +22 -1
  25. package/api/theme/template/template.d.mts +19 -0
  26. package/api/theme/template/template.mjs +102 -25
  27. package/api/theme/theme.type.d.mts +5 -1
  28. package/api/theme/theme.type.mjs +2 -1
  29. package/api/theme/themeBuild.doc.mjs +3 -3
  30. package/api/theme/themeEject.doc.mjs +1 -1
  31. package/api/theme/themeTemplate.doc.mjs +9 -3
  32. package/api/theme-edit/_adapter.d.mts +32 -2
  33. package/api/theme-edit/_adapter.mjs +213 -36
  34. package/api/theme-edit/_check.d.mts +69 -3
  35. package/api/theme-edit/_check.mjs +1517 -218
  36. package/api/theme-edit/_color.d.mts +2 -8
  37. package/api/theme-edit/_color.mjs +292 -219
  38. package/api/theme-edit/_compiler.d.mts +1 -0
  39. package/api/theme-edit/_compiler.mjs +20 -1
  40. package/api/theme-edit/_context.d.mts +29 -0
  41. package/api/theme-edit/_context.mjs +426 -40
  42. package/api/theme-edit/_css.d.mts +60 -1
  43. package/api/theme-edit/_css.mjs +404 -28
  44. package/api/theme-edit/_edit.d.mts +9 -0
  45. package/api/theme-edit/_edit.mjs +1300 -135
  46. package/api/theme-edit/_how-commands.d.mts +11 -26
  47. package/api/theme-edit/_how-commands.mjs +30 -2
  48. package/api/theme-edit/_how-question.d.mts +7 -0
  49. package/api/theme-edit/_how-question.mjs +1304 -176
  50. package/api/theme-edit/_how.mjs +144 -30
  51. package/api/theme-edit/_overview.mjs +2 -0
  52. package/api/theme-edit/_palette.d.mts +11 -0
  53. package/api/theme-edit/_palette.mjs +194 -65
  54. package/api/theme-edit/_parts.d.mts +33 -0
  55. package/api/theme-edit/_parts.mjs +138 -9
  56. package/api/theme-edit/_png.d.mts +18 -0
  57. package/api/theme-edit/_png.mjs +95 -14
  58. package/api/theme-edit/_preview-app.d.mts +9 -0
  59. package/api/theme-edit/_preview-app.mjs +1191 -71
  60. package/api/theme-edit/_preview.d.mts +16 -3
  61. package/api/theme-edit/_preview.mjs +335 -30
  62. package/api/theme-edit/_project.d.mts +11 -0
  63. package/api/theme-edit/_project.mjs +46 -12
  64. package/api/theme-edit/_settings.d.mts +240 -5
  65. package/api/theme-edit/_settings.mjs +2561 -115
  66. package/api/theme-edit/_tables.d.mts +24 -0
  67. package/api/theme-edit/_tables.mjs +211 -149
  68. package/api/theme-edit/_vet.d.mts +42 -0
  69. package/api/theme-edit/_vet.mjs +144 -0
  70. package/api/theme-edit/theme-edit.type.d.mts +2 -1
  71. package/api/theme-edit/theme-edit.type.mjs +1 -1
  72. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  73. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  74. package/api/upgrade/registry/registry.mjs +6 -1
  75. package/assets/codemods/parse.mjs +2 -2
  76. package/assets/docs/tree/single-component.doc.mjs +11 -2
  77. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  78. package/assets/docs.generated.json +2 -2
  79. package/assets/preview-app/next.config.mjs +7 -1
  80. package/assets/preview-app/package.json +1 -0
  81. package/assets/preview-app/src/app/globals.css +1 -0
  82. package/assets/self-audit.generated.json +1 -1
  83. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  84. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  85. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  86. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  87. package/assets/templates/components.generated.json +1 -1
  88. package/assets/templates/pages/dashboard/page.tsx +1 -1
  89. package/authoring/doctypes/_schema.d.mts +52 -5
  90. package/authoring/doctypes/_schema.mjs +62 -7
  91. package/authoring/doctypes/base/type.ts +10 -0
  92. package/authoring/doctypes/component/component.doc.mjs +1 -1
  93. package/authoring/doctypes/function/function.doc.mjs +6 -0
  94. package/authoring/doctypes/function/type.ts +3 -0
  95. package/authoring/doctypes/legacy.mjs +5 -1
  96. package/authoring/index.d.ts +1 -0
  97. package/authoring/shadcn/source-variants.d.mts +1 -1
  98. package/authoring/shadcn/source-variants.mjs +32 -10
  99. package/clients/cli/build-id.generated.json +1 -1
  100. package/clients/cli/commands/doctor.doc.mjs +2 -2
  101. package/clients/cli/commands/experimental/theme.mjs +237 -45
  102. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  103. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +2 -2
  104. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +2 -2
  105. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +3 -3
  106. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  107. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  108. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  109. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  110. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  111. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  112. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  113. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  114. package/clients/cli/commands/theme.mjs +190 -46
  115. package/clients/cli/formatters/index.mjs +7 -4
  116. package/clients/cli/lib/cli-error.mjs +9 -3
  117. package/clients/cli/lib/component-format.mjs +27 -9
  118. package/clients/cli/lib/json-shim.mjs +72 -2
  119. package/clients/cli/manifest.generated.json +1 -1
  120. package/clients/cli/run.mjs +49 -0
  121. package/foundation/agent-docs/agent-docs-target.d.mts +2 -6
  122. package/foundation/agent-docs/agent-docs-target.mjs +9 -17
  123. package/foundation/agent-docs/agent-docs.mjs +3 -2
  124. package/foundation/config/config-writer.mjs +2 -2
  125. package/foundation/config/project.mjs +60 -14
  126. package/foundation/discovery/component-discovery.mjs +5 -17
  127. package/foundation/discovery/icon-set-writer.mjs +1 -1
  128. package/foundation/discovery/module-exports.mjs +1 -15
  129. package/foundation/discovery/template-adapter.mjs +44 -19
  130. package/foundation/discovery/template-source-tree.mjs +3 -16
  131. package/foundation/discovery/theme-discovery.d.mts +5 -1
  132. package/foundation/discovery/theme-discovery.mjs +30 -35
  133. package/foundation/fs/exact-codec.d.mts +35 -0
  134. package/foundation/fs/exact-codec.mjs +148 -0
  135. package/foundation/fs/gather-cache.d.mts +15 -5
  136. package/foundation/fs/gather-cache.mjs +123 -30
  137. package/foundation/fs/paths.d.mts +39 -0
  138. package/foundation/fs/paths.mjs +44 -11
  139. package/foundation/fs/read-record.mjs +11 -1
  140. package/foundation/integrations/contribution-fixes.mjs +1 -16
  141. package/foundation/integrations/may-have-integrations.mjs +3 -2
  142. package/foundation/integrations/public-imports.mjs +1 -1
  143. package/foundation/render/embedded-imports.mjs +1 -1
  144. package/foundation/render/host-exit.d.mts +8 -0
  145. package/foundation/render/host-exit.mjs +11 -0
  146. package/foundation/render/page-host.mjs +56 -10
  147. package/foundation/render/page-worker.mjs +14 -0
  148. package/foundation/render/render-page.mjs +37 -2
  149. package/foundation/response/error-codes.d.mts +2 -1
  150. package/foundation/response/error-codes.d.ts +1 -0
  151. package/foundation/response/error-codes.doc.mjs +5 -0
  152. package/foundation/response/error-codes.mjs +3 -0
  153. package/foundation/response/json.d.mts +15 -0
  154. package/foundation/response/json.mjs +52 -1
  155. package/foundation/response/response-types.doc.mjs +1 -1
  156. package/foundation/runtime/lazy-dependencies.d.mts +14 -0
  157. package/foundation/runtime/lazy-dependencies.mjs +82 -0
  158. package/foundation/xle/browser.d.mts +2 -2
  159. package/package.json +7 -6
@@ -10,20 +10,25 @@
10
10
  */
11
11
 
12
12
  import * as fs from 'node:fs';
13
+ import {coversProperty} from './_css.mjs';
13
14
  import * as path from 'node:path';
14
15
  import {AstryxError} from '../error.mjs';
16
+ import {vetSuggestions} from './_vet.mjs';
15
17
  import {
16
18
  AUTO_SPREAD,
17
19
  CORNERS,
18
20
  DIALS,
19
21
  FAMILIES,
20
22
  FONT_ROLES,
23
+ HEADING_TRACKING,
24
+ HEADING_WEIGHTS,
21
25
  KEY_TOKENS,
22
26
  LIKE,
23
27
  P,
24
28
  SPACING,
25
29
  TYPE_STYLES,
26
30
  familyOf,
31
+ wordTable,
27
32
  } from './_tables.mjs';
28
33
  import {
29
34
  commitTheme,
@@ -42,7 +47,9 @@ import {
42
47
  undoArgs,
43
48
  withoutBadValues,
44
49
  NAME_RULE,
50
+ HISTORY_STEPS,
45
51
  readHistory,
52
+ refuseUnreadableFiles,
46
53
  refuse,
47
54
  settingsProblem,
48
55
  resolvedTokens,
@@ -53,6 +60,9 @@ import {
53
60
  staleBuild,
54
61
  EDITOR_SUFFIXES,
55
62
  madeByEditor,
63
+ outputsDrift,
64
+ kebab,
65
+ camel,
56
66
  NEW_MARKER,
57
67
  clearNewMarker,
58
68
  refuseThemeSource,
@@ -60,6 +70,17 @@ 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
+ freeThemeName,
81
+ refuseLinks,
82
+ usableNewName,
83
+ dialValueFits,
63
84
  } from './_settings.mjs';
64
85
  import {checkSetting, exampleOf, storedProblems} from './_check.mjs';
65
86
  import {MODAL} from './_compiler.mjs';
@@ -73,12 +94,15 @@ import {
73
94
  lockHeld,
74
95
  refuseIfLockLost,
75
96
  writeWhole,
97
+ isGraySeed,
98
+ seedOf,
76
99
  } from './_palette.mjs';
77
100
  import {renderPreview, renderSheet} from './_preview.mjs';
78
101
  import {refreshPreviewRoute} from './_preview-app.mjs';
79
- import {baseResolved, installLine} from './_project.mjs';
102
+ import {baseInstalled, baseResolved, installLine} from './_project.mjs';
80
103
  import {reactMissing} from './_parts.mjs';
81
104
  import {
105
+ renderCause,
82
106
  requireProject,
83
107
  context,
84
108
  pictures,
@@ -86,9 +110,13 @@ import {
86
110
  styledChanges,
87
111
  previewAfter,
88
112
  checkSection,
113
+ stampSheet,
89
114
  } from './_context.mjs';
90
115
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
91
- import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
116
+ import {
117
+ getCliInvocation,
118
+ quoteCommandArgument,
119
+ } from '../../foundation/env/package-manager.mjs';
92
120
 
93
121
  const E = ERROR_CODES;
94
122
 
@@ -177,6 +205,40 @@ function readableJson(file) {
177
205
  }
178
206
  }
179
207
 
208
+ /**
209
+ * A physical padding side as its logical side (left-to-right), so a later
210
+ * `padding-inline` replaces an earlier `padding-left` as it does
211
+ * `padding-inline-start`.
212
+ * @param {string} prop
213
+ */
214
+ const logicalSide = prop =>
215
+ /** @type {Record<string, string>} */ ({
216
+ 'padding-left': 'padding-inline-start',
217
+ 'padding-right': 'padding-inline-end',
218
+ 'padding-top': 'padding-block-start',
219
+ 'padding-bottom': 'padding-block-end',
220
+ })[prop] ?? prop;
221
+
222
+ /**
223
+ * Put back every recorded file: its bytes, or removed when it was not
224
+ * there; a palette file the build made new in tokens/ goes too.
225
+ * @param {Map<string, Buffer | null>} kept
226
+ * @param {string} tokensDir
227
+ */
228
+ function putBack(kept, tokensDir) {
229
+ for (const [file, bytes] of kept)
230
+ if (bytes) writeWhole(file, bytes);
231
+ else if (!fs.existsSync(file) || fs.lstatSync(file).isFile())
232
+ fs.rmSync(file, {force: true});
233
+ if (kept.size && fs.existsSync(tokensDir))
234
+ for (const n of fs.readdirSync(tokensDir)) {
235
+ const file = path.join(tokensDir, n);
236
+ // Only a file the build made new; a folder the user put there stays.
237
+ if (!kept.has(file) && fs.lstatSync(file).isFile())
238
+ fs.rmSync(file, {force: true});
239
+ }
240
+ }
241
+
180
242
  /**
181
243
  * Start a theme in themes/<name>/, optionally on a built-in theme, with any
182
244
  * dial settings applied in the same build. Each setting is checked as `set`
@@ -186,19 +248,104 @@ function readableJson(file) {
186
248
  * @param {import('./theme-edit.type.mjs').ThemeEditNewOptions} [options]
187
249
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditNewResponse>}
188
250
  */
251
+
189
252
  export async function themeEditNew(name, options = {}) {
190
253
  const {cwd = process.cwd(), png = false, settings = {}} = options;
191
254
  // `--like none` builds on no base, as `set <theme> base none` does.
192
255
  const like = options.like === 'none' ? undefined : options.like;
193
256
  requireProject(cwd);
257
+ // A corrected `new` keeps every option given, fixing only the bad one.
258
+ // A --like in another case is the built-in theme it names.
259
+ // A --like that names no built-in theme is the nearest one, or none: a
260
+ // corrected command never repeats a --like that is refused below.
261
+ // A guess (the nearest base to a word that names none) is only a base the
262
+ // project has installed: another would be refused in turn. A base named
263
+ // in other letters is the one meant, installed or not (its refusal then
264
+ // offers the install, or the same new on no base).
265
+ const have = LIKE.filter(b => baseInstalled(cwd, b));
266
+ // `@astryxdesign/theme-butter`, `theme-butter`, `Butter`: butter.
267
+ const baseName = (/** @type {unknown} */ v) =>
268
+ String(v)
269
+ .trim()
270
+ .toLowerCase()
271
+ .replace(/^@astryxdesign\/theme-/, '')
272
+ .replace(/^theme-/, '');
273
+ const likeFixed =
274
+ like == null
275
+ ? options.like === 'none'
276
+ ? 'none'
277
+ : undefined
278
+ : LIKE.includes(baseName(like))
279
+ ? baseName(like)
280
+ : (nearest(baseName(like), have)[0] ?? null);
281
+ // A dial value the dial does not take is left out of a suggested `new`
282
+ // (a corrected name must not repeat it), and the refusal says so.
283
+ /** @type {Array<[string, string]>} */
284
+ const badValue = Object.entries(settings).flatMap(([k, v]) =>
285
+ (Array.isArray(v) ? v : v == null ? [] : [v])
286
+ .map(x => /** @type {[string, string]} */ ([k, String(x)]))
287
+ .filter(([dial, x]) => DIALS[dial] && !dialValueFits(dial, x)),
288
+ );
289
+ // Refused for no effect as new refuses it: vibrancy with no color given
290
+ // that is not a gray (a new theme has no other color to saturate).
291
+ const colorGiven = Object.entries(settings).some(
292
+ ([k, v]) =>
293
+ PALETTE_DIALS.includes(k) &&
294
+ (Array.isArray(v) ? v : v == null ? [] : [v]).some(
295
+ x =>
296
+ !badValue.some(([a, b]) => a === k && b === String(x)) &&
297
+ !isGraySeed(seedOf(String(x))),
298
+ ),
299
+ );
300
+ /** @type {Array<[string, string]>} */
301
+ const noEffect =
302
+ settings.vibrancy != null && !colorGiven
303
+ ? (Array.isArray(settings.vibrancy)
304
+ ? settings.vibrancy
305
+ : [settings.vibrancy]
306
+ ).map(x => /** @type {[string, string]} */ (['vibrancy', String(x)]))
307
+ : [];
308
+ const unfit = [...badValue, ...noEffect];
309
+ const isUnfit = (/** @type {string} */ k, /** @type {unknown} */ x) =>
310
+ unfit.some(([a, b]) => a === k && b === String(x));
311
+ /** @type {Record<string, string | string[] | undefined>} */
312
+ const fitSettings = Object.fromEntries(
313
+ Object.entries(settings).map(([k, v]) => [
314
+ k,
315
+ Array.isArray(v)
316
+ ? v.filter(x => !isUnfit(k, x))
317
+ : isUnfit(k, v)
318
+ ? undefined
319
+ : v,
320
+ ]),
321
+ );
322
+ const flag = (/** @type {[string, string]} */ [k, x]) =>
323
+ `--${k} ${quoteCommandArgument(x)}`;
324
+ const dropped = [
325
+ badValue.length
326
+ ? ` 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('; ')}).`
327
+ : '',
328
+ noEffect.length
329
+ ? ` 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.`
330
+ : '',
331
+ ].join('');
332
+ const again = (
333
+ /** @type {string} */ newName,
334
+ /** @type {string | null | undefined} */ likeValue = likeFixed,
335
+ ) => `${P} new ${newName}${newFlags(likeValue, fitSettings, png)}`;
194
336
  if (!slugOk(name)) {
195
337
  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);
338
+ // Only a name typed in another case is the theme here already.
339
+ const sameName = String(name ?? '').toLowerCase() === fixed;
340
+ const exists = sameName && fs.existsSync(themeFiles(cwd, fixed).settings);
198
341
  refuse(
199
342
  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}`]},
343
+ `"${String(name ?? '').slice(0, 80)}" is not a theme name (${NAME_RULE})${exists ? `; ${fixed} is a theme here already` : ''}.${dropped}`,
344
+ {
345
+ run: exists
346
+ ? [`${P} show ${fixed}`]
347
+ : [again(usableNewName(cwd, fixed))],
348
+ },
202
349
  );
203
350
  }
204
351
  // A built-in theme's name would collide with the theme of that name the
@@ -206,8 +353,19 @@ export async function themeEditNew(name, options = {}) {
206
353
  if (LIKE.includes(name))
207
354
  refuse(
208
355
  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}`]},
356
+ `${name} is a built-in theme; an editor theme needs a name of its own. To start from ${name}, build on it.${dropped}`,
357
+ {
358
+ run: [
359
+ again(
360
+ fs.existsSync(themeFiles(cwd, `my-${name}`).dir)
361
+ ? freeThemeName(cwd, `my-${name}`)
362
+ : `my-${name}`,
363
+ // Built on the theme named when it is installed, unless another
364
+ // base (or none) was given.
365
+ likeFixed ?? name,
366
+ ),
367
+ ],
368
+ },
211
369
  );
212
370
  const f = themeFiles(cwd, name);
213
371
  // A link or a file where the theme goes is never written through or
@@ -218,22 +376,33 @@ export async function themeEditNew(name, options = {}) {
218
376
  refuse(
219
377
  E.ERR_FILE_EXISTS,
220
378
  `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']},
379
+ // A look that changes nothing: what is in the way.
380
+ {
381
+ run: [
382
+ `ls -la ${quoteCommandArgument(path.relative(cwd, f.root) || 'themes')}`,
383
+ ],
384
+ },
223
385
  );
224
386
  const dirSt = fs.lstatSync(f.dir, {throwIfNoEntry: false});
225
387
  if (dirSt && (dirSt.isSymbolicLink() || !dirSt.isDirectory()))
226
388
  refuse(
227
389
  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`]},
390
+ `themes/${name} is ${dirSt.isSymbolicLink() ? 'a link' : 'a file'}, so a theme is not made there.${dropped}`,
391
+ {run: [again(freeThemeName(cwd, name))]},
230
392
  );
231
393
  // Settings that are not valid JSON are kept aside, and the theme is
232
394
  // made again beside them.
233
395
  const damaged = fs.existsSync(f.settings) && !readableJson(f.settings);
234
396
  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`],
397
+ refuse(E.ERR_FILE_EXISTS, `Theme "${name}" already exists.${dropped}`, {
398
+ // What the command asked for, on the theme that exists or as a new one.
399
+ run: [
400
+ `${P} show ${name}`,
401
+ ...(likeFixed && LIKE.includes(likeFixed)
402
+ ? [`${P} set ${name} base ${likeFixed}`]
403
+ : []),
404
+ again(freeThemeName(cwd, name)),
405
+ ],
237
406
  });
238
407
  // A `new` stopped part way (killed, out of memory) leaves its own marker
239
408
  // beside the files it wrote: only such a folder is cleared, and only
@@ -249,29 +418,46 @@ export async function themeEditNew(name, options = {}) {
249
418
  if (holdsOther)
250
419
  refuse(
251
420
  E.ERR_FILE_EXISTS,
252
- `themes/${name}/ already holds files this command did not make; choose another name.`,
253
- {run: [`${P} new ${name}-copy`]},
421
+ `themes/${name}/ already holds files this command did not make; choose another name.${dropped}`,
422
+ {run: [again(freeThemeName(cwd, name))]},
254
423
  );
255
424
  if (like != null && !LIKE.includes(like))
256
425
  refuse(
257
426
  E.ERR_THEME_BAD_VALUE,
258
427
  `--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
428
  {
260
- didYouMean: nearest(String(like).toLowerCase(), LIKE),
261
- run: [`${P} new ${name}`],
429
+ // The built-in theme it names in another case, or the nearest
430
+ // installed one, else none: the did-you-mean and the run agree.
431
+ didYouMean: likeFixed ? [likeFixed] : [],
432
+ // A built-in base that is not installed: install it, then the same
433
+ // new on it.
434
+ run: [
435
+ ...(likeFixed && likeFixed !== 'none' && !have.includes(likeFixed)
436
+ ? [installLine(cwd, [`@astryxdesign/theme-${likeFixed}`])]
437
+ : []),
438
+ again(name, likeFixed ?? null),
439
+ ],
262
440
  },
263
441
  );
264
442
  const ctx = await context(cwd);
265
443
  /** @type {import('./_settings.mjs').ThemeData} */
266
444
  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
- );
445
+ try {
446
+ /** @type {import('./_settings.mjs').Ctx} */ (ctx).base =
447
+ await baseResolved(ctx.project, data.like);
448
+ } catch (e) {
449
+ // A base that is not installed: install it, or the same new on no base.
450
+ if (e instanceof AstryxError && e.code === E.ERR_UNKNOWN_THEME)
451
+ e.suggestions = [
452
+ ...(e.suggestions ?? []),
453
+ {name: again(name, null), reason: 'build on no theme'},
454
+ ];
455
+ throw e;
456
+ }
271
457
  // Every check comes before the first change to the folder: the settings,
272
458
  // and a source of the user's own kept from before (it must still extend
273
459
  // the settings, or the build fails after the folder was cleared).
274
- applyNewSettings(ctx, name, data, settings);
460
+ applyNewSettings(ctx, name, data, settings, png, likeFixed ?? undefined);
275
461
  if (left?.keep.some(p => path.basename(p) === `${name}.theme.ts`))
276
462
  refuseThemeSource(cwd, name);
277
463
  /** @type {string[]} */
@@ -290,7 +476,7 @@ export async function themeEditNew(name, options = {}) {
290
476
  );
291
477
  if (left?.keep.some(p => path.basename(p) === `${name}.history.json`))
292
478
  leftNotes.push(
293
- `the earlier settings are kept in ${name}.history.json: \`${P} undo ${name}\` steps back to them`,
479
+ `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
480
  );
295
481
  // The marker goes first and comes off last: a `new` stopped between
296
482
  // leaves a folder the next `new` can prove it made. The damaged settings
@@ -417,8 +603,17 @@ export async function themeEditNew(name, options = {}) {
417
603
  * @param {string} slug
418
604
  * @param {import('./_settings.mjs').ThemeData} data
419
605
  * @param {Record<string, string | string[] | undefined>} settings
606
+ * @param {boolean} [png] kept in a corrected `new` a refusal suggests
607
+ * @param {string} [likeFlag] the --like a corrected `new` keeps (`none` too)
420
608
  */
421
- function applyNewSettings(ctx, slug, data, settings) {
609
+ function applyNewSettings(
610
+ ctx,
611
+ slug,
612
+ data,
613
+ settings,
614
+ png = false,
615
+ likeFlag = data.like,
616
+ ) {
422
617
  const given = Object.entries(settings).filter(([, v]) => v != null);
423
618
  for (const [thing] of given)
424
619
  if (!DIALS[thing] || thing === 'base')
@@ -441,13 +636,21 @@ function applyNewSettings(ctx, slug, data, settings) {
441
636
  const given = settings[thing];
442
637
  if (given == null) continue;
443
638
  // `headings` takes a weight and a tracking: one value per axis.
444
- for (const value of Array.isArray(given) ? given : [given]) {
639
+ const values = Array.isArray(given) ? given : [given];
640
+ for (const [index, value] of values.entries()) {
445
641
  /** @type {import('./_settings.mjs').Setting} */
446
642
  let s;
447
643
  try {
448
644
  s = checkSetting(ctx, slug, data, thing, String(value), {}, false);
449
645
  } catch (e) {
450
- throw asNewRefusal(e, slug, settings);
646
+ throw asNewRefusal(
647
+ vetSuggestions(e, ctx, slug, data),
648
+ slug,
649
+ settings,
650
+ likeFlag,
651
+ png,
652
+ {thing, index},
653
+ );
451
654
  }
452
655
  if (thing === 'mode')
453
656
  data.mode = /** @type {'both' | 'light-only' | 'dark-only'} */ (
@@ -460,8 +663,14 @@ function applyNewSettings(ctx, slug, data, settings) {
460
663
  E.ERR_INVALID_ARGUMENT,
461
664
  `--${thing} was given two values for the same thing (${data.settings[same].value}, ${s.value}); give one.`,
462
665
  {
666
+ // Every other option given stays, and the first value on each
667
+ // axis: every later value for an axis already given goes.
463
668
  run: [
464
- `${P} new ${slug} --${thing} ${quoteCommandArgument(s.value)}`,
669
+ `${P} new ${slug}${newFlags(
670
+ likeFlag,
671
+ {...settings, [thing]: firstPerAxis(values)},
672
+ png,
673
+ )}`,
465
674
  ],
466
675
  },
467
676
  );
@@ -471,36 +680,117 @@ function applyNewSettings(ctx, slug, data, settings) {
471
680
  }
472
681
  }
473
682
 
683
+ /**
684
+ * The options of a `new` as flags, in the order given (`new --help`'s order
685
+ * for the command): `--like`, each dial setting, then `--png`.
686
+ * @param {string | null | undefined} like none when null or undefined
687
+ * @param {Record<string, string | string[] | undefined>} settings
688
+ * @param {boolean} [png]
689
+ * @returns {string[]}
690
+ */
691
+ export function newFlagList(like, settings, png = false) {
692
+ return [
693
+ ...(like ? [`--like ${quoteCommandArgument(like)}`] : []),
694
+ ...Object.entries(settings)
695
+ .filter(([, v]) => v != null)
696
+ .flatMap(([k, v]) => (Array.isArray(v) ? v : [v]).map(x => [k, x]))
697
+ .map(([k, v]) => `--${k} ${quoteCommandArgument(String(v))}`),
698
+ ...(png ? ['--png'] : []),
699
+ ];
700
+ }
701
+
702
+ /**
703
+ * The options of a `new` as one flag line, with its leading space.
704
+ * @param {string | null | undefined} like
705
+ * @param {Record<string, string | string[] | undefined>} settings
706
+ * @param {boolean} png
707
+ */
708
+ function newFlags(like, settings, png) {
709
+ const parts = newFlagList(like, settings, png);
710
+ return parts.length ? ` ${parts.join(' ')}` : '';
711
+ }
712
+
474
713
  /**
475
714
  * A refusal from a setting `new` was given, with its suggestions turned
476
715
  * into `new` commands: the theme does not exist yet, so a `set` would fail.
477
716
  * @param {unknown} e
478
717
  * @param {string} slug
479
718
  * @param {Record<string, string | string[] | undefined>} settings
719
+ * @param {string} [like] the --like given, kept in a corrected command
720
+ * @param {boolean} [png] --png, kept in a corrected command
721
+ * @param {{thing: string, index: number} | null} [at] the value refused
480
722
  */
481
- function asNewRefusal(e, slug, settings) {
723
+ function asNewRefusal(e, slug, settings, like, png = false, at = null) {
482
724
  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
725
  const setPrefix = `${P} set ${slug} `;
488
726
  e.suggestions = (e.suggestions ?? []).map(s => {
489
727
  if (s.name === `${P} set --help`) return {...s, name: `${P} new --help`};
490
728
  if (!s.name.startsWith(setPrefix)) return s;
491
729
  const [thing, ...rest] = s.name.slice(setPrefix.length).split(' ');
492
730
  if (thing.startsWith('--') || !DIALS[thing]) return s;
493
- const keep = flags.filter(f => !f.startsWith(`--${thing} `));
731
+ const fixed = unquoteWord(rest.join(' '));
732
+ // Only the refused value changes: a dial given several values
733
+ // (--headings tight --headings BOLD) keeps the others, in order.
734
+ const given = settings[thing];
735
+ const values = Array.isArray(given) ? [...given] : null;
736
+ const next =
737
+ values && at && at.thing === thing
738
+ ? firstPerAxis(values.map((v, i) => (i === at.index ? fixed : v)))
739
+ : fixed;
494
740
  return {
495
741
  ...s,
496
- name: [`${P} new ${slug}`, ...keep, `--${thing} ${rest.join(' ')}`].join(
497
- ' ',
498
- ),
742
+ name: `${P} new ${slug}${newFlags(like, {...settings, [thing]: next}, png)}`,
499
743
  };
500
744
  });
745
+ // A refused value with nothing to put in its place: the same new
746
+ // without it, every other option kept.
747
+ if (at && !e.suggestions.some(x => x.name.startsWith(`${P} new `))) {
748
+ const given = settings[at.thing];
749
+ const rest = Array.isArray(given)
750
+ ? given.filter((_, i) => i !== at.index)
751
+ : undefined;
752
+ e.suggestions.push({
753
+ name: `${P} new ${slug}${newFlags(like, {...settings, [at.thing]: rest?.length ? rest : undefined}, png)}`,
754
+ reason: `without --${at.thing} ${quoteCommandArgument(String(Array.isArray(given) ? given[at.index] : given))}`,
755
+ });
756
+ }
501
757
  return e;
502
758
  }
503
759
 
760
+ /**
761
+ * Headings values with every later value for an axis already given left
762
+ * out (the first weight and the first tracking stay); a word of neither
763
+ * axis stays, for its own refusal.
764
+ * @param {string[]} values
765
+ * @returns {string[]}
766
+ */
767
+ function firstPerAxis(values) {
768
+ const seen = new Set();
769
+ return values.filter(v => {
770
+ const w = String(v).trim().toLowerCase();
771
+ const axis =
772
+ HEADING_WEIGHTS[w] !== undefined
773
+ ? 'weight'
774
+ : HEADING_TRACKING[w] !== undefined
775
+ ? 'tracking'
776
+ : null;
777
+ if (!axis) return true;
778
+ if (seen.has(axis)) return false;
779
+ seen.add(axis);
780
+ return true;
781
+ });
782
+ }
783
+
784
+ /**
785
+ * A word as a suggested command writes it, without the quotes
786
+ * quoteCommandArgument adds.
787
+ * @param {string} word
788
+ */
789
+ function unquoteWord(word) {
790
+ const m = /^'(.*)'$/s.exec(word);
791
+ return m ? m[1].replace(/'\\''/g, "'") : word;
792
+ }
793
+
504
794
  /**
505
795
  * The preview after a change, with the in-app preview route kept in step:
506
796
  * its imports follow the theme, such as the stylesheet of a font package
@@ -552,7 +842,7 @@ export async function themeEditSet(theme, thing, value, options = {}) {
552
842
  * @param {import('./_settings.mjs').Ctx} ctx
553
843
  * @param {string} slug
554
844
  * @param {import('./_settings.mjs').ThemeData} data
555
- * @param {string} [skip]
845
+ * @param {string | {thing: string, on?: string, when?: string, state?: string, mode?: string}} [skip]
556
846
  */
557
847
  function refuseStoredTokens(ctx, slug, data, skip) {
558
848
  const bad = storedProblems(ctx, slug, data, skip);
@@ -571,7 +861,12 @@ function refuseStoredTokens(ctx, slug, data, skip) {
571
861
  // setting is never refused for another.
572
862
  run: [
573
863
  ...bad.slice(0, 5).map(b => `${P} undo ${slug} ${undoArgs(b.setting)}`),
574
- ...(one && !one.scope
864
+ // A value to set only for a token whose stored value has the wrong
865
+ // type; any other thing `set` would refuse, or read as a dial.
866
+ ...(one &&
867
+ !one.scope &&
868
+ one.setting.source === 'token' &&
869
+ ctx.C.isToken(one.setting.thing)
575
870
  ? [
576
871
  `${P} set ${slug} ${one.setting.thing} ${quoteCommandArgument(exampleOf(ctx.C.typeOf(one.setting.thing), one.setting.thing))}`,
577
872
  ]
@@ -611,6 +906,54 @@ function extremeSteps(res) {
611
906
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
612
907
  */
613
908
  async function change(sub, slug, thing, value, options) {
909
+ /** @type {{ctx?: import('./_settings.mjs').Ctx, data?: import('./_settings.mjs').ThemeData}} */
910
+ const seen = {};
911
+ try {
912
+ return await changeOnce(sub, slug, thing, value, options, seen);
913
+ } catch (e) {
914
+ // A theme name one letter off an existing theme: the same command with
915
+ // that name comes first, before making a theme of the typo.
916
+ if (e instanceof AstryxError && e.code === E.ERR_UNKNOWN_THEME) {
917
+ const near = (e.suggestions ?? []).find(x => x.reason === 'did you mean');
918
+ if (near && slugOk(near.name)) {
919
+ const flags = [
920
+ ...(options.on ? ['--on', options.on] : []),
921
+ ...(options.when ? ['--when', options.when] : []),
922
+ ...(options.state ? ['--state', options.state] : []),
923
+ ...(options.mode ? ['--mode', options.mode] : []),
924
+ ...(options.only ? ['--only'] : []),
925
+ ];
926
+ const words = [thing, ...(value == null ? [] : [value]), ...flags]
927
+ .filter(w => w != null && w !== '')
928
+ .map(w =>
929
+ String(w).startsWith('--') ? w : quoteCommandArgument(String(w)),
930
+ );
931
+ e.suggestions = [
932
+ {
933
+ name: `${P} ${sub} ${near.name}${words.length ? ` ${words.join(' ')}` : ''}`,
934
+ reason: `do this instead: ${near.name} is a theme here`,
935
+ },
936
+ ...(e.suggestions ?? []).filter(x => x !== near),
937
+ ];
938
+ }
939
+ throw e;
940
+ }
941
+ // Every `set` the refusal suggests is checked as `set` checks it.
942
+ throw vetSuggestions(e, seen.ctx, slug, seen.data);
943
+ }
944
+ }
945
+
946
+ /**
947
+ * @param {'set' | 'undo'} sub
948
+ * @param {string} slug
949
+ * @param {string} thing
950
+ * @param {string | undefined} value
951
+ * @param {ChangeOptions} options
952
+ * @param {{ctx?: import('./_settings.mjs').Ctx, data?: import('./_settings.mjs').ThemeData}} seen
953
+ * the context and the theme as loaded, for checking a refusal's suggestions
954
+ * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
955
+ */
956
+ async function changeOnce(sub, slug, thing, value, options, seen) {
614
957
  const {cwd = process.cwd(), png = false} = options;
615
958
  requireProject(cwd);
616
959
  // The setting this command changes or removes may be the bad one; any
@@ -643,7 +986,14 @@ async function change(sub, slug, thing, value, options) {
643
986
  const ctx = await context(cwd);
644
987
  // An undo of one setting only removes it, so it never waits on the
645
988
  // others being fixed.
646
- if (sub !== 'undo') refuseStoredTokens(ctx, slug, data, thing);
989
+ if (sub !== 'undo')
990
+ refuseStoredTokens(ctx, slug, data, {
991
+ thing,
992
+ on: options.on,
993
+ when: options.when,
994
+ state: options.state,
995
+ mode: options.mode,
996
+ });
647
997
  const flags = {
648
998
  on: options.on,
649
999
  when: options.when,
@@ -664,6 +1014,8 @@ async function change(sub, slug, thing, value, options) {
664
1014
  );
665
1015
  }
666
1016
  /** @type {import('./_settings.mjs').Ctx} */ (ctx).base = base;
1017
+ seen.ctx = ctx;
1018
+ seen.data = structuredClone(data);
667
1019
  /** @type {import('./_settings.mjs').Setting} */
668
1020
  let s;
669
1021
  try {
@@ -675,11 +1027,13 @@ async function change(sub, slug, thing, value, options) {
675
1027
  sub === 'undo'
676
1028
  ? data.settings.find(
677
1029
  x =>
678
- x.thing === thing &&
1030
+ x.thing.toLowerCase() === String(thing).toLowerCase() &&
679
1031
  (x.on ?? null) === (flags.on ?? null) &&
680
1032
  (x.when ?? null) === (flags.when ?? null) &&
681
1033
  (x.state ?? null) === (flags.state ?? null) &&
682
- (x.mode ?? null) === (flags.mode ?? null),
1034
+ (x.mode ?? null) === (flags.mode ?? null) &&
1035
+ // --only names a setting made with it; it is never dropped.
1036
+ Boolean(x.only) === Boolean(flags.only),
683
1037
  )
684
1038
  : null;
685
1039
  if (!stored) {
@@ -687,13 +1041,50 @@ async function change(sub, slug, thing, value, options) {
687
1041
  // what it named (or of the dial its refusal names), else the last
688
1042
  // step.
689
1043
  if (sub === 'undo' && e instanceof AstryxError) {
1044
+ // Setting names are matched in any case, and a near name of a
1045
+ // setting the theme has counts: `undo t Corners`, `undo t corner`.
1046
+ const typed = String(thing).toLowerCase();
1047
+ // A token named without its dashes (radius-element) is the token.
1048
+ const dashed = typed.startsWith('--') ? typed : `--${typed}`;
690
1049
  const named = new Set([
691
- thing,
1050
+ typed,
1051
+ dashed,
1052
+ ...(e.suggestions ?? [])
1053
+ .filter(x => x.reason === 'did you mean')
1054
+ .map(x => x.name.toLowerCase()),
692
1055
  ...(e.suggestions ?? [])
693
- .map(x => new RegExp(` set ${slug} (\\S+)`).exec(x.name)?.[1])
1056
+ .map(
1057
+ x => new RegExp(` (?:set|undo) ${slug} (\\S+)`).exec(x.name)?.[1],
1058
+ )
694
1059
  .filter(Boolean),
1060
+ ...nearest(
1061
+ typed,
1062
+ data.settings.map(x => x.thing.toLowerCase()),
1063
+ ),
695
1064
  ]);
696
- const matches = data.settings.filter(x => named.has(x.thing));
1065
+ const matches = data.settings.filter(x =>
1066
+ named.has(x.thing.toLowerCase()),
1067
+ );
1068
+ // A word that is near a setting name (a typo, another case) is never
1069
+ // answered with a bare step back, which would undo another change;
1070
+ // any other word (`all`) may mean the last step.
1071
+ // A token or a property named (radius-element, padding) is a named
1072
+ // thing too: never answered with a step back.
1073
+ const namesThing =
1074
+ ctx.C.isToken(dashed) ||
1075
+ data.settings.some(
1076
+ x => x.source === 'property' && x.thing.toLowerCase() === typed,
1077
+ ) ||
1078
+ /^[a-z]+(-[a-z]+)+$|^(padding|margin|color|background|border|gap|width|height|opacity)$/.test(
1079
+ typed,
1080
+ );
1081
+ const nearSetting =
1082
+ namesThing ||
1083
+ named.size > (dashed === typed ? 1 : 2) ||
1084
+ nearest(typed, [
1085
+ ...Object.keys(DIALS),
1086
+ ...data.settings.map(x => x.thing.toLowerCase()),
1087
+ ]).length > 0;
697
1088
  const steps = readHistory(themeFiles(cwd, slug).history).steps.length;
698
1089
  throw new AstryxError(
699
1090
  e.message,
@@ -703,7 +1094,7 @@ async function change(sub, slug, thing, value, options) {
703
1094
  reason: 'do this instead',
704
1095
  }))
705
1096
  : [
706
- steps
1097
+ steps && !nearSetting
707
1098
  ? {name: `${P} undo ${slug}`, reason: 'step back one change'}
708
1099
  : {name: `${P} show ${slug}`, reason: 'see what it sets'},
709
1100
  ],
@@ -734,7 +1125,11 @@ async function change(sub, slug, thing, value, options) {
734
1125
  .trim()
735
1126
  .toLowerCase()
736
1127
  .replace(/\s+/g, ' ')
737
- .replace(/^["']|["']$/g, '');
1128
+ // Spacing around commas, slashes and parentheses, and the quote
1129
+ // style, are not part of a value.
1130
+ .replace(/\s*([,()/])\s*/g, '$1')
1131
+ .replace(/'/g, '"')
1132
+ .replace(/^"|"$/g, '');
738
1133
  const half =
739
1134
  s.thing === 'headings' && ['weight', 'tracking'].includes(norm(value));
740
1135
  if (
@@ -819,9 +1214,16 @@ async function change(sub, slug, thing, value, options) {
819
1214
  if (sub === 'undo') {
820
1215
  if (!prev) {
821
1216
  const near = data.settings.filter(x => x.thing === s.thing).map(describe);
1217
+ // headings has two halves: name the one that is set.
1218
+ const otherHalf =
1219
+ s.thing === 'headings'
1220
+ ? data.settings.find(x => x.thing === 'headings' && x.axis !== s.axis)
1221
+ : null;
822
1222
  refuse(
823
1223
  E.ERR_THEME_NOT_SET,
824
- `The theme does not set ${describe({...s, value: '?'}).replace(' = ?', '')}.`,
1224
+ otherHalf
1225
+ ? `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.`
1226
+ : `The theme does not set ${describe({...s, value: '?'}).replace(' = ?', '')}.`,
825
1227
  {
826
1228
  also: near.length
827
1229
  ? [`settings for ${s.thing}: ${near.join('; ')}`]
@@ -837,6 +1239,8 @@ async function change(sub, slug, thing, value, options) {
837
1239
  );
838
1240
  }
839
1241
  data.settings.splice(prevIdx, 1);
1242
+ // A setting listed twice by hand goes in full.
1243
+ data.settings = data.settings.filter(x => keyOf(x) !== k);
840
1244
  // Vibrancy needs a color: undoing the last one takes it along, so the
841
1245
  // theme never holds a state `set` refuses.
842
1246
  if (
@@ -872,6 +1276,13 @@ async function change(sub, slug, thing, value, options) {
872
1276
  if (prev) data.settings.splice(prevIdx, 1);
873
1277
  data.settings.push(s);
874
1278
  }
1279
+ // A setting listed twice by hand keeps only the entry this command left.
1280
+ if (sub === 'set') {
1281
+ const last = data.settings.map(x => keyOf(x)).lastIndexOf(k);
1282
+ data.settings = data.settings.filter(
1283
+ (x, i) => keyOf(x) !== k || i === last,
1284
+ );
1285
+ }
875
1286
  // A setting for both modes replaces the ones made for one mode, which it
876
1287
  // would otherwise sit under.
877
1288
  /** @type {import('./_settings.mjs').Setting[]} */
@@ -889,16 +1300,24 @@ async function change(sub, slug, thing, value, options) {
889
1300
  x =>
890
1301
  x !== s &&
891
1302
  x.source === 'property' &&
892
- x.on === s.on &&
1303
+ // On the same part, or on a member of the group it is set on:
1304
+ // the later setting wins, whichever way Core writes it.
1305
+ (x.on === s.on ||
1306
+ (s.on != null &&
1307
+ (FAMILIES[s.on] ?? []).includes(
1308
+ /** @type {string} */ (x.on),
1309
+ ))) &&
893
1310
  x.when === s.when &&
894
1311
  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
- ),
1312
+ // A longhand the shorthand really sets (MDN's data), never a
1313
+ // property that only shares its name (overflow-wrap).
1314
+ (coversProperty(s.thing, x.thing) ||
1315
+ coversProperty(logicalSide(s.thing), logicalSide(x.thing))),
900
1316
  )
901
1317
  : [];
1318
+ // They go, as the note says: Core writes each side to its own variable,
1319
+ // where a later shorthand would not win over them (undo brings them back).
1320
+ data.settings = data.settings.filter(x => !longhands.includes(x));
902
1321
  // A group setting covers part settings made before it for its members.
903
1322
  const covers =
904
1323
  sub === 'set' && s.source === 'dial' && s.on && FAMILIES[s.on]
@@ -913,42 +1332,37 @@ async function change(sub, slug, thing, value, options) {
913
1332
  )
914
1333
  : [];
915
1334
  const r = await commitTheme(ctx, slug, data, {history: true});
916
- const styled = styledChanges(compiledBefore, compileTheme(ctx, data, base));
1335
+ const compiledAfter = compileTheme(ctx, data, base);
1336
+ const styled = styledChanges(compiledBefore, compiledAfter);
917
1337
  const parts = partsOf(ctx, s);
918
1338
  // Exact whole-theme tokens that win over what this dial writes: the dial
919
1339
  // 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
1340
  /** @type {import('./_settings.mjs').Setting[]} */
926
1341
  let exactWins = [];
1342
+ /** Tokens this whole-theme dial changes. */
1343
+ let dialTokens = new Set();
927
1344
  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);
1345
+ const touched = dialTouched(ctx, data, s, base);
948
1346
  exactWins = data.settings.filter(
949
1347
  x => x.source === 'token' && !x.on && !x.when && touched.has(x.thing),
950
1348
  );
1349
+ dialTokens = touched;
951
1350
  }
1351
+ // A role font (font X --on heading) writes --font-family-<role>: an exact
1352
+ // setting of that token wins over it.
1353
+ if (sub === 'set' && s.thing === 'font' && s.on && FONT_ROLES.includes(s.on))
1354
+ exactWins = data.settings.filter(
1355
+ x =>
1356
+ x.source === 'token' &&
1357
+ !x.on &&
1358
+ !x.when &&
1359
+ x.thing === `--font-family-${s.on}`,
1360
+ );
1361
+ // The theme's own source wins over an exact setting, as the exact
1362
+ // setting does over a dial: an exact token the file also sets is named
1363
+ // as the file's below, never as the one that shows after an undo.
1364
+ const ownFirst = new Set(ownSourceTokens(cwd, slug));
1365
+ exactWins = exactWins.filter(x => !ownFirst.has(x.thing));
952
1366
  const kept =
953
1367
  sub === 'set' && s.source === 'dial' && !s.on
954
1368
  ? [
@@ -956,13 +1370,62 @@ async function change(sub, slug, thing, value, options) {
956
1370
  ...exactWins,
957
1371
  ].map(describe)
958
1372
  : [];
1373
+ // The role fonts a whole-theme font sits under.
1374
+ // An exact --font-family-<role> wins over both: that role is named by
1375
+ // the exact note instead.
1376
+ /** @param {string} role */
1377
+ const exactFamily = role =>
1378
+ data.settings.find(
1379
+ x =>
1380
+ x.source === 'token' &&
1381
+ !x.on &&
1382
+ !x.when &&
1383
+ x.thing === `--font-family-${role}`,
1384
+ );
1385
+ const roleOver =
1386
+ sub === 'set' && s.thing === 'font' && !s.on
1387
+ ? data.settings.filter(
1388
+ x =>
1389
+ x.thing === 'font' &&
1390
+ x.on &&
1391
+ ['body', 'heading'].includes(x.on) &&
1392
+ !exactFamily(x.on),
1393
+ )
1394
+ : [];
1395
+ if (sub === 'set' && s.thing === 'font' && !s.on)
1396
+ for (const role of FONT_ROLES) {
1397
+ const exact = exactFamily(role);
1398
+ if (exact && !exactWins.includes(exact)) exactWins.push(exact);
1399
+ }
959
1400
  // 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
- });
1401
+ const DIAL_PROPERTY = wordTable(
1402
+ /** @type {Record<string, RegExp>} */ ({
1403
+ corners: /radius$/,
1404
+ spacing: /^(padding|gap)(-|$)/,
1405
+ }),
1406
+ );
1407
+ // A whole-theme look dial (buttons, surfaces) writes part properties
1408
+ // too: an exact property on one of them wins there, read from the build.
1409
+ const looksOver =
1410
+ sub === 'set' && s.source === 'dial' && !DIAL_PROPERTY[s.thing]
1411
+ ? (() => {
1412
+ const writes = dialWrites(ctx, data, s, base);
1413
+ if (!writes.size) return null;
1414
+ return (
1415
+ data.settings.find(
1416
+ x =>
1417
+ x.source === 'property' &&
1418
+ x.on &&
1419
+ !x.when &&
1420
+ !x.state &&
1421
+ partsOf(ctx, x).some(t => writes.has(`${t}\0${x.thing}`)),
1422
+ ) ?? null
1423
+ );
1424
+ })()
1425
+ : null;
964
1426
  const exactOver =
965
- sub === 'set' && s.source === 'dial' && s.on && DIAL_PROPERTY[s.thing]
1427
+ looksOver ??
1428
+ (sub === 'set' && s.source === 'dial' && s.on && DIAL_PROPERTY[s.thing]
966
1429
  ? (data.settings.find(
967
1430
  x =>
968
1431
  x.source === 'property' &&
@@ -972,13 +1435,111 @@ async function change(sub, slug, thing, value, options) {
972
1435
  (x.when ?? '') === (s.when ?? '') &&
973
1436
  (x.state ?? '') === (s.state ?? ''),
974
1437
  ) ?? null)
975
- : null;
1438
+ : null);
1439
+ // An exact token the theme's own source also sets: the file's value
1440
+ // shows (read from what the build made of it), not the setting.
1441
+ // On parts: every property or token this change writes on a part's
1442
+ // plain or variant rule (a dial's too, and each member of a group) that
1443
+ // the own source sets on that same rule.
1444
+ /** @type {Array<{target: string, key: string, prop: string, value: string | null}>} */
1445
+ const ownPartHits = [];
1446
+ if (sub === 'set' && s.on && !s.state) {
1447
+ const a = /** @type {any} */ (compiledBefore)?.components ?? {};
1448
+ const b = /** @type {any} */ (compiledAfter)?.components ?? {};
1449
+ for (const target of new Set([...Object.keys(a), ...Object.keys(b)]))
1450
+ for (const key of new Set([
1451
+ ...Object.keys(a[target] ?? {}),
1452
+ ...Object.keys(b[target] ?? {}),
1453
+ ])) {
1454
+ if (key !== 'base' && !key.startsWith('variant:')) continue;
1455
+ const x = a[target]?.[key] ?? {};
1456
+ const y = b[target]?.[key] ?? {};
1457
+ /** @type {Map<string, string | null> | null} */
1458
+ let own = null;
1459
+ for (const prop of new Set([...Object.keys(x), ...Object.keys(y)])) {
1460
+ if (
1461
+ prop.startsWith(':') ||
1462
+ JSON.stringify(x[prop]) === JSON.stringify(y[prop])
1463
+ )
1464
+ continue;
1465
+ const css = prop.startsWith('--')
1466
+ ? prop
1467
+ : prop.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`);
1468
+ own ??= ownPartTokens(cwd, slug, target, key);
1469
+ if (own.has(css))
1470
+ ownPartHits.push({
1471
+ target,
1472
+ key,
1473
+ prop: css,
1474
+ value: own.get(css) ?? null,
1475
+ });
1476
+ }
1477
+ }
1478
+ }
1479
+ // A part dial writes its property on each part it reaches: the own
1480
+ // source setting it there wins, whatever else wins over the dial.
1481
+ if (
1482
+ sub === 'set' &&
1483
+ s.source === 'dial' &&
1484
+ s.on &&
1485
+ !s.state &&
1486
+ DIAL_PROPERTY[s.thing]
1487
+ )
1488
+ for (const target of partsOf(ctx, s))
1489
+ for (const [prop, value] of ownPartTokens(
1490
+ cwd,
1491
+ slug,
1492
+ target,
1493
+ s.when ?? 'base',
1494
+ ))
1495
+ if (
1496
+ DIAL_PROPERTY[s.thing].test(prop) &&
1497
+ !ownPartHits.some(h => h.target === target && h.prop === prop)
1498
+ )
1499
+ ownPartHits.push({target, key: s.when ?? 'base', prop, value});
1500
+ // A direct setting on exactly the rule the own source sets: its undo
1501
+ // takes it back (anything else the file wins over either way).
1502
+ const ownHitDirect =
1503
+ ownPartHits.length === 1 &&
1504
+ (s.source === 'token' || s.source === 'property') &&
1505
+ ownPartHits[0].target === s.on &&
1506
+ ownPartHits[0].prop === s.thing &&
1507
+ ownPartHits[0].key === (s.when ?? 'base');
1508
+ const ownOverToken =
1509
+ sub !== 'set' || s.when || s.state || s.on
1510
+ ? null
1511
+ : s.source === 'token'
1512
+ ? (Object.entries(ownSourceTokenValues(cwd, slug)).find(
1513
+ ([k]) => k === s.thing,
1514
+ ) ??
1515
+ (ownSourceTokens(cwd, slug).includes(s.thing)
1516
+ ? [s.thing, null]
1517
+ : null))
1518
+ : null;
976
1519
  /** @type {string[]} */
977
1520
  const notes = [
978
1521
  ...(covered.length ? [`replaces ${covered.map(describe).join(', ')}`] : []),
1522
+ ...(ownPartHits.length
1523
+ ? [
1524
+ `${slug}.theme.ts sets ${ownPartHits
1525
+ .slice(0, 3)
1526
+ .map(
1527
+ h =>
1528
+ `${h.prop} on ${h.target}${h.key === 'base' ? '' : ` when ${h.key}`} itself${h.value != null ? ` (${h.value})` : ''}`,
1529
+ )
1530
+ .join(
1531
+ ', ',
1532
+ )}${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)}\`` : ''}`,
1533
+ ]
1534
+ : []),
1535
+ ...(ownOverToken
1536
+ ? [
1537
+ `${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)}\``,
1538
+ ]
1539
+ : []),
979
1540
  ...(exactWins.length
980
1541
  ? [
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`,
1542
+ `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
1543
  ]
983
1544
  : []),
984
1545
  ...(covers.length
@@ -986,6 +1547,29 @@ async function change(sub, slug, thing, value, options) {
986
1547
  `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
1548
  ]
988
1549
  : []),
1550
+ // Core writes a part's derived variables (a button's or card's radius
1551
+ // variable, read by what is drawn inside it) from plain declarations
1552
+ // only: in a state they keep the plain value, and the result says so.
1553
+ ...(sub === 'set' && s.state && s.on
1554
+ ? (() => {
1555
+ const prop =
1556
+ s.thing === 'corners' || /radius$/.test(s.thing)
1557
+ ? 'borderRadius'
1558
+ : s.thing === 'padding' || s.thing === 'spacing'
1559
+ ? 'padding'
1560
+ : s.thing.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
1561
+ const vars = parts.flatMap(t =>
1562
+ (ctx.derived?.[t] ?? [])
1563
+ .filter(d => d.property === prop)
1564
+ .flatMap(d => d.vars ?? []),
1565
+ );
1566
+ return vars.length
1567
+ ? [
1568
+ `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`,
1569
+ ]
1570
+ : [];
1571
+ })()
1572
+ : []),
989
1573
  // Phones keep the base theme's reading sizes (a coarse pointer below
990
1574
  // the lg width), so a size change says where it applies.
991
1575
  ...(sub === 'set' &&
@@ -1003,14 +1587,30 @@ async function change(sub, slug, thing, value, options) {
1003
1587
  // An exact property on the same part wins over a dial there.
1004
1588
  ...(exactOver
1005
1589
  ? [
1006
- `${describe(exactOver)} is an exact property and wins over ${s.thing} there, so this shows only after \`${P} undo ${slug} ${undoArgs(exactOver)}\``,
1590
+ ownPartHits.length
1591
+ ? `${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`
1592
+ : `${describe(exactOver)} is an exact property and wins over ${s.thing} there, so this shows only after \`${P} undo ${slug} ${undoArgs(exactOver)}\``,
1593
+ ]
1594
+ : []),
1595
+ // A whole-theme font under fonts set for each role shows only where no
1596
+ // role font is set.
1597
+ ...(roleOver.length
1598
+ ? [
1599
+ `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
1600
  ]
1008
1601
  : []),
1009
1602
  // An accepted change that the theme already showed says so.
1010
1603
  ...(sub === 'set' &&
1011
1604
  !exactOver &&
1012
- // With the last build unreadable, nothing was compared.
1013
- !r.notes.some(n => n.includes('could not be read')) &&
1605
+ !roleOver.length &&
1606
+ !ownOverToken &&
1607
+ !ownPartHits.length &&
1608
+ // With the last build unreadable or missing, nothing was compared.
1609
+ !r.notes.some(
1610
+ n =>
1611
+ n.includes('could not be read') ||
1612
+ n.includes('there was no last build'),
1613
+ ) &&
1014
1614
  !r.unchanged &&
1015
1615
  !r.changed.length &&
1016
1616
  !styled.length &&
@@ -1019,6 +1619,23 @@ async function change(sub, slug, thing, value, options) {
1019
1619
  `this changes nothing you see: the theme already shows ${describe(s)} (it is saved, and stays when the base theme changes)`,
1020
1620
  ]
1021
1621
  : []),
1622
+ // A card's content takes one radius from Core, whatever its corners.
1623
+ ...(sub === 'set' &&
1624
+ s.source === 'property' &&
1625
+ s.thing === 'border-radius' &&
1626
+ s.on &&
1627
+ (ctx.derived?.[s.on] ?? []).some(
1628
+ d => d.property === 'borderRadius' && d.vars?.length,
1629
+ ) &&
1630
+ /\s|\//.test(String(s.value).trim())
1631
+ ? [
1632
+ `each corner of ${s.on} takes its own radius; the content that reaches its edges takes one, ${
1633
+ String(s.value)
1634
+ .trim()
1635
+ .split(/[\s/]+/)[0]
1636
+ }, for every corner (Core gives it a single radius)`,
1637
+ ]
1638
+ : []),
1022
1639
  ...(longhands.length
1023
1640
  ? [
1024
1641
  `${s.thing} comes after ${longhands.map(x => x.thing).join(', ')} on ${s.on}, so it replaces them there`,
@@ -1039,6 +1656,20 @@ async function change(sub, slug, thing, value, options) {
1039
1656
  : null
1040
1657
  : null;
1041
1658
  if (s.note) notes.push(s.note);
1659
+ // A token the theme's own source sets itself wins over what this dial
1660
+ // writes, as an exact setting does.
1661
+ const ownWins = ownSourceTokens(cwd, slug).filter(
1662
+ k =>
1663
+ (dialTokens.has(k) ||
1664
+ // A role font writes --font-family-<role>.
1665
+ (s.thing === 'font' && s.on && k === `--font-family-${s.on}`)) &&
1666
+ !exactWins.some(x => x.thing === k),
1667
+ );
1668
+ const ownSet = new Set(ownSourceTokens(cwd, slug));
1669
+ if (ownWins.length)
1670
+ notes.push(
1671
+ `${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)}`,
1672
+ );
1042
1673
  if (PALETTE_DIALS.includes(s.thing) && sub === 'set')
1043
1674
  notes.push(
1044
1675
  ...paletteNotes(
@@ -1046,7 +1677,31 @@ async function change(sub, slug, thing, value, options) {
1046
1677
  s.thing,
1047
1678
  slug,
1048
1679
  modesOf(data),
1049
- ),
1680
+ )
1681
+ // A shade the mapping would pick for a token the theme's own source
1682
+ // sets never shows: the file's value does (named once above).
1683
+ .filter(n => {
1684
+ const subject = /^(?:in (?:light|dark), )?(--[a-z0-9-]+) /.exec(
1685
+ n,
1686
+ )?.[1];
1687
+ return (
1688
+ !subject ||
1689
+ !ownSet.has(subject) ||
1690
+ / uses your exact setting \(/.test(n)
1691
+ );
1692
+ })
1693
+ .map(n => {
1694
+ // The exact color is the one the theme's own source sets: named so.
1695
+ const token = n.split(' ')[0];
1696
+ return ownSet.has(token) && / uses your exact setting \(/.test(n)
1697
+ ? n
1698
+ .replace(
1699
+ ' uses your exact setting (',
1700
+ ` uses the value ${slug}.theme.ts sets (`,
1701
+ )
1702
+ .replace('an exact setting wins', 'your own source wins')
1703
+ : n;
1704
+ }),
1050
1705
  );
1051
1706
  // An exact color the mapping reads (a fill, a tint, text on a fill)
1052
1707
  // changes what it picks around it: say what, as the dial does.
@@ -1104,8 +1759,13 @@ async function change(sub, slug, thing, value, options) {
1104
1759
  if (s.thing === 'font' && sub === 'set')
1105
1760
  notes.unshift(...fontNotes(ctx, {...data, settings: [s]}));
1106
1761
  if (s.thing === 'type' || s.thing === 'headings')
1107
- for (const [m, why] of maskedSettings(data))
1762
+ for (const [m, why] of maskedSettings(data, ctx))
1108
1763
  notes.push(`${describe(m)}: ${why}`);
1764
+ // An earlier setting this one now covers (through a spread too) is named.
1765
+ else if (sub === 'set')
1766
+ for (const [m, why] of maskedSettings(data, ctx))
1767
+ if (m !== s && why.startsWith(describe(s)))
1768
+ notes.push(`${describe(m)} no longer shows: ${why}`);
1109
1769
  if (s.thing === 'type' && sub === 'set' && TYPE_STYLES[s.value].ratio > 1.2)
1110
1770
  notes.push(
1111
1771
  'text below the base size keeps its standard sizes, so small text stays readable',
@@ -1235,22 +1895,119 @@ export async function themeEditShow(theme, options = {}) {
1235
1895
  ? [installLine(cwd, ['react', 'react-dom'])]
1236
1896
  : // Two copies of React and other install problems are named by
1237
1897
  // doctor; the same show would fail the same way.
1238
- ['astryx doctor'],
1898
+ [`${getCliInvocation(cwd)} doctor`],
1239
1899
  },
1240
1900
  );
1241
1901
  const f = themeFiles(cwd, theme);
1242
1902
  // A build that does not match the settings (a command stopped mid-build,
1243
1903
  // a hand edit, another CLI) is made again from the settings, and said.
1244
- const stale = staleBuild(cwd, theme, data);
1904
+ // An own source that does not parse is refused before anything is
1905
+ // built, written or removed (the build would fail part way).
1906
+ if (!readOnly) refuseThemeParse(cwd, theme);
1245
1907
  const brokenSource = themeSourceProblem(cwd, theme);
1246
- if (stale && !brokenSource && !readOnly) await buildTheme(ctx, theme, data);
1908
+ // Every output, as `compile --check` reads them: one missing or edited by
1909
+ // hand is built again too.
1910
+ let stale = staleBuild(cwd, theme, data);
1911
+ // An own source changed since the editor's build, whose outputs a build
1912
+ // of it now makes as they are (it was compiled since): current, as
1913
+ // `compile --check` reads it, so the editor records the source it was
1914
+ // built with instead of building again. One rule for both.
1915
+ if (
1916
+ stale === sourceChangedReason(theme) &&
1917
+ !brokenSource &&
1918
+ !(await outputsDrift(ctx, theme))
1919
+ ) {
1920
+ if (!readOnly) refreshSourceStamp(cwd, theme);
1921
+ stale = readOnly ? stale : staleBuild(cwd, theme, data);
1922
+ }
1923
+ stale ||= brokenSource ? null : await outputsDrift(ctx, theme);
1924
+ // Every file the build may rewrite or remove (the settings module, the
1925
+ // built outputs, the variants types, section sheets, pictures), so a
1926
+ // theme source that does not build, or builds a value that is not text,
1927
+ // leaves the folder exactly as it was.
1928
+ // An output that was not there is recorded as absent (null), so putting
1929
+ // the folder back removes what the build made new; the palette files in
1930
+ // tokens/ are recorded the same way.
1931
+ /** @type {Map<string, Buffer | null>} */
1932
+ let kept = new Map();
1933
+ const tokensDir = path.join(f.dir, 'tokens');
1934
+ if (stale && !brokenSource && !readOnly) {
1935
+ kept = new Map(
1936
+ fs
1937
+ .readdirSync(f.dir)
1938
+ .filter(
1939
+ n =>
1940
+ n === path.basename(f.settingsTs) ||
1941
+ (n.startsWith(`${theme}.`) &&
1942
+ /\.(css|js|d\.ts|css\.d\.ts|variants\.d\.ts)$/.test(n)) ||
1943
+ /^(sheet-[a-z-]+\.html|(sheet|preview)(-[a-z-]+)?\.png)$/.test(n),
1944
+ )
1945
+ .map(n => [path.join(f.dir, n), fs.readFileSync(path.join(f.dir, n))]),
1946
+ );
1947
+ for (const n of [
1948
+ path.basename(f.settingsTs),
1949
+ `${theme}.css`,
1950
+ `${theme}.js`,
1951
+ `${theme}.d.ts`,
1952
+ `${theme}.css.d.ts`,
1953
+ `${theme}.variants.d.ts`,
1954
+ ])
1955
+ if (!kept.has(path.join(f.dir, n))) kept.set(path.join(f.dir, n), null);
1956
+ if (fs.existsSync(tokensDir))
1957
+ for (const n of fs.readdirSync(tokensDir)) {
1958
+ const file = path.join(tokensDir, n);
1959
+ if (fs.statSync(file).isFile()) kept.set(file, fs.readFileSync(file));
1960
+ }
1961
+ const refs = path.join(tokensDir, `${theme}.palette-refs.ts`);
1962
+ if (!kept.has(refs)) kept.set(refs, null);
1963
+ try {
1964
+ await buildTheme(ctx, theme, data);
1965
+ } catch (e) {
1966
+ putBack(kept, tokensDir);
1967
+ if (e instanceof AstryxError && e.code !== E.ERR_THEME_LOAD) throw e;
1968
+ // An own theme source that no longer builds is named, as `set` names
1969
+ // it; the old build is never shown as current.
1970
+ const why = (e instanceof Error ? e.message : String(e))
1971
+ .split(`${cwd}${path.sep}`)
1972
+ .join('')
1973
+ .replace(/\s*Make sure all imports[^|]*$/s, '')
1974
+ .split('\n')
1975
+ .slice(0, 3)
1976
+ .join(' | ');
1977
+ refuse(
1978
+ E.ERR_THEME_INVALID,
1979
+ `${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)` : ''}`,
1980
+ {run: [`${P} how --list dials`]},
1981
+ );
1982
+ }
1983
+ }
1247
1984
  // The settings loaded whole: a `new` marker beside them is stale.
1248
1985
  if (!readOnly) clearNewMarker(f.dir);
1249
1986
  // A built module that cannot be read (damaged by hand) is built again.
1250
1987
  /** @type {string | null} */
1251
1988
  let unreadable = null;
1252
1989
  const res = await resolvedTokens(ctx, theme).catch(async e => {
1990
+ if (
1991
+ e instanceof AstryxError &&
1992
+ e.code === E.ERR_THEME_INVALID &&
1993
+ kept.size
1994
+ ) {
1995
+ // What this show just built goes back with the refusal.
1996
+ putBack(kept, tokensDir);
1997
+ throw e;
1998
+ }
1253
1999
  if (e instanceof AstryxError || readOnly) throw e;
2000
+ // The source lines the settings need are missing too: the build cannot
2001
+ // be made again until they are back, and show says so (never a run of
2002
+ // show itself).
2003
+ if (brokenSource)
2004
+ refuse(
2005
+ E.ERR_THEME_INVALID,
2006
+ `${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.`,
2007
+ {
2008
+ run: [`cat ${quoteCommandArgument(shown(cwd, f.ts))}`],
2009
+ },
2010
+ );
1254
2011
  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
2012
  await buildTheme(ctx, theme, data);
1256
2013
  return resolvedTokens(ctx, theme);
@@ -1265,13 +2022,40 @@ export async function themeEditShow(theme, options = {}) {
1265
2022
  await baseResolved(ctx.project, data.like),
1266
2023
  ctx.project.core.tokenDefaults,
1267
2024
  );
2025
+ // A render that fails here (two copies of React, a component that
2026
+ // throws) is refused as the one above: what this show built goes back,
2027
+ // and the result says so.
2028
+ const rendering = async (/** @type {() => Promise<any>} */ run) => {
2029
+ try {
2030
+ return await run();
2031
+ } catch (e) {
2032
+ if (!(e instanceof Error)) throw e;
2033
+ if (e instanceof AstryxError && e.code !== E.ERR_RENDER_FAILED) throw e;
2034
+ putBack(kept, tokensDir);
2035
+ return refuse(
2036
+ E.ERR_RENDER_FAILED,
2037
+ `${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.`,
2038
+ {run: [`${getCliInvocation(cwd)} doctor`]},
2039
+ );
2040
+ }
2041
+ };
1268
2042
  const preview = noPages
1269
2043
  ? shown(cwd, f.preview)
1270
- : await renderPreview(ctx, theme, data);
1271
- const previewStale = noPages ? [] : await keepPreviewRoute(ctx, theme);
2044
+ : await rendering(() => renderPreview(ctx, theme, data));
2045
+ const previewStale = noPages
2046
+ ? []
2047
+ : await rendering(() => keepPreviewRoute(ctx, theme));
1272
2048
  const sheet = noPages
1273
2049
  ? {file: shown(cwd, f.sheet), components: 0, skipped: []}
1274
- : await renderSheet(ctx, theme, data, {group: section});
2050
+ : await rendering(() => renderSheet(ctx, theme, data, {group: section}));
2051
+ // The full sheet records the build it shows, so a later change tells a
2052
+ // sheet that still matches (after an undo) from one that does not.
2053
+ if (!noPages)
2054
+ stampSheet(
2055
+ section ? path.join(f.dir, `sheet-${section}.html`) : f.sheet,
2056
+ theme,
2057
+ cwd,
2058
+ );
1275
2059
  const modes = modesOf(data);
1276
2060
  const shots =
1277
2061
  png && !noPages
@@ -1296,10 +2080,32 @@ export async function themeEditShow(theme, options = {}) {
1296
2080
  theme,
1297
2081
  like: data.like ?? null,
1298
2082
  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
- }),
2083
+ settings: await (async () => {
2084
+ const looksBase = await baseResolved(ctx.project, data.like).catch(
2085
+ () => null,
2086
+ );
2087
+ return data.settings.map(s => {
2088
+ let masked = maskedSettings(data, ctx).get(s);
2089
+ // A look dial (buttons, surfaces) under an exact property on a
2090
+ // part it writes: named, as corners under border-radius is.
2091
+ if (!masked && looksBase && s.source === 'dial' && !s.on) {
2092
+ const writes = dialWrites(ctx, data, s, looksBase);
2093
+ const exact = writes.size
2094
+ ? data.settings.find(
2095
+ x =>
2096
+ x.source === 'property' &&
2097
+ x.on &&
2098
+ !x.when &&
2099
+ !x.state &&
2100
+ partsOf(ctx, x).some(t => writes.has(`${t}\0${x.thing}`)),
2101
+ )
2102
+ : undefined;
2103
+ if (exact)
2104
+ masked = `${describe(exact)} is an exact property and wins over ${s.thing} on ${exact.on}`;
2105
+ }
2106
+ return {...s, parts: partsOf(ctx, s), ...(masked ? {masked} : {})};
2107
+ });
2108
+ })(),
1303
2109
  notes: [
1304
2110
  ...(noReact
1305
2111
  ? [
@@ -1310,19 +2116,32 @@ export async function themeEditShow(theme, options = {}) {
1310
2116
  ? [
1311
2117
  `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
2118
  ]
1313
- : stale
2119
+ : stale && !brokenSource
1314
2120
  ? [
1315
- `the build did not match ${theme}.settings.json (${stale}), so it was built again from the settings`,
2121
+ `the build was not current (${stale}), so it was built again from the settings`,
1316
2122
  ]
1317
- : []),
2123
+ : stale
2124
+ ? [
2125
+ `the build is not current (${stale}), and it was not built again: the theme source cannot carry the settings`,
2126
+ ]
2127
+ : []),
1318
2128
  ...(unreadable ? [unreadable] : []),
1319
2129
  ...(brokenSource
1320
2130
  ? [
1321
- `${brokenSource}, so settings cannot take effect; put back the import, extends and name lines in ${theme}.theme.ts`,
2131
+ `${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
2132
  ]
1323
2133
  : []),
1324
2134
  ...checked.filter(x => x.startsWith('not checked')),
1325
2135
  ...fontNotes(ctx, data),
2136
+ ...ownSourceMaskNotes(
2137
+ ctx,
2138
+ cwd,
2139
+ theme,
2140
+ data,
2141
+ await baseResolved(ctx.project, data.like),
2142
+ ),
2143
+ ...ownOverSettingNotes(cwd, theme, data),
2144
+ ...ownPhoneNotes(cwd, theme, data),
1326
2145
  ],
1327
2146
  // A size, number or font is the same in both modes: one value.
1328
2147
  resolved: Object.fromEntries(
@@ -1339,7 +2158,7 @@ export async function themeEditShow(theme, options = {}) {
1339
2158
  res,
1340
2159
  modes[0],
1341
2160
  ),
1342
- ...colorsReport(pal, data),
2161
+ ...colorsReport(pal, data, res, theme),
1343
2162
  problems,
1344
2163
  preview,
1345
2164
  previewStale,
@@ -1353,6 +2172,39 @@ export async function themeEditShow(theme, options = {}) {
1353
2172
  };
1354
2173
  }
1355
2174
 
2175
+ /**
2176
+ * The part properties a dial writes, read from what the build writes with
2177
+ * it and without it (so a dial's outputs are never listed by hand), as
2178
+ * `target\0css-property` keys.
2179
+ * @param {import('./_settings.mjs').Ctx} ctx
2180
+ * @param {import('./_settings.mjs').ThemeData} data
2181
+ * @param {import('./_settings.mjs').Setting} dial
2182
+ * @param {{light: Record<string, string>, dark: Record<string, string>}} base
2183
+ * @returns {Set<string>}
2184
+ */
2185
+ function dialWrites(ctx, data, dial, base) {
2186
+ /** @type {Set<string>} */
2187
+ const out = new Set();
2188
+ const comps = (/** @type {import('./_settings.mjs').Setting[]} */ settings) =>
2189
+ /** @type {Record<string, Record<string, Record<string, unknown>>>} */ (
2190
+ compileTheme(ctx, {...data, settings}, base).components ?? {}
2191
+ );
2192
+ let plain;
2193
+ let withDial;
2194
+ try {
2195
+ plain = comps([]);
2196
+ withDial = comps([dial]);
2197
+ } catch {
2198
+ return out;
2199
+ }
2200
+ for (const [target, keys] of Object.entries(withDial))
2201
+ for (const [key, block] of Object.entries(keys ?? {}))
2202
+ for (const [prop, value] of Object.entries(block ?? {}))
2203
+ if (typeof value === 'string' && plain[target]?.[key]?.[prop] !== value)
2204
+ out.add(`${target}\0${kebab(prop)}`);
2205
+ return out;
2206
+ }
2207
+
1356
2208
  /**
1357
2209
  * What applies once `removed` is gone: a whole-theme setting of the same
1358
2210
  * thing for a part setting, a dial that still writes the token, or the
@@ -1364,6 +2216,44 @@ export async function themeEditShow(theme, options = {}) {
1364
2216
  * @returns {string}
1365
2217
  */
1366
2218
  function nowApplies(ctx, data, removed, base) {
2219
+ // A token the theme's own source sets shows its value, whatever else
2220
+ // the settings give it.
2221
+ if (removed.source === 'token' && !removed.on && !removed.when) {
2222
+ const own = ownSourceTokenValues(ctx.project.cwd, data.name)[removed.thing];
2223
+ if (own != null)
2224
+ return `${removed.thing} = ${own} (set in ${data.name}.theme.ts)`;
2225
+ }
2226
+ // On a part, the same for what the own source sets on that part's rule.
2227
+ if (
2228
+ (removed.source === 'token' || removed.source === 'property') &&
2229
+ removed.on &&
2230
+ !removed.state
2231
+ ) {
2232
+ const own = ownPartTokens(
2233
+ ctx.project.cwd,
2234
+ data.name,
2235
+ removed.on,
2236
+ removed.when ?? 'base',
2237
+ );
2238
+ if (own.has(removed.thing))
2239
+ return `${removed.thing} = ${own.get(removed.thing) ?? 'its value'} on ${removed.on}${removed.when ? ` when ${removed.when}` : ''} (set in ${data.name}.theme.ts)`;
2240
+ }
2241
+ // A role font removed under an exact --font-family-<role>: that token is
2242
+ // what shows there.
2243
+ if (
2244
+ removed.thing === 'font' &&
2245
+ removed.on &&
2246
+ FONT_ROLES.includes(removed.on)
2247
+ ) {
2248
+ const exact = data.settings.find(
2249
+ x =>
2250
+ x.source === 'token' &&
2251
+ !x.on &&
2252
+ !x.when &&
2253
+ x.thing === `--font-family-${removed.on}`,
2254
+ );
2255
+ if (exact) return describe(exact);
2256
+ }
1367
2257
  // A token a dial still writes (an accent color feeds --color-accent):
1368
2258
  // name that dial.
1369
2259
  if (removed.source === 'token' && !removed.on) {
@@ -1387,21 +2277,35 @@ function nowApplies(ctx, data, removed, base) {
1387
2277
  // exact property on the part that this dial would have competed with.
1388
2278
  if (removed.on) {
1389
2279
  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
- );
2280
+ // The part's or its group's setting for the same variant and state
2281
+ // first (a group's hover after the part's hover goes), then a plain one.
2282
+ /** @param {(x: import('./_settings.mjs').Setting) => boolean} scoped */
2283
+ const find = scoped =>
2284
+ [...data.settings]
2285
+ .reverse()
2286
+ .find(
2287
+ x =>
2288
+ x.thing === removed.thing &&
2289
+ x !== removed &&
2290
+ (!x.mode || x.mode === removed.mode) &&
2291
+ (x.on === removed.on || (fam != null && x.on === fam)) &&
2292
+ scoped(x),
2293
+ );
2294
+ const reaches =
2295
+ (removed.when || removed.state
2296
+ ? find(
2297
+ x =>
2298
+ (x.when ?? '') === (removed.when ?? '') &&
2299
+ (x.state ?? '') === (removed.state ?? ''),
2300
+ )
2301
+ : undefined) ?? find(x => !x.when && !x.state);
1400
2302
  if (reaches) return describe(reaches);
1401
- const DIAL_PROPERTY = /** @type {Record<string, RegExp>} */ ({
1402
- corners: /radius$/,
1403
- spacing: /^(padding|gap)(-|$)/,
1404
- });
2303
+ const DIAL_PROPERTY = wordTable(
2304
+ /** @type {Record<string, RegExp>} */ ({
2305
+ corners: /radius$/,
2306
+ spacing: /^(padding|gap)(-|$)/,
2307
+ }),
2308
+ );
1405
2309
  const exact =
1406
2310
  removed.source === 'dial' && DIAL_PROPERTY[removed.thing]
1407
2311
  ? data.settings.find(
@@ -1412,8 +2316,25 @@ function nowApplies(ctx, data, removed, base) {
1412
2316
  )
1413
2317
  : null;
1414
2318
  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.
2319
+ // A removed exact property leaves the dial whose build writes it there
2320
+ // (buttons, surfaces: read from the build), on the part, its group, or
2321
+ // the whole theme.
2322
+ if (removed.source === 'property') {
2323
+ const targets = partsOf(ctx, removed);
2324
+ const writer = [...data.settings].reverse().find(
2325
+ x =>
2326
+ x.source === 'dial' &&
2327
+ x !== removed &&
2328
+ (!x.on || x.on === removed.on || (fam != null && x.on === fam)) &&
2329
+ (x.when ?? '') === (removed.when ?? '') &&
2330
+ (x.state ?? '') === (removed.state ?? '') &&
2331
+ [...dialWrites(ctx, data, x, base)].some(k => {
2332
+ const [t, prop] = k.split('\0');
2333
+ return targets.includes(t) && prop === removed.thing;
2334
+ }),
2335
+ );
2336
+ if (writer) return describe(writer);
2337
+ }
1417
2338
  if (removed.source === 'property') {
1418
2339
  const dial = Object.entries(DIAL_PROPERTY).find(([, re]) =>
1419
2340
  re.test(removed.thing),
@@ -1469,6 +2390,162 @@ function otherModeNotes(data) {
1469
2390
  ];
1470
2391
  }
1471
2392
 
2393
+ /**
2394
+ * The tokens a whole-theme dial setting writes: those that differ between
2395
+ * the theme's dials with it and without it (a font role's family, and every
2396
+ * text size when the scale moves).
2397
+ * @param {import('./_settings.mjs').Ctx} ctx
2398
+ * @param {import('./_settings.mjs').ThemeData} data
2399
+ * @param {import('./_settings.mjs').Setting} s
2400
+ * @param {any} base
2401
+ * @returns {Set<string>}
2402
+ */
2403
+ function dialTouched(ctx, data, s, base) {
2404
+ /** @param {import('./_settings.mjs').Setting[]} list */
2405
+ const dialsOnly = list => ({
2406
+ ...data,
2407
+ settings: list.filter(x => x.source === 'dial'),
2408
+ });
2409
+ const withDial = compileTheme(ctx, dialsOnly(data.settings), base);
2410
+ const without = compileTheme(
2411
+ ctx,
2412
+ dialsOnly(data.settings.filter(x => x !== s)),
2413
+ base,
2414
+ );
2415
+ const differs = (/** @type {unknown} */ a, /** @type {unknown} */ b) =>
2416
+ JSON.stringify(a) !== JSON.stringify(b);
2417
+ const touched = new Set(
2418
+ [
2419
+ ...Object.keys(withDial.tokens ?? {}),
2420
+ ...Object.keys(without.tokens ?? {}),
2421
+ ].filter(k => differs(withDial.tokens?.[k], without.tokens?.[k])),
2422
+ );
2423
+ for (const r of FONT_ROLES)
2424
+ if (differs(withDial.typography?.[r], without.typography?.[r]))
2425
+ touched.add(`--font-family-${r}`);
2426
+ // The type scale feeds every font size and every role size (body,
2427
+ // headings, labels): an exact one of those keeps its text as it is.
2428
+ if (differs(withDial.typography?.scale, without.typography?.scale))
2429
+ for (const k of Object.keys(ctx.project.core.tokenDefaults ?? {}))
2430
+ if (/^--(font-size-|text-[a-z0-9-]+-size$)/.test(k)) touched.add(k);
2431
+ return touched;
2432
+ }
2433
+
2434
+ /**
2435
+ * The family and weight tokens the theme's own source sets that phones do
2436
+ * not show: on top of a base theme, its phone rule puts its own type back
2437
+ * there (a Core limit), unless an exact setting is repeated after it.
2438
+ * @param {string} cwd
2439
+ * @param {string} slug
2440
+ * @param {import('./_settings.mjs').ThemeData} data
2441
+ * @returns {string[]}
2442
+ */
2443
+ function ownPhoneNotes(cwd, slug, data) {
2444
+ if (!data.like) return [];
2445
+ const exact = new Set(
2446
+ data.settings
2447
+ .filter(x => x.source === 'token' && !x.on && !x.when && !x.state)
2448
+ .map(x => x.thing),
2449
+ );
2450
+ const lost = ownSourceTokens(cwd, slug).filter(
2451
+ k => PHONE_TYPE.test(k) && !exact.has(k),
2452
+ );
2453
+ if (!lost.length) return [];
2454
+ return [
2455
+ `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: the base theme sets its type again there, after your file (a Core limit); wide screens show your file's`,
2456
+ ];
2457
+ }
2458
+
2459
+ /**
2460
+ * Notes for the exact settings the theme's own source sets itself (a
2461
+ * whole-theme token, or a token or property on a part's plain or variant
2462
+ * rule): the file's value shows, not the setting.
2463
+ * @param {string} cwd
2464
+ * @param {string} slug
2465
+ * @param {import('./_settings.mjs').ThemeData} data
2466
+ * @returns {string[]}
2467
+ */
2468
+ function ownOverSettingNotes(cwd, slug, data) {
2469
+ const top = ownSourceTokenValues(cwd, slug);
2470
+ const topKeys = new Set(ownSourceTokens(cwd, slug));
2471
+ /** @type {Map<string, Map<string, string | null>>} */
2472
+ const parts = new Map();
2473
+ /** @type {string[]} */
2474
+ const out = [];
2475
+ for (const x of data.settings) {
2476
+ if (x.state || (x.source !== 'token' && x.source !== 'property')) continue;
2477
+ if (!x.on) {
2478
+ if (x.source === 'token' && !x.when && topKeys.has(x.thing))
2479
+ out.push(
2480
+ `${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)` : ''}`,
2481
+ );
2482
+ continue;
2483
+ }
2484
+ const key = `${x.on}\0${x.when ?? 'base'}`;
2485
+ if (!parts.has(key))
2486
+ parts.set(key, ownPartTokens(cwd, slug, x.on, x.when ?? 'base'));
2487
+ const own = /** @type {Map<string, string | null>} */ (parts.get(key));
2488
+ if (own.has(x.thing))
2489
+ out.push(
2490
+ `${describe(x)}: ${slug}.theme.ts sets ${x.thing} on ${x.on}${x.when ? ` when ${x.when}` : ''} itself${own.get(x.thing) != null ? ` (${own.get(x.thing)})` : ''}, so this setting does not show there`,
2491
+ );
2492
+ }
2493
+ return out;
2494
+ }
2495
+
2496
+ /** Phones, as the base themes' type rule names them. */
2497
+ const PHONES = 'phones (touch screens below 1024px)';
2498
+
2499
+ /**
2500
+ * What taking tokens out of the theme file lets show: the dial, or an
2501
+ * exact setting of a token first (file > exact > dial), with its undo.
2502
+ * @param {string} slug
2503
+ * @param {string} dial the dial's name
2504
+ * @param {string[]} tokens
2505
+ * @param {import('./_settings.mjs').ThemeData} data
2506
+ */
2507
+ function ownTakeOut(slug, dial, tokens, data) {
2508
+ const it = tokens.length > 1 ? 'them' : 'it';
2509
+ const exact = data.settings.filter(
2510
+ x =>
2511
+ x.source === 'token' &&
2512
+ !x.on &&
2513
+ !x.when &&
2514
+ !x.state &&
2515
+ tokens.includes(x.thing),
2516
+ );
2517
+ if (!exact.length)
2518
+ return `take ${it} out of ${slug}.theme.ts to let ${dial} set ${it}`;
2519
+ 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}`;
2520
+ }
2521
+
2522
+ /**
2523
+ * Notes for the tokens the theme's own source sets that a whole-theme dial
2524
+ * also writes: the source wins, so the dial does not change them.
2525
+ * @param {import('./_settings.mjs').Ctx} ctx
2526
+ * @param {string} cwd
2527
+ * @param {string} slug
2528
+ * @param {import('./_settings.mjs').ThemeData} data
2529
+ * @param {any} base
2530
+ * @returns {string[]}
2531
+ */
2532
+ function ownSourceMaskNotes(ctx, cwd, slug, data, base) {
2533
+ const own = ownSourceTokens(cwd, slug);
2534
+ if (!own.length) return [];
2535
+ /** @type {string[]} */
2536
+ const notes = [];
2537
+ for (const s of data.settings) {
2538
+ if (s.source !== 'dial' || s.on || s.when || s.state) continue;
2539
+ const touched = dialTouched(ctx, data, s, base);
2540
+ const wins = own.filter(k => touched.has(k));
2541
+ if (wins.length)
2542
+ notes.push(
2543
+ `${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)}`,
2544
+ );
2545
+ }
2546
+ return notes;
2547
+ }
2548
+
1472
2549
  /**
1473
2550
  * Each corners or spacing dial set on a part or group, with what its parts
1474
2551
  * get, beside the whole-theme value: `corners large on containers ->
@@ -1481,7 +2558,7 @@ function otherModeNotes(data) {
1481
2558
  * @returns {string[]}
1482
2559
  */
1483
2560
  function partValues(ctx, data, res, mode) {
1484
- const masked = maskedSettings(data);
2561
+ const masked = maskedSettings(data, ctx);
1485
2562
  return data.settings
1486
2563
  .filter(
1487
2564
  s =>
@@ -1554,9 +2631,13 @@ function partValues(ctx, data, res, mode) {
1554
2631
  * says so), and the contrast moves behind the shade choices.
1555
2632
  * @param {import('./_palette.mjs').PaletteMapping | null} pal
1556
2633
  * @param {import('./_settings.mjs').ThemeData} data
2634
+ * @param {Record<'light' | 'dark', Record<string, string>>} [built] the
2635
+ * built theme's resolved values: where one differs from the generated
2636
+ * shade with no exact setting, the theme's own source changed it
2637
+ * @param {string} [slug]
1557
2638
  * @returns {{vibrancy: number | null, colors: import('./theme-edit.type.mjs').ThemeEditColor[], colorNotes: string[]}}
1558
2639
  */
1559
- function colorsReport(pal, data) {
2640
+ function colorsReport(pal, data, built, slug = '') {
1560
2641
  if (!pal) return {vibrancy: null, colors: [], colorNotes: []};
1561
2642
  /** What the user set for each token exactly, in each mode. */
1562
2643
  const exactBy =
@@ -1566,6 +2647,19 @@ function colorsReport(pal, data) {
1566
2647
  for (const m of s.mode ? [s.mode] : ['light', 'dark'])
1567
2648
  (exactBy[s.thing] ??= {})[/** @type {'light' | 'dark'} */ (m)] =
1568
2649
  s.value;
2650
+ /** Tokens the theme's own source sets to another value than generated. */
2651
+ const ownBy =
2652
+ /** @type {Record<string, {light?: string, dark?: string}>} */ ({});
2653
+ for (const [k, v] of Object.entries(pal.tokens))
2654
+ for (const m of /** @type {const} */ (['light', 'dark'])) {
2655
+ const now = built?.[m]?.[k];
2656
+ if (
2657
+ now &&
2658
+ !exactBy[k]?.[m] &&
2659
+ now.trim().toLowerCase() !== String(v[m].color).trim().toLowerCase()
2660
+ )
2661
+ (ownBy[k] ??= {})[m] = now;
2662
+ }
1569
2663
  /** @param {import('./_palette.mjs').StopRef} r */
1570
2664
  const shade = r =>
1571
2665
  r.family === 'black' || r.family === 'white'
@@ -1587,12 +2681,14 @@ function colorsReport(pal, data) {
1587
2681
  k,
1588
2682
  // Each mode says what it shows: the exact setting where one is
1589
2683
  // made for it, else the generated shade.
1590
- exactBy[k]
2684
+ exactBy[k] || ownBy[k]
1591
2685
  ? modes
1592
2686
  .map(m =>
1593
- exactBy[k][m] != null
2687
+ exactBy[k]?.[m] != null
1594
2688
  ? `${m} ${exactBy[k][m]} (your exact setting wins over the generated ${shade(v[m])})`
1595
- : `${m} ${shade(v[m])}`,
2689
+ : ownBy[k]?.[m] != null
2690
+ ? `${m} ${ownBy[k][m]} (your change in ${slug}.theme.ts wins over the generated ${shade(v[m])})`
2691
+ : `${m} ${shade(v[m])}`,
1596
2692
  )
1597
2693
  .join(', ')
1598
2694
  : shades(v),
@@ -1600,9 +2696,22 @@ function colorsReport(pal, data) {
1600
2696
  ),
1601
2697
  })),
1602
2698
  colorNotes: [
1603
- ...pal.notes,
2699
+ // A note about a token the theme's own source changed is dropped:
2700
+ // what it says no longer holds.
2701
+ ...pal.notes.filter(
2702
+ n =>
2703
+ !Object.keys(ownBy).some(k =>
2704
+ new RegExp(`${k.replace(/[-]/g, '\\-')}(?![\\w-])`).test(n),
2705
+ ),
2706
+ ),
1604
2707
  ...pal.contrast
1605
2708
  .filter(c => modes.includes(c.mode))
2709
+ // A pairing the theme's own source changed no longer holds.
2710
+ .filter(
2711
+ c =>
2712
+ !ownBy[c.token]?.[/** @type {'light' | 'dark'} */ (c.mode)] &&
2713
+ !ownBy[c.against]?.[/** @type {'light' | 'dark'} */ (c.mode)],
2714
+ )
1606
2715
  .filter(c => c.note || !c.pass || c.stop !== c.preferred)
1607
2716
  .map(c =>
1608
2717
  c.note
@@ -1611,7 +2720,12 @@ function colorsReport(pal, data) {
1611
2720
  ? `${c.token} ${c.mode}: shade ${c.stop}, not ${c.preferred}, so it reads at ${c.ratio}:1 on ${c.against}`
1612
2721
  : `${c.token} ${c.mode}: only ${c.ratio}:1 on ${c.against} at shade ${c.stop} (needs ${c.needs}:1)`,
1613
2722
  ),
1614
- ],
2723
+ ].filter(
2724
+ n =>
2725
+ !Object.keys(ownBy).some(k =>
2726
+ new RegExp(`${k.replace(/[-]/g, '\\-')}(?![\\w-])`).test(n),
2727
+ ),
2728
+ ),
1615
2729
  };
1616
2730
  }
1617
2731
 
@@ -1640,7 +2754,16 @@ export async function themeEditUndo(theme, options = {}) {
1640
2754
  if (thing === 'base' || thing === 'mode') {
1641
2755
  requireProject(cwd);
1642
2756
  const now = loadTheme(cwd, theme, thing);
1643
- const [first] = readHistory(themeFiles(cwd, theme).history).steps;
2757
+ const historyFile = themeFiles(cwd, theme).history;
2758
+ const {steps, dropped} = readHistory(historyFile);
2759
+ const [first] = steps;
2760
+ // `new` writes no history: with none, no change is saved (a new theme,
2761
+ // or a history deleted). An empty one is every step undone, back to how
2762
+ // the theme was made. A full one may have lost its oldest steps.
2763
+ const noHistory = !fs.existsSync(historyFile);
2764
+ const reachesStart =
2765
+ (steps.length > 0 && steps.length < HISTORY_STEPS) ||
2766
+ (!noHistory && steps.length === 0 && dropped === 0);
1644
2767
  /** @type {any} */
1645
2768
  let made = now;
1646
2769
  try {
@@ -1650,10 +2773,24 @@ export async function themeEditUndo(theme, options = {}) {
1650
2773
  }
1651
2774
  const of = (/** @type {any} */ d) =>
1652
2775
  thing === 'base' ? (d?.like ?? 'none') : (d?.mode ?? 'both');
2776
+ // A step in between that had another value: changed and changed back.
2777
+ const changedBack = steps.some(step => {
2778
+ try {
2779
+ return of(JSON.parse(step.replace(/^\uFEFF/, ''))) !== of(now);
2780
+ } catch {
2781
+ return false;
2782
+ }
2783
+ });
1653
2784
  if (of(made) === of(now))
1654
2785
  refuse(
1655
2786
  E.ERR_THEME_NOT_SET,
1656
- `${thing} was never changed: it is ${of(now)}, as ${theme} was made.`,
2787
+ reachesStart && changedBack
2788
+ ? `${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.`
2789
+ : reachesStart
2790
+ ? `${thing} was never changed: it is ${of(now)}, as ${theme} was made.`
2791
+ : noHistory
2792
+ ? `${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.`
2793
+ : `${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
2794
  {run: [`${P} show ${theme}`]},
1658
2795
  );
1659
2796
  return change('set', theme, thing, of(made), options);
@@ -1695,6 +2832,12 @@ export async function themeEditUndo(theme, options = {}) {
1695
2832
  // entry replaces it without the current file being read.
1696
2833
  /** @type {import('./_settings.mjs').ThemeData | null} */
1697
2834
  let current = null;
2835
+ // A file in the theme that is a folder or cannot be read is named first;
2836
+ // the damaged-settings path below never sees it.
2837
+ if (slugOk(theme)) refuseUnreadableFiles(cwd, theme);
2838
+ // A link in the theme is refused as set refuses it, never read as an
2839
+ // empty history.
2840
+ if (slugOk(theme)) refuseLinks(cwd, theme);
1698
2841
  try {
1699
2842
  current = loadTheme(cwd, theme);
1700
2843
  } catch (e) {
@@ -1707,7 +2850,7 @@ export async function themeEditUndo(theme, options = {}) {
1707
2850
  E.ERR_THEME_INVALID,
1708
2851
  `${theme}.history.json is damaged, so there is no step to go back to.`,
1709
2852
  {
1710
- fix: `delete ${shown(cwd, f.history)}: the next change starts a new history, and your settings stay as they are`,
2853
+ 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
2854
  run: [`${P} show ${theme}`],
1712
2855
  },
1713
2856
  );
@@ -1783,13 +2926,35 @@ export async function themeEditUndo(theme, options = {}) {
1783
2926
  E.ERR_THEME_INVALID,
1784
2927
  `The settings before the last change, in ${theme}.history.json, are damaged: ${still}.`,
1785
2928
  {
1786
- fix: `delete ${shown(cwd, f.history)}: the next change starts a new history, and your settings stay as they are`,
2929
+ 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
2930
  run: [`${P} show ${theme}`],
1788
2931
  },
1789
2932
  );
1790
2933
  prev = repaired.data;
1791
2934
  leftOut = repaired.dropped;
1792
2935
  }
2936
+ // The checks that need this Core too (a token's type, a part, a state,
2937
+ // a name that is no token or property): what they refuse is left out of
2938
+ // the step, with the same note, so the build stays valid.
2939
+ {
2940
+ const bad = new Set(storedProblems(ctx, theme, prev).map(p => p.setting));
2941
+ if (bad.size) {
2942
+ leftOut = [...leftOut, ...prev.settings.filter(s => bad.has(s))];
2943
+ prev = {...prev, settings: prev.settings.filter(s => !bad.has(s))};
2944
+ }
2945
+ }
2946
+ // The steps a later undo can still go back to: one equal to the settings
2947
+ // it would leave (a step this undo left a setting out of may then equal
2948
+ // the next one) is skipped, as undo skips it.
2949
+ let stepsLeft = 0;
2950
+ {
2951
+ let at = JSON.stringify(prev);
2952
+ for (let i = history.length - 1; i >= 0; i--)
2953
+ if (!same(history[i], at)) {
2954
+ stepsLeft++;
2955
+ at = history[i];
2956
+ }
2957
+ }
1793
2958
  // The popped history is written with the change, inside its rollback.
1794
2959
  const committed = await commitTheme(ctx, theme, prev, {
1795
2960
  history: false,
@@ -1833,7 +2998,7 @@ export async function themeEditUndo(theme, options = {}) {
1833
2998
  action: 'step',
1834
2999
  undone,
1835
3000
  settings: prev.settings.length,
1836
- stepsLeft: history.length,
3001
+ stepsLeft: stepsLeft,
1837
3002
  // What the step back changed, as a change reports it.
1838
3003
  changedTokens: committed.changed,
1839
3004
  problems: committed.problems,