@astryxdesign/cli 0.7.15 → 0.7.16-canary.g22213fd

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 (222) hide show
  1. package/README.md +6 -4
  2. package/api/build/_adapter.d.mts +10 -0
  3. package/api/build/_adapter.mjs +24 -0
  4. package/api/build/blocks/blocks.d.mts +1 -0
  5. package/api/build/blocks/blocks.mjs +18 -1
  6. package/api/build/kit/shell.weights.json +1 -0
  7. package/api/build/kit/shellcall.d.mts +26 -0
  8. package/api/build/kit/shellcall.mjs +87 -0
  9. package/api/build/kit/start.mjs +67 -4
  10. package/api/build/kit/weights.d.mts +15 -0
  11. package/api/build/kit/weights.mjs +27 -0
  12. package/api/component/__fixtures__/resolutions/modules.txt +1 -1
  13. package/api/component/_adapter.d.mts +1 -1
  14. package/api/component/_adapter.mjs +28 -1
  15. package/api/doctor/_adapter.d.mts +38 -2
  16. package/api/doctor/_adapter.mjs +76 -1
  17. package/api/doctor/built-checks.mjs +1 -1
  18. package/api/doctor/doctor.d.mts +26 -0
  19. package/api/doctor/doctor.doc.mjs +1 -1
  20. package/api/doctor/doctor.mjs +156 -11
  21. package/api/doctor/theme-checks.mjs +163 -18
  22. package/api/icon/_adapter.d.mts +7 -3
  23. package/api/icon/_adapter.mjs +12 -3
  24. package/api/icon/icon.type.d.mts +15 -0
  25. package/api/icon/icon.type.mjs +10 -3
  26. package/api/icon/iconUse.doc.mjs +19 -5
  27. package/api/icon/list/list.mjs +7 -1
  28. package/api/icon/use/use.d.mts +8 -5
  29. package/api/icon/use/use.mjs +95 -13
  30. package/api/init/run/run.mjs +1 -0
  31. package/api/integration/add-contribution.mjs +3 -3
  32. package/api/integration/pack-check.mjs +14 -8
  33. package/api/integration/validate-integration.mjs +1 -1
  34. package/api/search/_adapter.mjs +15 -16
  35. package/api/search/_entries.d.mts +2 -1
  36. package/api/search/_entries.mjs +28 -1
  37. package/api/swizzle/_moduleGraph.mjs +1 -1
  38. package/api/template/template.type.d.mts +6 -2
  39. package/api/template/template.type.mjs +2 -1
  40. package/api/theme/_adapter.d.mts +5 -2
  41. package/api/theme/_adapter.mjs +59 -14
  42. package/api/theme/_fork.mjs +1 -1
  43. package/api/theme/build/build.d.mts +120 -32
  44. package/api/theme/build/build.mjs +471 -111
  45. package/api/theme/eject/eject.mjs +22 -1
  46. package/api/theme/generateTonalPalette.doc.mjs +2 -2
  47. package/api/theme/palette/generate/generator.mjs +141 -2
  48. package/api/theme/template/template.d.mts +19 -0
  49. package/api/theme/template/template.mjs +102 -25
  50. package/api/theme/theme.type.d.mts +44 -1
  51. package/api/theme/theme.type.mjs +23 -1
  52. package/api/theme/themeBuild.doc.mjs +4 -4
  53. package/api/theme/themeEject.doc.mjs +1 -1
  54. package/api/theme/themePaletteGenerate.doc.mjs +1 -1
  55. package/api/theme/themeTemplate.doc.mjs +9 -3
  56. package/api/theme-edit/_adapter.d.mts +33 -2
  57. package/api/theme-edit/_adapter.mjs +276 -41
  58. package/api/theme-edit/_check.d.mts +93 -4
  59. package/api/theme-edit/_check.mjs +1712 -223
  60. package/api/theme-edit/_color.d.mts +2 -8
  61. package/api/theme-edit/_color.mjs +292 -219
  62. package/api/theme-edit/_compiler.d.mts +1 -0
  63. package/api/theme-edit/_compiler.mjs +20 -1
  64. package/api/theme-edit/_context.d.mts +31 -1
  65. package/api/theme-edit/_context.mjs +445 -41
  66. package/api/theme-edit/_css.d.mts +60 -1
  67. package/api/theme-edit/_css.mjs +404 -28
  68. package/api/theme-edit/_edit.d.mts +25 -0
  69. package/api/theme-edit/_edit.mjs +1620 -154
  70. package/api/theme-edit/_how-commands.d.mts +11 -26
  71. package/api/theme-edit/_how-commands.mjs +30 -2
  72. package/api/theme-edit/_how-question.d.mts +15 -0
  73. package/api/theme-edit/_how-question.mjs +1469 -194
  74. package/api/theme-edit/_how.mjs +144 -30
  75. package/api/theme-edit/_marks.d.mts +13 -0
  76. package/api/theme-edit/_marks.mjs +15 -0
  77. package/api/theme-edit/_overview.mjs +2 -0
  78. package/api/theme-edit/_palette.d.mts +38 -0
  79. package/api/theme-edit/_palette.mjs +306 -73
  80. package/api/theme-edit/_parts.d.mts +33 -0
  81. package/api/theme-edit/_parts.mjs +138 -9
  82. package/api/theme-edit/_png.d.mts +18 -0
  83. package/api/theme-edit/_png.mjs +95 -14
  84. package/api/theme-edit/_preview-app.d.mts +55 -1
  85. package/api/theme-edit/_preview-app.mjs +1552 -101
  86. package/api/theme-edit/_preview.d.mts +71 -3
  87. package/api/theme-edit/_preview.mjs +565 -35
  88. package/api/theme-edit/_project.d.mts +15 -0
  89. package/api/theme-edit/_project.mjs +68 -13
  90. package/api/theme-edit/_settings.d.mts +299 -5
  91. package/api/theme-edit/_settings.mjs +2806 -158
  92. package/api/theme-edit/_tables.d.mts +24 -0
  93. package/api/theme-edit/_tables.mjs +212 -150
  94. package/api/theme-edit/_vet.d.mts +42 -0
  95. package/api/theme-edit/_vet.mjs +144 -0
  96. package/api/theme-edit/theme-edit.type.d.mts +31 -2
  97. package/api/theme-edit/theme-edit.type.mjs +10 -2
  98. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  99. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  100. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  101. package/api/upgrade/registry/registry.mjs +6 -1
  102. package/assets/codemods/parse.mjs +2 -2
  103. package/assets/docs/author-a-theme.doc.mjs +1 -1
  104. package/assets/docs/theme.doc.dense.mjs +1 -1
  105. package/assets/docs/theme.doc.mjs +1 -1
  106. package/assets/docs/theme.doc.zh.mjs +4 -3
  107. package/assets/docs/tree/define-the-theme.doc.mjs +1 -1
  108. package/assets/docs/tree/icon-sets.doc.mjs +63 -8
  109. package/assets/docs/tree/single-component.doc.mjs +11 -2
  110. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  111. package/assets/docs.generated.json +2 -2
  112. package/assets/preview-app/next.config.mjs +7 -1
  113. package/assets/preview-app/package.json +1 -0
  114. package/assets/preview-app/src/app/globals.css +1 -0
  115. package/assets/self-audit.generated.json +1 -1
  116. package/assets/templates/blocks/components/Outline/useOutlineFromDOMHookUsage.doc.mjs +21 -0
  117. package/assets/templates/blocks/components/Outline/useOutlineFromDOMHookUsage.tsx +62 -0
  118. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  119. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  120. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  121. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  122. package/assets/templates/components.generated.json +1 -1
  123. package/assets/templates/pages/ai-chat/page.tsx +20 -2
  124. package/assets/templates/pages/dashboard/page.tsx +1 -1
  125. package/assets/templates/themes/neutral/neutralPalettes.generated.receipt.json +2 -0
  126. package/authoring/config/config.doc.mjs +8 -0
  127. package/authoring/config/parse.d.mts +1 -0
  128. package/authoring/config/parse.mjs +12 -0
  129. package/authoring/config/type.ts +8 -0
  130. package/authoring/doctypes/_schema.d.mts +52 -5
  131. package/authoring/doctypes/_schema.mjs +62 -7
  132. package/authoring/doctypes/base/type.ts +10 -0
  133. package/authoring/doctypes/component/component.doc.mjs +1 -1
  134. package/authoring/doctypes/function/function.doc.mjs +6 -0
  135. package/authoring/doctypes/function/type.ts +3 -0
  136. package/authoring/doctypes/icon-set/icon-set-data.doc.mjs +3 -3
  137. package/authoring/doctypes/legacy.mjs +5 -1
  138. package/authoring/index.d.ts +1 -0
  139. package/authoring/shadcn/source-variants.d.mts +1 -1
  140. package/authoring/shadcn/source-variants.mjs +32 -10
  141. package/clients/cli/build-id.generated.json +1 -1
  142. package/clients/cli/commands/doctor.doc.mjs +2 -2
  143. package/clients/cli/commands/experimental/icon.mjs +61 -6
  144. package/clients/cli/commands/experimental/theme.mjs +244 -45
  145. package/clients/cli/commands/experimental-icon-use.doc.mjs +12 -5
  146. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  147. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +2 -2
  148. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +2 -2
  149. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +3 -3
  150. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  151. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  152. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  153. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  154. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  155. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  156. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  157. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  158. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  159. package/clients/cli/commands/theme.doc.mjs +7 -2
  160. package/clients/cli/commands/theme.mjs +222 -55
  161. package/clients/cli/commands.generated.json +1 -1
  162. package/clients/cli/formatters/index.mjs +7 -4
  163. package/clients/cli/index.mjs +25 -5
  164. package/clients/cli/lib/cli-error.mjs +9 -3
  165. package/clients/cli/lib/component-format.mjs +27 -9
  166. package/clients/cli/lib/json-shim.mjs +72 -2
  167. package/clients/cli/manifest.generated.json +1 -1
  168. package/clients/cli/run.mjs +49 -0
  169. package/foundation/agent-docs/agent-docs-target.d.mts +2 -6
  170. package/foundation/agent-docs/agent-docs-target.mjs +9 -17
  171. package/foundation/agent-docs/agent-docs.mjs +4 -3
  172. package/foundation/config/config-writer.d.mts +23 -0
  173. package/foundation/config/config-writer.mjs +152 -58
  174. package/foundation/config/project.mjs +103 -16
  175. package/foundation/discovery/component-discovery.mjs +11 -22
  176. package/foundation/discovery/icon-set-checks.mjs +164 -48
  177. package/foundation/discovery/icon-set-discovery.d.mts +38 -5
  178. package/foundation/discovery/icon-set-discovery.mjs +50 -6
  179. package/foundation/discovery/icon-set-theme-maps.d.mts +59 -0
  180. package/foundation/discovery/icon-set-theme-maps.mjs +95 -0
  181. package/foundation/discovery/icon-set-writer.d.mts +2 -3
  182. package/foundation/discovery/icon-set-writer.mjs +58 -17
  183. package/foundation/discovery/module-exports.mjs +1 -15
  184. package/foundation/discovery/template-adapter.mjs +44 -19
  185. package/foundation/discovery/template-icons.d.mts +27 -10
  186. package/foundation/discovery/template-icons.mjs +142 -26
  187. package/foundation/discovery/template-source-tree.mjs +3 -16
  188. package/foundation/discovery/theme-discovery.d.mts +30 -1
  189. package/foundation/discovery/theme-discovery.mjs +109 -50
  190. package/foundation/fs/exact-codec.d.mts +35 -0
  191. package/foundation/fs/exact-codec.mjs +148 -0
  192. package/foundation/fs/gather-cache.d.mts +15 -5
  193. package/foundation/fs/gather-cache.mjs +129 -31
  194. package/foundation/fs/paths.d.mts +39 -0
  195. package/foundation/fs/paths.mjs +44 -11
  196. package/foundation/fs/read-record.mjs +11 -1
  197. package/foundation/integrations/autolink.d.mts +4 -2
  198. package/foundation/integrations/autolink.mjs +4 -2
  199. package/foundation/integrations/cli-requirement.d.mts +16 -5
  200. package/foundation/integrations/cli-requirement.mjs +27 -6
  201. package/foundation/integrations/contribution-fixes.mjs +1 -16
  202. package/foundation/integrations/may-have-integrations.mjs +7 -3
  203. package/foundation/integrations/missing-dependency.d.mts +9 -0
  204. package/foundation/integrations/missing-dependency.mjs +100 -0
  205. package/foundation/integrations/public-imports.mjs +1 -1
  206. package/foundation/render/embedded-imports.mjs +1 -1
  207. package/foundation/render/host-exit.d.mts +8 -0
  208. package/foundation/render/host-exit.mjs +11 -0
  209. package/foundation/render/page-host.mjs +56 -10
  210. package/foundation/render/page-worker.mjs +14 -0
  211. package/foundation/render/render-page.mjs +37 -2
  212. package/foundation/response/error-codes.d.mts +2 -1
  213. package/foundation/response/error-codes.d.ts +1 -0
  214. package/foundation/response/error-codes.doc.mjs +5 -0
  215. package/foundation/response/error-codes.mjs +3 -0
  216. package/foundation/response/json.d.mts +15 -0
  217. package/foundation/response/json.mjs +52 -1
  218. package/foundation/response/response-types.doc.mjs +1 -1
  219. package/foundation/runtime/lazy-dependencies.d.mts +14 -0
  220. package/foundation/runtime/lazy-dependencies.mjs +82 -0
  221. package/foundation/xle/browser.d.mts +2 -2
  222. package/package.json +7 -6
@@ -10,20 +10,25 @@
10
10
  */
11
11
 
12
12
  import * as fs from 'node:fs';
13
+ import {coversProperty} from './_css.mjs';
13
14
  import * as path from 'node:path';
14
15
  import {AstryxError} from '../error.mjs';
16
+ import {vetSuggestions} from './_vet.mjs';
15
17
  import {
16
18
  AUTO_SPREAD,
17
19
  CORNERS,
18
20
  DIALS,
19
21
  FAMILIES,
20
22
  FONT_ROLES,
23
+ HEADING_TRACKING,
24
+ HEADING_WEIGHTS,
21
25
  KEY_TOKENS,
22
26
  LIKE,
23
27
  P,
24
28
  SPACING,
25
29
  TYPE_STYLES,
26
30
  familyOf,
31
+ wordTable,
27
32
  } from './_tables.mjs';
28
33
  import {
29
34
  commitTheme,
@@ -42,7 +47,9 @@ import {
42
47
  undoArgs,
43
48
  withoutBadValues,
44
49
  NAME_RULE,
50
+ HISTORY_STEPS,
45
51
  readHistory,
52
+ refuseUnreadableFiles,
46
53
  refuse,
47
54
  settingsProblem,
48
55
  resolvedTokens,
@@ -53,6 +60,9 @@ import {
53
60
  staleBuild,
54
61
  EDITOR_SUFFIXES,
55
62
  madeByEditor,
63
+ outputsDrift,
64
+ kebab,
65
+ camel,
56
66
  NEW_MARKER,
57
67
  clearNewMarker,
58
68
  refuseThemeSource,
@@ -60,8 +70,28 @@ import {
60
70
  slugFor,
61
71
  themeSource,
62
72
  themeSourceProblem,
73
+ refuseThemeParse,
74
+ ownSourceTokens,
75
+ ownSourceTokenValues,
76
+ ownPartTokens,
77
+ PHONE_TYPE,
78
+ refreshSourceStamp,
79
+ sourceChangedReason,
80
+ builtPairs,
81
+ ownPairMessage,
82
+ freeThemeName,
83
+ refuseLinks,
84
+ usableNewName,
85
+ FOLDER_JUNK,
86
+ dialValueFits,
87
+ holdAfterBuild,
63
88
  } from './_settings.mjs';
64
- import {checkSetting, exampleOf, storedProblems} from './_check.mjs';
89
+ import {
90
+ checkSetting,
91
+ exampleOf,
92
+ normalizeEntry,
93
+ storedProblems,
94
+ } from './_check.mjs';
65
95
  import {MODAL} from './_compiler.mjs';
66
96
  import {
67
97
  PALETTE_DIALS,
@@ -73,12 +103,21 @@ import {
73
103
  lockHeld,
74
104
  refuseIfLockLost,
75
105
  writeWhole,
106
+ isGraySeed,
107
+ seedOf,
76
108
  } from './_palette.mjs';
77
- import {renderPreview, renderSheet} from './_preview.mjs';
78
- import {refreshPreviewRoute} from './_preview-app.mjs';
79
- import {baseResolved, installLine} from './_project.mjs';
109
+ import {
110
+ renderPreview,
111
+ renderSheet,
112
+ previewIsCurrent,
113
+ takeFirstAppCopy,
114
+ writeAppCopy,
115
+ } from './_preview.mjs';
116
+ import {appWiring, refreshPreviewRoute, seeLine} from './_preview-app.mjs';
117
+ import {baseInstalled, baseResolved, installLine} from './_project.mjs';
80
118
  import {reactMissing} from './_parts.mjs';
81
119
  import {
120
+ renderCause,
82
121
  requireProject,
83
122
  context,
84
123
  pictures,
@@ -86,9 +125,13 @@ import {
86
125
  styledChanges,
87
126
  previewAfter,
88
127
  checkSection,
128
+ stampSheet,
89
129
  } from './_context.mjs';
90
130
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
91
- import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
131
+ import {
132
+ getCliInvocation,
133
+ quoteCommandArgument,
134
+ } from '../../foundation/env/package-manager.mjs';
92
135
 
93
136
  const E = ERROR_CODES;
94
137
 
@@ -97,9 +140,6 @@ const E = ERROR_CODES;
97
140
  */
98
141
  /** The marker a `new` writes first and removes last. */
99
142
 
100
- /** Files a system or a tool puts in any folder; a folder of only these is empty. */
101
- const FOLDER_JUNK = new Set(['.DS_Store', '.gitkeep', 'Thumbs.db']);
102
-
103
143
  /**
104
144
  * A folder the editor made but that has no settings: a stopped `new` left
105
145
  * its marker, or the settings were removed beside the editor's generated
@@ -177,6 +217,40 @@ function readableJson(file) {
177
217
  }
178
218
  }
179
219
 
220
+ /**
221
+ * A physical padding side as its logical side (left-to-right), so a later
222
+ * `padding-inline` replaces an earlier `padding-left` as it does
223
+ * `padding-inline-start`.
224
+ * @param {string} prop
225
+ */
226
+ const logicalSide = prop =>
227
+ /** @type {Record<string, string>} */ ({
228
+ 'padding-left': 'padding-inline-start',
229
+ 'padding-right': 'padding-inline-end',
230
+ 'padding-top': 'padding-block-start',
231
+ 'padding-bottom': 'padding-block-end',
232
+ })[prop] ?? prop;
233
+
234
+ /**
235
+ * Put back every recorded file: its bytes, or removed when it was not
236
+ * there; a palette file the build made new in tokens/ goes too.
237
+ * @param {Map<string, Buffer | null>} kept
238
+ * @param {string} tokensDir
239
+ */
240
+ function putBack(kept, tokensDir) {
241
+ for (const [file, bytes] of kept)
242
+ if (bytes) writeWhole(file, bytes);
243
+ else if (!fs.existsSync(file) || fs.lstatSync(file).isFile())
244
+ fs.rmSync(file, {force: true});
245
+ if (kept.size && fs.existsSync(tokensDir))
246
+ for (const n of fs.readdirSync(tokensDir)) {
247
+ const file = path.join(tokensDir, n);
248
+ // Only a file the build made new; a folder the user put there stays.
249
+ if (!kept.has(file) && fs.lstatSync(file).isFile())
250
+ fs.rmSync(file, {force: true});
251
+ }
252
+ }
253
+
180
254
  /**
181
255
  * Start a theme in themes/<name>/, optionally on a built-in theme, with any
182
256
  * dial settings applied in the same build. Each setting is checked as `set`
@@ -186,19 +260,104 @@ function readableJson(file) {
186
260
  * @param {import('./theme-edit.type.mjs').ThemeEditNewOptions} [options]
187
261
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditNewResponse>}
188
262
  */
263
+
189
264
  export async function themeEditNew(name, options = {}) {
190
265
  const {cwd = process.cwd(), png = false, settings = {}} = options;
191
266
  // `--like none` builds on no base, as `set <theme> base none` does.
192
267
  const like = options.like === 'none' ? undefined : options.like;
193
268
  requireProject(cwd);
269
+ // A corrected `new` keeps every option given, fixing only the bad one.
270
+ // A --like in another case is the built-in theme it names.
271
+ // A --like that names no built-in theme is the nearest one, or none: a
272
+ // corrected command never repeats a --like that is refused below.
273
+ // A guess (the nearest base to a word that names none) is only a base the
274
+ // project has installed: another would be refused in turn. A base named
275
+ // in other letters is the one meant, installed or not (its refusal then
276
+ // offers the install, or the same new on no base).
277
+ const have = LIKE.filter(b => baseInstalled(cwd, b));
278
+ // `@astryxdesign/theme-butter`, `theme-butter`, `Butter`: butter.
279
+ const baseName = (/** @type {unknown} */ v) =>
280
+ String(v)
281
+ .trim()
282
+ .toLowerCase()
283
+ .replace(/^@astryxdesign\/theme-/, '')
284
+ .replace(/^theme-/, '');
285
+ const likeFixed =
286
+ like == null
287
+ ? options.like === 'none'
288
+ ? 'none'
289
+ : undefined
290
+ : LIKE.includes(baseName(like))
291
+ ? baseName(like)
292
+ : (nearest(baseName(like), have)[0] ?? null);
293
+ // A dial value the dial does not take is left out of a suggested `new`
294
+ // (a corrected name must not repeat it), and the refusal says so.
295
+ /** @type {Array<[string, string]>} */
296
+ const badValue = Object.entries(settings).flatMap(([k, v]) =>
297
+ (Array.isArray(v) ? v : v == null ? [] : [v])
298
+ .map(x => /** @type {[string, string]} */ ([k, String(x)]))
299
+ .filter(([dial, x]) => DIALS[dial] && !dialValueFits(dial, x)),
300
+ );
301
+ // Refused for no effect as new refuses it: vibrancy with no color given
302
+ // that is not a gray (a new theme has no other color to saturate).
303
+ const colorGiven = Object.entries(settings).some(
304
+ ([k, v]) =>
305
+ PALETTE_DIALS.includes(k) &&
306
+ (Array.isArray(v) ? v : v == null ? [] : [v]).some(
307
+ x =>
308
+ !badValue.some(([a, b]) => a === k && b === String(x)) &&
309
+ !isGraySeed(seedOf(String(x))),
310
+ ),
311
+ );
312
+ /** @type {Array<[string, string]>} */
313
+ const noEffect =
314
+ settings.vibrancy != null && !colorGiven
315
+ ? (Array.isArray(settings.vibrancy)
316
+ ? settings.vibrancy
317
+ : [settings.vibrancy]
318
+ ).map(x => /** @type {[string, string]} */ (['vibrancy', String(x)]))
319
+ : [];
320
+ const unfit = [...badValue, ...noEffect];
321
+ const isUnfit = (/** @type {string} */ k, /** @type {unknown} */ x) =>
322
+ unfit.some(([a, b]) => a === k && b === String(x));
323
+ /** @type {Record<string, string | string[] | undefined>} */
324
+ const fitSettings = Object.fromEntries(
325
+ Object.entries(settings).map(([k, v]) => [
326
+ k,
327
+ Array.isArray(v)
328
+ ? v.filter(x => !isUnfit(k, x))
329
+ : isUnfit(k, v)
330
+ ? undefined
331
+ : v,
332
+ ]),
333
+ );
334
+ const flag = (/** @type {[string, string]} */ [k, x]) =>
335
+ `--${k} ${quoteCommandArgument(x)}`;
336
+ const dropped = [
337
+ badValue.length
338
+ ? ` 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('; ')}).`
339
+ : '',
340
+ noEffect.length
341
+ ? ` 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.`
342
+ : '',
343
+ ].join('');
344
+ const again = (
345
+ /** @type {string} */ newName,
346
+ /** @type {string | null | undefined} */ likeValue = likeFixed,
347
+ ) => `${P} new ${newName}${newFlags(likeValue, fitSettings, png)}`;
194
348
  if (!slugOk(name)) {
195
349
  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);
350
+ // Only a name typed in another case is the theme here already.
351
+ const sameName = String(name ?? '').toLowerCase() === fixed;
352
+ const exists = sameName && fs.existsSync(themeFiles(cwd, fixed).settings);
198
353
  refuse(
199
354
  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}`]},
355
+ `"${String(name ?? '').slice(0, 80)}" is not a theme name (${NAME_RULE})${exists ? `; ${fixed} is a theme here already` : ''}.${dropped}`,
356
+ {
357
+ run: exists
358
+ ? [`${P} show ${fixed}`]
359
+ : [again(usableNewName(cwd, fixed))],
360
+ },
202
361
  );
203
362
  }
204
363
  // A built-in theme's name would collide with the theme of that name the
@@ -206,8 +365,19 @@ export async function themeEditNew(name, options = {}) {
206
365
  if (LIKE.includes(name))
207
366
  refuse(
208
367
  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}`]},
368
+ `${name} is a built-in theme; an editor theme needs a name of its own. To start from ${name}, build on it.${dropped}`,
369
+ {
370
+ run: [
371
+ again(
372
+ fs.existsSync(themeFiles(cwd, `my-${name}`).dir)
373
+ ? freeThemeName(cwd, `my-${name}`)
374
+ : `my-${name}`,
375
+ // Built on the theme named when it is installed, unless another
376
+ // base (or none) was given.
377
+ likeFixed ?? name,
378
+ ),
379
+ ],
380
+ },
211
381
  );
212
382
  const f = themeFiles(cwd, name);
213
383
  // A link or a file where the theme goes is never written through or
@@ -218,22 +388,33 @@ export async function themeEditNew(name, options = {}) {
218
388
  refuse(
219
389
  E.ERR_FILE_EXISTS,
220
390
  `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']},
391
+ // A look that changes nothing: what is in the way.
392
+ {
393
+ run: [
394
+ `ls -la ${quoteCommandArgument(path.relative(cwd, f.root) || 'themes')}`,
395
+ ],
396
+ },
223
397
  );
224
398
  const dirSt = fs.lstatSync(f.dir, {throwIfNoEntry: false});
225
399
  if (dirSt && (dirSt.isSymbolicLink() || !dirSt.isDirectory()))
226
400
  refuse(
227
401
  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`]},
402
+ `themes/${name} is ${dirSt.isSymbolicLink() ? 'a link' : 'a file'}, so a theme is not made there.${dropped}`,
403
+ {run: [again(freeThemeName(cwd, name))]},
230
404
  );
231
405
  // Settings that are not valid JSON are kept aside, and the theme is
232
406
  // made again beside them.
233
407
  const damaged = fs.existsSync(f.settings) && !readableJson(f.settings);
234
408
  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`],
409
+ refuse(E.ERR_FILE_EXISTS, `Theme "${name}" already exists.${dropped}`, {
410
+ // What the command asked for, on the theme that exists or as a new one.
411
+ run: [
412
+ `${P} show ${name}`,
413
+ ...(likeFixed && LIKE.includes(likeFixed)
414
+ ? [`${P} set ${name} base ${likeFixed}`]
415
+ : []),
416
+ again(freeThemeName(cwd, name)),
417
+ ],
237
418
  });
238
419
  // A `new` stopped part way (killed, out of memory) leaves its own marker
239
420
  // beside the files it wrote: only such a folder is cleared, and only
@@ -249,29 +430,46 @@ export async function themeEditNew(name, options = {}) {
249
430
  if (holdsOther)
250
431
  refuse(
251
432
  E.ERR_FILE_EXISTS,
252
- `themes/${name}/ already holds files this command did not make; choose another name.`,
253
- {run: [`${P} new ${name}-copy`]},
433
+ `themes/${name}/ already holds files this command did not make; choose another name.${dropped}`,
434
+ {run: [again(freeThemeName(cwd, name))]},
254
435
  );
255
436
  if (like != null && !LIKE.includes(like))
256
437
  refuse(
257
438
  E.ERR_THEME_BAD_VALUE,
258
439
  `--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
440
  {
260
- didYouMean: nearest(String(like).toLowerCase(), LIKE),
261
- run: [`${P} new ${name}`],
441
+ // The built-in theme it names in another case, or the nearest
442
+ // installed one, else none: the did-you-mean and the run agree.
443
+ didYouMean: likeFixed ? [likeFixed] : [],
444
+ // A built-in base that is not installed: install it, then the same
445
+ // new on it.
446
+ run: [
447
+ ...(likeFixed && likeFixed !== 'none' && !have.includes(likeFixed)
448
+ ? [installLine(cwd, [`@astryxdesign/theme-${likeFixed}`])]
449
+ : []),
450
+ again(name, likeFixed ?? null),
451
+ ],
262
452
  },
263
453
  );
264
454
  const ctx = await context(cwd);
265
455
  /** @type {import('./_settings.mjs').ThemeData} */
266
456
  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
- );
457
+ try {
458
+ /** @type {import('./_settings.mjs').Ctx} */ (ctx).base =
459
+ await baseResolved(ctx.project, data.like);
460
+ } catch (e) {
461
+ // A base that is not installed: install it, or the same new on no base.
462
+ if (e instanceof AstryxError && e.code === E.ERR_UNKNOWN_THEME)
463
+ e.suggestions = [
464
+ ...(e.suggestions ?? []),
465
+ {name: again(name, null), reason: 'build on no theme'},
466
+ ];
467
+ throw e;
468
+ }
271
469
  // Every check comes before the first change to the folder: the settings,
272
470
  // and a source of the user's own kept from before (it must still extend
273
471
  // the settings, or the build fails after the folder was cleared).
274
- applyNewSettings(ctx, name, data, settings);
472
+ applyNewSettings(ctx, name, data, settings, png, likeFixed ?? undefined);
275
473
  if (left?.keep.some(p => path.basename(p) === `${name}.theme.ts`))
276
474
  refuseThemeSource(cwd, name);
277
475
  /** @type {string[]} */
@@ -290,7 +488,7 @@ export async function themeEditNew(name, options = {}) {
290
488
  );
291
489
  if (left?.keep.some(p => path.basename(p) === `${name}.history.json`))
292
490
  leftNotes.push(
293
- `the earlier settings are kept in ${name}.history.json: \`${P} undo ${name}\` steps back to them`,
491
+ `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
492
  );
295
493
  // The marker goes first and comes off last: a `new` stopped between
296
494
  // leaves a folder the next `new` can prove it made. The damaged settings
@@ -406,6 +604,8 @@ export async function themeEditNew(name, options = {}) {
406
604
  notes,
407
605
  problems: r.problems,
408
606
  ...p,
607
+ // How to use the theme in this app: theme add <theme> for its app copy.
608
+ wiring: appWiring(ctx, name, data),
409
609
  },
410
610
  };
411
611
  }
@@ -417,8 +617,17 @@ export async function themeEditNew(name, options = {}) {
417
617
  * @param {string} slug
418
618
  * @param {import('./_settings.mjs').ThemeData} data
419
619
  * @param {Record<string, string | string[] | undefined>} settings
620
+ * @param {boolean} [png] kept in a corrected `new` a refusal suggests
621
+ * @param {string} [likeFlag] the --like a corrected `new` keeps (`none` too)
420
622
  */
421
- function applyNewSettings(ctx, slug, data, settings) {
623
+ function applyNewSettings(
624
+ ctx,
625
+ slug,
626
+ data,
627
+ settings,
628
+ png = false,
629
+ likeFlag = data.like,
630
+ ) {
422
631
  const given = Object.entries(settings).filter(([, v]) => v != null);
423
632
  for (const [thing] of given)
424
633
  if (!DIALS[thing] || thing === 'base')
@@ -441,13 +650,21 @@ function applyNewSettings(ctx, slug, data, settings) {
441
650
  const given = settings[thing];
442
651
  if (given == null) continue;
443
652
  // `headings` takes a weight and a tracking: one value per axis.
444
- for (const value of Array.isArray(given) ? given : [given]) {
653
+ const values = Array.isArray(given) ? given : [given];
654
+ for (const [index, value] of values.entries()) {
445
655
  /** @type {import('./_settings.mjs').Setting} */
446
656
  let s;
447
657
  try {
448
658
  s = checkSetting(ctx, slug, data, thing, String(value), {}, false);
449
659
  } catch (e) {
450
- throw asNewRefusal(e, slug, settings);
660
+ throw asNewRefusal(
661
+ vetSuggestions(e, ctx, slug, data),
662
+ slug,
663
+ settings,
664
+ likeFlag,
665
+ png,
666
+ {thing, index},
667
+ );
451
668
  }
452
669
  if (thing === 'mode')
453
670
  data.mode = /** @type {'both' | 'light-only' | 'dark-only'} */ (
@@ -460,8 +677,14 @@ function applyNewSettings(ctx, slug, data, settings) {
460
677
  E.ERR_INVALID_ARGUMENT,
461
678
  `--${thing} was given two values for the same thing (${data.settings[same].value}, ${s.value}); give one.`,
462
679
  {
680
+ // Every other option given stays, and the first value on each
681
+ // axis: every later value for an axis already given goes.
463
682
  run: [
464
- `${P} new ${slug} --${thing} ${quoteCommandArgument(s.value)}`,
683
+ `${P} new ${slug}${newFlags(
684
+ likeFlag,
685
+ {...settings, [thing]: firstPerAxis(values)},
686
+ png,
687
+ )}`,
465
688
  ],
466
689
  },
467
690
  );
@@ -471,36 +694,134 @@ function applyNewSettings(ctx, slug, data, settings) {
471
694
  }
472
695
  }
473
696
 
697
+ /**
698
+ * The options of a `new` as flags, in the order given (`new --help`'s order
699
+ * for the command): `--like`, each dial setting, then `--png`.
700
+ * @param {string | null | undefined} like none when null or undefined
701
+ * @param {Record<string, string | string[] | undefined>} settings
702
+ * @param {boolean} [png]
703
+ * @returns {string[]}
704
+ */
705
+ export function newFlagList(like, settings, png = false) {
706
+ return [
707
+ ...(like ? [`--like ${quoteCommandArgument(like)}`] : []),
708
+ ...Object.entries(settings)
709
+ .filter(([, v]) => v != null)
710
+ .flatMap(([k, v]) => (Array.isArray(v) ? v : [v]).map(x => [k, x]))
711
+ .map(([k, v]) => `--${k} ${quoteCommandArgument(String(v))}`),
712
+ ...(png ? ['--png'] : []),
713
+ ];
714
+ }
715
+
716
+ /**
717
+ * The options of a `new` as one flag line, with its leading space.
718
+ * @param {string | null | undefined} like
719
+ * @param {Record<string, string | string[] | undefined>} settings
720
+ * @param {boolean} png
721
+ */
722
+ function newFlags(like, settings, png) {
723
+ const parts = newFlagList(like, settings, png);
724
+ return parts.length ? ` ${parts.join(' ')}` : '';
725
+ }
726
+
474
727
  /**
475
728
  * A refusal from a setting `new` was given, with its suggestions turned
476
729
  * into `new` commands: the theme does not exist yet, so a `set` would fail.
477
730
  * @param {unknown} e
478
731
  * @param {string} slug
479
732
  * @param {Record<string, string | string[] | undefined>} settings
733
+ * @param {string} [like] the --like given, kept in a corrected command
734
+ * @param {boolean} [png] --png, kept in a corrected command
735
+ * @param {{thing: string, index: number} | null} [at] the value refused
480
736
  */
481
- function asNewRefusal(e, slug, settings) {
737
+ function asNewRefusal(e, slug, settings, like, png = false, at = null) {
482
738
  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
739
  const setPrefix = `${P} set ${slug} `;
488
740
  e.suggestions = (e.suggestions ?? []).map(s => {
489
741
  if (s.name === `${P} set --help`) return {...s, name: `${P} new --help`};
490
742
  if (!s.name.startsWith(setPrefix)) return s;
491
743
  const [thing, ...rest] = s.name.slice(setPrefix.length).split(' ');
492
744
  if (thing.startsWith('--') || !DIALS[thing]) return s;
493
- const keep = flags.filter(f => !f.startsWith(`--${thing} `));
745
+ const fixed = unquoteWord(rest.join(' '));
746
+ // Only the refused value changes: a dial given several values
747
+ // (--headings tight --headings BOLD) keeps the others, in order.
748
+ const given = settings[thing];
749
+ const values = Array.isArray(given) ? [...given] : null;
750
+ const next =
751
+ values && at && at.thing === thing
752
+ ? firstPerAxis(values.map((v, i) => (i === at.index ? fixed : v)))
753
+ : fixed;
494
754
  return {
495
755
  ...s,
496
- name: [`${P} new ${slug}`, ...keep, `--${thing} ${rest.join(' ')}`].join(
497
- ' ',
498
- ),
756
+ name: `${P} new ${slug}${newFlags(like, {...settings, [thing]: next}, png)}`,
499
757
  };
500
758
  });
759
+ // A refused value with nothing to put in its place: the same new
760
+ // without it, every other option kept.
761
+ if (at && !e.suggestions.some(x => x.name.startsWith(`${P} new `))) {
762
+ const given = settings[at.thing];
763
+ const rest = Array.isArray(given)
764
+ ? given.filter((_, i) => i !== at.index)
765
+ : undefined;
766
+ e.suggestions.push({
767
+ name: `${P} new ${slug}${newFlags(like, {...settings, [at.thing]: rest?.length ? rest : undefined}, png)}`,
768
+ reason: `without --${at.thing} ${quoteCommandArgument(String(Array.isArray(given) ? given[at.index] : given))}`,
769
+ });
770
+ }
501
771
  return e;
502
772
  }
503
773
 
774
+ /**
775
+ * Headings values with every later value for an axis already given left
776
+ * out (the first weight and the first tracking stay); a word of neither
777
+ * axis stays, for its own refusal.
778
+ * @param {string[]} values
779
+ * @returns {string[]}
780
+ */
781
+ function firstPerAxis(values) {
782
+ const seen = new Set();
783
+ return values.filter(v => {
784
+ const w = String(v).trim().toLowerCase();
785
+ const axis =
786
+ HEADING_WEIGHTS[w] !== undefined
787
+ ? 'weight'
788
+ : HEADING_TRACKING[w] !== undefined
789
+ ? 'tracking'
790
+ : null;
791
+ if (!axis) return true;
792
+ if (seen.has(axis)) return false;
793
+ seen.add(axis);
794
+ return true;
795
+ });
796
+ }
797
+
798
+ /**
799
+ * A word as a suggested command writes it, without the quotes
800
+ * quoteCommandArgument adds.
801
+ * @param {string} word
802
+ */
803
+ function unquoteWord(word) {
804
+ const m = /^'(.*)'$/s.exec(word);
805
+ return m ? m[1].replace(/'\\''/g, "'") : word;
806
+ }
807
+
808
+ /**
809
+ * The preview page most about a change: Colors for a color (a color dial
810
+ * or a color token), Components for a part setting, else Overview.
811
+ * @param {{thing: string, on?: string | null}} s
812
+ * @returns {'colors' | 'components' | 'overview'}
813
+ */
814
+ function changeFocus(s) {
815
+ if (s.on) return 'components';
816
+ if (
817
+ PALETTE_DIALS.includes(s.thing) ||
818
+ s.thing === 'vibrancy' ||
819
+ /^--color-/.test(s.thing)
820
+ )
821
+ return 'colors';
822
+ return 'overview';
823
+ }
824
+
504
825
  /**
505
826
  * The preview after a change, with the in-app preview route kept in step:
506
827
  * its imports follow the theme, such as the stylesheet of a font package
@@ -509,10 +830,32 @@ function asNewRefusal(e, slug, settings) {
509
830
  * @param {string} slug
510
831
  * @param {import('./_settings.mjs').ThemeData} data
511
832
  * @param {boolean} png
833
+ * @param {'colors' | 'components' | 'overview'} [focus] the preview page
834
+ * most about the change: Colors for a color, Components for a part
512
835
  */
513
- async function previewAndRoute(ctx, slug, data, png) {
836
+ async function previewAndRoute(ctx, slug, data, png, focus = 'overview') {
514
837
  const p = await previewAfter(ctx, slug, data, png);
515
- return {...p, previewStale: await keepPreviewRoute(ctx, slug)};
838
+ const wrote = takeFirstAppCopy(ctx.project.cwd, slug);
839
+ return {
840
+ ...p,
841
+ previewStale: await keepPreviewRoute(ctx, slug),
842
+ // How to see the change: the page about it, at its own URL.
843
+ // A page not written this time (preview null) still shows the theme
844
+ // as it was; checks that failed with the page written do not.
845
+ see: seeLine(
846
+ ctx.project.cwd,
847
+ slug,
848
+ focus,
849
+ p.preview == null
850
+ ? (p.notChecked ?? {
851
+ code: 'ERR_THEME_NOT_CHECKED',
852
+ cause: 'no preview was rendered',
853
+ })
854
+ : null,
855
+ ),
856
+ // The first time the theme's app copy is written, its files are named.
857
+ ...(wrote ? {appCopy: {wrote}} : {}),
858
+ };
516
859
  }
517
860
 
518
861
  /**
@@ -552,12 +895,36 @@ export async function themeEditSet(theme, thing, value, options = {}) {
552
895
  * @param {import('./_settings.mjs').Ctx} ctx
553
896
  * @param {string} slug
554
897
  * @param {import('./_settings.mjs').ThemeData} data
555
- * @param {string} [skip]
898
+ * @param {string | {thing: string, on?: string, when?: string, state?: string, mode?: string}} [skip]
556
899
  */
557
900
  function refuseStoredTokens(ctx, slug, data, skip) {
558
901
  const bad = storedProblems(ctx, slug, data, skip);
559
902
  if (!bad.length) return;
560
- const one = bad.length === 1 ? bad[0] : null;
903
+ const found = bad.length === 1 ? bad[0] : null;
904
+ // A clean value is offered only when set takes it, so the line works.
905
+ const takes = (/** @type {typeof found} */ b) => {
906
+ if (!b?.fix) return true;
907
+ try {
908
+ checkSetting(
909
+ ctx,
910
+ slug,
911
+ {...data, settings: data.settings.filter(x => x !== b.setting)},
912
+ b.setting.thing,
913
+ b.fix,
914
+ {
915
+ on: b.setting.on,
916
+ when: b.setting.when,
917
+ state: b.setting.state,
918
+ mode: b.setting.mode,
919
+ },
920
+ false,
921
+ );
922
+ return true;
923
+ } catch {
924
+ return false;
925
+ }
926
+ };
927
+ const one = found && takes(found) ? found : null;
561
928
  refuse(
562
929
  E.ERR_THEME_INVALID,
563
930
  `themes/${slug}/${slug}.settings.json: ${bad
@@ -571,16 +938,68 @@ function refuseStoredTokens(ctx, slug, data, skip) {
571
938
  // setting is never refused for another.
572
939
  run: [
573
940
  ...bad.slice(0, 5).map(b => `${P} undo ${slug} ${undoArgs(b.setting)}`),
574
- ...(one && !one.scope
941
+ // A value to set only for a token whose stored value has the wrong
942
+ // type; any other thing `set` would refuse, or read as a dial.
943
+ ...(one &&
944
+ !one.scope &&
945
+ one.setting.source === 'token' &&
946
+ ctx.C.isToken(one.setting.thing)
575
947
  ? [
576
- `${P} set ${slug} ${one.setting.thing} ${quoteCommandArgument(exampleOf(ctx.C.typeOf(one.setting.thing), one.setting.thing))}`,
948
+ // The value the check suggests for this value, else a stock
949
+ // one of the token's type.
950
+ `${P} set ${slug} ${one.setting.thing} ${quoteCommandArgument(one.fix ?? exampleOf(ctx.C.typeOf(one.setting.thing), one.setting.thing))}`,
577
951
  ]
578
- : []),
952
+ : one && one.fix && one.setting.source === 'dial'
953
+ ? [
954
+ `${P} set ${slug} ${one.setting.thing} ${quoteCommandArgument(one.fix)}`,
955
+ ]
956
+ : []),
579
957
  ],
580
958
  },
581
959
  );
582
960
  }
583
961
 
962
+ /**
963
+ * For `compile`: the refusal `show` gives for saved settings the editor no
964
+ * longer accepts (naming the undo that removes each), or null.
965
+ * @param {string} root
966
+ * @param {string} slug
967
+ * @returns {Promise<import('../error.mjs').AstryxError | null>}
968
+ */
969
+ export async function editorStoredRefusal(root, slug) {
970
+ try {
971
+ const ctx = await context(root);
972
+ refuseStoredTokens(ctx, slug, loadTheme(root, slug));
973
+ return null;
974
+ } catch (e) {
975
+ if (e instanceof AstryxError) return e;
976
+ throw e;
977
+ }
978
+ }
979
+
980
+ /**
981
+ * For `compile`: the refusal of [light, dark] pairs on tokens that are not
982
+ * colors in what the theme builds now, or null.
983
+ * @param {string} root
984
+ * @param {string} slug
985
+ * @returns {Promise<import('../error.mjs').AstryxError | null>}
986
+ */
987
+ export async function editorPairRefusal(root, slug) {
988
+ const ctx = await context(root);
989
+ const names = await builtPairs(ctx, slug);
990
+ if (!names.length) return null;
991
+ return new AstryxError(
992
+ ownPairMessage(slug, names),
993
+ [
994
+ {
995
+ name: `grep -n -- ${quoteCommandArgument(names[0])} ${quoteCommandArgument(`themes/${slug}/${slug}.theme.ts`)}`,
996
+ reason: 'see where the file sets it',
997
+ },
998
+ ],
999
+ ERROR_CODES.ERR_THEME_INVALID,
1000
+ );
1001
+ }
1002
+
584
1003
  /**
585
1004
  * A note for type scale steps that land outside 9 to 200 pixels.
586
1005
  * @param {Record<string, string>} res resolved light tokens
@@ -611,12 +1030,79 @@ function extremeSteps(res) {
611
1030
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
612
1031
  */
613
1032
  async function change(sub, slug, thing, value, options) {
1033
+ // As typed: an undo of a saved entry written in a form the cleanup below
1034
+ // repairs (`Corners`, `var(--radius-page)`) removes that exact entry.
1035
+ const typedThing = thing;
1036
+ // How it was typed, put right before anything reads it (a pasted
1037
+ // declaration, a dash, a var(), invisible spaces).
1038
+ if (typeof thing === 'string') {
1039
+ const entry = normalizeEntry(thing, value);
1040
+ thing = entry.thing;
1041
+ value = entry.value;
1042
+ }
1043
+ /** @type {{ctx?: import('./_settings.mjs').Ctx, data?: import('./_settings.mjs').ThemeData}} */
1044
+ const seen = {};
1045
+ try {
1046
+ return await changeOnce(sub, slug, thing, value, options, seen, typedThing);
1047
+ } catch (e) {
1048
+ // A theme name one letter off an existing theme: the same command with
1049
+ // that name comes first, before making a theme of the typo.
1050
+ if (e instanceof AstryxError && e.code === E.ERR_UNKNOWN_THEME) {
1051
+ const near = (e.suggestions ?? []).find(x => x.reason === 'did you mean');
1052
+ if (near && slugOk(near.name)) {
1053
+ const flags = [
1054
+ ...(options.on ? ['--on', options.on] : []),
1055
+ ...(options.when ? ['--when', options.when] : []),
1056
+ ...(options.state ? ['--state', options.state] : []),
1057
+ ...(options.mode ? ['--mode', options.mode] : []),
1058
+ ...(options.only ? ['--only'] : []),
1059
+ ];
1060
+ const words = [thing, ...(value == null ? [] : [value]), ...flags]
1061
+ .filter(w => w != null && w !== '')
1062
+ .map(w =>
1063
+ String(w).startsWith('--') ? w : quoteCommandArgument(String(w)),
1064
+ );
1065
+ e.suggestions = [
1066
+ {
1067
+ name: `${P} ${sub} ${near.name}${words.length ? ` ${words.join(' ')}` : ''}`,
1068
+ reason: `do this instead: ${near.name} is a theme here`,
1069
+ },
1070
+ ...(e.suggestions ?? []).filter(x => x !== near),
1071
+ ];
1072
+ }
1073
+ throw e;
1074
+ }
1075
+ // Every `set` the refusal suggests is checked as `set` checks it.
1076
+ throw vetSuggestions(e, seen.ctx, slug, seen.data);
1077
+ }
1078
+ }
1079
+
1080
+ /**
1081
+ * @param {'set' | 'undo'} sub
1082
+ * @param {string} slug
1083
+ * @param {string} thing
1084
+ * @param {string | undefined} value
1085
+ * @param {ChangeOptions} options
1086
+ * @param {{ctx?: import('./_settings.mjs').Ctx, data?: import('./_settings.mjs').ThemeData}} seen
1087
+ * the context and the theme as loaded, for checking a refusal's suggestions
1088
+ * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
1089
+ */
1090
+ async function changeOnce(
1091
+ sub,
1092
+ slug,
1093
+ thing,
1094
+ value,
1095
+ options,
1096
+ seen,
1097
+ typedThing = thing,
1098
+ ) {
614
1099
  const {cwd = process.cwd(), png = false} = options;
615
1100
  requireProject(cwd);
616
1101
  // The setting this command changes or removes may be the bad one; any
617
1102
  // other bad setting still refuses (or is left out when this fixes one).
618
1103
  const target = /** @type {Partial<import('./_settings.mjs').Setting>} */ ({
619
- thing,
1104
+ // An undo may name a saved entry exactly as written.
1105
+ thing: sub === 'undo' ? typedThing : thing,
620
1106
  on: options.on,
621
1107
  when: options.when,
622
1108
  state: options.state,
@@ -643,7 +1129,14 @@ async function change(sub, slug, thing, value, options) {
643
1129
  const ctx = await context(cwd);
644
1130
  // An undo of one setting only removes it, so it never waits on the
645
1131
  // others being fixed.
646
- if (sub !== 'undo') refuseStoredTokens(ctx, slug, data, thing);
1132
+ if (sub !== 'undo')
1133
+ refuseStoredTokens(ctx, slug, data, {
1134
+ thing,
1135
+ on: options.on,
1136
+ when: options.when,
1137
+ state: options.state,
1138
+ mode: options.mode,
1139
+ });
647
1140
  const flags = {
648
1141
  on: options.on,
649
1142
  when: options.when,
@@ -664,10 +1157,65 @@ async function change(sub, slug, thing, value, options) {
664
1157
  );
665
1158
  }
666
1159
  /** @type {import('./_settings.mjs').Ctx} */ (ctx).base = base;
1160
+ seen.ctx = ctx;
1161
+ seen.data = structuredClone(data);
1162
+ // The saved entry an undo names exactly as written (thing and scope, in
1163
+ // their own letters), when the editor would read it as another setting
1164
+ // or refuse it: that entry is removed, never a valid neighbor the
1165
+ // cleaned name also matches.
1166
+ const exactIdx =
1167
+ sub === 'undo'
1168
+ ? data.settings.findIndex(
1169
+ x =>
1170
+ x.thing === typedThing &&
1171
+ (x.on ?? null) === (flags.on ?? null) &&
1172
+ (x.when ?? null) === (flags.when ?? null) &&
1173
+ (x.state ?? null) === (flags.state ?? null) &&
1174
+ (x.mode ?? null) === (flags.mode ?? null) &&
1175
+ Boolean(x.only) === Boolean(flags.only),
1176
+ )
1177
+ : -1;
1178
+ let rawIdx = -1;
1179
+ if (exactIdx >= 0) {
1180
+ // Only an entry the editor would not save as written: one it refuses,
1181
+ // or reads as another name, part or state.
1182
+ const entry = data.settings[exactIdx];
1183
+ let read = null;
1184
+ try {
1185
+ read = checkSetting(
1186
+ ctx,
1187
+ slug,
1188
+ data,
1189
+ normalizeEntry(entry.thing, '').thing,
1190
+ undefined,
1191
+ {
1192
+ on: entry.on,
1193
+ when: entry.when,
1194
+ state: entry.state,
1195
+ mode: entry.mode,
1196
+ only: entry.only,
1197
+ },
1198
+ true,
1199
+ );
1200
+ } catch {
1201
+ // Refused as written.
1202
+ }
1203
+ if (
1204
+ !read ||
1205
+ read.thing !== entry.thing ||
1206
+ (read.on ?? null) !== (entry.on ?? null) ||
1207
+ (read.state ?? null) !== (entry.state ?? null) ||
1208
+ (read.when ?? null) !== (entry.when ?? null)
1209
+ )
1210
+ rawIdx = exactIdx;
1211
+ }
667
1212
  /** @type {import('./_settings.mjs').Setting} */
668
1213
  let s;
669
1214
  try {
670
- s = checkSetting(ctx, slug, data, thing, value, flags, sub === 'undo');
1215
+ s =
1216
+ rawIdx >= 0
1217
+ ? data.settings[rawIdx]
1218
+ : checkSetting(ctx, slug, data, thing, value, flags, sub === 'undo');
671
1219
  } catch (e) {
672
1220
  // A stored setting this Core no longer knows (a renamed part or
673
1221
  // property, or a hand edit) can still be removed.
@@ -675,11 +1223,13 @@ async function change(sub, slug, thing, value, options) {
675
1223
  sub === 'undo'
676
1224
  ? data.settings.find(
677
1225
  x =>
678
- x.thing === thing &&
1226
+ x.thing.toLowerCase() === String(thing).toLowerCase() &&
679
1227
  (x.on ?? null) === (flags.on ?? null) &&
680
1228
  (x.when ?? null) === (flags.when ?? null) &&
681
1229
  (x.state ?? null) === (flags.state ?? null) &&
682
- (x.mode ?? null) === (flags.mode ?? null),
1230
+ (x.mode ?? null) === (flags.mode ?? null) &&
1231
+ // --only names a setting made with it; it is never dropped.
1232
+ Boolean(x.only) === Boolean(flags.only),
683
1233
  )
684
1234
  : null;
685
1235
  if (!stored) {
@@ -687,13 +1237,50 @@ async function change(sub, slug, thing, value, options) {
687
1237
  // what it named (or of the dial its refusal names), else the last
688
1238
  // step.
689
1239
  if (sub === 'undo' && e instanceof AstryxError) {
1240
+ // Setting names are matched in any case, and a near name of a
1241
+ // setting the theme has counts: `undo t Corners`, `undo t corner`.
1242
+ const typed = String(thing).toLowerCase();
1243
+ // A token named without its dashes (radius-element) is the token.
1244
+ const dashed = typed.startsWith('--') ? typed : `--${typed}`;
690
1245
  const named = new Set([
691
- thing,
1246
+ typed,
1247
+ dashed,
1248
+ ...(e.suggestions ?? [])
1249
+ .filter(x => x.reason === 'did you mean')
1250
+ .map(x => x.name.toLowerCase()),
692
1251
  ...(e.suggestions ?? [])
693
- .map(x => new RegExp(` set ${slug} (\\S+)`).exec(x.name)?.[1])
1252
+ .map(
1253
+ x => new RegExp(` (?:set|undo) ${slug} (\\S+)`).exec(x.name)?.[1],
1254
+ )
694
1255
  .filter(Boolean),
1256
+ ...nearest(
1257
+ typed,
1258
+ data.settings.map(x => x.thing.toLowerCase()),
1259
+ ),
695
1260
  ]);
696
- const matches = data.settings.filter(x => named.has(x.thing));
1261
+ const matches = data.settings.filter(x =>
1262
+ named.has(x.thing.toLowerCase()),
1263
+ );
1264
+ // A word that is near a setting name (a typo, another case) is never
1265
+ // answered with a bare step back, which would undo another change;
1266
+ // any other word (`all`) may mean the last step.
1267
+ // A token or a property named (radius-element, padding) is a named
1268
+ // thing too: never answered with a step back.
1269
+ const namesThing =
1270
+ ctx.C.isToken(dashed) ||
1271
+ data.settings.some(
1272
+ x => x.source === 'property' && x.thing.toLowerCase() === typed,
1273
+ ) ||
1274
+ /^[a-z]+(-[a-z]+)+$|^(padding|margin|color|background|border|gap|width|height|opacity)$/.test(
1275
+ typed,
1276
+ );
1277
+ const nearSetting =
1278
+ namesThing ||
1279
+ named.size > (dashed === typed ? 1 : 2) ||
1280
+ nearest(typed, [
1281
+ ...Object.keys(DIALS),
1282
+ ...data.settings.map(x => x.thing.toLowerCase()),
1283
+ ]).length > 0;
697
1284
  const steps = readHistory(themeFiles(cwd, slug).history).steps.length;
698
1285
  throw new AstryxError(
699
1286
  e.message,
@@ -703,7 +1290,7 @@ async function change(sub, slug, thing, value, options) {
703
1290
  reason: 'do this instead',
704
1291
  }))
705
1292
  : [
706
- steps
1293
+ steps && !nearSetting
707
1294
  ? {name: `${P} undo ${slug}`, reason: 'step back one change'}
708
1295
  : {name: `${P} show ${slug}`, reason: 'see what it sets'},
709
1296
  ],
@@ -734,7 +1321,11 @@ async function change(sub, slug, thing, value, options) {
734
1321
  .trim()
735
1322
  .toLowerCase()
736
1323
  .replace(/\s+/g, ' ')
737
- .replace(/^["']|["']$/g, '');
1324
+ // Spacing around commas, slashes and parentheses, and the quote
1325
+ // style, are not part of a value.
1326
+ .replace(/\s*([,()/])\s*/g, '$1')
1327
+ .replace(/'/g, '"')
1328
+ .replace(/^"|"$/g, '');
738
1329
  const half =
739
1330
  s.thing === 'headings' && ['weight', 'tracking'].includes(norm(value));
740
1331
  if (
@@ -786,6 +1377,13 @@ async function change(sub, slug, thing, value, options) {
786
1377
  ]
787
1378
  : []),
788
1379
  ...otherModeNotes(data),
1380
+ // Core has no mode inside a theme: the app's <Theme> is given it.
1381
+ ...(s.thing === 'mode' &&
1382
+ (data.mode === 'light-only' || data.mode === 'dark-only')
1383
+ ? [
1384
+ `the app shows ${slug} in ${data.mode === 'light-only' ? 'light' : 'dark'} mode when its <Theme> is given mode="${data.mode === 'light-only' ? 'light' : 'dark'}" (<Theme theme={…} mode="${data.mode === 'light-only' ? 'light' : 'dark'}">), as the preview does; the theme keeps both halves of its colors, so a toast or a lightbox Core draws in the other mode stays readable`,
1385
+ ]
1386
+ : []),
789
1387
  // The colors are made again for the new base or mode: their
790
1388
  // shade notes follow.
791
1389
  ...data.settings
@@ -812,16 +1410,24 @@ async function change(sub, slug, thing, value, options) {
812
1410
  };
813
1411
  }
814
1412
  const k = keyOf(s);
815
- const prevIdx = data.settings.findIndex(x => keyOf(x) === k);
1413
+ const prevIdx =
1414
+ rawIdx >= 0 ? rawIdx : data.settings.findIndex(x => keyOf(x) === k);
816
1415
  /** @type {string | null} */
817
1416
  let vibrancyGone = null;
818
1417
  const prev = prevIdx >= 0 ? data.settings[prevIdx] : null;
819
1418
  if (sub === 'undo') {
820
1419
  if (!prev) {
821
1420
  const near = data.settings.filter(x => x.thing === s.thing).map(describe);
1421
+ // headings has two halves: name the one that is set.
1422
+ const otherHalf =
1423
+ s.thing === 'headings'
1424
+ ? data.settings.find(x => x.thing === 'headings' && x.axis !== s.axis)
1425
+ : null;
822
1426
  refuse(
823
1427
  E.ERR_THEME_NOT_SET,
824
- `The theme does not set ${describe({...s, value: '?'}).replace(' = ?', '')}.`,
1428
+ otherHalf
1429
+ ? `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.`
1430
+ : `The theme does not set ${describe({...s, value: '?'}).replace(' = ?', '')}.`,
825
1431
  {
826
1432
  also: near.length
827
1433
  ? [`settings for ${s.thing}: ${near.join('; ')}`]
@@ -837,6 +1443,8 @@ async function change(sub, slug, thing, value, options) {
837
1443
  );
838
1444
  }
839
1445
  data.settings.splice(prevIdx, 1);
1446
+ // A setting listed twice by hand goes in full.
1447
+ data.settings = data.settings.filter(x => keyOf(x) !== k);
840
1448
  // Vibrancy needs a color: undoing the last one takes it along, so the
841
1449
  // theme never holds a state `set` refuses.
842
1450
  if (
@@ -872,6 +1480,13 @@ async function change(sub, slug, thing, value, options) {
872
1480
  if (prev) data.settings.splice(prevIdx, 1);
873
1481
  data.settings.push(s);
874
1482
  }
1483
+ // A setting listed twice by hand keeps only the entry this command left.
1484
+ if (sub === 'set') {
1485
+ const last = data.settings.map(x => keyOf(x)).lastIndexOf(k);
1486
+ data.settings = data.settings.filter(
1487
+ (x, i) => keyOf(x) !== k || i === last,
1488
+ );
1489
+ }
875
1490
  // A setting for both modes replaces the ones made for one mode, which it
876
1491
  // would otherwise sit under.
877
1492
  /** @type {import('./_settings.mjs').Setting[]} */
@@ -889,16 +1504,24 @@ async function change(sub, slug, thing, value, options) {
889
1504
  x =>
890
1505
  x !== s &&
891
1506
  x.source === 'property' &&
892
- x.on === s.on &&
1507
+ // On the same part, or on a member of the group it is set on:
1508
+ // the later setting wins, whichever way Core writes it.
1509
+ (x.on === s.on ||
1510
+ (s.on != null &&
1511
+ (FAMILIES[s.on] ?? []).includes(
1512
+ /** @type {string} */ (x.on),
1513
+ ))) &&
893
1514
  x.when === s.when &&
894
1515
  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
- ),
1516
+ // A longhand the shorthand really sets (MDN's data), never a
1517
+ // property that only shares its name (overflow-wrap).
1518
+ (coversProperty(s.thing, x.thing) ||
1519
+ coversProperty(logicalSide(s.thing), logicalSide(x.thing))),
900
1520
  )
901
1521
  : [];
1522
+ // They go, as the note says: Core writes each side to its own variable,
1523
+ // where a later shorthand would not win over them (undo brings them back).
1524
+ data.settings = data.settings.filter(x => !longhands.includes(x));
902
1525
  // A group setting covers part settings made before it for its members.
903
1526
  const covers =
904
1527
  sub === 'set' && s.source === 'dial' && s.on && FAMILIES[s.on]
@@ -913,42 +1536,37 @@ async function change(sub, slug, thing, value, options) {
913
1536
  )
914
1537
  : [];
915
1538
  const r = await commitTheme(ctx, slug, data, {history: true});
916
- const styled = styledChanges(compiledBefore, compileTheme(ctx, data, base));
1539
+ const compiledAfter = compileTheme(ctx, data, base);
1540
+ const styled = styledChanges(compiledBefore, compiledAfter, base);
917
1541
  const parts = partsOf(ctx, s);
918
1542
  // Exact whole-theme tokens that win over what this dial writes: the dial
919
1543
  // 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
1544
  /** @type {import('./_settings.mjs').Setting[]} */
926
1545
  let exactWins = [];
1546
+ /** Tokens this whole-theme dial changes. */
1547
+ let dialTokens = new Set();
927
1548
  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);
1549
+ const touched = dialTouched(ctx, data, s, base);
948
1550
  exactWins = data.settings.filter(
949
1551
  x => x.source === 'token' && !x.on && !x.when && touched.has(x.thing),
950
1552
  );
1553
+ dialTokens = touched;
951
1554
  }
1555
+ // A role font (font X --on heading) writes --font-family-<role>: an exact
1556
+ // setting of that token wins over it.
1557
+ if (sub === 'set' && s.thing === 'font' && s.on && FONT_ROLES.includes(s.on))
1558
+ exactWins = data.settings.filter(
1559
+ x =>
1560
+ x.source === 'token' &&
1561
+ !x.on &&
1562
+ !x.when &&
1563
+ x.thing === `--font-family-${s.on}`,
1564
+ );
1565
+ // The theme's own source wins over an exact setting, as the exact
1566
+ // setting does over a dial: an exact token the file also sets is named
1567
+ // as the file's below, never as the one that shows after an undo.
1568
+ const ownFirst = new Set(ownSourceTokens(cwd, slug));
1569
+ exactWins = exactWins.filter(x => !ownFirst.has(x.thing));
952
1570
  const kept =
953
1571
  sub === 'set' && s.source === 'dial' && !s.on
954
1572
  ? [
@@ -956,13 +1574,62 @@ async function change(sub, slug, thing, value, options) {
956
1574
  ...exactWins,
957
1575
  ].map(describe)
958
1576
  : [];
1577
+ // The role fonts a whole-theme font sits under.
1578
+ // An exact --font-family-<role> wins over both: that role is named by
1579
+ // the exact note instead.
1580
+ /** @param {string} role */
1581
+ const exactFamily = role =>
1582
+ data.settings.find(
1583
+ x =>
1584
+ x.source === 'token' &&
1585
+ !x.on &&
1586
+ !x.when &&
1587
+ x.thing === `--font-family-${role}`,
1588
+ );
1589
+ const roleOver =
1590
+ sub === 'set' && s.thing === 'font' && !s.on
1591
+ ? data.settings.filter(
1592
+ x =>
1593
+ x.thing === 'font' &&
1594
+ x.on &&
1595
+ ['body', 'heading'].includes(x.on) &&
1596
+ !exactFamily(x.on),
1597
+ )
1598
+ : [];
1599
+ if (sub === 'set' && s.thing === 'font' && !s.on)
1600
+ for (const role of FONT_ROLES) {
1601
+ const exact = exactFamily(role);
1602
+ if (exact && !exactWins.includes(exact)) exactWins.push(exact);
1603
+ }
959
1604
  // 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
- });
1605
+ const DIAL_PROPERTY = wordTable(
1606
+ /** @type {Record<string, RegExp>} */ ({
1607
+ corners: /radius$/,
1608
+ spacing: /^(padding|gap)(-|$)/,
1609
+ }),
1610
+ );
1611
+ // A whole-theme look dial (buttons, surfaces) writes part properties
1612
+ // too: an exact property on one of them wins there, read from the build.
1613
+ const looksOver =
1614
+ sub === 'set' && s.source === 'dial' && !DIAL_PROPERTY[s.thing]
1615
+ ? (() => {
1616
+ const writes = dialWrites(ctx, data, s, base);
1617
+ if (!writes.size) return null;
1618
+ return (
1619
+ data.settings.find(
1620
+ x =>
1621
+ x.source === 'property' &&
1622
+ x.on &&
1623
+ !x.when &&
1624
+ !x.state &&
1625
+ partsOf(ctx, x).some(t => writes.has(`${t}\0${x.thing}`)),
1626
+ ) ?? null
1627
+ );
1628
+ })()
1629
+ : null;
964
1630
  const exactOver =
965
- sub === 'set' && s.source === 'dial' && s.on && DIAL_PROPERTY[s.thing]
1631
+ looksOver ??
1632
+ (sub === 'set' && s.source === 'dial' && s.on && DIAL_PROPERTY[s.thing]
966
1633
  ? (data.settings.find(
967
1634
  x =>
968
1635
  x.source === 'property' &&
@@ -972,13 +1639,151 @@ async function change(sub, slug, thing, value, options) {
972
1639
  (x.when ?? '') === (s.when ?? '') &&
973
1640
  (x.state ?? '') === (s.state ?? ''),
974
1641
  ) ?? null)
975
- : null;
1642
+ : null);
1643
+ // An exact token the theme's own source also sets: the file's value
1644
+ // shows (read from what the build made of it), not the setting.
1645
+ // On parts: every property or token this change writes on a part's
1646
+ // plain or variant rule (a dial's too, and each member of a group) that
1647
+ // the own source sets on that same rule.
1648
+ /** @type {Array<{target: string, key: string, state?: string | null, prop: string, value: string | null}>} */
1649
+ const ownPartHits = [];
1650
+ if (sub === 'set' && s.on) {
1651
+ const a = /** @type {any} */ (compiledBefore)?.components ?? {};
1652
+ const b = /** @type {any} */ (compiledAfter)?.components ?? {};
1653
+ for (const target of new Set([...Object.keys(a), ...Object.keys(b)]))
1654
+ for (const key of new Set([
1655
+ ...Object.keys(a[target] ?? {}),
1656
+ ...Object.keys(b[target] ?? {}),
1657
+ ])) {
1658
+ if (key !== 'base' && !key.startsWith('variant:')) continue;
1659
+ const x = a[target]?.[key] ?? {};
1660
+ const y = b[target]?.[key] ?? {};
1661
+ /**
1662
+ * The changed properties of one rule (or a state block in it)
1663
+ * the own source sets there too.
1664
+ * @param {any} xs @param {any} ys @param {string | null} state
1665
+ */
1666
+ const compare = (xs, ys, state) => {
1667
+ /** @type {Map<string, string | null> | null} */
1668
+ let own = null;
1669
+ for (const prop of new Set([
1670
+ ...Object.keys(xs ?? {}),
1671
+ ...Object.keys(ys ?? {}),
1672
+ ])) {
1673
+ if (JSON.stringify(xs?.[prop]) === JSON.stringify(ys?.[prop]))
1674
+ continue;
1675
+ if (prop.startsWith(':')) {
1676
+ // A state block (`:hover`) in the rule.
1677
+ if (!state) compare(xs?.[prop], ys?.[prop], prop);
1678
+ continue;
1679
+ }
1680
+ const css = prop.startsWith('--')
1681
+ ? prop
1682
+ : prop.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`);
1683
+ own ??= ownPartTokens(cwd, slug, target, key, state);
1684
+ if (own.has(css))
1685
+ ownPartHits.push({
1686
+ target,
1687
+ key,
1688
+ state,
1689
+ prop: css,
1690
+ value: own.get(css) ?? null,
1691
+ });
1692
+ }
1693
+ };
1694
+ compare(x, y, null);
1695
+ }
1696
+ }
1697
+ // A part dial writes its property on each part it reaches: the own
1698
+ // source setting it there wins, whatever else wins over the dial.
1699
+ if (
1700
+ sub === 'set' &&
1701
+ s.source === 'dial' &&
1702
+ s.on &&
1703
+ !s.state &&
1704
+ DIAL_PROPERTY[s.thing]
1705
+ )
1706
+ for (const target of partsOf(ctx, s))
1707
+ for (const [prop, value] of ownPartTokens(
1708
+ cwd,
1709
+ slug,
1710
+ target,
1711
+ s.when ?? 'base',
1712
+ ))
1713
+ if (
1714
+ DIAL_PROPERTY[s.thing].test(prop) &&
1715
+ !ownPartHits.some(h => h.target === target && h.prop === prop)
1716
+ )
1717
+ ownPartHits.push({target, key: s.when ?? 'base', prop, value});
1718
+ // A padding the own source sets on a rule wins over every padding setting
1719
+ // there (the editor writes none), whichever sides each names.
1720
+ if (
1721
+ sub === 'set' &&
1722
+ s.source === 'property' &&
1723
+ s.on &&
1724
+ /^padding(-|$)/.test(s.thing)
1725
+ )
1726
+ for (const target of partsOf(ctx, s)) {
1727
+ const state = s.state ? `:${s.state}` : null;
1728
+ for (const [prop, value] of ownPartTokens(
1729
+ cwd,
1730
+ slug,
1731
+ target,
1732
+ s.when ?? 'base',
1733
+ state,
1734
+ ))
1735
+ if (
1736
+ /^padding(-|$)/.test(prop) &&
1737
+ !ownPartHits.some(h => h.target === target && h.prop === prop)
1738
+ ) {
1739
+ ownPartHits.push({target, key: s.when ?? 'base', state, prop, value});
1740
+ break;
1741
+ }
1742
+ }
1743
+ // A direct setting on exactly the rule the own source sets: its undo
1744
+ // takes it back (anything else the file wins over either way).
1745
+ const ownHitDirect =
1746
+ ownPartHits.length === 1 &&
1747
+ (s.source === 'token' || s.source === 'property') &&
1748
+ ownPartHits[0].target === s.on &&
1749
+ ownPartHits[0].prop === s.thing &&
1750
+ ownPartHits[0].key === (s.when ?? 'base') &&
1751
+ (ownPartHits[0].state ?? null) === (s.state ? `:${s.state}` : null);
1752
+ const ownOverToken =
1753
+ sub !== 'set' || s.when || s.state || s.on
1754
+ ? null
1755
+ : s.source === 'token'
1756
+ ? (Object.entries(ownSourceTokenValues(cwd, slug)).find(
1757
+ ([k]) => k === s.thing,
1758
+ ) ??
1759
+ (ownSourceTokens(cwd, slug).includes(s.thing)
1760
+ ? [s.thing, null]
1761
+ : null))
1762
+ : null;
976
1763
  /** @type {string[]} */
977
1764
  const notes = [
978
1765
  ...(covered.length ? [`replaces ${covered.map(describe).join(', ')}`] : []),
1766
+ ...(ownPartHits.length
1767
+ ? [
1768
+ `${slug}.theme.ts sets ${ownPartHits
1769
+ .slice(0, 3)
1770
+ .map(
1771
+ h =>
1772
+ `${h.prop} on ${h.target}${h.state ? ` ${h.state}` : ''}${h.key === 'base' ? '' : ` when ${h.key}`} itself${h.value != null ? ` (${h.value})` : ''}`,
1773
+ )
1774
+ .join(
1775
+ ', ',
1776
+ )}${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)}\`` : ''}`,
1777
+ ]
1778
+ : []),
1779
+ ...(ownOverToken
1780
+ ? [
1781
+ `${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)}\``,
1782
+ ]
1783
+ : []),
979
1784
  ...(exactWins.length
980
1785
  ? [
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`,
1786
+ `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
1787
  ]
983
1788
  : []),
984
1789
  ...(covers.length
@@ -986,6 +1791,29 @@ async function change(sub, slug, thing, value, options) {
986
1791
  `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
1792
  ]
988
1793
  : []),
1794
+ // Core writes a part's derived variables (a button's or card's radius
1795
+ // variable, read by what is drawn inside it) from plain declarations
1796
+ // only: in a state they keep the plain value, and the result says so.
1797
+ ...(sub === 'set' && s.state && s.on
1798
+ ? (() => {
1799
+ const prop =
1800
+ s.thing === 'corners' || /radius$/.test(s.thing)
1801
+ ? 'borderRadius'
1802
+ : s.thing === 'padding' || s.thing === 'spacing'
1803
+ ? 'padding'
1804
+ : s.thing.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
1805
+ const vars = parts.flatMap(t =>
1806
+ (ctx.derived?.[t] ?? [])
1807
+ .filter(d => d.property === prop)
1808
+ .flatMap(d => d.vars ?? []),
1809
+ );
1810
+ return vars.length
1811
+ ? [
1812
+ `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`,
1813
+ ]
1814
+ : [];
1815
+ })()
1816
+ : []),
989
1817
  // Phones keep the base theme's reading sizes (a coarse pointer below
990
1818
  // the lg width), so a size change says where it applies.
991
1819
  ...(sub === 'set' &&
@@ -1003,14 +1831,30 @@ async function change(sub, slug, thing, value, options) {
1003
1831
  // An exact property on the same part wins over a dial there.
1004
1832
  ...(exactOver
1005
1833
  ? [
1006
- `${describe(exactOver)} is an exact property and wins over ${s.thing} there, so this shows only after \`${P} undo ${slug} ${undoArgs(exactOver)}\``,
1834
+ ownPartHits.length
1835
+ ? `${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`
1836
+ : `${describe(exactOver)} is an exact property and wins over ${s.thing} there, so this shows only after \`${P} undo ${slug} ${undoArgs(exactOver)}\``,
1837
+ ]
1838
+ : []),
1839
+ // A whole-theme font under fonts set for each role shows only where no
1840
+ // role font is set.
1841
+ ...(roleOver.length
1842
+ ? [
1843
+ `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
1844
  ]
1008
1845
  : []),
1009
1846
  // An accepted change that the theme already showed says so.
1010
1847
  ...(sub === 'set' &&
1011
1848
  !exactOver &&
1012
- // With the last build unreadable, nothing was compared.
1013
- !r.notes.some(n => n.includes('could not be read')) &&
1849
+ !roleOver.length &&
1850
+ !ownOverToken &&
1851
+ !ownPartHits.length &&
1852
+ // With the last build unreadable or missing, nothing was compared.
1853
+ !r.notes.some(
1854
+ n =>
1855
+ n.includes('could not be read') ||
1856
+ n.includes('there was no last build'),
1857
+ ) &&
1014
1858
  !r.unchanged &&
1015
1859
  !r.changed.length &&
1016
1860
  !styled.length &&
@@ -1019,6 +1863,23 @@ async function change(sub, slug, thing, value, options) {
1019
1863
  `this changes nothing you see: the theme already shows ${describe(s)} (it is saved, and stays when the base theme changes)`,
1020
1864
  ]
1021
1865
  : []),
1866
+ // A card's content takes one radius from Core, whatever its corners.
1867
+ ...(sub === 'set' &&
1868
+ s.source === 'property' &&
1869
+ s.thing === 'border-radius' &&
1870
+ s.on &&
1871
+ (ctx.derived?.[s.on] ?? []).some(
1872
+ d => d.property === 'borderRadius' && d.vars?.length,
1873
+ ) &&
1874
+ /\s|\//.test(String(s.value).trim())
1875
+ ? [
1876
+ `each corner of ${s.on} takes its own radius; the content that reaches its edges takes one, ${
1877
+ String(s.value)
1878
+ .trim()
1879
+ .split(/[\s/]+/)[0]
1880
+ }, for every corner (Core gives it a single radius)`,
1881
+ ]
1882
+ : []),
1022
1883
  ...(longhands.length
1023
1884
  ? [
1024
1885
  `${s.thing} comes after ${longhands.map(x => x.thing).join(', ')} on ${s.on}, so it replaces them there`,
@@ -1039,6 +1900,20 @@ async function change(sub, slug, thing, value, options) {
1039
1900
  : null
1040
1901
  : null;
1041
1902
  if (s.note) notes.push(s.note);
1903
+ // A token the theme's own source sets itself wins over what this dial
1904
+ // writes, as an exact setting does.
1905
+ const ownWins = ownSourceTokens(cwd, slug).filter(
1906
+ k =>
1907
+ (dialTokens.has(k) ||
1908
+ // A role font writes --font-family-<role>.
1909
+ (s.thing === 'font' && s.on && k === `--font-family-${s.on}`)) &&
1910
+ !exactWins.some(x => x.thing === k),
1911
+ );
1912
+ const ownSet = new Set(ownSourceTokens(cwd, slug));
1913
+ if (ownWins.length)
1914
+ notes.push(
1915
+ `${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)}`,
1916
+ );
1042
1917
  if (PALETTE_DIALS.includes(s.thing) && sub === 'set')
1043
1918
  notes.push(
1044
1919
  ...paletteNotes(
@@ -1046,7 +1921,31 @@ async function change(sub, slug, thing, value, options) {
1046
1921
  s.thing,
1047
1922
  slug,
1048
1923
  modesOf(data),
1049
- ),
1924
+ )
1925
+ // A shade the mapping would pick for a token the theme's own source
1926
+ // sets never shows: the file's value does (named once above).
1927
+ .filter(n => {
1928
+ const subject = /^(?:in (?:light|dark), )?(--[a-z0-9-]+) /.exec(
1929
+ n,
1930
+ )?.[1];
1931
+ return (
1932
+ !subject ||
1933
+ !ownSet.has(subject) ||
1934
+ / uses your exact setting \(/.test(n)
1935
+ );
1936
+ })
1937
+ .map(n => {
1938
+ // The exact color is the one the theme's own source sets: named so.
1939
+ const token = n.split(' ')[0];
1940
+ return ownSet.has(token) && / uses your exact setting \(/.test(n)
1941
+ ? n
1942
+ .replace(
1943
+ ' uses your exact setting (',
1944
+ ` uses the value ${slug}.theme.ts sets (`,
1945
+ )
1946
+ .replace('an exact setting wins', 'your own source wins')
1947
+ : n;
1948
+ }),
1050
1949
  );
1051
1950
  // An exact color the mapping reads (a fill, a tint, text on a fill)
1052
1951
  // changes what it picks around it: say what, as the dial does.
@@ -1104,24 +2003,35 @@ async function change(sub, slug, thing, value, options) {
1104
2003
  if (s.thing === 'font' && sub === 'set')
1105
2004
  notes.unshift(...fontNotes(ctx, {...data, settings: [s]}));
1106
2005
  if (s.thing === 'type' || s.thing === 'headings')
1107
- for (const [m, why] of maskedSettings(data))
2006
+ for (const [m, why] of maskedSettings(data, ctx))
1108
2007
  notes.push(`${describe(m)}: ${why}`);
2008
+ // An earlier setting this one now covers (through a spread too) is named.
2009
+ else if (sub === 'set')
2010
+ for (const [m, why] of maskedSettings(data, ctx))
2011
+ if (m !== s && why.startsWith(describe(s)))
2012
+ notes.push(`${describe(m)} no longer shows: ${why}`);
1109
2013
  if (s.thing === 'type' && sub === 'set' && TYPE_STYLES[s.value].ratio > 1.2)
1110
2014
  notes.push(
1111
2015
  'text below the base size keeps its standard sizes, so small text stays readable',
1112
2016
  );
1113
- // A change that changed nothing writes nothing, the preview included.
2017
+ // A change that changed nothing writes nothing, the preview included,
2018
+ // once preview.html was rendered from the theme as it is now (a retry
2019
+ // after a render that failed renders it).
1114
2020
  const f0 = themeFiles(cwd, slug);
1115
2021
  const p =
1116
- r.unchanged && !png && fs.existsSync(f0.preview)
2022
+ r.unchanged &&
2023
+ !png &&
2024
+ fs.existsSync(f0.preview) &&
2025
+ previewIsCurrent(ctx, slug, data)
1117
2026
  ? {
1118
2027
  preview: shown(cwd, f0.preview),
1119
2028
  pictures: [],
1120
2029
  pictureProblem: null,
1121
2030
  notChecked: null,
1122
2031
  previewStale: [],
2032
+ see: seeLine(cwd, slug, changeFocus(s)),
1123
2033
  }
1124
- : await previewAndRoute(ctx, slug, data, png);
2034
+ : await previewAndRoute(ctx, slug, data, png, changeFocus(s));
1125
2035
  return {
1126
2036
  type: sub === 'set' ? 'themeEdit.set' : 'themeEdit.undo',
1127
2037
  data: {
@@ -1212,6 +2122,9 @@ export async function themeEditShow(theme, options = {}) {
1212
2122
  const section = checkSection(options.section, theme);
1213
2123
  const data = loadTheme(cwd, theme);
1214
2124
  const ctx = await context(cwd);
2125
+ // The app copy is written once show succeeds (at its end), never by a
2126
+ // build a later refusal puts back.
2127
+ holdAfterBuild(ctx);
1215
2128
  refuseStoredTokens(ctx, theme, data);
1216
2129
  // Without React, show still lists the settings and builds the theme, as
1217
2130
  // set does; only the pages, pictures and the checks that render are
@@ -1235,26 +2148,125 @@ export async function themeEditShow(theme, options = {}) {
1235
2148
  ? [installLine(cwd, ['react', 'react-dom'])]
1236
2149
  : // Two copies of React and other install problems are named by
1237
2150
  // doctor; the same show would fail the same way.
1238
- ['astryx doctor'],
2151
+ [`${getCliInvocation(cwd)} doctor`],
1239
2152
  },
1240
2153
  );
1241
2154
  const f = themeFiles(cwd, theme);
1242
2155
  // A build that does not match the settings (a command stopped mid-build,
1243
2156
  // a hand edit, another CLI) is made again from the settings, and said.
1244
- const stale = staleBuild(cwd, theme, data);
2157
+ // An own source that does not parse is refused before anything is
2158
+ // built, written or removed (the build would fail part way).
2159
+ if (!readOnly) refuseThemeParse(cwd, theme);
1245
2160
  const brokenSource = themeSourceProblem(cwd, theme);
1246
- if (stale && !brokenSource && !readOnly) await buildTheme(ctx, theme, data);
2161
+ // Every output, as `compile --check` reads them: one missing or edited by
2162
+ // hand is built again too.
2163
+ let stale = staleBuild(cwd, theme, data);
2164
+ // An own source changed since the editor's build, whose outputs a build
2165
+ // of it now makes as they are (it was compiled since): current, as
2166
+ // `compile --check` reads it, so the editor records the source it was
2167
+ // built with instead of building again. One rule for both.
2168
+ if (
2169
+ stale === sourceChangedReason(theme) &&
2170
+ !brokenSource &&
2171
+ !(await outputsDrift(ctx, theme))
2172
+ ) {
2173
+ if (!readOnly) refreshSourceStamp(cwd, theme);
2174
+ stale = readOnly ? stale : staleBuild(cwd, theme, data);
2175
+ }
2176
+ stale ||= brokenSource ? null : await outputsDrift(ctx, theme);
2177
+ // Every file the build may rewrite or remove (the settings module, the
2178
+ // built outputs, the variants types, section sheets, pictures), so a
2179
+ // theme source that does not build, or builds a value that is not text,
2180
+ // leaves the folder exactly as it was.
2181
+ // An output that was not there is recorded as absent (null), so putting
2182
+ // the folder back removes what the build made new; the palette files in
2183
+ // tokens/ are recorded the same way.
2184
+ /** @type {Map<string, Buffer | null>} */
2185
+ let kept = new Map();
2186
+ const tokensDir = path.join(f.dir, 'tokens');
2187
+ if (stale && !brokenSource && !readOnly) {
2188
+ kept = new Map(
2189
+ fs
2190
+ .readdirSync(f.dir)
2191
+ .filter(
2192
+ n =>
2193
+ n === path.basename(f.settingsTs) ||
2194
+ (n.startsWith(`${theme}.`) &&
2195
+ /\.(css|js|d\.ts|css\.d\.ts|variants\.d\.ts)$/.test(n)) ||
2196
+ /^(sheet-[a-z-]+\.html|(sheet|preview)(-[a-z-]+)?\.png)$/.test(n),
2197
+ )
2198
+ .map(n => [path.join(f.dir, n), fs.readFileSync(path.join(f.dir, n))]),
2199
+ );
2200
+ for (const n of [
2201
+ path.basename(f.settingsTs),
2202
+ `${theme}.css`,
2203
+ `${theme}.js`,
2204
+ `${theme}.d.ts`,
2205
+ `${theme}.css.d.ts`,
2206
+ `${theme}.variants.d.ts`,
2207
+ ])
2208
+ if (!kept.has(path.join(f.dir, n))) kept.set(path.join(f.dir, n), null);
2209
+ if (fs.existsSync(tokensDir))
2210
+ for (const n of fs.readdirSync(tokensDir)) {
2211
+ const file = path.join(tokensDir, n);
2212
+ if (fs.statSync(file).isFile()) kept.set(file, fs.readFileSync(file));
2213
+ }
2214
+ const refs = path.join(tokensDir, `${theme}.palette-refs.ts`);
2215
+ if (!kept.has(refs)) kept.set(refs, null);
2216
+ try {
2217
+ await buildTheme(ctx, theme, data);
2218
+ } catch (e) {
2219
+ putBack(kept, tokensDir);
2220
+ if (e instanceof AstryxError && e.code !== E.ERR_THEME_LOAD) throw e;
2221
+ // An own theme source that no longer builds is named, as `set` names
2222
+ // it; the old build is never shown as current.
2223
+ const why = (e instanceof Error ? e.message : String(e))
2224
+ .split(`${cwd}${path.sep}`)
2225
+ .join('')
2226
+ .replace(/\s*Make sure all imports[^|]*$/s, '')
2227
+ .split('\n')
2228
+ .slice(0, 3)
2229
+ .join(' | ');
2230
+ refuse(
2231
+ E.ERR_THEME_INVALID,
2232
+ `${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)` : ''}`,
2233
+ {run: [`${P} how --list dials`]},
2234
+ );
2235
+ }
2236
+ }
1247
2237
  // The settings loaded whole: a `new` marker beside them is stale.
1248
2238
  if (!readOnly) clearNewMarker(f.dir);
1249
2239
  // A built module that cannot be read (damaged by hand) is built again.
1250
2240
  /** @type {string | null} */
1251
2241
  let unreadable = null;
1252
2242
  const res = await resolvedTokens(ctx, theme).catch(async e => {
2243
+ if (
2244
+ e instanceof AstryxError &&
2245
+ e.code === E.ERR_THEME_INVALID &&
2246
+ kept.size
2247
+ ) {
2248
+ // What this show just built goes back with the refusal.
2249
+ putBack(kept, tokensDir);
2250
+ throw e;
2251
+ }
1253
2252
  if (e instanceof AstryxError || readOnly) throw e;
2253
+ // The source lines the settings need are missing too: the build cannot
2254
+ // be made again until they are back, and show says so (never a run of
2255
+ // show itself).
2256
+ if (brokenSource)
2257
+ refuse(
2258
+ E.ERR_THEME_INVALID,
2259
+ `${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.`,
2260
+ {
2261
+ run: [`cat ${quoteCommandArgument(shown(cwd, f.ts))}`],
2262
+ },
2263
+ );
1254
2264
  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
2265
  await buildTheme(ctx, theme, data);
1256
2266
  return resolvedTokens(ctx, theme);
1257
2267
  });
2268
+ const ownOverNotes = ownOverSettingNotes(cwd, theme, data);
2269
+ const ownMasked = ownOverNotes.map(n => n.slice(0, n.indexOf(': ')));
1258
2270
  const checked = await contrastProblems(ctx, data, res);
1259
2271
  // What cannot be measured is a note, not a problem.
1260
2272
  const problems = checked.filter(x => !x.startsWith('not checked'));
@@ -1265,13 +2277,40 @@ export async function themeEditShow(theme, options = {}) {
1265
2277
  await baseResolved(ctx.project, data.like),
1266
2278
  ctx.project.core.tokenDefaults,
1267
2279
  );
2280
+ // A render that fails here (two copies of React, a component that
2281
+ // throws) is refused as the one above: what this show built goes back,
2282
+ // and the result says so.
2283
+ const rendering = async (/** @type {() => Promise<any>} */ run) => {
2284
+ try {
2285
+ return await run();
2286
+ } catch (e) {
2287
+ if (!(e instanceof Error)) throw e;
2288
+ if (e instanceof AstryxError && e.code !== E.ERR_RENDER_FAILED) throw e;
2289
+ putBack(kept, tokensDir);
2290
+ return refuse(
2291
+ E.ERR_RENDER_FAILED,
2292
+ `${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.`,
2293
+ {run: [`${getCliInvocation(cwd)} doctor`]},
2294
+ );
2295
+ }
2296
+ };
1268
2297
  const preview = noPages
1269
2298
  ? shown(cwd, f.preview)
1270
- : await renderPreview(ctx, theme, data);
1271
- const previewStale = noPages ? [] : await keepPreviewRoute(ctx, theme);
2299
+ : await rendering(() => renderPreview(ctx, theme, data));
2300
+ const previewStale = noPages
2301
+ ? []
2302
+ : await rendering(() => keepPreviewRoute(ctx, theme));
1272
2303
  const sheet = noPages
1273
2304
  ? {file: shown(cwd, f.sheet), components: 0, skipped: []}
1274
- : await renderSheet(ctx, theme, data, {group: section});
2305
+ : await rendering(() => renderSheet(ctx, theme, data, {group: section}));
2306
+ // The full sheet records the build it shows, so a later change tells a
2307
+ // sheet that still matches (after an undo) from one that does not.
2308
+ if (!noPages)
2309
+ stampSheet(
2310
+ section ? path.join(f.dir, `sheet-${section}.html`) : f.sheet,
2311
+ theme,
2312
+ cwd,
2313
+ );
1275
2314
  const modes = modesOf(data);
1276
2315
  const shots =
1277
2316
  png && !noPages
@@ -1290,16 +2329,46 @@ export async function themeEditShow(theme, options = {}) {
1290
2329
  modes,
1291
2330
  )
1292
2331
  : {files: [], problem: null};
2332
+ // The app copy follows the build there now, also when the build was
2333
+ // current and only the copy is missing (a theme made before it existed).
2334
+ if (!readOnly)
2335
+ try {
2336
+ writeAppCopy(ctx, theme, data);
2337
+ } catch (e) {
2338
+ if (/** @type {any} */ (e)?.lockLost) throw e;
2339
+ }
1293
2340
  return {
1294
2341
  type: 'themeEdit.show',
1295
2342
  data: {
1296
2343
  theme,
1297
2344
  like: data.like ?? null,
1298
2345
  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
- }),
2346
+ settings: await (async () => {
2347
+ const looksBase = await baseResolved(ctx.project, data.like).catch(
2348
+ () => null,
2349
+ );
2350
+ return data.settings.map(s => {
2351
+ let masked = maskedSettings(data, ctx).get(s);
2352
+ // A look dial (buttons, surfaces) under an exact property on a
2353
+ // part it writes: named, as corners under border-radius is.
2354
+ if (!masked && looksBase && s.source === 'dial' && !s.on) {
2355
+ const writes = dialWrites(ctx, data, s, looksBase);
2356
+ const exact = writes.size
2357
+ ? data.settings.find(
2358
+ x =>
2359
+ x.source === 'property' &&
2360
+ x.on &&
2361
+ !x.when &&
2362
+ !x.state &&
2363
+ partsOf(ctx, x).some(t => writes.has(`${t}\0${x.thing}`)),
2364
+ )
2365
+ : undefined;
2366
+ if (exact)
2367
+ masked = `${describe(exact)} is an exact property and wins over ${s.thing} on ${exact.on}`;
2368
+ }
2369
+ return {...s, parts: partsOf(ctx, s), ...(masked ? {masked} : {})};
2370
+ });
2371
+ })(),
1303
2372
  notes: [
1304
2373
  ...(noReact
1305
2374
  ? [
@@ -1310,19 +2379,38 @@ export async function themeEditShow(theme, options = {}) {
1310
2379
  ? [
1311
2380
  `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
2381
  ]
1313
- : stale
2382
+ : stale && !brokenSource
1314
2383
  ? [
1315
- `the build did not match ${theme}.settings.json (${stale}), so it was built again from the settings`,
2384
+ `the build was not current (${stale}), so it was built again from the settings`,
1316
2385
  ]
1317
- : []),
2386
+ : stale
2387
+ ? [
2388
+ `the build is not current (${stale}), and it was not built again: the theme source cannot carry the settings`,
2389
+ ]
2390
+ : []),
1318
2391
  ...(unreadable ? [unreadable] : []),
1319
2392
  ...(brokenSource
1320
2393
  ? [
1321
- `${brokenSource}, so settings cannot take effect; put back the import, extends and name lines in ${theme}.theme.ts`,
2394
+ `${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
2395
  ]
1323
2396
  : []),
1324
- ...checked.filter(x => x.startsWith('not checked')),
2397
+ // A setting the theme file wins over is not live: no contrast
2398
+ // caveat for it (its own note says it does not show).
2399
+ ...checked.filter(
2400
+ x =>
2401
+ x.startsWith('not checked') &&
2402
+ !ownMasked.some(d => x.includes(` for ${d},`)),
2403
+ ),
1325
2404
  ...fontNotes(ctx, data),
2405
+ ...ownSourceMaskNotes(
2406
+ ctx,
2407
+ cwd,
2408
+ theme,
2409
+ data,
2410
+ await baseResolved(ctx.project, data.like),
2411
+ ),
2412
+ ...ownOverNotes,
2413
+ ...ownPhoneNotes(cwd, theme, data),
1326
2414
  ],
1327
2415
  // A size, number or font is the same in both modes: one value.
1328
2416
  resolved: Object.fromEntries(
@@ -1339,7 +2427,7 @@ export async function themeEditShow(theme, options = {}) {
1339
2427
  res,
1340
2428
  modes[0],
1341
2429
  ),
1342
- ...colorsReport(pal, data),
2430
+ ...colorsReport(pal, data, res, theme),
1343
2431
  problems,
1344
2432
  preview,
1345
2433
  previewStale,
@@ -1348,11 +2436,51 @@ export async function themeEditShow(theme, options = {}) {
1348
2436
  skipped: sheet.skipped,
1349
2437
  pictures: shots.files,
1350
2438
  pictureProblem: shots.problem,
2439
+ // How to use the theme in this app: theme add <theme> for its app copy.
2440
+ wiring: appWiring(ctx, theme, data),
2441
+ ...(() => {
2442
+ // The first time the theme's app copy is written, its files.
2443
+ const wrote = takeFirstAppCopy(cwd, theme);
2444
+ return wrote ? {appCopy: {wrote}} : {};
2445
+ })(),
1351
2446
  colorFiles: pal ? colorFiles(theme) : null,
1352
2447
  },
1353
2448
  };
1354
2449
  }
1355
2450
 
2451
+ /**
2452
+ * The part properties a dial writes, read from what the build writes with
2453
+ * it and without it (so a dial's outputs are never listed by hand), as
2454
+ * `target\0css-property` keys.
2455
+ * @param {import('./_settings.mjs').Ctx} ctx
2456
+ * @param {import('./_settings.mjs').ThemeData} data
2457
+ * @param {import('./_settings.mjs').Setting} dial
2458
+ * @param {{light: Record<string, string>, dark: Record<string, string>}} base
2459
+ * @returns {Set<string>}
2460
+ */
2461
+ function dialWrites(ctx, data, dial, base) {
2462
+ /** @type {Set<string>} */
2463
+ const out = new Set();
2464
+ const comps = (/** @type {import('./_settings.mjs').Setting[]} */ settings) =>
2465
+ /** @type {Record<string, Record<string, Record<string, unknown>>>} */ (
2466
+ compileTheme(ctx, {...data, settings}, base).components ?? {}
2467
+ );
2468
+ let plain;
2469
+ let withDial;
2470
+ try {
2471
+ plain = comps([]);
2472
+ withDial = comps([dial]);
2473
+ } catch {
2474
+ return out;
2475
+ }
2476
+ for (const [target, keys] of Object.entries(withDial))
2477
+ for (const [key, block] of Object.entries(keys ?? {}))
2478
+ for (const [prop, value] of Object.entries(block ?? {}))
2479
+ if (typeof value === 'string' && plain[target]?.[key]?.[prop] !== value)
2480
+ out.add(`${target}\0${kebab(prop)}`);
2481
+ return out;
2482
+ }
2483
+
1356
2484
  /**
1357
2485
  * What applies once `removed` is gone: a whole-theme setting of the same
1358
2486
  * thing for a part setting, a dial that still writes the token, or the
@@ -1364,6 +2492,44 @@ export async function themeEditShow(theme, options = {}) {
1364
2492
  * @returns {string}
1365
2493
  */
1366
2494
  function nowApplies(ctx, data, removed, base) {
2495
+ // A token the theme's own source sets shows its value, whatever else
2496
+ // the settings give it.
2497
+ if (removed.source === 'token' && !removed.on && !removed.when) {
2498
+ const own = ownSourceTokenValues(ctx.project.cwd, data.name)[removed.thing];
2499
+ if (own != null)
2500
+ return `${removed.thing} = ${own} (set in ${data.name}.theme.ts)`;
2501
+ }
2502
+ // On a part, the same for what the own source sets on that part's rule.
2503
+ if (
2504
+ (removed.source === 'token' || removed.source === 'property') &&
2505
+ removed.on
2506
+ ) {
2507
+ const own = ownPartTokens(
2508
+ ctx.project.cwd,
2509
+ data.name,
2510
+ removed.on,
2511
+ removed.when ?? 'base',
2512
+ removed.state ? `:${removed.state}` : null,
2513
+ );
2514
+ if (own.has(removed.thing))
2515
+ return `${removed.thing} = ${own.get(removed.thing) ?? 'its value'} on ${removed.on}${removed.state ? ` :${removed.state}` : ''}${removed.when ? ` when ${removed.when}` : ''} (set in ${data.name}.theme.ts)`;
2516
+ }
2517
+ // A role font removed under an exact --font-family-<role>: that token is
2518
+ // what shows there.
2519
+ if (
2520
+ removed.thing === 'font' &&
2521
+ removed.on &&
2522
+ FONT_ROLES.includes(removed.on)
2523
+ ) {
2524
+ const exact = data.settings.find(
2525
+ x =>
2526
+ x.source === 'token' &&
2527
+ !x.on &&
2528
+ !x.when &&
2529
+ x.thing === `--font-family-${removed.on}`,
2530
+ );
2531
+ if (exact) return describe(exact);
2532
+ }
1367
2533
  // A token a dial still writes (an accent color feeds --color-accent):
1368
2534
  // name that dial.
1369
2535
  if (removed.source === 'token' && !removed.on) {
@@ -1387,21 +2553,35 @@ function nowApplies(ctx, data, removed, base) {
1387
2553
  // exact property on the part that this dial would have competed with.
1388
2554
  if (removed.on) {
1389
2555
  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
- );
2556
+ // The part's or its group's setting for the same variant and state
2557
+ // first (a group's hover after the part's hover goes), then a plain one.
2558
+ /** @param {(x: import('./_settings.mjs').Setting) => boolean} scoped */
2559
+ const find = scoped =>
2560
+ [...data.settings]
2561
+ .reverse()
2562
+ .find(
2563
+ x =>
2564
+ x.thing === removed.thing &&
2565
+ x !== removed &&
2566
+ (!x.mode || x.mode === removed.mode) &&
2567
+ (x.on === removed.on || (fam != null && x.on === fam)) &&
2568
+ scoped(x),
2569
+ );
2570
+ const reaches =
2571
+ (removed.when || removed.state
2572
+ ? find(
2573
+ x =>
2574
+ (x.when ?? '') === (removed.when ?? '') &&
2575
+ (x.state ?? '') === (removed.state ?? ''),
2576
+ )
2577
+ : undefined) ?? find(x => !x.when && !x.state);
1400
2578
  if (reaches) return describe(reaches);
1401
- const DIAL_PROPERTY = /** @type {Record<string, RegExp>} */ ({
1402
- corners: /radius$/,
1403
- spacing: /^(padding|gap)(-|$)/,
1404
- });
2579
+ const DIAL_PROPERTY = wordTable(
2580
+ /** @type {Record<string, RegExp>} */ ({
2581
+ corners: /radius$/,
2582
+ spacing: /^(padding|gap)(-|$)/,
2583
+ }),
2584
+ );
1405
2585
  const exact =
1406
2586
  removed.source === 'dial' && DIAL_PROPERTY[removed.thing]
1407
2587
  ? data.settings.find(
@@ -1412,8 +2592,25 @@ function nowApplies(ctx, data, removed, base) {
1412
2592
  )
1413
2593
  : null;
1414
2594
  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.
2595
+ // A removed exact property leaves the dial whose build writes it there
2596
+ // (buttons, surfaces: read from the build), on the part, its group, or
2597
+ // the whole theme.
2598
+ if (removed.source === 'property') {
2599
+ const targets = partsOf(ctx, removed);
2600
+ const writer = [...data.settings].reverse().find(
2601
+ x =>
2602
+ x.source === 'dial' &&
2603
+ x !== removed &&
2604
+ (!x.on || x.on === removed.on || (fam != null && x.on === fam)) &&
2605
+ (x.when ?? '') === (removed.when ?? '') &&
2606
+ (x.state ?? '') === (removed.state ?? '') &&
2607
+ [...dialWrites(ctx, data, x, base)].some(k => {
2608
+ const [t, prop] = k.split('\0');
2609
+ return targets.includes(t) && prop === removed.thing;
2610
+ }),
2611
+ );
2612
+ if (writer) return describe(writer);
2613
+ }
1417
2614
  if (removed.source === 'property') {
1418
2615
  const dial = Object.entries(DIAL_PROPERTY).find(([, re]) =>
1419
2616
  re.test(removed.thing),
@@ -1469,6 +2666,176 @@ function otherModeNotes(data) {
1469
2666
  ];
1470
2667
  }
1471
2668
 
2669
+ /**
2670
+ * The tokens a whole-theme dial setting writes: those that differ between
2671
+ * the theme's dials with it and without it (a font role's family, and every
2672
+ * text size when the scale moves).
2673
+ * @param {import('./_settings.mjs').Ctx} ctx
2674
+ * @param {import('./_settings.mjs').ThemeData} data
2675
+ * @param {import('./_settings.mjs').Setting} s
2676
+ * @param {any} base
2677
+ * @returns {Set<string>}
2678
+ */
2679
+ function dialTouched(ctx, data, s, base) {
2680
+ /** @param {import('./_settings.mjs').Setting[]} list */
2681
+ const dialsOnly = list => ({
2682
+ ...data,
2683
+ settings: list.filter(x => x.source === 'dial'),
2684
+ });
2685
+ const withDial = compileTheme(ctx, dialsOnly(data.settings), base);
2686
+ const without = compileTheme(
2687
+ ctx,
2688
+ dialsOnly(data.settings.filter(x => x !== s)),
2689
+ base,
2690
+ );
2691
+ const differs = (/** @type {unknown} */ a, /** @type {unknown} */ b) =>
2692
+ JSON.stringify(a) !== JSON.stringify(b);
2693
+ const touched = new Set(
2694
+ [
2695
+ ...Object.keys(withDial.tokens ?? {}),
2696
+ ...Object.keys(without.tokens ?? {}),
2697
+ ].filter(k => differs(withDial.tokens?.[k], without.tokens?.[k])),
2698
+ );
2699
+ for (const r of FONT_ROLES)
2700
+ if (differs(withDial.typography?.[r], without.typography?.[r]))
2701
+ touched.add(`--font-family-${r}`);
2702
+ // The type scale feeds every font size and every role size (body,
2703
+ // headings, labels): an exact one of those keeps its text as it is.
2704
+ if (differs(withDial.typography?.scale, without.typography?.scale))
2705
+ for (const k of Object.keys(ctx.project.core.tokenDefaults ?? {}))
2706
+ if (/^--(font-size-|text-[a-z0-9-]+-size$)/.test(k)) touched.add(k);
2707
+ return touched;
2708
+ }
2709
+
2710
+ /**
2711
+ * The family and weight tokens the theme's own source sets as plain tokens
2712
+ * that phones do not show: on top of a base theme, its rule for those
2713
+ * screens sets its type again (a rule wins over plain tokens, by Core's
2714
+ * contract), unless an exact setting is repeated after it. The note names
2715
+ * the fix within that contract: the theme's typography, or a same-screens
2716
+ * rule.
2717
+ * @param {string} cwd
2718
+ * @param {string} slug
2719
+ * @param {import('./_settings.mjs').ThemeData} data
2720
+ * @returns {string[]}
2721
+ */
2722
+ function ownPhoneNotes(cwd, slug, data) {
2723
+ if (!data.like) return [];
2724
+ const exact = new Set(
2725
+ data.settings
2726
+ .filter(x => x.source === 'token' && !x.on && !x.when && !x.state)
2727
+ .map(x => x.thing),
2728
+ );
2729
+ const lost = ownSourceTokens(cwd, slug).filter(
2730
+ k => PHONE_TYPE.test(k) && !exact.has(k),
2731
+ );
2732
+ if (!lost.length) return [];
2733
+ const families = lost.filter(k => /^--font-family-/.test(k));
2734
+ const role =
2735
+ /^--font-family-([a-z]+)$/.exec(families[0] ?? '')?.[1] ?? 'body';
2736
+ return [
2737
+ `on ${PHONES}, the base theme's type shows for ${lost.slice(0, 4).join(', ')}${lost.length > 4 ? ` and ${lost.length - 4} more` : ''}, which ${slug}.theme.ts sets as plain tokens: the base theme's rule for those screens sets its type again, and a rule wins over plain tokens there. To keep yours on every screen, set ${lost.length > 1 ? 'them' : 'it'} on the theme's typography in ${slug}.theme.ts (such as typography: {${role}: {family: ...}}, which that rule then keeps), or in a rule for the same screens`,
2738
+ ];
2739
+ }
2740
+
2741
+ /**
2742
+ * Notes for the exact settings the theme's own source sets itself (a
2743
+ * whole-theme token, or a token or property on a part's plain or variant
2744
+ * rule): the file's value shows, not the setting.
2745
+ * @param {string} cwd
2746
+ * @param {string} slug
2747
+ * @param {import('./_settings.mjs').ThemeData} data
2748
+ * @returns {string[]}
2749
+ */
2750
+ function ownOverSettingNotes(cwd, slug, data) {
2751
+ const top = ownSourceTokenValues(cwd, slug);
2752
+ const topKeys = new Set(ownSourceTokens(cwd, slug));
2753
+ /** @type {Map<string, Map<string, string | null>>} */
2754
+ const parts = new Map();
2755
+ /** @type {string[]} */
2756
+ const out = [];
2757
+ for (const x of data.settings) {
2758
+ if (x.source !== 'token' && x.source !== 'property') continue;
2759
+ if (!x.on) {
2760
+ if (x.source === 'token' && !x.when && topKeys.has(x.thing))
2761
+ out.push(
2762
+ `${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)` : ''}`,
2763
+ );
2764
+ continue;
2765
+ }
2766
+ const state = x.state ? `:${x.state}` : null;
2767
+ const key = `${x.on}\0${x.when ?? 'base'}\0${state ?? ''}`;
2768
+ if (!parts.has(key))
2769
+ parts.set(key, ownPartTokens(cwd, slug, x.on, x.when ?? 'base', state));
2770
+ const own = /** @type {Map<string, string | null>} */ (parts.get(key));
2771
+ // A padding the own source sets on the rule wins over every padding
2772
+ // setting there, whichever sides each names.
2773
+ const shown = own.has(x.thing)
2774
+ ? x.thing
2775
+ : /^padding(-|$)/.test(x.thing)
2776
+ ? [...own.keys()].find(k => /^padding(-|$)/.test(k))
2777
+ : undefined;
2778
+ if (shown)
2779
+ out.push(
2780
+ `${describe(x)}: ${slug}.theme.ts sets ${shown} on ${x.on}${state ? ` ${state}` : ''}${x.when ? ` when ${x.when}` : ''} itself${own.get(shown) != null ? ` (${own.get(shown)})` : ''}, so this setting does not show there`,
2781
+ );
2782
+ }
2783
+ return out;
2784
+ }
2785
+
2786
+ /** Phones, as the base themes' type rule names them. */
2787
+ const PHONES = 'phones (touch screens below 1024px)';
2788
+
2789
+ /**
2790
+ * What taking tokens out of the theme file lets show: the dial, or an
2791
+ * exact setting of a token first (file > exact > dial), with its undo.
2792
+ * @param {string} slug
2793
+ * @param {string} dial the dial's name
2794
+ * @param {string[]} tokens
2795
+ * @param {import('./_settings.mjs').ThemeData} data
2796
+ */
2797
+ function ownTakeOut(slug, dial, tokens, data) {
2798
+ const it = tokens.length > 1 ? 'them' : 'it';
2799
+ const exact = data.settings.filter(
2800
+ x =>
2801
+ x.source === 'token' &&
2802
+ !x.on &&
2803
+ !x.when &&
2804
+ !x.state &&
2805
+ tokens.includes(x.thing),
2806
+ );
2807
+ if (!exact.length)
2808
+ return `take ${it} out of ${slug}.theme.ts to let ${dial} set ${it}`;
2809
+ 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}`;
2810
+ }
2811
+
2812
+ /**
2813
+ * Notes for the tokens the theme's own source sets that a whole-theme dial
2814
+ * also writes: the source wins, so the dial does not change them.
2815
+ * @param {import('./_settings.mjs').Ctx} ctx
2816
+ * @param {string} cwd
2817
+ * @param {string} slug
2818
+ * @param {import('./_settings.mjs').ThemeData} data
2819
+ * @param {any} base
2820
+ * @returns {string[]}
2821
+ */
2822
+ function ownSourceMaskNotes(ctx, cwd, slug, data, base) {
2823
+ const own = ownSourceTokens(cwd, slug);
2824
+ if (!own.length) return [];
2825
+ /** @type {string[]} */
2826
+ const notes = [];
2827
+ for (const s of data.settings) {
2828
+ if (s.source !== 'dial' || s.on || s.when || s.state) continue;
2829
+ const touched = dialTouched(ctx, data, s, base);
2830
+ const wins = own.filter(k => touched.has(k));
2831
+ if (wins.length)
2832
+ notes.push(
2833
+ `${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)}`,
2834
+ );
2835
+ }
2836
+ return notes;
2837
+ }
2838
+
1472
2839
  /**
1473
2840
  * Each corners or spacing dial set on a part or group, with what its parts
1474
2841
  * get, beside the whole-theme value: `corners large on containers ->
@@ -1481,7 +2848,7 @@ function otherModeNotes(data) {
1481
2848
  * @returns {string[]}
1482
2849
  */
1483
2850
  function partValues(ctx, data, res, mode) {
1484
- const masked = maskedSettings(data);
2851
+ const masked = maskedSettings(data, ctx);
1485
2852
  return data.settings
1486
2853
  .filter(
1487
2854
  s =>
@@ -1554,9 +2921,13 @@ function partValues(ctx, data, res, mode) {
1554
2921
  * says so), and the contrast moves behind the shade choices.
1555
2922
  * @param {import('./_palette.mjs').PaletteMapping | null} pal
1556
2923
  * @param {import('./_settings.mjs').ThemeData} data
2924
+ * @param {Record<'light' | 'dark', Record<string, string>>} [built] the
2925
+ * built theme's resolved values: where one differs from the generated
2926
+ * shade with no exact setting, the theme's own source changed it
2927
+ * @param {string} [slug]
1557
2928
  * @returns {{vibrancy: number | null, colors: import('./theme-edit.type.mjs').ThemeEditColor[], colorNotes: string[]}}
1558
2929
  */
1559
- function colorsReport(pal, data) {
2930
+ function colorsReport(pal, data, built, slug = '') {
1560
2931
  if (!pal) return {vibrancy: null, colors: [], colorNotes: []};
1561
2932
  /** What the user set for each token exactly, in each mode. */
1562
2933
  const exactBy =
@@ -1566,6 +2937,19 @@ function colorsReport(pal, data) {
1566
2937
  for (const m of s.mode ? [s.mode] : ['light', 'dark'])
1567
2938
  (exactBy[s.thing] ??= {})[/** @type {'light' | 'dark'} */ (m)] =
1568
2939
  s.value;
2940
+ /** Tokens the theme's own source sets to another value than generated. */
2941
+ const ownBy =
2942
+ /** @type {Record<string, {light?: string, dark?: string}>} */ ({});
2943
+ for (const [k, v] of Object.entries(pal.tokens))
2944
+ for (const m of /** @type {const} */ (['light', 'dark'])) {
2945
+ const now = built?.[m]?.[k];
2946
+ if (
2947
+ now &&
2948
+ !exactBy[k]?.[m] &&
2949
+ now.trim().toLowerCase() !== String(v[m].color).trim().toLowerCase()
2950
+ )
2951
+ (ownBy[k] ??= {})[m] = now;
2952
+ }
1569
2953
  /** @param {import('./_palette.mjs').StopRef} r */
1570
2954
  const shade = r =>
1571
2955
  r.family === 'black' || r.family === 'white'
@@ -1587,12 +2971,14 @@ function colorsReport(pal, data) {
1587
2971
  k,
1588
2972
  // Each mode says what it shows: the exact setting where one is
1589
2973
  // made for it, else the generated shade.
1590
- exactBy[k]
2974
+ exactBy[k] || ownBy[k]
1591
2975
  ? modes
1592
2976
  .map(m =>
1593
- exactBy[k][m] != null
2977
+ exactBy[k]?.[m] != null
1594
2978
  ? `${m} ${exactBy[k][m]} (your exact setting wins over the generated ${shade(v[m])})`
1595
- : `${m} ${shade(v[m])}`,
2979
+ : ownBy[k]?.[m] != null
2980
+ ? `${m} ${ownBy[k][m]} (your change in ${slug}.theme.ts wins over the generated ${shade(v[m])})`
2981
+ : `${m} ${shade(v[m])}`,
1596
2982
  )
1597
2983
  .join(', ')
1598
2984
  : shades(v),
@@ -1600,9 +2986,22 @@ function colorsReport(pal, data) {
1600
2986
  ),
1601
2987
  })),
1602
2988
  colorNotes: [
1603
- ...pal.notes,
2989
+ // A note about a token the theme's own source changed is dropped:
2990
+ // what it says no longer holds.
2991
+ ...pal.notes.filter(
2992
+ n =>
2993
+ !Object.keys(ownBy).some(k =>
2994
+ new RegExp(`${k.replace(/[-]/g, '\\-')}(?![\\w-])`).test(n),
2995
+ ),
2996
+ ),
1604
2997
  ...pal.contrast
1605
2998
  .filter(c => modes.includes(c.mode))
2999
+ // A pairing the theme's own source changed no longer holds.
3000
+ .filter(
3001
+ c =>
3002
+ !ownBy[c.token]?.[/** @type {'light' | 'dark'} */ (c.mode)] &&
3003
+ !ownBy[c.against]?.[/** @type {'light' | 'dark'} */ (c.mode)],
3004
+ )
1606
3005
  .filter(c => c.note || !c.pass || c.stop !== c.preferred)
1607
3006
  .map(c =>
1608
3007
  c.note
@@ -1611,7 +3010,12 @@ function colorsReport(pal, data) {
1611
3010
  ? `${c.token} ${c.mode}: shade ${c.stop}, not ${c.preferred}, so it reads at ${c.ratio}:1 on ${c.against}`
1612
3011
  : `${c.token} ${c.mode}: only ${c.ratio}:1 on ${c.against} at shade ${c.stop} (needs ${c.needs}:1)`,
1613
3012
  ),
1614
- ],
3013
+ ].filter(
3014
+ n =>
3015
+ !Object.keys(ownBy).some(k =>
3016
+ new RegExp(`${k.replace(/[-]/g, '\\-')}(?![\\w-])`).test(n),
3017
+ ),
3018
+ ),
1615
3019
  };
1616
3020
  }
1617
3021
 
@@ -1640,7 +3044,16 @@ export async function themeEditUndo(theme, options = {}) {
1640
3044
  if (thing === 'base' || thing === 'mode') {
1641
3045
  requireProject(cwd);
1642
3046
  const now = loadTheme(cwd, theme, thing);
1643
- const [first] = readHistory(themeFiles(cwd, theme).history).steps;
3047
+ const historyFile = themeFiles(cwd, theme).history;
3048
+ const {steps, dropped} = readHistory(historyFile);
3049
+ const [first] = steps;
3050
+ // `new` writes no history: with none, no change is saved (a new theme,
3051
+ // or a history deleted). An empty one is every step undone, back to how
3052
+ // the theme was made. A full one may have lost its oldest steps.
3053
+ const noHistory = !fs.existsSync(historyFile);
3054
+ const reachesStart =
3055
+ (steps.length > 0 && steps.length < HISTORY_STEPS) ||
3056
+ (!noHistory && steps.length === 0 && dropped === 0);
1644
3057
  /** @type {any} */
1645
3058
  let made = now;
1646
3059
  try {
@@ -1650,10 +3063,24 @@ export async function themeEditUndo(theme, options = {}) {
1650
3063
  }
1651
3064
  const of = (/** @type {any} */ d) =>
1652
3065
  thing === 'base' ? (d?.like ?? 'none') : (d?.mode ?? 'both');
3066
+ // A step in between that had another value: changed and changed back.
3067
+ const changedBack = steps.some(step => {
3068
+ try {
3069
+ return of(JSON.parse(step.replace(/^\uFEFF/, ''))) !== of(now);
3070
+ } catch {
3071
+ return false;
3072
+ }
3073
+ });
1653
3074
  if (of(made) === of(now))
1654
3075
  refuse(
1655
3076
  E.ERR_THEME_NOT_SET,
1656
- `${thing} was never changed: it is ${of(now)}, as ${theme} was made.`,
3077
+ reachesStart && changedBack
3078
+ ? `${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.`
3079
+ : reachesStart
3080
+ ? `${thing} was never changed: it is ${of(now)}, as ${theme} was made.`
3081
+ : noHistory
3082
+ ? `${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.`
3083
+ : `${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
3084
  {run: [`${P} show ${theme}`]},
1658
3085
  );
1659
3086
  return change('set', theme, thing, of(made), options);
@@ -1695,6 +3122,12 @@ export async function themeEditUndo(theme, options = {}) {
1695
3122
  // entry replaces it without the current file being read.
1696
3123
  /** @type {import('./_settings.mjs').ThemeData | null} */
1697
3124
  let current = null;
3125
+ // A file in the theme that is a folder or cannot be read is named first;
3126
+ // the damaged-settings path below never sees it.
3127
+ if (slugOk(theme)) refuseUnreadableFiles(cwd, theme);
3128
+ // A link in the theme is refused as set refuses it, never read as an
3129
+ // empty history.
3130
+ if (slugOk(theme)) refuseLinks(cwd, theme);
1698
3131
  try {
1699
3132
  current = loadTheme(cwd, theme);
1700
3133
  } catch (e) {
@@ -1707,7 +3140,7 @@ export async function themeEditUndo(theme, options = {}) {
1707
3140
  E.ERR_THEME_INVALID,
1708
3141
  `${theme}.history.json is damaged, so there is no step to go back to.`,
1709
3142
  {
1710
- fix: `delete ${shown(cwd, f.history)}: the next change starts a new history, and your settings stay as they are`,
3143
+ 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
3144
  run: [`${P} show ${theme}`],
1712
3145
  },
1713
3146
  );
@@ -1783,13 +3216,35 @@ export async function themeEditUndo(theme, options = {}) {
1783
3216
  E.ERR_THEME_INVALID,
1784
3217
  `The settings before the last change, in ${theme}.history.json, are damaged: ${still}.`,
1785
3218
  {
1786
- fix: `delete ${shown(cwd, f.history)}: the next change starts a new history, and your settings stay as they are`,
3219
+ 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
3220
  run: [`${P} show ${theme}`],
1788
3221
  },
1789
3222
  );
1790
3223
  prev = repaired.data;
1791
3224
  leftOut = repaired.dropped;
1792
3225
  }
3226
+ // The checks that need this Core too (a token's type, a part, a state,
3227
+ // a name that is no token or property): what they refuse is left out of
3228
+ // the step, with the same note, so the build stays valid.
3229
+ {
3230
+ const bad = new Set(storedProblems(ctx, theme, prev).map(p => p.setting));
3231
+ if (bad.size) {
3232
+ leftOut = [...leftOut, ...prev.settings.filter(s => bad.has(s))];
3233
+ prev = {...prev, settings: prev.settings.filter(s => !bad.has(s))};
3234
+ }
3235
+ }
3236
+ // The steps a later undo can still go back to: one equal to the settings
3237
+ // it would leave (a step this undo left a setting out of may then equal
3238
+ // the next one) is skipped, as undo skips it.
3239
+ let stepsLeft = 0;
3240
+ {
3241
+ let at = JSON.stringify(prev);
3242
+ for (let i = history.length - 1; i >= 0; i--)
3243
+ if (!same(history[i], at)) {
3244
+ stepsLeft++;
3245
+ at = history[i];
3246
+ }
3247
+ }
1793
3248
  // The popped history is written with the change, inside its rollback.
1794
3249
  const committed = await commitTheme(ctx, theme, prev, {
1795
3250
  history: false,
@@ -1825,7 +3280,18 @@ export async function themeEditUndo(theme, options = {}) {
1825
3280
  );
1826
3281
  if (current && current.mode !== prev.mode)
1827
3282
  undone.push(`mode ${current.mode} is back to ${prev.mode}`);
1828
- const p = await previewAndRoute(ctx, theme, prev, png);
3283
+ // The page most about what the step reverted: Colors for a color,
3284
+ // Components for a part setting, else Overview.
3285
+ const touched = [
3286
+ ...[...was].filter(([k, s]) => now.get(k)?.value !== s.value),
3287
+ ...[...now].filter(([k]) => !was.has(k)),
3288
+ ].map(([, s]) => changeFocus(s));
3289
+ const focus = touched.includes('colors')
3290
+ ? 'colors'
3291
+ : touched.includes('components')
3292
+ ? 'components'
3293
+ : 'overview';
3294
+ const p = await previewAndRoute(ctx, theme, prev, png, focus);
1829
3295
  return {
1830
3296
  type: 'themeEdit.undo',
1831
3297
  data: {
@@ -1833,7 +3299,7 @@ export async function themeEditUndo(theme, options = {}) {
1833
3299
  action: 'step',
1834
3300
  undone,
1835
3301
  settings: prev.settings.length,
1836
- stepsLeft: history.length,
3302
+ stepsLeft: stepsLeft,
1837
3303
  // What the step back changed, as a change reports it.
1838
3304
  changedTokens: committed.changed,
1839
3305
  problems: committed.problems,