@astryxdesign/cli 0.7.16 → 0.7.17-canary.g0404a74

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 (529) hide show
  1. package/README.md +76 -86
  2. package/api/build/_adapter.d.mts +17 -0
  3. package/api/build/_adapter.mjs +53 -34
  4. package/api/build/blocks/blocks.d.mts +7 -5
  5. package/api/build/blocks/blocks.mjs +113 -26
  6. package/api/build/blocks/blocks.weights.json +1 -1
  7. package/api/build/build.doc.mjs +4 -3
  8. package/api/build/build.type.d.mts +2 -2
  9. package/api/build/build.type.mjs +3 -3
  10. package/api/build/kit/kind.d.mts +2 -1
  11. package/api/build/kit/kind.mjs +199 -10
  12. package/api/build/kit/kit.mjs +6 -4
  13. package/api/build/kit/rank.d.mts +6 -4
  14. package/api/build/kit/rank.mjs +132 -28
  15. package/api/build/kit/signals.d.mts +7 -1
  16. package/api/build/kit/signals.mjs +21 -10
  17. package/api/build/kit/start.d.mts +5 -4
  18. package/api/build/kit/start.mjs +14 -9
  19. package/api/build/kit/weights.d.mts +39 -3
  20. package/api/build/kit/weights.json +1 -1
  21. package/api/build/kit/weights.mjs +351 -46
  22. package/api/build/kit/word-model.d.mts +23 -0
  23. package/api/build/kit/word-model.mjs +46 -0
  24. package/api/build/kit/words.d.mts +86 -0
  25. package/api/build/kit/words.mjs +241 -1
  26. package/api/build/tree.mjs +1 -1
  27. package/api/component/__fixtures__/resolutions/modules.txt +5 -6
  28. package/api/component/_adapter.d.mts +26 -2
  29. package/api/component/_adapter.mjs +135 -8
  30. package/api/component/component.mjs +14 -1
  31. package/api/component/list/list.d.mts +1 -1
  32. package/api/component/list/list.mjs +48 -6
  33. package/api/discover/_adapter.d.mts +11 -1
  34. package/api/discover/_adapter.mjs +95 -1
  35. package/api/discover/detail/item/item.mjs +5 -0
  36. package/api/discover/discover.mjs +12 -3
  37. package/api/discover/discover.type.d.mts +16 -3
  38. package/api/discover/discover.type.mjs +13 -3
  39. package/api/discover/search/search.mjs +3 -2
  40. package/api/docs/_adapter.d.mts +57 -2
  41. package/api/docs/_adapter.mjs +266 -33
  42. package/api/docs/_entry-names-lazily.d.mts +22 -0
  43. package/api/docs/_entry-names-lazily.mjs +25 -0
  44. package/api/docs/_entry-names.d.mts +23 -0
  45. package/api/docs/_entry-names.mjs +105 -0
  46. package/api/docs/docs.d.mts +3 -0
  47. package/api/docs/docs.doc.mjs +7 -1
  48. package/api/docs/docs.mjs +12 -0
  49. package/api/docs/docs.type.d.mts +5 -0
  50. package/api/docs/docs.type.mjs +2 -0
  51. package/api/docs/node/node.mjs +1 -1
  52. package/api/doctor/_adapter.d.mts +54 -5
  53. package/api/doctor/_adapter.mjs +162 -11
  54. package/api/doctor/built-checks.mjs +40 -14
  55. package/api/doctor/doctor.d.mts +15 -3
  56. package/api/doctor/doctor.doc.mjs +1 -1
  57. package/api/doctor/doctor.mjs +31 -7
  58. package/api/doctor/theme-checks.d.mts +35 -3
  59. package/api/doctor/theme-checks.mjs +377 -29
  60. package/api/hook/_adapter.d.mts +10 -4
  61. package/api/hook/_adapter.mjs +41 -5
  62. package/api/hook/detail/detail.mjs +5 -2
  63. package/api/hook/detail/params/params.mjs +10 -3
  64. package/api/icon/_records.mjs +2 -1
  65. package/api/index.d.mts +2 -0
  66. package/api/index.mjs +2 -0
  67. package/api/integration/_adapter.d.mts +44 -0
  68. package/api/integration/_adapter.mjs +77 -1
  69. package/api/integration/add-helpers.mjs +10 -0
  70. package/api/integration/authoring-checks.mjs +11 -8
  71. package/api/integration/example-scope.d.mts +14 -0
  72. package/api/integration/example-scope.mjs +44 -0
  73. package/api/integration/example-scope.type.d.mts +29 -0
  74. package/api/integration/example-scope.type.mjs +25 -0
  75. package/api/integration/integrationExampleScope.doc.d.mts +11 -0
  76. package/api/integration/integrationExampleScope.doc.mjs +59 -0
  77. package/api/integration/pack-check.mjs +16 -1
  78. package/api/integration/validate-integration.d.mts +18 -6
  79. package/api/integration/validate-integration.mjs +129 -15
  80. package/api/integration/validate-integration.type.d.mts +22 -0
  81. package/api/integration/validate-integration.type.mjs +2 -1
  82. package/api/integration/validateIntegration.doc.mjs +1 -1
  83. package/api/render/_adapter.mjs +591 -195
  84. package/api/render/render.doc.mjs +11 -3
  85. package/api/render/render.type.d.mts +53 -1
  86. package/api/render/render.type.mjs +32 -2
  87. package/api/search/ORDERING.md +2 -2
  88. package/api/search/_adapter.d.mts +9 -0
  89. package/api/search/_adapter.mjs +85 -0
  90. package/api/search/_candidate-score.d.mts +9 -4
  91. package/api/search/_candidate-score.mjs +133 -46
  92. package/api/search/_fit-order.mjs +3 -3
  93. package/api/search/_gather-components.d.mts +3 -2
  94. package/api/search/_gather-components.mjs +12 -3
  95. package/api/search/_lexical.d.mts +14 -0
  96. package/api/search/_lexical.mjs +93 -11
  97. package/api/search/_result.d.mts +11 -9
  98. package/api/search/_result.mjs +4 -4
  99. package/api/search/_score.d.mts +6 -1
  100. package/api/search/_score.mjs +15 -3
  101. package/api/search/search-index.mjs +7 -1
  102. package/api/search/search.d.mts +1 -1
  103. package/api/template/_adapter.d.mts +16 -0
  104. package/api/template/_adapter.mjs +39 -2
  105. package/api/template/cdn/cdn.mjs +37 -8
  106. package/api/template/copy/copy.d.mts +6 -3
  107. package/api/template/copy/copy.mjs +40 -8
  108. package/api/template/template.doc.mjs +3 -3
  109. package/api/template/template.mjs +63 -11
  110. package/api/template/template.type.d.mts +1 -0
  111. package/api/template/template.type.mjs +1 -0
  112. package/api/theme/_adapter.d.mts +12 -1
  113. package/api/theme/_adapter.mjs +132 -13
  114. package/api/theme/_app-provider.d.mts +31 -0
  115. package/api/theme/_app-provider.mjs +135 -0
  116. package/api/theme/add/add.mjs +3 -1
  117. package/api/theme/build/build.d.mts +142 -1
  118. package/api/theme/build/build.mjs +692 -284
  119. package/api/theme/build/core-interception.d.mts +10 -0
  120. package/api/theme/build/core-interception.mjs +10 -0
  121. package/api/theme/build/font-warning.d.mts +80 -5
  122. package/api/theme/build/font-warning.mjs +323 -55
  123. package/api/theme/build/icon-imports.mjs +51 -9
  124. package/api/theme/build/null-values.d.mts +28 -0
  125. package/api/theme/build/null-values.mjs +191 -0
  126. package/api/theme/list/list.mjs +17 -1
  127. package/api/theme/remove/remove.d.mts +2 -1
  128. package/api/theme/remove/remove.mjs +7 -3
  129. package/api/theme/theme.type.d.mts +78 -1
  130. package/api/theme/theme.type.mjs +38 -2
  131. package/api/theme/themeAdd.doc.mjs +1 -1
  132. package/api/theme/themeListAvailable.doc.mjs +1 -1
  133. package/api/theme/themeRemove.doc.mjs +8 -5
  134. package/api/theme-edit/_adapter.d.mts +116 -4
  135. package/api/theme-edit/_adapter.mjs +1058 -93
  136. package/api/theme-edit/_catalog.d.mts +46 -2
  137. package/api/theme-edit/_catalog.mjs +115 -14
  138. package/api/theme-edit/_check.d.mts +133 -24
  139. package/api/theme-edit/_check.mjs +3392 -531
  140. package/api/theme-edit/_color.d.mts +26 -0
  141. package/api/theme-edit/_color.mjs +92 -2
  142. package/api/theme-edit/_compiler.d.mts +5 -1
  143. package/api/theme-edit/_compiler.mjs +141 -17
  144. package/api/theme-edit/_context.d.mts +74 -6
  145. package/api/theme-edit/_context.mjs +468 -76
  146. package/api/theme-edit/_css.d.mts +21 -0
  147. package/api/theme-edit/_css.mjs +87 -14
  148. package/api/theme-edit/_edit.d.mts +74 -7
  149. package/api/theme-edit/_edit.mjs +4426 -319
  150. package/api/theme-edit/_how-commands.d.mts +76 -1
  151. package/api/theme-edit/_how-commands.mjs +793 -9
  152. package/api/theme-edit/_how-question.d.mts +97 -6
  153. package/api/theme-edit/_how-question.mjs +9184 -747
  154. package/api/theme-edit/_how.d.mts +5 -2
  155. package/api/theme-edit/_how.mjs +255 -46
  156. package/api/theme-edit/_importers.d.mts +38 -0
  157. package/api/theme-edit/_importers.mjs +188 -0
  158. package/api/theme-edit/_marks.d.mts +31 -5
  159. package/api/theme-edit/_marks.mjs +57 -5
  160. package/api/theme-edit/_name-rule.d.mts +11 -0
  161. package/api/theme-edit/_name-rule.mjs +12 -0
  162. package/api/theme-edit/_normal.d.mts +322 -0
  163. package/api/theme-edit/_normal.mjs +1630 -0
  164. package/api/theme-edit/_palette.d.mts +49 -0
  165. package/api/theme-edit/_palette.mjs +180 -38
  166. package/api/theme-edit/_part-words.d.mts +39 -0
  167. package/api/theme-edit/_part-words.mjs +152 -0
  168. package/api/theme-edit/_parts.d.mts +55 -3
  169. package/api/theme-edit/_parts.mjs +421 -36
  170. package/api/theme-edit/_preview-app.d.mts +7 -13
  171. package/api/theme-edit/_preview-app.mjs +1108 -599
  172. package/api/theme-edit/_preview.d.mts +156 -19
  173. package/api/theme-edit/_preview.mjs +809 -180
  174. package/api/theme-edit/_project.d.mts +61 -1
  175. package/api/theme-edit/_project.mjs +177 -6
  176. package/api/theme-edit/_settings.d.mts +619 -48
  177. package/api/theme-edit/_settings.mjs +4910 -617
  178. package/api/theme-edit/_tables.d.mts +41 -0
  179. package/api/theme-edit/_tables.mjs +261 -41
  180. package/api/theme-edit/_vet.d.mts +31 -0
  181. package/api/theme-edit/_vet.mjs +114 -8
  182. package/api/theme-edit/theme-edit.type.d.mts +34 -2
  183. package/api/theme-edit/theme-edit.type.mjs +18 -3
  184. package/api/theme-edit/themeEditHow.doc.mjs +1 -1
  185. package/api/theme-edit/themeEditNew.doc.d.mts +0 -1
  186. package/api/theme-edit/themeEditNew.doc.mjs +7 -4
  187. package/api/theme-edit/themeEditPreviewApp.doc.mjs +3 -3
  188. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +2 -2
  189. package/api/upgrade/run/run.mjs +4 -3
  190. package/api/upgrade/upgrade.mjs +16 -1
  191. package/assets/codemods/integration-discovery.mjs +2 -1
  192. package/assets/codemods/integration-runner.mjs +1 -1
  193. package/assets/codemods/jscodeshift.d.ts +1 -1
  194. package/assets/codemods/run-codemod.mjs +151 -18
  195. package/assets/codemods/runner.mjs +1 -4
  196. package/assets/codemods/transforms/next/index.mjs +11 -1
  197. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  198. package/assets/component-list.generated.json +1 -0
  199. package/assets/docs/author-a-theme.doc.mjs +2 -0
  200. package/assets/docs/theme.doc.dense.mjs +76 -7
  201. package/assets/docs/theme.doc.mjs +66 -2
  202. package/assets/docs/theme.doc.zh.mjs +51 -1
  203. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  204. package/assets/docs/tree/checks.doc.mjs +2 -2
  205. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  206. package/assets/docs/tree/document-the-theme.doc.mjs +1 -1
  207. package/assets/docs/tree/font-setup.doc.mjs +1 -1
  208. package/assets/docs/tree/fonts-and-assets.doc.mjs +1 -1
  209. package/assets/docs/tree/render-pages.doc.mjs +46 -5
  210. package/assets/docs/tree/share-a-page.doc.mjs +157 -0
  211. package/assets/docs/tree/single-component.doc.mjs +4 -0
  212. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  213. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  214. package/assets/docs/tree/write-good-templates.doc.mjs +1 -1
  215. package/assets/docs/use-a-theme.doc.mjs +2 -2
  216. package/assets/docs-routes.generated.json +1 -0
  217. package/assets/docs.generated.json +2 -2
  218. package/assets/search-catalog.generated.json +2 -0
  219. package/assets/self-audit.generated.json +1 -1
  220. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  221. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  222. package/assets/templates/blocks/components/ChatComposerInput/useSpeechRecognitionHookUsage.doc.mjs +14 -0
  223. package/assets/templates/blocks/components/ChatComposerInput/useSpeechRecognitionHookUsage.tsx +43 -0
  224. package/assets/templates/blocks/components/Hooks/useContainerRevealHookUsage.tsx +2 -2
  225. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  226. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  227. package/assets/templates/components.generated.json +1 -1
  228. package/assets/templates/pages/ai-chat/template.doc.mjs +5 -4
  229. package/assets/templates/pages/ai-chat-landing/page.tsx +31 -4
  230. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +5 -1
  231. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  232. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  233. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  234. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  235. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  236. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  237. package/assets/templates/pages/dashboard-alert-rail/page.tsx +1 -1
  238. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  239. package/assets/templates/pages/dashboard-cohort-funnel/page.tsx +1 -1
  240. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  241. package/assets/templates/pages/dashboard-comparison/page.tsx +2 -2
  242. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  243. package/assets/templates/pages/dashboard-progress/page.tsx +1 -1
  244. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  245. package/assets/templates/pages/detail-page/page.tsx +60 -7
  246. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  247. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  248. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  249. package/assets/templates/pages/documentation-technical/page.tsx +13 -13
  250. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  251. package/assets/templates/pages/editor/page.tsx +14 -2
  252. package/assets/templates/pages/editor/template.doc.mjs +2 -8
  253. package/assets/templates/pages/file-explorer/page.tsx +9 -0
  254. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  255. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  256. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  257. package/assets/templates/pages/form-wizard-vertical/page.tsx +23 -3
  258. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  259. package/assets/templates/pages/ide/page.tsx +33 -2
  260. package/assets/templates/pages/kanban-board/page.tsx +12 -2
  261. package/assets/templates/pages/kanban-board/template.doc.mjs +1 -9
  262. package/assets/templates/pages/library/template.doc.mjs +4 -1
  263. package/assets/templates/pages/login/template.doc.mjs +2 -1
  264. package/assets/templates/pages/login-card/page.tsx +16 -0
  265. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  266. package/assets/templates/pages/login-split/page.tsx +19 -6
  267. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  268. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  269. package/assets/templates/pages/messaging-shell/template.doc.mjs +6 -0
  270. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  271. package/assets/templates/pages/payment-form/page.tsx +30 -4
  272. package/assets/templates/pages/product-detail/page.tsx +26 -2
  273. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  274. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  275. package/assets/templates/pages/settings-dialog/page.tsx +162 -12
  276. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  277. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  278. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  279. package/assets/templates/pages/shell-side-nav/page.tsx +11 -3
  280. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  281. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  282. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  283. package/assets/templates/pages/table-filter/page.tsx +9 -0
  284. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  285. package/assets/templates/pages/table-grouped/page.tsx +161 -133
  286. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  287. package/assets/templates/pages/table-page/page.tsx +14 -1
  288. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  289. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  290. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -9
  291. package/assets/templates/pages/work-item-detail/page.tsx +47 -7
  292. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  293. package/assets/theme.template.ts +9 -2
  294. package/authoring/debug/parse.d.mts +3 -3
  295. package/authoring/doctypes/_schema.d.mts +9 -9
  296. package/authoring/doctypes/command/command.doc.mjs +1 -1
  297. package/authoring/doctypes/component/categories.d.mts +37 -0
  298. package/authoring/doctypes/component/categories.mjs +54 -0
  299. package/authoring/doctypes/template/template.doc.mjs +1 -1
  300. package/authoring/doctypes/template/type.ts +9 -0
  301. package/authoring/example/example.doc.d.mts +12 -0
  302. package/authoring/example/example.doc.mjs +69 -0
  303. package/authoring/example/preview.d.mts +92 -0
  304. package/authoring/example/preview.mjs +994 -0
  305. package/authoring/example/type.ts +102 -0
  306. package/authoring/index.d.mts +1 -0
  307. package/authoring/index.d.ts +12 -0
  308. package/authoring/index.mjs +3 -1
  309. package/authoring/integration/integration.doc.mjs +8 -0
  310. package/authoring/integration/schema.d.mts +24 -1
  311. package/authoring/integration/schema.mjs +126 -4
  312. package/authoring/integration/type.ts +14 -0
  313. package/clients/cli/bin/astryx.mjs +6 -9
  314. package/clients/cli/build-id.generated.json +1 -1
  315. package/clients/cli/commands/component.doc.mjs +1 -1
  316. package/clients/cli/commands/component.mjs +22 -3
  317. package/clients/cli/commands/discover.mjs +70 -3
  318. package/clients/cli/commands/docs.doc.mjs +7 -1
  319. package/clients/cli/commands/docs.mjs +44 -6
  320. package/clients/cli/commands/doctor.mjs +84 -16
  321. package/clients/cli/commands/experimental/render.mjs +42 -1
  322. package/clients/cli/commands/experimental/theme.mjs +1032 -134
  323. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  324. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  325. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +87 -1
  326. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +10 -3
  327. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +2 -2
  328. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +2 -2
  329. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  330. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  331. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +2 -2
  332. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  333. package/clients/cli/commands/experimental-theme-preview.doc.mjs +2 -1
  334. package/clients/cli/commands/experimental-theme-remove.doc.mjs +4 -4
  335. package/clients/cli/commands/experimental-theme.doc.mjs +5 -1
  336. package/clients/cli/commands/search.doc.mjs +2 -1
  337. package/clients/cli/commands/search.mjs +6 -1
  338. package/clients/cli/commands/template.doc.mjs +1 -1
  339. package/clients/cli/commands/template.mjs +15 -2
  340. package/clients/cli/commands/theme-add.doc.mjs +1 -1
  341. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  342. package/clients/cli/commands/theme-list.doc.mjs +1 -1
  343. package/clients/cli/commands/theme-remove.doc.mjs +13 -5
  344. package/clients/cli/commands/theme.doc.mjs +1 -1
  345. package/clients/cli/commands/theme.mjs +849 -441
  346. package/clients/cli/commands/upgrade.mjs +46 -8
  347. package/clients/cli/index.mjs +9 -19
  348. package/clients/cli/lib/cli-error.mjs +2 -1
  349. package/clients/cli/lib/component-format.mjs +205 -98
  350. package/clients/cli/lib/hook-format.mjs +9 -19
  351. package/clients/cli/lib/json-shim.mjs +265 -29
  352. package/clients/cli/lib/manifest.mjs +3 -2
  353. package/clients/cli/lib/stray-option.mjs +478 -0
  354. package/clients/cli/lib/unknown-command.mjs +353 -0
  355. package/clients/cli/manifest.generated.json +1 -1
  356. package/foundation/agent-docs/agent-docs.mjs +1 -1
  357. package/foundation/config/project.d.mts +8 -0
  358. package/foundation/config/project.mjs +26 -29
  359. package/foundation/config/theme-state.d.mts +31 -2
  360. package/foundation/config/theme-state.mjs +140 -8
  361. package/foundation/discovery/authoring-self-docs.mjs +1 -0
  362. package/foundation/discovery/cli-self-doc-names.d.mts +13 -0
  363. package/foundation/discovery/cli-self-doc-names.mjs +51 -0
  364. package/foundation/discovery/cli-self-docs.d.mts +0 -2
  365. package/foundation/discovery/cli-self-docs.mjs +2 -15
  366. package/foundation/discovery/component-discovery.d.mts +11 -0
  367. package/foundation/discovery/component-discovery.mjs +59 -10
  368. package/foundation/discovery/component-replacement.mjs +130 -1
  369. package/foundation/discovery/copied-passages.mjs +2 -1
  370. package/foundation/discovery/core-component-docs.d.mts +29 -0
  371. package/foundation/discovery/core-component-docs.mjs +83 -0
  372. package/foundation/discovery/core-theme-facts.d.mts +70 -0
  373. package/foundation/discovery/core-theme-facts.mjs +384 -0
  374. package/foundation/discovery/doc-types.mjs +4 -3
  375. package/foundation/discovery/docs-discovery.d.mts +66 -9
  376. package/foundation/discovery/docs-discovery.mjs +126 -60
  377. package/foundation/discovery/entry-name-files.d.mts +106 -0
  378. package/foundation/discovery/entry-name-files.mjs +354 -0
  379. package/foundation/discovery/hook-discovery.d.mts +18 -2
  380. package/foundation/discovery/hook-discovery.mjs +93 -42
  381. package/foundation/discovery/icon-definition-discovery.mjs +2 -1
  382. package/foundation/discovery/icon-set-checks.mjs +2 -1
  383. package/foundation/discovery/icon-set-discovery.mjs +2 -1
  384. package/foundation/discovery/integration-component-views.d.mts +15 -0
  385. package/foundation/discovery/integration-component-views.mjs +91 -0
  386. package/foundation/discovery/integration-doc-files.mjs +2 -1
  387. package/foundation/discovery/module-exports.d.mts +26 -1
  388. package/foundation/discovery/module-exports.mjs +114 -40
  389. package/foundation/discovery/name-roots.d.mts +38 -0
  390. package/foundation/discovery/name-roots.mjs +108 -0
  391. package/foundation/discovery/next-routes.d.mts +48 -0
  392. package/foundation/discovery/next-routes.mjs +181 -0
  393. package/foundation/discovery/package-exports.d.mts +10 -0
  394. package/foundation/discovery/package-exports.mjs +56 -3
  395. package/foundation/discovery/prop-drift.mjs +9 -9
  396. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  397. package/foundation/discovery/runner-allowlist.mjs +2 -0
  398. package/foundation/discovery/stored-component-list.d.mts +43 -0
  399. package/foundation/discovery/stored-component-list.mjs +90 -0
  400. package/foundation/discovery/stored-search-catalog.d.mts +115 -0
  401. package/foundation/discovery/stored-search-catalog.mjs +297 -0
  402. package/foundation/discovery/stored-self-audit.d.mts +26 -10
  403. package/foundation/discovery/stored-self-audit.mjs +40 -18
  404. package/foundation/discovery/template-adapter.d.mts +49 -29
  405. package/foundation/discovery/template-adapter.mjs +89 -99
  406. package/foundation/discovery/template-destination.d.mts +28 -0
  407. package/foundation/discovery/template-destination.mjs +104 -0
  408. package/foundation/discovery/template-icons.mjs +2 -1
  409. package/foundation/discovery/template-ids.d.mts +69 -0
  410. package/foundation/discovery/template-ids.mjs +199 -0
  411. package/foundation/discovery/theme-discovery.d.mts +12 -0
  412. package/foundation/discovery/theme-discovery.mjs +34 -4
  413. package/foundation/discovery/theme-imports.d.mts +24 -0
  414. package/foundation/discovery/theme-imports.mjs +61 -4
  415. package/foundation/discovery/theming-targets.d.mts +13 -5
  416. package/foundation/discovery/theming-targets.mjs +41 -47
  417. package/foundation/doc-compiler/generated-levels.d.mts +43 -0
  418. package/foundation/doc-compiler/generated-levels.mjs +72 -0
  419. package/foundation/doc-compiler/import.mjs +7 -1
  420. package/foundation/doc-compiler/inputs.mjs +3 -2
  421. package/foundation/doc-compiler/literal-doc.d.mts +12 -0
  422. package/foundation/doc-compiler/literal-doc.mjs +322 -0
  423. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  424. package/foundation/doc-compiler/stored-docs.d.mts +29 -0
  425. package/foundation/doc-compiler/stored-docs.mjs +63 -1
  426. package/foundation/doc-compiler/tree.d.mts +4 -84
  427. package/foundation/doc-compiler/tree.mjs +4 -62
  428. package/foundation/env/semver.mjs +3 -1
  429. package/foundation/fonts/font-stylesheet.d.mts +46 -0
  430. package/foundation/fonts/font-stylesheet.mjs +173 -0
  431. package/foundation/fs/cache-eviction.d.mts +21 -0
  432. package/foundation/fs/cache-eviction.mjs +73 -0
  433. package/foundation/fs/exact-codec.d.mts +12 -2
  434. package/foundation/fs/exact-codec.mjs +23 -6
  435. package/foundation/fs/file-protection.mjs +16 -5
  436. package/foundation/fs/gather-cache.d.mts +94 -4
  437. package/foundation/fs/gather-cache.mjs +671 -106
  438. package/foundation/fs/glob.d.mts +16 -0
  439. package/foundation/fs/glob.mjs +105 -0
  440. package/foundation/fs/jiti-cache.d.mts +19 -1
  441. package/foundation/fs/jiti-cache.mjs +130 -6
  442. package/foundation/fs/kept-tree.d.mts +80 -0
  443. package/foundation/fs/kept-tree.mjs +240 -0
  444. package/foundation/fs/listing-cache.d.mts +7 -0
  445. package/foundation/fs/listing-cache.mjs +10 -0
  446. package/foundation/fs/module-loader.d.mts +24 -2
  447. package/foundation/fs/module-loader.mjs +94 -21
  448. package/foundation/fs/path-safety.d.mts +11 -2
  449. package/foundation/fs/path-safety.mjs +108 -18
  450. package/foundation/fs/paths.d.mts +18 -0
  451. package/foundation/fs/paths.mjs +15 -2
  452. package/foundation/fs/read-record.d.mts +56 -7
  453. package/foundation/fs/read-record.mjs +280 -56
  454. package/foundation/fs/regular-file.d.mts +29 -0
  455. package/foundation/fs/regular-file.mjs +77 -0
  456. package/foundation/fs/stop-cleanup.d.mts +12 -0
  457. package/foundation/fs/stop-cleanup.mjs +66 -0
  458. package/foundation/identity/provider-identity.d.mts +6 -0
  459. package/foundation/identity/provider-identity.mjs +10 -1
  460. package/foundation/integrations/contribution-inventory.mjs +4 -3
  461. package/foundation/integrations/example-code.d.mts +63 -0
  462. package/foundation/integrations/example-code.mjs +416 -0
  463. package/foundation/integrations/integrations.d.mts +23 -1
  464. package/foundation/integrations/integrations.mjs +18 -1
  465. package/foundation/integrations/pack-state.d.mts +75 -0
  466. package/foundation/integrations/pack-state.mjs +314 -0
  467. package/foundation/integrations/public-imports.d.mts +9 -0
  468. package/foundation/integrations/public-imports.mjs +3 -2
  469. package/foundation/integrations/shipped-imports.d.mts +122 -0
  470. package/foundation/integrations/shipped-imports.mjs +497 -0
  471. package/foundation/integrations/validate-contributions.d.mts +0 -17
  472. package/foundation/integrations/validate-contributions.mjs +59 -333
  473. package/foundation/render/assets.mjs +52 -7
  474. package/foundation/render/charts.d.mts +78 -27
  475. package/foundation/render/charts.mjs +266 -90
  476. package/foundation/render/embedded-files.d.mts +6 -0
  477. package/foundation/render/embedded-files.mjs +25 -5
  478. package/foundation/render/embedded-imports.d.mts +70 -7
  479. package/foundation/render/embedded-imports.mjs +132 -41
  480. package/foundation/render/file-header.d.mts +66 -0
  481. package/foundation/render/file-header.mjs +118 -0
  482. package/foundation/render/host-answer.d.mts +18 -0
  483. package/foundation/render/host-answer.mjs +46 -0
  484. package/foundation/render/host-exit.d.mts +1 -0
  485. package/foundation/render/host-exit.mjs +6 -1
  486. package/foundation/render/html-reader.d.mts +55 -2
  487. package/foundation/render/html-reader.mjs +145 -26
  488. package/foundation/render/layers.d.mts +30 -0
  489. package/foundation/render/layers.mjs +158 -0
  490. package/foundation/render/markup-edits.d.mts +57 -0
  491. package/foundation/render/markup-edits.mjs +182 -0
  492. package/foundation/render/offline.d.mts +32 -0
  493. package/foundation/render/offline.mjs +56 -0
  494. package/foundation/render/page-host.mjs +29 -12
  495. package/foundation/render/page-worker.mjs +354 -21
  496. package/foundation/render/picture-chrome.d.mts +4 -0
  497. package/foundation/render/picture-chrome.mjs +192 -0
  498. package/foundation/render/picture-playwright.d.mts +4 -0
  499. package/foundation/render/picture-playwright.mjs +46 -0
  500. package/foundation/render/rebuild.mjs +2 -1
  501. package/foundation/render/render-page.d.mts +79 -5
  502. package/foundation/render/render-page.mjs +735 -109
  503. package/foundation/render/source-block.d.mts +85 -6
  504. package/foundation/render/source-block.mjs +211 -20
  505. package/foundation/render/ts-paths.d.mts +69 -6
  506. package/foundation/render/ts-paths.mjs +326 -40
  507. package/foundation/response/error-codes.d.mts +3 -1
  508. package/foundation/response/error-codes.d.ts +1 -0
  509. package/foundation/response/error-codes.doc.mjs +12 -1
  510. package/foundation/response/error-codes.mjs +11 -1
  511. package/foundation/response/response-types.doc.mjs +6 -6
  512. package/foundation/suggest/name-index.d.mts +148 -0
  513. package/foundation/suggest/name-index.mjs +317 -0
  514. package/foundation/suggest/other-command.d.mts +140 -0
  515. package/foundation/suggest/other-command.mjs +756 -0
  516. package/foundation/text/compare-text.d.mts +14 -0
  517. package/foundation/text/compare-text.mjs +68 -0
  518. package/foundation/text/css-escape.d.mts +18 -0
  519. package/foundation/text/css-escape.mjs +35 -0
  520. package/foundation/text/entry-names.d.mts +14 -0
  521. package/foundation/text/entry-names.mjs +14 -0
  522. package/foundation/text/string-utils.d.mts +46 -6
  523. package/foundation/text/string-utils.mjs +118 -20
  524. package/foundation/text/suggest-order.d.mts +47 -4
  525. package/foundation/text/suggest-order.mjs +174 -5
  526. package/foundation/xle/browser.d.mts +2 -2
  527. package/foundation/xle/expand.mjs +2 -1
  528. package/host/index.mjs +8 -6
  529. package/package.json +7 -6
@@ -12,10 +12,11 @@
12
12
  import {AstryxError} from '../error.mjs';
13
13
  import * as fs from 'node:fs';
14
14
  import * as path from 'node:path';
15
- import {partForWord} from './_how-question.mjs';
15
+ import {partForWord, partWords} from './_part-words.mjs';
16
16
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
17
- import {baseInstalled, baseThemeFile, installLine} from './_project.mjs';
17
+ import {cssUnescape} from '../../foundation/text/css-escape.mjs';
18
18
  import {levenshteinDistance} from '../../foundation/text/levenshtein.mjs';
19
+ import {baseInstalled, baseThemeFile} from './_project.mjs';
19
20
  import {
20
21
  withFallbacks,
21
22
  MATH_FUNCTION,
@@ -32,6 +33,7 @@ import {
32
33
  numbersIn,
33
34
  propertyGrammar,
34
35
  takesPercentage,
36
+ sameKindValues,
35
37
  } from './_css.mjs';
36
38
  import {calcVars, coreFallback, multipliedTokens} from './_parts.mjs';
37
39
  import {
@@ -61,13 +63,18 @@ import {
61
63
  wordTable,
62
64
  WRAPPED_PARTS,
63
65
  CARD_LIKE,
66
+ systemFontFamilies,
67
+ isSystemFamily,
68
+ fontStack,
64
69
  } from './_tables.mjs';
65
70
  import {
66
71
  COLOR_NAMES,
67
72
  colorProblem,
68
73
  isColorValue,
74
+ colorAsCssReads,
69
75
  isNumber,
70
76
  isSafeValue,
77
+ withoutCssEscapes,
71
78
  isSize,
72
79
  parseColor,
73
80
  mixSide,
@@ -77,35 +84,99 @@ import {
77
84
  PALETTE_DIALS,
78
85
  PALETTE_TOKENS,
79
86
  VIBRANCY_DEFAULT,
80
- isGraySeed,
87
+ vibrancyMoves,
81
88
  paletteToken,
82
89
  seedOf,
83
90
  } from './_palette.mjs';
84
91
  import {
85
92
  camel,
86
93
  kebab,
94
+ closestOf,
87
95
  nearest,
88
- partDefault,
96
+ negates,
89
97
  partsOf,
90
98
  refuse,
91
99
  lengthPx,
100
+ cornersPlain,
92
101
  radiusAt,
102
+ radioCircle,
93
103
  radiusTokenOf,
104
+ cornerParts,
94
105
  focusStateOf,
95
106
  valueProblem,
96
107
  partComponentDocs,
97
108
  themeFiles,
98
109
  ownSourceTokenValues,
99
110
  baseTopTokens,
111
+ baseComponent,
100
112
  baseComponentReads,
101
113
  partRuleTokens,
102
114
  cssFamily,
103
115
  familySpaces,
116
+ baseTextPx,
117
+ fontsourcePackageOf,
118
+ dialWordOf,
119
+ paddedParts,
120
+ onBuiltInSteps,
104
121
  } from './_settings.mjs';
122
+ import {isColorToken} from './_compiler.mjs';
123
+ import {
124
+ trimInsideQuotes,
125
+ colorPair,
126
+ otherSettingLabel,
127
+ familiesOf,
128
+ familyPieces,
129
+ normalValueText,
130
+ normalizeEntry,
131
+ withoutDebris,
132
+ typoOf,
133
+ typoNear,
134
+ stateSpelling,
135
+ modeWord,
136
+ documentTypoWords,
137
+ PROPERTY_WORDS,
138
+ WEIGHT_WORDS,
139
+ TAILWIND_RADIUS,
140
+ documentReadings,
141
+ documentNumericTable,
142
+ documentRange,
143
+ withoutCopyDebris,
144
+ commaNumbers,
145
+ thousandsSetting,
146
+ baseWord,
147
+ } from './_normal.mjs';
148
+
149
+ export {
150
+ familiesOf,
151
+ familyPieces,
152
+ normalValueText,
153
+ normalizeEntry,
154
+ withoutDebris,
155
+ };
105
156
  import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
106
157
 
107
158
  export {lengthPx};
108
159
 
160
+ /**
161
+ * The radius the base theme's own rule gives a part, in px, or null when
162
+ * its rule gives none.
163
+ * @param {any} ctx
164
+ * @param {{light: Record<string, string>}} base
165
+ * @param {string} part
166
+ * @param {string | undefined} when
167
+ * @returns {number | null}
168
+ */
169
+ function basePartRadiusPx(ctx, base, part, when) {
170
+ const own = ctx.base
171
+ ? baseComponent(ctx.base, ctx, part, 'borderRadius', {when})
172
+ : null;
173
+ if (typeof own !== 'string') return null;
174
+ const tokenName = /var\(\s*(--radius-[\w-]+)/.exec(own)?.[1];
175
+ if (tokenName) return tokenPx(base, tokenName);
176
+ const px = lengthPx(own);
177
+ return px == null ? null : Math.min(px, 9999);
178
+ }
179
+
109
180
  /**
110
181
  * A token's value in px, following var() references through the tokens.
111
182
  * @param {{light: Record<string, string>}} base
@@ -122,6 +193,13 @@ function tokenPx(base, token) {
122
193
  return lengthPx(v);
123
194
  }
124
195
 
196
+ // A type scale ratio is a number above 1, up to 2.
197
+ documentNumericTable(
198
+ ['type'],
199
+ Object.entries(TYPE_STYLES).map(([name, style]) => [name, style.ratio]),
200
+ [1, 2],
201
+ );
202
+
125
203
  /**
126
204
  * The `type` preset nearest a scale ratio typed as a number (1.3 is
127
205
  * editorial), or null for a number that is no ratio (16).
@@ -154,6 +232,108 @@ const cornerPxOf = v =>
154
232
 
155
233
  const E = ERROR_CODES;
156
234
 
235
+ /**
236
+ * Why the math in a value's calc() cannot work, or null: each `+`/`-`
237
+ * needs two sides of one kind (a length with a length or a percentage, a
238
+ * number with a number), `*` needs a plain number on one side, `/` a plain
239
+ * number on the right. A var() counts as its fallback; one with none, or a
240
+ * nested min(), max() or clamp(), is not judged.
241
+ * @param {string} value
242
+ * @returns {string | null}
243
+ */
244
+ export function calcUnitProblem(value) {
245
+ const text = String(value);
246
+ const re = /\bcalc\(/gi;
247
+ let m;
248
+ while ((m = re.exec(text))) {
249
+ const open = m.index + m[0].length - 1;
250
+ const close = matchingParen(text, open);
251
+ if (close < 0) return null;
252
+ let expr = text.slice(open + 1, close);
253
+ // Each var() is its fallback, innermost first.
254
+ for (let i = 0; i < 20 && /\bvar\(/i.test(expr); i += 1) {
255
+ const at = expr.search(/\bvar\((?:[^()]|\([^()]*\))*\)/i);
256
+ const v = /\bvar\(((?:[^()]|\([^()]*\))*)\)/i.exec(expr.slice(at));
257
+ if (at < 0 || !v) return null;
258
+ const comma = v[1].indexOf(',');
259
+ if (comma < 0) return null;
260
+ expr = `${expr.slice(0, at)}(${v[1].slice(comma + 1).trim()})${expr.slice(at + v[0].length)}`;
261
+ }
262
+ if (/[a-z-]+\(/i.test(expr.replace(/\bcalc\(/gi, '('))) continue;
263
+ const found = expr.match(/\d*\.?\d+(?:e[+-]?\d+)?[a-z%]*|[-+*/()]/gi);
264
+ if (!found) continue;
265
+ const tokens = found;
266
+ let pos = 0;
267
+ /** @returns {string | null} */
268
+ const kindOf = (/** @type {string} */ t) => {
269
+ const u = /[a-z%]*$/i.exec(t)?.[0].toLowerCase() ?? '';
270
+ if (!u) return 'number';
271
+ if (u === '%') return 'percent';
272
+ if (/^(m?s)$/.test(u)) return 'time';
273
+ if (/^(deg|rad|grad|turn)$/.test(u)) return 'angle';
274
+ return 'length';
275
+ };
276
+ /** @type {string | null} */
277
+ let why = null;
278
+ const fail = (/** @type {string} */ w) => {
279
+ why ??= w;
280
+ return 'number';
281
+ };
282
+ const join = (
283
+ /** @type {string} */ a,
284
+ /** @type {string} */ b,
285
+ /** @type {string} */ op,
286
+ ) => {
287
+ if (op === '+' || op === '-') {
288
+ if (a === b) return a;
289
+ const lp = new Set([a, b]);
290
+ if (lp.has('length') && lp.has('percent') && lp.size === 2)
291
+ return 'length';
292
+ return fail(`${a} ${op} ${b} adds two kinds of value`);
293
+ }
294
+ if (op === '*') {
295
+ if (a === 'number') return b;
296
+ if (b === 'number') return a;
297
+ return fail(`${a} * ${b} multiplies two values with units`);
298
+ }
299
+ if (b === 'number') return a;
300
+ return fail(`${a} / ${b} divides by a value with a unit`);
301
+ };
302
+ /** @returns {string} */
303
+ const factor = () => {
304
+ const t = tokens[pos++];
305
+ if (t === '(') {
306
+ const k = sum();
307
+ pos++;
308
+ return k;
309
+ }
310
+ if (t === '-' || t === '+') return factor();
311
+ return t == null ? 'number' : (kindOf(t) ?? 'number');
312
+ };
313
+ /** @returns {string} */
314
+ const product = () => {
315
+ let k = factor();
316
+ while (tokens[pos] === '*' || tokens[pos] === '/') {
317
+ const op = tokens[pos++];
318
+ k = join(k, factor(), op);
319
+ }
320
+ return k;
321
+ };
322
+ /** @returns {string} */
323
+ function sum() {
324
+ let k = product();
325
+ while (tokens[pos] === '+' || tokens[pos] === '-') {
326
+ const op = tokens[pos++];
327
+ k = join(k, product(), op);
328
+ }
329
+ return k;
330
+ }
331
+ sum();
332
+ if (why) return why;
333
+ }
334
+ return null;
335
+ }
336
+
157
337
  /**
158
338
  * The fallbacks of the var() calls inside a value that is not one var()
159
339
  * alone (`calc(var(--x, 4px) * 2)`), in order. A var() with an empty
@@ -227,6 +407,26 @@ function matchingParen(text, open) {
227
407
  return -1;
228
408
  }
229
409
 
410
+ /** A yes or no word, which `rounded` reads as round or square. */
411
+ const YES_NO = /^(true|yes|on|none|false|off|no)$/i;
412
+
413
+ /**
414
+ * A value as the corners dial reads it: a rung in any case, or a size with
415
+ * its unit (`10PX`, `1rem`) in px; null for anything else, a bare number
416
+ * included.
417
+ * @param {string} v
418
+ * @returns {string | null}
419
+ */
420
+ function cornersRead(v) {
421
+ // A comma between digits as the one comma rule reads it (0,5rem).
422
+ const lower = commaNumbers(String(v).trim().toLowerCase());
423
+ if (CORNERS.some(([n]) => n === lower)) return lower;
424
+ if (/^(0|none|sharp|zero|flat)$/.test(lower)) return 'square';
425
+ if (/^[+-]?\d*\.?\d+$/.test(lower)) return null;
426
+ const px = lengthPx(lower);
427
+ return px != null && px >= 0 ? `${Math.round(px * 100) / 100}px` : null;
428
+ }
429
+
230
430
  /**
231
431
  * A text size written another way (20px, 2e1, +20, 1.25rem, 125%, `20 px`,
232
432
  * `1,25rem`) as the body size in pixels text-size takes, kept to its 10 to
@@ -235,13 +435,55 @@ function matchingParen(text, open) {
235
435
  * @returns {number | null}
236
436
  */
237
437
  function textSizePx(v) {
238
- const m = /^\+?(\d*\.?\d+(?:e[+-]?\d+)?)(px|rem|em|pt|%)?$/i.exec(
239
- typedPlain(v)
240
- .replace(/(\d)\.(?=[a-z%]*$)/i, '$1')
241
- .replace(/\s+/g, '')
242
- .replace(/^(\d+),(\d+)/, '$1.$2'),
438
+ // Paste debris around the size (quotes, `!important`, a trailing `;` or
439
+ // `,`) is not part of it.
440
+ const bare = withoutDebris(
441
+ String(v)
442
+ .replace(/^\s*(["'])(.*)\1\s*$/, '$2')
443
+ .replace(/\s*!\s*important\s*/i, '')
444
+ .replace(/[;,]+\s*$/, ''),
243
445
  );
446
+ const plain = typedPlain(bare)
447
+ .replace(/(\d)\.(?=[a-z%]*$)/i, '$1')
448
+ // A unit split off by a space (`16 px`), and the spaces of a math
449
+ // function (`calc(1rem + 2px)`); two numbers stay two.
450
+ .replace(/(\d)\s+(?=[a-z%])/gi, '$1')
451
+ .replace(/\s*([*/+()-])\s*/g, '$1')
452
+ .replace(/^(\d+),(\d+)/, '$1.$2');
453
+ // A constant calc() of px and rem sizes (`calc(16px + 2px)`) is worked out.
454
+ const calc =
455
+ /^calc\((\d*\.?\d+)(px|rem|em)?([*/+-])(\d*\.?\d+)(px|rem|em)?\)$/i.exec(
456
+ plain,
457
+ );
458
+ if (calc) {
459
+ const px = (/** @type {string} */ n, /** @type {string | undefined} */ u) =>
460
+ Number(n) * (u && /r?em/i.test(u) ? 16 : 1);
461
+ const [a, b] = [px(calc[1], calc[2]), px(calc[4], calc[5])];
462
+ const op = calc[3];
463
+ // Sizes add and subtract; a size scales by a plain number.
464
+ const r =
465
+ op === '+' || op === '-'
466
+ ? calc[2] && calc[5]
467
+ ? op === '+'
468
+ ? a + b
469
+ : a - b
470
+ : null
471
+ : op === '*'
472
+ ? calc[2] && calc[5]
473
+ ? null
474
+ : a * b
475
+ : calc[5]
476
+ ? null
477
+ : a / b;
478
+ return r != null && Number.isFinite(r) && r >= 10 && r <= 32
479
+ ? Math.round(r * 100) / 100
480
+ : null;
481
+ }
482
+ const m = /^\+?(\d*\.?\d+(?:e[+-]?\d+)?)(px|rem|em|pt|%)?$/i.exec(plain);
244
483
  if (!m) return null;
484
+ // A bare number under 4 (1.5, 1.125) reads as rem as much as px: no
485
+ // size is guessed for it.
486
+ if (!m[2] && Number(m[1]) < 4) return null;
245
487
  const unit = (m[2] ?? '').toLowerCase();
246
488
  const n =
247
489
  Number(m[1]) *
@@ -334,6 +576,8 @@ function valueMeant(type, value) {
334
576
  .replace(/\s*!\s*important\s*$/i, '')
335
577
  .replace(/;+\s*$/, '')
336
578
  .trim();
579
+ // Copy debris around it (a trailing comma, a stray quote or bracket).
580
+ p = withoutDebris(p).trim();
337
581
  const q = /^(["'])(.*)\1$/.exec(p);
338
582
  if (q && type !== 'font') p = q[2].trim();
339
583
  const out = [p];
@@ -344,13 +588,20 @@ function valueMeant(type, value) {
344
588
  if (type === 'font' || type === 'font-family') {
345
589
  // A comma left out between families (`"Open Sans" serif`), read with
346
590
  // css-tree.
591
+ // The stack read as families (a trailing comma, a stack wrapped in one
592
+ // more pair of quotes), each quoted as CSS needs it.
593
+ const fams = familiesOf(p);
594
+ // A number or size is no family: never quoted into one (`"700"`).
595
+ if (fams?.length && !fams.some(f => NUMBERISH.test(f)))
596
+ out.push(fams.map(f => cssFamily(f, true)).join(', '));
347
597
  const listed = familyListMeant(p);
348
- if (listed) out.push(listed);
349
- // Each family quoted as CSS needs it, only when no family holds a
350
- // quote inside (the pieces are whole names).
351
- const pieces = p.split(',').map(f => f.trim().replace(/^["']|["']$/g, ''));
352
- if (!listed && pieces.every(f => !/["'\\]/.test(f)))
353
- out.push(pieces.map(f => cssFamily(f, true)).join(', '));
598
+ if (listed && !fams?.length) out.push(listed);
599
+ }
600
+ // A comma rgb() or hsl() CSS does not take as written: the same channels
601
+ // in the syntax CSS reads them in.
602
+ if (type === 'color') {
603
+ const asRead = colorAsCssReads(p);
604
+ if (asRead) out.push(asRead);
354
605
  }
355
606
  return [...new Set(out)].filter(x => x && x !== value.trim());
356
607
  }
@@ -391,13 +642,15 @@ function sizeMeant(v, ok) {
391
642
  n,
392
643
  n.replace(/(\d)\.(?=[a-z%]|$)/gi, '$1'),
393
644
  t.replace(/(\d)\.(?=[a-z%]|$)/gi, '$1'),
394
- t.replace(/\s+/g, ''),
395
- t.replace(/^([+-]?\d+),(\d+)/, '$1.$2').replace(/\s+/g, ''),
645
+ // A unit split off by a space (`16 px`); two numbers (`12 16px`) are
646
+ // never joined into one.
647
+ t.replace(/(\d)\s+(?=[a-z%])/gi, '$1'),
648
+ // A comma between digits as the one comma rule reads it (a decimal
649
+ // comma, or a thousands mark in a pixel length: 1,200px).
650
+ commaNumbers(t).replace(/(\d)\s+(?=[a-z%])/gi, '$1'),
396
651
  mathSpaced(t),
397
652
  ];
398
- const m = /^([+-]?\d*\.?\d+)\s*([a-z%]+)$/i.exec(
399
- t.replace(/^([+-]?\d+),(\d+)/, '$1.$2'),
400
- );
653
+ const m = /^([+-]?\d*\.?\d+)\s*([a-z%]+)$/i.exec(commaNumbers(t));
401
654
  if (m) {
402
655
  // A unit typed with a letter too many (pxx, remm, pxs).
403
656
  const unit = [...SIZE_UNITS]
@@ -430,7 +683,7 @@ function mathSpaced(v) {
430
683
  function numberMeant(v, name, ok) {
431
684
  const t = v.trim();
432
685
  const plain = typedPlain(t).replace(/(\d)\.$/, '$1');
433
- const comma = plain.replace(/^([+-]?\d+),(\d+)/, '$1.$2');
686
+ const comma = commaNumbers(plain, thousandsSetting(name));
434
687
  const tries = [
435
688
  /^[\doO.]+$/.test(plain) && /\d/.test(plain)
436
689
  ? plain.replace(/[oO]/g, '0')
@@ -590,6 +843,22 @@ export function storedProblems(ctx, slug, data, skip = '') {
590
843
  return scope(`${s.thing} applies to the whole theme, not to ${s.on}`);
591
844
  if (s.mode && s.source === 'dial' && !PALETTE_DIALS.includes(s.thing))
592
845
  return scope(`${s.thing} is the same in light and dark`);
846
+ // A light and a dark pair saved for one mode (a hand edit): set
847
+ // refuses that, so the loader does too; the repair is the half saved
848
+ // for that mode.
849
+ if (s.mode && /^\s*light-dark\(/i.test(String(s.value ?? ''))) {
850
+ const pair = colorPair(
851
+ String(s.value)
852
+ .trim()
853
+ .replace(/^light-dark\(\s*([\s\S]*)\)\s*$/i, 'light: $1')
854
+ .replace(/,\s*/, '; dark: '),
855
+ );
856
+ return {
857
+ setting: s,
858
+ why: `${s.thing} gives both modes with light-dark(), and is saved for ${s.mode} only`,
859
+ ...(pair ? {fix: s.mode === 'dark' ? pair.dark : pair.light} : {}),
860
+ };
861
+ }
593
862
  if (t && s.state && ![...t.states, ...COMMON_STATES].includes(s.state))
594
863
  return scope(`"${s.state}" is not a state of ${s.on}`);
595
864
  if (t && s.when) {
@@ -648,13 +917,45 @@ export function storedProblems(ctx, slug, data, skip = '') {
648
917
  // it.
649
918
  for (const s of data.settings) {
650
919
  if (replaced(s) || typeof s.value !== 'string') continue;
651
- const clean = normalValueText(s.value);
652
- if (clean !== s.value)
920
+ // Read as typed input is (a font family's quotes trimmed too), so the
921
+ // line offered is the value set would save.
922
+ const clean = /font/i.test(s.thing)
923
+ ? trimInsideQuotes(normalValueText(s.value))
924
+ : normalValueText(s.value);
925
+ if (clean !== s.value) {
926
+ // Name what is wrong: invisible spaces, or quotes around the value
927
+ // CSS does not read (a curly quote inside a quoted string is fine,
928
+ // and is left as it is).
929
+ const spaces =
930
+ clean.replace(/["']/g, '') !==
931
+ s.value.replace(
932
+ /[\u2018-\u201F\u00AB\u00BB\u2039\u203A\u300C-\u300F\uFF02\uFF07`"']/g,
933
+ '',
934
+ );
935
+ const quotes =
936
+ /[\u2018-\u201F\u00AB\u00BB\u2039\u203A\u300C-\u300F\uFF02\uFF07`]/.test(
937
+ s.value,
938
+ ) &&
939
+ clean.replace(
940
+ /[\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000\u200B-\u200D\u2060\uFEFF]/g,
941
+ '',
942
+ ) !==
943
+ s.value.replace(
944
+ /[\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000\u200B-\u200D\u2060\uFEFF]/g,
945
+ '',
946
+ );
947
+ const why = [
948
+ spaces &&
949
+ 'a no-break, thin or zero-width space, which the browser does not read as a space',
950
+ quotes &&
951
+ 'curly or other quotes around a value, where CSS reads only straight ones',
952
+ ].filter(Boolean);
653
953
  found.push({
654
954
  setting: s,
655
- why: `${s.thing} holds a no-break, thin or zero-width space, which the browser does not read as a space`,
955
+ why: `${s.thing} holds ${why.join(', and ') || 'characters the browser does not read as written'}`,
656
956
  fix: clean,
657
957
  });
958
+ }
658
959
  }
659
960
  for (const s of data.settings) {
660
961
  if (s.source !== 'token' || s.thing === skipThing || !(s.thing in TOKENS))
@@ -700,6 +1001,429 @@ export function storedProblems(ctx, slug, data, skip = '') {
700
1001
  return found;
701
1002
  }
702
1003
 
1004
+ /** The generic families a font list ends with. */
1005
+ const GENERIC_FAMILIES = [
1006
+ 'serif',
1007
+ 'sans-serif',
1008
+ 'monospace',
1009
+ 'system-ui',
1010
+ 'cursive',
1011
+ 'fantasy',
1012
+ 'ui-serif',
1013
+ 'ui-sans-serif',
1014
+ 'ui-monospace',
1015
+ 'ui-rounded',
1016
+ ];
1017
+ documentTypoWords(GENERIC_FAMILIES);
1018
+ documentTypoWords([...Object.keys(FONTS), ...Object.keys(OPEN_FONTS)]);
1019
+ // The system families the font readers compare a typo with: the gate
1020
+ // takes the family they offer.
1021
+ documentTypoWords(systemFontFamilies());
1022
+
1023
+ /** The theme-wide dial or token for a CSS property typed with no part. */
1024
+ const WHOLE_THEME_EQUIVALENT = /** @type {Record<string, string>} */ ({
1025
+ 'border-radius': 'corners',
1026
+ 'font-size': 'text-size',
1027
+ 'font-family': 'font',
1028
+ color: '--color-text-primary',
1029
+ background: '--color-background-body',
1030
+ 'background-color': '--color-background-body',
1031
+ });
1032
+
1033
+ /** A number or a size, which is never a font family. */
1034
+ const NUMBERISH = /^[+-]?(\d+\.?\d*|\.\d+)(px|rem|em|pt|%)?$/i;
1035
+
1036
+ /**
1037
+ * What is wrong with a typed family list, or null. Each family of the list
1038
+ * is read on its own, from its end:
1039
+ * - a size (`18px`, `Inter 16px`) is no family; a number is a weight only
1040
+ * as a whole hundred (100 to 1000), and any other bare number
1041
+ * (`Lato, 16`) is neither a weight nor a family;
1042
+ * - a weight (`600`, `ExtraBold`, `extra bold`, any form the weight table
1043
+ * reads) or a style (`Italic`, `Oblique`) after a family's name is that
1044
+ * family and the weight or style; a weight or style WORD is part of the
1045
+ * name unless the whole name is no family the editor knows and the name
1046
+ * without it is (knownFamily: `Arial Black` and `Segoe UI Semibold` are
1047
+ * families; `Inter ExtraBold` and `Inter Italic` are Inter and a word);
1048
+ * - a generic in quotes (`'sans-serif'`) is a family named so, and a
1049
+ * family the editor does not know that is a typo of a generic
1050
+ * (`sansserif`, `serf`, `system ui`) is that generic;
1051
+ * - with `presets` (the font dial), a lone family that is a typo of a
1052
+ * preset (`sytem`, `robto`) is that preset.
1053
+ * Only weight, style and size words (`16px bold`, `italic bold`) are a font
1054
+ * shorthand, read where the font dial reads one: null. `families` is the
1055
+ * list meant (empty when no family is left), `rung` the headings weight
1056
+ * nearest a weight given, `textSize` the text-size a size reads as, and
1057
+ * `style` a style given.
1058
+ * @param {string} value
1059
+ * @param {any} ctx
1060
+ * @param {boolean} [presets] whether a preset name is read (the font dial)
1061
+ * @param {Array<{name: string, near: string}>} [notes] filled with each family kept as
1062
+ * typed that is near a font a system ships (a family the editor does not
1063
+ * know may be a real one: Corben is no typo of Corbel)
1064
+ * @returns {{why: string, families: string, asTyped: string | null, rung: string | null, size: boolean, textSize: number | null, style: string | null} | null}
1065
+ */
1066
+ function fontListProblem(value, ctx, presets = false, notes = []) {
1067
+ // Copy debris (a trailing `;`, `!important`, a comment) is read away
1068
+ // first, as it is for any value.
1069
+ const pieces = familyPieces(withoutCopyDebris(pastedFont(value) ?? value));
1070
+ if (!pieces) return null;
1071
+ const weightOf = (/** @type {string} */ w) => {
1072
+ const k = w.toLowerCase().replace(/[\s_-]+/g, '');
1073
+ // A weight number is a whole hundred (Source Serif 4 is a family).
1074
+ return /^\d{3,4}$/.test(k) && Number(k) % 100 === 0 && Number(k) <= 1000
1075
+ ? Number(k)
1076
+ : HEADING_WEIGHTS[k] !== undefined
1077
+ ? Number(HEADING_WEIGHTS[k])
1078
+ : WEIGHT_WORDS[k] !== undefined
1079
+ ? Number(WEIGHT_WORDS[k])
1080
+ : null;
1081
+ };
1082
+ const STYLE = /^(italic|oblique)$/i;
1083
+ const bare = (/** @type {string} */ w) =>
1084
+ w.toLowerCase().replace(/[\s_-]+/g, '');
1085
+ /** The family a preset key or a system family names, by lowercase name. */
1086
+ const familyOfKnown = (/** @type {string} */ k) => {
1087
+ const lower = k.toLowerCase();
1088
+ const named =
1089
+ FONTS[lower]?.[0] ??
1090
+ /** @type {Record<string, {family: string}>} */ (OPEN_FONTS)[lower]
1091
+ ?.family ??
1092
+ k;
1093
+ return bare(named.replace(/["']/g, ''));
1094
+ };
1095
+ /** The generic a family the editor does not know is a typo of. */
1096
+ const genericOf = (/** @type {string} */ name) => {
1097
+ // Written with no dash or a space (sansserif, system ui): that generic.
1098
+ const exact = GENERIC_FAMILIES.find(g => bare(g) === bare(name));
1099
+ if (exact) return exact;
1100
+ const hits = GENERIC_FAMILIES.filter(g => typoNear(name.toLowerCase(), g));
1101
+ return hits.length === 1 ? hits[0] : null;
1102
+ };
1103
+
1104
+ /** @type {string[]} */
1105
+ const kept = [];
1106
+ /**
1107
+ * Each family read as a misspelling, as typed in quotes: quotes keep a
1108
+ * family the editor does not know as written (Inder, Monaspace).
1109
+ * @type {Map<number, string>}
1110
+ */
1111
+ const asTyped = new Map();
1112
+ /** @type {number | null} */
1113
+ let weight = null;
1114
+ let number = false;
1115
+ let size = false;
1116
+ /** @type {string | null} */
1117
+ let sizeTyped = null;
1118
+ /** @type {string | null} */
1119
+ let style = null;
1120
+ let quotedGeneric = false;
1121
+ let misspelled = false;
1122
+ for (const p of pieces) {
1123
+ const name = p.name.trim();
1124
+ if (!name) continue;
1125
+ if (p.quoted) {
1126
+ if (GENERIC_FAMILIES.includes(name.toLowerCase())) {
1127
+ quotedGeneric = true;
1128
+ kept.push(name.toLowerCase());
1129
+ } else kept.push(/[^a-z0-9-]/i.test(name) ? JSON.stringify(name) : name);
1130
+ continue;
1131
+ }
1132
+ // A number or size alone is read where the setting reads one (a
1133
+ // size for text-size, a weight for headings); in a list of several it
1134
+ // is a family that is not one.
1135
+ if (NUMBERISH.test(name)) {
1136
+ if (pieces.length < 2) return null;
1137
+ if (/[a-z%]$/i.test(name)) {
1138
+ size = true;
1139
+ sizeTyped ??= name;
1140
+ } else if (weightOf(name) != null) weight ??= weightOf(name);
1141
+ else number = true;
1142
+ continue;
1143
+ }
1144
+ // A preset named by its key on the font dial (dm-sans, mono) is that
1145
+ // preset.
1146
+ const PRESETS = [...Object.keys(FONTS), ...Object.keys(OPEN_FONTS)];
1147
+ if (presets && PRESETS.includes(name.toLowerCase())) {
1148
+ kept.push(name);
1149
+ continue;
1150
+ }
1151
+ // A family the editor knows is that family, whatever its last word
1152
+ // (Arial Black, Source Serif 4).
1153
+ if (knownFamily(ctx, name)) {
1154
+ kept.push(name);
1155
+ continue;
1156
+ }
1157
+ // Weight, style, size and number words after the name, read from the
1158
+ // end; a weight of two words (extra bold) first.
1159
+ const words = name.split(/\s+/);
1160
+ let end = words.length;
1161
+ /** @type {Array<{kind: string, text: string, value?: number}>} */
1162
+ const tail = [];
1163
+ while (end > 0) {
1164
+ // A known family before the words read so far keeps its own last
1165
+ // word (Arial Black 900 is Arial Black and 900).
1166
+ if (end < words.length && knownFamily(ctx, words.slice(0, end).join(' ')))
1167
+ break;
1168
+ const two =
1169
+ end >= 2 ? weightOf(words.slice(end - 2, end).join('')) : null;
1170
+ const w = words[end - 1];
1171
+ if (two != null && end >= 3) {
1172
+ tail.unshift({
1173
+ kind: 'weight',
1174
+ text: words.slice(end - 2, end).join(' '),
1175
+ value: two,
1176
+ });
1177
+ end -= 2;
1178
+ } else if (STYLE.test(w)) {
1179
+ tail.unshift({kind: 'style', text: w.toLowerCase()});
1180
+ end -= 1;
1181
+ } else if (weightOf(w) != null) {
1182
+ tail.unshift({
1183
+ kind: 'weight',
1184
+ text: w,
1185
+ value: /** @type {number} */ (weightOf(w)),
1186
+ });
1187
+ end -= 1;
1188
+ } else if (NUMBERISH.test(w) && /[a-z%]$/i.test(w)) {
1189
+ tail.unshift({kind: 'size', text: w});
1190
+ end -= 1;
1191
+ // A bare number that is no weight is part of the name (Source Sans
1192
+ // 3); only a separate list item is a number that is no family.
1193
+ } else break;
1194
+ }
1195
+ const base = words.slice(0, end).join(' ');
1196
+ // Only those words: alone, a font shorthand (read where the font dial
1197
+ // reads one); in a list of several, an item that is no family.
1198
+ if (!base) {
1199
+ if (pieces.length < 2) return null;
1200
+ for (const t of tail) {
1201
+ if (t.kind === 'weight') weight ??= t.value ?? null;
1202
+ else if (t.kind === 'style') style ??= t.text;
1203
+ else if (t.kind === 'size') {
1204
+ size = true;
1205
+ sizeTyped ??= t.text;
1206
+ }
1207
+ }
1208
+ continue;
1209
+ }
1210
+ if (!tail.length) {
1211
+ // A family the editor does not know that is a typo of a generic, or
1212
+ // (on the font dial, alone) of a preset: that name.
1213
+ // Or a typo of a system family the build knows (arail is Arial,
1214
+ // Menol is Menlo), on any font list: one known-family rule.
1215
+ const generic = genericOf(name);
1216
+ const known = [
1217
+ ...(presets && pieces.length === 1 ? PRESETS : []),
1218
+ ...systemFontFamilies(),
1219
+ ];
1220
+ const unknown = !generic && !isSystemFamily(cssUnescape(name));
1221
+ /** The known names a typo is near. @param {string[]} names */
1222
+ const hitsIn = names =>
1223
+ unknown ? names.filter(k => typoNear(bare(name), bare(k))) : [];
1224
+ /** @param {string} k */
1225
+ const distance = k =>
1226
+ levenshteinDistance(bare(name), bare(k), 99, {swaps: true});
1227
+ /** The nearest spelling among names of one family, else null. @param {string[]} hits */
1228
+ const oneReading = hits =>
1229
+ hits.length && new Set(hits.map(familyOfKnown)).size === 1
1230
+ ? hits.reduce((best, hit) =>
1231
+ distance(hit) < distance(best) ? hit : best,
1232
+ )
1233
+ : null;
1234
+ // The presets are read first: a typo of one (Corier is courier, even
1235
+ // beside Corbel) is that preset, refused with its line, offered at
1236
+ // the nearest spelling of the family it names (Segoe IU is Segoe
1237
+ // UI). A preset and the family it names are one reading. Only a
1238
+ // generic or a preset the editor offers is read as a typo: a family
1239
+ // it does not know near a font a system ships may be a real family
1240
+ // (Corben, Gabriela), so it is kept as typed, with a note.
1241
+ const presetHit = oneReading(
1242
+ presets && pieces.length === 1 ? hitsIn(PRESETS) : [],
1243
+ );
1244
+ const editorWord = presetHit
1245
+ ? oneReading(
1246
+ hitsIn(known).filter(
1247
+ h => familyOfKnown(h) === familyOfKnown(presetHit),
1248
+ ),
1249
+ )
1250
+ : null;
1251
+ const preset = editorWord ?? oneReading(hitsIn(known));
1252
+ if (generic || editorWord) {
1253
+ misspelled = true;
1254
+ kept.push(/** @type {string} */ (generic ?? preset));
1255
+ asTyped.set(kept.length - 1, JSON.stringify(name));
1256
+ } else {
1257
+ if (preset) notes.push({name, near: preset});
1258
+ kept.push(name);
1259
+ }
1260
+ continue;
1261
+ }
1262
+ // Words only (no number or size): part of the name unless the whole
1263
+ // name is unknown and the name without them is known.
1264
+ if (
1265
+ tail.every(
1266
+ t =>
1267
+ t.kind === 'style' || (t.kind === 'weight' && !/^\d+$/.test(t.text)),
1268
+ ) &&
1269
+ !(!knownFamily(ctx, name) && knownFamily(ctx, base))
1270
+ ) {
1271
+ kept.push(name);
1272
+ continue;
1273
+ }
1274
+ for (const t of tail) {
1275
+ if (t.kind === 'weight') weight ??= t.value ?? null;
1276
+ else if (t.kind === 'style') style ??= t.text;
1277
+ else if (t.kind === 'size') {
1278
+ size = true;
1279
+ sizeTyped ??= t.text;
1280
+ } else number = true;
1281
+ }
1282
+ kept.push(base);
1283
+ }
1284
+ if (
1285
+ weight == null &&
1286
+ !size &&
1287
+ !style &&
1288
+ !number &&
1289
+ !quotedGeneric &&
1290
+ !misspelled
1291
+ )
1292
+ return null;
1293
+ const rung =
1294
+ weight != null
1295
+ ? Object.entries(HEADING_WEIGHTS).reduce((a, b) =>
1296
+ Math.abs(Number(b[1]) - weight) < Math.abs(Number(a[1]) - weight)
1297
+ ? b
1298
+ : a,
1299
+ )[0]
1300
+ : null;
1301
+ return {
1302
+ why:
1303
+ weight != null
1304
+ ? 'holds a weight where a family goes, so the browser reads it as a family named that and falls back'
1305
+ : size
1306
+ ? 'holds a size where a family goes, so the browser reads it as a family named that and falls back'
1307
+ : style
1308
+ ? 'holds a style where a family goes, so the browser reads it as a family named that and falls back'
1309
+ : number
1310
+ ? 'holds a number where a family goes (a weight is a whole hundred, a size has a unit), so the browser reads it as a family named that and falls back'
1311
+ : quotedGeneric
1312
+ ? 'quotes a generic family, which makes it a family named that, so there is no generic to fall back to'
1313
+ : 'is near a generic family or font the editor knows; a family the editor does not know is kept as written when it is quoted',
1314
+ families: kept.join(', '),
1315
+ asTyped: misspelled
1316
+ ? kept.map((k, i) => asTyped.get(i) ?? k).join(', ')
1317
+ : null,
1318
+ rung,
1319
+ size,
1320
+ textSize: sizeTyped ? textSizePx(sizeTyped) : null,
1321
+ style,
1322
+ };
1323
+ }
1324
+
1325
+ /**
1326
+ * A mode's label before a value, in any spelling: `dark mode:`, `darkmode:`,
1327
+ * `dark-mode:`, `mode dark:` (group 1 or 2 the mode, group 3 the value).
1328
+ */
1329
+ const MODE_LABEL =
1330
+ /^\s*\{?\s*["']?(?:(light|dark)[\s_-]*mode|mode[\s_-]*(light|dark))["']?\s*[:=]\s*(.+?)\s*;?\s*\}?\s*$/i;
1331
+
1332
+ /**
1333
+ * The font list a value with a missing comma or a spaced generic means
1334
+ * (`Georgia serif` is `Georgia, serif`, `Inter, sans serif` is `Inter,
1335
+ * sans-serif`), with why; null when it has neither. A generic is read only
1336
+ * in lower case, so a family named `Source Serif` stays one name.
1337
+ * @param {string} value
1338
+ * @returns {{value: string, why: string} | null}
1339
+ */
1340
+ export function fontListMeant(value) {
1341
+ const v = String(value).trim();
1342
+ // A whole list in one pair of quotes or brackets (`"Inter, serif"`,
1343
+ // `「Inter, serif」`): the quotes go around one family, so the list is
1344
+ // what is inside.
1345
+ const wrapped =
1346
+ /^(?:"([^"]*,[^"]*)"|'([^']*,[^']*)'|「([^」]*,[^」]*)」|『([^』]*,[^』]*)』|“([^”]*,[^”]*)”|‘([^’]*,[^’]*)’|«([^»]*,[^»]*)»)$/.exec(
1347
+ v,
1348
+ );
1349
+ if (wrapped) {
1350
+ const inside = wrapped.slice(1).find(x => x != null) ?? '';
1351
+ return {
1352
+ value: (fontListMeant(inside)?.value ?? inside).trim(),
1353
+ why: 'quotes go around one family name, not the whole list',
1354
+ };
1355
+ }
1356
+ if (/["']/.test(v)) return null;
1357
+ // Families split by `|`, `;` or ` / ` instead of commas.
1358
+ if (
1359
+ // (A pasted declaration, `font-family: Georgia, serif;`, is read
1360
+ // elsewhere: a colon or a trailing `;` is no separator.)
1361
+ !/:|\.(woff2?|ttf|otf)\b/i.test(v) &&
1362
+ /\S\s*(?:\||;|\s\/\s)\s*\S/.test(v)
1363
+ ) {
1364
+ const list = v
1365
+ .split(/\s*(?:\||;|\s\/\s)\s*/)
1366
+ .map(x => x.trim())
1367
+ .filter(Boolean)
1368
+ .join(', ');
1369
+ if (list && list !== v)
1370
+ return {
1371
+ value: fontListMeant(list)?.value ?? list,
1372
+ why: 'families are separated by commas',
1373
+ };
1374
+ }
1375
+ if (/\bsans serif\b/.test(v) && !/\d/.test(v))
1376
+ return {
1377
+ value: v.replace(/\bsans serif\b/g, 'sans-serif'),
1378
+ why: 'the generic family is sans-serif, with a dash',
1379
+ };
1380
+ // A comma missing before the generic family of any family in the list
1381
+ // (`Inter, Georgia serif`), the names in any case (`georgia serif`).
1382
+ const SHORTHAND =
1383
+ /^(\d+(\.\d+)?(px|rem|em|pt|%)?|bold|bolder|lighter|normal|italic|oblique|small-caps)$/i;
1384
+ // A word of a family name: letters (a digit after the first word, as in
1385
+ // `Source Serif 4`), or a generic; never a shorthand's weight or size.
1386
+ const familyWord = (/** @type {string} */ w, /** @type {number} */ i) =>
1387
+ (/^[A-Za-z][A-Za-z0-9]*$/.test(w) && !SHORTHAND.test(w)) ||
1388
+ (i > 0 && /^\d+$/.test(w)) ||
1389
+ GENERIC_FAMILIES.includes(w);
1390
+ const pieces = v.split(/\s*,\s*/);
1391
+ let missing = false;
1392
+ const fixedPieces = pieces.map(piece => {
1393
+ const ws = piece.split(/\s+/);
1394
+ const end = ws[ws.length - 1];
1395
+ if (
1396
+ ws.length > 1 &&
1397
+ GENERIC_FAMILIES.includes(end) &&
1398
+ ws.slice(0, -1).every(familyWord)
1399
+ ) {
1400
+ missing = true;
1401
+ return `${ws.slice(0, -1).join(' ')}, ${end}`;
1402
+ }
1403
+ return piece;
1404
+ });
1405
+ if (missing && pieces.length > 1)
1406
+ return {
1407
+ value: fixedPieces.join(', '),
1408
+ why: 'a comma goes before each generic family',
1409
+ };
1410
+ if (v.includes(',')) return null;
1411
+ const words = v.split(/\s+/);
1412
+ const last = words[words.length - 1];
1413
+ // Only family names before it (capitalized words), never a font
1414
+ // shorthand's weight, style or size.
1415
+ if (
1416
+ words.length > 1 &&
1417
+ GENERIC_FAMILIES.includes(last) &&
1418
+ words.slice(0, -1).every(familyWord)
1419
+ )
1420
+ return {
1421
+ value: `${words.slice(0, -1).join(' ')}, ${last}`,
1422
+ why: `a comma goes before the generic family ${last}`,
1423
+ };
1424
+ return null;
1425
+ }
1426
+
703
1427
  /**
704
1428
  * A value of a type to put in a suggestion, so a suggested command runs.
705
1429
  * @param {string} type
@@ -739,6 +1463,8 @@ function groupOfPropType(prop) {
739
1463
  * @param {string} slug
740
1464
  * @param {string[]} [readers] the CSS properties that read the token
741
1465
  * @param {boolean} [multiplied] whether Core multiplies the token by a size
1466
+ * @param {boolean} [isSet] whether the theme sets the token now (an undo
1467
+ * of it works)
742
1468
  */
743
1469
  function checkTypedValue(
744
1470
  type,
@@ -749,6 +1475,7 @@ function checkTypedValue(
749
1475
  slug,
750
1476
  readers = [],
751
1477
  multiplied = false,
1478
+ isSet = true,
752
1479
  ) {
753
1480
  // The value meant, when what is wrong is how it was typed (a trailing
754
1481
  // `;`, a comment, quotes around it, full-width characters, a font name
@@ -772,17 +1499,37 @@ function checkTypedValue(
772
1499
  }
773
1500
  return null;
774
1501
  };
775
- /** @param {string} what @param {string} example */
1502
+ /** @param {string} what @param {string | null} example */
776
1503
  const bad = (what, example) =>
777
1504
  refuse(
778
1505
  E.ERR_THEME_BAD_VALUE,
779
1506
  `${name} is ${what}; "${value}" is not one.`,
780
1507
  {
1508
+ // Nothing read from the value (no example given): how, never a
1509
+ // stock value.
781
1510
  run: [
782
- `${P} set ${slug} ${name} ${quoteCommandArgument(meant() ?? example)}`,
1511
+ (meant() ?? example) == null
1512
+ ? `${HOW} ${name}`
1513
+ : `${P} set ${slug} ${name} ${quoteCommandArgument(String(meant() ?? example))}`,
783
1514
  ],
784
1515
  },
785
1516
  );
1517
+ // A font family list with a comma missing before a generic family
1518
+ // (`Georgia serif`), or a generic written with a space (`sans serif`): the
1519
+ // list meant.
1520
+ if (type === 'font') {
1521
+ const fixed = fontListMeant(value);
1522
+ if (fixed)
1523
+ refuse(
1524
+ E.ERR_THEME_BAD_VALUE,
1525
+ `"${value}" names a family that exists nowhere: ${fixed.why}.`,
1526
+ {
1527
+ run: [
1528
+ `${P} set ${slug} ${name} ${quoteCommandArgument(fixed.value)}`,
1529
+ ],
1530
+ },
1531
+ );
1532
+ }
786
1533
  // A font file or a link is no family name: never quoted into one.
787
1534
  if (type === 'font') {
788
1535
  const file = fontFileReason(pastedFont(value) || value);
@@ -792,6 +1539,18 @@ function checkTypedValue(
792
1539
  `${P} set ${slug} ${name} ${quoteCommandArgument(exampleOf(type, name))}`,
793
1540
  ],
794
1541
  });
1542
+ // An empty family (`""`, a trailing comma) or one quoted name holding
1543
+ // commas is a broken stack: the browser drops the fallback after it.
1544
+ const pieces = familyPieces(value);
1545
+ if (
1546
+ pieces &&
1547
+ (pieces.some(f => !f.name) ||
1548
+ pieces.some(f => f.quoted && f.name.includes(',')))
1549
+ )
1550
+ bad(
1551
+ 'a font family list with a name for each family',
1552
+ exampleOf(type, name),
1553
+ );
795
1554
  }
796
1555
  if (!isSafeValue(value))
797
1556
  refuse(
@@ -813,14 +1572,24 @@ function checkTypedValue(
813
1572
  if (keyword)
814
1573
  refuse(
815
1574
  E.ERR_THEME_BAD_VALUE,
816
- `"${keyword}" is a CSS keyword, not a value: on ${name} it leaves the token empty, so what reads it drops its style. Give a value such as ${exampleOf(type, name)}, or undo ${name} to go back to the base theme's.`,
1575
+ `"${keyword}" is a CSS keyword, not a value: on ${name} it leaves the token empty, so what reads it drops its style. Give a ${type} value${isSet ? `, or undo ${name} to go back to the base theme's` : ''}.`,
817
1576
  {
1577
+ // How for the token; the undo only when the theme sets it.
818
1578
  run: [
819
- `${P} set ${slug} ${name} ${quoteCommandArgument(exampleOf(type, name))}`,
820
- `${P} undo ${slug} ${name}`,
1579
+ `${HOW} ${name}`,
1580
+ ...(isSet ? [`${P} undo ${slug} ${name}`] : []),
821
1581
  ],
822
1582
  },
823
1583
  );
1584
+ // Math whose units cannot combine (`8 + 2px`, `0.5rem * 1px`, a var()
1585
+ // read as its fallback): the browser drops the whole value.
1586
+ const math = type === 'size' ? calcUnitProblem(value) : null;
1587
+ if (math)
1588
+ refuse(
1589
+ E.ERR_THEME_BAD_VALUE,
1590
+ `${name} is a ${type}; the calc() in "${value}" cannot be worked out: ${math} (with each var() at its fallback, as when the variable is unset), so the browser drops the value.`,
1591
+ {run: [`${HOW} ${name}`]},
1592
+ );
824
1593
  // A var() inside a larger value (calc, max, color-mix) has a fallback of
825
1594
  // the token's kind too, checked like a whole-value var().
826
1595
  if (type !== 'other')
@@ -834,6 +1603,16 @@ function checkTypedValue(
834
1603
  )
835
1604
  )
836
1605
  continue;
1606
+ // A factor in a size's math (`calc(0.75rem * var(--x, 1))`, as the
1607
+ // official themes write their type scale): a plain number there is
1608
+ // what multiplies the size.
1609
+ if (
1610
+ type === 'size' &&
1611
+ within.some(f => /^(calc|min|max|clamp)$/i.test(f)) &&
1612
+ /^[+-]?(\d+\.?\d*|\.\d+)$/.test(fallback.trim()) &&
1613
+ (/[*/]\s*var\(/i.test(value) || /var\([^()]*\)\s*[*/]/i.test(value))
1614
+ )
1615
+ continue;
837
1616
  if (fallback === '')
838
1617
  refuse(
839
1618
  E.ERR_THEME_BAD_VALUE,
@@ -896,26 +1675,74 @@ function checkTypedValue(
896
1675
  );
897
1676
  return;
898
1677
  }
899
- if (type === 'color' && !isFixedColor(value)) bad('a color', '#1f2937');
900
- if (type === 'size' && !isSize(value, name)) {
901
- // With nothing to read from the value, the token's own default (a text
902
- // size stays readable), never one size for every token.
903
- // Followed through the tokens it reads (var(--font-size-base)).
904
- let own = String(TOKENS[name] ?? '').trim();
905
- for (let hop = 0; hop < 4; hop += 1) {
906
- const ref = /^var\(\s*(--[a-z0-9-]+)\s*\)$/i.exec(own)?.[1];
907
- if (!ref) break;
908
- own = String(TOKENS[ref] ?? '').trim();
1678
+ // A var() naming a design token inside a function or a list
1679
+ // (`color-mix(in srgb, var(--radius-element) 50%, red)`, `calc(var(--x) *
1680
+ // 2)`, `0 1px 2px var(--spacing-4)`): the value read with an example of
1681
+ // that token's kind must still be this token's kind. It is refused when
1682
+ // an example of another kind would be, which names the kind the place
1683
+ // takes.
1684
+ if (type !== 'other') {
1685
+ /** @param {string} sample */
1686
+ const holds = sample => {
1687
+ try {
1688
+ checkTypedValue(
1689
+ type,
1690
+ sample,
1691
+ name,
1692
+ TOKENS,
1693
+ typeOf,
1694
+ slug,
1695
+ readers,
1696
+ multiplied,
1697
+ );
1698
+ return true;
1699
+ } catch {
1700
+ return false;
1701
+ }
1702
+ };
1703
+ /** One design token of each kind, for an example of that kind. @type {Map<string, string>} */
1704
+ const ofKind = new Map();
1705
+ for (const t of Object.keys(TOKENS)) {
1706
+ const k = typeOf(t);
1707
+ if (k !== 'other' && !ofKind.has(k)) ofKind.set(k, t);
1708
+ }
1709
+ for (const m of value.matchAll(
1710
+ /var\(\s*(--[a-z0-9-]+)\s*(?:,[^()]*)?\)/gi,
1711
+ )) {
1712
+ const token = m[1];
1713
+ if (!(token in TOKENS)) continue;
1714
+ const kind = typeOf(token);
1715
+ if (kind === 'other' || kind === type) continue;
1716
+ if (holds(value.replace(m[0], exampleOf(kind, token)))) continue;
1717
+ const takes = [...ofKind].find(
1718
+ ([k, t]) => k !== kind && holds(value.replace(m[0], exampleOf(k, t))),
1719
+ )?.[0];
1720
+ if (takes)
1721
+ refuse(
1722
+ E.ERR_THEME_BAD_VALUE,
1723
+ `${name} is a ${type}; in "${value}", ${token} sits where a ${takes} goes, and ${token} is a ${kind}, so the browser would drop the value.`,
1724
+ {
1725
+ run: [`${HOW} --list tokens ${takes}`],
1726
+ },
1727
+ );
909
1728
  }
910
- const sizeExample =
911
- own && isSize(own, name) && !/var\(/.test(own) ? own : '6px';
1729
+ }
1730
+ if (type === 'color' && !isFixedColor(value)) bad('a color', null);
1731
+ if (type === 'size' && !isSize(value, name)) {
1732
+ // The token's own default is never offered as a repair: only a size
1733
+ // read from the value typed.
1734
+ const sizeExample = null;
912
1735
  // The size meant, when one dot or sign is all that is wrong (1.px).
913
1736
  const meant = value.trim().replace(/(\d)\.(?=[a-z%]|$)/gi, '$1');
914
- // A bare number is the size in px.
915
- // A bare number is the size in px; a minus sign is dropped.
916
- const plain = value.trim().replace(/^-(?=\d|\.\d)/, '');
1737
+ // A bare number is the size in px; a minus sign is kept (a negative
1738
+ // size is refused, never offered as its positive).
1739
+ const plain = value.trim();
1740
+ // A bare number below one (a pasted `--radius: 0.5rem` that lost its
1741
+ // unit) has no unit to read it by: no size is guessed, as corners does.
917
1742
  const px = /^[+]?\d*\.?\d+(e[+-]?\d+)?$/i.test(plain)
918
- ? `${Number(plain)}px`
1743
+ ? Number(plain) > 0 && Number(plain) < 1
1744
+ ? null
1745
+ : `${Number(plain)}px`
919
1746
  : /^\d*\.?\d+[a-z%]+$/i.test(plain) && plain !== value.trim()
920
1747
  ? plain
921
1748
  : null;
@@ -1221,16 +2048,32 @@ function checkCycle(thing, value, TOKENS, data, cwd, scope = {}) {
1221
2048
  }
1222
2049
 
1223
2050
  /**
1224
- * The CSS color name nearest a word typed as a color (`banan` is not one,
1225
- * `rd` is red), or null when none is near.
2051
+ * The color a value typed as one most likely meant: a comma rgb() or hsl()
2052
+ * CSS does not take as written, in the syntax CSS reads its channels in
2053
+ * (`hsl(0, 100, 50)` is `hsl(0 100 50)`), else the CSS color name nearest a
2054
+ * word (`banan` is not one, `rd` is red); null when none is near.
1226
2055
  * @param {string} v
1227
2056
  */
1228
2057
  function nearestColorName(v) {
2058
+ const asRead = colorAsCssReads(v);
2059
+ if (asRead) return asRead;
1229
2060
  const w = v.trim().toLowerCase();
1230
2061
  if (!/^[a-z]+$/.test(w)) return null;
1231
2062
  return nearest(w, COLOR_NAMES)[0] ?? null;
1232
2063
  }
1233
2064
 
2065
+ /**
2066
+ * Old keywords a property's grammar lists that no current browser applies,
2067
+ * each with the keyword that does what it meant.
2068
+ * @type {Record<string, Record<string, string>>}
2069
+ */
2070
+ const OBSOLETE_KEYWORDS = {
2071
+ cursor: {hand: 'pointer'},
2072
+ };
2073
+ documentReadings(
2074
+ Object.values(OBSOLETE_KEYWORDS).flatMap(words => Object.entries(words)),
2075
+ );
2076
+
1234
2077
  /**
1235
2078
  * Why a value is not one the property takes, or null. Colors are checked
1236
2079
  * by the editor's own color check; a property css-tree has no grammar for
@@ -1251,12 +2094,18 @@ function propertyProblem(prop, value) {
1251
2094
  takes: `a value its CSS grammar takes in each var() fallback too (${grammarText(known)})`,
1252
2095
  near: initialOf(prop),
1253
2096
  };
2097
+ // An old keyword the grammar still lists but no current browser
2098
+ // applies (`cursor: hand`): the keyword that does what it meant.
2099
+ const obsolete = OBSOLETE_KEYWORDS[prop]?.[v.toLowerCase()];
2100
+ if (obsolete)
2101
+ return {
2102
+ takes: `a value current browsers apply ("${v}" is an old keyword none applies; ${obsolete} does what it meant)`,
2103
+ near: obsolete,
2104
+ };
1254
2105
  if (matchValue(prop, v))
1255
2106
  return belowRange(prop, v)
1256
- ? {
1257
- takes: 'a value of 0 or more',
1258
- near: v.replace(/(^|[\s(,/])-(?=\.?\d)/g, '$1'),
1259
- }
2107
+ ? // A negative value is no size of the other sign: no line mirrors it.
2108
+ {takes: 'a value of 0 or more', near: null}
1260
2109
  : null;
1261
2110
  // The same value as it was meant to be typed (a font name quoted, a
1262
2111
  // trailing `;` gone), when the property takes that.
@@ -1281,9 +2130,7 @@ function propertyProblem(prop, value) {
1281
2130
  null)
1282
2131
  : null;
1283
2132
  // A value that works, for the suggestion: a keyword near the one typed,
1284
- // the property's initial value, or an example of its kind; each checked.
1285
- const example = exampleOf(groupOfPropType(prop), prop);
1286
- const initial = initialOf(prop);
2133
+ // or the value typed cleaned; each checked.
1287
2134
  // A bare number on a length property means px (`padding 4` → `4px`, each
1288
2135
  // number in a list too), when the property takes that.
1289
2136
  // Each bare number token gets px (a mixed list `4 8px`, `8 / 4`, an
@@ -1296,31 +2143,99 @@ function propertyProblem(prop, value) {
1296
2143
  Number(num) === 0 ? `${pre}${num}` : `${pre}${num}px`,
1297
2144
  )
1298
2145
  : null;
1299
- // A suggestion is offered only when the property takes it, in range too.
2146
+ // A suggestion is offered only when the property takes it, in range too,
2147
+ // and never a reset the input did not hold (0, none, 1, auto, normal):
2148
+ // following it would undo what was asked. A reset typed with a typo
2149
+ // (`nnone`, `normall`: a word within two edits of it) is that reset,
2150
+ // corrected.
2151
+ const RESETS =
2152
+ /^(0|0px|none|1|auto|normal|initial|unset|inherit|revert|transparent)$/i;
2153
+ const typedAs = (/** @type {string} */ x) => x === typed || typoOf(typed, x);
1300
2154
  const takes = (/** @type {string | null} */ x) =>
1301
- x != null && matchValue(prop, x) != null && !belowRange(prop, x);
2155
+ x != null &&
2156
+ matchValue(prop, x) != null &&
2157
+ !belowRange(prop, x) &&
2158
+ !(RESETS.test(x.trim()) && !typedAs(x.trim().toLowerCase()));
2159
+ // A lone length on a shorthand where it is only a position (background,
2160
+ // mask) wipes the rest: no px is guessed there.
2161
+ const pxFits = !/^(background|mask)$/i.test(prop);
2162
+ // Words with a documented reading on a property (the allowlist a repair
2163
+ // may map through).
2164
+ const WORDS = PROPERTY_WORDS;
2165
+ // A weight word is its number (the same table the headings dial reads);
2166
+ // text in content is that text, quoted.
2167
+ const weightWord = typed.replace(/[\s-]+/g, '');
2168
+ const weight = HEADING_WEIGHTS[weightWord] ?? WEIGHT_WORDS[weightWord];
2169
+ const mapped =
2170
+ WORDS[prop]?.[typed.replace(/\s+/g, '-')] ??
2171
+ (prop === 'font-weight' && weight ? weight : null) ??
2172
+ (prop === 'content' && !/^["']|["']$/.test(v) ? JSON.stringify(v) : null) ??
2173
+ null;
1302
2174
  return {
1303
2175
  takes: `a value its CSS grammar takes (${grammarText(known)})`,
1304
2176
  near:
1305
- (takes(withPx) ? withPx : null) ??
1306
- // Below the property's range (a negative width): the same, 0 or more.
1307
- (withPx && takes(withPx.replace(/(^|[\s/(,])-(?=\.?\d)/g, '$1'))
1308
- ? withPx.replace(/(^|[\s/(,])-(?=\.?\d)/g, '$1')
1309
- : null) ??
2177
+ (mapped && matchValue(prop, mapped) != null ? mapped : null) ??
2178
+ (pxFits && takes(withPx) ? withPx : null) ??
2179
+ // Below the property's range (a negative width) is no size of the
2180
+ // other sign: the mirrored value is never offered.
1310
2181
  (takes(joined) && joined !== v ? joined : null) ??
1311
- // Several values on a property that takes one (padding-top with four):
1312
- // the first of them, when it is one the property takes.
2182
+ // A comma between two whole numbers of 1 or more that the grammar
2183
+ // pairs with a slash separates them (`aspect-ratio 16,9` is 16 / 9,
2184
+ // `grid-row 2,4` is 2 / 4), unless it reads as a decimal comma: written
2185
+ // tight after a 1 (`1,5`) or after one digit with two or more after it
2186
+ // (`1,78`, `2,35`), where the property takes that decimal. Any other
2187
+ // comma between digits (`0,75`) is a decimal comma.
2188
+ (() => {
2189
+ const pair = /^\s*([1-9]\d*)(\s*),(\s*)([1-9]\d*)\s*$/.exec(v);
2190
+ if (!pair) return null;
2191
+ const [, a, before, after, b] = pair;
2192
+ const decimal =
2193
+ !before &&
2194
+ !after &&
2195
+ (a === '1' || (a.length === 1 && b.length >= 2)) &&
2196
+ takes(`${a}.${b}`);
2197
+ return !decimal && takes(`${a} / ${b}`) ? `${a} / ${b}` : null;
2198
+ })() ??
2199
+ // A comma between digits is a decimal point (1,5rem is 1.5rem), never
2200
+ // a split into layers.
2201
+ (takes(commaNumbers(v, thousandsSetting(prop))) &&
2202
+ commaNumbers(v, thousandsSetting(prop)) !== v
2203
+ ? commaNumbers(v, thousandsSetting(prop))
2204
+ : null) ??
2205
+ // Several values of one kind on a property that takes one
2206
+ // (padding-top with four lengths): the first as typed, with px only
2207
+ // when the property takes no bare number. Never one value of a
2208
+ // shorthand of several kinds (`all 200` for transition). A property
2209
+ // whose grammar pairs them with a slash (`aspect-ratio 16 9`,
2210
+ // `grid-row 2 4`) takes the pair, never its first half.
1313
2211
  (() => {
1314
- const first = splitTop((withPx ?? joined).trim(), ' ')[0];
1315
- return first && first !== v && takes(first) ? first : null;
2212
+ const all = splitTop(v.trim(), ' ');
2213
+ const slashed = all.join(' / ');
2214
+ if (all.length === 2 && takes(slashed)) return slashed;
2215
+ if (all.length > 1 && takes(all.slice(0, 2).join(' / '))) return null;
2216
+ const same = sameKindValues(v);
2217
+ if (!same) return null;
2218
+ const first = same.items[0];
2219
+ const px = same.kind === '' ? `${first}px` : null;
2220
+ return takes(first) ? first : pxFits && px && takes(px) ? px : null;
1316
2221
  })() ??
1317
2222
  (near && takes(near) ? near : null) ??
1318
- // A value with numbers never falls back to the property's reset
1319
- // (padding 0 would remove what was asked for).
1320
- (/\d/.test(v)
1321
- ? null
1322
- : ((takes(initial) ? initial : null) ??
1323
- (takes(example) ? example : null))),
2223
+ // Layers typed with one too many or an empty one (`url(a.png), red,
2224
+ // blue`, `red,,blue`): the layers before the last, else one of them,
2225
+ // when the property takes it. Never the property's reset or a stock
2226
+ // example: a repair carries only what was typed.
2227
+ (() => {
2228
+ const layers = splitTop(v.trim(), ',')
2229
+ .map(x => x.trim())
2230
+ .filter(Boolean);
2231
+ if (layers.length < 2 && !/,\s*,/.test(v)) return null;
2232
+ const tries = [
2233
+ layers.join(', '),
2234
+ layers.slice(0, -1).join(', '),
2235
+ ...layers,
2236
+ ];
2237
+ return tries.find(x => x && x !== v && takes(x)) ?? null;
2238
+ })(),
1324
2239
  };
1325
2240
  }
1326
2241
 
@@ -1388,41 +2303,1033 @@ function baseReads(ctx, like, token) {
1388
2303
  }
1389
2304
 
1390
2305
  /**
1391
- * Check one setting and give it back ready to store, or refuse. What it
1392
- * accepts, the settings loader takes too: the loader's own check runs last,
1393
- * so a saved setting never blocks the theme.
1394
- * @param {import('./_settings.mjs').Ctx} ctx
1395
- * @param {string} slug
1396
- * @param {import('./_settings.mjs').ThemeData} data
1397
- * @param {string} thing
1398
- * @param {string | undefined} value
1399
- * @param {SetFlags} flags
1400
- * @param {boolean} [unset] an undo of one setting: only the identity of the setting is checked
1401
- * @returns {import('./_settings.mjs').Setting}
2306
+ * The headings rung nearest a weight number (800 is heavy).
2307
+ * @param {number} weight
1402
2308
  */
1403
- export function checkSetting(
1404
- ctx,
1405
- slug,
1406
- data,
1407
- thing,
1408
- value,
1409
- flags,
1410
- unset = false,
1411
- ) {
1412
- // Any other dial's value pasted with its property name (`font-size:
1413
- // 18px;` for text-size, `color: #e11d48` for accent) is the value: one
1414
- // path for every dial (the font dial reads its own below).
1415
- if (!unset && typeof value === 'string' && DIALS[thing] && thing !== 'font') {
1416
- const d = pastedDeclaration(value);
1417
- if (d?.value) value = d.value;
2309
+ const weightRung = weight =>
2310
+ Object.entries(HEADING_WEIGHTS).reduce((a, b) =>
2311
+ Math.abs(Number(b[1]) - weight) < Math.abs(Number(a[1]) - weight) ? b : a,
2312
+ )[0];
2313
+ documentNumericTable(
2314
+ ['headings', 'font-weight'],
2315
+ Object.entries(HEADING_WEIGHTS).map(([w, n]) => [w, Number(n)]),
2316
+ [1, 1000],
2317
+ );
2318
+ // A font weight runs from 1 to 1000.
2319
+ documentRange(['font-weight', '--font-weight-*'], 1, 1000);
2320
+ documentNumericTable(
2321
+ ['spacing'],
2322
+ SPACING.map(([name, factor]) => [name, factor]),
2323
+ );
2324
+ documentNumericTable(
2325
+ ['text-size'],
2326
+ TEXT_SIZE.map(([name, px]) => [name, px]),
2327
+ );
2328
+ // The text size number is the body size in pixels, 10 to 32; vibrancy
2329
+ // runs from 0 to 100.
2330
+ documentRange(['text-size'], 10, 32);
2331
+ documentRange(['vibrancy'], 0, 100);
2332
+ documentReadings(TEXT_SIZE.map(([name, px]) => [name, `${px}px`]));
2333
+ documentReadings(Object.entries(HEADING_TRACKING));
2334
+ // `bold` given a no (false, off) is the normal weight.
2335
+ documentReadings(['false', 'off', 'no', 'none'].map(w => [w, 'normal']));
2336
+ /**
2337
+ * The CSS absolute-size keywords that are no text-size rung, as the px
2338
+ * CSS gives each at a 16px root.
2339
+ */
2340
+ const CSS_SIZE_KEYWORDS = wordTable(
2341
+ /** @type {Record<string, number>} */ ({
2342
+ 'xx-small': 9,
2343
+ 'x-small': 10,
2344
+ 'x-large': 24,
2345
+ 'xx-large': 32,
2346
+ 'xxx-large': 48,
2347
+ }),
2348
+ );
2349
+ documentReadings(
2350
+ Object.entries(CSS_SIZE_KEYWORDS)
2351
+ .filter(([, px]) => px >= 10 && px <= 32)
2352
+ .map(([w, px]) => [w, String(px)]),
2353
+ );
2354
+ // A weight word read as the headings rung its number is nearest.
2355
+ documentReadings(
2356
+ Object.entries(WEIGHT_WORDS).map(([w, n]) => [w, weightRung(Number(n))]),
2357
+ );
2358
+ /** Words for no rounding: corners square. */
2359
+ const NO_ROUNDING = ['0', '0%', 'none', 'sharp', 'zero', 'no', 'flat'];
2360
+ /** Words for no space: spacing's tightest rung. */
2361
+ const NO_SPACE = ['0', 'none', 'zero', 'no', 'off'];
2362
+ documentReadings(NO_ROUNDING.map(w => [w, 'square']));
2363
+ documentReadings(NO_SPACE.map(w => [w, SPACING[0][0]]));
2364
+ documentReadings(
2365
+ Object.values(DIAL_WORDS).flatMap(words => Object.entries(words)),
2366
+ );
2367
+ /** State words a value may be labeled with. */
2368
+ const STATE_WORDS = [
2369
+ 'hover',
2370
+ 'active',
2371
+ 'focus',
2372
+ 'focus-visible',
2373
+ 'focus-within',
2374
+ 'disabled',
2375
+ 'pressed',
2376
+ 'selected',
2377
+ 'checked',
2378
+ 'open',
2379
+ 'expanded',
2380
+ 'visited',
2381
+ ];
2382
+ /** Words for a kind of screen a value may be labeled with. */
2383
+ const DEVICE_WORDS = [
2384
+ 'phone',
2385
+ 'phones',
2386
+ 'mobile',
2387
+ 'tablet',
2388
+ 'tablets',
2389
+ 'desktop',
2390
+ 'laptop',
2391
+ 'ipad',
2392
+ 'iphone',
2393
+ 'android',
2394
+ 'ios',
2395
+ 'touch',
2396
+ 'small-screen',
2397
+ 'small-screens',
2398
+ 'large-screen',
2399
+ 'large-screens',
2400
+ 'print',
2401
+ ];
2402
+
2403
+ /**
2404
+ * The word a value is labeled with and the value after it (`dark: #2563eb`,
2405
+ * `"corners": "pill"`, `{"dark": "#2563eb"}`, `dark=#2563eb`, `dark mode:
2406
+ * #2563eb`, `textSize: 18`), the word as a dashed name; null when the value
2407
+ * holds no label.
2408
+ * @param {string} value
2409
+ * @returns {{word: string, rest: string, when?: string} | null}
2410
+ */
2411
+ function valueLabel(value) {
2412
+ // A mode label in any spelling (`dark mode: red`, `darkmode: red`,
2413
+ // `mode dark: red`) is that mode's label: one reading, read first so the
2414
+ // value is never taken for the label.
2415
+ const modeLabel = MODE_LABEL.exec(String(value));
2416
+ if (modeLabel)
2417
+ return {
2418
+ word: (modeLabel[1] ?? modeLabel[2]).toLowerCase(),
2419
+ rest: modeLabel[3].trim(),
2420
+ };
2421
+ // A flag's label after the value (`red mode: dark`, `red state: hover`,
2422
+ // `red part: card`) reads as the same label before it (`dark: red`); a
2423
+ // variant or size after it (`red variant: primary`) keeps its prop.
2424
+ const trail =
2425
+ /^\s*(.+?)\s+(mode|theme|state|part|on|variant|size|when)\s*[:=]\s*([a-z][a-z0-9:-]*)\s*;?\s*$/i.exec(
2426
+ String(value),
2427
+ );
2428
+ if (trail && !/[:=]/.test(trail[1])) {
2429
+ const flag = trail[2].toLowerCase();
2430
+ const word = trail[3].toLowerCase();
2431
+ if (/^(variant|size|when)$/.test(flag))
2432
+ return {
2433
+ word: 'when',
2434
+ rest: trail[1].trim(),
2435
+ when: flag === 'when' ? word : `${flag}:${word}`,
2436
+ };
2437
+ return {word, rest: trail[1].trim()};
1418
2438
  }
1419
- // The font dial's value as pasted from a stylesheet (`Georgia, serif;`,
1420
- // a comment, `!important`): a refusal suggests the font it names, when
1421
- // set takes that.
1422
- // A font pasted with its property name is the family list it names.
1423
- if (
1424
- !unset &&
1425
- typeof value === 'string' &&
2439
+ const m =
2440
+ /^\s*\{?\s*["']?([a-zA-Z][a-zA-Z0-9 _-]*?|--[a-z0-9-]+)["']?\s*[:=]\s*(.+?)\s*;?\s*\}?\s*$/.exec(
2441
+ String(value),
2442
+ );
2443
+ if (!m || /^https?$/i.test(m[1])) return null;
2444
+ const word = m[1]
2445
+ .trim()
2446
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
2447
+ .replace(/[\s_]+/g, '-')
2448
+ .toLowerCase();
2449
+ const rest = m[2].trim().replace(/^"(.*)"\s*,?$/, '$1');
2450
+ return {word, rest};
2451
+ }
2452
+
2453
+ /**
2454
+ * Whether a label is the setting's own name (`accent: red` for accent,
2455
+ * `font-family: Inter` for font).
2456
+ * @param {string} thing @param {string} word
2457
+ */
2458
+ const ownLabel = (thing, word) =>
2459
+ word === thing ||
2460
+ (thing === 'font' && word === 'font-family') ||
2461
+ (thing.startsWith('--font-family') &&
2462
+ (word === 'font-family' || word === 'font')) ||
2463
+ (thing === 'text-size' && word === 'font-size');
2464
+
2465
+ /**
2466
+ * Whether a family is one the editor knows: a system family on the theme
2467
+ * build's list, an open font in its table or a preset's family, or one
2468
+ * whose @fontsource package the project has installed.
2469
+ * @param {any} ctx
2470
+ * @param {string} family without quotes
2471
+ */
2472
+ function knownFamily(ctx, family) {
2473
+ const name = family.trim().toLowerCase();
2474
+ if (!name) return false;
2475
+ if (isSystemFamily(family)) return true;
2476
+ if (
2477
+ [
2478
+ ...Object.values(OPEN_FONTS).map(f => f.family),
2479
+ ...Object.values(FONTS).map(f => f[0]),
2480
+ ].some(f => f.toLowerCase() === name)
2481
+ )
2482
+ return true;
2483
+ try {
2484
+ ctx?.project?.req?.resolve(`${fontsourcePackageOf(family)}/package.json`);
2485
+ return Boolean(ctx?.project?.req);
2486
+ } catch {
2487
+ return false;
2488
+ }
2489
+ }
2490
+
2491
+ /**
2492
+ * The CSS properties a dial sets, whose pasted declaration is the dial's
2493
+ * own value (`border-radius: 8px` for corners, `color: #e11d48` for a
2494
+ * color dial). A dial with none takes no pasted property.
2495
+ * @type {Record<string, (word: string) => boolean>}
2496
+ */
2497
+ const DIAL_PROPERTIES = {
2498
+ corners: w => /^border(-[a-z]+)*-radius$/.test(w),
2499
+ spacing: w => /^(padding|margin|gap|row-gap|column-gap)(-[a-z]+)*$/.test(w),
2500
+ 'text-size': w => w === 'font-size',
2501
+ font: w => w === 'font' || w === 'font-family',
2502
+ headings: w => w === 'font-weight' || w === 'letter-spacing',
2503
+ ...Object.fromEntries(
2504
+ PALETTE_DIALS.map(d => [
2505
+ d,
2506
+ (/** @type {string} */ w) => w === 'background' || COLOR_PROPS.test(w),
2507
+ ]),
2508
+ ),
2509
+ };
2510
+
2511
+ /**
2512
+ * Whether a CSS property pasted before a value (`margin: 8px`) is one the
2513
+ * setting sets: its own label, a property a dial sets, a property that
2514
+ * reads the token, or, for a color token, a color property.
2515
+ * @param {any} ctx
2516
+ * @param {string} thing
2517
+ * @param {string} word
2518
+ * @param {boolean} partProperty
2519
+ */
2520
+ function labelOwned(ctx, thing, word, partProperty) {
2521
+ if (word === thing || ownLabel(thing, word)) return true;
2522
+ if (partProperty) return false;
2523
+ if (DIALS[thing]) return DIAL_PROPERTIES[thing]?.(word) ?? false;
2524
+ if (thing.startsWith('--')) {
2525
+ const kebab = (/** @type {string} */ p) =>
2526
+ p.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`);
2527
+ return (
2528
+ (ctx?.C?.propsReading?.(thing) ?? []).some(
2529
+ (/** @type {string} */ p) => kebab(p) === word,
2530
+ ) ||
2531
+ (isColorToken(thing) && (word === 'background' || COLOR_PROPS.test(word)))
2532
+ );
2533
+ }
2534
+ return false;
2535
+ }
2536
+
2537
+ /**
2538
+ * The one mode a light-only or dark-only theme shows, or null.
2539
+ * @param {{mode?: string} | null | undefined} data
2540
+ * @returns {'light' | 'dark' | null}
2541
+ */
2542
+ function oneModeOfTheme(data) {
2543
+ return data?.mode === 'light-only'
2544
+ ? 'light'
2545
+ : data?.mode === 'dark-only'
2546
+ ? 'dark'
2547
+ : null;
2548
+ }
2549
+
2550
+ /**
2551
+ * Whether any of the parts draws a line of that kind (a border, one side's
2552
+ * border, an outline) with a width, at rest or in the state named: then its
2553
+ * color alone can differ by mode.
2554
+ * @param {any} C the part census
2555
+ * @param {string[]} parts
2556
+ * @param {string} prop border, border-<side> or outline
2557
+ * @param {string | undefined | null} [state]
2558
+ * @returns {boolean}
2559
+ */
2560
+ export function drawsLine(C, parts, prop, state) {
2561
+ // (A side's line is drawn by the side's own width or the shared one.)
2562
+ const keys =
2563
+ prop === 'border'
2564
+ ? [
2565
+ 'border-width',
2566
+ ...['top', 'right', 'bottom', 'left'].map(x => `border-${x}-width`),
2567
+ ]
2568
+ : prop.startsWith('border-')
2569
+ ? [`${prop}-width`, 'border-width']
2570
+ : [`${prop}-width`];
2571
+ return parts.some(t => {
2572
+ const at = C.MAP[t]?.at ?? {};
2573
+ return keys.some(k =>
2574
+ Object.entries(at[k] ?? {}).some(
2575
+ ([sel, w]) =>
2576
+ !/^\s*0(?:px)?\s*$/.test(String(w)) &&
2577
+ (state ? sel.includes(state) : !/:/.test(sel)),
2578
+ ),
2579
+ );
2580
+ });
2581
+ }
2582
+
2583
+ /**
2584
+ * Whether a part reads a token in any of its rules.
2585
+ * @param {any} C the part census
2586
+ * @param {string} part
2587
+ * @param {string} token
2588
+ */
2589
+ function readsToken(C, part, token) {
2590
+ return Object.keys(GROUPS).some(g =>
2591
+ (C.partReads(part, g) ?? []).some(
2592
+ (/** @type {{token: string}} */ r) => r.token === token,
2593
+ ),
2594
+ );
2595
+ }
2596
+
2597
+ /**
2598
+ * The parts drawn as pills: they read --radius-full, which the corners
2599
+ * dial leaves round.
2600
+ * @param {any} C the part census
2601
+ * @returns {string[]}
2602
+ */
2603
+ export function pillParts(C) {
2604
+ return Object.keys(C.MAP).filter(p => readsToken(C, p, '--radius-full'));
2605
+ }
2606
+
2607
+ /**
2608
+ * The surfaces whose border the shared border tokens never reach: the
2609
+ * containers, menus and overlays (a part with an elevation shadow, or one
2610
+ * the layer runtime places: a tooltip) whose border reads no border width
2611
+ * or border color token. Some draw none (a dialog); some draw a fixed
2612
+ * line of their own (a popover's 1px), which --border-width does not
2613
+ * widen. A family member the census does not record is kept.
2614
+ * @param {any} C the part census
2615
+ * @returns {string[]}
2616
+ */
2617
+ export function borderlessSurfaces(C) {
2618
+ const rest = (/** @type {{when: string[]}} */ r) =>
2619
+ r.when.some(w => !/:|selected/.test(w));
2620
+ /** Whether the layer runtime places the part (its sizes read the layer's inset). @param {string} pt */
2621
+ const layered = pt =>
2622
+ Object.values(C.MAP[pt]?.own ?? {}).some((/** @type {any} */ x) =>
2623
+ (x?.values ?? []).some((/** @type {unknown} */ v) =>
2624
+ /--astryx-layer-/.test(String(v)),
2625
+ ),
2626
+ );
2627
+ const candidates = new Set([
2628
+ ...(FAMILIES.containers ?? []),
2629
+ ...(FAMILIES.menus ?? []),
2630
+ ...Object.keys(C.MAP).filter(
2631
+ pt =>
2632
+ layered(pt) ||
2633
+ (C.partReads(pt, 'shadow') ?? []).some(
2634
+ (/** @type {any} */ r) => /^--shadow-/.test(r.token) && rest(r),
2635
+ ),
2636
+ ),
2637
+ ]);
2638
+ return [...candidates].filter(
2639
+ pt =>
2640
+ !(C.partReads(pt, 'border') ?? []).some(
2641
+ (/** @type {{token: string}} */ r) =>
2642
+ r.token === '--border-width' || /^--color-border/.test(r.token),
2643
+ ),
2644
+ );
2645
+ }
2646
+
2647
+ /**
2648
+ * The parts that draw a divider with the shared border width: one side's
2649
+ * border (a table cell's bottom rule) or an inner line (a divider's), not
2650
+ * a box around the part. A wider --border-width makes their rules heavy.
2651
+ * @param {any} C the part census
2652
+ * @returns {string[]}
2653
+ */
2654
+ export function dividerParts(C) {
2655
+ return Object.keys(C.MAP).filter(pt => {
2656
+ const at = C.MAP[pt]?.at ?? {};
2657
+ /** @param {string} k */
2658
+ const reads = k =>
2659
+ Object.values(at[k] ?? {}).some(v => /--border-width/.test(String(v)));
2660
+ if (reads('border-width')) return false;
2661
+ const sides = Object.keys(at).filter(
2662
+ k => /^border-[a-z-]+-width$/.test(k) && reads(k),
2663
+ );
2664
+ const inner = (C.MAP[pt]?.inside?.['--border-width'] ?? []).some(
2665
+ (/** @type {string} */ p) =>
2666
+ /^(height|width|block-size|inline-size)$/.test(p),
2667
+ );
2668
+ return sides.length === 1 || (!sides.length && inner);
2669
+ });
2670
+ }
2671
+
2672
+ /**
2673
+ * What a text property CSS inherits, set on a part, also reaches: the parts
2674
+ * inside it that set no such property of their own, said in one line; null
2675
+ * for any other property or when none does.
2676
+ * @param {import('./_settings.mjs').Ctx} ctx
2677
+ * @param {{on?: string, only?: boolean, thing?: string}} s
2678
+ * @param {string} prop kebab-case
2679
+ * @returns {string | null}
2680
+ */
2681
+ export function inheritedReach(ctx, s, prop) {
2682
+ if (
2683
+ !/^(font-(size|weight|style|family|variant)|text-(transform|align)|letter-spacing|line-height|white-space|word-spacing)$/.test(
2684
+ prop,
2685
+ )
2686
+ )
2687
+ return null;
2688
+ const reached = [
2689
+ ...new Set(
2690
+ partsOf(ctx, /** @type {any} */ (s)).flatMap(t =>
2691
+ /** @type {string[]} */ (ctx.C.MAP[t]?.contains ?? []).filter(
2692
+ inner =>
2693
+ ctx.project.target.has(inner) && !ctx.C.MAP[inner]?.own?.[prop],
2694
+ ),
2695
+ ),
2696
+ ),
2697
+ ];
2698
+ return reached.length
2699
+ ? `${prop} is inherited, so it also reaches ${reached.slice(0, 4).join(', ')}${reached.length > 4 ? ' and more' : ''} inside ${s.on}, which set no ${prop} of their own`
2700
+ : null;
2701
+ }
2702
+
2703
+ /**
2704
+ * The states `set` takes on a part: the ones its doc lists and the ones
2705
+ * every part takes, less any a change in it is refused for while the same
2706
+ * change without it passes (a state that never applies there). `how` lists
2707
+ * these, and a state that is not one names them.
2708
+ * @param {import('./_settings.mjs').Ctx} ctx
2709
+ * @param {string} slug
2710
+ * @param {any} data
2711
+ * @param {string} part
2712
+ * @returns {string[]}
2713
+ */
2714
+ export function settableStates(ctx, slug, data, part) {
2715
+ const t = ctx.project.target.get(part);
2716
+ if (!t) return [];
2717
+ const takes = (/** @type {string | undefined} */ state) => {
2718
+ try {
2719
+ checkSetting(ctx, slug, data, 'opacity', '1', {
2720
+ on: part,
2721
+ ...(state ? {state} : {}),
2722
+ });
2723
+ return true;
2724
+ } catch {
2725
+ return false;
2726
+ }
2727
+ };
2728
+ const plain = takes(undefined);
2729
+ return [...new Set([...t.states, ...COMMON_STATES])].filter(
2730
+ state => !plain || takes(state),
2731
+ );
2732
+ }
2733
+
2734
+ /**
2735
+ * The paints of a property Core gives a part in its variants and states at
2736
+ * rest (a primary button's accent fill, a checked box's), which a setting
2737
+ * of that property on the plain part covers in every one of them (the
2738
+ * theme's rules sit over Core's). Each with the condition as set names it
2739
+ * (`--when variant:primary`, `--state checked`) when it can, else as Core's
2740
+ * condition (`checked=checked`, `aria-current=page`); and the token the
2741
+ * plain part reads at rest, if any.
2742
+ * @param {import('./_settings.mjs').Ctx} ctx
2743
+ * @param {string} part
2744
+ * @param {string} prop a background or color property
2745
+ * @returns {{rest: string | null, covered: Array<{token: string, flags: string | null, cond: string}>}}
2746
+ */
2747
+ export function coveredPaints(ctx, part, prop) {
2748
+ const C = ctx.C;
2749
+ const group = C.groupOfProp(prop);
2750
+ const props = /^background/.test(prop)
2751
+ ? ['background-color', 'background']
2752
+ : [prop];
2753
+ const t = ctx.project.target.get(part);
2754
+ const reads = (group ? C.partReads(part, group) : []).filter(
2755
+ r => r.props.some(x => props.includes(x)) && !/overlay|tint/.test(r.token),
2756
+ );
2757
+ const rest = reads.find(r => r.when.includes(''))?.token ?? null;
2758
+ /** @type {Array<{token: string, flags: string | null, cond: string}>} */
2759
+ const covered = [];
2760
+ for (const r of reads)
2761
+ for (const w of r.when) {
2762
+ // Only the conditions of the part at rest: a pseudo-class (hover) is
2763
+ // a state set names itself.
2764
+ const cond = w
2765
+ .replace(/^--when /, '')
2766
+ .replace(/\s*\(not settable:.*$/, '')
2767
+ .trim();
2768
+ if (!cond || /(^|\s):|--state/.test(cond)) continue;
2769
+ // One condition set can name: a state of the part's own (written as
2770
+ // its name) with --state, a visual prop of its with --when.
2771
+ const one = /^([\w-]+)[=:]([\w-]+)$/.exec(cond);
2772
+ const [k, v] = one ? [one[1], one[2]] : ['', ''];
2773
+ const flags = !one
2774
+ ? null
2775
+ : t?.states.includes(k) && (v === k || v === 'true')
2776
+ ? `--state ${k}`
2777
+ : t?.props.includes(k)
2778
+ ? `--when ${k}:${v}`
2779
+ : null;
2780
+ covered.push({token: r.token, flags, cond: cond.replace(':', '=')});
2781
+ }
2782
+ return {rest, covered};
2783
+ }
2784
+
2785
+ /**
2786
+ * The colors a part's color prop may show when none is given: its default
2787
+ * as its doc gives it; with none (Text's depends on its type), each value
2788
+ * of the prop whose text token the part's own color reads, in the order
2789
+ * the prop lists them. Empty with no color prop.
2790
+ * @param {{type?: string, default?: string | null} | undefined} prop
2791
+ * @param {Record<string, unknown> | undefined} reads the tokens the part's color reads (its part data)
2792
+ * @returns {string[]}
2793
+ */
2794
+ function colorPropDefaults(prop, reads) {
2795
+ if (!prop) return [];
2796
+ const own = /^'([\w-]+)'$/.exec(String(prop.default ?? '').trim())?.[1];
2797
+ if (own) return [own];
2798
+ return [...String(prop.type ?? '').matchAll(/'([\w-]+)'/g)]
2799
+ .map(m => m[1])
2800
+ .filter(v => Object.hasOwn(reads ?? {}, `--color-text-${v}`));
2801
+ }
2802
+
2803
+ /**
2804
+ * Check one setting and give it back ready to store, or refuse. What it
2805
+ * accepts, the settings loader takes too: the loader's own check runs last,
2806
+ * so a saved setting never blocks the theme.
2807
+ * @param {import('./_settings.mjs').Ctx} ctx
2808
+ * @param {string} slug
2809
+ * @param {import('./_settings.mjs').ThemeData} data
2810
+ * @param {string} thing
2811
+ * @param {string | undefined} value
2812
+ * @param {SetFlags} flags
2813
+ * @param {boolean} [unset] an undo of one setting: only the identity of the setting is checked
2814
+ * @param {{reads?: ReadonlySet<string>}} [scope] `reads`: the custom
2815
+ * properties the theme itself sets where the value is read, which a var()
2816
+ * in it reads as it reads a design token
2817
+ * @returns {import('./_settings.mjs').Setting}
2818
+ */
2819
+ export function checkSetting(
2820
+ ctx,
2821
+ slug,
2822
+ data,
2823
+ thing,
2824
+ value,
2825
+ flags,
2826
+ unset = false,
2827
+ {reads} = {},
2828
+ ) {
2829
+ // Any other dial's value pasted with its property name (`font-size:
2830
+ // 18px;` for text-size, `color: #e11d48` for accent) is the value: one
2831
+ // path for every dial (the font dial reads its own below).
2832
+ // A light and a dark color typed as one value: a token takes both as
2833
+ // light-dark() or one --mode at a time; a color dial takes one color and
2834
+ // makes both modes from it. Never one of them for both.
2835
+ // A light-dark() written with another separator (`light-dark(red /
2836
+ // blue)`, `light-dark(red; blue)`): the pair meant, with a comma.
2837
+ // A dial's own words in any case (ROOMY, MORE, Both, NONE): the word.
2838
+ if (!unset && typeof value === 'string')
2839
+ value = dialWordOf(thing, value) ?? value;
2840
+ if (!unset && typeof value === 'string') {
2841
+ const near =
2842
+ /^\s*light-dark\(\s*([^,;/()]+?)\s*(?:\s\/\s|\/|;)\s*([^,;/()]+?)\s*\)\s*$/i.exec(
2843
+ value,
2844
+ );
2845
+ if (near)
2846
+ refuse(
2847
+ E.ERR_THEME_BAD_VALUE,
2848
+ `"${value}" separates its two colors with something other than a comma; light-dark() takes "light-dark(light, dark)".`,
2849
+ {
2850
+ run: [
2851
+ setLine(
2852
+ slug,
2853
+ thing,
2854
+ `light-dark(${near[1]}, ${near[2]})`,
2855
+ {...flags, mode: undefined},
2856
+ false,
2857
+ ),
2858
+ ],
2859
+ },
2860
+ );
2861
+ }
2862
+ // One reader for a family list, on the font dial, a family token and a
2863
+ // part's font-family: a weight or a size in it, alone or after a
2864
+ // family, is no family, and a quoted generic is a family named that.
2865
+ const fontish =
2866
+ thing === 'font' ||
2867
+ thing === 'font-family' ||
2868
+ thing.startsWith('--font-family');
2869
+ const listProblem =
2870
+ !unset && typeof value === 'string' && fontish
2871
+ ? fontListProblem(value, ctx, thing === 'font')
2872
+ : null;
2873
+ if (listProblem) {
2874
+ const on = flags.on ? ` --on ${flags.on}` : '';
2875
+ refuse(
2876
+ E.ERR_THEME_BAD_VALUE,
2877
+ `"${String(value).trim()}" ${listProblem.why}. ${thing} takes the families${listProblem.families ? ` (${listProblem.families})` : ''}${listProblem.size ? '; a size is set with text-size or a --font-size-* token' : listProblem.rung ? '; a weight is set with headings, font-weight or a --font-weight-* token' : listProblem.style ? '; a style is set with font-style on a part' : ''}.`,
2878
+ {
2879
+ run: [
2880
+ ...(listProblem.families
2881
+ ? [
2882
+ `${P} set ${slug} ${thing} ${quoteCommandArgument(listProblem.families)}${on}`,
2883
+ ]
2884
+ : []),
2885
+ // The family as typed, kept as written by its quotes.
2886
+ ...(listProblem.asTyped
2887
+ ? [
2888
+ `${P} set ${slug} ${thing} ${quoteCommandArgument(listProblem.asTyped)}${on}`,
2889
+ ]
2890
+ : []),
2891
+ ...(thing === 'font' && listProblem.rung
2892
+ ? [`${P} set ${slug} headings ${listProblem.rung}`]
2893
+ : []),
2894
+ ...(thing === 'font' && listProblem.textSize != null
2895
+ ? [`${P} set ${slug} text-size ${listProblem.textSize}`]
2896
+ : []),
2897
+ ...(thing === 'font-family' && flags.on && listProblem.style
2898
+ ? [`${P} set ${slug} font-style ${listProblem.style}${on}`]
2899
+ : []),
2900
+ ...(listProblem.families
2901
+ ? []
2902
+ : [`${HOW} ${quoteCommandArgument(thing)}`]),
2903
+ ],
2904
+ },
2905
+ );
2906
+ }
2907
+ // A font list with a comma missing before its generic family, or a
2908
+ // generic written with a space, on the font dial or a part's
2909
+ // font-family: the list meant (a family token reads it with its type).
2910
+ if (
2911
+ !unset &&
2912
+ typeof value === 'string' &&
2913
+ (thing === 'font' || thing === 'font-family')
2914
+ ) {
2915
+ const fixed = fontListMeant(value);
2916
+ if (fixed)
2917
+ refuse(
2918
+ E.ERR_THEME_BAD_VALUE,
2919
+ `"${value}" names a family that exists nowhere: ${fixed.why}.`,
2920
+ {run: [setLine(slug, thing, fixed.value, flags, false)]},
2921
+ );
2922
+ // A font dial word that names no family (mono, system, rounded): a
2923
+ // part's font-family takes the stack it stands for, never the word.
2924
+ const word = value.trim().toLowerCase();
2925
+ const stack = thing === 'font-family' ? fontStack(word) : null;
2926
+ if (
2927
+ stack &&
2928
+ FONTS[word] &&
2929
+ FONTS[word][0].toLowerCase() !== word &&
2930
+ !isSystemFamily(word)
2931
+ )
2932
+ refuse(
2933
+ E.ERR_THEME_BAD_VALUE,
2934
+ `"${value.trim()}" is a font dial word, not a family: no font is named that. font-family takes the families it stands for (${stack}).`,
2935
+ {run: [setLine(slug, thing, stack, flags, false)]},
2936
+ );
2937
+ }
2938
+ // A light and a dark color on a part's color property (`background`,
2939
+ // `color`, `border-color` …) is that property's light-dark() pair.
2940
+ if (
2941
+ !unset &&
2942
+ typeof value === 'string' &&
2943
+ flags.on &&
2944
+ !flags.mode &&
2945
+ /^(color|background|(background|border|outline|text-decoration|caret|accent|fill|stroke)(-[a-z]+)?-color)$/.test(
2946
+ String(thing).trim().toLowerCase(),
2947
+ )
2948
+ ) {
2949
+ const pair = colorPair(value);
2950
+ if (pair && !colorProblem(pair.light) && !colorProblem(pair.dark)) {
2951
+ // A theme with one mode shows one half: that half is the line, as
2952
+ // for a color token.
2953
+ const only = oneModeOfTheme(data);
2954
+ if (only)
2955
+ refuse(
2956
+ E.ERR_THEME_BAD_VALUE,
2957
+ `"${value}" is a light and a dark color; this theme is ${only} only, so it shows the ${only} one.`,
2958
+ {
2959
+ run: [
2960
+ setLine(slug, thing, pair[only], {...flags, mode: undefined}),
2961
+ ],
2962
+ },
2963
+ );
2964
+ value = `light-dark(${pair.light}, ${pair.dark})`;
2965
+ }
2966
+ }
2967
+ if (
2968
+ !unset &&
2969
+ typeof value === 'string' &&
2970
+ (PALETTE_DIALS.includes(thing) || isColorToken(thing))
2971
+ ) {
2972
+ const pair = colorPair(value);
2973
+ if (pair && !colorProblem(pair.light) && !colorProblem(pair.dark)) {
2974
+ const q = quoteCommandArgument;
2975
+ const on = flags.on ? ` --on ${flags.on}` : '';
2976
+ // A theme with one mode shows one half: that half is the line.
2977
+ const only = oneModeOfTheme(data);
2978
+ if (only)
2979
+ refuse(
2980
+ E.ERR_THEME_BAD_VALUE,
2981
+ `"${value}" is a light and a dark color; this theme is ${only} only, so it shows the ${only} one.`,
2982
+ {run: [`${P} set ${slug} ${thing} ${q(pair[only])}${on}`]},
2983
+ );
2984
+ refuse(
2985
+ E.ERR_THEME_BAD_VALUE,
2986
+ PALETTE_DIALS.includes(thing)
2987
+ ? `"${value}" is a light and a dark color; ${thing} takes one color and makes both modes from it.`
2988
+ : `"${value}" is a light and a dark color; ${thing} takes them as light-dark(), or one --mode at a time.`,
2989
+ {
2990
+ run: PALETTE_DIALS.includes(thing)
2991
+ ? [
2992
+ `${P} set ${slug} ${thing} ${q(pair.light)}${on}`,
2993
+ ...(thing === 'accent'
2994
+ ? [
2995
+ `${P} set ${slug} --color-accent ${q(`light-dark(${pair.light}, ${pair.dark})`)}${on}`,
2996
+ ]
2997
+ : []),
2998
+ ]
2999
+ : [
3000
+ `${P} set ${slug} ${thing} ${q(`light-dark(${pair.light}, ${pair.dark})`)}${on}`,
3001
+ `${P} set ${slug} ${thing} ${q(pair.light)}${on} --mode light`,
3002
+ `${P} set ${slug} ${thing} ${q(pair.dark)}${on} --mode dark`,
3003
+ ],
3004
+ },
3005
+ );
3006
+ }
3007
+ }
3008
+ // A value labeled with a word that is not this setting's own name (a
3009
+ // mode, a state, a device, a part, or a word the editor does not read) is
3010
+ // refused with what that word means here, never set with the word dropped.
3011
+ // A property set on a part (`padding 'hover: 4px' --on button`) and the
3012
+ // type tokens (`--font-weight-bold 'dark: 700'`) are read the same way;
3013
+ // a content string is its own text.
3014
+ const partProperty =
3015
+ Boolean(flags.on) && !DIALS[thing] && !thing.startsWith('--');
3016
+ const familyToken = thing.startsWith('--font-family');
3017
+ if (
3018
+ !unset &&
3019
+ typeof value === 'string' &&
3020
+ !/content/.test(thing) &&
3021
+ (DIALS[thing] || partProperty || thing.startsWith('--'))
3022
+ ) {
3023
+ const label = valueLabel(value);
3024
+ // Another CSS property's name before the value (`padding 'margin:
3025
+ // 8px'`, `corners 'margin: 24px'`, `--spacing-2 'border-radius: 8px'`)
3026
+ // is that property's value, never this setting's: for every setting, a
3027
+ // pasted property is read only when the setting is what it sets.
3028
+ if (
3029
+ label &&
3030
+ label.word !== thing &&
3031
+ !labelOwned(ctx, thing, label.word, Boolean(partProperty)) &&
3032
+ cssProperties().has(label.word) &&
3033
+ label.rest.trim()
3034
+ )
3035
+ refuse(
3036
+ E.ERR_THEME_BAD_VALUE,
3037
+ `"${value}" is labeled ${label.word}, another property than ${thing}; nothing is set from it.`,
3038
+ {
3039
+ didYouMean: [label.word],
3040
+ run: [setLine(slug, label.word, label.rest.trim(), flags, false)],
3041
+ },
3042
+ );
3043
+ // A CSS property's name before the value (`border-radius: pill`,
3044
+ // `color: #e11d48`, `font: bold 16px Inter`) is read by the paths
3045
+ // below, as a declaration pasted from a stylesheet.
3046
+ if (
3047
+ label &&
3048
+ !ownLabel(thing, label.word) &&
3049
+ !cssProperties().has(label.word)
3050
+ ) {
3051
+ const q = quoteCommandArgument;
3052
+ const rest = label.rest;
3053
+ const scope = `${flags.on ? ` --on ${flags.on}` : ''}${flags.when ? ` --when ${flags.when}` : ''}`;
3054
+ // A variant named after the value: the value with --when.
3055
+ if ('when' in label && label.when)
3056
+ refuse(
3057
+ E.ERR_THEME_BAD_VALUE,
3058
+ `"${value}" names a variant after the value; a value for one variant is given with --on <part> --when ${label.when}.`,
3059
+ {
3060
+ didYouMean: ['--when'],
3061
+ run: [
3062
+ flags.on
3063
+ ? `${P} set ${slug} ${thing} ${q(rest)} --on ${flags.on} --when ${label.when}`
3064
+ : `${HOW} ${q(`${label.when.split(':').pop()} ${thing}`)}`,
3065
+ ],
3066
+ },
3067
+ );
3068
+ const mode = modeWord(label.word);
3069
+ const colorful =
3070
+ PALETTE_DIALS.includes(thing) ||
3071
+ (thing.startsWith('--') && isColorToken(thing)) ||
3072
+ (partProperty &&
3073
+ /color|^background$|^fill$|^stroke$|shadow/.test(thing));
3074
+ const parts = [...ctx.project.target.keys(), ...Object.keys(FAMILIES)];
3075
+ // A theme with one mode: its own mode's label is the value, as the
3076
+ // theme has no other; the other mode's label names a mode it lacks.
3077
+ const only = oneModeOfTheme(data);
3078
+ if (mode && only) {
3079
+ if (mode === only)
3080
+ return checkSetting(ctx, slug, data, thing, rest, flags, unset);
3081
+ refuse(
3082
+ E.ERR_THEME_BAD_VALUE,
3083
+ `"${label.word}" in "${value}" names the ${mode} mode, which this ${only}-only theme does not show.`,
3084
+ {
3085
+ run: [
3086
+ `${P} set ${slug} mode both`,
3087
+ `${P} set ${slug} ${thing} ${q(rest)}${scope}`,
3088
+ ],
3089
+ },
3090
+ );
3091
+ }
3092
+ if (mode && DIALS[thing] && PALETTE_DIALS.includes(thing))
3093
+ refuse(
3094
+ E.ERR_THEME_BAD_VALUE,
3095
+ `"${label.word}" in "${value}" names the ${mode} mode; ${thing} makes both modes from one color.`,
3096
+ {
3097
+ run: [
3098
+ `${P} set ${slug} ${thing} ${q(rest)}${scope}`,
3099
+ ...(thing === 'accent'
3100
+ ? [
3101
+ `${P} set ${slug} --color-accent ${q(rest)}${scope} --mode ${mode}`,
3102
+ ]
3103
+ : []),
3104
+ ],
3105
+ },
3106
+ );
3107
+ const level = /^h([1-6])$/.exec(label.word)?.[1];
3108
+ if (level && thing === 'headings') {
3109
+ const w = rest.trim().toLowerCase();
3110
+ refuse(
3111
+ E.ERR_THEME_BAD_VALUE,
3112
+ `"${label.word}" in "${value}" is one heading level; headings sets every level, and one level is set with --on heading --when level:${level}.`,
3113
+ {
3114
+ run:
3115
+ HEADING_WEIGHTS[w] !== undefined
3116
+ ? [
3117
+ `${P} set ${slug} font-weight ${HEADING_WEIGHTS[w]} --on heading --when level:${level}`,
3118
+ `${P} set ${slug} headings ${w}`,
3119
+ ]
3120
+ : HEADING_TRACKING[w] !== undefined
3121
+ ? [
3122
+ `${P} set ${slug} letter-spacing ${q(HEADING_TRACKING[w])} --on heading --when level:${level}`,
3123
+ `${P} set ${slug} headings ${w}`,
3124
+ ]
3125
+ : [`${HOW} headings`],
3126
+ },
3127
+ );
3128
+ }
3129
+ if (mode)
3130
+ refuse(
3131
+ E.ERR_THEME_BAD_VALUE,
3132
+ colorful
3133
+ ? `"${label.word}" in "${value}" names the ${mode} mode; a value for one mode is given with --mode ${mode}.`
3134
+ : `"${label.word}" in "${value}" names the ${mode} mode, and ${thing} is the same in light and dark.`,
3135
+ {
3136
+ run: [
3137
+ `${P} set ${slug} ${thing} ${q(rest)}${scope}${colorful ? ` --mode ${mode}` : ''}`,
3138
+ ],
3139
+ },
3140
+ );
3141
+ if (STATE_WORDS.includes(label.word))
3142
+ refuse(
3143
+ E.ERR_THEME_BAD_VALUE,
3144
+ flags.on
3145
+ ? `"${label.word}" in "${value}" is a state; a value for it is given with --state ${label.word}.`
3146
+ : `"${label.word}" in "${value}" is a state; a state is set on a part, with --on <part> --state ${label.word}.`,
3147
+ {
3148
+ run: [
3149
+ flags.on
3150
+ ? `${P} set ${slug} ${thing} ${q(rest)}${scope} --state ${label.word}`
3151
+ : `${HOW} ${q(`${label.word} ${thing}`)}`,
3152
+ ],
3153
+ },
3154
+ );
3155
+ if (DEVICE_WORDS.includes(label.word))
3156
+ refuse(
3157
+ E.ERR_THEME_BAD_VALUE,
3158
+ `"${label.word}" in "${value}" names a kind of screen; the editor sets ${thing} for every screen, not for one kind.`,
3159
+ {run: [`${P} set ${slug} ${thing} ${q(rest)}${scope}`]},
3160
+ );
3161
+ // `on button: pill`: the part named after `on`.
3162
+ const onPart = /^on-([a-z][a-z0-9-]*)$/.exec(label.word)?.[1];
3163
+ if (onPart && parts.includes(onPart))
3164
+ refuse(
3165
+ E.ERR_THEME_BAD_VALUE,
3166
+ `"${value}" names the part ${onPart}; a value for one part is given with --on ${onPart}.`,
3167
+ {run: [`${P} set ${slug} ${thing} ${q(rest)} --on ${onPart}`]},
3168
+ );
3169
+ if (parts.includes(label.word))
3170
+ refuse(
3171
+ E.ERR_THEME_BAD_VALUE,
3172
+ `"${label.word}" in "${value}" is a part; a value for one part is given with --on ${label.word}.`,
3173
+ {run: [`${P} set ${slug} ${thing} ${q(rest)} --on ${label.word}`]},
3174
+ );
3175
+ // A flag's own name as the label (`state: hover`, `part: card`,
3176
+ // `variant: primary`, `mode: dark`): what that flag does here.
3177
+ const flagWord = {
3178
+ state: 'state',
3179
+ states: 'state',
3180
+ part: 'on',
3181
+ on: 'on',
3182
+ component: 'on',
3183
+ variant: 'when',
3184
+ size: 'when',
3185
+ when: 'when',
3186
+ prop: 'when',
3187
+ mode: 'mode',
3188
+ theme: 'mode',
3189
+ }[label.word];
3190
+ if (
3191
+ flagWord &&
3192
+ (flagWord === 'mode'
3193
+ ? Boolean(modeWord(rest))
3194
+ : !otherSettingLabel(thing, value))
3195
+ ) {
3196
+ const r = rest.trim().toLowerCase();
3197
+ // The flag's value and the setting's value in one (`state=hover
3198
+ // 4px`): the first word is the flag's, the rest the value.
3199
+ const [fv, ...more] = rest.trim().split(/\s+/);
3200
+ if (flagWord !== 'mode' && more.length > 0) {
3201
+ const flagged =
3202
+ flagWord === 'on'
3203
+ ? ` --on ${fv}${flags.when ? ` --when ${flags.when}` : ''}`
3204
+ : flags.on
3205
+ ? `${scope} --${flagWord} ${flagWord === 'when' && label.word !== 'when' && label.word !== 'prop' ? `${label.word}:${fv}` : fv}`
3206
+ : null;
3207
+ refuse(
3208
+ E.ERR_THEME_BAD_VALUE,
3209
+ `"${value}" holds the ${flagWord} ${fv} and the value ${more.join(' ')}; the ${flagWord} is given with --${flagWord}.`,
3210
+ {
3211
+ didYouMean: [`--${flagWord}`],
3212
+ run: [
3213
+ flagged
3214
+ ? `${P} set ${slug} ${thing} ${q(more.join(' '))}${flagged}`
3215
+ : `${HOW} ${q(`${fv} ${thing}`)}`,
3216
+ ],
3217
+ },
3218
+ );
3219
+ }
3220
+ const m = flagWord === 'mode' ? modeWord(r) : null;
3221
+ const when =
3222
+ flagWord === 'when'
3223
+ ? label.word === 'when' || label.word === 'prop'
3224
+ ? r
3225
+ : `${label.word}:${r}`
3226
+ : null;
3227
+ refuse(
3228
+ E.ERR_THEME_BAD_VALUE,
3229
+ flagWord === 'mode'
3230
+ ? `"${value}" names ${m ? `the ${m} mode` : 'a mode'}, not a value for ${thing}: ${colorful ? `a value for one mode is given with --mode ${m ?? 'dark'}` : `a theme for one mode is set with \`set ${slug} mode ${m ?? 'dark'}-only\``}.`
3231
+ : flagWord === 'state'
3232
+ ? `"${value}" names a state, not a value for ${thing}: a value for a state is given with --on <part> --state ${r}.`
3233
+ : flagWord === 'on'
3234
+ ? `"${value}" names a part, not a value for ${thing}: a value for one part is given with --on ${r}.`
3235
+ : `"${value}" names a variant, not a value for ${thing}: a value for one variant is given with --on <part> --when ${when}.`,
3236
+ {
3237
+ didYouMean: [`--${flagWord}`],
3238
+ run: [
3239
+ flagWord === 'mode' && !colorful
3240
+ ? `${P} set ${slug} mode ${m ?? 'dark'}-only`
3241
+ : `${HOW} ${q(`${r} ${thing}`)}`,
3242
+ ],
3243
+ },
3244
+ );
3245
+ }
3246
+ // A Google Fonts family spec (`Inter:wght@400;600`): the family
3247
+ // before the colon.
3248
+ if (
3249
+ (thing === 'font' || familyToken || thing === 'font-family') &&
3250
+ /^(ital,)?wght@|^ital@/i.test(rest)
3251
+ ) {
3252
+ const family = String(value).split(':')[0].replace(/\+/g, ' ').trim();
3253
+ refuse(
3254
+ E.ERR_THEME_BAD_VALUE,
3255
+ `"${value}" is a Google Fonts family spec; ${thing} takes the family (${family}). A weight is set with font-weight or a --font-weight-* token.`,
3256
+ {run: [`${P} set ${slug} ${thing} ${q(family)}${scope}`]},
3257
+ );
3258
+ }
3259
+ // A family's own words may hold a colon; only the words above are
3260
+ // read there.
3261
+ if (!familyToken && !otherSettingLabel(thing, value))
3262
+ refuse(
3263
+ E.ERR_THEME_BAD_VALUE,
3264
+ `"${label.word}" in "${value}" is not a name the editor reads for ${thing}; give the value alone.`,
3265
+ {
3266
+ // Only setting names: a part or a state is never a value.
3267
+ didYouMean: nearest(label.word, Object.keys(DIALS)),
3268
+ // The words after an unknown label are no value the person
3269
+ // gave (a typo before the colon, or a family with a colon in
3270
+ // it): only a known name is ever taken off. What it takes.
3271
+ run: [`${HOW} ${thing}`],
3272
+ },
3273
+ );
3274
+ }
3275
+ // The setting's own name before its value (`font: Inter`, `Font:
3276
+ // Georgia`) is the value.
3277
+ // (A `font:` shorthand is read whole below, as its family.)
3278
+ if (
3279
+ label &&
3280
+ ownLabel(thing, label.word) &&
3281
+ // A `font:` with a size is the shorthand, read whole below; with
3282
+ // only families (`font: Inter, serif`) it is the label.
3283
+ (label.word !== 'font' || !/\d/.test(label.rest)) &&
3284
+ label.rest.replace(/;+\s*$/, '').trim()
3285
+ )
3286
+ value = label.rest;
3287
+ }
3288
+ if (
3289
+ !unset &&
3290
+ typeof value === 'string' &&
3291
+ (DIALS[thing] || partProperty || thing.startsWith('--')) &&
3292
+ !/content/.test(thing)
3293
+ ) {
3294
+ // A value labeled with another setting's name is that setting's, never
3295
+ // this one's (`accent 'neutral: #64748b'`, `--radius-element 'accent:
3296
+ // red'`). The value goes to this setting again only for a dial that
3297
+ // checks it as its own (any word is a font family, so never the font).
3298
+ const other = otherSettingLabel(thing, value);
3299
+ if (other)
3300
+ refuse(
3301
+ E.ERR_THEME_BAD_VALUE,
3302
+ `"${value}" is labeled ${other.thing}, another setting than ${thing}; nothing is set from it.`,
3303
+ {
3304
+ didYouMean: [other.thing],
3305
+ run: [
3306
+ `${P} set ${slug} ${other.thing} ${quoteCommandArgument(other.value)}${flags.on ? ` --on ${flags.on}` : ''}`,
3307
+ // Another setting is not this part's property: the whole theme.
3308
+ ...(flags.on && partProperty
3309
+ ? [
3310
+ `${P} set ${slug} ${other.thing} ${quoteCommandArgument(other.value)}`,
3311
+ ]
3312
+ : []),
3313
+ ...(DIALS[thing] && thing !== 'font'
3314
+ ? [
3315
+ `${P} set ${slug} ${thing} ${quoteCommandArgument(other.value)}${flags.on ? ` --on ${flags.on}` : ''}`,
3316
+ ]
3317
+ : []),
3318
+ ],
3319
+ },
3320
+ );
3321
+ }
3322
+ if (!unset && typeof value === 'string' && DIALS[thing]) {
3323
+ const d = thing === 'font' ? null : pastedDeclaration(value);
3324
+ if (d?.value) value = d.value;
3325
+ }
3326
+ // The font dial's value as pasted from a stylesheet (`Georgia, serif;`,
3327
+ // a comment, `!important`): a refusal suggests the font it names, when
3328
+ // set takes that.
3329
+ // A font pasted with its property name is the family list it names.
3330
+ if (
3331
+ !unset &&
3332
+ typeof value === 'string' &&
1426
3333
  (thing === 'font' ||
1427
3334
  (thing.startsWith('--') && ctx.C.typeOf(thing) === 'font'))
1428
3335
  ) {
@@ -1465,13 +3372,43 @@ export function checkSetting(
1465
3372
  throw e;
1466
3373
  }
1467
3374
  }
1468
- const s = checkSettingAsTyped(ctx, slug, data, thing, value, flags, unset);
3375
+ const s = checkSettingAsTyped(
3376
+ ctx,
3377
+ slug,
3378
+ data,
3379
+ thing,
3380
+ value,
3381
+ flags,
3382
+ unset,
3383
+ reads,
3384
+ );
1469
3385
  // A var() with a fallback always gives a value; a name one slip from a
1470
3386
  // design token is noted as a likely typo, and the setting stands.
1471
3387
  if (!unset && typeof value === 'string' && !s.note) {
1472
3388
  const typo = fallbackVarTypo(value, ctx.project.core.tokenDefaults ?? {});
1473
3389
  if (typo) s.note = typo;
1474
3390
  }
3391
+ // A family kept as typed that is near a font a system ships: noted, as
3392
+ // the family may be a real one the editor does not know.
3393
+ if (
3394
+ !unset &&
3395
+ typeof value === 'string' &&
3396
+ !s.note &&
3397
+ (thing === 'font' ||
3398
+ thing === 'font-family' ||
3399
+ thing.startsWith('--font-family'))
3400
+ ) {
3401
+ /** @type {Array<{name: string, near: string}>} */
3402
+ const near = [];
3403
+ fontListProblem(value, ctx, thing === 'font', near);
3404
+ if (near.length)
3405
+ s.note = near
3406
+ .map(
3407
+ n =>
3408
+ `"${n.name}" is kept as typed: the editor does not know that family, and a font a system ships is spelled near it; if that was meant: ${P} set ${slug} ${thing} ${quoteCommandArgument(String(value).replace(n.name, n.near))}${flags.on ? ` --on ${flags.on}` : ''}`,
3409
+ )
3410
+ .join('; ');
3411
+ }
1475
3412
  return s;
1476
3413
  }
1477
3414
 
@@ -1485,8 +3422,8 @@ export function checkSetting(
1485
3422
  function fallbackVarTypo(v, TOKENS) {
1486
3423
  for (const [, name] of v.matchAll(/var\(\s*(--[a-z0-9-]+)\s*,/gi)) {
1487
3424
  if (name in TOKENS || name.startsWith('--_')) continue;
1488
- const near = nearest(name, Object.keys(TOKENS)).filter(
1489
- n => levenshteinDistance(n, name) <= 2,
3425
+ const near = nearest(name, Object.keys(TOKENS)).filter(n =>
3426
+ typoNear(name, n),
1490
3427
  );
1491
3428
  if (near.length)
1492
3429
  return `${name} is not a design token, so its fallback always shows; did you mean ${near[0]}?`;
@@ -1503,6 +3440,7 @@ function fallbackVarTypo(v, TOKENS) {
1503
3440
  * @param {string | undefined} value
1504
3441
  * @param {SetFlags} flags
1505
3442
  * @param {boolean} [unset]
3443
+ * @param {ReadonlySet<string>} [reads] custom properties the theme sets where the value is read
1506
3444
  * @returns {import('./_settings.mjs').Setting}
1507
3445
  */
1508
3446
  function checkSettingAsTyped(
@@ -1513,8 +3451,9 @@ function checkSettingAsTyped(
1513
3451
  value,
1514
3452
  flags,
1515
3453
  unset = false,
3454
+ reads = undefined,
1516
3455
  ) {
1517
- const s = checkOne(ctx, slug, data, thing, value, flags, unset);
3456
+ const s = checkOne(ctx, slug, data, thing, value, flags, unset, reads);
1518
3457
  const why = unset ? null : valueProblem(s);
1519
3458
  if (why)
1520
3459
  refuse(
@@ -1542,9 +3481,10 @@ function checkSettingAsTyped(
1542
3481
  * @param {string | undefined} value
1543
3482
  * @param {SetFlags} flags
1544
3483
  * @param {boolean} unset
3484
+ * @param {ReadonlySet<string>} [reads] custom properties the theme sets where the value is read
1545
3485
  * @returns {import('./_settings.mjs').Setting}
1546
3486
  */
1547
- function checkOne(ctx, slug, data, thing, value, flags, unset) {
3487
+ function checkOne(ctx, slug, data, thing, value, flags, unset, reads) {
1548
3488
  const {C} = ctx;
1549
3489
  const TARGET = ctx.project.target;
1550
3490
  const TOKENS = ctx.project.core.tokenDefaults;
@@ -1580,7 +3520,7 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1580
3520
  const v = normalValue(thing, value ?? '');
1581
3521
  // A var() that misspells a design token would read nothing.
1582
3522
  if (!unset) {
1583
- const bad = unknownVarRef(v, TOKENS, thing);
3523
+ const bad = unknownVarRef(v, TOKENS, thing, reads);
1584
3524
  if (bad)
1585
3525
  refuse(E.ERR_THEME_UNKNOWN_TOKEN, bad.message, {
1586
3526
  didYouMean: bad.near,
@@ -1619,32 +3559,92 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1619
3559
  if (flags.when) s.when = flags.when.trim();
1620
3560
  // A state in any case or spelling of its words (focusVisible,
1621
3561
  // focus_visible, 'focus visible') is the state, written as CSS writes it.
1622
- if (flags.state)
1623
- s.state = flags.state
1624
- .trim()
1625
- .replace(/^:+/, '')
1626
- .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
1627
- .replace(/[\s_]+/g, '-')
1628
- .toLowerCase();
3562
+ if (flags.state) s.state = stateSpelling(flags.state);
1629
3563
  if (flags.only) s.only = true;
1630
3564
  if (flags.mode) {
1631
- const mode = flags.mode.toLowerCase();
1632
- if (mode !== 'light' && mode !== 'dark')
3565
+ // Read as any value is: invisible or no-break spaces, quotes around
3566
+ // it, a trailing colon (`'dark '`, `“dark”`, `dark:`).
3567
+ const mode = withoutDebris(normalValueText(String(flags.mode)))
3568
+ .trim()
3569
+ .replace(/^(["'])(.*)\1$/, '$2')
3570
+ .replace(/:+$/, '')
3571
+ .trim()
3572
+ .toLowerCase();
3573
+ if (mode !== 'light' && mode !== 'dark') {
3574
+ // A word that names one of the two (dark-only, darkmode, night) is
3575
+ // that one, by the one mode reader; never the nearest spelling, which
3576
+ // can be the other (night → light).
3577
+ const meant = modeWord(mode);
3578
+ const near = meant ? [meant] : nearest(mode, ['light', 'dark']);
3579
+ // The line for that one mode: for a dial, the one `--mode dark` itself
3580
+ // offers (the color token for that mode), never the both-modes dial.
3581
+ const modeLine = (/** @type {string} */ m) => {
3582
+ if (DIALS[thing] && !unset)
3583
+ try {
3584
+ checkSetting(ctx, slug, data, thing, v, {...flags, mode: m});
3585
+ } catch (e) {
3586
+ const first = /** @type {any} */ (e)?.suggestions?.find(
3587
+ (/** @type {any} */ x) => / --mode (light|dark)\b/.test(x.name),
3588
+ );
3589
+ if (first) return first.name;
3590
+ }
3591
+ return setLine(slug, thing, v, {...s, mode: m}, unset);
3592
+ };
1633
3593
  refuse(
1634
3594
  E.ERR_THEME_BAD_VALUE,
1635
3595
  `--mode takes light or dark, not "${flags.mode}".`,
1636
3596
  {
1637
- didYouMean: nearest(mode, ['light', 'dark']),
1638
- // The same setting for both modes runs as printed; the mode it
1639
- // probably meant is the did-you-mean.
1640
- run: [setLine(slug, thing, v, {...s, mode: undefined}, unset)],
3597
+ didYouMean: near,
3598
+ // The mode it is nearest keeps --mode; only with none near is the
3599
+ // same setting for both modes offered.
3600
+ run: [
3601
+ ...(near.length === 1 ? [modeLine(near[0])] : []),
3602
+ // A word that means one mode (night) keeps it: the both-modes
3603
+ // line only for a word read by spelling.
3604
+ ...(meant
3605
+ ? []
3606
+ : [setLine(slug, thing, v, {...s, mode: undefined}, unset)]),
3607
+ ],
1641
3608
  },
1642
3609
  );
3610
+ }
1643
3611
  s.mode = mode;
1644
3612
  }
1645
3613
  const onFlag = s.on ? ` --on ${s.on}` : '';
1646
- // A value that already gives both modes takes no --mode.
1647
- if (s.mode && !unset && /^\s*light-dark\(/i.test(v ?? ''))
3614
+ // A CSS-wide keyword is no color for one mode: a mode's half takes a
3615
+ // color, and the keyword applies to the whole declaration, in both modes.
3616
+ if (
3617
+ s.mode &&
3618
+ !unset &&
3619
+ CSS_WIDE.includes(
3620
+ String(v ?? '')
3621
+ .trim()
3622
+ .toLowerCase(),
3623
+ )
3624
+ )
3625
+ // A token takes no keyword in any mode (it would be left empty), so for
3626
+ // a token only the color is offered.
3627
+ refuse(
3628
+ E.ERR_THEME_NO_MODE,
3629
+ String(thing).startsWith('--')
3630
+ ? `"${String(v).trim()}" is a CSS keyword, which applies in both modes, so it takes no --mode; and a token never takes one. Give the ${s.mode} color.`
3631
+ : `"${String(v).trim()}" is a CSS keyword, which applies in both modes, so it takes no --mode. Give the ${s.mode} color, or set ${thing} ${String(v).trim()} for both modes.`,
3632
+ {
3633
+ run: [
3634
+ String(thing).startsWith('--')
3635
+ ? `${HOW} ${thing}`
3636
+ : `${P} set ${slug} ${thing} ${String(v).trim()}${onFlag}${s.when ? ` --when ${s.when}` : ''}${s.state ? ` --state ${s.state}` : ''}`,
3637
+ ],
3638
+ },
3639
+ );
3640
+ // A value that already gives both modes takes no --mode (a gradient
3641
+ // holding a light-dark() stop included).
3642
+ if (
3643
+ s.mode &&
3644
+ !unset &&
3645
+ (/^\s*light-dark\(/i.test(v ?? '') ||
3646
+ (/gradient\(/i.test(v ?? '') && /light-dark\(/i.test(v ?? '')))
3647
+ )
1648
3648
  refuse(
1649
3649
  E.ERR_THEME_NO_MODE,
1650
3650
  `"${v}" already gives both modes, so it takes no --mode; drop --mode, or give the ${s.mode} color alone.`,
@@ -1655,17 +3655,59 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1655
3655
  },
1656
3656
  );
1657
3657
  // A setting saved for a mode the theme no longer has can still be removed.
1658
- if (s.mode && data.mode !== 'both' && !unset)
3658
+ // An entry saved for the one mode the theme has ("[dark only]" in a
3659
+ // dark-only theme) can be set again with that --mode, so a doubled one
3660
+ // can be kept: that set replaces both.
3661
+ const sameModeEntry =
3662
+ s.mode &&
3663
+ data.mode === `${s.mode}-only` &&
3664
+ (Array.isArray(data.settings) ? data.settings : []).some(
3665
+ (/** @type {any} */ x) =>
3666
+ x &&
3667
+ x.thing === thing &&
3668
+ x.mode === s.mode &&
3669
+ (x.on ?? null) === (s.on ?? null) &&
3670
+ (x.when ?? null) === (s.when ?? null) &&
3671
+ (x.state ?? null) === (s.state ?? null),
3672
+ );
3673
+ // A one-mode theme still has the other mode where Core draws it (a toast,
3674
+ // a lightbox): a value for that mode is written for those regions.
3675
+ const otherModeOfOneMode =
3676
+ s.mode != null &&
3677
+ oneModeOfTheme(data) != null &&
3678
+ oneModeOfTheme(data) !== s.mode;
3679
+ if (
3680
+ s.mode &&
3681
+ data.mode !== 'both' &&
3682
+ !unset &&
3683
+ !sameModeEntry &&
3684
+ !otherModeOfOneMode
3685
+ ) {
3686
+ // What takes no --mode in any theme (a size, a font, a keyword) is
3687
+ // refused for that, with the command that drops --mode: a theme with
3688
+ // both modes would refuse it too, so its mode is no way out.
3689
+ try {
3690
+ checkSetting(ctx, slug, {...data, mode: 'both'}, thing, v, flags);
3691
+ } catch (e) {
3692
+ if (/** @type {any} */ (e)?.code === E.ERR_THEME_NO_MODE) throw e;
3693
+ }
1659
3694
  refuse(
1660
3695
  E.ERR_THEME_NO_MODE,
1661
- `This theme is ${data.mode}; --mode is for themes with both modes.`,
1662
- {run: [`${P} set ${slug} ${thing} ${quoteCommandArgument(v)}${onFlag}`]},
3696
+ `This theme is ${data.mode}, so its own mode needs no --mode.`,
3697
+ {
3698
+ run: [
3699
+ `${P} set ${slug} ${thing} ${quoteCommandArgument(v)}${onFlag}${s.when ? ` --when ${s.when}` : ''}${s.state ? ` --state ${s.state}` : ''}`,
3700
+ ],
3701
+ },
1663
3702
  );
3703
+ }
1664
3704
  if ((s.when || s.state) && !s.on)
1665
3705
  refuse(E.ERR_MISSING_ARGUMENT, '--when and --state need --on <part>.', {
1666
3706
  run: [`${HOW} --list parts`],
1667
3707
  });
1668
- if (s.only) {
3708
+ // --only is checked on a part this Core has; a part in other letters or
3709
+ // misspelt gets the part's own refusal first, with --only kept.
3710
+ if (s.only && (!s.on || TARGET.has(s.on) || FAMILIES[s.on])) {
1669
3711
  const fam = s.on ? familyOf(s.on) : null;
1670
3712
  if (!fam || FAMILIES[/** @type {string} */ (s.on)])
1671
3713
  refuse(
@@ -1693,29 +3735,120 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1693
3735
  // Another case of a part or group, its class name copied from the
1694
3736
  // page (`.astryx-card`), or its component (`<Card>`, `Card`): that
1695
3737
  // part, as a working command with every flag kept.
3738
+ // Stray punctuation from a copied list ("text-input,") and the dashes
3739
+ // autocorrect types ("text\u2013input") are not part of the name.
1696
3740
  const lower = s.on
3741
+ .replace(/[\u2010-\u2015\u2212]/g, '-')
3742
+ .replace(/^[\s,;:.'"`]+|[\s,;:.'"`]+$/g, '')
1697
3743
  .trim()
1698
3744
  .replace(/^<\/?\s*|\s*\/?>$/g, '')
1699
3745
  .replace(/^\./, '')
1700
3746
  .replace(/^astryx-/, '')
1701
3747
  .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
1702
3748
  .toLowerCase();
1703
- // A plain word how reads as a part or group (checkboxes: checks).
1704
- const byWord = partForWord(lower);
3749
+ // A part named in words (dialog header, text inputs) is the dashed
3750
+ // part, read before any group a single word of it names.
3751
+ const dashed = lower.trim().replace(/[\s_]+/g, '-');
3752
+ // A plain word how reads as a part or group (checkboxes: checks):
3753
+ // only the whole value as one word, never one word inside a longer
3754
+ // name (nmber-input is no word for inputs).
3755
+ const byWord = /^[a-z]+$/.test(lower) ? partForWord(lower) : null;
3756
+ // A typo of a whole part or group name, or of a word how reads as
3757
+ // one (sidebar, checkbox, toggle), is the part the nearest of them
3758
+ // names, when the nearest name one part.
3759
+ const typoParts = (() => {
3760
+ const words = partWords();
3761
+ const candidates = [
3762
+ ...TARGET.keys(),
3763
+ ...Object.keys(FAMILIES),
3764
+ ...[...words]
3765
+ .filter(([, on]) => TARGET.has(on) || FAMILIES[on])
3766
+ .map(([w]) => w),
3767
+ ].filter(n => n !== lower && n !== dashed);
3768
+ // The one typo ranker (closestOf). A hit that is a part or group
3769
+ // name is that name (`tabel` is table); a word that is no name is
3770
+ // read as its part (`sidebr` is side-nav).
3771
+ const isName = (/** @type {string} */ n) =>
3772
+ TARGET.has(n) || Boolean(FAMILIES[n]);
3773
+ return [
3774
+ ...new Set(
3775
+ closestOf(dashed, candidates).map(n =>
3776
+ isName(n) ? n : (words.get(n) ?? n),
3777
+ ),
3778
+ ),
3779
+ ];
3780
+ })();
1705
3781
  // A plain plural of a part (cards, dialogs, tabs) is that part.
1706
- const singular = [
1707
- lower.replace(/ies$/, 'y'),
1708
- lower.replace(/(ch|sh|x|s)es$/, '$1'),
1709
- lower.replace(/s$/, ''),
1710
- ].find(x => x !== lower && (TARGET.has(x) || FAMILIES[x]));
3782
+ const singular = [lower, dashed]
3783
+ .flatMap(w => [
3784
+ w.replace(/ies$/, 'y'),
3785
+ w.replace(/(ch|sh|x|s)es$/, '$1'),
3786
+ w.replace(/s$/, ''),
3787
+ ])
3788
+ .find(x => x !== lower && (TARGET.has(x) || FAMILIES[x]));
3789
+ // Several parts named in one --on (`button, text-input`, `button/
3790
+ // text-input`, `button and text-input`, or spaces): one command per
3791
+ // part named, each checked, never a group that one word of the list
3792
+ // happens to name.
3793
+ const listed = /,|\/|&|\band\b/.test(lower);
3794
+ // (Words with only spaces that name one part, `text inputs`, are
3795
+ // that part.)
3796
+ if (!(TARGET.has(dashed) || FAMILIES[dashed]) && (listed || !singular)) {
3797
+ const pieces = lower
3798
+ .split(/\s*(?:,|\/|&|\band\b)\s*|\s+/)
3799
+ .map(x => x.trim())
3800
+ .filter(Boolean);
3801
+ const partOf = (/** @type {string} */ w) =>
3802
+ TARGET.has(w) || FAMILIES[w]
3803
+ ? w
3804
+ : ([w.replace(/ies$/, 'y'), w.replace(/s$/, '')].find(
3805
+ x => x !== w && (TARGET.has(x) || FAMILIES[x]),
3806
+ ) ?? null);
3807
+ const found = pieces.map(partOf);
3808
+ const parts = [...new Set(found.filter(x => x != null))];
3809
+ const missing = pieces.filter((_, i) => found[i] == null);
3810
+ if (
3811
+ pieces.length > 1 &&
3812
+ parts.length > 0 &&
3813
+ (missing.length === 0 || (listed && parts.length > 1))
3814
+ )
3815
+ refuse(
3816
+ E.ERR_THEME_UNKNOWN_PART,
3817
+ `"${s.on}" names ${pieces.length} parts; --on takes one part at a time${missing.length ? ` (${missing.map(x => `"${x}"`).join(', ')} is not a part you can style)` : ''}.`,
3818
+ {
3819
+ didYouMean: parts,
3820
+ run: parts
3821
+ .slice(0, 6)
3822
+ .map(on => setLine(slug, thing, v, {...s, on}, unset)),
3823
+ },
3824
+ );
3825
+ }
1711
3826
  const named =
1712
3827
  TARGET.has(lower) || FAMILIES[lower]
1713
3828
  ? lower
1714
- : singular
1715
- ? singular
1716
- : byWord && (TARGET.has(byWord) || FAMILIES[byWord])
1717
- ? byWord
1718
- : null;
3829
+ : TARGET.has(dashed) || FAMILIES[dashed]
3830
+ ? dashed
3831
+ : singular
3832
+ ? singular
3833
+ : typoParts.length === 1
3834
+ ? typoParts[0]
3835
+ : byWord && (TARGET.has(byWord) || FAMILIES[byWord])
3836
+ ? byWord
3837
+ : null;
3838
+ // The page (the body behind every part) is painted by the app shell.
3839
+ if (
3840
+ !named &&
3841
+ /^(page|body|app|background|page-background)$/i.test(s.on) &&
3842
+ TARGET.has('app-shell')
3843
+ )
3844
+ refuse(
3845
+ E.ERR_THEME_UNKNOWN_PART,
3846
+ `"${s.on}" is not a part name; the page behind your parts is app-shell (a background there shows in every AppShell variant).`,
3847
+ {
3848
+ didYouMean: ['app-shell'],
3849
+ run: [setLine(slug, thing, v, {...s, on: 'app-shell'}, unset)],
3850
+ },
3851
+ );
1719
3852
  if (named)
1720
3853
  refuse(
1721
3854
  E.ERR_THEME_UNKNOWN_PART,
@@ -1725,16 +3858,22 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1725
3858
  run: [setLine(slug, thing, v, {...s, on: named}, unset)],
1726
3859
  },
1727
3860
  );
3861
+ // A plural or another case names the part it means; a typo of one
3862
+ // part leads with the same command on that part.
3863
+ const near = nearest(s.on.toLowerCase().replace(/s$/, ''), [
3864
+ ...TARGET.keys(),
3865
+ ...Object.keys(FAMILIES),
3866
+ ]);
3867
+ const typo = near.filter(n => typoOf(lower, n));
1728
3868
  refuse(
1729
3869
  E.ERR_THEME_UNKNOWN_PART,
1730
3870
  `"${s.on}" is not a part you can style.`,
1731
3871
  {
1732
- // A plural or another case names the part it means.
1733
- didYouMean: nearest(s.on.toLowerCase().replace(/s$/, ''), [
1734
- ...TARGET.keys(),
1735
- ...Object.keys(FAMILIES),
1736
- ]),
3872
+ didYouMean: near,
1737
3873
  run: [
3874
+ ...(typo.length === 1
3875
+ ? [setLine(slug, thing, v, {...s, on: typo[0]}, unset)]
3876
+ : []),
1738
3877
  `${HOW} --list parts ${quoteCommandArgument(lower.replace(/s$/, '').split('-')[0] || 'button')}`,
1739
3878
  `${HOW} ${quoteCommandArgument(s.on)}`,
1740
3879
  ],
@@ -1742,6 +3881,26 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1742
3881
  );
1743
3882
  }
1744
3883
  if (s.when) {
3884
+ // A prop and value in other letters, with spaces or `=` between
3885
+ // (`Variant: Primary`, `variant=primary`): the working command.
3886
+ const m = /^\s*([^:=\s]+)\s*[:=]\s*([^:=]+?)\s*$/.exec(s.when);
3887
+ if (m) {
3888
+ const prop = t.props.find(x => x.toLowerCase() === m[1].toLowerCase());
3889
+ const vals = prop ? (C.variantValues(s.on)[prop] ?? []) : [];
3890
+ const val = vals.length
3891
+ ? vals.find(x => x.toLowerCase() === m[2].toLowerCase())
3892
+ : m[2];
3893
+ const when = prop && val ? `${prop}:${val}` : null;
3894
+ if (when && when !== s.when)
3895
+ refuse(
3896
+ E.ERR_THEME_UNKNOWN_VARIANT,
3897
+ `--when "${s.when}" is written ${when}.`,
3898
+ {
3899
+ didYouMean: [when],
3900
+ run: [setLine(slug, thing, v, {...s, when}, unset)],
3901
+ },
3902
+ );
3903
+ }
1745
3904
  const [p, wv, ...more] = s.when.split(':');
1746
3905
  if (!wv || more.length)
1747
3906
  refuse(
@@ -1749,7 +3908,8 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1749
3908
  '--when takes <prop>:<value>, such as variant:primary.',
1750
3909
  {run: [`${HOW} ${s.on}`]},
1751
3910
  );
1752
- if (!t.props.includes(p))
3911
+ const conditions = Object.keys(C.variantValues(s.on));
3912
+ if (!t.props.includes(p) && !conditions.includes(p))
1753
3913
  refuse(
1754
3914
  E.ERR_THEME_UNKNOWN_VARIANT,
1755
3915
  `${s.on} has no prop "${p}". It has: ${t.props.join(', ') || 'none'}.`,
@@ -1764,12 +3924,21 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1764
3924
  );
1765
3925
  }
1766
3926
  const states = [...t.states, ...COMMON_STATES];
3927
+ // A state the part lists in camelCase (toggle-button's isPressed) typed
3928
+ // in any case or with dashes is that state.
3929
+ const flat = (/** @type {string} */ x) =>
3930
+ x.replace(/[-_\s]/g, '').toLowerCase();
3931
+ if (s.state && !states.includes(s.state)) {
3932
+ const same = states.find(x => flat(x) === flat(String(s.state)));
3933
+ if (same) s.state = same;
3934
+ }
1767
3935
  // Other words for a state, mapped to the one the part has; with none
1768
3936
  // near, the list of its states (never a guess such as hover).
1769
3937
  const SYNONYMS = wordTable(
1770
3938
  /** @type {Record<string, string[]>} */ ({
1771
- pressed: ['active'],
1772
- press: ['active'],
3939
+ pressed: ['isPressed', 'active'],
3940
+ press: ['isPressed', 'active'],
3941
+ on: ['isPressed', 'checked', 'selected'],
1773
3942
  down: ['active'],
1774
3943
  clicked: ['active'],
1775
3944
  hovered: ['hover'],
@@ -1781,6 +3950,27 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1781
3950
  inactive: ['disabled'],
1782
3951
  }),
1783
3952
  );
3953
+ // Several states in one --state (`hover,focus-visible`, `hover
3954
+ // focus-visible`): one line per state, the value quoted as typed.
3955
+ const typedStates = String(flags.state ?? '')
3956
+ .split(/\s*(?:,|\/|&|\band\b)\s*|\s+/)
3957
+ .map(x => x.trim().toLowerCase())
3958
+ .filter(Boolean);
3959
+ if (
3960
+ typedStates.length > 1 &&
3961
+ typedStates.every(x => states.includes(x)) &&
3962
+ !states.includes(String(s.state))
3963
+ )
3964
+ refuse(
3965
+ E.ERR_THEME_UNKNOWN_STATE,
3966
+ `"${flags.state}" names ${typedStates.length} states; --state takes one at a time.`,
3967
+ {
3968
+ didYouMean: typedStates,
3969
+ run: typedStates
3970
+ .slice(0, 6)
3971
+ .map(state => setLine(slug, thing, v, {...s, state}, unset)),
3972
+ },
3973
+ );
1784
3974
  const meant =
1785
3975
  (SYNONYMS[String(s.state ?? '').toLowerCase()] ?? []).find(x =>
1786
3976
  states.includes(x),
@@ -1788,7 +3978,7 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1788
3978
  if (s.state && !states.includes(s.state))
1789
3979
  refuse(
1790
3980
  E.ERR_THEME_UNKNOWN_STATE,
1791
- `"${s.state}" is not a state of ${s.on}. States: ${states.join(', ')}.`,
3981
+ `"${s.state}" is not a state of ${s.on}. States: ${settableStates(ctx, slug, data, s.on).join(', ') || 'none'}.`,
1792
3982
  {
1793
3983
  ...(meant ? {didYouMean: [meant]} : {}),
1794
3984
  run: [
@@ -1901,6 +4091,13 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1901
4091
  if (parts.length && dead.length === parts.length) {
1902
4092
  const bare = Object.keys(own(dead[0])).length === 0;
1903
4093
  const within = keys(dead[0], 'focus-within');
4094
+ // A ring Core draws inline on the part at focus time (an indicator's)
4095
+ // is changed by its token, with no state.
4096
+ const inlineAlways = ctx.C.MAP[dead[0]]?.inline?.[''] ?? {};
4097
+ const ringToken = /^focus/.test(s.state)
4098
+ ? (inlineAlways[kebab(thing)] ??
4099
+ (Object.values(inlineAlways).includes(thing) ? thing : null))
4100
+ : null;
1904
4101
  refuse(
1905
4102
  E.ERR_THEME_NO_EFFECT,
1906
4103
  bare
@@ -1916,12 +4113,21 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1916
4113
  ...(within && !bare && /^focus/.test(s.state)
1917
4114
  ? {didYouMean: ['focus-within']}
1918
4115
  : {}),
4116
+ ...(ringToken
4117
+ ? {
4118
+ also: [
4119
+ `Core draws ${dead[0]}'s focus ring at focus time from ${ringToken}, set on the part with no state`,
4120
+ ],
4121
+ }
4122
+ : {}),
1919
4123
  run: [
1920
- within && !bare && /^focus/.test(s.state)
1921
- ? setLine(slug, thing, v, {...s, state: 'focus-within'}, unset)
1922
- : bare
1923
- ? `${HOW} --list parts ${s.on.split('-')[0]}`
1924
- : `${HOW} ${quoteCommandArgument(s.on)}`,
4124
+ ringToken
4125
+ ? `${P} set ${slug} ${ringToken} ${quoteCommandArgument(v)} --on ${s.on}${s.mode ? ` --mode ${s.mode}` : ''}`
4126
+ : within && !bare && /^focus/.test(s.state)
4127
+ ? setLine(slug, thing, v, {...s, state: 'focus-within'}, unset)
4128
+ : bare
4129
+ ? `${HOW} --list parts ${s.on.split('-')[0]}`
4130
+ : `${HOW} ${quoteCommandArgument(s.on)}`,
1925
4131
  ],
1926
4132
  },
1927
4133
  );
@@ -1973,7 +4179,12 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
1973
4179
  if (s.when) {
1974
4180
  const [p, wv, ...more] = s.when.split(':');
1975
4181
  const fits = members.some(([m, t]) => {
1976
- if (!wv || more.length || !t.props.includes(p)) return false;
4182
+ if (
4183
+ !wv ||
4184
+ more.length ||
4185
+ !(t.props.includes(p) || p in C.variantValues(m))
4186
+ )
4187
+ return false;
1977
4188
  const vals = C.variantValues(m)[p] ?? [];
1978
4189
  return !vals.length || vals.includes(wv);
1979
4190
  });
@@ -2057,7 +4268,7 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2057
4268
  ? [lower]
2058
4269
  : meant
2059
4270
  ? [meant]
2060
- : nearest(lower, ok);
4271
+ : closestOf(lower, ok);
2061
4272
  refuse(
2062
4273
  E.ERR_THEME_BAD_VALUE,
2063
4274
  `${thing} takes ${DIALS[thing].values}, not "${v}".`,
@@ -2073,7 +4284,8 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2073
4284
  `${P} set ${slug} text-size ${['small', 'medium', 'large', 'larger'].includes(lower) ? lower : textSizePx(lower)}`,
2074
4285
  ]
2075
4286
  : near[0]
2076
- ? [`${P} set ${slug} ${thing} ${near[0]}`]
4287
+ ? // Each reading of a typo equally near two values.
4288
+ near.map(x => `${P} set ${slug} ${thing} ${x}`)
2077
4289
  : // A type-scale ratio (1.25) is the nearest type preset.
2078
4290
  thing === 'type' && ratioPreset(lower)
2079
4291
  ? [`${P} set ${slug} type ${ratioPreset(lower)}`]
@@ -2131,6 +4343,49 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2131
4343
  })(),
2132
4344
  },
2133
4345
  );
4346
+ // A comparative weight word is the weight (lighter is light, never the
4347
+ // tracking tighter); two words (`bold tight`, `bold, tight`) are a
4348
+ // weight and a tracking, one line each.
4349
+ if (!unset) {
4350
+ const MORE = /** @type {Record<string, string>} */ ({
4351
+ lighter: 'light',
4352
+ thinner: 'light',
4353
+ bolder: 'bold',
4354
+ heavier: 'heavy',
4355
+ wider: 'wide',
4356
+ looser: 'wide',
4357
+ });
4358
+ const words = String(v ?? '')
4359
+ .trim()
4360
+ .toLowerCase()
4361
+ .split(/[\s,]+/)
4362
+ .filter(w => w && w !== 'and' && w !== '&')
4363
+ .map(w => MORE[w] ?? w);
4364
+ const known = (/** @type {string} */ w) =>
4365
+ HEADING_WEIGHTS[w] !== undefined || HEADING_TRACKING[w] !== undefined;
4366
+ if (
4367
+ (words.length > 1 || MORE[String(v).trim().toLowerCase()]) &&
4368
+ words.every(known)
4369
+ )
4370
+ refuse(
4371
+ E.ERR_THEME_BAD_VALUE,
4372
+ words.length > 1
4373
+ ? `"${v}" is ${words.length} headings values; headings takes one at a time (a weight and a tracking are two settings).`
4374
+ : `"${v}" is the weight ${words[0]}.`,
4375
+ // Both are wanted: the second line is the next step, not
4376
+ // another choice.
4377
+ {
4378
+ run: words.map((w, i) =>
4379
+ i === 0
4380
+ ? `${P} set ${slug} headings ${w}`
4381
+ : {
4382
+ name: `${P} set ${slug} headings ${w}`,
4383
+ reason: 'then this: headings takes one value at a time',
4384
+ },
4385
+ ),
4386
+ },
4387
+ );
4388
+ }
2134
4389
  if (s.mode)
2135
4390
  refuse(
2136
4391
  E.ERR_THEME_NO_MODE,
@@ -2168,24 +4423,29 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2168
4423
  ...Object.keys(HEADING_WEIGHTS),
2169
4424
  ...Object.keys(HEADING_TRACKING),
2170
4425
  ];
2171
- const weight = /^\d+(\.\d+)?$/.test(lower) ? Number(lower) : null;
2172
- const meant =
2173
- words.find(w => w === lower) ??
2174
- (weight != null
2175
- ? Object.entries(HEADING_WEIGHTS).reduce((a, b) =>
2176
- Math.abs(Number(b[1]) - weight) <
2177
- Math.abs(Number(a[1]) - weight)
2178
- ? b
2179
- : a,
2180
- )[0]
2181
- : nearest(lower, words)[0]);
4426
+ // A weight word (extra bold, ultra-bold) is its number, read as
4427
+ // the rung nearest it (800 is heavy).
4428
+ const weightWord = WEIGHT_WORDS[lower.replace(/[\s-]+/g, '')];
4429
+ const weight = /^\d+(\.\d+)?$/.test(lower)
4430
+ ? Number(lower)
4431
+ : weightWord
4432
+ ? Number(weightWord)
4433
+ : null;
4434
+ // A typo equally near two words (tightr: tight, tighter) has each
4435
+ // as a reading.
4436
+ const readings = words.includes(lower)
4437
+ ? [lower]
4438
+ : weight != null
4439
+ ? [weightRung(weight)].filter(Boolean)
4440
+ : closestOf(lower, words);
4441
+ const meant = readings[0];
2182
4442
  refuse(
2183
4443
  E.ERR_THEME_BAD_VALUE,
2184
- `headings takes ${DIALS.headings.values}, not "${v}".${weight != null && meant ? ` ${meant} sets weight ${HEADING_WEIGHTS[meant]}.` : ''}`,
4444
+ `headings takes ${DIALS.headings.values}, not "${v}".${weight != null && meant ? ` ${meant} sets weight ${HEADING_WEIGHTS[meant]}.` : ''}${readings.length > 1 ? ` "${v}" is as near ${readings.join(' as ')}.` : ''}`,
2185
4445
  {
2186
- didYouMean: meant ? [meant] : [],
2187
- run: meant
2188
- ? [setLine(slug, 'headings', meant, s)]
4446
+ didYouMean: readings,
4447
+ run: readings.length
4448
+ ? readings.map(x => setLine(slug, 'headings', x, s))
2189
4449
  : [`${HOW} headings`],
2190
4450
  },
2191
4451
  );
@@ -2241,17 +4501,34 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2241
4501
  ? group
2242
4502
  : mine
2243
4503
  : (mine ?? group);
4504
+ // A value the step reads: a rung or a size. A saved value it cannot
4505
+ // read (a step word saved by hand) steps from what applies without
4506
+ // it, never from the first rung.
4507
+ const readable = (/** @type {unknown} */ x) =>
4508
+ x != null &&
4509
+ (typeof x === 'number' ||
4510
+ L.some(([n]) => n === x) ||
4511
+ lengthPx(String(x)) != null ||
4512
+ /^\d*\.?\d+$/.test(String(x)));
2244
4513
  const cur =
2245
- shown?.value ??
2246
- // A part's own radius (a number) already counts a whole-theme
2247
- // setting.
2248
- (s.on && typeof def !== 'number' ? own('') : undefined) ??
2249
- def;
4514
+ [
4515
+ shown?.value,
4516
+ // A part's own radius (a number) already counts a whole-theme
4517
+ // setting.
4518
+ s.on && typeof def !== 'number' ? own('') : undefined,
4519
+ def,
4520
+ ].find(readable) ?? def;
2250
4521
  const at = L.findIndex(([n]) => n === cur);
4522
+ const stepped = at + (v === 'more' ? 1 : -1);
4523
+ if (at >= 0 && stepped >= 0 && stepped < L.length) return L[stepped][0];
4524
+ // At the last rung that way, a step goes nowhere: refused as every
4525
+ // dial refuses it at its end, with the other way.
2251
4526
  if (at >= 0)
2252
- return L[
2253
- Math.max(0, Math.min(L.length - 1, at + (v === 'more' ? 1 : -1)))
2254
- ][0];
4527
+ refuse(
4528
+ E.ERR_THEME_NO_EFFECT,
4529
+ `${thing} is already at its ${v === 'more' ? 'largest' : 'smallest'} step, ${L[at][0]}${s.on ? ` on ${s.on}` : ''}, so "${v}" has nowhere to go.`,
4530
+ {run: [setLine(slug, thing, v === 'more' ? 'less' : 'more', s)]},
4531
+ );
2255
4532
  // A size between rungs steps to the next rung that way, never past it.
2256
4533
  const px =
2257
4534
  typeof cur === 'number'
@@ -2279,7 +4556,7 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2279
4556
  );
2280
4557
  refuse(
2281
4558
  E.ERR_THEME_BAD_VALUE,
2282
- `${thing} is ${typeof cur === 'number' ? `${cur}px` : cur}, already ${v === 'more' ? 'above' : 'below'} its ${v === 'more' ? 'largest' : 'smallest'} step (${edge[0]}, ${edge[1]}px), so "${v}" has nowhere to go.${atEnd ? ` It is also the ${v === 'more' ? 'largest' : 'smallest'} size ${thing} takes (${lo} to ${hi}); the base font size token takes any size.` : ' Give an exact size.'}`,
4559
+ `${thing} is ${typeof cur === 'number' ? `${cur}px` : cur}, already ${Math.abs(px - edge[1]) < 0.01 ? 'at' : v === 'more' ? 'above' : 'below'} its ${v === 'more' ? 'largest' : 'smallest'} step (${edge[0]}, ${edge[1]}px), so "${v}" has nowhere to go.${atEnd ? ` It is also the ${v === 'more' ? 'largest' : 'smallest'} size ${thing} takes (${lo} to ${hi}); the base font size token takes any size.` : ' Give an exact size.'}`,
2283
4560
  {
2284
4561
  run: atEnd
2285
4562
  ? [
@@ -2335,7 +4612,10 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2335
4612
  {run: [setLine(slug, thing, v, {...s, mode: undefined})]},
2336
4613
  );
2337
4614
  if (thing === 'corners') {
2338
- if (s.on) refuseInvisibleCorners(ctx, slug, s, data);
4615
+ if (s.on) {
4616
+ refuseInvisibleCorners(ctx, slug, s, data);
4617
+ refuseRadioCorners(ctx, slug, s);
4618
+ }
2339
4619
  // With no corners setting yet, a step starts from the base theme's
2340
4620
  // own radius.
2341
4621
  if (step) {
@@ -2382,9 +4662,16 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2382
4662
  // A step on a member set alone stays on that member alone.
2383
4663
  if (onPart && onPart.on === s.on && onPart.only && !s.only)
2384
4664
  s.only = true;
4665
+ // A saved value the step cannot read (a step word saved by hand)
4666
+ // is passed over: the step goes from what applies without it.
2385
4667
  const whole = [...data.settings]
2386
4668
  .reverse()
2387
- .find(x => x.thing === 'corners' && !x.on);
4669
+ .find(
4670
+ x =>
4671
+ x.thing === 'corners' &&
4672
+ !x.on &&
4673
+ !Number.isNaN(cornerPxOf(String(x.value))),
4674
+ );
2388
4675
  const isRung = (/** @type {string} */ x) =>
2389
4676
  CORNERS.some(([n]) => n === x);
2390
4677
  // An exact border-radius on the part wins over any corners dial:
@@ -2406,17 +4693,33 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2406
4693
  const shown =
2407
4694
  exactPx != null
2408
4695
  ? exactPx
2409
- : onPart
4696
+ : onPart && !Number.isNaN(cornerPxOf(String(onPart.value)))
2410
4697
  ? isRung(onPart.value) || cornerPxOf(onPart.value) >= 1000
2411
4698
  ? radiusAt(base, onPart.value, token)
2412
4699
  : cornerPxOf(onPart.value)
2413
4700
  : whole
2414
4701
  ? radiusAt(base, whole.value, token)
2415
- : // The base theme's radius; one it does not give in px (a var()
2416
- // chain) counts as medium's.
2417
- (tokenPx(base, token) ?? radiusAt(base, 'medium', token));
2418
- const rungs = CORNERS.map(
2419
- ([n]) => /** @type {const} */ ([n, radiusAt(base, n, token)]),
4702
+ : // The base theme's own radius on the part, when its rule
4703
+ // gives one; else the radius token's; one it does not give
4704
+ // in px (a var() chain) counts as medium's.
4705
+ (basePartRadiusPx(ctx, base, part, s.when) ??
4706
+ tokenPx(base, token) ??
4707
+ radiusAt(base, 'medium', token));
4708
+ // A step between round and pill (half as round again as round), so
4709
+ // one step more from round is not a pill.
4710
+ const roundPx = CORNERS.find(([n]) => n === 'round')?.[1] ?? 16;
4711
+ const ladder = CORNERS.flatMap(([n]) =>
4712
+ n === 'pill' ? [`${roundPx * 1.5}px`, n] : [n],
4713
+ );
4714
+ // A size on a part is that radius as written (as the part's own
4715
+ // setting reads); a rung, or a size for the whole theme, is the
4716
+ // radius it gives the part's token.
4717
+ const rungs = ladder.map(
4718
+ n =>
4719
+ /** @type {const} */ ([
4720
+ n,
4721
+ s.on && !isRung(n) ? cornerPxOf(n) : radiusAt(base, n, token),
4722
+ ]),
2420
4723
  );
2421
4724
  const next =
2422
4725
  v === 'more'
@@ -2435,17 +4738,26 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2435
4738
  );
2436
4739
  s.value = next ? next[0] : 'medium';
2437
4740
  } else {
4741
+ // A value with copy debris (`8px;`): the value without it.
4742
+ if (withoutCopyDebris(v) !== v && withoutCopyDebris(v))
4743
+ refuse(
4744
+ E.ERR_THEME_BAD_VALUE,
4745
+ `"${v}" holds copy debris (a ;, a comment or !important); corners takes the value alone.`,
4746
+ {run: [setLine(slug, 'corners', withoutCopyDebris(v), s)]},
4747
+ );
2438
4748
  // A rung in any case, a size in px written any way: the plain form.
2439
4749
  const lower = v.toLowerCase();
2440
- // Any CSS number in px (2e1px, +4px), the shared length parse.
2441
- const pxLen = /px$/.test(lower) ? lengthPx(lower) : null;
2442
- if (CORNERS.some(([n]) => n === lower)) s.value = lower;
2443
- else if (pxLen != null && pxLen >= 0)
2444
- s.value =
2445
- pxLen >= 1000 ? 'pill' : `${Math.round(pxLen * 10000) / 10000}px`;
4750
+ // Any CSS number in px (2e1px, +4px), the shared length parse; a
4751
+ // rem is that many 16px, saved in px (the one reading, cornersPlain,
4752
+ // which the settings reader gives a saved value too).
4753
+ const plain = cornersPlain(v);
4754
+ if (plain) {
4755
+ s.value = plain;
4756
+ if (/rem$/.test(lower))
4757
+ s.note = `corners ${v.trim()} is saved as ${s.value}`;
4758
+ }
2446
4759
  // No rounding, said any way, is square.
2447
- else if (/^(0|0%|none|sharp|zero|no|flat)$/.test(lower))
2448
- s.value = 'square';
4760
+ else if (NO_ROUNDING.includes(lower)) s.value = 'square';
2449
4761
  else {
2450
4762
  // What it most likely means, as a value corners takes: a simple
2451
4763
  // calc() of px is worked out.
@@ -2461,14 +4773,33 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2461
4773
  '-': Number(calc[1]) - Number(calc[3]),
2462
4774
  }[/** @type {'*' | '/' | '+' | '-'} */ (calc[2])]
2463
4775
  : null;
4776
+ // A bare number (0.5, as a pasted --radius: 0.5rem loses its
4777
+ // unit) has no unit to read it by: no size is guessed.
4778
+ const bareNumber = /^[+-]?\d*\.?\d+$/.test(lower);
4779
+ // A comma between digits as the one comma rule reads it
4780
+ // (0,5rem is 0.5rem).
2464
4781
  const len =
2465
4782
  calcPx != null && Number.isFinite(calcPx)
2466
4783
  ? calcPx
2467
- : lengthPx(lower);
4784
+ : bareNumber
4785
+ ? null
4786
+ : lengthPx(commaNumbers(lower));
2468
4787
  const pct = /^(\d+(?:\.\d+)?)%$/.exec(lower);
4788
+ // Tailwind's names, and rounding said with a negation: what they
4789
+ // mean (rounded-none and not round are square, rounded-full is
4790
+ // pill, rounded-[12px] is 12px).
4791
+ const tw = /^rounded-\[(.+)\]$/.exec(lower)?.[1];
4792
+ const opposite =
4793
+ TAILWIND_RADIUS[lower] ??
4794
+ (tw && lengthPx(tw) != null
4795
+ ? `${Math.round(Number(lengthPx(tw)) * 100) / 100}px`
4796
+ : negates(lower) && /round/.test(lower)
4797
+ ? 'square'
4798
+ : null);
2469
4799
  // A radius below zero means none: square.
2470
4800
  const meant =
2471
- len != null
4801
+ opposite ??
4802
+ (len != null
2472
4803
  ? len <= 0
2473
4804
  ? 'square'
2474
4805
  : `${Math.round(len * 100) / 100}px`
@@ -2476,17 +4807,34 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2476
4807
  ? Number(pct[1]) >= 50
2477
4808
  ? 'pill'
2478
4809
  : null
2479
- : (nearest(
2480
- lower,
2481
- CORNERS.map(([n]) => n),
2482
- )[0] ?? null);
4810
+ : bareNumber
4811
+ ? null
4812
+ : (nearest(
4813
+ lower,
4814
+ CORNERS.map(([n]) => n),
4815
+ )[0] ?? null));
2483
4816
  refuse(
2484
4817
  E.ERR_THEME_BAD_VALUE,
2485
- `corners takes ${DIALS.corners.values}, not "${v}".`,
4818
+ `corners takes ${DIALS.corners.values}, not "${v}"${bareNumber ? ' (a number needs its unit: px or rem)' : ''}.`,
2486
4819
  {
2487
4820
  ...(meant ? {didYouMean: [meant]} : {}),
2488
4821
  // The same scope, flags included.
2489
- run: [setLine(slug, 'corners', meant ?? 'medium', s)],
4822
+ // Nothing near: how corners, never a stock rung.
4823
+ // A whole bare number gets the line with px, the unit it
4824
+ // most likely meant, and how corners; one below one (a
4825
+ // pasted 0.5rem that lost its unit) has no unit to read it
4826
+ // by: how corners only.
4827
+ run:
4828
+ bareNumber && Number(lower) >= 1
4829
+ ? [
4830
+ setLine(slug, 'corners', `${Number(lower)}px`, s),
4831
+ `${HOW} corners`,
4832
+ ]
4833
+ : [
4834
+ meant
4835
+ ? setLine(slug, 'corners', meant, s)
4836
+ : `${HOW} corners`,
4837
+ ],
2490
4838
  },
2491
4839
  );
2492
4840
  }
@@ -2528,7 +4876,7 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2528
4876
  }
2529
4877
  // A scale typed as a number (x0.75, 0.75, 75%) names the rung nearest
2530
4878
  // that factor.
2531
- const factor = /^x?(\d*\.?\d+)(%)?$/i.exec(v);
4879
+ const factor = /^x?(\d*\.?\d+)(%)?$/i.exec(commaNumbers(v));
2532
4880
  const nearFactor = factor
2533
4881
  ? SPACING.reduce((a, b) =>
2534
4882
  Math.abs(b[1] - Number(factor[1]) / (factor[2] ? 100 : 1)) <
@@ -2547,7 +4895,7 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2547
4895
  run: [setLine(slug, 'spacing', nearFactor, s)],
2548
4896
  },
2549
4897
  );
2550
- else if (/^(0|none|zero|no|off)$/i.test(v))
4898
+ else if (NO_SPACE.includes(v.toLowerCase()))
2551
4899
  // Spacing scales the theme's space; it never goes to nothing. The
2552
4900
  // tightest rung is the nearest that works.
2553
4901
  refuse(
@@ -2568,15 +4916,15 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2568
4916
  SPACING.map(([n]) => n),
2569
4917
  ),
2570
4918
  run: [
2571
- setLine(
2572
- slug,
2573
- 'spacing',
2574
- nearest(
4919
+ (() => {
4920
+ const near = nearest(
2575
4921
  v,
2576
4922
  SPACING.map(([n]) => n),
2577
- )[0] ?? 'roomy',
2578
- s,
2579
- ),
4923
+ )[0];
4924
+ return near
4925
+ ? setLine(slug, 'spacing', near, s)
4926
+ : `${HOW} spacing`;
4927
+ })(),
2580
4928
  ],
2581
4929
  },
2582
4930
  );
@@ -2601,7 +4949,10 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2601
4949
  })(),
2602
4950
  },
2603
4951
  );
2604
- if (step) s.value = ladder(TEXT_SIZE, 'medium');
4952
+ // With no text-size setting yet, a step starts from the size the base
4953
+ // theme's body text shows (past the last rung, it asks for a size).
4954
+ if (step)
4955
+ s.value = ladder(TEXT_SIZE, ctx.base ? baseTextPx(ctx.base) : 'medium');
2605
4956
  else if (
2606
4957
  /^\d+\.\d+$/.test(v.trim()) &&
2607
4958
  Number(v) >= 10 &&
@@ -2620,31 +4971,46 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2620
4971
  E.ERR_THEME_BAD_VALUE,
2621
4972
  `text-size takes ${DIALS['text-size'].values} (a number is the body size in pixels, 10 to 32), not "${v}".`,
2622
4973
  (() => {
2623
- // A rung in other letter case (Medium) or with px is that rung.
2624
- const near =
2625
- TEXT_SIZE.find(([n]) => n === v.trim().toLowerCase())?.[0] ??
2626
- nearest(
2627
- v.trim().toLowerCase(),
2628
- TEXT_SIZE.map(([n]) => n),
2629
- )[0];
2630
- return near
4974
+ // A rung in other letter case (Medium) or with px is that rung;
4975
+ // a CSS size keyword (x-large) is the size CSS gives it.
4976
+ const keyword = CSS_SIZE_KEYWORDS[v.trim().toLowerCase()];
4977
+ if (keyword != null && keyword >= 10 && keyword <= 32)
4978
+ return {run: [`${P} set ${slug} text-size ${keyword}`]};
4979
+ const exact = TEXT_SIZE.find(
4980
+ ([n]) => n === v.trim().toLowerCase(),
4981
+ )?.[0];
4982
+ // A typo equally near two rungs (largr) has each as a reading.
4983
+ const near = exact
4984
+ ? [exact]
4985
+ : closestOf(
4986
+ v.trim().toLowerCase(),
4987
+ TEXT_SIZE.map(([n]) => n),
4988
+ );
4989
+ return near.length
2631
4990
  ? {
2632
- didYouMean: [near],
2633
- run: [`${P} set ${slug} text-size ${near}`],
4991
+ didYouMean: near,
4992
+ run: near.map(x => `${P} set ${slug} text-size ${x}`),
2634
4993
  }
2635
- : {
2636
- run: [
2637
- `${P} set ${slug} text-size ${
2638
- // A size typed full-width or with a trailing dot
2639
- // (18, 18.) is that size.
2640
- /^\d+(\.\d+)?\.?$/.test(typedPlain(v)) &&
2641
- Number(typedPlain(v).replace(/\.$/, '')) >= 10 &&
2642
- Number(typedPlain(v).replace(/\.$/, '')) <= 32
2643
- ? String(Number(typedPlain(v).replace(/\.$/, '')))
2644
- : (textSizePx(v) ?? 16)
2645
- }`,
2646
- ],
2647
- };
4994
+ : (() => {
4995
+ // A size typed full-width or with a trailing dot
4996
+ // (18, 18.) is that size; one read any other way (a
4997
+ // unit, a constant calc()) is that size. Nothing read:
4998
+ // how text-size, never a stock size.
4999
+ const t = typedPlain(v).replace(/\.$/, '');
5000
+ const size =
5001
+ /^\d+(\.\d+)?$/.test(t) &&
5002
+ Number(t) >= 10 &&
5003
+ Number(t) <= 32
5004
+ ? String(Number(t))
5005
+ : textSizePx(v);
5006
+ return {
5007
+ run: [
5008
+ size != null
5009
+ ? `${P} set ${slug} text-size ${size}`
5010
+ : `${HOW} text-size`,
5011
+ ],
5012
+ };
5013
+ })();
2648
5014
  })(),
2649
5015
  );
2650
5016
  else if (!TEXT_SIZE.some(([n]) => n === v))
@@ -2665,13 +5031,51 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2665
5031
  .replace(/\s*!important\s*$/i, '')
2666
5032
  .replace(/;+\s*$/, '')
2667
5033
  .trim()
2668
- .replace(/^([0-9a-f]{3}|[0-9a-f]{6})$/i, '#$1')
2669
- // One hex digit short or over: repeat or drop the last one.
2670
- .replace(/^#([0-9a-f]{4})([0-9a-f])$/i, '#$1$2$2')
2671
- .replace(/^#([0-9a-f]{6})[0-9a-f]$/i, '#$1');
5034
+ // A hex written 0x… (as in code) is that hex.
5035
+ .replace(/^0x([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i, '#$1')
5036
+ .replace(/^([0-9a-f]{3}|[0-9a-f]{6})$/i, '#$1');
5037
+ // A hex a digit short or over is refused as it is: the digit
5038
+ // missing could be anywhere, so none is made up.
5039
+ // A name of several words with a color among them (`navy blue`)
5040
+ // is that color.
5041
+ // Two names run together (`navyblue`) are the first, as the
5042
+ // spaced form is.
5043
+ const words = v
5044
+ .toLowerCase()
5045
+ .split(/[\s,-]+/)
5046
+ .filter(Boolean);
5047
+ // The words joined (dark red, light-blue, dark-slate-gray) are the
5048
+ // color they name. A word with a scale step (red-500, gray-900) is
5049
+ // no CSS color, and the bare word is another color: none is named.
5050
+ const joined = words.join('');
5051
+ const scaled = words.some(w => /\d/.test(w)) || /^[{]/.test(v.trim());
5052
+ const named =
5053
+ negates(v) || scaled
5054
+ ? []
5055
+ : words.length > 1 && COLOR_NAMES.includes(joined)
5056
+ ? [joined]
5057
+ : v
5058
+ .toLowerCase()
5059
+ .split(/[\s,-]+/)
5060
+ .flatMap(w =>
5061
+ COLOR_NAMES.includes(w)
5062
+ ? [w]
5063
+ : COLOR_NAMES.filter(
5064
+ n =>
5065
+ n.length >= 3 &&
5066
+ w.startsWith(n) &&
5067
+ COLOR_NAMES.includes(w.slice(n.length)),
5068
+ ).slice(0, 1),
5069
+ );
2672
5070
  const near =
2673
5071
  problem.kind === 'unknown'
2674
- ? nearest(v.toLowerCase(), COLOR_NAMES)
5072
+ ? /^#?[0-9a-f]{4,8}$/i.test(v.trim())
5073
+ ? []
5074
+ : named.length
5075
+ ? named.slice(0, 1)
5076
+ : scaled
5077
+ ? []
5078
+ : nearest(v.toLowerCase(), COLOR_NAMES)
2675
5079
  : [];
2676
5080
  // light-dark(a, b): the dial takes one color, from which it makes
2677
5081
  // both modes; the light one is offered.
@@ -2730,17 +5134,33 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2730
5134
  const colors = data.settings.filter(
2731
5135
  x => x.source === 'dial' && PALETTE_DIALS.includes(x.thing),
2732
5136
  );
2733
- // With no color to saturate, no vibrancy value is suggested.
2734
- const canApply = colors.some(x => !isGraySeed(seedOf(x.value)));
5137
+ // With no color to saturate, no vibrancy value is suggested. A color
5138
+ // counts when vibrancy changes the shades made from it at all (a warm
5139
+ // gray has a little hue to take out or add; a pure gray has none).
5140
+ const canApply = colors.some(x =>
5141
+ vibrancyMoves(x.thing, seedOf(x.value), 0, 100),
5142
+ );
2735
5143
  if (!step && canApply && (!/^\d{1,3}$/.test(v) || Number(v) > 100)) {
2736
5144
  // The value meant: a step in other letters (MORE), or the number
2737
5145
  // read as CSS reads it (70%, 7e1), kept in range.
2738
- const word = v.trim().toLowerCase();
2739
- const n = cssNumber(v);
5146
+ // Quotes around it (`"50"`) are not part of it.
5147
+ const bare = v
5148
+ .trim()
5149
+ .replace(/^(["'])(.*)\1$/, '$2')
5150
+ .trim();
5151
+ const word = bare.toLowerCase();
5152
+ // A comma between digits as the one comma rule reads it (0,5).
5153
+ const n = cssNumber(commaNumbers(bare));
5154
+ // A fraction of one (0.5) is that share of the scale (50), as a
5155
+ // number with no unit from 0 to 1 is read.
5156
+ const scaled =
5157
+ n && n.unit === '' && n.value > 0 && n.value < 1
5158
+ ? n.value * 100
5159
+ : n?.value;
2740
5160
  const near = ['more', 'less'].includes(word)
2741
5161
  ? word
2742
- : n && (n.unit === '' || n.unit === '%')
2743
- ? String(Math.max(0, Math.min(100, Math.round(n.value))))
5162
+ : n && (n.unit === '' || n.unit === '%') && scaled != null
5163
+ ? String(Math.max(0, Math.min(100, Math.round(scaled))))
2744
5164
  : null;
2745
5165
  refuse(
2746
5166
  E.ERR_THEME_BAD_VALUE,
@@ -2757,9 +5177,25 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2757
5177
  refuse(
2758
5178
  E.ERR_THEME_NO_EFFECT,
2759
5179
  colors.length
2760
- ? 'vibrancy sets how saturated the generated colors are, and every color this theme sets is a gray, so it would change nothing. Set a color first.'
2761
- : 'vibrancy sets how saturated the generated colors are, and this theme sets no color yet. Set one first.',
2762
- {run: [`${P} set ${slug} accent ${quoteCommandArgument('#7c3aed')}`]},
5180
+ ? `vibrancy sets how saturated the generated colors are, and every color this theme sets (${colors.map(x => `${x.thing} ${x.value}`).join(', ')}) comes out the same at every vibrancy: a gray with no hue to change, so it would change nothing. Set a color first.`
5181
+ : (() => {
5182
+ // Colors set as tokens or on parts are values of their own:
5183
+ // vibrancy saturates only what the color dials make.
5184
+ const own = data.settings.find(
5185
+ (/** @type {any} */ x) =>
5186
+ x &&
5187
+ typeof x.value === 'string' &&
5188
+ (/^--color-/.test(String(x.thing)) ||
5189
+ /(^|-)colou?r$|^background(-color)?$|^fill$/.test(
5190
+ String(x.thing),
5191
+ )) &&
5192
+ parseColor(x.value) != null,
5193
+ );
5194
+ return own
5195
+ ? `vibrancy sets how saturated the colors made from the color dials (accent, neutral, …) are; this theme's colors are values of their own (${own.thing} ${own.value}), which vibrancy does not change. Set a color dial such as accent first.`
5196
+ : 'vibrancy sets how saturated the generated colors are, and this theme sets no color yet. Set one first.';
5197
+ })(),
5198
+ {run: [`${HOW} accent`]},
2763
5199
  );
2764
5200
  } else if (thing === 'font') {
2765
5201
  if (s.when || s.state)
@@ -2789,7 +5225,9 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2789
5225
  )
2790
5226
  : family
2791
5227
  ? [
2792
- `${P} set ${slug} font-family ${quoteCommandArgument(v)} --on ${s.on}`,
5228
+ // A font dial word (mono, system, inter) names no family:
5229
+ // the part takes the stack it stands for.
5230
+ `${P} set ${slug} font-family ${quoteCommandArgument(fontStack(v) ?? v)} --on ${s.on}`,
2793
5231
  ]
2794
5232
  : [example];
2795
5233
  refuse(
@@ -2944,9 +5382,11 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2944
5382
  'A font family name is at most 100 characters.',
2945
5383
  {run: [`${P} set ${slug} font inter`]},
2946
5384
  );
5385
+ // A CSS escape (`Gill\ Sans`, `\5FAE`) is part of a name, as any
5386
+ // CSS value reads it; a boundary is not.
2947
5387
  if (
2948
5388
  !s.value ||
2949
- /[;{}<>\\\n]/.test(s.value) ||
5389
+ /[;{}<>\\\n]/.test(withoutCssEscapes(s.value)) ||
2950
5390
  !s.value.split(',').every(f => family(f.trim()))
2951
5391
  )
2952
5392
  refuse(
@@ -2955,6 +5395,26 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2955
5395
  {run: [`${P} set ${slug} font inter`]},
2956
5396
  );
2957
5397
  } else if (thing === 'base') {
5398
+ // A built-in base this project has not installed: install it, then
5399
+ // the same set.
5400
+ // A theme that builds on a base keeps it by changing nothing: no
5401
+ // base is offered only to a theme on none.
5402
+ if (LIKE.includes(v) && !unset && !baseInstalled(ctx.project, v))
5403
+ throw new AstryxError(
5404
+ `The ${v} theme is not installed, so ${slug} cannot build on it. Install @astryxdesign/theme-${v}, then set the base again${data.like ? `; ${slug} stays on ${data.like} until then` : ', or build on no theme'}. Nothing was changed.`,
5405
+ [
5406
+ ...onBuiltInSteps(ctx.project.cwd, v, `${P} set ${slug} base ${v}`),
5407
+ ...(data.like
5408
+ ? []
5409
+ : [
5410
+ {
5411
+ name: `${P} set ${slug} base none`,
5412
+ reason: 'build on no theme',
5413
+ },
5414
+ ]),
5415
+ ],
5416
+ E.ERR_UNKNOWN_THEME,
5417
+ );
2958
5418
  if (s.on)
2959
5419
  refuse(
2960
5420
  E.ERR_THEME_BAD_VALUE,
@@ -2963,43 +5423,54 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
2963
5423
  );
2964
5424
  if (![...LIKE, 'none'].includes(v)) {
2965
5425
  // `NEUTRAL`, `base=neutral`, `None`: the base meant.
2966
- const meant = v
2967
- .toLowerCase()
2968
- .replace(/^base\s*[=:]\s*/, '')
2969
- .trim()
2970
- .replace(/^@astryxdesign\/theme-/, '')
2971
- .replace(/^theme-/, '');
2972
- // Only a base this project has installed is suggested; a theme
2973
- // made here is never a base.
2974
- const bases = [
2975
- ...LIKE.filter(b => baseInstalled(ctx.project, b)),
2976
- 'none',
2977
- ];
2978
- // The base named in other letters is the one meant; a guess is
2979
- // only among installed bases.
5426
+ // Read from the value as typed: its letters' case marks an export
5427
+ // name (neutralTheme).
5428
+ const meant = baseWord(
5429
+ String(value ?? v)
5430
+ .trim()
5431
+ .replace(/^base\s*[=:]\s*/i, ''),
5432
+ );
5433
+ // The base meant: named in other letters, or a typo of a built-in
5434
+ // base under the one typo limit, installed or not (a theme made
5435
+ // here is never a base).
2980
5436
  const near =
2981
- bases.includes(meant) || LIKE.includes(meant)
2982
- ? [meant]
2983
- : nearest(meant, bases);
2984
- // A built-in base named that is not installed: install it, then the
2985
- // same set.
2986
- const install =
2987
- LIKE.includes(meant) && !baseInstalled(ctx.project, meant)
2988
- ? [installLine(ctx.project.cwd, [`@astryxdesign/theme-${meant}`])]
2989
- : [];
5437
+ LIKE.includes(meant) || meant === 'none'
5438
+ ? meant
5439
+ : (nearest(meant, [...LIKE, 'none'])[0] ?? null);
2990
5440
  const madeHere = fs.existsSync(themeFiles(ctx.project.cwd, v).settings);
5441
+ const message = `base takes ${DIALS.base.values}, not "${v}".${madeHere ? ` ${v} is a theme made here, and a theme builds only on a built-in one.` : ''} Nothing was changed.`;
5442
+ // A built-in base that is not installed: install it, then the same
5443
+ // set (the one install helper).
5444
+ if (near && near !== 'none' && !baseInstalled(ctx.project, near))
5445
+ throw new AstryxError(
5446
+ message,
5447
+ [
5448
+ ...onBuiltInSteps(
5449
+ ctx.project.cwd,
5450
+ near,
5451
+ `${P} set ${slug} base ${near}`,
5452
+ ),
5453
+ {name: near, reason: 'did you mean'},
5454
+ ],
5455
+ E.ERR_THEME_BAD_VALUE,
5456
+ );
2991
5457
  refuse(
2992
5458
  E.ERR_THEME_BAD_VALUE,
2993
- `base takes ${DIALS.base.values}, not "${v}".${madeHere ? ` ${v} is a theme made here, and a theme builds only on a built-in one.` : ''}`,
5459
+ message.replace(/ Nothing was changed\.$/, ''),
2994
5460
  {
2995
- didYouMean: near,
2996
- // With nothing near, every base that works here, none first.
2997
- run: near[0]
2998
- ? [...install, `${P} set ${slug} base ${near[0]}`]
5461
+ didYouMean: near ? [near] : [],
5462
+ // With nothing near: what base takes, and the installed bases;
5463
+ // no base only for a theme on none, as keeping its base means
5464
+ // changing nothing.
5465
+ run: near
5466
+ ? [`${P} set ${slug} base ${near}`]
2999
5467
  : [
3000
- 'none',
3001
- ...LIKE.filter(b => baseInstalled(ctx.project, b)),
3002
- ].map(b => `${P} set ${slug} base ${b}`),
5468
+ ...LIKE.filter(b => baseInstalled(ctx.project, b)).map(
5469
+ b => `${P} set ${slug} base ${b}`,
5470
+ ),
5471
+ ...(data.like ? [] : [`${P} set ${slug} base none`]),
5472
+ `${HOW} base`,
5473
+ ],
3003
5474
  },
3004
5475
  );
3005
5476
  }
@@ -3012,9 +5483,16 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
3012
5483
  );
3013
5484
  if (!['both', 'light-only', 'dark-only'].includes(v)) {
3014
5485
  const lower = v.toLowerCase().replace(/^mode\s*[=:]\s*/, '');
5486
+ // The one mode reader: a word that means one mode (night, dark
5487
+ // mode) is that mode only.
5488
+ const oneMode = modeWord(lower);
3015
5489
  const meant =
3016
5490
  DIAL_WORDS.mode[lower] ??
3017
- (['both', 'light-only', 'dark-only'].includes(lower) ? lower : null);
5491
+ (['both', 'light-only', 'dark-only'].includes(lower)
5492
+ ? lower
5493
+ : oneMode
5494
+ ? `${oneMode}-only`
5495
+ : null);
3018
5496
  const near = meant
3019
5497
  ? [meant]
3020
5498
  : nearest(lower, ['both', 'light-only', 'dark-only']);
@@ -3053,21 +5531,123 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
3053
5531
  ],
3054
5532
  },
3055
5533
  );
5534
+ // A dial typed as a flag (--corners round): the dial is meant.
5535
+ const dial = thing.replace(/^-+/, '');
5536
+ if (
5537
+ !(thing in TOKENS) &&
5538
+ (dial in DIALS || dial === 'base' || dial === 'mode')
5539
+ )
5540
+ refuse(
5541
+ E.ERR_THEME_UNKNOWN_TOKEN,
5542
+ `"${thing}" is not a design token; ${dial} is a dial, typed without dashes.`,
5543
+ {
5544
+ run: [setLine(slug, dial, v, {...s, mode: undefined}, unset)],
5545
+ },
5546
+ );
3056
5547
  if (!(thing in TOKENS)) {
3057
- refuse(E.ERR_THEME_UNKNOWN_TOKEN, `"${thing}" is not a design token.`, {
3058
- didYouMean: nearest(thing, Object.keys(TOKENS)),
3059
- run: [
3060
- `${HOW} --list tokens ${thing
3061
- .replace(/^-+(color-)?/, '')
3062
- .split('-')[0]
3063
- .trim()}`.trim(),
3064
- ],
3065
- });
5548
+ // The editor's own color words: danger is the error role, brand and
5549
+ // primary are the accent (as the danger and accent dials say).
5550
+ const role = thing
5551
+ .replace(/\bdanger\b/, 'error')
5552
+ .replace(/\b(brand|primary)\b/, 'accent');
5553
+ const aliased = role !== thing && role in TOKENS ? role : null;
5554
+ // The filtered list only when it lists something.
5555
+ const word = thing
5556
+ .replace(/^-+(color-)?/, '')
5557
+ .split('-')[0]
5558
+ .trim();
5559
+ const listed =
5560
+ word && Object.keys(TOKENS).some(k => k.includes(word))
5561
+ ? `${HOW} --list tokens ${word}`
5562
+ : `${HOW} --list tokens`;
5563
+ // The token written in another style (`--color_accent`,
5564
+ // `--colorAccent`, `--color accent`), as a dial or a property is read
5565
+ // in any style; else the one token a typo is near.
5566
+ const styled = `--${thing
5567
+ .replace(/^-+/, '')
5568
+ .trim()
5569
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
5570
+ .replace(/[_\s]+/g, '-')
5571
+ .toLowerCase()}`;
5572
+ const near = nearest(thing, Object.keys(TOKENS));
5573
+ const meant =
5574
+ aliased ??
5575
+ (styled !== thing && styled in TOKENS
5576
+ ? styled
5577
+ : near.length === 1
5578
+ ? near[0]
5579
+ : null);
5580
+ refuse(
5581
+ E.ERR_THEME_UNKNOWN_TOKEN,
5582
+ `"${thing}" is not a design token.${aliased ? ` The token for that role is ${aliased}.` : meant === styled ? ` It reads as ${styled}.` : ''}`,
5583
+ {
5584
+ didYouMean: meant ? [meant] : near,
5585
+ run: [...(meant ? [setLine(slug, meant, v, s, unset)] : []), listed],
5586
+ },
5587
+ );
3066
5588
  }
3067
5589
  const type = C.typeOf(thing);
3068
- // Only colors differ by mode: a shadow list cannot sit inside
3069
- // light-dark(), so a shadow per mode would remove it in both.
3070
- // undo still removes a setting an earlier release saved for one mode.
5590
+ // A shadow's colors can differ by mode inside the value: each layer's
5591
+ // color as light-dark(), the other mode's half kept from what that mode
5592
+ // shows now (the theme's own value, else the base theme's).
5593
+ if (s.mode && type === 'shadow' && !unset) {
5594
+ const other = s.mode === 'dark' ? 'light' : 'dark';
5595
+ const saved = [...(Array.isArray(data.settings) ? data.settings : [])]
5596
+ .reverse()
5597
+ .find(
5598
+ (/** @type {any} */ x) =>
5599
+ x?.thing === thing && !x.on && (!x.mode || x.mode === other),
5600
+ )?.value;
5601
+ const now = String(
5602
+ saved ?? ctx.base?.[other]?.[thing] ?? TOKENS[thing] ?? '',
5603
+ );
5604
+ /** The one color word of a layer, or null. @param {string} layer */
5605
+ const colorOf = layer =>
5606
+ splitTop(layer.trim(), ' ').find(
5607
+ w => /^light-dark\(/i.test(w) || isColorValue(w),
5608
+ ) ?? null;
5609
+ /** A light-dark() pair's half for a mode, or the color itself. @param {string} c @param {'light' | 'dark'} m */
5610
+ const halfOf = (c, m) => {
5611
+ const inner = /^light-dark\((.*)\)$/is.exec(c.trim())?.[1];
5612
+ const halves = inner == null ? [] : splitTop(inner, ',');
5613
+ return halves.length === 2 ? halves[m === 'light' ? 0 : 1].trim() : c;
5614
+ };
5615
+ const typedLayers = splitTop(String(v), ',').map(x => x.trim());
5616
+ const nowLayers = splitTop(now, ',').map(x => x.trim());
5617
+ const paired =
5618
+ typedLayers.length === nowLayers.length &&
5619
+ typedLayers.every(l => colorOf(l)) &&
5620
+ nowLayers.every(l => colorOf(l))
5621
+ ? typedLayers
5622
+ .map((l, i) => {
5623
+ const typedColor = /** @type {string} */ (colorOf(l));
5624
+ const kept = halfOf(
5625
+ /** @type {string} */ (colorOf(nowLayers[i])),
5626
+ other,
5627
+ );
5628
+ return l.replace(
5629
+ typedColor,
5630
+ s.mode === 'dark'
5631
+ ? `light-dark(${kept}, ${typedColor})`
5632
+ : `light-dark(${typedColor}, ${kept})`,
5633
+ );
5634
+ })
5635
+ .join(', ')
5636
+ : null;
5637
+ refuse(
5638
+ E.ERR_THEME_NO_MODE,
5639
+ `--mode takes a plain color; ${thing} mixes colors with sizes, so --mode cannot hold it. Its colors can still differ between light and dark: write each in the value as light-dark(<light>, <dark>).${paired ? '' : ` Only the colors can differ: the ${other} ${thing} has ${nowLayers.length} layer${nowLayers.length === 1 ? '' : 's'} with their own sizes, so a value of ${typedLayers.length} changes the ${other} mode too.`}`,
5640
+ {
5641
+ run: [
5642
+ paired
5643
+ ? `${P} set ${slug} ${thing} ${quoteCommandArgument(paired)}${onFlag} # the colors in ${s.mode} only, ${other} kept`
5644
+ : `${P} set ${slug} ${thing} ${quoteCommandArgument(v)}${onFlag} # both modes`,
5645
+ ],
5646
+ },
5647
+ );
5648
+ }
5649
+ // Only colors differ by mode. undo still removes a setting an earlier
5650
+ // release saved for one mode.
3071
5651
  if (s.mode && type !== 'color' && !unset)
3072
5652
  refuse(
3073
5653
  E.ERR_THEME_NO_MODE,
@@ -3097,6 +5677,7 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
3097
5677
  slug,
3098
5678
  C.propsReading(thing),
3099
5679
  multipliedTokens(ctx.project).has(thing),
5680
+ data.settings.some(x => x.thing === thing),
3100
5681
  );
3101
5682
  checkCycle(thing, v, TOKENS, data, ctx.project.cwd, s);
3102
5683
  // With no part data, what reads the token is unknown: save, unchecked.
@@ -3172,7 +5753,7 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
3172
5753
  const instead = /reads: ([^.]+)\./.exec(
3173
5754
  String(/** @type {any} */ (hard[0][1])?.message ?? ''),
3174
5755
  )?.[1];
3175
- s.note = `${readers.length ? `${readers.join(', ')} read ${thing} and take this change; ` : ''}the editor's render of ${hard.map(([t]) => t).join(', ')} did not read it${instead ? ` (${hard[0][0]} reads ${instead})` : ''}, so those stay as they were; each part is rendered once, with its default props, so a variant that reads it may be missed`;
5756
+ s.note = `${readers.length ? `${readers.join(', ')} read ${thing} and take this change; ` : ''}the editor's render of ${hard.map(([t]) => t).join(', ')} did not read it${instead ? ` (${hard[0][0]} reads ${instead})` : ''}, so those stay as they were; each part is rendered with its default props, each variant value and each look flag, so a state or a combination that reads it may be missed`;
3176
5757
  }
3177
5758
  if (!s.note && recorded.length) {
3178
5759
  const fed = C.feeds(recorded[0][0], thing);
@@ -3201,6 +5782,8 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
3201
5782
  s.note = `no part reads ${thing} itself, but ${fed.slice(0, 4).join(', ')} ${fed.length > 1 ? 'are' : 'is'} built from it, so the change shows wherever ${fed.length > 1 ? 'those are' : 'that is'} used${fed.some(k => k.startsWith('--color-syntax-')) ? ' (such as diff rows in code blocks)' : ''}`;
3202
5783
  else if (r && data.like && baseReads(ctx, data.like, thing))
3203
5784
  s.note = `the ${data.like} theme's own part styles read ${thing}, so the change shows where they use it`;
5785
+ else if (r && coreStylesRead(ctx, thing))
5786
+ s.note = `Core's stylesheet reads ${thing} outside the parts the editor renders (such as the page behind them, the app shell), so the change shows where it is used`;
3204
5787
  else if (r && dialWrites(thing))
3205
5788
  s.note = `no part of this Core reads ${thing}, and no token it feeds is read, so it changes nothing you see now; it is set as asked because a dial writes it too`;
3206
5789
  // The editor's record of what parts read comes from one render of
@@ -3208,11 +5791,17 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
3208
5791
  // token is set as asked, and the result says nothing was seen
3209
5792
  // reading it.
3210
5793
  else if (r)
3211
- s.note = `no part the editor rendered reads ${thing} (each part is rendered once, with its default props, so a variant that reads it may be missed); it is set as asked, and reaches any part that reads it`;
5794
+ s.note = `no part the editor rendered reads ${thing} (each part is rendered with its default props, each variant value and each look flag, so a state or a combination that reads it may be missed); it is set as asked, and reaches any part that reads it`;
3212
5795
  }
3213
5796
  return s;
3214
5797
  }
3215
- const prop = kebab(thing);
5798
+ // A property in camel case, or with `_` or spaces for its dashes
5799
+ // (backgroundColor, font_size, "border radius"), is that property: one
5800
+ // reading, so each form gets the same answer.
5801
+ const spelled = kebab(thing.trim())
5802
+ .replace(/[_\s]+/g, '-')
5803
+ .replace(/-+/g, '-');
5804
+ const prop = cssProperties().has(spelled) ? spelled : kebab(thing);
3216
5805
  // A token typed without its leading dashes (color-accent,
3217
5806
  // text-body-size): the token, when no CSS property has that name.
3218
5807
  if (
@@ -3252,39 +5841,43 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
3252
5841
  E.ERR_MISSING_ARGUMENT,
3253
5842
  `${prop} is a CSS property, so it needs --on <part|group>. For the whole theme use a dial or a token.`,
3254
5843
  {
5844
+ // The theme-wide dial or token for it, when there is one; never
5845
+ // a part that was not named.
3255
5846
  run: [
3256
- `${P} set ${slug} ${prop} ${quoteCommandArgument(v || exampleOf(groupOfPropType(prop), prop))} --on card`,
3257
- `${HOW} "${prop}"`,
5847
+ ...(v && WHOLE_THEME_EQUIVALENT[prop]
5848
+ ? [
5849
+ `${P} set ${slug} ${WHOLE_THEME_EQUIVALENT[prop]} ${quoteCommandArgument(v)}`,
5850
+ ]
5851
+ : []),
5852
+ `${HOW} ${quoteCommandArgument(prop)}`,
3258
5853
  ],
3259
5854
  },
3260
5855
  );
3261
5856
  s.source = 'property';
3262
5857
  s.thing = prop;
3263
5858
  if (unset) return s;
3264
- // A length property (padding, a corner radius, a gap) that reads a
3265
- // design token of another kind (a color, a font, a duration) gets
5859
+ // A property that reads a design token of a kind it does not take (a
5860
+ // color property reading a size, a length reading a color) gets
3266
5861
  // nothing the browser keeps: refused like the token form.
3267
- if (matchValue(prop, '1px') && !matchValue(prop, 'red'))
3268
- for (const m of v.matchAll(/var\(\s*(--[a-z0-9-]+)/gi)) {
3269
- const kind = ctx.C.isToken(m[1]) ? ctx.C.typeOf(m[1]) : null;
3270
- if (kind && !['size', 'number', 'other'].includes(kind)) {
3271
- const like = /radius/.test(prop)
3272
- ? 'var(--radius-container)'
3273
- : /^(padding|margin|gap|row-gap|column-gap|inset)/.test(prop)
3274
- ? 'var(--spacing-4)'
3275
- : exampleOf('size', prop);
3276
- refuse(
3277
- E.ERR_THEME_BAD_VALUE,
3278
- `${prop} takes a length; ${m[1]} is a ${kind}, so the browser would drop it.`,
3279
- {
3280
- run: [
3281
- `${P} set ${slug} ${prop} ${quoteCommandArgument(v.replace(new RegExp(`var\\(\\s*${m[1]}\\s*(,[^)]*)?\\)`, 'i'), like))} --on ${quoteCommandArgument(String(s.on))}${s.state ? ` --state ${s.state}` : ''}${s.when ? ` --when ${quoteCommandArgument(s.when)}` : ''}${s.mode ? ` --mode ${s.mode}` : ''}`,
3282
- `${HOW} --list tokens ${/radius/.test(prop) ? 'radius' : 'spacing'}`,
3283
- ],
3284
- },
3285
- );
3286
- }
3287
- }
5862
+ const mismatch = tokenKindMismatch(ctx, prop, v);
5863
+ if (mismatch) {
5864
+ const length = mismatch.takes === 'a length';
5865
+ const like = /radius/.test(prop)
5866
+ ? 'var(--radius-container)'
5867
+ : /^(padding|margin|gap|row-gap|column-gap|inset)/.test(prop)
5868
+ ? 'var(--spacing-4)'
5869
+ : null;
5870
+ refuse(E.ERR_THEME_BAD_VALUE, `${mismatch.message}.`, {
5871
+ run: [
5872
+ ...(length && like
5873
+ ? [
5874
+ `${P} set ${slug} ${prop} ${quoteCommandArgument(v.replace(new RegExp(`var\\(\\s*${mismatch.token}\\s*(,[^)]*)?\\)`, 'i'), like))} --on ${quoteCommandArgument(String(s.on))}${s.state ? ` --state ${s.state}` : ''}${s.when ? ` --when ${quoteCommandArgument(s.when)}` : ''}${s.mode ? ` --mode ${s.mode}` : ''}`,
5875
+ ]
5876
+ : []),
5877
+ `${HOW} --list tokens ${length ? (/radius/.test(prop) ? 'radius' : 'spacing') : mismatch.takes === 'a color' ? 'color' : ''}`.trimEnd(),
5878
+ ],
5879
+ });
5880
+ }
3288
5881
  // initial and unset leave a part's padding variables without a value:
3289
5882
  // the part takes Core's own default, which the result names.
3290
5883
  if (
@@ -3374,9 +5967,168 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
3374
5967
  },
3375
5968
  );
3376
5969
  }
5970
+ // A property Core paints with an inline style from a token outranks any
5971
+ // theme rule for it: the token the inline style reads is what changes it.
5972
+ // A paint Core always makes (an indicator's focus ring) is changed by the
5973
+ // token on the part with no state. A paint in a state (a selected table
5974
+ // row's wash) is changed by the token in that state; a component option
5975
+ // can turn that paint off (a table without its row highlight), and then
5976
+ // a rule in the state applies, so the refusal says both.
5977
+ if (!unset) {
5978
+ const family =
5979
+ prop === 'background' || prop === 'background-color'
5980
+ ? 'background-color'
5981
+ : prop;
5982
+ const inline = partsOf(ctx, s)
5983
+ .map(t => {
5984
+ const at = ctx.C.MAP[t]?.inline ?? {};
5985
+ const tok =
5986
+ (s.state ? at[s.state]?.[family] : undefined) ?? at['']?.[family];
5987
+ return /** @type {const} */ ([t, tok]);
5988
+ })
5989
+ .find(([, tok]) => tok);
5990
+ if (inline) {
5991
+ const [part, token] = inline;
5992
+ const alwaysInline = Boolean(ctx.C.MAP[part]?.inline?.['']?.[family]);
5993
+ refuse(
5994
+ E.ERR_THEME_NO_EFFECT,
5995
+ alwaysInline
5996
+ ? `Core paints ${part}'s ${family} as an inline style from ${token}, which no theme rule can replace; set ${token} on ${part} instead.`
5997
+ : `By default Core paints ${part}'s ${family} when ${s.state} as an inline style from ${token}, which no theme rule can replace, so set ${token} on ${part} when ${s.state} instead; only where the component is set not to paint it (such as a table with its row highlight off) does a ${s.state} ${family} apply, and there ${token} paints nothing.`,
5998
+ {
5999
+ run: [
6000
+ `${P} set ${slug} ${token} ${quoteCommandArgument(v)} --on ${part}${alwaysInline || !s.state ? '' : ` --state ${s.state}`}${s.mode ? ` --mode ${s.mode}` : ''}`,
6001
+ ],
6002
+ },
6003
+ );
6004
+ }
6005
+ }
6006
+ // A border on a part that draws none itself, whose edges are drawn by
6007
+ // parts of its own inside it (a date-time input's date and time boxes):
6008
+ // those parts take it.
6009
+ if (
6010
+ !unset &&
6011
+ /^border(?!.*radius)(-|$)/.test(prop) &&
6012
+ partsOf(ctx, s).length === 1
6013
+ ) {
6014
+ const part = partsOf(ctx, s)[0];
6015
+ const own = ctx.C.MAP[part]?.own ?? {};
6016
+ const inner = cornerParts(ctx, part).filter(t => t !== part);
6017
+ if (
6018
+ inner.length &&
6019
+ !Object.keys(own).some(k => /^border(?!.*radius)/.test(k))
6020
+ )
6021
+ refuse(
6022
+ E.ERR_THEME_NO_EFFECT,
6023
+ `${part} draws no border of its own; its edges are the borders of ${inner.join(' and ')}, so set ${prop} on ${inner.length > 1 ? 'those parts' : 'that part'}.`,
6024
+ {
6025
+ run: inner.map(t =>
6026
+ setLine(slug, prop, v, {...s, on: t, only: undefined}),
6027
+ ),
6028
+ },
6029
+ );
6030
+ }
6031
+ // Padding on a part Core renders as a box CSS draws no padding on (a
6032
+ // table row): the parts inside it with padding of their own take it.
6033
+ if (
6034
+ !unset &&
6035
+ /^padding(-|$)/.test(prop) &&
6036
+ !s.state &&
6037
+ partsOf(ctx, s).length === 1
6038
+ ) {
6039
+ const part = partsOf(ctx, s)[0];
6040
+ const inner = paddedParts(ctx, part).filter(t => t !== part);
6041
+ if (inner.length)
6042
+ refuse(
6043
+ E.ERR_THEME_NO_EFFECT,
6044
+ `${part} is drawn as a table row, row group or column, which CSS draws no padding on; its space is the padding of ${inner.join(' and ')}, so set ${prop} on ${inner.length > 1 ? 'those parts' : 'that part'}.`,
6045
+ {
6046
+ run: inner.map(t =>
6047
+ setLine(slug, prop, v, {...s, on: t, only: undefined}),
6048
+ ),
6049
+ },
6050
+ );
6051
+ }
6052
+ // A text property on a part whose text is drawn by elements inside it
6053
+ // that set that property themselves from a token (a top nav heading's
6054
+ // title span) never reaches that text: the token, on the part, does.
6055
+ // So does a part whose text is all in parts inside it that each set
6056
+ // the property themselves (a dialog's title block: its title and
6057
+ // subtitle).
6058
+ if (
6059
+ !unset &&
6060
+ !s.state &&
6061
+ [
6062
+ 'font-size',
6063
+ 'font-weight',
6064
+ 'line-height',
6065
+ 'letter-spacing',
6066
+ 'color',
6067
+ ].includes(prop)
6068
+ ) {
6069
+ const inner = partsOf(ctx, s)
6070
+ .map(t => {
6071
+ const rec = ctx.C.MAP[t];
6072
+ // (A color only through the parts inside it: elements inside a
6073
+ // part that read a color token are answered with the tokens on
6074
+ // the part by how.)
6075
+ let toks =
6076
+ prop === 'color'
6077
+ ? []
6078
+ : Object.entries(rec?.inside ?? {})
6079
+ .filter(([, props]) => props.includes(prop))
6080
+ .map(([tok]) => tok);
6081
+ const held = (rec?.contains ?? []).map(x => ctx.C.MAP[x]);
6082
+ if (
6083
+ !toks.length &&
6084
+ !Object.keys(rec?.inside ?? {}).length &&
6085
+ held.length &&
6086
+ held.every(x => x?.own?.[prop])
6087
+ )
6088
+ toks = [
6089
+ ...new Set(
6090
+ held.flatMap(x => Object.keys(x.own[prop].tokens ?? {})),
6091
+ ),
6092
+ ]
6093
+ .filter(tok => !/disabled|placeholder|accent/.test(tok))
6094
+ .slice(0, 4);
6095
+ return /** @type {const} */ ([
6096
+ t,
6097
+ rec && !rec.own?.[prop] ? toks : [],
6098
+ ]);
6099
+ })
6100
+ .filter(([, toks]) => toks.length);
6101
+ if (inner.length && inner.length === partsOf(ctx, s).length) {
6102
+ const [part, toks] = inner[0];
6103
+ refuse(
6104
+ E.ERR_THEME_NO_EFFECT,
6105
+ `${part}'s text is drawn by elements inside it that set their own ${prop} from ${toks.join(', ')}, so a ${prop} on ${part} never reaches it; set ${toks.length > 1 ? 'one of those tokens' : 'that token'} on ${part} instead.`,
6106
+ {
6107
+ run: toks.map(
6108
+ tok =>
6109
+ `${P} set ${slug} ${tok} ${quoteCommandArgument(v)} --on ${part}`,
6110
+ ),
6111
+ },
6112
+ );
6113
+ }
6114
+ }
6115
+ // A text property CSS inherits reaches the parts inside the part that
6116
+ // do not set it themselves (a side nav section's items): the result
6117
+ // says which.
6118
+ if (!unset) {
6119
+ const reach = inheritedReach(ctx, s, prop);
6120
+ if (reach) s.note = reach;
6121
+ }
3377
6122
  // Text, headings and links take their color from the color prop.
3378
6123
  const textParts = COLOR_PROP_PARTS;
6124
+ // A heading's color is written as the text color tokens its color prop
6125
+ // reads, on the heading alone (compileTheme), so it shows.
6126
+ const headingColor =
6127
+ prop === 'color' &&
6128
+ partsOf(ctx, s).length > 0 &&
6129
+ partsOf(ctx, s).every(t => t === 'heading');
3379
6130
  if (
6131
+ !headingColor &&
3380
6132
  (prop === 'color' || prop === '-webkit-text-fill-color') &&
3381
6133
  partsOf(ctx, s).some(t => textParts.includes(t))
3382
6134
  ) {
@@ -3388,84 +6140,47 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
3388
6140
  v && isColorValue(v) && isFixedColor(v) && !/\bvar\(/i.test(v)
3389
6141
  ? v
3390
6142
  : (nearestColorName(v) ?? '#1f2937');
6143
+ // The tokens the part's color prop reads: the one named, else the
6144
+ // prop's default as its doc gives it (a link's accent), else each
6145
+ // color whose token the part reads (Text's depends on its type),
6146
+ // set on the part alone.
6147
+ const colors = named
6148
+ ? [named]
6149
+ : colorPropDefaults(
6150
+ partComponentDocs(ctx, /** @type {string} */ (s.on))
6151
+ .map(d => d.doc.props?.color)
6152
+ .find(Boolean),
6153
+ ctx.C.MAP[/** @type {string} */ (s.on)]?.own?.color?.tokens,
6154
+ );
6155
+ const tail = `${s.on ? ` --on ${s.on}` : ''}${s.mode ? ` --mode ${s.mode}` : ''}`;
3391
6156
  refuse(
3392
6157
  E.ERR_THEME_NO_EFFECT,
3393
- `${s.on} takes its color from the color prop, which Core sets after part styles, so a color set on ${s.on} never shows. Set the text color token instead.`,
6158
+ `${s.on} takes its color from the color prop, which Core sets after part styles, so a color set on ${s.on} never shows. Set the token its color prop reads (${colors.map(c => `${c}: --color-text-${c}`).join('; ')}) on ${s.on} instead.`,
3394
6159
  {
3395
- run: [
3396
- `${P} set ${slug} --color-text-${named ?? 'primary'} ${quoteCommandArgument(color)}${s.mode ? ` --mode ${s.mode}` : ''}`,
3397
- ...(named
3398
- ? []
3399
- : [
3400
- `${P} set ${slug} --color-text-secondary ${quoteCommandArgument(color)}${s.mode ? ` --mode ${s.mode}` : ''}`,
3401
- ]),
3402
- ],
6160
+ run: colors.map(
6161
+ c =>
6162
+ `${P} set ${slug} --color-text-${c} ${quoteCommandArgument(color)}${tail}`,
6163
+ ),
3403
6164
  },
3404
6165
  );
3405
6166
  }
3406
6167
  s.note = `text, heading and link inside ${s.on} keep the color their color prop gives; set --color-text-primary for those`;
3407
6168
  }
3408
- // One mode on a part whose variants each read their own value: the
3409
- // other mode cannot keep each variant's value in one rule.
3410
- // With a state, the other mode would take one variant's value for
3411
- // every variant, so any part whose variants read their own value needs
3412
- // the variant named.
3413
- // Per-variant colors only: a value that is not a color is refused for
3414
- // --mode below, with the reason that holds.
3415
- if (
3416
- s.mode &&
3417
- !s.when &&
3418
- (COLOR_PROPS.test(prop) || (prop === 'background' && isColorValue(v)))
3419
- ) {
3420
- const g = C.groupOfProp(
3421
- prop === 'background' ? 'background-color' : prop,
3422
- );
3423
- for (const t of partsOf(ctx, s)) {
3424
- const reads = g
3425
- ? C.partReads(t, g).filter(r => r.props.includes(prop))
3426
- : [];
3427
- const variantsOf = (
3428
- /** @type {(w: string) => string | undefined} */ pick,
3429
- ) => [
3430
- ...new Set(
3431
- reads
3432
- .flatMap(r => r.when)
3433
- .map(pick)
3434
- .filter(Boolean),
3435
- ),
3436
- ];
3437
- // Resting reads keyed by the variant alone, and reads in the state.
3438
- const rest = variantsOf(w => /^variant=([\w-]+)$/.exec(w)?.[1]);
3439
- const inState = s.state
3440
- ? variantsOf(w =>
3441
- w.includes(`:${s.state}`)
3442
- ? /(?:^|,)variant=([\w-]+)/.exec(w)?.[1]
3443
- : undefined,
3444
- )
3445
- : [];
3446
- // A state that does not change this property shows each variant's
3447
- // resting value, so that is what the other mode must keep.
3448
- const variants = inState.length ? inState : rest;
3449
- const perVariant = inState.length
3450
- ? true
3451
- : rest.length > 0 && !reads.some(r => r.when.includes(''));
3452
- if (reads.length && variants.length && perVariant)
3453
- refuse(
3454
- E.ERR_THEME_NO_MODE,
3455
- `Each variant of ${t} has its own ${prop}${s.state ? ` when ${s.state}` : ''}, so one mode cannot be set for all of them at once: the other mode would take one variant's color for every variant. Name the variant.`,
3456
- {
3457
- run: [
3458
- `${P} set ${slug} ${prop} ${quoteCommandArgument(v)} --on ${s.on} --when variant:${variants[0]}${s.state ? ` --state ${s.state}` : ''} --mode ${s.mode}`,
3459
- ],
3460
- },
3461
- );
3462
- }
3463
- }
6169
+ // One mode on a part whose variants each read their own color is
6170
+ // written to each variant's rule with that variant's own other half
6171
+ // (compileTheme), so it needs no variant named.
3464
6172
  if (!isSafeValue(v))
3465
6173
  refuse(
3466
6174
  E.ERR_THEME_BAD_VALUE,
3467
6175
  `"${v}" cannot be a CSS value: it has a ; { } < > or a newline, a comment, !important, or an unclosed bracket or quote.`,
3468
- {run: [`${HOW} ${prop}`]},
6176
+ {
6177
+ // The value without its copy debris, when that is one.
6178
+ run: [
6179
+ withoutCopyDebris(v) !== v && isSafeValue(withoutCopyDebris(v))
6180
+ ? setLine(slug, prop, withoutCopyDebris(v), s)
6181
+ : `${HOW} ${prop}`,
6182
+ ],
6183
+ },
3469
6184
  );
3470
6185
  if (/radius$/.test(prop)) refuseInvisibleCorners(ctx, slug, s, data);
3471
6186
  if (step)
@@ -3536,61 +6251,141 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
3536
6251
  if (
3537
6252
  s.mode &&
3538
6253
  !COLOR_PROPS.test(prop) &&
3539
- !(prop === 'background' && isColorValue(v))
6254
+ !(prop === 'background' && isColorValue(v)) &&
6255
+ // A gradient background (no image file) goes per mode: its colors
6256
+ // are each painted in that mode only (compileTheme).
6257
+ !(
6258
+ /^background(-image)?$/.test(prop) &&
6259
+ /gradient\(/i.test(v) &&
6260
+ !/url\(/i.test(v)
6261
+ )
3540
6262
  ) {
3541
- // A color mixed into the value (a border's) can go per mode on its
3542
- // own; a value with none (a radius) is just set for both modes.
3543
- const hasColor = /#[0-9a-f]{3,8}\b|rgba?\(|hsla?\(/i.test(v);
3544
- const alt = !hasColor
6263
+ // A shorthand's color can go per mode through its color longhand
6264
+ // (border-color for border), set for that mode alone: the other mode
6265
+ // keeps its color. Its other words (width, style) are not colors, so
6266
+ // they are set for both modes, as their own longhands. A value with
6267
+ // no color (a radius) is just set for both modes.
6268
+ const words = splitTop(String(v).trim(), ' ').filter(Boolean);
6269
+ const colorWord = /gradient\(/i.test(v)
3545
6270
  ? null
3546
- : prop === 'border' || prop.startsWith('border-')
3547
- ? 'border-color'
3548
- : prop === 'background'
3549
- ? 'background-color'
6271
+ : (words.find(
6272
+ w =>
6273
+ isColorValue(w) &&
6274
+ !/^(currentcolor|inherit|initial|unset|revert)$/i.test(w),
6275
+ ) ?? null);
6276
+ const longhandOf = (/** @type {string} */ part) =>
6277
+ cssProperties().has(`${prop}-${part}`) ? `${prop}-${part}` : null;
6278
+ // The longhands a shorthand's words go to, from CSS's own names.
6279
+ const alt = !colorWord
6280
+ ? null
6281
+ : prop === 'background'
6282
+ ? 'background-color'
6283
+ : longhandOf('color') && COLOR_PROPS.test(`${prop}-color`)
6284
+ ? `${prop}-color`
3550
6285
  : null;
3551
- refuse(
3552
- E.ERR_THEME_NO_MODE,
3553
- `--mode works on plain colors; ${prop} ${prop === 'box-shadow' || prop === 'border' ? 'mixes a color with sizes' : 'is not a color'}, so it cannot differ between light and dark.`,
3554
- {
3555
- run: alt
3556
- ? [
3557
- `${P} set ${slug} ${prop} ${quoteCommandArgument(v.replace(/#[0-9a-f]{3,8}|rgba?\([^)]*\)/i, 'currentcolor'))} --on ${s.on}${whenFlag} # the shape, both modes`,
3558
- `${P} set ${slug} ${alt} ${quoteCommandArgument(/#[0-9a-f]{3,8}\b|rgba?\([^)]*\)|hsla?\([^)]*\)/i.exec(v)?.[0] ?? '#1f2937')} --on ${s.on}${whenFlag} --mode ${s.mode} # then the color per mode`,
3559
- ]
3560
- : [
3561
- `${P} set ${slug} ${prop} ${quoteCommandArgument(v)} --on ${s.on}${whenFlag} # both modes`,
3562
- ],
3563
- },
6286
+ // A line (a border, one side's border, an outline) the part does not
6287
+ // draw now would appear in the other mode too, with its current
6288
+ // color: only a line the part draws takes its color by mode here.
6289
+ const lined = /^(?:border(?:-(?:top|right|bottom|left))?|outline)$/.test(
6290
+ prop,
3564
6291
  );
3565
- }
3566
- // In a state, the other mode keeps the state's own value there (or a
3567
- // value set for both modes); with none to keep, the setting would
3568
- // change that mode too. Without a state, the other mode keeps the
3569
- // part's plain color.
3570
- if (
3571
- s.mode &&
3572
- s.state &&
3573
- !partsOf(ctx, s).every(t =>
3574
- partDefault(ctx, t, camel(prop), s.when, s.state),
3575
- ) &&
3576
- !data.settings.some(
3577
- x =>
3578
- x.thing === prop &&
3579
- x.on === s.on &&
3580
- x.when === s.when &&
3581
- x.state === s.state &&
3582
- x.mode !== s.mode,
3583
- )
3584
- )
6292
+ const undrawn =
6293
+ lined && !drawsLine(C, partsOf(ctx, s), prop, s.state ?? null);
6294
+ // On a part whose variants each have their own color, the color per
6295
+ // mode is set for one variant at a time (as that refusal says): the
6296
+ // step names the default one, or the first.
6297
+ let altWhen = '';
6298
+ if (alt === 'background-color' && !s.when) {
6299
+ const g = C.groupOfProp(alt);
6300
+ const variants = [
6301
+ ...new Set(
6302
+ partsOf(ctx, s).flatMap(t =>
6303
+ (g ? C.partReads(t, g) : [])
6304
+ .filter(r => r.props.includes(alt))
6305
+ .flatMap(r => r.when)
6306
+ .map(w => /^variant=([\w-]+)$/.exec(w)?.[1])
6307
+ .filter(Boolean),
6308
+ ),
6309
+ ),
6310
+ ];
6311
+ const plain = partsOf(ctx, s).some(t =>
6312
+ (g ? C.partReads(t, g) : []).some(
6313
+ r => r.props.includes(alt) && r.when.includes(''),
6314
+ ),
6315
+ );
6316
+ if (variants.length && !plain)
6317
+ altWhen = ` --when variant:${variants.includes('default') ? 'default' : variants[0]}`;
6318
+ }
6319
+ // The shorthand's other words, each to its own longhand (a width, a
6320
+ // style), for both modes: only what the value gives.
6321
+ const shapeLines =
6322
+ alt && prop !== 'background'
6323
+ ? words
6324
+ .filter(w => w !== colorWord)
6325
+ .map(w => {
6326
+ const longhand = ['style', 'width', 'line', 'thickness']
6327
+ .map(longhandOf)
6328
+ .find(
6329
+ lh =>
6330
+ lh &&
6331
+ matchValue(lh, w) &&
6332
+ !(lh.endsWith('-width') && /^(none|hidden)$/.test(w)),
6333
+ );
6334
+ return longhand
6335
+ ? `${P} set ${slug} ${longhand} ${quoteCommandArgument(w)}${onFlag}${whenFlag} # both modes`
6336
+ : null;
6337
+ })
6338
+ : [];
6339
+ const shapeRuns = /** @type {string[]} */ (
6340
+ shapeLines.filter(x => x != null)
6341
+ );
6342
+ // A color with no longhand of its own (a shadow's) goes per mode in
6343
+ // the value: light-dark() holds each mode's color, and a part with
6344
+ // no such property of its own shows none in the other mode.
6345
+ const ownShadow = partsOf(ctx, s).some(t => ctx.C.MAP[t]?.own?.[prop]);
6346
+ const inValue =
6347
+ !alt &&
6348
+ colorWord &&
6349
+ /shadow$/.test(prop) &&
6350
+ !ownShadow &&
6351
+ matchValue(prop, String(v).replace(colorWord, 'red'))
6352
+ ? String(v).replace(
6353
+ colorWord,
6354
+ s.mode === 'dark'
6355
+ ? `light-dark(transparent, ${colorWord})`
6356
+ : `light-dark(${colorWord}, transparent)`,
6357
+ )
6358
+ : null;
6359
+ const runs = alt
6360
+ ? shapeRuns.length < shapeLines.length || undrawn
6361
+ ? null
6362
+ : [
6363
+ ...shapeRuns,
6364
+ `${P} set ${slug} ${alt} ${quoteCommandArgument(String(colorWord))}${onFlag}${altWhen}${whenFlag} --mode ${s.mode} # the color, ${s.mode} only${altWhen ? ', for each variant' : ''}`,
6365
+ ]
6366
+ : inValue
6367
+ ? [
6368
+ `${P} set ${slug} ${prop} ${quoteCommandArgument(inValue)}${onFlag}${whenFlag} # the color in ${s.mode} only`,
6369
+ ]
6370
+ : null;
3585
6371
  refuse(
3586
6372
  E.ERR_THEME_NO_MODE,
3587
- `${s.on} has no ${prop}${s.state ? ` when ${s.state}` : ''}${s.when ? ` for ${s.when}` : ''} of its own for the ${s.mode === 'light' ? 'dark' : 'light'} mode to keep, so a ${s.mode}-only value would change it too. Set it for both modes.`,
6373
+ alt && undrawn
6374
+ ? `--mode takes a plain color; ${s.on} draws no ${prop} now, and a line's width and style are the same in both modes, so it would show in the other mode too. Write its color in the value as light-dark(<light>, <dark>), with transparent for the mode that shows none.`
6375
+ : alt
6376
+ ? `--mode takes a plain color; ${prop} mixes a color with ${words.length > 1 ? 'other words' : 'nothing else'}, so its color goes per mode through ${alt}${shapeLines.length ? `, and its ${prop === 'text-decoration' ? 'line and style' : 'width and style'} for both modes` : ''}.`
6377
+ : colorWord && /shadow$/.test(prop)
6378
+ ? `--mode takes a plain color; ${prop} mixes a color with sizes, so --mode cannot hold it. Its color can still differ between light and dark: write it in the value as light-dark(<light>, <dark>).`
6379
+ : `--mode works on plain colors; ${prop} is not a color, so it is set for both modes.`,
3588
6380
  {
3589
- run: [
3590
- `${P} set ${slug} ${prop} ${quoteCommandArgument(v)} --on ${s.on}${s.when ? ` --when ${s.when}` : ''}${s.state ? ` --state ${s.state}` : ''}`,
6381
+ run: runs ?? [
6382
+ colorWord
6383
+ ? `${HOW} ${s.on ?? ''}`.trim()
6384
+ : `${P} set ${slug} ${prop} ${quoteCommandArgument(v)}${onFlag}${whenFlag} # both modes`,
3591
6385
  ],
3592
6386
  },
3593
6387
  );
6388
+ }
3594
6389
  return s;
3595
6390
  }
3596
6391
  // A property written with _ or spaces, a trailing colon, or in camel
@@ -3607,7 +6402,10 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
3607
6402
  run: [
3608
6403
  unset
3609
6404
  ? `${P} undo ${slug} ${meant}${onFlag}`
3610
- : `${P} set ${slug} ${meant} ${quoteCommandArgument(v || exampleOf(groupOfPropType(meant), meant))}${onFlag || ' --on card'}`,
6405
+ : // The scope typed, never a part nobody named: with no --on,
6406
+ // set's own answer for the property (its whole-theme dial or
6407
+ // token) is folded in when the line is vetted.
6408
+ `${P} set ${slug} ${meant} ${quoteCommandArgument(v || exampleOf(groupOfPropType(meant), meant))}${onFlag}`,
3611
6409
  ],
3612
6410
  },
3613
6411
  );
@@ -3638,13 +6436,18 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
3638
6436
  // A hint names this theme and the part (card when none is given),
3639
6437
  // and a corners value corners takes.
3640
6438
  run: hint
3641
- ? hint(
3642
- /corners/.test(String(hint('', '')))
3643
- ? CORNERS.some(([n]) => n === v) || /^\d+(\.\d+)?px$/.test(v)
3644
- ? v
3645
- : ''
3646
- : v,
3647
- s.on,
6439
+ ? (/corners/.test(String(hint('', ''))) &&
6440
+ v.trim() &&
6441
+ !YES_NO.test(v.trim()) &&
6442
+ cornersRead(v) == null
6443
+ ? // A value corners cannot read: how corners, never a stock rung.
6444
+ [`${HOW} corners`]
6445
+ : hint(
6446
+ /corners/.test(String(hint('', ''))) && !YES_NO.test(v.trim())
6447
+ ? (cornersRead(v) ?? '')
6448
+ : v,
6449
+ s.on,
6450
+ )
3648
6451
  ).map(x =>
3649
6452
  x
3650
6453
  .replace(/<theme>/g, slug)
@@ -3660,6 +6463,32 @@ function checkOne(ctx, slug, data, thing, value, flags, unset) {
3660
6463
  );
3661
6464
  }
3662
6465
 
6466
+ /**
6467
+ * Refuse the corners dial on parts that are all radios' circles
6468
+ * (radioCircle): the dial leaves them, so it changes nothing you see. A
6469
+ * border-radius set on the part itself still changes it.
6470
+ * @param {import('./_settings.mjs').Ctx} ctx
6471
+ * @param {string} slug
6472
+ * @param {import('./_settings.mjs').Setting} s
6473
+ */
6474
+ function refuseRadioCorners(ctx, slug, s) {
6475
+ if (ctx.unchecked) return;
6476
+ const parts = partsOf(ctx, s);
6477
+ if (!parts.length || !parts.every(t => radioCircle(ctx.C, t))) return;
6478
+ // A radius set on the part itself overrides the circle: a square radio
6479
+ // is asked of this component, by name.
6480
+ const px = cornerPxOf(String(s.value));
6481
+ const own =
6482
+ Number.isFinite(px) && px < 9999
6483
+ ? setLine(slug, 'border-radius', px === 0 ? '0' : `${px}px`, s)
6484
+ : null;
6485
+ refuse(
6486
+ E.ERR_THEME_NO_EFFECT,
6487
+ `${s.on} is a radio's circle (border-radius 50%), not a corner, so the corners dial leaves it and changes nothing you see.${own ? ` A border-radius on it sets its shape: ${own.replace(`${P} `, '')}.` : ''}`,
6488
+ {run: own ? [own] : [`${HOW} ${s.on}`]},
6489
+ );
6490
+ }
6491
+
3663
6492
  /**
3664
6493
  * Refuse rounding a part that shows no edge: no background, border, shadow
3665
6494
  * or radius of its own, so a radius on it changes nothing you see.
@@ -3672,6 +6501,13 @@ function refuseInvisibleCorners(ctx, slug, s, data) {
3672
6501
  if (ctx.unchecked) return;
3673
6502
  const parts = partsOf(ctx, s);
3674
6503
  if (!parts.length || parts.some(t => ctx.C.showsCorners(t))) return;
6504
+ // The corners dial on a part whose corners are drawn by parts of its own
6505
+ // inside it (a date-time input's date and time boxes) rounds those.
6506
+ if (
6507
+ s.thing === 'corners' &&
6508
+ parts.some(t => cornerParts(ctx, t).some(x => x !== t))
6509
+ )
6510
+ return;
3675
6511
  // An edge the theme gives the part itself shows its corners too.
3676
6512
  const edged = data.settings.some(
3677
6513
  x =>
@@ -3765,6 +6601,68 @@ export function normalValue(thing, value) {
3765
6601
  /** @see familySpaces in _settings.mjs, re-exported for the checks. */
3766
6602
  export {familySpaces};
3767
6603
 
6604
+ /**
6605
+ * The first design token a property's value reads through var() whose kind
6606
+ * the property does not take, or null: the value with the var() replaced by
6607
+ * a value of the token's kind (the example each kind's refusals give) is
6608
+ * one the property's grammar does not take, so the browser drops it.
6609
+ * @param {import('./_settings.mjs').Ctx} ctx
6610
+ * @param {string} prop the property, as CSS names it
6611
+ * @param {string} v
6612
+ * @returns {{token: string, kind: string, takes: string, message: string} | null}
6613
+ */
6614
+ function tokenKindMismatch(ctx, prop, v) {
6615
+ for (const m of v.matchAll(/var\(\s*(--[a-z0-9-]+)\s*(?:,[^()]*)?\)/gi)) {
6616
+ const token = m[1];
6617
+ if (!ctx.C.isToken(token)) continue;
6618
+ const kind = ctx.C.typeOf(token);
6619
+ if (kind === 'other') continue;
6620
+ const sample = v.replace(m[0], exampleOf(kind, token));
6621
+ if (matchValue(prop, sample)) continue;
6622
+ const takes =
6623
+ matchValue(prop, '1px') && !matchValue(prop, 'red')
6624
+ ? 'a length'
6625
+ : matchValue(prop, 'red') && !matchValue(prop, '1px')
6626
+ ? 'a color'
6627
+ : null;
6628
+ return {
6629
+ token,
6630
+ kind,
6631
+ takes: takes ?? `no ${kind}`,
6632
+ message: takes
6633
+ ? `${prop} takes ${takes}; ${token} is a ${kind}, so the browser would drop it`
6634
+ : `${prop} takes no ${kind}; ${token} is a ${kind}, so the browser would drop it`,
6635
+ };
6636
+ }
6637
+ return null;
6638
+ }
6639
+
6640
+ /**
6641
+ * Why a part's CSS property value is refused, as `set` refuses it, or
6642
+ * null: a var() that reads nothing, a color property's value that is no
6643
+ * color, or a value the property's grammar does not take.
6644
+ * @param {import('./_settings.mjs').Ctx} ctx
6645
+ * @param {string} prop the property, as CSS names it
6646
+ * @param {string} value
6647
+ * @param {Record<string, unknown>} TOKENS
6648
+ * @param {ReadonlySet<string>} [reads] custom properties the theme sets where the value is read
6649
+ * @returns {string | null}
6650
+ */
6651
+ export function propertyValueProblem(ctx, prop, value, TOKENS, reads) {
6652
+ const v = value.trim();
6653
+ const ref = unknownVarRef(v, TOKENS, prop, reads);
6654
+ if (ref) return ref.message;
6655
+ const mismatch = tokenKindMismatch(ctx, prop, v);
6656
+ if (mismatch) return mismatch.message;
6657
+ if (CSS_WIDE.includes(v.toLowerCase())) return null;
6658
+ if (COLOR_PROPS.test(prop))
6659
+ return /\bvar\(/i.test(v) || isColorValue(v)
6660
+ ? null
6661
+ : `${prop} takes a color; "${v}" is not one.`;
6662
+ const grammar = propertyProblem(prop, v);
6663
+ return grammar ? `${prop} takes ${grammar.takes}; "${v}" is not one.` : null;
6664
+ }
6665
+
3768
6666
  /**
3769
6667
  * The first var() in a value that names no design token and would read
3770
6668
  * nothing (no fallback), or one a letter or two off a token, else null.
@@ -3772,9 +6670,11 @@ export {familySpaces};
3772
6670
  * @param {string} v
3773
6671
  * @param {Record<string, unknown>} TOKENS
3774
6672
  * @param {string} thing
6673
+ * @param {ReadonlySet<string>} [reads] custom properties the theme itself
6674
+ * sets where the value is read: a var() naming one reads it
3775
6675
  * @returns {{message: string, near: string[], close: boolean, fixed?: string} | null}
3776
6676
  */
3777
- export function unknownVarRef(v, TOKENS, thing) {
6677
+ export function unknownVarRef(v, TOKENS, thing, reads) {
3778
6678
  // A var() whose name is not a custom property (`var(color-x)`, `var(-x)`,
3779
6679
  // `var()`, `var(--)`) makes the whole value invalid: the browser drops
3780
6680
  // it. Named with the repaired form when there is one.
@@ -3793,12 +6693,12 @@ export function unknownVarRef(v, TOKENS, thing) {
3793
6693
  };
3794
6694
  }
3795
6695
  for (const [, name, comma] of v.matchAll(/var\(\s*(--[a-z0-9-]+)\s*(,)?/gi)) {
3796
- if (name in TOKENS || name.startsWith('--_')) continue;
6696
+ if (name in TOKENS || name.startsWith('--_') || reads?.has(name)) continue;
3797
6697
  // A fallback always gives a value: never "reads nothing" (a likely
3798
6698
  // typo is noted when the setting is made).
3799
6699
  if (comma) continue;
3800
- const near = nearest(name, Object.keys(TOKENS)).filter(
3801
- n => levenshteinDistance(n, name) <= 2,
6700
+ const near = nearest(name, Object.keys(TOKENS)).filter(n =>
6701
+ typoNear(name, n),
3802
6702
  );
3803
6703
  if (near.length)
3804
6704
  return {
@@ -3827,20 +6727,21 @@ export function unknownVarRef(v, TOKENS, thing) {
3827
6727
  * @returns {string | null}
3828
6728
  */
3829
6729
  export function fontFileReason(value) {
3830
- const hit = String(value)
3831
- .split(',')
3832
- .map(f => f.trim().replace(/^["']|["']$/g, ''))
3833
- .find(
3834
- f =>
3835
- /^url\(/i.test(f) ||
3836
- /:\/\//.test(f) ||
3837
- /[\\/]/.test(f) ||
3838
- /\.(woff2?|ttf|otf|eot)$/i.test(f),
3839
- );
3840
- const colon = String(value)
3841
- .split(',')
3842
- .map(f => f.trim().replace(/^["']|["']$/g, ''))
3843
- .find(f => f.includes(':'));
6730
+ // Each family as CSS reads it: an escape (`Gill\ Sans`, `\5FAE`) is part
6731
+ // of the name, never a path separator.
6732
+ // The families as the one family-list reader splits them (a quoted name
6733
+ // with a comma is one family).
6734
+ const families = (familiesOf(value) ?? String(value).split(',')).map(f =>
6735
+ cssUnescape(f.trim().replace(/^["']|["']$/g, '')),
6736
+ );
6737
+ const hit = families.find(
6738
+ f =>
6739
+ /^url\(/i.test(f) ||
6740
+ /:\/\//.test(f) ||
6741
+ /[\\/]/.test(f) ||
6742
+ /\.(woff2?|ttf|otf|eot)$/i.test(f),
6743
+ );
6744
+ const colon = families.find(f => f.includes(':'));
3844
6745
  if (!hit && colon)
3845
6746
  return `"${colon}" holds a colon, so it is a pasted declaration or a link, not a font family name. Give the family alone, such as Inter, sans-serif.`;
3846
6747
  return hit
@@ -3849,78 +6750,38 @@ export function fontFileReason(value) {
3849
6750
  }
3850
6751
 
3851
6752
  /**
3852
- * A value with every Unicode space (no-break, thin, ideographic…) as a plain
3853
- * space and zero-width and format characters dropped, for every value type:
3854
- * the browser reads only a plain space as one.
3855
- * @param {string} v
6753
+ * A word as a suggested command quotes it, without the quotes.
6754
+ * @param {string} word
3856
6755
  */
3857
- export function normalValueText(v) {
3858
- // Curly quotes (a word processor's, a phone's) are the straight ones CSS
3859
- // reads.
3860
- const straight = v
3861
- .replace(/[\u2018\u2019\u201A\u201B]/g, "'")
3862
- .replace(/[\u201C\u201D\u201E\u201F]/g, '"');
3863
- // A quoted CSS string (`content: "a\u00A0b"`) keeps what is inside it.
3864
- return straight
3865
- .split(/("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/)
3866
- .map((part, i) =>
3867
- i % 2
3868
- ? part
3869
- : part
3870
- .replace(/[\u200B-\u200D\u2060\uFEFF]/g, '')
3871
- .replace(/[\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]/g, ' '),
3872
- )
3873
- .join('');
6756
+ function unquoteArg(word) {
6757
+ const m = /^'(.*)'$/s.exec(word.trim());
6758
+ return m ? m[1].replace(/'\\''/g, "'") : word.trim();
3874
6759
  }
3875
6760
 
6761
+ /** Core's stylesheet text, by project folder. @type {Map<string, string>} */
6762
+ const coreStyles = new Map();
6763
+
3876
6764
  /**
3877
- * The thing and value a setting was typed as, put right before any check: a
3878
- * declaration pasted whole or split (`accent: #e11d48`, `--color-accent=red`,
3879
- * `font:inter`, `accent:` with the value next), a token typed with an em or
3880
- * en dash (`—color-accent`) or as `var(--color-accent)`, and the value's
3881
- * Unicode spaces. A thing it cannot read is left as typed.
3882
- * @param {string} thing
3883
- * @param {string | undefined} value
3884
- * @returns {{thing: string, value: string | undefined}}
3885
- */
3886
- export function normalizeEntry(thing, value) {
3887
- let t = normalValueText(String(thing ?? '')).trim();
3888
- let v = value == null ? value : normalValueText(String(value));
3889
- // A pasted declaration (the whole of it in the thing, or the thing with
3890
- // its colon and the value next): its `;` and `!important` go with it.
3891
- let pasted = false;
3892
- if (v == null || v.trim() === '') {
3893
- const m = /^(\S+?)\s*[:=]\s*(.+?)\s*;?\s*$/.exec(t);
3894
- if (m && !/^https?$/i.test(m[1])) {
3895
- t = m[1];
3896
- v = m[2];
3897
- pasted = true;
6765
+ * Whether Core's own stylesheet reads a token anywhere (a part the editor
6766
+ * does not render, such as the app shell behind the page, included).
6767
+ * @param {any} ctx
6768
+ * @param {string} token
6769
+ */
6770
+ function coreStylesRead(ctx, token) {
6771
+ const cwd = String(ctx?.project?.cwd ?? '');
6772
+ let css = coreStyles.get(cwd);
6773
+ if (css == null) {
6774
+ try {
6775
+ css = fs.readFileSync(
6776
+ ctx.project.req.resolve('@astryxdesign/core/astryx.css'),
6777
+ 'utf8',
6778
+ );
6779
+ } catch {
6780
+ css = '';
3898
6781
  }
6782
+ coreStyles.set(cwd, css);
3899
6783
  }
3900
- // A thing ending in its colon or equals sign, the value given next.
3901
- if (/\s*[:=]+$/.test(t)) {
3902
- t = t.replace(/\s*[:=]+$/, '');
3903
- pasted = true;
3904
- }
3905
- // Dash-like characters where a token's two dashes go (an em or en dash,
3906
- // a non-breaking hyphen, a minus sign, a full-width hyphen, alone or
3907
- // mixed with hyphens): `--`.
3908
- t = t.replace(/^[-\u2010-\u2015\u2212\uFE58\uFE63\uFF0D]+/, run =>
3909
- /[^-]/.test(run) ? '--' : run,
6784
+ return new RegExp(`var\\(\\s*${token.replace(/[-]/g, '\\-')}\\s*[,)]`).test(
6785
+ css,
3910
6786
  );
3911
- // A token typed as a var() reference.
3912
- const ref = /^var\(\s*(--[a-z0-9-]+)\s*\)$/i.exec(t);
3913
- if (ref) t = ref[1];
3914
- if (pasted && typeof v === 'string')
3915
- v = v.replace(/\s*!\s*important\s*;?\s*$/i, '').replace(/;+\s*$/, '');
3916
- return {thing: t, value: v};
3917
- }
3918
-
3919
- /**
3920
- * A word as a suggested command quotes it, without the quotes.
3921
- * @param {string} word
3922
- */
3923
- function unquoteArg(word) {
3924
- const m = /^'(.*)'$/s.exec(word.trim());
3925
- return m ? m[1].replace(/'\\''/g, "'") : word.trim();
3926
6787
  }