@astryxdesign/cli 0.7.15 → 0.7.16-canary.g8514aae

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 (116) hide show
  1. package/README.md +5 -3
  2. package/api/component/_adapter.d.mts +1 -1
  3. package/api/component/_adapter.mjs +28 -1
  4. package/api/doctor/_adapter.d.mts +17 -0
  5. package/api/doctor/_adapter.mjs +35 -0
  6. package/api/doctor/doctor.mjs +18 -4
  7. package/api/integration/validate-integration.mjs +1 -1
  8. package/api/theme/_adapter.d.mts +5 -2
  9. package/api/theme/_adapter.mjs +43 -12
  10. package/api/theme/build/build.d.mts +1 -21
  11. package/api/theme/build/build.mjs +149 -37
  12. package/api/theme/eject/eject.mjs +22 -1
  13. package/api/theme/template/template.d.mts +19 -0
  14. package/api/theme/template/template.mjs +91 -19
  15. package/api/theme/theme.type.d.mts +5 -1
  16. package/api/theme/theme.type.mjs +2 -1
  17. package/api/theme/themeBuild.doc.mjs +3 -3
  18. package/api/theme/themeEject.doc.mjs +1 -1
  19. package/api/theme/themeTemplate.doc.mjs +9 -3
  20. package/api/theme-edit/_adapter.d.mts +21 -0
  21. package/api/theme-edit/_adapter.mjs +176 -22
  22. package/api/theme-edit/_check.d.mts +7 -0
  23. package/api/theme-edit/_check.mjs +1050 -173
  24. package/api/theme-edit/_color.d.mts +2 -8
  25. package/api/theme-edit/_color.mjs +292 -219
  26. package/api/theme-edit/_compiler.d.mts +1 -0
  27. package/api/theme-edit/_compiler.mjs +20 -1
  28. package/api/theme-edit/_context.d.mts +21 -0
  29. package/api/theme-edit/_context.mjs +235 -12
  30. package/api/theme-edit/_css.d.mts +50 -1
  31. package/api/theme-edit/_css.mjs +310 -28
  32. package/api/theme-edit/_edit.d.mts +9 -0
  33. package/api/theme-edit/_edit.mjs +907 -123
  34. package/api/theme-edit/_how-commands.d.mts +11 -26
  35. package/api/theme-edit/_how-commands.mjs +30 -2
  36. package/api/theme-edit/_how-question.d.mts +7 -0
  37. package/api/theme-edit/_how-question.mjs +1304 -176
  38. package/api/theme-edit/_how.mjs +144 -30
  39. package/api/theme-edit/_palette.d.mts +6 -0
  40. package/api/theme-edit/_palette.mjs +164 -62
  41. package/api/theme-edit/_parts.d.mts +16 -0
  42. package/api/theme-edit/_parts.mjs +49 -1
  43. package/api/theme-edit/_png.mjs +19 -14
  44. package/api/theme-edit/_preview-app.mjs +514 -27
  45. package/api/theme-edit/_preview.d.mts +11 -0
  46. package/api/theme-edit/_preview.mjs +245 -24
  47. package/api/theme-edit/_project.d.mts +11 -0
  48. package/api/theme-edit/_project.mjs +35 -9
  49. package/api/theme-edit/_settings.d.mts +122 -5
  50. package/api/theme-edit/_settings.mjs +1363 -71
  51. package/api/theme-edit/_tables.d.mts +19 -0
  52. package/api/theme-edit/_tables.mjs +205 -149
  53. package/api/theme-edit/_vet.d.mts +42 -0
  54. package/api/theme-edit/_vet.mjs +144 -0
  55. package/api/theme-edit/theme-edit.type.d.mts +2 -1
  56. package/api/theme-edit/theme-edit.type.mjs +1 -1
  57. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  58. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  59. package/assets/docs/tree/single-component.doc.mjs +11 -2
  60. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  61. package/assets/docs.generated.json +2 -2
  62. package/assets/preview-app/next.config.mjs +7 -1
  63. package/assets/preview-app/src/app/globals.css +1 -0
  64. package/assets/self-audit.generated.json +1 -1
  65. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  66. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  67. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  68. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  69. package/assets/templates/components.generated.json +1 -1
  70. package/authoring/doctypes/_schema.d.mts +52 -5
  71. package/authoring/doctypes/_schema.mjs +62 -7
  72. package/authoring/doctypes/base/type.ts +10 -0
  73. package/authoring/doctypes/component/component.doc.mjs +1 -1
  74. package/authoring/doctypes/function/function.doc.mjs +6 -0
  75. package/authoring/doctypes/function/type.ts +3 -0
  76. package/authoring/doctypes/legacy.mjs +5 -1
  77. package/authoring/index.d.ts +1 -0
  78. package/clients/cli/build-id.generated.json +1 -1
  79. package/clients/cli/commands/doctor.doc.mjs +2 -2
  80. package/clients/cli/commands/experimental/theme.mjs +188 -37
  81. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  82. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +1 -1
  83. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +2 -2
  84. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  85. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  86. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  87. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  88. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  89. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  90. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  91. package/clients/cli/commands/theme.mjs +89 -6
  92. package/clients/cli/formatters/index.mjs +7 -4
  93. package/clients/cli/lib/cli-error.mjs +9 -3
  94. package/clients/cli/lib/component-format.mjs +27 -9
  95. package/clients/cli/lib/json-shim.mjs +40 -2
  96. package/clients/cli/manifest.generated.json +1 -1
  97. package/foundation/config/project.mjs +50 -14
  98. package/foundation/discovery/theme-discovery.d.mts +5 -1
  99. package/foundation/discovery/theme-discovery.mjs +24 -3
  100. package/foundation/fs/gather-cache.d.mts +9 -2
  101. package/foundation/fs/gather-cache.mjs +36 -10
  102. package/foundation/fs/paths.d.mts +16 -0
  103. package/foundation/fs/paths.mjs +25 -0
  104. package/foundation/render/host-exit.d.mts +8 -0
  105. package/foundation/render/host-exit.mjs +11 -0
  106. package/foundation/render/page-host.mjs +56 -10
  107. package/foundation/render/page-worker.mjs +14 -0
  108. package/foundation/render/render-page.mjs +37 -2
  109. package/foundation/response/error-codes.d.mts +2 -1
  110. package/foundation/response/error-codes.d.ts +1 -0
  111. package/foundation/response/error-codes.doc.mjs +5 -0
  112. package/foundation/response/error-codes.mjs +3 -0
  113. package/foundation/response/json.d.mts +15 -0
  114. package/foundation/response/json.mjs +52 -1
  115. package/foundation/response/response-types.doc.mjs +1 -1
  116. package/package.json +7 -6
@@ -11,11 +11,14 @@
11
11
 
12
12
  import * as fs from 'node:fs';
13
13
  import * as path from 'node:path';
14
+ import {partForWord} from './_how-question.mjs';
14
15
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
15
- import {baseThemeFile} from './_project.mjs';
16
+ import {baseInstalled, baseThemeFile} from './_project.mjs';
16
17
  import {levenshteinDistance} from '../../foundation/text/levenshtein.mjs';
17
18
  import {
19
+ withFallbacks,
18
20
  MATH_FUNCTION,
21
+ cssNumber,
19
22
  belowRange,
20
23
  fontShorthandParts,
21
24
  cssProperties,
@@ -28,6 +31,7 @@ import {
28
31
  propertyGrammar,
29
32
  takesPercentage,
30
33
  } from './_css.mjs';
34
+ import {multipliedTokens} from './_parts.mjs';
31
35
  import {
32
36
  AUTO_SPREAD,
33
37
  COLOR_PROP_PARTS,
@@ -50,7 +54,10 @@ import {
50
54
  SPACING,
51
55
  TEXT_SIZE,
52
56
  THING_HINTS,
57
+ TYPE_STYLES,
53
58
  familyOf,
59
+ wordTable,
60
+ WRAPPED_PARTS,
54
61
  } from './_tables.mjs';
55
62
  import {
56
63
  COLOR_NAMES,
@@ -83,6 +90,10 @@ import {
83
90
  radiusTokenOf,
84
91
  focusStateOf,
85
92
  valueProblem,
93
+ partComponentDocs,
94
+ themeFiles,
95
+ ownSourceTokenValues,
96
+ cssFamily,
86
97
  } from './_settings.mjs';
87
98
  import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
88
99
 
@@ -104,6 +115,21 @@ function tokenPx(base, token) {
104
115
  return lengthPx(v);
105
116
  }
106
117
 
118
+ /**
119
+ * The `type` preset nearest a scale ratio typed as a number (1.3 is
120
+ * editorial), or null for a number that is no ratio (16).
121
+ * @param {string} v
122
+ * @returns {string | null}
123
+ */
124
+ function ratioPreset(v) {
125
+ if (!/^\d+(\.\d+)?$/.test(v)) return null;
126
+ const r = Number(v);
127
+ if (!(r > 1 && r <= 2)) return null;
128
+ return Object.entries(TYPE_STYLES).reduce((a, b) =>
129
+ Math.abs(b[1].ratio - r) < Math.abs(a[1].ratio - r) ? b : a,
130
+ )[0];
131
+ }
132
+
107
133
  /**
108
134
  * A `set` (or `undo`) command for a setting, with its scope, to suggest.
109
135
  * @param {string} slug
@@ -112,7 +138,7 @@ function tokenPx(base, token) {
112
138
  * @param {{on?: string, when?: string, state?: string, mode?: string, only?: boolean}} s
113
139
  * @param {boolean} [unset]
114
140
  */
115
- const setLine = (slug, thing, value, s, unset = false) =>
141
+ export const setLine = (slug, thing, value, s, unset = false) =>
116
142
  `${P} ${unset ? 'undo' : 'set'} ${slug} ${thing}${value ? ` ${quoteCommandArgument(value)}` : ''}${s.on ? ` --on ${s.on}` : ''}${s.when ? ` --when ${s.when}` : ''}${s.state ? ` --state ${s.state}` : ''}${s.mode ? ` --mode ${s.mode}` : ''}${s.only ? ' --only' : ''}`;
117
143
 
118
144
  /** @param {string} v */
@@ -121,6 +147,213 @@ const cornerPxOf = v =>
121
147
 
122
148
  const E = ERROR_CODES;
123
149
 
150
+ /**
151
+ * The fallbacks of the var() calls inside a value that is not one var()
152
+ * alone (`calc(var(--x, 4px) * 2)`), in order. A var() with an empty
153
+ * fallback (`var(--x,)`) gives ''.
154
+ * @param {string} value
155
+ * @returns {Array<{fallback: string, within: string[]}>} each fallback, with
156
+ * the names of the functions around its var(), innermost first
157
+ */
158
+ function innerVarFallbacks(value) {
159
+ const text = value.trim();
160
+ if (/^var\(/i.test(text) && matchingParen(text, 3) === text.length - 1)
161
+ return [];
162
+ /** @type {Array<{fallback: string, within: string[]}>} */
163
+ const out = [];
164
+ const re = /\bvar\(/gi;
165
+ let m;
166
+ while ((m = re.exec(text))) {
167
+ const open = m.index + m[0].length - 1;
168
+ const close = matchingParen(text, open);
169
+ if (close < 0) break;
170
+ const inner = text.slice(open + 1, close);
171
+ let depth = 0;
172
+ for (let i = 0; i < inner.length; i += 1) {
173
+ const c = inner[i];
174
+ if (c === '(') depth += 1;
175
+ else if (c === ')') depth -= 1;
176
+ else if (c === ',' && depth === 0) {
177
+ out.push({
178
+ fallback: inner.slice(i + 1).trim(),
179
+ within: enclosingFunctions(text, m.index),
180
+ });
181
+ break;
182
+ }
183
+ }
184
+ }
185
+ return out;
186
+ }
187
+
188
+ /**
189
+ * The names of the functions whose parentheses are open at `at`, innermost
190
+ * first.
191
+ * @param {string} text
192
+ * @param {number} at
193
+ * @returns {string[]}
194
+ */
195
+ function enclosingFunctions(text, at) {
196
+ /** @type {string[]} */
197
+ const open = [];
198
+ for (let i = 0; i < at; i += 1) {
199
+ if (text[i] === '(')
200
+ open.push(/([a-z-]*)$/i.exec(text.slice(0, i))?.[1] ?? '');
201
+ else if (text[i] === ')') open.pop();
202
+ }
203
+ return open.reverse();
204
+ }
205
+
206
+ /**
207
+ * The index of the parenthesis that closes the one at `open`, or -1.
208
+ * @param {string} text
209
+ * @param {number} open
210
+ */
211
+ function matchingParen(text, open) {
212
+ let depth = 0;
213
+ for (let i = open; i < text.length; i += 1) {
214
+ if (text[i] === '(') depth += 1;
215
+ else if (text[i] === ')') {
216
+ depth -= 1;
217
+ if (depth === 0) return i;
218
+ }
219
+ }
220
+ return -1;
221
+ }
222
+
223
+ /**
224
+ * A text size written another way (20px, 2e1, +20, 1.25rem, 125%, `20 px`,
225
+ * `1,25rem`) as the body size in pixels text-size takes, kept to its 10 to
226
+ * 32 (a size past an end is that end); null when it reads as no size.
227
+ * @param {string} v
228
+ * @returns {number | null}
229
+ */
230
+ function textSizePx(v) {
231
+ const m = /^\+?(\d*\.?\d+(?:e[+-]?\d+)?)(px|rem|em|%)?$/i.exec(
232
+ typedPlain(v)
233
+ .replace(/(\d)\.(?=[a-z%]*$)/i, '$1')
234
+ .replace(/\s+/g, '')
235
+ .replace(/^(\d+),(\d+)/, '$1.$2'),
236
+ );
237
+ if (!m) return null;
238
+ const unit = (m[2] ?? '').toLowerCase();
239
+ const n =
240
+ Number(m[1]) * (/r?em/.test(unit) ? 16 : unit === '%' ? 16 / 100 : 1);
241
+ const px = Math.round(n * 100) / 100;
242
+ return Math.max(10, Math.min(32, px));
243
+ }
244
+
245
+ /**
246
+ * A value as it reads once what an input method or a stylesheet adds is
247
+ * taken off: full-width digits, letters and signs (`18`, `#`) as their
248
+ * plain forms, and CSS comments.
249
+ * @param {string} v
250
+ */
251
+ function typedPlain(v) {
252
+ return v
253
+ .normalize('NFKC')
254
+ .replace(/\/\*[\s\S]*?\*\//g, ' ')
255
+ .replace(/\s+/g, ' ')
256
+ .trim();
257
+ }
258
+
259
+ /**
260
+ * The values a value may have meant, when what is wrong is how it was
261
+ * typed: plain (full-width characters, comments and a trailing `;` gone,
262
+ * quotes around a whole non-font value dropped), and for a font list each
263
+ * family quoted as CSS needs it (`Font Awesome 6 Free`). Only values that
264
+ * differ from the one typed.
265
+ * @param {string} type
266
+ * @param {string} value
267
+ */
268
+ function valueMeant(type, value) {
269
+ let p = typedPlain(value)
270
+ .replace(/;+\s*$/, '')
271
+ .trim();
272
+ const q = /^(["'])(.*)\1$/.exec(p);
273
+ if (q && type !== 'font') p = q[2].trim();
274
+ const out = [p];
275
+ if (type === 'font' || type === 'font-family')
276
+ out.push(
277
+ p
278
+ .split(',')
279
+ .map(f => cssFamily(f.trim().replace(/^["']|["']$/g, ''), true))
280
+ .join(', '),
281
+ );
282
+ return [...new Set(out)].filter(x => x && x !== value.trim());
283
+ }
284
+
285
+ /** The size units a typo is read against. */
286
+ const SIZE_UNITS = ['px', 'rem', 'em', '%', 'vh', 'vw', 'ch'];
287
+
288
+ /**
289
+ * The size meant by a value one slip away from one: a space inside
290
+ * (`16 px`), a decimal comma (`1,5rem`), a doubled or mistyped unit
291
+ * (`16pxx`), a dot with no digit after it (`1.px`); null when none reads.
292
+ * @param {string} v
293
+ * @param {(x: string) => boolean} ok
294
+ */
295
+ function sizeMeant(v, ok) {
296
+ const t = v.trim();
297
+ const n = typedPlain(t);
298
+ const tries = [
299
+ n,
300
+ n.replace(/(\d)\.(?=[a-z%]|$)/gi, '$1'),
301
+ t.replace(/(\d)\.(?=[a-z%]|$)/gi, '$1'),
302
+ t.replace(/\s+/g, ''),
303
+ t.replace(/^([+-]?\d+),(\d+)/, '$1.$2').replace(/\s+/g, ''),
304
+ mathSpaced(t),
305
+ ];
306
+ const m = /^([+-]?\d*\.?\d+)\s*([a-z%]+)$/i.exec(
307
+ t.replace(/^([+-]?\d+),(\d+)/, '$1.$2'),
308
+ );
309
+ if (m) {
310
+ // A unit typed with a letter too many (pxx, remm, pxs).
311
+ const unit = [...SIZE_UNITS]
312
+ .sort((a, b) => b.length - a.length)
313
+ .find(u => m[2].toLowerCase().startsWith(u));
314
+ if (unit) tries.push(`${m[1]}${unit}`);
315
+ }
316
+ return tries.find(x => x !== t && ok(x)) ?? null;
317
+ }
318
+
319
+ /**
320
+ * A math function with the spaces CSS needs around `+` and `-` put back
321
+ * (`calc(1rem+2px)` is `calc(1rem + 2px)`); the value as it is otherwise.
322
+ * @param {string} v
323
+ */
324
+ function mathSpaced(v) {
325
+ if (!/^(calc|min|max|clamp)\(/i.test(v) || /\bvar\(/i.test(v)) return v;
326
+ return v.replace(/(\d(?<![\d.]e)|[%a-z)])([+-])(?=[\d.(])/gi, '$1 $2 ');
327
+ }
328
+
329
+ /**
330
+ * The number meant by a value one slip away from one: a unit on a number
331
+ * (`700px`), a decimal comma (`1,5`), letter O for zero (`7OO`), a weight
332
+ * past the range (`1001` is 1000), a math function with no spaces around
333
+ * `+` or `-`; null when none reads.
334
+ * @param {string} v
335
+ * @param {string} name the token
336
+ * @param {(x: string) => boolean} ok
337
+ */
338
+ function numberMeant(v, name, ok) {
339
+ const t = v.trim();
340
+ const plain = typedPlain(t).replace(/(\d)\.$/, '$1');
341
+ const comma = plain.replace(/^([+-]?\d+),(\d+)/, '$1.$2');
342
+ const tries = [
343
+ /^[\doO.]+$/.test(plain) && /\d/.test(plain)
344
+ ? plain.replace(/[oO]/g, '0')
345
+ : plain,
346
+ comma.replace(/^([+-]?\d*\.?\d+)\s*[a-z]+$/i, '$1'),
347
+ comma,
348
+ mathSpaced(t),
349
+ ];
350
+ if (/weight/.test(name)) {
351
+ const n = Number(tries[1]);
352
+ if (Number.isFinite(n)) tries.push(String(Math.min(1000, Math.max(1, n))));
353
+ }
354
+ return tries.find(x => x !== t && ok(x)) ?? null;
355
+ }
356
+
124
357
  /**
125
358
  * The value to carry into a suggestion for another dial: the one given when
126
359
  * that dial takes it, else the dial's example.
@@ -223,6 +456,32 @@ export function storedProblems(ctx, slug, data, skip = '') {
223
456
  !(s.thing === 'font' && FONT_ROLES.includes(s.on))
224
457
  )
225
458
  return scope(`there is no part or group "${s.on}"`);
459
+ // A token that is no design token, or a part property that is no
460
+ // CSS property or names no part, styles nothing: reported, never
461
+ // built.
462
+ if (s.source === 'token' && !(s.thing in TOKENS))
463
+ return {setting: s, why: `${s.thing} is not a design token`};
464
+ if (s.source === 'property' && !s.on)
465
+ return {
466
+ setting: s,
467
+ why: `${s.thing} is a CSS property, so it needs a part (--on)`,
468
+ };
469
+ if (
470
+ s.source === 'property' &&
471
+ !s.thing.startsWith('--') &&
472
+ !cssProperties().has(s.thing)
473
+ )
474
+ return {setting: s, why: `${s.thing} is not a CSS property`};
475
+ // A value its CSS grammar does not take (a hand edit: padding
476
+ // banana) is dropped by the browser: reported by name, never built.
477
+ if (s.source === 'property' && !s.thing.startsWith('--')) {
478
+ const bad = propertyProblem(s.thing, String(s.value ?? ''));
479
+ if (bad)
480
+ return {
481
+ setting: s,
482
+ why: `${s.thing} takes ${bad.takes}, not "${String(s.value ?? '').slice(0, 60)}"`,
483
+ };
484
+ }
226
485
  if (s.source === 'dial' && s.on && WHOLE_ONLY.includes(s.thing))
227
486
  return scope(`${s.thing} applies to the whole theme, not to ${s.on}`);
228
487
  if (s.mode && s.source === 'dial' && !PALETTE_DIALS.includes(s.thing))
@@ -240,6 +499,22 @@ export function storedProblems(ctx, slug, data, skip = '') {
240
499
  })();
241
500
  if (problem) found.push(problem);
242
501
  }
502
+ // A font dial is checked as set checks it (a CSS keyword, a size or a
503
+ // whole CSS font value is no family).
504
+ for (const s of data.settings) {
505
+ if (s.source !== 'dial' || s.thing !== 'font' || s.thing === skip) continue;
506
+ try {
507
+ checkSetting(ctx, slug, data, 'font', s.value, {on: s.on});
508
+ } catch (e) {
509
+ found.push({
510
+ setting: s,
511
+ why:
512
+ e instanceof Error
513
+ ? e.message.replace(/ Nothing was changed\.$/, '')
514
+ : String(e),
515
+ });
516
+ }
517
+ }
243
518
  for (const s of data.settings) {
244
519
  if (s.source !== 'token' || s.thing === skip || !(s.thing in TOKENS))
245
520
  continue;
@@ -252,8 +527,9 @@ export function storedProblems(ctx, slug, data, skip = '') {
252
527
  ctx.C.typeOf,
253
528
  slug,
254
529
  ctx.C.propsReading(s.thing),
530
+ multipliedTokens(ctx.project).has(s.thing),
255
531
  );
256
- checkCycle(s.thing, s.value, TOKENS, data);
532
+ checkCycle(s.thing, s.value, TOKENS, data, ctx.project.cwd, s);
257
533
  } catch (e) {
258
534
  found.push({
259
535
  setting: s,
@@ -305,6 +581,7 @@ function groupOfPropType(prop) {
305
581
  * @param {(token: string) => string} typeOf
306
582
  * @param {string} slug
307
583
  * @param {string[]} [readers] the CSS properties that read the token
584
+ * @param {boolean} [multiplied] whether Core multiplies the token by a size
308
585
  */
309
586
  function checkTypedValue(
310
587
  type,
@@ -314,13 +591,40 @@ function checkTypedValue(
314
591
  typeOf,
315
592
  slug,
316
593
  readers = [],
594
+ multiplied = false,
317
595
  ) {
596
+ // The value meant, when what is wrong is how it was typed (a trailing
597
+ // `;`, a comment, quotes around it, full-width characters, a font name
598
+ // that needs quotes): the same value, if the token takes it.
599
+ const meant = () => {
600
+ for (const c of valueMeant(type, value))
601
+ try {
602
+ checkTypedValue(
603
+ type,
604
+ c,
605
+ name,
606
+ TOKENS,
607
+ typeOf,
608
+ slug,
609
+ readers,
610
+ multiplied,
611
+ );
612
+ return c;
613
+ } catch {
614
+ // Not this one.
615
+ }
616
+ return null;
617
+ };
318
618
  /** @param {string} what @param {string} example */
319
619
  const bad = (what, example) =>
320
620
  refuse(
321
621
  E.ERR_THEME_BAD_VALUE,
322
622
  `${name} is ${what}; "${value}" is not one.`,
323
- {run: [`${P} set ${slug} ${name} ${quoteCommandArgument(example)}`]},
623
+ {
624
+ run: [
625
+ `${P} set ${slug} ${name} ${quoteCommandArgument(meant() ?? example)}`,
626
+ ],
627
+ },
324
628
  );
325
629
  if (!isSafeValue(value))
326
630
  refuse(
@@ -328,7 +632,7 @@ function checkTypedValue(
328
632
  `"${value}" cannot be a CSS value: it has a ; { } < > or a newline, a comment, !important, or an unclosed bracket or quote.`,
329
633
  {
330
634
  run: [
331
- `${P} set ${slug} ${name} ${quoteCommandArgument(exampleOf(type, name))}`,
635
+ `${P} set ${slug} ${name} ${quoteCommandArgument(meant() ?? exampleOf(type, name))}`,
332
636
  ],
333
637
  },
334
638
  );
@@ -350,6 +654,41 @@ function checkTypedValue(
350
654
  ],
351
655
  },
352
656
  );
657
+ // A var() inside a larger value (calc, max, color-mix) has a fallback of
658
+ // the token's kind too, checked like a whole-value var().
659
+ if (type !== 'other')
660
+ for (const {fallback, within} of innerVarFallbacks(value)) {
661
+ // Inside a color's channels (rgb(var(--r, 0) 0 0)) a fallback is a
662
+ // channel, not a color.
663
+ if (
664
+ type === 'color' &&
665
+ within.some(f =>
666
+ /^(rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)$/i.test(f),
667
+ )
668
+ )
669
+ continue;
670
+ if (fallback === '')
671
+ refuse(
672
+ E.ERR_THEME_BAD_VALUE,
673
+ `${name} is a ${type}; the var() in "${value}" has an empty fallback, which leaves it with no value when the variable is unset.`,
674
+ {
675
+ run: [
676
+ `${P} set ${slug} ${name} ${quoteCommandArgument(exampleOf(type, name))}`,
677
+ ],
678
+ },
679
+ );
680
+ if (!/\bvar\(/i.test(fallback) && !/^[a-z-]+\(/i.test(fallback))
681
+ checkTypedValue(
682
+ type,
683
+ fallback,
684
+ name,
685
+ TOKENS,
686
+ typeOf,
687
+ slug,
688
+ readers,
689
+ multiplied,
690
+ );
691
+ }
353
692
  // A var() naming a design token must name one of the same kind; the
354
693
  // app's own variables are its business.
355
694
  const ref = /^var\(\s*(--[a-z0-9-]+)\s*(,.*)?\)$/i.exec(value.trim());
@@ -364,10 +703,54 @@ function checkTypedValue(
364
703
  ],
365
704
  },
366
705
  );
706
+ // The fallback is what shows when the variable is unset: it must be a
707
+ // value of the token's kind too.
708
+ const fallback = ref[2]?.slice(1).trim();
709
+ if (fallback === '' && type !== 'other')
710
+ refuse(
711
+ E.ERR_THEME_BAD_VALUE,
712
+ `${name} is a ${type}; "${value}" has an empty fallback, which leaves it with no value when the variable is unset.`,
713
+ {
714
+ run: [
715
+ `${P} set ${slug} ${name} ${quoteCommandArgument(exampleOf(type, name))}`,
716
+ ],
717
+ },
718
+ );
719
+ if (fallback)
720
+ checkTypedValue(
721
+ type,
722
+ fallback,
723
+ name,
724
+ TOKENS,
725
+ typeOf,
726
+ slug,
727
+ readers,
728
+ multiplied,
729
+ );
367
730
  return;
368
731
  }
369
732
  if (type === 'color' && !isFixedColor(value)) bad('a color', '#1f2937');
370
- if (type === 'size' && !isSize(value, name)) bad('a size', '6px');
733
+ if (type === 'size' && !isSize(value, name)) {
734
+ // The size meant, when one dot or sign is all that is wrong (1.px).
735
+ const meant = value.trim().replace(/(\d)\.(?=[a-z%]|$)/gi, '$1');
736
+ // A bare number is the size in px.
737
+ // A bare number is the size in px; a minus sign is dropped.
738
+ const plain = value.trim().replace(/^-(?=\d|\.\d)/, '');
739
+ const px = /^[+]?\d*\.?\d+(e[+-]?\d+)?$/i.test(plain)
740
+ ? `${Number(plain)}px`
741
+ : /^\d*\.?\d+[a-z%]+$/i.test(plain) && plain !== value.trim()
742
+ ? plain
743
+ : null;
744
+ const slip = sizeMeant(value, x => isSize(x, name));
745
+ bad(
746
+ 'a size',
747
+ meant !== value.trim() && isSize(meant, name)
748
+ ? meant
749
+ : px && isSize(px, name)
750
+ ? px
751
+ : (slip ?? '6px'),
752
+ );
753
+ }
371
754
  // A percentage reaches every property that reads the token; one that
372
755
  // takes none (a border or outline width, an outline offset) drops it.
373
756
  if (type === 'size' && /%/.test(value.replace(/var\([^)]*\)/g, ''))) {
@@ -379,7 +762,38 @@ function checkTypedValue(
379
762
  );
380
763
  }
381
764
  if (type === 'number' && !isNumber(value, name))
382
- bad('a number', /weight/.test(name) ? '600' : '1.4');
765
+ bad(
766
+ 'a number',
767
+ numberMeant(value, name, x => isNumber(x, name)) ??
768
+ (/weight/.test(name) ? '600' : '1.4'),
769
+ );
770
+ // A token Core's stylesheet multiplies by a size inside calc() (the line
771
+ // heights) takes a number with no unit: there a length, a percentage or
772
+ // normal is invalid.
773
+ const coreDefault = String(TOKENS[name] ?? '').trim();
774
+ const v0 = value.trim();
775
+ const read = cssNumber(v0);
776
+ if (
777
+ type === 'number' &&
778
+ multiplied &&
779
+ !/^var\(--[a-z0-9-]+\)$/i.test(v0) &&
780
+ read?.unit !== '' &&
781
+ !(MATH_FUNCTION.test(v0) && matchType('number', v0) != null)
782
+ ) {
783
+ const unitless =
784
+ read?.unit === 'em'
785
+ ? String(read.value)
786
+ : read?.unit === '%'
787
+ ? String(read.value / 100)
788
+ : coreDefault;
789
+ refuse(
790
+ E.ERR_THEME_BAD_VALUE,
791
+ `${name} takes a number with no unit: Core multiplies it by a text size inside calc() (field heights, dialog headers, code blocks), where "${value}" is invalid. ${unitless === coreDefault ? `Core's own value is ${coreDefault}.` : `${unitless} is the same line height as a number.`}`,
792
+ {
793
+ run: [`${P} set ${slug} ${name} ${quoteCommandArgument(unitless)}`],
794
+ },
795
+ );
796
+ }
383
797
  if (type === 'time' && !isTime(value)) bad('a time up to 60s', '150ms');
384
798
  if (type === 'easing' && !isEasing(value))
385
799
  bad('an easing', 'cubic-bezier(0.2, 0, 0, 1)');
@@ -408,9 +822,13 @@ function isFixedColor(value) {
408
822
  if (/^var\(/.test(v)) return true;
409
823
  if (SYSTEM_COLORS.includes(v)) return true;
410
824
  // Percentages that add up to 0 leave color-mix() no color.
825
+ // A share is 0% to 100%.
411
826
  const zeroMix = (/** @type {string[]} */ colors) => {
412
827
  const pcts = colors.map(c => mixSide(c).pct);
413
- return pcts.every(p => p != null) && pcts.every(p => p === 0);
828
+ return (
829
+ pcts.some(p => p != null && (p < 0 || p > 100)) ||
830
+ (pcts.every(p => p != null) && pcts.every(p => p === 0))
831
+ );
414
832
  };
415
833
  const inner = (/** @type {string} */ fn) =>
416
834
  splitTop(v.slice(fn.length + 1, -1), ',').map(x => x.trim());
@@ -517,18 +935,47 @@ function isShadow(value) {
517
935
 
518
936
  /**
519
937
  * Refuse a value that would read the token itself, through other tokens.
938
+ * A token set on a part (`--on`) overrides only inside that part: there
939
+ * it reads the part's own settings first and the whole theme's after, and
940
+ * a whole-theme value never reads a part's. So a loop counts only when it
941
+ * closes within one scope: a part token that reads a whole-theme token
942
+ * reads the inherited value, which is already resolved.
520
943
  * @param {string} thing
521
944
  * @param {string} value
522
945
  * @param {Record<string, unknown>} TOKENS
523
946
  * @param {import('./_settings.mjs').ThemeData} data
947
+ * @param {string} [cwd] the project, whose `<slug>.theme.ts` tokens win
948
+ * over the settings and are read too
949
+ * @param {{on?: string, state?: string, when?: string}} [scope] where
950
+ * the token is set; none for the whole theme
524
951
  */
525
- function checkCycle(thing, value, TOKENS, data) {
952
+ function checkCycle(thing, value, TOKENS, data, cwd, scope = {}) {
953
+ const own = cwd ? ownSourceTokenValues(cwd, data.name) : {};
954
+ const on = scope.on ?? null;
955
+ const settings = [...data.settings].reverse();
956
+ /**
957
+ * The token's value set on the part, or undefined: a setting with the
958
+ * same state and variant wins over the part's plain one.
959
+ * @param {string} t
960
+ */
961
+ const partValue = t => {
962
+ if (on == null) return undefined;
963
+ const onPart = settings.filter(
964
+ s => s.source === 'token' && s.thing === t && s.on === on,
965
+ );
966
+ const same = onPart.find(
967
+ s =>
968
+ (s.state ?? null) === (scope.state ?? null) &&
969
+ (s.when ?? null) === (scope.when ?? null),
970
+ );
971
+ return (same ?? onPart.find(s => s.state == null && s.when == null))?.value;
972
+ };
526
973
  /** @param {string} t */
527
- const valueOf = t =>
974
+ const globalValue = t =>
528
975
  String(
529
- [...data.settings]
530
- .reverse()
531
- .find(s => s.source === 'token' && s.thing === t && !s.on)?.value ??
976
+ (Object.hasOwn(own, t) ? own[t] : null) ??
977
+ settings.find(s => s.source === 'token' && s.thing === t && !s.on)
978
+ ?.value ??
532
979
  TOKENS[t] ??
533
980
  '',
534
981
  );
@@ -537,23 +984,40 @@ function checkCycle(thing, value, TOKENS, data) {
537
984
  /** @type {string[]} */
538
985
  const path = [];
539
986
  const seen = new Set();
540
- /** @param {string} t @returns {boolean} */
541
- const reaches = t => {
542
- if (t === thing) return true;
543
- if (seen.has(t)) return false;
544
- seen.add(t);
545
- path.push(t);
546
- if (refs(valueOf(t)).some(reaches)) return true;
987
+ /**
988
+ * Whether `t`, read in the part (`inPart`) or the whole theme, reaches
989
+ * the token being set in its own scope.
990
+ * @param {string} t @param {boolean} inPart @returns {boolean}
991
+ */
992
+ const reaches = (t, inPart) => {
993
+ // The token being set is reached only in the scope it is set in.
994
+ if (t === thing && inPart === (on != null)) return true;
995
+ const part = inPart ? partValue(t) : undefined;
996
+ const local = part !== undefined;
997
+ const key = `${local ? 'part' : 'theme'}:${t}`;
998
+ if (seen.has(key)) return false;
999
+ seen.add(key);
1000
+ path.push(
1001
+ local
1002
+ ? `${t} (on ${on})`
1003
+ : Object.hasOwn(own, t)
1004
+ ? `${t} (set in ${data.name}.theme.ts)`
1005
+ : t,
1006
+ );
1007
+ if (
1008
+ refs(local ? String(part) : globalValue(t)).some(r => reaches(r, local))
1009
+ )
1010
+ return true;
547
1011
  path.pop();
548
1012
  return false;
549
1013
  };
550
- if (refs(value).some(reaches))
1014
+ if (refs(value).some(r => reaches(r, on != null)))
551
1015
  refuse(
552
1016
  E.ERR_THEME_BAD_VALUE,
553
1017
  `${thing} would read itself${path.length ? ` through ${path.join(', ')}` : ''}, so it would have no value at all.`,
554
1018
  {
555
1019
  run: [
556
- `${P} set ${data.name} ${thing} <a value that does not read ${thing}>`,
1020
+ `${P} set ${data.name} ${thing} <a value that does not read ${thing}>${on != null ? ` --on ${on}` : ''}`,
557
1021
  ],
558
1022
  },
559
1023
  );
@@ -582,10 +1046,31 @@ function propertyProblem(prop, value) {
582
1046
  const v = value.trim();
583
1047
  const known = propertyGrammar(prop);
584
1048
  if (!known || COLOR_PROPS.test(prop)) return null;
1049
+ // Each var() fallback is what shows when its variable is unset: the
1050
+ // value with the fallbacks in place must be one the property takes too.
1051
+ const unset = withFallbacks(v);
1052
+ if (unset != null && matchValue(prop, v) && !matchValue(prop, unset))
1053
+ return {
1054
+ takes: `a value its CSS grammar takes in each var() fallback too (${grammarText(known)})`,
1055
+ near: initialOf(prop),
1056
+ };
585
1057
  if (matchValue(prop, v))
586
1058
  return belowRange(prop, v)
587
- ? {takes: 'a value of 0 or more', near: null}
1059
+ ? {
1060
+ takes: 'a value of 0 or more',
1061
+ near: v.replace(/(^|[\s(,/])-(?=\.?\d)/g, '$1'),
1062
+ }
588
1063
  : null;
1064
+ // The same value as it was meant to be typed (a font name quoted, a
1065
+ // trailing `;` gone), when the property takes that.
1066
+ const fixed = valueMeant(prop === 'font-family' ? 'font' : 'other', v).find(
1067
+ c => matchValue(prop, c),
1068
+ );
1069
+ if (fixed)
1070
+ return {
1071
+ takes: `a value its CSS grammar takes (${grammarText(known)})`,
1072
+ near: fixed,
1073
+ };
589
1074
  // Only keywords the property takes on their own are offered; the same
590
1075
  // word without its dashes or a trailing -ed/-s comes first (no-wrap is
591
1076
  // nowrap, underlined is underline), then the nearest in spelling.
@@ -602,57 +1087,90 @@ function propertyProblem(prop, value) {
602
1087
  // the property's initial value, or an example of its kind; each checked.
603
1088
  const example = exampleOf(groupOfPropType(prop), prop);
604
1089
  const initial = initialOf(prop);
1090
+ // A bare number on a length property means px (`padding 4` → `4px`, each
1091
+ // number in a list too), when the property takes that.
1092
+ // Each bare number token gets px (a mixed list `4 8px`, `8 / 4`, an
1093
+ // exponent `1e1`), a unit split off by a space (`4 px`) joins its number.
1094
+ const joined = v.replace(/(\d)\s+(px|rem|em|%)\b/gi, '$1$2');
1095
+ const withPx = /\d/.test(joined)
1096
+ ? joined.replace(
1097
+ /(^|[\s/(,])([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(?=$|[\s/),])/gi,
1098
+ (_, pre, num) =>
1099
+ Number(num) === 0 ? `${pre}${num}` : `${pre}${num}px`,
1100
+ )
1101
+ : null;
1102
+ // A suggestion is offered only when the property takes it, in range too.
1103
+ const takes = (/** @type {string | null} */ x) =>
1104
+ x != null && matchValue(prop, x) != null && !belowRange(prop, x);
605
1105
  return {
606
1106
  takes: `a value its CSS grammar takes (${grammarText(known)})`,
607
1107
  near:
608
- near ??
609
- (initial && matchValue(prop, initial) ? initial : null) ??
610
- (matchValue(prop, example) ? example : null),
1108
+ (takes(withPx) ? withPx : null) ??
1109
+ // Below the property's range (a negative width): the same, 0 or more.
1110
+ (withPx && takes(withPx.replace(/(^|[\s/(,])-(?=\.?\d)/g, '$1'))
1111
+ ? withPx.replace(/(^|[\s/(,])-(?=\.?\d)/g, '$1')
1112
+ : null) ??
1113
+ (takes(joined) && joined !== v ? joined : null) ??
1114
+ // Several values on a property that takes one (padding-top with four):
1115
+ // the first of them, when it is one the property takes.
1116
+ (() => {
1117
+ const first = splitTop((withPx ?? joined).trim(), ' ')[0];
1118
+ return first && first !== v && takes(first) ? first : null;
1119
+ })() ??
1120
+ (near && takes(near) ? near : null) ??
1121
+ // A value with numbers never falls back to the property's reset
1122
+ // (padding 0 would remove what was asked for).
1123
+ (/\d/.test(v)
1124
+ ? null
1125
+ : ((takes(initial) ? initial : null) ??
1126
+ (takes(example) ? example : null))),
611
1127
  };
612
1128
  }
613
1129
 
614
1130
  /** Words people use for a dial's values, by dial. */
615
- const DIAL_WORDS = /** @type {Record<string, Record<string, string>>} */ ({
616
- surfaces: {
617
- elevated: 'raised',
618
- elevation: 'raised',
619
- shadow: 'raised',
620
- shadows: 'raised',
621
- lifted: 'raised',
622
- frosted: 'glass',
623
- blur: 'glass',
624
- blurred: 'glass',
625
- translucent: 'glass',
626
- bordered: 'outlined',
627
- border: 'outlined',
628
- borders: 'outlined',
629
- lined: 'outlined',
630
- outline: 'outlined',
631
- plain: 'flat',
632
- minimal: 'flat',
633
- },
634
- buttons: {
635
- uppercase: 'caps',
636
- upper: 'caps',
637
- allcaps: 'caps',
638
- capitals: 'caps',
639
- tint: 'soft',
640
- tinted: 'soft',
641
- subtle: 'soft',
642
- outlined: 'outline',
643
- bordered: 'outline',
644
- ghost: 'outline',
645
- filled: 'solid',
646
- fill: 'solid',
647
- },
648
- mode: {
649
- auto: 'both',
650
- system: 'both',
651
- default: 'both',
652
- light: 'light-only',
653
- dark: 'dark-only',
654
- },
655
- });
1131
+ const DIAL_WORDS = wordTable(
1132
+ /** @type {Record<string, Record<string, string>>} */ ({
1133
+ surfaces: {
1134
+ elevated: 'raised',
1135
+ elevation: 'raised',
1136
+ shadow: 'raised',
1137
+ shadows: 'raised',
1138
+ lifted: 'raised',
1139
+ frosted: 'glass',
1140
+ blur: 'glass',
1141
+ blurred: 'glass',
1142
+ translucent: 'glass',
1143
+ bordered: 'outlined',
1144
+ border: 'outlined',
1145
+ borders: 'outlined',
1146
+ lined: 'outlined',
1147
+ outline: 'outlined',
1148
+ plain: 'flat',
1149
+ minimal: 'flat',
1150
+ },
1151
+ buttons: {
1152
+ uppercase: 'caps',
1153
+ upper: 'caps',
1154
+ allcaps: 'caps',
1155
+ capitals: 'caps',
1156
+ tint: 'soft',
1157
+ tinted: 'soft',
1158
+ subtle: 'soft',
1159
+ outlined: 'outline',
1160
+ bordered: 'outline',
1161
+ ghost: 'outline',
1162
+ filled: 'solid',
1163
+ fill: 'solid',
1164
+ },
1165
+ mode: {
1166
+ auto: 'both',
1167
+ system: 'both',
1168
+ default: 'both',
1169
+ light: 'light-only',
1170
+ dark: 'dark-only',
1171
+ },
1172
+ }),
1173
+ );
656
1174
 
657
1175
  /**
658
1176
  /**
@@ -814,7 +1332,15 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
814
1332
  });
815
1333
  if (flags.on) s.on = flags.on.trim();
816
1334
  if (flags.when) s.when = flags.when.trim();
817
- if (flags.state) s.state = flags.state.trim();
1335
+ // A state in any case or spelling of its words (focusVisible,
1336
+ // focus_visible, 'focus visible') is the state, written as CSS writes it.
1337
+ if (flags.state)
1338
+ s.state = flags.state
1339
+ .trim()
1340
+ .replace(/^:+/, '')
1341
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
1342
+ .replace(/[\s_]+/g, '-')
1343
+ .toLowerCase();
818
1344
  if (flags.only) s.only = true;
819
1345
  if (flags.mode) {
820
1346
  const mode = flags.mode.toLowerCase();
@@ -879,17 +1405,39 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
879
1405
  if (s.on && !isRole && !FAMILIES[s.on]) {
880
1406
  const t = TARGET.get(s.on);
881
1407
  if (!t) {
882
- // Another case of a part or group: that one, as a working command.
883
- const lower = s.on.toLowerCase();
884
- if (TARGET.has(lower) || FAMILIES[lower])
1408
+ // Another case of a part or group, its class name copied from the
1409
+ // page (`.astryx-card`), or its component (`<Card>`, `Card`): that
1410
+ // part, as a working command with every flag kept.
1411
+ const lower = s.on
1412
+ .trim()
1413
+ .replace(/^<\/?\s*|\s*\/?>$/g, '')
1414
+ .replace(/^\./, '')
1415
+ .replace(/^astryx-/, '')
1416
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
1417
+ .toLowerCase();
1418
+ // A plain word how reads as a part or group (checkboxes: checks).
1419
+ const byWord = partForWord(lower);
1420
+ // A plain plural of a part (cards, dialogs, tabs) is that part.
1421
+ const singular = [
1422
+ lower.replace(/ies$/, 'y'),
1423
+ lower.replace(/(ch|sh|x|s)es$/, '$1'),
1424
+ lower.replace(/s$/, ''),
1425
+ ].find(x => x !== lower && (TARGET.has(x) || FAMILIES[x]));
1426
+ const named =
1427
+ TARGET.has(lower) || FAMILIES[lower]
1428
+ ? lower
1429
+ : singular
1430
+ ? singular
1431
+ : byWord && (TARGET.has(byWord) || FAMILIES[byWord])
1432
+ ? byWord
1433
+ : null;
1434
+ if (named)
885
1435
  refuse(
886
1436
  E.ERR_THEME_UNKNOWN_PART,
887
- `"${s.on}" is not a part you can style; part names are lower case: ${lower}.`,
1437
+ `"${s.on}" is not a part name; the part is ${named}.`,
888
1438
  {
889
- didYouMean: [lower],
890
- run: [
891
- `${P} ${unset ? 'undo' : 'set'} ${slug} ${thing}${v ? ` ${quoteCommandArgument(v)}` : ''} --on ${lower}${s.when ? ` --when ${s.when}` : ''}${s.state ? ` --state ${s.state}` : ''}${s.mode ? ` --mode ${s.mode}` : ''}`,
892
- ],
1439
+ didYouMean: [named],
1440
+ run: [setLine(slug, thing, v, {...s, on: named}, unset)],
893
1441
  },
894
1442
  );
895
1443
  refuse(
@@ -902,7 +1450,7 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
902
1450
  ...Object.keys(FAMILIES),
903
1451
  ]),
904
1452
  run: [
905
- `${HOW} --list parts ${s.on.toLowerCase().replace(/s$/, '').split('-')[0]}`,
1453
+ `${HOW} --list parts ${quoteCommandArgument(lower.replace(/s$/, '').split('-')[0] || 'button')}`,
906
1454
  `${HOW} ${quoteCommandArgument(s.on)}`,
907
1455
  ],
908
1456
  },
@@ -931,20 +1479,37 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
931
1479
  );
932
1480
  }
933
1481
  const states = [...t.states, ...COMMON_STATES];
1482
+ // Other words for a state, mapped to the one the part has; with none
1483
+ // near, the list of its states (never a guess such as hover).
1484
+ const SYNONYMS = wordTable(
1485
+ /** @type {Record<string, string[]>} */ ({
1486
+ pressed: ['active'],
1487
+ press: ['active'],
1488
+ down: ['active'],
1489
+ clicked: ['active'],
1490
+ hovered: ['hover'],
1491
+ focused: ['focus-visible', 'focus-within', 'focus'],
1492
+ checked: ['checked', 'selected'],
1493
+ selected: ['selected', 'checked'],
1494
+ open: ['open', 'expanded'],
1495
+ expanded: ['expanded', 'open'],
1496
+ inactive: ['disabled'],
1497
+ }),
1498
+ );
1499
+ const meant =
1500
+ (SYNONYMS[String(s.state ?? '').toLowerCase()] ?? []).find(x =>
1501
+ states.includes(x),
1502
+ ) ?? nearest(String(s.state ?? ''), states)[0];
934
1503
  if (s.state && !states.includes(s.state))
935
1504
  refuse(
936
1505
  E.ERR_THEME_UNKNOWN_STATE,
937
1506
  `"${s.state}" is not a state of ${s.on}. States: ${states.join(', ')}.`,
938
1507
  {
939
- didYouMean: nearest(s.state, states),
1508
+ ...(meant ? {didYouMean: [meant]} : {}),
940
1509
  run: [
941
- setLine(
942
- slug,
943
- thing,
944
- v,
945
- {...s, state: nearest(s.state, states)[0] ?? 'hover'},
946
- unset,
947
- ),
1510
+ meant
1511
+ ? setLine(slug, thing, v, {...s, state: meant}, unset)
1512
+ : `${HOW} ${quoteCommandArgument(s.on)}`,
948
1513
  ],
949
1514
  },
950
1515
  );
@@ -990,16 +1555,10 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
990
1555
  // The part's component, or the one named like the part (tab is Tab,
991
1556
  // under TabList), takes a disabled prop.
992
1557
  const disables = (/** @type {string} */ t) => {
993
- const comps = /** @type {Record<string, any>} */ (
994
- ctx.project.components ?? {}
995
- );
996
- const pascal = t.replace(/(^|-)([a-z0-9])/g, (_, __, c) =>
997
- c.toUpperCase(),
998
- );
999
1558
  // Or its built module sets aria-disabled (a tab takes it through its
1000
1559
  // other props): what Core renders, read from Core itself.
1001
- const marks = (/** @type {string} */ n) => {
1002
- const at = comps[n]?.importPath?.split('/').pop();
1560
+ const marks = (/** @type {string} */ n, /** @type {any} */ doc) => {
1561
+ const at = doc?.importPath?.split('/').pop();
1003
1562
  const file =
1004
1563
  at && ctx.project.coreDir
1005
1564
  ? path.join(ctx.project.coreDir, 'dist', at, `${n}.js`)
@@ -1012,13 +1571,25 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1012
1571
  return false;
1013
1572
  }
1014
1573
  };
1015
- return [ctx.project.target.get(t)?.component, pascal].some(
1016
- n =>
1017
- n != null &&
1018
- (Object.keys(comps[n]?.props ?? {}).some(p => /disabled/i.test(p)) ||
1019
- marks(n)),
1574
+ return partComponentDocs(ctx, t).some(
1575
+ ({name, doc}) =>
1576
+ Object.keys(doc.props ?? {}).some(p => /disabled/i.test(p)) ||
1577
+ marks(name, doc),
1020
1578
  );
1021
1579
  };
1580
+ // A part holds content that can take focus, so focus-within applies
1581
+ // there: its component takes children or elements in a prop (a dialog,
1582
+ // a section, a chat composer's input).
1583
+ const holdsContent = (/** @type {string} */ t) =>
1584
+ partComponentDocs(ctx, t).some(({doc}) =>
1585
+ Object.entries(doc.props ?? {}).some(
1586
+ ([k, v]) =>
1587
+ k === 'children' ||
1588
+ /\bReact(Node|Element)\b/.test(
1589
+ String(/** @type {any} */ (v)?.type ?? ''),
1590
+ ),
1591
+ ),
1592
+ );
1022
1593
  // A part Core never styles in focus is not what takes focus (the
1023
1594
  // focusable element is inside it, or beside it).
1024
1595
  const focusable = (/** @type {string} */ t) =>
@@ -1026,7 +1597,8 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1026
1597
  const dead = parts.filter(
1027
1598
  t =>
1028
1599
  !states(t).includes(/** @type {string} */ (s.state)) &&
1029
- (Object.keys(own(t)).length === 0 ||
1600
+ ((Object.keys(own(t)).length === 0 &&
1601
+ !(s.state === 'focus-within' && holdsContent(t))) ||
1030
1602
  ((s.state === 'focus' || s.state === 'focus-visible') &&
1031
1603
  !focusable(t)) ||
1032
1604
  (s.state === 'disabled' &&
@@ -1038,7 +1610,8 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1038
1610
  // focusable is inside it (a switch's input sits beside its track).
1039
1611
  (s.state === 'focus-within' &&
1040
1612
  !keys(t, 'focus-within') &&
1041
- !focusable(t))),
1613
+ !focusable(t) &&
1614
+ !holdsContent(t))),
1042
1615
  );
1043
1616
  if (parts.length && dead.length === parts.length) {
1044
1617
  const bare = Object.keys(own(dead[0])).length === 0;
@@ -1069,6 +1642,42 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1069
1642
  );
1070
1643
  }
1071
1644
  }
1645
+ // Core expands a part's padding into its container tokens from a plain
1646
+ // padding only, so in a state that padding never reaches what sits edge
1647
+ // to edge inside it: refused, judged on the part named (a group member
1648
+ // spreads; when only another member is the reason, --only keeps it to
1649
+ // the part named).
1650
+ if (!unset && s.on && s.state && ctx.derived) {
1651
+ const prop =
1652
+ /^padding/.test(thing) || thing === 'spacing' ? 'padding' : null;
1653
+ const expands = (/** @type {string} */ t) =>
1654
+ (ctx.derived?.[t] ?? []).some(
1655
+ d => d.property === prop && d.expand === 'container',
1656
+ );
1657
+ const named = ctx.project.target.get(s.on) ? s.on : null;
1658
+ const hit = prop
1659
+ ? named && expands(named)
1660
+ ? named
1661
+ : partsOf(ctx, s).find(expands)
1662
+ : undefined;
1663
+ if (hit)
1664
+ refuse(
1665
+ E.ERR_THEME_NO_EFFECT,
1666
+ `Core sets ${hit}'s inner padding (what sits edge to edge inside it) from a plain padding setting only, so with --state ${s.state} it would stay behind.`,
1667
+ {
1668
+ // The value as set takes it: a bare number in px.
1669
+ run: (() => {
1670
+ const fixed =
1671
+ thing === 'spacing' ? v : (propertyProblem(thing, v)?.near ?? v);
1672
+ return [
1673
+ named && !expands(named) && !s.only
1674
+ ? setLine(slug, thing, fixed, {...s, only: true})
1675
+ : setLine(slug, thing, fixed, {...s, state: undefined}),
1676
+ ];
1677
+ })(),
1678
+ },
1679
+ );
1680
+ }
1072
1681
  // On a group, a variant or state must belong to at least one member.
1073
1682
  if (s.on && FAMILIES[s.on] && (s.when || s.state)) {
1074
1683
  const members =
@@ -1100,6 +1709,23 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1100
1709
  {run: [`${HOW} ${s.on}`]},
1101
1710
  );
1102
1711
  }
1712
+ // A comparative is a step from the value now (never a rung picked by
1713
+ // spelling, which can go the other way).
1714
+ if (!unset && (thing === 'corners' || thing === 'spacing')) {
1715
+ const w = v.toLowerCase();
1716
+ const MORE =
1717
+ thing === 'corners'
1718
+ ? /^(rounder|softer|bigger|larger|curvier|more rounded)$/
1719
+ : /^(roomier|looser|bigger|larger|wider|airier|more spacious)$/;
1720
+ const LESS =
1721
+ thing === 'corners'
1722
+ ? /^(sharper|squarer|smaller|tighter|harder|less rounded)$/
1723
+ : /^(tighter|denser|smaller|narrower|more compact|closer)$/;
1724
+ if (MORE.test(w))
1725
+ return checkOne(ctx, slug, data, thing, 'more', flags, unset);
1726
+ if (LESS.test(w))
1727
+ return checkOne(ctx, slug, data, thing, 'less', flags, unset);
1728
+ }
1103
1729
  const step = v === 'more' || v === 'less';
1104
1730
  // more/less step a dial with a scale; on a dial of named looks, they name
1105
1731
  // nothing, so the answer is what the dial takes, not one of its values.
@@ -1153,21 +1779,32 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1153
1779
  didYouMean: near,
1154
1780
  run: near[0]
1155
1781
  ? [`${P} set ${slug} ${thing} ${near[0]}`]
1156
- : // A corner word or a size is the corners dial: on the
1157
- // buttons for `buttons`, for the whole theme otherwise.
1158
- CORNERS.some(([n]) => lower.replace(/s$/, '') === n) ||
1159
- lengthPx(lower) != null
1160
- ? [
1161
- setLine(
1162
- slug,
1163
- 'corners',
1164
- CORNERS.find(
1165
- ([n]) => lower.replace(/s$/, '') === n,
1166
- )?.[0] ?? lower,
1167
- thing === 'buttons' ? {on: 'button'} : {},
1168
- ),
1169
- ]
1170
- : [`${HOW} ${thing}`],
1782
+ : // A type-scale ratio (1.25) is the nearest type preset.
1783
+ thing === 'type' && ratioPreset(lower)
1784
+ ? [`${P} set ${slug} type ${ratioPreset(lower)}`]
1785
+ : // A corner word or a size with a unit is the corners dial:
1786
+ // on the buttons for `buttons`, for the whole theme
1787
+ // otherwise. A bare number is no size: the dial's own
1788
+ // words.
1789
+ CORNERS.some(([n]) => lower.replace(/s$/, '') === n) ||
1790
+ (/[a-z%]$/.test(lower) && lengthPx(lower) != null)
1791
+ ? [
1792
+ setLine(
1793
+ slug,
1794
+ 'corners',
1795
+ CORNERS.find(
1796
+ ([n]) => lower.replace(/s$/, '') === n,
1797
+ )?.[0] ?? lower,
1798
+ thing === 'buttons' ? {on: 'button'} : {},
1799
+ ),
1800
+ ]
1801
+ : [
1802
+ ...(/^[+-]?\d*\.?\d+$/.test(lower) ? ok : [])
1803
+ .filter(w => /^[a-z-]+$/.test(w))
1804
+ .slice(0, 4)
1805
+ .map(w => `${P} set ${slug} ${thing} ${w}`),
1806
+ `${HOW} ${thing}`,
1807
+ ],
1171
1808
  },
1172
1809
  );
1173
1810
  }
@@ -1179,9 +1816,24 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1179
1816
  E.ERR_THEME_BAD_VALUE,
1180
1817
  'headings applies to every heading; drop --on. For one heading level use font-weight or letter-spacing --on heading --when level:<1-6>.',
1181
1818
  {
1182
- run: [
1183
- `${P} set ${slug} font-weight 700 --on heading --when level:1`,
1184
- ],
1819
+ // The dial without --on, then the asked weight or tracking on
1820
+ // one level; a word with no meaning here gets neither.
1821
+ run: (() => {
1822
+ const w = String(v ?? '')
1823
+ .trim()
1824
+ .toLowerCase();
1825
+ if (HEADING_WEIGHTS[w] !== undefined)
1826
+ return [
1827
+ `${P} set ${slug} headings ${w}`,
1828
+ `${P} set ${slug} font-weight ${HEADING_WEIGHTS[w]} --on heading --when level:1`,
1829
+ ];
1830
+ if (HEADING_TRACKING[w] !== undefined)
1831
+ return [
1832
+ `${P} set ${slug} headings ${w}`,
1833
+ `${P} set ${slug} letter-spacing ${quoteCommandArgument(HEADING_TRACKING[w])} --on heading --when level:1`,
1834
+ ];
1835
+ return [`${HOW} headings`];
1836
+ })(),
1185
1837
  },
1186
1838
  );
1187
1839
  if (s.mode)
@@ -1209,28 +1861,36 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1209
1861
  }
1210
1862
  if (HEADING_WEIGHTS[v] !== undefined) s.axis = 'weight';
1211
1863
  else if (HEADING_TRACKING[v] !== undefined) s.axis = 'tracking';
1212
- else
1864
+ else {
1865
+ // The word meant: in other letters (BOLD), or the rung nearest a
1866
+ // weight number (800 is heavy); never a rung the other way.
1867
+ const lower = v.trim().toLowerCase();
1868
+ const words = [
1869
+ ...Object.keys(HEADING_WEIGHTS),
1870
+ ...Object.keys(HEADING_TRACKING),
1871
+ ];
1872
+ const weight = /^\d+(\.\d+)?$/.test(lower) ? Number(lower) : null;
1873
+ const meant =
1874
+ words.find(w => w === lower) ??
1875
+ (weight != null
1876
+ ? Object.entries(HEADING_WEIGHTS).reduce((a, b) =>
1877
+ Math.abs(Number(b[1]) - weight) <
1878
+ Math.abs(Number(a[1]) - weight)
1879
+ ? b
1880
+ : a,
1881
+ )[0]
1882
+ : nearest(lower, words)[0]);
1213
1883
  refuse(
1214
1884
  E.ERR_THEME_BAD_VALUE,
1215
- `headings takes ${DIALS.headings.values}, not "${v}".`,
1885
+ `headings takes ${DIALS.headings.values}, not "${v}".${weight != null && meant ? ` ${meant} sets weight ${HEADING_WEIGHTS[meant]}.` : ''}`,
1216
1886
  {
1217
- didYouMean: nearest(v, [
1218
- ...Object.keys(HEADING_WEIGHTS),
1219
- ...Object.keys(HEADING_TRACKING),
1220
- ]),
1221
- run: [
1222
- setLine(
1223
- slug,
1224
- 'headings',
1225
- nearest(v, [
1226
- ...Object.keys(HEADING_WEIGHTS),
1227
- ...Object.keys(HEADING_TRACKING),
1228
- ])[0] ?? Object.keys(HEADING_WEIGHTS)[0],
1229
- s,
1230
- ),
1231
- ],
1887
+ didYouMean: meant ? [meant] : [],
1888
+ run: meant
1889
+ ? [setLine(slug, 'headings', meant, s)]
1890
+ : [`${HOW} headings`],
1232
1891
  },
1233
1892
  );
1893
+ }
1234
1894
  return s;
1235
1895
  }
1236
1896
  if (unset) return s;
@@ -1309,17 +1969,26 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1309
1969
  const edge = /** @type {[string, number]} */ (
1310
1970
  v === 'more' ? L[L.length - 1] : L[0]
1311
1971
  );
1972
+ // The example stays inside what the dial takes (text-size: 10 to
1973
+ // 32); at that end, the exact token takes the size instead.
1974
+ const [lo, hi] = thing === 'text-size' ? [10, 32] : [0, Infinity];
1975
+ const want = Math.round(px + (v === 'more' ? 2 : -2));
1976
+ const atEnd = v === 'more' ? px >= hi : px <= lo;
1312
1977
  const example = String(cur).replace(
1313
1978
  /\d*\.?\d+/,
1314
- String(Math.max(0, Math.round(px + (v === 'more' ? 2 : -2)))),
1979
+ String(Math.max(lo, Math.min(hi, want))),
1315
1980
  );
1316
1981
  refuse(
1317
1982
  E.ERR_THEME_BAD_VALUE,
1318
- `${thing} is ${typeof cur === 'number' ? `${cur}px` : cur}, already ${v === 'more' ? 'above' : 'below'} its ${v === 'more' ? 'largest' : 'smallest'} step (${edge[0]}, ${edge[1]}px), so "${v}" has nowhere to go. Give an exact size.`,
1983
+ `${thing} is ${typeof cur === 'number' ? `${cur}px` : cur}, already ${v === 'more' ? 'above' : 'below'} its ${v === 'more' ? 'largest' : 'smallest'} step (${edge[0]}, ${edge[1]}px), so "${v}" has nowhere to go.${atEnd ? ` It is also the ${v === 'more' ? 'largest' : 'smallest'} size ${thing} takes (${lo} to ${hi}); the base font size token takes any size.` : ' Give an exact size.'}`,
1319
1984
  {
1320
- run: [
1321
- `${P} set ${slug} ${thing} ${quoteCommandArgument(example)}${s.on ? ` --on ${s.on}` : ''}`,
1322
- ],
1985
+ run: atEnd
1986
+ ? [
1987
+ `${P} set ${slug} --font-size-base ${quoteCommandArgument(`${Math.max(1, want)}px`)}`,
1988
+ ]
1989
+ : [
1990
+ `${P} set ${slug} ${thing} ${quoteCommandArgument(example)}${s.on ? ` --on ${s.on}` : ''}`,
1991
+ ],
1323
1992
  },
1324
1993
  );
1325
1994
  }
@@ -1469,10 +2138,15 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1469
2138
  } else {
1470
2139
  // A rung in any case, a size in px written any way: the plain form.
1471
2140
  const lower = v.toLowerCase();
1472
- const px = /^(\d+(?:\.\d+)?|\.\d+)px$/.exec(lower);
2141
+ // Any CSS number in px (2e1px, +4px), the shared length parse.
2142
+ const pxLen = /px$/.test(lower) ? lengthPx(lower) : null;
1473
2143
  if (CORNERS.some(([n]) => n === lower)) s.value = lower;
1474
- else if (px) s.value = `${Number(px[1])}px`;
1475
- else if (lower === '0') s.value = 'square';
2144
+ else if (pxLen != null && pxLen >= 0)
2145
+ s.value =
2146
+ pxLen >= 1000 ? 'pill' : `${Math.round(pxLen * 10000) / 10000}px`;
2147
+ // No rounding, said any way, is square.
2148
+ else if (/^(0|0%|none|sharp|zero|no|flat)$/.test(lower))
2149
+ s.value = 'square';
1476
2150
  else {
1477
2151
  // What it most likely means, as a value corners takes: a simple
1478
2152
  // calc() of px is worked out.
@@ -1574,6 +2248,17 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1574
2248
  run: [setLine(slug, 'spacing', nearFactor, s)],
1575
2249
  },
1576
2250
  );
2251
+ else if (/^(0|none|zero|no|off)$/i.test(v))
2252
+ // Spacing scales the theme's space; it never goes to nothing. The
2253
+ // tightest rung is the nearest that works.
2254
+ refuse(
2255
+ E.ERR_THEME_BAD_VALUE,
2256
+ `spacing scales the theme's space and never removes it; the tightest it goes is ${SPACING[0][0]}. For no space on one part, set padding or gap 0 on it.`,
2257
+ {
2258
+ didYouMean: [SPACING[0][0]],
2259
+ run: [setLine(slug, 'spacing', SPACING[0][0], s)],
2260
+ },
2261
+ );
1577
2262
  else if (!SPACING.some(([n]) => n === v))
1578
2263
  refuse(
1579
2264
  E.ERR_THEME_BAD_VALUE,
@@ -1601,10 +2286,34 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1601
2286
  refuse(
1602
2287
  E.ERR_THEME_BAD_VALUE,
1603
2288
  'text-size applies to the whole theme; for one part use font-size.',
1604
- {run: [`${P} set ${slug} font-size 13px --on ${s.on}`]},
2289
+ {
2290
+ // The asked size on the part: a rung's px (large is 15px), a
2291
+ // number as px; a step (more, less) has no size to carry.
2292
+ run: (() => {
2293
+ const w = String(v ?? '')
2294
+ .trim()
2295
+ .toLowerCase();
2296
+ const rung = TEXT_SIZE.find(([n]) => n === w)?.[1];
2297
+ const px =
2298
+ rung ?? (/^\d+(\.\d+)?(px)?$/.test(w) ? parseFloat(w) : null);
2299
+ return px != null && px > 0
2300
+ ? [setLine(slug, 'font-size', `${px}px`, s)]
2301
+ : [`${HOW} font-size`];
2302
+ })(),
2303
+ },
1605
2304
  );
1606
2305
  if (step) s.value = ladder(TEXT_SIZE, 'medium');
1607
2306
  else if (
2307
+ /^\d+\.\d+$/.test(v.trim()) &&
2308
+ Number(v) >= 10 &&
2309
+ Number(v) <= 32 &&
2310
+ Math.round(Number(v)) !== Number(v)
2311
+ ) {
2312
+ // Core builds the type scale in whole pixels: the size is saved as
2313
+ // the whole pixel it builds, and the result says so.
2314
+ s.value = String(Math.round(Number(v)));
2315
+ s.note = `text-size ${v.trim()} is saved as ${s.value}: the type scale is built in whole pixels`;
2316
+ } else if (
1608
2317
  !TEXT_SIZE.some(([n]) => n === v) &&
1609
2318
  !(/^\d+(\.\d+)?$/.test(v.trim()) && Number(v) >= 10 && Number(v) <= 32)
1610
2319
  )
@@ -1624,7 +2333,19 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1624
2333
  didYouMean: [near],
1625
2334
  run: [`${P} set ${slug} text-size ${near}`],
1626
2335
  }
1627
- : {run: [`${P} set ${slug} text-size 16`]};
2336
+ : {
2337
+ run: [
2338
+ `${P} set ${slug} text-size ${
2339
+ // A size typed full-width or with a trailing dot
2340
+ // (18, 18.) is that size.
2341
+ /^\d+(\.\d+)?\.?$/.test(typedPlain(v)) &&
2342
+ Number(typedPlain(v).replace(/\.$/, '')) >= 10 &&
2343
+ Number(typedPlain(v).replace(/\.$/, '')) <= 32
2344
+ ? String(Number(typedPlain(v).replace(/\.$/, '')))
2345
+ : (textSizePx(v) ?? 16)
2346
+ }`,
2347
+ ],
2348
+ };
1628
2349
  })(),
1629
2350
  );
1630
2351
  else if (!TEXT_SIZE.some(([n]) => n === v))
@@ -1639,7 +2360,7 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1639
2360
  // What the value most likely meant: without quotes, a trailing `;`
1640
2361
  // or `!important`, a bare hex with its #, the opaque color, or the
1641
2362
  // nearest color name.
1642
- const cleaned = v
2363
+ const cleaned = typedPlain(v)
1643
2364
  .replace(/^(["'])(.*)\1$/, '$2')
1644
2365
  .replace(/\s*!important\s*$/i, '')
1645
2366
  .replace(/;+\s*$/, '')
@@ -1697,23 +2418,34 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1697
2418
  },
1698
2419
  );
1699
2420
  s.value = String(next);
1700
- } else if (!/^\d{1,3}$/.test(v) || Number(v) > 100) {
1701
- // A number out of range suggests the nearest one in range.
1702
- const n = Number(v);
1703
- const near = /^[+-]?(\d+\.?\d*|\.\d+)$/.test(v)
1704
- ? Math.max(0, Math.min(100, Math.round(n)))
1705
- : 60;
2421
+ }
2422
+ const colors = data.settings.filter(
2423
+ x => x.source === 'dial' && PALETTE_DIALS.includes(x.thing),
2424
+ );
2425
+ // With no color to saturate, no vibrancy value is suggested.
2426
+ const canApply = colors.some(x => !isGraySeed(seedOf(x.value)));
2427
+ if (!step && canApply && (!/^\d{1,3}$/.test(v) || Number(v) > 100)) {
2428
+ // The value meant: a step in other letters (MORE), or the number
2429
+ // read as CSS reads it (70%, 7e1), kept in range.
2430
+ const word = v.trim().toLowerCase();
2431
+ const n = cssNumber(v);
2432
+ const near = ['more', 'less'].includes(word)
2433
+ ? word
2434
+ : n && (n.unit === '' || n.unit === '%')
2435
+ ? String(Math.max(0, Math.min(100, Math.round(n.value))))
2436
+ : null;
1706
2437
  refuse(
1707
2438
  E.ERR_THEME_BAD_VALUE,
1708
2439
  `vibrancy takes a whole number from 0 (gray) to 100 (most vivid), or more or less, not "${v}".`,
1709
- {run: [`${P} set ${slug} vibrancy ${near}`]},
2440
+ {
2441
+ run: near
2442
+ ? [`${P} set ${slug} vibrancy ${near}`]
2443
+ : [`${HOW} vibrancy`],
2444
+ },
1710
2445
  );
1711
- } else s.value = String(Number(v));
1712
- const colors = data.settings.filter(
1713
- x => x.source === 'dial' && PALETTE_DIALS.includes(x.thing),
1714
- );
2446
+ } else if (!step && /^\d{1,3}$/.test(v)) s.value = String(Number(v));
1715
2447
  // A gray has no color to saturate, so vibrancy changes nothing.
1716
- if (!colors.some(x => !isGraySeed(seedOf(x.value))))
2448
+ if (!canApply)
1717
2449
  refuse(
1718
2450
  E.ERR_THEME_NO_EFFECT,
1719
2451
  colors.length
@@ -1741,7 +2473,7 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1741
2473
  const family = !parts && matchValue('font-family', v);
1742
2474
  const example = `${P} set ${slug} font-family ${quoteCommandArgument(exampleOf('font', 'font-family'))} --on ${s.on}`;
1743
2475
  const runs = parts
1744
- ? parts.system
2476
+ ? parts.system || parts.repeat
1745
2477
  ? [example]
1746
2478
  : Object.entries(parts).map(
1747
2479
  ([k, x]) =>
@@ -1754,9 +2486,55 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1754
2486
  : [example];
1755
2487
  refuse(
1756
2488
  E.ERR_THEME_BAD_VALUE,
1757
- parts?.system
1758
- ? `font --on takes body, heading, or code, and "${v}" is a system font keyword of the CSS font shorthand, which sets every part of the font at once. For one part's font use font-family with a family.`
1759
- : `font --on takes body, heading, or code. For one part's font use font-family${parts ? ', and the other parts of the font shorthand one by one' : ''}.`,
2489
+ parts?.repeat
2490
+ ? `font --on takes body, heading, or code, and "${v}" ${parts.part?.includes(',') ? `gives ${parts.repeat} more times than the parts that take it (${parts.part})` : `gives ${parts.part ?? 'one part of the font'} twice (${parts.repeat} is the second)`}, which no CSS font value does. For one part's font use font-family with a family, and set each other part of the font once.`
2491
+ : parts?.system
2492
+ ? `font --on takes body, heading, or code, and "${v}" is a system font keyword of the CSS font shorthand, which sets every part of the font at once. For one part's font use font-family with a family.`
2493
+ : `font --on takes body, heading, or code. For one part's font use font-family${parts ? ', and the other parts of the font shorthand one by one' : ''}.`,
2494
+ {run: runs},
2495
+ );
2496
+ }
2497
+ // A size, a weight or a whole CSS font value is no family: the font
2498
+ // dial and the roles take the family alone.
2499
+ // A variable is answered below, as the token form.
2500
+ const fontParts =
2501
+ step || /\b(var|env)\(/i.test(v) ? null : fontShorthandParts(v);
2502
+ if (
2503
+ fontParts &&
2504
+ (fontParts.repeat ||
2505
+ fontParts.system ||
2506
+ Object.keys(fontParts).some(k => k !== 'font-family'))
2507
+ ) {
2508
+ const fam = fontParts['font-family'];
2509
+ const on = s.on ? ` --on ${s.on}` : '';
2510
+ /** @type {string[]} */
2511
+ const runs = [
2512
+ `${P} set ${slug} font ${quoteCommandArgument(fam ?? 'inter')}${on}`,
2513
+ ];
2514
+ if (fontParts['font-size'] && (!s.on || s.on === 'body'))
2515
+ runs.push(
2516
+ `${P} set ${slug} --font-size-base ${quoteCommandArgument(fontParts['font-size'])}`,
2517
+ );
2518
+ const w = fontParts['font-weight'];
2519
+ if (w && (!s.on || s.on === 'heading')) {
2520
+ const num =
2521
+ w === 'bold' ? 700 : w === 'normal' ? 400 : Number(w) || null;
2522
+ const rung = num
2523
+ ? Object.entries(HEADING_WEIGHTS).reduce((a, b) =>
2524
+ Math.abs(Number(b[1]) - num) < Math.abs(Number(a[1]) - num)
2525
+ ? b
2526
+ : a,
2527
+ )[0]
2528
+ : null;
2529
+ if (rung) runs.push(`${P} set ${slug} headings ${rung}`);
2530
+ }
2531
+ refuse(
2532
+ E.ERR_THEME_BAD_VALUE,
2533
+ `font${s.on ? ` --on ${s.on}` : ''} takes a family or a preset, and "${v}" ${fam ? 'is a whole CSS font value' : 'is no family'}: ${
2534
+ Object.keys(fontParts)
2535
+ .filter(k => !['font-family', 'repeat', 'system'].includes(k))
2536
+ .join(', ') || 'a keyword'
2537
+ } ${fam ? 'would be read as part of the family name' : 'would be read as a family name'}, and the text would fall back.`,
1760
2538
  {run: runs},
1761
2539
  );
1762
2540
  }
@@ -1876,15 +2654,28 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1876
2654
  .toLowerCase()
1877
2655
  .replace(/^base\s*[=:]\s*/, '')
1878
2656
  .trim();
1879
- const near = [...LIKE, 'none'].includes(meant)
1880
- ? [meant]
1881
- : nearest(meant, [...LIKE, 'none']);
2657
+ // Only a base this project has installed is suggested; a theme
2658
+ // made here is never a base.
2659
+ const bases = [
2660
+ ...LIKE.filter(b => baseInstalled(ctx.project, b)),
2661
+ 'none',
2662
+ ];
2663
+ // The base named in other letters is the one meant; a guess is
2664
+ // only among installed bases.
2665
+ const near = bases.includes(meant) ? [meant] : nearest(meant, bases);
2666
+ const madeHere = fs.existsSync(themeFiles(ctx.project.cwd, v).settings);
1882
2667
  refuse(
1883
2668
  E.ERR_THEME_BAD_VALUE,
1884
- `base takes ${DIALS.base.values}, not "${v}".`,
2669
+ `base takes ${DIALS.base.values}, not "${v}".${madeHere ? ` ${v} is a theme made here, and a theme builds only on a built-in one.` : ''}`,
1885
2670
  {
1886
2671
  didYouMean: near,
1887
- run: near[0] ? [`${P} set ${slug} base ${near[0]}`] : [],
2672
+ // With nothing near, every base that works here, none first.
2673
+ run: near[0]
2674
+ ? [`${P} set ${slug} base ${near[0]}`]
2675
+ : [
2676
+ 'none',
2677
+ ...LIKE.filter(b => baseInstalled(ctx.project, b)),
2678
+ ].map(b => `${P} set ${slug} base ${b}`),
1888
2679
  },
1889
2680
  );
1890
2681
  }
@@ -1965,8 +2756,9 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1965
2756
  C.typeOf,
1966
2757
  slug,
1967
2758
  C.propsReading(thing),
2759
+ multipliedTokens(ctx.project).has(thing),
1968
2760
  );
1969
- checkCycle(thing, v, TOKENS, data);
2761
+ checkCycle(thing, v, TOKENS, data, ctx.project.cwd, s);
1970
2762
  // With no part data, what reads the token is unknown: save, unchecked.
1971
2763
  if (ctx.unchecked) return s;
1972
2764
  const parts = partsOf(ctx, s);
@@ -2101,6 +2893,54 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2101
2893
  s.source = 'property';
2102
2894
  s.thing = prop;
2103
2895
  if (unset) return s;
2896
+ // A part whose visible box is drawn inside its themed wrapper: only
2897
+ // what reaches that box is taken.
2898
+ const wrapped = s.on ? WRAPPED_PARTS[s.on] : undefined;
2899
+ if (wrapped) {
2900
+ const surface =
2901
+ /^(background|border|box-shadow|outline)(-|$)/.test(prop) &&
2902
+ !/radius/.test(prop);
2903
+ const side = /^padding-/.test(prop);
2904
+ const density = prop === 'padding' && /^density:/.test(s.when ?? '');
2905
+ if (surface || side || density)
2906
+ refuse(
2907
+ E.ERR_THEME_BAD_VALUE,
2908
+ surface
2909
+ ? `${s.on}'s theme class is on a transparent wrapper; Core draws ${wrapped.box} inside it, and that box has no class of its own, so ${prop} would paint the wrapper's square corners, not the box. Its colors come from the theme's popover tokens.`
2910
+ : side
2911
+ ? `${s.on}'s theme class is on a transparent wrapper; ${wrapped.box} inside it reads one padding for every side, so a side padding would add a strip outside the box. Set padding (every side).`
2912
+ : `${s.on} sets its own padding on ${wrapped.box} for each density, which a theme padding for one density cannot reach. Set padding for every density.`,
2913
+ {
2914
+ run: surface
2915
+ ? [
2916
+ `${P} set ${slug} --color-background-popover ${quoteCommandArgument('#ffffff')}`,
2917
+ `${HOW} ${s.on}`,
2918
+ ]
2919
+ : [
2920
+ `${P} set ${slug} padding ${quoteCommandArgument(v)} --on ${s.on}`,
2921
+ ],
2922
+ },
2923
+ );
2924
+ }
2925
+ // Core writes a container part's padding to variables of its own, where
2926
+ // a keyword that takes its value from elsewhere means no value at all.
2927
+ if (
2928
+ /^padding/.test(prop) &&
2929
+ /^(inherit|revert|revert-layer)$/i.test(v.trim()) &&
2930
+ (ctx.derived?.[/** @type {string} */ (s.on)] ?? []).some(
2931
+ d => d.property === 'padding' && d.expand,
2932
+ )
2933
+ )
2934
+ refuse(
2935
+ E.ERR_THEME_BAD_VALUE,
2936
+ `${s.on} writes ${prop} to variables of its own, where "${v.trim()}" has nothing to take its value from, so ${s.on} would fall back to its default padding. Give a length, or undo the padding to go back to the base theme's.`,
2937
+ {
2938
+ run: [
2939
+ `${P} set ${slug} ${prop} 0 --on ${s.on}`,
2940
+ `${P} undo ${slug} ${prop} --on ${s.on}`,
2941
+ ],
2942
+ },
2943
+ );
2104
2944
  // Text, headings and links take their color from the color prop.
2105
2945
  const textParts = COLOR_PROP_PARTS;
2106
2946
  if (
@@ -2109,16 +2949,22 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2109
2949
  ) {
2110
2950
  if (partsOf(ctx, s).every(t => textParts.includes(t))) {
2111
2951
  const named = /^color:([\w-]+)$/.exec(s.when ?? '')?.[1];
2952
+ // The typed value goes into the token only when it is a plain color;
2953
+ // else the nearest color name, else an example.
2954
+ const color =
2955
+ v && isColorValue(v) && isFixedColor(v) && !/\bvar\(/i.test(v)
2956
+ ? v
2957
+ : (nearestColorName(v) ?? '#1f2937');
2112
2958
  refuse(
2113
2959
  E.ERR_THEME_NO_EFFECT,
2114
2960
  `${s.on} takes its color from the color prop, which Core sets after part styles, so a color set on ${s.on} never shows. Set the text color token instead.`,
2115
2961
  {
2116
2962
  run: [
2117
- `${P} set ${slug} --color-text-${named ?? 'primary'} ${quoteCommandArgument(v || '#1f2937')}${s.mode ? ` --mode ${s.mode}` : ''}`,
2963
+ `${P} set ${slug} --color-text-${named ?? 'primary'} ${quoteCommandArgument(color)}${s.mode ? ` --mode ${s.mode}` : ''}`,
2118
2964
  ...(named
2119
2965
  ? []
2120
2966
  : [
2121
- `${P} set ${slug} --color-text-secondary ${quoteCommandArgument(v || '#1f2937')}${s.mode ? ` --mode ${s.mode}` : ''}`,
2967
+ `${P} set ${slug} --color-text-secondary ${quoteCommandArgument(color)}${s.mode ? ` --mode ${s.mode}` : ''}`,
2122
2968
  ]),
2123
2969
  ],
2124
2970
  },
@@ -2131,7 +2977,13 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2131
2977
  // With a state, the other mode would take one variant's value for
2132
2978
  // every variant, so any part whose variants read their own value needs
2133
2979
  // the variant named.
2134
- if (s.mode && !s.when) {
2980
+ // Per-variant colors only: a value that is not a color is refused for
2981
+ // --mode below, with the reason that holds.
2982
+ if (
2983
+ s.mode &&
2984
+ !s.when &&
2985
+ (COLOR_PROPS.test(prop) || (prop === 'background' && isColorValue(v)))
2986
+ ) {
2135
2987
  const g = C.groupOfProp(
2136
2988
  prop === 'background' ? 'background-color' : prop,
2137
2989
  );
@@ -2225,6 +3077,27 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2225
3077
  },
2226
3078
  );
2227
3079
  }
3080
+ // A var() inside a color (color-mix(in srgb, var(--x, 12px), red)) shows
3081
+ // its fallback when the variable is unset: that must be a color too,
3082
+ // except in a color's channels (rgb(var(--r, 0) 0 0)).
3083
+ if (COLOR_PROPS.test(prop) || (prop === 'background' && isColorValue(v)))
3084
+ for (const {fallback, within} of innerVarFallbacks(v)) {
3085
+ if (
3086
+ within.some(f =>
3087
+ /^(rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)$/i.test(f),
3088
+ ) ||
3089
+ /\bvar\(/i.test(fallback)
3090
+ )
3091
+ continue;
3092
+ if (fallback === '' || !isColorValue(fallback))
3093
+ refuse(
3094
+ E.ERR_THEME_BAD_VALUE,
3095
+ fallback === ''
3096
+ ? `${prop} takes a color; the var() in "${v}" has an empty fallback, which leaves it with no color when the variable is unset.`
3097
+ : `${prop} takes a color; "${fallback}", a var() fallback in "${v}", is not one, so the ${prop} is lost when the variable is unset.`,
3098
+ {run: [setLine(slug, prop, exampleOf('color', prop), s)]},
3099
+ );
3100
+ }
2228
3101
  // Every scope flag but --mode carries into the runs.
2229
3102
  const whenFlag = `${s.when ? ` --when ${s.when}` : ''}${s.state ? ` --state ${s.state}` : ''}${s.only ? ' --only' : ''}`;
2230
3103
  if (
@@ -2232,8 +3105,12 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2232
3105
  !COLOR_PROPS.test(prop) &&
2233
3106
  !(prop === 'background' && isColorValue(v))
2234
3107
  ) {
2235
- const alt =
2236
- prop === 'border' || prop.startsWith('border-')
3108
+ // A color mixed into the value (a border's) can go per mode on its
3109
+ // own; a value with none (a radius) is just set for both modes.
3110
+ const hasColor = /#[0-9a-f]{3,8}\b|rgba?\(|hsla?\(/i.test(v);
3111
+ const alt = !hasColor
3112
+ ? null
3113
+ : prop === 'border' || prop.startsWith('border-')
2237
3114
  ? 'border-color'
2238
3115
  : prop === 'background'
2239
3116
  ? 'background-color'