@astryxdesign/cli 0.7.16 → 0.7.17-canary.g16fe6a8

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 (380) 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 +28 -2
  29. package/api/docs/_adapter.mjs +249 -10
  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 +132 -1
  79. package/api/theme/build/build.mjs +482 -157
  80. package/api/theme/build/core-interception.d.mts +10 -0
  81. package/api/theme/build/core-interception.mjs +10 -0
  82. package/api/theme/build/font-warning.d.mts +44 -5
  83. package/api/theme/build/font-warning.mjs +118 -10
  84. package/api/theme/build/icon-imports.mjs +51 -9
  85. package/api/theme/theme.type.d.mts +10 -0
  86. package/api/theme/theme.type.mjs +7 -1
  87. package/api/theme-edit/_adapter.d.mts +115 -4
  88. package/api/theme-edit/_adapter.mjs +997 -83
  89. package/api/theme-edit/_catalog.d.mts +20 -2
  90. package/api/theme-edit/_catalog.mjs +50 -10
  91. package/api/theme-edit/_check.d.mts +75 -24
  92. package/api/theme-edit/_check.mjs +2672 -422
  93. package/api/theme-edit/_color.d.mts +10 -0
  94. package/api/theme-edit/_color.mjs +54 -1
  95. package/api/theme-edit/_compiler.d.mts +1 -0
  96. package/api/theme-edit/_compiler.mjs +133 -15
  97. package/api/theme-edit/_context.d.mts +14 -3
  98. package/api/theme-edit/_context.mjs +225 -65
  99. package/api/theme-edit/_css.d.mts +14 -0
  100. package/api/theme-edit/_css.mjs +46 -1
  101. package/api/theme-edit/_edit.d.mts +54 -4
  102. package/api/theme-edit/_edit.mjs +2966 -286
  103. package/api/theme-edit/_how-commands.d.mts +72 -1
  104. package/api/theme-edit/_how-commands.mjs +770 -9
  105. package/api/theme-edit/_how-question.d.mts +82 -5
  106. package/api/theme-edit/_how-question.mjs +6983 -701
  107. package/api/theme-edit/_how.d.mts +2 -1
  108. package/api/theme-edit/_how.mjs +237 -41
  109. package/api/theme-edit/_importers.d.mts +38 -0
  110. package/api/theme-edit/_importers.mjs +188 -0
  111. package/api/theme-edit/_marks.d.mts +31 -5
  112. package/api/theme-edit/_marks.mjs +57 -5
  113. package/api/theme-edit/_name-rule.d.mts +11 -0
  114. package/api/theme-edit/_name-rule.mjs +12 -0
  115. package/api/theme-edit/_normal.d.mts +303 -0
  116. package/api/theme-edit/_normal.mjs +1517 -0
  117. package/api/theme-edit/_palette.d.mts +12 -0
  118. package/api/theme-edit/_palette.mjs +37 -4
  119. package/api/theme-edit/_part-words.d.mts +31 -0
  120. package/api/theme-edit/_part-words.mjs +126 -0
  121. package/api/theme-edit/_parts.d.mts +28 -2
  122. package/api/theme-edit/_parts.mjs +267 -31
  123. package/api/theme-edit/_preview-app.d.mts +7 -13
  124. package/api/theme-edit/_preview-app.mjs +814 -406
  125. package/api/theme-edit/_preview.d.mts +116 -16
  126. package/api/theme-edit/_preview.mjs +649 -152
  127. package/api/theme-edit/_project.d.mts +22 -1
  128. package/api/theme-edit/_project.mjs +83 -3
  129. package/api/theme-edit/_settings.d.mts +467 -42
  130. package/api/theme-edit/_settings.mjs +3527 -468
  131. package/api/theme-edit/_tables.d.mts +21 -0
  132. package/api/theme-edit/_tables.mjs +97 -3
  133. package/api/theme-edit/_vet.d.mts +31 -0
  134. package/api/theme-edit/_vet.mjs +114 -8
  135. package/api/theme-edit/theme-edit.type.d.mts +16 -2
  136. package/api/theme-edit/theme-edit.type.mjs +6 -3
  137. package/api/theme-edit/themeEditHow.doc.mjs +1 -1
  138. package/api/theme-edit/themeEditNew.doc.d.mts +0 -1
  139. package/api/theme-edit/themeEditNew.doc.mjs +7 -4
  140. package/api/theme-edit/themeEditPreviewApp.doc.mjs +3 -3
  141. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +2 -2
  142. package/api/upgrade/run/run.mjs +4 -3
  143. package/assets/codemods/integration-discovery.mjs +2 -1
  144. package/assets/codemods/run-codemod.mjs +87 -7
  145. package/assets/codemods/transforms/next/index.mjs +11 -1
  146. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  147. package/assets/component-list.generated.json +1 -0
  148. package/assets/docs/author-a-theme.doc.mjs +1 -0
  149. package/assets/docs/theme.doc.dense.mjs +2 -2
  150. package/assets/docs/theme.doc.mjs +1 -1
  151. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  152. package/assets/docs/tree/checks.doc.mjs +1 -1
  153. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  154. package/assets/docs/tree/render-pages.doc.mjs +44 -3
  155. package/assets/docs/tree/share-a-page.doc.mjs +157 -0
  156. package/assets/docs/tree/single-component.doc.mjs +4 -0
  157. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  158. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  159. package/assets/docs/use-a-theme.doc.mjs +1 -1
  160. package/assets/docs.generated.json +2 -2
  161. package/assets/search-catalog.generated.json +2 -0
  162. package/assets/self-audit.generated.json +1 -1
  163. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  164. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  165. package/assets/templates/blocks/components/Hooks/useContainerRevealHookUsage.tsx +2 -2
  166. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  167. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  168. package/assets/templates/components.generated.json +1 -1
  169. package/assets/templates/pages/ai-chat/template.doc.mjs +5 -4
  170. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +5 -1
  171. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  172. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  173. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  174. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  175. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  176. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  177. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  178. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  179. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  180. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  181. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  182. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  183. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  184. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  185. package/assets/templates/pages/editor/template.doc.mjs +2 -8
  186. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  187. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  188. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  189. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  190. package/assets/templates/pages/ide/page.tsx +24 -2
  191. package/assets/templates/pages/kanban-board/template.doc.mjs +1 -9
  192. package/assets/templates/pages/library/template.doc.mjs +4 -1
  193. package/assets/templates/pages/login/template.doc.mjs +2 -1
  194. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  195. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  196. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  197. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  198. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  199. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  200. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  201. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  202. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  203. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  204. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  205. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  206. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  207. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  208. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  209. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  210. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -9
  211. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  212. package/assets/theme.template.ts +6 -0
  213. package/authoring/debug/parse.d.mts +3 -3
  214. package/authoring/doctypes/_schema.d.mts +3 -3
  215. package/authoring/doctypes/command/command.doc.mjs +1 -1
  216. package/authoring/doctypes/component/categories.d.mts +37 -0
  217. package/authoring/doctypes/component/categories.mjs +54 -0
  218. package/authoring/doctypes/template/template.doc.mjs +1 -1
  219. package/authoring/doctypes/template/type.ts +9 -0
  220. package/authoring/example/example.doc.d.mts +12 -0
  221. package/authoring/example/example.doc.mjs +69 -0
  222. package/authoring/example/preview.d.mts +92 -0
  223. package/authoring/example/preview.mjs +994 -0
  224. package/authoring/example/type.ts +102 -0
  225. package/authoring/index.d.mts +1 -0
  226. package/authoring/index.d.ts +12 -0
  227. package/authoring/index.mjs +3 -1
  228. package/clients/cli/bin/astryx.mjs +6 -9
  229. package/clients/cli/build-id.generated.json +1 -1
  230. package/clients/cli/commands/component.doc.mjs +1 -1
  231. package/clients/cli/commands/component.mjs +22 -3
  232. package/clients/cli/commands/docs.doc.mjs +7 -1
  233. package/clients/cli/commands/docs.mjs +3 -1
  234. package/clients/cli/commands/doctor.mjs +32 -14
  235. package/clients/cli/commands/experimental/render.mjs +42 -1
  236. package/clients/cli/commands/experimental/theme.mjs +573 -119
  237. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  238. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  239. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +87 -1
  240. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +10 -3
  241. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -1
  242. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +2 -2
  243. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  244. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  245. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  246. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  247. package/clients/cli/commands/experimental-theme-preview.doc.mjs +2 -1
  248. package/clients/cli/commands/experimental-theme.doc.mjs +5 -1
  249. package/clients/cli/commands/search.doc.mjs +2 -1
  250. package/clients/cli/commands/search.mjs +6 -1
  251. package/clients/cli/commands/template.mjs +4 -2
  252. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  253. package/clients/cli/commands/theme.doc.mjs +1 -1
  254. package/clients/cli/commands/theme.mjs +718 -438
  255. package/clients/cli/commands/upgrade.mjs +42 -7
  256. package/clients/cli/index.mjs +1 -1
  257. package/clients/cli/lib/cli-error.mjs +2 -1
  258. package/clients/cli/lib/component-format.mjs +205 -98
  259. package/clients/cli/lib/hook-format.mjs +9 -19
  260. package/clients/cli/lib/json-shim.mjs +132 -24
  261. package/clients/cli/lib/manifest.mjs +3 -2
  262. package/clients/cli/manifest.generated.json +1 -1
  263. package/foundation/agent-docs/agent-docs.mjs +1 -1
  264. package/foundation/config/theme-state.d.mts +13 -1
  265. package/foundation/config/theme-state.mjs +47 -7
  266. package/foundation/discovery/authoring-self-docs.mjs +1 -0
  267. package/foundation/discovery/component-discovery.d.mts +11 -0
  268. package/foundation/discovery/component-discovery.mjs +56 -8
  269. package/foundation/discovery/component-replacement.mjs +130 -1
  270. package/foundation/discovery/copied-passages.mjs +2 -1
  271. package/foundation/discovery/core-component-docs.d.mts +29 -0
  272. package/foundation/discovery/core-component-docs.mjs +83 -0
  273. package/foundation/discovery/doc-types.mjs +4 -3
  274. package/foundation/discovery/entry-name-files.d.mts +43 -0
  275. package/foundation/discovery/entry-name-files.mjs +264 -0
  276. package/foundation/discovery/hook-discovery.d.mts +8 -2
  277. package/foundation/discovery/hook-discovery.mjs +22 -8
  278. package/foundation/discovery/icon-definition-discovery.mjs +2 -1
  279. package/foundation/discovery/icon-set-checks.mjs +2 -1
  280. package/foundation/discovery/icon-set-discovery.mjs +2 -1
  281. package/foundation/discovery/integration-doc-files.mjs +2 -1
  282. package/foundation/discovery/package-exports.d.mts +10 -0
  283. package/foundation/discovery/package-exports.mjs +56 -3
  284. package/foundation/discovery/prop-drift.mjs +9 -9
  285. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  286. package/foundation/discovery/runner-allowlist.mjs +2 -0
  287. package/foundation/discovery/stored-component-list.d.mts +43 -0
  288. package/foundation/discovery/stored-component-list.mjs +90 -0
  289. package/foundation/discovery/stored-search-catalog.d.mts +115 -0
  290. package/foundation/discovery/stored-search-catalog.mjs +297 -0
  291. package/foundation/discovery/stored-self-audit.d.mts +26 -10
  292. package/foundation/discovery/stored-self-audit.mjs +38 -18
  293. package/foundation/discovery/template-adapter.d.mts +53 -1
  294. package/foundation/discovery/template-adapter.mjs +176 -12
  295. package/foundation/discovery/template-icons.mjs +2 -1
  296. package/foundation/discovery/theme-discovery.mjs +31 -4
  297. package/foundation/discovery/theme-imports.d.mts +14 -0
  298. package/foundation/discovery/theme-imports.mjs +43 -1
  299. package/foundation/discovery/theming-targets.d.mts +6 -5
  300. package/foundation/discovery/theming-targets.mjs +31 -47
  301. package/foundation/doc-compiler/import.mjs +7 -1
  302. package/foundation/doc-compiler/inputs.mjs +3 -2
  303. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  304. package/foundation/doc-compiler/stored-docs.d.mts +22 -0
  305. package/foundation/doc-compiler/stored-docs.mjs +49 -0
  306. package/foundation/env/semver.mjs +3 -1
  307. package/foundation/fonts/font-stylesheet.d.mts +38 -0
  308. package/foundation/fonts/font-stylesheet.mjs +141 -0
  309. package/foundation/fs/cache-eviction.d.mts +21 -0
  310. package/foundation/fs/cache-eviction.mjs +73 -0
  311. package/foundation/fs/exact-codec.d.mts +12 -2
  312. package/foundation/fs/exact-codec.mjs +23 -6
  313. package/foundation/fs/file-protection.mjs +4 -3
  314. package/foundation/fs/gather-cache.d.mts +62 -4
  315. package/foundation/fs/gather-cache.mjs +517 -91
  316. package/foundation/fs/jiti-cache.d.mts +19 -1
  317. package/foundation/fs/jiti-cache.mjs +130 -6
  318. package/foundation/fs/kept-tree.d.mts +60 -0
  319. package/foundation/fs/kept-tree.mjs +154 -0
  320. package/foundation/fs/listing-cache.d.mts +7 -0
  321. package/foundation/fs/listing-cache.mjs +10 -0
  322. package/foundation/fs/module-loader.d.mts +24 -2
  323. package/foundation/fs/module-loader.mjs +94 -21
  324. package/foundation/fs/paths.d.mts +18 -0
  325. package/foundation/fs/paths.mjs +15 -2
  326. package/foundation/fs/read-record.d.mts +9 -0
  327. package/foundation/fs/read-record.mjs +19 -11
  328. package/foundation/fs/stop-cleanup.d.mts +12 -0
  329. package/foundation/fs/stop-cleanup.mjs +66 -0
  330. package/foundation/identity/provider-identity.d.mts +6 -0
  331. package/foundation/identity/provider-identity.mjs +10 -1
  332. package/foundation/integrations/contribution-inventory.mjs +4 -3
  333. package/foundation/integrations/example-code.d.mts +63 -0
  334. package/foundation/integrations/example-code.mjs +416 -0
  335. package/foundation/integrations/public-imports.d.mts +9 -0
  336. package/foundation/integrations/public-imports.mjs +3 -2
  337. package/foundation/integrations/validate-contributions.mjs +17 -45
  338. package/foundation/render/embedded-files.d.mts +6 -0
  339. package/foundation/render/embedded-files.mjs +25 -5
  340. package/foundation/render/embedded-imports.d.mts +39 -7
  341. package/foundation/render/embedded-imports.mjs +66 -27
  342. package/foundation/render/file-header.d.mts +66 -0
  343. package/foundation/render/file-header.mjs +118 -0
  344. package/foundation/render/host-answer.d.mts +18 -0
  345. package/foundation/render/host-answer.mjs +46 -0
  346. package/foundation/render/host-exit.d.mts +1 -0
  347. package/foundation/render/host-exit.mjs +6 -1
  348. package/foundation/render/html-reader.d.mts +55 -2
  349. package/foundation/render/html-reader.mjs +145 -26
  350. package/foundation/render/markup-edits.d.mts +57 -0
  351. package/foundation/render/markup-edits.mjs +182 -0
  352. package/foundation/render/page-host.mjs +29 -12
  353. package/foundation/render/page-worker.mjs +121 -13
  354. package/foundation/render/picture-chrome.d.mts +4 -0
  355. package/foundation/render/picture-chrome.mjs +185 -0
  356. package/foundation/render/picture-playwright.d.mts +4 -0
  357. package/foundation/render/picture-playwright.mjs +34 -0
  358. package/foundation/render/rebuild.mjs +2 -1
  359. package/foundation/render/render-page.d.mts +35 -3
  360. package/foundation/render/render-page.mjs +641 -96
  361. package/foundation/render/source-block.d.mts +85 -6
  362. package/foundation/render/source-block.mjs +211 -20
  363. package/foundation/render/ts-paths.d.mts +69 -6
  364. package/foundation/render/ts-paths.mjs +326 -40
  365. package/foundation/response/error-codes.d.mts +3 -1
  366. package/foundation/response/error-codes.d.ts +1 -0
  367. package/foundation/response/error-codes.doc.mjs +12 -1
  368. package/foundation/response/error-codes.mjs +11 -1
  369. package/foundation/response/response-types.doc.mjs +2 -2
  370. package/foundation/text/compare-text.d.mts +14 -0
  371. package/foundation/text/compare-text.mjs +68 -0
  372. package/foundation/text/css-escape.d.mts +18 -0
  373. package/foundation/text/css-escape.mjs +35 -0
  374. package/foundation/text/string-utils.d.mts +3 -2
  375. package/foundation/text/string-utils.mjs +18 -4
  376. package/foundation/text/suggest-order.d.mts +9 -0
  377. package/foundation/text/suggest-order.mjs +15 -1
  378. package/foundation/xle/expand.mjs +2 -1
  379. package/host/index.mjs +8 -6
  380. 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';
@@ -24,8 +24,23 @@ import {cliVersion} from '../../foundation/release/run-context.mjs';
24
24
  import {AstryxError} from '../error.mjs';
25
25
  import {logger} from '../logger.mjs';
26
26
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
27
+ import {cssUnescape} from '../../foundation/text/css-escape.mjs';
27
28
  import {levenshteinDistance} from '../../foundation/text/levenshtein.mjs';
28
- import {themeBuildForReport} from '../theme/build/build.mjs';
29
+ import {
30
+ loadThemeExport,
31
+ loadThemeInput,
32
+ oneColorMode,
33
+ themeBuildForReport,
34
+ } from '../theme/build/build.mjs';
35
+ import {
36
+ expandFontVars,
37
+ fontShorthandFamilyList,
38
+ namedFontFamilies,
39
+ } from '../theme/build/font-warning.mjs';
40
+ import {
41
+ customPropertyValues,
42
+ declarationValues,
43
+ } from '../../foundation/fonts/font-stylesheet.mjs';
29
44
  import {
30
45
  AUTO_SPREAD,
31
46
  CORNERS,
@@ -46,6 +61,15 @@ import {
46
61
  WRAPPED_PARTS,
47
62
  CARD_LIKE,
48
63
  } from './_tables.mjs';
64
+ import {TOP_BAR_COMPONENTS} from './_catalog.mjs';
65
+ import {
66
+ baseWord,
67
+ booleanWord,
68
+ cleanDialValue,
69
+ modeWord,
70
+ typoLimit,
71
+ typoNear,
72
+ } from './_normal.mjs';
49
73
  import {
50
74
  alphaOf,
51
75
  colorProblem,
@@ -81,8 +105,11 @@ import {
81
105
  baseModule,
82
106
  baseResolved,
83
107
  baseThemeFile,
108
+ installLine,
109
+ packageInstalled,
84
110
  } from './_project.mjs';
85
111
  import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
112
+ import {compareText} from '../../foundation/text/compare-text.mjs';
86
113
 
87
114
  // The palette reads the tokens the own source sets through this module.
88
115
  setOwnTokenReader((cwd, slug) => ownSourceTokenValues(cwd, slug));
@@ -116,13 +143,13 @@ setOwnTokenReader((cwd, slug) => ownSourceTokenValues(cwd, slug));
116
143
  /** What lifted secondary text sits on: the contrast check measures it there. */
117
144
  const LIFT_GROUND_TOKENS = new Set(LIFT_PARTS.map(([, , g]) => g));
118
145
 
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 */
146
+ /** @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
147
  /** @typedef {import('./_parts.mjs').PaintSide} PaintSide */
121
148
  /** @typedef {import('./_parts.mjs').TextPair} TextPair */
122
149
 
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)';
150
+ import {NAME_RULE} from './_name-rule.mjs';
151
+
152
+ export {NAME_RULE};
126
153
 
127
154
  /** A theme name: lowercase letters, digits and dashes, starting with a letter, 64 characters at most. @param {string} s */
128
155
  export const slugOk = s =>
@@ -197,20 +224,35 @@ export function themeFiles(cwd, slug) {
197
224
  }
198
225
 
199
226
  /** 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']);
227
+ export const FOLDER_JUNK = new Set([
228
+ '.DS_Store',
229
+ '.gitkeep',
230
+ 'Thumbs.db',
231
+ 'desktop.ini',
232
+ ]);
201
233
 
202
234
  /**
203
235
  * Whether `dir` holds nothing of anyone's: absent, empty, or only system
204
236
  * files (what `git rm -r` or a branch switch leaves). A path that is not a
205
237
  * folder, or one that does not read, is not empty.
206
238
  * @param {string} dir
239
+ * @returns {boolean}
207
240
  */
208
241
  export function folderIsEmpty(dir) {
209
242
  if (!fs.existsSync(dir)) return true;
210
243
  try {
244
+ // A folder holding only empty folders (an empty tokens/) holds nothing
245
+ // either; a link is never followed.
211
246
  return (
212
247
  fs.lstatSync(dir).isDirectory() &&
213
- fs.readdirSync(dir).every(n => FOLDER_JUNK.has(n))
248
+ fs
249
+ .readdirSync(dir)
250
+ .every(
251
+ n =>
252
+ FOLDER_JUNK.has(n) ||
253
+ (fs.lstatSync(path.join(dir, n)).isDirectory() &&
254
+ folderIsEmpty(path.join(dir, n))),
255
+ )
214
256
  );
215
257
  } catch {
216
258
  return false;
@@ -290,34 +332,17 @@ export function editorWrote(cwd, slug, file) {
290
332
  }
291
333
 
292
334
  /**
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.
335
+ * Whether the pictures record names this file and it is unchanged since the
336
+ * editor wrote it. Only such a file is ever deleted: a stamp alone is not
337
+ * enough, since a byte copy of a picture (preview-before.png) carries the
338
+ * same stamp and is the person's.
297
339
  * @param {string} cwd
298
340
  * @param {string} slug
299
341
  * @param {string} file
300
342
  */
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;
343
+ export function editorRecorded(cwd, slug, file) {
344
+ const was = readWrittenRecord(cwd, slug)[path.basename(file)];
345
+ return Boolean(was) && was === contentHash(file);
321
346
  }
322
347
 
323
348
  /**
@@ -470,7 +495,7 @@ export function editedThemes(cwd, order = 'name') {
470
495
  };
471
496
  return names
472
497
  .map(d => ({d, t: when(d)}))
473
- .sort((a, b) => b.t - a.t || a.d.localeCompare(b.d))
498
+ .sort((a, b) => b.t - a.t || compareText(a.d, b.d))
474
499
  .map(x => x.d);
475
500
  }
476
501
 
@@ -485,21 +510,51 @@ export const shown = (cwd, f) =>
485
510
  * @param {number} [n]
486
511
  */
487
512
  export function nearest(x, list, n = 3) {
513
+ // A phrase that negates a word (not round, no caps, unbold,
514
+ // rounded-none) never has that word as its nearest: it asks the opposite.
515
+ // A typo of a listed keyword that itself starts with no- or not-
516
+ // (`not-alowed` for not-allowed, `no-repat` for no-repeat) is no
517
+ // negation: it is read as a typo.
518
+ if (
519
+ negates(x) &&
520
+ ![...list].some(c => /^(no|not)-/.test(c) && typoNear(x, c))
521
+ )
522
+ return [];
523
+ // A long input (a pasted stylesheet or blob) holds many names inside
524
+ // it: it is near nothing.
525
+ if (x.length > 64) return [];
526
+ // Only within the editor's one typo limit (typoLimit: none under four
527
+ // letters, so only the name itself in other letters is near those),
528
+ // nearest by edit distance first (brand-drak is brand-dark, not brand). A
529
+ // name that only holds the typed word inside it is no typo of it.
530
+ const limit = typoLimit(x);
531
+ const typed = x.toLowerCase();
488
532
  return [...list]
489
533
  .filter(c => c.length > 2)
490
534
  .map(
491
535
  c =>
492
536
  /** @type {[string, number]} */ ([
493
537
  c,
494
- c.includes(x) || x.includes(c) ? 1 : levenshteinDistance(x, c),
538
+ levenshteinDistance(typed, c.toLowerCase(), limit, {swaps: true}),
495
539
  ]),
496
540
  )
497
- .filter(([, s]) => s <= Math.max(2, Math.floor(x.length / 3)))
541
+ .filter(([, d]) => d <= limit)
498
542
  .sort((a, b) => a[1] - b[1])
499
543
  .slice(0, n)
500
544
  .map(([c]) => c);
501
545
  }
502
546
 
547
+ /**
548
+ * Whether typed words negate what they name (`not round`, `no caps`,
549
+ * `anything but blue`, `unbold`, `non-bold`, `rounded-none`).
550
+ * @param {string} x
551
+ */
552
+ export function negates(x) {
553
+ return /(^|[\s-])(not|no|non|without|never|less)([\s-]|$)|anything but|^un(round|bold|rais|outlin|cap)|-none$/i.test(
554
+ String(x).trim(),
555
+ );
556
+ }
557
+
503
558
  /**
504
559
  * A refusal: nothing was changed, and the suggestions lead with the command
505
560
  * that does what the person wanted.
@@ -577,6 +632,91 @@ export function typedThemeName(s) {
577
632
  );
578
633
  }
579
634
 
635
+ /**
636
+ * The theme names a name typed the way the app shows it may mean, most
637
+ * likely first: a path with doubled slashes or `../` (`themes//t`), a file
638
+ * name with or without its folder (`brand.theme.ts`, `tTheme.ts`), the app
639
+ * copy's export (`tTheme`), camelCase (`brandDark`) and spaces
640
+ * (`Brand Dark`) each read as dashes. The caller picks the first that
641
+ * exists, else the first.
642
+ * @param {string} s
643
+ * @returns {string[]}
644
+ */
645
+ export function themeNameReadings(s) {
646
+ const base = unlabeledThemeName(String(s ?? ''))
647
+ .replace(/[\\/]+/g, '/')
648
+ .replace(/^(\.\.?\/)+/, '')
649
+ .replace(/^.*themes\//i, '')
650
+ .replace(/\/.*$/, '')
651
+ .replace(
652
+ /\.(theme\.ts|settings\.(json|ts)|history\.json|css\.d\.ts|d\.ts|doc\.mjs|fonts\.css|css|mjs|js|tsx?)$/i,
653
+ '',
654
+ )
655
+ .trim();
656
+ const noTheme = base.replace(/([a-z0-9])Theme$/, '$1');
657
+ const read = [base, noTheme === base ? '' : noTheme]
658
+ .flatMap(x => [kebab(x), x.toLowerCase()])
659
+ .filter(x => /[a-z]/i.test(x))
660
+ .map(x => slugFor(x));
661
+ // A module name in any letters (brandtheme, brand-theme) last: only
662
+ // when the theme it names exists does it win.
663
+ const moduleNames = read
664
+ .map(n => n.replace(/-?theme$/, ''))
665
+ .filter(n => n && slugOk(n));
666
+ return [...new Set([...read, ...moduleNames])];
667
+ }
668
+
669
+ /**
670
+ * A vibrancy written as set reads typed input: a share of one (0.5) or a
671
+ * percent (50%) is that much of the 0-100 scale, as a whole number. Any
672
+ * other dial's value, or a vibrancy that is no such number, comes back as
673
+ * it was.
674
+ * @param {string} dial
675
+ * @param {string} v
676
+ * @returns {string}
677
+ */
678
+ export function vibrancyMeant(dial, v) {
679
+ if (dial !== 'vibrancy') return v;
680
+ const m = /^(\d*\.?\d+)\s*(%?)$/.exec(v.trim());
681
+ if (!m) return v;
682
+ const n = Number(m[1]);
683
+ const scaled = !m[2] && n > 0 && n < 1 ? n * 100 : n;
684
+ return scaled <= 100 ? String(Math.round(scaled)) : v;
685
+ }
686
+
687
+ /**
688
+ * The mode and base a damaged theme file meant, read the way typed input
689
+ * is: other letters, stray spaces, `_` or a space for a dash (`Dark-Only`,
690
+ * ` Neutral`), and a base written as its package name
691
+ * (`@astryxdesign/theme-neutral`). Each is the cleaned text even when it is
692
+ * no value the editor takes; the caller checks it.
693
+ * @param {any} data
694
+ * @returns {{mode: string, like: string}}
695
+ */
696
+ export function fieldsMeant(data) {
697
+ const MODES = ['both', 'light-only', 'dark-only'];
698
+ const typed = String(data?.mode ?? '')
699
+ .trim()
700
+ .toLowerCase()
701
+ .replace(/[\s_]+/g, '-');
702
+ // A word for one mode (light, night, darkmode) is that one mode, by the
703
+ // one mode reader; a typo of a mode is that mode.
704
+ const one = modeWord(typed);
705
+ const word = one ? `${one}-only` : undefined;
706
+ const near = (/** @type {string} */ t, /** @type {string[]} */ list) => {
707
+ const hits = list.filter(x => typoNear(t, x));
708
+ return hits.length === 1 ? hits[0] : null;
709
+ };
710
+ const mode = MODES.includes(typed)
711
+ ? typed
712
+ : (word ?? (typed ? near(typed, MODES) : null) ?? typed);
713
+ const likeTyped = baseWord(data?.like);
714
+ const like = LIKE.includes(likeTyped)
715
+ ? likeTyped
716
+ : ((likeTyped ? near(likeTyped, LIKE) : null) ?? likeTyped);
717
+ return {mode, like};
718
+ }
719
+
580
720
  /**
581
721
  * The settings of a theme, or a refusal naming the command that makes it.
582
722
  * @param {string} cwd
@@ -605,9 +745,22 @@ export function loadTheme(
605
745
  );
606
746
  const plain = typedThemeName(slug);
607
747
  const named = slugFor(plain);
748
+ // brandDark is brand-dark.
749
+ const camelWords = slugFor(
750
+ unlabeledThemeName(String(slug ?? '')).replace(
751
+ /([a-z0-9])([A-Z])/g,
752
+ '$1-$2',
753
+ ),
754
+ );
608
755
  const exists = (/** @type {string} */ n) =>
609
756
  Boolean(n) && fs.existsSync(themeFiles(cwd, n).settings);
610
- const fixed = !exists(named) && exists(whole) ? whole : named;
757
+ // The module or export name (brandTheme, the app copy's brandTheme.ts)
758
+ // names the theme brand: one reader for every way a name is typed.
759
+ const readings = themeNameReadings(slug);
760
+ const fixed =
761
+ [named, whole, camelWords, ...readings].find(exists) ??
762
+ readings[0] ??
763
+ named;
611
764
  const same = fs.existsSync(themeFiles(cwd, fixed).settings) ? fixed : null;
612
765
  // A list where one theme goes (t,u or "t;u"): one theme at a time,
613
766
  // each that exists named; never a new theme made of the list. A name
@@ -685,14 +838,18 @@ export function loadTheme(
685
838
  // none): the settings were lost after.
686
839
  const stopped =
687
840
  fs.existsSync(path.join(f.dir, NEW_MARKER)) && !fs.existsSync(f.history);
688
- if (!same && (stopped || madeByEditor(f.settingsTs)))
841
+ if (!same && editorMadeFolder(cwd, slug)) {
842
+ const remake = remakeLines(cwd, slug);
689
843
  refuse(
690
844
  ERROR_CODES.ERR_UNKNOWN_THEME,
691
- stopped
692
- ? `themes/${slug} was left by a \`new\` that was stopped part way, so it has no settings yet. Run new again to finish it; files you added there are kept.`
693
- : `themes/${slug} has lost its settings (${slug}.settings.json is gone), but the editor made it. Run new to make it again: your own files there are kept${fs.existsSync(f.history) ? `, and \`undo ${slug}\` then steps back to the settings from before the last change (the last change itself is not kept)` : ''}.`,
694
- {run: [`${P} new ${slug}`]},
845
+ `${
846
+ stopped
847
+ ? `themes/${slug} was left by a \`new\` that was stopped part way, so it has no settings yet. Run new again to finish it; files you added there are kept`
848
+ : `themes/${slug} has lost its settings (${slug}.settings.json is gone), but the editor made it. Run new to make it again: your own files there are kept${fs.existsSync(f.history) ? `, and \`undo ${slug}\` then steps back to the settings from before the last change (the last change itself is not kept)` : ''}`
849
+ }; ${remake.base ? `it is made again on ${remake.base}, the base it was built on` : 'it starts on no base (the base it was built on cannot be read)'}.`,
850
+ {run: remake.lines},
695
851
  );
852
+ }
696
853
  // A folder copied or renamed by hand from an editor theme: its files
697
854
  // still carry the old name (t.settings.json in themes/t2).
698
855
  const copied =
@@ -741,6 +898,30 @@ export function loadTheme(
741
898
  `themes/${slug} is an empty folder: there is no theme ${slug} yet. new makes it there.`,
742
899
  {run: [`${P} new ${slug}`]},
743
900
  );
901
+ // The editor's own app copy left behind when themes/<slug>/ is gone
902
+ // (a git clean, a wrong rm, a branch switch): `new` makes the theme
903
+ // again and writes the copy over.
904
+ const copyName = `${camel(slug)}Theme`;
905
+ if (
906
+ !same &&
907
+ other &&
908
+ other[1] === `src/themes/${slug}` &&
909
+ !fs.existsSync(f.dir) &&
910
+ [`${copyName}.ts`, `${copyName}.doc.mjs`, `${slug}.fonts.css`].some(n => {
911
+ try {
912
+ return fs
913
+ .readFileSync(path.join(other[0], n), 'utf8')
914
+ .includes(APP_COPY_MARK);
915
+ } catch {
916
+ return false;
917
+ }
918
+ })
919
+ )
920
+ refuse(
921
+ ERROR_CODES.ERR_UNKNOWN_THEME,
922
+ `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).`,
923
+ {run: [`${P} new ${slug}`]},
924
+ );
744
925
  if (!same && (other || LIKE.includes(slug)))
745
926
  refuse(
746
927
  ERROR_CODES.ERR_UNKNOWN_THEME,
@@ -752,7 +933,18 @@ export function loadTheme(
752
933
  ...(fs.existsSync(themeFiles(cwd, `my-${slug}`).settings)
753
934
  ? [`${P} show my-${slug}`]
754
935
  : []),
755
- `${P} new ${usableNewName(cwd, `my-${slug}`)}${LIKE.includes(slug) ? ` --like ${slug}` : ''}`,
936
+ ...(LIKE.includes(slug)
937
+ ? [
938
+ ...onBuiltIn(
939
+ cwd,
940
+ slug,
941
+ `${P} new ${usableNewName(cwd, `my-${slug}`)} --like ${slug}`,
942
+ ),
943
+ ...(baseInstalled(cwd, slug)
944
+ ? []
945
+ : [`${P} new ${usableNewName(cwd, `my-${slug}`)}`]),
946
+ ]
947
+ : [`${P} new ${usableNewName(cwd, `my-${slug}`)}`]),
756
948
  ],
757
949
  },
758
950
  );
@@ -760,7 +952,24 @@ export function loadTheme(
760
952
  ERROR_CODES.ERR_UNKNOWN_THEME,
761
953
  `There is no theme "${slug}" made by this command (no themes/${slug}/${slug}.settings.json).`,
762
954
  (() => {
763
- const near = same ? [same] : nearest(slug, have);
955
+ // A doubled or trailing dash (brand--dark, t--): the name as new
956
+ // cleans it, the theme of that name when there is one, never a new
957
+ // theme new refuses.
958
+ const cleaned = String(slug)
959
+ .replace(/-{2,}/g, '-')
960
+ .replace(/^-+|-+$/g, '');
961
+ const cleanedHere =
962
+ cleaned !== slug &&
963
+ slugOk(cleaned) &&
964
+ fs.existsSync(themeFiles(cwd, cleaned).settings)
965
+ ? cleaned
966
+ : null;
967
+ const near = same
968
+ ? [same]
969
+ : cleanedHere
970
+ ? [cleanedHere]
971
+ : nearest(slug, have);
972
+ const newName = usableNewName(cwd, cleaned || slug);
764
973
  // A theme near the name comes first; a new theme of the name as
765
974
  // typed only after.
766
975
  return {
@@ -768,8 +977,8 @@ export function loadTheme(
768
977
  run: same
769
978
  ? [`${P} show ${same}`]
770
979
  : near.length
771
- ? [`${P} show ${near[0]}`, `${P} new ${slug}`]
772
- : [`${P} new ${slug}`],
980
+ ? [`${P} show ${near[0]}`, `${P} new ${newName}`]
981
+ : [`${P} new ${newName}`],
773
982
  };
774
983
  })(),
775
984
  );
@@ -780,44 +989,78 @@ export function loadTheme(
780
989
  refuseUnreadableFiles(cwd, slug);
781
990
  // undo is offered only when there is a step to go back to.
782
991
  const steps = readHistory(f.history).steps.length;
992
+ // Made again, the theme keeps the base it was built on when that can be
993
+ // read; else the text says it starts on no base.
994
+ const remake = remakeLines(cwd, slug);
995
+ const remakeText = `make the theme again with ${remake.lines.at(-1)}, which keeps the damaged file beside it and every file of yours${remake.base ? `, on ${remake.base}, the base it was built on` : ', on no base (the base it was built on cannot be read)'}`;
996
+ const remakeRun = remake.lines.map(name => ({
997
+ name,
998
+ reason: 'do this instead',
999
+ }));
1000
+ /** @type {any} */
1001
+ const data = settingsJson(fs.readFileSync(f.settings, 'utf8'));
1002
+ // A step back when there is one; else `new` only for damage `new` itself
1003
+ // keeps aside and makes again (settingsRemade): never a `new` it refuses.
783
1004
  const recover = steps
784
1005
  ? {
785
1006
  text: `, or step back to the settings before the last change with ${P} undo ${slug} (the last change is then lost)`,
786
1007
  run: [{name: `${P} undo ${slug}`, reason: 'do this instead'}],
787
1008
  }
788
- : {
789
- text: `; or make the theme again with ${P} new ${slug}, which keeps the damaged file beside it and every file of yours`,
790
- run: [{name: `${P} new ${slug}`, reason: 'do this instead'}],
791
- };
792
- /** @type {any} */
793
- let data;
794
- try {
795
- data = JSON.parse(
796
- fs.readFileSync(f.settings, 'utf8').replace(/^\uFEFF/, ''),
797
- );
798
- } catch {
1009
+ : settingsRemade(data)
1010
+ ? {text: `; or ${remakeText}`, run: remakeRun}
1011
+ : {text: '', run: []};
1012
+ if (data === undefined)
799
1013
  throw new AstryxError(
800
1014
  `themes/${slug}/${slug}.settings.json is not valid JSON. Fix it by hand${recover.text}.`,
801
1015
  recover.run,
802
1016
  ERROR_CODES.ERR_THEME_INVALID,
803
1017
  );
804
- }
805
1018
  // Valid JSON of the wrong shape ([], {}, settings: null) is damage like
806
1019
  // invalid JSON: `new` makes the theme again, keeping the file aside.
807
1020
  if (!settingsShapeOk(data))
808
1021
  throw new AstryxError(
809
- `themes/${slug}/${slug}.settings.json is damaged: ${settingsProblem(data) ?? 'it is not a settings object'}. Fix it by hand${steps ? `, step back to the settings before the last change with ${P} undo ${slug},` : ''} or make the theme again with ${P} new ${slug}, which keeps the damaged file beside it and every file of yours. Nothing was changed.`,
1022
+ `themes/${slug}/${slug}.settings.json is damaged: ${settingsProblem(data) ?? 'it is not a settings object'}. Fix it by hand${steps ? `, step back to the settings before the last change with ${P} undo ${slug},` : ''} or ${remakeText}. Nothing was changed.`,
1023
+ [...recover.run.filter(r => !/ new /.test(r.name)), ...remakeRun],
1024
+ ERROR_CODES.ERR_THEME_INVALID,
1025
+ );
1026
+ readEntryWords(data);
1027
+ // `like: "none"`, the word for no base, is no base.
1028
+ if (data.like === 'none') delete data.like;
1029
+ // The folder names the theme: a name missing or changed by hand in the
1030
+ // file is the folder's, and the next save writes it back.
1031
+ data.name = slug;
1032
+ const problem = settingsProblem(data, skip);
1033
+ // An entry whose mode or source means nothing: `undo` with its name
1034
+ // removes that entry only; a step back loses the last change.
1035
+ const damaged = problem ? damagedEntry(data, problem) : null;
1036
+ if (damaged)
1037
+ throw new AstryxError(
1038
+ `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.`,
810
1039
  [
811
- ...recover.run.filter(r => !/ new /.test(r.name)),
812
- {name: `${P} new ${slug}`, reason: 'do this instead'},
1040
+ {
1041
+ name: `${P} undo ${slug} ${undoArgs(damagedUndo(damaged))}`,
1042
+ reason: 'do this instead: removes only that setting',
1043
+ },
1044
+ ...(steps
1045
+ ? [
1046
+ {
1047
+ name: `${P} undo ${slug}`,
1048
+ reason:
1049
+ 'or step back to the settings before the last change (the last change is then lost)',
1050
+ },
1051
+ ]
1052
+ : []),
813
1053
  ],
814
1054
  ERROR_CODES.ERR_THEME_INVALID,
815
1055
  );
816
- const problem = settingsProblem(data, skip);
817
1056
  // A value made under looser rules is not damage: the command that
818
1057
  // changes or removes that setting still works, with the other bad ones
819
1058
  // left out of the build, so each listed fix runs on its own.
820
- const all = problem ? badSettings(data) : [];
1059
+ // A setting listed twice is named as such, with keep and remove lines,
1060
+ // even when one of its values is bad: removing the bad one by its name
1061
+ // would remove both.
1062
+ const listedTwice = Boolean(problem?.includes(' is listed twice ('));
1063
+ const all = problem && !listedTwice ? badSettings(data) : [];
821
1064
  if (
822
1065
  problem &&
823
1066
  skip &&
@@ -854,43 +1097,126 @@ export function loadTheme(
854
1097
  })),
855
1098
  ERROR_CODES.ERR_THEME_INVALID,
856
1099
  );
857
- const bad = problem ? badSetting(data) : null;
1100
+ // A damaged mode or base is fixed first: the message names it, so the
1101
+ // suggestions set it (another bad value is named on the next run).
1102
+ // (Not an entry named mode or base inside the settings list.)
1103
+ const fieldBroken =
1104
+ (/^(it has no mode|mode ")/.test(problem ?? '') &&
1105
+ !['both', 'light-only', 'dark-only'].includes(data?.mode)) ||
1106
+ (/^base "/.test(problem ?? '') &&
1107
+ data?.like != null &&
1108
+ !LIKE.includes(data.like));
1109
+ const bad = problem && !fieldBroken && !listedTwice ? badSetting(data) : null;
858
1110
  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'
1111
+ // The value it holds, cleaned as typed input is (stray or invisible
1112
+ // spaces, other letters, a pasted `corners: pill`), when the dial takes
1113
+ // that; else a value it takes, for a dial; a color for a color token.
1114
+ const cleaned =
1115
+ DIALS[bad.thing] && typeof bad.value === 'string'
1116
+ ? vibrancyMeant(bad.thing, cleanDialValue(bad.thing, bad.value))
1117
+ : null;
1118
+ // Vibrancy saturates the colors the color dials make: with none, set
1119
+ // refuses it as having no effect, so it is not offered.
1120
+ const vibrancyActs =
1121
+ bad.thing !== 'vibrancy' ||
1122
+ (Array.isArray(data.settings) ? data.settings : []).some(
1123
+ (/** @type {any} */ x) =>
1124
+ x && x.source === 'dial' && PALETTE_DIALS.includes(x.thing),
1125
+ );
1126
+ const meant =
1127
+ cleaned &&
1128
+ cleaned !== bad.value &&
1129
+ vibrancyActs &&
1130
+ !valueProblem({...bad, value: cleaned})
1131
+ ? cleaned
1132
+ : null;
1133
+ // Only the value it holds, cleaned: never a stock value it did not hold.
1134
+ // A vibrancy with no color to saturate is one set refuses: undo only.
1135
+ const example =
1136
+ bad.thing === 'vibrancy' &&
1137
+ !data.settings.some(
1138
+ (/** @type {any} */ x) =>
1139
+ x !== bad && x.source === 'dial' && PALETTE_DIALS.includes(x.thing),
1140
+ )
1141
+ ? null
1142
+ : meant;
1143
+ // The entry rides on the refusal: a change reads its value as set reads
1144
+ // a typed one, and offers that repair beside the undo (see _edit).
1145
+ throw Object.assign(
1146
+ new AstryxError(
1147
+ `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.`,
1148
+ [
1149
+ {
1150
+ name: `${P} undo ${slug} ${undoArgs(bad)}`,
1151
+ reason: 'do this instead',
1152
+ },
1153
+ // Only a set that replaces this very entry: `mode` and `base` set
1154
+ // the theme's own fields, not an entry in the list.
1155
+ ...(example && !['mode', 'base'].includes(bad.thing)
1156
+ ? [
1157
+ {
1158
+ name: `${P} set ${slug} ${setArgs(bad, example)}`,
1159
+ reason: meant
1160
+ ? 'or set the value it holds, cleaned'
1161
+ : 'or give it a value it takes',
1162
+ },
1163
+ ]
1164
+ : []),
1165
+ ],
1166
+ ERROR_CODES.ERR_THEME_INVALID,
1167
+ ),
1168
+ {damaged: bad, aboutSaved: true},
1169
+ );
1170
+ }
1171
+ // A bad mode or base is fixed by setting it.
1172
+ // A value written in other letters (Dark-Only, Neutral) is the one meant.
1173
+ const {mode: modeMeant, like: likeMeant} = fieldsMeant(data);
1174
+ const fieldFix = /^(it has no mode|mode ")/.test(problem ?? '')
1175
+ ? `${P} set ${slug} mode ${['both', 'light-only', 'dark-only'].includes(modeMeant) ? modeMeant : 'both'}`
1176
+ : /^base "/.test(problem ?? '')
1177
+ ? `${P} set ${slug} base ${LIKE.includes(likeMeant) && baseInstalled(cwd, likeMeant) ? likeMeant : (builtOnBase(cwd, slug) ?? 'none')}`
1178
+ : null;
1179
+ // A damaged mode or base and a bad value in the list: setting the field
1180
+ // is refused while the list holds the bad value, but fixing that entry
1181
+ // saves the field as meant too, so its fix comes first. Never a bare
1182
+ // undo, which would throw away the last real change.
1183
+ const alsoBad = fieldFix ? badSetting(data) : null;
1184
+ if (problem && fieldFix && alsoBad) {
1185
+ const cleaned =
1186
+ DIALS[alsoBad.thing] && typeof alsoBad.value === 'string'
1187
+ ? vibrancyMeant(
1188
+ alsoBad.thing,
1189
+ cleanDialValue(alsoBad.thing, alsoBad.value),
1190
+ )
1191
+ : null;
1192
+ const meant =
1193
+ cleaned &&
1194
+ cleaned !== alsoBad.value &&
1195
+ !['mode', 'base'].includes(alsoBad.thing) &&
1196
+ !valueProblem({...alsoBad, value: cleaned})
1197
+ ? cleaned
864
1198
  : null;
1199
+ const field = /^base "/.test(problem) ? 'base' : 'mode';
1200
+ const fieldValue = fieldFix.split(' ').pop();
865
1201
  throw new AstryxError(
866
- `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.`,
1202
+ `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.`,
867
1203
  [
868
- {name: `${P} undo ${slug} ${undoArgs(bad)}`, reason: 'do this instead'},
869
- ...(example
1204
+ ...(meant
870
1205
  ? [
871
1206
  {
872
- name: `${P} set ${slug} ${undoArgs(bad).replace(bad.thing, `${bad.thing} ${quoteCommandArgument(example)}`)}`,
873
- reason: 'or give it a value it takes',
1207
+ name: `${P} set ${slug} ${setArgs(alsoBad, meant)}`,
1208
+ reason: 'do this instead: set the value it holds, cleaned',
874
1209
  },
875
1210
  ]
876
1211
  : []),
1212
+ {
1213
+ name: `${P} undo ${slug} ${undoArgs(alsoBad)}`,
1214
+ reason: meant ? 'or remove that setting' : 'do this instead',
1215
+ },
877
1216
  ],
878
1217
  ERROR_CODES.ERR_THEME_INVALID,
879
1218
  );
880
1219
  }
881
- // A bad mode or base is fixed by setting it.
882
- // 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();
889
- const fieldFix = /^(it has no mode|mode ")/.test(problem ?? '')
890
- ? `${P} set ${slug} mode ${['both', 'light-only', 'dark-only'].includes(modeMeant) ? modeMeant : 'both'}`
891
- : /^base "/.test(problem ?? '')
892
- ? `${P} set ${slug} base ${LIKE.includes(likeMeant) && baseInstalled(cwd, likeMeant) ? likeMeant : 'none'}`
893
- : null;
894
1220
  // A setting listed twice: setting it to one of its values, or undoing
895
1221
  // it, keeps one entry or none.
896
1222
  const twice = problem?.includes(' is listed twice (')
@@ -900,7 +1226,7 @@ export function loadTheme(
900
1226
  throw new AstryxError(
901
1227
  `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
1228
  fieldFix
903
- ? [{name: fieldFix, reason: 'do this instead'}, ...recover.run]
1229
+ ? [{name: fieldFix, reason: 'do this instead'}]
904
1230
  : twice
905
1231
  ? [
906
1232
  ...twice.values
@@ -911,7 +1237,7 @@ export function loadTheme(
911
1237
  )
912
1238
  .slice(0, 2)
913
1239
  .map(v => ({
914
- name: `${P} set ${slug} ${undoArgs(twice.setting).replace(twice.setting.thing, `${twice.setting.thing} ${quoteCommandArgument(String(v))}`)}`,
1240
+ name: `${P} set ${slug} ${setArgs(twice.setting, String(v))}`,
915
1241
  reason: `keep ${v}`,
916
1242
  })),
917
1243
  {
@@ -926,6 +1252,43 @@ export function loadTheme(
926
1252
  return data;
927
1253
  }
928
1254
 
1255
+ /**
1256
+ * A command that builds on a built-in theme, as it runs here: after the
1257
+ * line that installs that theme's package when the project does not have
1258
+ * it, so the first line offered always works.
1259
+ * @param {string} cwd
1260
+ * @param {string} base a built-in theme
1261
+ * @param {string} line the command on that base
1262
+ * @returns {string[]}
1263
+ */
1264
+ export function onBuiltIn(cwd, base, line) {
1265
+ return baseInstalled(cwd, base)
1266
+ ? [line]
1267
+ : [installLine(cwd, [`@astryxdesign/theme-${base}`]), line];
1268
+ }
1269
+
1270
+ /**
1271
+ * {@link onBuiltIn} with what each line is for: the install first, then
1272
+ * the line, which works once it is installed (never offered as working
1273
+ * now).
1274
+ * @param {string} cwd
1275
+ * @param {string} base
1276
+ * @param {string} line
1277
+ * @returns {Array<{name: string, reason: string}>}
1278
+ */
1279
+ export function onBuiltInSteps(cwd, base, line) {
1280
+ return onBuiltIn(cwd, base, line).map(name =>
1281
+ name === line
1282
+ ? {
1283
+ name,
1284
+ reason: baseInstalled(cwd, base)
1285
+ ? 'do this instead'
1286
+ : `then this, once @astryxdesign/theme-${base} is installed`,
1287
+ }
1288
+ : {name, reason: 'install it'},
1289
+ );
1290
+ }
1291
+
929
1292
  /**
930
1293
  * The first setting listed more than once, with every value it is listed
931
1294
  * with, in order.
@@ -961,9 +1324,11 @@ export function settingsProblem(
961
1324
  ) {
962
1325
  if (!data || typeof data !== 'object' || Array.isArray(data))
963
1326
  return 'the file is not a settings object';
964
- // `set <theme> mode` and `set <theme> base` fix their own field.
1327
+ // A command that changes or removes a setting (or sets mode or base)
1328
+ // puts a damaged mode or base back to its default itself, with a note, so
1329
+ // two damaged fields never send each fix to the other.
965
1330
  const fixing = typeof skip === 'string' ? skip : skip?.thing;
966
- const field = fixing === 'mode' || fixing === 'base';
1331
+ const field = Boolean(fixing);
967
1332
  if (!field && !['both', 'light-only', 'dark-only'].includes(data.mode))
968
1333
  return data.mode == null
969
1334
  ? 'it has no mode'
@@ -980,28 +1345,345 @@ export function settingsProblem(
980
1345
  return `lifted is ${JSON.stringify(data.lifted)}, not a list of text (the build writes it; remove the field and the next build writes it again)`;
981
1346
  /** @type {Map<string, any>} */
982
1347
  const keys = new Map();
1348
+ /** How many entries each key has. @type {Map<string, number>} */
1349
+ const twins = new Map();
1350
+ for (const s of data.settings)
1351
+ if (s && typeof s.thing === 'string')
1352
+ twins.set(keyOf(s), (twins.get(keyOf(s)) ?? 0) + 1);
983
1353
  for (const s of data.settings) {
984
1354
  // A value or scope that is not text is a bad setting `undo` removes;
985
1355
  // a setting with no name is damage.
986
1356
  if (!s || typeof s.thing !== 'string' || !('value' in s))
987
1357
  return 'a setting has no thing or value';
1358
+ if (removes(skip) && skips(s, skip) && entryDamage(s)) continue;
988
1359
  if (!['dial', 'token', 'property'].includes(s.source))
989
- return `${s.thing} has no source (dial, token or property)`;
1360
+ return s.source == null || s.source === ''
1361
+ ? `${s.thing} has no source (dial, token or property)`
1362
+ : `${s.thing} has source ${JSON.stringify(s.source)}, not dial, token or property`;
990
1363
  if (s.mode != null && s.mode !== 'light' && s.mode !== 'dark')
991
- return `${s.thing} has mode "${s.mode}"`;
1364
+ return `${s.thing} has mode ${JSON.stringify(s.mode)}, not light or dark`;
1365
+ if (s.only != null && s.only !== true)
1366
+ return `${s.thing} has only ${JSON.stringify(s.only)}, not true or false`;
1367
+ if (s.only === true && !onlyFits(s))
1368
+ return `${describe({...s, only: undefined, value: '?'}).replace(' = ?', '')} has only, which is for one member of a group styled alike (${AUTO_SPREAD.join(', ')})`;
992
1369
  const key = keyOf(s);
993
1370
  // The command that changes or removes a setting listed twice keeps one
994
- // value, or none, so it fixes the list.
1371
+ // value, or none, so it fixes the list. An entry with a twin is named
1372
+ // as listed twice, even when one value is bad: an undo of that setting
1373
+ // would remove both.
995
1374
  if (keys.has(key) && !skips(s, skip))
996
1375
  return `${describe({...s, value: '?'}).replace(' = ?', '')} is listed twice (${JSON.stringify(keys.get(key).value)}, ${JSON.stringify(s.value)})`;
997
1376
  keys.set(key, s);
998
- if (skips(s, skip)) continue;
999
- const problem = valueProblem(s);
1000
- if (problem) return problem;
1377
+ if (!skips(s, skip) && (twins.get(key) ?? 0) < 2) {
1378
+ const problem = valueProblem(s);
1379
+ if (problem) return problem;
1380
+ }
1381
+ }
1382
+ return null;
1383
+ }
1384
+
1385
+ /**
1386
+ * The built-in base the editor last built a theme on, read from the
1387
+ * generated module's header (`// Built on @astryxdesign/theme-neutral …`),
1388
+ * else from the newest undo step, or null when neither can be read. What a damaged base in
1389
+ * the settings file is put back to, and what a theme made again keeps.
1390
+ * @param {string} cwd
1391
+ * @param {string} slug
1392
+ * @returns {string | null}
1393
+ */
1394
+ export function builtOnBase(cwd, slug) {
1395
+ const f = themeFiles(cwd, slug);
1396
+ /** @type {string | null | undefined} */
1397
+ let header;
1398
+ try {
1399
+ header = /\/\/ Built on @astryxdesign\/theme-([a-z0-9-]+) /.exec(
1400
+ fs.readFileSync(f.settingsTs, 'utf8'),
1401
+ )?.[1];
1402
+ } catch {
1403
+ header = null;
1404
+ }
1405
+ // With the module gone too, the newest undo step names the base.
1406
+ const steps = readHistory(f.history).steps;
1407
+ const stepped = steps.length
1408
+ ? settingsJson(steps[steps.length - 1])?.like
1409
+ : null;
1410
+ return (
1411
+ [header, stepped].find(b => typeof b === 'string' && LIKE.includes(b)) ??
1412
+ null
1413
+ );
1414
+ }
1415
+
1416
+ /**
1417
+ * The `new` that makes a theme again in place, on the base it was built on
1418
+ * as far as can still be read: the settings file's base (in any case), else
1419
+ * the base the generated module was built on. With none, it says the theme
1420
+ * starts on no base.
1421
+ * @param {string} cwd
1422
+ * @param {string} slug
1423
+ * @returns {{lines: string[], base: string | null}}
1424
+ */
1425
+ export function remakeLines(cwd, slug) {
1426
+ const f = themeFiles(cwd, slug);
1427
+ const read = (/** @type {string} */ file) => {
1428
+ try {
1429
+ return fs.readFileSync(file, 'utf8');
1430
+ } catch {
1431
+ return '';
1432
+ }
1433
+ };
1434
+ const saved = settingsJson(read(f.settings));
1435
+ // The base the file names, read as every reader reads it.
1436
+ const typed =
1437
+ saved && typeof saved.like === 'string' ? fieldsMeant(saved).like : null;
1438
+ const base =
1439
+ [typed, builtOnBase(cwd, slug)].find(b => b && LIKE.includes(b)) ?? null;
1440
+ return {
1441
+ base,
1442
+ lines: base
1443
+ ? onBuiltIn(cwd, base, `${P} new ${slug} --like ${base}`)
1444
+ : [`${P} new ${slug}`],
1445
+ };
1446
+ }
1447
+
1448
+ /**
1449
+ * A dial's own word typed in any case (ROOMY, MORE, Both, NONE): the word,
1450
+ * or null when the value is no word of that dial. The one case rule for
1451
+ * every dial, typed or saved. On the font dial several words are a family
1452
+ * list, whose names keep their letters; one word is the preset.
1453
+ * @param {string} thing
1454
+ * @param {string} value
1455
+ * @returns {string | null}
1456
+ */
1457
+ export function dialWordOf(thing, value) {
1458
+ if (!DIALS[thing]) return null;
1459
+ const words = new Set(
1460
+ String(DIALS[thing].values ?? '')
1461
+ .split('|')
1462
+ .filter(w => /^[a-z][a-z-]*$/.test(w)),
1463
+ );
1464
+ const lower = value.trim().toLowerCase();
1465
+ const read = thing === 'font' ? [lower] : lower.split(/\s+/);
1466
+ return lower && read.every(w => words.has(w)) ? lower : null;
1467
+ }
1468
+
1469
+ /**
1470
+ * Read each entry's mode and source as the editor writes them: a mode in
1471
+ * other letters or words (`Dark`, `night`, `day`) as light or dark, a
1472
+ * source in other letters (`Dial`) as written, and a missing source from
1473
+ * the thing (a dial name is a dial, a `--` name a token, anything with a
1474
+ * part a property). Each change is kept as a note for the next command,
1475
+ * which saves the entry that way. A value that means nothing is left for
1476
+ * the check to name.
1477
+ * @param {any} data
1478
+ */
1479
+ function readEntryWords(data) {
1480
+ /** @type {string[]} */
1481
+ const notes = [];
1482
+ // `lifted` is written by the build: one that is no list of text is
1483
+ // dropped, and the next build writes it again.
1484
+ if (
1485
+ data &&
1486
+ data.lifted != null &&
1487
+ (!Array.isArray(data.lifted) ||
1488
+ data.lifted.some((/** @type {unknown} */ x) => typeof x !== 'string'))
1489
+ ) {
1490
+ notes.push(
1491
+ `lifted was ${JSON.stringify(data.lifted)}, not a list of text; the build writes it again`,
1492
+ );
1493
+ delete data.lifted;
1494
+ }
1495
+ for (const s of Array.isArray(data?.settings) ? data.settings : []) {
1496
+ if (!s || typeof s !== 'object' || typeof s.thing !== 'string') continue;
1497
+ if (typeof s.mode === 'string' && s.mode !== 'light' && s.mode !== 'dark') {
1498
+ const read = modeWord(s.mode);
1499
+ if (read) {
1500
+ notes.push(
1501
+ `${s.thing} was saved with mode ${JSON.stringify(s.mode)}, read as ${read}`,
1502
+ );
1503
+ s.mode = read;
1504
+ }
1505
+ }
1506
+ // A part saved in other letters, with spaces around it, or as a list
1507
+ // of that one part (`Card`, ` card`, `["card"]`) is that part: part
1508
+ // names are lower case, so every reader matches it as one scope.
1509
+ {
1510
+ const one =
1511
+ Array.isArray(s.on) && s.on.length === 1 && typeof s.on[0] === 'string'
1512
+ ? s.on[0]
1513
+ : s.on;
1514
+ const part =
1515
+ typeof one === 'string' && /^\s*[a-z][a-z0-9-]*\s*$/i.test(one)
1516
+ ? one.trim().toLowerCase()
1517
+ : null;
1518
+ if (part && part !== s.on) {
1519
+ notes.push(
1520
+ `${s.thing} was saved on ${JSON.stringify(s.on)}, read as ${part}`,
1521
+ );
1522
+ s.on = part;
1523
+ }
1524
+ }
1525
+ // A dial's word saved in other letters (`Pill`) is that word.
1526
+ if (
1527
+ ['dial', undefined, null, ''].includes(s.source) ||
1528
+ String(s.source).toLowerCase() === 'dial'
1529
+ ) {
1530
+ // A corners size saved in rem is the px set saves it as.
1531
+ const word =
1532
+ typeof s.value !== 'string'
1533
+ ? null
1534
+ : (dialWordOf(s.thing, s.value) ??
1535
+ (s.thing === 'corners' ? cornersPlain(s.value) : null));
1536
+ if (word && word !== s.value) {
1537
+ notes.push(
1538
+ `${s.thing} was saved as ${JSON.stringify(s.value)}, read as ${word}`,
1539
+ );
1540
+ s.value = word;
1541
+ }
1542
+ }
1543
+ // A headings word saved under the other half (or a tracking word with
1544
+ // no half) is filed under the half the word belongs to.
1545
+ if (
1546
+ s.thing === 'headings' &&
1547
+ typeof s.value === 'string' &&
1548
+ (s.axis == null || s.axis === 'weight' || s.axis === 'tracking')
1549
+ ) {
1550
+ const half = Object.hasOwn(HEADING_TRACKING, s.value)
1551
+ ? 'tracking'
1552
+ : Object.hasOwn(HEADING_WEIGHTS, s.value)
1553
+ ? 'weight'
1554
+ : null;
1555
+ if (half && (s.axis ?? 'weight') !== half) {
1556
+ notes.push(
1557
+ `headings "${s.value}" was saved under ${s.axis ?? 'weight'}, read as ${half}`,
1558
+ );
1559
+ if (half === 'tracking') s.axis = 'tracking';
1560
+ else delete s.axis;
1561
+ }
1562
+ }
1563
+ // `only` is true or absent; a yes or no written as text (`"true"`,
1564
+ // `"yes"`, `"off"`) is read as what it says by the one yes/no reader,
1565
+ // since the build reads any other value as true.
1566
+ if (typeof s.only === 'string' && booleanWord(s.only) != null) {
1567
+ const read = booleanWord(s.only) === true;
1568
+ notes.push(
1569
+ `${s.thing} was saved with only ${JSON.stringify(s.only)}, read as ${read}`,
1570
+ );
1571
+ if (read) s.only = true;
1572
+ else delete s.only;
1573
+ } else if (s.only === false) delete s.only;
1574
+ if (!['dial', 'token', 'property'].includes(s.source)) {
1575
+ const typed = typeof s.source === 'string' ? s.source.trim() : '';
1576
+ const read = typed
1577
+ ? ['dial', 'token', 'property'].find(x => x === typed.toLowerCase())
1578
+ : s.source == null || s.source === ''
1579
+ ? DIALS[s.thing]
1580
+ ? 'dial'
1581
+ : s.thing.startsWith('--')
1582
+ ? 'token'
1583
+ : s.on
1584
+ ? 'property'
1585
+ : undefined
1586
+ : undefined;
1587
+ if (read) {
1588
+ notes.push(
1589
+ typed
1590
+ ? `${s.thing} was saved with source ${JSON.stringify(s.source)}, read as ${read}`
1591
+ : `${s.thing} was saved with no source, read as ${read}`,
1592
+ );
1593
+ s.source = read;
1594
+ }
1595
+ }
1001
1596
  }
1597
+ ENTRY_NOTES.set(data, notes);
1598
+ }
1599
+
1600
+ /** @type {WeakMap<object, string[]>} */
1601
+ const ENTRY_NOTES = new WeakMap();
1602
+
1603
+ /**
1604
+ * What loading read differently from the file in the theme's entries (a
1605
+ * mode or source in other letters, a missing source): one note each.
1606
+ * @param {object} data the theme as {@link loadTheme} returned it
1607
+ * @returns {string[]}
1608
+ */
1609
+ export function entryNotes(data) {
1610
+ return ENTRY_NOTES.get(data) ?? [];
1611
+ }
1612
+
1613
+ /**
1614
+ * Which part of an entry means nothing after reading: its source, mode or
1615
+ * `only`, or null.
1616
+ * @param {any} s
1617
+ * @returns {'mode' | 'source' | 'only' | null}
1618
+ */
1619
+ export function entryDamage(s) {
1620
+ if (!s || typeof s.thing !== 'string') return null;
1621
+ if (!['dial', 'token', 'property'].includes(s.source)) return 'source';
1622
+ if (s.mode != null && s.mode !== 'light' && s.mode !== 'dark') return 'mode';
1623
+ if (s.only != null && (s.only !== true || !onlyFits(s))) return 'only';
1002
1624
  return null;
1003
1625
  }
1004
1626
 
1627
+ /**
1628
+ * Whether `only` fits a setting: it names one member of a group styled
1629
+ * alike (a text input of inputs), as `set --only` takes it.
1630
+ * @param {any} s
1631
+ */
1632
+ function onlyFits(s) {
1633
+ const fam = typeof s.on === 'string' ? familyOf(s.on) : null;
1634
+ return Boolean(
1635
+ fam && !FAMILIES[s.on] && AUTO_SPREAD.includes(/** @type {string} */ (fam)),
1636
+ );
1637
+ }
1638
+
1639
+ /**
1640
+ * The entry as an undo names it: without the mode or `only` that means
1641
+ * nothing (an undo without them removes that entry).
1642
+ * @param {any} s
1643
+ */
1644
+ function damagedUndo(s) {
1645
+ const damage = entryDamage(s);
1646
+ return {
1647
+ ...s,
1648
+ mode: damage === 'mode' ? undefined : s.mode,
1649
+ only: damage === 'only' ? undefined : s.only,
1650
+ };
1651
+ }
1652
+
1653
+ /**
1654
+ * The entry a settings problem names when that problem is its mode or
1655
+ * `only`, or null.
1656
+ * @param {any} data
1657
+ * @param {string} problem
1658
+ */
1659
+ function damagedEntry(data, problem) {
1660
+ return (
1661
+ (Array.isArray(data?.settings) ? data.settings : []).find(
1662
+ (/** @type {any} */ s) =>
1663
+ (entryDamage(s) === 'source' &&
1664
+ typeof s.source === 'string' &&
1665
+ s.source !== '' &&
1666
+ problem.startsWith(`${s.thing} has source `)) ||
1667
+ (entryDamage(s) === 'mode' &&
1668
+ problem.startsWith(`${s.thing} has mode `)) ||
1669
+ (entryDamage(s) === 'only' &&
1670
+ (problem.startsWith(`${s.thing} has only `) ||
1671
+ problem.includes(' has only, which is for one member'))),
1672
+ ) ?? null
1673
+ );
1674
+ }
1675
+
1676
+ /**
1677
+ * Whether the command removes the setting it names (an undo): only that
1678
+ * takes an entry whose mode or source means nothing.
1679
+ * @param {string | Partial<Setting> | undefined} skip
1680
+ */
1681
+ function removes(skip) {
1682
+ return Boolean(
1683
+ skip && typeof skip === 'object' && /** @type {any} */ (skip).removing,
1684
+ );
1685
+ }
1686
+
1005
1687
  /**
1006
1688
  * Whether a setting is the one a command changes or removes: by thing, or
1007
1689
  * by the whole identity (part, variant, state, mode) when one is given.
@@ -1016,7 +1698,8 @@ function skips(s, skip) {
1016
1698
  (s.on ?? '') === (skip.on ?? '') &&
1017
1699
  (s.when ?? '') === (skip.when ?? '') &&
1018
1700
  (s.state ?? '') === (skip.state ?? '') &&
1019
- (s.mode ?? '') === (skip.mode ?? '')
1701
+ ((s.mode ?? '') === (skip.mode ?? '') ||
1702
+ (removes(skip) && !skip.mode && entryDamage(s) === 'mode'))
1020
1703
  );
1021
1704
  }
1022
1705
 
@@ -1040,24 +1723,53 @@ export function badSettings(data) {
1040
1723
  export function undoArgs(x) {
1041
1724
  return [
1042
1725
  quoteCommandArgument(String(x.thing)),
1043
- ...(x.on ? [`--on ${quoteCommandArgument(String(x.on))}`] : []),
1044
- ...(x.when ? [`--when ${quoteCommandArgument(String(x.when))}`] : []),
1045
- ...(x.state ? [`--state ${quoteCommandArgument(String(x.state))}`] : []),
1046
- ...(x.mode ? [`--mode ${quoteCommandArgument(String(x.mode))}`] : []),
1047
- ...(x.only ? ['--only'] : []),
1726
+ // The tracking half of headings is named, so the undo reaches it even
1727
+ // when it is listed twice (a bare `undo headings` then reads the weight
1728
+ // half).
1729
+ ...(x.thing === 'headings' && x.axis === 'tracking' ? ['tracking'] : []),
1730
+ ...scopeFlags(x),
1048
1731
  ].join(' ');
1049
1732
  }
1050
1733
 
1051
1734
  /**
1052
- * The first setting whose only problem is its value (made under looser
1053
- * rules): `undo <theme> <undoArgs>` removes it.
1054
- * @param {any} data
1055
- * @returns {Setting | null}
1735
+ * The words of a `set` that gives a setting's scope a value: set reads a
1736
+ * headings half from its word, so no half is named.
1737
+ * @param {import('./_settings.mjs').Setting} x
1738
+ * @param {string} value
1056
1739
  */
1057
- export function badSetting(data) {
1058
- for (const s of Array.isArray(data?.settings) ? data.settings : [])
1059
- if (s && typeof s.thing === 'string' && valueProblem(s)) return s;
1060
- return null;
1740
+ export function setArgs(x, value) {
1741
+ return [
1742
+ quoteCommandArgument(String(x.thing)),
1743
+ quoteCommandArgument(value),
1744
+ ...scopeFlags(x),
1745
+ ].join(' ');
1746
+ }
1747
+
1748
+ /**
1749
+ * The flags that name a setting's scope, as set and undo take them.
1750
+ * @param {import('./_settings.mjs').Setting} x
1751
+ * @returns {string[]}
1752
+ */
1753
+ function scopeFlags(x) {
1754
+ return [
1755
+ ...(x.on ? [`--on ${quoteCommandArgument(String(x.on))}`] : []),
1756
+ ...(x.when ? [`--when ${quoteCommandArgument(String(x.when))}`] : []),
1757
+ ...(x.state ? [`--state ${quoteCommandArgument(String(x.state))}`] : []),
1758
+ ...(x.mode ? [`--mode ${quoteCommandArgument(String(x.mode))}`] : []),
1759
+ ...(x.only ? ['--only'] : []),
1760
+ ];
1761
+ }
1762
+
1763
+ /**
1764
+ * The first setting whose only problem is its value (made under looser
1765
+ * rules): `undo <theme> <undoArgs>` removes it.
1766
+ * @param {any} data
1767
+ * @returns {Setting | null}
1768
+ */
1769
+ export function badSetting(data) {
1770
+ for (const s of Array.isArray(data?.settings) ? data.settings : [])
1771
+ if (s && typeof s.thing === 'string' && valueProblem(s)) return s;
1772
+ return null;
1061
1773
  }
1062
1774
 
1063
1775
  /**
@@ -1111,6 +1823,17 @@ export function valueProblem(s) {
1111
1823
  const seed = colorProblem(s.value);
1112
1824
  if (seed) return `${bad} ${seed.message}`;
1113
1825
  }
1826
+ // `axis` names the half of headings a value sets; no other dial has
1827
+ // one, and each half takes only its own words.
1828
+ if (s.axis != null && s.thing !== 'headings')
1829
+ return `${s.thing} has an axis (${JSON.stringify(s.axis)}), which only headings takes`;
1830
+ if (s.thing === 'headings') {
1831
+ if (s.axis != null && s.axis !== 'weight' && s.axis !== 'tracking')
1832
+ return `headings has axis ${JSON.stringify(s.axis)}, not weight or tracking`;
1833
+ const half = s.axis === 'tracking' ? HEADING_TRACKING : HEADING_WEIGHTS;
1834
+ if (!Object.hasOwn(half, s.value))
1835
+ return `${bad} is not a ${s.axis ?? 'weight'} headings takes (${Object.keys(half).join('|')})`;
1836
+ }
1114
1837
  const words = d.values.split('|').filter(w => !w.startsWith('<'));
1115
1838
  const ok =
1116
1839
  s.thing === 'corners'
@@ -1133,6 +1856,35 @@ export function valueProblem(s) {
1133
1856
  return null;
1134
1857
  }
1135
1858
 
1859
+ /**
1860
+ * One entry of the top-level `tokens` map in a theme's own source, as
1861
+ * written: its token (null for a computed key no read of the file can
1862
+ * resolve), the key as typed, the line that sets it, and its value's shape.
1863
+ * A `chain` entry is another theme the file defines (`theme`, its name):
1864
+ * its call, or a token its literal tokens map sets. A `scope` entry names
1865
+ * where a scope (`components`, `onDark`, `onLight`, `adaptations`,
1866
+ * `localTokens`) starts; a `scoped` entry is a token one sets, with its
1867
+ * scope path (`components.button.base`). A `duplicate` entry names a
1868
+ * second `tokens` key (with every line); a
1869
+ * `typography` entry is one typography field (its dotted key and value);
1870
+ * an `unresolved` entry says the map holds something only a build reads.
1871
+ * @typedef {{token: string | null, key: string, line: number | null, kind: 'text' | 'number' | 'pair' | 'object' | 'other' | 'duplicate' | 'typography' | 'unresolved' | 'scope' | 'scoped' | 'chain', scope?: string, theme?: string, value?: any, halves?: Array<string | number | undefined>, lines?: Array<number | null>, file?: string, overridden?: boolean, expression?: boolean, notToken?: boolean}} OwnTokenEntry
1872
+ */
1873
+
1874
+ /**
1875
+ * The entries of the top-level `tokens` map in a theme's own source, read
1876
+ * from its syntax tree, each with the line that sets it.
1877
+ * @param {string} cwd
1878
+ * @param {string} slug
1879
+ * @returns {OwnTokenEntry[]}
1880
+ */
1881
+ export function ownTokenEntries(cwd, slug) {
1882
+ /** @type {OwnTokenEntry[]} */
1883
+ const detail = [];
1884
+ ownPageTokens(cwd, slug, detail);
1885
+ return detail;
1886
+ }
1887
+
1136
1888
  /**
1137
1889
  * The page-wide tokens a theme's own source sets: the keys of the top-level
1138
1890
  * `tokens` map in its `defineTheme({...})`, read from the syntax tree, each
@@ -1142,7 +1894,11 @@ export function valueProblem(s) {
1142
1894
  * @param {string} slug
1143
1895
  * @returns {Map<string, string | null>}
1144
1896
  */
1145
- function ownPageTokens(cwd, slug) {
1897
+ function ownPageTokens(
1898
+ cwd,
1899
+ slug,
1900
+ detail = /** @type {OwnTokenEntry[] | null} */ (null),
1901
+ ) {
1146
1902
  /** @type {Map<string, string | null>} */
1147
1903
  const out = new Map();
1148
1904
  /** @type {string} */
@@ -1241,34 +1997,379 @@ function ownPageTokens(cwd, slug) {
1241
1997
  ) ??
1242
1998
  (calls.length === 1 ? calls[0] : null);
1243
1999
  if (!chosen) return out;
2000
+ // Every other theme the file defines (one the exported theme extends),
2001
+ // by its name: the line of its call and of each token its literal
2002
+ // tokens map sets.
2003
+ if (detail)
2004
+ for (const {call} of calls) {
2005
+ if (call === chosen.call) continue;
2006
+ const other = unwrap(call.arguments[0]);
2007
+ if (other?.type !== 'ObjectExpression') continue;
2008
+ /** @param {string} key */
2009
+ const prop = key =>
2010
+ other.properties.find(
2011
+ (/** @type {any} */ p) =>
2012
+ p.type === 'ObjectProperty' && !p.computed && keyOf(p.key) === key,
2013
+ );
2014
+ const theme = textOf(unwrap(prop('name')?.value));
2015
+ if (!theme) continue;
2016
+ detail.push({
2017
+ token: null,
2018
+ key: theme,
2019
+ kind: 'chain',
2020
+ theme,
2021
+ line: call.loc?.start?.line ?? null,
2022
+ });
2023
+ const map = unwrap(prop('tokens')?.value);
2024
+ for (const p of map?.type === 'ObjectExpression' ? map.properties : []) {
2025
+ const k =
2026
+ p.type !== 'ObjectProperty'
2027
+ ? null
2028
+ : p.computed
2029
+ ? textOf(unwrap(p.key))
2030
+ : keyOf(p.key);
2031
+ if (k?.startsWith('--'))
2032
+ detail.push({
2033
+ token: k,
2034
+ key: k,
2035
+ kind: 'chain',
2036
+ theme,
2037
+ line: p.loc?.start?.line ?? null,
2038
+ });
2039
+ }
2040
+ }
1244
2041
  const def = unwrap(chosen.call.arguments[0]);
1245
2042
  if (def?.type !== 'ObjectExpression') return out;
1246
- const tokensProp = def.properties.find(
2043
+ // JavaScript keeps the last of two `tokens` keys: that one is read, and
2044
+ // both are named.
2045
+ const tokensProps = def.properties.filter(
1247
2046
  (/** @type {any} */ p) =>
1248
2047
  p.type === 'ObjectProperty' && !p.computed && keyOf(p.key) === 'tokens',
1249
2048
  );
2049
+ if (detail && tokensProps.length > 1)
2050
+ detail.push({
2051
+ token: null,
2052
+ key: 'tokens',
2053
+ kind: 'duplicate',
2054
+ line: tokensProps[0].loc?.start?.line ?? null,
2055
+ lines: tokensProps.map((/** @type {any} */ p) => p.loc?.start?.line),
2056
+ });
2057
+ // Tokens a scope sets (a part's blocks in `components`, `onDark`,
2058
+ // `onLight`, an adaptation rule), each with its scope path and line.
2059
+ if (detail)
2060
+ for (const p of def.properties) {
2061
+ const scope =
2062
+ p.type === 'ObjectProperty' && !p.computed ? keyOf(p.key) : null;
2063
+ if (
2064
+ !scope ||
2065
+ ![
2066
+ 'components',
2067
+ 'onDark',
2068
+ 'onLight',
2069
+ 'adaptations',
2070
+ 'localTokens',
2071
+ ].includes(scope)
2072
+ )
2073
+ continue;
2074
+ detail.push({
2075
+ token: null,
2076
+ key: scope,
2077
+ kind: 'scope',
2078
+ line: p.loc?.start?.line ?? null,
2079
+ });
2080
+ /** @param {any} node @param {string[]} at @param {number} depth */
2081
+ const walk = (node, at, depth) => {
2082
+ const obj = unwrap(node);
2083
+ if (depth > 12) return;
2084
+ if (obj?.type === 'ArrayExpression') {
2085
+ obj.elements.forEach(
2086
+ (/** @type {any} */ el, /** @type {number} */ i) =>
2087
+ walk(el, [...at, String(i)], depth + 1),
2088
+ );
2089
+ return;
2090
+ }
2091
+ if (obj?.type !== 'ObjectExpression') return;
2092
+ for (const q of obj.properties) {
2093
+ if (q.type !== 'ObjectProperty') continue;
2094
+ const k = q.computed ? textOf(unwrap(q.key)) : keyOf(q.key);
2095
+ if (!k) continue;
2096
+ const leaf = unwrap(q.value);
2097
+ // A token, or a part's property (its value no block), by its
2098
+ // scope path and line.
2099
+ if (
2100
+ k.startsWith('--') ||
2101
+ (leaf?.type !== 'ObjectExpression' &&
2102
+ leaf?.type !== 'ArrayExpression')
2103
+ )
2104
+ detail.push({
2105
+ token: k,
2106
+ key: k,
2107
+ kind: 'scoped',
2108
+ scope: at.join('.'),
2109
+ line: q.loc?.start?.line ?? null,
2110
+ });
2111
+ else walk(q.value, [...at, k], depth + 1);
2112
+ }
2113
+ };
2114
+ walk(p.value, [scope], 0);
2115
+ }
2116
+ // The typography fields, as written, for their own checks.
2117
+ const typo = def.properties.find(
2118
+ (/** @type {any} */ p) =>
2119
+ p.type === 'ObjectProperty' &&
2120
+ !p.computed &&
2121
+ keyOf(p.key) === 'typography',
2122
+ );
2123
+ if (detail && typo) {
2124
+ /** @param {any} node @param {string[]} at */
2125
+ const walk = (node, at) => {
2126
+ const obj = unwrap(node);
2127
+ if (obj?.type !== 'ObjectExpression') return;
2128
+ for (const p of obj.properties) {
2129
+ if (p.type !== 'ObjectProperty' || p.computed) continue;
2130
+ const k = keyOf(p.key);
2131
+ if (!k) continue;
2132
+ const v = unwrap(p.value);
2133
+ if (v?.type === 'ObjectExpression') walk(v, [...at, k]);
2134
+ else
2135
+ detail.push({
2136
+ token: null,
2137
+ key: [...at, k].join('.'),
2138
+ kind: 'typography',
2139
+ line: p.loc?.start?.line ?? null,
2140
+ expression:
2141
+ textOf(v) == null &&
2142
+ v?.type !== 'NumericLiteral' &&
2143
+ !(
2144
+ v?.type === 'UnaryExpression' &&
2145
+ v.argument?.type === 'NumericLiteral'
2146
+ ),
2147
+ value:
2148
+ textOf(v) ??
2149
+ (v?.type === 'NumericLiteral'
2150
+ ? v.value
2151
+ : v?.type === 'UnaryExpression' &&
2152
+ v.operator === '-' &&
2153
+ v.argument?.type === 'NumericLiteral'
2154
+ ? -v.argument.value
2155
+ : undefined),
2156
+ });
2157
+ }
2158
+ };
2159
+ walk(typo.value, []);
2160
+ }
2161
+ const tokensProp = tokensProps[tokensProps.length - 1];
1250
2162
  if (!tokensProp) return out;
1251
2163
  let unresolved = false;
1252
- /** @param {any} node @param {number} depth */
1253
- const collect = (node, depth) => {
1254
- const obj = unwrap(node);
2164
+ const dir = path.dirname(themeFiles(cwd, slug).ts);
2165
+ /**
2166
+ * The object a name imported from a file beside the theme gives (`import
2167
+ * {mine} from './mine'`, a default import of a .json file), read from
2168
+ * that file, with its own code and path; null for any other name.
2169
+ * @param {string} name
2170
+ * @returns {{obj: any, code: string, file: string, unwrap: (n: any) => any} | null}
2171
+ */
2172
+ const imported = name => {
2173
+ for (const st of ast.program.body) {
2174
+ if (st.type !== 'ImportDeclaration') continue;
2175
+ const spec = st.specifiers.find(
2176
+ (/** @type {any} */ x) => x.local?.name === name,
2177
+ );
2178
+ const from = String(st.source?.value ?? '');
2179
+ if (!spec || !from.startsWith('.')) continue;
2180
+ const base = path.resolve(dir, from);
2181
+ const file = [
2182
+ '',
2183
+ '.ts',
2184
+ '.mts',
2185
+ '.tsx',
2186
+ '.js',
2187
+ '.mjs',
2188
+ '.json',
2189
+ '/index.ts',
2190
+ ]
2191
+ .map(x => base + x)
2192
+ .find(f => {
2193
+ try {
2194
+ return fs.statSync(f).isFile();
2195
+ } catch {
2196
+ return false;
2197
+ }
2198
+ });
2199
+ if (!file) return null;
2200
+ try {
2201
+ const text = fs.readFileSync(file, 'utf8');
2202
+ const json = file.endsWith('.json');
2203
+ const source = json ? `export default ${text}` : text;
2204
+ const other = /** @type {any} */ (
2205
+ parseModule(source, {sourceType: 'module', plugins: ['typescript']})
2206
+ );
2207
+ /** @type {Map<string, any>} */
2208
+ const local = new Map();
2209
+ /** @type {any} */
2210
+ let found = null;
2211
+ const want =
2212
+ spec.type === 'ImportDefaultSpecifier'
2213
+ ? 'default'
2214
+ : (spec.imported?.name ?? spec.imported?.value);
2215
+ for (const top of other.program.body) {
2216
+ const d =
2217
+ top.type === 'ExportNamedDeclaration' ? top.declaration : top;
2218
+ for (const v of d?.declarations ?? [])
2219
+ if (v.id?.type === 'Identifier') {
2220
+ local.set(v.id.name, v.init);
2221
+ if (top.type === 'ExportNamedDeclaration' && v.id.name === want)
2222
+ found = v.init;
2223
+ }
2224
+ if (top.type === 'ExportDefaultDeclaration' && want === 'default')
2225
+ found = top.declaration;
2226
+ }
2227
+ /** @param {any} n @param {number} [k] @returns {any} */
2228
+ const unwrapIn = (n, k = 0) => {
2229
+ if (!n || k > 20) return null;
2230
+ if (
2231
+ [
2232
+ 'TSAsExpression',
2233
+ 'TSSatisfiesExpression',
2234
+ 'TSNonNullExpression',
2235
+ 'ParenthesizedExpression',
2236
+ ].includes(n.type)
2237
+ )
2238
+ return unwrapIn(n.expression, k + 1);
2239
+ if (n.type === 'Identifier' && local.has(n.name))
2240
+ return unwrapIn(local.get(n.name), k + 1);
2241
+ return n;
2242
+ };
2243
+ return found
2244
+ ? {obj: unwrapIn(found), code: source, file, unwrap: unwrapIn}
2245
+ : null;
2246
+ } catch {
2247
+ return null;
2248
+ }
2249
+ }
2250
+ return null;
2251
+ };
2252
+ /**
2253
+ * @param {any} node
2254
+ * @param {number} depth
2255
+ * @param {{code: string, file: string | null, unwrap: (n: any) => any}} [at]
2256
+ * the file the node is in (null for the theme file)
2257
+ */
2258
+ const collect = (node, depth, at = {code, file: null, unwrap}) => {
2259
+ const obj = at.unwrap(node);
2260
+ // A name imported from a file beside the theme: read in that file, so
2261
+ // its values and lines are its own; the build still judges the result.
2262
+ if (obj?.type === 'Identifier' && at.file == null) {
2263
+ const from = imported(obj.name);
2264
+ if (from) {
2265
+ unresolved = true;
2266
+ collect(from.obj, depth + 1, from);
2267
+ return;
2268
+ }
2269
+ }
1255
2270
  if (obj?.type !== 'ObjectExpression' || depth > 20) {
1256
2271
  unresolved = true;
1257
2272
  return;
1258
2273
  }
1259
- // Spreads and keys merge in order: a later one wins.
2274
+ // Spreads and keys merge in order: a later one wins. A computed key
2275
+ // that is text (`['--radius-page']`) is read like a literal one.
1260
2276
  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)));
2277
+ if (p.type === 'SpreadElement') collect(p.argument, depth + 1, at);
2278
+ else if (p.type === 'ObjectProperty') {
2279
+ const k = p.computed ? textOf(at.unwrap(p.key)) : keyOf(p.key);
2280
+ if (k?.startsWith('--')) out.set(k, builtText(at.unwrap(p.value)));
2281
+ else if (p.computed) unresolved = true;
2282
+ if (detail && (k || p.computed))
2283
+ detail.push({
2284
+ token: k?.startsWith('--') ? k : null,
2285
+ key: at.code.slice(p.key.start, p.key.end),
2286
+ line: p.loc?.start?.line ?? null,
2287
+ ...(at.file ? {file: at.file} : {}),
2288
+ // A key that is no token name (`color`): the build writes it
2289
+ // as a declaration on the theme's root.
2290
+ ...(k && !k.startsWith('--') ? {notToken: true} : {}),
2291
+ ...valueShape(at.unwrap(p.value), at.unwrap),
2292
+ });
1265
2293
  } else unresolved = true;
1266
2294
  }
1267
2295
  };
2296
+ /**
2297
+ * A token's value as the build writes it, when the file gives it as
2298
+ * text: a [light, dark] pair of two texts is its light-dark(); else
2299
+ * null.
2300
+ * @param {any} node
2301
+ * @returns {string | null}
2302
+ */
2303
+ const builtText = node => {
2304
+ const halves =
2305
+ node?.type === 'ArrayExpression' && node.elements.length === 2
2306
+ ? node.elements.map((/** @type {any} */ e) => textOf(unwrap(e)))
2307
+ : null;
2308
+ return halves && halves.every((/** @type {any} */ h) => h != null)
2309
+ ? `light-dark(${halves.join(', ')})`
2310
+ : textOf(node);
2311
+ };
2312
+ /**
2313
+ * What a token's value is, as written: text, a number, a [light, dark]
2314
+ * pair (each half's text, a number, or undefined), or something else.
2315
+ * @param {any} node
2316
+ * @param {(n: any) => any} [unwrapIn] how the node's file reads a name
2317
+ * @returns {Pick<OwnTokenEntry, 'kind' | 'value' | 'halves'>}
2318
+ */
2319
+ const valueShape = (node, unwrapIn = unwrap) => {
2320
+ const t = textOf(node);
2321
+ if (t != null) return {kind: 'text', value: t};
2322
+ if (node?.type === 'NumericLiteral')
2323
+ return {kind: 'number', value: node.value};
2324
+ if (node?.type === 'ArrayExpression')
2325
+ return {
2326
+ kind: 'pair',
2327
+ halves: node.elements.map((/** @type {any} */ e) => {
2328
+ const h = unwrapIn(e);
2329
+ return (
2330
+ textOf(h) ?? (h?.type === 'NumericLiteral' ? h.value : undefined)
2331
+ );
2332
+ }),
2333
+ };
2334
+ if (node?.type === 'ObjectExpression')
2335
+ return {
2336
+ kind: 'object',
2337
+ value: Object.fromEntries(
2338
+ node.properties
2339
+ .filter((/** @type {any} */ p) => p.type === 'ObjectProperty')
2340
+ .map((/** @type {any} */ p) => [
2341
+ keyOf(p.key) ?? '?',
2342
+ textOf(unwrap(p.value)) ?? null,
2343
+ ]),
2344
+ ),
2345
+ };
2346
+ return {kind: 'other'};
2347
+ };
1268
2348
  collect(tokensProp.value, 0);
2349
+ // Only the last entry for a token is what the build writes: an earlier
2350
+ // one a later key or spread overrides is marked, never judged.
2351
+ if (detail) {
2352
+ /** @type {Map<string, number>} */
2353
+ const last = new Map();
2354
+ /** A page token's entry, from the tokens map the build reads. @param {OwnTokenEntry} e */
2355
+ const page = e => e.token && e.kind !== 'scoped' && e.kind !== 'chain';
2356
+ detail.forEach((e, i) => {
2357
+ if (page(e)) last.set(/** @type {string} */ (e.token), i);
2358
+ });
2359
+ detail.forEach((e, i) => {
2360
+ if (page(e) && last.get(/** @type {string} */ (e.token)) !== i)
2361
+ e.overridden = true;
2362
+ });
2363
+ }
1269
2364
  // A value no read of the file can resolve (a call, an import) is read
1270
2365
  // from the build (ownTokens), and checked again after the next one.
1271
- void unresolved;
2366
+ if (detail && unresolved)
2367
+ detail.push({
2368
+ token: null,
2369
+ key: 'tokens',
2370
+ kind: 'unresolved',
2371
+ line: tokensProp.loc?.start?.line ?? null,
2372
+ });
1272
2373
  return out;
1273
2374
  }
1274
2375
 
@@ -1774,7 +2875,7 @@ export function ownSourceTokenValues(cwd, slug) {
1774
2875
  function scopeProblem(s) {
1775
2876
  if (s.on != null && !/^[a-z][a-z0-9-]*$/.test(s.on))
1776
2877
  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))
2878
+ if (s.state != null && !/^[a-z][a-zA-Z-]*$/.test(s.state))
1778
2879
  return `${s.thing} has state "${s.state}", which is not a state name`;
1779
2880
  if (s.when != null && !/^[\w-]+:[\w.-]+$/.test(s.when))
1780
2881
  return `${s.thing} has --when "${s.when}", which is not prop:value`;
@@ -1787,7 +2888,10 @@ function scopeProblem(s) {
1787
2888
  export const keyOf = s =>
1788
2889
  [
1789
2890
  s.thing,
1790
- s.axis ?? '',
2891
+ // A headings value saved with no axis is its weight half, as the build
2892
+ // reads it, so a set or undo of the weight replaces it. Only headings
2893
+ // has halves: an axis on any other setting names nothing.
2894
+ s.thing === 'headings' ? (s.axis ?? 'weight') : '',
1791
2895
  s.on ?? '',
1792
2896
  s.when ?? '',
1793
2897
  s.state ?? '',
@@ -1823,6 +2927,22 @@ export function partsOf(ctx, s) {
1823
2927
 
1824
2928
  export {modesOf};
1825
2929
 
2930
+ /**
2931
+ * A corners value in the plain form the editor saves, typed or saved: a
2932
+ * rung in any case is that rung; a size in px or rem, any way a CSS number
2933
+ * is written, is that many px (a rem is 16px; 1000px and more is pill).
2934
+ * Null for any other value.
2935
+ * @param {string} v
2936
+ * @returns {string | null}
2937
+ */
2938
+ export function cornersPlain(v) {
2939
+ const lower = String(v).trim().toLowerCase();
2940
+ if (CORNERS.some(([n]) => n === lower)) return lower;
2941
+ const px = /\d(px|rem)$/.test(lower) ? lengthPx(lower) : null;
2942
+ if (px == null || px < 0) return null;
2943
+ return px >= 1000 ? 'pill' : `${Math.round(px * 10000) / 10000}px`;
2944
+ }
2945
+
1826
2946
  /**
1827
2947
  * A length in pixels: px as given, rem and em at 16px; null for anything
1828
2948
  * else (a percentage, calc(), a word).
@@ -1843,6 +2963,18 @@ export function lengthPx(v) {
1843
2963
  /** @param {string} v */
1844
2964
  export const cornerPx = v =>
1845
2965
  CORNERS.find(([n]) => n === v)?.[1] ?? parseFloat(v);
2966
+ /**
2967
+ * The base theme's body text size in px, read back from its built base
2968
+ * size (14 when it writes none).
2969
+ * @param {{light: Record<string, string>}} base
2970
+ */
2971
+ export function baseTextPx(base) {
2972
+ const v = base?.light?.['--font-size-base'];
2973
+ return /^[\d.]+rem$/.test(v ?? '')
2974
+ ? Math.round(Number.parseFloat(String(v)) * 16)
2975
+ : 14;
2976
+ }
2977
+
1846
2978
  /** @param {string} v */
1847
2979
  export const textPx = v => TEXT_SIZE.find(([n]) => n === v)?.[1] ?? Number(v);
1848
2980
 
@@ -1925,8 +3057,7 @@ export function cssFamily(name, spaced = false) {
1925
3057
  }
1926
3058
 
1927
3059
  /**
1928
- * What a part reads for a property when the theme does not set it, so a
1929
- * one-mode component setting keeps the other mode as it was.
3060
+ * What a part reads for a property when the theme does not set it.
1930
3061
  * @param {Ctx} ctx
1931
3062
  * @param {string} target
1932
3063
  * @param {string} prop camelCase or kebab-case
@@ -1959,6 +3090,44 @@ function partDefault(ctx, target, prop, when, state) {
1959
3090
  return r ? `var(${r.token})` : null;
1960
3091
  }
1961
3092
 
3093
+ /**
3094
+ * The variants (`variant:<name>`) of a part that each read their own value
3095
+ * of a color property (the button's background, a badge's text), in a
3096
+ * state when one is named and changes it: one rule's other-mode half would
3097
+ * give every one of them one variant's color. Empty when the part reads one
3098
+ * value for all.
3099
+ * @param {Ctx} ctx
3100
+ * @param {string} target
3101
+ * @param {string} prop camelCase or kebab-case
3102
+ * @param {string} [state]
3103
+ * @returns {string[]}
3104
+ */
3105
+ function variantsReading(ctx, target, prop, state) {
3106
+ const k = kebab(prop);
3107
+ const g = ctx.C.groupOfProp(k === 'background' ? 'background-color' : k);
3108
+ if (!g) return [];
3109
+ const reads = ctx.C.partReads(target, g).filter(x =>
3110
+ x.props.some(
3111
+ p => p === k || (k === 'background' && p === 'background-color'),
3112
+ ),
3113
+ );
3114
+ const named = (/** @type {(w: string) => boolean} */ ok) => [
3115
+ ...new Set(
3116
+ reads
3117
+ .flatMap(x => x.when)
3118
+ .filter(ok)
3119
+ .map(w => /(?:^|,)variant=([\w-]+)/.exec(w)?.[1])
3120
+ .filter(Boolean)
3121
+ .map(n => `variant:${n}`),
3122
+ ),
3123
+ ];
3124
+ const inState = state ? named(w => w.includes(`:${state}`)) : [];
3125
+ if (inState.length) return inState;
3126
+ return reads.some(x => x.when.includes(''))
3127
+ ? []
3128
+ : named(w => /^variant=[\w-]+$/.test(w));
3129
+ }
3130
+
1962
3131
  /** The line that records a generated module's own hash. */
1963
3132
  const SEAL = /^\/\/ Module ([0-9a-f]{16})\.\n/m;
1964
3133
 
@@ -1986,6 +3155,37 @@ export function sourceChangedReason(slug) {
1986
3155
  /** The type tokens base themes set again for phones: families and weights. */
1987
3156
  export const PHONE_TYPE = /^--font-family|^--(text-[a-z0-9-]+|font)-weight/;
1988
3157
 
3158
+ /**
3159
+ * The tokens the theme's last build sets for touch screens (in its rules
3160
+ * for a coarse pointer), each with the last value it is given there.
3161
+ * @param {string} cwd
3162
+ * @param {string} slug
3163
+ * @returns {Map<string, string>}
3164
+ */
3165
+ export function builtTouchTokens(cwd, slug) {
3166
+ /** @type {Map<string, string>} */
3167
+ const out = new Map();
3168
+ try {
3169
+ postcss
3170
+ .parse(fs.readFileSync(themeFiles(cwd, slug).css, 'utf8'))
3171
+ .walkAtRules('media', rule => {
3172
+ if (!/pointer\s*:\s*coarse/i.test(rule.params)) return;
3173
+ rule.walkDecls(/^--/, decl => {
3174
+ out.set(decl.prop, decl.value);
3175
+ });
3176
+ });
3177
+ } catch {
3178
+ // Not built, or not readable: nothing known.
3179
+ }
3180
+ return out;
3181
+ }
3182
+
3183
+ /**
3184
+ * The screens a base theme's type rule is for (touch screens below the
3185
+ * large breakpoint), as an adaptation rule's `when` writes them.
3186
+ */
3187
+ export const PHONE_RULE_WHEN = {pointer: 'coarse', width: {below: 'lg'}};
3188
+
1989
3189
  /**
1990
3190
  * Record in an editor theme's generated settings that they were built with
1991
3191
  * its own source as it is now, after `compile` built that source (the
@@ -2101,6 +3301,138 @@ function keepShades(pal, kept) {
2101
3301
  return {...pal, tokens, lift: kept['lifted parts'] ? pal.lift : null};
2102
3302
  }
2103
3303
 
3304
+ /**
3305
+ * A size in px: px, rem (16px each), or a calc() of those added and
3306
+ * subtracted; null for anything else.
3307
+ * @param {string} v
3308
+ * @param {Record<string, string>} [vars] values for the tokens a var() may name
3309
+ * @returns {number | null}
3310
+ */
3311
+ export function sizePx(v, vars = {}) {
3312
+ let t = String(v).trim();
3313
+ // A token the dial or the theme gives a value (var(--spacing-12)),
3314
+ // through that value; a clamp() at its preferred value held to its
3315
+ // bounds, or its upper bound when the preferred one is no length;
3316
+ // min() and max() of the lengths they hold.
3317
+ const fn = /^(var|clamp|min|max)\((.*)\)$/is.exec(t);
3318
+ if (fn) {
3319
+ const args = splitTop(fn[2], ',').map(x => x.trim());
3320
+ if (fn[1].toLowerCase() === 'var') {
3321
+ const own = vars[args[0]];
3322
+ if (own != null) return sizePx(own, vars);
3323
+ return args[1] != null ? sizePx(args.slice(1).join(','), vars) : null;
3324
+ }
3325
+ const n = args.map(x => sizePx(x, vars));
3326
+ if (fn[1].toLowerCase() === 'clamp') {
3327
+ const [lo, mid, hi] = n;
3328
+ if (lo == null || hi == null) return null;
3329
+ return mid == null ? hi : Math.min(hi, Math.max(lo, mid));
3330
+ }
3331
+ const known = /** @type {number[]} */ (n.filter(x => x != null));
3332
+ if (!known.length) return null;
3333
+ return fn[1].toLowerCase() === 'min'
3334
+ ? Math.min(...known)
3335
+ : Math.max(...known);
3336
+ }
3337
+ const calc = /^calc\((.*)\)$/is.exec(t);
3338
+ if (calc) t = calc[1].trim();
3339
+ const terms =
3340
+ t.match(/[+-]?\s*[\d.]+(?:px|rem|em|pt|pc|in|cm|mm|q)\b|\S+/gi) ?? [];
3341
+ let sum = 0;
3342
+ let sign = 1;
3343
+ for (const raw of terms) {
3344
+ const x = raw.replace(/\s+/g, '');
3345
+ if (x === '+' || x === '-') {
3346
+ if (!calc) return null;
3347
+ sign = x === '-' ? -1 : 1;
3348
+ continue;
3349
+ }
3350
+ const m = /^([+-]?)([\d.]+)(px|rem|em|pt|pc|in|cm|mm|q)$/i.exec(x);
3351
+ if (!m || (!calc && terms.length > 1)) return null;
3352
+ // Absolute units by their fixed ratio to px; em and rem against the
3353
+ // 16px a control's text starts from.
3354
+ const n = parseFloat(m[2]) * (PX_PER[m[3].toLowerCase()] ?? 1);
3355
+ if (!Number.isFinite(n)) return null;
3356
+ sum += (m[1] === '-' ? -1 : 1) * sign * n;
3357
+ sign = 1;
3358
+ }
3359
+ return terms.length ? sum : null;
3360
+ }
3361
+
3362
+ /** Pixels per unit of each length unit a kept size may be written in. */
3363
+ const PX_PER = /** @type {Record<string, number>} */ ({
3364
+ px: 1,
3365
+ rem: 16,
3366
+ em: 16,
3367
+ pt: 96 / 72,
3368
+ pc: 16,
3369
+ in: 96,
3370
+ cm: 96 / 2.54,
3371
+ mm: 96 / 25.4,
3372
+ q: 96 / 101.6,
3373
+ });
3374
+
3375
+ /**
3376
+ * Spacing steps scaled with the spacing dial, kept in order around the
3377
+ * steps the theme keeps exact: each the plain scaled value unless it would
3378
+ * meet or pass a kept one; those are spread evenly between the kept one and
3379
+ * the nearest step that keeps its place. A step with no room below a kept
3380
+ * one takes the value of the one below it.
3381
+ * @param {Array<[string, number]>} steps token name and the base value, in px
3382
+ * @param {number} f the rung's factor
3383
+ * @param {Record<string, number>} kept exact steps the theme keeps, in px
3384
+ * @param {string[]} [noRoom] filled with the steps left no room
3385
+ * @returns {Array<[string, number]>} every step's new value in px, kept ones as kept
3386
+ */
3387
+ export function spacingSteps(steps, f, kept, noRoom = []) {
3388
+ const px = [...steps].sort((a, b) => a[1] - b[1]);
3389
+ const n = px.map(([k, v]) => (k in kept ? kept[k] : v * f));
3390
+ const isKept = (/** @type {number} */ i) => px[i][0] in kept;
3391
+ px.forEach(([, base], k) => {
3392
+ if (!isKept(k)) return;
3393
+ // The steps below that would meet or pass it are spread evenly between
3394
+ // the last one that does not and it.
3395
+ let j0 = k;
3396
+ while (
3397
+ j0 > 0 &&
3398
+ !isKept(j0 - 1) &&
3399
+ n[j0 - 1] >= n[k] &&
3400
+ px[j0 - 1][1] < base
3401
+ )
3402
+ j0--;
3403
+ if (j0 < k) {
3404
+ const lo = j0 > 0 ? n[j0 - 1] : 0;
3405
+ if (lo >= n[k])
3406
+ for (let j = j0; j < k; j++) {
3407
+ n[j] = lo;
3408
+ noRoom.push(px[j][0]);
3409
+ }
3410
+ else
3411
+ for (let j = j0; j < k; j++)
3412
+ n[j] = lo + ((n[k] - lo) * (j - j0 + 1)) / (k - j0 + 1);
3413
+ }
3414
+ // The steps above that would meet or fall under it, likewise up to the
3415
+ // next one that does not (or above it by their own scaled steps).
3416
+ let j1 = k;
3417
+ while (
3418
+ j1 < n.length - 1 &&
3419
+ !isKept(j1 + 1) &&
3420
+ n[j1 + 1] <= n[k] &&
3421
+ px[j1 + 1][1] > base
3422
+ )
3423
+ j1++;
3424
+ if (j1 > k) {
3425
+ const hi = j1 < n.length - 1 ? n[j1 + 1] : null;
3426
+ for (let j = k + 1; j <= j1; j++)
3427
+ n[j] =
3428
+ hi == null
3429
+ ? n[k] + (px[j][1] - base) * f
3430
+ : n[k] + ((hi - n[k]) * (j - k)) / (j1 - k + 1);
3431
+ }
3432
+ });
3433
+ return px.map(([k], i) => [k, n[i]]);
3434
+ }
3435
+
2104
3436
  /**
2105
3437
  * Control heights scaled with the spacing dial (a denser theme has shorter
2106
3438
  * controls), each kept distinct and in order: smallest to largest, a
@@ -2110,28 +3442,44 @@ function keepShades(pal, kept) {
2110
3442
  * scaled above it.
2111
3443
  * @param {Array<[string, string]>} sizes token name and the theme's value
2112
3444
  * @param {number} f the spacing rung's factor
3445
+ * @param {Record<string, number>} [kept] exact sizes the theme keeps, in px,
3446
+ * which the others stay in order around
3447
+ * @param {string[]} [noRoom] filled with the sizes left no room between
3448
+ * two kept ones (each then equals the one below it)
2113
3449
  * @returns {Array<[string, string]>} the tokens it writes, in px
2114
3450
  */
2115
- export function controlSizes(sizes, f) {
3451
+ export function controlSizes(sizes, f, kept = {}, noRoom = []) {
2116
3452
  const px = sizes
2117
3453
  .filter(([, v]) => /^[\d.]+px$/.test(String(v).trim()))
2118
3454
  .map(([k, v]) => /** @type {[string, number]} */ ([k, parseFloat(v)]))
2119
3455
  .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;
3456
+ /** @type {number[]} */
3457
+ const n = px.map(([k, v]) =>
3458
+ k in kept ? kept[k] : Math.max(Math.min(24, v), Math.round(v * f)),
3459
+ );
3460
+ /** The step between two sizes, scaled. @param {number} i */
3461
+ const step = i => Math.max(1, Math.round((px[i][1] - px[i - 1][1]) * f));
3462
+ // Only a size that would meet (or pass) the one below moves, up; then one
3463
+ // that would meet a kept size above it moves down (a kept size stays).
3464
+ for (let i = 1; i < n.length; i++)
3465
+ if (!(px[i][0] in kept) && n[i] <= n[i - 1]) n[i] = n[i - 1] + step(i);
3466
+ for (let i = n.length - 2; i >= 0; i--)
3467
+ if (!(px[i][0] in kept) && n[i] >= n[i + 1]) n[i] = n[i + 1] - step(i + 1);
3468
+ // A size between two that cannot both move (kept, or one kept and the
3469
+ // other already at its place) sits halfway between them; with no room
3470
+ // between them it takes the smaller one's size, and the result says so.
3471
+ for (let i = 1; i < n.length - 1; i++)
3472
+ if (!(px[i][0] in kept) && (n[i] <= n[i - 1] || n[i] >= n[i + 1])) {
3473
+ const mid = Math.round(((n[i - 1] + n[i + 1]) / 2) * 2) / 2;
3474
+ if (mid > n[i - 1] && mid < n[i + 1]) n[i] = mid;
3475
+ else {
3476
+ n[i] = n[i - 1];
3477
+ noRoom.push(px[i][0]);
3478
+ }
3479
+ }
3480
+ return px
3481
+ .map(([k], i) => /** @type {[string, string]} */ ([k, `${n[i]}px`]))
3482
+ .filter(([k]) => !(k in kept));
2135
3483
  }
2136
3484
 
2137
3485
  /**
@@ -2142,6 +3490,8 @@ export function controlSizes(sizes, f) {
2142
3490
  * @returns {any}
2143
3491
  */
2144
3492
  export function compileTheme(ctx, data, base) {
3493
+ ctx.sizeNotes = [];
3494
+ ctx.compileNotes = [];
2145
3495
  // A setting the editor no longer accepts never reaches the build.
2146
3496
  data = {...data, settings: data.settings.filter(s => !valueProblem(s))};
2147
3497
  const TOKENS = ctx.project.core.tokenDefaults;
@@ -2153,7 +3503,7 @@ export function compileTheme(ctx, data, base) {
2153
3503
  rem(base.light['--font-size-base']),
2154
3504
  rem(base.light['--font-size-2xl']),
2155
3505
  ];
2156
- const baseSize = b0 ? Math.round(b0 * 16) : 14;
3506
+ const baseSize = baseTextPx(base);
2157
3507
  const baseRatio =
2158
3508
  b0 && b3 ? Math.round((b3 / b0) ** (1 / 3) * 100) / 100 : 1.2;
2159
3509
  /** @type {any} */
@@ -2164,6 +3514,42 @@ export function compileTheme(ctx, data, base) {
2164
3514
  : data.mode === 'dark-only'
2165
3515
  ? 'dark'
2166
3516
  : null;
3517
+ /** The tokens the theme's own source sets, which win over the settings. */
3518
+ /** @type {Record<string, string> | null} */
3519
+ let ownTok = null;
3520
+ const ownTokenValues = () => {
3521
+ if (ownTok) return ownTok;
3522
+ try {
3523
+ ownTok = ownSourceTokenValues(ctx.project.cwd, data.name);
3524
+ } catch {
3525
+ ownTok = {};
3526
+ }
3527
+ return ownTok;
3528
+ };
3529
+ /**
3530
+ * The exact tokens kept where a dial writes (whole theme with no part):
3531
+ * the whole-theme settings', then the own source's, by name.
3532
+ * @param {string | null} t a part, for its own settings too
3533
+ * @returns {Map<string, string>}
3534
+ */
3535
+ const keptTokens = t => {
3536
+ /** @type {Map<string, string>} */
3537
+ const out = new Map();
3538
+ for (const x of data.settings)
3539
+ if (
3540
+ x.source === 'token' &&
3541
+ !x.when &&
3542
+ !x.state &&
3543
+ !(modeOnly && x.mode && x.mode !== modeOnly) &&
3544
+ (!x.on || (t != null && partsOf(ctx, x).includes(t)))
3545
+ )
3546
+ out.set(x.thing, String(x.value));
3547
+ for (const [k, v] of Object.entries(ownTokenValues())) out.set(k, v);
3548
+ return out;
3549
+ };
3550
+ /** @param {string | null} t */
3551
+ const keptSizes = t =>
3552
+ [...keptTokens(t)].filter(([k]) => /^--size-element-/.test(k));
2167
3553
  /** @type {Record<string, {light?: string, dark?: string}>} */
2168
3554
  const tok = {};
2169
3555
  /** @param {string} name @param {string | [string, string]} v @param {string} [mode] */
@@ -2177,12 +3563,22 @@ export function compileTheme(ctx, data, base) {
2177
3563
  if (!mode || mode === 'dark') t.dark = v[1];
2178
3564
  return;
2179
3565
  }
2180
- if (!MODAL.has(ctx.C.typeOf(name)) || modeOnly || !mode) {
3566
+ // A color set in a one-mode theme fills its mode's half only; the other
3567
+ // half keeps what it had (the base theme's), for the regions Core draws
3568
+ // in the other mode.
3569
+ const half = mode ?? modeOnly;
3570
+ // Only a color has a half per mode (light-dark() takes colors only): a
3571
+ // shadow or any other value in a one-mode theme is written whole.
3572
+ if (
3573
+ !MODAL.has(ctx.C.typeOf(name)) ||
3574
+ !half ||
3575
+ (!mode && !parseColor(String(v).trim()))
3576
+ ) {
2181
3577
  t.light = v;
2182
3578
  t.dark = v;
2183
3579
  return;
2184
3580
  }
2185
- t[/** @type {'light' | 'dark'} */ (mode)] = v;
3581
+ t[/** @type {'light' | 'dark'} */ (half)] = v;
2186
3582
  };
2187
3583
  /** @param {Setting} s @param {string} target @returns {Record<string, any>} */
2188
3584
  const block = (s, target) => {
@@ -2197,6 +3593,29 @@ export function compileTheme(ctx, data, base) {
2197
3593
  }
2198
3594
  return b;
2199
3595
  };
3596
+ /**
3597
+ * A setting's rule block for one color mode: the style key's `@light` or
3598
+ * `@dark` block, with the state inside it for a state Core writes as a
3599
+ * pseudo-class.
3600
+ * @param {Setting} s @param {string} target @param {'light' | 'dark'} mode
3601
+ * @returns {Record<string, any>}
3602
+ */
3603
+ const modeBlock = (s, target, mode) => {
3604
+ const t = (theme.components[target] ??= {});
3605
+ const tg = ctx.project.target.get(target);
3606
+ const state = s.state;
3607
+ const ownState = !!state && !!tg?.states.includes(state);
3608
+ const key =
3609
+ state && ownState
3610
+ ? s.when == null
3611
+ ? state
3612
+ : `${s.when}+${state}`
3613
+ : (s.when ?? 'base');
3614
+ const rule = (t[key] ??= {});
3615
+ const mb = (rule[`@${mode}`] ??= {});
3616
+ if (!state || ownState) return mb;
3617
+ return (mb[stateKey(state, wrapsOneControl(ctx, target))] ??= {});
3618
+ };
2200
3619
  /**
2201
3620
  * A padding on a part whose padding Core writes one variable per side
2202
3621
  * (its derivedVarRegistry's container expansion), as each side's value,
@@ -2302,6 +3721,34 @@ export function compileTheme(ctx, data, base) {
2302
3721
  ]),
2303
3722
  );
2304
3723
  };
3724
+ /**
3725
+ * A part's shadow with the layers Core composes its own shadow from (the
3726
+ * private variables in its resting declaration), over the theme's; a
3727
+ * shadow of none keeps those layers alone. Any other part's is as given.
3728
+ * @param {string} target @param {string} v
3729
+ */
3730
+ const withCoreShadowLayers = (target, v) => {
3731
+ const at = ctx.C.MAP[target]?.at?.['box-shadow'] ?? {};
3732
+ const rest = Object.entries(at).find(([k]) => !/:|selected=/.test(k))?.[1];
3733
+ const layers = splitTop(String(rest ?? ''), ',')
3734
+ .map(x => x.trim())
3735
+ .filter(x => /^var\(\s*--_/.test(x));
3736
+ const value = String(v).trim();
3737
+ if (!layers.length || layers.every(l => value.includes(l))) return v;
3738
+ return /^none$/i.test(value)
3739
+ ? layers.join(', ')
3740
+ : `${layers.join(', ')}, ${value}`;
3741
+ };
3742
+ /** Whether the base theme's own rule for the part writes a radius. */
3743
+ const baseWritesRadius = (
3744
+ /** @type {string} */ target,
3745
+ /** @type {string | undefined} */ when,
3746
+ ) => {
3747
+ const rules = /** @type {any} */ (base).components?.[target] ?? {};
3748
+ return [rules.base, when ? rules[when] : undefined].some(
3749
+ r => r && typeof r === 'object' && 'borderRadius' in r,
3750
+ );
3751
+ };
2305
3752
  /**
2306
3753
  * A radius of more than one value on a part whose radius Core copies
2307
3754
  * into a variable for the content inside it (a card's full-bleed
@@ -2471,9 +3918,11 @@ export function compileTheme(ctx, data, base) {
2471
3918
  return n && n.unit === '' && n.value === 0 ? '0px' : v;
2472
3919
  };
2473
3920
  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;
3921
+ // The own source's padding on the same rule wins over the editor's on
3922
+ // the sides it sets (the result says so); the editor's other sides
3923
+ // still apply.
3924
+ const own = ownBox(target, s);
3925
+ if (own.ltr.size === 4 && own.rtl.size === 4) continue;
2477
3926
  const prefix = /** @type {string} */ (padVars(target));
2478
3927
  const owner = prefix.slice('--astryx-'.length, -'-padding'.length);
2479
3928
  const scoped = target !== owner || s.when != null || s.state != null;
@@ -2517,6 +3966,10 @@ export function compileTheme(ctx, data, base) {
2517
3966
  }
2518
3967
  }
2519
3968
  }
3969
+ // The sides the own source pads in a direction are its own there.
3970
+ for (const dir of /** @type {const} */ (['ltr', 'rtl']))
3971
+ for (const x of Object.keys(side[dir]))
3972
+ if (own[dir].has(boxSide(x, dir))) delete side[dir][x];
2520
3973
  /** @type {Record<string, string>} */
2521
3974
  let plain = {};
2522
3975
  /** @type {Record<string, string>} */
@@ -2586,6 +4039,78 @@ export function compileTheme(ctx, data, base) {
2586
4039
  b[key] = {...(b[key] ?? {}), ...rule};
2587
4040
  }
2588
4041
  }
4042
+ // A variant the own source pads: the sides it sets are left without a
4043
+ // side variable there, so the variant's own padding (which Core writes
4044
+ // as the whole padding) wins over any side the plain rule writes.
4045
+ for (const owner of new Set(
4046
+ [...padQueue.values()]
4047
+ .filter(({target, s}) => !s.when && !s.state && padVars(target))
4048
+ .map(({target}) =>
4049
+ /** @type {string} */ (padVars(target)).slice(
4050
+ '--astryx-'.length,
4051
+ -'-padding'.length,
4052
+ ),
4053
+ ),
4054
+ )) {
4055
+ const values = ctx.C.variantValues(owner);
4056
+ for (const [prop, vals] of Object.entries(values ?? {}))
4057
+ for (const v of /** @type {string[]} */ (vals ?? [])) {
4058
+ const when = `${prop}:${v}`;
4059
+ const own = ownBox(owner, /** @type {any} */ ({when}));
4060
+ if (!own.ltr.size && !own.rtl.size) continue;
4061
+ const variant = /** @type {any} */ ({when});
4062
+ const logical = [
4063
+ 'block-start',
4064
+ 'block-end',
4065
+ 'inline-start',
4066
+ 'inline-end',
4067
+ ];
4068
+ const at = (/** @type {'ltr' | 'rtl'} */ dir) =>
4069
+ logical.filter(x => own[dir].has(boxSide(x, dir)));
4070
+ const [l, r] = [at('ltr'), at('rtl')];
4071
+ const b = block(variant, owner);
4072
+ for (const x of l.filter(x => r.includes(x)))
4073
+ b[`--astryx-${owner}-padding-${x}`] ??= 'initial';
4074
+ // A pair variable the plain rule writes (the inline or block
4075
+ // padding) feeds both its sides, under the side variables: where
4076
+ // the own source pads both, it is left without a value too, so
4077
+ // the variant's own padding holds there.
4078
+ for (const pair of ['block', 'inline'])
4079
+ if (
4080
+ [`${pair}-start`, `${pair}-end`].every(
4081
+ x => l.includes(x) && r.includes(x),
4082
+ )
4083
+ )
4084
+ b[`--astryx-${owner}-padding-${pair}`] ??= 'initial';
4085
+ // Its own sides inherit into a plain one of the part inside it:
4086
+ // they are reset there like the editor's (below).
4087
+ const sel = narrowSelector(owner, variant);
4088
+ if (sel) {
4089
+ const bySel = narrow.get(owner) ?? new Map();
4090
+ const names = bySel.get(sel) ?? new Set();
4091
+ for (const x of new Set([...l, ...r]))
4092
+ names.add(`--astryx-${owner}-padding-${x}`);
4093
+ for (const pair of ['block', 'inline'])
4094
+ if ([...l, ...r].some(x => x.startsWith(pair)))
4095
+ names.add(`--astryx-${owner}-padding-${pair}`);
4096
+ bySel.set(sel, names);
4097
+ narrow.set(owner, bySel);
4098
+ }
4099
+ for (const [dir, xs] of /** @type {const} */ ([
4100
+ [':dir(ltr)', l.filter(x => !r.includes(x))],
4101
+ [':dir(rtl)', r.filter(x => !l.includes(x))],
4102
+ ]))
4103
+ if (xs.length) {
4104
+ const [db, key] = dirBlock(variant, owner, dir);
4105
+ db[key] = {
4106
+ ...(db[key] ?? {}),
4107
+ ...Object.fromEntries(
4108
+ xs.map(x => [`--astryx-${owner}-padding-${x}`, 'initial']),
4109
+ ),
4110
+ };
4111
+ }
4112
+ }
4113
+ }
2589
4114
  // A plain part inside a narrower one: each side the narrower selector
2590
4115
  // writes is reset (left without a value, so Core's own fallback holds),
2591
4116
  // on the part's own class at its own weight, before any base setting a
@@ -2668,25 +4193,66 @@ export function compileTheme(ctx, data, base) {
2668
4193
  return out;
2669
4194
  };
2670
4195
  /**
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).
4196
+ * The box side a padding side names in a direction: a physical side as it
4197
+ * is, a logical one as the direction reads it (inline-start is the left in
4198
+ * left-to-right text, the right in right-to-left).
4199
+ * @param {string} x top, right, bottom, left, or a logical side
4200
+ * @param {'ltr' | 'rtl'} dir
4201
+ */
4202
+ const boxSide = (x, dir) =>
4203
+ ({
4204
+ 'block-start': 'top',
4205
+ 'block-end': 'bottom',
4206
+ 'inline-start': dir === 'ltr' ? 'left' : 'right',
4207
+ 'inline-end': dir === 'ltr' ? 'right' : 'left',
4208
+ })[x] ?? x;
4209
+ /**
4210
+ * The padding sides a padding property names, as it names them (physical
4211
+ * stays physical, logical stays logical), with each one's value.
4212
+ * @param {string} prop kebab-case
4213
+ * @param {string} value
4214
+ * @returns {Record<string, string>}
4215
+ */
4216
+ const paddingSides = (prop, value) => {
4217
+ const w = splitTop(String(value).trim(), ' ').map(y => y.trim());
4218
+ if (prop === 'padding') {
4219
+ const [top, right = top, bottom = top, left = right] = w;
4220
+ return {top, right, bottom, left};
4221
+ }
4222
+ if (prop === 'padding-block')
4223
+ return {'block-start': w[0], 'block-end': w[1] ?? w[0]};
4224
+ if (prop === 'padding-inline')
4225
+ return {'inline-start': w[0], 'inline-end': w[1] ?? w[0]};
4226
+ const side = prop.slice('padding-'.length);
4227
+ return /^(top|right|bottom|left|(block|inline)-(start|end))$/.test(side)
4228
+ ? {[side]: w[0]}
4229
+ : {};
4230
+ };
4231
+ /**
4232
+ * The box sides the theme's own source pads on a part's rule for a scope
4233
+ * (its plain rule, a variant, a state), in each direction.
2673
4234
  * @param {string} target @param {Setting} s
4235
+ * @returns {Record<'ltr' | 'rtl', Set<string>>}
2674
4236
  */
2675
- const ownPads = (target, s) => {
4237
+ const ownBox = (target, s) => {
4238
+ const out = {ltr: new Set(), rtl: new Set()};
2676
4239
  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));
4240
+ for (const k of ownPartTokens(
4241
+ ctx.project.cwd,
4242
+ data.name,
4243
+ target,
4244
+ s.when ?? 'base',
4245
+ s.state ? `:${s.state}` : null,
4246
+ ).keys())
4247
+ for (const x of Object.keys(paddingSides(k, '0')))
4248
+ for (const dir of /** @type {const} */ (['ltr', 'rtl']))
4249
+ out[dir].add(boxSide(x, dir));
2686
4250
  } catch {
2687
- return false;
4251
+ // No own source.
2688
4252
  }
4253
+ return out;
2689
4254
  };
4255
+
2690
4256
  /**
2691
4257
  * The selector a narrower padding scope is written with (a clickable
2692
4258
  * card's class, a variant's attribute, a state's pseudo-class), or null
@@ -2712,11 +4278,18 @@ export function compileTheme(ctx, data, base) {
2712
4278
  const keys = Object.keys(b);
2713
4279
  const plain = keys.filter(k => !k.startsWith(':'));
2714
4280
  const dirs = keys.filter(k => /^:(where\()?dir\(/.test(k));
4281
+ // The reset a plain part inside a narrower one gets comes before the
4282
+ // part's own direction rules at the same weight, so a side the part
4283
+ // sets for a direction holds inside a variant too.
4284
+ const resets = keys.filter(k => /^:where\((?!:?dir\().* \*\)$/.test(k));
2715
4285
  const rest = keys.filter(
2716
- k => k.startsWith(':') && !/^:(where\()?dir\(/.test(k),
4286
+ k =>
4287
+ k.startsWith(':') &&
4288
+ !/^:(where\()?dir\(/.test(k) &&
4289
+ !resets.includes(k),
2717
4290
  );
2718
4291
  return Object.fromEntries(
2719
- [...plain, ...dirs, ...rest].map(k => [
4292
+ [...plain, ...resets, ...dirs, ...rest].map(k => [
2720
4293
  k,
2721
4294
  k.startsWith(':') && b[k] && typeof b[k] === 'object'
2722
4295
  ? dirFirst(b[k])
@@ -2767,49 +4340,234 @@ export function compileTheme(ctx, data, base) {
2767
4340
  const parent = block({...s, state: undefined}, target);
2768
4341
  return [parent, `${stateKey(s.state, wrapsOneControl(ctx, target))}${dir}`];
2769
4342
  };
4343
+ /**
4344
+ * One half of a light-dark() pair (1 light, 2 dark), or the value itself.
4345
+ * @param {string} x @param {1 | 2} side
4346
+ */
4347
+ const halfOf = (x, side) => {
4348
+ const inner = /^light-dark\((.*)\)$/s.exec(x.trim())?.[1];
4349
+ const halves = inner == null ? [] : splitTop(inner, ',');
4350
+ return halves.length === 2 ? halves[side - 1].trim() : x.trim();
4351
+ };
4352
+ /**
4353
+ * The value a variant of a part shows for a color property where the
4354
+ * theme sets none of its own: the base theme's rule for that variant (in
4355
+ * the state, else at rest), else Core's, else transparent for a
4356
+ * background Core never paints; null for a text color Core never sets.
4357
+ * @param {string} target @param {string} css a color longhand, kebab-case
4358
+ * @param {string} name the variant @param {string} [state]
4359
+ * @param {boolean} [stateOnly] the state's own value only, never the resting one
4360
+ * @returns {string | null}
4361
+ */
4362
+ const exactVariantValue = (target, css, name, state, stateOnly = false) => {
4363
+ const when = `variant:${name}`;
4364
+ const kebabs =
4365
+ css === 'background-color' ? ['background-color', 'background'] : [css];
4366
+ const props = kebabs.map(camel);
4367
+ const steps = state
4368
+ ? stateOnly
4369
+ ? [state]
4370
+ : [state, undefined]
4371
+ : [undefined];
4372
+ for (const st of steps)
4373
+ for (const p of props) {
4374
+ const b = baseComponent(base, ctx, target, p, {when, state: st});
4375
+ if (b != null) return b;
4376
+ }
4377
+ const keyOf = (/** @type {string} */ k) => {
4378
+ const [attrs, cond = ''] = k.split(' ');
4379
+ return attrs.split(',').includes(`variant=${name}`) ? cond : null;
4380
+ };
4381
+ for (const st of steps)
4382
+ for (const p of kebabs) {
4383
+ const at = ctx.C.MAP[target]?.at?.[p];
4384
+ for (const [k, val] of Object.entries(at ?? {})) {
4385
+ const cond = keyOf(k);
4386
+ if (cond == null) continue;
4387
+ if (st ? cond.includes(`:${st}`) : cond === '') return val;
4388
+ }
4389
+ }
4390
+ if (stateOnly) return null;
4391
+ return css === 'background-color'
4392
+ ? 'transparent'
4393
+ : css === 'color'
4394
+ ? null
4395
+ : 'currentcolor';
4396
+ };
4397
+ /** The family a color property belongs to: background is background-color. @param {string} p */
4398
+ const colorFamily = p => {
4399
+ const k = kebab(p);
4400
+ return k === 'background' ? 'background-color' : k;
4401
+ };
2770
4402
  /** @param {Setting} s @param {string} target @param {string} prop @param {string} v */
2771
4403
  const putComp = (s, target, prop, v) => {
4404
+ // A shadow on a part whose shadow Core composes from layers of its own
4405
+ // (a card's selection ring and elevation) keeps those layers over the
4406
+ // theme's: the theme's shadow is one more layer, never a list that
4407
+ // drops the ring.
4408
+ if (kebab(prop) === 'box-shadow') v = withCoreShadowLayers(target, v);
2772
4409
  const b = block(s, target);
2773
- if (s.mode && !modeOnly) {
2774
- const prev = b[prop];
2775
- // The other mode keeps exactly what it had: the value set for it, the
2776
- // part's own, else what the property shows unset (light-dark() takes
2777
- // colors only, so never inherit).
2778
- const other =
2779
- prev ??
2780
- baseComponent(base, ctx, target, prop, s) ??
2781
- partDefault(ctx, target, prop, s.when, s.state) ??
2782
- (s.state
2783
- ? baseComponent(base, ctx, target, prop, {...s, state: undefined})
2784
- : null) ??
2785
- partDefault(ctx, target, prop, s.when) ??
2786
- (/^background/.test(kebab(prop)) ? 'transparent' : 'currentcolor');
2787
- // At the top-level comma: a mode's color may hold commas itself.
2788
- const split = (/** @type {string} */ x, /** @type {1 | 2} */ side) => {
2789
- const inner = /^light-dark\((.*)\)$/s.exec(x.trim())?.[1];
2790
- const halves = inner == null ? [] : splitTop(inner, ',');
2791
- return halves.length === 2 ? halves[side - 1].trim() : x;
2792
- };
2793
- b[prop] =
2794
- s.mode === 'light'
2795
- ? `light-dark(${v}, ${prev ? split(prev, 2) : other})`
2796
- : `light-dark(${prev ? split(prev, 1) : other}, ${v})`;
2797
- } else b[prop] = v;
2798
- };
2799
- // Palette stops go first, so an exact token setting always wins over them.
2800
- const pal = keepShades(
2801
- paletteMapping(ctx.project.cwd, data.name, data, base, TOKENS),
2802
- ctx.keepStops,
2803
- );
2804
- for (const [k, v] of Object.entries(pal?.tokens ?? {}))
2805
- putTok(k, [v.light.color, v.dark.color]);
2806
- // Secondary text lifted on the parts the official neutral theme lifts it
2807
- // on, each for what it sits on. It is written into the very block the
2808
- // base theme lifts it in, so it replaces the base's lift. A setting of it
2809
- // on the part (no --when or --state) wins there, per mode, so a numbered
2810
- // citation shows what `--on citation` set.
2811
- // Without a color dial nothing is lifted, but an exact secondary text
2812
- // still reaches those parts, and the base theme's own lift stays in the
4410
+ // A gradient background for one mode goes into the rule's block for
4411
+ // that mode as its image layers (with their positions, sizes and
4412
+ // repeats), and a layer that is a color alone as that mode's color: the
4413
+ // other mode keeps every image and color it had, Core's own included.
4414
+ if (
4415
+ s.mode &&
4416
+ /^background(-image)?$/.test(kebab(prop)) &&
4417
+ /gradient\(/i.test(v)
4418
+ ) {
4419
+ const mb = modeBlock(s, target, s.mode);
4420
+ // The background shorthand's last layer may carry the color under
4421
+ // the images: that color is this mode's background color, and the
4422
+ // rest are the images.
4423
+ const {images, color} =
4424
+ kebab(prop) === 'background'
4425
+ ? backgroundColorLayer(v)
4426
+ : {images: v, color: null};
4427
+ const parts = splitTop(images ?? '', ',')
4428
+ .map(x => x.trim())
4429
+ .filter(Boolean)
4430
+ .map(layerParts);
4431
+ for (const k of [
4432
+ 'background',
4433
+ 'backgroundImage',
4434
+ 'backgroundPosition',
4435
+ 'backgroundSize',
4436
+ 'backgroundRepeat',
4437
+ ])
4438
+ delete mb[k];
4439
+ mb.backgroundImage = parts.map(x => x.image).join(', ');
4440
+ if (parts.some(x => x.position || x.size || x.repeat)) {
4441
+ mb.backgroundPosition = parts
4442
+ .map(x => x.position || '0% 0%')
4443
+ .join(', ');
4444
+ mb.backgroundSize = parts.map(x => x.size || 'auto').join(', ');
4445
+ mb.backgroundRepeat = parts.map(x => x.repeat || 'repeat').join(', ');
4446
+ }
4447
+ if (!parts.length) delete mb.backgroundImage;
4448
+ if (color) mb.backgroundColor = color;
4449
+ return;
4450
+ }
4451
+ // A color set in a one-mode theme fills its mode's half only (as a
4452
+ // setting for that mode does), so a region Core draws in the other mode
4453
+ // reads the other half.
4454
+ const mode =
4455
+ s.mode ??
4456
+ (modeOnly && parseColor(String(v).trim()) ? modeOnly : undefined);
4457
+ if (mode && !s.when && variantsReading(ctx, target, prop, s.state).length) {
4458
+ // A color for one mode on a part whose variants each have their own:
4459
+ // each variant's rule (in the state, for a state setting) gets the
4460
+ // color in its block for that mode, so no variant takes another's and
4461
+ // the other mode stays as it was. The part's own rule is left alone.
4462
+ // The property itself (a border color stays a border color); the
4463
+ // background shorthand is written as its color.
4464
+ const css = colorFamily(prop);
4465
+ // The part's own background being an image (a gradient) covers any
4466
+ // color under it: the color is written, and the result says it does
4467
+ // not show.
4468
+ // A color given beside its own image in one background (`linear-
4469
+ // gradient(…), ivory`) is that image's bottom layer, never covered by
4470
+ // it.
4471
+ const plainImage =
4472
+ css === 'background-color' && !ownImageLayer(s)
4473
+ ? ['background', 'backgroundImage']
4474
+ .map(k => b[k])
4475
+ .find(y => typeof y === 'string' && /gradient\(|url\(/i.test(y))
4476
+ : undefined;
4477
+ if (plainImage)
4478
+ (ctx.compileNotes ??= []).push(
4479
+ `${target}'s own background is an image (${plainImage}), which covers the ${mode} color: it does not show until that background is a color`,
4480
+ );
4481
+ const names = new Set([
4482
+ ...(ctx.C.variantValues(target)?.variant ?? []),
4483
+ ...(ctx.C.MAP[target]?.attrs?.variant ?? []),
4484
+ ]);
4485
+ for (const name of names) {
4486
+ const x = exactVariantValue(target, css, name, s.state);
4487
+ const variant = {...s, when: `variant:${name}`};
4488
+ const vb = block({...variant, mode: undefined}, target);
4489
+ const family = [
4490
+ css,
4491
+ ...(css === 'background-color' ? ['background'] : []),
4492
+ ];
4493
+ // A variant whose own background is an image (a gradient) keeps
4494
+ // it: one mode's color is not written there, and the result says so.
4495
+ const image = family
4496
+ .map(k => vb[camel(k)])
4497
+ .find(y => typeof y === 'string' && /gradient\(|url\(/i.test(y));
4498
+ if (image) {
4499
+ (ctx.compileNotes ??= []).push(
4500
+ `${target} variant:${name} keeps its own background image (${image}), so the ${mode} color is not written there`,
4501
+ );
4502
+ continue;
4503
+ }
4504
+ const mb = modeBlock(variant, target, mode);
4505
+ for (const k of family) delete mb[camel(k)];
4506
+ mb[camel(css)] = v;
4507
+ // A resting color on the variant's rule in this mode would also hide
4508
+ // the hover the variant shows unset in this mode: that hover is
4509
+ // written back there as it was, unless a hover setting of the
4510
+ // theme's own gives it one.
4511
+ if (
4512
+ !s.state &&
4513
+ !data.settings.some(
4514
+ y =>
4515
+ y.on === s.on &&
4516
+ y.state === 'hover' &&
4517
+ colorFamily(y.thing) === colorFamily(s.thing),
4518
+ )
4519
+ ) {
4520
+ const hover = exactVariantValue(target, css, name, 'hover', true);
4521
+ if (hover != null && hover !== x)
4522
+ modeBlock({...variant, state: 'hover'}, target, mode)[
4523
+ camel(css)
4524
+ ] ??= halfOf(hover, mode === 'light' ? 1 : 2);
4525
+ }
4526
+ }
4527
+ return;
4528
+ }
4529
+ // A color for one mode under the part's own gradient does not show:
4530
+ // the result says so.
4531
+ if (
4532
+ mode &&
4533
+ colorFamily(prop) === 'background-color' &&
4534
+ !ownImageLayer(s) &&
4535
+ ['background', 'backgroundImage'].some(
4536
+ k => typeof b[k] === 'string' && /gradient\(|url\(/i.test(b[k]),
4537
+ )
4538
+ )
4539
+ (ctx.compileNotes ??= []).push(
4540
+ `${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`,
4541
+ );
4542
+ // A color for one mode goes into the rule's block for that mode, which
4543
+ // applies only where the element's color mode is that mode: in the other
4544
+ // mode the rule, and every rule the base theme and Core give the part in
4545
+ // context, apply as they would without it.
4546
+ // The background shorthand and its color are one property there: the
4547
+ // later setting replaces the earlier.
4548
+ if (mode) {
4549
+ const mb = modeBlock(s, target, mode);
4550
+ if (colorFamily(prop) === 'background-color')
4551
+ for (const k of ['background', 'backgroundColor'])
4552
+ if (typeof mb[k] === 'string' && !/gradient\(|url\(/i.test(mb[k]))
4553
+ delete mb[k];
4554
+ mb[prop] = v;
4555
+ } else b[prop] = v;
4556
+ };
4557
+ // Palette stops go first, so an exact token setting always wins over them.
4558
+ const pal = keepShades(
4559
+ paletteMapping(ctx.project.cwd, data.name, data, base, TOKENS),
4560
+ ctx.keepStops,
4561
+ );
4562
+ for (const [k, v] of Object.entries(pal?.tokens ?? {}))
4563
+ putTok(k, [v.light.color, v.dark.color]);
4564
+ // Secondary text lifted on the parts the official neutral theme lifts it
4565
+ // on, each for what it sits on. It is written into the very block the
4566
+ // base theme lifts it in, so it replaces the base's lift. A setting of it
4567
+ // on the part (no --when or --state) wins there, per mode, so a numbered
4568
+ // citation shows what `--on citation` set.
4569
+ // Without a color dial nothing is lifted, but an exact secondary text
4570
+ // still reaches those parts, and the base theme's own lift stays in the
2813
4571
  // mode it does not cover.
2814
4572
  /** @type {Partial<Record<'light' | 'dark', string>>} */
2815
4573
  const exactText = {};
@@ -2871,18 +4629,34 @@ export function compileTheme(ctx, data, base) {
2871
4629
  );
2872
4630
  // Dials first, then exact tokens and part properties: an exact setting
2873
4631
  // 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;
4632
+ // A dial on a part (a font for one role, corners on cards) comes after
4633
+ // the whole-theme dials, so the part keeps its own whatever the order.
4634
+ const onPart = (/** @type {Setting} */ x) => !!x.on;
2877
4635
  const ordered = [
2878
- ...data.settings.filter(x => x.source === 'dial' && !roleFont(x)),
2879
- ...data.settings.filter(x => x.source === 'dial' && roleFont(x)),
4636
+ ...data.settings.filter(x => x.source === 'dial' && !onPart(x)),
4637
+ ...data.settings.filter(x => x.source === 'dial' && onPart(x)),
2880
4638
  ...data.settings.filter(x => x.source !== 'dial'),
2881
4639
  ];
4640
+ // The shell regions a setting gives a background of their own keep it
4641
+ // when the page background paints the rest of the shell.
4642
+ // A background for one mode is that region's in its mode block only:
4643
+ // the page background still paints the region in the other mode.
4644
+ const regionsWithOwnBackground = new Set(
4645
+ data.settings
4646
+ .filter(
4647
+ x =>
4648
+ x.source === 'property' &&
4649
+ !x.mode &&
4650
+ /^background(-color|-image)?$/.test(kebab(x.thing)),
4651
+ )
4652
+ .flatMap(x => partsOf(ctx, x)),
4653
+ );
4654
+ /** @type {Record<string, any>[]} */
4655
+ const fixedToViewport = [];
2882
4656
  for (const s of ordered) {
2883
- // A setting for the mode a one-mode theme does not have stays saved but
2884
- // does not apply (maskedSettings names it).
2885
- if (modeOnly && s.mode && s.mode !== modeOnly) continue;
4657
+ // A setting for the mode a one-mode theme does not show still applies
4658
+ // where Core draws that mode (a toast, a lightbox), as the theme's other
4659
+ // halves of its colors do.
2886
4660
  const parts = partsOf(ctx, s);
2887
4661
  if (s.source === 'dial') {
2888
4662
  if (s.thing === 'corners') {
@@ -2893,27 +4667,56 @@ export function compileTheme(ctx, data, base) {
2893
4667
  /** @param {string} token */
2894
4668
  const derived = token => `${radiusAt(base, s.value, token)}px`;
2895
4669
  if (parts.length)
2896
- for (const t of parts) {
4670
+ for (const t of parts.flatMap(p => cornerParts(ctx, p))) {
2897
4671
  // A rung on a part gives what the whole-theme rung gives the
2898
4672
  // radius token the part reads; an exact size is as given.
2899
- putComp(
2900
- {...s, mode: undefined},
2901
- t,
2902
- 'borderRadius',
2903
- rung || pill ? derived(radiusTokenOf(ctx, t, s.when)) : `${px}px`,
2904
- );
4673
+ {
4674
+ const value =
4675
+ rung || pill
4676
+ ? derived(radiusTokenOf(ctx, t, s.when))
4677
+ : `${px}px`;
4678
+ // (A base rule that writes the part's own radius would win
4679
+ // over the token: the radius is written there as before.)
4680
+ const token = baseWritesRadius(t, s.when)
4681
+ ? null
4682
+ : positionalCornerToken(ctx, t);
4683
+ putComp(
4684
+ {...s, mode: undefined},
4685
+ t,
4686
+ token ?? 'borderRadius',
4687
+ value,
4688
+ );
4689
+ }
2905
4690
  }
2906
- else
2907
- for (const token of [
2908
- '--radius-element',
2909
- '--radius-inner',
2910
- '--radius-container',
2911
- '--radius-page',
2912
- ])
4691
+ else {
4692
+ for (const token of DIAL_RADII)
2913
4693
  // The radii the build already shows for this corners value (a
2914
4694
  // build by an earlier editor, or a step back) are kept, as the
2915
4695
  // colors are: they change only when corners or the base does.
2916
4696
  putTok(token, ctx.keepRadii?.[token] ?? derived(token));
4697
+ // A part rule of the base theme that gives a radius other than the
4698
+ // dial token the part reads (a length, or a token the dial never
4699
+ // moves, such as --radius-full) would keep it over the dial: the
4700
+ // rule is given that dial token, so the part follows the dial. A
4701
+ // part Core rounds with a token the dial never moves (a badge's
4702
+ // --radius-full) keeps its base radius.
4703
+ for (const [t, when, radius] of baseRadii(
4704
+ /** @type {{components?: Record<string, any>}} */ (base),
4705
+ )) {
4706
+ const token = radiusTokenOf(ctx, t, when);
4707
+ if (
4708
+ ctx.project.target.has(t) &&
4709
+ DIAL_RADII.includes(token) &&
4710
+ radius !== `var(${token})`
4711
+ )
4712
+ putComp(
4713
+ {...s, mode: undefined, when},
4714
+ t,
4715
+ 'borderRadius',
4716
+ `var(${token})`,
4717
+ );
4718
+ }
4719
+ }
2917
4720
  } else if (PALETTE_DIALS.includes(s.thing) || s.thing === 'vibrancy') {
2918
4721
  // The palette mapping above sets these tokens.
2919
4722
  } else if (s.thing === 'font') {
@@ -3001,40 +4804,272 @@ export function compileTheme(ctx, data, base) {
3001
4804
  // The rungs scale the spacing the base theme starts from.
3002
4805
  /** @param {string} k @param {string} nv */
3003
4806
  const put = (k, nv) => {
3004
- if (parts.length) for (const t of parts) block(s, t)[k] = nv;
3005
- else putTok(k, nv);
4807
+ if (parts.length) {
4808
+ // An exact whole-theme or own-source token holds inside the
4809
+ // part too.
4810
+ if (!keptTokens(null).has(k))
4811
+ for (const t of parts) block(s, t)[k] = nv;
4812
+ } else putTok(k, nv);
3006
4813
  };
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`);
4814
+ // The spacing steps, in order around the exact steps the theme
4815
+ // keeps (a whole-theme one or the own source's: they win over the
4816
+ // dial).
4817
+ /** @type {Record<string, string>} */
4818
+ const dialVars = {};
4819
+ {
4820
+ /** @type {Array<[string, number]>} */
4821
+ const steps = [];
4822
+ for (const [k, core] of Object.entries(
4823
+ /** @type {Record<string, string>} */ (TOKENS),
4824
+ )) {
4825
+ const v = base.light[k] ?? core;
4826
+ if (/^--spacing-/.test(k) && /rem$/.test(v))
4827
+ steps.push([k, parseFloat(v) * 16]);
4828
+ }
4829
+ /** @type {Record<string, number>} */
4830
+ const keptSteps = {};
4831
+ for (const [k, v] of keptTokens(null))
4832
+ if (/^--spacing-/.test(k)) {
4833
+ const n = sizePx(v);
4834
+ if (n != null) keptSteps[k] = n;
4835
+ }
4836
+ /** @type {string[]} */
4837
+ const noRoom = [];
4838
+ for (const [k, n] of spacingSteps(steps, f, keptSteps, noRoom)) {
4839
+ const nv = `${Number((n / 16).toFixed(3))}rem`;
4840
+ dialVars[k] = k in keptSteps ? String(keptTokens(null).get(k)) : nv;
4841
+ if (!(k in keptSteps)) put(k, nv);
4842
+ }
4843
+ for (const k of noRoom)
4844
+ (ctx.sizeNotes ??= []).push(
4845
+ `${k} has no room between the exact spacing steps kept around it, so it takes the value of the one below it`,
4846
+ );
4847
+ }
4848
+ // An exact size the theme keeps (it wins over the dial) is a fixed
4849
+ // point the others stay in order around: a whole-theme one, one of
4850
+ // the theme's own source, and on a part the part's own, in any
4851
+ // unit that comes to a length (a spacing token through the value
4852
+ // this dial gives it). A whole-theme dial also keeps each part's
4853
+ // own exact sizes in order on that part.
4854
+ const sizeParts = parts.length
4855
+ ? parts
4856
+ : [
4857
+ null,
4858
+ ...new Set(
4859
+ data.settings
4860
+ .filter(
4861
+ x =>
4862
+ x.source === 'token' &&
4863
+ /^--size-element-/.test(x.thing) &&
4864
+ x.on &&
4865
+ !x.when &&
4866
+ !x.state,
4867
+ )
4868
+ .flatMap(x => partsOf(ctx, x)),
4869
+ ),
4870
+ ];
4871
+ for (const t of sizeParts) {
4872
+ /** @type {Record<string, number>} */
4873
+ const kept = {};
4874
+ for (const [k, v] of keptSizes(t)) {
4875
+ const n = sizePx(v, dialVars);
4876
+ if (n != null) kept[k] = n;
4877
+ }
4878
+ /** @type {string[]} */
4879
+ const noRoom = [];
4880
+ for (const [k, nv] of controlSizes(
4881
+ Object.keys(/** @type {Record<string, string>} */ (TOKENS))
4882
+ .filter(k => /^--size-element-/.test(k))
4883
+ .map(k => [k, base.light[k] ?? TOKENS[k]]),
4884
+ f,
4885
+ kept,
4886
+ noRoom,
4887
+ ))
4888
+ if (t) block(s, t)[k] = nv;
4889
+ else putTok(k, nv);
4890
+ for (const k of noRoom)
4891
+ (ctx.sizeNotes ??= []).push(
4892
+ `${k}${t ? ` on ${t}` : ''} has no room between the exact sizes kept around it, so it takes the size of the one below it`,
4893
+ );
4894
+ }
4895
+ // A variant's own exact size is kept in order on that variant too,
4896
+ // with the part's and the theme's kept sizes around it.
4897
+ /** @type {Map<string, {t: string, when: string}>} */
4898
+ const variantScopes = new Map();
4899
+ for (const x of data.settings)
4900
+ if (
4901
+ x.source === 'token' &&
4902
+ /^--size-element-/.test(x.thing) &&
4903
+ x.on &&
4904
+ x.when &&
4905
+ !x.state
4906
+ )
4907
+ for (const t of partsOf(ctx, x))
4908
+ if (!parts.length || parts.includes(t))
4909
+ variantScopes.set(`${t} ${x.when}`, {t, when: x.when});
4910
+ for (const {t, when} of variantScopes.values()) {
4911
+ /** @type {Record<string, number>} */
4912
+ const kept = {};
4913
+ for (const [k, v] of keptSizes(t)) {
4914
+ const n = sizePx(v, dialVars);
4915
+ if (n != null) kept[k] = n;
4916
+ }
4917
+ for (const x of data.settings)
4918
+ if (
4919
+ x.source === 'token' &&
4920
+ /^--size-element-/.test(x.thing) &&
4921
+ x.when === when &&
4922
+ !x.state &&
4923
+ partsOf(ctx, x).includes(t)
4924
+ ) {
4925
+ const n = sizePx(String(x.value), dialVars);
4926
+ if (n != null) kept[x.thing] = n;
4927
+ }
4928
+ /** @type {string[]} */
4929
+ const noRoom = [];
4930
+ for (const [k, nv] of controlSizes(
4931
+ Object.keys(/** @type {Record<string, string>} */ (TOKENS))
4932
+ .filter(k => /^--size-element-/.test(k))
4933
+ .map(k => [k, base.light[k] ?? TOKENS[k]]),
4934
+ f,
4935
+ kept,
4936
+ noRoom,
4937
+ ))
4938
+ block({...s, when}, t)[k] = nv;
4939
+ for (const k of noRoom)
4940
+ (ctx.sizeNotes ??= []).push(
4941
+ `${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`,
4942
+ );
3013
4943
  }
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
4944
  }
3022
4945
  } else if (s.source === 'token') {
3023
4946
  if (parts.length) for (const t of parts) putComp(s, t, s.thing, s.value);
3024
4947
  else putTok(s.thing, s.value, s.mode);
3025
4948
  } else if (s.source === 'property') {
3026
- for (const t of parts) {
4949
+ // A background on the whole app shell is the page background. The
4950
+ // shell's header and side nav paint the body or surface color over it
4951
+ // in every variant but section, and in an auto-height shell they are
4952
+ // sticky, so content must not show through them when it scrolls: they
4953
+ // take the same background. The main content area is made
4954
+ // see-through. A gradient is fixed to the viewport on the shell and on
4955
+ // those regions, so the regions line up with the page behind them. A
4956
+ // background a setting gives one of those regions itself is kept.
4957
+ /** @type {string[]} */
4958
+ const pageParts = [];
4959
+ if (
4960
+ parts.includes('app-shell') &&
4961
+ /^background(-color|-image)?$/.test(kebab(s.thing)) &&
4962
+ !s.when &&
4963
+ !s.state
4964
+ ) {
4965
+ /** @param {Record<string, any>} r */
4966
+ const ownBackground = r =>
4967
+ ['background', 'backgroundColor', 'backgroundImage'].some(
4968
+ k => k in r,
4969
+ );
4970
+ for (const region of ['app-shell-header', 'app-shell-sidenav'])
4971
+ if (
4972
+ ctx.project.target.has(region) &&
4973
+ !regionsWithOwnBackground.has(region)
4974
+ )
4975
+ pageParts.push(region);
4976
+ // The see-through main area and the fixed attachment go with the
4977
+ // page background: in its mode's block for a one-mode one, so the
4978
+ // other mode keeps the content panel Core paints.
4979
+ if (ctx.project.target.has('layout-content')) {
4980
+ const lc = ((theme.components['layout-content'] ??= {}).base ??= {});
4981
+ const scope = s.mode ? (lc[`@${s.mode}`] ??= {}) : lc;
4982
+ const main = (scope[':where(.astryx-app-shell [role="main"])'] ??=
4983
+ {});
4984
+ if (!ownBackground(main)) main.backgroundColor = 'transparent';
4985
+ }
4986
+ // Written after every setting (below), so no background shorthand
4987
+ // in the same rule resets it.
4988
+ if (/gradient\(/.test(String(s.value)))
4989
+ for (const t of ['app-shell', ...pageParts])
4990
+ fixedToViewport.push(
4991
+ s.mode
4992
+ ? modeBlock({...s, state: undefined}, t, s.mode)
4993
+ : block({...s, mode: undefined}, t),
4994
+ );
4995
+ (ctx.compileNotes ??= []).push(
4996
+ "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",
4997
+ );
4998
+ }
4999
+ for (const t of [...parts, ...pageParts]) {
5000
+ // A heading takes its color from its color prop, which reads the
5001
+ // text color tokens after part styles: the color goes into those
5002
+ // tokens on the heading (a named color prop's own token for
5003
+ // --when color:<name>), so it shows there and nowhere else.
5004
+ if (t === 'heading' && kebab(s.thing) === 'color') {
5005
+ const named = /^color:([\w-]+)$/.exec(s.when ?? '')?.[1];
5006
+ const scope = named ? {...s, when: undefined} : s;
5007
+ for (const tok of named
5008
+ ? [`--color-text-${named}`]
5009
+ : ['--color-text-primary', '--color-text-secondary'])
5010
+ // A value naming one of these tokens (the secondary text color)
5011
+ // leaves that token as it is: it would read itself.
5012
+ if (!new RegExp(`var\\(\\s*${tok}\\s*[,)]`).test(String(s.value)))
5013
+ putComp(scope, t, tok, s.value);
5014
+ continue;
5015
+ }
5016
+ // A part whose text is drawn by elements inside it that read a text
5017
+ // color token themselves (a top nav heading's title) takes the color
5018
+ // in those tokens too, on the part alone, so that text shows it.
5019
+ if (kebab(s.thing) === 'color')
5020
+ for (const tok of innerTextTokens(ctx.C, t))
5021
+ if (!new RegExp(`var\\(\\s*${tok}\\s*[,)]`).test(String(s.value)))
5022
+ putComp(s, t, tok, s.value);
3027
5023
  // A padding on a part whose box reads Core's padding variables is
3028
5024
  // resolved with the rest of that part's padding, below.
3029
5025
  if (padVars(t) && /^padding(-|$)/.test(kebab(s.thing))) {
3030
5026
  queuePadding(s, t);
3031
5027
  continue;
3032
5028
  }
3033
- const sides =
3034
- wrappedPadding(t, s) ??
3035
- containerSides(t, s) ??
3036
- cornerRadii(t, s) ??
3037
- boxSides(t, s);
5029
+ // A padding on a part without padding variables, where the own source
5030
+ // pads some sides of the same rule: the editor writes the other
5031
+ // sides only, each as it names it (physical stays physical), so the
5032
+ // own sides win; a side the own source holds in one direction only
5033
+ // is written for the other direction.
5034
+ if (/^padding(-|$)/.test(kebab(s.thing)) && !s.mode && !padVars(t)) {
5035
+ const own = ownBox(t, s);
5036
+ if (own.ltr.size || own.rtl.size) {
5037
+ for (const [x, v] of Object.entries(
5038
+ paddingSides(kebab(s.thing), String(s.value)),
5039
+ )) {
5040
+ const prop = camel(`padding-${x}`);
5041
+ const [inL, inR] = [
5042
+ own.ltr.has(boxSide(x, 'ltr')),
5043
+ own.rtl.has(boxSide(x, 'rtl')),
5044
+ ];
5045
+ if (inL && inR) continue;
5046
+ if (!inL && !inR) {
5047
+ putComp(s, t, prop, v);
5048
+ continue;
5049
+ }
5050
+ const [db, key] = dirBlock(s, t, inL ? ':dir(rtl)' : ':dir(ltr)');
5051
+ db[key] = {...(db[key] ?? {}), [prop]: v};
5052
+ }
5053
+ continue;
5054
+ }
5055
+ }
5056
+ // One radius for a part whose corners Core draws by position: its
5057
+ // corner token on the part.
5058
+ const cornerToken =
5059
+ kebab(s.thing) === 'border-radius' &&
5060
+ !s.mode &&
5061
+ splitTop(String(s.value).trim(), ' ').length === 1 &&
5062
+ !String(s.value).includes('/')
5063
+ ? baseWritesRadius(t, s.when)
5064
+ ? null
5065
+ : positionalCornerToken(ctx, t)
5066
+ : null;
5067
+ const sides = cornerToken
5068
+ ? {[cornerToken]: String(s.value)}
5069
+ : (wrappedPadding(t, s) ??
5070
+ containerSides(t, s) ??
5071
+ cornerRadii(t, s) ??
5072
+ boxSides(t, s));
3038
5073
  if (sides)
3039
5074
  for (const [k, v] of Object.entries(sides)) {
3040
5075
  // A per-direction block joins what that direction already has,
@@ -3109,6 +5144,10 @@ export function compileTheme(ctx, data, base) {
3109
5144
  }
3110
5145
  }
3111
5146
  emitPadding();
5147
+ for (const r of fixedToViewport) {
5148
+ delete r.backgroundAttachment;
5149
+ r.backgroundAttachment = 'fixed';
5150
+ }
3112
5151
  orderBlocks();
3113
5152
  // Core gives headings the body font when a theme sets only the body's:
3114
5153
  // a font for the body alone keeps the base theme's heading font.
@@ -3159,10 +5198,32 @@ export function compileTheme(ctx, data, base) {
3159
5198
  weights: {...(theme.typography.heading?.weights ?? {}), ...heading},
3160
5199
  };
3161
5200
  }
5201
+ /**
5202
+ * What a token shows in one mode where the theme sets no half for it:
5203
+ * Core's own default when that is a reference to another token the base
5204
+ * theme's value equals (a focus ring that follows the accent), so it keeps
5205
+ * following what the theme sets there; else the base theme's value.
5206
+ * @param {string} k @param {'light' | 'dark'} side
5207
+ */
5208
+ const shownHalf = (k, side) => {
5209
+ const held = base[side][k];
5210
+ const ref = /^var\((--[\w-]+)\)$/.exec(String(TOKENS[k] ?? '').trim());
5211
+ if (ref && (held == null || base[side][ref[1]] === held)) return TOKENS[k];
5212
+ return held ?? TOKENS[k];
5213
+ };
3162
5214
  for (const [k, {light, dark}] of Object.entries(tok)) {
3163
- const l = light ?? base.light[k] ?? TOKENS[k];
3164
- const d = dark ?? base.dark[k] ?? TOKENS[k];
3165
- theme.tokens[k] = l === d ? l : [l, d];
5215
+ const l = light ?? shownHalf(k, 'light');
5216
+ const d = dark ?? shownHalf(k, 'dark');
5217
+ // A pair only for a color: anything else (a shadow) is one value, the
5218
+ // one the theme's mode shows.
5219
+ theme.tokens[k] =
5220
+ l === d
5221
+ ? l
5222
+ : ctx.C.typeOf(k) === 'color' || isColorToken(k)
5223
+ ? [l, d]
5224
+ : modeOnly === 'dark'
5225
+ ? d
5226
+ : l;
3166
5227
  }
3167
5228
  // Base themes set the type tokens again for phones (a coarse pointer
3168
5229
  // below the lg width); an exact font family or weight, and the headings
@@ -3193,16 +5254,205 @@ export function compileTheme(ctx, data, base) {
3193
5254
  theme.adaptations = {
3194
5255
  rules: [
3195
5256
  {
3196
- when: {pointer: 'coarse', width: {below: 'lg'}},
5257
+ when: PHONE_RULE_WHEN,
3197
5258
  value: {tokens: phone},
3198
5259
  },
3199
5260
  ],
3200
5261
  };
5262
+ // A longhand set after a shorthand that covers it is the one in effect,
5263
+ // as the result says. The build merges these blocks over the base
5264
+ // theme's, and a key the base holds keeps the base's (earlier) place, so
5265
+ // such a longhand would come before the shorthand and lose: it is written
5266
+ // as its own sides instead, which the base does not hold.
5267
+ const baseBlocks =
5268
+ /** @type {{components?: Record<string, any>}} */ (base).components ?? {};
5269
+ for (const [target, keys] of Object.entries(theme.components ?? {}))
5270
+ for (const [key, b] of Object.entries(
5271
+ /** @type {Record<string, any>} */ (keys),
5272
+ ))
5273
+ laterLonghandsAsSides(b, baseBlocks[target]?.[key]);
3201
5274
  if (!Object.keys(theme.tokens).length) delete theme.tokens;
3202
5275
  if (!Object.keys(theme.components).length) delete theme.components;
3203
5276
  return theme;
3204
5277
  }
3205
5278
 
5279
+ /**
5280
+ * Whether shorthand `a` sets `b`, a logical side included: padding sets
5281
+ * padding-inline, border-color sets border-inline-start-color.
5282
+ * @param {string} a @param {string} b
5283
+ */
5284
+ function coversSide(a, b) {
5285
+ if (coversProperty(a, b)) return true;
5286
+ const root = b.replace(/-(inline|block)(-start|-end)?(?=-|$)/, '');
5287
+ return root !== b && (a === root || coversProperty(a, root));
5288
+ }
5289
+
5290
+ /**
5291
+ * The part rules of a base theme that give a border radius: each as its
5292
+ * part, the rule's --when (undefined for the plain rule) and the radius.
5293
+ * @param {{components?: Record<string, any>}} base
5294
+ * @returns {Array<[string, string | undefined, string]>}
5295
+ */
5296
+ function baseRadii(base) {
5297
+ /** @type {Array<[string, string | undefined, string]>} */
5298
+ const out = [];
5299
+ for (const [t, rules] of Object.entries(base.components ?? {}))
5300
+ for (const [key, rule] of Object.entries(
5301
+ /** @type {Record<string, any>} */ (rules ?? {}),
5302
+ )) {
5303
+ if (key !== 'base' && !/^[\w-]+:[\w-]+$/.test(key)) continue;
5304
+ const r = rule?.borderRadius;
5305
+ if (typeof r === 'string')
5306
+ out.push([t, key === 'base' ? undefined : key, r.trim()]);
5307
+ }
5308
+ return out;
5309
+ }
5310
+
5311
+ /**
5312
+ * Whether a setting's own value is a background with an image layer, so any
5313
+ * color it writes is that background's bottom layer.
5314
+ * @param {Setting} s
5315
+ */
5316
+ function ownImageLayer(s) {
5317
+ return (
5318
+ kebab(s.thing) === 'background' && /gradient\(|url\(/i.test(String(s.value))
5319
+ );
5320
+ }
5321
+
5322
+ /**
5323
+ * A background shorthand split into its image layers and the color its
5324
+ * last layer may carry (the color under every image): a color word beside
5325
+ * the last image, or a last layer that is a color alone.
5326
+ * @param {string} value
5327
+ * @returns {{images: string, color: string | null}}
5328
+ */
5329
+ export function backgroundColorLayer(value) {
5330
+ const layers = splitTop(value, ',')
5331
+ .map(x => x.trim())
5332
+ .filter(Boolean);
5333
+ const last = layers.at(-1) ?? '';
5334
+ const words = splitTop(last, ' ').map(x => x.trim());
5335
+ const at = words.findIndex(
5336
+ w => !/gradient\(|url\(/i.test(w) && isColorValue(w),
5337
+ );
5338
+ if (at < 0) return {images: value, color: null};
5339
+ const rest = words.filter((_, i) => i !== at).join(' ');
5340
+ return {
5341
+ images: [...layers.slice(0, -1), ...(rest ? [rest] : [])].join(', '),
5342
+ color: words[at],
5343
+ };
5344
+ }
5345
+
5346
+ /**
5347
+ * A background layer's image (its gradient) and what follows it, as the
5348
+ * background longhands take them: position, size (after a slash) and
5349
+ * repeat.
5350
+ * @param {string} layer
5351
+ * @returns {{image: string, position: string, size: string, repeat: string}}
5352
+ */
5353
+ function layerParts(layer) {
5354
+ const fn = /^((?:repeating-)?(?:linear|radial|conic)-gradient)\(/i.exec(
5355
+ layer,
5356
+ );
5357
+ if (!fn) return {image: layer, position: '', size: '', repeat: ''};
5358
+ let depth = 0;
5359
+ let end = layer.length - 1;
5360
+ for (let i = fn[0].length - 1; i < layer.length; i++) {
5361
+ if (layer[i] === '(') depth++;
5362
+ if (layer[i] === ')' && --depth === 0) {
5363
+ end = i;
5364
+ break;
5365
+ }
5366
+ }
5367
+ const rest = splitTop(layer.slice(end + 1).trim(), ' ');
5368
+ const REPEAT = /^(repeat|no-repeat|repeat-x|repeat-y|space|round)$/i;
5369
+ const repeat = rest.filter(w => REPEAT.test(w)).join(' ');
5370
+ const words = rest.filter(w => !REPEAT.test(w)).join(' ');
5371
+ const [position = '', size = ''] = words.split('/').map(x => x.trim());
5372
+ return {image: layer.slice(0, end + 1), position, size, repeat};
5373
+ }
5374
+
5375
+ /** A side word in a longhand's name, in the order a box value lists sides. */
5376
+ const BOX_SIDES = ['top', 'right', 'bottom', 'left'];
5377
+
5378
+ /**
5379
+ * A block's longhands that follow a shorthand covering them, where the base
5380
+ * theme's block holds the same key, rewritten as that longhand's own sides
5381
+ * (padding-inline as padding-inline-start and -end, border-color as the
5382
+ * four side colors), in place and at the same position; a state's block
5383
+ * nested in it too. A longhand that is no side pair or box is kept.
5384
+ * @param {Record<string, any>} b
5385
+ * @param {Record<string, any> | undefined} baseBlock
5386
+ */
5387
+ function laterLonghandsAsSides(b, baseBlock) {
5388
+ if (
5389
+ !b ||
5390
+ typeof b !== 'object' ||
5391
+ !baseBlock ||
5392
+ typeof baseBlock !== 'object'
5393
+ )
5394
+ return;
5395
+ for (const [k, v] of Object.entries(b))
5396
+ if (k.startsWith(':') && v && typeof v === 'object')
5397
+ laterLonghandsAsSides(v, baseBlock[k]);
5398
+ const keys = Object.keys(b);
5399
+ /** @type {Record<string, any>} */
5400
+ const out = {};
5401
+ let changed = false;
5402
+ keys.forEach((k, i) => {
5403
+ const v = b[k];
5404
+ const css = kebab(k);
5405
+ const sides =
5406
+ typeof v === 'string' &&
5407
+ !k.startsWith('-') &&
5408
+ typeof baseBlock[k] === 'string' &&
5409
+ keys
5410
+ .slice(0, i)
5411
+ .some(e => !e.startsWith(':') && coversSide(kebab(e), css))
5412
+ ? sidesOf(css, v)
5413
+ : null;
5414
+ if (!sides) {
5415
+ out[k] = v;
5416
+ return;
5417
+ }
5418
+ changed = true;
5419
+ for (const [p, x] of Object.entries(sides)) {
5420
+ delete out[camel(p)];
5421
+ out[camel(p)] = x;
5422
+ }
5423
+ });
5424
+ if (!changed) return;
5425
+ for (const k of Object.keys(b)) delete b[k];
5426
+ Object.assign(b, out);
5427
+ }
5428
+
5429
+ /**
5430
+ * A two-sided (start/end) or four-sided (top/right/bottom/left) longhand's
5431
+ * value, as each side's property and value by the shorthand rules; null for
5432
+ * any other property.
5433
+ * @param {string} prop kebab-case
5434
+ * @param {string} v
5435
+ * @returns {Record<string, string> | null}
5436
+ */
5437
+ function sidesOf(prop, v) {
5438
+ const direct = [...longhandsOf(prop)].filter(p => longhandsOf(p).size === 0);
5439
+ const w = splitTop(v.trim(), ' ').map(x => x.trim());
5440
+ if (!w.length || /!important/i.test(v)) return null;
5441
+ const start = direct.find(p => /-start(-|$)/.test(p));
5442
+ const end = direct.find(p => /-end(-|$)/.test(p));
5443
+ if (direct.length === 2 && start && end && w.length <= 2)
5444
+ return {[start]: w[0], [end]: w[1] ?? w[0]};
5445
+ const named = BOX_SIDES.map(side =>
5446
+ direct.find(p => new RegExp(`-${side}(-|$)`).test(p)),
5447
+ );
5448
+ if (direct.length !== 4 || named.some(x => !x) || w.length > 4) return null;
5449
+ const [t, r = t, bo = t, l = r] = w;
5450
+ const vals = [t, r, bo, l];
5451
+ return Object.fromEntries(
5452
+ named.map((p, i) => [/** @type {string} */ (p), vals[i]]),
5453
+ );
5454
+ }
5455
+
3206
5456
  /** Core's default type scale ratio. */
3207
5457
  const STANDARD_RATIO = 1.2;
3208
5458
  /** The font-size tokens below the base, with their step on the scale. */
@@ -3229,18 +5479,6 @@ export function maskedSettings(data, ctx = null) {
3229
5479
  .filter(x => x.thing === 'headings')
3230
5480
  .map(x => x.axis ?? 'weight'),
3231
5481
  );
3232
- const only =
3233
- data.mode === 'light-only'
3234
- ? 'light'
3235
- : data.mode === 'dark-only'
3236
- ? 'dark'
3237
- : null;
3238
- for (const s of data.settings)
3239
- if (only && s.mode && s.mode !== only)
3240
- out.set(
3241
- s,
3242
- `saved for ${s.mode} mode, which a ${data.mode} theme does not have, so it does not apply`,
3243
- );
3244
5482
  // A part setting that a later setting on a group holding that part
3245
5483
  // covers: the later one is written after it, so it wins.
3246
5484
  data.settings.forEach((s, i) => {
@@ -3314,16 +5552,16 @@ export function maskedSettings(data, ctx = null) {
3314
5552
  * {font-weight}`. Find those rules in the built stylesheet.
3315
5553
  * @param {string} cssText
3316
5554
  * @param {any} theme
3317
- * @returns {Array<{target: string, key: string, prop: string, value: string}>}
5555
+ * @returns {Array<{target: string, key: string, prop: string, value: string, state?: string}>}
3318
5556
  */
3319
5557
  export function findOverrides(cssText, theme) {
3320
- /** @type {Array<{target: string, key: string, prop: string, value: string}>} */
5558
+ /** @type {Array<{target: string, key: string, prop: string, value: string, state?: string}>} */
3321
5559
  const extra = [];
3322
5560
  for (const [target, keys] of Object.entries(
3323
5561
  /** @type {Record<string, any>} */ (theme.components ?? {}),
3324
5562
  )) {
3325
5563
  const props = Object.keys(keys.base ?? {}).filter(
3326
- p => !p.startsWith('--') && !p.startsWith(':'),
5564
+ p => !p.startsWith('--') && !p.startsWith(':') && !p.startsWith('@'),
3327
5565
  );
3328
5566
  if (!props.length) continue;
3329
5567
  const re = new RegExp(
@@ -3362,6 +5600,51 @@ export function findOverrides(cssText, theme) {
3362
5600
  }
3363
5601
  }
3364
5602
  }
5603
+ // A state setting on the plain part (a whole-part hover) loses the same
5604
+ // way to a variant's own rule in that state: it is repeated there too.
5605
+ for (const [target, keys] of Object.entries(
5606
+ /** @type {Record<string, any>} */ (theme.components ?? {}),
5607
+ ))
5608
+ for (const [state, decl] of Object.entries(keys.base ?? {})) {
5609
+ if (!/^:[a-z-]+$/.test(state) || !decl || typeof decl !== 'object')
5610
+ continue;
5611
+ const props = Object.keys(decl).filter(
5612
+ p => !p.startsWith('--') && !p.startsWith(':'),
5613
+ );
5614
+ if (!props.length) continue;
5615
+ const re = new RegExp(
5616
+ `\\.astryx-${target.replace(/-/g, '\\-')}\\[data-([a-z-]+)="([^"]+)"\\](?:${state}(?![\\w-])[^{}]*|\\s*)\\{([^}]*)\\}`,
5617
+ 'g',
5618
+ );
5619
+ // The variant's own rule in that state, and its resting rule: that
5620
+ // one comes after the plain state rule at the same weight.
5621
+ const seen = new Set();
5622
+ for (const m of cssText.matchAll(re)) {
5623
+ const declared = [...m[3].matchAll(/(?:^|[;\s])([a-z-]+)\s*:/g)].map(
5624
+ d => d[1],
5625
+ );
5626
+ for (const prop of props) {
5627
+ const css = kebab(prop);
5628
+ if (css === m[1] || css.endsWith(`-${m[1]}`)) continue;
5629
+ if (
5630
+ !seen.has(`${m[1]}:${m[2]} ${prop}`) &&
5631
+ declared.some(
5632
+ d =>
5633
+ d === css || coversProperty(d, css) || coversProperty(css, d),
5634
+ )
5635
+ ) {
5636
+ seen.add(`${m[1]}:${m[2]} ${prop}`);
5637
+ extra.push({
5638
+ target,
5639
+ key: `${m[1]}:${m[2]}`,
5640
+ state,
5641
+ prop,
5642
+ value: decl[prop],
5643
+ });
5644
+ }
5645
+ }
5646
+ }
5647
+ }
3365
5648
  return extra;
3366
5649
  }
3367
5650
 
@@ -3384,8 +5667,43 @@ const liftValue = (lift, only) =>
3384
5667
  * @param {ThemeData} data
3385
5668
  * @param {any} theme
3386
5669
  * @param {import('./_palette.mjs').PaletteMapping | null} pal
5670
+ * @param {string} [cwd]
5671
+ * @param {Record<string, any> | null} [baseParts] the base theme's components, whose state objects each written one starts from
3387
5672
  */
3388
- function settingsSource(slug, data, theme, pal, cwd = '') {
5673
+ function settingsSource(slug, data, theme, pal, cwd = '', baseParts = null) {
5674
+ // Core merges a theme's state object (`:hover` in a rule) over the base
5675
+ // theme's whole, one level deep: each one starts as the base theme's own
5676
+ // for that rule, so the properties no setting names keep the base's.
5677
+ if (baseParts) {
5678
+ theme = {...theme, components: {...(theme.components ?? {})}};
5679
+ for (const [target, keys] of Object.entries(theme.components)) {
5680
+ /** @type {Record<string, any>} */
5681
+ const next = {};
5682
+ for (const [key, rule] of Object.entries(
5683
+ /** @type {Record<string, any>} */ (keys),
5684
+ )) {
5685
+ if (!rule || typeof rule !== 'object') {
5686
+ next[key] = rule;
5687
+ continue;
5688
+ }
5689
+ /** @type {Record<string, any>} */
5690
+ const r = {...rule};
5691
+ for (const [k, v] of Object.entries(rule)) {
5692
+ const own = baseParts[target]?.[key]?.[k];
5693
+ if (
5694
+ k.startsWith(':') &&
5695
+ v &&
5696
+ typeof v === 'object' &&
5697
+ own &&
5698
+ typeof own === 'object'
5699
+ )
5700
+ r[k] = {...own, ...v};
5701
+ }
5702
+ next[key] = r;
5703
+ }
5704
+ theme.components[target] = next;
5705
+ }
5706
+ }
3389
5707
  const like = data.like;
3390
5708
  const REF = '@@palette:';
3391
5709
  /** @param {string} family @param {'light' | 'dark'} m @param {import('./_palette.mjs').StopRef} r */
@@ -3393,7 +5711,7 @@ function settingsSource(slug, data, theme, pal, cwd = '') {
3393
5711
  r.family === 'black' || r.family === 'white'
3394
5712
  ? `${REF}${r.family}`
3395
5713
  : `${REF}${r.family ?? family}.${m}.${r.stop}${r.alpha ? `+${r.alpha}` : ''}`;
3396
- const out = {...theme, name: `${slug}-settings`};
5714
+ const out = {...theme, name: settingsThemeName(slug)};
3397
5715
  // A one-mode theme keeps both halves too (see compileTheme).
3398
5716
  if (pal && theme.tokens) {
3399
5717
  out.tokens = {...theme.tokens};
@@ -3637,32 +5955,217 @@ function themeModuleSource(slug) {
3637
5955
  export const themeSource = slug => themeModuleSource(slug);
3638
5956
 
3639
5957
  /**
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.
5958
+ * The name of the theme a settings module defines.
5959
+ * @param {string} slug
5960
+ */
5961
+ export const settingsThemeName = slug => `${slug}-settings`;
5962
+
5963
+ /**
5964
+ * Why a theme's source cannot carry its settings, with the step that puts
5965
+ * it right; null when it carries them. The theme is the export a build of
5966
+ * the source reads, loaded as the build loads it: it must be named for the
5967
+ * theme, and the settings module's own export must be in the chain of
5968
+ * themes it extends (after every spread and repeated key), the very object,
5969
+ * not a theme named like it. Null for a source that does not parse (its
5970
+ * parse error is its own finding), and for one that imports the settings
5971
+ * but does not load (outputsDrift and the build report that).
3643
5972
  * @param {string} cwd
3644
5973
  * @param {string} slug
3645
- * @returns {string | null}
5974
+ * @returns {Promise<{problem: string, fix: string} | null>}
3646
5975
  */
3647
- export function themeSourceProblem(cwd, slug) {
5976
+ export async function themeSourceProblem(cwd, slug) {
3648
5977
  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, '');
5978
+ /** @type {string} */
5979
+ let code;
5980
+ try {
5981
+ code = fs.readFileSync(f.ts, 'utf8');
5982
+ } catch {
5983
+ return null;
5984
+ }
5985
+ /** @type {any} */
5986
+ let ast;
5987
+ try {
5988
+ ast = parseModule(code, {sourceType: 'module', plugins: ['typescript']});
5989
+ } catch {
5990
+ return null;
5991
+ }
3654
5992
  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}'`;
5993
+ const putBack = `Put back the import of ${settings} from './${slug}.settings', extends: ${settings} and name: '${slug}' in themes/${slug}/${slug}.theme.ts (your own changes stay below them).`;
5994
+ const fromSettings = new RegExp(`^\\./${slug}\\.settings(\\.[jt]s)?$`);
5995
+ const importsSettings = ast.program.body.some(
5996
+ (/** @type {any} */ node) =>
5997
+ node.type === 'ImportDeclaration' && fromSettings.test(node.source.value),
5998
+ );
5999
+ const notImported = {
6000
+ problem: `${slug}.theme.ts does not import ./${slug}.settings`,
6001
+ fix: putBack,
6002
+ };
6003
+ /** @type {{theme: any, exportName: string, extendsBase?: boolean}} */
6004
+ let loaded;
6005
+ try {
6006
+ loaded = await loadThemeExport(f.ts, {
6007
+ cwd,
6008
+ // The settings module's own export, by identity: a theme merely
6009
+ // named like it is not it.
6010
+ base: {
6011
+ file: path.join(f.dir, `${slug}.settings.ts`),
6012
+ exportName: settings,
6013
+ specifiers: ['', '.ts', '.js'].map(x => `./${slug}.settings${x}`),
6014
+ },
6015
+ });
6016
+ } catch {
6017
+ // A source that does not load is the build's own finding
6018
+ // (outputsDrift and every build report it); one that does not import
6019
+ // the settings says that first.
6020
+ return importsSettings ? null : notImported;
6021
+ }
6022
+ if (loaded.theme?.name !== slug) {
6023
+ // Another export of the file names the theme: the build reads a
6024
+ // different one, so say which, and how to make it read the theme.
6025
+ const other = exportedNames(ast).find(
6026
+ name =>
6027
+ name !== loaded.exportName &&
6028
+ plainText(
6029
+ unwrapConst(
6030
+ ast,
6031
+ exportedDefinition(ast, name)?.properties.find(
6032
+ (/** @type {any} */ p) =>
6033
+ p.type === 'ObjectProperty' &&
6034
+ (p.key.name ?? p.key.value) === 'name',
6035
+ )?.value,
6036
+ ),
6037
+ ) === slug,
6038
+ );
6039
+ return other
6040
+ ? {
6041
+ problem: `a build of ${slug}.theme.ts reads its export ${loaded.exportName} (the theme '${loaded.theme?.name}'), not ${other}, the theme named '${slug}'`,
6042
+ fix: `Make ${other} the theme a build reads: export it as the default (export default ${other}), or move the other theme to a file of its own.`,
6043
+ }
6044
+ : {
6045
+ problem: `${slug}.theme.ts no longer names the theme '${slug}'`,
6046
+ fix: putBack,
6047
+ };
6048
+ }
6049
+ if (!loaded.extendsBase)
6050
+ return importsSettings
6051
+ ? {
6052
+ problem: `${slug}.theme.ts no longer extends ${settings}`,
6053
+ fix: putBack,
6054
+ }
6055
+ : notImported;
3663
6056
  return null;
3664
6057
  }
3665
6058
 
6059
+ /**
6060
+ * A plain text value: a string, or a template with no expressions.
6061
+ * @param {any} node
6062
+ * @returns {string | null}
6063
+ */
6064
+ function plainText(node) {
6065
+ return node?.type === 'StringLiteral'
6066
+ ? node.value
6067
+ : node?.type === 'TemplateLiteral' && node.expressions.length === 0
6068
+ ? node.quasis.map((/** @type {any} */ q) => q.value.cooked).join('')
6069
+ : null;
6070
+ }
6071
+
6072
+ /**
6073
+ * A module's top-level const bindings, by name.
6074
+ * @param {any} ast
6075
+ * @returns {Map<string, any>}
6076
+ */
6077
+ function topConsts(ast) {
6078
+ /** @type {Map<string, any>} */
6079
+ const out = new Map();
6080
+ for (const node of ast.program.body) {
6081
+ const decl =
6082
+ node.type === 'ExportNamedDeclaration' ? node.declaration : node;
6083
+ if (decl?.type === 'VariableDeclaration')
6084
+ for (const d of decl.declarations)
6085
+ if (d.id.type === 'Identifier') out.set(d.id.name, d.init);
6086
+ }
6087
+ return out;
6088
+ }
6089
+
6090
+ /**
6091
+ * An expression with TypeScript wrappers and parentheses taken off, and a
6092
+ * name read through to the top-level const it names. An imported name stays
6093
+ * the identifier.
6094
+ * @param {any} ast
6095
+ * @param {any} node
6096
+ * @returns {any}
6097
+ */
6098
+ function unwrapConst(ast, node) {
6099
+ const consts = topConsts(ast);
6100
+ for (let depth = 0; node && depth < 20; depth++) {
6101
+ if (
6102
+ [
6103
+ 'TSAsExpression',
6104
+ 'TSSatisfiesExpression',
6105
+ 'TSNonNullExpression',
6106
+ 'TSTypeAssertion',
6107
+ 'ParenthesizedExpression',
6108
+ ].includes(node.type)
6109
+ )
6110
+ node = node.expression;
6111
+ else if (node.type === 'Identifier' && consts.get(node.name))
6112
+ node = consts.get(node.name);
6113
+ else return node;
6114
+ }
6115
+ return node;
6116
+ }
6117
+
6118
+ /**
6119
+ * The names a module exports, `default` included.
6120
+ * @param {any} ast
6121
+ * @returns {string[]}
6122
+ */
6123
+ function exportedNames(ast) {
6124
+ /** @type {string[]} */
6125
+ const names = [];
6126
+ for (const node of ast.program.body) {
6127
+ if (node.type === 'ExportDefaultDeclaration') names.push('default');
6128
+ if (node.type !== 'ExportNamedDeclaration' || node.source) continue;
6129
+ if (node.declaration?.type === 'VariableDeclaration')
6130
+ for (const d of node.declaration.declarations)
6131
+ if (d.id.type === 'Identifier') names.push(d.id.name);
6132
+ for (const spec of node.specifiers ?? [])
6133
+ names.push(spec.exported.name ?? spec.exported.value);
6134
+ }
6135
+ return names;
6136
+ }
6137
+
6138
+ /**
6139
+ * The object a module export defines its theme with: the argument of the
6140
+ * `defineTheme(...)` call, or the object itself, that the export names.
6141
+ * @param {any} ast
6142
+ * @param {string} exportName
6143
+ * @returns {any} an ObjectExpression, or null
6144
+ */
6145
+ function exportedDefinition(ast, exportName) {
6146
+ /** @type {any} */
6147
+ let value = null;
6148
+ for (const node of ast.program.body) {
6149
+ if (node.type === 'ExportDefaultDeclaration' && exportName === 'default')
6150
+ value = node.declaration;
6151
+ if (node.type !== 'ExportNamedDeclaration') continue;
6152
+ if (node.declaration?.type === 'VariableDeclaration')
6153
+ for (const d of node.declaration.declarations)
6154
+ if (d.id.type === 'Identifier' && d.id.name === exportName)
6155
+ value = d.init;
6156
+ for (const spec of node.specifiers ?? [])
6157
+ if (
6158
+ !node.source &&
6159
+ (spec.exported.name ?? spec.exported.value) === exportName
6160
+ )
6161
+ value = spec.local;
6162
+ }
6163
+ value = unwrapConst(ast, value);
6164
+ if (value?.type === 'CallExpression')
6165
+ value = unwrapConst(ast, value.arguments[0]);
6166
+ return value?.type === 'ObjectExpression' ? value : null;
6167
+ }
6168
+
3666
6169
  /**
3667
6170
  * Why the person's own theme source does not parse (its line and the
3668
6171
  * parser's message), or null when it parses or is not there.
@@ -3712,132 +6215,57 @@ export function refuseThemeParse(cwd, slug) {
3712
6215
  /**
3713
6216
  * Refuse a build whose theme source cannot carry the settings, naming the
3714
6217
  * lines that put it back.
3715
- * @param {string} cwd
3716
- * @param {string} slug
3717
- */
3718
- export function refuseThemeSource(cwd, slug) {
3719
- 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
- );
3727
- }
3728
-
3729
- /**
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
3735
- * @param {string} cwd
3736
- * @param {string} slug
3737
- */
3738
- function refuseOwnPairs(ctx, cwd, slug) {
3739
- const f = themeFiles(cwd, slug);
3740
- /** @type {string[]} */
3741
- const bad = [];
3742
- try {
3743
- const ast = /** @type {any} */ (
3744
- parseModule(fs.readFileSync(f.ts, 'utf8'), {
3745
- sourceType: 'module',
3746
- plugins: ['typescript'],
3747
- })
3748
- );
3749
- /** @param {any} node */
3750
- const visit = node => {
3751
- 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',
3763
- )
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);
3776
- }
3777
- 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);
3780
- };
3781
- visit(ast.program);
3782
- } catch {
3783
- return;
3784
- }
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
- );
6218
+ * @param {string} cwd
6219
+ * @param {string} slug
6220
+ */
6221
+ export async function refuseThemeSource(cwd, slug) {
6222
+ refuseThemeParse(cwd, slug);
6223
+ const refusal = await themeSourceRefusal(cwd, slug);
6224
+ if (refusal) throw refusal;
6225
+ }
6226
+
6227
+ /**
6228
+ * The refusal for a theme source that cannot carry the settings (it no
6229
+ * longer imports or extends them, or names another theme), naming the
6230
+ * lines that put it back; null when it carries them. Every command that
6231
+ * builds the theme refuses with it.
6232
+ * @param {string} cwd
6233
+ * @param {string} slug
6234
+ * @returns {Promise<AstryxError | null>}
6235
+ */
6236
+ export async function themeSourceRefusal(cwd, slug) {
6237
+ const why = await themeSourceProblem(cwd, slug);
6238
+ return why
6239
+ ? new AstryxError(
6240
+ `${why.problem}, so settings cannot take effect. ${why.fix} Nothing was changed.`,
6241
+ [{name: `${P} show ${slug}`, reason: 'see the theme as it is'}],
6242
+ ERROR_CODES.ERR_THEME_INVALID,
6243
+ )
6244
+ : null;
3796
6245
  }
3797
6246
 
3798
6247
  /**
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).
6248
+ * The input the theme's own source gives `defineTheme()`, evaluated as a
6249
+ * build evaluates it, with the theme Core made of it (or Core's error when
6250
+ * it refuses the input); null when the source does not load.
3804
6251
  * @param {Ctx} ctx
3805
6252
  * @param {string} slug
3806
- * @returns {Promise<string[]>}
6253
+ * @param {string | null} like the base theme, whose built tokens are `base`
6254
+ * @returns {Promise<{input: any, theme: any, error: Error | null, chain: any[], base: Map<string, string | null>} | null>}
3807
6255
  */
3808
- export async function builtPairs(ctx, slug) {
6256
+ export async function ownThemeInput(ctx, slug, like) {
3809
6257
  const {cwd} = ctx.project;
3810
- const f = themeFiles(cwd, slug);
3811
- // The build writes only inside the project: the cache folder when it is
3812
- // there, else a hidden folder in the theme's (removed after).
3813
- const name = `.${slug}.pairs-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
3814
- const inside = !path.relative(cwd, ctx.project.cacheDir).startsWith('..');
3815
- const dir = path.join(inside ? ctx.project.cacheDir : f.dir, name);
3816
- const silent = logger.silent;
3817
- logger.setSilent(true);
6258
+ const baseFile = like ? baseModule(cwd, like) : null;
3818
6259
  try {
3819
- fs.mkdirSync(dir, {recursive: true});
3820
- await themeBuildForReport(
3821
- shown(cwd, f.ts),
3822
- {out: path.relative(cwd, path.join(dir, `${slug}.css`))},
3823
- {cwd},
3824
- {compact: true},
6260
+ const loaded = await loadThemeInput(themeFiles(cwd, slug).ts, {
6261
+ cwd,
6262
+ name: slug,
6263
+ });
6264
+ return (
6265
+ loaded && {...loaded, base: baseFile ? topTokensOf(baseFile) : new Map()}
3825
6266
  );
3826
- const js = fs
3827
- .readdirSync(dir)
3828
- .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);
3836
6267
  } catch {
3837
- return [];
3838
- } finally {
3839
- logger.setSilent(silent);
3840
- fs.rmSync(dir, {recursive: true, force: true});
6268
+ return null;
3841
6269
  }
3842
6270
  }
3843
6271
 
@@ -3850,6 +6278,21 @@ export function ownPairMessage(slug, names) {
3850
6278
  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
6279
  }
3852
6280
 
6281
+ /**
6282
+ * The check of a theme's own token values, run before every build, set by
6283
+ * the editor (which owns the checks a value meets): null until it is set.
6284
+ * @type {((ctx: Ctx, slug: string, data: ThemeData) => Promise<void>) | null}
6285
+ */
6286
+ let ownTokenCheck = null;
6287
+
6288
+ /**
6289
+ * Set the check of a theme's own token values run before every build.
6290
+ * @param {((ctx: Ctx, slug: string, data: ThemeData) => Promise<void>) | null} fn
6291
+ */
6292
+ export function setOwnTokenCheck(fn) {
6293
+ ownTokenCheck = fn;
6294
+ }
6295
+
3853
6296
  /**
3854
6297
  * What runs after every build of a theme, set by the adapter (the app copy
3855
6298
  * of the theme): null until it is set.
@@ -3888,13 +6331,15 @@ export function holdAfterBuild(ctx) {
3888
6331
  * @param {Ctx} ctx
3889
6332
  * @param {string} slug
3890
6333
  * @param {ThemeData} data
3891
- * @returns {Promise<{warnings: string[], lifted: string[], notes: string[]}>} `notes`: what the color config kept or replaced of a hand edit
6334
+ * @returns {Promise<{warnings: string[], lifted: string[], notes: string[], removedPictures: string[]}>} `notes`: what the color config kept or replaced of a hand edit; `removedPictures`: the editor's pictures of the look before, removed
3892
6335
  */
3893
6336
  export async function buildTheme(ctx, slug, data) {
3894
6337
  const {cwd} = ctx.project;
3895
6338
  const f = themeFiles(cwd, slug);
3896
- refuseThemeSource(cwd, slug);
3897
- refuseOwnPairs(ctx, cwd, slug);
6339
+ await refuseThemeSource(cwd, slug);
6340
+ // The theme's own token values, judged as a build of the source writes
6341
+ // them, before anything is written.
6342
+ await ownTokenCheck?.(ctx, slug, data);
3898
6343
  if (data.like) baseThemeFile(ctx.project, data.like);
3899
6344
  const base = await baseResolved(ctx.project, data.like);
3900
6345
  fs.mkdirSync(f.dir, {recursive: true});
@@ -3933,7 +6378,17 @@ export async function buildTheme(ctx, slug, data) {
3933
6378
  ctx.keepStops,
3934
6379
  );
3935
6380
  await step(() => {
3936
- writeWhole(f.settingsTs, settingsSource(slug, data, theme, pal, cwd));
6381
+ writeWhole(
6382
+ f.settingsTs,
6383
+ settingsSource(
6384
+ slug,
6385
+ data,
6386
+ theme,
6387
+ pal,
6388
+ cwd,
6389
+ /** @type {any} */ (base).components ?? null,
6390
+ ),
6391
+ );
3937
6392
  syncPaletteRefs(cwd, slug, fs.readFileSync(f.settingsTs, 'utf8'), pal);
3938
6393
  if (!fs.existsSync(f.ts)) writeWhole(f.ts, themeModuleSource(slug));
3939
6394
  });
@@ -3942,16 +6397,23 @@ export async function buildTheme(ctx, slug, data) {
3942
6397
  // Only a picture the editor recorded writing, unchanged since, goes: a
3943
6398
  // file of the user's is never touched. Section sheets stay, marked as
3944
6399
  // out of date like sheet.html.
6400
+ /** The pictures removed: named in the result. @type {string[]} */
6401
+ let removedPictures = [];
3945
6402
  await step(() => {
6403
+ // The full sheet's and the preview's pictures, in each mode; a section
6404
+ // sheet's (`sheet-inputs.png`) is not one of them.
3946
6405
  const pictures = fs.existsSync(f.dir)
3947
6406
  ? fs
3948
6407
  .readdirSync(f.dir)
3949
6408
  .filter(
3950
6409
  n =>
3951
- /^(sheet|preview)(-[a-z-]+)?\.png$/.test(n) &&
3952
- editorWrote(cwd, slug, path.join(f.dir, n)),
6410
+ /^(sheet|preview)(-dark)?\.png$/.test(n) &&
6411
+ editorRecorded(cwd, slug, path.join(f.dir, n)),
3953
6412
  )
3954
6413
  : [];
6414
+ removedPictures = pictures.map(n =>
6415
+ path.relative(cwd, path.join(f.dir, n)).split(path.sep).join('/'),
6416
+ );
3955
6417
  for (const file of [
3956
6418
  path.join(f.dir, `${slug}.variants.d.ts`),
3957
6419
  ...pictures.map(n => path.join(f.dir, n)),
@@ -3959,9 +6421,47 @@ export async function buildTheme(ctx, slug, data) {
3959
6421
  fs.rmSync(file, {force: true});
3960
6422
  forgetWritten(cwd, slug, pictures);
3961
6423
  });
3962
- let receipt = await step(() => runBuild(ctx, slug));
6424
+ let receipt = await step(() => runBuild(ctx, slug, data));
6425
+ // A state setting on the plain part that the own source's same state
6426
+ // rule wins over is not repeated on the variants either: the own source
6427
+ // wins on every variant, as the result says.
6428
+ /** @type {Map<string, Map<string, string | null>>} */
6429
+ const ownStates = new Map();
6430
+ /** @param {string} target @param {string} state @param {string} prop */
6431
+ const ownHolds = (target, state, prop) => {
6432
+ const k = `${target} ${state}`;
6433
+ const own =
6434
+ ownStates.get(k) ?? ownPartTokens(cwd, slug, target, 'base', state);
6435
+ ownStates.set(k, own);
6436
+ const css = kebab(prop);
6437
+ return [...own.keys()].some(
6438
+ o => o === css || coversProperty(o, css) || coversProperty(css, o),
6439
+ );
6440
+ };
3963
6441
  const found = findOverrides(fs.readFileSync(f.css, 'utf8'), theme).filter(
3964
- x => !(theme.components[x.target][x.key] ?? {})[x.prop],
6442
+ x =>
6443
+ // By property: a variant whose rule the settings give this property
6444
+ // or a shorthand covering it needs no copy; nor one holding a
6445
+ // longhand of it that the base theme's rule also holds and that has
6446
+ // no sides to be written as (a background color, one-mode or not):
6447
+ // the copy would come after it there and win. Any other longhand
6448
+ // takes the copy, then is written after it (as its sides where the
6449
+ // base holds it).
6450
+ !Object.entries(
6451
+ (x.state
6452
+ ? theme.components[x.target][x.key]?.[x.state]
6453
+ : theme.components[x.target][x.key]) ?? {},
6454
+ ).some(([k, v]) => {
6455
+ if (k.startsWith(':')) return false;
6456
+ if (k === x.prop || coversProperty(kebab(k), kebab(x.prop)))
6457
+ return true;
6458
+ if (!coversProperty(kebab(x.prop), kebab(k))) return false;
6459
+ const baseRule = /** @type {any} */ (base).components?.[x.target]?.[
6460
+ x.key
6461
+ ];
6462
+ const held = (x.state ? baseRule?.[x.state] : baseRule)?.[k];
6463
+ return held != null && sidesOf(kebab(k), String(v)) == null;
6464
+ }) && !(x.state && ownHolds(x.target, x.state, x.prop)),
3965
6465
  );
3966
6466
  /** @type {string[]} */
3967
6467
  const lifted = [];
@@ -3972,19 +6472,42 @@ export async function buildTheme(ctx, slug, data) {
3972
6472
  // longhand or shorthand the variant sets itself (border-color after
3973
6473
  // a base border) still wins over it.
3974
6474
  const own = t[x.key] ?? {};
6475
+ const ownState = x.state ? (own[x.state] ?? {}) : own;
3975
6476
  // A variant that sets every longhand of the property itself needs
3976
6477
  // none of the base value (and a lifted radius would feed Core's copy
3977
6478
  // of it into the content's radius, after the variant's own).
3978
6479
  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)}`);
6480
+ if (longs.length && longs.every(l => camel(l) in ownState)) continue;
6481
+ t[x.key] = x.state
6482
+ ? {...own, [x.state]: {[x.prop]: x.value, ...ownState}}
6483
+ : {[x.prop]: x.value, ...own};
6484
+ // The variant's own longhands come after the copied shorthand; one
6485
+ // the base theme holds would keep the base's earlier place and lose,
6486
+ // so it is written as its sides.
6487
+ const baseRule = /** @type {any} */ (base).components?.[x.target]?.[
6488
+ x.key
6489
+ ];
6490
+ laterLonghandsAsSides(
6491
+ x.state ? t[x.key][x.state] : t[x.key],
6492
+ x.state ? baseRule?.[x.state] : baseRule,
6493
+ );
6494
+ lifted.push(`${x.target} ${x.key}${x.state ?? ''} ${kebab(x.prop)}`);
3982
6495
  }
3983
6496
  await step(() => {
3984
- writeWhole(f.settingsTs, settingsSource(slug, data, theme, pal, cwd));
6497
+ writeWhole(
6498
+ f.settingsTs,
6499
+ settingsSource(
6500
+ slug,
6501
+ data,
6502
+ theme,
6503
+ pal,
6504
+ cwd,
6505
+ /** @type {any} */ (base).components ?? null,
6506
+ ),
6507
+ );
3985
6508
  syncPaletteRefs(cwd, slug, fs.readFileSync(f.settingsTs, 'utf8'), pal);
3986
6509
  });
3987
- receipt = await step(() => runBuild(ctx, slug));
6510
+ receipt = await step(() => runBuild(ctx, slug, data));
3988
6511
  }
3989
6512
  for (const out of [f.css, f.js])
3990
6513
  if (fs.existsSync(out))
@@ -4002,11 +6525,45 @@ export async function buildTheme(ctx, slug, data) {
4002
6525
  await step(() => {
4003
6526
  afterBuild?.(ctx, slug, data);
4004
6527
  });
4005
- return {warnings, lifted, notes};
6528
+ // Every caller reports the build's notes, so the pictures it removed are
6529
+ // named in the result of whatever command built (set, undo, show, a
6530
+ // preview command).
6531
+ if (removedPictures.length)
6532
+ notes = [
6533
+ ...notes,
6534
+ `removed ${removedPictures.join(', ')}: ${removedPictures.length === 1 ? 'a picture' : 'pictures'} of ${slug} as it was before this build; ${P} show ${slug} --png takes new ones`,
6535
+ ];
6536
+ return {warnings, lifted, notes, removedPictures};
6537
+ }
6538
+
6539
+ /**
6540
+ * The one color mode of a light-only or dark-only theme, from its settings,
6541
+ * for the build to write into the built module (`colorModes`); null for a
6542
+ * theme with both modes.
6543
+ * @param {string} cwd
6544
+ * @param {string} slug
6545
+ * @returns {['light'] | ['dark'] | null}
6546
+ */
6547
+ export function buildColorModes(cwd, slug) {
6548
+ try {
6549
+ return oneColorMode(
6550
+ modesOf(
6551
+ settingsJson(fs.readFileSync(themeFiles(cwd, slug).settings, 'utf8')),
6552
+ ),
6553
+ );
6554
+ } catch {
6555
+ return null;
6556
+ }
4006
6557
  }
4007
6558
 
4008
- /** @param {Ctx} ctx @param {string} slug @returns {Promise<any>} */
4009
- async function runBuild(ctx, slug) {
6559
+ /**
6560
+ * @param {Ctx} ctx
6561
+ * @param {string} slug
6562
+ * @param {{mode?: string}} [data] the settings being built (saved after the
6563
+ * build), whose mode the built module exports
6564
+ * @returns {Promise<any>}
6565
+ */
6566
+ async function runBuild(ctx, slug, data) {
4010
6567
  const {cwd} = ctx.project;
4011
6568
  const f = themeFiles(cwd, slug);
4012
6569
  const silent = logger.silent;
@@ -4020,6 +6577,11 @@ async function runBuild(ctx, slug) {
4020
6577
  {},
4021
6578
  {cwd},
4022
6579
  {compact: true},
6580
+ {
6581
+ colorModes: data
6582
+ ? oneColorMode(modesOf(data))
6583
+ : buildColorModes(cwd, slug),
6584
+ },
4023
6585
  );
4024
6586
  return receipt;
4025
6587
  } finally {
@@ -4046,6 +6608,7 @@ export async function outputsDrift(ctx, slug) {
4046
6608
  {check: true},
4047
6609
  {cwd},
4048
6610
  {compact: true},
6611
+ {colorModes: buildColorModes(cwd, slug)},
4049
6612
  );
4050
6613
  const first = /** @type {any} */ (receipt)?.data?.stale?.[0];
4051
6614
  if (!first) return null;
@@ -4054,11 +6617,10 @@ export async function outputsDrift(ctx, slug) {
4054
6617
  ? `${name} was missing`
4055
6618
  : `${name} differs from what the settings build, after an edit by hand or by another tool`;
4056
6619
  } catch (e) {
4057
- // A theme source that does not load is named by its own checks; any
4058
- // other failure means the outputs could not be compared: built again.
6620
+ // The outputs could not be compared (the source does not load, or
6621
+ // anything else): the theme is built again, and a build that fails
6622
+ // says why. Nothing records the source as built.
4059
6623
  const err = /** @type {any} */ (e);
4060
- if (err instanceof AstryxError && err.code === ERROR_CODES.ERR_THEME_LOAD)
4061
- return null;
4062
6624
  return `the outputs could not be checked (${String(err?.message ?? e)
4063
6625
  .split('\n')[0]
4064
6626
  .slice(0, 160)})`;
@@ -4220,6 +6782,29 @@ function nonTextToken(t, typeOf = (/** @type {string} */ _k) => 'other') {
4220
6782
  return null;
4221
6783
  }
4222
6784
 
6785
+ /**
6786
+ * A value as a message names it, whatever it is: text in quotes, a number,
6787
+ * a BigInt with its `n`, a symbol, a function, an array or an object as
6788
+ * JSON where it has one. Never throws.
6789
+ * @param {unknown} value
6790
+ * @returns {string}
6791
+ */
6792
+ export function describeValue(value) {
6793
+ if (typeof value === 'bigint') return `${value}n`;
6794
+ if (typeof value === 'number' && !Number.isFinite(value))
6795
+ return String(value);
6796
+ if (typeof value === 'symbol') return String(value);
6797
+ if (typeof value === 'function') return 'a function';
6798
+ if (value === undefined) return 'undefined';
6799
+ try {
6800
+ return JSON.stringify(value, (_k, v) =>
6801
+ typeof v === 'bigint' ? `${v}n` : typeof v === 'symbol' ? String(v) : v,
6802
+ );
6803
+ } catch {
6804
+ return String(value);
6805
+ }
6806
+ }
6807
+
4223
6808
  /**
4224
6809
  * Why a token value is not one, with a value of the token's own type to
4225
6810
  * write instead (a size in px, a weight as a number in quotes), or none.
@@ -4227,11 +6812,11 @@ function nonTextToken(t, typeOf = (/** @type {string} */ _k) => 'other') {
4227
6812
  * @param {string} slug
4228
6813
  * @param {[string, unknown, ('object' | 'pair' | 'unit' | 'value' | 'mode')?]} bad
4229
6814
  */
4230
- function nonTextMessage(ctx, slug, [name, value, kind = 'value']) {
6815
+ export function nonTextMessage(ctx, slug, [name, value, kind = 'value']) {
4231
6816
  const type = ctx.C.typeOf(name);
4232
6817
  if (kind === 'mode') return ownPairMessage(slug, [name]);
4233
6818
  if (kind === 'object')
4234
- return `${slug}.theme.ts gives ${name} an object (${JSON.stringify(value)}); a token value is a CSS value in quotes, such as '8px' (only a color takes a [light, dark] pair).`;
6819
+ return `${slug}.theme.ts gives ${name} an object (${describeValue(value)}); a token value is a CSS value in quotes, such as '8px' (only a color takes a [light, dark] pair).`;
4235
6820
  if (kind === 'unit') {
4236
6821
  const n = /** @type {unknown[]} */ (value).find(
4237
6822
  x => typeof x === 'number' && x !== 0,
@@ -4250,7 +6835,7 @@ function nonTextMessage(ctx, slug, [name, value, kind = 'value']) {
4250
6835
  const shape = Array.isArray(value)
4251
6836
  ? 'a [light, dark] pair of two CSS values in quotes'
4252
6837
  : 'a CSS value in quotes';
4253
- return `${slug}.theme.ts gives ${name} the value ${JSON.stringify(value)}, which is not text: a token value is ${shape}${example ? ` (such as ${Array.isArray(value) ? `[${example}, ${example}]` : example})` : ''}.`;
6838
+ return `${slug}.theme.ts gives ${name} the value ${describeValue(value)}, which is not text: a token value is ${shape}${example ? ` (such as ${Array.isArray(value) ? `[${example}, ${example}]` : example})` : ''}.`;
4254
6839
  }
4255
6840
 
4256
6841
  /**
@@ -4383,6 +6968,39 @@ export async function contrastProblems(ctx, data, res) {
4383
6968
  );
4384
6969
  }
4385
6970
  }
6971
+ // Text of a part that sits in the app's top bar (one the census saw inside
6972
+ // the header region, or one the preview's own top bar draws) is measured
6973
+ // over the header's background too: a see-through background of its own
6974
+ // shows the header through it, not the page.
6975
+ /** @type {TextPair[]} */
6976
+ const headerPairs = [];
6977
+ const HEADER = 'app-shell-header';
6978
+ const census = /** @type {any} */ (ctx).parts;
6979
+ const grounds = [
6980
+ ...new Map(
6981
+ census.pairs
6982
+ .filter((/** @type {TextPair} */ p) => p.bg.target === HEADER)
6983
+ .map((/** @type {TextPair} */ p) => [
6984
+ p.bg.tokens.join('+') || p.bg.raw,
6985
+ p.bg,
6986
+ ]),
6987
+ ).values(),
6988
+ ];
6989
+ const inHeader = new Set([
6990
+ ...(census.map[HEADER]?.contains ?? []),
6991
+ ...TOP_BAR_COMPONENTS.map(kebab).filter(t => ctx.project.target.has(t)),
6992
+ ]);
6993
+ // A pair is in the top bar when the part whose background it sits on is
6994
+ // one there too (a segmented item on its control's track), or it paints
6995
+ // none of its own.
6996
+ for (const p of census.pairs)
6997
+ if (
6998
+ inHeader.has(p.text) &&
6999
+ p.bg.target !== HEADER &&
7000
+ (p.bg.target == null || inHeader.has(p.bg.target))
7001
+ )
7002
+ for (const over of grounds)
7003
+ headerPairs.push({...p, text: `${p.text} in the ${HEADER}`, over});
4386
7004
  const {problems, more, unchecked} = ctx.C.contrast(
4387
7005
  value,
4388
7006
  baseValue,
@@ -4395,12 +7013,12 @@ export async function contrastProblems(ctx, data, res) {
4395
7013
  page: m =>
4396
7014
  res[/** @type {'light' | 'dark'} */ (m)]['--color-background-body'],
4397
7015
  },
4398
- variantPairs,
7016
+ [...variantPairs, ...headerPairs],
4399
7017
  );
4400
7018
  return [
4401
7019
  ...problems.map(
4402
7020
  x =>
4403
- `text in ${x.part} ("${x.sample}") is ${x.ratio}:1 in ${x.mode} (${x.fg} on ${x.bgPart ?? 'the page'}'s ${x.bg}); text needs 4.5:1`,
7021
+ `text in ${x.part} ("${x.sample}") is ${x.ratio}:1 in ${x.mode} (${x.fg} on ${x.bgPart ?? 'the page'}'s ${x.bg}${x.over ? ` over ${x.over}` : ''}); text needs 4.5:1`,
4404
7022
  ),
4405
7023
  ...(more
4406
7024
  ? [`and ${more} more text pair${more > 1 ? 's' : ''} below 4.5:1`]
@@ -4442,18 +7060,191 @@ export async function contrastProblems(ctx, data, res) {
4442
7060
  * @returns {ThemeData | null}
4443
7061
  */
4444
7062
  function parseSettings(text) {
4445
- if (text == null) return null;
7063
+ const data = settingsJson(text);
7064
+ return entriesReadable(data) ? data : null;
7065
+ }
7066
+
7067
+ /**
7068
+ * A settings file's or an undo step's text as JSON, a byte-order mark
7069
+ * aside; undefined when there is no text or it does not parse. Every reader
7070
+ * of settings text reads it here.
7071
+ * @param {string | null | undefined} text
7072
+ * @returns {any}
7073
+ */
7074
+ export function settingsJson(text) {
7075
+ if (text == null) return undefined;
4446
7076
  try {
4447
- const data = JSON.parse(text);
4448
- return settingsShapeOk(data) ? data : null;
7077
+ return JSON.parse(text.replace(/^\uFEFF/, ''));
4449
7078
  } catch {
4450
- return null;
7079
+ return undefined;
7080
+ }
7081
+ }
7082
+
7083
+ /**
7084
+ * Whether settings data has its shape and every entry is an object with a
7085
+ * thing name: what a reader may go through entry by entry. Any other entry
7086
+ * (null, a number, text) is damage the file check names.
7087
+ * @param {any} data
7088
+ */
7089
+ export function entriesReadable(data) {
7090
+ return (
7091
+ settingsShapeOk(data) &&
7092
+ data.settings.every(
7093
+ (/** @type {any} */ s) =>
7094
+ s != null &&
7095
+ typeof s === 'object' &&
7096
+ !Array.isArray(s) &&
7097
+ typeof s.thing === 'string',
7098
+ )
7099
+ );
7100
+ }
7101
+
7102
+ /**
7103
+ * Read a damaged mode or base the way a change reads it, in place: one
7104
+ * written in other letters, as a package name, as a mode word or with a
7105
+ * typo (`Dark-Only`, `@astryxdesign/theme-neutral`, `light`, `neutrl`) is
7106
+ * the value meant, as `set` reads it. Any other is refused for a change
7107
+ * (slug given), with the line that sets it; read for an undo step, it goes
7108
+ * back to its default. `like: "none"` is no base. The field a command sets
7109
+ * itself is left to that command.
7110
+ * @param {any} data
7111
+ * @param {string} cwd
7112
+ * @param {string} [fixing] `mode` or `base` when the command sets it
7113
+ * @param {string} [slug] the theme a change is made to
7114
+ * @returns {string[]} a note for each field read differently from the file
7115
+ */
7116
+ export function readFields(data, cwd, fixing, slug) {
7117
+ /** @type {string[]} */
7118
+ const notes = [];
7119
+ const meant = fieldsMeant(data);
7120
+ // A field written as no value the reader can read: for a change (slug
7121
+ // given), refused with the line that sets it, never dropped on the way.
7122
+ // The lines offered set it again: the value it reads as when there is
7123
+ // one, else each value it can be (each installed base, each mode), never
7124
+ // a default that would drop what the file held.
7125
+ // A refusal about what the file holds, not what was typed: its lines
7126
+ // set the field again, and are not read against the typed value.
7127
+ const damaged = (
7128
+ /** @type {string} */ field,
7129
+ /** @type {string[]} */ fixes,
7130
+ ) => {
7131
+ throw Object.assign(
7132
+ new AstryxError(
7133
+ `themes/${slug}/${slug}.settings.json: ${field === 'mode' ? 'mode' : 'base'} "${field === 'mode' ? data.mode : data.like}" is no value the editor reads, and a change never drops it. Set it again. Nothing was changed.`,
7134
+ (fixes.length
7135
+ ? fixes.map(fix => `${P} set ${slug} ${field} ${fix}`)
7136
+ : [`${P} how ${field}`]
7137
+ ).map(name => ({name, reason: 'do this instead'})),
7138
+ ERROR_CODES.ERR_THEME_INVALID,
7139
+ ),
7140
+ {aboutSaved: true},
7141
+ );
7142
+ };
7143
+ if (
7144
+ fixing !== 'mode' &&
7145
+ !['both', 'light-only', 'dark-only'].includes(data.mode)
7146
+ ) {
7147
+ if (['both', 'light-only', 'dark-only'].includes(meant.mode)) {
7148
+ notes.push(
7149
+ `mode was written "${data.mode}", so it is saved as ${meant.mode}`,
7150
+ );
7151
+ data.mode = meant.mode;
7152
+ } else if (slug && data.mode != null && String(data.mode).trim()) {
7153
+ damaged('mode', ['both', 'light-only', 'dark-only']);
7154
+ } else {
7155
+ data.mode = 'both';
7156
+ notes.push('mode was missing or damaged, so it is both again');
7157
+ }
7158
+ }
7159
+ if (data.like === 'none') delete data.like;
7160
+ if (fixing !== 'base' && data.like != null && !LIKE.includes(data.like)) {
7161
+ if (LIKE.includes(meant.like) && baseInstalled(cwd, meant.like)) {
7162
+ notes.push(
7163
+ `base was written "${data.like}", so it is saved as ${meant.like}`,
7164
+ );
7165
+ data.like = meant.like;
7166
+ } else if (slug) {
7167
+ // The base the theme was built on, when its module or history still
7168
+ // says it; else each installed base.
7169
+ damaged(
7170
+ 'base',
7171
+ LIKE.includes(meant.like)
7172
+ ? [meant.like]
7173
+ : (b => (b ? [b] : LIKE.filter(x => baseInstalled(cwd, x))))(
7174
+ builtOnBase(cwd, slug),
7175
+ ),
7176
+ );
7177
+ } else {
7178
+ delete data.like;
7179
+ notes.push('base was not a built-in theme, so it is none again');
7180
+ }
4451
7181
  }
7182
+ return notes;
7183
+ }
7184
+
7185
+ /**
7186
+ * The text an undo step keeps for the settings before a change: the file
7187
+ * as the change read it (entry words and fields read as meant), so the
7188
+ * step back restores what the change started from and passes undo's check.
7189
+ * Text that reads as written is kept byte for byte.
7190
+ * @param {string} text
7191
+ * @param {string} cwd
7192
+ * @param {Record<string, string> | null} radii the whole-theme radii it was built with
7193
+ */
7194
+ function stepText(text, cwd, radii) {
7195
+ const data = settingsJson(text);
7196
+ if (!entriesReadable(data)) return text;
7197
+ const asWritten = JSON.stringify(data);
7198
+ readAsMeant(data, cwd);
7199
+ return JSON.stringify(data) !== asWritten
7200
+ ? `${JSON.stringify(radii ? {...data, built: {radii}} : data, null, 2)}\n`
7201
+ : withBuilt(text, radii);
7202
+ }
7203
+
7204
+ /**
7205
+ * Read settings data as a change reads it, in place: entry modes and
7206
+ * sources in other words, and a damaged mode or base (see
7207
+ * {@link readFields}). The settings file and every undo step are read
7208
+ * through here.
7209
+ * @param {any} data
7210
+ * @param {string} cwd
7211
+ * @param {string} [fixing] `mode` or `base` when the command sets it
7212
+ * @returns {string[]} a note for each thing read differently from the text
7213
+ */
7214
+ export function readAsMeant(data, cwd, fixing) {
7215
+ readEntryWords(data);
7216
+ return [...entryNotes(data), ...readFields(data, cwd, fixing)];
7217
+ }
7218
+
7219
+ /**
7220
+ * Whether `new` makes a theme again over these settings, keeping the file
7221
+ * aside: text that does not parse, or entries it cannot read (no thing, no
7222
+ * value, no source). The one rule both `new` and the refusals that offer
7223
+ * it read; any other damage is repaired by the lines its refusal names.
7224
+ * @param {unknown} data the parsed file (undefined when it does not parse)
7225
+ */
7226
+ export function settingsRemade(data) {
7227
+ return data === undefined || !settingsEntriesOk(data);
7228
+ }
7229
+
7230
+ /**
7231
+ * Whether every settings entry has the parts the editor reads (a thing, a
7232
+ * value and a source); one without is damage `new` keeps aside.
7233
+ * @param {any} data
7234
+ */
7235
+ export function settingsEntriesOk(data) {
7236
+ return (
7237
+ entriesReadable(data) &&
7238
+ data.settings.every(
7239
+ (/** @type {any} */ s) =>
7240
+ 'value' in s && ['dial', 'token', 'property'].includes(s.source),
7241
+ )
7242
+ );
4452
7243
  }
4453
7244
 
4454
7245
  /**
4455
- * Whether parsed settings have the shape the editor reads: an object with a
4456
- * list of settings.
7246
+ * Whether settings data has the shape the editor reads: an object with a
7247
+ * settings list.
4457
7248
  * @param {any} data
4458
7249
  */
4459
7250
  export function settingsShapeOk(data) {
@@ -4465,6 +7256,23 @@ export function settingsShapeOk(data) {
4465
7256
  );
4466
7257
  }
4467
7258
 
7259
+ /**
7260
+ * The settings as the file keeps them: a setting's `note` is what the
7261
+ * command that made it says in its result, not part of the setting.
7262
+ * @param {ThemeData} data
7263
+ * @returns {ThemeData}
7264
+ */
7265
+ function savedForm(data) {
7266
+ return {
7267
+ ...data,
7268
+ settings: data.settings.map(s => {
7269
+ const entry = {...s};
7270
+ delete entry.note;
7271
+ return entry;
7272
+ }),
7273
+ };
7274
+ }
7275
+
4468
7276
  /**
4469
7277
  * Every regular file under `dir` and the hash of its bytes; empty when
4470
7278
  * there is no folder.
@@ -4521,6 +7329,106 @@ export function focusStateOf(ctx, part) {
4521
7329
  return null;
4522
7330
  }
4523
7331
 
7332
+ /**
7333
+ * The radius token a part's corners follow when Core draws its corners one
7334
+ * by one from that token by position (a button squares the joins inside a
7335
+ * button group; a button group's outer corners are its end buttons'), or
7336
+ * null. A radius for such a part is written as that
7337
+ * token on the part, so every position keeps its own corner; a radius
7338
+ * written on the part would override Core's per-corner rules.
7339
+ * @param {Ctx} ctx
7340
+ * @param {string} part
7341
+ * @returns {string | null}
7342
+ */
7343
+ export function positionalCornerToken(ctx, part) {
7344
+ const own = ctx.C.MAP[part]?.own ?? {};
7345
+ for (const prop of [
7346
+ 'border-start-start-radius',
7347
+ 'border-start-end-radius',
7348
+ 'border-end-start-radius',
7349
+ 'border-end-end-radius',
7350
+ ]) {
7351
+ const e = own[prop];
7352
+ const token = Object.keys(e?.tokens ?? {}).find(t => /^--radius-/.test(t));
7353
+ if (token && (e.values ?? []).some((/** @type {string} */ v) => v === '0'))
7354
+ return token;
7355
+ }
7356
+ // A part with no corners of its own whose outer corners are the corners
7357
+ // Core draws by place on the parts inside it (a button group's first and
7358
+ // last buttons): the one token those read, set on the part.
7359
+ const inner = ctx.C.MAP[part]?.innerCorners ?? [];
7360
+ if (
7361
+ inner.length === 1 &&
7362
+ !Object.keys(own).some(k => /^border-.*radius$/.test(k))
7363
+ )
7364
+ return inner[0];
7365
+ return null;
7366
+ }
7367
+
7368
+ /** The radius tokens the corners dial moves. */
7369
+ export const DIAL_RADII = [
7370
+ '--radius-element',
7371
+ '--radius-inner',
7372
+ '--radius-container',
7373
+ '--radius-page',
7374
+ ];
7375
+
7376
+ /**
7377
+ * The parts that draw a part's corners: the part itself, or, when Core gives
7378
+ * it no radius of its own, the parts inside it that it has (a date-time
7379
+ * input's date and time boxes).
7380
+ * @param {Ctx} ctx
7381
+ * @param {string} part
7382
+ * @returns {string[]}
7383
+ */
7384
+ export function cornerParts(ctx, part) {
7385
+ const rec = ctx.C.MAP[part];
7386
+ if (!rec || rec.own?.['border-radius']) return [part];
7387
+ const inner = (rec.contains ?? []).filter(
7388
+ (/** @type {string} */ t) =>
7389
+ ctx.C.MAP[t]?.own?.['border-radius'] &&
7390
+ t.startsWith(`${part}-`) &&
7391
+ ctx.project.target.has(t),
7392
+ );
7393
+ return inner.length ? inner : [part];
7394
+ }
7395
+
7396
+ /** The table boxes CSS draws no padding on: rows, row groups and columns. */
7397
+ const UNPADDED_BOXES = new Set([
7398
+ 'tr',
7399
+ 'thead',
7400
+ 'tbody',
7401
+ 'tfoot',
7402
+ 'col',
7403
+ 'colgroup',
7404
+ ]);
7405
+
7406
+ /**
7407
+ * The parts that take a part's padding: the part itself, or, when Core
7408
+ * renders it as a box CSS draws no padding on (a table row) and gives it no
7409
+ * other display, the parts inside it with padding of their own (its cells).
7410
+ * @param {Ctx} ctx
7411
+ * @param {string} part
7412
+ * @returns {string[]}
7413
+ */
7414
+ export function paddedParts(ctx, part) {
7415
+ const rec = ctx.C.MAP[part];
7416
+ const tags = rec?.tags ?? [];
7417
+ if (
7418
+ !rec ||
7419
+ !tags.length ||
7420
+ !tags.every(t => UNPADDED_BOXES.has(t)) ||
7421
+ rec.own?.display
7422
+ )
7423
+ return [part];
7424
+ const inner = (rec.contains ?? []).filter(
7425
+ (/** @type {string} */ t) =>
7426
+ ctx.project.target.has(t) &&
7427
+ Object.keys(ctx.C.MAP[t]?.own ?? {}).some(k => /^padding/.test(k)),
7428
+ );
7429
+ return inner.length ? inner : [part];
7430
+ }
7431
+
4524
7432
  /**
4525
7433
  * The radius token a part's resting corners read. A part the census saw
4526
7434
  * closed (a menu, a popover) has none recorded: a container or menu reads
@@ -4583,6 +7491,47 @@ export function stateKey(state, wrapsControl = false) {
4583
7491
  : ':is(:disabled,[aria-disabled="true"])';
4584
7492
  }
4585
7493
 
7494
+ /**
7495
+ * The text color tokens Core's elements inside a part read for their own
7496
+ * color (a top nav heading's title span reads --color-text-primary itself),
7497
+ * so a color set on the part never reaches that text. Only the main and
7498
+ * supporting text colors count: the disabled, placeholder and accent ones
7499
+ * mark a state or a role, not the part's text. With `deep`, the parts inside
7500
+ * it count too (a top nav's heading and items).
7501
+ * @param {{MAP: Record<string, any>}} C
7502
+ * @param {string} part
7503
+ * @param {boolean} [deep]
7504
+ * @returns {string[]}
7505
+ */
7506
+ export function innerTextTokens(C, part, deep = false) {
7507
+ const TEXT_ROLES = ['--color-text-primary', '--color-text-secondary'];
7508
+ /** @type {Set<string>} */
7509
+ const out = new Set();
7510
+ /** @param {Record<string, string[]> | undefined} reads */
7511
+ const add = reads => {
7512
+ for (const [tok, props] of Object.entries(reads ?? {}))
7513
+ if (TEXT_ROLES.includes(tok) && props.includes('color')) out.add(tok);
7514
+ };
7515
+ const rec = C.MAP[part];
7516
+ add(rec?.inside);
7517
+ if (deep)
7518
+ for (const inner of rec?.contains ?? []) {
7519
+ const r = C.MAP[inner];
7520
+ add(r?.inside);
7521
+ // A part's own color counts where it reads the token always, not
7522
+ // only in a variant or a state.
7523
+ for (const [tok, conds] of Object.entries(r?.own?.color?.tokens ?? {}))
7524
+ if (
7525
+ TEXT_ROLES.includes(tok) &&
7526
+ /** @type {string[]} */ (conds).some(
7527
+ w => !w.trim() || w.trim() === 'always',
7528
+ )
7529
+ )
7530
+ out.add(tok);
7531
+ }
7532
+ return [...out].sort();
7533
+ }
7534
+
4586
7535
  /**
4587
7536
  * The component docs of a part: its own component's, and the one named like
4588
7537
  * the part (tab is Tab, under TabList), each with its name, for the ones the
@@ -4651,13 +7600,9 @@ export function radiiIn(source) {
4651
7600
  */
4652
7601
  function withBuilt(text, radii) {
4653
7602
  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
- }
7603
+ const data = settingsJson(text);
7604
+ if (!settingsShapeOk(data)) return text;
7605
+ return `${JSON.stringify({...data, built: {radii}}, null, 2)}\n`;
4661
7606
  }
4662
7607
 
4663
7608
  /**
@@ -4710,6 +7655,37 @@ export function radiusAt(base, value, token) {
4710
7655
  * editor's header).
4711
7656
  * @param {string} file
4712
7657
  */
7658
+ /**
7659
+ * Whether the editor made a theme's folder, though its settings may be
7660
+ * gone: a stopped `new` left its marker, or the folder holds what only the
7661
+ * editor writes (the generated settings module, an undo history, the theme
7662
+ * source with the header the editor wrote it with).
7663
+ * @param {string} cwd
7664
+ * @param {string} slug
7665
+ */
7666
+ export function editorMadeFolder(cwd, slug) {
7667
+ const f = themeFiles(cwd, slug);
7668
+ const firstLine = (/** @type {string} */ file) => {
7669
+ try {
7670
+ return fs.readFileSync(file, 'utf8').split('\n', 1)[0];
7671
+ } catch {
7672
+ return '';
7673
+ }
7674
+ };
7675
+ return (
7676
+ fs.existsSync(path.join(f.dir, NEW_MARKER)) ||
7677
+ madeByEditor(f.settingsTs) ||
7678
+ // Only editor commands write the undo history.
7679
+ readHistory(f.history).steps.length > 0 ||
7680
+ firstLine(f.ts) ===
7681
+ `// The ${slug} theme. \`${P}\` wrote this file once and never changes it again.`
7682
+ );
7683
+ }
7684
+
7685
+ /**
7686
+ * Whether a file carries the editor's generated header.
7687
+ * @param {string} file
7688
+ */
4713
7689
  export function madeByEditor(file) {
4714
7690
  try {
4715
7691
  return fs
@@ -4939,12 +7915,15 @@ export function refuseLinks(cwd, slug) {
4939
7915
  * @param {ThemeData} data
4940
7916
  */
4941
7917
  export function settingsStamp(data) {
7918
+ // The settings as the file keeps them, so the stamp of a build matches
7919
+ // the file it was built from.
7920
+ const saved = savedForm(data);
4942
7921
  const hash = createHash('sha256')
4943
7922
  .update(
4944
7923
  JSON.stringify({
4945
- like: data.like ?? null,
4946
- mode: data.mode,
4947
- settings: data.settings,
7924
+ like: saved.like ?? null,
7925
+ mode: saved.mode,
7926
+ settings: saved.settings,
4948
7927
  }),
4949
7928
  )
4950
7929
  .digest('hex')
@@ -5052,7 +8031,9 @@ export function builtFiles(cwd, slug, data, some = false) {
5052
8031
  const colors = data.settings.some(
5053
8032
  s => s.source === 'dial' && PALETTE_DIALS.includes(s.thing),
5054
8033
  )
5055
- ? [pal.palette, pal.refs, pal.receipt].map(p => path.join(cwd, p))
8034
+ ? [pal.config, pal.palette, pal.refs, pal.receipt].map(p =>
8035
+ path.join(cwd, p),
8036
+ )
5056
8037
  : [];
5057
8038
  return [
5058
8039
  f.settingsTs,
@@ -5067,6 +8048,21 @@ export function builtFiles(cwd, slug, data, some = false) {
5067
8048
  ];
5068
8049
  }
5069
8050
 
8051
+ /**
8052
+ * The file's stat, or undefined when it is not there. On Node 22.13 a folder
8053
+ * above the file that is a file throws ENOTDIR even with throwIfNoEntry
8054
+ * false; that file is not there either, as on later Node.
8055
+ * @param {string} file
8056
+ */
8057
+ function statIfThere(file) {
8058
+ try {
8059
+ return fs.statSync(file, {throwIfNoEntry: false});
8060
+ } catch (e) {
8061
+ if (/** @type {any} */ (e)?.code === 'ENOTDIR') return undefined;
8062
+ throw e;
8063
+ }
8064
+ }
8065
+
5070
8066
  /**
5071
8067
  * Refuse, by name, a built file that is there but cannot be read: its
5072
8068
  * permissions, or a folder where the file goes.
@@ -5075,7 +8071,7 @@ export function builtFiles(cwd, slug, data, some = false) {
5075
8071
  */
5076
8072
  function refuseUnreadable(cwd, files) {
5077
8073
  for (const file of files) {
5078
- const st = fs.statSync(file, {throwIfNoEntry: false});
8074
+ const st = statIfThere(file);
5079
8075
  if (!st) continue;
5080
8076
  const rel = shown(cwd, file);
5081
8077
  if (st.isDirectory())
@@ -5166,10 +8162,7 @@ export function readHistory(file) {
5166
8162
  if (!Array.isArray(h)) return {steps: [], dropped: 1};
5167
8163
  const ok = (/** @type {unknown} */ x) => {
5168
8164
  try {
5169
- return (
5170
- typeof x === 'string' &&
5171
- Array.isArray(JSON.parse(x.replace(/^\uFEFF/, '')).settings)
5172
- );
8165
+ return typeof x === 'string' && settingsShapeOk(settingsJson(x));
5173
8166
  } catch {
5174
8167
  return false;
5175
8168
  }
@@ -5204,7 +8197,7 @@ export async function commitTheme(
5204
8197
  const {cwd} = ctx.project;
5205
8198
  const f = themeFiles(cwd, slug);
5206
8199
  refuseLinks(cwd, slug);
5207
- refuseThemeSource(cwd, slug);
8200
+ await refuseThemeSource(cwd, slug);
5208
8201
  const snapBefore = fs.existsSync(f.settings)
5209
8202
  ? fs.readFileSync(f.settings, 'utf8')
5210
8203
  : null;
@@ -5225,8 +8218,8 @@ export async function commitTheme(
5225
8218
  // no undo step.
5226
8219
  const same = (/** @type {ThemeData | null} */ a) =>
5227
8220
  a != null &&
5228
- JSON.stringify({...a, lifted: undefined}) ===
5229
- JSON.stringify({...data, lifted: undefined});
8221
+ JSON.stringify({...savedForm(a), lifted: undefined}) ===
8222
+ JSON.stringify({...savedForm(data), lifted: undefined});
5230
8223
  // A no-op change still mends a build that does not match the settings
5231
8224
  // (an undo stopped part way): it is built again, with no new step.
5232
8225
  const noop = history && same(parseSettings(snapBefore));
@@ -5324,7 +8317,7 @@ export async function commitTheme(
5324
8317
  const wrote = new Map();
5325
8318
  ctx.wrote = wrote;
5326
8319
  fs.mkdirSync(f.dir, {recursive: true});
5327
- /** @type {{warnings: string[], lifted: string[], notes: string[]}} */
8320
+ /** @type {{warnings: string[], lifted: string[], notes: string[], removedPictures: string[]}} */
5328
8321
  let built;
5329
8322
  // The token loops the last build had, so a change that adds one (through
5330
8323
  // tokens the own source sets in a way no read of the file follows) is
@@ -5361,7 +8354,7 @@ export async function commitTheme(
5361
8354
  // for an undo, a top step equal to the settings, which undo skips),
5362
8355
  // never a step that undoes nothing or a lost step.
5363
8356
  await track(f.dir, wrote, () => {
5364
- writeWhole(f.settings, `${JSON.stringify(data, null, 2)}\n`);
8357
+ writeWhole(f.settings, `${JSON.stringify(savedForm(data), null, 2)}\n`);
5365
8358
  if (historyAfter)
5366
8359
  writeWhole(
5367
8360
  f.history,
@@ -5371,7 +8364,9 @@ export async function commitTheme(
5371
8364
  writeWhole(
5372
8365
  f.history,
5373
8366
  JSON.stringify(
5374
- [...past, withBuilt(snapBefore, radiiNow)].slice(-HISTORY_STEPS),
8367
+ [...past, stepText(snapBefore, cwd, radiiNow)].slice(
8368
+ -HISTORY_STEPS,
8369
+ ),
5375
8370
  ),
5376
8371
  );
5377
8372
  });
@@ -5536,31 +8531,95 @@ export async function commitTheme(
5536
8531
  };
5537
8532
  }
5538
8533
 
5539
- /** @param {Ctx} ctx @param {ThemeData} data */
5540
- export function fontPackages(ctx, data) {
5541
- /** @type {Array<{pkg: string, family: string, installed: boolean, of: Setting}>} */
8534
+ /**
8535
+ * The @fontsource package for a font family: an open font's own package
8536
+ * as the editor's font table names it (Geist is `@fontsource/geist-sans`),
8537
+ * else the family's name in Fontsource's form (`Open Sans` is
8538
+ * `@fontsource/open-sans`).
8539
+ * @param {string} family
8540
+ * @returns {string}
8541
+ */
8542
+ export function fontsourcePackageOf(family) {
8543
+ const name = cssUnescape(String(family).replace(/["']/g, '')).trim();
8544
+ const open = Object.values(OPEN_FONTS).find(
8545
+ f =>
8546
+ f.family.replace(/["']/g, '').trim().toLowerCase() === name.toLowerCase(),
8547
+ );
8548
+ return open?.pkg ?? `@fontsource/${name.toLowerCase().replace(/\s+/g, '-')}`;
8549
+ }
8550
+
8551
+ /**
8552
+ * The font families the theme's last build names (its `--font-family-*`
8553
+ * tokens, every part's `font-family`, and a `font` shorthand's families), by lowercase name; null before the
8554
+ * theme has been built.
8555
+ * @param {Ctx} ctx
8556
+ * @param {string} slug
8557
+ * @returns {Map<string, string> | null}
8558
+ */
8559
+ export function builtFontFamilies(ctx, slug) {
8560
+ /** @type {string} */
8561
+ let css;
8562
+ try {
8563
+ css = fs.readFileSync(themeFiles(ctx.project.cwd, slug).css, 'utf8');
8564
+ } catch {
8565
+ return null;
8566
+ }
8567
+ /** @type {Map<string, string>} */
8568
+ const out = new Map();
8569
+ // Every family the build writes: the font tokens, a part's own
8570
+ // font-family, the families a `font` shorthand names last, and a family
8571
+ // held in the theme's own property that one of those reads.
8572
+ // A var() of the theme's own property reads as each value it sets.
8573
+ const own = customPropertyValues(css);
8574
+ const lists = [
8575
+ ...declarationValues(css, /^(--font-family-.*|font-family)$/),
8576
+ ...declarationValues(css, /^font$/).map(fontShorthandFamilyList),
8577
+ ].flatMap(value => expandFontVars(value, name => own.get(name) ?? []));
8578
+ for (const value of lists)
8579
+ for (const family of namedFontFamilies(value))
8580
+ if (!out.has(family.toLowerCase())) out.set(family.toLowerCase(), family);
8581
+ return out;
8582
+ }
8583
+
8584
+ /**
8585
+ * The font packages that load the families the theme builds: a font
8586
+ * setting's package while the build still uses its family, and the
8587
+ * installed @fontsource package of a family the theme's own source sets.
8588
+ * Font notes, the previews and the app copy all load fonts from this list.
8589
+ * For a new app that installs its own packages (`forNewApp`), every built
8590
+ * family that is an open font comes too, installed here or not.
8591
+ * @param {Ctx} ctx
8592
+ * @param {ThemeData} data
8593
+ * @param {{forNewApp?: boolean}} [opts]
8594
+ */
8595
+ export function fontPackages(ctx, data, {forNewApp = false} = {}) {
8596
+ /** @type {Array<{pkg: string, family: string, installed: boolean, of: Setting | null}>} */
5542
8597
  const out = [];
5543
8598
  /** @param {string} pkg */
5544
- const isInstalled = pkg => {
5545
- try {
5546
- ctx.project.req.resolve(`${pkg}/package.json`);
5547
- return true;
5548
- } catch {
5549
- return false;
5550
- }
5551
- };
8599
+ const isInstalled = pkg => packageInstalled(ctx.project.cwd, pkg);
8600
+ /** An open font's package, which a new app installs. @param {string} pkg */
8601
+ const isOpen = pkg => Object.values(OPEN_FONTS).some(f => f.pkg === pkg);
8602
+ /** Whether a package loads its family where the fonts go. @param {string} pkg */
8603
+ const loads = pkg => isInstalled(pkg) || (forNewApp && isOpen(pkg));
8604
+ const built = builtFontFamilies(ctx, data.name);
5552
8605
  for (const s of data.settings) {
5553
8606
  if (s.thing !== 'font') continue;
5554
8607
  const {pkg: known, family} = fontOf(s.value);
5555
8608
  const name = family.replace(/["']/g, '');
8609
+ // A family the theme's own source replaced everywhere it was set is
8610
+ // not in the build: nothing loads it.
8611
+ if (built && !built.has(name.toLowerCase())) continue;
5556
8612
  // An installed @fontsource package of the family always loads it, even
5557
8613
  // for a family some systems ship.
5558
- const own = `@fontsource/${name.toLowerCase().replace(/\s+/g, '-')}`;
5559
- const pkg = known ?? (isInstalled(own) ? own : null);
8614
+ const own = fontsourcePackageOf(name);
8615
+ const pkg = known ?? (loads(own) ? own : null);
5560
8616
  if (!pkg || out.some(x => x.pkg === pkg)) continue;
5561
8617
  out.push({pkg, family: name, installed: isInstalled(pkg), of: s});
5562
8618
  }
8619
+ for (const family of built?.values() ?? []) {
8620
+ const pkg = fontsourcePackageOf(family);
8621
+ if (out.some(x => x.pkg === pkg) || !loads(pkg)) continue;
8622
+ out.push({pkg, family, installed: isInstalled(pkg), of: null});
8623
+ }
5563
8624
  return out;
5564
8625
  }
5565
-
5566
- export {partDefault};