@astryxdesign/cli 0.7.18-canary.gfacee17 → 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 (363) 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 +5 -5
  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 +2 -2
  16. package/api/icon/_adapter.mjs +6 -2
  17. package/api/icon/_authoring.mjs +22 -13
  18. package/api/icon/_default-look.mjs +15 -15
  19. package/api/icon/add/add.mjs +14 -9
  20. package/api/icon/icon.doc.mjs +7 -7
  21. package/api/icon/icon.type.d.mts +33 -33
  22. package/api/icon/icon.type.mjs +45 -45
  23. package/api/icon/iconAdd.doc.mjs +9 -10
  24. package/api/icon/iconMap.doc.mjs +11 -12
  25. package/api/icon/iconNewDefinition.doc.mjs +8 -8
  26. package/api/icon/iconNewSet.doc.mjs +5 -5
  27. package/api/icon/map/map.mjs +7 -7
  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/integration/validate-integration.type.d.mts +6 -6
  32. package/api/integration/validate-integration.type.mjs +6 -6
  33. package/api/render/_adapter.d.mts +5 -3
  34. package/api/render/_adapter.mjs +64 -4
  35. package/api/render/render.doc.mjs +9 -2
  36. package/api/render/render.mjs +5 -2
  37. package/api/render/render.type.d.mts +17 -0
  38. package/api/render/render.type.mjs +10 -0
  39. package/api/search/ORDERING.md +1 -1
  40. package/api/search/_candidate-score.mjs +20 -0
  41. package/api/search/_words.d.mts +8 -0
  42. package/api/search/_words.mjs +15 -0
  43. package/api/template/template.type.d.mts +2 -2
  44. package/api/template/template.type.mjs +2 -2
  45. package/api/theme/_adapter.mjs +19 -11
  46. package/api/theme/build/build.d.mts +19 -51
  47. package/api/theme/build/build.mjs +195 -189
  48. package/api/theme/build/font-warning.d.mts +19 -2
  49. package/api/theme/build/font-warning.mjs +46 -5
  50. package/api/theme/generateTonalPalette.doc.mjs +1 -1
  51. package/api/theme/palette/generate/derive-look.mjs +108 -37
  52. package/api/theme/palette/generate/mapping.mjs +2 -0
  53. package/api/theme/template/template.d.mts +0 -17
  54. package/api/theme/template/template.mjs +1 -42
  55. package/api/theme/theme.type.d.mts +5 -4
  56. package/api/theme/theme.type.mjs +5 -4
  57. package/api/theme/themePaletteGenerate.doc.mjs +1 -1
  58. package/api/theme/themeRemove.doc.mjs +1 -1
  59. package/assets/codemods/transforms/v0.7.0/preserve-bottom-sheet-content-padding.mjs +3 -1
  60. package/assets/component-list.generated.json +1 -1
  61. package/assets/discover/official-packages.json +26 -2
  62. package/assets/docs/author-a-theme.doc.mjs +6 -5
  63. package/assets/docs/browser-support.doc.mjs +1 -0
  64. package/assets/docs/icons.doc.mjs +8 -7
  65. package/assets/docs/motion.doc.mjs +46 -0
  66. package/assets/docs/theme.doc.dense.mjs +6 -17
  67. package/assets/docs/theme.doc.mjs +6 -16
  68. package/assets/docs/theme.doc.zh.mjs +6 -16
  69. package/assets/docs/tree/ci-and-containers.doc.mjs +1 -1
  70. package/assets/docs/tree/data-colors-in-renderers.doc.mjs +400 -0
  71. package/assets/docs/tree/font-setup.doc.mjs +30 -0
  72. package/assets/docs/tree/icon-sets.doc.mjs +2 -2
  73. package/assets/docs/tree/share-a-page.doc.mjs +1 -1
  74. package/assets/docs/tree/template-icons.doc.mjs +3 -3
  75. package/assets/docs/tree/tokens-color.doc.mjs +5 -0
  76. package/assets/docs/tree/tokens.doc.mjs +4 -3
  77. package/assets/docs/tree/updates.doc.mjs +1 -1
  78. package/assets/docs/tree/visualization.doc.mjs +30 -0
  79. package/assets/docs-routes.generated.json +1 -1
  80. package/assets/docs.generated.json +2 -2
  81. package/assets/icons/definitions/drag.doc.mjs +1 -0
  82. package/assets/search-catalog.generated.json +2 -2
  83. package/assets/self-audit.generated.json +1 -1
  84. package/assets/templates/blocks/components/Card/SelectableCardElevated.doc.mjs +1 -1
  85. package/assets/templates/blocks/components/Card/SelectableCardElevated.tsx +20 -10
  86. package/assets/templates/blocks/components/Card/SelectableCardShowcase.doc.mjs +1 -1
  87. package/assets/templates/blocks/components/Card/SelectableCardShowcase.tsx +36 -16
  88. package/assets/templates/blocks/components/ChatComposerInput/ChatComposerInputMentionTrigger.tsx +6 -0
  89. package/assets/templates/blocks/components/ChatComposerInput/ChatComposerInputMultipleTriggers.tsx +6 -0
  90. package/assets/templates/blocks/components/Hooks/useIndicatorFocusRingHookUsage.doc.mjs +14 -0
  91. package/assets/templates/blocks/components/Hooks/useIndicatorFocusRingHookUsage.tsx +63 -0
  92. package/assets/templates/blocks/components/Hooks/useLongPressHookUsage.doc.mjs +29 -0
  93. package/assets/templates/blocks/components/Hooks/useLongPressHookUsage.tsx +237 -0
  94. package/assets/templates/blocks/components/SideNav/SideNavShowcase.tsx +10 -72
  95. package/assets/templates/blocks/components/SideNav/SideNavWithHeaderMenu.doc.mjs +1 -1
  96. package/assets/templates/blocks/components/SideNav/SideNavWithHeaderMenu.tsx +7 -7
  97. package/assets/templates/blocks/components/Table/TableCustomRowTable.doc.mjs +14 -0
  98. package/assets/templates/blocks/components/Table/TableCustomRowTable.tsx +96 -0
  99. package/assets/templates/components.generated.json +1 -1
  100. package/assets/templates/pages/ai-chat-landing/page.tsx +4 -0
  101. package/assets/templates/pages/dashboard-scorecard/page.tsx +26 -7
  102. package/assets/templates/pages/editor/page.tsx +13 -3
  103. package/assets/templates/themes/butter/butterPaletteRefs.generated.ts +2 -2
  104. package/assets/templates/themes/butter/butterTheme.ts +12 -10
  105. package/assets/templates/themes/butter/icons.tsx +2 -0
  106. package/assets/templates/themes/chocolate/chocolateTheme.ts +1 -0
  107. package/assets/templates/themes/chocolate/icons.tsx +2 -0
  108. package/assets/templates/themes/gothic/gothicPaletteRefs.generated.ts +1 -1
  109. package/assets/templates/themes/gothic/gothicTheme.ts +1 -0
  110. package/assets/templates/themes/gothic/icons.tsx +2 -0
  111. package/assets/templates/themes/matcha/icons.tsx +2 -0
  112. package/assets/templates/themes/matcha/matchaPaletteRefs.generated.ts +2 -2
  113. package/assets/templates/themes/matcha/matchaTheme.ts +1 -0
  114. package/assets/templates/themes/neutral/icons.tsx +2 -0
  115. package/assets/templates/themes/neutral/neutralPaletteRefs.generated.ts +2 -2
  116. package/assets/templates/themes/neutral/neutralTheme.ts +1 -0
  117. package/assets/templates/themes/stone/icons.tsx +2 -0
  118. package/assets/templates/themes/stone/stonePaletteRefs.generated.ts +1 -1
  119. package/assets/templates/themes/stone/stoneTheme.ts +1 -0
  120. package/assets/templates/themes/y2k/icons.tsx +2 -0
  121. package/assets/templates/themes/y2k/y2kTheme.ts +1 -0
  122. package/assets/theme.template.ts +9 -5
  123. package/authoring/config/parse.mjs +1 -1
  124. package/authoring/doctypes/base/type.ts +2 -3
  125. package/authoring/doctypes/component/component.doc.mjs +1 -1
  126. package/authoring/doctypes/icon-set/icon-names.mjs +1 -0
  127. package/authoring/integration/integration.doc.mjs +1 -1
  128. package/authoring/integration/type.ts +1 -1
  129. package/clients/cli/build-id.generated.json +1 -1
  130. package/clients/cli/commands/doctor.mjs +2 -2
  131. package/clients/cli/commands/experimental/export.mjs +2 -1
  132. package/clients/cli/commands/experimental/icon.mjs +17 -17
  133. package/clients/cli/commands/experimental/index.mjs +0 -5
  134. package/clients/cli/commands/experimental/render-output.mjs +9 -0
  135. package/clients/cli/commands/experimental-export.doc.mjs +6 -0
  136. package/clients/cli/commands/experimental-icon-add.doc.mjs +8 -8
  137. package/clients/cli/commands/experimental-icon-map.doc.mjs +6 -6
  138. package/clients/cli/commands/experimental-icon-new-definition.doc.mjs +6 -6
  139. package/clients/cli/commands/experimental-icon-new-set.doc.mjs +3 -3
  140. package/clients/cli/commands/experimental-icon-use.doc.mjs +1 -1
  141. package/clients/cli/commands/experimental-icon.doc.mjs +6 -6
  142. package/clients/cli/commands/experimental.doc.mjs +2 -6
  143. package/clients/cli/commands/template.mjs +1 -1
  144. package/clients/cli/commands/theme-build.doc.mjs +8 -1
  145. package/clients/cli/commands/theme-palette-generate.doc.mjs +1 -1
  146. package/clients/cli/commands/theme-remove.doc.mjs +1 -1
  147. package/clients/cli/commands/theme.doc.mjs +1 -11
  148. package/clients/cli/commands/theme.mjs +110 -475
  149. package/clients/cli/commands.generated.json +1 -1
  150. package/clients/cli/index.mjs +4 -34
  151. package/clients/cli/lib/base-gate.mjs +2 -3
  152. package/clients/cli/lib/cli-error.mjs +8 -72
  153. package/clients/cli/lib/define-command.mjs +0 -19
  154. package/clients/cli/lib/json-shim.mjs +11 -633
  155. package/clients/cli/lib/manifest.mjs +0 -4
  156. package/clients/cli/lib/stray-option.mjs +1 -2
  157. package/clients/cli/manifest.generated.json +1 -1
  158. package/foundation/agent-docs/agent-docs.mjs +1 -1
  159. package/foundation/color/css-color.mjs +2 -3
  160. package/foundation/discovery/app-layout.d.mts +13 -0
  161. package/foundation/discovery/app-layout.mjs +35 -0
  162. package/foundation/discovery/cli-self-docs.mjs +4 -4
  163. package/foundation/discovery/fixture-refs.d.mts +51 -0
  164. package/foundation/discovery/fixture-refs.mjs +351 -0
  165. package/foundation/discovery/icon-definition-discovery.mjs +7 -7
  166. package/foundation/discovery/icon-ranking.mjs +2 -2
  167. package/foundation/discovery/icon-set-checks.mjs +6 -6
  168. package/foundation/discovery/icon-set-discovery.mjs +2 -2
  169. package/foundation/discovery/icon-set-writer.d.mts +24 -7
  170. package/foundation/discovery/icon-set-writer.mjs +75 -31
  171. package/foundation/discovery/static-descriptor.d.mts +49 -0
  172. package/foundation/discovery/static-descriptor.mjs +548 -0
  173. package/foundation/discovery/template-adapter.d.mts +0 -47
  174. package/foundation/discovery/template-adapter.mjs +1 -333
  175. package/foundation/discovery/theme-discovery.d.mts +6 -47
  176. package/foundation/discovery/theme-discovery.mjs +15 -537
  177. package/foundation/doc-compiler/bundle.mjs +2 -2
  178. package/foundation/doc-compiler/import.mjs +1 -1
  179. package/foundation/env/user-dirs.d.mts +5 -2
  180. package/foundation/env/user-dirs.mjs +12 -5
  181. package/foundation/fonts/next-font.d.mts +26 -0
  182. package/foundation/fonts/next-font.mjs +149 -0
  183. package/foundation/fs/empty-folder.mjs +2 -2
  184. package/foundation/fs/read-record.mjs +11 -4
  185. package/foundation/pictures/pictures.d.mts +152 -0
  186. package/foundation/pictures/pictures.mjs +565 -0
  187. package/foundation/release/folder-lock.mjs +3 -2
  188. package/foundation/render/cut-short.d.mts +2 -2
  189. package/foundation/render/cut-short.mjs +2 -2
  190. package/foundation/render/drawn-contrast.d.mts +2 -2
  191. package/foundation/render/drawn-contrast.mjs +2 -2
  192. package/foundation/render/font-probe.d.mts +2 -2
  193. package/foundation/render/font-probe.mjs +2 -2
  194. package/foundation/render/layers.mjs +1 -2
  195. package/foundation/render/package-resolve-hooks.d.mts +25 -5
  196. package/foundation/render/package-resolve-hooks.mjs +77 -14
  197. package/foundation/render/page-worker.mjs +24 -12
  198. package/foundation/render/part-boxes.d.mts +2 -3
  199. package/foundation/render/part-boxes.mjs +2 -3
  200. package/foundation/render/picture-chrome.mjs +18 -15
  201. package/foundation/render/picture-playwright.mjs +10 -7
  202. package/foundation/render/picture-window.d.mts +13 -0
  203. package/foundation/render/picture-window.mjs +31 -0
  204. package/foundation/render/render-page.d.mts +1 -1
  205. package/foundation/render/render-page.mjs +4 -5
  206. package/foundation/render/single-copy-hooks.d.mts +2 -0
  207. package/foundation/render/single-copy-hooks.mjs +2 -0
  208. package/foundation/response/error-codes.doc.mjs +14 -14
  209. package/foundation/response/error-codes.mjs +13 -13
  210. package/foundation/response/response-types.doc.mjs +8 -69
  211. package/foundation/runtime/css-tree.mjs +2 -2
  212. package/foundation/runtime/word-table.d.mts +1 -1
  213. package/foundation/runtime/word-table.mjs +1 -1
  214. package/foundation/suggest/other-command.d.mts +52 -15
  215. package/foundation/suggest/other-command.mjs +168 -45
  216. package/foundation/text/suggest-order.d.mts +7 -0
  217. package/foundation/text/suggest-order.mjs +1 -1
  218. package/package.json +7 -8
  219. package/api/theme-edit/_adapter.d.mts +0 -228
  220. package/api/theme-edit/_adapter.mjs +0 -2025
  221. package/api/theme-edit/_catalog.d.mts +0 -172
  222. package/api/theme-edit/_catalog.mjs +0 -806
  223. package/api/theme-edit/_check.d.mts +0 -391
  224. package/api/theme-edit/_check.mjs +0 -9370
  225. package/api/theme-edit/_color.d.mts +0 -135
  226. package/api/theme-edit/_color.mjs +0 -480
  227. package/api/theme-edit/_compiler.d.mts +0 -77
  228. package/api/theme-edit/_compiler.mjs +0 -1053
  229. package/api/theme-edit/_context.d.mts +0 -399
  230. package/api/theme-edit/_context.mjs +0 -1778
  231. package/api/theme-edit/_css.d.mts +0 -169
  232. package/api/theme-edit/_css.mjs +0 -1167
  233. package/api/theme-edit/_edit.d.mts +0 -167
  234. package/api/theme-edit/_edit.mjs +0 -11220
  235. package/api/theme-edit/_how-commands.d.mts +0 -315
  236. package/api/theme-edit/_how-commands.mjs +0 -1664
  237. package/api/theme-edit/_how-question.d.mts +0 -341
  238. package/api/theme-edit/_how-question.mjs +0 -33291
  239. package/api/theme-edit/_how-sides.d.mts +0 -22
  240. package/api/theme-edit/_how-sides.mjs +0 -173
  241. package/api/theme-edit/_how-steps.d.mts +0 -42
  242. package/api/theme-edit/_how-steps.mjs +0 -208
  243. package/api/theme-edit/_how-values.d.mts +0 -29
  244. package/api/theme-edit/_how-values.mjs +0 -111
  245. package/api/theme-edit/_how-words.d.mts +0 -15
  246. package/api/theme-edit/_how-words.mjs +0 -239
  247. package/api/theme-edit/_how.d.mts +0 -55
  248. package/api/theme-edit/_how.mjs +0 -2388
  249. package/api/theme-edit/_importers.d.mts +0 -38
  250. package/api/theme-edit/_importers.mjs +0 -188
  251. package/api/theme-edit/_marks.d.mts +0 -39
  252. package/api/theme-edit/_marks.mjs +0 -67
  253. package/api/theme-edit/_missed.d.mts +0 -56
  254. package/api/theme-edit/_missed.mjs +0 -1128
  255. package/api/theme-edit/_name-rule.d.mts +0 -11
  256. package/api/theme-edit/_name-rule.mjs +0 -12
  257. package/api/theme-edit/_normal.d.mts +0 -365
  258. package/api/theme-edit/_normal.mjs +0 -1978
  259. package/api/theme-edit/_overview.d.mts +0 -9
  260. package/api/theme-edit/_overview.mjs +0 -293
  261. package/api/theme-edit/_palette.d.mts +0 -616
  262. package/api/theme-edit/_palette.mjs +0 -2776
  263. package/api/theme-edit/_part-pieces.d.mts +0 -54
  264. package/api/theme-edit/_part-pieces.mjs +0 -179
  265. package/api/theme-edit/_part-words.d.mts +0 -39
  266. package/api/theme-edit/_part-words.mjs +0 -242
  267. package/api/theme-edit/_parts.d.mts +0 -402
  268. package/api/theme-edit/_parts.mjs +0 -2294
  269. package/api/theme-edit/_picture-traits.d.mts +0 -259
  270. package/api/theme-edit/_picture-traits.mjs +0 -1030
  271. package/api/theme-edit/_png.d.mts +0 -94
  272. package/api/theme-edit/_png.mjs +0 -479
  273. package/api/theme-edit/_preview-app.d.mts +0 -172
  274. package/api/theme-edit/_preview-app.mjs +0 -6430
  275. package/api/theme-edit/_preview.d.mts +0 -549
  276. package/api/theme-edit/_preview.mjs +0 -3264
  277. package/api/theme-edit/_project.d.mts +0 -207
  278. package/api/theme-edit/_project.mjs +0 -643
  279. package/api/theme-edit/_resolved.d.mts +0 -46
  280. package/api/theme-edit/_resolved.mjs +0 -800
  281. package/api/theme-edit/_set-line.d.mts +0 -29
  282. package/api/theme-edit/_set-line.mjs +0 -100
  283. package/api/theme-edit/_settings.d.mts +0 -2426
  284. package/api/theme-edit/_settings.mjs +0 -18435
  285. package/api/theme-edit/_tables.d.mts +0 -227
  286. package/api/theme-edit/_tables.mjs +0 -1128
  287. package/api/theme-edit/_text-looks.d.mts +0 -78
  288. package/api/theme-edit/_text-looks.mjs +0 -376
  289. package/api/theme-edit/_vet.d.mts +0 -50
  290. package/api/theme-edit/_vet.mjs +0 -166
  291. package/api/theme-edit/how/how.d.mts +0 -17
  292. package/api/theme-edit/how/how.mjs +0 -28
  293. package/api/theme-edit/new/new.d.mts +0 -11
  294. package/api/theme-edit/new/new.mjs +0 -22
  295. package/api/theme-edit/preview-add/preview-add.d.mts +0 -14
  296. package/api/theme-edit/preview-add/preview-add.mjs +0 -25
  297. package/api/theme-edit/preview-app/preview-app.d.mts +0 -13
  298. package/api/theme-edit/preview-app/preview-app.mjs +0 -24
  299. package/api/theme-edit/preview-list/preview-list.d.mts +0 -10
  300. package/api/theme-edit/preview-list/preview-list.mjs +0 -21
  301. package/api/theme-edit/preview-remove/preview-remove.d.mts +0 -12
  302. package/api/theme-edit/preview-remove/preview-remove.mjs +0 -23
  303. package/api/theme-edit/set/set.d.mts +0 -13
  304. package/api/theme-edit/set/set.mjs +0 -24
  305. package/api/theme-edit/show/show.d.mts +0 -13
  306. package/api/theme-edit/show/show.mjs +0 -24
  307. package/api/theme-edit/theme-edit.d.mts +0 -12
  308. package/api/theme-edit/theme-edit.mjs +0 -36
  309. package/api/theme-edit/theme-edit.type.d.mts +0 -730
  310. package/api/theme-edit/theme-edit.type.mjs +0 -342
  311. package/api/theme-edit/themeEditHow.doc.d.mts +0 -6
  312. package/api/theme-edit/themeEditHow.doc.mjs +0 -105
  313. package/api/theme-edit/themeEditNew.doc.d.mts +0 -5
  314. package/api/theme-edit/themeEditNew.doc.mjs +0 -112
  315. package/api/theme-edit/themeEditPreviewAdd.doc.d.mts +0 -6
  316. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +0 -121
  317. package/api/theme-edit/themeEditPreviewApp.doc.d.mts +0 -6
  318. package/api/theme-edit/themeEditPreviewApp.doc.mjs +0 -87
  319. package/api/theme-edit/themeEditPreviewList.doc.d.mts +0 -6
  320. package/api/theme-edit/themeEditPreviewList.doc.mjs +0 -62
  321. package/api/theme-edit/themeEditPreviewRemove.doc.d.mts +0 -6
  322. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +0 -96
  323. package/api/theme-edit/themeEditSet.doc.d.mts +0 -6
  324. package/api/theme-edit/themeEditSet.doc.mjs +0 -175
  325. package/api/theme-edit/themeEditShow.doc.d.mts +0 -6
  326. package/api/theme-edit/themeEditShow.doc.mjs +0 -118
  327. package/api/theme-edit/themeEditUndo.doc.d.mts +0 -6
  328. package/api/theme-edit/themeEditUndo.doc.mjs +0 -133
  329. package/api/theme-edit/undo/undo.d.mts +0 -13
  330. package/api/theme-edit/undo/undo.mjs +0 -24
  331. package/assets/preview-app/README.md +0 -6
  332. package/assets/preview-app/css.d.ts +0 -5
  333. package/assets/preview-app/gitignore +0 -4
  334. package/assets/preview-app/next.config.mjs +0 -12
  335. package/assets/preview-app/package.json +0 -24
  336. package/assets/preview-app/src/app/globals.css +0 -6
  337. package/assets/preview-app/src/app/layout.tsx +0 -21
  338. package/assets/preview-app/src/app/page.tsx +0 -94
  339. package/assets/preview-app/src/app/providers.tsx +0 -16
  340. package/assets/preview-app/tsconfig.json +0 -27
  341. package/clients/cli/commands/experimental/theme.mjs +0 -2990
  342. package/clients/cli/commands/experimental-theme-add.doc.mjs +0 -80
  343. package/clients/cli/commands/experimental-theme-compile.doc.mjs +0 -98
  344. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +0 -196
  345. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +0 -174
  346. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +0 -139
  347. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +0 -77
  348. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +0 -105
  349. package/clients/cli/commands/experimental-theme-editor.doc.mjs +0 -49
  350. package/clients/cli/commands/experimental-theme-eject.doc.mjs +0 -72
  351. package/clients/cli/commands/experimental-theme-list.doc.mjs +0 -49
  352. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +0 -88
  353. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +0 -61
  354. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +0 -48
  355. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +0 -59
  356. package/clients/cli/commands/experimental-theme-preview.doc.mjs +0 -41
  357. package/clients/cli/commands/experimental-theme-remove.doc.mjs +0 -57
  358. package/clients/cli/commands/experimental-theme-targets.doc.mjs +0 -62
  359. package/clients/cli/commands/experimental-theme-template.doc.mjs +0 -63
  360. package/clients/cli/commands/experimental-theme-use.doc.mjs +0 -57
  361. package/clients/cli/commands/experimental-theme.doc.mjs +0 -60
  362. package/foundation/fonts/fontsource-families.generated.d.mts +0 -5
  363. package/foundation/fonts/fontsource-families.generated.mjs +0 -2110
@@ -1,2294 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
-
3
- /**
4
- * @file What each themeable part reads, derived from the installed Core
5
- * itself: render a catalog of every component on the server with the
6
- * project's own React (the machinery of `astryx experimental export`), then
7
- * join each element's classes to the rules in Core's shipped stylesheet.
8
- * The result names, for every part, the CSS properties it sets and the
9
- * public tokens that feed each one (under which variant or state), the parts
10
- * inside it, the variant values seen, and the real text-on-background pairs.
11
- *
12
- * It needs no browser. It is cached per Core version (and stylesheet) under
13
- * node_modules/.cache/astryx-theme/, so it is built once per install.
14
- *
15
- * @position api/theme-edit — part data for the checks, and `how`
16
- */
17
-
18
- import * as fs from 'node:fs';
19
- import * as os from 'node:os';
20
- import * as path from 'node:path';
21
- import {createHash} from 'node:crypto';
22
- import {createRequire} from 'node:module';
23
- import {fileURLToPath} from 'node:url';
24
- import {AstryxError} from '../error.mjs';
25
- import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
26
- import {importPathOf, installLine, literals} from './_project.mjs';
27
- import {removeEmptyFolder} from '../../foundation/fs/empty-folder.mjs';
28
- import {sidesOf} from './_css.mjs';
29
-
30
- /** Text properties CSS inherits, which a part passes to the text inside it. */
31
- export const INHERITED_TEXT =
32
- /^(font-(size|weight|style|family|variant)|text-(transform|align)|letter-spacing|line-height|white-space|word-spacing)$/;
33
- import {VOID} from '../../foundation/render/html-reader.mjs';
34
- import {
35
- RENDER_TIMEOUT_MS,
36
- renderPage,
37
- RenderError,
38
- } from '../../foundation/render/render-page.mjs';
39
- import {
40
- SAMPLE_PAGE,
41
- SAMPLE_SOURCE,
42
- elementNames,
43
- pageSource,
44
- } from './_catalog.mjs';
45
- import {removeOnStop} from '../../foundation/fs/stop-cleanup.mjs';
46
- import {
47
- fileStamp,
48
- recordContentRead,
49
- } from '../../foundation/fs/read-record.mjs';
50
-
51
- /**
52
- * A fingerprint of a module and every file it imports by a relative path,
53
- * read once: what a cache built by that code is keyed by, so any change to
54
- * the code builds it again, with no number to bump by hand (the installed
55
- * Core is the cache folder's own key).
56
- * @param {string} url the module's own `import.meta.url`
57
- */
58
- export function codeFingerprint(url) {
59
- const hash = createHash('sha256');
60
- /** @type {Set<string>} */
61
- const seen = new Set();
62
- /** @param {string} file */
63
- const walk = file => {
64
- if (seen.has(file)) return;
65
- seen.add(file);
66
- /** @type {string} */
67
- let src;
68
- try {
69
- src = fs.readFileSync(file, 'utf8');
70
- } catch {
71
- return;
72
- }
73
- hash.update(`${path.basename(file)}\0${src}\0`);
74
- for (const m of src.matchAll(
75
- /(?:\bfrom|\bimport\s*\(?)\s*['"](\.{1,2}\/[^'"]+)['"]/g,
76
- ))
77
- walk(path.resolve(path.dirname(file), m[1]));
78
- };
79
- walk(fileURLToPath(url));
80
- return hash.digest('hex').slice(0, 16);
81
- }
82
-
83
- /** What the cached part data is built by ({@link codeFingerprint}). */
84
- const CENSUS_KEY = codeFingerprint(import.meta.url);
85
-
86
- /**
87
- * Flags that change what a component does or whether it shows, not how it
88
- * looks: the catalog never turns them on (disabled has its own entry).
89
- */
90
- const LIFECYCLE_FLAGS = new Set([
91
- 'isDisabled',
92
- 'isOpen',
93
- 'isDefaultOpen',
94
- 'hasAutoFocus',
95
- 'isHidden',
96
- ]);
97
-
98
- /**
99
- * @typedef {object} PartRecord
100
- * @property {Record<string, {tokens: Record<string, string[]>, values: string[]}>} own - property -> tokens (with conditions) and raw values
101
- * @property {Record<string, Record<string, string>>} [at] - property -> the value under each condition, private variables resolved
102
- * @property {Record<string, string[]>} inside - tokens read by unnamed elements inside the part -> properties
103
- * @property {Record<string, string[]>} [innerSets] - inherited text properties a visible unnamed element inside the part that holds text sets to values of its own -> those values (a code block's lines: white-space pre or pre-wrap)
104
- * @property {Record<string, string[]>} attrs - data attributes seen on the part
105
- * @property {string[]} contains - parts rendered inside it
106
- * @property {string[]} [drawnAs] - the other parts drawn on the same element (a select's option is drawn as an Item)
107
- * @property {string[]} [repeats] - parts it holds more than one of side by side, as the nearest part around them (a shortcut's keys, a button group's buttons)
108
- * @property {string[]} [listed] - the parts inside it drawn more than once in one of its elements (a menu's items), unlike a part drawn there once (a header's nav)
109
- * @property {Record<string, string[]>} [holdsVariants] - for a part rendered inside it, the variants it is drawn in there (a toast's close button: ghost)
110
- * @property {string[]} [tags] - the elements it is rendered as (`tr` for a table row)
111
- * @property {string} [underInput] - drawn under an invisible native input
112
- * laid over it (a checkbox's box), which takes its pointer and focus: the
113
- * part that holds that input (empty when none is themed)
114
- * @property {string[]} [innerCorners] - the radius tokens of the corners Core draws by place on the parts directly inside it (a button group's end buttons)
115
- * @property {Record<string, string[]>} [held] - the tokens the parts inside it draw with there, at rest, and the properties they set with each
116
- * @property {string[]} [line] - the properties a line inside it with no target of its own draws (a divider's line), recorded as the part's: a setting on the part's own element does not reach them
117
- * @property {boolean} [media] - Core's media surface sits inside it (a toast's inverted surface), setting the text tokens of what it holds from --color-on-dark and --color-on-light
118
- * @property {string[]} [mediaSides] - the sides that media surface took where the census drew it (`dark`, `light`)
119
- * @property {Record<string, Record<string, string>>} [inline] - state ('' for always) -> property -> the token Core paints it with as an inline style, which no theme rule can replace
120
- */
121
-
122
- /**
123
- * @typedef {{target: string | null, tokens: string[], raw: string | null}} PaintSide
124
- * @typedef {{text: string, fg: PaintSide, bg: PaintSide, sample: string, over?: PaintSide, within?: string[]}} TextPair
125
- * `over`: the region the part sits in (a header), whose background shows
126
- * through a see-through background of the part's own, else the page
127
- * @typedef {{censusKey: string, coreKey: string, map: Record<string, PartRecord>, pairs: TextPair[], rendered: number, items: number}} PartData
128
- */
129
-
130
- /** The days a sample date and range of days stand on. */
131
- const SAMPLE_DAYS = {start: '2026-01-12', end: '2026-01-16'};
132
-
133
- /**
134
- * A sample value for a required prop the doc declares, from its type: the
135
- * component's name for text, false for a flag, the first value of a union,
136
- * else null where the type allows it.
137
- * Undefined for a type with no plain sample, such as a function.
138
- * @param {string} name
139
- * @param {string} type
140
- * @returns {unknown}
141
- */
142
- function sampleOf(name, type) {
143
- if (type.includes('=>')) return undefined;
144
- // Null and undefined are the absence of a value, never a sample.
145
- const t = type
146
- .split('|')
147
- .map(x => x.trim())
148
- .filter(x => x !== 'null' && x !== 'undefined')
149
- .join(' | ');
150
- if (t === 'string' || /ReactNode$/.test(t)) return name;
151
- if (t === 'boolean') return false;
152
- if (t === 'number') return 1;
153
- // A search source: the page's sample one, a few fixed items.
154
- if (/^SearchSource\b/.test(t)) return SAMPLE_SOURCE;
155
- const words = literals(t);
156
- if (words.length) return words[0];
157
- if (/^\d+(\s*\|\s*\d+)*$/.test(t)) return Number(t.split('|')[0]);
158
- // A date, and a range of days (a calendar's in range): fixed days, so
159
- // the part data reads the same whatever day it is drawn on.
160
- if (t === 'ISODateString') return SAMPLE_DAYS.start;
161
- if (t === 'DateRange') return {...SAMPLE_DAYS};
162
- // A value the type lets be null (a file input's chosen file): none
163
- // chosen, when nothing plainer stands for it.
164
- if (/(^|\|)\s*null\s*(\||$)/.test(type)) return null;
165
- return undefined;
166
- }
167
-
168
- /**
169
- * Three items made from the element the doc suggests for a group's
170
- * children, each with its own label and value; the first takes the group's
171
- * value, so it shows selected.
172
- * @param {{__element: string, props?: Record<string, unknown>, children?: unknown}} slot
173
- * @param {unknown} selected
174
- */
175
- function slotItems(slot, selected) {
176
- // (A group of many values, a checkbox list's, selects by a list.)
177
- if (Array.isArray(selected)) selected = selected[0];
178
- return [1, 2, 3].map(i => {
179
- const props = {...(slot.props ?? {})};
180
- if (typeof props.label === 'string') props.label = `${props.label} ${i}`;
181
- if ('value' in props || typeof selected === 'string')
182
- props.value =
183
- i === 1 && typeof selected === 'string'
184
- ? selected
185
- : `${String(props.value ?? 'item')}-${i}`;
186
- return {...slot, props};
187
- });
188
- }
189
-
190
- /**
191
- * The props a component renders with: its doc's playground defaults, or,
192
- * for a doc with none (an older Core), a sample for each required prop.
193
- * A group with no children gets three of the items its doc suggests. Null
194
- * for a doc with no defaults that has no theming targets (a hook or a
195
- * helper), or that is a part its parent lists as an item: it works only
196
- * inside the parent, whose own entry shows it.
197
- * @param {import('./_project.mjs').ThemeProject} project
198
- * @param {string} name
199
- * @returns {Record<string, unknown> | null}
200
- */
201
- export function demoProps(project, name) {
202
- const info = project.components[name];
203
- const given =
204
- info.defaults && typeof info.defaults === 'object'
205
- ? /** @type {Record<string, unknown>} */ ({...info.defaults})
206
- : null;
207
- if (
208
- !given &&
209
- // Only a component a theme styles: hooks, providers and helpers have
210
- // docs too, and render nothing.
211
- (!/^[A-Z]/.test(name) ||
212
- !info.targets.length ||
213
- // A doc that declares no props of its own name is a family page,
214
- // not a component the Core exports.
215
- !Object.keys(info.props ?? {}).length ||
216
- needsParent(project, name))
217
- )
218
- return null;
219
- const props = given ?? {};
220
- // A required prop its defaults leave out (a status dot's variant, a
221
- // command palette's search source) takes its sample, as for a doc with no
222
- // defaults: without it the part draws nothing (no color, no list).
223
- if (given)
224
- for (const [p, d] of Object.entries(info.props ?? {})) {
225
- if (p in props || /^on[A-Z]/.test(p) || p === 'children') continue;
226
- if (!d.required && !/^SearchSource\b/.test(d.type)) continue;
227
- const v = d.slots?.[0] ?? sampleOf(name, d.type);
228
- if (v !== undefined) props[p] = v;
229
- }
230
- if (!given)
231
- for (const [p, d] of Object.entries(info.props ?? {})) {
232
- if (!d.required || /^on[A-Z]/.test(p)) continue;
233
- if (p === 'children' && d.slots.length) continue;
234
- // A value the type allows to be null (`T | null`, nothing chosen yet)
235
- // with no plain sample is null.
236
- // A prop the doc suggests elements for (a nav icon's icon) takes the
237
- // first of them: a plain sample would draw its own text in their place.
238
- const v =
239
- d.slots?.[0] ??
240
- sampleOf(name, d.type) ??
241
- (/(^|\|)\s*null\s*($|\|)/.test(d.type) ? null : undefined);
242
- // A required prop with no plain sample, such as a render function:
243
- // the component cannot be shown from its doc alone.
244
- if (v === undefined) return null;
245
- props[p] = v;
246
- }
247
- const kids = info.props?.children;
248
- // A part whose children are required and whose doc suggests none (a
249
- // dropdown menu's submenu, whose children are its flyout's rows) gets
250
- // three of its parent's item part (DropdownMenuItem), as a group gets its
251
- // slot's: drawn open, an empty flyout shows nothing of the theme.
252
- const parentItem =
253
- kids?.required && !kids.slots?.length && info.subComponentOf
254
- ? `${info.subComponentOf}Item`
255
- : null;
256
- const slot =
257
- kids?.slots?.[0] ??
258
- (parentItem && project.components[parentItem]?.props?.label
259
- ? {__element: parentItem, props: {label: 'Item'}}
260
- : undefined);
261
- if (!('children' in props) && kids) {
262
- if (slot?.__element && (kids.required || slot.__element.startsWith(name))) {
263
- if (
264
- info.props.value &&
265
- !('value' in props) &&
266
- slot.props?.value != null
267
- ) {
268
- // A group that holds many values (a checkbox list's `string[]`)
269
- // takes them as a list.
270
- const first = `${String(slot.props.value)}-1`;
271
- props.value = /\[\]\s*$/.test(String(info.props.value.type ?? ''))
272
- ? [first]
273
- : first;
274
- }
275
- props.children = slotItems(slot, props.value);
276
- // The first item shows the icon its doc lets it take (a menu row's
277
- // leading icon), so the paint Core gives an item's icon is read.
278
- const iconProp = Object.entries(
279
- project.components[slot.__element]?.props ?? {},
280
- ).find(
281
- ([p, d]) =>
282
- /^(icon|startIcon|leadingIcon)$/.test(p) &&
283
- /IconType|IconName/.test(String(/** @type {any} */ (d)?.type ?? '')),
284
- )?.[0];
285
- const first = /** @type {any} */ (props.children)[0];
286
- if (iconProp && first && first.props?.[iconProp] == null)
287
- first.props = {...first.props, [iconProp]: 'check'};
288
- }
289
- }
290
- return props;
291
- }
292
-
293
- /**
294
- * Whether a part works only inside its parent: its parent lists it as an
295
- * item, or it is a piece of its parent by name (TableBody of Table) and
296
- * its doc gives no playground of its own.
297
- * @param {import('./_project.mjs').ThemeProject} project
298
- * @param {string} name
299
- */
300
- export function needsParent(project, name) {
301
- const info = project.components[name];
302
- const parent = info?.subComponentOf;
303
- if (!parent) return false;
304
- if (isItemOf(project, name)) return true;
305
- const own = info.defaults && typeof info.defaults === 'object';
306
- return !own && name.startsWith(parent) && name !== parent;
307
- }
308
-
309
- /**
310
- * Whether a part's parent lists it as an item of its children.
311
- * @param {import('./_project.mjs').ThemeProject} project
312
- * @param {string} name
313
- */
314
- export function isItemOf(project, name) {
315
- const parent = project.components[name]?.subComponentOf;
316
- const slots = parent
317
- ? (project.components[parent]?.props?.children?.slots ?? [])
318
- : [];
319
- return slots.some(s => s?.__element === name);
320
- }
321
-
322
- /**
323
- * A component's catalog entries, all from its doc: its demo props
324
- * ({@link demoProps}), then once per value of each visual prop with a
325
- * closed set of values (`variant`, `status`, `color`, and a number union
326
- * such as a heading's level), its checked and disabled states, and each look
327
- * flag (`isStriped`) turned on. An
328
- * overlay the playground shows in place renders open; on a page people
329
- * see, once, as some of its variants size the window, not the card.
330
- * @param {import('./_project.mjs').ThemeProject} project
331
- * @param {string} name
332
- * @param {number} cap at most this many
333
- * @param {{shown?: boolean}} [opts] `shown`: for a page people see
334
- * @returns {Array<{label: string, props: Record<string, unknown>}>}
335
- */
336
- export function catalogVariants(project, name, cap, opts = {}) {
337
- const info = project.components[name];
338
- const own = demoProps(project, name);
339
- if (!own) return [];
340
- // No demo takes focus as it mounts: on a page of many, each would pull
341
- // the page to itself.
342
- /** @type {Record<string, unknown>} */
343
- const demo = {
344
- ...own,
345
- ...(info.props?.hasAutoFocus ? {hasAutoFocus: false} : {}),
346
- ...(info.props?.autoFocus && own.autoFocus ? {autoFocus: false} : {}),
347
- };
348
- // An overlay shown open, named, as a dialog must be.
349
- /** @param {Record<string, unknown>} d @returns {Record<string, unknown>} */
350
- const opened = d => ({
351
- ...d,
352
- ...('isOpen' in d ? {} : {isOpen: true}),
353
- ...(info.props?.label && d.label == null ? {label: `${name} example`} : {}),
354
- });
355
- if (info.opens && opts.shown) return [{label: '', props: opened(demo)}];
356
- const base = info.opens ? opened(demo) : demo;
357
- const values = info.targets[0]?.values ?? {};
358
- const variants = [{label: '', props: base}];
359
- // Every prop that changes the look, one sample per value (a variant, a
360
- // status, a toast's type, an avatar's shape); a size is read at the one
361
- // size drawn.
362
- // (A number scale, a heading's level, is drawn below.)
363
- for (const p of Object.keys(values).filter(
364
- k =>
365
- !/^(size|density|elevation)$/.test(k) &&
366
- info.props?.[k] &&
367
- !/^\s*\d+(\s*\|\s*\d+)*\s*$/.test(info.props[k].type ?? ''),
368
- ))
369
- for (const v of values[p] ?? []) {
370
- // A value kind the look names (a calendar's `range` mode, whose value
371
- // is a DateRange): a sample of that kind, so what Core draws for it
372
- // (the days in the range) is read too.
373
- const kind = String(info.props?.value?.type ?? '')
374
- .split('|')
375
- .map(x => x.trim())
376
- .find(x =>
377
- new RegExp(`${v[0]?.toUpperCase() ?? ''}${v.slice(1)}$`).test(x),
378
- );
379
- const sample = kind ? sampleOf(name, kind) : undefined;
380
- variants.push({
381
- label: v,
382
- // A status like `{type: 'error', message?: string}` takes the
383
- // value as its `type`; the bare string breaks the component.
384
- props: {
385
- ...base,
386
- [p]: info.props?.[p]?.type.startsWith('{') ? {type: v} : v,
387
- ...(sample != null && /^[a-z]/.test(v) ? {value: sample} : {}),
388
- },
389
- });
390
- }
391
- // The states the doc names that a prop sets: checked (a boolean value)
392
- // and disabled. The label says the state shown.
393
- const states = new Set(info.targets.flatMap(t => t.states ?? []));
394
- // A value the doc lists beside true and false (a checkbox's
395
- // 'indeterminate'): rendered too, so the look Core gives it is read.
396
- if (states.has('checked'))
397
- for (const word of literals(info.props?.value?.type ?? ''))
398
- if (word !== 'true' && word !== 'false')
399
- variants.push({label: word, props: {...base, value: word}});
400
- if (states.has('checked') && info.props?.value?.type.startsWith('boolean')) {
401
- const on = base.value !== true;
402
- variants.push({
403
- label: on ? 'on' : 'off',
404
- props: {
405
- ...base,
406
- value: on,
407
- ...(typeof base.label === 'string' ? {label: on ? 'On' : 'Off'} : {}),
408
- },
409
- });
410
- }
411
- if (states.has('disabled') && info.props?.isDisabled)
412
- variants.push({label: 'disabled', props: {...base, isDisabled: true}});
413
- for (const p of Object.keys(values)) {
414
- const type = info.props?.[p]?.type ?? '';
415
- if (!/^\s*\d+(\s*\|\s*\d+)*\s*$/.test(type)) continue;
416
- for (const n of type.split('|').map(Number))
417
- if (n !== base[p])
418
- variants.push({label: `${p} ${n}`, props: {...base, [p]: n}});
419
- }
420
- // Each look flag the doc names (`isStriped`, `hasHover`), turned on, so
421
- // the styles Core gives only under it are read too: a table row's hover
422
- // and stripes come from its table's flags.
423
- for (const [p, doc] of Object.entries(info.props ?? {}))
424
- if (
425
- /^(is|has)[A-Z]/.test(p) &&
426
- !LIFECYCLE_FLAGS.has(p) &&
427
- String(/** @type {any} */ (doc)?.type ?? '').trim() === 'boolean' &&
428
- base[p] !== true
429
- )
430
- variants.push({
431
- label: p,
432
- props: {...base, [p]: true, ...flagNeeds(info, p, base)},
433
- });
434
- return variants.slice(0, cap);
435
- }
436
-
437
- /**
438
- * What a look flag needs to show its look: the prop its name starts with
439
- * (`isIconOnly` reads `icon`), given the first element its doc suggests when
440
- * the sample leaves it empty. Without it an icon-only button is an empty
441
- * square.
442
- * @param {any} info
443
- * @param {string} flag
444
- * @param {Record<string, unknown>} base
445
- * @returns {Record<string, unknown>}
446
- */
447
- function flagNeeds(info, flag, base) {
448
- const word = /^(?:is|has)([A-Z][a-z0-9]*)/.exec(flag)?.[1];
449
- const prop = word ? word[0].toLowerCase() + word.slice(1) : '';
450
- const slot = info.props?.[prop]?.slots?.[0];
451
- return prop && prop !== flag && slot && base[prop] == null
452
- ? {[prop]: slot}
453
- : {};
454
- }
455
-
456
- /**
457
- * The catalog: each component with playground defaults, once per visual
458
- * variant value ({@link catalogVariants}), and the sample page.
459
- * @param {import('./_project.mjs').ThemeProject} project
460
- * @returns {{items: import('./_catalog.mjs').CatalogItem[], imports: Record<string, string>}}
461
- */
462
- export function catalogItems(project) {
463
- /** @type {import('./_catalog.mjs').CatalogItem[]} */
464
- const items = [];
465
- for (const name of Object.keys(project.components))
466
- for (const v of catalogVariants(project, name, 24))
467
- items.push({
468
- name,
469
- label: v.label,
470
- tree: {__element: name, props: v.props},
471
- });
472
- // (A component whose layout changes at phone width renders that layout
473
- // too, from its doc's mobile props over its demo: AppShell's menu button
474
- // in the top bar and its open drawer.)
475
- for (const [name, info] of Object.entries(project.components)) {
476
- const mobile = /** @type {any} */ (info).mobile;
477
- if (!mobile) continue;
478
- const demo = demoProps(project, name);
479
- if (!demo) continue;
480
- items.push({
481
- name,
482
- label: 'mobile',
483
- tree: {__element: name, props: {...demo, ...mobile}},
484
- });
485
- }
486
- /** @type {Record<string, string>} */
487
- const imports = {};
488
- for (const n of elementNames([items.map(i => i.tree), SAMPLE_PAGE])) {
489
- const spec = importPathOf(project, n);
490
- if (spec) imports[n] = spec;
491
- }
492
- return {items, imports};
493
- }
494
-
495
- /**
496
- * What of React the project cannot resolve (react, react-dom/server), to
497
- * render the editor's pages; empty when both resolve.
498
- * @param {string} cwd
499
- * @returns {string[]}
500
- */
501
- export function reactMissing(cwd) {
502
- const req = createRequire(path.join(cwd, 'package.json'));
503
- return ['react', 'react-dom/server'].filter(m => {
504
- try {
505
- req.resolve(m);
506
- return false;
507
- } catch {
508
- return true;
509
- }
510
- });
511
- }
512
-
513
- /** How long the editor's own pages may take to render. */
514
- const EDITOR_RENDER_MS = 3 * RENDER_TIMEOUT_MS;
515
-
516
- /** One name per process, so two commands at once never share a folder. */
517
- const RUN = `${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
518
-
519
- /**
520
- * The folder generated pages render from: inside the project but outside
521
- * node_modules, so the render compiles them and their stylesheet imports as
522
- * the project's own. Its name is this process's own, and it is removed
523
- * after each render.
524
- * @param {import('./_project.mjs').ThemeProject} project
525
- */
526
- export const renderDir = project =>
527
- path.join(project.cwd, 'themes', `.astryx-render-${RUN}`);
528
-
529
- /** The file in a render folder that names the process that made it. */
530
- const RENDER_OWNER = '.astryx-render-owner.json';
531
- /** The renders of this process running now, which share its render folder. */
532
- let rendersInFlight = 0;
533
-
534
- /**
535
- * The process space this process runs in: its host and, on Linux, its pid
536
- * namespace, so a process id read from a render folder's owner file is
537
- * known to be this machine's own (a container that shares the project
538
- * folder has another).
539
- */
540
- const processSpace = () => {
541
- let namespace = '';
542
- try {
543
- namespace = fs.readlinkSync('/proc/self/ns/pid');
544
- } catch {
545
- // No pid namespaces here.
546
- }
547
- return `${os.hostname()}\0${namespace}`;
548
- };
549
-
550
- /**
551
- * Whether the process that made a render folder is known to be gone: its
552
- * owner file names this process space, and no process has its id.
553
- * @param {string} dir
554
- * @param {number} pid
555
- */
556
- function renderOwnerGone(dir, pid) {
557
- /** @type {any} */
558
- let owner;
559
- try {
560
- owner = JSON.parse(fs.readFileSync(path.join(dir, RENDER_OWNER), 'utf8'));
561
- } catch {
562
- return false;
563
- }
564
- if (owner?.space !== processSpace() || owner?.pid !== pid) return false;
565
- try {
566
- process.kill(pid, 0);
567
- return false;
568
- } catch (error) {
569
- return /** @type {any} */ (error)?.code === 'ESRCH';
570
- }
571
- }
572
-
573
- /**
574
- * Remove render folders a stopped command left (killed, out of memory):
575
- * `.astryx-render-<pid>-<random>` folders whose maker is known to be gone
576
- * (its owner file names this process space, and no process has its id),
577
- * else only those more than ten minutes old. Links are never followed.
578
- * @param {string} themes
579
- */
580
- function sweepRenders(themes) {
581
- let names;
582
- try {
583
- names = fs.readdirSync(themes);
584
- } catch {
585
- return;
586
- }
587
- for (const n of names) {
588
- const m = /^\.astryx-render-(\d+)-[a-z0-9]+$/.exec(n);
589
- if (!m || Number(m[1]) === process.pid) continue;
590
- const p = path.join(themes, n);
591
- // A folder whose maker is known gone is a leftover at once. A process id
592
- // from another process space may look gone or alive here, so there age
593
- // decides: a render takes at most three minutes, and a folder older than
594
- // ten is a leftover.
595
- /** @type {import('node:fs').Stats} */
596
- let stat;
597
- try {
598
- stat = fs.lstatSync(p);
599
- } catch {
600
- continue;
601
- }
602
- if (!stat.isDirectory()) continue;
603
- if (
604
- !renderOwnerGone(p, Number(m[1])) &&
605
- Date.now() - stat.mtimeMs < 10 * 60_000
606
- )
607
- continue;
608
- try {
609
- if (fs.lstatSync(p).isDirectory())
610
- fs.rmSync(p, {recursive: true, force: true});
611
- } catch {
612
- // Gone already.
613
- }
614
- }
615
- }
616
-
617
- /**
618
- * Render a generated page module and give its HTML and markup (the body,
619
- * without the embedded source block).
620
- * @param {import('./_project.mjs').ThemeProject} project
621
- * @param {string} file name inside the render folder
622
- * @param {string} source
623
- * @param {Array<{name: string, from?: string, text?: string}>} [extra] files
624
- * written beside it: `text` as given, else a copy of `from`
625
- * @param {{openLayers?: boolean}} [opts] `openLayers`: the overlays it shows
626
- * or opens are drawn and added after its markup
627
- * @returns {Promise<{html: string, markup: string}>}
628
- */
629
- export async function renderGenerated(
630
- project,
631
- file,
632
- source,
633
- extra = [],
634
- opts = {},
635
- ) {
636
- const dir = renderDir(project);
637
- // A lookup in an app with no themes must not leave a themes/ folder.
638
- const themes = path.dirname(dir);
639
- // A themes/ folder that holds only other renders was made by another
640
- // lookup running beside this one, so it is ours to remove too.
641
- sweepRenders(themes);
642
- const madeThemes =
643
- !fs.existsSync(themes) ||
644
- (() => {
645
- const names = fs.readdirSync(themes);
646
- return (
647
- names.length > 0 && names.every(n => n.startsWith('.astryx-render-'))
648
- );
649
- })();
650
- fs.mkdirSync(dir, {recursive: true});
651
- // Stopped by a signal (the terminal closing too), the render folder
652
- // still goes.
653
- const untrack = removeOnStop(dir);
654
- const entry = path.join(dir, file);
655
- rendersInFlight++;
656
- try {
657
- // Who made it, so a later render can tell it is left over once this
658
- // process is gone (killed outright, which no handler sees).
659
- fs.writeFileSync(
660
- path.join(dir, RENDER_OWNER),
661
- `${JSON.stringify({pid: process.pid, space: processSpace()})}\n`,
662
- );
663
- // Demo images point at the docs site's own folder
664
- // (`/template-assets/…`), which a page opened from disk cannot reach:
665
- // the inline placeholder takes their place, as when a template is
666
- // scaffolded.
667
- const {stripTemplateAssetRefs} =
668
- await import('../../foundation/discovery/template-adapter.mjs');
669
- fs.writeFileSync(entry, stripTemplateAssetRefs(source));
670
- for (const x of extra) {
671
- fs.mkdirSync(path.dirname(path.join(dir, x.name)), {recursive: true});
672
- if (x.text != null) fs.writeFileSync(path.join(dir, x.name), x.text);
673
- else
674
- fs.copyFileSync(/** @type {string} */ (x.from), path.join(dir, x.name));
675
- }
676
- // The editor's pages render every component, and a busy machine slows
677
- // them down: they get three times the page limit.
678
- const page = await renderPage(entry, {
679
- title: file.replace(/\.[^.]+$/, ''),
680
- timeoutMs: EDITOR_RENDER_MS,
681
- // The editor shows the markup itself and writes no file, so it needs
682
- // no script.
683
- markupOnly: true,
684
- // A theme's image too large for a page is named by the editor (show's
685
- // notes); the page goes on without it.
686
- leaveLargeStyleAssets: true,
687
- ...(opts.openLayers ? {openLayers: true} : {}),
688
- });
689
- // The page is the same whichever command rendered it: the folder's
690
- // per-process name never reaches the file.
691
- const html = page.html.split(path.basename(dir)).join('.astryx-render');
692
- const body = html.slice(html.indexOf('<body>') + 6);
693
- const end = body.indexOf('<script type=');
694
- return {html, markup: end >= 0 ? body.slice(0, end) : body};
695
- } catch (e) {
696
- // A theme file too large for a page to carry is the file's size, not
697
- // React: it is named with its size and where it is.
698
- if (e instanceof RenderError && e.code === 'ERR_RENDER_ASSET_TOO_LARGE') {
699
- const d = /** @type {{file?: string, bytes?: number, limit?: number}} */ (
700
- e.detail ?? {}
701
- );
702
- throw new AstryxError(
703
- d.file && d.bytes && d.limit
704
- ? `${path.relative(project.cwd, d.file).split(path.sep).join('/')} is ${(d.bytes / 1048576).toFixed(1)} MB, more than the ${d.limit / 1048576} MB a preview page carries per file: use a smaller copy of it (the app itself can keep the large one).`
705
- : e.message,
706
- [],
707
- ERROR_CODES.ERR_RENDER_ASSET_TOO_LARGE,
708
- );
709
- }
710
- if (e instanceof RenderError) {
711
- const missing = e.code === 'ERR_RENDER_MISSING_DEPENDENCY';
712
- // A render stopped by its time limit on the editor's own page is the
713
- // machine being busy, not a loop in the page.
714
- const slow = e.code === 'ERR_RENDER_TIMEOUT';
715
- throw new AstryxError(
716
- slow
717
- ? `The components did not finish rendering within ${EDITOR_RENDER_MS / 1000} seconds, so the render was stopped. The theme files are written; only its pages were not rendered. The machine may be busy: run show again when it is less loaded.`
718
- : `Could not render the components with this project's React: ${e.message}${missing ? ' The theme command renders components on the server, so react and react-dom must be installed.' : ''}`,
719
- missing
720
- ? [
721
- {
722
- name: installLine(project.cwd, ['react', 'react-dom']),
723
- reason: 'install them',
724
- },
725
- ]
726
- : [],
727
- missing
728
- ? ERROR_CODES.ERR_RENDER_MISSING_DEPENDENCY
729
- : ERROR_CODES.ERR_RENDER_FAILED,
730
- );
731
- }
732
- throw e;
733
- } finally {
734
- // Only this render's files go; the folder goes when nothing else is in
735
- // it, so a render running beside this one keeps its own.
736
- for (const f of [entry, ...extra.map(x => path.join(dir, x.name))])
737
- fs.rmSync(f, {force: true});
738
- // The owner file goes with this process's last render: then the folder
739
- // holds nothing of a render still running.
740
- if (--rendersInFlight === 0)
741
- fs.rmSync(path.join(dir, RENDER_OWNER), {force: true});
742
- // Another render may still use it: a folder with a file in it stays.
743
- removeEmptyFolder(madeThemes ? themes : dir, {deep: true});
744
- untrack();
745
- }
746
- }
747
-
748
- /** @param {unknown} v @returns {v is Record<string, unknown>} */
749
- const isRecord = v => typeof v === 'object' && v !== null && !Array.isArray(v);
750
-
751
- /**
752
- * Part data read from a cache file, by file, with the file's stamp
753
- * (`fileStamp`) when it was read. Shared by every command in the process, so it
754
- * is frozen.
755
- * @type {Map<string, {stamp: string, data: PartData}>}
756
- */
757
- const readParts = new Map();
758
-
759
- /**
760
- * Freeze a parsed value and everything in it.
761
- * @template T
762
- * @param {T} value
763
- * @returns {T}
764
- */
765
- function deepFreeze(value) {
766
- if (value && typeof value === 'object' && !Object.isFrozen(value)) {
767
- Object.freeze(value);
768
- for (const v of Object.values(value)) deepFreeze(v);
769
- }
770
- return value;
771
- }
772
-
773
- /**
774
- * The runtime states the census finds a part's own element marked with
775
- * that its doc does not list (a list item rides an Item, whose
776
- * `data-selected` marks it selected): each `name=name` condition the part
777
- * reads under, less its visual props. Added to the part's states, so set
778
- * names them and the build writes them as the data attribute Core marks.
779
- * @param {{target: Map<string, {props: string[], states: string[]}>}} project
780
- * @param {PartData} parts
781
- */
782
- export function addCensusStates(project, parts) {
783
- const named = censusStateNames(parts);
784
- for (const [part, names] of named) {
785
- const t = project.target.get(part);
786
- if (!t) continue;
787
- const props = new Set(t.props);
788
- for (const name of names)
789
- if (!props.has(name) && !t.states.includes(name)) {
790
- t.states.push(name);
791
- let seen = CENSUS_STATES.get(t);
792
- if (!seen) CENSUS_STATES.set(t, (seen = new Set()));
793
- seen.add(name);
794
- }
795
- }
796
- }
797
-
798
- /**
799
- * The states each part target took from the census alone (addCensusStates):
800
- * Core's theme takes no style key for them on that part.
801
- * @type {WeakMap<object, Set<string>>}
802
- */
803
- const CENSUS_STATES = new WeakMap();
804
-
805
- /**
806
- * A part's states that came from the census alone, not its doc: states
807
- * Core's theme takes no style key for on that part (a list item rides an
808
- * Item, whose own `selected` it shows), which the build writes as the
809
- * attribute Core marks.
810
- * @param {{target: Map<string, any>}} project
811
- * @param {string} part
812
- * @returns {string[]}
813
- */
814
- export function censusStatesOf(project, part) {
815
- const t = project.target.get(part);
816
- return t ? [...(CENSUS_STATES.get(t) ?? [])] : [];
817
- }
818
-
819
- /**
820
- * The names each part's rules write as a state (`selected=selected`), read
821
- * from the part data: partData hands out the same frozen data while its
822
- * file is unchanged, so they are read once for each.
823
- * @param {PartData} parts
824
- * @returns {Map<string, Set<string>>}
825
- */
826
- function censusStateNames(parts) {
827
- const kept = STATE_NAMES.get(parts.map);
828
- if (kept) return kept;
829
- /** @type {Map<string, Set<string>>} */
830
- const out = new Map();
831
- for (const [part, rec] of Object.entries(parts.map)) {
832
- /** @type {Set<string>} */
833
- const found = new Set();
834
- for (const byCond of Object.values(rec.at ?? {}))
835
- for (const cond of Object.keys(byCond ?? {}))
836
- for (const pair of cond.split(/\s/)[0].split(','))
837
- if (
838
- /^([a-z][\w-]*)=\1$/.test(pair) &&
839
- // (A state of a part drawn on this part's element is that
840
- // part's: only the part's own marks count, see walkMarkup.)
841
- Object.hasOwn(rec.attrs ?? {}, pair.slice(0, pair.indexOf('=')))
842
- )
843
- found.add(pair.slice(0, pair.indexOf('=')));
844
- if (found.size) out.set(part, found);
845
- }
846
- STATE_NAMES.set(parts.map, out);
847
- return out;
848
- }
849
- /** @type {WeakMap<object, Map<string, Set<string>>>} */
850
- const STATE_NAMES = new WeakMap();
851
-
852
- /**
853
- * The part data for the installed Core, from the cache or built now.
854
- * @param {import('./_project.mjs').ThemeProject} project
855
- * @returns {Promise<PartData>}
856
- */
857
- export async function partData(project) {
858
- if (!project.cacheDir) return buildPartData(project);
859
- const file = path.join(project.cacheDir, 'parts.json');
860
- try {
861
- // The file is read again only when it changed: every command reads it,
862
- // and parsing it costs more than the rest of a small command.
863
- recordContentRead(file);
864
- const stamp = fileStamp(file);
865
- const kept = readParts.get(file);
866
- const cached =
867
- kept?.stamp === stamp
868
- ? kept.data
869
- : deepFreeze(JSON.parse(fs.readFileSync(file, 'utf8')));
870
- // A file that parses but has the wrong shape (a hand edit, a cut-off
871
- // write) is built again, as a file that does not parse is.
872
- if (
873
- cached.censusKey === CENSUS_KEY &&
874
- cached.coreKey === project.coreKey &&
875
- isRecord(cached.map) &&
876
- Object.values(cached.map).every(isRecord) &&
877
- Array.isArray(cached.pairs)
878
- ) {
879
- // A file that appeared after its stamp is not kept: the entry would
880
- // outlive its removal.
881
- if (stamp !== '-') readParts.set(file, {stamp, data: cached});
882
- return cached;
883
- }
884
- } catch {
885
- // Not built yet, or unreadable: build it.
886
- }
887
- const data = await buildPartData(project);
888
- try {
889
- fs.mkdirSync(project.cacheDir, {recursive: true});
890
- // Write beside it and rename, so a reader never sees half a file.
891
- const part = `${file}.${RUN}`;
892
- fs.writeFileSync(part, JSON.stringify(data));
893
- fs.renameSync(part, file);
894
- } catch {
895
- // A read-only node_modules: build it again next time.
896
- }
897
- return data;
898
- }
899
-
900
- /** The tokens Core's indicator focus ring is drawn from, per property. */
901
- const RING_TOKENS = {
902
- 'outline-width': '--focus-outline-width',
903
- 'outline-style': '--focus-outline-style',
904
- 'outline-color': '--focus-outline-color',
905
- };
906
-
907
- /**
908
- * Add the focus ring a control draws on its indicator at focus time (Core's
909
- * `useIndicatorFocusRing`, used by a control whose input is visually
910
- * hidden): an inline style the server render never shows, read from the
911
- * focus outline tokens. The tokens are read by the indicator always (it
912
- * never takes focus itself, so no state reaches the ring), and the outline
913
- * properties are painted inline, which no theme rule can replace. The
914
- * indicator is the control's own `-indicator` target, or for a part of
915
- * another component (a radio list's item), that component's.
916
- * @param {import('./_project.mjs').ThemeProject} project
917
- * @param {Record<string, PartRecord>} map
918
- */
919
- function addIndicatorRings(project, map) {
920
- for (const [name, info] of Object.entries(project.components)) {
921
- const at = info.importPath?.split('/').pop();
922
- let source;
923
- try {
924
- source = at
925
- ? fs.readFileSync(
926
- path.join(project.coreDir, 'dist', at, `${name}.js`),
927
- 'utf8',
928
- )
929
- : '';
930
- } catch {
931
- continue;
932
- }
933
- if (!source.includes('useIndicatorFocusRing')) continue;
934
- /** @param {import('./_project.mjs').ComponentInfo | undefined} c */
935
- const indicators = c =>
936
- (c?.targets ?? [])
937
- .map(t => t.className.replace(/^astryx-/, ''))
938
- .filter(k => k.endsWith('-indicator'));
939
- const own = indicators(info);
940
- const keys = own.length
941
- ? own
942
- : indicators(
943
- info.subComponentOf
944
- ? project.components[info.subComponentOf]
945
- : undefined,
946
- );
947
- for (const key of keys) {
948
- const rec = (map[key] ??= {
949
- own: {},
950
- inside: {},
951
- attrs: {},
952
- contains: [],
953
- });
954
- for (const [prop, token] of Object.entries(RING_TOKENS)) {
955
- rec.inside[token] = [...new Set([...(rec.inside[token] ?? []), prop])];
956
- (rec.inline ??= {})[''] = {...rec.inline?.[''], [prop]: token};
957
- }
958
- }
959
- }
960
- }
961
-
962
- /**
963
- * Add the paint Core writes as an inline style when it sets a theme state
964
- * at run time (a table row's selection wash, set by the selection plugin
965
- * beside the row's `selected` state): something the server render never
966
- * shows. A built module under a component's folder that writes a state's
967
- * attribute (`themeDataAttributes({selected: 'selected'})`) and an inline
968
- * property from a color token (`el.style.backgroundColor = …` with
969
- * `colorVars['--color-accent-muted']`) paints that state with it, on each
970
- * of the component's targets that lists the state.
971
- * @param {import('./_project.mjs').ThemeProject} project
972
- * @param {Record<string, PartRecord>} map
973
- */
974
- function addInlineStatePaint(project, map) {
975
- const dist = path.join(project.coreDir, 'dist');
976
- /** @param {string} dir @returns {string[]} */
977
- const modules = dir => {
978
- let entries;
979
- try {
980
- entries = fs.readdirSync(dir, {withFileTypes: true});
981
- } catch {
982
- return [];
983
- }
984
- return entries.flatMap(e =>
985
- e.isDirectory()
986
- ? modules(path.join(dir, e.name))
987
- : e.name.endsWith('.js')
988
- ? [path.join(dir, e.name)]
989
- : [],
990
- );
991
- };
992
- for (const [name, info] of Object.entries(project.components)) {
993
- const folder = info.importPath?.split('/').pop();
994
- if (!folder || folder !== name) continue;
995
- const withStates = info.targets.filter(t => t.states.length);
996
- if (!withStates.length) continue;
997
- for (const file of modules(path.join(dist, folder))) {
998
- const source = fs.readFileSync(file, 'utf8');
999
- const states = [
1000
- ...source.matchAll(
1001
- /themeDataAttributes\(\{\s*([\w-]+):\s*'\1'\s*\}\)/g,
1002
- ),
1003
- ].map(m => m[1]);
1004
- if (!states.length) continue;
1005
- const props = [
1006
- ...source.matchAll(/\.style\.([a-z][A-Za-z]*)\s*=(?!=)/g),
1007
- ].map(m => m[1].replace(/[A-Z]/g, c => `-${c.toLowerCase()}`));
1008
- const colorTokens = [
1009
- ...source.matchAll(/colorVars\[['"](--color-[\w-]+)['"]\]/g),
1010
- ].map(m => m[1]);
1011
- if (!props.length || colorTokens.length !== 1) continue;
1012
- for (const t of withStates) {
1013
- const key = t.className.replace(/^astryx-/, '');
1014
- const rec = map[key];
1015
- if (!rec) continue;
1016
- for (const state of states.filter(st => t.states.includes(st)))
1017
- for (const prop of props) {
1018
- (rec.inline ??= {})[state] = {
1019
- ...rec.inline?.[state],
1020
- [prop]: colorTokens[0],
1021
- };
1022
- const own = (rec.own[prop] ??= {tokens: {}, values: []});
1023
- own.tokens[colorTokens[0]] = [
1024
- ...new Set([
1025
- ...(own.tokens[colorTokens[0]] ?? []),
1026
- `${state}=${state}`,
1027
- ]),
1028
- ];
1029
- }
1030
- }
1031
- }
1032
- }
1033
- }
1034
-
1035
- /**
1036
- * Build the part data: render the catalog, then walk its markup.
1037
- * @param {import('./_project.mjs').ThemeProject} project
1038
- * @returns {Promise<PartData>}
1039
- */
1040
- async function buildPartData(project) {
1041
- const {items, imports} = catalogItems(project);
1042
- const all = [...items, {name: 'sample-page', label: '', tree: SAMPLE_PAGE}];
1043
- // Overlays (a tooltip, a menu's list) are drawn open too: the server
1044
- // markup holds none of them.
1045
- const {markup} = await renderGenerated(
1046
- project,
1047
- 'catalog.mjs',
1048
- pageSource({items: all, imports, theme: null, layout: 'catalog'}),
1049
- [],
1050
- {openLayers: true},
1051
- );
1052
- let css = '';
1053
- try {
1054
- css = fs.readFileSync(
1055
- project.req.resolve('@astryxdesign/core/astryx.css'),
1056
- 'utf8',
1057
- );
1058
- } catch {
1059
- // No stylesheet: every part reads nothing.
1060
- }
1061
- const tokens = new Set(Object.keys(project.core.tokenDefaults ?? {}));
1062
- // The overlays drawn open add the parts the server markup cannot hold (a
1063
- // tooltip, a menu's items); a part the page shows already keeps what it
1064
- // reads there, never a look another component gives it inside an overlay
1065
- // (a dialog's round close button).
1066
- const at = markup.indexOf('<div data-astryx-open-layers=');
1067
- const decls = declarations(css);
1068
- const result = walkMarkup(
1069
- at < 0 ? markup : markup.slice(0, at),
1070
- decls,
1071
- tokens,
1072
- project.target,
1073
- );
1074
- if (at >= 0) {
1075
- const layers = walkMarkup(markup.slice(at), decls, tokens, project.target);
1076
- const added = Object.keys(layers.map).filter(k => !(k in result.map));
1077
- for (const k of added) result.map[k] = layers.map[k];
1078
- // A part the page draws too keeps its page record, and takes from the
1079
- // opened overlays only the open state the page never shows (a menu's
1080
- // submenu row, open while its flyout is): its conditions under the open
1081
- // attribute.
1082
- for (const [k, rec] of Object.entries(layers.map)) {
1083
- if (added.includes(k)) continue;
1084
- const page = result.map[k];
1085
- if (!page) continue;
1086
- for (const [prop, byCond] of Object.entries(rec.at ?? {}))
1087
- for (const [cond, v] of Object.entries(byCond ?? {}))
1088
- if (/(?:^|,)aria-expanded=true\b/.test(cond.split(' ')[0]))
1089
- ((page.at ??= {})[prop] ??= {})[cond] ??= v;
1090
- }
1091
- const seen = new Set(result.pairs.map(x => JSON.stringify(x)));
1092
- for (const x of layers.pairs)
1093
- if (
1094
- [x.text, x.fg.target, x.bg.target].some(t =>
1095
- added.includes(String(t)),
1096
- ) &&
1097
- !seen.has(JSON.stringify(x))
1098
- )
1099
- result.pairs.push(x);
1100
- }
1101
- addInlineStatePaint(project, result.map);
1102
- addIndicatorRings(project, result.map);
1103
- return {
1104
- censusKey: CENSUS_KEY,
1105
- coreKey: project.coreKey,
1106
- ...result,
1107
- rendered: (markup.match(/<section data-cat=/g) ?? []).length,
1108
- items: all.length,
1109
- };
1110
- }
1111
-
1112
- /**
1113
- * The value Core falls back to where its stylesheet reads a variable
1114
- * (`var(--astryx-card-padding, var(--spacing-4))` gives `var(--spacing-4)`),
1115
- * or null when it gives none.
1116
- * @param {any} project
1117
- * @param {string} name
1118
- * @returns {string | null}
1119
- */
1120
- export function coreFallback(project, name) {
1121
- /** @type {string} */
1122
- let css;
1123
- try {
1124
- css = fs.readFileSync(
1125
- project.req.resolve('@astryxdesign/core/astryx.css'),
1126
- 'utf8',
1127
- );
1128
- } catch {
1129
- return null;
1130
- }
1131
- const at = css.indexOf(`var(${name},`);
1132
- if (at < 0) return null;
1133
- let depth = 0;
1134
- const from = at + `var(${name},`.length;
1135
- for (let j = from; j < css.length; j++) {
1136
- if (css[j] === '(') depth++;
1137
- else if (css[j] === ')') {
1138
- if (depth === 0) return css.slice(from, j).trim();
1139
- depth--;
1140
- }
1141
- }
1142
- return null;
1143
- }
1144
-
1145
- /** @type {Map<string, string>} */
1146
- const coreCssCache = new Map();
1147
-
1148
- /**
1149
- * Core's stylesheet text, read once; empty with no stylesheet.
1150
- * @param {any} project
1151
- * @returns {string}
1152
- */
1153
- function coreCss(project) {
1154
- /** @type {string} */
1155
- let file;
1156
- try {
1157
- file = project.req.resolve('@astryxdesign/core/astryx.css');
1158
- } catch {
1159
- return '';
1160
- }
1161
- let css = coreCssCache.get(file);
1162
- if (css == null) {
1163
- try {
1164
- css = fs.readFileSync(file, 'utf8');
1165
- } catch {
1166
- css = '';
1167
- }
1168
- coreCssCache.set(file, css);
1169
- }
1170
- return css;
1171
- }
1172
-
1173
- /**
1174
- * The properties a keyframes rule of Core's animates (a tooltip's entrance
1175
- * animates opacity and transform), and the transform functions it uses.
1176
- * Empty when Core has no such rule.
1177
- * @param {any} project
1178
- * @param {string} name
1179
- * @returns {{props: string[], transforms: string[]}}
1180
- */
1181
- export function coreKeyframes(project, name) {
1182
- const css = coreCss(project);
1183
- const at = css.indexOf(`@keyframes ${name}{`);
1184
- if (at < 0) return {props: [], transforms: []};
1185
- let depth = 0;
1186
- let end = at;
1187
- for (let j = css.indexOf('{', at); j < css.length; j++) {
1188
- if (css[j] === '{') depth++;
1189
- else if (css[j] === '}' && --depth === 0) {
1190
- end = j;
1191
- break;
1192
- }
1193
- }
1194
- const body = css.slice(at, end);
1195
- return {
1196
- props: [
1197
- ...new Set([...body.matchAll(/[{;]\s*([a-z-]+)\s*:/g)].map(m => m[1])),
1198
- ].filter(p => p !== 'animation-timing-function'),
1199
- transforms: [
1200
- ...new Set([...body.matchAll(/\b([a-z]+[XYZ3d]*)\(/g)].map(m => m[1])),
1201
- ].filter(f => /^(?:translate|scale|rotate|skew)/.test(f)),
1202
- };
1203
- }
1204
-
1205
- /**
1206
- * Every value Core's stylesheet gives a variable of its own (a card's
1207
- * `--_card-elevation` is a shared shadow at each elevation; its
1208
- * `--_card-ring` is a colored ring), deduplicated. Empty with no
1209
- * stylesheet.
1210
- * @param {any} project
1211
- * @param {string} name
1212
- * @returns {string[]}
1213
- */
1214
- export function coreVarValues(project, name) {
1215
- const css = coreCss(project);
1216
- if (!css) return [];
1217
- const esc = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1218
- return [
1219
- ...new Set(
1220
- [...css.matchAll(new RegExp(`${esc}\\s*:\\s*([^;}]+)`, 'g'))].map(m =>
1221
- m[1].trim(),
1222
- ),
1223
- ),
1224
- ];
1225
- }
1226
-
1227
- /** @type {Map<string, Set<string>>} */
1228
- const calcCache = new Map();
1229
-
1230
- /**
1231
- * The variables Core's stylesheet reads inside a calc() (a composer's
1232
- * padding in its send button's radius): only one length works there.
1233
- * Empty with no stylesheet.
1234
- * @param {any} project
1235
- * @returns {Set<string>}
1236
- */
1237
- export function calcVars(project) {
1238
- /** @type {string} */
1239
- let file;
1240
- try {
1241
- file = project.req.resolve('@astryxdesign/core/astryx.css');
1242
- } catch {
1243
- return new Set();
1244
- }
1245
- const cached = calcCache.get(file);
1246
- if (cached) return cached;
1247
- const css = fs.readFileSync(file, 'utf8');
1248
- /** @type {Set<string>} */
1249
- const out = new Set();
1250
- for (let i = css.indexOf('calc('); i >= 0; i = css.indexOf('calc(', i + 5)) {
1251
- let depth = 0;
1252
- let j = i + 4;
1253
- for (; j < css.length; j++) {
1254
- if (css[j] === '(') depth++;
1255
- else if (css[j] === ')' && --depth === 0) break;
1256
- }
1257
- for (const m of css.slice(i, j).matchAll(/var\((--[a-z0-9_-]+)/gi))
1258
- out.add(m[1].toLowerCase());
1259
- }
1260
- calcCache.set(file, out);
1261
- return out;
1262
- }
1263
-
1264
- /** @type {Map<string, Set<string>>} */
1265
- const multipliedCache = new Map();
1266
-
1267
- /**
1268
- * The tokens Core's stylesheet multiplies by another value inside calc()
1269
- * (`var(--text-body-size) * var(--text-body-leading)`): a unit there makes
1270
- * the declaration invalid. Empty with no stylesheet.
1271
- * @param {any} project
1272
- * @returns {Set<string>}
1273
- */
1274
- export function multipliedTokens(project) {
1275
- /** @type {string} */
1276
- let file;
1277
- try {
1278
- file = project.req.resolve('@astryxdesign/core/astryx.css');
1279
- } catch {
1280
- return new Set();
1281
- }
1282
- const cached = multipliedCache.get(file);
1283
- if (cached) return cached;
1284
- const css = fs.readFileSync(file, 'utf8');
1285
- /** @type {Set<string>} */
1286
- const out = new Set();
1287
- // Each side of a `*` on its own, so `a * b * c` names all three.
1288
- for (const m of css.matchAll(/var\((--[a-z0-9-]+)\)(?=\s*\*)/gi))
1289
- out.add(m[1].toLowerCase());
1290
- for (const m of css.matchAll(/\*\s*var\((--[a-z0-9-]+)\)/gi))
1291
- out.add(m[1].toLowerCase());
1292
- multipliedCache.set(file, out);
1293
- return out;
1294
- }
1295
-
1296
- /**
1297
- * The stylesheet without its forced-colors blocks: what Core draws for a
1298
- * high-contrast system mode (a button's 1px ButtonText border) is no look
1299
- * a theme gives, so the part data never reads it as the part's.
1300
- * @param {string} css
1301
- */
1302
- function withoutForcedColors(css) {
1303
- let out = '';
1304
- let i = 0;
1305
- const re = /@media\s*\(\s*forced-colors\s*:\s*active\s*\)\s*\{/g;
1306
- for (let m = re.exec(css); m; m = re.exec(css)) {
1307
- out += css.slice(i, m.index);
1308
- let depth = 1;
1309
- let j = m.index + m[0].length;
1310
- for (; j < css.length && depth; j++) {
1311
- if (css[j] === '{') depth++;
1312
- else if (css[j] === '}') depth--;
1313
- }
1314
- i = j;
1315
- re.lastIndex = j;
1316
- }
1317
- return out + css.slice(i);
1318
- }
1319
-
1320
- /**
1321
- * Atomic class -> its declarations, with the condition (pseudo-class,
1322
- * attribute) each one applies under.
1323
- * @param {string} css
1324
- * @returns {Map<string, Array<{prop: string, value: string, cond: string}>>}
1325
- */
1326
- export function declarations(css) {
1327
- /** @type {Map<string, Array<{prop: string, value: string, cond: string}>>} */
1328
- const decls = new Map();
1329
- for (const m of withoutForcedColors(css).matchAll(
1330
- /\.(x[a-z0-9]+)((?:\.x[a-z0-9]+|[:[][^{]*)?)\{([^{}]*)\}/g,
1331
- )) {
1332
- const [, cls, rest, body] = m;
1333
- const cond = rest
1334
- .replace(/\.x[a-z0-9]+/g, '')
1335
- .replace(/:not\(#\\#\)/g, '')
1336
- .replace(/:where\([^)]*\)\)?/g, '')
1337
- .trim();
1338
- for (const d of body.split(';')) {
1339
- const i = d.indexOf(':');
1340
- if (i < 0) continue;
1341
- const prop = d.slice(0, i).trim();
1342
- const value = d.slice(i + 1).trim();
1343
- if (!prop) continue;
1344
- const list = decls.get(cls) ?? [];
1345
- list.push({prop, value, cond});
1346
- decls.set(cls, list);
1347
- }
1348
- }
1349
- return decls;
1350
- }
1351
-
1352
- /** @param {string} v */
1353
- const refs = v => [...v.matchAll(/var\((--[a-zA-Z0-9_-]+)/g)].map(m => m[1]);
1354
-
1355
- /**
1356
- * The public tokens a value reads, following private variables set on the
1357
- * element or its ancestors.
1358
- * @param {string} v
1359
- * @param {Record<string, string>} env
1360
- * @param {Set<string>} tokens
1361
- * @param {Set<string>} [seen]
1362
- * @param {number} [depth]
1363
- * @returns {Set<string>}
1364
- */
1365
- function expand(v, env, tokens, seen = new Set(), depth = 0) {
1366
- /** @type {Set<string>} */
1367
- const out = new Set();
1368
- for (const r of refs(v)) {
1369
- if (tokens.has(r)) out.add(r);
1370
- else if (env[r] && !seen.has(r) && depth < 8) {
1371
- seen.add(r);
1372
- for (const t of expand(env[r], env, tokens, seen, depth + 1)) out.add(t);
1373
- }
1374
- }
1375
- return out;
1376
- }
1377
-
1378
- /**
1379
- * A value with the private variables set on the element or its ancestors
1380
- * put in (a variable with no fallback only), so it reads public tokens and
1381
- * literal values alone where it can.
1382
- * @param {string} v
1383
- * @param {Record<string, string>} env
1384
- * @param {Set<string>} tokens
1385
- * @param {number} [depth]
1386
- * @returns {string}
1387
- */
1388
- function resolvePrivate(v, env, tokens, depth = 0) {
1389
- if (depth > 8) return v;
1390
- const out = v.replace(/var\((--[a-zA-Z0-9_-]+)\)/g, (m, name) =>
1391
- !tokens.has(name) && env[name] != null ? env[name] : m,
1392
- );
1393
- return out === v ? v : resolvePrivate(out, env, tokens, depth + 1);
1394
- }
1395
-
1396
- /**
1397
- * Walk server-rendered markup: for each element, its classes' declarations
1398
- * become what its part reads; text records the color pair it sits on.
1399
- * @param {string} html
1400
- * @param {ReturnType<typeof declarations>} decls
1401
- * @param {Set<string>} tokens
1402
- * @param {Map<string, {props: string[], states: string[]}>} [targets] the theming targets by key: the visual props and runtime states each declares are the data attributes read as its conditions
1403
- * @returns {{map: Record<string, PartRecord>, pairs: TextPair[]}}
1404
- */
1405
- export function walkMarkup(html, decls, tokens, targets = new Map()) {
1406
- /** @type {Record<string, {own: Record<string, {tokens: Record<string, Set<string>>, values: Set<string>}>, at: Record<string, Record<string, string>>, inside: Record<string, Set<string>>, attrs: Record<string, Set<string>>, contains: Set<string>, repeats: Set<string>, holdsVariants?: Record<string, Set<string>>, tags: Set<string>, innerCorners: Set<string>, media: boolean, mediaSides?: Set<string>, line?: Set<string>, lineAdded?: Array<[string, string, Set<string>, boolean?]>, held?: Record<string, Set<string>>, alone?: boolean, borrowed?: Record<string, Set<string>>, listed?: Set<string>, drawnAs?: Set<string>, innerSets?: Record<string, Set<string>>, underInput?: string}>} */
1407
- const map = {};
1408
- /** @type {Array<{env: Record<string, string>, target: string | null, all?: string[], fg: PaintSide | null, bg: PaintSide | null, cond: string, kids?: string[], input?: boolean, owns?: boolean, seenParts?: Record<string, number>, seen?: Map<string, number>}>} */
1409
- const stack = [{env: {}, target: null, fg: null, bg: null, cond: ''}];
1410
- /** @type {Map<string, TextPair>} */
1411
- const pairs = new Map();
1412
- /**
1413
- * Text drawn by a part with its paint: one pair per part, text and
1414
- * ground.
1415
- * @param {string} target @param {PaintSide} fg @param {PaintSide} bg @param {string} sample
1416
- */
1417
- const addPair = (target, fg, bg, sample) => {
1418
- const k = `${target}|${fg.target}:${fg.tokens.join('+') || fg.raw}|${bg.target}:${bg.tokens.join('+') || bg.raw}`;
1419
- // (The parts the text sits inside where the census drew it, between
1420
- // it and its ground and beyond: a side nav's item inside the side nav.)
1421
- const within = new Set(pairs.get(k)?.within ?? []);
1422
- for (const anc of stack)
1423
- for (const at of anc.all ?? (anc.target ? [anc.target] : []))
1424
- if (at !== target) within.add(at);
1425
- pairs.set(k, {
1426
- text: target,
1427
- fg,
1428
- bg,
1429
- sample: sample.slice(0, 30),
1430
- within: [...within],
1431
- });
1432
- };
1433
- /** The parts whose paint is a line inside them. @type {Set<string>} */
1434
- const lined = new Set();
1435
- for (const m of html.matchAll(
1436
- /([^<]+)|<(\/?)([a-zA-Z][a-zA-Z0-9-]*)([^>]*?)(\/?)>/g,
1437
- )) {
1438
- const [, text, close, tag, attrs, selfClose] = m;
1439
- if (text !== undefined) {
1440
- const top = stack[stack.length - 1];
1441
- const t = text.trim();
1442
- if (t && top.target && top.fg && top.bg && !/^skip to/i.test(t))
1443
- addPair(top.target, top.fg, top.bg, t);
1444
- continue;
1445
- }
1446
- if (close) {
1447
- if (stack.length > 1) {
1448
- const done = /** @type {typeof stack[number]} */ (stack.pop());
1449
- // (A native input laid over its siblings, invisible, takes the
1450
- // pointer and the focus for them: a checkbox's box draws under
1451
- // it, so its own :hover or :focus never applies. The part that
1452
- // holds the input is where those states land.)
1453
- if (done.input)
1454
- for (const k of done.kids ?? [])
1455
- map[k].underInput ??= done.target ?? stack.at(-1)?.target ?? '';
1456
- }
1457
- continue;
1458
- }
1459
- const cls = (/class="([^"]*)"/.exec(attrs)?.[1] ?? '')
1460
- .split(/\s+/)
1461
- .filter(Boolean);
1462
- const parent = stack[stack.length - 1];
1463
- // The theming targets the element carries (else the one it sits in).
1464
- const keys = cls
1465
- .filter(c => c.startsWith('astryx-') && !c.startsWith('astryx-theme'))
1466
- .map(c => c.slice(7));
1467
- const declaredBy = (keys.length ? keys : [parent.target])
1468
- .map(k => (k ? targets.get(k) : undefined))
1469
- .filter(t => t != null);
1470
- const props = new Set(declaredBy.flatMap(t => t.props));
1471
- const states = new Set(declaredBy.flatMap(t => t.states));
1472
- // A data attribute the element's target declares (a visual prop or a
1473
- // runtime state, written by `themeProps` as `data-<name>`) is a
1474
- // condition of what the part reads.
1475
- const dataAttrs = Object.fromEntries(
1476
- [...attrs.matchAll(/\bdata-([a-z][\w-]*)="([^"]*)"/g)]
1477
- .filter(x => props.has(x[1]) || states.has(x[1]))
1478
- .map(x => [x[1], x[2]]),
1479
- );
1480
- // The place another component puts a part in (the current page's
1481
- // button in a pagination, a pressed toggle) is a condition of what that
1482
- // component styles it with there, never the part's look at rest. A part
1483
- // that marks the place with a runtime state of its own (a selected tab)
1484
- // is conditioned by that state already.
1485
- const ownState = Object.keys(dataAttrs).some(k => states.has(k));
1486
- // (Open is the part's own state, never a place another component puts
1487
- // it: a submenu's row is highlighted while its flyout is open, and open
1488
- // too.)
1489
- const context = [
1490
- ...attrs.matchAll(
1491
- ownState
1492
- ? /\b(aria-expanded)="([^"]*)"/g
1493
- : /\b(aria-(?:current|pressed|expanded))="([^"]*)"/g,
1494
- ),
1495
- ]
1496
- .filter(x => x[2] !== 'false')
1497
- .map(x => `${x[1]}=${x[2]}`);
1498
- const open = context.includes('aria-expanded=true');
1499
- const env = {...parent.env};
1500
- const own = cls.flatMap(c => decls.get(c) ?? []);
1501
- for (const d of own)
1502
- if (d.prop.startsWith('--') && !d.cond) env[d.prop] = d.value;
1503
- const named = cls.filter(
1504
- c => c.startsWith('astryx-') && !c.startsWith('astryx-theme'),
1505
- );
1506
- const target = named[0]?.slice(7) ?? parent.target;
1507
- const ownsTarget = named.length > 0;
1508
- // An empty element with no target of its own inside a part that paints
1509
- // nothing at rest (a divider's line): what it paints is the part's own
1510
- // paint, under the part's conditions, so the readers find it as the
1511
- // part's (its fill, its line color and its thickness).
1512
- const empty =
1513
- Boolean(selfClose) ||
1514
- VOID.has(tag.toLowerCase()) ||
1515
- html.startsWith(`</${tag}>`, (m.index ?? 0) + m[0].length);
1516
- // (An element that holds text a reader sees: never an empty one, an
1517
- // icon's box, or text hidden for screen readers alone.)
1518
- const after = html.slice((m.index ?? 0) + m[0].length);
1519
- const holdsText =
1520
- !empty &&
1521
- !/^\s*<svg\b/i.test(after) &&
1522
- !own.some(
1523
- d =>
1524
- (d.prop === 'clip' && d.value !== 'auto') ||
1525
- (d.prop === 'clip-path' && /inset\(\s*50%/.test(d.value)),
1526
- );
1527
- const paints = (
1528
- /** @type {{prop: string, value: string, cond: string}} */ d,
1529
- ) =>
1530
- !d.cond &&
1531
- /^(background(-color)?|border(-[a-z-]+)?-color)$/.test(d.prop) &&
1532
- expand(d.value, env, tokens).size > 0;
1533
- // (Every part the parent element carries: a menu's separator is a
1534
- // divider too.)
1535
- const lineOf =
1536
- !ownsTarget &&
1537
- empty &&
1538
- parent.target != null &&
1539
- own.some(paints) &&
1540
- (lined.has(parent.target) ||
1541
- !Object.keys(map[parent.target]?.own ?? {}).some(p =>
1542
- /^background(-color)?$/.test(p),
1543
- ))
1544
- ? parent.target
1545
- : null;
1546
- if (lineOf) lined.add(lineOf);
1547
- const lineParts = lineOf ? (parent.all ?? [lineOf]) : [];
1548
- // An element can carry several targets (a shell's side nav region is a
1549
- // layout panel too): its declarations are each one's own. What an
1550
- // element without one draws is each of its parent's.
1551
- for (const t of ownsTarget
1552
- ? named.map(c => c.slice(7))
1553
- : (parent.all ?? [target])) {
1554
- if (!t) continue;
1555
- const asOwn = ownsTarget || lineParts.includes(t);
1556
- const T = (map[t] ??= {
1557
- own: {},
1558
- at: {},
1559
- inside: {},
1560
- attrs: {},
1561
- contains: new Set(),
1562
- repeats: new Set(),
1563
- tags: new Set(),
1564
- innerCorners: new Set(),
1565
- media: false,
1566
- });
1567
- // A data attribute another target on the element declares is this
1568
- // part's only when the part rides on that one: a part always drawn
1569
- // together with another (a list item on its Item) takes that one's
1570
- // states; a part also drawn on its own (a Button) never takes the
1571
- // states of a part drawn on it (a pagination cell's selected). Which
1572
- // is which is known once the whole census is read.
1573
- if (ownsTarget) {
1574
- const mine = targets.get(t);
1575
- if (named.length === 1) T.alone = true;
1576
- for (const o of named)
1577
- if (o.slice(7) !== t) (T.drawnAs ??= new Set()).add(o.slice(7));
1578
- for (const [k, v] of Object.entries(dataAttrs))
1579
- if (!mine || mine.props.includes(k) || mine.states.includes(k))
1580
- (T.attrs[k] ??= new Set()).add(v);
1581
- else ((T.borrowed ??= {})[k] ??= new Set()).add(v);
1582
- }
1583
- // Core's media surface inside the part (a toast's inverted surface):
1584
- // it sets the text tokens of what it holds from the on-dark color
1585
- // where it is dark and the on-light color where it is light (Core's
1586
- // onMediaTokens), so the part's text reads one of them in each mode.
1587
- else if (/\bdata-astryx-media="/.test(attrs)) {
1588
- T.media = true;
1589
- const side = /\bdata-astryx-media="(dark|light)"/.exec(attrs)?.[1];
1590
- if (side) (T.mediaSides ??= new Set()).add(side);
1591
- for (const t of ['--color-on-dark', '--color-on-light'])
1592
- if (tokens.has(t)) (T.inside[t] ??= new Set()).add('color');
1593
- }
1594
- const cond0 = ownsTarget
1595
- ? [
1596
- ...Object.entries(dataAttrs).map(([k, v]) => `${k}=${v}`),
1597
- ...context,
1598
- ].join(',')
1599
- : parent.cond;
1600
- for (const d of own) {
1601
- if (d.prop.startsWith('--')) continue;
1602
- // (An element drawn open is never disabled: what opens it is
1603
- // enabled. Its disabled rules are recorded where Core draws it
1604
- // closed, never as open and disabled at once.)
1605
- if (open && d.cond && /disabled/.test(d.cond)) continue;
1606
- // (An inherited background paints nothing of its own: it reads no
1607
- // token, and what shows is its parent's.)
1608
- const toks = expand(d.value, env, tokens);
1609
- const cond = [cond0, d.cond].filter(Boolean).join(' ');
1610
- // A line's paint and its thickness (a size read from the border
1611
- // width) are the part's; its layout is not.
1612
- const lineProp =
1613
- lineParts.includes(t) &&
1614
- (paints(d) ||
1615
- /^border(-[a-z-]+)?-(width|style)$/.test(d.prop) ||
1616
- (/^(height|width|block-size|inline-size)$/.test(d.prop) &&
1617
- toks.has('--border-width')));
1618
- if (!ownsTarget)
1619
- for (const k of toks) (T.inside[k] ??= new Set()).add(d.prop);
1620
- // (An element inside the part that sets an inherited text property
1621
- // to a value of its own, a code block's lines keeping white-space
1622
- // pre: that property set on the part never reaches its text.)
1623
- if (
1624
- !ownsTarget &&
1625
- !toks.size &&
1626
- INHERITED_TEXT.test(d.prop) &&
1627
- !/^(inherit|unset|initial|revert)$/.test(String(d.value).trim()) &&
1628
- holdsText
1629
- )
1630
- ((T.innerSets ??= {})[d.prop] ??= new Set()).add(
1631
- String(d.value).trim(),
1632
- );
1633
- if (asOwn && (ownsTarget || lineProp)) {
1634
- // (Drawn by the line inside the part, not the part's own element:
1635
- // a setting on the part does not reach it.)
1636
- if (lineProp && !ownsTarget) {
1637
- (T.line ??= new Set()).add(d.prop);
1638
- // (Undone at the end for a part that holds other parts: its
1639
- // own element is no bare line.)
1640
- if (!T.own[d.prop])
1641
- (T.lineAdded ??= []).push([d.prop, cond || 'always', toks]);
1642
- else if (!(T.at[d.prop] ?? {})[cond || 'always'])
1643
- (T.lineAdded ??= []).push([d.prop, cond || 'always', toks, true]);
1644
- }
1645
- const P = (T.own[d.prop] ??= {tokens: {}, values: new Set()});
1646
- (T.at[d.prop] ??= {})[cond || 'always'] ??= resolvePrivate(
1647
- d.value,
1648
- env,
1649
- tokens,
1650
- );
1651
- P.values.add(
1652
- d.value.length > 80 ? `${d.value.slice(0, 80)}...` : d.value,
1653
- );
1654
- for (const t of toks)
1655
- (P.tokens[t] ??= new Set()).add(cond || 'always');
1656
- }
1657
- }
1658
- }
1659
- let fg = parent.fg;
1660
- let bg = parent.bg;
1661
- for (const d of own) {
1662
- if (d.cond) continue;
1663
- if (
1664
- d.prop === 'color' &&
1665
- !/^(inherit|currentcolor|unset|initial)$/i.test(d.value)
1666
- ) {
1667
- const t = [...expand(d.value, env, tokens)];
1668
- fg = {target, tokens: t, raw: t.length ? null : d.value};
1669
- }
1670
- if (d.prop === 'background-color') {
1671
- const t = [...expand(d.value, env, tokens)];
1672
- if (t.length || !/transparent|^\s*inherit\s*$/i.test(d.value))
1673
- bg = {target, tokens: t, raw: t.length ? null : d.value};
1674
- }
1675
- }
1676
- // An input's text is its value, and its placeholder where it has none:
1677
- // attributes, not text nodes, drawn in the input's text color (the
1678
- // placeholder in its own ::placeholder color) on the ground it sits on.
1679
- if (tag.toLowerCase() === 'input' && target && fg && bg) {
1680
- const attr = (/** @type {string} */ n) =>
1681
- new RegExp(`\\b${n}="([^"]*)"`).exec(attrs)?.[1]?.trim() ?? '';
1682
- const type = attr('type') || 'text';
1683
- if (
1684
- !/^(checkbox|radio|hidden|range|color|file|submit|button|reset|image)$/.test(
1685
- type,
1686
- )
1687
- ) {
1688
- if (attr('value')) addPair(target, fg, bg, attr('value'));
1689
- const ph = own.find(
1690
- d => d.prop === 'color' && /placeholder/.test(d.cond ?? ''),
1691
- );
1692
- if (attr('placeholder') && ph) {
1693
- const t = [...expand(ph.value, env, tokens)];
1694
- addPair(
1695
- target,
1696
- {target, tokens: t, raw: t.length ? null : ph.value},
1697
- bg,
1698
- attr('placeholder'),
1699
- );
1700
- } else if (attr('placeholder') && !attr('value'))
1701
- addPair(target, fg, bg, attr('placeholder'));
1702
- }
1703
- }
1704
- // (A part held more than once by the nearest part around it, side by
1705
- // side: a shortcut's keys, a button group's buttons.)
1706
- if (ownsTarget) {
1707
- const nearest = [...stack]
1708
- .reverse()
1709
- .find(anc => (anc.all ?? (anc.target ? [anc.target] : [])).length);
1710
- if (nearest)
1711
- for (const t of named.map(c => c.slice(7))) {
1712
- const seen = (nearest.seenParts ??= {});
1713
- seen[t] = (seen[t] ?? 0) + 1;
1714
- if (seen[t] === 2)
1715
- for (const at of nearest.all ??
1716
- (nearest.target ? [nearest.target] : []))
1717
- if (at !== t) map[at].repeats.add(t);
1718
- }
1719
- }
1720
- // (Each part an element carries holds what is inside it: a checkbox
1721
- // list's root is a field too.)
1722
- for (const t of ownsTarget ? named.map(c => c.slice(7)) : [])
1723
- for (const anc of stack)
1724
- for (const at of anc.all ?? (anc.target ? [anc.target] : []))
1725
- if (at !== t) {
1726
- map[at].contains.add(t);
1727
- // (A part drawn a second time inside the same element is listed
1728
- // there: a menu's items, never a header's one nav.)
1729
- const seen = (anc.seen ??= new Map());
1730
- seen.set(`${at}\0${t}`, (seen.get(`${at}\0${t}`) ?? 0) + 1);
1731
- if (seen.get(`${at}\0${t}`) === 2)
1732
- (map[at].listed ??= new Set()).add(t);
1733
- // (The variant each holds there: a toast's close button is a
1734
- // ghost button.)
1735
- if (dataAttrs.variant)
1736
- ((map[at].holdsVariants ??= {})[t] ??= new Set()).add(
1737
- dataAttrs.variant,
1738
- );
1739
- // What the parts inside it draw with there, at rest (a table
1740
- // row's cells' border color; a toast's ghost button declares
1741
- // none).
1742
- const A = map[at];
1743
- for (const d of own)
1744
- if (!d.cond && !d.prop.startsWith('--'))
1745
- for (const tk of expand(d.value, env, tokens))
1746
- ((A.held ??= {})[tk] ??= new Set()).add(d.prop);
1747
- }
1748
- if (ownsTarget) {
1749
- for (const t of named) map[t.slice(7)].tags.add(tag.toLowerCase());
1750
- // Corners Core draws on a part by its place among its siblings (a
1751
- // button group's first and last buttons): the radius token they read
1752
- // is the enclosing part's corners.
1753
- if (parent.target && !named.includes(`astryx-${parent.target}`))
1754
- for (const d of own)
1755
- if (/^border-(start|end)-(start|end)-radius$/.test(d.prop))
1756
- for (const tok of expand(d.value, env, tokens))
1757
- if (/^--radius-/.test(tok))
1758
- map[parent.target].innerCorners.add(tok);
1759
- }
1760
- // (The conditions a part's own element is drawn under go to what it
1761
- // holds.)
1762
- const condHere = ownsTarget
1763
- ? [
1764
- ...Object.entries(dataAttrs).map(([k, v]) => `${k}=${v}`),
1765
- ...context,
1766
- ].join(',')
1767
- : parent.cond;
1768
- if (
1769
- tag.toLowerCase() === 'input' &&
1770
- own.some(
1771
- d =>
1772
- (d.prop === 'opacity' && /^0(?:\.0+)?$/.test(d.value.trim())) ||
1773
- (d.prop === 'position' && d.value.trim() === 'absolute'),
1774
- )
1775
- )
1776
- parent.input = true;
1777
- else if (ownsTarget)
1778
- // (Into each element it sits in, up to the nearest themed one: the
1779
- // box inside a wrapper with no box of its own, beside the input.)
1780
- for (let i = stack.length - 1; i >= 1; i--) {
1781
- (stack[i].kids ??= []).push(...named.map(c => c.slice(7)));
1782
- if (stack[i].owns) break;
1783
- }
1784
- if (!selfClose && !VOID.has(tag.toLowerCase()))
1785
- stack.push({
1786
- env,
1787
- target,
1788
- all: ownsTarget ? named.map(c => c.slice(7)) : parent.all,
1789
- fg,
1790
- bg,
1791
- cond: condHere,
1792
- owns: ownsTarget,
1793
- });
1794
- }
1795
- // A part that holds other parts (a layout, an outline, a slider's
1796
- // control) is no bare line: what an empty element inside it painted
1797
- // stays what that element draws.
1798
- for (const v of Object.values(map))
1799
- if (v.contains.size && v.lineAdded) {
1800
- for (const [prop, cond, toks, kept] of v.lineAdded) {
1801
- if (!kept) {
1802
- delete v.own[prop];
1803
- delete v.at[prop];
1804
- continue;
1805
- }
1806
- delete v.at[prop]?.[cond];
1807
- for (const tk of toks) v.own[prop]?.tokens[tk]?.delete(cond);
1808
- }
1809
- v.line = undefined;
1810
- }
1811
- /** @type {Record<string, PartRecord>} */
1812
- const out = {};
1813
- for (const [t, v] of Object.entries(map)) {
1814
- out[t] = {
1815
- own: Object.fromEntries(
1816
- Object.entries(v.own).map(([p, x]) => [
1817
- p,
1818
- {
1819
- tokens: Object.fromEntries(
1820
- Object.entries(x.tokens).map(([k, s]) => [
1821
- k,
1822
- [...s].slice(0, 12),
1823
- ]),
1824
- ),
1825
- values: [...x.values].slice(0, 6),
1826
- },
1827
- ]),
1828
- ),
1829
- at: v.at,
1830
- inside: Object.fromEntries(
1831
- Object.entries(v.inside).map(([k, s]) => [k, [...s]]),
1832
- ),
1833
- ...(v.innerSets
1834
- ? {
1835
- innerSets: Object.fromEntries(
1836
- Object.entries(v.innerSets).map(([k, s]) => [k, [...s]]),
1837
- ),
1838
- }
1839
- : {}),
1840
- attrs: Object.fromEntries(
1841
- Object.entries(
1842
- v.alone
1843
- ? v.attrs
1844
- : {
1845
- ...Object.fromEntries(
1846
- Object.entries(v.borrowed ?? {}).map(([k, s]) => [
1847
- k,
1848
- new Set([...s, ...(v.attrs[k] ?? [])]),
1849
- ]),
1850
- ),
1851
- ...v.attrs,
1852
- },
1853
- ).map(([k, s]) => [k, [...s]]),
1854
- ),
1855
- contains: [...v.contains],
1856
- ...(v.repeats?.size ? {repeats: [...v.repeats]} : {}),
1857
- ...(v.listed?.size ? {listed: [...v.listed]} : {}),
1858
- ...(v.drawnAs?.size ? {drawnAs: [...v.drawnAs]} : {}),
1859
- ...(v.holdsVariants
1860
- ? {
1861
- holdsVariants: Object.fromEntries(
1862
- Object.entries(v.holdsVariants).map(([k, s]) => [k, [...s]]),
1863
- ),
1864
- }
1865
- : {}),
1866
- tags: [...v.tags],
1867
- ...(v.underInput != null ? {underInput: v.underInput} : {}),
1868
- innerCorners: [...v.innerCorners],
1869
- ...(v.media ? {media: true} : {}),
1870
- ...(v.mediaSides?.size ? {mediaSides: [...v.mediaSides].sort()} : {}),
1871
- ...(v.line?.size ? {line: [...v.line]} : {}),
1872
- ...(v.held
1873
- ? {
1874
- held: Object.fromEntries(
1875
- Object.entries(v.held).map(([k, s]) => [k, [...s]]),
1876
- ),
1877
- }
1878
- : {}),
1879
- };
1880
- }
1881
- return {map: out, pairs: [...pairs.values()]};
1882
- }
1883
-
1884
- /**
1885
- * The family roles the census shows, each read from the parts' own
1886
- * structure (their tags, states, resting fills, press overlays and their
1887
- * component's doc category), never from their names: a look set on one
1888
- * member of a role reaches the others.
1889
- * - `button-like`: drawn as a <button> with a press overlay and a box of
1890
- * its own (a fill at rest in some variant, or a pressed state), never a
1891
- * selectable item;
1892
- * - `overlays`: an Overlay component's own surface, filled with the
1893
- * surface or popover color;
1894
- * - `option-rows`: a row (a <div> or <li>) clear at rest that is
1895
- * highlighted as you move through a list, or pressed without being
1896
- * selectable;
1897
- * - `selected-items`: a part with a selected (or active) state whose
1898
- * selected look fills it;
1899
- * - `accent-fills`: a part filled with the accent at rest;
1900
- * - `inset-fields`: the inputs and the parts filled with the track color;
1901
- * - `status-surfaces`: a part holding a message with a control of its own
1902
- * whose fill follows a prop whose values name the theme's status roles
1903
- * (info, success, warning, error);
1904
- * - `overlay-headers`: an Overlay component's part, not its surface, that
1905
- * holds a heading and a control (its title and its close button);
1906
- * - `controls`: the parts that take their height from the control size
1907
- * tokens (`--size-element-sm`, `-md`, `-lg`) and are a button, an input,
1908
- * or a form control's own part (an input group): at each size they share
1909
- * one height.
1910
- * @param {{MAP: Record<string, any>}} C
1911
- * @param {{target: Map<string, any>, components: Record<string, any>}} project
1912
- * @param {string[]} inputs the inputs group's members
1913
- * @param {string[]} statusWords the theme's status role words
1914
- * @returns {Record<'button-like' | 'overlays' | 'option-rows' | 'selected-items' | 'accent-fills' | 'inset-fields' | 'status-surfaces' | 'overlay-headers' | 'controls', string[]>}
1915
- */
1916
- export function familyRoles(
1917
- C,
1918
- project,
1919
- inputs = [],
1920
- statusWords = ['info', 'success', 'warning', 'error'],
1921
- ) {
1922
- /** @type {Record<string, string[]>} */
1923
- const out = {
1924
- 'button-like': [],
1925
- overlays: [],
1926
- 'option-rows': [],
1927
- 'selected-items': [],
1928
- 'accent-fills': [],
1929
- 'inset-fields': [],
1930
- 'status-surfaces': [],
1931
- 'overlay-headers': [],
1932
- controls: [],
1933
- };
1934
- /** @param {string} key @param {string} prop @param {(cond: string) => boolean} keep */
1935
- const values = (key, prop, keep) =>
1936
- Object.entries(C.MAP?.[key]?.at?.[prop] ?? {})
1937
- .filter(([cond]) => keep(cond))
1938
- .map(([, v]) => String(v).trim());
1939
- const CLEAR = /^(?:transparent|none|rgba\(0, ?0, ?0, ?0\))$/;
1940
- for (const [key, tg] of project.target) {
1941
- const rec = C.MAP?.[key];
1942
- if (!rec) continue;
1943
- const tags = [...(rec.tags ?? [])];
1944
- const states = [...(tg.states ?? []), ...Object.keys(rec.attrs ?? {})].map(
1945
- String,
1946
- );
1947
- const selectable = states.some(st => /^(?:selected|active)$/.test(st));
1948
- const highlighted = states.includes('highlighted');
1949
- const pressed = JSON.stringify(rec.at ?? {}).includes('data-astryx-press');
1950
- // (At rest: a condition of visual props only, no state (a state the
1951
- // docs name, an ARIA state, or a boolean attribute Core writes as its
1952
- // own name, selected="selected"), pseudo-class or inner element.)
1953
- const docStates = new Set((tg.states ?? []).map(String));
1954
- const rest = values(
1955
- key,
1956
- 'background-color',
1957
- cond =>
1958
- !/[\s:[]/.test(cond) &&
1959
- (cond === 'always' ||
1960
- cond.split(',').every(kv => {
1961
- const [k, v] = kv.split('=');
1962
- return k !== v && !docStates.has(k) && !k.startsWith('aria-');
1963
- })),
1964
- );
1965
- const comp = project.components?.[tg.component];
1966
- const own = comp?.targets?.[0]?.className === `astryx-${key}`;
1967
- if (
1968
- tags.length &&
1969
- tags.every(t => t === 'button') &&
1970
- pressed &&
1971
- !selectable &&
1972
- !highlighted &&
1973
- (rest.some(v => !CLEAR.test(v)) || states.some(st => /pressed/i.test(st)))
1974
- )
1975
- out['button-like'].push(key);
1976
- if (
1977
- comp?.category === 'Overlay' &&
1978
- own &&
1979
- values(key, 'background-color', cond => !/[\s:[]/.test(cond)).some(v =>
1980
- /--color-background-(?:surface|popover)\b/.test(v),
1981
- )
1982
- )
1983
- out.overlays.push(key);
1984
- if (
1985
- tags.length &&
1986
- tags.every(t => t === 'div' || t === 'li') &&
1987
- rest.length > 0 &&
1988
- rest.every(v => CLEAR.test(v)) &&
1989
- (highlighted || (pressed && !selectable))
1990
- )
1991
- out['option-rows'].push(key);
1992
- if (
1993
- selectable &&
1994
- values(
1995
- key,
1996
- 'background-color',
1997
- cond =>
1998
- /(?:^|,)(?:selected=selected|active=active)(?:,|$)/.test(cond) &&
1999
- !/[\s:[]/.test(cond),
2000
- ).some(v => !CLEAR.test(v))
2001
- )
2002
- out['selected-items'].push(key);
2003
- if (rest.some(v => /^var\(--color-accent\)$/.test(v)))
2004
- out['accent-fills'].push(key);
2005
- if (
2006
- inputs.includes(key) ||
2007
- rest.some(v => /^var\(--color-track\)$/.test(v))
2008
- )
2009
- out['inset-fields'].push(key);
2010
- // (A status prop: one whose values are the theme's status words; the
2011
- // fill follows it when it differs between them or reads a status
2012
- // token.)
2013
- const statusProps = Object.entries(rec.attrs ?? {})
2014
- .filter(
2015
- ([, vals]) =>
2016
- Array.isArray(vals) &&
2017
- vals.some(v => statusWords.includes(String(v))),
2018
- )
2019
- .map(([k]) => k);
2020
- if (statusProps.length) {
2021
- const fills = Object.entries(rec.at?.['background-color'] ?? {}).filter(
2022
- ([cond]) => !/[\s:[]/.test(cond),
2023
- );
2024
- const statusFill = new RegExp(
2025
- `--color-(?:background-)?(?:${statusWords.join('|')})\\b`,
2026
- );
2027
- const byStatus = fills.filter(([cond]) =>
2028
- statusProps.some(k => new RegExp(`(?:^|,)${k}=`).test(cond)),
2029
- );
2030
- // (A surface: it holds a message with a control of its own, a dismiss
2031
- // or an action; a badge or a dot is a mark, not a surface.)
2032
- if (
2033
- (rec.contains ?? []).includes('button') &&
2034
- (byStatus.some(([, v]) => statusFill.test(String(v))) ||
2035
- new Set(fills.map(([, v]) => String(v))).size > 1)
2036
- )
2037
- out['status-surfaces'].push(key);
2038
- }
2039
- if (
2040
- comp?.category === 'Overlay' &&
2041
- !own &&
2042
- (rec.contains ?? []).includes('heading') &&
2043
- (rec.contains ?? []).includes('button')
2044
- )
2045
- out['overlay-headers'].push(key);
2046
- /** Whether a part's own height reads a control size token. @param {string} part */
2047
- const sizedOwn = part =>
2048
- Object.entries(C.MAP?.[part]?.own ?? {}).some(
2049
- ([prop, v]) =>
2050
- CONTROL_HEIGHT_PROPS.test(prop) &&
2051
- Object.keys(/** @type {any} */ (v)?.tokens ?? {}).some(t =>
2052
- CONTROL_SIZE_TOKEN.test(t),
2053
- ),
2054
- );
2055
- // (A field whose boxes are its parts, a date and time input's two
2056
- // segments, is sized through them: the token set on the field reaches
2057
- // them.)
2058
- const sizedByControlSize =
2059
- sizedOwn(key) ||
2060
- (own &&
2061
- inputs.includes(key) &&
2062
- [...project.target].some(
2063
- ([k, t]) => k !== key && t.component === tg.component && sizedOwn(k),
2064
- ));
2065
- if (
2066
- sizedByControlSize &&
2067
- (inputs.includes(key) ||
2068
- out['button-like'].includes(key) ||
2069
- (comp?.category === 'Form Controls' && own))
2070
- )
2071
- out.controls.push(key);
2072
- }
2073
- return /** @type {any} */ (out);
2074
- }
2075
-
2076
- /** The properties a control's height is set by. */
2077
- export const CONTROL_HEIGHT_PROPS = /^(height|min-height|block-size)$/;
2078
-
2079
- /** The tokens that hold a control's height at each size. */
2080
- export const CONTROL_SIZE_TOKEN = /^--size-element-(sm|md|lg)$/;
2081
-
2082
- /**
2083
- * The properties that size a part in the block direction: a part that sets
2084
- * none of them (a layout region, which may draw a divider line) is a frame
2085
- * a bar's height passes through.
2086
- */
2087
- const BLOCK_BOX =
2088
- /^(height|min-height|max-height|(min-|max-)?block-size|padding(-(top|bottom|block(-start|-end)?))?|margin-(top|bottom|block(-start|-end)?))$/;
2089
-
2090
- /** The elements a control is drawn as: never a bar, nor a bar's row. */
2091
- const CONTROL_TAGS = new Set([
2092
- 'button',
2093
- 'a',
2094
- 'input',
2095
- 'select',
2096
- 'textarea',
2097
- 'label',
2098
- ]);
2099
-
2100
- /**
2101
- * The value a part draws a property with as the census saw it: the one it
2102
- * always has, else the one every condition it was drawn in agrees on; null
2103
- * when it sets none (or conditions differ).
2104
- * @param {PartRecord | undefined} rec
2105
- * @param {string} prop
2106
- * @returns {string | null}
2107
- */
2108
- export function drawnValue(rec, prop) {
2109
- const at = rec?.at?.[prop];
2110
- if (!at) return null;
2111
- if (at.always != null) return at.always;
2112
- const values = [...new Set(Object.values(at))];
2113
- return values.length === 1 ? values[0] : null;
2114
- }
2115
-
2116
- /**
2117
- * The bar rows a part holds, from the part map's `contains` relation: the
2118
- * parts drawn inside it that lay their own children out in one row,
2119
- * centered across its whole width (display flex, align-items center, width
2120
- * 100%: the top nav in the app's header) and holding items of more than
2121
- * one kind, drawn there once (a part listed inside it is a list's item,
2122
- * never its bar's row: a menu's items, a side nav's items), neither of them
2123
- * drawn as a control (a collapsible's trigger, an avatar's button), reached
2124
- * through frames that draw no box of their own (a layout region). A part
2125
- * holding such a row is laid out as a bar:
2126
- * a height or a vertical padding set on it makes the bar that row fills.
2127
- * @param {Record<string, PartRecord>} map
2128
- * @param {string} holder
2129
- * @returns {string[]}
2130
- */
2131
- export function barRows(map, holder) {
2132
- const inside = map[holder]?.contains ?? [];
2133
- /** @param {string} p */
2134
- const frame = p =>
2135
- !Object.keys(map[p]?.at ?? {}).some(k => BLOCK_BOX.test(k));
2136
- /** A part drawn as a control (a button, a link, a field). @param {string} p */
2137
- const control = p =>
2138
- (map[p]?.tags ?? []).some(t => CONTROL_TAGS.has(t.toLowerCase()));
2139
- if (control(holder)) return [];
2140
- const listed = new Set(map[holder]?.listed ?? []);
2141
- return inside.filter(r => {
2142
- const rec = map[r];
2143
- if (listed.has(r) || control(r)) return false;
2144
- // (A bar's row lays out items: more than one kind of part inside it,
2145
- // where a menu's divider or a typeahead option's icon is one or none.)
2146
- if ((rec?.contains ?? []).length < 2) return false;
2147
- if (
2148
- !/^(inline-)?flex$/.test(drawnValue(rec, 'display') ?? '') ||
2149
- /^column/.test(drawnValue(rec, 'flex-direction') ?? '') ||
2150
- drawnValue(rec, 'align-items') !== 'center' ||
2151
- drawnValue(rec, 'width') !== '100%'
2152
- )
2153
- return false;
2154
- return inside
2155
- .filter(p => p !== r && (map[p]?.contains ?? []).includes(r))
2156
- .every(frame);
2157
- });
2158
- }
2159
-
2160
- /**
2161
- * A pair of block-direction sides (top and bottom) one family of
2162
- * properties gives, read from `get(prop)`: the longhands win over
2163
- * `<family>-block`, which wins over the shorthand. Null sides are unset.
2164
- * @param {(prop: string) => string | null} get
2165
- * @param {'padding' | 'border-width'} family
2166
- * @returns {[string | null, string | null]}
2167
- */
2168
- export function blockSides(get, family) {
2169
- const [head, tail] =
2170
- family === 'padding' ? ['padding', ''] : ['border', '-width'];
2171
- /** @param {string} side */
2172
- const name = side => `${head}-${side}${tail}`;
2173
- const whole = get(family);
2174
- const all = whole ? sidesOf(family, whole) : null;
2175
- const block = get(name('block'));
2176
- const ends = block ? sidesOf(name('block'), block) : null;
2177
- return [
2178
- get(name('top')) ??
2179
- get(name('block-start')) ??
2180
- ends?.[name('block-start')] ??
2181
- all?.[name('top')] ??
2182
- null,
2183
- get(name('bottom')) ??
2184
- get(name('block-end')) ??
2185
- ends?.[name('block-end')] ??
2186
- all?.[name('bottom')] ??
2187
- null,
2188
- ];
2189
- }
2190
-
2191
- /**
2192
- * A part's measured height as it is drawn, in px: its own height or
2193
- * min-height when it gives one in px, else its vertical padding and
2194
- * borders around one line of its text (its line height: a length, or a
2195
- * number times its font size). The theme's own values (`own(prop)`) win
2196
- * over the ones Core draws it with (the part map's); `px(value)` reads a
2197
- * length, tokens resolved (null when the value is no length). Null when
2198
- * neither a height nor a line height reads.
2199
- * @param {Record<string, PartRecord>} map
2200
- * @param {string} part
2201
- * @param {(prop: string) => string | null} own
2202
- * @param {Record<string, unknown>} tokens the token values a var() reads
2203
- * @param {(value: string) => number | null} pxOf
2204
- * @returns {number | null}
2205
- */
2206
- export function partHeightPx(map, part, own, tokens, pxOf) {
2207
- /** A value with the tokens it reads put in. @param {string} v */
2208
- const resolve = v => {
2209
- let out = String(v);
2210
- for (let i = 0; i < 6 && /var\(/.test(out); i++)
2211
- out = out.replace(
2212
- /var\(\s*(--[\w-]+)\s*(?:,\s*([^()]*))?\)/g,
2213
- (_, name, fallback) => {
2214
- const t = tokens[name];
2215
- const one = Array.isArray(t) ? t[0] : t;
2216
- return one != null ? String(one) : (fallback ?? '');
2217
- },
2218
- );
2219
- return out.trim();
2220
- };
2221
- /** @param {string} v */
2222
- const px = v => pxOf(resolve(v));
2223
- /**
2224
- * The value in effect: a property family the theme sets is all the
2225
- * theme's (its shorthand covers Core's longhands), else Core's.
2226
- * @param {RegExp} family
2227
- */
2228
- const reader = family => {
2229
- const ownsFamily = [...Object.keys(map[part]?.at ?? {}), ...FAMILY_PROPS]
2230
- .filter(k => family.test(k))
2231
- .some(k => own(k) != null);
2232
- return (/** @type {string} */ prop) =>
2233
- ownsFamily ? own(prop) : drawnValue(map[part], prop);
2234
- };
2235
- /** @param {string | null} v */
2236
- const len = v => (v == null ? 0 : (px(v) ?? 0));
2237
- const pad = blockSides(reader(/^padding/), 'padding');
2238
- const border = blockSides(reader(/^border/), 'border-width');
2239
- const sizes = reader(/^(min-)?height$|block-size$/);
2240
- const explicit = [sizes('height'), sizes('min-height'), sizes('block-size')]
2241
- .map(v => (v == null ? null : px(v)))
2242
- .filter(n => n != null);
2243
- const text = reader(/^(font-size|line-height)$/);
2244
- /** One line of text: a length, or a number times the font size. @param {string | null} size @param {string | null} leading */
2245
- const lineOf = (size, leading) => {
2246
- const fontPx = px(size ?? 'var(--text-body-size, 16px)') ?? 16;
2247
- const lh = resolve(leading ?? 'var(--text-body-leading)');
2248
- return /^[\d.]+$/.test(lh)
2249
- ? Number(lh) * fontPx
2250
- : lh === 'normal' || lh === ''
2251
- ? null
2252
- : px(lh);
2253
- };
2254
- // Text the part's own unnamed elements draw with a type of their own (a
2255
- // nav heading's title) is the line it holds; else its own text, or the
2256
- // body text it inherits.
2257
- const inner = Object.entries(map[part]?.inside ?? {})
2258
- .filter(
2259
- ([tok, props]) => props.includes('line-height') && /-leading$/.test(tok),
2260
- )
2261
- .map(([tok]) =>
2262
- lineOf(`var(${tok.replace(/-leading$/, '-size')})`, `var(${tok})`),
2263
- )
2264
- .filter(n => n != null);
2265
- const line =
2266
- text('line-height') == null && inner.length
2267
- ? Math.max(...inner)
2268
- : lineOf(text('font-size'), text('line-height'));
2269
- const box =
2270
- line == null
2271
- ? null
2272
- : len(pad[0]) + len(pad[1]) + len(border[0]) + len(border[1]) + line;
2273
- const all = [...explicit, ...(box == null ? [] : [box])];
2274
- return all.length ? Math.max(...all) : null;
2275
- }
2276
-
2277
- /** The block-direction properties a theme may set on a part. */
2278
- const FAMILY_PROPS = [
2279
- 'padding',
2280
- 'padding-block',
2281
- 'padding-top',
2282
- 'padding-bottom',
2283
- 'padding-block-start',
2284
- 'padding-block-end',
2285
- 'border-width',
2286
- 'border-block-width',
2287
- 'border-top-width',
2288
- 'border-bottom-width',
2289
- 'height',
2290
- 'min-height',
2291
- 'block-size',
2292
- 'font-size',
2293
- 'line-height',
2294
- ];