@astryxdesign/cli 0.7.14-canary.gfdb9213 → 0.7.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/CHANGELOG.md +197 -0
  2. package/api/theme/_adapter.d.mts +33 -0
  3. package/api/theme/_adapter.mjs +352 -16
  4. package/api/theme/build/build.mjs +261 -10
  5. package/api/theme/eject/eject.mjs +13 -1
  6. package/api/theme/list/list.mjs +11 -2
  7. package/api/theme/template/template.mjs +139 -6
  8. package/api/theme/theme.type.d.mts +15 -1
  9. package/api/theme/theme.type.mjs +9 -3
  10. package/api/theme/themeAdd.doc.mjs +1 -1
  11. package/api/theme/themeBuild.doc.mjs +10 -2
  12. package/api/theme/themeEject.doc.mjs +2 -2
  13. package/api/theme/themeListAvailable.doc.mjs +1 -1
  14. package/api/theme/themeRemove.doc.mjs +1 -1
  15. package/api/theme/themeTemplate.doc.mjs +8 -0
  16. package/api/theme/themeUse.doc.mjs +1 -1
  17. package/api/theme-edit/_adapter.d.mts +10 -2
  18. package/api/theme-edit/_adapter.mjs +52 -31
  19. package/api/theme-edit/_check.d.mts +28 -25
  20. package/api/theme-edit/_check.mjs +586 -548
  21. package/api/theme-edit/_color.d.mts +28 -2
  22. package/api/theme-edit/_color.mjs +306 -68
  23. package/api/theme-edit/_compiler.d.mts +8 -4
  24. package/api/theme-edit/_compiler.mjs +30 -27
  25. package/api/theme-edit/_context.d.mts +10 -4
  26. package/api/theme-edit/_context.mjs +21 -4
  27. package/api/theme-edit/_edit.mjs +300 -43
  28. package/api/theme-edit/_how-commands.d.mts +91 -0
  29. package/api/theme-edit/_how-commands.mjs +269 -0
  30. package/api/theme-edit/_how-question.d.mts +57 -0
  31. package/api/theme-edit/_how-question.mjs +2574 -0
  32. package/api/theme-edit/_how.d.mts +25 -17
  33. package/api/theme-edit/_how.mjs +727 -305
  34. package/api/theme-edit/_palette.d.mts +127 -19
  35. package/api/theme-edit/_palette.mjs +1313 -399
  36. package/api/theme-edit/_parts.mjs +36 -3
  37. package/api/theme-edit/_png.d.mts +18 -6
  38. package/api/theme-edit/_png.mjs +135 -25
  39. package/api/theme-edit/_preview-app.d.mts +26 -7
  40. package/api/theme-edit/_preview-app.mjs +1611 -280
  41. package/api/theme-edit/_preview.d.mts +4 -2
  42. package/api/theme-edit/_preview.mjs +18 -7
  43. package/api/theme-edit/_settings.d.mts +56 -5
  44. package/api/theme-edit/_settings.mjs +197 -49
  45. package/api/theme-edit/_tables.d.mts +0 -12
  46. package/api/theme-edit/_tables.mjs +24 -97
  47. package/api/theme-edit/theme-edit.type.d.mts +22 -5
  48. package/api/theme-edit/theme-edit.type.mjs +17 -6
  49. package/api/theme-edit/themeEditHow.doc.mjs +13 -3
  50. package/api/theme-edit/themeEditNew.doc.mjs +2 -1
  51. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +16 -4
  52. package/api/theme-edit/themeEditPreviewApp.doc.mjs +12 -4
  53. package/api/theme-edit/themeEditPreviewList.doc.mjs +9 -1
  54. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +27 -2
  55. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  56. package/assets/docs.generated.json +1 -0
  57. package/assets/preview-app/gitignore +3 -0
  58. package/assets/templates/components.generated.json +1 -0
  59. package/clients/cli/bin/astryx.mjs +37 -5
  60. package/clients/cli/commands/experimental/theme.mjs +231 -31
  61. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +14 -5
  62. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +0 -1
  63. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  64. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +3 -2
  65. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +2 -2
  66. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +2 -2
  67. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  68. package/clients/cli/commands/experimental-theme-targets.doc.mjs +1 -1
  69. package/clients/cli/commands/experimental-theme.doc.mjs +2 -2
  70. package/clients/cli/commands/theme-build.doc.mjs +1 -1
  71. package/clients/cli/commands/theme-eject.doc.mjs +3 -3
  72. package/clients/cli/commands/theme-remove.doc.mjs +2 -2
  73. package/clients/cli/commands/theme-template.doc.mjs +11 -4
  74. package/clients/cli/commands/theme.mjs +104 -40
  75. package/clients/cli/commands.generated.json +1 -0
  76. package/clients/cli/index.mjs +96 -4
  77. package/clients/cli/lib/json-shim.mjs +29 -1
  78. package/foundation/config/project.d.mts +16 -2
  79. package/foundation/config/project.mjs +40 -6
  80. package/foundation/config/theme-state.d.mts +9 -0
  81. package/foundation/config/theme-state.mjs +20 -1
  82. package/foundation/discovery/template-adapter.d.mts +12 -1
  83. package/foundation/discovery/template-adapter.mjs +24 -1
  84. package/foundation/discovery/template-needs.d.mts +7 -0
  85. package/foundation/discovery/template-needs.mjs +117 -8
  86. package/foundation/discovery/template-source-tree.d.mts +5 -1
  87. package/foundation/discovery/template-source-tree.mjs +6 -4
  88. package/foundation/discovery/theme-discovery.d.mts +14 -3
  89. package/foundation/discovery/theme-discovery.mjs +45 -12
  90. package/foundation/doc-compiler/import.mjs +68 -3
  91. package/foundation/doc-compiler/stored-docs.d.mts +27 -0
  92. package/foundation/doc-compiler/stored-docs.mjs +65 -0
  93. package/foundation/fs/fs-error.d.mts +17 -0
  94. package/foundation/fs/fs-error.mjs +34 -0
  95. package/package.json +6 -6
@@ -3,27 +3,44 @@
3
3
  /**
4
4
  * @file The palette behind the color dials of `astryx experimental theme`:
5
5
  * each color dial is one family in the theme's palette.config.json, grown by
6
- * the palette generator (the same function as `theme palette generate`), and
7
- * the theme's color tokens point at stops of that palette. Contrast moves a
8
- * token to a nearer stop that passes; it never makes a new color. The
9
- * `vibrancy` dial is the generator's `vibrancy`. Users see "colors" and
10
- * "shades": the words palette, family and stop stay in the code.
6
+ * the palette generator (the same function as `theme palette generate`).
7
+ * Every color decision is generator config: the seed's exact color is an
8
+ * anchor at its stop, in dark too when it reads there. The theme's color
9
+ * tokens point at stops as the official themes map them, and contrast moves
10
+ * a token to a nearer stop that passes; it never makes a new color. The
11
+ * theme imports only the stops it uses. `vibrancy` is the generator's
12
+ * `vibrancy`. Users see "colors" and "shades": the words palette, family and
13
+ * stop stay in the code.
11
14
  *
12
15
  * @position api/theme-edit — imported by _settings.mjs, _check.mjs, _how.mjs
13
16
  */
14
17
 
15
18
  import {createHash} from 'node:crypto';
16
19
  import * as fs from 'node:fs';
20
+ import {createRequire} from 'node:module';
21
+ import * as os from 'node:os';
17
22
  import * as path from 'node:path';
18
23
  import {AstryxError} from '../error.mjs';
19
24
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
20
25
  import {
26
+ DEFAULT_21_STOPS,
27
+ PALETTE_BLACK,
28
+ PALETTE_GENERATOR_VERSION,
29
+ PALETTE_WHITE,
21
30
  generateTonalPalette,
22
31
  perceptualDelta,
23
32
  } from '../theme/palette/generate/generator.mjs';
24
33
  import {themePaletteGenerate} from '../theme/palette/generate/generate.mjs';
25
- import {hexToOklch} from '../theme/palette/generate/color.mjs';
26
- import {parseColor, hex, ratio} from './_color.mjs';
34
+ import {hexToOklch, normalizeColor} from '../theme/palette/generate/color.mjs';
35
+ import {
36
+ alphaOf,
37
+ compositeOver,
38
+ hex,
39
+ isClipped,
40
+ parseColor,
41
+ ratio,
42
+ } from './_color.mjs';
43
+ import {P} from './_tables.mjs';
27
44
 
28
45
  /**
29
46
  * Write a file whole: a temp file beside it, renamed into place, so a link
@@ -56,15 +73,17 @@ export function tempFor(file) {
56
73
  }
57
74
 
58
75
  /** @typedef {'light' | 'dark'} Mode */
76
+ /** @typedef {import('./_settings.mjs').Setting} Setting */
59
77
  /** @typedef {import('../theme/theme.type.mjs').TonalPaletteCandidate} Candidate */
60
78
 
61
79
  /**
62
80
  * One token pointed at a palette stop in each mode.
63
81
  * @typedef {object} StopRef
64
82
  * @property {number} stop
65
- * @property {Mode} [from] - The ramp the stop is from when it is not the token's own mode: a dark fill that keeps the exact color takes the light ramp's stop.
66
83
  * @property {string} color - The stop's color, with `alpha` appended when set.
67
84
  * @property {string} [alpha] - Two hex digits of opacity.
85
+ * @property {string} [family] - The family the stop is from when it is not the token's own: `neutral` for text on a fill, or `black` / `white`, the palette's own ends.
86
+ * @property {boolean} [exact] - The stop holds the seed's exact color (an exact anchor).
68
87
  */
69
88
 
70
89
  /**
@@ -78,6 +97,7 @@ export function tempFor(file) {
78
97
  * @property {number} ratio - The lowest ratio over everything it was measured on.
79
98
  * @property {number} needs
80
99
  * @property {boolean} pass
100
+ * @property {string} [note] - The whole sentence to report, when the check is not a plain stop move.
81
101
  */
82
102
 
83
103
  /**
@@ -88,6 +108,8 @@ export function tempFor(file) {
88
108
  * @property {Record<string, {family: string, light: StopRef, dark: StopRef}>} tokens
89
109
  * @property {ContrastCheck[]} contrast
90
110
  * @property {number} vibrancy - The generator's vibrancy, 0 to 100.
111
+ * @property {Record<string, Partial<Record<Mode, string>>>} exact - Main tokens the theme sets exactly, the value per mode: the dial's fill gives way to them.
112
+ * @property {string[]} notes - What the config writer kept or replaced of a hand edit.
91
113
  */
92
114
 
93
115
  /** The color dials. Each one is a palette family of the same id. */
@@ -104,15 +126,19 @@ export const PALETTE_DIALS = [
104
126
  export const VIBRANCY_DEFAULT = 50;
105
127
 
106
128
  /**
107
- * The vibrancy the theme sets, or null.
108
- * @param {import('./_settings.mjs').ThemeData} data
129
+ * The vibrancy dial a settings list sets, or null.
130
+ * @param {Setting[]} settings
109
131
  * @returns {number | null}
110
132
  */
111
- function dialVibrancy(data) {
112
- const s = [...data.settings]
133
+ function dialVibrancy(settings) {
134
+ const s = [...settings]
113
135
  .reverse()
114
- .find(x => x.source === 'dial' && x.thing === 'vibrancy');
115
- return s ? Number(s.value) : null;
136
+ .find(x => x?.source === 'dial' && x.thing === 'vibrancy');
137
+ // A value edited by hand that is not one (`high`, `150`) counts as none,
138
+ // so the command that fixes it can still build the state before it.
139
+ return s && /^\d{1,3}$/.test(String(s.value)) && Number(s.value) <= 100
140
+ ? Number(s.value)
141
+ : null;
116
142
  }
117
143
 
118
144
  /** The Core token word of each status family. */
@@ -134,19 +160,15 @@ export const paletteToken = dial =>
134
160
  ? '--color-background-surface'
135
161
  : `--color-${STATUS_TOKEN[dial]}`;
136
162
 
137
- /** Text contrast (WCAG AA) and non-text contrast (focus rings, icons). */
163
+ /** Text contrast and non-text contrast (fills, focus rings, icons). */
138
164
  const TEXT = 4.5;
139
165
  const NON_TEXT = 3;
140
166
 
141
167
  /**
142
- * The stop each token starts from, `[light, dark]`, as the official themes
143
- * map them: neutral surfaces, text and borders as in the neutral theme (the
144
- * page background, `--color-background-body`, stays the base theme's, so a
145
- * tinted gray never tints the page); an
146
- * accent or status fill at its seed's anchored stop in light (as the neutral
147
- * theme anchors its blue) and 70 in dark (as the theme authoring guide maps
148
- * it); status text, tints and borders as the neutral theme maps its hue
149
- * families.
168
+ * The stop each token starts from, `[light, dark]`, as the official neutral
169
+ * theme maps them. The page background, `--color-background-body`, stays
170
+ * the base theme's, so a tinted gray never tints the page. A layout without
171
+ * one of these stops uses the nearest one it has.
150
172
  */
151
173
  const NEUTRAL_STOPS = /** @type {Record<string, [number, number]>} */ ({
152
174
  '--color-background-surface': [100, 15],
@@ -178,16 +200,34 @@ const NEUTRAL_TINTS =
178
200
  [100, '1a'],
179
201
  ],
180
202
  });
181
- const FILL = /** @type {[number, number]} */ ([45, 70]);
203
+ /**
204
+ * Accent and status stops, `[light, dark]`, as the official neutral theme
205
+ * maps its accent tint and its status families. The dark fill starts at 70,
206
+ * where the theme authoring guide puts it, when the exact color does not
207
+ * read in dark. A status tint is translucent in dark (`[stop, alpha]`).
208
+ */
209
+ const DARK_FILL = 70;
182
210
  const TEXT_STOP = /** @type {[number, number]} */ ([45, 80]);
183
- const MUTED = /** @type {[number, number]} */ ([85, 25]);
211
+ const ACCENT_MUTED = /** @type {[number, number]} */ ([85, 30]);
212
+ const STATUS_MUTED = /** @type {[number, [number, string]]} */ ([
213
+ 85,
214
+ [75, '3d'],
215
+ ]);
184
216
  const ON_MUTED = /** @type {[number, number]} */ ([25, 80]);
185
217
  const BORDER = /** @type {[number, number]} */ ([80, 65]);
186
- /** Text on a fill: white on light-mode fills, near-black on dark-mode fills. */
187
- const ON_FILL = /** @type {Record<Mode, number[]>} */ ({
218
+ /**
219
+ * Text on a fill, from the neutral family as the official themes take it:
220
+ * white (100) first in light, near-black (5) first in dark, and near-black
221
+ * first in both modes on warning. Without a neutral color, black and white.
222
+ */
223
+ const ON_FILL = /** @type {Record<Mode, [number, number]>} */ ({
188
224
  light: [100, 5],
189
225
  dark: [5, 100],
190
226
  });
227
+ /** A layout needs this many stops between black and white to map every token. */
228
+ const MIN_INNER_STOPS = 5;
229
+ /** The widest gap between two stops that still maps every token near its stop. */
230
+ const MAX_STOP_GAP = 25;
191
231
 
192
232
  /** Text on surfaces darkens in light mode and lightens in dark mode. */
193
233
  const TOWARD_CONTRAST = /** @type {Record<Mode, 1 | -1>} */ ({
@@ -201,18 +241,31 @@ export function paletteFiles(slug) {
201
241
  config: `themes/${slug}/palette.config.json`,
202
242
  palette: `themes/${slug}/tokens/${slug}.palette.ts`,
203
243
  receipt: `themes/${slug}/tokens/${slug}.palette.receipt.json`,
244
+ refs: `themes/${slug}/tokens/${slug}.palette-refs.ts`,
204
245
  importPath: `./tokens/${slug}.palette`,
246
+ refsImportPath: `./tokens/${slug}.palette-refs`,
205
247
  };
206
248
  }
207
249
 
250
+ /** The export name of a theme's selected stops. @param {string} slug */
251
+ const refsName = slug =>
252
+ `${slug.replace(/-+([a-z0-9])?/g, (_, c) => (c ? c.toUpperCase() : ''))}PaletteRefs`;
253
+
254
+ /**
255
+ * The import line the generated settings use for the stops they read.
256
+ * @param {string} slug
257
+ */
258
+ export const paletteImport = slug =>
259
+ `import {${refsName(slug)} as palette} from '${paletteFiles(slug).refsImportPath}';`;
260
+
208
261
  /**
209
- * The seed a color dial value grows from, or null for a value with no fixed
210
- * color (a variable, a keyword, `color-mix()`).
262
+ * The seed a color dial value grows from, or null for a value with no fixed,
263
+ * opaque color (a variable, a keyword, `color-mix()`, a translucent color).
211
264
  * @param {string} value
212
265
  */
213
266
  export function seedOf(value) {
214
267
  const rgb = parseColor(value);
215
- return rgb ? hex(rgb) : null;
268
+ return rgb && alphaOf(value) >= 1 ? hex(rgb) : null;
216
269
  }
217
270
 
218
271
  /**
@@ -227,9 +280,31 @@ const isGray = seed => hexToOklch(seed).C < GRAY_CHROMA;
227
280
  /** Whether a seed (or no seed) has no color to saturate. @param {string | null} seed */
228
281
  export const isGraySeed = seed => !seed || isGray(seed);
229
282
 
283
+ /** @param {unknown} a @param {unknown} b */
284
+ function sameColor(a, b) {
285
+ try {
286
+ return normalizeColor(String(a)) === normalizeColor(String(b));
287
+ } catch {
288
+ return false;
289
+ }
290
+ }
291
+
292
+ /**
293
+ * The modes a theme has.
294
+ * @param {{mode?: string}} data
295
+ * @returns {Mode[]}
296
+ */
297
+ function themeModes(data) {
298
+ return data.mode === 'light-only'
299
+ ? ['light']
300
+ : data.mode === 'dark-only'
301
+ ? ['dark']
302
+ : ['light', 'dark'];
303
+ }
304
+
230
305
  /**
231
306
  * The color dial settings of a theme, in dial order.
232
- * @param {import('./_settings.mjs').ThemeData} data
307
+ * @param {{settings: Setting[]}} data
233
308
  */
234
309
  function dialFamilies(data) {
235
310
  /** @type {Array<{id: string, dial: string, seed: string, value: string}>} */
@@ -237,7 +312,7 @@ function dialFamilies(data) {
237
312
  for (const dial of PALETTE_DIALS) {
238
313
  const s = [...data.settings]
239
314
  .reverse()
240
- .find(x => x.source === 'dial' && x.thing === dial && !x.on && !x.mode);
315
+ .find(x => x?.source === 'dial' && x.thing === dial && !x.on && !x.mode);
241
316
  const seed = s && seedOf(s.value);
242
317
  if (s && seed) out.push({id: dial, dial, seed, value: s.value});
243
318
  }
@@ -248,7 +323,7 @@ function dialFamilies(data) {
248
323
  function readConfig(file) {
249
324
  if (!fs.existsSync(file)) return null;
250
325
  try {
251
- return JSON.parse(fs.readFileSync(file, 'utf8'));
326
+ return JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
252
327
  } catch (e) {
253
328
  throw new AstryxError(
254
329
  `${path.basename(path.dirname(file))}/palette.config.json is not valid JSON (${e instanceof Error ? e.message : String(e)}). Fix it by hand. Nothing was changed.`,
@@ -258,13 +333,80 @@ function readConfig(file) {
258
333
  }
259
334
  }
260
335
 
336
+ /**
337
+ * The settings saved on disk, before the change being built: what the
338
+ * editor wrote into the config last time, so a value it did not write is
339
+ * known to be a hand edit.
340
+ * @param {string} cwd
341
+ * @param {string} slug
342
+ * @returns {{settings: Setting[], mode: string | null}}
343
+ */
344
+ function savedSettings(cwd, slug) {
345
+ try {
346
+ const data = JSON.parse(
347
+ fs.readFileSync(
348
+ path.join(cwd, 'themes', slug, `${slug}.settings.json`),
349
+ 'utf8',
350
+ ),
351
+ );
352
+ return {
353
+ settings: Array.isArray(data?.settings) ? data.settings : [],
354
+ mode: typeof data?.mode === 'string' ? data.mode : null,
355
+ };
356
+ } catch {
357
+ return {settings: [], mode: null};
358
+ }
359
+ }
360
+
361
+ /** The generator's mode strategy for a list of modes. @param {Mode[]} modes */
362
+ const strategyOf = modes =>
363
+ modes.length > 1 ? 'light-and-dark' : `${modes[0]}-only`;
364
+
365
+ /** The config fields the generator reads; anything else changes nothing. */
366
+ const CONFIG_KEYS = [
367
+ 'vibrancy',
368
+ 'neutralProfile',
369
+ 'modeStrategy',
370
+ 'stops',
371
+ 'families',
372
+ ];
373
+ const FAMILY_KEYS = ['id', 'name', 'seed', 'kind', 'anchors'];
374
+ const ANCHOR_KEYS = ['mode', 'stop', 'color', 'policy', 'maxDeltaE'];
375
+
376
+ /**
377
+ * The fields of a config the generator never reads (such as
378
+ * `darkChromaTaper`), by path.
379
+ * @param {any} config
380
+ * @returns {string[]}
381
+ */
382
+ function deadKeys(config) {
383
+ /** @type {string[]} */
384
+ const out = Object.keys(config).filter(k => !CONFIG_KEYS.includes(k));
385
+ (Array.isArray(config.families) ? config.families : []).forEach(
386
+ (/** @type {any} */ f, /** @type {number} */ i) => {
387
+ if (!f || typeof f !== 'object') return;
388
+ for (const k of Object.keys(f))
389
+ if (!FAMILY_KEYS.includes(k)) out.push(`families[${i}].${k}`);
390
+ (Array.isArray(f.anchors) ? f.anchors : []).forEach(
391
+ (/** @type {any} */ a, /** @type {number} */ j) => {
392
+ if (a && typeof a === 'object')
393
+ for (const k of Object.keys(a))
394
+ if (!ANCHOR_KEYS.includes(k))
395
+ out.push(`families[${i}].anchors[${j}].${k}`);
396
+ },
397
+ );
398
+ },
399
+ );
400
+ return out;
401
+ }
402
+
261
403
  /**
262
404
  * The light stop nearest a seed color in the ramp the generator grows from
263
405
  * it. The official themes anchor a brand color there, exactly, so the fill
264
406
  * keeps the color as given. The end stops are pure black and white and
265
407
  * never hold an anchor.
266
408
  * @param {string} seed
267
- * @param {any} config - Its `stops`, `vibrancy` and `neutralProfile` shape the ramp.
409
+ * @param {any} config - Its `stops` and `vibrancy` shape the ramp.
268
410
  * @param {'chromatic' | 'neutral'} [kind]
269
411
  */
270
412
  function seedStop(seed, config, kind = 'chromatic') {
@@ -287,80 +429,593 @@ function seedStop(seed, config, kind = 'chromatic') {
287
429
  }
288
430
 
289
431
  /**
290
- * The palette config a theme's settings ask for: the existing config, with
291
- * each color dial's family written in place and families the dials no longer
292
- * set removed, and `vibrancy` as the vibrancy dial sets it (absent without
293
- * the dial). Other families and fields are kept. Null when the config would
294
- * hold no family.
432
+ * The stop of a layout nearest `n`; on a tie, the one nearer the middle.
433
+ * @param {readonly number[]} stops
434
+ * @param {number} n
435
+ */
436
+ function nearestStop(stops, n) {
437
+ return stops.reduce((best, s) => {
438
+ const d = Math.abs(s - n) - Math.abs(best - n);
439
+ return d < 0 || (d === 0 && Math.abs(s - 50) < Math.abs(best - 50))
440
+ ? s
441
+ : best;
442
+ });
443
+ }
444
+
445
+ /**
446
+ * Refuse a stop layout the token mapping cannot use: numbers only, black
447
+ * (0) and white (100), enough shades between them, and no gap so wide that
448
+ * tokens land far from where they belong. The generator checks the order.
449
+ * @param {any} stops
450
+ * @param {string} slug
451
+ * @returns {readonly number[]}
452
+ */
453
+ function usableStops(stops, slug) {
454
+ if (stops == null) return DEFAULT_21_STOPS;
455
+ const list = Array.isArray(stops) ? stops : [];
456
+ const shown = Array.isArray(stops)
457
+ ? stops.map(x => JSON.stringify(x)).join(', ')
458
+ : JSON.stringify(stops);
459
+ const fix = `Remove "stops" from it to use the default 21 shades, or give 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100. Nothing was changed.`;
460
+ /** @param {string} why */
461
+ const refuse = why => {
462
+ throw new AstryxError(
463
+ `themes/${slug}/palette.config.json: its stops (${shown}) ${why}. ${fix}`,
464
+ [],
465
+ ERROR_CODES.ERR_THEME_INVALID,
466
+ );
467
+ };
468
+ if (!Array.isArray(stops) || !list.length)
469
+ refuse('are not a list of numbers');
470
+ const bad = list.filter(x => typeof x !== 'number' || !Number.isFinite(x));
471
+ if (bad.length)
472
+ refuse(
473
+ `hold ${bad.map(x => JSON.stringify(x)).join(', ')}, which ${bad.length > 1 ? 'are not numbers' : 'is not a number'}`,
474
+ );
475
+ if (!list.includes(0) || !list.includes(100))
476
+ refuse('need 0 (black) and 100 (white) at the ends');
477
+ const inner = list.filter(s => s > 0 && s < 100);
478
+ if (inner.length < MIN_INNER_STOPS)
479
+ refuse(
480
+ `leave ${inner.length} shades between black and white, and the color tokens need at least ${MIN_INNER_STOPS}`,
481
+ );
482
+ const sorted = [...list].sort((a, b) => a - b);
483
+ const gap = Math.max(...sorted.slice(1).map((x, i) => x - sorted[i]));
484
+ if (gap > MAX_STOP_GAP)
485
+ refuse(
486
+ `leave a gap of ${gap} between two shades, and the color tokens need one at least every ${MAX_STOP_GAP}`,
487
+ );
488
+ return list;
489
+ }
490
+
491
+ /**
492
+ * Look-ups shared by the config writer and the mapping, on one candidate:
493
+ * the nearest stop, a stop's color, the surfaces text and fills sit on, the
494
+ * text that reads on a fill, and the theme's exact color settings.
495
+ * @param {Candidate} candidate
496
+ * @param {{settings: Setting[]}} data
497
+ * @param {{light: Record<string, string>, dark: Record<string, string>} | undefined} base
498
+ */
499
+ function tools(candidate, data, base) {
500
+ const {stops} = candidate;
501
+ /** @param {number} n */
502
+ const at = n => nearestStop(stops, n);
503
+ /** @param {string} id @param {Mode} m @param {number} stop @param {string} [alpha] @returns {StopRef} */
504
+ const ref = (id, m, stop, alpha) => {
505
+ const color = /** @type {any} */ (candidate.palette[id])[m][stop];
506
+ return alpha ? {stop, color: `${color}${alpha}`, alpha} : {stop, color};
507
+ };
508
+ const neutral = Boolean(/** @type {any} */ (candidate.palette).neutral);
509
+ /**
510
+ * The exact whole-theme color a token setting gives in a mode, or null.
511
+ * @param {string} token @param {Mode} m
512
+ */
513
+ const exactOf = (token, m) => {
514
+ const v = [...data.settings]
515
+ .reverse()
516
+ .find(
517
+ s =>
518
+ s.source === 'token' &&
519
+ s.thing === token &&
520
+ !s.on &&
521
+ !s.when &&
522
+ !s.state &&
523
+ (!s.mode || s.mode === m),
524
+ )?.value;
525
+ const rgb = v == null ? null : parseColor(v);
526
+ return rgb && alphaOf(v) >= 1 ? hex(rgb) : null;
527
+ };
528
+ /**
529
+ * What text and fills sit on in a mode: the theme's exact surface
530
+ * colors, else the neutral color's surfaces, else the base theme's; the
531
+ * family's own surface stop when nothing else is known.
532
+ * @param {Mode} m @param {string} id
533
+ * @returns {Array<[string, string]>}
534
+ */
535
+ const surfaces = (m, id) => {
536
+ /** @type {Array<[string, string]>} */
537
+ const out = [];
538
+ for (const n of [
539
+ '--color-background-surface',
540
+ '--color-background-body',
541
+ '--color-background-card',
542
+ ]) {
543
+ const own =
544
+ neutral && NEUTRAL_STOPS[n]
545
+ ? ref('neutral', m, at(NEUTRAL_STOPS[n][m === 'light' ? 0 : 1])).color
546
+ : null;
547
+ const v = exactOf(n, m) ?? own ?? base?.[m]?.[n];
548
+ if (v && parseColor(v) && alphaOf(v) >= 1)
549
+ out.push([n, hex(/** @type {number[]} */ (parseColor(v)))]);
550
+ }
551
+ if (!out.length) {
552
+ const s = at(
553
+ NEUTRAL_STOPS['--color-background-surface'][m === 'light' ? 0 : 1],
554
+ );
555
+ out.push([`${id} shade ${s}`, ref(id, m, s).color]);
556
+ }
557
+ return out;
558
+ };
559
+ /**
560
+ * The text shades for a fill, preferred first.
561
+ * @param {string} id @param {Mode} m
562
+ * @returns {StopRef[]}
563
+ */
564
+ const onChoices = (id, m) =>
565
+ (id === 'warning' ? [5, 100] : ON_FILL[m]).map(s =>
566
+ neutral
567
+ ? {...ref('neutral', m, at(s)), family: 'neutral'}
568
+ : s >= 50
569
+ ? {stop: 100, color: PALETTE_WHITE, family: 'white'}
570
+ : {stop: 0, color: PALETTE_BLACK, family: 'black'},
571
+ );
572
+ /**
573
+ * The text on a fill: the preferred shade when it reads at 4.5:1, else
574
+ * the one that reads better.
575
+ * @param {string} id @param {Mode} m @param {string} fill
576
+ */
577
+ const onFor = (id, m, fill) => {
578
+ const [a, b] = onChoices(id, m).map(on => ({
579
+ on,
580
+ r: contrast(on.color, fill),
581
+ }));
582
+ const best = a.r >= TEXT || a.r >= b.r ? a : b;
583
+ const other = best === a ? b : a;
584
+ return {
585
+ on: best.on,
586
+ r: best.r,
587
+ other: other.on,
588
+ otherR: other.r,
589
+ first: a.on,
590
+ };
591
+ };
592
+ /** The lowest contrast of a color on the surfaces. @param {string} color @param {Mode} m @param {string} id */
593
+ const page = (color, m, id) =>
594
+ Math.min(...surfaces(m, id).map(([, bg]) => contrast(color, bg)));
595
+ return {stops, at, ref, exactOf, surfaces, onFor, page, neutral};
596
+ }
597
+
598
+ /** @type {Partial<Record<Mode, number | null>>} */
599
+ const citationCache = {};
600
+
601
+ /**
602
+ * How well citation text (`--color-text-secondary`) reads on the accent
603
+ * tint (`--color-accent-muted`) in the official neutral theme, per mode:
604
+ * both tokens' stops come from its theme source and their colors from its
605
+ * selected palette stops, read from the installed package. Without the
606
+ * package, the same official stops of a plain gray ramp from the
607
+ * generator. Null when neither can be read.
608
+ * @param {Mode} m
609
+ * @returns {number | null}
610
+ */
611
+ export function officialCitation(m) {
612
+ if (m in citationCache)
613
+ return /** @type {number | null} */ (citationCache[m]);
614
+ const i = m === 'light' ? 0 : 1;
615
+ /** @type {number | null} */
616
+ let r = null;
617
+ try {
618
+ const dir = path.dirname(
619
+ path.dirname(
620
+ createRequire(import.meta.url).resolve('@astryxdesign/theme-neutral'),
621
+ ),
622
+ );
623
+ const theme = fs.readFileSync(
624
+ path.join(dir, 'src/neutralTheme.ts'),
625
+ 'utf8',
626
+ );
627
+ const refs = fs.readFileSync(
628
+ path.join(dir, 'src/neutralPaletteRefs.generated.ts'),
629
+ 'utf8',
630
+ );
631
+ /** @param {string} token */
632
+ const stopOf = token =>
633
+ new RegExp(
634
+ `'${token}':\\s*\\[\\s*neutral\\.light\\[(\\d+)\\],\\s*neutral\\.dark\\[(\\d+)\\]\\s*\\]`,
635
+ ).exec(theme)?.[i + 1];
636
+ // The first ramp of each mode after `neutral: {` is the neutral one.
637
+ const from = refs.search(/\bneutral:\s*\{/);
638
+ const ramp =
639
+ from < 0
640
+ ? ''
641
+ : (new RegExp(`\\b${m}:\\s*\\{([^}]*)\\}`).exec(
642
+ refs.slice(from),
643
+ )?.[1] ?? '');
644
+ /** @param {string | undefined} stop */
645
+ const colorOf = stop =>
646
+ stop == null
647
+ ? null
648
+ : new RegExp(`\\b${stop}:\\s*'(#[0-9a-f]{6})'`).exec(ramp)?.[1];
649
+ const text = colorOf(stopOf('--color-text-secondary'));
650
+ const tint = colorOf(stopOf('--color-accent-muted'));
651
+ if (text && tint) r = contrast(text, tint);
652
+ } catch {
653
+ r = null;
654
+ }
655
+ if (r == null)
656
+ try {
657
+ const gray = /** @type {any} */ (
658
+ generateTonalPalette({
659
+ families: [{id: 'n', seed: '#808080', kind: 'neutral'}],
660
+ }).palette.n
661
+ )[m];
662
+ r = contrast(
663
+ gray[NEUTRAL_STOPS['--color-text-secondary'][i]],
664
+ gray[ACCENT_MUTED[i]],
665
+ );
666
+ } catch {
667
+ r = null;
668
+ }
669
+ citationCache[m] = r;
670
+ return r;
671
+ }
672
+
673
+ /** A text shade, named for a sentence. @param {StopRef} r */
674
+ const textName = r =>
675
+ r.family === 'white' || (r.family === 'neutral' && r.stop >= 95)
676
+ ? 'white'
677
+ : r.family === 'black' || (r.family === 'neutral' && r.stop <= 10)
678
+ ? 'near-black'
679
+ : `shade ${r.stop}`;
680
+
681
+ /**
682
+ * Whether the exact seed color works as the dark fill: text on it reads at
683
+ * 4.5:1 and it stands out from the dark surfaces at 3:1. Why not otherwise.
684
+ * @param {ReturnType<typeof tools>} t
685
+ * @param {string} id
686
+ * @param {string} seed
687
+ */
688
+ function darkExact(t, id, seed) {
689
+ const on = t.onFor(id, 'dark', seed);
690
+ if (on.r < TEXT)
691
+ return {
692
+ ok: false,
693
+ ratio: round(on.r),
694
+ why: `your exact color reads at only ${round(on.r)}:1 with any text shade, and text needs ${TEXT}:1`,
695
+ };
696
+ const p = t.page(seed, 'dark', id);
697
+ if (p < NON_TEXT)
698
+ return {
699
+ ok: false,
700
+ ratio: round(p),
701
+ why: `your exact color stands out from the dark page at only ${round(p)}:1, and a fill needs ${NON_TEXT}:1`,
702
+ };
703
+ return {ok: true, ratio: round(on.r), why: ''};
704
+ }
705
+
706
+ /**
707
+ * What the config writer decided: the config, what it kept or replaced of
708
+ * a hand edit, and for each accent or status color the stop of its exact
709
+ * color and whether dark mode holds it too (why not, when not).
710
+ * @typedef {object} PalettePlan
711
+ * @property {any} config
712
+ * @property {string[]} notes
713
+ * @property {Record<string, {stop: number, dark: boolean, why: string, ratio: number}>} fills
714
+ */
715
+
716
+ /**
717
+ * The palette config a theme's settings ask for. The existing config is
718
+ * kept, and each color dial changes only what it owns: its family's seed,
719
+ * the exact anchors of its seed (light, and dark when the color reads
720
+ * there; both modes for neutral), and a gray seed's `kind`. `modeStrategy`
721
+ * follows the theme's modes; `vibrancy` follows the vibrancy dial and is
722
+ * kept when written by hand; anchors, names, profile, stops and families of
723
+ * the author's own stay. Null when the config would hold no family.
295
724
  * @param {string} cwd
296
725
  * @param {string} slug
297
- * @param {import('./_settings.mjs').ThemeData} data
298
- * @returns {any}
726
+ * @param {{mode?: string, settings: Setting[]}} data
727
+ * @param {{light: Record<string, string>, dark: Record<string, string>}} [base] the base theme's resolved colors, which the dark check reads
728
+ * @returns {PalettePlan | null}
299
729
  */
300
- export function paletteConfig(cwd, slug, data) {
301
- const existing = readConfig(path.join(cwd, paletteFiles(slug).config));
730
+ function planPalette(cwd, slug, data, base) {
731
+ const file = paletteFiles(slug).config;
732
+ const existing = readConfig(path.join(cwd, file));
302
733
  const fams = dialFamilies(data);
303
734
  if (!existing && !fams.length) return null;
304
- const config = {...(existing ?? {})};
305
- const vibrancy = dialVibrancy(data);
306
- if (vibrancy == null) delete config.vibrancy;
307
- else config.vibrancy = vibrancy;
735
+ /** @type {string[]} */
736
+ const notes = [];
737
+ const config =
738
+ existing && typeof existing === 'object' && !Array.isArray(existing)
739
+ ? {...existing}
740
+ : {};
741
+ const {settings: saved, mode: savedMode} = savedSettings(cwd, slug);
742
+ const modes = themeModes(data);
743
+
744
+ const vibrancy = dialVibrancy(data.settings);
745
+ const savedVibrancy = dialVibrancy(saved);
746
+ if (vibrancy != null) {
747
+ if (
748
+ config.vibrancy != null &&
749
+ savedVibrancy == null &&
750
+ config.vibrancy !== vibrancy
751
+ )
752
+ notes.push(
753
+ `${file}: your vibrancy ${config.vibrancy} there is replaced by the vibrancy setting, ${vibrancy}`,
754
+ );
755
+ config.vibrancy = vibrancy;
756
+ } else if (savedVibrancy != null) delete config.vibrancy;
757
+ else if (config.vibrancy != null)
758
+ notes.push(
759
+ `${file} keeps the vibrancy ${config.vibrancy} written there by hand; ${P} set ${slug} vibrancy ${config.vibrancy} makes it a setting`,
760
+ );
761
+
762
+ const strategy = strategyOf(modes);
763
+ // Only a value the editor did not write is a hand edit worth naming: the
764
+ // one it wrote follows the theme's mode as it was saved.
765
+ const wrote = savedMode ? strategyOf(themeModes({mode: savedMode})) : null;
766
+ if (
767
+ config.modeStrategy != null &&
768
+ config.modeStrategy !== strategy &&
769
+ config.modeStrategy !== wrote
770
+ )
771
+ notes.push(
772
+ `${file}: modeStrategy ${config.modeStrategy} is now ${strategy}, the modes the theme has`,
773
+ );
774
+ config.modeStrategy = strategy;
775
+ usableStops(config.stops, slug);
776
+
777
+ if (config.families != null && !Array.isArray(config.families))
778
+ notes.push(
779
+ `${file}: families was not a list, so it is made again from your color settings`,
780
+ );
308
781
  /** @type {any[]} */
309
782
  const before = Array.isArray(config.families) ? config.families : [];
310
- /** @param {{id: string, seed: string}} f */
311
- const familyOf = f => {
312
- if (f.id === 'neutral')
313
- return {id: f.id, name: 'Neutral', seed: f.seed, kind: 'neutral'};
314
- const kind = isGray(f.seed) ? 'neutral' : 'chromatic';
315
- return {
316
- id: f.id,
317
- name: f.id[0].toUpperCase() + f.id.slice(1),
318
- seed: f.seed,
319
- ...(kind === 'neutral' ? {kind} : {}),
320
- anchors: [
321
- {
322
- mode: 'light',
323
- stop: seedStop(f.seed, config, kind),
783
+ const savedSeeds = dialFamilies({settings: saved});
784
+
785
+ /**
786
+ * One dial family: the author's family with the dial's seed and the
787
+ * exact anchors of that seed in place of the old ones.
788
+ * @param {any} prev
789
+ * @param {{id: string, seed: string}} f
790
+ */
791
+ const familyOf = (prev, f) => {
792
+ const old = prev && typeof prev === 'object' ? prev : {};
793
+ const neutral = f.id === 'neutral';
794
+ const wasSaved = savedSeeds.find(x => x.id === f.id)?.seed;
795
+ if (old.seed != null && wasSaved && !sameColor(old.seed, wasSaved))
796
+ notes.push(
797
+ `${file}: the ${f.id} seed ${old.seed} there is replaced by your ${f.id} setting, ${f.seed}`,
798
+ );
799
+ const gray = isGray(f.seed);
800
+ const kind =
801
+ neutral || gray
802
+ ? 'neutral'
803
+ : old.kind === 'chromatic'
804
+ ? 'chromatic'
805
+ : undefined;
806
+ if (
807
+ old.kind === 'neutral' &&
808
+ !kind &&
809
+ !neutral &&
810
+ !(wasSaved && isGray(wasSaved))
811
+ )
812
+ notes.push(
813
+ `${file}: the ${f.id} kind "neutral" is dropped: your ${f.id} is not a gray, and a neutral kind turns its shades gray where no exact color holds them`,
814
+ );
815
+ const stop = seedStop(
816
+ f.seed,
817
+ config,
818
+ kind === 'neutral' ? 'neutral' : 'chromatic',
819
+ );
820
+ // White and black already end every ramp, so a neutral of either holds
821
+ // no anchor of its own.
822
+ const ends =
823
+ neutral &&
824
+ (sameColor(f.seed, PALETTE_WHITE) || sameColor(f.seed, PALETTE_BLACK));
825
+ /** @type {any[]} */
826
+ const mine = ends
827
+ ? []
828
+ : (neutral ? modes : modes.filter(m => m === 'light')).map(m => ({
829
+ mode: m,
830
+ stop,
324
831
  color: f.seed,
325
832
  policy: 'exact',
326
- },
327
- ],
833
+ }));
834
+ /** @type {any[]} */
835
+ const kept = [];
836
+ const anchors = Array.isArray(old.anchors) ? old.anchors : [];
837
+ // The editor's own anchors: the seed's exact color at the one stop it
838
+ // put it (light, else dark). The same color at another stop is the
839
+ // author's.
840
+ /** @param {any} a */
841
+ const seedColored = a =>
842
+ a?.policy === 'exact' &&
843
+ (sameColor(a.color, old.seed) ||
844
+ sameColor(a.color, f.seed) ||
845
+ (wasSaved && sameColor(a.color, wasSaved)));
846
+ const editorStop = (
847
+ anchors.find(
848
+ (/** @type {any} */ a) => seedColored(a) && a.mode === 'light',
849
+ ) ?? anchors.find((/** @type {any} */ a) => seedColored(a))
850
+ )?.stop;
851
+ for (const a of anchors) {
852
+ if (seedColored(a) && a.stop === editorStop) continue;
853
+ if (!modes.includes(a?.mode)) {
854
+ notes.push(
855
+ `${file}: the ${f.id} ${a?.mode} anchor at shade ${a?.stop} is dropped: the theme has no ${a?.mode} mode`,
856
+ );
857
+ continue;
858
+ }
859
+ if (mine.some(x => x.mode === a.mode && x.stop === a.stop)) {
860
+ notes.push(
861
+ `${file}: your ${a.mode} anchor at shade ${a.stop} of ${f.id} is replaced by your exact ${f.id} color`,
862
+ );
863
+ continue;
864
+ }
865
+ kept.push(a);
866
+ }
867
+ if (kept.length && wasSaved && !sameColor(wasSaved, f.seed))
868
+ notes.push(
869
+ `${file} keeps your own ${f.id} anchors (${kept.map(a => `${a.mode} ${a.stop} ${a.color}`).join(', ')}): they were set for your earlier ${f.id}, ${wasSaved}, and still pull its shades toward them`,
870
+ );
871
+ const out = {
872
+ ...old,
873
+ id: f.id,
874
+ name: old.name ?? f.id[0].toUpperCase() + f.id.slice(1),
875
+ seed: f.seed,
876
+ ...(kind ? {kind} : {}),
877
+ anchors: [...mine, ...kept].sort((a, b) =>
878
+ a.mode === b.mode ? a.stop - b.stop : a.mode === 'light' ? -1 : 1,
879
+ ),
328
880
  };
881
+ if (!kind) delete out.kind;
882
+ if (!out.anchors.length) delete out.anchors;
883
+ return {family: out, stop};
329
884
  };
885
+
886
+ /** @type {PalettePlan['fills']} */
887
+ const fills = {};
330
888
  const families = before
331
889
  .map(f => {
332
890
  if (!PALETTE_DIALS.includes(f?.id)) return f;
333
891
  const mine = fams.find(x => x.id === f.id);
334
892
  if (!mine) return null;
335
- const {kind, ...rest} = f;
336
- void kind;
337
- return {...rest, ...familyOf(mine)};
893
+ const {family, stop} = familyOf(f, mine);
894
+ if (mine.id !== 'neutral')
895
+ fills[mine.id] = {stop, dark: false, why: '', ratio: 0};
896
+ return family;
338
897
  })
339
898
  .filter(Boolean);
340
899
  for (const f of fams)
341
- if (!families.some(x => x.id === f.id)) families.push(familyOf(f));
900
+ if (!families.some(x => x?.id === f.id)) {
901
+ const {family, stop} = familyOf(null, f);
902
+ if (f.id !== 'neutral')
903
+ fills[f.id] = {stop, dark: false, why: '', ratio: 0};
904
+ families.push(family);
905
+ }
342
906
  if (!families.length) return null;
343
- config.modeStrategy = 'light-and-dark';
344
- // The neutral profiles other than `custom` ignore the seed.
345
- if (families.some(f => f?.kind === 'neutral'))
346
- config.neutralProfile = 'custom';
347
907
  config.families = families;
348
- return config;
908
+ const dead = deadKeys(config);
909
+ if (dead.length)
910
+ notes.push(
911
+ `${file}: the color generator does not read ${dead.join(', ')}, so ${dead.length > 1 ? 'they change' : 'it changes'} nothing`,
912
+ );
913
+ if (config.neutralProfile != null) {
914
+ const grays = families.filter(f => f?.kind === 'neutral');
915
+ const unheld = grays.filter(f =>
916
+ modes.some(
917
+ m => !(f.anchors ?? []).some((/** @type {any} */ a) => a.mode === m),
918
+ ),
919
+ );
920
+ if (!unheld.length)
921
+ notes.push(
922
+ `${file}: neutralProfile ${config.neutralProfile} changes nothing here: ${grays.length ? 'each gray color holds its exact color in every mode, and that sets its grays' : 'no color is a gray'}`,
923
+ );
924
+ }
925
+
926
+ // The exact color anchors dark mode too when it reads there, as the
927
+ // official themes anchor a brand color in both modes.
928
+ if (modes.includes('dark') && Object.keys(fills).length) {
929
+ const t = tools(generate(config, file), data, base);
930
+ /** @type {string[]} */
931
+ const add = [];
932
+ for (const [id, fill] of Object.entries(fills)) {
933
+ const seed = /** @type {string} */ (fams.find(f => f.id === id)?.seed);
934
+ const check = darkExact(t, id, seed);
935
+ Object.assign(fill, {why: check.why, ratio: check.ratio});
936
+ if (check.ok) add.push(id);
937
+ }
938
+ /** @param {string} id @param {any} cfg */
939
+ const withDark = (id, cfg) => ({
940
+ ...cfg,
941
+ families: cfg.families.map((/** @type {any} */ f) => {
942
+ if (f?.id !== id) return f;
943
+ const anchor = {
944
+ mode: 'dark',
945
+ stop: fills[id].stop,
946
+ color: f.seed,
947
+ policy: 'exact',
948
+ };
949
+ const others = (f.anchors ?? []).filter(
950
+ (/** @type {any} */ a) =>
951
+ !(a.mode === 'dark' && a.stop === anchor.stop),
952
+ );
953
+ if (others.length < (f.anchors ?? []).length)
954
+ notes.push(
955
+ `${file}: your dark anchor at shade ${anchor.stop} of ${id} is replaced by your exact ${id} color`,
956
+ );
957
+ return {
958
+ ...f,
959
+ anchors: [...others, anchor].sort((a, b) =>
960
+ a.mode === b.mode ? a.stop - b.stop : a.mode === 'light' ? -1 : 1,
961
+ ),
962
+ };
963
+ }),
964
+ });
965
+ let next = config;
966
+ for (const id of add) {
967
+ const tried = withDark(id, next);
968
+ try {
969
+ generateTonalPalette(tried);
970
+ next = tried;
971
+ fills[id].dark = true;
972
+ } catch {
973
+ fills[id].why =
974
+ 'the dark shades cannot hold your exact color and stay in order from dark to light';
975
+ }
976
+ }
977
+ config.families = next.families;
978
+ }
979
+ return {config, notes, fills};
980
+ }
981
+
982
+ /**
983
+ * The palette config a theme's settings ask for (see {@link planPalette}),
984
+ * or null when it would hold no family.
985
+ * @param {string} cwd
986
+ * @param {string} slug
987
+ * @param {{mode?: string, settings: Setting[]}} data
988
+ * @param {{light: Record<string, string>, dark: Record<string, string>}} [base]
989
+ * @returns {any}
990
+ */
991
+ export function paletteConfig(cwd, slug, data, base) {
992
+ return planPalette(cwd, slug, data, base)?.config ?? null;
349
993
  }
350
994
 
995
+ /** @param {string} text */
996
+ const sha256 = text => createHash('sha256').update(text).digest('hex');
997
+
351
998
  /**
352
999
  * Write the palette config, palette and receipt the settings ask for, with
353
- * the same generator as `theme palette generate --out`; remove all three
354
- * when no family is left. Files are only rewritten when the config changes.
1000
+ * the same generator as `theme palette generate --out`; remove them all
1001
+ * when no family is left. The palette is generated again when the config
1002
+ * changes, when a file is missing, or when it came from another generator
1003
+ * version. A palette edited by hand ({@link paletteEdited}) is never
1004
+ * overwritten: a change that would rewrite it is refused with the commands
1005
+ * that keep or discard the edit; a change that leaves it alone goes ahead. Gives back what the config writer kept or replaced
1006
+ * of a hand edit, for the result notes.
355
1007
  * @param {string} cwd
356
1008
  * @param {string} slug
357
- * @param {import('./_settings.mjs').ThemeData} data
1009
+ * @param {{mode?: string, settings: Setting[], palette?: string}} data
1010
+ * `palette`: the hash of the config the editor wrote, kept in the settings
1011
+ * @param {{light: Record<string, string>, dark: Record<string, string>}} [base]
1012
+ * @returns {string[]}
358
1013
  */
359
- export function syncPalette(cwd, slug, data) {
1014
+ export function syncPalette(cwd, slug, data, base) {
360
1015
  const f = paletteFiles(slug);
361
1016
  const abs = (/** @type {string} */ p) => path.join(cwd, p);
362
- const config = paletteConfig(cwd, slug, data);
363
- if (!config) {
1017
+ const plan = planPalette(cwd, slug, data, base);
1018
+ if (!plan) {
364
1019
  // Only palette files the editor wrote go: a hand-made palette.config.json
365
1020
  // (and what it generated) stays.
366
1021
  // The hash the saved settings recorded too: an undo may carry settings
@@ -375,42 +1030,235 @@ export function syncPalette(cwd, slug, data) {
375
1030
  saved = undefined;
376
1031
  }
377
1032
  const hash = fs.existsSync(abs(f.config))
378
- ? createHash('sha256')
379
- .update(fs.readFileSync(abs(f.config)))
380
- .digest('hex')
1033
+ ? sha256(fs.readFileSync(abs(f.config), 'utf8'))
381
1034
  : null;
382
1035
  const mine = hash != null && (data.palette === hash || saved === hash);
383
1036
  delete data.palette;
384
- if (!mine) return;
385
- for (const p of [f.config, f.palette, f.receipt])
1037
+ if (!mine) return [];
1038
+ for (const p of [f.config, f.palette, f.receipt, f.refs])
386
1039
  fs.rmSync(abs(p), {force: true});
387
1040
  const tokensDir = path.dirname(abs(f.palette));
388
1041
  if (fs.existsSync(tokensDir) && !fs.readdirSync(tokensDir).length)
389
1042
  fs.rmdirSync(tokensDir);
390
- return;
1043
+ return [];
1044
+ }
1045
+ const text = `${JSON.stringify(plan.config, null, 2)}\n`;
1046
+ /** @type {any} */
1047
+ let receipt;
1048
+ try {
1049
+ receipt = JSON.parse(fs.readFileSync(abs(f.receipt), 'utf8'));
1050
+ } catch {
1051
+ receipt = null;
391
1052
  }
392
- const text = `${JSON.stringify(config, null, 2)}\n`;
393
1053
  const same =
394
1054
  fs.existsSync(abs(f.config)) &&
395
1055
  fs.readFileSync(abs(f.config), 'utf8') === text &&
396
1056
  fs.existsSync(abs(f.palette)) &&
397
- fs.existsSync(abs(f.receipt));
1057
+ receipt?.generatorVersion === PALETTE_GENERATOR_VERSION;
1058
+ // Nothing to rewrite: no notes either, so a kept hand edit is named once,
1059
+ // when a color change touches the config.
398
1060
  if (same) {
399
- data.palette = createHash('sha256').update(text).digest('hex');
400
- return;
1061
+ data.palette = sha256(text);
1062
+ return [];
401
1063
  }
1064
+ if (paletteEdited(cwd, slug)) {
1065
+ throw new AstryxError(
1066
+ `${f.palette} was edited by hand, so the editor will not write over it. To keep your edits, move the file out of tokens/ (it is then yours: import it in ${slug}.theme.ts); to discard them, delete it. Then run the command again, and the editor writes the generated shades back. Only color changes wait for this; other changes still work. Nothing was changed.`,
1067
+ [],
1068
+ ERROR_CODES.ERR_THEME_INVALID,
1069
+ );
1070
+ }
1071
+ fs.mkdirSync(path.dirname(abs(f.config)), {recursive: true});
402
1072
  writeWhole(abs(f.config), text);
403
- data.palette = createHash('sha256').update(text).digest('hex');
1073
+ data.palette = sha256(text);
404
1074
  themePaletteGenerate(f.config, {out: f.palette, overwrite: true}, {cwd});
1075
+ return plan.notes;
1076
+ }
1077
+
1078
+ /**
1079
+ * Text with the differences a formatter or a checkout makes taken out:
1080
+ * line endings, white space at line ends and at the end, and quote style.
1081
+ * @param {string} text
1082
+ */
1083
+ const normalized = text =>
1084
+ text
1085
+ .replace(/\r\n?/g, '\n')
1086
+ .replace(/[ \t]+$/gm, '')
1087
+ .replace(/'/g, '"')
1088
+ .trimEnd();
1089
+
1090
+ /**
1091
+ * The palette file the generator writes for a config, or null when it
1092
+ * cannot be generated.
1093
+ * @param {any} config
1094
+ * @returns {string | null}
1095
+ */
1096
+ function renderPalette(config) {
1097
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-palette-check-'));
1098
+ try {
1099
+ fs.writeFileSync(path.join(dir, 'config.json'), JSON.stringify(config));
1100
+ themePaletteGenerate('config.json', {out: 'palette.ts'}, {cwd: dir});
1101
+ return fs.readFileSync(path.join(dir, 'palette.ts'), 'utf8');
1102
+ } catch {
1103
+ return null;
1104
+ } finally {
1105
+ fs.rmSync(dir, {recursive: true, force: true});
1106
+ }
405
1107
  }
406
1108
 
407
- /** @param {any} config @returns {Candidate} */
408
- function generate(config) {
1109
+ /**
1110
+ * Whether a theme's palette file was edited by hand: its bytes match no
1111
+ * receipt, and, formatting aside, it is not what the generator writes for
1112
+ * the request it came from (the receipt's, else the config's). False when
1113
+ * there is no palette file.
1114
+ * @param {string} cwd
1115
+ * @param {string} slug
1116
+ */
1117
+ export function paletteEdited(cwd, slug) {
1118
+ const f = paletteFiles(slug);
1119
+ const file = path.join(cwd, f.palette);
1120
+ if (!fs.existsSync(file)) return false;
1121
+ const palette = fs.readFileSync(file, 'utf8');
1122
+ /** @type {any} */
1123
+ let receipt;
1124
+ try {
1125
+ receipt = JSON.parse(fs.readFileSync(path.join(cwd, f.receipt), 'utf8'));
1126
+ } catch {
1127
+ receipt = null;
1128
+ }
1129
+ if (receipt?.candidateSha256 === sha256(palette)) return false;
1130
+ /** @type {any} */
1131
+ let request = receipt?.request ?? null;
1132
+ if (!request)
1133
+ try {
1134
+ request = JSON.parse(fs.readFileSync(path.join(cwd, f.config), 'utf8'));
1135
+ } catch {
1136
+ request = null;
1137
+ }
1138
+ const expected = request ? renderPalette(request) : null;
1139
+ return expected == null || normalized(expected) !== normalized(palette);
1140
+ }
1141
+
1142
+ /**
1143
+ * The stops a source reads: `palette.<family>.<mode>[<stop>]`, any number
1144
+ * as the stop (a layout may have 12.5), and `palette.black` / `palette.white`.
1145
+ */
1146
+ const READS =
1147
+ /\bpalette(?:\.([a-z]\w*)|\["([a-z][a-z0-9-]*)"\])\.(light|dark)\[(\d+(?:\.\d+)?)\]|\bpalette\.(black|white)\b/g;
1148
+
1149
+ /** What the generated settings write for a stop before it becomes a reference. */
1150
+ const PLACEHOLDER = '@@palette:';
1151
+
1152
+ /**
1153
+ * Refuse generated text that still holds a stop placeholder: the CSS would
1154
+ * carry it as a value no browser reads.
1155
+ * @param {string} file shown in the refusal
1156
+ * @param {string} text
1157
+ */
1158
+ export function assertNoPlaceholder(file, text) {
1159
+ const at = text.indexOf(PLACEHOLDER);
1160
+ if (at < 0) return;
1161
+ const what = text.slice(at, at + 60).split(/["\s,)]/)[0];
1162
+ throw new AstryxError(
1163
+ `${file} would hold ${what}, a color reference that never resolved, so the change was not made. This is a bug in the editor; palette.config.json may hold a stop layout it cannot write. Nothing was changed.`,
1164
+ [],
1165
+ ERROR_CODES.ERR_THEME_INVALID,
1166
+ );
1167
+ }
1168
+
1169
+ /**
1170
+ * The module of only the stops a generated settings source reads, in the
1171
+ * shape `scripts/generate-selected-palette-refs.mjs` gives the official
1172
+ * themes, or null when it reads none.
1173
+ * @param {string} slug
1174
+ * @param {Candidate} candidate
1175
+ * @param {string} source
1176
+ * @returns {string | null}
1177
+ */
1178
+ export function paletteRefsSource(slug, candidate, source) {
1179
+ /** @type {Map<string, Map<Mode, Set<number>>>} */
1180
+ const used = new Map();
1181
+ /** @type {Set<'black' | 'white'>} */
1182
+ const ends = new Set();
1183
+ for (const m of source.matchAll(READS)) {
1184
+ if (m[5]) {
1185
+ ends.add(/** @type {'black' | 'white'} */ (m[5]));
1186
+ continue;
1187
+ }
1188
+ const family = m[1] ?? m[2];
1189
+ const modes = used.get(family) ?? new Map();
1190
+ used.set(family, modes);
1191
+ const mode = /** @type {Mode} */ (m[3]);
1192
+ (modes.get(mode) ?? modes.set(mode, new Set()).get(mode))?.add(
1193
+ Number(m[4]),
1194
+ );
1195
+ }
1196
+ if (!used.size && !ends.size) return null;
1197
+ const key = (/** @type {string} */ k) =>
1198
+ /^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k);
1199
+ /** @type {string[]} */
1200
+ const body = [];
1201
+ for (const [family, modes] of used) {
1202
+ body.push(` ${key(family)}: {`);
1203
+ for (const mode of /** @type {Mode[]} */ (['light', 'dark'])) {
1204
+ const stops = modes.get(mode);
1205
+ if (!stops) continue;
1206
+ const ramp = /** @type {any} */ (candidate.palette[family])?.[mode] ?? {};
1207
+ const pairs = [...stops]
1208
+ .sort((a, b) => a - b)
1209
+ .map(s => `${s}: '${ramp[s]}'`);
1210
+ body.push(` ${mode}: {${pairs.join(', ')}},`);
1211
+ }
1212
+ body.push(' },');
1213
+ }
1214
+ for (const end of ends)
1215
+ body.push(
1216
+ ` ${end}: '${end === 'black' ? PALETTE_BLACK : PALETTE_WHITE}',`,
1217
+ );
1218
+ return [
1219
+ `// Generated by \`${P}\` on every change: do not edit.`,
1220
+ `// Only the shades ${slug}.settings.ts reads, from ${slug}.palette.ts, so the`,
1221
+ '// theme ships no shade it does not use.',
1222
+ '// prettier-ignore',
1223
+ `export const ${refsName(slug)} = {`,
1224
+ ...body,
1225
+ '};',
1226
+ '',
1227
+ ].join('\n');
1228
+ }
1229
+
1230
+ /**
1231
+ * Write the selected stops module beside the palette for a generated
1232
+ * settings source, or remove it when the source reads no stop. A source
1233
+ * that still holds a stop placeholder is refused.
1234
+ * @param {string} cwd
1235
+ * @param {string} slug
1236
+ * @param {string} source the generated settings source
1237
+ * @param {PaletteMapping | null} pal
1238
+ */
1239
+ export function syncPaletteRefs(cwd, slug, source, pal) {
1240
+ assertNoPlaceholder(`themes/${slug}/${slug}.settings.ts`, source);
1241
+ const file = path.join(cwd, paletteFiles(slug).refs);
1242
+ const text = pal ? paletteRefsSource(slug, pal.candidate, source) : null;
1243
+ if (text == null) {
1244
+ fs.rmSync(file, {force: true});
1245
+ return;
1246
+ }
1247
+ fs.mkdirSync(path.dirname(file), {recursive: true});
1248
+ writeWhole(file, text);
1249
+ }
1250
+
1251
+ /**
1252
+ * @param {any} config
1253
+ * @param {string} [file] the config's path, for the refusal
1254
+ * @returns {Candidate}
1255
+ */
1256
+ function generate(config, file = 'palette.config.json') {
409
1257
  try {
410
1258
  return generateTonalPalette(config);
411
1259
  } catch (e) {
412
1260
  throw new AstryxError(
413
- `The palette could not be generated: ${e instanceof Error ? e.message : String(e)}. Nothing was changed.`,
1261
+ `${file}: the colors could not be generated: ${(e instanceof Error ? e.message : String(e)).replace(/\.$/, '')}. Fix that part of the file by hand, or remove it. Nothing was changed.`,
414
1262
  [],
415
1263
  ERROR_CODES.ERR_PALETTE_GENERATION,
416
1264
  );
@@ -418,24 +1266,39 @@ function generate(config) {
418
1266
  }
419
1267
 
420
1268
  /**
421
- * The stops from `start` toward `dir`, `start` first.
422
- * @param {number[]} stops
423
- * @param {number} start
424
- * @param {1 | -1} dir
1269
+ * The contrast ratio of two opaque colors. A color that does not parse is
1270
+ * a bug in the mapping, never a ratio of 0.
1271
+ * @param {string} a @param {string} b
425
1272
  */
426
- function walk(stops, start, dir) {
427
- const i = stops.includes(start)
428
- ? stops.indexOf(start)
429
- : stops.findIndex(s => s >= start);
430
- const from = i < 0 ? stops.length - 1 : i;
431
- return dir > 0 ? stops.slice(from) : stops.slice(0, from + 1).reverse();
432
- }
433
-
434
- /** @param {string} a @param {string} b */
435
1273
  function contrast(a, b) {
436
1274
  const x = parseColor(a);
437
1275
  const y = parseColor(b);
438
- return x && y ? ratio(x, y) : 0;
1276
+ if (!x || !y) throw new Error(`No contrast between "${a}" and "${b}".`);
1277
+ return ratio(x, y);
1278
+ }
1279
+
1280
+ /**
1281
+ * A translucent stop drawn over each surface, as the opaque colors the eye
1282
+ * sees; an opaque stop as it is.
1283
+ * @param {string} name @param {StopRef} r @param {Array<[string, string]>} under
1284
+ * @returns {Array<[string, string]>}
1285
+ */
1286
+ function over(name, r, under) {
1287
+ if (!r.alpha) return [[name, r.color]];
1288
+ const top = /** @type {[number, number, number]} */ (
1289
+ parseColor(r.color.slice(0, 7))
1290
+ );
1291
+ const a = parseInt(r.alpha, 16) / 255;
1292
+ return under.map(([n, bg]) => [
1293
+ `${name} over ${n}`,
1294
+ hex(
1295
+ compositeOver(
1296
+ top,
1297
+ a,
1298
+ /** @type {[number, number, number]} */ (parseColor(bg)),
1299
+ ),
1300
+ ),
1301
+ ]);
439
1302
  }
440
1303
 
441
1304
  /** @param {number} r */
@@ -455,50 +1318,80 @@ const round = r => Math.round(r * 100) / 100;
455
1318
  export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
456
1319
  const fams = dialFamilies(data);
457
1320
  if (!fams.length) return null;
458
- const config = paletteConfig(cwd, slug, data);
459
- const candidate = generate(config);
460
- /** The light fill starts at the family's light anchor, as the seed lands there. @param {string} id */
461
- const fillStart = id =>
462
- /** @type {any[]} */ (config.families)
463
- .find(f => f.id === id)
464
- ?.anchors?.find((/** @type {any} */ a) => a.mode === 'light')?.stop ??
465
- FILL[0];
466
- const {stops} = candidate;
1321
+ const plan = /** @type {PalettePlan} */ (planPalette(cwd, slug, data, base));
1322
+ const {config} = plan;
1323
+ const candidate = generate(config, paletteFiles(slug).config);
1324
+ const t = tools(candidate, data, base);
1325
+ const {stops, at, ref, exactOf, surfaces} = t;
1326
+ const modes = themeModes(data);
1327
+ /**
1328
+ * The secondary text color in a mode: an exact setting, else the neutral
1329
+ * color's, else the base theme's; null when it is not a fixed color.
1330
+ * @param {Mode} m
1331
+ */
1332
+ const textSecondary = m => {
1333
+ const v =
1334
+ exactOf('--color-text-secondary', m) ??
1335
+ tokens['--color-text-secondary']?.[m].color ??
1336
+ base?.[m]?.['--color-text-secondary'];
1337
+ return v && parseColor(v) && alphaOf(v) >= 1 ? v : null;
1338
+ };
467
1339
  /** @type {PaletteMapping['tokens']} */
468
1340
  const tokens = {};
469
1341
  /** @type {ContrastCheck[]} */
470
1342
  const checks = [];
471
- const has = (/** @type {string} */ t) => t in tokenDefaults;
472
- /** @param {string} id @param {Mode} m @param {number} stop @param {string} [alpha] @returns {StopRef} */
473
- const ref = (id, m, stop, alpha) => {
474
- const color = /** @type {any} */ (candidate.palette[id])[m][stop];
475
- return alpha ? {stop, color: `${color}${alpha}`, alpha} : {stop, color};
476
- };
477
- /** @param {string} token @param {string} id @param {StopRef} light @param {StopRef} dark */
478
- const put = (token, id, light, dark) => {
479
- if (has(token)) tokens[token] = {family: id, light, dark};
1343
+ /** @type {PaletteMapping['exact']} */
1344
+ const exact = {};
1345
+ const has = (/** @type {string} */ k) => k in tokenDefaults;
1346
+ /** A token the theme sets exactly in any mode: no check speaks for it. @param {string} k */
1347
+ const setExactly = k =>
1348
+ data.settings.some(
1349
+ s =>
1350
+ s.source === 'token' && s.thing === k && !s.on && !s.when && !s.state,
1351
+ );
1352
+ const reports = (/** @type {string} */ k) => has(k) && !setExactly(k);
1353
+ /**
1354
+ * Point a token at its stops. A theme with one mode has one ramp: the
1355
+ * other side repeats it.
1356
+ * @param {string} token @param {string} id @param {Partial<Record<Mode, StopRef>>} refs
1357
+ */
1358
+ const put = (token, id, refs) => {
1359
+ if (!has(token)) return;
1360
+ const one = /** @type {StopRef} */ (refs[modes[0]]);
1361
+ tokens[token] = {
1362
+ family: id,
1363
+ light: refs.light ?? one,
1364
+ dark: refs.dark ?? one,
1365
+ };
480
1366
  };
1367
+ /** @template T @param {(m: Mode) => T} fn @returns {Partial<Record<Mode, T>>} */
1368
+ const each = fn => Object.fromEntries(modes.map(m => [m, fn(m)]));
481
1369
  /**
482
- * The first stop from `start` toward more contrast that reads at `needs`
483
- * on every color in `on`; the most contrasting stop when none does.
1370
+ * The stop nearest `start` that reads at `needs` on every color in `on`,
1371
+ * searched both ways (the usual way first on a tie: darker in light,
1372
+ * lighter in dark), so a base with dark light-mode surfaces still finds
1373
+ * one; the most contrasting stop of all when none does.
484
1374
  * @param {string} token @param {string} id @param {Mode} m @param {number} start
485
1375
  * @param {Array<[string, string]>} on - `[name, color]` pairs.
486
1376
  * @param {number} needs
487
1377
  */
488
1378
  const pick = (token, id, m, start, on, needs) => {
489
- /** @type {{stop: number, r: number} | null} */
490
- let best = null;
491
- for (const stop of walk(stops, start, TOWARD_CONTRAST[m])) {
1379
+ const usual = TOWARD_CONTRAST[m];
1380
+ const order = [...stops].sort(
1381
+ (a, b) =>
1382
+ Math.abs(a - start) - Math.abs(b - start) ||
1383
+ (Math.sign(b - a) === usual ? 1 : -1),
1384
+ );
1385
+ /** @param {number} stop */
1386
+ const score = stop => {
492
1387
  const c = ref(id, m, stop).color;
493
- const r = Math.min(...on.map(([, bg]) => contrast(c, bg)));
494
- if (!best || r > best.r) best = {stop, r};
495
- if (r >= needs) {
496
- best = {stop, r};
497
- break;
498
- }
499
- }
500
- const b = /** @type {{stop: number, r: number}} */ (best);
501
- if (has(token))
1388
+ return Math.min(...on.map(([, bg]) => contrast(c, bg)));
1389
+ };
1390
+ const scored = order.map(stop => ({stop, r: score(stop)}));
1391
+ const b =
1392
+ scored.find(x => x.r >= needs) ??
1393
+ scored.reduce((x, y) => (y.r > x.r ? y : x));
1394
+ if (reports(token))
502
1395
  checks.push({
503
1396
  token,
504
1397
  mode: m,
@@ -511,138 +1404,10 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
511
1404
  });
512
1405
  return ref(id, m, b.stop);
513
1406
  };
514
- /**
515
- * A fill and the text on it: the fill moves toward more contrast until the
516
- * better of the two text stops reads at 4.5:1 on it.
517
- * @param {string} fillToken @param {string} onToken @param {string} id @param {Mode} m @param {number} start
518
- */
519
- const fillPair = (fillToken, onToken, id, m, start) => {
520
- /** @type {{fill: number, on: number, r: number} | null} */
521
- let best = null;
522
- for (const stop of walk(stops, start, TOWARD_CONTRAST[m])) {
523
- const fill = ref(id, m, stop).color;
524
- for (const on of ON_FILL[m]) {
525
- const r = contrast(ref(id, m, on).color, fill);
526
- if (!best || r > best.r + 0.01) best = {fill: stop, on, r};
527
- }
528
- if (/** @type {{r: number}} */ (best).r >= TEXT) break;
529
- }
530
- const b = /** @type {{fill: number, on: number, r: number}} */ (best);
531
- // The other text shade's ratio on the same fill, so a switch between
532
- // white and near-black text says why.
533
- const other = ON_FILL[m].find(on => on !== b.on);
534
- const otherR =
535
- other == null
536
- ? null
537
- : round(contrast(ref(id, m, other).color, ref(id, m, b.fill).color));
538
- if (has(onToken))
539
- checks.push({
540
- token: onToken,
541
- mode: m,
542
- stop: b.on,
543
- preferred: ON_FILL[m][0],
544
- against: `${fillToken} (shade ${b.fill})${otherR == null ? '' : `, where ${other === 100 ? 'white' : other === 0 || other === 5 ? 'near-black' : `shade ${other}`} text reads at only ${otherR}:1`}`,
545
- ratio: round(b.r),
546
- needs: TEXT,
547
- pass: b.r >= TEXT,
548
- });
549
- return {fill: ref(id, m, b.fill), on: ref(id, m, b.on), moved: b.fill};
550
- };
551
-
552
- /**
553
- * The dark fill as the exact color given, when text on it reads at 4.5:1
554
- * (white first, then the dark text stop) and it stands out from the dark
555
- * surfaces at 3:1; no pair otherwise, with why.
556
- * @param {string} fillToken @param {string} onToken @param {string} id @param {number} seedStop
557
- * @returns {{pair: ReturnType<typeof fillPair> | null, ratio: number, why: string}}
558
- */
559
- const exactDarkFill = (fillToken, onToken, id, seedStop) => {
560
- const fill = ref(id, 'light', seedStop);
561
- const best = [...ON_FILL.dark]
562
- .reverse()
563
- .map(on => ({on, r: contrast(ref(id, 'dark', on).color, fill.color)}))
564
- .reduce((a, b) => (b.r > a.r + 0.01 ? b : a));
565
- if (best.r < TEXT)
566
- return {
567
- pair: null,
568
- ratio: round(best.r),
569
- why: `your exact color reads at only ${round(best.r)}:1 with any text shade, and text needs ${TEXT}:1`,
570
- };
571
- // The fill must also stand out from the dark surfaces it sits on.
572
- const page = Math.min(
573
- ...surfaces('dark', id).map(([, bg]) => contrast(fill.color, bg)),
574
- );
575
- if (page < NON_TEXT)
576
- return {
577
- pair: null,
578
- ratio: round(page),
579
- why: `your exact color stands out from the dark page at only ${round(page)}:1, and a fill needs ${NON_TEXT}:1`,
580
- };
581
- if (has(onToken))
582
- checks.push({
583
- token: onToken,
584
- mode: 'dark',
585
- stop: best.on,
586
- preferred: ON_FILL.dark[1],
587
- against: `${fillToken} (your exact color)`,
588
- ratio: round(best.r),
589
- needs: TEXT,
590
- pass: true,
591
- });
592
- return {
593
- pair: {
594
- fill: {...fill, from: /** @type {Mode} */ ('light')},
595
- on: ref(id, 'dark', best.on),
596
- moved: FILL[1],
597
- },
598
- ratio: round(best.r),
599
- why: '',
600
- };
601
- };
602
-
603
- /**
604
- * The dark shade nearest the seed's own shade (a lighter one on a tie)
605
- * where text on it reads at 4.5:1 and it stands out from the dark
606
- * surfaces at 3:1; null when no shade does both.
607
- * @param {string} onToken @param {string} id @param {number} seedStop
608
- */
609
- const nearestDarkFill = (onToken, id, seedStop) => {
610
- const page = surfaces('dark', id);
611
- const order = [...stops]
612
- .filter(s => s > 0 && s < 100)
613
- .sort((a, b) => Math.abs(a - seedStop) - Math.abs(b - seedStop) || b - a);
614
- for (const stop of order) {
615
- const fill = ref(id, 'dark', stop).color;
616
- if (Math.min(...page.map(([, bg]) => contrast(fill, bg))) < NON_TEXT)
617
- continue;
618
- const best = ON_FILL.dark
619
- .map(on => ({on, r: contrast(ref(id, 'dark', on).color, fill)}))
620
- .reduce((a, b) => (b.r > a.r + 0.01 ? b : a));
621
- if (best.r < TEXT) continue;
622
- if (has(onToken))
623
- checks.push({
624
- token: onToken,
625
- mode: 'dark',
626
- stop: best.on,
627
- preferred: ON_FILL.dark[0],
628
- against: `the fill (shade ${stop})`,
629
- ratio: round(best.r),
630
- needs: TEXT,
631
- pass: true,
632
- });
633
- return {
634
- fill: ref(id, 'dark', stop),
635
- on: ref(id, 'dark', best.on),
636
- moved: stop,
637
- };
638
- }
639
- return null;
640
- };
641
1407
 
642
- const modes = /** @type {Mode[]} */ (['light', 'dark']);
643
1408
  const neutral = fams.find(f => f.id === 'neutral');
644
1409
  if (neutral) {
645
- for (const [token, [l, d]] of Object.entries(NEUTRAL_STOPS)) {
1410
+ for (const [token, pair] of Object.entries(NEUTRAL_STOPS)) {
646
1411
  if (
647
1412
  token === '--color-text-secondary' ||
648
1413
  token === '--color-icon-secondary'
@@ -651,82 +1416,42 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
651
1416
  put(
652
1417
  token,
653
1418
  'neutral',
654
- ref('neutral', 'light', l),
655
- ref('neutral', 'dark', d),
1419
+ each(m => ref('neutral', m, at(pair[m === 'light' ? 0 : 1]))),
656
1420
  );
657
1421
  }
658
- for (const [token, [[l, la], [d, da]]] of Object.entries(NEUTRAL_TINTS))
1422
+ for (const [token, pair] of Object.entries(NEUTRAL_TINTS))
659
1423
  put(
660
1424
  token,
661
1425
  'neutral',
662
- ref('neutral', 'light', l, la),
663
- ref('neutral', 'dark', d, da),
1426
+ each(m => {
1427
+ const [s, a] = pair[m === 'light' ? 0 : 1];
1428
+ return ref('neutral', m, at(s), a);
1429
+ }),
664
1430
  );
665
- }
666
- /** What text sits on in each mode: the neutral surfaces, else the base theme's. @param {Mode} m @param {string} id */
667
- const surfaces = (m, id) => {
668
- const names = [
669
- '--color-background-surface',
670
- '--color-background-body',
671
- '--color-background-card',
672
- ];
673
- /** @type {Array<[string, string]>} */
674
- const out = [];
675
- for (const n of names) {
676
- // The theme's own exact page and surface colors win, as they do in
677
- // the built theme.
678
- const exact = [...data.settings]
679
- .reverse()
680
- .find(
681
- s =>
682
- s.source === 'token' &&
683
- s.thing === n &&
684
- !s.on &&
685
- !s.when &&
686
- !s.state &&
687
- (!s.mode || s.mode === m),
688
- )?.value;
689
- const v = exact ?? tokens[n]?.[m].color ?? base[m][n];
690
- if (v && parseColor(v)) out.push([n, v]);
691
- }
692
- if (!out.length)
693
- out.push([
694
- `${id} shade ${NEUTRAL_STOPS['--color-background-surface'][m === 'light' ? 0 : 1]}`,
695
- ref(
696
- id,
697
- m,
698
- NEUTRAL_STOPS['--color-background-surface'][m === 'light' ? 0 : 1],
699
- ).color,
700
- ]);
701
- return out;
702
- };
703
- if (neutral) {
704
- const [[tl, td], [il, id]] = [
705
- NEUTRAL_STOPS['--color-text-secondary'],
706
- NEUTRAL_STOPS['--color-icon-secondary'],
707
- ];
708
- const text = modes.map((m, i) =>
709
- pick(
710
- '--color-text-secondary',
711
- 'neutral',
712
- m,
713
- [tl, td][i],
714
- surfaces(m, 'neutral'),
715
- TEXT,
716
- ),
717
- );
718
- put('--color-text-secondary', 'neutral', text[0], text[1]);
719
- const icon = modes.map((m, i) =>
720
- pick(
721
- '--color-icon-secondary',
1431
+ for (const [token, needs] of /** @type {const} */ ([
1432
+ ['--color-text-secondary', TEXT],
1433
+ ['--color-icon-secondary', NON_TEXT],
1434
+ ]))
1435
+ put(
1436
+ token,
722
1437
  'neutral',
723
- m,
724
- [il, id][i],
725
- surfaces(m, 'neutral'),
726
- NON_TEXT,
727
- ),
728
- );
729
- put('--color-icon-secondary', 'neutral', icon[0], icon[1]);
1438
+ each(m =>
1439
+ pick(
1440
+ token,
1441
+ 'neutral',
1442
+ m,
1443
+ at(NEUTRAL_STOPS[token][m === 'light' ? 0 : 1]),
1444
+ surfaces(m, 'neutral'),
1445
+ needs,
1446
+ ),
1447
+ ),
1448
+ );
1449
+ const surface = paletteToken('neutral');
1450
+ const set = each(m => exactOf(surface, m));
1451
+ if (Object.values(set).some(Boolean))
1452
+ exact[surface] = /** @type {Partial<Record<Mode, string>>} */ (
1453
+ Object.fromEntries(Object.entries(set).filter(([, v]) => v))
1454
+ );
730
1455
  }
731
1456
 
732
1457
  for (const f of fams) {
@@ -753,75 +1478,228 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
753
1478
  border: null,
754
1479
  focus: '--focus-outline-color',
755
1480
  };
756
- const muted = modes.map((m, i) => ref(f.id, m, MUTED[i]));
757
- put(names.muted, f.id, muted[0], muted[1]);
758
- const pairs = modes.map(m => {
759
- if (m === 'light')
760
- return fillPair(names.fill, names.on, f.id, m, fillStart(f.id));
761
- const exact = exactDarkFill(names.fill, names.on, f.id, fillStart(f.id));
762
- if (exact.pair) return exact.pair;
763
- const pair =
764
- nearestDarkFill(names.on, f.id, fillStart(f.id)) ??
765
- fillPair(names.fill, names.on, f.id, m, FILL[1]);
766
- if (has(names.fill))
1481
+ const plain = plan.fills[f.id];
1482
+ const S = plain.stop;
1483
+ const fillWord = f.id;
1484
+ /** @type {Partial<Record<Mode, string>>} */
1485
+ const exactFill = {};
1486
+ for (const m of modes) {
1487
+ const v = exactOf(names.fill, m);
1488
+ if (v) exactFill[m] = v;
1489
+ }
1490
+ if (Object.keys(exactFill).length) exact[names.fill] = exactFill;
1491
+
1492
+ /** @type {Partial<Record<Mode, StopRef>>} */
1493
+ const fill = {};
1494
+ for (const m of modes) {
1495
+ if (m === 'light' || plain.dark) {
1496
+ fill[m] = {...ref(f.id, m, S), exact: true};
1497
+ continue;
1498
+ }
1499
+ // The dark fill when the exact color does not read there: shade 70,
1500
+ // else the shade nearest 70 that passes, else 70.
1501
+ const start = at(DARK_FILL);
1502
+ const order = [...stops]
1503
+ .filter(s => s > 0 && s < 100)
1504
+ .sort((a, b) => Math.abs(a - start) - Math.abs(b - start) || b - a);
1505
+ const found =
1506
+ order.find(s => {
1507
+ const c = ref(f.id, m, s).color;
1508
+ return (
1509
+ t.page(c, m, f.id) >= NON_TEXT && t.onFor(f.id, m, c).r >= TEXT
1510
+ );
1511
+ }) ?? start;
1512
+ fill[m] = ref(f.id, m, found);
1513
+ if (reports(names.fill))
767
1514
  checks.push({
768
1515
  token: names.fill,
769
- mode: 'dark',
770
- stop: pair.fill.stop,
771
- preferred: fillStart(f.id),
772
- against: `the text on it: ${exact.why}`,
773
- ratio: exact.ratio,
1516
+ mode: m,
1517
+ stop: found,
1518
+ preferred: S,
1519
+ against: 'the dark page and the text on it',
1520
+ ratio: plain.ratio,
774
1521
  needs: TEXT,
775
1522
  pass: true,
1523
+ note: `in dark, ${names.fill} is shade ${found}, not your exact color: ${plain.why}${found === start ? '' : `; shade ${start} does not pass either, so it is the nearest shade that does`}`,
1524
+ });
1525
+ }
1526
+ put(names.fill, f.id, fill);
1527
+
1528
+ // Text on the fill reads on the fill the theme really uses: the exact
1529
+ // token setting when there is one. The exact color never moves; the
1530
+ // text changes instead.
1531
+ const on = each(m => {
1532
+ const used = exactFill[m] ?? /** @type {StopRef} */ (fill[m]).color;
1533
+ const o = t.onFor(fillWord, m, used);
1534
+ const what = exactFill[m]
1535
+ ? `your exact ${names.fill} (${used})`
1536
+ : `${names.fill} (shade ${fill[m]?.stop})`;
1537
+ const moved = o.on !== o.first;
1538
+ if (reports(names.on))
1539
+ checks.push({
1540
+ token: names.on,
1541
+ mode: m,
1542
+ stop: o.on.stop,
1543
+ preferred: o.first.stop,
1544
+ against: what,
1545
+ ratio: round(o.r),
1546
+ needs: TEXT,
1547
+ pass: o.r >= TEXT,
1548
+ ...(o.r < TEXT
1549
+ ? {
1550
+ note: `text on ${what} reads at only ${round(o.r)}:1 in ${m} with white or near-black text (needs ${TEXT}:1); the fill keeps your color: pick a lighter or darker ${f.id}, or set ${names.on} exactly`,
1551
+ }
1552
+ : moved
1553
+ ? {
1554
+ note: `${names.on} uses ${textName(o.on)} text in ${m}, not ${textName(o.first)}, so it reads at ${round(o.r)}:1 on ${what}, where ${textName(o.other)} text reads at only ${round(o.otherR)}:1`,
1555
+ }
1556
+ : {}),
776
1557
  });
777
- return pair;
1558
+ return o.on;
778
1559
  });
779
- put(names.fill, f.id, pairs[0].fill, pairs[1].fill);
780
- put(names.on, f.id, pairs[0].on, pairs[1].on);
781
- const text = modes.map((m, i) =>
1560
+ put(names.on, f.id, on);
1561
+
1562
+ // A pale fill in light can disappear into the page: say so, and keep
1563
+ // the exact color, the dial's or the token's.
1564
+ if (modes.includes('light') && has(names.fill)) {
1565
+ const used = exactFill.light ?? /** @type {StopRef} */ (fill.light).color;
1566
+ const p = t.page(used, 'light', f.id);
1567
+ if (p < NON_TEXT)
1568
+ checks.push({
1569
+ token: names.fill,
1570
+ mode: 'light',
1571
+ stop: S,
1572
+ preferred: S,
1573
+ against: 'the light page',
1574
+ ratio: round(p),
1575
+ needs: NON_TEXT,
1576
+ pass: false,
1577
+ note: exactFill.light
1578
+ ? `in light, your exact ${names.fill} (${used}) stands out from the page at only ${round(p)}:1, and a fill needs ${NON_TEXT}:1, so its buttons and badges may not show: give it a darker color`
1579
+ : `in light, your exact ${f.id} stands out from the page at only ${round(p)}:1, and a fill needs ${NON_TEXT}:1, so ${names.fill} buttons and badges may not show: pick a darker ${f.id}`,
1580
+ });
1581
+ }
1582
+
1583
+ // The tint: never the fill's own shade, see-through or not. The accent
1584
+ // tint keeps the official stop (85 light, 30 dark) unless Core's
1585
+ // citation text (--color-text-secondary) reads on it below both 4.5:1
1586
+ // and the official neutral theme's own pair (text-secondary on the
1587
+ // accent tint, read from the installed theme); only then it takes the
1588
+ // nearest shade that reads that well (darker first in dark, lighter
1589
+ // first in light), so it never ships below the official theme.
1590
+ const muted = each(m => {
1591
+ const i = m === 'light' ? 0 : 1;
1592
+ const spec = word ? STATUS_MUTED[i] : ACCENT_MUTED[i];
1593
+ const [s, alpha] = Array.isArray(spec) ? spec : [spec, undefined];
1594
+ const start = at(s);
1595
+ // Nearest first, both ways: lighter first in light, darker in dark.
1596
+ const usual = m === 'light' ? 1 : -1;
1597
+ const away = [...stops]
1598
+ .filter(x => x !== fill[m]?.stop)
1599
+ .sort(
1600
+ (a, b) =>
1601
+ Math.abs(a - start) - Math.abs(b - start) ||
1602
+ (Math.sign(b - a) === usual ? 1 : -1),
1603
+ );
1604
+ const secondary = word ? null : textSecondary(m);
1605
+ if (!secondary) return ref(f.id, m, away[0] ?? start, alpha);
1606
+ const scored = away.map(x => ({
1607
+ stop: x,
1608
+ r: contrast(secondary, ref(f.id, m, x).color),
1609
+ }));
1610
+ const official = officialCitation(m);
1611
+ if (official == null) return ref(f.id, m, away[0] ?? start, alpha);
1612
+ // Readable text (4.5:1) or the official theme's own ratio, whichever
1613
+ // asks less: in dark the official pair reads under 4.5:1, so that is
1614
+ // the bar; in light it reads above, so the tint moves only for text
1615
+ // that does not read.
1616
+ const needs = Math.min(TEXT, official);
1617
+ const b =
1618
+ scored.find(x => x.r >= needs - 0.005) ??
1619
+ scored.reduce((x, y) => (y.r > x.r ? y : x));
1620
+ const pass = b.r >= needs - 0.005;
1621
+ if (reports(names.muted) && (b.stop !== start || !pass))
1622
+ checks.push({
1623
+ token: names.muted,
1624
+ mode: m,
1625
+ stop: b.stop,
1626
+ preferred: start,
1627
+ against: 'citation text (--color-text-secondary)',
1628
+ ratio: round(b.r),
1629
+ needs: round(needs),
1630
+ pass,
1631
+ note: pass
1632
+ ? `${names.muted} uses shade ${b.stop} in ${m}, not ${start}, so citation text (--color-text-secondary) reads at ${round(b.r)}:1 on it${needs < TEXT ? `, as well as in the official neutral theme (${round(needs)}:1)` : ''}`
1633
+ : `citation text (--color-text-secondary) reads at only ${round(b.r)}:1 in ${m} on ${names.muted} even at shade ${b.stop}, the most contrasting one (needs ${round(needs)}:1): pick another ${f.id}, or set ${names.muted} exactly`,
1634
+ });
1635
+ return ref(f.id, m, b.stop, alpha);
1636
+ });
1637
+ put(names.muted, f.id, muted);
1638
+ /** The tint the theme really shows: an exact setting wins. @param {Mode} m */
1639
+ const mutedSeen = m => {
1640
+ const own = exactOf(names.muted, m);
1641
+ return own
1642
+ ? [/** @type {[string, string]} */ ([`your exact ${names.muted}`, own])]
1643
+ : over(
1644
+ names.muted,
1645
+ /** @type {StopRef} */ (muted[m]),
1646
+ surfaces(m, f.id),
1647
+ );
1648
+ };
1649
+
1650
+ const text = each(m =>
782
1651
  pick(
783
1652
  names.text,
784
1653
  f.id,
785
1654
  m,
786
- TEXT_STOP[i],
787
- [...surfaces(m, f.id), [names.muted, muted[i].color]],
1655
+ at(TEXT_STOP[m === 'light' ? 0 : 1]),
1656
+ [...surfaces(m, f.id), ...mutedSeen(m)],
788
1657
  TEXT,
789
1658
  ),
790
1659
  );
791
- put(names.text, f.id, text[0], text[1]);
792
- put(names.icon, f.id, text[0], text[1]);
1660
+ put(names.text, f.id, text);
1661
+ put(names.icon, f.id, text);
793
1662
  if (names.onMuted) {
794
- const on = modes.map((m, i) =>
795
- pick(
796
- /** @type {string} */ (names.onMuted),
797
- f.id,
798
- m,
799
- ON_MUTED[i],
800
- [[names.muted, muted[i].color]],
801
- TEXT,
1663
+ const onMuted = /** @type {string} */ (names.onMuted);
1664
+ put(
1665
+ onMuted,
1666
+ f.id,
1667
+ each(m =>
1668
+ pick(
1669
+ onMuted,
1670
+ f.id,
1671
+ m,
1672
+ at(ON_MUTED[m === 'light' ? 0 : 1]),
1673
+ mutedSeen(m),
1674
+ TEXT,
1675
+ ),
802
1676
  ),
803
1677
  );
804
- put(names.onMuted, f.id, on[0], on[1]);
805
1678
  }
806
1679
  if (names.border)
807
1680
  put(
808
1681
  names.border,
809
1682
  f.id,
810
- ref(f.id, 'light', BORDER[0]),
811
- ref(f.id, 'dark', BORDER[1]),
1683
+ each(m => ref(f.id, m, at(BORDER[m === 'light' ? 0 : 1]))),
812
1684
  );
813
- if (names.focus) {
814
- const ring = modes.map((m, i) =>
815
- pick(
816
- /** @type {string} */ (names.focus),
817
- f.id,
818
- m,
819
- pairs[i].moved,
820
- surfaces(m, f.id),
821
- NON_TEXT,
1685
+ // The focus ring follows the fill; with an exact fill it keeps
1686
+ // following that (Core's ring reads --color-accent).
1687
+ if (names.focus && !Object.keys(exactFill).length) {
1688
+ const focus = /** @type {string} */ (names.focus);
1689
+ put(
1690
+ focus,
1691
+ f.id,
1692
+ each(m =>
1693
+ pick(
1694
+ focus,
1695
+ f.id,
1696
+ m,
1697
+ /** @type {StopRef} */ (fill[m]).stop,
1698
+ surfaces(m, f.id),
1699
+ NON_TEXT,
1700
+ ),
822
1701
  ),
823
1702
  );
824
- put(names.focus, f.id, ring[0], ring[1]);
825
1703
  }
826
1704
  }
827
1705
  return {
@@ -830,6 +1708,15 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
830
1708
  tokens,
831
1709
  contrast: checks,
832
1710
  vibrancy: config.vibrancy ?? VIBRANCY_DEFAULT,
1711
+ exact,
1712
+ notes: [
1713
+ ...plan.notes,
1714
+ ...(paletteEdited(cwd, slug)
1715
+ ? [
1716
+ `${paletteFiles(slug).palette} was edited by hand: the theme reads only the shades in ${paletteFiles(slug).refs}, which the editor writes, so the edit does not show, and the next color change asks whether to keep or discard it`,
1717
+ ]
1718
+ : []),
1719
+ ],
833
1720
  };
834
1721
  }
835
1722
 
@@ -863,6 +1750,7 @@ export const PALETTE_TOKENS = new Set([
863
1750
  export function mappingRows(dial) {
864
1751
  if (dial === 'neutral')
865
1752
  return [
1753
+ 'your exact color sits at its own shade, light and dark, and the shades around it follow it (white and black are already the ends of every ramp)',
866
1754
  ...Object.entries(NEUTRAL_STOPS).map(
867
1755
  ([t, [l, d]]) =>
868
1756
  `${t}: light shade ${l}, dark shade ${d}${t.endsWith('-secondary') ? ` (moves to a shade that reads at ${t.includes('icon') ? NON_TEXT : TEXT}:1 on the surfaces)` : ''}`,
@@ -871,16 +1759,23 @@ export function mappingRows(dial) {
871
1759
  ([t, [[l, la], [d, da]]]) =>
872
1760
  `${t}: light shade ${l} at opacity ${la}, dark shade ${d} at opacity ${da}`,
873
1761
  ),
1762
+ "--color-background-body: the base theme's page color, so a tinted gray never tints the page",
874
1763
  ];
875
1764
  const word = dial === 'accent' ? null : STATUS_TOKEN[dial];
876
1765
  if (dial !== 'accent' && !word) return [];
877
1766
  const t = (/** @type {string} */ a, /** @type {string} */ b) =>
878
1767
  word ? a.replace('$', word) : b;
1768
+ const onFirst =
1769
+ dial === 'warning'
1770
+ ? 'near-black first in both modes'
1771
+ : 'white first in light, near-black first in dark';
879
1772
  const rows = [
880
- `${t('--color-$', '--color-accent')}: the color you gave, exactly, in light, and in dark when text on it reads at ${TEXT}:1 and it stands out from the dark page at ${NON_TEXT}:1; otherwise dark mode uses the shade nearest your color that passes both, and the result says so`,
881
- `${t('--color-on-$', '--color-on-accent')}: shade ${ON_FILL.light[0]} or ${ON_FILL.light[1]} in light, ${ON_FILL.dark[0]} or ${ON_FILL.dark[1]} in dark, whichever reads better on the fill`,
882
- `${t('--color-text-$', '--color-text-accent')} and ${t('--color-icon-$', '--color-icon-accent')}: light shade ${TEXT_STOP[0]}, dark shade ${TEXT_STOP[1]} (moves until it reads at ${TEXT}:1 on the surfaces and the muted tint)`,
883
- `${t('--color-$-muted', '--color-accent-muted')}: light shade ${MUTED[0]}, dark shade ${MUTED[1]}`,
1773
+ `${t('--color-$', '--color-accent')}: the color you gave, exactly, in light, and in dark when text on it reads at ${TEXT}:1 and it stands out from the dark page at ${NON_TEXT}:1; otherwise dark mode uses shade ${DARK_FILL}, or the shade nearest it that passes both, and the result says so. A light fill that stands out from the page at under ${NON_TEXT}:1 keeps your color, and the result says so`,
1774
+ `${t('--color-on-$', '--color-on-accent')}: the neutral color's white or near-black (${onFirst}; pure white or black without a neutral color), whichever reads at ${TEXT}:1 on the fill the theme uses`,
1775
+ `${t('--color-text-$', '--color-text-accent')} and ${t('--color-icon-$', '--color-icon-accent')}: light shade ${TEXT_STOP[0]}, dark shade ${TEXT_STOP[1]} (moves to the nearest shade, darker or lighter, that reads at ${TEXT}:1 on the surfaces and the muted tint)`,
1776
+ word
1777
+ ? `--color-${word}-muted: light shade ${STATUS_MUTED[0]}, dark shade ${STATUS_MUTED[1][0]} at opacity ${STATUS_MUTED[1][1]} over the surface, never the fill's own shade`
1778
+ : `--color-accent-muted: light shade ${ACCENT_MUTED[0]}, dark shade ${ACCENT_MUTED[1]}, as the official neutral theme maps it; moved to the nearest shade only when citation text (--color-text-secondary) would read on it below both ${TEXT}:1 and the official theme's own ratio, and never the fill's own shade`,
884
1779
  ];
885
1780
  if (word)
886
1781
  rows.push(
@@ -889,15 +1784,20 @@ export function mappingRows(dial) {
889
1784
  );
890
1785
  else
891
1786
  rows.push(
892
- `--focus-outline-color (the focus ring): the accent's shade, moved until it reads at ${NON_TEXT}:1 on the surfaces`,
1787
+ `--focus-outline-color (the focus ring): the fill's shade, moved until it reads at ${NON_TEXT}:1 on the surfaces; with an exact --color-accent it follows that`,
893
1788
  'links and selection read --color-text-accent and --color-accent; Core has no separate accent hover or pressed tokens (buttons tint with the overlay tokens, which the neutral dial sets)',
894
1789
  );
1790
+ rows.push(
1791
+ `an exact ${t('--color-$', '--color-accent')} setting wins: the text on it is picked to read on your color, and the other tokens keep the generated shades`,
1792
+ );
895
1793
  return rows;
896
1794
  }
897
1795
 
898
1796
  /**
899
- * What one color dial did, for the result notes: the shade of its main token
1797
+ * What one color dial did, for the result notes: what its main token uses
900
1798
  * in each mode, every token contrast moved, and last the generated files.
1799
+ * What the config writer kept or replaced of a hand edit comes from the
1800
+ * build ({@link syncPalette}).
901
1801
  * @param {PaletteMapping | null} pal
902
1802
  * @param {string} dial
903
1803
  * @param {string} slug
@@ -907,25 +1807,39 @@ export function mappingRows(dial) {
907
1807
  export function paletteNotes(pal, dial, slug, modes = ['light', 'dark']) {
908
1808
  if (!pal) return [];
909
1809
  const f = paletteFiles(slug);
910
- const main = pal.tokens[paletteToken(dial)];
1810
+ const token = paletteToken(dial);
1811
+ const main = pal.tokens[token];
1812
+ const exact = pal.exact[token];
911
1813
  /** @type {string[]} */
912
1814
  const notes = [];
913
- const lightPart = `${dial} shade ${main?.light.stop} (${main?.light.color}) in light`;
914
- const darkPart = main?.dark.from
915
- ? 'the same exact color in dark'
916
- : `shade ${main?.dark.stop} (${main?.dark.color}) in dark`;
917
- if (main)
1815
+ if (exact) {
1816
+ const shown = modes
1817
+ .filter(m => exact[m])
1818
+ .map(m => `${exact[m]}${modes.length > 1 ? ` in ${m}` : ''}`)
1819
+ .join(' and ');
918
1820
  notes.push(
919
- `${paletteToken(dial)} uses ${modes.length > 1 ? `${lightPart} and ${darkPart}` : modes[0] === 'light' ? lightPart : darkPart.replace(/^shade/, `${dial} shade`).replace(/^the same exact color/, 'your exact color')}`,
1821
+ `${token} uses your exact setting (${shown}), not the generated ${dial} shade: an exact setting wins${dial === 'neutral' ? '' : '; the text on it is picked to read on your color'}${dial === 'accent' ? ', and the focus ring keeps following it' : ''}`,
1822
+ );
1823
+ } else if (main) {
1824
+ /** @param {Mode} m */
1825
+ const part = m =>
1826
+ main[m].exact
1827
+ ? m === 'dark' && modes.length > 1
1828
+ ? 'the same exact color in dark'
1829
+ : `your exact color (${main[m].color}, ${dial} shade ${main[m].stop}) in ${m}`
1830
+ : `${dial} shade ${main[m].stop} (${main[m].color}) in ${m}`;
1831
+ notes.push(`${token} uses ${modes.map(part).join(' and ')}`);
1832
+ }
1833
+ const given = pal.families.find(x => x.dial === dial);
1834
+ if (given && isClipped(given.value))
1835
+ notes.push(
1836
+ `your ${dial} ${given.value} is outside the colors every screen shows (sRGB), so the nearest one, ${given.seed}, is used`,
920
1837
  );
921
1838
  for (const c of pal.contrast) {
922
1839
  if (pal.tokens[c.token]?.family !== dial) continue;
923
1840
  // A theme with one mode never shows the other one's shades.
924
1841
  if (!modes.includes(c.mode)) continue;
925
- if (c.against.startsWith('the text on it'))
926
- notes.push(
927
- `in dark, ${c.token} is shade ${c.stop}, not your exact color: ${c.against.slice('the text on it: '.length)}`,
928
- );
1842
+ if (c.note) notes.push(c.note);
929
1843
  else if (!c.pass)
930
1844
  notes.push(
931
1845
  `${c.token} reads at only ${c.ratio}:1 in ${c.mode} on ${c.against} (needs ${c.needs}:1) even at shade ${c.stop}, the most contrasting one: pick a lighter or darker ${dial}, or set ${c.token} exactly`,
@@ -936,7 +1850,7 @@ export function paletteNotes(pal, dial, slug, modes = ['light', 'dark']) {
936
1850
  );
937
1851
  }
938
1852
  notes.push(
939
- `the generated colors are in ${f.palette}, made from ${f.config} (receipt: ${f.receipt})`,
1853
+ `the generated colors are in ${f.palette}, made from ${f.config} (receipt: ${f.receipt}); the theme imports only the shades it uses, from ${f.refs}`,
940
1854
  );
941
1855
  return notes;
942
1856
  }