@astryxdesign/cli 0.7.14-canary.gfb823d9 → 0.7.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/CHANGELOG.md +197 -0
  2. package/api/component/_adapter.d.mts +15 -0
  3. package/api/component/_adapter.mjs +76 -0
  4. package/api/component/component.mjs +8 -1
  5. package/api/search/_named-keywords.d.mts +31 -0
  6. package/api/search/_named-keywords.mjs +177 -0
  7. package/api/search/search-index.mjs +8 -1
  8. package/api/search/search.d.mts +6 -1
  9. package/api/search/search.mjs +49 -8
  10. package/api/theme/_adapter.d.mts +33 -0
  11. package/api/theme/_adapter.mjs +352 -16
  12. package/api/theme/build/build.mjs +261 -10
  13. package/api/theme/eject/eject.mjs +13 -1
  14. package/api/theme/list/list.mjs +11 -2
  15. package/api/theme/palette/generate/color.d.mts +2 -0
  16. package/api/theme/palette/generate/color.mjs +1 -1
  17. package/api/theme/template/template.mjs +139 -6
  18. package/api/theme/theme.type.d.mts +15 -1
  19. package/api/theme/theme.type.mjs +9 -3
  20. package/api/theme/themeAdd.doc.mjs +1 -1
  21. package/api/theme/themeBuild.doc.mjs +10 -2
  22. package/api/theme/themeEject.doc.mjs +2 -2
  23. package/api/theme/themeListAvailable.doc.mjs +1 -1
  24. package/api/theme/themeRemove.doc.mjs +1 -1
  25. package/api/theme/themeTemplate.doc.mjs +8 -0
  26. package/api/theme/themeUse.doc.mjs +1 -1
  27. package/api/theme-edit/_adapter.d.mts +36 -2
  28. package/api/theme-edit/_adapter.mjs +340 -12
  29. package/api/theme-edit/_check.d.mts +28 -25
  30. package/api/theme-edit/_check.mjs +876 -308
  31. package/api/theme-edit/_color.d.mts +53 -4
  32. package/api/theme-edit/_color.mjs +406 -79
  33. package/api/theme-edit/_compiler.d.mts +14 -6
  34. package/api/theme-edit/_compiler.mjs +89 -59
  35. package/api/theme-edit/_context.d.mts +28 -8
  36. package/api/theme-edit/_context.mjs +142 -19
  37. package/api/theme-edit/_edit.d.mts +3 -1
  38. package/api/theme-edit/_edit.mjs +746 -76
  39. package/api/theme-edit/_how-commands.d.mts +91 -0
  40. package/api/theme-edit/_how-commands.mjs +269 -0
  41. package/api/theme-edit/_how-question.d.mts +57 -0
  42. package/api/theme-edit/_how-question.mjs +2574 -0
  43. package/api/theme-edit/_how.d.mts +27 -8
  44. package/api/theme-edit/_how.mjs +776 -175
  45. package/api/theme-edit/_overview.d.mts +9 -0
  46. package/api/theme-edit/_overview.mjs +296 -0
  47. package/api/theme-edit/_palette.d.mts +155 -15
  48. package/api/theme-edit/_palette.mjs +1446 -262
  49. package/api/theme-edit/_parts.mjs +61 -5
  50. package/api/theme-edit/_png.d.mts +18 -6
  51. package/api/theme-edit/_png.mjs +135 -25
  52. package/api/theme-edit/_preview-app.d.mts +32 -11
  53. package/api/theme-edit/_preview-app.mjs +1976 -285
  54. package/api/theme-edit/_preview.d.mts +39 -8
  55. package/api/theme-edit/_preview.mjs +367 -41
  56. package/api/theme-edit/_settings.d.mts +147 -11
  57. package/api/theme-edit/_settings.mjs +908 -99
  58. package/api/theme-edit/_tables.d.mts +4 -16
  59. package/api/theme-edit/_tables.mjs +51 -117
  60. package/api/theme-edit/theme-edit.type.d.mts +102 -66
  61. package/api/theme-edit/theme-edit.type.mjs +58 -40
  62. package/api/theme-edit/themeEditHow.doc.mjs +17 -6
  63. package/api/theme-edit/themeEditNew.doc.mjs +21 -5
  64. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +18 -5
  65. package/api/theme-edit/themeEditPreviewApp.doc.mjs +12 -9
  66. package/api/theme-edit/themeEditPreviewList.doc.mjs +11 -2
  67. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +29 -3
  68. package/api/theme-edit/themeEditSet.doc.mjs +14 -8
  69. package/api/theme-edit/themeEditShow.doc.mjs +10 -5
  70. package/api/theme-edit/themeEditUndo.doc.mjs +9 -4
  71. package/assets/discover/official-packages.json +4 -0
  72. package/assets/docs/tree/icon-sets.doc.mjs +3 -3
  73. package/assets/docs.generated.json +1 -0
  74. package/assets/icons/definitions/bookmarkAdd.doc.mjs +9 -0
  75. package/assets/icons/definitions/documentSearch.doc.mjs +9 -0
  76. package/assets/icons/definitions/keyboard.doc.mjs +9 -0
  77. package/assets/icons/definitions/paintBrush.doc.mjs +9 -0
  78. package/assets/icons/definitions/wallet.doc.mjs +9 -0
  79. package/assets/preview-app/gitignore +3 -0
  80. package/assets/templates/blocks/components/ButtonGroup/ButtonGroupShowcase.doc.mjs +1 -1
  81. package/assets/templates/blocks/components/Lightbox/LightboxGallery.tsx +1 -1
  82. package/assets/templates/components.generated.json +1 -0
  83. package/assets/templates/pages/gallery-hero/page.tsx +8 -2
  84. package/assets/templates/pages/settings-dialog/template.doc.mjs +3 -3
  85. package/assets/templates/pages/side-gallery/page.tsx +1 -1
  86. package/assets/templates/pages/table-filter/template.doc.mjs +2 -2
  87. package/assets/templates/pages/theme-showcase/template.doc.mjs +1 -1
  88. package/clients/cli/bin/astryx.mjs +37 -5
  89. package/clients/cli/commands/experimental/theme.mjs +422 -57
  90. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +22 -9
  91. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +103 -4
  92. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +13 -8
  93. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +5 -5
  94. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +5 -5
  95. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  96. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +3 -2
  97. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +2 -8
  98. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +2 -2
  99. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  100. package/clients/cli/commands/experimental-theme-targets.doc.mjs +1 -1
  101. package/clients/cli/commands/experimental-theme.doc.mjs +3 -4
  102. package/clients/cli/commands/theme-build.doc.mjs +1 -1
  103. package/clients/cli/commands/theme-eject.doc.mjs +3 -3
  104. package/clients/cli/commands/theme-remove.doc.mjs +2 -2
  105. package/clients/cli/commands/theme-template.doc.mjs +11 -4
  106. package/clients/cli/commands/theme.mjs +145 -46
  107. package/clients/cli/commands.generated.json +1 -0
  108. package/clients/cli/index.mjs +96 -5
  109. package/clients/cli/lib/json-shim.mjs +29 -1
  110. package/foundation/config/project.d.mts +16 -2
  111. package/foundation/config/project.mjs +40 -6
  112. package/foundation/config/theme-state.d.mts +9 -0
  113. package/foundation/config/theme-state.mjs +20 -1
  114. package/foundation/discovery/template-adapter.d.mts +12 -1
  115. package/foundation/discovery/template-adapter.mjs +29 -4
  116. package/foundation/discovery/template-icons.d.mts +13 -0
  117. package/foundation/discovery/template-icons.mjs +76 -0
  118. package/foundation/discovery/template-needs.d.mts +7 -0
  119. package/foundation/discovery/template-needs.mjs +117 -8
  120. package/foundation/discovery/template-source-tree.d.mts +5 -1
  121. package/foundation/discovery/template-source-tree.mjs +6 -4
  122. package/foundation/discovery/theme-discovery.d.mts +14 -3
  123. package/foundation/discovery/theme-discovery.mjs +45 -12
  124. package/foundation/doc-compiler/import.mjs +68 -3
  125. package/foundation/doc-compiler/stored-docs.d.mts +27 -0
  126. package/foundation/doc-compiler/stored-docs.mjs +65 -0
  127. package/foundation/fs/fs-error.d.mts +17 -0
  128. package/foundation/fs/fs-error.mjs +34 -0
  129. package/foundation/response/error-codes.d.mts +3 -1
  130. package/foundation/response/error-codes.doc.mjs +13 -1
  131. package/foundation/response/error-codes.mjs +11 -1
  132. package/foundation/response/response-types.doc.mjs +6 -6
  133. package/package.json +6 -7
  134. package/clients/cli/commands/experimental-theme-palette-generate.doc.mjs +0 -73
  135. package/clients/cli/commands/experimental-theme-palette.doc.mjs +0 -37
@@ -2,8 +2,10 @@
2
2
 
3
3
  /**
4
4
  * @file The lookup behind `astryx experimental theme editor how`: a part, a
5
- * family, a setting, an aspect, a plain-words question, a PNG picture's
6
- * colors, or a list of what a change can name.
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. 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,7 +16,9 @@ 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,
@@ -23,51 +27,142 @@ import {
23
27
  familyOf,
24
28
  } from './_tables.mjs';
25
29
  import {colorsAt, decodePng, mainColors} from './_png.mjs';
26
- import {nearest, refuse} from './_settings.mjs';
27
- import {ASPECTS, answerHow, wholeThemeTokens} from './_check.mjs';
30
+ import {loadTheme, nearest, refuse} from './_settings.mjs';
31
+ import {ASPECTS} from './_check.mjs';
28
32
  import {MODAL} from './_compiler.mjs';
29
33
  import {PALETTE_DIALS, mappingRows, paletteFiles} from './_palette.mjs';
30
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';
31
38
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
32
39
 
33
40
  const E = ERROR_CODES;
34
41
 
35
42
  /** What `how --list` takes. */
36
- const HOW_LISTS = ['dials', 'tokens', 'parts', 'families', 'properties'];
43
+ const HOW_LISTS = ['dials', 'tokens', 'parts', 'groups', 'properties'];
44
+
45
+ /** The most points one `--at` reads. */
46
+ const MAX_POINTS = 1000;
47
+
48
+ /** The in-app preview, whose Colors page shows every shade. */
49
+ const PREVIEW = 'astryx experimental theme preview';
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
+ }
37
77
 
38
78
  /**
39
79
  * Explain anything a theme change can name, or answer a question about one:
40
- * a part (what it reads for each aspect, its variants, states and the parts
41
- * inside it), a family (its members), a setting (a dial's rungs, a token's
42
- * type and readers, a CSS property), an aspect (colors, text, corners...: the
43
- * whole-theme tokens and dial), a plain-words question (exact commands), a
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
44
85
  * PNG picture (its main colors, or the color at points), or with `list` a
45
- * list of dials, tokens, parts, families or CSS properties.
86
+ * list of dials, tokens, parts, groups or CSS properties.
46
87
  * @experimental
47
- * @param {string} subject a part, family, setting, aspect, question, or PNG file; with `list`, a filter
88
+ * @param {string} subject a part, group, setting, aspect, question, or PNG file; with `list`, a filter
48
89
  * @param {import('./theme-edit.type.mjs').ThemeEditHowOptions} [options]
49
90
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditHowResponse>}
50
91
  */
51
92
  export async function themeEditHow(subject, options = {}) {
52
- const {cwd = process.cwd(), list, at = [], count} = options;
93
+ const {cwd = process.cwd()} = options;
53
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;
54
137
  const t = (subject ?? '').trim();
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);
55
145
  if (list != null) {
56
146
  if (at.length)
57
147
  refuse(
58
148
  E.ERR_INVALID_ARGUMENT,
59
149
  '--at reads a picture; --list lists names, so drop one of them.',
60
150
  );
61
- return {
62
- type: 'themeEdit.how',
63
- data: {kind: 'list', subject: t, ...(await listItems(list, t, cwd))},
64
- };
151
+ const kind = listKind(list);
152
+ if (kind === 'kinds')
153
+ return {
154
+ kind: 'list',
155
+ subject: t,
156
+ list: 'kinds',
157
+ items: HOW_LISTS.map(name => ({
158
+ name,
159
+ example: `${HOW} --list ${name}`,
160
+ })),
161
+ };
162
+ return {kind: 'list', subject: t, ...(await listItems(kind, t, cwd))};
65
163
  }
66
- if (/\.png$/i.test(t))
67
- return {
68
- type: 'themeEdit.how',
69
- data: {kind: 'picture', subject: t, ...pictureColors(t, cwd, at, count)},
70
- };
164
+ if (isPicture(t, cwd))
165
+ return {kind: 'picture', subject: t, ...pictureColors(t, cwd, at, count)};
71
166
  if (at.length)
72
167
  refuse(
73
168
  E.ERR_INVALID_ARGUMENT,
@@ -76,12 +171,12 @@ export async function themeEditHow(subject, options = {}) {
76
171
  );
77
172
  if (count != null)
78
173
  refuse(E.ERR_INVALID_ARGUMENT, 'A count applies only to a picture.', {
79
- run: [`${HOW} picture.png --at "40,20;300,180"`],
174
+ run: [`${HOW} picture.png 5`],
80
175
  });
81
176
  if (!t) {
82
177
  refuse(
83
178
  E.ERR_MISSING_ARGUMENT,
84
- 'Name a part, a family, a setting, an aspect, a question in quotes, or a PNG picture.',
179
+ 'Name a part, a group, a setting, an aspect, a question in quotes, or a PNG picture.',
85
180
  {
86
181
  run: [
87
182
  `${HOW} card`,
@@ -93,157 +188,594 @@ export async function themeEditHow(subject, options = {}) {
93
188
  }
94
189
  const ctx = await context(cwd);
95
190
  const {C} = ctx;
96
- if (FAMILIES[t]) {
191
+ const env = await howTheme(ctx, cwd, options.theme);
192
+ // Without part data, what each part reads is unknown: answers that need
193
+ // it say so instead of reporting nothing read.
194
+ const unknown = ctx.unchecked
195
+ ? {notChecked: {code: E.ERR_THEME_NOT_CHECKED, cause: ctx.unchecked}}
196
+ : {};
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))};
219
+ }
220
+ if (Object.hasOwn(FAMILIES, key)) {
97
221
  return {
98
- type: 'themeEdit.how',
99
- data: {
100
- kind: 'family',
101
- subject: t,
102
- family: t,
103
- members: FAMILIES[t],
104
- spreads: AUTO_SPREAD.includes(t),
105
- },
222
+ kind: 'group',
223
+ subject: t,
224
+ group: key,
225
+ members: FAMILIES[key],
226
+ spreads: AUTO_SPREAD.includes(key),
106
227
  };
107
228
  }
108
- if (ctx.project.target.has(t)) {
109
- const fam = familyOf(t);
229
+ if (ctx.project.target.has(key))
230
+ return partAnswer(ctx, env, t, key, unknown, themeFields);
231
+ if (key === 'colors' || key === 'palette')
110
232
  return {
111
- type: 'themeEdit.how',
112
- data: {
113
- kind: 'part',
114
- subject: t,
115
- component: ctx.project.target.get(t)?.component ?? null,
116
- recorded: Boolean(C.MAP[t]),
117
- family: fam,
118
- familyMembers: fam ? FAMILIES[fam] : [],
119
- spreads: fam ? AUTO_SPREAD.includes(fam) : false,
120
- variants: C.variantValues(t),
121
- states: ctx.project.target.get(t)?.states ?? [],
122
- reads: Object.fromEntries(
123
- Object.keys(GROUPS).map(g => [g, C.partReads(t, g)]),
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),
124
240
  ),
125
- contains: C.MAP[t]?.contains ?? [],
126
- },
241
+ ],
127
242
  };
128
- }
129
- if (ASPECTS.includes(t)) {
130
- const aspects = t === 'colors' ? ['text', 'background', 'border'] : [t];
131
- const results = aspects.flatMap(a => wholeThemeTokens(ctx, a));
243
+ if (ASPECTS.includes(key)) {
244
+ const results = wholeThemeTokens(ctx, env, key);
132
245
  const dial = /** @type {Record<string, string>} */ ({
133
246
  corners: 'corners',
134
247
  spacing: 'spacing',
135
248
  font: 'font',
136
249
  size: 'text-size',
137
- })[t];
138
- if (t === 'colors' || t === 'text' || t === 'background')
250
+ shadow: 'surfaces',
251
+ border: 'surfaces',
252
+ })[key];
253
+ if (key === 'text' || key === 'background')
139
254
  results.unshift(
140
255
  ...['accent', 'neutral'].map(d => ({
141
256
  text: DIALS[d].help,
142
- commands: DIALS[d].examples.map(e => `${P} ${e}`),
257
+ commands: dialCommands(d),
143
258
  })),
144
259
  );
145
260
  if (dial)
146
- results.unshift({
147
- text: DIALS[dial].help,
148
- commands: DIALS[dial].examples.map(e => `${P} ${e}`),
149
- });
261
+ results.unshift({text: DIALS[dial].help, commands: dialCommands(dial)});
150
262
  results.push({
151
- 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}`,
152
264
  commands: [`${HOW} button`],
153
265
  });
154
- return {
155
- type: 'themeEdit.how',
156
- data: {kind: 'aspect', subject: t, results},
157
- };
266
+ return {kind: 'aspect', subject: t, ...themeFields, results};
158
267
  }
159
- if (t === 'palette') {
160
- const f = paletteFiles('<theme>');
268
+ if (Object.hasOwn(DIALS, key)) {
269
+ const d = DIALS[key];
161
270
  return {
162
- type: 'themeEdit.how',
163
- data: {
164
- kind: 'aspect',
165
- subject: t,
166
- results: [
167
- {
168
- text: `The color dials (${PALETTE_DIALS.join(', ')}) each seed one family of the theme palette. The editor writes ${f.config} in the shape \`theme palette generate\` reads, runs the same generator to write ${f.palette} and its receipt, and points the color tokens at palette stops, light and dark from one color. The generated <theme>.settings.ts imports the palette, so regenerating it moves the theme with it. A token moves to a nearer stop of the same family when it must read: text at 4.5:1 on the surfaces, the focus ring and secondary icons at 3:1, a fill until the text on it reads at 4.5:1. It never mixes a new color. An exact token setting always wins over the palette. Undo a dial to remove its family and its tokens.`,
169
- commands: [
170
- `${P} set <theme> accent "#7c3aed"`,
171
- `${P} set <theme> neutral "#64748b"`,
172
- `${P} show <theme>`,
173
- `${P} set <theme> --color-accent "#7c3aed"`,
174
- `${P} undo <theme> accent`,
175
- ],
176
- },
177
- ...PALETTE_DIALS.map(d => ({
178
- text: `${d}: ${mappingRows(d).join('; ')}`,
179
- commands: DIALS[d].examples.map(e => `${P} ${e}`),
180
- })),
181
- ],
182
- },
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),
183
279
  };
184
280
  }
185
- if (DIALS[t]) {
186
- const d = DIALS[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: []};
187
299
  return {
188
- type: 'themeEdit.how',
189
- data: {
190
- kind: 'setting',
191
- subject: t,
192
- source: 'dial',
193
- values: d.values,
194
- help: d.help,
195
- ...(PALETTE_DIALS.includes(t) ? {stops: mappingRows(t)} : {}),
196
- examples: d.examples.map(e => `${P} ${e}`),
197
- },
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
+ : {}),
198
310
  };
199
311
  }
200
- if (t.startsWith('--') && t in ctx.project.core.tokenDefaults) {
201
- const readers = C.anyReader(t);
202
- const type = C.typeOf(t);
203
- return {
204
- type: 'themeEdit.how',
205
- data: {
206
- 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',
207
342
  subject: t,
208
- source: 'token',
209
- tokenType: type,
210
- default: String(ctx.project.core.tokenDefaults[t]),
211
- perMode: MODAL.has(type),
212
- readBy: readers,
213
- examples: [
214
- `${P} set <theme> ${t} <value>`,
215
- ...(readers[0]
216
- ? [`${P} set <theme> ${t} <value> --on ${readers[0]}`]
217
- : []),
218
- ],
219
- },
220
- };
343
+ understood: {parts: q.parts, aspects: q.aspects},
344
+ ...themeFields,
345
+ results,
346
+ ...unknown,
347
+ };
221
348
  }
222
- if (CSS_PROPERTIES.has(t)) {
223
- const setters = Object.keys(C.MAP).filter(p => t in C.MAP[p].own);
224
- return {
225
- type: 'themeEdit.how',
226
- data: {
227
- kind: 'setting',
228
- subject: t,
229
- source: 'property',
230
- setBy: setters,
231
- examples: [
232
- `${P} set <theme> ${t} <value> --on ${setters[0] ?? '<part>'}`,
233
- ],
234
- },
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,
235
493
  };
236
494
  }
237
- const h = answerHow(ctx, t);
238
495
  return {
239
- type: 'themeEdit.how',
240
- data: {
241
- kind: 'question',
242
- subject: t,
243
- understood: {parts: h.parts, aspects: h.aspects},
244
- results: h.results,
245
- },
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',
246
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} : {}),
688
+ };
689
+ }
690
+
691
+ /**
692
+ * How the theme's colors are made, for `how colors`: one line on the
693
+ * generator, one per color with the shade each token starts from, then
694
+ * vibrancy, every shade, and the exact-token escape hatch.
695
+ * @param {import('./_how-commands.mjs').HowTheme} env
696
+ * @param {(dial: string) => string[]} dialCommands
697
+ * @returns {Array<{text: string, commands: string[]}>}
698
+ */
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;
703
+ return [
704
+ {
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.`,
706
+ commands: [
707
+ ...one([{verb: 'set', thing: 'accent', value: '#7c3aed'}]),
708
+ ...one([{verb: 'set', thing: 'neutral', value: '#64748b'}]),
709
+ ...(env.exists ? [`${P} show ${env.slug}`] : []),
710
+ ],
711
+ },
712
+ ...PALETTE_DIALS.map(d => ({
713
+ text: `${d}: ${mappingRows(d).join('; ')}`,
714
+ commands: dialCommands(d),
715
+ })),
716
+ {
717
+ text: DIALS.vibrancy.help,
718
+ commands: dialCommands('vibrancy'),
719
+ },
720
+ {
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.',
722
+ commands: env.exists ? [`${PREVIEW} add --theme ${env.slug}`] : [],
723
+ },
724
+ {
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.',
726
+ commands: one([{verb: 'set', thing: '--color-accent', value: '#7c3aed'}]),
727
+ },
728
+ ];
729
+ }
730
+
731
+ /**
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[]}>}
737
+ */
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]}`],
756
+ },
757
+ ];
758
+ }
759
+
760
+ /**
761
+ * What `--list` lists: a kind in any case, singular or plural.
762
+ * @param {string} list
763
+ */
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
+ );
247
779
  }
248
780
 
249
781
  /**
@@ -254,18 +786,11 @@ export async function themeEditHow(subject, options = {}) {
254
786
  * @returns {Promise<{list: string, items: Array<Record<string, unknown>>, common?: boolean}>}
255
787
  */
256
788
  async function listItems(kind, filter, cwd) {
257
- if (!HOW_LISTS.includes(kind))
258
- refuse(
259
- E.ERR_INVALID_ARGUMENT,
260
- `--list takes ${HOW_LISTS.join(', ')}${kind ? `, not "${kind}"` : ''}.`,
261
- {
262
- didYouMean: kind ? nearest(kind, HOW_LISTS) : [],
263
- run: [`${HOW} --list dials`],
264
- },
265
- );
266
789
  const f = (/** @type {string} */ x) =>
267
790
  x.toLowerCase().includes(filter.toLowerCase());
268
- if (kind === 'dials')
791
+ if (kind === 'dials') {
792
+ const ctx = await context(cwd);
793
+ const env = await howTheme(ctx, cwd, undefined);
269
794
  return {
270
795
  list: kind,
271
796
  items: Object.entries(DIALS)
@@ -274,10 +799,19 @@ async function listItems(kind, filter, cwd) {
274
799
  name,
275
800
  values: d.values,
276
801
  help: d.help,
277
- 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
+ ),
278
811
  })),
279
812
  };
280
- if (kind === 'families')
813
+ }
814
+ if (kind === 'groups')
281
815
  return {
282
816
  list: kind,
283
817
  items: Object.entries(FAMILIES)
@@ -304,17 +838,26 @@ async function listItems(kind, filter, cwd) {
304
838
  name: k,
305
839
  type: C.typeOf(k),
306
840
  default: String(ctx.project.core.tokenDefaults[k]),
307
- readBy: C.anyReader(k).length,
841
+ readBy: ctx.unchecked ? null : C.anyReader(k).length,
308
842
  })),
309
843
  };
310
844
  }
311
- 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
+ }
312
855
  return {
313
856
  list: kind,
314
- items: targets.map(x => ({
857
+ items: [...byKey.values()].map(x => ({
315
858
  name: x.key,
316
- component: x.component,
317
- family: familyOf(x.key),
859
+ component: x.components.join(', '),
860
+ group: familyOf(x.key),
318
861
  variants: C.variantValues(x.key),
319
862
  states: x.states,
320
863
  recorded: Boolean(C.MAP[x.key]),
@@ -324,24 +867,44 @@ async function listItems(kind, filter, cwd) {
324
867
 
325
868
  /**
326
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.
327
871
  * @param {string[]} at
872
+ * @returns {Array<{x: number, y: number}>}
328
873
  */
329
874
  export function parsePoints(at) {
330
- const nums = at
875
+ const words = at
331
876
  .join(' ')
332
- .split(/[^\d]+/)
333
- .filter(Boolean)
334
- .map(Number);
335
- 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)
336
904
  refuse(
337
905
  E.ERR_INVALID_ARGUMENT,
338
- `--at takes x,y pairs; "${at.join(' ')}" has an odd count of numbers.`,
339
- {run: [`${HOW} picture.png --at "40,20;300,180"`]},
906
+ `--at reads at most ${MAX_POINTS} points; it got ${points.length}.`,
340
907
  );
341
- /** @type {Array<{x: number, y: number}>} */
342
- const points = [];
343
- for (let i = 0; i < nums.length; i += 2)
344
- points.push({x: nums[i], y: nums[i + 1]});
345
908
  return points;
346
909
  }
347
910
 
@@ -352,14 +915,38 @@ export function parsePoints(at) {
352
915
  * @param {string[]} at
353
916
  * @param {number | undefined} count
354
917
  */
355
- function pictureColors(file, cwd, at, count = 14) {
918
+ function pictureColors(file, cwd, at, count) {
356
919
  const abs = path.resolve(cwd, file);
357
920
  if (!fs.existsSync(abs) || !fs.statSync(abs).isFile())
358
- throw new AstryxError(`${file} does not exist.`, [], E.ERR_FILE_NOT_FOUND);
359
- 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))
360
932
  refuse(
361
933
  E.ERR_INVALID_ARGUMENT,
362
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.`,
363
950
  );
364
951
  /** @type {import('./_png.mjs').Picture} */
365
952
  let pic;
@@ -372,19 +959,33 @@ function pictureColors(file, cwd, at, count = 14) {
372
959
  E.ERR_INVALID_ARGUMENT,
373
960
  );
374
961
  }
375
- 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
+ );
376
976
  return {
377
977
  file,
378
978
  width: pic.width,
379
979
  height: pic.height,
380
980
  colors: null,
381
- points: colorsAt(pic, parsePoints(at)),
981
+ points: colorsAt(pic, points),
382
982
  };
983
+ }
383
984
  return {
384
985
  file,
385
986
  width: pic.width,
386
987
  height: pic.height,
387
- colors: mainColors(pic, count),
988
+ colors: mainColors(pic, count ?? 14),
388
989
  points: null,
389
990
  };
390
991
  }