@astryxdesign/cli 0.7.14-canary.gfb823d9 → 0.7.14

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 (135) hide show
  1. package/CHANGELOG.md +197 -0
  2. package/api/component/_adapter.d.mts +15 -0
  3. package/api/component/_adapter.mjs +76 -0
  4. package/api/component/component.mjs +8 -1
  5. package/api/search/_named-keywords.d.mts +31 -0
  6. package/api/search/_named-keywords.mjs +177 -0
  7. package/api/search/search-index.mjs +8 -1
  8. package/api/search/search.d.mts +6 -1
  9. package/api/search/search.mjs +49 -8
  10. package/api/theme/_adapter.d.mts +33 -0
  11. package/api/theme/_adapter.mjs +352 -16
  12. package/api/theme/build/build.mjs +261 -10
  13. package/api/theme/eject/eject.mjs +13 -1
  14. package/api/theme/list/list.mjs +11 -2
  15. package/api/theme/palette/generate/color.d.mts +2 -0
  16. package/api/theme/palette/generate/color.mjs +1 -1
  17. package/api/theme/template/template.mjs +139 -6
  18. package/api/theme/theme.type.d.mts +15 -1
  19. package/api/theme/theme.type.mjs +9 -3
  20. package/api/theme/themeAdd.doc.mjs +1 -1
  21. package/api/theme/themeBuild.doc.mjs +10 -2
  22. package/api/theme/themeEject.doc.mjs +2 -2
  23. package/api/theme/themeListAvailable.doc.mjs +1 -1
  24. package/api/theme/themeRemove.doc.mjs +1 -1
  25. package/api/theme/themeTemplate.doc.mjs +8 -0
  26. package/api/theme/themeUse.doc.mjs +1 -1
  27. package/api/theme-edit/_adapter.d.mts +36 -2
  28. package/api/theme-edit/_adapter.mjs +340 -12
  29. package/api/theme-edit/_check.d.mts +28 -25
  30. package/api/theme-edit/_check.mjs +876 -308
  31. package/api/theme-edit/_color.d.mts +53 -4
  32. package/api/theme-edit/_color.mjs +406 -79
  33. package/api/theme-edit/_compiler.d.mts +14 -6
  34. package/api/theme-edit/_compiler.mjs +89 -59
  35. package/api/theme-edit/_context.d.mts +28 -8
  36. package/api/theme-edit/_context.mjs +142 -19
  37. package/api/theme-edit/_edit.d.mts +3 -1
  38. package/api/theme-edit/_edit.mjs +746 -76
  39. package/api/theme-edit/_how-commands.d.mts +91 -0
  40. package/api/theme-edit/_how-commands.mjs +269 -0
  41. package/api/theme-edit/_how-question.d.mts +57 -0
  42. package/api/theme-edit/_how-question.mjs +2574 -0
  43. package/api/theme-edit/_how.d.mts +27 -8
  44. package/api/theme-edit/_how.mjs +776 -175
  45. package/api/theme-edit/_overview.d.mts +9 -0
  46. package/api/theme-edit/_overview.mjs +296 -0
  47. package/api/theme-edit/_palette.d.mts +155 -15
  48. package/api/theme-edit/_palette.mjs +1446 -262
  49. package/api/theme-edit/_parts.mjs +61 -5
  50. package/api/theme-edit/_png.d.mts +18 -6
  51. package/api/theme-edit/_png.mjs +135 -25
  52. package/api/theme-edit/_preview-app.d.mts +32 -11
  53. package/api/theme-edit/_preview-app.mjs +1976 -285
  54. package/api/theme-edit/_preview.d.mts +39 -8
  55. package/api/theme-edit/_preview.mjs +367 -41
  56. package/api/theme-edit/_settings.d.mts +147 -11
  57. package/api/theme-edit/_settings.mjs +908 -99
  58. package/api/theme-edit/_tables.d.mts +4 -16
  59. package/api/theme-edit/_tables.mjs +51 -117
  60. package/api/theme-edit/theme-edit.type.d.mts +102 -66
  61. package/api/theme-edit/theme-edit.type.mjs +58 -40
  62. package/api/theme-edit/themeEditHow.doc.mjs +17 -6
  63. package/api/theme-edit/themeEditNew.doc.mjs +21 -5
  64. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +18 -5
  65. package/api/theme-edit/themeEditPreviewApp.doc.mjs +12 -9
  66. package/api/theme-edit/themeEditPreviewList.doc.mjs +11 -2
  67. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +29 -3
  68. package/api/theme-edit/themeEditSet.doc.mjs +14 -8
  69. package/api/theme-edit/themeEditShow.doc.mjs +10 -5
  70. package/api/theme-edit/themeEditUndo.doc.mjs +9 -4
  71. package/assets/discover/official-packages.json +4 -0
  72. package/assets/docs/tree/icon-sets.doc.mjs +3 -3
  73. package/assets/docs.generated.json +1 -0
  74. package/assets/icons/definitions/bookmarkAdd.doc.mjs +9 -0
  75. package/assets/icons/definitions/documentSearch.doc.mjs +9 -0
  76. package/assets/icons/definitions/keyboard.doc.mjs +9 -0
  77. package/assets/icons/definitions/paintBrush.doc.mjs +9 -0
  78. package/assets/icons/definitions/wallet.doc.mjs +9 -0
  79. package/assets/preview-app/gitignore +3 -0
  80. package/assets/templates/blocks/components/ButtonGroup/ButtonGroupShowcase.doc.mjs +1 -1
  81. package/assets/templates/blocks/components/Lightbox/LightboxGallery.tsx +1 -1
  82. package/assets/templates/components.generated.json +1 -0
  83. package/assets/templates/pages/gallery-hero/page.tsx +8 -2
  84. package/assets/templates/pages/settings-dialog/template.doc.mjs +3 -3
  85. package/assets/templates/pages/side-gallery/page.tsx +1 -1
  86. package/assets/templates/pages/table-filter/template.doc.mjs +2 -2
  87. package/assets/templates/pages/theme-showcase/template.doc.mjs +1 -1
  88. package/clients/cli/bin/astryx.mjs +37 -5
  89. package/clients/cli/commands/experimental/theme.mjs +422 -57
  90. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +22 -9
  91. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +103 -4
  92. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +13 -8
  93. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +5 -5
  94. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +5 -5
  95. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  96. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +3 -2
  97. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +2 -8
  98. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +2 -2
  99. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  100. package/clients/cli/commands/experimental-theme-targets.doc.mjs +1 -1
  101. package/clients/cli/commands/experimental-theme.doc.mjs +3 -4
  102. package/clients/cli/commands/theme-build.doc.mjs +1 -1
  103. package/clients/cli/commands/theme-eject.doc.mjs +3 -3
  104. package/clients/cli/commands/theme-remove.doc.mjs +2 -2
  105. package/clients/cli/commands/theme-template.doc.mjs +11 -4
  106. package/clients/cli/commands/theme.mjs +145 -46
  107. package/clients/cli/commands.generated.json +1 -0
  108. package/clients/cli/index.mjs +96 -5
  109. package/clients/cli/lib/json-shim.mjs +29 -1
  110. package/foundation/config/project.d.mts +16 -2
  111. package/foundation/config/project.mjs +40 -6
  112. package/foundation/config/theme-state.d.mts +9 -0
  113. package/foundation/config/theme-state.mjs +20 -1
  114. package/foundation/discovery/template-adapter.d.mts +12 -1
  115. package/foundation/discovery/template-adapter.mjs +29 -4
  116. package/foundation/discovery/template-icons.d.mts +13 -0
  117. package/foundation/discovery/template-icons.mjs +76 -0
  118. package/foundation/discovery/template-needs.d.mts +7 -0
  119. package/foundation/discovery/template-needs.mjs +117 -8
  120. package/foundation/discovery/template-source-tree.d.mts +5 -1
  121. package/foundation/discovery/template-source-tree.mjs +6 -4
  122. package/foundation/discovery/theme-discovery.d.mts +14 -3
  123. package/foundation/discovery/theme-discovery.mjs +45 -12
  124. package/foundation/doc-compiler/import.mjs +68 -3
  125. package/foundation/doc-compiler/stored-docs.d.mts +27 -0
  126. package/foundation/doc-compiler/stored-docs.mjs +65 -0
  127. package/foundation/fs/fs-error.d.mts +17 -0
  128. package/foundation/fs/fs-error.mjs +34 -0
  129. package/foundation/response/error-codes.d.mts +3 -1
  130. package/foundation/response/error-codes.doc.mjs +13 -1
  131. package/foundation/response/error-codes.mjs +11 -1
  132. package/foundation/response/response-types.doc.mjs +6 -6
  133. package/package.json +6 -7
  134. package/clients/cli/commands/experimental-theme-palette-generate.doc.mjs +0 -73
  135. package/clients/cli/commands/experimental-theme-palette.doc.mjs +0 -37
@@ -13,36 +13,50 @@ import * as fs from 'node:fs';
13
13
  import {AstryxError} from '../error.mjs';
14
14
  import {
15
15
  AUTO_SPREAD,
16
+ DIALS,
16
17
  FAMILIES,
17
18
  KEY_TOKENS,
18
19
  LIKE,
19
20
  P,
21
+ SPACING,
22
+ TYPE_STYLES,
20
23
  familyOf,
21
24
  } from './_tables.mjs';
22
25
  import {
23
26
  commitTheme,
24
27
  compileTheme,
28
+ cornerPx,
25
29
  contrastProblems,
26
30
  describe,
27
31
  keyOf,
28
32
  loadTheme,
33
+ maskedSettings,
29
34
  modesOf,
30
35
  nearest,
36
+ partDefault,
31
37
  partsOf,
38
+ q,
39
+ undoArgs,
40
+ withoutBadValues,
41
+ NAME_RULE,
42
+ readHistory,
32
43
  refuse,
44
+ settingsProblem,
33
45
  resolvedTokens,
34
46
  shown,
35
47
  slugOk,
36
48
  themeFiles,
37
49
  buildTheme,
50
+ staleBuild,
38
51
  } from './_settings.mjs';
39
- import {checkSetting} from './_check.mjs';
52
+ import {checkSetting, exampleOf, storedTokenProblem} from './_check.mjs';
53
+ import {MODAL} from './_compiler.mjs';
40
54
  import {
41
55
  PALETTE_DIALS,
56
+ VIBRANCY_DEFAULT,
42
57
  paletteFiles,
43
58
  paletteMapping,
44
59
  paletteNotes,
45
- paletteToken,
46
60
  } from './_palette.mjs';
47
61
  import {renderPreview, renderSheet} from './_preview.mjs';
48
62
  import {refreshPreviewRoute} from './_preview-app.mjs';
@@ -54,7 +68,7 @@ import {
54
68
  fontNotes,
55
69
  styledChanges,
56
70
  previewAfter,
57
- checkGroup,
71
+ checkSection,
58
72
  } from './_context.mjs';
59
73
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
60
74
 
@@ -64,43 +78,81 @@ const E = ERROR_CODES;
64
78
  * @typedef {import('./theme-edit.type.mjs').ThemeEditChangeOptions} ChangeOptions
65
79
  */
66
80
  /**
67
- * Start a theme in themes/<name>/, optionally on a built-in theme.
81
+ * Start a theme in themes/<name>/, optionally on a built-in theme, with any
82
+ * dial settings applied in the same build. Each setting is checked as `set`
83
+ * checks it, before anything is written.
68
84
  * @experimental
69
85
  * @param {string} name
70
86
  * @param {import('./theme-edit.type.mjs').ThemeEditNewOptions} [options]
71
87
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditNewResponse>}
72
88
  */
73
89
  export async function themeEditNew(name, options = {}) {
74
- const {cwd = process.cwd(), like, png = false} = options;
90
+ const {cwd = process.cwd(), like, png = false, settings = {}} = options;
75
91
  requireProject(cwd);
76
- if (!slugOk(name))
92
+ if (!slugOk(name)) {
93
+ const fixed =
94
+ String(name ?? '')
95
+ .normalize('NFKD')
96
+ .replace(/[\u0300-\u036f]/g, '')
97
+ .toLowerCase()
98
+ .replace(/[^a-z0-9-]+/g, '-')
99
+ .replace(/^[^a-z]+/, '')
100
+ .replace(/-+$/, '')
101
+ .slice(0, 64) || 'my-theme';
77
102
  refuse(
78
103
  E.ERR_INVALID_ARGUMENT,
79
- `"${name ?? ''}" is not a theme name (lowercase letters, digits, dashes, starting with a letter).`,
80
- {run: [`${P} new my-theme`]},
104
+ `"${String(name ?? '').slice(0, 80)}" is not a theme name (${NAME_RULE}).`,
105
+ {run: [`${P} new ${fixed}`]},
81
106
  );
107
+ }
82
108
  const f = themeFiles(cwd, name);
109
+ // A link or a file where the theme goes is never written through or
110
+ // replaced.
111
+ for (const [p, what] of /** @type {const} */ ([
112
+ [f.root, 'themes/'],
113
+ [f.dir, `themes/${name}`],
114
+ ])) {
115
+ const st = fs.lstatSync(p, {throwIfNoEntry: false});
116
+ if (st && (st.isSymbolicLink() || !st.isDirectory()))
117
+ refuse(
118
+ E.ERR_FILE_EXISTS,
119
+ `${what} is ${st.isSymbolicLink() ? 'a link' : 'a file'}, so a theme is not made there.`,
120
+ {run: [`${P} new ${name}-copy`]},
121
+ );
122
+ }
83
123
  if (fs.existsSync(f.settings))
84
124
  refuse(E.ERR_FILE_EXISTS, `Theme "${name}" already exists.`, {
85
- run: [`${P} show ${name}`, `${P} set ${name} base <theme>`],
125
+ run: [`${P} show ${name}`, `${P} set ${name} base neutral`],
86
126
  });
87
127
  if (fs.existsSync(f.dir) && fs.readdirSync(f.dir).length)
88
128
  refuse(
89
129
  E.ERR_FILE_EXISTS,
90
130
  `themes/${name}/ already holds files this command did not make; choose another name.`,
91
- {run: [`${P} new ${name}-2`]},
131
+ {run: [`${P} new ${name}-copy`]},
92
132
  );
93
- if (like && !LIKE.includes(like))
133
+ if (like != null && !LIKE.includes(like))
94
134
  refuse(
95
135
  E.ERR_THEME_BAD_VALUE,
96
- `--like takes ${LIKE.join(', ')}, not "${like}".`,
97
- {didYouMean: nearest(like, LIKE)},
136
+ `--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` : ''}.`,
137
+ {
138
+ didYouMean: nearest(String(like).toLowerCase(), LIKE),
139
+ run: [`${P} new ${name}`],
140
+ },
98
141
  );
99
142
  const ctx = await context(cwd);
100
143
  /** @type {import('./_settings.mjs').ThemeData} */
101
144
  const data = {name, ...(like ? {like} : {}), mode: 'both', settings: []};
145
+ /** @type {import('./_settings.mjs').Ctx} */ (ctx).base = await baseResolved(
146
+ ctx.project,
147
+ data.like,
148
+ );
149
+ applyNewSettings(ctx, name, data, settings);
102
150
  const r = await commitTheme(ctx, name, data, {history: false});
103
151
  const p = await previewAndRoute(ctx, name, data, png);
152
+ /** @type {string[]} */
153
+ const notes = data.settings.some(s => s.thing === 'font')
154
+ ? fontNotes(ctx, data)
155
+ : [];
104
156
  return {
105
157
  type: 'themeEdit.new',
106
158
  data: {
@@ -112,12 +164,105 @@ export async function themeEditNew(name, options = {}) {
112
164
  css: shown(cwd, f.css),
113
165
  module: shown(cwd, f.js),
114
166
  },
167
+ // Every setting it applied: mode is the theme's, not a setting entry.
168
+ settings: [
169
+ ...(settings.mode != null ? [`mode = ${data.mode} (whole theme)`] : []),
170
+ ...data.settings.map(describe),
171
+ ],
172
+ notes,
115
173
  problems: r.problems,
116
174
  ...p,
117
175
  },
118
176
  };
119
177
  }
120
178
 
179
+ /**
180
+ * The dial settings of `new`, checked one at a time in dial order (mode
181
+ * first; a color before vibrancy, which needs one) into `data`.
182
+ * @param {import('./_settings.mjs').Ctx} ctx
183
+ * @param {string} slug
184
+ * @param {import('./_settings.mjs').ThemeData} data
185
+ * @param {Record<string, string | string[] | undefined>} settings
186
+ */
187
+ function applyNewSettings(ctx, slug, data, settings) {
188
+ const given = Object.entries(settings).filter(([, v]) => v != null);
189
+ for (const [thing] of given)
190
+ if (!DIALS[thing] || thing === 'base')
191
+ refuse(
192
+ E.ERR_INVALID_ARGUMENT,
193
+ thing === 'base'
194
+ ? 'new takes the base theme as --like.'
195
+ : `"${thing}" is not a setting new takes; it takes ${Object.keys(
196
+ DIALS,
197
+ )
198
+ .filter(d => d !== 'base')
199
+ .join(', ')}.`,
200
+ {
201
+ didYouMean: nearest(thing, Object.keys(DIALS)),
202
+ run: [`${P} new ${slug} --help`],
203
+ },
204
+ );
205
+ const order = ['mode', ...Object.keys(DIALS).filter(d => d !== 'mode')];
206
+ for (const thing of order) {
207
+ const given = settings[thing];
208
+ if (given == null) continue;
209
+ // `headings` takes a weight and a tracking: one value per axis.
210
+ for (const value of Array.isArray(given) ? given : [given]) {
211
+ /** @type {import('./_settings.mjs').Setting} */
212
+ let s;
213
+ try {
214
+ s = checkSetting(ctx, slug, data, thing, String(value), {}, false);
215
+ } catch (e) {
216
+ throw asNewRefusal(e, slug, settings);
217
+ }
218
+ if (thing === 'mode')
219
+ data.mode = /** @type {'both' | 'light-only' | 'dark-only'} */ (
220
+ s.value
221
+ );
222
+ else {
223
+ const same = data.settings.findIndex(x => keyOf(x) === keyOf(s));
224
+ if (same >= 0)
225
+ refuse(
226
+ E.ERR_INVALID_ARGUMENT,
227
+ `--${thing} was given two values for the same thing (${data.settings[same].value}, ${s.value}); give one.`,
228
+ {run: [`${P} new ${slug} --${thing} ${q(s.value)}`]},
229
+ );
230
+ data.settings.push(s);
231
+ }
232
+ }
233
+ }
234
+ }
235
+
236
+ /**
237
+ * A refusal from a setting `new` was given, with its suggestions turned
238
+ * into `new` commands: the theme does not exist yet, so a `set` would fail.
239
+ * @param {unknown} e
240
+ * @param {string} slug
241
+ * @param {Record<string, string | string[] | undefined>} settings
242
+ */
243
+ function asNewRefusal(e, slug, settings) {
244
+ if (!(e instanceof AstryxError)) return e;
245
+ const flags = Object.entries(settings)
246
+ .filter(([, v]) => v != null)
247
+ .flatMap(([k, v]) => (Array.isArray(v) ? v : [v]).map(x => [k, x]))
248
+ .map(([k, v]) => `--${k} ${q(v)}`);
249
+ const setPrefix = `${P} set ${slug} `;
250
+ e.suggestions = (e.suggestions ?? []).map(s => {
251
+ if (s.name === `${P} set --help`) return {...s, name: `${P} new --help`};
252
+ if (!s.name.startsWith(setPrefix)) return s;
253
+ const [thing, ...rest] = s.name.slice(setPrefix.length).split(' ');
254
+ if (thing.startsWith('--') || !DIALS[thing]) return s;
255
+ const keep = flags.filter(f => !f.startsWith(`--${thing} `));
256
+ return {
257
+ ...s,
258
+ name: [`${P} new ${slug}`, ...keep, `--${thing} ${rest.join(' ')}`].join(
259
+ ' ',
260
+ ),
261
+ };
262
+ });
263
+ return e;
264
+ }
265
+
121
266
  /**
122
267
  * The preview after a change, with the in-app preview route kept in step:
123
268
  * its imports follow the theme, such as the stylesheet of a font package
@@ -129,8 +274,7 @@ export async function themeEditNew(name, options = {}) {
129
274
  */
130
275
  async function previewAndRoute(ctx, slug, data, png) {
131
276
  const p = await previewAfter(ctx, slug, data, png);
132
- await keepPreviewRoute(ctx, slug);
133
- return p;
277
+ return {...p, previewStale: await keepPreviewRoute(ctx, slug)};
134
278
  }
135
279
 
136
280
  /**
@@ -139,12 +283,15 @@ async function previewAndRoute(ctx, slug, data, png) {
139
283
  * the next `preview add` writes the route again.
140
284
  * @param {import('./_settings.mjs').Ctx} ctx
141
285
  * @param {string} slug
286
+ * @returns {Promise<string[]>} preview files changed by hand, left showing
287
+ * the theme as it was
142
288
  */
143
289
  async function keepPreviewRoute(ctx, slug) {
144
290
  try {
145
- await refreshPreviewRoute(ctx.project.cwd, slug);
291
+ return (await refreshPreviewRoute(ctx.project.cwd, slug)).stale;
146
292
  } catch {
147
293
  // A damaged or moved preview.
294
+ return [];
148
295
  }
149
296
  }
150
297
 
@@ -161,6 +308,50 @@ export async function themeEditSet(theme, thing, value, options = {}) {
161
308
  return change('set', theme, thing, value, options);
162
309
  }
163
310
 
311
+ /**
312
+ * Refuse a theme whose saved exact tokens the type rules no longer take,
313
+ * naming the undo that removes the one that fails.
314
+ * @param {import('./_settings.mjs').Ctx} ctx
315
+ * @param {string} slug
316
+ * @param {import('./_settings.mjs').ThemeData} data
317
+ * @param {string} [skip]
318
+ */
319
+ function refuseStoredTokens(ctx, slug, data, skip) {
320
+ const bad = storedTokenProblem(ctx, slug, data, skip);
321
+ if (bad)
322
+ refuse(
323
+ E.ERR_THEME_INVALID,
324
+ `themes/${slug}/${slug}.settings.json: ${describe(bad.setting)} holds a value the editor no longer accepts (${bad.why}).`,
325
+ {
326
+ run: [
327
+ `${P} undo ${slug} ${undoArgs(bad.setting)}`,
328
+ `${P} set ${slug} ${bad.setting.thing} ${q(exampleOf(ctx.C.typeOf(bad.setting.thing), bad.setting.thing))}`,
329
+ ],
330
+ },
331
+ );
332
+ }
333
+
334
+ /**
335
+ * A note for type scale steps that land outside 9 to 200 pixels.
336
+ * @param {Record<string, string>} res resolved light tokens
337
+ * @returns {string[]}
338
+ */
339
+ function extremeSteps(res) {
340
+ const out = Object.entries(res)
341
+ .filter(([k]) => /^--font-size-/.test(k))
342
+ .map(([k, v]) => {
343
+ const n = Number.parseFloat(v);
344
+ return /** @type {[string, number]} */ ([k, /rem$/.test(v) ? n * 16 : n]);
345
+ })
346
+ .filter(([, px]) => Number.isFinite(px) && (px < 9 || px > 200))
347
+ .map(([k, px]) => `${k} ${Math.round(px)}px`);
348
+ return out.length
349
+ ? [
350
+ `some scale steps are outside reading sizes (9 to 200px): ${out.slice(0, 4).join(', ')}`,
351
+ ]
352
+ : [];
353
+ }
354
+
164
355
  /**
165
356
  * @param {'set' | 'undo'} sub
166
357
  * @param {string} slug
@@ -172,8 +363,9 @@ export async function themeEditSet(theme, thing, value, options = {}) {
172
363
  async function change(sub, slug, thing, value, options) {
173
364
  const {cwd = process.cwd(), png = false} = options;
174
365
  requireProject(cwd);
175
- const data = loadTheme(cwd, slug);
366
+ const data = loadTheme(cwd, slug, thing);
176
367
  const ctx = await context(cwd);
368
+ refuseStoredTokens(ctx, slug, data, thing);
177
369
  const flags = {
178
370
  on: options.on,
179
371
  when: options.when,
@@ -181,8 +373,50 @@ async function change(sub, slug, thing, value, options) {
181
373
  mode: options.mode,
182
374
  only: options.only,
183
375
  };
184
- const s = checkSetting(ctx, slug, data, thing, value, flags, sub === 'undo');
185
- const base = await baseResolved(ctx.project, data.like);
376
+ /** @type {{light: Record<string, string>, dark: Record<string, string>}} */
377
+ let base;
378
+ try {
379
+ base = await baseResolved(ctx.project, data.like);
380
+ } catch (e) {
381
+ // A base package that is gone: moving off it still works.
382
+ if (!(sub === 'set' && thing === 'base')) throw e;
383
+ base = await baseResolved(
384
+ ctx.project,
385
+ value === 'none' ? undefined : value,
386
+ );
387
+ }
388
+ /** @type {import('./_settings.mjs').Ctx} */ (ctx).base = base;
389
+ /** @type {import('./_settings.mjs').Setting} */
390
+ let s;
391
+ try {
392
+ s = checkSetting(ctx, slug, data, thing, value, flags, sub === 'undo');
393
+ } catch (e) {
394
+ // A stored setting this Core no longer knows (a renamed part or
395
+ // property, or a hand edit) can still be removed.
396
+ const stored =
397
+ sub === 'undo'
398
+ ? data.settings.find(
399
+ x =>
400
+ x.thing === thing &&
401
+ (x.on ?? null) === (flags.on ?? null) &&
402
+ (x.when ?? null) === (flags.when ?? null) &&
403
+ (x.state ?? null) === (flags.state ?? null) &&
404
+ (x.mode ?? null) === (flags.mode ?? null),
405
+ )
406
+ : null;
407
+ if (!stored) throw e;
408
+ s = stored;
409
+ }
410
+ // undo <thing> <value> removes the setting only when that is its value.
411
+ if (sub === 'undo' && value != null && value !== '') {
412
+ const held = data.settings.find(x => keyOf(x) === keyOf(s));
413
+ if (held && held.value !== value.trim())
414
+ refuse(
415
+ E.ERR_THEME_NOT_SET,
416
+ `The theme sets ${describe(held)}, not ${value}.`,
417
+ {run: [`${P} undo ${slug} ${undoArgs(held)}`]},
418
+ );
419
+ }
186
420
  const compiledBefore = compileTheme(ctx, data, base);
187
421
  if (sub === 'set' && (s.thing === 'base' || s.thing === 'mode')) {
188
422
  const before = s.thing === 'base' ? (data.like ?? 'none') : data.mode;
@@ -193,6 +427,7 @@ async function change(sub, slug, thing, value, options) {
193
427
  data.mode = /** @type {'both' | 'light-only' | 'dark-only'} */ (s.value);
194
428
  const r = await commitTheme(ctx, slug, data, {history: true});
195
429
  const p = await previewAndRoute(ctx, slug, data, png);
430
+ const after = await baseResolved(ctx.project, data.like).catch(() => base);
196
431
  return {
197
432
  type: 'themeEdit.set',
198
433
  data: {
@@ -202,12 +437,37 @@ async function change(sub, slug, thing, value, options) {
202
437
  replaced: null,
203
438
  was: before,
204
439
  parts: [],
205
- family: null,
440
+ group: null,
206
441
  changedTokens: r.changed,
207
- styled: [],
442
+ styled: styledChanges(compiledBefore, compileTheme(ctx, data, after)),
208
443
  kept: [],
209
444
  lifted: r.lifted,
210
- notes: [`your ${data.settings.length} settings are kept`],
445
+ notes: [
446
+ ...(r.unchanged
447
+ ? [`no change: ${s.thing} is already ${s.value}`]
448
+ : []),
449
+ ...r.notes,
450
+ `your ${data.settings.length} settings are kept`,
451
+ ...otherModeNotes(data),
452
+ // The colors are made again for the new base or mode: their
453
+ // shade notes follow.
454
+ ...data.settings
455
+ .filter(x => x.source === 'dial' && PALETTE_DIALS.includes(x.thing))
456
+ .flatMap(x =>
457
+ paletteNotes(
458
+ paletteMapping(
459
+ cwd,
460
+ slug,
461
+ data,
462
+ after,
463
+ ctx.project.core.tokenDefaults,
464
+ ),
465
+ x.thing,
466
+ slug,
467
+ modesOf(data),
468
+ ).slice(0, -1),
469
+ ),
470
+ ],
211
471
  problems: r.problems,
212
472
  warnings: r.warnings,
213
473
  ...p,
@@ -216,6 +476,8 @@ async function change(sub, slug, thing, value, options) {
216
476
  }
217
477
  const k = keyOf(s);
218
478
  const prevIdx = data.settings.findIndex(x => keyOf(x) === k);
479
+ /** @type {string | null} */
480
+ let vibrancyGone = null;
219
481
  const prev = prevIdx >= 0 ? data.settings[prevIdx] : null;
220
482
  if (sub === 'undo') {
221
483
  if (!prev) {
@@ -227,13 +489,63 @@ async function change(sub, slug, thing, value, options) {
227
489
  also: near.length
228
490
  ? [`settings for ${s.thing}: ${near.join('; ')}`]
229
491
  : [],
230
- run: [`${P} show ${slug}`],
492
+ run: [
493
+ ...data.settings
494
+ .filter(x => x.thing === s.thing)
495
+ .slice(0, 3)
496
+ .map(x => `${P} undo ${slug} ${undoArgs(x)}`),
497
+ `${P} show ${slug}`,
498
+ ],
231
499
  },
232
500
  );
233
501
  }
234
502
  data.settings.splice(prevIdx, 1);
235
- } else if (prev) data.settings[prevIdx] = s;
236
- else data.settings.push(s);
503
+ // Vibrancy needs a color: undoing the last one takes it along, so the
504
+ // theme never holds a state `set` refuses.
505
+ if (
506
+ PALETTE_DIALS.includes(s.thing) &&
507
+ !data.settings.some(
508
+ x => x.source === 'dial' && PALETTE_DIALS.includes(x.thing),
509
+ )
510
+ ) {
511
+ const v = data.settings.findIndex(
512
+ x => x.source === 'dial' && x.thing === 'vibrancy',
513
+ );
514
+ if (v >= 0)
515
+ vibrancyGone = /** @type {string} */ (
516
+ data.settings.splice(v, 1)[0]?.value
517
+ );
518
+ }
519
+ } else if (prev && JSON.stringify(prev) === JSON.stringify(s)) {
520
+ // The same setting again: nothing moves.
521
+ } else {
522
+ // A changed setting goes last, so it wins over what came before it.
523
+ if (prev) data.settings.splice(prevIdx, 1);
524
+ data.settings.push(s);
525
+ }
526
+ // A setting for both modes replaces the ones made for one mode, which it
527
+ // would otherwise sit under.
528
+ /** @type {import('./_settings.mjs').Setting[]} */
529
+ const covered =
530
+ sub === 'set' && !s.mode && s.source !== 'dial'
531
+ ? data.settings.filter(
532
+ x => x !== s && x.mode && keyOf({...x, mode: undefined}) === k,
533
+ )
534
+ : [];
535
+ data.settings = data.settings.filter(x => !covered.includes(x));
536
+ // A shorthand set after its longhands on the same part replaces them.
537
+ const longhands =
538
+ sub === 'set' && s.source === 'property'
539
+ ? data.settings.filter(
540
+ x =>
541
+ x !== s &&
542
+ x.source === 'property' &&
543
+ x.on === s.on &&
544
+ x.when === s.when &&
545
+ x.state === s.state &&
546
+ x.thing.startsWith(`${s.thing}-`),
547
+ )
548
+ : [];
237
549
  const r = await commitTheme(ctx, slug, data, {history: true});
238
550
  const styled = styledChanges(compiledBefore, compileTheme(ctx, data, base));
239
551
  const parts = partsOf(ctx, s);
@@ -242,8 +554,45 @@ async function change(sub, slug, thing, value, options) {
242
554
  ? data.settings.filter(x => x.thing === s.thing && x.on).map(describe)
243
555
  : [];
244
556
  /** @type {string[]} */
245
- const notes = [];
246
- const fam = s.on
557
+ const notes = [
558
+ ...(covered.length ? [`replaces ${covered.map(describe).join(', ')}`] : []),
559
+ // Phones keep the base theme's reading sizes (a coarse pointer below
560
+ // the lg width), so a size change says where it applies.
561
+ ...(sub === 'set' &&
562
+ !s.on &&
563
+ (['text-size', 'type'].includes(s.thing) ||
564
+ /^--(font-size-|text-[a-z0-9-]+-(size|leading)$)/.test(s.thing))
565
+ ? [
566
+ 'phones (touch screens below 1024px wide) keep the base theme reading sizes; this applies on wider or mouse screens',
567
+ ]
568
+ : []),
569
+ // A scale step far outside reading sizes is named.
570
+ ...(sub === 'set' && ['text-size', 'type'].includes(s.thing)
571
+ ? extremeSteps(r.res.light)
572
+ : []),
573
+ // An accepted change that the theme already showed says so.
574
+ ...(sub === 'set' &&
575
+ !r.unchanged &&
576
+ !r.changed.length &&
577
+ !styled.length &&
578
+ !ctx.unchecked
579
+ ? [
580
+ `this changes nothing you see: the theme already shows ${describe(s)} (it is saved, and stays when the base theme changes)`,
581
+ ]
582
+ : []),
583
+ ...(longhands.length
584
+ ? [
585
+ `${s.thing} comes after ${longhands.map(x => x.thing).join(', ')} on ${s.on}, so it replaces them there`,
586
+ ]
587
+ : []),
588
+ ...(r.unchanged
589
+ ? [
590
+ `no change: ${describe(s)} is already set, so nothing was built and no undo step was added`,
591
+ ]
592
+ : []),
593
+ ...r.notes,
594
+ ];
595
+ const group = s.on
247
596
  ? FAMILIES[s.on]
248
597
  ? s.on
249
598
  : parts.length > 1
@@ -257,14 +606,50 @@ async function change(sub, slug, thing, value, options) {
257
606
  paletteMapping(cwd, slug, data, base, ctx.project.core.tokenDefaults),
258
607
  s.thing,
259
608
  slug,
609
+ modesOf(data),
260
610
  ),
261
611
  );
262
612
  if (PALETTE_DIALS.includes(s.thing) && sub === 'undo')
263
613
  notes.push(
264
- `the ${s.thing} family and the tokens it fed are removed from the palette; they go back to the base theme's values`,
614
+ `the ${s.thing} color is no longer generated, and the tokens it fed go back to the base theme's values`,
615
+ ...(vibrancyGone != null
616
+ ? [
617
+ `vibrancy ${vibrancyGone} is removed too: it sets how saturated the colors are, and the theme sets no color now`,
618
+ ]
619
+ : []),
265
620
  );
621
+ if (s.thing === 'neutral' && sub === 'set') {
622
+ // Only the theme's own modes; a dark theme gets no white-page offer.
623
+ const modes = modesOf(data);
624
+ const pages = modes
625
+ .map(m => [m, base[m]['--color-background-body']])
626
+ .filter(([, v]) => v)
627
+ .map(([m, v]) => `${v} in ${m}`);
628
+ notes.push(
629
+ `the page background stays the base theme's${pages.length ? ` (${pages.join(', ')})` : ''}${
630
+ modes.includes('light')
631
+ ? `; for a white or off-white page: ${P} set ${slug} --color-background-body "#ffffff"${modes.length > 1 ? ' --mode light' : ''}`
632
+ : `; for another page color: ${P} set ${slug} --color-background-body "<color>"`
633
+ }`,
634
+ );
635
+ }
636
+ if (s.thing === 'vibrancy') {
637
+ notes.push(
638
+ sub === 'set'
639
+ ? `every color this theme sets is made again at vibrancy ${s.value} (0 is gray, 100 the most vivid, ${VIBRANCY_DEFAULT} the default)`
640
+ : `every color this theme sets is made again at the default vibrancy, ${VIBRANCY_DEFAULT}`,
641
+ );
642
+ notes.push(...unsetColorNotes(data, base, slug));
643
+ }
266
644
  if (s.thing === 'font' && sub === 'set')
267
- notes.push(...fontNotes(ctx, {...data, settings: [s]}));
645
+ notes.unshift(...fontNotes(ctx, {...data, settings: [s]}));
646
+ if (s.thing === 'type' || s.thing === 'headings')
647
+ for (const [m, why] of maskedSettings(data))
648
+ notes.push(`${describe(m)}: ${why}`);
649
+ if (s.thing === 'type' && sub === 'set' && TYPE_STYLES[s.value].ratio > 1.2)
650
+ notes.push(
651
+ 'text below the base size keeps its standard sizes, so small text stays readable',
652
+ );
268
653
  const p = await previewAndRoute(ctx, slug, data, png);
269
654
  return {
270
655
  type: sub === 'set' ? 'themeEdit.set' : 'themeEdit.undo',
@@ -275,15 +660,23 @@ async function change(sub, slug, thing, value, options) {
275
660
  sub === 'set'
276
661
  ? s
277
662
  : /** @type {import('./_settings.mjs').Setting} */ (prev),
663
+ // On undo, the setting above is the one removed, named as such.
664
+ ...(sub === 'undo' && prev
665
+ ? {removed: prev, now: nowApplies(ctx, data, prev, base)}
666
+ : {}),
278
667
  replaced: sub === 'set' ? prev : null,
279
- was: null,
668
+ // A whole-theme dial names the value it replaced, as base and mode do.
669
+ was:
670
+ sub === 'set' && prev && prev.source === 'dial' && !prev.on
671
+ ? prev.value
672
+ : null,
280
673
  notes,
281
674
  parts,
282
- family: fam
675
+ group: group
283
676
  ? {
284
- name: fam,
677
+ name: group,
285
678
  members: parts,
286
- onlyHint: !FAMILIES[s.on ?? ''] && AUTO_SPREAD.includes(fam),
679
+ onlyHint: !FAMILIES[s.on ?? ''] && AUTO_SPREAD.includes(group),
287
680
  }
288
681
  : null,
289
682
  changedTokens: r.changed,
@@ -297,6 +690,34 @@ async function change(sub, slug, thing, value, options) {
297
690
  };
298
691
  }
299
692
 
693
+ /**
694
+ * Which status colors the theme does not set, so they keep the base theme's
695
+ * values whatever the vibrancy, with the commands that bring them in: each
696
+ * seeded with the base theme's own color, so it is then generated at the
697
+ * theme's vibrancy. Colored cards and other info-tinted surfaces follow info.
698
+ * @param {import('./_settings.mjs').ThemeData} data
699
+ * @param {{light: Record<string, string>, dark: Record<string, string>}} base
700
+ * @param {string} slug
701
+ * @returns {string[]}
702
+ */
703
+ function unsetColorNotes(data, base, slug) {
704
+ const word = /** @type {Record<string, string>} */ ({
705
+ info: '--color-info',
706
+ success: '--color-success',
707
+ warning: '--color-warning',
708
+ danger: '--color-error',
709
+ });
710
+ const unset = Object.keys(word).filter(
711
+ d => !data.settings.some(x => x.source === 'dial' && x.thing === d),
712
+ );
713
+ if (!unset.length) return [];
714
+ return [
715
+ `${unset.join(', ')} ${unset.length > 1 ? 'are' : 'is'} not set by this theme, so ${unset.length > 1 ? 'they keep' : 'it keeps'} the base theme's colors at any vibrancy${unset.includes('info') ? ', and so do surfaces tinted with info, such as colored cards' : ''}. To include ${unset.length > 1 ? 'them' : 'it'}: ${unset
716
+ .map(d => `${P} set ${slug} ${d} "${base.light[word[d]] ?? '<color>'}"`)
717
+ .join('; ')}`,
718
+ ];
719
+ }
720
+
300
721
  /**
301
722
  * Every setting of a theme, key resolved values, problems it caused, the
302
723
  * sample page and the theme-building page with every component.
@@ -306,13 +727,17 @@ async function change(sub, slug, thing, value, options) {
306
727
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditShowResponse>}
307
728
  */
308
729
  export async function themeEditShow(theme, options = {}) {
309
- const {cwd = process.cwd(), png = false, group} = options;
730
+ const {cwd = process.cwd(), png = false} = options;
310
731
  requireProject(cwd);
311
- checkGroup(group);
732
+ const section = checkSection(options.section, theme);
312
733
  const data = loadTheme(cwd, theme);
313
734
  const ctx = await context(cwd);
735
+ refuseStoredTokens(ctx, theme, data);
314
736
  const f = themeFiles(cwd, theme);
315
- if (!fs.existsSync(f.js)) await buildTheme(ctx, theme, data);
737
+ // A build that does not match the settings (a command stopped mid-build,
738
+ // a hand edit, another CLI) is made again from the settings, and said.
739
+ const stale = staleBuild(cwd, theme, data);
740
+ if (stale) await buildTheme(ctx, theme, data);
316
741
  const res = await resolvedTokens(ctx, theme);
317
742
  const problems = await contrastProblems(ctx, data, res);
318
743
  const pal = paletteMapping(
@@ -323,8 +748,8 @@ export async function themeEditShow(theme, options = {}) {
323
748
  ctx.project.core.tokenDefaults,
324
749
  );
325
750
  const preview = await renderPreview(ctx, theme, data);
326
- await keepPreviewRoute(ctx, theme);
327
- const sheet = await renderSheet(ctx, theme, data, {group});
751
+ const previewStale = await keepPreviewRoute(ctx, theme);
752
+ const sheet = await renderSheet(ctx, theme, data, {group: section});
328
753
  const modes = modesOf(data);
329
754
  const shots = png
330
755
  ? await pictures(
@@ -342,69 +767,241 @@ export async function themeEditShow(theme, options = {}) {
342
767
  theme,
343
768
  like: data.like ?? null,
344
769
  mode: data.mode,
345
- settings: data.settings.map(s => ({...s, parts: partsOf(ctx, s)})),
346
- notes: fontNotes(ctx, data),
770
+ settings: data.settings.map(s => {
771
+ const masked = maskedSettings(data).get(s);
772
+ return {...s, parts: partsOf(ctx, s), ...(masked ? {masked} : {})};
773
+ }),
774
+ notes: [
775
+ ...(stale
776
+ ? [
777
+ `the build did not match ${theme}.settings.json (${stale}), so it was built again from the settings`,
778
+ ]
779
+ : []),
780
+ ...fontNotes(ctx, data),
781
+ ],
782
+ // A size, number or font is the same in both modes: one value.
347
783
  resolved: Object.fromEntries(
348
784
  KEY_TOKENS.map(k => [
349
785
  k,
350
- Object.fromEntries(modes.map(m => [m, res[m][k] ?? null])),
786
+ MODAL.has(ctx.C.typeOf(k))
787
+ ? Object.fromEntries(modes.map(m => [m, res[m][k] ?? null]))
788
+ : (res[modes[0]][k] ?? null),
351
789
  ]),
352
790
  ),
353
- palette: pal && paletteReport(pal, data, theme),
791
+ partValues: partValues(ctx, data, res, modes[0]),
792
+ ...colorsReport(pal, data),
354
793
  problems,
355
794
  preview,
795
+ previewStale,
356
796
  sheet: sheet.file,
357
797
  sheetComponents: sheet.components,
358
798
  skipped: sheet.skipped,
359
799
  pictures: shots.files,
360
800
  pictureProblem: shots.problem,
801
+ colorFiles: pal ? colorFiles(theme) : null,
361
802
  },
362
803
  };
363
804
  }
364
805
 
365
806
  /**
366
- * The palette part of `show`: its files, each family with its seed and the
367
- * stops that feed each token, the contrast behind each stop choice, and the
368
- * tokens an exact token setting overrides.
369
- * @param {import('./_palette.mjs').PaletteMapping} pal
807
+ * What applies once `removed` is gone: a whole-theme setting of the same
808
+ * thing for a part setting, a dial that still writes the token, or the
809
+ * base theme's value.
810
+ * @param {import('./_settings.mjs').Ctx} ctx
370
811
  * @param {import('./_settings.mjs').ThemeData} data
371
- * @param {string} slug
372
- * @returns {import('./theme-edit.type.mjs').ThemeEditPaletteReport}
812
+ * @param {import('./_settings.mjs').Setting} removed
813
+ * @param {{light: Record<string, string>, dark: Record<string, string>}} base
814
+ * @returns {string}
815
+ */
816
+ function nowApplies(ctx, data, removed, base) {
817
+ // A token a dial still writes (an accent color feeds --color-accent):
818
+ // name that dial.
819
+ if (removed.source === 'token' && !removed.on) {
820
+ const value = (/** @type {import('./_settings.mjs').ThemeData} */ d) =>
821
+ JSON.stringify(
822
+ compileTheme(ctx, d, base).tokens?.[removed.thing] ?? null,
823
+ );
824
+ const now = value(data);
825
+ if (now !== 'null')
826
+ for (const d of [...data.settings].reverse()) {
827
+ if (d.source !== 'dial' || d.on) continue;
828
+ const without = {...data, settings: data.settings.filter(x => x !== d)};
829
+ if (value(without) !== now)
830
+ return PALETTE_DIALS.includes(d.thing)
831
+ ? `the generated ${d.thing} color (${describe(d)})`
832
+ : describe(d);
833
+ }
834
+ }
835
+ const whole =
836
+ removed.on || removed.when || removed.state || removed.mode
837
+ ? [...data.settings]
838
+ .reverse()
839
+ .find(
840
+ x =>
841
+ x.thing === removed.thing &&
842
+ x.source === removed.source &&
843
+ !x.on &&
844
+ !x.when &&
845
+ !x.state &&
846
+ (!x.mode || x.mode === removed.mode),
847
+ )
848
+ : null;
849
+ return whole ? describe(whole) : "the base theme's value";
850
+ }
851
+
852
+ /**
853
+ * Settings saved for a mode a one-mode theme does not have: they stay saved
854
+ * and apply again when the theme has that mode.
855
+ * @param {import('./_settings.mjs').ThemeData} data
856
+ * @returns {string[]}
373
857
  */
374
- function paletteReport(pal, data, slug) {
375
- const exact = new Set(
376
- data.settings.filter(s => s.source === 'token' && !s.on).map(s => s.thing),
858
+ function otherModeNotes(data) {
859
+ const modes = modesOf(data);
860
+ const off = data.settings.filter(
861
+ s => s.mode && !modes.includes(/** @type {'light' | 'dark'} */ (s.mode)),
377
862
  );
378
- const f = paletteFiles(slug);
863
+ if (!off.length) return [];
864
+ return [
865
+ `not applied in a ${data.mode} theme, kept for when it has that mode again: ${off
866
+ .slice(0, 4)
867
+ .map(describe)
868
+ .join(', ')}${off.length > 4 ? `, and ${off.length - 4} more` : ''}`,
869
+ ];
870
+ }
871
+
872
+ /**
873
+ * Each corners or spacing dial set on a part or group, with what its parts
874
+ * get, beside the whole-theme value: `corners large on containers ->
875
+ * border-radius 12px on card, dialog, ... (whole theme: --radius-container
876
+ * 10px)`.
877
+ * @param {import('./_settings.mjs').Ctx} ctx
878
+ * @param {import('./_settings.mjs').ThemeData} data
879
+ * @param {{light: Record<string, string>, dark: Record<string, string>}} res
880
+ * @param {'light' | 'dark'} mode
881
+ * @returns {string[]}
882
+ */
883
+ function partValues(ctx, data, res, mode) {
884
+ return data.settings
885
+ .filter(
886
+ s =>
887
+ s.source === 'dial' && s.on && ['corners', 'spacing'].includes(s.thing),
888
+ )
889
+ .map(s => {
890
+ const parts = partsOf(ctx, s);
891
+ const listed = `${parts.slice(0, 4).join(', ')}${parts.length > 4 ? `, and ${parts.length - 4} more` : ''}`;
892
+ if (s.thing === 'corners') {
893
+ const px = cornerPx(s.value);
894
+ // The radius token each part's resting corners read, as the whole-
895
+ // theme value they would have without this setting.
896
+ // The token each part's resting corners read. A part the census saw
897
+ // closed (a menu, a popover) has none recorded: a container or menu
898
+ // reads the container radius, like every Core surface; any other
899
+ // part's is unknown.
900
+ /** @type {Map<string, string[]>} */
901
+ const byToken = new Map();
902
+ for (const t of parts) {
903
+ const token =
904
+ /var\((--[\w-]+)\)/.exec(
905
+ partDefault(ctx, t, 'borderRadius', undefined) ?? '',
906
+ )?.[1] ??
907
+ // Every variant reads it (none is the resting one).
908
+ ctx.C.partReads(t, 'corners').find(x =>
909
+ x.props.includes('border-radius'),
910
+ )?.token ??
911
+ (['containers', 'menus'].includes(familyOf(t) ?? '')
912
+ ? '--radius-container'
913
+ : 'unknown');
914
+ byToken.set(token, [...(byToken.get(token) ?? []), t]);
915
+ }
916
+ const whole = [...byToken]
917
+ .map(
918
+ ([token, ts]) =>
919
+ `${token === 'unknown' ? 'unknown' : `${token} ${res[mode][token] ?? 'unset'}`}${byToken.size > 1 ? ` for ${ts.join(', ')}` : ''}`,
920
+ )
921
+ .join('; ');
922
+ return `${describe(s)} -> border-radius ${px >= 9999 ? 'fully round' : `${px}px`} on ${listed} (whole theme: ${whole})`;
923
+ }
924
+ const f = SPACING.find(([n]) => n === s.value)?.[1] ?? 1;
925
+ return `${describe(s)} -> spacing x${f} inside ${listed} (whole theme: --spacing-4 ${res[mode]['--spacing-4'] ?? 'unset'})`;
926
+ });
927
+ }
928
+
929
+ /**
930
+ * The colors part of `show`: the vibrancy, each color with its seed and the
931
+ * shade each token uses in light and dark (an exact token setting wins and
932
+ * says so), and the contrast moves behind the shade choices.
933
+ * @param {import('./_palette.mjs').PaletteMapping | null} pal
934
+ * @param {import('./_settings.mjs').ThemeData} data
935
+ * @returns {{vibrancy: number | null, colors: import('./theme-edit.type.mjs').ThemeEditColor[], colorNotes: string[]}}
936
+ */
937
+ function colorsReport(pal, data) {
938
+ if (!pal) return {vibrancy: null, colors: [], colorNotes: []};
939
+ /** What the user set for each token exactly, in each mode. */
940
+ const exactBy =
941
+ /** @type {Record<string, {light?: string, dark?: string}>} */ ({});
942
+ for (const s of data.settings)
943
+ if (s.source === 'token' && !s.on && !s.when && !s.state)
944
+ for (const m of s.mode ? [s.mode] : ['light', 'dark'])
945
+ (exactBy[s.thing] ??= {})[/** @type {'light' | 'dark'} */ (m)] =
946
+ s.value;
947
+ /** @param {import('./_palette.mjs').StopRef} r */
948
+ const shade = r =>
949
+ r.family === 'black' || r.family === 'white'
950
+ ? `${r.family} ${r.color}`
951
+ : `${r.family ? `${r.family} ` : ''}${r.stop}${r.alpha ? ` at opacity ${r.alpha}` : ''} ${r.color}${r.exact ? ' (your exact color)' : ''}`;
952
+ // A theme with one mode lists only that mode's shades.
953
+ const modes = modesOf(data);
954
+ /** @param {{light: import('./_palette.mjs').StopRef, dark: import('./_palette.mjs').StopRef}} v */
955
+ const shades = v => modes.map(m => `${m} ${shade(v[m])}`).join(', ');
379
956
  return {
380
- config: f.config,
381
- file: f.palette,
382
- receipt: f.receipt,
383
- families: pal.families.map(fam => ({
384
- family: fam.id,
957
+ vibrancy: pal.vibrancy,
958
+ colors: pal.families.map(fam => ({
959
+ color: fam.id,
385
960
  seed: fam.seed,
386
- value: fam.value,
387
- exactToken: paletteToken(fam.id),
388
961
  tokens: Object.fromEntries(
389
962
  Object.entries(pal.tokens)
390
963
  .filter(([, v]) => v.family === fam.id)
391
964
  .map(([k, v]) => [
392
965
  k,
393
- {
394
- light: `stop ${v.light.stop}${v.light.alpha ? ` at opacity ${v.light.alpha}` : ''} ${v.light.color}`,
395
- dark: `stop ${v.dark.stop}${v.dark.alpha ? ` at opacity ${v.dark.alpha}` : ''} ${v.dark.color}`,
396
- },
966
+ // Each mode says what it shows: the exact setting where one is
967
+ // made for it, else the generated shade.
968
+ exactBy[k]
969
+ ? modes
970
+ .map(m =>
971
+ exactBy[k][m] != null
972
+ ? `${m} ${exactBy[k][m]} (your exact setting wins over the generated ${shade(v[m])})`
973
+ : `${m} ${shade(v[m])}`,
974
+ )
975
+ .join(', ')
976
+ : shades(v),
397
977
  ]),
398
978
  ),
399
979
  })),
400
- contrast: pal.contrast.map(
401
- c =>
402
- `${c.token} ${c.mode}: stop ${c.stop}${c.stop !== c.preferred ? ` (from ${c.preferred})` : ''} is ${c.ratio}:1 on ${c.against}, needs ${c.needs}:1: ${c.pass ? 'pass' : 'FAIL'}`,
403
- ),
404
- overridden: Object.keys(pal.tokens).filter(k => exact.has(k)),
980
+ colorNotes: [
981
+ ...pal.notes,
982
+ ...pal.contrast
983
+ .filter(c => modes.includes(c.mode))
984
+ .filter(c => c.note || !c.pass || c.stop !== c.preferred)
985
+ .map(c =>
986
+ c.note
987
+ ? c.note
988
+ : c.pass
989
+ ? `${c.token} ${c.mode}: shade ${c.stop}, not ${c.preferred}, so it reads at ${c.ratio}:1 on ${c.against}`
990
+ : `${c.token} ${c.mode}: only ${c.ratio}:1 on ${c.against} at shade ${c.stop} (needs ${c.needs}:1)`,
991
+ ),
992
+ ],
405
993
  };
406
994
  }
407
995
 
996
+ /**
997
+ * The generated color files of a theme, for the end of `show`.
998
+ * @param {string} slug
999
+ */
1000
+ function colorFiles(slug) {
1001
+ const f = paletteFiles(slug);
1002
+ return {config: f.config, module: f.palette, receipt: f.receipt};
1003
+ }
1004
+
408
1005
  /**
409
1006
  * Put the theme back as it was before its last change. With `thing`, remove
410
1007
  * that one setting instead, wherever it is in the settings: it goes back to
@@ -416,9 +1013,49 @@ function paletteReport(pal, data, slug) {
416
1013
  */
417
1014
  export async function themeEditUndo(theme, options = {}) {
418
1015
  const {cwd = process.cwd(), png = false, thing} = options;
1016
+ // base and mode are not settings in the list: undoing one sets it back to
1017
+ // its default.
1018
+ if (thing === 'base' || thing === 'mode')
1019
+ return change(
1020
+ 'set',
1021
+ theme,
1022
+ thing,
1023
+ thing === 'base' ? 'none' : 'both',
1024
+ options,
1025
+ );
419
1026
  if (thing != null)
420
1027
  return change('undo', theme, thing, options.value, options);
421
1028
  requireProject(cwd);
1029
+ // A scope flag without a thing would undo some other change.
1030
+ const scoped = /** @type {const} */ (['on', 'when', 'state', 'mode']).find(
1031
+ k => options[k] != null,
1032
+ );
1033
+ if (scoped || options.only)
1034
+ refuse(
1035
+ E.ERR_MISSING_ARGUMENT,
1036
+ `--${scoped ?? 'only'} names where one setting applies; name the setting too, or drop it to step back one change.`,
1037
+ {
1038
+ run: [
1039
+ // The saved settings in that scope, as commands that remove them.
1040
+ ...(() => {
1041
+ try {
1042
+ return loadTheme(cwd, theme)
1043
+ .settings.filter(x =>
1044
+ scoped
1045
+ ? String(/** @type {any} */ (x)[scoped] ?? '') ===
1046
+ String(options[scoped])
1047
+ : x.only,
1048
+ )
1049
+ .slice(0, 3)
1050
+ .map(x => `${P} undo ${theme} ${undoArgs(x)}`);
1051
+ } catch {
1052
+ return [];
1053
+ }
1054
+ })(),
1055
+ `${P} undo ${theme}`,
1056
+ ],
1057
+ },
1058
+ );
422
1059
  // A damaged settings file is what undo recovers from: the last history
423
1060
  // entry replaces it without the current file being read.
424
1061
  /** @type {import('./_settings.mjs').ThemeData | null} */
@@ -429,9 +1066,16 @@ export async function themeEditUndo(theme, options = {}) {
429
1066
  if (!(e instanceof AstryxError && e.code === E.ERR_THEME_INVALID)) throw e;
430
1067
  }
431
1068
  const f = themeFiles(cwd, theme);
432
- const history = fs.existsSync(f.history)
433
- ? JSON.parse(fs.readFileSync(f.history, 'utf8'))
434
- : [];
1069
+ const {steps: history, dropped} = readHistory(f.history);
1070
+ if (!history.length && dropped)
1071
+ refuse(
1072
+ E.ERR_THEME_INVALID,
1073
+ `${theme}.history.json is damaged, so there is no step to go back to.`,
1074
+ {
1075
+ fix: `delete ${shown(cwd, f.history)}: the next change starts a new history, and your settings stay as they are`,
1076
+ run: [`${P} show ${theme}`],
1077
+ },
1078
+ );
435
1079
  if (!history.length)
436
1080
  refuse(
437
1081
  E.ERR_THEME_NOTHING_TO_UNDO,
@@ -439,18 +1083,44 @@ export async function themeEditUndo(theme, options = {}) {
439
1083
  {run: [`${P} show ${theme}`]},
440
1084
  );
441
1085
  const ctx = await context(cwd);
442
- const prevText = history.pop();
443
- const prev = /** @type {import('./_settings.mjs').ThemeData} */ (
444
- JSON.parse(prevText)
1086
+ const prevText = /** @type {string} */ (history.pop());
1087
+ let prev = /** @type {import('./_settings.mjs').ThemeData} */ (
1088
+ JSON.parse(prevText.replace(/^\uFEFF/, ''))
445
1089
  );
446
- await commitTheme(ctx, theme, prev, {history: false});
447
- fs.writeFileSync(f.history, JSON.stringify(history));
1090
+ // A step always restores into this theme, whatever name it holds.
1091
+ prev.name = theme;
1092
+ // The step it goes back to is checked like the settings file itself. A
1093
+ // value the editor no longer accepts is left out of that step (with a
1094
+ // note); a step whose shape is broken is refused.
1095
+ /** @type {import('./_settings.mjs').Setting[]} */
1096
+ let leftOut = [];
1097
+ if (settingsProblem(prev)) {
1098
+ const repaired = withoutBadValues(prev);
1099
+ const still = settingsProblem(repaired.data);
1100
+ if (still)
1101
+ refuse(
1102
+ E.ERR_THEME_INVALID,
1103
+ `The settings before the last change, in ${theme}.history.json, are damaged: ${still}.`,
1104
+ {
1105
+ fix: `delete ${shown(cwd, f.history)}: the next change starts a new history, and your settings stay as they are`,
1106
+ run: [`${P} show ${theme}`],
1107
+ },
1108
+ );
1109
+ prev = repaired.data;
1110
+ leftOut = repaired.dropped;
1111
+ }
1112
+ // The popped history is written with the change, inside its rollback.
1113
+ await commitTheme(ctx, theme, prev, {history: false, historyAfter: history});
448
1114
  /** @type {string[]} */
449
1115
  const undone = current
450
1116
  ? []
451
1117
  : [
452
1118
  `the damaged ${theme}.settings.json is replaced by the settings before the last change`,
453
1119
  ];
1120
+ for (const x of leftOut)
1121
+ undone.push(
1122
+ `left out ${describe(x)} from the step it went back to: a value the editor no longer accepts`,
1123
+ );
454
1124
  const now = new Map(prev.settings.map(s => [keyOf(s), s]));
455
1125
  const was = new Map((current?.settings ?? []).map(s => [keyOf(s), s]));
456
1126
  for (const [k, s] of was) {