@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,3264 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
-
3
- /**
4
- * @file Previews for `astryx experimental theme editor` and `theme preview`: the sample app page and
5
- * the theme-building page (every component grouped, overlays open, and real
6
- * template pages), rendered with the theme to self-contained HTML by the
7
- * render machinery; and the sources of the in-app preview route and its
8
- * pages. PNG pictures
9
- * are made only on request, with a Playwright or Chrome installed on the
10
- * machine.
11
- *
12
- * @position api/theme-edit — previews and pictures
13
- */
14
-
15
- import {createHash} from 'node:crypto';
16
- import * as fs from 'node:fs';
17
- import * as path from 'node:path';
18
- import {spawn} from 'node:child_process';
19
- import * as os from 'node:os';
20
- import {fileURLToPath} from 'node:url';
21
- import {AstryxError} from '../error.mjs';
22
- import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
23
- import {
24
- SAMPLE_PAGE,
25
- SHEET_ORDER,
26
- elementNames,
27
- pageSource,
28
- bindingFrom,
29
- SAMPLE_SEARCH_ITEMS,
30
- SAMPLE_SOURCE,
31
- OPEN_SCENES,
32
- sampleControls,
33
- } from './_catalog.mjs';
34
- import {
35
- catalogVariants,
36
- codeFingerprint,
37
- demoProps,
38
- needsParent,
39
- renderDir,
40
- renderGenerated,
41
- } from './_parts.mjs';
42
- import {OVERVIEW_SECTIONS} from './_overview.mjs';
43
- import {
44
- camel,
45
- folderIsEmpty,
46
- builtFontWeights,
47
- builtItalic,
48
- fontPackages,
49
- mediaSurfaceSides,
50
- modesOf,
51
- settleMediaSides,
52
- shown,
53
- themeFiles,
54
- APP_COPY_BUILT,
55
- appCopyNames,
56
- groupsOf,
57
- } from './_settings.mjs';
58
- import {readRegularFile, writeWhole} from './_palette.mjs';
59
- import {cliVersion} from '../../foundation/release/run-context.mjs';
60
- import {importPathOf, installLine} from './_project.mjs';
61
- import {
62
- COLOR_PROP_PARTS,
63
- DIRECT,
64
- P,
65
- SHOWCASE_GROUPS,
66
- wordTable,
67
- } from './_tables.mjs';
68
- import {extractImportedPackages} from '../../foundation/discovery/template-needs.mjs';
69
- import {fillTemplatePlaceholders} from '../../foundation/discovery/template-placeholders.mjs';
70
- import {findNodeModulesPackage} from '../../foundation/fs/paths.mjs';
71
- import {fontFaces} from '../../foundation/fonts/font-stylesheet.mjs';
72
- import {themeFileImports} from '../../foundation/discovery/theme-discovery.mjs';
73
- import {withListingCache} from '../../foundation/fs/listing-cache.mjs';
74
- import {compareText} from '../../foundation/text/compare-text.mjs';
75
- import {PICTURE_TAKEN} from '../../foundation/render/picture-window.mjs';
76
- import {FONT_PROBE_PREFIX} from '../../foundation/render/font-probe.mjs';
77
- import {CUT_SHORT_PREFIX} from '../../foundation/render/cut-short.mjs';
78
- import {LOW_CONTRAST_PREFIX} from '../../foundation/render/drawn-contrast.mjs';
79
- import {PART_BOXES_PREFIX} from '../../foundation/render/part-boxes.mjs';
80
-
81
- const TEMPLATES_DIR = path.resolve(
82
- path.dirname(fileURLToPath(import.meta.url)),
83
- '../../assets/templates/pages',
84
- );
85
-
86
- /**
87
- * A template page's source as a copy of it reads: icon placeholders filled.
88
- * @param {string} template
89
- * @returns {string}
90
- */
91
- function templatePageSource(template) {
92
- return fillTemplatePlaceholders(
93
- fs.readFileSync(path.join(TEMPLATES_DIR, template, 'page.tsx'), 'utf8'),
94
- ).source;
95
- }
96
-
97
- /** The groups of the theme-building page, in order. */
98
- export {SHOWCASE_GROUPS};
99
-
100
- /**
101
- * Packages whose output is drawn in the browser once the page runs (a
102
- * recharts chart measures and draws itself after it mounts): a server
103
- * render, which the sheet is, has none of it.
104
- */
105
- const DRAWN_IN_BROWSER = Object.freeze(['recharts']);
106
-
107
- /** Real template pages the theme-building page shows in full. */
108
- const PAGE_TEMPLATES = ['dashboard', 'contact-form', 'settings'];
109
-
110
- const SELECTION =
111
- /Select|Checkbox|Radio|Switch|Segmented|Toggle|Slider|Typeahead|Tokenizer/;
112
-
113
- /** The overlays the preview's strip draws open, in its order: one of each kind a look styles (a tooltip, a popover, a menu, a select list). */
114
- const PREVIEW_OVERLAYS = ['Tooltip', 'Popover', 'DropdownMenu', 'Selector'];
115
-
116
- /** Props a doc names that open a part's own menu or list. */
117
- const OPENERS = ['isMenuOpen', 'isDefaultOpen'];
118
-
119
- /**
120
- * The group a component belongs to on the theme-building page.
121
- * @param {string} name
122
- * @param {string} category
123
- * @returns {string | null}
124
- */
125
- function groupOf(name, category) {
126
- if (SELECTION.test(name)) return 'selection';
127
- const c = category.toLowerCase();
128
- if (c === 'action') return 'actions';
129
- if (c === 'form controls') return 'inputs';
130
- if (c === 'navigation') return 'navigation';
131
- if (c === 'feedback & status') return 'feedback';
132
- if (c === 'content' || c === 'table & list' || c === 'text' || c === 'media')
133
- return 'data';
134
- if (c === 'container' || c === 'layout') return 'containers';
135
- if (c === 'overlay') return 'overlays';
136
- return null;
137
- }
138
-
139
- /**
140
- * A container's or a layout's props on the sheet, with a line of sample
141
- * text when its doc suggests no children (a section, a form layout): empty,
142
- * it draws nothing of the theme. The part data reads the doc's own props.
143
- * @param {import('./_project.mjs').ThemeProject} project
144
- * @param {string} name
145
- * @param {Record<string, unknown>} props
146
- * @returns {Record<string, unknown>}
147
- */
148
- function withSampleContent(project, name, props) {
149
- const info = project.components[name];
150
- const kids = info?.props?.children;
151
- if (
152
- 'children' in props ||
153
- !kids ||
154
- kids.slots?.length ||
155
- !/ReactNode/.test(String(kids.type ?? '')) ||
156
- !/^(container|layout)$/i.test(String(info.category ?? '')) ||
157
- !project.components.Text
158
- )
159
- return props;
160
- return {
161
- ...props,
162
- children: [{__element: 'Text', props: {}, children: ['Sample content']}],
163
- };
164
- }
165
-
166
- /**
167
- * The section of the theme-building page a component sits in; a part with
168
- * no category of its own sits with its parent.
169
- * @param {import('./_project.mjs').ThemeProject} project
170
- * @param {string} name
171
- * @returns {string | null}
172
- */
173
- export function familyOf(project, name) {
174
- const info = project.components[name];
175
- const parent = info?.subComponentOf
176
- ? project.components[info.subComponentOf]
177
- : null;
178
- return groupOf(name, info?.category || parent?.category || '');
179
- }
180
-
181
- /**
182
- * Whether a section's own page draws a component in a cell of its own. On
183
- * the overlays section's page, a part of an overlay (a dialog's header, a
184
- * command palette's list) shows inside the overlay it belongs to, never
185
- * alone beside it, and inside it only while the overlay is open: that page
186
- * stays one or two screens. The whole sheet draws it alone.
187
- * @param {import('./_project.mjs').ThemeProject} project
188
- * @param {string} name
189
- * @param {string | null | undefined} group the section drawn, none for the whole sheet
190
- */
191
- export function shownOnSection(project, name, group) {
192
- return !(
193
- group === 'overlays' &&
194
- familyOf(project, name) === 'overlays' &&
195
- project.components[name]?.subComponentOf
196
- );
197
- }
198
-
199
- /**
200
- * The sections of the theme-building page whose parts the theme's settings
201
- * set on their own (`--on badge`, or a group of parts such as `--on
202
- * inputs`): the components each part names a class of, each in its section. A setting for the whole theme (a color, the
203
- * corners) sets no section here: the sample page and the open states show
204
- * it.
205
- * A family role (`--on option-rows`) is read from the census, as the
206
- * change itself reads it, so the pictured set is what the change touched.
207
- * @param {{project: import('./_project.mjs').ThemeProject, C?: any}} ctx
208
- * @param {import('./_settings.mjs').ThemeData} data
209
- * @returns {string[]}
210
- */
211
- export function touchedFamilies(ctx, data) {
212
- const {project} = ctx;
213
- // A group (`--on inputs`, `--on option-rows`) sets each of its parts.
214
- const groups = groupsOf(ctx);
215
- const parts = new Set(
216
- (data.settings ?? []).flatMap(s => (s.on ? (groups[s.on] ?? [s.on]) : [])),
217
- );
218
- /** @type {Set<string>} */
219
- const out = new Set();
220
- for (const [name, info] of Object.entries(project.components)) {
221
- if (!info.targets.some(t => parts.has(t.className.replace(/^astryx-/, ''))))
222
- continue;
223
- const family = familyOf(project, name);
224
- if (family) out.add(family);
225
- }
226
- return [...out];
227
- }
228
-
229
- /** The Astryx control each plain HTML text control is drawn as. */
230
- const ASTRYX_CONTROLS = Object.freeze({
231
- input: 'TextInput',
232
- textarea: 'TextArea',
233
- });
234
-
235
- /** The input types a text input draws. */
236
- const TEXT_TYPES = new Set([
237
- '',
238
- 'text',
239
- 'email',
240
- 'search',
241
- 'url',
242
- 'tel',
243
- 'password',
244
- ]);
245
-
246
- /**
247
- * A value with each plain HTML text control in a doc's sample (a field's
248
- * `<input>`) drawn as the Astryx control for it, its label hidden, so the
249
- * sheet shows the theme's own control where an app would use one: a bare
250
- * browser control shows nothing of the theme. Every other value is the same
251
- * object.
252
- * @param {import('./_project.mjs').ThemeProject} project
253
- * @param {unknown} v
254
- * @returns {unknown}
255
- */
256
- function withAstryxControls(project, v) {
257
- if (Array.isArray(v)) {
258
- const out = v.map(x => withAstryxControls(project, x));
259
- return out.every((x, i) => x === v[i]) ? v : out;
260
- }
261
- if (!v || typeof v !== 'object') return v;
262
- if (isElement(v)) {
263
- const own = /** @type {Record<string, string>} */ (ASTRYX_CONTROLS)[
264
- v.__element
265
- ];
266
- const p = /** @type {Record<string, unknown>} */ (v.props ?? {});
267
- if (
268
- own &&
269
- project.components[own] &&
270
- (v.__element !== 'input' || TEXT_TYPES.has(String(p.type ?? '')))
271
- )
272
- return {
273
- __element: own,
274
- props: {
275
- label: String(p['aria-label'] ?? p.placeholder ?? 'Text'),
276
- isLabelHidden: true,
277
- ...(p.placeholder != null ? {placeholder: p.placeholder} : {}),
278
- ...(p.id != null ? {id: p.id} : {}),
279
- },
280
- };
281
- const props = withAstryxControls(project, v.props);
282
- const children = withAstryxControls(project, v.children);
283
- return props === v.props && children === v.children
284
- ? v
285
- : {...v, props, children};
286
- }
287
- const entries = Object.entries(v);
288
- const out = entries.map(([k, x]) => [k, withAstryxControls(project, x)]);
289
- return out.every(([, x], i) => x === entries[i][1])
290
- ? v
291
- : {...v, ...Object.fromEntries(out)};
292
- }
293
-
294
- /**
295
- * What the cached component items are built by ({@link codeFingerprint}):
296
- * this file and every file it imports, read the first time it is needed.
297
- * @type {string | null}
298
- */
299
- let itemsKey = null;
300
-
301
- /**
302
- * The component items of the theme-building page for each group, as JSON,
303
- * by cache file: read or made once a process. They come from the installed
304
- * Core's component docs alone, which the same install (its cache folder,
305
- * keyed by its version and stylesheet) never changes, and every sample page
306
- * and sheet a command renders starts from them; the cache file
307
- * (items.json beside the part data) keeps them for the next command.
308
- * @type {Map<string, Record<string, string>>}
309
- */
310
- const itemsByFile = new Map();
311
-
312
- /**
313
- * The component items for a group, from the cache or made now
314
- * ({@link componentItems}), as a copy of their own.
315
- * @param {import('./_project.mjs').ThemeProject} project
316
- * @param {string | undefined} group
317
- * @returns {import('./_catalog.mjs').CatalogItem[]}
318
- */
319
- function cachedComponentItems(project, group) {
320
- itemsKey ??= codeFingerprint(import.meta.url);
321
- if (!project.cacheDir) return componentItems(project, group);
322
- const file = path.join(project.cacheDir, 'items.json');
323
- let kept = itemsByFile.get(file);
324
- if (!kept) {
325
- kept = {};
326
- try {
327
- const cached = JSON.parse(fs.readFileSync(file, 'utf8'));
328
- if (
329
- cached?.itemsKey === itemsKey &&
330
- cached.coreKey === project.coreKey &&
331
- cached.groups &&
332
- typeof cached.groups === 'object'
333
- )
334
- for (const [g, items] of Object.entries(cached.groups))
335
- if (Array.isArray(items)) kept[g] = JSON.stringify(items);
336
- } catch {
337
- // Not made yet, or unreadable: made now.
338
- }
339
- itemsByFile.set(file, kept);
340
- }
341
- const at = group ?? '';
342
- if (kept[at] == null) {
343
- kept[at] = JSON.stringify(componentItems(project, group));
344
- try {
345
- fs.mkdirSync(project.cacheDir, {recursive: true});
346
- // Written beside it and renamed in, so a reader never sees half a
347
- // file; another command writing at once leaves one whole file.
348
- const part = `${file}.${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
349
- fs.writeFileSync(
350
- part,
351
- `{"itemsKey":${JSON.stringify(itemsKey)},"coreKey":${JSON.stringify(project.coreKey)},"groups":{${Object.entries(
352
- kept,
353
- )
354
- .map(([g, json]) => `${JSON.stringify(g)}:${json}`)
355
- .join(',')}}}`,
356
- );
357
- fs.renameSync(part, file);
358
- } catch {
359
- // A read-only node_modules: made again next time.
360
- }
361
- }
362
- return JSON.parse(kept[at]);
363
- }
364
-
365
- /**
366
- * Items of the theme-building page: each component once per variant
367
- * (overlays open), the sample page, and template pages
368
- * whose packages the project has.
369
- * @param {import('./_project.mjs').ThemeProject} project
370
- * @param {string | undefined} group only this group
371
- * @returns {{items: import('./_catalog.mjs').CatalogItem[], imports: Record<string, import('./_catalog.mjs').Binding>, skipped: string[], notes: string[]}}
372
- */
373
- export function showcaseItems(project, group) {
374
- return withPages(project, group, cachedComponentItems(project, group));
375
- }
376
-
377
- /**
378
- * The component items of the theme-building page ({@link showcaseItems}).
379
- * @param {import('./_project.mjs').ThemeProject} project
380
- * @param {string | undefined} group only this group
381
- * @returns {import('./_catalog.mjs').CatalogItem[]}
382
- */
383
- function componentItems(project, group) {
384
- /** @type {import('./_catalog.mjs').CatalogItem[]} */
385
- const items = [];
386
- /** @param {string} name */
387
- const groupFor = name => familyOf(project, name);
388
- for (const name of Object.keys(project.components)) {
389
- const g = groupFor(name);
390
- if (!g) continue;
391
- const inParent = inParentOf(project, name);
392
- if (inParent === null) continue;
393
- // A component no Core module exports by its name cannot be imported,
394
- // so it would draw an empty cell: it gets none.
395
- if (!importPathOf(project, name)) continue;
396
- const info = project.components[name];
397
- if (!shownOnSection(project, name, group)) continue;
398
- // A deprecated part is not drawn: a theme styles the part that replaces
399
- // it. An overlay whose playground opens it over the page draws nothing
400
- // closed (a phone's navigation drawer, slid out of the window): where
401
- // the open states draw it open, that is its only cell, on every page.
402
- if (info?.deprecated) continue;
403
- if (info?.overlay && OPEN_SCENES.some(s => s.name === name)) continue;
404
- catalogVariants(project, name, 12, {shown: true}).forEach((v, i) =>
405
- items.push({
406
- group: g,
407
- name,
408
- label: v.label,
409
- tree: inParent({
410
- __element: name,
411
- // A doc's sample children may name a part by an older name (a
412
- // stack, a heading): each is drawn by the name Core exports.
413
- props: /** @type {Record<string, unknown>} */ (
414
- withAstryxControls(
415
- project,
416
- withCoreAliases(
417
- project,
418
- withSampleContent(project, name, v.props),
419
- ),
420
- )
421
- ),
422
- }),
423
- // An overlay shown open is drawn open: Core places a popover,
424
- // tooltip or hover card only once it is mounted. Any other part, as
425
- // first shown, is shown open with the overlays too when a press
426
- // opens one from it (the page sees which: _catalog.mjs).
427
- // A part of another part that opens a layer of its own (a menu's
428
- // submenu, a tab list's overflow menu) is drawn open as any part
429
- // is: only an overlay's own parts stay inside it (above).
430
- ...(info?.opens
431
- ? {open: true, ...(info?.props?.placement ? {anchored: true} : {})}
432
- : i === 0 && g !== 'overlays'
433
- ? {
434
- openable: true,
435
- // A prop its doc names that opens it opens it; else the
436
- // drawing's press does. A part that waits after a keystroke
437
- // before it searches (a typeahead's `debounceMs`) waits for
438
- // none: the drawing types once and reads the list then.
439
- ...(OPENERS.some(p => info?.props?.[p]) ||
440
- info?.props?.debounceMs
441
- ? {
442
- openTree: inParent({
443
- __element: name,
444
- props: {
445
- ...v.props,
446
- ...(OPENERS.some(p => info?.props?.[p])
447
- ? {
448
- [/** @type {string} */ (
449
- OPENERS.find(p => info?.props?.[p])
450
- )]: true,
451
- }
452
- : {}),
453
- ...(info?.props?.debounceMs ? {debounceMs: 0} : {}),
454
- },
455
- }),
456
- }
457
- : {}),
458
- }
459
- : {}),
460
- }),
461
- );
462
- }
463
- // The overlays section also shows overlays in deeper states (a submenu, a
464
- // form in a popover), and the sample page's controls in each state a
465
- // person puts them in. A scene a Core without one of its parts cannot
466
- // draw is left out.
467
- if (!group || group === 'overlays') {
468
- for (const scene of OPEN_SCENES)
469
- if ([...elementNames(scene.tree)].every(n => importPathOf(project, n)))
470
- items.push({
471
- ...scene,
472
- // A cell of its own: a deeper state is as tall as the overlay.
473
- name: `${scene.name} ${scene.label}`,
474
- group: 'overlays',
475
- ...(scene.openable ? {onlyOpen: true} : {}),
476
- });
477
- for (const c of sampleControls())
478
- if ([...elementNames(c.tree)].every(n => importPathOf(project, n)))
479
- items.push({
480
- group: 'overlays',
481
- name: [...elementNames(c.tree)].at(-1) ?? '',
482
- label: c.label,
483
- tree: c.tree,
484
- states: true,
485
- });
486
- }
487
- return items;
488
- }
489
-
490
- /**
491
- * {@link showcaseItems}' items with the sample app and the template pages
492
- * whose packages the project has (read from the project each time: what it
493
- * installs can change).
494
- * @param {import('./_project.mjs').ThemeProject} project
495
- * @param {string | undefined} group only this group
496
- * @param {import('./_catalog.mjs').CatalogItem[]} items
497
- * @returns {{items: import('./_catalog.mjs').CatalogItem[], imports: Record<string, import('./_catalog.mjs').Binding>, skipped: string[], notes: string[]}}
498
- */
499
- function withPages(project, group, items) {
500
- items.push({
501
- group: 'pages',
502
- name: 'Sample app',
503
- label: '',
504
- tree: SAMPLE_PAGE,
505
- });
506
- /** @type {string[]} */
507
- const skipped = [];
508
- /** What a page in the sheet cannot show, said in the result. @type {string[]} */
509
- const notes = [];
510
- /** @type {Record<string, import('./_catalog.mjs').Binding>} */
511
- const templateImports = {};
512
- for (const t of PAGE_TEMPLATES) {
513
- const file = path.join(TEMPLATES_DIR, t, 'page.tsx');
514
- if (!fs.existsSync(file)) continue;
515
- const src = templatePageSource(t);
516
- const pkgs = [...extractImportedPackages(src)].filter(
517
- pkg => !findNodeModulesPackage(project.cwd, pkg),
518
- );
519
- if (pkgs.length) {
520
- skipped.push(
521
- `the ${t} page needs ${pkgs.join(', ')} (${installLine(project.cwd, pkgs)})`,
522
- );
523
- continue;
524
- }
525
- const drawn = [...extractImportedPackages(src)].filter(pkg =>
526
- DRAWN_IN_BROWSER.includes(pkg),
527
- );
528
- if (drawn.length && (!group || group === 'pages'))
529
- notes.push(
530
- `the ${t} page's charts are drawn in the browser (${drawn.join(', ')}), so sheet.html and its pictures show the page with their space empty; the in-app preview draws them (astryx experimental theme preview add --template ${t})`,
531
- );
532
- const local = `Template_${t.replace(/-/g, '_')}`;
533
- // A template page is its file's default export.
534
- templateImports[local] = {from: `./templates/${t}.tsx`, export: 'default'};
535
- items.push({
536
- group: 'pages',
537
- name: `${t} template`,
538
- label: '',
539
- tree: {__element: local, props: {}},
540
- });
541
- }
542
- const order = (/** @type {import('./_catalog.mjs').CatalogItem} */ it) => {
543
- const i = SHEET_ORDER.indexOf(it.name);
544
- return SHOWCASE_GROUPS.indexOf(it.group ?? '') * 1000 + (i < 0 ? 500 : i);
545
- };
546
- // The overlays section also shows open each part another section holds
547
- // that opens one (a dropdown's menu), and only open.
548
- const chosen = items
549
- .flatMap(it =>
550
- !group || it.group === group
551
- ? [it]
552
- : group === 'overlays' && it.openable
553
- ? [{...it, onlyOpen: true}]
554
- : [],
555
- )
556
- .sort((a, b) => order(a) - order(b) || compareText(a.name, b.name));
557
- /** @type {Record<string, import('./_catalog.mjs').Binding>} */
558
- const imports = {};
559
- for (const n of elementNames(chosen.map(i => i.tree))) {
560
- if (templateImports[n]) {
561
- imports[n] = templateImports[n];
562
- continue;
563
- }
564
- const spec = importPathOf(project, n);
565
- if (spec) imports[n] = spec;
566
- }
567
- return {
568
- items: chosen,
569
- imports,
570
- skipped: !group || group === 'pages' ? skipped : [],
571
- notes,
572
- };
573
- }
574
-
575
- /** Wrapper props that open a layer. A part shown on the page stays closed. */
576
- const OPEN_PROPS = ['isOpen', 'isMenuOpen', 'defaultOpen', 'defaultIsOpen'];
577
-
578
- /**
579
- * How a component renders on its own: unchanged for a whole component; for
580
- * a part of another, inside the parent its playground names. Null for a part
581
- * with no such parent, or whose parent needs a parent of its own: the part
582
- * only works inside its parent, and the parent's own item shows it.
583
- * @param {import('./_project.mjs').ThemeProject} project
584
- * @param {string} name
585
- * @returns {((tree: import('./_catalog.mjs').Tree) => import('./_catalog.mjs').Tree) | null}
586
- */
587
- function inParentOf(project, name) {
588
- const info = project.components[name];
589
- if (!info?.subComponentOf) return tree => tree;
590
- const wrapper = info.wrapper;
591
- // A part of a parent that shows inline (a dialog's header) renders inside
592
- // that parent shown open and inline, as Core's docs show it: alone, it
593
- // acts as in a modal one (a dialog header takes focus as it mounts).
594
- const of = info.subComponentOf;
595
- const parent = project.components[of];
596
- if (!wrapper && parent?.props?.isInline && parent.props.isOpen) {
597
- const props = Object.fromEntries(
598
- Object.entries(demoProps(project, of) ?? {}).filter(
599
- ([k]) => k !== 'children',
600
- ),
601
- );
602
- return tree => ({
603
- __element: of,
604
- props: {...props, isOpen: true, isInline: true},
605
- children: [tree],
606
- });
607
- }
608
- // A part its parent does not list as an item, such as a heading of the
609
- // text family, renders on its own.
610
- if (!wrapper) return needsParent(project, name) ? null : tree => tree;
611
- if (project.components[wrapper.component]?.wrapper) return null;
612
- const props = Object.fromEntries(
613
- Object.entries(wrapper.props).filter(([k]) => !OPEN_PROPS.includes(k)),
614
- );
615
- return tree => ({__element: wrapper.component, props, children: [tree]});
616
- }
617
-
618
- /**
619
- * Template page modules the theme-building page imports, written beside it
620
- * as a copy of the template writes them: each icon placeholder import is the
621
- * library import that draws it.
622
- * @param {Record<string, import('./_catalog.mjs').Binding>} imports
623
- * @returns {Array<{name: string, text: string}>}
624
- */
625
- function templateFiles(imports) {
626
- return Object.values(imports).flatMap(b => {
627
- const m = /^\.\/templates\/([a-z0-9-]+)\.tsx$/.exec(bindingFrom(b));
628
- return m
629
- ? [
630
- {
631
- name: `templates/${m[1]}.tsx`,
632
- text: templatePageSource(m[1]),
633
- },
634
- ]
635
- : [];
636
- });
637
- }
638
-
639
- /**
640
- * The fonts stylesheet of the theme a theme is built on, when its package
641
- * ships one (`@astryxdesign/theme-neutral/fonts.css` loads Figtree): naming
642
- * a family does not load it, and the base theme's families apply until the
643
- * theme sets its own. Once the theme's build names none of the families the
644
- * sheet loads, it is left out.
645
- * @param {import('./_settings.mjs').Ctx} ctx
646
- * @param {import('./_settings.mjs').ThemeData} data
647
- * @returns {string[]}
648
- */
649
- export function baseFontsCss(ctx, data) {
650
- const sheet = baseFontsSheet(ctx, data);
651
- return sheet ? [sheet.spec] : [];
652
- }
653
-
654
- /**
655
- * The base theme's fonts stylesheet as {@link baseFontsCss} imports it: its
656
- * import spec, the families it loads, and the remote stylesheets it loads
657
- * them from (a Google Fonts `@import`), which a static page cannot load.
658
- * Null when the base ships none or the build names none of its families.
659
- * @param {import('./_settings.mjs').Ctx} ctx
660
- * @param {import('./_settings.mjs').ThemeData} data
661
- * With the weights it loads of each family (`weights`, by family; none
662
- * for a family whose weights it does not say, such as a variable face).
663
- * @returns {{spec: string, families: string[], remote: string[], weights: Map<string, number[]>} | null}
664
- */
665
- export function baseFontsSheet(ctx, data) {
666
- if (!data.like) return null;
667
- const pkg = `@astryxdesign/theme-${data.like}`;
668
- const sheet = `${pkg}/fonts.css`;
669
- // Read off disk: the package must export the sheet for an app to import
670
- // it.
671
- const found = findNodeModulesPackage(ctx.project.cwd, pkg);
672
- /** @type {string} */
673
- let text;
674
- try {
675
- if (!found) return null;
676
- const exportsMap = JSON.parse(
677
- fs.readFileSync(path.join(found.packageDir, 'package.json'), 'utf8'),
678
- ).exports;
679
- if (
680
- !exportsMap ||
681
- typeof exportsMap !== 'object' ||
682
- !('./fonts.css' in exportsMap)
683
- )
684
- return null;
685
- text = fs.readFileSync(path.join(found.packageDir, 'fonts.css'), 'utf8');
686
- } catch {
687
- return null;
688
- }
689
- // The families the sheet loads, from a font service request or from its
690
- // own `@font-face` rules (a base that ships its font files); with the
691
- // theme's build at hand, the sheet is imported only while the build still
692
- // names one of them.
693
- const faces = fontFaces(text);
694
- const families = [
695
- ...new Set([
696
- ...[...text.matchAll(/family=([^:&'")]+)/g)].map(m =>
697
- decodeURIComponent(m[1].replace(/\+/g, ' ')),
698
- ),
699
- ...faces.map(f => f.family),
700
- ]),
701
- ];
702
- /** @type {string | null} */
703
- let built = null;
704
- try {
705
- built = fs.readFileSync(themeFiles(ctx.project.cwd, data.name).css, 'utf8');
706
- } catch {
707
- // Not built yet: the base families may still apply.
708
- }
709
- if (built != null && families.length) {
710
- const css = built;
711
- if (!families.some(f => css.includes(f))) return null;
712
- }
713
- const remote = [
714
- ...text.matchAll(
715
- /@import\s+(?:url\(\s*)?["']?((?:[a-z]+:)?\/\/[^"')\s]+)/gi,
716
- ),
717
- ].map(m => m[1]);
718
- // The weights a font service request names: its axes (`wght`,
719
- // `ital,wght`, `opsz,wght`) and one tuple of values per face
720
- // (`Figtree:wght@400;500`, `Fraunces:opsz,wght@9..144,400`), the weight
721
- // at the wght axis's place in each tuple.
722
- /** @type {Map<string, number[]>} */
723
- const weights = new Map();
724
- for (const m of text.matchAll(/family=([^:&'")]+):([a-z,]+)@([0-9;,.]+)/gi)) {
725
- const family = decodeURIComponent(m[1].replace(/\+/g, ' '));
726
- const at = m[2].toLowerCase().split(',').indexOf('wght');
727
- if (at < 0) continue;
728
- const values = m[3].split(';').map(t => t.split(',')[at] ?? '');
729
- // A range (`100..900`) is a variable face: every weight in it.
730
- if (values.some(v => v.includes('..'))) continue;
731
- const list = values.map(Number).filter(n => Number.isInteger(n));
732
- if (list.length)
733
- weights.set(
734
- family,
735
- [...new Set(list)].sort((a, b) => a - b),
736
- );
737
- }
738
- // The weights the sheet's own faces load: one weight each; a range
739
- // (`100 900`) is a variable face, every weight in it, so none is listed.
740
- for (const family of new Set(faces.map(f => f.family))) {
741
- const own = faces.filter(f => f.family === family).map(f => f.weights);
742
- if (own.some(w => !w || w[0] !== w[1])) continue;
743
- const list = own.flatMap(w => (w ? [w[0]] : []));
744
- if (list.length)
745
- weights.set(
746
- family,
747
- [...new Set([...(weights.get(family) ?? []), ...list])].sort(
748
- (a, b) => a - b,
749
- ),
750
- );
751
- }
752
- return {spec: sheet, families, remote, weights};
753
- }
754
-
755
- /**
756
- * The stylesheets of an installed font package that load the theme's
757
- * fonts in every weight it uses: a variable package's one stylesheet
758
- * (every weight); for a package with a stylesheet per weight, as
759
- * Fontsource ships them, each weight the theme's build uses that the
760
- * package has; else its index stylesheet. When the theme sets italic text,
761
- * each with its italic stylesheet the package has.
762
- * @param {import('./_settings.mjs').Ctx} ctx
763
- * @param {string} slug
764
- * @param {string} pkg
765
- * @returns {string[]}
766
- */
767
- export function fontPackageSheets(ctx, slug, pkg) {
768
- /** Whether the package has a stylesheet. @param {string} sheet */
769
- const has = sheet => {
770
- try {
771
- ctx.project.req.resolve(sheet);
772
- return true;
773
- } catch {
774
- return false;
775
- }
776
- };
777
- // Italic text loads the italic face of each sheet beside it, as
778
- // Fontsource names them (`400-italic.css`, a variable package's
779
- // `wght-italic.css`), where the package has it.
780
- const italic = builtItalic(ctx, slug);
781
- /** A sheet and, for italic text, its italic one. @param {string} upright @param {string} slanted */
782
- const withItalic = (upright, slanted) => [
783
- upright,
784
- ...(italic && has(slanted) ? [slanted] : []),
785
- ];
786
- const faces = fontPackageWeights(ctx, pkg);
787
- if (!faces?.length)
788
- return withItalic(`${pkg}/index.css`, `${pkg}/wght-italic.css`);
789
- // Each weight the theme uses loads the face CSS font matching shows for
790
- // it (550 shows the 600 face), once.
791
- const shown = new Set(
792
- (builtFontWeights(ctx, slug) ?? [400]).map(w => shownWeight(w, faces)),
793
- );
794
- return faces
795
- .filter(w => shown.has(w))
796
- .flatMap(w => withItalic(`${pkg}/${w}.css`, `${pkg}/${w}-italic.css`));
797
- }
798
-
799
- /**
800
- * The weights an installed font package has a stylesheet of its own for
801
- * (`@fontsource/lobster/400.css`), as Fontsource ships a static family;
802
- * null for a variable package or one with no stylesheet per weight, which
803
- * loads every weight it has from its index stylesheet.
804
- * @param {import('./_settings.mjs').Ctx} ctx
805
- * @param {string} pkg
806
- * @returns {number[] | null}
807
- */
808
- export function fontPackageWeights(ctx, pkg) {
809
- if (pkg.startsWith('@fontsource-variable/')) return null;
810
- const faces = [100, 200, 300, 400, 500, 600, 700, 800, 900].filter(w => {
811
- try {
812
- ctx.project.req.resolve(`${pkg}/${w}.css`);
813
- return true;
814
- } catch {
815
- return false;
816
- }
817
- });
818
- return faces.length ? faces : null;
819
- }
820
-
821
- /**
822
- * The weights a font package's index stylesheet loads, read from its own
823
- * @font-face rules: each rule's font-weight as a [from, to] span, one
824
- * weight (`400`) or a range (`100 900`, a variable face, every weight in
825
- * it); a rule with no font-weight is weight 400. Null when the package is
826
- * not installed here or its sheet names no face.
827
- * @param {import('./_settings.mjs').Ctx} ctx
828
- * @param {string} pkg
829
- * @returns {Array<[number, number]> | null}
830
- */
831
- export function fontIndexWeights(ctx, pkg) {
832
- /** @type {string} */
833
- let text;
834
- try {
835
- text = fs.readFileSync(ctx.project.req.resolve(`${pkg}/index.css`), 'utf8');
836
- } catch {
837
- return null;
838
- }
839
- const spans = fontFaces(text).flatMap(face =>
840
- face.weights ? [face.weights] : [],
841
- );
842
- return spans.length ? spans : null;
843
- }
844
-
845
- /**
846
- * The face a browser shows for a font weight among the weights a family
847
- * loads, by CSS font matching: from 400 to 500, the weights up to 500
848
- * first, then lighter, then heavier; below 400, lighter first; above 500,
849
- * heavier first.
850
- * @param {number} weight
851
- * @param {number[]} faces
852
- * @returns {number}
853
- */
854
- export function shownWeight(weight, faces) {
855
- if (faces.includes(weight)) return weight;
856
- const up = faces.filter(w => w > weight).sort((a, b) => a - b);
857
- const down = faces.filter(w => w < weight).sort((a, b) => b - a);
858
- const order =
859
- weight >= 400 && weight <= 500
860
- ? [...up.filter(w => w <= 500), ...down, ...up.filter(w => w > 500)]
861
- : weight < 400
862
- ? [...down, ...up]
863
- : [...up, ...down];
864
- return order[0] ?? weight;
865
- }
866
-
867
- /**
868
- * How a generated page imports the theme: its built module, its stylesheet,
869
- * and the stylesheets of open fonts the project has installed.
870
- * @param {import('./_settings.mjs').Ctx} ctx
871
- * @param {string} slug
872
- * @param {import('./_settings.mjs').ThemeData} data
873
- * @param {string} fromDir the folder of the page
874
- */
875
- export function themeImports(ctx, slug, data, fromDir) {
876
- const f = themeFiles(ctx.project.cwd, slug);
877
- /** @param {string} file */
878
- const rel = file => {
879
- const r = path.relative(fromDir, file).split(path.sep).join('/');
880
- return r.startsWith('.') ? r : `./${r}`;
881
- };
882
- const modes = modesOf(data);
883
- const fonts = fontPackages(ctx, data)
884
- .filter(x => x.installed)
885
- .flatMap(x => fontPackageSheets(ctx, slug, x.pkg));
886
- return {
887
- module: rel(f.js),
888
- css: [rel(f.css), ...baseFontsCss(ctx, data), ...fonts],
889
- mode: /** @type {'system' | 'light' | 'dark'} */ (
890
- modes.length > 1 ? 'system' : modes[0]
891
- ),
892
- };
893
- }
894
-
895
- /**
896
- * The inputs a page was rendered from and a hash of the page above it,
897
- * recorded at the end of the page.
898
- */
899
- const RENDER_STAMP = /<!-- astryx: render of ([0-9a-f]{24}) ([0-9a-f]{16}) -->/;
900
-
901
- /** @type {Map<string, string>} */
902
- const treeKeys = new Map();
903
-
904
- /**
905
- * A cheap fingerprint of the files a package runs from: each file's path,
906
- * size and modification time under its folder (node_modules left out), so a
907
- * linked or patched copy with the same version reads as another. Once per
908
- * process for each folder.
909
- * @param {string | null | undefined} dir
910
- * @returns {string}
911
- */
912
- function treeKey(dir) {
913
- if (!dir) return 'none';
914
- const known = treeKeys.get(dir);
915
- if (known) return known;
916
- const h = createHash('sha256');
917
- /** @param {string} d */
918
- const walk = d => {
919
- let entries;
920
- try {
921
- entries = fs.readdirSync(d, {withFileTypes: true});
922
- } catch {
923
- return;
924
- }
925
- entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
926
- for (const e of entries) {
927
- if (e.name === 'node_modules' || e.name.startsWith('.')) continue;
928
- const p = path.join(d, e.name);
929
- if (e.isDirectory()) walk(p);
930
- else if (e.isFile()) {
931
- try {
932
- const st = fs.statSync(p);
933
- h.update(`${path.relative(dir, p)}\0${st.size}\0${st.mtimeMs}\0`);
934
- } catch {
935
- // Gone meanwhile.
936
- }
937
- }
938
- }
939
- };
940
- walk(dir);
941
- const key = h.digest('hex').slice(0, 16);
942
- treeKeys.set(dir, key);
943
- return key;
944
- }
945
-
946
- /**
947
- * The folder of an installed package, resolved from the project, or null.
948
- * @param {string} cwd
949
- * @param {string} name
950
- */
951
- function packageDirOf(cwd, name) {
952
- try {
953
- return findNodeModulesPackage(cwd, name)?.packageDir ?? null;
954
- } catch {
955
- return null;
956
- }
957
- }
958
-
959
- /** @param {string} text */
960
- const bodyHash = text =>
961
- createHash('sha256').update(text).digest('hex').slice(0, 16);
962
-
963
- /**
964
- * A key for everything a page render reads: the CLI, Core (its version and
965
- * stylesheet, and the files it runs from), the base theme package's files,
966
- * the generated page source, and the theme's built stylesheet and module.
967
- * The same key means the same page.
968
- * @param {import('./_project.mjs').ThemeProject} project
969
- * @param {string} slug
970
- * @param {string} source
971
- * @param {string | null | undefined} [like] the base theme
972
- * @returns {string}
973
- */
974
- function renderKey(project, slug, source, like) {
975
- const f = themeFiles(project.cwd, slug);
976
- const h = createHash('sha256')
977
- .update(cliVersion())
978
- .update('\0')
979
- .update(String(project.coreKey ?? ''))
980
- .update('\0')
981
- .update(treeKey(path.join(project.coreDir, 'dist')))
982
- .update('\0')
983
- .update(
984
- like
985
- ? treeKey(packageDirOf(project.cwd, `@astryxdesign/theme-${like}`))
986
- : 'none',
987
- )
988
- .update('\0')
989
- .update(source);
990
- for (const file of [f.css, f.js]) {
991
- h.update('\0');
992
- try {
993
- h.update(fs.readFileSync(file));
994
- } catch {
995
- h.update('missing');
996
- }
997
- }
998
- return h.digest('hex').slice(0, 24);
999
- }
1000
-
1001
- /**
1002
- * The stamps the editor writes into every page it makes: the render key
1003
- * at its end, and a sheet's build.
1004
- */
1005
- const EDITOR_PAGE_STAMP =
1006
- /<!-- astryx: (?:render of [0-9a-f]{24} [0-9a-f]{16}|sheet of build [0-9a-f]{16}) -->/;
1007
-
1008
- /**
1009
- * What is at the name of a page the editor writes in the theme folder
1010
- * (preview.html, sheet.html, a section's sheet, the open states page) when
1011
- * it is not the editor's own page: `link`, `folder`, `other` (not a plain
1012
- * file) or `file` (a file without the editor's stamp). Null when nothing
1013
- * is there or the page there is the editor's. Something of yours at a
1014
- * page's name is never written over: it is left as it is, and named.
1015
- * @param {string} file
1016
- * @returns {'link' | 'folder' | 'other' | 'file' | null}
1017
- */
1018
- export function pageInTheWay(file) {
1019
- const st = fs.lstatSync(file, {throwIfNoEntry: false});
1020
- if (!st) return null;
1021
- if (st.isSymbolicLink()) return 'link';
1022
- if (st.isDirectory()) return 'folder';
1023
- if (!st.isFile()) return 'other';
1024
- try {
1025
- return EDITOR_PAGE_STAMP.test(readRegularFile(file, 'utf8'))
1026
- ? null
1027
- : 'file';
1028
- } catch {
1029
- return 'file';
1030
- }
1031
- }
1032
-
1033
- /**
1034
- * Refuse to write a page over a pipe, a device or a socket at its name: a
1035
- * write renamed into place would replace it, and something of yours at a
1036
- * page's name is never written over.
1037
- * @param {string} cwd
1038
- * @param {string} file
1039
- * @param {string} page what goes there
1040
- */
1041
- function refuseOverIrregular(cwd, file, page) {
1042
- if (pageInTheWay(file) !== 'other') return;
1043
- throw new AstryxError(
1044
- `${inTheWayPhrase(shown(cwd, file), 'other', page)}; it is left as it is. Move it, then run the command again.`,
1045
- [],
1046
- ERROR_CODES.ERR_WRITE_FAILED,
1047
- );
1048
- }
1049
-
1050
- /**
1051
- * What {@link pageInTheWay} found, said: `<file> is a link, and the editor
1052
- * writes nothing through a link`, `… is a folder, where <page> goes`, `…
1053
- * is a file the editor did not write, and it is left as it is`.
1054
- * @param {string} shownFile the file, as shown
1055
- * @param {'link' | 'folder' | 'other' | 'file'} kind
1056
- * @param {string} page what goes there (`the open states page`)
1057
- */
1058
- export function inTheWayPhrase(shownFile, kind, page) {
1059
- return kind === 'link'
1060
- ? `${shownFile} is a link, and the editor writes nothing through a link`
1061
- : kind === 'file'
1062
- ? `${shownFile} is a file the editor did not write, and it is left as it is`
1063
- : `${shownFile} is ${kind === 'folder' ? 'a folder' : 'not a plain file'}, where ${page} goes`;
1064
- }
1065
-
1066
- /**
1067
- * Whether `out` is a page rendered from `key` (a no-op show renders
1068
- * nothing again).
1069
- * @param {string} out
1070
- * @param {string} key
1071
- */
1072
- function renderedFrom(out, key) {
1073
- try {
1074
- const st = fs.lstatSync(out);
1075
- if (!st.isFile()) return false;
1076
- const text = fs.readFileSync(out, 'utf8');
1077
- const m = RENDER_STAMP.exec(text);
1078
- // The page above the comment is the one rendered: an edit by hand, or
1079
- // a comment pasted under another page, is rendered again.
1080
- // Nothing may follow the comment but the sheet's own build stamp
1081
- // (written after it by show): text added after it is rendered over.
1082
- const after = m
1083
- ? text
1084
- .slice(m.index + m[0].length)
1085
- .replace(/<!-- astryx: sheet of build [0-9a-f]{16} -->/, '')
1086
- : '';
1087
- return (
1088
- m != null &&
1089
- m[1] === key &&
1090
- after.trim() === '' &&
1091
- m[2] === bodyHash(text.slice(0, m.index).trimEnd())
1092
- );
1093
- } catch {
1094
- return false;
1095
- }
1096
- }
1097
-
1098
- /**
1099
- * The page with its render key recorded at its end (after the closing tag:
1100
- * a comment before the doctype would put it in quirks mode).
1101
- * @param {string} html
1102
- * @param {string} key
1103
- */
1104
- const withRenderKey = (html, key) => {
1105
- const body = html.replace(RENDER_STAMP, '').trimEnd();
1106
- return `${body}\n<!-- astryx: render of ${key} ${bodyHash(body)} -->\n`;
1107
- };
1108
-
1109
- /**
1110
- * The sample page source of a theme's preview.html, its file, and the key
1111
- * of the inputs it is rendered from.
1112
- * @param {import('./_settings.mjs').Ctx} ctx
1113
- * @param {string} slug
1114
- * @param {import('./_settings.mjs').ThemeData} data
1115
- */
1116
- function previewInputs(ctx, slug, data) {
1117
- const {project} = ctx;
1118
- /** @type {Record<string, import('./_catalog.mjs').Binding>} */
1119
- const imports = {};
1120
- for (const n of elementNames(SAMPLE_PAGE)) {
1121
- const spec = importPathOf(project, n);
1122
- if (spec) imports[n] = spec;
1123
- }
1124
- // Below the sample page, a strip of overlays drawn open (a tooltip, a
1125
- // popover, a menu, a select list), from the overlays the sheet draws, so
1126
- // the one picture every look starts from shows them too.
1127
- const overlays = showcaseItems(project, 'overlays');
1128
- /** @type {import('./_catalog.mjs').CatalogItem[]} */
1129
- const strip = [];
1130
- for (const name of PREVIEW_OVERLAYS) {
1131
- const it = overlays.items.find(
1132
- x => x.name === name && (x.open || x.openable),
1133
- );
1134
- if (!it) continue;
1135
- strip.push({
1136
- ...it,
1137
- label: '',
1138
- strip: true,
1139
- ...(it.openable ? {onlyOpen: true} : {}),
1140
- });
1141
- for (const n of elementNames([it.tree, it.openTree ?? it.tree]))
1142
- if (overlays.imports[n]) imports[n] = overlays.imports[n];
1143
- }
1144
- const source = pageSource({
1145
- items: [{name: 'page', label: '', tree: SAMPLE_PAGE}, ...strip],
1146
- imports,
1147
- theme: themeImports(ctx, slug, data, renderDir(project)),
1148
- layout: 'page',
1149
- title: `${slug}: sample page`,
1150
- });
1151
- const out = themeFiles(project.cwd, slug).preview;
1152
- return {source, out, key: renderKey(project, slug, source, data.like)};
1153
- }
1154
-
1155
- /**
1156
- * Whether themes/<slug>/preview.html was rendered from the theme as it is
1157
- * now (the same check renderPreview makes before it renders again).
1158
- * @param {import('./_settings.mjs').Ctx} ctx
1159
- * @param {string} slug
1160
- * @param {import('./_settings.mjs').ThemeData} data
1161
- */
1162
- export function previewIsCurrent(ctx, slug, data) {
1163
- try {
1164
- const {out, key} = previewInputs(ctx, slug, data);
1165
- return renderedFrom(out, key);
1166
- } catch {
1167
- return false;
1168
- }
1169
- }
1170
-
1171
- /**
1172
- * Render the sample app page with the theme to themes/<slug>/preview.html.
1173
- * @param {import('./_settings.mjs').Ctx} ctx
1174
- * @param {string} slug
1175
- * @param {import('./_settings.mjs').ThemeData} data
1176
- * @returns {Promise<string>} the file written, as shown
1177
- */
1178
- export async function renderPreview(ctx, slug, data) {
1179
- const {project} = ctx;
1180
- const {source, out, key} = previewInputs(ctx, slug, data);
1181
- // Rendered from the same inputs before: the page is as it would be.
1182
- if (renderedFrom(out, key)) return shown(project.cwd, out);
1183
- const {html} = await renderGenerated(project, `preview-${slug}.mjs`, source);
1184
- refuseOverIrregular(project.cwd, out, 'the sample page');
1185
- // Written whole and renamed in, never through a link; an auto media
1186
- // surface drawn on the side the app's measurement picks.
1187
- writeWhole(
1188
- out,
1189
- withRenderKey(
1190
- settleMediaSides(
1191
- html,
1192
- await mediaSurfaceSides(ctx, slug, data),
1193
- themeImports(ctx, slug, data, renderDir(project)).mode,
1194
- ),
1195
- key,
1196
- ),
1197
- );
1198
- return shown(project.cwd, out);
1199
- }
1200
-
1201
- /**
1202
- * Render the theme-building page with the theme to one HTML file.
1203
- * @param {import('./_settings.mjs').Ctx} ctx
1204
- * @param {string} slug
1205
- * @param {import('./_settings.mjs').ThemeData} data
1206
- * @param {{group?: string, out?: string}} [options]
1207
- * @returns {Promise<{file: string, components: number, skipped: string[], notes: string[]}>} `notes`: what a page in the sheet cannot show
1208
- */
1209
- export async function renderSheet(ctx, slug, data, options = {}) {
1210
- const {project} = ctx;
1211
- const {items, imports, skipped, notes} = showcaseItems(
1212
- project,
1213
- options.group,
1214
- );
1215
- const source = pageSource({
1216
- items,
1217
- imports,
1218
- theme: themeImports(ctx, slug, data, renderDir(project)),
1219
- layout: 'sheet',
1220
- section: options.group,
1221
- title: `${slug}: every component${options.group ? ` (${options.group})` : ''}`,
1222
- });
1223
- // One section goes to its own file, so the full sheet stays whole.
1224
- const full = themeFiles(project.cwd, slug).sheet;
1225
- const out =
1226
- options.out ??
1227
- (options.group
1228
- ? path.join(path.dirname(full), `sheet-${options.group}.html`)
1229
- : full);
1230
- const key = renderKey(project, slug, source, data.like);
1231
- const result = {
1232
- file: shown(project.cwd, out),
1233
- components: new Set(items.map(i => i.name)).size,
1234
- skipped,
1235
- notes,
1236
- };
1237
- // Rendered from the same inputs before: the sheet is as it would be.
1238
- if (renderedFrom(out, key)) return result;
1239
- const {html} = await renderGenerated(
1240
- project,
1241
- `sheet-${slug}.mjs`,
1242
- source,
1243
- templateFiles(imports),
1244
- );
1245
- fs.mkdirSync(path.dirname(out), {recursive: true});
1246
- refuseOverIrregular(project.cwd, out, 'the sheet');
1247
- // Written whole and renamed in, never through a link; an auto media
1248
- // surface drawn on the side the app's measurement picks.
1249
- writeWhole(
1250
- out,
1251
- withRenderKey(
1252
- settleMediaSides(
1253
- html,
1254
- await mediaSurfaceSides(ctx, slug, data),
1255
- themeImports(ctx, slug, data, renderDir(project)).mode,
1256
- ),
1257
- key,
1258
- ),
1259
- );
1260
- return {
1261
- file: shown(project.cwd, out),
1262
- components: new Set(items.map(i => i.name)).size,
1263
- skipped,
1264
- notes,
1265
- };
1266
- }
1267
-
1268
- /** @param {unknown} v @returns {v is import('./_catalog.mjs').Tree} */
1269
- const isElement = v =>
1270
- Boolean(
1271
- v &&
1272
- typeof v === 'object' &&
1273
- !Array.isArray(v) &&
1274
- typeof (/** @type {any} */ (v).__element) === 'string',
1275
- );
1276
-
1277
- /**
1278
- * The Core name an element stands for, or null when Core has no module for
1279
- * it. Some playground samples still use the old `XDS` prefix (`XDSVStack`).
1280
- * @param {import('./_project.mjs').ThemeProject} project
1281
- * @param {string} name
1282
- * @returns {string | null}
1283
- */
1284
- function coreName(project, name) {
1285
- if (importPathOf(project, name)) return name;
1286
- const bare = name.replace(/^XDS(?=[A-Z])/, '');
1287
- return bare !== name && importPathOf(project, bare) ? bare : null;
1288
- }
1289
-
1290
- /**
1291
- * A copy of an element tree with Core names only. An element Core has no
1292
- * module for is left out.
1293
- * @param {import('./_project.mjs').ThemeProject} project
1294
- * @param {unknown} v
1295
- * @returns {unknown}
1296
- */
1297
- function withCoreNames(project, v) {
1298
- if (Array.isArray(v))
1299
- return v.map(x => withCoreNames(project, x)).filter(x => x !== undefined);
1300
- if (isElement(v)) {
1301
- const name = coreName(project, v.__element);
1302
- if (!name) return undefined;
1303
- const props = Object.fromEntries(
1304
- Object.entries(v.props ?? {})
1305
- .map(([k, x]) => [k, withCoreNames(project, x)])
1306
- .filter(([, x]) => x !== undefined),
1307
- );
1308
- return {
1309
- __element: name,
1310
- props,
1311
- ...(v.children === undefined
1312
- ? {}
1313
- : {children: withCoreNames(project, v.children)}),
1314
- };
1315
- }
1316
- if (v && typeof v === 'object')
1317
- return Object.fromEntries(
1318
- Object.entries(v).map(([k, x]) => [k, withCoreNames(project, x)]),
1319
- );
1320
- return v;
1321
- }
1322
-
1323
- /**
1324
- * A value with each element a doc names by an older name named as Core
1325
- * exports it; everything else is the same value, the same
1326
- * object where nothing in it changed (a part's props keep what marks them).
1327
- * @param {import('./_project.mjs').ThemeProject} project
1328
- * @param {unknown} v
1329
- * @returns {unknown}
1330
- */
1331
- function withCoreAliases(project, v) {
1332
- if (Array.isArray(v)) {
1333
- const out = v.map(x => withCoreAliases(project, x));
1334
- return out.every((x, i) => x === v[i]) ? v : out;
1335
- }
1336
- if (!v || typeof v !== 'object') return v;
1337
- if (isElement(v)) {
1338
- const name = coreName(project, v.__element) ?? v.__element;
1339
- const props = withCoreAliases(project, v.props);
1340
- const children = withCoreAliases(project, v.children);
1341
- return name === v.__element && props === v.props && children === v.children
1342
- ? v
1343
- : {...v, __element: name, props, children};
1344
- }
1345
- const entries = Object.entries(v);
1346
- const out = entries.map(([k, x]) => [k, withCoreAliases(project, x)]);
1347
- return out.every(([, x], i) => x === entries[i][1])
1348
- ? v
1349
- : {...v, ...Object.fromEntries(out)};
1350
- }
1351
-
1352
- /** @param {unknown} v @returns {boolean} */
1353
- const holdsElement = v =>
1354
- isElement(v) || (Array.isArray(v) && v.some(holdsElement));
1355
-
1356
- /**
1357
- * A prop value that is source code, such as the name of a constant the page
1358
- * defines. @param {unknown} v @returns {v is {__code: string}}
1359
- */
1360
- const isCode = v =>
1361
- Boolean(
1362
- v &&
1363
- typeof v === 'object' &&
1364
- typeof (/** @type {any} */ (v).__code) === 'string',
1365
- );
1366
-
1367
- /** @param {unknown} v @param {number} depth @returns {string} */
1368
- function jsxValue(v, depth) {
1369
- if (isElement(v)) return jsx(v, depth);
1370
- if (isCode(v)) return v.__code;
1371
- if (Array.isArray(v) && v.some(holdsElement))
1372
- return `[${v
1373
- .map((x, i) =>
1374
- isElement(x)
1375
- ? jsx({...x, props: {key: String(i), ...x.props}}, depth)
1376
- : jsxValue(x, depth),
1377
- )
1378
- .join(', ')}]`;
1379
- return JSON.stringify(v);
1380
- }
1381
-
1382
- /**
1383
- * JSX source for an element tree whose names are Core names. Each element
1384
- * renders through `C`, the page's table of Core components.
1385
- * @param {import('./_catalog.mjs').Tree} tree
1386
- * @param {number} depth
1387
- * @returns {string}
1388
- */
1389
- function jsx(tree, depth) {
1390
- const pad = ' '.repeat(depth);
1391
- const {children: childProp, ...rest} = tree.props ?? {};
1392
- const props = Object.entries(rest).map(([k, v]) =>
1393
- typeof v === 'string' && !/[{}"<>&\n]/.test(v)
1394
- ? `${k}="${v}"`
1395
- : v === true
1396
- ? k
1397
- : `${k}={${jsxValue(v, depth + 1)}}`,
1398
- );
1399
- const kids = /** @type {unknown[]} */ (
1400
- [].concat(/** @type {any} */ (tree.children ?? childProp ?? []))
1401
- );
1402
- const tag = `C.${tree.__element}`;
1403
- const open = `<${tag}${props.length ? ` ${props.join(' ')}` : ''}`;
1404
- if (!kids.length) return `${open} />`;
1405
- const inner = kids
1406
- .map(k =>
1407
- isElement(k)
1408
- ? `${pad} ${jsx(k, depth + 1)}`
1409
- : `${pad} {${jsxValue(k, depth + 1)}}`,
1410
- )
1411
- .join('\n');
1412
- return `${open}>\n${inner}\n${pad}</${tag}>`;
1413
- }
1414
-
1415
- /**
1416
- * The imports of a page and its table of components, `C`. Playground samples
1417
- * are not full prop sets (a controlled part has no handler), so `C` takes
1418
- * any props for each part; children must still be React nodes, and every
1419
- * name must be imported from Core.
1420
- * @param {import('./_project.mjs').ThemeProject} project
1421
- * @param {unknown} trees element trees with Core names
1422
- * @returns {string[]}
1423
- */
1424
- function componentTable(project, trees) {
1425
- /** @type {Map<string, string[]>} */
1426
- const byModule = new Map();
1427
- for (const name of [...elementNames(trees)].sort()) {
1428
- const spec = /** @type {string} */ (importPathOf(project, name));
1429
- byModule.set(spec, [...(byModule.get(spec) ?? []), name]);
1430
- }
1431
- const names = [...byModule.values()].flat();
1432
- return [
1433
- ...[...byModule].map(
1434
- ([spec, list]) =>
1435
- `import {${list.join(', ')}} from ${JSON.stringify(spec)};`,
1436
- ),
1437
- '',
1438
- 'type Part = React.ComponentType<{children?: React.ReactNode} & Record<string, unknown>>;',
1439
- `const C = {${names.map(n => `${n}: ${n} as unknown as Part`).join(', ')}};`,
1440
- ];
1441
- }
1442
-
1443
- const SAFE = [
1444
- '/** Shows a short note for a component that throws, so the rest of the page renders. */',
1445
- 'class Safe extends React.Component<{name: string, children: React.ReactNode}, {failed: boolean}> {',
1446
- ' override state = {failed: false};',
1447
- ' static getDerivedStateFromError() {',
1448
- ' return {failed: true};',
1449
- ' }',
1450
- ' override render() {',
1451
- ' return this.state.failed ? <div className="tp-note">{this.props.name} could not render here</div> : this.props.children;',
1452
- ' }',
1453
- '}',
1454
- ];
1455
-
1456
- /** The search source the page hands a part that needs one: a few fixed items. */
1457
- const SAMPLE_SOURCE_LINES = [
1458
- 'const SAMPLE_ITEMS = [',
1459
- ...SAMPLE_SEARCH_ITEMS.map(
1460
- i => ` {id: ${JSON.stringify(i.id)}, label: ${JSON.stringify(i.label)}},`,
1461
- ),
1462
- '];',
1463
- 'const SAMPLE_SOURCE = {',
1464
- ' search: (query: string) => SAMPLE_ITEMS.filter(item => item.label.toLowerCase().includes(query.toLowerCase())),',
1465
- ' bootstrap: () => SAMPLE_ITEMS,',
1466
- ' cancel: () => {},',
1467
- '};',
1468
- ];
1469
-
1470
- /**
1471
- * A copy of an element tree in which every part that requires a search
1472
- * source and has none gets the page's sample source. A typeahead without a
1473
- * source throws when it unmounts, and that error leaves the boundary around
1474
- * it, so leaving the page would crash the whole route.
1475
- * @param {import('./_project.mjs').ThemeProject} project
1476
- * @param {unknown} v
1477
- * @returns {unknown}
1478
- */
1479
- function withSources(project, v) {
1480
- if (Array.isArray(v)) return v.map(x => withSources(project, x));
1481
- if (isElement(v)) {
1482
- const props = Object.fromEntries(
1483
- Object.entries(v.props ?? {}).map(([k, x]) => [
1484
- k,
1485
- withSources(project, x),
1486
- ]),
1487
- );
1488
- for (const [k, p] of Object.entries(
1489
- project.components[v.__element]?.props ?? {},
1490
- ))
1491
- if (p.required && p.type.startsWith('SearchSource') && !(k in props))
1492
- props[k] = SAMPLE_SOURCE;
1493
- return {
1494
- ...v,
1495
- props,
1496
- ...(v.children === undefined
1497
- ? {}
1498
- : {children: withSources(project, v.children)}),
1499
- };
1500
- }
1501
- return v;
1502
- }
1503
-
1504
- /** Controlled parts a sample gives a value: they call onChange on a click. */
1505
- const CONTROLLED = new Set([
1506
- 'TabList',
1507
- 'SegmentedControl',
1508
- 'RadioList',
1509
- 'Switch',
1510
- 'CheckboxInput',
1511
- 'Selector',
1512
- 'TextInput',
1513
- 'TextArea',
1514
- 'NumberInput',
1515
- ]);
1516
-
1517
- /**
1518
- * A copy of an element tree in which every controlled part with a value and
1519
- * no onChange gets one that does nothing, so a click on it never throws. A
1520
- * callback the part's doc requires (a toast's onDismiss) that the sample
1521
- * leaves out gets one that does nothing too, so the part never calls a
1522
- * missing function (a toast's timer).
1523
- * @param {unknown} v
1524
- * @param {import('./_project.mjs').ThemeProject} [project]
1525
- * @returns {unknown}
1526
- */
1527
- export function withHandlers(v, project) {
1528
- if (Array.isArray(v)) return v.map(x => withHandlers(x, project));
1529
- if (isElement(v)) {
1530
- const props = Object.fromEntries(
1531
- Object.entries(v.props ?? {}).map(([k, x]) => [
1532
- k,
1533
- withHandlers(x, project),
1534
- ]),
1535
- );
1536
- if (CONTROLLED.has(v.__element) && 'value' in props && !props.onChange)
1537
- props.onChange = {__code: '() => {}'};
1538
- // Written without an arrow, so this no-op adds no `>` inside a tag.
1539
- const docProps = project?.components[v.__element]?.props ?? {};
1540
- for (const [name, doc] of Object.entries(docProps))
1541
- if (/^on[A-Z]/.test(name) && doc?.required && !(name in props))
1542
- props[name] = {__code: 'function () {}'};
1543
- return {
1544
- ...v,
1545
- props,
1546
- ...(v.children === undefined
1547
- ? {}
1548
- : {children: withHandlers(v.children, project)}),
1549
- };
1550
- }
1551
- return v;
1552
- }
1553
-
1554
- /**
1555
- * Whether an element tree uses the page's sample search source.
1556
- * @param {unknown} v
1557
- * @returns {boolean}
1558
- */
1559
- const usesSource = v =>
1560
- isCode(v)
1561
- ? v.__code === SAMPLE_SOURCE.__code
1562
- : Boolean(v && typeof v === 'object') &&
1563
- Object.values(/** @type {object} */ (v)).some(usesSource);
1564
-
1565
- /** The heading of each group on the components page. */
1566
- const GROUP_TITLES = wordTable(
1567
- /** @type {Record<string, string>} */ ({
1568
- data: 'data display',
1569
- overlays: 'overlays (shown open)',
1570
- }),
1571
- );
1572
-
1573
- /**
1574
- * A cell with the component's name. A cell whose parts show nothing on
1575
- * their own (no size and no text) says so, so no cell is blank.
1576
- */
1577
- const CELL = [
1578
- 'function Cell({name, children}: {name: string, children: React.ReactNode}) {',
1579
- ' const ref = React.useRef<HTMLDivElement>(null);',
1580
- ' const [empty, setEmpty] = React.useState(false);',
1581
- ' React.useEffect(() => {',
1582
- " const row = ref.current?.querySelector('.tp-row');",
1583
- ' if (!row) return;',
1584
- " const shown = Array.from(row.querySelectorAll('.tp-item > :not(.tp-label)')).some(el => {",
1585
- ' const box = el.getBoundingClientRect();',
1586
- " return (box.width > 0 && box.height > 0 && (box.width > 2 || box.height > 2)) || (el.textContent ?? '').trim() !== '';",
1587
- ' });',
1588
- ' setEmpty(!shown);',
1589
- ' }, []);',
1590
- ' return (',
1591
- ' <div ref={ref} className="tp-cell">',
1592
- ' <div className="tp-name">{name}</div>',
1593
- ' {children}',
1594
- ' {empty ? <div className="tp-note">{name} shows nothing on its own here: it needs content or a trigger</div> : null}',
1595
- ' </div>',
1596
- ' );',
1597
- '}',
1598
- ];
1599
-
1600
- /**
1601
- * The command that changes a component most, from what its main part reads:
1602
- * its background, else its border, else its text color, else its corners;
1603
- * `how <part>` when it reads none of them.
1604
- * @param {import('./_project.mjs').ThemeProject} project
1605
- * @param {import('./_compiler.mjs').Compiler} C
1606
- * @param {string} name
1607
- * @param {string | null} theme
1608
- * @returns {string | null}
1609
- */
1610
- function changeLine(project, C, name, theme) {
1611
- const keys = project.targets
1612
- .filter(t => t.component === name)
1613
- .map(t => t.key);
1614
- const kebabName = name.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
1615
- const part = keys.includes(kebabName) ? kebabName : keys[0];
1616
- if (!part) return null;
1617
- const t = theme ?? '<theme>';
1618
- for (const [aspect, value] of /** @type {const} */ ([
1619
- ['background', '"<color>"'],
1620
- ['border', '"1px solid <color>"'],
1621
- ['text', '"<color>"'],
1622
- ]))
1623
- if (C.partReads(part, aspect).length) {
1624
- // A part whose paint is a line inside it (a divider) takes the token
1625
- // its line reads: a fill on its own element would be under the line.
1626
- const lineToken =
1627
- aspect === 'background' &&
1628
- (C.MAP[part]?.line ?? []).includes('background-color')
1629
- ? Object.keys(C.MAP[part]?.own?.['background-color']?.tokens ?? {})[0]
1630
- : null;
1631
- if (lineToken) return `${P} set ${t} ${lineToken} ${value} --on ${part}`;
1632
- // A part whose color comes from its color prop takes the text token.
1633
- return aspect === 'text' && COLOR_PROP_PARTS.includes(part)
1634
- ? `${P} set ${t} --color-text-primary ${value}`
1635
- : `${P} set ${t} ${DIRECT[aspect]} ${value} --on ${part}`;
1636
- }
1637
- if (C.showsCorners(part)) return `${P} set ${t} corners round --on ${part}`;
1638
- return `${P} how ${part}`;
1639
- }
1640
-
1641
- /** Layers that stay closed until a person opens them, and a frame with no content: on the page they show nothing. */
1642
- const PAGE_SKIP = new Set([
1643
- 'AspectRatio',
1644
- 'BottomSheet',
1645
- 'BottomSheetSwitcher',
1646
- 'Drawer',
1647
- 'Lightbox',
1648
- ]);
1649
-
1650
- /**
1651
- * The source of the preview's components page: every component grouped,
1652
- * each variant side by side, overlays open. Template pages are pages of
1653
- * their own (`preview add --template`), so they are not on it.
1654
- * Under each cell, one line: the command that changes the component most,
1655
- * from what its part reads (`how <part>`).
1656
- * @param {import('./_project.mjs').ThemeProject} project
1657
- * @param {{theme?: string | null, C?: import('./_compiler.mjs').Compiler}} [options]
1658
- * @returns {{source: string, components: number}}
1659
- */
1660
- export function componentsPageSource(project, options = {}) {
1661
- // A name that Core's docs lack resolves by walking Core's source tree. One
1662
- // listing cache reads each folder once for the page, not once per name.
1663
- return withListingCache(() => componentsPage(project, options));
1664
- }
1665
-
1666
- /**
1667
- * {@link componentsPageSource}'s work, inside its listing cache.
1668
- * @param {import('./_project.mjs').ThemeProject} project
1669
- * @param {{theme?: string | null, C?: import('./_compiler.mjs').Compiler}} options
1670
- * @returns {{source: string, components: number}}
1671
- */
1672
- function componentsPage(project, {theme = null, C}) {
1673
- const items = showcaseItems(project, undefined)
1674
- .items.filter(
1675
- it =>
1676
- it.group !== 'pages' &&
1677
- // The sheet's own deeper overlays and drawn states: the app's page
1678
- // opens and hovers its parts live.
1679
- !it.states &&
1680
- Boolean(project.components[it.name]) &&
1681
- !PAGE_SKIP.has(it.name) &&
1682
- !project.components[it.name]?.overlay,
1683
- )
1684
- .map(it => ({
1685
- ...it,
1686
- tree: withHandlers(
1687
- withSources(project, withCoreNames(project, it.tree)),
1688
- project,
1689
- ),
1690
- }))
1691
- .filter(it => it.tree !== undefined);
1692
- /** @type {Map<string, Map<string, import('./_catalog.mjs').CatalogItem[]>>} */
1693
- const groups = new Map();
1694
- for (const it of items) {
1695
- const g = groups.get(it.group ?? '') ?? new Map();
1696
- const list = /** @type {import('./_catalog.mjs').CatalogItem[]} */ (
1697
- g.get(it.name) ?? []
1698
- );
1699
- if (!list.some(x => x.label === it.label)) list.push(it);
1700
- g.set(it.name, list);
1701
- groups.set(it.group ?? '', g);
1702
- }
1703
- const sections = [...groups]
1704
- .map(([g, comps]) => {
1705
- const cells = [...comps]
1706
- .map(([name, list]) => {
1707
- const body = list
1708
- .map(
1709
- it =>
1710
- ` <div className="${project.components[name]?.category === 'Layout' ? 'tp-item tp-fill' : 'tp-item'}">${it.label ? `\n <div className="tp-label">${it.label}</div>` : ''}\n <Safe name=${JSON.stringify(name)}>\n ${jsx(/** @type {any} */ (it.tree), 7)}\n </Safe>\n </div>`,
1711
- )
1712
- .join('\n');
1713
- const line = C ? changeLine(project, C, name, theme) : null;
1714
- return ` <Cell name=${JSON.stringify(name)}>\n <div className="tp-row">\n${body}\n </div>${line ? `\n <code className="tp-cmd">{${JSON.stringify(line)}}</code>` : ''}\n </Cell>`;
1715
- })
1716
- .join('\n');
1717
- return ` <section>\n <h2 className="tp-group">${GROUP_TITLES[g] ?? g}</h2>\n <div className="tp-grid">\n${cells}\n </div>\n </section>`;
1718
- })
1719
- .join('\n');
1720
- const css = `.tp-group{font:600 14px ui-monospace,monospace;margin:16px 14px 0;opacity:.75}.tp-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px;padding:14px;align-items:start}.tp-cell{border:1px dashed #8885;padding:10px;overflow:hidden}.tp-name{font:600 12px ui-monospace,monospace;opacity:.6;margin-bottom:8px}.tp-row{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-start}.tp-fill{flex:1 1 100%;max-height:300px;overflow:auto}.tp-label{font:10px ui-monospace,monospace;opacity:.5}.tp-cmd{display:block;margin-top:10px;font:10px ui-monospace,monospace;opacity:.75;overflow-wrap:break-word}.tp-note{font:11px ui-monospace,monospace;opacity:.6;padding:6px 8px;border:1px dashed #8886}`;
1721
- const source = [
1722
- '// Written by `astryx experimental theme preview add`: every component grouped, each variant side by side, overlays open.',
1723
- "'use client';",
1724
- '',
1725
- "import * as React from 'react';",
1726
- ...componentTable(
1727
- project,
1728
- items.map(it => it.tree),
1729
- ),
1730
- '',
1731
- ...SAFE,
1732
- '',
1733
- ...CELL,
1734
- '',
1735
- ...(usesSource(items) ? [...SAMPLE_SOURCE_LINES, ''] : []),
1736
- 'export default function ComponentsPage() {',
1737
- ' return (',
1738
- ' <div>',
1739
- ` <style>{${JSON.stringify(css)}}</style>`,
1740
- sections,
1741
- ' </div>',
1742
- ' );',
1743
- '}',
1744
- '',
1745
- ].join('\n');
1746
- return {source, components: new Set(items.map(i => i.name)).size};
1747
- }
1748
-
1749
- /**
1750
- * The source of the preview's Overview page: the theme at a glance, built
1751
- * to show what themes most often break (see _overview.mjs). A header names
1752
- * the theme, its fonts and its main colors; each section renders inside a
1753
- * boundary, so one part that throws never blanks the page. The preview
1754
- * route is the app shell, so the page has no shell of its own.
1755
- * @param {import('./_project.mjs').ThemeProject} project
1756
- * @param {{theme?: string | null, colors?: boolean}} [options] `colors`:
1757
- * the preview has a Colors page, so the header points to it
1758
- * @returns {string}
1759
- */
1760
- export function overviewPageSource(project, options = {}) {
1761
- // One listing cache for the page's names, as componentsPageSource holds.
1762
- return withListingCache(() => overviewPage(project, options));
1763
- }
1764
-
1765
- /**
1766
- * {@link overviewPageSource}'s work, inside its listing cache.
1767
- * @param {import('./_project.mjs').ThemeProject} project
1768
- * @param {{theme?: string | null, colors?: boolean}} options
1769
- * @returns {string}
1770
- */
1771
- function overviewPage(project, {theme = null, colors = false}) {
1772
- const sections = OVERVIEW_SECTIONS.map(x => ({
1773
- title: x.title,
1774
- tree: /** @type {import('./_catalog.mjs').Tree | undefined} */ (
1775
- withHandlers(withCoreNames(project, x.tree), project)
1776
- ),
1777
- })).filter(x => x.tree !== undefined);
1778
- const body = sections
1779
- .map(
1780
- x =>
1781
- ` <section className="tp-section">\n <h2 className="tp-group">${x.title}</h2>\n <Safe name=${JSON.stringify(x.title)}>\n ${jsx(/** @type {any} */ (x.tree), 5)}\n </Safe>\n </section>`,
1782
- )
1783
- .join('\n');
1784
- const css =
1785
- '.tp-page{display:grid;gap:20px;padding:24px 24px 160px;color:var(--color-text-primary)}' +
1786
- '.tp-group{font:600 13px ui-monospace,monospace;margin:0 0 10px;opacity:.7;text-transform:uppercase;letter-spacing:.04em}' +
1787
- '.tp-head{display:flex;flex-wrap:wrap;gap:16px;align-items:end;justify-content:space-between}' +
1788
- '.tp-swatches{display:flex;flex-wrap:wrap;gap:8px}' +
1789
- '.tp-swatch{display:grid;gap:4px;font:11px ui-monospace,monospace;color:var(--color-text-secondary)}' +
1790
- '.tp-chip{width:56px;height:36px;border-radius:var(--radius-element);border:1px solid var(--color-border)}' +
1791
- '.tp-note{font:11px ui-monospace,monospace;opacity:.6;padding:6px 8px;border:1px dashed #8886}';
1792
- return [
1793
- '// Written by `astryx experimental theme preview add`: the theme at a glance, built to show what themes most often break.',
1794
- "'use client';",
1795
- '',
1796
- "import * as React from 'react';",
1797
- ...componentTable(
1798
- project,
1799
- sections.map(x => x.tree),
1800
- ),
1801
- '',
1802
- ...SAFE,
1803
- '',
1804
- '/** The main colors, as the theme resolves them. */',
1805
- 'const SWATCHES = [',
1806
- ...[
1807
- ['accent', '--color-accent'],
1808
- ['neutral', '--color-background-surface'],
1809
- ['text', '--color-text-primary'],
1810
- ['info', '--color-info'],
1811
- ['success', '--color-success'],
1812
- ['warning', '--color-warning'],
1813
- ['danger', '--color-error'],
1814
- ].map(
1815
- ([n, t]) =>
1816
- ` {name: ${JSON.stringify(n)}, token: ${JSON.stringify(t)}},`,
1817
- ),
1818
- '];',
1819
- '',
1820
- '/** The first family of the body and heading fonts, read from the theme. */',
1821
- 'function FontNames() {',
1822
- ' const ref = React.useRef<HTMLDivElement>(null);',
1823
- " const [fonts, setFonts] = React.useState('');",
1824
- ' React.useEffect(() => {',
1825
- ' if (!ref.current) return;',
1826
- ' const style = getComputedStyle(ref.current);',
1827
- " const first = (token: string) => (style.getPropertyValue(token).split(',')[0] ?? '').replace(/[\"']/g, '').trim() || 'default';",
1828
- ' // A family the browser does not have measures as its fallback does.',
1829
- ' const GENERIC = /^(default|serif|sans-serif|monospace|cursive|fantasy|system-ui|ui-[a-z-]+|math|emoji|fangsong)$/i;',
1830
- ' const missing = (family: string) => {',
1831
- ' if (GENERIC.test(family)) return false;',
1832
- " const ctx = document.createElement('canvas').getContext('2d');",
1833
- ' if (!ctx) return false;',
1834
- " const sample = 'mmmmmmmmmwwwwwww1234567890';",
1835
- " return ['monospace', 'serif'].every(fallback => {",
1836
- ' ctx.font = `48px ${fallback}`;',
1837
- ' const plain = ctx.measureText(sample).width;',
1838
- ' ctx.font = `48px "${family}", ${fallback}`;',
1839
- ' return ctx.measureText(sample).width === plain;',
1840
- ' });',
1841
- ' };',
1842
- ' const shown = (token: string) => { const f = first(token); return missing(f) ? `${f} (not installed here)` : f; };',
1843
- " const write = () => setFonts(`Body: ${shown('--font-family-body')}. Headings: ${shown('--font-family-heading')}.`);",
1844
- ' write();',
1845
- ' // Read again when the theme changes live (a stylesheet or theme',
1846
- ' // update while the page is open) and when a font finishes loading.',
1847
- ' document.fonts?.ready.then(write);',
1848
- " document.fonts?.addEventListener?.('loadingdone', write);",
1849
- ' let queued = 0;',
1850
- ' const soon = () => { if (!queued) queued = requestAnimationFrame(() => { queued = 0; write(); }); };',
1851
- ' const watch = new MutationObserver(soon);',
1852
- ' watch.observe(document.head, {childList: true, subtree: true, characterData: true});',
1853
- " watch.observe(document.documentElement, {attributes: true, subtree: true, attributeFilter: ['style', 'class', 'data-theme']});",
1854
- ' return () => {',
1855
- ' watch.disconnect();',
1856
- ' cancelAnimationFrame(queued);',
1857
- " document.fonts?.removeEventListener?.('loadingdone', write);",
1858
- ' };',
1859
- ' }, []);',
1860
- ' return (',
1861
- " <div ref={ref} style={{color: 'var(--color-text-secondary)', fontSize: 13}}>",
1862
- ' {fonts}',
1863
- ' </div>',
1864
- ' );',
1865
- '}',
1866
- '',
1867
- 'export default function OverviewPage() {',
1868
- ' return (',
1869
- ' <div className="tp-page">',
1870
- ` <style>{${JSON.stringify(css)}}</style>`,
1871
- ' <header className="tp-head">',
1872
- ' <div>',
1873
- ` <h1 style={{margin: 0, fontSize: 28}}>{${JSON.stringify(theme ? `${theme} at a glance` : 'The theme at a glance')}}</h1>`,
1874
- ' <FontNames />',
1875
- ' </div>',
1876
- ' <div className="tp-swatches">',
1877
- ' {SWATCHES.map(s => (',
1878
- ' <div key={s.name} className="tp-swatch" title={s.token}>',
1879
- ' <div className="tp-chip" style={{background: `var(${s.token})`}} />',
1880
- ' {s.name}',
1881
- ' </div>',
1882
- ' ))}',
1883
- // The Colors page is there only for a theme with generated colors.
1884
- ...(colors
1885
- ? [
1886
- ' <div className="tp-swatch" style={{alignSelf: \'center\'}}>Every shade: the Colors page</div>',
1887
- ]
1888
- : []),
1889
- ' </div>',
1890
- ' </header>',
1891
- body,
1892
- ' </div>',
1893
- ' );',
1894
- '}',
1895
- '',
1896
- ].join('\n');
1897
- }
1898
-
1899
- /**
1900
- * The source of the preview's Colors page: each generated color's shades in
1901
- * light and dark, with the shade number, the hex, and the tokens that use
1902
- * it. The shades come from the theme's generated color module, so the page
1903
- * follows every change; `uses` and `seeds` are written in by the editor.
1904
- * With no generated colors, the page says how to set one.
1905
- * @param {{slug: string, module: string | null, seeds: Record<string, string>, uses: Record<string, Record<'light' | 'dark', Record<string, string[]>>>}} colors
1906
- * `module`: the import of the generated colors from the page, or null.
1907
- * @returns {string}
1908
- */
1909
- export function colorsPageSource({slug, module, seeds, uses}) {
1910
- const head = [
1911
- "// Written by `astryx experimental theme preview add`: the theme's generated colors.",
1912
- '// `astryx experimental theme editor set` rewrites it with every change.',
1913
- "'use client';",
1914
- '',
1915
- ];
1916
- const text = {color: 'var(--color-text-primary)'};
1917
- const page = {
1918
- padding: 32,
1919
- display: 'grid',
1920
- gap: 32,
1921
- fontFamily: 'var(--font-family-body)',
1922
- ...text,
1923
- };
1924
- if (!module)
1925
- return [
1926
- ...head,
1927
- '',
1928
- 'export default function ColorsPage() {',
1929
- ' return (',
1930
- ` <div style={${JSON.stringify(page)}}>`,
1931
- ' <p style={{margin: 0}}>',
1932
- ` {${JSON.stringify(`This theme sets no color yet. Set one, and its shades show here: astryx experimental theme editor set ${slug} accent "#7c3aed"`)}}`,
1933
- ' </p>',
1934
- ' </div>',
1935
- ' );',
1936
- '}',
1937
- '',
1938
- ].join('\n');
1939
- return [
1940
- ...head,
1941
- `import {palette} from ${JSON.stringify(module)};`,
1942
- '',
1943
- "type Mode = 'light' | 'dark';",
1944
- 'type Ramp = Readonly<Record<string, string>>;',
1945
- '',
1946
- `const SEEDS: Record<string, string> = ${JSON.stringify(seeds)};`,
1947
- '// The tokens that use each shade, by color, mode and shade.',
1948
- `const USES: Record<string, Partial<Record<Mode, Record<string, string[]>>>> = ${JSON.stringify(uses)};`,
1949
- 'const COLORS = Object.entries(palette) as Array<[string, Readonly<Partial<Record<Mode, Ramp>>>]>;',
1950
- "const MODES: Mode[] = ['light', 'dark'];",
1951
- '',
1952
- 'export default function ColorsPage() {',
1953
- ' return (',
1954
- ` <div style={${JSON.stringify(page)}}>`,
1955
- ' <div>',
1956
- ' <h1 style={{margin: 0, fontSize: 28}}>Colors</h1>',
1957
- " <p style={{margin: '8px 0 0', color: 'var(--color-text-secondary)'}}>",
1958
- ` {${JSON.stringify(`Each color is generated from one seed, light and dark. An outlined shade is one a token uses. Change one with: astryx experimental theme editor set ${slug} accent <color>`)}}`,
1959
- ' </p>',
1960
- ' </div>',
1961
- ' {COLORS.map(([name, ramps]) => (',
1962
- " <section key={name} style={{display: 'grid', gap: 12}}>",
1963
- " <h2 style={{margin: 0, fontSize: 20, textTransform: 'capitalize'}}>",
1964
- ' {name}',
1965
- ' {SEEDS[name] ? (',
1966
- " <span style={{marginLeft: 8, fontSize: 14, fontWeight: 400, textTransform: 'none', color: 'var(--color-text-secondary)'}}>",
1967
- ' from {SEEDS[name]}',
1968
- ' </span>',
1969
- ' ) : null}',
1970
- ' </h2>',
1971
- ' {MODES.filter(mode => ramps[mode]).map(mode => (',
1972
- " <div key={mode} style={{display: 'grid', gap: 6}}>",
1973
- " <div style={{fontSize: 13, fontWeight: 600, textTransform: 'capitalize'}}>{mode}</div>",
1974
- " <div style={{display: 'grid', gridTemplateColumns: 'repeat(7, minmax(0, 1fr))', gap: 8}}>",
1975
- ' {Object.entries(ramps[mode] ?? {}).map(([shade, hex]) => {',
1976
- ' const tokens = USES[name]?.[mode]?.[shade] ?? [];',
1977
- ' return (',
1978
- ' <div',
1979
- ' key={shade}',
1980
- " title={tokens.join(', ')}",
1981
- ' style={{',
1982
- " border: tokens.length ? '2px solid var(--color-text-primary)' : '1px solid var(--color-border)',",
1983
- ' borderRadius: 8,',
1984
- " overflow: 'hidden',",
1985
- " background: 'var(--color-background-card)',",
1986
- ' }}>',
1987
- ' <div style={{background: hex, height: 48}} />',
1988
- " <div style={{padding: 6, fontSize: 11, lineHeight: 1.4, fontFamily: 'ui-monospace, monospace'}}>",
1989
- ' <div>',
1990
- ' <strong>{shade}</strong> {hex}',
1991
- ' </div>',
1992
- ' {tokens.map(t => (',
1993
- " <div key={t} style={{color: 'var(--color-text-secondary)', overflowWrap: 'anywhere'}}>",
1994
- ' {t}',
1995
- ' </div>',
1996
- ' ))}',
1997
- ' </div>',
1998
- ' </div>',
1999
- ' );',
2000
- ' })}',
2001
- ' </div>',
2002
- ' </div>',
2003
- ' ))}',
2004
- ' </section>',
2005
- ' ))}',
2006
- ' </div>',
2007
- ' );',
2008
- '}',
2009
- '',
2010
- ].join('\n');
2011
- }
2012
-
2013
- /**
2014
- * The source of the preview route: an app shell with a side nav item per
2015
- * preview page, a top bar with the theme name and, with a theme, a
2016
- * light/dark/system switch, and the selected page in the content area. It is a normal page of
2017
- * the app, so it keeps the app's layout, global CSS and providers.
2018
- * @param {{pages: Array<{id: string, label: string, file: string}>, theme: {name: string, module: string, css: string[], mode?: 'system' | 'light' | 'dark'} | null, by?: string}} spec
2019
- * `file` relative to the route folder, without extension; no theme: the
2020
- * app's own theme. A theme with one mode starts in it, with no switch.
2021
- * `by`: the command that wrote the route, for its header.
2022
- * @returns {string}
2023
- */
2024
- export function previewRouteSource({
2025
- pages,
2026
- theme,
2027
- by = 'astryx experimental theme preview add',
2028
- }) {
2029
- const name = theme?.name ?? 'app theme';
2030
- const oneMode = theme?.mode && theme.mode !== 'system' ? theme.mode : null;
2031
- const mode =
2032
- theme && !oneMode
2033
- ? [
2034
- ' <SegmentedControl label="Color mode" size="sm" value={mode} onChange={v => setMode(v as Mode)}>',
2035
- ' <SegmentedControlItem value="light" label="Light" />',
2036
- ' <SegmentedControlItem value="dark" label="Dark" />',
2037
- ' <SegmentedControlItem value="system" label="System" />',
2038
- ' </SegmentedControl>',
2039
- ]
2040
- : [];
2041
- // The frame fills the viewport with the theme's own page background, so
2042
- // no root-layout background shows at the edges or on overscroll.
2043
- const shell = [
2044
- ' <div style={FRAME}>',
2045
- ' <AppShell',
2046
- ' height="fill"',
2047
- ' topNav={',
2048
- // Core's own heading, as an app's top bar draws it, so a setting on the
2049
- // header (its text color) shows here as it does in the app.
2050
- ` <TopNav label="Theme preview" heading={<TopNavHeading heading={${JSON.stringify(name)}} />} endContent={`,
2051
- ...(mode.length ? mode : [' null']),
2052
- ' } />',
2053
- ' }',
2054
- ' sideNav={',
2055
- ' <SideNav>',
2056
- ' {PAGES.map(p => (',
2057
- // Only a plain left click switches the page in place; a modified or
2058
- // middle click opens the page's URL as a link does (a new tab).
2059
- ' <SideNavItem key={p.id} label={p.label} isSelected={p.id === current.id} href={`?page=${p.id}`} onClick={e => { if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; e.preventDefault(); go(p.id); }} />',
2060
- ' ))}',
2061
- ' </SideNav>',
2062
- ' }>',
2063
- ' {ready ? <current.Page /> : null}',
2064
- ' </AppShell>',
2065
- ' </div>',
2066
- ];
2067
- return [
2068
- `// Written by \`${by}\`. \`preview add\`, \`preview remove\` and`,
2069
- '// theme-preview.json keep it: edit the list with those commands, not by hand.',
2070
- "'use client';",
2071
- '',
2072
- "import * as React from 'react';",
2073
- "import {AppShell} from '@astryxdesign/core/AppShell';",
2074
- "import {SideNav, SideNavItem} from '@astryxdesign/core/SideNav';",
2075
- "import {TopNav, TopNavHeading} from '@astryxdesign/core/TopNav';",
2076
- ...(theme
2077
- ? [
2078
- // The mode switch only for a theme with both modes: an import the
2079
- // route does not draw fails an app with noUnusedLocals.
2080
- ...(mode.length
2081
- ? [
2082
- "import {SegmentedControl, SegmentedControlItem} from '@astryxdesign/core/SegmentedControl';",
2083
- ]
2084
- : []),
2085
- "import {Theme} from '@astryxdesign/core/theme';",
2086
- `import {${camelName(theme.name)}Theme as theme} from ${JSON.stringify(theme.module.replace(/\.js$/, ''))};`,
2087
- ...theme.css.map(c => `import ${JSON.stringify(c)};`),
2088
- ]
2089
- : []),
2090
- ...pages.map(
2091
- (p, i) => `import Page${i} from ${JSON.stringify(`./${p.file}`)};`,
2092
- ),
2093
- '',
2094
- ...(theme ? ["type Mode = 'light' | 'dark' | 'system';", ''] : []),
2095
- 'const FRAME: React.CSSProperties = {',
2096
- " position: 'fixed',",
2097
- ' inset: 0,',
2098
- " overflow: 'auto',",
2099
- " overscrollBehavior: 'none',",
2100
- " background: 'var(--color-background-body)',",
2101
- " color: 'var(--color-text-primary)',",
2102
- '};',
2103
- '',
2104
- 'const PAGES = [',
2105
- ...pages.map(
2106
- (p, i) =>
2107
- ` {id: ${JSON.stringify(p.id)}, label: ${JSON.stringify(p.label)}, Page: Page${i}},`,
2108
- ),
2109
- '];',
2110
- '',
2111
- 'export default function ThemePreviewPage() {',
2112
- ' const [page, setPage] = React.useState(PAGES[0]?.id);',
2113
- // Each page has its own URL (?page=<id>), so a link, a reload, the back
2114
- // button or a screenshot reaches any page; the page renders after mount.
2115
- " const fromUrl = () => new URLSearchParams(window.location.search).get('page');",
2116
- ' React.useEffect(() => {',
2117
- // A URL with no (or an unknown) ?page shows the first page, as a reload does.
2118
- ' const sync = () => { const id = fromUrl(); setPage(id && PAGES.some(p => p.id === id) ? id : PAGES[0]?.id); };',
2119
- ' sync();',
2120
- " window.addEventListener('popstate', sync);",
2121
- " return () => window.removeEventListener('popstate', sync);",
2122
- ' }, []);',
2123
- ' const go = (id: string) => {',
2124
- ' setPage(id);',
2125
- ' const url = new URL(window.location.href);',
2126
- " url.searchParams.set('page', id);",
2127
- " window.history.pushState(null, '', url);",
2128
- ' };',
2129
- // Pages render only in the browser: some components crash a server
2130
- // render, and Next prerenders a client page's first state.
2131
- ' const [ready, setReady] = React.useState(false);',
2132
- ' React.useEffect(() => setReady(true), []);',
2133
- ...(theme
2134
- ? [
2135
- oneMode
2136
- ? ` const mode: Mode = ${JSON.stringify(oneMode)};`
2137
- : " const [mode, setMode] = React.useState<Mode>('system');",
2138
- ]
2139
- : []),
2140
- // The route always has a page; the cast keeps noUncheckedIndexedAccess apps building.
2141
- ' const current = (PAGES.find(p => p.id === page) ?? PAGES[0]) as (typeof PAGES)[number];',
2142
- ' return (',
2143
- ...(theme
2144
- ? [' <Theme theme={theme} mode={mode}>', ...shell, ' </Theme>']
2145
- : [' <>', ...shell, ' </>']),
2146
- ' );',
2147
- '}',
2148
- '',
2149
- ].join('\n');
2150
- }
2151
-
2152
- /** @param {string} slug */
2153
- const camelName = camel;
2154
-
2155
- /** The script that takes one picture through the project's Playwright. */
2156
- const PLAYWRIGHT_PICTURE = fileURLToPath(
2157
- new URL('../../foundation/render/picture-playwright.mjs', import.meta.url),
2158
- );
2159
-
2160
- /** The script that takes one picture through a Chrome or Chromium. */
2161
- const CHROME_PICTURE = fileURLToPath(
2162
- new URL('../../foundation/render/picture-chrome.mjs', import.meta.url),
2163
- );
2164
-
2165
- /** How long a stopped browser may take to close before it is killed. */
2166
- const STOP_GRACE_MS = 5_000;
2167
-
2168
- /** The signals that stop a picture run, the terminal closing among them. */
2169
- const STOP_SIGNALS = /** @type {const} */ (['SIGINT', 'SIGTERM', 'SIGHUP']);
2170
-
2171
- /** How long a browser may take for one picture before it is stopped. */
2172
- const BROWSER_BOUND_MS = 60_000;
2173
-
2174
- /**
2175
- * What the pictures of one run share: the browsers that failed or hung,
2176
- * each with its reason, so a later picture does not wait on them again.
2177
- * @typedef {{failed: Map<string, string>}} PictureRun
2178
- */
2179
-
2180
- /** A new picture run. @returns {PictureRun} */
2181
- export function newPictureRun() {
2182
- return {failed: new Map()};
2183
- }
2184
-
2185
- /**
2186
- * A whole-page PNG of an HTML file: {@link screenshots} with one picture.
2187
- * @param {import('./_project.mjs').ThemeProject} project
2188
- * @param {string} html absolute
2189
- * @param {string} png absolute
2190
- * @param {'light' | 'dark'} mode
2191
- * @param {PictureRun} [run]
2192
- * @returns {Promise<PictureResult>}
2193
- */
2194
- export async function screenshot(
2195
- project,
2196
- html,
2197
- png,
2198
- mode,
2199
- run = newPictureRun(),
2200
- ) {
2201
- const [r] = await screenshots(project, [{html, png, mode}], run);
2202
- return /** @type {PictureResult} */ (r);
2203
- }
2204
-
2205
- /**
2206
- * @typedef {{ok: true, file: string, notes?: string[], boxes?: Record<string, Array<[number, number]>>, cutShort?: Array<{part: string | null, text: string, whole: boolean, broken?: boolean, overlaps?: boolean}>, lowContrast?: Array<{part: string, text: string, ratio: number, fg: string, bg: string}>} | {ok: false, reason: string, stopped?: string}} PictureResult
2207
- */
2208
-
2209
- /** The time a batch adds to its browser's bound for each page after the first. */
2210
- const PAGE_BOUND_MS = 20_000;
2211
-
2212
- /**
2213
- * Whole-page PNGs of HTML files, all with one browser: a Playwright the
2214
- * project has installed, else a Chrome or Chromium found on the machine.
2215
- * One browser start for the whole batch, a few pages drawn at once, so a
2216
- * run of many pictures costs about one start. Each browser gets its own
2217
- * time bound, and the next one the pictures still to take when one fails
2218
- * or hangs. A result for each picture, in order, up to the first that was
2219
- * not taken: that one not ok with a reason (naming each browser's real
2220
- * error, or that none is there), and none after it. When a later browser
2221
- * took a picture, its `notes` say why an earlier one did not. `cutShort` is
2222
- * the text the page draws cut short, measured in it by the browser that
2223
- * took the picture, each with whether its part keeping its width draws it
2224
- * whole; absent when that browser's script measured nothing.
2225
- * @param {import('./_project.mjs').ThemeProject} project
2226
- * @param {Array<{html: string, png: string, mode: 'light' | 'dark', boxes?: string[]}>} jobs
2227
- * absolute paths; `boxes`: parts whose drawn sizes the picture measures
2228
- * (its result's `boxes`)
2229
- * @param {PictureRun} [run] what earlier pictures of the same run learned:
2230
- * a browser that failed or hung there is not tried again
2231
- * @returns {Promise<PictureResult[]>}
2232
- */
2233
- export async function screenshots(project, jobs, run = newPictureRun()) {
2234
- /** @type {PictureResult[]} */
2235
- const results = [];
2236
- if (!jobs.length) return results;
2237
- /** What was tried and why it could not take the picture. @type {string[]} */
2238
- const failed = [...run.failed.values()];
2239
- /** Whether a Playwright was found without its own browser installed. */
2240
- let pwMissing = false;
2241
- /** Whether a Playwright was found at all. */
2242
- let pwFound = false;
2243
- /** A line with no path of this machine. @param {string} line */
2244
- const local = line => line.split(project.cwd).join('.');
2245
- /**
2246
- * Why a browser did not take the picture: Playwright's first line names
2247
- * only the call ("browserType.launch: Target … closed"); the cause, such
2248
- * as a missing library, is in a later line, so that line comes too.
2249
- * Chrome's startup warnings (dbus, GPU) are not a cause.
2250
- * @param {string} text
2251
- */
2252
- const causeOf = text => {
2253
- const lines = String(text ?? '')
2254
- .split('\n')
2255
- .map(l => l.replace(/^[\s=<>-]+/, '').trim())
2256
- .filter(Boolean);
2257
- const head =
2258
- meaningfulLine(lines.join('\n')) || 'it stopped with no message';
2259
- const rest = lines
2260
- .slice(lines.indexOf(head) + 1)
2261
- .find(l =>
2262
- /error|cannot|can't|missing|not found|while loading|no such|failed|denied/i.test(
2263
- l,
2264
- ),
2265
- );
2266
- return local(rest ? `${head} (${rest})` : head);
2267
- };
2268
- /** The browsers to try, in order: each a picture script and its first argument. */
2269
- /** @type {Array<{who: string, script: string, first: string}>} */
2270
- const tries = [];
2271
- for (const pkg of ['playwright', 'playwright-core']) {
2272
- try {
2273
- const entry = project.req.resolve(pkg);
2274
- pwFound = true;
2275
- tries.push({
2276
- who: `${pkg}'s own browser`,
2277
- script: PLAYWRIGHT_PICTURE,
2278
- first: entry,
2279
- });
2280
- break;
2281
- } catch {
2282
- // Not installed here.
2283
- }
2284
- }
2285
- const chrome = chromeBinary();
2286
- if (chrome) tries.push({who: chrome, script: CHROME_PICTURE, first: chrome});
2287
- for (const t of tries) {
2288
- if (run.failed.has(t.who)) continue;
2289
- const rest = jobs.slice(results.length);
2290
- const r = await runBrowser(
2291
- t.script,
2292
- [t.first, JSON.stringify(rest)],
2293
- BROWSER_BOUND_MS + (rest.length - 1) * PAGE_BOUND_MS,
2294
- {drop: rest.map(j => j.png)},
2295
- );
2296
- if (r.stoppedBy) {
2297
- results.push({
2298
- ok: false,
2299
- stopped: r.stoppedBy,
2300
- reason: `the pictures were stopped (${r.stoppedBy}) before the browser finished`,
2301
- });
2302
- return results;
2303
- }
2304
- if (r.noTemp) {
2305
- results.push({
2306
- ok: false,
2307
- reason: `no browser was started: the system temp folder cannot be written (${r.noTemp}), and a browser needs a profile folder of its own there; fix the temp folder (TMPDIR), then run the command again`,
2308
- });
2309
- return results;
2310
- }
2311
- // Each picture's own lines, by its place in this browser's share.
2312
- /** @type {Map<number, string[]>} */
2313
- const said = new Map();
2314
- for (const line of String(r.stdout ?? '').split('\n')) {
2315
- const tab = line.indexOf('\t');
2316
- const i = Number(line.slice(0, tab));
2317
- if (tab < 1 || !Number.isInteger(i)) continue;
2318
- said.set(i, [...(said.get(i) ?? []), line.slice(tab + 1)]);
2319
- }
2320
- // The pictures it took whole, in order, up to the first it did not.
2321
- for (const [i, job] of rest.entries()) {
2322
- const lines = said.get(i) ?? [];
2323
- if (!lines.includes(PICTURE_TAKEN) || !fs.existsSync(job.png)) break;
2324
- const out = lines.join('\n');
2325
- results.push({
2326
- ok: true,
2327
- file: shown(project.cwd, job.png),
2328
- notes: [
2329
- ...(failed.length
2330
- ? [`the picture was taken with ${t.who}; ${failed.join('; ')}`]
2331
- : []),
2332
- ...pictureFontNotes(out),
2333
- ],
2334
- ...measuredCutShort(out),
2335
- ...measuredLowContrast(out),
2336
- ...measuredBoxes(out),
2337
- });
2338
- }
2339
- if (results.length === jobs.length) return results;
2340
- // A share it did not finish is the next browser's.
2341
- for (const job of jobs.slice(results.length))
2342
- fs.rmSync(job.png, {force: true});
2343
- const text = r.error ? String(r.error.message) : r.stderr;
2344
- if (
2345
- t.script === PLAYWRIGHT_PICTURE &&
2346
- /Executable doesn't exist|playwright install/i.test(text)
2347
- )
2348
- pwMissing = true;
2349
- const why = r.timedOut
2350
- ? `${t.who} did not finish within ${(BROWSER_BOUND_MS + (rest.length - 1) * PAGE_BOUND_MS) / 1000} seconds, so it was stopped`
2351
- : `${t.who} could not take it: ${causeOf(text || (r.status === 0 ? 'it stopped before every picture was taken' : ''))}`;
2352
- run.failed.set(t.who, why);
2353
- failed.push(why);
2354
- }
2355
- results.push(
2356
- failed.length
2357
- ? {
2358
- ok: false,
2359
- // Advice that can change the result: Playwright's browser only when
2360
- // it is missing; a Chrome to check only when there is one.
2361
- reason: `${failed.join('; ')}. ${
2362
- !pwFound
2363
- ? `Install Playwright with its browser (${installLine(project.cwd, ['playwright'])}, then npx playwright install chromium), or`
2364
- : pwMissing
2365
- ? 'Give Playwright its browser (npx playwright install chromium), or'
2366
- : "Fix what Playwright's browser needs (the reason is above), or"
2367
- } ${chrome ? `check that ${chrome} starts on this machine` : 'install Google Chrome or Chromium'}. The HTML preview needs neither.`,
2368
- }
2369
- : {
2370
- ok: false,
2371
- reason: `No browser was found to take the picture. Install Playwright with its browser (${installLine(project.cwd, ['playwright'])}, then npx playwright install chromium), or install Google Chrome or Chromium. The HTML preview needs neither.`,
2372
- },
2373
- );
2374
- return results;
2375
- }
2376
-
2377
- /**
2378
- * How much each part's drawn size changes from one page to another (the
2379
- * sheet before a change and after it): both pictured in one browser run,
2380
- * each part's boxes measured, and the largest growth of a box at the same
2381
- * place in the page taken, in px. A part not drawn on both pages is
2382
- * counted as not drawn. The pictures themselves are not kept.
2383
- * @param {import('./_project.mjs').ThemeProject} project
2384
- * @param {string} before absolute path of the page before
2385
- * @param {string} after absolute path of the page after
2386
- * @param {string[]} parts
2387
- * @param {'light' | 'dark'} mode
2388
- * @returns {Promise<{changes: Array<{part: string, width: number, height: number, drawn: number}>} | {problem: string}>}
2389
- */
2390
- export async function partSizeChanges(project, before, after, parts, mode) {
2391
- const pngs = [before, after].map(h => h.replace(/\.html$/, '.png'));
2392
- /** @type {PictureResult[]} */
2393
- let shots;
2394
- try {
2395
- shots = await screenshots(project, [
2396
- {html: before, png: pngs[0], mode, boxes: parts},
2397
- {html: after, png: pngs[1], mode, boxes: parts},
2398
- ]);
2399
- } finally {
2400
- for (const p of pngs) fs.rmSync(p, {force: true});
2401
- }
2402
- const [a, b] = shots;
2403
- if (!a?.ok || !b?.ok)
2404
- return {
2405
- problem:
2406
- (a && !a.ok ? a.reason : b && !b.ok ? b.reason : null) ??
2407
- 'no picture was taken',
2408
- };
2409
- return {changes: boxChanges(parts, a.boxes ?? {}, b.boxes ?? {})};
2410
- }
2411
-
2412
- /**
2413
- * How much each part's drawn boxes grow from one measurement to another:
2414
- * the largest growth in width and in height of a box at the same place in
2415
- * the page, in px, to a hundredth (0 when none grows; a box that shrinks
2416
- * does not count), and how many boxes both measurements draw.
2417
- * @param {string[]} parts
2418
- * @param {Record<string, Array<[number, number]>>} was
2419
- * @param {Record<string, Array<[number, number]>>} now
2420
- * @returns {Array<{part: string, width: number, height: number, drawn: number}>}
2421
- */
2422
- export function boxChanges(parts, was, now) {
2423
- const round = (/** @type {number} */ n) => Math.round(n * 100) / 100;
2424
- return parts.map(part => {
2425
- const a = was[part] ?? [];
2426
- const b = now[part] ?? [];
2427
- const drawn = Math.min(a.length, b.length);
2428
- let width = 0;
2429
- let height = 0;
2430
- for (let i = 0; i < drawn; i++) {
2431
- width = Math.max(width, b[i][0] - a[i][0]);
2432
- height = Math.max(height, b[i][1] - a[i][1]);
2433
- }
2434
- return {part, width: round(width), height: round(height), drawn};
2435
- });
2436
- }
2437
-
2438
- /**
2439
- * What a change of size says about the parts it measured: how much each
2440
- * part that grows grows, else that they keep their size; null when none
2441
- * of them is drawn.
2442
- * @param {Array<{part: string, width: number, height: number, drawn: number}>} changes
2443
- * @param {string} cause what grew them ("the added border")
2444
- * @returns {string | null}
2445
- */
2446
- export function sizeChangeNote(changes, cause) {
2447
- const drawn = changes.filter(x => x.drawn);
2448
- if (!drawn.length) return null;
2449
- const grows = drawn.filter(x => x.width > 0 || x.height > 0);
2450
- if (!grows.length)
2451
- return `${drawn.map(x => x.part).join(', ')} keeps its size with ${cause} (measured on the sheet, at rest and in each state it draws)`;
2452
- return grows
2453
- .map(
2454
- x =>
2455
- `${x.part} grows by ${[
2456
- ...(x.height > 0 ? [`${x.height}px in height`] : []),
2457
- ...(x.width > 0 ? [`${x.width}px in width`] : []),
2458
- ].join(' and ')} (${cause}; measured on the sheet)`,
2459
- )
2460
- .join('; ');
2461
- }
2462
-
2463
- /** The generic families any font of a common kind stands in for. */
2464
- const PLAIN_GENERICS = ['sans-serif', 'system-ui', 'ui-sans-serif'];
2465
-
2466
- /**
2467
- * What a picture shows in place of a font stack: a role whose stack ends in
2468
- * a generic of a kind (serif, monospace, cursive) and none of whose named
2469
- * families this machine has is drawn in this machine's font for that
2470
- * generic, which may be of another kind (a system with no serif font draws
2471
- * serif in a sans-serif one). A stack that ends in sans-serif falls back
2472
- * to a font of its own kind, so it is not named.
2473
- * @param {string} stdout what the picture script printed
2474
- * @returns {string[]}
2475
- */
2476
- export function pictureFontNotes(stdout) {
2477
- const line = stdout.split('\n').find(l => l.startsWith(FONT_PROBE_PREFIX));
2478
- if (!line) return [];
2479
- /** @type {Record<string, {stack: string[], shown: string | null} | null>} */
2480
- let probe;
2481
- try {
2482
- probe = JSON.parse(line.slice(FONT_PROBE_PREFIX.length));
2483
- } catch {
2484
- return [];
2485
- }
2486
- /** @type {string[]} */
2487
- const out = [];
2488
- for (const [role, label] of /** @type {const} */ ([
2489
- ['heading', 'headings'],
2490
- ['body', 'body text'],
2491
- ])) {
2492
- const r = probe?.[role];
2493
- const generic = r?.stack.at(-1)?.toLowerCase();
2494
- if (!r?.shown || !generic || PLAIN_GENERICS.includes(generic)) continue;
2495
- const named = r.stack.slice(0, -1);
2496
- const drawn = r.shown.toLowerCase();
2497
- if (!named.length || named.some(f => f.toLowerCase() === drawn)) continue;
2498
- out.push(
2499
- `this machine has none of ${named.join(', ')}, so the pictures draw the ${label} in ${r.shown}, its font for ${generic}; a system with ${named[0]} shows them as set (an open font with its package installed shows everywhere, the pictures included)`,
2500
- );
2501
- }
2502
- return out;
2503
- }
2504
-
2505
- /**
2506
- * The text a picture script measured cut short, from the line it prints
2507
- * after `CUT_SHORT_PREFIX`; nothing when it printed none that reads.
2508
- * @param {string} stdout what the picture script printed
2509
- * @returns {{cutShort?: Array<{part: string | null, text: string, whole: boolean, broken?: boolean, overlaps?: boolean}>}}
2510
- */
2511
- function measuredCutShort(stdout) {
2512
- const line = stdout.split('\n').find(l => l.startsWith(CUT_SHORT_PREFIX));
2513
- if (!line) return {};
2514
- /** @type {unknown} */
2515
- let found;
2516
- try {
2517
- found = JSON.parse(line.slice(CUT_SHORT_PREFIX.length));
2518
- } catch {
2519
- return {};
2520
- }
2521
- if (!Array.isArray(found)) return {};
2522
- return {
2523
- cutShort: found
2524
- .filter(x => x && typeof x.text === 'string')
2525
- .map(x => ({
2526
- part: typeof x.part === 'string' ? x.part : null,
2527
- text: x.text,
2528
- whole: x.whole === true,
2529
- ...(x.broken === true ? {broken: true} : {}),
2530
- ...(x.overlaps === true ? {overlaps: true} : {}),
2531
- })),
2532
- };
2533
- }
2534
-
2535
- /**
2536
- * The text a picture script measured too faint to read, from the line it
2537
- * prints after `LOW_CONTRAST_PREFIX`; nothing when it printed none that
2538
- * reads.
2539
- * @param {string} stdout what the picture script printed
2540
- * @returns {{lowContrast?: Array<{part: string, text: string, ratio: number, fg: string, bg: string}>}}
2541
- */
2542
- function measuredLowContrast(stdout) {
2543
- const line = stdout.split('\n').find(l => l.startsWith(LOW_CONTRAST_PREFIX));
2544
- if (!line) return {};
2545
- /** @type {unknown} */
2546
- let found;
2547
- try {
2548
- found = JSON.parse(line.slice(LOW_CONTRAST_PREFIX.length));
2549
- } catch {
2550
- return {};
2551
- }
2552
- if (!Array.isArray(found)) return {};
2553
- return {
2554
- lowContrast: found.filter(
2555
- x =>
2556
- x &&
2557
- typeof x.part === 'string' &&
2558
- typeof x.text === 'string' &&
2559
- typeof x.ratio === 'number' &&
2560
- /^#[0-9a-f]{6}$/.test(String(x.fg)) &&
2561
- /^#[0-9a-f]{6}$/.test(String(x.bg)),
2562
- ),
2563
- };
2564
- }
2565
-
2566
- /**
2567
- * The part sizes a picture script measured, from the line it prints after
2568
- * `PART_BOXES_PREFIX`; nothing when it printed none that reads.
2569
- * @param {string} stdout what the picture script printed
2570
- * @returns {{boxes?: Record<string, Array<[number, number]>>}}
2571
- */
2572
- function measuredBoxes(stdout) {
2573
- const line = stdout.split('\n').find(l => l.startsWith(PART_BOXES_PREFIX));
2574
- if (!line) return {};
2575
- /** @type {unknown} */
2576
- let found;
2577
- try {
2578
- found = JSON.parse(line.slice(PART_BOXES_PREFIX.length));
2579
- } catch {
2580
- return {};
2581
- }
2582
- if (!found || typeof found !== 'object' || Array.isArray(found)) return {};
2583
- /** @type {Record<string, Array<[number, number]>>} */
2584
- const boxes = {};
2585
- for (const [part, list] of Object.entries(found))
2586
- if (Array.isArray(list))
2587
- boxes[part] = list.filter(
2588
- (/** @type {unknown} */ b) =>
2589
- Array.isArray(b) &&
2590
- b.length === 2 &&
2591
- b.every(n => typeof n === 'number'),
2592
- );
2593
- return {boxes};
2594
- }
2595
-
2596
- /** A Chrome or Chromium on this machine, at a usual place or on PATH. */
2597
- function chromeBinary() {
2598
- const names = [
2599
- 'google-chrome',
2600
- 'google-chrome-stable',
2601
- 'chromium',
2602
- 'chromium-browser',
2603
- 'chrome',
2604
- ];
2605
- const fixed = [
2606
- '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
2607
- '/Applications/Chromium.app/Contents/MacOS/Chromium',
2608
- 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
2609
- 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
2610
- ];
2611
- // Only a file that runs: a folder or a file with no execute permission
2612
- // by a browser's name is passed over, and the search goes on.
2613
- /** @param {string} f */
2614
- const runs = f => {
2615
- try {
2616
- if (!fs.statSync(f).isFile()) return false;
2617
- if (process.platform !== 'win32') fs.accessSync(f, fs.constants.X_OK);
2618
- return true;
2619
- } catch {
2620
- return false;
2621
- }
2622
- };
2623
- for (const f of fixed) if (runs(f)) return f;
2624
- for (const dir of (process.env.PATH ?? '').split(path.delimiter)) {
2625
- for (const n of names) {
2626
- const f = path.join(dir, n);
2627
- if (dir && runs(f)) return f;
2628
- }
2629
- }
2630
- return null;
2631
- }
2632
-
2633
- /** The first line of every file the editor writes into a theme's app copy. */
2634
- export {APP_COPY_MARK} from './_marks.mjs';
2635
- import {APP_COPY_MARK, appCopyMark} from './_marks.mjs';
2636
- import {builtColorMode} from '../../foundation/discovery/theme-imports.mjs';
2637
-
2638
- /**
2639
- * The font stylesheets a theme's app copy imports, from the fonts the theme
2640
- * loads now (an installed font package, the base theme's fonts).
2641
- * @param {import('./_settings.mjs').Ctx} ctx
2642
- * @param {string} slug
2643
- * @param {import('./_settings.mjs').ThemeData} data
2644
- * @returns {string[]}
2645
- */
2646
- export function copyFontsCss(ctx, slug, data) {
2647
- return themeImports(
2648
- ctx,
2649
- slug,
2650
- data,
2651
- path.join(ctx.project.cwd, 'src', 'themes', slug),
2652
- ).css.slice(1);
2653
- }
2654
-
2655
- /**
2656
- * The app's copy of an editor theme: a standard local theme in
2657
- * src/themes/<theme>/ (a descriptor, a source that re-exports the built
2658
- * module, the built module, its stylesheet and font stylesheet), the shape
2659
- * `astryx theme add <theme>` reads, so the theme goes into the app with the
2660
- * stable theme commands. It is written again after every build of the
2661
- * theme, never edited by hand. A folder there that is not the editor's own
2662
- * copy is left alone: returns null then, else the folder.
2663
- * The built module and stylesheet are written whole: a local theme's source
2664
- * may import only files inside its own folder.
2665
- * @param {import('./_settings.mjs').Ctx} ctx
2666
- * @param {string} slug
2667
- * @param {import('./_settings.mjs').ThemeData} data
2668
- * @returns {string | null}
2669
- */
2670
- export function writeAppCopy(ctx, slug, data) {
2671
- return writeAppCopyAt(ctx.project.cwd, slug, copyFontsCss(ctx, slug, data));
2672
- }
2673
-
2674
- /** What a module file of the theme folder may end with, as a bundler reads it. */
2675
- const LOCAL_MODULE_ENDINGS = ['', '.ts', '.tsx', '.mts', '.js', '.mjs', '.jsx'];
2676
-
2677
- /**
2678
- * The modules of the theme's own folder its built module imports (an icon
2679
- * registry beside the theme, and what those import in turn), by their path
2680
- * in the folder: the copy carries each, as the app's bundler resolves it
2681
- * (an import without its ending, or a folder's index). `problem` names an
2682
- * import that leaves the folder, does not resolve, or names a file the
2683
- * editor writes; the copy is not written then.
2684
- * @param {string} cwd
2685
- * @param {string} slug
2686
- * @returns {{files: Array<{rel: string, file: string}>, problem: string | null}}
2687
- */
2688
- export function themeLocalModules(cwd, slug) {
2689
- const f = themeFiles(cwd, slug);
2690
- /** @type {string} */
2691
- let root;
2692
- try {
2693
- root = fs.realpathSync(f.dir);
2694
- } catch {
2695
- return {files: [], problem: null};
2696
- }
2697
- const own = appCopyNames(slug);
2698
- /** @type {Map<string, string>} */
2699
- const found = new Map();
2700
- /** @param {string} from @param {string} spec */
2701
- const resolveIn = (from, spec) => {
2702
- const at = path.resolve(path.dirname(from), spec);
2703
- for (const c of [
2704
- ...LOCAL_MODULE_ENDINGS.map(e => `${at}${e}`),
2705
- ...LOCAL_MODULE_ENDINGS.slice(1).map(e => path.join(at, `index${e}`)),
2706
- ]) {
2707
- const st = fs.statSync(c, {throwIfNoEntry: false});
2708
- if (st?.isFile()) return c;
2709
- }
2710
- return null;
2711
- };
2712
- /** @param {string} from @returns {string | null} */
2713
- const walk = from => {
2714
- /** @type {string[]} */
2715
- let specs;
2716
- try {
2717
- specs = themeFileImports(from);
2718
- } catch {
2719
- specs = [];
2720
- }
2721
- for (const spec of specs.filter(s => s.startsWith('.'))) {
2722
- const shownFrom = `themes/${slug}/${path.relative(f.dir, from).split(path.sep).join('/')}`;
2723
- const file = resolveIn(from, spec);
2724
- if (!file)
2725
- return `${shownFrom} imports ${spec}, which is not there, so the copy cannot carry it`;
2726
- const real = fs.realpathSync(file);
2727
- if (real !== root && !real.startsWith(root + path.sep))
2728
- return `${shownFrom} imports ${spec}, a file outside themes/${slug}/, which the copy cannot carry (a local theme imports only files of its own folder); move it into themes/${slug}/`;
2729
- const rel = path.relative(root, real).split(path.sep).join('/');
2730
- if (own.has(rel) && rel !== `${slug}.js`)
2731
- return `${shownFrom} imports ${spec}, a file the editor writes, which the copy cannot carry as a module of its own`;
2732
- if (rel === `${slug}.js` || found.has(rel)) continue;
2733
- found.set(rel, real);
2734
- const deeper = walk(real);
2735
- if (deeper) return deeper;
2736
- }
2737
- return null;
2738
- };
2739
- if (!fs.existsSync(f.js)) return {files: [], problem: null};
2740
- const problem = walk(f.js);
2741
- return {
2742
- files: [...found].map(([rel, file]) => ({rel, file})),
2743
- problem,
2744
- };
2745
- }
2746
-
2747
- /**
2748
- * The files of a theme's app copy as the editor would write them now, by
2749
- * name; null with no build to copy. Font stylesheets as given, or null for
2750
- * the copy's own.
2751
- * @param {string} cwd
2752
- * @param {string} slug
2753
- * @param {string[] | null} fontsCss
2754
- * @returns {Record<string, string> | null}
2755
- */
2756
- function appCopyFiles(cwd, slug, fontsCss) {
2757
- const f = themeFiles(cwd, slug);
2758
- const dir = path.join(cwd, 'src', 'themes', slug);
2759
- const name = `${camel(slug)}Theme`;
2760
- if (!fs.existsSync(f.js) || !fs.existsSync(f.css)) return null;
2761
- const source = `src/themes/${slug}/${name}.ts`;
2762
- const head = (/** @type {string} */ open, /** @type {string} */ close) =>
2763
- `${open} ${appCopyMark(slug)} after every build of themes/${slug}/; do not edit it here. Change the theme with the editor. ${close}\n`;
2764
- const keptFonts = path.join(dir, `${slug}.fonts.css`);
2765
- const fonts =
2766
- fontsCss ??
2767
- (fs.existsSync(keptFonts)
2768
- ? [
2769
- ...fs.readFileSync(keptFonts, 'utf8').matchAll(/@import "([^"]+)";/g),
2770
- ].map(m => m[1])
2771
- : []);
2772
- // A built file as `theme build` of the copy's source writes it: the
2773
- // editor's build of the same theme, with the header naming that source.
2774
- const asBuilt = (/** @type {string} */ text) =>
2775
- text
2776
- .replace(/^( \* Source: ).*$/m, `$1${source}`)
2777
- .replace(/^( \* Command: ).*$/m, `$1astryx theme build ${source}`);
2778
- /** @type {Record<string, string>} */
2779
- const built = {};
2780
- for (const ext of APP_COPY_BUILT) {
2781
- const from = path.join(f.dir, `${slug}${ext}`);
2782
- if (fs.existsSync(from))
2783
- built[`${slug}${ext}`] = asBuilt(fs.readFileSync(from, 'utf8'));
2784
- }
2785
- // A light-only or dark-only theme's build exports its one color mode
2786
- // (`colorModes`); the copy's source re-exports it, so a build of the copy
2787
- // writes it too and `theme add` reads it.
2788
- const oneMode = builtColorMode(f.js).mode;
2789
- const files = {
2790
- [`${name}.doc.mjs`]: `${head('//', '')}\n/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */\nexport default {\n type: 'theme',\n name: ${JSON.stringify(slug)},\n displayName: ${JSON.stringify(slug)},\n description: ${JSON.stringify(`The ${slug} theme, made with the theme editor (themes/${slug}/).`)},\n maintained: false,\n};\n`,
2791
- [`${name}.ts`]: `${head('//', '')}export {${name}${oneMode ? ', colorModes' : ''}} from './${slug}';\n`,
2792
- ...built,
2793
- // The theme folder's own modules the build imports, as they are, under
2794
- // the copy's mark (a file there without it is yours, and is left).
2795
- ...Object.fromEntries(
2796
- themeLocalModules(cwd, slug).files.map(({rel, file}) => [
2797
- rel,
2798
- `${head('//', '')}${fs.readFileSync(file, 'utf8')}`,
2799
- ]),
2800
- ),
2801
- // Always there, so the app theme module's import of it holds when the
2802
- // theme's fonts change (none: a comment only).
2803
- [`${slug}.fonts.css`]: fonts.length
2804
- ? `${head('/*', '*/')}${fonts.map(c => `@import ${JSON.stringify(c)};`).join('\n')}\n`
2805
- : `${head('/*', '*/')}/* No font stylesheets: no installed package loads the theme's fonts. A font the system does not have shows only once its package is installed (experimental theme editor show ${slug} names it). */\n`,
2806
- };
2807
- return files;
2808
- }
2809
-
2810
- /**
2811
- * Why a theme's app copy is behind its build, or null when it is current:
2812
- * something in its way (appCopyStale), a copy file missing, or a file
2813
- * whose content is not what the editor would write now.
2814
- * @param {string} cwd
2815
- * @param {string} slug
2816
- * @param {string[] | null} [fontsCss] the font stylesheets the copy should
2817
- * import now (null: the copy's own)
2818
- * @returns {string | null}
2819
- */
2820
- export function appCopyBehind(cwd, slug, fontsCss = null) {
2821
- const stale = appCopyStale(cwd, slug).appCopyStale;
2822
- if (stale) return stale;
2823
- const files = appCopyFiles(cwd, slug, fontsCss);
2824
- if (!files) return null;
2825
- const dir = path.join(cwd, 'src', 'themes', slug);
2826
- if (!fs.existsSync(dir))
2827
- return `the app copy in src/themes/${slug}/ is gone; the editor writes it again`;
2828
- for (const [n, text] of Object.entries(files)) {
2829
- /** @type {string} */
2830
- let now;
2831
- try {
2832
- now = fs.readFileSync(path.join(dir, n), 'utf8');
2833
- } catch {
2834
- return `src/themes/${slug}/${n} is missing from the app copy`;
2835
- }
2836
- // Line endings as a checkout writes them (CRLF on Windows) are the
2837
- // same content, as the outputs check reads them.
2838
- const lf = (/** @type {string} */ x) => x.replace(/\r\n/g, '\n');
2839
- if (lf(now) !== lf(text))
2840
- return `src/themes/${slug}/${n} is not the current build of themes/${slug}/`;
2841
- }
2842
- return null;
2843
- }
2844
-
2845
- /**
2846
- * {@link writeAppCopy} with the font stylesheets given, or null to keep the
2847
- * copy's own (a compile, which changes no setting).
2848
- * @param {string} cwd
2849
- * @param {string} slug
2850
- * @param {string[] | null} fontsCss
2851
- * @returns {string | null}
2852
- */
2853
- export function writeAppCopyAt(cwd, slug, fontsCss) {
2854
- const f = themeFiles(cwd, slug);
2855
- const dir = path.join(cwd, 'src', 'themes', slug);
2856
- const name = `${camel(slug)}Theme`;
2857
- const first = !fs.existsSync(path.join(dir, `${name}.doc.mjs`));
2858
- if (!fs.existsSync(f.js) || !fs.existsSync(f.css)) return null;
2859
- // Only the editor's own copy is written over.
2860
- if (appCopyBlocker(cwd, slug) !== null) return null;
2861
- const files = appCopyFiles(cwd, slug, fontsCss);
2862
- if (!files) return null;
2863
- const failKey = `${path.resolve(cwd)}\0${slug}`;
2864
- try {
2865
- fs.mkdirSync(dir, {recursive: true});
2866
- for (const [n, text] of Object.entries(files)) {
2867
- const file = path.join(dir, n);
2868
- if (fs.existsSync(file) && fs.readFileSync(file, 'utf8') === text)
2869
- continue;
2870
- // A module of the theme folder may sit in a folder of its own.
2871
- fs.mkdirSync(path.dirname(file), {recursive: true});
2872
- writeWhole(file, text);
2873
- }
2874
- // A copy's own file this build no longer writes goes; anything else in
2875
- // the folder (yours, or the system's) stays as it is.
2876
- for (const n of fs.readdirSync(dir))
2877
- if (appCopyNames(slug).has(n) && !(n in files))
2878
- fs.rmSync(path.join(dir, n), {force: true});
2879
- } catch (e) {
2880
- // A copy that cannot be written is said, with the system's reason;
2881
- // the change itself stands.
2882
- const code = /** @type {any} */ (e)?.code ?? 'error';
2883
- // The folder that failed: the copy's, or a parent it could not be
2884
- // made in.
2885
- const failed = /** @type {any} */ (e)?.path
2886
- ? path.resolve(String(/** @type {any} */ (e).path))
2887
- : dir;
2888
- const at = fs.existsSync(failed) ? failed : path.dirname(failed);
2889
- const rel = path.relative(cwd, at).split(path.sep).join('/');
2890
- const unwritable =
2891
- code === 'EACCES' || code === 'EPERM' || code === 'EROFS';
2892
- COPY_FAILED.set(failKey, {
2893
- why: unwritable
2894
- ? `${rel} is not writable (${code})`
2895
- : code === 'ENOSPC'
2896
- ? `the disk is full (${code})`
2897
- : `${rel} could not be written (${code})`,
2898
- // A folder that was not writable, to see whether it still is.
2899
- ...(unwritable ? {folder: at} : {}),
2900
- });
2901
- return null;
2902
- }
2903
- COPY_FAILED.delete(failKey);
2904
- // The first write is named in the command's result; later ones are not.
2905
- if (first)
2906
- FIRST_COPIES.set(
2907
- `${path.resolve(cwd)}\0${slug}`,
2908
- Object.keys(files)
2909
- .sort()
2910
- .map(n =>
2911
- path.relative(cwd, path.join(dir, n)).split(path.sep).join('/'),
2912
- ),
2913
- );
2914
- return dir;
2915
- }
2916
-
2917
- /**
2918
- * The note for a copy a file of yours keeps from being written, as a
2919
- * result field: `{appCopyStale}` when one does, else nothing.
2920
- * @param {string} cwd
2921
- * @param {string} slug
2922
- * @returns {{appCopyStale?: string}}
2923
- */
2924
- export function appCopyStale(cwd, slug) {
2925
- const blocker = appCopyBlocker(cwd, slug) ?? copyFailure(cwd, slug) ?? null;
2926
- return blocker
2927
- ? {
2928
- appCopyStale: `the app copy in src/themes/${slug}/ was not updated: ${blocker}. The app keeps the theme as it was until that is out of the way; then any set or show writes it.`,
2929
- }
2930
- : {};
2931
- }
2932
-
2933
- /**
2934
- * Why the editor will not write a theme's app copy, or null when it will.
2935
- * Only a file of yours AT one of the copy's names stops it: a descriptor,
2936
- * source or font stylesheet without the editor's mark, or any copy file
2937
- * while the descriptor is not the editor's. Other files there (a note, a
2938
- * swap file, desktop.ini) are left as they are and the copy is written
2939
- * around them. Built bytes are not compared, so a stable rebuild of the
2940
- * copy leaves it the editor's. The one test the copy's writer, the change
2941
- * results and `wiring` use. Returns the file in the way.
2942
- * @param {string} cwd
2943
- * @param {string} slug
2944
- * @returns {string | null}
2945
- */
2946
- export function appCopyBlocker(cwd, slug) {
2947
- const dir = path.join(cwd, 'src', 'themes', slug);
2948
- const name = `${camel(slug)}Theme`;
2949
- const rel = path.relative(cwd, dir).split(path.sep).join('/');
2950
- // The copy carries the built module whole, with the modules of the theme
2951
- // folder it imports (an icon registry beside the theme); one it cannot
2952
- // carry (outside the folder, or not there) keeps the copy as it was.
2953
- const locals = themeLocalModules(cwd, slug);
2954
- if (locals.problem) return locals.problem;
2955
- // A file of yours at a name the copy carries a module to is left alone.
2956
- for (const {rel: r} of locals.files) {
2957
- const at = path.join(dir, r);
2958
- const st = fs.lstatSync(at, {throwIfNoEntry: false});
2959
- if (!st) continue;
2960
- if (!st.isFile())
2961
- return `${rel}/${r} is ${st.isSymbolicLink() ? 'a link' : 'a folder'}, at a name the copy carries themes/${slug}/${r} to, and the editor writes nothing there`;
2962
- /** @type {string} */
2963
- let text;
2964
- try {
2965
- text = fs.readFileSync(at, 'utf8');
2966
- } catch {
2967
- text = '';
2968
- }
2969
- if (!text.includes(APP_COPY_MARK))
2970
- return `${rel}/${r} is a file the editor did not write, at a name the copy carries themes/${slug}/${r} to; move it, then any set or show writes the copy`;
2971
- }
2972
- // Nothing is written through a link on the way from the app to the copy
2973
- // (src/, src/themes/, the copy's folder), as for themes/.
2974
- for (const part of ['src', 'src/themes', rel]) {
2975
- try {
2976
- const st = fs.lstatSync(path.join(cwd, part));
2977
- if (st.isSymbolicLink())
2978
- return `${part} is a link (to ${fs.readlinkSync(path.join(cwd, part))}), and the editor writes nothing through a link`;
2979
- // A file where a folder on the way goes: nothing is half-written.
2980
- if (!st.isDirectory())
2981
- return part === rel
2982
- ? `${rel} is a file, where the copy's folder goes`
2983
- : `${part} is a file, where a folder on the way to the copy goes`;
2984
- } catch {
2985
- break;
2986
- }
2987
- }
2988
- try {
2989
- if (!fs.lstatSync(dir).isDirectory())
2990
- return `${rel} is a file, where the copy's folder goes`;
2991
- } catch {
2992
- // Not there yet: the copy makes it.
2993
- }
2994
- if (folderIsEmpty(dir)) return null;
2995
- /** @type {string[]} */
2996
- let names;
2997
- try {
2998
- names = fs.readdirSync(dir);
2999
- } catch (e) {
3000
- return `${rel} cannot be read (${/** @type {any} */ (e)?.code ?? 'error'})`;
3001
- }
3002
- /** @param {string} n */
3003
- const marked = n => {
3004
- try {
3005
- return fs.readFileSync(path.join(dir, n), 'utf8').includes(APP_COPY_MARK);
3006
- } catch {
3007
- return false;
3008
- }
3009
- };
3010
- const own = appCopyNames(slug);
3011
- const present = names.filter(n => own.has(n));
3012
- // A link at a copy name is never written through or replaced.
3013
- for (const n of present)
3014
- try {
3015
- const st = fs.lstatSync(path.join(dir, n));
3016
- if (st.isSymbolicLink())
3017
- return `${rel}/${n} is a link (to ${fs.readlinkSync(path.join(dir, n))}), at a name the copy uses, and the editor writes nothing through a link`;
3018
- if (st.isDirectory())
3019
- return `${rel}/${n} is a folder, at a name the copy uses for a file`;
3020
- } catch {
3021
- // Gone since it was listed.
3022
- }
3023
- // The copy is the editor's when any of its marked files carries the
3024
- // mark (one of them deleted is written back); then only a marked name
3025
- // without the mark is yours.
3026
- const markedNames = [`${name}.doc.mjs`, `${name}.ts`, `${slug}.fonts.css`];
3027
- // A build output of the copy's source carries the build's own header.
3028
- const generated = (/** @type {string} */ n) => {
3029
- try {
3030
- return /@generated by `astryx theme build`/.test(
3031
- fs.readFileSync(path.join(dir, n), 'utf8').slice(0, 600),
3032
- );
3033
- } catch {
3034
- return false;
3035
- }
3036
- };
3037
- const ours =
3038
- markedNames.some(n => present.includes(n) && marked(n)) ||
3039
- (present.length > 0 &&
3040
- present.every(n => !markedNames.includes(n) && generated(n)));
3041
- const foreign = ours
3042
- ? present.find(n => markedNames.includes(n) && !marked(n))
3043
- : present[0];
3044
- return foreign
3045
- ? `${rel}/${foreign} is yours, at a name the copy uses, and the editor never writes over your files`
3046
- : null;
3047
- }
3048
-
3049
- /**
3050
- * Why the last write of a theme's app copy failed, by app and theme, and
3051
- * the folder that was not writable when that was why.
3052
- * @type {Map<string, {why: string, folder?: string}>}
3053
- */
3054
- const COPY_FAILED = new Map();
3055
-
3056
- /**
3057
- * Why the last write of a theme's app copy failed, while that still holds:
3058
- * a folder that was not writable and is now is no reason any more (a
3059
- * process that runs several commands, as an API caller does, reads the
3060
- * folder as it is now).
3061
- * @param {string} cwd
3062
- * @param {string} slug
3063
- * @returns {string | null}
3064
- */
3065
- function copyFailure(cwd, slug) {
3066
- const key = `${path.resolve(cwd)}\0${slug}`;
3067
- const failed = COPY_FAILED.get(key);
3068
- if (!failed) return null;
3069
- if (failed.folder)
3070
- try {
3071
- fs.accessSync(failed.folder, fs.constants.W_OK);
3072
- COPY_FAILED.delete(key);
3073
- return null;
3074
- } catch {
3075
- // Still not writable.
3076
- }
3077
- return failed.why;
3078
- }
3079
-
3080
- /** App copies written for the first time in this process, by app and theme. @type {Map<string, string[]>} */
3081
- const FIRST_COPIES = new Map();
3082
-
3083
- /**
3084
- * The files of a theme's app copy when this command wrote it for the first
3085
- * time (then forgotten, so one result names them), else null.
3086
- * @param {string} cwd
3087
- * @param {string} slug
3088
- * @returns {string[] | null}
3089
- */
3090
- export function takeFirstAppCopy(cwd, slug) {
3091
- const key = `${path.resolve(cwd)}\0${slug}`;
3092
- const wrote = FIRST_COPIES.get(key) ?? null;
3093
- FIRST_COPIES.delete(key);
3094
- return wrote;
3095
- }
3096
-
3097
- /**
3098
- * Run a picture script (one browser, one picture) as its own process group,
3099
- * without blocking this process. The one owner of every browser run:
3100
- * - a temp folder of its own (TMPDIR, TMP, TEMP), where the browser keeps
3101
- * its profile; with none to make, nothing runs (`noTemp`);
3102
- * - a time bound (`timedOut`);
3103
- * - a stop (SIGINT, SIGTERM, SIGHUP) that reaches the run stops it
3104
- * (`stoppedBy`), then ends this process as the stop would have.
3105
- * A stop or the bound asks the whole group to close, waits for it (killing
3106
- * it past a short grace), then removes the temp folder and the `drop` files
3107
- * (a picture part a stopped run leaves); a run that ends on its own removes
3108
- * the temp folder only, and gives what the script wrote on its standard
3109
- * output (`stdout`: what it measured in the page).
3110
- * @param {string} script a picture script
3111
- * @param {string[]} args
3112
- * @param {number} [bound] milliseconds before the run is stopped
3113
- * @param {{drop?: string[]}} [opts]
3114
- * @returns {Promise<{status: number | null, signal: string | null, stderr: string, stdout?: string, error?: Error, stoppedBy?: string, timedOut?: boolean, noTemp?: string}>}
3115
- */
3116
- export function runBrowser(script, args, bound = BROWSER_BOUND_MS, opts = {}) {
3117
- const drop = opts.drop ?? [];
3118
- /** @type {string} */
3119
- let temp;
3120
- try {
3121
- temp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-browser-'));
3122
- } catch (e) {
3123
- return Promise.resolve({
3124
- status: null,
3125
- signal: null,
3126
- stderr: '',
3127
- noTemp: String(/** @type {any} */ (e)?.code ?? e),
3128
- });
3129
- }
3130
- return new Promise(resolve => {
3131
- let stderr = '';
3132
- let stdout = '';
3133
- const posix = process.platform !== 'win32';
3134
- const child = spawn(process.execPath, [script, ...args], {
3135
- stdio: ['ignore', 'pipe', 'pipe'],
3136
- env: {...process.env, TMPDIR: temp, TMP: temp, TEMP: temp},
3137
- // A group of its own, so a stop reaches the browser it starts too.
3138
- detached: posix,
3139
- });
3140
- /** @param {NodeJS.Signals} sig */
3141
- const signalAll = sig => {
3142
- try {
3143
- if (posix && child.pid) process.kill(-child.pid, sig);
3144
- else child.kill(sig);
3145
- } catch {
3146
- // Gone already.
3147
- }
3148
- };
3149
- const closed = new Promise(done => child.once('close', done));
3150
- /** @param {string[]} files */
3151
- const remove = files => {
3152
- for (const f of files)
3153
- try {
3154
- fs.rmSync(f, {recursive: true, force: true});
3155
- } catch {
3156
- // Gone already.
3157
- }
3158
- };
3159
- /** The temp folder goes on every way out; `drop` only with a stop. */
3160
- const clean = () => remove([temp]);
3161
- /** Close the group (killed past the grace), then clean up. */
3162
- const finish = async () => {
3163
- signalAll('SIGTERM');
3164
- const grace = new Promise(done =>
3165
- setTimeout(done, STOP_GRACE_MS).unref(),
3166
- );
3167
- if ((await Promise.race([closed.then(() => true), grace])) !== true) {
3168
- signalAll('SIGKILL');
3169
- await closed;
3170
- }
3171
- remove([temp, ...drop]);
3172
- };
3173
- // This process ending some other way: the group is killed, and the temp
3174
- // folder and the unfinished files removed, as far as an exit allows.
3175
- const onExit = () => {
3176
- signalAll('SIGKILL');
3177
- remove([temp, ...drop]);
3178
- };
3179
- process.once('exit', onExit);
3180
- child.stderr?.setEncoding('utf8');
3181
- child.stderr?.on('data', d => {
3182
- if (stderr.length < 8000) stderr += d;
3183
- });
3184
- child.stdout?.setEncoding('utf8');
3185
- child.stdout?.on('data', d => {
3186
- // Room for every line the script prints: the fonts, and the text cut
3187
- // short on a page of every component.
3188
- if (stdout.length < 64_000) stdout += d;
3189
- });
3190
- /** Set once the run is being stopped (bound, signal): it ends there. */
3191
- let stopping = false;
3192
- let settled = false;
3193
- /** @param {Awaited<ReturnType<typeof runBrowser>>} out */
3194
- const settle = out => {
3195
- if (settled) return;
3196
- settled = true;
3197
- clearTimeout(timer);
3198
- process.removeListener('exit', onExit);
3199
- for (const sig of STOP_SIGNALS) process.removeListener(sig, onStop);
3200
- resolve(out);
3201
- };
3202
- const timer = setTimeout(() => {
3203
- stopping = true;
3204
- void finish().then(() =>
3205
- settle({status: null, signal: null, stderr, timedOut: true}),
3206
- );
3207
- }, bound);
3208
- /** @param {NodeJS.Signals} sig */
3209
- const onStop = async sig => {
3210
- stopping = true;
3211
- for (const s of STOP_SIGNALS) process.removeListener(s, onStop);
3212
- // A second stop during the grace does not wait for it: the group is
3213
- // killed and the files removed at once, then the process ends.
3214
- /** @param {NodeJS.Signals} again */
3215
- const onAgain = again => {
3216
- for (const s of STOP_SIGNALS) process.removeListener(s, onAgain);
3217
- signalAll('SIGKILL');
3218
- remove([temp, ...drop]);
3219
- if (process.listenerCount(again) === 0)
3220
- process.kill(process.pid, again);
3221
- };
3222
- for (const s of STOP_SIGNALS) process.once(s, onAgain);
3223
- await finish();
3224
- for (const s of STOP_SIGNALS) process.removeListener(s, onAgain);
3225
- settle({status: null, signal: null, stderr, stoppedBy: sig});
3226
- // Nothing else listening: the stop ends this process, as it would
3227
- // have without this listener.
3228
- if (process.listenerCount(sig) === 0) process.kill(process.pid, sig);
3229
- };
3230
- for (const sig of STOP_SIGNALS) process.once(sig, onStop);
3231
- child.once('error', error => {
3232
- clean();
3233
- settle({status: null, signal: null, stderr, error});
3234
- });
3235
- child.once('close', (status, signal) => {
3236
- if (stopping) return;
3237
- clean();
3238
- settle({status, signal, stderr, stdout});
3239
- });
3240
- });
3241
- }
3242
-
3243
- /**
3244
- * The first stderr line that says something about the picture: Chrome's
3245
- * startup warnings (dbus, GPU, sandbox notices) come first on Linux and
3246
- * say nothing about why no picture was written.
3247
- * @param {string} text
3248
- */
3249
- export function meaningfulLine(text) {
3250
- const lines = String(text ?? '')
3251
- .split(/\r?\n/)
3252
- .map(l => l.trim())
3253
- .filter(Boolean);
3254
- return (
3255
- lines.find(
3256
- l =>
3257
- !/dbus|bus\.cc|gpu_|gl_|sandbox|fontconfig|crashpad|DevTools listening|WARNING:/i.test(
3258
- l,
3259
- ),
3260
- ) ??
3261
- lines[0] ??
3262
- ''
3263
- );
3264
- }