@astryxdesign/cli 0.7.14-canary.gfb823d9 → 0.7.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/CHANGELOG.md +197 -0
  2. package/api/component/_adapter.d.mts +15 -0
  3. package/api/component/_adapter.mjs +76 -0
  4. package/api/component/component.mjs +8 -1
  5. package/api/search/_named-keywords.d.mts +31 -0
  6. package/api/search/_named-keywords.mjs +177 -0
  7. package/api/search/search-index.mjs +8 -1
  8. package/api/search/search.d.mts +6 -1
  9. package/api/search/search.mjs +49 -8
  10. package/api/theme/_adapter.d.mts +33 -0
  11. package/api/theme/_adapter.mjs +352 -16
  12. package/api/theme/build/build.mjs +261 -10
  13. package/api/theme/eject/eject.mjs +13 -1
  14. package/api/theme/list/list.mjs +11 -2
  15. package/api/theme/palette/generate/color.d.mts +2 -0
  16. package/api/theme/palette/generate/color.mjs +1 -1
  17. package/api/theme/template/template.mjs +139 -6
  18. package/api/theme/theme.type.d.mts +15 -1
  19. package/api/theme/theme.type.mjs +9 -3
  20. package/api/theme/themeAdd.doc.mjs +1 -1
  21. package/api/theme/themeBuild.doc.mjs +10 -2
  22. package/api/theme/themeEject.doc.mjs +2 -2
  23. package/api/theme/themeListAvailable.doc.mjs +1 -1
  24. package/api/theme/themeRemove.doc.mjs +1 -1
  25. package/api/theme/themeTemplate.doc.mjs +8 -0
  26. package/api/theme/themeUse.doc.mjs +1 -1
  27. package/api/theme-edit/_adapter.d.mts +36 -2
  28. package/api/theme-edit/_adapter.mjs +340 -12
  29. package/api/theme-edit/_check.d.mts +28 -25
  30. package/api/theme-edit/_check.mjs +876 -308
  31. package/api/theme-edit/_color.d.mts +53 -4
  32. package/api/theme-edit/_color.mjs +406 -79
  33. package/api/theme-edit/_compiler.d.mts +14 -6
  34. package/api/theme-edit/_compiler.mjs +89 -59
  35. package/api/theme-edit/_context.d.mts +28 -8
  36. package/api/theme-edit/_context.mjs +142 -19
  37. package/api/theme-edit/_edit.d.mts +3 -1
  38. package/api/theme-edit/_edit.mjs +746 -76
  39. package/api/theme-edit/_how-commands.d.mts +91 -0
  40. package/api/theme-edit/_how-commands.mjs +269 -0
  41. package/api/theme-edit/_how-question.d.mts +57 -0
  42. package/api/theme-edit/_how-question.mjs +2574 -0
  43. package/api/theme-edit/_how.d.mts +27 -8
  44. package/api/theme-edit/_how.mjs +776 -175
  45. package/api/theme-edit/_overview.d.mts +9 -0
  46. package/api/theme-edit/_overview.mjs +296 -0
  47. package/api/theme-edit/_palette.d.mts +155 -15
  48. package/api/theme-edit/_palette.mjs +1446 -262
  49. package/api/theme-edit/_parts.mjs +61 -5
  50. package/api/theme-edit/_png.d.mts +18 -6
  51. package/api/theme-edit/_png.mjs +135 -25
  52. package/api/theme-edit/_preview-app.d.mts +32 -11
  53. package/api/theme-edit/_preview-app.mjs +1976 -285
  54. package/api/theme-edit/_preview.d.mts +39 -8
  55. package/api/theme-edit/_preview.mjs +367 -41
  56. package/api/theme-edit/_settings.d.mts +147 -11
  57. package/api/theme-edit/_settings.mjs +908 -99
  58. package/api/theme-edit/_tables.d.mts +4 -16
  59. package/api/theme-edit/_tables.mjs +51 -117
  60. package/api/theme-edit/theme-edit.type.d.mts +102 -66
  61. package/api/theme-edit/theme-edit.type.mjs +58 -40
  62. package/api/theme-edit/themeEditHow.doc.mjs +17 -6
  63. package/api/theme-edit/themeEditNew.doc.mjs +21 -5
  64. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +18 -5
  65. package/api/theme-edit/themeEditPreviewApp.doc.mjs +12 -9
  66. package/api/theme-edit/themeEditPreviewList.doc.mjs +11 -2
  67. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +29 -3
  68. package/api/theme-edit/themeEditSet.doc.mjs +14 -8
  69. package/api/theme-edit/themeEditShow.doc.mjs +10 -5
  70. package/api/theme-edit/themeEditUndo.doc.mjs +9 -4
  71. package/assets/discover/official-packages.json +4 -0
  72. package/assets/docs/tree/icon-sets.doc.mjs +3 -3
  73. package/assets/docs.generated.json +1 -0
  74. package/assets/icons/definitions/bookmarkAdd.doc.mjs +9 -0
  75. package/assets/icons/definitions/documentSearch.doc.mjs +9 -0
  76. package/assets/icons/definitions/keyboard.doc.mjs +9 -0
  77. package/assets/icons/definitions/paintBrush.doc.mjs +9 -0
  78. package/assets/icons/definitions/wallet.doc.mjs +9 -0
  79. package/assets/preview-app/gitignore +3 -0
  80. package/assets/templates/blocks/components/ButtonGroup/ButtonGroupShowcase.doc.mjs +1 -1
  81. package/assets/templates/blocks/components/Lightbox/LightboxGallery.tsx +1 -1
  82. package/assets/templates/components.generated.json +1 -0
  83. package/assets/templates/pages/gallery-hero/page.tsx +8 -2
  84. package/assets/templates/pages/settings-dialog/template.doc.mjs +3 -3
  85. package/assets/templates/pages/side-gallery/page.tsx +1 -1
  86. package/assets/templates/pages/table-filter/template.doc.mjs +2 -2
  87. package/assets/templates/pages/theme-showcase/template.doc.mjs +1 -1
  88. package/clients/cli/bin/astryx.mjs +37 -5
  89. package/clients/cli/commands/experimental/theme.mjs +422 -57
  90. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +22 -9
  91. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +103 -4
  92. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +13 -8
  93. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +5 -5
  94. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +5 -5
  95. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  96. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +3 -2
  97. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +2 -8
  98. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +2 -2
  99. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  100. package/clients/cli/commands/experimental-theme-targets.doc.mjs +1 -1
  101. package/clients/cli/commands/experimental-theme.doc.mjs +3 -4
  102. package/clients/cli/commands/theme-build.doc.mjs +1 -1
  103. package/clients/cli/commands/theme-eject.doc.mjs +3 -3
  104. package/clients/cli/commands/theme-remove.doc.mjs +2 -2
  105. package/clients/cli/commands/theme-template.doc.mjs +11 -4
  106. package/clients/cli/commands/theme.mjs +145 -46
  107. package/clients/cli/commands.generated.json +1 -0
  108. package/clients/cli/index.mjs +96 -5
  109. package/clients/cli/lib/json-shim.mjs +29 -1
  110. package/foundation/config/project.d.mts +16 -2
  111. package/foundation/config/project.mjs +40 -6
  112. package/foundation/config/theme-state.d.mts +9 -0
  113. package/foundation/config/theme-state.mjs +20 -1
  114. package/foundation/discovery/template-adapter.d.mts +12 -1
  115. package/foundation/discovery/template-adapter.mjs +29 -4
  116. package/foundation/discovery/template-icons.d.mts +13 -0
  117. package/foundation/discovery/template-icons.mjs +76 -0
  118. package/foundation/discovery/template-needs.d.mts +7 -0
  119. package/foundation/discovery/template-needs.mjs +117 -8
  120. package/foundation/discovery/template-source-tree.d.mts +5 -1
  121. package/foundation/discovery/template-source-tree.mjs +6 -4
  122. package/foundation/discovery/theme-discovery.d.mts +14 -3
  123. package/foundation/discovery/theme-discovery.mjs +45 -12
  124. package/foundation/doc-compiler/import.mjs +68 -3
  125. package/foundation/doc-compiler/stored-docs.d.mts +27 -0
  126. package/foundation/doc-compiler/stored-docs.mjs +65 -0
  127. package/foundation/fs/fs-error.d.mts +17 -0
  128. package/foundation/fs/fs-error.mjs +34 -0
  129. package/foundation/response/error-codes.d.mts +3 -1
  130. package/foundation/response/error-codes.doc.mjs +13 -1
  131. package/foundation/response/error-codes.mjs +11 -1
  132. package/foundation/response/response-types.doc.mjs +6 -6
  133. package/package.json +6 -7
  134. package/clients/cli/commands/experimental-theme-palette-generate.doc.mjs +0 -73
  135. package/clients/cli/commands/experimental-theme-palette.doc.mjs +0 -37
@@ -3,25 +3,77 @@
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.
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.
9
14
  *
10
15
  * @position api/theme-edit — imported by _settings.mjs, _check.mjs, _how.mjs
11
16
  */
12
17
 
18
+ import {createHash} from 'node:crypto';
13
19
  import * as fs from 'node:fs';
20
+ import {createRequire} from 'node:module';
21
+ import * as os from 'node:os';
14
22
  import * as path from 'node:path';
15
23
  import {AstryxError} from '../error.mjs';
16
24
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
17
25
  import {
26
+ DEFAULT_21_STOPS,
27
+ PALETTE_BLACK,
28
+ PALETTE_GENERATOR_VERSION,
29
+ PALETTE_WHITE,
18
30
  generateTonalPalette,
19
31
  perceptualDelta,
20
32
  } from '../theme/palette/generate/generator.mjs';
21
33
  import {themePaletteGenerate} from '../theme/palette/generate/generate.mjs';
22
- 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';
44
+
45
+ /**
46
+ * Write a file whole: a temp file beside it, renamed into place, so a link
47
+ * there is replaced, never written through, and a stopped write leaves the
48
+ * old file. The temp file goes whatever happens.
49
+ * @param {string} file
50
+ * @param {string | Buffer} text
51
+ */
52
+ export function writeWhole(file, text) {
53
+ const tmp = tempFor(file);
54
+ try {
55
+ fs.writeFileSync(tmp, text);
56
+ fs.renameSync(tmp, file);
57
+ } finally {
58
+ fs.rmSync(tmp, {force: true});
59
+ }
60
+ }
61
+
62
+ /**
63
+ * A temp file beside `file` for a whole write, named so only the editor
64
+ * makes such names: `.<name>.astryx-<pid>-<random>.tmp`. The write that
65
+ * makes one removes it.
66
+ * @param {string} file
67
+ */
68
+ export function tempFor(file) {
69
+ return path.join(
70
+ path.dirname(file),
71
+ `.${path.basename(file)}.astryx-${process.pid}-${Math.random().toString(36).slice(2, 10)}.tmp`,
72
+ );
73
+ }
23
74
 
24
75
  /** @typedef {'light' | 'dark'} Mode */
76
+ /** @typedef {import('./_settings.mjs').Setting} Setting */
25
77
  /** @typedef {import('../theme/theme.type.mjs').TonalPaletteCandidate} Candidate */
26
78
 
27
79
  /**
@@ -30,6 +82,8 @@ import {parseColor, hex, ratio} from './_color.mjs';
30
82
  * @property {number} stop
31
83
  * @property {string} color - The stop's color, with `alpha` appended when set.
32
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).
33
87
  */
34
88
 
35
89
  /**
@@ -43,6 +97,7 @@ import {parseColor, hex, ratio} from './_color.mjs';
43
97
  * @property {number} ratio - The lowest ratio over everything it was measured on.
44
98
  * @property {number} needs
45
99
  * @property {boolean} pass
100
+ * @property {string} [note] - The whole sentence to report, when the check is not a plain stop move.
46
101
  */
47
102
 
48
103
  /**
@@ -52,6 +107,9 @@ import {parseColor, hex, ratio} from './_color.mjs';
52
107
  * @property {Array<{id: string, dial: string, seed: string, value: string}>} families
53
108
  * @property {Record<string, {family: string, light: StopRef, dark: StopRef}>} tokens
54
109
  * @property {ContrastCheck[]} contrast
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.
55
113
  */
56
114
 
57
115
  /** The color dials. Each one is a palette family of the same id. */
@@ -64,6 +122,25 @@ export const PALETTE_DIALS = [
64
122
  'info',
65
123
  ];
66
124
 
125
+ /** The generator's vibrancy when the theme sets none. */
126
+ export const VIBRANCY_DEFAULT = 50;
127
+
128
+ /**
129
+ * The vibrancy dial a settings list sets, or null.
130
+ * @param {Setting[]} settings
131
+ * @returns {number | null}
132
+ */
133
+ function dialVibrancy(settings) {
134
+ const s = [...settings]
135
+ .reverse()
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;
142
+ }
143
+
67
144
  /** The Core token word of each status family. */
68
145
  const STATUS_TOKEN = /** @type {Record<string, string>} */ ({
69
146
  success: 'success',
@@ -80,24 +157,21 @@ export const paletteToken = dial =>
80
157
  dial === 'accent'
81
158
  ? '--color-accent'
82
159
  : dial === 'neutral'
83
- ? '--color-background-body'
160
+ ? '--color-background-surface'
84
161
  : `--color-${STATUS_TOKEN[dial]}`;
85
162
 
86
- /** Text contrast (WCAG AA) and non-text contrast (focus rings, icons). */
163
+ /** Text contrast and non-text contrast (fills, focus rings, icons). */
87
164
  const TEXT = 4.5;
88
165
  const NON_TEXT = 3;
89
166
 
90
167
  /**
91
- * The stop each token starts from, `[light, dark]`, as the official themes
92
- * map them: neutral surfaces, text and borders as in the neutral theme; an
93
- * accent or status fill at its seed's anchored stop in light (as the neutral
94
- * theme anchors its blue) and 70 in dark (as the theme authoring guide maps
95
- * it); status text, tints and borders as the neutral theme maps its hue
96
- * 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.
97
172
  */
98
173
  const NEUTRAL_STOPS = /** @type {Record<string, [number, number]>} */ ({
99
174
  '--color-background-surface': [100, 15],
100
- '--color-background-body': [95, 10],
101
175
  '--color-background-card': [100, 10],
102
176
  '--color-background-popover': [100, 10],
103
177
  '--color-background-muted': [95, 10],
@@ -126,16 +200,34 @@ const NEUTRAL_TINTS =
126
200
  [100, '1a'],
127
201
  ],
128
202
  });
129
- 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;
130
210
  const TEXT_STOP = /** @type {[number, number]} */ ([45, 80]);
131
- 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
+ ]);
132
216
  const ON_MUTED = /** @type {[number, number]} */ ([25, 80]);
133
217
  const BORDER = /** @type {[number, number]} */ ([80, 65]);
134
- /** Text on a fill: white on light-mode fills, near-black on dark-mode fills. */
135
- 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]>} */ ({
136
224
  light: [100, 5],
137
225
  dark: [5, 100],
138
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;
139
231
 
140
232
  /** Text on surfaces darkens in light mode and lightens in dark mode. */
141
233
  const TOWARD_CONTRAST = /** @type {Record<Mode, 1 | -1>} */ ({
@@ -149,23 +241,70 @@ export function paletteFiles(slug) {
149
241
  config: `themes/${slug}/palette.config.json`,
150
242
  palette: `themes/${slug}/tokens/${slug}.palette.ts`,
151
243
  receipt: `themes/${slug}/tokens/${slug}.palette.receipt.json`,
244
+ refs: `themes/${slug}/tokens/${slug}.palette-refs.ts`,
152
245
  importPath: `./tokens/${slug}.palette`,
246
+ refsImportPath: `./tokens/${slug}.palette-refs`,
153
247
  };
154
248
  }
155
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
+
156
254
  /**
157
- * The seed a color dial value grows from, or null for a value with no fixed
158
- * color (a variable, a keyword, `color-mix()`).
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
+
261
+ /**
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).
159
264
  * @param {string} value
160
265
  */
161
266
  export function seedOf(value) {
162
267
  const rgb = parseColor(value);
163
- return rgb ? hex(rgb) : null;
268
+ return rgb && alphaOf(value) >= 1 ? hex(rgb) : null;
269
+ }
270
+
271
+ /**
272
+ * Below this OKLCH chroma a seed reads as gray: its family is generated as a
273
+ * neutral, so no hue is invented for it in either mode.
274
+ */
275
+ const GRAY_CHROMA = 0.02;
276
+
277
+ /** @param {string} seed */
278
+ const isGray = seed => hexToOklch(seed).C < GRAY_CHROMA;
279
+
280
+ /** Whether a seed (or no seed) has no color to saturate. @param {string | null} seed */
281
+ export const isGraySeed = seed => !seed || isGray(seed);
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'];
164
303
  }
165
304
 
166
305
  /**
167
306
  * The color dial settings of a theme, in dial order.
168
- * @param {import('./_settings.mjs').ThemeData} data
307
+ * @param {{settings: Setting[]}} data
169
308
  */
170
309
  function dialFamilies(data) {
171
310
  /** @type {Array<{id: string, dial: string, seed: string, value: string}>} */
@@ -173,7 +312,7 @@ function dialFamilies(data) {
173
312
  for (const dial of PALETTE_DIALS) {
174
313
  const s = [...data.settings]
175
314
  .reverse()
176
- .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);
177
316
  const seed = s && seedOf(s.value);
178
317
  if (s && seed) out.push({id: dial, dial, seed, value: s.value});
179
318
  }
@@ -184,7 +323,7 @@ function dialFamilies(data) {
184
323
  function readConfig(file) {
185
324
  if (!fs.existsSync(file)) return null;
186
325
  try {
187
- return JSON.parse(fs.readFileSync(file, 'utf8'));
326
+ return JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
188
327
  } catch (e) {
189
328
  throw new AstryxError(
190
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.`,
@@ -194,20 +333,89 @@ function readConfig(file) {
194
333
  }
195
334
  }
196
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
+
197
403
  /**
198
404
  * The light stop nearest a seed color in the ramp the generator grows from
199
405
  * it. The official themes anchor a brand color there, exactly, so the fill
200
406
  * keeps the color as given. The end stops are pure black and white and
201
407
  * never hold an anchor.
202
408
  * @param {string} seed
203
- * @param {any} config - Its `stops`, `vibrancy` and `neutralProfile` shape the ramp.
409
+ * @param {any} config - Its `stops` and `vibrancy` shape the ramp.
410
+ * @param {'chromatic' | 'neutral'} [kind]
204
411
  */
205
- function seedStop(seed, config) {
412
+ function seedStop(seed, config, kind = 'chromatic') {
206
413
  const {stops, palette} = generate({
207
414
  ...(config.stops ? {stops: config.stops} : {}),
208
415
  ...(config.vibrancy != null ? {vibrancy: config.vibrancy} : {}),
416
+ ...(kind === 'neutral' ? {neutralProfile: 'custom'} : {}),
209
417
  modeStrategy: 'light-only',
210
- families: [{id: 'seed', seed}],
418
+ families: [{id: 'seed', seed, kind}],
211
419
  });
212
420
  const ramp = /** @type {Record<number, string>} */ (
213
421
  /** @type {any} */ (palette.seed).light
@@ -221,94 +429,836 @@ function seedStop(seed, config) {
221
429
  }
222
430
 
223
431
  /**
224
- * The palette config a theme's settings ask for: the existing config, with
225
- * each color dial's family written in place and families the dials no longer
226
- * set removed. Families and fields the editor does not own are kept. Null
227
- * when the config would 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.
228
724
  * @param {string} cwd
229
725
  * @param {string} slug
230
- * @param {import('./_settings.mjs').ThemeData} data
231
- * @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}
232
729
  */
233
- export function paletteConfig(cwd, slug, data) {
234
- 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));
235
733
  const fams = dialFamilies(data);
236
734
  if (!existing && !fams.length) return null;
237
- const config = {...(existing ?? {})};
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
+ );
238
781
  /** @type {any[]} */
239
782
  const before = Array.isArray(config.families) ? config.families : [];
240
- /** @param {{id: string, seed: string}} f */
241
- const familyOf = f =>
242
- f.id === 'neutral'
243
- ? {id: f.id, name: 'Neutral', seed: f.seed, kind: 'neutral'}
244
- : {
245
- id: f.id,
246
- name: f.id[0].toUpperCase() + f.id.slice(1),
247
- seed: f.seed,
248
- anchors: [
249
- {
250
- mode: 'light',
251
- stop: seedStop(f.seed, config),
252
- color: f.seed,
253
- policy: 'exact',
254
- },
255
- ],
256
- };
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,
831
+ color: f.seed,
832
+ policy: 'exact',
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
+ ),
880
+ };
881
+ if (!kind) delete out.kind;
882
+ if (!out.anchors.length) delete out.anchors;
883
+ return {family: out, stop};
884
+ };
885
+
886
+ /** @type {PalettePlan['fills']} */
887
+ const fills = {};
257
888
  const families = before
258
889
  .map(f => {
259
890
  if (!PALETTE_DIALS.includes(f?.id)) return f;
260
891
  const mine = fams.find(x => x.id === f.id);
261
- return mine ? {...f, ...familyOf(mine)} : null;
892
+ if (!mine) return null;
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;
262
897
  })
263
898
  .filter(Boolean);
264
899
  for (const f of fams)
265
- 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
+ }
266
906
  if (!families.length) return null;
267
- config.modeStrategy = 'light-and-dark';
268
- // The neutral profiles other than `custom` ignore the seed.
269
- if (fams.some(f => f.id === 'neutral')) config.neutralProfile = 'custom';
270
907
  config.families = families;
271
- 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};
272
980
  }
273
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;
993
+ }
994
+
995
+ /** @param {string} text */
996
+ const sha256 = text => createHash('sha256').update(text).digest('hex');
997
+
274
998
  /**
275
999
  * Write the palette config, palette and receipt the settings ask for, with
276
- * the same generator as `theme palette generate --out`; remove all three
277
- * 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.
278
1007
  * @param {string} cwd
279
1008
  * @param {string} slug
280
- * @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[]}
281
1013
  */
282
- export function syncPalette(cwd, slug, data) {
1014
+ export function syncPalette(cwd, slug, data, base) {
283
1015
  const f = paletteFiles(slug);
284
1016
  const abs = (/** @type {string} */ p) => path.join(cwd, p);
285
- const config = paletteConfig(cwd, slug, data);
286
- if (!config) {
287
- for (const p of [f.config, f.palette, f.receipt])
1017
+ const plan = planPalette(cwd, slug, data, base);
1018
+ if (!plan) {
1019
+ // Only palette files the editor wrote go: a hand-made palette.config.json
1020
+ // (and what it generated) stays.
1021
+ // The hash the saved settings recorded too: an undo may carry settings
1022
+ // from before the palette existed.
1023
+ /** @type {string | undefined} */
1024
+ let saved;
1025
+ try {
1026
+ saved = JSON.parse(
1027
+ fs.readFileSync(abs(`themes/${slug}/${slug}.settings.json`), 'utf8'),
1028
+ ).palette;
1029
+ } catch {
1030
+ saved = undefined;
1031
+ }
1032
+ const hash = fs.existsSync(abs(f.config))
1033
+ ? sha256(fs.readFileSync(abs(f.config), 'utf8'))
1034
+ : null;
1035
+ const mine = hash != null && (data.palette === hash || saved === hash);
1036
+ delete data.palette;
1037
+ if (!mine) return [];
1038
+ for (const p of [f.config, f.palette, f.receipt, f.refs])
288
1039
  fs.rmSync(abs(p), {force: true});
289
1040
  const tokensDir = path.dirname(abs(f.palette));
290
1041
  if (fs.existsSync(tokensDir) && !fs.readdirSync(tokensDir).length)
291
1042
  fs.rmdirSync(tokensDir);
292
- 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;
293
1052
  }
294
- const text = `${JSON.stringify(config, null, 2)}\n`;
295
1053
  const same =
296
1054
  fs.existsSync(abs(f.config)) &&
297
1055
  fs.readFileSync(abs(f.config), 'utf8') === text &&
298
1056
  fs.existsSync(abs(f.palette)) &&
299
- fs.existsSync(abs(f.receipt));
300
- if (same) return;
301
- fs.writeFileSync(abs(f.config), text);
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.
1060
+ if (same) {
1061
+ data.palette = sha256(text);
1062
+ return [];
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});
1072
+ writeWhole(abs(f.config), text);
1073
+ data.palette = sha256(text);
302
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
+ }
303
1107
  }
304
1108
 
305
- /** @param {any} config @returns {Candidate} */
306
- 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') {
307
1257
  try {
308
1258
  return generateTonalPalette(config);
309
1259
  } catch (e) {
310
1260
  throw new AstryxError(
311
- `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.`,
312
1262
  [],
313
1263
  ERROR_CODES.ERR_PALETTE_GENERATION,
314
1264
  );
@@ -316,24 +1266,39 @@ function generate(config) {
316
1266
  }
317
1267
 
318
1268
  /**
319
- * The stops from `start` toward `dir`, `start` first.
320
- * @param {number[]} stops
321
- * @param {number} start
322
- * @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
323
1272
  */
324
- function walk(stops, start, dir) {
325
- const i = stops.includes(start)
326
- ? stops.indexOf(start)
327
- : stops.findIndex(s => s >= start);
328
- const from = i < 0 ? stops.length - 1 : i;
329
- return dir > 0 ? stops.slice(from) : stops.slice(0, from + 1).reverse();
330
- }
331
-
332
- /** @param {string} a @param {string} b */
333
1273
  function contrast(a, b) {
334
1274
  const x = parseColor(a);
335
1275
  const y = parseColor(b);
336
- 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
+ ]);
337
1302
  }
338
1303
 
339
1304
  /** @param {number} r */
@@ -353,50 +1318,80 @@ const round = r => Math.round(r * 100) / 100;
353
1318
  export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
354
1319
  const fams = dialFamilies(data);
355
1320
  if (!fams.length) return null;
356
- const config = paletteConfig(cwd, slug, data);
357
- const candidate = generate(config);
358
- /** The light fill starts at the family's light anchor, as the seed lands there. @param {string} id */
359
- const fillStart = id =>
360
- /** @type {any[]} */ (config.families)
361
- .find(f => f.id === id)
362
- ?.anchors?.find((/** @type {any} */ a) => a.mode === 'light')?.stop ??
363
- FILL[0];
364
- 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
+ };
365
1339
  /** @type {PaletteMapping['tokens']} */
366
1340
  const tokens = {};
367
1341
  /** @type {ContrastCheck[]} */
368
1342
  const checks = [];
369
- const has = (/** @type {string} */ t) => t in tokenDefaults;
370
- /** @param {string} id @param {Mode} m @param {number} stop @param {string} [alpha] @returns {StopRef} */
371
- const ref = (id, m, stop, alpha) => {
372
- const color = /** @type {any} */ (candidate.palette[id])[m][stop];
373
- return alpha ? {stop, color: `${color}${alpha}`, alpha} : {stop, color};
374
- };
375
- /** @param {string} token @param {string} id @param {StopRef} light @param {StopRef} dark */
376
- const put = (token, id, light, dark) => {
377
- 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
+ };
378
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)]));
379
1369
  /**
380
- * The first stop from `start` toward more contrast that reads at `needs`
381
- * 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.
382
1374
  * @param {string} token @param {string} id @param {Mode} m @param {number} start
383
1375
  * @param {Array<[string, string]>} on - `[name, color]` pairs.
384
1376
  * @param {number} needs
385
1377
  */
386
1378
  const pick = (token, id, m, start, on, needs) => {
387
- /** @type {{stop: number, r: number} | null} */
388
- let best = null;
389
- 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 => {
390
1387
  const c = ref(id, m, stop).color;
391
- const r = Math.min(...on.map(([, bg]) => contrast(c, bg)));
392
- if (!best || r > best.r) best = {stop, r};
393
- if (r >= needs) {
394
- best = {stop, r};
395
- break;
396
- }
397
- }
398
- const b = /** @type {{stop: number, r: number}} */ (best);
399
- 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))
400
1395
  checks.push({
401
1396
  token,
402
1397
  mode: m,
@@ -409,41 +1404,10 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
409
1404
  });
410
1405
  return ref(id, m, b.stop);
411
1406
  };
412
- /**
413
- * A fill and the text on it: the fill moves toward more contrast until the
414
- * better of the two text stops reads at 4.5:1 on it.
415
- * @param {string} fillToken @param {string} onToken @param {string} id @param {Mode} m @param {number} start
416
- */
417
- const fillPair = (fillToken, onToken, id, m, start) => {
418
- /** @type {{fill: number, on: number, r: number} | null} */
419
- let best = null;
420
- for (const stop of walk(stops, start, TOWARD_CONTRAST[m])) {
421
- const fill = ref(id, m, stop).color;
422
- for (const on of ON_FILL[m]) {
423
- const r = contrast(ref(id, m, on).color, fill);
424
- if (!best || r > best.r + 0.01) best = {fill: stop, on, r};
425
- }
426
- if (/** @type {{r: number}} */ (best).r >= TEXT) break;
427
- }
428
- const b = /** @type {{fill: number, on: number, r: number}} */ (best);
429
- if (has(onToken))
430
- checks.push({
431
- token: onToken,
432
- mode: m,
433
- stop: b.on,
434
- preferred: ON_FILL[m][0],
435
- against: `${fillToken} (stop ${b.fill})`,
436
- ratio: round(b.r),
437
- needs: TEXT,
438
- pass: b.r >= TEXT,
439
- });
440
- return {fill: ref(id, m, b.fill), on: ref(id, m, b.on), moved: b.fill};
441
- };
442
1407
 
443
- const modes = /** @type {Mode[]} */ (['light', 'dark']);
444
1408
  const neutral = fams.find(f => f.id === 'neutral');
445
1409
  if (neutral) {
446
- for (const [token, [l, d]] of Object.entries(NEUTRAL_STOPS)) {
1410
+ for (const [token, pair] of Object.entries(NEUTRAL_STOPS)) {
447
1411
  if (
448
1412
  token === '--color-text-secondary' ||
449
1413
  token === '--color-icon-secondary'
@@ -452,69 +1416,42 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
452
1416
  put(
453
1417
  token,
454
1418
  'neutral',
455
- ref('neutral', 'light', l),
456
- ref('neutral', 'dark', d),
1419
+ each(m => ref('neutral', m, at(pair[m === 'light' ? 0 : 1]))),
457
1420
  );
458
1421
  }
459
- for (const [token, [[l, la], [d, da]]] of Object.entries(NEUTRAL_TINTS))
1422
+ for (const [token, pair] of Object.entries(NEUTRAL_TINTS))
460
1423
  put(
461
1424
  token,
462
1425
  'neutral',
463
- ref('neutral', 'light', l, la),
464
- 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
+ }),
465
1430
  );
466
- }
467
- /** What text sits on in each mode: the neutral surfaces, else the base theme's. @param {Mode} m @param {string} id */
468
- const surfaces = (m, id) => {
469
- const names = [
470
- '--color-background-surface',
471
- '--color-background-body',
472
- '--color-background-card',
473
- ];
474
- /** @type {Array<[string, string]>} */
475
- const out = [];
476
- for (const n of names) {
477
- const v = tokens[n]?.[m].color ?? base[m][n];
478
- if (v && parseColor(v)) out.push([n, v]);
479
- }
480
- if (!out.length)
481
- out.push([
482
- `${id} stop ${NEUTRAL_STOPS['--color-background-surface'][m === 'light' ? 0 : 1]}`,
483
- ref(
484
- id,
485
- m,
486
- NEUTRAL_STOPS['--color-background-surface'][m === 'light' ? 0 : 1],
487
- ).color,
488
- ]);
489
- return out;
490
- };
491
- if (neutral) {
492
- const [[tl, td], [il, id]] = [
493
- NEUTRAL_STOPS['--color-text-secondary'],
494
- NEUTRAL_STOPS['--color-icon-secondary'],
495
- ];
496
- const text = modes.map((m, i) =>
497
- pick(
498
- '--color-text-secondary',
499
- 'neutral',
500
- m,
501
- [tl, td][i],
502
- surfaces(m, 'neutral'),
503
- TEXT,
504
- ),
505
- );
506
- put('--color-text-secondary', 'neutral', text[0], text[1]);
507
- const icon = modes.map((m, i) =>
508
- pick(
509
- '--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,
510
1437
  'neutral',
511
- m,
512
- [il, id][i],
513
- surfaces(m, 'neutral'),
514
- NON_TEXT,
515
- ),
516
- );
517
- 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
+ );
518
1455
  }
519
1456
 
520
1457
  for (const f of fams) {
@@ -541,62 +1478,270 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
541
1478
  border: null,
542
1479
  focus: '--focus-outline-color',
543
1480
  };
544
- const muted = modes.map((m, i) => ref(f.id, m, MUTED[i]));
545
- put(names.muted, f.id, muted[0], muted[1]);
546
- const pairs = modes.map((m, i) =>
547
- fillPair(names.fill, names.on, f.id, m, i ? FILL[1] : fillStart(f.id)),
548
- );
549
- put(names.fill, f.id, pairs[0].fill, pairs[1].fill);
550
- put(names.on, f.id, pairs[0].on, pairs[1].on);
551
- const text = modes.map((m, i) =>
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))
1514
+ checks.push({
1515
+ token: names.fill,
1516
+ mode: m,
1517
+ stop: found,
1518
+ preferred: S,
1519
+ against: 'the dark page and the text on it',
1520
+ ratio: plain.ratio,
1521
+ needs: TEXT,
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
+ : {}),
1557
+ });
1558
+ return o.on;
1559
+ });
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 =>
552
1651
  pick(
553
1652
  names.text,
554
1653
  f.id,
555
1654
  m,
556
- TEXT_STOP[i],
557
- [...surfaces(m, f.id), [names.muted, muted[i].color]],
1655
+ at(TEXT_STOP[m === 'light' ? 0 : 1]),
1656
+ [...surfaces(m, f.id), ...mutedSeen(m)],
558
1657
  TEXT,
559
1658
  ),
560
1659
  );
561
- put(names.text, f.id, text[0], text[1]);
562
- put(names.icon, f.id, text[0], text[1]);
1660
+ put(names.text, f.id, text);
1661
+ put(names.icon, f.id, text);
563
1662
  if (names.onMuted) {
564
- const on = modes.map((m, i) =>
565
- pick(
566
- /** @type {string} */ (names.onMuted),
567
- f.id,
568
- m,
569
- ON_MUTED[i],
570
- [[names.muted, muted[i].color]],
571
- 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
+ ),
572
1676
  ),
573
1677
  );
574
- put(names.onMuted, f.id, on[0], on[1]);
575
1678
  }
576
1679
  if (names.border)
577
1680
  put(
578
1681
  names.border,
579
1682
  f.id,
580
- ref(f.id, 'light', BORDER[0]),
581
- ref(f.id, 'dark', BORDER[1]),
1683
+ each(m => ref(f.id, m, at(BORDER[m === 'light' ? 0 : 1]))),
582
1684
  );
583
- if (names.focus) {
584
- const ring = modes.map((m, i) =>
585
- pick(
586
- /** @type {string} */ (names.focus),
587
- f.id,
588
- m,
589
- pairs[i].moved,
590
- surfaces(m, f.id),
591
- 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
+ ),
592
1701
  ),
593
1702
  );
594
- put(names.focus, f.id, ring[0], ring[1]);
595
1703
  }
596
1704
  }
597
- return {candidate, families: fams, tokens, contrast: checks};
1705
+ return {
1706
+ candidate,
1707
+ families: fams,
1708
+ tokens,
1709
+ contrast: checks,
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
+ ],
1720
+ };
598
1721
  }
599
1722
 
1723
+ /** Every token a color dial can point at a generated shade. */
1724
+ export const PALETTE_TOKENS = new Set([
1725
+ ...Object.keys(NEUTRAL_STOPS),
1726
+ '--color-background-body',
1727
+ ...Object.keys(NEUTRAL_TINTS),
1728
+ '--color-accent',
1729
+ '--color-on-accent',
1730
+ '--color-text-accent',
1731
+ '--color-icon-accent',
1732
+ '--color-accent-muted',
1733
+ '--focus-outline-color',
1734
+ ...Object.values(STATUS_TOKEN).flatMap(w => [
1735
+ `--color-${w}`,
1736
+ `--color-on-${w}`,
1737
+ `--color-text-${w}`,
1738
+ `--color-icon-${w}`,
1739
+ `--color-${w}-muted`,
1740
+ `--color-on-${w}-muted`,
1741
+ `--color-border-${w}`,
1742
+ ]),
1743
+ ]);
1744
+
600
1745
  /**
601
1746
  * Where each token starts, for `how`: `token: light stop L, dark stop D`.
602
1747
  * @param {string} dial
@@ -605,68 +1750,107 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
605
1750
  export function mappingRows(dial) {
606
1751
  if (dial === 'neutral')
607
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)',
608
1754
  ...Object.entries(NEUTRAL_STOPS).map(
609
1755
  ([t, [l, d]]) =>
610
- `${t}: light stop ${l}, dark stop ${d}${t.endsWith('-secondary') ? ` (moves to a stop that reads at ${t.includes('icon') ? NON_TEXT : TEXT}:1 on the surfaces)` : ''}`,
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)` : ''}`,
611
1757
  ),
612
1758
  ...Object.entries(NEUTRAL_TINTS).map(
613
1759
  ([t, [[l, la], [d, da]]]) =>
614
- `${t}: light stop ${l} at opacity ${la}, dark stop ${d} at opacity ${da}`,
1760
+ `${t}: light shade ${l} at opacity ${la}, dark shade ${d} at opacity ${da}`,
615
1761
  ),
1762
+ "--color-background-body: the base theme's page color, so a tinted gray never tints the page",
616
1763
  ];
617
1764
  const word = dial === 'accent' ? null : STATUS_TOKEN[dial];
618
1765
  if (dial !== 'accent' && !word) return [];
619
1766
  const t = (/** @type {string} */ a, /** @type {string} */ b) =>
620
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';
621
1772
  const rows = [
622
- `${t('--color-$', '--color-accent')}: in light, the stop the color lands on (anchored there exactly, so it stays the color you gave); in dark, stop ${FILL[1]}; either moves until the text on it reads at ${TEXT}:1`,
623
- `${t('--color-on-$', '--color-on-accent')}: stop ${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`,
624
- `${t('--color-text-$', '--color-text-accent')} and ${t('--color-icon-$', '--color-icon-accent')}: light stop ${TEXT_STOP[0]}, dark stop ${TEXT_STOP[1]} (moves until it reads at ${TEXT}:1 on the surfaces and the muted tint)`,
625
- `${t('--color-$-muted', '--color-accent-muted')}: light stop ${MUTED[0]}, dark stop ${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`,
626
1779
  ];
627
1780
  if (word)
628
1781
  rows.push(
629
- `--color-on-${word}-muted: light stop ${ON_MUTED[0]}, dark stop ${ON_MUTED[1]} (moves until it reads at ${TEXT}:1 on the muted tint)`,
630
- `--color-border-${word}: light stop ${BORDER[0]}, dark stop ${BORDER[1]}`,
1782
+ `--color-on-${word}-muted: light shade ${ON_MUTED[0]}, dark shade ${ON_MUTED[1]} (moves until it reads at ${TEXT}:1 on the muted tint)`,
1783
+ `--color-border-${word}: light shade ${BORDER[0]}, dark shade ${BORDER[1]}`,
631
1784
  );
632
1785
  else
633
1786
  rows.push(
634
- `--focus-outline-color (the focus ring): the accent's stop, 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`,
635
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)',
636
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
+ );
637
1793
  return rows;
638
1794
  }
639
1795
 
640
1796
  /**
641
- * What one color dial did, for the result notes: where its palette lives,
642
- * the stop of its main token in each mode, and every token contrast moved.
1797
+ * What one color dial did, for the result notes: what its main token uses
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}).
643
1801
  * @param {PaletteMapping | null} pal
644
1802
  * @param {string} dial
645
1803
  * @param {string} slug
1804
+ * @param {Mode[]} [modes] the modes the theme has
646
1805
  * @returns {string[]}
647
1806
  */
648
- export function paletteNotes(pal, dial, slug) {
1807
+ export function paletteNotes(pal, dial, slug, modes = ['light', 'dark']) {
649
1808
  if (!pal) return [];
650
1809
  const f = paletteFiles(slug);
651
- const main = pal.tokens[paletteToken(dial)];
1810
+ const token = paletteToken(dial);
1811
+ const main = pal.tokens[token];
1812
+ const exact = pal.exact[token];
652
1813
  /** @type {string[]} */
653
- const notes = [
654
- `the ${dial} family is in ${f.config}; the palette and its receipt are ${f.palette} and ${f.receipt}`,
655
- ];
656
- if (main)
1814
+ const notes = [];
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 ');
657
1820
  notes.push(
658
- `${paletteToken(dial)} is ${dial} stop ${main.light.stop} (${main.light.color}) in light and stop ${main.dark.stop} (${main.dark.color}) in dark`,
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`,
659
1837
  );
660
1838
  for (const c of pal.contrast) {
661
1839
  if (pal.tokens[c.token]?.family !== dial) continue;
662
- if (!c.pass)
1840
+ // A theme with one mode never shows the other one's shades.
1841
+ if (!modes.includes(c.mode)) continue;
1842
+ if (c.note) notes.push(c.note);
1843
+ else if (!c.pass)
663
1844
  notes.push(
664
- `${c.token} reads at only ${c.ratio}:1 in ${c.mode} on ${c.against} (needs ${c.needs}:1) even at stop ${c.stop}, the most contrasting stop: pick a lighter or darker ${dial}, or set ${c.token} exactly`,
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`,
665
1846
  );
666
1847
  else if (c.stop !== c.preferred)
667
1848
  notes.push(
668
- `${c.token} uses stop ${c.stop} in ${c.mode}, not ${c.preferred}, so it reads at ${c.ratio}:1 on ${c.against}`,
1849
+ `${c.token} uses shade ${c.stop} in ${c.mode}, not ${c.preferred}, so it reads at ${c.ratio}:1 on ${c.against}`,
669
1850
  );
670
1851
  }
1852
+ notes.push(
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}`,
1854
+ );
671
1855
  return notes;
672
1856
  }