@astryxdesign/cli 0.7.18-canary.gfca8508 → 0.7.18

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 (341) hide show
  1. package/CHANGELOG.md +185 -19
  2. package/README.md +19 -19
  3. package/api/component/_adapter.d.mts +2 -1
  4. package/api/component/_adapter.mjs +2 -1
  5. package/api/docs/_adapter.d.mts +6 -5
  6. package/api/docs/_adapter.mjs +36 -5
  7. package/api/doctor/_adapter.d.mts +6 -3
  8. package/api/doctor/_adapter.mjs +13 -5
  9. package/api/doctor/doctor.mjs +2 -2
  10. package/api/doctor/font-packages.d.mts +36 -0
  11. package/api/doctor/font-packages.mjs +124 -0
  12. package/api/doctor/theme-checks.mjs +110 -49
  13. package/api/experimental.d.mts +0 -2
  14. package/api/experimental.mjs +0 -12
  15. package/api/icon/_adapter.d.mts +1 -1
  16. package/api/icon/_adapter.mjs +1 -0
  17. package/api/icon/_authoring.mjs +17 -8
  18. package/api/icon/_default-look.mjs +15 -15
  19. package/api/icon/add/add.mjs +9 -4
  20. package/api/icon/exportIconIndex.doc.mjs +1 -1
  21. package/api/icon/icon.doc.mjs +1 -1
  22. package/api/icon/icon.type.d.mts +33 -33
  23. package/api/icon/icon.type.mjs +45 -45
  24. package/api/icon/iconAdd.doc.mjs +1 -1
  25. package/api/icon/iconNewSet.doc.mjs +3 -3
  26. package/api/icon/iconUse.doc.mjs +5 -5
  27. package/api/icon/rankIconIndex.doc.mjs +1 -1
  28. package/api/icon/use/use.mjs +4 -4
  29. package/api/init/run/run.mjs +0 -1
  30. package/api/integration/add-helpers.mjs +1 -1
  31. package/api/render/_adapter.mjs +7 -1
  32. package/api/search/ORDERING.md +1 -1
  33. package/api/search/_candidate-score.mjs +20 -0
  34. package/api/search/_words.d.mts +8 -0
  35. package/api/search/_words.mjs +15 -0
  36. package/api/template/template.type.d.mts +2 -2
  37. package/api/template/template.type.mjs +2 -2
  38. package/api/theme/_adapter.mjs +19 -11
  39. package/api/theme/build/build.d.mts +19 -51
  40. package/api/theme/build/build.mjs +195 -189
  41. package/api/theme/build/font-warning.d.mts +19 -2
  42. package/api/theme/build/font-warning.mjs +46 -5
  43. package/api/theme/generateTonalPalette.doc.mjs +1 -1
  44. package/api/theme/palette/generate/derive-look.mjs +108 -37
  45. package/api/theme/palette/generate/mapping.mjs +2 -0
  46. package/api/theme/template/template.d.mts +0 -17
  47. package/api/theme/template/template.mjs +1 -42
  48. package/api/theme/theme.type.d.mts +5 -4
  49. package/api/theme/theme.type.mjs +5 -4
  50. package/api/theme/themePaletteGenerate.doc.mjs +1 -1
  51. package/api/theme/themeRemove.doc.mjs +1 -1
  52. package/assets/codemods/transforms/v0.7.0/preserve-bottom-sheet-content-padding.mjs +3 -1
  53. package/assets/component-list.generated.json +1 -1
  54. package/assets/discover/official-packages.json +26 -2
  55. package/assets/docs/author-a-theme.doc.mjs +6 -5
  56. package/assets/docs/browser-support.doc.mjs +1 -0
  57. package/assets/docs/icons.doc.mjs +8 -7
  58. package/assets/docs/motion.doc.mjs +46 -0
  59. package/assets/docs/theme.doc.dense.mjs +6 -17
  60. package/assets/docs/theme.doc.mjs +6 -16
  61. package/assets/docs/theme.doc.zh.mjs +6 -16
  62. package/assets/docs/tree/ci-and-containers.doc.mjs +1 -1
  63. package/assets/docs/tree/font-setup.doc.mjs +30 -0
  64. package/assets/docs/tree/icon-sets.doc.mjs +1 -1
  65. package/assets/docs/tree/template-icons.doc.mjs +3 -3
  66. package/assets/docs/tree/tokens-color.doc.mjs +5 -0
  67. package/assets/docs/tree/tokens.doc.mjs +4 -3
  68. package/assets/docs/tree/updates.doc.mjs +1 -1
  69. package/assets/docs-routes.generated.json +1 -1
  70. package/assets/docs.generated.json +2 -2
  71. package/assets/icons/definitions/drag.doc.mjs +1 -0
  72. package/assets/search-catalog.generated.json +2 -2
  73. package/assets/self-audit.generated.json +1 -1
  74. package/assets/templates/blocks/components/Card/SelectableCardElevated.doc.mjs +1 -1
  75. package/assets/templates/blocks/components/Card/SelectableCardElevated.tsx +20 -10
  76. package/assets/templates/blocks/components/Card/SelectableCardShowcase.doc.mjs +1 -1
  77. package/assets/templates/blocks/components/Card/SelectableCardShowcase.tsx +36 -16
  78. package/assets/templates/blocks/components/ChatComposerInput/ChatComposerInputMentionTrigger.tsx +6 -0
  79. package/assets/templates/blocks/components/ChatComposerInput/ChatComposerInputMultipleTriggers.tsx +6 -0
  80. package/assets/templates/blocks/components/Hooks/useIndicatorFocusRingHookUsage.doc.mjs +14 -0
  81. package/assets/templates/blocks/components/Hooks/useIndicatorFocusRingHookUsage.tsx +63 -0
  82. package/assets/templates/blocks/components/Hooks/useLongPressHookUsage.doc.mjs +29 -0
  83. package/assets/templates/blocks/components/Hooks/useLongPressHookUsage.tsx +237 -0
  84. package/assets/templates/blocks/components/SideNav/SideNavShowcase.tsx +10 -72
  85. package/assets/templates/blocks/components/SideNav/SideNavWithHeaderMenu.doc.mjs +1 -1
  86. package/assets/templates/blocks/components/SideNav/SideNavWithHeaderMenu.tsx +7 -7
  87. package/assets/templates/blocks/components/Table/TableCustomRowTable.doc.mjs +14 -0
  88. package/assets/templates/blocks/components/Table/TableCustomRowTable.tsx +96 -0
  89. package/assets/templates/components.generated.json +1 -1
  90. package/assets/templates/pages/ai-chat-landing/page.tsx +4 -0
  91. package/assets/templates/pages/dashboard-scorecard/page.tsx +26 -7
  92. package/assets/templates/pages/editor/page.tsx +13 -3
  93. package/assets/templates/themes/butter/butterPaletteRefs.generated.ts +2 -2
  94. package/assets/templates/themes/butter/butterTheme.ts +12 -10
  95. package/assets/templates/themes/butter/icons.tsx +2 -0
  96. package/assets/templates/themes/chocolate/chocolateTheme.ts +1 -0
  97. package/assets/templates/themes/chocolate/icons.tsx +2 -0
  98. package/assets/templates/themes/gothic/gothicPaletteRefs.generated.ts +1 -1
  99. package/assets/templates/themes/gothic/gothicTheme.ts +1 -0
  100. package/assets/templates/themes/gothic/icons.tsx +2 -0
  101. package/assets/templates/themes/matcha/icons.tsx +2 -0
  102. package/assets/templates/themes/matcha/matchaPaletteRefs.generated.ts +2 -2
  103. package/assets/templates/themes/matcha/matchaTheme.ts +1 -0
  104. package/assets/templates/themes/neutral/icons.tsx +2 -0
  105. package/assets/templates/themes/neutral/neutralPaletteRefs.generated.ts +2 -2
  106. package/assets/templates/themes/neutral/neutralTheme.ts +1 -0
  107. package/assets/templates/themes/stone/icons.tsx +2 -0
  108. package/assets/templates/themes/stone/stonePaletteRefs.generated.ts +1 -1
  109. package/assets/templates/themes/stone/stoneTheme.ts +1 -0
  110. package/assets/templates/themes/y2k/icons.tsx +2 -0
  111. package/assets/templates/themes/y2k/y2kTheme.ts +1 -0
  112. package/assets/theme.template.ts +9 -5
  113. package/authoring/config/parse.mjs +1 -1
  114. package/authoring/doctypes/base/type.ts +2 -3
  115. package/authoring/doctypes/component/component.doc.mjs +1 -1
  116. package/authoring/doctypes/icon-set/icon-names.mjs +1 -0
  117. package/authoring/integration/integration.doc.mjs +1 -1
  118. package/authoring/integration/type.ts +1 -1
  119. package/clients/cli/build-id.generated.json +1 -1
  120. package/clients/cli/commands/experimental/icon.mjs +7 -7
  121. package/clients/cli/commands/experimental/index.mjs +0 -5
  122. package/clients/cli/commands/experimental-icon-new-set.doc.mjs +2 -2
  123. package/clients/cli/commands/experimental-icon-use.doc.mjs +4 -4
  124. package/clients/cli/commands/experimental-icon.doc.mjs +1 -1
  125. package/clients/cli/commands/experimental.doc.mjs +2 -6
  126. package/clients/cli/commands/template.mjs +1 -1
  127. package/clients/cli/commands/theme-build.doc.mjs +8 -1
  128. package/clients/cli/commands/theme-palette-generate.doc.mjs +1 -1
  129. package/clients/cli/commands/theme-remove.doc.mjs +1 -1
  130. package/clients/cli/commands/theme.doc.mjs +1 -11
  131. package/clients/cli/commands/theme.mjs +110 -475
  132. package/clients/cli/commands.generated.json +1 -1
  133. package/clients/cli/index.mjs +4 -34
  134. package/clients/cli/lib/base-gate.mjs +2 -3
  135. package/clients/cli/lib/cli-error.mjs +8 -72
  136. package/clients/cli/lib/define-command.mjs +0 -19
  137. package/clients/cli/lib/json-shim.mjs +11 -633
  138. package/clients/cli/lib/manifest.mjs +0 -4
  139. package/clients/cli/lib/stray-option.mjs +1 -2
  140. package/clients/cli/manifest.generated.json +1 -1
  141. package/foundation/agent-docs/agent-docs.mjs +1 -1
  142. package/foundation/color/css-color.mjs +2 -3
  143. package/foundation/discovery/app-layout.d.mts +13 -0
  144. package/foundation/discovery/app-layout.mjs +35 -0
  145. package/foundation/discovery/fixture-refs.d.mts +51 -0
  146. package/foundation/discovery/fixture-refs.mjs +351 -0
  147. package/foundation/discovery/icon-definition-discovery.mjs +1 -1
  148. package/foundation/discovery/icon-ranking.mjs +2 -2
  149. package/foundation/discovery/icon-set-checks.mjs +1 -1
  150. package/foundation/discovery/icon-set-discovery.mjs +1 -1
  151. package/foundation/discovery/icon-set-writer.d.mts +24 -7
  152. package/foundation/discovery/icon-set-writer.mjs +66 -22
  153. package/foundation/discovery/static-descriptor.d.mts +49 -0
  154. package/foundation/discovery/static-descriptor.mjs +548 -0
  155. package/foundation/discovery/template-adapter.d.mts +0 -47
  156. package/foundation/discovery/template-adapter.mjs +1 -333
  157. package/foundation/discovery/theme-discovery.d.mts +6 -47
  158. package/foundation/discovery/theme-discovery.mjs +15 -537
  159. package/foundation/doc-compiler/import.mjs +1 -1
  160. package/foundation/env/user-dirs.d.mts +5 -2
  161. package/foundation/env/user-dirs.mjs +12 -5
  162. package/foundation/fonts/next-font.d.mts +26 -0
  163. package/foundation/fonts/next-font.mjs +149 -0
  164. package/foundation/fs/empty-folder.mjs +2 -2
  165. package/foundation/fs/read-record.mjs +11 -4
  166. package/foundation/pictures/pictures.d.mts +1 -45
  167. package/foundation/pictures/pictures.mjs +8 -8
  168. package/foundation/release/folder-lock.mjs +3 -2
  169. package/foundation/render/cut-short.d.mts +2 -2
  170. package/foundation/render/cut-short.mjs +2 -2
  171. package/foundation/render/drawn-contrast.d.mts +2 -2
  172. package/foundation/render/drawn-contrast.mjs +2 -2
  173. package/foundation/render/font-probe.d.mts +2 -2
  174. package/foundation/render/font-probe.mjs +2 -2
  175. package/foundation/render/layers.mjs +1 -2
  176. package/foundation/render/package-resolve-hooks.d.mts +25 -5
  177. package/foundation/render/package-resolve-hooks.mjs +77 -14
  178. package/foundation/render/page-worker.mjs +24 -12
  179. package/foundation/render/part-boxes.d.mts +2 -3
  180. package/foundation/render/part-boxes.mjs +2 -3
  181. package/foundation/render/picture-chrome.mjs +5 -0
  182. package/foundation/render/render-page.d.mts +1 -1
  183. package/foundation/render/render-page.mjs +4 -5
  184. package/foundation/render/single-copy-hooks.d.mts +2 -0
  185. package/foundation/render/single-copy-hooks.mjs +2 -0
  186. package/foundation/response/error-codes.doc.mjs +14 -14
  187. package/foundation/response/error-codes.mjs +13 -13
  188. package/foundation/response/response-types.doc.mjs +7 -68
  189. package/foundation/runtime/css-tree.mjs +2 -2
  190. package/foundation/runtime/word-table.d.mts +1 -1
  191. package/foundation/runtime/word-table.mjs +1 -1
  192. package/foundation/suggest/other-command.d.mts +52 -15
  193. package/foundation/suggest/other-command.mjs +168 -45
  194. package/foundation/text/suggest-order.d.mts +7 -0
  195. package/foundation/text/suggest-order.mjs +1 -1
  196. package/package.json +7 -8
  197. package/api/theme-edit/_adapter.d.mts +0 -228
  198. package/api/theme-edit/_adapter.mjs +0 -2025
  199. package/api/theme-edit/_catalog.d.mts +0 -172
  200. package/api/theme-edit/_catalog.mjs +0 -806
  201. package/api/theme-edit/_check.d.mts +0 -391
  202. package/api/theme-edit/_check.mjs +0 -9370
  203. package/api/theme-edit/_color.d.mts +0 -135
  204. package/api/theme-edit/_color.mjs +0 -480
  205. package/api/theme-edit/_compiler.d.mts +0 -77
  206. package/api/theme-edit/_compiler.mjs +0 -1053
  207. package/api/theme-edit/_context.d.mts +0 -399
  208. package/api/theme-edit/_context.mjs +0 -1778
  209. package/api/theme-edit/_css.d.mts +0 -169
  210. package/api/theme-edit/_css.mjs +0 -1167
  211. package/api/theme-edit/_edit.d.mts +0 -167
  212. package/api/theme-edit/_edit.mjs +0 -11220
  213. package/api/theme-edit/_how-commands.d.mts +0 -315
  214. package/api/theme-edit/_how-commands.mjs +0 -1664
  215. package/api/theme-edit/_how-question.d.mts +0 -341
  216. package/api/theme-edit/_how-question.mjs +0 -33339
  217. package/api/theme-edit/_how-sides.d.mts +0 -22
  218. package/api/theme-edit/_how-sides.mjs +0 -173
  219. package/api/theme-edit/_how-steps.d.mts +0 -42
  220. package/api/theme-edit/_how-steps.mjs +0 -208
  221. package/api/theme-edit/_how-values.d.mts +0 -29
  222. package/api/theme-edit/_how-values.mjs +0 -111
  223. package/api/theme-edit/_how-words.d.mts +0 -15
  224. package/api/theme-edit/_how-words.mjs +0 -239
  225. package/api/theme-edit/_how.d.mts +0 -55
  226. package/api/theme-edit/_how.mjs +0 -2388
  227. package/api/theme-edit/_importers.d.mts +0 -38
  228. package/api/theme-edit/_importers.mjs +0 -188
  229. package/api/theme-edit/_marks.d.mts +0 -39
  230. package/api/theme-edit/_marks.mjs +0 -67
  231. package/api/theme-edit/_missed.d.mts +0 -56
  232. package/api/theme-edit/_missed.mjs +0 -1128
  233. package/api/theme-edit/_name-rule.d.mts +0 -11
  234. package/api/theme-edit/_name-rule.mjs +0 -12
  235. package/api/theme-edit/_normal.d.mts +0 -365
  236. package/api/theme-edit/_normal.mjs +0 -1978
  237. package/api/theme-edit/_overview.d.mts +0 -9
  238. package/api/theme-edit/_overview.mjs +0 -293
  239. package/api/theme-edit/_palette.d.mts +0 -616
  240. package/api/theme-edit/_palette.mjs +0 -2776
  241. package/api/theme-edit/_part-pieces.d.mts +0 -54
  242. package/api/theme-edit/_part-pieces.mjs +0 -179
  243. package/api/theme-edit/_part-words.d.mts +0 -39
  244. package/api/theme-edit/_part-words.mjs +0 -242
  245. package/api/theme-edit/_parts.d.mts +0 -402
  246. package/api/theme-edit/_parts.mjs +0 -2322
  247. package/api/theme-edit/_picture-traits.d.mts +0 -259
  248. package/api/theme-edit/_picture-traits.mjs +0 -1030
  249. package/api/theme-edit/_png.d.mts +0 -94
  250. package/api/theme-edit/_png.mjs +0 -479
  251. package/api/theme-edit/_preview-app.d.mts +0 -172
  252. package/api/theme-edit/_preview-app.mjs +0 -6430
  253. package/api/theme-edit/_preview.d.mts +0 -484
  254. package/api/theme-edit/_preview.mjs +0 -2775
  255. package/api/theme-edit/_project.d.mts +0 -207
  256. package/api/theme-edit/_project.mjs +0 -643
  257. package/api/theme-edit/_resolved.d.mts +0 -46
  258. package/api/theme-edit/_resolved.mjs +0 -800
  259. package/api/theme-edit/_set-line.d.mts +0 -29
  260. package/api/theme-edit/_set-line.mjs +0 -100
  261. package/api/theme-edit/_settings.d.mts +0 -2426
  262. package/api/theme-edit/_settings.mjs +0 -18449
  263. package/api/theme-edit/_tables.d.mts +0 -227
  264. package/api/theme-edit/_tables.mjs +0 -1128
  265. package/api/theme-edit/_text-looks.d.mts +0 -78
  266. package/api/theme-edit/_text-looks.mjs +0 -376
  267. package/api/theme-edit/_vet.d.mts +0 -50
  268. package/api/theme-edit/_vet.mjs +0 -166
  269. package/api/theme-edit/how/how.d.mts +0 -17
  270. package/api/theme-edit/how/how.mjs +0 -28
  271. package/api/theme-edit/new/new.d.mts +0 -11
  272. package/api/theme-edit/new/new.mjs +0 -22
  273. package/api/theme-edit/preview-add/preview-add.d.mts +0 -14
  274. package/api/theme-edit/preview-add/preview-add.mjs +0 -25
  275. package/api/theme-edit/preview-app/preview-app.d.mts +0 -13
  276. package/api/theme-edit/preview-app/preview-app.mjs +0 -24
  277. package/api/theme-edit/preview-list/preview-list.d.mts +0 -10
  278. package/api/theme-edit/preview-list/preview-list.mjs +0 -21
  279. package/api/theme-edit/preview-remove/preview-remove.d.mts +0 -12
  280. package/api/theme-edit/preview-remove/preview-remove.mjs +0 -23
  281. package/api/theme-edit/set/set.d.mts +0 -13
  282. package/api/theme-edit/set/set.mjs +0 -24
  283. package/api/theme-edit/show/show.d.mts +0 -13
  284. package/api/theme-edit/show/show.mjs +0 -24
  285. package/api/theme-edit/theme-edit.d.mts +0 -12
  286. package/api/theme-edit/theme-edit.mjs +0 -36
  287. package/api/theme-edit/theme-edit.type.d.mts +0 -730
  288. package/api/theme-edit/theme-edit.type.mjs +0 -342
  289. package/api/theme-edit/themeEditHow.doc.d.mts +0 -6
  290. package/api/theme-edit/themeEditHow.doc.mjs +0 -105
  291. package/api/theme-edit/themeEditNew.doc.d.mts +0 -5
  292. package/api/theme-edit/themeEditNew.doc.mjs +0 -112
  293. package/api/theme-edit/themeEditPreviewAdd.doc.d.mts +0 -6
  294. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +0 -121
  295. package/api/theme-edit/themeEditPreviewApp.doc.d.mts +0 -6
  296. package/api/theme-edit/themeEditPreviewApp.doc.mjs +0 -87
  297. package/api/theme-edit/themeEditPreviewList.doc.d.mts +0 -6
  298. package/api/theme-edit/themeEditPreviewList.doc.mjs +0 -62
  299. package/api/theme-edit/themeEditPreviewRemove.doc.d.mts +0 -6
  300. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +0 -96
  301. package/api/theme-edit/themeEditSet.doc.d.mts +0 -6
  302. package/api/theme-edit/themeEditSet.doc.mjs +0 -175
  303. package/api/theme-edit/themeEditShow.doc.d.mts +0 -6
  304. package/api/theme-edit/themeEditShow.doc.mjs +0 -118
  305. package/api/theme-edit/themeEditUndo.doc.d.mts +0 -6
  306. package/api/theme-edit/themeEditUndo.doc.mjs +0 -133
  307. package/api/theme-edit/undo/undo.d.mts +0 -13
  308. package/api/theme-edit/undo/undo.mjs +0 -24
  309. package/assets/preview-app/README.md +0 -6
  310. package/assets/preview-app/css.d.ts +0 -5
  311. package/assets/preview-app/gitignore +0 -4
  312. package/assets/preview-app/next.config.mjs +0 -12
  313. package/assets/preview-app/package.json +0 -24
  314. package/assets/preview-app/src/app/globals.css +0 -6
  315. package/assets/preview-app/src/app/layout.tsx +0 -21
  316. package/assets/preview-app/src/app/page.tsx +0 -94
  317. package/assets/preview-app/src/app/providers.tsx +0 -16
  318. package/assets/preview-app/tsconfig.json +0 -27
  319. package/clients/cli/commands/experimental/theme.mjs +0 -2990
  320. package/clients/cli/commands/experimental-theme-add.doc.mjs +0 -80
  321. package/clients/cli/commands/experimental-theme-compile.doc.mjs +0 -98
  322. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +0 -196
  323. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +0 -174
  324. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +0 -139
  325. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +0 -77
  326. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +0 -105
  327. package/clients/cli/commands/experimental-theme-editor.doc.mjs +0 -49
  328. package/clients/cli/commands/experimental-theme-eject.doc.mjs +0 -72
  329. package/clients/cli/commands/experimental-theme-list.doc.mjs +0 -49
  330. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +0 -88
  331. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +0 -61
  332. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +0 -48
  333. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +0 -59
  334. package/clients/cli/commands/experimental-theme-preview.doc.mjs +0 -41
  335. package/clients/cli/commands/experimental-theme-remove.doc.mjs +0 -57
  336. package/clients/cli/commands/experimental-theme-targets.doc.mjs +0 -62
  337. package/clients/cli/commands/experimental-theme-template.doc.mjs +0 -63
  338. package/clients/cli/commands/experimental-theme-use.doc.mjs +0 -57
  339. package/clients/cli/commands/experimental-theme.doc.mjs +0 -60
  340. package/foundation/fonts/fontsource-families.generated.d.mts +0 -5
  341. package/foundation/fonts/fontsource-families.generated.mjs +0 -2110
@@ -1,1664 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
-
3
- /**
4
- * @file The commands `how` suggests: written for the user's theme, quoted so
5
- * a shell runs them as printed, and each one checked as `set` checks it and
6
- * compiled, so an answer names only commands that are accepted and change
7
- * the theme. Nothing is written.
8
- * @position api/theme-edit — imported by _how.mjs and _how-question.mjs
9
- */
10
-
11
- import {AstryxError} from '../error.mjs';
12
- import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
13
- import {
14
- BORDER_COLOR_PROP,
15
- borderFor,
16
- broughtBorderAt,
17
- checkSetting,
18
- indicatorLines,
19
- pillDrawnRadios,
20
- } from './_check.mjs';
21
- import {baseResolved} from './_project.mjs';
22
- import {readThemeListState} from '../theme/_adapter.mjs';
23
- import {
24
- compileTheme,
25
- editedThemes,
26
- keyOf,
27
- loadTheme,
28
- readHistory,
29
- themeFiles,
30
- groupsOf,
31
- } from './_settings.mjs';
32
- import {GROUPS, LIKE, P} from './_tables.mjs';
33
- import {hexToOklch} from '../theme/palette/generate/color.mjs';
34
- import {
35
- COLOR_IN_VALUE,
36
- alphaOf,
37
- colorsIn,
38
- parseColor,
39
- splitTop,
40
- } from './_color.mjs';
41
- import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
42
-
43
- /** The theme name commands use when the app has no theme yet. */
44
- export const EXAMPLE_THEME = 'my-theme';
45
-
46
- /**
47
- * One change a command makes.
48
- * @typedef {object} Step
49
- * @property {'set' | 'undo'} verb
50
- * @property {string} thing
51
- * @property {string} [value]
52
- * @property {string} [on]
53
- * @property {string} [when]
54
- * @property {string} [state]
55
- * @property {string} [mode]
56
- * @property {boolean} [only] the one member of a group, not the group
57
- * @property {boolean} [keeps] writes a look back as it shows it now (a
58
- * status Core draws its own way): an except of that look never leaves
59
- * it out, as it is what keeps the look
60
- */
61
-
62
- /**
63
- * The theme the commands of one answer are for, and the checks they pass.
64
- * @typedef {object} HowTheme
65
- * @property {string} slug
66
- * @property {boolean} exists - false when the app has no theme: the commands name {@link EXAMPLE_THEME} and the answer starts with `new`.
67
- * @property {string | null} previewDamage - why the in-app preview's record is damaged and how to fix it, or null.
68
- * @property {string[]} themes - Every theme the editor made in the app.
69
- * @property {string | null} note - Which theme the commands are for when the app has several, or that it has none.
70
- * @property {'named' | 'only' | 'last-changed' | 'none'} chosenBy - How the theme was picked.
71
- * @property {number} undoSteps - How many changes `undo` can step back.
72
- * @property {boolean} bodyFontReachesHeadings - Whether `font X --on body` also changes the heading font in this release.
73
- * @property {import('./_settings.mjs').ThemeData} data
74
- * @property {{light: Record<string, string>, dark: Record<string, string>, onDark?: Record<string, string>}} base - `onDark`: the tokens the base's dark media rule replaces
75
- * @property {{light: Record<string, string>, dark: Record<string, string>}} [own] - The theme's own values: the base's with its settings applied.
76
- * @property {(steps: Step[]) => {ok: true} | {ok: false, why: string, run?: string[]}} check
77
- * @property {(steps: Step[], part: string, prop: string) => {light: string, dark: string} | null} valueAfter what a part shows for a property at rest after the steps, in each mode, or null when it reads none
78
- * @property {(steps: Step[], intent: MeasureIntent) => string | null} measure the measured check: why the built result does not do what the question asks, or null
79
- */
80
-
81
- /**
82
- * The theme's own token values in each mode: the base theme's, with the
83
- * theme's settings applied (a whole-theme corners setting, an exact
84
- * token), as `compile` builds them.
85
- * A type scale the theme writes (the text-size and type dials write one)
86
- * is expanded the way Core expands it, so a heading size reads as the
87
- * scale draws it, not as the base theme's.
88
- * @param {any} compiled
89
- * @param {{light: Record<string, string>, dark: Record<string, string>}} base
90
- * @param {any} [core] the project's Core module, which expands the scale
91
- * @returns {{light: Record<string, string>, dark: Record<string, string>}}
92
- */
93
- export function ownTokens(compiled, base, core) {
94
- const out = {light: {...base.light}, dark: {...base.dark}};
95
- const scale = compiled?.typography?.scale;
96
- if (
97
- scale &&
98
- typeof scale.base === 'number' &&
99
- typeof scale.ratio === 'number' &&
100
- typeof core?.expandTypeScale === 'function'
101
- ) {
102
- try {
103
- const expanded = core.expandTypeScale({
104
- base: scale.base,
105
- ratio: scale.ratio,
106
- });
107
- for (const [k, v] of Object.entries(expanded ?? {}))
108
- if (typeof v === 'string' && /^--font-size-|^--text-.*-size$/.test(k)) {
109
- out.light[k] = v;
110
- out.dark[k] = v;
111
- }
112
- } catch {
113
- // (A Core that cannot expand the scale leaves the base sizes.)
114
- }
115
- }
116
- for (const [k, v] of Object.entries(compiled?.tokens ?? {})) {
117
- const pair = Array.isArray(v)
118
- ? v
119
- : v && typeof v === 'object'
120
- ? [/** @type {any} */ (v).light, /** @type {any} */ (v).dark]
121
- : [v, v];
122
- if (typeof pair[0] === 'string') out.light[k] = pair[0];
123
- if (typeof pair[1] === 'string') out.dark[k] = pair[1];
124
- }
125
- return out;
126
- }
127
-
128
- /**
129
- * The theme an answer's commands are for: the one named, the only one, or
130
- * the one changed last; with none, a theme the answer first makes.
131
- * @param {import('./_settings.mjs').Ctx} ctx
132
- * @param {string} cwd
133
- * @param {string | undefined} name
134
- * @returns {Promise<HowTheme>}
135
- */
136
- export async function howTheme(ctx, cwd, name) {
137
- const themes = editedThemes(cwd, 'changed');
138
- /** @type {import('./_settings.mjs').ThemeData | null} */
139
- let data = null;
140
- let slug = name ?? themes[0] ?? EXAMPLE_THEME;
141
- let note = null;
142
- if (name === '')
143
- throw new AstryxError(
144
- '--theme was given no name.',
145
- [{name: `${P} how --list kinds`, reason: 'or leave --theme out'}],
146
- ERROR_CODES.ERR_INVALID_ARGUMENT,
147
- );
148
- if (name) data = loadTheme(cwd, name);
149
- else if (themes.length) {
150
- try {
151
- data = loadTheme(cwd, slug);
152
- } catch (e) {
153
- if (!(e instanceof AstryxError)) throw e;
154
- note = `${slug} cannot be read (${e.message}); the commands are checked against a new theme instead`;
155
- }
156
- if (themes.length > 1 && !note)
157
- note = `the commands are for ${slug}, the theme changed last; --theme picks another of: ${themes.join(', ')}`;
158
- }
159
- // With no editor theme, the theme the app shows now (its default, read
160
- // as `theme add` and doctor read it) is what the answer starts from and
161
- // measures against, when it is a base the editor can start from.
162
- const appDefault = (() => {
163
- try {
164
- const d = readThemeListState(cwd).defaultSlug;
165
- return d && LIKE.includes(d) ? d : null;
166
- } catch {
167
- return null;
168
- }
169
- })();
170
- const startLike = appDefault ?? LIKE[0];
171
- if (!name && !themes.length)
172
- note = `the app has no theme yet; the commands are for a theme named ${EXAMPLE_THEME}, made first with: ${P} new ${EXAMPLE_THEME} --like ${startLike}${appDefault ? ` (${appDefault} is the theme the app shows now)` : ''}`;
173
- const exists = Boolean(data);
174
- if (!data) {
175
- if (!themes.length) slug = EXAMPLE_THEME;
176
- data = {name: slug, like: startLike, mode: 'both', settings: []};
177
- }
178
- const theme = /** @type {import('./_settings.mjs').ThemeData} */ (data);
179
- const base = await baseResolved(ctx.project, theme.like);
180
- const compiled = (/** @type {import('./_settings.mjs').ThemeData} */ d) =>
181
- JSON.stringify([d.mode, compileTheme(ctx, d, base)]);
182
- const before = compiled(theme);
183
- /** @type {any} */
184
- let beforeCache = null;
185
- const beforeCompiled = () => (beforeCache ??= compileTheme(ctx, theme, base));
186
- // Whether a body font setting also moves the heading font: Core gives
187
- // headings the body family when a theme names no heading family, so it is
188
- // read from Core, and stays right when that changes.
189
- const {core} = ctx.project;
190
- /** @param {any} typography */
191
- const headingOf = typography => {
192
- try {
193
- return core.resolveThemeTokens(
194
- core.defineTheme({
195
- name: 'how-probe',
196
- ...(typography ? {typography} : {}),
197
- }),
198
- {mode: 'light'},
199
- )['--font-family-heading'];
200
- } catch {
201
- return null;
202
- }
203
- };
204
- const fontless = {
205
- ...theme,
206
- settings: theme.settings.filter(
207
- x => x.thing !== 'font' || x.on === 'heading',
208
- ),
209
- };
210
- const withBody = compileTheme(
211
- ctx,
212
- {
213
- ...fontless,
214
- settings: [
215
- ...fontless.settings,
216
- {thing: 'font', value: 'courier', on: 'body', source: 'dial'},
217
- ],
218
- },
219
- base,
220
- ).typography;
221
- // The editor writes the base theme's heading font beside a body font of
222
- // its own; only a build that writes none leaves headings to Core.
223
- const bodyFontReachesHeadings =
224
- !withBody?.heading &&
225
- headingOf(compileTheme(ctx, fontless, base).typography) !==
226
- headingOf(withBody);
227
- // A damaged preview record refuses every preview command, so an answer
228
- // names its fix instead of a preview command.
229
- const {previewRecordProblem} = await import('./_preview-app.mjs');
230
- return {
231
- slug,
232
- exists,
233
- themes,
234
- note,
235
- previewDamage: previewRecordProblem(cwd),
236
- chosenBy: name
237
- ? 'named'
238
- : !themes.length
239
- ? 'none'
240
- : themes.length === 1
241
- ? 'only'
242
- : 'last-changed',
243
- data: theme,
244
- base,
245
- own: ownTokens(compileTheme(ctx, theme, base), base, ctx.project?.core),
246
- undoSteps: exists
247
- ? readHistory(themeFiles(cwd, slug).history).steps.length
248
- : 0,
249
- bodyFontReachesHeadings,
250
- /**
251
- * The measured check: build the theme with the steps in memory (the
252
- * same compile `set` builds from; nothing is written), resolve every
253
- * value the touched parts show at rest and in the named state or
254
- * variant, in light and dark, before and after, and hold them to what
255
- * the question asks. Returns why it does not fit, or null.
256
- * @param {Step[]} steps
257
- * @param {MeasureIntent} intent
258
- * @returns {string | null}
259
- */
260
- measure(steps, intent) {
261
- const d = JSON.parse(JSON.stringify(theme));
262
- const checkCtx = /** @type {any} */ ({...ctx, base});
263
- try {
264
- for (const st of steps) apply(checkCtx, slug, d, st);
265
- } catch {
266
- return null; // check() says why
267
- }
268
- const was = beforeCompiled();
269
- const now = compileTheme(ctx, d, base);
270
- // A one-mode theme shows only that mode: only it is measured.
271
- const visible =
272
- d.mode === 'light-only'
273
- ? 'light'
274
- : d.mode === 'dark-only'
275
- ? 'dark'
276
- : null;
277
- return measureFit(ctx, base, was, now, intent, steps, visible);
278
- },
279
- /**
280
- * What a part shows for a property at rest after the steps (built in
281
- * memory, nothing written): its own rule, else what Core declares at
282
- * rest, every var() written out from the part's tokens.
283
- * @param {Step[]} steps
284
- * @param {string} part
285
- * @param {string} prop
286
- */
287
- valueAfter(steps, part, prop) {
288
- const d = JSON.parse(JSON.stringify(theme));
289
- const checkCtx = /** @type {any} */ ({...ctx, base});
290
- try {
291
- for (const st of steps) apply(checkCtx, slug, d, st);
292
- } catch {
293
- return null;
294
- }
295
- const now = compileTheme(ctx, d, base);
296
- const toks = ownTokens(now, base, ctx.project?.core);
297
- const camel = prop.replace(/-([a-z])/g, (_m, x) => x.toUpperCase());
298
- /** @type {Record<string, any>} */
299
- const rules = {
300
- ...(base.components?.[part]?.base ?? {}),
301
- ...(now.components?.[part]?.base ?? {}),
302
- };
303
- const at = ctx.C.MAP?.[part]?.at?.[prop] ?? {};
304
- const rest =
305
- Object.entries(/** @type {Record<string, string>} */ (at)).find(
306
- ([k]) =>
307
- !/[\s:]/.test(k) &&
308
- k
309
- .split(',')
310
- .every(x =>
311
- /^(?:variant=(?:default|primary|standard)|size=md|elevation=none|always)$|^$/.test(
312
- x,
313
- ),
314
- ),
315
- )?.[1] ?? Object.values(at)[0];
316
- const raw = rules[camel] ?? rules[prop] ?? rest;
317
- if (raw == null) return null;
318
- /** @param {'light' | 'dark'} m */
319
- const scoped = m => {
320
- /** @type {Record<string, string>} */
321
- const t = {...toks[m]};
322
- for (const [k, v] of Object.entries(rules))
323
- if (k.startsWith('--') && typeof v === 'string') t[k] = v;
324
- return t;
325
- };
326
- // (A private variable Core sets nowhere at rest shows its fallback.)
327
- /** @param {'light' | 'dark'} m */
328
- const shown = m => {
329
- let v = String(raw);
330
- for (let i = 0; i < 4; i++)
331
- v = resolveIn(v, scoped(m), m).replace(
332
- /var\(\s*--_[\w-]+\s*,\s*((?:[^()]|\([^()]*\))*)\)/g,
333
- '$1',
334
- );
335
- return v.trim();
336
- };
337
- return {light: shown('light'), dark: shown('dark')};
338
- },
339
- check(steps) {
340
- /** @type {import('./_settings.mjs').ThemeData} */
341
- const d = JSON.parse(JSON.stringify(theme));
342
- // The checks set runs read the base theme's values (the corner rungs).
343
- const checkCtx = /** @type {any} */ ({...ctx, base});
344
- try {
345
- for (const st of steps) apply(checkCtx, slug, d, st);
346
- if (compiled(d) === before)
347
- return {
348
- ok: false,
349
- why: 'it changes nothing: the theme already looks that way',
350
- };
351
- return {ok: true};
352
- } catch (e) {
353
- if (e instanceof AstryxError) {
354
- // The command the refusal names to run instead, when it names
355
- // one ("set t text-size 18").
356
- const run = (e.suggestions ?? [])
357
- .filter(x => /^do this instead/.test(String(x.reason ?? '')))
358
- .map(x => String(x.name));
359
- return {
360
- ok: false,
361
- why: e.message.replace(/ Nothing was changed\.$/, ''),
362
- ...(run.length ? {run} : {}),
363
- };
364
- }
365
- throw e;
366
- }
367
- },
368
- };
369
- }
370
-
371
- /**
372
- * What the measured check holds a command to.
373
- * @typedef {object} MeasureIntent
374
- * @property {string[]} families the kinds of change asked for (color, radius, space, border, weight, opacity, shadow, fontsize); empty: any
375
- * @property {'more' | 'less' | null} dir the way a size moves
376
- * @property {boolean | null} lighter the way a color moves
377
- * @property {'more' | 'less' | null} opacityDir the way an opacity moves
378
- * @property {boolean} zero a removal: the changed values reach none or 0
379
- * @property {string[]} subjects the parts the question changes
380
- * @property {string[]} keep the parts it excepts, compares against or forbids changing
381
- * @property {string[]} typed values the question gives (taken as given)
382
- * @property {'light' | 'dark' | null} [mode] the mode the question names
383
- * @property {boolean} [bound] the question gives a bound ("smaller than 24px"): a space is checked against it too
384
- * @property {boolean} [contrast] the words ask about contrast ("too light to read"): text in dark mode moves the other way
385
- * @property {string[]} [than] parts the question compares against ("darker than the page"): a color moves past theirs
386
- * @property {string} [from] a theme color the way is taken from ("the accent color but lighter"): a color moves that way from it, not from the part's own
387
- * @property {'more' | 'less'} [saturation] the colors asked more or less saturated ("more colorful", "more muted")
388
- * @property {boolean} [literal] a mode is named with lighter or darker: borders and the shared text color move as written
389
- * @property {'more' | 'less' | null} [shadowDir] the way a shadow's strength moves ("darker shadows": more)
390
- * @property {boolean} [fainter] the question makes something fainter, less visible or more see-through ("less visible", "half as visible", "more transparent"): no border, outline, ring or shadow gets stronger anywhere
391
- */
392
-
393
- /** A camelCase property as CSS writes it. @param {string} k */
394
- const kebab = k => k.replace(/[A-Z]/g, m => `-${m.toLowerCase()}`);
395
-
396
- /**
397
- * Every value of a compiled part, by `when|state|prop`.
398
- * @param {any} comp the part's compiled styles
399
- * @returns {Map<string, string>}
400
- */
401
- export function partValues(comp) {
402
- /** @type {Map<string, string>} */
403
- const out = new Map();
404
- for (const [when, rules] of Object.entries(comp ?? {}))
405
- for (const [k, v] of Object.entries(/** @type {any} */ (rules) ?? {}))
406
- if (v && typeof v === 'object')
407
- for (const [k2, v2] of Object.entries(v))
408
- out.set(`${when}|${k}|${kebab(k2)}`, String(v2));
409
- else out.set(`${when}||${kebab(k)}`, String(v));
410
- // A plain color written as `background` paints the background color.
411
- for (const [k, v] of [...out])
412
- if (/\|background$/.test(k) && !/gradient|url\(/.test(v)) {
413
- const bc = k.replace(/background$/, 'background-color');
414
- if (!out.has(bc)) out.set(bc, v);
415
- }
416
- return out;
417
- }
418
-
419
- /**
420
- * A value with every var() written out from a mode's tokens, and
421
- * light-dark() taken for that mode.
422
- * @param {string} v
423
- * @param {Record<string, string>} map
424
- * @param {'light' | 'dark'} mode
425
- */
426
- export function resolveIn(v, map, mode) {
427
- let out = String(v ?? '');
428
- for (let i = 0; i < 8; i++) {
429
- const next = out
430
- // (A variable with no value here and no fallback stays as written:
431
- // a value read in part is no value, never the rest of it.)
432
- .replace(/var\(\s*(--[a-z0-9-]+)\s*(?:,\s*([^()]*))?\)/gi, (m, t, fb) =>
433
- String(map[t] ?? fb ?? m),
434
- )
435
- .replace(
436
- /light-dark\(\s*([^,()]+(?:\([^()]*\))?)\s*,\s*([^()]+(?:\([^()]*\))?)\s*\)/gi,
437
- (_, a, b) => (mode === 'light' ? a : b),
438
- );
439
- if (next === out) break;
440
- out = next;
441
- }
442
- return out.trim().toLowerCase();
443
- }
444
-
445
- /** The family of a CSS property or token, as the step check names them. @param {string} prop */
446
- function familyOf(prop) {
447
- if (/radius/.test(prop)) return 'radius';
448
- if (/^--shadow-|^box-shadow$/.test(prop)) return 'shadow';
449
- if (/^opacity$/.test(prop)) return 'opacity';
450
- if (/weight/.test(prop)) return 'weight';
451
- if (/^(font-size|--font-size-[a-z0-9]+|--text-[a-z0-9-]+-size)$/.test(prop))
452
- return 'fontsize';
453
- if (
454
- /^(border(-[a-z]+)?-width|border(-(top|bottom|left|right|block|inline))?$|--border-width|--focus-outline-width|outline-width)$/.test(
455
- prop,
456
- )
457
- )
458
- return 'border';
459
- if (/colou?r|^background(-image)?$|^fill$|^stroke$|^filter$/.test(prop))
460
- return 'color';
461
- if (
462
- /^(padding|gap|margin|min-height|height|width|max-width|min-width|--spacing-|--size-)/.test(
463
- prop,
464
- )
465
- )
466
- return 'space';
467
- return null;
468
- }
469
-
470
- /** A length as px (rem/em at 16), or a plain number, or null. @param {string} v */
471
- function measureNumber(v) {
472
- const m = /^(-?\d*\.?\d+)(px|rem|em)?$/.exec(
473
- String(v).trim().split(/\s+/)[0],
474
- );
475
- return m ? Number(m[1]) * (m[2] === 'rem' || m[2] === 'em' ? 16 : 1) : null;
476
- }
477
-
478
- /**
479
- * Whether a color steps for contrast in dark mode (a border; text when the
480
- * words ask about contrast): there "darker" asks for more contrast, so it
481
- * moves lighter, and "lighter" darker; a fill moves the same way in both
482
- * modes.
483
- * @param {string} name a token or a property
484
- * @param {boolean} [contrast] the words ask about contrast
485
- * @param {boolean} [literal] a mode is named with lighter or darker
486
- */
487
- const isForeground = (name, contrast = false, literal = false) =>
488
- !/background|surface|fill|accent|overlay/.test(name) &&
489
- // Borders and the shared text tokens step by contrast with the page (how
490
- // answers "lighter text" and "darker borders" that way), unless a mode is
491
- // named; a part's own color steps as written.
492
- ((!literal && /border|outline/.test(name)) ||
493
- (!literal && /^--color-text-/.test(name)) ||
494
- (contrast && /text|^color$|on-/.test(name)));
495
-
496
- /**
497
- * How strong a shadow reads: the sum of its colors' alphas; 0 for none.
498
- * @param {string} v
499
- */
500
- function shadowStrength(v) {
501
- if (!v || /^none$/.test(v.trim())) return 0;
502
- // Each layer's color, read by the one color reader (hex with alpha,
503
- // rgba(), hsla(), `/ alpha`). A layer has lengths: a bare color is no
504
- // shadow.
505
- return splitTop(v, ',')
506
- .filter(layer => /(?:^|\s)-?\d*\.?\d+(?:px|rem|em)?(?=\s|$)/.test(layer))
507
- .reduce(
508
- (sum, layer) => sum + colorsIn(layer).reduce((n, c) => n + alphaOf(c), 0),
509
- 0,
510
- );
511
- }
512
-
513
- /** The line properties the way of a line is measured on. */
514
- const LINE_PROPS =
515
- /^(?:border(?:-(?:top|right|bottom|left))?-width|outline-width|box-shadow)$/;
516
-
517
- /**
518
- * A line's strength as it renders: a width in px, or a shadow's summed
519
- * alpha.
520
- * @param {string} prop
521
- * @param {string} v resolved value
522
- */
523
- function lineStrength(prop, v) {
524
- const x = String(v ?? '').trim();
525
- if (!x || /^(?:none|hidden|0|0px|initial|unset)$/.test(x)) return 0;
526
- if (prop === 'box-shadow') return shadowStrength(x);
527
- if (/\b(?:none|hidden)\b/.test(x)) return 0;
528
- const kw = /\b(thin|medium|thick)\b/.exec(x)?.[1];
529
- if (kw) return {thin: 1, medium: 3, thick: 5}[kw] ?? 1;
530
- const m = /(-?\d*\.?\d+)(px|rem|em)?/.exec(x);
531
- if (!m) return 0;
532
- return Number(m[1]) * (m[2] === 'rem' || m[2] === 'em' ? 16 : 1);
533
- }
534
-
535
- /**
536
- * The value a compiled theme gives one look of a part (a render Core
537
- * draws, `variant=default,size=md :focus-within`): its most specific rule
538
- * that matches, in that state, with the custom properties those rules set.
539
- * @param {any} compiled
540
- * @param {string} part
541
- * @param {string} render
542
- * @param {string} prop
543
- * @returns {{value: string | undefined, tokens: Record<string, string>}}
544
- */
545
- function ruleValue(compiled, part, render, prop) {
546
- const rules = /** @type {Record<string, any>} */ (
547
- compiled?.components?.[part] ?? {}
548
- );
549
- const [head, ...rest] = String(render).split(' ');
550
- const attrs =
551
- head.startsWith(':') || head === 'always' ? [] : head.split(',');
552
- const state = (head.startsWith(':') ? [head, ...rest] : rest).join(' ');
553
- const matching = Object.keys(rules)
554
- .filter(
555
- w =>
556
- w === 'base' ||
557
- w.split(',').every(kv => attrs.includes(kv.replace(':', '='))),
558
- )
559
- .sort(
560
- (x, y) =>
561
- (x === 'base' ? 0 : x.split(',').length) -
562
- (y === 'base' ? 0 : y.split(',').length),
563
- );
564
- const camel = (/** @type {string} */ k) =>
565
- k.replace(/-([a-z])/g, (_m, c) => c.toUpperCase());
566
- /** @type {Record<string, string>} */
567
- const tokens = {};
568
- /** @type {string | undefined} */
569
- let value;
570
- const side = /^border-(top|right|bottom|left)-width$/.exec(prop)?.[1];
571
- for (const w of matching) {
572
- const layers = [rules[w], ...(state ? [rules[w]?.[state]] : [])];
573
- for (const r of layers) {
574
- if (!r || typeof r !== 'object') continue;
575
- for (const [k, v] of Object.entries(r))
576
- if (k.startsWith('--') && typeof v === 'string') tokens[k] = v;
577
- const own =
578
- r[camel(prop)] ??
579
- (side ? (r[camel(`border-${side}`)] ?? r.borderWidth) : undefined) ??
580
- (/^border(?:-[a-z]+)?-width$/.test(prop) ? r.border : undefined) ??
581
- (prop === 'outline-width' ? r.outline : undefined);
582
- if (typeof own === 'string' || typeof own === 'number')
583
- value = String(own);
584
- }
585
- }
586
- return {value, tokens};
587
- }
588
-
589
- /**
590
- * Why a step moves a line against the way asked, or null: every look Core
591
- * draws of each part the steps reach (a token step reaches every part that
592
- * reads the token), before and after, in each mode.
593
- * @param {any} C
594
- * @param {any} was
595
- * @param {any} now
596
- * @param {{light: Record<string, string>, dark: Record<string, string>}} tw
597
- * @param {{light: Record<string, string>, dark: Record<string, string>}} tn
598
- * @param {Step[]} steps
599
- * @param {MeasureIntent} intent
600
- * @param {'light' | 'dark' | null} visible
601
- * @param {Record<string, string[]>} groups the family groups `--on` takes, read from the census
602
- * @returns {string | null}
603
- */
604
- function lineWay(C, was, now, tw, tn, steps, intent, visible, groups) {
605
- const fainter = Boolean(intent.fainter) || intent.zero;
606
- // (A dial set to a named look, "the buttons dial, outline", draws that
607
- // look's lines: a line it adds is the look asked.)
608
- const namedLook = steps.some(
609
- st =>
610
- !st.on &&
611
- !/^--/.test(String(st.thing)) &&
612
- !/^(?:more|less)$/.test(String(st.value ?? '')),
613
- );
614
- const changedTokens = new Set(
615
- [...new Set([...Object.keys(tw.light), ...Object.keys(tn.light)])].filter(
616
- t => tw.light[t] !== tn.light[t] || tw.dark[t] !== tn.dark[t],
617
- ),
618
- );
619
- /** @type {Set<string>} */
620
- const parts = new Set(
621
- steps
622
- .map(st => st.on)
623
- .filter(Boolean)
624
- .flatMap(x => groups[String(x)] ?? [String(x)]),
625
- );
626
- if (changedTokens.size)
627
- for (const [part, info] of Object.entries(C.MAP ?? {}))
628
- for (const [prop, byRender] of Object.entries(
629
- /** @type {any} */ (info)?.at ?? {},
630
- ))
631
- if (
632
- LINE_PROPS.test(prop) &&
633
- Object.values(/** @type {Record<string, string>} */ (byRender)).some(
634
- v =>
635
- [...String(v).matchAll(/var\(\s*(--[a-z0-9-]+)/g)].some(m =>
636
- changedTokens.has(m[1]),
637
- ),
638
- )
639
- )
640
- parts.add(part);
641
- for (const part of parts) {
642
- const at = /** @type {Record<string, Record<string, string>>} */ (
643
- C.MAP?.[part]?.at ?? {}
644
- );
645
- // Every look Core draws of the part; a part that draws no line at all
646
- // has one plain look with none.
647
- const renders = new Set(
648
- Object.values(at)
649
- .flatMap(x => Object.keys(x ?? {}))
650
- .filter(r => !/::/.test(r)),
651
- );
652
- if (!renders.size) renders.add('always');
653
- const props = new Set([
654
- ...Object.keys(at).filter(p => LINE_PROPS.test(p)),
655
- 'border-top-width',
656
- 'box-shadow',
657
- ]);
658
- for (const prop of props)
659
- for (const render of renders) {
660
- // (A look in a state Core writes nothing new for shows its plain
661
- // look's value: a popover's shadow while focused.)
662
- const head = render.startsWith(':') ? 'always' : render.split(' ')[0];
663
- const coreOf = (/** @type {string} */ pr) =>
664
- at[pr]?.[render] ?? at[pr]?.[head] ?? at[pr]?.always;
665
- const core =
666
- coreOf(prop) ??
667
- (prop === 'border-top-width' ? coreOf('border-width') : undefined);
668
- const a = ruleValue(was, part, render, prop);
669
- const b = ruleValue(now, part, render, prop);
670
- const rawA = a.value ?? core ?? '0';
671
- const rawB = b.value ?? core ?? '0';
672
- if (
673
- rawA === rawB &&
674
- JSON.stringify(a.tokens) === JSON.stringify(b.tokens) &&
675
- !/var\(/.test(rawA)
676
- )
677
- continue;
678
- // (A border whose style is none or hidden draws nothing, whatever
679
- // its width.)
680
- const styled = (/** @type {any} */ c, /** @type {string} */ raw) => {
681
- if (prop === 'box-shadow' || prop.startsWith('outline')) return true;
682
- const side =
683
- /^border-(top|right|bottom|left)-width$/.exec(prop)?.[1] ?? '';
684
- const st =
685
- ruleValue(
686
- c,
687
- part,
688
- render,
689
- side ? `border-${side}-style` : 'border-style',
690
- ).value ??
691
- /\b(?:solid|dashed|dotted|double|groove|ridge|inset|outset|none|hidden)\b/.exec(
692
- raw,
693
- )?.[0] ??
694
- coreOf(side ? `border-${side}-style` : 'border-style') ??
695
- coreOf('border-style');
696
- // (A border with no style is none: CSS's initial style.)
697
- if (/^(?:none|hidden)$/.test(String(st ?? 'none').trim()))
698
- return false;
699
- // (A transparent border draws nothing either.)
700
- const colorProp = side ? `border-${side}-color` : 'border-color';
701
- const col =
702
- ruleValue(c, part, render, colorProp).value ??
703
- coreOf(colorProp) ??
704
- coreOf('border-color') ??
705
- '';
706
- return !/^\s*transparent\s*$/.test(
707
- resolveIn(String(col), {...tw.light}, 'light'),
708
- );
709
- };
710
- const drawnA = styled(was, rawA);
711
- const drawnB = styled(now, rawB);
712
- for (const mode of /** @type {const} */ (['light', 'dark'])) {
713
- if (visible && mode !== visible) continue;
714
- const x = !drawnA
715
- ? 0
716
- : lineStrength(
717
- prop,
718
- resolveIn(rawA, {...tw[mode], ...a.tokens}, mode),
719
- );
720
- const y = !drawnB
721
- ? 0
722
- : lineStrength(
723
- prop,
724
- resolveIn(rawB, {...tn[mode], ...b.tokens}, mode),
725
- );
726
- const look = render === 'always' ? '' : ` (${render})`;
727
- const what =
728
- prop === 'box-shadow' ? 'shadow' : prop.replace(/-width$/, '');
729
- // (A removal keeps what an except pins in a state, and a group's
730
- // state look that drew nothing may take a fainter line: only the
731
- // looks at rest are held to an added line; a stronger one is
732
- // held everywhere.)
733
- const atRest = !/(?:^|\s):/.test(render);
734
- if (fainter && y > x + 1e-6 && (atRest || (intent.fainter && x > 0)))
735
- return `it would ${x ? 'strengthen' : 'add'} a ${what} on ${part}${look} in ${mode} mode, which the question makes fainter`;
736
- // (A shadow asked stronger may be new on a look that drew none.)
737
- if (
738
- !fainter &&
739
- !namedLook &&
740
- prop !== 'box-shadow' &&
741
- x === 0 &&
742
- y > 0 &&
743
- b.value !== undefined
744
- )
745
- return `it would add a ${what} on ${part}${look} in ${mode} mode, where Core draws none`;
746
- }
747
- }
748
- }
749
- return null;
750
- }
751
-
752
- /**
753
- * A shadow as it renders: each color written in one form (hex with its
754
- * alpha), so two spellings of the same shadow compare equal.
755
- * @param {string} v
756
- */
757
- function shadowLook(v) {
758
- return String(v)
759
- .replace(COLOR_IN_VALUE, c => {
760
- const rgb = parseColor(c);
761
- if (!rgb) return c;
762
- const a = Math.round(alphaOf(c) * 255);
763
- return `rgb(${rgb.slice(0, 3).join(' ')} / ${a})`;
764
- })
765
- .replace(/\s+/g, ' ')
766
- .trim();
767
- }
768
-
769
- /**
770
- * A color as it paints over the page in a mode: its alpha blended with the
771
- * page color, so a see-through fill compares by what shows.
772
- * @param {string} v
773
- * @param {Record<string, string>} toks the mode's tokens
774
- * @param {'light' | 'dark'} mode
775
- * @returns {number[] | null}
776
- */
777
- function painted(v, toks, mode) {
778
- const rgb = parseColor(v);
779
- if (!rgb) return null;
780
- const a = alphaOf(v);
781
- const page =
782
- parseColor(resolveIn('var(--color-background-body)', toks, mode)) ??
783
- (mode === 'dark' ? [0, 0, 0] : [255, 255, 255]);
784
- return rgb.slice(0, 3).map((x, i) => x * a + page[i] * (1 - a));
785
- }
786
-
787
- /**
788
- * How colorful a color looks: its OKLCH chroma, the measure the palette
789
- * generator's vibrancy moves, or null when it does not read. (HSL
790
- * saturation rates a pale yellow near full and a deeper, more colorful one
791
- * lower.)
792
- * @param {string | number[] | null} v a color, or its RGB
793
- */
794
- function saturationOf(v) {
795
- const rgb = Array.isArray(v) ? v : v == null ? null : parseColor(v);
796
- if (!rgb) return null;
797
- const hexOf = rgb
798
- .slice(0, 3)
799
- .map(x =>
800
- Math.round(Math.max(0, Math.min(255, x)))
801
- .toString(16)
802
- .padStart(2, '0'),
803
- )
804
- .join('');
805
- return hexToOklch(`#${hexOf}`).C;
806
- }
807
-
808
- /** The chroma change, per color, too small to count as a move. */
809
- const CHROMA_STEP = 0.005;
810
-
811
- /** @param {number[]} c */
812
- const luminance = c => c[0] * 0.299 + c[1] * 0.587 + c[2] * 0.114;
813
-
814
- /**
815
- * One part's rules: each source's declarations on top of the one before,
816
- * condition by condition (a rule that sets one property keeps the earlier
817
- * rule's others).
818
- * @param {...Record<string, any>} sources the part's rules, earliest first
819
- * @returns {Record<string, Record<string, any>>}
820
- */
821
- export function mergeRules(...sources) {
822
- /** @type {Record<string, Record<string, any>>} */
823
- const rules = {};
824
- for (const src of sources)
825
- for (const [when, rule] of Object.entries(src ?? {}))
826
- rules[when] =
827
- rule && typeof rule === 'object' && !Array.isArray(rule)
828
- ? {...(rules[when] ?? {}), ...rule}
829
- : rule;
830
- return rules;
831
- }
832
-
833
- /**
834
- * The tokens inside a part in one mode: the theme's, with each token the
835
- * part's own rule sets (a part-scoped dial's `--spacing-4`) over them, and a
836
- * variant's rule over the part's in that variant.
837
- * @param {Record<string, Record<string, any>>} rules the part's rules
838
- * @param {Record<string, string>} tokens the theme's tokens in that mode
839
- * @param {string} when the rule's condition (`base` at rest)
840
- * @returns {Record<string, string>}
841
- */
842
- export function scopedTokens(rules, tokens, when) {
843
- /** @type {Record<string, string>} */
844
- const t = {...tokens};
845
- for (const w of when === 'base' ? ['base'] : ['base', when])
846
- for (const [k, v] of Object.entries(rules[w] ?? {}))
847
- if (k.startsWith('--') && typeof v === 'string') t[k] = v;
848
- return t;
849
- }
850
-
851
- /**
852
- * The values a part shows, by `when|state|prop` and mode: its own
853
- * compiled rules (the base theme's, with the theme's on top), then each
854
- * token it reads for a property, with every var() written out from the
855
- * part's tokens in that mode. `raw` is the declaration as written.
856
- * @param {any} C the part data (what each part reads, from Core)
857
- * @param {Record<string, any>} baseComponents the base theme's own part styles
858
- * @param {any} compiled the theme's own compiled styles
859
- * @param {{light: Record<string, string>, dark: Record<string, string>}} toks
860
- * @param {string} part
861
- * @returns {Map<string, {light: string, dark: string, raw: string}>}
862
- */
863
- export function partShows(C, baseComponents, compiled, toks, part) {
864
- const rules = mergeRules(
865
- baseComponents?.[part] ?? {},
866
- compiled.components?.[part] ?? {},
867
- );
868
- const own = partValues(rules);
869
- const scoped = (
870
- /** @type {'light' | 'dark'} */ m,
871
- /** @type {string} */ when,
872
- ) => scopedTokens(rules, toks[m], when);
873
- /** @type {Map<string, string>} */
874
- const raw = new Map(own);
875
- // The part at rest in its main variant is its `base` too (a set with no
876
- // --when writes base).
877
- const mainWhen = (/** @type {string[]} */ ws) =>
878
- ws.some(
879
- w =>
880
- w === '' ||
881
- /^variant=(default|primary|accent|neutral)$|^size=md$/.test(w),
882
- );
883
- // What Core writes for a property in a rule (a card's padding is its
884
- // container padding less the border width): the whole declaration, so
885
- // a value is never read from one token of several.
886
- const declOf = (
887
- /** @type {string} */ prop,
888
- /** @type {string} */ w,
889
- /** @type {string} */ token,
890
- ) => {
891
- const at = C.MAP[part]?.at?.[prop] ?? {};
892
- const attrs = w ? w.split(' ') : [];
893
- const key = Object.keys(at).find(k =>
894
- attrs.every(x => k.split(',').includes(x)),
895
- );
896
- // (Only a declaration of several theme tokens: one token alone is
897
- // read as that token.)
898
- const decl = key ? String(at[key]) : '';
899
- const tokens = new Set(
900
- [...decl.matchAll(/var\(\s*(--[a-z][a-z0-9-]*)/g)]
901
- .map(m => m[1])
902
- .filter(t => !/^--(_|astryx-)/.test(t)),
903
- );
904
- return decl.includes(token) && tokens.size > 1 ? decl : `var(${token})`;
905
- };
906
- for (const g of Object.keys(GROUPS))
907
- for (const r of C.partReads(part, g) ?? [])
908
- if (mainWhen(r.when?.length ? r.when : ['']))
909
- for (const prop of r.props ?? []) {
910
- const key = `base||${prop}`;
911
- const w = (r.when?.length ? r.when : ['']).find(
912
- (/** @type {string} */ x) => mainWhen([x]),
913
- );
914
- if (!raw.has(key)) raw.set(key, declOf(prop, w ?? '', r.token));
915
- }
916
- for (const g of Object.keys(GROUPS))
917
- for (const r of C.partReads(part, g) ?? [])
918
- for (const prop of r.props ?? [])
919
- for (const w of r.when?.length ? r.when : [''])
920
- if (!/::|:active|:hover|:focus|:checked|:disabled/.test(w)) {
921
- const key = `${w ? w.replace('=', ':') : 'base'}||${prop}`;
922
- // A variant with no rule of its own takes the part's own base
923
- // rule over the token it reads.
924
- if (!raw.has(key))
925
- raw.set(
926
- key,
927
- own.get(`base||${prop}`) ?? declOf(prop, w, r.token),
928
- );
929
- }
930
- /** @type {Map<string, {light: string, dark: string, raw: string}>} */
931
- const out = new Map();
932
- for (const [k, v] of raw)
933
- out.set(k, {
934
- light: resolveIn(v, scoped('light', k.split('|')[0]), 'light'),
935
- dark: resolveIn(v, scoped('dark', k.split('|')[0]), 'dark'),
936
- raw: v,
937
- });
938
- return out;
939
- }
940
-
941
- /**
942
- * Hold the after build to the intent; why it does not fit, or null.
943
- * @param {any} ctx
944
- * @param {any} base
945
- * @param {any} was
946
- * @param {any} now
947
- * @param {MeasureIntent} intent
948
- * @param {Step[]} steps
949
- * @param {'light' | 'dark' | null} [visible] the one mode a one-mode theme shows
950
- */
951
- function measureFit(ctx, base, was, now, intent, steps, visible = null) {
952
- const tw = ownTokens(was, base, ctx.project?.core);
953
- const tn = ownTokens(now, base, ctx.project?.core);
954
- const C = ctx.C;
955
- /** @param {string} part */
956
- const members = part => groupsOf(ctx)[part] ?? [part];
957
- // A kept part, or one state or variant of it (`part@when|state|`).
958
- /** @type {Array<{part: string, prefix: string}>} */
959
- const keeps = intent.keep.flatMap(k => {
960
- const [part, prefix = ''] = k.split('@');
961
- return members(part).map(m => ({part: m, prefix}));
962
- });
963
- const subjects = new Set(intent.subjects.flatMap(members));
964
- /**
965
- * @param {any} compiled
966
- * @param {{light: Record<string, string>, dark: Record<string, string>}} toks
967
- * @param {string} part
968
- */
969
- const shown = (compiled, toks, part) =>
970
- partShows(C, base.components, compiled, toks, part);
971
- // Parts the question keeps: every value they show is the same after.
972
- for (const {part, prefix} of keeps) {
973
- const a = shown(was, tw, part);
974
- const b = shown(now, tn, part);
975
- for (const [k, v] of b) {
976
- // A whole kept part: its plain look (base); a state or variant: that.
977
- // A whole kept part: every rule it shows at rest (its plain rule and
978
- // each variant's); a state or variant: that.
979
- // (At rest: the plain rule, or one variant's alone; a variant in a
980
- // selected or checked state is a state of it.)
981
- if (
982
- prefix
983
- ? !k.startsWith(prefix)
984
- : k.split('|')[1] || !/^(base|[a-z]+:[\w-]+)$/.test(k.split('|')[0])
985
- )
986
- continue;
987
- // A plain color written as `background` is the background color the
988
- // part painted before.
989
- const prop0 = k.split('|')[2] ?? '';
990
- const o =
991
- a.get(k) ??
992
- (/\|background$/.test(k) ? a.get(`${k}-color`) : undefined) ??
993
- // A custom property set on the part: what that token was before.
994
- (/^--/.test(prop0)
995
- ? {
996
- light: resolveIn(`var(${prop0})`, tw.light, 'light'),
997
- dark: resolveIn(`var(${prop0})`, tw.dark, 'dark'),
998
- raw: `var(${prop0})`,
999
- }
1000
- : undefined);
1001
- // (A state rule the part did not list before is not measured: what
1002
- // it showed in that state is not known here.)
1003
- if (!o && k.split('|')[1]) continue;
1004
- // A value the part did not show before (a keep rule on a member that
1005
- // reads none of it) is not a change it shows; a kept variant is held
1006
- // exactly: a rule it did not have, other than none, is a change,
1007
- // unless it is what the part showed at rest; a corner longhand under
1008
- // a kept shorthand follows the shorthand.
1009
- if (!o && (!prefix || /^(none|transparent|initial|unset)$/.test(v.raw)))
1010
- continue;
1011
- const inherited = a.get(`base||${k.split('|')[2]}`);
1012
- if (
1013
- !o &&
1014
- inherited &&
1015
- inherited.light === v.light &&
1016
- inherited.dark === v.dark
1017
- )
1018
- continue;
1019
- // A look kept with no rule of its own under its condition is held to
1020
- // what the part drew under it before, in any of its looks (Core
1021
- // writes the condition beside the variant and size): measured as
1022
- // drawn, never as stored.
1023
- const condOf = k.split('|')[0].replace(':', '=');
1024
- const drawnUnder = (/** @type {string} */ x) =>
1025
- [...a.entries()].find(([k2]) => {
1026
- const [w2, st2, p2] = k2.split('|');
1027
- return (
1028
- !st2 &&
1029
- p2 === x &&
1030
- w2.replace(/:/g, '=').split(/[\s,]/).includes(condOf)
1031
- );
1032
- })?.[1];
1033
- if (!o && k.split('|')[0] !== 'base' && !k.split('|')[1]) {
1034
- const was = drawnUnder(prop0);
1035
- if (was && was.light === v.light && was.dark === v.dark) continue;
1036
- // (A type property the look never set draws what it inherits, the
1037
- // body's: a pin of the body's value keeps it as it drew.)
1038
- const BODY = /** @type {Record<string, string>} */ ({
1039
- 'font-weight': '--text-body-weight',
1040
- 'font-family': '--font-family-body',
1041
- 'font-size': '--text-body-size',
1042
- 'line-height': '--text-body-line-height',
1043
- });
1044
- const bodyTok = BODY[prop0];
1045
- if (!was && !a.get(`base||${prop0}`) && bodyTok) {
1046
- const inh = (/** @type {'light' | 'dark'} */ m) =>
1047
- resolveIn(`var(${bodyTok})`, tw[m], m);
1048
- const same = (/** @type {'light' | 'dark'} */ m) => {
1049
- const x = String(inh(m) ?? '').trim();
1050
- return x !== '' && !/^var\(/.test(x) && x === String(v[m]).trim();
1051
- };
1052
- if (same('light') && same('dark')) continue;
1053
- }
1054
- }
1055
- // A border color on a look that draws no border (no width there, as
1056
- // a date input's own box, whose field draws the line) shows nothing.
1057
- if (!o && /^border(?:-(?:top|right|bottom|left))?-color$/.test(prop0)) {
1058
- const when0 = k.split('|')[0];
1059
- const width =
1060
- b.get(`${when0}||border-width`) ?? b.get('base||border-width');
1061
- if (
1062
- !width ||
1063
- (lineStrength('border-width', width.light) === 0 &&
1064
- lineStrength('border-width', width.dark) === 0)
1065
- )
1066
- continue;
1067
- }
1068
- // A border shorthand written back on a kept look is held to the
1069
- // longhands it showed before: its width and color, in each mode.
1070
- if (!o && /^border(?:-(?:top|right|bottom|left))?$/.test(prop0)) {
1071
- const when0 = k.split('|')[0];
1072
- // (Read under that condition in any look of the part: Core writes
1073
- // it with the variant and size beside it.)
1074
- const underCond = drawnUnder;
1075
- const long = (/** @type {string} */ x) =>
1076
- a.get(`${when0}||${prop0}-${x}`) ??
1077
- a.get(`${when0}||border-${x}`) ??
1078
- underCond(`${prop0}-${x}`) ??
1079
- underCond(`border-${x}`) ??
1080
- a.get(`base||${prop0}-${x}`) ??
1081
- a.get(`base||border-${x}`);
1082
- const w0 = long('width');
1083
- const c0 = long('color');
1084
- const same = (/** @type {'light' | 'dark'} */ m) => {
1085
- const parts = splitTop(v[m], ' ').filter(Boolean);
1086
- const w = parts.find(x =>
1087
- /^-?\d*\.?\d+(?:px|rem|em)?$|^(?:thin|medium|thick)$/.test(x),
1088
- );
1089
- const c = parts
1090
- .filter(
1091
- x =>
1092
- x !== w &&
1093
- !/^(?:solid|dashed|dotted|double|none|hidden)$/.test(x),
1094
- )
1095
- .join(' ');
1096
- return (
1097
- w0 != null &&
1098
- c0 != null &&
1099
- lineStrength('border-width', w ?? '') ===
1100
- lineStrength('border-width', w0[m]) &&
1101
- c === c0[m]
1102
- );
1103
- };
1104
- // (The same width and the same color token, written as Core
1105
- // writes them, draw the same: the token takes the value its scope
1106
- // gives it under the condition.)
1107
- const rawParts = splitTop(String(v.raw ?? ''), ' ').filter(Boolean);
1108
- const widthOf = (/** @type {'light' | 'dark'} */ m) =>
1109
- splitTop(v[m], ' ').find(x =>
1110
- /^-?\d*\.?\d+(?:px|rem|em)?$|^(?:thin|medium|thick)$/.test(x),
1111
- ) ?? '';
1112
- const sameRaw =
1113
- w0 != null &&
1114
- c0?.raw != null &&
1115
- ['light', 'dark'].every(
1116
- m =>
1117
- lineStrength('border-width', widthOf(/** @type {any} */ (m))) ===
1118
- lineStrength(
1119
- 'border-width',
1120
- w0[/** @type {'light' | 'dark'} */ (m)],
1121
- ),
1122
- ) &&
1123
- rawParts.includes(String(c0.raw).trim());
1124
- if (sameRaw || (same('light') && same('dark'))) continue;
1125
- }
1126
- if (!o)
1127
- return `it would change ${part} (${k.split('|').filter(Boolean).join(' ')}), which the question keeps as it is`;
1128
- if (
1129
- /radius$/.test(k) &&
1130
- /-(start|end)-(start|end)-radius$/.test(k) &&
1131
- b.has('base||border-radius')
1132
- )
1133
- continue;
1134
- // A padding side under a kept padding shorthand follows the shorthand
1135
- // (the part's own padding covers every side).
1136
- if (/\|padding-/.test(k)) {
1137
- const sh = b.get('base||padding');
1138
- const was = a.get('base||padding');
1139
- if (sh && was && sh.light === was.light && sh.dark === was.dark)
1140
- continue;
1141
- }
1142
- if (o.light !== v.light || o.dark !== v.dark)
1143
- return `it would change ${part} (${k.split('|').filter(Boolean).join(' ')}), which the question keeps as it is`;
1144
- }
1145
- }
1146
- // The way of a line, in every look Core draws: an ask that makes
1147
- // something fainter, or removes it, never adds or strengthens a border,
1148
- // outline, ring or shadow anywhere; a way asked of a line or a shadow
1149
- // never adds one to a look that drew none (a card variant with no
1150
- // border, a table row whose cells draw the dividers).
1151
- const lineAsk =
1152
- Boolean(intent.fainter) ||
1153
- intent.zero ||
1154
- (Boolean(intent.dir) &&
1155
- intent.families.some(f => f === 'border' || f === 'shadow'));
1156
- if (lineAsk) {
1157
- const why = lineWay(
1158
- C,
1159
- was,
1160
- now,
1161
- tw,
1162
- tn,
1163
- steps,
1164
- intent,
1165
- visible,
1166
- groupsOf(ctx),
1167
- );
1168
- if (why) return why;
1169
- }
1170
- const typed = new Set(intent.typed.map(x => x.toLowerCase()));
1171
- // A shadow ask is answered only by a shadow that looks different: an
1172
- // opaque color written with alpha ff, or clamped there, is no change.
1173
- let shadowMoved = !intent.shadowDir;
1174
- // A value the question types is the target: the way of what it writes
1175
- // is as written, but the kind of change and a removal are still held,
1176
- // and every other value is measured the way asked (a dial step beside a
1177
- // typed value included: "smaller, 16px" never gives spacing more). A dial
1178
- // is judged by what it does, never by its own word: "vibrancy less" is
1179
- // the way "more washed out" asks.
1180
- const typedFamilies = new Set(
1181
- steps
1182
- .filter(st => typed.has(String(st.value ?? '').toLowerCase()))
1183
- .map(st => familyOf(st.thing)),
1184
- );
1185
- // The subject's changed values: family, direction, removal.
1186
- const touched = new Set([
1187
- ...subjects,
1188
- ...steps
1189
- .map(st => st.on)
1190
- .filter(Boolean)
1191
- .flatMap(x => members(String(x))),
1192
- ]);
1193
- // A radio mark the editor keeps round on a Core that draws its circle
1194
- // with the pill token, and its dot: a zero radius ask leaves them.
1195
- const radios = new Set(
1196
- pillDrawnRadios(C).flatMap(m => [m, ...(C.MAP[m]?.contains ?? [])]),
1197
- );
1198
- // An indicator line's thickness (a tab's underline height) is the
1199
- // width of a line it draws, as a border's is.
1200
- const lineSide = new Map(indicatorLines(C).map(x => [x.part, x.side]));
1201
- for (const part of touched) {
1202
- // A whole kept part is checked above, not as a subject.
1203
- if (keeps.some(k => k.part === part && !k.prefix)) continue;
1204
- const a = shown(was, tw, part);
1205
- const b = shown(now, tn, part);
1206
- for (const [k, v] of b) {
1207
- // A kept state or variant of the part is checked above.
1208
- if (
1209
- keeps.some(x => x.part === part && x.prefix && k.startsWith(x.prefix))
1210
- )
1211
- continue;
1212
- const prop = k.split('|')[2];
1213
- // A shorthand written where the part read longhands: its first side.
1214
- // (Whether the value before is the same rule's, not a stand-in.)
1215
- const exact = a.has(k);
1216
- const o =
1217
- a.get(k) ??
1218
- (prop === 'padding'
1219
- ? (a.get(`${k.split('|')[0]}||padding-top`) ??
1220
- a.get('base||padding-top'))
1221
- : prop === 'border'
1222
- ? a.get('base||border-width')
1223
- : a.get(`base||${prop}`));
1224
- if (o && o.light === v.light && o.dark === v.dark) continue;
1225
- // The see-through border a border color brings to a part that draws
1226
- // none (set writes it with the color) is that color's line: asked
1227
- // with it, never a change of its own.
1228
- if (
1229
- prop === 'border' &&
1230
- /\btransparent\b/.test(`${v.light} ${v.dark}`) &&
1231
- steps.some(st => BORDER_COLOR_PROP.test(String(st.thing)))
1232
- )
1233
- continue;
1234
- const fam = familyOf(prop);
1235
- if (!fam) continue;
1236
- // A property a typed value writes is asked: the question wrote it.
1237
- const typedHere = steps.some(
1238
- st =>
1239
- typed.has(String(st.value ?? '').toLowerCase()) &&
1240
- familyOf(st.thing) === fam,
1241
- );
1242
- // A property Core draws from the very token a step writes (a title's
1243
- // margin from its heading size) moves with it: that token is asked.
1244
- const sameToken = steps.some(
1245
- st =>
1246
- /^--/.test(String(st.thing)) &&
1247
- Object.keys(GROUPS).some(g =>
1248
- (C.partReads(part, g) ?? []).some(
1249
- (/** @type {{token: string, props: string[]}} */ r) =>
1250
- r.token === st.thing && r.props.includes(prop),
1251
- ),
1252
- ) &&
1253
- steps.some(x => x.thing === st.thing && familyOf(x.thing) !== fam),
1254
- );
1255
- // An indicator line's thickness is also the width of a line it
1256
- // draws: a border ask reaches it.
1257
- const lineWidth =
1258
- lineSide.get(part) === prop && intent.families.includes('border');
1259
- if (
1260
- intent.families.length &&
1261
- !intent.families.includes(fam) &&
1262
- !lineWidth &&
1263
- !typedHere &&
1264
- !sameToken
1265
- )
1266
- return `it would also change ${part}'s ${prop}, which is not what the question asks to change`;
1267
- for (const mode of /** @type {const} */ (['light', 'dark'])) {
1268
- if (visible && mode !== visible) continue;
1269
- const after = v[mode];
1270
- const before = o?.[mode] ?? null;
1271
- if (intent.zero && fam === 'radius' && radios.has(part)) continue;
1272
- if (
1273
- intent.zero &&
1274
- ['radius', 'space', 'border', 'shadow'].includes(fam)
1275
- ) {
1276
- // (Core's own composed layers, a card's ring, are no shadow of
1277
- // the theme's: a shadow of only those is none at rest.)
1278
- const own = splitTop(after, ',')
1279
- .map(x => x.trim())
1280
- .filter(
1281
- x =>
1282
- x &&
1283
- !/^var\(\s*--_/.test(x) &&
1284
- !/^(?:0(?:px)?\s+)+transparent$/i.test(x),
1285
- )
1286
- .join(', ');
1287
- const n = measureNumber(own);
1288
- if (own && !/^(none|transparent|0)$/.test(own) && n !== 0)
1289
- return `${part}'s ${prop} would be ${after} in ${mode} mode, not none`;
1290
- continue;
1291
- }
1292
- // A shadow written where the part showed none it can read is a
1293
- // change.
1294
- if (fam === 'shadow' && before == null && !/^none$/i.test(after))
1295
- shadowMoved = true;
1296
- if (before == null || typedFamilies.has(fam)) continue;
1297
- // A shadow's strength moves the way asked, in each mode.
1298
- if (fam === 'shadow' && intent.shadowDir) {
1299
- const x = shadowStrength(after);
1300
- const y = shadowStrength(before);
1301
- if (Math.abs(x - y) > 1e-6 && (intent.shadowDir === 'more') !== x > y)
1302
- return `${part}'s ${prop} would get ${intent.shadowDir === 'more' ? 'weaker' : 'stronger'} in ${mode} mode`;
1303
- if (shadowLook(after) !== shadowLook(before)) shadowMoved = true;
1304
- continue;
1305
- }
1306
- // "more transparent": the color's alpha goes down, "more opaque" up.
1307
- if (fam === 'color' && intent.opacityDir) {
1308
- const x = parseColor(after) ? alphaOf(after) : null;
1309
- const y = parseColor(before) ? alphaOf(before) : null;
1310
- if (
1311
- x != null &&
1312
- y != null &&
1313
- Math.abs(x - y) > 1e-3 &&
1314
- (intent.opacityDir === 'more') !== x > y
1315
- )
1316
- return `${part}'s ${prop} would get ${intent.opacityDir === 'more' ? 'more' : 'less'} see-through in ${mode} mode`;
1317
- }
1318
- if (fam === 'color' && intent.lighter != null) {
1319
- // A part's color, in every variant and state it shows (a step on
1320
- // the plain rule reaches the variants that take it), in each mode
1321
- // (or the one the question names), never an overlay layer over
1322
- // the fill; only the kind of color the steps write (a new fill
1323
- // may bring a text color that reads on it).
1324
- if (intent.mode && mode !== intent.mode) continue;
1325
- const [when] = k.split('|');
1326
- if (!exact) continue;
1327
- const kindOf = (/** @type {string} */ x) =>
1328
- /^background/.test(x)
1329
- ? 'fill'
1330
- : /border|outline/.test(x)
1331
- ? 'line'
1332
- : 'ink';
1333
- if (
1334
- !steps.some(
1335
- st => kindOf(st.thing.replace(/^--color-/, '')) === kindOf(prop),
1336
- )
1337
- )
1338
- continue;
1339
- if (
1340
- /overlay|tint/.test(String(o?.raw ?? '')) ||
1341
- /overlay|tint/.test(v.raw)
1342
- )
1343
- continue;
1344
- const x = painted(after, tn[mode], mode);
1345
- const y = intent.from
1346
- ? painted(
1347
- resolveIn(`var(${intent.from})`, tw[mode], mode),
1348
- tw[mode],
1349
- mode,
1350
- )
1351
- : painted(before, tw[mode], mode);
1352
- // (A way from a theme color is that color's way, in every mode.)
1353
- const want =
1354
- mode === 'dark' &&
1355
- !intent.from &&
1356
- isForeground(prop, intent.contrast, intent.literal)
1357
- ? !intent.lighter
1358
- : intent.lighter;
1359
- if (x && y && Math.abs(luminance(x) - luminance(y)) >= 0.5)
1360
- if (want !== luminance(x) > luminance(y))
1361
- return `${part}'s ${prop}${when !== 'base' ? ` (${when})` : ''} would get ${want ? 'darker' : 'lighter'} in ${mode} mode (${before} to ${after})`;
1362
- // "darker than the page": past the part compared against, in
1363
- // each mode it shows.
1364
- if (x && /^background/.test(prop))
1365
- for (const ref of intent.than ?? []) {
1366
- const refValue =
1367
- ref === 'page'
1368
- ? resolveIn('var(--color-background-body)', tn[mode], mode)
1369
- : shown(now, tn, ref).get('base||background-color')?.[mode];
1370
- const r = refValue ? painted(refValue, tn[mode], mode) : null;
1371
- if (r && want !== luminance(x) > luminance(r))
1372
- return `${part}'s ${prop}${when !== 'base' ? ` (${when})` : ''} would still be ${want ? 'darker' : 'lighter'} than the ${ref} in ${mode} mode (${after} on ${refValue})`;
1373
- }
1374
- continue;
1375
- }
1376
- const dir = fam === 'opacity' ? intent.opacityDir : intent.dir;
1377
- if (
1378
- !dir ||
1379
- !(
1380
- ['radius', 'border', 'weight', 'opacity', 'fontsize'].includes(
1381
- fam,
1382
- ) ||
1383
- // A space: one length written over one read (never a shorthand).
1384
- (fam === 'space' &&
1385
- (intent.bound ||
1386
- (exact &&
1387
- steps.some(st => st.thing === prop) &&
1388
- !/\s/.test(after) &&
1389
- !/\s/.test(String(before)))))
1390
- )
1391
- )
1392
- continue;
1393
- const x = measureNumber(after);
1394
- const y = measureNumber(before);
1395
- if (x != null && y != null && x !== y && (dir === 'more') !== x > y)
1396
- return `${part}'s ${prop} would move the other way in ${mode} mode (${before} to ${after})`;
1397
- }
1398
- }
1399
- }
1400
- // Tokens the steps name (a dial: its main token): the same checks.
1401
- const DIAL_TOKEN = /** @type {Record<string, string>} */ ({
1402
- accent: '--color-accent',
1403
- danger: '--color-error',
1404
- success: '--color-success',
1405
- warning: '--color-warning',
1406
- info: '--color-info',
1407
- neutral: '--color-neutral',
1408
- });
1409
- for (const st of steps) {
1410
- const tok = /^--/.test(st.thing) ? st.thing : DIAL_TOKEN[st.thing];
1411
- if (!tok || st.on) continue;
1412
- const fam = familyOf(tok);
1413
- if (!fam) continue;
1414
- if (intent.families.length && !intent.families.includes(fam))
1415
- return `${tok} is not what the question asks to change`;
1416
- for (const mode of /** @type {const} */ (['light', 'dark'])) {
1417
- if (visible && mode !== visible) continue;
1418
- const after = resolveIn(`var(${tok})`, tn[mode], mode);
1419
- const before = resolveIn(`var(${tok})`, tw[mode], mode);
1420
- if (after === before) continue;
1421
- if (
1422
- intent.zero &&
1423
- ['radius', 'space', 'border', 'shadow'].includes(fam)
1424
- ) {
1425
- const n = measureNumber(after);
1426
- if (!/^(none|transparent|0)$/.test(after) && n !== 0)
1427
- return `${tok} would be ${after} in ${mode} mode, not none`;
1428
- continue;
1429
- }
1430
- if (typedFamilies.has(fam)) continue;
1431
- if (fam === 'shadow' && intent.shadowDir) {
1432
- const x = shadowStrength(after);
1433
- const y = shadowStrength(before);
1434
- if (Math.abs(x - y) > 1e-6 && (intent.shadowDir === 'more') !== x > y)
1435
- return `${tok} would get ${intent.shadowDir === 'more' ? 'weaker' : 'stronger'} in ${mode} mode`;
1436
- if (shadowLook(after) !== shadowLook(before)) shadowMoved = true;
1437
- continue;
1438
- }
1439
- if (fam === 'color' && intent.opacityDir) {
1440
- const x = parseColor(after) ? alphaOf(after) : null;
1441
- const y = parseColor(before) ? alphaOf(before) : null;
1442
- if (
1443
- x != null &&
1444
- y != null &&
1445
- Math.abs(x - y) > 1e-3 &&
1446
- (intent.opacityDir === 'more') !== x > y
1447
- )
1448
- return `${tok} would get ${intent.opacityDir === 'more' ? 'more' : 'less'} see-through in ${mode} mode`;
1449
- continue;
1450
- }
1451
- if (fam === 'color' && intent.lighter != null) {
1452
- if (intent.mode && mode !== intent.mode) continue;
1453
- const x = painted(after, tn[mode], mode);
1454
- const y = painted(before, tw[mode], mode);
1455
- const want =
1456
- mode === 'dark' && isForeground(tok, intent.contrast, intent.literal)
1457
- ? !intent.lighter
1458
- : intent.lighter;
1459
- if (x && y && Math.abs(luminance(x) - luminance(y)) >= 0.5)
1460
- if (want !== luminance(x) > luminance(y))
1461
- return `${tok} would get ${want ? 'darker' : 'lighter'} in ${mode} mode (${before} to ${after})`;
1462
- continue;
1463
- }
1464
- const dir = fam === 'opacity' ? intent.opacityDir : intent.dir;
1465
- if (!dir) continue;
1466
- const x = measureNumber(after);
1467
- const y = measureNumber(before);
1468
- if (x != null && y != null && x !== y && (dir === 'more') !== x > y)
1469
- return `${tok} would move the other way in ${mode} mode (${before} to ${after})`;
1470
- }
1471
- }
1472
- // "more colorful", "more muted": the accent colors the theme shows (the
1473
- // accent and the text and icons drawn in it) move that way in saturation
1474
- // together, in each mode shown (a step that dulls them is not more
1475
- // colorful), and the accent wash, as it paints over the page, never moves
1476
- // the other way (a faint wash made a solid fill is not less colorful).
1477
- if (intent.saturation)
1478
- for (const mode of /** @type {Array<'light' | 'dark'>} */ (
1479
- visible ? [visible] : ['light', 'dark']
1480
- )) {
1481
- let x = 0;
1482
- let y = 0;
1483
- let n = 0;
1484
- for (const tok of Object.keys(tw[mode])) {
1485
- if (!/^--color-(?:text-|icon-)?accent$/.test(tok)) continue;
1486
- // (As it paints over the page.)
1487
- const a = saturationOf(
1488
- painted(resolveIn(`var(${tok})`, tn[mode], mode), tn[mode], mode),
1489
- );
1490
- const b = saturationOf(
1491
- painted(resolveIn(`var(${tok})`, tw[mode], mode), tw[mode], mode),
1492
- );
1493
- if (a == null || b == null) continue;
1494
- x += a;
1495
- y += b;
1496
- n++;
1497
- }
1498
- if (
1499
- n &&
1500
- (intent.saturation === 'more'
1501
- ? x < y - CHROMA_STEP * n
1502
- : x > y + CHROMA_STEP * n)
1503
- )
1504
- return `the accent colors would get ${intent.saturation === 'more' ? 'duller' : 'more saturated'} in ${mode} mode`;
1505
- const wash = (/** @type {Record<string, string>} */ t) =>
1506
- t['--color-accent-muted'] == null
1507
- ? null
1508
- : saturationOf(
1509
- painted(resolveIn('var(--color-accent-muted)', t, mode), t, mode),
1510
- );
1511
- const [wa, wb] = [wash(tn[mode]), wash(tw[mode])];
1512
- if (
1513
- wa != null &&
1514
- wb != null &&
1515
- (intent.saturation === 'more'
1516
- ? wa < wb - CHROMA_STEP
1517
- : wa > wb + CHROMA_STEP)
1518
- )
1519
- return `the accent wash (--color-accent-muted) would get ${intent.saturation === 'more' ? 'duller' : 'more saturated'} in ${mode} mode, as it paints over the page`;
1520
- }
1521
- if (!shadowMoved && steps.some(st => familyOf(st.thing) === 'shadow'))
1522
- return 'the shadows would look the same as they do now (a shadow color at full strength gets no stronger; a bigger or blurrier shadow can)';
1523
- return null;
1524
- }
1525
-
1526
- /**
1527
- * Apply one step to theme data in memory, as `set` and `undo` do.
1528
- * @param {import('./_settings.mjs').Ctx} ctx
1529
- * @param {string} slug
1530
- * @param {import('./_settings.mjs').ThemeData} d
1531
- * @param {Step} st
1532
- */
1533
- export function apply(ctx, slug, d, st) {
1534
- const unset = st.verb === 'undo';
1535
- const s = checkSetting(
1536
- ctx,
1537
- slug,
1538
- d,
1539
- st.thing,
1540
- st.value,
1541
- {
1542
- on: st.on,
1543
- when: st.when,
1544
- state: st.state,
1545
- mode: st.mode,
1546
- only: st.only,
1547
- // A box shorthand `set` writes as its sides is checked the same way.
1548
- ...(unset ? {} : {sides: true}),
1549
- },
1550
- unset,
1551
- );
1552
- // The sides replace the typed shorthand and each its own earlier entry,
1553
- // as set writes them.
1554
- if (!unset && s.sides?.length) {
1555
- const typed = keyOf(s);
1556
- d.settings = d.settings.filter(x => keyOf(x) !== typed);
1557
- for (const side of s.sides) {
1558
- d.settings = d.settings.filter(x => keyOf(x) !== keyOf(side));
1559
- d.settings.push(side);
1560
- }
1561
- return;
1562
- }
1563
- if (!unset && s.thing === 'mode') {
1564
- d.mode = /** @type {'both' | 'light-only' | 'dark-only'} */ (s.value);
1565
- return;
1566
- }
1567
- if (!unset && s.thing === 'base')
1568
- throw new AstryxError(
1569
- 'how does not check a change of base',
1570
- [],
1571
- ERROR_CODES.ERR_INVALID_ARGUMENT,
1572
- );
1573
- // A border color on a part that draws no border brings the border it
1574
- // needs, as set writes it.
1575
- const edge = unset ? null : borderFor(ctx, slug, d, s);
1576
- const k = keyOf(s);
1577
- // (With a border brought, the color goes after it, as set writes them:
1578
- // a color the theme saves already moves last, never stays before the
1579
- // border, whose shorthand would reset it.)
1580
- if (edge) {
1581
- d.settings = d.settings.filter(x => keyOf(x) !== k);
1582
- d.settings.splice(broughtBorderAt(ctx, d.settings, edge), 0, edge);
1583
- }
1584
- const i = d.settings.findIndex(x => keyOf(x) === k);
1585
- if (unset) {
1586
- if (i < 0)
1587
- throw new AstryxError(
1588
- `the theme does not set ${st.thing}${st.on ? ` on ${st.on}` : ''}`,
1589
- [],
1590
- ERROR_CODES.ERR_THEME_NOT_SET,
1591
- );
1592
- d.settings.splice(i, 1);
1593
- } else if (i >= 0) d.settings[i] = s;
1594
- else d.settings.push(s);
1595
- }
1596
-
1597
- /**
1598
- * A step as the command a person runs.
1599
- * @param {Step} st
1600
- * @param {string} slug
1601
- */
1602
- export function render(st, slug) {
1603
- return [
1604
- P,
1605
- st.verb,
1606
- slug,
1607
- quoteCommandArgument(st.thing),
1608
- ...(st.value != null ? [quoteCommandArgument(st.value)] : []),
1609
- ...(st.on ? ['--on', st.on] : []),
1610
- ...(st.when ? ['--when', st.when] : []),
1611
- ...(st.state ? ['--state', st.state] : []),
1612
- ...(st.mode ? ['--mode', st.mode] : []),
1613
- ...(st.only ? ['--only'] : []),
1614
- ].join(' ');
1615
- }
1616
-
1617
- /**
1618
- * Parse a dial example (`set my corners pill --on button`) into a step.
1619
- * @param {string} example
1620
- * @returns {Step | null}
1621
- */
1622
- export function exampleStep(example) {
1623
- const words = [...example.matchAll(/"((?:[^"\\]|\\.)*)"|(\S+)/g)].map(
1624
- m => m[1] ?? m[2],
1625
- );
1626
- const [verb, , thing, ...rest] = words;
1627
- if (verb !== 'set' || !thing) return null;
1628
- /** @type {Step} */
1629
- const st = {verb: 'set', thing};
1630
- const flag = rest.findIndex(w => w.startsWith('--'));
1631
- const value = (flag < 0 ? rest : rest.slice(0, flag)).join(' ');
1632
- if (value) st.value = value;
1633
- for (let i = flag < 0 ? rest.length : flag; i < rest.length; i += 2) {
1634
- const k = rest[i].slice(2);
1635
- if (k === 'on' || k === 'when' || k === 'state' || k === 'mode')
1636
- st[k] = rest[i + 1];
1637
- }
1638
- return st;
1639
- }
1640
-
1641
- /**
1642
- * Keep the alternatives that pass, and render them for the theme.
1643
- * @param {HowTheme} env
1644
- * @param {Step[][]} options each a list of steps run in order
1645
- * @returns {{commands: string[], refused: Array<{command: string, why: string, run?: string[]}>}}
1646
- */
1647
- export function checked(env, options) {
1648
- /** @type {string[]} */
1649
- const commands = [];
1650
- /** @type {Array<{command: string, why: string, run?: string[]}>} */
1651
- const refused = [];
1652
- for (const steps of options) {
1653
- const text = steps.map(st => render(st, env.slug));
1654
- const r = env.check(steps);
1655
- if (r.ok) commands.push(...text.filter(c => !commands.includes(c)));
1656
- else
1657
- refused.push({
1658
- command: text.join(' && '),
1659
- why: r.why,
1660
- ...(r.run ? {run: r.run} : {}),
1661
- });
1662
- }
1663
- return {commands, refused};
1664
- }