@astryxdesign/cli 0.7.16 → 0.7.17-canary.g335a172

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 (339) hide show
  1. package/README.md +76 -86
  2. package/api/build/_adapter.d.mts +12 -0
  3. package/api/build/_adapter.mjs +51 -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 +4 -3
  7. package/api/build/build.type.d.mts +2 -2
  8. package/api/build/build.type.mjs +3 -3
  9. package/api/build/kit/kind.d.mts +2 -1
  10. package/api/build/kit/kind.mjs +199 -10
  11. package/api/build/kit/kit.mjs +6 -4
  12. package/api/build/kit/rank.mjs +69 -16
  13. package/api/build/kit/start.d.mts +5 -4
  14. package/api/build/kit/start.mjs +12 -8
  15. package/api/build/kit/weights.d.mts +16 -3
  16. package/api/build/kit/weights.json +1 -1
  17. package/api/build/kit/weights.mjs +251 -35
  18. package/api/build/kit/word-model.d.mts +23 -0
  19. package/api/build/kit/word-model.mjs +46 -0
  20. package/api/build/kit/words.d.mts +48 -0
  21. package/api/build/kit/words.mjs +90 -1
  22. package/api/component/__fixtures__/resolutions/modules.txt +4 -5
  23. package/api/component/list/list.d.mts +1 -1
  24. package/api/component/list/list.mjs +48 -6
  25. package/api/discover/_adapter.d.mts +1 -1
  26. package/api/discover/search/search.mjs +3 -2
  27. package/api/docs/_adapter.d.mts +26 -2
  28. package/api/docs/_adapter.mjs +219 -6
  29. package/api/docs/docs.d.mts +3 -0
  30. package/api/docs/docs.doc.mjs +7 -1
  31. package/api/docs/docs.mjs +12 -0
  32. package/api/docs/docs.type.d.mts +5 -0
  33. package/api/docs/docs.type.mjs +2 -0
  34. package/api/docs/node/node.mjs +1 -1
  35. package/api/doctor/_adapter.d.mts +27 -5
  36. package/api/doctor/_adapter.mjs +83 -10
  37. package/api/doctor/built-checks.mjs +40 -14
  38. package/api/doctor/doctor.d.mts +4 -3
  39. package/api/doctor/doctor.mjs +14 -7
  40. package/api/doctor/theme-checks.mjs +121 -17
  41. package/api/icon/_records.mjs +2 -1
  42. package/api/index.d.mts +2 -0
  43. package/api/index.mjs +2 -0
  44. package/api/integration/_adapter.d.mts +44 -0
  45. package/api/integration/_adapter.mjs +77 -1
  46. package/api/integration/authoring-checks.mjs +6 -6
  47. package/api/integration/example-scope.d.mts +14 -0
  48. package/api/integration/example-scope.mjs +44 -0
  49. package/api/integration/example-scope.type.d.mts +29 -0
  50. package/api/integration/example-scope.type.mjs +25 -0
  51. package/api/integration/integrationExampleScope.doc.d.mts +11 -0
  52. package/api/integration/integrationExampleScope.doc.mjs +59 -0
  53. package/api/integration/validate-integration.mjs +19 -1
  54. package/api/integration/validate-integration.type.d.mts +9 -0
  55. package/api/integration/validate-integration.type.mjs +1 -1
  56. package/api/integration/validateIntegration.doc.mjs +1 -1
  57. package/api/render/_adapter.mjs +591 -195
  58. package/api/render/render.doc.mjs +11 -3
  59. package/api/render/render.type.d.mts +52 -0
  60. package/api/render/render.type.mjs +31 -1
  61. package/api/search/ORDERING.md +1 -1
  62. package/api/search/_candidate-score.mjs +51 -32
  63. package/api/search/_fit-order.mjs +3 -3
  64. package/api/search/_gather-components.d.mts +3 -2
  65. package/api/search/_gather-components.mjs +12 -3
  66. package/api/search/_lexical.d.mts +5 -0
  67. package/api/search/_lexical.mjs +8 -2
  68. package/api/search/_result.d.mts +11 -9
  69. package/api/search/_result.mjs +4 -4
  70. package/api/search/_score.d.mts +6 -1
  71. package/api/search/_score.mjs +15 -3
  72. package/api/search/search-index.mjs +7 -1
  73. package/api/search/search.d.mts +1 -1
  74. package/api/theme/_adapter.mjs +12 -1
  75. package/api/theme/build/build.d.mts +60 -0
  76. package/api/theme/build/build.mjs +210 -54
  77. package/api/theme/build/font-warning.d.mts +8 -0
  78. package/api/theme/build/font-warning.mjs +19 -0
  79. package/api/theme/theme.type.d.mts +10 -0
  80. package/api/theme/theme.type.mjs +7 -1
  81. package/api/theme-edit/_adapter.d.mts +55 -0
  82. package/api/theme-edit/_adapter.mjs +673 -42
  83. package/api/theme-edit/_check.d.mts +28 -22
  84. package/api/theme-edit/_check.mjs +1858 -312
  85. package/api/theme-edit/_color.d.mts +10 -0
  86. package/api/theme-edit/_color.mjs +49 -1
  87. package/api/theme-edit/_compiler.mjs +9 -0
  88. package/api/theme-edit/_context.mjs +60 -3
  89. package/api/theme-edit/_css.mjs +21 -1
  90. package/api/theme-edit/_edit.d.mts +22 -0
  91. package/api/theme-edit/_edit.mjs +1533 -92
  92. package/api/theme-edit/_how-commands.d.mts +57 -0
  93. package/api/theme-edit/_how-commands.mjs +587 -1
  94. package/api/theme-edit/_how-question.d.mts +78 -0
  95. package/api/theme-edit/_how-question.mjs +4716 -235
  96. package/api/theme-edit/_how.mjs +134 -8
  97. package/api/theme-edit/_marks.d.mts +31 -5
  98. package/api/theme-edit/_marks.mjs +57 -5
  99. package/api/theme-edit/_normal.d.mts +219 -0
  100. package/api/theme-edit/_normal.mjs +1041 -0
  101. package/api/theme-edit/_palette.mjs +10 -4
  102. package/api/theme-edit/_parts.d.mts +8 -0
  103. package/api/theme-edit/_parts.mjs +103 -2
  104. package/api/theme-edit/_playwright-picture.d.mts +4 -0
  105. package/api/theme-edit/_playwright-picture.mjs +34 -0
  106. package/api/theme-edit/_preview-app.d.mts +7 -1
  107. package/api/theme-edit/_preview-app.mjs +394 -74
  108. package/api/theme-edit/_preview.d.mts +69 -8
  109. package/api/theme-edit/_preview.mjs +531 -108
  110. package/api/theme-edit/_settings.d.mts +243 -6
  111. package/api/theme-edit/_settings.mjs +2415 -147
  112. package/api/theme-edit/_tables.d.mts +6 -0
  113. package/api/theme-edit/_tables.mjs +44 -1
  114. package/api/theme-edit/_vet.d.mts +18 -0
  115. package/api/theme-edit/_vet.mjs +32 -0
  116. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  117. package/api/theme-edit/theme-edit.type.mjs +4 -1
  118. package/api/theme-edit/themeEditHow.doc.mjs +1 -1
  119. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  120. package/api/theme-edit/themeEditPreviewApp.doc.mjs +3 -3
  121. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +2 -2
  122. package/api/upgrade/run/run.mjs +4 -3
  123. package/assets/codemods/integration-discovery.mjs +2 -1
  124. package/assets/codemods/run-codemod.mjs +87 -7
  125. package/assets/codemods/transforms/next/index.mjs +11 -1
  126. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  127. package/assets/component-list.generated.json +1 -0
  128. package/assets/docs/author-a-theme.doc.mjs +1 -0
  129. package/assets/docs/theme.doc.dense.mjs +2 -2
  130. package/assets/docs/theme.doc.mjs +1 -1
  131. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  132. package/assets/docs/tree/checks.doc.mjs +1 -1
  133. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  134. package/assets/docs/tree/render-pages.doc.mjs +44 -3
  135. package/assets/docs/tree/single-component.doc.mjs +4 -0
  136. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  137. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  138. package/assets/docs/use-a-theme.doc.mjs +1 -1
  139. package/assets/docs.generated.json +2 -2
  140. package/assets/self-audit.generated.json +1 -1
  141. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  142. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  143. package/assets/templates/blocks/components/Hooks/useContainerRevealHookUsage.tsx +2 -2
  144. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  145. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  146. package/assets/templates/components.generated.json +1 -1
  147. package/assets/templates/pages/ai-chat/template.doc.mjs +5 -4
  148. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +2 -1
  149. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  150. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  151. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  152. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  153. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  154. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  155. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  156. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  157. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  158. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  159. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  160. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  161. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  162. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  163. package/assets/templates/pages/editor/template.doc.mjs +2 -8
  164. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  165. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  166. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  167. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  168. package/assets/templates/pages/ide/page.tsx +24 -2
  169. package/assets/templates/pages/kanban-board/template.doc.mjs +1 -9
  170. package/assets/templates/pages/library/template.doc.mjs +4 -1
  171. package/assets/templates/pages/login/template.doc.mjs +2 -1
  172. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  173. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  174. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  175. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  176. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  177. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  178. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  179. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  180. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  181. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  182. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  183. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  184. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  185. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  186. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  187. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  188. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -9
  189. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  190. package/assets/theme.template.ts +6 -0
  191. package/authoring/debug/parse.d.mts +3 -3
  192. package/authoring/doctypes/_schema.d.mts +3 -3
  193. package/authoring/doctypes/command/command.doc.mjs +1 -1
  194. package/authoring/doctypes/component/categories.d.mts +37 -0
  195. package/authoring/doctypes/component/categories.mjs +54 -0
  196. package/authoring/doctypes/template/template.doc.mjs +1 -1
  197. package/authoring/doctypes/template/type.ts +9 -0
  198. package/authoring/example/example.doc.d.mts +12 -0
  199. package/authoring/example/example.doc.mjs +69 -0
  200. package/authoring/example/preview.d.mts +92 -0
  201. package/authoring/example/preview.mjs +994 -0
  202. package/authoring/example/type.ts +102 -0
  203. package/authoring/index.d.mts +1 -0
  204. package/authoring/index.d.ts +12 -0
  205. package/authoring/index.mjs +3 -1
  206. package/clients/cli/bin/astryx.mjs +6 -9
  207. package/clients/cli/build-id.generated.json +1 -1
  208. package/clients/cli/commands/component.doc.mjs +1 -1
  209. package/clients/cli/commands/component.mjs +22 -3
  210. package/clients/cli/commands/docs.doc.mjs +7 -1
  211. package/clients/cli/commands/docs.mjs +3 -1
  212. package/clients/cli/commands/doctor.mjs +32 -14
  213. package/clients/cli/commands/experimental/render.mjs +42 -1
  214. package/clients/cli/commands/experimental/theme.mjs +145 -16
  215. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  216. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  217. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +87 -1
  218. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +2 -2
  219. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -1
  220. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  221. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  222. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  223. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  224. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  225. package/clients/cli/commands/search.doc.mjs +2 -1
  226. package/clients/cli/commands/search.mjs +6 -1
  227. package/clients/cli/commands/template.mjs +4 -2
  228. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  229. package/clients/cli/commands/theme.doc.mjs +1 -1
  230. package/clients/cli/commands/theme.mjs +183 -6
  231. package/clients/cli/commands/upgrade.mjs +42 -7
  232. package/clients/cli/index.mjs +1 -1
  233. package/clients/cli/lib/cli-error.mjs +2 -1
  234. package/clients/cli/lib/component-format.mjs +205 -98
  235. package/clients/cli/lib/hook-format.mjs +9 -19
  236. package/clients/cli/lib/json-shim.mjs +77 -21
  237. package/clients/cli/lib/manifest.mjs +3 -2
  238. package/clients/cli/manifest.generated.json +1 -1
  239. package/foundation/agent-docs/agent-docs.mjs +1 -1
  240. package/foundation/config/theme-state.d.mts +13 -1
  241. package/foundation/config/theme-state.mjs +47 -7
  242. package/foundation/discovery/authoring-self-docs.mjs +1 -0
  243. package/foundation/discovery/component-discovery.d.mts +11 -0
  244. package/foundation/discovery/component-discovery.mjs +56 -8
  245. package/foundation/discovery/component-replacement.mjs +130 -1
  246. package/foundation/discovery/copied-passages.mjs +2 -1
  247. package/foundation/discovery/doc-types.mjs +4 -3
  248. package/foundation/discovery/entry-name-files.d.mts +43 -0
  249. package/foundation/discovery/entry-name-files.mjs +264 -0
  250. package/foundation/discovery/hook-discovery.d.mts +8 -2
  251. package/foundation/discovery/hook-discovery.mjs +22 -8
  252. package/foundation/discovery/icon-definition-discovery.mjs +2 -1
  253. package/foundation/discovery/icon-set-checks.mjs +2 -1
  254. package/foundation/discovery/icon-set-discovery.mjs +2 -1
  255. package/foundation/discovery/integration-doc-files.mjs +2 -1
  256. package/foundation/discovery/package-exports.d.mts +10 -0
  257. package/foundation/discovery/package-exports.mjs +56 -3
  258. package/foundation/discovery/prop-drift.mjs +9 -9
  259. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  260. package/foundation/discovery/runner-allowlist.mjs +2 -0
  261. package/foundation/discovery/stored-component-list.d.mts +43 -0
  262. package/foundation/discovery/stored-component-list.mjs +90 -0
  263. package/foundation/discovery/stored-self-audit.d.mts +26 -10
  264. package/foundation/discovery/stored-self-audit.mjs +38 -18
  265. package/foundation/discovery/template-adapter.d.mts +52 -0
  266. package/foundation/discovery/template-adapter.mjs +176 -12
  267. package/foundation/discovery/template-icons.mjs +2 -1
  268. package/foundation/discovery/theme-discovery.mjs +3 -2
  269. package/foundation/discovery/theme-imports.d.mts +14 -0
  270. package/foundation/discovery/theme-imports.mjs +43 -1
  271. package/foundation/discovery/theming-targets.mjs +3 -2
  272. package/foundation/doc-compiler/import.mjs +7 -1
  273. package/foundation/doc-compiler/inputs.mjs +3 -2
  274. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  275. package/foundation/doc-compiler/stored-docs.d.mts +22 -0
  276. package/foundation/doc-compiler/stored-docs.mjs +49 -0
  277. package/foundation/env/semver.mjs +3 -1
  278. package/foundation/fonts/font-stylesheet.d.mts +31 -0
  279. package/foundation/fonts/font-stylesheet.mjs +115 -0
  280. package/foundation/fs/cache-eviction.d.mts +21 -0
  281. package/foundation/fs/cache-eviction.mjs +73 -0
  282. package/foundation/fs/file-protection.mjs +4 -3
  283. package/foundation/fs/gather-cache.d.mts +25 -4
  284. package/foundation/fs/gather-cache.mjs +164 -55
  285. package/foundation/fs/jiti-cache.d.mts +19 -1
  286. package/foundation/fs/jiti-cache.mjs +130 -6
  287. package/foundation/fs/kept-tree.d.mts +60 -0
  288. package/foundation/fs/kept-tree.mjs +154 -0
  289. package/foundation/fs/listing-cache.d.mts +7 -0
  290. package/foundation/fs/listing-cache.mjs +10 -0
  291. package/foundation/fs/module-loader.d.mts +24 -2
  292. package/foundation/fs/module-loader.mjs +94 -21
  293. package/foundation/fs/paths.d.mts +18 -0
  294. package/foundation/fs/paths.mjs +15 -2
  295. package/foundation/identity/provider-identity.d.mts +6 -0
  296. package/foundation/identity/provider-identity.mjs +10 -1
  297. package/foundation/integrations/contribution-inventory.mjs +4 -3
  298. package/foundation/integrations/example-code.d.mts +63 -0
  299. package/foundation/integrations/example-code.mjs +416 -0
  300. package/foundation/integrations/public-imports.d.mts +9 -0
  301. package/foundation/integrations/public-imports.mjs +3 -2
  302. package/foundation/integrations/validate-contributions.mjs +17 -45
  303. package/foundation/render/embedded-files.d.mts +6 -0
  304. package/foundation/render/embedded-files.mjs +25 -5
  305. package/foundation/render/embedded-imports.d.mts +39 -7
  306. package/foundation/render/embedded-imports.mjs +66 -27
  307. package/foundation/render/file-header.d.mts +66 -0
  308. package/foundation/render/file-header.mjs +118 -0
  309. package/foundation/render/host-answer.d.mts +18 -0
  310. package/foundation/render/host-answer.mjs +46 -0
  311. package/foundation/render/host-exit.d.mts +1 -0
  312. package/foundation/render/host-exit.mjs +6 -1
  313. package/foundation/render/html-reader.d.mts +55 -2
  314. package/foundation/render/html-reader.mjs +145 -26
  315. package/foundation/render/markup-edits.d.mts +57 -0
  316. package/foundation/render/markup-edits.mjs +182 -0
  317. package/foundation/render/page-host.mjs +29 -12
  318. package/foundation/render/page-worker.mjs +121 -13
  319. package/foundation/render/rebuild.mjs +2 -1
  320. package/foundation/render/render-page.d.mts +35 -3
  321. package/foundation/render/render-page.mjs +316 -42
  322. package/foundation/render/source-block.d.mts +85 -6
  323. package/foundation/render/source-block.mjs +211 -20
  324. package/foundation/render/ts-paths.d.mts +69 -6
  325. package/foundation/render/ts-paths.mjs +326 -40
  326. package/foundation/response/error-codes.d.mts +3 -1
  327. package/foundation/response/error-codes.d.ts +1 -0
  328. package/foundation/response/error-codes.doc.mjs +12 -1
  329. package/foundation/response/error-codes.mjs +11 -1
  330. package/foundation/response/response-types.doc.mjs +2 -2
  331. package/foundation/text/compare-text.d.mts +14 -0
  332. package/foundation/text/compare-text.mjs +68 -0
  333. package/foundation/text/string-utils.d.mts +3 -2
  334. package/foundation/text/string-utils.mjs +18 -4
  335. package/foundation/text/suggest-order.d.mts +9 -0
  336. package/foundation/text/suggest-order.mjs +15 -1
  337. package/foundation/xle/expand.mjs +2 -1
  338. package/host/index.mjs +8 -6
  339. package/package.json +7 -6
@@ -10,7 +10,7 @@
10
10
  * @position api/theme-edit — storage and compile for the theme commands
11
11
  */
12
12
 
13
- import {EDITOR_GENERATED_MARK} from './_marks.mjs';
13
+ import {APP_COPY_MARK, EDITOR_GENERATED_MARK} from './_marks.mjs';
14
14
  import {parse as parseModule} from '@babel/parser';
15
15
  import {createHash} from 'node:crypto';
16
16
  import * as fs from 'node:fs';
@@ -25,8 +25,9 @@ import {AstryxError} from '../error.mjs';
25
25
  import {logger} from '../logger.mjs';
26
26
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
27
27
  import {levenshteinDistance} from '../../foundation/text/levenshtein.mjs';
28
- import {themeBuildForReport} from '../theme/build/build.mjs';
28
+ import {oneColorMode, themeBuildForReport} from '../theme/build/build.mjs';
29
29
  import {
30
+ MODE_WORDS,
30
31
  AUTO_SPREAD,
31
32
  CORNERS,
32
33
  DIALS,
@@ -46,6 +47,7 @@ import {
46
47
  WRAPPED_PARTS,
47
48
  CARD_LIKE,
48
49
  } from './_tables.mjs';
50
+ import {cleanDialValue, typoLimit, typoNear} from './_normal.mjs';
49
51
  import {
50
52
  alphaOf,
51
53
  colorProblem,
@@ -83,6 +85,7 @@ import {
83
85
  baseThemeFile,
84
86
  } from './_project.mjs';
85
87
  import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
88
+ import {compareText} from '../../foundation/text/compare-text.mjs';
86
89
 
87
90
  // The palette reads the tokens the own source sets through this module.
88
91
  setOwnTokenReader((cwd, slug) => ownSourceTokenValues(cwd, slug));
@@ -116,13 +119,13 @@ setOwnTokenReader((cwd, slug) => ownSourceTokenValues(cwd, slug));
116
119
  /** What lifted secondary text sits on: the contrast check measures it there. */
117
120
  const LIFT_GROUND_TOKENS = new Set(LIFT_PARTS.map(([, , g]) => g));
118
121
 
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 */
122
+ /** @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
123
  /** @typedef {import('./_parts.mjs').PaintSide} PaintSide */
121
124
  /** @typedef {import('./_parts.mjs').TextPair} TextPair */
122
125
 
123
126
  /** What a theme name may be, in words. */
124
127
  export const NAME_RULE =
125
- 'lowercase letters, digits and dashes, starting with a letter, 64 characters at most, and not a name Windows reserves (con, prn, aux, nul, com1-com9, lpt1-lpt9)';
128
+ 'lowercase letters, digits and dashes, starting with a letter, 64 characters at most, and not a name Windows reserves (con, prn, aux, nul, com0-com9, lpt0-lpt9, and com¹-com³, lpt¹-lpt³)';
126
129
 
127
130
  /** A theme name: lowercase letters, digits and dashes, starting with a letter, 64 characters at most. @param {string} s */
128
131
  export const slugOk = s =>
@@ -197,20 +200,35 @@ export function themeFiles(cwd, slug) {
197
200
  }
198
201
 
199
202
  /** 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']);
203
+ export const FOLDER_JUNK = new Set([
204
+ '.DS_Store',
205
+ '.gitkeep',
206
+ 'Thumbs.db',
207
+ 'desktop.ini',
208
+ ]);
201
209
 
202
210
  /**
203
211
  * Whether `dir` holds nothing of anyone's: absent, empty, or only system
204
212
  * files (what `git rm -r` or a branch switch leaves). A path that is not a
205
213
  * folder, or one that does not read, is not empty.
206
214
  * @param {string} dir
215
+ * @returns {boolean}
207
216
  */
208
217
  export function folderIsEmpty(dir) {
209
218
  if (!fs.existsSync(dir)) return true;
210
219
  try {
220
+ // A folder holding only empty folders (an empty tokens/) holds nothing
221
+ // either; a link is never followed.
211
222
  return (
212
223
  fs.lstatSync(dir).isDirectory() &&
213
- fs.readdirSync(dir).every(n => FOLDER_JUNK.has(n))
224
+ fs
225
+ .readdirSync(dir)
226
+ .every(
227
+ n =>
228
+ FOLDER_JUNK.has(n) ||
229
+ (fs.lstatSync(path.join(dir, n)).isDirectory() &&
230
+ folderIsEmpty(path.join(dir, n))),
231
+ )
214
232
  );
215
233
  } catch {
216
234
  return false;
@@ -289,6 +307,20 @@ export function editorWrote(cwd, slug, file) {
289
307
  }
290
308
  }
291
309
 
310
+ /**
311
+ * Whether the pictures record names this file and it is unchanged since the
312
+ * editor wrote it. Only such a file is ever deleted: a stamp alone is not
313
+ * enough, since a byte copy of a picture (preview-before.png) carries the
314
+ * same stamp and is the person's.
315
+ * @param {string} cwd
316
+ * @param {string} slug
317
+ * @param {string} file
318
+ */
319
+ export function editorRecorded(cwd, slug, file) {
320
+ const was = readWrittenRecord(cwd, slug)[path.basename(file)];
321
+ return Boolean(was) && was === contentHash(file);
322
+ }
323
+
292
324
  /**
293
325
  * Adopt a picture an older editor took (before it recorded or stamped its
294
326
  * pictures) into the record: only while the theme has no record at all, the
@@ -470,7 +502,7 @@ export function editedThemes(cwd, order = 'name') {
470
502
  };
471
503
  return names
472
504
  .map(d => ({d, t: when(d)}))
473
- .sort((a, b) => b.t - a.t || a.d.localeCompare(b.d))
505
+ .sort((a, b) => b.t - a.t || compareText(a.d, b.d))
474
506
  .map(x => x.d);
475
507
  }
476
508
 
@@ -485,21 +517,51 @@ export const shown = (cwd, f) =>
485
517
  * @param {number} [n]
486
518
  */
487
519
  export function nearest(x, list, n = 3) {
520
+ // A phrase that negates a word (not round, no caps, unbold,
521
+ // rounded-none) never has that word as its nearest: it asks the opposite.
522
+ // A typo of a listed keyword that itself starts with no- or not-
523
+ // (`not-alowed` for not-allowed, `no-repat` for no-repeat) is no
524
+ // negation: it is read as a typo.
525
+ if (
526
+ negates(x) &&
527
+ ![...list].some(c => /^(no|not)-/.test(c) && typoNear(x, c))
528
+ )
529
+ return [];
530
+ // A long input (a pasted stylesheet or blob) holds many names inside
531
+ // it: it is near nothing.
532
+ if (x.length > 64) return [];
533
+ // Within the editor's one typo limit (typoLimit), nearest by edit
534
+ // distance first (brand-drak is brand-dark, not brand); a name one holds
535
+ // inside the other is near too, after the close ones.
536
+ const limit = typoLimit(x);
488
537
  return [...list]
489
538
  .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)))
539
+ .map(c => {
540
+ const d = levenshteinDistance(x.toLowerCase(), c.toLowerCase(), limit, {
541
+ swaps: true,
542
+ });
543
+ return /** @type {[string, number]} */ ([
544
+ c,
545
+ d <= limit ? d : c.includes(x) || x.includes(c) ? limit + 0.5 : d,
546
+ ]);
547
+ })
548
+ .filter(([, s]) => s <= limit + 0.5)
498
549
  .sort((a, b) => a[1] - b[1])
499
550
  .slice(0, n)
500
551
  .map(([c]) => c);
501
552
  }
502
553
 
554
+ /**
555
+ * Whether typed words negate what they name (`not round`, `no caps`,
556
+ * `anything but blue`, `unbold`, `non-bold`, `rounded-none`).
557
+ * @param {string} x
558
+ */
559
+ export function negates(x) {
560
+ return /(^|[\s-])(not|no|non|without|never|less)([\s-]|$)|anything but|^un(round|bold|rais|outlin|cap)|-none$/i.test(
561
+ String(x).trim(),
562
+ );
563
+ }
564
+
503
565
  /**
504
566
  * A refusal: nothing was changed, and the suggestions lead with the command
505
567
  * that does what the person wanted.
@@ -577,6 +639,79 @@ export function typedThemeName(s) {
577
639
  );
578
640
  }
579
641
 
642
+ /**
643
+ * The theme names a name typed the way the app shows it may mean, most
644
+ * likely first: a path with doubled slashes or `../` (`themes//t`), a file
645
+ * name with or without its folder (`brand.theme.ts`, `tTheme.ts`), the app
646
+ * copy's export (`tTheme`), camelCase (`brandDark`) and spaces
647
+ * (`Brand Dark`) each read as dashes. The caller picks the first that
648
+ * exists, else the first.
649
+ * @param {string} s
650
+ * @returns {string[]}
651
+ */
652
+ export function themeNameReadings(s) {
653
+ const base = unlabeledThemeName(String(s ?? ''))
654
+ .replace(/[\\/]+/g, '/')
655
+ .replace(/^(\.\.?\/)+/, '')
656
+ .replace(/^.*themes\//i, '')
657
+ .replace(/\/.*$/, '')
658
+ .replace(
659
+ /\.(theme\.ts|settings\.(json|ts)|history\.json|css\.d\.ts|d\.ts|doc\.mjs|fonts\.css|css|mjs|js|tsx?)$/i,
660
+ '',
661
+ )
662
+ .trim();
663
+ const noTheme = base.replace(/([a-z0-9])Theme$/, '$1');
664
+ const read = [base, noTheme === base ? '' : noTheme]
665
+ .flatMap(x => [kebab(x), x.toLowerCase()])
666
+ .filter(x => /[a-z]/i.test(x))
667
+ .map(x => slugFor(x));
668
+ // A module name in any letters (brandtheme, brand-theme) last: only
669
+ // when the theme it names exists does it win.
670
+ const moduleNames = read
671
+ .map(n => n.replace(/-?theme$/, ''))
672
+ .filter(n => n && slugOk(n));
673
+ return [...new Set([...read, ...moduleNames])];
674
+ }
675
+
676
+ /**
677
+ * A vibrancy written as set reads typed input: a share of one (0.5) or a
678
+ * percent (50%) is that much of the 0-100 scale, as a whole number. Any
679
+ * other dial's value, or a vibrancy that is no such number, comes back as
680
+ * it was.
681
+ * @param {string} dial
682
+ * @param {string} v
683
+ * @returns {string}
684
+ */
685
+ export function vibrancyMeant(dial, v) {
686
+ if (dial !== 'vibrancy') return v;
687
+ const m = /^(\d*\.?\d+)\s*(%?)$/.exec(v.trim());
688
+ if (!m) return v;
689
+ const n = Number(m[1]);
690
+ const scaled = !m[2] && n > 0 && n < 1 ? n * 100 : n;
691
+ return scaled <= 100 ? String(Math.round(scaled)) : v;
692
+ }
693
+
694
+ /**
695
+ * The mode and base a damaged theme file meant, read the way typed input
696
+ * is: other letters, stray spaces, `_` or a space for a dash (`Dark-Only`,
697
+ * ` Neutral`), and a base written as its package name
698
+ * (`@astryxdesign/theme-neutral`). Each is the cleaned text even when it is
699
+ * no value the editor takes; the caller checks it.
700
+ * @param {any} data
701
+ * @returns {{mode: string, like: string}}
702
+ */
703
+ export function fieldsMeant(data) {
704
+ const mode = String(data?.mode ?? '')
705
+ .trim()
706
+ .toLowerCase()
707
+ .replace(/[\s_]+/g, '-');
708
+ const like = String(data?.like ?? '')
709
+ .trim()
710
+ .toLowerCase()
711
+ .replace(/^@astryxdesign\/theme-/, '');
712
+ return {mode, like};
713
+ }
714
+
580
715
  /**
581
716
  * The settings of a theme, or a refusal naming the command that makes it.
582
717
  * @param {string} cwd
@@ -605,9 +740,22 @@ export function loadTheme(
605
740
  );
606
741
  const plain = typedThemeName(slug);
607
742
  const named = slugFor(plain);
743
+ // brandDark is brand-dark.
744
+ const camelWords = slugFor(
745
+ unlabeledThemeName(String(slug ?? '')).replace(
746
+ /([a-z0-9])([A-Z])/g,
747
+ '$1-$2',
748
+ ),
749
+ );
608
750
  const exists = (/** @type {string} */ n) =>
609
751
  Boolean(n) && fs.existsSync(themeFiles(cwd, n).settings);
610
- const fixed = !exists(named) && exists(whole) ? whole : named;
752
+ // The module or export name (brandTheme, the app copy's brandTheme.ts)
753
+ // names the theme brand: one reader for every way a name is typed.
754
+ const readings = themeNameReadings(slug);
755
+ const fixed =
756
+ [named, whole, camelWords, ...readings].find(exists) ??
757
+ readings[0] ??
758
+ named;
611
759
  const same = fs.existsSync(themeFiles(cwd, fixed).settings) ? fixed : null;
612
760
  // A list where one theme goes (t,u or "t;u"): one theme at a time,
613
761
  // each that exists named; never a new theme made of the list. A name
@@ -741,6 +889,30 @@ export function loadTheme(
741
889
  `themes/${slug} is an empty folder: there is no theme ${slug} yet. new makes it there.`,
742
890
  {run: [`${P} new ${slug}`]},
743
891
  );
892
+ // The editor's own app copy left behind when themes/<slug>/ is gone
893
+ // (a git clean, a wrong rm, a branch switch): `new` makes the theme
894
+ // again and writes the copy over.
895
+ const copyName = `${camel(slug)}Theme`;
896
+ if (
897
+ !same &&
898
+ other &&
899
+ other[1] === `src/themes/${slug}` &&
900
+ !fs.existsSync(f.dir) &&
901
+ [`${copyName}.ts`, `${copyName}.doc.mjs`, `${slug}.fonts.css`].some(n => {
902
+ try {
903
+ return fs
904
+ .readFileSync(path.join(other[0], n), 'utf8')
905
+ .includes(APP_COPY_MARK);
906
+ } catch {
907
+ return false;
908
+ }
909
+ })
910
+ )
911
+ refuse(
912
+ ERROR_CODES.ERR_UNKNOWN_THEME,
913
+ `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).`,
914
+ {run: [`${P} new ${slug}`]},
915
+ );
744
916
  if (!same && (other || LIKE.includes(slug)))
745
917
  refuse(
746
918
  ERROR_CODES.ERR_UNKNOWN_THEME,
@@ -760,7 +932,24 @@ export function loadTheme(
760
932
  ERROR_CODES.ERR_UNKNOWN_THEME,
761
933
  `There is no theme "${slug}" made by this command (no themes/${slug}/${slug}.settings.json).`,
762
934
  (() => {
763
- const near = same ? [same] : nearest(slug, have);
935
+ // A doubled or trailing dash (brand--dark, t--): the name as new
936
+ // cleans it, the theme of that name when there is one, never a new
937
+ // theme new refuses.
938
+ const cleaned = String(slug)
939
+ .replace(/-{2,}/g, '-')
940
+ .replace(/^-+|-+$/g, '');
941
+ const cleanedHere =
942
+ cleaned !== slug &&
943
+ slugOk(cleaned) &&
944
+ fs.existsSync(themeFiles(cwd, cleaned).settings)
945
+ ? cleaned
946
+ : null;
947
+ const near = same
948
+ ? [same]
949
+ : cleanedHere
950
+ ? [cleanedHere]
951
+ : nearest(slug, have);
952
+ const newName = usableNewName(cwd, cleaned || slug);
764
953
  // A theme near the name comes first; a new theme of the name as
765
954
  // typed only after.
766
955
  return {
@@ -768,8 +957,8 @@ export function loadTheme(
768
957
  run: same
769
958
  ? [`${P} show ${same}`]
770
959
  : near.length
771
- ? [`${P} show ${near[0]}`, `${P} new ${slug}`]
772
- : [`${P} new ${slug}`],
960
+ ? [`${P} show ${near[0]}`, `${P} new ${newName}`]
961
+ : [`${P} new ${newName}`],
773
962
  };
774
963
  })(),
775
964
  );
@@ -813,7 +1002,31 @@ export function loadTheme(
813
1002
  ],
814
1003
  ERROR_CODES.ERR_THEME_INVALID,
815
1004
  );
1005
+ readEntryWords(data);
816
1006
  const problem = settingsProblem(data, skip);
1007
+ // An entry whose mode or source means nothing: `undo` with its name
1008
+ // removes that entry only; a step back loses the last change.
1009
+ const damaged = problem ? damagedEntry(data, problem) : null;
1010
+ if (damaged)
1011
+ throw new AstryxError(
1012
+ `themes/${slug}/${slug}.settings.json: ${problem}. Remove that setting with ${P} undo ${slug} ${undoArgs(damagedUndo(damaged))}; nothing else needs to change${steps ? `, or step back to the settings before the last change with ${P} undo ${slug} (the last change is then lost)` : ''}. Nothing was changed.`,
1013
+ [
1014
+ {
1015
+ name: `${P} undo ${slug} ${undoArgs(damagedUndo(damaged))}`,
1016
+ reason: 'do this instead: removes only that setting',
1017
+ },
1018
+ ...(steps
1019
+ ? [
1020
+ {
1021
+ name: `${P} undo ${slug}`,
1022
+ reason:
1023
+ 'or step back to the settings before the last change (the last change is then lost)',
1024
+ },
1025
+ ]
1026
+ : []),
1027
+ ],
1028
+ ERROR_CODES.ERR_THEME_INVALID,
1029
+ );
817
1030
  // A value made under looser rules is not damage: the command that
818
1031
  // changes or removes that setting still works, with the other bad ones
819
1032
  // left out of the build, so each listed fix runs on its own.
@@ -854,23 +1067,62 @@ export function loadTheme(
854
1067
  })),
855
1068
  ERROR_CODES.ERR_THEME_INVALID,
856
1069
  );
857
- const bad = problem ? badSetting(data) : null;
1070
+ // A damaged mode or base is fixed first: the message names it, so the
1071
+ // suggestions set it (another bad value is named on the next run).
1072
+ // (Not an entry named mode or base inside the settings list.)
1073
+ const fieldBroken =
1074
+ (/^(it has no mode|mode ")/.test(problem ?? '') &&
1075
+ !['both', 'light-only', 'dark-only'].includes(data?.mode)) ||
1076
+ (/^base "/.test(problem ?? '') &&
1077
+ data?.like != null &&
1078
+ !LIKE.includes(data.like));
1079
+ const bad = problem && !fieldBroken ? badSetting(data) : null;
858
1080
  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'
1081
+ // The value it holds, cleaned as typed input is (stray or invisible
1082
+ // spaces, other letters, a pasted `corners: pill`), when the dial takes
1083
+ // that; else a value it takes, for a dial; a color for a color token.
1084
+ const cleaned =
1085
+ DIALS[bad.thing] && typeof bad.value === 'string'
1086
+ ? vibrancyMeant(bad.thing, cleanDialValue(bad.thing, bad.value))
1087
+ : null;
1088
+ // Vibrancy saturates the colors the color dials make: with none, set
1089
+ // refuses it as having no effect, so it is not offered.
1090
+ const vibrancyActs =
1091
+ bad.thing !== 'vibrancy' ||
1092
+ (Array.isArray(data.settings) ? data.settings : []).some(
1093
+ (/** @type {any} */ x) =>
1094
+ x && x.source === 'dial' && PALETTE_DIALS.includes(x.thing),
1095
+ );
1096
+ const meant =
1097
+ cleaned &&
1098
+ cleaned !== bad.value &&
1099
+ vibrancyActs &&
1100
+ !valueProblem({...bad, value: cleaned})
1101
+ ? cleaned
864
1102
  : null;
1103
+ // Only the value it holds, cleaned: never a stock value it did not hold.
1104
+ // A vibrancy with no color to saturate is one set refuses: undo only.
1105
+ const example =
1106
+ bad.thing === 'vibrancy' &&
1107
+ !data.settings.some(
1108
+ (/** @type {any} */ x) =>
1109
+ x !== bad && x.source === 'dial' && PALETTE_DIALS.includes(x.thing),
1110
+ )
1111
+ ? null
1112
+ : meant;
865
1113
  throw new AstryxError(
866
1114
  `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
1115
  [
868
1116
  {name: `${P} undo ${slug} ${undoArgs(bad)}`, reason: 'do this instead'},
869
- ...(example
1117
+ // Only a set that replaces this very entry: `mode` and `base` set
1118
+ // the theme's own fields, not an entry in the list.
1119
+ ...(example && !['mode', 'base'].includes(bad.thing)
870
1120
  ? [
871
1121
  {
872
1122
  name: `${P} set ${slug} ${undoArgs(bad).replace(bad.thing, `${bad.thing} ${quoteCommandArgument(example)}`)}`,
873
- reason: 'or give it a value it takes',
1123
+ reason: meant
1124
+ ? 'or set the value it holds, cleaned'
1125
+ : 'or give it a value it takes',
874
1126
  },
875
1127
  ]
876
1128
  : []),
@@ -880,17 +1132,53 @@ export function loadTheme(
880
1132
  }
881
1133
  // A bad mode or base is fixed by setting it.
882
1134
  // 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();
1135
+ const {mode: modeMeant, like: likeMeant} = fieldsMeant(data);
889
1136
  const fieldFix = /^(it has no mode|mode ")/.test(problem ?? '')
890
1137
  ? `${P} set ${slug} mode ${['both', 'light-only', 'dark-only'].includes(modeMeant) ? modeMeant : 'both'}`
891
1138
  : /^base "/.test(problem ?? '')
892
1139
  ? `${P} set ${slug} base ${LIKE.includes(likeMeant) && baseInstalled(cwd, likeMeant) ? likeMeant : 'none'}`
893
1140
  : null;
1141
+ // A damaged mode or base and a bad value in the list: setting the field
1142
+ // is refused while the list holds the bad value, but fixing that entry
1143
+ // saves the field as meant too, so its fix comes first. Never a bare
1144
+ // undo, which would throw away the last real change.
1145
+ const alsoBad = fieldFix ? badSetting(data) : null;
1146
+ if (problem && fieldFix && alsoBad) {
1147
+ const cleaned =
1148
+ DIALS[alsoBad.thing] && typeof alsoBad.value === 'string'
1149
+ ? vibrancyMeant(
1150
+ alsoBad.thing,
1151
+ cleanDialValue(alsoBad.thing, alsoBad.value),
1152
+ )
1153
+ : null;
1154
+ const meant =
1155
+ cleaned &&
1156
+ cleaned !== alsoBad.value &&
1157
+ !['mode', 'base'].includes(alsoBad.thing) &&
1158
+ !valueProblem({...alsoBad, value: cleaned})
1159
+ ? cleaned
1160
+ : null;
1161
+ const field = /^base "/.test(problem) ? 'base' : 'mode';
1162
+ const fieldValue = fieldFix.split(' ').pop();
1163
+ throw new AstryxError(
1164
+ `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.`,
1165
+ [
1166
+ ...(meant
1167
+ ? [
1168
+ {
1169
+ name: `${P} set ${slug} ${undoArgs(alsoBad).replace(alsoBad.thing, `${alsoBad.thing} ${quoteCommandArgument(meant)}`)}`,
1170
+ reason: 'do this instead: set the value it holds, cleaned',
1171
+ },
1172
+ ]
1173
+ : []),
1174
+ {
1175
+ name: `${P} undo ${slug} ${undoArgs(alsoBad)}`,
1176
+ reason: meant ? 'or remove that setting' : 'do this instead',
1177
+ },
1178
+ ],
1179
+ ERROR_CODES.ERR_THEME_INVALID,
1180
+ );
1181
+ }
894
1182
  // A setting listed twice: setting it to one of its values, or undoing
895
1183
  // it, keeps one entry or none.
896
1184
  const twice = problem?.includes(' is listed twice (')
@@ -900,7 +1188,7 @@ export function loadTheme(
900
1188
  throw new AstryxError(
901
1189
  `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
1190
  fieldFix
903
- ? [{name: fieldFix, reason: 'do this instead'}, ...recover.run]
1191
+ ? [{name: fieldFix, reason: 'do this instead'}]
904
1192
  : twice
905
1193
  ? [
906
1194
  ...twice.values
@@ -961,9 +1249,11 @@ export function settingsProblem(
961
1249
  ) {
962
1250
  if (!data || typeof data !== 'object' || Array.isArray(data))
963
1251
  return 'the file is not a settings object';
964
- // `set <theme> mode` and `set <theme> base` fix their own field.
1252
+ // A command that changes or removes a setting (or sets mode or base)
1253
+ // puts a damaged mode or base back to its default itself, with a note, so
1254
+ // two damaged fields never send each fix to the other.
965
1255
  const fixing = typeof skip === 'string' ? skip : skip?.thing;
966
- const field = fixing === 'mode' || fixing === 'base';
1256
+ const field = Boolean(fixing);
967
1257
  if (!field && !['both', 'light-only', 'dark-only'].includes(data.mode))
968
1258
  return data.mode == null
969
1259
  ? 'it has no mode'
@@ -985,10 +1275,15 @@ export function settingsProblem(
985
1275
  // a setting with no name is damage.
986
1276
  if (!s || typeof s.thing !== 'string' || !('value' in s))
987
1277
  return 'a setting has no thing or value';
1278
+ if (removes(skip) && skips(s, skip) && entryDamage(s)) continue;
988
1279
  if (!['dial', 'token', 'property'].includes(s.source))
989
- return `${s.thing} has no source (dial, token or property)`;
1280
+ return s.source == null || s.source === ''
1281
+ ? `${s.thing} has no source (dial, token or property)`
1282
+ : `${s.thing} has source ${JSON.stringify(s.source)}, not dial, token or property`;
990
1283
  if (s.mode != null && s.mode !== 'light' && s.mode !== 'dark')
991
- return `${s.thing} has mode "${s.mode}"`;
1284
+ return `${s.thing} has mode ${JSON.stringify(s.mode)}, not light or dark`;
1285
+ if (s.only != null && s.only !== true)
1286
+ return `${s.thing} has only ${JSON.stringify(s.only)}, not true or false`;
992
1287
  const key = keyOf(s);
993
1288
  // The command that changes or removes a setting listed twice keeps one
994
1289
  // value, or none, so it fixes the list.
@@ -1002,6 +1297,140 @@ export function settingsProblem(
1002
1297
  return null;
1003
1298
  }
1004
1299
 
1300
+ /**
1301
+ * Read each entry's mode and source as the editor writes them: a mode in
1302
+ * other letters or words (`Dark`, `night`, `day`) as light or dark, a
1303
+ * source in other letters (`Dial`) as written, and a missing source from
1304
+ * the thing (a dial name is a dial, a `--` name a token, anything with a
1305
+ * part a property). Each change is kept as a note for the next command,
1306
+ * which saves the entry that way. A value that means nothing is left for
1307
+ * the check to name.
1308
+ * @param {any} data
1309
+ */
1310
+ function readEntryWords(data) {
1311
+ /** @type {string[]} */
1312
+ const notes = [];
1313
+ for (const s of Array.isArray(data?.settings) ? data.settings : []) {
1314
+ if (!s || typeof s !== 'object' || typeof s.thing !== 'string') continue;
1315
+ if (typeof s.mode === 'string' && s.mode !== 'light' && s.mode !== 'dark') {
1316
+ const read = MODE_WORDS[s.mode.trim().toLowerCase()];
1317
+ if (read) {
1318
+ notes.push(
1319
+ `${s.thing} was saved with mode ${JSON.stringify(s.mode)}, read as ${read}`,
1320
+ );
1321
+ s.mode = read;
1322
+ }
1323
+ }
1324
+ // `only` is true or absent; `"true"` and `"false"` written as text are
1325
+ // read as what they say, since the build reads any other value as true.
1326
+ if (typeof s.only === 'string' && /^\s*(true|false)\s*$/i.test(s.only)) {
1327
+ const read = s.only.trim().toLowerCase() === 'true';
1328
+ notes.push(
1329
+ `${s.thing} was saved with only ${JSON.stringify(s.only)}, read as ${read}`,
1330
+ );
1331
+ if (read) s.only = true;
1332
+ else delete s.only;
1333
+ } else if (s.only === false) delete s.only;
1334
+ if (!['dial', 'token', 'property'].includes(s.source)) {
1335
+ const typed = typeof s.source === 'string' ? s.source.trim() : '';
1336
+ const read = typed
1337
+ ? ['dial', 'token', 'property'].find(x => x === typed.toLowerCase())
1338
+ : s.source == null || s.source === ''
1339
+ ? DIALS[s.thing]
1340
+ ? 'dial'
1341
+ : s.thing.startsWith('--')
1342
+ ? 'token'
1343
+ : s.on
1344
+ ? 'property'
1345
+ : undefined
1346
+ : undefined;
1347
+ if (read) {
1348
+ notes.push(
1349
+ typed
1350
+ ? `${s.thing} was saved with source ${JSON.stringify(s.source)}, read as ${read}`
1351
+ : `${s.thing} was saved with no source, read as ${read}`,
1352
+ );
1353
+ s.source = read;
1354
+ }
1355
+ }
1356
+ }
1357
+ ENTRY_NOTES.set(data, notes);
1358
+ }
1359
+
1360
+ /** @type {WeakMap<object, string[]>} */
1361
+ const ENTRY_NOTES = new WeakMap();
1362
+
1363
+ /**
1364
+ * What loading read differently from the file in the theme's entries (a
1365
+ * mode or source in other letters, a missing source): one note each.
1366
+ * @param {object} data the theme as {@link loadTheme} returned it
1367
+ * @returns {string[]}
1368
+ */
1369
+ export function entryNotes(data) {
1370
+ return ENTRY_NOTES.get(data) ?? [];
1371
+ }
1372
+
1373
+ /**
1374
+ * Which part of an entry means nothing after reading: its source, mode or
1375
+ * `only`, or null.
1376
+ * @param {any} s
1377
+ * @returns {'mode' | 'source' | 'only' | null}
1378
+ */
1379
+ export function entryDamage(s) {
1380
+ if (!s || typeof s.thing !== 'string') return null;
1381
+ if (!['dial', 'token', 'property'].includes(s.source)) return 'source';
1382
+ if (s.mode != null && s.mode !== 'light' && s.mode !== 'dark') return 'mode';
1383
+ if (s.only != null && s.only !== true) return 'only';
1384
+ return null;
1385
+ }
1386
+
1387
+ /**
1388
+ * The entry as an undo names it: without the mode or `only` that means
1389
+ * nothing (an undo without them removes that entry).
1390
+ * @param {any} s
1391
+ */
1392
+ function damagedUndo(s) {
1393
+ const damage = entryDamage(s);
1394
+ return {
1395
+ ...s,
1396
+ mode: damage === 'mode' ? undefined : s.mode,
1397
+ only: damage === 'only' ? undefined : s.only,
1398
+ };
1399
+ }
1400
+
1401
+ /**
1402
+ * The entry a settings problem names when that problem is its mode or
1403
+ * `only`, or null.
1404
+ * @param {any} data
1405
+ * @param {string} problem
1406
+ */
1407
+ function damagedEntry(data, problem) {
1408
+ return (
1409
+ (Array.isArray(data?.settings) ? data.settings : []).find(
1410
+ (/** @type {any} */ s) =>
1411
+ (entryDamage(s) === 'source' &&
1412
+ typeof s.source === 'string' &&
1413
+ s.source !== '' &&
1414
+ problem.startsWith(`${s.thing} has source `)) ||
1415
+ (entryDamage(s) === 'mode' &&
1416
+ problem.startsWith(`${s.thing} has mode `)) ||
1417
+ (entryDamage(s) === 'only' &&
1418
+ problem.startsWith(`${s.thing} has only `)),
1419
+ ) ?? null
1420
+ );
1421
+ }
1422
+
1423
+ /**
1424
+ * Whether the command removes the setting it names (an undo): only that
1425
+ * takes an entry whose mode or source means nothing.
1426
+ * @param {string | Partial<Setting> | undefined} skip
1427
+ */
1428
+ function removes(skip) {
1429
+ return Boolean(
1430
+ skip && typeof skip === 'object' && /** @type {any} */ (skip).removing,
1431
+ );
1432
+ }
1433
+
1005
1434
  /**
1006
1435
  * Whether a setting is the one a command changes or removes: by thing, or
1007
1436
  * by the whole identity (part, variant, state, mode) when one is given.
@@ -1016,7 +1445,8 @@ function skips(s, skip) {
1016
1445
  (s.on ?? '') === (skip.on ?? '') &&
1017
1446
  (s.when ?? '') === (skip.when ?? '') &&
1018
1447
  (s.state ?? '') === (skip.state ?? '') &&
1019
- (s.mode ?? '') === (skip.mode ?? '')
1448
+ ((s.mode ?? '') === (skip.mode ?? '') ||
1449
+ (removes(skip) && !skip.mode && entryDamage(s) === 'mode'))
1020
1450
  );
1021
1451
  }
1022
1452
 
@@ -1040,6 +1470,10 @@ export function badSettings(data) {
1040
1470
  export function undoArgs(x) {
1041
1471
  return [
1042
1472
  quoteCommandArgument(String(x.thing)),
1473
+ // The tracking half of headings is named, so the undo reaches it even
1474
+ // when it is listed twice (a bare `undo headings` then reads the weight
1475
+ // half).
1476
+ ...(x.thing === 'headings' && x.axis === 'tracking' ? ['tracking'] : []),
1043
1477
  ...(x.on ? [`--on ${quoteCommandArgument(String(x.on))}`] : []),
1044
1478
  ...(x.when ? [`--when ${quoteCommandArgument(String(x.when))}`] : []),
1045
1479
  ...(x.state ? [`--state ${quoteCommandArgument(String(x.state))}`] : []),
@@ -1133,6 +1567,30 @@ export function valueProblem(s) {
1133
1567
  return null;
1134
1568
  }
1135
1569
 
1570
+ /**
1571
+ * One entry of the top-level `tokens` map in a theme's own source, as
1572
+ * written: its token (null for a computed key no read of the file can
1573
+ * resolve), the key as typed, the line that sets it, and its value's shape.
1574
+ * A `duplicate` entry names a second `tokens` key (with every line); a
1575
+ * `typography` entry is one typography field (its dotted key and value);
1576
+ * an `unresolved` entry says the map holds something only a build reads.
1577
+ * @typedef {{token: string | null, key: string, line: number | null, kind: 'text' | 'number' | 'pair' | 'object' | 'other' | 'duplicate' | 'typography' | 'unresolved', value?: any, halves?: Array<string | number | undefined>, lines?: Array<number | null>, file?: string, overridden?: boolean, expression?: boolean}} OwnTokenEntry
1578
+ */
1579
+
1580
+ /**
1581
+ * The entries of the top-level `tokens` map in a theme's own source, read
1582
+ * from its syntax tree, each with the line that sets it.
1583
+ * @param {string} cwd
1584
+ * @param {string} slug
1585
+ * @returns {OwnTokenEntry[]}
1586
+ */
1587
+ export function ownTokenEntries(cwd, slug) {
1588
+ /** @type {OwnTokenEntry[]} */
1589
+ const detail = [];
1590
+ ownPageTokens(cwd, slug, detail);
1591
+ return detail;
1592
+ }
1593
+
1136
1594
  /**
1137
1595
  * The page-wide tokens a theme's own source sets: the keys of the top-level
1138
1596
  * `tokens` map in its `defineTheme({...})`, read from the syntax tree, each
@@ -1142,7 +1600,11 @@ export function valueProblem(s) {
1142
1600
  * @param {string} slug
1143
1601
  * @returns {Map<string, string | null>}
1144
1602
  */
1145
- function ownPageTokens(cwd, slug) {
1603
+ function ownPageTokens(
1604
+ cwd,
1605
+ slug,
1606
+ detail = /** @type {OwnTokenEntry[] | null} */ (null),
1607
+ ) {
1146
1608
  /** @type {Map<string, string | null>} */
1147
1609
  const out = new Map();
1148
1610
  /** @type {string} */
@@ -1243,32 +1705,255 @@ function ownPageTokens(cwd, slug) {
1243
1705
  if (!chosen) return out;
1244
1706
  const def = unwrap(chosen.call.arguments[0]);
1245
1707
  if (def?.type !== 'ObjectExpression') return out;
1246
- const tokensProp = def.properties.find(
1708
+ // JavaScript keeps the last of two `tokens` keys: that one is read, and
1709
+ // both are named.
1710
+ const tokensProps = def.properties.filter(
1247
1711
  (/** @type {any} */ p) =>
1248
1712
  p.type === 'ObjectProperty' && !p.computed && keyOf(p.key) === 'tokens',
1249
1713
  );
1714
+ if (detail && tokensProps.length > 1)
1715
+ detail.push({
1716
+ token: null,
1717
+ key: 'tokens',
1718
+ kind: 'duplicate',
1719
+ line: tokensProps[0].loc?.start?.line ?? null,
1720
+ lines: tokensProps.map((/** @type {any} */ p) => p.loc?.start?.line),
1721
+ });
1722
+ // The typography fields, as written, for their own checks.
1723
+ const typo = def.properties.find(
1724
+ (/** @type {any} */ p) =>
1725
+ p.type === 'ObjectProperty' &&
1726
+ !p.computed &&
1727
+ keyOf(p.key) === 'typography',
1728
+ );
1729
+ if (detail && typo) {
1730
+ /** @param {any} node @param {string[]} at */
1731
+ const walk = (node, at) => {
1732
+ const obj = unwrap(node);
1733
+ if (obj?.type !== 'ObjectExpression') return;
1734
+ for (const p of obj.properties) {
1735
+ if (p.type !== 'ObjectProperty' || p.computed) continue;
1736
+ const k = keyOf(p.key);
1737
+ if (!k) continue;
1738
+ const v = unwrap(p.value);
1739
+ if (v?.type === 'ObjectExpression') walk(v, [...at, k]);
1740
+ else
1741
+ detail.push({
1742
+ token: null,
1743
+ key: [...at, k].join('.'),
1744
+ kind: 'typography',
1745
+ line: p.loc?.start?.line ?? null,
1746
+ expression:
1747
+ textOf(v) == null &&
1748
+ v?.type !== 'NumericLiteral' &&
1749
+ !(
1750
+ v?.type === 'UnaryExpression' &&
1751
+ v.argument?.type === 'NumericLiteral'
1752
+ ),
1753
+ value:
1754
+ textOf(v) ??
1755
+ (v?.type === 'NumericLiteral'
1756
+ ? v.value
1757
+ : v?.type === 'UnaryExpression' &&
1758
+ v.operator === '-' &&
1759
+ v.argument?.type === 'NumericLiteral'
1760
+ ? -v.argument.value
1761
+ : undefined),
1762
+ });
1763
+ }
1764
+ };
1765
+ walk(typo.value, []);
1766
+ }
1767
+ const tokensProp = tokensProps[tokensProps.length - 1];
1250
1768
  if (!tokensProp) return out;
1251
1769
  let unresolved = false;
1252
- /** @param {any} node @param {number} depth */
1253
- const collect = (node, depth) => {
1254
- const obj = unwrap(node);
1770
+ const dir = path.dirname(themeFiles(cwd, slug).ts);
1771
+ /**
1772
+ * The object a name imported from a file beside the theme gives (`import
1773
+ * {mine} from './mine'`, a default import of a .json file), read from
1774
+ * that file, with its own code and path; null for any other name.
1775
+ * @param {string} name
1776
+ * @returns {{obj: any, code: string, file: string, unwrap: (n: any) => any} | null}
1777
+ */
1778
+ const imported = name => {
1779
+ for (const st of ast.program.body) {
1780
+ if (st.type !== 'ImportDeclaration') continue;
1781
+ const spec = st.specifiers.find(
1782
+ (/** @type {any} */ x) => x.local?.name === name,
1783
+ );
1784
+ const from = String(st.source?.value ?? '');
1785
+ if (!spec || !from.startsWith('.')) continue;
1786
+ const base = path.resolve(dir, from);
1787
+ const file = [
1788
+ '',
1789
+ '.ts',
1790
+ '.mts',
1791
+ '.tsx',
1792
+ '.js',
1793
+ '.mjs',
1794
+ '.json',
1795
+ '/index.ts',
1796
+ ]
1797
+ .map(x => base + x)
1798
+ .find(f => {
1799
+ try {
1800
+ return fs.statSync(f).isFile();
1801
+ } catch {
1802
+ return false;
1803
+ }
1804
+ });
1805
+ if (!file) return null;
1806
+ try {
1807
+ const text = fs.readFileSync(file, 'utf8');
1808
+ const json = file.endsWith('.json');
1809
+ const source = json ? `export default ${text}` : text;
1810
+ const other = /** @type {any} */ (
1811
+ parseModule(source, {sourceType: 'module', plugins: ['typescript']})
1812
+ );
1813
+ /** @type {Map<string, any>} */
1814
+ const local = new Map();
1815
+ /** @type {any} */
1816
+ let found = null;
1817
+ const want =
1818
+ spec.type === 'ImportDefaultSpecifier'
1819
+ ? 'default'
1820
+ : (spec.imported?.name ?? spec.imported?.value);
1821
+ for (const top of other.program.body) {
1822
+ const d =
1823
+ top.type === 'ExportNamedDeclaration' ? top.declaration : top;
1824
+ for (const v of d?.declarations ?? [])
1825
+ if (v.id?.type === 'Identifier') {
1826
+ local.set(v.id.name, v.init);
1827
+ if (top.type === 'ExportNamedDeclaration' && v.id.name === want)
1828
+ found = v.init;
1829
+ }
1830
+ if (top.type === 'ExportDefaultDeclaration' && want === 'default')
1831
+ found = top.declaration;
1832
+ }
1833
+ /** @param {any} n @param {number} [k] @returns {any} */
1834
+ const unwrapIn = (n, k = 0) => {
1835
+ if (!n || k > 20) return null;
1836
+ if (
1837
+ [
1838
+ 'TSAsExpression',
1839
+ 'TSSatisfiesExpression',
1840
+ 'TSNonNullExpression',
1841
+ 'ParenthesizedExpression',
1842
+ ].includes(n.type)
1843
+ )
1844
+ return unwrapIn(n.expression, k + 1);
1845
+ if (n.type === 'Identifier' && local.has(n.name))
1846
+ return unwrapIn(local.get(n.name), k + 1);
1847
+ return n;
1848
+ };
1849
+ return found
1850
+ ? {obj: unwrapIn(found), code: source, file, unwrap: unwrapIn}
1851
+ : null;
1852
+ } catch {
1853
+ return null;
1854
+ }
1855
+ }
1856
+ return null;
1857
+ };
1858
+ /**
1859
+ * @param {any} node
1860
+ * @param {number} depth
1861
+ * @param {{code: string, file: string | null, unwrap: (n: any) => any}} [at]
1862
+ * the file the node is in (null for the theme file)
1863
+ */
1864
+ const collect = (node, depth, at = {code, file: null, unwrap}) => {
1865
+ const obj = at.unwrap(node);
1866
+ // A name imported from a file beside the theme: read in that file, so
1867
+ // its values and lines are its own; the build still judges the result.
1868
+ if (obj?.type === 'Identifier' && at.file == null) {
1869
+ const from = imported(obj.name);
1870
+ if (from) {
1871
+ unresolved = true;
1872
+ collect(from.obj, depth + 1, from);
1873
+ return;
1874
+ }
1875
+ }
1255
1876
  if (obj?.type !== 'ObjectExpression' || depth > 20) {
1256
1877
  unresolved = true;
1257
1878
  return;
1258
1879
  }
1259
- // Spreads and keys merge in order: a later one wins.
1880
+ // Spreads and keys merge in order: a later one wins. A computed key
1881
+ // that is text (`['--radius-page']`) is read like a literal one.
1260
1882
  for (const p of obj.properties) {
1261
- if (p.type === 'SpreadElement') collect(p.argument, depth + 1);
1262
- else if (p.type === 'ObjectProperty' && !p.computed) {
1263
- const k = keyOf(p.key);
1264
- if (k?.startsWith('--')) out.set(k, textOf(unwrap(p.value)));
1883
+ if (p.type === 'SpreadElement') collect(p.argument, depth + 1, at);
1884
+ else if (p.type === 'ObjectProperty') {
1885
+ const k = p.computed ? textOf(at.unwrap(p.key)) : keyOf(p.key);
1886
+ if (k?.startsWith('--')) out.set(k, textOf(at.unwrap(p.value)));
1887
+ else if (p.computed) unresolved = true;
1888
+ if (detail && (k?.startsWith('--') || p.computed))
1889
+ detail.push({
1890
+ token: k?.startsWith('--') ? k : null,
1891
+ key: at.code.slice(p.key.start, p.key.end),
1892
+ line: p.loc?.start?.line ?? null,
1893
+ ...(at.file ? {file: at.file} : {}),
1894
+ ...valueShape(at.unwrap(p.value), at.unwrap),
1895
+ });
1265
1896
  } else unresolved = true;
1266
1897
  }
1267
1898
  };
1899
+ /**
1900
+ * What a token's value is, as written: text, a number, a [light, dark]
1901
+ * pair (each half's text, a number, or undefined), or something else.
1902
+ * @param {any} node
1903
+ * @param {(n: any) => any} [unwrapIn] how the node's file reads a name
1904
+ * @returns {Pick<OwnTokenEntry, 'kind' | 'value' | 'halves'>}
1905
+ */
1906
+ const valueShape = (node, unwrapIn = unwrap) => {
1907
+ const t = textOf(node);
1908
+ if (t != null) return {kind: 'text', value: t};
1909
+ if (node?.type === 'NumericLiteral')
1910
+ return {kind: 'number', value: node.value};
1911
+ if (node?.type === 'ArrayExpression')
1912
+ return {
1913
+ kind: 'pair',
1914
+ halves: node.elements.map((/** @type {any} */ e) => {
1915
+ const h = unwrapIn(e);
1916
+ return (
1917
+ textOf(h) ?? (h?.type === 'NumericLiteral' ? h.value : undefined)
1918
+ );
1919
+ }),
1920
+ };
1921
+ if (node?.type === 'ObjectExpression')
1922
+ return {
1923
+ kind: 'object',
1924
+ value: Object.fromEntries(
1925
+ node.properties
1926
+ .filter((/** @type {any} */ p) => p.type === 'ObjectProperty')
1927
+ .map((/** @type {any} */ p) => [
1928
+ keyOf(p.key) ?? '?',
1929
+ textOf(unwrap(p.value)) ?? null,
1930
+ ]),
1931
+ ),
1932
+ };
1933
+ return {kind: 'other'};
1934
+ };
1268
1935
  collect(tokensProp.value, 0);
1936
+ // Only the last entry for a token is what the build writes: an earlier
1937
+ // one a later key or spread overrides is marked, never judged.
1938
+ if (detail) {
1939
+ /** @type {Map<string, number>} */
1940
+ const last = new Map();
1941
+ detail.forEach((e, i) => {
1942
+ if (e.token) last.set(e.token, i);
1943
+ });
1944
+ detail.forEach((e, i) => {
1945
+ if (e.token && last.get(e.token) !== i) e.overridden = true;
1946
+ });
1947
+ }
1269
1948
  // A value no read of the file can resolve (a call, an import) is read
1270
1949
  // from the build (ownTokens), and checked again after the next one.
1271
- void unresolved;
1950
+ if (detail && unresolved)
1951
+ detail.push({
1952
+ token: null,
1953
+ key: 'tokens',
1954
+ kind: 'unresolved',
1955
+ line: tokensProp.loc?.start?.line ?? null,
1956
+ });
1272
1957
  return out;
1273
1958
  }
1274
1959
 
@@ -1541,6 +2226,27 @@ export function partRuleTokens(cwd, slug, like, part) {
1541
2226
  return out;
1542
2227
  }
1543
2228
 
2229
+ /**
2230
+ * Whether the base theme's own source gives a part's rule a property, in a
2231
+ * state (`:hover`) or at rest, read from its module as written.
2232
+ * @param {string} cwd
2233
+ * @param {string | undefined} like
2234
+ * @param {string} part
2235
+ * @param {string} scope `base` or a variant such as `variant:secondary`
2236
+ * @param {string | null} state a state block (`:hover`), or null
2237
+ * @param {string} prop camelCase
2238
+ */
2239
+ export function baseRuleHas(cwd, like, part, scope, state, prop) {
2240
+ const file = like ? baseModule(cwd, like) : null;
2241
+ if (!file) return false;
2242
+ try {
2243
+ const at = ['components', part, scope, ...(state ? [state] : [])];
2244
+ return blockOf(file, at).has(prop);
2245
+ } catch {
2246
+ return false;
2247
+ }
2248
+ }
2249
+
1544
2250
  /**
1545
2251
  * The tokens and properties a theme's own source sets on a part's plain
1546
2252
  * rule, read from the build as ownTokens reads page-wide ones: what the
@@ -1621,7 +2327,7 @@ function ownTokens(cwd, slug) {
1621
2327
  * @param {string} slug
1622
2328
  * @returns {Map<string, string | null> | null}
1623
2329
  */
1624
- function builtOwnTokens(cwd, slug) {
2330
+ function builtOwnTokens(cwd, slug, js = /** @type {string | null} */ (null)) {
1625
2331
  const f = themeFiles(cwd, slug);
1626
2332
  /** @type {string} */
1627
2333
  let module;
@@ -1633,7 +2339,10 @@ function builtOwnTokens(cwd, slug) {
1633
2339
  const built = /\/\/ Built with \S+\.theme\.ts ([0-9a-f]{16})\./.exec(
1634
2340
  module,
1635
2341
  )?.[1];
1636
- if (!built || !fs.existsSync(f.js) || built !== themeSourceHash(cwd, slug))
2342
+ if (
2343
+ !js &&
2344
+ (!built || !fs.existsSync(f.js) || built !== themeSourceHash(cwd, slug))
2345
+ )
1637
2346
  return null;
1638
2347
  // What the settings module gives each top-level token: a text value as
1639
2348
  // it is, a [light, dark] pair as a pair.
@@ -1688,7 +2397,7 @@ function builtOwnTokens(cwd, slug) {
1688
2397
  const named = namedInOwnSource(cwd, slug);
1689
2398
  /** @type {Map<string, string | null>} */
1690
2399
  const out = new Map();
1691
- for (const [k, v] of builtTopTokens(cwd, slug)) {
2400
+ for (const [k, v] of js ? topTokensOf(js) : builtTopTokens(cwd, slug)) {
1692
2401
  const given = settings.get(k);
1693
2402
  const own =
1694
2403
  given === undefined
@@ -1774,7 +2483,7 @@ export function ownSourceTokenValues(cwd, slug) {
1774
2483
  function scopeProblem(s) {
1775
2484
  if (s.on != null && !/^[a-z][a-z0-9-]*$/.test(s.on))
1776
2485
  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))
2486
+ if (s.state != null && !/^[a-z][a-zA-Z-]*$/.test(s.state))
1778
2487
  return `${s.thing} has state "${s.state}", which is not a state name`;
1779
2488
  if (s.when != null && !/^[\w-]+:[\w.-]+$/.test(s.when))
1780
2489
  return `${s.thing} has --when "${s.when}", which is not prop:value`;
@@ -1787,7 +2496,9 @@ function scopeProblem(s) {
1787
2496
  export const keyOf = s =>
1788
2497
  [
1789
2498
  s.thing,
1790
- s.axis ?? '',
2499
+ // A headings value saved with no axis is its weight half, as the build
2500
+ // reads it, so a set or undo of the weight replaces it.
2501
+ s.thing === 'headings' ? (s.axis ?? 'weight') : (s.axis ?? ''),
1791
2502
  s.on ?? '',
1792
2503
  s.when ?? '',
1793
2504
  s.state ?? '',
@@ -1959,6 +2670,44 @@ function partDefault(ctx, target, prop, when, state) {
1959
2670
  return r ? `var(${r.token})` : null;
1960
2671
  }
1961
2672
 
2673
+ /**
2674
+ * The variants (`variant:<name>`) of a part that each read their own value
2675
+ * of a color property (the button's background, a badge's text), in a
2676
+ * state when one is named and changes it: one rule's other-mode half would
2677
+ * give every one of them one variant's color. Empty when the part reads one
2678
+ * value for all.
2679
+ * @param {Ctx} ctx
2680
+ * @param {string} target
2681
+ * @param {string} prop camelCase or kebab-case
2682
+ * @param {string} [state]
2683
+ * @returns {string[]}
2684
+ */
2685
+ function variantsReading(ctx, target, prop, state) {
2686
+ const k = kebab(prop);
2687
+ const g = ctx.C.groupOfProp(k === 'background' ? 'background-color' : k);
2688
+ if (!g) return [];
2689
+ const reads = ctx.C.partReads(target, g).filter(x =>
2690
+ x.props.some(
2691
+ p => p === k || (k === 'background' && p === 'background-color'),
2692
+ ),
2693
+ );
2694
+ const named = (/** @type {(w: string) => boolean} */ ok) => [
2695
+ ...new Set(
2696
+ reads
2697
+ .flatMap(x => x.when)
2698
+ .filter(ok)
2699
+ .map(w => /(?:^|,)variant=([\w-]+)/.exec(w)?.[1])
2700
+ .filter(Boolean)
2701
+ .map(n => `variant:${n}`),
2702
+ ),
2703
+ ];
2704
+ const inState = state ? named(w => w.includes(`:${state}`)) : [];
2705
+ if (inState.length) return inState;
2706
+ return reads.some(x => x.when.includes(''))
2707
+ ? []
2708
+ : named(w => /^variant=[\w-]+$/.test(w));
2709
+ }
2710
+
1962
2711
  /** The line that records a generated module's own hash. */
1963
2712
  const SEAL = /^\/\/ Module ([0-9a-f]{16})\.\n/m;
1964
2713
 
@@ -2101,6 +2850,138 @@ function keepShades(pal, kept) {
2101
2850
  return {...pal, tokens, lift: kept['lifted parts'] ? pal.lift : null};
2102
2851
  }
2103
2852
 
2853
+ /**
2854
+ * A size in px: px, rem (16px each), or a calc() of those added and
2855
+ * subtracted; null for anything else.
2856
+ * @param {string} v
2857
+ * @param {Record<string, string>} [vars] values for the tokens a var() may name
2858
+ * @returns {number | null}
2859
+ */
2860
+ export function sizePx(v, vars = {}) {
2861
+ let t = String(v).trim();
2862
+ // A token the dial or the theme gives a value (var(--spacing-12)),
2863
+ // through that value; a clamp() at its preferred value held to its
2864
+ // bounds, or its upper bound when the preferred one is no length;
2865
+ // min() and max() of the lengths they hold.
2866
+ const fn = /^(var|clamp|min|max)\((.*)\)$/is.exec(t);
2867
+ if (fn) {
2868
+ const args = splitTop(fn[2], ',').map(x => x.trim());
2869
+ if (fn[1].toLowerCase() === 'var') {
2870
+ const own = vars[args[0]];
2871
+ if (own != null) return sizePx(own, vars);
2872
+ return args[1] != null ? sizePx(args.slice(1).join(','), vars) : null;
2873
+ }
2874
+ const n = args.map(x => sizePx(x, vars));
2875
+ if (fn[1].toLowerCase() === 'clamp') {
2876
+ const [lo, mid, hi] = n;
2877
+ if (lo == null || hi == null) return null;
2878
+ return mid == null ? hi : Math.min(hi, Math.max(lo, mid));
2879
+ }
2880
+ const known = /** @type {number[]} */ (n.filter(x => x != null));
2881
+ if (!known.length) return null;
2882
+ return fn[1].toLowerCase() === 'min'
2883
+ ? Math.min(...known)
2884
+ : Math.max(...known);
2885
+ }
2886
+ const calc = /^calc\((.*)\)$/is.exec(t);
2887
+ if (calc) t = calc[1].trim();
2888
+ const terms =
2889
+ t.match(/[+-]?\s*[\d.]+(?:px|rem|em|pt|pc|in|cm|mm|q)\b|\S+/gi) ?? [];
2890
+ let sum = 0;
2891
+ let sign = 1;
2892
+ for (const raw of terms) {
2893
+ const x = raw.replace(/\s+/g, '');
2894
+ if (x === '+' || x === '-') {
2895
+ if (!calc) return null;
2896
+ sign = x === '-' ? -1 : 1;
2897
+ continue;
2898
+ }
2899
+ const m = /^([+-]?)([\d.]+)(px|rem|em|pt|pc|in|cm|mm|q)$/i.exec(x);
2900
+ if (!m || (!calc && terms.length > 1)) return null;
2901
+ // Absolute units by their fixed ratio to px; em and rem against the
2902
+ // 16px a control's text starts from.
2903
+ const n = parseFloat(m[2]) * (PX_PER[m[3].toLowerCase()] ?? 1);
2904
+ if (!Number.isFinite(n)) return null;
2905
+ sum += (m[1] === '-' ? -1 : 1) * sign * n;
2906
+ sign = 1;
2907
+ }
2908
+ return terms.length ? sum : null;
2909
+ }
2910
+
2911
+ /** Pixels per unit of each length unit a kept size may be written in. */
2912
+ const PX_PER = /** @type {Record<string, number>} */ ({
2913
+ px: 1,
2914
+ rem: 16,
2915
+ em: 16,
2916
+ pt: 96 / 72,
2917
+ pc: 16,
2918
+ in: 96,
2919
+ cm: 96 / 2.54,
2920
+ mm: 96 / 25.4,
2921
+ q: 96 / 101.6,
2922
+ });
2923
+
2924
+ /**
2925
+ * Spacing steps scaled with the spacing dial, kept in order around the
2926
+ * steps the theme keeps exact: each the plain scaled value unless it would
2927
+ * meet or pass a kept one; those are spread evenly between the kept one and
2928
+ * the nearest step that keeps its place. A step with no room below a kept
2929
+ * one takes the value of the one below it.
2930
+ * @param {Array<[string, number]>} steps token name and the base value, in px
2931
+ * @param {number} f the rung's factor
2932
+ * @param {Record<string, number>} kept exact steps the theme keeps, in px
2933
+ * @param {string[]} [noRoom] filled with the steps left no room
2934
+ * @returns {Array<[string, number]>} every step's new value in px, kept ones as kept
2935
+ */
2936
+ export function spacingSteps(steps, f, kept, noRoom = []) {
2937
+ const px = [...steps].sort((a, b) => a[1] - b[1]);
2938
+ const n = px.map(([k, v]) => (k in kept ? kept[k] : v * f));
2939
+ const isKept = (/** @type {number} */ i) => px[i][0] in kept;
2940
+ px.forEach(([, base], k) => {
2941
+ if (!isKept(k)) return;
2942
+ // The steps below that would meet or pass it are spread evenly between
2943
+ // the last one that does not and it.
2944
+ let j0 = k;
2945
+ while (
2946
+ j0 > 0 &&
2947
+ !isKept(j0 - 1) &&
2948
+ n[j0 - 1] >= n[k] &&
2949
+ px[j0 - 1][1] < base
2950
+ )
2951
+ j0--;
2952
+ if (j0 < k) {
2953
+ const lo = j0 > 0 ? n[j0 - 1] : 0;
2954
+ if (lo >= n[k])
2955
+ for (let j = j0; j < k; j++) {
2956
+ n[j] = lo;
2957
+ noRoom.push(px[j][0]);
2958
+ }
2959
+ else
2960
+ for (let j = j0; j < k; j++)
2961
+ n[j] = lo + ((n[k] - lo) * (j - j0 + 1)) / (k - j0 + 1);
2962
+ }
2963
+ // The steps above that would meet or fall under it, likewise up to the
2964
+ // next one that does not (or above it by their own scaled steps).
2965
+ let j1 = k;
2966
+ while (
2967
+ j1 < n.length - 1 &&
2968
+ !isKept(j1 + 1) &&
2969
+ n[j1 + 1] <= n[k] &&
2970
+ px[j1 + 1][1] > base
2971
+ )
2972
+ j1++;
2973
+ if (j1 > k) {
2974
+ const hi = j1 < n.length - 1 ? n[j1 + 1] : null;
2975
+ for (let j = k + 1; j <= j1; j++)
2976
+ n[j] =
2977
+ hi == null
2978
+ ? n[k] + (px[j][1] - base) * f
2979
+ : n[k] + ((hi - n[k]) * (j - k)) / (j1 - k + 1);
2980
+ }
2981
+ });
2982
+ return px.map(([k], i) => [k, n[i]]);
2983
+ }
2984
+
2104
2985
  /**
2105
2986
  * Control heights scaled with the spacing dial (a denser theme has shorter
2106
2987
  * controls), each kept distinct and in order: smallest to largest, a
@@ -2110,28 +2991,44 @@ function keepShades(pal, kept) {
2110
2991
  * scaled above it.
2111
2992
  * @param {Array<[string, string]>} sizes token name and the theme's value
2112
2993
  * @param {number} f the spacing rung's factor
2994
+ * @param {Record<string, number>} [kept] exact sizes the theme keeps, in px,
2995
+ * which the others stay in order around
2996
+ * @param {string[]} [noRoom] filled with the sizes left no room between
2997
+ * two kept ones (each then equals the one below it)
2113
2998
  * @returns {Array<[string, string]>} the tokens it writes, in px
2114
2999
  */
2115
- export function controlSizes(sizes, f) {
3000
+ export function controlSizes(sizes, f, kept = {}, noRoom = []) {
2116
3001
  const px = sizes
2117
3002
  .filter(([, v]) => /^[\d.]+px$/.test(String(v).trim()))
2118
3003
  .map(([k, v]) => /** @type {[string, number]} */ ([k, parseFloat(v)]))
2119
3004
  .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;
3005
+ /** @type {number[]} */
3006
+ const n = px.map(([k, v]) =>
3007
+ k in kept ? kept[k] : Math.max(Math.min(24, v), Math.round(v * f)),
3008
+ );
3009
+ /** The step between two sizes, scaled. @param {number} i */
3010
+ const step = i => Math.max(1, Math.round((px[i][1] - px[i - 1][1]) * f));
3011
+ // Only a size that would meet (or pass) the one below moves, up; then one
3012
+ // that would meet a kept size above it moves down (a kept size stays).
3013
+ for (let i = 1; i < n.length; i++)
3014
+ if (!(px[i][0] in kept) && n[i] <= n[i - 1]) n[i] = n[i - 1] + step(i);
3015
+ for (let i = n.length - 2; i >= 0; i--)
3016
+ if (!(px[i][0] in kept) && n[i] >= n[i + 1]) n[i] = n[i + 1] - step(i + 1);
3017
+ // A size between two that cannot both move (kept, or one kept and the
3018
+ // other already at its place) sits halfway between them; with no room
3019
+ // between them it takes the smaller one's size, and the result says so.
3020
+ for (let i = 1; i < n.length - 1; i++)
3021
+ if (!(px[i][0] in kept) && (n[i] <= n[i - 1] || n[i] >= n[i + 1])) {
3022
+ const mid = Math.round(((n[i - 1] + n[i + 1]) / 2) * 2) / 2;
3023
+ if (mid > n[i - 1] && mid < n[i + 1]) n[i] = mid;
3024
+ else {
3025
+ n[i] = n[i - 1];
3026
+ noRoom.push(px[i][0]);
3027
+ }
3028
+ }
3029
+ return px
3030
+ .map(([k], i) => /** @type {[string, string]} */ ([k, `${n[i]}px`]))
3031
+ .filter(([k]) => !(k in kept));
2135
3032
  }
2136
3033
 
2137
3034
  /**
@@ -2142,6 +3039,8 @@ export function controlSizes(sizes, f) {
2142
3039
  * @returns {any}
2143
3040
  */
2144
3041
  export function compileTheme(ctx, data, base) {
3042
+ ctx.sizeNotes = [];
3043
+ ctx.compileNotes = [];
2145
3044
  // A setting the editor no longer accepts never reaches the build.
2146
3045
  data = {...data, settings: data.settings.filter(s => !valueProblem(s))};
2147
3046
  const TOKENS = ctx.project.core.tokenDefaults;
@@ -2164,6 +3063,44 @@ export function compileTheme(ctx, data, base) {
2164
3063
  : data.mode === 'dark-only'
2165
3064
  ? 'dark'
2166
3065
  : null;
3066
+ /** The tokens the theme's own source sets, which win over the settings. */
3067
+ /** @type {Record<string, string> | null} */
3068
+ let ownTok = null;
3069
+ const ownTokenValues = () => {
3070
+ if (ownTok) return ownTok;
3071
+ try {
3072
+ ownTok = ownSourceTokenValues(ctx.project.cwd, data.name);
3073
+ } catch {
3074
+ ownTok = {};
3075
+ }
3076
+ return ownTok;
3077
+ };
3078
+ /**
3079
+ * The exact tokens kept where a dial writes (whole theme with no part):
3080
+ * the whole-theme settings', then the own source's, by name.
3081
+ * @param {string | null} t a part, for its own settings too
3082
+ * @returns {Map<string, string>}
3083
+ */
3084
+ const keptTokens = t => {
3085
+ /** @type {Map<string, string>} */
3086
+ const out = new Map();
3087
+ for (const x of data.settings)
3088
+ if (
3089
+ x.source === 'token' &&
3090
+ !x.when &&
3091
+ !x.state &&
3092
+ !(modeOnly && x.mode && x.mode !== modeOnly) &&
3093
+ (!x.on || (t != null && partsOf(ctx, x).includes(t)))
3094
+ )
3095
+ out.set(x.thing, String(x.value));
3096
+ for (const [k, v] of Object.entries(ownTokenValues())) out.set(k, v);
3097
+ return out;
3098
+ };
3099
+ /** @param {string | null} t */
3100
+ const keptSizes = t =>
3101
+ [...keptTokens(t)].filter(([k]) => /^--size-element-/.test(k));
3102
+ /** The one-mode gradient layers each block holds, by mode. @type {WeakMap<object, {light: string[], dark: string[]}>} */
3103
+ const modeLayers = new WeakMap();
2167
3104
  /** @type {Record<string, {light?: string, dark?: string}>} */
2168
3105
  const tok = {};
2169
3106
  /** @param {string} name @param {string | [string, string]} v @param {string} [mode] */
@@ -2177,12 +3114,22 @@ export function compileTheme(ctx, data, base) {
2177
3114
  if (!mode || mode === 'dark') t.dark = v[1];
2178
3115
  return;
2179
3116
  }
2180
- if (!MODAL.has(ctx.C.typeOf(name)) || modeOnly || !mode) {
3117
+ // A color set in a one-mode theme fills its mode's half only; the other
3118
+ // half keeps what it had (the base theme's), for the regions Core draws
3119
+ // in the other mode.
3120
+ const half = mode ?? modeOnly;
3121
+ // Only a color has a half per mode (light-dark() takes colors only): a
3122
+ // shadow or any other value in a one-mode theme is written whole.
3123
+ if (
3124
+ !MODAL.has(ctx.C.typeOf(name)) ||
3125
+ !half ||
3126
+ (!mode && !parseColor(String(v).trim()))
3127
+ ) {
2181
3128
  t.light = v;
2182
3129
  t.dark = v;
2183
3130
  return;
2184
3131
  }
2185
- t[/** @type {'light' | 'dark'} */ (mode)] = v;
3132
+ t[/** @type {'light' | 'dark'} */ (half)] = v;
2186
3133
  };
2187
3134
  /** @param {Setting} s @param {string} target @returns {Record<string, any>} */
2188
3135
  const block = (s, target) => {
@@ -2471,9 +3418,11 @@ export function compileTheme(ctx, data, base) {
2471
3418
  return n && n.unit === '' && n.value === 0 ? '0px' : v;
2472
3419
  };
2473
3420
  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;
3421
+ // The own source's padding on the same rule wins over the editor's on
3422
+ // the sides it sets (the result says so); the editor's other sides
3423
+ // still apply.
3424
+ const own = ownBox(target, s);
3425
+ if (own.ltr.size === 4 && own.rtl.size === 4) continue;
2477
3426
  const prefix = /** @type {string} */ (padVars(target));
2478
3427
  const owner = prefix.slice('--astryx-'.length, -'-padding'.length);
2479
3428
  const scoped = target !== owner || s.when != null || s.state != null;
@@ -2517,6 +3466,10 @@ export function compileTheme(ctx, data, base) {
2517
3466
  }
2518
3467
  }
2519
3468
  }
3469
+ // The sides the own source pads in a direction are its own there.
3470
+ for (const dir of /** @type {const} */ (['ltr', 'rtl']))
3471
+ for (const x of Object.keys(side[dir]))
3472
+ if (own[dir].has(boxSide(x, dir))) delete side[dir][x];
2520
3473
  /** @type {Record<string, string>} */
2521
3474
  let plain = {};
2522
3475
  /** @type {Record<string, string>} */
@@ -2586,6 +3539,78 @@ export function compileTheme(ctx, data, base) {
2586
3539
  b[key] = {...(b[key] ?? {}), ...rule};
2587
3540
  }
2588
3541
  }
3542
+ // A variant the own source pads: the sides it sets are left without a
3543
+ // side variable there, so the variant's own padding (which Core writes
3544
+ // as the whole padding) wins over any side the plain rule writes.
3545
+ for (const owner of new Set(
3546
+ [...padQueue.values()]
3547
+ .filter(({target, s}) => !s.when && !s.state && padVars(target))
3548
+ .map(({target}) =>
3549
+ /** @type {string} */ (padVars(target)).slice(
3550
+ '--astryx-'.length,
3551
+ -'-padding'.length,
3552
+ ),
3553
+ ),
3554
+ )) {
3555
+ const values = ctx.C.variantValues(owner);
3556
+ for (const [prop, vals] of Object.entries(values ?? {}))
3557
+ for (const v of /** @type {string[]} */ (vals ?? [])) {
3558
+ const when = `${prop}:${v}`;
3559
+ const own = ownBox(owner, /** @type {any} */ ({when}));
3560
+ if (!own.ltr.size && !own.rtl.size) continue;
3561
+ const variant = /** @type {any} */ ({when});
3562
+ const logical = [
3563
+ 'block-start',
3564
+ 'block-end',
3565
+ 'inline-start',
3566
+ 'inline-end',
3567
+ ];
3568
+ const at = (/** @type {'ltr' | 'rtl'} */ dir) =>
3569
+ logical.filter(x => own[dir].has(boxSide(x, dir)));
3570
+ const [l, r] = [at('ltr'), at('rtl')];
3571
+ const b = block(variant, owner);
3572
+ for (const x of l.filter(x => r.includes(x)))
3573
+ b[`--astryx-${owner}-padding-${x}`] ??= 'initial';
3574
+ // A pair variable the plain rule writes (the inline or block
3575
+ // padding) feeds both its sides, under the side variables: where
3576
+ // the own source pads both, it is left without a value too, so
3577
+ // the variant's own padding holds there.
3578
+ for (const pair of ['block', 'inline'])
3579
+ if (
3580
+ [`${pair}-start`, `${pair}-end`].every(
3581
+ x => l.includes(x) && r.includes(x),
3582
+ )
3583
+ )
3584
+ b[`--astryx-${owner}-padding-${pair}`] ??= 'initial';
3585
+ // Its own sides inherit into a plain one of the part inside it:
3586
+ // they are reset there like the editor's (below).
3587
+ const sel = narrowSelector(owner, variant);
3588
+ if (sel) {
3589
+ const bySel = narrow.get(owner) ?? new Map();
3590
+ const names = bySel.get(sel) ?? new Set();
3591
+ for (const x of new Set([...l, ...r]))
3592
+ names.add(`--astryx-${owner}-padding-${x}`);
3593
+ for (const pair of ['block', 'inline'])
3594
+ if ([...l, ...r].some(x => x.startsWith(pair)))
3595
+ names.add(`--astryx-${owner}-padding-${pair}`);
3596
+ bySel.set(sel, names);
3597
+ narrow.set(owner, bySel);
3598
+ }
3599
+ for (const [dir, xs] of /** @type {const} */ ([
3600
+ [':dir(ltr)', l.filter(x => !r.includes(x))],
3601
+ [':dir(rtl)', r.filter(x => !l.includes(x))],
3602
+ ]))
3603
+ if (xs.length) {
3604
+ const [db, key] = dirBlock(variant, owner, dir);
3605
+ db[key] = {
3606
+ ...(db[key] ?? {}),
3607
+ ...Object.fromEntries(
3608
+ xs.map(x => [`--astryx-${owner}-padding-${x}`, 'initial']),
3609
+ ),
3610
+ };
3611
+ }
3612
+ }
3613
+ }
2589
3614
  // A plain part inside a narrower one: each side the narrower selector
2590
3615
  // writes is reset (left without a value, so Core's own fallback holds),
2591
3616
  // on the part's own class at its own weight, before any base setting a
@@ -2668,25 +3693,66 @@ export function compileTheme(ctx, data, base) {
2668
3693
  return out;
2669
3694
  };
2670
3695
  /**
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).
3696
+ * The box side a padding side names in a direction: a physical side as it
3697
+ * is, a logical one as the direction reads it (inline-start is the left in
3698
+ * left-to-right text, the right in right-to-left).
3699
+ * @param {string} x top, right, bottom, left, or a logical side
3700
+ * @param {'ltr' | 'rtl'} dir
3701
+ */
3702
+ const boxSide = (x, dir) =>
3703
+ ({
3704
+ 'block-start': 'top',
3705
+ 'block-end': 'bottom',
3706
+ 'inline-start': dir === 'ltr' ? 'left' : 'right',
3707
+ 'inline-end': dir === 'ltr' ? 'right' : 'left',
3708
+ })[x] ?? x;
3709
+ /**
3710
+ * The padding sides a padding property names, as it names them (physical
3711
+ * stays physical, logical stays logical), with each one's value.
3712
+ * @param {string} prop kebab-case
3713
+ * @param {string} value
3714
+ * @returns {Record<string, string>}
3715
+ */
3716
+ const paddingSides = (prop, value) => {
3717
+ const w = splitTop(String(value).trim(), ' ').map(y => y.trim());
3718
+ if (prop === 'padding') {
3719
+ const [top, right = top, bottom = top, left = right] = w;
3720
+ return {top, right, bottom, left};
3721
+ }
3722
+ if (prop === 'padding-block')
3723
+ return {'block-start': w[0], 'block-end': w[1] ?? w[0]};
3724
+ if (prop === 'padding-inline')
3725
+ return {'inline-start': w[0], 'inline-end': w[1] ?? w[0]};
3726
+ const side = prop.slice('padding-'.length);
3727
+ return /^(top|right|bottom|left|(block|inline)-(start|end))$/.test(side)
3728
+ ? {[side]: w[0]}
3729
+ : {};
3730
+ };
3731
+ /**
3732
+ * The box sides the theme's own source pads on a part's rule for a scope
3733
+ * (its plain rule, a variant, a state), in each direction.
2673
3734
  * @param {string} target @param {Setting} s
3735
+ * @returns {Record<'ltr' | 'rtl', Set<string>>}
2674
3736
  */
2675
- const ownPads = (target, s) => {
3737
+ const ownBox = (target, s) => {
3738
+ const out = {ltr: new Set(), rtl: new Set()};
2676
3739
  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));
3740
+ for (const k of ownPartTokens(
3741
+ ctx.project.cwd,
3742
+ data.name,
3743
+ target,
3744
+ s.when ?? 'base',
3745
+ s.state ? `:${s.state}` : null,
3746
+ ).keys())
3747
+ for (const x of Object.keys(paddingSides(k, '0')))
3748
+ for (const dir of /** @type {const} */ (['ltr', 'rtl']))
3749
+ out[dir].add(boxSide(x, dir));
2686
3750
  } catch {
2687
- return false;
3751
+ // No own source.
2688
3752
  }
3753
+ return out;
2689
3754
  };
3755
+
2690
3756
  /**
2691
3757
  * The selector a narrower padding scope is written with (a clickable
2692
3758
  * card's class, a variant's attribute, a state's pseudo-class), or null
@@ -2712,11 +3778,18 @@ export function compileTheme(ctx, data, base) {
2712
3778
  const keys = Object.keys(b);
2713
3779
  const plain = keys.filter(k => !k.startsWith(':'));
2714
3780
  const dirs = keys.filter(k => /^:(where\()?dir\(/.test(k));
3781
+ // The reset a plain part inside a narrower one gets comes before the
3782
+ // part's own direction rules at the same weight, so a side the part
3783
+ // sets for a direction holds inside a variant too.
3784
+ const resets = keys.filter(k => /^:where\((?!:?dir\().* \*\)$/.test(k));
2715
3785
  const rest = keys.filter(
2716
- k => k.startsWith(':') && !/^:(where\()?dir\(/.test(k),
3786
+ k =>
3787
+ k.startsWith(':') &&
3788
+ !/^:(where\()?dir\(/.test(k) &&
3789
+ !resets.includes(k),
2717
3790
  );
2718
3791
  return Object.fromEntries(
2719
- [...plain, ...dirs, ...rest].map(k => [
3792
+ [...plain, ...resets, ...dirs, ...rest].map(k => [
2720
3793
  k,
2721
3794
  k.startsWith(':') && b[k] && typeof b[k] === 'object'
2722
3795
  ? dirFirst(b[k])
@@ -2767,16 +3840,338 @@ export function compileTheme(ctx, data, base) {
2767
3840
  const parent = block({...s, state: undefined}, target);
2768
3841
  return [parent, `${stateKey(s.state, wrapsOneControl(ctx, target))}${dir}`];
2769
3842
  };
3843
+ /**
3844
+ * One half of a light-dark() pair (1 light, 2 dark), or the value itself.
3845
+ * @param {string} x @param {1 | 2} side
3846
+ */
3847
+ const halfOf = (x, side) => {
3848
+ const inner = /^light-dark\((.*)\)$/s.exec(x.trim())?.[1];
3849
+ const halves = inner == null ? [] : splitTop(inner, ',');
3850
+ return halves.length === 2 ? halves[side - 1].trim() : x.trim();
3851
+ };
3852
+ /**
3853
+ * The value a variant of a part shows for a color property where the
3854
+ * theme sets none of its own: the base theme's rule for that variant (in
3855
+ * the state, else at rest), else Core's, else transparent for a
3856
+ * background Core never paints; null for a text color Core never sets.
3857
+ * @param {string} target @param {string} css a color longhand, kebab-case
3858
+ * @param {string} name the variant @param {string} [state]
3859
+ * @param {boolean} [stateOnly] the state's own value only, never the resting one
3860
+ * @returns {string | null}
3861
+ */
3862
+ const exactVariantValue = (target, css, name, state, stateOnly = false) => {
3863
+ const when = `variant:${name}`;
3864
+ const kebabs =
3865
+ css === 'background-color' ? ['background-color', 'background'] : [css];
3866
+ const props = kebabs.map(camel);
3867
+ const steps = state
3868
+ ? stateOnly
3869
+ ? [state]
3870
+ : [state, undefined]
3871
+ : [undefined];
3872
+ for (const st of steps)
3873
+ for (const p of props) {
3874
+ const b = baseComponent(base, ctx, target, p, {when, state: st});
3875
+ if (b != null) return b;
3876
+ }
3877
+ const keyOf = (/** @type {string} */ k) => {
3878
+ const [attrs, cond = ''] = k.split(' ');
3879
+ return attrs.split(',').includes(`variant=${name}`) ? cond : null;
3880
+ };
3881
+ for (const st of steps)
3882
+ for (const p of kebabs) {
3883
+ const at = ctx.C.MAP[target]?.at?.[p];
3884
+ for (const [k, val] of Object.entries(at ?? {})) {
3885
+ const cond = keyOf(k);
3886
+ if (cond == null) continue;
3887
+ if (st ? cond.includes(`:${st}`) : cond === '') return val;
3888
+ }
3889
+ }
3890
+ if (stateOnly) return null;
3891
+ return css === 'background-color'
3892
+ ? 'transparent'
3893
+ : css === 'color'
3894
+ ? null
3895
+ : 'currentcolor';
3896
+ };
3897
+ /** The family a color property belongs to: background is background-color. @param {string} p */
3898
+ const colorFamily = p => {
3899
+ const k = kebab(p);
3900
+ return k === 'background' ? 'background-color' : k;
3901
+ };
3902
+ /** One-mode colors in a variant or a state, written after every other setting. @type {Array<() => void>} */
3903
+ const scopedQueue = [];
3904
+ let drainingScoped = false;
3905
+ /**
3906
+ * A part's rule for a scope as the theme has it, without making one.
3907
+ * @param {Setting} s @param {string} target
3908
+ * @returns {Record<string, any> | undefined}
3909
+ */
3910
+ const peekBlock = (s, target) => {
3911
+ const t = theme.components[target];
3912
+ if (!t) return undefined;
3913
+ const rule = t[s.when ?? 'base'];
3914
+ if (!s.state) return rule;
3915
+ const tg = ctx.project.target.get(target);
3916
+ if (tg?.states.includes(s.state))
3917
+ return s.when == null ? t[s.state] : t[`${s.when}+${s.state}`];
3918
+ return rule?.[stateKey(s.state, wrapsOneControl(ctx, target))];
3919
+ };
3920
+ /**
3921
+ * The theme's own value of a property in one mode for the scope around a
3922
+ * setting's scope: the variant's resting rule for a state, then the
3923
+ * part's plain rule, then, for a token, the whole theme's value; null
3924
+ * when the theme gives none, so the base theme's and Core's values apply.
3925
+ * @param {Setting} s @param {string} target @param {string} prop
3926
+ * @param {'light' | 'dark'} side
3927
+ * @returns {string | null}
3928
+ */
3929
+ const enclosingValue = (s, target, prop, side) => {
3930
+ const family = /^background(-color)?$/.test(kebab(prop))
3931
+ ? ['backgroundColor', 'background']
3932
+ : [prop];
3933
+ /** @type {Setting[]} */
3934
+ const scopes = [];
3935
+ if (s.state) scopes.push({...s, state: undefined, mode: undefined});
3936
+ if (s.when || s.state)
3937
+ scopes.push({...s, when: undefined, state: undefined, mode: undefined});
3938
+ for (const sc of scopes) {
3939
+ const rule = peekBlock(sc, target);
3940
+ for (const k of family) {
3941
+ const x = rule?.[k];
3942
+ if (typeof x === 'string' && !/gradient\(|url\(/i.test(x))
3943
+ return halfOf(x, side === 'light' ? 1 : 2);
3944
+ }
3945
+ }
3946
+ if (prop.startsWith('--')) return tok[prop]?.[side] ?? null;
3947
+ return null;
3948
+ };
2770
3949
  /** @param {Setting} s @param {string} target @param {string} prop @param {string} v */
2771
3950
  const putComp = (s, target, prop, v) => {
2772
3951
  const b = block(s, target);
2773
- if (s.mode && !modeOnly) {
3952
+ // A gradient background for one mode: each layer's colors are painted
3953
+ // in that mode only (transparent in the other), as background images
3954
+ // beside the other mode's, so each mode keeps its own background color;
3955
+ // a gradient for both modes held before keeps showing in the other
3956
+ // mode. Which layers belong to which mode is recorded as they are
3957
+ // written, never read back from their stops.
3958
+ if (
3959
+ s.mode &&
3960
+ /^background(-image)?$/.test(kebab(prop)) &&
3961
+ /gradient\(/i.test(v)
3962
+ ) {
3963
+ let rec = modeLayers.get(b);
3964
+ if (!rec) {
3965
+ rec = {light: [], dark: []};
3966
+ for (const k of ['background', 'backgroundImage']) {
3967
+ const held = b[k];
3968
+ if (typeof held !== 'string' || !/gradient\(/i.test(held)) continue;
3969
+ rec.light.push(...maskLayers(held, 'light'));
3970
+ rec.dark.push(...maskLayers(held, 'dark'));
3971
+ if (k === 'backgroundImage') delete b[k];
3972
+ }
3973
+ modeLayers.set(b, rec);
3974
+ }
3975
+ // The background shorthand's last layer may carry the color under
3976
+ // the images: that color is this mode's background color, and the
3977
+ // rest are the images.
3978
+ const {images, color} =
3979
+ kebab(prop) === 'background'
3980
+ ? backgroundColorLayer(v)
3981
+ : {images: v, color: null};
3982
+ rec[s.mode] = images ? maskLayers(images, s.mode) : [];
3983
+ const parts = [...rec.light, ...rec.dark].map(layerParts);
3984
+ for (const k of [
3985
+ 'backgroundImage',
3986
+ 'backgroundPosition',
3987
+ 'backgroundSize',
3988
+ 'backgroundRepeat',
3989
+ ])
3990
+ delete b[k];
3991
+ b.backgroundImage = parts.map(x => x.image).join(', ');
3992
+ if (parts.some(x => x.position || x.size || x.repeat)) {
3993
+ b.backgroundPosition = parts.map(x => x.position || '0% 0%').join(', ');
3994
+ b.backgroundSize = parts.map(x => x.size || 'auto').join(', ');
3995
+ b.backgroundRepeat = parts.map(x => x.repeat || 'repeat').join(', ');
3996
+ }
3997
+ if (!parts.length) delete b.backgroundImage;
3998
+ if (color) putComp(s, target, 'backgroundColor', color);
3999
+ return;
4000
+ }
4001
+ // A color set in a one-mode theme fills its mode's half only (as a
4002
+ // setting for that mode does), so a region Core draws in the other mode
4003
+ // reads the other half.
4004
+ const mode =
4005
+ s.mode ??
4006
+ (modeOnly && parseColor(String(v).trim()) ? modeOnly : undefined);
4007
+ // A color for one mode on a part rule also gives the other mode a
4008
+ // value in that rule, which outranks the rules the base theme and Core
4009
+ // give the part in context there (a selected or current item, a status
4010
+ // border): the result says so.
4011
+ if (mode && !prop.startsWith('--')) {
4012
+ const note = `a ${mode}-only color on ${target} gives the other mode ${target}'s own value, so in that mode it overrides what Core or the base theme gives ${target} in context (a selected or current item, a status border)`;
4013
+ if (!(ctx.compileNotes ?? []).includes(note))
4014
+ (ctx.compileNotes ??= []).push(note);
4015
+ }
4016
+ if (mode && !s.when && variantsReading(ctx, target, prop, s.state).length) {
4017
+ // A color for one mode on a part whose variants each have their own:
4018
+ // each variant's rule (in the state, for a state setting) gets the
4019
+ // color in that mode and, in the other, exactly the value it shows
4020
+ // unset there (the base theme's, else Core's), so no variant takes
4021
+ // another's and the other mode stays as it was. The part's own rule
4022
+ // is left alone.
4023
+ // The property itself (a border color stays a border color); the
4024
+ // background shorthand is written as its color.
4025
+ const css = colorFamily(prop);
4026
+ const other = mode === 'light' ? 2 : 1;
4027
+ // What the part's own rule holds of it (an earlier setting for both
4028
+ // modes): the other half each variant keeps, before its unset value.
4029
+ const plainHeld = [
4030
+ css,
4031
+ ...(css === 'background-color' ? ['background'] : []),
4032
+ ]
4033
+ .map(k => b[camel(k)])
4034
+ .find(y => typeof y === 'string' && !/gradient\(|url\(/i.test(y));
4035
+ // The part's own background being an image (a gradient) covers any
4036
+ // color under it: the color is written, and the result says it does
4037
+ // not show.
4038
+ const plainImage =
4039
+ css === 'background-color'
4040
+ ? ['background', 'backgroundImage']
4041
+ .map(k => b[k])
4042
+ .find(y => typeof y === 'string' && /gradient\(|url\(/i.test(y))
4043
+ : undefined;
4044
+ if (plainImage)
4045
+ (ctx.compileNotes ??= []).push(
4046
+ `${target}'s own background is an image (${plainImage}), which covers the ${mode} color: it does not show until that background is a color`,
4047
+ );
4048
+ const names = new Set([
4049
+ ...(ctx.C.variantValues(target)?.variant ?? []),
4050
+ ...(ctx.C.MAP[target]?.attrs?.variant ?? []),
4051
+ ]);
4052
+ for (const name of names) {
4053
+ const x = exactVariantValue(target, css, name, s.state);
4054
+ const vb = block({...s, when: `variant:${name}`}, target);
4055
+ // What the variant's rule already holds (a setting for the other
4056
+ // mode, or one for both) keeps its other half; else the value the
4057
+ // variant shows unset.
4058
+ // The background shorthand is the same property: its color counts,
4059
+ // and it is taken out so the color written here is in effect.
4060
+ const family = [
4061
+ css,
4062
+ ...(css === 'background-color' ? ['background'] : []),
4063
+ ];
4064
+ // A variant whose own background is an image (a gradient) keeps
4065
+ // it: one mode's color is not written there, and the result says so.
4066
+ const image = family
4067
+ .map(k => vb[camel(k)])
4068
+ .find(y => typeof y === 'string' && /gradient\(|url\(/i.test(y));
4069
+ if (image) {
4070
+ (ctx.compileNotes ??= []).push(
4071
+ `${target} variant:${name} keeps its own background image (${image}), so the ${mode} color is not written there`,
4072
+ );
4073
+ continue;
4074
+ }
4075
+ const prev = family
4076
+ .map(k => vb[camel(k)])
4077
+ .find(y => typeof y === 'string');
4078
+ // In a state, what the state shows now in the other mode: its own
4079
+ // value there, else the resting color a setting gives the variant
4080
+ // or the part (a state that does not change the color shows the
4081
+ // resting one), else the unset value.
4082
+ /** @param {Record<string, any> | undefined} rule */
4083
+ const restOf = rule =>
4084
+ family
4085
+ .map(k => rule?.[camel(k)])
4086
+ .find(y => typeof y === 'string' && !/gradient\(|url\(/i.test(y));
4087
+ const rest = s.state
4088
+ ? (exactVariantValue(target, css, name, s.state, true) ??
4089
+ restOf(theme.components[target]?.[`variant:${name}`]) ??
4090
+ plainHeld ??
4091
+ restOf(theme.components[target]?.base))
4092
+ : plainHeld;
4093
+ const from = prev ?? rest ?? x;
4094
+ if (from == null) continue;
4095
+ for (const k of family) delete vb[camel(k)];
4096
+ const half = halfOf(from, other);
4097
+ vb[camel(css)] =
4098
+ mode === 'light'
4099
+ ? `light-dark(${v}, ${half})`
4100
+ : `light-dark(${half}, ${v})`;
4101
+ // A resting color written on the variant's rule would also hide the
4102
+ // hover the variant shows unset: that hover is written back as it
4103
+ // was, in both modes, unless a hover setting of the theme's own
4104
+ // gives it one.
4105
+ if (
4106
+ !s.state &&
4107
+ !data.settings.some(
4108
+ y =>
4109
+ y.on === s.on &&
4110
+ y.state === 'hover' &&
4111
+ colorFamily(y.thing) === colorFamily(s.thing),
4112
+ )
4113
+ ) {
4114
+ const hover = exactVariantValue(target, css, name, 'hover', true);
4115
+ if (hover != null && hover !== x) {
4116
+ const hb = block(
4117
+ {...s, when: `variant:${name}`, state: 'hover', mode: undefined},
4118
+ target,
4119
+ );
4120
+ hb[camel(css)] ??= hover;
4121
+ }
4122
+ }
4123
+ }
4124
+ return;
4125
+ }
4126
+ // A color for one mode in a variant or a state is written once every
4127
+ // other setting is in, so its other half is the theme's own value for
4128
+ // the scope around it as the theme finally has it (below).
4129
+ if (mode && (s.when || s.state) && !drainingScoped) {
4130
+ scopedQueue.push(() => putComp(s, target, prop, v));
4131
+ return;
4132
+ }
4133
+ if (mode && colorFamily(prop) === 'background-color') {
4134
+ // The background shorthand and its color are one property: the one
4135
+ // the rule holds (as a color) gives the other half and is replaced, so
4136
+ // one key carries both modes.
4137
+ const held = ['backgroundColor', 'background'].find(
4138
+ k => typeof b[k] === 'string' && !/gradient\(|url\(/i.test(b[k]),
4139
+ );
4140
+ if (held && held !== camel(prop)) {
4141
+ const was = b[held];
4142
+ delete b[held];
4143
+ b[camel(prop)] ??= was;
4144
+ }
4145
+ }
4146
+ // A color for one mode under the part's own gradient does not show:
4147
+ // the result says so.
4148
+ if (
4149
+ mode &&
4150
+ colorFamily(prop) === 'background-color' &&
4151
+ ['background', 'backgroundImage'].some(
4152
+ k => typeof b[k] === 'string' && /gradient\(|url\(/i.test(b[k]),
4153
+ )
4154
+ )
4155
+ (ctx.compileNotes ??= []).push(
4156
+ `${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`,
4157
+ );
4158
+ if (mode) {
2774
4159
  const prev = b[prop];
2775
4160
  // The other mode keeps exactly what it had: the value set for it, the
2776
4161
  // part's own, else what the property shows unset (light-dark() takes
2777
4162
  // colors only, so never inherit).
4163
+ // A token on the part: its own value in the other mode (the base
4164
+ // theme's, else Core's), never another color.
4165
+ const otherSide = mode === 'light' ? 'dark' : 'light';
4166
+ const tokenOther = prop.startsWith('--')
4167
+ ? (base[otherSide]?.[prop] ??
4168
+ /** @type {Record<string, string>} */ (TOKENS)[prop] ??
4169
+ null)
4170
+ : null;
2778
4171
  const other =
2779
4172
  prev ??
4173
+ enclosingValue(s, target, prop, otherSide) ??
4174
+ tokenOther ??
2780
4175
  baseComponent(base, ctx, target, prop, s) ??
2781
4176
  partDefault(ctx, target, prop, s.when, s.state) ??
2782
4177
  (s.state
@@ -2791,7 +4186,7 @@ export function compileTheme(ctx, data, base) {
2791
4186
  return halves.length === 2 ? halves[side - 1].trim() : x;
2792
4187
  };
2793
4188
  b[prop] =
2794
- s.mode === 'light'
4189
+ mode === 'light'
2795
4190
  ? `light-dark(${v}, ${prev ? split(prev, 2) : other})`
2796
4191
  : `light-dark(${prev ? split(prev, 1) : other}, ${v})`;
2797
4192
  } else b[prop] = v;
@@ -2879,6 +4274,19 @@ export function compileTheme(ctx, data, base) {
2879
4274
  ...data.settings.filter(x => x.source === 'dial' && roleFont(x)),
2880
4275
  ...data.settings.filter(x => x.source !== 'dial'),
2881
4276
  ];
4277
+ // The shell regions a setting gives a background of their own keep it
4278
+ // when the page background paints the rest of the shell.
4279
+ const regionsWithOwnBackground = new Set(
4280
+ data.settings
4281
+ .filter(
4282
+ x =>
4283
+ x.source === 'property' &&
4284
+ /^background(-color|-image)?$/.test(kebab(x.thing)),
4285
+ )
4286
+ .flatMap(x => partsOf(ctx, x)),
4287
+ );
4288
+ /** @type {Record<string, any>[]} */
4289
+ const fixedToViewport = [];
2882
4290
  for (const s of ordered) {
2883
4291
  // A setting for the mode a one-mode theme does not have stays saved but
2884
4292
  // does not apply (maskedSettings names it).
@@ -2903,7 +4311,7 @@ export function compileTheme(ctx, data, base) {
2903
4311
  rung || pill ? derived(radiusTokenOf(ctx, t, s.when)) : `${px}px`,
2904
4312
  );
2905
4313
  }
2906
- else
4314
+ else {
2907
4315
  for (const token of [
2908
4316
  '--radius-element',
2909
4317
  '--radius-inner',
@@ -2914,6 +4322,21 @@ export function compileTheme(ctx, data, base) {
2914
4322
  // build by an earlier editor, or a step back) are kept, as the
2915
4323
  // colors are: they change only when corners or the base does.
2916
4324
  putTok(token, ctx.keepRadii?.[token] ?? derived(token));
4325
+ // A part rule of the base theme that gives a radius of its own
4326
+ // (not one of the radius tokens) would keep it over the dial: the
4327
+ // rule is given the radius token the part reads, so every part
4328
+ // follows the dial.
4329
+ for (const [t, when] of basePinnedRadii(
4330
+ /** @type {{components?: Record<string, any>}} */ (base),
4331
+ ))
4332
+ if (ctx.project.target.has(t))
4333
+ putComp(
4334
+ {...s, mode: undefined, when},
4335
+ t,
4336
+ 'borderRadius',
4337
+ `var(${radiusTokenOf(ctx, t, when)})`,
4338
+ );
4339
+ }
2917
4340
  } else if (PALETTE_DIALS.includes(s.thing) || s.thing === 'vibrancy') {
2918
4341
  // The palette mapping above sets these tokens.
2919
4342
  } else if (s.thing === 'font') {
@@ -3001,35 +4424,239 @@ export function compileTheme(ctx, data, base) {
3001
4424
  // The rungs scale the spacing the base theme starts from.
3002
4425
  /** @param {string} k @param {string} nv */
3003
4426
  const put = (k, nv) => {
3004
- if (parts.length) for (const t of parts) block(s, t)[k] = nv;
3005
- else putTok(k, nv);
4427
+ if (parts.length) {
4428
+ // An exact whole-theme or own-source token holds inside the
4429
+ // part too.
4430
+ if (!keptTokens(null).has(k))
4431
+ for (const t of parts) block(s, t)[k] = nv;
4432
+ } else putTok(k, nv);
3006
4433
  };
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`);
4434
+ // The spacing steps, in order around the exact steps the theme
4435
+ // keeps (a whole-theme one or the own source's: they win over the
4436
+ // dial).
4437
+ /** @type {Record<string, string>} */
4438
+ const dialVars = {};
4439
+ {
4440
+ /** @type {Array<[string, number]>} */
4441
+ const steps = [];
4442
+ for (const [k, core] of Object.entries(
4443
+ /** @type {Record<string, string>} */ (TOKENS),
4444
+ )) {
4445
+ const v = base.light[k] ?? core;
4446
+ if (/^--spacing-/.test(k) && /rem$/.test(v))
4447
+ steps.push([k, parseFloat(v) * 16]);
4448
+ }
4449
+ /** @type {Record<string, number>} */
4450
+ const keptSteps = {};
4451
+ for (const [k, v] of keptTokens(null))
4452
+ if (/^--spacing-/.test(k)) {
4453
+ const n = sizePx(v);
4454
+ if (n != null) keptSteps[k] = n;
4455
+ }
4456
+ /** @type {string[]} */
4457
+ const noRoom = [];
4458
+ for (const [k, n] of spacingSteps(steps, f, keptSteps, noRoom)) {
4459
+ const nv = `${Number((n / 16).toFixed(3))}rem`;
4460
+ dialVars[k] = k in keptSteps ? String(keptTokens(null).get(k)) : nv;
4461
+ if (!(k in keptSteps)) put(k, nv);
4462
+ }
4463
+ for (const k of noRoom)
4464
+ (ctx.sizeNotes ??= []).push(
4465
+ `${k} has no room between the exact spacing steps kept around it, so it takes the value of the one below it`,
4466
+ );
4467
+ }
4468
+ // An exact size the theme keeps (it wins over the dial) is a fixed
4469
+ // point the others stay in order around: a whole-theme one, one of
4470
+ // the theme's own source, and on a part the part's own, in any
4471
+ // unit that comes to a length (a spacing token through the value
4472
+ // this dial gives it). A whole-theme dial also keeps each part's
4473
+ // own exact sizes in order on that part.
4474
+ const sizeParts = parts.length
4475
+ ? parts
4476
+ : [
4477
+ null,
4478
+ ...new Set(
4479
+ data.settings
4480
+ .filter(
4481
+ x =>
4482
+ x.source === 'token' &&
4483
+ /^--size-element-/.test(x.thing) &&
4484
+ x.on &&
4485
+ !x.when &&
4486
+ !x.state,
4487
+ )
4488
+ .flatMap(x => partsOf(ctx, x)),
4489
+ ),
4490
+ ];
4491
+ for (const t of sizeParts) {
4492
+ /** @type {Record<string, number>} */
4493
+ const kept = {};
4494
+ for (const [k, v] of keptSizes(t)) {
4495
+ const n = sizePx(v, dialVars);
4496
+ if (n != null) kept[k] = n;
4497
+ }
4498
+ /** @type {string[]} */
4499
+ const noRoom = [];
4500
+ for (const [k, nv] of controlSizes(
4501
+ Object.keys(/** @type {Record<string, string>} */ (TOKENS))
4502
+ .filter(k => /^--size-element-/.test(k))
4503
+ .map(k => [k, base.light[k] ?? TOKENS[k]]),
4504
+ f,
4505
+ kept,
4506
+ noRoom,
4507
+ ))
4508
+ if (t) block(s, t)[k] = nv;
4509
+ else putTok(k, nv);
4510
+ for (const k of noRoom)
4511
+ (ctx.sizeNotes ??= []).push(
4512
+ `${k}${t ? ` on ${t}` : ''} has no room between the exact sizes kept around it, so it takes the size of the one below it`,
4513
+ );
4514
+ }
4515
+ // A variant's own exact size is kept in order on that variant too,
4516
+ // with the part's and the theme's kept sizes around it.
4517
+ /** @type {Map<string, {t: string, when: string}>} */
4518
+ const variantScopes = new Map();
4519
+ for (const x of data.settings)
4520
+ if (
4521
+ x.source === 'token' &&
4522
+ /^--size-element-/.test(x.thing) &&
4523
+ x.on &&
4524
+ x.when &&
4525
+ !x.state
4526
+ )
4527
+ for (const t of partsOf(ctx, x))
4528
+ if (!parts.length || parts.includes(t))
4529
+ variantScopes.set(`${t} ${x.when}`, {t, when: x.when});
4530
+ for (const {t, when} of variantScopes.values()) {
4531
+ /** @type {Record<string, number>} */
4532
+ const kept = {};
4533
+ for (const [k, v] of keptSizes(t)) {
4534
+ const n = sizePx(v, dialVars);
4535
+ if (n != null) kept[k] = n;
4536
+ }
4537
+ for (const x of data.settings)
4538
+ if (
4539
+ x.source === 'token' &&
4540
+ /^--size-element-/.test(x.thing) &&
4541
+ x.when === when &&
4542
+ !x.state &&
4543
+ partsOf(ctx, x).includes(t)
4544
+ ) {
4545
+ const n = sizePx(String(x.value), dialVars);
4546
+ if (n != null) kept[x.thing] = n;
4547
+ }
4548
+ /** @type {string[]} */
4549
+ const noRoom = [];
4550
+ for (const [k, nv] of controlSizes(
4551
+ Object.keys(/** @type {Record<string, string>} */ (TOKENS))
4552
+ .filter(k => /^--size-element-/.test(k))
4553
+ .map(k => [k, base.light[k] ?? TOKENS[k]]),
4554
+ f,
4555
+ kept,
4556
+ noRoom,
4557
+ ))
4558
+ block({...s, when}, t)[k] = nv;
4559
+ for (const k of noRoom)
4560
+ (ctx.sizeNotes ??= []).push(
4561
+ `${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`,
4562
+ );
3013
4563
  }
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
4564
  }
3022
4565
  } else if (s.source === 'token') {
3023
4566
  if (parts.length) for (const t of parts) putComp(s, t, s.thing, s.value);
3024
4567
  else putTok(s.thing, s.value, s.mode);
3025
4568
  } else if (s.source === 'property') {
3026
- for (const t of parts) {
4569
+ // A background on the whole app shell is the page background. The
4570
+ // shell's header and side nav paint the body or surface color over it
4571
+ // in every variant but section, and in an auto-height shell they are
4572
+ // sticky, so content must not show through them when it scrolls: they
4573
+ // take the same background. The main content area is made
4574
+ // see-through. A gradient is fixed to the viewport on the shell and on
4575
+ // those regions, so the regions line up with the page behind them. A
4576
+ // background a setting gives one of those regions itself is kept.
4577
+ /** @type {string[]} */
4578
+ const pageParts = [];
4579
+ if (
4580
+ parts.includes('app-shell') &&
4581
+ /^background(-color|-image)?$/.test(kebab(s.thing)) &&
4582
+ !s.when &&
4583
+ !s.state
4584
+ ) {
4585
+ /** @param {Record<string, any>} r */
4586
+ const ownBackground = r =>
4587
+ ['background', 'backgroundColor', 'backgroundImage'].some(
4588
+ k => k in r,
4589
+ );
4590
+ for (const region of ['app-shell-header', 'app-shell-sidenav'])
4591
+ if (
4592
+ ctx.project.target.has(region) &&
4593
+ !regionsWithOwnBackground.has(region)
4594
+ )
4595
+ pageParts.push(region);
4596
+ if (ctx.project.target.has('layout-content')) {
4597
+ const lc = ((theme.components['layout-content'] ??= {}).base ??= {});
4598
+ const main = (lc[':where(.astryx-app-shell [role="main"])'] ??= {});
4599
+ if (!ownBackground(main)) main.backgroundColor = 'transparent';
4600
+ }
4601
+ // Written after every setting (below), so no background shorthand
4602
+ // in the same rule resets it.
4603
+ if (/gradient\(/.test(String(s.value)))
4604
+ for (const t of ['app-shell', ...pageParts])
4605
+ fixedToViewport.push(block({...s, mode: undefined}, t));
4606
+ (ctx.compileNotes ??= []).push(
4607
+ "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",
4608
+ );
4609
+ }
4610
+ for (const t of [...parts, ...pageParts]) {
4611
+ // A heading takes its color from its color prop, which reads the
4612
+ // text color tokens after part styles: the color goes into those
4613
+ // tokens on the heading (a named color prop's own token for
4614
+ // --when color:<name>), so it shows there and nowhere else.
4615
+ if (t === 'heading' && kebab(s.thing) === 'color') {
4616
+ const named = /^color:([\w-]+)$/.exec(s.when ?? '')?.[1];
4617
+ const scope = named ? {...s, when: undefined} : s;
4618
+ for (const tok of named
4619
+ ? [`--color-text-${named}`]
4620
+ : ['--color-text-primary', '--color-text-secondary'])
4621
+ // A value naming one of these tokens (the secondary text color)
4622
+ // leaves that token as it is: it would read itself.
4623
+ if (!new RegExp(`var\\(\\s*${tok}\\s*[,)]`).test(String(s.value)))
4624
+ putComp(scope, t, tok, s.value);
4625
+ continue;
4626
+ }
3027
4627
  // A padding on a part whose box reads Core's padding variables is
3028
4628
  // resolved with the rest of that part's padding, below.
3029
4629
  if (padVars(t) && /^padding(-|$)/.test(kebab(s.thing))) {
3030
4630
  queuePadding(s, t);
3031
4631
  continue;
3032
4632
  }
4633
+ // A padding on a part without padding variables, where the own source
4634
+ // pads some sides of the same rule: the editor writes the other
4635
+ // sides only, each as it names it (physical stays physical), so the
4636
+ // own sides win; a side the own source holds in one direction only
4637
+ // is written for the other direction.
4638
+ if (/^padding(-|$)/.test(kebab(s.thing)) && !s.mode && !padVars(t)) {
4639
+ const own = ownBox(t, s);
4640
+ if (own.ltr.size || own.rtl.size) {
4641
+ for (const [x, v] of Object.entries(
4642
+ paddingSides(kebab(s.thing), String(s.value)),
4643
+ )) {
4644
+ const prop = camel(`padding-${x}`);
4645
+ const [inL, inR] = [
4646
+ own.ltr.has(boxSide(x, 'ltr')),
4647
+ own.rtl.has(boxSide(x, 'rtl')),
4648
+ ];
4649
+ if (inL && inR) continue;
4650
+ if (!inL && !inR) {
4651
+ putComp(s, t, prop, v);
4652
+ continue;
4653
+ }
4654
+ const [db, key] = dirBlock(s, t, inL ? ':dir(rtl)' : ':dir(ltr)');
4655
+ db[key] = {...(db[key] ?? {}), [prop]: v};
4656
+ }
4657
+ continue;
4658
+ }
4659
+ }
3033
4660
  const sides =
3034
4661
  wrappedPadding(t, s) ??
3035
4662
  containerSides(t, s) ??
@@ -3108,7 +4735,13 @@ export function compileTheme(ctx, data, base) {
3108
4735
  }
3109
4736
  }
3110
4737
  }
4738
+ drainingScoped = true;
4739
+ for (const write of scopedQueue) write();
3111
4740
  emitPadding();
4741
+ for (const r of fixedToViewport) {
4742
+ delete r.backgroundAttachment;
4743
+ r.backgroundAttachment = 'fixed';
4744
+ }
3112
4745
  orderBlocks();
3113
4746
  // Core gives headings the body font when a theme sets only the body's:
3114
4747
  // a font for the body alone keeps the base theme's heading font.
@@ -3162,7 +4795,16 @@ export function compileTheme(ctx, data, base) {
3162
4795
  for (const [k, {light, dark}] of Object.entries(tok)) {
3163
4796
  const l = light ?? base.light[k] ?? TOKENS[k];
3164
4797
  const d = dark ?? base.dark[k] ?? TOKENS[k];
3165
- theme.tokens[k] = l === d ? l : [l, d];
4798
+ // A pair only for a color: anything else (a shadow) is one value, the
4799
+ // one the theme's mode shows.
4800
+ theme.tokens[k] =
4801
+ l === d
4802
+ ? l
4803
+ : ctx.C.typeOf(k) === 'color' || isColorToken(k)
4804
+ ? [l, d]
4805
+ : modeOnly === 'dark'
4806
+ ? d
4807
+ : l;
3166
4808
  }
3167
4809
  // Base themes set the type tokens again for phones (a coarse pointer
3168
4810
  // below the lg width); an exact font family or weight, and the headings
@@ -3198,11 +4840,240 @@ export function compileTheme(ctx, data, base) {
3198
4840
  },
3199
4841
  ],
3200
4842
  };
4843
+ // A longhand set after a shorthand that covers it is the one in effect,
4844
+ // as the result says. The build merges these blocks over the base
4845
+ // theme's, and a key the base holds keeps the base's (earlier) place, so
4846
+ // such a longhand would come before the shorthand and lose: it is written
4847
+ // as its own sides instead, which the base does not hold.
4848
+ const baseBlocks =
4849
+ /** @type {{components?: Record<string, any>}} */ (base).components ?? {};
4850
+ for (const [target, keys] of Object.entries(theme.components ?? {}))
4851
+ for (const [key, b] of Object.entries(
4852
+ /** @type {Record<string, any>} */ (keys),
4853
+ ))
4854
+ laterLonghandsAsSides(b, baseBlocks[target]?.[key]);
3201
4855
  if (!Object.keys(theme.tokens).length) delete theme.tokens;
3202
4856
  if (!Object.keys(theme.components).length) delete theme.components;
3203
4857
  return theme;
3204
4858
  }
3205
4859
 
4860
+ /**
4861
+ * Whether shorthand `a` sets `b`, a logical side included: padding sets
4862
+ * padding-inline, border-color sets border-inline-start-color.
4863
+ * @param {string} a @param {string} b
4864
+ */
4865
+ function coversSide(a, b) {
4866
+ if (coversProperty(a, b)) return true;
4867
+ const root = b.replace(/-(inline|block)(-start|-end)?(?=-|$)/, '');
4868
+ return root !== b && (a === root || coversProperty(a, root));
4869
+ }
4870
+
4871
+ /**
4872
+ * A background's layers with each color painted in one mode only: a color
4873
+ * stop becomes light-dark(<color>, transparent) for light (the reverse for
4874
+ * dark), and a layer that is a color alone becomes a gradient of it, so
4875
+ * every layer is an image the other mode does not show.
4876
+ * @param {string} value
4877
+ * @param {'light' | 'dark'} mode
4878
+ * @returns {string[]}
4879
+ */
4880
+ export function maskLayers(value, mode) {
4881
+ /** @param {string} c */
4882
+ const wrap = c =>
4883
+ mode === 'light'
4884
+ ? `light-dark(${c}, transparent)`
4885
+ : `light-dark(transparent, ${c})`;
4886
+ /** @param {string} w */
4887
+ const isColor = w =>
4888
+ !/^light-dark\(/i.test(w) &&
4889
+ (isColorValue(w) || /^var\(\s*--color-/i.test(w));
4890
+ return splitTop(value, ',')
4891
+ .map(x => x.trim())
4892
+ .filter(Boolean)
4893
+ .map(layer => {
4894
+ const fn = /^((?:repeating-)?(?:linear|radial|conic)-gradient)\(/i.exec(
4895
+ layer,
4896
+ );
4897
+ if (!fn)
4898
+ return isColor(layer)
4899
+ ? `linear-gradient(${wrap(layer)}, ${wrap(layer)})`
4900
+ : layer;
4901
+ // The gradient's own arguments, up to its closing bracket; what
4902
+ // follows (position, size, repeat) stays as it is.
4903
+ let depth = 0;
4904
+ let end = fn[0].length - 1;
4905
+ for (let i = end; i < layer.length; i++) {
4906
+ if (layer[i] === '(') depth++;
4907
+ if (layer[i] === ')' && --depth === 0) {
4908
+ end = i;
4909
+ break;
4910
+ }
4911
+ }
4912
+ const args = splitTop(layer.slice(fn[0].length, end), ',').map(arg =>
4913
+ splitTop(arg.trim(), ' ')
4914
+ .map(w => (isColor(w.trim()) ? wrap(w.trim()) : w.trim()))
4915
+ .join(' '),
4916
+ );
4917
+ return `${fn[1]}(${args.join(', ')})${layer.slice(end + 1)}`;
4918
+ });
4919
+ }
4920
+
4921
+ /**
4922
+ * The part rules of a base theme that give a border radius of their own,
4923
+ * not a radius token: each as its part and the rule's --when (undefined
4924
+ * for the plain rule).
4925
+ * @param {{components?: Record<string, any>}} base
4926
+ * @returns {Array<[string, string | undefined]>}
4927
+ */
4928
+ function basePinnedRadii(base) {
4929
+ /** @type {Array<[string, string | undefined]>} */
4930
+ const out = [];
4931
+ for (const [t, rules] of Object.entries(base.components ?? {}))
4932
+ for (const [key, rule] of Object.entries(
4933
+ /** @type {Record<string, any>} */ (rules ?? {}),
4934
+ )) {
4935
+ if (key !== 'base' && !/^[\w-]+:[\w-]+$/.test(key)) continue;
4936
+ const r = rule?.borderRadius;
4937
+ if (typeof r === 'string' && !/var\(\s*--radius-/.test(r))
4938
+ out.push([t, key === 'base' ? undefined : key]);
4939
+ }
4940
+ return out;
4941
+ }
4942
+
4943
+ /**
4944
+ * A background shorthand split into its image layers and the color its
4945
+ * last layer may carry (the color under every image): a color word beside
4946
+ * the last image, or a last layer that is a color alone.
4947
+ * @param {string} value
4948
+ * @returns {{images: string, color: string | null}}
4949
+ */
4950
+ export function backgroundColorLayer(value) {
4951
+ const layers = splitTop(value, ',')
4952
+ .map(x => x.trim())
4953
+ .filter(Boolean);
4954
+ const last = layers.at(-1) ?? '';
4955
+ const words = splitTop(last, ' ').map(x => x.trim());
4956
+ const at = words.findIndex(
4957
+ w => !/gradient\(|url\(/i.test(w) && isColorValue(w),
4958
+ );
4959
+ if (at < 0) return {images: value, color: null};
4960
+ const rest = words.filter((_, i) => i !== at).join(' ');
4961
+ return {
4962
+ images: [...layers.slice(0, -1), ...(rest ? [rest] : [])].join(', '),
4963
+ color: words[at],
4964
+ };
4965
+ }
4966
+
4967
+ /**
4968
+ * A background layer's image (its gradient) and what follows it, as the
4969
+ * background longhands take them: position, size (after a slash) and
4970
+ * repeat.
4971
+ * @param {string} layer
4972
+ * @returns {{image: string, position: string, size: string, repeat: string}}
4973
+ */
4974
+ function layerParts(layer) {
4975
+ const fn = /^((?:repeating-)?(?:linear|radial|conic)-gradient)\(/i.exec(
4976
+ layer,
4977
+ );
4978
+ if (!fn) return {image: layer, position: '', size: '', repeat: ''};
4979
+ let depth = 0;
4980
+ let end = layer.length - 1;
4981
+ for (let i = fn[0].length - 1; i < layer.length; i++) {
4982
+ if (layer[i] === '(') depth++;
4983
+ if (layer[i] === ')' && --depth === 0) {
4984
+ end = i;
4985
+ break;
4986
+ }
4987
+ }
4988
+ const rest = splitTop(layer.slice(end + 1).trim(), ' ');
4989
+ const REPEAT = /^(repeat|no-repeat|repeat-x|repeat-y|space|round)$/i;
4990
+ const repeat = rest.filter(w => REPEAT.test(w)).join(' ');
4991
+ const words = rest.filter(w => !REPEAT.test(w)).join(' ');
4992
+ const [position = '', size = ''] = words.split('/').map(x => x.trim());
4993
+ return {image: layer.slice(0, end + 1), position, size, repeat};
4994
+ }
4995
+
4996
+ /** A side word in a longhand's name, in the order a box value lists sides. */
4997
+ const BOX_SIDES = ['top', 'right', 'bottom', 'left'];
4998
+
4999
+ /**
5000
+ * A block's longhands that follow a shorthand covering them, where the base
5001
+ * theme's block holds the same key, rewritten as that longhand's own sides
5002
+ * (padding-inline as padding-inline-start and -end, border-color as the
5003
+ * four side colors), in place and at the same position; a state's block
5004
+ * nested in it too. A longhand that is no side pair or box is kept.
5005
+ * @param {Record<string, any>} b
5006
+ * @param {Record<string, any> | undefined} baseBlock
5007
+ */
5008
+ function laterLonghandsAsSides(b, baseBlock) {
5009
+ if (
5010
+ !b ||
5011
+ typeof b !== 'object' ||
5012
+ !baseBlock ||
5013
+ typeof baseBlock !== 'object'
5014
+ )
5015
+ return;
5016
+ for (const [k, v] of Object.entries(b))
5017
+ if (k.startsWith(':') && v && typeof v === 'object')
5018
+ laterLonghandsAsSides(v, baseBlock[k]);
5019
+ const keys = Object.keys(b);
5020
+ /** @type {Record<string, any>} */
5021
+ const out = {};
5022
+ let changed = false;
5023
+ keys.forEach((k, i) => {
5024
+ const v = b[k];
5025
+ const css = kebab(k);
5026
+ const sides =
5027
+ typeof v === 'string' &&
5028
+ !k.startsWith('-') &&
5029
+ typeof baseBlock[k] === 'string' &&
5030
+ keys
5031
+ .slice(0, i)
5032
+ .some(e => !e.startsWith(':') && coversSide(kebab(e), css))
5033
+ ? sidesOf(css, v)
5034
+ : null;
5035
+ if (!sides) {
5036
+ out[k] = v;
5037
+ return;
5038
+ }
5039
+ changed = true;
5040
+ for (const [p, x] of Object.entries(sides)) {
5041
+ delete out[camel(p)];
5042
+ out[camel(p)] = x;
5043
+ }
5044
+ });
5045
+ if (!changed) return;
5046
+ for (const k of Object.keys(b)) delete b[k];
5047
+ Object.assign(b, out);
5048
+ }
5049
+
5050
+ /**
5051
+ * A two-sided (start/end) or four-sided (top/right/bottom/left) longhand's
5052
+ * value, as each side's property and value by the shorthand rules; null for
5053
+ * any other property.
5054
+ * @param {string} prop kebab-case
5055
+ * @param {string} v
5056
+ * @returns {Record<string, string> | null}
5057
+ */
5058
+ function sidesOf(prop, v) {
5059
+ const direct = [...longhandsOf(prop)].filter(p => longhandsOf(p).size === 0);
5060
+ const w = splitTop(v.trim(), ' ').map(x => x.trim());
5061
+ if (!w.length || /!important/i.test(v)) return null;
5062
+ const start = direct.find(p => /-start(-|$)/.test(p));
5063
+ const end = direct.find(p => /-end(-|$)/.test(p));
5064
+ if (direct.length === 2 && start && end && w.length <= 2)
5065
+ return {[start]: w[0], [end]: w[1] ?? w[0]};
5066
+ const named = BOX_SIDES.map(side =>
5067
+ direct.find(p => new RegExp(`-${side}(-|$)`).test(p)),
5068
+ );
5069
+ if (direct.length !== 4 || named.some(x => !x) || w.length > 4) return null;
5070
+ const [t, r = t, bo = t, l = r] = w;
5071
+ const vals = [t, r, bo, l];
5072
+ return Object.fromEntries(
5073
+ named.map((p, i) => [/** @type {string} */ (p), vals[i]]),
5074
+ );
5075
+ }
5076
+
3206
5077
  /** Core's default type scale ratio. */
3207
5078
  const STANDARD_RATIO = 1.2;
3208
5079
  /** The font-size tokens below the base, with their step on the scale. */
@@ -3314,10 +5185,10 @@ export function maskedSettings(data, ctx = null) {
3314
5185
  * {font-weight}`. Find those rules in the built stylesheet.
3315
5186
  * @param {string} cssText
3316
5187
  * @param {any} theme
3317
- * @returns {Array<{target: string, key: string, prop: string, value: string}>}
5188
+ * @returns {Array<{target: string, key: string, prop: string, value: string, state?: string}>}
3318
5189
  */
3319
5190
  export function findOverrides(cssText, theme) {
3320
- /** @type {Array<{target: string, key: string, prop: string, value: string}>} */
5191
+ /** @type {Array<{target: string, key: string, prop: string, value: string, state?: string}>} */
3321
5192
  const extra = [];
3322
5193
  for (const [target, keys] of Object.entries(
3323
5194
  /** @type {Record<string, any>} */ (theme.components ?? {}),
@@ -3362,6 +5233,51 @@ export function findOverrides(cssText, theme) {
3362
5233
  }
3363
5234
  }
3364
5235
  }
5236
+ // A state setting on the plain part (a whole-part hover) loses the same
5237
+ // way to a variant's own rule in that state: it is repeated there too.
5238
+ for (const [target, keys] of Object.entries(
5239
+ /** @type {Record<string, any>} */ (theme.components ?? {}),
5240
+ ))
5241
+ for (const [state, decl] of Object.entries(keys.base ?? {})) {
5242
+ if (!/^:[a-z-]+$/.test(state) || !decl || typeof decl !== 'object')
5243
+ continue;
5244
+ const props = Object.keys(decl).filter(
5245
+ p => !p.startsWith('--') && !p.startsWith(':'),
5246
+ );
5247
+ if (!props.length) continue;
5248
+ const re = new RegExp(
5249
+ `\\.astryx-${target.replace(/-/g, '\\-')}\\[data-([a-z-]+)="([^"]+)"\\](?:${state}(?![\\w-])[^{}]*|\\s*)\\{([^}]*)\\}`,
5250
+ 'g',
5251
+ );
5252
+ // The variant's own rule in that state, and its resting rule: that
5253
+ // one comes after the plain state rule at the same weight.
5254
+ const seen = new Set();
5255
+ for (const m of cssText.matchAll(re)) {
5256
+ const declared = [...m[3].matchAll(/(?:^|[;\s])([a-z-]+)\s*:/g)].map(
5257
+ d => d[1],
5258
+ );
5259
+ for (const prop of props) {
5260
+ const css = kebab(prop);
5261
+ if (css === m[1] || css.endsWith(`-${m[1]}`)) continue;
5262
+ if (
5263
+ !seen.has(`${m[1]}:${m[2]} ${prop}`) &&
5264
+ declared.some(
5265
+ d =>
5266
+ d === css || coversProperty(d, css) || coversProperty(css, d),
5267
+ )
5268
+ ) {
5269
+ seen.add(`${m[1]}:${m[2]} ${prop}`);
5270
+ extra.push({
5271
+ target,
5272
+ key: `${m[1]}:${m[2]}`,
5273
+ state,
5274
+ prop,
5275
+ value: decl[prop],
5276
+ });
5277
+ }
5278
+ }
5279
+ }
5280
+ }
3365
5281
  return extra;
3366
5282
  }
3367
5283
 
@@ -3384,8 +5300,43 @@ const liftValue = (lift, only) =>
3384
5300
  * @param {ThemeData} data
3385
5301
  * @param {any} theme
3386
5302
  * @param {import('./_palette.mjs').PaletteMapping | null} pal
5303
+ * @param {string} [cwd]
5304
+ * @param {Record<string, any> | null} [baseParts] the base theme's components, whose state objects each written one starts from
3387
5305
  */
3388
- function settingsSource(slug, data, theme, pal, cwd = '') {
5306
+ function settingsSource(slug, data, theme, pal, cwd = '', baseParts = null) {
5307
+ // Core merges a theme's state object (`:hover` in a rule) over the base
5308
+ // theme's whole, one level deep: each one starts as the base theme's own
5309
+ // for that rule, so the properties no setting names keep the base's.
5310
+ if (baseParts) {
5311
+ theme = {...theme, components: {...(theme.components ?? {})}};
5312
+ for (const [target, keys] of Object.entries(theme.components)) {
5313
+ /** @type {Record<string, any>} */
5314
+ const next = {};
5315
+ for (const [key, rule] of Object.entries(
5316
+ /** @type {Record<string, any>} */ (keys),
5317
+ )) {
5318
+ if (!rule || typeof rule !== 'object') {
5319
+ next[key] = rule;
5320
+ continue;
5321
+ }
5322
+ /** @type {Record<string, any>} */
5323
+ const r = {...rule};
5324
+ for (const [k, v] of Object.entries(rule)) {
5325
+ const own = baseParts[target]?.[key]?.[k];
5326
+ if (
5327
+ k.startsWith(':') &&
5328
+ v &&
5329
+ typeof v === 'object' &&
5330
+ own &&
5331
+ typeof own === 'object'
5332
+ )
5333
+ r[k] = {...own, ...v};
5334
+ }
5335
+ next[key] = r;
5336
+ }
5337
+ theme.components[target] = next;
5338
+ }
5339
+ }
3389
5340
  const like = data.like;
3390
5341
  const REF = '@@palette:';
3391
5342
  /** @param {string} family @param {'light' | 'dark'} m @param {import('./_palette.mjs').StopRef} r */
@@ -3717,13 +5668,28 @@ export function refuseThemeParse(cwd, slug) {
3717
5668
  */
3718
5669
  export function refuseThemeSource(cwd, slug) {
3719
5670
  refuseThemeParse(cwd, slug);
5671
+ const refusal = themeSourceRefusal(cwd, slug);
5672
+ if (refusal) throw refusal;
5673
+ }
5674
+
5675
+ /**
5676
+ * The refusal for a theme source that cannot carry the settings (it no
5677
+ * longer imports or extends them, or names another theme), naming the
5678
+ * lines that put it back; null when it carries them. Every command that
5679
+ * builds the theme refuses with it.
5680
+ * @param {string} cwd
5681
+ * @param {string} slug
5682
+ * @returns {AstryxError | null}
5683
+ */
5684
+ export function themeSourceRefusal(cwd, slug) {
3720
5685
  const why = themeSourceProblem(cwd, slug);
3721
- if (why)
3722
- throw new AstryxError(
3723
- `${why}, so settings cannot take effect. Put back the import of ${camel(slug)}Settings from './${slug}.settings', extends: ${camel(slug)}Settings and name: '${slug}' in themes/${slug}/${slug}.theme.ts (your own changes stay below them). Nothing was changed.`,
3724
- [{name: `${P} show ${slug}`, reason: 'see the theme as it is'}],
3725
- ERROR_CODES.ERR_THEME_INVALID,
3726
- );
5686
+ return why
5687
+ ? new AstryxError(
5688
+ `${why}, so settings cannot take effect. Put back the import of ${camel(slug)}Settings from './${slug}.settings', extends: ${camel(slug)}Settings and name: '${slug}' in themes/${slug}/${slug}.theme.ts (your own changes stay below them). Nothing was changed.`,
5689
+ [{name: `${P} show ${slug}`, reason: 'see the theme as it is'}],
5690
+ ERROR_CODES.ERR_THEME_INVALID,
5691
+ )
5692
+ : null;
3727
5693
  }
3728
5694
 
3729
5695
  /**
@@ -3806,6 +5772,146 @@ function refuseOwnPairs(ctx, cwd, slug) {
3806
5772
  * @returns {Promise<string[]>}
3807
5773
  */
3808
5774
  export async function builtPairs(ctx, slug) {
5775
+ const tops = await cacheBuild(ctx, slug, js => topTokensOf(js));
5776
+ return [...(tops ?? [])]
5777
+ .filter(
5778
+ ([k, v]) =>
5779
+ /^light-dark\(/.test(String(v ?? '')) && ctx.C.typeOf(k) !== 'color',
5780
+ )
5781
+ .map(([k]) => k);
5782
+ }
5783
+
5784
+ /**
5785
+ * The page-wide tokens the theme's own source gives, as a build made now
5786
+ * evaluates them (an imported module, an expression, a template): read
5787
+ * from a build into the project's cache folder, never beside the theme.
5788
+ * Null when it does not build there.
5789
+ * @param {Ctx} ctx
5790
+ * @param {string} slug
5791
+ * @returns {Promise<Map<string, string | null> | null>}
5792
+ */
5793
+ export async function evaluatedOwnTokens(ctx, slug) {
5794
+ return cacheBuild(ctx, slug, js => builtOwnTokens(ctx.project.cwd, slug, js));
5795
+ }
5796
+
5797
+ /**
5798
+ * What a build made now writes for a theme: its own page-wide tokens (see
5799
+ * builtOwnTokens), every top-level token, and the typography it was given
5800
+ * (evaluated: an import or an expression is its value). Null when it does
5801
+ * not build in the project's cache folder.
5802
+ * @param {Ctx} ctx
5803
+ * @param {string} slug
5804
+ * @returns {Promise<{own: Map<string, string | null>, tops: Map<string, string | null>, shapes: Map<string, BuiltShape>, typography: any} | null>}
5805
+ */
5806
+ export async function evaluatedTheme(ctx, slug) {
5807
+ return cacheBuild(ctx, slug, js => {
5808
+ const read = builtModule(js);
5809
+ return {
5810
+ own: builtOwnTokens(ctx.project.cwd, slug, js) ?? new Map(),
5811
+ tops: topTokensOf(js),
5812
+ shapes: read.shapes,
5813
+ typography: read.axes?.typography ?? null,
5814
+ };
5815
+ });
5816
+ }
5817
+
5818
+ /**
5819
+ * What a built module writes for a top-level token: text, a number, an
5820
+ * object, a pair (each half), or something else.
5821
+ * @typedef {{kind: 'text' | 'number' | 'object' | 'pair' | 'other', value?: any, halves?: unknown[]}} BuiltShape
5822
+ */
5823
+
5824
+ /**
5825
+ * What a built theme module holds: the shape of each top-level token, and
5826
+ * its `__axes` (the typography and motion it was given, evaluated).
5827
+ * @param {string} js
5828
+ * @returns {{shapes: Map<string, BuiltShape>, axes: any}}
5829
+ */
5830
+ function builtModule(js) {
5831
+ /** @type {Map<string, BuiltShape>} */
5832
+ const shapes = new Map();
5833
+ try {
5834
+ const ast = /** @type {any} */ (
5835
+ parseModule(fs.readFileSync(js, 'utf8'), {
5836
+ sourceType: 'module',
5837
+ plugins: ['typescript'],
5838
+ })
5839
+ );
5840
+ /** @param {any} n @returns {any} */
5841
+ const plain = n =>
5842
+ n?.type === 'StringLiteral' || n?.type === 'NumericLiteral'
5843
+ ? n.value
5844
+ : n?.type === 'UnaryExpression' && n.operator === '-'
5845
+ ? -plain(n.argument)
5846
+ : n?.type === 'NullLiteral'
5847
+ ? null
5848
+ : n?.type === 'ObjectExpression'
5849
+ ? Object.fromEntries(
5850
+ n.properties.map((/** @type {any} */ p) => [
5851
+ p.key?.value ?? p.key?.name,
5852
+ plain(p.value),
5853
+ ]),
5854
+ )
5855
+ : n?.type === 'ArrayExpression'
5856
+ ? n.elements.map(plain)
5857
+ : undefined;
5858
+ /** @type {any} */
5859
+ let axes = null;
5860
+ /** @type {any} */
5861
+ let tokens = null;
5862
+ /** @param {any} node @param {number} depth */
5863
+ const visit = (node, depth) => {
5864
+ if (!node || typeof node !== 'object') return;
5865
+ if (node.type === 'ObjectProperty') {
5866
+ const k = node.key?.name ?? node.key?.value;
5867
+ if (k === '__axes' && !axes) axes = plain(node.value);
5868
+ // The theme's own top-level tokens: the first `tokens` object.
5869
+ if (
5870
+ k === 'tokens' &&
5871
+ !tokens &&
5872
+ node.value?.type === 'ObjectExpression'
5873
+ )
5874
+ tokens = node.value;
5875
+ }
5876
+ for (const v of Object.values(node))
5877
+ if (Array.isArray(v)) v.forEach(c => visit(c, depth + 1));
5878
+ else if (v && typeof v === 'object' && v.type) visit(v, depth + 1);
5879
+ };
5880
+ visit(ast.program, 0);
5881
+ for (const p of tokens?.properties ?? []) {
5882
+ const k = p.key?.value ?? p.key?.name;
5883
+ if (typeof k !== 'string') continue;
5884
+ const v = p.value;
5885
+ shapes.set(
5886
+ k,
5887
+ v?.type === 'StringLiteral'
5888
+ ? {kind: 'text', value: v.value}
5889
+ : v?.type === 'NumericLiteral'
5890
+ ? {kind: 'number', value: v.value}
5891
+ : v?.type === 'ObjectExpression'
5892
+ ? {kind: 'object', value: plain(v)}
5893
+ : v?.type === 'ArrayExpression'
5894
+ ? {kind: 'pair', halves: plain(v)}
5895
+ : {kind: 'other'},
5896
+ );
5897
+ }
5898
+ return {shapes, axes};
5899
+ } catch {
5900
+ return {shapes, axes: null};
5901
+ }
5902
+ }
5903
+
5904
+ /**
5905
+ * Build the theme into the project's cache folder and read the built
5906
+ * module with `read` before the folder is removed; null when it does not
5907
+ * build there.
5908
+ * @template T
5909
+ * @param {Ctx} ctx
5910
+ * @param {string} slug
5911
+ * @param {(js: string) => T} read
5912
+ * @returns {Promise<T | null>}
5913
+ */
5914
+ async function cacheBuild(ctx, slug, read) {
3809
5915
  const {cwd} = ctx.project;
3810
5916
  const f = themeFiles(cwd, slug);
3811
5917
  // The build writes only inside the project: the cache folder when it is
@@ -3826,15 +5932,10 @@ export async function builtPairs(ctx, slug) {
3826
5932
  const js = fs
3827
5933
  .readdirSync(dir)
3828
5934
  .find(n => n.endsWith('.js') && !n.endsWith('.d.js'));
3829
- if (!js) return [];
3830
- return [...topTokensOf(path.join(dir, js))]
3831
- .filter(
3832
- ([k, v]) =>
3833
- /^light-dark\(/.test(String(v ?? '')) && ctx.C.typeOf(k) !== 'color',
3834
- )
3835
- .map(([k]) => k);
5935
+ if (!js) return null;
5936
+ return read(path.join(dir, js));
3836
5937
  } catch {
3837
- return [];
5938
+ return null;
3838
5939
  } finally {
3839
5940
  logger.setSilent(silent);
3840
5941
  fs.rmSync(dir, {recursive: true, force: true});
@@ -3933,7 +6034,17 @@ export async function buildTheme(ctx, slug, data) {
3933
6034
  ctx.keepStops,
3934
6035
  );
3935
6036
  await step(() => {
3936
- writeWhole(f.settingsTs, settingsSource(slug, data, theme, pal, cwd));
6037
+ writeWhole(
6038
+ f.settingsTs,
6039
+ settingsSource(
6040
+ slug,
6041
+ data,
6042
+ theme,
6043
+ pal,
6044
+ cwd,
6045
+ /** @type {any} */ (base).components ?? null,
6046
+ ),
6047
+ );
3937
6048
  syncPaletteRefs(cwd, slug, fs.readFileSync(f.settingsTs, 'utf8'), pal);
3938
6049
  if (!fs.existsSync(f.ts)) writeWhole(f.ts, themeModuleSource(slug));
3939
6050
  });
@@ -3949,7 +6060,7 @@ export async function buildTheme(ctx, slug, data) {
3949
6060
  .filter(
3950
6061
  n =>
3951
6062
  /^(sheet|preview)(-[a-z-]+)?\.png$/.test(n) &&
3952
- editorWrote(cwd, slug, path.join(f.dir, n)),
6063
+ editorRecorded(cwd, slug, path.join(f.dir, n)),
3953
6064
  )
3954
6065
  : [];
3955
6066
  for (const file of [
@@ -3959,9 +6070,47 @@ export async function buildTheme(ctx, slug, data) {
3959
6070
  fs.rmSync(file, {force: true});
3960
6071
  forgetWritten(cwd, slug, pictures);
3961
6072
  });
3962
- let receipt = await step(() => runBuild(ctx, slug));
6073
+ let receipt = await step(() => runBuild(ctx, slug, data));
6074
+ // A state setting on the plain part that the own source's same state
6075
+ // rule wins over is not repeated on the variants either: the own source
6076
+ // wins on every variant, as the result says.
6077
+ /** @type {Map<string, Map<string, string | null>>} */
6078
+ const ownStates = new Map();
6079
+ /** @param {string} target @param {string} state @param {string} prop */
6080
+ const ownHolds = (target, state, prop) => {
6081
+ const k = `${target} ${state}`;
6082
+ const own =
6083
+ ownStates.get(k) ?? ownPartTokens(cwd, slug, target, 'base', state);
6084
+ ownStates.set(k, own);
6085
+ const css = kebab(prop);
6086
+ return [...own.keys()].some(
6087
+ o => o === css || coversProperty(o, css) || coversProperty(css, o),
6088
+ );
6089
+ };
3963
6090
  const found = findOverrides(fs.readFileSync(f.css, 'utf8'), theme).filter(
3964
- x => !(theme.components[x.target][x.key] ?? {})[x.prop],
6091
+ x =>
6092
+ // By property: a variant whose rule the settings give this property
6093
+ // or a shorthand covering it needs no copy; nor one holding a
6094
+ // longhand of it that the base theme's rule also holds and that has
6095
+ // no sides to be written as (a background color, one-mode or not):
6096
+ // the copy would come after it there and win. Any other longhand
6097
+ // takes the copy, then is written after it (as its sides where the
6098
+ // base holds it).
6099
+ !Object.entries(
6100
+ (x.state
6101
+ ? theme.components[x.target][x.key]?.[x.state]
6102
+ : theme.components[x.target][x.key]) ?? {},
6103
+ ).some(([k, v]) => {
6104
+ if (k.startsWith(':')) return false;
6105
+ if (k === x.prop || coversProperty(kebab(k), kebab(x.prop)))
6106
+ return true;
6107
+ if (!coversProperty(kebab(x.prop), kebab(k))) return false;
6108
+ const baseRule = /** @type {any} */ (base).components?.[x.target]?.[
6109
+ x.key
6110
+ ];
6111
+ const held = (x.state ? baseRule?.[x.state] : baseRule)?.[k];
6112
+ return held != null && sidesOf(kebab(k), String(v)) == null;
6113
+ }) && !(x.state && ownHolds(x.target, x.state, x.prop)),
3965
6114
  );
3966
6115
  /** @type {string[]} */
3967
6116
  const lifted = [];
@@ -3972,19 +6121,42 @@ export async function buildTheme(ctx, slug, data) {
3972
6121
  // longhand or shorthand the variant sets itself (border-color after
3973
6122
  // a base border) still wins over it.
3974
6123
  const own = t[x.key] ?? {};
6124
+ const ownState = x.state ? (own[x.state] ?? {}) : own;
3975
6125
  // A variant that sets every longhand of the property itself needs
3976
6126
  // none of the base value (and a lifted radius would feed Core's copy
3977
6127
  // of it into the content's radius, after the variant's own).
3978
6128
  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)}`);
6129
+ if (longs.length && longs.every(l => camel(l) in ownState)) continue;
6130
+ t[x.key] = x.state
6131
+ ? {...own, [x.state]: {[x.prop]: x.value, ...ownState}}
6132
+ : {[x.prop]: x.value, ...own};
6133
+ // The variant's own longhands come after the copied shorthand; one
6134
+ // the base theme holds would keep the base's earlier place and lose,
6135
+ // so it is written as its sides.
6136
+ const baseRule = /** @type {any} */ (base).components?.[x.target]?.[
6137
+ x.key
6138
+ ];
6139
+ laterLonghandsAsSides(
6140
+ x.state ? t[x.key][x.state] : t[x.key],
6141
+ x.state ? baseRule?.[x.state] : baseRule,
6142
+ );
6143
+ lifted.push(`${x.target} ${x.key}${x.state ?? ''} ${kebab(x.prop)}`);
3982
6144
  }
3983
6145
  await step(() => {
3984
- writeWhole(f.settingsTs, settingsSource(slug, data, theme, pal, cwd));
6146
+ writeWhole(
6147
+ f.settingsTs,
6148
+ settingsSource(
6149
+ slug,
6150
+ data,
6151
+ theme,
6152
+ pal,
6153
+ cwd,
6154
+ /** @type {any} */ (base).components ?? null,
6155
+ ),
6156
+ );
3985
6157
  syncPaletteRefs(cwd, slug, fs.readFileSync(f.settingsTs, 'utf8'), pal);
3986
6158
  });
3987
- receipt = await step(() => runBuild(ctx, slug));
6159
+ receipt = await step(() => runBuild(ctx, slug, data));
3988
6160
  }
3989
6161
  for (const out of [f.css, f.js])
3990
6162
  if (fs.existsSync(out))
@@ -4005,8 +6177,34 @@ export async function buildTheme(ctx, slug, data) {
4005
6177
  return {warnings, lifted, notes};
4006
6178
  }
4007
6179
 
4008
- /** @param {Ctx} ctx @param {string} slug @returns {Promise<any>} */
4009
- async function runBuild(ctx, slug) {
6180
+ /**
6181
+ * The one color mode of a light-only or dark-only theme, from its settings,
6182
+ * for the build to write into the built module (`colorModes`); null for a
6183
+ * theme with both modes.
6184
+ * @param {string} cwd
6185
+ * @param {string} slug
6186
+ * @returns {['light'] | ['dark'] | null}
6187
+ */
6188
+ export function buildColorModes(cwd, slug) {
6189
+ try {
6190
+ return oneColorMode(
6191
+ modesOf(
6192
+ JSON.parse(fs.readFileSync(themeFiles(cwd, slug).settings, 'utf8')),
6193
+ ),
6194
+ );
6195
+ } catch {
6196
+ return null;
6197
+ }
6198
+ }
6199
+
6200
+ /**
6201
+ * @param {Ctx} ctx
6202
+ * @param {string} slug
6203
+ * @param {{mode?: string}} [data] the settings being built (saved after the
6204
+ * build), whose mode the built module exports
6205
+ * @returns {Promise<any>}
6206
+ */
6207
+ async function runBuild(ctx, slug, data) {
4010
6208
  const {cwd} = ctx.project;
4011
6209
  const f = themeFiles(cwd, slug);
4012
6210
  const silent = logger.silent;
@@ -4020,6 +6218,11 @@ async function runBuild(ctx, slug) {
4020
6218
  {},
4021
6219
  {cwd},
4022
6220
  {compact: true},
6221
+ {
6222
+ colorModes: data
6223
+ ? oneColorMode(modesOf(data))
6224
+ : buildColorModes(cwd, slug),
6225
+ },
4023
6226
  );
4024
6227
  return receipt;
4025
6228
  } finally {
@@ -4046,6 +6249,7 @@ export async function outputsDrift(ctx, slug) {
4046
6249
  {check: true},
4047
6250
  {cwd},
4048
6251
  {compact: true},
6252
+ {colorModes: buildColorModes(cwd, slug)},
4049
6253
  );
4050
6254
  const first = /** @type {any} */ (receipt)?.data?.stale?.[0];
4051
6255
  if (!first) return null;
@@ -4227,7 +6431,7 @@ function nonTextToken(t, typeOf = (/** @type {string} */ _k) => 'other') {
4227
6431
  * @param {string} slug
4228
6432
  * @param {[string, unknown, ('object' | 'pair' | 'unit' | 'value' | 'mode')?]} bad
4229
6433
  */
4230
- function nonTextMessage(ctx, slug, [name, value, kind = 'value']) {
6434
+ export function nonTextMessage(ctx, slug, [name, value, kind = 'value']) {
4231
6435
  const type = ctx.C.typeOf(name);
4232
6436
  if (kind === 'mode') return ownPairMessage(slug, [name]);
4233
6437
  if (kind === 'object')
@@ -4452,8 +6656,26 @@ function parseSettings(text) {
4452
6656
  }
4453
6657
 
4454
6658
  /**
4455
- * Whether parsed settings have the shape the editor reads: an object with a
4456
- * list of settings.
6659
+ * Whether every settings entry has the parts the editor reads (a thing, a
6660
+ * value and a source); one without is damage `new` keeps aside.
6661
+ * @param {any} data
6662
+ */
6663
+ export function settingsEntriesOk(data) {
6664
+ return (
6665
+ settingsShapeOk(data) &&
6666
+ data.settings.every(
6667
+ (/** @type {any} */ s) =>
6668
+ s &&
6669
+ typeof s.thing === 'string' &&
6670
+ 'value' in s &&
6671
+ ['dial', 'token', 'property'].includes(s.source),
6672
+ )
6673
+ );
6674
+ }
6675
+
6676
+ /**
6677
+ * Whether settings data has the shape the editor reads: an object with a
6678
+ * settings list.
4457
6679
  * @param {any} data
4458
6680
  */
4459
6681
  export function settingsShapeOk(data) {
@@ -4465,6 +6687,23 @@ export function settingsShapeOk(data) {
4465
6687
  );
4466
6688
  }
4467
6689
 
6690
+ /**
6691
+ * The settings as the file keeps them: a setting's `note` is what the
6692
+ * command that made it says in its result, not part of the setting.
6693
+ * @param {ThemeData} data
6694
+ * @returns {ThemeData}
6695
+ */
6696
+ function savedForm(data) {
6697
+ return {
6698
+ ...data,
6699
+ settings: data.settings.map(s => {
6700
+ const entry = {...s};
6701
+ delete entry.note;
6702
+ return entry;
6703
+ }),
6704
+ };
6705
+ }
6706
+
4468
6707
  /**
4469
6708
  * Every regular file under `dir` and the hash of its bytes; empty when
4470
6709
  * there is no folder.
@@ -5067,6 +7306,21 @@ export function builtFiles(cwd, slug, data, some = false) {
5067
7306
  ];
5068
7307
  }
5069
7308
 
7309
+ /**
7310
+ * The file's stat, or undefined when it is not there. On Node 22.13 a folder
7311
+ * above the file that is a file throws ENOTDIR even with throwIfNoEntry
7312
+ * false; that file is not there either, as on later Node.
7313
+ * @param {string} file
7314
+ */
7315
+ function statIfThere(file) {
7316
+ try {
7317
+ return fs.statSync(file, {throwIfNoEntry: false});
7318
+ } catch (e) {
7319
+ if (/** @type {any} */ (e)?.code === 'ENOTDIR') return undefined;
7320
+ throw e;
7321
+ }
7322
+ }
7323
+
5070
7324
  /**
5071
7325
  * Refuse, by name, a built file that is there but cannot be read: its
5072
7326
  * permissions, or a folder where the file goes.
@@ -5075,7 +7329,7 @@ export function builtFiles(cwd, slug, data, some = false) {
5075
7329
  */
5076
7330
  function refuseUnreadable(cwd, files) {
5077
7331
  for (const file of files) {
5078
- const st = fs.statSync(file, {throwIfNoEntry: false});
7332
+ const st = statIfThere(file);
5079
7333
  if (!st) continue;
5080
7334
  const rel = shown(cwd, file);
5081
7335
  if (st.isDirectory())
@@ -5225,8 +7479,8 @@ export async function commitTheme(
5225
7479
  // no undo step.
5226
7480
  const same = (/** @type {ThemeData | null} */ a) =>
5227
7481
  a != null &&
5228
- JSON.stringify({...a, lifted: undefined}) ===
5229
- JSON.stringify({...data, lifted: undefined});
7482
+ JSON.stringify({...savedForm(a), lifted: undefined}) ===
7483
+ JSON.stringify({...savedForm(data), lifted: undefined});
5230
7484
  // A no-op change still mends a build that does not match the settings
5231
7485
  // (an undo stopped part way): it is built again, with no new step.
5232
7486
  const noop = history && same(parseSettings(snapBefore));
@@ -5361,7 +7615,7 @@ export async function commitTheme(
5361
7615
  // for an undo, a top step equal to the settings, which undo skips),
5362
7616
  // never a step that undoes nothing or a lost step.
5363
7617
  await track(f.dir, wrote, () => {
5364
- writeWhole(f.settings, `${JSON.stringify(data, null, 2)}\n`);
7618
+ writeWhole(f.settings, `${JSON.stringify(savedForm(data), null, 2)}\n`);
5365
7619
  if (historyAfter)
5366
7620
  writeWhole(
5367
7621
  f.history,
@@ -5536,6 +7790,20 @@ export async function commitTheme(
5536
7790
  };
5537
7791
  }
5538
7792
 
7793
+ /**
7794
+ * The @fontsource package named for a font family (`Open Sans` is
7795
+ * `@fontsource/open-sans`).
7796
+ * @param {string} family
7797
+ * @returns {string}
7798
+ */
7799
+ export function fontsourcePackageOf(family) {
7800
+ return `@fontsource/${String(family)
7801
+ .replace(/["']/g, '')
7802
+ .trim()
7803
+ .toLowerCase()
7804
+ .replace(/\s+/g, '-')}`;
7805
+ }
7806
+
5539
7807
  /** @param {Ctx} ctx @param {ThemeData} data */
5540
7808
  export function fontPackages(ctx, data) {
5541
7809
  /** @type {Array<{pkg: string, family: string, installed: boolean, of: Setting}>} */
@@ -5555,7 +7823,7 @@ export function fontPackages(ctx, data) {
5555
7823
  const name = family.replace(/["']/g, '');
5556
7824
  // An installed @fontsource package of the family always loads it, even
5557
7825
  // for a family some systems ship.
5558
- const own = `@fontsource/${name.toLowerCase().replace(/\s+/g, '-')}`;
7826
+ const own = fontsourcePackageOf(name);
5559
7827
  const pkg = known ?? (isInstalled(own) ? own : null);
5560
7828
  if (!pkg || out.some(x => x.pkg === pkg)) continue;
5561
7829
  out.push({pkg, family: name, installed: isInstalled(pkg), of: s});