@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
@@ -12,6 +12,8 @@
12
12
 
13
13
  import {createHash} from 'node:crypto';
14
14
  import * as fs from 'node:fs';
15
+ import postcss from 'postcss';
16
+ import {createRequire} from 'node:module';
15
17
  import * as path from 'node:path';
16
18
  import {pathToFileURL} from 'node:url';
17
19
  import {cliVersion} from '../../foundation/release/run-context.mjs';
@@ -43,21 +45,28 @@ import {
43
45
  compositeOver,
44
46
  isColorValue,
45
47
  isSafeValue,
46
- isSize,
47
48
  parseColor,
48
49
  ratio,
50
+ splitTop,
49
51
  } from './_color.mjs';
50
52
  import {
51
53
  PALETTE_DIALS,
52
54
  assertNoPlaceholder,
55
+ LIFT_PARTS,
56
+ modesOf,
57
+ paletteFiles,
53
58
  paletteImport,
54
59
  paletteMapping,
55
60
  syncPalette,
56
61
  syncPaletteRefs,
62
+ refuseIfLockLost,
63
+ lockHeld,
64
+ removeEmptyFolder,
57
65
  writeWhole,
58
66
  } from './_palette.mjs';
59
- import {MODAL} from './_compiler.mjs';
67
+ import {MODAL, isColorToken} from './_compiler.mjs';
60
68
  import {baseResolved, baseThemeFile} from './_project.mjs';
69
+ import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
61
70
 
62
71
  /**
63
72
  * One setting the CLI owns.
@@ -85,17 +94,49 @@ import {baseResolved, baseThemeFile} from './_project.mjs';
85
94
  * @property {string} [palette] - The hash of the palette.config.json the editor last wrote.
86
95
  */
87
96
 
88
- /** @typedef {{project: import('./_project.mjs').ThemeProject, C: import('./_compiler.mjs').Compiler, unchecked?: string | null, wrote?: Map<string, string | null>, base?: {light: Record<string, string>, dark: Record<string, string>}}} Ctx */
97
+ /** What lifted secondary text sits on: the contrast check measures it there. */
98
+ const LIFT_GROUND_TOKENS = new Set(LIFT_PARTS.map(([, , g]) => g));
99
+
100
+ /** @typedef {{project: import('./_project.mjs').ThemeProject, C: import('./_compiler.mjs').Compiler, unchecked?: string | null, uncheckedCode?: string | null, wrote?: Map<string, string | null>, base?: {light: Record<string, string>, dark: Record<string, string>, components?: Record<string, any>}, keepStops?: Record<string, Record<'light' | 'dark', {family: string, stop: number, alpha?: string}>> | null, keepRadii?: Record<string, string> | null}} Ctx */
89
101
  /** @typedef {import('./_parts.mjs').PaintSide} PaintSide */
90
102
  /** @typedef {import('./_parts.mjs').TextPair} TextPair */
91
103
 
92
104
  /** What a theme name may be, in words. */
93
105
  export const NAME_RULE =
94
- 'lowercase letters, digits and dashes, starting with a letter, 64 characters at most';
106
+ 'lowercase letters, digits and dashes, starting with a letter, 64 characters at most, and not a name Windows reserves (con, prn, aux, nul, com1-com9, lpt1-lpt9)';
95
107
 
96
108
  /** A theme name: lowercase letters, digits and dashes, starting with a letter, 64 characters at most. @param {string} s */
97
109
  export const slugOk = s =>
98
- typeof s === 'string' && s.length <= 64 && /^[a-z][a-z0-9-]*$/.test(s);
110
+ typeof s === 'string' &&
111
+ s.length <= 64 &&
112
+ /^[a-z][a-z0-9-]*$/.test(s) &&
113
+ !windowsReserved(s);
114
+
115
+ /**
116
+ * A name Windows reserves for a device (con, nul, com1…): a folder named
117
+ * so cannot be checked out there.
118
+ * @param {string} s
119
+ */
120
+ export const windowsReserved = s =>
121
+ /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(s);
122
+ /**
123
+ * The theme name closest to what was typed: spaces and accents dropped,
124
+ * lower case, anything else a dash.
125
+ * @param {unknown} name
126
+ */
127
+ export const slugFor = name =>
128
+ String(name ?? '')
129
+ .trim()
130
+ .normalize('NFKD')
131
+ .replace(/[\u0300-\u036f]/g, '')
132
+ .toLowerCase()
133
+ .replace(/[^a-z0-9-]+/g, '-')
134
+ .replace(/^[^a-z]+/, '')
135
+ .replace(/-+$/, '')
136
+ .slice(0, 64)
137
+ // A device name Windows reserves gets a suffix.
138
+ .replace(/^.+$/, w => (windowsReserved(w) ? `${w}-theme` : w)) ||
139
+ 'my-theme';
99
140
  /** @param {string} s */
100
141
  export const kebab = s =>
101
142
  s.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
@@ -106,9 +147,6 @@ export const kebab = s =>
106
147
  */
107
148
  export const camel = s =>
108
149
  s.replace(/-+([a-z0-9])?/g, (_, c) => (c ? c.toUpperCase() : ''));
109
- /** Quote a value for a suggested command. @param {unknown} v */
110
- export const q = v =>
111
- /[\s"#(]/.test(String(v)) ? `"${String(v).replace(/"/g, '\\"')}"` : String(v);
112
150
 
113
151
  /**
114
152
  * The files of one theme, absolute.
@@ -133,6 +171,36 @@ export function themeFiles(cwd, slug) {
133
171
  };
134
172
  }
135
173
 
174
+ /**
175
+ * The themes the editor made in the app (a settings file of its own), by
176
+ * name, or with `changed` the one an editor command changed last first: the
177
+ * undo history is written only by an editor command, so its time is the
178
+ * last change made there.
179
+ * @param {string} cwd
180
+ * @param {'name' | 'changed'} [order]
181
+ * @returns {string[]}
182
+ */
183
+ export function editedThemes(cwd, order = 'name') {
184
+ const root = path.join(cwd, 'themes');
185
+ if (!fs.existsSync(root)) return [];
186
+ const names = fs
187
+ .readdirSync(root)
188
+ .filter(d => fs.existsSync(themeFiles(cwd, d).settings))
189
+ .sort();
190
+ if (order === 'name') return names;
191
+ const when = (/** @type {string} */ d) => {
192
+ const f = themeFiles(cwd, d);
193
+ const t =
194
+ [f.history, f.settingsTs, f.settings].find(x => fs.existsSync(x)) ??
195
+ f.settings;
196
+ return fs.statSync(t).mtimeMs;
197
+ };
198
+ return names
199
+ .map(d => ({d, t: when(d)}))
200
+ .sort((a, b) => b.t - a.t || a.d.localeCompare(b.d))
201
+ .map(x => x.d);
202
+ }
203
+
136
204
  /** A path as the person sees it: relative to cwd. @param {string} cwd @param {string} f */
137
205
  export const shown = (cwd, f) =>
138
206
  path.relative(cwd, f).split(path.sep).join('/');
@@ -195,27 +263,58 @@ export function refuse(code, message, extra = {}) {
195
263
  * The settings of a theme, or a refusal naming the command that makes it.
196
264
  * @param {string} cwd
197
265
  * @param {string} slug
198
- * @param {string} [skip] the thing a command changes or removes: its value
199
- * is not checked, so a value made under looser rules can be fixed
266
+ * @param {string | Partial<Setting>} [skip] the thing (or the one setting)
267
+ * a command changes or removes: its value is not checked, so a value made
268
+ * under looser rules can be fixed
200
269
  * @returns {ThemeData}
201
270
  */
202
- export function loadTheme(cwd, slug, skip = '') {
271
+ export function loadTheme(
272
+ cwd,
273
+ slug,
274
+ skip = /** @type {string | Partial<Setting>} */ (''),
275
+ ) {
203
276
  if (!slugOk(slug)) {
204
277
  // A path or a capital letter typed for a theme that exists names it.
278
+ // A file name typed for the theme (t.theme.ts, Brand.settings.json)
279
+ // names the theme.
205
280
  const plain = String(slug ?? '')
281
+ .trim()
206
282
  .toLowerCase()
207
283
  .replace(/^.*themes[\\/]/, '')
208
- .replace(/[\\/].*$/, '');
209
- const same =
210
- slugOk(plain) && fs.existsSync(themeFiles(cwd, plain).settings)
211
- ? plain
212
- : null;
284
+ .replace(/[\\/].*$/, '')
285
+ .replace(
286
+ /\.(theme\.ts|settings\.(json|ts)|history\.json|css\.d\.ts|d\.ts|css|js|ts)$/,
287
+ '',
288
+ );
289
+ const fixed = slugFor(plain);
290
+ const same = fs.existsSync(themeFiles(cwd, fixed).settings) ? fixed : null;
291
+ // A list where one theme goes (t,u or "t;u"): one theme at a time,
292
+ // each that exists named; never a new theme made of the list. A name
293
+ // with spaces ("My Theme") is one name: its theme, found above, wins.
294
+ const words = String(slug ?? '')
295
+ .split(/\s*[,;|]\s*/)
296
+ .map(w => slugFor(w.trim()))
297
+ .filter(Boolean);
298
+ if (!same && words.length > 1) {
299
+ const existing = words.filter(
300
+ w => slugOk(w) && fs.existsSync(themeFiles(cwd, w).settings),
301
+ );
302
+ refuse(
303
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
304
+ `"${String(slug ?? '').slice(0, 80)}" names more than one theme; a command takes one theme at a time.`,
305
+ {
306
+ run: existing.length
307
+ ? existing.map(w => `${P} show ${w}`)
308
+ : [`${P} new ${words[0]}`],
309
+ },
310
+ );
311
+ }
213
312
  refuse(
214
313
  ERROR_CODES.ERR_INVALID_ARGUMENT,
215
314
  `"${String(slug ?? '').slice(0, 80)}" is not a theme name (${NAME_RULE}).`,
216
315
  same
217
316
  ? {didYouMean: [same], run: [`${P} show ${same}`]}
218
- : {run: [`${P} new my-theme`]},
317
+ : {run: [`${P} new ${fixed}`]},
219
318
  );
220
319
  }
221
320
  const f = themeFiles(cwd, slug);
@@ -231,6 +330,37 @@ export function loadTheme(cwd, slug, skip = '') {
231
330
  .replace(/^.*themes[\\/]/, '')
232
331
  .replace(/[\\/].*$/, '');
233
332
  const same = have.includes(plain) ? plain : null;
333
+ // A theme written by hand, ejected or built in: not one the editor
334
+ // made, and `new` with its name would be refused.
335
+ const other = [
336
+ [f.dir, `themes/${slug}`],
337
+ [path.join(cwd, 'src', 'themes', slug), `src/themes/${slug}`],
338
+ ].find(([d]) => fs.existsSync(d));
339
+ // A `new` that was stopped part way left its marker, or the settings
340
+ // were removed beside the editor's generated module: `new` makes the
341
+ // theme again and keeps every file it did not write.
342
+ // A marker beside a history is from a `new` that finished (it writes
343
+ // none): the settings were lost after.
344
+ const stopped =
345
+ fs.existsSync(path.join(f.dir, NEW_MARKER)) && !fs.existsSync(f.history);
346
+ if (!same && (stopped || madeByEditor(f.settingsTs)))
347
+ refuse(
348
+ ERROR_CODES.ERR_UNKNOWN_THEME,
349
+ stopped
350
+ ? `themes/${slug} was left by a \`new\` that was stopped part way, so it has no settings yet. Run new again to finish it; files you added there are kept.`
351
+ : `themes/${slug} has lost its settings (${slug}.settings.json is gone), but the editor made it. Run new to make it again: your own files there are kept${fs.existsSync(f.history) ? `, and \`undo ${slug}\` then steps back to the earlier settings` : ''}.`,
352
+ {run: [`${P} new ${slug}`]},
353
+ );
354
+ if (!same && (other || LIKE.includes(slug)))
355
+ refuse(
356
+ ERROR_CODES.ERR_UNKNOWN_THEME,
357
+ `${other ? `${other[1]} is a theme the editor did not make (written by hand, or ejected)` : `${slug} is a built-in theme`}, so the editor does not change it. Make an editor theme with its own name instead${LIKE.includes(slug) ? `, on top of ${slug}` : ''}.`,
358
+ {
359
+ run: [
360
+ `${P} new my-${slug}${LIKE.includes(slug) ? ` --like ${slug}` : ''}`,
361
+ ],
362
+ },
363
+ );
234
364
  refuse(
235
365
  ERROR_CODES.ERR_UNKNOWN_THEME,
236
366
  `There is no theme "${slug}" made by this command (no themes/${slug}/${slug}.settings.json).`,
@@ -248,29 +378,81 @@ export function loadTheme(cwd, slug, skip = '') {
248
378
  text: `, or step back to the settings before the last change with ${P} undo ${slug} (the last change is then lost)`,
249
379
  run: [{name: `${P} undo ${slug}`, reason: 'do this instead'}],
250
380
  }
251
- : {text: '; there is no earlier step to go back to', run: []};
381
+ : {
382
+ text: `; or make the theme again with ${P} new ${slug}, which keeps the damaged file beside it and every file of yours`,
383
+ run: [{name: `${P} new ${slug}`, reason: 'do this instead'}],
384
+ };
252
385
  /** @type {any} */
253
386
  let data;
254
387
  try {
255
388
  data = JSON.parse(
256
389
  fs.readFileSync(f.settings, 'utf8').replace(/^\uFEFF/, ''),
257
390
  );
258
- } catch (e) {
391
+ } catch {
259
392
  throw new AstryxError(
260
- `themes/${slug}/${slug}.settings.json is not valid JSON (${e instanceof Error ? e.message : String(e)}). Fix it by hand${recover.text}.`,
393
+ `themes/${slug}/${slug}.settings.json is not valid JSON. Fix it by hand${recover.text}.`,
261
394
  recover.run,
262
395
  ERROR_CODES.ERR_THEME_INVALID,
263
396
  );
264
397
  }
398
+ // Valid JSON of the wrong shape ([], {}, settings: null) is damage like
399
+ // invalid JSON: `new` makes the theme again, keeping the file aside.
400
+ if (!settingsShapeOk(data))
401
+ throw new AstryxError(
402
+ `themes/${slug}/${slug}.settings.json is damaged: ${settingsProblem(data) ?? 'it is not a settings object'}. Fix it by hand${steps ? `, step back to the settings before the last change with ${P} undo ${slug},` : ''} or make the theme again with ${P} new ${slug}, which keeps the damaged file beside it and every file of yours. Nothing was changed.`,
403
+ [
404
+ ...recover.run.filter(r => !/ new /.test(r.name)),
405
+ {name: `${P} new ${slug}`, reason: 'do this instead'},
406
+ ],
407
+ ERROR_CODES.ERR_THEME_INVALID,
408
+ );
265
409
  const problem = settingsProblem(data, skip);
266
410
  // A value made under looser rules is not damage: the command that
267
- // changes or removes that setting still works.
411
+ // changes or removes that setting still works, with the other bad ones
412
+ // left out of the build, so each listed fix runs on its own.
413
+ const all = problem ? badSettings(data) : [];
414
+ if (
415
+ problem &&
416
+ skip &&
417
+ all.some(s => skips(s, skip)) &&
418
+ !settingsProblem({
419
+ ...data,
420
+ settings: data.settings.filter(
421
+ (/** @type {any} */ s) => !all.includes(s),
422
+ ),
423
+ })
424
+ )
425
+ return data;
426
+ if (
427
+ problem &&
428
+ all.length &&
429
+ !settingsProblem({
430
+ ...data,
431
+ settings: data.settings.filter(
432
+ (/** @type {any} */ s) => !all.includes(s),
433
+ ),
434
+ }) &&
435
+ all.length > 1
436
+ )
437
+ throw new AstryxError(
438
+ `themes/${slug}/${slug}.settings.json holds ${all.length} settings the editor no longer accepts: ${all
439
+ .slice(0, 6)
440
+ .map(s => valueProblem(s))
441
+ .join(
442
+ '; ',
443
+ )}${all.length > 6 ? `; and ${all.length - 6} more` : ''}. Remove or change each; nothing else needs to change. Nothing was changed.`,
444
+ all.slice(0, 6).map(s => ({
445
+ name: `${P} undo ${slug} ${undoArgs(s)}`,
446
+ reason: 'do this instead',
447
+ })),
448
+ ERROR_CODES.ERR_THEME_INVALID,
449
+ );
268
450
  const bad = problem ? badSetting(data) : null;
269
451
  if (problem && bad && settingsProblem(data, bad.thing) !== problem) {
270
452
  // A value it takes, for a dial; a color for a color token.
271
453
  const example = DIALS[bad.thing]
272
454
  ? DIALS[bad.thing].values.split('|').find(w => !w.startsWith('<'))
273
- : bad.thing.startsWith('--color-')
455
+ : isColorToken(bad.thing)
274
456
  ? '#1f2937'
275
457
  : null;
276
458
  throw new AstryxError(
@@ -280,7 +462,7 @@ export function loadTheme(cwd, slug, skip = '') {
280
462
  ...(example
281
463
  ? [
282
464
  {
283
- name: `${P} set ${slug} ${undoArgs(bad).replace(bad.thing, `${bad.thing} ${q(example)}`)}`,
465
+ name: `${P} set ${slug} ${undoArgs(bad).replace(bad.thing, `${bad.thing} ${quoteCommandArgument(example)}`)}`,
284
466
  reason: 'or give it a value it takes',
285
467
  },
286
468
  ]
@@ -289,10 +471,18 @@ export function loadTheme(cwd, slug, skip = '') {
289
471
  ERROR_CODES.ERR_THEME_INVALID,
290
472
  );
291
473
  }
474
+ // A bad mode or base is fixed by setting it.
475
+ const fieldFix = /^(it has no mode|mode ")/.test(problem ?? '')
476
+ ? `${P} set ${slug} mode both`
477
+ : /^base "/.test(problem ?? '')
478
+ ? `${P} set ${slug} base none`
479
+ : null;
292
480
  if (problem)
293
481
  throw new AstryxError(
294
- `themes/${slug}/${slug}.settings.json: ${problem}. Fix it by hand${recover.text}. Nothing was changed.`,
295
- recover.run,
482
+ `themes/${slug}/${slug}.settings.json: ${problem}. ${fieldFix ? 'Set it again' : `Fix it by hand${recover.text}`}. Nothing was changed.`,
483
+ fieldFix
484
+ ? [{name: fieldFix, reason: 'do this instead'}, ...recover.run]
485
+ : recover.run,
296
486
  ERROR_CODES.ERR_THEME_INVALID,
297
487
  );
298
488
  return data;
@@ -303,50 +493,88 @@ export function loadTheme(cwd, slug, skip = '') {
303
493
  * the same rules `set` checks it by (without the installed Core), so a value
304
494
  * edited by hand never reaches the build.
305
495
  * @param {any} data
306
- * @param {string} [skip] a thing whose value is not checked (the one a
496
+ * @param {string | Partial<Setting>} [skip] a thing or setting whose value is not checked (the one a
307
497
  * command is about to change or remove)
308
498
  * @returns {string | null}
309
499
  */
310
- export function settingsProblem(data, skip = '') {
500
+ export function settingsProblem(
501
+ data,
502
+ skip = /** @type {string | Partial<Setting>} */ (''),
503
+ ) {
311
504
  if (!data || typeof data !== 'object' || Array.isArray(data))
312
505
  return 'the file is not a settings object';
313
- if (!['both', 'light-only', 'dark-only'].includes(data.mode))
314
- return `mode "${data.mode}" is not both, light-only or dark-only`;
315
- if (data.like != null && !LIKE.includes(data.like))
506
+ // `set <theme> mode` and `set <theme> base` fix their own field.
507
+ const fixing = typeof skip === 'string' ? skip : skip?.thing;
508
+ const field = fixing === 'mode' || fixing === 'base';
509
+ if (!field && !['both', 'light-only', 'dark-only'].includes(data.mode))
510
+ return data.mode == null
511
+ ? 'it has no mode'
512
+ : `mode "${data.mode}" is not both, light-only or dark-only`;
513
+ if (!field && data.like != null && !LIKE.includes(data.like))
316
514
  return `base "${data.like}" is not a built-in theme (${LIKE.join(', ')})`;
317
515
  if (!Array.isArray(data.settings)) return 'settings is not a list';
318
516
  const keys = new Set();
319
517
  for (const s of data.settings) {
320
- if (!s || typeof s.thing !== 'string' || typeof s.value !== 'string')
518
+ // A value or scope that is not text is a bad setting `undo` removes;
519
+ // a setting with no name is damage.
520
+ if (!s || typeof s.thing !== 'string' || !('value' in s))
321
521
  return 'a setting has no thing or value';
322
522
  if (!['dial', 'token', 'property'].includes(s.source))
323
523
  return `${s.thing} has no source (dial, token or property)`;
324
- for (const k of ['on', 'when', 'state'])
325
- if (s[k] != null && typeof s[k] !== 'string')
326
- return `${s.thing} has a ${k} that is not a word`;
327
524
  if (s.mode != null && s.mode !== 'light' && s.mode !== 'dark')
328
525
  return `${s.thing} has mode "${s.mode}"`;
329
526
  const key = keyOf(s);
330
527
  if (keys.has(key)) return `${describe(s)} is listed twice`;
331
528
  keys.add(key);
332
- if (s.thing === skip) continue;
529
+ if (skips(s, skip)) continue;
333
530
  const problem = valueProblem(s);
334
531
  if (problem) return problem;
335
532
  }
336
533
  return null;
337
534
  }
338
535
 
536
+ /**
537
+ * Whether a setting is the one a command changes or removes: by thing, or
538
+ * by the whole identity (part, variant, state, mode) when one is given.
539
+ * @param {any} s
540
+ * @param {string | Partial<Setting> | undefined} skip
541
+ */
542
+ function skips(s, skip) {
543
+ if (!skip) return false;
544
+ if (typeof skip === 'string') return s.thing === skip;
545
+ return (
546
+ s.thing === skip.thing &&
547
+ (s.on ?? '') === (skip.on ?? '') &&
548
+ (s.when ?? '') === (skip.when ?? '') &&
549
+ (s.state ?? '') === (skip.state ?? '') &&
550
+ (s.mode ?? '') === (skip.mode ?? '')
551
+ );
552
+ }
553
+
554
+ /**
555
+ * Every setting whose only problem is its value or scope, each with the
556
+ * command that removes it.
557
+ * @param {any} data
558
+ * @returns {Setting[]}
559
+ */
560
+ export function badSettings(data) {
561
+ return (Array.isArray(data?.settings) ? data.settings : []).filter(
562
+ (/** @type {any} */ s) =>
563
+ s && typeof s.thing === 'string' && valueProblem(s),
564
+ );
565
+ }
566
+
339
567
  /**
340
568
  * The words that name a setting for `undo`.
341
569
  * @param {import('./_settings.mjs').Setting} x
342
570
  */
343
571
  export function undoArgs(x) {
344
572
  return [
345
- x.thing,
346
- ...(x.on ? [`--on ${x.on}`] : []),
347
- ...(x.when ? [`--when ${x.when}`] : []),
348
- ...(x.state ? [`--state ${x.state}`] : []),
349
- ...(x.mode ? [`--mode ${x.mode}`] : []),
573
+ quoteCommandArgument(String(x.thing)),
574
+ ...(x.on ? [`--on ${quoteCommandArgument(String(x.on))}`] : []),
575
+ ...(x.when ? [`--when ${quoteCommandArgument(String(x.when))}`] : []),
576
+ ...(x.state ? [`--state ${quoteCommandArgument(String(x.state))}`] : []),
577
+ ...(x.mode ? [`--mode ${quoteCommandArgument(String(x.mode))}`] : []),
350
578
  ...(x.only ? ['--only'] : []),
351
579
  ].join(' ');
352
580
  }
@@ -382,12 +610,25 @@ export function withoutBadValues(data) {
382
610
  * @param {any} s
383
611
  * @returns {string | null}
384
612
  */
385
- function valueProblem(s) {
613
+ export function valueProblem(s) {
614
+ if (typeof s.value !== 'string')
615
+ return `${s.thing} has a value that is not text (${JSON.stringify(s.value)})`;
616
+ for (const k of ['on', 'when', 'state', 'mode'])
617
+ if (s[k] != null && typeof s[k] !== 'string')
618
+ return `${s.thing} has a ${k} that is not text`;
619
+ const scope = scopeProblem(s);
620
+ if (scope) return scope;
386
621
  {
387
622
  const bad = `${s.thing} "${s.value}"`;
388
- if (!isSafeValue(s.value)) return `${bad} cannot be a CSS value`;
623
+ // A font family name may hold an apostrophe (O'Reilly Sans): Core
624
+ // quotes the family itself.
625
+ const checked =
626
+ s.source === 'dial' && s.thing === 'font'
627
+ ? s.value.replace(/'/g, '')
628
+ : s.value;
629
+ if (!isSafeValue(checked)) return `${bad} cannot be a CSS value`;
389
630
  if (s.source === 'token') {
390
- if (s.mode && !s.thing.startsWith('--color-'))
631
+ if (s.mode && !isColorToken(s.thing))
391
632
  return `${s.thing} is set for ${s.mode} only, but only colors differ by mode`;
392
633
  if (new RegExp(`var\\(\\s*${s.thing}\\s*[,)]`, 'i').test(s.value))
393
634
  return `${bad} reads itself`;
@@ -398,7 +639,7 @@ function valueProblem(s) {
398
639
  const words = d.values.split('|').filter(w => !w.startsWith('<'));
399
640
  const ok =
400
641
  s.thing === 'corners'
401
- ? words.includes(s.value) || isSize(s.value, '--radius')
642
+ ? words.includes(s.value) || /^\d+(\.\d+)?px$/.test(s.value)
402
643
  : s.thing === 'text-size'
403
644
  ? words.includes(s.value) ||
404
645
  (/^\d+(\.\d+)?$/.test(s.value) &&
@@ -412,11 +653,29 @@ function valueProblem(s) {
412
653
  ? s.value.trim() !== ''
413
654
  : words.includes(s.value);
414
655
  if (!ok || s.value === 'more' || s.value === 'less')
415
- return `${bad} is not a value ${s.thing} takes (${d.values})`;
656
+ return `${bad} is not a value ${s.thing} takes (${d.values.replace('|more|less', '')})`;
416
657
  }
417
658
  return null;
418
659
  }
419
660
 
661
+ /**
662
+ * What is wrong with where a setting applies, or null: names only, as
663
+ * `set` takes them.
664
+ * @param {any} s
665
+ * @returns {string | null}
666
+ */
667
+ function scopeProblem(s) {
668
+ if (s.on != null && !/^[a-z][a-z0-9-]*$/.test(s.on))
669
+ return `${s.thing} is set on "${s.on}", which is not a part or group name`;
670
+ if (s.state != null && !/^[a-z][a-z-]*$/.test(s.state))
671
+ return `${s.thing} has state "${s.state}", which is not a state name`;
672
+ if (s.when != null && !/^[\w-]+:[\w.-]+$/.test(s.when))
673
+ return `${s.thing} has --when "${s.when}", which is not prop:value`;
674
+ if ((s.when != null || s.state != null) && s.on == null)
675
+ return `${s.thing} has a variant or state but no part`;
676
+ return null;
677
+ }
678
+
420
679
  /** The identity of a setting: a new one with the same identity replaces it. @param {Setting} s */
421
680
  export const keyOf = s =>
422
681
  [
@@ -455,13 +714,20 @@ export function partsOf(ctx, s) {
455
714
  return [s.on];
456
715
  }
457
716
 
458
- /** @param {ThemeData} d @returns {Array<'light' | 'dark'>} */
459
- export const modesOf = d =>
460
- d.mode === 'light-only'
461
- ? ['light']
462
- : d.mode === 'dark-only'
463
- ? ['dark']
464
- : ['light', 'dark'];
717
+ export {modesOf};
718
+
719
+ /**
720
+ * A length in pixels: px as given, rem and em at 16px; null for anything
721
+ * else (a percentage, calc(), a word).
722
+ * @param {string} v
723
+ * @returns {number | null}
724
+ */
725
+ export function lengthPx(v) {
726
+ const m = /^\s*(-?\d+(?:\.\d+)?|-?\.\d+)\s*(px|rem|em)?\s*$/i.exec(String(v));
727
+ if (!m) return null;
728
+ const n = Number(m[1]);
729
+ return (m[2] ?? 'px').toLowerCase() === 'px' ? n : n * 16;
730
+ }
465
731
 
466
732
  /** @param {string} v */
467
733
  export const cornerPx = v =>
@@ -476,7 +742,6 @@ export const textPx = v => TEXT_SIZE.find(([n]) => n === v)?.[1] ?? Number(v);
476
742
  * @returns {{family: string, fallbacks: string, pkg: string | null}}
477
743
  */
478
744
  export function fontOf(value) {
479
- // Core quotes the family itself, so it is stored without quotes.
480
745
  const unquote = (/** @type {string} */ x) => x.replace(/^["']|["']$/g, '');
481
746
  if (FONTS[value])
482
747
  return {
@@ -493,24 +758,46 @@ export function fontOf(value) {
493
758
  f.family.replace(/"/g, '').toLowerCase() ===
494
759
  family.replace(/["']/g, '').toLowerCase(),
495
760
  )?.pkg ?? null;
496
- if (v.includes(',')) {
497
- const parts = v
498
- .split(',')
499
- .map(x => x.trim())
500
- .filter(Boolean);
501
- return {
502
- family: unquote(parts[0]),
503
- fallbacks: parts.slice(1).join(', ') || 'system-ui, sans-serif',
504
- pkg: pkgOf(parts[0]),
505
- };
506
- }
761
+ /** Fallbacks without the family itself, so `system-ui` never repeats. @param {string} family @param {string[]} list */
762
+ const without = (family, list) =>
763
+ list
764
+ .filter(x => unquote(x).toLowerCase() !== family.toLowerCase())
765
+ .map(x => cssFamily(unquote(x), true))
766
+ .join(', ');
767
+ const parts = v
768
+ .split(',')
769
+ .map(x => x.trim())
770
+ .filter(Boolean);
771
+ const family = unquote(parts[0] ?? v);
507
772
  return {
508
- family: unquote(v),
509
- fallbacks: 'system-ui, sans-serif',
510
- pkg: pkgOf(v),
773
+ family: cssFamily(family),
774
+ fallbacks:
775
+ parts.length > 1
776
+ ? without(family, parts.slice(1))
777
+ : without(family, ['system-ui', 'sans-serif']),
778
+ pkg: pkgOf(family),
511
779
  };
512
780
  }
513
781
 
782
+ /**
783
+ * A font family name as CSS reads it. A name that is a sequence of CSS
784
+ * identifiers stays bare; any other is quoted, or the browser drops the
785
+ * whole font (`3Dumb`, `My/Font`, `a.b`). Core quotes a family that has
786
+ * a space itself, so such a name is quoted here only as a fallback
787
+ * (`spaced`), where Core writes the list as given.
788
+ * @param {string} name without quotes
789
+ * @param {boolean} [spaced]
790
+ */
791
+ export function cssFamily(name, spaced = false) {
792
+ const words = name.trim().split(/\s+/);
793
+ const ident = (/** @type {string} */ w) =>
794
+ /^-?(?:[A-Za-z_]|[\u0080-\uffff])(?:[\w-]|[\u0080-\uffff])*$/.test(w) &&
795
+ !w.startsWith('--');
796
+ if (words.every(ident)) return name.trim();
797
+ if (words.length > 1 && !spaced && !/["\\]/.test(name)) return name.trim();
798
+ return `"${name.trim().replace(/["\\]/g, '\\$&')}"`;
799
+ }
800
+
514
801
  /**
515
802
  * What a part reads for a property when the theme does not set it, so a
516
803
  * one-mode component setting keeps the other mode as it was.
@@ -518,8 +805,9 @@ export function fontOf(value) {
518
805
  * @param {string} target
519
806
  * @param {string} prop camelCase or kebab-case
520
807
  * @param {string | undefined} when
808
+ * @param {string} [state] a state (hover): that state's own value
521
809
  */
522
- function partDefault(ctx, target, prop, when) {
810
+ function partDefault(ctx, target, prop, when, state) {
523
811
  const k = kebab(prop);
524
812
  const g = ctx.C.groupOfProp(k === 'background' ? 'background-color' : k);
525
813
  const want = (/** @type {import('./_compiler.mjs').Read} */ x) =>
@@ -528,6 +816,15 @@ function partDefault(ctx, target, prop, when) {
528
816
  );
529
817
  const reads = g ? ctx.C.partReads(target, g).filter(want) : [];
530
818
  const wv = when ? when.replace(':', '=') : null;
819
+ // With a state, that state's own value (for the variant, if named);
820
+ // when the state does not change this property, the plain value is what
821
+ // shows in that state too.
822
+ if (state) {
823
+ const sr = reads.find(x =>
824
+ x.when.some(w => w.includes(`:${state}`) && (!wv || w.includes(wv))),
825
+ );
826
+ if (sr) return `var(${sr.token})`;
827
+ }
531
828
  const r =
532
829
  (wv && reads.find(x => x.when.some(w => w === wv))) ||
533
830
  reads.find(x => x.when.includes('')) ||
@@ -536,6 +833,112 @@ function partDefault(ctx, target, prop, when) {
536
833
  return r ? `var(${r.token})` : null;
537
834
  }
538
835
 
836
+ /** The line that records a generated module's own hash. */
837
+ const SEAL = /^\/\/ Module ([0-9a-f]{16})\.\n/m;
838
+
839
+ /**
840
+ * A generated module with its own hash after its header, so a hand edit to
841
+ * it is told from a module an earlier editor wrote (which has none).
842
+ * @param {string} text
843
+ */
844
+ function sealModule(text) {
845
+ const hash = createHash('sha256').update(text).digest('hex').slice(0, 16);
846
+ return text.replace(
847
+ /^(\/\/ Built from settings [^\n]*\n)/m,
848
+ `$1// Module ${hash}.\n`,
849
+ );
850
+ }
851
+
852
+ /**
853
+ * Whether a generated module is as the editor wrote it: true, false for a
854
+ * hand edit, null for a module with no hash (an earlier editor's).
855
+ * @param {string} text
856
+ * @returns {boolean | null}
857
+ */
858
+ export function moduleUnedited(text) {
859
+ // A checkout that writes CRLF line endings changes no line.
860
+ text = text.replace(/\r\n/g, '\n');
861
+ const seal = SEAL.exec(text);
862
+ if (!seal) return null;
863
+ return (
864
+ createHash('sha256')
865
+ .update(text.replace(SEAL, ''))
866
+ .digest('hex')
867
+ .slice(0, 16) === seal[1]
868
+ );
869
+ }
870
+
871
+ /**
872
+ * The palette stops each token reads in a generated settings module, as
873
+ * written there (`palette.accent.light[85]`, with ` + 'aa'` for a
874
+ * see-through one): `[light, dark]` per token.
875
+ * @param {string} source
876
+ * @returns {Record<string, Record<'light' | 'dark', {family: string, stop: number, alpha?: string}>>}
877
+ */
878
+ export function stopsIn(source) {
879
+ /** @type {Record<string, Record<'light' | 'dark', {family: string, stop: number, alpha?: string}>>} */
880
+ const out = {};
881
+ const one = String.raw`palette(?:\.([a-z][\w]*)|\["([a-z][\w-]*)"\])\.(?:light|dark)\[(\d+(?:\.\d+)?)\](?: \+ '([0-9a-f]{2})')?`;
882
+ const pair = new RegExp(
883
+ String.raw`"(--[\w-]+)": \[\s*${one},\s*${one}\s*\]`,
884
+ 'g',
885
+ );
886
+ // Whether the module lifts secondary text on parts (an earlier editor
887
+ // did not): the key cannot be a token's name.
888
+ out['lifted parts'] = /** @type {any} */ (
889
+ /"components":[\s\S]*"--color-text-secondary"/.test(source)
890
+ );
891
+ for (const m of source.matchAll(pair))
892
+ out[m[1]] = {
893
+ light: {
894
+ family: m[2] ?? m[3],
895
+ stop: Number(m[4]),
896
+ ...(m[5] ? {alpha: m[5]} : {}),
897
+ },
898
+ dark: {
899
+ family: m[6] ?? m[7],
900
+ stop: Number(m[8]),
901
+ ...(m[9] ? {alpha: m[9]} : {}),
902
+ },
903
+ };
904
+ return out;
905
+ }
906
+
907
+ /**
908
+ * The palette mapping with the shades a theme already shows kept, where
909
+ * the palette still has them (see commitTheme).
910
+ * @param {import('./_palette.mjs').PaletteMapping | null} pal
911
+ * @param {ReturnType<typeof stopsIn> | null | undefined} kept
912
+ * @returns {import('./_palette.mjs').PaletteMapping | null}
913
+ */
914
+ function keepShades(pal, kept) {
915
+ if (!pal || !kept) return pal;
916
+ const tokens = {...pal.tokens};
917
+ for (const [k, v] of Object.entries(tokens)) {
918
+ if (k === 'lifted parts') continue;
919
+ const old = kept[k];
920
+ if (!old) continue;
921
+ /** @type {any} */
922
+ const next = {...v};
923
+ for (const m of /** @type {const} */ (['light', 'dark'])) {
924
+ const r = old[m];
925
+ const color = /** @type {any} */ (pal.candidate.palette)[r.family]?.[m]?.[
926
+ r.stop
927
+ ];
928
+ if (typeof color !== 'string') continue;
929
+ next[m] = {
930
+ stop: r.stop,
931
+ color: r.alpha ? `${color}${r.alpha}` : color,
932
+ ...(r.alpha ? {alpha: r.alpha} : {}),
933
+ ...(r.family !== v.family ? {family: r.family} : {}),
934
+ };
935
+ }
936
+ tokens[k] = next;
937
+ }
938
+ // A theme built without lifted text keeps the base theme's own.
939
+ return {...pal, tokens, lift: kept['lifted parts'] ? pal.lift : null};
940
+ }
941
+
539
942
  /**
540
943
  * The settings, as a `defineTheme` object.
541
944
  * @param {Ctx} ctx
@@ -544,6 +947,8 @@ function partDefault(ctx, target, prop, when) {
544
947
  * @returns {any}
545
948
  */
546
949
  export function compileTheme(ctx, data, base) {
950
+ // A setting the editor no longer accepts never reaches the build.
951
+ data = {...data, settings: data.settings.filter(s => !valueProblem(s))};
547
952
  const TOKENS = ctx.project.core.tokenDefaults;
548
953
  // The base theme's type scale, read back from its sizes: base text, and
549
954
  // the ratio (2xl is three steps above base).
@@ -595,7 +1000,7 @@ export function compileTheme(ctx, data, base) {
595
1000
  if (tg?.states.includes(s.state) && s.when == null) b = t[s.state] ??= {};
596
1001
  else if (tg?.states.includes(s.state))
597
1002
  b = t[`${s.when}+${s.state}`] ??= {};
598
- else b = b[`:${s.state}`] ??= {};
1003
+ else b = b[stateKey(s.state)] ??= {};
599
1004
  }
600
1005
  return b;
601
1006
  };
@@ -604,9 +1009,24 @@ export function compileTheme(ctx, data, base) {
604
1009
  const b = block(s, target);
605
1010
  if (s.mode && !modeOnly) {
606
1011
  const prev = b[prop];
607
- const other = prev ?? partDefault(ctx, target, prop, s.when) ?? v;
608
- const split = (/** @type {string} */ x, /** @type {1 | 2} */ side) =>
609
- x.replace(/^light-dark\((.*),\s*(.*)\)$/, `$${side}`);
1012
+ // The other mode keeps exactly what it had: the value set for it, the
1013
+ // part's own, else what the property shows unset (light-dark() takes
1014
+ // colors only, so never inherit).
1015
+ const other =
1016
+ prev ??
1017
+ baseComponent(base, ctx, target, prop, s) ??
1018
+ partDefault(ctx, target, prop, s.when, s.state) ??
1019
+ (s.state
1020
+ ? baseComponent(base, ctx, target, prop, {...s, state: undefined})
1021
+ : null) ??
1022
+ partDefault(ctx, target, prop, s.when) ??
1023
+ (/^background/.test(kebab(prop)) ? 'transparent' : 'currentcolor');
1024
+ // At the top-level comma: a mode's color may hold commas itself.
1025
+ const split = (/** @type {string} */ x, /** @type {1 | 2} */ side) => {
1026
+ const inner = /^light-dark\((.*)\)$/s.exec(x.trim())?.[1];
1027
+ const halves = inner == null ? [] : splitTop(inner, ',');
1028
+ return halves.length === 2 ? halves[side - 1].trim() : x;
1029
+ };
610
1030
  b[prop] =
611
1031
  s.mode === 'light'
612
1032
  ? `light-dark(${v}, ${prev ? split(prev, 2) : other})`
@@ -614,9 +1034,69 @@ export function compileTheme(ctx, data, base) {
614
1034
  } else b[prop] = v;
615
1035
  };
616
1036
  // Palette stops go first, so an exact token setting always wins over them.
617
- const pal = paletteMapping(ctx.project.cwd, data.name, data, base, TOKENS);
1037
+ const pal = keepShades(
1038
+ paletteMapping(ctx.project.cwd, data.name, data, base, TOKENS),
1039
+ ctx.keepStops,
1040
+ );
618
1041
  for (const [k, v] of Object.entries(pal?.tokens ?? {}))
619
1042
  putTok(k, [v.light.color, v.dark.color]);
1043
+ // Secondary text lifted on the parts the official neutral theme lifts it
1044
+ // on, each for what it sits on. It is written into the very block the
1045
+ // base theme lifts it in, so it replaces the base's lift. A setting of it
1046
+ // on the part (no --when or --state) wins there, per mode, so a numbered
1047
+ // citation shows what `--on citation` set.
1048
+ // Without a color dial nothing is lifted, but an exact secondary text
1049
+ // still reaches those parts, and the base theme's own lift stays in the
1050
+ // mode it does not cover.
1051
+ /** @type {Partial<Record<'light' | 'dark', string>>} */
1052
+ const exactText = {};
1053
+ for (const x of data.settings)
1054
+ if (
1055
+ x.source === 'token' &&
1056
+ x.thing === '--color-text-secondary' &&
1057
+ !x.on &&
1058
+ !x.when &&
1059
+ !x.state
1060
+ )
1061
+ for (const m of /** @type {const} */ (['light', 'dark']))
1062
+ if (!x.mode || x.mode === m) exactText[m] = x.value;
1063
+ const blocks =
1064
+ /** @type {{components?: Record<string, any>}} */ (base).components ?? {};
1065
+ for (const [target, key, ground] of pal?.lift || Object.keys(exactText).length
1066
+ ? LIFT_PARTS
1067
+ : []) {
1068
+ /** @type {Partial<Record<'light' | 'dark', {color: string}>> | undefined} */
1069
+ let lift = pal?.lift?.[ground];
1070
+ if (!lift) {
1071
+ const own = blocks[target]?.[key]?.['--color-text-secondary'];
1072
+ const split =
1073
+ typeof own === 'string'
1074
+ ? /^light-dark\((.*),\s*([^,]*)\)$/.exec(own.trim())
1075
+ : null;
1076
+ /** @param {'light' | 'dark'} m */
1077
+ const at = m =>
1078
+ exactText[m] ??
1079
+ (split ? split[m === 'light' ? 1 : 2].trim() : own) ??
1080
+ base[m]['--color-text-secondary'];
1081
+ lift = {light: {color: at('light')}, dark: {color: at('dark')}};
1082
+ }
1083
+ if (!lift || !ctx.project.target.has(target)) continue;
1084
+ /** @type {Partial<Record<'light' | 'dark', {color: string}>>} */
1085
+ const value = {...lift};
1086
+ for (const x of data.settings)
1087
+ if (
1088
+ x.source === 'token' &&
1089
+ x.thing === '--color-text-secondary' &&
1090
+ x.on &&
1091
+ !x.when &&
1092
+ !x.state &&
1093
+ partsOf(ctx, x).includes(target)
1094
+ )
1095
+ for (const m of /** @type {const} */ (['light', 'dark']))
1096
+ if (!x.mode || x.mode === m) value[m] = {color: x.value};
1097
+ ((theme.components[target] ??= {})[key] ??= {})['--color-text-secondary'] =
1098
+ liftValue(value, modeOnly);
1099
+ }
620
1100
  // `headings` owns heading weight and tracking whatever the order: `type`
621
1101
  // sets them only where no `headings` setting does.
622
1102
  const headingsAxis = (/** @type {'weight' | 'tracking'} */ axis) =>
@@ -643,28 +1123,34 @@ export function compileTheme(ctx, data, base) {
643
1123
  const parts = partsOf(ctx, s);
644
1124
  if (s.source === 'dial') {
645
1125
  if (s.thing === 'corners') {
646
- const px = cornerPx(s.value);
647
- const val = (/** @type {number} */ x) =>
648
- px >= 9999 ? '9999px' : `${x}px`;
1126
+ // Past 1000px a radius is fully round: the pill tokens apply.
1127
+ const px = cornerPx(s.value) >= 1000 ? 9999 : cornerPx(s.value);
1128
+ const pill = px >= 9999;
1129
+ const rung = CORNERS.some(([n]) => n === s.value);
1130
+ /** @param {string} token */
1131
+ const derived = token => `${radiusAt(base, s.value, token)}px`;
649
1132
  if (parts.length)
650
- for (const t of parts)
651
- putComp({...s, mode: undefined}, t, 'borderRadius', val(px));
652
- else {
653
- putTok('--radius-element', val(px));
654
- // A checkbox stays a rounded square next to a round radio.
655
- putTok(
1133
+ for (const t of parts) {
1134
+ // A rung on a part gives what the whole-theme rung gives the
1135
+ // radius token the part reads; an exact size is as given.
1136
+ putComp(
1137
+ {...s, mode: undefined},
1138
+ t,
1139
+ 'borderRadius',
1140
+ rung || pill ? derived(radiusTokenOf(ctx, t, s.when)) : `${px}px`,
1141
+ );
1142
+ }
1143
+ else
1144
+ for (const token of [
1145
+ '--radius-element',
656
1146
  '--radius-inner',
657
- px >= 9999 ? '6px' : val(Math.round(px * 0.6)),
658
- );
659
- putTok(
660
1147
  '--radius-container',
661
- px >= 9999 ? '24px' : `${Math.round(px * 1.25)}px`,
662
- );
663
- putTok(
664
1148
  '--radius-page',
665
- px >= 9999 ? '32px' : `${Math.round(px * 2.5)}px`,
666
- );
667
- }
1149
+ ])
1150
+ // The radii the build already shows for this corners value (a
1151
+ // build by an earlier editor, or a step back) are kept, as the
1152
+ // colors are: they change only when corners or the base does.
1153
+ putTok(token, ctx.keepRadii?.[token] ?? derived(token));
668
1154
  } else if (PALETTE_DIALS.includes(s.thing) || s.thing === 'vibrancy') {
669
1155
  // The palette mapping above sets these tokens.
670
1156
  } else if (s.thing === 'font') {
@@ -674,7 +1160,14 @@ export function compileTheme(ctx, data, base) {
674
1160
  theme.typography[r] = {
675
1161
  ...(theme.typography[r] ?? {}),
676
1162
  family: f.family,
677
- fallbacks: f.fallbacks,
1163
+ // Code falls back to a monospace font unless the value names
1164
+ // its own fallbacks.
1165
+ fallbacks:
1166
+ r === 'code' &&
1167
+ !s.value.includes(',') &&
1168
+ !/monospace/.test(f.fallbacks)
1169
+ ? 'ui-monospace, monospace'
1170
+ : f.fallbacks,
678
1171
  };
679
1172
  } else if (s.thing === 'surfaces') {
680
1173
  for (const t of SURFACE_PARTS.filter(x => ctx.project.target.has(x)))
@@ -750,8 +1243,10 @@ export function compileTheme(ctx, data, base) {
750
1243
  let nv = null;
751
1244
  if (/^--spacing-/.test(k) && /rem$/.test(v))
752
1245
  nv = `${Number((parseFloat(v) * f).toFixed(3))}rem`;
1246
+ // A control never gets smaller than 24px, the smallest target a
1247
+ // pointer can use comfortably.
753
1248
  if (/^--size-element-/.test(k) && /px$/.test(v))
754
- nv = `${Math.round(parseFloat(v) * f)}px`;
1249
+ nv = `${Math.max(Math.min(24, parseFloat(v)), Math.round(parseFloat(v) * f))}px`;
755
1250
  if (nv === null) continue;
756
1251
  if (parts.length) for (const t of parts) block(s, t)[k] = nv;
757
1252
  else putTok(k, nv);
@@ -764,11 +1259,29 @@ export function compileTheme(ctx, data, base) {
764
1259
  for (const t of parts) putComp(s, t, camel(s.thing), s.value);
765
1260
  }
766
1261
  }
767
- // A scale steeper than the standard one enlarges the headings; the steps
768
- // below the base text size keep the standard ratio, so small text stays
769
- // readable. An exact token setting still wins.
1262
+ // Core gives headings the body font when a theme sets only the body's:
1263
+ // a font for the body alone keeps the base theme's heading font.
1264
+ if (theme.typography?.body && !theme.typography.heading) {
1265
+ const heading = base.light['--font-family-heading'];
1266
+ if (heading) {
1267
+ const f = fontOf(heading);
1268
+ theme.typography.heading = {family: f.family, fallbacks: f.fallbacks};
1269
+ }
1270
+ }
1271
+ // A one-mode theme looks the same whatever the system asks for: every
1272
+ // color the theme does not set takes its mode's value from the base (or
1273
+ // Core) on both sides.
1274
+ if (modeOnly)
1275
+ for (const k of Object.keys(/** @type {Record<string, string>} */ (TOKENS)))
1276
+ if (MODAL.has(ctx.C.typeOf(k)) && !tok[k]) {
1277
+ const v = base[modeOnly]?.[k];
1278
+ if (v && !/var\(/.test(v)) putTok(k, v);
1279
+ }
1280
+ // A scale steeper or flatter than the standard one changes the headings;
1281
+ // the steps below the base text size keep the standard ratio, so small
1282
+ // text stays as it was. An exact token setting still wins.
770
1283
  const scale = theme.typography?.scale;
771
- if (scale && scale.ratio > STANDARD_RATIO)
1284
+ if (scale && scale.ratio !== STANDARD_RATIO)
772
1285
  for (const [k, step] of SMALL_STEPS)
773
1286
  if (
774
1287
  !data.settings.some(x => x.source === 'token' && x.thing === k && !x.on)
@@ -876,6 +1389,26 @@ export function maskedSettings(data) {
876
1389
  s,
877
1390
  `saved for ${s.mode} mode, which a ${data.mode} theme does not have, so it does not apply`,
878
1391
  );
1392
+ // A part setting that a later setting on a group holding that part
1393
+ // covers: the later one is written after it, so it wins.
1394
+ data.settings.forEach((s, i) => {
1395
+ if (s.source !== 'dial' || !s.on || FAMILIES[s.on]) return;
1396
+ const later = data.settings
1397
+ .slice(i + 1)
1398
+ .find(
1399
+ x =>
1400
+ x.thing === s.thing &&
1401
+ x.on &&
1402
+ (FAMILIES[x.on] ?? []).includes(/** @type {string} */ (s.on)) &&
1403
+ (x.when ?? '') === (s.when ?? '') &&
1404
+ (x.state ?? '') === (s.state ?? ''),
1405
+ );
1406
+ if (later)
1407
+ out.set(
1408
+ s,
1409
+ `${describe(later)} comes later and covers ${s.on}, so ${s.on} shows ${later.value}; set ${s.on} again to make it win`,
1410
+ );
1411
+ });
879
1412
  for (const s of data.settings) {
880
1413
  if (s.thing !== 'type' || !axes.size) continue;
881
1414
  const T = TYPE_STYLES[s.value];
@@ -914,13 +1447,32 @@ export function findOverrides(cssText, theme) {
914
1447
  `\\.astryx-${target.replace(/-/g, '\\-')}\\[data-([a-z-]+)="([^"]+)"\\]\\s*\\{([^}]*)\\}`,
915
1448
  'g',
916
1449
  );
1450
+ // A shorthand and its longhands are one property: the last one set
1451
+ // (background after background-color) is the one in effect.
1452
+ // border-radius, border-collapse and border-spacing are not part of
1453
+ // border.
1454
+ const NOT_LONGHAND =
1455
+ /^border-(radius|collapse|spacing)|^border-[a-z]+-radius$/;
1456
+ /** @param {string} a @param {string} b */
1457
+ const sameProperty = (a, b) => {
1458
+ const [x, y] = [kebab(a), kebab(b)];
1459
+ if (NOT_LONGHAND.test(x) || NOT_LONGHAND.test(y)) return x === y;
1460
+ return x.startsWith(`${y}-`) || y.startsWith(`${x}-`) || x === y;
1461
+ };
1462
+ const last = props.filter(
1463
+ (p, i) => !props.slice(i + 1).some(later => sameProperty(later, p)),
1464
+ );
917
1465
  for (const m of cssText.matchAll(re)) {
918
- for (const prop of props) {
1466
+ for (const prop of last) {
919
1467
  // A prop named for the property itself (weight for font-weight,
920
1468
  // color for color) is the author's own choice: it keeps winning.
921
1469
  const css = kebab(prop);
922
1470
  if (css === m[1] || css.endsWith(`-${m[1]}`)) continue;
923
- if (new RegExp(`(^|[;\\s])${kebab(prop)}\\s*:`).test(m[3]))
1471
+ // The override may set the property or one of its longhands.
1472
+ const declared = [...m[3].matchAll(/(?:^|[;\s])([a-z-]+)\s*:/g)].map(
1473
+ d => d[1],
1474
+ );
1475
+ if (declared.some(d => sameProperty(d, css)))
924
1476
  extra.push({
925
1477
  target,
926
1478
  key: `${m[1]}:${m[2]}`,
@@ -933,6 +1485,17 @@ export function findOverrides(cssText, theme) {
933
1485
  return extra;
934
1486
  }
935
1487
 
1488
+ /**
1489
+ * The CSS value of lifted secondary text: one color in a one-mode theme,
1490
+ * else light-dark().
1491
+ * @param {Partial<Record<'light' | 'dark', {color: string}>>} lift
1492
+ * @param {'light' | 'dark' | null} only
1493
+ */
1494
+ const liftValue = (lift, only) =>
1495
+ only
1496
+ ? String(lift[only]?.color)
1497
+ : `light-dark(${lift.light?.color}, ${lift.dark?.color})`;
1498
+
936
1499
  /**
937
1500
  * The generated theme source. A token the palette mapping set, and no exact
938
1501
  * token setting replaced, reads its palette stop from the generated palette
@@ -942,7 +1505,7 @@ export function findOverrides(cssText, theme) {
942
1505
  * @param {any} theme
943
1506
  * @param {import('./_palette.mjs').PaletteMapping | null} pal
944
1507
  */
945
- function settingsSource(slug, data, theme, pal) {
1508
+ function settingsSource(slug, data, theme, pal, cwd = '') {
946
1509
  const like = data.like;
947
1510
  const REF = '@@palette:';
948
1511
  /** @param {string} family @param {'light' | 'dark'} m @param {import('./_palette.mjs').StopRef} r */
@@ -975,33 +1538,81 @@ function settingsSource(slug, data, theme, pal) {
975
1538
  ];
976
1539
  }
977
1540
  }
1541
+ // A lifted part reads the neutral color's stops too.
1542
+ if (pal?.lift && out.components) {
1543
+ out.components = {...out.components};
1544
+ for (const [target, key, ground] of LIFT_PARTS) {
1545
+ const lift = pal.lift[ground];
1546
+ if (!lift) continue;
1547
+ const literal = liftValue(lift, only);
1548
+ /** A shade of the neutral palette as a reference; a color as it is. @param {'light' | 'dark'} m */
1549
+ const one = m => {
1550
+ const r = /** @type {any} */ (lift[m]);
1551
+ return r.family === 'literal' ? r.color : refOf('neutral', m, r);
1552
+ };
1553
+ const refs = only
1554
+ ? one(only)
1555
+ : `light-dark(${one('light')}, ${one('dark')})`;
1556
+ const block = out.components[target]?.[key];
1557
+ if (block?.['--color-text-secondary'] !== literal) continue;
1558
+ out.components[target] = {
1559
+ ...out.components[target],
1560
+ [key]: {...block, '--color-text-secondary': refs},
1561
+ };
1562
+ }
1563
+ }
978
1564
  let usesPalette = false;
979
- const body = JSON.stringify(out, null, 2).replace(
980
- /"@@palette:(?:(black|white)|([a-z][a-z0-9-]*)\.(light|dark)\.(\d+(?:\.\d+)?)(?:\+([0-9a-f]{2}))?)"/g,
981
- (_, end, family, m, stop, alpha) => {
982
- usesPalette = true;
983
- if (end) return `palette.${end}`;
984
- return `palette${/^[a-z]\w*$/.test(family) ? `.${family}` : `[${JSON.stringify(family)}]`}.${m}[${stop}]${alpha ? ` + '${alpha}'` : ''}`;
985
- },
1565
+ const body = JSON.stringify(out, null, 2)
1566
+ .replace(
1567
+ /"@@palette:(?:(black|white)|([a-z][a-z0-9-]*)\.(light|dark)\.(\d+(?:\.\d+)?)(?:\+([0-9a-f]{2}))?)"/g,
1568
+ (_, end, family, m, stop, alpha) => {
1569
+ usesPalette = true;
1570
+ if (end) return `palette.${end}`;
1571
+ return `palette${/^[a-z]\w*$/.test(family) ? `.${family}` : `[${JSON.stringify(family)}]`}.${m}[${stop}]${alpha ? ` + '${alpha}'` : ''}`;
1572
+ },
1573
+ )
1574
+ .replace(
1575
+ // A stop inside a longer value (light-dark()) becomes a template.
1576
+ /"([^"\n]*@@palette:[^"\n]*)"/g,
1577
+ (_, inner) => {
1578
+ usesPalette = true;
1579
+ return `\`${inner.replace(
1580
+ /@@palette:([a-z][a-z0-9-]*)\.(light|dark)\.(\d+(?:\.\d+)?)/g,
1581
+ (
1582
+ /** @type {string} */ __,
1583
+ /** @type {string} */ family,
1584
+ /** @type {string} */ m,
1585
+ /** @type {string} */ stop,
1586
+ ) =>
1587
+ `\${palette${/^[a-z]\w*$/.test(family) ? `.${family}` : `[${JSON.stringify(family)}]`}.${m}[${stop}]}`,
1588
+ )}\``;
1589
+ },
1590
+ );
1591
+ return sealModule(
1592
+ [
1593
+ `// Generated by \`${P}\` from ${slug}.settings.json on every change: do not edit.`,
1594
+ `// Built from settings ${settingsStamp(data)}.`,
1595
+ ...(like && cwd
1596
+ ? [
1597
+ `// Built on @astryxdesign/theme-${like} ${baseVersionOf(cwd, like) ?? 'unknown'}.`,
1598
+ ]
1599
+ : []),
1600
+ `// Change it with \`${P} set ${slug} ...\`; your own changes go in ${slug}.theme.ts.`,
1601
+ "import {defineTheme} from '@astryxdesign/core/theme';",
1602
+ ...(like
1603
+ ? [
1604
+ `import {${like}Theme as base} from '@astryxdesign/theme-${like}/built';`,
1605
+ ]
1606
+ : []),
1607
+ ...(usesPalette ? [paletteImport(slug)] : []),
1608
+ '',
1609
+ `export const ${camel(slug)}Settings = defineTheme({`,
1610
+ ...(like ? [' extends: base,'] : []),
1611
+ ...body.split('\n').slice(1, -1),
1612
+ '});',
1613
+ '',
1614
+ ].join('\n'),
986
1615
  );
987
- return [
988
- `// Generated by \`${P}\` from ${slug}.settings.json on every change: do not edit.`,
989
- `// Built from settings ${settingsStamp(data)}.`,
990
- `// Change it with \`${P} set ${slug} ...\`; your own changes go in ${slug}.theme.ts.`,
991
- "import {defineTheme} from '@astryxdesign/core/theme';",
992
- ...(like
993
- ? [
994
- `import {${like}Theme as base} from '@astryxdesign/theme-${like}/built';`,
995
- ]
996
- : []),
997
- ...(usesPalette ? [paletteImport(slug)] : []),
998
- '',
999
- `export const ${camel(slug)}Settings = defineTheme({`,
1000
- ...(like ? [' extends: base,'] : []),
1001
- ...body.split('\n').slice(1, -1),
1002
- '});',
1003
- '',
1004
- ].join('\n');
1005
1616
  }
1006
1617
 
1007
1618
  /**
@@ -1025,6 +1636,52 @@ function themeModuleSource(slug) {
1025
1636
  ].join('\n');
1026
1637
  }
1027
1638
 
1639
+ /** The theme source as the editor first writes it. @param {string} slug */
1640
+ export const themeSource = slug => themeModuleSource(slug);
1641
+
1642
+ /**
1643
+ * Why `<slug>.theme.ts` cannot carry the settings, or null: it must import
1644
+ * `./<slug>.settings`, extend `<camel>Settings` and keep the name, or no
1645
+ * setting takes effect.
1646
+ * @param {string} cwd
1647
+ * @param {string} slug
1648
+ * @returns {string | null}
1649
+ */
1650
+ export function themeSourceProblem(cwd, slug) {
1651
+ const f = themeFiles(cwd, slug);
1652
+ if (!fs.existsSync(f.ts)) return null;
1653
+ const code = fs
1654
+ .readFileSync(f.ts, 'utf8')
1655
+ .replace(/\/\*[\s\S]*?\*\//g, '')
1656
+ .replace(/\/\/.*$/gm, '');
1657
+ const settings = `${camel(slug)}Settings`;
1658
+ if (
1659
+ !new RegExp(`from\\s+['"]\\./${slug}\\.settings(\\.[jt]s)?['"]`).test(code)
1660
+ )
1661
+ return `${slug}.theme.ts does not import ./${slug}.settings`;
1662
+ if (!new RegExp(`extends\\s*:\\s*${settings}\\b`).test(code))
1663
+ return `${slug}.theme.ts no longer extends ${settings}`;
1664
+ if (!new RegExp(`name\\s*:\\s*(['"\`])${slug}\\1`).test(code))
1665
+ return `${slug}.theme.ts no longer names the theme '${slug}'`;
1666
+ return null;
1667
+ }
1668
+
1669
+ /**
1670
+ * Refuse a build whose theme source cannot carry the settings, naming the
1671
+ * lines that put it back.
1672
+ * @param {string} cwd
1673
+ * @param {string} slug
1674
+ */
1675
+ export function refuseThemeSource(cwd, slug) {
1676
+ const why = themeSourceProblem(cwd, slug);
1677
+ if (why)
1678
+ throw new AstryxError(
1679
+ `${why}, so settings cannot take effect. Put back the import of ${camel(slug)}Settings from './${slug}.settings', extends: ${camel(slug)}Settings and name: '${slug}' in themes/${slug}/${slug}.theme.ts (your own changes stay below them). Nothing was changed.`,
1680
+ [{name: `${P} show ${slug}`, reason: 'see the theme as it is'}],
1681
+ ERROR_CODES.ERR_THEME_INVALID,
1682
+ );
1683
+ }
1684
+
1028
1685
  /**
1029
1686
  * Generate the theme source, build it with the theme build, then repeat any
1030
1687
  * part setting a more specific rule would beat and build again.
@@ -1036,27 +1693,67 @@ function themeModuleSource(slug) {
1036
1693
  export async function buildTheme(ctx, slug, data) {
1037
1694
  const {cwd} = ctx.project;
1038
1695
  const f = themeFiles(cwd, slug);
1696
+ refuseThemeSource(cwd, slug);
1039
1697
  if (data.like) baseThemeFile(ctx.project, data.like);
1040
1698
  const base = await baseResolved(ctx.project, data.like);
1041
- const theme = compileTheme(ctx, data, base);
1042
- const pal = paletteMapping(
1043
- cwd,
1044
- slug,
1045
- data,
1046
- base,
1047
- ctx.project.core.tokenDefaults,
1048
- );
1049
1699
  fs.mkdirSync(f.dir, {recursive: true});
1050
1700
  // Each write is recorded for a rollback; the time between them is not.
1701
+ // Each step checks first that this command still holds the theme lock:
1702
+ // the build's own writes (the stylesheet and module the stable build
1703
+ // writes, the files it removes) are fenced as each step starts.
1051
1704
  /** @type {<T>(fn: () => T) => Promise<Awaited<T>>} */
1052
- const step = fn => track(f.dir, ctx.wrote ?? new Map(), fn);
1705
+ const step = fn => {
1706
+ refuseIfLockLost();
1707
+ return track(f.dir, ctx.wrote ?? new Map(), fn);
1708
+ };
1053
1709
  /** @type {string[]} */
1054
1710
  let notes = [];
1711
+ // The palette files are written first, and the theme is built from them
1712
+ // as written: a config an earlier editor wrote is brought up to date
1713
+ // before any color is read from it.
1714
+ const paletteFile = path.join(cwd, paletteFiles(slug).palette);
1715
+ const paletteBefore = fs.existsSync(paletteFile)
1716
+ ? fs.readFileSync(paletteFile, 'utf8')
1717
+ : null;
1055
1718
  await step(() => {
1056
1719
  notes = syncPalette(cwd, slug, data, base);
1057
- writeAtomic(f.settingsTs, settingsSource(slug, data, theme, pal));
1720
+ });
1721
+ // Shades a theme already shows are kept only while its palette stays the
1722
+ // same: a palette made again moves every shade.
1723
+ if (
1724
+ (fs.existsSync(paletteFile)
1725
+ ? fs.readFileSync(paletteFile, 'utf8')
1726
+ : null) !== paletteBefore
1727
+ )
1728
+ ctx.keepStops = null;
1729
+ const theme = compileTheme(ctx, data, base);
1730
+ const pal = keepShades(
1731
+ paletteMapping(cwd, slug, data, base, ctx.project.core.tokenDefaults),
1732
+ ctx.keepStops,
1733
+ );
1734
+ await step(() => {
1735
+ writeWhole(f.settingsTs, settingsSource(slug, data, theme, pal, cwd));
1058
1736
  syncPaletteRefs(cwd, slug, fs.readFileSync(f.settingsTs, 'utf8'), pal);
1059
- if (!fs.existsSync(f.ts)) writeAtomic(f.ts, themeModuleSource(slug));
1737
+ if (!fs.existsSync(f.ts)) writeWhole(f.ts, themeModuleSource(slug));
1738
+ });
1739
+ // Files an earlier build wrote that this one may not: the variants types
1740
+ // of an older base, and section sheets of an older look.
1741
+ await step(() => {
1742
+ for (const file of [
1743
+ path.join(f.dir, `${slug}.variants.d.ts`),
1744
+ ...(fs.existsSync(f.dir)
1745
+ ? fs
1746
+ .readdirSync(f.dir)
1747
+ // Section sheets, and every picture: all show the look before
1748
+ // this build. The full sheet and the preview page are written
1749
+ // again by the commands that make them.
1750
+ .filter(n =>
1751
+ /^(sheet-[a-z-]+\.html|(sheet|preview)(-[a-z-]+)?\.png)$/.test(n),
1752
+ )
1753
+ .map(n => path.join(f.dir, n))
1754
+ : []),
1755
+ ])
1756
+ fs.rmSync(file, {force: true});
1060
1757
  });
1061
1758
  let receipt = await step(() => runBuild(ctx, slug));
1062
1759
  const found = findOverrides(fs.readFileSync(f.css, 'utf8'), theme).filter(
@@ -1071,7 +1768,7 @@ export async function buildTheme(ctx, slug, data) {
1071
1768
  lifted.push(`${x.target} ${x.key} ${kebab(x.prop)}`);
1072
1769
  }
1073
1770
  await step(() => {
1074
- writeAtomic(f.settingsTs, settingsSource(slug, data, theme, pal));
1771
+ writeWhole(f.settingsTs, settingsSource(slug, data, theme, pal, cwd));
1075
1772
  syncPaletteRefs(cwd, slug, fs.readFileSync(f.settingsTs, 'utf8'), pal);
1076
1773
  });
1077
1774
  receipt = await step(() => runBuild(ctx, slug));
@@ -1096,9 +1793,12 @@ async function runBuild(ctx, slug) {
1096
1793
  const silent = logger.silent;
1097
1794
  logger.setSilent(true);
1098
1795
  try {
1796
+ // No --out: the theme's name is its slug, so the build writes
1797
+ // <slug>.css beside the source, and the generated headers read as a
1798
+ // plain `compile themes/<slug>/<slug>.theme.ts` writes them.
1099
1799
  const {receipt} = await themeBuildForReport(
1100
1800
  shown(cwd, f.ts),
1101
- {out: shown(cwd, f.css)},
1801
+ {},
1102
1802
  {cwd},
1103
1803
  {compact: true},
1104
1804
  );
@@ -1155,10 +1855,22 @@ export async function resolvedTokens(ctx, slug) {
1155
1855
  v => v && typeof v === 'object' && typeof v.name === 'string',
1156
1856
  );
1157
1857
  const {core} = ctx.project;
1158
- return {
1858
+ const out = {
1159
1859
  light: core.resolveThemeTokens(t, {mode: 'light'}),
1160
1860
  dark: core.resolveThemeTokens(t, {mode: 'dark'}),
1161
1861
  };
1862
+ // The tokens each part sets for itself (the official themes lift
1863
+ // secondary text on some parts), for the contrast check; kept out of the
1864
+ // modes so nothing that lists the resolved tokens sees it.
1865
+ /** @type {Record<string, Record<string, string>>} */
1866
+ const parts = {};
1867
+ for (const [target, blocks] of Object.entries(t?.components ?? {}))
1868
+ for (const block of Object.values(/** @type {any} */ (blocks) ?? {}))
1869
+ for (const [k, v] of Object.entries(/** @type {any} */ (block) ?? {}))
1870
+ if (k.startsWith('--') && typeof v === 'string')
1871
+ (parts[target] ??= {})[k] = v;
1872
+ Object.defineProperty(out, 'parts', {value: parts, enumerable: false});
1873
+ return out;
1162
1874
  }
1163
1875
 
1164
1876
  /**
@@ -1172,8 +1884,8 @@ export async function resolvedTokens(ctx, slug) {
1172
1884
  */
1173
1885
  export async function contrastProblems(ctx, data, res) {
1174
1886
  const base = await baseResolved(ctx.project, data.like);
1175
- /** @param {PaintSide} side @param {'fg' | 'bg'} which @param {string} m */
1176
- const override = (side, which, m) => {
1887
+ /** @param {PaintSide} side @param {'fg' | 'bg'} which @param {string} m @param {string} [when] */
1888
+ const override = (side, which, m, when) => {
1177
1889
  if (!side.target) return null;
1178
1890
  const props =
1179
1891
  which === 'fg' ? ['color'] : ['background', 'background-color'];
@@ -1182,7 +1894,7 @@ export async function contrastProblems(ctx, data, res) {
1182
1894
  .find(
1183
1895
  x =>
1184
1896
  partsOf(ctx, x).includes(/** @type {string} */ (side.target)) &&
1185
- !x.when &&
1897
+ (!x.when || x.when === when) &&
1186
1898
  !x.state &&
1187
1899
  (!x.mode || x.mode === m) &&
1188
1900
  ((x.source === 'property' && props.includes(x.thing)) ||
@@ -1190,11 +1902,56 @@ export async function contrastProblems(ctx, data, res) {
1190
1902
  );
1191
1903
  return hit?.value ?? null;
1192
1904
  };
1905
+ /**
1906
+ * Text on a lifted background (the accent tint, the neutral track) as
1907
+ * the part sets it for itself: the official themes lift secondary text
1908
+ * there, and so does a generated theme.
1909
+ * @param {TextPair} p @param {string} m
1910
+ */
1911
+ const onTint = (p, m) => {
1912
+ const tok = p.fg.tokens[0];
1913
+ if (!tok || !LIFT_GROUND_TOKENS.has(String(p.bg.tokens[0]))) return null;
1914
+ const own = /** @type {any} */ (res).parts?.[p.fg.target ?? p.text]?.[tok];
1915
+ if (typeof own !== 'string') return null;
1916
+ const split = /^light-dark\((.*),\s*([^,]*)\)$/.exec(own.trim());
1917
+ const v = split ? split[m === 'dark' ? 2 : 1].trim() : own;
1918
+ const ref = /^var\((--[\w-]+)\)$/.exec(v);
1919
+ return ref ? res[/** @type {'light' | 'dark'} */ (m)][ref[1]] : v;
1920
+ };
1921
+ /** @type {(p: TextPair, side: 'fg' | 'bg', m: string) => string | null} */
1922
+ const ofBase = (p, side, m) => {
1923
+ const target = p[side].target;
1924
+ if (!target) return null;
1925
+ const own =
1926
+ baseComponent(
1927
+ base,
1928
+ ctx,
1929
+ target,
1930
+ side === 'fg' ? 'color' : 'backgroundColor',
1931
+ {
1932
+ when: /** @type {any} */ (p).when,
1933
+ },
1934
+ ) ??
1935
+ (side === 'bg'
1936
+ ? baseComponent(base, ctx, target, 'background', {
1937
+ when: /** @type {any} */ (p).when,
1938
+ })
1939
+ : null);
1940
+ if (!own) return null;
1941
+ const ref = /^var\((--[\w-]+)\)$/.exec(own.trim());
1942
+ return ref
1943
+ ? (res[/** @type {'light' | 'dark'} */ (m)][ref[1]] ?? null)
1944
+ : own;
1945
+ };
1193
1946
  /** @type {(p: TextPair, side: 'fg' | 'bg', m: string) => string | null} */
1194
1947
  const value = (p, side, m) => {
1195
1948
  const s = p[side];
1196
1949
  return (
1197
- override(s, side, m) ??
1950
+ override(s, side, m, /** @type {any} */ (p).when) ??
1951
+ // The base theme's own part style (neutral's destructive button),
1952
+ // which Core's reads do not know.
1953
+ ofBase(p, side, m) ??
1954
+ (side === 'fg' ? onTint(p, m) : null) ??
1198
1955
  (s.tokens.length
1199
1956
  ? res[/** @type {'light' | 'dark'} */ (m)][s.tokens[0]]
1200
1957
  : s.raw)
@@ -1202,11 +1959,50 @@ export async function contrastProblems(ctx, data, res) {
1202
1959
  };
1203
1960
  /** @type {(p: TextPair, side: 'fg' | 'bg', m: string) => string | null} */
1204
1961
  const baseValue = (p, side, m) => {
1962
+ // Lifted text on the tint is held to 4.5:1, never excused by an
1963
+ // unlifted base pair.
1964
+ if (onTint(p, m) != null) return null;
1205
1965
  const s = p[side];
1206
1966
  return s.tokens.length
1207
1967
  ? base[/** @type {'light' | 'dark'} */ (m)][s.tokens[0]]
1208
1968
  : s.raw;
1209
1969
  };
1970
+ // The census renders each part once, with its default props: text on a
1971
+ // part whose variants each have their own colors (a destructive button)
1972
+ // is measured per variant too, from what each variant reads.
1973
+ /** @type {TextPair[]} */
1974
+ const variantPairs = [];
1975
+ for (const p of /** @type {any} */ (ctx).parts.pairs) {
1976
+ const t = p.fg.target;
1977
+ if (!t || t !== p.bg.target) continue;
1978
+ const fgReads = ctx.C.partReads(t, 'text');
1979
+ const bgReads = ctx.C.partReads(t, 'background');
1980
+ const variants = [
1981
+ ...new Set(
1982
+ bgReads
1983
+ .flatMap(r => r.when)
1984
+ .map(w => /^variant=([\w-]+)$/.exec(w)?.[1])
1985
+ .filter(Boolean),
1986
+ ),
1987
+ ];
1988
+ for (const v of /** @type {string[]} */ (variants)) {
1989
+ const bgTok = bgReads.find(r => r.when.includes(`variant=${v}`))?.token;
1990
+ const fgTok =
1991
+ fgReads.find(r => r.when.includes(`variant=${v}`))?.token ??
1992
+ p.fg.tokens[0];
1993
+ if (!bgTok || !fgTok) continue;
1994
+ if (bgTok === p.bg.tokens[0] && fgTok === p.fg.tokens[0]) continue;
1995
+ variantPairs.push(
1996
+ /** @type {any} */ ({
1997
+ ...p,
1998
+ text: `${p.text} (variant ${v})`,
1999
+ when: `variant:${v}`,
2000
+ fg: {...p.fg, tokens: [fgTok]},
2001
+ bg: {...p.bg, tokens: [bgTok]},
2002
+ }),
2003
+ );
2004
+ }
2005
+ }
1210
2006
  const {problems, more, unchecked} = ctx.C.contrast(
1211
2007
  value,
1212
2008
  baseValue,
@@ -1219,6 +2015,7 @@ export async function contrastProblems(ctx, data, res) {
1219
2015
  page: m =>
1220
2016
  res[/** @type {'light' | 'dark'} */ (m)]['--color-background-body'],
1221
2017
  },
2018
+ variantPairs,
1222
2019
  );
1223
2020
  return [
1224
2021
  ...problems.map(
@@ -1233,7 +2030,8 @@ export async function contrastProblems(ctx, data, res) {
1233
2030
  const scoped = data.settings.filter(
1234
2031
  x =>
1235
2032
  (x.on &&
1236
- (x.when || x.state) &&
2033
+ // A variant's own colors are measured with the variant pairs.
2034
+ (x.state || (x.when && !/^variant:/.test(x.when))) &&
1237
2035
  (/^(color|background|background-color)$/.test(x.thing) ||
1238
2036
  /^--color-/.test(x.thing))) ||
1239
2037
  // The button style recolors the primary button only.
@@ -1266,12 +2064,27 @@ export async function contrastProblems(ctx, data, res) {
1266
2064
  function parseSettings(text) {
1267
2065
  if (text == null) return null;
1268
2066
  try {
1269
- return JSON.parse(text);
2067
+ const data = JSON.parse(text);
2068
+ return settingsShapeOk(data) ? data : null;
1270
2069
  } catch {
1271
2070
  return null;
1272
2071
  }
1273
2072
  }
1274
2073
 
2074
+ /**
2075
+ * Whether parsed settings have the shape the editor reads: an object with a
2076
+ * list of settings.
2077
+ * @param {any} data
2078
+ */
2079
+ export function settingsShapeOk(data) {
2080
+ return (
2081
+ !!data &&
2082
+ typeof data === 'object' &&
2083
+ !Array.isArray(data) &&
2084
+ Array.isArray(data.settings)
2085
+ );
2086
+ }
2087
+
1275
2088
  /**
1276
2089
  * Every regular file under `dir` and the hash of its bytes; empty when
1277
2090
  * there is no folder.
@@ -1281,20 +2094,244 @@ function parseSettings(text) {
1281
2094
  function hashDir(dir) {
1282
2095
  /** @type {Map<string, string>} */
1283
2096
  const out = new Map();
1284
- if (!fs.lstatSync(dir, {throwIfNoEntry: false})?.isDirectory()) return out;
1285
- /** @param {string} d */
1286
- const walk = d => {
1287
- for (const e of fs.readdirSync(d, {withFileTypes: true})) {
1288
- const p = path.join(d, e.name);
1289
- if (e.isDirectory()) walk(p);
1290
- else if (e.isFile())
1291
- out.set(
1292
- p,
1293
- createHash('sha256').update(fs.readFileSync(p)).digest('hex'),
1294
- );
1295
- }
2097
+ for (const p of ownFiles(dir))
2098
+ out.set(p, createHash('sha256').update(fs.readFileSync(p)).digest('hex'));
2099
+ return out;
2100
+ }
2101
+
2102
+ /**
2103
+ * The value the base theme itself gives a part's property where a setting
2104
+ * applies (its variant and state), as the build keys part styles; null
2105
+ * when the base theme leaves it to Core.
2106
+ * @param {{light: Record<string, string>, components?: Record<string, any>}} base
2107
+ * @param {Ctx} ctx
2108
+ * @param {string} target
2109
+ * @param {string} prop camelCase
2110
+ * @param {{when?: string, state?: string}} s
2111
+ * @returns {string | null}
2112
+ */
2113
+ export function baseComponent(base, ctx, target, prop, s) {
2114
+ const t = base.components?.[target];
2115
+ if (!t) return null;
2116
+ let b = t[s.when ?? 'base'];
2117
+ if (s.state) {
2118
+ const states = ctx.project.target.get(target)?.states ?? [];
2119
+ b = states.includes(s.state)
2120
+ ? t[s.when == null ? s.state : `${s.when}+${s.state}`]
2121
+ : (b?.[stateKey(s.state)] ?? b?.[`:${s.state}`]);
2122
+ }
2123
+ const v = b?.[prop];
2124
+ return typeof v === 'string' ? v : null;
2125
+ }
2126
+
2127
+ /**
2128
+ * The focus state a part's own styles key on: a part whose styled element
2129
+ * is a wrapper (a text input's box) shows focus only through
2130
+ * `focus-within`; null when it keys on none.
2131
+ * @param {Ctx} ctx
2132
+ * @param {string} part
2133
+ * @returns {string | null}
2134
+ */
2135
+ export function focusStateOf(ctx, part) {
2136
+ const conds = JSON.stringify(ctx.C.MAP[part]?.own ?? {});
2137
+ for (const st of ['focus-within', 'focus-visible', 'focus'])
2138
+ if (conds.includes(`:${st}`)) return st;
2139
+ return null;
2140
+ }
2141
+
2142
+ /**
2143
+ * The radius token a part's resting corners read. A part the census saw
2144
+ * closed (a menu, a popover) has none recorded: a container or menu reads
2145
+ * the container radius, like every Core surface; any other part reads the
2146
+ * element radius.
2147
+ * @param {Ctx} ctx
2148
+ * @param {string} part
2149
+ * @param {string} [when]
2150
+ * @returns {string}
2151
+ */
2152
+ export function radiusTokenOf(ctx, part, when) {
2153
+ return (
2154
+ /var\((--radius-[\w-]+)\)/.exec(
2155
+ partDefault(ctx, part, 'borderRadius', when) ?? '',
2156
+ )?.[1] ??
2157
+ ctx.C.partReads(part, 'corners').find(
2158
+ (/** @type {any} */ x) =>
2159
+ x.props.includes('border-radius') && /^--radius-/.test(x.token),
2160
+ )?.token ??
2161
+ (['containers', 'menus'].includes(familyOf(part) ?? '')
2162
+ ? '--radius-container'
2163
+ : '--radius-element')
2164
+ );
2165
+ }
2166
+
2167
+ /** The file a `new` keeps beside the files it writes until it is done. */
2168
+ export const NEW_MARKER = '.astryx-new.json';
2169
+
2170
+ /**
2171
+ * Remove a `new` marker from a theme folder whose settings are whole: the
2172
+ * `new` that left it made the theme, and nothing is left to finish.
2173
+ * @param {string} dir
2174
+ */
2175
+ export function clearNewMarker(dir) {
2176
+ // Fenced like every write under the theme lock.
2177
+ refuseIfLockLost();
2178
+ try {
2179
+ fs.rmSync(path.join(dir, NEW_MARKER), {force: true});
2180
+ } catch {
2181
+ // Read-only: the next writing command tries again.
2182
+ }
2183
+ }
2184
+
2185
+ /**
2186
+ * The pseudo key a state writes in a part's styles. Core marks a disabled
2187
+ * button, link, tab or menu item with aria-disabled (it stays focusable),
2188
+ * and its own styles match both forms: so does the theme.
2189
+ * @param {string} state
2190
+ * @returns {string}
2191
+ */
2192
+ export function stateKey(state) {
2193
+ return state === 'disabled'
2194
+ ? ':is(:disabled,[aria-disabled="true"])'
2195
+ : `:${state}`;
2196
+ }
2197
+
2198
+ /**
2199
+ * The whole-theme radius tokens a generated settings module writes, or null
2200
+ * when it writes none.
2201
+ * @param {string} source
2202
+ * @returns {Record<string, string> | null}
2203
+ */
2204
+ export function radiiIn(source) {
2205
+ /** @type {Record<string, string>} */
2206
+ const out = {};
2207
+ for (const m of source.matchAll(
2208
+ /^ {4}"(--radius-(?:element|inner|container|page))": "([^"]+)"/gm,
2209
+ ))
2210
+ out[m[1]] = m[2];
2211
+ return Object.keys(out).length ? out : null;
2212
+ }
2213
+
2214
+ /**
2215
+ * A history step: the settings as they were, with the radii their build
2216
+ * showed (so a step back restores them exactly, also for a theme an earlier
2217
+ * editor built). A step an older CLI wrote has none, and is read as before.
2218
+ * @param {string} text
2219
+ * @param {Record<string, string> | null} radii
2220
+ */
2221
+ function withBuilt(text, radii) {
2222
+ if (!radii) return text;
2223
+ try {
2224
+ const data = JSON.parse(text.replace(/^\uFEFF/, ''));
2225
+ if (!settingsShapeOk(data)) return text;
2226
+ return `${JSON.stringify({...data, built: {radii}}, null, 2)}\n`;
2227
+ } catch {
2228
+ return text;
2229
+ }
2230
+ }
2231
+
2232
+ /**
2233
+ * The radius, in px, the build writes for a radius token at a corners value
2234
+ * (a rung, or a size). The derived radii keep the base theme's own
2235
+ * proportions to the element radius (matcha's page is 3.5 times it), so a
2236
+ * bigger element radius never makes them smaller; a checkbox stays a
2237
+ * rounded square at pill, and a container or page at pill is half again as
2238
+ * round as at `round` (a fully round card is a capsule). Past 1000px a
2239
+ * radius is fully round.
2240
+ * @param {{light: Record<string, string>}} base the base theme's tokens
2241
+ * @param {string} value
2242
+ * @param {string} token
2243
+ * @returns {number}
2244
+ */
2245
+ export function radiusAt(base, value, token) {
2246
+ const px = cornerPx(value) >= 1000 ? 9999 : cornerPx(value);
2247
+ const pill = px >= 9999;
2248
+ const el = lengthPx(base.light['--radius-element'] ?? '');
2249
+ /** @param {string} t @param {number} fallback */
2250
+ const ratio = (t, fallback) => {
2251
+ const v = lengthPx(base.light[t] ?? '');
2252
+ return el && v != null ? v / el : fallback;
1296
2253
  };
1297
- walk(dir);
2254
+ const roundPx = CORNERS.find(([n]) => n === 'round')?.[1] ?? 16;
2255
+ // Inner corners (a checkbox) stay a rounded square: never rounder than
2256
+ // at round, so pill keeps round's and no step makes them smaller.
2257
+ if (token === '--radius-inner') {
2258
+ const inner = (/** @type {number} */ x) =>
2259
+ Math.round(x * Math.min(1, ratio(token, 0.6)));
2260
+ return Math.min(inner(roundPx), inner(pill ? roundPx : px));
2261
+ }
2262
+ // A container or page is never rounder than at pill, so pill never makes
2263
+ // one less round, and a size just under 1000px meets pill smoothly.
2264
+ if (token === '--radius-container') {
2265
+ const atPill = Math.max(24, 1.5 * roundPx * ratio(token, 1.25));
2266
+ return Math.round(
2267
+ pill ? atPill : Math.min(atPill, px * ratio(token, 1.25)),
2268
+ );
2269
+ }
2270
+ if (token === '--radius-page') {
2271
+ const atPill = Math.max(32, 1.5 * roundPx * ratio(token, 2.5));
2272
+ return Math.round(pill ? atPill : Math.min(atPill, px * ratio(token, 2.5)));
2273
+ }
2274
+ return pill ? 9999 : px;
2275
+ }
2276
+
2277
+ /**
2278
+ * Whether a file is a module the editor generated (its first line is the
2279
+ * editor's header).
2280
+ * @param {string} file
2281
+ */
2282
+ export function madeByEditor(file) {
2283
+ try {
2284
+ return fs
2285
+ .readFileSync(file, 'utf8')
2286
+ .startsWith('// Generated by `astryx experimental theme editor`');
2287
+ } catch {
2288
+ return false;
2289
+ }
2290
+ }
2291
+
2292
+ /**
2293
+ * The files the editor writes for a theme, after `<slug>.`: the only ones a
2294
+ * change reads, hashes or puts back, and the only ones a stopped `new`
2295
+ * leaves (a designer's `<slug>.design.psd` beside them is never touched).
2296
+ */
2297
+ export const EDITOR_SUFFIXES = [
2298
+ 'settings.ts',
2299
+ 'settings.json',
2300
+ 'css',
2301
+ 'css.d.ts',
2302
+ 'js',
2303
+ 'd.ts',
2304
+ 'variants.d.ts',
2305
+ 'history.json',
2306
+ ];
2307
+
2308
+ /**
2309
+ * The files in a theme folder that the editor writes, by name: the
2310
+ * theme's generated files, its settings, history and pages, and its color
2311
+ * files. Anything else there (notes, a designer's source file, the
2312
+ * person's own tokens) is never read, hashed or put back.
2313
+ * `<slug>.theme.ts` is the person's file: it is listed only while it does
2314
+ * not exist yet, so the run that creates it can take it back.
2315
+ * @param {string} dir
2316
+ * @returns {string[]}
2317
+ */
2318
+ function ownFiles(dir) {
2319
+ if (!fs.lstatSync(dir, {throwIfNoEntry: false})?.isDirectory()) return [];
2320
+ const slug = path.basename(dir);
2321
+ const mine = (/** @type {string} */ n) =>
2322
+ EDITOR_SUFFIXES.some(x => n === `${slug}.${x}`) ||
2323
+ /^(preview(-[a-z]+)?\.(html|png)|sheet(-[a-z-]+)?\.(html|png)|palette\.config(\.damaged(-\d+)?)?\.json)$/.test(
2324
+ n,
2325
+ );
2326
+ /** @type {string[]} */
2327
+ const out = [];
2328
+ for (const e of fs.readdirSync(dir, {withFileTypes: true}))
2329
+ if (e.isFile() && mine(e.name)) out.push(path.join(dir, e.name));
2330
+ const tokens = path.join(dir, 'tokens');
2331
+ if (fs.lstatSync(tokens, {throwIfNoEntry: false})?.isDirectory())
2332
+ for (const e of fs.readdirSync(tokens, {withFileTypes: true}))
2333
+ if (e.isFile() && e.name.startsWith(`${slug}.palette`))
2334
+ out.push(path.join(tokens, e.name));
1298
2335
  return out;
1299
2336
  }
1300
2337
 
@@ -1310,10 +2347,18 @@ function hashDir(dir) {
1310
2347
  */
1311
2348
  async function track(dir, wrote, fn) {
1312
2349
  const before = hashDir(dir);
2350
+ const theme = path.join(dir, `${path.basename(dir)}.theme.ts`);
2351
+ const themeWasThere = fs.existsSync(theme);
1313
2352
  try {
1314
2353
  return await fn();
1315
2354
  } finally {
1316
2355
  const after = hashDir(dir);
2356
+ // The theme source this run made is its own to take back.
2357
+ if (!themeWasThere && fs.existsSync(theme))
2358
+ after.set(
2359
+ theme,
2360
+ createHash('sha256').update(fs.readFileSync(theme)).digest('hex'),
2361
+ );
1317
2362
  for (const [p, h] of after) if (before.get(p) !== h) wrote.set(p, h);
1318
2363
  for (const p of before.keys()) if (!after.has(p)) wrote.set(p, null);
1319
2364
  }
@@ -1387,7 +2432,7 @@ export function refuseLinks(cwd, slug) {
1387
2432
  `${path.relative(cwd, p) || p} is a link; the editor writes a theme's own files only, never through a link. Replace the link with a copy of what it points to. Nothing was changed.`,
1388
2433
  [
1389
2434
  {
1390
- name: `cp -rL ${q(path.relative(cwd, p))} ${q(`${path.relative(cwd, p)}.copy`)}`,
2435
+ name: `cp -rL ${quoteCommandArgument(path.relative(cwd, p))} ${quoteCommandArgument(`${path.relative(cwd, p)}.copy`)}`,
1391
2436
  reason: 'copy what it points to, then put the copy in its place',
1392
2437
  },
1393
2438
  ],
@@ -1427,18 +2472,6 @@ export function settingsStamp(data) {
1427
2472
  return `${hash} (CLI ${cliVersion()})`;
1428
2473
  }
1429
2474
 
1430
- /**
1431
- * Whether the theme's build was made, whole, from these settings by this
1432
- * CLI (a command stopped mid-build, or settings edited by hand, leave it
1433
- * behind).
1434
- * @param {string} cwd
1435
- * @param {string} slug
1436
- * @param {ThemeData} data
1437
- */
1438
- export function buildCurrent(cwd, slug, data) {
1439
- return staleBuild(cwd, slug, data) == null;
1440
- }
1441
-
1442
2475
  /**
1443
2476
  * Why the theme's build does not match its settings, in words, or null when
1444
2477
  * it does: a file missing, another CLI version, settings changed since the
@@ -1450,8 +2483,16 @@ export function buildCurrent(cwd, slug, data) {
1450
2483
  */
1451
2484
  export function staleBuild(cwd, slug, data) {
1452
2485
  const f = themeFiles(cwd, slug);
1453
- const missing = [f.js, f.css, f.settingsTs].find(p => !fs.existsSync(p));
1454
- if (missing) return `${path.basename(missing)} was missing`;
2486
+ // The generated colors are part of the build when a color dial is set.
2487
+ const colors = data.settings.some(
2488
+ s => s.source === 'dial' && PALETTE_DIALS.includes(s.thing),
2489
+ )
2490
+ ? [path.join(cwd, paletteFiles(slug).palette)]
2491
+ : [];
2492
+ const missing = [f.js, f.css, f.settingsTs, ...colors].find(
2493
+ p => !fs.existsSync(p),
2494
+ );
2495
+ if (missing) return `${path.relative(f.dir, missing)} was missing`;
1455
2496
  const ts = fs.readFileSync(f.settingsTs, 'utf8');
1456
2497
  const stamp =
1457
2498
  /\/\/ Built from settings ([0-9a-f]{16}) \(CLI ([^)]+)\)\./.exec(ts);
@@ -1459,36 +2500,69 @@ export function staleBuild(cwd, slug, data) {
1459
2500
  if (stamp && stamp[1] === hash && stamp[2] !== cliVersion())
1460
2501
  return `it was built by CLI ${stamp[2]}, and this is ${cliVersion()}`;
1461
2502
  if (!stamp || stamp[1] !== hash)
1462
- return `${slug}.settings.json changed after the build (edited by hand, or by another tool)`;
2503
+ return `${slug}.settings.json does not match the build (a command stopped part way, a hand edit, or another tool)`;
2504
+ // A base theme updated since the build changes what the theme builds on.
2505
+ if (data.like) {
2506
+ const built = new RegExp(
2507
+ `// Built on @astryxdesign/theme-${data.like} ([^.\\s]+(?:\\.[^.\\s]+)*)\\.`,
2508
+ ).exec(ts)?.[1];
2509
+ const now = baseVersionOf(cwd, data.like);
2510
+ if (built && now && built !== now)
2511
+ return `@astryxdesign/theme-${data.like} is ${now} now, and the build was made on ${built}`;
2512
+ }
2513
+ // By content, never by file times (an editor's re-save or a checkout
2514
+ // changes those): a generated module cut short, or built outputs whose
2515
+ // header names another CLI than the settings were written by (a build
2516
+ // stopped after the settings module was written).
2517
+ const builtBy = (/** @type {string} */ file) =>
2518
+ /^ \* CLI: @astryxdesign\/cli@(\S+)$/m.exec(
2519
+ fs.readFileSync(file, 'utf8').slice(0, 600),
2520
+ )?.[1] ?? null;
1463
2521
  if (
1464
2522
  !ts.trimEnd().endsWith('});') ||
1465
- fs.statSync(f.css).mtimeMs < fs.statSync(f.settingsTs).mtimeMs - 1000
2523
+ [f.css, f.js].some(file => {
2524
+ const by = builtBy(file);
2525
+ return by != null && by !== stamp[2];
2526
+ })
1466
2527
  )
1467
2528
  return 'the last build did not finish (a command stopped while building)';
2529
+ // A built stylesheet cut short (a crash, a bad merge) is built again, as
2530
+ // an unreadable built module is.
2531
+ try {
2532
+ postcss.parse(fs.readFileSync(f.css, 'utf8'));
2533
+ } catch {
2534
+ return `${slug}.css is not valid CSS (cut short or damaged)`;
2535
+ }
1468
2536
  return null;
1469
2537
  }
1470
2538
 
1471
- /** @param {string} dir */
1472
- function removeIfEmpty(dir) {
2539
+ /**
2540
+ * The installed version of a base theme package, or null.
2541
+ * @param {string} cwd
2542
+ * @param {string} like
2543
+ */
2544
+ function baseVersionOf(cwd, like) {
2545
+ const pkg = `@astryxdesign/theme-${like}`;
1473
2546
  try {
1474
- fs.rmdirSync(dir);
2547
+ // The package exports no package.json: find it above its built module.
2548
+ let dir = path.dirname(
2549
+ createRequire(path.join(cwd, 'package.json')).resolve(`${pkg}/built`),
2550
+ );
2551
+ for (let i = 0; i < 6; i++, dir = path.dirname(dir)) {
2552
+ const file = path.join(dir, 'package.json');
2553
+ if (!fs.existsSync(file)) continue;
2554
+ const json = JSON.parse(fs.readFileSync(file, 'utf8'));
2555
+ if (json.name === pkg) return String(json.version ?? '') || null;
2556
+ }
2557
+ return null;
1475
2558
  } catch {
1476
- // Not empty, or gone already.
2559
+ return null;
1477
2560
  }
1478
2561
  }
1479
2562
 
1480
2563
  /** The undo steps a theme keeps; older ones are dropped. */
1481
2564
  export const HISTORY_STEPS = 80;
1482
2565
 
1483
- /**
1484
- * Write a file whole: a new file beside it, renamed into place.
1485
- * @param {string} file
1486
- * @param {string} text
1487
- */
1488
- export function writeAtomic(file, text) {
1489
- writeWhole(file, text);
1490
- }
1491
-
1492
2566
  /**
1493
2567
  * A theme's undo history: the settings text before each change, oldest
1494
2568
  * first, and how many damaged steps were dropped. Every step after the
@@ -1533,13 +2607,20 @@ export function readHistory(file) {
1533
2607
  * @param {Ctx} ctx
1534
2608
  * @param {string} slug
1535
2609
  * @param {ThemeData} data
1536
- * @param {{history: boolean, historyAfter?: string[]}} options
1537
- * `historyAfter`: the history to write with the change (a step back pops it)
2610
+ * @param {{history: boolean, historyAfter?: string[], radii?: Record<string, string> | null}} options
2611
+ * `historyAfter`: the history to write with the change (a step back pops it);
2612
+ * `radii`: the whole-theme radii the step being restored was built with
1538
2613
  */
1539
- export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
2614
+ export async function commitTheme(
2615
+ ctx,
2616
+ slug,
2617
+ data,
2618
+ {history, historyAfter, radii},
2619
+ ) {
1540
2620
  const {cwd} = ctx.project;
1541
2621
  const f = themeFiles(cwd, slug);
1542
2622
  refuseLinks(cwd, slug);
2623
+ refuseThemeSource(cwd, slug);
1543
2624
  const snapBefore = fs.existsSync(f.settings)
1544
2625
  ? fs.readFileSync(f.settings, 'utf8')
1545
2626
  : null;
@@ -1562,7 +2643,10 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
1562
2643
  a != null &&
1563
2644
  JSON.stringify({...a, lifted: undefined}) ===
1564
2645
  JSON.stringify({...data, lifted: undefined});
1565
- if (history && same(parseSettings(snapBefore)) && fs.existsSync(f.js))
2646
+ // A no-op change still mends a build that does not match the settings
2647
+ // (an undo stopped part way): it is built again, with no new step.
2648
+ const noop = history && same(parseSettings(snapBefore));
2649
+ if (noop && fs.existsSync(f.js) && !staleBuild(cwd, slug, data))
1566
2650
  return {
1567
2651
  changed: [],
1568
2652
  res: {light: {}, dark: {}},
@@ -1574,10 +2658,65 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
1574
2658
  };
1575
2659
  const resBefore =
1576
2660
  snapBefore && fs.existsSync(f.js)
1577
- ? await resolvedTokens(ctx, slug).catch(() => null)
2661
+ ? await resolvedTokens(ctx, slug).catch(() => {
2662
+ // The last build is damaged: the change still stands, and the
2663
+ // result says why it lists no token changes.
2664
+ notes.push(
2665
+ `the last build (${path.basename(f.js)}) could not be read, so the token changes are not listed; the theme is built again`,
2666
+ );
2667
+ return null;
2668
+ })
1578
2669
  : null;
1579
2670
  const before = parseSettings(snapBefore);
1580
2671
  const liftedBefore = new Set(before?.lifted ?? []);
2672
+ // A change that leaves every color setting as it was keeps the shades the
2673
+ // theme already shows: a theme an earlier editor built keeps its colors
2674
+ // until a color, the mode or the base changes, and undo brings them back.
2675
+ /** @param {ThemeData | null} d */
2676
+ const colorKey = d =>
2677
+ d &&
2678
+ JSON.stringify({
2679
+ mode: d.mode ?? 'both',
2680
+ like: d.like ?? null,
2681
+ colors: d.settings.filter(
2682
+ x =>
2683
+ (x.source === 'dial' &&
2684
+ (PALETTE_DIALS.includes(x.thing) || x.thing === 'vibrancy')) ||
2685
+ (x.source === 'token' && isColorToken(x.thing)),
2686
+ ),
2687
+ });
2688
+ // A module edited by hand (it says "do not edit") keeps nothing: it is
2689
+ // built over from the settings, as its header says.
2690
+ const moduleNow = fs.existsSync(f.settingsTs)
2691
+ ? fs.readFileSync(f.settingsTs, 'utf8')
2692
+ : null;
2693
+ ctx.keepStops =
2694
+ before &&
2695
+ colorKey(before) === colorKey(data) &&
2696
+ moduleNow &&
2697
+ moduleUnedited(moduleNow) !== false
2698
+ ? stopsIn(moduleNow)
2699
+ : null;
2700
+ // The same for the whole-theme radii: kept while corners and the base
2701
+ // stay as they are; a step back restores the radii it was built with.
2702
+ /** @param {ThemeData | null} d */
2703
+ const cornersKey = d =>
2704
+ d &&
2705
+ JSON.stringify({
2706
+ like: d.like ?? null,
2707
+ corners: d.settings.filter(x => x.thing === 'corners' && !x.on),
2708
+ // An exact radius token feeds the built radii too.
2709
+ tokens: d.settings.filter(
2710
+ x => x.source === 'token' && /^--radius-/.test(x.thing),
2711
+ ),
2712
+ });
2713
+ const radiiNow =
2714
+ moduleNow && moduleUnedited(moduleNow) !== false
2715
+ ? radiiIn(moduleNow)
2716
+ : null;
2717
+ ctx.keepRadii =
2718
+ radii ??
2719
+ (before && cornersKey(before) === cornersKey(data) ? radiiNow : null);
1581
2720
  // What this run writes is recorded as it writes it, so a failed change
1582
2721
  // puts back exactly that and nothing else.
1583
2722
  const rootMade = !fs.existsSync(f.root);
@@ -1590,28 +2729,52 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
1590
2729
  /** @type {{warnings: string[], lifted: string[], notes: string[]}} */
1591
2730
  let built;
1592
2731
  try {
1593
- built = await buildTheme(ctx, slug, data);
2732
+ refuseIfLockLost();
2733
+ try {
2734
+ built = await buildTheme(ctx, slug, data);
2735
+ } finally {
2736
+ ctx.keepStops = null;
2737
+ }
2738
+ // The build writes its outputs itself: a lock lost meanwhile is seen
2739
+ // before anything else is written.
2740
+ refuseIfLockLost();
1594
2741
  data.lifted = built.lifted;
1595
2742
  // The undo step and the settings are part of the change: written whole,
1596
- // inside the rollback, the history before the settings.
2743
+ // inside the rollback, the settings first. A command stopped between
2744
+ // the two leaves the change saved with the history one step short (or,
2745
+ // for an undo, a top step equal to the settings, which undo skips),
2746
+ // never a step that undoes nothing or a lost step.
1597
2747
  await track(f.dir, wrote, () => {
2748
+ writeWhole(f.settings, `${JSON.stringify(data, null, 2)}\n`);
1598
2749
  if (historyAfter)
1599
- writeAtomic(
2750
+ writeWhole(
1600
2751
  f.history,
1601
2752
  JSON.stringify(historyAfter.slice(-HISTORY_STEPS)),
1602
2753
  );
1603
- else if (snapBefore && history)
1604
- writeAtomic(
2754
+ else if (snapBefore && history && !noop)
2755
+ writeWhole(
1605
2756
  f.history,
1606
- JSON.stringify([...past, snapBefore].slice(-HISTORY_STEPS)),
2757
+ JSON.stringify(
2758
+ [...past, withBuilt(snapBefore, radiiNow)].slice(-HISTORY_STEPS),
2759
+ ),
1607
2760
  );
1608
- writeAtomic(f.settings, `${JSON.stringify(data, null, 2)}\n`);
1609
2761
  });
2762
+ // Settings written whole: a `new` marker left beside them (a `new`
2763
+ // stopped after its theme was made) has nothing left to finish.
2764
+ clearNewMarker(f.dir);
1610
2765
  } catch (e) {
2766
+ // A command that lost its lock while stopped owns none of these files
2767
+ // now: it puts nothing back and deletes nothing (that would undo the
2768
+ // other command's change).
2769
+ if (/** @type {any} */ (e)?.lockLost || !lockHeld()) {
2770
+ ctx.keepStops = null;
2771
+ if (/** @type {any} */ (e)?.lockLost) throw e;
2772
+ refuseIfLockLost();
2773
+ }
1611
2774
  const {failed, skipped} = restoreWritten(was, wrote);
1612
- removeIfEmpty(path.join(f.dir, 'tokens'));
1613
- if (dirMade) removeIfEmpty(f.dir);
1614
- if (rootMade) removeIfEmpty(f.root);
2775
+ removeEmptyFolder(path.join(f.dir, 'tokens'));
2776
+ if (dirMade) removeEmptyFolder(f.dir);
2777
+ if (rootMade) removeEmptyFolder(f.root);
1615
2778
  if (failed.length || skipped.length)
1616
2779
  throw new AstryxError(
1617
2780
  `The change failed (${e instanceof Error ? e.message.split('\n')[0] : String(e)}). ${failed.length ? `These files could not be put back: ${failed.join(', ')}. ` : ''}${skipped.length ? `These files changed while it ran, so they were left as they are: ${skipped.join(', ')}. ` : ''}Run ${P} show ${slug} to rebuild from the settings.`,
@@ -1622,7 +2785,12 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
1622
2785
  if (['EACCES', 'EPERM', 'ENOSPC', 'EROFS', 'EIO', 'EISDIR'].includes(code))
1623
2786
  throw new AstryxError(
1624
2787
  `Could not write the theme files (${code}), so the change was undone. Free space or fix the permission, then run the command again.`,
1625
- [],
2788
+ [
2789
+ {
2790
+ name: `ls -ld ${quoteCommandArgument(themeFiles(ctx.project.cwd, slug).dir)}`,
2791
+ reason: 'see who owns the theme folder',
2792
+ },
2793
+ ],
1626
2794
  ERROR_CODES.ERR_WRITE_FAILED,
1627
2795
  );
1628
2796
  // The color config's own refusals already name the file and the fix.
@@ -1630,7 +2798,9 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
1630
2798
  e instanceof AstryxError &&
1631
2799
  (e.code === ERROR_CODES.ERR_UNKNOWN_THEME ||
1632
2800
  e.code === ERROR_CODES.ERR_THEME_INVALID ||
1633
- e.code === ERROR_CODES.ERR_PALETTE_GENERATION)
2801
+ e.code === ERROR_CODES.ERR_PALETTE_GENERATION ||
2802
+ e.code === ERROR_CODES.ERR_WRITE_FAILED ||
2803
+ e.code === ERROR_CODES.ERR_THEME_BUSY)
1634
2804
  )
1635
2805
  throw e;
1636
2806
  const why = (e instanceof Error ? e.message : String(e))
@@ -1665,18 +2835,45 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
1665
2835
  res = await resolvedTokens(ctx, slug);
1666
2836
  const modes = modesOf(data);
1667
2837
  if (resBefore) {
1668
- for (const m of modes) {
2838
+ /** @param {unknown} a @param {unknown} b */
2839
+ const same = (a, b) =>
2840
+ String(a).toLowerCase() === String(b).toLowerCase();
2841
+ // Both modes are compared: a theme that becomes one-mode changes what
2842
+ // the other mode's visitors see, though it no longer has that mode.
2843
+ for (const m of /** @type {const} */ (['light', 'dark'])) {
2844
+ const own = modes.includes(m);
1669
2845
  for (const k of Object.keys(res[m])) {
1670
- if (resBefore[m][k] === res[m][k]) continue;
2846
+ // A change of letter case alone (#FFFFFF, #ffffff) is no change.
2847
+ if (same(resBefore[m][k], res[m][k])) continue;
1671
2848
  const modal = MODAL.has(ctx.C.typeOf(k));
1672
- if (!modal && m === 'dark' && modes.length > 1) continue;
2849
+ if (!modal && m === 'dark') continue;
2850
+ // A one-mode theme writes its mode on both sides: the other side
2851
+ // that moved with it says nothing new, and a setting made for the
2852
+ // mode it dropped (and what reads it) is named as not applied
2853
+ // instead.
2854
+ if (
2855
+ modal &&
2856
+ !own &&
2857
+ ((same(resBefore[m][k], resBefore[modes[0]][k]) &&
2858
+ same(res[m][k], res[modes[0]][k])) ||
2859
+ data.settings.some(
2860
+ x =>
2861
+ x.source === 'token' &&
2862
+ x.mode === m &&
2863
+ (x.thing === k || same(x.value, resBefore[m][k])),
2864
+ ))
2865
+ )
2866
+ continue;
1673
2867
  changed.push(
1674
- `${k}${modal && modes.length > 1 ? ` (${m})` : ''}: ${resBefore[m][k]} -> ${res[m][k]}`,
2868
+ `${k}${modal && (modes.length > 1 || !own) ? ` (${m})` : ''}: ${resBefore[m][k]} -> ${res[m][k]}`,
1675
2869
  );
1676
2870
  }
1677
2871
  }
1678
2872
  }
1679
2873
  problems = await contrastProblems(ctx, data, res);
2874
+ // What cannot be measured is a note, not a problem.
2875
+ notes.push(...problems.filter(x => x.startsWith('not checked')));
2876
+ problems = problems.filter(x => !x.startsWith('not checked'));
1680
2877
  } catch (e) {
1681
2878
  ctx.unchecked ??= `checking it failed: ${e instanceof Error ? e.message : String(e)}`;
1682
2879
  }
@@ -1693,19 +2890,27 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
1693
2890
 
1694
2891
  /** @param {Ctx} ctx @param {ThemeData} data */
1695
2892
  export function fontPackages(ctx, data) {
1696
- /** @type {Array<{pkg: string, family: string, installed: boolean}>} */
2893
+ /** @type {Array<{pkg: string, family: string, installed: boolean, of: Setting}>} */
1697
2894
  const out = [];
1698
- for (const s of data.settings) {
1699
- if (s.thing !== 'font') continue;
1700
- const {pkg, family} = fontOf(s.value);
1701
- if (!pkg || out.some(x => x.pkg === pkg)) continue;
1702
- let installed = true;
2895
+ /** @param {string} pkg */
2896
+ const isInstalled = pkg => {
1703
2897
  try {
1704
2898
  ctx.project.req.resolve(`${pkg}/package.json`);
2899
+ return true;
1705
2900
  } catch {
1706
- installed = false;
2901
+ return false;
1707
2902
  }
1708
- out.push({pkg, family: family.replace(/["']/g, ''), installed});
2903
+ };
2904
+ for (const s of data.settings) {
2905
+ if (s.thing !== 'font') continue;
2906
+ const {pkg: known, family} = fontOf(s.value);
2907
+ const name = family.replace(/["']/g, '');
2908
+ // An installed @fontsource package of the family always loads it, even
2909
+ // for a family some systems ship.
2910
+ const own = `@fontsource/${name.toLowerCase().replace(/\s+/g, '-')}`;
2911
+ const pkg = known ?? (isInstalled(own) ? own : null);
2912
+ if (!pkg || out.some(x => x.pkg === pkg)) continue;
2913
+ out.push({pkg, family: name, installed: isInstalled(pkg), of: s});
1709
2914
  }
1710
2915
  return out;
1711
2916
  }