@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
@@ -3,7 +3,9 @@
3
3
  /**
4
4
  * @file The lookup behind `astryx experimental theme editor how`: a part, a
5
5
  * group, a setting, an aspect, a plain-words question, a PNG picture's
6
- * colors, or a list of what a change can name.
6
+ * colors, or a list of what a change can name. Every command it suggests is
7
+ * written for the user's theme, safe to paste into a shell, and checked as
8
+ * `set` checks it, so it is accepted and changes the theme.
7
9
  *
8
10
  * @position api/theme-edit — imported only by _adapter.mjs
9
11
  */
@@ -14,22 +16,25 @@ import {AstryxError} from '../error.mjs';
14
16
  import {CSS_PROPERTIES} from './_css-properties.mjs';
15
17
  import {
16
18
  AUTO_SPREAD,
19
+ COLOR_PROPS,
17
20
  COMMON_PROPERTIES,
21
+ COMMON_STATES,
18
22
  DIALS,
19
23
  FAMILIES,
20
24
  GROUPS,
21
25
  HOW,
22
- INTENTS,
23
26
  P,
24
- PART_WORDS,
25
27
  familyOf,
26
28
  } from './_tables.mjs';
27
29
  import {colorsAt, decodePng, mainColors} from './_png.mjs';
28
- import {nearest, refuse} from './_settings.mjs';
29
- import {ASPECTS, answerHow, wholeThemeTokens} from './_check.mjs';
30
+ import {loadTheme, nearest, refuse} from './_settings.mjs';
31
+ import {ASPECTS} from './_check.mjs';
30
32
  import {MODAL} from './_compiler.mjs';
31
33
  import {PALETTE_DIALS, mappingRows, paletteFiles} from './_palette.mjs';
32
34
  import {requireProject, context} from './_context.mjs';
35
+ import {checked, exampleStep, howTheme, render} from './_how-commands.mjs';
36
+ import {draftAnswer} from './_how-question.mjs';
37
+ import {getCliInvocation} from '../../foundation/env/package-manager.mjs';
33
38
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
34
39
 
35
40
  const E = ERROR_CODES;
@@ -37,31 +42,115 @@ const E = ERROR_CODES;
37
42
  /** What `how --list` takes. */
38
43
  const HOW_LISTS = ['dials', 'tokens', 'parts', 'groups', 'properties'];
39
44
 
45
+ /** The most points one `--at` reads. */
46
+ const MAX_POINTS = 1000;
47
+
40
48
  /** The in-app preview, whose Colors page shows every shade. */
41
49
  const PREVIEW = 'astryx experimental theme preview';
42
50
 
51
+ /** Picture formats people try that are not PNG, by their first bytes. */
52
+ const OTHER_FORMATS = /** @type {Array<[string, number[]]>} */ ([
53
+ ['JPEG', [0xff, 0xd8, 0xff]],
54
+ ['GIF', [0x47, 0x49, 0x46, 0x38]],
55
+ ['WebP', [0x52, 0x49, 0x46, 0x46]],
56
+ ['BMP', [0x42, 0x4d]],
57
+ ]);
58
+
59
+ /** File names that are pictures, whatever their format. */
60
+ const PICTURE_NAME = /\.(png|jpe?g|gif|webp|bmp|avif|heic|tiff?|svg)$/i;
61
+
62
+ /**
63
+ * Whether a subject names a picture: a picture file name, or a file that
64
+ * exists.
65
+ * @param {string} subject
66
+ * @param {string} cwd
67
+ */
68
+ export function isPicture(subject, cwd) {
69
+ if (!subject || /\s/.test(subject.trim())) return false;
70
+ if (PICTURE_NAME.test(subject)) return true;
71
+ try {
72
+ return fs.statSync(path.resolve(cwd, subject)).isFile();
73
+ } catch {
74
+ return false;
75
+ }
76
+ }
77
+
43
78
  /**
44
79
  * Explain anything a theme change can name, or answer a question about one:
45
- * a part (what it reads for each aspect, its variants, states and the parts
46
- * inside it), a group (its members), a setting (a dial's rungs, a token's
47
- * type and readers, a CSS property), an aspect (text, corners...: the
48
- * whole-theme tokens and dial), `colors` (how the theme's colors are made),
49
- * a plain-words question (exact commands), a PNG picture (its main colors,
50
- * or the color at points), or with `list` a list of dials, tokens, parts,
51
- * groups or CSS properties.
80
+ * a part (what it reads for each aspect, under which `--when` or `--state`,
81
+ * its variants, states and the parts inside it), a group (its members), a
82
+ * setting (a dial's rungs, a token's type and readers, a CSS property), an
83
+ * aspect (text, corners...: the whole-theme tokens and dial), `colors` (how
84
+ * the theme's colors are made), a plain-words question (exact commands), a
85
+ * PNG picture (its main colors, or the color at points), or with `list` a
86
+ * list of dials, tokens, parts, groups or CSS properties.
52
87
  * @experimental
53
88
  * @param {string} subject a part, group, setting, aspect, question, or PNG file; with `list`, a filter
54
89
  * @param {import('./theme-edit.type.mjs').ThemeEditHowOptions} [options]
55
90
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditHowResponse>}
56
91
  */
57
92
  export async function themeEditHow(subject, options = {}) {
58
- const {cwd = process.cwd(), list, at = [], count} = options;
93
+ const {cwd = process.cwd()} = options;
59
94
  requireProject(cwd);
95
+ try {
96
+ const data = await answer(subject, options, cwd);
97
+ return {type: 'themeEdit.how', data: withPrefix(data, cwd)};
98
+ } catch (e) {
99
+ // A refusal's commands start the same way as an answer's.
100
+ if (e instanceof AstryxError && e.suggestions)
101
+ e.suggestions = withPrefix(e.suggestions, cwd);
102
+ throw e;
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Every command in the answer starts the way this project runs the CLI,
108
+ * the same in JSON as in text.
109
+ * @template T
110
+ * @param {T} value
111
+ * @param {string} cwd
112
+ * @returns {T}
113
+ */
114
+ function withPrefix(value, cwd) {
115
+ const stem = `${getCliInvocation(cwd)} experimental theme`;
116
+ if (stem === 'astryx experimental theme') return value;
117
+ /** @param {any} v @returns {any} */
118
+ const walk = v =>
119
+ typeof v === 'string'
120
+ ? v.split('astryx experimental theme').join(stem)
121
+ : Array.isArray(v)
122
+ ? v.map(walk)
123
+ : v && typeof v === 'object'
124
+ ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x)]))
125
+ : v;
126
+ return walk(value);
127
+ }
128
+
129
+ /**
130
+ * @param {string} subject
131
+ * @param {import('./theme-edit.type.mjs').ThemeEditHowOptions} options
132
+ * @param {string} cwd
133
+ * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditHowResponse['data']>}
134
+ */
135
+ async function answer(subject, options, cwd) {
136
+ const {list, at = [], count} = options;
60
137
  const t = (subject ?? '').trim();
61
- if (list === '')
62
- return {
63
- type: 'themeEdit.how',
64
- data: {
138
+ // --theme names a theme whatever the subject, so a bad one is refused
139
+ // for a picture and a list too.
140
+ if (options.theme === '')
141
+ refuse(E.ERR_INVALID_ARGUMENT, '--theme was given no name.', {
142
+ run: [`${HOW} ${t ? JSON.stringify(t) : 'card'}`],
143
+ });
144
+ if (options.theme != null) loadTheme(cwd, options.theme);
145
+ if (list != null) {
146
+ if (at.length)
147
+ refuse(
148
+ E.ERR_INVALID_ARGUMENT,
149
+ '--at reads a picture; --list lists names, so drop one of them.',
150
+ );
151
+ const kind = listKind(list);
152
+ if (kind === 'kinds')
153
+ return {
65
154
  kind: 'list',
66
155
  subject: t,
67
156
  list: 'kinds',
@@ -69,24 +158,11 @@ export async function themeEditHow(subject, options = {}) {
69
158
  name,
70
159
  example: `${HOW} --list ${name}`,
71
160
  })),
72
- },
73
- };
74
- if (list != null) {
75
- if (at.length)
76
- refuse(
77
- E.ERR_INVALID_ARGUMENT,
78
- '--at reads a picture; --list lists names, so drop one of them.',
79
- );
80
- return {
81
- type: 'themeEdit.how',
82
- data: {kind: 'list', subject: t, ...(await listItems(list, t, cwd))},
83
- };
161
+ };
162
+ return {kind: 'list', subject: t, ...(await listItems(kind, t, cwd))};
84
163
  }
85
- if (/\.png$/i.test(t))
86
- return {
87
- type: 'themeEdit.how',
88
- data: {kind: 'picture', subject: t, ...pictureColors(t, cwd, at, count)},
89
- };
164
+ if (isPicture(t, cwd))
165
+ return {kind: 'picture', subject: t, ...pictureColors(t, cwd, at, count)};
90
166
  if (at.length)
91
167
  refuse(
92
168
  E.ERR_INVALID_ARGUMENT,
@@ -95,7 +171,7 @@ export async function themeEditHow(subject, options = {}) {
95
171
  );
96
172
  if (count != null)
97
173
  refuse(E.ERR_INVALID_ARGUMENT, 'A count applies only to a picture.', {
98
- run: [`${HOW} picture.png --at "40,20;300,180"`],
174
+ run: [`${HOW} picture.png 5`],
99
175
  });
100
176
  if (!t) {
101
177
  refuse(
@@ -112,165 +188,503 @@ export async function themeEditHow(subject, options = {}) {
112
188
  }
113
189
  const ctx = await context(cwd);
114
190
  const {C} = ctx;
191
+ const env = await howTheme(ctx, cwd, options.theme);
115
192
  // Without part data, what each part reads is unknown: answers that need
116
193
  // it say so instead of reporting nothing read.
117
194
  const unknown = ctx.unchecked
118
195
  ? {notChecked: {code: E.ERR_THEME_NOT_CHECKED, cause: ctx.unchecked}}
119
196
  : {};
120
- if (FAMILIES[t]) {
121
- return {
122
- type: 'themeEdit.how',
123
- data: {
124
- kind: 'group',
125
- subject: t,
126
- group: t,
127
- members: FAMILIES[t],
128
- spreads: AUTO_SPREAD.includes(t),
129
- },
130
- };
197
+ const themeFields = {
198
+ theme: env.slug,
199
+ themeChosenBy: env.chosenBy,
200
+ ...(env.note ? {themeNote: env.note} : {}),
201
+ };
202
+ /**
203
+ * Dial examples as commands for the theme, each checked.
204
+ * @param {string} dial
205
+ */
206
+ const dialCommands = dial =>
207
+ checked(
208
+ env,
209
+ DIALS[dial].examples
210
+ .map(exampleStep)
211
+ .filter(st => st != null)
212
+ .map(st => [/** @type {import('./_how-commands.mjs').Step} */ (st)]),
213
+ ).commands;
214
+ const key = lookupKey(t, ctx);
215
+ // A list's name alone ("dials", "tokens") is that list.
216
+ if (/^(dials?|tokens?|parts?|groups?|propert(y|ies))$/.test(key)) {
217
+ const kind = listKind(key);
218
+ return {kind: 'list', subject: '', ...(await listItems(kind, '', cwd))};
131
219
  }
132
- if (ctx.project.target.has(t)) {
133
- const group = familyOf(t);
220
+ if (Object.hasOwn(FAMILIES, key)) {
134
221
  return {
135
- type: 'themeEdit.how',
136
- data: {
137
- kind: 'part',
138
- subject: t,
139
- component: ctx.project.target.get(t)?.component ?? null,
140
- recorded: Boolean(C.MAP[t]),
141
- group,
142
- groupMembers: group ? FAMILIES[group] : [],
143
- spreads: group ? AUTO_SPREAD.includes(group) : false,
144
- variants: C.variantValues(t),
145
- states: ctx.project.target.get(t)?.states ?? [],
146
- reads: Object.fromEntries(
147
- Object.keys(GROUPS).map(g => [g, C.partReads(t, g)]),
148
- ),
149
- contains: C.MAP[t]?.contains ?? [],
150
- ...unknown,
151
- },
222
+ kind: 'group',
223
+ subject: t,
224
+ group: key,
225
+ members: FAMILIES[key],
226
+ spreads: AUTO_SPREAD.includes(key),
152
227
  };
153
228
  }
154
- if (t === 'colors' || t === 'palette')
229
+ if (ctx.project.target.has(key))
230
+ return partAnswer(ctx, env, t, key, unknown, themeFields);
231
+ if (key === 'colors' || key === 'palette')
155
232
  return {
156
- type: 'themeEdit.how',
157
- data: {
158
- kind: 'aspect',
159
- subject: t,
160
- results: [
161
- ...colorsAnswer(),
162
- ...['text', 'background', 'border'].flatMap(a =>
163
- wholeThemeTokens(ctx, a),
164
- ),
165
- ],
166
- },
233
+ kind: 'aspect',
234
+ subject: t,
235
+ ...themeFields,
236
+ results: [
237
+ ...colorsAnswer(env, dialCommands),
238
+ ...['text', 'background', 'border'].flatMap(a =>
239
+ wholeThemeTokens(ctx, env, a),
240
+ ),
241
+ ],
167
242
  };
168
- if (ASPECTS.includes(t)) {
169
- const results = wholeThemeTokens(ctx, t);
243
+ if (ASPECTS.includes(key)) {
244
+ const results = wholeThemeTokens(ctx, env, key);
170
245
  const dial = /** @type {Record<string, string>} */ ({
171
246
  corners: 'corners',
172
247
  spacing: 'spacing',
173
248
  font: 'font',
174
249
  size: 'text-size',
175
- })[t];
176
- if (t === 'text' || t === 'background')
250
+ shadow: 'surfaces',
251
+ border: 'surfaces',
252
+ })[key];
253
+ if (key === 'text' || key === 'background')
177
254
  results.unshift(
178
255
  ...['accent', 'neutral'].map(d => ({
179
256
  text: DIALS[d].help,
180
- commands: DIALS[d].examples.map(e => `${P} ${e}`),
257
+ commands: dialCommands(d),
181
258
  })),
182
259
  );
183
260
  if (dial)
184
- results.unshift({
185
- text: DIALS[dial].help,
186
- commands: DIALS[dial].examples.map(e => `${P} ${e}`),
187
- });
261
+ results.unshift({text: DIALS[dial].help, commands: dialCommands(dial)});
188
262
  results.push({
189
- text: `for one part: ${HOW} <part> lists what it reads for ${t}`,
263
+ text: `for one part: ${HOW} <part> lists what it reads for ${key}`,
190
264
  commands: [`${HOW} button`],
191
265
  });
192
- return {
193
- type: 'themeEdit.how',
194
- data: {kind: 'aspect', subject: t, results},
195
- };
266
+ return {kind: 'aspect', subject: t, ...themeFields, results};
196
267
  }
197
- if (DIALS[t]) {
198
- const d = DIALS[t];
268
+ if (Object.hasOwn(DIALS, key)) {
269
+ const d = DIALS[key];
199
270
  return {
200
- type: 'themeEdit.how',
201
- data: {
202
- kind: 'setting',
203
- subject: t,
204
- source: 'dial',
205
- values: d.values,
206
- help: d.help,
207
- ...(PALETTE_DIALS.includes(t) ? {shades: mappingRows(t)} : {}),
208
- examples: d.examples.map(e => `${P} ${e}`),
209
- },
271
+ kind: 'setting',
272
+ subject: t,
273
+ source: 'dial',
274
+ values: d.values,
275
+ help: d.help,
276
+ ...(PALETTE_DIALS.includes(key) ? {shades: mappingRows(key)} : {}),
277
+ ...themeFields,
278
+ examples: dialCommands(key),
210
279
  };
211
280
  }
212
- if (t.startsWith('--') && t in ctx.project.core.tokenDefaults) {
213
- const readers = C.anyReader(t);
214
- const type = C.typeOf(t);
281
+ if (
282
+ key.startsWith('--') &&
283
+ Object.hasOwn(ctx.project.core.tokenDefaults, key)
284
+ )
285
+ return tokenAnswer(ctx, env, t, key, unknown, themeFields);
286
+ if (CSS_PROPERTIES.has(key)) {
287
+ const setters = Object.keys(C.MAP).filter(p => key in C.MAP[p].own);
288
+ const value = exampleForProperty(key);
289
+ const {commands, refused} = value
290
+ ? checked(
291
+ env,
292
+ setters
293
+ .slice(0, 3)
294
+ .map(on => [
295
+ {verb: /** @type {'set'} */ ('set'), thing: key, value, on},
296
+ ]),
297
+ )
298
+ : {commands: [], refused: []};
215
299
  return {
216
- type: 'themeEdit.how',
217
- data: {
218
- kind: 'setting',
219
- subject: t,
220
- source: 'token',
221
- tokenType: type,
222
- default: String(ctx.project.core.tokenDefaults[t]),
223
- perMode: MODAL.has(type),
224
- readBy: readers,
225
- ...unknown,
226
- examples: [
227
- `${P} set <theme> ${t} <value>`,
228
- ...(readers[0]
229
- ? [`${P} set <theme> ${t} <value> --on ${readers[0]}`]
230
- : []),
231
- ],
232
- },
300
+ kind: 'setting',
301
+ subject: t,
302
+ source: 'property',
303
+ setBy: setters,
304
+ ...unknown,
305
+ ...themeFields,
306
+ examples: commands.slice(0, 1),
307
+ ...(refused.length && !commands.length
308
+ ? {refused: refused.slice(0, 2)}
309
+ : {}),
233
310
  };
234
311
  }
235
- if (CSS_PROPERTIES.has(t)) {
236
- const setters = Object.keys(C.MAP).filter(p => t in C.MAP[p].own);
237
- return {
238
- type: 'themeEdit.how',
239
- data: {
240
- kind: 'setting',
312
+ // "What does --color-accent do", "what's the variable for card padding":
313
+ // a question about what something is gets the lookup, not a change.
314
+ if (
315
+ /^\s*(what|which|where)\b.*\b(variables?|tokens?|do|does|means?|controls?|for)\b|^\s*what('s| is) the (css )?(variable|token|property)/i.test(
316
+ t,
317
+ ) &&
318
+ !/\b(command|make|makes|set|change)\b/i.test(t)
319
+ ) {
320
+ const tok = /--[a-z0-9-]+/i.exec(t)?.[0]?.toLowerCase();
321
+ if (tok && Object.hasOwn(ctx.project.core.tokenDefaults, tok))
322
+ return tokenAnswer(ctx, env, t, tok, unknown, themeFields);
323
+ const q = draftAnswer(ctx, env, t);
324
+ const groups = q.aspects.filter(a => Object.hasOwn(GROUPS, a));
325
+ const results = q.parts
326
+ .map(p => (FAMILIES[p] ? FAMILIES[p][0] : p))
327
+ .filter(p => ctx.project.target.has(p))
328
+ .map(p => {
329
+ const toks = (groups.length ? groups : [null]).flatMap(g =>
330
+ C.partReads(p, g).map(r => r.token),
331
+ );
332
+ return {
333
+ text: toks.length
334
+ ? `${p} reads ${[...new Set(toks)].slice(0, 6).join(', ')}${groups.length ? ` for ${groups.join(' and ')}` : ''}`
335
+ : `what ${p} reads`,
336
+ commands: [`${HOW} ${p}`],
337
+ };
338
+ });
339
+ if (results.length)
340
+ return {
341
+ kind: 'question',
241
342
  subject: t,
242
- source: 'property',
243
- setBy: setters,
343
+ understood: {parts: q.parts, aspects: q.aspects},
344
+ ...themeFields,
345
+ results,
244
346
  ...unknown,
245
- examples: [
246
- `${P} set <theme> ${t} <value> --on ${setters[0] ?? '<part>'}`,
247
- ],
248
- },
249
- };
347
+ };
250
348
  }
251
- const colors = PART_WORDS.some(([re]) => re.test(t.toLowerCase()))
252
- ? null
253
- : colorQuestion(t);
254
- if (colors)
255
- return {
256
- type: 'themeEdit.how',
257
- data: {
258
- kind: 'question',
259
- subject: t,
260
- understood: {parts: [], aspects: ['colors']},
261
- results: colors,
262
- },
349
+ const h = draftAnswer(ctx, env, t);
350
+ const results = finish(env, h.drafts);
351
+ const empty = !results.some(r => r.commands.length);
352
+ return {
353
+ kind: 'question',
354
+ subject: t,
355
+ understood: {parts: h.parts, aspects: h.aspects},
356
+ ...themeFields,
357
+ results,
358
+ ...unknown,
359
+ ...(empty
360
+ ? {
361
+ hint: results.length
362
+ ? `No command does all of "${t}" on ${env.slug}; the lines above say why.`
363
+ : `No match for "${t}". Name the part (header, nav links, card, button, banner, input...) and what to change (text color, background, gradient, corners, border, shadow, spacing, bold), in English.`,
364
+ run: [
365
+ `${HOW} --list parts`,
366
+ `${HOW} "rounder buttons"`,
367
+ `${HOW} colors`,
368
+ ],
369
+ }
370
+ : {}),
371
+ };
372
+ }
373
+
374
+ /**
375
+ * Check each draft's commands and keep what passes; a draft whose commands
376
+ * are all refused says why, and points to the lookup that helps.
377
+ * @param {import('./_how-commands.mjs').HowTheme} env
378
+ * @param {import('./_how-question.mjs').Draft[]} drafts
379
+ */
380
+ function finish(env, drafts) {
381
+ /** @type {Array<{text: string, commands: string[], sequence?: boolean, refused?: Array<{command: string, why: string}>}>} */
382
+ const out = [];
383
+ for (const d of drafts) {
384
+ const {commands, refused} = checked(env, d.options);
385
+ const lookups = d.lookup ? [d.lookup] : [];
386
+ if (!commands.length && d.options.length && !lookups.length) {
387
+ out.push({
388
+ text: `${d.text}: no command does it on ${env.slug}`,
389
+ commands: [],
390
+ refused,
391
+ });
392
+ continue;
393
+ }
394
+ out.push({
395
+ text: d.text,
396
+ commands: [...commands, ...lookups],
397
+ ...(d.sequence && commands.length ? {sequence: true} : {}),
398
+ ...(refused.length ? {refused} : {}),
399
+ });
400
+ }
401
+ if (!env.exists && out.some(r => r.commands.some(c => / set /.test(c))))
402
+ out.unshift({
403
+ text: `the app has no theme yet: make ${env.slug} first`,
404
+ commands: [`${P} new ${env.slug} --like ${env.data.like ?? 'neutral'}`],
405
+ });
406
+ const seen = new Set();
407
+ // Changes first; a lookup ("how card") after the commands that change.
408
+ const changes = (/** @type {{commands: string[]}} */ r) =>
409
+ r.commands.some(c => / editor (set|undo|new) /.test(c)) ? 0 : 1;
410
+ return out
411
+ .sort((a, b) => changes(a) - changes(b))
412
+ .filter(r => {
413
+ const k = `${r.text}\n${r.commands.join('\n')}`;
414
+ if (seen.has(k)) return false;
415
+ seen.add(k);
416
+ return true;
417
+ })
418
+ .slice(0, 10);
419
+ }
420
+
421
+ /**
422
+ * The key a lookup matches: lower case, without closing punctuation, a
423
+ * plural part or aspect made singular, and a token name given its dashes.
424
+ * @param {string} t
425
+ * @param {import('./_settings.mjs').Ctx} ctx
426
+ */
427
+ function lookupKey(t, ctx) {
428
+ const k = t
429
+ .toLowerCase()
430
+ .replace(/[?.!]+$/, '')
431
+ .trim();
432
+ if (/\s/.test(k)) return t;
433
+ const known = (/** @type {string} */ x) =>
434
+ Object.hasOwn(FAMILIES, x) ||
435
+ ctx.project.target.has(x) ||
436
+ ASPECTS.includes(x) ||
437
+ Object.hasOwn(DIALS, x) ||
438
+ CSS_PROPERTIES.has(x) ||
439
+ x === 'colors' ||
440
+ x === 'palette';
441
+ if (known(k)) return k;
442
+ const token = `--${k.replace(/^-+/, '')}`;
443
+ if (Object.hasOwn(ctx.project.core.tokenDefaults, token)) return token;
444
+ for (const x of [k.replace(/s$/, ''), k.replace(/es$/, ''), `${k}s`])
445
+ if (x !== k && known(x)) return x;
446
+ return t;
447
+ }
448
+
449
+ /**
450
+ * The answer for one part.
451
+ * @param {import('./_settings.mjs').Ctx} ctx
452
+ * @param {import('./_how-commands.mjs').HowTheme} env
453
+ * @param {string} subject
454
+ * @param {string} key
455
+ * @param {object} unknown
456
+ * @param {object} themeFields
457
+ * @returns {import('./theme-edit.type.mjs').ThemeEditHowResponse['data']}
458
+ */
459
+ function partAnswer(ctx, env, subject, key, unknown, themeFields) {
460
+ const {C} = ctx;
461
+ const target = /** @type {{component?: string, states: string[]}} */ (
462
+ ctx.project.target.get(key)
463
+ );
464
+ const group = familyOf(key);
465
+ const states = [...new Set([...target.states, ...COMMON_STATES])];
466
+ const reads = Object.fromEntries(
467
+ Object.keys(GROUPS).map(g => [
468
+ g,
469
+ C.partReads(key, g).map(r => ({
470
+ token: r.token,
471
+ props: r.props,
472
+ when: [...new Set(r.when.map(w => condition(ctx, key, w)))],
473
+ })),
474
+ ]),
475
+ );
476
+ const components = [
477
+ ...new Set(
478
+ ctx.project.targets.filter(x => x.key === key).map(x => x.component),
479
+ ),
480
+ ];
481
+ const recorded = Boolean(C.MAP[key]);
482
+ /** @type {Record<string, unknown>} */
483
+ const extra = {};
484
+ if (!recorded && !ctx.unchecked) {
485
+ const {commands} = checked(env, [
486
+ [{verb: 'set', thing: 'background', value: '#f3f4f6', on: key}],
487
+ [{verb: 'set', thing: 'color', value: '#111827', on: key}],
488
+ [{verb: 'set', thing: 'border-radius', value: '8px', on: key}],
489
+ ]);
490
+ extra.unrecorded = {
491
+ reason: `the part data comes from one render of every component, and it has no ${key}, so what ${key} reads is unknown; a CSS property set --on ${key} still applies`,
492
+ examples: commands,
263
493
  };
264
- const h = answerHow(ctx, t);
494
+ }
265
495
  return {
266
- type: 'themeEdit.how',
267
- data: {
268
- kind: 'question',
269
- subject: t,
270
- understood: {parts: h.parts, aspects: h.aspects},
271
- results: h.results,
272
- ...unknown,
273
- },
496
+ kind: 'part',
497
+ subject,
498
+ component: target.component ?? null,
499
+ components,
500
+ recorded,
501
+ group,
502
+ groupMembers: group ? FAMILIES[group] : [],
503
+ spreads: group ? AUTO_SPREAD.includes(group) : false,
504
+ variants: C.variantValues(key),
505
+ states,
506
+ reads,
507
+ contains: C.MAP[key]?.contains ?? [],
508
+ ...extra,
509
+ ...unknown,
510
+ ...themeFields,
511
+ };
512
+ }
513
+
514
+ /**
515
+ * One condition a part reads a token under, written as the flags `set`
516
+ * takes (`always` for none), or the condition and why no flag reaches it.
517
+ * @param {import('./_settings.mjs').Ctx} ctx
518
+ * @param {string} target
519
+ * @param {string} cond
520
+ * @returns {string}
521
+ */
522
+ export function condition(ctx, target, cond) {
523
+ if (!cond.trim()) return 'always';
524
+ const t = ctx.project.target.get(target);
525
+ const props = t?.props ?? [];
526
+ const states = [...(t?.states ?? []), ...COMMON_STATES];
527
+ const values = ctx.C.variantValues(target);
528
+ const words = cond.trim().split(/\s+/);
529
+ const isAttr = (/** @type {string} */ w) => /^[a-z][\w-]*=[^\s]*$/i.test(w);
530
+ const attrs = words.filter(isAttr).flatMap(w => w.split(','));
531
+ const css = words.filter(w => !isAttr(w)).join(' ');
532
+ /** @type {string[]} */
533
+ const flags = [];
534
+ /** @type {string | null} */
535
+ let why = null;
536
+ for (const kv of attrs) {
537
+ const [k, v] = kv.split('=');
538
+ if (k === 'selected' && states.includes('selected'))
539
+ flags.push('--state selected');
540
+ else if (props.includes(k) && (!values[k]?.length || values[k].includes(v)))
541
+ flags.push(`--when ${k}:${v}`);
542
+ else why ??= `${target} has no ${k} prop or state that set can name`;
543
+ }
544
+ if (css) {
545
+ const m = /^:([a-z-]+)$/.exec(css);
546
+ if (m && states.includes(m[1])) flags.push(`--state ${m[1]}`);
547
+ else why ??= `${css} is a CSS selector that set cannot name`;
548
+ }
549
+ if (flags.filter(f => f.startsWith('--when')).length > 1)
550
+ why ??= 'set names one --when at a time';
551
+ if (flags.filter(f => f.startsWith('--state')).length > 1)
552
+ why ??= 'set names one --state at a time';
553
+ return why ? `${cond.trim()} (not settable: ${why})` : flags.join(' ');
554
+ }
555
+
556
+ /** Whether Core's stylesheet reads a token. @type {Map<string, string>} */
557
+ const sheets = new Map();
558
+ /**
559
+ * @param {import('./_settings.mjs').Ctx} ctx
560
+ * @param {string} token
561
+ */
562
+ function stylesheetReads(ctx, token) {
563
+ const file = ctx.project.req.resolve('@astryxdesign/core/astryx.css');
564
+ let css = sheets.get(file);
565
+ if (css == null) {
566
+ try {
567
+ css = fs.readFileSync(file, 'utf8');
568
+ } catch {
569
+ css = '';
570
+ }
571
+ sheets.set(file, css);
572
+ }
573
+ return new RegExp(`var\\(${token}[,)]`).test(css);
574
+ }
575
+
576
+ /**
577
+ * A value of a token's own type that differs from the one it has now.
578
+ * @param {string} type
579
+ * @param {string} token
580
+ * @param {string} now
581
+ */
582
+ function exampleForToken(type, token, now) {
583
+ const pick = (/** @type {string[]} */ xs) =>
584
+ xs.find(x => x.toLowerCase() !== now.toLowerCase()) ?? xs[0];
585
+ if (type === 'color') return pick(['#7c3aed', '#2563eb']);
586
+ if (type === 'shadow') return '0 2px 8px rgb(0 0 0 / 0.15)';
587
+ if (type === 'size') {
588
+ const m = /^(\d*\.?\d+)(px|rem|em)$/.exec(now.trim());
589
+ if (m) return `${Number((Number(m[1]) * 1.25).toFixed(3))}${m[2]}`;
590
+ return pick(['8px', '10px']);
591
+ }
592
+ if (type === 'number')
593
+ return /leading|line-height/.test(token)
594
+ ? pick(['1.6', '1.4'])
595
+ : pick(['600', '700']);
596
+ if (type === 'font') return 'Georgia, serif';
597
+ if (type === 'time') return pick(['200ms', '300ms']);
598
+ if (type === 'easing') return 'ease-out';
599
+ return null;
600
+ }
601
+
602
+ /** An example value for a CSS property. @param {string} prop */
603
+ function exampleForProperty(prop) {
604
+ if (COLOR_PROPS.test(prop)) return '#7c3aed';
605
+ /** @type {Record<string, string>} */
606
+ const known = {
607
+ background: '#f3f4f6',
608
+ 'background-image': 'linear-gradient(#ffffff, #e5e7eb)',
609
+ border: '1px solid var(--color-border)',
610
+ 'border-width': '2px',
611
+ 'border-style': 'dashed',
612
+ 'box-shadow': 'var(--shadow-med)',
613
+ 'font-weight': '600',
614
+ 'font-family': 'Georgia, serif',
615
+ 'letter-spacing': '0.02em',
616
+ 'text-transform': 'uppercase',
617
+ 'font-style': 'italic',
618
+ opacity: '0.8',
619
+ transform: 'scale(0.97)',
620
+ outline: 'none',
621
+ };
622
+ if (known[prop]) return known[prop];
623
+ if (/radius$/.test(prop)) return '8px';
624
+ if (/^(padding|margin|gap|row-gap|column-gap)/.test(prop)) return '12px';
625
+ if (/^(font-size)$/.test(prop)) return '16px';
626
+ if (/(height|width|block-size|inline-size)$/.test(prop)) return '40px';
627
+ return null;
628
+ }
629
+
630
+ /**
631
+ * The answer for one design token: its type, default, the parts that read
632
+ * it, and commands that set it, each checked.
633
+ * @param {import('./_settings.mjs').Ctx} ctx
634
+ * @param {import('./_how-commands.mjs').HowTheme} env
635
+ * @param {string} subject
636
+ * @param {string} key
637
+ * @param {object} unknown
638
+ * @param {object} themeFields
639
+ * @returns {import('./theme-edit.type.mjs').ThemeEditHowResponse['data']}
640
+ */
641
+ function tokenAnswer(ctx, env, subject, key, unknown, themeFields) {
642
+ const {C} = ctx;
643
+ const readers = C.anyReader(key);
644
+ const type = C.typeOf(key);
645
+ const now =
646
+ env.base.light[key] ?? String(ctx.project.core.tokenDefaults[key]);
647
+ const value = exampleForToken(type, key, now);
648
+ const {commands, refused} = value
649
+ ? checked(env, [
650
+ [{verb: 'set', thing: key, value}],
651
+ ...(readers[0]
652
+ ? [
653
+ [
654
+ {
655
+ verb: /** @type {'set'} */ ('set'),
656
+ thing: key,
657
+ value,
658
+ on: readers[0],
659
+ },
660
+ ],
661
+ ]
662
+ : []),
663
+ ])
664
+ : {commands: [], refused: []};
665
+ // The part data comes from one render of each component, so a token only
666
+ // a variant it does not render reads (heading level 5, an error toast)
667
+ // shows no reader there; Core's stylesheet still names it.
668
+ const inSheet = !readers.length && stylesheetReads(ctx, key);
669
+ return {
670
+ kind: 'setting',
671
+ subject,
672
+ source: 'token',
673
+ tokenType: type,
674
+ default: String(ctx.project.core.tokenDefaults[key]),
675
+ perMode: MODAL.has(type),
676
+ readBy: readers,
677
+ ...(readers.length || ctx.unchecked
678
+ ? {}
679
+ : {
680
+ readByNote: inSheet
681
+ ? `no part in the part data reads ${key}, but Core's stylesheet does, in a variant or state the part data does not render; so readBy is incomplete`
682
+ : `no part reads ${key}, and Core's stylesheet does not use it`,
683
+ }),
684
+ ...unknown,
685
+ ...themeFields,
686
+ examples: commands,
687
+ ...(refused.length ? {refused} : {}),
274
688
  };
275
689
  }
276
690
 
@@ -278,151 +692,90 @@ export async function themeEditHow(subject, options = {}) {
278
692
  * How the theme's colors are made, for `how colors`: one line on the
279
693
  * generator, one per color with the shade each token starts from, then
280
694
  * vibrancy, every shade, and the exact-token escape hatch.
695
+ * @param {import('./_how-commands.mjs').HowTheme} env
696
+ * @param {(dial: string) => string[]} dialCommands
281
697
  * @returns {Array<{text: string, commands: string[]}>}
282
698
  */
283
- function colorsAnswer() {
284
- const f = paletteFiles('<theme>');
699
+ function colorsAnswer(env, dialCommands) {
700
+ const f = paletteFiles(env.slug);
701
+ const one = (/** @type {import('./_how-commands.mjs').Step[]} */ steps) =>
702
+ checked(env, [steps]).commands;
285
703
  return [
286
704
  {
287
- text: `Each color you set (${PALETTE_DIALS.join(', ')}) is one seed: the editor generates its shades from it, light and dark, with the same generator as \`theme palette generate\`, and points the color tokens at those shades. A token moves to a nearby shade when it must read: text at 4.5:1, the focus ring and secondary icons at 3:1, a fill until the text on it reads. It never mixes a new color. The generated files are ${f.palette}, made from ${f.config}, and the theme imports them, so every change moves the theme with it.`,
705
+ text: `Each color you set (${PALETTE_DIALS.join(', ')}) is one seed: the editor generates its shades from it, light and dark, with the same generator as \`theme palette generate\`, and points the color tokens at those shades. The exact color you gave sits at its own shade, in dark too when it reads there. A token moves to a nearby shade when it must read: text at 4.5:1, the focus ring and secondary icons at 3:1. A fill never moves: the text on it changes instead. It never mixes a new color. The generated files are ${f.palette}, made from ${f.config}; the theme imports only the shades it uses, from ${f.refs}, so every change moves the theme with it. Hand edits to ${f.config} that no color setting owns are kept; a hand edit to ${f.palette} is never overwritten.`,
288
706
  commands: [
289
- `${P} set <theme> accent "#7c3aed"`,
290
- `${P} set <theme> neutral "#64748b"`,
291
- `${P} show <theme>`,
292
- `${P} undo <theme> accent`,
707
+ ...one([{verb: 'set', thing: 'accent', value: '#7c3aed'}]),
708
+ ...one([{verb: 'set', thing: 'neutral', value: '#64748b'}]),
709
+ ...(env.exists ? [`${P} show ${env.slug}`] : []),
293
710
  ],
294
711
  },
295
712
  ...PALETTE_DIALS.map(d => ({
296
713
  text: `${d}: ${mappingRows(d).join('; ')}`,
297
- commands: DIALS[d].examples.map(e => `${P} ${e}`),
714
+ commands: dialCommands(d),
298
715
  })),
299
716
  {
300
717
  text: DIALS.vibrancy.help,
301
- commands: DIALS.vibrancy.examples.map(e => `${P} ${e}`),
718
+ commands: dialCommands('vibrancy'),
302
719
  },
303
720
  {
304
721
  text: 'Every shade, light and dark, with the tokens that use each: the Colors page of the in-app preview. It changes with every set.',
305
- commands: [`${PREVIEW} add --theme <theme>`],
722
+ commands: env.exists ? [`${PREVIEW} add --theme ${env.slug}`] : [],
306
723
  },
307
724
  {
308
725
  text: 'An exact color for one token: set the token itself. It always wins over the generated colors, whatever order you set them in.',
309
- commands: [`${P} set <theme> --color-accent "#7c3aed"`],
726
+ commands: one([{verb: 'set', thing: '--color-accent', value: '#7c3aed'}]),
310
727
  },
311
728
  ];
312
729
  }
313
730
 
314
731
  /**
315
- * Plain-words questions about colors, as `[words, answer]`: the first match
316
- * answers, with what happens and the commands. Asked only when the question
317
- * names no part.
318
- * @type {Array<[RegExp, (q: string) => {text: string, commands: string[]}]>}
732
+ * The tokens most parts read for one aspect, for a whole-theme change.
733
+ * @param {import('./_settings.mjs').Ctx} ctx
734
+ * @param {import('./_how-commands.mjs').HowTheme} env
735
+ * @param {string} aspect
736
+ * @returns {Array<{text: string, commands: string[]}>}
319
737
  */
320
- const COLOR_QUESTIONS = [
321
- [
322
- /\b(exact|one token|single token|specific token|override)\b/,
323
- () => ({
324
- 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.',
325
- commands: [
326
- `${P} set <theme> --color-accent "#7c3aed"`,
327
- `${P} set <theme> --color-text-primary "#111827" --mode light`,
328
- `${HOW} --list tokens`,
329
- ],
330
- }),
331
- ],
332
- [
333
- /\b(shades?|swatch(es)?|ramps?|all (the )?colou?rs|every colou?r|see (the )?colou?rs)\b/,
334
- () => ({
335
- 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.',
336
- commands: [`${PREVIEW} add --theme <theme>`, `${P} show <theme>`],
337
- }),
338
- ],
339
- [
340
- /\b(colou?rful|(de)?saturat\w*|vivid|vibran\w*|muted|dull|washed|pastel|intense|punch\w*|gr[ae]yer)\b/,
341
- q => {
342
- const less =
343
- /\b(less|desaturat\w*|muted|dull|washed|pastel|gr[ae]yer|calm\w*|softer)\b/.test(
344
- q,
345
- ) && !/\bmore\b/.test(q);
346
- return {
347
- text: `vibrancy sets how saturated every generated color is: 0 is gray, 100 the most vivid, 50 the default; ${less ? 'less' : 'more'} steps it by 10.`,
348
- commands: [
349
- `${P} set <theme> vibrancy ${less ? 'less' : 'more'}`,
350
- `${P} set <theme> vibrancy ${less ? 30 : 70}`,
351
- ],
352
- };
353
- },
354
- ],
355
- [
356
- /\bdark\b.*\b(colou?rs?|mode|shades?)\b|\bcolou?rs?\b.*\bdark\b/,
357
- () => ({
358
- 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.',
359
- commands: [
360
- `${P} set <theme> accent "#7c3aed"`,
361
- `${P} set <theme> --color-background-body "#0b0b0f" --mode dark`,
362
- `${P} set <theme> mode dark-only`,
363
- ],
364
- }),
365
- ],
366
- [
367
- /\b(status|errors?|danger|destructive|success|warnings?|caution|info|notices?|red|green|yellow|amber)\b/,
368
- q => {
369
- const all = [
370
- ['danger', /\b(errors?|danger|destructive|red)\b/, '"#dc2626"'],
371
- ['success', /\b(success|green)\b/, '"#16a34a"'],
372
- ['warning', /\b(warnings?|caution|yellow|amber)\b/, '"#f59e0b"'],
373
- ['info', /\b(info|notices?)\b/, '"#0284c7"'],
374
- ];
375
- const named = all.filter(([, re]) => /** @type {RegExp} */ (re).test(q));
376
- const order = [...named, ...all.filter(x => !named.includes(x))];
377
- return {
378
- 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.',
379
- commands: order.map(([d, , v]) => `${P} set <theme> ${d} ${v}`),
380
- };
738
+ function wholeThemeTokens(ctx, env, aspect) {
739
+ const {C} = ctx;
740
+ const toks = Object.keys(ctx.project.core.tokenDefaults)
741
+ .filter(k => C.groupOfToken(k) === aspect && C.anyReader(k).length)
742
+ .sort((a, b) => C.anyReader(b).length - C.anyReader(a).length)
743
+ .slice(0, 6);
744
+ if (!toks.length) return [];
745
+ const value = exampleForToken(
746
+ C.typeOf(toks[0]),
747
+ toks[0],
748
+ env.base.light[toks[0]] ?? '',
749
+ );
750
+ return [
751
+ {
752
+ text: `whole-theme tokens for ${aspect}, most used first: ${toks.map(k => `${k} (${C.anyReader(k).length} parts)`).join(', ')}`,
753
+ commands: value
754
+ ? checked(env, [[{verb: 'set', thing: toks[0], value}]]).commands
755
+ : [`${HOW} ${toks[0]}`],
381
756
  },
382
- ],
383
- [
384
- /\b(brand|accent|primary colou?r|main colou?r|key colou?r)\b/,
385
- () => ({
386
- text: 'The brand color is accent: primary buttons, links, selection and the focus ring. It makes its light and dark shades from the one color, and the fill keeps that exact color.',
387
- commands: [`${P} set <theme> accent "#7c3aed"`, `${HOW} accent`],
388
- }),
389
- ],
390
- [
391
- /\b(gr[ae]y|neutral|warm|cool)\b/,
392
- () => ({
393
- text: 'The gray of surfaces, text and borders is neutral. A gray with a little color makes a cool or warm theme.',
394
- commands: [
395
- `${P} set <theme> neutral "#64748b"`,
396
- `${P} set <theme> neutral "#78716c"`,
397
- ],
398
- }),
399
- ],
400
- ];
757
+ ];
758
+ }
401
759
 
402
760
  /**
403
- * The answer to a plain-words color question, or null when it is not one:
404
- * a question that names a part, or an aspect other than color, is not.
405
- * @param {string} question
406
- * @returns {Array<{text: string, commands: string[]}> | null}
761
+ * What `--list` lists: a kind in any case, singular or plural.
762
+ * @param {string} list
407
763
  */
408
- export function colorQuestion(question) {
409
- const q = question.toLowerCase();
410
- // A question about another aspect ("make the text red", "override the
411
- // corner radius", "a yellow background") is answered for that aspect, not
412
- // as a color question. Color words alone raise the background aspect, so
413
- // only a background named outright counts, and not for a status: "the
414
- // error background" is the danger color.
415
- const status =
416
- /\b(errors?|danger|destructive|success|warnings?|caution|info|notices?)\b/.test(
417
- q,
418
- );
419
- if (
420
- INTENTS.some(([aspect, re]) => aspect !== 'background' && re.test(q)) ||
421
- (/\b(background|bg|backdrop|fill)\b/.test(q) && !status)
422
- )
423
- return null;
424
- const hit = COLOR_QUESTIONS.find(([re]) => re.test(q));
425
- return hit ? [hit[1](q)] : null;
764
+ function listKind(list) {
765
+ const k = list.trim().toLowerCase();
766
+ if (k === '' || k === 'kinds' || k === 'kind') return 'kinds';
767
+ const plural =
768
+ k.endsWith('ies') || k.endsWith('s') ? k : k.replace(/y$/, 'ie') + 's';
769
+ if (HOW_LISTS.includes(plural)) return plural;
770
+ const near = nearest(k, [...HOW_LISTS, 'kinds']);
771
+ return refuse(
772
+ E.ERR_INVALID_ARGUMENT,
773
+ `--list takes ${HOW_LISTS.join(', ')} or kinds, not "${list}".`,
774
+ {
775
+ didYouMean: near,
776
+ run: [...near.map(n => `${HOW} --list ${n}`), `${HOW} --list kinds`],
777
+ },
778
+ );
426
779
  }
427
780
 
428
781
  /**
@@ -433,18 +786,11 @@ export function colorQuestion(question) {
433
786
  * @returns {Promise<{list: string, items: Array<Record<string, unknown>>, common?: boolean}>}
434
787
  */
435
788
  async function listItems(kind, filter, cwd) {
436
- if (!HOW_LISTS.includes(kind))
437
- refuse(
438
- E.ERR_INVALID_ARGUMENT,
439
- `--list takes ${HOW_LISTS.join(', ')}${kind ? `, not "${kind}"` : ''}.`,
440
- {
441
- didYouMean: kind ? nearest(kind, HOW_LISTS) : [],
442
- run: [`${HOW} --list dials`],
443
- },
444
- );
445
789
  const f = (/** @type {string} */ x) =>
446
790
  x.toLowerCase().includes(filter.toLowerCase());
447
- if (kind === 'dials')
791
+ if (kind === 'dials') {
792
+ const ctx = await context(cwd);
793
+ const env = await howTheme(ctx, cwd, undefined);
448
794
  return {
449
795
  list: kind,
450
796
  items: Object.entries(DIALS)
@@ -453,9 +799,18 @@ async function listItems(kind, filter, cwd) {
453
799
  name,
454
800
  values: d.values,
455
801
  help: d.help,
456
- examples: d.examples.map(e => `${P} ${e}`),
802
+ examples: d.examples
803
+ .map(exampleStep)
804
+ .filter(st => st != null)
805
+ .map(st =>
806
+ render(
807
+ /** @type {import('./_how-commands.mjs').Step} */ (st),
808
+ env.slug,
809
+ ),
810
+ ),
457
811
  })),
458
812
  };
813
+ }
459
814
  if (kind === 'groups')
460
815
  return {
461
816
  list: kind,
@@ -487,12 +842,21 @@ async function listItems(kind, filter, cwd) {
487
842
  })),
488
843
  };
489
844
  }
490
- const targets = ctx.project.targets.filter(x => f(x.key) || f(x.component));
845
+ // One item per part name: a name two components share lists both.
846
+ /** @type {Map<string, {key: string, components: string[], states: string[]}>} */
847
+ const byKey = new Map();
848
+ for (const x of ctx.project.targets) {
849
+ if (!f(x.key) && !f(x.component)) continue;
850
+ const e = byKey.get(x.key) ?? {key: x.key, components: [], states: []};
851
+ if (!e.components.includes(x.component)) e.components.push(x.component);
852
+ for (const s of x.states) if (!e.states.includes(s)) e.states.push(s);
853
+ byKey.set(x.key, e);
854
+ }
491
855
  return {
492
856
  list: kind,
493
- items: targets.map(x => ({
857
+ items: [...byKey.values()].map(x => ({
494
858
  name: x.key,
495
- component: x.component,
859
+ component: x.components.join(', '),
496
860
  group: familyOf(x.key),
497
861
  variants: C.variantValues(x.key),
498
862
  states: x.states,
@@ -503,24 +867,44 @@ async function listItems(kind, filter, cwd) {
503
867
 
504
868
  /**
505
869
  * Read `--at` points: "x,y;x,y", "x,y x,y", repeated, or a flat "a,b,c,d".
870
+ * Each number is a whole pixel; anything else is refused by name.
506
871
  * @param {string[]} at
872
+ * @returns {Array<{x: number, y: number}>}
507
873
  */
508
874
  export function parsePoints(at) {
509
- const nums = at
875
+ const words = at
510
876
  .join(' ')
511
- .split(/[^\d]+/)
512
- .filter(Boolean)
513
- .map(Number);
514
- if (nums.length % 2)
877
+ .split(/[;\s]+/)
878
+ .filter(Boolean);
879
+ const example = `${HOW} picture.png --at "40,20;300,180"`;
880
+ if (!words.length)
881
+ refuse(E.ERR_INVALID_ARGUMENT, '--at names no point; give x,y pairs.', {
882
+ run: [example],
883
+ });
884
+ /** @type {Array<{x: number, y: number}>} */
885
+ const points = [];
886
+ for (const w of words) {
887
+ const nums = w.split(',');
888
+ if (!nums.every(n => /^-?\d+$/.test(n)))
889
+ refuse(
890
+ E.ERR_INVALID_ARGUMENT,
891
+ `--at takes whole pixel numbers as x,y; "${w}" is not that.`,
892
+ {run: [example]},
893
+ );
894
+ if (nums.length % 2)
895
+ refuse(
896
+ E.ERR_INVALID_ARGUMENT,
897
+ `--at takes x,y pairs; "${w}" has an odd count of numbers.`,
898
+ {run: [example]},
899
+ );
900
+ for (let i = 0; i < nums.length; i += 2)
901
+ points.push({x: Number(nums[i]), y: Number(nums[i + 1])});
902
+ }
903
+ if (points.length > MAX_POINTS)
515
904
  refuse(
516
905
  E.ERR_INVALID_ARGUMENT,
517
- `--at takes x,y pairs; "${at.join(' ')}" has an odd count of numbers.`,
518
- {run: [`${HOW} picture.png --at "40,20;300,180"`]},
906
+ `--at reads at most ${MAX_POINTS} points; it got ${points.length}.`,
519
907
  );
520
- /** @type {Array<{x: number, y: number}>} */
521
- const points = [];
522
- for (let i = 0; i < nums.length; i += 2)
523
- points.push({x: nums[i], y: nums[i + 1]});
524
908
  return points;
525
909
  }
526
910
 
@@ -531,14 +915,38 @@ export function parsePoints(at) {
531
915
  * @param {string[]} at
532
916
  * @param {number | undefined} count
533
917
  */
534
- function pictureColors(file, cwd, at, count = 14) {
918
+ function pictureColors(file, cwd, at, count) {
535
919
  const abs = path.resolve(cwd, file);
536
920
  if (!fs.existsSync(abs) || !fs.statSync(abs).isFile())
537
- throw new AstryxError(`${file} does not exist.`, [], E.ERR_FILE_NOT_FOUND);
538
- if (!Number.isInteger(count) || count <= 0)
921
+ throw new AstryxError(
922
+ `${file} does not exist.`,
923
+ [{name: `${HOW} --list parts`, reason: 'or ask in plain words'}],
924
+ E.ERR_FILE_NOT_FOUND,
925
+ );
926
+ if (count != null && at.length)
927
+ refuse(
928
+ E.ERR_INVALID_ARGUMENT,
929
+ 'A count lists main colors; --at reads points. Give one of them.',
930
+ );
931
+ if (count != null && (!Number.isInteger(count) || count <= 0))
539
932
  refuse(
540
933
  E.ERR_INVALID_ARGUMENT,
541
934
  `The count must be a positive whole number, not "${count}".`,
935
+ {run: [`${HOW} ${file} 5`]},
936
+ );
937
+ const points = at.length ? parsePoints(at) : null;
938
+ // The header holds the size, so a huge picture is refused unread.
939
+ const fd = fs.openSync(abs, 'r');
940
+ const head = Buffer.alloc(8);
941
+ fs.readSync(fd, head, 0, 8, 0);
942
+ fs.closeSync(fd);
943
+ const other = OTHER_FORMATS.find(([, sig]) =>
944
+ sig.every((b, i) => head[i] === b),
945
+ );
946
+ if (other)
947
+ refuse(
948
+ E.ERR_INVALID_ARGUMENT,
949
+ `${file} is a ${other[0]} picture; how reads PNG only. Save or convert it as PNG.`,
542
950
  );
543
951
  /** @type {import('./_png.mjs').Picture} */
544
952
  let pic;
@@ -551,19 +959,33 @@ function pictureColors(file, cwd, at, count = 14) {
551
959
  E.ERR_INVALID_ARGUMENT,
552
960
  );
553
961
  }
554
- if (at.length)
962
+ if (points) {
963
+ const outside = points.filter(
964
+ p => p.x < 0 || p.y < 0 || p.x >= pic.width || p.y >= pic.height,
965
+ );
966
+ if (outside.length)
967
+ refuse(
968
+ E.ERR_INVALID_ARGUMENT,
969
+ `${outside
970
+ .slice(0, 3)
971
+ .map(p => `${p.x},${p.y}`)
972
+ .join(
973
+ '; ',
974
+ )} ${outside.length > 1 ? 'are' : 'is'} outside the picture, which is ${pic.width}x${pic.height} (x from 0 to ${pic.width - 1}, y from 0 to ${pic.height - 1}).`,
975
+ );
555
976
  return {
556
977
  file,
557
978
  width: pic.width,
558
979
  height: pic.height,
559
980
  colors: null,
560
- points: colorsAt(pic, parsePoints(at)),
981
+ points: colorsAt(pic, points),
561
982
  };
983
+ }
562
984
  return {
563
985
  file,
564
986
  width: pic.width,
565
987
  height: pic.height,
566
- colors: mainColors(pic, count),
988
+ colors: mainColors(pic, count ?? 14),
567
989
  points: null,
568
990
  };
569
991
  }