@dooc-dev/dooc 0.0.6 → 0.0.8

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 (395) hide show
  1. package/dist/client.global.js +1 -0
  2. package/dist/code-worker.global.js +11 -11
  3. package/dist/code.global.js +75 -75
  4. package/dist/edit.global.js +234 -231
  5. package/dist/{compiler → engine/compiler}/bundle-urls.js +1 -4
  6. package/dist/{compiler → engine/compiler}/check-prose.d.ts +1 -1
  7. package/dist/{compiler → engine/compiler}/check-prose.js +1 -1
  8. package/dist/{compiler → engine/compiler}/check.js +15 -27
  9. package/dist/{compiler → engine/compiler}/code-blocks.js +3 -1
  10. package/dist/{compiler → engine/compiler}/code-languages.js +1 -2
  11. package/dist/{compiler → engine/compiler}/compile.d.ts +5 -4
  12. package/dist/{compiler → engine/compiler}/compile.js +91 -32
  13. package/dist/{compiler → engine/compiler}/config.js +1 -3
  14. package/dist/{compiler → engine/compiler}/dialect.d.ts +1 -3
  15. package/dist/{compiler → engine/compiler}/dialect.js +8 -52
  16. package/dist/{compiler → engine/compiler}/dxf.js +1 -1
  17. package/dist/{compiler → engine/compiler}/export.js +15 -8
  18. package/dist/{compiler → engine/compiler}/figures.js +26 -22
  19. package/dist/{compiler → engine/compiler}/file-cache.d.ts +1 -2
  20. package/dist/{compiler → engine/compiler}/file-cache.js +8 -15
  21. package/dist/{compiler → engine/compiler}/files.js +49 -38
  22. package/dist/{compiler → engine/compiler}/fonts.js +1 -3
  23. package/dist/{compiler → engine/compiler}/from-mdast.js +1 -1
  24. package/dist/engine/compiler/host.d.ts +10 -0
  25. package/dist/engine/compiler/host.js +16 -0
  26. package/dist/{compiler → engine/compiler}/icons.d.ts +3 -0
  27. package/dist/{compiler → engine/compiler}/icons.js +28 -10
  28. package/dist/{compiler → engine/compiler}/ignored-files.d.ts +2 -0
  29. package/dist/{compiler → engine/compiler}/ignored-files.js +12 -3
  30. package/dist/{compiler → engine/compiler}/locales.js +2 -8
  31. package/dist/{compiler → engine/compiler}/manifest.d.ts +3 -2
  32. package/dist/engine/compiler/manifest.js +46 -0
  33. package/dist/{compiler → engine/compiler}/ops.d.ts +4 -1
  34. package/dist/{compiler → engine/compiler}/ops.js +36 -21
  35. package/dist/engine/compiler/schema-file-references.d.ts +2 -0
  36. package/dist/engine/compiler/schema-file-references.js +82 -0
  37. package/dist/engine/compiler/serialize.d.ts +2 -0
  38. package/dist/engine/compiler/serialize.js +5 -0
  39. package/dist/{compiler → engine/compiler}/subformat-schema.js +1 -3
  40. package/dist/{compiler → engine/compiler}/subformats.d.ts +10 -0
  41. package/dist/{compiler → engine/compiler}/subformats.js +122 -18
  42. package/dist/{compiler → engine/compiler}/textfile-remote.js +1 -2
  43. package/dist/{compiler → engine/compiler}/textfile.js +4 -6
  44. package/dist/{compiler → engine/compiler}/theme-variants.js +1 -1
  45. package/dist/{compiler → engine/compiler}/zip.js +1 -1
  46. package/dist/{core → engine/core}/blocks.d.ts +6 -4
  47. package/dist/{core → engine/core}/content-metadata.d.ts +6 -1
  48. package/dist/{core → engine/core}/content-metadata.js +84 -18
  49. package/dist/{core → engine/core}/content-types.d.ts +4 -2
  50. package/dist/{core → engine/core}/html.d.ts +7 -0
  51. package/dist/{core → engine/core}/html.js +44 -3
  52. package/dist/{core → engine/core}/icons.d.ts +3 -0
  53. package/dist/engine/core/icons.js +20 -0
  54. package/dist/{core → engine/core}/routing.d.ts +2 -0
  55. package/dist/{core → engine/core}/routing.js +9 -0
  56. package/dist/{core → engine/core}/schema-refs.d.ts +1 -1
  57. package/dist/{core → engine/core}/schema-refs.js +3 -1
  58. package/dist/engine/core/subformat-references.d.ts +5 -0
  59. package/dist/engine/core/subformat-references.js +33 -0
  60. package/dist/{core → engine/core}/subformats.d.ts +7 -0
  61. package/dist/{core → engine/core}/subformats.js +5 -1
  62. package/dist/{core → engine/core}/taxonomy.d.ts +2 -3
  63. package/dist/{core → engine/core}/taxonomy.js +1 -5
  64. package/dist/flow.global.js +1031 -1057
  65. package/dist/frontend/application-request.d.ts +14 -0
  66. package/dist/frontend/application-request.js +36 -0
  67. package/dist/frontend/document-application.d.ts +200 -0
  68. package/dist/{viewer/serve.js → frontend/document-application.js} +1611 -1670
  69. package/dist/frontend/figure-preview.d.ts +4 -0
  70. package/dist/{viewer → frontend}/figure-preview.js +4 -4
  71. package/dist/{viewer → frontend}/file-references.d.ts +1 -1
  72. package/dist/{viewer → frontend}/file-references.js +3 -3
  73. package/dist/{viewer → frontend}/font-picker.d.ts +1 -1
  74. package/dist/{viewer → frontend}/font-settings.d.ts +1 -1
  75. package/dist/{viewer → frontend}/language-picker.js +112 -18
  76. package/dist/{viewer → frontend}/locales/eng.json +16 -2
  77. package/dist/{viewer → frontend}/locales/jpn.json +16 -2
  78. package/dist/{viewer → frontend}/locales/zho.json +16 -2
  79. package/dist/{viewer → frontend}/nav-focus.js +2 -0
  80. package/dist/{viewer → frontend}/plugin-blocks.js +2 -2
  81. package/dist/{viewer → frontend}/resize.js +14 -2
  82. package/dist/frontend/resource-download.d.ts +2 -0
  83. package/dist/frontend/resource-download.js +43 -0
  84. package/dist/{viewer → frontend}/resource-library.d.ts +9 -2
  85. package/dist/{viewer → frontend}/resource-library.js +133 -37
  86. package/dist/{core → frontend}/schema-graph-flow.d.ts +1 -1
  87. package/dist/{core → frontend}/schema-graph-flow.js +1 -1
  88. package/dist/{viewer → frontend}/search.d.ts +2 -2
  89. package/dist/{viewer → frontend}/search.js +26 -8
  90. package/dist/graph/{abnfDiagram-S7VZAUFO-ASBULSKE.js → abnfDiagram-S7VZAUFO-GAGCW2J5.js} +1 -1
  91. package/dist/graph/{architecture-WOLXFQ4H-V57EDXXY.js → architecture-WOLXFQ4H-AWAC3VBS.js} +1 -1
  92. package/dist/graph/{architectureDiagram-YGSQEFNW-GIMP347N.js → architectureDiagram-YGSQEFNW-WQ7QKSUJ.js} +1 -1
  93. package/dist/graph/{blockDiagram-APKKGZFW-RDL2T4JW.js → blockDiagram-APKKGZFW-H7ZNJMOM.js} +1 -1
  94. package/dist/graph/{bpmnIcons-APHXDYXF-TWOSQNUQ.js → bpmnIcons-APHXDYXF-EAVPNTFE.js} +1 -1
  95. package/dist/graph/{c4Diagram-KJ2TOQU5-75LIUC4F.js → c4Diagram-KJ2TOQU5-3IYS34YL.js} +1 -1
  96. package/dist/graph/{chunk-KU6GTEMS.js → chunk-3CJU2RDX.js} +1 -1
  97. package/dist/graph/{chunk-ISO77HML.js → chunk-5N2X2DXU.js} +1 -1
  98. package/dist/graph/{chunk-YCRLJT2S.js → chunk-67BPVAXC.js} +1 -1
  99. package/dist/graph/{chunk-26TUJSYJ.js → chunk-6CDZONCA.js} +1 -1
  100. package/dist/graph/{chunk-I3DMZIHV.js → chunk-7ASYMKN2.js} +1 -1
  101. package/dist/graph/{chunk-K2KLZU7M.js → chunk-7JQUFVT4.js} +2 -2
  102. package/dist/graph/{chunk-BBD5CEDC.js → chunk-7LSMJ4VU.js} +1 -1
  103. package/dist/graph/{chunk-EG5UVNOC.js → chunk-7UKJADAE.js} +1 -1
  104. package/dist/graph/{chunk-BZAMCJ6B.js → chunk-AARGNXTW.js} +1 -1
  105. package/dist/graph/{chunk-HOPPTA6H.js → chunk-BOXAA5AP.js} +2 -2
  106. package/dist/graph/{chunk-N3OHKGRZ.js → chunk-BTMPKSGF.js} +1 -1
  107. package/dist/graph/{chunk-QCJUF4YA.js → chunk-DIDARDST.js} +1 -1
  108. package/dist/graph/{chunk-R63JUMUK.js → chunk-EWYECPNJ.js} +1 -1
  109. package/dist/graph/{chunk-3YJHMOOA.js → chunk-FD7ZFC7R.js} +1 -1
  110. package/dist/graph/chunk-GWYODWCE.js +1 -0
  111. package/dist/graph/{chunk-IC23EEF6.js → chunk-HKRJKXEE.js} +1 -1
  112. package/dist/graph/{chunk-PW2RGZ3O.js → chunk-I5LEUF24.js} +1 -1
  113. package/dist/graph/{chunk-OFZLK5G4.js → chunk-ICJPOOXG.js} +1 -1
  114. package/dist/graph/{chunk-KT4VPQD5.js → chunk-IVZHB6RS.js} +2 -2
  115. package/dist/graph/{chunk-VM2H7G2R.js → chunk-JZGXHT3J.js} +1 -1
  116. package/dist/graph/{chunk-HJG2HUYJ.js → chunk-LSRL537V.js} +1 -1
  117. package/dist/graph/{chunk-C6J4A356.js → chunk-N44XPVUD.js} +1 -1
  118. package/dist/graph/{chunk-JD7ZBJD2.js → chunk-NDAMZVXQ.js} +1 -1
  119. package/dist/graph/{chunk-QEEA3KYY.js → chunk-QLS7NIYR.js} +1 -1
  120. package/dist/graph/{chunk-JRSH5GNS.js → chunk-QQIGL7OP.js} +1 -1
  121. package/dist/graph/chunk-SQE76S5B.js +1 -0
  122. package/dist/graph/{chunk-ZMCB7VP2.js → chunk-WQHTQAFY.js} +1 -1
  123. package/dist/graph/{classDiagram-v2-L25IHNXF-JL7LVDZH.js → classDiagram-v2-L25IHNXF-HNTCDTNK.js} +1 -1
  124. package/dist/graph/{cose-bilkent-JH36ORCC-PNM3EYPB.js → cose-bilkent-JH36ORCC-2GVA7XKO.js} +1 -1
  125. package/dist/graph/{cynefin-EF2NZ3EQ-PSXP3DXL.js → cynefin-EF2NZ3EQ-TCI65RAQ.js} +1 -1
  126. package/dist/graph/{cynefinDiagram-L36ESFBY-QVY54CXO.js → cynefinDiagram-L36ESFBY-OKQ5BLVF.js} +1 -1
  127. package/dist/graph/{dagre-SPEB5RXH-HPGQXBZJ.js → dagre-SPEB5RXH-KZEBD52K.js} +1 -1
  128. package/dist/graph/{diagram-3B7GL73J-DWH5WS2P.js → diagram-3B7GL73J-ESCBJM3O.js} +1 -1
  129. package/dist/graph/{diagram-DNEMPZML-TEGH2U5I.js → diagram-DNEMPZML-ZIBUSQZI.js} +1 -1
  130. package/dist/graph/{diagram-L3MUGCDN-X4MREUWR.js → diagram-L3MUGCDN-IGK62IPN.js} +1 -1
  131. package/dist/graph/{diagram-LA4NIPWU-NXT746HG.js → diagram-LA4NIPWU-2KZCOFJ5.js} +1 -1
  132. package/dist/graph/{diagram-MHCOC4E2-JGHXSAGS.js → diagram-MHCOC4E2-EYAAB236.js} +1 -1
  133. package/dist/graph/{diagram-XPFHEONP-ZHZPBLT4.js → diagram-XPFHEONP-OZ5ARGMG.js} +1 -1
  134. package/dist/graph/{ebnfDiagram-UZSYDL2S-SMF6KJ43.js → ebnfDiagram-UZSYDL2S-M3XJHARD.js} +1 -1
  135. package/dist/graph/{erDiagram-EYBAPDEH-B3JNJ357.js → erDiagram-EYBAPDEH-Y7KUBH7A.js} +1 -1
  136. package/dist/graph/{eventmodeling-K75KTNOO-WG6DDYMC.js → eventmodeling-K75KTNOO-ROLYRDEP.js} +1 -1
  137. package/dist/graph/flowDiagram-MALGAFMO-AAUEIPCR.js +1 -0
  138. package/dist/graph/{ganttDiagram-23REXITY-YXBYWFOJ.js → ganttDiagram-23REXITY-JSBTFSSJ.js} +1 -1
  139. package/dist/graph/{gitGraph-VSP46ZUC-VBFWJBBT.js → gitGraph-VSP46ZUC-ZCBCDVNF.js} +1 -1
  140. package/dist/graph/{gitGraphDiagram-STJD7YCW-4FZDCFGV.js → gitGraphDiagram-STJD7YCW-3ZA5FT3G.js} +1 -1
  141. package/dist/graph/{info-OHQRW6UA-ALVDUVYV.js → info-OHQRW6UA-JKJGOQNY.js} +1 -1
  142. package/dist/graph/infoDiagram-KBXO4MBG-6LFMPP2O.js +2 -0
  143. package/dist/graph/{ishikawaDiagram-M35NCXHK-FRZD2PWQ.js → ishikawaDiagram-M35NCXHK-YLEU44DY.js} +1 -1
  144. package/dist/graph/{journeyDiagram-OPLOXDXO-7Z66JCPR.js → journeyDiagram-OPLOXDXO-ZHJV66ZT.js} +1 -1
  145. package/dist/graph/{kanban-definition-BZKZHSQY-NN5AIKTE.js → kanban-definition-BZKZHSQY-SDU25WUM.js} +1 -1
  146. package/dist/graph/{katex-DXDNVO6V.js → katex-WSLZOTY7.js} +1 -1
  147. package/dist/graph/{mindmap-definition-I2QAS2VK-HDPCABN2.js → mindmap-definition-I2QAS2VK-XQNBCYHN.js} +1 -1
  148. package/dist/graph/{packet-JDAUHWVQ-5MQIBWAH.js → packet-JDAUHWVQ-Y3H77ERD.js} +1 -1
  149. package/dist/graph/{pegDiagram-FD4XPPHP-H2BFNCKT.js → pegDiagram-FD4XPPHP-YO4VWH6V.js} +1 -1
  150. package/dist/graph/{pie-XZMESJXO-T5VRKHVT.js → pie-XZMESJXO-PRER4XL5.js} +1 -1
  151. package/dist/graph/{pieDiagram-J4AKIIQI-O3NJSVD3.js → pieDiagram-J4AKIIQI-TJ5WOOSV.js} +1 -1
  152. package/dist/graph/{quadrantDiagram-XTYBLID2-TMTZJI3P.js → quadrantDiagram-XTYBLID2-G6MSSZLW.js} +1 -1
  153. package/dist/graph/{radar-ABXABTNO-C6FXIBYW.js → radar-ABXABTNO-M6MV34GM.js} +1 -1
  154. package/dist/graph/{railroad-I3PHUGI6-ZSO5JXB3.js → railroad-I3PHUGI6-YIWPGN6Q.js} +1 -1
  155. package/dist/graph/{railroad-abnf-LNEFI6M7-CI4GQRHB.js → railroad-abnf-LNEFI6M7-7JHLZ2R7.js} +1 -1
  156. package/dist/graph/{railroad-ebnf-DWYD2UWJ-MUENNCGK.js → railroad-ebnf-DWYD2UWJ-V55BXEWY.js} +1 -1
  157. package/dist/graph/{railroad-peg-JR7BVNR7-N3X5GGIX.js → railroad-peg-JR7BVNR7-XCGKDRMK.js} +1 -1
  158. package/dist/graph/{railroadDiagram-MRQ6NCDL-JHWS23UO.js → railroadDiagram-MRQ6NCDL-RACSFXC4.js} +1 -1
  159. package/dist/graph/{requirementDiagram-Y7LWUY3S-7DVLPO4B.js → requirementDiagram-Y7LWUY3S-4LQIQWHQ.js} +1 -1
  160. package/dist/graph/{sankeyDiagram-WGJFYUXA-Z5L4R5TR.js → sankeyDiagram-WGJFYUXA-K3RXG5FB.js} +1 -1
  161. package/dist/graph/schema-graph-global.js +17 -17
  162. package/dist/graph/{sequenceDiagram-5NDRBG5M-RCTU25NT.js → sequenceDiagram-5NDRBG5M-Y6RBHRS3.js} +1 -1
  163. package/dist/graph/{sizeCapture-INFHLROL-RROY32P5.js → sizeCapture-INFHLROL-TJW3VUGH.js} +1 -1
  164. package/dist/graph/{stateDiagram-v2-FJ4FJNEA-BXUSPWDK.js → stateDiagram-v2-FJ4FJNEA-4M5WZORG.js} +1 -1
  165. package/dist/graph/swimlanes-UMQ2AFYF-O4W6U4RO.js +1 -0
  166. package/dist/graph/swimlanesDiagram-OMPLPG4O-HZAKM45N.js +8 -0
  167. package/dist/graph/{timeline-definition-SEUHKTQE-ZQSMIVAS.js → timeline-definition-SEUHKTQE-IHISQ4Q7.js} +1 -1
  168. package/dist/graph/{treeView-D4JQ5SDB-42S7U73N.js → treeView-D4JQ5SDB-EVGY4VYS.js} +1 -1
  169. package/dist/graph/{treemap-SAJKECNS-RUBYQ7XF.js → treemap-SAJKECNS-LN3SMFRX.js} +1 -1
  170. package/dist/graph/{usecaseDiagram-AFA6YXN4-57RDRYXF.js → usecaseDiagram-AFA6YXN4-B645A3J6.js} +1 -1
  171. package/dist/graph/{vennDiagram-NNMJR3RB-5C3LVAV6.js → vennDiagram-NNMJR3RB-K3HWMON6.js} +1 -1
  172. package/dist/graph/{wardley-7MLQ67FV-NV5HXTTC.js → wardley-7MLQ67FV-RRWOELC6.js} +1 -1
  173. package/dist/graph/{wardleyDiagram-S7YFUSEH-6D5BKXHM.js → wardleyDiagram-S7YFUSEH-DMMWKJEK.js} +1 -1
  174. package/dist/graph/{xychartDiagram-GGNKY7IX-6ET3ZM67.js → xychartDiagram-GGNKY7IX-K6MUQVXR.js} +1 -1
  175. package/dist/install.sh +68 -0
  176. package/dist/plugins.global.js +62 -62
  177. package/dist/{viewer → server}/assets.d.ts +2 -0
  178. package/dist/server/assets.js +7 -0
  179. package/dist/{viewer → server}/build-plugins.js +4 -4
  180. package/dist/{viewer → server}/build.d.ts +2 -1
  181. package/dist/{viewer → server}/build.js +31 -15
  182. package/dist/{cli.js → server/cli.js} +223 -56
  183. package/dist/server/editor-tools.d.ts +1 -0
  184. package/dist/server/editor-tools.js +1 -0
  185. package/dist/{viewer → server}/extension-pack.js +2 -2
  186. package/dist/{viewer → server}/extensions.d.ts +1 -1
  187. package/dist/{viewer → server}/extensions.js +3 -3
  188. package/dist/server/git-diff.d.ts +10 -0
  189. package/dist/{viewer → server}/git-diff.js +45 -10
  190. package/dist/server/git-origin.d.ts +4 -0
  191. package/dist/server/git-origin.js +103 -0
  192. package/dist/server/git.d.ts +9 -0
  193. package/dist/{viewer → server}/git.js +50 -6
  194. package/dist/server/history.d.ts +14 -0
  195. package/dist/server/history.js +205 -0
  196. package/dist/{viewer → server}/hmr.d.ts +0 -22
  197. package/dist/server/hmr.js +168 -0
  198. package/dist/server/index.d.ts +17 -0
  199. package/dist/{index.js → server/index.js} +16 -16
  200. package/dist/{viewer → server}/ja-lint.d.ts +1 -1
  201. package/dist/{viewer → server}/languages.d.ts +1 -1
  202. package/dist/{viewer → server}/languages.js +3 -3
  203. package/dist/{mcp.d.ts → server/mcp.d.ts} +2 -2
  204. package/dist/{mcp.js → server/mcp.js} +60 -21
  205. package/dist/{viewer → server}/plugin-config.d.ts +2 -2
  206. package/dist/{viewer → server}/plugin-config.js +2 -2
  207. package/dist/{plugins → server/plugins}/local-storage.d.ts +1 -1
  208. package/dist/{plugins → server/plugins}/local-storage.js +1 -1
  209. package/dist/{plugins → server/plugins}/runtime.d.ts +4 -4
  210. package/dist/{plugins → server/plugins}/runtime.js +4 -4
  211. package/dist/{viewer → server}/plugins.d.ts +3 -3
  212. package/dist/{viewer → server}/plugins.js +14 -13
  213. package/dist/server/resource-library.d.ts +1 -0
  214. package/dist/server/resource-library.js +1 -0
  215. package/dist/server/self.d.ts +5 -0
  216. package/dist/server/self.js +98 -0
  217. package/dist/server/serve.d.ts +61 -0
  218. package/dist/server/serve.js +503 -0
  219. package/dist/server/static-client.d.ts +4 -0
  220. package/dist/server/static-client.js +117 -0
  221. package/dist/server/workspace-server.d.ts +16 -0
  222. package/dist/server/workspace-server.js +266 -0
  223. package/dist/{viewer → server}/workspace.d.ts +6 -1
  224. package/dist/{viewer → server}/workspace.js +46 -0
  225. package/dist/subformats.global.js +92 -6
  226. package/dist/ui.global.js +85 -72
  227. package/dist/workspace/client.d.ts +13 -0
  228. package/dist/workspace/client.js +114 -0
  229. package/dist/{viewer → workspace}/code-file.d.ts +1 -1
  230. package/dist/{viewer → workspace}/code-file.js +7 -7
  231. package/dist/workspace/connection.d.ts +27 -0
  232. package/dist/workspace/connection.js +38 -0
  233. package/dist/{viewer → workspace}/editor-tools.d.ts +7 -1
  234. package/dist/{viewer → workspace}/editor-tools.js +12 -9
  235. package/dist/{viewer → workspace}/git-types.d.ts +7 -0
  236. package/dist/workspace/github.d.ts +4 -0
  237. package/dist/workspace/github.js +99 -0
  238. package/dist/workspace/history.d.ts +46 -0
  239. package/dist/workspace/history.js +86 -0
  240. package/dist/workspace/protocol.d.ts +38 -0
  241. package/dist/workspace/protocol.js +20 -0
  242. package/dist/workspace/resource-download.d.ts +1 -0
  243. package/dist/workspace/resource-download.js +8 -0
  244. package/dist/workspace/server.d.ts +9 -0
  245. package/dist/workspace/server.js +48 -0
  246. package/dist/{viewer → workspace}/site-icon.js +9 -10
  247. package/dist/{viewer → workspace}/site-title.js +6 -7
  248. package/dist/{viewer → workspace}/textfile.d.ts +1 -1
  249. package/dist/{viewer → workspace}/textfile.js +5 -5
  250. package/dist/workspace-worker.global.js +2859 -0
  251. package/package.json +43 -21
  252. package/dist/compiler/manifest.js +0 -37
  253. package/dist/compiler/serialize.d.ts +0 -3
  254. package/dist/compiler/serialize.js +0 -16
  255. package/dist/core/icons.js +0 -5
  256. package/dist/graph/chunk-3RNHDNP5.js +0 -1
  257. package/dist/graph/chunk-5UUEAHTN.js +0 -1
  258. package/dist/graph/chunk-6T55RVVR.js +0 -1
  259. package/dist/graph/elk-XV6XMXQE-AZ4HLCWI.js +0 -27
  260. package/dist/graph/flowDiagram-MALGAFMO-2R7EYAQI.js +0 -1
  261. package/dist/graph/infoDiagram-KBXO4MBG-7EHX2GQG.js +0 -2
  262. package/dist/graph/swimlanes-UMQ2AFYF-LDD74Q2S.js +0 -1
  263. package/dist/graph/swimlanesDiagram-OMPLPG4O-ZYULLJSU.js +0 -8
  264. package/dist/index.d.ts +0 -17
  265. package/dist/viewer/assets.js +0 -3
  266. package/dist/viewer/figure-preview.d.ts +0 -4
  267. package/dist/viewer/git-diff.d.ts +0 -6
  268. package/dist/viewer/git.d.ts +0 -5
  269. package/dist/viewer/hmr.js +0 -341
  270. package/dist/viewer/serve.d.ts +0 -216
  271. /package/dist/{compiler → engine/compiler}/asset-references.d.ts +0 -0
  272. /package/dist/{compiler → engine/compiler}/asset-references.js +0 -0
  273. /package/dist/{compiler → engine/compiler}/bundle-urls.d.ts +0 -0
  274. /package/dist/{compiler → engine/compiler}/check-types.d.ts +0 -0
  275. /package/dist/{compiler → engine/compiler}/check-types.js +0 -0
  276. /package/dist/{compiler → engine/compiler}/check.d.ts +0 -0
  277. /package/dist/{compiler → engine/compiler}/code-blocks.d.ts +0 -0
  278. /package/dist/{compiler → engine/compiler}/code-languages.d.ts +0 -0
  279. /package/dist/{compiler → engine/compiler}/config.d.ts +0 -0
  280. /package/dist/{compiler → engine/compiler}/drawio.d.ts +0 -0
  281. /package/dist/{compiler → engine/compiler}/drawio.js +0 -0
  282. /package/dist/{compiler → engine/compiler}/dxf.d.ts +0 -0
  283. /package/dist/{compiler → engine/compiler}/export.d.ts +0 -0
  284. /package/dist/{compiler → engine/compiler}/figures.d.ts +0 -0
  285. /package/dist/{compiler → engine/compiler}/files.d.ts +0 -0
  286. /package/dist/{compiler → engine/compiler}/fonts.d.ts +0 -0
  287. /package/dist/{compiler → engine/compiler}/format.d.ts +0 -0
  288. /package/dist/{compiler → engine/compiler}/format.js +0 -0
  289. /package/dist/{compiler → engine/compiler}/from-mdast.d.ts +0 -0
  290. /package/dist/{compiler → engine/compiler}/language-codes.d.ts +0 -0
  291. /package/dist/{compiler → engine/compiler}/language-codes.js +0 -0
  292. /package/dist/{compiler → engine/compiler}/locales.d.ts +0 -0
  293. /package/dist/{compiler → engine/compiler}/public-file.d.ts +0 -0
  294. /package/dist/{compiler → engine/compiler}/public-file.js +0 -0
  295. /package/dist/{compiler → engine/compiler}/subformat-schema.d.ts +0 -0
  296. /package/dist/{compiler → engine/compiler}/terms.d.ts +0 -0
  297. /package/dist/{compiler → engine/compiler}/terms.js +0 -0
  298. /package/dist/{compiler → engine/compiler}/textfile-remote.d.ts +0 -0
  299. /package/dist/{compiler → engine/compiler}/textfile.d.ts +0 -0
  300. /package/dist/{compiler → engine/compiler}/theme-variants.d.ts +0 -0
  301. /package/dist/{compiler → engine/compiler}/zip.d.ts +0 -0
  302. /package/dist/{core → engine/core}/blocks.js +0 -0
  303. /package/dist/{core → engine/core}/code-file.d.ts +0 -0
  304. /package/dist/{core → engine/core}/code-file.js +0 -0
  305. /package/dist/{core → engine/core}/code-grammars.d.ts +0 -0
  306. /package/dist/{core → engine/core}/code-grammars.js +0 -0
  307. /package/dist/{core → engine/core}/content-types.js +0 -0
  308. /package/dist/{core → engine/core}/escape-html.d.ts +0 -0
  309. /package/dist/{core → engine/core}/escape-html.js +0 -0
  310. /package/dist/{core → engine/core}/extension-package.d.ts +0 -0
  311. /package/dist/{core → engine/core}/extension-package.js +0 -0
  312. /package/dist/{core → engine/core}/figure-frame.d.ts +0 -0
  313. /package/dist/{core → engine/core}/figure-frame.js +0 -0
  314. /package/dist/{core → engine/core}/file-embed.d.ts +0 -0
  315. /package/dist/{core → engine/core}/file-embed.js +0 -0
  316. /package/dist/{core → engine/core}/files.d.ts +0 -0
  317. /package/dist/{core → engine/core}/files.js +0 -0
  318. /package/dist/{core → engine/core}/graph-common.d.ts +0 -0
  319. /package/dist/{core → engine/core}/graph-common.js +0 -0
  320. /package/dist/{core → engine/core}/graph.d.ts +0 -0
  321. /package/dist/{core → engine/core}/graph.js +0 -0
  322. /package/dist/{core → engine/core}/inline.d.ts +0 -0
  323. /package/dist/{core → engine/core}/inline.js +0 -0
  324. /package/dist/{core → engine/core}/json-tools.d.ts +0 -0
  325. /package/dist/{core → engine/core}/json-tools.js +0 -0
  326. /package/dist/{core → engine/core}/language.d.ts +0 -0
  327. /package/dist/{core → engine/core}/language.js +0 -0
  328. /package/dist/{core → engine/core}/languages/ja.d.ts +0 -0
  329. /package/dist/{core → engine/core}/languages/ja.js +0 -0
  330. /package/dist/{core → engine/core}/markdown.d.ts +0 -0
  331. /package/dist/{core → engine/core}/markdown.js +0 -0
  332. /package/dist/{core → engine/core}/previewers.d.ts +0 -0
  333. /package/dist/{core → engine/core}/previewers.js +0 -0
  334. /package/dist/{core → engine/core}/schema-comments.d.ts +0 -0
  335. /package/dist/{core → engine/core}/schema-comments.js +0 -0
  336. /package/dist/{core → engine/core}/schema-fields.d.ts +0 -0
  337. /package/dist/{core → engine/core}/schema-fields.js +0 -0
  338. /package/dist/{core → engine/core}/schema-graph.d.ts +0 -0
  339. /package/dist/{core → engine/core}/schema-graph.js +0 -0
  340. /package/dist/{core → engine/core}/subformat-record.d.ts +0 -0
  341. /package/dist/{core → engine/core}/subformat-record.js +0 -0
  342. /package/dist/{core → engine/core}/term-reference.d.ts +0 -0
  343. /package/dist/{core → engine/core}/term-reference.js +0 -0
  344. /package/dist/{core → engine/core}/textfile.d.ts +0 -0
  345. /package/dist/{core → engine/core}/textfile.js +0 -0
  346. /package/dist/{core → engine/core}/theme-variants.d.ts +0 -0
  347. /package/dist/{core → engine/core}/theme-variants.js +0 -0
  348. /package/dist/{core → engine/core}/workspace.d.ts +0 -0
  349. /package/dist/{core → engine/core}/workspace.js +0 -0
  350. /package/dist/{viewer → frontend}/bundle-network.d.ts +0 -0
  351. /package/dist/{viewer → frontend}/bundle-network.js +0 -0
  352. /package/dist/{core → frontend}/flow-base-css.generated.d.ts +0 -0
  353. /package/dist/{core → frontend}/flow-base-css.generated.js +0 -0
  354. /package/dist/{core → frontend}/flow-css.d.ts +0 -0
  355. /package/dist/{core → frontend}/flow-css.js +0 -0
  356. /package/dist/{viewer → frontend}/font-picker.js +0 -0
  357. /package/dist/{viewer → frontend}/font-settings.js +0 -0
  358. /package/dist/{viewer → frontend}/i18n.d.ts +0 -0
  359. /package/dist/{viewer → frontend}/i18n.js +0 -0
  360. /package/dist/{viewer → frontend}/language-picker.d.ts +0 -0
  361. /package/dist/{viewer → frontend}/lazy-preview.d.ts +0 -0
  362. /package/dist/{viewer → frontend}/lazy-preview.js +0 -0
  363. /package/dist/{viewer → frontend}/nav-focus.d.ts +0 -0
  364. /package/dist/{viewer → frontend}/nav-update.d.ts +0 -0
  365. /package/dist/{viewer → frontend}/nav-update.js +0 -0
  366. /package/dist/{viewer → frontend}/plugin-blocks.d.ts +0 -0
  367. /package/dist/{viewer → frontend}/plugin-style.d.ts +0 -0
  368. /package/dist/{viewer → frontend}/plugin-style.js +0 -0
  369. /package/dist/{viewer → frontend}/plugin-view.d.ts +0 -0
  370. /package/dist/{viewer → frontend}/plugin-view.js +0 -0
  371. /package/dist/{viewer → frontend}/resize.d.ts +0 -0
  372. /package/dist/{core → frontend}/schema-graph-mount.d.ts +0 -0
  373. /package/dist/{core → frontend}/schema-graph-mount.js +0 -0
  374. /package/dist/{core → frontend}/table-ui.d.ts +0 -0
  375. /package/dist/{core → frontend}/table-ui.js +0 -0
  376. /package/dist/{core → frontend}/terms-ui.d.ts +0 -0
  377. /package/dist/{core → frontend}/terms-ui.js +0 -0
  378. /package/dist/{viewer → frontend}/theme-picker.d.ts +0 -0
  379. /package/dist/{viewer → frontend}/theme-picker.js +0 -0
  380. /package/dist/{core → frontend}/toc-ui.d.ts +0 -0
  381. /package/dist/{core → frontend}/toc-ui.js +0 -0
  382. /package/dist/{core → frontend}/video-ui.d.ts +0 -0
  383. /package/dist/{core → frontend}/video-ui.js +0 -0
  384. /package/dist/graph/{chunk-GYT4IYBZ.js → chunk-RJFVWYCA.js} +0 -0
  385. /package/dist/{viewer → server}/build-plugins.d.ts +0 -0
  386. /package/dist/{cli.d.ts → server/cli.d.ts} +0 -0
  387. /package/dist/{viewer → server}/extension-pack.d.ts +0 -0
  388. /package/dist/{viewer → server}/fonts/LICENSE.txt +0 -0
  389. /package/dist/{viewer → server}/fonts/udev-gothic-regular.woff2 +0 -0
  390. /package/dist/{viewer → server}/fonts.d.ts +0 -0
  391. /package/dist/{viewer → server}/fonts.js +0 -0
  392. /package/dist/{viewer → server}/ja-lint.js +0 -0
  393. /package/dist/{viewer → workspace}/git-types.js +0 -0
  394. /package/dist/{viewer → workspace}/site-icon.d.ts +0 -0
  395. /package/dist/{viewer → workspace}/site-title.d.ts +0 -0
@@ -1,415 +1,417 @@
1
- import { completeFilePaths, filesSnapshot, updateFiles, uploadFile } from "../compiler/files.js";
2
- import { loadProjectFonts } from "../compiler/fonts.js";
3
- import { textfilePath, writeTextfile } from "../compiler/textfile.js";
4
- import { defaultFilePath, docIconFile, MAX_FILE_UPLOAD_BYTES, parseFileLayout, docFile as sourceDocFile, suggestDocFileName, } from "../core/files.js";
5
- // The local server itself (shared by preview / edit). Files are re-read on every request, so a
6
- // change is always reflected on the next request. HMR (hmr.ts) triggers that "next request"
7
- // automatically: content changes are pushed over SSE and preview swaps just the main body, while
8
- // src/*.ts changes cause a tsx watch restart → reconnect → reload (= no manual reload or restart
9
- // needed). Rendering goes through the same "mdast → Block AST → HTML" pipeline as the build.
10
- // Dialect validation errors are shown at the top of the page.
11
- // preview = read-only view
12
- // edit = left = live render of the body / right = front-matter form + insert palette +
13
- // CodeMirror (`dooc edit`). The save API rewrites content/<id>.md directly,
14
- // and hierarchy changes (create / move / rename / delete) rewrite
15
- // dooc.yaml.
16
- // The client (src/viewer/edit-client.ts) is bundled in memory with esbuild on
17
- // first request (cached) and served.
18
- import { createHash } from "node:crypto";
19
- import { existsSync, mkdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
20
- import { createServer } from "node:http";
21
- import { basename, dirname, join, resolve } from "node:path";
22
- import { fileURLToPath } from "node:url";
23
- import { parseContentSource } from "../compiler/code-blocks.js";
24
- import { compileDraft, createCompiler, } from "../compiler/compile.js";
25
- import { figureName } from "../compiler/figures.js";
26
- import { ICONS_DIR, squareSvg } from "../compiler/icons.js";
27
- import { ignoredFiles, withIgnoredFilesCache } from "../compiler/ignored-files.js";
28
- import { contentLanguageCode, contentLanguages, isContentLanguage, webLanguage, } from "../compiler/language-codes.js";
29
- import { setDocTranslation, siteContentLanguages, translationFile, translationFiles, } from "../compiler/locales.js";
30
- import { readManifest, writeManifest } from "../compiler/manifest.js";
31
- import { assembleDoc, createDocOps, isOpError } from "../compiler/ops.js";
32
- import { subformatResponse, validateSubformatFile } from "../compiler/subformats.js";
33
- import { walkBlocks } from "../core/blocks.js";
34
- import { selectCodeGrammars, subformatCodeGrammars } from "../core/code-grammars.js";
35
- import { docIdOfFile, flattenTree } from "../core/content-metadata.js";
36
- import { MAX_EXTENSION_BYTES } from "../core/extension-package.js";
37
- import { figureFrameHtml, mountFigureFrames } from "../core/figure-frame.js";
38
- import { blocksHtml, docHtml, escapeHtml, termsHtml } from "../core/html.js";
39
- import { FOLDER_ICON_PATH, PLUGINS_ICON } from "../core/icons.js";
40
- import { DEFAULT_LANG, isLangTag, resolveLanguage, } from "../core/language.js";
41
- import { defaultPreviewSettings, parsePreviewSettings, } from "../core/previewers.js";
42
- import { ancestorsOf, childrenOf, docPath, resolveDocPath } from "../core/routing.js";
43
- import { mountTables } from "../core/table-ui.js";
44
- import { CODE_LANGS, docDisplayName } from "../core/taxonomy.js";
45
- import { isTermFile, termAnchor, termFileUrl } from "../core/term-reference.js";
46
- import { mountTerms } from "../core/terms-ui.js";
47
- import { isRemoteTextfile, textfileName } from "../core/textfile.js";
48
- import { mountThemeVariants } from "../core/theme-variants.js";
49
- import { mountToc } from "../core/toc-ui.js";
50
- import { mountVideos } from "../core/video-ui.js";
51
- import { parseWorkspaceSource, workspaceLabel } from "../core/workspace.js";
52
- import { createLocalPluginStorage } from "../plugins/local-storage.js";
53
- import { readViewerAsset, prebuilt as usePrebuiltAssets } from "./assets.js";
1
+ import { parseContentSource } from "../engine/compiler/code-blocks.js";
2
+ import { compileDraft, createCompiler, } from "../engine/compiler/compile.js";
3
+ import { figureName } from "../engine/compiler/figures.js";
4
+ import { filesSnapshot, updateFiles } from "../engine/compiler/files.js";
5
+ import { loadProjectFonts } from "../engine/compiler/fonts.js";
6
+ import { createHash, dirname, existsSync, join, mkdirSync, readFileSync, statSync, unlinkSync, writeFileSync, } from "../engine/compiler/host.js";
7
+ import { ICONS_DIR, ownsDocIcon, squareSvg } from "../engine/compiler/icons.js";
8
+ import { ignoredFiles, withIgnoredFilesCache } from "../engine/compiler/ignored-files.js";
9
+ import { contentLanguageCode, contentLanguages, isContentLanguage, webLanguage, } from "../engine/compiler/language-codes.js";
10
+ import { setDocTranslation, siteContentLanguages, translationFile, translationFiles, } from "../engine/compiler/locales.js";
11
+ import { readManifest, writeManifest } from "../engine/compiler/manifest.js";
12
+ import { assembleDoc, createDocOps, isOpError, } from "../engine/compiler/ops.js";
13
+ import { subformatResponse, validateSubformatFile } from "../engine/compiler/subformats.js";
14
+ import { textfilePath, writeTextfile } from "../engine/compiler/textfile.js";
15
+ import { walkBlocks } from "../engine/core/blocks.js";
16
+ import { selectCodeGrammars, subformatCodeGrammars } from "../engine/core/code-grammars.js";
17
+ import { docIdOfFile, flattenTree } from "../engine/core/content-metadata.js";
18
+ import { figureFrameHtml, mountFigureFrames } from "../engine/core/figure-frame.js";
19
+ import { defaultFilePath, docIconFile, parseFileLayout, docFile as sourceDocFile, suggestDocFileName, } from "../engine/core/files.js";
20
+ import { blocksHtml, docHtml, escapeHtml, resourceDownloadHtml, termsHtml, } from "../engine/core/html.js";
21
+ import { FOLDER_ICON_PATH, LIBRARY_ICONS, libraryIcon, PLUGINS_ICON, } from "../engine/core/icons.js";
22
+ import { DEFAULT_LANG, isLangTag, resolveLanguage, } from "../engine/core/language.js";
23
+ import { ja } from "../engine/core/languages/ja.js";
24
+ import { defaultPreviewSettings } from "../engine/core/previewers.js";
25
+ import { ancestorsOf, childrenOf, docPath, resolveDocPath } from "../engine/core/routing.js";
26
+ import { CODE_LANGS, CODE_TEMPLATES, docDisplayName, } from "../engine/core/taxonomy.js";
27
+ import { isTermFile, termAnchor, termFileUrl } from "../engine/core/term-reference.js";
28
+ import { isRemoteTextfile, textfileName } from "../engine/core/textfile.js";
29
+ import { mountThemeVariants } from "../engine/core/theme-variants.js";
30
+ import { workspaceLabel } from "../engine/core/workspace.js";
31
+ import { codeFileResponse } from "../workspace/code-file.js";
32
+ import { workspaceFetch } from "../workspace/connection.js";
33
+ import { readDownloadFile } from "../workspace/resource-download.js";
34
+ import { siteIconResponse } from "../workspace/site-icon.js";
35
+ import { siteTitleResponse } from "../workspace/site-title.js";
36
+ import { previewTextfiles, textfileResponse } from "../workspace/textfile.js";
54
37
  import { mountBundleNetwork } from "./bundle-network.js";
55
- import { codeFileResponse } from "./code-file.js";
56
- import { isLocalToolRequest, runCodeTool, validateCodeTools, validateTextfileCode, } from "./editor-tools.js";
57
- import { createExtensionManager, EXTENSIONS_DIR } from "./extensions.js";
58
38
  import { deferredFigureHtml, mountFigurePreviews } from "./figure-preview.js";
59
39
  import { fileReferences } from "./file-references.js";
60
40
  import { mountFontPickers } from "./font-picker.js";
61
41
  import { createFontSettings } from "./font-settings.js";
62
- import { fontCss, readFont } from "./fonts.js";
63
- import { createGitHandler, validateGitOrigin } from "./git.js";
64
- import { gitBaseBody, gitBaseText, setSubformatChanges } from "./git-diff.js";
65
- import { createHmrHub, HMR_PATH, hmrClientScript, watchProject } from "./hmr.js";
66
42
  import { translate } from "./i18n.js";
67
- import { DEFAULT_SITE_LANGUAGES, loadSiteLanguages } from "./languages.js";
68
43
  import { loadPreviewScript } from "./lazy-preview.js";
69
44
  import { focusNavTree } from "./nav-focus.js";
70
45
  import { updateNav } from "./nav-update.js";
71
- import { loadViewerPlugins } from "./plugin-config.js";
72
46
  import { PLUGIN_BLOCK_CSS } from "./plugin-style.js";
73
- import { createPluginHandler } from "./plugins.js";
74
47
  import { mountPanelResize } from "./resize.js";
75
- import { resourceIndex, resourceLibraryHtml, resourceTabs } from "./resource-library.js";
48
+ import { mountResourceDownloads } from "./resource-download.js";
49
+ import { libraryPageHtml, resourceIndex, resourceLibraryHtml, resourceTabs, } from "./resource-library.js";
76
50
  import { mountSearch, SEARCH_LABELS, searchIndex, searchSections } from "./search.js";
77
- import { siteIconResponse } from "./site-icon.js";
78
- import { siteTitleResponse } from "./site-title.js";
79
- import { previewTextfiles, textfileResponse } from "./textfile.js";
51
+ import { mountTables } from "./table-ui.js";
52
+ import { mountTerms } from "./terms-ui.js";
80
53
  import { initializeThemes, mountThemePickers } from "./theme-picker.js";
81
- import { readWorkspaceSource, sourceFileBase } from "./workspace.js";
82
- // pkgRoot = the viewer itself (src/ for the client bundles). docsRoot = the docs folder that
83
- // follows the layout convention (content/ figures/).
84
- const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
85
- const root = resolve(process.env.DOCS_ROOT ?? process.cwd());
86
- const CONTENT_PREFIX = "content/";
87
- const toEntry = (doc, source) => ({
88
- id: doc.id,
89
- ...(doc.subformat ? { subformat: doc.subformat } : {}),
90
- ...(doc.parent == null ? {} : { parent: doc.parent }),
91
- file: `${doc.id}.md`,
92
- sourceFile: doc.file,
93
- frontmatter: source.frontmatter,
94
- lang: doc.lang,
95
- body: doc.body,
96
- blocks: doc.blocks,
97
- toc: doc.toc,
98
- blockLines: source.lines,
99
- raw: source.raw,
100
- errors: source.errors,
101
- ...(doc.icon == null ? {} : { icon: doc.icon }),
102
- figureRefs: doc.refs.figures,
103
- termRefs: doc.refs.terms,
104
- terms: source.terms,
105
- referencedFiles: source.referencedFiles,
106
- });
107
- // Recompile source files on every request. The compiler's cache
108
- // skips re-parsing files unchanged on disk, so it stays cheap even when called on every keystroke
109
- // (POST /api/render). Replaced in startServer once docs.config.mjs (language adapters)
110
- // has been loaded.
111
- let siteLanguages = DEFAULT_SITE_LANGUAGES;
112
- let compiler = createCompiler(root);
113
- const ops = createDocOps(root);
114
- /** Compile result → viewer Site (shared by the server's per-request path and one-off publish). */
115
- export const siteFrom = ({ title, icon, iconVariants, docs, terms, figures, sources, siteErrors, defaultLang, previews, contentLanguages, themes, subformats, }, languages = DEFAULT_SITE_LANGUAGES.languages, code = {}) => {
116
- return {
117
- previews,
118
- subformats,
119
- codeLanguages: [
120
- ...new Set([
121
- ...(code.codeLanguages ?? CODE_LANGS),
122
- ...(subformats ?? []).map(({ ext }) => `.${ext}`),
123
- ]),
124
- ],
125
- codeGrammars: subformatCodeGrammars(code.codeGrammars ?? [], subformats),
126
- ...(contentLanguages ? { contentLanguages } : {}),
127
- ...(themes ? { themes } : {}),
128
- ...(title === undefined ? {} : { title }),
129
- ...(icon === undefined ? {} : { icon }),
130
- ...(iconVariants === undefined ? {} : { iconVariants }),
131
- entries: docs.flatMap((doc) => {
132
- const source = sources.get(doc.file);
133
- return source ? [toEntry(doc, source)] : [];
134
- }),
135
- ctx: {
136
- docLinks: new Map(docs.map((doc) => [doc.file, docPath(docs, doc.id)])),
137
- figures: new Map(figures.map((f) => [f.name, f])),
138
- terms,
139
- termLinks: new Map([
140
- ...terms.map((term) => [
141
- term.id,
142
- `/_files/terms#${encodeURIComponent(termAnchor(term.id))}`,
54
+ import { mountToc } from "./toc-ui.js";
55
+ import { mountVideos } from "./video-ui.js";
56
+ const DEFAULT_SITE_LANGUAGES = { languages: [ja] };
57
+ export const createDocumentApplication = (root, host) => {
58
+ const { fontCss, readWorkspaceSource, sourceFileBase, gitBaseBody, gitBaseText, setSubformatChanges, runCodeTool, validateCodeTools, validateTextfileCode, } = host;
59
+ const CONTENT_PREFIX = "content/";
60
+ const toEntry = (doc, source) => ({
61
+ id: doc.id,
62
+ ...(doc.subformat ? { subformat: doc.subformat } : {}),
63
+ ...(doc.library ? { library: doc.library } : {}),
64
+ ...(doc.parent == null ? {} : { parent: doc.parent }),
65
+ file: `${doc.id}.md`,
66
+ sourceFile: doc.file,
67
+ frontmatter: source.frontmatter,
68
+ lang: doc.lang,
69
+ body: doc.body,
70
+ blocks: doc.blocks,
71
+ toc: doc.toc,
72
+ blockLines: source.lines,
73
+ raw: source.raw,
74
+ errors: source.errors,
75
+ ...(doc.icon == null ? {} : { icon: doc.icon }),
76
+ figureRefs: doc.refs.figures,
77
+ termRefs: doc.refs.terms,
78
+ terms: source.terms,
79
+ referencedFiles: source.referencedFiles,
80
+ });
81
+ // Recompile source files on every request. The compiler's cache
82
+ // skips re-parsing files unchanged on disk, so it stays cheap even when called on every keystroke
83
+ // (POST /api/render). Replaced in startServer once docs.config.mjs (language adapters)
84
+ // has been loaded.
85
+ let siteLanguages = DEFAULT_SITE_LANGUAGES;
86
+ let compiler = createCompiler(root);
87
+ const ops = createDocOps(root);
88
+ /** Compile result → viewer Site (shared by the server's per-request path and one-off publish). */
89
+ const siteFrom = ({ title, icon, iconVariants, docs, terms, figures, sources, siteErrors, defaultLang, previews, contentLanguages, themes, subformats, }, languages = DEFAULT_SITE_LANGUAGES.languages, code = {}) => {
90
+ return {
91
+ previews,
92
+ subformats,
93
+ codeLanguages: [
94
+ ...new Set([
95
+ ...(code.codeLanguages ?? CODE_LANGS),
96
+ ...(subformats ?? []).map(({ ext }) => `.${ext}`),
143
97
  ]),
144
- ...docs.flatMap((doc) => doc.blocks.flatMap((block) => block.type === "term"
145
- ? [
146
- [
147
- block.entry.id,
148
- `/${doc.id}#${encodeURIComponent(termAnchor(block.entry.id))}`,
149
- ],
150
- ]
151
- : [])),
152
- ]),
153
- },
154
- errors: siteErrors,
155
- languages,
156
- defaultLang,
98
+ ],
99
+ codeGrammars: subformatCodeGrammars(code.codeGrammars ?? [], subformats),
100
+ ...(contentLanguages ? { contentLanguages } : {}),
101
+ ...(themes ? { themes } : {}),
102
+ ...(title === undefined ? {} : { title }),
103
+ ...(icon === undefined ? {} : { icon }),
104
+ ...(iconVariants === undefined ? {} : { iconVariants }),
105
+ entries: docs.flatMap((doc) => {
106
+ const source = sources.get(doc.file);
107
+ return source ? [toEntry(doc, source)] : [];
108
+ }),
109
+ ctx: {
110
+ docLinks: new Map(docs.map((doc) => [doc.file, docPath(docs, doc.id)])),
111
+ figures: new Map(figures.map((f) => [f.name, f])),
112
+ terms,
113
+ termLinks: new Map([
114
+ ...terms.map((term) => [
115
+ term.id,
116
+ `/_files/terms#${encodeURIComponent(termAnchor(term.id))}`,
117
+ ]),
118
+ ...docs.flatMap((doc) => doc.blocks.flatMap((block) => block.type === "term"
119
+ ? [
120
+ [
121
+ block.entry.id,
122
+ `/${doc.id}#${encodeURIComponent(termAnchor(block.entry.id))}`,
123
+ ],
124
+ ]
125
+ : [])),
126
+ ]),
127
+ },
128
+ errors: siteErrors,
129
+ languages,
130
+ defaultLang,
131
+ };
157
132
  };
158
- };
159
- const localeCompilers = new Map();
160
- let workspaceSource;
161
- let applicationPreviews = defaultPreviewSettings();
162
- let watchTextfiles;
163
- const watchEntryTextfiles = (entries) => {
164
- watchTextfiles?.(entries
165
- .filter((entry) => !entry.subformat)
166
- .flatMap((entry) => [
167
- entry.sourceFile ?? CONTENT_PREFIX + entry.file,
168
- ...(entry.referencedFiles ?? []),
169
- ]));
170
- };
171
- const loadSite = (locale) => withIgnoredFilesCache(() => {
172
- const previews = applicationPreviews;
173
- const manifest = readManifest(root);
174
- const source = contentLanguageCode(manifest.defaultLang ?? DEFAULT_LANG);
175
- locale ??= source;
176
- let selected = compiler;
177
- if (locale !== source) {
178
- selected = localeCompilers.get(locale) ?? createCompiler(root, { locale, previews });
179
- localeCompilers.set(locale, selected);
180
- }
181
- const site = siteFrom(selected.compile(), siteLanguages.languages, siteLanguages);
182
- const sourceLanguage = contentLanguageCode(site.defaultLang);
183
- for (const entry of site.entries) {
184
- entry.translatedLanguages = [sourceLanguage];
185
- entry.iconFile = docIconFile(entry.id, manifest.files);
186
- }
187
- try {
188
- const translated = new Set(translationFiles(root));
189
- for (const language of siteContentLanguages(root, manifest).filter((language) => language !== sourceLanguage)) {
190
- for (const entry of site.entries) {
191
- if (translated.has(translationFile(sourceDocFile(entry.id, manifest.files), language)))
192
- entry.translatedLanguages?.push(language);
193
- }
194
- }
195
- }
196
- catch (error) {
197
- site.errors.push(String(error));
198
- }
199
- watchEntryTextfiles(site.entries);
200
- watchTextfiles?.([manifest.icon, ...Object.values(manifest.themeIcons ?? {})].filter((file) => !!file));
201
- const workspace = workspaceSource ?? readWorkspaceSource(root);
202
- const subformats = site.entries.flatMap((entry) => entry.subformat ? [entry.subformat] : []);
203
- if (workspace?.protocol === "git" && subformats.length)
204
- setSubformatChanges(root, subformats);
205
- return {
206
- ...site,
207
- ctx: { ...site.ctx, figurePreview: deferredFigureHtml },
208
- fonts: loadProjectFonts(root),
209
- workspace,
210
- sourceBase: sourceFileBase(root),
211
- filePaths: manifest.errors.length
212
- ? undefined
213
- : filesSnapshot(root).files.map((file) => file.path),
214
- contentLanguage: locale,
133
+ const localeCompilers = new Map();
134
+ // Set by startServer; pages hide branch-level Git while it is defined.
135
+ let sharedBranch;
136
+ let editDownloads = false;
137
+ let workspaceSource;
138
+ let applicationPreviews = defaultPreviewSettings();
139
+ let watchTextfiles;
140
+ const watchEntryTextfiles = (entries) => {
141
+ watchTextfiles?.(entries
142
+ .filter((entry) => !entry.subformat && !entry.library)
143
+ .flatMap((entry) => [
144
+ entry.sourceFile ?? CONTENT_PREFIX + entry.file,
145
+ ...(entry.referencedFiles ?? []),
146
+ ]));
215
147
  };
216
- });
217
- const draftContext = (site) => ({
218
- previews: site.previews,
219
- root,
220
- docs: site.entries
221
- .filter((e) => !e.subformat)
222
- .map((e) => ({
223
- id: e.id,
224
- ...(e.parent == null ? {} : { parent: e.parent }),
225
- file: e.sourceFile ?? CONTENT_PREFIX + e.file,
226
- toc: e.toc,
227
- })),
228
- figures: site.ctx.figures,
229
- defaultLang: site.defaultLang,
230
- });
231
- // fallbackTitle stands in for the h1 when frontmatter is missing. Each doc renders with its own
232
- // language's adapter (term ordering) and `<article lang>`.
233
- const docLinks = (site, html) => html.replace(/href="\/([a-z0-9][a-z0-9-]*)(?=["?#])/g, (whole, id) => site.entries.some((entry) => entry.id === id)
234
- ? `href="${docPath(site.entries, id)}`
235
- : whole);
236
- const renderEntry = (site, entry, fallbackTitle) => docLinks(site, docHtml(entry.frontmatter ?? { title: fallbackTitle }, entry.blocks, [...site.errors, ...entry.errors], {
237
- ...site.ctx,
238
- terms: entry.terms ?? site.ctx.terms,
239
- lang: webLanguage(entry.lang),
240
- tocTitle: translate(entry.lang, "Contents"),
241
- sectionUrl: `${docPath(site.entries, entry.id)}?lang=${encodeURIComponent(site.contentLanguage ?? entry.lang)}`,
242
- language: resolveLanguage(entry.lang, site.languages),
243
- }, entry.toc));
244
- /** Compiles one source (unsaved or on disk; file = `<id>.md`) in the site context into an Entry. */
245
- const draftEntry = (site, file, raw, textfiles) => {
246
- const known = site.entries.find((entry) => entry.file === file);
247
- const { doc, source } = compileDraft({ ...draftContext(site), defaultLang: known?.lang ?? site.defaultLang, textfiles }, known?.sourceFile ?? CONTENT_PREFIX + file, raw);
248
- const entry = toEntry(doc, source);
249
- watchEntryTextfiles([entry]);
250
- return entry;
251
- };
252
- export const filePreviewResults = (entry, site) => {
253
- const results = new Map();
254
- const bodyOffset = entry.raw.slice(0, entry.raw.length - entry.body.length).split("\n").length - 1;
255
- for (const { line, file, kind } of fileReferences(entry.body, site.previews)) {
256
- const errors = results.get(file) ?? [];
257
- errors.push(...entry.errors.filter((error) => error.startsWith(`L${bodyOffset + line}:`)));
258
- if (kind === "term") {
259
- errors.push(...entry.errors.filter((error) => error.startsWith(`${file}:`)));
260
- }
261
- else if (kind === "textfile") {
262
- errors.push(...entry.errors.filter((error) => error.startsWith(`${file}:`)));
263
- for (const block of walkBlocks(entry.blocks)) {
264
- if (block.type !== "code" || block.filename?.replace(/^(\.\/)+/, "") !== file)
265
- continue;
266
- if (block.unavailable)
267
- errors.push(block.unavailable === "missing"
268
- ? "File not found"
269
- : "File could not be loaded");
270
- errors.push(...entry.errors.filter((error) => error.startsWith(`${block.filename}${block.range ?? ""}:`)));
148
+ const loadSite = (locale) => withIgnoredFilesCache(() => {
149
+ const previews = applicationPreviews;
150
+ const manifest = readManifest(root);
151
+ const source = contentLanguageCode(manifest.defaultLang ?? DEFAULT_LANG);
152
+ locale ??= source;
153
+ let selected = compiler;
154
+ if (locale !== source) {
155
+ selected =
156
+ localeCompilers.get(locale) ?? createCompiler(root, { locale, previews });
157
+ localeCompilers.set(locale, selected);
158
+ }
159
+ const site = siteFrom(selected.compile(), siteLanguages.languages, siteLanguages);
160
+ const sourceLanguage = contentLanguageCode(site.defaultLang);
161
+ for (const entry of site.entries) {
162
+ entry.translatedLanguages = [sourceLanguage];
163
+ entry.iconFile = docIconFile(entry.id, manifest.files);
164
+ }
165
+ try {
166
+ const translated = new Set(translationFiles(root));
167
+ for (const language of siteContentLanguages(root, manifest).filter((language) => language !== sourceLanguage)) {
168
+ for (const entry of site.entries) {
169
+ if (translated.has(translationFile(sourceDocFile(entry.id, manifest.files), language)))
170
+ entry.translatedLanguages?.push(language);
171
+ }
271
172
  }
272
173
  }
273
- else {
274
- if (site.ctx.figures.get(figureName(file))?.file !== file)
275
- errors.push("File not found");
276
- errors.push(...site.errors.filter((error) => error.startsWith(`${file}:`)));
174
+ catch (error) {
175
+ site.errors.push(String(error));
277
176
  }
278
- results.set(file, [...new Set(errors)]);
279
- }
280
- return Object.fromEntries(results);
281
- };
282
- // Render the raw being edited (unsaved draft) to body html — shared by the save / render APIs.
283
- const entryGitBase = (entry, site) => site.workspace?.protocol === "git"
284
- ? gitBaseBody(root, entry.sourceFile ?? CONTENT_PREFIX + entry.file)
285
- : null;
286
- const renderDraft = (site, file, raw, textfiles) => {
287
- const entry = draftEntry(site, file, raw, textfiles);
288
- return {
289
- gitBase: entryGitBase(entry, site),
290
- sourceFile: entry.sourceFile,
291
- html: renderEntry(site, entry, ""),
292
- errors: [...site.errors, ...entry.errors],
293
- toc: entry.toc,
294
- blockLines: entry.blockLines,
295
- filePreviews: filePreviewResults(entry, site),
177
+ watchEntryTextfiles(site.entries);
178
+ watchTextfiles?.([manifest.icon, ...Object.values(manifest.themeIcons ?? {})].filter((file) => !!file));
179
+ const workspace = workspaceSource ?? readWorkspaceSource(root);
180
+ const subformats = site.entries.flatMap((entry) => entry.subformat ? [entry.subformat] : []);
181
+ const snapshot = manifest.errors.length ? undefined : filesSnapshot(root);
182
+ if (workspace?.protocol === "git" && subformats.length)
183
+ setSubformatChanges(root, subformats, snapshot?.revision);
184
+ return {
185
+ ...site,
186
+ ctx: {
187
+ ...site.ctx,
188
+ figurePreview: deferredFigureHtml,
189
+ ...(editDownloads
190
+ ? {
191
+ downloads: new Map((snapshot?.files ?? []).map(({ path }) => [
192
+ path,
193
+ `/api/download?file=${encodeURIComponent(path)}`,
194
+ ])),
195
+ }
196
+ : {}),
197
+ },
198
+ fonts: loadProjectFonts(root),
199
+ workspace,
200
+ sourceBase: sourceFileBase(root),
201
+ filePaths: snapshot?.files.map((file) => file.path),
202
+ contentLanguage: locale,
203
+ };
204
+ });
205
+ const draftContext = (site) => ({
296
206
  previews: site.previews,
207
+ root,
208
+ docs: site.entries
209
+ .filter((e) => !e.subformat && !e.library)
210
+ .map((e) => ({
211
+ id: e.id,
212
+ ...(e.parent == null ? {} : { parent: e.parent }),
213
+ file: e.sourceFile ?? CONTENT_PREFIX + e.file,
214
+ toc: e.toc,
215
+ ...(e.frontmatter ? { title: e.frontmatter.title } : {}),
216
+ })),
217
+ figures: site.ctx.figures,
218
+ defaultLang: site.defaultLang,
219
+ });
220
+ // fallbackTitle stands in for the h1 when frontmatter is missing. Each doc renders with its own
221
+ // language's adapter (term ordering) and `<article lang>`.
222
+ const docLinks = (site, html) => html.replace(/href="\/([a-z0-9][a-z0-9-]*)(?=["?#])/g, (whole, id) => site.entries.some((entry) => entry.id === id)
223
+ ? `href="${docPath(site.entries, id)}`
224
+ : whole);
225
+ /** Easy download offers the page's own Markdown beside its title. */
226
+ const pageDownload = (site, entry) => {
227
+ const file = entry.sourceFile ?? CONTENT_PREFIX + entry.file;
228
+ const href = site.ctx.downloads?.get(file);
229
+ return href ? { pageDownload: { file, href } } : {};
297
230
  };
298
- };
299
- // Render result cache — opening the same doc repeatedly (page GET / nav switch) doesn't re-render.
300
- // The compiler's cache returns the same blocks reference while disk is unchanged, so check that,
301
- // plus that the id list (affects document file link resolution) / terms / figures / errors haven't
302
- // changed. Rebuild if any of them did.
303
- const renderSignature = (site, entry) => JSON.stringify([site.ctx.terms, site.errors, entry.errors, entry.frontmatter, entry.lang]) +
304
- site.entries
305
- .map((e) => [e.sourceFile ?? CONTENT_PREFIX + e.file, docPath(site.entries, e.id)])
306
- .sort()
307
- .join("\n");
308
- const entryHtmlCache = new Map();
309
- /** Renders only the requested doc, not every doc in site.entries. */
310
- export const renderEntryHtml = (site, entry) => {
311
- if (entry.subformat)
231
+ const renderEntry = (site, entry, fallbackTitle) => docLinks(site, docHtml(entry.frontmatter ?? { title: fallbackTitle }, entry.blocks, [...site.errors, ...entry.errors], {
232
+ ...site.ctx,
233
+ ...pageDownload(site, entry),
234
+ terms: entry.terms ?? site.ctx.terms,
235
+ lang: webLanguage(entry.lang),
236
+ tocTitle: translate(entry.lang, "Contents"),
237
+ sectionUrl: `${docPath(site.entries, entry.id)}?lang=${encodeURIComponent(site.contentLanguage ?? entry.lang)}`,
238
+ language: resolveLanguage(entry.lang, site.languages),
239
+ }, entry.toc));
240
+ /** Compiles one source (unsaved or on disk; file = `<id>.md`) in the site context into an Entry. */
241
+ const draftEntry = (site, file, raw, textfiles) => {
242
+ const known = site.entries.find((entry) => entry.file === file);
243
+ const { doc, source } = compileDraft({ ...draftContext(site), defaultLang: known?.lang ?? site.defaultLang, textfiles }, known?.sourceFile ?? CONTENT_PREFIX + file, raw);
244
+ const entry = toEntry(doc, source);
245
+ watchEntryTextfiles([entry]);
246
+ return entry;
247
+ };
248
+ const filePreviewResults = (entry, site) => {
249
+ const results = new Map();
250
+ const bodyOffset = entry.raw.slice(0, entry.raw.length - entry.body.length).split("\n").length - 1;
251
+ for (const { line, file, kind } of fileReferences(entry.body, site.previews)) {
252
+ const errors = results.get(file) ?? [];
253
+ errors.push(...entry.errors.filter((error) => error.startsWith(`L${bodyOffset + line}:`)));
254
+ if (kind === "term") {
255
+ errors.push(...entry.errors.filter((error) => error.startsWith(`${file}:`)));
256
+ }
257
+ else if (kind === "textfile") {
258
+ errors.push(...entry.errors.filter((error) => error.startsWith(`${file}:`)));
259
+ for (const block of walkBlocks(entry.blocks)) {
260
+ if (block.type !== "code" || block.filename?.replace(/^(\.\/)+/, "") !== file)
261
+ continue;
262
+ if (block.unavailable)
263
+ errors.push(block.unavailable === "missing"
264
+ ? "File not found"
265
+ : "File could not be loaded");
266
+ errors.push(...entry.errors.filter((error) => error.startsWith(`${block.filename}${block.range ?? ""}:`)));
267
+ }
268
+ }
269
+ else {
270
+ if (site.ctx.figures.get(figureName(file))?.file !== file)
271
+ errors.push("File not found");
272
+ errors.push(...site.errors.filter((error) => error.startsWith(`${file}:`)));
273
+ }
274
+ results.set(file, [...new Set(errors)]);
275
+ }
276
+ return Object.fromEntries(results);
277
+ };
278
+ // Render the raw being edited (unsaved draft) to body html — shared by the save / render APIs.
279
+ const entryGitBase = (entry, site) => site.workspace?.protocol === "git"
280
+ ? gitBaseBody(root, entry.sourceFile ?? CONTENT_PREFIX + entry.file)
281
+ : null;
282
+ const renderDraft = (site, file, raw, textfiles) => {
283
+ const entry = draftEntry(site, file, raw, textfiles);
312
284
  return {
313
- html: `<article class="res-page resource-library subformat-page">${resourceLibraryHtml({
314
- codeblocks: [],
315
- urls: [],
316
- urlPreviews: [],
317
- subformats: [entry.subformat],
318
- errors: [...site.errors, ...entry.errors],
319
- }, "subformats", docDisplayName(entry.frontmatter, entry.id))}</article>`,
285
+ gitBase: entryGitBase(entry, site),
286
+ sourceFile: entry.sourceFile,
287
+ html: renderEntry(site, entry, ""),
320
288
  errors: [...site.errors, ...entry.errors],
289
+ toc: entry.toc,
290
+ blockLines: entry.blockLines,
291
+ filePreviews: filePreviewResults(entry, site),
292
+ previews: site.previews,
321
293
  };
322
- const sig = renderSignature(site, entry);
323
- const cached = entryHtmlCache.get(entry.file);
324
- if (cached &&
325
- cached.blocks === entry.blocks &&
326
- cached.sig === sig &&
327
- cached.figures === site.ctx.figures &&
328
- cached.figurePreview === site.ctx.figurePreview) {
329
- return cached.value;
330
- }
331
- const value = {
332
- html: renderEntry(site, entry, entry.id),
333
- errors: [...site.errors, ...entry.errors],
334
294
  };
335
- entryHtmlCache.set(entry.file, {
336
- blocks: entry.blocks,
337
- sig,
338
- figures: site.ctx.figures,
339
- figurePreview: site.ctx.figurePreview,
340
- value,
341
- });
342
- return value;
343
- };
344
- /** Compiles + renders one source (its current content on disk) (implements `/api/doc`). */
345
- export const renderDocFile = (site, file, raw) => {
346
- const entry = draftEntry(site, file, raw);
347
- return {
348
- gitBase: entryGitBase(entry, site),
349
- sourceFile: entry.sourceFile,
350
- raw,
351
- frontmatter: entry.frontmatter,
352
- body: entry.body,
353
- html: renderEntry(site, entry, ""),
354
- errors: [...site.errors, ...entry.errors],
355
- toc: entry.toc,
356
- blockLines: entry.blockLines,
357
- filePreviews: filePreviewResults(entry, site),
358
- previews: site.previews,
295
+ // Render result cache — opening the same doc repeatedly (page GET / nav switch) doesn't re-render.
296
+ // The compiler's cache returns the same blocks reference while disk is unchanged, so check that,
297
+ // plus that the id list (affects document file link resolution) / terms / figures / errors haven't
298
+ // changed. Rebuild if any of them did.
299
+ const renderSignature = (site, entry) => JSON.stringify([site.ctx.terms, site.errors, entry.errors, entry.frontmatter, entry.lang]) +
300
+ site.entries
301
+ .map((e) => [e.sourceFile ?? CONTENT_PREFIX + e.file, docPath(site.entries, e.id)])
302
+ .sort()
303
+ .join("\n");
304
+ const entryHtmlCache = new Map();
305
+ /** Renders only the requested doc, not every doc in site.entries. */
306
+ const renderEntryHtml = (site, entry) => {
307
+ if (entry.library)
308
+ return {
309
+ html: `<article class="res-page resource-library subformat-page">${libraryPageHtml(resourceIndex(root, site.filePaths ?? filesSnapshot(root).files.map((item) => item.path), site.previews?.domains), entry.library, docDisplayName(entry.frontmatter, entry.id))}</article>`,
310
+ errors: [...site.errors, ...entry.errors],
311
+ };
312
+ if (entry.subformat)
313
+ return {
314
+ html: `<article class="res-page resource-library subformat-page">${resourceLibraryHtml({
315
+ codeblocks: [],
316
+ urls: [],
317
+ urlPreviews: [],
318
+ subformats: [entry.subformat],
319
+ errors: [...site.errors, ...entry.errors],
320
+ }, "subformats", docDisplayName(entry.frontmatter, entry.id))}</article>`,
321
+ errors: [...site.errors, ...entry.errors],
322
+ };
323
+ const sig = renderSignature(site, entry);
324
+ const cached = entryHtmlCache.get(entry.file);
325
+ if (cached &&
326
+ cached.blocks === entry.blocks &&
327
+ cached.sig === sig &&
328
+ cached.figures === site.ctx.figures &&
329
+ cached.figurePreview === site.ctx.figurePreview &&
330
+ cached.downloads === site.ctx.downloads) {
331
+ return cached.value;
332
+ }
333
+ const value = {
334
+ html: renderEntry(site, entry, entry.id),
335
+ errors: [...site.errors, ...entry.errors],
336
+ };
337
+ entryHtmlCache.set(entry.file, {
338
+ blocks: entry.blocks,
339
+ sig,
340
+ figures: site.ctx.figures,
341
+ figurePreview: site.ctx.figurePreview,
342
+ downloads: site.ctx.downloads,
343
+ value,
344
+ });
345
+ return value;
359
346
  };
360
- };
361
- /** Response for `GET /api/doc?file=<id>.md` (status + body). mode === "edit" only. */
362
- export const docQueryResponse = (site, file) => {
363
- const target = resolveContentFile(file);
364
- if (!target) {
365
- return { status: 400, body: { error: "file must be <id>.md" } };
366
- }
367
- if (!existsSync(target.abs)) {
368
- return { status: 404, body: { error: `${target.name} not found` } };
369
- }
370
- return {
371
- status: 200,
372
- body: renderDocFile(site, target.name, site.entries.find((entry) => entry.file === target.name)?.raw ??
373
- readFileSync(target.abs, "utf8")),
347
+ /** Compiles + renders one source (its current content on disk) (implements `/api/doc`). */
348
+ const renderDocFile = (site, file, raw) => {
349
+ const entry = draftEntry(site, file, raw);
350
+ return {
351
+ gitBase: entryGitBase(entry, site),
352
+ sourceFile: entry.sourceFile,
353
+ raw,
354
+ frontmatter: entry.frontmatter,
355
+ body: entry.body,
356
+ html: renderEntry(site, entry, ""),
357
+ errors: [...site.errors, ...entry.errors],
358
+ toc: entry.toc,
359
+ blockLines: entry.blockLines,
360
+ filePreviews: filePreviewResults(entry, site),
361
+ previews: site.previews,
362
+ };
374
363
  };
375
- };
376
- export { assembleDoc };
377
- const asString = (v) => (typeof v === "string" ? v : "");
378
- /** Client JSON → Frontmatter (keeps supported fields and drops empty optional values). */
379
- export const sanitizeFrontmatter = (v) => {
380
- const o = (typeof v === "object" && v != null ? v : {});
381
- const lang = asString(o.lang).trim();
382
- return { title: asString(o.title).trim(), ...(lang ? { lang } : {}) };
383
- };
384
- /**
385
- * Compares the base the editor started from (the disk source the client last read) with the
386
- * current disk source to tell whether it was rewritten externally (direct edit / git etc.)
387
- * without the editor knowing.
388
- * A client that sends no base (no baseRaw) can't be judged, so false (= overwrite).
389
- */
390
- export const isExternallyModified = (baseRaw, currentRaw) => typeof baseRaw === "string" && baseRaw !== currentRaw;
391
- /**
392
- * Validates the write target path — rejects anything other than `<id>.md` (directly under
393
- * content/), including traversal.
394
- */
395
- export const resolveContentFile = (rel) => {
396
- const id = typeof rel === "string" ? docIdOfFile(rel) : undefined;
397
- if (flattenTree(readManifest(root).tree).some((node) => node.id === id && node.subformat))
398
- return undefined;
399
- const file = id == null ? undefined : sourceDocFile(id, readManifest(root).files);
400
- return id == null || !file || ignoredFiles(root, [file]).has(file)
401
- ? undefined
402
- : {
403
- id,
404
- name: `${id}.md`,
405
- abs: textfilePath(root, file),
364
+ /** Response for `GET /api/doc?file=<id>.md` (status + body). mode === "edit" only. */
365
+ const docQueryResponse = (site, file) => {
366
+ const target = resolveContentFile(file);
367
+ if (!target) {
368
+ return { status: 400, body: { error: "file must be <id>.md" } };
369
+ }
370
+ if (!existsSync(target.abs)) {
371
+ return { status: 404, body: { error: `${target.name} not found` } };
372
+ }
373
+ return {
374
+ status: 200,
375
+ body: renderDocFile(site, target.name, site.entries.find((entry) => entry.file === target.name)?.raw ??
376
+ readFileSync(target.abs, "utf8")),
406
377
  };
407
- };
408
- // Default palette — resolves the figures' var(--doc-*) and color-mix() following the theme. The
409
- // theme has 3 states: default = follow the OS (prefers-color-scheme), explicitly overridden via
410
- // <html data-theme="light|dark">.
411
- // Maps the viewer's --c-* palette onto the body's --doc-* tokens. Unmapped tokens use defaults.
412
- const DARK_C = `
378
+ };
379
+ const asString = (v) => (typeof v === "string" ? v : "");
380
+ /** Client JSON → Frontmatter (keeps supported fields and drops empty optional values). */
381
+ const sanitizeFrontmatter = (v) => {
382
+ const o = (typeof v === "object" && v != null ? v : {});
383
+ const lang = asString(o.lang).trim();
384
+ return { title: asString(o.title).trim(), ...(lang ? { lang } : {}) };
385
+ };
386
+ /**
387
+ * Compares the base the editor started from (the disk source the client last read) with the
388
+ * current disk source to tell whether it was rewritten externally (direct edit / git etc.)
389
+ * without the editor knowing.
390
+ * A client that sends no base (no baseRaw) can't be judged, so false (= overwrite).
391
+ */
392
+ const isExternallyModified = (baseRaw, currentRaw) => typeof baseRaw === "string" && baseRaw !== currentRaw;
393
+ /**
394
+ * Validates the write target path — rejects anything other than `<id>.md` (directly under
395
+ * content/), including traversal.
396
+ */
397
+ const resolveContentFile = (rel) => {
398
+ const id = typeof rel === "string" ? docIdOfFile(rel) : undefined;
399
+ if (flattenTree(readManifest(root).tree).some((node) => node.id === id && (node.subformat || node.library)))
400
+ return undefined;
401
+ const file = id == null ? undefined : sourceDocFile(id, readManifest(root).files);
402
+ return id == null || !file || ignoredFiles(root, [file]).has(file)
403
+ ? undefined
404
+ : {
405
+ id,
406
+ name: `${id}.md`,
407
+ abs: textfilePath(root, file),
408
+ };
409
+ };
410
+ // Default palette — resolves the figures' var(--doc-*) and color-mix() following the theme. The
411
+ // theme has 3 states: default = follow the OS (prefers-color-scheme), explicitly overridden via
412
+ // <html data-theme="light|dark">.
413
+ // Maps the viewer's --c-* palette onto the body's --doc-* tokens. Unmapped tokens use defaults.
414
+ const DARK_C = `
413
415
  color-scheme: dark;
414
416
  --c-bg0:#101316; --c-bg1:#16191d; --c-surface:#1b1f24; --c-raised:#22272d;
415
417
  --c-line:#2a3037; --c-line-soft:#22272c;
@@ -418,7 +420,7 @@ const DARK_C = `
418
420
  --c-shadow:rgba(0,0,0,.4);
419
421
  --doc-fg-4:#525a66; --doc-accent-2:#4a8bff; --doc-accent-fg:#ffffff;
420
422
  --doc-ok-2:#56d364; --doc-warn-2:#ffc14d; --doc-danger-2:#ff7a7a; --doc-info-2:#79b0ff;`;
421
- const LIGHT_C = `
423
+ const LIGHT_C = `
422
424
  color-scheme: light;
423
425
  --c-bg0:#ffffff; --c-bg1:#f5f7f9; --c-surface:#fbfcfd; --c-raised:#e9edf2;
424
426
  --c-line:#d5dae0; --c-line-soft:#e4e8ec;
@@ -427,76 +429,76 @@ const LIGHT_C = `
427
429
  --c-shadow:rgba(15,23,32,.14);
428
430
  --doc-fg-4:#9099a8; --doc-accent-2:#0277bd; --doc-accent-fg:#ffffff;
429
431
  --doc-ok-2:#2ea043; --doc-warn-2:#f59f00; --doc-danger-2:#f04848; --doc-info-2:#4a8bff;`;
430
- const DOC_FROM_C = `
432
+ const DOC_FROM_C = `
431
433
  --doc-bg:var(--c-bg0); --doc-bg-2:var(--c-bg1); --doc-bg-3:var(--c-surface);
432
434
  --doc-panel:var(--c-surface); --doc-panel-2:var(--c-raised); --doc-rail:var(--c-bg1);
433
435
  --doc-border:var(--c-line-soft); --doc-border-2:var(--c-line);
434
436
  --doc-fg:var(--c-fg); --doc-fg-2:var(--c-fg-muted); --doc-fg-3:var(--c-fg-faint);
435
437
  --doc-accent:var(--c-accent); --doc-ok:var(--c-ok); --doc-warn:var(--c-warn);
436
438
  --doc-danger:var(--c-danger); --doc-info:var(--c-info);`;
437
- // Default for code and editing; browser display settings can override each independently.
438
- const MONO_FONT = `"UDEV Gothic", monospace`;
439
- const SANS_FONT = `"IBM Plex Sans JP", -apple-system, "Segoe UI", "Noto Sans JP", sans-serif`;
440
- // Viewer icons (20x20 stroke glyphs).
441
- const icon = (paths, size = 18) => `<svg class="nav-icon" viewBox="0 0 20 20" width="${size}" height="${size}" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${paths}</svg>`;
442
- const SIDEBAR_ICON = icon('<rect x="3" y="4" width="14" height="12" rx="1.5"/><path d="M8 4v12"/>');
443
- const DOCS_ICON = icon('<path d="M10 5.2c-1.2-1-2.9-1.5-4.7-1.5-.7 0-1.3.6-1.3 1.3v9c0 .7.6 1.3 1.3 1.3 1.8 0 3.5.5 4.7 1.5"/><path d="M10 5.2c1.2-1 2.9-1.5 4.7-1.5.7 0 1.3.6 1.3 1.3v9c0 .7-.6 1.3-1.3 1.3-1.8 0-3.5.5-4.7 1.5Z"/><path d="M10 5.2v11.6"/>');
444
- const CHEVRON_ICON = icon('<path d="M8 5.5 12.5 10 8 14.5"/>', 14);
445
- const GLOBE_ICON = icon('<circle cx="10" cy="10" r="7"/><ellipse cx="10" cy="10" rx="3" ry="7"/><path d="M3 10h14"/>');
446
- const BOX_ICON = icon('<path d="M3.5 6.5 10 3l6.5 3.5v7L10 17l-6.5-3.5v-7Z"/><path d="M3.5 6.5 10 10l6.5-3.5M10 10v7"/>');
447
- const STATICS_ICON = icon('<path d="M3 3v14h14M7 13V9m4 4V5m4 8V7"/>');
448
- const SUBFORMATS_ICON = icon('<rect x="3" y="3" width="14" height="14" rx="1"/><rect x="6" y="8" width="6" height="6" rx="1"/>');
449
- const GIT_ICON = icon('<path d="M5.5 6.5v7M14.5 6.5v1a4 4 0 0 1-4 4h-5"/><circle cx="5.5" cy="4.5" r="2"/><circle cx="5.5" cy="15.5" r="2"/><circle cx="14.5" cy="4.5" r="2"/>');
450
- const STORAGE_ICON = icon('<path d="m3 12 2-8h10l2 8"/><rect x="3" y="12" width="14" height="5" rx="1"/><path d="M13 14.5h1"/>');
451
- const FOLDER_ICON = icon(`<path d="${FOLDER_ICON_PATH}"/>`);
452
- const workspaceName = (site) => site.workspace?.protocol === "storage" ? workspaceLabel(site.workspace) : "Files";
453
- const workspaceText = (site) => `<span${site.workspace?.protocol === "storage" ? "" : ' data-i18n="Files"'}>${escapeHtml(workspaceName(site))}</span>`;
454
- const workspaceIcon = (site) => {
455
- if (site.workspace?.protocol === "git")
456
- return FOLDER_ICON;
457
- return site.workspace?.icon
458
- ? svgImg(site.workspace.icon, "nav-icon workspace-icon")
459
- : STORAGE_ICON;
460
- };
461
- const UPLOAD_ICON = icon('<path d="M11.5 3H6a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V6.5L11.5 3Z"/><path d="M11.5 3v3.5H15M10 14V9M7.8 11.2 10 9l2.2 2.2"/>', 24);
462
- const svgDataUri = (svg) => `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`;
463
- /**
464
- * Full svg → <img> (data URI; inline svgs would let the ids / styles of multiple icons collide,
465
- * so each is confined to an img).
466
- */
467
- const svgImg = (svg, cls) => {
468
- const uri = svgDataUri(svg);
469
- const img = `<img class="${cls}" alt="" src="${uri}">`;
470
- return cls.includes("doc-icon")
471
- ? `<span class="doc-icon-frame" style="--doc-icon:url('${uri}')">${img}</span>`
472
- : img;
473
- };
474
- const GEAR_ICON = icon('<path d="M4 6h7M15 6h1M4 14h1M9 14h7"/><circle cx="13" cy="6" r="2"/><circle cx="7" cy="14" r="2"/>', 16);
475
- const DELETE_ICON = icon('<path d="M4.5 6h11M8 6V4.5h4V6M6 6l.7 9.5h6.6L14 6M8.7 9v4M11.3 9v4"/>', 15);
476
- const PLUS_ICON = icon('<path d="M10 4.5v11M4.5 10h11"/>', 15);
477
- const THEME_ICONS = {
478
- "": icon('<circle cx="10" cy="10" r="6.5"/><path d="M10 3.5a6.5 6.5 0 0 0 0 13Z" fill="currentColor" stroke="none"/>'),
479
- light: icon('<circle cx="10" cy="10" r="3.4"/><path d="M10 2.6v1.8M10 15.6v1.8M2.6 10h1.8M15.6 10h1.8M4.8 4.8l1.3 1.3M13.9 13.9l1.3 1.3M15.2 4.8l-1.3 1.3M6.1 13.9l-1.3 1.3"/>'),
480
- dark: icon('<path d="M15.5 12.4A6.2 6.2 0 0 1 7.6 4.5a6.5 6.5 0 1 0 7.9 7.9Z"/>'),
481
- };
482
- const FONT_ICON = icon('<path d="M2.5 15 7 4l4.5 11M4 11h6M13 10.5c0-2.5 5-2.5 5 0V15M18 12h-2.5c-3.5 0-3.5 4 0 3L18 13.5"/>');
483
- const SELECT_ICON = icon('<path d="m5 7 5 5 5-5"/>', 12);
484
- const fontButton = (target) => {
485
- const label = target === "editor" ? "Editor font" : "Viewer font";
486
- return `<button class="pbtn font-control${target === "editor" ? " setting-picker" : ""}" type="button" data-font-picker="${target}" aria-haspopup="menu" aria-expanded="false" aria-label="${label}" title="${label}" disabled>${target === "editor" ? `<span data-picker-value></span>${SELECT_ICON}` : FONT_ICON}</button>`;
487
- };
488
- const CSS = `
439
+ // Default for code and editing; browser display settings can override each independently.
440
+ const MONO_FONT = `"UDEV Gothic", monospace`;
441
+ const SANS_FONT = `"IBM Plex Sans JP", -apple-system, "Segoe UI", "Noto Sans JP", sans-serif`;
442
+ // Viewer icons (20x20 stroke glyphs).
443
+ const icon = (paths, size = 18) => `<svg class="nav-icon" viewBox="0 0 20 20" width="${size}" height="${size}" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${paths}</svg>`;
444
+ const SIDEBAR_ICON = icon('<rect x="3" y="4" width="14" height="12" rx="1.5"/><path d="M8 4v12"/>');
445
+ const DOCS_ICON = icon('<path d="M10 5.2c-1.2-1-2.9-1.5-4.7-1.5-.7 0-1.3.6-1.3 1.3v9c0 .7.6 1.3 1.3 1.3 1.8 0 3.5.5 4.7 1.5"/><path d="M10 5.2c1.2-1 2.9-1.5 4.7-1.5.7 0 1.3.6 1.3 1.3v9c0 .7-.6 1.3-1.3 1.3-1.8 0-3.5.5-4.7 1.5Z"/><path d="M10 5.2v11.6"/>');
446
+ const CHEVRON_ICON = icon('<path d="M8 5.5 12.5 10 8 14.5"/>', 14);
447
+ const GLOBE_ICON = icon('<circle cx="10" cy="10" r="7"/><ellipse cx="10" cy="10" rx="3" ry="7"/><path d="M3 10h14"/>');
448
+ const BOX_ICON = icon('<path d="M3.5 6.5 10 3l6.5 3.5v7L10 17l-6.5-3.5v-7Z"/><path d="M3.5 6.5 10 10l6.5-3.5M10 10v7"/>');
449
+ const STATICS_ICON = icon('<path d="M3 3v14h14M7 13V9m4 4V5m4 8V7"/>');
450
+ const SUBFORMATS_ICON = icon('<rect x="3" y="3" width="14" height="14" rx="1"/><rect x="6" y="8" width="6" height="6" rx="1"/>');
451
+ const GIT_ICON = icon('<path d="M5.5 6.5v7M14.5 6.5v1a4 4 0 0 1-4 4h-5"/><circle cx="5.5" cy="4.5" r="2"/><circle cx="5.5" cy="15.5" r="2"/><circle cx="14.5" cy="4.5" r="2"/>');
452
+ const STORAGE_ICON = icon('<path d="m3 12 2-8h10l2 8"/><rect x="3" y="12" width="14" height="5" rx="1"/><path d="M13 14.5h1"/>');
453
+ const FOLDER_ICON = icon(`<path d="${FOLDER_ICON_PATH}"/>`);
454
+ const workspaceName = (site) => site.workspace?.protocol === "storage" ? workspaceLabel(site.workspace) : "Files";
455
+ const workspaceText = (site) => `<span${site.workspace?.protocol === "storage" ? "" : ' data-i18n="Files"'}>${escapeHtml(workspaceName(site))}</span>`;
456
+ const workspaceIcon = (site) => {
457
+ if (site.workspace?.protocol === "git")
458
+ return FOLDER_ICON;
459
+ return site.workspace?.icon
460
+ ? svgImg(site.workspace.icon, "nav-icon workspace-icon")
461
+ : STORAGE_ICON;
462
+ };
463
+ const UPLOAD_ICON = icon('<path d="M11.5 3H6a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V6.5L11.5 3Z"/><path d="M11.5 3v3.5H15M10 14V9M7.8 11.2 10 9l2.2 2.2"/>', 24);
464
+ const svgDataUri = (svg) => `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`;
465
+ /**
466
+ * Full svg → <img> (data URI; inline svgs would let the ids / styles of multiple icons collide,
467
+ * so each is confined to an img).
468
+ */
469
+ const svgImg = (svg, cls) => {
470
+ const uri = svgDataUri(svg);
471
+ const img = `<img class="${cls}" alt="" src="${uri}">`;
472
+ return cls.includes("doc-icon")
473
+ ? `<span class="doc-icon-frame" style="--doc-icon:url('${uri}')">${img}</span>`
474
+ : img;
475
+ };
476
+ const GEAR_ICON = icon('<path d="M4 6h7M15 6h1M4 14h1M9 14h7"/><circle cx="13" cy="6" r="2"/><circle cx="7" cy="14" r="2"/>', 16);
477
+ const DELETE_ICON = icon('<path d="M4.5 6h11M8 6V4.5h4V6M6 6l.7 9.5h6.6L14 6M8.7 9v4M11.3 9v4"/>', 15);
478
+ const PLUS_ICON = icon('<path d="M10 4.5v11M4.5 10h11"/>', 15);
479
+ const THEME_ICONS = {
480
+ "": icon('<circle cx="10" cy="10" r="6.5"/><path d="M10 3.5a6.5 6.5 0 0 0 0 13Z" fill="currentColor" stroke="none"/>'),
481
+ light: icon('<circle cx="10" cy="10" r="3.4"/><path d="M10 2.6v1.8M10 15.6v1.8M2.6 10h1.8M15.6 10h1.8M4.8 4.8l1.3 1.3M13.9 13.9l1.3 1.3M15.2 4.8l-1.3 1.3M6.1 13.9l-1.3 1.3"/>'),
482
+ dark: icon('<path d="M15.5 12.4A6.2 6.2 0 0 1 7.6 4.5a6.5 6.5 0 1 0 7.9 7.9Z"/>'),
483
+ };
484
+ const FONT_ICON = icon('<path d="M2.5 15 7 4l4.5 11M4 11h6M13 10.5c0-2.5 5-2.5 5 0V15M18 12h-2.5c-3.5 0-3.5 4 0 3L18 13.5"/>');
485
+ const SELECT_ICON = icon('<path d="m5 7 5 5 5-5"/>', 12);
486
+ const fontButton = (target) => {
487
+ const label = target === "editor" ? "Editor font" : "Viewer font";
488
+ return `<button class="pbtn font-control${target === "editor" ? " setting-picker" : ""}" type="button" data-font-picker="${target}" aria-haspopup="menu" aria-expanded="false" aria-label="${label}" title="${label}" disabled>${target === "editor" ? `<span data-picker-value></span>${SELECT_ICON}` : FONT_ICON}</button>`;
489
+ };
490
+ const CSS = `
489
491
  :root { ${DARK_C} ${DOC_FROM_C} --doc-mono: ${MONO_FONT}; --font-sans: ${SANS_FONT}; }
490
492
  html[data-theme] iframe[data-doc-figure-frame]:not([data-theme-ready]) { visibility: hidden; }
491
493
  @media (prefers-color-scheme: light) { :root:not([data-theme="dark"]) { ${LIGHT_C} } }
492
494
  :root[data-theme="light"] { ${LIGHT_C} }
493
- body.edit :is(#sidebar, #panel, .resources-pane, .subformat-toast), .preview-pane[data-theme], .theme-picker[data-theme] { ${DARK_C} ${DOC_FROM_C} }
495
+ body.edit :is(#sidebar, #panel, .resources-pane, .subformat-toast, .app-dialog, .workspace-dialog, #doc-search), :is(.preview-pane, .theme-picker, #preview-language-menu)[data-theme] { ${DARK_C} ${DOC_FROM_C} }
494
496
  @media (prefers-color-scheme: light) {
495
- :root:not([data-editor-theme="dark"]) body.edit :is(#sidebar, #panel, .resources-pane, .subformat-toast),
496
- :is(.preview-pane, .theme-picker)[data-theme="auto"] { ${LIGHT_C} }
497
+ :root:not([data-editor-theme="dark"]) body.edit :is(#sidebar, #panel, .resources-pane, .subformat-toast, .app-dialog, .workspace-dialog, #doc-search),
498
+ :is(.preview-pane, .theme-picker, #preview-language-menu)[data-theme="auto"] { ${LIGHT_C} }
497
499
  }
498
- :root[data-editor-theme="light"] body.edit :is(#sidebar, #panel, .resources-pane, .subformat-toast),
499
- :is(.preview-pane, .theme-picker)[data-theme="light"] { ${LIGHT_C} }
500
+ :root[data-editor-theme="light"] body.edit :is(#sidebar, #panel, .resources-pane, .subformat-toast, .app-dialog, .workspace-dialog, #doc-search),
501
+ :is(.preview-pane, .theme-picker, #preview-language-menu)[data-theme="light"] { ${LIGHT_C} }
500
502
  .preview-pane { background: var(--c-bg0); color: var(--c-fg); }
501
503
  .theme-picker { position: fixed; margin: 0; padding: 5px; width: 148px; border: 1px solid var(--c-line);
502
504
  border-radius: 6px; background: var(--c-bg1); color: var(--c-fg); box-shadow: 0 8px 24px var(--c-shadow); }
@@ -603,7 +605,7 @@ button { font-family: inherit; font-size: inherit; font-weight: var(--fw-body);
603
605
  .search-docked #doc-search-results { margin-right: -10px; padding-right: 10px; }
604
606
  /* Keep the preview readable; the editor panel gives up width before the search sidebar does. */
605
607
  body:has(#doc-search.search-docked[open]) main { min-width: 240px; }
606
- body:has(#doc-search.search-docked[open]) #panel { flex-shrink: 100; min-width: 240px; }
608
+ body:has(#doc-search.search-docked[open]) #panel { flex-shrink: 100; min-width: 320px; }
607
609
  .search-docked :is(.search-grip, .search-resize-x, .search-resize-y, .search-resize-xy),
608
610
  #doc-search:not(.search-docked) .search-resize-w { display: none; }
609
611
  /* Invisible edges: the right and bottom borders resize the window. */
@@ -630,7 +632,8 @@ body.sidebar-closed #sidebar-resize { display: none; }
630
632
  #resize::before { left: -1px; }
631
633
  .panel-resize:hover::before, .panel-resize:focus-visible::before, .panel-resize.drag::before {
632
634
  background: color-mix(in srgb, var(--c-accent) 60%, transparent); }
633
- .panel-resize.drag { outline: none; }
635
+ /* The accent bar is the focus indicator; the generic outline would draw a second line. */
636
+ .panel-resize:focus-visible { outline: none; }
634
637
  body.resizing, body.resizing * { cursor: col-resize !important; user-select: none !important; }
635
638
  body.sidebar-closed .site-title { display: none; }
636
639
  #sidebar-head { position: relative; flex: none; display: flex; align-items: center; min-width: 0; min-height: 36px;
@@ -798,6 +801,19 @@ main { flex: 1; min-width: 0; padding: 20px 24px 50vh; }
798
801
  main:not(.editor-workspace) { height: 100vh; overflow: auto; overscroll-behavior: contain; }
799
802
  article { max-width: 860px; margin: 0 auto; font-family: var(--viewer-font, system-ui, sans-serif); }
800
803
  .external-embed { margin: 18px 0; overflow-wrap: anywhere; }
804
+ .downloadable-resource { position: relative; }
805
+ .resource-download-tools { position: absolute; top: 4px; right: 4px; z-index: 1; display: flex; align-items: center; gap: 8px; border-radius: 4px; background: var(--doc-panel); opacity: .65; }
806
+ .downloadable-resource:hover > .resource-download-tools, .resource-download-tools:focus-within { opacity: 1; }
807
+ .codeblk-head .resource-download { width: 16px; height: 16px; border-radius: 6px; color: var(--doc-fg-3); }
808
+ .codeblk-head .resource-download svg { width: 14px; height: 14px; }
809
+ .doc-title > .resource-download { align-self: center; }
810
+ .doc-title:has(.toc-card) > h1 { display: inline-block; vertical-align: middle; }
811
+ .resource-download { display: inline-flex; flex: none; align-items: center; justify-content: center; box-sizing: border-box; width: 24px; height: 24px; border-radius: 4px; color: var(--doc-fg-2); text-decoration: none; }
812
+ .resource-download:hover { background: var(--doc-panel); color: var(--doc-accent); }
813
+ .resource-download:focus-visible { outline: 2px solid var(--doc-accent); outline-offset: 2px; }
814
+ .resource-download[aria-busy="true"] { cursor: progress; }
815
+ .res-file-page h1 > .resource-download { margin-left: 8px; vertical-align: middle; }
816
+ .resource-download-tools [role="status"] { font: 12px/1.5 var(--font-sans); color: var(--doc-fg-2); }
801
817
  .plugin { position: relative; min-width: 0; border: 2px solid var(--doc-border); border-top: 0; }
802
818
  .plugin-toolbar { position: absolute; top: 0; left: -2px; right: -2px; transform: translateY(-50%);
803
819
  display: flex; align-items: center; gap: 4px; }
@@ -857,7 +873,7 @@ body:has(.plugin-resize.drag) iframe { pointer-events: none; }
857
873
  ${PLUGIN_BLOCK_CSS}
858
874
 
859
875
  article, article * { font-weight: 400; }
860
- h1, h2, h3 { font-weight: 400; }
876
+ h1, h2, h3, h4, h5, h6 { font-weight: 400; }
861
877
  article h1 { font-size: 26px; margin: 0 0 2px; }
862
878
  article :is(h1, h2, h3, h4, h5, h6):has(> .section-copy) { position: relative; padding-right: 32px; }
863
879
  .section-copy { position: absolute; right: 0; top: 0; display: flex; align-items: center; justify-content: center;
@@ -871,7 +887,10 @@ article :is(h1, h2, h3, h4, h5, h6):has(> .section-copy) { position: relative; p
871
887
  article h2 { font-size: 20px; margin-top: 24px; margin-bottom: 8px; border-bottom: 1px solid
872
888
  color-mix(in srgb, currentColor 20%, transparent); padding-bottom: 3px; }
873
889
  article h3 { font-size: 16px; margin-top: 16px; margin-bottom: 4px; }
874
- h2[id], h3[id] { scroll-margin-top: 12px; }
890
+ article h4 { font-size: 15px; margin-top: 14px; margin-bottom: 4px; }
891
+ article h5 { font-size: 14px; margin-top: 12px; margin-bottom: 4px; }
892
+ article h6 { font-size: 13px; margin-top: 12px; margin-bottom: 4px; color: var(--doc-fg-2); }
893
+ :is(h2, h3, h4, h5, h6)[id] { scroll-margin-top: 12px; }
875
894
  p { margin: 8px 0; }
876
895
  ul, ol { margin: 4px 0; }
877
896
  li { margin: 0; }
@@ -1022,6 +1041,9 @@ article a { color: var(--doc-accent); }
1022
1041
  text-decoration: none; font: 12px/1.5 var(--font-sans); color: var(--doc-fg-2); }
1023
1042
  .in-toc .lvl2 a { padding-left: 20px; }
1024
1043
  .in-toc .lvl3 a { padding-left: 30px; }
1044
+ .in-toc .lvl4 a { padding-left: 40px; }
1045
+ .in-toc .lvl5 a { padding-left: 50px; }
1046
+ .in-toc .lvl6 a { padding-left: 60px; }
1025
1047
  .in-toc a:hover, .in-toc a[aria-current] { color: var(--doc-accent); background: color-mix(in srgb, var(--doc-accent) 8%, transparent); }
1026
1048
  .doc-title:has(.toc-card) { display: block; max-width: none; }
1027
1049
  .doc-title:has(.toc-card) > h1 { max-width: calc(100% - 100px); }
@@ -1029,7 +1051,7 @@ article a { color: var(--doc-accent); }
1029
1051
  .toc-card::before { content: attr(aria-label); display: block; margin: 0 10px 6px; color: var(--doc-fg-3); font: 12px/1.5 var(--font-sans); }
1030
1052
  .toc-card .toc-current { display: none; }
1031
1053
  .toc-card .toc-options { position: static; padding: 0; border: 0; background: transparent; box-shadow: none; }
1032
- main :is(h1, h2, h3)[id] { scroll-margin-top: 52px; }
1054
+ main :is(h1, h2, h3, h4, h5, h6)[id] { scroll-margin-top: 52px; }
1033
1055
  article strong { font-weight: 700; }
1034
1056
  article em { font-style: italic; }
1035
1057
  article blockquote { margin: 16px 0; padding: 4px 16px; border-left: 3px solid var(--doc-border-2); color: var(--doc-fg-2); }
@@ -1045,7 +1067,7 @@ details summary { cursor: pointer; opacity: .8; }
1045
1067
  transform: translateX(-50%); top: calc(100% + 6px); z-index: 5;
1046
1068
  width: min(560px, 78vw); padding: 12px 14px;
1047
1069
  background: var(--doc-panel); border: 1px solid var(--doc-border);
1048
- border-radius: 8px; box-shadow: 0 4px 16px color-mix(in srgb, var(--doc-fg) 18%, transparent);
1070
+ border-radius: 8px;
1049
1071
  color: var(--doc-fg); font-size: 13px; line-height: 1.7; }
1050
1072
  .figref:hover .figpop, .figref:focus-visible .figpop, .dictref:hover .dictpop { display: block; }
1051
1073
  .figpop svg { max-width: 100%; height: auto; display: block; }
@@ -1099,7 +1121,7 @@ details summary { cursor: pointer; opacity: .8; }
1099
1121
  .extension-editor { border-top: 1px solid var(--c-line); margin-top: 12px; padding-top: 4px; }
1100
1122
  .extension-editor .extensions-header { font-size: 12px; }
1101
1123
  .extension-editor select { min-width: 0; max-width: 100%; margin-left: auto; }
1102
- .extension-editor textarea { display: block; box-sizing: border-box; width: 100%; min-height: 320px; margin: 8px 0; padding: 10px; border: 1px solid var(--c-line); border-radius: 4px; background: var(--c-bg1); color: var(--c-fg); font: 12px/1.6 var(--font-mono); tab-size: 2; resize: vertical; }
1124
+ .extension-editor textarea { display: block; box-sizing: border-box; width: 100%; min-height: 320px; margin: 8px 0; padding: 10px; border: 1px solid var(--c-line); border-radius: 4px; background: var(--c-bg1); color: var(--c-fg); font: 12px/1.6 var(--doc-mono); tab-size: 2; resize: vertical; }
1103
1125
  .extension-icon { position: relative; flex: none; display: grid; place-items: center; width: 40px; height: 40px; color: var(--c-fg-muted); }
1104
1126
  .extension-icon > :is(svg, img) { width: 32px; height: 32px; object-fit: contain; }
1105
1127
  .extension-icon > img { position: absolute; inset: 4px; }
@@ -1114,6 +1136,11 @@ body.extensions-over #nav-extensions, body.extensions-over .extensions-dropzone
1114
1136
 
1115
1137
  .resource-library { width: 100%; max-width: none; }
1116
1138
  .git-page { padding-top: 8px; font: 12px/1.55 var(--font-sans); }
1139
+ .git-page > #git-manager { max-width: 880px; margin-inline: auto; }
1140
+ .git-toolbar { gap: 8px; padding-block: 6px; }
1141
+ .git-toolbar > :last-child { margin-left: auto; }
1142
+ .git-controls > section { padding: 4px 0; }
1143
+ .git-page .resource-tabs { margin: 12px 0; padding: 0; }
1117
1144
  .git-controls { min-width: 0; margin: 0; padding: 0; border: 0; }
1118
1145
  .git-toolbar, .git-actions, .git-branches { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; min-height: 30px; }
1119
1146
  .git-toolbar { border-bottom: 1px solid var(--c-line); margin: 4px 0 8px; padding-inline: 6px; }
@@ -1143,7 +1170,10 @@ body.extensions-over #nav-extensions, body.extensions-over .extensions-dropzone
1143
1170
  .git-diff { max-height: 320px; overflow: auto; padding: 8px; background: var(--c-surface); font: 11px/1.6 var(--editor-font, ${MONO_FONT}); }
1144
1171
  .git-checkbox { display: flex; align-items: center; gap: 6px; }
1145
1172
  .resource-tabs { display: flex; gap: 4px; overflow-x: auto; border-bottom: 1px solid var(--doc-border); margin-bottom: 18px; }
1146
- .resource-tabs a { padding: 9px 15px; color: var(--doc-fg-3); text-decoration: none; white-space: nowrap; font-size: 13px; border-bottom: 2px solid transparent; }
1173
+ .resource-tabs a { display: inline-flex; align-items: center; gap: 6px; padding: 9px 15px; color: var(--doc-fg-3); text-decoration: none; white-space: nowrap; font-size: 13px; border-bottom: 2px solid transparent; }
1174
+ .resource-tabs a svg, .resource-item > summary > svg { flex: none; width: 15px; height: 15px; }
1175
+ .nav-page-menu .subformat-setting-option > button svg { width: 16px; height: 16px; margin-right: 9px; vertical-align: -3px; color: var(--c-fg-muted); }
1176
+ .subformat-picker button > img.doc-icon { width: 16px; height: 16px; margin-right: 8px; vertical-align: -3px; }
1147
1177
  .resource-tabs a:hover { color: var(--doc-fg); background: color-mix(in srgb, var(--doc-fg) 4%, transparent); }
1148
1178
  .resource-tabs a[aria-current] { color: var(--doc-accent); border-bottom-color: currentColor; }
1149
1179
  .resource-toolbar { position: relative; display: flex; align-items: center; gap: 10px; height: 30px; padding: 0 6px;
@@ -1289,6 +1319,10 @@ body.extensions-over #nav-extensions, body.extensions-over .extensions-dropzone
1289
1319
  .app-dialog button:hover { background: var(--c-raised); border-color: var(--c-fg-muted); }
1290
1320
  .app-dialog button:focus-visible { outline-color: var(--c-fg-muted); }
1291
1321
  .app-dialog button.danger { color: var(--c-danger); }
1322
+ .history-dialog input { box-sizing: border-box; width: 100%; padding: 8px; color: var(--c-fg); background: var(--c-bg0); border: 1px solid var(--c-line); border-radius: 4px; font: inherit; }
1323
+ .history-dialog ul { max-height: 50dvh; margin: 12px 0 20px; padding: 0; overflow-y: auto; list-style: none; color: var(--c-fg-muted); }
1324
+ .history-dialog li { display: flex; align-items: center; gap: 8px; padding: 4px 0; }
1325
+ .history-dialog li span { flex: 1; overflow-wrap: anywhere; }
1292
1326
  .subformat-page-name { display: block; box-sizing: border-box; width: 100%; margin: 8px 0 20px; padding: 8px; color: var(--c-fg); background: var(--c-bg0); border: 1px solid var(--c-line); border-radius: 4px; font: inherit; }
1293
1327
  .subformat-page .resource-query { flex-wrap: wrap; max-width: none; }
1294
1328
  .subformat-page-title { flex: 1 1 100%; margin: 0 0 12px; color: var(--c-fg); font: 500 24px/1.3 var(--font-sans); overflow-wrap: anywhere; }
@@ -1322,6 +1356,30 @@ body:not(.edit) .subformat-page { padding-top: 64px; }
1322
1356
  .resource-item .codeblk > pre { max-height: 260px; overflow: auto; }
1323
1357
  .resource-usage { flex: none; margin-left: auto; color: var(--doc-fg-3); font-size: 11px; font-variant-numeric: tabular-nums; }
1324
1358
  .resource-sources { display: flex; flex-direction: column; gap: 4px; }
1359
+ [data-resource-page] { container-type: inline-size; }
1360
+ [data-resource-page] .resource-search { flex-basis: 220px; color: var(--doc-fg-2); }
1361
+ [data-resource-page] .resource-search input::placeholder { color: var(--doc-fg-2); }
1362
+ [data-resource-page] .resource-code { border-bottom: 1px solid var(--doc-border); }
1363
+ [data-resource-page] .resource-code > summary { height: auto; min-height: 28px; }
1364
+ [data-resource-page] .resource-code > summary > .resource-source:only-of-type { max-width: 100%; }
1365
+ [data-resource-page] .resource-body { padding: 4px 6px 12px; }
1366
+ [data-resource-page] .resource-body > :is(.fig, .data-table, .callout) { margin-block: 0; }
1367
+ [data-resource-page] .resource-body > .resource-sources { margin-bottom: 8px; }
1368
+ [data-resource-page] [data-resource-group="callouth"] .callout { border: 0; border-radius: 0; padding: 0; max-width: 75ch; background: transparent; }
1369
+ [data-resource-page] [data-resource-group="callouth"] .callout-body { font-size: 13.5px; }
1370
+ [data-resource-page] [data-resource-group="callouth"] .callout-body > p:first-child { font-size: inherit; }
1371
+ [data-resource-page] :is([data-resource-group="csv"], [data-resource-group="tsv"]) .data-table-scroll { border-radius: 0; }
1372
+ .resource-term { margin: 4px 0; font: 13.5px/1.4 var(--font-sans); }
1373
+ .resource-term .terms { margin: 0; }
1374
+ .resource-term .dict-card { padding: 0 8px 4px; }
1375
+ .resource-term legend { gap: 4px; padding-inline: 2px; font-size: 13.5px; }
1376
+ .resource-term .term-definition { margin: 0; line-height: 1.4; }
1377
+ .resource-term-sources { display: flex; flex-wrap: wrap; align-items: baseline; gap: 0 12px;
1378
+ min-width: 0; padding: 0 8px; color: var(--doc-fg-2); font-size: 11px; }
1379
+ .resource-term-sources > .resource-source { min-height: 24px; color: inherit; }
1380
+ .resource-term-sources > details { min-width: 0; max-width: 100%; }
1381
+ .resource-term-sources summary { width: fit-content; min-height: 24px; cursor: pointer; }
1382
+ .resource-term-sources :is(a, summary):focus-visible { outline: 2px solid var(--doc-accent); outline-offset: 2px; }
1325
1383
  .resource-empty { padding: 20px 6px; color: var(--doc-fg-3); font-size: 12px; }
1326
1384
  .resource-errors { margin: 0 0 16px; color: var(--doc-danger); font-size: 12px; overflow-wrap: anywhere; }
1327
1385
  .resource-errors summary { cursor: pointer; }
@@ -1331,12 +1389,15 @@ body:not(.edit) .subformat-page { padding-top: 64px; }
1331
1389
  .resource-library .files-table thead th { position: sticky; top: 0; z-index: 1; border-bottom: 1px solid var(--c-line); background: var(--c-bg1); font-size: 11px; color: var(--c-fg-muted); font-weight: 500; }
1332
1390
  @media(max-width:600px) { .resource-tabs a { padding-inline: 10px; } .resource-toolbar { gap: 8px; } }
1333
1391
  `;
1334
- // edit mode only (right panel / new doc form). Uses the viewer's shared background / rules and
1335
- // button / input styles. To keep CM as wide as possible the fm is compact, and the toggles
1336
- // (autosave / correspondence display / fm visibility) are gathered in the header gear's hover
1337
- // menu. Width is drag-resizable.
1338
- const EDIT_CSS = `
1392
+ // edit mode only (right panel / new doc form). Uses the viewer's shared background / rules and
1393
+ // button / input styles. To keep CM as wide as possible the fm is compact, and the toggles
1394
+ // (autosave / correspondence display / fm visibility) are gathered in the header gear's
1395
+ // menu. Width is drag-resizable.
1396
+ const EDIT_CSS = `
1339
1397
  body.line-wrap-off .cm-content { white-space: pre; }
1398
+ a.file-editor-title { color: inherit; text-decoration: none; }
1399
+ a.file-editor-title:hover { color: var(--c-accent); text-decoration: underline; }
1400
+ #cm .cm-lineNumbers .cm-gutterElement:hover { color: var(--c-accent); text-decoration: underline; cursor: pointer; }
1340
1401
  body.git-diff-hidden .cm-lineNumbers :is(.cm-git-added, .cm-git-modified, .cm-git-deleted-start, .cm-git-deleted-end) { box-shadow: none; }
1341
1402
  body.git-diff-hidden .cm-line:is(.cm-git-added, .cm-git-modified, .cm-git-deleted-start, .cm-git-deleted-end) { background-color: transparent; }
1342
1403
  #site-title[role="button"] { cursor: text; position: relative; }
@@ -1348,7 +1409,7 @@ body.git-diff-hidden .cm-line:is(.cm-git-added, .cm-git-modified, .cm-git-delete
1348
1409
  body.sidebar-closed #site-icon-slot input { display: none; }
1349
1410
  /* Right panel = header / properties / editor stacked on one surface, separated by rules (no
1350
1411
  nested frames). */
1351
- #panel { width: var(--panel-width, min(760px, 52vw)); flex-shrink: 0; position: sticky; top: 0; height: 100vh;
1412
+ #panel { width: var(--panel-width, min(760px, 52vw)); flex-shrink: 0; position: sticky; top: 0; height: 100vh; container: editor-panel / inline-size;
1352
1413
  display: flex; flex-direction: column; font-size: 12.5px; line-height: 1.6;
1353
1414
  border-left: 1px solid var(--c-line); background: var(--c-bg1); }
1354
1415
  body.textfile-open #phead :is(.fm-language, #status, #validate, #save, #split-preview) { display: none; }
@@ -1368,7 +1429,7 @@ body.textfile-open #phead :is(.fm-language, #status, #validate, #save, #split-pr
1368
1429
  #file-editor .cm-textfile-status.error { color: var(--doc-danger); }
1369
1430
  #file-editor:is([data-subformat-register], [data-subformat-record]) { position: static; width: auto; max-height: none; padding: 0; border: 0; border-radius: 0; overflow: hidden; }
1370
1431
  #file-editor:is([data-subformat-register], [data-subformat-record]) fieldset { display: flex; flex-direction: column; flex: 1; min-height: 0; }
1371
- .subformat-register-fields { display: grid; flex: 1; min-width: 0; grid-template-columns: minmax(36px, .5fr) 60px minmax(50px, 1.5fr); gap: 6px; margin: 0; padding: 0; border: 0; }
1432
+ .subformat-register-fields { display: grid; flex: 1; min-width: 0; grid-template-columns: minmax(0, .5fr) 60px minmax(0, 1.5fr); gap: 6px; margin: 0; padding: 0; border: 0; }
1372
1433
  .subformat-register-fields :is(input, select) { width: 100%; min-width: 0; height: 28px; padding: 4px; background: transparent; color: var(--c-fg); border: 0; border-bottom: 1px solid var(--c-line); border-radius: 0; font: 12px/18px var(--font-sans); }
1373
1434
  .subformat-register-fields input:hover, .subformat-register-fields input:focus-visible { background: transparent; outline: none; border-bottom-color: var(--c-fg-muted); }
1374
1435
  .subformat-register-fields .language-select { min-width: 0; }
@@ -1476,9 +1537,9 @@ body.textfile-open #phead :is(.fm-language, #status, #validate, #save, #split-pr
1476
1537
  .schema-builder input[aria-invalid="true"], .schema-builder input[aria-invalid="true"]:focus-visible, .subformat-register-fields input:user-invalid { outline: 1px solid var(--c-danger); outline-offset: 1px; }
1477
1538
  .schema-json-note { margin: 8px 0 0; color: var(--c-fg-muted); font-size: 11px; }
1478
1539
  .schema-builder .schema-extra-fields { margin: 6px 0; }
1479
- .subformat-value-form > label, .subformat-value-form fieldset > label { margin-block: 12px; }
1480
1540
  .subformat-value-form fieldset { min-width: 0; margin: 12px 0; padding: 0 12px; border: 1px solid var(--c-line); }
1481
- .subformat-value-form legend { padding-inline: 4px; }
1541
+ .subformat-value-form legend { max-width: 100%; padding-inline: 4px; overflow-wrap: anywhere; color: var(--c-fg-muted); font-size: 11px; }
1542
+ .subformat-value-form .subformat-value-field { padding: 0 6px 6px; border-radius: 4px; }
1482
1543
  .subformat-value-form small { overflow-wrap: anywhere; }
1483
1544
  .date-control { position: relative; }
1484
1545
  .schema-builder .date-control > input { padding-right: 34px; font-variant-numeric: tabular-nums; }
@@ -1503,9 +1564,46 @@ body.textfile-open #phead :is(.fm-language, #status, #validate, #save, #split-pr
1503
1564
  @container(max-width:440px) { .schema-add-field { grid-template-columns: minmax(0, 1fr) auto; } }
1504
1565
  @container(max-width:440px) { .schema-range { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0 8px; } .schema-range [data-schema-bound="max"] { grid-column: 2; } .schema-range > .schema-range-track { grid-column: 1 / -1; grid-row: 2; } .schema-range .schema-parameter label { grid-template-columns: minmax(0, 1fr); gap: 0; } }
1505
1566
 
1506
- /* header band (same height and rule as sidebar-head) */
1507
- #phead { flex: none; display: flex; align-items: center; gap: 2px; height: 36px; padding: 0 10px 0 14px;
1567
+ /* Workspace and document controls share the editor's compact header. */
1568
+ #phead { flex: none; display: grid; grid-template-columns: minmax(0, 1fr) 144px minmax(0, 1fr); align-items: center; gap: 4px; height: 36px; padding: 0 6px; container: editor-header / inline-size;
1508
1569
  border-bottom: 1px solid var(--c-line); }
1570
+ #editor-header-context, #editor-header-actions { display: flex; align-items: center; gap: 2px; min-width: 0; }
1571
+ #editor-header-actions { justify-content: flex-end; }
1572
+ #editor-header-workspace { display: flex; align-items: center; gap: 4px; width: 100%; min-width: 0; }
1573
+ #editor-header-workspace .workspace-select { flex: 1 1 0; min-width: 0; }
1574
+ #editor-header-context .file-editor-heading { margin-left: 0; }
1575
+ .workspace-select::after { display: none; }
1576
+ .workspace-select .workspace-picker-input { display: block; width: 100%; min-width: 0; height: 28px; padding: 4px; color: var(--c-fg); background: transparent; border: 0; border-radius: 0; outline: 0; font: 12px var(--font-sans); text-align: center; text-decoration: none; text-underline-offset: 3px; caret-color: transparent; cursor: pointer; }
1577
+ #editor-header-workspace[data-split="true"] .workspace-picker-input { padding-inline: 0; }
1578
+ .workspace-select[data-active="true"] .workspace-picker-input { text-decoration-line: underline; }
1579
+ .workspace-select .workspace-picker-input:is(:hover, :focus-visible) { background: transparent; outline: 0; text-decoration-thickness: 2px; }
1580
+ .workspace-select .workspace-picker-input:focus-visible { text-decoration-line: underline; }
1581
+ .workspace-select .workspace-picker-input::selection { color: inherit; background: transparent; }
1582
+ .workspace-picker .language-options button { white-space: normal; overflow-wrap: anywhere; text-overflow: clip; }
1583
+ .workspace-select .workspace-picker-input[data-change="added"], .workspace-picker .language-options button[data-change="added"] { color: var(--c-ok); }
1584
+ .workspace-select .workspace-picker-input[data-change="modified"], .workspace-picker .language-options button[data-change="modified"] { color: var(--c-accent); }
1585
+ .workspace-select .workspace-picker-input[data-change="deleted"], .workspace-picker .language-options button[data-change="deleted"] { color: var(--c-danger); }
1586
+ .workspace-picker .language-options button[data-unavailable] { display: flex; align-items: center; gap: 8px; color: light-dark(var(--c-danger), var(--doc-danger-2)); cursor: not-allowed; }
1587
+ .workspace-picker .language-options button[data-unavailable] > :first-child { flex: 1; min-width: 0; }
1588
+ .workspace-unavailable-icon { display: flex; flex: none; }
1589
+ .workspace-picker .language-options button[data-create="true"] { margin-top: 4px; border-top: 1px solid var(--c-line); }
1590
+ .workspace-picker .language-options button[aria-selected="true"] { text-decoration: underline; text-underline-offset: 3px; }
1591
+ .workspace-picker .language-options button:focus-visible { outline: 0; background: var(--c-raised); }
1592
+ #phead .fm-language { flex: 0 1 144px; min-width: 44px; }
1593
+ #phead #status { padding-inline: 0; }
1594
+ #fm-lang-picker { min-width: 120px; }
1595
+ @container editor-panel (min-width: 564px) {
1596
+ #phead:has(#editor-header-workspace[data-split="true"]) { grid-template-columns: minmax(0, 1fr) 248px minmax(0, 1fr); }
1597
+ }
1598
+ @container editor-panel (max-width: 459px) {
1599
+ #phead { grid-template-columns: minmax(44px, 1fr) minmax(52px, 1fr) auto; }
1600
+ body.textfile-open #phead { grid-template-columns: minmax(0, 1fr) 52px auto; }
1601
+ }
1602
+ @container editor-header (max-width: 640px) {
1603
+ .subformat-register-fields { grid-template-columns: minmax(30px, .75fr) 42px minmax(30px, 1fr); gap: 2px; }
1604
+ .subformat-register-fields .language-select-input { padding-inline: 3px 12px; }
1605
+ .subformat-register-fields .language-select::after { right: 4px; }
1606
+ }
1509
1607
  /* Document metadata is edited in the tree, without changing the row's size. */
1510
1608
  body.edit #nav-groups { --nav-rail: 22px; --nav-icon-half: 9px; }
1511
1609
  .nav-doc-row { padding-left: 12px; gap: 3px; min-height: 38px; }
@@ -1532,6 +1630,15 @@ body.edit #nav-groups { --nav-rail: 22px; --nav-icon-half: 9px; }
1532
1630
  .nav-rename-form input:invalid { outline: 1px solid var(--c-danger); }
1533
1631
  .nav-rename-form input:focus, .nav-new input:focus { outline: 1px solid var(--c-line); }
1534
1632
  @media (forced-colors: active) { .nav-rename-form input:focus, .nav-new input:focus { outline: 1px solid CanvasText; } }
1633
+ .nav-doc-row .nav-rename-form { background: transparent; }
1634
+ .nav-doc-row .nav-rename-form input { border-bottom: 1px solid transparent; border-radius: 0; outline: none; caret-color: var(--c-fg); }
1635
+ .nav-doc-row .nav-rename-form input:focus { border-bottom-color: var(--c-fg-muted); }
1636
+ .nav-doc-row .nav-rename-form input:invalid { border-bottom-color: var(--c-danger); }
1637
+ .nav-doc-row .nav-rename-form input::selection { color: var(--c-fg); background: color-mix(in srgb, var(--c-fg) 22%, var(--c-raised)); }
1638
+ @media (forced-colors: active) {
1639
+ .nav-doc-row .nav-rename-form input:focus { border-bottom-color: Highlight; }
1640
+ .nav-doc-row .nav-rename-form input::selection { color: HighlightText; background: Highlight; }
1641
+ }
1535
1642
  .nav-doc-row.renaming > a { visibility: hidden; }
1536
1643
  .nav-delete:hover, .nav-delete:focus-visible { color: var(--c-danger); }
1537
1644
  #status { flex: 1; min-width: 0; padding: 0 8px; text-align: right; color: var(--c-fg-faint);
@@ -1555,7 +1662,7 @@ body.edit #nav-groups { --nav-rail: 22px; --nav-icon-half: 9px; }
1555
1662
  min-width: 220px; padding: 4px; flex-direction: column; gap: 1px; color: var(--c-fg);
1556
1663
  background: var(--c-surface); border: 1px solid var(--c-line); border-radius: 6px;
1557
1664
  box-shadow: 0 10px 28px var(--c-shadow); font-size: 12.5px; }
1558
- #gear:hover #gearmenu, #gear:focus-within #gearmenu, #gear.open #gearmenu, #gear:has([aria-expanded="true"]) #gearmenu { display: flex; }
1665
+ #gear.open #gearmenu { display: flex; }
1559
1666
  #gearmenu label { display: flex; gap: 10px; align-items: center; cursor: pointer;
1560
1667
  padding: 7px 10px; border-radius: 4px; }
1561
1668
  #gearmenu label:hover { background: var(--c-raised); }
@@ -1606,18 +1713,30 @@ body.edit #nav-groups { --nav-rail: 22px; --nav-icon-half: 9px; }
1606
1713
 
1607
1714
  main.editor-workspace { padding: 0; height: 100vh; display: flex; flex-direction: column; position: sticky; top: 0; }
1608
1715
  #split-preview[aria-pressed="true"] { color: var(--c-accent); background: var(--c-raised); }
1609
- .pane-actions { top: -20px; margin: -20px -24px -36px; }
1716
+ .pane-actions { flex-wrap: wrap; top: -20px; margin: -20px -24px 16px; padding: 4px 12px; min-height: 38px; height: auto; background: var(--c-bg0); }
1717
+ .pane-resource { min-width: 0; }
1610
1718
  #preview-panes { display: flex; flex: 1; min-height: 0; }
1611
1719
  #preview-panes[hidden] { display: none; }
1612
1720
  .preview-pane.resources-pane { min-height: 0; padding-bottom: 24px; }
1613
- .preview-pane.resources-pane:has(.resource-library) { padding-top: 0; }
1721
+ .preview-pane.resources-pane:has(.resource-library) { padding-top: 20px; }
1614
1722
  .resources-pane .resource-tabs { margin-inline: -24px; padding: 0 12px; }
1615
1723
  .preview-pane { flex: 1; min-width: 0; overflow: auto; padding: 20px 24px 50vh; border-top: 2px solid transparent; }
1616
1724
  #preview-panes.split .preview-pane { padding: 16px; }
1617
- #preview-panes.split .pane-actions { top: -16px; margin: -16px -16px -36px; padding-inline: 10px; }
1725
+ #preview-panes.split .pane-actions { top: -16px; margin: -16px -16px 16px; padding-inline: 10px; }
1618
1726
  #preview-panes.split .preview-pane + .preview-pane { border-left: 1px solid var(--c-line); }
1619
1727
  #preview-panes.split .preview-pane.active { border-top-color: var(--c-accent); }
1620
1728
  .preview-pane:focus-visible { outline: 2px solid var(--c-accent); outline-offset: -2px; }
1729
+ @media (max-width: 820px) {
1730
+ body.edit:has(#panel) { display: grid; grid-template-columns: 52px minmax(0, 1fr); grid-template-rows: 50dvh 50dvh; height: 100dvh; min-height: 0; overflow: hidden; }
1731
+ body.edit:has(#panel) #sidebar { grid-column: 1; grid-row: 1 / 3; height: 100dvh; z-index: 10; }
1732
+ body.edit:has(#panel) main.editor-workspace { grid-column: 2; grid-row: 1; height: 100%; min-height: 0; min-width: 0; }
1733
+ body.edit:has(#panel) #panel { grid-column: 2; grid-row: 2; width: auto; height: 100%; min-width: 0; min-height: 0; border-left: 0; border-top: 1px solid var(--c-line); }
1734
+ body.edit:has(#panel) :is(#resize, #sidebar-resize) { display: none; }
1735
+ body.edit:has(#panel) #cm { min-height: 0; }
1736
+ #gearmenu { top: auto; bottom: calc(100% + 6px); max-height: calc(50dvh - 12px); overflow-y: auto; }
1737
+ #preview-panes.split { overflow-x: auto; scroll-snap-type: x mandatory; }
1738
+ #preview-panes.split .preview-pane { flex: 0 0 100%; scroll-snap-align: start; }
1739
+ }
1621
1740
  #preview-language-menu { position: fixed; z-index: 9; min-width: 180px; max-height: min(360px, calc(100vh - 64px)); overflow-y: auto; padding: 6px; background: var(--c-surface); border: 1px solid var(--c-line); border-radius: 10px; box-shadow: 0 10px 28px var(--c-shadow); transform-origin: top right; }
1622
1741
  .language-option { display: flex; align-items: center; gap: 10px; width: 100%; padding: 9px 10px; border: 0; border-radius: 5px; background: transparent; color: var(--c-fg); text-align: left; font: inherit; font-size: 13px; cursor: pointer; }
1623
1742
  .language-option::before { content: ""; width: 14px; flex: none; }
@@ -1750,12 +1869,16 @@ body.corr main article > [data-ln].corr-hi {
1750
1869
 
1751
1870
 
1752
1871
  /* Draft placeholders, the in-sidebar create form, and drag moves */
1753
- .nav-row :is(.new, .nav-delete, .nav-create) { flex: none; width: 20px; height: 24px; display: flex;
1872
+ .nav-row :is(.new, .nav-delete, .nav-create, .nav-rename-save, .nav-rename-cancel) { flex: none; width: 20px; height: 24px; display: flex;
1754
1873
  align-items: center; justify-content: center; border: none; border-radius: 4px; padding: 0;
1755
1874
  background: transparent; color: var(--c-fg-muted); cursor: pointer; opacity: 0; }
1756
1875
  .nav-row:hover :is(.new, .nav-delete), .nav-row:focus-within :is(.new, .nav-delete),
1757
- .nav-row.renaming :is(.new, .nav-delete) { opacity: 1; }
1758
- .nav-row :is(.new, .nav-delete, .nav-create):is(:hover, :focus-visible) { background: var(--c-line); }
1876
+ .nav-row.renaming :is(.nav-rename-save, .nav-rename-cancel) { opacity: 1; }
1877
+ .nav-row.renaming > :is(.new, .nav-delete, .nav-tree-toggle, .nav-tree-spacer) { display: none; }
1878
+ .nav-row :is(.new, .nav-delete, .nav-create, .nav-rename-save, .nav-rename-cancel):is(:hover, :focus-visible) { background: var(--c-line); }
1879
+ .nav-row :is(.nav-rename-save, .nav-rename-cancel):disabled { opacity: .5; cursor: wait; }
1880
+ .nav-row :is(.nav-rename-save, .nav-rename-cancel) svg { width: 15px; height: 15px; }
1881
+ .nav-doc-row .nav-rename-save { margin-right: 3px; }
1759
1882
  .nav-doc-row .nav-tree-toggle, .nav-tree-spacer { width: 18px; margin-right: 3px; }
1760
1883
  .nav-tree-spacer { flex: none; height: 28px; }
1761
1884
  @media (hover: none) { .nav-row :is(.new, .nav-delete) { opacity: 1; } }
@@ -1815,378 +1938,427 @@ body.edit .nav-row { cursor: grab; }
1815
1938
  .nav-row.drop-after { box-shadow: inset 0 -2px 0 var(--c-accent); }
1816
1939
  .nav-row.drop-into > a { background: color-mix(in srgb, var(--c-accent) 18%, transparent); }
1817
1940
  `;
1818
- // Contents of #nav-groups (the doc tree). Used by both page()'s initial render and
1819
- // `GET /api/nav` (edit mode; the client reconciles changed nodes after an md change)
1820
- // (= the same value isn't declared in two places).
1821
- // Each item is a page row and its children list, emitted even when empty
1822
- // (it's the insertion target for the sidebar create form / drag).
1823
- export const navGroupsHtml = (mode, site, currentId, currentRes) => {
1824
- const open = new Set(currentId == null
1825
- ? []
1826
- : [...ancestorsOf(site.entries, currentId).map((e) => e.id), currentId]);
1827
- const list = (parent, depth) => {
1828
- const items = childrenOf(site.entries, parent)
1829
- .map((e) => {
1830
- const label = escapeHtml(docDisplayName(e.frontmatter, e.id));
1831
- const cur = e.id === currentId ? " cur" : "";
1832
- // Top level = nav-link with an icon, descendants = nav-tree-link with guide lines.
1833
- // A doc-specific icon (icons/<id>.svg), if any, replaces the book icon at top
1834
- // level and goes before the label below that.
1835
- let link = depth === 0
1836
- ? `<a class="nav-link${cur}" href="/${e.id}" title="${label}">${e.icon ? svgImg(e.icon, "nav-icon doc-icon") : e.subformat ? SUBFORMATS_ICON : DOCS_ICON}<span class="nav-label">${label}</span></a>`
1837
- : `<a class="nav-tree-link${cur}" href="/${e.id}" title="${label}">${e.icon ? svgImg(e.icon, "doc-icon") : e.subformat ? SUBFORMATS_ICON : DOCS_ICON}<span class="nav-label">${label}</span></a>`;
1838
- let actions = "";
1839
- let editableIcon = "";
1840
- if (mode === "edit") {
1841
- link = `<a class="${depth === 0 ? "nav-link" : "nav-tree-link"}${cur}" href="/${e.id}" title="${label}" aria-keyshortcuts="F2"><span class="nav-doc-name"><span class="nav-label">${label}</span></span></a>`;
1842
- editableIcon = `<span class="nav-doc-icon" title="icon" data-i18n-title="icon">${e.icon ? svgImg(e.icon, "doc-icon") : e.subformat ? SUBFORMATS_ICON : DOCS_ICON}<input type="file" accept=".svg,image/svg+xml" aria-label="icon" data-i18n-aria-label="icon">${e.icon ? '<button class="nav-icon-clear" type="button" title="Remove icon" data-i18n-title="Remove icon" aria-label="Remove icon" data-i18n-aria-label="Remove icon">×</button>' : ""}</span>`;
1843
- actions = `<button class="new" type="button" data-parent="${escapeHtml(e.id)}" popovertarget="nav-page-menu" aria-haspopup="menu" title="Add doc" data-i18n-title="Add doc" aria-label="Add doc" data-i18n-aria-label="Add doc">${PLUS_ICON}</button><button class="nav-delete" type="button" data-doc-action="delete" title="Delete doc" data-i18n-title="Delete doc" aria-label="Delete doc" data-i18n-aria-label="Delete doc">${DELETE_ICON}</button>`;
1941
+ // Contents of #nav-groups (the doc tree). Used by both page()'s initial render and
1942
+ /** Sidebar glyph of a page: its own icon, else its subformat's or Library view's, else the book. */
1943
+ const entryIcon = (e, cls) => {
1944
+ const svg = e.icon ?? e.subformat?.iconSvg;
1945
+ return svg
1946
+ ? svgImg(svg, cls)
1947
+ : e.subformat
1948
+ ? SUBFORMATS_ICON
1949
+ : e.library
1950
+ ? (libraryIcon(e.library) ?? STATICS_ICON)
1951
+ : DOCS_ICON;
1952
+ };
1953
+ // `GET /api/nav` (edit mode; the client reconciles changed nodes after an md change)
1954
+ // (= the same value isn't declared in two places).
1955
+ // Each item is a page row and its children list, emitted even when empty
1956
+ // (it's the insertion target for the sidebar create form / drag).
1957
+ const navGroupsHtml = (mode, site, currentId, currentRes) => {
1958
+ const open = new Set(currentId == null
1959
+ ? []
1960
+ : [...ancestorsOf(site.entries, currentId).map((e) => e.id), currentId]);
1961
+ const list = (parent, depth) => {
1962
+ const items = childrenOf(site.entries, parent)
1963
+ .map((e) => {
1964
+ const label = escapeHtml(docDisplayName(e.frontmatter, e.id));
1965
+ const cur = e.id === currentId ? " cur" : "";
1966
+ // Top level = nav-link with an icon, descendants = nav-tree-link with guide lines.
1967
+ // A doc-specific icon (icons/<id>.svg), if any, replaces the book icon at top
1968
+ // level and goes before the label below that.
1969
+ let link = depth === 0
1970
+ ? `<a class="nav-link${cur}" href="/${e.id}" title="${label}">${entryIcon(e, "nav-icon doc-icon")}<span class="nav-label">${label}</span></a>`
1971
+ : `<a class="nav-tree-link${cur}" href="/${e.id}" title="${label}">${entryIcon(e, "doc-icon")}<span class="nav-label">${label}</span></a>`;
1972
+ let actions = "";
1973
+ let editableIcon = "";
1974
+ if (mode === "edit") {
1975
+ link = `<a class="${depth === 0 ? "nav-link" : "nav-tree-link"}${cur}" href="/${e.id}" title="${label}" aria-keyshortcuts="F2"><span class="nav-doc-name"><span class="nav-label">${label}</span></span></a>`;
1976
+ editableIcon = `<span class="nav-doc-icon" title="icon" data-i18n-title="icon">${entryIcon(e, "doc-icon")}<input type="file" accept=".svg,image/svg+xml" aria-label="icon" data-i18n-aria-label="icon">${e.icon ? '<button class="nav-icon-clear" type="button" title="Remove icon" data-i18n-title="Remove icon" aria-label="Remove icon" data-i18n-aria-label="Remove icon">×</button>' : ""}</span>`;
1977
+ actions = `<button class="new" type="button" data-parent="${escapeHtml(e.id)}" popovertarget="nav-page-menu" aria-haspopup="menu" title="Add doc" data-i18n-title="Add doc" aria-label="Add doc" data-i18n-aria-label="Add doc">${PLUS_ICON}</button><button class="nav-delete" type="button" data-doc-action="delete" title="Delete doc" data-i18n-title="Delete doc" aria-label="Delete doc" data-i18n-aria-label="Delete doc">${DELETE_ICON}</button>`;
1978
+ }
1979
+ const branch = childrenOf(site.entries, e.id).length > 0;
1980
+ const toggle = branch
1981
+ ? `<button class="nav-tree-toggle" type="button" aria-expanded="${open.has(e.id)}" aria-label="Toggle ${label}">${CHEVRON_ICON}</button>`
1982
+ : mode === "edit"
1983
+ ? '<span class="nav-tree-spacer" aria-hidden="true"></span>'
1984
+ : "";
1985
+ return `<div class="nav-item${open.has(e.id) ? " open" : ""}" data-doc-id="${escapeHtml(e.id)}"${e.subformat || e.library ? " data-subformat-nav" : ""}><div class="nav-row${mode === "edit" ? " nav-doc-row" : ""}"${mode === "edit" ? ' draggable="true"' : ""}>${editableIcon}${link}${actions}${toggle}</div>${list(e.id, depth + 1)}</div>`;
1986
+ })
1987
+ .join("");
1988
+ const placeholder = mode === "edit" && depth === 0
1989
+ ? `<div class="nav-item nav-placeholder"><div class="nav-row"><button class="nav-create" type="button" data-parent="" popovertarget="nav-page-menu" aria-haspopup="menu" title="Add doc" data-i18n-title="Add doc" aria-label="Add doc" data-i18n-aria-label="Add doc">${PLUS_ICON}</button></div></div>`
1990
+ : "";
1991
+ return depth === 0
1992
+ ? `<div class="nav-list nav-root" data-parent=""${mode === "edit" ? ' id="nav-docs"' : ""}>${items}${placeholder}</div>`
1993
+ : `<div class="nav-list nav-tree" data-parent="${escapeHtml(parent ?? "")}" style="--nav-depth:${depth + 1}">${items}${placeholder}</div>`;
1994
+ };
1995
+ const html = list(undefined, 0) +
1996
+ (mode === "edit"
1997
+ ? `<template data-page-libraries>${escapeHtml(JSON.stringify([...Object.keys(CODE_TEMPLATES), "urls", "url-previews"].filter((view) => !site.entries.some((entry) => entry.library === view))))}</template><template data-page-subformats>${escapeHtml(JSON.stringify((site.subformats ?? []).filter((format) => !site.entries.some((entry) => entry.subformat?.ext === format.ext))))}</template>${navFilesHtml(site, currentRes)}`
1998
+ : "");
1999
+ return docLinks(site, site.contentLanguage ? languageLinks(html, site.contentLanguage) : html);
2000
+ };
2001
+ // ── Resources (file management in edit mode; linked figures and terms also in preview) ──
2002
+ // Structure: Resources (list page of everything) › kind (list pages for figures / html / icons) › individual file.
2003
+ // Route is `/_files[/<kind>[/<file>]]` (doc ids can't start with `_`, so no collision).
2004
+ const RESOURCE_KINDS = ["markdown", "figures", "html", "icons", "terms"];
2005
+ const siteResources = (site) => [
2006
+ ...site.entries
2007
+ .filter((entry) => !entry.subformat && !entry.library)
2008
+ .map((entry) => ({
2009
+ kind: "markdown",
2010
+ file: entry.file,
2011
+ path: entry.sourceFile ?? CONTENT_PREFIX + entry.file,
2012
+ })),
2013
+ ...site.ctx.terms.map((term) => ({
2014
+ kind: "terms",
2015
+ file: term.id,
2016
+ path: isTermFile(term.id)
2017
+ ? term.id
2018
+ : CONTENT_PREFIX +
2019
+ (site.entries.find((entry) => entry.blocks.some((block) => block.type === "term" && block.entry.id === term.id))?.file ?? ""),
2020
+ })),
2021
+ ...[...site.ctx.figures.values()].map((f) => ({
2022
+ kind: f.kind === "html" ? "html" : "figures",
2023
+ file: f.file.replace(/^figures\//, ""),
2024
+ path: f.file,
2025
+ })),
2026
+ ...site.entries
2027
+ .filter((e) => e.icon != null)
2028
+ .map((e) => ({
2029
+ kind: "icons",
2030
+ file: `${e.id}.svg`,
2031
+ path: e.iconFile ?? `${ICONS_DIR}/${e.id}.svg`,
2032
+ })),
2033
+ ];
2034
+ const resourceHref = (kind, file) => `/_files${kind ? `/${kind}` : ""}${file ? `/${encodeURIComponent(file)}` : ""}`;
2035
+ const navFilesHtml = (site, currentRes) => {
2036
+ const source = site.workspace;
2037
+ const library = currentRes?.startsWith("_library") ||
2038
+ ["codeblocks", "urls", "url-previews", "dictionary", "code"].includes(currentRes ?? "");
2039
+ const hint = `<div class="files-drop-hint" aria-hidden="true">${UPLOAD_ICON}<span data-i18n="Upload files">Upload files</span></div>`;
2040
+ const location = source?.protocol === "git"
2041
+ ? `<summary class="workspace-location" aria-label="Workspace tools" data-i18n-aria-label="Workspace tools" data-workspace-protocol="git" title="${escapeHtml(`${source.repo ?? "repo"}[${source.branch}]`)}">${GIT_ICON}<span class="workspace-address"><span class="git-repo-name">${escapeHtml(source.repo ?? "repo")}</span><span class="git-branch-caption">[${escapeHtml(source.branch)}]</span></span>${CHEVRON_ICON}</summary>`
2042
+ : `<summary class="workspace-location" aria-label="Workspace tools" data-i18n-aria-label="Workspace tools" id="nav-storage" data-workspace-protocol="storage" title="${escapeHtml(workspaceName(site))}">${workspaceIcon(site)}<span class="workspace-address">${escapeHtml(source?.folder ?? "Files")} / ${escapeHtml(source?.service ?? "Local")}</span>${CHEVRON_ICON}</summary>`;
2043
+ const git = source?.protocol === "git" && sharedBranch === undefined
2044
+ ? `<div class="nav-resources" id="nav-git"><div class="nav-item" data-node-id="_git"><div class="nav-row"><a class="nav-link${currentRes === "_git" ? " cur" : ""}" href="/_git" title="Git controls" data-i18n-title="Git controls">${GIT_ICON}<span class="nav-label">Git</span></a></div></div></div>`
2045
+ : "";
2046
+ const extensions = `<div class="nav-resources" id="nav-extensions" data-scope="${createHash("sha256").update(root).digest("hex")}"><div class="nav-item" data-node-id="_extensions"><div class="nav-row"><a class="nav-link${currentRes === "_extensions" ? " cur" : ""}" href="/_extensions" title="Plugins" data-i18n-title="Plugins">${PLUGINS_ICON}<span class="nav-label" data-i18n="Plugins">Plugins</span></a></div></div><div class="extensions-drop-hint" aria-hidden="true">${PLUGINS_ICON}<span data-i18n="Add plugins">Add plugins</span></div></div>`;
2047
+ const subformats = `<div class="nav-resources" id="nav-subformats"><div class="nav-item" data-node-id="_subformats"><div class="nav-row"><a class="nav-link${currentRes === "_subformats" ? " cur" : ""}" href="/_subformats" title="Subformats" data-i18n-title="Subformats">${SUBFORMATS_ICON}<span class="nav-label" data-i18n="Subformats">Subformats</span></a></div></div></div>`;
2048
+ return `<details id="nav-tools" open>${location}<div class="nav-tool-cards"><div class="nav-resources" id="nav-files"><div class="nav-item" data-node-id="_files"><div class="nav-row"><a class="nav-link${currentRes !== undefined && currentRes !== "_git" && currentRes !== "_extensions" && currentRes !== "_subformats" && !library ? " cur" : ""}" href="/_files" title="Files" data-i18n-title="Files">${FOLDER_ICON}<span class="nav-label" data-i18n="Files">Files</span></a><span class="files-upload-status" role="status"></span></div></div>${hint}</div><div class="nav-resources" id="nav-library"><div class="nav-item" data-node-id="_library"><div class="nav-row"><a class="nav-link${library ? " cur" : ""}" href="/_library" title="Library" data-i18n-title="Library">${STATICS_ICON}<span class="nav-label" data-i18n="Library">Library</span></a></div></div></div>${subformats}${git}${extensions}</div></details>`;
2049
+ };
2050
+ const formatSize = (bytes) => bytes < 1024
2051
+ ? `${bytes} B`
2052
+ : bytes < 1024 * 1024
2053
+ ? `${(bytes / 1024).toFixed(1)} KB`
2054
+ : `${(bytes / 1024 / 1024).toFixed(1)} MB`;
2055
+ const sizeOf = (path) => {
2056
+ try {
2057
+ return formatSize(statSync(join(root, path)).size);
2058
+ }
2059
+ catch {
2060
+ return "—";
2061
+ }
2062
+ };
2063
+ // Thumbnail in the lists / preview on the individual page. svg is confined to an img (avoids id
2064
+ // collisions), raster is already <img data:>, and html figures are shown
2065
+ // isolated in a sandboxed iframe.
2066
+ const resourcePreview = (site, r) => {
2067
+ if (r.kind === "markdown") {
2068
+ const entry = site.entries.find((e) => e.file === r.file);
2069
+ return `<pre class="res-markdown">${escapeHtml(entry?.raw ?? "")}</pre>`;
2070
+ }
2071
+ if (r.kind === "terms")
2072
+ return termsHtml(site.ctx.terms.filter((term) => term.id === r.file));
2073
+ if (r.kind === "figures" || r.kind === "html") {
2074
+ const f = site.ctx.figures.get(figureName(r.path));
2075
+ if (!f) {
2076
+ return "";
1844
2077
  }
1845
- const branch = childrenOf(site.entries, e.id).length > 0;
1846
- const toggle = branch
1847
- ? `<button class="nav-tree-toggle" type="button" aria-label="Toggle ${label}">${CHEVRON_ICON}</button>`
1848
- : mode === "edit"
1849
- ? '<span class="nav-tree-spacer" aria-hidden="true"></span>'
1850
- : "";
1851
- return `<div class="nav-item${open.has(e.id) ? " open" : ""}" data-doc-id="${escapeHtml(e.id)}"${e.subformat ? " data-subformat-nav" : ""}><div class="nav-row${mode === "edit" ? " nav-doc-row" : ""}"${mode === "edit" ? ' draggable="true"' : ""}>${editableIcon}${link}${actions}${toggle}</div>${list(e.id, depth + 1)}</div>`;
2078
+ // svg figures are inline, as in the body (figures.ts has already namespaced the ids and
2079
+ // embedded the theme).
2080
+ return f.kind === "image"
2081
+ ? f.markup.replace("<img ", '<img class="res-img" ')
2082
+ : (site.ctx.figurePreview ?? figureFrameHtml)(f, `fig-frame res-${f.kind}`);
2083
+ }
2084
+ const e = site.entries.find((x) => `${x.id}.svg` === r.file);
2085
+ return e?.icon ? svgImg(e.icon, "res-img res-icon") : "";
2086
+ };
2087
+ const resourceUsage = (site, r) => r.kind === "markdown"
2088
+ ? site.entries.filter((e) => e.file === r.file)
2089
+ : r.kind === "figures" || r.kind === "html"
2090
+ ? site.entries.filter((e) => e.figureRefs?.includes(figureName(r.path)))
2091
+ : r.kind === "icons"
2092
+ ? site.entries.filter((e) => `${e.id}.svg` === r.file)
2093
+ : site.entries.filter((e) => e.termRefs?.includes(r.file));
2094
+ const resourceCards = (site, list) => list.length === 0
2095
+ ? ""
2096
+ : `<div class="res-grid">${list
2097
+ .map((r) => {
2098
+ const used = resourceUsage(site, r).length;
2099
+ return `<a class="res-card" href="${resourceHref(r.kind, r.file)}"><div class="res-thumb">${resourcePreview(site, r)}</div><div class="res-meta"><span class="res-name">${escapeHtml(r.file)}</span><span class="res-sub">${sizeOf(r.path)} · used by ${used}</span></div></a>`;
1852
2100
  })
1853
- .join("");
1854
- const placeholder = mode === "edit" && depth === 0
1855
- ? `<div class="nav-item nav-placeholder"><div class="nav-row"><button class="nav-create" type="button" data-parent="" popovertarget="nav-page-menu" aria-haspopup="menu" title="Add doc" data-i18n-title="Add doc" aria-label="Add doc" data-i18n-aria-label="Add doc">${PLUS_ICON}</button></div></div>`
1856
- : "";
1857
- return depth === 0
1858
- ? `<div class="nav-list nav-root" data-parent=""${mode === "edit" ? ' id="nav-docs"' : ""}>${items}${placeholder}</div>`
1859
- : `<div class="nav-list nav-tree" data-parent="${escapeHtml(parent ?? "")}" style="--nav-depth:${depth + 1}">${items}${placeholder}</div>`;
2101
+ .join("")}</div>`;
2102
+ /** Path after `/_files` → main content (unknown → undefined = 404). */
2103
+ const textfilePreview = (site, file, source) => {
2104
+ const language = (file.split(".").at(-1) ?? "text").toLowerCase();
2105
+ const parsed = parseContentSource(language, source, file);
2106
+ const errors = parsed?.errors.map(({ message }) => message) ?? [];
2107
+ if (errors.length)
2108
+ return { html: "", errors };
2109
+ try {
2110
+ return {
2111
+ html: blocksHtml(parsed?.blocks ?? [
2112
+ {
2113
+ type: "code",
2114
+ lang: language,
2115
+ lines: source.split(/\r?\n/),
2116
+ filename: file,
2117
+ },
2118
+ ], site.ctx),
2119
+ errors,
2120
+ };
2121
+ }
2122
+ catch (error) {
2123
+ return { html: "", errors: [error instanceof Error ? error.message : String(error)] };
2124
+ }
1860
2125
  };
1861
- const html = list(undefined, 0) +
1862
- (mode === "edit"
1863
- ? `<template data-page-subformats>${escapeHtml(JSON.stringify((site.subformats ?? []).filter((format) => !site.entries.some((entry) => entry.subformat?.ext === format.ext))))}</template>${navFilesHtml(site, currentRes)}`
1864
- : "");
1865
- return docLinks(site, site.contentLanguage ? languageLinks(html, site.contentLanguage) : html);
1866
- };
1867
- // ── Resources (file management in edit mode; linked figures and terms also in preview) ──
1868
- // Structure: Resources (list page of everything) › kind (list pages for figures / html / icons) › individual file.
1869
- // Route is `/_files[/<kind>[/<file>]]` (doc ids can't start with `_`, so no collision).
1870
- const RESOURCE_KINDS = ["markdown", "figures", "html", "icons", "terms"];
1871
- const siteResources = (site) => [
1872
- ...site.entries
1873
- .filter((entry) => !entry.subformat)
1874
- .map((entry) => ({
1875
- kind: "markdown",
1876
- file: entry.file,
1877
- path: entry.sourceFile ?? CONTENT_PREFIX + entry.file,
1878
- })),
1879
- ...site.ctx.terms.map((term) => ({
1880
- kind: "terms",
1881
- file: term.id,
1882
- path: isTermFile(term.id)
1883
- ? term.id
1884
- : CONTENT_PREFIX +
1885
- (site.entries.find((entry) => entry.blocks.some((block) => block.type === "term" && block.entry.id === term.id))?.file ?? ""),
1886
- })),
1887
- ...[...site.ctx.figures.values()].map((f) => ({
1888
- kind: f.kind === "html" ? "html" : "figures",
1889
- file: f.file.replace(/^figures\//, ""),
1890
- path: f.file,
1891
- })),
1892
- ...site.entries
1893
- .filter((e) => e.icon != null)
1894
- .map((e) => ({
1895
- kind: "icons",
1896
- file: `${e.id}.svg`,
1897
- path: e.iconFile ?? `${ICONS_DIR}/${e.id}.svg`,
1898
- })),
1899
- ];
1900
- const resourceHref = (kind, file) => `/_files${kind ? `/${kind}` : ""}${file ? `/${encodeURIComponent(file)}` : ""}`;
1901
- const navFilesHtml = (site, currentRes) => {
1902
- const source = site.workspace;
1903
- const statics = currentRes?.startsWith("_statics") ||
1904
- ["codeblocks", "urls", "url-previews", "dictionary", "code"].includes(currentRes ?? "");
1905
- const hint = `<div class="files-drop-hint" aria-hidden="true">${UPLOAD_ICON}<span data-i18n="Upload files">Upload files</span></div>`;
1906
- const location = source?.protocol === "git"
1907
- ? `<summary class="workspace-location" aria-label="Workspace tools" data-i18n-aria-label="Workspace tools" data-workspace-protocol="git" title="${escapeHtml(`${source.repo ?? "repo"}[${source.branch}]`)}">${GIT_ICON}<span class="workspace-address"><span class="git-repo-name">${escapeHtml(source.repo ?? "repo")}</span><span class="git-branch-caption">[${escapeHtml(source.branch)}]</span></span>${CHEVRON_ICON}</summary>`
1908
- : `<summary class="workspace-location" aria-label="Workspace tools" data-i18n-aria-label="Workspace tools" id="nav-storage" data-workspace-protocol="storage" title="${escapeHtml(workspaceName(site))}">${workspaceIcon(site)}<span class="workspace-address">${escapeHtml(source?.folder ?? "Files")} / ${escapeHtml(source?.service ?? "Local")}</span>${CHEVRON_ICON}</summary>`;
1909
- const git = source?.protocol === "git"
1910
- ? `<div class="nav-resources" id="nav-git"><div class="nav-item" data-node-id="_git"><div class="nav-row"><a class="nav-link${currentRes === "_git" ? " cur" : ""}" href="/_git" title="Git controls" data-i18n-title="Git controls">${GIT_ICON}<span class="nav-label">Git</span></a></div></div></div>`
1911
- : "";
1912
- const extensions = `<div class="nav-resources" id="nav-extensions" data-scope="${createHash("sha256").update(root).digest("hex")}"><div class="nav-item" data-node-id="_extensions"><div class="nav-row"><a class="nav-link${currentRes === "_extensions" ? " cur" : ""}" href="/_extensions" title="Plugins" data-i18n-title="Plugins">${PLUGINS_ICON}<span class="nav-label" data-i18n="Plugins">Plugins</span></a></div></div><div class="extensions-drop-hint" aria-hidden="true">${PLUGINS_ICON}<span data-i18n="Add plugins">Add plugins</span></div></div>`;
1913
- const subformats = `<div class="nav-resources" id="nav-subformats"><div class="nav-item" data-node-id="_subformats"><div class="nav-row"><a class="nav-link${currentRes === "_subformats" ? " cur" : ""}" href="/_subformats" title="Subformats" data-i18n-title="Subformats">${SUBFORMATS_ICON}<span class="nav-label" data-i18n="Subformats">Subformats</span></a></div></div></div>`;
1914
- return `<details id="nav-tools" open>${location}<div class="nav-tool-cards"><div class="nav-resources" id="nav-files"><div class="nav-item" data-node-id="_files"><div class="nav-row"><a class="nav-link${currentRes !== undefined && currentRes !== "_git" && currentRes !== "_extensions" && currentRes !== "_subformats" && !statics ? " cur" : ""}" href="/_files" title="Files" data-i18n-title="Files">${FOLDER_ICON}<span class="nav-label" data-i18n="Files">Files</span></a><span class="files-upload-status" role="status"></span></div></div>${hint}</div><div class="nav-resources" id="nav-statics"><div class="nav-item" data-node-id="_statics"><div class="nav-row"><a class="nav-link${statics ? " cur" : ""}" href="/_statics" title="Statics" data-i18n-title="Statics">${STATICS_ICON}<span class="nav-label" data-i18n="Statics">Statics</span></a></div></div></div>${subformats}${git}${extensions}</div></details>`;
1915
- };
1916
- const formatSize = (bytes) => bytes < 1024
1917
- ? `${bytes} B`
1918
- : bytes < 1024 * 1024
1919
- ? `${(bytes / 1024).toFixed(1)} KB`
1920
- : `${(bytes / 1024 / 1024).toFixed(1)} MB`;
1921
- const sizeOf = (path) => {
1922
- try {
1923
- return formatSize(statSync(join(root, path)).size);
1924
- }
1925
- catch {
1926
- return "—";
1927
- }
1928
- };
1929
- // Thumbnail in the lists / preview on the individual page. svg is confined to an img (avoids id
1930
- // collisions), raster is already <img data:>, and html figures are shown
1931
- // isolated in a sandboxed iframe.
1932
- const resourcePreview = (site, r) => {
1933
- if (r.kind === "markdown") {
1934
- const entry = site.entries.find((e) => e.file === r.file);
1935
- return `<pre class="res-markdown">${escapeHtml(entry?.raw ?? "")}</pre>`;
1936
- }
1937
- if (r.kind === "terms")
1938
- return termsHtml(site.ctx.terms.filter((term) => term.id === r.file));
1939
- if (r.kind === "figures" || r.kind === "html") {
1940
- const f = site.ctx.figures.get(figureName(r.path));
1941
- if (!f) {
1942
- return "";
1943
- }
1944
- // svg figures are inline, as in the body (figures.ts has already namespaced the ids and
1945
- // embedded the theme).
1946
- return f.kind === "image"
1947
- ? f.markup.replace("<img ", '<img class="res-img" ')
1948
- : (site.ctx.figurePreview ?? figureFrameHtml)(f, `fig-frame res-${f.kind}`);
1949
- }
1950
- const e = site.entries.find((x) => `${x.id}.svg` === r.file);
1951
- return e?.icon ? svgImg(e.icon, "res-img res-icon") : "";
1952
- };
1953
- const resourceUsage = (site, r) => r.kind === "markdown"
1954
- ? site.entries.filter((e) => e.file === r.file)
1955
- : r.kind === "figures" || r.kind === "html"
1956
- ? site.entries.filter((e) => e.figureRefs?.includes(figureName(r.path)))
1957
- : r.kind === "icons"
1958
- ? site.entries.filter((e) => `${e.id}.svg` === r.file)
1959
- : site.entries.filter((e) => e.termRefs?.includes(r.file));
1960
- const resourceCards = (site, list) => list.length === 0
1961
- ? ""
1962
- : `<div class="res-grid">${list
1963
- .map((r) => {
1964
- const used = resourceUsage(site, r).length;
1965
- return `<a class="res-card" href="${resourceHref(r.kind, r.file)}"><div class="res-thumb">${resourcePreview(site, r)}</div><div class="res-meta"><span class="res-name">${escapeHtml(r.file)}</span><span class="res-sub">${sizeOf(r.path)} · used by ${used}</span></div></a>`;
1966
- })
1967
- .join("")}</div>`;
1968
- /** Path after `/_files` → main content (unknown → undefined = 404). */
1969
- const textfilePreview = (site, file, source) => {
1970
- const language = (file.split(".").at(-1) ?? "text").toLowerCase();
1971
- const parsed = parseContentSource(language, source, file);
1972
- const errors = parsed?.errors.map(({ message }) => message) ?? [];
1973
- if (errors.length)
1974
- return { html: "", errors };
1975
- try {
1976
- return {
1977
- html: blocksHtml(parsed?.blocks ?? [
1978
- { type: "code", lang: language, lines: source.split(/\r?\n/), filename: file },
1979
- ], site.ctx),
1980
- errors,
1981
- };
1982
- }
1983
- catch (error) {
1984
- return { html: "", errors: [error instanceof Error ? error.message : String(error)] };
1985
- }
1986
- };
1987
- export const textfilePreviewHtml = (site, file, source) => {
1988
- const { html, errors } = textfilePreview(site, file, source);
1989
- return errors.length
1990
- ? `<div class="errors" role="status">${errors.map(escapeHtml).join("<br>")}</div>`
1991
- : html;
1992
- };
1993
- export const textfilePreviewErrors = (site, file, source) => {
1994
- const errors = textfilePreview(site, file, source).errors;
1995
- try {
1996
- validateSubformatFile(root, file, source, site.previews?.domains);
1997
- }
1998
- catch (error) {
1999
- errors.push(error instanceof Error ? error.message : String(error));
2000
- }
2001
- if (/\.(md|markdown)$/i.test(file)) {
2002
- const { doc, source: parsed } = compileDraft(draftContext(site), file, source);
2003
- errors.push(...parsed.errors);
2126
+ const textfilePreviewHtml = (site, file, source) => {
2127
+ const { html, errors } = textfilePreview(site, file, source);
2128
+ return errors.length
2129
+ ? `<div class="errors" role="status">${errors.map(escapeHtml).join("<br>")}</div>`
2130
+ : html;
2131
+ };
2132
+ const textfilePreviewErrors = (site, file, source) => {
2133
+ const errors = textfilePreview(site, file, source).errors;
2004
2134
  try {
2005
- blocksHtml(doc.blocks, site.ctx);
2135
+ validateSubformatFile(root, file, source, site.previews?.domains);
2006
2136
  }
2007
2137
  catch (error) {
2008
2138
  errors.push(error instanceof Error ? error.message : String(error));
2009
2139
  }
2010
- }
2011
- return errors;
2012
- };
2013
- export const resourcesMain = (site, rest) => {
2014
- if (rest === "_extensions")
2015
- return {
2016
- title: "Plugins",
2017
- main: '<article class="res-page resource-library"><div id="extensions-manager"></div></article>',
2018
- };
2019
- if (rest === "_git")
2020
- return site.workspace?.protocol === "git"
2021
- ? {
2022
- title: `${site.workspace.repo ?? "repo"} [${site.workspace.branch}]`,
2023
- main: '<article class="res-page resource-library git-page"><div id="git-manager"></div></article>',
2140
+ if (/\.(md|markdown)$/i.test(file)) {
2141
+ const { doc, source: parsed } = compileDraft(draftContext(site), file, source);
2142
+ errors.push(...parsed.errors);
2143
+ try {
2144
+ blocksHtml(doc.blocks, site.ctx);
2024
2145
  }
2025
- : undefined;
2026
- if (rest === "_statics" || rest.startsWith("_statics/")) {
2027
- const view = rest.slice("_statics".length).replace(/^\//, "") || "codeblocks";
2028
- return ["codeblocks", "urls", "url-previews", "dictionary", "code"].includes(view)
2029
- ? resourcesMain(site, view)
2030
- : undefined;
2031
- }
2032
- const all = siteResources(site);
2033
- const [kind, ...tail] = rest === "" ? [] : rest.split("/");
2034
- const file = tail.length > 0 ? decodeURIComponent(tail.join("/")) : undefined;
2035
- if (kind == null) {
2036
- return {
2037
- title: workspaceName(site),
2038
- main: `<article class="res-page files-page resource-library"><div id="files-manager"></div></article>`,
2039
- };
2040
- }
2041
- if (!file && (kind === "dictionary" || kind === "code"))
2042
- return resourcesMain(site, "codeblocks");
2043
- if (!file &&
2044
- (kind === "codeblocks" ||
2045
- kind === "urls" ||
2046
- kind === "url-previews" ||
2047
- kind === "_subformats")) {
2048
- const index = resourceIndex(root, site.filePaths ?? filesSnapshot(root).files.map((item) => item.path), site.previews?.domains);
2049
- if (site.workspace?.protocol === "git" && index.subformats.length)
2050
- setSubformatChanges(root, index.subformats);
2051
- return {
2052
- title: kind === "_subformats" ? "Subformats" : "Statics",
2053
- main: `<article class="res-page files-page resource-library">${kind === "_subformats" ? "" : resourceTabs(kind)}${resourceLibraryHtml(index, kind === "_subformats" ? "subformats" : kind)}</article>`,
2054
- };
2055
- }
2056
- if (kind === "file" && file) {
2057
- const resource = all.find((item) => item.path === file);
2058
- if (resource)
2059
- return resourcesMain(site, `${resource.kind}/${encodeURIComponent(resource.file)}`);
2146
+ catch (error) {
2147
+ errors.push(error instanceof Error ? error.message : String(error));
2148
+ }
2149
+ }
2150
+ return errors;
2151
+ };
2152
+ /** Only files in the project snapshot are readable, which also rejects traversal and dotfiles. */
2153
+ const readProjectFile = (file) => {
2060
2154
  try {
2061
- if (!filesSnapshot(root).files.some((item) => item.path === file))
2062
- return undefined;
2063
- const content = readFileSync(textfilePath(root, file));
2064
- let preview = "";
2065
- let sourceFile;
2066
- if (/\.(svg|png|jpe?g|gif|webp)$/i.test(file)) {
2067
- const extension = file.split(".").pop()?.toLowerCase();
2068
- const mime = extension === "svg" ? "svg+xml" : extension === "jpg" ? "jpeg" : extension;
2069
- preview = `<img alt="" src="data:image/${mime};base64,${content.toString("base64")}">`;
2070
- if (extension === "svg")
2071
- sourceFile = file;
2155
+ return filesSnapshot(root).files.some((item) => item.path === file)
2156
+ ? readFileSync(textfilePath(root, file))
2157
+ : undefined;
2158
+ }
2159
+ catch {
2160
+ return undefined;
2161
+ }
2162
+ };
2163
+ const filePage = (site, file, content, download = site.ctx.downloads?.get(file)) => {
2164
+ let preview = "";
2165
+ let sourceFile;
2166
+ if (/\.(svg|png|jpe?g|gif|webp)$/i.test(file)) {
2167
+ const extension = file.split(".").pop()?.toLowerCase();
2168
+ const mime = extension === "svg" ? "svg+xml" : extension === "jpg" ? "jpeg" : extension;
2169
+ preview = `<img alt="" src="data:image/${mime};base64,${content.toString("base64")}">`;
2170
+ if (extension === "svg")
2171
+ sourceFile = file;
2172
+ }
2173
+ else if (/\.(mp4|webm|ogg)$/i.test(file)) {
2174
+ preview = `<video data-dooc-video controls playsinline preload="metadata" aria-label="Video preview" src="data:video/${file.split(".").pop()};base64,${content.toString("base64")}"></video>`;
2175
+ }
2176
+ else {
2177
+ try {
2178
+ const source = new TextDecoder("utf-8", { fatal: true }).decode(content);
2179
+ if (source.includes("\0"))
2180
+ throw new Error("Binary file");
2181
+ sourceFile = file;
2182
+ // The heading carries the download, so blocks do not repeat it.
2183
+ preview = textfilePreviewHtml({ ...site, ctx: { ...site.ctx, downloads: undefined } }, file, source);
2072
2184
  }
2073
- else if (/\.(mp4|webm|ogg)$/i.test(file)) {
2074
- preview = `<video data-dooc-video controls playsinline preload="metadata" aria-label="Video preview" src="data:video/${file.split(".").pop()};base64,${content.toString("base64")}"></video>`;
2185
+ catch {
2186
+ preview = BOX_ICON;
2075
2187
  }
2076
- else {
2077
- try {
2078
- const source = new TextDecoder("utf-8", { fatal: true }).decode(content);
2079
- if (source.includes("\0"))
2080
- throw new Error("Binary file");
2081
- sourceFile = file;
2082
- preview = textfilePreviewHtml(site, file, source);
2083
- }
2084
- catch {
2085
- preview = BOX_ICON;
2188
+ }
2189
+ return {
2190
+ title: file,
2191
+ sourceFile,
2192
+ main: `<article class="res-page res-file-page"><nav class="res-crumbs"><a href="/_files">${workspaceText(site)}</a></nav><h1>${escapeHtml(file)}${download ? resourceDownloadHtml(file, download) : ""}</h1><div class="res-preview${sourceFile ? " res-text-preview" : ""}">${preview}</div></article>`,
2193
+ };
2194
+ };
2195
+ const resourcesMain = (site, rest) => {
2196
+ const download = (file) => {
2197
+ const href = site.ctx.downloads?.get(file);
2198
+ return href ? resourceDownloadHtml(file, href) : "";
2199
+ };
2200
+ if (rest === "_extensions")
2201
+ return {
2202
+ title: "Plugins",
2203
+ main: '<article class="res-page resource-library"><div id="extensions-manager"></div></article>',
2204
+ };
2205
+ if (rest === "_git")
2206
+ return site.workspace?.protocol === "git" && sharedBranch === undefined
2207
+ ? {
2208
+ title: `${site.workspace.repo ?? "repo"} [${site.workspace.branch}]`,
2209
+ main: '<article class="res-page resource-library git-page"><div id="git-manager"></div></article>',
2086
2210
  }
2087
- }
2211
+ : undefined;
2212
+ if (rest === "_library" || rest.startsWith("_library/")) {
2213
+ const view = rest.slice("_library".length).replace(/^\//, "") || "codeblocks";
2214
+ return ["codeblocks", "urls", "url-previews", "dictionary", "code"].includes(view)
2215
+ ? resourcesMain(site, view)
2216
+ : undefined;
2217
+ }
2218
+ const all = siteResources(site);
2219
+ const [kind, ...tail] = rest === "" ? [] : rest.split("/");
2220
+ const file = tail.length > 0 ? decodeURIComponent(tail.join("/")) : undefined;
2221
+ if (kind == null) {
2088
2222
  return {
2089
- title: file,
2090
- sourceFile,
2091
- main: `<article class="res-page res-file-page"><nav class="res-crumbs"><a href="/_files">${workspaceText(site)}</a></nav><h1>${escapeHtml(file)}</h1><div class="res-preview${sourceFile ? " res-text-preview" : ""}">${preview}</div></article>`,
2223
+ title: workspaceName(site),
2224
+ main: `<article class="res-page files-page resource-library"><div id="files-manager"></div></article>`,
2092
2225
  };
2093
2226
  }
2094
- catch {
2227
+ if (!file && (kind === "dictionary" || kind === "code"))
2228
+ return resourcesMain(site, "codeblocks");
2229
+ if (!file &&
2230
+ (kind === "codeblocks" ||
2231
+ kind === "urls" ||
2232
+ kind === "url-previews" ||
2233
+ kind === "_subformats")) {
2234
+ const index = resourceIndex(root, site.filePaths ?? filesSnapshot(root).files.map((item) => item.path), site.previews?.domains);
2235
+ if (site.workspace?.protocol === "git" && index.subformats.length)
2236
+ setSubformatChanges(root, index.subformats);
2237
+ return {
2238
+ title: kind === "_subformats" ? "Subformats" : "Library",
2239
+ main: `<article class="res-page files-page resource-library">${kind === "_subformats" ? "" : resourceTabs(kind)}${resourceLibraryHtml(index, kind === "_subformats" ? "subformats" : kind)}</article>`,
2240
+ };
2241
+ }
2242
+ if (kind === "file" && file) {
2243
+ const resource = all.find((item) => item.path === file);
2244
+ if (resource)
2245
+ return resourcesMain(site, `${resource.kind}/${encodeURIComponent(resource.file)}`);
2246
+ const content = readProjectFile(file);
2247
+ return content && filePage(site, file, content);
2248
+ }
2249
+ if (!RESOURCE_KINDS.includes(kind)) {
2095
2250
  return undefined;
2096
2251
  }
2097
- }
2098
- if (!RESOURCE_KINDS.includes(kind)) {
2099
- return undefined;
2100
- }
2101
- const k = kind;
2102
- const crumbs = `<nav class="res-crumbs"><a href="/_files">${workspaceText(site)}</a> › ${file ? `<a href="${resourceHref(k)}" data-i18n="${k}">${k}</a> › ${escapeHtml(file)}` : k}</nav>`;
2103
- if (file == null) {
2252
+ const k = kind;
2253
+ const crumbs = `<nav class="res-crumbs"><a href="/_files">${workspaceText(site)}</a> › ${file ? `<a href="${resourceHref(k)}" data-i18n="${k}">${k}</a> › ${escapeHtml(file)}` : k}</nav>`;
2254
+ if (file == null) {
2255
+ return {
2256
+ title: `${k} — ${workspaceName(site)}`,
2257
+ main: `<article class="res-page">${k === "terms" ? "" : crumbs}<h1 data-i18n="${k}">${translate("eng", k)}</h1>${k === "terms"
2258
+ ? termsHtml(site.ctx.terms, resolveLanguage(site.contentLanguage ?? site.defaultLang, site.languages), true)
2259
+ : resourceCards(site, all.filter((r) => r.kind === k))}</article>`,
2260
+ };
2261
+ }
2262
+ const r = all.find((x) => x.kind === k && x.file === file);
2263
+ if (!r) {
2264
+ return undefined;
2265
+ }
2266
+ const fig = k === "figures" || k === "html" ? site.ctx.figures.get(figureName(r.path)) : undefined;
2267
+ const used = resourceUsage(site, r);
2268
+ const snippet = k === "terms"
2269
+ ? isTermFile(r.file)
2270
+ ? `[](${termFileUrl(r.file)})`
2271
+ : undefined
2272
+ : fig
2273
+ ? `![](${r.path})`
2274
+ : undefined;
2275
+ const rows = [
2276
+ ["path", `<code>${escapeHtml(r.path)}</code>`],
2277
+ ["size", sizeOf(r.path)],
2278
+ ...(fig ? [["kind", fig.kind]] : []),
2279
+ ...(fig?.title ? [["title", escapeHtml(fig.title)]] : []),
2280
+ ...(fig?.desc ? [["desc", escapeHtml(fig.desc)]] : []),
2281
+ ...(snippet
2282
+ ? [["syntax", `<code class="res-snippet">${escapeHtml(snippet)}</code>`]]
2283
+ : []),
2284
+ [
2285
+ k === "icons" || k === "markdown" ? "doc" : "used in",
2286
+ used.length === 0
2287
+ ? `<span class="res-sub" data-i18n="none">none</span>`
2288
+ : used
2289
+ .map((e) => `<a href="/${e.id}">${escapeHtml(docDisplayName(e.frontmatter, e.id))}</a>`)
2290
+ .join(", "),
2291
+ ],
2292
+ ];
2104
2293
  return {
2105
- title: `${k} — ${workspaceName(site)}`,
2106
- main: `<article class="res-page">${k === "terms" ? "" : crumbs}<h1 data-i18n="${k}">${translate("eng", k)}</h1>${k === "terms"
2107
- ? termsHtml(site.ctx.terms, resolveLanguage(site.contentLanguage ?? site.defaultLang, site.languages), true)
2108
- : resourceCards(site, all.filter((r) => r.kind === k))}</article>`,
2294
+ title: `${r.file} — Files`,
2295
+ ...(/\.(?:svg|html|termth|md|markdown)$/i.test(r.path) ? { sourceFile: r.path } : {}),
2296
+ main: `<article class="res-page res-file-page">${crumbs}<h1>${escapeHtml(r.file)}${download(r.path)}</h1><div class="res-preview${k === "icons" ? " square" : ""}">${resourcePreview(site, r)}</div><details class="res-details"><summary data-i18n="File details">File details</summary><dl class="res-dl">${rows.map(([dt, dd]) => `<dt data-i18n="${dt}">${dt}</dt><dd>${dd}</dd>`).join("")}</dl></details></article>`,
2109
2297
  };
2110
- }
2111
- const r = all.find((x) => x.kind === k && x.file === file);
2112
- if (!r) {
2113
- return undefined;
2114
- }
2115
- const fig = k === "figures" || k === "html" ? site.ctx.figures.get(figureName(r.path)) : undefined;
2116
- const used = resourceUsage(site, r);
2117
- const snippet = k === "terms"
2118
- ? isTermFile(r.file)
2119
- ? `[](${termFileUrl(r.file)})`
2120
- : undefined
2121
- : fig
2122
- ? `![](${r.path})`
2123
- : undefined;
2124
- const rows = [
2125
- ["path", `<code>${escapeHtml(r.path)}</code>`],
2126
- ["size", sizeOf(r.path)],
2127
- ...(fig ? [["kind", fig.kind]] : []),
2128
- ...(fig?.title ? [["title", escapeHtml(fig.title)]] : []),
2129
- ...(fig?.desc ? [["desc", escapeHtml(fig.desc)]] : []),
2130
- ...(snippet ? [["syntax", `<code class="res-snippet">${escapeHtml(snippet)}</code>`]] : []),
2131
- [
2132
- k === "icons" || k === "markdown" ? "doc" : "used in",
2133
- used.length === 0
2134
- ? `<span class="res-sub" data-i18n="none">none</span>`
2135
- : used
2136
- .map((e) => `<a href="/${e.id}">${escapeHtml(docDisplayName(e.frontmatter, e.id))}</a>`)
2137
- .join(", "),
2138
- ],
2139
- ];
2140
- return {
2141
- title: `${r.file} — Files`,
2142
- ...(/\.(?:svg|html|termth|md|markdown)$/i.test(r.path) ? { sourceFile: r.path } : {}),
2143
- main: `<article class="res-page res-file-page">${crumbs}<h1>${escapeHtml(r.file)}</h1><div class="res-preview${k === "icons" ? " square" : ""}">${resourcePreview(site, r)}</div><details class="res-details"><summary data-i18n="File details">File details</summary><dl class="res-dl">${rows.map(([dt, dd]) => `<dt data-i18n="${dt}">${dt}</dt><dd>${dd}</dd>`).join("")}</dl></details></article>`,
2144
2298
  };
2145
- };
2146
- const figurePage = (site, fig) => {
2147
- const title = fig.title ?? fig.file;
2148
- return {
2149
- title,
2150
- main: docHtml({ title }, [{ type: "figureRef", name: fig.name }], [], site.ctx),
2299
+ const figurePage = (site, fig) => {
2300
+ const title = fig.title ?? fig.file;
2301
+ return {
2302
+ title,
2303
+ main: docHtml({ title }, [{ type: "figureRef", name: fig.name }], [], site.ctx),
2304
+ };
2151
2305
  };
2152
- };
2153
- // Browser tab title — shared by page() and `/api/page` (doc switching via client-side navigation).
2154
- const pageTitle = (mode, title, siteTitle) => title === siteTitle ? title : `${title} — ${siteTitle ?? `dooc ${mode}`}`;
2155
- // Navigation follows the manifest hierarchy via routing.docPath.
2156
- const page = (mode, site, opts) => {
2157
- const nav = navGroupsHtml(mode, site, opts.currentId, opts.currentRes);
2158
- const siteTitle = escapeHtml(site.title ?? "dooc");
2159
- const iconImg = `<img id="site-icon" alt=""${site.icon ? ` src="${svgDataUri(site.icon)}"` : " hidden"}>`;
2160
- const iconVariants = Object.entries(site.iconVariants ?? {});
2161
- // The base image sits in a wrapper so theme switching and edit-client's #site-icon.hidden never fight.
2162
- const iconHtml = iconVariants.length
2163
- ? `<span class="site-icon-variants" data-theme-variants><span data-theme-variant="">${iconImg}</span>${iconVariants.map(([theme, svg]) => `<img data-theme-variant="${escapeHtml(theme)}" alt="" src="${svgDataUri(svg)}" hidden>`).join("")}</span>`
2164
- : iconImg;
2165
- const siteIcon = `<span id="site-icon-slot"${mode === "edit" ? ' title="Change site icon" data-i18n-title="Change site icon"' : ""}>${iconHtml}${DOCS_ICON}${mode === "edit" ? '<input type="file" accept=".svg,image/svg+xml" aria-label="Change site icon" data-i18n-aria-label="Change site icon">' : ""}</span>`;
2166
- const bootScripts = opts.boot != null
2167
- ? `<script id="boot" type="application/json">${JSON.stringify(opts.boot).replace(/</g, "\\u003c")}</script>
2168
- <script src="/assets/edit.js"></script>`
2169
- : !opts.publish
2170
- ? '<script src="/assets/ui.js"></script>'
2171
- : opts.publish.subformatJs
2172
- ? `<script>${inlineScript(opts.publish.subformatJs)}</script>`
2173
- : "";
2174
- // Interaction layer of the schema graph (zoom / pan / box drag / enlarged view). Shared by
2175
- // preview / edit. Figures are readable without JS, so defer is enough (= progressive
2176
- // enhancement).
2177
- const main = opts.boot != null
2178
- ? `<main class="editor-workspace">
2306
+ /** View-mode page for a file that a document links to; catalog figures keep their framed page. */
2307
+ const linkedFilePage = (site, file) => {
2308
+ const fig = [...site.ctx.figures.values()].find((fig) => fig.file === file);
2309
+ if (fig)
2310
+ return figurePage(site, fig);
2311
+ const content = (site.readLinkedFile ?? readProjectFile)(file);
2312
+ if (!content)
2313
+ return undefined;
2314
+ // Builds only map exported dependencies, so link-only files are embedded here.
2315
+ const page = filePage(site, file, content, site.ctx.downloads &&
2316
+ (site.ctx.downloads.get(file) ??
2317
+ `data:application/octet-stream;base64,${content.toString("base64")}`));
2318
+ // Breadcrumbs lead to the editor's file manager, which view mode does not serve.
2319
+ return {
2320
+ title: page.title,
2321
+ main: page.main.replace(/<nav class="res-crumbs">.*?<\/nav>/, ""),
2322
+ };
2323
+ };
2324
+ // Browser tab title — shared by page() and `/api/page` (doc switching via client-side navigation).
2325
+ const pageTitle = (mode, title, siteTitle) => title === siteTitle ? title : `${title} — ${siteTitle ?? `dooc ${mode}`}`;
2326
+ // Navigation follows the manifest hierarchy via routing.docPath.
2327
+ const page = (mode, site, opts) => {
2328
+ const nav = navGroupsHtml(mode, site, opts.currentId, opts.currentRes);
2329
+ const siteTitle = escapeHtml(site.title ?? "dooc");
2330
+ const iconImg = `<img id="site-icon" alt=""${site.icon ? ` src="${svgDataUri(site.icon)}"` : " hidden"}>`;
2331
+ const iconVariants = Object.entries(site.iconVariants ?? {});
2332
+ // The base image sits in a wrapper so theme switching and edit-client's #site-icon.hidden never fight.
2333
+ const iconHtml = iconVariants.length
2334
+ ? `<span class="site-icon-variants" data-theme-variants><span data-theme-variant="">${iconImg}</span>${iconVariants.map(([theme, svg]) => `<img data-theme-variant="${escapeHtml(theme)}" alt="" src="${svgDataUri(svg)}" hidden>`).join("")}</span>`
2335
+ : iconImg;
2336
+ const siteIcon = `<span id="site-icon-slot"${mode === "edit" ? ' title="Change site icon" data-i18n-title="Change site icon"' : ""}>${iconHtml}${DOCS_ICON}${mode === "edit" ? '<input type="file" accept=".svg,image/svg+xml" aria-label="Change site icon" data-i18n-aria-label="Change site icon">' : ""}</span>`;
2337
+ const bootScripts = opts.boot != null
2338
+ ? `<script id="boot" type="application/json">${JSON.stringify(opts.boot).replace(/</g, "\\u003c")}</script>
2339
+ <script src="/assets/edit.js"></script>
2340
+ <script src="/assets/client.js"></script>`
2341
+ : !opts.publish
2342
+ ? '<script src="/assets/ui.js"></script>'
2343
+ : opts.publish.subformatJs
2344
+ ? `<script>${inlineScript(opts.publish.subformatJs)}</script>`
2345
+ : "";
2346
+ // Interaction layer of the schema graph (zoom / pan / box drag / enlarged view). Shared by
2347
+ // preview / edit. Figures are readable without JS, so defer is enough (= progressive
2348
+ // enhancement).
2349
+ const main = opts.boot != null
2350
+ ? `<main class="editor-workspace">
2179
2351
 
2180
2352
 
2181
2353
  <div id="preview-language-menu" role="menu" aria-label="Change language" data-i18n-aria-label="Change language" hidden></div>
2182
2354
  <div id="preview-panes"${opts.currentRes !== undefined ? " hidden" : ""}><section class="preview-pane active" tabindex="0" aria-label="Active pane" data-i18n-aria-label="Active pane"><div class="pane-actions"><button class="pbtn" type="button" data-theme-picker="document" aria-label="Preview theme"></button>${fontButton("viewer")}<button class="pbtn pane-language" type="button" aria-haspopup="menu" aria-expanded="false" aria-controls="preview-language-menu" aria-label="Change language" data-i18n-aria-label="Change language" title="Change language" data-i18n-title="Change language">${GLOBE_ICON}</button></div><div class="preview-content">${opts.main}</div></section></div></main>`
2183
- : mode === "edit" && opts.currentRes !== undefined
2184
- ? `<main class="resources-pane">${opts.main}</main>`
2185
- : `<main><div class="page-actions"><button class="pbtn" type="button" data-theme-picker="document" aria-label="Preview theme"></button>${fontButton("viewer")}</div>${opts.main}</main>`;
2186
- const graphScript = opts.publish
2187
- ? `<script>${inlineScript(opts.publish.graphJs)}</script>`
2188
- : `<script>(${loadPreviewScript.toString()})("/assets/graph.js", "svg[data-sg-layout], [data-mermaid]", "module");</script>`;
2189
- return `<!doctype html><html lang="en"><head><meta charset="utf-8">
2355
+ : mode === "edit" && opts.currentRes !== undefined
2356
+ ? `<main class="resources-pane">${opts.main}</main>`
2357
+ : `<main><div class="page-actions"><button class="pbtn" type="button" data-theme-picker="document" aria-label="Preview theme"></button>${fontButton("viewer")}</div>${opts.main}</main>`;
2358
+ const graphScript = opts.publish
2359
+ ? `<script>${inlineScript(opts.publish.graphJs)}</script>`
2360
+ : `<script>(${loadPreviewScript.toString()})("/assets/graph.js", "svg[data-sg-layout], [data-mermaid]", "module");</script>`;
2361
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8">
2190
2362
  ${opts.publish ? `<meta name="referrer" content="no-referrer"><meta http-equiv="x-dns-prefetch-control" content="off">${opts.publish.network ? "" : `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline' data:; img-src data: blob:; media-src data: blob:; object-src data:; font-src data: blob:; frame-src data: blob:; connect-src 'none'; base-uri 'none'; form-action 'none'">`}` : ""}
2191
2363
  <meta name="viewport" content="width=device-width, initial-scale=1">
2192
2364
  <title>${escapeHtml(pageTitle(mode, opts.title, site.title))}</title>
@@ -2194,10 +2366,11 @@ ${opts.publish ? `<meta name="referrer" content="no-referrer"><meta http-equiv="
2194
2366
  (${initializeThemes.toString()})(${JSON.stringify(site.themes)});
2195
2367
  (${mountFigureFrames.toString()})(document);</script>
2196
2368
  <style>${fontCss(Boolean(opts.publish))}${CSS}${mode === "edit" ? EDIT_CSS : ""}</style></head>
2197
- <body${mode === "edit" ? ' class="edit"' : ""}${site.sourceBase ? ` data-source-base="${escapeHtml(site.sourceBase)}"` : ""}><nav id="sidebar"><div id="sidebar-resize" class="panel-resize" role="separator" tabindex="0" aria-orientation="vertical" aria-controls="sidebar" aria-label="Resize sidebar" data-i18n-aria-label="Resize sidebar" title="Resize sidebar" data-i18n-title="Resize sidebar"></div><div id="sidebar-head">${siteIcon}<div id="site-title" class="site-title" title="${siteTitle}"${mode === "edit" ? ` data-title="${escapeHtml(site.title ?? "")}" tabindex="0" role="button" aria-label="Edit site title" data-i18n-aria-label="Edit site title"` : ""}>${siteTitle}</div><button id="sidebar-toggle" type="button" aria-controls="sidebar-content" aria-expanded="true" title="Close sidebar" data-i18n-title="Close sidebar">${SIDEBAR_ICON}</button></div><div id="sidebar-content"><div id="nav-groups">${nav}</div><div id="nav-status" role="status" aria-live="polite"></div></div></nav>${main}${opts.aside ?? ""}
2369
+ <body${mode === "edit" ? ' class="edit"' : ""}${site.ctx.downloads ? " data-easy-download" : ""}${site.sourceBase ? ` data-source-base="${escapeHtml(site.sourceBase)}"` : ""}><nav id="sidebar"><div id="sidebar-resize" class="panel-resize" role="separator" tabindex="0" aria-orientation="vertical" aria-controls="sidebar" aria-label="Resize sidebar" data-i18n-aria-label="Resize sidebar" title="Resize sidebar" data-i18n-title="Resize sidebar"></div><div id="sidebar-head">${siteIcon}<div id="site-title" class="site-title" title="${siteTitle}"${mode === "edit" ? ` data-title="${escapeHtml(site.title ?? "")}" tabindex="0" role="button" aria-label="Edit site title" data-i18n-aria-label="Edit site title"` : ""}>${siteTitle}</div><button id="sidebar-toggle" type="button" aria-controls="sidebar-content" aria-expanded="true" title="Close sidebar" data-i18n-title="Close sidebar">${SIDEBAR_ICON}</button></div><div id="sidebar-content"><div id="nav-groups">${nav}</div><div id="nav-status" role="status" aria-live="polite"></div></div></nav>${main}${opts.aside ?? ""}
2198
2370
  <script>
2199
2371
  (${mountThemePickers.toString()})(${JSON.stringify(THEME_ICONS)}, ${JSON.stringify(site.themes)});
2200
2372
  (${mountThemeVariants.toString()})(document);
2373
+ ${site.ctx.downloads ? `(${mountResourceDownloads.toString()})(${workspaceFetch.toString()});` : ""}
2201
2374
  </script>
2202
2375
  ${bootScripts}${graphScript}
2203
2376
  <script id="code-grammars" type="application/json"${opts.publish ? "" : ' data-src="/assets/code-grammars.json"'}>${opts.publish ? JSON.stringify(site.codeGrammars ?? []).replace(/</g, "\\u003c") : "[]"}</script>
@@ -2206,12 +2379,12 @@ ${opts.publish ? `<script>${inlineScript(opts.publish.codeJs)}</script>` : `<scr
2206
2379
  // Functions toString'd under tsx (esbuild keepNames) contain __name(...) calls; define a no-op.
2207
2380
  var __name = (f) => f;
2208
2381
  const contentLanguage = () => JSON.parse(document.getElementById("boot")?.textContent || "null")?.contentLanguage || ${JSON.stringify(site.contentLanguage ?? site.defaultLang)};
2209
- const localeFetch = (url, init = {}) => fetch(url, { ...init, headers: { ...init.headers, "x-docs-language": contentLanguage() } });
2382
+ const localeFetch = (url, init = {}) => (${workspaceFetch.toString()})(url, { ...init, headers: { ...init.headers, "x-docs-language": contentLanguage() } });
2210
2383
  (${mountTerms.toString()})(document);
2211
2384
  (${mountTables.toString()})(document);
2212
2385
  (${mountToc.toString()})(document);
2213
2386
  (${mountVideos.toString()})(document);
2214
- ${opts.publish ? "" : `(${mountFigurePreviews.toString()})();`}
2387
+ ${opts.publish ? "" : `(${mountFigurePreviews.toString()})(${workspaceFetch.toString()});`}
2215
2388
  void (${mountFontPickers.toString()})(${createFontSettings.toString()}, ${JSON.stringify(site.fonts ?? []).replace(/</g, "\\u003c")});
2216
2389
  (() => {
2217
2390
  const KEY = "docs:sidebar-open";
@@ -2223,7 +2396,7 @@ void (${mountFontPickers.toString()})(${createFontSettings.toString()}, ${JSON.s
2223
2396
  toggle.dataset.i18nTitle = open ? "Close sidebar" : "Open sidebar";
2224
2397
  toggle.title = window.__docsTranslate ? window.__docsTranslate(toggle.dataset.i18nTitle) : toggle.dataset.i18nTitle;
2225
2398
  };
2226
- const narrow = matchMedia("(max-width: 600px)");
2399
+ const narrow = matchMedia("(max-width: ${opts.boot ? 820 : 600}px)");
2227
2400
  let preferred;
2228
2401
  try { const saved = localStorage.getItem(KEY); if (saved !== null) preferred = saved !== "0"; } catch {}
2229
2402
  let open = !narrow.matches && preferred !== false;
@@ -2283,7 +2456,7 @@ void (${mountFontPickers.toString()})(${createFontSettings.toString()}, ${JSON.s
2283
2456
  new ResizeObserver(() => (${focusNavTree.toString()})(nav)).observe(nav);
2284
2457
  })();
2285
2458
  ${mode === "edit"
2286
- ? `(() => {
2459
+ ? `(() => {
2287
2460
  // Sidebar tree editing stays delegated while navigation nodes are reconciled.
2288
2461
  // drag: top 1/4 of a row = before, bottom 1/4 = after, middle = move into that doc's children
2289
2462
  // (at the end). The DOM isn't moved, only a marker is shown; on drop, POST /api/move →
@@ -2301,7 +2474,7 @@ ${mode === "edit"
2301
2474
  if (window.__docsRefreshNav) return window.__docsRefreshNav();
2302
2475
  const cur = document.querySelector("#nav-groups .nav-row a.cur");
2303
2476
  const id = (cur && cur.closest(".nav-item").dataset.docId) || "";
2304
- const rp = location.pathname.startsWith("/_statics") ? location.pathname.slice(1) : ["/_git", "/_extensions", "/_subformats"].includes(location.pathname) ? location.pathname.slice(1) : location.pathname.startsWith("/_files") ? location.pathname.slice(8).replace(/^\\/|\\/$/g, "") : null;
2477
+ const rp = location.pathname.startsWith("/_library") ? location.pathname.slice(1) : ["/_git", "/_extensions", "/_subformats"].includes(location.pathname) ? location.pathname.slice(1) : location.pathname.startsWith("/_files") ? location.pathname.slice(8).replace(/^\\/|\\/$/g, "") : null;
2305
2478
  const res = await localeFetch("/api/nav?current=" + encodeURIComponent(id) + (rp == null ? "" : "&res=" + encodeURIComponent(rp)));
2306
2479
  if (res.ok) {
2307
2480
  const data = await res.json();
@@ -2315,9 +2488,11 @@ ${mode === "edit"
2315
2488
  if (window.__docsNavRestore) window.__docsNavRestore();
2316
2489
  document.dispatchEvent(new Event("docs:ui-refresh"));
2317
2490
  };
2318
- const post = async (path, body) => {
2491
+ const context = () => ({ workspace: globalThis.__doocConnections?.active, language: contentLanguage() });
2492
+ const current = (target) => target.workspace === globalThis.__doocConnections?.active && target.language === contentLanguage();
2493
+ const post = async (path, body, target = context()) => {
2319
2494
  // Tell HMR, so the watch notification for our own write (dooc.yaml etc.) doesn't reload.
2320
- const res = await localeFetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
2495
+ const res = await (${workspaceFetch.toString()})(path, { method: "POST", headers: { "content-type": "application/json", "x-docs-language": target.language }, body: JSON.stringify(body) }, target.workspace);
2321
2496
  const data = await res.json().catch(() => ({}));
2322
2497
  if (!res.ok) throw new Error(data.error || String(res.status));
2323
2498
  return data;
@@ -2343,6 +2518,7 @@ ${mode === "edit"
2343
2518
  docAction(button.closest(".nav-item"), button.dataset.docAction);
2344
2519
  });
2345
2520
  const editSiteTitle = (label) => {
2521
+ const target = context();
2346
2522
  if (document.querySelector(".nav-rename-form")) return;
2347
2523
  const original = label.textContent;
2348
2524
  const baseTitle = label.dataset.title || null;
@@ -2387,7 +2563,8 @@ ${mode === "edit"
2387
2563
  busy = true;
2388
2564
  input.readOnly = true;
2389
2565
  try {
2390
- const result = await post("/api/site-title", { title: input.value, baseTitle, language: new URL(location.href).searchParams.get("lang") });
2566
+ const result = await post("/api/site-title", { title: input.value, baseTitle, language: target.language }, target);
2567
+ if (!current(target)) { close(); return; }
2391
2568
  closed = true;
2392
2569
  form.remove();
2393
2570
  label.textContent = label.title = result.title;
@@ -2422,6 +2599,7 @@ ${mode === "edit"
2422
2599
  document.addEventListener("dblclick", editLabel);
2423
2600
  document.addEventListener("keydown", (event) => { if (event.key === "F2" || (event.key === "Enter" && event.target.id === "site-title")) editLabel(event); });
2424
2601
  const setIcon = async (slot, file) => {
2602
+ const target = context();
2425
2603
  if (file && !/\\.svg$/i.test(file.name) && file.type !== "image/svg+xml") {
2426
2604
  setStatus("Icon must be svg", true);
2427
2605
  return;
@@ -2429,7 +2607,8 @@ ${mode === "edit"
2429
2607
  const id = slot.closest(".nav-item")?.dataset.docId;
2430
2608
  try {
2431
2609
  const data = file ? btoa(Array.from(new Uint8Array(await file.arrayBuffer()), (byte) => String.fromCharCode(byte)).join("")) : null;
2432
- const result = await post(id ? "/api/icon" : "/api/site-icon", { file: id ? id + ".md" : undefined, data, theme: getComputedStyle(document.documentElement).colorScheme === "dark" ? "dark" : "light" });
2610
+ const result = await post(id ? "/api/icon" : "/api/site-icon", { file: id ? id + ".md" : undefined, data, theme: getComputedStyle(document.documentElement).colorScheme === "dark" ? "dark" : "light" }, target);
2611
+ if (!current(target)) return;
2433
2612
  if (!id) {
2434
2613
  const logo = document.getElementById("site-icon");
2435
2614
  logo.src = result.icon;
@@ -2473,6 +2652,7 @@ ${mode === "edit"
2473
2652
  void setIcon(slot, file);
2474
2653
  });
2475
2654
 
2655
+ let dragContext;
2476
2656
  let dragged = null;
2477
2657
  let drop = null; // { row, zone: "before" | "after" | "into" }
2478
2658
  const clearMarker = () => {
@@ -2487,6 +2667,7 @@ ${mode === "edit"
2487
2667
  event.preventDefault();
2488
2668
  return;
2489
2669
  }
2670
+ dragContext = context();
2490
2671
  dragged = row.closest(".nav-item");
2491
2672
  dragged.classList.add("dragging");
2492
2673
  event.dataTransfer.effectAllowed = "move";
@@ -2533,7 +2714,8 @@ ${mode === "edit"
2533
2714
  clearMarker();
2534
2715
  setStatus("Moving…", false);
2535
2716
  try {
2536
- await post("/api/move", { id, parent, index });
2717
+ await post("/api/move", { id, parent, index }, dragContext);
2718
+ if (!current(dragContext)) return;
2537
2719
  setStatus("Moved", false);
2538
2720
  } catch (error) {
2539
2721
  setStatus("Failed to move: " + error.message, true);
@@ -2545,9 +2727,11 @@ ${mode === "edit"
2545
2727
 
2546
2728
  // ── Page type menu and in-sidebar create form ──
2547
2729
  const suggestFileName = ${suggestDocFileName.toString()};
2730
+ const availableLibraries = () => JSON.parse(document.querySelector("[data-page-libraries]")?.content.textContent || "[]");
2548
2731
  const availableSubformats = () => JSON.parse(document.querySelector("[data-page-subformats]")?.content.textContent || "[]");
2549
2732
  const closeForm = () => { for (const f of document.querySelectorAll(".nav-new-item")) f.remove(); };
2550
2733
  const openForm = (trigger) => {
2734
+ const target = context();
2551
2735
  closeForm();
2552
2736
  const parent = trigger.dataset.parent || "";
2553
2737
  const host = parent
@@ -2600,7 +2784,8 @@ ${mode === "edit"
2600
2784
  submit.setAttribute("aria-busy", "true");
2601
2785
  err.textContent = "";
2602
2786
  try {
2603
- await post("/api/create", { parent: parent || undefined, title: title.value.trim(), name: nameInput.value.trim() });
2787
+ await post("/api/create", { parent: parent || undefined, title: title.value.trim(), name: nameInput.value.trim() }, target);
2788
+ if (!current(target)) return;
2604
2789
  closeForm();
2605
2790
  await refresh();
2606
2791
  } catch (error) {
@@ -2620,14 +2805,22 @@ ${mode === "edit"
2620
2805
  menu.setAttribute("role", "menu");
2621
2806
  menu.setAttribute("aria-label", t("Page type"));
2622
2807
  menu.dataset.i18nAriaLabel = "Page type";
2623
- menu.innerHTML = '<button type="button" role="menuitem" tabindex="-1" data-page-type="markdown">${DOCS_ICON}Markdown</button><button type="button" role="menuitem" tabindex="-1" data-page-type="subformat" aria-haspopup="menu" popovertarget="nav-subformat-menu">${SUBFORMATS_ICON}Subformat<span class="nav-page-chevron">${CHEVRON_ICON}</span></button><div id="nav-subformat-menu" class="subformat-picker-menu subformat-setting-menu" role="menu" aria-label="Subformat" popover="auto"></div><p class="err" role="alert"></p>';
2808
+ menu.innerHTML = '<button type="button" role="menuitem" tabindex="-1" data-page-type="markdown">${DOCS_ICON}Markdown</button><button type="button" role="menuitem" tabindex="-1" data-page-type="subformat" aria-haspopup="menu" popovertarget="nav-subformat-menu">${SUBFORMATS_ICON}Subformat<span class="nav-page-chevron">${CHEVRON_ICON}</span></button><button type="button" role="menuitem" tabindex="-1" data-page-type="library" aria-haspopup="menu">${STATICS_ICON}Library<span class="nav-page-chevron">${CHEVRON_ICON}</span></button><div id="nav-subformat-menu" class="subformat-picker-menu subformat-setting-menu" role="menu" aria-label="Subformat" popover="auto"></div><p class="err" role="alert"></p>';
2624
2809
  document.body.append(menu);
2625
2810
  const formatsMenu = menu.querySelector("#nav-subformat-menu");
2626
2811
  const formatTrigger = menu.querySelector('[data-page-type="subformat"]');
2812
+ const libraryTrigger = menu.querySelector('[data-page-type="library"]');
2627
2813
  const markdownTrigger = menu.querySelector('[data-page-type="markdown"]');
2628
2814
  const menuError = menu.querySelector(".err");
2629
2815
  let menuTrigger;
2630
2816
  let addingPage = false;
2817
+ document.addEventListener("dooc:workspace-changed", () => {
2818
+ closeForm();
2819
+ if (formatsMenu.matches(":popover-open")) formatsMenu.hidePopover();
2820
+ if (menu.matches(":popover-open")) menu.hidePopover();
2821
+ clearMarker();
2822
+ dragged = null;
2823
+ });
2631
2824
  const showMenu = (popup, trigger) => {
2632
2825
  popup.style.maxHeight = "";
2633
2826
  popup.showPopover();
@@ -2648,12 +2841,15 @@ ${mode === "edit"
2648
2841
  menu.hidePopover();
2649
2842
  openForm(menuTrigger);
2650
2843
  });
2651
- formatTrigger.addEventListener("click", (event) => {
2844
+ let pageKind = "subformat";
2845
+ const libraryIcons = ${JSON.stringify(LIBRARY_ICONS)};
2846
+ const openPages = (trigger, kind, names) => (event) => {
2652
2847
  event.preventDefault();
2653
2848
  if (addingPage) return;
2654
- if (formatsMenu.matches(":popover-open")) { formatsMenu.hidePopover(); return; }
2849
+ if (formatsMenu.matches(":popover-open")) { formatsMenu.hidePopover(); if (pageKind === kind) return; }
2850
+ pageKind = kind;
2655
2851
  formatsMenu.replaceChildren();
2656
- for (const format of availableSubformats()) {
2852
+ for (const name of names()) {
2657
2853
  const row = document.createElement("div");
2658
2854
  row.className = "subformat-setting-option";
2659
2855
  row.setAttribute("role", "none");
@@ -2661,25 +2857,30 @@ ${mode === "edit"
2661
2857
  option.type = "button";
2662
2858
  option.tabIndex = -1;
2663
2859
  option.setAttribute("role", "menuitem");
2664
- option.dataset.subformat = format.ext;
2665
- option.textContent = format.ext;
2860
+ option.dataset.page = name;
2861
+ option.textContent = name;
2862
+ if (kind === "library" && Object.hasOwn(libraryIcons, name)) option.insertAdjacentHTML("afterbegin", libraryIcons[name]);
2666
2863
  row.append(option);
2667
2864
  formatsMenu.append(row);
2668
2865
  }
2669
- showMenu(formatsMenu, formatTrigger);
2670
- });
2866
+ showMenu(formatsMenu, trigger);
2867
+ };
2868
+ formatTrigger.addEventListener("click", openPages(formatTrigger, "subformat", () => availableSubformats().map((format) => format.ext)));
2869
+ libraryTrigger.addEventListener("click", openPages(libraryTrigger, "library", availableLibraries));
2671
2870
  formatsMenu.addEventListener("click", async (event) => {
2672
- const option = event.target.closest("button[data-subformat]");
2871
+ const option = event.target.closest("button[data-page]");
2673
2872
  if (!option || addingPage) return;
2873
+ const target = context();
2674
2874
  const parent = menuTrigger.dataset.parent || undefined;
2675
- const subformat = option.dataset.subformat;
2676
- addingPage = markdownTrigger.disabled = formatTrigger.disabled = true;
2875
+ const page = option.dataset.page;
2876
+ addingPage = markdownTrigger.disabled = formatTrigger.disabled = libraryTrigger.disabled = true;
2677
2877
  menu.setAttribute("aria-busy", "true");
2678
2878
  menuError.textContent = "";
2679
2879
  setStatus("", false);
2680
2880
  formatsMenu.hidePopover();
2681
2881
  try {
2682
- const result = await post("/api/create", { parent, subformat, title: subformat });
2882
+ const result = await post("/api/create", { parent, [pageKind]: page, title: page }, target);
2883
+ if (!current(target)) return;
2683
2884
  menu.hidePopover();
2684
2885
  await refresh();
2685
2886
  if (result.path) {
@@ -2690,7 +2891,7 @@ ${mode === "edit"
2690
2891
  menuError.textContent = error.message;
2691
2892
  if (!menu.matches(":popover-open")) setStatus(error.message, true);
2692
2893
  } finally {
2693
- addingPage = markdownTrigger.disabled = false;
2894
+ addingPage = markdownTrigger.disabled = libraryTrigger.disabled = false;
2694
2895
  formatTrigger.disabled = !availableSubformats().length;
2695
2896
  menu.removeAttribute("aria-busy");
2696
2897
  if (menu.matches(":popover-open")) formatTrigger.focus();
@@ -2730,7 +2931,7 @@ ${mode === "edit"
2730
2931
  showMenu(menu, btn);
2731
2932
  });
2732
2933
  })();`
2733
- : ""}
2934
+ : ""}
2734
2935
  // code block copy — delegated to document so it keeps working after edit's innerHTML swaps.
2735
2936
  document.addEventListener("click", async (event) => {
2736
2937
  const button = event.target instanceof Element ? event.target.closest("button.section-copy") : null;
@@ -2765,7 +2966,7 @@ document.addEventListener("click", (ev) => {
2765
2966
  // Code blocks toggle from their border label.
2766
2967
  document.addEventListener("click", (ev) => {
2767
2968
  const head = ev.target instanceof Element ? ev.target.closest(".codeblk-head") : null;
2768
- if (!head || (ev.target instanceof Element && ev.target.closest("button.codecopy"))) return;
2969
+ if (!head || (ev.target instanceof Element && ev.target.closest("button.codecopy, a.resource-download"))) return;
2769
2970
  const wrap = head.closest(".codeblk");
2770
2971
  if (!wrap) return;
2771
2972
  const collapsed = wrap.classList.toggle("collapsed");
@@ -2781,14 +2982,14 @@ document.addEventListener("click", (ev) => {
2781
2982
  }
2782
2983
  });
2783
2984
  </script>
2784
- <script>${inlineScript(`(${mountSearch.toString()})(${JSON.stringify(opts.publish ? searchIndex(site) : []).replace(/</g, "\\u003c")}, ${searchSections.toString()}, ${JSON.stringify(Object.fromEntries(SEARCH_LABELS.map((key) => [key, translate(site.defaultLang, key)]))).replace(/</g, "\\u003c")}, ${Boolean(opts.publish)});`)}</script>
2785
- ${opts.publish ? `${opts.publish.pages}<script>${publishRouterScript(opts.publish.first)}${opts.publish.network && !opts.publish.pluginJs ? `\n(${mountBundleNetwork.toString()})();` : ""}</script>${opts.publish.pluginJs ? `<script>${inlineScript(opts.publish.pluginJs)}</script>` : ""}` : `<script>${hmrClientScript(mode)}</script>`}</body></html>`;
2786
- };
2787
- // A `</script` inside an inline <script> would close the script early, so escape it.
2788
- const inlineScript = (js) => js.replace(/<\/(script)/gi, "<\\/$1");
2789
- // Router for the published output — keeps each route's main content in <template data-route>
2790
- // and swaps <main> based on location.hash (`#/<ancestor/.../docId>[#<anchor>]`) (works without a server).
2791
- const publishRouterScript = (first) => `
2985
+ <script>${inlineScript(`(${mountSearch.toString()})(${JSON.stringify(opts.publish ? searchIndex(site) : []).replace(/</g, "\\u003c")}, ${searchSections.toString()}, ${JSON.stringify(Object.fromEntries(SEARCH_LABELS.map((key) => [key, translate(site.defaultLang, key)]))).replace(/</g, "\\u003c")}, ${Boolean(opts.publish)}, ${workspaceFetch.toString()});`)}</script>
2986
+ ${opts.publish ? `${opts.publish.pages}<script>${publishRouterScript(opts.publish.first)}${opts.publish.network && !opts.publish.pluginJs ? `\n(${mountBundleNetwork.toString()})();` : ""}</script>${opts.publish.pluginJs ? `<script>${inlineScript(opts.publish.pluginJs)}</script>` : ""}` : ""}</body></html>`;
2987
+ };
2988
+ // A `</script` inside an inline <script> would close the script early, so escape it.
2989
+ const inlineScript = (js) => js.replace(/<\/(script)/gi, "<\\/$1");
2990
+ // Router for the published output — keeps each route's main content in <template data-route>
2991
+ // and swaps <main> based on location.hash (`#/<ancestor/.../docId>[#<anchor>]`) (works without a server).
2992
+ const publishRouterScript = (first) => `
2792
2993
  (() => {
2793
2994
  const FIRST = ${JSON.stringify(first)};
2794
2995
  const main = document.querySelector("main");
@@ -2821,626 +3022,530 @@ const publishRouterScript = (first) => `
2821
3022
  window.addEventListener("hashchange", show);
2822
3023
  show();
2823
3024
  })();`;
2824
- // Maps the server's absolute-path links (`/<route>`) and in-body anchors (`#<id>`) to the
2825
- // published output's hash routes.
2826
- const toHashLinks = (html, route) => html
2827
- .replace(/(href|data-section-url)="\/(?!\/)/g, '$1="#/')
2828
- .replace(/href="#(?!\/)/g, `href="#/${route}#`);
2829
- /**
2830
- * Turns the whole Site into a single HTML file readable without a server (everything embedded,
2831
- * down to figures / terms / schema graph JS). Each doc is held in a
2832
- * <template> and switched via hash routes.
2833
- */
2834
- export const publishHtml = (site, graphJs, title = site.title ?? "dooc", codeJs = "", mode = "static", pluginJs = "", subformatJs = "") => {
2835
- const pages = site.entries.map((e) => ({
2836
- route: docPath(site.entries, e.id).slice(1),
2837
- title: docDisplayName(e.frontmatter, e.id),
2838
- main: entryMain(site, e),
2839
- }));
2840
- const first = pages[0]?.route ?? "";
2841
- if (site.ctx.terms.length > 0) {
2842
- const terms = resourcesMain(site, "terms");
2843
- if (terms)
2844
- pages.push({ route: "_files/terms", ...terms });
2845
- }
2846
- const figureRefs = new Set(site.entries.flatMap((entry) => entry.figureRefs ?? []));
2847
- for (const name of figureRefs) {
2848
- const fig = site.ctx.figures.get(name);
2849
- if (!fig)
2850
- continue;
2851
- const route = `_files/file/${encodeURIComponent(fig.file)}`;
2852
- pages.push({ route, ...figurePage(site, fig) });
2853
- }
2854
- const templates = pages
2855
- .map((p) => `<template data-route="${escapeHtml(p.route)}" data-title="${escapeHtml(pageTitle("preview", p.title, title))}">${toHashLinks(p.main, p.route)}</template>`)
2856
- .join("");
2857
- return toHashLinks(page("preview", { ...site, title }, {
2858
- title,
2859
- main: "",
2860
- publish: {
2861
- graphJs,
2862
- codeJs,
2863
- pages: templates,
2864
- first,
2865
- network: mode !== "static",
2866
- pluginJs: mode === "live" ? pluginJs : undefined,
2867
- subformatJs,
2868
- },
2869
- }), first);
2870
- };
2871
- // A doc's main content. A doc with an empty body and children (a chapter-heading-only doc) shows
2872
- // its children list in place of the body.
2873
- const entryMain = (site, e) => {
2874
- const html = renderEntryHtml(site, e).html;
2875
- const kids = childrenOf(site.entries, e.id);
2876
- if (e.subformat || e.blocks.length > 0 || kids.length === 0) {
2877
- return html;
2878
- }
2879
- const items = kids
2880
- .map((k) => `<li><a href="${docPath(site.entries, k.id)}">${escapeHtml(docDisplayName(k.frontmatter, k.id))}</a></li>`)
2881
- .join("");
2882
- return html.replace(/<\/article>\s*$/, `<ul class="idx">${items}</ul></article>`);
2883
- };
2884
- export const languageFieldHtml = (defaultLang, language = contentLanguageCode(defaultLang), translatedLanguages = [contentLanguageCode(defaultLang)], declaredLanguages) => {
2885
- const existing = new Set(translatedLanguages);
2886
- const options = [...contentLanguages]
2887
- .filter(({ code }) => !declaredLanguages || declaredLanguages.includes(code))
2888
- .sort((a, b) => Number(existing.has(b.code)) - Number(existing.has(a.code)))
2889
- .map(({ code, name }) => `<option value="${code}" data-name="${escapeHtml(name)}" data-added="${existing.has(code)}"${code === language ? " selected" : ""}>${escapeHtml(name)} (${code})</option>`)
2890
- .join("");
2891
- return `<div class="fm-language"><button class="pbtn" type="button" data-language-open aria-label="Change language" data-i18n-aria-label="Change language" aria-haspopup="listbox" aria-expanded="false" aria-controls="fm-lang-options">${GLOBE_ICON}</button><select id="fm-lang" data-source="${contentLanguageCode(defaultLang)}" aria-label="Change language" data-i18n-aria-label="Change language">${options}</select></div>`;
2892
- };
2893
- // The same thing is passed for the initial render (editorAside) and doc switch (`/api/page`)
2894
- // (= the client only has to handle one boot shape, initially and after a switch).
2895
- export const editorBoot = (entry, site) => {
2896
- // Completion candidates are files in the figures/ catalog.
2897
- const figures = [...site.ctx.figures.values()].map((f) => f.file);
2898
- const docs = site.entries
2899
- .filter((e) => !e.subformat)
2900
- .map((e) => ({
2901
- ref: e.sourceFile ?? CONTENT_PREFIX + e.file,
2902
- title: docDisplayName(e.frontmatter, e.id),
2903
- }));
2904
- return {
2905
- gitBase: entryGitBase(entry, site),
2906
- ...(site.title === undefined ? {} : { siteTitle: site.title }),
2907
- ...(site.icon === undefined ? {} : { siteIcon: svgDataUri(site.icon) }),
2908
- ...(entry.frontmatter?.lang ? { docLanguage: entry.frontmatter.lang } : {}),
2909
- ...(entry.translatedLanguages ? { translatedLanguages: entry.translatedLanguages } : {}),
2910
- ...(site.contentLanguage
2911
- ? {
2912
- contentLanguage: site.contentLanguage,
2913
- sourceLanguage: contentLanguageCode(site.defaultLang),
2914
- }
2915
- : {}),
2916
- file: entry.file,
2917
- sourceFile: entry.sourceFile,
2918
- docId: entry.id,
2919
- title: entry.frontmatter?.title ?? "",
2920
- path: docPath(site.entries, entry.id),
2921
- body: entry.body,
2922
- figures,
2923
- codeLanguages: site.codeLanguages ?? CODE_LANGS,
2924
- docs,
2925
- terms: [...site.ctx.terms],
2926
- blockLines: entry.blockLines,
2927
- baseRaw: entry.raw,
2928
- icon: entry.icon ? svgDataUri(entry.icon) : null,
2929
- defaultLang: site.defaultLang,
2930
- spellcheckLang: resolveLanguage(entry.lang, site.languages).spellcheckLang ?? entry.lang,
2931
- filePreviews: filePreviewResults(entry, site),
2932
- previews: site.previews,
3025
+ // Maps the server's absolute-path links (`/<route>`) and in-body anchors (`#<id>`) to the
3026
+ // published output's hash routes.
3027
+ const toHashLinks = (html, route) => html
3028
+ .replace(/(href|data-section-url)="\/(?!\/)/g, '$1="#/')
3029
+ .replace(/href="#(?!\/)/g, `href="#/${route}#`);
3030
+ /**
3031
+ * Turns the whole Site into a single HTML file readable without a server (everything embedded,
3032
+ * down to figures / terms / schema graph JS). Each doc is held in a
3033
+ * <template> and switched via hash routes.
3034
+ */
3035
+ const publishHtml = (site, graphJs, title = site.title ?? "dooc", codeJs = "", mode = "static", pluginJs = "", subformatJs = "") => {
3036
+ const pages = site.entries.map((e) => ({
3037
+ route: docPath(site.entries, e.id).slice(1),
3038
+ title: docDisplayName(e.frontmatter, e.id),
3039
+ main: entryMain(site, e),
3040
+ }));
3041
+ const first = pages[0]?.route ?? "";
3042
+ if (site.ctx.terms.length > 0) {
3043
+ const terms = resourcesMain(site, "terms");
3044
+ if (terms)
3045
+ pages.push({ route: "_files/terms", ...terms });
3046
+ }
3047
+ const figureRefs = new Set(site.entries.flatMap((entry) => entry.figureRefs ?? []));
3048
+ for (const name of figureRefs) {
3049
+ const fig = site.ctx.figures.get(name);
3050
+ if (!fig)
3051
+ continue;
3052
+ const route = `_files/file/${encodeURIComponent(fig.file)}`;
3053
+ pages.push({ route, ...figurePage(site, fig) });
3054
+ }
3055
+ // Linked files get their previewer page too.
3056
+ // shortcut: file names containing HTML-escaped characters (& < > " ') get no page, decode entities if needed
3057
+ const routes = new Set(pages.map((p) => p.route));
3058
+ for (const [, encoded] of pages
3059
+ .map((p) => p.main)
3060
+ .join("")
3061
+ .matchAll(/href="\/(_files\/file\/[^"#&]+)/g)) {
3062
+ if (!encoded || routes.has(encoded))
3063
+ continue;
3064
+ routes.add(encoded);
3065
+ const linked = linkedFilePage(site, decodeURIComponent(encoded.slice("_files/file/".length)));
3066
+ if (linked)
3067
+ pages.push({ route: encoded, ...linked });
3068
+ }
3069
+ const templates = pages
3070
+ .map((p) => `<template data-route="${escapeHtml(p.route)}" data-title="${escapeHtml(pageTitle("preview", p.title, title))}">${toHashLinks(p.main, p.route)}</template>`)
3071
+ .join("");
3072
+ return toHashLinks(page("preview", { ...site, title }, {
3073
+ title,
3074
+ main: "",
3075
+ publish: {
3076
+ graphJs,
3077
+ codeJs,
3078
+ pages: templates,
3079
+ first,
3080
+ network: mode !== "static",
3081
+ pluginJs: mode === "live" ? pluginJs : undefined,
3082
+ subformatJs,
3083
+ },
3084
+ }), first);
2933
3085
  };
2934
- };
2935
- // Language and editor actions stay in the header; document actions live in the tree.
2936
- const editorAside = (entry, site) => {
2937
- const aside = `<aside id="panel"><div id="resize" class="panel-resize" role="separator" tabindex="0" aria-orientation="vertical" aria-controls="panel" aria-label="Resize editor" data-i18n-aria-label="Resize editor" title="Resize editor" data-i18n-title="Resize editor"></div>
2938
- <div id="phead">
2939
- ${languageFieldHtml(site.defaultLang, site.contentLanguage, entry.translatedLanguages, site.contentLanguages)}
2940
- <span id="status"></span>
2941
- <button id="validate" class="pbtn" type="button" title="Validate and apply" data-i18n-title="Validate and apply" aria-label="Validate and apply" data-i18n-aria-label="Validate and apply">${icon('<path d="M5 5l-4 5 4 5M15 5l4 5-4 5M7 10l2 2 4-5"/>')}</button>
2942
- <button id="save" class="pbtn" data-state="saved" type="button" title="Save (Ctrl+S)" data-i18n-title="Save (Ctrl+S)" aria-label="Save" data-i18n-aria-label="Save">${icon('<path d="M3 3h11l3 3v11H3z"/><path d="M6 3v5h7V3M6 17v-6h8v6"/>')}</button>
2943
- <button id="split-preview" class="pbtn" type="button" aria-pressed="false" aria-label="Split view" data-i18n-aria-label="Split view" title="Split view" data-i18n-title="Split view">${icon('<rect x="3" y="3" width="14" height="14" rx="2"/><path d="M10 3v14"/>')}</button>
2944
- <div id="gear"><button class="pbtn" type="button" aria-haspopup="true" aria-label="View settings" data-i18n-aria-label="View settings" title="View settings" data-i18n-title="View settings">${GEAR_ICON}</button><div id="gearmenu">
2945
- <div class="editor-setting"><span class="editor-setting-icon" data-setting-theme-icon aria-hidden="true"></span><div class="subformat-control"><span class="subformat-control-label" data-i18n="Editor theme">Editor theme</span><button class="setting-picker" type="button" data-theme-picker="editor" aria-label="Editor theme"><span data-picker-value></span>${SELECT_ICON}</button></div></div>
2946
- <div class="editor-setting"><span class="editor-setting-icon" aria-hidden="true">${FONT_ICON}</span><div class="subformat-control"><span class="subformat-control-label" data-i18n="Editor font">Editor font</span>${fontButton("editor")}</div></div>
2947
- <div id="language-setting" class="editor-setting">${GLOBE_ICON}<div class="subformat-control"><span class="subformat-control-label" data-i18n="Language">Editor language</span><select id="ui-language" aria-label="Editor language" data-i18n-aria-label="Language"><option value="eng">English</option><option value="jpn">日本語</option><option value="zho">中文</option></select></div></div>
2948
- <label><input type="checkbox" id="opt-autovalidate"><span data-i18n="Auto validate">Auto validate</span></label>
2949
- <label><input type="checkbox" id="opt-autosave"><span data-i18n="Auto save">Auto save</span></label>
2950
- <label><input type="checkbox" id="opt-corr"><span data-i18n="Source mapping">Source mapping</span></label>
2951
- <label><input type="checkbox" id="opt-git-diff"><span data-i18n="Show Git changes">Show Git changes</span></label>
3086
+ // A doc's main content. A doc with an empty body and children (a chapter-heading-only doc) shows
3087
+ // its children list in place of the body.
3088
+ const entryMain = (site, e) => {
3089
+ const html = renderEntryHtml(site, e).html;
3090
+ const kids = childrenOf(site.entries, e.id);
3091
+ if (e.subformat || e.library || e.blocks.length > 0 || kids.length === 0) {
3092
+ return html;
3093
+ }
3094
+ const items = kids
3095
+ .map((k) => `<li><a href="${docPath(site.entries, k.id)}">${escapeHtml(docDisplayName(k.frontmatter, k.id))}</a></li>`)
3096
+ .join("");
3097
+ return html.replace(/<\/article>\s*$/, `<ul class="idx">${items}</ul></article>`);
3098
+ };
3099
+ const languageFieldHtml = (defaultLang, language = contentLanguageCode(defaultLang), translatedLanguages = [contentLanguageCode(defaultLang)], declaredLanguages) => {
3100
+ const existing = new Set(translatedLanguages);
3101
+ const options = [...contentLanguages]
3102
+ .filter(({ code }) => !declaredLanguages || declaredLanguages.includes(code))
3103
+ .sort((a, b) => Number(existing.has(b.code)) - Number(existing.has(a.code)))
3104
+ .map(({ code, name }) => `<option value="${code}" data-name="${escapeHtml(name)}" data-added="${existing.has(code)}"${code === language ? " selected" : ""}>${escapeHtml(name)} (${code})</option>`)
3105
+ .join("");
3106
+ return `<div class="fm-language"><button class="pbtn" type="button" data-language-open aria-label="Change language" data-i18n-aria-label="Change language" aria-haspopup="listbox" aria-expanded="false" aria-controls="fm-lang-options">${GLOBE_ICON}</button><select id="fm-lang" data-source="${contentLanguageCode(defaultLang)}" aria-label="Change language" data-i18n-aria-label="Change language">${options}</select></div>`;
3107
+ };
3108
+ // The same thing is passed for the initial render (editorAside) and doc switch (`/api/page`)
3109
+ // (= the client only has to handle one boot shape, initially and after a switch).
3110
+ const editorBoot = (entry, site) => {
3111
+ // Completion candidates are files in the figures/ catalog.
3112
+ const figures = [...site.ctx.figures.values()].map((f) => f.file);
3113
+ const docs = site.entries
3114
+ .filter((e) => !e.subformat && !e.library)
3115
+ .map((e) => ({
3116
+ ref: e.sourceFile ?? CONTENT_PREFIX + e.file,
3117
+ title: docDisplayName(e.frontmatter, e.id),
3118
+ }));
3119
+ return {
3120
+ gitBase: entryGitBase(entry, site),
3121
+ ...(site.title === undefined ? {} : { siteTitle: site.title }),
3122
+ ...(site.icon === undefined ? {} : { siteIcon: svgDataUri(site.icon) }),
3123
+ ...(site.workspace
3124
+ ? {
3125
+ workspaceLabel: site.workspace.protocol === "git"
3126
+ ? `${site.workspace.branch}/${site.workspace.repo ?? "repo"}`
3127
+ : site.workspace.folder,
3128
+ }
3129
+ : {}),
3130
+ ...(entry.frontmatter?.lang ? { docLanguage: entry.frontmatter.lang } : {}),
3131
+ ...(entry.translatedLanguages
3132
+ ? { translatedLanguages: entry.translatedLanguages }
3133
+ : {}),
3134
+ ...(site.contentLanguage
3135
+ ? {
3136
+ contentLanguage: site.contentLanguage,
3137
+ sourceLanguage: contentLanguageCode(site.defaultLang),
3138
+ }
3139
+ : {}),
3140
+ file: entry.file,
3141
+ sourceFile: entry.sourceFile,
3142
+ docId: entry.id,
3143
+ title: entry.frontmatter?.title ?? "",
3144
+ path: docPath(site.entries, entry.id),
3145
+ body: entry.body,
3146
+ figures,
3147
+ codeLanguages: site.codeLanguages ?? CODE_LANGS,
3148
+ docs,
3149
+ terms: [...site.ctx.terms],
3150
+ blockLines: entry.blockLines,
3151
+ baseRaw: entry.raw,
3152
+ icon: entry.icon ? svgDataUri(entry.icon) : null,
3153
+ defaultLang: site.defaultLang,
3154
+ spellcheckLang: resolveLanguage(entry.lang, site.languages).spellcheckLang ?? entry.lang,
3155
+ filePreviews: filePreviewResults(entry, site),
3156
+ previews: site.previews,
3157
+ };
3158
+ };
3159
+ // Language and editor actions stay in the header; document actions live in the tree.
3160
+ const editorAside = (entry, site) => {
3161
+ const aside = `<aside id="panel"><div id="resize" class="panel-resize" role="separator" tabindex="0" aria-orientation="vertical" aria-controls="panel" aria-label="Resize editor" data-i18n-aria-label="Resize editor" title="Resize editor" data-i18n-title="Resize editor"></div>
3162
+ <div id="phead"><div id="editor-header-context">
3163
+ ${languageFieldHtml(site.defaultLang, site.contentLanguage, entry.translatedLanguages, site.contentLanguages)}
3164
+ <span id="status"></span>
3165
+ </div><div id="editor-header-workspace"></div><div id="editor-header-actions">
3166
+ <button id="validate" class="pbtn" type="button" title="Validate and apply" data-i18n-title="Validate and apply" aria-label="Validate and apply" data-i18n-aria-label="Validate and apply">${icon('<path d="M5 5l-4 5 4 5M15 5l4 5-4 5M7 10l2 2 4-5"/>')}</button>
3167
+ <button id="save" class="pbtn" data-state="saved" type="button" title="Save (Ctrl+S)" data-i18n-title="Save (Ctrl+S)" aria-label="Save" data-i18n-aria-label="Save">${icon('<path d="M3 3h11l3 3v11H3z"/><path d="M6 3v5h7V3M6 17v-6h8v6"/>')}</button>
3168
+ <button id="split-preview" class="pbtn" type="button" aria-pressed="false" aria-label="Split view" data-i18n-aria-label="Split view" title="Split view" data-i18n-title="Split view">${icon('<rect x="3" y="3" width="14" height="14" rx="2"/><path d="M10 3v14"/>')}</button>
3169
+ <div id="gear"><button class="pbtn" type="button" aria-expanded="false" aria-controls="gearmenu" aria-label="View settings" data-i18n-aria-label="View settings" title="View settings" data-i18n-title="View settings">${GEAR_ICON}</button><div id="gearmenu">
3170
+ <div class="editor-setting"><span class="editor-setting-icon" data-setting-theme-icon aria-hidden="true"></span><div class="subformat-control"><span class="subformat-control-label" data-i18n="Editor theme">Editor theme</span><button class="setting-picker" type="button" data-theme-picker="editor" aria-label="Editor theme"><span data-picker-value></span>${SELECT_ICON}</button></div></div>
3171
+ <div class="editor-setting"><span class="editor-setting-icon" aria-hidden="true">${FONT_ICON}</span><div class="subformat-control"><span class="subformat-control-label" data-i18n="Editor font">Editor font</span>${fontButton("editor")}</div></div>
3172
+ <div id="language-setting" class="editor-setting">${GLOBE_ICON}<div class="subformat-control"><span class="subformat-control-label" data-i18n="Language">Editor language</span><select id="ui-language" aria-label="Editor language" data-i18n-aria-label="Language"><option value="eng">English</option><option value="jpn">日本語</option><option value="zho">中文</option></select></div></div>
3173
+ <label><input type="checkbox" id="opt-autovalidate"><span data-i18n="Auto validate">Auto validate</span></label>
3174
+ <label><input type="checkbox" id="opt-autosave"><span data-i18n="Auto save">Auto save</span></label>
3175
+ <label><input type="checkbox" id="opt-corr"><span data-i18n="Source mapping">Source mapping</span></label>
3176
+ <label><input type="checkbox" id="opt-git-diff"><span data-i18n="Show Git changes">Show Git changes</span></label>
2952
3177
  <label><input type="checkbox" id="opt-line-wrap" checked><span data-i18n="Wrap lines">Wrap lines</span></label>
2953
3178
  </div></div>
2954
- </div>
3179
+ <button id="editor-open-workspace" class="pbtn" type="button" aria-label="Open workspace" data-i18n-aria-label="Open workspace" title="Open workspace" data-i18n-title="Open workspace">${icon('<path d="M2 5h6l2 2h8v10H2zM2 5V3h6l2 2"/>')}</button>
3180
+ </div></div>
2955
3181
 
2956
3182
  <div id="cm"></div>
2957
3183
  </aside>`;
2958
- return { aside, boot: editorBoot(entry, site) };
2959
- };
2960
- /**
2961
- * Response for `GET /api/page?route=/<ancestor/.../docId>` (status + body). mode === "edit" only.
2962
- * The diff for doing edit's doc switch via client-side navigation (= keep scroll position /
2963
- * search term / open state without rebuilding the sidebar DOM); it returns only what the client
2964
- * replaces: main html + the panel's variable parts (file name / front-matter fields) + the new
2965
- * doc's boot.
2966
- * File views replace the central workspace while retaining the current editor.
2967
- */
2968
- export const pageDataResponse = (site, path) => {
2969
- if (typeof path !== "string" || !path.startsWith("/")) {
2970
- return { status: 400, body: { error: "route must be /<docId>" } };
2971
- }
2972
- if (path === "/_extensions" ||
2973
- path === "/_subformats" ||
2974
- path === "/_git" ||
2975
- path === "/_statics" ||
2976
- path.startsWith("/_statics/") ||
2977
- path === "/_files" ||
2978
- path.startsWith("/_files/")) {
2979
- try {
2980
- const resource = resourcesMain(site, path.startsWith("/_statics")
2981
- ? path.slice(1)
2982
- : ["/_git", "/_extensions", "/_subformats"].includes(path)
3184
+ return { aside, boot: editorBoot(entry, site) };
3185
+ };
3186
+ /**
3187
+ * Response for `GET /api/page?route=/<ancestor/.../docId>` (status + body). mode === "edit" only.
3188
+ * The diff for doing edit's doc switch via client-side navigation (= keep scroll position /
3189
+ * search term / open state without rebuilding the sidebar DOM); it returns only what the client
3190
+ * replaces: main html + the panel's variable parts (file name / front-matter fields) + the new
3191
+ * doc's boot.
3192
+ * File views replace the central workspace while retaining the current editor.
3193
+ */
3194
+ const pageDataResponse = (site, path) => {
3195
+ if (typeof path !== "string" || !path.startsWith("/")) {
3196
+ return { status: 400, body: { error: "route must be /<docId>" } };
3197
+ }
3198
+ if (path === "/_extensions" ||
3199
+ path === "/_subformats" ||
3200
+ path === "/_git" ||
3201
+ path === "/_library" ||
3202
+ path.startsWith("/_library/") ||
3203
+ path === "/_files" ||
3204
+ path.startsWith("/_files/")) {
3205
+ try {
3206
+ const resource = resourcesMain(site, path.startsWith("/_library")
2983
3207
  ? path.slice(1)
2984
- : path.slice("/_files".length).replace(/^\/|\/$/g, ""));
2985
- return resource
2986
- ? {
2987
- status: 200,
2988
- body: {
2989
- resource: true,
2990
- path,
2991
- title: pageTitle("edit", resource.title, site.title),
2992
- html: docLinks(site, resource.main),
2993
- sourceFile: resource.sourceFile,
2994
- },
2995
- }
2996
- : { status: 404, body: { error: `${path} is not a file route` } };
3208
+ : ["/_git", "/_extensions", "/_subformats"].includes(path)
3209
+ ? path.slice(1)
3210
+ : path.slice("/_files".length).replace(/^\/|\/$/g, ""));
3211
+ return resource
3212
+ ? {
3213
+ status: 200,
3214
+ body: {
3215
+ resource: true,
3216
+ path,
3217
+ title: pageTitle("edit", resource.title, site.title),
3218
+ html: docLinks(site, resource.main),
3219
+ sourceFile: resource.sourceFile,
3220
+ },
3221
+ }
3222
+ : { status: 404, body: { error: `${path} is not a file route` } };
3223
+ }
3224
+ catch {
3225
+ return { status: 400, body: { error: "Invalid file route" } };
3226
+ }
2997
3227
  }
2998
- catch {
2999
- return { status: 400, body: { error: "Invalid file route" } };
3228
+ const id = resolveDocPath(site.entries, path);
3229
+ const doc = site.entries.find((e) => e.id === id);
3230
+ if (!doc) {
3231
+ return { status: 404, body: { error: `${path} is not a doc route` } };
3000
3232
  }
3001
- }
3002
- const id = resolveDocPath(site.entries, path);
3003
- const doc = site.entries.find((e) => e.id === id);
3004
- if (!doc) {
3005
- return { status: 404, body: { error: `${path} is not a doc route` } };
3006
- }
3007
- const html = entryMain(site, doc);
3008
- if (doc.subformat)
3233
+ const html = entryMain(site, doc);
3234
+ if (doc.subformat || doc.library)
3235
+ return {
3236
+ status: 200,
3237
+ body: {
3238
+ resource: true,
3239
+ path,
3240
+ title: pageTitle("edit", docDisplayName(doc.frontmatter, doc.id), site.title),
3241
+ html,
3242
+ },
3243
+ };
3244
+ const errors = [...site.errors, ...doc.errors];
3009
3245
  return {
3010
3246
  status: 200,
3011
3247
  body: {
3012
- resource: true,
3013
- path,
3014
3248
  title: pageTitle("edit", docDisplayName(doc.frontmatter, doc.id), site.title),
3249
+ file: doc.file,
3015
3250
  html,
3251
+ errors,
3252
+ toc: doc.toc,
3253
+ boot: editorBoot(doc, site),
3254
+ filePreviews: filePreviewResults(doc, site),
3016
3255
  },
3017
3256
  };
3018
- const errors = [...site.errors, ...doc.errors];
3019
- return {
3020
- status: 200,
3021
- body: {
3022
- title: pageTitle("edit", docDisplayName(doc.frontmatter, doc.id), site.title),
3023
- file: doc.file,
3024
- html,
3025
- errors,
3026
- toc: doc.toc,
3027
- boot: editorBoot(doc, site),
3028
- filePreviews: filePreviewResults(doc, site),
3029
- },
3030
3257
  };
3031
- };
3032
- const readJson = async (req, limit) => {
3033
- try {
3034
- const v = JSON.parse(await readBody(req, limit));
3035
- return typeof v === "object" && v != null ? v : undefined;
3036
- }
3037
- catch {
3038
- return undefined;
3039
- }
3040
- };
3041
- const notFound = (res, path) => {
3042
- res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
3043
- res.end(`not found: ${path}`);
3044
- };
3045
- const sendJson = (res, code, body) => {
3046
- res.writeHead(code, { "content-type": "application/json; charset=utf-8" });
3047
- res.end(JSON.stringify(body));
3048
- };
3049
- const sendOp = (res, r) => {
3050
- if (isOpError(r)) {
3051
- const { status, ...body } = r;
3052
- sendJson(res, status, body);
3053
- }
3054
- else {
3055
- sendJson(res, 200, { ok: true, ...r });
3056
- }
3057
- };
3058
- const languageLinks = (html, locale) => html.replace(/href="(\/(?!\/)[^"#?]*)(#[^"]*)?"/g, (_match, path, hash = "") => `href="${path}?lang=${encodeURIComponent(locale)}${hash}"`);
3059
- const sendPage = (res, mode, site, opts) => {
3060
- res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
3061
- const html = docLinks(site, page(mode, site, opts));
3062
- res.end(site.contentLanguage ? languageLinks(html, site.contentLanguage) : html);
3063
- };
3064
- const readBody = (req, limit = 5_000_000) => new Promise((resolve, reject) => {
3065
- let data = "";
3066
- req.setEncoding("utf8");
3067
- req.on("data", (chunk) => {
3068
- data += chunk;
3069
- if (data.length > limit) {
3070
- reject(new Error("body too large"));
3071
- req.destroy();
3258
+ const readJson = async (req, limit) => {
3259
+ try {
3260
+ const v = JSON.parse(await readBody(req, limit));
3261
+ return typeof v === "object" && v != null ? v : undefined;
3262
+ }
3263
+ catch {
3264
+ return undefined;
3265
+ }
3266
+ };
3267
+ const notFound = (res, path) => {
3268
+ res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
3269
+ res.end(`not found: ${path}`);
3270
+ };
3271
+ const sendJson = (res, code, body) => {
3272
+ res.writeHead(code, { "content-type": "application/json; charset=utf-8" });
3273
+ res.end(JSON.stringify(body));
3274
+ };
3275
+ const sendOp = (res, r) => {
3276
+ if (isOpError(r)) {
3277
+ const { status, ...body } = r;
3278
+ sendJson(res, status, body);
3072
3279
  }
3073
- });
3074
- req.on("end", () => resolve(data));
3075
- req.on("error", reject);
3076
- });
3077
- // Preview refresh (/api/render) and save (/api/save) — they differ only in the disk write and
3078
- // share the response shape (the client can update the left pane straight from a save response).
3079
- const handleDraft = async (req, res, save, locale) => {
3080
- let parsedBody;
3081
- try {
3082
- parsedBody = JSON.parse(await readBody(req));
3083
- }
3084
- catch {
3085
- sendJson(res, 400, { error: "invalid JSON body" });
3086
- return;
3087
- }
3088
- const { file, frontmatter, body, baseRaw, textfiles } = (parsedBody ?? {});
3089
- let fileDrafts;
3090
- try {
3091
- fileDrafts = previewTextfiles(root, textfiles);
3092
- }
3093
- catch (error) {
3094
- sendJson(res, 400, { error: String(error) });
3095
- return;
3096
- }
3097
- const target = resolveContentFile(file);
3098
- if (!target) {
3099
- sendJson(res, 400, { error: "file must be <id>.md" });
3100
- return;
3101
- }
3102
- if (save && !existsSync(target.abs)) {
3103
- sendJson(res, 404, { error: `${target.name} not found (use + in the nav to create)` });
3104
- return;
3105
- }
3106
- // So that autosave never silently overwrites external changes (direct edits / git pull etc.),
3107
- // compare the current disk content with the base (the raw the client last read) right before
3108
- // saving. If they differ, skip the write and return the disk content for the client to load
3109
- // into the editor (= the md file wins).
3110
- const site = loadSite(locale);
3111
- const currentRaw = save
3112
- ? (site.entries.find((entry) => entry.id === target.id)?.raw ??
3113
- readFileSync(target.abs, "utf8"))
3114
- : undefined;
3115
- if (save && currentRaw !== undefined && isExternallyModified(baseRaw, currentRaw)) {
3116
- const { raw: _raw, ...doc } = renderDocFile(site, target.name, currentRaw);
3117
- sendJson(res, 200, { ...doc, saved: false, conflict: true, raw: currentRaw });
3118
- return;
3119
- }
3120
- const fm = sanitizeFrontmatter(frontmatter);
3121
- const text = typeof body === "string" ? body : "";
3122
- if (locale !== contentLanguageCode(site.defaultLang))
3123
- fm.lang = locale;
3124
- const raw = assembleDoc(fm, text);
3125
- if (save) {
3126
- if (locale === contentLanguageCode(site.defaultLang))
3127
- writeFileSync(target.abs, raw);
3128
3280
  else {
3129
- const file = translationFile(sourceDocFile(target.id, readManifest(root).files), locale);
3130
- const base = existsSync(textfilePath(root, file)) ? (currentRaw ?? null) : null;
3131
- if (!writeTextfile(root, file, raw, base)) {
3132
- sendJson(res, 409, { error: "Translation changed. Reload before saving." });
3281
+ sendJson(res, 200, { ok: true, ...r });
3282
+ }
3283
+ };
3284
+ const languageLinks = (html, locale) => html.replace(/href="(\/(?!\/)[^"#?]*)(#[^"]*)?"/g, (_match, path, hash = "") => `href="${path}?lang=${encodeURIComponent(locale)}${hash}"`);
3285
+ const sendPage = (res, mode, site, opts) => {
3286
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
3287
+ const html = docLinks(site, page(mode, site, opts));
3288
+ res.end(site.contentLanguage ? languageLinks(html, site.contentLanguage) : html);
3289
+ };
3290
+ const readBody = (req, limit = 5_000_000) => "body" in req
3291
+ ? Promise.resolve(String(req.body))
3292
+ : new Promise((resolve, reject) => {
3293
+ let data = "";
3294
+ req.setEncoding("utf8");
3295
+ req.on("data", (chunk) => {
3296
+ data += chunk;
3297
+ if (data.length > limit) {
3298
+ reject(new Error("body too large"));
3299
+ req.destroy();
3300
+ }
3301
+ });
3302
+ req.on("end", () => resolve(data));
3303
+ req.on("error", reject);
3304
+ });
3305
+ // Preview refresh (/api/render) and save (/api/save) — they differ only in the disk write and
3306
+ // share the response shape (the client can update the left pane straight from a save response).
3307
+ const handleDraft = async (req, res, save, locale) => {
3308
+ let parsedBody;
3309
+ try {
3310
+ parsedBody = JSON.parse(await readBody(req));
3311
+ }
3312
+ catch {
3313
+ sendJson(res, 400, { error: "invalid JSON body" });
3314
+ return;
3315
+ }
3316
+ // A preview only reads, so its Git ignore checks are shared; a save writes in between.
3317
+ if (save)
3318
+ respondDraft(res, parsedBody, save, locale);
3319
+ else
3320
+ withIgnoredFilesCache(() => respondDraft(res, parsedBody, save, locale));
3321
+ };
3322
+ const respondDraft = (res, parsedBody, save, locale) => {
3323
+ const { file, frontmatter, body, baseRaw, textfiles } = (parsedBody ?? {});
3324
+ let fileDrafts;
3325
+ try {
3326
+ fileDrafts = previewTextfiles(root, textfiles);
3327
+ }
3328
+ catch (error) {
3329
+ sendJson(res, 400, { error: String(error) });
3330
+ return;
3331
+ }
3332
+ const target = resolveContentFile(file);
3333
+ if (!target) {
3334
+ sendJson(res, 400, { error: "file must be <id>.md" });
3335
+ return;
3336
+ }
3337
+ if (save && !existsSync(target.abs)) {
3338
+ sendJson(res, 404, { error: `${target.name} not found (use + in the nav to create)` });
3339
+ return;
3340
+ }
3341
+ // So that autosave never silently overwrites external changes (direct edits / git pull etc.),
3342
+ // compare the current disk content with the base (the raw the client last read) right before
3343
+ // saving. If they differ, skip the write and return the disk content for the client to load
3344
+ // into the editor (= the md file wins).
3345
+ const site = loadSite(locale);
3346
+ const currentRaw = save
3347
+ ? (site.entries.find((entry) => entry.id === target.id)?.raw ??
3348
+ readFileSync(target.abs, "utf8"))
3349
+ : undefined;
3350
+ if (save && currentRaw !== undefined && isExternallyModified(baseRaw, currentRaw)) {
3351
+ const { raw: _raw, ...doc } = renderDocFile(site, target.name, currentRaw);
3352
+ sendJson(res, 200, { ...doc, saved: false, conflict: true, raw: currentRaw });
3353
+ return;
3354
+ }
3355
+ const fm = sanitizeFrontmatter(frontmatter);
3356
+ const text = typeof body === "string" ? body : "";
3357
+ const raw = assembleDoc(text);
3358
+ if (save) {
3359
+ // The manifest owns the title; the editor's title field renames it there.
3360
+ const current = site.entries.find((entry) => entry.id === target.id)?.frontmatter
3361
+ ?.title;
3362
+ if (fm.title && fm.title !== current)
3363
+ ops.setTitle(target.id, fm.title);
3364
+ if (locale === contentLanguageCode(site.defaultLang))
3365
+ writeFileSync(target.abs, raw);
3366
+ else {
3367
+ const file = translationFile(sourceDocFile(target.id, readManifest(root).files), locale);
3368
+ const base = existsSync(textfilePath(root, file)) ? (currentRaw ?? null) : null;
3369
+ if (!writeTextfile(root, file, raw, base)) {
3370
+ sendJson(res, 409, { error: "Translation changed. Reload before saving." });
3371
+ return;
3372
+ }
3373
+ }
3374
+ }
3375
+ const draft = renderDraft(save ? loadSite(locale) : site, target.name, raw, fileDrafts);
3376
+ sendJson(res, 200, { ...draft, saved: save, conflict: false, raw });
3377
+ };
3378
+ // Prose lint (/api/lint) = the `lint` of the doc language's adapter (language socket); languages
3379
+ // without one return no findings. Lints the body string (same coordinate system as the CM doc)
3380
+ // and returns findings with offsets — spellchecking is left to the browser (client side).
3381
+ const handleLint = async (req, res) => {
3382
+ let parsedBody;
3383
+ try {
3384
+ parsedBody = JSON.parse(await readBody(req));
3385
+ }
3386
+ catch {
3387
+ sendJson(res, 400, { error: "invalid JSON body" });
3388
+ return;
3389
+ }
3390
+ const { body, lang } = (parsedBody ?? {});
3391
+ const tag = typeof lang === "string" && isLangTag(lang)
3392
+ ? lang
3393
+ : (readManifest(root).defaultLang ?? DEFAULT_LANG);
3394
+ const { lint } = resolveLanguage(tag, siteLanguages.languages);
3395
+ const findings = lint ? await lint(typeof body === "string" ? body : "") : [];
3396
+ sendJson(res, 200, { findings });
3397
+ };
3398
+ // Create a new doc; the sidebar refresh keeps the current document open.
3399
+ const handleCreate = async (req, res) => {
3400
+ const body = await readJson(req);
3401
+ const name = typeof body?.name === "string" ? body.name.trim() : "";
3402
+ const title = typeof body?.title === "string" ? body.title.trim() : "";
3403
+ const parent = typeof body?.parent === "string" && body.parent !== "" ? body.parent : undefined;
3404
+ const result = typeof body?.library === "string"
3405
+ ? ops.addLibrary(body.library, title, parent)
3406
+ : typeof body?.subformat === "string"
3407
+ ? ops.addSubformat(body.subformat, title, parent)
3408
+ : ops.addFile(name, title, parent);
3409
+ sendOp(res, isOpError(result)
3410
+ ? result
3411
+ : { ...result, path: docPath(loadSite().entries, result.id) });
3412
+ };
3413
+ // Add a figure (sidebar file picker / drag-and-drop). Returns the written file name
3414
+ // (the client inserts ![](figures/<file>)).
3415
+ const handleFigure = async (req, res) => {
3416
+ const body = await readJson(req);
3417
+ if (typeof body?.name !== "string" || typeof body?.data !== "string") {
3418
+ sendJson(res, 400, { error: "specify an svg / png / webp / jpeg / html file" });
3419
+ return;
3420
+ }
3421
+ const result = ops.addFigure(body.name, Buffer.from(body.data, "base64"));
3422
+ sendOp(res, isOpError(result)
3423
+ ? result
3424
+ : { ...result, path: result.path ?? `figures/${result.file}` });
3425
+ };
3426
+ // Doc icon (the header's icon slot). data = base64 of an svg (null = remove). Pads it to 1:1 and
3427
+ // writes icons/<id>.svg. Response icon = the new data URI (null if removed).
3428
+ const handleIcon = async (req, res) => {
3429
+ const body = await readJson(req);
3430
+ const manifest = readManifest(root);
3431
+ if (manifest.errors.length) {
3432
+ sendJson(res, 409, { error: manifest.errors.join("\n") });
3433
+ return;
3434
+ }
3435
+ const requestedId = typeof body?.file === "string" ? docIdOfFile(body.file) : undefined;
3436
+ const page = flattenTree(manifest.tree).find((node) => node.id === requestedId && (node.subformat || node.library));
3437
+ const target = page ? undefined : resolveContentFile(body?.file);
3438
+ const id = page?.id ?? (target && existsSync(target.abs) ? target.id : undefined);
3439
+ if (!id) {
3440
+ sendJson(res, 404, { error: "target doc not found" });
3441
+ return;
3442
+ }
3443
+ const previous = docIconFile(id, manifest.files);
3444
+ const file = manifest.format !== "nested" &&
3445
+ manifest.files?.defaultLayout !== false &&
3446
+ !Object.hasOwn(manifest.files?.icons ?? {}, id) &&
3447
+ !existsSync(textfilePath(root, previous))
3448
+ ? defaultFilePath(`${id}-icon.svg`)
3449
+ : previous;
3450
+ const path = textfilePath(root, file);
3451
+ if (body?.data == null) {
3452
+ const owned = ownsDocIcon(id, manifest);
3453
+ const fallback = docIconFile(id, manifest.files && { ...manifest.files, icons: undefined });
3454
+ if (!owned && existsSync(textfilePath(root, fallback))) {
3455
+ sendJson(res, 409, {
3456
+ error: `Remove or relocate the default icon file before clearing this reference: ${fallback}`,
3457
+ });
3133
3458
  return;
3134
3459
  }
3460
+ if (owned && existsSync(path)) {
3461
+ unlinkSync(path);
3462
+ }
3463
+ if (manifest.files?.icons && Object.hasOwn(manifest.files.icons, id)) {
3464
+ delete manifest.files.icons[id];
3465
+ writeManifest(root, manifest.tree, manifest);
3466
+ }
3467
+ sendJson(res, 200, { ok: true, icon: null });
3468
+ return;
3135
3469
  }
3136
- }
3137
- const draft = renderDraft(save ? loadSite(locale) : site, target.name, raw, fileDrafts);
3138
- sendJson(res, 200, { ...draft, saved: save, conflict: false, raw });
3139
- };
3140
- // Prose lint (/api/lint) = the `lint` of the doc language's adapter (language socket); languages
3141
- // without one return no findings. Lints the body string (same coordinate system as the CM doc)
3142
- // and returns findings with offsets — spellchecking is left to the browser (client side).
3143
- const handleLint = async (req, res) => {
3144
- let parsedBody;
3145
- try {
3146
- parsedBody = JSON.parse(await readBody(req));
3147
- }
3148
- catch {
3149
- sendJson(res, 400, { error: "invalid JSON body" });
3150
- return;
3151
- }
3152
- const { body, lang } = (parsedBody ?? {});
3153
- const tag = typeof lang === "string" && isLangTag(lang)
3154
- ? lang
3155
- : (readManifest(root).defaultLang ?? DEFAULT_LANG);
3156
- const { lint } = resolveLanguage(tag, siteLanguages.languages);
3157
- const findings = lint ? await lint(typeof body === "string" ? body : "") : [];
3158
- sendJson(res, 200, { findings });
3159
- };
3160
- // Create a new doc; the sidebar refresh keeps the current document open.
3161
- const handleCreate = async (req, res) => {
3162
- const body = await readJson(req);
3163
- const name = typeof body?.name === "string" ? body.name.trim() : "";
3164
- const title = typeof body?.title === "string" ? body.title.trim() : "";
3165
- const parent = typeof body?.parent === "string" && body.parent !== "" ? body.parent : undefined;
3166
- const result = typeof body?.subformat === "string"
3167
- ? ops.addSubformat(body.subformat, title, parent)
3168
- : ops.addFile(name, title, parent);
3169
- sendOp(res, isOpError(result) ? result : { ...result, path: docPath(loadSite().entries, result.id) });
3170
- };
3171
- // Add a figure (sidebar file picker / drag-and-drop). Returns the written file name
3172
- // (the client inserts ![](figures/<file>)).
3173
- const handleFigure = async (req, res) => {
3174
- const body = await readJson(req);
3175
- if (typeof body?.name !== "string" || typeof body?.data !== "string") {
3176
- sendJson(res, 400, { error: "specify an svg / png / webp / jpeg / html file" });
3177
- return;
3178
- }
3179
- const result = ops.addFigure(body.name, Buffer.from(body.data, "base64"));
3180
- sendOp(res, isOpError(result) ? result : { ...result, path: result.path ?? `figures/${result.file}` });
3181
- };
3182
- // Doc icon (the header's icon slot). data = base64 of an svg (null = remove). Pads it to 1:1 and
3183
- // writes icons/<id>.svg. Response icon = the new data URI (null if removed).
3184
- const handleIcon = async (req, res) => {
3185
- const body = await readJson(req);
3186
- const manifest = readManifest(root);
3187
- if (manifest.errors.length) {
3188
- sendJson(res, 409, { error: manifest.errors.join("\n") });
3189
- return;
3190
- }
3191
- const requestedId = typeof body?.file === "string" ? docIdOfFile(body.file) : undefined;
3192
- const page = flattenTree(manifest.tree).find((node) => node.id === requestedId && node.subformat);
3193
- const target = page ? undefined : resolveContentFile(body?.file);
3194
- const id = page?.id ?? (target && existsSync(target.abs) ? target.id : undefined);
3195
- if (!id) {
3196
- sendJson(res, 404, { error: "target doc not found" });
3197
- return;
3198
- }
3199
- const previous = docIconFile(id, manifest.files);
3200
- const file = manifest.format !== "nested" &&
3201
- manifest.files?.defaultLayout !== false &&
3202
- !Object.hasOwn(manifest.files?.icons ?? {}, id) &&
3203
- !existsSync(textfilePath(root, previous))
3204
- ? defaultFilePath(`${id}-icon.svg`)
3205
- : previous;
3206
- const path = textfilePath(root, file);
3207
- if (body?.data == null) {
3208
- if (existsSync(path)) {
3209
- unlinkSync(path);
3210
- }
3211
- if (manifest.files?.icons && Object.hasOwn(manifest.files.icons, id)) {
3212
- delete manifest.files.icons[id];
3470
+ const svg = typeof body.data === "string"
3471
+ ? squareSvg(Buffer.from(body.data, "base64").toString("utf8"))
3472
+ : undefined;
3473
+ if (!svg) {
3474
+ sendJson(res, 400, { error: "specify an svg (viewBox or width / height required)" });
3475
+ return;
3476
+ }
3477
+ if (file !== previous && existsSync(path)) {
3478
+ sendJson(res, 409, { error: "File already exists" });
3479
+ return;
3480
+ }
3481
+ mkdirSync(dirname(path), { recursive: true });
3482
+ writeFileSync(path, svg);
3483
+ if (file !== previous) {
3484
+ manifest.files ??= parseFileLayout({});
3485
+ manifest.files.icons ??= {};
3486
+ manifest.files.icons[id] = file;
3213
3487
  writeManifest(root, manifest.tree, manifest);
3214
3488
  }
3215
- sendJson(res, 200, { ok: true, icon: null });
3216
- return;
3217
- }
3218
- const svg = typeof body.data === "string"
3219
- ? squareSvg(Buffer.from(body.data, "base64").toString("utf8"))
3220
- : undefined;
3221
- if (!svg) {
3222
- sendJson(res, 400, { error: "specify an svg (viewBox or width / height required)" });
3223
- return;
3224
- }
3225
- if (file !== previous && existsSync(path)) {
3226
- sendJson(res, 409, { error: "File already exists" });
3227
- return;
3228
- }
3229
- mkdirSync(dirname(path), { recursive: true });
3230
- writeFileSync(path, svg);
3231
- if (file !== previous) {
3232
- manifest.files ??= parseFileLayout({});
3233
- manifest.files.icons ??= {};
3234
- manifest.files.icons[id] = file;
3235
- writeManifest(root, manifest.tree, manifest);
3236
- }
3237
- sendJson(res, 200, { ok: true, icon: svgDataUri(svg) });
3238
- };
3239
- // Sidebar DnD move (reorder + reparent). Rewrites only dooc.yaml (file / id unchanged).
3240
- const handleMove = async (req, res) => {
3241
- const body = await readJson(req);
3242
- const { id, parent, index } = body ?? {};
3243
- if (typeof id !== "string" ||
3244
- (parent !== undefined && typeof parent !== "string") ||
3245
- typeof index !== "number") {
3246
- sendJson(res, 400, { error: "id / parent? / index required" });
3247
- return;
3248
- }
3249
- sendOp(res, ops.move(id, parent, index));
3250
- };
3251
- // Rename the source file, update its references, and preserve the document's URL.
3252
- const handleRename = async (req, res) => {
3253
- const body = await readJson(req);
3254
- const target = resolveContentFile(body?.file);
3255
- if (!target) {
3256
- sendJson(res, 404, { error: "target doc not found" });
3257
- return;
3258
- }
3259
- try {
3260
- const snapshot = filesSnapshot(root);
3261
- const file = sourceDocFile(target.id, snapshot.layout);
3262
- if (body?.sourceFile !== file)
3263
- throw new Error("Files changed. Reload before retrying.");
3264
- const result = updateFiles(root, {
3265
- action: "rename",
3266
- file,
3267
- name: typeof body?.name === "string" ? body.name.trim() : "",
3268
- revision: snapshot.revision,
3269
- });
3270
- sendOp(res, {
3271
- path: docPath(loadSite().entries, target.id),
3272
- sourceFile: sourceDocFile(target.id, result.layout),
3273
- });
3274
- }
3275
- catch (error) {
3276
- sendJson(res, 409, { error: error instanceof Error ? error.message : String(error) });
3277
- }
3278
- };
3279
- // Delete a doc. If it's referenced, refuse without force and return the referrers (the client
3280
- // confirms and resends with force). Response parent = where to navigate after deletion.
3281
- const handleDelete = async (req, res) => {
3282
- const body = await readJson(req);
3283
- const target = resolveContentFile(body?.file);
3284
- if (!target) {
3285
- sendJson(res, 404, { error: "target doc not found" });
3286
- return;
3287
- }
3288
- const result = ops.remove(target.id, body?.force === true);
3289
- sendOp(res, isOpError(result)
3290
- ? result
3291
- : {
3292
- ...result,
3293
- path: result.parent ? docPath(loadSite().entries, result.parent) : "/",
3294
- });
3295
- };
3296
- export const createBundleCache = () => {
3297
- const store = new Map();
3298
- return {
3299
- get: async (entry, build) => {
3300
- const hit = store.get(entry);
3301
- if (hit) {
3302
- return hit;
3303
- }
3304
- const js = await build();
3305
- const etag = `"${createHash("sha256").update(js).digest("hex")}"`;
3306
- const value = { js, etag };
3307
- store.set(entry, value);
3308
- return value;
3309
- },
3310
- clear: () => store.clear(),
3489
+ sendJson(res, 200, { ok: true, icon: svgDataUri(svg) });
3311
3490
  };
3312
- };
3313
- // The npm package (running as dist/*.js) has no src/, so read the prebuilt bundles.
3314
- const PREBUILT = {
3315
- "core/schema-graph-global.tsx": "flow.global.js",
3316
- "viewer/edit-client.ts": "edit.global.js",
3317
- "viewer/ui-client.ts": "ui.global.js",
3318
- "viewer/code-highlight.ts": "code.global.js",
3319
- "viewer/code-worker.ts": "code-worker.global.js",
3320
- "viewer/published-plugins.ts": "plugins.global.js",
3321
- "viewer/published-subformats.ts": "subformats.global.js",
3322
- };
3323
- /** Minified client bundle shared by local viewing and published HTML. */
3324
- export const bundleClient = async (entry) => {
3325
- const prebuilt = PREBUILT[entry];
3326
- if (usePrebuiltAssets && prebuilt) {
3327
- return readViewerAsset(prebuilt).toString("utf8");
3328
- }
3329
- const esbuild = await import("esbuild");
3330
- const out = await esbuild.build({
3331
- entryPoints: [join(pkgRoot, "src", entry)],
3332
- bundle: true,
3333
- format: "iife",
3334
- target: "es2022",
3335
- write: false,
3336
- minify: true,
3337
- });
3338
- return out.outputFiles?.[0]?.text ?? "";
3339
- };
3340
- export const startServer = async (mode, port = 5179, pluginModule, startup) => {
3341
- // Language adapters are read once; the manifest is re-read by the compiler.
3342
- siteLanguages = await loadSiteLanguages(root);
3343
- const viewerPlugins = await loadViewerPlugins(pluginModule);
3344
- workspaceSource = viewerPlugins.workspace;
3345
- let gitOrigin = viewerPlugins.gitOrigin;
3346
- const handleGit = createGitHandler(root, () => gitOrigin);
3347
- const personal = createLocalPluginStorage();
3348
- const handlePlugins = createPluginHandler(viewerPlugins.plugins, viewerPlugins, personal.credentials);
3349
- const handleExtensions = createExtensionManager(root, handlePlugins, viewerPlugins, personal);
3350
- let loginPlugins = startup?.login ? [startup.login] : [];
3351
- process.once("exit", handleExtensions.dispose);
3352
- // Client bundles (bundleClient) = edit's editing UI and the schema graph interaction layer
3353
- // shared by preview/edit. React Flow's stylesheet isn't mixed into the bundle — the mount
3354
- // layer (flow-css.ts) injects it into a <style> at runtime, so the page needs no CSS delivery
3355
- // path (same conditions as the published output).
3356
- // Cache the bundle result + etag per entry (graph.js / edit.js) — this path isn't hit by the
3357
- // per-keystroke /api/render / /api/save, but tsx watch doesn't restart for these, so
3358
- // invalidate explicitly on the watcher's "client" notification (changes to edit-client.ts /
3359
- // the schema graph interaction layer's src/*.tsx).
3360
- const bundleCache = createBundleCache();
3361
- let graphChunks;
3362
- const graphAsset = async (name) => {
3363
- if (usePrebuiltAssets)
3364
- return readViewerAsset(`graph/${name}`).toString("utf8");
3365
- graphChunks ??= import("esbuild")
3366
- .then(async (esbuild) => {
3367
- const output = await esbuild.build({
3368
- entryPoints: [join(pkgRoot, "src/core/schema-graph-global.tsx")],
3369
- bundle: true,
3370
- splitting: true,
3371
- format: "esm",
3372
- target: "es2022",
3373
- outdir: join(pkgRoot, "dist/graph"),
3374
- write: false,
3375
- minify: true,
3376
- });
3377
- return new Map(output.outputFiles.map((file) => [basename(file.path), file.text]));
3378
- })
3379
- .catch((error) => {
3380
- graphChunks = undefined;
3381
- throw error;
3382
- });
3383
- const js = (await graphChunks).get(name);
3384
- if (js === undefined)
3385
- throw new Error("Diagram asset not found");
3386
- return js;
3491
+ // Sidebar DnD move (reorder + reparent). Rewrites only dooc.yaml (file / id unchanged).
3492
+ const handleMove = async (req, res) => {
3493
+ const body = await readJson(req);
3494
+ const { id, parent, index } = body ?? {};
3495
+ if (typeof id !== "string" ||
3496
+ (parent !== undefined && typeof parent !== "string") ||
3497
+ typeof index !== "number") {
3498
+ sendJson(res, 400, { error: "id / parent? / index required" });
3499
+ return;
3500
+ }
3501
+ sendOp(res, ops.move(id, parent, index));
3387
3502
  };
3388
- // HMR — bootId changes on every process start. It's how the client detects a tsx watch
3389
- // restart.
3390
- const hub = createHmrHub(`${process.pid}-${Date.now()}`);
3391
- const viewer = {
3392
- register: handlePlugins.register,
3393
- unregister: handlePlugins.unregister,
3394
- setWorkspace(workspace) {
3395
- workspaceSource = workspace === undefined ? undefined : parseWorkspaceSource(workspace);
3396
- hub.broadcast("content", []);
3397
- },
3398
- setGitOrigin(origin) {
3399
- gitOrigin = origin === undefined ? undefined : validateGitOrigin(origin);
3400
- },
3401
- setAllowedDomains(domains) {
3402
- if (!Array.isArray(domains))
3403
- throw new Error("Allowed domains must be a list");
3404
- const previews = parsePreviewSettings({ domains });
3405
- applicationPreviews = previews;
3406
- compiler = createCompiler(root, { previews });
3407
- localeCompilers.clear();
3408
- hub.broadcast("content", []);
3409
- },
3503
+ // Rename the source file, update its references, and preserve the document's URL.
3504
+ const handleRename = async (req, res) => {
3505
+ const body = await readJson(req);
3506
+ const target = resolveContentFile(body?.file);
3507
+ if (!target) {
3508
+ sendJson(res, 404, { error: "target doc not found" });
3509
+ return;
3510
+ }
3511
+ try {
3512
+ const snapshot = filesSnapshot(root);
3513
+ const file = sourceDocFile(target.id, snapshot.layout);
3514
+ if (body?.sourceFile !== file)
3515
+ throw new Error("Files changed. Reload before retrying.");
3516
+ const result = updateFiles(root, {
3517
+ action: "rename",
3518
+ file,
3519
+ name: typeof body?.name === "string" ? body.name.trim() : "",
3520
+ revision: snapshot.revision,
3521
+ });
3522
+ sendOp(res, {
3523
+ path: docPath(loadSite().entries, target.id),
3524
+ sourceFile: sourceDocFile(target.id, result.layout),
3525
+ });
3526
+ }
3527
+ catch (error) {
3528
+ sendJson(res, 409, { error: error instanceof Error ? error.message : String(error) });
3529
+ }
3410
3530
  };
3411
- viewer.setAllowedDomains(viewerPlugins.allowedDomains ?? []);
3412
- await viewerPlugins.setup?.(viewer);
3413
- const extensionErrors = await handleExtensions
3414
- .restore()
3415
- .catch((error) => [error instanceof Error ? error.message : String(error)]);
3416
- for (const error of extensionErrors)
3417
- console.error(`Plugin: ${error}`);
3418
- if (startup?.file && startup.data) {
3419
- const result = (await handleExtensions({
3420
- action: "install",
3421
- file: startup.file,
3422
- data: startup.data,
3423
- base: null,
3424
- }));
3425
- loginPlugins = result.items.find((item) => item.file === startup.file)?.plugins ?? [];
3426
- console.log(`Installed ${startup.file} in ${join(root, EXTENSIONS_DIR)}`);
3427
- }
3428
- // DOCS_HMR=0 = no hot reload (nothing is watched = changes need a manual reload).
3429
- if (process.env.DOCS_HMR !== "0") {
3430
- const watcher = watchProject(root, pkgRoot, (kind, files) => {
3431
- console.log(`hmr: ${kind} (${files.join(", ")})`);
3432
- if (kind === "client") {
3433
- bundleCache.clear();
3434
- graphChunks = undefined;
3435
- }
3436
- hub.broadcast(kind, files);
3437
- });
3438
- watchTextfiles = watcher.watchTextfiles;
3439
- process.once("exit", watcher.close);
3440
- }
3441
- const handle = async (req, res) => {
3442
- if (await handlePlugins(req, res))
3531
+ // Delete a doc. If it's referenced, refuse without force and return the referrers (the client
3532
+ // confirms and resends with force). Response parent = where to navigate after deletion.
3533
+ const handleDelete = async (req, res) => {
3534
+ const body = await readJson(req);
3535
+ const target = resolveContentFile(body?.file);
3536
+ if (!target) {
3537
+ sendJson(res, 404, { error: "target doc not found" });
3443
3538
  return;
3539
+ }
3540
+ const result = ops.remove(target.id, body?.force === true);
3541
+ sendOp(res, isOpError(result)
3542
+ ? result
3543
+ : {
3544
+ ...result,
3545
+ path: result.parent ? docPath(loadSite().entries, result.parent) : "/",
3546
+ });
3547
+ };
3548
+ const handle = async (mode, req, res) => {
3444
3549
  const requestUrl = new URL(req.url ?? "/", "http://localhost");
3445
3550
  const requestedLanguage = req.headers["x-docs-language"] ??
3446
3551
  requestUrl.searchParams.get("lang") ??
@@ -3451,176 +3556,37 @@ export const startServer = async (mode, port = 5179, pluginModule, startup) => {
3451
3556
  }
3452
3557
  const locale = requestedLanguage;
3453
3558
  const path = decodeURIComponent(requestUrl.pathname);
3454
- if (req.method === "GET" && path.startsWith("/assets/fonts/")) {
3455
- const font = readFont(path.slice("/assets/fonts/".length));
3456
- if (!font) {
3457
- notFound(res, path);
3458
- return;
3559
+ if (mode === "edit" && req.method === "GET" && path === "/api/download") {
3560
+ try {
3561
+ const file = requestUrl.searchParams.get("file") ?? "";
3562
+ const data = readDownloadFile(root, file);
3563
+ res.writeHead(200, {
3564
+ "content-type": "application/octet-stream",
3565
+ "content-disposition": `attachment; filename*=UTF-8''${encodeURIComponent(textfileName(file))}`,
3566
+ "cache-control": "no-store",
3567
+ "x-content-type-options": "nosniff",
3568
+ });
3569
+ res.end(data);
3459
3570
  }
3460
- res.writeHead(200, {
3461
- "content-type": "font/woff2",
3462
- "cache-control": "public, max-age=86400",
3463
- });
3464
- res.end(font);
3465
- return;
3466
- }
3467
- // No favicon (this only silences the 404 console error from the browser's auto-request).
3468
- if (path === "/favicon.ico") {
3469
- res.writeHead(204);
3470
- res.end();
3471
- return;
3472
- }
3473
- if (req.method === "GET" && path === HMR_PATH) {
3474
- hub.handle(res);
3475
- return;
3476
- }
3477
- // Client bundles — graph.js (the schema graph interaction layer) is shared by
3478
- // preview / edit, edit.js is for the editing UI only.
3479
- const clientEntry = path === "/assets/code.js"
3480
- ? "viewer/code-highlight.ts"
3481
- : path === "/assets/code-worker.js"
3482
- ? "viewer/code-worker.ts"
3483
- : mode === "edit" && path === "/assets/edit.js"
3484
- ? "viewer/edit-client.ts"
3485
- : path === "/assets/ui.js"
3486
- ? "viewer/ui-client.ts"
3487
- : undefined;
3488
- const graphName = path === "/assets/graph.js"
3489
- ? "schema-graph-global.js"
3490
- : /^\/assets\/graph\/([\w-]+\.js)$/.exec(path)?.[1];
3491
- if (req.method === "GET" && (clientEntry != null || graphName)) {
3492
- const { js, etag } = await bundleCache.get(graphName ? path : (clientEntry ?? ""), () => graphName
3493
- ? path === "/assets/graph.js"
3494
- ? Promise.resolve('import "/assets/graph/schema-graph-global.js";')
3495
- : graphAsset(graphName)
3496
- : bundleClient(clientEntry ?? ""));
3497
- if (req.headers["if-none-match"] === etag) {
3498
- res.writeHead(304, { etag, "cache-control": "no-cache" });
3499
- res.end();
3500
- return;
3571
+ catch (error) {
3572
+ sendJson(res, 400, {
3573
+ error: error instanceof Error ? error.message : String(error),
3574
+ });
3501
3575
  }
3502
- res.writeHead(200, {
3503
- "content-type": "application/javascript; charset=utf-8",
3504
- etag,
3505
- "cache-control": "no-cache",
3506
- });
3507
- res.end(js);
3508
3576
  return;
3509
3577
  }
3510
3578
  if (mode === "edit" && req.method === "POST") {
3511
- if (path === "/api/extensions") {
3512
- res.setHeader("cache-control", "no-store");
3513
- if (!isLocalToolRequest(req.headers.host ?? "", req.headers.origin, req.headers["content-type"]) ||
3514
- ![
3515
- `localhost:${req.socket.localPort}`,
3516
- `127.0.0.1:${req.socket.localPort}`,
3517
- `[::1]:${req.socket.localPort}`,
3518
- ].includes(req.headers.host ?? "")) {
3519
- sendJson(res, 403, {
3520
- error: "Plugins require a same-origin local editor request",
3521
- });
3522
- return;
3523
- }
3524
- try {
3525
- const input = await readJson(req, MAX_EXTENSION_BYTES * 6 + 4096);
3526
- if (!input)
3527
- throw new Error("Expected a plugin request");
3528
- sendJson(res, 200, await handleExtensions(input));
3529
- }
3530
- catch (error) {
3531
- sendJson(res, 409, {
3532
- error: error instanceof Error ? error.message : "Plugin operation failed",
3533
- });
3534
- }
3535
- return;
3536
- }
3537
- if (path === "/api/git") {
3538
- res.setHeader("cache-control", "no-store");
3539
- if (!isLocalToolRequest(req.headers.host ?? "", req.headers.origin, req.headers["content-type"]) ||
3540
- (req.headers.host !== `localhost:${req.socket.localPort}` &&
3541
- req.headers.host !== `127.0.0.1:${req.socket.localPort}` &&
3542
- req.headers.host !== `[::1]:${req.socket.localPort}`)) {
3543
- sendJson(res, 403, {
3544
- error: "Git requires a same-origin local editor request",
3545
- });
3546
- return;
3547
- }
3548
- try {
3549
- if ((workspaceSource ?? readWorkspaceSource(root)).protocol !== "git")
3550
- throw new Error("Git workspace is not available");
3551
- const input = await readJson(req, 1_048_576);
3552
- const result = await handleGit(input);
3553
- if (workspaceSource?.protocol === "git" &&
3554
- (input?.action === "switch" || input?.action === "branch")) {
3555
- const local = readWorkspaceSource(root);
3556
- if (local.protocol === "git")
3557
- workspaceSource = { ...workspaceSource, branch: local.branch };
3558
- }
3559
- sendJson(res, 200, result);
3560
- }
3561
- catch (error) {
3562
- sendJson(res, 409, {
3563
- error: error instanceof Error ? error.message : "Git operation failed",
3564
- });
3565
- }
3566
- return;
3567
- }
3568
- if (path === "/api/files") {
3569
- if (!isLocalToolRequest(req.headers.host ?? "", req.headers.origin, req.headers["content-type"])) {
3570
- sendJson(res, 403, {
3571
- error: "Files require a same-origin local editor request",
3572
- });
3573
- return;
3574
- }
3575
- try {
3576
- const input = await readJson(req, Math.ceil((MAX_FILE_UPLOAD_BYTES * 4) / 3) + 16_384);
3577
- if (!input)
3578
- throw new Error("Invalid file request");
3579
- const result = input.action === "complete"
3580
- ? completeFilePaths(root, input.prefix)
3581
- : input.action === "read"
3582
- ? filesSnapshot(root)
3583
- : input.action === "upload"
3584
- ? uploadFile(root, input)
3585
- : updateFiles(root, input);
3586
- sendJson(res, 200, result);
3587
- }
3588
- catch (error) {
3589
- sendJson(res, 409, {
3590
- error: error instanceof Error ? error.message : String(error),
3591
- });
3592
- }
3593
- return;
3594
- }
3595
3579
  if (path === "/api/subformat") {
3596
- if (!isLocalToolRequest(req.headers.host ?? "", req.headers.origin, req.headers["content-type"])) {
3597
- sendJson(res, 403, {
3598
- error: "Record changes require a same-origin local editor request",
3599
- });
3600
- return;
3601
- }
3602
3580
  const result = subformatResponse(root, await readJson(req), applicationPreviews.domains);
3603
3581
  sendJson(res, result.status, result.body);
3604
3582
  return;
3605
3583
  }
3606
3584
  if (path === "/api/code-file") {
3607
- if (!isLocalToolRequest(req.headers.host ?? "", req.headers.origin, req.headers["content-type"])) {
3608
- sendJson(res, 403, {
3609
- error: "Code tools require a same-origin local editor request",
3610
- });
3611
- return;
3612
- }
3613
3585
  const result = codeFileResponse(root, await readJson(req), applicationPreviews);
3614
3586
  sendJson(res, result.status, result.body);
3615
3587
  return;
3616
3588
  }
3617
3589
  if (path === "/api/textfile") {
3618
- if (!isLocalToolRequest(req.headers.host ?? "", req.headers.origin, req.headers["content-type"])) {
3619
- sendJson(res, 403, {
3620
- error: "Text files require a same-origin local editor request",
3621
- });
3622
- return;
3623
- }
3624
3590
  const input = await readJson(req);
3625
3591
  if (input?.action === "preview") {
3626
3592
  try {
@@ -3687,12 +3653,6 @@ export const startServer = async (mode, port = 5179, pluginModule, startup) => {
3687
3653
  return;
3688
3654
  }
3689
3655
  if (path === "/api/translation") {
3690
- if (!isLocalToolRequest(req.headers.host ?? "", req.headers.origin, req.headers["content-type"])) {
3691
- sendJson(res, 403, {
3692
- error: "Translations require a same-origin local editor request",
3693
- });
3694
- return;
3695
- }
3696
3656
  const input = await readJson(req);
3697
3657
  const target = resolveContentFile(input?.file);
3698
3658
  if (!target ||
@@ -3713,12 +3673,6 @@ export const startServer = async (mode, port = 5179, pluginModule, startup) => {
3713
3673
  return;
3714
3674
  }
3715
3675
  if (path === "/api/code-tool") {
3716
- if (!isLocalToolRequest(req.headers.host ?? "", req.headers.origin, req.headers["content-type"])) {
3717
- sendJson(res, 403, {
3718
- error: "Code tools require a same-origin local editor request",
3719
- });
3720
- return;
3721
- }
3722
3676
  const input = await readJson(req);
3723
3677
  const target = resolveContentFile(input?.file);
3724
3678
  if (!target ||
@@ -3752,22 +3706,16 @@ export const startServer = async (mode, port = 5179, pluginModule, startup) => {
3752
3706
  return;
3753
3707
  }
3754
3708
  if (path === "/api/subformat-page") {
3755
- if (!isLocalToolRequest(req.headers.host ?? "", req.headers.origin, req.headers["content-type"])) {
3756
- sendJson(res, 403, {
3757
- error: "Page changes require a same-origin local editor request",
3758
- });
3759
- return;
3760
- }
3761
3709
  const body = await readJson(req);
3762
3710
  const id = typeof body?.id === "string" ? body.id : "";
3763
- if (!loadSite().entries.some((entry) => entry.id === id && entry.subformat)) {
3711
+ if (!loadSite().entries.some((entry) => entry.id === id && (entry.subformat || entry.library))) {
3764
3712
  sendJson(res, 404, { error: "Subformat page not found" });
3765
3713
  return;
3766
3714
  }
3767
3715
  sendOp(res, body?.action === "delete"
3768
3716
  ? ops.remove(id)
3769
3717
  : body?.action === "rename" && typeof body.title === "string"
3770
- ? ops.renameSubformat(id, body.title)
3718
+ ? ops.setTitle(id, body.title)
3771
3719
  : { status: 400, error: "Unknown page action" });
3772
3720
  return;
3773
3721
  }
@@ -3776,12 +3724,6 @@ export const startServer = async (mode, port = 5179, pluginModule, startup) => {
3776
3724
  return;
3777
3725
  }
3778
3726
  if (path === "/api/site-icon" || path === "/api/site-title") {
3779
- if (!isLocalToolRequest(req.headers.host ?? "", req.headers.origin, req.headers["content-type"])) {
3780
- sendJson(res, 403, {
3781
- error: "Site settings require a same-origin local editor request",
3782
- });
3783
- return;
3784
- }
3785
3727
  const input = await readJson(req);
3786
3728
  const result = path === "/api/site-title"
3787
3729
  ? siteTitleResponse(root, input)
@@ -3884,23 +3826,23 @@ export const startServer = async (mode, port = 5179, pluginModule, startup) => {
3884
3826
  notFound(res, path);
3885
3827
  return;
3886
3828
  }
3887
- const linkedFigure = path.startsWith("/_files/file/")
3888
- ? [...site.ctx.figures.values()].find((fig) => fig.file === path.slice("/_files/file/".length))
3829
+ const linkedFile = mode === "preview" && path.startsWith("/_files/file/")
3830
+ ? linkedFilePage(site, path.slice("/_files/file/".length))
3889
3831
  : undefined;
3890
- if (mode === "preview" && linkedFigure) {
3891
- sendPage(res, mode, site, figurePage(site, linkedFigure));
3832
+ if (linkedFile) {
3833
+ sendPage(res, mode, site, linkedFile);
3892
3834
  return;
3893
3835
  }
3894
3836
  if ((mode === "edit" &&
3895
3837
  (path === "/_extensions" ||
3896
3838
  path === "/_subformats" ||
3897
3839
  path === "/_git" ||
3898
- path === "/_statics" ||
3899
- path.startsWith("/_statics/") ||
3840
+ path === "/_library" ||
3841
+ path.startsWith("/_library/") ||
3900
3842
  path === "/_files" ||
3901
3843
  path.startsWith("/_files/"))) ||
3902
3844
  path === "/_files/terms") {
3903
- const rest = path.startsWith("/_statics")
3845
+ const rest = path.startsWith("/_library")
3904
3846
  ? path.slice(1)
3905
3847
  : ["/_git", "/_extensions", "/_subformats"].includes(path)
3906
3848
  ? path.slice(1)
@@ -3912,7 +3854,8 @@ export const startServer = async (mode, port = 5179, pluginModule, startup) => {
3912
3854
  }
3913
3855
  const editor = mode === "edit"
3914
3856
  ? (site.entries.find((entry) => !entry.subformat &&
3915
- entry.id === requestUrl.searchParams.get("editor")) ?? site.entries.find((entry) => !entry.subformat))
3857
+ !entry.library &&
3858
+ entry.id === requestUrl.searchParams.get("editor")) ?? site.entries.find((entry) => !entry.subformat && !entry.library))
3916
3859
  : undefined;
3917
3860
  if (editor) {
3918
3861
  const { aside, boot } = editorAside(editor, site);
@@ -3948,11 +3891,11 @@ export const startServer = async (mode, port = 5179, pluginModule, startup) => {
3948
3891
  main: entryMain(site, doc),
3949
3892
  currentId: doc.id,
3950
3893
  };
3951
- if (mode === "edit" && !doc.subformat) {
3894
+ if (mode === "edit" && !doc.subformat && !doc.library) {
3952
3895
  Object.assign(opts, editorAside(doc, site));
3953
3896
  }
3954
- if (mode === "edit" && doc.subformat) {
3955
- const editor = site.entries.find((entry) => !entry.subformat);
3897
+ if (mode === "edit" && (doc.subformat || doc.library)) {
3898
+ const editor = site.entries.find((entry) => !entry.subformat && !entry.library);
3956
3899
  if (editor) {
3957
3900
  const { aside, boot } = editorAside(editor, site);
3958
3901
  Object.assign(opts, {
@@ -3972,43 +3915,41 @@ export const startServer = async (mode, port = 5179, pluginModule, startup) => {
3972
3915
  }
3973
3916
  sendPage(res, mode, site, opts);
3974
3917
  };
3975
- const server = createServer((req, res) => {
3976
- handle(req, res).catch((e) => {
3977
- if (!res.headersSent) {
3978
- res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
3979
- }
3980
- res.end(`error: ${e instanceof Error ? e.message : e}`);
3981
- });
3982
- });
3983
- // If the port is in use (e.g. a previous instance left running), automatically try +1, up to
3984
- // 10 ports.
3985
- // The URL is printed once, on "listening" (no callbacks left over from failed listens).
3986
- server.once("listening", () => {
3987
- const addr = server.address();
3988
- const p = typeof addr === "object" && addr ? addr.port : port;
3989
- console.log(`dooc ${mode} (${root}): http://localhost:${p}/`);
3990
- for (const plugin of loginPlugins) {
3991
- try {
3992
- console.log(`Log in to ${plugin}: ${handlePlugins.loginLink(plugin, `http://localhost:${p}`)}`);
3993
- }
3994
- catch (error) {
3995
- console.error(error instanceof Error ? error.message : String(error));
3996
- }
3997
- }
3998
- if (loginPlugins.length)
3999
- console.log("Keep this command running while signing in. Login links expire in 10 minutes.");
4000
- });
4001
- const listen = (p, left) => {
4002
- server.once("error", (err) => {
4003
- if (err.code === "EADDRINUSE" && left > 0) {
4004
- console.log(`port ${p} in use → trying ${p + 1}`);
4005
- listen(p + 1, left - 1);
4006
- return;
3918
+ return {
3919
+ siteFrom,
3920
+ filePreviewResults,
3921
+ renderEntryHtml,
3922
+ renderDocFile,
3923
+ docQueryResponse,
3924
+ sanitizeFrontmatter,
3925
+ isExternallyModified,
3926
+ resolveContentFile,
3927
+ navGroupsHtml,
3928
+ textfilePreviewHtml,
3929
+ textfilePreviewErrors,
3930
+ resourcesMain,
3931
+ publishHtml,
3932
+ languageFieldHtml,
3933
+ editorBoot,
3934
+ pageDataResponse,
3935
+ assembleDoc,
3936
+ handle,
3937
+ readJson,
3938
+ sendJson,
3939
+ notFound,
3940
+ configure(settings) {
3941
+ if (settings.languages)
3942
+ siteLanguages = settings.languages;
3943
+ workspaceSource = settings.workspace;
3944
+ sharedBranch = settings.shared;
3945
+ editDownloads = Boolean(settings.downloads);
3946
+ if ("watch" in settings)
3947
+ watchTextfiles = settings.watch;
3948
+ if (settings.previews) {
3949
+ applicationPreviews = settings.previews;
3950
+ compiler = createCompiler(root, { previews: settings.previews });
3951
+ localeCompilers.clear();
4007
3952
  }
4008
- throw err;
4009
- });
4010
- server.listen(p, "127.0.0.1");
3953
+ },
4011
3954
  };
4012
- listen(port, 10);
4013
- return viewer;
4014
3955
  };