@astryxdesign/cli 0.7.14-canary.gfdb9213 → 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 (95) hide show
  1. package/CHANGELOG.md +197 -0
  2. package/api/theme/_adapter.d.mts +33 -0
  3. package/api/theme/_adapter.mjs +352 -16
  4. package/api/theme/build/build.mjs +261 -10
  5. package/api/theme/eject/eject.mjs +13 -1
  6. package/api/theme/list/list.mjs +11 -2
  7. package/api/theme/template/template.mjs +139 -6
  8. package/api/theme/theme.type.d.mts +15 -1
  9. package/api/theme/theme.type.mjs +9 -3
  10. package/api/theme/themeAdd.doc.mjs +1 -1
  11. package/api/theme/themeBuild.doc.mjs +10 -2
  12. package/api/theme/themeEject.doc.mjs +2 -2
  13. package/api/theme/themeListAvailable.doc.mjs +1 -1
  14. package/api/theme/themeRemove.doc.mjs +1 -1
  15. package/api/theme/themeTemplate.doc.mjs +8 -0
  16. package/api/theme/themeUse.doc.mjs +1 -1
  17. package/api/theme-edit/_adapter.d.mts +10 -2
  18. package/api/theme-edit/_adapter.mjs +52 -31
  19. package/api/theme-edit/_check.d.mts +28 -25
  20. package/api/theme-edit/_check.mjs +586 -548
  21. package/api/theme-edit/_color.d.mts +28 -2
  22. package/api/theme-edit/_color.mjs +306 -68
  23. package/api/theme-edit/_compiler.d.mts +8 -4
  24. package/api/theme-edit/_compiler.mjs +30 -27
  25. package/api/theme-edit/_context.d.mts +10 -4
  26. package/api/theme-edit/_context.mjs +21 -4
  27. package/api/theme-edit/_edit.mjs +300 -43
  28. package/api/theme-edit/_how-commands.d.mts +91 -0
  29. package/api/theme-edit/_how-commands.mjs +269 -0
  30. package/api/theme-edit/_how-question.d.mts +57 -0
  31. package/api/theme-edit/_how-question.mjs +2574 -0
  32. package/api/theme-edit/_how.d.mts +25 -17
  33. package/api/theme-edit/_how.mjs +727 -305
  34. package/api/theme-edit/_palette.d.mts +127 -19
  35. package/api/theme-edit/_palette.mjs +1313 -399
  36. package/api/theme-edit/_parts.mjs +36 -3
  37. package/api/theme-edit/_png.d.mts +18 -6
  38. package/api/theme-edit/_png.mjs +135 -25
  39. package/api/theme-edit/_preview-app.d.mts +26 -7
  40. package/api/theme-edit/_preview-app.mjs +1611 -280
  41. package/api/theme-edit/_preview.d.mts +4 -2
  42. package/api/theme-edit/_preview.mjs +18 -7
  43. package/api/theme-edit/_settings.d.mts +56 -5
  44. package/api/theme-edit/_settings.mjs +197 -49
  45. package/api/theme-edit/_tables.d.mts +0 -12
  46. package/api/theme-edit/_tables.mjs +24 -97
  47. package/api/theme-edit/theme-edit.type.d.mts +22 -5
  48. package/api/theme-edit/theme-edit.type.mjs +17 -6
  49. package/api/theme-edit/themeEditHow.doc.mjs +13 -3
  50. package/api/theme-edit/themeEditNew.doc.mjs +2 -1
  51. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +16 -4
  52. package/api/theme-edit/themeEditPreviewApp.doc.mjs +12 -4
  53. package/api/theme-edit/themeEditPreviewList.doc.mjs +9 -1
  54. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +27 -2
  55. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  56. package/assets/docs.generated.json +1 -0
  57. package/assets/preview-app/gitignore +3 -0
  58. package/assets/templates/components.generated.json +1 -0
  59. package/clients/cli/bin/astryx.mjs +37 -5
  60. package/clients/cli/commands/experimental/theme.mjs +231 -31
  61. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +14 -5
  62. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +0 -1
  63. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  64. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +3 -2
  65. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +2 -2
  66. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +2 -2
  67. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  68. package/clients/cli/commands/experimental-theme-targets.doc.mjs +1 -1
  69. package/clients/cli/commands/experimental-theme.doc.mjs +2 -2
  70. package/clients/cli/commands/theme-build.doc.mjs +1 -1
  71. package/clients/cli/commands/theme-eject.doc.mjs +3 -3
  72. package/clients/cli/commands/theme-remove.doc.mjs +2 -2
  73. package/clients/cli/commands/theme-template.doc.mjs +11 -4
  74. package/clients/cli/commands/theme.mjs +104 -40
  75. package/clients/cli/commands.generated.json +1 -0
  76. package/clients/cli/index.mjs +96 -4
  77. package/clients/cli/lib/json-shim.mjs +29 -1
  78. package/foundation/config/project.d.mts +16 -2
  79. package/foundation/config/project.mjs +40 -6
  80. package/foundation/config/theme-state.d.mts +9 -0
  81. package/foundation/config/theme-state.mjs +20 -1
  82. package/foundation/discovery/template-adapter.d.mts +12 -1
  83. package/foundation/discovery/template-adapter.mjs +24 -1
  84. package/foundation/discovery/template-needs.d.mts +7 -0
  85. package/foundation/discovery/template-needs.mjs +117 -8
  86. package/foundation/discovery/template-source-tree.d.mts +5 -1
  87. package/foundation/discovery/template-source-tree.mjs +6 -4
  88. package/foundation/discovery/theme-discovery.d.mts +14 -3
  89. package/foundation/discovery/theme-discovery.mjs +45 -12
  90. package/foundation/doc-compiler/import.mjs +68 -3
  91. package/foundation/doc-compiler/stored-docs.d.mts +27 -0
  92. package/foundation/doc-compiler/stored-docs.mjs +65 -0
  93. package/foundation/fs/fs-error.d.mts +17 -0
  94. package/foundation/fs/fs-error.mjs +34 -0
  95. package/package.json +6 -6
@@ -0,0 +1,2574 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file A plain-words question for `how`, read clause by clause: the parts
5
+ * it names (with a variant, size, state or mode), what to change about
6
+ * them, the values typed in it, and whether it asks for more, less or none.
7
+ * Each clause becomes the commands that do exactly that; `how` then keeps
8
+ * only the commands `set` accepts and that change the theme.
9
+ * @position api/theme-edit — imported only by _how.mjs
10
+ */
11
+
12
+ import {hex, parseColor} from './_color.mjs';
13
+ import {
14
+ DESIGN,
15
+ DIALS,
16
+ HEADING_WEIGHTS,
17
+ P,
18
+ FAMILIES,
19
+ FONTS,
20
+ HOW,
21
+ OPEN_FONTS,
22
+ COMMON_STATES,
23
+ } from './_tables.mjs';
24
+ import {PALETTE_DIALS, isGraySeed, seedOf} from './_palette.mjs';
25
+ import {COLOR_PROPS} from './_tables.mjs';
26
+
27
+ /** @typedef {import('./_how-commands.mjs').Step} Step */
28
+
29
+ /**
30
+ * One answer: what it does, and the ways to do it. Each option is a list of
31
+ * steps run in order; most options are one step.
32
+ * @typedef {{text: string, options: Step[][], sequence?: boolean, lookup?: string}} Draft
33
+ */
34
+
35
+ /**
36
+ * Words of other languages the docs ship, and the English word each means.
37
+ * Matched as whole words, or anywhere for scripts without spaces.
38
+ * @type {Array<[RegExp, string]>}
39
+ */
40
+ const TRANSLATE = /** @type {Array<[RegExp, string]>} */ (
41
+ [
42
+ [
43
+ 'botones?|boutons?|knöpfe|knopf|кнопк[аиу]|botões|botão|botao|pulsanti|bottoni',
44
+ '按钮|ボタン|버튼',
45
+ 'buttons',
46
+ ],
47
+ ['tarjetas?|cartes|karten?|карточк[аи]', '卡片|カード', 'cards'],
48
+ [
49
+ 'redondead[oa]s?|arrondi[es]*|abgerundet\\p{L}*|скругл\\p{L}*|arredondad\\p{L}*|arrotondat\\p{L}*',
50
+ '圆|丸く|丸い|둥글게|둥근',
51
+ 'rounded',
52
+ ],
53
+ ['esquinas?|coins|ecken|углы', '角', 'corners'],
54
+ ['sombras?|ombres?|schatten|тен[ьи]', '阴影|影', 'shadow'],
55
+ ['entfernen|quitar|enlever|supprimer|убрать', '去掉|删除|消して', 'remove'],
56
+ ['más|mais|mehr|più|более', '更', 'more'],
57
+ // "sans" is a typeface word before serif or font.
58
+ [
59
+ 'sin|sans(?![\\s-]*(serif|fonts?|typefaces?))|ohne|без|sem|senza',
60
+ '没有|无',
61
+ 'without',
62
+ ],
63
+ [
64
+ 'bordes?|bordures?|rand|rahmen|границ\\p{L}*|bordas?|bordi',
65
+ '边框|枠線',
66
+ 'border',
67
+ ],
68
+ ['azul(es)?|bleus?|blaue?n?|син\\p{L}*|blu', '蓝色?|青い|青く|青', 'blue'],
69
+ ['rojos?|rouges?|rote?n?|красн\\p{L}*', '红色?|赤い', 'red'],
70
+ ['verdes?|verts?|grüne?n?|зелён\\p{L}*', '绿色?|緑', 'green'],
71
+ ].map(([words, cjk, en]) => [
72
+ new RegExp(`(?<!\\p{L})(?:${words})(?!\\p{L})|${cjk}`, 'gu'),
73
+ ` ${en} `,
74
+ ])
75
+ );
76
+
77
+ /** Words a near miss is corrected to (one or two letters off). */
78
+ const VOCAB = [
79
+ 'button',
80
+ 'buttons',
81
+ 'card',
82
+ 'cards',
83
+ 'shadow',
84
+ 'shadows',
85
+ 'border',
86
+ 'borders',
87
+ 'background',
88
+ 'rounded',
89
+ 'rounder',
90
+ 'corners',
91
+ 'radius',
92
+ 'padding',
93
+ 'spacing',
94
+ 'header',
95
+ 'banner',
96
+ 'input',
97
+ 'inputs',
98
+ 'dialog',
99
+ 'dialogs',
100
+ 'tooltip',
101
+ 'heading',
102
+ 'headings',
103
+ 'checkbox',
104
+ 'switch',
105
+ 'toggle',
106
+ 'table',
107
+ 'badge',
108
+ 'badges',
109
+ 'avatar',
110
+ 'avatars',
111
+ 'sidebar',
112
+ 'gradient',
113
+ 'color',
114
+ 'colour',
115
+ 'bigger',
116
+ 'smaller',
117
+ 'darker',
118
+ 'lighter',
119
+ 'thicker',
120
+ 'italic',
121
+ 'uppercase',
122
+ 'compact',
123
+ 'accent',
124
+ 'remove',
125
+ 'shadows',
126
+ 'rounded',
127
+ 'headers',
128
+ 'tables',
129
+ 'progress',
130
+ 'outline',
131
+ ];
132
+
133
+ /** Short forms people type, and the word each means. */
134
+ const SHORT = /** @type {Record<string, string>} */ ({
135
+ btn: 'button',
136
+ btns: 'buttons',
137
+ bttn: 'button',
138
+ bttns: 'buttons',
139
+ brdr: 'border',
140
+ bdr: 'border',
141
+ hdr: 'header',
142
+ rad: 'radius',
143
+ dlg: 'dialog',
144
+ txt: 'text',
145
+ clr: 'color',
146
+ shdw: 'shadow',
147
+ });
148
+
149
+ /** Plain words that are never corrected, though one letter off a VOCAB word. */
150
+ const KEEP = new Set([
151
+ 'remote',
152
+ 'reverse',
153
+ 'access',
154
+ 'accept',
155
+ 'tablet',
156
+ 'outlined',
157
+ 'shadowed',
158
+ 'process',
159
+ 'agent',
160
+ 'tighter',
161
+ 'tight',
162
+ 'lighter',
163
+ 'brighter',
164
+ 'wider',
165
+ 'danger',
166
+ 'orange',
167
+ 'ranger',
168
+ 'rows',
169
+ 'darker',
170
+ 'thinner',
171
+ 'rounds',
172
+ 'should',
173
+ 'button',
174
+ 'buttons',
175
+ 'color',
176
+ 'colors',
177
+ 'italics',
178
+ 'border',
179
+ 'fonts',
180
+ 'title',
181
+ 'titles',
182
+ 'shade',
183
+ 'shades',
184
+ 'faded',
185
+ 'muted',
186
+ 'filled',
187
+ 'spaced',
188
+ 'wider',
189
+ 'bolder',
190
+ 'cord',
191
+ 'board',
192
+ 'order',
193
+ 'boarder',
194
+ 'hover',
195
+ 'heavier',
196
+ 'later',
197
+ 'darken',
198
+ 'ladder',
199
+ 'header',
200
+ 'leader',
201
+ 'bigger',
202
+ 'cars',
203
+ 'care',
204
+ 'hard',
205
+ 'carts',
206
+ 'bottom',
207
+ 'botton',
208
+ 'inside',
209
+ 'tables',
210
+ 'colors',
211
+ 'colours',
212
+ 'sitch',
213
+ 'witch',
214
+ 'border',
215
+ 'sharper',
216
+ 'shadows',
217
+ 'smaller',
218
+ 'taller',
219
+ ]);
220
+
221
+ /**
222
+ * Edit distance where two swapped letters count as one edit, capped at 3.
223
+ * @param {string} a @param {string} b
224
+ */
225
+ function distance(a, b) {
226
+ if (Math.abs(a.length - b.length) > 2) return 3;
227
+ /** @type {number[][]} */
228
+ const d = Array.from({length: a.length + 1}, (_, i) =>
229
+ Array.from({length: b.length + 1}, (_, j) =>
230
+ i === 0 ? j : j === 0 ? i : 0,
231
+ ),
232
+ );
233
+ for (let i = 1; i <= a.length; i++)
234
+ for (let j = 1; j <= b.length; j++) {
235
+ d[i][j] = Math.min(
236
+ d[i - 1][j] + 1,
237
+ d[i][j - 1] + 1,
238
+ d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1),
239
+ );
240
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1])
241
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
242
+ }
243
+ return Math.min(3, d[a.length][b.length]);
244
+ }
245
+
246
+ /** @param {string} w */
247
+ function corrected(w) {
248
+ if (SHORT[w]) return SHORT[w];
249
+ if (w.length < 5 || KEEP.has(w) || VOCAB.includes(w) || !/^[a-z]+$/.test(w))
250
+ return w;
251
+ const limit = w.length >= 8 ? 2 : 1;
252
+ let best = w;
253
+ let bestD = limit + 1;
254
+ for (const v of VOCAB) {
255
+ const d = distance(w, v);
256
+ if (d < bestD) [best, bestD] = [v, d];
257
+ }
258
+ return bestD <= limit ? best : w;
259
+ }
260
+
261
+ /** Hues people name, as fills a part can take. */
262
+ const HUES = /** @type {Record<string, string>} */ ({
263
+ red: '#dc2626',
264
+ orange: '#f97316',
265
+ amber: '#f59e0b',
266
+ yellow: '#eab308',
267
+ lime: '#65a30d',
268
+ green: '#16a34a',
269
+ mint: '#34d399',
270
+ minty: '#34d399',
271
+ teal: '#0d9488',
272
+ cyan: '#0891b2',
273
+ blue: '#2563eb',
274
+ navy: '#1e3a8a',
275
+ indigo: '#4f46e5',
276
+ purple: '#7c3aed',
277
+ violet: '#7c3aed',
278
+ pink: '#db2777',
279
+ magenta: '#c026d3',
280
+ brown: '#92400e',
281
+ gray: '#9ca3af',
282
+ grey: '#9ca3af',
283
+ black: '#000000',
284
+ white: '#ffffff',
285
+ cream: '#fef3c7',
286
+ beige: '#f5f5dc',
287
+ });
288
+ /** A hue with light, pale or dark before it. */
289
+ const SHADED = /** @type {Record<string, Record<string, string>>} */ ({
290
+ light: {
291
+ gray: '#e5e7eb',
292
+ grey: '#e5e7eb',
293
+ blue: '#dbeafe',
294
+ green: '#dcfce7',
295
+ red: '#fee2e2',
296
+ yellow: '#fef9c3',
297
+ purple: '#ede9fe',
298
+ pink: '#fce7f3',
299
+ orange: '#ffedd5',
300
+ },
301
+ pale: {gray: '#f3f4f6', grey: '#f3f4f6', blue: '#eff6ff', green: '#f0fdf4'},
302
+ dark: {
303
+ gray: '#374151',
304
+ grey: '#374151',
305
+ blue: '#1e40af',
306
+ green: '#166534',
307
+ red: '#991b1b',
308
+ purple: '#5b21b6',
309
+ },
310
+ });
311
+
312
+ /** The color tokens a word for a color the theme uses names. */
313
+ const THEME_COLOR_WORDS = /** @type {Array<[RegExp, string, string]>} */ ([
314
+ [
315
+ /\b(accent|brand|primary) colou?r(ed)?\b|\bin (the )?accent\b|\baccent\b/,
316
+ 'var(--color-accent)',
317
+ 'var(--color-text-accent)',
318
+ ],
319
+ ]);
320
+
321
+ /**
322
+ * The colors written in a clause, in order: hex, color functions, CSS color
323
+ * names and hues (with light, pale or dark), skipping any after "not".
324
+ * @param {string} c a clause, lower-case
325
+ * @returns {string[]}
326
+ */
327
+ function colorsIn(c) {
328
+ /** @type {Array<[number, string, boolean?]>} */
329
+ const found = [];
330
+ const re =
331
+ /#[0-9a-f]{3,8}\b|\b(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\([^)]*\)|\b(?:(light|pale|dark)\s+)?([a-z]+)\b/g;
332
+ for (const m of c.matchAll(re)) {
333
+ const before = c.slice(Math.max(0, (m.index ?? 0) - 5), m.index);
334
+ if (/\bnot\s*$|\bno\s*$/.test(before)) continue;
335
+ const whole = m[0];
336
+ if (whole.startsWith('#') || whole.includes('(')) {
337
+ // A typed hex color keeps the case it is written in, as set stores it.
338
+ if (parseColor(whole)) found.push([m.index ?? 0, whole, true]);
339
+ continue;
340
+ }
341
+ const [shade, word] = [m[1], m[2]];
342
+ if (shade && SHADED[shade]?.[word]) {
343
+ found.push([m.index ?? 0, SHADED[shade][word]]);
344
+ continue;
345
+ }
346
+ if (HUES[word])
347
+ found.push([(m.index ?? 0) + (shade ? shade.length + 1 : 0), HUES[word]]);
348
+ else if (word.length > 3 && !NOT_COLORS.has(word) && parseColor(word))
349
+ found.push([
350
+ m.index ?? 0,
351
+ hex(/** @type {number[]} */ (parseColor(word))),
352
+ ]);
353
+ }
354
+ // "success green should be more minty": the color after "be" or "to"
355
+ // is the one asked for.
356
+ // A color written out (hex, rgb()...) beats a color word: "brand blue,
357
+ // #0057ff" is #0057ff.
358
+ const turn = /\b(to|be|into|become|instead)\b/.exec(c);
359
+ const at = turn ? (turn.index ?? 0) : -1;
360
+ return found
361
+ .sort((a, b) => a[0] - b[0])
362
+ .sort((a, b) => Number(b[0] > at) - Number(a[0] > at))
363
+ .sort((a, b) => Number(Boolean(b[2])) - Number(Boolean(a[2])))
364
+ .map(([, v]) => v);
365
+ }
366
+
367
+ /**
368
+ * A hex color written with the wrong number of digits ("#12345").
369
+ * @param {string} c
370
+ */
371
+ const badHex = c =>
372
+ [...c.matchAll(/(?<![\w&])#([0-9a-f]+)\b/g)]
373
+ .map(m => m[0])
374
+ .find(h => ![3, 4, 6, 8].includes(h.length - 1)) ?? null;
375
+
376
+ /**
377
+ * A fill a clause names with dark or light alone ("make the header dark").
378
+ * @param {string} c
379
+ */
380
+ function toneIn(c) {
381
+ const t = c.replace(
382
+ /\b(dark|light)[- ](mode|theme)s?\b|\bin (dark|light)\b/g,
383
+ ' ',
384
+ );
385
+ if (/\bdark\b(?!er)/.test(t)) return '#1f2937';
386
+ if (/\blight\b(?!er)/.test(t)) return '#f3f4f6';
387
+ return null;
388
+ }
389
+ /** CSS color names that are also plain words in a question. */
390
+ const NOT_COLORS = new Set([
391
+ 'chocolate',
392
+ 'linen',
393
+ 'snow',
394
+ 'tan',
395
+ 'peru',
396
+ 'plum',
397
+ 'gold',
398
+ 'silver',
399
+ 'salmon',
400
+ 'tomato',
401
+ 'thistle',
402
+ 'orchid',
403
+ 'wheat',
404
+ 'bisque',
405
+ 'moccasin',
406
+ 'transparent',
407
+ 'currentcolor',
408
+ 'inherit',
409
+ 'initial',
410
+ ]);
411
+
412
+ /** Lengths written in a clause, in order. @param {string} c */
413
+ const lengthsIn = c =>
414
+ [...c.matchAll(/(?<![\w#.])-?(\d*\.?\d+)(px|rem|em)\b/g)].map(m => m[0]);
415
+
416
+ /** Two to four lengths in a row, as one value ("12px 20px"). @param {string} c */
417
+ const boxIn = c =>
418
+ /(?<![\w#.])(-?\d*\.?\d+(?:px|rem|em)(?:\s+-?\d*\.?\d+(?:px|rem|em)){1,3})\b/.exec(
419
+ c,
420
+ )?.[1] ?? null;
421
+
422
+ /**
423
+ * A box-shadow value written out: offsets, then a blur, spread and color,
424
+ * several separated by commas.
425
+ * @param {string} c
426
+ */
427
+ function shadowIn(c) {
428
+ const one =
429
+ '(?:inset\\s+)?-?\\d*\\.?\\d+(?:px)?\\s+-?\\d*\\.?\\d+(?:px)?(?:\\s+-?\\d*\\.?\\d+(?:px)?){0,2}\\s+(?:#[0-9a-f]{3,8}|(?:rgba?|hsla?|oklch)\\([^)]*\\)|[a-z]+)';
430
+ return new RegExp(`${one}(?:\\s*,\\s*${one})*`).exec(c)?.[0] ?? null;
431
+ }
432
+
433
+ /** A length tied to a height word ("40px tall", "height 40px"). @param {string} c */
434
+ const tallIn = c =>
435
+ /\b(\d+(?:px|rem))\s+(?:tall|high)\b|\b(?:height|tall)\s*:?\s*(\d+(?:px|rem))\b/
436
+ .exec(c)
437
+ ?.slice(1)
438
+ .find(Boolean) ?? null;
439
+
440
+ /** A length tied to a radius word ("8px radius", "radius: 8px"). @param {string} c */
441
+ const radiusIn = c =>
442
+ /(-?\d*\.?\d+(?:px|rem|em)?)\s*(?:radius|corners?)\b|\b(?:radius|corners?|rounded)\s*:?\s*(?:to\s+)?(-?\d*\.?\d+(?:px|rem|em)?)\b/
443
+ .exec(c)
444
+ ?.slice(1)
445
+ .find(Boolean) ?? null;
446
+
447
+ /**
448
+ * Make a color lighter or darker by mixing in white or black.
449
+ * @param {string} color @param {number} amount -1 (darker) to 1 (lighter)
450
+ */
451
+ function shift(color, amount) {
452
+ const rgb = parseColor(color);
453
+ if (!rgb) return null;
454
+ const to = amount > 0 ? 255 : 0;
455
+ const a = Math.abs(amount);
456
+ return hex(rgb.map(c => c + (to - c) * a));
457
+ }
458
+
459
+ /**
460
+ * A color made stronger or fainter: a see-through color (#00000014) keeps
461
+ * its hue and scales its alpha; an opaque one moves toward black or white.
462
+ * @param {string} color @param {number} f above 1 stronger, below 1 fainter
463
+ * @param {'light' | 'dark'} mode
464
+ */
465
+ function stronger(color, f, mode) {
466
+ const m = /^#([0-9a-f]{6})([0-9a-f]{2})$/i.exec(String(color).trim());
467
+ if (m) {
468
+ const a = Math.max(1, Math.min(255, Math.round(parseInt(m[2], 16) * f)));
469
+ return `#${m[1]}${a.toString(16).padStart(2, '0')}`;
470
+ }
471
+ const away = mode === 'dark' ? 1 : -1;
472
+ return shift(color, (f > 1 ? 0.25 : -0.25) * away);
473
+ }
474
+
475
+ /**
476
+ * A font weight written in a clause: a number from 100 to 900, or a weight
477
+ * word ("semibold").
478
+ * @param {{text: string}} c
479
+ */
480
+ function weightIn(c) {
481
+ const n = /\b([1-9]00)\b(?!\s*(px|ms|%))/.exec(c.text)?.[1];
482
+ if (n) return n;
483
+ const w = /\b(semibold|semi-bold|medium|regular|normal)\b/.exec(c.text)?.[1];
484
+ return w
485
+ ? /** @type {Record<string, string>} */ ({
486
+ semibold: '600',
487
+ 'semi-bold': '600',
488
+ medium: '500',
489
+ regular: '400',
490
+ normal: '400',
491
+ })[w]
492
+ : null;
493
+ }
494
+
495
+ /** Scale a CSS length. @param {string} v @param {number} f */
496
+ function scaled(v, f) {
497
+ const m = /^(\d*\.?\d+)(px|rem|em)$/.exec(String(v ?? '').trim());
498
+ if (!m) return null;
499
+ const n = Number(m[1]) * f;
500
+ return `${m[2] === 'px' ? Math.round(n) : Number(n.toFixed(3))}${m[2]}`;
501
+ }
502
+
503
+ /**
504
+ * Words for parts, longest phrase first. Each gives the part (or group),
505
+ * and maybe a `--when` condition, a heading level or a font role.
506
+ * @type {Array<[RegExp, {on: string, when?: string, role?: string, level?: string}]>}
507
+ */
508
+ const PARTS = [
509
+ [/\b(focus (ring|outline)s?)\b/, {on: 'focus-ring'}],
510
+ [/\b((modal |dialog )?(overlay|scrim|backdrop))\b/, {on: 'overlay'}],
511
+ [/\bicons?\b/, {on: 'icons'}],
512
+ [
513
+ /\b(table header|column headers?|table headings?)\b/,
514
+ {on: 'table-header-cell'},
515
+ ],
516
+ [
517
+ /\b(tabs? (underline|indicator)s?|underline (of|on|under) (the )?tabs?)\b/,
518
+ {on: 'tab-indicator'},
519
+ ],
520
+ [/\b(status dots?)\b/, {on: 'status-dot'}],
521
+ [/\b(progress( bar)?( fill)?|loading bar)\b/, {on: 'progress-bar-fill'}],
522
+ [
523
+ /\b((side ?nav|sidebar)( nav(igation)?)? (links?|items?))\b/,
524
+ {on: 'side-nav-item'},
525
+ ],
526
+ [/\b(nav(igation)? (links?|items?)|menu items?)\b/, {on: 'top-nav-item'}],
527
+ [/\b(side ?nav|sidebar|side ?panel)\b/, {on: 'side-nav'}],
528
+ [
529
+ /\b(app (name|title)|logo|site title|product name)\b/,
530
+ {on: 'top-nav-heading'},
531
+ ],
532
+ [
533
+ /\b(header|top ?bar|title ?bar|nav ?bar|app ?bar|masthead)\b/,
534
+ {on: 'app-shell-header'},
535
+ ],
536
+ [/\b(page|app background|whole background|body background)\b/, {on: 'page'}],
537
+ [/\b(primary|main) buttons?\b/, {on: 'button', when: 'variant:primary'}],
538
+ [/\bsecondary buttons?\b/, {on: 'button', when: 'variant:secondary'}],
539
+ [/\bghost buttons?\b/, {on: 'button', when: 'variant:ghost'}],
540
+ [
541
+ /\b(danger|destructive|delete) (buttons?|ones?|variant)\b/,
542
+ {on: 'button', when: 'variant:destructive'},
543
+ ],
544
+ [/\bbuttons?\b/, {on: 'button'}],
545
+ [/\bcards?\b/, {on: 'card'}],
546
+ [/\b(panels?|windows?|boxes|tiles?|containers?)\b/, {on: 'containers'}],
547
+ [/\b(banners?|alerts?|notices?|announcements?)\b/, {on: 'banner'}],
548
+ [
549
+ /\b(inputs?|text ?box(es)?|text ?fields?|form fields?|fields?)\b/,
550
+ {on: 'inputs'},
551
+ ],
552
+ [/\b(checkbox(es)?|check ?marks?)\b/, {on: 'checks'}],
553
+ [/\b(toggles?|switch(es)?)\b/, {on: 'switch'}],
554
+ [/\b(table rows?|rows?|tables?)\b/, {on: 'table-row'}],
555
+ [/\btabs?\b/, {on: 'tab'}],
556
+ [/\b(badges?|chips?|tags?)\b/, {on: 'badge'}],
557
+ [/\bh([1-4])\b/, {on: 'heading'}],
558
+ [/\b(headings?|titles?)\b/, {on: 'heading'}],
559
+ [/\b(dialogs?|modals?|popups?)\b/, {on: 'dialog'}],
560
+ [/\btooltips?\b/, {on: 'tooltip'}],
561
+ [/\btoasts?\b/, {on: 'toast'}],
562
+ [/\bavatars?\b/, {on: 'avatar'}],
563
+ [/\blinks?\b/, {on: 'link'}],
564
+ [/\bcode\b/, {on: 'code', role: 'code'}],
565
+ [/\bbody( text)?\b/, {on: 'body', role: 'body'}],
566
+ ];
567
+
568
+ /** Words for a color the theme generates. */
569
+ const ROLE_WORDS =
570
+ /\b(accent|brand|primary colou?r|main colou?r|key colou?r|errors?|danger|destructive|success|positive|warnings?|caution|info|notices?|neutrals?)\b|\bprimary\s*:?\s*(?=#|rgb|hsl|oklch)/;
571
+
572
+ /** States a word names. */
573
+ const STATE_WORDS = /** @type {Array<[RegExp, string]>} */ ([
574
+ [/\b(hover(ed|ing)?|mouse ?over)\b/, 'hover'],
575
+ [/\b(focus(ed|ing)?|on focus)\b/, 'focus'],
576
+ [/\b(disabled|inactive)\b/, 'disabled'],
577
+ [/\b(checked|ticked|when on|turned on|toggled on|is on)\b/, 'checked'],
578
+ [
579
+ /\b(selected|active (tab|nav|item|link|page))\b|\bactive\b(?=.*\b(nav|tab|item)\b)/,
580
+ 'selected',
581
+ ],
582
+ [/\b(pressed|clicked|tapped|on press|on click)\b/, 'active'],
583
+ [/\b(invalid|errors? state|has an error|with an error)\b/, 'invalid'],
584
+ ]);
585
+
586
+ /**
587
+ * One clause, read.
588
+ * @typedef {object} Clause
589
+ * @property {string} text
590
+ * @property {Array<{on: string, when?: string, role?: string, level?: string}>} parts
591
+ * @property {string[]} aspects
592
+ * @property {boolean} neg
593
+ * @property {'more' | 'less' | null} dir
594
+ * @property {string[]} colors
595
+ * @property {string | null} bad - a hex color written with the wrong number of digits
596
+ * @property {string[]} lengths
597
+ * @property {string | null} state
598
+ * @property {'light' | 'dark' | null} mode
599
+ * @property {boolean} except - "but not on X": X keeps what the clause before does
600
+ * @property {Record<string, string>} decl - CSS written as `prop: value`
601
+ */
602
+
603
+ /**
604
+ * The aspects a clause asks about, by its words. Order is the answer order.
605
+ * @param {string} text
606
+ */
607
+ function aspectsOf(text) {
608
+ // A part's name is not an aspect: "text input" asks about an input.
609
+ const c = text.replace(
610
+ /\btext ?(inputs?|fields?|box(es)?|areas?)\b/g,
611
+ 'inputs',
612
+ );
613
+ /** @type {string[]} */
614
+ const a = [];
615
+ const add = (/** @type {string} */ x) => {
616
+ if (!a.includes(x)) a.push(x);
617
+ };
618
+ if (/\b(letter ?spacing|tracking|kerning)\b/.test(c)) add('tracking');
619
+ if (
620
+ /\b(round(ed|er|ness|ing)?|unround\w*|corners?|radius|radii|curv\w*|circular|circles?|pill( shaped)?|sharp(er)?|square(d|r)?)\b/.test(
621
+ c,
622
+ )
623
+ )
624
+ add('corners');
625
+ if (
626
+ /\b(shadows?|elevat\w*|depth|raised|lifts?|lifted|lifting|glow\w*|bevel\w*|sunken|inset|flat)\b/.test(
627
+ c,
628
+ )
629
+ )
630
+ add('shadow');
631
+ if (
632
+ /\b(borders?(?!-radius)|outlines?|strokes?|edges?|frames?|rings?)\b/.test(c)
633
+ )
634
+ add('border');
635
+ if (/\bunderlined?\b|\bunderlines\b/.test(c) && !/\btabs?\b/.test(c))
636
+ add('underline');
637
+ if (/\bline ?height|\bleading\b|\bline spacing\b/.test(c)) add('leading');
638
+ if (
639
+ !a.includes('tracking') &&
640
+ /\b(padding|spacing|space|spaced|gaps?|margins?|room(y|ier)?|airy|breathing|dense|denser|density|compact|tight(er)?|cramped|crowded|spacious|packed)\b/.test(
641
+ c,
642
+ )
643
+ )
644
+ add('spacing');
645
+ if (
646
+ /\b(uppercase|upper case|all caps|caps|lowercase|capitali[sz]ed?)\b/.test(c)
647
+ )
648
+ add('case');
649
+ if (/\bitalics?\b/.test(c)) add('italic');
650
+ if (
651
+ /\b(bold(er)?|unbold\w*|weight|heav(y|ier)|semibold)\b/.test(c) ||
652
+ /\bthin(ner)? (font|text|type|letters|headings?|labels?)\b/.test(c) ||
653
+ (/\blight(er)?\b/.test(c) &&
654
+ /\b(headings?|titles?|font|weight)\b/.test(c) &&
655
+ !/\b(text|colou?r|mode|background|bg)\b/.test(c))
656
+ )
657
+ add('weight');
658
+ if (
659
+ /\b(fonts?|typefaces?|serif|sans(-serif)?|mono(space|spaced)?)\b/.test(c) &&
660
+ !/\bfont ?size\b/.test(c) &&
661
+ !/\bfont ?weight\b|\b(bold|heav|light(er)?|thin)\w* fonts?\b|\bfonts? weight/.test(
662
+ c,
663
+ ) &&
664
+ !/\bfont (colou?r)\b/.test(c)
665
+ )
666
+ add('family');
667
+ if (
668
+ /\b(font ?size|text ?size|(bigger|larger|smaller|huge|tiny|big|small) (text|font|headings?|titles?|labels?)|(text|font|headings?|titles?|labels?|h[1-6]) (bigger|larger|smaller))\b/.test(
669
+ c,
670
+ ) ||
671
+ (/\b(bigger|larger|smaller)\b/.test(c) &&
672
+ /\b(text|font|headings?|titles?|h[1-6]|body)\b/.test(c)) ||
673
+ /\b\d+(px|rem) (text|font|labels?|type)\b/.test(c)
674
+ )
675
+ add('fontsize');
676
+ if (
677
+ (/\b(taller|shorter|wider|narrower|width|height|bigger|larger|smaller|tall)\b/.test(
678
+ c,
679
+ ) ||
680
+ (/\b(thick(er)?|thin(ner)?)\b/.test(c) &&
681
+ /\b(progress|underline|indicator)/.test(c))) &&
682
+ !a.includes('fontsize') &&
683
+ !a.includes('tracking')
684
+ )
685
+ add('size');
686
+ if (!a.includes('family') && new RegExp(`\\b(${FONT_NAMES})\\b`).test(c))
687
+ add('family');
688
+ if (!a.length && /\b(thick(er)?|thin(ner)?)\b/.test(c)) add('border');
689
+ if (
690
+ /\b(faded|fade|opacity|see-through|washed out)\b/.test(c) ||
691
+ /\d+%/.test(
692
+ c.replace(/\b(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\([^)]*\)/g, ''),
693
+ )
694
+ )
695
+ add('opacity');
696
+ if (/\b(scales? (down|up)|shrinks?|grows?)\b/.test(c)) add('scale');
697
+ if (
698
+ /\b(text|writing|words|labels?|font colou?r|readable|links?)\b/.test(c) &&
699
+ !a.some(x =>
700
+ ['case', 'italic', 'weight', 'family', 'fontsize', 'tracking'].includes(
701
+ x,
702
+ ),
703
+ )
704
+ )
705
+ add('text');
706
+ if (
707
+ /\b(background|bg|fill(ed)?|gradient|glossy|tint(ed)?|stripes|striped|zebra|transparent)\b/.test(
708
+ c,
709
+ )
710
+ )
711
+ add('background');
712
+ return a;
713
+ }
714
+
715
+ /** Font names a question can name, as words. */
716
+ const FONT_NAMES = [...Object.keys(OPEN_FONTS), ...Object.keys(FONTS)]
717
+ .filter(k => !['system', 'serif', 'mono', 'rounded', 'comic'].includes(k))
718
+ .map(k => k.replace(/-/g, ' '))
719
+ .join('|');
720
+
721
+ /**
722
+ * Read a question into clauses.
723
+ * @param {string} q lower-case, translated, corrected
724
+ * @returns {Clause[]}
725
+ */
726
+ function clausesOf(q) {
727
+ // "swap X and Y" is one ask.
728
+ const pieces = (/\bswap\b/.test(q) ? q.replace(/\band\b/g, '&') : q)
729
+ .split(
730
+ /;|\.(?=\s|$)|,(?![^(]*\))|\b(?:and|with|but|then|plus|also)\b|\bwhile\b|(?=\bexcept\b)/,
731
+ )
732
+ .map(s => s.trim())
733
+ .filter(Boolean);
734
+ return pieces.map(text => {
735
+ /** @type {Clause['parts']} */
736
+ const parts = [];
737
+ let rest = ` ${text} `;
738
+ const cornerWords = /\b(round|corner|radius|shape|circular)/.test(text);
739
+ for (const [re, part] of PARTS) {
740
+ const m = re.exec(rest);
741
+ if (!m) continue;
742
+ const p = {...part};
743
+ if (p.on === 'heading' && /^h[1-4]$/.test(m[0])) p.level = m[1];
744
+ parts.push(p);
745
+ rest = rest.replace(re, ' ');
746
+ }
747
+ // "pill" names a corner shape, not a badge, when the clause is about shape.
748
+ if (cornerWords || /\bpill( shaped)?\b/.test(text))
749
+ for (let i = parts.length - 1; i >= 0; i--)
750
+ if (parts[i].on === 'badge' && !/\b(badges?|chips?|tags?)\b/.test(text))
751
+ parts.splice(i, 1);
752
+ const aspects = aspectsOf(text);
753
+ // "orange not red" negates a color, not the change.
754
+ const hue = Object.keys(HUES).join('|');
755
+ const negText = text.replace(
756
+ new RegExp(`\\b(not|no)\\s+((light|dark|pale)\\s+)?(${hue})\\b`, 'g'),
757
+ ' ',
758
+ );
759
+ const neg =
760
+ /\b(no|not|don'?t|do not|never|without|remove|removing|get rid of|lose|drop|kill|none|shouldn'?t|should not|mustn'?t|turn off|turn (the|it|them) off|switch off|stop|unbold\w*|unround\w*|disable)\b/.test(
761
+ negText.replace(/\bdisabled\b/g, ' '),
762
+ ) && !/\bno (wait|longer)\b/.test(negText);
763
+ // "too X" asks for less X: too sharp is rounder, too heavy is lighter.
764
+ const tooLess =
765
+ /\btoo (big|large|round|rounded|bold|heavy|thick|dark|spacious|airy|bright|loud|strong|harsh|much|wide|tall)\b/;
766
+ const tooMore =
767
+ /\btoo (small|cramped|tight|crowded|faded|light|thin|sharp|square|boxy|pointy|subtle|weak|narrow|dim|low|short)\b/;
768
+ const dir = tooLess.test(text)
769
+ ? 'less'
770
+ : tooMore.test(text)
771
+ ? 'more'
772
+ : /\b(less|fewer|smaller|lower|reduce|softer|lighter|thinner|narrower|shorter|tight(er)?|dense(r)?|denser|compact|sharper|squarer|subtler|tone down|dimmer)\b/.test(
773
+ text,
774
+ )
775
+ ? 'less'
776
+ : /\b(more|bigger|larger|higher|increase|stronger|thicker|wider|taller|rounder|roomier|airy|spacious|bolder|heavier|darker|a bit|a little|slightly|much)\b/.test(
777
+ text,
778
+ )
779
+ ? 'more'
780
+ : null;
781
+ /** @type {Record<string, string>} */
782
+ const decl = {};
783
+ for (const m of text.matchAll(
784
+ /\b([a-z]+(?:-[a-z]+)*)\s*:\s*([^;,]+?)(?=\s+(?:on|for|in)\s+(?:the\s+)?[a-z]+\s*$|$)/g,
785
+ ))
786
+ if (
787
+ /^(box-shadow|background(-color)?|color|border(-[a-z]+)*|padding|margin|gap|font-[a-z]+|letter-spacing|text-transform|opacity|width|height|min-height|max-width)$/.test(
788
+ m[1],
789
+ )
790
+ )
791
+ decl[m[1]] = m[2].trim();
792
+ let state = null;
793
+ for (const [re, s] of STATE_WORDS)
794
+ if (re.test(text)) {
795
+ state = s;
796
+ break;
797
+ }
798
+ const mode =
799
+ /\bdark( mode| theme)?\b/.test(text) &&
800
+ /\b(mode|theme|in dark)\b/.test(text)
801
+ ? 'dark'
802
+ : /\blight (mode|theme)\b/.test(text)
803
+ ? 'light'
804
+ : null;
805
+ const except =
806
+ parts.length > 0 &&
807
+ (/^except\b/.test(text) ||
808
+ (neg &&
809
+ aspects.length === 0 &&
810
+ /\b(not|except)( for| on| in| the)* [a-z]/.test(negText)));
811
+ return {
812
+ text,
813
+ parts,
814
+ aspects,
815
+ neg,
816
+ dir,
817
+ colors: colorsIn(text),
818
+ bad: badHex(text),
819
+ lengths: lengthsIn(text),
820
+ state,
821
+ mode,
822
+ except,
823
+ decl,
824
+ };
825
+ });
826
+ }
827
+
828
+ /**
829
+ * Answer a plain-words question with drafts of commands.
830
+ * @param {import('./_settings.mjs').Ctx} ctx
831
+ * @param {import('./_how-commands.mjs').HowTheme} env
832
+ * @param {string} question
833
+ * @returns {{parts: string[], aspects: string[], drafts: Draft[]}}
834
+ */
835
+ export function draftAnswer(ctx, env, question) {
836
+ const {C} = ctx;
837
+ const TARGET = ctx.project.target;
838
+ const TOKENS = ctx.project.core.tokenDefaults;
839
+ let q = question
840
+ .normalize('NFKC')
841
+ .replace(/\p{Cc}/gu, ' ')
842
+ // Code-shaped asks: camelCase keys, JSON and CSS punctuation, dotted
843
+ // paths ("primaryColor=#3b82f6", {"accent": ...}, theme.colors.primary).
844
+ .replace(/([a-z])([A-Z])/g, '$1 $2')
845
+ .replace(/[{}"`]/g, ' ')
846
+ .replace(/(?<=[a-z])\.(?=[a-z])/gi, ' ')
847
+ .replace(/(?<![\w-])\.(?=[a-z])/gi, ' ')
848
+ .replace(/\s*=\s*/g, ' ')
849
+ .toLowerCase()
850
+ .replace(/[\u2018\u2019]/g, "'");
851
+ for (const [re, w] of TRANSLATE) q = q.replace(re, w);
852
+ q = q
853
+ .replace(/\bbutton-s\b/g, 'buttons')
854
+ .replace(/[a-z]+/g, w => corrected(w))
855
+ .replace(/\b(everything|everywhere|all) but\b/g, '$1 except')
856
+ .replace(
857
+ /\b(apart from|other than|excluding|but not (on|in|for)|but not)\b/g,
858
+ 'except',
859
+ )
860
+ .replace(/\s+/g, ' ')
861
+ .trim();
862
+ const clauses = clausesOf(q);
863
+ // "nav items" in a question about the sidebar are the side nav's; an
864
+ // underline on tabs is the tab indicator.
865
+ const side = /\b(side ?nav|sidebar|side ?panel)\b/.test(q);
866
+ for (const c of clauses)
867
+ for (const p of c.parts) {
868
+ if (side && p.on === 'top-nav-item') p.on = 'side-nav-item';
869
+ if (p.on === 'tab' && /\bunderline/.test(c.text)) p.on = 'tab-indicator';
870
+ }
871
+ // A clause with no part takes the part of the clause before it ("a dark
872
+ // card with white text"); one with values but no aspect takes the aspect
873
+ // of a neighbor ("cards: 8px radius; buttons: 4px").
874
+ const fillAspect = () => {
875
+ for (const c of clauses)
876
+ if (
877
+ c.parts.length &&
878
+ !c.aspects.length &&
879
+ !c.except &&
880
+ (c.colors.length ||
881
+ THEME_COLOR_WORDS.some(([re]) => re.test(c.text)) ||
882
+ /\b(darker|lighter|brighter|colou?r(ed)?)\b/.test(c.text) ||
883
+ (!c.neg && toneIn(c.text)))
884
+ )
885
+ c.aspects.push('background');
886
+ };
887
+ fillAspect();
888
+ for (let i = 0; i < clauses.length; i++) {
889
+ const c = clauses[i];
890
+ const prev = clauses[i - 1];
891
+ const next = clauses[i + 1];
892
+ const before = clauses
893
+ .slice(0, i)
894
+ .reverse()
895
+ .find(x => x.parts.length && !x.except);
896
+ if (
897
+ !c.parts.length &&
898
+ before &&
899
+ !c.except &&
900
+ // "per the brand guide" names no part; "accent text" does.
901
+ !(ROLE_WORDS.test(c.text) && !c.aspects.length) &&
902
+ (c.aspects.length || c.colors.length || c.lengths.length)
903
+ ) {
904
+ c.parts = before.parts.map(p => ({...p}));
905
+ c.state ??= before.state;
906
+ }
907
+ if (
908
+ !c.aspects.length &&
909
+ !ROLE_WORDS.test(c.text) &&
910
+ (c.lengths.length || /\b(stay|keep)\b/.test(c.text))
911
+ ) {
912
+ const from = prev?.aspects.length
913
+ ? prev
914
+ : next?.aspects.length
915
+ ? next
916
+ : null;
917
+ if (from) c.aspects = [...from.aspects];
918
+ }
919
+ // "in dark mode, cards are #1c1c1e": a clause that only names the mode
920
+ // gives it to the clauses after it.
921
+ if (
922
+ !c.mode &&
923
+ prev?.mode &&
924
+ (!c.parts.length || (!prev.parts.length && !prev.aspects.length))
925
+ )
926
+ c.mode = prev.mode;
927
+ // "brand blue, #0057ff": a clause that is only a color belongs to the
928
+ // clause before it.
929
+ if (
930
+ prev &&
931
+ !c.parts.length &&
932
+ !c.aspects.length &&
933
+ c.colors.length &&
934
+ c.text
935
+ .replace(/#[0-9a-f]+|\b(?:rgba?|hsla?|oklch)\([^)]*\)/g, '')
936
+ .trim()
937
+ .split(/\s+/)
938
+ .filter(Boolean).length <= 1
939
+ ) {
940
+ prev.colors = [...c.colors, ...prev.colors];
941
+ c.colors = [];
942
+ c.text = '';
943
+ }
944
+ }
945
+ fillAspect();
946
+ const modal = env.data.mode === 'both';
947
+ const modeOf = (/** @type {Clause} */ c) =>
948
+ c.mode && modal ? {mode: c.mode} : {};
949
+ /** @type {Draft[]} */
950
+ const drafts = [];
951
+ /** @type {string[]} */
952
+ const partsSeen = [];
953
+ /** @type {string[]} */
954
+ const aspectsSeen = [];
955
+ const seenPart = (/** @type {string} */ p) => {
956
+ if (!partsSeen.includes(p)) partsSeen.push(p);
957
+ };
958
+ const seenAspect = (/** @type {string} */ a) => {
959
+ if (!aspectsSeen.includes(a)) aspectsSeen.push(a);
960
+ };
961
+ /** @param {string} token @param {'light' | 'dark'} [mode] */
962
+ const current = (token, mode = 'light') =>
963
+ env.base[mode]?.[token] ?? String(TOKENS[token] ?? '');
964
+ /** The member a group's checks read. @param {string} on */
965
+ const one = on => (FAMILIES[on] ? FAMILIES[on][0] : on);
966
+ /**
967
+ * The state a part takes for a state word, as `set` names it.
968
+ * @param {string} on @param {string} word
969
+ */
970
+ const stateFor = (on, word) => {
971
+ const t = TARGET.get(one(on));
972
+ const states = [...(t?.states ?? []), ...COMMON_STATES];
973
+ if (word === 'focus') {
974
+ const conds = JSON.stringify(C.MAP[one(on)]?.own ?? {});
975
+ for (const s of ['focus-within', 'focus-visible', 'focus'])
976
+ if (conds.includes(`:${s}`)) return s;
977
+ return 'focus-visible';
978
+ }
979
+ if (word === 'invalid') return null;
980
+ return states.includes(word) ? word : null;
981
+ };
982
+ /** @param {Clause} c @param {{on: string, when?: string, level?: string}} p */
983
+ const flagsFor = (c, p) => {
984
+ /** @type {{on?: string, when?: string, state?: string, noState?: string}} */
985
+ const f = {on: p.on};
986
+ if (p.when) f.when = p.when;
987
+ if (p.level) f.when = `level:${p.level}`;
988
+ const vals = C.variantValues(one(p.on));
989
+ if (!f.when && vals.size) {
990
+ const size = /\b(small|sm)\b/.test(c.text)
991
+ ? ['sm', 'small']
992
+ : /\b(large|lg)\b/.test(c.text)
993
+ ? ['lg', 'large']
994
+ : [];
995
+ const hit = size.find(s => vals.size.includes(s));
996
+ if (hit) f.when = `size:${hit}`;
997
+ }
998
+ if (
999
+ c.state === 'invalid' &&
1000
+ (vals.status ?? []).includes('error') &&
1001
+ !f.when
1002
+ )
1003
+ f.when = 'status:error';
1004
+ else if (c.state) {
1005
+ const st = stateFor(p.on, c.state);
1006
+ if (st) f.state = st;
1007
+ else f.noState = c.state;
1008
+ }
1009
+ return f;
1010
+ };
1011
+ /** A setting the theme already has for the thing on the part. @param {string[]} things @param {string | undefined} on */
1012
+ const existing = (things, on) =>
1013
+ env.data.settings.filter(
1014
+ s => things.includes(s.thing) && (s.on ?? '') === (on ?? ''),
1015
+ );
1016
+ /**
1017
+ * Carry the clause's color mode into every step that takes --mode, and
1018
+ * say so when a step cannot: only colors and shadows differ by mode.
1019
+ * @param {Draft} d @param {Clause | null} c
1020
+ * @returns {Draft}
1021
+ */
1022
+ const withMode = (d, c) => {
1023
+ if (!c?.mode || !d.options.length) return d;
1024
+ if (d.options.every(o => o.every(st => st.thing === 'mode'))) return d;
1025
+ if (env.data.mode !== 'both') {
1026
+ const only = env.data.mode === 'light-only' ? 'light' : 'dark';
1027
+ if (only === c.mode) return d;
1028
+ return {
1029
+ text: `${env.slug} has only a ${only} mode, so it has no ${c.mode} mode to change; set mode both to give it one`,
1030
+ options: [],
1031
+ lookup: `${HOW} mode`,
1032
+ };
1033
+ }
1034
+ /** @param {Step} st */
1035
+ const modal = st => {
1036
+ if (st.mode) return true;
1037
+ if (st.verb !== 'set') return false;
1038
+ if (st.thing.startsWith('--')) return C.typeOf(st.thing) === 'color';
1039
+ if (st.thing === 'background')
1040
+ return (
1041
+ parseColor(st.value ?? '') != null || /^var\(/.test(st.value ?? '')
1042
+ );
1043
+ return COLOR_PROPS.test(st.thing);
1044
+ };
1045
+ const options = d.options
1046
+ .filter(o => o.every(modal))
1047
+ .map(o =>
1048
+ o.map(st => (st.mode ? st : {...st, mode: c.mode ?? undefined})),
1049
+ );
1050
+ if (options.length) return {...d, options};
1051
+ return {
1052
+ text: `${d.text}: this is the same in light and dark; set takes --mode only for colors, so it cannot be ${c.mode} mode only`,
1053
+ options: [],
1054
+ };
1055
+ };
1056
+ /** @type {Clause | null} */
1057
+ let clauseNow = null;
1058
+ /** @param {Draft} input */
1059
+ const push = input => {
1060
+ const d = withMode(input, clauseNow);
1061
+ const options = d.options.filter(o => o.length);
1062
+ // The caller reads what was kept.
1063
+ input.text = d.text;
1064
+ input.options = options;
1065
+ drafts.push({
1066
+ text: d.text,
1067
+ options,
1068
+ ...(d.sequence && options.length ? {sequence: true} : {}),
1069
+ ...(d.lookup ? {lookup: d.lookup} : {}),
1070
+ });
1071
+ };
1072
+ const set = (
1073
+ /** @type {string} */ thing,
1074
+ /** @type {string} */ value,
1075
+ /** @type {Record<string, string | undefined>} */ flags = {},
1076
+ ) =>
1077
+ /** @type {Step} */ ({
1078
+ verb: 'set',
1079
+ thing,
1080
+ value,
1081
+ ...Object.fromEntries(Object.entries(flags).filter(([, v]) => v)),
1082
+ });
1083
+ /** A color for the clause, for a fill or a text color. @param {Clause} c @param {'fill' | 'text'} kind */
1084
+ const colorFor = (c, kind) => {
1085
+ for (const [re, fill, text] of THEME_COLOR_WORDS)
1086
+ if (re.test(c.text)) return kind === 'fill' ? fill : text;
1087
+ if (kind === 'text' && !c.colors.length) {
1088
+ if (/\bdark (text|labels?|writing|words)\b/.test(c.text))
1089
+ return '#111827';
1090
+ if (/\blight (text|labels?|writing|words)\b/.test(c.text))
1091
+ return '#f9fafb';
1092
+ }
1093
+ return c.colors[0] ?? null;
1094
+ };
1095
+ /** @type {Array<{clause: Clause, steps: Step[]}>} */
1096
+ const tops = [];
1097
+ const recordTop = (/** @type {Clause} */ c, /** @type {Step[]} */ steps) => {
1098
+ if (steps.length) tops.push({clause: c, steps});
1099
+ };
1100
+
1101
+ for (const c of clauses) {
1102
+ clauseNow = c;
1103
+ if (c.except) {
1104
+ const prior = tops[tops.length - 1];
1105
+ if (!prior) continue;
1106
+ for (const p of c.parts) {
1107
+ seenPart(p.on);
1108
+ const keep = prior.steps
1109
+ .map(st => keepAsIs(st, p))
1110
+ .filter(x => x != null);
1111
+ if (!keep.length) {
1112
+ push({
1113
+ text: `${p.on} keeps what it has: a setting --on ${p.on} wins over a whole-theme one there, but this change has no setting for ${p.on} to keep`,
1114
+ options: [],
1115
+ lookup: `${HOW} ${p.on}`,
1116
+ });
1117
+ continue;
1118
+ }
1119
+ push({
1120
+ text: `${prior.clause.text}, except ${p.on}, which keeps what it has now`,
1121
+ options: [[...prior.steps, .../** @type {Step[]} */ (keep)]],
1122
+ sequence: true,
1123
+ });
1124
+ // The whole ask comes first, before the change alone.
1125
+ drafts.unshift(/** @type {Draft} */ (drafts.pop()));
1126
+ tops.pop();
1127
+ }
1128
+ continue;
1129
+ }
1130
+ // A color the theme generates, named by its role ("error background",
1131
+ // "slightly darker accent"), is that color, not a part's fill.
1132
+ if (
1133
+ !c.parts.length &&
1134
+ c.aspects.every(a => a === 'background' || a === 'text') &&
1135
+ ROLE_WORDS.test(c.text) &&
1136
+ !/\b(text|labels?)\b/.test(c.text)
1137
+ ) {
1138
+ const whole = wholeTheme({...c, aspects: []});
1139
+ if (whole) {
1140
+ seenAspect('colors');
1141
+ push(whole);
1142
+ recordTop(c, whole.options[0] ?? []);
1143
+ continue;
1144
+ }
1145
+ }
1146
+ for (const a of c.aspects) seenAspect(a);
1147
+ for (const p of c.parts) seenPart(p.on);
1148
+ // A hover effect with nothing more said: a slightly darker part.
1149
+ if (c.parts.length && !c.aspects.length && c.state === 'hover' && !c.neg)
1150
+ c.aspects.push('background');
1151
+ // A part with no aspect: what it reads.
1152
+ if (c.parts.length && !c.aspects.length) {
1153
+ for (const p of c.parts.slice(0, 2))
1154
+ if (TARGET.has(one(p.on)))
1155
+ drafts.push({
1156
+ text: `what ${p.on} reads`,
1157
+ options: [],
1158
+ lookup: `${HOW} ${p.on}`,
1159
+ });
1160
+ continue;
1161
+ }
1162
+ const targets = c.parts.length ? c.parts : [null];
1163
+ for (const p of targets.slice(0, 3)) {
1164
+ for (const a of c.aspects.slice(0, 3)) {
1165
+ const d = answerFor(c, p, a);
1166
+ if (d && p && d.options.length) {
1167
+ d.text += readsNote(p.on, a);
1168
+ // A part with variants: without --when the change reaches all.
1169
+ const first = d.options[0]?.[0];
1170
+ const variant = Object.entries(C.variantValues(one(p.on))).find(
1171
+ ([k, vals]) =>
1172
+ ['status', 'variant', 'tone', 'type'].includes(k) &&
1173
+ vals.length > 1,
1174
+ );
1175
+ if (
1176
+ first?.on &&
1177
+ !first.when &&
1178
+ variant &&
1179
+ ['text', 'background', 'border'].includes(a)
1180
+ ) {
1181
+ const [vp, vals] = variant;
1182
+ d.text += `; ${p.on} has ${vp} ${vals.join('|')}, and without --when the change reaches every ${vp}; for one, add --when ${vp}:${vals[0]}`;
1183
+ d.options.push([{...first, when: `${vp}:${vals[0]}`}]);
1184
+ }
1185
+ }
1186
+ if (d) {
1187
+ push(d);
1188
+ recordTop(c, d.options[0] ?? []);
1189
+ }
1190
+ }
1191
+ if (!c.aspects.length && !p) {
1192
+ const whole = wholeTheme(c);
1193
+ if (whole) {
1194
+ push(whole);
1195
+ recordTop(c, whole.options[0] ?? []);
1196
+ }
1197
+ }
1198
+ }
1199
+ }
1200
+
1201
+ /**
1202
+ * The step that keeps one part as it is now when a step changes the whole
1203
+ * theme (or a group the part is in), or null when none can.
1204
+ * @param {Step} st
1205
+ * @param {{on: string, when?: string}} p
1206
+ * @returns {Step | null}
1207
+ */
1208
+ function keepAsIs(st, p) {
1209
+ const flags = {on: p.on, ...(p.when ? {when: p.when} : {})};
1210
+ if (st.on && st.on !== p.on && !(FAMILIES[st.on] ?? []).includes(one(p.on)))
1211
+ return null;
1212
+ if (st.thing === 'corners') {
1213
+ const read = C.partReads(one(p.on), 'corners').find(r =>
1214
+ r.when.includes(''),
1215
+ );
1216
+ return set(
1217
+ 'border-radius',
1218
+ read
1219
+ ? current(read.token) || `var(${read.token})`
1220
+ : current('--radius-element'),
1221
+ flags,
1222
+ );
1223
+ }
1224
+ if (st.thing === 'spacing') {
1225
+ const now =
1226
+ [...env.data.settings]
1227
+ .reverse()
1228
+ .find(x => x.thing === 'spacing' && (x.on ?? '') === (p.on ?? ''))
1229
+ ?.value ?? 'medium';
1230
+ return set('spacing', now, {on: p.on});
1231
+ }
1232
+ if (
1233
+ /^--shadow-/.test(st.thing) ||
1234
+ st.thing === 'box-shadow' ||
1235
+ st.thing === 'surfaces'
1236
+ )
1237
+ return set('box-shadow', 'none', flags);
1238
+ if (
1239
+ st.thing === 'headings' ||
1240
+ st.thing === '--text-body-weight' ||
1241
+ st.thing === 'font-weight'
1242
+ )
1243
+ return set(
1244
+ 'font-weight',
1245
+ String(current('--text-body-weight') || '400'),
1246
+ flags,
1247
+ );
1248
+ const group = /** @type {Record<string, string>} */ ({
1249
+ background: 'background',
1250
+ 'background-color': 'background',
1251
+ color: 'text',
1252
+ 'border-color': 'border',
1253
+ border: 'border',
1254
+ })[st.thing];
1255
+ if (group) {
1256
+ const want = p.when?.replace(':', '=');
1257
+ const read =
1258
+ C.partReads(one(p.on), group).find(r =>
1259
+ want ? r.when.includes(want) : r.when.includes(''),
1260
+ ) ??
1261
+ C.partReads(one(p.on), group).find(r =>
1262
+ p.when
1263
+ ? r.when.includes(`--when ${p.when}`) ||
1264
+ r.when.some(w => w.includes(p.when?.replace(':', '=') ?? ''))
1265
+ : r.when.includes(''),
1266
+ );
1267
+ if (read)
1268
+ return set(
1269
+ st.thing === 'border' ? 'border-color' : st.thing,
1270
+ `var(${read.token})`,
1271
+ flags,
1272
+ );
1273
+ }
1274
+ return null;
1275
+ }
1276
+
1277
+ /**
1278
+ * The commands for one part (or the whole theme) and one aspect.
1279
+ * @param {Clause} c
1280
+ * @param {{on: string, when?: string, role?: string, level?: string} | null} p
1281
+ * @param {string} a
1282
+ * @returns {Draft | null}
1283
+ */
1284
+ function answerFor(c, p, a) {
1285
+ if (c.bad)
1286
+ return {
1287
+ text: `"${c.bad}" is not a color: a hex color has 3, 4, 6 or 8 digits after the #. Give the color again.`,
1288
+ options: [],
1289
+ };
1290
+ const on = p?.on;
1291
+ const {noState, ...f} = p ? flagsFor(c, p) : {};
1292
+ if (noState && on) {
1293
+ const t = TARGET.get(one(on));
1294
+ return {
1295
+ text: `${on} has no ${noState} state that set can name (its states: ${[...(t?.states ?? []), ...COMMON_STATES].join(', ')}), so a change would reach every ${on}`,
1296
+ options: [],
1297
+ lookup: `${HOW} ${on}`,
1298
+ };
1299
+ }
1300
+ const where = on
1301
+ ? ` on ${on}${f.when ? ` (${f.when.replace(':', ' ')})` : ''}${f.state ? ` when ${f.state}` : ''}`
1302
+ : ' for the whole theme';
1303
+ const undo = (/** @type {string[]} */ things) =>
1304
+ existing(things, on).map(s => [
1305
+ /** @type {Step} */ ({
1306
+ verb: 'undo',
1307
+ thing: s.thing,
1308
+ ...(on ? {on} : {}),
1309
+ ...(s.when ? {when: s.when} : {}),
1310
+ ...(s.state ? {state: s.state} : {}),
1311
+ ...(s.mode ? {mode: s.mode} : {}),
1312
+ }),
1313
+ ]);
1314
+ if (on === 'focus-ring') {
1315
+ const ringColor = colorFor(c, 'fill');
1316
+ if (ringColor && c.lengths[0] && !c.neg)
1317
+ return {
1318
+ text: "the focus ring's width and color: --focus-outline-width and --focus-outline-color",
1319
+ options: [
1320
+ [
1321
+ set('--focus-outline-width', c.lengths[0]),
1322
+ set('--focus-outline-color', ringColor, modeOf(c)),
1323
+ ],
1324
+ ],
1325
+ sequence: true,
1326
+ };
1327
+ if (
1328
+ (a === 'border' && !ringColor) ||
1329
+ a === 'size' ||
1330
+ a === 'spacing' ||
1331
+ /\b(thick|thin|width)/.test(c.text)
1332
+ ) {
1333
+ const w =
1334
+ c.lengths[0] ??
1335
+ scaled(
1336
+ current('--focus-outline-width'),
1337
+ c.dir === 'less' ? 0.5 : 1.5,
1338
+ ) ??
1339
+ '3px';
1340
+ return {
1341
+ text: `the focus ring's width${where}: --focus-outline-width`,
1342
+ options: [[set('--focus-outline-width', w)]],
1343
+ };
1344
+ }
1345
+ const color = colorFor(c, 'fill');
1346
+ if (c.neg)
1347
+ return {
1348
+ text: 'the focus ring shows keyboard users where they are; it can be made subtle but not removed',
1349
+ options: [[set('--focus-outline-width', '1px')]],
1350
+ };
1351
+ return color
1352
+ ? {
1353
+ text: `the focus ring's color: --focus-outline-color`,
1354
+ options: [[set('--focus-outline-color', color, modeOf(c))]],
1355
+ }
1356
+ : null;
1357
+ }
1358
+ if (on === 'page') {
1359
+ const color = colorFor(c, 'fill') ?? (c.neg ? null : null);
1360
+ if (!color) return null;
1361
+ return {
1362
+ text: `the page background: --color-background-body${c.mode && modal ? ` in ${c.mode} mode` : ''}`,
1363
+ options: [
1364
+ [set('--color-background-body', color, modeOf(c))],
1365
+ [set('background', color, {on: 'app-shell'})],
1366
+ ],
1367
+ };
1368
+ }
1369
+ if (on === 'icons') {
1370
+ const color = colorFor(c, 'fill');
1371
+ if (!color) return null;
1372
+ return {
1373
+ text: 'icon colors: --color-icon-primary for most icons, --color-icon-secondary for quieter ones',
1374
+ options: [
1375
+ [set('--color-icon-primary', color, modeOf(c))],
1376
+ [set('--color-icon-secondary', color, modeOf(c))],
1377
+ ],
1378
+ };
1379
+ }
1380
+ if (on === 'overlay') {
1381
+ const now = current('--color-overlay', c.mode ?? 'light');
1382
+ const value =
1383
+ colorFor(c, 'fill') ??
1384
+ (c.dir || c.neg
1385
+ ? stronger(now, c.dir === 'more' ? 1.5 : 0.6, c.mode ?? 'light')
1386
+ : null);
1387
+ if (!value) return null;
1388
+ return {
1389
+ text: `the dimmed layer behind dialogs and drawers: --color-overlay (now ${now})`,
1390
+ options: [[set('--color-overlay', value, modeOf(c))]],
1391
+ };
1392
+ }
1393
+ if (p?.role === 'body' && a === 'weight') {
1394
+ const v =
1395
+ weightIn(c) ??
1396
+ (c.neg
1397
+ ? '400'
1398
+ : /\b(light(er)?|thin(ner)?)\b/.test(c.text)
1399
+ ? '300'
1400
+ : c.dir === 'less'
1401
+ ? '400'
1402
+ : '700');
1403
+ return {
1404
+ text: `body text weight: --text-body-weight (now ${current('--text-body-weight')})`,
1405
+ options: [[set('--text-body-weight', v)]],
1406
+ };
1407
+ }
1408
+ if (p?.role && (a === 'family' || a === 'fontsize')) {
1409
+ if (a === 'family') {
1410
+ const font = fontIn(c.text, question);
1411
+ return font
1412
+ ? {
1413
+ text: `the ${p.role} font: font --on ${p.role}`,
1414
+ options: [[set('font', font, {on: p.role})]],
1415
+ }
1416
+ : null;
1417
+ }
1418
+ if (p.role === 'body') {
1419
+ const px = /\b(\d+)px\b/.exec(c.text)?.[1];
1420
+ return {
1421
+ text: 'the body text size: text-size (every heading scales from it)',
1422
+ options: [
1423
+ [set('text-size', px ?? (c.dir === 'less' ? 'less' : 'more'))],
1424
+ ],
1425
+ };
1426
+ }
1427
+ }
1428
+ if (p?.role === 'body' && a !== 'leading')
1429
+ return wholeTheme({...c, parts: []}, a);
1430
+ switch (a) {
1431
+ case 'underline': {
1432
+ if (!on) return null;
1433
+ const value = c.neg ? 'none' : 'underline';
1434
+ return {
1435
+ text: `${c.neg ? 'no underline' : 'underlined'}${where}: text-decoration`,
1436
+ options: [[set('text-decoration', value, f)]],
1437
+ };
1438
+ }
1439
+ case 'leading': {
1440
+ const n = /\b(\d(?:\.\d+)?)\b(?!\s*(px|rem|em|%))/.exec(c.text)?.[1];
1441
+ const tok =
1442
+ !on || on === 'body' || p?.role === 'body'
1443
+ ? '--text-body-leading'
1444
+ : null;
1445
+ const now = tok ? current(tok) : null;
1446
+ const value =
1447
+ n ??
1448
+ (now && /^\d*\.?\d+$/.test(now)
1449
+ ? String(
1450
+ Number(
1451
+ (Number(now) * (c.dir === 'less' ? 0.9 : 1.1)).toFixed(2),
1452
+ ),
1453
+ )
1454
+ : c.dir === 'less'
1455
+ ? '1.3'
1456
+ : '1.6');
1457
+ if (tok)
1458
+ return {
1459
+ text: `body line height: --text-body-leading${now ? ` (now ${now})` : ''}`,
1460
+ options: [[set(tok, value)]],
1461
+ };
1462
+ return {
1463
+ text: `line height${where}`,
1464
+ options: [[set('line-height', value, f)]],
1465
+ };
1466
+ }
1467
+ case 'corners': {
1468
+ const tall = tallIn(c.text);
1469
+ const tied = radiusIn(c.text);
1470
+ const px =
1471
+ (tied && /^-?\d*\.?\d+$/.test(tied) ? `${tied}px` : tied) ??
1472
+ c.lengths.find(l => l !== tall) ??
1473
+ null;
1474
+ if (px?.startsWith('-'))
1475
+ return {
1476
+ text: `a radius cannot be negative ("${px}"); give a size of 0 or more`,
1477
+ options: [],
1478
+ };
1479
+ // "too sharp" asks for rounder, not square.
1480
+ const shapeText = c.text.replace(/\btoo \w+/g, ' ');
1481
+ const shape =
1482
+ c.neg || /\b(square(d)?|sharp)\b/.test(shapeText)
1483
+ ? 'square'
1484
+ : /\b(pill|circular|circles?|fully round)\b/.test(shapeText)
1485
+ ? 'pill'
1486
+ : null;
1487
+ const value =
1488
+ px ??
1489
+ shape ??
1490
+ (/\b(stay|keep)\b/.test(c.text)
1491
+ ? null
1492
+ : c.dir === 'less'
1493
+ ? 'less'
1494
+ : c.dir === 'more' || /\brounder\b/.test(c.text)
1495
+ ? 'more'
1496
+ : 'round');
1497
+ if (!value) return null;
1498
+ if (!on)
1499
+ return {
1500
+ text: `corners${where}: the corners dial (sets the corner tokens together)`,
1501
+ options: [[set('corners', value)]],
1502
+ };
1503
+ if (px)
1504
+ return {
1505
+ text: `corners${where}: border-radius ${px}`,
1506
+ options: [[set('border-radius', px, f)], [set('corners', px, f)]],
1507
+ };
1508
+ return {
1509
+ text: `corners${where}: corners ${value}`,
1510
+ options: [[set('corners', value, f)]],
1511
+ };
1512
+ }
1513
+ case 'shadow': {
1514
+ const typedShadow = c.decl['box-shadow'] ?? shadowIn(c.text);
1515
+ if (typedShadow && on && !c.neg)
1516
+ return {
1517
+ text: `the shadow you wrote${where}`,
1518
+ options: [[set('box-shadow', typedShadow, f)]],
1519
+ };
1520
+ if (typedShadow && !on && !c.neg)
1521
+ return {
1522
+ text: 'the shadow you wrote, as the shared medium shadow most panels use: --shadow-med',
1523
+ options: [[set('--shadow-med', typedShadow, modeOf(c))]],
1524
+ };
1525
+ const strong =
1526
+ /\b(strong(er)?|deep(er)?|heav(y|ier)|bigger|more)\b/.test(c.text);
1527
+ const soft = /\b(soft(er)?|subtle(r)?|light(er)?|gentle|less)\b/.test(
1528
+ c.text,
1529
+ );
1530
+ if (!on) {
1531
+ if (c.neg || /\bflat\b/.test(c.text))
1532
+ return {
1533
+ text: /\bflat\b/.test(c.text)
1534
+ ? 'flat panels: no border, no shadow, a tinted fill (the surfaces dial); or only the shadows off'
1535
+ : 'no shadows: set each shared shadow token to none',
1536
+ options: /\bflat\b/.test(c.text)
1537
+ ? [[set('surfaces', 'flat')]]
1538
+ : [
1539
+ ['--shadow-low', '--shadow-med', '--shadow-high']
1540
+ .filter(t => t in TOKENS)
1541
+ .map(t => set(t, 'none')),
1542
+ ],
1543
+ sequence: !/\bflat\b/.test(c.text),
1544
+ };
1545
+ if (/\b(raised|elevated|lifted)\b/.test(c.text))
1546
+ return {
1547
+ text: 'raised panels: a soft shadow, no border (the surfaces dial)',
1548
+ options: [[set('surfaces', 'raised')]],
1549
+ };
1550
+ const shades = soft
1551
+ ? [
1552
+ '0 1px 2px rgb(0 0 0 / 0.05)',
1553
+ '0 2px 6px rgb(0 0 0 / 0.07)',
1554
+ '0 6px 16px rgb(0 0 0 / 0.1)',
1555
+ ]
1556
+ : [
1557
+ '0 2px 4px rgb(0 0 0 / 0.12)',
1558
+ '0 6px 14px rgb(0 0 0 / 0.18)',
1559
+ '0 14px 32px rgb(0 0 0 / 0.26)',
1560
+ ];
1561
+ return {
1562
+ text: `${soft ? 'softer' : 'stronger'} shadows everywhere: the three shared shadow tokens, light to strong`,
1563
+ options: [
1564
+ ['--shadow-low', '--shadow-med', '--shadow-high']
1565
+ .filter(t => t in TOKENS)
1566
+ .map((t, i) => set(t, shades[i], modeOf(c))),
1567
+ ],
1568
+ sequence: true,
1569
+ };
1570
+ }
1571
+ if (c.neg)
1572
+ return {
1573
+ text: `no shadow${where}`,
1574
+ options: [...undo(['box-shadow']), [set('box-shadow', 'none', f)]],
1575
+ };
1576
+ const design = Object.keys(DESIGN).find(
1577
+ d =>
1578
+ ['bevel', 'raised', 'sunken'].includes(d) &&
1579
+ new RegExp(`\\b${d}`).test(c.text.replace(/\bbeveled\b/, 'bevel')),
1580
+ );
1581
+ const glow = /\bglow/.test(c.text);
1582
+ if (/\blift/.test(c.text) && !f.state && on) f.state = 'hover';
1583
+ const value = glow
1584
+ ? `0 0 12px 2px ${c.colors[0] ?? 'var(--color-accent)'}`
1585
+ : design
1586
+ ? DESIGN[design].replace(/^"|"$/g, '')
1587
+ : `var(${soft ? '--shadow-low' : strong || /\blift/.test(c.text) ? '--shadow-high' : '--shadow-med'})`;
1588
+ return {
1589
+ text: `${glow ? 'a glow' : 'shadow'}${where}: box-shadow`,
1590
+ options: [[set('box-shadow', value, f)]],
1591
+ };
1592
+ }
1593
+ case 'border': {
1594
+ if (on === 'tab-indicator') return answerFor(c, p, 'size');
1595
+ const outline =
1596
+ /\boutlines?\b/.test(c.text) && !/\bborders?\b/.test(c.text);
1597
+ if (!on) {
1598
+ const color = colorFor(c, 'fill');
1599
+ if (c.neg)
1600
+ return {
1601
+ text: 'no borders: the shared border width to 0',
1602
+ options: [[set('--border-width', '0px')]],
1603
+ };
1604
+ if (color)
1605
+ return {
1606
+ text: 'the border color of the whole theme: --color-border',
1607
+ options: [[set('--color-border', color, modeOf(c))]],
1608
+ };
1609
+ // Darker, lighter, subtler or more contrast asks for the color.
1610
+ if (
1611
+ /\b(darker|lighter|subtle\w*|contrast|stronger|fainter|softer|visible|invisible)\b/.test(
1612
+ c.text,
1613
+ )
1614
+ ) {
1615
+ const now = current('--color-border', c.mode ?? 'light');
1616
+ const more =
1617
+ /\b(darker|stronger|more contrast|visible)\b/.test(c.text) &&
1618
+ !/\binvisible\b/.test(c.text);
1619
+ const value = stronger(now, more ? 2 : 0.5, c.mode ?? 'light');
1620
+ return value
1621
+ ? {
1622
+ text: `the border color of the whole theme: --color-border (now ${now})`,
1623
+ options: [[set('--color-border', value, modeOf(c))]],
1624
+ }
1625
+ : null;
1626
+ }
1627
+ if (c.lengths[0] || c.dir)
1628
+ return {
1629
+ text: 'the border width of the whole theme: --border-width',
1630
+ options: [
1631
+ [
1632
+ set(
1633
+ '--border-width',
1634
+ c.lengths[0] ?? (c.dir === 'less' ? '1px' : '2px'),
1635
+ ),
1636
+ ],
1637
+ ],
1638
+ };
1639
+ return null;
1640
+ }
1641
+ if (/\brings?\b/.test(c.text)) {
1642
+ const color = colorFor(c, 'fill');
1643
+ const w = c.lengths[0];
1644
+ const fl = {...f, state: f.state ?? 'focus-visible'};
1645
+ /** @type {Step[]} */
1646
+ const steps = [
1647
+ ...(color ? [set('outline-color', color, fl)] : []),
1648
+ ...(w ? [set('outline-width', w, fl)] : []),
1649
+ ...(c.neg ? [set('outline', 'none', fl)] : []),
1650
+ ];
1651
+ return steps.length
1652
+ ? {
1653
+ text: `the focus ring${where}: the outline`,
1654
+ options: [steps],
1655
+ sequence: steps.length > 1,
1656
+ }
1657
+ : null;
1658
+ }
1659
+ if (c.neg)
1660
+ return {
1661
+ text: `no ${outline ? 'outline' : 'border'}${where}`,
1662
+ options: [
1663
+ ...undo([
1664
+ 'border',
1665
+ 'border-color',
1666
+ 'border-width',
1667
+ 'border-style',
1668
+ 'outline',
1669
+ ]),
1670
+ [set('border', 'none', f)],
1671
+ ...(outline ? [[set('outline', 'none', f)]] : []),
1672
+ ],
1673
+ };
1674
+ const color = colorFor(c, 'fill');
1675
+ const width =
1676
+ c.lengths[0] ??
1677
+ (/\b(thick(er)?)\b/.test(c.text) || c.dir === 'more'
1678
+ ? '2px'
1679
+ : /\bthin(ner)?\b/.test(c.text) || c.dir === 'less'
1680
+ ? '1px'
1681
+ : null);
1682
+ const style = /\b(dashed|dotted|double)\b/.exec(c.text)?.[1] ?? null;
1683
+ const side = /\b(top|bottom|left|right)\b/.exec(c.text)?.[1];
1684
+ const prop = side ? `border-${side}` : 'border';
1685
+ const own = C.MAP[one(on)]?.own ?? {};
1686
+ const hasBorder = 'border-style' in own || 'border-width' in own;
1687
+ if (hasBorder && !side) {
1688
+ /** @type {Step[][]} */
1689
+ const opts = [];
1690
+ if (color && !width && !style)
1691
+ opts.push([set('border-color', color, {...f, ...modeOf(c)})]);
1692
+ if (width && !color && !style)
1693
+ opts.push([set('border-width', width, f)]);
1694
+ if (style && !color && !width)
1695
+ opts.push([set('border-style', style, f)]);
1696
+ opts.push([
1697
+ set(
1698
+ prop,
1699
+ `${width ?? '1px'} ${style ?? 'solid'} ${color ?? 'var(--color-border)'}`,
1700
+ f,
1701
+ ),
1702
+ ]);
1703
+ return {text: `the border${where}`, options: opts};
1704
+ }
1705
+ return {
1706
+ text: `a border${where}: ${prop}`,
1707
+ options: [
1708
+ [
1709
+ set(
1710
+ prop,
1711
+ `${width ?? '1px'} ${style ?? 'solid'} ${color ?? 'var(--color-border)'}`,
1712
+ f,
1713
+ ),
1714
+ ],
1715
+ ],
1716
+ };
1717
+ }
1718
+ case 'spacing': {
1719
+ const px = c.lengths[0];
1720
+ const gap = /\b(gaps?|between)\b/.test(c.text);
1721
+ const value =
1722
+ /\b(dense|compact)\b/.test(c.text) && !c.dir
1723
+ ? 'compact'
1724
+ : c.neg && /\b(padding|space|gap|margin)\b/.test(c.text)
1725
+ ? null
1726
+ : /\b(cramped|crowded|airy|spacious|roomy)\b/.test(c.text) ||
1727
+ c.dir === 'more'
1728
+ ? 'more'
1729
+ : c.dir === 'less' || /\b(dense|compact|tight)\b/.test(c.text)
1730
+ ? 'less'
1731
+ : 'more';
1732
+ if (!on)
1733
+ return value
1734
+ ? {
1735
+ text: 'room in the whole theme: the spacing dial (padding, gaps and control heights together)',
1736
+ options: [[set('spacing', value)]],
1737
+ }
1738
+ : null;
1739
+ if (px) {
1740
+ const box = boxIn(c.text) ?? px;
1741
+ return {
1742
+ text: `${gap ? 'the gap' : 'padding'}${where}: ${box}`,
1743
+ options: [[set(gap ? 'gap' : 'padding', box, f)]],
1744
+ };
1745
+ }
1746
+ if (!value)
1747
+ return {
1748
+ text: `no padding${where}`,
1749
+ options: [[set('padding', '0px', f)]],
1750
+ };
1751
+ return {
1752
+ text: `room inside ${on}: spacing ${value} (padding, gaps and heights inside it)`,
1753
+ options: [[set('spacing', value, {on})]],
1754
+ };
1755
+ }
1756
+ case 'tracking': {
1757
+ const tight = /\b(tight(er)?|narrow(er)?|less|condensed)\b/.test(
1758
+ c.text,
1759
+ );
1760
+ const typedTrack = c.lengths.find(l => /em$/.test(l)) ?? c.lengths[0];
1761
+ const value = typedTrack ?? (tight ? '-0.02em' : '0.04em');
1762
+ if (!on || on === 'heading')
1763
+ return {
1764
+ text: `letter spacing${where}`,
1765
+ options: [
1766
+ ...(on ? [[set('letter-spacing', value, f)]] : []),
1767
+ ...(typedTrack
1768
+ ? []
1769
+ : [[set('headings', tight ? 'tight' : 'wide')]]),
1770
+ ],
1771
+ };
1772
+ return {
1773
+ text: `letter spacing${where}`,
1774
+ options: [[set('letter-spacing', value, f)]],
1775
+ };
1776
+ }
1777
+ case 'weight': {
1778
+ const typedW = weightIn(c);
1779
+ const light =
1780
+ /\b(light(er)?|thin(ner)?)\b/.test(c.text) ||
1781
+ (c.dir === 'less' && !c.neg);
1782
+ const value =
1783
+ typedW ??
1784
+ (c.neg
1785
+ ? '400'
1786
+ : light
1787
+ ? /\btoo /.test(c.text)
1788
+ ? '400'
1789
+ : '300'
1790
+ : '700');
1791
+ const rung = Object.entries(HEADING_WEIGHTS).find(
1792
+ ([, v]) => v === value,
1793
+ )?.[0];
1794
+ if (
1795
+ (!on && /\b(headings?|titles?)\b/.test(c.text)) ||
1796
+ (on === 'heading' && !f.when)
1797
+ )
1798
+ return {
1799
+ text: `${rung ?? value} headings: the headings dial, or font-weight on the part`,
1800
+ options: [
1801
+ ...(rung ? [[set('headings', rung)]] : []),
1802
+ [set('font-weight', value, {...f, on: 'heading'})],
1803
+ ],
1804
+ };
1805
+ if (!on)
1806
+ return {
1807
+ text: `body text weight: --text-body-weight (now ${current('--text-body-weight')})`,
1808
+ options: [[set('--text-body-weight', value)]],
1809
+ };
1810
+ return {
1811
+ text: `${rung ?? value} text${where}: font-weight ${value}`,
1812
+ options: [[set('font-weight', value, f)]],
1813
+ };
1814
+ }
1815
+ case 'family': {
1816
+ const font = fontIn(c.text, question);
1817
+ if (!font) return null;
1818
+ if (!on)
1819
+ return {
1820
+ text: `the typeface of the whole theme: font ${font}`,
1821
+ options: [[set('font', font)]],
1822
+ };
1823
+ if (on === 'heading')
1824
+ return {
1825
+ text: 'the heading font: font --on heading',
1826
+ options: [[set('font', font, {on: 'heading'})]],
1827
+ };
1828
+ const family = FONTS[font]?.[0] ?? OPEN_FONTS[font]?.family ?? font;
1829
+ return {
1830
+ text: `the font${where}: font-family`,
1831
+ options: [[set('font-family', family, f)]],
1832
+ };
1833
+ }
1834
+ case 'fontsize': {
1835
+ const px = c.lengths[0];
1836
+ const f2 = /\bmuch\b/.test(c.text) ? 1.5 : 1.25;
1837
+ const factor = c.dir === 'less' ? 1 / f2 : f2;
1838
+ if (!on)
1839
+ return {
1840
+ text: 'the base text size: text-size (every heading scales from it)',
1841
+ options: [
1842
+ [
1843
+ set(
1844
+ 'text-size',
1845
+ px
1846
+ ? String(parseFloat(px))
1847
+ : c.dir === 'less'
1848
+ ? 'less'
1849
+ : 'more',
1850
+ ),
1851
+ ],
1852
+ ],
1853
+ };
1854
+ if (on === 'heading' && !f.when && !px)
1855
+ return c.dir === 'less'
1856
+ ? {
1857
+ text: 'smaller steps between heading sizes: type compact (x1.15)',
1858
+ options: [[set('type', 'compact')]],
1859
+ }
1860
+ : {
1861
+ text: 'bigger steps between heading sizes: the type dial',
1862
+ options: [
1863
+ [
1864
+ set(
1865
+ 'type',
1866
+ /\bmuch\b/.test(c.text) ? 'display' : 'editorial',
1867
+ ),
1868
+ ],
1869
+ [set('text-size', 'more')],
1870
+ ],
1871
+ };
1872
+ const sizeTok =
1873
+ on === 'heading' && p?.level
1874
+ ? `--text-heading-${p.level}-size`
1875
+ : C.partReads(one(on), 'font').find(r =>
1876
+ r.props.includes('font-size'),
1877
+ )?.token;
1878
+ const now = sizeTok ? current(sizeTok) : null;
1879
+ const value = px ?? (now ? scaled(now, factor) : null);
1880
+ if (!value) return null;
1881
+ return {
1882
+ text: `the text size${where}: font-size ${value}${now && !px ? ` (now ${now})` : ''}`,
1883
+ options: [
1884
+ [set('font-size', value, f)],
1885
+ ...(sizeTok && on === 'heading' ? [[set(sizeTok, value)]] : []),
1886
+ ],
1887
+ };
1888
+ }
1889
+ case 'case': {
1890
+ const value = c.neg
1891
+ ? 'none'
1892
+ : /\blower/.test(c.text)
1893
+ ? 'lowercase'
1894
+ : /\bcapitali/.test(c.text)
1895
+ ? 'capitalize'
1896
+ : 'uppercase';
1897
+ if (!on) return null;
1898
+ return {
1899
+ text: `${value} text${where}: text-transform`,
1900
+ options: [
1901
+ [set('text-transform', value, f)],
1902
+ ...(on === 'button' && value === 'uppercase'
1903
+ ? [[set('buttons', 'caps')]]
1904
+ : []),
1905
+ ],
1906
+ };
1907
+ }
1908
+ case 'italic':
1909
+ return on
1910
+ ? {
1911
+ text: `italic text${where}: font-style`,
1912
+ options: [[set('font-style', c.neg ? 'normal' : 'italic', f)]],
1913
+ }
1914
+ : null;
1915
+ case 'opacity': {
1916
+ const pct = /\b(\d{1,3})%/.exec(c.text)?.[1];
1917
+ if (pct && on)
1918
+ return Number(pct) > 100
1919
+ ? {text: `opacity runs from 0% to 100%, not ${pct}%`, options: []}
1920
+ : {
1921
+ text: `opacity${where}: ${pct}%`,
1922
+ options: [[set('opacity', String(Number(pct) / 100), f)]],
1923
+ };
1924
+ return on
1925
+ ? {
1926
+ text: `${c.neg || f.state === 'disabled' ? 'less faded' : 'more see-through'}${where}: opacity`,
1927
+ options: [
1928
+ [
1929
+ set(
1930
+ 'opacity',
1931
+ c.neg ||
1932
+ f.state === 'disabled' ||
1933
+ /\btoo faded\b/.test(c.text)
1934
+ ? '0.8'
1935
+ : '0.6',
1936
+ f,
1937
+ ),
1938
+ ],
1939
+ ],
1940
+ }
1941
+ : null;
1942
+ }
1943
+ case 'scale':
1944
+ return on
1945
+ ? {
1946
+ text: `${on} scales${where}: transform`,
1947
+ options: [
1948
+ [
1949
+ set(
1950
+ 'transform',
1951
+ /\b(up|grows?)\b/.test(c.text)
1952
+ ? 'scale(1.03)'
1953
+ : 'scale(0.97)',
1954
+ f,
1955
+ ),
1956
+ ],
1957
+ ],
1958
+ }
1959
+ : null;
1960
+ case 'size': {
1961
+ if (!on) return null;
1962
+ const tall = tallIn(c.text);
1963
+ if (tall)
1964
+ return {
1965
+ text: `the height${where}: min-height ${tall}`,
1966
+ options: [[set('min-height', tall, f)], [set('height', tall, f)]],
1967
+ };
1968
+ if (on === 'progress-bar-fill' || on === 'progress-bar-track')
1969
+ return {
1970
+ text: 'the progress bar thickness: the height of its track',
1971
+ options: [
1972
+ [
1973
+ set(
1974
+ 'height',
1975
+ c.lengths[0] ??
1976
+ (c.dir === 'less' || /\bthin/.test(c.text) ? '2px' : '8px'),
1977
+ {on: 'progress-bar-track'},
1978
+ ),
1979
+ ],
1980
+ ],
1981
+ };
1982
+ if (/\b(wider|narrower|width)\b/.test(c.text)) {
1983
+ const w =
1984
+ c.lengths[0] ??
1985
+ (/\bnarrower\b/.test(c.text) || c.dir === 'less'
1986
+ ? '400px'
1987
+ : '720px');
1988
+ return {
1989
+ text: `the width${where}`,
1990
+ options: [
1991
+ [set('width', `min(${w}, 100%)`, f)],
1992
+ [set('max-width', w, f)],
1993
+ ],
1994
+ };
1995
+ }
1996
+ if (on === 'tab-indicator')
1997
+ return {
1998
+ text: 'the tab underline height',
1999
+ options: [
2000
+ [
2001
+ set(
2002
+ 'height',
2003
+ c.lengths[0] ?? (c.dir === 'less' ? '1px' : '3px'),
2004
+ f,
2005
+ ),
2006
+ ],
2007
+ ],
2008
+ };
2009
+ return {
2010
+ text: `${c.dir === 'less' ? 'smaller' : 'bigger'} ${on}: spacing ${c.dir === 'less' ? 'less' : 'more'} --on ${on} sets its padding and control height`,
2011
+ options: [
2012
+ [set('spacing', c.dir === 'less' ? 'less' : 'more', {on})],
2013
+ ...(c.lengths[0] ? [[set('min-height', c.lengths[0], f)]] : []),
2014
+ ],
2015
+ };
2016
+ }
2017
+ case 'text': {
2018
+ const color = colorFor(c, 'text');
2019
+ const tok = /\bsecondary\b/.test(c.text)
2020
+ ? '--color-text-secondary'
2021
+ : '--color-text-primary';
2022
+ if (!on) {
2023
+ const now = current(tok, c.mode ?? 'light');
2024
+ const darker =
2025
+ /\b(darker|too light|can'?t read|hard to read|unreadable|more contrast)\b/.test(
2026
+ c.text,
2027
+ );
2028
+ // "never use pure black": a near color that is not it.
2029
+ const avoid = c.neg && color;
2030
+ const value =
2031
+ (avoid
2032
+ ? (parseColor(color)?.reduce((x, y) => x + y, 0) ?? 0) < 384
2033
+ ? '#1f2937'
2034
+ : '#f9fafb'
2035
+ : color) ??
2036
+ (darker
2037
+ ? shift(now, c.mode === 'dark' ? 0.25 : -0.3)
2038
+ : /\b(less bright|dimmer|softer|lighter)\b/.test(c.text)
2039
+ ? shift(now, c.mode === 'dark' ? -0.15 : 0.25)
2040
+ : null);
2041
+ if (!value) return null;
2042
+ return {
2043
+ text: `${tok === '--color-text-secondary' ? 'secondary' : 'main'} text color${c.mode && modal ? ` in ${c.mode} mode` : ''}: ${tok} (now ${now})`,
2044
+ options: [[set(tok, value, modeOf(c))]],
2045
+ };
2046
+ }
2047
+ if (!color) return null;
2048
+ return {
2049
+ text: `text color${where}: color`,
2050
+ options: [[set('color', color, {...f, ...modeOf(c)})]],
2051
+ };
2052
+ }
2053
+ case 'background': {
2054
+ if (/\bstripe[sd]?\b|\bstriped\b|\bzebra\b/.test(c.text))
2055
+ return {
2056
+ text: 'striped rows need a style on every other row, and set has no condition for that; a row background colors every row',
2057
+ options: [],
2058
+ };
2059
+ const design = /\bglossy\b/.test(c.text)
2060
+ ? 'glossy'
2061
+ : /\bgradient\b/.test(c.text)
2062
+ ? 'gradient'
2063
+ : null;
2064
+ if (c.neg && on) {
2065
+ const undos = undo([
2066
+ 'background',
2067
+ 'background-image',
2068
+ 'background-color',
2069
+ ]);
2070
+ return undos.length
2071
+ ? {
2072
+ text: `take back the ${design ?? 'background'} this theme sets${where}`,
2073
+ options: undos,
2074
+ }
2075
+ : {
2076
+ text: `${on} has no ${design ?? 'background'} this theme sets, so there is nothing to remove`,
2077
+ options: [],
2078
+ lookup: `${HOW} ${on}`,
2079
+ };
2080
+ }
2081
+ if (!on && c.neg && /\bgradients?\b/.test(c.text)) {
2082
+ const grads = env.data.settings.filter(x =>
2083
+ /gradient\(/.test(x.value),
2084
+ );
2085
+ return grads.length
2086
+ ? {
2087
+ text: 'take back every gradient this theme sets',
2088
+ options: [
2089
+ grads.map(
2090
+ x =>
2091
+ /** @type {Step} */ ({
2092
+ verb: 'undo',
2093
+ thing: x.thing,
2094
+ ...(x.on ? {on: x.on} : {}),
2095
+ ...(x.when ? {when: x.when} : {}),
2096
+ ...(x.state ? {state: x.state} : {}),
2097
+ ...(x.mode ? {mode: x.mode} : {}),
2098
+ }),
2099
+ ),
2100
+ ],
2101
+ sequence: grads.length > 1,
2102
+ }
2103
+ : {
2104
+ text: `${env.slug} sets no gradient, so there is nothing to remove`,
2105
+ options: [],
2106
+ };
2107
+ }
2108
+ if (!on) {
2109
+ const now = current('--color-background-body', c.mode ?? 'light');
2110
+ const color =
2111
+ colorFor(c, 'fill') ??
2112
+ (c.dir
2113
+ ? shift(now, /\blight(er)?|brighter\b/.test(c.text) ? 0.5 : -0.06)
2114
+ : null);
2115
+ if (!color) return null;
2116
+ return {
2117
+ text: `the page background: --color-background-body${c.mode && modal ? ` in ${c.mode} mode` : ''}`,
2118
+ options: [[set('--color-background-body', color, modeOf(c))]],
2119
+ };
2120
+ }
2121
+ if (c.decl.background || c.decl['background-color'])
2122
+ return {
2123
+ text: `the background you wrote${where}`,
2124
+ options: [
2125
+ [
2126
+ set(
2127
+ 'background',
2128
+ c.decl.background ?? c.decl['background-color'],
2129
+ f,
2130
+ ),
2131
+ ],
2132
+ ],
2133
+ };
2134
+ if (design)
2135
+ return {
2136
+ text: `a ${design} fill${where}`,
2137
+ options: [
2138
+ [set('background', DESIGN[design].replace(/^"|"$/g, ''), f)],
2139
+ ],
2140
+ };
2141
+ /** @type {string | null} */
2142
+ let color =
2143
+ (/\btransparent\b/.test(c.text) ? 'transparent' : null) ??
2144
+ colorFor(c, 'fill') ??
2145
+ (c.dir ? null : toneIn(c.text));
2146
+ if (on === 'tab-indicator' && color && c.lengths[0])
2147
+ return {
2148
+ text: `the tab underline${where}: its color and height`,
2149
+ options: [
2150
+ [set('background', color, f), set('height', c.lengths[0], {on})],
2151
+ ],
2152
+ sequence: true,
2153
+ };
2154
+ if (!color && c.dir) {
2155
+ const tok =
2156
+ C.partReads(one(on), 'background').find(r => r.when.includes(''))
2157
+ ?.token ??
2158
+ (FAMILIES.containers.includes(one(on))
2159
+ ? '--color-background-card'
2160
+ : '--color-background-surface');
2161
+ const now = tok ? current(tok, c.mode ?? 'light') : null;
2162
+ const lighter = /\blight(er)?\b/.test(c.text);
2163
+ color = now ? shift(now, lighter ? 0.12 : -0.12) : null;
2164
+ if (color && f.state)
2165
+ return {
2166
+ text: `${lighter ? 'a lighter' : 'a darker'} background${where}`,
2167
+ options: [
2168
+ [set('filter', `brightness(${lighter ? 1.1 : 0.9})`, f)],
2169
+ [set('background-color', color, f)],
2170
+ ],
2171
+ };
2172
+ }
2173
+ if (!color && f.state === 'hover')
2174
+ return {
2175
+ text: `a slightly darker ${on}${where}`,
2176
+ options: [
2177
+ [
2178
+ set(
2179
+ 'filter',
2180
+ `brightness(${/\bdark/.test(c.text) ? 0.9 : 0.95})`,
2181
+ f,
2182
+ ),
2183
+ ],
2184
+ ],
2185
+ };
2186
+ if (!color) return null;
2187
+ return {
2188
+ text: `the background${where}${c.mode && modal ? ` in ${c.mode} mode` : ''}`,
2189
+ options: [[set('background', color, {...f, ...modeOf(c)})]],
2190
+ };
2191
+ }
2192
+ default:
2193
+ return null;
2194
+ }
2195
+ }
2196
+
2197
+ /**
2198
+ * A whole-theme answer for a clause that names no part or aspect: a
2199
+ * color the theme generates, vibrancy, the color modes.
2200
+ * @param {Clause} c
2201
+ * @param {string} [aspect]
2202
+ * @returns {Draft | null}
2203
+ */
2204
+ function wholeTheme(c, aspect) {
2205
+ if (aspect) return answerFor(c, null, aspect);
2206
+ const t = c.text;
2207
+ if (c.bad)
2208
+ return {
2209
+ text: `"${c.bad}" is not a color: a hex color has 3, 4, 6 or 8 digits after the #. Give the color again.`,
2210
+ options: [],
2211
+ };
2212
+ if (/\bswap\b/.test(t)) {
2213
+ const ROLE_TOKEN = /** @type {Record<string, string>} */ ({
2214
+ accent: '--color-accent',
2215
+ danger: '--color-error',
2216
+ success: '--color-success',
2217
+ warning: '--color-warning',
2218
+ info: '--color-info',
2219
+ });
2220
+ const named = Object.keys(ROLE_TOKEN).filter(r =>
2221
+ new RegExp(`\\b${r === 'danger' ? '(danger|error)' : r}\\b`).test(t),
2222
+ );
2223
+ if (named.length === 2) {
2224
+ const [x, y] = named;
2225
+ const cx = current(ROLE_TOKEN[x]);
2226
+ const cy = current(ROLE_TOKEN[y]);
2227
+ if (parseColor(cx) && parseColor(cy)) {
2228
+ seenAspect('colors');
2229
+ return {
2230
+ text: `${x} takes ${y}'s color (${cy}) and ${y} takes ${x}'s (${cx})`,
2231
+ options: [[set(x, cy), set(y, cx)]],
2232
+ sequence: true,
2233
+ };
2234
+ }
2235
+ }
2236
+ }
2237
+ if (/\b(more|higher|high|better) contrast\b|\bcontrast mode\b/.test(t)) {
2238
+ const sec = current('--color-text-secondary');
2239
+ const border = current('--color-border');
2240
+ /** @type {Step[]} */
2241
+ const steps = [];
2242
+ const darkerSec = shift(sec, -0.35);
2243
+ if (darkerSec) steps.push(set('--color-text-secondary', darkerSec));
2244
+ const strongBorder = stronger(border, 2.5, 'light');
2245
+ if (strongBorder) steps.push(set('--color-border', strongBorder));
2246
+ return {
2247
+ text: `more contrast: darker secondary text (now ${sec}) and stronger borders (now ${border}), in light mode`,
2248
+ options: [steps],
2249
+ sequence: steps.length > 1,
2250
+ };
2251
+ }
2252
+ if (/\b(apply|use|want|make it) (a )?dark (theme|look|ui)\b/.test(t))
2253
+ return {
2254
+ text:
2255
+ env.data.mode === 'both'
2256
+ ? `${env.slug} has a dark mode already, which the app shows when the system asks for it; for a theme that is always dark: mode dark-only`
2257
+ : 'a theme that is always dark: mode dark-only',
2258
+ options: [[set('mode', 'dark-only')]],
2259
+ };
2260
+ if (/\b(undo|revert|go back|take back)\b/.test(t))
2261
+ return {
2262
+ text: `undo ${env.slug} steps back one change; undo ${env.slug} <thing> removes one setting`,
2263
+ options: [],
2264
+ ...(env.exists ? {lookup: `${P} undo ${env.slug}`} : {}),
2265
+ };
2266
+ if (/\breset\b|\bstart over\b|\bback to (the )?defaults?\b/.test(t))
2267
+ return {
2268
+ text: `each undo ${env.slug} steps back one change; show ${env.slug} lists every setting, and undo ${env.slug} <thing> removes one`,
2269
+ options: [],
2270
+ ...(env.exists ? {lookup: `${P} show ${env.slug}`} : {}),
2271
+ };
2272
+ if (/\b(dark|light)\b/.test(t) && /\b(mode|theme|only)\b/.test(t))
2273
+ seenAspect('mode');
2274
+ if (/\bdark[- ]?(mode|theme)? only\b|\bonly dark\b|\bdark-only\b/.test(t))
2275
+ return {
2276
+ text: 'a theme with only a dark mode: mode dark-only',
2277
+ options: [[set('mode', 'dark-only')]],
2278
+ };
2279
+ if (
2280
+ /\blight[- ]?(mode|theme)? only\b|\bonly light\b|\blight-only\b/.test(t)
2281
+ )
2282
+ return {
2283
+ text: 'a theme with only a light mode: mode light-only',
2284
+ options: [[set('mode', 'light-only')]],
2285
+ };
2286
+ if (
2287
+ /\b(support|add|enable|want|need)\b.*\bdark\b|\bdark mode\b/.test(t) &&
2288
+ !c.colors.length &&
2289
+ !/\b(accent|text|background|colou?rs?)\b/.test(t)
2290
+ ) {
2291
+ if (env.data.mode === 'both')
2292
+ return {
2293
+ text: `${env.slug} has a dark mode already: every color it sets makes its dark shades too. The in-app preview switches between them.`,
2294
+ options: [],
2295
+ };
2296
+ return {
2297
+ text: 'light and dark modes both: mode both',
2298
+ options: [[set('mode', 'both')]],
2299
+ };
2300
+ }
2301
+ const vib =
2302
+ /\b(colou?rful|saturat\w*|desaturat\w*|vivid|vibran\w*|muted|dull|washed|pastel|intense|pop|punch\w*|gr[ae]yer)\b/.test(
2303
+ t,
2304
+ );
2305
+ if (vib) {
2306
+ seenAspect('colors');
2307
+ const less =
2308
+ /\b(less|desaturat\w*|muted|dull|washed|pastel|gr[ae]yer|calm\w*|softer)\b/.test(
2309
+ t,
2310
+ ) && !/\bmore\b/.test(t);
2311
+ const step = set('vibrancy', less ? 'less' : 'more');
2312
+ const colored = (/** @type {string} */ v) => !isGraySeed(seedOf(v));
2313
+ const hasColor = env.data.settings.some(
2314
+ x => PALETTE_DIALS.includes(x.thing) && colored(x.value),
2315
+ );
2316
+ const help =
2317
+ 'vibrancy sets how saturated every generated color is (0 is gray, 100 the most vivid, 50 the default)';
2318
+ if (hasColor)
2319
+ return {
2320
+ text: `${help}; ${less ? 'less' : 'more'} steps it by 10.`,
2321
+ options: [[step]],
2322
+ };
2323
+ if (less)
2324
+ return {
2325
+ text: `${help}, and every color ${env.slug} has is a gray, so there is no color to take out.`,
2326
+ options: [],
2327
+ lookup: `${HOW} colors`,
2328
+ };
2329
+ const now = parseColor(current('--color-accent'));
2330
+ if (now && colored(hex(now)))
2331
+ return {
2332
+ text: `${help}. It works once the theme sets a color, so the first command sets accent to the color it has now.`,
2333
+ options: [[set('accent', hex(now)), step]],
2334
+ sequence: true,
2335
+ };
2336
+ // No color to saturate, and none was asked for: never pick one.
2337
+ return {
2338
+ text: `${help}, and every color ${env.slug} has is a gray, so there is nothing to saturate yet. Set a color first: how accent shows how.`,
2339
+ options: [],
2340
+ lookup: `${HOW} accent`,
2341
+ };
2342
+ }
2343
+ if (
2344
+ /\b(shades?|swatch(es)?|ramps?|all (the )?colou?rs|every colou?r|see (the )?colou?rs)\b/.test(
2345
+ t,
2346
+ )
2347
+ ) {
2348
+ seenAspect('colors');
2349
+ return {
2350
+ text: 'Every shade of every color, light and dark, with the tokens that use each, is on the Colors page of the in-app preview. It changes with every set.',
2351
+ options: [],
2352
+ ...(env.exists
2353
+ ? {
2354
+ lookup: `astryx experimental theme preview add --theme ${env.slug}`,
2355
+ }
2356
+ : {}),
2357
+ };
2358
+ }
2359
+ if (
2360
+ /\b(exact|one token|single token|specific token|override)\b/.test(t) &&
2361
+ /\bcolou?rs?\b/.test(t)
2362
+ ) {
2363
+ seenAspect('colors');
2364
+ return {
2365
+ text: 'An exact color for one token: set the token itself. It always wins over the generated colors, whatever order you set them in. Add --mode light|dark for one mode, or --on <part> for one part.',
2366
+ options: [
2367
+ [set('--color-accent', '#7c3aed')],
2368
+ ...(modal
2369
+ ? [[set('--color-text-primary', '#111827', {mode: 'light'})]]
2370
+ : []),
2371
+ ],
2372
+ lookup: `${HOW} --list tokens`,
2373
+ };
2374
+ }
2375
+ if (/\bstatus(es)? colou?rs?\b|\bstatus\b/.test(t) && !c.colors.length) {
2376
+ seenAspect('colors');
2377
+ return {
2378
+ text: 'Status colors are four settings: danger (errors and destructive actions: the --color-error tokens), success, warning and info. Each one makes its light and dark shades from one color: set <color> <value>. how <color> shows each.',
2379
+ options: [],
2380
+ lookup: `${HOW} danger`,
2381
+ };
2382
+ }
2383
+ if (
2384
+ /\bdark\b/.test(t) &&
2385
+ /\bcolou?rs?\b/.test(t) &&
2386
+ !c.colors.length &&
2387
+ !ROLE_WORDS.test(t)
2388
+ ) {
2389
+ seenAspect('colors');
2390
+ return {
2391
+ text: 'Each color you set makes its dark shades too, so dark mode follows by itself. For one token in dark mode only, set it with --mode dark; for a theme with only a dark mode, set mode dark-only.',
2392
+ options: [],
2393
+ lookup: `${HOW} colors`,
2394
+ };
2395
+ }
2396
+ // A color the theme generates, named by its role.
2397
+ const roles = /** @type {Array<[RegExp, string, string]>} */ ([
2398
+ [
2399
+ /\b(accent|brand|primary colou?r|main colou?r|key colou?r)\b|\bprimary\s*:?\s*(?=#|rgb|hsl|oklch)/,
2400
+ 'accent',
2401
+ '--color-accent',
2402
+ ],
2403
+ [/\b(errors?|danger|destructive)\b/, 'danger', '--color-error'],
2404
+ [/\b(success|positive)\b/, 'success', '--color-success'],
2405
+ [/\b(warnings?|caution)\b/, 'warning', '--color-warning'],
2406
+ [/\b(info|notices?)\b/, 'info', '--color-info'],
2407
+ [
2408
+ /\b(neutrals?|gr[ae]ys?|warm(er)?|cool(er)?)\b/,
2409
+ 'neutral',
2410
+ '--color-neutral',
2411
+ ],
2412
+ ]);
2413
+ const role = roles.find(([re]) => re.test(t));
2414
+ if (role) {
2415
+ seenAspect('colors');
2416
+ const [, dial, token] = role;
2417
+ let color =
2418
+ c.colors.find(
2419
+ x =>
2420
+ !(
2421
+ dial === 'neutral' &&
2422
+ ['#9ca3af', '#e5e7eb', '#374151', '#f3f4f6'].includes(x)
2423
+ ),
2424
+ ) ?? null;
2425
+ if (dial === 'neutral' && !color)
2426
+ color = /\bwarm(er)?\b/.test(t)
2427
+ ? '#78716c'
2428
+ : /\bcool(er)?\b/.test(t)
2429
+ ? '#64748b'
2430
+ : null;
2431
+ // "make the error red darker": the hue names the color; the change is darker.
2432
+ const NATURAL = /** @type {Record<string, string>} */ ({
2433
+ danger: HUES.red,
2434
+ success: HUES.green,
2435
+ warning: HUES.yellow,
2436
+ info: HUES.blue,
2437
+ });
2438
+ if (c.dir && color && (color === NATURAL[dial] || color === HUES.amber))
2439
+ color = null;
2440
+ if (!color && c.dir) {
2441
+ const now = current(token, c.mode ?? 'light');
2442
+ const lighter = /\b(light(er)?|brighter|paler)\b/.test(t);
2443
+ color = shift(now, lighter ? 0.2 : -0.2);
2444
+ if (color && c.mode && modal)
2445
+ return {
2446
+ text: `${dial} in ${c.mode} mode: the exact token ${token} (now ${now}), only in ${c.mode} mode`,
2447
+ options: [[set(token, color, modeOf(c))]],
2448
+ };
2449
+ }
2450
+ // No color given: say how, and never pick one.
2451
+ if (!color)
2452
+ return {
2453
+ text: `${DIALS[dial].help} Give the color: set ${env.slug} ${dial} <color>.`,
2454
+ options: [],
2455
+ lookup: `${HOW} ${dial}`,
2456
+ };
2457
+ if (c.mode && modal)
2458
+ return {
2459
+ text: `${dial} in ${c.mode} mode only: the exact token ${token}`,
2460
+ options: [[set(token, color, modeOf(c))]],
2461
+ };
2462
+ return {
2463
+ text: `${dial}: the editor makes its light and dark shades from ${color}`,
2464
+ options: [[set(dial, color)], [set(token, color)]],
2465
+ };
2466
+ }
2467
+ return null;
2468
+ }
2469
+
2470
+ /**
2471
+ * The tokens a part reads for an aspect, for the answer's text.
2472
+ * @param {string} on @param {string} a
2473
+ */
2474
+ function readsNote(on, a) {
2475
+ const group =
2476
+ /** @type {Record<string, string>} */ ({
2477
+ weight: 'font',
2478
+ family: 'font',
2479
+ fontsize: 'font',
2480
+ tracking: 'font',
2481
+ case: 'font',
2482
+ italic: 'font',
2483
+ })[a] ?? a;
2484
+ if (
2485
+ !C.MAP[one(on)] ||
2486
+ ![
2487
+ 'text',
2488
+ 'background',
2489
+ 'border',
2490
+ 'corners',
2491
+ 'shadow',
2492
+ 'spacing',
2493
+ 'font',
2494
+ 'size',
2495
+ ].includes(group)
2496
+ )
2497
+ return '';
2498
+ // Reads that always apply first; partReads sorts them so.
2499
+ const toks = C.partReads(one(on), group)
2500
+ .map(r => r.token)
2501
+ .slice(0, 4);
2502
+ return toks.length ? `; ${one(on)} reads ${toks.join(', ')} for it` : '';
2503
+ }
2504
+
2505
+ /** @type {Draft[]} */
2506
+ const result = [];
2507
+ // Several changes in one question: one answer that runs them all first,
2508
+ // with repeats dropped and a step dropped when a later one replaces it.
2509
+ // Two clauses that set one thing two ways contradict each other: they are
2510
+ // offered as choices, not run in turn.
2511
+ /** @param {Step} st */
2512
+ const idOf = st =>
2513
+ [
2514
+ st.verb,
2515
+ st.thing,
2516
+ st.on ?? '',
2517
+ st.when ?? '',
2518
+ st.state ?? '',
2519
+ st.mode ?? '',
2520
+ ].join('|');
2521
+ /** @type {Map<string, {step: Step, clause: Clause}>} */
2522
+ const last = new Map();
2523
+ /** @type {Array<[Step, Step]>} */
2524
+ const clashes = [];
2525
+ for (const {clause, steps} of tops)
2526
+ for (const st of steps) {
2527
+ const prior = last.get(idOf(st));
2528
+ if (prior && prior.clause !== clause && prior.step.value !== st.value)
2529
+ clashes.push([prior.step, st]);
2530
+ last.delete(idOf(st));
2531
+ last.set(idOf(st), {step: st, clause});
2532
+ }
2533
+ const MAX_STEPS = 12;
2534
+ if (clashes.length) {
2535
+ const [a, b] = clashes[0];
2536
+ result.push({
2537
+ text: `the question asks for ${a.thing} ${a.value} and ${b.thing} ${b.value}${a.on ? ` on ${a.on}` : ''}, which contradict each other; pick one`,
2538
+ options: [[a], [b]],
2539
+ });
2540
+ } else if (last.size > 1 && clauses.length > 1) {
2541
+ const all = [...last.values()].map(x => x.step);
2542
+ result.push({
2543
+ text:
2544
+ all.length > MAX_STEPS
2545
+ ? `the first ${MAX_STEPS} of ${all.length} changes, in order; ask again for the rest`
2546
+ : 'all of it, in order',
2547
+ options: [all.slice(0, MAX_STEPS)],
2548
+ sequence: true,
2549
+ });
2550
+ }
2551
+ result.push(...drafts.slice(0, clashes.length ? 0 : undefined));
2552
+ return {parts: partsSeen, aspects: aspectsSeen, drafts: result};
2553
+ }
2554
+
2555
+ /**
2556
+ * A font a clause names: a preset, an open font, or a family written with
2557
+ * capitals in the question.
2558
+ * @param {string} c the clause, lower-case
2559
+ * @param {string} question the question as typed
2560
+ */
2561
+ function fontIn(c, question) {
2562
+ if (/\bmono(space|spaced)?\b/.test(c)) return 'mono';
2563
+ if (/\bsans(-serif)?\b/.test(c)) return 'system';
2564
+ if (/\bserif\b/.test(c)) return 'serif';
2565
+ for (const k of [...Object.keys(OPEN_FONTS), ...Object.keys(FONTS)]) {
2566
+ const words = k.replace(/-/g, ' ');
2567
+ if (new RegExp(`\\b${words}\\b`).test(c)) return k;
2568
+ }
2569
+ const typed =
2570
+ /\b(?:use|font|typeface)\s+["']?([A-Z][\w-]*(?: [A-Z][\w-]*)?)["']?/.exec(
2571
+ question,
2572
+ )?.[1];
2573
+ return typed ?? null;
2574
+ }