@astryxdesign/cli 0.7.16 → 0.7.17-canary.g49a475f

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 (354) 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.d.mts +4 -2
  13. package/api/build/kit/rank.mjs +125 -24
  14. package/api/build/kit/start.d.mts +5 -4
  15. package/api/build/kit/start.mjs +12 -8
  16. package/api/build/kit/weights.d.mts +39 -3
  17. package/api/build/kit/weights.json +1 -1
  18. package/api/build/kit/weights.mjs +340 -43
  19. package/api/build/kit/word-model.d.mts +23 -0
  20. package/api/build/kit/word-model.mjs +46 -0
  21. package/api/build/kit/words.d.mts +48 -0
  22. package/api/build/kit/words.mjs +90 -1
  23. package/api/component/__fixtures__/resolutions/modules.txt +4 -5
  24. package/api/component/list/list.d.mts +1 -1
  25. package/api/component/list/list.mjs +48 -6
  26. package/api/discover/_adapter.d.mts +1 -1
  27. package/api/discover/search/search.mjs +3 -2
  28. package/api/docs/_adapter.d.mts +26 -2
  29. package/api/docs/_adapter.mjs +219 -6
  30. package/api/docs/docs.d.mts +3 -0
  31. package/api/docs/docs.doc.mjs +7 -1
  32. package/api/docs/docs.mjs +12 -0
  33. package/api/docs/docs.type.d.mts +5 -0
  34. package/api/docs/docs.type.mjs +2 -0
  35. package/api/docs/node/node.mjs +1 -1
  36. package/api/doctor/_adapter.d.mts +27 -5
  37. package/api/doctor/_adapter.mjs +83 -10
  38. package/api/doctor/built-checks.mjs +40 -14
  39. package/api/doctor/doctor.d.mts +4 -3
  40. package/api/doctor/doctor.mjs +14 -7
  41. package/api/doctor/theme-checks.mjs +121 -17
  42. package/api/icon/_records.mjs +2 -1
  43. package/api/index.d.mts +2 -0
  44. package/api/index.mjs +2 -0
  45. package/api/integration/_adapter.d.mts +44 -0
  46. package/api/integration/_adapter.mjs +77 -1
  47. package/api/integration/authoring-checks.mjs +6 -6
  48. package/api/integration/example-scope.d.mts +14 -0
  49. package/api/integration/example-scope.mjs +44 -0
  50. package/api/integration/example-scope.type.d.mts +29 -0
  51. package/api/integration/example-scope.type.mjs +25 -0
  52. package/api/integration/integrationExampleScope.doc.d.mts +11 -0
  53. package/api/integration/integrationExampleScope.doc.mjs +59 -0
  54. package/api/integration/validate-integration.mjs +19 -1
  55. package/api/integration/validate-integration.type.d.mts +9 -0
  56. package/api/integration/validate-integration.type.mjs +1 -1
  57. package/api/integration/validateIntegration.doc.mjs +1 -1
  58. package/api/render/_adapter.mjs +591 -195
  59. package/api/render/render.doc.mjs +11 -3
  60. package/api/render/render.type.d.mts +52 -0
  61. package/api/render/render.type.mjs +31 -1
  62. package/api/search/ORDERING.md +1 -1
  63. package/api/search/_adapter.d.mts +9 -0
  64. package/api/search/_adapter.mjs +85 -0
  65. package/api/search/_candidate-score.mjs +51 -32
  66. package/api/search/_fit-order.mjs +3 -3
  67. package/api/search/_gather-components.d.mts +3 -2
  68. package/api/search/_gather-components.mjs +12 -3
  69. package/api/search/_lexical.d.mts +5 -0
  70. package/api/search/_lexical.mjs +8 -2
  71. package/api/search/_result.d.mts +11 -9
  72. package/api/search/_result.mjs +4 -4
  73. package/api/search/_score.d.mts +6 -1
  74. package/api/search/_score.mjs +15 -3
  75. package/api/search/search-index.mjs +7 -1
  76. package/api/search/search.d.mts +1 -1
  77. package/api/theme/_adapter.mjs +12 -1
  78. package/api/theme/build/build.d.mts +75 -0
  79. package/api/theme/build/build.mjs +243 -58
  80. package/api/theme/build/font-warning.d.mts +7 -0
  81. package/api/theme/build/font-warning.mjs +17 -0
  82. package/api/theme/theme.type.d.mts +10 -0
  83. package/api/theme/theme.type.mjs +7 -1
  84. package/api/theme-edit/_adapter.d.mts +63 -2
  85. package/api/theme-edit/_adapter.mjs +771 -57
  86. package/api/theme-edit/_check.d.mts +40 -22
  87. package/api/theme-edit/_check.mjs +2029 -336
  88. package/api/theme-edit/_color.d.mts +10 -0
  89. package/api/theme-edit/_color.mjs +49 -1
  90. package/api/theme-edit/_compiler.mjs +9 -0
  91. package/api/theme-edit/_context.d.mts +3 -3
  92. package/api/theme-edit/_context.mjs +111 -48
  93. package/api/theme-edit/_css.d.mts +14 -0
  94. package/api/theme-edit/_css.mjs +46 -1
  95. package/api/theme-edit/_edit.d.mts +18 -4
  96. package/api/theme-edit/_edit.mjs +1685 -155
  97. package/api/theme-edit/_how-commands.d.mts +65 -0
  98. package/api/theme-edit/_how-commands.mjs +633 -1
  99. package/api/theme-edit/_how-question.d.mts +84 -0
  100. package/api/theme-edit/_how-question.mjs +5124 -281
  101. package/api/theme-edit/_how.mjs +140 -29
  102. package/api/theme-edit/_marks.d.mts +31 -5
  103. package/api/theme-edit/_marks.mjs +57 -5
  104. package/api/theme-edit/_name-rule.d.mts +11 -0
  105. package/api/theme-edit/_name-rule.mjs +12 -0
  106. package/api/theme-edit/_normal.d.mts +257 -0
  107. package/api/theme-edit/_normal.mjs +1252 -0
  108. package/api/theme-edit/_palette.mjs +10 -4
  109. package/api/theme-edit/_parts.d.mts +10 -1
  110. package/api/theme-edit/_parts.mjs +179 -3
  111. package/api/theme-edit/_preview-app.d.mts +7 -1
  112. package/api/theme-edit/_preview-app.mjs +515 -148
  113. package/api/theme-edit/_preview.d.mts +100 -14
  114. package/api/theme-edit/_preview.mjs +549 -137
  115. package/api/theme-edit/_settings.d.mts +347 -30
  116. package/api/theme-edit/_settings.mjs +2971 -327
  117. package/api/theme-edit/_tables.d.mts +6 -0
  118. package/api/theme-edit/_tables.mjs +44 -1
  119. package/api/theme-edit/_vet.d.mts +18 -0
  120. package/api/theme-edit/_vet.mjs +32 -0
  121. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  122. package/api/theme-edit/theme-edit.type.mjs +4 -1
  123. package/api/theme-edit/themeEditHow.doc.mjs +1 -1
  124. package/api/theme-edit/themeEditNew.doc.d.mts +0 -1
  125. package/api/theme-edit/themeEditNew.doc.mjs +7 -4
  126. package/api/theme-edit/themeEditPreviewApp.doc.mjs +3 -3
  127. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +2 -2
  128. package/api/upgrade/run/run.mjs +4 -3
  129. package/assets/codemods/integration-discovery.mjs +2 -1
  130. package/assets/codemods/run-codemod.mjs +87 -7
  131. package/assets/codemods/transforms/next/index.mjs +11 -1
  132. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  133. package/assets/component-list.generated.json +1 -0
  134. package/assets/docs/author-a-theme.doc.mjs +1 -0
  135. package/assets/docs/theme.doc.dense.mjs +2 -2
  136. package/assets/docs/theme.doc.mjs +1 -1
  137. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  138. package/assets/docs/tree/checks.doc.mjs +1 -1
  139. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  140. package/assets/docs/tree/render-pages.doc.mjs +44 -3
  141. package/assets/docs/tree/single-component.doc.mjs +4 -0
  142. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  143. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  144. package/assets/docs/use-a-theme.doc.mjs +1 -1
  145. package/assets/docs.generated.json +2 -2
  146. package/assets/search-catalog.generated.json +2 -0
  147. package/assets/self-audit.generated.json +1 -1
  148. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  149. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  150. package/assets/templates/blocks/components/Hooks/useContainerRevealHookUsage.tsx +2 -2
  151. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  152. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  153. package/assets/templates/components.generated.json +1 -1
  154. package/assets/templates/pages/ai-chat/template.doc.mjs +5 -4
  155. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +2 -1
  156. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  157. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  158. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  159. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  160. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  161. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  162. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  163. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  164. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  165. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  166. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  167. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  168. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  169. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  170. package/assets/templates/pages/editor/template.doc.mjs +2 -8
  171. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  172. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  173. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  174. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  175. package/assets/templates/pages/ide/page.tsx +24 -2
  176. package/assets/templates/pages/kanban-board/template.doc.mjs +1 -9
  177. package/assets/templates/pages/library/template.doc.mjs +4 -1
  178. package/assets/templates/pages/login/template.doc.mjs +2 -1
  179. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  180. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  181. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  182. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  183. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  184. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  185. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  186. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  187. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  188. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  189. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  190. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  191. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  192. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  193. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  194. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  195. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -9
  196. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  197. package/assets/theme.template.ts +6 -0
  198. package/authoring/debug/parse.d.mts +3 -3
  199. package/authoring/doctypes/_schema.d.mts +3 -3
  200. package/authoring/doctypes/command/command.doc.mjs +1 -1
  201. package/authoring/doctypes/component/categories.d.mts +37 -0
  202. package/authoring/doctypes/component/categories.mjs +54 -0
  203. package/authoring/doctypes/template/template.doc.mjs +1 -1
  204. package/authoring/doctypes/template/type.ts +9 -0
  205. package/authoring/example/example.doc.d.mts +12 -0
  206. package/authoring/example/example.doc.mjs +69 -0
  207. package/authoring/example/preview.d.mts +92 -0
  208. package/authoring/example/preview.mjs +994 -0
  209. package/authoring/example/type.ts +102 -0
  210. package/authoring/index.d.mts +1 -0
  211. package/authoring/index.d.ts +12 -0
  212. package/authoring/index.mjs +3 -1
  213. package/clients/cli/bin/astryx.mjs +6 -9
  214. package/clients/cli/build-id.generated.json +1 -1
  215. package/clients/cli/commands/component.doc.mjs +1 -1
  216. package/clients/cli/commands/component.mjs +22 -3
  217. package/clients/cli/commands/docs.doc.mjs +7 -1
  218. package/clients/cli/commands/docs.mjs +3 -1
  219. package/clients/cli/commands/doctor.mjs +32 -14
  220. package/clients/cli/commands/experimental/render.mjs +42 -1
  221. package/clients/cli/commands/experimental/theme.mjs +163 -28
  222. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  223. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  224. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +87 -1
  225. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +10 -3
  226. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -1
  227. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  228. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  229. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  230. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  231. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  232. package/clients/cli/commands/experimental-theme-preview.doc.mjs +2 -1
  233. package/clients/cli/commands/experimental-theme.doc.mjs +5 -1
  234. package/clients/cli/commands/search.doc.mjs +2 -1
  235. package/clients/cli/commands/search.mjs +6 -1
  236. package/clients/cli/commands/template.mjs +4 -2
  237. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  238. package/clients/cli/commands/theme.doc.mjs +1 -1
  239. package/clients/cli/commands/theme.mjs +209 -8
  240. package/clients/cli/commands/upgrade.mjs +42 -7
  241. package/clients/cli/index.mjs +1 -1
  242. package/clients/cli/lib/cli-error.mjs +2 -1
  243. package/clients/cli/lib/component-format.mjs +205 -98
  244. package/clients/cli/lib/hook-format.mjs +9 -19
  245. package/clients/cli/lib/json-shim.mjs +77 -21
  246. package/clients/cli/lib/manifest.mjs +3 -2
  247. package/clients/cli/manifest.generated.json +1 -1
  248. package/foundation/agent-docs/agent-docs.mjs +1 -1
  249. package/foundation/config/theme-state.d.mts +13 -1
  250. package/foundation/config/theme-state.mjs +47 -7
  251. package/foundation/discovery/authoring-self-docs.mjs +1 -0
  252. package/foundation/discovery/component-discovery.d.mts +11 -0
  253. package/foundation/discovery/component-discovery.mjs +56 -8
  254. package/foundation/discovery/component-replacement.mjs +130 -1
  255. package/foundation/discovery/copied-passages.mjs +2 -1
  256. package/foundation/discovery/doc-types.mjs +4 -3
  257. package/foundation/discovery/entry-name-files.d.mts +43 -0
  258. package/foundation/discovery/entry-name-files.mjs +264 -0
  259. package/foundation/discovery/hook-discovery.d.mts +8 -2
  260. package/foundation/discovery/hook-discovery.mjs +22 -8
  261. package/foundation/discovery/icon-definition-discovery.mjs +2 -1
  262. package/foundation/discovery/icon-set-checks.mjs +2 -1
  263. package/foundation/discovery/icon-set-discovery.mjs +2 -1
  264. package/foundation/discovery/integration-doc-files.mjs +2 -1
  265. package/foundation/discovery/package-exports.d.mts +10 -0
  266. package/foundation/discovery/package-exports.mjs +56 -3
  267. package/foundation/discovery/prop-drift.mjs +9 -9
  268. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  269. package/foundation/discovery/runner-allowlist.mjs +2 -0
  270. package/foundation/discovery/stored-component-list.d.mts +43 -0
  271. package/foundation/discovery/stored-component-list.mjs +90 -0
  272. package/foundation/discovery/stored-search-catalog.d.mts +115 -0
  273. package/foundation/discovery/stored-search-catalog.mjs +297 -0
  274. package/foundation/discovery/stored-self-audit.d.mts +26 -10
  275. package/foundation/discovery/stored-self-audit.mjs +38 -18
  276. package/foundation/discovery/template-adapter.d.mts +52 -0
  277. package/foundation/discovery/template-adapter.mjs +176 -12
  278. package/foundation/discovery/template-icons.mjs +2 -1
  279. package/foundation/discovery/theme-discovery.mjs +3 -2
  280. package/foundation/discovery/theme-imports.d.mts +14 -0
  281. package/foundation/discovery/theme-imports.mjs +43 -1
  282. package/foundation/discovery/theming-targets.mjs +3 -2
  283. package/foundation/doc-compiler/import.mjs +7 -1
  284. package/foundation/doc-compiler/inputs.mjs +3 -2
  285. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  286. package/foundation/doc-compiler/stored-docs.d.mts +22 -0
  287. package/foundation/doc-compiler/stored-docs.mjs +49 -0
  288. package/foundation/env/semver.mjs +3 -1
  289. package/foundation/fonts/font-stylesheet.d.mts +31 -0
  290. package/foundation/fonts/font-stylesheet.mjs +115 -0
  291. package/foundation/fs/cache-eviction.d.mts +21 -0
  292. package/foundation/fs/cache-eviction.mjs +73 -0
  293. package/foundation/fs/file-protection.mjs +4 -3
  294. package/foundation/fs/gather-cache.d.mts +25 -4
  295. package/foundation/fs/gather-cache.mjs +164 -55
  296. package/foundation/fs/jiti-cache.d.mts +19 -1
  297. package/foundation/fs/jiti-cache.mjs +130 -6
  298. package/foundation/fs/kept-tree.d.mts +60 -0
  299. package/foundation/fs/kept-tree.mjs +154 -0
  300. package/foundation/fs/listing-cache.d.mts +7 -0
  301. package/foundation/fs/listing-cache.mjs +10 -0
  302. package/foundation/fs/module-loader.d.mts +24 -2
  303. package/foundation/fs/module-loader.mjs +94 -21
  304. package/foundation/fs/paths.d.mts +18 -0
  305. package/foundation/fs/paths.mjs +15 -2
  306. package/foundation/identity/provider-identity.d.mts +6 -0
  307. package/foundation/identity/provider-identity.mjs +10 -1
  308. package/foundation/integrations/contribution-inventory.mjs +4 -3
  309. package/foundation/integrations/example-code.d.mts +63 -0
  310. package/foundation/integrations/example-code.mjs +416 -0
  311. package/foundation/integrations/public-imports.d.mts +9 -0
  312. package/foundation/integrations/public-imports.mjs +3 -2
  313. package/foundation/integrations/validate-contributions.mjs +17 -45
  314. package/foundation/render/embedded-files.d.mts +6 -0
  315. package/foundation/render/embedded-files.mjs +25 -5
  316. package/foundation/render/embedded-imports.d.mts +39 -7
  317. package/foundation/render/embedded-imports.mjs +66 -27
  318. package/foundation/render/file-header.d.mts +66 -0
  319. package/foundation/render/file-header.mjs +118 -0
  320. package/foundation/render/host-answer.d.mts +18 -0
  321. package/foundation/render/host-answer.mjs +46 -0
  322. package/foundation/render/host-exit.d.mts +1 -0
  323. package/foundation/render/host-exit.mjs +6 -1
  324. package/foundation/render/html-reader.d.mts +55 -2
  325. package/foundation/render/html-reader.mjs +145 -26
  326. package/foundation/render/markup-edits.d.mts +57 -0
  327. package/foundation/render/markup-edits.mjs +182 -0
  328. package/foundation/render/page-host.mjs +29 -12
  329. package/foundation/render/page-worker.mjs +121 -13
  330. package/foundation/render/picture-chrome.d.mts +4 -0
  331. package/foundation/render/picture-chrome.mjs +185 -0
  332. package/foundation/render/picture-playwright.d.mts +4 -0
  333. package/foundation/render/picture-playwright.mjs +34 -0
  334. package/foundation/render/rebuild.mjs +2 -1
  335. package/foundation/render/render-page.d.mts +35 -3
  336. package/foundation/render/render-page.mjs +316 -42
  337. package/foundation/render/source-block.d.mts +85 -6
  338. package/foundation/render/source-block.mjs +211 -20
  339. package/foundation/render/ts-paths.d.mts +69 -6
  340. package/foundation/render/ts-paths.mjs +326 -40
  341. package/foundation/response/error-codes.d.mts +3 -1
  342. package/foundation/response/error-codes.d.ts +1 -0
  343. package/foundation/response/error-codes.doc.mjs +12 -1
  344. package/foundation/response/error-codes.mjs +11 -1
  345. package/foundation/response/response-types.doc.mjs +2 -2
  346. package/foundation/text/compare-text.d.mts +14 -0
  347. package/foundation/text/compare-text.mjs +68 -0
  348. package/foundation/text/string-utils.d.mts +3 -2
  349. package/foundation/text/string-utils.mjs +18 -4
  350. package/foundation/text/suggest-order.d.mts +9 -0
  351. package/foundation/text/suggest-order.mjs +15 -1
  352. package/foundation/xle/expand.mjs +2 -1
  353. package/host/index.mjs +8 -6
  354. 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,15 @@ 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';
29
28
  import {
29
+ loadThemeExport,
30
+ oneColorMode,
31
+ themeBuildForReport,
32
+ } from '../theme/build/build.mjs';
33
+ import {namedFontFamilies} from '../theme/build/font-warning.mjs';
34
+ import {declarationValues} from '../../foundation/fonts/font-stylesheet.mjs';
35
+ import {
36
+ MODE_WORDS,
30
37
  AUTO_SPREAD,
31
38
  CORNERS,
32
39
  DIALS,
@@ -46,6 +53,7 @@ import {
46
53
  WRAPPED_PARTS,
47
54
  CARD_LIKE,
48
55
  } from './_tables.mjs';
56
+ import {cleanDialValue, typoLimit, typoNear} from './_normal.mjs';
49
57
  import {
50
58
  alphaOf,
51
59
  colorProblem,
@@ -81,8 +89,10 @@ import {
81
89
  baseModule,
82
90
  baseResolved,
83
91
  baseThemeFile,
92
+ installLine,
84
93
  } from './_project.mjs';
85
94
  import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
95
+ import {compareText} from '../../foundation/text/compare-text.mjs';
86
96
 
87
97
  // The palette reads the tokens the own source sets through this module.
88
98
  setOwnTokenReader((cwd, slug) => ownSourceTokenValues(cwd, slug));
@@ -116,13 +126,13 @@ setOwnTokenReader((cwd, slug) => ownSourceTokenValues(cwd, slug));
116
126
  /** What lifted secondary text sits on: the contrast check measures it there. */
117
127
  const LIFT_GROUND_TOKENS = new Set(LIFT_PARTS.map(([, , g]) => g));
118
128
 
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 */
129
+ /** @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
130
  /** @typedef {import('./_parts.mjs').PaintSide} PaintSide */
121
131
  /** @typedef {import('./_parts.mjs').TextPair} TextPair */
122
132
 
123
- /** What a theme name may be, in words. */
124
- 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)';
133
+ import {NAME_RULE} from './_name-rule.mjs';
134
+
135
+ export {NAME_RULE};
126
136
 
127
137
  /** A theme name: lowercase letters, digits and dashes, starting with a letter, 64 characters at most. @param {string} s */
128
138
  export const slugOk = s =>
@@ -197,20 +207,35 @@ export function themeFiles(cwd, slug) {
197
207
  }
198
208
 
199
209
  /** 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']);
210
+ export const FOLDER_JUNK = new Set([
211
+ '.DS_Store',
212
+ '.gitkeep',
213
+ 'Thumbs.db',
214
+ 'desktop.ini',
215
+ ]);
201
216
 
202
217
  /**
203
218
  * Whether `dir` holds nothing of anyone's: absent, empty, or only system
204
219
  * files (what `git rm -r` or a branch switch leaves). A path that is not a
205
220
  * folder, or one that does not read, is not empty.
206
221
  * @param {string} dir
222
+ * @returns {boolean}
207
223
  */
208
224
  export function folderIsEmpty(dir) {
209
225
  if (!fs.existsSync(dir)) return true;
210
226
  try {
227
+ // A folder holding only empty folders (an empty tokens/) holds nothing
228
+ // either; a link is never followed.
211
229
  return (
212
230
  fs.lstatSync(dir).isDirectory() &&
213
- fs.readdirSync(dir).every(n => FOLDER_JUNK.has(n))
231
+ fs
232
+ .readdirSync(dir)
233
+ .every(
234
+ n =>
235
+ FOLDER_JUNK.has(n) ||
236
+ (fs.lstatSync(path.join(dir, n)).isDirectory() &&
237
+ folderIsEmpty(path.join(dir, n))),
238
+ )
214
239
  );
215
240
  } catch {
216
241
  return false;
@@ -290,34 +315,17 @@ export function editorWrote(cwd, slug, file) {
290
315
  }
291
316
 
292
317
  /**
293
- * Adopt a picture an older editor took (before it recorded or stamped its
294
- * pictures) into the record: only while the theme has no record at all, the
295
- * name is one the editor writes, and the picture is the editor's 1280-pixel
296
- * wide window. Returns whether it was adopted.
318
+ * Whether the pictures record names this file and it is unchanged since the
319
+ * editor wrote it. Only such a file is ever deleted: a stamp alone is not
320
+ * enough, since a byte copy of a picture (preview-before.png) carries the
321
+ * same stamp and is the person's.
297
322
  * @param {string} cwd
298
323
  * @param {string} slug
299
324
  * @param {string} file
300
325
  */
301
- export function adoptOlderPicture(cwd, slug, file) {
302
- if (fs.existsSync(themeFiles(cwd, slug).pictures)) return false;
303
- if (!/^(sheet|preview)(-[a-z-]+)?\.png$/.test(path.basename(file)))
304
- return false;
305
- /** @type {Buffer} */
306
- let bytes;
307
- try {
308
- bytes = fs.readFileSync(file);
309
- } catch {
310
- return false;
311
- }
312
- // The width in the PNG header: the editor takes a 1280-pixel window.
313
- if (
314
- bytes.length < 24 ||
315
- bytes.toString('latin1', 12, 16) !== 'IHDR' ||
316
- bytes.readUInt32BE(16) !== 1280
317
- )
318
- return false;
319
- recordWritten(cwd, slug, [file]);
320
- return true;
326
+ export function editorRecorded(cwd, slug, file) {
327
+ const was = readWrittenRecord(cwd, slug)[path.basename(file)];
328
+ return Boolean(was) && was === contentHash(file);
321
329
  }
322
330
 
323
331
  /**
@@ -470,7 +478,7 @@ export function editedThemes(cwd, order = 'name') {
470
478
  };
471
479
  return names
472
480
  .map(d => ({d, t: when(d)}))
473
- .sort((a, b) => b.t - a.t || a.d.localeCompare(b.d))
481
+ .sort((a, b) => b.t - a.t || compareText(a.d, b.d))
474
482
  .map(x => x.d);
475
483
  }
476
484
 
@@ -485,21 +493,57 @@ export const shown = (cwd, f) =>
485
493
  * @param {number} [n]
486
494
  */
487
495
  export function nearest(x, list, n = 3) {
496
+ // A phrase that negates a word (not round, no caps, unbold,
497
+ // rounded-none) never has that word as its nearest: it asks the opposite.
498
+ // A typo of a listed keyword that itself starts with no- or not-
499
+ // (`not-alowed` for not-allowed, `no-repat` for no-repeat) is no
500
+ // negation: it is read as a typo.
501
+ if (
502
+ negates(x) &&
503
+ ![...list].some(c => /^(no|not)-/.test(c) && typoNear(x, c))
504
+ )
505
+ return [];
506
+ // A long input (a pasted stylesheet or blob) holds many names inside
507
+ // it: it is near nothing.
508
+ if (x.length > 64) return [];
509
+ // Within the editor's one typo limit (typoLimit: none under four
510
+ // letters, so only the name itself in other letters is near those),
511
+ // nearest by edit distance first (brand-drak is brand-dark, not brand); a
512
+ // name one holds inside the other is near too, after the close ones, for
513
+ // a word long enough to be a typo.
514
+ const limit = typoLimit(x);
515
+ const typed = x.toLowerCase();
488
516
  return [...list]
489
517
  .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)))
518
+ .map(c => {
519
+ const name = c.toLowerCase();
520
+ const d = levenshteinDistance(typed, name, limit, {swaps: true});
521
+ return /** @type {[string, number]} */ ([
522
+ c,
523
+ d <= limit
524
+ ? d
525
+ : limit > 0 && (name.includes(typed) || typed.includes(name))
526
+ ? limit + 0.5
527
+ : d,
528
+ ]);
529
+ })
530
+ .filter(([, s]) => s <= limit + 0.5)
498
531
  .sort((a, b) => a[1] - b[1])
499
532
  .slice(0, n)
500
533
  .map(([c]) => c);
501
534
  }
502
535
 
536
+ /**
537
+ * Whether typed words negate what they name (`not round`, `no caps`,
538
+ * `anything but blue`, `unbold`, `non-bold`, `rounded-none`).
539
+ * @param {string} x
540
+ */
541
+ export function negates(x) {
542
+ return /(^|[\s-])(not|no|non|without|never|less)([\s-]|$)|anything but|^un(round|bold|rais|outlin|cap)|-none$/i.test(
543
+ String(x).trim(),
544
+ );
545
+ }
546
+
503
547
  /**
504
548
  * A refusal: nothing was changed, and the suggestions lead with the command
505
549
  * that does what the person wanted.
@@ -577,6 +621,79 @@ export function typedThemeName(s) {
577
621
  );
578
622
  }
579
623
 
624
+ /**
625
+ * The theme names a name typed the way the app shows it may mean, most
626
+ * likely first: a path with doubled slashes or `../` (`themes//t`), a file
627
+ * name with or without its folder (`brand.theme.ts`, `tTheme.ts`), the app
628
+ * copy's export (`tTheme`), camelCase (`brandDark`) and spaces
629
+ * (`Brand Dark`) each read as dashes. The caller picks the first that
630
+ * exists, else the first.
631
+ * @param {string} s
632
+ * @returns {string[]}
633
+ */
634
+ export function themeNameReadings(s) {
635
+ const base = unlabeledThemeName(String(s ?? ''))
636
+ .replace(/[\\/]+/g, '/')
637
+ .replace(/^(\.\.?\/)+/, '')
638
+ .replace(/^.*themes\//i, '')
639
+ .replace(/\/.*$/, '')
640
+ .replace(
641
+ /\.(theme\.ts|settings\.(json|ts)|history\.json|css\.d\.ts|d\.ts|doc\.mjs|fonts\.css|css|mjs|js|tsx?)$/i,
642
+ '',
643
+ )
644
+ .trim();
645
+ const noTheme = base.replace(/([a-z0-9])Theme$/, '$1');
646
+ const read = [base, noTheme === base ? '' : noTheme]
647
+ .flatMap(x => [kebab(x), x.toLowerCase()])
648
+ .filter(x => /[a-z]/i.test(x))
649
+ .map(x => slugFor(x));
650
+ // A module name in any letters (brandtheme, brand-theme) last: only
651
+ // when the theme it names exists does it win.
652
+ const moduleNames = read
653
+ .map(n => n.replace(/-?theme$/, ''))
654
+ .filter(n => n && slugOk(n));
655
+ return [...new Set([...read, ...moduleNames])];
656
+ }
657
+
658
+ /**
659
+ * A vibrancy written as set reads typed input: a share of one (0.5) or a
660
+ * percent (50%) is that much of the 0-100 scale, as a whole number. Any
661
+ * other dial's value, or a vibrancy that is no such number, comes back as
662
+ * it was.
663
+ * @param {string} dial
664
+ * @param {string} v
665
+ * @returns {string}
666
+ */
667
+ export function vibrancyMeant(dial, v) {
668
+ if (dial !== 'vibrancy') return v;
669
+ const m = /^(\d*\.?\d+)\s*(%?)$/.exec(v.trim());
670
+ if (!m) return v;
671
+ const n = Number(m[1]);
672
+ const scaled = !m[2] && n > 0 && n < 1 ? n * 100 : n;
673
+ return scaled <= 100 ? String(Math.round(scaled)) : v;
674
+ }
675
+
676
+ /**
677
+ * The mode and base a damaged theme file meant, read the way typed input
678
+ * is: other letters, stray spaces, `_` or a space for a dash (`Dark-Only`,
679
+ * ` Neutral`), and a base written as its package name
680
+ * (`@astryxdesign/theme-neutral`). Each is the cleaned text even when it is
681
+ * no value the editor takes; the caller checks it.
682
+ * @param {any} data
683
+ * @returns {{mode: string, like: string}}
684
+ */
685
+ export function fieldsMeant(data) {
686
+ const mode = String(data?.mode ?? '')
687
+ .trim()
688
+ .toLowerCase()
689
+ .replace(/[\s_]+/g, '-');
690
+ const like = String(data?.like ?? '')
691
+ .trim()
692
+ .toLowerCase()
693
+ .replace(/^@astryxdesign\/theme-/, '');
694
+ return {mode, like};
695
+ }
696
+
580
697
  /**
581
698
  * The settings of a theme, or a refusal naming the command that makes it.
582
699
  * @param {string} cwd
@@ -605,9 +722,22 @@ export function loadTheme(
605
722
  );
606
723
  const plain = typedThemeName(slug);
607
724
  const named = slugFor(plain);
725
+ // brandDark is brand-dark.
726
+ const camelWords = slugFor(
727
+ unlabeledThemeName(String(slug ?? '')).replace(
728
+ /([a-z0-9])([A-Z])/g,
729
+ '$1-$2',
730
+ ),
731
+ );
608
732
  const exists = (/** @type {string} */ n) =>
609
733
  Boolean(n) && fs.existsSync(themeFiles(cwd, n).settings);
610
- const fixed = !exists(named) && exists(whole) ? whole : named;
734
+ // The module or export name (brandTheme, the app copy's brandTheme.ts)
735
+ // names the theme brand: one reader for every way a name is typed.
736
+ const readings = themeNameReadings(slug);
737
+ const fixed =
738
+ [named, whole, camelWords, ...readings].find(exists) ??
739
+ readings[0] ??
740
+ named;
611
741
  const same = fs.existsSync(themeFiles(cwd, fixed).settings) ? fixed : null;
612
742
  // A list where one theme goes (t,u or "t;u"): one theme at a time,
613
743
  // each that exists named; never a new theme made of the list. A name
@@ -741,6 +871,30 @@ export function loadTheme(
741
871
  `themes/${slug} is an empty folder: there is no theme ${slug} yet. new makes it there.`,
742
872
  {run: [`${P} new ${slug}`]},
743
873
  );
874
+ // The editor's own app copy left behind when themes/<slug>/ is gone
875
+ // (a git clean, a wrong rm, a branch switch): `new` makes the theme
876
+ // again and writes the copy over.
877
+ const copyName = `${camel(slug)}Theme`;
878
+ if (
879
+ !same &&
880
+ other &&
881
+ other[1] === `src/themes/${slug}` &&
882
+ !fs.existsSync(f.dir) &&
883
+ [`${copyName}.ts`, `${copyName}.doc.mjs`, `${slug}.fonts.css`].some(n => {
884
+ try {
885
+ return fs
886
+ .readFileSync(path.join(other[0], n), 'utf8')
887
+ .includes(APP_COPY_MARK);
888
+ } catch {
889
+ return false;
890
+ }
891
+ })
892
+ )
893
+ refuse(
894
+ ERROR_CODES.ERR_UNKNOWN_THEME,
895
+ `themes/${slug}/, the theme's source folder, is missing; src/themes/${slug}/ is the editor's app copy of it, left behind. \`new ${slug}\` makes the theme again and writes the copy over (its settings are lost: restore themes/${slug}/ from version control to keep them).`,
896
+ {run: [`${P} new ${slug}`]},
897
+ );
744
898
  if (!same && (other || LIKE.includes(slug)))
745
899
  refuse(
746
900
  ERROR_CODES.ERR_UNKNOWN_THEME,
@@ -752,7 +906,18 @@ export function loadTheme(
752
906
  ...(fs.existsSync(themeFiles(cwd, `my-${slug}`).settings)
753
907
  ? [`${P} show my-${slug}`]
754
908
  : []),
755
- `${P} new ${usableNewName(cwd, `my-${slug}`)}${LIKE.includes(slug) ? ` --like ${slug}` : ''}`,
909
+ ...(LIKE.includes(slug)
910
+ ? [
911
+ ...onBuiltIn(
912
+ cwd,
913
+ slug,
914
+ `${P} new ${usableNewName(cwd, `my-${slug}`)} --like ${slug}`,
915
+ ),
916
+ ...(baseInstalled(cwd, slug)
917
+ ? []
918
+ : [`${P} new ${usableNewName(cwd, `my-${slug}`)}`]),
919
+ ]
920
+ : [`${P} new ${usableNewName(cwd, `my-${slug}`)}`]),
756
921
  ],
757
922
  },
758
923
  );
@@ -760,7 +925,24 @@ export function loadTheme(
760
925
  ERROR_CODES.ERR_UNKNOWN_THEME,
761
926
  `There is no theme "${slug}" made by this command (no themes/${slug}/${slug}.settings.json).`,
762
927
  (() => {
763
- const near = same ? [same] : nearest(slug, have);
928
+ // A doubled or trailing dash (brand--dark, t--): the name as new
929
+ // cleans it, the theme of that name when there is one, never a new
930
+ // theme new refuses.
931
+ const cleaned = String(slug)
932
+ .replace(/-{2,}/g, '-')
933
+ .replace(/^-+|-+$/g, '');
934
+ const cleanedHere =
935
+ cleaned !== slug &&
936
+ slugOk(cleaned) &&
937
+ fs.existsSync(themeFiles(cwd, cleaned).settings)
938
+ ? cleaned
939
+ : null;
940
+ const near = same
941
+ ? [same]
942
+ : cleanedHere
943
+ ? [cleanedHere]
944
+ : nearest(slug, have);
945
+ const newName = usableNewName(cwd, cleaned || slug);
764
946
  // A theme near the name comes first; a new theme of the name as
765
947
  // typed only after.
766
948
  return {
@@ -768,8 +950,8 @@ export function loadTheme(
768
950
  run: same
769
951
  ? [`${P} show ${same}`]
770
952
  : near.length
771
- ? [`${P} show ${near[0]}`, `${P} new ${slug}`]
772
- : [`${P} new ${slug}`],
953
+ ? [`${P} show ${near[0]}`, `${P} new ${newName}`]
954
+ : [`${P} new ${newName}`],
773
955
  };
774
956
  })(),
775
957
  );
@@ -790,18 +972,13 @@ export function loadTheme(
790
972
  run: [{name: `${P} new ${slug}`, reason: 'do this instead'}],
791
973
  };
792
974
  /** @type {any} */
793
- let data;
794
- try {
795
- data = JSON.parse(
796
- fs.readFileSync(f.settings, 'utf8').replace(/^\uFEFF/, ''),
797
- );
798
- } catch {
975
+ const data = settingsJson(fs.readFileSync(f.settings, 'utf8'));
976
+ if (data === undefined)
799
977
  throw new AstryxError(
800
978
  `themes/${slug}/${slug}.settings.json is not valid JSON. Fix it by hand${recover.text}.`,
801
979
  recover.run,
802
980
  ERROR_CODES.ERR_THEME_INVALID,
803
981
  );
804
- }
805
982
  // Valid JSON of the wrong shape ([], {}, settings: null) is damage like
806
983
  // invalid JSON: `new` makes the theme again, keeping the file aside.
807
984
  if (!settingsShapeOk(data))
@@ -813,7 +990,36 @@ export function loadTheme(
813
990
  ],
814
991
  ERROR_CODES.ERR_THEME_INVALID,
815
992
  );
993
+ readEntryWords(data);
994
+ // `like: "none"`, the word for no base, is no base.
995
+ if (data.like === 'none') delete data.like;
996
+ // The folder names the theme: a name missing or changed by hand in the
997
+ // file is the folder's, and the next save writes it back.
998
+ data.name = slug;
816
999
  const problem = settingsProblem(data, skip);
1000
+ // An entry whose mode or source means nothing: `undo` with its name
1001
+ // removes that entry only; a step back loses the last change.
1002
+ const damaged = problem ? damagedEntry(data, problem) : null;
1003
+ if (damaged)
1004
+ throw new AstryxError(
1005
+ `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.`,
1006
+ [
1007
+ {
1008
+ name: `${P} undo ${slug} ${undoArgs(damagedUndo(damaged))}`,
1009
+ reason: 'do this instead: removes only that setting',
1010
+ },
1011
+ ...(steps
1012
+ ? [
1013
+ {
1014
+ name: `${P} undo ${slug}`,
1015
+ reason:
1016
+ 'or step back to the settings before the last change (the last change is then lost)',
1017
+ },
1018
+ ]
1019
+ : []),
1020
+ ],
1021
+ ERROR_CODES.ERR_THEME_INVALID,
1022
+ );
817
1023
  // A value made under looser rules is not damage: the command that
818
1024
  // changes or removes that setting still works, with the other bad ones
819
1025
  // left out of the build, so each listed fix runs on its own.
@@ -854,23 +1060,62 @@ export function loadTheme(
854
1060
  })),
855
1061
  ERROR_CODES.ERR_THEME_INVALID,
856
1062
  );
857
- const bad = problem ? badSetting(data) : null;
1063
+ // A damaged mode or base is fixed first: the message names it, so the
1064
+ // suggestions set it (another bad value is named on the next run).
1065
+ // (Not an entry named mode or base inside the settings list.)
1066
+ const fieldBroken =
1067
+ (/^(it has no mode|mode ")/.test(problem ?? '') &&
1068
+ !['both', 'light-only', 'dark-only'].includes(data?.mode)) ||
1069
+ (/^base "/.test(problem ?? '') &&
1070
+ data?.like != null &&
1071
+ !LIKE.includes(data.like));
1072
+ const bad = problem && !fieldBroken ? badSetting(data) : null;
858
1073
  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'
1074
+ // The value it holds, cleaned as typed input is (stray or invisible
1075
+ // spaces, other letters, a pasted `corners: pill`), when the dial takes
1076
+ // that; else a value it takes, for a dial; a color for a color token.
1077
+ const cleaned =
1078
+ DIALS[bad.thing] && typeof bad.value === 'string'
1079
+ ? vibrancyMeant(bad.thing, cleanDialValue(bad.thing, bad.value))
864
1080
  : null;
1081
+ // Vibrancy saturates the colors the color dials make: with none, set
1082
+ // refuses it as having no effect, so it is not offered.
1083
+ const vibrancyActs =
1084
+ bad.thing !== 'vibrancy' ||
1085
+ (Array.isArray(data.settings) ? data.settings : []).some(
1086
+ (/** @type {any} */ x) =>
1087
+ x && x.source === 'dial' && PALETTE_DIALS.includes(x.thing),
1088
+ );
1089
+ const meant =
1090
+ cleaned &&
1091
+ cleaned !== bad.value &&
1092
+ vibrancyActs &&
1093
+ !valueProblem({...bad, value: cleaned})
1094
+ ? cleaned
1095
+ : null;
1096
+ // Only the value it holds, cleaned: never a stock value it did not hold.
1097
+ // A vibrancy with no color to saturate is one set refuses: undo only.
1098
+ const example =
1099
+ bad.thing === 'vibrancy' &&
1100
+ !data.settings.some(
1101
+ (/** @type {any} */ x) =>
1102
+ x !== bad && x.source === 'dial' && PALETTE_DIALS.includes(x.thing),
1103
+ )
1104
+ ? null
1105
+ : meant;
865
1106
  throw new AstryxError(
866
1107
  `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
1108
  [
868
1109
  {name: `${P} undo ${slug} ${undoArgs(bad)}`, reason: 'do this instead'},
869
- ...(example
1110
+ // Only a set that replaces this very entry: `mode` and `base` set
1111
+ // the theme's own fields, not an entry in the list.
1112
+ ...(example && !['mode', 'base'].includes(bad.thing)
870
1113
  ? [
871
1114
  {
872
- name: `${P} set ${slug} ${undoArgs(bad).replace(bad.thing, `${bad.thing} ${quoteCommandArgument(example)}`)}`,
873
- reason: 'or give it a value it takes',
1115
+ name: `${P} set ${slug} ${setArgs(bad, example)}`,
1116
+ reason: meant
1117
+ ? 'or set the value it holds, cleaned'
1118
+ : 'or give it a value it takes',
874
1119
  },
875
1120
  ]
876
1121
  : []),
@@ -880,17 +1125,53 @@ export function loadTheme(
880
1125
  }
881
1126
  // A bad mode or base is fixed by setting it.
882
1127
  // 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();
1128
+ const {mode: modeMeant, like: likeMeant} = fieldsMeant(data);
889
1129
  const fieldFix = /^(it has no mode|mode ")/.test(problem ?? '')
890
1130
  ? `${P} set ${slug} mode ${['both', 'light-only', 'dark-only'].includes(modeMeant) ? modeMeant : 'both'}`
891
1131
  : /^base "/.test(problem ?? '')
892
1132
  ? `${P} set ${slug} base ${LIKE.includes(likeMeant) && baseInstalled(cwd, likeMeant) ? likeMeant : 'none'}`
893
1133
  : null;
1134
+ // A damaged mode or base and a bad value in the list: setting the field
1135
+ // is refused while the list holds the bad value, but fixing that entry
1136
+ // saves the field as meant too, so its fix comes first. Never a bare
1137
+ // undo, which would throw away the last real change.
1138
+ const alsoBad = fieldFix ? badSetting(data) : null;
1139
+ if (problem && fieldFix && alsoBad) {
1140
+ const cleaned =
1141
+ DIALS[alsoBad.thing] && typeof alsoBad.value === 'string'
1142
+ ? vibrancyMeant(
1143
+ alsoBad.thing,
1144
+ cleanDialValue(alsoBad.thing, alsoBad.value),
1145
+ )
1146
+ : null;
1147
+ const meant =
1148
+ cleaned &&
1149
+ cleaned !== alsoBad.value &&
1150
+ !['mode', 'base'].includes(alsoBad.thing) &&
1151
+ !valueProblem({...alsoBad, value: cleaned})
1152
+ ? cleaned
1153
+ : null;
1154
+ const field = /^base "/.test(problem) ? 'base' : 'mode';
1155
+ const fieldValue = fieldFix.split(' ').pop();
1156
+ throw new AstryxError(
1157
+ `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.`,
1158
+ [
1159
+ ...(meant
1160
+ ? [
1161
+ {
1162
+ name: `${P} set ${slug} ${setArgs(alsoBad, meant)}`,
1163
+ reason: 'do this instead: set the value it holds, cleaned',
1164
+ },
1165
+ ]
1166
+ : []),
1167
+ {
1168
+ name: `${P} undo ${slug} ${undoArgs(alsoBad)}`,
1169
+ reason: meant ? 'or remove that setting' : 'do this instead',
1170
+ },
1171
+ ],
1172
+ ERROR_CODES.ERR_THEME_INVALID,
1173
+ );
1174
+ }
894
1175
  // A setting listed twice: setting it to one of its values, or undoing
895
1176
  // it, keeps one entry or none.
896
1177
  const twice = problem?.includes(' is listed twice (')
@@ -900,7 +1181,7 @@ export function loadTheme(
900
1181
  throw new AstryxError(
901
1182
  `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
1183
  fieldFix
903
- ? [{name: fieldFix, reason: 'do this instead'}, ...recover.run]
1184
+ ? [{name: fieldFix, reason: 'do this instead'}]
904
1185
  : twice
905
1186
  ? [
906
1187
  ...twice.values
@@ -911,7 +1192,7 @@ export function loadTheme(
911
1192
  )
912
1193
  .slice(0, 2)
913
1194
  .map(v => ({
914
- name: `${P} set ${slug} ${undoArgs(twice.setting).replace(twice.setting.thing, `${twice.setting.thing} ${quoteCommandArgument(String(v))}`)}`,
1195
+ name: `${P} set ${slug} ${setArgs(twice.setting, String(v))}`,
915
1196
  reason: `keep ${v}`,
916
1197
  })),
917
1198
  {
@@ -926,6 +1207,21 @@ export function loadTheme(
926
1207
  return data;
927
1208
  }
928
1209
 
1210
+ /**
1211
+ * A command that builds on a built-in theme, as it runs here: after the
1212
+ * line that installs that theme's package when the project does not have
1213
+ * it, so the first line offered always works.
1214
+ * @param {string} cwd
1215
+ * @param {string} base a built-in theme
1216
+ * @param {string} line the command on that base
1217
+ * @returns {string[]}
1218
+ */
1219
+ export function onBuiltIn(cwd, base, line) {
1220
+ return baseInstalled(cwd, base)
1221
+ ? [line]
1222
+ : [installLine(cwd, [`@astryxdesign/theme-${base}`]), line];
1223
+ }
1224
+
929
1225
  /**
930
1226
  * The first setting listed more than once, with every value it is listed
931
1227
  * with, in order.
@@ -961,9 +1257,11 @@ export function settingsProblem(
961
1257
  ) {
962
1258
  if (!data || typeof data !== 'object' || Array.isArray(data))
963
1259
  return 'the file is not a settings object';
964
- // `set <theme> mode` and `set <theme> base` fix their own field.
1260
+ // A command that changes or removes a setting (or sets mode or base)
1261
+ // puts a damaged mode or base back to its default itself, with a note, so
1262
+ // two damaged fields never send each fix to the other.
965
1263
  const fixing = typeof skip === 'string' ? skip : skip?.thing;
966
- const field = fixing === 'mode' || fixing === 'base';
1264
+ const field = Boolean(fixing);
967
1265
  if (!field && !['both', 'light-only', 'dark-only'].includes(data.mode))
968
1266
  return data.mode == null
969
1267
  ? 'it has no mode'
@@ -985,23 +1283,165 @@ export function settingsProblem(
985
1283
  // a setting with no name is damage.
986
1284
  if (!s || typeof s.thing !== 'string' || !('value' in s))
987
1285
  return 'a setting has no thing or value';
1286
+ if (removes(skip) && skips(s, skip) && entryDamage(s)) continue;
988
1287
  if (!['dial', 'token', 'property'].includes(s.source))
989
- return `${s.thing} has no source (dial, token or property)`;
1288
+ return s.source == null || s.source === ''
1289
+ ? `${s.thing} has no source (dial, token or property)`
1290
+ : `${s.thing} has source ${JSON.stringify(s.source)}, not dial, token or property`;
990
1291
  if (s.mode != null && s.mode !== 'light' && s.mode !== 'dark')
991
- return `${s.thing} has mode "${s.mode}"`;
1292
+ return `${s.thing} has mode ${JSON.stringify(s.mode)}, not light or dark`;
1293
+ if (s.only != null && s.only !== true)
1294
+ return `${s.thing} has only ${JSON.stringify(s.only)}, not true or false`;
1295
+ // A bad value comes first: an entry under the wrong headings half is
1296
+ // that, not a second entry of the half it names.
1297
+ if (!skips(s, skip)) {
1298
+ const problem = valueProblem(s);
1299
+ if (problem) return problem;
1300
+ }
992
1301
  const key = keyOf(s);
993
1302
  // The command that changes or removes a setting listed twice keeps one
994
1303
  // value, or none, so it fixes the list.
995
1304
  if (keys.has(key) && !skips(s, skip))
996
1305
  return `${describe({...s, value: '?'}).replace(' = ?', '')} is listed twice (${JSON.stringify(keys.get(key).value)}, ${JSON.stringify(s.value)})`;
997
1306
  keys.set(key, s);
998
- if (skips(s, skip)) continue;
999
- const problem = valueProblem(s);
1000
- if (problem) return problem;
1001
1307
  }
1002
1308
  return null;
1003
1309
  }
1004
1310
 
1311
+ /**
1312
+ * Read each entry's mode and source as the editor writes them: a mode in
1313
+ * other letters or words (`Dark`, `night`, `day`) as light or dark, a
1314
+ * source in other letters (`Dial`) as written, and a missing source from
1315
+ * the thing (a dial name is a dial, a `--` name a token, anything with a
1316
+ * part a property). Each change is kept as a note for the next command,
1317
+ * which saves the entry that way. A value that means nothing is left for
1318
+ * the check to name.
1319
+ * @param {any} data
1320
+ */
1321
+ function readEntryWords(data) {
1322
+ /** @type {string[]} */
1323
+ const notes = [];
1324
+ for (const s of Array.isArray(data?.settings) ? data.settings : []) {
1325
+ if (!s || typeof s !== 'object' || typeof s.thing !== 'string') continue;
1326
+ if (typeof s.mode === 'string' && s.mode !== 'light' && s.mode !== 'dark') {
1327
+ const read = MODE_WORDS[s.mode.trim().toLowerCase()];
1328
+ if (read) {
1329
+ notes.push(
1330
+ `${s.thing} was saved with mode ${JSON.stringify(s.mode)}, read as ${read}`,
1331
+ );
1332
+ s.mode = read;
1333
+ }
1334
+ }
1335
+ // `only` is true or absent; `"true"` and `"false"` written as text are
1336
+ // read as what they say, since the build reads any other value as true.
1337
+ if (typeof s.only === 'string' && /^\s*(true|false)\s*$/i.test(s.only)) {
1338
+ const read = s.only.trim().toLowerCase() === 'true';
1339
+ notes.push(
1340
+ `${s.thing} was saved with only ${JSON.stringify(s.only)}, read as ${read}`,
1341
+ );
1342
+ if (read) s.only = true;
1343
+ else delete s.only;
1344
+ } else if (s.only === false) delete s.only;
1345
+ if (!['dial', 'token', 'property'].includes(s.source)) {
1346
+ const typed = typeof s.source === 'string' ? s.source.trim() : '';
1347
+ const read = typed
1348
+ ? ['dial', 'token', 'property'].find(x => x === typed.toLowerCase())
1349
+ : s.source == null || s.source === ''
1350
+ ? DIALS[s.thing]
1351
+ ? 'dial'
1352
+ : s.thing.startsWith('--')
1353
+ ? 'token'
1354
+ : s.on
1355
+ ? 'property'
1356
+ : undefined
1357
+ : undefined;
1358
+ if (read) {
1359
+ notes.push(
1360
+ typed
1361
+ ? `${s.thing} was saved with source ${JSON.stringify(s.source)}, read as ${read}`
1362
+ : `${s.thing} was saved with no source, read as ${read}`,
1363
+ );
1364
+ s.source = read;
1365
+ }
1366
+ }
1367
+ }
1368
+ ENTRY_NOTES.set(data, notes);
1369
+ }
1370
+
1371
+ /** @type {WeakMap<object, string[]>} */
1372
+ const ENTRY_NOTES = new WeakMap();
1373
+
1374
+ /**
1375
+ * What loading read differently from the file in the theme's entries (a
1376
+ * mode or source in other letters, a missing source): one note each.
1377
+ * @param {object} data the theme as {@link loadTheme} returned it
1378
+ * @returns {string[]}
1379
+ */
1380
+ export function entryNotes(data) {
1381
+ return ENTRY_NOTES.get(data) ?? [];
1382
+ }
1383
+
1384
+ /**
1385
+ * Which part of an entry means nothing after reading: its source, mode or
1386
+ * `only`, or null.
1387
+ * @param {any} s
1388
+ * @returns {'mode' | 'source' | 'only' | null}
1389
+ */
1390
+ export function entryDamage(s) {
1391
+ if (!s || typeof s.thing !== 'string') return null;
1392
+ if (!['dial', 'token', 'property'].includes(s.source)) return 'source';
1393
+ if (s.mode != null && s.mode !== 'light' && s.mode !== 'dark') return 'mode';
1394
+ if (s.only != null && s.only !== true) return 'only';
1395
+ return null;
1396
+ }
1397
+
1398
+ /**
1399
+ * The entry as an undo names it: without the mode or `only` that means
1400
+ * nothing (an undo without them removes that entry).
1401
+ * @param {any} s
1402
+ */
1403
+ function damagedUndo(s) {
1404
+ const damage = entryDamage(s);
1405
+ return {
1406
+ ...s,
1407
+ mode: damage === 'mode' ? undefined : s.mode,
1408
+ only: damage === 'only' ? undefined : s.only,
1409
+ };
1410
+ }
1411
+
1412
+ /**
1413
+ * The entry a settings problem names when that problem is its mode or
1414
+ * `only`, or null.
1415
+ * @param {any} data
1416
+ * @param {string} problem
1417
+ */
1418
+ function damagedEntry(data, problem) {
1419
+ return (
1420
+ (Array.isArray(data?.settings) ? data.settings : []).find(
1421
+ (/** @type {any} */ s) =>
1422
+ (entryDamage(s) === 'source' &&
1423
+ typeof s.source === 'string' &&
1424
+ s.source !== '' &&
1425
+ problem.startsWith(`${s.thing} has source `)) ||
1426
+ (entryDamage(s) === 'mode' &&
1427
+ problem.startsWith(`${s.thing} has mode `)) ||
1428
+ (entryDamage(s) === 'only' &&
1429
+ problem.startsWith(`${s.thing} has only `)),
1430
+ ) ?? null
1431
+ );
1432
+ }
1433
+
1434
+ /**
1435
+ * Whether the command removes the setting it names (an undo): only that
1436
+ * takes an entry whose mode or source means nothing.
1437
+ * @param {string | Partial<Setting> | undefined} skip
1438
+ */
1439
+ function removes(skip) {
1440
+ return Boolean(
1441
+ skip && typeof skip === 'object' && /** @type {any} */ (skip).removing,
1442
+ );
1443
+ }
1444
+
1005
1445
  /**
1006
1446
  * Whether a setting is the one a command changes or removes: by thing, or
1007
1447
  * by the whole identity (part, variant, state, mode) when one is given.
@@ -1016,7 +1456,8 @@ function skips(s, skip) {
1016
1456
  (s.on ?? '') === (skip.on ?? '') &&
1017
1457
  (s.when ?? '') === (skip.when ?? '') &&
1018
1458
  (s.state ?? '') === (skip.state ?? '') &&
1019
- (s.mode ?? '') === (skip.mode ?? '')
1459
+ ((s.mode ?? '') === (skip.mode ?? '') ||
1460
+ (removes(skip) && !skip.mode && entryDamage(s) === 'mode'))
1020
1461
  );
1021
1462
  }
1022
1463
 
@@ -1040,12 +1481,41 @@ export function badSettings(data) {
1040
1481
  export function undoArgs(x) {
1041
1482
  return [
1042
1483
  quoteCommandArgument(String(x.thing)),
1484
+ // The tracking half of headings is named, so the undo reaches it even
1485
+ // when it is listed twice (a bare `undo headings` then reads the weight
1486
+ // half).
1487
+ ...(x.thing === 'headings' && x.axis === 'tracking' ? ['tracking'] : []),
1488
+ ...scopeFlags(x),
1489
+ ].join(' ');
1490
+ }
1491
+
1492
+ /**
1493
+ * The words of a `set` that gives a setting's scope a value: set reads a
1494
+ * headings half from its word, so no half is named.
1495
+ * @param {import('./_settings.mjs').Setting} x
1496
+ * @param {string} value
1497
+ */
1498
+ export function setArgs(x, value) {
1499
+ return [
1500
+ quoteCommandArgument(String(x.thing)),
1501
+ quoteCommandArgument(value),
1502
+ ...scopeFlags(x),
1503
+ ].join(' ');
1504
+ }
1505
+
1506
+ /**
1507
+ * The flags that name a setting's scope, as set and undo take them.
1508
+ * @param {import('./_settings.mjs').Setting} x
1509
+ * @returns {string[]}
1510
+ */
1511
+ function scopeFlags(x) {
1512
+ return [
1043
1513
  ...(x.on ? [`--on ${quoteCommandArgument(String(x.on))}`] : []),
1044
1514
  ...(x.when ? [`--when ${quoteCommandArgument(String(x.when))}`] : []),
1045
1515
  ...(x.state ? [`--state ${quoteCommandArgument(String(x.state))}`] : []),
1046
1516
  ...(x.mode ? [`--mode ${quoteCommandArgument(String(x.mode))}`] : []),
1047
1517
  ...(x.only ? ['--only'] : []),
1048
- ].join(' ');
1518
+ ];
1049
1519
  }
1050
1520
 
1051
1521
  /**
@@ -1111,6 +1581,17 @@ export function valueProblem(s) {
1111
1581
  const seed = colorProblem(s.value);
1112
1582
  if (seed) return `${bad} ${seed.message}`;
1113
1583
  }
1584
+ // `axis` names the half of headings a value sets; no other dial has
1585
+ // one, and each half takes only its own words.
1586
+ if (s.axis != null && s.thing !== 'headings')
1587
+ return `${s.thing} has an axis (${JSON.stringify(s.axis)}), which only headings takes`;
1588
+ if (s.thing === 'headings') {
1589
+ if (s.axis != null && s.axis !== 'weight' && s.axis !== 'tracking')
1590
+ return `headings has axis ${JSON.stringify(s.axis)}, not weight or tracking`;
1591
+ const half = s.axis === 'tracking' ? HEADING_TRACKING : HEADING_WEIGHTS;
1592
+ if (!Object.hasOwn(half, s.value))
1593
+ return `${bad} is not a ${s.axis ?? 'weight'} headings takes (${Object.keys(half).join('|')})`;
1594
+ }
1114
1595
  const words = d.values.split('|').filter(w => !w.startsWith('<'));
1115
1596
  const ok =
1116
1597
  s.thing === 'corners'
@@ -1133,6 +1614,30 @@ export function valueProblem(s) {
1133
1614
  return null;
1134
1615
  }
1135
1616
 
1617
+ /**
1618
+ * One entry of the top-level `tokens` map in a theme's own source, as
1619
+ * written: its token (null for a computed key no read of the file can
1620
+ * resolve), the key as typed, the line that sets it, and its value's shape.
1621
+ * A `duplicate` entry names a second `tokens` key (with every line); a
1622
+ * `typography` entry is one typography field (its dotted key and value);
1623
+ * an `unresolved` entry says the map holds something only a build reads.
1624
+ * @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, notToken?: boolean}} OwnTokenEntry
1625
+ */
1626
+
1627
+ /**
1628
+ * The entries of the top-level `tokens` map in a theme's own source, read
1629
+ * from its syntax tree, each with the line that sets it.
1630
+ * @param {string} cwd
1631
+ * @param {string} slug
1632
+ * @returns {OwnTokenEntry[]}
1633
+ */
1634
+ export function ownTokenEntries(cwd, slug) {
1635
+ /** @type {OwnTokenEntry[]} */
1636
+ const detail = [];
1637
+ ownPageTokens(cwd, slug, detail);
1638
+ return detail;
1639
+ }
1640
+
1136
1641
  /**
1137
1642
  * The page-wide tokens a theme's own source sets: the keys of the top-level
1138
1643
  * `tokens` map in its `defineTheme({...})`, read from the syntax tree, each
@@ -1142,7 +1647,11 @@ export function valueProblem(s) {
1142
1647
  * @param {string} slug
1143
1648
  * @returns {Map<string, string | null>}
1144
1649
  */
1145
- function ownPageTokens(cwd, slug) {
1650
+ function ownPageTokens(
1651
+ cwd,
1652
+ slug,
1653
+ detail = /** @type {OwnTokenEntry[] | null} */ (null),
1654
+ ) {
1146
1655
  /** @type {Map<string, string | null>} */
1147
1656
  const out = new Map();
1148
1657
  /** @type {string} */
@@ -1243,32 +1752,274 @@ function ownPageTokens(cwd, slug) {
1243
1752
  if (!chosen) return out;
1244
1753
  const def = unwrap(chosen.call.arguments[0]);
1245
1754
  if (def?.type !== 'ObjectExpression') return out;
1246
- const tokensProp = def.properties.find(
1755
+ // JavaScript keeps the last of two `tokens` keys: that one is read, and
1756
+ // both are named.
1757
+ const tokensProps = def.properties.filter(
1247
1758
  (/** @type {any} */ p) =>
1248
1759
  p.type === 'ObjectProperty' && !p.computed && keyOf(p.key) === 'tokens',
1249
1760
  );
1761
+ if (detail && tokensProps.length > 1)
1762
+ detail.push({
1763
+ token: null,
1764
+ key: 'tokens',
1765
+ kind: 'duplicate',
1766
+ line: tokensProps[0].loc?.start?.line ?? null,
1767
+ lines: tokensProps.map((/** @type {any} */ p) => p.loc?.start?.line),
1768
+ });
1769
+ // The typography fields, as written, for their own checks.
1770
+ const typo = def.properties.find(
1771
+ (/** @type {any} */ p) =>
1772
+ p.type === 'ObjectProperty' &&
1773
+ !p.computed &&
1774
+ keyOf(p.key) === 'typography',
1775
+ );
1776
+ if (detail && typo) {
1777
+ /** @param {any} node @param {string[]} at */
1778
+ const walk = (node, at) => {
1779
+ const obj = unwrap(node);
1780
+ if (obj?.type !== 'ObjectExpression') return;
1781
+ for (const p of obj.properties) {
1782
+ if (p.type !== 'ObjectProperty' || p.computed) continue;
1783
+ const k = keyOf(p.key);
1784
+ if (!k) continue;
1785
+ const v = unwrap(p.value);
1786
+ if (v?.type === 'ObjectExpression') walk(v, [...at, k]);
1787
+ else
1788
+ detail.push({
1789
+ token: null,
1790
+ key: [...at, k].join('.'),
1791
+ kind: 'typography',
1792
+ line: p.loc?.start?.line ?? null,
1793
+ expression:
1794
+ textOf(v) == null &&
1795
+ v?.type !== 'NumericLiteral' &&
1796
+ !(
1797
+ v?.type === 'UnaryExpression' &&
1798
+ v.argument?.type === 'NumericLiteral'
1799
+ ),
1800
+ value:
1801
+ textOf(v) ??
1802
+ (v?.type === 'NumericLiteral'
1803
+ ? v.value
1804
+ : v?.type === 'UnaryExpression' &&
1805
+ v.operator === '-' &&
1806
+ v.argument?.type === 'NumericLiteral'
1807
+ ? -v.argument.value
1808
+ : undefined),
1809
+ });
1810
+ }
1811
+ };
1812
+ walk(typo.value, []);
1813
+ }
1814
+ const tokensProp = tokensProps[tokensProps.length - 1];
1250
1815
  if (!tokensProp) return out;
1251
1816
  let unresolved = false;
1252
- /** @param {any} node @param {number} depth */
1253
- const collect = (node, depth) => {
1254
- const obj = unwrap(node);
1817
+ const dir = path.dirname(themeFiles(cwd, slug).ts);
1818
+ /**
1819
+ * The object a name imported from a file beside the theme gives (`import
1820
+ * {mine} from './mine'`, a default import of a .json file), read from
1821
+ * that file, with its own code and path; null for any other name.
1822
+ * @param {string} name
1823
+ * @returns {{obj: any, code: string, file: string, unwrap: (n: any) => any} | null}
1824
+ */
1825
+ const imported = name => {
1826
+ for (const st of ast.program.body) {
1827
+ if (st.type !== 'ImportDeclaration') continue;
1828
+ const spec = st.specifiers.find(
1829
+ (/** @type {any} */ x) => x.local?.name === name,
1830
+ );
1831
+ const from = String(st.source?.value ?? '');
1832
+ if (!spec || !from.startsWith('.')) continue;
1833
+ const base = path.resolve(dir, from);
1834
+ const file = [
1835
+ '',
1836
+ '.ts',
1837
+ '.mts',
1838
+ '.tsx',
1839
+ '.js',
1840
+ '.mjs',
1841
+ '.json',
1842
+ '/index.ts',
1843
+ ]
1844
+ .map(x => base + x)
1845
+ .find(f => {
1846
+ try {
1847
+ return fs.statSync(f).isFile();
1848
+ } catch {
1849
+ return false;
1850
+ }
1851
+ });
1852
+ if (!file) return null;
1853
+ try {
1854
+ const text = fs.readFileSync(file, 'utf8');
1855
+ const json = file.endsWith('.json');
1856
+ const source = json ? `export default ${text}` : text;
1857
+ const other = /** @type {any} */ (
1858
+ parseModule(source, {sourceType: 'module', plugins: ['typescript']})
1859
+ );
1860
+ /** @type {Map<string, any>} */
1861
+ const local = new Map();
1862
+ /** @type {any} */
1863
+ let found = null;
1864
+ const want =
1865
+ spec.type === 'ImportDefaultSpecifier'
1866
+ ? 'default'
1867
+ : (spec.imported?.name ?? spec.imported?.value);
1868
+ for (const top of other.program.body) {
1869
+ const d =
1870
+ top.type === 'ExportNamedDeclaration' ? top.declaration : top;
1871
+ for (const v of d?.declarations ?? [])
1872
+ if (v.id?.type === 'Identifier') {
1873
+ local.set(v.id.name, v.init);
1874
+ if (top.type === 'ExportNamedDeclaration' && v.id.name === want)
1875
+ found = v.init;
1876
+ }
1877
+ if (top.type === 'ExportDefaultDeclaration' && want === 'default')
1878
+ found = top.declaration;
1879
+ }
1880
+ /** @param {any} n @param {number} [k] @returns {any} */
1881
+ const unwrapIn = (n, k = 0) => {
1882
+ if (!n || k > 20) return null;
1883
+ if (
1884
+ [
1885
+ 'TSAsExpression',
1886
+ 'TSSatisfiesExpression',
1887
+ 'TSNonNullExpression',
1888
+ 'ParenthesizedExpression',
1889
+ ].includes(n.type)
1890
+ )
1891
+ return unwrapIn(n.expression, k + 1);
1892
+ if (n.type === 'Identifier' && local.has(n.name))
1893
+ return unwrapIn(local.get(n.name), k + 1);
1894
+ return n;
1895
+ };
1896
+ return found
1897
+ ? {obj: unwrapIn(found), code: source, file, unwrap: unwrapIn}
1898
+ : null;
1899
+ } catch {
1900
+ return null;
1901
+ }
1902
+ }
1903
+ return null;
1904
+ };
1905
+ /**
1906
+ * @param {any} node
1907
+ * @param {number} depth
1908
+ * @param {{code: string, file: string | null, unwrap: (n: any) => any}} [at]
1909
+ * the file the node is in (null for the theme file)
1910
+ */
1911
+ const collect = (node, depth, at = {code, file: null, unwrap}) => {
1912
+ const obj = at.unwrap(node);
1913
+ // A name imported from a file beside the theme: read in that file, so
1914
+ // its values and lines are its own; the build still judges the result.
1915
+ if (obj?.type === 'Identifier' && at.file == null) {
1916
+ const from = imported(obj.name);
1917
+ if (from) {
1918
+ unresolved = true;
1919
+ collect(from.obj, depth + 1, from);
1920
+ return;
1921
+ }
1922
+ }
1255
1923
  if (obj?.type !== 'ObjectExpression' || depth > 20) {
1256
1924
  unresolved = true;
1257
1925
  return;
1258
1926
  }
1259
- // Spreads and keys merge in order: a later one wins.
1927
+ // Spreads and keys merge in order: a later one wins. A computed key
1928
+ // that is text (`['--radius-page']`) is read like a literal one.
1260
1929
  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)));
1930
+ if (p.type === 'SpreadElement') collect(p.argument, depth + 1, at);
1931
+ else if (p.type === 'ObjectProperty') {
1932
+ const k = p.computed ? textOf(at.unwrap(p.key)) : keyOf(p.key);
1933
+ if (k?.startsWith('--')) out.set(k, builtText(at.unwrap(p.value)));
1934
+ else if (p.computed) unresolved = true;
1935
+ if (detail && (k || p.computed))
1936
+ detail.push({
1937
+ token: k?.startsWith('--') ? k : null,
1938
+ key: at.code.slice(p.key.start, p.key.end),
1939
+ line: p.loc?.start?.line ?? null,
1940
+ ...(at.file ? {file: at.file} : {}),
1941
+ // A key that is no token name (`color`): the build writes it
1942
+ // as a declaration on the theme's root.
1943
+ ...(k && !k.startsWith('--') ? {notToken: true} : {}),
1944
+ ...valueShape(at.unwrap(p.value), at.unwrap),
1945
+ });
1265
1946
  } else unresolved = true;
1266
1947
  }
1267
1948
  };
1949
+ /**
1950
+ * A token's value as the build writes it, when the file gives it as
1951
+ * text: a [light, dark] pair of two texts is its light-dark(); else
1952
+ * null.
1953
+ * @param {any} node
1954
+ * @returns {string | null}
1955
+ */
1956
+ const builtText = node => {
1957
+ const halves =
1958
+ node?.type === 'ArrayExpression' && node.elements.length === 2
1959
+ ? node.elements.map((/** @type {any} */ e) => textOf(unwrap(e)))
1960
+ : null;
1961
+ return halves && halves.every((/** @type {any} */ h) => h != null)
1962
+ ? `light-dark(${halves.join(', ')})`
1963
+ : textOf(node);
1964
+ };
1965
+ /**
1966
+ * What a token's value is, as written: text, a number, a [light, dark]
1967
+ * pair (each half's text, a number, or undefined), or something else.
1968
+ * @param {any} node
1969
+ * @param {(n: any) => any} [unwrapIn] how the node's file reads a name
1970
+ * @returns {Pick<OwnTokenEntry, 'kind' | 'value' | 'halves'>}
1971
+ */
1972
+ const valueShape = (node, unwrapIn = unwrap) => {
1973
+ const t = textOf(node);
1974
+ if (t != null) return {kind: 'text', value: t};
1975
+ if (node?.type === 'NumericLiteral')
1976
+ return {kind: 'number', value: node.value};
1977
+ if (node?.type === 'ArrayExpression')
1978
+ return {
1979
+ kind: 'pair',
1980
+ halves: node.elements.map((/** @type {any} */ e) => {
1981
+ const h = unwrapIn(e);
1982
+ return (
1983
+ textOf(h) ?? (h?.type === 'NumericLiteral' ? h.value : undefined)
1984
+ );
1985
+ }),
1986
+ };
1987
+ if (node?.type === 'ObjectExpression')
1988
+ return {
1989
+ kind: 'object',
1990
+ value: Object.fromEntries(
1991
+ node.properties
1992
+ .filter((/** @type {any} */ p) => p.type === 'ObjectProperty')
1993
+ .map((/** @type {any} */ p) => [
1994
+ keyOf(p.key) ?? '?',
1995
+ textOf(unwrap(p.value)) ?? null,
1996
+ ]),
1997
+ ),
1998
+ };
1999
+ return {kind: 'other'};
2000
+ };
1268
2001
  collect(tokensProp.value, 0);
2002
+ // Only the last entry for a token is what the build writes: an earlier
2003
+ // one a later key or spread overrides is marked, never judged.
2004
+ if (detail) {
2005
+ /** @type {Map<string, number>} */
2006
+ const last = new Map();
2007
+ detail.forEach((e, i) => {
2008
+ if (e.token) last.set(e.token, i);
2009
+ });
2010
+ detail.forEach((e, i) => {
2011
+ if (e.token && last.get(e.token) !== i) e.overridden = true;
2012
+ });
2013
+ }
1269
2014
  // A value no read of the file can resolve (a call, an import) is read
1270
2015
  // from the build (ownTokens), and checked again after the next one.
1271
- void unresolved;
2016
+ if (detail && unresolved)
2017
+ detail.push({
2018
+ token: null,
2019
+ key: 'tokens',
2020
+ kind: 'unresolved',
2021
+ line: tokensProp.loc?.start?.line ?? null,
2022
+ });
1272
2023
  return out;
1273
2024
  }
1274
2025
 
@@ -1541,6 +2292,27 @@ export function partRuleTokens(cwd, slug, like, part) {
1541
2292
  return out;
1542
2293
  }
1543
2294
 
2295
+ /**
2296
+ * Whether the base theme's own source gives a part's rule a property, in a
2297
+ * state (`:hover`) or at rest, read from its module as written.
2298
+ * @param {string} cwd
2299
+ * @param {string | undefined} like
2300
+ * @param {string} part
2301
+ * @param {string} scope `base` or a variant such as `variant:secondary`
2302
+ * @param {string | null} state a state block (`:hover`), or null
2303
+ * @param {string} prop camelCase
2304
+ */
2305
+ export function baseRuleHas(cwd, like, part, scope, state, prop) {
2306
+ const file = like ? baseModule(cwd, like) : null;
2307
+ if (!file) return false;
2308
+ try {
2309
+ const at = ['components', part, scope, ...(state ? [state] : [])];
2310
+ return blockOf(file, at).has(prop);
2311
+ } catch {
2312
+ return false;
2313
+ }
2314
+ }
2315
+
1544
2316
  /**
1545
2317
  * The tokens and properties a theme's own source sets on a part's plain
1546
2318
  * rule, read from the build as ownTokens reads page-wide ones: what the
@@ -1621,7 +2393,7 @@ function ownTokens(cwd, slug) {
1621
2393
  * @param {string} slug
1622
2394
  * @returns {Map<string, string | null> | null}
1623
2395
  */
1624
- function builtOwnTokens(cwd, slug) {
2396
+ function builtOwnTokens(cwd, slug, js = /** @type {string | null} */ (null)) {
1625
2397
  const f = themeFiles(cwd, slug);
1626
2398
  /** @type {string} */
1627
2399
  let module;
@@ -1633,7 +2405,10 @@ function builtOwnTokens(cwd, slug) {
1633
2405
  const built = /\/\/ Built with \S+\.theme\.ts ([0-9a-f]{16})\./.exec(
1634
2406
  module,
1635
2407
  )?.[1];
1636
- if (!built || !fs.existsSync(f.js) || built !== themeSourceHash(cwd, slug))
2408
+ if (
2409
+ !js &&
2410
+ (!built || !fs.existsSync(f.js) || built !== themeSourceHash(cwd, slug))
2411
+ )
1637
2412
  return null;
1638
2413
  // What the settings module gives each top-level token: a text value as
1639
2414
  // it is, a [light, dark] pair as a pair.
@@ -1688,7 +2463,7 @@ function builtOwnTokens(cwd, slug) {
1688
2463
  const named = namedInOwnSource(cwd, slug);
1689
2464
  /** @type {Map<string, string | null>} */
1690
2465
  const out = new Map();
1691
- for (const [k, v] of builtTopTokens(cwd, slug)) {
2466
+ for (const [k, v] of js ? topTokensOf(js) : builtTopTokens(cwd, slug)) {
1692
2467
  const given = settings.get(k);
1693
2468
  const own =
1694
2469
  given === undefined
@@ -1774,7 +2549,7 @@ export function ownSourceTokenValues(cwd, slug) {
1774
2549
  function scopeProblem(s) {
1775
2550
  if (s.on != null && !/^[a-z][a-z0-9-]*$/.test(s.on))
1776
2551
  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))
2552
+ if (s.state != null && !/^[a-z][a-zA-Z-]*$/.test(s.state))
1778
2553
  return `${s.thing} has state "${s.state}", which is not a state name`;
1779
2554
  if (s.when != null && !/^[\w-]+:[\w.-]+$/.test(s.when))
1780
2555
  return `${s.thing} has --when "${s.when}", which is not prop:value`;
@@ -1787,7 +2562,10 @@ function scopeProblem(s) {
1787
2562
  export const keyOf = s =>
1788
2563
  [
1789
2564
  s.thing,
1790
- s.axis ?? '',
2565
+ // A headings value saved with no axis is its weight half, as the build
2566
+ // reads it, so a set or undo of the weight replaces it. Only headings
2567
+ // has halves: an axis on any other setting names nothing.
2568
+ s.thing === 'headings' ? (s.axis ?? 'weight') : '',
1791
2569
  s.on ?? '',
1792
2570
  s.when ?? '',
1793
2571
  s.state ?? '',
@@ -1843,7 +2621,19 @@ export function lengthPx(v) {
1843
2621
  /** @param {string} v */
1844
2622
  export const cornerPx = v =>
1845
2623
  CORNERS.find(([n]) => n === v)?.[1] ?? parseFloat(v);
1846
- /** @param {string} v */
2624
+ /**
2625
+ * The base theme's body text size in px, read back from its built base
2626
+ * size (14 when it writes none).
2627
+ * @param {{light: Record<string, string>}} base
2628
+ */
2629
+ export function baseTextPx(base) {
2630
+ const v = base?.light?.['--font-size-base'];
2631
+ return /^[\d.]+rem$/.test(v ?? '')
2632
+ ? Math.round(Number.parseFloat(String(v)) * 16)
2633
+ : 14;
2634
+ }
2635
+
2636
+ /** @param {string} v */
1847
2637
  export const textPx = v => TEXT_SIZE.find(([n]) => n === v)?.[1] ?? Number(v);
1848
2638
 
1849
2639
  /**
@@ -1959,6 +2749,44 @@ function partDefault(ctx, target, prop, when, state) {
1959
2749
  return r ? `var(${r.token})` : null;
1960
2750
  }
1961
2751
 
2752
+ /**
2753
+ * The variants (`variant:<name>`) of a part that each read their own value
2754
+ * of a color property (the button's background, a badge's text), in a
2755
+ * state when one is named and changes it: one rule's other-mode half would
2756
+ * give every one of them one variant's color. Empty when the part reads one
2757
+ * value for all.
2758
+ * @param {Ctx} ctx
2759
+ * @param {string} target
2760
+ * @param {string} prop camelCase or kebab-case
2761
+ * @param {string} [state]
2762
+ * @returns {string[]}
2763
+ */
2764
+ function variantsReading(ctx, target, prop, state) {
2765
+ const k = kebab(prop);
2766
+ const g = ctx.C.groupOfProp(k === 'background' ? 'background-color' : k);
2767
+ if (!g) return [];
2768
+ const reads = ctx.C.partReads(target, g).filter(x =>
2769
+ x.props.some(
2770
+ p => p === k || (k === 'background' && p === 'background-color'),
2771
+ ),
2772
+ );
2773
+ const named = (/** @type {(w: string) => boolean} */ ok) => [
2774
+ ...new Set(
2775
+ reads
2776
+ .flatMap(x => x.when)
2777
+ .filter(ok)
2778
+ .map(w => /(?:^|,)variant=([\w-]+)/.exec(w)?.[1])
2779
+ .filter(Boolean)
2780
+ .map(n => `variant:${n}`),
2781
+ ),
2782
+ ];
2783
+ const inState = state ? named(w => w.includes(`:${state}`)) : [];
2784
+ if (inState.length) return inState;
2785
+ return reads.some(x => x.when.includes(''))
2786
+ ? []
2787
+ : named(w => /^variant=[\w-]+$/.test(w));
2788
+ }
2789
+
1962
2790
  /** The line that records a generated module's own hash. */
1963
2791
  const SEAL = /^\/\/ Module ([0-9a-f]{16})\.\n/m;
1964
2792
 
@@ -2101,6 +2929,138 @@ function keepShades(pal, kept) {
2101
2929
  return {...pal, tokens, lift: kept['lifted parts'] ? pal.lift : null};
2102
2930
  }
2103
2931
 
2932
+ /**
2933
+ * A size in px: px, rem (16px each), or a calc() of those added and
2934
+ * subtracted; null for anything else.
2935
+ * @param {string} v
2936
+ * @param {Record<string, string>} [vars] values for the tokens a var() may name
2937
+ * @returns {number | null}
2938
+ */
2939
+ export function sizePx(v, vars = {}) {
2940
+ let t = String(v).trim();
2941
+ // A token the dial or the theme gives a value (var(--spacing-12)),
2942
+ // through that value; a clamp() at its preferred value held to its
2943
+ // bounds, or its upper bound when the preferred one is no length;
2944
+ // min() and max() of the lengths they hold.
2945
+ const fn = /^(var|clamp|min|max)\((.*)\)$/is.exec(t);
2946
+ if (fn) {
2947
+ const args = splitTop(fn[2], ',').map(x => x.trim());
2948
+ if (fn[1].toLowerCase() === 'var') {
2949
+ const own = vars[args[0]];
2950
+ if (own != null) return sizePx(own, vars);
2951
+ return args[1] != null ? sizePx(args.slice(1).join(','), vars) : null;
2952
+ }
2953
+ const n = args.map(x => sizePx(x, vars));
2954
+ if (fn[1].toLowerCase() === 'clamp') {
2955
+ const [lo, mid, hi] = n;
2956
+ if (lo == null || hi == null) return null;
2957
+ return mid == null ? hi : Math.min(hi, Math.max(lo, mid));
2958
+ }
2959
+ const known = /** @type {number[]} */ (n.filter(x => x != null));
2960
+ if (!known.length) return null;
2961
+ return fn[1].toLowerCase() === 'min'
2962
+ ? Math.min(...known)
2963
+ : Math.max(...known);
2964
+ }
2965
+ const calc = /^calc\((.*)\)$/is.exec(t);
2966
+ if (calc) t = calc[1].trim();
2967
+ const terms =
2968
+ t.match(/[+-]?\s*[\d.]+(?:px|rem|em|pt|pc|in|cm|mm|q)\b|\S+/gi) ?? [];
2969
+ let sum = 0;
2970
+ let sign = 1;
2971
+ for (const raw of terms) {
2972
+ const x = raw.replace(/\s+/g, '');
2973
+ if (x === '+' || x === '-') {
2974
+ if (!calc) return null;
2975
+ sign = x === '-' ? -1 : 1;
2976
+ continue;
2977
+ }
2978
+ const m = /^([+-]?)([\d.]+)(px|rem|em|pt|pc|in|cm|mm|q)$/i.exec(x);
2979
+ if (!m || (!calc && terms.length > 1)) return null;
2980
+ // Absolute units by their fixed ratio to px; em and rem against the
2981
+ // 16px a control's text starts from.
2982
+ const n = parseFloat(m[2]) * (PX_PER[m[3].toLowerCase()] ?? 1);
2983
+ if (!Number.isFinite(n)) return null;
2984
+ sum += (m[1] === '-' ? -1 : 1) * sign * n;
2985
+ sign = 1;
2986
+ }
2987
+ return terms.length ? sum : null;
2988
+ }
2989
+
2990
+ /** Pixels per unit of each length unit a kept size may be written in. */
2991
+ const PX_PER = /** @type {Record<string, number>} */ ({
2992
+ px: 1,
2993
+ rem: 16,
2994
+ em: 16,
2995
+ pt: 96 / 72,
2996
+ pc: 16,
2997
+ in: 96,
2998
+ cm: 96 / 2.54,
2999
+ mm: 96 / 25.4,
3000
+ q: 96 / 101.6,
3001
+ });
3002
+
3003
+ /**
3004
+ * Spacing steps scaled with the spacing dial, kept in order around the
3005
+ * steps the theme keeps exact: each the plain scaled value unless it would
3006
+ * meet or pass a kept one; those are spread evenly between the kept one and
3007
+ * the nearest step that keeps its place. A step with no room below a kept
3008
+ * one takes the value of the one below it.
3009
+ * @param {Array<[string, number]>} steps token name and the base value, in px
3010
+ * @param {number} f the rung's factor
3011
+ * @param {Record<string, number>} kept exact steps the theme keeps, in px
3012
+ * @param {string[]} [noRoom] filled with the steps left no room
3013
+ * @returns {Array<[string, number]>} every step's new value in px, kept ones as kept
3014
+ */
3015
+ export function spacingSteps(steps, f, kept, noRoom = []) {
3016
+ const px = [...steps].sort((a, b) => a[1] - b[1]);
3017
+ const n = px.map(([k, v]) => (k in kept ? kept[k] : v * f));
3018
+ const isKept = (/** @type {number} */ i) => px[i][0] in kept;
3019
+ px.forEach(([, base], k) => {
3020
+ if (!isKept(k)) return;
3021
+ // The steps below that would meet or pass it are spread evenly between
3022
+ // the last one that does not and it.
3023
+ let j0 = k;
3024
+ while (
3025
+ j0 > 0 &&
3026
+ !isKept(j0 - 1) &&
3027
+ n[j0 - 1] >= n[k] &&
3028
+ px[j0 - 1][1] < base
3029
+ )
3030
+ j0--;
3031
+ if (j0 < k) {
3032
+ const lo = j0 > 0 ? n[j0 - 1] : 0;
3033
+ if (lo >= n[k])
3034
+ for (let j = j0; j < k; j++) {
3035
+ n[j] = lo;
3036
+ noRoom.push(px[j][0]);
3037
+ }
3038
+ else
3039
+ for (let j = j0; j < k; j++)
3040
+ n[j] = lo + ((n[k] - lo) * (j - j0 + 1)) / (k - j0 + 1);
3041
+ }
3042
+ // The steps above that would meet or fall under it, likewise up to the
3043
+ // next one that does not (or above it by their own scaled steps).
3044
+ let j1 = k;
3045
+ while (
3046
+ j1 < n.length - 1 &&
3047
+ !isKept(j1 + 1) &&
3048
+ n[j1 + 1] <= n[k] &&
3049
+ px[j1 + 1][1] > base
3050
+ )
3051
+ j1++;
3052
+ if (j1 > k) {
3053
+ const hi = j1 < n.length - 1 ? n[j1 + 1] : null;
3054
+ for (let j = k + 1; j <= j1; j++)
3055
+ n[j] =
3056
+ hi == null
3057
+ ? n[k] + (px[j][1] - base) * f
3058
+ : n[k] + ((hi - n[k]) * (j - k)) / (j1 - k + 1);
3059
+ }
3060
+ });
3061
+ return px.map(([k], i) => [k, n[i]]);
3062
+ }
3063
+
2104
3064
  /**
2105
3065
  * Control heights scaled with the spacing dial (a denser theme has shorter
2106
3066
  * controls), each kept distinct and in order: smallest to largest, a
@@ -2110,28 +3070,44 @@ function keepShades(pal, kept) {
2110
3070
  * scaled above it.
2111
3071
  * @param {Array<[string, string]>} sizes token name and the theme's value
2112
3072
  * @param {number} f the spacing rung's factor
3073
+ * @param {Record<string, number>} [kept] exact sizes the theme keeps, in px,
3074
+ * which the others stay in order around
3075
+ * @param {string[]} [noRoom] filled with the sizes left no room between
3076
+ * two kept ones (each then equals the one below it)
2113
3077
  * @returns {Array<[string, string]>} the tokens it writes, in px
2114
3078
  */
2115
- export function controlSizes(sizes, f) {
3079
+ export function controlSizes(sizes, f, kept = {}, noRoom = []) {
2116
3080
  const px = sizes
2117
3081
  .filter(([, v]) => /^[\d.]+px$/.test(String(v).trim()))
2118
3082
  .map(([k, v]) => /** @type {[string, number]} */ ([k, parseFloat(v)]))
2119
3083
  .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;
3084
+ /** @type {number[]} */
3085
+ const n = px.map(([k, v]) =>
3086
+ k in kept ? kept[k] : Math.max(Math.min(24, v), Math.round(v * f)),
3087
+ );
3088
+ /** The step between two sizes, scaled. @param {number} i */
3089
+ const step = i => Math.max(1, Math.round((px[i][1] - px[i - 1][1]) * f));
3090
+ // Only a size that would meet (or pass) the one below moves, up; then one
3091
+ // that would meet a kept size above it moves down (a kept size stays).
3092
+ for (let i = 1; i < n.length; i++)
3093
+ if (!(px[i][0] in kept) && n[i] <= n[i - 1]) n[i] = n[i - 1] + step(i);
3094
+ for (let i = n.length - 2; i >= 0; i--)
3095
+ if (!(px[i][0] in kept) && n[i] >= n[i + 1]) n[i] = n[i + 1] - step(i + 1);
3096
+ // A size between two that cannot both move (kept, or one kept and the
3097
+ // other already at its place) sits halfway between them; with no room
3098
+ // between them it takes the smaller one's size, and the result says so.
3099
+ for (let i = 1; i < n.length - 1; i++)
3100
+ if (!(px[i][0] in kept) && (n[i] <= n[i - 1] || n[i] >= n[i + 1])) {
3101
+ const mid = Math.round(((n[i - 1] + n[i + 1]) / 2) * 2) / 2;
3102
+ if (mid > n[i - 1] && mid < n[i + 1]) n[i] = mid;
3103
+ else {
3104
+ n[i] = n[i - 1];
3105
+ noRoom.push(px[i][0]);
3106
+ }
3107
+ }
3108
+ return px
3109
+ .map(([k], i) => /** @type {[string, string]} */ ([k, `${n[i]}px`]))
3110
+ .filter(([k]) => !(k in kept));
2135
3111
  }
2136
3112
 
2137
3113
  /**
@@ -2142,6 +3118,8 @@ export function controlSizes(sizes, f) {
2142
3118
  * @returns {any}
2143
3119
  */
2144
3120
  export function compileTheme(ctx, data, base) {
3121
+ ctx.sizeNotes = [];
3122
+ ctx.compileNotes = [];
2145
3123
  // A setting the editor no longer accepts never reaches the build.
2146
3124
  data = {...data, settings: data.settings.filter(s => !valueProblem(s))};
2147
3125
  const TOKENS = ctx.project.core.tokenDefaults;
@@ -2153,7 +3131,7 @@ export function compileTheme(ctx, data, base) {
2153
3131
  rem(base.light['--font-size-base']),
2154
3132
  rem(base.light['--font-size-2xl']),
2155
3133
  ];
2156
- const baseSize = b0 ? Math.round(b0 * 16) : 14;
3134
+ const baseSize = baseTextPx(base);
2157
3135
  const baseRatio =
2158
3136
  b0 && b3 ? Math.round((b3 / b0) ** (1 / 3) * 100) / 100 : 1.2;
2159
3137
  /** @type {any} */
@@ -2164,6 +3142,44 @@ export function compileTheme(ctx, data, base) {
2164
3142
  : data.mode === 'dark-only'
2165
3143
  ? 'dark'
2166
3144
  : null;
3145
+ /** The tokens the theme's own source sets, which win over the settings. */
3146
+ /** @type {Record<string, string> | null} */
3147
+ let ownTok = null;
3148
+ const ownTokenValues = () => {
3149
+ if (ownTok) return ownTok;
3150
+ try {
3151
+ ownTok = ownSourceTokenValues(ctx.project.cwd, data.name);
3152
+ } catch {
3153
+ ownTok = {};
3154
+ }
3155
+ return ownTok;
3156
+ };
3157
+ /**
3158
+ * The exact tokens kept where a dial writes (whole theme with no part):
3159
+ * the whole-theme settings', then the own source's, by name.
3160
+ * @param {string | null} t a part, for its own settings too
3161
+ * @returns {Map<string, string>}
3162
+ */
3163
+ const keptTokens = t => {
3164
+ /** @type {Map<string, string>} */
3165
+ const out = new Map();
3166
+ for (const x of data.settings)
3167
+ if (
3168
+ x.source === 'token' &&
3169
+ !x.when &&
3170
+ !x.state &&
3171
+ !(modeOnly && x.mode && x.mode !== modeOnly) &&
3172
+ (!x.on || (t != null && partsOf(ctx, x).includes(t)))
3173
+ )
3174
+ out.set(x.thing, String(x.value));
3175
+ for (const [k, v] of Object.entries(ownTokenValues())) out.set(k, v);
3176
+ return out;
3177
+ };
3178
+ /** @param {string | null} t */
3179
+ const keptSizes = t =>
3180
+ [...keptTokens(t)].filter(([k]) => /^--size-element-/.test(k));
3181
+ /** The one-mode gradient layers each block holds, by mode. @type {WeakMap<object, {light: string[], dark: string[]}>} */
3182
+ const modeLayers = new WeakMap();
2167
3183
  /** @type {Record<string, {light?: string, dark?: string}>} */
2168
3184
  const tok = {};
2169
3185
  /** @param {string} name @param {string | [string, string]} v @param {string} [mode] */
@@ -2177,12 +3193,22 @@ export function compileTheme(ctx, data, base) {
2177
3193
  if (!mode || mode === 'dark') t.dark = v[1];
2178
3194
  return;
2179
3195
  }
2180
- if (!MODAL.has(ctx.C.typeOf(name)) || modeOnly || !mode) {
3196
+ // A color set in a one-mode theme fills its mode's half only; the other
3197
+ // half keeps what it had (the base theme's), for the regions Core draws
3198
+ // in the other mode.
3199
+ const half = mode ?? modeOnly;
3200
+ // Only a color has a half per mode (light-dark() takes colors only): a
3201
+ // shadow or any other value in a one-mode theme is written whole.
3202
+ if (
3203
+ !MODAL.has(ctx.C.typeOf(name)) ||
3204
+ !half ||
3205
+ (!mode && !parseColor(String(v).trim()))
3206
+ ) {
2181
3207
  t.light = v;
2182
3208
  t.dark = v;
2183
3209
  return;
2184
3210
  }
2185
- t[/** @type {'light' | 'dark'} */ (mode)] = v;
3211
+ t[/** @type {'light' | 'dark'} */ (half)] = v;
2186
3212
  };
2187
3213
  /** @param {Setting} s @param {string} target @returns {Record<string, any>} */
2188
3214
  const block = (s, target) => {
@@ -2471,9 +3497,11 @@ export function compileTheme(ctx, data, base) {
2471
3497
  return n && n.unit === '' && n.value === 0 ? '0px' : v;
2472
3498
  };
2473
3499
  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;
3500
+ // The own source's padding on the same rule wins over the editor's on
3501
+ // the sides it sets (the result says so); the editor's other sides
3502
+ // still apply.
3503
+ const own = ownBox(target, s);
3504
+ if (own.ltr.size === 4 && own.rtl.size === 4) continue;
2477
3505
  const prefix = /** @type {string} */ (padVars(target));
2478
3506
  const owner = prefix.slice('--astryx-'.length, -'-padding'.length);
2479
3507
  const scoped = target !== owner || s.when != null || s.state != null;
@@ -2517,6 +3545,10 @@ export function compileTheme(ctx, data, base) {
2517
3545
  }
2518
3546
  }
2519
3547
  }
3548
+ // The sides the own source pads in a direction are its own there.
3549
+ for (const dir of /** @type {const} */ (['ltr', 'rtl']))
3550
+ for (const x of Object.keys(side[dir]))
3551
+ if (own[dir].has(boxSide(x, dir))) delete side[dir][x];
2520
3552
  /** @type {Record<string, string>} */
2521
3553
  let plain = {};
2522
3554
  /** @type {Record<string, string>} */
@@ -2586,6 +3618,78 @@ export function compileTheme(ctx, data, base) {
2586
3618
  b[key] = {...(b[key] ?? {}), ...rule};
2587
3619
  }
2588
3620
  }
3621
+ // A variant the own source pads: the sides it sets are left without a
3622
+ // side variable there, so the variant's own padding (which Core writes
3623
+ // as the whole padding) wins over any side the plain rule writes.
3624
+ for (const owner of new Set(
3625
+ [...padQueue.values()]
3626
+ .filter(({target, s}) => !s.when && !s.state && padVars(target))
3627
+ .map(({target}) =>
3628
+ /** @type {string} */ (padVars(target)).slice(
3629
+ '--astryx-'.length,
3630
+ -'-padding'.length,
3631
+ ),
3632
+ ),
3633
+ )) {
3634
+ const values = ctx.C.variantValues(owner);
3635
+ for (const [prop, vals] of Object.entries(values ?? {}))
3636
+ for (const v of /** @type {string[]} */ (vals ?? [])) {
3637
+ const when = `${prop}:${v}`;
3638
+ const own = ownBox(owner, /** @type {any} */ ({when}));
3639
+ if (!own.ltr.size && !own.rtl.size) continue;
3640
+ const variant = /** @type {any} */ ({when});
3641
+ const logical = [
3642
+ 'block-start',
3643
+ 'block-end',
3644
+ 'inline-start',
3645
+ 'inline-end',
3646
+ ];
3647
+ const at = (/** @type {'ltr' | 'rtl'} */ dir) =>
3648
+ logical.filter(x => own[dir].has(boxSide(x, dir)));
3649
+ const [l, r] = [at('ltr'), at('rtl')];
3650
+ const b = block(variant, owner);
3651
+ for (const x of l.filter(x => r.includes(x)))
3652
+ b[`--astryx-${owner}-padding-${x}`] ??= 'initial';
3653
+ // A pair variable the plain rule writes (the inline or block
3654
+ // padding) feeds both its sides, under the side variables: where
3655
+ // the own source pads both, it is left without a value too, so
3656
+ // the variant's own padding holds there.
3657
+ for (const pair of ['block', 'inline'])
3658
+ if (
3659
+ [`${pair}-start`, `${pair}-end`].every(
3660
+ x => l.includes(x) && r.includes(x),
3661
+ )
3662
+ )
3663
+ b[`--astryx-${owner}-padding-${pair}`] ??= 'initial';
3664
+ // Its own sides inherit into a plain one of the part inside it:
3665
+ // they are reset there like the editor's (below).
3666
+ const sel = narrowSelector(owner, variant);
3667
+ if (sel) {
3668
+ const bySel = narrow.get(owner) ?? new Map();
3669
+ const names = bySel.get(sel) ?? new Set();
3670
+ for (const x of new Set([...l, ...r]))
3671
+ names.add(`--astryx-${owner}-padding-${x}`);
3672
+ for (const pair of ['block', 'inline'])
3673
+ if ([...l, ...r].some(x => x.startsWith(pair)))
3674
+ names.add(`--astryx-${owner}-padding-${pair}`);
3675
+ bySel.set(sel, names);
3676
+ narrow.set(owner, bySel);
3677
+ }
3678
+ for (const [dir, xs] of /** @type {const} */ ([
3679
+ [':dir(ltr)', l.filter(x => !r.includes(x))],
3680
+ [':dir(rtl)', r.filter(x => !l.includes(x))],
3681
+ ]))
3682
+ if (xs.length) {
3683
+ const [db, key] = dirBlock(variant, owner, dir);
3684
+ db[key] = {
3685
+ ...(db[key] ?? {}),
3686
+ ...Object.fromEntries(
3687
+ xs.map(x => [`--astryx-${owner}-padding-${x}`, 'initial']),
3688
+ ),
3689
+ };
3690
+ }
3691
+ }
3692
+ }
2589
3693
  // A plain part inside a narrower one: each side the narrower selector
2590
3694
  // writes is reset (left without a value, so Core's own fallback holds),
2591
3695
  // on the part's own class at its own weight, before any base setting a
@@ -2668,25 +3772,66 @@ export function compileTheme(ctx, data, base) {
2668
3772
  return out;
2669
3773
  };
2670
3774
  /**
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).
3775
+ * The box side a padding side names in a direction: a physical side as it
3776
+ * is, a logical one as the direction reads it (inline-start is the left in
3777
+ * left-to-right text, the right in right-to-left).
3778
+ * @param {string} x top, right, bottom, left, or a logical side
3779
+ * @param {'ltr' | 'rtl'} dir
3780
+ */
3781
+ const boxSide = (x, dir) =>
3782
+ ({
3783
+ 'block-start': 'top',
3784
+ 'block-end': 'bottom',
3785
+ 'inline-start': dir === 'ltr' ? 'left' : 'right',
3786
+ 'inline-end': dir === 'ltr' ? 'right' : 'left',
3787
+ })[x] ?? x;
3788
+ /**
3789
+ * The padding sides a padding property names, as it names them (physical
3790
+ * stays physical, logical stays logical), with each one's value.
3791
+ * @param {string} prop kebab-case
3792
+ * @param {string} value
3793
+ * @returns {Record<string, string>}
3794
+ */
3795
+ const paddingSides = (prop, value) => {
3796
+ const w = splitTop(String(value).trim(), ' ').map(y => y.trim());
3797
+ if (prop === 'padding') {
3798
+ const [top, right = top, bottom = top, left = right] = w;
3799
+ return {top, right, bottom, left};
3800
+ }
3801
+ if (prop === 'padding-block')
3802
+ return {'block-start': w[0], 'block-end': w[1] ?? w[0]};
3803
+ if (prop === 'padding-inline')
3804
+ return {'inline-start': w[0], 'inline-end': w[1] ?? w[0]};
3805
+ const side = prop.slice('padding-'.length);
3806
+ return /^(top|right|bottom|left|(block|inline)-(start|end))$/.test(side)
3807
+ ? {[side]: w[0]}
3808
+ : {};
3809
+ };
3810
+ /**
3811
+ * The box sides the theme's own source pads on a part's rule for a scope
3812
+ * (its plain rule, a variant, a state), in each direction.
2673
3813
  * @param {string} target @param {Setting} s
3814
+ * @returns {Record<'ltr' | 'rtl', Set<string>>}
2674
3815
  */
2675
- const ownPads = (target, s) => {
3816
+ const ownBox = (target, s) => {
3817
+ const out = {ltr: new Set(), rtl: new Set()};
2676
3818
  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));
3819
+ for (const k of ownPartTokens(
3820
+ ctx.project.cwd,
3821
+ data.name,
3822
+ target,
3823
+ s.when ?? 'base',
3824
+ s.state ? `:${s.state}` : null,
3825
+ ).keys())
3826
+ for (const x of Object.keys(paddingSides(k, '0')))
3827
+ for (const dir of /** @type {const} */ (['ltr', 'rtl']))
3828
+ out[dir].add(boxSide(x, dir));
2686
3829
  } catch {
2687
- return false;
3830
+ // No own source.
2688
3831
  }
3832
+ return out;
2689
3833
  };
3834
+
2690
3835
  /**
2691
3836
  * The selector a narrower padding scope is written with (a clickable
2692
3837
  * card's class, a variant's attribute, a state's pseudo-class), or null
@@ -2712,11 +3857,18 @@ export function compileTheme(ctx, data, base) {
2712
3857
  const keys = Object.keys(b);
2713
3858
  const plain = keys.filter(k => !k.startsWith(':'));
2714
3859
  const dirs = keys.filter(k => /^:(where\()?dir\(/.test(k));
3860
+ // The reset a plain part inside a narrower one gets comes before the
3861
+ // part's own direction rules at the same weight, so a side the part
3862
+ // sets for a direction holds inside a variant too.
3863
+ const resets = keys.filter(k => /^:where\((?!:?dir\().* \*\)$/.test(k));
2715
3864
  const rest = keys.filter(
2716
- k => k.startsWith(':') && !/^:(where\()?dir\(/.test(k),
3865
+ k =>
3866
+ k.startsWith(':') &&
3867
+ !/^:(where\()?dir\(/.test(k) &&
3868
+ !resets.includes(k),
2717
3869
  );
2718
3870
  return Object.fromEntries(
2719
- [...plain, ...dirs, ...rest].map(k => [
3871
+ [...plain, ...resets, ...dirs, ...rest].map(k => [
2720
3872
  k,
2721
3873
  k.startsWith(':') && b[k] && typeof b[k] === 'object'
2722
3874
  ? dirFirst(b[k])
@@ -2767,16 +3919,342 @@ export function compileTheme(ctx, data, base) {
2767
3919
  const parent = block({...s, state: undefined}, target);
2768
3920
  return [parent, `${stateKey(s.state, wrapsOneControl(ctx, target))}${dir}`];
2769
3921
  };
3922
+ /**
3923
+ * One half of a light-dark() pair (1 light, 2 dark), or the value itself.
3924
+ * @param {string} x @param {1 | 2} side
3925
+ */
3926
+ const halfOf = (x, side) => {
3927
+ const inner = /^light-dark\((.*)\)$/s.exec(x.trim())?.[1];
3928
+ const halves = inner == null ? [] : splitTop(inner, ',');
3929
+ return halves.length === 2 ? halves[side - 1].trim() : x.trim();
3930
+ };
3931
+ /**
3932
+ * The value a variant of a part shows for a color property where the
3933
+ * theme sets none of its own: the base theme's rule for that variant (in
3934
+ * the state, else at rest), else Core's, else transparent for a
3935
+ * background Core never paints; null for a text color Core never sets.
3936
+ * @param {string} target @param {string} css a color longhand, kebab-case
3937
+ * @param {string} name the variant @param {string} [state]
3938
+ * @param {boolean} [stateOnly] the state's own value only, never the resting one
3939
+ * @returns {string | null}
3940
+ */
3941
+ const exactVariantValue = (target, css, name, state, stateOnly = false) => {
3942
+ const when = `variant:${name}`;
3943
+ const kebabs =
3944
+ css === 'background-color' ? ['background-color', 'background'] : [css];
3945
+ const props = kebabs.map(camel);
3946
+ const steps = state
3947
+ ? stateOnly
3948
+ ? [state]
3949
+ : [state, undefined]
3950
+ : [undefined];
3951
+ for (const st of steps)
3952
+ for (const p of props) {
3953
+ const b = baseComponent(base, ctx, target, p, {when, state: st});
3954
+ if (b != null) return b;
3955
+ }
3956
+ const keyOf = (/** @type {string} */ k) => {
3957
+ const [attrs, cond = ''] = k.split(' ');
3958
+ return attrs.split(',').includes(`variant=${name}`) ? cond : null;
3959
+ };
3960
+ for (const st of steps)
3961
+ for (const p of kebabs) {
3962
+ const at = ctx.C.MAP[target]?.at?.[p];
3963
+ for (const [k, val] of Object.entries(at ?? {})) {
3964
+ const cond = keyOf(k);
3965
+ if (cond == null) continue;
3966
+ if (st ? cond.includes(`:${st}`) : cond === '') return val;
3967
+ }
3968
+ }
3969
+ if (stateOnly) return null;
3970
+ return css === 'background-color'
3971
+ ? 'transparent'
3972
+ : css === 'color'
3973
+ ? null
3974
+ : 'currentcolor';
3975
+ };
3976
+ /** The family a color property belongs to: background is background-color. @param {string} p */
3977
+ const colorFamily = p => {
3978
+ const k = kebab(p);
3979
+ return k === 'background' ? 'background-color' : k;
3980
+ };
3981
+ /** One-mode colors in a variant or a state, written after every other setting. @type {Array<() => void>} */
3982
+ const scopedQueue = [];
3983
+ let drainingScoped = false;
3984
+ /**
3985
+ * A part's rule for a scope as the theme has it, without making one.
3986
+ * @param {Setting} s @param {string} target
3987
+ * @returns {Record<string, any> | undefined}
3988
+ */
3989
+ const peekBlock = (s, target) => {
3990
+ const t = theme.components[target];
3991
+ if (!t) return undefined;
3992
+ const rule = t[s.when ?? 'base'];
3993
+ if (!s.state) return rule;
3994
+ const tg = ctx.project.target.get(target);
3995
+ if (tg?.states.includes(s.state))
3996
+ return s.when == null ? t[s.state] : t[`${s.when}+${s.state}`];
3997
+ return rule?.[stateKey(s.state, wrapsOneControl(ctx, target))];
3998
+ };
3999
+ /**
4000
+ * The theme's own value of a property in one mode for the scope around a
4001
+ * setting's scope: the variant's resting rule for a state, then the
4002
+ * part's plain rule, then, for a token, the whole theme's value; null
4003
+ * when the theme gives none, so the base theme's and Core's values apply.
4004
+ * @param {Setting} s @param {string} target @param {string} prop
4005
+ * @param {'light' | 'dark'} side
4006
+ * @returns {string | null}
4007
+ */
4008
+ const enclosingValue = (s, target, prop, side) => {
4009
+ const family = /^background(-color)?$/.test(kebab(prop))
4010
+ ? ['backgroundColor', 'background']
4011
+ : [prop];
4012
+ /** @type {Setting[]} */
4013
+ const scopes = [];
4014
+ if (s.state) scopes.push({...s, state: undefined, mode: undefined});
4015
+ if (s.when || s.state)
4016
+ scopes.push({...s, when: undefined, state: undefined, mode: undefined});
4017
+ for (const sc of scopes) {
4018
+ const rule = peekBlock(sc, target);
4019
+ for (const k of family) {
4020
+ const x = rule?.[k];
4021
+ if (typeof x === 'string' && !/gradient\(|url\(/i.test(x))
4022
+ return halfOf(x, side === 'light' ? 1 : 2);
4023
+ }
4024
+ }
4025
+ if (prop.startsWith('--')) return tok[prop]?.[side] ?? null;
4026
+ return null;
4027
+ };
2770
4028
  /** @param {Setting} s @param {string} target @param {string} prop @param {string} v */
2771
4029
  const putComp = (s, target, prop, v) => {
2772
4030
  const b = block(s, target);
2773
- if (s.mode && !modeOnly) {
4031
+ // A gradient background for one mode: each layer's colors are painted
4032
+ // in that mode only (transparent in the other), as background images
4033
+ // beside the other mode's, so each mode keeps its own background color;
4034
+ // a gradient for both modes held before keeps showing in the other
4035
+ // mode. Which layers belong to which mode is recorded as they are
4036
+ // written, never read back from their stops.
4037
+ if (
4038
+ s.mode &&
4039
+ /^background(-image)?$/.test(kebab(prop)) &&
4040
+ /gradient\(/i.test(v)
4041
+ ) {
4042
+ let rec = modeLayers.get(b);
4043
+ if (!rec) {
4044
+ rec = {light: [], dark: []};
4045
+ for (const k of ['background', 'backgroundImage']) {
4046
+ const held = b[k];
4047
+ if (typeof held !== 'string' || !/gradient\(/i.test(held)) continue;
4048
+ rec.light.push(...maskLayers(held, 'light'));
4049
+ rec.dark.push(...maskLayers(held, 'dark'));
4050
+ if (k === 'backgroundImage') delete b[k];
4051
+ }
4052
+ modeLayers.set(b, rec);
4053
+ }
4054
+ // The background shorthand's last layer may carry the color under
4055
+ // the images: that color is this mode's background color, and the
4056
+ // rest are the images.
4057
+ const {images, color} =
4058
+ kebab(prop) === 'background'
4059
+ ? backgroundColorLayer(v)
4060
+ : {images: v, color: null};
4061
+ rec[s.mode] = images ? maskLayers(images, s.mode) : [];
4062
+ const parts = [...rec.light, ...rec.dark].map(layerParts);
4063
+ for (const k of [
4064
+ 'backgroundImage',
4065
+ 'backgroundPosition',
4066
+ 'backgroundSize',
4067
+ 'backgroundRepeat',
4068
+ ])
4069
+ delete b[k];
4070
+ b.backgroundImage = parts.map(x => x.image).join(', ');
4071
+ if (parts.some(x => x.position || x.size || x.repeat)) {
4072
+ b.backgroundPosition = parts.map(x => x.position || '0% 0%').join(', ');
4073
+ b.backgroundSize = parts.map(x => x.size || 'auto').join(', ');
4074
+ b.backgroundRepeat = parts.map(x => x.repeat || 'repeat').join(', ');
4075
+ }
4076
+ if (!parts.length) delete b.backgroundImage;
4077
+ if (color) putComp(s, target, 'backgroundColor', color);
4078
+ return;
4079
+ }
4080
+ // A color set in a one-mode theme fills its mode's half only (as a
4081
+ // setting for that mode does), so a region Core draws in the other mode
4082
+ // reads the other half.
4083
+ const mode =
4084
+ s.mode ??
4085
+ (modeOnly && parseColor(String(v).trim()) ? modeOnly : undefined);
4086
+ // A color for one mode on a part rule also gives the other mode a
4087
+ // value in that rule, which outranks the rules the base theme and Core
4088
+ // give the part in context there (a selected or current item, a status
4089
+ // border): the result says so.
4090
+ if (mode && !prop.startsWith('--')) {
4091
+ 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)`;
4092
+ if (!(ctx.compileNotes ?? []).includes(note))
4093
+ (ctx.compileNotes ??= []).push(note);
4094
+ }
4095
+ if (mode && !s.when && variantsReading(ctx, target, prop, s.state).length) {
4096
+ // A color for one mode on a part whose variants each have their own:
4097
+ // each variant's rule (in the state, for a state setting) gets the
4098
+ // color in that mode and, in the other, exactly the value it shows
4099
+ // unset there (the base theme's, else Core's), so no variant takes
4100
+ // another's and the other mode stays as it was. The part's own rule
4101
+ // is left alone.
4102
+ // The property itself (a border color stays a border color); the
4103
+ // background shorthand is written as its color.
4104
+ const css = colorFamily(prop);
4105
+ const other = mode === 'light' ? 2 : 1;
4106
+ // What the part's own rule holds of it (an earlier setting for both
4107
+ // modes): the other half each variant keeps, before its unset value.
4108
+ const plainHeld = [
4109
+ css,
4110
+ ...(css === 'background-color' ? ['background'] : []),
4111
+ ]
4112
+ .map(k => b[camel(k)])
4113
+ .find(y => typeof y === 'string' && !/gradient\(|url\(/i.test(y));
4114
+ // The part's own background being an image (a gradient) covers any
4115
+ // color under it: the color is written, and the result says it does
4116
+ // not show.
4117
+ // A color given beside its own image in one background (`linear-
4118
+ // gradient(…), ivory`) is that image's bottom layer, never covered by
4119
+ // it.
4120
+ const plainImage =
4121
+ css === 'background-color' && !ownImageLayer(s)
4122
+ ? ['background', 'backgroundImage']
4123
+ .map(k => b[k])
4124
+ .find(y => typeof y === 'string' && /gradient\(|url\(/i.test(y))
4125
+ : undefined;
4126
+ if (plainImage)
4127
+ (ctx.compileNotes ??= []).push(
4128
+ `${target}'s own background is an image (${plainImage}), which covers the ${mode} color: it does not show until that background is a color`,
4129
+ );
4130
+ const names = new Set([
4131
+ ...(ctx.C.variantValues(target)?.variant ?? []),
4132
+ ...(ctx.C.MAP[target]?.attrs?.variant ?? []),
4133
+ ]);
4134
+ for (const name of names) {
4135
+ const x = exactVariantValue(target, css, name, s.state);
4136
+ const vb = block({...s, when: `variant:${name}`}, target);
4137
+ // What the variant's rule already holds (a setting for the other
4138
+ // mode, or one for both) keeps its other half; else the value the
4139
+ // variant shows unset.
4140
+ // The background shorthand is the same property: its color counts,
4141
+ // and it is taken out so the color written here is in effect.
4142
+ const family = [
4143
+ css,
4144
+ ...(css === 'background-color' ? ['background'] : []),
4145
+ ];
4146
+ // A variant whose own background is an image (a gradient) keeps
4147
+ // it: one mode's color is not written there, and the result says so.
4148
+ const image = family
4149
+ .map(k => vb[camel(k)])
4150
+ .find(y => typeof y === 'string' && /gradient\(|url\(/i.test(y));
4151
+ if (image) {
4152
+ (ctx.compileNotes ??= []).push(
4153
+ `${target} variant:${name} keeps its own background image (${image}), so the ${mode} color is not written there`,
4154
+ );
4155
+ continue;
4156
+ }
4157
+ const prev = family
4158
+ .map(k => vb[camel(k)])
4159
+ .find(y => typeof y === 'string');
4160
+ // In a state, what the state shows now in the other mode: its own
4161
+ // value there, else the resting color a setting gives the variant
4162
+ // or the part (a state that does not change the color shows the
4163
+ // resting one), else the unset value.
4164
+ /** @param {Record<string, any> | undefined} rule */
4165
+ const restOf = rule =>
4166
+ family
4167
+ .map(k => rule?.[camel(k)])
4168
+ .find(y => typeof y === 'string' && !/gradient\(|url\(/i.test(y));
4169
+ const rest = s.state
4170
+ ? (exactVariantValue(target, css, name, s.state, true) ??
4171
+ restOf(theme.components[target]?.[`variant:${name}`]) ??
4172
+ plainHeld ??
4173
+ restOf(theme.components[target]?.base))
4174
+ : plainHeld;
4175
+ const from = prev ?? rest ?? x;
4176
+ if (from == null) continue;
4177
+ for (const k of family) delete vb[camel(k)];
4178
+ const half = halfOf(from, other);
4179
+ vb[camel(css)] =
4180
+ mode === 'light'
4181
+ ? `light-dark(${v}, ${half})`
4182
+ : `light-dark(${half}, ${v})`;
4183
+ // A resting color written on the variant's rule would also hide the
4184
+ // hover the variant shows unset: that hover is written back as it
4185
+ // was, in both modes, unless a hover setting of the theme's own
4186
+ // gives it one.
4187
+ if (
4188
+ !s.state &&
4189
+ !data.settings.some(
4190
+ y =>
4191
+ y.on === s.on &&
4192
+ y.state === 'hover' &&
4193
+ colorFamily(y.thing) === colorFamily(s.thing),
4194
+ )
4195
+ ) {
4196
+ const hover = exactVariantValue(target, css, name, 'hover', true);
4197
+ if (hover != null && hover !== x) {
4198
+ const hb = block(
4199
+ {...s, when: `variant:${name}`, state: 'hover', mode: undefined},
4200
+ target,
4201
+ );
4202
+ hb[camel(css)] ??= hover;
4203
+ }
4204
+ }
4205
+ }
4206
+ return;
4207
+ }
4208
+ // A color for one mode in a variant or a state is written once every
4209
+ // other setting is in, so its other half is the theme's own value for
4210
+ // the scope around it as the theme finally has it (below).
4211
+ if (mode && (s.when || s.state) && !drainingScoped) {
4212
+ scopedQueue.push(() => putComp(s, target, prop, v));
4213
+ return;
4214
+ }
4215
+ if (mode && colorFamily(prop) === 'background-color') {
4216
+ // The background shorthand and its color are one property: the one
4217
+ // the rule holds (as a color) gives the other half and is replaced, so
4218
+ // one key carries both modes.
4219
+ const held = ['backgroundColor', 'background'].find(
4220
+ k => typeof b[k] === 'string' && !/gradient\(|url\(/i.test(b[k]),
4221
+ );
4222
+ if (held && held !== camel(prop)) {
4223
+ const was = b[held];
4224
+ delete b[held];
4225
+ b[camel(prop)] ??= was;
4226
+ }
4227
+ }
4228
+ // A color for one mode under the part's own gradient does not show:
4229
+ // the result says so.
4230
+ if (
4231
+ mode &&
4232
+ colorFamily(prop) === 'background-color' &&
4233
+ !ownImageLayer(s) &&
4234
+ ['background', 'backgroundImage'].some(
4235
+ k => typeof b[k] === 'string' && /gradient\(|url\(/i.test(b[k]),
4236
+ )
4237
+ )
4238
+ (ctx.compileNotes ??= []).push(
4239
+ `${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`,
4240
+ );
4241
+ if (mode) {
2774
4242
  const prev = b[prop];
2775
4243
  // The other mode keeps exactly what it had: the value set for it, the
2776
4244
  // part's own, else what the property shows unset (light-dark() takes
2777
4245
  // colors only, so never inherit).
4246
+ // A token on the part: its own value in the other mode (the base
4247
+ // theme's, else Core's), never another color.
4248
+ const otherSide = mode === 'light' ? 'dark' : 'light';
4249
+ const tokenOther = prop.startsWith('--')
4250
+ ? (base[otherSide]?.[prop] ??
4251
+ /** @type {Record<string, string>} */ (TOKENS)[prop] ??
4252
+ null)
4253
+ : null;
2778
4254
  const other =
2779
4255
  prev ??
4256
+ enclosingValue(s, target, prop, otherSide) ??
4257
+ tokenOther ??
2780
4258
  baseComponent(base, ctx, target, prop, s) ??
2781
4259
  partDefault(ctx, target, prop, s.when, s.state) ??
2782
4260
  (s.state
@@ -2791,7 +4269,7 @@ export function compileTheme(ctx, data, base) {
2791
4269
  return halves.length === 2 ? halves[side - 1].trim() : x;
2792
4270
  };
2793
4271
  b[prop] =
2794
- s.mode === 'light'
4272
+ mode === 'light'
2795
4273
  ? `light-dark(${v}, ${prev ? split(prev, 2) : other})`
2796
4274
  : `light-dark(${prev ? split(prev, 1) : other}, ${v})`;
2797
4275
  } else b[prop] = v;
@@ -2871,14 +4349,27 @@ export function compileTheme(ctx, data, base) {
2871
4349
  );
2872
4350
  // Dials first, then exact tokens and part properties: an exact setting
2873
4351
  // always wins over a dial, whatever the order they were made in.
2874
- // A font for one role (body, heading, code) comes after the whole-theme
2875
- // font, so the role keeps its own font whatever the order.
2876
- const roleFont = (/** @type {Setting} */ x) => x.thing === 'font' && !!x.on;
4352
+ // A dial on a part (a font for one role, corners on cards) comes after
4353
+ // the whole-theme dials, so the part keeps its own whatever the order.
4354
+ const onPart = (/** @type {Setting} */ x) => !!x.on;
2877
4355
  const ordered = [
2878
- ...data.settings.filter(x => x.source === 'dial' && !roleFont(x)),
2879
- ...data.settings.filter(x => x.source === 'dial' && roleFont(x)),
4356
+ ...data.settings.filter(x => x.source === 'dial' && !onPart(x)),
4357
+ ...data.settings.filter(x => x.source === 'dial' && onPart(x)),
2880
4358
  ...data.settings.filter(x => x.source !== 'dial'),
2881
4359
  ];
4360
+ // The shell regions a setting gives a background of their own keep it
4361
+ // when the page background paints the rest of the shell.
4362
+ const regionsWithOwnBackground = new Set(
4363
+ data.settings
4364
+ .filter(
4365
+ x =>
4366
+ x.source === 'property' &&
4367
+ /^background(-color|-image)?$/.test(kebab(x.thing)),
4368
+ )
4369
+ .flatMap(x => partsOf(ctx, x)),
4370
+ );
4371
+ /** @type {Record<string, any>[]} */
4372
+ const fixedToViewport = [];
2882
4373
  for (const s of ordered) {
2883
4374
  // A setting for the mode a one-mode theme does not have stays saved but
2884
4375
  // does not apply (maskedSettings names it).
@@ -2893,7 +4384,7 @@ export function compileTheme(ctx, data, base) {
2893
4384
  /** @param {string} token */
2894
4385
  const derived = token => `${radiusAt(base, s.value, token)}px`;
2895
4386
  if (parts.length)
2896
- for (const t of parts) {
4387
+ for (const t of parts.flatMap(p => cornerParts(ctx, p))) {
2897
4388
  // A rung on a part gives what the whole-theme rung gives the
2898
4389
  // radius token the part reads; an exact size is as given.
2899
4390
  putComp(
@@ -2903,17 +4394,35 @@ export function compileTheme(ctx, data, base) {
2903
4394
  rung || pill ? derived(radiusTokenOf(ctx, t, s.when)) : `${px}px`,
2904
4395
  );
2905
4396
  }
2906
- else
2907
- for (const token of [
2908
- '--radius-element',
2909
- '--radius-inner',
2910
- '--radius-container',
2911
- '--radius-page',
2912
- ])
4397
+ else {
4398
+ for (const token of DIAL_RADII)
2913
4399
  // The radii the build already shows for this corners value (a
2914
4400
  // build by an earlier editor, or a step back) are kept, as the
2915
4401
  // colors are: they change only when corners or the base does.
2916
4402
  putTok(token, ctx.keepRadii?.[token] ?? derived(token));
4403
+ // A part rule of the base theme that gives a radius other than the
4404
+ // dial token the part reads (a length, or a token the dial never
4405
+ // moves, such as --radius-full) would keep it over the dial: the
4406
+ // rule is given that dial token, so the part follows the dial. A
4407
+ // part Core rounds with a token the dial never moves (a badge's
4408
+ // --radius-full) keeps its base radius.
4409
+ for (const [t, when, radius] of baseRadii(
4410
+ /** @type {{components?: Record<string, any>}} */ (base),
4411
+ )) {
4412
+ const token = radiusTokenOf(ctx, t, when);
4413
+ if (
4414
+ ctx.project.target.has(t) &&
4415
+ DIAL_RADII.includes(token) &&
4416
+ radius !== `var(${token})`
4417
+ )
4418
+ putComp(
4419
+ {...s, mode: undefined, when},
4420
+ t,
4421
+ 'borderRadius',
4422
+ `var(${token})`,
4423
+ );
4424
+ }
4425
+ }
2917
4426
  } else if (PALETTE_DIALS.includes(s.thing) || s.thing === 'vibrancy') {
2918
4427
  // The palette mapping above sets these tokens.
2919
4428
  } else if (s.thing === 'font') {
@@ -3001,35 +4510,246 @@ export function compileTheme(ctx, data, base) {
3001
4510
  // The rungs scale the spacing the base theme starts from.
3002
4511
  /** @param {string} k @param {string} nv */
3003
4512
  const put = (k, nv) => {
3004
- if (parts.length) for (const t of parts) block(s, t)[k] = nv;
3005
- else putTok(k, nv);
4513
+ if (parts.length) {
4514
+ // An exact whole-theme or own-source token holds inside the
4515
+ // part too.
4516
+ if (!keptTokens(null).has(k))
4517
+ for (const t of parts) block(s, t)[k] = nv;
4518
+ } else putTok(k, nv);
3006
4519
  };
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`);
4520
+ // The spacing steps, in order around the exact steps the theme
4521
+ // keeps (a whole-theme one or the own source's: they win over the
4522
+ // dial).
4523
+ /** @type {Record<string, string>} */
4524
+ const dialVars = {};
4525
+ {
4526
+ /** @type {Array<[string, number]>} */
4527
+ const steps = [];
4528
+ for (const [k, core] of Object.entries(
4529
+ /** @type {Record<string, string>} */ (TOKENS),
4530
+ )) {
4531
+ const v = base.light[k] ?? core;
4532
+ if (/^--spacing-/.test(k) && /rem$/.test(v))
4533
+ steps.push([k, parseFloat(v) * 16]);
4534
+ }
4535
+ /** @type {Record<string, number>} */
4536
+ const keptSteps = {};
4537
+ for (const [k, v] of keptTokens(null))
4538
+ if (/^--spacing-/.test(k)) {
4539
+ const n = sizePx(v);
4540
+ if (n != null) keptSteps[k] = n;
4541
+ }
4542
+ /** @type {string[]} */
4543
+ const noRoom = [];
4544
+ for (const [k, n] of spacingSteps(steps, f, keptSteps, noRoom)) {
4545
+ const nv = `${Number((n / 16).toFixed(3))}rem`;
4546
+ dialVars[k] = k in keptSteps ? String(keptTokens(null).get(k)) : nv;
4547
+ if (!(k in keptSteps)) put(k, nv);
4548
+ }
4549
+ for (const k of noRoom)
4550
+ (ctx.sizeNotes ??= []).push(
4551
+ `${k} has no room between the exact spacing steps kept around it, so it takes the value of the one below it`,
4552
+ );
4553
+ }
4554
+ // An exact size the theme keeps (it wins over the dial) is a fixed
4555
+ // point the others stay in order around: a whole-theme one, one of
4556
+ // the theme's own source, and on a part the part's own, in any
4557
+ // unit that comes to a length (a spacing token through the value
4558
+ // this dial gives it). A whole-theme dial also keeps each part's
4559
+ // own exact sizes in order on that part.
4560
+ const sizeParts = parts.length
4561
+ ? parts
4562
+ : [
4563
+ null,
4564
+ ...new Set(
4565
+ data.settings
4566
+ .filter(
4567
+ x =>
4568
+ x.source === 'token' &&
4569
+ /^--size-element-/.test(x.thing) &&
4570
+ x.on &&
4571
+ !x.when &&
4572
+ !x.state,
4573
+ )
4574
+ .flatMap(x => partsOf(ctx, x)),
4575
+ ),
4576
+ ];
4577
+ for (const t of sizeParts) {
4578
+ /** @type {Record<string, number>} */
4579
+ const kept = {};
4580
+ for (const [k, v] of keptSizes(t)) {
4581
+ const n = sizePx(v, dialVars);
4582
+ if (n != null) kept[k] = n;
4583
+ }
4584
+ /** @type {string[]} */
4585
+ const noRoom = [];
4586
+ for (const [k, nv] of controlSizes(
4587
+ Object.keys(/** @type {Record<string, string>} */ (TOKENS))
4588
+ .filter(k => /^--size-element-/.test(k))
4589
+ .map(k => [k, base.light[k] ?? TOKENS[k]]),
4590
+ f,
4591
+ kept,
4592
+ noRoom,
4593
+ ))
4594
+ if (t) block(s, t)[k] = nv;
4595
+ else putTok(k, nv);
4596
+ for (const k of noRoom)
4597
+ (ctx.sizeNotes ??= []).push(
4598
+ `${k}${t ? ` on ${t}` : ''} has no room between the exact sizes kept around it, so it takes the size of the one below it`,
4599
+ );
4600
+ }
4601
+ // A variant's own exact size is kept in order on that variant too,
4602
+ // with the part's and the theme's kept sizes around it.
4603
+ /** @type {Map<string, {t: string, when: string}>} */
4604
+ const variantScopes = new Map();
4605
+ for (const x of data.settings)
4606
+ if (
4607
+ x.source === 'token' &&
4608
+ /^--size-element-/.test(x.thing) &&
4609
+ x.on &&
4610
+ x.when &&
4611
+ !x.state
4612
+ )
4613
+ for (const t of partsOf(ctx, x))
4614
+ if (!parts.length || parts.includes(t))
4615
+ variantScopes.set(`${t} ${x.when}`, {t, when: x.when});
4616
+ for (const {t, when} of variantScopes.values()) {
4617
+ /** @type {Record<string, number>} */
4618
+ const kept = {};
4619
+ for (const [k, v] of keptSizes(t)) {
4620
+ const n = sizePx(v, dialVars);
4621
+ if (n != null) kept[k] = n;
4622
+ }
4623
+ for (const x of data.settings)
4624
+ if (
4625
+ x.source === 'token' &&
4626
+ /^--size-element-/.test(x.thing) &&
4627
+ x.when === when &&
4628
+ !x.state &&
4629
+ partsOf(ctx, x).includes(t)
4630
+ ) {
4631
+ const n = sizePx(String(x.value), dialVars);
4632
+ if (n != null) kept[x.thing] = n;
4633
+ }
4634
+ /** @type {string[]} */
4635
+ const noRoom = [];
4636
+ for (const [k, nv] of controlSizes(
4637
+ Object.keys(/** @type {Record<string, string>} */ (TOKENS))
4638
+ .filter(k => /^--size-element-/.test(k))
4639
+ .map(k => [k, base.light[k] ?? TOKENS[k]]),
4640
+ f,
4641
+ kept,
4642
+ noRoom,
4643
+ ))
4644
+ block({...s, when}, t)[k] = nv;
4645
+ for (const k of noRoom)
4646
+ (ctx.sizeNotes ??= []).push(
4647
+ `${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`,
4648
+ );
3013
4649
  }
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
4650
  }
3022
4651
  } else if (s.source === 'token') {
3023
4652
  if (parts.length) for (const t of parts) putComp(s, t, s.thing, s.value);
3024
4653
  else putTok(s.thing, s.value, s.mode);
3025
4654
  } else if (s.source === 'property') {
3026
- for (const t of parts) {
4655
+ // A background on the whole app shell is the page background. The
4656
+ // shell's header and side nav paint the body or surface color over it
4657
+ // in every variant but section, and in an auto-height shell they are
4658
+ // sticky, so content must not show through them when it scrolls: they
4659
+ // take the same background. The main content area is made
4660
+ // see-through. A gradient is fixed to the viewport on the shell and on
4661
+ // those regions, so the regions line up with the page behind them. A
4662
+ // background a setting gives one of those regions itself is kept.
4663
+ /** @type {string[]} */
4664
+ const pageParts = [];
4665
+ if (
4666
+ parts.includes('app-shell') &&
4667
+ /^background(-color|-image)?$/.test(kebab(s.thing)) &&
4668
+ !s.when &&
4669
+ !s.state
4670
+ ) {
4671
+ /** @param {Record<string, any>} r */
4672
+ const ownBackground = r =>
4673
+ ['background', 'backgroundColor', 'backgroundImage'].some(
4674
+ k => k in r,
4675
+ );
4676
+ for (const region of ['app-shell-header', 'app-shell-sidenav'])
4677
+ if (
4678
+ ctx.project.target.has(region) &&
4679
+ !regionsWithOwnBackground.has(region)
4680
+ )
4681
+ pageParts.push(region);
4682
+ if (ctx.project.target.has('layout-content')) {
4683
+ const lc = ((theme.components['layout-content'] ??= {}).base ??= {});
4684
+ const main = (lc[':where(.astryx-app-shell [role="main"])'] ??= {});
4685
+ if (!ownBackground(main)) main.backgroundColor = 'transparent';
4686
+ }
4687
+ // Written after every setting (below), so no background shorthand
4688
+ // in the same rule resets it.
4689
+ if (/gradient\(/.test(String(s.value)))
4690
+ for (const t of ['app-shell', ...pageParts])
4691
+ fixedToViewport.push(block({...s, mode: undefined}, t));
4692
+ (ctx.compileNotes ??= []).push(
4693
+ "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",
4694
+ );
4695
+ }
4696
+ for (const t of [...parts, ...pageParts]) {
4697
+ // A heading takes its color from its color prop, which reads the
4698
+ // text color tokens after part styles: the color goes into those
4699
+ // tokens on the heading (a named color prop's own token for
4700
+ // --when color:<name>), so it shows there and nowhere else.
4701
+ if (t === 'heading' && kebab(s.thing) === 'color') {
4702
+ const named = /^color:([\w-]+)$/.exec(s.when ?? '')?.[1];
4703
+ const scope = named ? {...s, when: undefined} : s;
4704
+ for (const tok of named
4705
+ ? [`--color-text-${named}`]
4706
+ : ['--color-text-primary', '--color-text-secondary'])
4707
+ // A value naming one of these tokens (the secondary text color)
4708
+ // leaves that token as it is: it would read itself.
4709
+ if (!new RegExp(`var\\(\\s*${tok}\\s*[,)]`).test(String(s.value)))
4710
+ putComp(scope, t, tok, s.value);
4711
+ continue;
4712
+ }
4713
+ // A part whose text is drawn by elements inside it that read a text
4714
+ // color token themselves (a top nav heading's title) takes the color
4715
+ // in those tokens too, on the part alone, so that text shows it.
4716
+ if (kebab(s.thing) === 'color')
4717
+ for (const tok of innerTextTokens(ctx.C, t))
4718
+ if (!new RegExp(`var\\(\\s*${tok}\\s*[,)]`).test(String(s.value)))
4719
+ putComp(s, t, tok, s.value);
3027
4720
  // A padding on a part whose box reads Core's padding variables is
3028
4721
  // resolved with the rest of that part's padding, below.
3029
4722
  if (padVars(t) && /^padding(-|$)/.test(kebab(s.thing))) {
3030
4723
  queuePadding(s, t);
3031
4724
  continue;
3032
4725
  }
4726
+ // A padding on a part without padding variables, where the own source
4727
+ // pads some sides of the same rule: the editor writes the other
4728
+ // sides only, each as it names it (physical stays physical), so the
4729
+ // own sides win; a side the own source holds in one direction only
4730
+ // is written for the other direction.
4731
+ if (/^padding(-|$)/.test(kebab(s.thing)) && !s.mode && !padVars(t)) {
4732
+ const own = ownBox(t, s);
4733
+ if (own.ltr.size || own.rtl.size) {
4734
+ for (const [x, v] of Object.entries(
4735
+ paddingSides(kebab(s.thing), String(s.value)),
4736
+ )) {
4737
+ const prop = camel(`padding-${x}`);
4738
+ const [inL, inR] = [
4739
+ own.ltr.has(boxSide(x, 'ltr')),
4740
+ own.rtl.has(boxSide(x, 'rtl')),
4741
+ ];
4742
+ if (inL && inR) continue;
4743
+ if (!inL && !inR) {
4744
+ putComp(s, t, prop, v);
4745
+ continue;
4746
+ }
4747
+ const [db, key] = dirBlock(s, t, inL ? ':dir(rtl)' : ':dir(ltr)');
4748
+ db[key] = {...(db[key] ?? {}), [prop]: v};
4749
+ }
4750
+ continue;
4751
+ }
4752
+ }
3033
4753
  const sides =
3034
4754
  wrappedPadding(t, s) ??
3035
4755
  containerSides(t, s) ??
@@ -3108,7 +4828,13 @@ export function compileTheme(ctx, data, base) {
3108
4828
  }
3109
4829
  }
3110
4830
  }
4831
+ drainingScoped = true;
4832
+ for (const write of scopedQueue) write();
3111
4833
  emitPadding();
4834
+ for (const r of fixedToViewport) {
4835
+ delete r.backgroundAttachment;
4836
+ r.backgroundAttachment = 'fixed';
4837
+ }
3112
4838
  orderBlocks();
3113
4839
  // Core gives headings the body font when a theme sets only the body's:
3114
4840
  // a font for the body alone keeps the base theme's heading font.
@@ -3162,7 +4888,16 @@ export function compileTheme(ctx, data, base) {
3162
4888
  for (const [k, {light, dark}] of Object.entries(tok)) {
3163
4889
  const l = light ?? base.light[k] ?? TOKENS[k];
3164
4890
  const d = dark ?? base.dark[k] ?? TOKENS[k];
3165
- theme.tokens[k] = l === d ? l : [l, d];
4891
+ // A pair only for a color: anything else (a shadow) is one value, the
4892
+ // one the theme's mode shows.
4893
+ theme.tokens[k] =
4894
+ l === d
4895
+ ? l
4896
+ : ctx.C.typeOf(k) === 'color' || isColorToken(k)
4897
+ ? [l, d]
4898
+ : modeOnly === 'dark'
4899
+ ? d
4900
+ : l;
3166
4901
  }
3167
4902
  // Base themes set the type tokens again for phones (a coarse pointer
3168
4903
  // below the lg width); an exact font family or weight, and the headings
@@ -3198,11 +4933,250 @@ export function compileTheme(ctx, data, base) {
3198
4933
  },
3199
4934
  ],
3200
4935
  };
4936
+ // A longhand set after a shorthand that covers it is the one in effect,
4937
+ // as the result says. The build merges these blocks over the base
4938
+ // theme's, and a key the base holds keeps the base's (earlier) place, so
4939
+ // such a longhand would come before the shorthand and lose: it is written
4940
+ // as its own sides instead, which the base does not hold.
4941
+ const baseBlocks =
4942
+ /** @type {{components?: Record<string, any>}} */ (base).components ?? {};
4943
+ for (const [target, keys] of Object.entries(theme.components ?? {}))
4944
+ for (const [key, b] of Object.entries(
4945
+ /** @type {Record<string, any>} */ (keys),
4946
+ ))
4947
+ laterLonghandsAsSides(b, baseBlocks[target]?.[key]);
3201
4948
  if (!Object.keys(theme.tokens).length) delete theme.tokens;
3202
4949
  if (!Object.keys(theme.components).length) delete theme.components;
3203
4950
  return theme;
3204
4951
  }
3205
4952
 
4953
+ /**
4954
+ * Whether shorthand `a` sets `b`, a logical side included: padding sets
4955
+ * padding-inline, border-color sets border-inline-start-color.
4956
+ * @param {string} a @param {string} b
4957
+ */
4958
+ function coversSide(a, b) {
4959
+ if (coversProperty(a, b)) return true;
4960
+ const root = b.replace(/-(inline|block)(-start|-end)?(?=-|$)/, '');
4961
+ return root !== b && (a === root || coversProperty(a, root));
4962
+ }
4963
+
4964
+ /**
4965
+ * A background's layers with each color painted in one mode only: a color
4966
+ * stop becomes light-dark(<color>, transparent) for light (the reverse for
4967
+ * dark), and a layer that is a color alone becomes a gradient of it, so
4968
+ * every layer is an image the other mode does not show.
4969
+ * @param {string} value
4970
+ * @param {'light' | 'dark'} mode
4971
+ * @returns {string[]}
4972
+ */
4973
+ export function maskLayers(value, mode) {
4974
+ /** @param {string} c */
4975
+ const wrap = c =>
4976
+ mode === 'light'
4977
+ ? `light-dark(${c}, transparent)`
4978
+ : `light-dark(transparent, ${c})`;
4979
+ /** @param {string} w */
4980
+ const isColor = w =>
4981
+ !/^light-dark\(/i.test(w) &&
4982
+ (isColorValue(w) || /^var\(\s*--color-/i.test(w));
4983
+ return splitTop(value, ',')
4984
+ .map(x => x.trim())
4985
+ .filter(Boolean)
4986
+ .map(layer => {
4987
+ const fn = /^((?:repeating-)?(?:linear|radial|conic)-gradient)\(/i.exec(
4988
+ layer,
4989
+ );
4990
+ if (!fn)
4991
+ return isColor(layer)
4992
+ ? `linear-gradient(${wrap(layer)}, ${wrap(layer)})`
4993
+ : layer;
4994
+ // The gradient's own arguments, up to its closing bracket; what
4995
+ // follows (position, size, repeat) stays as it is.
4996
+ let depth = 0;
4997
+ let end = fn[0].length - 1;
4998
+ for (let i = end; i < layer.length; i++) {
4999
+ if (layer[i] === '(') depth++;
5000
+ if (layer[i] === ')' && --depth === 0) {
5001
+ end = i;
5002
+ break;
5003
+ }
5004
+ }
5005
+ const args = splitTop(layer.slice(fn[0].length, end), ',').map(arg =>
5006
+ splitTop(arg.trim(), ' ')
5007
+ .map(w => (isColor(w.trim()) ? wrap(w.trim()) : w.trim()))
5008
+ .join(' '),
5009
+ );
5010
+ return `${fn[1]}(${args.join(', ')})${layer.slice(end + 1)}`;
5011
+ });
5012
+ }
5013
+
5014
+ /**
5015
+ * The part rules of a base theme that give a border radius: each as its
5016
+ * part, the rule's --when (undefined for the plain rule) and the radius.
5017
+ * @param {{components?: Record<string, any>}} base
5018
+ * @returns {Array<[string, string | undefined, string]>}
5019
+ */
5020
+ function baseRadii(base) {
5021
+ /** @type {Array<[string, string | undefined, string]>} */
5022
+ const out = [];
5023
+ for (const [t, rules] of Object.entries(base.components ?? {}))
5024
+ for (const [key, rule] of Object.entries(
5025
+ /** @type {Record<string, any>} */ (rules ?? {}),
5026
+ )) {
5027
+ if (key !== 'base' && !/^[\w-]+:[\w-]+$/.test(key)) continue;
5028
+ const r = rule?.borderRadius;
5029
+ if (typeof r === 'string')
5030
+ out.push([t, key === 'base' ? undefined : key, r.trim()]);
5031
+ }
5032
+ return out;
5033
+ }
5034
+
5035
+ /**
5036
+ * Whether a setting's own value is a background with an image layer, so any
5037
+ * color it writes is that background's bottom layer.
5038
+ * @param {Setting} s
5039
+ */
5040
+ function ownImageLayer(s) {
5041
+ return (
5042
+ kebab(s.thing) === 'background' && /gradient\(|url\(/i.test(String(s.value))
5043
+ );
5044
+ }
5045
+
5046
+ /**
5047
+ * A background shorthand split into its image layers and the color its
5048
+ * last layer may carry (the color under every image): a color word beside
5049
+ * the last image, or a last layer that is a color alone.
5050
+ * @param {string} value
5051
+ * @returns {{images: string, color: string | null}}
5052
+ */
5053
+ export function backgroundColorLayer(value) {
5054
+ const layers = splitTop(value, ',')
5055
+ .map(x => x.trim())
5056
+ .filter(Boolean);
5057
+ const last = layers.at(-1) ?? '';
5058
+ const words = splitTop(last, ' ').map(x => x.trim());
5059
+ const at = words.findIndex(
5060
+ w => !/gradient\(|url\(/i.test(w) && isColorValue(w),
5061
+ );
5062
+ if (at < 0) return {images: value, color: null};
5063
+ const rest = words.filter((_, i) => i !== at).join(' ');
5064
+ return {
5065
+ images: [...layers.slice(0, -1), ...(rest ? [rest] : [])].join(', '),
5066
+ color: words[at],
5067
+ };
5068
+ }
5069
+
5070
+ /**
5071
+ * A background layer's image (its gradient) and what follows it, as the
5072
+ * background longhands take them: position, size (after a slash) and
5073
+ * repeat.
5074
+ * @param {string} layer
5075
+ * @returns {{image: string, position: string, size: string, repeat: string}}
5076
+ */
5077
+ function layerParts(layer) {
5078
+ const fn = /^((?:repeating-)?(?:linear|radial|conic)-gradient)\(/i.exec(
5079
+ layer,
5080
+ );
5081
+ if (!fn) return {image: layer, position: '', size: '', repeat: ''};
5082
+ let depth = 0;
5083
+ let end = layer.length - 1;
5084
+ for (let i = fn[0].length - 1; i < layer.length; i++) {
5085
+ if (layer[i] === '(') depth++;
5086
+ if (layer[i] === ')' && --depth === 0) {
5087
+ end = i;
5088
+ break;
5089
+ }
5090
+ }
5091
+ const rest = splitTop(layer.slice(end + 1).trim(), ' ');
5092
+ const REPEAT = /^(repeat|no-repeat|repeat-x|repeat-y|space|round)$/i;
5093
+ const repeat = rest.filter(w => REPEAT.test(w)).join(' ');
5094
+ const words = rest.filter(w => !REPEAT.test(w)).join(' ');
5095
+ const [position = '', size = ''] = words.split('/').map(x => x.trim());
5096
+ return {image: layer.slice(0, end + 1), position, size, repeat};
5097
+ }
5098
+
5099
+ /** A side word in a longhand's name, in the order a box value lists sides. */
5100
+ const BOX_SIDES = ['top', 'right', 'bottom', 'left'];
5101
+
5102
+ /**
5103
+ * A block's longhands that follow a shorthand covering them, where the base
5104
+ * theme's block holds the same key, rewritten as that longhand's own sides
5105
+ * (padding-inline as padding-inline-start and -end, border-color as the
5106
+ * four side colors), in place and at the same position; a state's block
5107
+ * nested in it too. A longhand that is no side pair or box is kept.
5108
+ * @param {Record<string, any>} b
5109
+ * @param {Record<string, any> | undefined} baseBlock
5110
+ */
5111
+ function laterLonghandsAsSides(b, baseBlock) {
5112
+ if (
5113
+ !b ||
5114
+ typeof b !== 'object' ||
5115
+ !baseBlock ||
5116
+ typeof baseBlock !== 'object'
5117
+ )
5118
+ return;
5119
+ for (const [k, v] of Object.entries(b))
5120
+ if (k.startsWith(':') && v && typeof v === 'object')
5121
+ laterLonghandsAsSides(v, baseBlock[k]);
5122
+ const keys = Object.keys(b);
5123
+ /** @type {Record<string, any>} */
5124
+ const out = {};
5125
+ let changed = false;
5126
+ keys.forEach((k, i) => {
5127
+ const v = b[k];
5128
+ const css = kebab(k);
5129
+ const sides =
5130
+ typeof v === 'string' &&
5131
+ !k.startsWith('-') &&
5132
+ typeof baseBlock[k] === 'string' &&
5133
+ keys
5134
+ .slice(0, i)
5135
+ .some(e => !e.startsWith(':') && coversSide(kebab(e), css))
5136
+ ? sidesOf(css, v)
5137
+ : null;
5138
+ if (!sides) {
5139
+ out[k] = v;
5140
+ return;
5141
+ }
5142
+ changed = true;
5143
+ for (const [p, x] of Object.entries(sides)) {
5144
+ delete out[camel(p)];
5145
+ out[camel(p)] = x;
5146
+ }
5147
+ });
5148
+ if (!changed) return;
5149
+ for (const k of Object.keys(b)) delete b[k];
5150
+ Object.assign(b, out);
5151
+ }
5152
+
5153
+ /**
5154
+ * A two-sided (start/end) or four-sided (top/right/bottom/left) longhand's
5155
+ * value, as each side's property and value by the shorthand rules; null for
5156
+ * any other property.
5157
+ * @param {string} prop kebab-case
5158
+ * @param {string} v
5159
+ * @returns {Record<string, string> | null}
5160
+ */
5161
+ function sidesOf(prop, v) {
5162
+ const direct = [...longhandsOf(prop)].filter(p => longhandsOf(p).size === 0);
5163
+ const w = splitTop(v.trim(), ' ').map(x => x.trim());
5164
+ if (!w.length || /!important/i.test(v)) return null;
5165
+ const start = direct.find(p => /-start(-|$)/.test(p));
5166
+ const end = direct.find(p => /-end(-|$)/.test(p));
5167
+ if (direct.length === 2 && start && end && w.length <= 2)
5168
+ return {[start]: w[0], [end]: w[1] ?? w[0]};
5169
+ const named = BOX_SIDES.map(side =>
5170
+ direct.find(p => new RegExp(`-${side}(-|$)`).test(p)),
5171
+ );
5172
+ if (direct.length !== 4 || named.some(x => !x) || w.length > 4) return null;
5173
+ const [t, r = t, bo = t, l = r] = w;
5174
+ const vals = [t, r, bo, l];
5175
+ return Object.fromEntries(
5176
+ named.map((p, i) => [/** @type {string} */ (p), vals[i]]),
5177
+ );
5178
+ }
5179
+
3206
5180
  /** Core's default type scale ratio. */
3207
5181
  const STANDARD_RATIO = 1.2;
3208
5182
  /** The font-size tokens below the base, with their step on the scale. */
@@ -3314,10 +5288,10 @@ export function maskedSettings(data, ctx = null) {
3314
5288
  * {font-weight}`. Find those rules in the built stylesheet.
3315
5289
  * @param {string} cssText
3316
5290
  * @param {any} theme
3317
- * @returns {Array<{target: string, key: string, prop: string, value: string}>}
5291
+ * @returns {Array<{target: string, key: string, prop: string, value: string, state?: string}>}
3318
5292
  */
3319
5293
  export function findOverrides(cssText, theme) {
3320
- /** @type {Array<{target: string, key: string, prop: string, value: string}>} */
5294
+ /** @type {Array<{target: string, key: string, prop: string, value: string, state?: string}>} */
3321
5295
  const extra = [];
3322
5296
  for (const [target, keys] of Object.entries(
3323
5297
  /** @type {Record<string, any>} */ (theme.components ?? {}),
@@ -3362,6 +5336,51 @@ export function findOverrides(cssText, theme) {
3362
5336
  }
3363
5337
  }
3364
5338
  }
5339
+ // A state setting on the plain part (a whole-part hover) loses the same
5340
+ // way to a variant's own rule in that state: it is repeated there too.
5341
+ for (const [target, keys] of Object.entries(
5342
+ /** @type {Record<string, any>} */ (theme.components ?? {}),
5343
+ ))
5344
+ for (const [state, decl] of Object.entries(keys.base ?? {})) {
5345
+ if (!/^:[a-z-]+$/.test(state) || !decl || typeof decl !== 'object')
5346
+ continue;
5347
+ const props = Object.keys(decl).filter(
5348
+ p => !p.startsWith('--') && !p.startsWith(':'),
5349
+ );
5350
+ if (!props.length) continue;
5351
+ const re = new RegExp(
5352
+ `\\.astryx-${target.replace(/-/g, '\\-')}\\[data-([a-z-]+)="([^"]+)"\\](?:${state}(?![\\w-])[^{}]*|\\s*)\\{([^}]*)\\}`,
5353
+ 'g',
5354
+ );
5355
+ // The variant's own rule in that state, and its resting rule: that
5356
+ // one comes after the plain state rule at the same weight.
5357
+ const seen = new Set();
5358
+ for (const m of cssText.matchAll(re)) {
5359
+ const declared = [...m[3].matchAll(/(?:^|[;\s])([a-z-]+)\s*:/g)].map(
5360
+ d => d[1],
5361
+ );
5362
+ for (const prop of props) {
5363
+ const css = kebab(prop);
5364
+ if (css === m[1] || css.endsWith(`-${m[1]}`)) continue;
5365
+ if (
5366
+ !seen.has(`${m[1]}:${m[2]} ${prop}`) &&
5367
+ declared.some(
5368
+ d =>
5369
+ d === css || coversProperty(d, css) || coversProperty(css, d),
5370
+ )
5371
+ ) {
5372
+ seen.add(`${m[1]}:${m[2]} ${prop}`);
5373
+ extra.push({
5374
+ target,
5375
+ key: `${m[1]}:${m[2]}`,
5376
+ state,
5377
+ prop,
5378
+ value: decl[prop],
5379
+ });
5380
+ }
5381
+ }
5382
+ }
5383
+ }
3365
5384
  return extra;
3366
5385
  }
3367
5386
 
@@ -3384,8 +5403,43 @@ const liftValue = (lift, only) =>
3384
5403
  * @param {ThemeData} data
3385
5404
  * @param {any} theme
3386
5405
  * @param {import('./_palette.mjs').PaletteMapping | null} pal
5406
+ * @param {string} [cwd]
5407
+ * @param {Record<string, any> | null} [baseParts] the base theme's components, whose state objects each written one starts from
3387
5408
  */
3388
- function settingsSource(slug, data, theme, pal, cwd = '') {
5409
+ function settingsSource(slug, data, theme, pal, cwd = '', baseParts = null) {
5410
+ // Core merges a theme's state object (`:hover` in a rule) over the base
5411
+ // theme's whole, one level deep: each one starts as the base theme's own
5412
+ // for that rule, so the properties no setting names keep the base's.
5413
+ if (baseParts) {
5414
+ theme = {...theme, components: {...(theme.components ?? {})}};
5415
+ for (const [target, keys] of Object.entries(theme.components)) {
5416
+ /** @type {Record<string, any>} */
5417
+ const next = {};
5418
+ for (const [key, rule] of Object.entries(
5419
+ /** @type {Record<string, any>} */ (keys),
5420
+ )) {
5421
+ if (!rule || typeof rule !== 'object') {
5422
+ next[key] = rule;
5423
+ continue;
5424
+ }
5425
+ /** @type {Record<string, any>} */
5426
+ const r = {...rule};
5427
+ for (const [k, v] of Object.entries(rule)) {
5428
+ const own = baseParts[target]?.[key]?.[k];
5429
+ if (
5430
+ k.startsWith(':') &&
5431
+ v &&
5432
+ typeof v === 'object' &&
5433
+ own &&
5434
+ typeof own === 'object'
5435
+ )
5436
+ r[k] = {...own, ...v};
5437
+ }
5438
+ next[key] = r;
5439
+ }
5440
+ theme.components[target] = next;
5441
+ }
5442
+ }
3389
5443
  const like = data.like;
3390
5444
  const REF = '@@palette:';
3391
5445
  /** @param {string} family @param {'light' | 'dark'} m @param {import('./_palette.mjs').StopRef} r */
@@ -3613,54 +5667,197 @@ function isGeneratedPaletteFile(dir, slug, file) {
3613
5667
  }
3614
5668
 
3615
5669
  /**
3616
- * The theme module, written once: it extends the generated settings and is
3617
- * the person's own from then on, so hand edits in it survive every change.
3618
- * @param {string} slug
5670
+ * The theme module, written once: it extends the generated settings and is
5671
+ * the person's own from then on, so hand edits in it survive every change.
5672
+ * @param {string} slug
5673
+ */
5674
+ function themeModuleSource(slug) {
5675
+ return [
5676
+ `// The ${slug} theme. \`${P}\` wrote this file once and never changes it again.`,
5677
+ `// The checked settings live in ${slug}.settings.json and the generated ${slug}.settings.ts;`,
5678
+ `// change them with \`${P} set ${slug} ...\`. Add your own changes below: they win over the settings.`,
5679
+ "import {defineTheme} from '@astryxdesign/core/theme';",
5680
+ `import {${camel(slug)}Settings} from './${slug}.settings';`,
5681
+ '',
5682
+ `export const ${camel(slug)}Theme = defineTheme({`,
5683
+ ` extends: ${camel(slug)}Settings,`,
5684
+ ` name: '${slug}',`,
5685
+ '});',
5686
+ '',
5687
+ ].join('\n');
5688
+ }
5689
+
5690
+ /** The theme source as the editor first writes it. @param {string} slug */
5691
+ export const themeSource = slug => themeModuleSource(slug);
5692
+
5693
+ /**
5694
+ * Why a theme's source cannot carry its settings, or null when it carries
5695
+ * them. The theme is the export a build of the source reads, loaded as the
5696
+ * build loads it: it must be named for the theme, and its definition must
5697
+ * extend the settings imported from ./<slug>.settings. Null for a source
5698
+ * that does not parse: its parse error is its own finding.
5699
+ * @param {string} cwd
5700
+ * @param {string} slug
5701
+ * @returns {Promise<string | null>}
5702
+ */
5703
+ export async function themeSourceProblem(cwd, slug) {
5704
+ const f = themeFiles(cwd, slug);
5705
+ /** @type {string} */
5706
+ let code;
5707
+ try {
5708
+ code = fs.readFileSync(f.ts, 'utf8');
5709
+ } catch {
5710
+ return null;
5711
+ }
5712
+ /** @type {any} */
5713
+ let ast;
5714
+ try {
5715
+ ast = parseModule(code, {sourceType: 'module', plugins: ['typescript']});
5716
+ } catch {
5717
+ // Its parse error is its own finding (refuseThemeParse, the build).
5718
+ return null;
5719
+ }
5720
+ const settings = `${camel(slug)}Settings`;
5721
+ const fromSettings = new RegExp(`^\\./${slug}\\.settings(\\.[jt]s)?$`);
5722
+ /** @type {string | null} */
5723
+ let settingsBinding = null;
5724
+ for (const node of ast.program.body)
5725
+ if (
5726
+ node.type === 'ImportDeclaration' &&
5727
+ fromSettings.test(node.source.value)
5728
+ )
5729
+ for (const spec of node.specifiers)
5730
+ if (
5731
+ spec.type === 'ImportSpecifier' &&
5732
+ (spec.imported.name ?? spec.imported.value) === settings
5733
+ )
5734
+ settingsBinding = spec.local.name;
5735
+ if (!settingsBinding)
5736
+ return `${slug}.theme.ts does not import ./${slug}.settings`;
5737
+ /** @param {any} definition */
5738
+ const extendsSettings = definition =>
5739
+ unwrapConst(
5740
+ ast,
5741
+ definition?.properties.find(
5742
+ (/** @type {any} */ p) =>
5743
+ p.type === 'ObjectProperty' &&
5744
+ (p.key.name ?? p.key.value) === 'extends',
5745
+ )?.value,
5746
+ )?.name === settingsBinding;
5747
+ /** @type {{theme: any, exportName: string}} */
5748
+ let loaded;
5749
+ try {
5750
+ loaded = await loadThemeExport(f.ts, {cwd});
5751
+ } catch {
5752
+ // A module that does not load names no export. When none of its
5753
+ // exported definitions extends the settings, that is why (defineTheme
5754
+ // refuses a missing parent); else the build names its own failure.
5755
+ return exportedDefinitions(ast).some(extendsSettings)
5756
+ ? null
5757
+ : `${slug}.theme.ts no longer extends ${settings}`;
5758
+ }
5759
+ if (loaded.theme?.name !== slug)
5760
+ return `${slug}.theme.ts no longer names the theme '${slug}'`;
5761
+ if (!extendsSettings(exportedDefinition(ast, loaded.exportName)))
5762
+ return `${slug}.theme.ts no longer extends ${settings}`;
5763
+ return null;
5764
+ }
5765
+
5766
+ /**
5767
+ * A module's top-level const bindings, by name.
5768
+ * @param {any} ast
5769
+ * @returns {Map<string, any>}
5770
+ */
5771
+ function topConsts(ast) {
5772
+ /** @type {Map<string, any>} */
5773
+ const out = new Map();
5774
+ for (const node of ast.program.body) {
5775
+ const decl =
5776
+ node.type === 'ExportNamedDeclaration' ? node.declaration : node;
5777
+ if (decl?.type === 'VariableDeclaration')
5778
+ for (const d of decl.declarations)
5779
+ if (d.id.type === 'Identifier') out.set(d.id.name, d.init);
5780
+ }
5781
+ return out;
5782
+ }
5783
+
5784
+ /**
5785
+ * An expression with TypeScript wrappers and parentheses taken off, and a
5786
+ * name read through to the top-level const it names. An imported name stays
5787
+ * the identifier.
5788
+ * @param {any} ast
5789
+ * @param {any} node
5790
+ * @returns {any}
5791
+ */
5792
+ function unwrapConst(ast, node) {
5793
+ const consts = topConsts(ast);
5794
+ for (let depth = 0; node && depth < 20; depth++) {
5795
+ if (
5796
+ [
5797
+ 'TSAsExpression',
5798
+ 'TSSatisfiesExpression',
5799
+ 'TSNonNullExpression',
5800
+ 'TSTypeAssertion',
5801
+ 'ParenthesizedExpression',
5802
+ ].includes(node.type)
5803
+ )
5804
+ node = node.expression;
5805
+ else if (node.type === 'Identifier' && consts.get(node.name))
5806
+ node = consts.get(node.name);
5807
+ else return node;
5808
+ }
5809
+ return node;
5810
+ }
5811
+
5812
+ /**
5813
+ * The theme definitions of every export of a module.
5814
+ * @param {any} ast
5815
+ * @returns {any[]} ObjectExpressions
3619
5816
  */
3620
- function themeModuleSource(slug) {
3621
- return [
3622
- `// The ${slug} theme. \`${P}\` wrote this file once and never changes it again.`,
3623
- `// The checked settings live in ${slug}.settings.json and the generated ${slug}.settings.ts;`,
3624
- `// change them with \`${P} set ${slug} ...\`. Add your own changes below: they win over the settings.`,
3625
- "import {defineTheme} from '@astryxdesign/core/theme';",
3626
- `import {${camel(slug)}Settings} from './${slug}.settings';`,
3627
- '',
3628
- `export const ${camel(slug)}Theme = defineTheme({`,
3629
- ` extends: ${camel(slug)}Settings,`,
3630
- ` name: '${slug}',`,
3631
- '});',
3632
- '',
3633
- ].join('\n');
5817
+ function exportedDefinitions(ast) {
5818
+ /** @type {string[]} */
5819
+ const names = [];
5820
+ for (const node of ast.program.body) {
5821
+ if (node.type === 'ExportDefaultDeclaration') names.push('default');
5822
+ if (node.type !== 'ExportNamedDeclaration' || node.source) continue;
5823
+ if (node.declaration?.type === 'VariableDeclaration')
5824
+ for (const d of node.declaration.declarations)
5825
+ if (d.id.type === 'Identifier') names.push(d.id.name);
5826
+ for (const spec of node.specifiers ?? [])
5827
+ names.push(spec.exported.name ?? spec.exported.value);
5828
+ }
5829
+ return names.map(n => exportedDefinition(ast, n)).filter(Boolean);
3634
5830
  }
3635
5831
 
3636
- /** The theme source as the editor first writes it. @param {string} slug */
3637
- export const themeSource = slug => themeModuleSource(slug);
3638
-
3639
5832
  /**
3640
- * Why `<slug>.theme.ts` cannot carry the settings, or null: it must import
3641
- * `./<slug>.settings`, extend `<camel>Settings` and keep the name, or no
3642
- * setting takes effect.
3643
- * @param {string} cwd
3644
- * @param {string} slug
3645
- * @returns {string | null}
5833
+ * The object a module export defines its theme with: the argument of the
5834
+ * `defineTheme(...)` call, or the object itself, that the export names.
5835
+ * @param {any} ast
5836
+ * @param {string} exportName
5837
+ * @returns {any} an ObjectExpression, or null
3646
5838
  */
3647
- export function themeSourceProblem(cwd, slug) {
3648
- const f = themeFiles(cwd, slug);
3649
- if (!fs.existsSync(f.ts)) return null;
3650
- const code = fs
3651
- .readFileSync(f.ts, 'utf8')
3652
- .replace(/\/\*[\s\S]*?\*\//g, '')
3653
- .replace(/\/\/.*$/gm, '');
3654
- const settings = `${camel(slug)}Settings`;
3655
- if (
3656
- !new RegExp(`from\\s+['"]\\./${slug}\\.settings(\\.[jt]s)?['"]`).test(code)
3657
- )
3658
- return `${slug}.theme.ts does not import ./${slug}.settings`;
3659
- if (!new RegExp(`extends\\s*:\\s*${settings}\\b`).test(code))
3660
- return `${slug}.theme.ts no longer extends ${settings}`;
3661
- if (!new RegExp(`name\\s*:\\s*(['"\`])${slug}\\1`).test(code))
3662
- return `${slug}.theme.ts no longer names the theme '${slug}'`;
3663
- return null;
5839
+ function exportedDefinition(ast, exportName) {
5840
+ /** @type {any} */
5841
+ let value = null;
5842
+ for (const node of ast.program.body) {
5843
+ if (node.type === 'ExportDefaultDeclaration' && exportName === 'default')
5844
+ value = node.declaration;
5845
+ if (node.type !== 'ExportNamedDeclaration') continue;
5846
+ if (node.declaration?.type === 'VariableDeclaration')
5847
+ for (const d of node.declaration.declarations)
5848
+ if (d.id.type === 'Identifier' && d.id.name === exportName)
5849
+ value = d.init;
5850
+ for (const spec of node.specifiers ?? [])
5851
+ if (
5852
+ !node.source &&
5853
+ (spec.exported.name ?? spec.exported.value) === exportName
5854
+ )
5855
+ value = spec.local;
5856
+ }
5857
+ value = unwrapConst(ast, value);
5858
+ if (value?.type === 'CallExpression')
5859
+ value = unwrapConst(ast, value.arguments[0]);
5860
+ return value?.type === 'ObjectExpression' ? value : null;
3664
5861
  }
3665
5862
 
3666
5863
  /**
@@ -3715,97 +5912,153 @@ export function refuseThemeParse(cwd, slug) {
3715
5912
  * @param {string} cwd
3716
5913
  * @param {string} slug
3717
5914
  */
3718
- export function refuseThemeSource(cwd, slug) {
5915
+ export async function refuseThemeSource(cwd, slug) {
3719
5916
  refuseThemeParse(cwd, slug);
3720
- 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
- );
5917
+ const refusal = await themeSourceRefusal(cwd, slug);
5918
+ if (refusal) throw refusal;
3727
5919
  }
3728
5920
 
3729
5921
  /**
3730
- * Refuse a [light, dark] pair the theme's own source gives a token that is
3731
- * not a color (a font family, a size, a weight): the build would write
3732
- * `light-dark()`, which browsers take only for colors. The editor refuses
3733
- * `--mode` on those tokens for the same reason.
3734
- * @param {Ctx} ctx
5922
+ * The refusal for a theme source that cannot carry the settings (it no
5923
+ * longer imports or extends them, or names another theme), naming the
5924
+ * lines that put it back; null when it carries them. Every command that
5925
+ * builds the theme refuses with it.
3735
5926
  * @param {string} cwd
3736
5927
  * @param {string} slug
5928
+ * @returns {Promise<AstryxError | null>}
3737
5929
  */
3738
- function refuseOwnPairs(ctx, cwd, slug) {
3739
- const f = themeFiles(cwd, slug);
3740
- /** @type {string[]} */
3741
- const bad = [];
5930
+ export async function themeSourceRefusal(cwd, slug) {
5931
+ const why = await themeSourceProblem(cwd, slug);
5932
+ return why
5933
+ ? new AstryxError(
5934
+ `${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.`,
5935
+ [{name: `${P} show ${slug}`, reason: 'see the theme as it is'}],
5936
+ ERROR_CODES.ERR_THEME_INVALID,
5937
+ )
5938
+ : null;
5939
+ }
5940
+
5941
+ /**
5942
+ * What a build made now writes for a theme: its own page-wide tokens (see
5943
+ * builtOwnTokens), every top-level token, and the typography it was given
5944
+ * (evaluated: an import or an expression is its value). Null when it does
5945
+ * not build in the project's cache folder.
5946
+ * @param {Ctx} ctx
5947
+ * @param {string} slug
5948
+ * @param {string | null} like the base theme, whose built tokens are `base`
5949
+ * @returns {Promise<{own: Map<string, string | null>, tops: Map<string, string | null>, base: Map<string, string | null>, shapes: Map<string, BuiltShape>, typography: any} | null>}
5950
+ */
5951
+ export async function evaluatedTheme(ctx, slug, like) {
5952
+ const baseFile = like ? baseModule(ctx.project.cwd, like) : null;
5953
+ return cacheBuild(ctx, slug, js => {
5954
+ const read = builtModule(js);
5955
+ return {
5956
+ own: builtOwnTokens(ctx.project.cwd, slug, js) ?? new Map(),
5957
+ tops: topTokensOf(js),
5958
+ base: baseFile ? topTokensOf(baseFile) : new Map(),
5959
+ shapes: read.shapes,
5960
+ typography: read.axes?.typography ?? null,
5961
+ };
5962
+ });
5963
+ }
5964
+
5965
+ /**
5966
+ * What a built module writes for a top-level token: text, a number, an
5967
+ * object, a pair (each half), or something else.
5968
+ * @typedef {{kind: 'text' | 'number' | 'object' | 'pair' | 'other', value?: any, halves?: unknown[]}} BuiltShape
5969
+ */
5970
+
5971
+ /**
5972
+ * What a built theme module holds: the shape of each top-level token, and
5973
+ * its `__axes` (the typography and motion it was given, evaluated).
5974
+ * @param {string} js
5975
+ * @returns {{shapes: Map<string, BuiltShape>, axes: any}}
5976
+ */
5977
+ function builtModule(js) {
5978
+ /** @type {Map<string, BuiltShape>} */
5979
+ const shapes = new Map();
3742
5980
  try {
3743
5981
  const ast = /** @type {any} */ (
3744
- parseModule(fs.readFileSync(f.ts, 'utf8'), {
5982
+ parseModule(fs.readFileSync(js, 'utf8'), {
3745
5983
  sourceType: 'module',
3746
5984
  plugins: ['typescript'],
3747
5985
  })
3748
5986
  );
3749
- /** @param {any} node */
3750
- const visit = node => {
5987
+ /** @param {any} n @returns {any} */
5988
+ const plain = n =>
5989
+ n?.type === 'StringLiteral' || n?.type === 'NumericLiteral'
5990
+ ? n.value
5991
+ : n?.type === 'UnaryExpression' && n.operator === '-'
5992
+ ? -plain(n.argument)
5993
+ : n?.type === 'NullLiteral'
5994
+ ? null
5995
+ : n?.type === 'ObjectExpression'
5996
+ ? Object.fromEntries(
5997
+ n.properties.map((/** @type {any} */ p) => [
5998
+ p.key?.value ?? p.key?.name,
5999
+ plain(p.value),
6000
+ ]),
6001
+ )
6002
+ : n?.type === 'ArrayExpression'
6003
+ ? n.elements.map(plain)
6004
+ : undefined;
6005
+ /** @type {any} */
6006
+ let axes = null;
6007
+ /** @type {any} */
6008
+ let tokens = null;
6009
+ /** @param {any} node @param {number} depth */
6010
+ const visit = (node, depth) => {
3751
6011
  if (!node || typeof node !== 'object') return;
3752
- if (
3753
- node.type === 'ObjectProperty' &&
3754
- typeof (node.key?.value ?? node.key?.name) === 'string' &&
3755
- String(node.key?.value ?? node.key?.name).startsWith('--') &&
3756
- node.value?.type === 'ArrayExpression' &&
3757
- node.value.elements.length === 2 &&
3758
- // A pair holding a value that is not text is named by the value
3759
- // checks, with the fix for that value.
3760
- node.value.elements.every(
3761
- (/** @type {any} */ e) =>
3762
- e?.type === 'StringLiteral' || e?.type === 'TemplateLiteral',
6012
+ if (node.type === 'ObjectProperty') {
6013
+ const k = node.key?.name ?? node.key?.value;
6014
+ if (k === '__axes' && !axes) axes = plain(node.value);
6015
+ // The theme's own top-level tokens: the first `tokens` object.
6016
+ if (
6017
+ k === 'tokens' &&
6018
+ !tokens &&
6019
+ node.value?.type === 'ObjectExpression'
3763
6020
  )
3764
- ) {
3765
- const k = String(node.key.value ?? node.key.name);
3766
- const type = ctx.C.typeOf(k);
3767
- // A size given as a bare number is named by the value check, with
3768
- // the unit it needs.
3769
- const unitless =
3770
- type === 'size' &&
3771
- node.value.elements.some(
3772
- (/** @type {any} */ e) =>
3773
- e?.type === 'StringLiteral' && /^\d*\.?\d+$/.test(e.value.trim()),
3774
- );
3775
- if (type !== 'color' && !unitless) bad.push(k);
6021
+ tokens = node.value;
3776
6022
  }
3777
6023
  for (const v of Object.values(node))
3778
- if (Array.isArray(v)) v.forEach(visit);
3779
- else if (v && typeof v === 'object' && v.type) visit(v);
6024
+ if (Array.isArray(v)) v.forEach(c => visit(c, depth + 1));
6025
+ else if (v && typeof v === 'object' && v.type) visit(v, depth + 1);
3780
6026
  };
3781
- visit(ast.program);
6027
+ visit(ast.program, 0);
6028
+ for (const p of tokens?.properties ?? []) {
6029
+ const k = p.key?.value ?? p.key?.name;
6030
+ if (typeof k !== 'string') continue;
6031
+ const v = p.value;
6032
+ shapes.set(
6033
+ k,
6034
+ v?.type === 'StringLiteral'
6035
+ ? {kind: 'text', value: v.value}
6036
+ : v?.type === 'NumericLiteral'
6037
+ ? {kind: 'number', value: v.value}
6038
+ : v?.type === 'ObjectExpression'
6039
+ ? {kind: 'object', value: plain(v)}
6040
+ : v?.type === 'ArrayExpression'
6041
+ ? {kind: 'pair', halves: plain(v)}
6042
+ : {kind: 'other'},
6043
+ );
6044
+ }
6045
+ return {shapes, axes};
3782
6046
  } catch {
3783
- return;
6047
+ return {shapes, axes: null};
3784
6048
  }
3785
- if (bad.length)
3786
- throw new AstryxError(
3787
- ownPairMessage(slug, [...new Set(bad)]),
3788
- [
3789
- {
3790
- name: `grep -n -- ${quoteCommandArgument(bad[0])} ${quoteCommandArgument(`themes/${slug}/${slug}.theme.ts`)}`,
3791
- reason: 'see the line',
3792
- },
3793
- ],
3794
- ERROR_CODES.ERR_THEME_INVALID,
3795
- );
3796
6049
  }
3797
6050
 
3798
6051
  /**
3799
- * The tokens that are not colors the theme as it builds now gives a
3800
- * [light, dark] pair (light-dark()), however its file writes them (a
3801
- * constant, `as const`, `satisfies`, a spread from an imported module):
3802
- * read from a build made into the project's cache folder, never beside the
3803
- * theme. Empty when it does not build there (the build names that itself).
6052
+ * Build the theme into the project's cache folder and read the built
6053
+ * module with `read` before the folder is removed; null when it does not
6054
+ * build there.
6055
+ * @template T
3804
6056
  * @param {Ctx} ctx
3805
6057
  * @param {string} slug
3806
- * @returns {Promise<string[]>}
6058
+ * @param {(js: string) => T} read
6059
+ * @returns {Promise<T | null>}
3807
6060
  */
3808
- export async function builtPairs(ctx, slug) {
6061
+ async function cacheBuild(ctx, slug, read) {
3809
6062
  const {cwd} = ctx.project;
3810
6063
  const f = themeFiles(cwd, slug);
3811
6064
  // The build writes only inside the project: the cache folder when it is
@@ -3826,15 +6079,10 @@ export async function builtPairs(ctx, slug) {
3826
6079
  const js = fs
3827
6080
  .readdirSync(dir)
3828
6081
  .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);
6082
+ if (!js) return null;
6083
+ return read(path.join(dir, js));
3836
6084
  } catch {
3837
- return [];
6085
+ return null;
3838
6086
  } finally {
3839
6087
  logger.setSilent(silent);
3840
6088
  fs.rmSync(dir, {recursive: true, force: true});
@@ -3850,6 +6098,21 @@ export function ownPairMessage(slug, names) {
3850
6098
  return `themes/${slug}/${slug}.theme.ts gives ${names.join(', ')} a [light, dark] pair, but only colors differ by mode: the build would write light-dark(), which browsers take only for colors. Give ${names.length > 1 ? 'each' : 'it'} one value in ${slug}.theme.ts. Nothing was changed.`;
3851
6099
  }
3852
6100
 
6101
+ /**
6102
+ * The check of a theme's own token values, run before every build, set by
6103
+ * the editor (which owns the checks a value meets): null until it is set.
6104
+ * @type {((ctx: Ctx, slug: string, data: ThemeData) => Promise<void>) | null}
6105
+ */
6106
+ let ownTokenCheck = null;
6107
+
6108
+ /**
6109
+ * Set the check of a theme's own token values run before every build.
6110
+ * @param {((ctx: Ctx, slug: string, data: ThemeData) => Promise<void>) | null} fn
6111
+ */
6112
+ export function setOwnTokenCheck(fn) {
6113
+ ownTokenCheck = fn;
6114
+ }
6115
+
3853
6116
  /**
3854
6117
  * What runs after every build of a theme, set by the adapter (the app copy
3855
6118
  * of the theme): null until it is set.
@@ -3893,8 +6156,10 @@ export function holdAfterBuild(ctx) {
3893
6156
  export async function buildTheme(ctx, slug, data) {
3894
6157
  const {cwd} = ctx.project;
3895
6158
  const f = themeFiles(cwd, slug);
3896
- refuseThemeSource(cwd, slug);
3897
- refuseOwnPairs(ctx, cwd, slug);
6159
+ await refuseThemeSource(cwd, slug);
6160
+ // The theme's own token values, judged as a build of the source writes
6161
+ // them, before anything is written.
6162
+ await ownTokenCheck?.(ctx, slug, data);
3898
6163
  if (data.like) baseThemeFile(ctx.project, data.like);
3899
6164
  const base = await baseResolved(ctx.project, data.like);
3900
6165
  fs.mkdirSync(f.dir, {recursive: true});
@@ -3933,7 +6198,17 @@ export async function buildTheme(ctx, slug, data) {
3933
6198
  ctx.keepStops,
3934
6199
  );
3935
6200
  await step(() => {
3936
- writeWhole(f.settingsTs, settingsSource(slug, data, theme, pal, cwd));
6201
+ writeWhole(
6202
+ f.settingsTs,
6203
+ settingsSource(
6204
+ slug,
6205
+ data,
6206
+ theme,
6207
+ pal,
6208
+ cwd,
6209
+ /** @type {any} */ (base).components ?? null,
6210
+ ),
6211
+ );
3937
6212
  syncPaletteRefs(cwd, slug, fs.readFileSync(f.settingsTs, 'utf8'), pal);
3938
6213
  if (!fs.existsSync(f.ts)) writeWhole(f.ts, themeModuleSource(slug));
3939
6214
  });
@@ -3949,7 +6224,7 @@ export async function buildTheme(ctx, slug, data) {
3949
6224
  .filter(
3950
6225
  n =>
3951
6226
  /^(sheet|preview)(-[a-z-]+)?\.png$/.test(n) &&
3952
- editorWrote(cwd, slug, path.join(f.dir, n)),
6227
+ editorRecorded(cwd, slug, path.join(f.dir, n)),
3953
6228
  )
3954
6229
  : [];
3955
6230
  for (const file of [
@@ -3959,9 +6234,47 @@ export async function buildTheme(ctx, slug, data) {
3959
6234
  fs.rmSync(file, {force: true});
3960
6235
  forgetWritten(cwd, slug, pictures);
3961
6236
  });
3962
- let receipt = await step(() => runBuild(ctx, slug));
6237
+ let receipt = await step(() => runBuild(ctx, slug, data));
6238
+ // A state setting on the plain part that the own source's same state
6239
+ // rule wins over is not repeated on the variants either: the own source
6240
+ // wins on every variant, as the result says.
6241
+ /** @type {Map<string, Map<string, string | null>>} */
6242
+ const ownStates = new Map();
6243
+ /** @param {string} target @param {string} state @param {string} prop */
6244
+ const ownHolds = (target, state, prop) => {
6245
+ const k = `${target} ${state}`;
6246
+ const own =
6247
+ ownStates.get(k) ?? ownPartTokens(cwd, slug, target, 'base', state);
6248
+ ownStates.set(k, own);
6249
+ const css = kebab(prop);
6250
+ return [...own.keys()].some(
6251
+ o => o === css || coversProperty(o, css) || coversProperty(css, o),
6252
+ );
6253
+ };
3963
6254
  const found = findOverrides(fs.readFileSync(f.css, 'utf8'), theme).filter(
3964
- x => !(theme.components[x.target][x.key] ?? {})[x.prop],
6255
+ x =>
6256
+ // By property: a variant whose rule the settings give this property
6257
+ // or a shorthand covering it needs no copy; nor one holding a
6258
+ // longhand of it that the base theme's rule also holds and that has
6259
+ // no sides to be written as (a background color, one-mode or not):
6260
+ // the copy would come after it there and win. Any other longhand
6261
+ // takes the copy, then is written after it (as its sides where the
6262
+ // base holds it).
6263
+ !Object.entries(
6264
+ (x.state
6265
+ ? theme.components[x.target][x.key]?.[x.state]
6266
+ : theme.components[x.target][x.key]) ?? {},
6267
+ ).some(([k, v]) => {
6268
+ if (k.startsWith(':')) return false;
6269
+ if (k === x.prop || coversProperty(kebab(k), kebab(x.prop)))
6270
+ return true;
6271
+ if (!coversProperty(kebab(x.prop), kebab(k))) return false;
6272
+ const baseRule = /** @type {any} */ (base).components?.[x.target]?.[
6273
+ x.key
6274
+ ];
6275
+ const held = (x.state ? baseRule?.[x.state] : baseRule)?.[k];
6276
+ return held != null && sidesOf(kebab(k), String(v)) == null;
6277
+ }) && !(x.state && ownHolds(x.target, x.state, x.prop)),
3965
6278
  );
3966
6279
  /** @type {string[]} */
3967
6280
  const lifted = [];
@@ -3972,19 +6285,42 @@ export async function buildTheme(ctx, slug, data) {
3972
6285
  // longhand or shorthand the variant sets itself (border-color after
3973
6286
  // a base border) still wins over it.
3974
6287
  const own = t[x.key] ?? {};
6288
+ const ownState = x.state ? (own[x.state] ?? {}) : own;
3975
6289
  // A variant that sets every longhand of the property itself needs
3976
6290
  // none of the base value (and a lifted radius would feed Core's copy
3977
6291
  // of it into the content's radius, after the variant's own).
3978
6292
  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)}`);
6293
+ if (longs.length && longs.every(l => camel(l) in ownState)) continue;
6294
+ t[x.key] = x.state
6295
+ ? {...own, [x.state]: {[x.prop]: x.value, ...ownState}}
6296
+ : {[x.prop]: x.value, ...own};
6297
+ // The variant's own longhands come after the copied shorthand; one
6298
+ // the base theme holds would keep the base's earlier place and lose,
6299
+ // so it is written as its sides.
6300
+ const baseRule = /** @type {any} */ (base).components?.[x.target]?.[
6301
+ x.key
6302
+ ];
6303
+ laterLonghandsAsSides(
6304
+ x.state ? t[x.key][x.state] : t[x.key],
6305
+ x.state ? baseRule?.[x.state] : baseRule,
6306
+ );
6307
+ lifted.push(`${x.target} ${x.key}${x.state ?? ''} ${kebab(x.prop)}`);
3982
6308
  }
3983
6309
  await step(() => {
3984
- writeWhole(f.settingsTs, settingsSource(slug, data, theme, pal, cwd));
6310
+ writeWhole(
6311
+ f.settingsTs,
6312
+ settingsSource(
6313
+ slug,
6314
+ data,
6315
+ theme,
6316
+ pal,
6317
+ cwd,
6318
+ /** @type {any} */ (base).components ?? null,
6319
+ ),
6320
+ );
3985
6321
  syncPaletteRefs(cwd, slug, fs.readFileSync(f.settingsTs, 'utf8'), pal);
3986
6322
  });
3987
- receipt = await step(() => runBuild(ctx, slug));
6323
+ receipt = await step(() => runBuild(ctx, slug, data));
3988
6324
  }
3989
6325
  for (const out of [f.css, f.js])
3990
6326
  if (fs.existsSync(out))
@@ -4005,8 +6341,34 @@ export async function buildTheme(ctx, slug, data) {
4005
6341
  return {warnings, lifted, notes};
4006
6342
  }
4007
6343
 
4008
- /** @param {Ctx} ctx @param {string} slug @returns {Promise<any>} */
4009
- async function runBuild(ctx, slug) {
6344
+ /**
6345
+ * The one color mode of a light-only or dark-only theme, from its settings,
6346
+ * for the build to write into the built module (`colorModes`); null for a
6347
+ * theme with both modes.
6348
+ * @param {string} cwd
6349
+ * @param {string} slug
6350
+ * @returns {['light'] | ['dark'] | null}
6351
+ */
6352
+ export function buildColorModes(cwd, slug) {
6353
+ try {
6354
+ return oneColorMode(
6355
+ modesOf(
6356
+ settingsJson(fs.readFileSync(themeFiles(cwd, slug).settings, 'utf8')),
6357
+ ),
6358
+ );
6359
+ } catch {
6360
+ return null;
6361
+ }
6362
+ }
6363
+
6364
+ /**
6365
+ * @param {Ctx} ctx
6366
+ * @param {string} slug
6367
+ * @param {{mode?: string}} [data] the settings being built (saved after the
6368
+ * build), whose mode the built module exports
6369
+ * @returns {Promise<any>}
6370
+ */
6371
+ async function runBuild(ctx, slug, data) {
4010
6372
  const {cwd} = ctx.project;
4011
6373
  const f = themeFiles(cwd, slug);
4012
6374
  const silent = logger.silent;
@@ -4020,6 +6382,11 @@ async function runBuild(ctx, slug) {
4020
6382
  {},
4021
6383
  {cwd},
4022
6384
  {compact: true},
6385
+ {
6386
+ colorModes: data
6387
+ ? oneColorMode(modesOf(data))
6388
+ : buildColorModes(cwd, slug),
6389
+ },
4023
6390
  );
4024
6391
  return receipt;
4025
6392
  } finally {
@@ -4046,6 +6413,7 @@ export async function outputsDrift(ctx, slug) {
4046
6413
  {check: true},
4047
6414
  {cwd},
4048
6415
  {compact: true},
6416
+ {colorModes: buildColorModes(cwd, slug)},
4049
6417
  );
4050
6418
  const first = /** @type {any} */ (receipt)?.data?.stale?.[0];
4051
6419
  if (!first) return null;
@@ -4227,7 +6595,7 @@ function nonTextToken(t, typeOf = (/** @type {string} */ _k) => 'other') {
4227
6595
  * @param {string} slug
4228
6596
  * @param {[string, unknown, ('object' | 'pair' | 'unit' | 'value' | 'mode')?]} bad
4229
6597
  */
4230
- function nonTextMessage(ctx, slug, [name, value, kind = 'value']) {
6598
+ export function nonTextMessage(ctx, slug, [name, value, kind = 'value']) {
4231
6599
  const type = ctx.C.typeOf(name);
4232
6600
  if (kind === 'mode') return ownPairMessage(slug, [name]);
4233
6601
  if (kind === 'object')
@@ -4442,18 +6810,141 @@ export async function contrastProblems(ctx, data, res) {
4442
6810
  * @returns {ThemeData | null}
4443
6811
  */
4444
6812
  function parseSettings(text) {
4445
- if (text == null) return null;
6813
+ const data = settingsJson(text);
6814
+ return entriesReadable(data) ? data : null;
6815
+ }
6816
+
6817
+ /**
6818
+ * A settings file's or an undo step's text as JSON, a byte-order mark
6819
+ * aside; undefined when there is no text or it does not parse. Every reader
6820
+ * of settings text reads it here.
6821
+ * @param {string | null | undefined} text
6822
+ * @returns {any}
6823
+ */
6824
+ export function settingsJson(text) {
6825
+ if (text == null) return undefined;
4446
6826
  try {
4447
- const data = JSON.parse(text);
4448
- return settingsShapeOk(data) ? data : null;
6827
+ return JSON.parse(text.replace(/^\uFEFF/, ''));
4449
6828
  } catch {
4450
- return null;
6829
+ return undefined;
6830
+ }
6831
+ }
6832
+
6833
+ /**
6834
+ * Whether settings data has its shape and every entry is an object with a
6835
+ * thing name: what a reader may go through entry by entry. Any other entry
6836
+ * (null, a number, text) is damage the file check names.
6837
+ * @param {any} data
6838
+ */
6839
+ export function entriesReadable(data) {
6840
+ return (
6841
+ settingsShapeOk(data) &&
6842
+ data.settings.every(
6843
+ (/** @type {any} */ s) =>
6844
+ s != null &&
6845
+ typeof s === 'object' &&
6846
+ !Array.isArray(s) &&
6847
+ typeof s.thing === 'string',
6848
+ )
6849
+ );
6850
+ }
6851
+
6852
+ /**
6853
+ * Read a damaged mode or base the way a change reads it, in place: one
6854
+ * written in other letters or as a package name (`Dark-Only`,
6855
+ * `@astryxdesign/theme-neutral`) is the value meant; any other goes back to
6856
+ * its default. `like: "none"` is no base. The field a command sets itself
6857
+ * is left to that command.
6858
+ * @param {any} data
6859
+ * @param {string} cwd
6860
+ * @param {string} [fixing] `mode` or `base` when the command sets it
6861
+ * @returns {string[]} a note for each field read differently from the file
6862
+ */
6863
+ export function readFields(data, cwd, fixing) {
6864
+ /** @type {string[]} */
6865
+ const notes = [];
6866
+ const meant = fieldsMeant(data);
6867
+ if (
6868
+ fixing !== 'mode' &&
6869
+ !['both', 'light-only', 'dark-only'].includes(data.mode)
6870
+ ) {
6871
+ if (['both', 'light-only', 'dark-only'].includes(meant.mode)) {
6872
+ notes.push(
6873
+ `mode was written "${data.mode}", so it is saved as ${meant.mode}`,
6874
+ );
6875
+ data.mode = meant.mode;
6876
+ } else {
6877
+ data.mode = 'both';
6878
+ notes.push('mode was missing or damaged, so it is both again');
6879
+ }
6880
+ }
6881
+ if (data.like === 'none') delete data.like;
6882
+ if (fixing !== 'base' && data.like != null && !LIKE.includes(data.like)) {
6883
+ if (LIKE.includes(meant.like) && baseInstalled(cwd, meant.like)) {
6884
+ notes.push(
6885
+ `base was written "${data.like}", so it is saved as ${meant.like}`,
6886
+ );
6887
+ data.like = meant.like;
6888
+ } else {
6889
+ delete data.like;
6890
+ notes.push('base was not a built-in theme, so it is none again');
6891
+ }
4451
6892
  }
6893
+ return notes;
6894
+ }
6895
+
6896
+ /**
6897
+ * The text an undo step keeps for the settings before a change: the file
6898
+ * as the change read it (entry words and fields read as meant), so the
6899
+ * step back restores what the change started from and passes undo's check.
6900
+ * Text that reads as written is kept byte for byte.
6901
+ * @param {string} text
6902
+ * @param {string} cwd
6903
+ * @param {Record<string, string> | null} radii the whole-theme radii it was built with
6904
+ */
6905
+ function stepText(text, cwd, radii) {
6906
+ const data = settingsJson(text);
6907
+ if (!entriesReadable(data)) return text;
6908
+ const asWritten = JSON.stringify(data);
6909
+ readAsMeant(data, cwd);
6910
+ return JSON.stringify(data) !== asWritten
6911
+ ? `${JSON.stringify(radii ? {...data, built: {radii}} : data, null, 2)}\n`
6912
+ : withBuilt(text, radii);
6913
+ }
6914
+
6915
+ /**
6916
+ * Read settings data as a change reads it, in place: entry modes and
6917
+ * sources in other words, and a damaged mode or base (see
6918
+ * {@link readFields}). The settings file and every undo step are read
6919
+ * through here.
6920
+ * @param {any} data
6921
+ * @param {string} cwd
6922
+ * @param {string} [fixing] `mode` or `base` when the command sets it
6923
+ * @returns {string[]} a note for each thing read differently from the text
6924
+ */
6925
+ export function readAsMeant(data, cwd, fixing) {
6926
+ readEntryWords(data);
6927
+ return [...entryNotes(data), ...readFields(data, cwd, fixing)];
6928
+ }
6929
+
6930
+ /**
6931
+ * Whether every settings entry has the parts the editor reads (a thing, a
6932
+ * value and a source); one without is damage `new` keeps aside.
6933
+ * @param {any} data
6934
+ */
6935
+ export function settingsEntriesOk(data) {
6936
+ return (
6937
+ entriesReadable(data) &&
6938
+ data.settings.every(
6939
+ (/** @type {any} */ s) =>
6940
+ 'value' in s && ['dial', 'token', 'property'].includes(s.source),
6941
+ )
6942
+ );
4452
6943
  }
4453
6944
 
4454
6945
  /**
4455
- * Whether parsed settings have the shape the editor reads: an object with a
4456
- * list of settings.
6946
+ * Whether settings data has the shape the editor reads: an object with a
6947
+ * settings list.
4457
6948
  * @param {any} data
4458
6949
  */
4459
6950
  export function settingsShapeOk(data) {
@@ -4465,6 +6956,23 @@ export function settingsShapeOk(data) {
4465
6956
  );
4466
6957
  }
4467
6958
 
6959
+ /**
6960
+ * The settings as the file keeps them: a setting's `note` is what the
6961
+ * command that made it says in its result, not part of the setting.
6962
+ * @param {ThemeData} data
6963
+ * @returns {ThemeData}
6964
+ */
6965
+ function savedForm(data) {
6966
+ return {
6967
+ ...data,
6968
+ settings: data.settings.map(s => {
6969
+ const entry = {...s};
6970
+ delete entry.note;
6971
+ return entry;
6972
+ }),
6973
+ };
6974
+ }
6975
+
4468
6976
  /**
4469
6977
  * Every regular file under `dir` and the hash of its bytes; empty when
4470
6978
  * there is no folder.
@@ -4521,6 +7029,34 @@ export function focusStateOf(ctx, part) {
4521
7029
  return null;
4522
7030
  }
4523
7031
 
7032
+ /** The radius tokens the corners dial moves. */
7033
+ export const DIAL_RADII = [
7034
+ '--radius-element',
7035
+ '--radius-inner',
7036
+ '--radius-container',
7037
+ '--radius-page',
7038
+ ];
7039
+
7040
+ /**
7041
+ * The parts that draw a part's corners: the part itself, or, when Core gives
7042
+ * it no radius of its own, the parts inside it that it has (a date-time
7043
+ * input's date and time boxes).
7044
+ * @param {Ctx} ctx
7045
+ * @param {string} part
7046
+ * @returns {string[]}
7047
+ */
7048
+ export function cornerParts(ctx, part) {
7049
+ const rec = ctx.C.MAP[part];
7050
+ if (!rec || rec.own?.['border-radius']) return [part];
7051
+ const inner = (rec.contains ?? []).filter(
7052
+ (/** @type {string} */ t) =>
7053
+ ctx.C.MAP[t]?.own?.['border-radius'] &&
7054
+ t.startsWith(`${part}-`) &&
7055
+ ctx.project.target.has(t),
7056
+ );
7057
+ return inner.length ? inner : [part];
7058
+ }
7059
+
4524
7060
  /**
4525
7061
  * The radius token a part's resting corners read. A part the census saw
4526
7062
  * closed (a menu, a popover) has none recorded: a container or menu reads
@@ -4583,6 +7119,47 @@ export function stateKey(state, wrapsControl = false) {
4583
7119
  : ':is(:disabled,[aria-disabled="true"])';
4584
7120
  }
4585
7121
 
7122
+ /**
7123
+ * The text color tokens Core's elements inside a part read for their own
7124
+ * color (a top nav heading's title span reads --color-text-primary itself),
7125
+ * so a color set on the part never reaches that text. Only the main and
7126
+ * supporting text colors count: the disabled, placeholder and accent ones
7127
+ * mark a state or a role, not the part's text. With `deep`, the parts inside
7128
+ * it count too (a top nav's heading and items).
7129
+ * @param {{MAP: Record<string, any>}} C
7130
+ * @param {string} part
7131
+ * @param {boolean} [deep]
7132
+ * @returns {string[]}
7133
+ */
7134
+ export function innerTextTokens(C, part, deep = false) {
7135
+ const TEXT_ROLES = ['--color-text-primary', '--color-text-secondary'];
7136
+ /** @type {Set<string>} */
7137
+ const out = new Set();
7138
+ /** @param {Record<string, string[]> | undefined} reads */
7139
+ const add = reads => {
7140
+ for (const [tok, props] of Object.entries(reads ?? {}))
7141
+ if (TEXT_ROLES.includes(tok) && props.includes('color')) out.add(tok);
7142
+ };
7143
+ const rec = C.MAP[part];
7144
+ add(rec?.inside);
7145
+ if (deep)
7146
+ for (const inner of rec?.contains ?? []) {
7147
+ const r = C.MAP[inner];
7148
+ add(r?.inside);
7149
+ // A part's own color counts where it reads the token always, not
7150
+ // only in a variant or a state.
7151
+ for (const [tok, conds] of Object.entries(r?.own?.color?.tokens ?? {}))
7152
+ if (
7153
+ TEXT_ROLES.includes(tok) &&
7154
+ /** @type {string[]} */ (conds).some(
7155
+ w => !w.trim() || w.trim() === 'always',
7156
+ )
7157
+ )
7158
+ out.add(tok);
7159
+ }
7160
+ return [...out].sort();
7161
+ }
7162
+
4586
7163
  /**
4587
7164
  * The component docs of a part: its own component's, and the one named like
4588
7165
  * the part (tab is Tab, under TabList), each with its name, for the ones the
@@ -4651,13 +7228,9 @@ export function radiiIn(source) {
4651
7228
  */
4652
7229
  function withBuilt(text, radii) {
4653
7230
  if (!radii) return text;
4654
- try {
4655
- const data = JSON.parse(text.replace(/^\uFEFF/, ''));
4656
- if (!settingsShapeOk(data)) return text;
4657
- return `${JSON.stringify({...data, built: {radii}}, null, 2)}\n`;
4658
- } catch {
4659
- return text;
4660
- }
7231
+ const data = settingsJson(text);
7232
+ if (!settingsShapeOk(data)) return text;
7233
+ return `${JSON.stringify({...data, built: {radii}}, null, 2)}\n`;
4661
7234
  }
4662
7235
 
4663
7236
  /**
@@ -4939,12 +7512,15 @@ export function refuseLinks(cwd, slug) {
4939
7512
  * @param {ThemeData} data
4940
7513
  */
4941
7514
  export function settingsStamp(data) {
7515
+ // The settings as the file keeps them, so the stamp of a build matches
7516
+ // the file it was built from.
7517
+ const saved = savedForm(data);
4942
7518
  const hash = createHash('sha256')
4943
7519
  .update(
4944
7520
  JSON.stringify({
4945
- like: data.like ?? null,
4946
- mode: data.mode,
4947
- settings: data.settings,
7521
+ like: saved.like ?? null,
7522
+ mode: saved.mode,
7523
+ settings: saved.settings,
4948
7524
  }),
4949
7525
  )
4950
7526
  .digest('hex')
@@ -5067,6 +7643,21 @@ export function builtFiles(cwd, slug, data, some = false) {
5067
7643
  ];
5068
7644
  }
5069
7645
 
7646
+ /**
7647
+ * The file's stat, or undefined when it is not there. On Node 22.13 a folder
7648
+ * above the file that is a file throws ENOTDIR even with throwIfNoEntry
7649
+ * false; that file is not there either, as on later Node.
7650
+ * @param {string} file
7651
+ */
7652
+ function statIfThere(file) {
7653
+ try {
7654
+ return fs.statSync(file, {throwIfNoEntry: false});
7655
+ } catch (e) {
7656
+ if (/** @type {any} */ (e)?.code === 'ENOTDIR') return undefined;
7657
+ throw e;
7658
+ }
7659
+ }
7660
+
5070
7661
  /**
5071
7662
  * Refuse, by name, a built file that is there but cannot be read: its
5072
7663
  * permissions, or a folder where the file goes.
@@ -5075,7 +7666,7 @@ export function builtFiles(cwd, slug, data, some = false) {
5075
7666
  */
5076
7667
  function refuseUnreadable(cwd, files) {
5077
7668
  for (const file of files) {
5078
- const st = fs.statSync(file, {throwIfNoEntry: false});
7669
+ const st = statIfThere(file);
5079
7670
  if (!st) continue;
5080
7671
  const rel = shown(cwd, file);
5081
7672
  if (st.isDirectory())
@@ -5166,10 +7757,7 @@ export function readHistory(file) {
5166
7757
  if (!Array.isArray(h)) return {steps: [], dropped: 1};
5167
7758
  const ok = (/** @type {unknown} */ x) => {
5168
7759
  try {
5169
- return (
5170
- typeof x === 'string' &&
5171
- Array.isArray(JSON.parse(x.replace(/^\uFEFF/, '')).settings)
5172
- );
7760
+ return typeof x === 'string' && settingsShapeOk(settingsJson(x));
5173
7761
  } catch {
5174
7762
  return false;
5175
7763
  }
@@ -5204,7 +7792,7 @@ export async function commitTheme(
5204
7792
  const {cwd} = ctx.project;
5205
7793
  const f = themeFiles(cwd, slug);
5206
7794
  refuseLinks(cwd, slug);
5207
- refuseThemeSource(cwd, slug);
7795
+ await refuseThemeSource(cwd, slug);
5208
7796
  const snapBefore = fs.existsSync(f.settings)
5209
7797
  ? fs.readFileSync(f.settings, 'utf8')
5210
7798
  : null;
@@ -5225,8 +7813,8 @@ export async function commitTheme(
5225
7813
  // no undo step.
5226
7814
  const same = (/** @type {ThemeData | null} */ a) =>
5227
7815
  a != null &&
5228
- JSON.stringify({...a, lifted: undefined}) ===
5229
- JSON.stringify({...data, lifted: undefined});
7816
+ JSON.stringify({...savedForm(a), lifted: undefined}) ===
7817
+ JSON.stringify({...savedForm(data), lifted: undefined});
5230
7818
  // A no-op change still mends a build that does not match the settings
5231
7819
  // (an undo stopped part way): it is built again, with no new step.
5232
7820
  const noop = history && same(parseSettings(snapBefore));
@@ -5361,7 +7949,7 @@ export async function commitTheme(
5361
7949
  // for an undo, a top step equal to the settings, which undo skips),
5362
7950
  // never a step that undoes nothing or a lost step.
5363
7951
  await track(f.dir, wrote, () => {
5364
- writeWhole(f.settings, `${JSON.stringify(data, null, 2)}\n`);
7952
+ writeWhole(f.settings, `${JSON.stringify(savedForm(data), null, 2)}\n`);
5365
7953
  if (historyAfter)
5366
7954
  writeWhole(
5367
7955
  f.history,
@@ -5371,7 +7959,9 @@ export async function commitTheme(
5371
7959
  writeWhole(
5372
7960
  f.history,
5373
7961
  JSON.stringify(
5374
- [...past, withBuilt(snapBefore, radiiNow)].slice(-HISTORY_STEPS),
7962
+ [...past, stepText(snapBefore, cwd, radiiNow)].slice(
7963
+ -HISTORY_STEPS,
7964
+ ),
5375
7965
  ),
5376
7966
  );
5377
7967
  });
@@ -5536,9 +8126,54 @@ export async function commitTheme(
5536
8126
  };
5537
8127
  }
5538
8128
 
5539
- /** @param {Ctx} ctx @param {ThemeData} data */
8129
+ /**
8130
+ * The @fontsource package named for a font family (`Open Sans` is
8131
+ * `@fontsource/open-sans`).
8132
+ * @param {string} family
8133
+ * @returns {string}
8134
+ */
8135
+ export function fontsourcePackageOf(family) {
8136
+ return `@fontsource/${String(family)
8137
+ .replace(/["']/g, '')
8138
+ .trim()
8139
+ .toLowerCase()
8140
+ .replace(/\s+/g, '-')}`;
8141
+ }
8142
+
8143
+ /**
8144
+ * The font families the theme's last build names (its
8145
+ * `--font-family-*` declarations), by lowercase name; null before the
8146
+ * theme has been built.
8147
+ * @param {Ctx} ctx
8148
+ * @param {string} slug
8149
+ * @returns {Map<string, string> | null}
8150
+ */
8151
+ export function builtFontFamilies(ctx, slug) {
8152
+ /** @type {string} */
8153
+ let css;
8154
+ try {
8155
+ css = fs.readFileSync(themeFiles(ctx.project.cwd, slug).css, 'utf8');
8156
+ } catch {
8157
+ return null;
8158
+ }
8159
+ /** @type {Map<string, string>} */
8160
+ const out = new Map();
8161
+ for (const value of declarationValues(css, /^--font-family-/))
8162
+ for (const family of namedFontFamilies(value))
8163
+ if (!out.has(family.toLowerCase())) out.set(family.toLowerCase(), family);
8164
+ return out;
8165
+ }
8166
+
8167
+ /**
8168
+ * The font packages that load the families the theme builds: a font
8169
+ * setting's package while the build still uses its family, and the
8170
+ * installed @fontsource package of a family the theme's own source sets.
8171
+ * Font notes, the previews and the app copy all load fonts from this list.
8172
+ * @param {Ctx} ctx
8173
+ * @param {ThemeData} data
8174
+ */
5540
8175
  export function fontPackages(ctx, data) {
5541
- /** @type {Array<{pkg: string, family: string, installed: boolean, of: Setting}>} */
8176
+ /** @type {Array<{pkg: string, family: string, installed: boolean, of: Setting | null}>} */
5542
8177
  const out = [];
5543
8178
  /** @param {string} pkg */
5544
8179
  const isInstalled = pkg => {
@@ -5549,17 +8184,26 @@ export function fontPackages(ctx, data) {
5549
8184
  return false;
5550
8185
  }
5551
8186
  };
8187
+ const built = builtFontFamilies(ctx, data.name);
5552
8188
  for (const s of data.settings) {
5553
8189
  if (s.thing !== 'font') continue;
5554
8190
  const {pkg: known, family} = fontOf(s.value);
5555
8191
  const name = family.replace(/["']/g, '');
8192
+ // A family the theme's own source replaced everywhere it was set is
8193
+ // not in the build: nothing loads it.
8194
+ if (built && !built.has(name.toLowerCase())) continue;
5556
8195
  // An installed @fontsource package of the family always loads it, even
5557
8196
  // for a family some systems ship.
5558
- const own = `@fontsource/${name.toLowerCase().replace(/\s+/g, '-')}`;
8197
+ const own = fontsourcePackageOf(name);
5559
8198
  const pkg = known ?? (isInstalled(own) ? own : null);
5560
8199
  if (!pkg || out.some(x => x.pkg === pkg)) continue;
5561
8200
  out.push({pkg, family: name, installed: isInstalled(pkg), of: s});
5562
8201
  }
8202
+ for (const family of built?.values() ?? []) {
8203
+ const pkg = fontsourcePackageOf(family);
8204
+ if (out.some(x => x.pkg === pkg) || !isInstalled(pkg)) continue;
8205
+ out.push({pkg, family, installed: true, of: null});
8206
+ }
5563
8207
  return out;
5564
8208
  }
5565
8209