@astryxdesign/cli 0.7.14 → 0.7.15-canary.g06b7e61

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 (203) hide show
  1. package/CHANGELOG.md +3 -3
  2. package/README.md +63 -63
  3. package/api/build/_adapter.d.mts +4 -0
  4. package/api/build/_adapter.mjs +28 -2
  5. package/api/build/blocks/blocks.d.mts +10 -1
  6. package/api/build/blocks/blocks.mjs +84 -7
  7. package/api/build/build.mjs +6 -1
  8. package/api/build/tree.d.mts +4 -0
  9. package/api/build/tree.mjs +9 -2
  10. package/api/doctor/_adapter.d.mts +3 -1
  11. package/api/doctor/_adapter.mjs +14 -1
  12. package/api/doctor/_authoring-audit.d.mts +42 -0
  13. package/api/doctor/_authoring-audit.mjs +106 -0
  14. package/api/doctor/doctor.d.mts +7 -0
  15. package/api/doctor/doctor.mjs +24 -39
  16. package/api/doctor/theme-checks.mjs +56 -21
  17. package/api/integration/add-helpers.mjs +5 -0
  18. package/api/integration/add-theme.mjs +15 -110
  19. package/api/integration/validate-integration.mjs +17 -3
  20. package/api/integration/validateIntegration.doc.mjs +1 -1
  21. package/api/search/_adapter.mjs +124 -3
  22. package/api/search/_candidate-score.mjs +63 -9
  23. package/api/search/_entries.d.mts +10 -0
  24. package/api/search/_entries.mjs +68 -1
  25. package/api/search/_gather-templates.d.mts +11 -0
  26. package/api/search/_gather-templates.mjs +22 -2
  27. package/api/search/_words.mjs +26 -6
  28. package/api/swizzle/copy/copy.mjs +1 -1
  29. package/api/theme/_adapter.d.mts +37 -5
  30. package/api/theme/_adapter.mjs +381 -57
  31. package/api/theme/_fork.d.mts +90 -0
  32. package/api/theme/_fork.mjs +246 -0
  33. package/api/theme/build/build.d.mts +40 -2
  34. package/api/theme/build/build.mjs +477 -66
  35. package/api/theme/eject/eject.mjs +36 -15
  36. package/api/theme/list/list.mjs +3 -6
  37. package/api/theme/palette/generate/generator.d.mts +13 -0
  38. package/api/theme/palette/generate/generator.mjs +32 -2
  39. package/api/theme/targets/targets.d.mts +8 -0
  40. package/api/theme/targets/targets.mjs +24 -4
  41. package/api/theme/template/template.mjs +48 -2
  42. package/api/theme/theme.type.d.mts +8 -0
  43. package/api/theme/theme.type.mjs +5 -1
  44. package/api/theme/themeBuild.doc.mjs +7 -4
  45. package/api/theme/themeEject.doc.mjs +3 -3
  46. package/api/theme/themeRemove.doc.mjs +5 -2
  47. package/api/theme/themeTargets.doc.mjs +1 -1
  48. package/api/theme/themeTemplate.doc.mjs +2 -2
  49. package/api/theme/themeUse.doc.mjs +8 -2
  50. package/api/theme-edit/_adapter.d.mts +46 -3
  51. package/api/theme-edit/_adapter.mjs +496 -112
  52. package/api/theme-edit/_catalog.d.mts +1 -6
  53. package/api/theme-edit/_catalog.mjs +5 -268
  54. package/api/theme-edit/_check.d.mts +9 -4
  55. package/api/theme-edit/_check.mjs +1232 -229
  56. package/api/theme-edit/_color.d.mts +19 -0
  57. package/api/theme-edit/_color.mjs +280 -34
  58. package/api/theme-edit/_compiler.d.mts +3 -1
  59. package/api/theme-edit/_compiler.mjs +52 -13
  60. package/api/theme-edit/_context.d.mts +4 -1
  61. package/api/theme-edit/_context.mjs +126 -13
  62. package/api/theme-edit/_css.d.mts +84 -0
  63. package/api/theme-edit/_css.mjs +700 -0
  64. package/api/theme-edit/_edit.d.mts +9 -3
  65. package/api/theme-edit/_edit.mjs +806 -103
  66. package/api/theme-edit/_how-commands.d.mts +38 -7
  67. package/api/theme-edit/_how-commands.mjs +64 -45
  68. package/api/theme-edit/_how-question.d.mts +33 -0
  69. package/api/theme-edit/_how-question.mjs +2553 -381
  70. package/api/theme-edit/_how.mjs +402 -31
  71. package/api/theme-edit/_overview.mjs +2 -7
  72. package/api/theme-edit/_palette.d.mts +60 -13
  73. package/api/theme-edit/_palette.mjs +826 -295
  74. package/api/theme-edit/_parts.d.mts +42 -10
  75. package/api/theme-edit/_parts.mjs +280 -69
  76. package/api/theme-edit/_png.d.mts +4 -4
  77. package/api/theme-edit/_png.mjs +4 -2
  78. package/api/theme-edit/_preview-app.d.mts +14 -0
  79. package/api/theme-edit/_preview-app.mjs +1675 -235
  80. package/api/theme-edit/_preview.d.mts +7 -16
  81. package/api/theme-edit/_preview.mjs +79 -86
  82. package/api/theme-edit/_project.d.mts +32 -2
  83. package/api/theme-edit/_project.mjs +80 -19
  84. package/api/theme-edit/_settings.d.mts +199 -52
  85. package/api/theme-edit/_settings.mjs +1422 -217
  86. package/api/theme-edit/_tables.d.mts +19 -6
  87. package/api/theme-edit/_tables.mjs +150 -92
  88. package/api/theme-edit/theme-edit.type.d.mts +20 -1
  89. package/api/theme-edit/theme-edit.type.mjs +6 -3
  90. package/api/theme-edit/themeEditHow.doc.mjs +6 -0
  91. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  92. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +1 -1
  93. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  94. package/api/theme-edit/themeEditPreviewList.doc.mjs +2 -2
  95. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +5 -1
  96. package/api/theme-edit/themeEditSet.doc.mjs +1 -1
  97. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  98. package/api/upgrade/_adapter.d.mts +1 -0
  99. package/assets/codemods/run-codemod.mjs +61 -0
  100. package/assets/codemods/runner.mjs +5 -4
  101. package/assets/codemods/transforms/v0.0.14/rename-status-variants.mjs +3 -0
  102. package/assets/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs +5 -1
  103. package/assets/codemods/transforms/v0.6.4/migrate-native-picker-to-presentation.mjs +3 -0
  104. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +4 -0
  105. package/assets/codemods/transforms/v0.7.0/rename-empty-search-results-text.mjs +17 -12
  106. package/assets/codemods/transforms/v0.7.2/migrate-list-edge-compensation-to-edge.mjs +3 -0
  107. package/assets/codemods/transforms/v0.7.5/migrate-codeblock-tokenizer-to-language.mjs +3 -0
  108. package/assets/codemods/transforms/v0.7.8/promote-tokenizer-presentation.mjs +3 -0
  109. package/assets/docs/tree/calendars.doc.mjs +1 -3
  110. package/assets/docs/tree/checks.doc.mjs +22 -1
  111. package/assets/docs/tree/publishing.doc.mjs +1 -0
  112. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  113. package/assets/docs.generated.json +2 -1
  114. package/assets/preview-app/next.config.mjs +7 -1
  115. package/assets/self-audit.generated.json +1 -0
  116. package/assets/templates/blocks/components/Theme/useThemeNameHookUsage.doc.mjs +14 -0
  117. package/assets/templates/blocks/components/Theme/useThemeNameHookUsage.tsx +31 -0
  118. package/assets/templates/components.generated.json +1 -1
  119. package/authoring/integration/integration.doc.mjs +8 -0
  120. package/authoring/integration/schema.d.mts +8 -0
  121. package/authoring/integration/schema.mjs +1 -0
  122. package/authoring/integration/type.ts +9 -0
  123. package/clients/cli/bin/astryx.mjs +19 -15
  124. package/clients/cli/build-id.generated.json +1 -0
  125. package/clients/cli/commands/ensure-core-built.mjs +12 -5
  126. package/clients/cli/commands/experimental/index.mjs +10 -10
  127. package/clients/cli/commands/experimental/theme.mjs +200 -81
  128. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  129. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +1 -1
  130. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +3 -3
  131. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -2
  132. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  133. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  134. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  135. package/clients/cli/commands/experimental-theme-eject.doc.mjs +3 -3
  136. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  137. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  138. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +1 -1
  139. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +1 -1
  140. package/clients/cli/commands/experimental-theme-remove.doc.mjs +1 -1
  141. package/clients/cli/commands/experimental-theme-template.doc.mjs +4 -3
  142. package/clients/cli/commands/integration.mjs +8 -0
  143. package/clients/cli/commands/manifest.mjs +5 -2
  144. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  145. package/clients/cli/commands/theme-list.doc.mjs +1 -1
  146. package/clients/cli/commands/theme-template.doc.mjs +1 -1
  147. package/clients/cli/commands/theme.mjs +439 -66
  148. package/clients/cli/index.mjs +27 -6
  149. package/clients/cli/lib/cli-error.mjs +118 -3
  150. package/clients/cli/lib/manifest.mjs +37 -0
  151. package/clients/cli/lib/resolve-theme.mjs +2 -1
  152. package/clients/cli/manifest.generated.json +1 -0
  153. package/foundation/config/project.mjs +34 -8
  154. package/foundation/config/theme-state.d.mts +16 -0
  155. package/foundation/config/theme-state.mjs +84 -13
  156. package/foundation/discovery/module-exports.mjs +16 -2
  157. package/foundation/discovery/stored-self-audit.d.mts +31 -0
  158. package/foundation/discovery/stored-self-audit.mjs +119 -0
  159. package/foundation/discovery/template-adapter.d.mts +48 -2
  160. package/foundation/discovery/template-adapter.mjs +51 -19
  161. package/foundation/discovery/template-needs.d.mts +19 -0
  162. package/foundation/discovery/template-needs.mjs +50 -16
  163. package/foundation/discovery/template-source-tree.d.mts +7 -0
  164. package/foundation/discovery/template-source-tree.mjs +15 -0
  165. package/foundation/discovery/theme-discovery.d.mts +2 -1
  166. package/foundation/discovery/theme-discovery.mjs +16 -10
  167. package/foundation/discovery/theme-imports.d.mts +16 -0
  168. package/foundation/discovery/theme-imports.mjs +30 -2
  169. package/foundation/discovery/theme-module-extensions.d.mts +18 -0
  170. package/foundation/discovery/theme-module-extensions.mjs +30 -0
  171. package/foundation/doc-compiler/import.mjs +22 -15
  172. package/foundation/doc-compiler/stored-docs.d.mts +18 -12
  173. package/foundation/doc-compiler/stored-docs.mjs +52 -19
  174. package/foundation/env/private-dir.d.mts +17 -0
  175. package/foundation/env/private-dir.mjs +42 -0
  176. package/foundation/fs/gather-cache.d.mts +108 -0
  177. package/foundation/fs/gather-cache.mjs +783 -0
  178. package/foundation/fs/jiti-cache.d.mts +21 -0
  179. package/foundation/fs/jiti-cache.mjs +66 -0
  180. package/foundation/fs/module-loader.mjs +14 -3
  181. package/foundation/fs/read-record.d.mts +31 -1
  182. package/foundation/fs/read-record.mjs +100 -7
  183. package/foundation/integrations/autolink.d.mts +1 -24
  184. package/foundation/integrations/autolink.mjs +7 -60
  185. package/foundation/integrations/declared-dependencies.d.mts +27 -0
  186. package/foundation/integrations/declared-dependencies.mjs +73 -0
  187. package/foundation/integrations/integrations.d.mts +8 -0
  188. package/foundation/integrations/integrations.mjs +4 -0
  189. package/foundation/integrations/may-have-integrations.d.mts +8 -0
  190. package/foundation/integrations/may-have-integrations.mjs +47 -0
  191. package/foundation/integrations/validate-contributions.d.mts +62 -1
  192. package/foundation/integrations/validate-contributions.mjs +476 -40
  193. package/foundation/release/cache.d.mts +32 -4
  194. package/foundation/release/cache.mjs +105 -16
  195. package/foundation/release/folder-lock.d.mts +28 -0
  196. package/foundation/release/folder-lock.mjs +205 -0
  197. package/foundation/release/lock-lease.d.mts +2 -1
  198. package/foundation/release/lock-lease.mjs +7 -2
  199. package/foundation/response/error-codes.doc.mjs +1 -1
  200. package/foundation/response/response-types.doc.mjs +5 -5
  201. package/package.json +8 -6
  202. package/api/theme-edit/_css-properties.d.mts +0 -10
  203. package/api/theme-edit/_css-properties.mjs +0 -556
@@ -15,19 +15,24 @@
15
15
  * @position api/theme-edit — imported by _settings.mjs, _check.mjs, _how.mjs
16
16
  */
17
17
 
18
- import {createHash} from 'node:crypto';
19
18
  import * as fs from 'node:fs';
20
- import {createRequire} from 'node:module';
21
- import * as os from 'node:os';
22
19
  import * as path from 'node:path';
20
+ import {isAlive} from '../../foundation/release/cache.mjs';
21
+ import {stillHolds} from '../../foundation/release/folder-lock.mjs';
23
22
  import {AstryxError} from '../error.mjs';
24
23
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
24
+ import {parse} from '@babel/parser';
25
+ import {THEMES_DIR} from '../../foundation/discovery/theme-discovery.mjs';
25
26
  import {
27
+ ANCHOR_INPUT_KEYS,
26
28
  DEFAULT_21_STOPS,
29
+ FAMILY_INPUT_KEYS,
30
+ GENERATION_INPUT_KEYS,
27
31
  PALETTE_BLACK,
28
32
  PALETTE_GENERATOR_VERSION,
29
33
  PALETTE_WHITE,
30
34
  generateTonalPalette,
35
+ modesForStrategy,
31
36
  perceptualDelta,
32
37
  } from '../theme/palette/generate/generator.mjs';
33
38
  import {themePaletteGenerate} from '../theme/palette/generate/generate.mjs';
@@ -41,6 +46,8 @@ import {
41
46
  ratio,
42
47
  } from './_color.mjs';
43
48
  import {P} from './_tables.mjs';
49
+ import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
50
+ import {sha256} from '../../foundation/render/source-block.mjs';
44
51
 
45
52
  /**
46
53
  * Write a file whole: a temp file beside it, renamed into place, so a link
@@ -50,6 +57,22 @@ import {P} from './_tables.mjs';
50
57
  * @param {string | Buffer} text
51
58
  */
52
59
  export function writeWhole(file, text) {
60
+ // A folder where a file goes (a folder named preview.html) is never
61
+ // written through or replaced.
62
+ if (fs.lstatSync(file, {throwIfNoEntry: false})?.isDirectory())
63
+ throw new AstryxError(
64
+ `${[path.dirname(path.dirname(file)), path.dirname(file), file].map(p => path.basename(p)).join('/')} is a folder, so the editor cannot write that file there. Rename or move the folder, then run the command again.`,
65
+ [
66
+ {
67
+ name: `ls -la ${quoteCommandArgument(file)}`,
68
+ reason:
69
+ 'see what is in the folder; move or rename it, then run the same command again',
70
+ },
71
+ ],
72
+ ERROR_CODES.ERR_WRITE_FAILED,
73
+ );
74
+ sweepTemps(path.dirname(file));
75
+ refuseIfLockLost();
53
76
  const tmp = tempFor(file);
54
77
  try {
55
78
  fs.writeFileSync(tmp, text);
@@ -59,6 +82,95 @@ export function writeWhole(file, text) {
59
82
  }
60
83
  }
61
84
 
85
+ /**
86
+ * A command stopped long enough for another to take its lock (Ctrl-Z, a
87
+ * sleeping computer, a debugger) writes nothing more: refuse. Called right
88
+ * before each write.
89
+ */
90
+ export function refuseIfLockLost() {
91
+ if (lockHeld()) return;
92
+ const error = new AstryxError(
93
+ `Another command took over the theme's lock while this one was stopped (Ctrl-Z, a sleeping computer, a debugger). This command's change was not applied, and it touched nothing more: the files stay as the other command left them. Run it again if you still want it.`,
94
+ [{name: `${P} how --list dials`, reason: 'what you can set'}],
95
+ ERROR_CODES.ERR_THEME_BUSY,
96
+ );
97
+ /** @type {any} */ (error).lockLost = true;
98
+ throw error;
99
+ }
100
+
101
+ /** Whether this command still holds its lock (true outside a lock). */
102
+ export function lockHeld() {
103
+ try {
104
+ stillHolds();
105
+ return true;
106
+ } catch {
107
+ return false;
108
+ }
109
+ }
110
+
111
+ /** When this process started, for telling its own temp files from an earlier one's with the same id. */
112
+ const STARTED_AT = Date.now() - process.uptime() * 1000;
113
+
114
+ /**
115
+ * Remove the editor's own temp files a stopped command left in a folder:
116
+ * only names the editor makes (`.<name>.astryx-<pid>-<random>.tmp`) whose
117
+ * process is gone, or that are older than ten minutes. Links are never
118
+ * followed. A theme folder holds a few files, so every write looks.
119
+ * @param {string} dir
120
+ */
121
+ function sweepTemps(dir) {
122
+ let names;
123
+ try {
124
+ names = fs.readdirSync(dir);
125
+ } catch {
126
+ return;
127
+ }
128
+ for (const n of names) {
129
+ const m = /^\..+\.astryx-(\d+)-[a-z0-9]+\.tmp$/.exec(n);
130
+ if (!m) continue;
131
+ const p = path.join(dir, n);
132
+ try {
133
+ const st = fs.lstatSync(p);
134
+ // Writes into a theme folder run under its lock, so a temp file
135
+ // whose process is gone is never one a live command still renames.
136
+ if (!st.isFile()) continue;
137
+ // A process id from another process space (pid 1 in a container)
138
+ // may look alive here: past ten minutes, an editor temp file is a
139
+ // leftover whatever its id says (a live writer renames it in
140
+ // moments, and holds the lock this write holds now).
141
+ // A temp named with this process's own id but older than this process
142
+ // is another one's (pid 1 in each container start).
143
+ const own = Number(m[1]) === process.pid;
144
+ const young = Date.now() - st.mtimeMs < 10 * 60_000;
145
+ if (
146
+ own ? st.mtimeMs >= STARTED_AT && young : isAlive(Number(m[1])) && young
147
+ )
148
+ continue;
149
+ fs.rmSync(p, {force: true});
150
+ } catch {
151
+ // Gone already, or not ours to judge.
152
+ }
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Remove `dir` when it is empty; with `deep`, the empty folders under it
158
+ * first. A folder with a file in it stays.
159
+ * @param {string} dir
160
+ * @param {{deep?: boolean}} [opts]
161
+ */
162
+ export function removeEmptyFolder(dir, opts = {}) {
163
+ if (!fs.existsSync(dir)) return;
164
+ if (opts.deep)
165
+ for (const e of fs.readdirSync(dir, {withFileTypes: true}))
166
+ if (e.isDirectory()) removeEmptyFolder(path.join(dir, e.name), opts);
167
+ try {
168
+ fs.rmdirSync(dir);
169
+ } catch {
170
+ // Not empty, or gone already.
171
+ }
172
+ }
173
+
62
174
  /**
63
175
  * A temp file beside `file` for a whole write, named so only the editor
64
176
  * makes such names: `.<name>.astryx-<pid>-<random>.tmp`. The write that
@@ -98,6 +210,7 @@ export function tempFor(file) {
98
210
  * @property {number} needs
99
211
  * @property {boolean} pass
100
212
  * @property {string} [note] - The whole sentence to report, when the check is not a plain stop move.
213
+ * @property {string[]} [dials] - The color dials whose notes report it, when its token belongs to none of them.
101
214
  */
102
215
 
103
216
  /**
@@ -110,6 +223,7 @@ export function tempFor(file) {
110
223
  * @property {number} vibrancy - The generator's vibrancy, 0 to 100.
111
224
  * @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
225
  * @property {string[]} notes - What the config writer kept or replaced of a hand edit.
226
+ * @property {Record<string, Partial<Record<Mode, StopRef>>> | null} lift - Lifted secondary text per background token of LIFT_PARTS (the accent tint, the neutral track), per mode, from the neutral color; null without one.
113
227
  */
114
228
 
115
229
  /** The color dials. Each one is a palette family of the same id. */
@@ -165,64 +279,156 @@ const TEXT = 4.5;
165
279
  const NON_TEXT = 3;
166
280
 
167
281
  /**
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.
282
+ * The official neutral theme's color mapping, read from the theme the CLI
283
+ * ships rather than copied: each token's stops, `[light, dark]`, written
284
+ * there as `<family>.<mode>[N]` or `withAlpha(<family>.<mode>[N], 'aa')`,
285
+ * and the parts whose secondary text it lifts (`[part, block]`).
286
+ * @returns {{stops: Record<string, Array<{stop: number, alpha?: string}>>, lifted: Array<[string, string]>}}
172
287
  */
173
- const NEUTRAL_STOPS = /** @type {Record<string, [number, number]>} */ ({
174
- '--color-background-surface': [100, 15],
175
- '--color-background-card': [100, 10],
176
- '--color-background-popover': [100, 10],
177
- '--color-background-muted': [95, 10],
178
- '--color-text-primary': [0, 100],
179
- '--color-text-secondary': [30, 65],
180
- '--color-text-disabled': [60, 35],
181
- '--color-icon-primary': [0, 100],
182
- '--color-icon-secondary': [45, 65],
183
- '--color-icon-disabled': [60, 35],
184
- '--color-border-emphasized': [85, 35],
185
- '--color-skeleton': [95, 35],
186
- });
288
+ function readOfficialNeutral() {
289
+ const ast = parse(
290
+ fs.readFileSync(
291
+ path.join(THEMES_DIR, 'neutral', 'neutralTheme.ts'),
292
+ 'utf8',
293
+ ),
294
+ {sourceType: 'module', plugins: ['typescript']},
295
+ );
296
+ /** @param {any} n @returns {{stop: number, alpha?: string} | null} */
297
+ const stopOf = n => {
298
+ if (n?.type === 'CallExpression' && n.callee?.name === 'withAlpha') {
299
+ const inner = stopOf(n.arguments[0]);
300
+ const alpha = n.arguments[1]?.value;
301
+ return inner && typeof alpha === 'string'
302
+ ? {...inner, alpha: alpha.toLowerCase()}
303
+ : null;
304
+ }
305
+ return n?.type === 'MemberExpression' &&
306
+ n.computed &&
307
+ n.property.type === 'NumericLiteral' &&
308
+ ['light', 'dark'].includes(n.object?.property?.name)
309
+ ? {stop: n.property.value}
310
+ : null;
311
+ };
312
+ /** @type {Record<string, Array<{stop: number, alpha?: string}>>} */
313
+ const stops = {};
314
+ /** @type {Array<[string, string]>} */
315
+ const lifted = [];
316
+ /** @param {any} node @param {string[]} keys */
317
+ const visit = (node, keys) => {
318
+ if (!node || typeof node !== 'object') return;
319
+ if (node.type === 'ObjectProperty') {
320
+ const key = node.key.name ?? node.key.value;
321
+ const at = [...keys, String(key)];
322
+ if (keys.at(-1) === 'tokens' && node.value.type === 'ArrayExpression') {
323
+ const pair = node.value.elements.map(stopOf);
324
+ if (pair.length === 2 && pair.every(Boolean)) stops[key] = pair;
325
+ }
326
+ if (keys.at(-3) === 'components' && key === '--color-text-secondary')
327
+ lifted.push([keys.at(-2) ?? '', keys.at(-1) ?? '']);
328
+ visit(node.value, at);
329
+ return;
330
+ }
331
+ for (const [k, v] of Object.entries(node))
332
+ if (k !== 'loc' && k !== 'start' && k !== 'end')
333
+ for (const x of Array.isArray(v) ? v : [v]) visit(x, keys);
334
+ };
335
+ visit(ast.program, []);
336
+ return {stops, lifted};
337
+ }
338
+ const OFFICIAL = readOfficialNeutral();
339
+ /** A token's official `[light, dark]` stops. @param {string} token */
340
+ const officialStops = token =>
341
+ /** @type {[number, number]} */ (
342
+ (OFFICIAL.stops[token] ?? []).map(x => x.stop)
343
+ );
344
+
345
+ /**
346
+ * The tokens the neutral color sets at the official theme's stops. The page
347
+ * background, `--color-background-body`, stays the base theme's, so a
348
+ * tinted gray never tints the page. A layout without one of these stops
349
+ * uses the nearest one it has.
350
+ */
351
+ const NEUTRAL_STOPS = Object.fromEntries(
352
+ [
353
+ '--color-background-surface',
354
+ '--color-background-card',
355
+ '--color-background-popover',
356
+ '--color-background-muted',
357
+ '--color-text-primary',
358
+ '--color-text-secondary',
359
+ '--color-text-disabled',
360
+ '--color-icon-primary',
361
+ '--color-icon-secondary',
362
+ '--color-icon-disabled',
363
+ '--color-border-emphasized',
364
+ '--color-skeleton',
365
+ ].map(t => [t, officialStops(t)]),
366
+ );
187
367
  /** Neutral tints: a stop with an opacity, `[[stop, alpha], [stop, alpha]]`. */
188
- const NEUTRAL_TINTS =
189
- /** @type {Record<string, [[number, string], [number, string]]>} */ ({
190
- '--color-border': [
191
- [0, '14'],
192
- [100, '1a'],
193
- ],
194
- '--color-overlay-hover': [
195
- [0, '0d'],
196
- [100, '0d'],
197
- ],
198
- '--color-overlay-pressed': [
199
- [0, '1a'],
200
- [100, '1a'],
368
+ const NEUTRAL_TINTS = Object.fromEntries(
369
+ ['--color-border', '--color-overlay-hover', '--color-overlay-pressed'].map(
370
+ t => [
371
+ t,
372
+ /** @type {[[number, string], [number, string]]} */ (
373
+ OFFICIAL.stops[t].map(x => [x.stop, String(x.alpha)])
374
+ ),
201
375
  ],
202
- });
376
+ ),
377
+ );
203
378
  /**
204
379
  * 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]`).
380
+ * maps its accent tint and its status families (info stands for them). The
381
+ * dark fill starts at 70, where the theme authoring guide puts it, when the
382
+ * exact color does not read in dark. A status tint is translucent in dark
383
+ * (`[stop, alpha]`).
208
384
  */
209
385
  const DARK_FILL = 70;
210
- const TEXT_STOP = /** @type {[number, number]} */ ([45, 80]);
211
- const ACCENT_MUTED = /** @type {[number, number]} */ ([85, 30]);
212
- const STATUS_MUTED = /** @type {[number, [number, string]]} */ ([
213
- 85,
214
- [75, '3d'],
215
- ]);
216
- const ON_MUTED = /** @type {[number, number]} */ ([25, 80]);
386
+ const TEXT_STOP = officialStops('--color-text-info');
387
+ const ACCENT_MUTED = officialStops('--color-accent-muted');
388
+ const STATUS_MUTED = /** @type {[number, [number, string]]} */ (
389
+ OFFICIAL.stops['--color-info-muted'].map((x, i) =>
390
+ i === 0 ? x.stop : [x.stop, String(x.alpha)],
391
+ )
392
+ );
393
+ const ON_MUTED = officialStops('--color-on-info-muted');
394
+ /**
395
+ * The parts whose secondary text the official neutral theme lifts, with
396
+ * the block it lifts it in and what the text sits on: the accent tint,
397
+ * except under segmented-control labels, which sit on the translucent
398
+ * neutral track (`--color-neutral`).
399
+ */
400
+ export const LIFT_PARTS = OFFICIAL.lifted.map(
401
+ ([part, block]) =>
402
+ /** @type {[string, string, string]} */ ([
403
+ part,
404
+ block,
405
+ part === 'segmented-control-item'
406
+ ? '--color-neutral'
407
+ : '--color-accent-muted',
408
+ ]),
409
+ );
410
+ /** What each lifted background is, and the parts on it, for notes. */
411
+ const LIFT_GROUNDS =
412
+ /** @type {Record<string, {what: string, parts: string}>} */ ({
413
+ '--color-accent-muted': {
414
+ what: 'the accent tint',
415
+ parts: 'selected items and rows, a dropzone, numbered citations',
416
+ },
417
+ '--color-neutral': {
418
+ what: 'the neutral track',
419
+ parts: 'segmented-control labels',
420
+ },
421
+ });
217
422
  const BORDER = /** @type {[number, number]} */ ([80, 65]);
218
423
  /**
219
424
  * Text on a fill, from the neutral family as the official themes take it:
220
425
  * white (100) first in light, near-black (5) first in dark, and near-black
221
426
  * first in both modes on warning. Without a neutral color, black and white.
222
427
  */
428
+ const [ON_LIGHT, ON_DARK] = officialStops('--color-on-accent');
223
429
  const ON_FILL = /** @type {Record<Mode, [number, number]>} */ ({
224
- light: [100, 5],
225
- dark: [5, 100],
430
+ light: [ON_LIGHT, ON_DARK],
431
+ dark: [ON_DARK, ON_LIGHT],
226
432
  });
227
433
  /** A layout needs this many stops between black and white to map every token. */
228
434
  const MIN_INNER_STOPS = 5;
@@ -290,16 +496,16 @@ function sameColor(a, b) {
290
496
  }
291
497
 
292
498
  /**
293
- * The modes a theme has.
499
+ * The modes a theme has: one for a one-mode theme, else light and dark.
294
500
  * @param {{mode?: string}} data
295
501
  * @returns {Mode[]}
296
502
  */
297
- function themeModes(data) {
298
- return data.mode === 'light-only'
299
- ? ['light']
300
- : data.mode === 'dark-only'
301
- ? ['dark']
302
- : ['light', 'dark'];
503
+ export function modesOf(data) {
504
+ return modesForStrategy(
505
+ data.mode === 'light-only' || data.mode === 'dark-only'
506
+ ? data.mode
507
+ : 'light-and-dark',
508
+ );
303
509
  }
304
510
 
305
511
  /**
@@ -319,16 +525,47 @@ function dialFamilies(data) {
319
525
  return out;
320
526
  }
321
527
 
528
+ /** Notes for damaged color configs kept aside during one sync. @type {string[]} */
529
+ const keptDamaged = [];
530
+
322
531
  /** @param {string} file */
323
532
  function readConfig(file) {
324
533
  if (!fs.existsSync(file)) return null;
325
534
  try {
326
535
  return JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
327
- } catch (e) {
328
- throw new AstryxError(
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.`,
330
- [],
331
- ERROR_CODES.ERR_THEME_INVALID,
536
+ } catch {
537
+ // A file that does not parse holds nothing the editor can keep: it is
538
+ // read as no config. Only a command that writes the theme keeps its
539
+ // text aside (keepDamaged), so a read writes nothing.
540
+ damagedConfigs.add(file);
541
+ return null;
542
+ }
543
+ }
544
+
545
+ /** Damaged configs read in this run, kept aside when a change is written. */
546
+ const damagedConfigs = new Set();
547
+
548
+ /**
549
+ * Keep a damaged config's text beside it (palette.config.damaged.json,
550
+ * then -2, -3 …; the same text once) before the editor writes the config
551
+ * again, and say where.
552
+ * @param {string} file
553
+ */
554
+ function keepDamaged(file) {
555
+ if (!damagedConfigs.has(file) || !fs.existsSync(file)) return;
556
+ damagedConfigs.delete(file);
557
+ {
558
+ const text = fs.readFileSync(file);
559
+ let n = 1;
560
+ const name = (/** @type {number} */ k) =>
561
+ `palette.config.damaged${k > 1 ? `-${k}` : ''}.json`;
562
+ const at = (/** @type {number} */ k) =>
563
+ path.join(path.dirname(file), name(k));
564
+ // The same damaged text is kept once.
565
+ while (fs.existsSync(at(n)) && !fs.readFileSync(at(n)).equals(text)) n++;
566
+ if (!fs.existsSync(at(n))) fs.copyFileSync(file, at(n));
567
+ keptDamaged.push(
568
+ `palette.config.json was damaged, so it was made again from the settings; its text is kept in ${name(n)}`,
332
569
  );
333
570
  }
334
571
  }
@@ -362,17 +599,6 @@ function savedSettings(cwd, slug) {
362
599
  const strategyOf = modes =>
363
600
  modes.length > 1 ? 'light-and-dark' : `${modes[0]}-only`;
364
601
 
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
602
  /**
377
603
  * The fields of a config the generator never reads (such as
378
604
  * `darkChromaTaper`), by path.
@@ -381,17 +607,19 @@ const ANCHOR_KEYS = ['mode', 'stop', 'color', 'policy', 'maxDeltaE'];
381
607
  */
382
608
  function deadKeys(config) {
383
609
  /** @type {string[]} */
384
- const out = Object.keys(config).filter(k => !CONFIG_KEYS.includes(k));
610
+ const out = Object.keys(config).filter(
611
+ k => !GENERATION_INPUT_KEYS.includes(k),
612
+ );
385
613
  (Array.isArray(config.families) ? config.families : []).forEach(
386
614
  (/** @type {any} */ f, /** @type {number} */ i) => {
387
615
  if (!f || typeof f !== 'object') return;
388
616
  for (const k of Object.keys(f))
389
- if (!FAMILY_KEYS.includes(k)) out.push(`families[${i}].${k}`);
617
+ if (!FAMILY_INPUT_KEYS.includes(k)) out.push(`families[${i}].${k}`);
390
618
  (Array.isArray(f.anchors) ? f.anchors : []).forEach(
391
619
  (/** @type {any} */ a, /** @type {number} */ j) => {
392
620
  if (a && typeof a === 'object')
393
621
  for (const k of Object.keys(a))
394
- if (!ANCHOR_KEYS.includes(k))
622
+ if (!ANCHOR_INPUT_KEYS.includes(k))
395
623
  out.push(`families[${i}].anchors[${j}].${k}`);
396
624
  },
397
625
  );
@@ -461,7 +689,7 @@ function usableStops(stops, slug) {
461
689
  const refuse = why => {
462
690
  throw new AstryxError(
463
691
  `themes/${slug}/palette.config.json: its stops (${shown}) ${why}. ${fix}`,
464
- [],
692
+ [{name: `${P} how colors`, reason: 'how the shades are made'}],
465
693
  ERROR_CODES.ERR_THEME_INVALID,
466
694
  );
467
695
  };
@@ -525,6 +753,42 @@ function tools(candidate, data, base) {
525
753
  const rgb = v == null ? null : parseColor(v);
526
754
  return rgb && alphaOf(v) >= 1 ? hex(rgb) : null;
527
755
  };
756
+ /**
757
+ * The exact whole-theme color a token setting gives in a mode, see-through
758
+ * or not, as written (a hex keeps its alpha digits); null when there is
759
+ * none or it is not a fixed color.
760
+ * @param {string} token @param {Mode} m
761
+ */
762
+ const rawOf = (token, m) => {
763
+ const v = [...data.settings]
764
+ .reverse()
765
+ .find(
766
+ s =>
767
+ s.source === 'token' &&
768
+ s.thing === token &&
769
+ !s.on &&
770
+ !s.when &&
771
+ !s.state &&
772
+ (!s.mode || s.mode === m),
773
+ )?.value;
774
+ return v != null && parseColor(v) ? String(v).trim() : null;
775
+ };
776
+ /**
777
+ * Which column of a `[light, dark]` mapping a mode takes: the light one
778
+ * on a light page and the dark one on a dark page, by the page the theme
779
+ * keeps (its exact page color, else the base theme's). A base whose
780
+ * light page is dark, such as Gothic, gets dark-page shades in light.
781
+ * @param {Mode} m
782
+ * @returns {0 | 1}
783
+ */
784
+ const side = m => {
785
+ const page =
786
+ rawOf('--color-background-body', m) ??
787
+ base?.[m]?.['--color-background-body'];
788
+ const rgb = page ? parseColor(page) : null;
789
+ if (!rgb || alphaOf(page) < 1) return m === 'light' ? 0 : 1;
790
+ return ratio(rgb, [255, 255, 255]) > ratio(rgb, [0, 0, 0]) ? 1 : 0;
791
+ };
528
792
  /**
529
793
  * What text and fills sit on in a mode: the theme's exact surface
530
794
  * colors, else the neutral color's surfaces, else the base theme's; the
@@ -542,16 +806,14 @@ function tools(candidate, data, base) {
542
806
  ]) {
543
807
  const own =
544
808
  neutral && NEUTRAL_STOPS[n]
545
- ? ref('neutral', m, at(NEUTRAL_STOPS[n][m === 'light' ? 0 : 1])).color
809
+ ? ref('neutral', m, at(NEUTRAL_STOPS[n][side(m)])).color
546
810
  : null;
547
811
  const v = exactOf(n, m) ?? own ?? base?.[m]?.[n];
548
812
  if (v && parseColor(v) && alphaOf(v) >= 1)
549
813
  out.push([n, hex(/** @type {number[]} */ (parseColor(v)))]);
550
814
  }
551
815
  if (!out.length) {
552
- const s = at(
553
- NEUTRAL_STOPS['--color-background-surface'][m === 'light' ? 0 : 1],
554
- );
816
+ const s = at(NEUTRAL_STOPS['--color-background-surface'][side(m)]);
555
817
  out.push([`${id} shade ${s}`, ref(id, m, s).color]);
556
818
  }
557
819
  return out;
@@ -592,82 +854,33 @@ function tools(candidate, data, base) {
592
854
  /** The lowest contrast of a color on the surfaces. @param {string} color @param {Mode} m @param {string} id */
593
855
  const page = (color, m, id) =>
594
856
  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',
857
+ /**
858
+ * A color as the eye sees it on the surface in a mode: a see-through one
859
+ * drawn over the first surface.
860
+ * @param {string} color @param {Mode} m @param {string} id
861
+ */
862
+ const solid = (color, m, id) => {
863
+ const rgb = /** @type {[number, number, number]} */ (parseColor(color));
864
+ const a = alphaOf(color);
865
+ if (a >= 1) return hex(rgb);
866
+ const under = /** @type {[number, number, number]} */ (
867
+ parseColor(surfaces(m, id)[0][1])
630
868
  );
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;
869
+ return hex(compositeOver(rgb, a, under));
870
+ };
871
+ return {
872
+ stops,
873
+ at,
874
+ ref,
875
+ exactOf,
876
+ rawOf,
877
+ side,
878
+ solid,
879
+ surfaces,
880
+ onFor,
881
+ page,
882
+ neutral,
883
+ };
671
884
  }
672
885
 
673
886
  /** A text shade, named for a sentence. @param {StopRef} r */
@@ -739,7 +952,7 @@ function planPalette(cwd, slug, data, base) {
739
952
  ? {...existing}
740
953
  : {};
741
954
  const {settings: saved, mode: savedMode} = savedSettings(cwd, slug);
742
- const modes = themeModes(data);
955
+ const modes = modesOf(data);
743
956
 
744
957
  const vibrancy = dialVibrancy(data.settings);
745
958
  const savedVibrancy = dialVibrancy(saved);
@@ -762,7 +975,7 @@ function planPalette(cwd, slug, data, base) {
762
975
  const strategy = strategyOf(modes);
763
976
  // Only a value the editor did not write is a hand edit worth naming: the
764
977
  // one it wrote follows the theme's mode as it was saved.
765
- const wrote = savedMode ? strategyOf(themeModes({mode: savedMode})) : null;
978
+ const wrote = savedMode ? strategyOf(modesOf({mode: savedMode})) : null;
766
979
  if (
767
980
  config.modeStrategy != null &&
768
981
  config.modeStrategy !== strategy &&
@@ -852,13 +1065,13 @@ function planPalette(cwd, slug, data, base) {
852
1065
  if (seedColored(a) && a.stop === editorStop) continue;
853
1066
  if (!modes.includes(a?.mode)) {
854
1067
  notes.push(
855
- `${file}: the ${f.id} ${a?.mode} anchor at shade ${a?.stop} is dropped: the theme has no ${a?.mode} mode`,
1068
+ `${file}: the ${f.id} ${a?.mode} anchor at shade ${shade(a?.stop)} is dropped: the theme has no ${a?.mode} mode`,
856
1069
  );
857
1070
  continue;
858
1071
  }
859
1072
  if (mine.some(x => x.mode === a.mode && x.stop === a.stop)) {
860
1073
  notes.push(
861
- `${file}: your ${a.mode} anchor at shade ${a.stop} of ${f.id} is replaced by your exact ${f.id} color`,
1074
+ `${file}: your ${a.mode} anchor at shade ${shade(a.stop)} of ${f.id} is replaced by your exact ${f.id} color`,
862
1075
  );
863
1076
  continue;
864
1077
  }
@@ -880,7 +1093,13 @@ function planPalette(cwd, slug, data, base) {
880
1093
  };
881
1094
  if (!kind) delete out.kind;
882
1095
  if (!out.anchors.length) delete out.anchors;
883
- return {family: out, stop};
1096
+ // The keys always in one order, so a change and its undo write the
1097
+ // same bytes.
1098
+ /** @type {Record<string, unknown>} */
1099
+ const ordered = {};
1100
+ for (const k of FAMILY_INPUT_KEYS) if (k in out) ordered[k] = out[k];
1101
+ for (const k of Object.keys(out)) if (!(k in ordered)) ordered[k] = out[k];
1102
+ return {family: /** @type {typeof out} */ (ordered), stop};
884
1103
  };
885
1104
 
886
1105
  /** @type {PalettePlan['fills']} */
@@ -952,7 +1171,7 @@ function planPalette(cwd, slug, data, base) {
952
1171
  );
953
1172
  if (others.length < (f.anchors ?? []).length)
954
1173
  notes.push(
955
- `${file}: your dark anchor at shade ${anchor.stop} of ${id} is replaced by your exact ${id} color`,
1174
+ `${file}: your dark anchor at shade ${shade(anchor.stop)} of ${id} is replaced by your exact ${id} color`,
956
1175
  );
957
1176
  return {
958
1177
  ...f,
@@ -992,9 +1211,6 @@ export function paletteConfig(cwd, slug, data, base) {
992
1211
  return planPalette(cwd, slug, data, base)?.config ?? null;
993
1212
  }
994
1213
 
995
- /** @param {string} text */
996
- const sha256 = text => createHash('sha256').update(text).digest('hex');
997
-
998
1214
  /**
999
1215
  * Write the palette config, palette and receipt the settings ask for, with
1000
1216
  * the same generator as `theme palette generate --out`; remove them all
@@ -1012,6 +1228,24 @@ const sha256 = text => createHash('sha256').update(text).digest('hex');
1012
1228
  * @returns {string[]}
1013
1229
  */
1014
1230
  export function syncPalette(cwd, slug, data, base) {
1231
+ keptDamaged.length = 0;
1232
+ // The config is read first, so a damaged one is kept aside before the
1233
+ // sync writes it again.
1234
+ const config = path.join(cwd, paletteFiles(slug).config);
1235
+ readConfig(config);
1236
+ keepDamaged(config);
1237
+ const notes = syncPaletteFiles(cwd, slug, data, base);
1238
+ return [...keptDamaged.splice(0), ...notes];
1239
+ }
1240
+
1241
+ /**
1242
+ * @param {string} cwd
1243
+ * @param {string} slug
1244
+ * @param {any} data
1245
+ * @param {any} base
1246
+ * @returns {string[]}
1247
+ */
1248
+ function syncPaletteFiles(cwd, slug, data, base) {
1015
1249
  const f = paletteFiles(slug);
1016
1250
  const abs = (/** @type {string} */ p) => path.join(cwd, p);
1017
1251
  const plan = planPalette(cwd, slug, data, base);
@@ -1030,17 +1264,30 @@ export function syncPalette(cwd, slug, data, base) {
1030
1264
  saved = undefined;
1031
1265
  }
1032
1266
  const hash = fs.existsSync(abs(f.config))
1033
- ? sha256(fs.readFileSync(abs(f.config), 'utf8'))
1267
+ ? sha256(fs.readFileSync(abs(f.config)))
1034
1268
  : null;
1035
1269
  const mine = hash != null && (data.palette === hash || saved === hash);
1036
1270
  delete data.palette;
1037
1271
  if (!mine) return [];
1038
- for (const p of [f.config, f.palette, f.receipt, f.refs])
1272
+ // A palette file edited by hand is never deleted: it stays, and the
1273
+ // result names it. Its config and receipt go, so the next color change
1274
+ // asks whether to keep or discard it.
1275
+ // The selected-stops file is generated from the palette on every
1276
+ // change, so it always goes.
1277
+ const editedPalette = paletteEdited(cwd, slug);
1278
+ /** @type {string[]} */
1279
+ const notes = [];
1280
+ for (const p of [f.config, f.receipt, f.refs])
1039
1281
  fs.rmSync(abs(p), {force: true});
1282
+ if (editedPalette)
1283
+ notes.push(
1284
+ `${f.palette} was edited by hand, so it stays: the theme no longer reads it. Move it out of tokens/ to keep it as your own, or delete it`,
1285
+ );
1286
+ else fs.rmSync(abs(f.palette), {force: true});
1040
1287
  const tokensDir = path.dirname(abs(f.palette));
1041
1288
  if (fs.existsSync(tokensDir) && !fs.readdirSync(tokensDir).length)
1042
1289
  fs.rmdirSync(tokensDir);
1043
- return [];
1290
+ return notes;
1044
1291
  }
1045
1292
  const text = `${JSON.stringify(plan.config, null, 2)}\n`;
1046
1293
  /** @type {any} */
@@ -1058,59 +1305,160 @@ export function syncPalette(cwd, slug, data, base) {
1058
1305
  // Nothing to rewrite: no notes either, so a kept hand edit is named once,
1059
1306
  // when a color change touches the config.
1060
1307
  if (same) {
1061
- data.palette = sha256(text);
1062
- return [];
1308
+ data.palette = sha256(Buffer.from(text));
1309
+ // The theme reads only the selected shades, which come from the
1310
+ // generator, so a hand edit to the palette file never shows: say so.
1311
+ return paletteEdited(cwd, slug)
1312
+ ? [
1313
+ `${f.palette} was edited by hand, but the theme never reads it: it reads ${f.refs}, which the editor writes from the generator, so your edit does not show. The next color change asks whether to keep or discard it`,
1314
+ ]
1315
+ : [];
1063
1316
  }
1064
1317
  if (paletteEdited(cwd, slug)) {
1065
1318
  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
- [],
1319
+ `${f.palette} was edited by hand, so the editor will not write over it. The theme never read the edit: it reads ${f.refs}, which the editor writes from the generator. 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.`,
1320
+ [
1321
+ {
1322
+ name: `${P} show ${slug}`,
1323
+ reason: `do this next: after you move ${f.palette} out of tokens/ (keeps your edits) or delete it (discards them), run your command again; show lists the theme as it is now`,
1324
+ },
1325
+ ],
1068
1326
  ERROR_CODES.ERR_THEME_INVALID,
1069
1327
  );
1070
1328
  }
1071
1329
  fs.mkdirSync(path.dirname(abs(f.config)), {recursive: true});
1072
1330
  writeWhole(abs(f.config), text);
1073
- data.palette = sha256(text);
1331
+ data.palette = sha256(Buffer.from(text));
1074
1332
  themePaletteGenerate(f.config, {out: f.palette, overwrite: true}, {cwd});
1075
1333
  return plan.notes;
1076
1334
  }
1077
1335
 
1078
1336
  /**
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.
1337
+ * The value of the object literal that starts at the first `{` from
1338
+ * `from`, read as data: string and numeric keys, string values, nested
1339
+ * objects; quotes, commas, comments and white space as any formatter writes
1340
+ * them. Null when it is not such a literal.
1081
1341
  * @param {string} text
1342
+ * @param {number} from
1343
+ * @returns {any}
1082
1344
  */
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-'));
1345
+ function objectLiteral(text, from) {
1346
+ const open = text.indexOf('{', from);
1347
+ if (open < 0) return null;
1348
+ /** @type {string[]} */
1349
+ const json = [];
1350
+ let depth = 0;
1351
+ let i = open;
1352
+ while (i < text.length) {
1353
+ const c = text[i];
1354
+ if (c === '/' && text[i + 1] === '/') {
1355
+ i = text.indexOf('\n', i);
1356
+ if (i < 0) return null;
1357
+ continue;
1358
+ }
1359
+ if (c === '/' && text[i + 1] === '*') {
1360
+ i = text.indexOf('*/', i + 2);
1361
+ if (i < 0) return null;
1362
+ i += 2;
1363
+ continue;
1364
+ }
1365
+ if (c === '"' || c === "'") {
1366
+ let j = i + 1;
1367
+ let v = '';
1368
+ while (j < text.length && text[j] !== c) {
1369
+ if (text[j] === '\\') j++;
1370
+ v += text[j++];
1371
+ }
1372
+ json.push(JSON.stringify(v));
1373
+ i = j + 1;
1374
+ continue;
1375
+ }
1376
+ if (/[\s]/.test(c)) {
1377
+ i++;
1378
+ continue;
1379
+ }
1380
+ if (c === '{' || c === '[') depth++;
1381
+ if (c === '}' || c === ']') {
1382
+ // A trailing comma before a closing bracket.
1383
+ if (json.at(-1) === ',') json.pop();
1384
+ depth--;
1385
+ }
1386
+ if ('{}[]:,'.includes(c)) {
1387
+ json.push(c);
1388
+ i++;
1389
+ if (depth === 0) break;
1390
+ continue;
1391
+ }
1392
+ const word = /^[\w.$+-]+/.exec(text.slice(i))?.[0];
1393
+ if (!word) return null;
1394
+ json.push(JSON.stringify(word));
1395
+ i += word.length;
1396
+ }
1098
1397
  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');
1398
+ return JSON.parse(json.join(''));
1102
1399
  } catch {
1103
1400
  return null;
1104
- } finally {
1105
- fs.rmSync(dir, {recursive: true, force: true});
1106
1401
  }
1107
1402
  }
1108
1403
 
1109
1404
  /**
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.
1405
+ * The colors a palette module holds, read as data so formatting never
1406
+ * counts: `palette` (family, mode, stop, color) and `black`/`white`. Null
1407
+ * when the file does not read as one.
1408
+ * @param {string} text
1409
+ * @returns {{palette: any, black: string | null, white: string | null} | null}
1410
+ */
1411
+ function paletteData(text) {
1412
+ const t = text.replace(/^\uFEFF/, '');
1413
+ const at = /\bconst\s+palette\s*=/.exec(t);
1414
+ const palette = at ? objectLiteral(t, at.index) : null;
1415
+ if (!palette || typeof palette !== 'object') return null;
1416
+ /** @param {string} name */
1417
+ const end = name =>
1418
+ new RegExp(`\\bconst\\s+${name}\\s*=\\s*["'](#[0-9a-fA-F]{6})["']`)
1419
+ .exec(t)?.[1]
1420
+ ?.toLowerCase() ?? null;
1421
+ return {palette, black: end('black'), white: end('white')};
1422
+ }
1423
+
1424
+ /**
1425
+ * Whether two palettes hold the same colors at the same stops.
1426
+ * @param {any} a @param {any} b
1427
+ */
1428
+ function samePalette(a, b) {
1429
+ /** @param {any} p */
1430
+ const flat = p => {
1431
+ /** @type {string[]} */
1432
+ const out = [];
1433
+ for (const [fam, f] of Object.entries(p ?? {}))
1434
+ for (const m of /** @type {Mode[]} */ (['light', 'dark']))
1435
+ for (const [stop, color] of Object.entries(
1436
+ /** @type {any} */ (f)?.[m] ?? {},
1437
+ ))
1438
+ out.push(
1439
+ `${fam}.${m}.${Number(stop)}=${String(color).toLowerCase()}`,
1440
+ );
1441
+ return out.sort().join('|');
1442
+ };
1443
+ return flat(a) === flat(b);
1444
+ }
1445
+
1446
+ /**
1447
+ * The first line of the empty palette module the preview writes for a
1448
+ * Colors page it keeps (changed by hand) once the theme has no colors, so
1449
+ * the app still builds. The editor replaces it freely.
1450
+ */
1451
+ export const PALETTE_STAND_IN =
1452
+ '// A stand-in for a preview page that imports this file: the theme has no generated colors.';
1453
+
1454
+ /**
1455
+ * Whether a theme's palette file was edited by hand. Its bytes match its
1456
+ * receipt, or its colors (read as data, so formatting, a BOM or semicolons
1457
+ * never count) are the ones the generator gives for the request it came
1458
+ * from: the receipt's, else the config the editor wrote. Without a receipt
1459
+ * and with a config edited by hand since, the request is unknown; then the
1460
+ * file counts as the editor's when it holds every shade the theme ships
1461
+ * (the selected-stops file) unchanged. False when there is no palette file.
1114
1462
  * @param {string} cwd
1115
1463
  * @param {string} slug
1116
1464
  */
@@ -1118,7 +1466,9 @@ export function paletteEdited(cwd, slug) {
1118
1466
  const f = paletteFiles(slug);
1119
1467
  const file = path.join(cwd, f.palette);
1120
1468
  if (!fs.existsSync(file)) return false;
1121
- const palette = fs.readFileSync(file, 'utf8');
1469
+ const text = fs.readFileSync(file, 'utf8');
1470
+ // The empty stand-in a kept preview page imports is the editor's own.
1471
+ if (text.startsWith(PALETTE_STAND_IN)) return false;
1122
1472
  /** @type {any} */
1123
1473
  let receipt;
1124
1474
  try {
@@ -1126,17 +1476,67 @@ export function paletteEdited(cwd, slug) {
1126
1476
  } catch {
1127
1477
  receipt = null;
1128
1478
  }
1129
- if (receipt?.candidateSha256 === sha256(palette)) return false;
1479
+ if (receipt?.candidateSha256 === sha256(Buffer.from(text))) return false;
1480
+ const data = paletteData(text);
1481
+ if (!data) return true;
1130
1482
  /** @type {any} */
1131
1483
  let request = receipt?.request ?? null;
1484
+ let configMine = false;
1132
1485
  if (!request)
1133
1486
  try {
1134
- request = JSON.parse(fs.readFileSync(path.join(cwd, f.config), 'utf8'));
1487
+ const configText = fs.readFileSync(path.join(cwd, f.config), 'utf8');
1488
+ const saved = JSON.parse(
1489
+ fs.readFileSync(
1490
+ path.join(cwd, 'themes', slug, `${slug}.settings.json`),
1491
+ 'utf8',
1492
+ ),
1493
+ )?.palette;
1494
+ configMine = saved == null || saved === sha256(Buffer.from(configText));
1495
+ request = JSON.parse(configText.replace(/^\uFEFF/, ''));
1135
1496
  } catch {
1136
1497
  request = null;
1137
1498
  }
1138
- const expected = request ? renderPalette(request) : null;
1139
- return expected == null || normalized(expected) !== normalized(palette);
1499
+ if (request && (receipt?.request || configMine))
1500
+ try {
1501
+ const candidate = generateTonalPalette(request);
1502
+ return !(
1503
+ samePalette(candidate.palette, data.palette) &&
1504
+ (data.black == null || data.black === candidate.black) &&
1505
+ (data.white == null || data.white === candidate.white)
1506
+ );
1507
+ } catch {
1508
+ return true;
1509
+ }
1510
+ return refsDiffer(cwd, slug, data.palette) !== false;
1511
+ }
1512
+
1513
+ /**
1514
+ * Whether the selected-stops file holds a shade that differs from the
1515
+ * palette's: true when one differs, false when every one matches, null
1516
+ * when there is no such file to compare.
1517
+ * @param {string} cwd
1518
+ * @param {string} slug
1519
+ * @param {any} palette the palette file's colors
1520
+ * @returns {boolean | null}
1521
+ */
1522
+ function refsDiffer(cwd, slug, palette) {
1523
+ const file = path.join(cwd, paletteFiles(slug).refs);
1524
+ if (!fs.existsSync(file)) return null;
1525
+ const refs = objectLiteral(fs.readFileSync(file, 'utf8'), 0);
1526
+ if (!refs || typeof refs !== 'object') return true;
1527
+ for (const [fam, f] of Object.entries(refs)) {
1528
+ if (typeof f !== 'object' || !f) continue;
1529
+ for (const [m, ramp] of Object.entries(/** @type {any} */ (f)))
1530
+ for (const [stop, color] of Object.entries(/** @type {any} */ (ramp))) {
1531
+ const mine = palette?.[fam]?.[m];
1532
+ const at = mine
1533
+ ? Object.entries(mine).find(([k]) => Number(k) === Number(stop))?.[1]
1534
+ : undefined;
1535
+ if (String(at ?? '').toLowerCase() !== String(color).toLowerCase())
1536
+ return true;
1537
+ }
1538
+ }
1539
+ return false;
1140
1540
  }
1141
1541
 
1142
1542
  /**
@@ -1259,7 +1659,7 @@ function generate(config, file = 'palette.config.json') {
1259
1659
  } catch (e) {
1260
1660
  throw new AstryxError(
1261
1661
  `${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.`,
1262
- [],
1662
+ [{name: `${P} how colors`, reason: 'how the colors are made'}],
1263
1663
  ERROR_CODES.ERR_PALETTE_GENERATION,
1264
1664
  );
1265
1665
  }
@@ -1304,6 +1704,9 @@ function over(name, r, under) {
1304
1704
  /** @param {number} r */
1305
1705
  const round = r => Math.round(r * 100) / 100;
1306
1706
 
1707
+ /** A stop as text: a layout may hold 16.666666666666668. @param {number} s */
1708
+ const shade = s => String(round(s));
1709
+
1307
1710
  /**
1308
1711
  * The colors and token mapping of a theme's palette, or null when it sets no
1309
1712
  * color dial. Reads the config the settings ask for and runs the generator
@@ -1322,20 +1725,8 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
1322
1725
  const {config} = plan;
1323
1726
  const candidate = generate(config, paletteFiles(slug).config);
1324
1727
  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
- };
1728
+ const {stops, at, ref, exactOf, rawOf, side, solid, surfaces} = t;
1729
+ const modes = modesOf(data);
1339
1730
  /** @type {PaletteMapping['tokens']} */
1340
1731
  const tokens = {};
1341
1732
  /** @type {ContrastCheck[]} */
@@ -1416,7 +1807,7 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
1416
1807
  put(
1417
1808
  token,
1418
1809
  'neutral',
1419
- each(m => ref('neutral', m, at(pair[m === 'light' ? 0 : 1]))),
1810
+ each(m => ref('neutral', m, at(pair[side(m)]))),
1420
1811
  );
1421
1812
  }
1422
1813
  for (const [token, pair] of Object.entries(NEUTRAL_TINTS))
@@ -1424,7 +1815,7 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
1424
1815
  token,
1425
1816
  'neutral',
1426
1817
  each(m => {
1427
- const [s, a] = pair[m === 'light' ? 0 : 1];
1818
+ const [s, a] = pair[side(m)];
1428
1819
  return ref('neutral', m, at(s), a);
1429
1820
  }),
1430
1821
  );
@@ -1440,7 +1831,7 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
1440
1831
  token,
1441
1832
  'neutral',
1442
1833
  m,
1443
- at(NEUTRAL_STOPS[token][m === 'light' ? 0 : 1]),
1834
+ at(NEUTRAL_STOPS[token][side(m)]),
1444
1835
  surfaces(m, 'neutral'),
1445
1836
  needs,
1446
1837
  ),
@@ -1484,7 +1875,7 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
1484
1875
  /** @type {Partial<Record<Mode, string>>} */
1485
1876
  const exactFill = {};
1486
1877
  for (const m of modes) {
1487
- const v = exactOf(names.fill, m);
1878
+ const v = rawOf(names.fill, m);
1488
1879
  if (v) exactFill[m] = v;
1489
1880
  }
1490
1881
  if (Object.keys(exactFill).length) exact[names.fill] = exactFill;
@@ -1520,7 +1911,7 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
1520
1911
  ratio: plain.ratio,
1521
1912
  needs: TEXT,
1522
1913
  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`}`,
1914
+ note: `in dark, ${names.fill} is shade ${shade(found)}, not your exact color: ${plain.why}${found === start ? '' : `; shade ${shade(start)} does not pass either, so it is the nearest shade that does`}`,
1524
1915
  });
1525
1916
  }
1526
1917
  put(names.fill, f.id, fill);
@@ -1530,10 +1921,11 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
1530
1921
  // text changes instead.
1531
1922
  const on = each(m => {
1532
1923
  const used = exactFill[m] ?? /** @type {StopRef} */ (fill[m]).color;
1533
- const o = t.onFor(fillWord, m, used);
1924
+ // A see-through exact fill is measured as it shows on the surface.
1925
+ const o = t.onFor(fillWord, m, solid(used, m, f.id));
1534
1926
  const what = exactFill[m]
1535
- ? `your exact ${names.fill} (${used})`
1536
- : `${names.fill} (shade ${fill[m]?.stop})`;
1927
+ ? `your exact ${names.fill} (${used}${alphaOf(used) < 1 ? `, as it shows: ${solid(used, m, f.id)}` : ''})`
1928
+ : `${names.fill} (shade ${shade(Number(fill[m]?.stop))})`;
1537
1929
  const moved = o.on !== o.first;
1538
1930
  if (reports(names.on))
1539
1931
  checks.push({
@@ -1563,7 +1955,7 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
1563
1955
  // the exact color, the dial's or the token's.
1564
1956
  if (modes.includes('light') && has(names.fill)) {
1565
1957
  const used = exactFill.light ?? /** @type {StopRef} */ (fill.light).color;
1566
- const p = t.page(used, 'light', f.id);
1958
+ const p = t.page(solid(used, 'light', f.id), 'light', f.id);
1567
1959
  if (p < NON_TEXT)
1568
1960
  checks.push({
1569
1961
  token: names.fill,
@@ -1580,66 +1972,42 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
1580
1972
  });
1581
1973
  }
1582
1974
 
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.
1975
+ // The tint: the official stop, never the fill's own shade, see-through
1976
+ // or not. Secondary text on the parts that sit on the accent tint is
1977
+ // lifted instead, as the official neutral theme lifts it (`lift`).
1590
1978
  const muted = each(m => {
1591
- const i = m === 'light' ? 0 : 1;
1979
+ const i = side(m);
1592
1980
  const spec = word ? STATUS_MUTED[i] : ACCENT_MUTED[i];
1593
1981
  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);
1982
+ // Nearest the official stop first, both ways; on a tie (a layout
1983
+ // without that stop) lighter first in light, darker in dark.
1984
+ const usual = i === 0 ? 1 : -1;
1985
+ const order = [...stops].sort(
1986
+ (a, b) =>
1987
+ Math.abs(a - s) - Math.abs(b - s) ||
1988
+ (Math.sign(b - a) === usual ? 1 : -1),
1989
+ );
1990
+ const away = order.filter(x => x !== fill[m]?.stop);
1991
+ return ref(f.id, m, away[0] ?? order[0], alpha);
1636
1992
  });
1637
1993
  put(names.muted, f.id, muted);
1638
1994
  /** The tint the theme really shows: an exact setting wins. @param {Mode} m */
1639
1995
  const mutedSeen = m => {
1640
- const own = exactOf(names.muted, m);
1996
+ const own = rawOf(names.muted, m);
1641
1997
  return own
1642
- ? [/** @type {[string, string]} */ ([`your exact ${names.muted}`, own])]
1998
+ ? surfaces(m, f.id).map(
1999
+ ([n, bg]) =>
2000
+ /** @type {[string, string]} */ ([
2001
+ `your exact ${names.muted} over ${n}`,
2002
+ hex(
2003
+ compositeOver(
2004
+ /** @type {[number, number, number]} */ (parseColor(own)),
2005
+ alphaOf(own),
2006
+ /** @type {[number, number, number]} */ (parseColor(bg)),
2007
+ ),
2008
+ ),
2009
+ ]),
2010
+ )
1643
2011
  : over(
1644
2012
  names.muted,
1645
2013
  /** @type {StopRef} */ (muted[m]),
@@ -1652,7 +2020,7 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
1652
2020
  names.text,
1653
2021
  f.id,
1654
2022
  m,
1655
- at(TEXT_STOP[m === 'light' ? 0 : 1]),
2023
+ at(TEXT_STOP[side(m)]),
1656
2024
  [...surfaces(m, f.id), ...mutedSeen(m)],
1657
2025
  TEXT,
1658
2026
  ),
@@ -1665,14 +2033,7 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
1665
2033
  onMuted,
1666
2034
  f.id,
1667
2035
  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
- ),
2036
+ pick(onMuted, f.id, m, at(ON_MUTED[side(m)]), mutedSeen(m), TEXT),
1676
2037
  ),
1677
2038
  );
1678
2039
  }
@@ -1680,7 +2041,7 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
1680
2041
  put(
1681
2042
  names.border,
1682
2043
  f.id,
1683
- each(m => ref(f.id, m, at(BORDER[m === 'light' ? 0 : 1]))),
2044
+ each(m => ref(f.id, m, at(BORDER[side(m)]))),
1684
2045
  );
1685
2046
  // The focus ring follows the fill; with an exact fill it keeps
1686
2047
  // following that (Core's ring reads --color-accent).
@@ -1702,24 +2063,189 @@ export function paletteMapping(cwd, slug, data, base, tokenDefaults) {
1702
2063
  );
1703
2064
  }
1704
2065
  }
2066
+
2067
+ // Secondary text on the parts the official neutral theme lifts it on
2068
+ // (LIFT_PARTS), lifted the same way, for every accent: for each
2069
+ // background (the accent tint, the neutral track), the gray shade
2070
+ // nearest the secondary text's own that reads at 4.5:1 on it and on it
2071
+ // under a hover, over every surface. The grays are the neutral color's,
2072
+ // else a gray ramp the generator grows from the base theme's own
2073
+ // secondary text (written as colors, not shades of the palette). The
2074
+ // tint stays at its official stop. A mode where the theme sets
2075
+ // secondary text exactly takes that value instead, as written.
2076
+ /** @type {Record<string, Partial<Record<Mode, StopRef>>> | null} */
2077
+ let lift = null;
2078
+ {
2079
+ /** @param {Mode} m @param {string} token */
2080
+ const valueOf = (m, token) => {
2081
+ const v =
2082
+ rawOf(token, m) ?? tokens[token]?.[m].color ?? base?.[m]?.[token];
2083
+ return v && parseColor(v) ? v : null;
2084
+ };
2085
+ /** The secondary text a mode starts from. @param {Mode} m */
2086
+ const startText = m => {
2087
+ const v =
2088
+ tokens['--color-text-secondary']?.[m].color ??
2089
+ base?.[m]?.['--color-text-secondary'];
2090
+ return v && parseColor(v)
2091
+ ? hex(/** @type {number[]} */ (parseColor(v)))
2092
+ : null;
2093
+ };
2094
+ /**
2095
+ * The gray ramp of a mode, and whether its shades are the palette's
2096
+ * neutral ones (else plain colors).
2097
+ * @param {Mode} m
2098
+ * @returns {{ramp: Record<string, string>, palette: boolean} | null}
2099
+ */
2100
+ const grays = m => {
2101
+ if (neutral)
2102
+ return {
2103
+ ramp: /** @type {any} */ (candidate.palette.neutral)[m],
2104
+ palette: true,
2105
+ };
2106
+ const seed = startText(m);
2107
+ if (!seed) return null;
2108
+ try {
2109
+ const g = generateTonalPalette({
2110
+ modeStrategy: m === 'light' ? 'light-only' : 'dark-only',
2111
+ neutralProfile: 'custom',
2112
+ families: [{id: 'gray', seed, kind: 'neutral'}],
2113
+ });
2114
+ return {ramp: /** @type {any} */ (g.palette.gray)[m], palette: false};
2115
+ } catch {
2116
+ return null;
2117
+ }
2118
+ };
2119
+ /**
2120
+ * A color drawn over each of `under`, as the eye sees it.
2121
+ * @param {string} name @param {string} color @param {Array<[string, string]>} under
2122
+ * @returns {Array<[string, string]>}
2123
+ */
2124
+ const drawn = (name, color, under) => {
2125
+ const top = /** @type {[number, number, number]} */ (parseColor(color));
2126
+ const a = alphaOf(color);
2127
+ return under.map(([n, c]) => [
2128
+ `${name} over ${n}`,
2129
+ hex(
2130
+ compositeOver(
2131
+ top,
2132
+ a,
2133
+ /** @type {[number, number, number]} */ (parseColor(c)),
2134
+ ),
2135
+ ),
2136
+ ]);
2137
+ };
2138
+ /** @type {Record<string, Partial<Record<Mode, StopRef>>>} */
2139
+ const found = {};
2140
+ for (const ground of new Set(LIFT_PARTS.map(([, , g]) => g))) {
2141
+ const {what, parts} = LIFT_GROUNDS[ground];
2142
+ /** @type {Partial<Record<Mode, StopRef>>} */
2143
+ const byMode = {};
2144
+ for (const m of modes) {
2145
+ const own = rawOf('--color-text-secondary', m);
2146
+ if (own) {
2147
+ byMode[m] = {stop: 0, color: own, family: 'literal'};
2148
+ continue;
2149
+ }
2150
+ const fillColor = valueOf(m, ground);
2151
+ const g = grays(m);
2152
+ const text = startText(m);
2153
+ if (!fillColor || !g || !text) break;
2154
+ const seen = drawn(what, fillColor, surfaces(m, 'neutral'));
2155
+ const hover = valueOf(m, '--color-overlay-hover');
2156
+ const on = [
2157
+ ...seen,
2158
+ ...(hover && alphaOf(hover) > 0
2159
+ ? drawn('a hover', hover, seen).map(
2160
+ ([n, c]) =>
2161
+ /** @type {[string, string]} */ ([
2162
+ n.replace(/^a hover over (.*)$/, '$1 under a hover'),
2163
+ c,
2164
+ ]),
2165
+ )
2166
+ : []),
2167
+ ];
2168
+ const keys = Object.keys(g.ramp)
2169
+ .map(Number)
2170
+ .sort((a, b) => a - b);
2171
+ const start = keys.reduce((x, y) =>
2172
+ perceptualDelta(g.ramp[y], text) < perceptualDelta(g.ramp[x], text)
2173
+ ? y
2174
+ : x,
2175
+ );
2176
+ const scored = keys
2177
+ .sort(
2178
+ (a, b) =>
2179
+ Math.abs(a - start) - Math.abs(b - start) ||
2180
+ (Math.sign(b - a) === TOWARD_CONTRAST[m] ? 1 : -1),
2181
+ )
2182
+ .map(stop => ({
2183
+ stop,
2184
+ r: Math.min(...on.map(([, bg]) => contrast(g.ramp[stop], bg))),
2185
+ }));
2186
+ const b =
2187
+ scored.find(x => x.r >= TEXT) ??
2188
+ scored.reduce((x, y) => (y.r > x.r ? y : x));
2189
+ byMode[m] = g.palette
2190
+ ? ref('neutral', m, b.stop)
2191
+ : {stop: b.stop, color: g.ramp[b.stop], family: 'literal'};
2192
+ const moved =
2193
+ hex(/** @type {number[]} */ (parseColor(g.ramp[b.stop]))) !== text;
2194
+ if (b.r < TEXT || moved)
2195
+ checks.push({
2196
+ token: '--color-text-secondary',
2197
+ mode: m,
2198
+ stop: b.stop,
2199
+ preferred: start,
2200
+ against: `${what} over the surfaces`,
2201
+ ratio: round(b.r),
2202
+ needs: TEXT,
2203
+ pass: b.r >= TEXT,
2204
+ dials: ['accent', 'neutral'],
2205
+ note:
2206
+ b.r >= TEXT
2207
+ ? `--color-text-secondary on ${parts} uses ${g.ramp[b.stop]} in ${m}, not ${text}, so it reads at ${round(b.r)}:1 on ${what} and under a hover, as the official theme lifts it`
2208
+ : `--color-text-secondary on ${parts} reads at only ${round(b.r)}:1 in ${m} on ${what} even at ${g.ramp[b.stop]}, the most contrasting gray (needs ${TEXT}:1): pick another accent or neutral, or set --color-text-secondary on those parts exactly`,
2209
+ });
2210
+ }
2211
+ if (modes.every(m => byMode[m])) found[ground] = byMode;
2212
+ }
2213
+ if (Object.keys(found).length) lift = found;
2214
+ }
2215
+
1705
2216
  return {
1706
2217
  candidate,
1707
2218
  families: fams,
1708
2219
  tokens,
1709
- contrast: checks,
2220
+ contrast: checks.filter(c => c.note !== ''),
2221
+ lift,
1710
2222
  vibrancy: config.vibrancy ?? VIBRANCY_DEFAULT,
1711
2223
  exact,
1712
2224
  notes: [
1713
2225
  ...plan.notes,
1714
2226
  ...(paletteEdited(cwd, slug)
1715
2227
  ? [
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`,
2228
+ `${paletteFiles(slug).palette} was edited by hand, but the theme never reads it: it reads ${paletteFiles(slug).refs}, which the editor writes from the generator, so the edit does not show. The next color change asks whether to keep or discard it`,
1717
2229
  ]
1718
2230
  : []),
1719
2231
  ],
1720
2232
  };
1721
2233
  }
1722
2234
 
2235
+ /**
2236
+ * The color dial whose generated colors a token belongs to, or null: an
2237
+ * exact setting of it changes what that dial's mapping picks around it.
2238
+ * @param {string} token
2239
+ * @returns {string | null}
2240
+ */
2241
+ export function paletteDialOf(token) {
2242
+ if (!PALETTE_TOKENS.has(token)) return null;
2243
+ if (/accent|^--focus-outline-color$/.test(token)) return 'accent';
2244
+ for (const [dial, word] of Object.entries(STATUS_TOKEN))
2245
+ if (new RegExp(`-${word}(-muted)?$`).test(token)) return dial;
2246
+ return 'neutral';
2247
+ }
2248
+
1723
2249
  /** Every token a color dial can point at a generated shade. */
1724
2250
  export const PALETTE_TOKENS = new Set([
1725
2251
  ...Object.keys(NEUTRAL_STOPS),
@@ -1760,6 +2286,10 @@ export function mappingRows(dial) {
1760
2286
  `${t}: light shade ${l} at opacity ${la}, dark shade ${d} at opacity ${da}`,
1761
2287
  ),
1762
2288
  "--color-background-body: the base theme's page color, so a tinted gray never tints the page",
2289
+ ...Object.values(LIFT_GROUNDS).map(
2290
+ g =>
2291
+ `--color-text-secondary on ${g.parts}: the shade nearest the secondary text's that reads at ${TEXT}:1 on ${g.what} and under a hover, as the official theme lifts it`,
2292
+ ),
1763
2293
  ];
1764
2294
  const word = dial === 'accent' ? null : STATUS_TOKEN[dial];
1765
2295
  if (dial !== 'accent' && !word) return [];
@@ -1775,7 +2305,7 @@ export function mappingRows(dial) {
1775
2305
  `${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
2306
  word
1777
2307
  ? `--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`,
2308
+ : `--color-accent-muted: light shade ${ACCENT_MUTED[0]}, dark shade ${ACCENT_MUTED[1]}, as the official neutral theme maps it, never the fill's own shade; secondary text on the parts that sit on it (selected items and rows, a dropzone, numbered citations) is lifted instead, to the gray nearest it that reads at ${TEXT}:1 on the tint and under a hover: the neutral color's shades, else grays grown from the base theme's own secondary text`,
1779
2309
  ];
1780
2310
  if (word)
1781
2311
  rows.push(
@@ -1826,8 +2356,8 @@ export function paletteNotes(pal, dial, slug, modes = ['light', 'dark']) {
1826
2356
  main[m].exact
1827
2357
  ? m === 'dark' && modes.length > 1
1828
2358
  ? '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}`;
2359
+ : `your exact color (${main[m].color}, ${dial} shade ${shade(main[m].stop)}) in ${m}`
2360
+ : `${dial} shade ${shade(main[m].stop)} (${main[m].color}) in ${m}`;
1831
2361
  notes.push(`${token} uses ${modes.map(part).join(' and ')}`);
1832
2362
  }
1833
2363
  const given = pal.families.find(x => x.dial === dial);
@@ -1836,17 +2366,18 @@ export function paletteNotes(pal, dial, slug, modes = ['light', 'dark']) {
1836
2366
  `your ${dial} ${given.value} is outside the colors every screen shows (sRGB), so the nearest one, ${given.seed}, is used`,
1837
2367
  );
1838
2368
  for (const c of pal.contrast) {
1839
- if (pal.tokens[c.token]?.family !== dial) continue;
2369
+ if (pal.tokens[c.token]?.family !== dial && !c.dials?.includes(dial))
2370
+ continue;
1840
2371
  // A theme with one mode never shows the other one's shades.
1841
2372
  if (!modes.includes(c.mode)) continue;
1842
2373
  if (c.note) notes.push(c.note);
1843
2374
  else if (!c.pass)
1844
2375
  notes.push(
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`,
2376
+ `${c.token} reads at only ${c.ratio}:1 in ${c.mode} on ${c.against} (needs ${c.needs}:1) even at shade ${shade(c.stop)}, the most contrasting one: pick a lighter or darker ${dial}, or set ${c.token} exactly`,
1846
2377
  );
1847
2378
  else if (c.stop !== c.preferred)
1848
2379
  notes.push(
1849
- `${c.token} uses shade ${c.stop} in ${c.mode}, not ${c.preferred}, so it reads at ${c.ratio}:1 on ${c.against}`,
2380
+ `${c.token} uses shade ${shade(c.stop)} in ${c.mode}, not ${shade(c.preferred)}, so it reads at ${c.ratio}:1 on ${c.against}`,
1850
2381
  );
1851
2382
  }
1852
2383
  notes.push(