@astryxdesign/cli 0.7.18-canary.gfca8508 → 0.7.18

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