@astryxdesign/cli 0.7.16 → 0.7.17-canary.g9a957aa

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 (229) hide show
  1. package/README.md +12 -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 +47 -9
  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 +32 -0
  14. package/api/build/kit/words.mjs +49 -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 +48 -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 +491 -186
  34. package/api/render/render.doc.mjs +10 -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 +38 -0
  46. package/api/theme/build/build.mjs +144 -24
  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 +35 -0
  50. package/api/theme-edit/_adapter.mjs +477 -41
  51. package/api/theme-edit/_check.d.mts +28 -22
  52. package/api/theme-edit/_check.mjs +1077 -200
  53. package/api/theme-edit/_compiler.mjs +9 -0
  54. package/api/theme-edit/_context.mjs +60 -3
  55. package/api/theme-edit/_css.mjs +21 -1
  56. package/api/theme-edit/_edit.d.mts +22 -0
  57. package/api/theme-edit/_edit.mjs +932 -82
  58. package/api/theme-edit/_how-commands.d.mts +49 -0
  59. package/api/theme-edit/_how-commands.mjs +386 -1
  60. package/api/theme-edit/_how-question.d.mts +56 -0
  61. package/api/theme-edit/_how-question.mjs +3509 -168
  62. package/api/theme-edit/_how.mjs +104 -4
  63. package/api/theme-edit/_marks.d.mts +31 -5
  64. package/api/theme-edit/_marks.mjs +57 -5
  65. package/api/theme-edit/_normal.d.mts +137 -0
  66. package/api/theme-edit/_normal.mjs +612 -0
  67. package/api/theme-edit/_palette.mjs +10 -4
  68. package/api/theme-edit/_parts.d.mts +4 -0
  69. package/api/theme-edit/_parts.mjs +28 -2
  70. package/api/theme-edit/_preview-app.d.mts +7 -1
  71. package/api/theme-edit/_preview-app.mjs +191 -15
  72. package/api/theme-edit/_preview.d.mts +64 -8
  73. package/api/theme-edit/_preview.mjs +401 -83
  74. package/api/theme-edit/_settings.d.mts +139 -5
  75. package/api/theme-edit/_settings.mjs +1659 -112
  76. package/api/theme-edit/_tables.mjs +17 -1
  77. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  78. package/api/theme-edit/theme-edit.type.mjs +4 -1
  79. package/api/theme-edit/themeEditPreviewApp.doc.mjs +2 -2
  80. package/assets/codemods/run-codemod.mjs +73 -6
  81. package/assets/codemods/transforms/next/index.mjs +11 -1
  82. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  83. package/assets/docs/author-a-theme.doc.mjs +1 -0
  84. package/assets/docs/theme.doc.dense.mjs +2 -2
  85. package/assets/docs/theme.doc.mjs +1 -1
  86. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  87. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  88. package/assets/docs/tree/render-pages.doc.mjs +43 -2
  89. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  90. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  91. package/assets/docs/use-a-theme.doc.mjs +1 -1
  92. package/assets/docs.generated.json +2 -2
  93. package/assets/self-audit.generated.json +1 -1
  94. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  95. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  96. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  97. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  98. package/assets/templates/components.generated.json +1 -1
  99. package/assets/templates/pages/ai-chat/template.doc.mjs +8 -4
  100. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +2 -1
  101. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  102. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  103. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  104. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  105. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  106. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  107. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  108. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  109. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  110. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  111. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  112. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  113. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  114. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  115. package/assets/templates/pages/editor/template.doc.mjs +1 -7
  116. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  117. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  118. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  119. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  120. package/assets/templates/pages/ide/page.tsx +24 -2
  121. package/assets/templates/pages/library/template.doc.mjs +4 -1
  122. package/assets/templates/pages/login/template.doc.mjs +2 -1
  123. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  124. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  125. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  126. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  127. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  128. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  129. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  130. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  131. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  132. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  133. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  134. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  135. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  136. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  137. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  138. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  139. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -1
  140. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  141. package/authoring/debug/parse.d.mts +3 -3
  142. package/authoring/doctypes/_schema.d.mts +3 -3
  143. package/authoring/doctypes/command/command.doc.mjs +1 -1
  144. package/authoring/doctypes/template/template.doc.mjs +1 -1
  145. package/authoring/doctypes/template/type.ts +9 -0
  146. package/clients/cli/bin/astryx.mjs +6 -9
  147. package/clients/cli/build-id.generated.json +1 -1
  148. package/clients/cli/commands/component.doc.mjs +1 -1
  149. package/clients/cli/commands/component.mjs +20 -2
  150. package/clients/cli/commands/docs.doc.mjs +7 -1
  151. package/clients/cli/commands/docs.mjs +3 -1
  152. package/clients/cli/commands/doctor.mjs +22 -14
  153. package/clients/cli/commands/experimental/render.mjs +32 -1
  154. package/clients/cli/commands/experimental/theme.mjs +27 -2
  155. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  156. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  157. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  158. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  159. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  160. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  161. package/clients/cli/commands/search.doc.mjs +2 -1
  162. package/clients/cli/commands/search.mjs +6 -1
  163. package/clients/cli/commands/template.mjs +4 -2
  164. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  165. package/clients/cli/commands/theme.doc.mjs +1 -1
  166. package/clients/cli/commands/theme.mjs +138 -3
  167. package/clients/cli/commands/upgrade.mjs +42 -7
  168. package/clients/cli/index.mjs +1 -1
  169. package/clients/cli/lib/component-format.mjs +205 -98
  170. package/clients/cli/lib/hook-format.mjs +9 -19
  171. package/clients/cli/manifest.generated.json +1 -1
  172. package/foundation/agent-docs/agent-docs.mjs +1 -1
  173. package/foundation/config/theme-state.d.mts +13 -1
  174. package/foundation/config/theme-state.mjs +47 -7
  175. package/foundation/discovery/component-discovery.d.mts +11 -0
  176. package/foundation/discovery/component-discovery.mjs +27 -2
  177. package/foundation/discovery/component-replacement.mjs +130 -1
  178. package/foundation/discovery/entry-name-files.d.mts +43 -0
  179. package/foundation/discovery/entry-name-files.mjs +264 -0
  180. package/foundation/discovery/hook-discovery.d.mts +8 -2
  181. package/foundation/discovery/hook-discovery.mjs +20 -7
  182. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  183. package/foundation/discovery/runner-allowlist.mjs +2 -0
  184. package/foundation/discovery/template-adapter.d.mts +52 -0
  185. package/foundation/discovery/template-adapter.mjs +169 -0
  186. package/foundation/discovery/theme-imports.d.mts +14 -0
  187. package/foundation/discovery/theme-imports.mjs +43 -1
  188. package/foundation/doc-compiler/import.mjs +7 -1
  189. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  190. package/foundation/doc-compiler/stored-docs.d.mts +22 -0
  191. package/foundation/doc-compiler/stored-docs.mjs +49 -0
  192. package/foundation/fs/cache-eviction.d.mts +21 -0
  193. package/foundation/fs/cache-eviction.mjs +73 -0
  194. package/foundation/fs/gather-cache.d.mts +25 -4
  195. package/foundation/fs/gather-cache.mjs +138 -52
  196. package/foundation/fs/jiti-cache.d.mts +19 -1
  197. package/foundation/fs/jiti-cache.mjs +130 -6
  198. package/foundation/fs/kept-tree.d.mts +60 -0
  199. package/foundation/fs/kept-tree.mjs +154 -0
  200. package/foundation/fs/module-loader.d.mts +18 -2
  201. package/foundation/fs/module-loader.mjs +92 -20
  202. package/foundation/identity/provider-identity.d.mts +6 -0
  203. package/foundation/identity/provider-identity.mjs +10 -1
  204. package/foundation/render/file-header.d.mts +66 -0
  205. package/foundation/render/file-header.mjs +118 -0
  206. package/foundation/render/host-answer.d.mts +18 -0
  207. package/foundation/render/host-answer.mjs +46 -0
  208. package/foundation/render/host-exit.d.mts +1 -0
  209. package/foundation/render/host-exit.mjs +6 -1
  210. package/foundation/render/html-reader.d.mts +55 -2
  211. package/foundation/render/html-reader.mjs +145 -26
  212. package/foundation/render/markup-edits.d.mts +57 -0
  213. package/foundation/render/markup-edits.mjs +182 -0
  214. package/foundation/render/page-host.mjs +29 -12
  215. package/foundation/render/page-worker.mjs +79 -10
  216. package/foundation/render/render-page.d.mts +34 -2
  217. package/foundation/render/render-page.mjs +210 -29
  218. package/foundation/render/source-block.d.mts +73 -6
  219. package/foundation/render/source-block.mjs +170 -19
  220. package/foundation/render/ts-paths.d.mts +4 -1
  221. package/foundation/render/ts-paths.mjs +7 -3
  222. package/foundation/response/error-codes.d.mts +2 -1
  223. package/foundation/response/error-codes.doc.mjs +7 -1
  224. package/foundation/response/error-codes.mjs +7 -0
  225. package/foundation/text/string-utils.d.mts +3 -2
  226. package/foundation/text/string-utils.mjs +16 -3
  227. package/foundation/text/suggest-order.d.mts +9 -0
  228. package/foundation/text/suggest-order.mjs +13 -0
  229. 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,7 +25,7 @@ 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
30
  AUTO_SPREAD,
31
31
  CORNERS,
@@ -46,6 +46,7 @@ import {
46
46
  WRAPPED_PARTS,
47
47
  CARD_LIKE,
48
48
  } from './_tables.mjs';
49
+ import {cleanDialValue} from './_normal.mjs';
49
50
  import {
50
51
  alphaOf,
51
52
  colorProblem,
@@ -116,7 +117,7 @@ setOwnTokenReader((cwd, slug) => ownSourceTokenValues(cwd, slug));
116
117
  /** What lifted secondary text sits on: the contrast check measures it there. */
117
118
  const LIFT_GROUND_TOKENS = new Set(LIFT_PARTS.map(([, , g]) => g));
118
119
 
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 */
120
+ /** @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
121
  /** @typedef {import('./_parts.mjs').PaintSide} PaintSide */
121
122
  /** @typedef {import('./_parts.mjs').TextPair} TextPair */
122
123
 
@@ -197,20 +198,35 @@ export function themeFiles(cwd, slug) {
197
198
  }
198
199
 
199
200
  /** 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']);
201
+ export const FOLDER_JUNK = new Set([
202
+ '.DS_Store',
203
+ '.gitkeep',
204
+ 'Thumbs.db',
205
+ 'desktop.ini',
206
+ ]);
201
207
 
202
208
  /**
203
209
  * Whether `dir` holds nothing of anyone's: absent, empty, or only system
204
210
  * files (what `git rm -r` or a branch switch leaves). A path that is not a
205
211
  * folder, or one that does not read, is not empty.
206
212
  * @param {string} dir
213
+ * @returns {boolean}
207
214
  */
208
215
  export function folderIsEmpty(dir) {
209
216
  if (!fs.existsSync(dir)) return true;
210
217
  try {
218
+ // A folder holding only empty folders (an empty tokens/) holds nothing
219
+ // either; a link is never followed.
211
220
  return (
212
221
  fs.lstatSync(dir).isDirectory() &&
213
- fs.readdirSync(dir).every(n => FOLDER_JUNK.has(n))
222
+ fs
223
+ .readdirSync(dir)
224
+ .every(
225
+ n =>
226
+ FOLDER_JUNK.has(n) ||
227
+ (fs.lstatSync(path.join(dir, n)).isDirectory() &&
228
+ folderIsEmpty(path.join(dir, n))),
229
+ )
214
230
  );
215
231
  } catch {
216
232
  return false;
@@ -485,16 +501,19 @@ export const shown = (cwd, f) =>
485
501
  * @param {number} [n]
486
502
  */
487
503
  export function nearest(x, list, n = 3) {
504
+ const limit = Math.max(2, Math.floor(x.length / 3));
505
+ // Nearest by edit distance first (brand-drak is brand-dark, not brand); a
506
+ // name one holds inside the other is near too, after the close ones.
488
507
  return [...list]
489
508
  .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)))
509
+ .map(c => {
510
+ const d = levenshteinDistance(x, c);
511
+ return /** @type {[string, number]} */ ([
512
+ c,
513
+ d <= limit ? d : c.includes(x) || x.includes(c) ? limit + 0.5 : d,
514
+ ]);
515
+ })
516
+ .filter(([, s]) => s <= limit + 0.5)
498
517
  .sort((a, b) => a[1] - b[1])
499
518
  .slice(0, n)
500
519
  .map(([c]) => c);
@@ -577,6 +596,79 @@ export function typedThemeName(s) {
577
596
  );
578
597
  }
579
598
 
599
+ /**
600
+ * The theme names a name typed the way the app shows it may mean, most
601
+ * likely first: a path with doubled slashes or `../` (`themes//t`), a file
602
+ * name with or without its folder (`brand.theme.ts`, `tTheme.ts`), the app
603
+ * copy's export (`tTheme`), camelCase (`brandDark`) and spaces
604
+ * (`Brand Dark`) each read as dashes. The caller picks the first that
605
+ * exists, else the first.
606
+ * @param {string} s
607
+ * @returns {string[]}
608
+ */
609
+ export function themeNameReadings(s) {
610
+ const base = unlabeledThemeName(String(s ?? ''))
611
+ .replace(/[\\/]+/g, '/')
612
+ .replace(/^(\.\.?\/)+/, '')
613
+ .replace(/^.*themes\//i, '')
614
+ .replace(/\/.*$/, '')
615
+ .replace(
616
+ /\.(theme\.ts|settings\.(json|ts)|history\.json|css\.d\.ts|d\.ts|doc\.mjs|fonts\.css|css|mjs|js|tsx?)$/i,
617
+ '',
618
+ )
619
+ .trim();
620
+ const noTheme = base.replace(/([a-z0-9])Theme$/, '$1');
621
+ const read = [base, noTheme === base ? '' : noTheme]
622
+ .flatMap(x => [kebab(x), x.toLowerCase()])
623
+ .filter(x => /[a-z]/i.test(x))
624
+ .map(x => slugFor(x));
625
+ // A module name in any letters (brandtheme, brand-theme) last: only
626
+ // when the theme it names exists does it win.
627
+ const moduleNames = read
628
+ .map(n => n.replace(/-?theme$/, ''))
629
+ .filter(n => n && slugOk(n));
630
+ return [...new Set([...read, ...moduleNames])];
631
+ }
632
+
633
+ /**
634
+ * A vibrancy written as set reads typed input: a share of one (0.5) or a
635
+ * percent (50%) is that much of the 0-100 scale, as a whole number. Any
636
+ * other dial's value, or a vibrancy that is no such number, comes back as
637
+ * it was.
638
+ * @param {string} dial
639
+ * @param {string} v
640
+ * @returns {string}
641
+ */
642
+ export function vibrancyMeant(dial, v) {
643
+ if (dial !== 'vibrancy') return v;
644
+ const m = /^(\d*\.?\d+)\s*(%?)$/.exec(v.trim());
645
+ if (!m) return v;
646
+ const n = Number(m[1]);
647
+ const scaled = !m[2] && n > 0 && n < 1 ? n * 100 : n;
648
+ return scaled <= 100 ? String(Math.round(scaled)) : v;
649
+ }
650
+
651
+ /**
652
+ * The mode and base a damaged theme file meant, read the way typed input
653
+ * is: other letters, stray spaces, `_` or a space for a dash (`Dark-Only`,
654
+ * ` Neutral`), and a base written as its package name
655
+ * (`@astryxdesign/theme-neutral`). Each is the cleaned text even when it is
656
+ * no value the editor takes; the caller checks it.
657
+ * @param {any} data
658
+ * @returns {{mode: string, like: string}}
659
+ */
660
+ export function fieldsMeant(data) {
661
+ const mode = String(data?.mode ?? '')
662
+ .trim()
663
+ .toLowerCase()
664
+ .replace(/[\s_]+/g, '-');
665
+ const like = String(data?.like ?? '')
666
+ .trim()
667
+ .toLowerCase()
668
+ .replace(/^@astryxdesign\/theme-/, '');
669
+ return {mode, like};
670
+ }
671
+
580
672
  /**
581
673
  * The settings of a theme, or a refusal naming the command that makes it.
582
674
  * @param {string} cwd
@@ -605,9 +697,22 @@ export function loadTheme(
605
697
  );
606
698
  const plain = typedThemeName(slug);
607
699
  const named = slugFor(plain);
700
+ // brandDark is brand-dark.
701
+ const camelWords = slugFor(
702
+ unlabeledThemeName(String(slug ?? '')).replace(
703
+ /([a-z0-9])([A-Z])/g,
704
+ '$1-$2',
705
+ ),
706
+ );
608
707
  const exists = (/** @type {string} */ n) =>
609
708
  Boolean(n) && fs.existsSync(themeFiles(cwd, n).settings);
610
- const fixed = !exists(named) && exists(whole) ? whole : named;
709
+ // The module or export name (brandTheme, the app copy's brandTheme.ts)
710
+ // names the theme brand: one reader for every way a name is typed.
711
+ const readings = themeNameReadings(slug);
712
+ const fixed =
713
+ [named, whole, camelWords, ...readings].find(exists) ??
714
+ readings[0] ??
715
+ named;
611
716
  const same = fs.existsSync(themeFiles(cwd, fixed).settings) ? fixed : null;
612
717
  // A list where one theme goes (t,u or "t;u"): one theme at a time,
613
718
  // each that exists named; never a new theme made of the list. A name
@@ -741,6 +846,30 @@ export function loadTheme(
741
846
  `themes/${slug} is an empty folder: there is no theme ${slug} yet. new makes it there.`,
742
847
  {run: [`${P} new ${slug}`]},
743
848
  );
849
+ // The editor's own app copy left behind when themes/<slug>/ is gone
850
+ // (a git clean, a wrong rm, a branch switch): `new` makes the theme
851
+ // again and writes the copy over.
852
+ const copyName = `${camel(slug)}Theme`;
853
+ if (
854
+ !same &&
855
+ other &&
856
+ other[1] === `src/themes/${slug}` &&
857
+ !fs.existsSync(f.dir) &&
858
+ [`${copyName}.ts`, `${copyName}.doc.mjs`, `${slug}.fonts.css`].some(n => {
859
+ try {
860
+ return fs
861
+ .readFileSync(path.join(other[0], n), 'utf8')
862
+ .includes(APP_COPY_MARK);
863
+ } catch {
864
+ return false;
865
+ }
866
+ })
867
+ )
868
+ refuse(
869
+ ERROR_CODES.ERR_UNKNOWN_THEME,
870
+ `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).`,
871
+ {run: [`${P} new ${slug}`]},
872
+ );
744
873
  if (!same && (other || LIKE.includes(slug)))
745
874
  refuse(
746
875
  ERROR_CODES.ERR_UNKNOWN_THEME,
@@ -760,7 +889,24 @@ export function loadTheme(
760
889
  ERROR_CODES.ERR_UNKNOWN_THEME,
761
890
  `There is no theme "${slug}" made by this command (no themes/${slug}/${slug}.settings.json).`,
762
891
  (() => {
763
- const near = same ? [same] : nearest(slug, have);
892
+ // A doubled or trailing dash (brand--dark, t--): the name as new
893
+ // cleans it, the theme of that name when there is one, never a new
894
+ // theme new refuses.
895
+ const cleaned = String(slug)
896
+ .replace(/-{2,}/g, '-')
897
+ .replace(/^-+|-+$/g, '');
898
+ const cleanedHere =
899
+ cleaned !== slug &&
900
+ slugOk(cleaned) &&
901
+ fs.existsSync(themeFiles(cwd, cleaned).settings)
902
+ ? cleaned
903
+ : null;
904
+ const near = same
905
+ ? [same]
906
+ : cleanedHere
907
+ ? [cleanedHere]
908
+ : nearest(slug, have);
909
+ const newName = usableNewName(cwd, cleaned || slug);
764
910
  // A theme near the name comes first; a new theme of the name as
765
911
  // typed only after.
766
912
  return {
@@ -768,8 +914,8 @@ export function loadTheme(
768
914
  run: same
769
915
  ? [`${P} show ${same}`]
770
916
  : near.length
771
- ? [`${P} show ${near[0]}`, `${P} new ${slug}`]
772
- : [`${P} new ${slug}`],
917
+ ? [`${P} show ${near[0]}`, `${P} new ${newName}`]
918
+ : [`${P} new ${newName}`],
773
919
  };
774
920
  })(),
775
921
  );
@@ -854,23 +1000,62 @@ export function loadTheme(
854
1000
  })),
855
1001
  ERROR_CODES.ERR_THEME_INVALID,
856
1002
  );
857
- const bad = problem ? badSetting(data) : null;
1003
+ // A damaged mode or base is fixed first: the message names it, so the
1004
+ // suggestions set it (another bad value is named on the next run).
1005
+ // (Not an entry named mode or base inside the settings list.)
1006
+ const fieldBroken =
1007
+ (/^(it has no mode|mode ")/.test(problem ?? '') &&
1008
+ !['both', 'light-only', 'dark-only'].includes(data?.mode)) ||
1009
+ (/^base "/.test(problem ?? '') &&
1010
+ data?.like != null &&
1011
+ !LIKE.includes(data.like));
1012
+ const bad = problem && !fieldBroken ? badSetting(data) : null;
858
1013
  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'
1014
+ // The value it holds, cleaned as typed input is (stray or invisible
1015
+ // spaces, other letters, a pasted `corners: pill`), when the dial takes
1016
+ // that; else a value it takes, for a dial; a color for a color token.
1017
+ const cleaned =
1018
+ DIALS[bad.thing] && typeof bad.value === 'string'
1019
+ ? vibrancyMeant(bad.thing, cleanDialValue(bad.thing, bad.value))
864
1020
  : null;
1021
+ // Vibrancy saturates the colors the color dials make: with none, set
1022
+ // refuses it as having no effect, so it is not offered.
1023
+ const vibrancyActs =
1024
+ bad.thing !== 'vibrancy' ||
1025
+ (Array.isArray(data.settings) ? data.settings : []).some(
1026
+ (/** @type {any} */ x) =>
1027
+ x && x.source === 'dial' && PALETTE_DIALS.includes(x.thing),
1028
+ );
1029
+ const meant =
1030
+ cleaned &&
1031
+ cleaned !== bad.value &&
1032
+ vibrancyActs &&
1033
+ !valueProblem({...bad, value: cleaned})
1034
+ ? cleaned
1035
+ : null;
1036
+ // Only the value it holds, cleaned: never a stock value it did not hold.
1037
+ // A vibrancy with no color to saturate is one set refuses: undo only.
1038
+ const example =
1039
+ bad.thing === 'vibrancy' &&
1040
+ !data.settings.some(
1041
+ (/** @type {any} */ x) =>
1042
+ x !== bad && x.source === 'dial' && PALETTE_DIALS.includes(x.thing),
1043
+ )
1044
+ ? null
1045
+ : meant;
865
1046
  throw new AstryxError(
866
1047
  `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
1048
  [
868
1049
  {name: `${P} undo ${slug} ${undoArgs(bad)}`, reason: 'do this instead'},
869
- ...(example
1050
+ // Only a set that replaces this very entry: `mode` and `base` set
1051
+ // the theme's own fields, not an entry in the list.
1052
+ ...(example && !['mode', 'base'].includes(bad.thing)
870
1053
  ? [
871
1054
  {
872
1055
  name: `${P} set ${slug} ${undoArgs(bad).replace(bad.thing, `${bad.thing} ${quoteCommandArgument(example)}`)}`,
873
- reason: 'or give it a value it takes',
1056
+ reason: meant
1057
+ ? 'or set the value it holds, cleaned'
1058
+ : 'or give it a value it takes',
874
1059
  },
875
1060
  ]
876
1061
  : []),
@@ -880,17 +1065,53 @@ export function loadTheme(
880
1065
  }
881
1066
  // A bad mode or base is fixed by setting it.
882
1067
  // 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();
1068
+ const {mode: modeMeant, like: likeMeant} = fieldsMeant(data);
889
1069
  const fieldFix = /^(it has no mode|mode ")/.test(problem ?? '')
890
1070
  ? `${P} set ${slug} mode ${['both', 'light-only', 'dark-only'].includes(modeMeant) ? modeMeant : 'both'}`
891
1071
  : /^base "/.test(problem ?? '')
892
1072
  ? `${P} set ${slug} base ${LIKE.includes(likeMeant) && baseInstalled(cwd, likeMeant) ? likeMeant : 'none'}`
893
1073
  : null;
1074
+ // A damaged mode or base and a bad value in the list: setting the field
1075
+ // is refused while the list holds the bad value, but fixing that entry
1076
+ // saves the field as meant too, so its fix comes first. Never a bare
1077
+ // undo, which would throw away the last real change.
1078
+ const alsoBad = fieldFix ? badSetting(data) : null;
1079
+ if (problem && fieldFix && alsoBad) {
1080
+ const cleaned =
1081
+ DIALS[alsoBad.thing] && typeof alsoBad.value === 'string'
1082
+ ? vibrancyMeant(
1083
+ alsoBad.thing,
1084
+ cleanDialValue(alsoBad.thing, alsoBad.value),
1085
+ )
1086
+ : null;
1087
+ const meant =
1088
+ cleaned &&
1089
+ cleaned !== alsoBad.value &&
1090
+ !['mode', 'base'].includes(alsoBad.thing) &&
1091
+ !valueProblem({...alsoBad, value: cleaned})
1092
+ ? cleaned
1093
+ : null;
1094
+ const field = /^base "/.test(problem) ? 'base' : 'mode';
1095
+ const fieldValue = fieldFix.split(' ').pop();
1096
+ throw new AstryxError(
1097
+ `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.`,
1098
+ [
1099
+ ...(meant
1100
+ ? [
1101
+ {
1102
+ name: `${P} set ${slug} ${undoArgs(alsoBad).replace(alsoBad.thing, `${alsoBad.thing} ${quoteCommandArgument(meant)}`)}`,
1103
+ reason: 'do this instead: set the value it holds, cleaned',
1104
+ },
1105
+ ]
1106
+ : []),
1107
+ {
1108
+ name: `${P} undo ${slug} ${undoArgs(alsoBad)}`,
1109
+ reason: meant ? 'or remove that setting' : 'do this instead',
1110
+ },
1111
+ ],
1112
+ ERROR_CODES.ERR_THEME_INVALID,
1113
+ );
1114
+ }
894
1115
  // A setting listed twice: setting it to one of its values, or undoing
895
1116
  // it, keeps one entry or none.
896
1117
  const twice = problem?.includes(' is listed twice (')
@@ -900,7 +1121,7 @@ export function loadTheme(
900
1121
  throw new AstryxError(
901
1122
  `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
1123
  fieldFix
903
- ? [{name: fieldFix, reason: 'do this instead'}, ...recover.run]
1124
+ ? [{name: fieldFix, reason: 'do this instead'}]
904
1125
  : twice
905
1126
  ? [
906
1127
  ...twice.values
@@ -961,9 +1182,11 @@ export function settingsProblem(
961
1182
  ) {
962
1183
  if (!data || typeof data !== 'object' || Array.isArray(data))
963
1184
  return 'the file is not a settings object';
964
- // `set <theme> mode` and `set <theme> base` fix their own field.
1185
+ // A command that changes or removes a setting (or sets mode or base)
1186
+ // puts a damaged mode or base back to its default itself, with a note, so
1187
+ // two damaged fields never send each fix to the other.
965
1188
  const fixing = typeof skip === 'string' ? skip : skip?.thing;
966
- const field = fixing === 'mode' || fixing === 'base';
1189
+ const field = Boolean(fixing);
967
1190
  if (!field && !['both', 'light-only', 'dark-only'].includes(data.mode))
968
1191
  return data.mode == null
969
1192
  ? 'it has no mode'
@@ -1040,6 +1263,10 @@ export function badSettings(data) {
1040
1263
  export function undoArgs(x) {
1041
1264
  return [
1042
1265
  quoteCommandArgument(String(x.thing)),
1266
+ // The tracking half of headings is named, so the undo reaches it even
1267
+ // when it is listed twice (a bare `undo headings` then reads the weight
1268
+ // half).
1269
+ ...(x.thing === 'headings' && x.axis === 'tracking' ? ['tracking'] : []),
1043
1270
  ...(x.on ? [`--on ${quoteCommandArgument(String(x.on))}`] : []),
1044
1271
  ...(x.when ? [`--when ${quoteCommandArgument(String(x.when))}`] : []),
1045
1272
  ...(x.state ? [`--state ${quoteCommandArgument(String(x.state))}`] : []),
@@ -1133,6 +1360,27 @@ export function valueProblem(s) {
1133
1360
  return null;
1134
1361
  }
1135
1362
 
1363
+ /**
1364
+ * One entry of the top-level `tokens` map in a theme's own source, as
1365
+ * written: its token (null for a computed key no read of the file can
1366
+ * resolve), the key as typed, the line that sets it, and its value's shape.
1367
+ * @typedef {{token: string | null, key: string, line: number | null, kind: 'text' | 'number' | 'pair' | 'other', value?: string | number, halves?: Array<string | number | undefined>}} OwnTokenEntry
1368
+ */
1369
+
1370
+ /**
1371
+ * The entries of the top-level `tokens` map in a theme's own source, read
1372
+ * from its syntax tree, each with the line that sets it.
1373
+ * @param {string} cwd
1374
+ * @param {string} slug
1375
+ * @returns {OwnTokenEntry[]}
1376
+ */
1377
+ export function ownTokenEntries(cwd, slug) {
1378
+ /** @type {OwnTokenEntry[]} */
1379
+ const detail = [];
1380
+ ownPageTokens(cwd, slug, detail);
1381
+ return detail;
1382
+ }
1383
+
1136
1384
  /**
1137
1385
  * The page-wide tokens a theme's own source sets: the keys of the top-level
1138
1386
  * `tokens` map in its `defineTheme({...})`, read from the syntax tree, each
@@ -1142,7 +1390,11 @@ export function valueProblem(s) {
1142
1390
  * @param {string} slug
1143
1391
  * @returns {Map<string, string | null>}
1144
1392
  */
1145
- function ownPageTokens(cwd, slug) {
1393
+ function ownPageTokens(
1394
+ cwd,
1395
+ slug,
1396
+ detail = /** @type {OwnTokenEntry[] | null} */ (null),
1397
+ ) {
1146
1398
  /** @type {Map<string, string | null>} */
1147
1399
  const out = new Map();
1148
1400
  /** @type {string} */
@@ -1256,15 +1508,47 @@ function ownPageTokens(cwd, slug) {
1256
1508
  unresolved = true;
1257
1509
  return;
1258
1510
  }
1259
- // Spreads and keys merge in order: a later one wins.
1511
+ // Spreads and keys merge in order: a later one wins. A computed key
1512
+ // that is text (`['--radius-page']`) is read like a literal one.
1260
1513
  for (const p of obj.properties) {
1261
1514
  if (p.type === 'SpreadElement') collect(p.argument, depth + 1);
1262
- else if (p.type === 'ObjectProperty' && !p.computed) {
1263
- const k = keyOf(p.key);
1515
+ else if (p.type === 'ObjectProperty') {
1516
+ const k = p.computed ? textOf(unwrap(p.key)) : keyOf(p.key);
1264
1517
  if (k?.startsWith('--')) out.set(k, textOf(unwrap(p.value)));
1518
+ else if (p.computed) unresolved = true;
1519
+ if (detail && (k?.startsWith('--') || p.computed))
1520
+ detail.push({
1521
+ token: k?.startsWith('--') ? k : null,
1522
+ key: code.slice(p.key.start, p.key.end),
1523
+ line: p.loc?.start?.line ?? null,
1524
+ ...valueShape(unwrap(p.value)),
1525
+ });
1265
1526
  } else unresolved = true;
1266
1527
  }
1267
1528
  };
1529
+ /**
1530
+ * What a token's value is, as written: text, a number, a [light, dark]
1531
+ * pair (each half's text, a number, or undefined), or something else.
1532
+ * @param {any} node
1533
+ * @returns {Pick<OwnTokenEntry, 'kind' | 'value' | 'halves'>}
1534
+ */
1535
+ const valueShape = node => {
1536
+ const t = textOf(node);
1537
+ if (t != null) return {kind: 'text', value: t};
1538
+ if (node?.type === 'NumericLiteral')
1539
+ return {kind: 'number', value: node.value};
1540
+ if (node?.type === 'ArrayExpression')
1541
+ return {
1542
+ kind: 'pair',
1543
+ halves: node.elements.map((/** @type {any} */ e) => {
1544
+ const h = unwrap(e);
1545
+ return (
1546
+ textOf(h) ?? (h?.type === 'NumericLiteral' ? h.value : undefined)
1547
+ );
1548
+ }),
1549
+ };
1550
+ return {kind: 'other'};
1551
+ };
1268
1552
  collect(tokensProp.value, 0);
1269
1553
  // A value no read of the file can resolve (a call, an import) is read
1270
1554
  // from the build (ownTokens), and checked again after the next one.
@@ -1541,6 +1825,27 @@ export function partRuleTokens(cwd, slug, like, part) {
1541
1825
  return out;
1542
1826
  }
1543
1827
 
1828
+ /**
1829
+ * Whether the base theme's own source gives a part's rule a property, in a
1830
+ * state (`:hover`) or at rest, read from its module as written.
1831
+ * @param {string} cwd
1832
+ * @param {string | undefined} like
1833
+ * @param {string} part
1834
+ * @param {string} scope `base` or a variant such as `variant:secondary`
1835
+ * @param {string | null} state a state block (`:hover`), or null
1836
+ * @param {string} prop camelCase
1837
+ */
1838
+ export function baseRuleHas(cwd, like, part, scope, state, prop) {
1839
+ const file = like ? baseModule(cwd, like) : null;
1840
+ if (!file) return false;
1841
+ try {
1842
+ const at = ['components', part, scope, ...(state ? [state] : [])];
1843
+ return blockOf(file, at).has(prop);
1844
+ } catch {
1845
+ return false;
1846
+ }
1847
+ }
1848
+
1544
1849
  /**
1545
1850
  * The tokens and properties a theme's own source sets on a part's plain
1546
1851
  * rule, read from the build as ownTokens reads page-wide ones: what the
@@ -1774,7 +2079,7 @@ export function ownSourceTokenValues(cwd, slug) {
1774
2079
  function scopeProblem(s) {
1775
2080
  if (s.on != null && !/^[a-z][a-z0-9-]*$/.test(s.on))
1776
2081
  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))
2082
+ if (s.state != null && !/^[a-z][a-zA-Z-]*$/.test(s.state))
1778
2083
  return `${s.thing} has state "${s.state}", which is not a state name`;
1779
2084
  if (s.when != null && !/^[\w-]+:[\w.-]+$/.test(s.when))
1780
2085
  return `${s.thing} has --when "${s.when}", which is not prop:value`;
@@ -1787,7 +2092,9 @@ function scopeProblem(s) {
1787
2092
  export const keyOf = s =>
1788
2093
  [
1789
2094
  s.thing,
1790
- s.axis ?? '',
2095
+ // A headings value saved with no axis is its weight half, as the build
2096
+ // reads it, so a set or undo of the weight replaces it.
2097
+ s.thing === 'headings' ? (s.axis ?? 'weight') : (s.axis ?? ''),
1791
2098
  s.on ?? '',
1792
2099
  s.when ?? '',
1793
2100
  s.state ?? '',
@@ -1959,6 +2266,44 @@ function partDefault(ctx, target, prop, when, state) {
1959
2266
  return r ? `var(${r.token})` : null;
1960
2267
  }
1961
2268
 
2269
+ /**
2270
+ * The variants (`variant:<name>`) of a part that each read their own value
2271
+ * of a color property (the button's background, a badge's text), in a
2272
+ * state when one is named and changes it: one rule's other-mode half would
2273
+ * give every one of them one variant's color. Empty when the part reads one
2274
+ * value for all.
2275
+ * @param {Ctx} ctx
2276
+ * @param {string} target
2277
+ * @param {string} prop camelCase or kebab-case
2278
+ * @param {string} [state]
2279
+ * @returns {string[]}
2280
+ */
2281
+ function variantsReading(ctx, target, prop, state) {
2282
+ const k = kebab(prop);
2283
+ const g = ctx.C.groupOfProp(k === 'background' ? 'background-color' : k);
2284
+ if (!g) return [];
2285
+ const reads = ctx.C.partReads(target, g).filter(x =>
2286
+ x.props.some(
2287
+ p => p === k || (k === 'background' && p === 'background-color'),
2288
+ ),
2289
+ );
2290
+ const named = (/** @type {(w: string) => boolean} */ ok) => [
2291
+ ...new Set(
2292
+ reads
2293
+ .flatMap(x => x.when)
2294
+ .filter(ok)
2295
+ .map(w => /(?:^|,)variant=([\w-]+)/.exec(w)?.[1])
2296
+ .filter(Boolean)
2297
+ .map(n => `variant:${n}`),
2298
+ ),
2299
+ ];
2300
+ const inState = state ? named(w => w.includes(`:${state}`)) : [];
2301
+ if (inState.length) return inState;
2302
+ return reads.some(x => x.when.includes(''))
2303
+ ? []
2304
+ : named(w => /^variant=[\w-]+$/.test(w));
2305
+ }
2306
+
1962
2307
  /** The line that records a generated module's own hash. */
1963
2308
  const SEAL = /^\/\/ Module ([0-9a-f]{16})\.\n/m;
1964
2309
 
@@ -2101,6 +2446,138 @@ function keepShades(pal, kept) {
2101
2446
  return {...pal, tokens, lift: kept['lifted parts'] ? pal.lift : null};
2102
2447
  }
2103
2448
 
2449
+ /**
2450
+ * A size in px: px, rem (16px each), or a calc() of those added and
2451
+ * subtracted; null for anything else.
2452
+ * @param {string} v
2453
+ * @param {Record<string, string>} [vars] values for the tokens a var() may name
2454
+ * @returns {number | null}
2455
+ */
2456
+ export function sizePx(v, vars = {}) {
2457
+ let t = String(v).trim();
2458
+ // A token the dial or the theme gives a value (var(--spacing-12)),
2459
+ // through that value; a clamp() at its preferred value held to its
2460
+ // bounds, or its upper bound when the preferred one is no length;
2461
+ // min() and max() of the lengths they hold.
2462
+ const fn = /^(var|clamp|min|max)\((.*)\)$/is.exec(t);
2463
+ if (fn) {
2464
+ const args = splitTop(fn[2], ',').map(x => x.trim());
2465
+ if (fn[1].toLowerCase() === 'var') {
2466
+ const own = vars[args[0]];
2467
+ if (own != null) return sizePx(own, vars);
2468
+ return args[1] != null ? sizePx(args.slice(1).join(','), vars) : null;
2469
+ }
2470
+ const n = args.map(x => sizePx(x, vars));
2471
+ if (fn[1].toLowerCase() === 'clamp') {
2472
+ const [lo, mid, hi] = n;
2473
+ if (lo == null || hi == null) return null;
2474
+ return mid == null ? hi : Math.min(hi, Math.max(lo, mid));
2475
+ }
2476
+ const known = /** @type {number[]} */ (n.filter(x => x != null));
2477
+ if (!known.length) return null;
2478
+ return fn[1].toLowerCase() === 'min'
2479
+ ? Math.min(...known)
2480
+ : Math.max(...known);
2481
+ }
2482
+ const calc = /^calc\((.*)\)$/is.exec(t);
2483
+ if (calc) t = calc[1].trim();
2484
+ const terms =
2485
+ t.match(/[+-]?\s*[\d.]+(?:px|rem|em|pt|pc|in|cm|mm|q)\b|\S+/gi) ?? [];
2486
+ let sum = 0;
2487
+ let sign = 1;
2488
+ for (const raw of terms) {
2489
+ const x = raw.replace(/\s+/g, '');
2490
+ if (x === '+' || x === '-') {
2491
+ if (!calc) return null;
2492
+ sign = x === '-' ? -1 : 1;
2493
+ continue;
2494
+ }
2495
+ const m = /^([+-]?)([\d.]+)(px|rem|em|pt|pc|in|cm|mm|q)$/i.exec(x);
2496
+ if (!m || (!calc && terms.length > 1)) return null;
2497
+ // Absolute units by their fixed ratio to px; em and rem against the
2498
+ // 16px a control's text starts from.
2499
+ const n = parseFloat(m[2]) * (PX_PER[m[3].toLowerCase()] ?? 1);
2500
+ if (!Number.isFinite(n)) return null;
2501
+ sum += (m[1] === '-' ? -1 : 1) * sign * n;
2502
+ sign = 1;
2503
+ }
2504
+ return terms.length ? sum : null;
2505
+ }
2506
+
2507
+ /** Pixels per unit of each length unit a kept size may be written in. */
2508
+ const PX_PER = /** @type {Record<string, number>} */ ({
2509
+ px: 1,
2510
+ rem: 16,
2511
+ em: 16,
2512
+ pt: 96 / 72,
2513
+ pc: 16,
2514
+ in: 96,
2515
+ cm: 96 / 2.54,
2516
+ mm: 96 / 25.4,
2517
+ q: 96 / 101.6,
2518
+ });
2519
+
2520
+ /**
2521
+ * Spacing steps scaled with the spacing dial, kept in order around the
2522
+ * steps the theme keeps exact: each the plain scaled value unless it would
2523
+ * meet or pass a kept one; those are spread evenly between the kept one and
2524
+ * the nearest step that keeps its place. A step with no room below a kept
2525
+ * one takes the value of the one below it.
2526
+ * @param {Array<[string, number]>} steps token name and the base value, in px
2527
+ * @param {number} f the rung's factor
2528
+ * @param {Record<string, number>} kept exact steps the theme keeps, in px
2529
+ * @param {string[]} [noRoom] filled with the steps left no room
2530
+ * @returns {Array<[string, number]>} every step's new value in px, kept ones as kept
2531
+ */
2532
+ export function spacingSteps(steps, f, kept, noRoom = []) {
2533
+ const px = [...steps].sort((a, b) => a[1] - b[1]);
2534
+ const n = px.map(([k, v]) => (k in kept ? kept[k] : v * f));
2535
+ const isKept = (/** @type {number} */ i) => px[i][0] in kept;
2536
+ px.forEach(([, base], k) => {
2537
+ if (!isKept(k)) return;
2538
+ // The steps below that would meet or pass it are spread evenly between
2539
+ // the last one that does not and it.
2540
+ let j0 = k;
2541
+ while (
2542
+ j0 > 0 &&
2543
+ !isKept(j0 - 1) &&
2544
+ n[j0 - 1] >= n[k] &&
2545
+ px[j0 - 1][1] < base
2546
+ )
2547
+ j0--;
2548
+ if (j0 < k) {
2549
+ const lo = j0 > 0 ? n[j0 - 1] : 0;
2550
+ if (lo >= n[k])
2551
+ for (let j = j0; j < k; j++) {
2552
+ n[j] = lo;
2553
+ noRoom.push(px[j][0]);
2554
+ }
2555
+ else
2556
+ for (let j = j0; j < k; j++)
2557
+ n[j] = lo + ((n[k] - lo) * (j - j0 + 1)) / (k - j0 + 1);
2558
+ }
2559
+ // The steps above that would meet or fall under it, likewise up to the
2560
+ // next one that does not (or above it by their own scaled steps).
2561
+ let j1 = k;
2562
+ while (
2563
+ j1 < n.length - 1 &&
2564
+ !isKept(j1 + 1) &&
2565
+ n[j1 + 1] <= n[k] &&
2566
+ px[j1 + 1][1] > base
2567
+ )
2568
+ j1++;
2569
+ if (j1 > k) {
2570
+ const hi = j1 < n.length - 1 ? n[j1 + 1] : null;
2571
+ for (let j = k + 1; j <= j1; j++)
2572
+ n[j] =
2573
+ hi == null
2574
+ ? n[k] + (px[j][1] - base) * f
2575
+ : n[k] + ((hi - n[k]) * (j - k)) / (j1 - k + 1);
2576
+ }
2577
+ });
2578
+ return px.map(([k], i) => [k, n[i]]);
2579
+ }
2580
+
2104
2581
  /**
2105
2582
  * Control heights scaled with the spacing dial (a denser theme has shorter
2106
2583
  * controls), each kept distinct and in order: smallest to largest, a
@@ -2110,28 +2587,44 @@ function keepShades(pal, kept) {
2110
2587
  * scaled above it.
2111
2588
  * @param {Array<[string, string]>} sizes token name and the theme's value
2112
2589
  * @param {number} f the spacing rung's factor
2590
+ * @param {Record<string, number>} [kept] exact sizes the theme keeps, in px,
2591
+ * which the others stay in order around
2592
+ * @param {string[]} [noRoom] filled with the sizes left no room between
2593
+ * two kept ones (each then equals the one below it)
2113
2594
  * @returns {Array<[string, string]>} the tokens it writes, in px
2114
2595
  */
2115
- export function controlSizes(sizes, f) {
2596
+ export function controlSizes(sizes, f, kept = {}, noRoom = []) {
2116
2597
  const px = sizes
2117
2598
  .filter(([, v]) => /^[\d.]+px$/.test(String(v).trim()))
2118
2599
  .map(([k, v]) => /** @type {[string, number]} */ ([k, parseFloat(v)]))
2119
2600
  .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;
2601
+ /** @type {number[]} */
2602
+ const n = px.map(([k, v]) =>
2603
+ k in kept ? kept[k] : Math.max(Math.min(24, v), Math.round(v * f)),
2604
+ );
2605
+ /** The step between two sizes, scaled. @param {number} i */
2606
+ const step = i => Math.max(1, Math.round((px[i][1] - px[i - 1][1]) * f));
2607
+ // Only a size that would meet (or pass) the one below moves, up; then one
2608
+ // that would meet a kept size above it moves down (a kept size stays).
2609
+ for (let i = 1; i < n.length; i++)
2610
+ if (!(px[i][0] in kept) && n[i] <= n[i - 1]) n[i] = n[i - 1] + step(i);
2611
+ for (let i = n.length - 2; i >= 0; i--)
2612
+ if (!(px[i][0] in kept) && n[i] >= n[i + 1]) n[i] = n[i + 1] - step(i + 1);
2613
+ // A size between two that cannot both move (kept, or one kept and the
2614
+ // other already at its place) sits halfway between them; with no room
2615
+ // between them it takes the smaller one's size, and the result says so.
2616
+ for (let i = 1; i < n.length - 1; i++)
2617
+ if (!(px[i][0] in kept) && (n[i] <= n[i - 1] || n[i] >= n[i + 1])) {
2618
+ const mid = Math.round(((n[i - 1] + n[i + 1]) / 2) * 2) / 2;
2619
+ if (mid > n[i - 1] && mid < n[i + 1]) n[i] = mid;
2620
+ else {
2621
+ n[i] = n[i - 1];
2622
+ noRoom.push(px[i][0]);
2623
+ }
2624
+ }
2625
+ return px
2626
+ .map(([k], i) => /** @type {[string, string]} */ ([k, `${n[i]}px`]))
2627
+ .filter(([k]) => !(k in kept));
2135
2628
  }
2136
2629
 
2137
2630
  /**
@@ -2142,6 +2635,8 @@ export function controlSizes(sizes, f) {
2142
2635
  * @returns {any}
2143
2636
  */
2144
2637
  export function compileTheme(ctx, data, base) {
2638
+ ctx.sizeNotes = [];
2639
+ ctx.compileNotes = [];
2145
2640
  // A setting the editor no longer accepts never reaches the build.
2146
2641
  data = {...data, settings: data.settings.filter(s => !valueProblem(s))};
2147
2642
  const TOKENS = ctx.project.core.tokenDefaults;
@@ -2164,6 +2659,44 @@ export function compileTheme(ctx, data, base) {
2164
2659
  : data.mode === 'dark-only'
2165
2660
  ? 'dark'
2166
2661
  : null;
2662
+ /** The tokens the theme's own source sets, which win over the settings. */
2663
+ /** @type {Record<string, string> | null} */
2664
+ let ownTok = null;
2665
+ const ownTokenValues = () => {
2666
+ if (ownTok) return ownTok;
2667
+ try {
2668
+ ownTok = ownSourceTokenValues(ctx.project.cwd, data.name);
2669
+ } catch {
2670
+ ownTok = {};
2671
+ }
2672
+ return ownTok;
2673
+ };
2674
+ /**
2675
+ * The exact tokens kept where a dial writes (whole theme with no part):
2676
+ * the whole-theme settings', then the own source's, by name.
2677
+ * @param {string | null} t a part, for its own settings too
2678
+ * @returns {Map<string, string>}
2679
+ */
2680
+ const keptTokens = t => {
2681
+ /** @type {Map<string, string>} */
2682
+ const out = new Map();
2683
+ for (const x of data.settings)
2684
+ if (
2685
+ x.source === 'token' &&
2686
+ !x.when &&
2687
+ !x.state &&
2688
+ !(modeOnly && x.mode && x.mode !== modeOnly) &&
2689
+ (!x.on || (t != null && partsOf(ctx, x).includes(t)))
2690
+ )
2691
+ out.set(x.thing, String(x.value));
2692
+ for (const [k, v] of Object.entries(ownTokenValues())) out.set(k, v);
2693
+ return out;
2694
+ };
2695
+ /** @param {string | null} t */
2696
+ const keptSizes = t =>
2697
+ [...keptTokens(t)].filter(([k]) => /^--size-element-/.test(k));
2698
+ /** The one-mode gradient layers each block holds, by mode. @type {WeakMap<object, {light: string[], dark: string[]}>} */
2699
+ const modeLayers = new WeakMap();
2167
2700
  /** @type {Record<string, {light?: string, dark?: string}>} */
2168
2701
  const tok = {};
2169
2702
  /** @param {string} name @param {string | [string, string]} v @param {string} [mode] */
@@ -2177,12 +2710,22 @@ export function compileTheme(ctx, data, base) {
2177
2710
  if (!mode || mode === 'dark') t.dark = v[1];
2178
2711
  return;
2179
2712
  }
2180
- if (!MODAL.has(ctx.C.typeOf(name)) || modeOnly || !mode) {
2713
+ // A color set in a one-mode theme fills its mode's half only; the other
2714
+ // half keeps what it had (the base theme's), for the regions Core draws
2715
+ // in the other mode.
2716
+ const half = mode ?? modeOnly;
2717
+ // Only a color has a half per mode (light-dark() takes colors only): a
2718
+ // shadow or any other value in a one-mode theme is written whole.
2719
+ if (
2720
+ !MODAL.has(ctx.C.typeOf(name)) ||
2721
+ !half ||
2722
+ (!mode && !parseColor(String(v).trim()))
2723
+ ) {
2181
2724
  t.light = v;
2182
2725
  t.dark = v;
2183
2726
  return;
2184
2727
  }
2185
- t[/** @type {'light' | 'dark'} */ (mode)] = v;
2728
+ t[/** @type {'light' | 'dark'} */ (half)] = v;
2186
2729
  };
2187
2730
  /** @param {Setting} s @param {string} target @returns {Record<string, any>} */
2188
2731
  const block = (s, target) => {
@@ -2471,9 +3014,11 @@ export function compileTheme(ctx, data, base) {
2471
3014
  return n && n.unit === '' && n.value === 0 ? '0px' : v;
2472
3015
  };
2473
3016
  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;
3017
+ // The own source's padding on the same rule wins over the editor's on
3018
+ // the sides it sets (the result says so); the editor's other sides
3019
+ // still apply.
3020
+ const own = ownBox(target, s);
3021
+ if (own.ltr.size === 4 && own.rtl.size === 4) continue;
2477
3022
  const prefix = /** @type {string} */ (padVars(target));
2478
3023
  const owner = prefix.slice('--astryx-'.length, -'-padding'.length);
2479
3024
  const scoped = target !== owner || s.when != null || s.state != null;
@@ -2517,6 +3062,10 @@ export function compileTheme(ctx, data, base) {
2517
3062
  }
2518
3063
  }
2519
3064
  }
3065
+ // The sides the own source pads in a direction are its own there.
3066
+ for (const dir of /** @type {const} */ (['ltr', 'rtl']))
3067
+ for (const x of Object.keys(side[dir]))
3068
+ if (own[dir].has(boxSide(x, dir))) delete side[dir][x];
2520
3069
  /** @type {Record<string, string>} */
2521
3070
  let plain = {};
2522
3071
  /** @type {Record<string, string>} */
@@ -2586,6 +3135,78 @@ export function compileTheme(ctx, data, base) {
2586
3135
  b[key] = {...(b[key] ?? {}), ...rule};
2587
3136
  }
2588
3137
  }
3138
+ // A variant the own source pads: the sides it sets are left without a
3139
+ // side variable there, so the variant's own padding (which Core writes
3140
+ // as the whole padding) wins over any side the plain rule writes.
3141
+ for (const owner of new Set(
3142
+ [...padQueue.values()]
3143
+ .filter(({target, s}) => !s.when && !s.state && padVars(target))
3144
+ .map(({target}) =>
3145
+ /** @type {string} */ (padVars(target)).slice(
3146
+ '--astryx-'.length,
3147
+ -'-padding'.length,
3148
+ ),
3149
+ ),
3150
+ )) {
3151
+ const values = ctx.C.variantValues(owner);
3152
+ for (const [prop, vals] of Object.entries(values ?? {}))
3153
+ for (const v of /** @type {string[]} */ (vals ?? [])) {
3154
+ const when = `${prop}:${v}`;
3155
+ const own = ownBox(owner, /** @type {any} */ ({when}));
3156
+ if (!own.ltr.size && !own.rtl.size) continue;
3157
+ const variant = /** @type {any} */ ({when});
3158
+ const logical = [
3159
+ 'block-start',
3160
+ 'block-end',
3161
+ 'inline-start',
3162
+ 'inline-end',
3163
+ ];
3164
+ const at = (/** @type {'ltr' | 'rtl'} */ dir) =>
3165
+ logical.filter(x => own[dir].has(boxSide(x, dir)));
3166
+ const [l, r] = [at('ltr'), at('rtl')];
3167
+ const b = block(variant, owner);
3168
+ for (const x of l.filter(x => r.includes(x)))
3169
+ b[`--astryx-${owner}-padding-${x}`] ??= 'initial';
3170
+ // A pair variable the plain rule writes (the inline or block
3171
+ // padding) feeds both its sides, under the side variables: where
3172
+ // the own source pads both, it is left without a value too, so
3173
+ // the variant's own padding holds there.
3174
+ for (const pair of ['block', 'inline'])
3175
+ if (
3176
+ [`${pair}-start`, `${pair}-end`].every(
3177
+ x => l.includes(x) && r.includes(x),
3178
+ )
3179
+ )
3180
+ b[`--astryx-${owner}-padding-${pair}`] ??= 'initial';
3181
+ // Its own sides inherit into a plain one of the part inside it:
3182
+ // they are reset there like the editor's (below).
3183
+ const sel = narrowSelector(owner, variant);
3184
+ if (sel) {
3185
+ const bySel = narrow.get(owner) ?? new Map();
3186
+ const names = bySel.get(sel) ?? new Set();
3187
+ for (const x of new Set([...l, ...r]))
3188
+ names.add(`--astryx-${owner}-padding-${x}`);
3189
+ for (const pair of ['block', 'inline'])
3190
+ if ([...l, ...r].some(x => x.startsWith(pair)))
3191
+ names.add(`--astryx-${owner}-padding-${pair}`);
3192
+ bySel.set(sel, names);
3193
+ narrow.set(owner, bySel);
3194
+ }
3195
+ for (const [dir, xs] of /** @type {const} */ ([
3196
+ [':dir(ltr)', l.filter(x => !r.includes(x))],
3197
+ [':dir(rtl)', r.filter(x => !l.includes(x))],
3198
+ ]))
3199
+ if (xs.length) {
3200
+ const [db, key] = dirBlock(variant, owner, dir);
3201
+ db[key] = {
3202
+ ...(db[key] ?? {}),
3203
+ ...Object.fromEntries(
3204
+ xs.map(x => [`--astryx-${owner}-padding-${x}`, 'initial']),
3205
+ ),
3206
+ };
3207
+ }
3208
+ }
3209
+ }
2589
3210
  // A plain part inside a narrower one: each side the narrower selector
2590
3211
  // writes is reset (left without a value, so Core's own fallback holds),
2591
3212
  // on the part's own class at its own weight, before any base setting a
@@ -2668,25 +3289,66 @@ export function compileTheme(ctx, data, base) {
2668
3289
  return out;
2669
3290
  };
2670
3291
  /**
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).
3292
+ * The box side a padding side names in a direction: a physical side as it
3293
+ * is, a logical one as the direction reads it (inline-start is the left in
3294
+ * left-to-right text, the right in right-to-left).
3295
+ * @param {string} x top, right, bottom, left, or a logical side
3296
+ * @param {'ltr' | 'rtl'} dir
3297
+ */
3298
+ const boxSide = (x, dir) =>
3299
+ ({
3300
+ 'block-start': 'top',
3301
+ 'block-end': 'bottom',
3302
+ 'inline-start': dir === 'ltr' ? 'left' : 'right',
3303
+ 'inline-end': dir === 'ltr' ? 'right' : 'left',
3304
+ })[x] ?? x;
3305
+ /**
3306
+ * The padding sides a padding property names, as it names them (physical
3307
+ * stays physical, logical stays logical), with each one's value.
3308
+ * @param {string} prop kebab-case
3309
+ * @param {string} value
3310
+ * @returns {Record<string, string>}
3311
+ */
3312
+ const paddingSides = (prop, value) => {
3313
+ const w = splitTop(String(value).trim(), ' ').map(y => y.trim());
3314
+ if (prop === 'padding') {
3315
+ const [top, right = top, bottom = top, left = right] = w;
3316
+ return {top, right, bottom, left};
3317
+ }
3318
+ if (prop === 'padding-block')
3319
+ return {'block-start': w[0], 'block-end': w[1] ?? w[0]};
3320
+ if (prop === 'padding-inline')
3321
+ return {'inline-start': w[0], 'inline-end': w[1] ?? w[0]};
3322
+ const side = prop.slice('padding-'.length);
3323
+ return /^(top|right|bottom|left|(block|inline)-(start|end))$/.test(side)
3324
+ ? {[side]: w[0]}
3325
+ : {};
3326
+ };
3327
+ /**
3328
+ * The box sides the theme's own source pads on a part's rule for a scope
3329
+ * (its plain rule, a variant, a state), in each direction.
2673
3330
  * @param {string} target @param {Setting} s
3331
+ * @returns {Record<'ltr' | 'rtl', Set<string>>}
2674
3332
  */
2675
- const ownPads = (target, s) => {
3333
+ const ownBox = (target, s) => {
3334
+ const out = {ltr: new Set(), rtl: new Set()};
2676
3335
  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));
3336
+ for (const k of ownPartTokens(
3337
+ ctx.project.cwd,
3338
+ data.name,
3339
+ target,
3340
+ s.when ?? 'base',
3341
+ s.state ? `:${s.state}` : null,
3342
+ ).keys())
3343
+ for (const x of Object.keys(paddingSides(k, '0')))
3344
+ for (const dir of /** @type {const} */ (['ltr', 'rtl']))
3345
+ out[dir].add(boxSide(x, dir));
2686
3346
  } catch {
2687
- return false;
3347
+ // No own source.
2688
3348
  }
3349
+ return out;
2689
3350
  };
3351
+
2690
3352
  /**
2691
3353
  * The selector a narrower padding scope is written with (a clickable
2692
3354
  * card's class, a variant's attribute, a state's pseudo-class), or null
@@ -2712,11 +3374,18 @@ export function compileTheme(ctx, data, base) {
2712
3374
  const keys = Object.keys(b);
2713
3375
  const plain = keys.filter(k => !k.startsWith(':'));
2714
3376
  const dirs = keys.filter(k => /^:(where\()?dir\(/.test(k));
3377
+ // The reset a plain part inside a narrower one gets comes before the
3378
+ // part's own direction rules at the same weight, so a side the part
3379
+ // sets for a direction holds inside a variant too.
3380
+ const resets = keys.filter(k => /^:where\((?!:?dir\().* \*\)$/.test(k));
2715
3381
  const rest = keys.filter(
2716
- k => k.startsWith(':') && !/^:(where\()?dir\(/.test(k),
3382
+ k =>
3383
+ k.startsWith(':') &&
3384
+ !/^:(where\()?dir\(/.test(k) &&
3385
+ !resets.includes(k),
2717
3386
  );
2718
3387
  return Object.fromEntries(
2719
- [...plain, ...dirs, ...rest].map(k => [
3388
+ [...plain, ...resets, ...dirs, ...rest].map(k => [
2720
3389
  k,
2721
3390
  k.startsWith(':') && b[k] && typeof b[k] === 'object'
2722
3391
  ? dirFirst(b[k])
@@ -2767,16 +3436,265 @@ export function compileTheme(ctx, data, base) {
2767
3436
  const parent = block({...s, state: undefined}, target);
2768
3437
  return [parent, `${stateKey(s.state, wrapsOneControl(ctx, target))}${dir}`];
2769
3438
  };
3439
+ /**
3440
+ * One half of a light-dark() pair (1 light, 2 dark), or the value itself.
3441
+ * @param {string} x @param {1 | 2} side
3442
+ */
3443
+ const halfOf = (x, side) => {
3444
+ const inner = /^light-dark\((.*)\)$/s.exec(x.trim())?.[1];
3445
+ const halves = inner == null ? [] : splitTop(inner, ',');
3446
+ return halves.length === 2 ? halves[side - 1].trim() : x.trim();
3447
+ };
3448
+ /**
3449
+ * The value a variant of a part shows for a color property where the
3450
+ * theme sets none of its own: the base theme's rule for that variant (in
3451
+ * the state, else at rest), else Core's, else transparent for a
3452
+ * background Core never paints; null for a text color Core never sets.
3453
+ * @param {string} target @param {string} css a color longhand, kebab-case
3454
+ * @param {string} name the variant @param {string} [state]
3455
+ * @param {boolean} [stateOnly] the state's own value only, never the resting one
3456
+ * @returns {string | null}
3457
+ */
3458
+ const exactVariantValue = (target, css, name, state, stateOnly = false) => {
3459
+ const when = `variant:${name}`;
3460
+ const kebabs =
3461
+ css === 'background-color' ? ['background-color', 'background'] : [css];
3462
+ const props = kebabs.map(camel);
3463
+ const steps = state
3464
+ ? stateOnly
3465
+ ? [state]
3466
+ : [state, undefined]
3467
+ : [undefined];
3468
+ for (const st of steps)
3469
+ for (const p of props) {
3470
+ const b = baseComponent(base, ctx, target, p, {when, state: st});
3471
+ if (b != null) return b;
3472
+ }
3473
+ const keyOf = (/** @type {string} */ k) => {
3474
+ const [attrs, cond = ''] = k.split(' ');
3475
+ return attrs.split(',').includes(`variant=${name}`) ? cond : null;
3476
+ };
3477
+ for (const st of steps)
3478
+ for (const p of kebabs) {
3479
+ const at = ctx.C.MAP[target]?.at?.[p];
3480
+ for (const [k, val] of Object.entries(at ?? {})) {
3481
+ const cond = keyOf(k);
3482
+ if (cond == null) continue;
3483
+ if (st ? cond.includes(`:${st}`) : cond === '') return val;
3484
+ }
3485
+ }
3486
+ if (stateOnly) return null;
3487
+ return css === 'background-color'
3488
+ ? 'transparent'
3489
+ : css === 'color'
3490
+ ? null
3491
+ : 'currentcolor';
3492
+ };
3493
+ /** The family a color property belongs to: background is background-color. @param {string} p */
3494
+ const colorFamily = p => {
3495
+ const k = kebab(p);
3496
+ return k === 'background' ? 'background-color' : k;
3497
+ };
2770
3498
  /** @param {Setting} s @param {string} target @param {string} prop @param {string} v */
2771
3499
  const putComp = (s, target, prop, v) => {
2772
3500
  const b = block(s, target);
2773
- if (s.mode && !modeOnly) {
3501
+ // A gradient background for one mode: each layer's colors are painted
3502
+ // in that mode only (transparent in the other), as background images
3503
+ // beside the other mode's, so each mode keeps its own background color;
3504
+ // a gradient for both modes held before keeps showing in the other
3505
+ // mode. Which layers belong to which mode is recorded as they are
3506
+ // written, never read back from their stops.
3507
+ if (
3508
+ s.mode &&
3509
+ /^background(-image)?$/.test(kebab(prop)) &&
3510
+ /gradient\(/i.test(v)
3511
+ ) {
3512
+ let rec = modeLayers.get(b);
3513
+ if (!rec) {
3514
+ rec = {light: [], dark: []};
3515
+ for (const k of ['background', 'backgroundImage']) {
3516
+ const held = b[k];
3517
+ if (typeof held !== 'string' || !/gradient\(/i.test(held)) continue;
3518
+ rec.light.push(...maskLayers(held, 'light'));
3519
+ rec.dark.push(...maskLayers(held, 'dark'));
3520
+ if (k === 'backgroundImage') delete b[k];
3521
+ }
3522
+ modeLayers.set(b, rec);
3523
+ }
3524
+ rec[s.mode] = maskLayers(v, s.mode);
3525
+ const parts = [...rec.light, ...rec.dark].map(layerParts);
3526
+ for (const k of [
3527
+ 'backgroundImage',
3528
+ 'backgroundPosition',
3529
+ 'backgroundSize',
3530
+ 'backgroundRepeat',
3531
+ ])
3532
+ delete b[k];
3533
+ b.backgroundImage = parts.map(x => x.image).join(', ');
3534
+ if (parts.some(x => x.position || x.size || x.repeat)) {
3535
+ b.backgroundPosition = parts.map(x => x.position || '0% 0%').join(', ');
3536
+ b.backgroundSize = parts.map(x => x.size || 'auto').join(', ');
3537
+ b.backgroundRepeat = parts.map(x => x.repeat || 'repeat').join(', ');
3538
+ }
3539
+ return;
3540
+ }
3541
+ // A color set in a one-mode theme fills its mode's half only (as a
3542
+ // setting for that mode does), so a region Core draws in the other mode
3543
+ // reads the other half.
3544
+ const mode =
3545
+ s.mode ??
3546
+ (modeOnly && parseColor(String(v).trim()) ? modeOnly : undefined);
3547
+ if (mode && !s.when && variantsReading(ctx, target, prop, s.state).length) {
3548
+ // A color for one mode on a part whose variants each have their own:
3549
+ // each variant's rule (in the state, for a state setting) gets the
3550
+ // color in that mode and, in the other, exactly the value it shows
3551
+ // unset there (the base theme's, else Core's), so no variant takes
3552
+ // another's and the other mode stays as it was. The part's own rule
3553
+ // is left alone.
3554
+ // The property itself (a border color stays a border color); the
3555
+ // background shorthand is written as its color.
3556
+ const css = colorFamily(prop);
3557
+ const other = mode === 'light' ? 2 : 1;
3558
+ // What the part's own rule holds of it (an earlier setting for both
3559
+ // modes): the other half each variant keeps, before its unset value.
3560
+ const plainHeld = [
3561
+ css,
3562
+ ...(css === 'background-color' ? ['background'] : []),
3563
+ ]
3564
+ .map(k => b[camel(k)])
3565
+ .find(y => typeof y === 'string' && !/gradient\(|url\(/i.test(y));
3566
+ // The part's own background being an image (a gradient) covers any
3567
+ // color under it: the color is written, and the result says it does
3568
+ // not show.
3569
+ const plainImage =
3570
+ css === 'background-color'
3571
+ ? ['background', 'backgroundImage']
3572
+ .map(k => b[k])
3573
+ .find(y => typeof y === 'string' && /gradient\(|url\(/i.test(y))
3574
+ : undefined;
3575
+ if (plainImage)
3576
+ (ctx.compileNotes ??= []).push(
3577
+ `${target}'s own background is an image (${plainImage}), which covers the ${mode} color: it does not show until that background is a color`,
3578
+ );
3579
+ const names = new Set([
3580
+ ...(ctx.C.variantValues(target)?.variant ?? []),
3581
+ ...(ctx.C.MAP[target]?.attrs?.variant ?? []),
3582
+ ]);
3583
+ for (const name of names) {
3584
+ const x = exactVariantValue(target, css, name, s.state);
3585
+ const vb = block({...s, when: `variant:${name}`}, target);
3586
+ // What the variant's rule already holds (a setting for the other
3587
+ // mode, or one for both) keeps its other half; else the value the
3588
+ // variant shows unset.
3589
+ // The background shorthand is the same property: its color counts,
3590
+ // and it is taken out so the color written here is in effect.
3591
+ const family = [
3592
+ css,
3593
+ ...(css === 'background-color' ? ['background'] : []),
3594
+ ];
3595
+ // A variant whose own background is an image (a gradient) keeps
3596
+ // it: one mode's color is not written there, and the result says so.
3597
+ const image = family
3598
+ .map(k => vb[camel(k)])
3599
+ .find(y => typeof y === 'string' && /gradient\(|url\(/i.test(y));
3600
+ if (image) {
3601
+ (ctx.compileNotes ??= []).push(
3602
+ `${target} variant:${name} keeps its own background image (${image}), so the ${mode} color is not written there`,
3603
+ );
3604
+ continue;
3605
+ }
3606
+ const prev = family
3607
+ .map(k => vb[camel(k)])
3608
+ .find(y => typeof y === 'string');
3609
+ // In a state, what the state shows now in the other mode: its own
3610
+ // value there, else the resting color a setting gives the variant
3611
+ // or the part (a state that does not change the color shows the
3612
+ // resting one), else the unset value.
3613
+ /** @param {Record<string, any> | undefined} rule */
3614
+ const restOf = rule =>
3615
+ family
3616
+ .map(k => rule?.[camel(k)])
3617
+ .find(y => typeof y === 'string' && !/gradient\(|url\(/i.test(y));
3618
+ const rest = s.state
3619
+ ? (exactVariantValue(target, css, name, s.state, true) ??
3620
+ restOf(theme.components[target]?.[`variant:${name}`]) ??
3621
+ plainHeld ??
3622
+ restOf(theme.components[target]?.base))
3623
+ : plainHeld;
3624
+ const from = prev ?? rest ?? x;
3625
+ if (from == null) continue;
3626
+ for (const k of family) delete vb[camel(k)];
3627
+ const half = halfOf(from, other);
3628
+ vb[camel(css)] =
3629
+ mode === 'light'
3630
+ ? `light-dark(${v}, ${half})`
3631
+ : `light-dark(${half}, ${v})`;
3632
+ // A resting color written on the variant's rule would also hide the
3633
+ // hover the variant shows unset: that hover is written back as it
3634
+ // was, in both modes, unless a hover setting of the theme's own
3635
+ // gives it one.
3636
+ if (
3637
+ !s.state &&
3638
+ !data.settings.some(
3639
+ y =>
3640
+ y.on === s.on &&
3641
+ y.state === 'hover' &&
3642
+ colorFamily(y.thing) === colorFamily(s.thing),
3643
+ )
3644
+ ) {
3645
+ const hover = exactVariantValue(target, css, name, 'hover', true);
3646
+ if (hover != null && hover !== x) {
3647
+ const hb = block(
3648
+ {...s, when: `variant:${name}`, state: 'hover', mode: undefined},
3649
+ target,
3650
+ );
3651
+ hb[camel(css)] ??= hover;
3652
+ }
3653
+ }
3654
+ }
3655
+ return;
3656
+ }
3657
+ if (mode && colorFamily(prop) === 'background-color') {
3658
+ // The background shorthand and its color are one property: the one
3659
+ // the rule holds (as a color) gives the other half and is replaced, so
3660
+ // one key carries both modes.
3661
+ const held = ['backgroundColor', 'background'].find(
3662
+ k => typeof b[k] === 'string' && !/gradient\(|url\(/i.test(b[k]),
3663
+ );
3664
+ if (held && held !== camel(prop)) {
3665
+ const was = b[held];
3666
+ delete b[held];
3667
+ b[camel(prop)] ??= was;
3668
+ }
3669
+ }
3670
+ // A color for one mode under the part's own gradient does not show:
3671
+ // the result says so.
3672
+ if (
3673
+ mode &&
3674
+ colorFamily(prop) === 'background-color' &&
3675
+ ['background', 'backgroundImage'].some(
3676
+ k => typeof b[k] === 'string' && /gradient\(|url\(/i.test(b[k]),
3677
+ )
3678
+ )
3679
+ (ctx.compileNotes ??= []).push(
3680
+ `${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`,
3681
+ );
3682
+ if (mode) {
2774
3683
  const prev = b[prop];
2775
3684
  // The other mode keeps exactly what it had: the value set for it, the
2776
3685
  // part's own, else what the property shows unset (light-dark() takes
2777
3686
  // colors only, so never inherit).
3687
+ // A token on the part: its own value in the other mode (the base
3688
+ // theme's, else Core's), never another color.
3689
+ const otherSide = mode === 'light' ? 'dark' : 'light';
3690
+ const tokenOther = prop.startsWith('--')
3691
+ ? (base[otherSide]?.[prop] ??
3692
+ /** @type {Record<string, string>} */ (TOKENS)[prop] ??
3693
+ null)
3694
+ : null;
2778
3695
  const other =
2779
3696
  prev ??
3697
+ tokenOther ??
2780
3698
  baseComponent(base, ctx, target, prop, s) ??
2781
3699
  partDefault(ctx, target, prop, s.when, s.state) ??
2782
3700
  (s.state
@@ -2791,7 +3709,7 @@ export function compileTheme(ctx, data, base) {
2791
3709
  return halves.length === 2 ? halves[side - 1].trim() : x;
2792
3710
  };
2793
3711
  b[prop] =
2794
- s.mode === 'light'
3712
+ mode === 'light'
2795
3713
  ? `light-dark(${v}, ${prev ? split(prev, 2) : other})`
2796
3714
  : `light-dark(${prev ? split(prev, 1) : other}, ${v})`;
2797
3715
  } else b[prop] = v;
@@ -2879,6 +3797,19 @@ export function compileTheme(ctx, data, base) {
2879
3797
  ...data.settings.filter(x => x.source === 'dial' && roleFont(x)),
2880
3798
  ...data.settings.filter(x => x.source !== 'dial'),
2881
3799
  ];
3800
+ // The shell regions a setting gives a background of their own keep it
3801
+ // when the page background paints the rest of the shell.
3802
+ const regionsWithOwnBackground = new Set(
3803
+ data.settings
3804
+ .filter(
3805
+ x =>
3806
+ x.source === 'property' &&
3807
+ /^background(-color|-image)?$/.test(kebab(x.thing)),
3808
+ )
3809
+ .flatMap(x => partsOf(ctx, x)),
3810
+ );
3811
+ /** @type {Record<string, any>[]} */
3812
+ const fixedToViewport = [];
2882
3813
  for (const s of ordered) {
2883
3814
  // A setting for the mode a one-mode theme does not have stays saved but
2884
3815
  // does not apply (maskedSettings names it).
@@ -3001,35 +3932,239 @@ export function compileTheme(ctx, data, base) {
3001
3932
  // The rungs scale the spacing the base theme starts from.
3002
3933
  /** @param {string} k @param {string} nv */
3003
3934
  const put = (k, nv) => {
3004
- if (parts.length) for (const t of parts) block(s, t)[k] = nv;
3005
- else putTok(k, nv);
3935
+ if (parts.length) {
3936
+ // An exact whole-theme or own-source token holds inside the
3937
+ // part too.
3938
+ if (!keptTokens(null).has(k))
3939
+ for (const t of parts) block(s, t)[k] = nv;
3940
+ } else putTok(k, nv);
3006
3941
  };
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`);
3942
+ // The spacing steps, in order around the exact steps the theme
3943
+ // keeps (a whole-theme one or the own source's: they win over the
3944
+ // dial).
3945
+ /** @type {Record<string, string>} */
3946
+ const dialVars = {};
3947
+ {
3948
+ /** @type {Array<[string, number]>} */
3949
+ const steps = [];
3950
+ for (const [k, core] of Object.entries(
3951
+ /** @type {Record<string, string>} */ (TOKENS),
3952
+ )) {
3953
+ const v = base.light[k] ?? core;
3954
+ if (/^--spacing-/.test(k) && /rem$/.test(v))
3955
+ steps.push([k, parseFloat(v) * 16]);
3956
+ }
3957
+ /** @type {Record<string, number>} */
3958
+ const keptSteps = {};
3959
+ for (const [k, v] of keptTokens(null))
3960
+ if (/^--spacing-/.test(k)) {
3961
+ const n = sizePx(v);
3962
+ if (n != null) keptSteps[k] = n;
3963
+ }
3964
+ /** @type {string[]} */
3965
+ const noRoom = [];
3966
+ for (const [k, n] of spacingSteps(steps, f, keptSteps, noRoom)) {
3967
+ const nv = `${Number((n / 16).toFixed(3))}rem`;
3968
+ dialVars[k] = k in keptSteps ? String(keptTokens(null).get(k)) : nv;
3969
+ if (!(k in keptSteps)) put(k, nv);
3970
+ }
3971
+ for (const k of noRoom)
3972
+ (ctx.sizeNotes ??= []).push(
3973
+ `${k} has no room between the exact spacing steps kept around it, so it takes the value of the one below it`,
3974
+ );
3975
+ }
3976
+ // An exact size the theme keeps (it wins over the dial) is a fixed
3977
+ // point the others stay in order around: a whole-theme one, one of
3978
+ // the theme's own source, and on a part the part's own, in any
3979
+ // unit that comes to a length (a spacing token through the value
3980
+ // this dial gives it). A whole-theme dial also keeps each part's
3981
+ // own exact sizes in order on that part.
3982
+ const sizeParts = parts.length
3983
+ ? parts
3984
+ : [
3985
+ null,
3986
+ ...new Set(
3987
+ data.settings
3988
+ .filter(
3989
+ x =>
3990
+ x.source === 'token' &&
3991
+ /^--size-element-/.test(x.thing) &&
3992
+ x.on &&
3993
+ !x.when &&
3994
+ !x.state,
3995
+ )
3996
+ .flatMap(x => partsOf(ctx, x)),
3997
+ ),
3998
+ ];
3999
+ for (const t of sizeParts) {
4000
+ /** @type {Record<string, number>} */
4001
+ const kept = {};
4002
+ for (const [k, v] of keptSizes(t)) {
4003
+ const n = sizePx(v, dialVars);
4004
+ if (n != null) kept[k] = n;
4005
+ }
4006
+ /** @type {string[]} */
4007
+ const noRoom = [];
4008
+ for (const [k, nv] of controlSizes(
4009
+ Object.keys(/** @type {Record<string, string>} */ (TOKENS))
4010
+ .filter(k => /^--size-element-/.test(k))
4011
+ .map(k => [k, base.light[k] ?? TOKENS[k]]),
4012
+ f,
4013
+ kept,
4014
+ noRoom,
4015
+ ))
4016
+ if (t) block(s, t)[k] = nv;
4017
+ else putTok(k, nv);
4018
+ for (const k of noRoom)
4019
+ (ctx.sizeNotes ??= []).push(
4020
+ `${k}${t ? ` on ${t}` : ''} has no room between the exact sizes kept around it, so it takes the size of the one below it`,
4021
+ );
4022
+ }
4023
+ // A variant's own exact size is kept in order on that variant too,
4024
+ // with the part's and the theme's kept sizes around it.
4025
+ /** @type {Map<string, {t: string, when: string}>} */
4026
+ const variantScopes = new Map();
4027
+ for (const x of data.settings)
4028
+ if (
4029
+ x.source === 'token' &&
4030
+ /^--size-element-/.test(x.thing) &&
4031
+ x.on &&
4032
+ x.when &&
4033
+ !x.state
4034
+ )
4035
+ for (const t of partsOf(ctx, x))
4036
+ if (!parts.length || parts.includes(t))
4037
+ variantScopes.set(`${t} ${x.when}`, {t, when: x.when});
4038
+ for (const {t, when} of variantScopes.values()) {
4039
+ /** @type {Record<string, number>} */
4040
+ const kept = {};
4041
+ for (const [k, v] of keptSizes(t)) {
4042
+ const n = sizePx(v, dialVars);
4043
+ if (n != null) kept[k] = n;
4044
+ }
4045
+ for (const x of data.settings)
4046
+ if (
4047
+ x.source === 'token' &&
4048
+ /^--size-element-/.test(x.thing) &&
4049
+ x.when === when &&
4050
+ !x.state &&
4051
+ partsOf(ctx, x).includes(t)
4052
+ ) {
4053
+ const n = sizePx(String(x.value), dialVars);
4054
+ if (n != null) kept[x.thing] = n;
4055
+ }
4056
+ /** @type {string[]} */
4057
+ const noRoom = [];
4058
+ for (const [k, nv] of controlSizes(
4059
+ Object.keys(/** @type {Record<string, string>} */ (TOKENS))
4060
+ .filter(k => /^--size-element-/.test(k))
4061
+ .map(k => [k, base.light[k] ?? TOKENS[k]]),
4062
+ f,
4063
+ kept,
4064
+ noRoom,
4065
+ ))
4066
+ block({...s, when}, t)[k] = nv;
4067
+ for (const k of noRoom)
4068
+ (ctx.sizeNotes ??= []).push(
4069
+ `${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`,
4070
+ );
3013
4071
  }
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
4072
  }
3022
4073
  } else if (s.source === 'token') {
3023
4074
  if (parts.length) for (const t of parts) putComp(s, t, s.thing, s.value);
3024
4075
  else putTok(s.thing, s.value, s.mode);
3025
4076
  } else if (s.source === 'property') {
3026
- for (const t of parts) {
4077
+ // A background on the whole app shell is the page background. The
4078
+ // shell's header and side nav paint the body or surface color over it
4079
+ // in every variant but section, and in an auto-height shell they are
4080
+ // sticky, so content must not show through them when it scrolls: they
4081
+ // take the same background. The main content area is made
4082
+ // see-through. A gradient is fixed to the viewport on the shell and on
4083
+ // those regions, so the regions line up with the page behind them. A
4084
+ // background a setting gives one of those regions itself is kept.
4085
+ /** @type {string[]} */
4086
+ const pageParts = [];
4087
+ if (
4088
+ parts.includes('app-shell') &&
4089
+ /^background(-color|-image)?$/.test(kebab(s.thing)) &&
4090
+ !s.when &&
4091
+ !s.state
4092
+ ) {
4093
+ /** @param {Record<string, any>} r */
4094
+ const ownBackground = r =>
4095
+ ['background', 'backgroundColor', 'backgroundImage'].some(
4096
+ k => k in r,
4097
+ );
4098
+ for (const region of ['app-shell-header', 'app-shell-sidenav'])
4099
+ if (
4100
+ ctx.project.target.has(region) &&
4101
+ !regionsWithOwnBackground.has(region)
4102
+ )
4103
+ pageParts.push(region);
4104
+ if (ctx.project.target.has('layout-content')) {
4105
+ const lc = ((theme.components['layout-content'] ??= {}).base ??= {});
4106
+ const main = (lc[':where(.astryx-app-shell [role="main"])'] ??= {});
4107
+ if (!ownBackground(main)) main.backgroundColor = 'transparent';
4108
+ }
4109
+ // Written after every setting (below), so no background shorthand
4110
+ // in the same rule resets it.
4111
+ if (/gradient\(/.test(String(s.value)))
4112
+ for (const t of ['app-shell', ...pageParts])
4113
+ fixedToViewport.push(block({...s, mode: undefined}, t));
4114
+ (ctx.compileNotes ??= []).push(
4115
+ "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",
4116
+ );
4117
+ }
4118
+ for (const t of [...parts, ...pageParts]) {
4119
+ // A heading takes its color from its color prop, which reads the
4120
+ // text color tokens after part styles: the color goes into those
4121
+ // tokens on the heading (a named color prop's own token for
4122
+ // --when color:<name>), so it shows there and nowhere else.
4123
+ if (t === 'heading' && kebab(s.thing) === 'color') {
4124
+ const named = /^color:([\w-]+)$/.exec(s.when ?? '')?.[1];
4125
+ const scope = named ? {...s, when: undefined} : s;
4126
+ for (const tok of named
4127
+ ? [`--color-text-${named}`]
4128
+ : ['--color-text-primary', '--color-text-secondary'])
4129
+ // A value naming one of these tokens (the secondary text color)
4130
+ // leaves that token as it is: it would read itself.
4131
+ if (!new RegExp(`var\\(\\s*${tok}\\s*[,)]`).test(String(s.value)))
4132
+ putComp(scope, t, tok, s.value);
4133
+ continue;
4134
+ }
3027
4135
  // A padding on a part whose box reads Core's padding variables is
3028
4136
  // resolved with the rest of that part's padding, below.
3029
4137
  if (padVars(t) && /^padding(-|$)/.test(kebab(s.thing))) {
3030
4138
  queuePadding(s, t);
3031
4139
  continue;
3032
4140
  }
4141
+ // A padding on a part without padding variables, where the own source
4142
+ // pads some sides of the same rule: the editor writes the other
4143
+ // sides only, each as it names it (physical stays physical), so the
4144
+ // own sides win; a side the own source holds in one direction only
4145
+ // is written for the other direction.
4146
+ if (/^padding(-|$)/.test(kebab(s.thing)) && !s.mode && !padVars(t)) {
4147
+ const own = ownBox(t, s);
4148
+ if (own.ltr.size || own.rtl.size) {
4149
+ for (const [x, v] of Object.entries(
4150
+ paddingSides(kebab(s.thing), String(s.value)),
4151
+ )) {
4152
+ const prop = camel(`padding-${x}`);
4153
+ const [inL, inR] = [
4154
+ own.ltr.has(boxSide(x, 'ltr')),
4155
+ own.rtl.has(boxSide(x, 'rtl')),
4156
+ ];
4157
+ if (inL && inR) continue;
4158
+ if (!inL && !inR) {
4159
+ putComp(s, t, prop, v);
4160
+ continue;
4161
+ }
4162
+ const [db, key] = dirBlock(s, t, inL ? ':dir(rtl)' : ':dir(ltr)');
4163
+ db[key] = {...(db[key] ?? {}), [prop]: v};
4164
+ }
4165
+ continue;
4166
+ }
4167
+ }
3033
4168
  const sides =
3034
4169
  wrappedPadding(t, s) ??
3035
4170
  containerSides(t, s) ??
@@ -3109,6 +4244,10 @@ export function compileTheme(ctx, data, base) {
3109
4244
  }
3110
4245
  }
3111
4246
  emitPadding();
4247
+ for (const r of fixedToViewport) {
4248
+ delete r.backgroundAttachment;
4249
+ r.backgroundAttachment = 'fixed';
4250
+ }
3112
4251
  orderBlocks();
3113
4252
  // Core gives headings the body font when a theme sets only the body's:
3114
4253
  // a font for the body alone keeps the base theme's heading font.
@@ -3162,7 +4301,16 @@ export function compileTheme(ctx, data, base) {
3162
4301
  for (const [k, {light, dark}] of Object.entries(tok)) {
3163
4302
  const l = light ?? base.light[k] ?? TOKENS[k];
3164
4303
  const d = dark ?? base.dark[k] ?? TOKENS[k];
3165
- theme.tokens[k] = l === d ? l : [l, d];
4304
+ // A pair only for a color: anything else (a shadow) is one value, the
4305
+ // one the theme's mode shows.
4306
+ theme.tokens[k] =
4307
+ l === d
4308
+ ? l
4309
+ : ctx.C.typeOf(k) === 'color' || isColorToken(k)
4310
+ ? [l, d]
4311
+ : modeOnly === 'dark'
4312
+ ? d
4313
+ : l;
3166
4314
  }
3167
4315
  // Base themes set the type tokens again for phones (a coarse pointer
3168
4316
  // below the lg width); an exact font family or weight, and the headings
@@ -3198,11 +4346,194 @@ export function compileTheme(ctx, data, base) {
3198
4346
  },
3199
4347
  ],
3200
4348
  };
4349
+ // A longhand set after a shorthand that covers it is the one in effect,
4350
+ // as the result says. The build merges these blocks over the base
4351
+ // theme's, and a key the base holds keeps the base's (earlier) place, so
4352
+ // such a longhand would come before the shorthand and lose: it is written
4353
+ // as its own sides instead, which the base does not hold.
4354
+ const baseBlocks =
4355
+ /** @type {{components?: Record<string, any>}} */ (base).components ?? {};
4356
+ for (const [target, keys] of Object.entries(theme.components ?? {}))
4357
+ for (const [key, b] of Object.entries(
4358
+ /** @type {Record<string, any>} */ (keys),
4359
+ ))
4360
+ laterLonghandsAsSides(b, baseBlocks[target]?.[key]);
3201
4361
  if (!Object.keys(theme.tokens).length) delete theme.tokens;
3202
4362
  if (!Object.keys(theme.components).length) delete theme.components;
3203
4363
  return theme;
3204
4364
  }
3205
4365
 
4366
+ /**
4367
+ * Whether shorthand `a` sets `b`, a logical side included: padding sets
4368
+ * padding-inline, border-color sets border-inline-start-color.
4369
+ * @param {string} a @param {string} b
4370
+ */
4371
+ function coversSide(a, b) {
4372
+ if (coversProperty(a, b)) return true;
4373
+ const root = b.replace(/-(inline|block)(-start|-end)?(?=-|$)/, '');
4374
+ return root !== b && (a === root || coversProperty(a, root));
4375
+ }
4376
+
4377
+ /**
4378
+ * A background's layers with each color painted in one mode only: a color
4379
+ * stop becomes light-dark(<color>, transparent) for light (the reverse for
4380
+ * dark), and a layer that is a color alone becomes a gradient of it, so
4381
+ * every layer is an image the other mode does not show.
4382
+ * @param {string} value
4383
+ * @param {'light' | 'dark'} mode
4384
+ * @returns {string[]}
4385
+ */
4386
+ export function maskLayers(value, mode) {
4387
+ /** @param {string} c */
4388
+ const wrap = c =>
4389
+ mode === 'light'
4390
+ ? `light-dark(${c}, transparent)`
4391
+ : `light-dark(transparent, ${c})`;
4392
+ /** @param {string} w */
4393
+ const isColor = w =>
4394
+ !/^light-dark\(/i.test(w) &&
4395
+ (isColorValue(w) || /^var\(\s*--color-/i.test(w));
4396
+ return splitTop(value, ',')
4397
+ .map(x => x.trim())
4398
+ .filter(Boolean)
4399
+ .map(layer => {
4400
+ const fn = /^((?:repeating-)?(?:linear|radial|conic)-gradient)\(/i.exec(
4401
+ layer,
4402
+ );
4403
+ if (!fn)
4404
+ return isColor(layer)
4405
+ ? `linear-gradient(${wrap(layer)}, ${wrap(layer)})`
4406
+ : layer;
4407
+ // The gradient's own arguments, up to its closing bracket; what
4408
+ // follows (position, size, repeat) stays as it is.
4409
+ let depth = 0;
4410
+ let end = fn[0].length - 1;
4411
+ for (let i = end; i < layer.length; i++) {
4412
+ if (layer[i] === '(') depth++;
4413
+ if (layer[i] === ')' && --depth === 0) {
4414
+ end = i;
4415
+ break;
4416
+ }
4417
+ }
4418
+ const args = splitTop(layer.slice(fn[0].length, end), ',').map(arg =>
4419
+ splitTop(arg.trim(), ' ')
4420
+ .map(w => (isColor(w.trim()) ? wrap(w.trim()) : w.trim()))
4421
+ .join(' '),
4422
+ );
4423
+ return `${fn[1]}(${args.join(', ')})${layer.slice(end + 1)}`;
4424
+ });
4425
+ }
4426
+
4427
+ /**
4428
+ * A background layer's image (its gradient) and what follows it, as the
4429
+ * background longhands take them: position, size (after a slash) and
4430
+ * repeat.
4431
+ * @param {string} layer
4432
+ * @returns {{image: string, position: string, size: string, repeat: string}}
4433
+ */
4434
+ function layerParts(layer) {
4435
+ const fn = /^((?:repeating-)?(?:linear|radial|conic)-gradient)\(/i.exec(
4436
+ layer,
4437
+ );
4438
+ if (!fn) return {image: layer, position: '', size: '', repeat: ''};
4439
+ let depth = 0;
4440
+ let end = layer.length - 1;
4441
+ for (let i = fn[0].length - 1; i < layer.length; i++) {
4442
+ if (layer[i] === '(') depth++;
4443
+ if (layer[i] === ')' && --depth === 0) {
4444
+ end = i;
4445
+ break;
4446
+ }
4447
+ }
4448
+ const rest = splitTop(layer.slice(end + 1).trim(), ' ');
4449
+ const REPEAT = /^(repeat|no-repeat|repeat-x|repeat-y|space|round)$/i;
4450
+ const repeat = rest.filter(w => REPEAT.test(w)).join(' ');
4451
+ const words = rest.filter(w => !REPEAT.test(w)).join(' ');
4452
+ const [position = '', size = ''] = words.split('/').map(x => x.trim());
4453
+ return {image: layer.slice(0, end + 1), position, size, repeat};
4454
+ }
4455
+
4456
+ /** A side word in a longhand's name, in the order a box value lists sides. */
4457
+ const BOX_SIDES = ['top', 'right', 'bottom', 'left'];
4458
+
4459
+ /**
4460
+ * A block's longhands that follow a shorthand covering them, where the base
4461
+ * theme's block holds the same key, rewritten as that longhand's own sides
4462
+ * (padding-inline as padding-inline-start and -end, border-color as the
4463
+ * four side colors), in place and at the same position; a state's block
4464
+ * nested in it too. A longhand that is no side pair or box is kept.
4465
+ * @param {Record<string, any>} b
4466
+ * @param {Record<string, any> | undefined} baseBlock
4467
+ */
4468
+ function laterLonghandsAsSides(b, baseBlock) {
4469
+ if (
4470
+ !b ||
4471
+ typeof b !== 'object' ||
4472
+ !baseBlock ||
4473
+ typeof baseBlock !== 'object'
4474
+ )
4475
+ return;
4476
+ for (const [k, v] of Object.entries(b))
4477
+ if (k.startsWith(':') && v && typeof v === 'object')
4478
+ laterLonghandsAsSides(v, baseBlock[k]);
4479
+ const keys = Object.keys(b);
4480
+ /** @type {Record<string, any>} */
4481
+ const out = {};
4482
+ let changed = false;
4483
+ keys.forEach((k, i) => {
4484
+ const v = b[k];
4485
+ const css = kebab(k);
4486
+ const sides =
4487
+ typeof v === 'string' &&
4488
+ !k.startsWith('-') &&
4489
+ typeof baseBlock[k] === 'string' &&
4490
+ keys
4491
+ .slice(0, i)
4492
+ .some(e => !e.startsWith(':') && coversSide(kebab(e), css))
4493
+ ? sidesOf(css, v)
4494
+ : null;
4495
+ if (!sides) {
4496
+ out[k] = v;
4497
+ return;
4498
+ }
4499
+ changed = true;
4500
+ for (const [p, x] of Object.entries(sides)) {
4501
+ delete out[camel(p)];
4502
+ out[camel(p)] = x;
4503
+ }
4504
+ });
4505
+ if (!changed) return;
4506
+ for (const k of Object.keys(b)) delete b[k];
4507
+ Object.assign(b, out);
4508
+ }
4509
+
4510
+ /**
4511
+ * A two-sided (start/end) or four-sided (top/right/bottom/left) longhand's
4512
+ * value, as each side's property and value by the shorthand rules; null for
4513
+ * any other property.
4514
+ * @param {string} prop kebab-case
4515
+ * @param {string} v
4516
+ * @returns {Record<string, string> | null}
4517
+ */
4518
+ function sidesOf(prop, v) {
4519
+ const direct = [...longhandsOf(prop)].filter(p => longhandsOf(p).size === 0);
4520
+ const w = splitTop(v.trim(), ' ').map(x => x.trim());
4521
+ if (!w.length || /!important/i.test(v)) return null;
4522
+ const start = direct.find(p => /-start(-|$)/.test(p));
4523
+ const end = direct.find(p => /-end(-|$)/.test(p));
4524
+ if (direct.length === 2 && start && end && w.length <= 2)
4525
+ return {[start]: w[0], [end]: w[1] ?? w[0]};
4526
+ const named = BOX_SIDES.map(side =>
4527
+ direct.find(p => new RegExp(`-${side}(-|$)`).test(p)),
4528
+ );
4529
+ if (direct.length !== 4 || named.some(x => !x) || w.length > 4) return null;
4530
+ const [t, r = t, bo = t, l = r] = w;
4531
+ const vals = [t, r, bo, l];
4532
+ return Object.fromEntries(
4533
+ named.map((p, i) => [/** @type {string} */ (p), vals[i]]),
4534
+ );
4535
+ }
4536
+
3206
4537
  /** Core's default type scale ratio. */
3207
4538
  const STANDARD_RATIO = 1.2;
3208
4539
  /** The font-size tokens below the base, with their step on the scale. */
@@ -3314,10 +4645,10 @@ export function maskedSettings(data, ctx = null) {
3314
4645
  * {font-weight}`. Find those rules in the built stylesheet.
3315
4646
  * @param {string} cssText
3316
4647
  * @param {any} theme
3317
- * @returns {Array<{target: string, key: string, prop: string, value: string}>}
4648
+ * @returns {Array<{target: string, key: string, prop: string, value: string, state?: string}>}
3318
4649
  */
3319
4650
  export function findOverrides(cssText, theme) {
3320
- /** @type {Array<{target: string, key: string, prop: string, value: string}>} */
4651
+ /** @type {Array<{target: string, key: string, prop: string, value: string, state?: string}>} */
3321
4652
  const extra = [];
3322
4653
  for (const [target, keys] of Object.entries(
3323
4654
  /** @type {Record<string, any>} */ (theme.components ?? {}),
@@ -3362,6 +4693,51 @@ export function findOverrides(cssText, theme) {
3362
4693
  }
3363
4694
  }
3364
4695
  }
4696
+ // A state setting on the plain part (a whole-part hover) loses the same
4697
+ // way to a variant's own rule in that state: it is repeated there too.
4698
+ for (const [target, keys] of Object.entries(
4699
+ /** @type {Record<string, any>} */ (theme.components ?? {}),
4700
+ ))
4701
+ for (const [state, decl] of Object.entries(keys.base ?? {})) {
4702
+ if (!/^:[a-z-]+$/.test(state) || !decl || typeof decl !== 'object')
4703
+ continue;
4704
+ const props = Object.keys(decl).filter(
4705
+ p => !p.startsWith('--') && !p.startsWith(':'),
4706
+ );
4707
+ if (!props.length) continue;
4708
+ const re = new RegExp(
4709
+ `\\.astryx-${target.replace(/-/g, '\\-')}\\[data-([a-z-]+)="([^"]+)"\\](?:${state}(?![\\w-])[^{}]*|\\s*)\\{([^}]*)\\}`,
4710
+ 'g',
4711
+ );
4712
+ // The variant's own rule in that state, and its resting rule: that
4713
+ // one comes after the plain state rule at the same weight.
4714
+ const seen = new Set();
4715
+ for (const m of cssText.matchAll(re)) {
4716
+ const declared = [...m[3].matchAll(/(?:^|[;\s])([a-z-]+)\s*:/g)].map(
4717
+ d => d[1],
4718
+ );
4719
+ for (const prop of props) {
4720
+ const css = kebab(prop);
4721
+ if (css === m[1] || css.endsWith(`-${m[1]}`)) continue;
4722
+ if (
4723
+ !seen.has(`${m[1]}:${m[2]} ${prop}`) &&
4724
+ declared.some(
4725
+ d =>
4726
+ d === css || coversProperty(d, css) || coversProperty(css, d),
4727
+ )
4728
+ ) {
4729
+ seen.add(`${m[1]}:${m[2]} ${prop}`);
4730
+ extra.push({
4731
+ target,
4732
+ key: `${m[1]}:${m[2]}`,
4733
+ state,
4734
+ prop,
4735
+ value: decl[prop],
4736
+ });
4737
+ }
4738
+ }
4739
+ }
4740
+ }
3365
4741
  return extra;
3366
4742
  }
3367
4743
 
@@ -3384,8 +4760,43 @@ const liftValue = (lift, only) =>
3384
4760
  * @param {ThemeData} data
3385
4761
  * @param {any} theme
3386
4762
  * @param {import('./_palette.mjs').PaletteMapping | null} pal
4763
+ * @param {string} [cwd]
4764
+ * @param {Record<string, any> | null} [baseParts] the base theme's components, whose state objects each written one starts from
3387
4765
  */
3388
- function settingsSource(slug, data, theme, pal, cwd = '') {
4766
+ function settingsSource(slug, data, theme, pal, cwd = '', baseParts = null) {
4767
+ // Core merges a theme's state object (`:hover` in a rule) over the base
4768
+ // theme's whole, one level deep: each one starts as the base theme's own
4769
+ // for that rule, so the properties no setting names keep the base's.
4770
+ if (baseParts) {
4771
+ theme = {...theme, components: {...(theme.components ?? {})}};
4772
+ for (const [target, keys] of Object.entries(theme.components)) {
4773
+ /** @type {Record<string, any>} */
4774
+ const next = {};
4775
+ for (const [key, rule] of Object.entries(
4776
+ /** @type {Record<string, any>} */ (keys),
4777
+ )) {
4778
+ if (!rule || typeof rule !== 'object') {
4779
+ next[key] = rule;
4780
+ continue;
4781
+ }
4782
+ /** @type {Record<string, any>} */
4783
+ const r = {...rule};
4784
+ for (const [k, v] of Object.entries(rule)) {
4785
+ const own = baseParts[target]?.[key]?.[k];
4786
+ if (
4787
+ k.startsWith(':') &&
4788
+ v &&
4789
+ typeof v === 'object' &&
4790
+ own &&
4791
+ typeof own === 'object'
4792
+ )
4793
+ r[k] = {...own, ...v};
4794
+ }
4795
+ next[key] = r;
4796
+ }
4797
+ theme.components[target] = next;
4798
+ }
4799
+ }
3389
4800
  const like = data.like;
3390
4801
  const REF = '@@palette:';
3391
4802
  /** @param {string} family @param {'light' | 'dark'} m @param {import('./_palette.mjs').StopRef} r */
@@ -3933,7 +5344,17 @@ export async function buildTheme(ctx, slug, data) {
3933
5344
  ctx.keepStops,
3934
5345
  );
3935
5346
  await step(() => {
3936
- writeWhole(f.settingsTs, settingsSource(slug, data, theme, pal, cwd));
5347
+ writeWhole(
5348
+ f.settingsTs,
5349
+ settingsSource(
5350
+ slug,
5351
+ data,
5352
+ theme,
5353
+ pal,
5354
+ cwd,
5355
+ /** @type {any} */ (base).components ?? null,
5356
+ ),
5357
+ );
3937
5358
  syncPaletteRefs(cwd, slug, fs.readFileSync(f.settingsTs, 'utf8'), pal);
3938
5359
  if (!fs.existsSync(f.ts)) writeWhole(f.ts, themeModuleSource(slug));
3939
5360
  });
@@ -3959,9 +5380,47 @@ export async function buildTheme(ctx, slug, data) {
3959
5380
  fs.rmSync(file, {force: true});
3960
5381
  forgetWritten(cwd, slug, pictures);
3961
5382
  });
3962
- let receipt = await step(() => runBuild(ctx, slug));
5383
+ let receipt = await step(() => runBuild(ctx, slug, data));
5384
+ // A state setting on the plain part that the own source's same state
5385
+ // rule wins over is not repeated on the variants either: the own source
5386
+ // wins on every variant, as the result says.
5387
+ /** @type {Map<string, Map<string, string | null>>} */
5388
+ const ownStates = new Map();
5389
+ /** @param {string} target @param {string} state @param {string} prop */
5390
+ const ownHolds = (target, state, prop) => {
5391
+ const k = `${target} ${state}`;
5392
+ const own =
5393
+ ownStates.get(k) ?? ownPartTokens(cwd, slug, target, 'base', state);
5394
+ ownStates.set(k, own);
5395
+ const css = kebab(prop);
5396
+ return [...own.keys()].some(
5397
+ o => o === css || coversProperty(o, css) || coversProperty(css, o),
5398
+ );
5399
+ };
3963
5400
  const found = findOverrides(fs.readFileSync(f.css, 'utf8'), theme).filter(
3964
- x => !(theme.components[x.target][x.key] ?? {})[x.prop],
5401
+ x =>
5402
+ // By property: a variant whose rule the settings give this property
5403
+ // or a shorthand covering it needs no copy; nor one holding a
5404
+ // longhand of it that the base theme's rule also holds and that has
5405
+ // no sides to be written as (a background color, one-mode or not):
5406
+ // the copy would come after it there and win. Any other longhand
5407
+ // takes the copy, then is written after it (as its sides where the
5408
+ // base holds it).
5409
+ !Object.entries(
5410
+ (x.state
5411
+ ? theme.components[x.target][x.key]?.[x.state]
5412
+ : theme.components[x.target][x.key]) ?? {},
5413
+ ).some(([k, v]) => {
5414
+ if (k.startsWith(':')) return false;
5415
+ if (k === x.prop || coversProperty(kebab(k), kebab(x.prop)))
5416
+ return true;
5417
+ if (!coversProperty(kebab(x.prop), kebab(k))) return false;
5418
+ const baseRule = /** @type {any} */ (base).components?.[x.target]?.[
5419
+ x.key
5420
+ ];
5421
+ const held = (x.state ? baseRule?.[x.state] : baseRule)?.[k];
5422
+ return held != null && sidesOf(kebab(k), String(v)) == null;
5423
+ }) && !(x.state && ownHolds(x.target, x.state, x.prop)),
3965
5424
  );
3966
5425
  /** @type {string[]} */
3967
5426
  const lifted = [];
@@ -3972,19 +5431,42 @@ export async function buildTheme(ctx, slug, data) {
3972
5431
  // longhand or shorthand the variant sets itself (border-color after
3973
5432
  // a base border) still wins over it.
3974
5433
  const own = t[x.key] ?? {};
5434
+ const ownState = x.state ? (own[x.state] ?? {}) : own;
3975
5435
  // A variant that sets every longhand of the property itself needs
3976
5436
  // none of the base value (and a lifted radius would feed Core's copy
3977
5437
  // of it into the content's radius, after the variant's own).
3978
5438
  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)}`);
5439
+ if (longs.length && longs.every(l => camel(l) in ownState)) continue;
5440
+ t[x.key] = x.state
5441
+ ? {...own, [x.state]: {[x.prop]: x.value, ...ownState}}
5442
+ : {[x.prop]: x.value, ...own};
5443
+ // The variant's own longhands come after the copied shorthand; one
5444
+ // the base theme holds would keep the base's earlier place and lose,
5445
+ // so it is written as its sides.
5446
+ const baseRule = /** @type {any} */ (base).components?.[x.target]?.[
5447
+ x.key
5448
+ ];
5449
+ laterLonghandsAsSides(
5450
+ x.state ? t[x.key][x.state] : t[x.key],
5451
+ x.state ? baseRule?.[x.state] : baseRule,
5452
+ );
5453
+ lifted.push(`${x.target} ${x.key}${x.state ?? ''} ${kebab(x.prop)}`);
3982
5454
  }
3983
5455
  await step(() => {
3984
- writeWhole(f.settingsTs, settingsSource(slug, data, theme, pal, cwd));
5456
+ writeWhole(
5457
+ f.settingsTs,
5458
+ settingsSource(
5459
+ slug,
5460
+ data,
5461
+ theme,
5462
+ pal,
5463
+ cwd,
5464
+ /** @type {any} */ (base).components ?? null,
5465
+ ),
5466
+ );
3985
5467
  syncPaletteRefs(cwd, slug, fs.readFileSync(f.settingsTs, 'utf8'), pal);
3986
5468
  });
3987
- receipt = await step(() => runBuild(ctx, slug));
5469
+ receipt = await step(() => runBuild(ctx, slug, data));
3988
5470
  }
3989
5471
  for (const out of [f.css, f.js])
3990
5472
  if (fs.existsSync(out))
@@ -4005,8 +5487,34 @@ export async function buildTheme(ctx, slug, data) {
4005
5487
  return {warnings, lifted, notes};
4006
5488
  }
4007
5489
 
4008
- /** @param {Ctx} ctx @param {string} slug @returns {Promise<any>} */
4009
- async function runBuild(ctx, slug) {
5490
+ /**
5491
+ * The one color mode of a light-only or dark-only theme, from its settings,
5492
+ * for the build to write into the built module (`colorModes`); null for a
5493
+ * theme with both modes.
5494
+ * @param {string} cwd
5495
+ * @param {string} slug
5496
+ * @returns {['light'] | ['dark'] | null}
5497
+ */
5498
+ export function buildColorModes(cwd, slug) {
5499
+ try {
5500
+ return oneColorMode(
5501
+ modesOf(
5502
+ JSON.parse(fs.readFileSync(themeFiles(cwd, slug).settings, 'utf8')),
5503
+ ),
5504
+ );
5505
+ } catch {
5506
+ return null;
5507
+ }
5508
+ }
5509
+
5510
+ /**
5511
+ * @param {Ctx} ctx
5512
+ * @param {string} slug
5513
+ * @param {{mode?: string}} [data] the settings being built (saved after the
5514
+ * build), whose mode the built module exports
5515
+ * @returns {Promise<any>}
5516
+ */
5517
+ async function runBuild(ctx, slug, data) {
4010
5518
  const {cwd} = ctx.project;
4011
5519
  const f = themeFiles(cwd, slug);
4012
5520
  const silent = logger.silent;
@@ -4020,6 +5528,11 @@ async function runBuild(ctx, slug) {
4020
5528
  {},
4021
5529
  {cwd},
4022
5530
  {compact: true},
5531
+ {
5532
+ colorModes: data
5533
+ ? oneColorMode(modesOf(data))
5534
+ : buildColorModes(cwd, slug),
5535
+ },
4023
5536
  );
4024
5537
  return receipt;
4025
5538
  } finally {
@@ -4046,6 +5559,7 @@ export async function outputsDrift(ctx, slug) {
4046
5559
  {check: true},
4047
5560
  {cwd},
4048
5561
  {compact: true},
5562
+ {colorModes: buildColorModes(cwd, slug)},
4049
5563
  );
4050
5564
  const first = /** @type {any} */ (receipt)?.data?.stale?.[0];
4051
5565
  if (!first) return null;
@@ -4227,7 +5741,7 @@ function nonTextToken(t, typeOf = (/** @type {string} */ _k) => 'other') {
4227
5741
  * @param {string} slug
4228
5742
  * @param {[string, unknown, ('object' | 'pair' | 'unit' | 'value' | 'mode')?]} bad
4229
5743
  */
4230
- function nonTextMessage(ctx, slug, [name, value, kind = 'value']) {
5744
+ export function nonTextMessage(ctx, slug, [name, value, kind = 'value']) {
4231
5745
  const type = ctx.C.typeOf(name);
4232
5746
  if (kind === 'mode') return ownPairMessage(slug, [name]);
4233
5747
  if (kind === 'object')
@@ -4452,8 +5966,26 @@ function parseSettings(text) {
4452
5966
  }
4453
5967
 
4454
5968
  /**
4455
- * Whether parsed settings have the shape the editor reads: an object with a
4456
- * list of settings.
5969
+ * Whether every settings entry has the parts the editor reads (a thing, a
5970
+ * value and a source); one without is damage `new` keeps aside.
5971
+ * @param {any} data
5972
+ */
5973
+ export function settingsEntriesOk(data) {
5974
+ return (
5975
+ settingsShapeOk(data) &&
5976
+ data.settings.every(
5977
+ (/** @type {any} */ s) =>
5978
+ s &&
5979
+ typeof s.thing === 'string' &&
5980
+ 'value' in s &&
5981
+ ['dial', 'token', 'property'].includes(s.source),
5982
+ )
5983
+ );
5984
+ }
5985
+
5986
+ /**
5987
+ * Whether settings data has the shape the editor reads: an object with a
5988
+ * settings list.
4457
5989
  * @param {any} data
4458
5990
  */
4459
5991
  export function settingsShapeOk(data) {
@@ -5067,6 +6599,21 @@ export function builtFiles(cwd, slug, data, some = false) {
5067
6599
  ];
5068
6600
  }
5069
6601
 
6602
+ /**
6603
+ * The file's stat, or undefined when it is not there. On Node 22.13 a folder
6604
+ * above the file that is a file throws ENOTDIR even with throwIfNoEntry
6605
+ * false; that file is not there either, as on later Node.
6606
+ * @param {string} file
6607
+ */
6608
+ function statIfThere(file) {
6609
+ try {
6610
+ return fs.statSync(file, {throwIfNoEntry: false});
6611
+ } catch (e) {
6612
+ if (/** @type {any} */ (e)?.code === 'ENOTDIR') return undefined;
6613
+ throw e;
6614
+ }
6615
+ }
6616
+
5070
6617
  /**
5071
6618
  * Refuse, by name, a built file that is there but cannot be read: its
5072
6619
  * permissions, or a folder where the file goes.
@@ -5075,7 +6622,7 @@ export function builtFiles(cwd, slug, data, some = false) {
5075
6622
  */
5076
6623
  function refuseUnreadable(cwd, files) {
5077
6624
  for (const file of files) {
5078
- const st = fs.statSync(file, {throwIfNoEntry: false});
6625
+ const st = statIfThere(file);
5079
6626
  if (!st) continue;
5080
6627
  const rel = shown(cwd, file);
5081
6628
  if (st.isDirectory())