@astryxdesign/cli 0.7.16 → 0.7.17-canary.gb36275e

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 (239) hide show
  1. package/README.md +13 -23
  2. package/api/build/_adapter.d.mts +5 -0
  3. package/api/build/_adapter.mjs +49 -34
  4. package/api/build/blocks/blocks.d.mts +7 -5
  5. package/api/build/blocks/blocks.mjs +113 -26
  6. package/api/build/build.doc.mjs +2 -1
  7. package/api/build/kit/rank.mjs +59 -12
  8. package/api/build/kit/weights.d.mts +16 -3
  9. package/api/build/kit/weights.json +1 -1
  10. package/api/build/kit/weights.mjs +238 -31
  11. package/api/build/kit/word-model.d.mts +23 -0
  12. package/api/build/kit/word-model.mjs +46 -0
  13. package/api/build/kit/words.d.mts +42 -0
  14. package/api/build/kit/words.mjs +82 -1
  15. package/api/component/__fixtures__/resolutions/modules.txt +4 -5
  16. package/api/component/list/list.d.mts +1 -1
  17. package/api/component/list/list.mjs +46 -5
  18. package/api/discover/_adapter.d.mts +1 -1
  19. package/api/docs/_adapter.d.mts +26 -2
  20. package/api/docs/_adapter.mjs +217 -5
  21. package/api/docs/docs.d.mts +3 -0
  22. package/api/docs/docs.doc.mjs +7 -1
  23. package/api/docs/docs.mjs +12 -0
  24. package/api/docs/docs.type.d.mts +5 -0
  25. package/api/docs/docs.type.mjs +2 -0
  26. package/api/docs/node/node.mjs +1 -1
  27. package/api/doctor/_adapter.d.mts +27 -5
  28. package/api/doctor/_adapter.mjs +77 -6
  29. package/api/doctor/built-checks.mjs +38 -13
  30. package/api/doctor/doctor.d.mts +4 -3
  31. package/api/doctor/doctor.mjs +14 -7
  32. package/api/doctor/theme-checks.mjs +121 -17
  33. package/api/render/_adapter.mjs +531 -192
  34. package/api/render/render.doc.mjs +11 -3
  35. package/api/render/render.type.d.mts +30 -0
  36. package/api/render/render.type.mjs +19 -0
  37. package/api/search/ORDERING.md +1 -1
  38. package/api/search/_candidate-score.mjs +51 -32
  39. package/api/search/_fit-order.mjs +3 -3
  40. package/api/search/_result.d.mts +5 -5
  41. package/api/search/_score.d.mts +6 -1
  42. package/api/search/_score.mjs +15 -3
  43. package/api/search/search.d.mts +1 -1
  44. package/api/theme/_adapter.mjs +10 -0
  45. package/api/theme/build/build.d.mts +47 -0
  46. package/api/theme/build/build.mjs +147 -25
  47. package/api/theme/theme.type.d.mts +10 -0
  48. package/api/theme/theme.type.mjs +7 -1
  49. package/api/theme-edit/_adapter.d.mts +48 -0
  50. package/api/theme-edit/_adapter.mjs +675 -42
  51. package/api/theme-edit/_check.d.mts +28 -22
  52. package/api/theme-edit/_check.mjs +1481 -252
  53. package/api/theme-edit/_color.d.mts +9 -0
  54. package/api/theme-edit/_color.mjs +41 -1
  55. package/api/theme-edit/_compiler.mjs +9 -0
  56. package/api/theme-edit/_context.mjs +60 -3
  57. package/api/theme-edit/_css.mjs +21 -1
  58. package/api/theme-edit/_edit.d.mts +22 -0
  59. package/api/theme-edit/_edit.mjs +1196 -88
  60. package/api/theme-edit/_how-commands.d.mts +57 -0
  61. package/api/theme-edit/_how-commands.mjs +536 -1
  62. package/api/theme-edit/_how-question.d.mts +65 -0
  63. package/api/theme-edit/_how-question.mjs +4401 -225
  64. package/api/theme-edit/_how.mjs +104 -4
  65. package/api/theme-edit/_marks.d.mts +31 -5
  66. package/api/theme-edit/_marks.mjs +57 -5
  67. package/api/theme-edit/_normal.d.mts +153 -0
  68. package/api/theme-edit/_normal.mjs +661 -0
  69. package/api/theme-edit/_palette.mjs +10 -4
  70. package/api/theme-edit/_parts.d.mts +8 -0
  71. package/api/theme-edit/_parts.mjs +103 -2
  72. package/api/theme-edit/_preview-app.d.mts +7 -1
  73. package/api/theme-edit/_preview-app.mjs +205 -17
  74. package/api/theme-edit/_preview.d.mts +64 -8
  75. package/api/theme-edit/_preview.mjs +447 -89
  76. package/api/theme-edit/_settings.d.mts +176 -5
  77. package/api/theme-edit/_settings.mjs +1936 -128
  78. package/api/theme-edit/_tables.d.mts +6 -0
  79. package/api/theme-edit/_tables.mjs +32 -1
  80. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  81. package/api/theme-edit/theme-edit.type.mjs +4 -1
  82. package/api/theme-edit/themeEditPreviewApp.doc.mjs +3 -3
  83. package/assets/codemods/run-codemod.mjs +73 -6
  84. package/assets/codemods/transforms/next/index.mjs +11 -1
  85. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  86. package/assets/docs/author-a-theme.doc.mjs +1 -0
  87. package/assets/docs/theme.doc.dense.mjs +2 -2
  88. package/assets/docs/theme.doc.mjs +1 -1
  89. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  90. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  91. package/assets/docs/tree/render-pages.doc.mjs +43 -2
  92. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  93. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  94. package/assets/docs/use-a-theme.doc.mjs +1 -1
  95. package/assets/docs.generated.json +2 -2
  96. package/assets/self-audit.generated.json +1 -1
  97. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  98. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  99. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  100. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  101. package/assets/templates/components.generated.json +1 -1
  102. package/assets/templates/pages/ai-chat/template.doc.mjs +5 -4
  103. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +2 -1
  104. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  105. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  106. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  107. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  108. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  109. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  110. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  111. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  112. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  113. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  114. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  115. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  116. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  117. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  118. package/assets/templates/pages/editor/template.doc.mjs +2 -8
  119. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  120. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  121. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  122. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  123. package/assets/templates/pages/ide/page.tsx +24 -2
  124. package/assets/templates/pages/kanban-board/template.doc.mjs +1 -9
  125. package/assets/templates/pages/library/template.doc.mjs +4 -1
  126. package/assets/templates/pages/login/template.doc.mjs +2 -1
  127. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  128. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  129. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  130. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  131. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  132. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  133. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  134. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  135. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  136. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  137. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  138. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  139. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  140. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  141. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  142. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  143. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -9
  144. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  145. package/authoring/debug/parse.d.mts +3 -3
  146. package/authoring/doctypes/_schema.d.mts +3 -3
  147. package/authoring/doctypes/command/command.doc.mjs +1 -1
  148. package/authoring/doctypes/template/template.doc.mjs +1 -1
  149. package/authoring/doctypes/template/type.ts +9 -0
  150. package/clients/cli/bin/astryx.mjs +6 -9
  151. package/clients/cli/build-id.generated.json +1 -1
  152. package/clients/cli/commands/component.doc.mjs +1 -1
  153. package/clients/cli/commands/component.mjs +20 -2
  154. package/clients/cli/commands/docs.doc.mjs +7 -1
  155. package/clients/cli/commands/docs.mjs +3 -1
  156. package/clients/cli/commands/doctor.mjs +22 -14
  157. package/clients/cli/commands/experimental/render.mjs +32 -1
  158. package/clients/cli/commands/experimental/theme.mjs +65 -14
  159. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  160. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  161. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  162. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  163. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  164. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  165. package/clients/cli/commands/search.doc.mjs +2 -1
  166. package/clients/cli/commands/search.mjs +6 -1
  167. package/clients/cli/commands/template.mjs +4 -2
  168. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  169. package/clients/cli/commands/theme.doc.mjs +1 -1
  170. package/clients/cli/commands/theme.mjs +153 -5
  171. package/clients/cli/commands/upgrade.mjs +42 -7
  172. package/clients/cli/index.mjs +1 -1
  173. package/clients/cli/lib/component-format.mjs +205 -98
  174. package/clients/cli/lib/hook-format.mjs +9 -19
  175. package/clients/cli/manifest.generated.json +1 -1
  176. package/foundation/agent-docs/agent-docs.mjs +1 -1
  177. package/foundation/config/theme-state.d.mts +13 -1
  178. package/foundation/config/theme-state.mjs +47 -7
  179. package/foundation/discovery/component-discovery.d.mts +11 -0
  180. package/foundation/discovery/component-discovery.mjs +27 -2
  181. package/foundation/discovery/component-replacement.mjs +130 -1
  182. package/foundation/discovery/entry-name-files.d.mts +43 -0
  183. package/foundation/discovery/entry-name-files.mjs +264 -0
  184. package/foundation/discovery/hook-discovery.d.mts +8 -2
  185. package/foundation/discovery/hook-discovery.mjs +20 -7
  186. package/foundation/discovery/package-exports.d.mts +10 -0
  187. package/foundation/discovery/package-exports.mjs +56 -3
  188. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  189. package/foundation/discovery/runner-allowlist.mjs +2 -0
  190. package/foundation/discovery/template-adapter.d.mts +52 -0
  191. package/foundation/discovery/template-adapter.mjs +173 -10
  192. package/foundation/discovery/theme-imports.d.mts +14 -0
  193. package/foundation/discovery/theme-imports.mjs +43 -1
  194. package/foundation/doc-compiler/import.mjs +7 -1
  195. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  196. package/foundation/doc-compiler/stored-docs.d.mts +22 -0
  197. package/foundation/doc-compiler/stored-docs.mjs +49 -0
  198. package/foundation/fs/cache-eviction.d.mts +21 -0
  199. package/foundation/fs/cache-eviction.mjs +73 -0
  200. package/foundation/fs/gather-cache.d.mts +25 -4
  201. package/foundation/fs/gather-cache.mjs +163 -53
  202. package/foundation/fs/jiti-cache.d.mts +19 -1
  203. package/foundation/fs/jiti-cache.mjs +130 -6
  204. package/foundation/fs/kept-tree.d.mts +60 -0
  205. package/foundation/fs/kept-tree.mjs +154 -0
  206. package/foundation/fs/module-loader.d.mts +18 -2
  207. package/foundation/fs/module-loader.mjs +92 -20
  208. package/foundation/identity/provider-identity.d.mts +6 -0
  209. package/foundation/identity/provider-identity.mjs +10 -1
  210. package/foundation/render/embedded-imports.d.mts +5 -4
  211. package/foundation/render/embedded-imports.mjs +7 -16
  212. package/foundation/render/file-header.d.mts +66 -0
  213. package/foundation/render/file-header.mjs +118 -0
  214. package/foundation/render/host-answer.d.mts +18 -0
  215. package/foundation/render/host-answer.mjs +46 -0
  216. package/foundation/render/host-exit.d.mts +1 -0
  217. package/foundation/render/host-exit.mjs +6 -1
  218. package/foundation/render/html-reader.d.mts +55 -2
  219. package/foundation/render/html-reader.mjs +145 -26
  220. package/foundation/render/markup-edits.d.mts +57 -0
  221. package/foundation/render/markup-edits.mjs +182 -0
  222. package/foundation/render/page-host.mjs +29 -12
  223. package/foundation/render/page-worker.mjs +83 -13
  224. package/foundation/render/render-page.d.mts +34 -2
  225. package/foundation/render/render-page.mjs +210 -29
  226. package/foundation/render/source-block.d.mts +73 -6
  227. package/foundation/render/source-block.mjs +170 -19
  228. package/foundation/render/ts-paths.d.mts +53 -6
  229. package/foundation/render/ts-paths.mjs +286 -41
  230. package/foundation/response/error-codes.d.mts +3 -1
  231. package/foundation/response/error-codes.d.ts +1 -0
  232. package/foundation/response/error-codes.doc.mjs +12 -1
  233. package/foundation/response/error-codes.mjs +10 -0
  234. package/foundation/text/string-utils.d.mts +3 -2
  235. package/foundation/text/string-utils.mjs +16 -3
  236. package/foundation/text/suggest-order.d.mts +9 -0
  237. package/foundation/text/suggest-order.mjs +13 -0
  238. package/host/index.mjs +8 -6
  239. package/package.json +6 -6
@@ -10,7 +10,7 @@
10
10
  * @position api/theme-edit — storage and compile for the theme commands
11
11
  */
12
12
 
13
- import {EDITOR_GENERATED_MARK} from './_marks.mjs';
13
+ import {APP_COPY_MARK, EDITOR_GENERATED_MARK} from './_marks.mjs';
14
14
  import {parse as parseModule} from '@babel/parser';
15
15
  import {createHash} from 'node:crypto';
16
16
  import * as fs from 'node:fs';
@@ -25,8 +25,9 @@ import {AstryxError} from '../error.mjs';
25
25
  import {logger} from '../logger.mjs';
26
26
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
27
27
  import {levenshteinDistance} from '../../foundation/text/levenshtein.mjs';
28
- import {themeBuildForReport} from '../theme/build/build.mjs';
28
+ import {oneColorMode, themeBuildForReport} from '../theme/build/build.mjs';
29
29
  import {
30
+ MODE_WORDS,
30
31
  AUTO_SPREAD,
31
32
  CORNERS,
32
33
  DIALS,
@@ -46,6 +47,7 @@ import {
46
47
  WRAPPED_PARTS,
47
48
  CARD_LIKE,
48
49
  } from './_tables.mjs';
50
+ import {cleanDialValue, typoLimit, typoNear} from './_normal.mjs';
49
51
  import {
50
52
  alphaOf,
51
53
  colorProblem,
@@ -116,7 +118,7 @@ setOwnTokenReader((cwd, slug) => ownSourceTokenValues(cwd, slug));
116
118
  /** What lifted secondary text sits on: the contrast check measures it there. */
117
119
  const LIFT_GROUND_TOKENS = new Set(LIFT_PARTS.map(([, , g]) => g));
118
120
 
119
- /** @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, derived?: Record<string, Array<{property: string, vars?: string[], replaces?: boolean, expand?: string}>>}} Ctx */
121
+ /** @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, sizeNotes?: string[], compileNotes?: string[], derived?: Record<string, Array<{property: string, vars?: string[], replaces?: boolean, expand?: string}>>}} Ctx */
120
122
  /** @typedef {import('./_parts.mjs').PaintSide} PaintSide */
121
123
  /** @typedef {import('./_parts.mjs').TextPair} TextPair */
122
124
 
@@ -197,20 +199,35 @@ export function themeFiles(cwd, slug) {
197
199
  }
198
200
 
199
201
  /** Files a system or a tool puts in any folder; a folder of only these is empty. */
200
- export const FOLDER_JUNK = new Set(['.DS_Store', '.gitkeep', 'Thumbs.db']);
202
+ export const FOLDER_JUNK = new Set([
203
+ '.DS_Store',
204
+ '.gitkeep',
205
+ 'Thumbs.db',
206
+ 'desktop.ini',
207
+ ]);
201
208
 
202
209
  /**
203
210
  * Whether `dir` holds nothing of anyone's: absent, empty, or only system
204
211
  * files (what `git rm -r` or a branch switch leaves). A path that is not a
205
212
  * folder, or one that does not read, is not empty.
206
213
  * @param {string} dir
214
+ * @returns {boolean}
207
215
  */
208
216
  export function folderIsEmpty(dir) {
209
217
  if (!fs.existsSync(dir)) return true;
210
218
  try {
219
+ // A folder holding only empty folders (an empty tokens/) holds nothing
220
+ // either; a link is never followed.
211
221
  return (
212
222
  fs.lstatSync(dir).isDirectory() &&
213
- fs.readdirSync(dir).every(n => FOLDER_JUNK.has(n))
223
+ fs
224
+ .readdirSync(dir)
225
+ .every(
226
+ n =>
227
+ FOLDER_JUNK.has(n) ||
228
+ (fs.lstatSync(path.join(dir, n)).isDirectory() &&
229
+ folderIsEmpty(path.join(dir, n))),
230
+ )
214
231
  );
215
232
  } catch {
216
233
  return false;
@@ -485,21 +502,48 @@ export const shown = (cwd, f) =>
485
502
  * @param {number} [n]
486
503
  */
487
504
  export function nearest(x, list, n = 3) {
505
+ // A phrase that negates a word (not round, no caps, unbold,
506
+ // rounded-none) never has that word as its nearest: it asks the opposite.
507
+ // A typo of a listed keyword that itself starts with no- or not-
508
+ // (`not-alowed` for not-allowed, `no-repat` for no-repeat) is no
509
+ // negation: it is read as a typo.
510
+ if (
511
+ negates(x) &&
512
+ ![...list].some(c => /^(no|not)-/.test(c) && typoNear(x, c))
513
+ )
514
+ return [];
515
+ // Within the editor's one typo limit (typoLimit), nearest by edit
516
+ // distance first (brand-drak is brand-dark, not brand); a name one holds
517
+ // inside the other is near too, after the close ones.
518
+ const limit = typoLimit(x);
488
519
  return [...list]
489
520
  .filter(c => c.length > 2)
490
- .map(
491
- c =>
492
- /** @type {[string, number]} */ ([
493
- c,
494
- c.includes(x) || x.includes(c) ? 1 : levenshteinDistance(x, c),
495
- ]),
496
- )
497
- .filter(([, s]) => s <= Math.max(2, Math.floor(x.length / 3)))
521
+ .map(c => {
522
+ const d = levenshteinDistance(x.toLowerCase(), c.toLowerCase(), limit, {
523
+ swaps: true,
524
+ });
525
+ return /** @type {[string, number]} */ ([
526
+ c,
527
+ d <= limit ? d : c.includes(x) || x.includes(c) ? limit + 0.5 : d,
528
+ ]);
529
+ })
530
+ .filter(([, s]) => s <= limit + 0.5)
498
531
  .sort((a, b) => a[1] - b[1])
499
532
  .slice(0, n)
500
533
  .map(([c]) => c);
501
534
  }
502
535
 
536
+ /**
537
+ * Whether typed words negate what they name (`not round`, `no caps`,
538
+ * `anything but blue`, `unbold`, `non-bold`, `rounded-none`).
539
+ * @param {string} x
540
+ */
541
+ export function negates(x) {
542
+ return /(^|[\s-])(not|no|non|without|never|less)([\s-]|$)|anything but|^un(round|bold|rais|outlin|cap)|-none$/i.test(
543
+ String(x).trim(),
544
+ );
545
+ }
546
+
503
547
  /**
504
548
  * A refusal: nothing was changed, and the suggestions lead with the command
505
549
  * that does what the person wanted.
@@ -577,6 +621,79 @@ export function typedThemeName(s) {
577
621
  );
578
622
  }
579
623
 
624
+ /**
625
+ * The theme names a name typed the way the app shows it may mean, most
626
+ * likely first: a path with doubled slashes or `../` (`themes//t`), a file
627
+ * name with or without its folder (`brand.theme.ts`, `tTheme.ts`), the app
628
+ * copy's export (`tTheme`), camelCase (`brandDark`) and spaces
629
+ * (`Brand Dark`) each read as dashes. The caller picks the first that
630
+ * exists, else the first.
631
+ * @param {string} s
632
+ * @returns {string[]}
633
+ */
634
+ export function themeNameReadings(s) {
635
+ const base = unlabeledThemeName(String(s ?? ''))
636
+ .replace(/[\\/]+/g, '/')
637
+ .replace(/^(\.\.?\/)+/, '')
638
+ .replace(/^.*themes\//i, '')
639
+ .replace(/\/.*$/, '')
640
+ .replace(
641
+ /\.(theme\.ts|settings\.(json|ts)|history\.json|css\.d\.ts|d\.ts|doc\.mjs|fonts\.css|css|mjs|js|tsx?)$/i,
642
+ '',
643
+ )
644
+ .trim();
645
+ const noTheme = base.replace(/([a-z0-9])Theme$/, '$1');
646
+ const read = [base, noTheme === base ? '' : noTheme]
647
+ .flatMap(x => [kebab(x), x.toLowerCase()])
648
+ .filter(x => /[a-z]/i.test(x))
649
+ .map(x => slugFor(x));
650
+ // A module name in any letters (brandtheme, brand-theme) last: only
651
+ // when the theme it names exists does it win.
652
+ const moduleNames = read
653
+ .map(n => n.replace(/-?theme$/, ''))
654
+ .filter(n => n && slugOk(n));
655
+ return [...new Set([...read, ...moduleNames])];
656
+ }
657
+
658
+ /**
659
+ * A vibrancy written as set reads typed input: a share of one (0.5) or a
660
+ * percent (50%) is that much of the 0-100 scale, as a whole number. Any
661
+ * other dial's value, or a vibrancy that is no such number, comes back as
662
+ * it was.
663
+ * @param {string} dial
664
+ * @param {string} v
665
+ * @returns {string}
666
+ */
667
+ export function vibrancyMeant(dial, v) {
668
+ if (dial !== 'vibrancy') return v;
669
+ const m = /^(\d*\.?\d+)\s*(%?)$/.exec(v.trim());
670
+ if (!m) return v;
671
+ const n = Number(m[1]);
672
+ const scaled = !m[2] && n > 0 && n < 1 ? n * 100 : n;
673
+ return scaled <= 100 ? String(Math.round(scaled)) : v;
674
+ }
675
+
676
+ /**
677
+ * The mode and base a damaged theme file meant, read the way typed input
678
+ * is: other letters, stray spaces, `_` or a space for a dash (`Dark-Only`,
679
+ * ` Neutral`), and a base written as its package name
680
+ * (`@astryxdesign/theme-neutral`). Each is the cleaned text even when it is
681
+ * no value the editor takes; the caller checks it.
682
+ * @param {any} data
683
+ * @returns {{mode: string, like: string}}
684
+ */
685
+ export function fieldsMeant(data) {
686
+ const mode = String(data?.mode ?? '')
687
+ .trim()
688
+ .toLowerCase()
689
+ .replace(/[\s_]+/g, '-');
690
+ const like = String(data?.like ?? '')
691
+ .trim()
692
+ .toLowerCase()
693
+ .replace(/^@astryxdesign\/theme-/, '');
694
+ return {mode, like};
695
+ }
696
+
580
697
  /**
581
698
  * The settings of a theme, or a refusal naming the command that makes it.
582
699
  * @param {string} cwd
@@ -605,9 +722,22 @@ export function loadTheme(
605
722
  );
606
723
  const plain = typedThemeName(slug);
607
724
  const named = slugFor(plain);
725
+ // brandDark is brand-dark.
726
+ const camelWords = slugFor(
727
+ unlabeledThemeName(String(slug ?? '')).replace(
728
+ /([a-z0-9])([A-Z])/g,
729
+ '$1-$2',
730
+ ),
731
+ );
608
732
  const exists = (/** @type {string} */ n) =>
609
733
  Boolean(n) && fs.existsSync(themeFiles(cwd, n).settings);
610
- const fixed = !exists(named) && exists(whole) ? whole : named;
734
+ // The module or export name (brandTheme, the app copy's brandTheme.ts)
735
+ // names the theme brand: one reader for every way a name is typed.
736
+ const readings = themeNameReadings(slug);
737
+ const fixed =
738
+ [named, whole, camelWords, ...readings].find(exists) ??
739
+ readings[0] ??
740
+ named;
611
741
  const same = fs.existsSync(themeFiles(cwd, fixed).settings) ? fixed : null;
612
742
  // A list where one theme goes (t,u or "t;u"): one theme at a time,
613
743
  // each that exists named; never a new theme made of the list. A name
@@ -741,6 +871,30 @@ export function loadTheme(
741
871
  `themes/${slug} is an empty folder: there is no theme ${slug} yet. new makes it there.`,
742
872
  {run: [`${P} new ${slug}`]},
743
873
  );
874
+ // The editor's own app copy left behind when themes/<slug>/ is gone
875
+ // (a git clean, a wrong rm, a branch switch): `new` makes the theme
876
+ // again and writes the copy over.
877
+ const copyName = `${camel(slug)}Theme`;
878
+ if (
879
+ !same &&
880
+ other &&
881
+ other[1] === `src/themes/${slug}` &&
882
+ !fs.existsSync(f.dir) &&
883
+ [`${copyName}.ts`, `${copyName}.doc.mjs`, `${slug}.fonts.css`].some(n => {
884
+ try {
885
+ return fs
886
+ .readFileSync(path.join(other[0], n), 'utf8')
887
+ .includes(APP_COPY_MARK);
888
+ } catch {
889
+ return false;
890
+ }
891
+ })
892
+ )
893
+ refuse(
894
+ ERROR_CODES.ERR_UNKNOWN_THEME,
895
+ `themes/${slug}/, the theme's source folder, is missing; src/themes/${slug}/ is the editor's app copy of it, left behind. \`new ${slug}\` makes the theme again and writes the copy over (its settings are lost: restore themes/${slug}/ from version control to keep them).`,
896
+ {run: [`${P} new ${slug}`]},
897
+ );
744
898
  if (!same && (other || LIKE.includes(slug)))
745
899
  refuse(
746
900
  ERROR_CODES.ERR_UNKNOWN_THEME,
@@ -760,7 +914,24 @@ export function loadTheme(
760
914
  ERROR_CODES.ERR_UNKNOWN_THEME,
761
915
  `There is no theme "${slug}" made by this command (no themes/${slug}/${slug}.settings.json).`,
762
916
  (() => {
763
- const near = same ? [same] : nearest(slug, have);
917
+ // A doubled or trailing dash (brand--dark, t--): the name as new
918
+ // cleans it, the theme of that name when there is one, never a new
919
+ // theme new refuses.
920
+ const cleaned = String(slug)
921
+ .replace(/-{2,}/g, '-')
922
+ .replace(/^-+|-+$/g, '');
923
+ const cleanedHere =
924
+ cleaned !== slug &&
925
+ slugOk(cleaned) &&
926
+ fs.existsSync(themeFiles(cwd, cleaned).settings)
927
+ ? cleaned
928
+ : null;
929
+ const near = same
930
+ ? [same]
931
+ : cleanedHere
932
+ ? [cleanedHere]
933
+ : nearest(slug, have);
934
+ const newName = usableNewName(cwd, cleaned || slug);
764
935
  // A theme near the name comes first; a new theme of the name as
765
936
  // typed only after.
766
937
  return {
@@ -768,8 +939,8 @@ export function loadTheme(
768
939
  run: same
769
940
  ? [`${P} show ${same}`]
770
941
  : near.length
771
- ? [`${P} show ${near[0]}`, `${P} new ${slug}`]
772
- : [`${P} new ${slug}`],
942
+ ? [`${P} show ${near[0]}`, `${P} new ${newName}`]
943
+ : [`${P} new ${newName}`],
773
944
  };
774
945
  })(),
775
946
  );
@@ -813,7 +984,31 @@ export function loadTheme(
813
984
  ],
814
985
  ERROR_CODES.ERR_THEME_INVALID,
815
986
  );
987
+ readEntryWords(data);
816
988
  const problem = settingsProblem(data, skip);
989
+ // An entry whose mode or source means nothing: `undo` with its name
990
+ // removes that entry only; a step back loses the last change.
991
+ const damaged = problem ? damagedEntry(data, problem) : null;
992
+ if (damaged)
993
+ throw new AstryxError(
994
+ `themes/${slug}/${slug}.settings.json: ${problem}. Remove that setting with ${P} undo ${slug} ${undoArgs({...damaged, mode: entryDamage(damaged) === 'mode' ? undefined : damaged.mode})}; nothing else needs to change${steps ? `, or step back to the settings before the last change with ${P} undo ${slug} (the last change is then lost)` : ''}. Nothing was changed.`,
995
+ [
996
+ {
997
+ name: `${P} undo ${slug} ${undoArgs({...damaged, mode: entryDamage(damaged) === 'mode' ? undefined : damaged.mode})}`,
998
+ reason: 'do this instead: removes only that setting',
999
+ },
1000
+ ...(steps
1001
+ ? [
1002
+ {
1003
+ name: `${P} undo ${slug}`,
1004
+ reason:
1005
+ 'or step back to the settings before the last change (the last change is then lost)',
1006
+ },
1007
+ ]
1008
+ : []),
1009
+ ],
1010
+ ERROR_CODES.ERR_THEME_INVALID,
1011
+ );
817
1012
  // A value made under looser rules is not damage: the command that
818
1013
  // changes or removes that setting still works, with the other bad ones
819
1014
  // left out of the build, so each listed fix runs on its own.
@@ -854,23 +1049,62 @@ export function loadTheme(
854
1049
  })),
855
1050
  ERROR_CODES.ERR_THEME_INVALID,
856
1051
  );
857
- const bad = problem ? badSetting(data) : null;
1052
+ // A damaged mode or base is fixed first: the message names it, so the
1053
+ // suggestions set it (another bad value is named on the next run).
1054
+ // (Not an entry named mode or base inside the settings list.)
1055
+ const fieldBroken =
1056
+ (/^(it has no mode|mode ")/.test(problem ?? '') &&
1057
+ !['both', 'light-only', 'dark-only'].includes(data?.mode)) ||
1058
+ (/^base "/.test(problem ?? '') &&
1059
+ data?.like != null &&
1060
+ !LIKE.includes(data.like));
1061
+ const bad = problem && !fieldBroken ? badSetting(data) : null;
858
1062
  if (problem && bad && settingsProblem(data, bad.thing) !== problem) {
859
- // A value it takes, for a dial; a color for a color token.
860
- const example = DIALS[bad.thing]
861
- ? DIALS[bad.thing].values.split('|').find(w => !w.startsWith('<'))
862
- : isColorToken(bad.thing)
863
- ? '#1f2937'
1063
+ // The value it holds, cleaned as typed input is (stray or invisible
1064
+ // spaces, other letters, a pasted `corners: pill`), when the dial takes
1065
+ // that; else a value it takes, for a dial; a color for a color token.
1066
+ const cleaned =
1067
+ DIALS[bad.thing] && typeof bad.value === 'string'
1068
+ ? vibrancyMeant(bad.thing, cleanDialValue(bad.thing, bad.value))
864
1069
  : null;
1070
+ // Vibrancy saturates the colors the color dials make: with none, set
1071
+ // refuses it as having no effect, so it is not offered.
1072
+ const vibrancyActs =
1073
+ bad.thing !== 'vibrancy' ||
1074
+ (Array.isArray(data.settings) ? data.settings : []).some(
1075
+ (/** @type {any} */ x) =>
1076
+ x && x.source === 'dial' && PALETTE_DIALS.includes(x.thing),
1077
+ );
1078
+ const meant =
1079
+ cleaned &&
1080
+ cleaned !== bad.value &&
1081
+ vibrancyActs &&
1082
+ !valueProblem({...bad, value: cleaned})
1083
+ ? cleaned
1084
+ : null;
1085
+ // Only the value it holds, cleaned: never a stock value it did not hold.
1086
+ // A vibrancy with no color to saturate is one set refuses: undo only.
1087
+ const example =
1088
+ bad.thing === 'vibrancy' &&
1089
+ !data.settings.some(
1090
+ (/** @type {any} */ x) =>
1091
+ x !== bad && x.source === 'dial' && PALETTE_DIALS.includes(x.thing),
1092
+ )
1093
+ ? null
1094
+ : meant;
865
1095
  throw new AstryxError(
866
1096
  `themes/${slug}/${slug}.settings.json: ${problem}, a value the editor no longer accepts. Remove or change that setting; nothing else needs to change. Nothing was changed.`,
867
1097
  [
868
1098
  {name: `${P} undo ${slug} ${undoArgs(bad)}`, reason: 'do this instead'},
869
- ...(example
1099
+ // Only a set that replaces this very entry: `mode` and `base` set
1100
+ // the theme's own fields, not an entry in the list.
1101
+ ...(example && !['mode', 'base'].includes(bad.thing)
870
1102
  ? [
871
1103
  {
872
1104
  name: `${P} set ${slug} ${undoArgs(bad).replace(bad.thing, `${bad.thing} ${quoteCommandArgument(example)}`)}`,
873
- reason: 'or give it a value it takes',
1105
+ reason: meant
1106
+ ? 'or set the value it holds, cleaned'
1107
+ : 'or give it a value it takes',
874
1108
  },
875
1109
  ]
876
1110
  : []),
@@ -880,17 +1114,53 @@ export function loadTheme(
880
1114
  }
881
1115
  // A bad mode or base is fixed by setting it.
882
1116
  // A value written in other letters (Dark-Only, Neutral) is the one meant.
883
- const modeMeant = String(data?.mode ?? '')
884
- .trim()
885
- .toLowerCase();
886
- const likeMeant = String(data?.like ?? '')
887
- .trim()
888
- .toLowerCase();
1117
+ const {mode: modeMeant, like: likeMeant} = fieldsMeant(data);
889
1118
  const fieldFix = /^(it has no mode|mode ")/.test(problem ?? '')
890
1119
  ? `${P} set ${slug} mode ${['both', 'light-only', 'dark-only'].includes(modeMeant) ? modeMeant : 'both'}`
891
1120
  : /^base "/.test(problem ?? '')
892
1121
  ? `${P} set ${slug} base ${LIKE.includes(likeMeant) && baseInstalled(cwd, likeMeant) ? likeMeant : 'none'}`
893
1122
  : null;
1123
+ // A damaged mode or base and a bad value in the list: setting the field
1124
+ // is refused while the list holds the bad value, but fixing that entry
1125
+ // saves the field as meant too, so its fix comes first. Never a bare
1126
+ // undo, which would throw away the last real change.
1127
+ const alsoBad = fieldFix ? badSetting(data) : null;
1128
+ if (problem && fieldFix && alsoBad) {
1129
+ const cleaned =
1130
+ DIALS[alsoBad.thing] && typeof alsoBad.value === 'string'
1131
+ ? vibrancyMeant(
1132
+ alsoBad.thing,
1133
+ cleanDialValue(alsoBad.thing, alsoBad.value),
1134
+ )
1135
+ : null;
1136
+ const meant =
1137
+ cleaned &&
1138
+ cleaned !== alsoBad.value &&
1139
+ !['mode', 'base'].includes(alsoBad.thing) &&
1140
+ !valueProblem({...alsoBad, value: cleaned})
1141
+ ? cleaned
1142
+ : null;
1143
+ const field = /^base "/.test(problem) ? 'base' : 'mode';
1144
+ const fieldValue = fieldFix.split(' ').pop();
1145
+ throw new AstryxError(
1146
+ `themes/${slug}/${slug}.settings.json: ${problem}, and ${settingsProblem(data, alsoBad.thing) ?? `${alsoBad.thing} "${alsoBad.value}" is not a value it takes`}. Fix that setting first: ${meant ? 'either command below does' : 'the command below does'}, and saves the ${field} as ${fieldValue}. Nothing was changed.`,
1147
+ [
1148
+ ...(meant
1149
+ ? [
1150
+ {
1151
+ name: `${P} set ${slug} ${undoArgs(alsoBad).replace(alsoBad.thing, `${alsoBad.thing} ${quoteCommandArgument(meant)}`)}`,
1152
+ reason: 'do this instead: set the value it holds, cleaned',
1153
+ },
1154
+ ]
1155
+ : []),
1156
+ {
1157
+ name: `${P} undo ${slug} ${undoArgs(alsoBad)}`,
1158
+ reason: meant ? 'or remove that setting' : 'do this instead',
1159
+ },
1160
+ ],
1161
+ ERROR_CODES.ERR_THEME_INVALID,
1162
+ );
1163
+ }
894
1164
  // A setting listed twice: setting it to one of its values, or undoing
895
1165
  // it, keeps one entry or none.
896
1166
  const twice = problem?.includes(' is listed twice (')
@@ -900,7 +1170,7 @@ export function loadTheme(
900
1170
  throw new AstryxError(
901
1171
  `themes/${slug}/${slug}.settings.json: ${problem}. ${fieldFix ? 'Set it again' : twice ? `Set it to one of its values or undo it, or fix it by hand${recover.text}` : `Fix it by hand${recover.text}`}. Nothing was changed.`,
902
1172
  fieldFix
903
- ? [{name: fieldFix, reason: 'do this instead'}, ...recover.run]
1173
+ ? [{name: fieldFix, reason: 'do this instead'}]
904
1174
  : twice
905
1175
  ? [
906
1176
  ...twice.values
@@ -961,9 +1231,11 @@ export function settingsProblem(
961
1231
  ) {
962
1232
  if (!data || typeof data !== 'object' || Array.isArray(data))
963
1233
  return 'the file is not a settings object';
964
- // `set <theme> mode` and `set <theme> base` fix their own field.
1234
+ // A command that changes or removes a setting (or sets mode or base)
1235
+ // puts a damaged mode or base back to its default itself, with a note, so
1236
+ // two damaged fields never send each fix to the other.
965
1237
  const fixing = typeof skip === 'string' ? skip : skip?.thing;
966
- const field = fixing === 'mode' || fixing === 'base';
1238
+ const field = Boolean(fixing);
967
1239
  if (!field && !['both', 'light-only', 'dark-only'].includes(data.mode))
968
1240
  return data.mode == null
969
1241
  ? 'it has no mode'
@@ -985,10 +1257,13 @@ export function settingsProblem(
985
1257
  // a setting with no name is damage.
986
1258
  if (!s || typeof s.thing !== 'string' || !('value' in s))
987
1259
  return 'a setting has no thing or value';
1260
+ if (removes(skip) && skips(s, skip) && entryDamage(s)) continue;
988
1261
  if (!['dial', 'token', 'property'].includes(s.source))
989
- return `${s.thing} has no source (dial, token or property)`;
1262
+ return s.source == null || s.source === ''
1263
+ ? `${s.thing} has no source (dial, token or property)`
1264
+ : `${s.thing} has source ${JSON.stringify(s.source)}, not dial, token or property`;
990
1265
  if (s.mode != null && s.mode !== 'light' && s.mode !== 'dark')
991
- return `${s.thing} has mode "${s.mode}"`;
1266
+ return `${s.thing} has mode ${JSON.stringify(s.mode)}, not light or dark`;
992
1267
  const key = keyOf(s);
993
1268
  // The command that changes or removes a setting listed twice keeps one
994
1269
  // value, or none, so it fixes the list.
@@ -1002,6 +1277,113 @@ export function settingsProblem(
1002
1277
  return null;
1003
1278
  }
1004
1279
 
1280
+ /**
1281
+ * Read each entry's mode and source as the editor writes them: a mode in
1282
+ * other letters or words (`Dark`, `night`, `day`) as light or dark, a
1283
+ * source in other letters (`Dial`) as written, and a missing source from
1284
+ * the thing (a dial name is a dial, a `--` name a token, anything with a
1285
+ * part a property). Each change is kept as a note for the next command,
1286
+ * which saves the entry that way. A value that means nothing is left for
1287
+ * the check to name.
1288
+ * @param {any} data
1289
+ */
1290
+ function readEntryWords(data) {
1291
+ /** @type {string[]} */
1292
+ const notes = [];
1293
+ for (const s of Array.isArray(data?.settings) ? data.settings : []) {
1294
+ if (!s || typeof s !== 'object' || typeof s.thing !== 'string') continue;
1295
+ if (typeof s.mode === 'string' && s.mode !== 'light' && s.mode !== 'dark') {
1296
+ const read = MODE_WORDS[s.mode.trim().toLowerCase()];
1297
+ if (read) {
1298
+ notes.push(
1299
+ `${s.thing} was saved with mode ${JSON.stringify(s.mode)}, read as ${read}`,
1300
+ );
1301
+ s.mode = read;
1302
+ }
1303
+ }
1304
+ if (!['dial', 'token', 'property'].includes(s.source)) {
1305
+ const typed = typeof s.source === 'string' ? s.source.trim() : '';
1306
+ const read = typed
1307
+ ? ['dial', 'token', 'property'].find(x => x === typed.toLowerCase())
1308
+ : s.source == null || s.source === ''
1309
+ ? DIALS[s.thing]
1310
+ ? 'dial'
1311
+ : s.thing.startsWith('--')
1312
+ ? 'token'
1313
+ : s.on
1314
+ ? 'property'
1315
+ : undefined
1316
+ : undefined;
1317
+ if (read) {
1318
+ notes.push(
1319
+ typed
1320
+ ? `${s.thing} was saved with source ${JSON.stringify(s.source)}, read as ${read}`
1321
+ : `${s.thing} was saved with no source, read as ${read}`,
1322
+ );
1323
+ s.source = read;
1324
+ }
1325
+ }
1326
+ }
1327
+ ENTRY_NOTES.set(data, notes);
1328
+ }
1329
+
1330
+ /** @type {WeakMap<object, string[]>} */
1331
+ const ENTRY_NOTES = new WeakMap();
1332
+
1333
+ /**
1334
+ * What loading read differently from the file in the theme's entries (a
1335
+ * mode or source in other letters, a missing source): one note each.
1336
+ * @param {object} data the theme as {@link loadTheme} returned it
1337
+ * @returns {string[]}
1338
+ */
1339
+ export function entryNotes(data) {
1340
+ return ENTRY_NOTES.get(data) ?? [];
1341
+ }
1342
+
1343
+ /**
1344
+ * Which part of an entry means nothing after reading: its mode or its
1345
+ * source, or null.
1346
+ * @param {any} s
1347
+ * @returns {'mode' | 'source' | null}
1348
+ */
1349
+ export function entryDamage(s) {
1350
+ if (!s || typeof s.thing !== 'string') return null;
1351
+ if (!['dial', 'token', 'property'].includes(s.source)) return 'source';
1352
+ if (s.mode != null && s.mode !== 'light' && s.mode !== 'dark') return 'mode';
1353
+ return null;
1354
+ }
1355
+
1356
+ /**
1357
+ * The entry a settings problem names when that problem is its mode or
1358
+ * source, or null.
1359
+ * @param {any} data
1360
+ * @param {string} problem
1361
+ */
1362
+ function damagedEntry(data, problem) {
1363
+ return (
1364
+ (Array.isArray(data?.settings) ? data.settings : []).find(
1365
+ (/** @type {any} */ s) =>
1366
+ (entryDamage(s) === 'source' &&
1367
+ typeof s.source === 'string' &&
1368
+ s.source !== '' &&
1369
+ problem.startsWith(`${s.thing} has source `)) ||
1370
+ (entryDamage(s) === 'mode' &&
1371
+ problem.startsWith(`${s.thing} has mode `)),
1372
+ ) ?? null
1373
+ );
1374
+ }
1375
+
1376
+ /**
1377
+ * Whether the command removes the setting it names (an undo): only that
1378
+ * takes an entry whose mode or source means nothing.
1379
+ * @param {string | Partial<Setting> | undefined} skip
1380
+ */
1381
+ function removes(skip) {
1382
+ return Boolean(
1383
+ skip && typeof skip === 'object' && /** @type {any} */ (skip).removing,
1384
+ );
1385
+ }
1386
+
1005
1387
  /**
1006
1388
  * Whether a setting is the one a command changes or removes: by thing, or
1007
1389
  * by the whole identity (part, variant, state, mode) when one is given.
@@ -1016,7 +1398,8 @@ function skips(s, skip) {
1016
1398
  (s.on ?? '') === (skip.on ?? '') &&
1017
1399
  (s.when ?? '') === (skip.when ?? '') &&
1018
1400
  (s.state ?? '') === (skip.state ?? '') &&
1019
- (s.mode ?? '') === (skip.mode ?? '')
1401
+ ((s.mode ?? '') === (skip.mode ?? '') ||
1402
+ (removes(skip) && !skip.mode && entryDamage(s) === 'mode'))
1020
1403
  );
1021
1404
  }
1022
1405
 
@@ -1040,6 +1423,10 @@ export function badSettings(data) {
1040
1423
  export function undoArgs(x) {
1041
1424
  return [
1042
1425
  quoteCommandArgument(String(x.thing)),
1426
+ // The tracking half of headings is named, so the undo reaches it even
1427
+ // when it is listed twice (a bare `undo headings` then reads the weight
1428
+ // half).
1429
+ ...(x.thing === 'headings' && x.axis === 'tracking' ? ['tracking'] : []),
1043
1430
  ...(x.on ? [`--on ${quoteCommandArgument(String(x.on))}`] : []),
1044
1431
  ...(x.when ? [`--when ${quoteCommandArgument(String(x.when))}`] : []),
1045
1432
  ...(x.state ? [`--state ${quoteCommandArgument(String(x.state))}`] : []),
@@ -1133,6 +1520,30 @@ export function valueProblem(s) {
1133
1520
  return null;
1134
1521
  }
1135
1522
 
1523
+ /**
1524
+ * One entry of the top-level `tokens` map in a theme's own source, as
1525
+ * written: its token (null for a computed key no read of the file can
1526
+ * resolve), the key as typed, the line that sets it, and its value's shape.
1527
+ * A `duplicate` entry names a second `tokens` key (with every line); a
1528
+ * `typography` entry is one typography field (its dotted key and value);
1529
+ * an `unresolved` entry says the map holds something only a build reads.
1530
+ * @typedef {{token: string | null, key: string, line: number | null, kind: 'text' | 'number' | 'pair' | 'object' | 'other' | 'duplicate' | 'typography' | 'unresolved', value?: any, halves?: Array<string | number | undefined>, lines?: Array<number | null>}} OwnTokenEntry
1531
+ */
1532
+
1533
+ /**
1534
+ * The entries of the top-level `tokens` map in a theme's own source, read
1535
+ * from its syntax tree, each with the line that sets it.
1536
+ * @param {string} cwd
1537
+ * @param {string} slug
1538
+ * @returns {OwnTokenEntry[]}
1539
+ */
1540
+ export function ownTokenEntries(cwd, slug) {
1541
+ /** @type {OwnTokenEntry[]} */
1542
+ const detail = [];
1543
+ ownPageTokens(cwd, slug, detail);
1544
+ return detail;
1545
+ }
1546
+
1136
1547
  /**
1137
1548
  * The page-wide tokens a theme's own source sets: the keys of the top-level
1138
1549
  * `tokens` map in its `defineTheme({...})`, read from the syntax tree, each
@@ -1142,7 +1553,11 @@ export function valueProblem(s) {
1142
1553
  * @param {string} slug
1143
1554
  * @returns {Map<string, string | null>}
1144
1555
  */
1145
- function ownPageTokens(cwd, slug) {
1556
+ function ownPageTokens(
1557
+ cwd,
1558
+ slug,
1559
+ detail = /** @type {OwnTokenEntry[] | null} */ (null),
1560
+ ) {
1146
1561
  /** @type {Map<string, string | null>} */
1147
1562
  const out = new Map();
1148
1563
  /** @type {string} */
@@ -1243,10 +1658,59 @@ function ownPageTokens(cwd, slug) {
1243
1658
  if (!chosen) return out;
1244
1659
  const def = unwrap(chosen.call.arguments[0]);
1245
1660
  if (def?.type !== 'ObjectExpression') return out;
1246
- const tokensProp = def.properties.find(
1661
+ // JavaScript keeps the last of two `tokens` keys: that one is read, and
1662
+ // both are named.
1663
+ const tokensProps = def.properties.filter(
1247
1664
  (/** @type {any} */ p) =>
1248
1665
  p.type === 'ObjectProperty' && !p.computed && keyOf(p.key) === 'tokens',
1249
1666
  );
1667
+ if (detail && tokensProps.length > 1)
1668
+ detail.push({
1669
+ token: null,
1670
+ key: 'tokens',
1671
+ kind: 'duplicate',
1672
+ line: tokensProps[0].loc?.start?.line ?? null,
1673
+ lines: tokensProps.map((/** @type {any} */ p) => p.loc?.start?.line),
1674
+ });
1675
+ // The typography fields, as written, for their own checks.
1676
+ const typo = def.properties.find(
1677
+ (/** @type {any} */ p) =>
1678
+ p.type === 'ObjectProperty' &&
1679
+ !p.computed &&
1680
+ keyOf(p.key) === 'typography',
1681
+ );
1682
+ if (detail && typo) {
1683
+ /** @param {any} node @param {string[]} at */
1684
+ const walk = (node, at) => {
1685
+ const obj = unwrap(node);
1686
+ if (obj?.type !== 'ObjectExpression') return;
1687
+ for (const p of obj.properties) {
1688
+ if (p.type !== 'ObjectProperty' || p.computed) continue;
1689
+ const k = keyOf(p.key);
1690
+ if (!k) continue;
1691
+ const v = unwrap(p.value);
1692
+ if (v?.type === 'ObjectExpression') walk(v, [...at, k]);
1693
+ else
1694
+ detail.push({
1695
+ token: null,
1696
+ key: [...at, k].join('.'),
1697
+ kind: 'typography',
1698
+ line: p.loc?.start?.line ?? null,
1699
+ value:
1700
+ textOf(v) ??
1701
+ (v?.type === 'NumericLiteral'
1702
+ ? v.value
1703
+ : v?.type === 'UnaryExpression' &&
1704
+ v.operator === '-' &&
1705
+ v.argument?.type === 'NumericLiteral'
1706
+ ? -v.argument.value
1707
+ : undefined),
1708
+ });
1709
+ }
1710
+ };
1711
+ walk(typo.value, []);
1712
+ }
1713
+ const tokensProp = tokensProps[tokensProps.length - 1];
1250
1714
  if (!tokensProp) return out;
1251
1715
  let unresolved = false;
1252
1716
  /** @param {any} node @param {number} depth */
@@ -1256,19 +1720,69 @@ function ownPageTokens(cwd, slug) {
1256
1720
  unresolved = true;
1257
1721
  return;
1258
1722
  }
1259
- // Spreads and keys merge in order: a later one wins.
1723
+ // Spreads and keys merge in order: a later one wins. A computed key
1724
+ // that is text (`['--radius-page']`) is read like a literal one.
1260
1725
  for (const p of obj.properties) {
1261
1726
  if (p.type === 'SpreadElement') collect(p.argument, depth + 1);
1262
- else if (p.type === 'ObjectProperty' && !p.computed) {
1263
- const k = keyOf(p.key);
1727
+ else if (p.type === 'ObjectProperty') {
1728
+ const k = p.computed ? textOf(unwrap(p.key)) : keyOf(p.key);
1264
1729
  if (k?.startsWith('--')) out.set(k, textOf(unwrap(p.value)));
1730
+ else if (p.computed) unresolved = true;
1731
+ if (detail && (k?.startsWith('--') || p.computed))
1732
+ detail.push({
1733
+ token: k?.startsWith('--') ? k : null,
1734
+ key: code.slice(p.key.start, p.key.end),
1735
+ line: p.loc?.start?.line ?? null,
1736
+ ...valueShape(unwrap(p.value)),
1737
+ });
1265
1738
  } else unresolved = true;
1266
1739
  }
1267
1740
  };
1741
+ /**
1742
+ * What a token's value is, as written: text, a number, a [light, dark]
1743
+ * pair (each half's text, a number, or undefined), or something else.
1744
+ * @param {any} node
1745
+ * @returns {Pick<OwnTokenEntry, 'kind' | 'value' | 'halves'>}
1746
+ */
1747
+ const valueShape = node => {
1748
+ const t = textOf(node);
1749
+ if (t != null) return {kind: 'text', value: t};
1750
+ if (node?.type === 'NumericLiteral')
1751
+ return {kind: 'number', value: node.value};
1752
+ if (node?.type === 'ArrayExpression')
1753
+ return {
1754
+ kind: 'pair',
1755
+ halves: node.elements.map((/** @type {any} */ e) => {
1756
+ const h = unwrap(e);
1757
+ return (
1758
+ textOf(h) ?? (h?.type === 'NumericLiteral' ? h.value : undefined)
1759
+ );
1760
+ }),
1761
+ };
1762
+ if (node?.type === 'ObjectExpression')
1763
+ return {
1764
+ kind: 'object',
1765
+ value: Object.fromEntries(
1766
+ node.properties
1767
+ .filter((/** @type {any} */ p) => p.type === 'ObjectProperty')
1768
+ .map((/** @type {any} */ p) => [
1769
+ keyOf(p.key) ?? '?',
1770
+ textOf(unwrap(p.value)) ?? null,
1771
+ ]),
1772
+ ),
1773
+ };
1774
+ return {kind: 'other'};
1775
+ };
1268
1776
  collect(tokensProp.value, 0);
1269
1777
  // A value no read of the file can resolve (a call, an import) is read
1270
1778
  // from the build (ownTokens), and checked again after the next one.
1271
- void unresolved;
1779
+ if (detail && unresolved)
1780
+ detail.push({
1781
+ token: null,
1782
+ key: 'tokens',
1783
+ kind: 'unresolved',
1784
+ line: tokensProp.loc?.start?.line ?? null,
1785
+ });
1272
1786
  return out;
1273
1787
  }
1274
1788
 
@@ -1541,6 +2055,27 @@ export function partRuleTokens(cwd, slug, like, part) {
1541
2055
  return out;
1542
2056
  }
1543
2057
 
2058
+ /**
2059
+ * Whether the base theme's own source gives a part's rule a property, in a
2060
+ * state (`:hover`) or at rest, read from its module as written.
2061
+ * @param {string} cwd
2062
+ * @param {string | undefined} like
2063
+ * @param {string} part
2064
+ * @param {string} scope `base` or a variant such as `variant:secondary`
2065
+ * @param {string | null} state a state block (`:hover`), or null
2066
+ * @param {string} prop camelCase
2067
+ */
2068
+ export function baseRuleHas(cwd, like, part, scope, state, prop) {
2069
+ const file = like ? baseModule(cwd, like) : null;
2070
+ if (!file) return false;
2071
+ try {
2072
+ const at = ['components', part, scope, ...(state ? [state] : [])];
2073
+ return blockOf(file, at).has(prop);
2074
+ } catch {
2075
+ return false;
2076
+ }
2077
+ }
2078
+
1544
2079
  /**
1545
2080
  * The tokens and properties a theme's own source sets on a part's plain
1546
2081
  * rule, read from the build as ownTokens reads page-wide ones: what the
@@ -1621,7 +2156,7 @@ function ownTokens(cwd, slug) {
1621
2156
  * @param {string} slug
1622
2157
  * @returns {Map<string, string | null> | null}
1623
2158
  */
1624
- function builtOwnTokens(cwd, slug) {
2159
+ function builtOwnTokens(cwd, slug, js = /** @type {string | null} */ (null)) {
1625
2160
  const f = themeFiles(cwd, slug);
1626
2161
  /** @type {string} */
1627
2162
  let module;
@@ -1633,7 +2168,10 @@ function builtOwnTokens(cwd, slug) {
1633
2168
  const built = /\/\/ Built with \S+\.theme\.ts ([0-9a-f]{16})\./.exec(
1634
2169
  module,
1635
2170
  )?.[1];
1636
- if (!built || !fs.existsSync(f.js) || built !== themeSourceHash(cwd, slug))
2171
+ if (
2172
+ !js &&
2173
+ (!built || !fs.existsSync(f.js) || built !== themeSourceHash(cwd, slug))
2174
+ )
1637
2175
  return null;
1638
2176
  // What the settings module gives each top-level token: a text value as
1639
2177
  // it is, a [light, dark] pair as a pair.
@@ -1688,7 +2226,7 @@ function builtOwnTokens(cwd, slug) {
1688
2226
  const named = namedInOwnSource(cwd, slug);
1689
2227
  /** @type {Map<string, string | null>} */
1690
2228
  const out = new Map();
1691
- for (const [k, v] of builtTopTokens(cwd, slug)) {
2229
+ for (const [k, v] of js ? topTokensOf(js) : builtTopTokens(cwd, slug)) {
1692
2230
  const given = settings.get(k);
1693
2231
  const own =
1694
2232
  given === undefined
@@ -1774,7 +2312,7 @@ export function ownSourceTokenValues(cwd, slug) {
1774
2312
  function scopeProblem(s) {
1775
2313
  if (s.on != null && !/^[a-z][a-z0-9-]*$/.test(s.on))
1776
2314
  return `${s.thing} is set on "${s.on}", which is not a part or group name`;
1777
- if (s.state != null && !/^[a-z][a-z-]*$/.test(s.state))
2315
+ if (s.state != null && !/^[a-z][a-zA-Z-]*$/.test(s.state))
1778
2316
  return `${s.thing} has state "${s.state}", which is not a state name`;
1779
2317
  if (s.when != null && !/^[\w-]+:[\w.-]+$/.test(s.when))
1780
2318
  return `${s.thing} has --when "${s.when}", which is not prop:value`;
@@ -1787,7 +2325,9 @@ function scopeProblem(s) {
1787
2325
  export const keyOf = s =>
1788
2326
  [
1789
2327
  s.thing,
1790
- s.axis ?? '',
2328
+ // A headings value saved with no axis is its weight half, as the build
2329
+ // reads it, so a set or undo of the weight replaces it.
2330
+ s.thing === 'headings' ? (s.axis ?? 'weight') : (s.axis ?? ''),
1791
2331
  s.on ?? '',
1792
2332
  s.when ?? '',
1793
2333
  s.state ?? '',
@@ -1959,6 +2499,44 @@ function partDefault(ctx, target, prop, when, state) {
1959
2499
  return r ? `var(${r.token})` : null;
1960
2500
  }
1961
2501
 
2502
+ /**
2503
+ * The variants (`variant:<name>`) of a part that each read their own value
2504
+ * of a color property (the button's background, a badge's text), in a
2505
+ * state when one is named and changes it: one rule's other-mode half would
2506
+ * give every one of them one variant's color. Empty when the part reads one
2507
+ * value for all.
2508
+ * @param {Ctx} ctx
2509
+ * @param {string} target
2510
+ * @param {string} prop camelCase or kebab-case
2511
+ * @param {string} [state]
2512
+ * @returns {string[]}
2513
+ */
2514
+ function variantsReading(ctx, target, prop, state) {
2515
+ const k = kebab(prop);
2516
+ const g = ctx.C.groupOfProp(k === 'background' ? 'background-color' : k);
2517
+ if (!g) return [];
2518
+ const reads = ctx.C.partReads(target, g).filter(x =>
2519
+ x.props.some(
2520
+ p => p === k || (k === 'background' && p === 'background-color'),
2521
+ ),
2522
+ );
2523
+ const named = (/** @type {(w: string) => boolean} */ ok) => [
2524
+ ...new Set(
2525
+ reads
2526
+ .flatMap(x => x.when)
2527
+ .filter(ok)
2528
+ .map(w => /(?:^|,)variant=([\w-]+)/.exec(w)?.[1])
2529
+ .filter(Boolean)
2530
+ .map(n => `variant:${n}`),
2531
+ ),
2532
+ ];
2533
+ const inState = state ? named(w => w.includes(`:${state}`)) : [];
2534
+ if (inState.length) return inState;
2535
+ return reads.some(x => x.when.includes(''))
2536
+ ? []
2537
+ : named(w => /^variant=[\w-]+$/.test(w));
2538
+ }
2539
+
1962
2540
  /** The line that records a generated module's own hash. */
1963
2541
  const SEAL = /^\/\/ Module ([0-9a-f]{16})\.\n/m;
1964
2542
 
@@ -2101,6 +2679,138 @@ function keepShades(pal, kept) {
2101
2679
  return {...pal, tokens, lift: kept['lifted parts'] ? pal.lift : null};
2102
2680
  }
2103
2681
 
2682
+ /**
2683
+ * A size in px: px, rem (16px each), or a calc() of those added and
2684
+ * subtracted; null for anything else.
2685
+ * @param {string} v
2686
+ * @param {Record<string, string>} [vars] values for the tokens a var() may name
2687
+ * @returns {number | null}
2688
+ */
2689
+ export function sizePx(v, vars = {}) {
2690
+ let t = String(v).trim();
2691
+ // A token the dial or the theme gives a value (var(--spacing-12)),
2692
+ // through that value; a clamp() at its preferred value held to its
2693
+ // bounds, or its upper bound when the preferred one is no length;
2694
+ // min() and max() of the lengths they hold.
2695
+ const fn = /^(var|clamp|min|max)\((.*)\)$/is.exec(t);
2696
+ if (fn) {
2697
+ const args = splitTop(fn[2], ',').map(x => x.trim());
2698
+ if (fn[1].toLowerCase() === 'var') {
2699
+ const own = vars[args[0]];
2700
+ if (own != null) return sizePx(own, vars);
2701
+ return args[1] != null ? sizePx(args.slice(1).join(','), vars) : null;
2702
+ }
2703
+ const n = args.map(x => sizePx(x, vars));
2704
+ if (fn[1].toLowerCase() === 'clamp') {
2705
+ const [lo, mid, hi] = n;
2706
+ if (lo == null || hi == null) return null;
2707
+ return mid == null ? hi : Math.min(hi, Math.max(lo, mid));
2708
+ }
2709
+ const known = /** @type {number[]} */ (n.filter(x => x != null));
2710
+ if (!known.length) return null;
2711
+ return fn[1].toLowerCase() === 'min'
2712
+ ? Math.min(...known)
2713
+ : Math.max(...known);
2714
+ }
2715
+ const calc = /^calc\((.*)\)$/is.exec(t);
2716
+ if (calc) t = calc[1].trim();
2717
+ const terms =
2718
+ t.match(/[+-]?\s*[\d.]+(?:px|rem|em|pt|pc|in|cm|mm|q)\b|\S+/gi) ?? [];
2719
+ let sum = 0;
2720
+ let sign = 1;
2721
+ for (const raw of terms) {
2722
+ const x = raw.replace(/\s+/g, '');
2723
+ if (x === '+' || x === '-') {
2724
+ if (!calc) return null;
2725
+ sign = x === '-' ? -1 : 1;
2726
+ continue;
2727
+ }
2728
+ const m = /^([+-]?)([\d.]+)(px|rem|em|pt|pc|in|cm|mm|q)$/i.exec(x);
2729
+ if (!m || (!calc && terms.length > 1)) return null;
2730
+ // Absolute units by their fixed ratio to px; em and rem against the
2731
+ // 16px a control's text starts from.
2732
+ const n = parseFloat(m[2]) * (PX_PER[m[3].toLowerCase()] ?? 1);
2733
+ if (!Number.isFinite(n)) return null;
2734
+ sum += (m[1] === '-' ? -1 : 1) * sign * n;
2735
+ sign = 1;
2736
+ }
2737
+ return terms.length ? sum : null;
2738
+ }
2739
+
2740
+ /** Pixels per unit of each length unit a kept size may be written in. */
2741
+ const PX_PER = /** @type {Record<string, number>} */ ({
2742
+ px: 1,
2743
+ rem: 16,
2744
+ em: 16,
2745
+ pt: 96 / 72,
2746
+ pc: 16,
2747
+ in: 96,
2748
+ cm: 96 / 2.54,
2749
+ mm: 96 / 25.4,
2750
+ q: 96 / 101.6,
2751
+ });
2752
+
2753
+ /**
2754
+ * Spacing steps scaled with the spacing dial, kept in order around the
2755
+ * steps the theme keeps exact: each the plain scaled value unless it would
2756
+ * meet or pass a kept one; those are spread evenly between the kept one and
2757
+ * the nearest step that keeps its place. A step with no room below a kept
2758
+ * one takes the value of the one below it.
2759
+ * @param {Array<[string, number]>} steps token name and the base value, in px
2760
+ * @param {number} f the rung's factor
2761
+ * @param {Record<string, number>} kept exact steps the theme keeps, in px
2762
+ * @param {string[]} [noRoom] filled with the steps left no room
2763
+ * @returns {Array<[string, number]>} every step's new value in px, kept ones as kept
2764
+ */
2765
+ export function spacingSteps(steps, f, kept, noRoom = []) {
2766
+ const px = [...steps].sort((a, b) => a[1] - b[1]);
2767
+ const n = px.map(([k, v]) => (k in kept ? kept[k] : v * f));
2768
+ const isKept = (/** @type {number} */ i) => px[i][0] in kept;
2769
+ px.forEach(([, base], k) => {
2770
+ if (!isKept(k)) return;
2771
+ // The steps below that would meet or pass it are spread evenly between
2772
+ // the last one that does not and it.
2773
+ let j0 = k;
2774
+ while (
2775
+ j0 > 0 &&
2776
+ !isKept(j0 - 1) &&
2777
+ n[j0 - 1] >= n[k] &&
2778
+ px[j0 - 1][1] < base
2779
+ )
2780
+ j0--;
2781
+ if (j0 < k) {
2782
+ const lo = j0 > 0 ? n[j0 - 1] : 0;
2783
+ if (lo >= n[k])
2784
+ for (let j = j0; j < k; j++) {
2785
+ n[j] = lo;
2786
+ noRoom.push(px[j][0]);
2787
+ }
2788
+ else
2789
+ for (let j = j0; j < k; j++)
2790
+ n[j] = lo + ((n[k] - lo) * (j - j0 + 1)) / (k - j0 + 1);
2791
+ }
2792
+ // The steps above that would meet or fall under it, likewise up to the
2793
+ // next one that does not (or above it by their own scaled steps).
2794
+ let j1 = k;
2795
+ while (
2796
+ j1 < n.length - 1 &&
2797
+ !isKept(j1 + 1) &&
2798
+ n[j1 + 1] <= n[k] &&
2799
+ px[j1 + 1][1] > base
2800
+ )
2801
+ j1++;
2802
+ if (j1 > k) {
2803
+ const hi = j1 < n.length - 1 ? n[j1 + 1] : null;
2804
+ for (let j = k + 1; j <= j1; j++)
2805
+ n[j] =
2806
+ hi == null
2807
+ ? n[k] + (px[j][1] - base) * f
2808
+ : n[k] + ((hi - n[k]) * (j - k)) / (j1 - k + 1);
2809
+ }
2810
+ });
2811
+ return px.map(([k], i) => [k, n[i]]);
2812
+ }
2813
+
2104
2814
  /**
2105
2815
  * Control heights scaled with the spacing dial (a denser theme has shorter
2106
2816
  * controls), each kept distinct and in order: smallest to largest, a
@@ -2110,28 +2820,44 @@ function keepShades(pal, kept) {
2110
2820
  * scaled above it.
2111
2821
  * @param {Array<[string, string]>} sizes token name and the theme's value
2112
2822
  * @param {number} f the spacing rung's factor
2823
+ * @param {Record<string, number>} [kept] exact sizes the theme keeps, in px,
2824
+ * which the others stay in order around
2825
+ * @param {string[]} [noRoom] filled with the sizes left no room between
2826
+ * two kept ones (each then equals the one below it)
2113
2827
  * @returns {Array<[string, string]>} the tokens it writes, in px
2114
2828
  */
2115
- export function controlSizes(sizes, f) {
2829
+ export function controlSizes(sizes, f, kept = {}, noRoom = []) {
2116
2830
  const px = sizes
2117
2831
  .filter(([, v]) => /^[\d.]+px$/.test(String(v).trim()))
2118
2832
  .map(([k, v]) => /** @type {[string, number]} */ ([k, parseFloat(v)]))
2119
2833
  .sort((a, b) => a[1] - b[1]);
2120
- /** @type {Array<[string, string]>} */
2121
- const out = [];
2122
- let prev = null;
2123
- let prevOwn = null;
2124
- for (const [k, v] of px) {
2125
- let n = Math.max(Math.min(24, v), Math.round(v * f));
2126
- // Only a size that would meet (or pass) the one below moves: the plain
2127
- // scaled value otherwise.
2128
- if (prev != null && prevOwn != null && n <= prev)
2129
- n = prev + Math.max(1, Math.round((v - prevOwn) * f));
2130
- out.push([k, `${n}px`]);
2131
- prev = n;
2132
- prevOwn = v;
2133
- }
2134
- return out;
2834
+ /** @type {number[]} */
2835
+ const n = px.map(([k, v]) =>
2836
+ k in kept ? kept[k] : Math.max(Math.min(24, v), Math.round(v * f)),
2837
+ );
2838
+ /** The step between two sizes, scaled. @param {number} i */
2839
+ const step = i => Math.max(1, Math.round((px[i][1] - px[i - 1][1]) * f));
2840
+ // Only a size that would meet (or pass) the one below moves, up; then one
2841
+ // that would meet a kept size above it moves down (a kept size stays).
2842
+ for (let i = 1; i < n.length; i++)
2843
+ if (!(px[i][0] in kept) && n[i] <= n[i - 1]) n[i] = n[i - 1] + step(i);
2844
+ for (let i = n.length - 2; i >= 0; i--)
2845
+ if (!(px[i][0] in kept) && n[i] >= n[i + 1]) n[i] = n[i + 1] - step(i + 1);
2846
+ // A size between two that cannot both move (kept, or one kept and the
2847
+ // other already at its place) sits halfway between them; with no room
2848
+ // between them it takes the smaller one's size, and the result says so.
2849
+ for (let i = 1; i < n.length - 1; i++)
2850
+ if (!(px[i][0] in kept) && (n[i] <= n[i - 1] || n[i] >= n[i + 1])) {
2851
+ const mid = Math.round(((n[i - 1] + n[i + 1]) / 2) * 2) / 2;
2852
+ if (mid > n[i - 1] && mid < n[i + 1]) n[i] = mid;
2853
+ else {
2854
+ n[i] = n[i - 1];
2855
+ noRoom.push(px[i][0]);
2856
+ }
2857
+ }
2858
+ return px
2859
+ .map(([k], i) => /** @type {[string, string]} */ ([k, `${n[i]}px`]))
2860
+ .filter(([k]) => !(k in kept));
2135
2861
  }
2136
2862
 
2137
2863
  /**
@@ -2142,6 +2868,8 @@ export function controlSizes(sizes, f) {
2142
2868
  * @returns {any}
2143
2869
  */
2144
2870
  export function compileTheme(ctx, data, base) {
2871
+ ctx.sizeNotes = [];
2872
+ ctx.compileNotes = [];
2145
2873
  // A setting the editor no longer accepts never reaches the build.
2146
2874
  data = {...data, settings: data.settings.filter(s => !valueProblem(s))};
2147
2875
  const TOKENS = ctx.project.core.tokenDefaults;
@@ -2164,6 +2892,44 @@ export function compileTheme(ctx, data, base) {
2164
2892
  : data.mode === 'dark-only'
2165
2893
  ? 'dark'
2166
2894
  : null;
2895
+ /** The tokens the theme's own source sets, which win over the settings. */
2896
+ /** @type {Record<string, string> | null} */
2897
+ let ownTok = null;
2898
+ const ownTokenValues = () => {
2899
+ if (ownTok) return ownTok;
2900
+ try {
2901
+ ownTok = ownSourceTokenValues(ctx.project.cwd, data.name);
2902
+ } catch {
2903
+ ownTok = {};
2904
+ }
2905
+ return ownTok;
2906
+ };
2907
+ /**
2908
+ * The exact tokens kept where a dial writes (whole theme with no part):
2909
+ * the whole-theme settings', then the own source's, by name.
2910
+ * @param {string | null} t a part, for its own settings too
2911
+ * @returns {Map<string, string>}
2912
+ */
2913
+ const keptTokens = t => {
2914
+ /** @type {Map<string, string>} */
2915
+ const out = new Map();
2916
+ for (const x of data.settings)
2917
+ if (
2918
+ x.source === 'token' &&
2919
+ !x.when &&
2920
+ !x.state &&
2921
+ !(modeOnly && x.mode && x.mode !== modeOnly) &&
2922
+ (!x.on || (t != null && partsOf(ctx, x).includes(t)))
2923
+ )
2924
+ out.set(x.thing, String(x.value));
2925
+ for (const [k, v] of Object.entries(ownTokenValues())) out.set(k, v);
2926
+ return out;
2927
+ };
2928
+ /** @param {string | null} t */
2929
+ const keptSizes = t =>
2930
+ [...keptTokens(t)].filter(([k]) => /^--size-element-/.test(k));
2931
+ /** The one-mode gradient layers each block holds, by mode. @type {WeakMap<object, {light: string[], dark: string[]}>} */
2932
+ const modeLayers = new WeakMap();
2167
2933
  /** @type {Record<string, {light?: string, dark?: string}>} */
2168
2934
  const tok = {};
2169
2935
  /** @param {string} name @param {string | [string, string]} v @param {string} [mode] */
@@ -2177,12 +2943,22 @@ export function compileTheme(ctx, data, base) {
2177
2943
  if (!mode || mode === 'dark') t.dark = v[1];
2178
2944
  return;
2179
2945
  }
2180
- if (!MODAL.has(ctx.C.typeOf(name)) || modeOnly || !mode) {
2946
+ // A color set in a one-mode theme fills its mode's half only; the other
2947
+ // half keeps what it had (the base theme's), for the regions Core draws
2948
+ // in the other mode.
2949
+ const half = mode ?? modeOnly;
2950
+ // Only a color has a half per mode (light-dark() takes colors only): a
2951
+ // shadow or any other value in a one-mode theme is written whole.
2952
+ if (
2953
+ !MODAL.has(ctx.C.typeOf(name)) ||
2954
+ !half ||
2955
+ (!mode && !parseColor(String(v).trim()))
2956
+ ) {
2181
2957
  t.light = v;
2182
2958
  t.dark = v;
2183
2959
  return;
2184
2960
  }
2185
- t[/** @type {'light' | 'dark'} */ (mode)] = v;
2961
+ t[/** @type {'light' | 'dark'} */ (half)] = v;
2186
2962
  };
2187
2963
  /** @param {Setting} s @param {string} target @returns {Record<string, any>} */
2188
2964
  const block = (s, target) => {
@@ -2471,9 +3247,11 @@ export function compileTheme(ctx, data, base) {
2471
3247
  return n && n.unit === '' && n.value === 0 ? '0px' : v;
2472
3248
  };
2473
3249
  for (const {target, s, list} of padQueue.values()) {
2474
- // The own source's padding on the same rule wins over the editor's:
2475
- // nothing is written there (the result says so).
2476
- if (ownPads(target, s)) continue;
3250
+ // The own source's padding on the same rule wins over the editor's on
3251
+ // the sides it sets (the result says so); the editor's other sides
3252
+ // still apply.
3253
+ const own = ownBox(target, s);
3254
+ if (own.ltr.size === 4 && own.rtl.size === 4) continue;
2477
3255
  const prefix = /** @type {string} */ (padVars(target));
2478
3256
  const owner = prefix.slice('--astryx-'.length, -'-padding'.length);
2479
3257
  const scoped = target !== owner || s.when != null || s.state != null;
@@ -2517,6 +3295,10 @@ export function compileTheme(ctx, data, base) {
2517
3295
  }
2518
3296
  }
2519
3297
  }
3298
+ // The sides the own source pads in a direction are its own there.
3299
+ for (const dir of /** @type {const} */ (['ltr', 'rtl']))
3300
+ for (const x of Object.keys(side[dir]))
3301
+ if (own[dir].has(boxSide(x, dir))) delete side[dir][x];
2520
3302
  /** @type {Record<string, string>} */
2521
3303
  let plain = {};
2522
3304
  /** @type {Record<string, string>} */
@@ -2586,6 +3368,78 @@ export function compileTheme(ctx, data, base) {
2586
3368
  b[key] = {...(b[key] ?? {}), ...rule};
2587
3369
  }
2588
3370
  }
3371
+ // A variant the own source pads: the sides it sets are left without a
3372
+ // side variable there, so the variant's own padding (which Core writes
3373
+ // as the whole padding) wins over any side the plain rule writes.
3374
+ for (const owner of new Set(
3375
+ [...padQueue.values()]
3376
+ .filter(({target, s}) => !s.when && !s.state && padVars(target))
3377
+ .map(({target}) =>
3378
+ /** @type {string} */ (padVars(target)).slice(
3379
+ '--astryx-'.length,
3380
+ -'-padding'.length,
3381
+ ),
3382
+ ),
3383
+ )) {
3384
+ const values = ctx.C.variantValues(owner);
3385
+ for (const [prop, vals] of Object.entries(values ?? {}))
3386
+ for (const v of /** @type {string[]} */ (vals ?? [])) {
3387
+ const when = `${prop}:${v}`;
3388
+ const own = ownBox(owner, /** @type {any} */ ({when}));
3389
+ if (!own.ltr.size && !own.rtl.size) continue;
3390
+ const variant = /** @type {any} */ ({when});
3391
+ const logical = [
3392
+ 'block-start',
3393
+ 'block-end',
3394
+ 'inline-start',
3395
+ 'inline-end',
3396
+ ];
3397
+ const at = (/** @type {'ltr' | 'rtl'} */ dir) =>
3398
+ logical.filter(x => own[dir].has(boxSide(x, dir)));
3399
+ const [l, r] = [at('ltr'), at('rtl')];
3400
+ const b = block(variant, owner);
3401
+ for (const x of l.filter(x => r.includes(x)))
3402
+ b[`--astryx-${owner}-padding-${x}`] ??= 'initial';
3403
+ // A pair variable the plain rule writes (the inline or block
3404
+ // padding) feeds both its sides, under the side variables: where
3405
+ // the own source pads both, it is left without a value too, so
3406
+ // the variant's own padding holds there.
3407
+ for (const pair of ['block', 'inline'])
3408
+ if (
3409
+ [`${pair}-start`, `${pair}-end`].every(
3410
+ x => l.includes(x) && r.includes(x),
3411
+ )
3412
+ )
3413
+ b[`--astryx-${owner}-padding-${pair}`] ??= 'initial';
3414
+ // Its own sides inherit into a plain one of the part inside it:
3415
+ // they are reset there like the editor's (below).
3416
+ const sel = narrowSelector(owner, variant);
3417
+ if (sel) {
3418
+ const bySel = narrow.get(owner) ?? new Map();
3419
+ const names = bySel.get(sel) ?? new Set();
3420
+ for (const x of new Set([...l, ...r]))
3421
+ names.add(`--astryx-${owner}-padding-${x}`);
3422
+ for (const pair of ['block', 'inline'])
3423
+ if ([...l, ...r].some(x => x.startsWith(pair)))
3424
+ names.add(`--astryx-${owner}-padding-${pair}`);
3425
+ bySel.set(sel, names);
3426
+ narrow.set(owner, bySel);
3427
+ }
3428
+ for (const [dir, xs] of /** @type {const} */ ([
3429
+ [':dir(ltr)', l.filter(x => !r.includes(x))],
3430
+ [':dir(rtl)', r.filter(x => !l.includes(x))],
3431
+ ]))
3432
+ if (xs.length) {
3433
+ const [db, key] = dirBlock(variant, owner, dir);
3434
+ db[key] = {
3435
+ ...(db[key] ?? {}),
3436
+ ...Object.fromEntries(
3437
+ xs.map(x => [`--astryx-${owner}-padding-${x}`, 'initial']),
3438
+ ),
3439
+ };
3440
+ }
3441
+ }
3442
+ }
2589
3443
  // A plain part inside a narrower one: each side the narrower selector
2590
3444
  // writes is reset (left without a value, so Core's own fallback holds),
2591
3445
  // on the part's own class at its own weight, before any base setting a
@@ -2668,25 +3522,66 @@ export function compileTheme(ctx, data, base) {
2668
3522
  return out;
2669
3523
  };
2670
3524
  /**
2671
- * Whether the theme's own source sets a padding on a part's rule for a
2672
- * scope (its plain rule, a variant, a state).
3525
+ * The box side a padding side names in a direction: a physical side as it
3526
+ * is, a logical one as the direction reads it (inline-start is the left in
3527
+ * left-to-right text, the right in right-to-left).
3528
+ * @param {string} x top, right, bottom, left, or a logical side
3529
+ * @param {'ltr' | 'rtl'} dir
3530
+ */
3531
+ const boxSide = (x, dir) =>
3532
+ ({
3533
+ 'block-start': 'top',
3534
+ 'block-end': 'bottom',
3535
+ 'inline-start': dir === 'ltr' ? 'left' : 'right',
3536
+ 'inline-end': dir === 'ltr' ? 'right' : 'left',
3537
+ })[x] ?? x;
3538
+ /**
3539
+ * The padding sides a padding property names, as it names them (physical
3540
+ * stays physical, logical stays logical), with each one's value.
3541
+ * @param {string} prop kebab-case
3542
+ * @param {string} value
3543
+ * @returns {Record<string, string>}
3544
+ */
3545
+ const paddingSides = (prop, value) => {
3546
+ const w = splitTop(String(value).trim(), ' ').map(y => y.trim());
3547
+ if (prop === 'padding') {
3548
+ const [top, right = top, bottom = top, left = right] = w;
3549
+ return {top, right, bottom, left};
3550
+ }
3551
+ if (prop === 'padding-block')
3552
+ return {'block-start': w[0], 'block-end': w[1] ?? w[0]};
3553
+ if (prop === 'padding-inline')
3554
+ return {'inline-start': w[0], 'inline-end': w[1] ?? w[0]};
3555
+ const side = prop.slice('padding-'.length);
3556
+ return /^(top|right|bottom|left|(block|inline)-(start|end))$/.test(side)
3557
+ ? {[side]: w[0]}
3558
+ : {};
3559
+ };
3560
+ /**
3561
+ * The box sides the theme's own source pads on a part's rule for a scope
3562
+ * (its plain rule, a variant, a state), in each direction.
2673
3563
  * @param {string} target @param {Setting} s
3564
+ * @returns {Record<'ltr' | 'rtl', Set<string>>}
2674
3565
  */
2675
- const ownPads = (target, s) => {
3566
+ const ownBox = (target, s) => {
3567
+ const out = {ltr: new Set(), rtl: new Set()};
2676
3568
  try {
2677
- return [
2678
- ...ownPartTokens(
2679
- ctx.project.cwd,
2680
- data.name,
2681
- target,
2682
- s.when ?? 'base',
2683
- s.state ? `:${s.state}` : null,
2684
- ).keys(),
2685
- ].some(k => /^padding(-|$)/.test(k));
3569
+ for (const k of ownPartTokens(
3570
+ ctx.project.cwd,
3571
+ data.name,
3572
+ target,
3573
+ s.when ?? 'base',
3574
+ s.state ? `:${s.state}` : null,
3575
+ ).keys())
3576
+ for (const x of Object.keys(paddingSides(k, '0')))
3577
+ for (const dir of /** @type {const} */ (['ltr', 'rtl']))
3578
+ out[dir].add(boxSide(x, dir));
2686
3579
  } catch {
2687
- return false;
3580
+ // No own source.
2688
3581
  }
3582
+ return out;
2689
3583
  };
3584
+
2690
3585
  /**
2691
3586
  * The selector a narrower padding scope is written with (a clickable
2692
3587
  * card's class, a variant's attribute, a state's pseudo-class), or null
@@ -2712,11 +3607,18 @@ export function compileTheme(ctx, data, base) {
2712
3607
  const keys = Object.keys(b);
2713
3608
  const plain = keys.filter(k => !k.startsWith(':'));
2714
3609
  const dirs = keys.filter(k => /^:(where\()?dir\(/.test(k));
3610
+ // The reset a plain part inside a narrower one gets comes before the
3611
+ // part's own direction rules at the same weight, so a side the part
3612
+ // sets for a direction holds inside a variant too.
3613
+ const resets = keys.filter(k => /^:where\((?!:?dir\().* \*\)$/.test(k));
2715
3614
  const rest = keys.filter(
2716
- k => k.startsWith(':') && !/^:(where\()?dir\(/.test(k),
3615
+ k =>
3616
+ k.startsWith(':') &&
3617
+ !/^:(where\()?dir\(/.test(k) &&
3618
+ !resets.includes(k),
2717
3619
  );
2718
3620
  return Object.fromEntries(
2719
- [...plain, ...dirs, ...rest].map(k => [
3621
+ [...plain, ...resets, ...dirs, ...rest].map(k => [
2720
3622
  k,
2721
3623
  k.startsWith(':') && b[k] && typeof b[k] === 'object'
2722
3624
  ? dirFirst(b[k])
@@ -2767,16 +3669,265 @@ export function compileTheme(ctx, data, base) {
2767
3669
  const parent = block({...s, state: undefined}, target);
2768
3670
  return [parent, `${stateKey(s.state, wrapsOneControl(ctx, target))}${dir}`];
2769
3671
  };
3672
+ /**
3673
+ * One half of a light-dark() pair (1 light, 2 dark), or the value itself.
3674
+ * @param {string} x @param {1 | 2} side
3675
+ */
3676
+ const halfOf = (x, side) => {
3677
+ const inner = /^light-dark\((.*)\)$/s.exec(x.trim())?.[1];
3678
+ const halves = inner == null ? [] : splitTop(inner, ',');
3679
+ return halves.length === 2 ? halves[side - 1].trim() : x.trim();
3680
+ };
3681
+ /**
3682
+ * The value a variant of a part shows for a color property where the
3683
+ * theme sets none of its own: the base theme's rule for that variant (in
3684
+ * the state, else at rest), else Core's, else transparent for a
3685
+ * background Core never paints; null for a text color Core never sets.
3686
+ * @param {string} target @param {string} css a color longhand, kebab-case
3687
+ * @param {string} name the variant @param {string} [state]
3688
+ * @param {boolean} [stateOnly] the state's own value only, never the resting one
3689
+ * @returns {string | null}
3690
+ */
3691
+ const exactVariantValue = (target, css, name, state, stateOnly = false) => {
3692
+ const when = `variant:${name}`;
3693
+ const kebabs =
3694
+ css === 'background-color' ? ['background-color', 'background'] : [css];
3695
+ const props = kebabs.map(camel);
3696
+ const steps = state
3697
+ ? stateOnly
3698
+ ? [state]
3699
+ : [state, undefined]
3700
+ : [undefined];
3701
+ for (const st of steps)
3702
+ for (const p of props) {
3703
+ const b = baseComponent(base, ctx, target, p, {when, state: st});
3704
+ if (b != null) return b;
3705
+ }
3706
+ const keyOf = (/** @type {string} */ k) => {
3707
+ const [attrs, cond = ''] = k.split(' ');
3708
+ return attrs.split(',').includes(`variant=${name}`) ? cond : null;
3709
+ };
3710
+ for (const st of steps)
3711
+ for (const p of kebabs) {
3712
+ const at = ctx.C.MAP[target]?.at?.[p];
3713
+ for (const [k, val] of Object.entries(at ?? {})) {
3714
+ const cond = keyOf(k);
3715
+ if (cond == null) continue;
3716
+ if (st ? cond.includes(`:${st}`) : cond === '') return val;
3717
+ }
3718
+ }
3719
+ if (stateOnly) return null;
3720
+ return css === 'background-color'
3721
+ ? 'transparent'
3722
+ : css === 'color'
3723
+ ? null
3724
+ : 'currentcolor';
3725
+ };
3726
+ /** The family a color property belongs to: background is background-color. @param {string} p */
3727
+ const colorFamily = p => {
3728
+ const k = kebab(p);
3729
+ return k === 'background' ? 'background-color' : k;
3730
+ };
2770
3731
  /** @param {Setting} s @param {string} target @param {string} prop @param {string} v */
2771
3732
  const putComp = (s, target, prop, v) => {
2772
3733
  const b = block(s, target);
2773
- if (s.mode && !modeOnly) {
3734
+ // A gradient background for one mode: each layer's colors are painted
3735
+ // in that mode only (transparent in the other), as background images
3736
+ // beside the other mode's, so each mode keeps its own background color;
3737
+ // a gradient for both modes held before keeps showing in the other
3738
+ // mode. Which layers belong to which mode is recorded as they are
3739
+ // written, never read back from their stops.
3740
+ if (
3741
+ s.mode &&
3742
+ /^background(-image)?$/.test(kebab(prop)) &&
3743
+ /gradient\(/i.test(v)
3744
+ ) {
3745
+ let rec = modeLayers.get(b);
3746
+ if (!rec) {
3747
+ rec = {light: [], dark: []};
3748
+ for (const k of ['background', 'backgroundImage']) {
3749
+ const held = b[k];
3750
+ if (typeof held !== 'string' || !/gradient\(/i.test(held)) continue;
3751
+ rec.light.push(...maskLayers(held, 'light'));
3752
+ rec.dark.push(...maskLayers(held, 'dark'));
3753
+ if (k === 'backgroundImage') delete b[k];
3754
+ }
3755
+ modeLayers.set(b, rec);
3756
+ }
3757
+ rec[s.mode] = maskLayers(v, s.mode);
3758
+ const parts = [...rec.light, ...rec.dark].map(layerParts);
3759
+ for (const k of [
3760
+ 'backgroundImage',
3761
+ 'backgroundPosition',
3762
+ 'backgroundSize',
3763
+ 'backgroundRepeat',
3764
+ ])
3765
+ delete b[k];
3766
+ b.backgroundImage = parts.map(x => x.image).join(', ');
3767
+ if (parts.some(x => x.position || x.size || x.repeat)) {
3768
+ b.backgroundPosition = parts.map(x => x.position || '0% 0%').join(', ');
3769
+ b.backgroundSize = parts.map(x => x.size || 'auto').join(', ');
3770
+ b.backgroundRepeat = parts.map(x => x.repeat || 'repeat').join(', ');
3771
+ }
3772
+ return;
3773
+ }
3774
+ // A color set in a one-mode theme fills its mode's half only (as a
3775
+ // setting for that mode does), so a region Core draws in the other mode
3776
+ // reads the other half.
3777
+ const mode =
3778
+ s.mode ??
3779
+ (modeOnly && parseColor(String(v).trim()) ? modeOnly : undefined);
3780
+ if (mode && !s.when && variantsReading(ctx, target, prop, s.state).length) {
3781
+ // A color for one mode on a part whose variants each have their own:
3782
+ // each variant's rule (in the state, for a state setting) gets the
3783
+ // color in that mode and, in the other, exactly the value it shows
3784
+ // unset there (the base theme's, else Core's), so no variant takes
3785
+ // another's and the other mode stays as it was. The part's own rule
3786
+ // is left alone.
3787
+ // The property itself (a border color stays a border color); the
3788
+ // background shorthand is written as its color.
3789
+ const css = colorFamily(prop);
3790
+ const other = mode === 'light' ? 2 : 1;
3791
+ // What the part's own rule holds of it (an earlier setting for both
3792
+ // modes): the other half each variant keeps, before its unset value.
3793
+ const plainHeld = [
3794
+ css,
3795
+ ...(css === 'background-color' ? ['background'] : []),
3796
+ ]
3797
+ .map(k => b[camel(k)])
3798
+ .find(y => typeof y === 'string' && !/gradient\(|url\(/i.test(y));
3799
+ // The part's own background being an image (a gradient) covers any
3800
+ // color under it: the color is written, and the result says it does
3801
+ // not show.
3802
+ const plainImage =
3803
+ css === 'background-color'
3804
+ ? ['background', 'backgroundImage']
3805
+ .map(k => b[k])
3806
+ .find(y => typeof y === 'string' && /gradient\(|url\(/i.test(y))
3807
+ : undefined;
3808
+ if (plainImage)
3809
+ (ctx.compileNotes ??= []).push(
3810
+ `${target}'s own background is an image (${plainImage}), which covers the ${mode} color: it does not show until that background is a color`,
3811
+ );
3812
+ const names = new Set([
3813
+ ...(ctx.C.variantValues(target)?.variant ?? []),
3814
+ ...(ctx.C.MAP[target]?.attrs?.variant ?? []),
3815
+ ]);
3816
+ for (const name of names) {
3817
+ const x = exactVariantValue(target, css, name, s.state);
3818
+ const vb = block({...s, when: `variant:${name}`}, target);
3819
+ // What the variant's rule already holds (a setting for the other
3820
+ // mode, or one for both) keeps its other half; else the value the
3821
+ // variant shows unset.
3822
+ // The background shorthand is the same property: its color counts,
3823
+ // and it is taken out so the color written here is in effect.
3824
+ const family = [
3825
+ css,
3826
+ ...(css === 'background-color' ? ['background'] : []),
3827
+ ];
3828
+ // A variant whose own background is an image (a gradient) keeps
3829
+ // it: one mode's color is not written there, and the result says so.
3830
+ const image = family
3831
+ .map(k => vb[camel(k)])
3832
+ .find(y => typeof y === 'string' && /gradient\(|url\(/i.test(y));
3833
+ if (image) {
3834
+ (ctx.compileNotes ??= []).push(
3835
+ `${target} variant:${name} keeps its own background image (${image}), so the ${mode} color is not written there`,
3836
+ );
3837
+ continue;
3838
+ }
3839
+ const prev = family
3840
+ .map(k => vb[camel(k)])
3841
+ .find(y => typeof y === 'string');
3842
+ // In a state, what the state shows now in the other mode: its own
3843
+ // value there, else the resting color a setting gives the variant
3844
+ // or the part (a state that does not change the color shows the
3845
+ // resting one), else the unset value.
3846
+ /** @param {Record<string, any> | undefined} rule */
3847
+ const restOf = rule =>
3848
+ family
3849
+ .map(k => rule?.[camel(k)])
3850
+ .find(y => typeof y === 'string' && !/gradient\(|url\(/i.test(y));
3851
+ const rest = s.state
3852
+ ? (exactVariantValue(target, css, name, s.state, true) ??
3853
+ restOf(theme.components[target]?.[`variant:${name}`]) ??
3854
+ plainHeld ??
3855
+ restOf(theme.components[target]?.base))
3856
+ : plainHeld;
3857
+ const from = prev ?? rest ?? x;
3858
+ if (from == null) continue;
3859
+ for (const k of family) delete vb[camel(k)];
3860
+ const half = halfOf(from, other);
3861
+ vb[camel(css)] =
3862
+ mode === 'light'
3863
+ ? `light-dark(${v}, ${half})`
3864
+ : `light-dark(${half}, ${v})`;
3865
+ // A resting color written on the variant's rule would also hide the
3866
+ // hover the variant shows unset: that hover is written back as it
3867
+ // was, in both modes, unless a hover setting of the theme's own
3868
+ // gives it one.
3869
+ if (
3870
+ !s.state &&
3871
+ !data.settings.some(
3872
+ y =>
3873
+ y.on === s.on &&
3874
+ y.state === 'hover' &&
3875
+ colorFamily(y.thing) === colorFamily(s.thing),
3876
+ )
3877
+ ) {
3878
+ const hover = exactVariantValue(target, css, name, 'hover', true);
3879
+ if (hover != null && hover !== x) {
3880
+ const hb = block(
3881
+ {...s, when: `variant:${name}`, state: 'hover', mode: undefined},
3882
+ target,
3883
+ );
3884
+ hb[camel(css)] ??= hover;
3885
+ }
3886
+ }
3887
+ }
3888
+ return;
3889
+ }
3890
+ if (mode && colorFamily(prop) === 'background-color') {
3891
+ // The background shorthand and its color are one property: the one
3892
+ // the rule holds (as a color) gives the other half and is replaced, so
3893
+ // one key carries both modes.
3894
+ const held = ['backgroundColor', 'background'].find(
3895
+ k => typeof b[k] === 'string' && !/gradient\(|url\(/i.test(b[k]),
3896
+ );
3897
+ if (held && held !== camel(prop)) {
3898
+ const was = b[held];
3899
+ delete b[held];
3900
+ b[camel(prop)] ??= was;
3901
+ }
3902
+ }
3903
+ // A color for one mode under the part's own gradient does not show:
3904
+ // the result says so.
3905
+ if (
3906
+ mode &&
3907
+ colorFamily(prop) === 'background-color' &&
3908
+ ['background', 'backgroundImage'].some(
3909
+ k => typeof b[k] === 'string' && /gradient\(|url\(/i.test(b[k]),
3910
+ )
3911
+ )
3912
+ (ctx.compileNotes ??= []).push(
3913
+ `${target}${s.when ? ` ${s.when}` : ''}${s.state ? ` :${s.state}` : ''} has a background image (a gradient) over its color, so the ${mode} color does not show until that background is a color`,
3914
+ );
3915
+ if (mode) {
2774
3916
  const prev = b[prop];
2775
3917
  // The other mode keeps exactly what it had: the value set for it, the
2776
3918
  // part's own, else what the property shows unset (light-dark() takes
2777
3919
  // colors only, so never inherit).
3920
+ // A token on the part: its own value in the other mode (the base
3921
+ // theme's, else Core's), never another color.
3922
+ const otherSide = mode === 'light' ? 'dark' : 'light';
3923
+ const tokenOther = prop.startsWith('--')
3924
+ ? (base[otherSide]?.[prop] ??
3925
+ /** @type {Record<string, string>} */ (TOKENS)[prop] ??
3926
+ null)
3927
+ : null;
2778
3928
  const other =
2779
3929
  prev ??
3930
+ tokenOther ??
2780
3931
  baseComponent(base, ctx, target, prop, s) ??
2781
3932
  partDefault(ctx, target, prop, s.when, s.state) ??
2782
3933
  (s.state
@@ -2791,7 +3942,7 @@ export function compileTheme(ctx, data, base) {
2791
3942
  return halves.length === 2 ? halves[side - 1].trim() : x;
2792
3943
  };
2793
3944
  b[prop] =
2794
- s.mode === 'light'
3945
+ mode === 'light'
2795
3946
  ? `light-dark(${v}, ${prev ? split(prev, 2) : other})`
2796
3947
  : `light-dark(${prev ? split(prev, 1) : other}, ${v})`;
2797
3948
  } else b[prop] = v;
@@ -2879,6 +4030,19 @@ export function compileTheme(ctx, data, base) {
2879
4030
  ...data.settings.filter(x => x.source === 'dial' && roleFont(x)),
2880
4031
  ...data.settings.filter(x => x.source !== 'dial'),
2881
4032
  ];
4033
+ // The shell regions a setting gives a background of their own keep it
4034
+ // when the page background paints the rest of the shell.
4035
+ const regionsWithOwnBackground = new Set(
4036
+ data.settings
4037
+ .filter(
4038
+ x =>
4039
+ x.source === 'property' &&
4040
+ /^background(-color|-image)?$/.test(kebab(x.thing)),
4041
+ )
4042
+ .flatMap(x => partsOf(ctx, x)),
4043
+ );
4044
+ /** @type {Record<string, any>[]} */
4045
+ const fixedToViewport = [];
2882
4046
  for (const s of ordered) {
2883
4047
  // A setting for the mode a one-mode theme does not have stays saved but
2884
4048
  // does not apply (maskedSettings names it).
@@ -3001,35 +4165,239 @@ export function compileTheme(ctx, data, base) {
3001
4165
  // The rungs scale the spacing the base theme starts from.
3002
4166
  /** @param {string} k @param {string} nv */
3003
4167
  const put = (k, nv) => {
3004
- if (parts.length) for (const t of parts) block(s, t)[k] = nv;
3005
- else putTok(k, nv);
4168
+ if (parts.length) {
4169
+ // An exact whole-theme or own-source token holds inside the
4170
+ // part too.
4171
+ if (!keptTokens(null).has(k))
4172
+ for (const t of parts) block(s, t)[k] = nv;
4173
+ } else putTok(k, nv);
3006
4174
  };
3007
- for (const [k, core] of Object.entries(
3008
- /** @type {Record<string, string>} */ (TOKENS),
3009
- )) {
3010
- const v = base.light[k] ?? core;
3011
- if (/^--spacing-/.test(k) && /rem$/.test(v))
3012
- put(k, `${Number((parseFloat(v) * f).toFixed(3))}rem`);
4175
+ // The spacing steps, in order around the exact steps the theme
4176
+ // keeps (a whole-theme one or the own source's: they win over the
4177
+ // dial).
4178
+ /** @type {Record<string, string>} */
4179
+ const dialVars = {};
4180
+ {
4181
+ /** @type {Array<[string, number]>} */
4182
+ const steps = [];
4183
+ for (const [k, core] of Object.entries(
4184
+ /** @type {Record<string, string>} */ (TOKENS),
4185
+ )) {
4186
+ const v = base.light[k] ?? core;
4187
+ if (/^--spacing-/.test(k) && /rem$/.test(v))
4188
+ steps.push([k, parseFloat(v) * 16]);
4189
+ }
4190
+ /** @type {Record<string, number>} */
4191
+ const keptSteps = {};
4192
+ for (const [k, v] of keptTokens(null))
4193
+ if (/^--spacing-/.test(k)) {
4194
+ const n = sizePx(v);
4195
+ if (n != null) keptSteps[k] = n;
4196
+ }
4197
+ /** @type {string[]} */
4198
+ const noRoom = [];
4199
+ for (const [k, n] of spacingSteps(steps, f, keptSteps, noRoom)) {
4200
+ const nv = `${Number((n / 16).toFixed(3))}rem`;
4201
+ dialVars[k] = k in keptSteps ? String(keptTokens(null).get(k)) : nv;
4202
+ if (!(k in keptSteps)) put(k, nv);
4203
+ }
4204
+ for (const k of noRoom)
4205
+ (ctx.sizeNotes ??= []).push(
4206
+ `${k} has no room between the exact spacing steps kept around it, so it takes the value of the one below it`,
4207
+ );
4208
+ }
4209
+ // An exact size the theme keeps (it wins over the dial) is a fixed
4210
+ // point the others stay in order around: a whole-theme one, one of
4211
+ // the theme's own source, and on a part the part's own, in any
4212
+ // unit that comes to a length (a spacing token through the value
4213
+ // this dial gives it). A whole-theme dial also keeps each part's
4214
+ // own exact sizes in order on that part.
4215
+ const sizeParts = parts.length
4216
+ ? parts
4217
+ : [
4218
+ null,
4219
+ ...new Set(
4220
+ data.settings
4221
+ .filter(
4222
+ x =>
4223
+ x.source === 'token' &&
4224
+ /^--size-element-/.test(x.thing) &&
4225
+ x.on &&
4226
+ !x.when &&
4227
+ !x.state,
4228
+ )
4229
+ .flatMap(x => partsOf(ctx, x)),
4230
+ ),
4231
+ ];
4232
+ for (const t of sizeParts) {
4233
+ /** @type {Record<string, number>} */
4234
+ const kept = {};
4235
+ for (const [k, v] of keptSizes(t)) {
4236
+ const n = sizePx(v, dialVars);
4237
+ if (n != null) kept[k] = n;
4238
+ }
4239
+ /** @type {string[]} */
4240
+ const noRoom = [];
4241
+ for (const [k, nv] of controlSizes(
4242
+ Object.keys(/** @type {Record<string, string>} */ (TOKENS))
4243
+ .filter(k => /^--size-element-/.test(k))
4244
+ .map(k => [k, base.light[k] ?? TOKENS[k]]),
4245
+ f,
4246
+ kept,
4247
+ noRoom,
4248
+ ))
4249
+ if (t) block(s, t)[k] = nv;
4250
+ else putTok(k, nv);
4251
+ for (const k of noRoom)
4252
+ (ctx.sizeNotes ??= []).push(
4253
+ `${k}${t ? ` on ${t}` : ''} has no room between the exact sizes kept around it, so it takes the size of the one below it`,
4254
+ );
4255
+ }
4256
+ // A variant's own exact size is kept in order on that variant too,
4257
+ // with the part's and the theme's kept sizes around it.
4258
+ /** @type {Map<string, {t: string, when: string}>} */
4259
+ const variantScopes = new Map();
4260
+ for (const x of data.settings)
4261
+ if (
4262
+ x.source === 'token' &&
4263
+ /^--size-element-/.test(x.thing) &&
4264
+ x.on &&
4265
+ x.when &&
4266
+ !x.state
4267
+ )
4268
+ for (const t of partsOf(ctx, x))
4269
+ if (!parts.length || parts.includes(t))
4270
+ variantScopes.set(`${t} ${x.when}`, {t, when: x.when});
4271
+ for (const {t, when} of variantScopes.values()) {
4272
+ /** @type {Record<string, number>} */
4273
+ const kept = {};
4274
+ for (const [k, v] of keptSizes(t)) {
4275
+ const n = sizePx(v, dialVars);
4276
+ if (n != null) kept[k] = n;
4277
+ }
4278
+ for (const x of data.settings)
4279
+ if (
4280
+ x.source === 'token' &&
4281
+ /^--size-element-/.test(x.thing) &&
4282
+ x.when === when &&
4283
+ !x.state &&
4284
+ partsOf(ctx, x).includes(t)
4285
+ ) {
4286
+ const n = sizePx(String(x.value), dialVars);
4287
+ if (n != null) kept[x.thing] = n;
4288
+ }
4289
+ /** @type {string[]} */
4290
+ const noRoom = [];
4291
+ for (const [k, nv] of controlSizes(
4292
+ Object.keys(/** @type {Record<string, string>} */ (TOKENS))
4293
+ .filter(k => /^--size-element-/.test(k))
4294
+ .map(k => [k, base.light[k] ?? TOKENS[k]]),
4295
+ f,
4296
+ kept,
4297
+ noRoom,
4298
+ ))
4299
+ block({...s, when}, t)[k] = nv;
4300
+ for (const k of noRoom)
4301
+ (ctx.sizeNotes ??= []).push(
4302
+ `${k} on ${t} when ${when} has no room between the exact sizes kept around it, so it takes the size of the one below it`,
4303
+ );
3013
4304
  }
3014
- for (const [k, nv] of controlSizes(
3015
- Object.keys(/** @type {Record<string, string>} */ (TOKENS))
3016
- .filter(k => /^--size-element-/.test(k))
3017
- .map(k => [k, base.light[k] ?? TOKENS[k]]),
3018
- f,
3019
- ))
3020
- put(k, nv);
3021
4305
  }
3022
4306
  } else if (s.source === 'token') {
3023
4307
  if (parts.length) for (const t of parts) putComp(s, t, s.thing, s.value);
3024
4308
  else putTok(s.thing, s.value, s.mode);
3025
4309
  } else if (s.source === 'property') {
3026
- for (const t of parts) {
4310
+ // A background on the whole app shell is the page background. The
4311
+ // shell's header and side nav paint the body or surface color over it
4312
+ // in every variant but section, and in an auto-height shell they are
4313
+ // sticky, so content must not show through them when it scrolls: they
4314
+ // take the same background. The main content area is made
4315
+ // see-through. A gradient is fixed to the viewport on the shell and on
4316
+ // those regions, so the regions line up with the page behind them. A
4317
+ // background a setting gives one of those regions itself is kept.
4318
+ /** @type {string[]} */
4319
+ const pageParts = [];
4320
+ if (
4321
+ parts.includes('app-shell') &&
4322
+ /^background(-color|-image)?$/.test(kebab(s.thing)) &&
4323
+ !s.when &&
4324
+ !s.state
4325
+ ) {
4326
+ /** @param {Record<string, any>} r */
4327
+ const ownBackground = r =>
4328
+ ['background', 'backgroundColor', 'backgroundImage'].some(
4329
+ k => k in r,
4330
+ );
4331
+ for (const region of ['app-shell-header', 'app-shell-sidenav'])
4332
+ if (
4333
+ ctx.project.target.has(region) &&
4334
+ !regionsWithOwnBackground.has(region)
4335
+ )
4336
+ pageParts.push(region);
4337
+ if (ctx.project.target.has('layout-content')) {
4338
+ const lc = ((theme.components['layout-content'] ??= {}).base ??= {});
4339
+ const main = (lc[':where(.astryx-app-shell [role="main"])'] ??= {});
4340
+ if (!ownBackground(main)) main.backgroundColor = 'transparent';
4341
+ }
4342
+ // Written after every setting (below), so no background shorthand
4343
+ // in the same rule resets it.
4344
+ if (/gradient\(/.test(String(s.value)))
4345
+ for (const t of ['app-shell', ...pageParts])
4346
+ fixedToViewport.push(block({...s, mode: undefined}, t));
4347
+ (ctx.compileNotes ??= []).push(
4348
+ "the page background on app-shell also paints the shell's header and side nav (they stay opaque when content scrolls under them) and makes the main content area see-through; what is drawn inside keeps its colors, and in the default elevated layout the content panel keeps its own surface",
4349
+ );
4350
+ }
4351
+ for (const t of [...parts, ...pageParts]) {
4352
+ // A heading takes its color from its color prop, which reads the
4353
+ // text color tokens after part styles: the color goes into those
4354
+ // tokens on the heading (a named color prop's own token for
4355
+ // --when color:<name>), so it shows there and nowhere else.
4356
+ if (t === 'heading' && kebab(s.thing) === 'color') {
4357
+ const named = /^color:([\w-]+)$/.exec(s.when ?? '')?.[1];
4358
+ const scope = named ? {...s, when: undefined} : s;
4359
+ for (const tok of named
4360
+ ? [`--color-text-${named}`]
4361
+ : ['--color-text-primary', '--color-text-secondary'])
4362
+ // A value naming one of these tokens (the secondary text color)
4363
+ // leaves that token as it is: it would read itself.
4364
+ if (!new RegExp(`var\\(\\s*${tok}\\s*[,)]`).test(String(s.value)))
4365
+ putComp(scope, t, tok, s.value);
4366
+ continue;
4367
+ }
3027
4368
  // A padding on a part whose box reads Core's padding variables is
3028
4369
  // resolved with the rest of that part's padding, below.
3029
4370
  if (padVars(t) && /^padding(-|$)/.test(kebab(s.thing))) {
3030
4371
  queuePadding(s, t);
3031
4372
  continue;
3032
4373
  }
4374
+ // A padding on a part without padding variables, where the own source
4375
+ // pads some sides of the same rule: the editor writes the other
4376
+ // sides only, each as it names it (physical stays physical), so the
4377
+ // own sides win; a side the own source holds in one direction only
4378
+ // is written for the other direction.
4379
+ if (/^padding(-|$)/.test(kebab(s.thing)) && !s.mode && !padVars(t)) {
4380
+ const own = ownBox(t, s);
4381
+ if (own.ltr.size || own.rtl.size) {
4382
+ for (const [x, v] of Object.entries(
4383
+ paddingSides(kebab(s.thing), String(s.value)),
4384
+ )) {
4385
+ const prop = camel(`padding-${x}`);
4386
+ const [inL, inR] = [
4387
+ own.ltr.has(boxSide(x, 'ltr')),
4388
+ own.rtl.has(boxSide(x, 'rtl')),
4389
+ ];
4390
+ if (inL && inR) continue;
4391
+ if (!inL && !inR) {
4392
+ putComp(s, t, prop, v);
4393
+ continue;
4394
+ }
4395
+ const [db, key] = dirBlock(s, t, inL ? ':dir(rtl)' : ':dir(ltr)');
4396
+ db[key] = {...(db[key] ?? {}), [prop]: v};
4397
+ }
4398
+ continue;
4399
+ }
4400
+ }
3033
4401
  const sides =
3034
4402
  wrappedPadding(t, s) ??
3035
4403
  containerSides(t, s) ??
@@ -3109,6 +4477,10 @@ export function compileTheme(ctx, data, base) {
3109
4477
  }
3110
4478
  }
3111
4479
  emitPadding();
4480
+ for (const r of fixedToViewport) {
4481
+ delete r.backgroundAttachment;
4482
+ r.backgroundAttachment = 'fixed';
4483
+ }
3112
4484
  orderBlocks();
3113
4485
  // Core gives headings the body font when a theme sets only the body's:
3114
4486
  // a font for the body alone keeps the base theme's heading font.
@@ -3162,7 +4534,16 @@ export function compileTheme(ctx, data, base) {
3162
4534
  for (const [k, {light, dark}] of Object.entries(tok)) {
3163
4535
  const l = light ?? base.light[k] ?? TOKENS[k];
3164
4536
  const d = dark ?? base.dark[k] ?? TOKENS[k];
3165
- theme.tokens[k] = l === d ? l : [l, d];
4537
+ // A pair only for a color: anything else (a shadow) is one value, the
4538
+ // one the theme's mode shows.
4539
+ theme.tokens[k] =
4540
+ l === d
4541
+ ? l
4542
+ : ctx.C.typeOf(k) === 'color' || isColorToken(k)
4543
+ ? [l, d]
4544
+ : modeOnly === 'dark'
4545
+ ? d
4546
+ : l;
3166
4547
  }
3167
4548
  // Base themes set the type tokens again for phones (a coarse pointer
3168
4549
  // below the lg width); an exact font family or weight, and the headings
@@ -3198,11 +4579,194 @@ export function compileTheme(ctx, data, base) {
3198
4579
  },
3199
4580
  ],
3200
4581
  };
4582
+ // A longhand set after a shorthand that covers it is the one in effect,
4583
+ // as the result says. The build merges these blocks over the base
4584
+ // theme's, and a key the base holds keeps the base's (earlier) place, so
4585
+ // such a longhand would come before the shorthand and lose: it is written
4586
+ // as its own sides instead, which the base does not hold.
4587
+ const baseBlocks =
4588
+ /** @type {{components?: Record<string, any>}} */ (base).components ?? {};
4589
+ for (const [target, keys] of Object.entries(theme.components ?? {}))
4590
+ for (const [key, b] of Object.entries(
4591
+ /** @type {Record<string, any>} */ (keys),
4592
+ ))
4593
+ laterLonghandsAsSides(b, baseBlocks[target]?.[key]);
3201
4594
  if (!Object.keys(theme.tokens).length) delete theme.tokens;
3202
4595
  if (!Object.keys(theme.components).length) delete theme.components;
3203
4596
  return theme;
3204
4597
  }
3205
4598
 
4599
+ /**
4600
+ * Whether shorthand `a` sets `b`, a logical side included: padding sets
4601
+ * padding-inline, border-color sets border-inline-start-color.
4602
+ * @param {string} a @param {string} b
4603
+ */
4604
+ function coversSide(a, b) {
4605
+ if (coversProperty(a, b)) return true;
4606
+ const root = b.replace(/-(inline|block)(-start|-end)?(?=-|$)/, '');
4607
+ return root !== b && (a === root || coversProperty(a, root));
4608
+ }
4609
+
4610
+ /**
4611
+ * A background's layers with each color painted in one mode only: a color
4612
+ * stop becomes light-dark(<color>, transparent) for light (the reverse for
4613
+ * dark), and a layer that is a color alone becomes a gradient of it, so
4614
+ * every layer is an image the other mode does not show.
4615
+ * @param {string} value
4616
+ * @param {'light' | 'dark'} mode
4617
+ * @returns {string[]}
4618
+ */
4619
+ export function maskLayers(value, mode) {
4620
+ /** @param {string} c */
4621
+ const wrap = c =>
4622
+ mode === 'light'
4623
+ ? `light-dark(${c}, transparent)`
4624
+ : `light-dark(transparent, ${c})`;
4625
+ /** @param {string} w */
4626
+ const isColor = w =>
4627
+ !/^light-dark\(/i.test(w) &&
4628
+ (isColorValue(w) || /^var\(\s*--color-/i.test(w));
4629
+ return splitTop(value, ',')
4630
+ .map(x => x.trim())
4631
+ .filter(Boolean)
4632
+ .map(layer => {
4633
+ const fn = /^((?:repeating-)?(?:linear|radial|conic)-gradient)\(/i.exec(
4634
+ layer,
4635
+ );
4636
+ if (!fn)
4637
+ return isColor(layer)
4638
+ ? `linear-gradient(${wrap(layer)}, ${wrap(layer)})`
4639
+ : layer;
4640
+ // The gradient's own arguments, up to its closing bracket; what
4641
+ // follows (position, size, repeat) stays as it is.
4642
+ let depth = 0;
4643
+ let end = fn[0].length - 1;
4644
+ for (let i = end; i < layer.length; i++) {
4645
+ if (layer[i] === '(') depth++;
4646
+ if (layer[i] === ')' && --depth === 0) {
4647
+ end = i;
4648
+ break;
4649
+ }
4650
+ }
4651
+ const args = splitTop(layer.slice(fn[0].length, end), ',').map(arg =>
4652
+ splitTop(arg.trim(), ' ')
4653
+ .map(w => (isColor(w.trim()) ? wrap(w.trim()) : w.trim()))
4654
+ .join(' '),
4655
+ );
4656
+ return `${fn[1]}(${args.join(', ')})${layer.slice(end + 1)}`;
4657
+ });
4658
+ }
4659
+
4660
+ /**
4661
+ * A background layer's image (its gradient) and what follows it, as the
4662
+ * background longhands take them: position, size (after a slash) and
4663
+ * repeat.
4664
+ * @param {string} layer
4665
+ * @returns {{image: string, position: string, size: string, repeat: string}}
4666
+ */
4667
+ function layerParts(layer) {
4668
+ const fn = /^((?:repeating-)?(?:linear|radial|conic)-gradient)\(/i.exec(
4669
+ layer,
4670
+ );
4671
+ if (!fn) return {image: layer, position: '', size: '', repeat: ''};
4672
+ let depth = 0;
4673
+ let end = layer.length - 1;
4674
+ for (let i = fn[0].length - 1; i < layer.length; i++) {
4675
+ if (layer[i] === '(') depth++;
4676
+ if (layer[i] === ')' && --depth === 0) {
4677
+ end = i;
4678
+ break;
4679
+ }
4680
+ }
4681
+ const rest = splitTop(layer.slice(end + 1).trim(), ' ');
4682
+ const REPEAT = /^(repeat|no-repeat|repeat-x|repeat-y|space|round)$/i;
4683
+ const repeat = rest.filter(w => REPEAT.test(w)).join(' ');
4684
+ const words = rest.filter(w => !REPEAT.test(w)).join(' ');
4685
+ const [position = '', size = ''] = words.split('/').map(x => x.trim());
4686
+ return {image: layer.slice(0, end + 1), position, size, repeat};
4687
+ }
4688
+
4689
+ /** A side word in a longhand's name, in the order a box value lists sides. */
4690
+ const BOX_SIDES = ['top', 'right', 'bottom', 'left'];
4691
+
4692
+ /**
4693
+ * A block's longhands that follow a shorthand covering them, where the base
4694
+ * theme's block holds the same key, rewritten as that longhand's own sides
4695
+ * (padding-inline as padding-inline-start and -end, border-color as the
4696
+ * four side colors), in place and at the same position; a state's block
4697
+ * nested in it too. A longhand that is no side pair or box is kept.
4698
+ * @param {Record<string, any>} b
4699
+ * @param {Record<string, any> | undefined} baseBlock
4700
+ */
4701
+ function laterLonghandsAsSides(b, baseBlock) {
4702
+ if (
4703
+ !b ||
4704
+ typeof b !== 'object' ||
4705
+ !baseBlock ||
4706
+ typeof baseBlock !== 'object'
4707
+ )
4708
+ return;
4709
+ for (const [k, v] of Object.entries(b))
4710
+ if (k.startsWith(':') && v && typeof v === 'object')
4711
+ laterLonghandsAsSides(v, baseBlock[k]);
4712
+ const keys = Object.keys(b);
4713
+ /** @type {Record<string, any>} */
4714
+ const out = {};
4715
+ let changed = false;
4716
+ keys.forEach((k, i) => {
4717
+ const v = b[k];
4718
+ const css = kebab(k);
4719
+ const sides =
4720
+ typeof v === 'string' &&
4721
+ !k.startsWith('-') &&
4722
+ typeof baseBlock[k] === 'string' &&
4723
+ keys
4724
+ .slice(0, i)
4725
+ .some(e => !e.startsWith(':') && coversSide(kebab(e), css))
4726
+ ? sidesOf(css, v)
4727
+ : null;
4728
+ if (!sides) {
4729
+ out[k] = v;
4730
+ return;
4731
+ }
4732
+ changed = true;
4733
+ for (const [p, x] of Object.entries(sides)) {
4734
+ delete out[camel(p)];
4735
+ out[camel(p)] = x;
4736
+ }
4737
+ });
4738
+ if (!changed) return;
4739
+ for (const k of Object.keys(b)) delete b[k];
4740
+ Object.assign(b, out);
4741
+ }
4742
+
4743
+ /**
4744
+ * A two-sided (start/end) or four-sided (top/right/bottom/left) longhand's
4745
+ * value, as each side's property and value by the shorthand rules; null for
4746
+ * any other property.
4747
+ * @param {string} prop kebab-case
4748
+ * @param {string} v
4749
+ * @returns {Record<string, string> | null}
4750
+ */
4751
+ function sidesOf(prop, v) {
4752
+ const direct = [...longhandsOf(prop)].filter(p => longhandsOf(p).size === 0);
4753
+ const w = splitTop(v.trim(), ' ').map(x => x.trim());
4754
+ if (!w.length || /!important/i.test(v)) return null;
4755
+ const start = direct.find(p => /-start(-|$)/.test(p));
4756
+ const end = direct.find(p => /-end(-|$)/.test(p));
4757
+ if (direct.length === 2 && start && end && w.length <= 2)
4758
+ return {[start]: w[0], [end]: w[1] ?? w[0]};
4759
+ const named = BOX_SIDES.map(side =>
4760
+ direct.find(p => new RegExp(`-${side}(-|$)`).test(p)),
4761
+ );
4762
+ if (direct.length !== 4 || named.some(x => !x) || w.length > 4) return null;
4763
+ const [t, r = t, bo = t, l = r] = w;
4764
+ const vals = [t, r, bo, l];
4765
+ return Object.fromEntries(
4766
+ named.map((p, i) => [/** @type {string} */ (p), vals[i]]),
4767
+ );
4768
+ }
4769
+
3206
4770
  /** Core's default type scale ratio. */
3207
4771
  const STANDARD_RATIO = 1.2;
3208
4772
  /** The font-size tokens below the base, with their step on the scale. */
@@ -3314,10 +4878,10 @@ export function maskedSettings(data, ctx = null) {
3314
4878
  * {font-weight}`. Find those rules in the built stylesheet.
3315
4879
  * @param {string} cssText
3316
4880
  * @param {any} theme
3317
- * @returns {Array<{target: string, key: string, prop: string, value: string}>}
4881
+ * @returns {Array<{target: string, key: string, prop: string, value: string, state?: string}>}
3318
4882
  */
3319
4883
  export function findOverrides(cssText, theme) {
3320
- /** @type {Array<{target: string, key: string, prop: string, value: string}>} */
4884
+ /** @type {Array<{target: string, key: string, prop: string, value: string, state?: string}>} */
3321
4885
  const extra = [];
3322
4886
  for (const [target, keys] of Object.entries(
3323
4887
  /** @type {Record<string, any>} */ (theme.components ?? {}),
@@ -3362,6 +4926,51 @@ export function findOverrides(cssText, theme) {
3362
4926
  }
3363
4927
  }
3364
4928
  }
4929
+ // A state setting on the plain part (a whole-part hover) loses the same
4930
+ // way to a variant's own rule in that state: it is repeated there too.
4931
+ for (const [target, keys] of Object.entries(
4932
+ /** @type {Record<string, any>} */ (theme.components ?? {}),
4933
+ ))
4934
+ for (const [state, decl] of Object.entries(keys.base ?? {})) {
4935
+ if (!/^:[a-z-]+$/.test(state) || !decl || typeof decl !== 'object')
4936
+ continue;
4937
+ const props = Object.keys(decl).filter(
4938
+ p => !p.startsWith('--') && !p.startsWith(':'),
4939
+ );
4940
+ if (!props.length) continue;
4941
+ const re = new RegExp(
4942
+ `\\.astryx-${target.replace(/-/g, '\\-')}\\[data-([a-z-]+)="([^"]+)"\\](?:${state}(?![\\w-])[^{}]*|\\s*)\\{([^}]*)\\}`,
4943
+ 'g',
4944
+ );
4945
+ // The variant's own rule in that state, and its resting rule: that
4946
+ // one comes after the plain state rule at the same weight.
4947
+ const seen = new Set();
4948
+ for (const m of cssText.matchAll(re)) {
4949
+ const declared = [...m[3].matchAll(/(?:^|[;\s])([a-z-]+)\s*:/g)].map(
4950
+ d => d[1],
4951
+ );
4952
+ for (const prop of props) {
4953
+ const css = kebab(prop);
4954
+ if (css === m[1] || css.endsWith(`-${m[1]}`)) continue;
4955
+ if (
4956
+ !seen.has(`${m[1]}:${m[2]} ${prop}`) &&
4957
+ declared.some(
4958
+ d =>
4959
+ d === css || coversProperty(d, css) || coversProperty(css, d),
4960
+ )
4961
+ ) {
4962
+ seen.add(`${m[1]}:${m[2]} ${prop}`);
4963
+ extra.push({
4964
+ target,
4965
+ key: `${m[1]}:${m[2]}`,
4966
+ state,
4967
+ prop,
4968
+ value: decl[prop],
4969
+ });
4970
+ }
4971
+ }
4972
+ }
4973
+ }
3365
4974
  return extra;
3366
4975
  }
3367
4976
 
@@ -3384,8 +4993,43 @@ const liftValue = (lift, only) =>
3384
4993
  * @param {ThemeData} data
3385
4994
  * @param {any} theme
3386
4995
  * @param {import('./_palette.mjs').PaletteMapping | null} pal
4996
+ * @param {string} [cwd]
4997
+ * @param {Record<string, any> | null} [baseParts] the base theme's components, whose state objects each written one starts from
3387
4998
  */
3388
- function settingsSource(slug, data, theme, pal, cwd = '') {
4999
+ function settingsSource(slug, data, theme, pal, cwd = '', baseParts = null) {
5000
+ // Core merges a theme's state object (`:hover` in a rule) over the base
5001
+ // theme's whole, one level deep: each one starts as the base theme's own
5002
+ // for that rule, so the properties no setting names keep the base's.
5003
+ if (baseParts) {
5004
+ theme = {...theme, components: {...(theme.components ?? {})}};
5005
+ for (const [target, keys] of Object.entries(theme.components)) {
5006
+ /** @type {Record<string, any>} */
5007
+ const next = {};
5008
+ for (const [key, rule] of Object.entries(
5009
+ /** @type {Record<string, any>} */ (keys),
5010
+ )) {
5011
+ if (!rule || typeof rule !== 'object') {
5012
+ next[key] = rule;
5013
+ continue;
5014
+ }
5015
+ /** @type {Record<string, any>} */
5016
+ const r = {...rule};
5017
+ for (const [k, v] of Object.entries(rule)) {
5018
+ const own = baseParts[target]?.[key]?.[k];
5019
+ if (
5020
+ k.startsWith(':') &&
5021
+ v &&
5022
+ typeof v === 'object' &&
5023
+ own &&
5024
+ typeof own === 'object'
5025
+ )
5026
+ r[k] = {...own, ...v};
5027
+ }
5028
+ next[key] = r;
5029
+ }
5030
+ theme.components[target] = next;
5031
+ }
5032
+ }
3389
5033
  const like = data.like;
3390
5034
  const REF = '@@palette:';
3391
5035
  /** @param {string} family @param {'light' | 'dark'} m @param {import('./_palette.mjs').StopRef} r */
@@ -3806,6 +5450,39 @@ function refuseOwnPairs(ctx, cwd, slug) {
3806
5450
  * @returns {Promise<string[]>}
3807
5451
  */
3808
5452
  export async function builtPairs(ctx, slug) {
5453
+ const tops = await cacheBuild(ctx, slug, js => topTokensOf(js));
5454
+ return [...(tops ?? [])]
5455
+ .filter(
5456
+ ([k, v]) =>
5457
+ /^light-dark\(/.test(String(v ?? '')) && ctx.C.typeOf(k) !== 'color',
5458
+ )
5459
+ .map(([k]) => k);
5460
+ }
5461
+
5462
+ /**
5463
+ * The page-wide tokens the theme's own source gives, as a build made now
5464
+ * evaluates them (an imported module, an expression, a template): read
5465
+ * from a build into the project's cache folder, never beside the theme.
5466
+ * Null when it does not build there.
5467
+ * @param {Ctx} ctx
5468
+ * @param {string} slug
5469
+ * @returns {Promise<Map<string, string | null> | null>}
5470
+ */
5471
+ export async function evaluatedOwnTokens(ctx, slug) {
5472
+ return cacheBuild(ctx, slug, js => builtOwnTokens(ctx.project.cwd, slug, js));
5473
+ }
5474
+
5475
+ /**
5476
+ * Build the theme into the project's cache folder and read the built
5477
+ * module with `read` before the folder is removed; null when it does not
5478
+ * build there.
5479
+ * @template T
5480
+ * @param {Ctx} ctx
5481
+ * @param {string} slug
5482
+ * @param {(js: string) => T} read
5483
+ * @returns {Promise<T | null>}
5484
+ */
5485
+ async function cacheBuild(ctx, slug, read) {
3809
5486
  const {cwd} = ctx.project;
3810
5487
  const f = themeFiles(cwd, slug);
3811
5488
  // The build writes only inside the project: the cache folder when it is
@@ -3826,15 +5503,10 @@ export async function builtPairs(ctx, slug) {
3826
5503
  const js = fs
3827
5504
  .readdirSync(dir)
3828
5505
  .find(n => n.endsWith('.js') && !n.endsWith('.d.js'));
3829
- if (!js) return [];
3830
- return [...topTokensOf(path.join(dir, js))]
3831
- .filter(
3832
- ([k, v]) =>
3833
- /^light-dark\(/.test(String(v ?? '')) && ctx.C.typeOf(k) !== 'color',
3834
- )
3835
- .map(([k]) => k);
5506
+ if (!js) return null;
5507
+ return read(path.join(dir, js));
3836
5508
  } catch {
3837
- return [];
5509
+ return null;
3838
5510
  } finally {
3839
5511
  logger.setSilent(silent);
3840
5512
  fs.rmSync(dir, {recursive: true, force: true});
@@ -3933,7 +5605,17 @@ export async function buildTheme(ctx, slug, data) {
3933
5605
  ctx.keepStops,
3934
5606
  );
3935
5607
  await step(() => {
3936
- writeWhole(f.settingsTs, settingsSource(slug, data, theme, pal, cwd));
5608
+ writeWhole(
5609
+ f.settingsTs,
5610
+ settingsSource(
5611
+ slug,
5612
+ data,
5613
+ theme,
5614
+ pal,
5615
+ cwd,
5616
+ /** @type {any} */ (base).components ?? null,
5617
+ ),
5618
+ );
3937
5619
  syncPaletteRefs(cwd, slug, fs.readFileSync(f.settingsTs, 'utf8'), pal);
3938
5620
  if (!fs.existsSync(f.ts)) writeWhole(f.ts, themeModuleSource(slug));
3939
5621
  });
@@ -3959,9 +5641,47 @@ export async function buildTheme(ctx, slug, data) {
3959
5641
  fs.rmSync(file, {force: true});
3960
5642
  forgetWritten(cwd, slug, pictures);
3961
5643
  });
3962
- let receipt = await step(() => runBuild(ctx, slug));
5644
+ let receipt = await step(() => runBuild(ctx, slug, data));
5645
+ // A state setting on the plain part that the own source's same state
5646
+ // rule wins over is not repeated on the variants either: the own source
5647
+ // wins on every variant, as the result says.
5648
+ /** @type {Map<string, Map<string, string | null>>} */
5649
+ const ownStates = new Map();
5650
+ /** @param {string} target @param {string} state @param {string} prop */
5651
+ const ownHolds = (target, state, prop) => {
5652
+ const k = `${target} ${state}`;
5653
+ const own =
5654
+ ownStates.get(k) ?? ownPartTokens(cwd, slug, target, 'base', state);
5655
+ ownStates.set(k, own);
5656
+ const css = kebab(prop);
5657
+ return [...own.keys()].some(
5658
+ o => o === css || coversProperty(o, css) || coversProperty(css, o),
5659
+ );
5660
+ };
3963
5661
  const found = findOverrides(fs.readFileSync(f.css, 'utf8'), theme).filter(
3964
- x => !(theme.components[x.target][x.key] ?? {})[x.prop],
5662
+ x =>
5663
+ // By property: a variant whose rule the settings give this property
5664
+ // or a shorthand covering it needs no copy; nor one holding a
5665
+ // longhand of it that the base theme's rule also holds and that has
5666
+ // no sides to be written as (a background color, one-mode or not):
5667
+ // the copy would come after it there and win. Any other longhand
5668
+ // takes the copy, then is written after it (as its sides where the
5669
+ // base holds it).
5670
+ !Object.entries(
5671
+ (x.state
5672
+ ? theme.components[x.target][x.key]?.[x.state]
5673
+ : theme.components[x.target][x.key]) ?? {},
5674
+ ).some(([k, v]) => {
5675
+ if (k.startsWith(':')) return false;
5676
+ if (k === x.prop || coversProperty(kebab(k), kebab(x.prop)))
5677
+ return true;
5678
+ if (!coversProperty(kebab(x.prop), kebab(k))) return false;
5679
+ const baseRule = /** @type {any} */ (base).components?.[x.target]?.[
5680
+ x.key
5681
+ ];
5682
+ const held = (x.state ? baseRule?.[x.state] : baseRule)?.[k];
5683
+ return held != null && sidesOf(kebab(k), String(v)) == null;
5684
+ }) && !(x.state && ownHolds(x.target, x.state, x.prop)),
3965
5685
  );
3966
5686
  /** @type {string[]} */
3967
5687
  const lifted = [];
@@ -3972,19 +5692,42 @@ export async function buildTheme(ctx, slug, data) {
3972
5692
  // longhand or shorthand the variant sets itself (border-color after
3973
5693
  // a base border) still wins over it.
3974
5694
  const own = t[x.key] ?? {};
5695
+ const ownState = x.state ? (own[x.state] ?? {}) : own;
3975
5696
  // A variant that sets every longhand of the property itself needs
3976
5697
  // none of the base value (and a lifted radius would feed Core's copy
3977
5698
  // of it into the content's radius, after the variant's own).
3978
5699
  const longs = [...longhandsOf(kebab(x.prop))];
3979
- if (longs.length && longs.every(l => camel(l) in own)) continue;
3980
- t[x.key] = {[x.prop]: x.value, ...own};
3981
- lifted.push(`${x.target} ${x.key} ${kebab(x.prop)}`);
5700
+ if (longs.length && longs.every(l => camel(l) in ownState)) continue;
5701
+ t[x.key] = x.state
5702
+ ? {...own, [x.state]: {[x.prop]: x.value, ...ownState}}
5703
+ : {[x.prop]: x.value, ...own};
5704
+ // The variant's own longhands come after the copied shorthand; one
5705
+ // the base theme holds would keep the base's earlier place and lose,
5706
+ // so it is written as its sides.
5707
+ const baseRule = /** @type {any} */ (base).components?.[x.target]?.[
5708
+ x.key
5709
+ ];
5710
+ laterLonghandsAsSides(
5711
+ x.state ? t[x.key][x.state] : t[x.key],
5712
+ x.state ? baseRule?.[x.state] : baseRule,
5713
+ );
5714
+ lifted.push(`${x.target} ${x.key}${x.state ?? ''} ${kebab(x.prop)}`);
3982
5715
  }
3983
5716
  await step(() => {
3984
- writeWhole(f.settingsTs, settingsSource(slug, data, theme, pal, cwd));
5717
+ writeWhole(
5718
+ f.settingsTs,
5719
+ settingsSource(
5720
+ slug,
5721
+ data,
5722
+ theme,
5723
+ pal,
5724
+ cwd,
5725
+ /** @type {any} */ (base).components ?? null,
5726
+ ),
5727
+ );
3985
5728
  syncPaletteRefs(cwd, slug, fs.readFileSync(f.settingsTs, 'utf8'), pal);
3986
5729
  });
3987
- receipt = await step(() => runBuild(ctx, slug));
5730
+ receipt = await step(() => runBuild(ctx, slug, data));
3988
5731
  }
3989
5732
  for (const out of [f.css, f.js])
3990
5733
  if (fs.existsSync(out))
@@ -4005,8 +5748,34 @@ export async function buildTheme(ctx, slug, data) {
4005
5748
  return {warnings, lifted, notes};
4006
5749
  }
4007
5750
 
4008
- /** @param {Ctx} ctx @param {string} slug @returns {Promise<any>} */
4009
- async function runBuild(ctx, slug) {
5751
+ /**
5752
+ * The one color mode of a light-only or dark-only theme, from its settings,
5753
+ * for the build to write into the built module (`colorModes`); null for a
5754
+ * theme with both modes.
5755
+ * @param {string} cwd
5756
+ * @param {string} slug
5757
+ * @returns {['light'] | ['dark'] | null}
5758
+ */
5759
+ export function buildColorModes(cwd, slug) {
5760
+ try {
5761
+ return oneColorMode(
5762
+ modesOf(
5763
+ JSON.parse(fs.readFileSync(themeFiles(cwd, slug).settings, 'utf8')),
5764
+ ),
5765
+ );
5766
+ } catch {
5767
+ return null;
5768
+ }
5769
+ }
5770
+
5771
+ /**
5772
+ * @param {Ctx} ctx
5773
+ * @param {string} slug
5774
+ * @param {{mode?: string}} [data] the settings being built (saved after the
5775
+ * build), whose mode the built module exports
5776
+ * @returns {Promise<any>}
5777
+ */
5778
+ async function runBuild(ctx, slug, data) {
4010
5779
  const {cwd} = ctx.project;
4011
5780
  const f = themeFiles(cwd, slug);
4012
5781
  const silent = logger.silent;
@@ -4020,6 +5789,11 @@ async function runBuild(ctx, slug) {
4020
5789
  {},
4021
5790
  {cwd},
4022
5791
  {compact: true},
5792
+ {
5793
+ colorModes: data
5794
+ ? oneColorMode(modesOf(data))
5795
+ : buildColorModes(cwd, slug),
5796
+ },
4023
5797
  );
4024
5798
  return receipt;
4025
5799
  } finally {
@@ -4046,6 +5820,7 @@ export async function outputsDrift(ctx, slug) {
4046
5820
  {check: true},
4047
5821
  {cwd},
4048
5822
  {compact: true},
5823
+ {colorModes: buildColorModes(cwd, slug)},
4049
5824
  );
4050
5825
  const first = /** @type {any} */ (receipt)?.data?.stale?.[0];
4051
5826
  if (!first) return null;
@@ -4227,7 +6002,7 @@ function nonTextToken(t, typeOf = (/** @type {string} */ _k) => 'other') {
4227
6002
  * @param {string} slug
4228
6003
  * @param {[string, unknown, ('object' | 'pair' | 'unit' | 'value' | 'mode')?]} bad
4229
6004
  */
4230
- function nonTextMessage(ctx, slug, [name, value, kind = 'value']) {
6005
+ export function nonTextMessage(ctx, slug, [name, value, kind = 'value']) {
4231
6006
  const type = ctx.C.typeOf(name);
4232
6007
  if (kind === 'mode') return ownPairMessage(slug, [name]);
4233
6008
  if (kind === 'object')
@@ -4452,8 +6227,26 @@ function parseSettings(text) {
4452
6227
  }
4453
6228
 
4454
6229
  /**
4455
- * Whether parsed settings have the shape the editor reads: an object with a
4456
- * list of settings.
6230
+ * Whether every settings entry has the parts the editor reads (a thing, a
6231
+ * value and a source); one without is damage `new` keeps aside.
6232
+ * @param {any} data
6233
+ */
6234
+ export function settingsEntriesOk(data) {
6235
+ return (
6236
+ settingsShapeOk(data) &&
6237
+ data.settings.every(
6238
+ (/** @type {any} */ s) =>
6239
+ s &&
6240
+ typeof s.thing === 'string' &&
6241
+ 'value' in s &&
6242
+ ['dial', 'token', 'property'].includes(s.source),
6243
+ )
6244
+ );
6245
+ }
6246
+
6247
+ /**
6248
+ * Whether settings data has the shape the editor reads: an object with a
6249
+ * settings list.
4457
6250
  * @param {any} data
4458
6251
  */
4459
6252
  export function settingsShapeOk(data) {
@@ -5067,6 +6860,21 @@ export function builtFiles(cwd, slug, data, some = false) {
5067
6860
  ];
5068
6861
  }
5069
6862
 
6863
+ /**
6864
+ * The file's stat, or undefined when it is not there. On Node 22.13 a folder
6865
+ * above the file that is a file throws ENOTDIR even with throwIfNoEntry
6866
+ * false; that file is not there either, as on later Node.
6867
+ * @param {string} file
6868
+ */
6869
+ function statIfThere(file) {
6870
+ try {
6871
+ return fs.statSync(file, {throwIfNoEntry: false});
6872
+ } catch (e) {
6873
+ if (/** @type {any} */ (e)?.code === 'ENOTDIR') return undefined;
6874
+ throw e;
6875
+ }
6876
+ }
6877
+
5070
6878
  /**
5071
6879
  * Refuse, by name, a built file that is there but cannot be read: its
5072
6880
  * permissions, or a folder where the file goes.
@@ -5075,7 +6883,7 @@ export function builtFiles(cwd, slug, data, some = false) {
5075
6883
  */
5076
6884
  function refuseUnreadable(cwd, files) {
5077
6885
  for (const file of files) {
5078
- const st = fs.statSync(file, {throwIfNoEntry: false});
6886
+ const st = statIfThere(file);
5079
6887
  if (!st) continue;
5080
6888
  const rel = shown(cwd, file);
5081
6889
  if (st.isDirectory())