collabmd 0.1.47 → 0.1.49

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 (305) hide show
  1. package/README.md +70 -11
  2. package/bin/collabmd.js +3 -0
  3. package/dist/client/assets/CodeMirrorEditor-UCMRAMCV-C-nmgL5g.js +1 -0
  4. package/dist/client/assets/JetBrainsMono-Regular-BQaDgvhP.woff2 +0 -0
  5. package/dist/client/assets/abnfDiagram-VCTEODGH-CdVZqicp.js +1 -0
  6. package/dist/client/assets/{architectureDiagram-5GKGNRK7-I39sYjHI.js → architectureDiagram-5GKGNRK7-wUo0bXif.js} +3 -3
  7. package/dist/client/assets/babel-CY5KOv-I.js +16 -0
  8. package/dist/client/assets/{blockDiagram-NRAW4CY4-C6DtJy5Y.js → blockDiagram-I7D4REHJ-BRSK3m49.js} +4 -4
  9. package/dist/client/assets/browser-utils-DbXSMI-6.js +1 -0
  10. package/dist/client/assets/{c4Diagram-UCG6FXSJ-CtWtxS9_.js → c4Diagram-7LVT6UL2-yD2poxqw.js} +1 -1
  11. package/dist/client/assets/channel-Fa4GS_-F.js +1 -0
  12. package/dist/client/assets/chunk-2E4U76K2-BPnTT-J3.js +2 -0
  13. package/dist/client/assets/{chunk-TEH6E4GO-DVayPj-q.js → chunk-4HAMMTFA-DStbIfJ1.js} +20 -20
  14. package/dist/client/assets/{chunk-75Z2AOVW-CdFSaPjz.js → chunk-75Z2AOVW-C5pGd3W9.js} +1 -1
  15. package/dist/client/assets/{chunk-CLGD4ZFX-DQLgbQrv.js → chunk-CLGD4ZFX-BMeArk03.js} +1 -1
  16. package/dist/client/assets/chunk-DU6HZSFF-Zkp69c6c.js +127 -0
  17. package/dist/client/assets/{chunk-F27PBJKO-CNHIFhjo.js → chunk-F27PBJKO-D4xNct1r.js} +1 -1
  18. package/dist/client/assets/{chunk-GMAD6QVW-CbcBqPM5.js → chunk-GMAD6QVW-NZ6WpDb8.js} +1 -1
  19. package/dist/client/assets/{chunk-OBVCFTLP-BJR7u1jh.js → chunk-GVQU2GXP-D8SDprfX.js} +1 -1
  20. package/dist/client/assets/{chunk-G27WJ6UU-D9-eg537.js → chunk-IMKFNOWR-D8jEuU3Q.js} +2 -2
  21. package/dist/client/assets/{chunk-JQ64N6SF-DSFNH4bh.js → chunk-L3NEJ4N5-aijKP-eh.js} +1 -1
  22. package/dist/client/assets/chunk-OSK3NFVY-CCbLQAMa.js +10 -0
  23. package/dist/client/assets/{chunk-P2QGCYS3-BRpqY32H.js → chunk-P2QGCYS3-Oag_FdCq.js} +1 -1
  24. package/dist/client/assets/{chunk-POPQ4Y6H-Cb4SlVZF.js → chunk-POPQ4Y6H-CYnpIgXT.js} +1 -1
  25. package/dist/client/assets/{chunk-PWAF6VOD-Cz8IwBB5.js → chunk-PWAF6VOD-JSNrcBmP.js} +1 -1
  26. package/dist/client/assets/{chunk-RM4UPSZO-CWRwxNWJ.js → chunk-RM4UPSZO-DOWllDY8.js} +4 -4
  27. package/dist/client/assets/{chunk-RHFEMEQ7-CWY8cf4H.js → chunk-SHT3W25Y-BiQGljao.js} +5 -5
  28. package/dist/client/assets/{chunk-SVP7TREG-CyHOmcac.js → chunk-SVP7TREG-DB485R5x.js} +1 -1
  29. package/dist/client/assets/{chunk-LCL6LL3I-DmDkVukh.js → chunk-TICWLB2K-8rAVvoS3.js} +4 -4
  30. package/dist/client/assets/{chunk-CKBBP62Z-DG26UiBv.js → chunk-TLUHSLCS-DTY5v0aj.js} +2 -2
  31. package/dist/client/assets/classDiagram-ZZMXUADV-BsQWoR3Q.js +1 -0
  32. package/dist/client/assets/classDiagram-v2-VYDZK3BY-BsQWoR3Q.js +1 -0
  33. package/dist/client/assets/{comment-thread-store-CdcwrObc.js → comment-thread-store-CX98zR6q.js} +1 -1
  34. package/dist/client/assets/comment-threads-BnRwo5B9.js +4 -0
  35. package/dist/client/assets/{cynefinDiagram-5FMLGOSQ-CdTPi2yO.js → cynefinDiagram-5FMLGOSQ-rTz9RhFH.js} +1 -1
  36. package/dist/client/assets/{dagre-3AP2YEHR-5gtJtd0O.js → dagre-GXQ25YYZ-Cr67wLpQ.js} +2 -2
  37. package/dist/client/assets/{diagram-S7CK7UJ4-BudWz9WU.js → diagram-S7CK7UJ4-DywERe__.js} +2 -2
  38. package/dist/client/assets/{diagram-UQ7AKVKN-3v4rbH-s.js → diagram-UQ7AKVKN-CNYlXtu4.js} +1 -1
  39. package/dist/client/assets/diagram-VSXAHHWV-0H1a61Bn.js +3 -0
  40. package/dist/client/assets/{diagram-VX7I27RA-C_-rj0sw.js → diagram-VX7I27RA-CsJbsx5F.js} +1 -1
  41. package/dist/client/assets/{diagram-Z3DM3KII-B4yxavgj.js → diagram-Z3DM3KII-D0mLxEgI.js} +1 -1
  42. package/dist/client/assets/dist--hk9I5HQ.js +1 -0
  43. package/dist/client/assets/{dist-DutPuFmC.js → dist-B1XEa-Zs.js} +1 -1
  44. package/dist/client/assets/dist-Bd1JucQF.js +1 -0
  45. package/dist/client/assets/{dist-DZAAWTG-.js → dist-C0G3AaXG.js} +1 -1
  46. package/dist/client/assets/dist-ChRoo3IB.js +9 -0
  47. package/dist/client/assets/dist-Dm4w5UId.js +1 -0
  48. package/dist/client/assets/{dist-B_yQaEv_.js → dist-DpYDHR9p.js} +1 -1
  49. package/dist/client/assets/{dist-CietwTVS.js → dist-DzNmC81X.js} +1 -1
  50. package/dist/client/assets/{dist-DDUn5zTz.js → dist-GvvCNBe4.js} +1 -1
  51. package/dist/client/assets/dist-JaU3aRlD.js +19 -0
  52. package/dist/client/assets/{dist-Bw3VIE_v.js → dist-TW8iFRyW.js} +1 -1
  53. package/dist/client/assets/{dist-Dir5dDKZ.js → dist-jVU5Be5P.js} +1 -1
  54. package/dist/client/assets/document-formatter-rDDjRfZ2.js +2 -0
  55. package/dist/client/assets/drawioEditor-JubEEha7.js +9 -0
  56. package/dist/client/assets/ebnfDiagram-PWID7BFC-HeTxHpCU.js +1 -0
  57. package/dist/client/assets/editor-session-Bk6oIvSr.js +54 -0
  58. package/dist/client/assets/embedded-editor-base-BlCgz6mw.css +1 -0
  59. package/dist/client/assets/{erDiagram-SSCWMZ5O-C-iy6VkX.js → erDiagram-RLTQ6QDP-CbrDdd5P.js} +2 -2
  60. package/dist/client/assets/{es-CAsWR6hG.js → es-Bfdp096f.js} +13 -13
  61. package/dist/client/assets/estree-CuT_pB8K.js +44 -0
  62. package/dist/client/assets/excalidraw-element-link-YLIaTnVF.js +7 -0
  63. package/dist/client/assets/{excalidraw-scene-BOben2gr.js → excalidraw-scene-6uROebca.js} +1 -1
  64. package/dist/client/assets/{excalidraw-editor-BlcN6umJ.css → excalidrawEditor-BbSbI80a.css} +1 -1
  65. package/dist/client/assets/excalidrawEditor-dBMbRX_S.js +9 -0
  66. package/dist/client/assets/export-page-CRRQ2NEl.js +57 -0
  67. package/dist/client/assets/exportDocument-BlQRd9_m.js +2 -0
  68. package/dist/client/assets/exportDocument-CNSbjZwu.css +1 -0
  69. package/dist/client/assets/{file-icon-svg-CQAjlWjK.js → file-icon-svg-Y_kpF957.js} +1 -1
  70. package/dist/client/assets/file-kind-BwMIcZbi.js +1 -0
  71. package/dist/client/assets/file-search-DDLyyLDU.js +1 -0
  72. package/dist/client/assets/flowDiagram-HODETNUW-D5Gy0wmg.js +1 -0
  73. package/dist/client/assets/{ganttDiagram-EL5Y4UJY-DtKHAbez.js → ganttDiagram-EL5Y4UJY-BHgOYiZz.js} +1 -1
  74. package/dist/client/assets/{gitGraphDiagram-WWUBYQGX-oue8fQ5o.js → gitGraphDiagram-WWUBYQGX-Dl__X3Sk.js} +1 -1
  75. package/dist/client/assets/html-Cdnr2qzU.js +25 -0
  76. package/dist/client/assets/image-ZVKINSPA-DgzW5zAy.js +1 -0
  77. package/dist/client/assets/index-D3RER1SZ.js +1023 -0
  78. package/dist/client/assets/index-DREVKl_K.css +1 -0
  79. package/dist/client/assets/{infoDiagram-RXCK75RN-BMzo6KIn.js → infoDiagram-27XIBGKW-DBpoANC9.js} +1 -1
  80. package/dist/client/assets/{ishikawaDiagram-5VMMS53U-BIM3h287.js → ishikawaDiagram-5VMMS53U-BMPC6hfp.js} +1 -1
  81. package/dist/client/assets/{journeyDiagram-EYS64GPL-mF6Lh8O-.js → journeyDiagram-3NMN7TZE-B1sApUmM.js} +2 -2
  82. package/dist/client/assets/{kanban-definition-3QL26DDD-DLN2NyoR.js → kanban-definition-UXKFOSKX-C9yP4td1.js} +4 -4
  83. package/dist/client/assets/{line-BfTWJmgf.js → line-BFl3ujec.js} +1 -1
  84. package/dist/client/assets/markdown-CByV-4CU.js +70 -0
  85. package/dist/client/assets/{mermaid.core-CLZBlpIW.js → mermaid.core-BrY09czX.js} +5 -5
  86. package/dist/client/assets/mermaid.core-DfcNfOTv.js +1 -0
  87. package/dist/client/assets/{mindmap-definition-FBJOCRG2-CRyHaHTk.js → mindmap-definition-YA3MSWOX-BUQHcYbK.js} +8 -8
  88. package/dist/client/assets/pegDiagram-XKGWAZYB-Bi2Iml7Z.js +1 -0
  89. package/dist/client/assets/{pieDiagram-E7YTZNPT-B5OZPb88.js → pieDiagram-E7YTZNPT-_gYXnMoi.js} +1 -1
  90. package/dist/client/assets/preview-render-compiler-CfxJYldJ.js +41 -0
  91. package/dist/client/assets/preview-render-compiler-Cu8_i9iS.js +1 -0
  92. package/dist/client/assets/{preview-render-worker-BmN79bVc.js → preview-render-worker-c4Yi93qW.js} +41 -35
  93. package/dist/client/assets/prod-BiJL30sl.js +1 -0
  94. package/dist/client/assets/prod-qAk7rHa4.js +177 -0
  95. package/dist/client/assets/{quadrantDiagram-AXDQQJYC-Drrw14YH.js → quadrantDiagram-AXDQQJYC-DwexhEhd.js} +1 -1
  96. package/dist/client/assets/quick-switcher-controller-BoIK_wuG.js +1 -0
  97. package/dist/client/assets/railroadDiagram-O6MQD6OU-BVA5UbMu.js +1 -0
  98. package/dist/client/assets/{requirementDiagram-EFPCY7ZU-CRZG6mRB.js → requirementDiagram-BXWQKSXE-C4cKwiIw.js} +2 -2
  99. package/dist/client/assets/runtime-config-DcmnGcXU.js +1 -0
  100. package/dist/client/assets/{sankeyDiagram-P5KCCOFB-DvarEJpo.js → sankeyDiagram-P5KCCOFB-B5HHkRT2.js} +1 -1
  101. package/dist/client/assets/{sequenceDiagram-WJ2MYXX4-B4oWlb-w.js → sequenceDiagram-WJ2MYXX4-BX6jqJFD.js} +6 -6
  102. package/dist/client/assets/standalone-6z5x8CWe.js +29 -0
  103. package/dist/client/assets/{stateDiagram-HBIQ2CUA-qbHIIqRZ.js → stateDiagram-D77RDMKH-CmqxyRGx.js} +1 -1
  104. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-zoLLQVyh.js +1 -0
  105. package/dist/client/assets/{swimlanes-XN3QIQJK-xB6CtUGj.js → swimlanes-42K2YHIH-Bmgb9Zld.js} +1 -1
  106. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-DS-KQN37.js +8 -0
  107. package/dist/client/assets/{timeline-definition-24CTP7MA-Lj_yTNlY.js → timeline-definition-24CTP7MA-BA-lVH6P.js} +1 -1
  108. package/dist/client/assets/vault-api-client-iZLhMJKe.js +6 -0
  109. package/dist/client/assets/{vennDiagram-4TSXK5OY-BekRp5Y0.js → vennDiagram-4TSXK5OY-DNdUC_Xj.js} +1 -1
  110. package/dist/client/assets/{wardleyDiagram-VM6X3IG4-kdnV_Hdm.js → wardleyDiagram-VM6X3IG4-C2oY-YbF.js} +1 -1
  111. package/dist/client/assets/wiki-link-resolver-DFIwErjc.js +1 -0
  112. package/dist/client/assets/{xychartDiagram-S5SC5T6Z-DufGwNSB.js → xychartDiagram-S5SC5T6Z-CoIR8CBX.js} +1 -1
  113. package/dist/client/assets/yaml-9ltHPDNO.js +154 -0
  114. package/dist/client/assets/{yjs-provider-reset-guard-DE0vINDP.js → yjs-provider-reset-guard-9ul1qF6k.js} +1 -1
  115. package/dist/client/drawio-editor.html +11 -3
  116. package/dist/client/excalidraw-editor.html +45 -2
  117. package/dist/client/export-document.html +3 -3
  118. package/dist/client/index.html +106 -52
  119. package/integrations/pi/index.ts +94 -0
  120. package/package.json +41 -29
  121. package/src/client/app/drawio-editor.html +2 -2
  122. package/src/client/app/excalidraw-editor.html +2 -2
  123. package/src/client/app/export-document.html +1 -1
  124. package/src/client/app/index.html +88 -50
  125. package/src/client/app/main-entry.js +15 -1
  126. package/src/client/application/app-shell/chat-feature.js +7 -22
  127. package/src/client/application/app-shell/export-feature.js +17 -1
  128. package/src/client/application/app-shell/git-feature.js +51 -14
  129. package/src/client/application/app-shell/presence-feature.js +8 -25
  130. package/src/client/application/app-shell/ui-feature-identity.js +13 -0
  131. package/src/client/application/app-shell/ui-feature-shell.js +199 -99
  132. package/src/client/application/app-shell/ui-feature-sidebar.js +43 -7
  133. package/src/client/application/app-shell/ui-feature-tab-activity.js +19 -6
  134. package/src/client/application/app-shell/ui-feature-toolbar.js +16 -129
  135. package/src/client/application/app-shell-elements.js +8 -0
  136. package/src/client/application/preview-render-compiler.js +1 -87
  137. package/src/client/application/preview-render-scheduler.js +8 -24
  138. package/src/client/application/preview-renderer.js +2 -2
  139. package/src/client/application/webmcp-diagram-renderer.js +47 -0
  140. package/src/client/application/workspace-coordinator.js +23 -4
  141. package/src/client/application/workspace-preview-controller.js +120 -2
  142. package/src/client/application/workspace-route-controller.js +11 -1
  143. package/src/client/assets/vendor/jetbrains-mono/JetBrainsMono-Regular.woff2 +0 -0
  144. package/src/client/assets/vendor/jetbrains-mono/OFL.txt +93 -0
  145. package/src/client/bootstrap/collabmd-app-shell.js +99 -6
  146. package/src/client/domain/document-formatter.js +193 -0
  147. package/src/client/domain/excalidraw-element-link.js +73 -0
  148. package/src/client/domain/excalidraw-scene.js +21 -0
  149. package/src/client/domain/file-search.js +73 -0
  150. package/src/client/domain/git-labels.js +5 -0
  151. package/src/client/domain/hash-routes.js +8 -0
  152. package/src/client/domain/room.js +1 -5
  153. package/src/client/domain/runtime-paths.js +5 -0
  154. package/src/client/domain/vault-paths.js +6 -4
  155. package/src/client/domain/wiki-link-completions.js +20 -20
  156. package/src/client/drawio-editor.js +8 -3
  157. package/src/client/excalidraw-editor.js +287 -16
  158. package/src/client/export/export-host.js +59 -36
  159. package/src/client/export/export-page.js +14 -4
  160. package/src/client/export/export-pipeline.js +270 -42
  161. package/src/client/infrastructure/agent-connection-api-client.js +23 -0
  162. package/src/client/infrastructure/auth-client.js +3 -13
  163. package/src/client/infrastructure/editor-session.js +15 -0
  164. package/src/client/infrastructure/editor-view-adapter.js +73 -14
  165. package/src/client/infrastructure/excalidraw-room-client.js +80 -1
  166. package/src/client/infrastructure/git-api-client.js +39 -33
  167. package/src/client/infrastructure/lobby-presence.js +2 -5
  168. package/src/client/infrastructure/runtime-config.js +11 -1
  169. package/src/client/infrastructure/tab-activity-lock.js +2 -5
  170. package/src/client/infrastructure/vault-api-client.js +33 -26
  171. package/src/client/infrastructure/webmcp-tool-registry.js +283 -0
  172. package/src/client/infrastructure/workspace-sync-client.js +6 -4
  173. package/src/client/presentation/agent-connection-controller.js +255 -0
  174. package/src/client/presentation/backlinks-panel.js +3 -0
  175. package/src/client/presentation/bases-preview-controller.js +59 -26
  176. package/src/client/presentation/comment-ui/comment-ui-card.js +4 -2
  177. package/src/client/presentation/create-menu-presenter.js +19 -16
  178. package/src/client/presentation/excalidraw-embed-controller.js +164 -4
  179. package/src/client/presentation/file-action-controller.js +15 -2
  180. package/src/client/presentation/file-explorer-controller.js +3 -0
  181. package/src/client/presentation/file-explorer-view.js +71 -12
  182. package/src/client/presentation/file-history-view-controller.js +19 -12
  183. package/src/client/presentation/file-tree-state.js +1 -11
  184. package/src/client/presentation/git-diff-view-controller.js +70 -53
  185. package/src/client/presentation/git-panel-controller.js +86 -32
  186. package/src/client/presentation/image-lightbox-controller.js +20 -16
  187. package/src/client/presentation/layout-controller.js +3 -1
  188. package/src/client/presentation/quick-switcher-controller.js +74 -232
  189. package/src/client/presentation/quick-switcher-text-search.js +10 -14
  190. package/src/client/styles/components/navigation.css +1 -2
  191. package/src/client/styles/components/scrollbars.css +10 -0
  192. package/src/client/styles/export-document.css +44 -29
  193. package/src/client/styles/features/agent-connection.css +202 -0
  194. package/src/client/styles/features/collaboration-chat.css +8 -1
  195. package/src/client/styles/features/collaboration-dialogs.css +16 -1
  196. package/src/client/styles/features/collaboration-presence.css +30 -5
  197. package/src/client/styles/features/diff-toolbar.css +1 -1
  198. package/src/client/styles/features/media-lightbox.css +12 -3
  199. package/src/client/styles/features/preview-markdown.css +54 -0
  200. package/src/client/styles/features/quick-switcher.css +20 -11
  201. package/src/client/styles/foundation/themes.css +2 -0
  202. package/src/client/styles/foundation/tokens.css +8 -0
  203. package/src/client/styles/layout/editor-page.css +25 -11
  204. package/src/client/styles/layout/responsive.css +2 -20
  205. package/src/client/styles/layout/shell.css +77 -24
  206. package/src/client/styles/layout/sidebar.css +7 -4
  207. package/src/client/styles/layout/view-modes.css +2 -0
  208. package/src/client/styles/overrides/codemirror.css +31 -19
  209. package/src/client/styles/primitives/controls.css +21 -54
  210. package/src/client/styles/style.css +1 -0
  211. package/src/client/styles/surfaces/excalidraw-editor.css +42 -0
  212. package/src/domain/agent-tool-definitions.js +796 -0
  213. package/src/domain/collabmd-content-capabilities.js +149 -0
  214. package/src/domain/collaboration-protocol.js +2 -0
  215. package/src/domain/comment-threads.js +3 -5
  216. package/src/domain/diagram-source.js +50 -0
  217. package/src/domain/editable-content-revision.js +10 -0
  218. package/src/domain/editable-text.js +3 -0
  219. package/src/domain/exact-text-edits.js +69 -0
  220. package/src/domain/excalidraw-agent-scene.js +522 -0
  221. package/src/domain/excalidraw-agent-verification.js +460 -0
  222. package/src/domain/excalidraw-room-codec.js +1 -5
  223. package/src/domain/file-kind.js +12 -1
  224. package/src/domain/video-embed.js +76 -0
  225. package/src/server/application/agent-connection-service.js +178 -0
  226. package/src/server/application/agent-content-service.js +773 -0
  227. package/src/server/application/workspace-reconciliation.js +5 -7
  228. package/src/server/config/env.js +51 -1
  229. package/src/server/create-app-server.js +36 -0
  230. package/src/server/domain/bases/base-query-service.js +1 -5
  231. package/src/server/domain/collaboration/collaboration-room.js +121 -25
  232. package/src/server/domain/collaboration/protocol.js +4 -0
  233. package/src/server/domain/hosted-workspace.js +21 -0
  234. package/src/server/domain/markdown-reference-extractor.js +15 -1
  235. package/src/server/domain/ripgrep-search-service.js +110 -37
  236. package/src/server/infrastructure/git/git-service.js +19 -1
  237. package/src/server/infrastructure/git/history-service.js +1 -1
  238. package/src/server/infrastructure/git/local-exclude.js +25 -0
  239. package/src/server/infrastructure/git/parsers.js +19 -17
  240. package/src/server/infrastructure/git/path-utils.js +0 -16
  241. package/src/server/infrastructure/git/status-service.js +1 -1
  242. package/src/server/infrastructure/git/untracked-files.js +12 -21
  243. package/src/server/infrastructure/http/create-agent-api-handler.js +171 -0
  244. package/src/server/infrastructure/http/create-git-api-command-handler.js +32 -0
  245. package/src/server/infrastructure/http/create-request-handler.js +28 -0
  246. package/src/server/infrastructure/http/create-static-handler.js +6 -0
  247. package/src/server/infrastructure/mcp/create-agent-mcp-handler.js +199 -0
  248. package/src/server/infrastructure/persistence/agent-connection-store.js +120 -0
  249. package/src/server/infrastructure/persistence/path-utils.js +10 -4
  250. package/src/server/infrastructure/persistence/pull-backup-store.js +2 -27
  251. package/src/server/infrastructure/persistence/vault-file-store.js +11 -2
  252. package/src/server/shared/agent-tool-image.js +22 -0
  253. package/src/server/shared/agent-tool-rate-limiter.js +20 -0
  254. package/src/server/startup/git-remote-bootstrap.js +5 -33
  255. package/dist/client/assets/CodeMirrorEditor-UCMRAMCV-BPH4FJkv.js +0 -1
  256. package/dist/client/assets/abnfDiagram-VCTEODGH-BNDLzJ7L.js +0 -1
  257. package/dist/client/assets/browser-utils--H_DkyEF.js +0 -1
  258. package/dist/client/assets/channel-CaoKA_We.js +0 -1
  259. package/dist/client/assets/chunk-DSNCTWBM-8xkug7fQ.js +0 -2
  260. package/dist/client/assets/chunk-DU6HZSFF-COXDzJK1.js +0 -127
  261. package/dist/client/assets/chunk-R7TYR2AO-CTd0Yj98.js +0 -10
  262. package/dist/client/assets/classDiagram-DTDB5LWJ-7fEmn0zV.js +0 -1
  263. package/dist/client/assets/classDiagram-v2-JRS7N3AN-7fEmn0zV.js +0 -1
  264. package/dist/client/assets/comment-threads-9J6Em-_y.js +0 -4
  265. package/dist/client/assets/comment-ui-shared-DWkk9Vh3.js +0 -7
  266. package/dist/client/assets/diagram-VSXAHHWV-CQRVEZR7.js +0 -3
  267. package/dist/client/assets/dist-73RPdcyU.js +0 -1
  268. package/dist/client/assets/dist-CH-sQu3r.js +0 -1
  269. package/dist/client/assets/drawio-editor-BjrxTe3l.js +0 -9
  270. package/dist/client/assets/drawioEditor-DUVZjSSr.js +0 -2
  271. package/dist/client/assets/ebnfDiagram-PWID7BFC-OXa8VEp1.js +0 -1
  272. package/dist/client/assets/editor-session-DfZuRgB_.js +0 -54
  273. package/dist/client/assets/embedded-editor-base-DvMynhKu.css +0 -1
  274. package/dist/client/assets/excalidraw-editor-D7pnUCLH.js +0 -9
  275. package/dist/client/assets/excalidraw-mermaid-stub-BNckbX2n.js +0 -1
  276. package/dist/client/assets/excalidraw-mermaid-stub-DE5FTiZB.js +0 -1
  277. package/dist/client/assets/excalidrawEditor-B0jOK3lv.js +0 -2
  278. package/dist/client/assets/export-page-Bs3xE1fg.js +0 -57
  279. package/dist/client/assets/exportDocument-Dg9MjkIk.js +0 -2
  280. package/dist/client/assets/exportDocument-PnYU3v1s.css +0 -1
  281. package/dist/client/assets/file-kind-BbqgGzpc.js +0 -1
  282. package/dist/client/assets/flowDiagram-A5DVABFB-CiW1eN8C.js +0 -1
  283. package/dist/client/assets/image-ZVKINSPA-0zXSnE7M.js +0 -1
  284. package/dist/client/assets/index-BIpgxyGZ.css +0 -1
  285. package/dist/client/assets/index-Z5sI0Bj-.js +0 -2
  286. package/dist/client/assets/main-Dwnj9Gaq.js +0 -903
  287. package/dist/client/assets/pegDiagram-XKGWAZYB-B31fKPR2.js +0 -1
  288. package/dist/client/assets/preview-render-compiler-BApvlLLo.js +0 -35
  289. package/dist/client/assets/preview-render-compiler-BQ_3h9vD.js +0 -1
  290. package/dist/client/assets/preview-render-profile-CE-5rVTC.js +0 -1
  291. package/dist/client/assets/prod-BiYPMR1i.js +0 -177
  292. package/dist/client/assets/prod-VxdGZ5Ly.js +0 -1
  293. package/dist/client/assets/quick-switcher-controller-ButWPmCI.js +0 -12
  294. package/dist/client/assets/railroadDiagram-O6MQD6OU-BPifP0MB.js +0 -1
  295. package/dist/client/assets/runtime-config-BLrEKVO1.js +0 -1
  296. package/dist/client/assets/stateDiagram-v2-4QOOHH4V-B--gjrit.js +0 -1
  297. package/dist/client/assets/swimlanesDiagram-VK2B7HYN-DO8XNXEg.js +0 -8
  298. package/dist/client/assets/vault-api-client-_LpV1aIn.js +0 -6
  299. package/dist/client/assets/vault-utils-wdQ0RNR9.js +0 -1
  300. package/src/client/app/drawio-editor-entry.js +0 -1
  301. package/src/client/app/excalidraw-editor-entry.js +0 -1
  302. package/src/client/excalidraw-mermaid-stub.js +0 -7
  303. package/src/client/main.js +0 -16
  304. /package/dist/client/assets/{drawio-editor-UQQ8XHou.css → drawioEditor-UQQ8XHou.css} +0 -0
  305. /package/dist/client/assets/{sizeCapture-X5ZJPWSS-B0uUizjq.js → sizeCapture-INFHLROL-B0uUizjq.js} +0 -0
@@ -1,903 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./embedpdf-BmE13ZZ0.js","./embedpdf-DA4bA119-BPqZxwjc.js","./rolldown-runtime-Dd_uD5pT.js","./preload-helper-HclGiUj8.js","./mermaid.core-CLZBlpIW.js","./chunk-Y2CYZVJY-DsF7k-Jl.js","./src-oBChb5qS.js","./chunk-DU6HZSFF-COXDzJK1.js","./chunk-75Z2AOVW-CdFSaPjz.js","./dist-B_J_HbC0.js","./chunk-CLGD4ZFX-DQLgbQrv.js","./chunk-PWAF6VOD-Cz8IwBB5.js","./chunk-GMAD6QVW-CbcBqPM5.js","./chunk-P2QGCYS3-BRpqY32H.js","./chunk-TEH6E4GO-DVayPj-q.js","./rough.esm-Dy-Kn_BL.js","./chunk-OBVCFTLP-BJR7u1jh.js","./chunk-R7TYR2AO-CTd0Yj98.js","./line-BfTWJmgf.js","./path-fybaL0A-.js","./array-BifhSqXX.js","./chunk-JQ64N6SF-DSFNH4bh.js","./chunk-CKBBP62Z-DG26UiBv.js","./chunk-DSNCTWBM-8xkug7fQ.js","./graphlib-DS17s2tU.js","./chunk-LNGE3PJU-DWpGwHrW.js","./preview-render-compiler-BQ_3h9vD.js","./preview-render-compiler-BApvlLLo.js","./es-CAsWR6hG.js","./file-kind-BbqgGzpc.js","./preview-render-profile-CE-5rVTC.js","./vault-utils-wdQ0RNR9.js","./prod-VxdGZ5Ly.js","./chunk-RM4UPSZO-CWRwxNWJ.js","./chunk-SRAX5OIU-KFQikY-4.js","./prod-BiYPMR1i.js","./jsx-runtime-BpzPEenQ.js","./chunk-FLYJHZSQ-Be7lKF17.js","./chunk-7XWMRXBY-CfMzEq80.js","./excalidraw-mermaid-stub-BNckbX2n.js","./editor-session-DfZuRgB_.js","./dist-RKBTaQMb.js","./dist-BJ1bJs33.js","./dist-B_yQaEv_.js","./dist-Bw3VIE_v.js","./dist-CdmKGRGr.js","./dist-netZOQtD.js","./dist-BK9QvQrc.js","./dist-DuH3ZrHo.js","./dist-ByrG2qBA.js","./runtime-config-BLrEKVO1.js","./yjs-provider-reset-guard-DE0vINDP.js","./comment-threads-9J6Em-_y.js","./comment-thread-store-CdcwrObc.js","./quick-switcher-controller-ButWPmCI.js","./file-icon-svg-CQAjlWjK.js"])))=>i.map(i=>d[i]);
2
- import{t as e}from"./preload-helper-HclGiUj8.js";import{_ as t,a as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,n as d,o as f,p,r as m,s as h,t as g,u as _,v}from"./file-kind-BbqgGzpc.js";import{i as ee,n as te,r as ne}from"./preview-render-profile-CE-5rVTC.js";import{n as y,t as b}from"./vault-utils-wdQ0RNR9.js";import{a as x,c as S,d as C,f as w,g as T,h as E,i as D,l as O,m as k,n as A,o as j,p as M,r as N,s as re,t as ie,u as ae}from"./vault-api-client-_LpV1aIn.js";import{a as P,c as oe,d as se,f as ce,g as le,i as ue,l as F,m as de,n as fe,o as I,p as pe,r as me,s as he,t as ge,u as _e}from"./runtime-config-BLrEKVO1.js";import{n as ve,r as L,t as ye}from"./yjs-provider-reset-guard-DE0vINDP.js";import{r as be}from"./drawio-room-yBUzk-vg.js";import{a as xe,i as Se,n as Ce,o as R,r as we,t as z}from"./browser-utils--H_DkyEF.js";import{f as Te,p as Ee,t as De,u as Oe}from"./comment-threads-9J6Em-_y.js";import{C as ke,S as Ae,T as je,_ as Me,a as Ne,b as Pe,c as Fe,d as Ie,f as Le,g as Re,h as ze,i as Be,l as Ve,n as He,o as Ue,p as We,r as Ge,s as Ke,t as qe,u as Je,v as Ye,w as Xe,x as Ze,y as Qe}from"./comment-ui-shared-DWkk9Vh3.js";import{a as $e,c as et,d as tt,f as nt,h as B,i as rt,l as it,m as at,n as ot,o as st,p as ct,r as lt,s as ut,t as dt,u as ft}from"./preview-diagram-utils-txBCoW8d.js";import{t as pt}from"./file-icon-svg-CQAjlWjK.js";var mt=Object.freeze([`annotation`,`document-capture`,`document-close`,`document-open`,`document-print`,`document-protect`,`form`,`history`,`insert`,`panel-comment`,`redaction`,`rotate`]),ht=class{constructor({getTheme:t=()=>`dark`,loadEmbedPdf:n}={}){this.getTheme=t,this.loadEmbedPdf=n??(()=>e(()=>import(`./embedpdf-BmE13ZZ0.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)),this.renderToken=0,this.viewer=null}async render({filePath:e,renderHost:t}){this.cancel();let n=this.renderToken,r=document.createElement(`div`);r.className=`pdf-file-preview-viewer`,r.setAttribute(`aria-label`,`${String(e).split(`/`).pop()||e} PDF preview`),t.replaceChildren(r);try{let{default:t,LockModeType:i,ZoomMode:a}=await this.loadEmbedPdf();if(n!==this.renderToken||!r.isConnected)return;let o=t.init({type:`container`,target:r,src:F(`/download/file?path=${encodeURIComponent(e)}`),annotations:{locked:{type:i.All}},disabledCategories:mt,fontFallback:null,fonts:{signature:null,ui:null},stamp:{defaultLibrary:!1,manifests:[]},tabBar:`never`,theme:{preference:this.getTheme()},wasmUrl:new URL(``+new URL(`pdfium-RAgkpwfK.wasm`,import.meta.url).href,``+import.meta.url).toString(),zoom:{defaultZoomLevel:a.FitWidth,maxZoom:2,minZoom:.5,zoomStep:.25}});this.viewer=o}catch{if(n!==this.renderToken)return;r.classList.add(`pdf-file-preview-error`),r.textContent=`This PDF could not be rendered in the browser.`}}setTheme(e){this.viewer?.setTheme?.(e)}cancel(){this.renderToken+=1,this.viewer?.remove(),this.viewer=null}},gt=Object.freeze({htmlLabels:!1,flowchart:{defaultRenderer:`dagre-wrapper`,htmlLabels:!1,useMaxWidth:!0},class:{defaultRenderer:`dagre-wrapper`,htmlLabels:!1,useMaxWidth:!0},startOnLoad:!1,theme:`default`}),_t=/^\s*%%\{\s*(?:init|initialize)\s*:[\s\S]*?\}%%\s*\n?/gim,vt=0;function yt(){return vt+=1,`mermaid-export-${vt.toString(36)}`}async function bt(e){if(typeof e.toBlob==`function`){let t=await new Promise(t=>e.toBlob(t,`image/png`));if(t instanceof Blob)return t}return xt(e.toDataURL(`image/png`))}function xt(e){let[t=``,n=``]=String(e).split(`,`,2),r=t.match(/^data:([^;,]+)?/u)?.[1]||`application/octet-stream`;if(t.includes(`;base64`)){let e=atob(n),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return new Blob([t],{type:r})}return new Blob([decodeURIComponent(n)],{type:r})}function St(e){let t=e.cloneNode(!0);if(!(t instanceof SVGSVGElement))throw Error(`Renderer returned invalid SVG`);t.style.removeProperty(`display`),t.style.removeProperty(`margin`),t.style.removeProperty(`max-width`),t.style.removeProperty(`height`),t.style.removeProperty(`width`),t.setAttribute(`xmlns`,`http://www.w3.org/2000/svg`);let{width:n,height:r}=tt(t);return t.setAttribute(`width`,String(Math.max(1,Math.ceil(n)))),t.setAttribute(`height`,String(Math.max(1,Math.ceil(r)))),t}function Ct(e,{padding:t=16}={}){let n=St(e);if(typeof e.getBBox!=`function`)return n;try{let r=e.getBBox();if(!r||r.width<=0||r.height<=0)return n;let i=Math.max(0,Number(t)||0),a=Math.ceil(r.width+i*2),o=Math.ceil(r.height+i*2),s=[Math.floor(r.x-i),Math.floor(r.y-i),a,o];return n.setAttribute(`viewBox`,s.join(` `)),n.setAttribute(`width`,String(a)),n.setAttribute(`height`,String(o)),n.setAttribute(`preserveAspectRatio`,`xMidYMid meet`),n}catch{return n}}function wt({currentFilePath:e=``,diagramKind:t=`diagram`,sourceLine:n=``,targetPath:r=``}={}){let a=w(r);if(a)return o(a)||`${t}-diagram`;let s=w(e),c=o(s)||`document`;return t===`mermaid`&&i(e)||t===`plantuml`&&p(e)?c:n?`${c}-${t}-L${n}`:`${c}-${t}`}function Tt(e={}){let t=wt(e);return{baseName:t,pngFileName:`${t}.png`,svgFileName:`${t}.svg`}}function Et(e){let t=St(e);return ct(t)}function Dt(e,t={}){return ct(Ct(e,t))}function Ot(e){let t=String(e??``).replace(_t,``);if(t=`%%{init: ${JSON.stringify(gt)}}%%\n${t}`,/^\s*gantt\b/m.test(t)&&!/\btodayMarker\b/.test(t)){let e=t.split(`
3
- `),n=e.findIndex(e=>/^\s*gantt\b/.test(e));n!==-1&&(e.splice(n+1,0,` todayMarker off`),t=e.join(`
4
- `))}return t}async function kt(e,t){if(!e?.initialize||!e?.run)throw Error(`Mermaid runtime is unavailable`);e.initialize(gt);let n=document.createElement(`div`);n.style.position=`fixed`,n.style.left=`-10000px`,n.style.top=`0`,n.style.width=`1200px`,n.style.visibility=`hidden`,n.style.pointerEvents=`none`,document.body.appendChild(n);try{let r=document.createElement(`div`);r.className=`mermaid mermaid-export-node`,r.id=yt(),r.textContent=Ot(t),n.appendChild(r),await e.run({nodes:[r]});let i=r.querySelector(`svg`);if(!(i instanceof SVGSVGElement))throw Error(`Mermaid export returned no SVG`);return Dt(i,{padding:24})}finally{n.remove()}}async function At(e){let t=nt(e),n=await et($e(t)),r=document.createElement(`div`);r.innerHTML=t;let i=r.querySelector(`svg`),{width:a,height:o}=i?tt(i):{height:n.naturalHeight||800,width:n.naturalWidth||1200},s=document.createElement(`canvas`);s.width=Math.max(1,Math.ceil(a)),s.height=Math.max(1,Math.ceil(o));let c=s.getContext(`2d`);if(!c)throw Error(`Canvas is unavailable`);return c.fillStyle=`#ffffff`,c.fillRect(0,0,s.width,s.height),c.drawImage(n,0,0,s.width,s.height),bt(s)}async function jt(e){if(typeof ClipboardItem!=`function`||!navigator.clipboard?.write)throw Error(`Clipboard image copy is unavailable`);await navigator.clipboard.write([new ClipboardItem({[e.type||`image/png`]:e})])}function Mt(e){return`data-${e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`}var Nt=class{constructor(e,{batchSize:t,datasetKeys:n,loadFileSource:r=null,filePathLabel:i,requestIdleRenderFn:a=R,cancelIdleRenderFn:o=z,intersectionObserverFactory:s=(e,t)=>new IntersectionObserver(e,t),isNearViewportFn:c=we,requestAnimationFrameFn:l=e=>requestAnimationFrame(e),shellClassName:u,sourceClassName:d}){this.renderer=e,this.batchSize=t,this.datasetKeys=n,this.loadFileSource=r,this.filePathLabel=i,this.requestIdleRenderFn=a,this.cancelIdleRenderFn=o,this.intersectionObserverFactory=s,this.isNearViewportFn=c,this.requestAnimationFrameFn=l,this.shellClassName=u,this.sourceClassName=d,this.shellSelector=`.${u}`,this.sourceSelector=`.${d}`,this.attributeNames=Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Mt(t)])),this.observer=null,this.idleId=null,this.pendingShells=[],this.hydrationInProgress=!1,this.hydrationToken=0,this.hydrationRenderVersion=null,this.instanceCounter=0,this.preservedShells=[],this.fileInflightRequests=new Map}destroy(){this.cancelHydration(),this.clearPreservedShells()}cancelHydration(){this.hydrationToken+=1,this.hydrationRenderVersion=null,this.observer&&=(this.observer.disconnect(),null),this.cancelIdleRenderFn(this.idleId),this.idleId=null,this.pendingShells=[],this.hydrationInProgress=!1}cancelPendingIdleWork(){this.cancelIdleRenderFn(this.idleId),this.idleId=null}clearPreservedShells(){this.preservedShells.forEach(({shell:e})=>{this.renderer.diagramChrome?.destroyShell?.(e)}),this.preservedShells.length=0}getPreviewShells(){let e=this.renderer.previewElement;if(!e)return[];let t=e.ownerDocument?.querySelectorAll?.(this.shellSelector);return t?Array.from(t):Array.from(e.querySelectorAll(this.shellSelector))}getPreservationIdentity(e){let t=e?.getAttribute?.(this.attributeNames.sourceLine);return t?`${this.shellClassName}:${t}`:null}isShellRenderable(e){return this.isShellHydrated(e)||e?.getAttribute?.(`data-diagram-output`)===`true`}isShellError(e){return e?.getAttribute?.(`data-diagram-state`)===`error`}hasPendingWork(){return this.hydrationInProgress||this.pendingShells.length>0}preserveHydratedShellsForCommit(){this.preservedShells.length=0,this.renderer.previewElement&&this.getPreviewShells().filter(e=>this.isShellRenderable(e)).forEach(e=>{let t=e.dataset[this.datasetKeys.key],n=e.querySelector(this.sourceSelector)?.textContent??``,r=e.dataset[this.datasetKeys.target]??``;!t||!n&&!r||(e.isConnected&&(this.renderer.diagramChrome?.captureShellViewState?.(e),e.remove()),this.preservedShells.push({key:t,identity:this.getPreservationIdentity(e),shell:e,source:n,target:r}))})}reconcileHydratedShells(){let e=this.renderer.previewElement;if(!e||this.preservedShells.length===0){this.clearPreservedShells();return}let t=!1;Array.from(e.querySelectorAll(`${this.shellSelector}[${this.attributeNames.key}]`)).forEach(e=>{let n=e.dataset[this.datasetKeys.key],r=n?this.preservedShells.findIndex(e=>e.key===n):-1;if(r===-1){let t=this.getPreservationIdentity(e);r=t?this.preservedShells.findIndex(e=>e.identity===t):-1}if(r===-1)return;let i=this.preservedShells[r],a=e.querySelector(this.sourceSelector)?.textContent??``,o=e.dataset[this.datasetKeys.target]??``,s=this.isShellRenderable(i.shell)&&a!==i.source&&!o;if(!at({nextSource:a,nextTarget:o,preservedSource:i.source,preservedTarget:i.target})&&!s)return;this.syncPreservedShell(i.shell,e,{sourceChanged:s}),e.replaceWith(i.shell);let c=this.renderer.diagramChrome?.getShellViewState?.(i.shell),l=i.shell.querySelector(`.diagram-preview-frame`);c&&l&&(l.scrollLeft=c.scrollLeft??0,l.scrollTop=c.scrollTop??0),t||=i.shell.classList.contains(`is-maximized`),this.preservedShells.splice(r,1)}),this.preservedShells.forEach(({shell:e})=>{this.renderer.diagramChrome?.destroyShell?.(e)}),this.preservedShells.length=0,this.handleReconcile({restoredMaximizedShell:t})}handleReconcile(){}syncPreservedShell(e,t,{sourceChanged:n=!1}={}){B(e,t,this.attributeNames.sourceLine),B(e,t,this.attributeNames.sourceLineEnd),B(e,t,this.attributeNames.key),B(e,t,this.attributeNames.target),B(e,t,this.attributeNames.label),B(e,t,this.attributeNames.sourceHash),e.classList.add(this.shellClassName),this.removeDatasetValue(e,`queued`);let r=t.querySelector(this.sourceSelector),i=e.querySelector(this.sourceSelector);if(!i&&r&&(i=r.cloneNode(!0),e.prepend(i)),i&&r){let e=r.textContent??``;(e||!t.dataset[this.datasetKeys.target])&&(i.textContent=e),i.hidden=!0}if(n){this.markShellPending(e);return}if(this.isShellError(e)){e.dataset[this.datasetKeys.hydrated]=`true`;return}this.markShellHydrated(e)}getShellErrorCard(e){return e?.querySelector?.(`:scope > .diagram-preview-error-card`)??null}notifyShellLayoutChange(){this.renderer.onPreviewLayoutChange?.({renderVersion:this.renderer.activeRenderVersion})}clearShellErrorCard(e){e&&(this.getShellErrorCard(e)?.remove?.(),this.notifyShellLayoutChange())}getShellLabel(e){return e?.dataset?.[this.datasetKeys.label]||`${this.filePathLabel} diagram`}markShellRendered(e){e&&(e.setAttribute(`data-diagram-output`,`true`),e.removeAttribute(`data-diagram-state`),e.removeAttribute(`aria-busy`),this.clearShellErrorCard(e))}markShellPending(e){return this.isShellRenderable(e)?(this.removeDatasetValue(e,`hydrated`),e.setAttribute(`data-diagram-output`,`true`),e.setAttribute(`data-diagram-state`,`pending`),e.setAttribute(`aria-busy`,`true`),this.getShellErrorCard(e)&&this.clearShellErrorCard(e),!0):!1}markShellError(e,t){if(!this.isShellRenderable(e))return!1;let n=it(t);e.dataset[this.datasetKeys.hydrated]=`true`,e.setAttribute(`data-diagram-output`,`true`),e.setAttribute(`data-diagram-state`,`error`),e.removeAttribute(`aria-busy`),this.getShellErrorCard(e)?.remove?.();let r=this.shellClassName.replace(/-shell$/,``);return e.append(dt({key:e.dataset[this.datasetKeys.key],kind:r,label:this.getShellLabel(e),message:n,subtitle:`Showing the last valid result.`})),this.notifyShellLayoutChange(),!0}clearShellOutput(e){this.removeDatasetValue(e,`hydrated`),e?.removeAttribute?.(`data-diagram-output`),e?.removeAttribute?.(`data-diagram-state`),e?.removeAttribute?.(`aria-busy`),this.clearShellErrorCard(e)}markPending(){this.cancelHydration(),this.getPreviewShells().filter(e=>this.isShellRenderable(e)).forEach(e=>{this.markShellPending(e)})}retryShell(e){e?.isConnected&&(this.removeDatasetValue(e,`hydrated`),this.markShellPending(e),this.enqueueShell(e,{prioritize:!0}))}isHydrationCurrent(e,t,n=this.hydrationToken){return!!(t?.isConnected&&n===this.hydrationToken&&(e==null||e===this.hydrationRenderVersion&&e===this.renderer.activeRenderVersion))}setupHydration(e){let t=this.renderer.previewElement,n=this.renderer.previewContainer;if(!t||!n)return 0;let r=Array.from(t.querySelectorAll(this.shellSelector));if(r.length===0)return 0;this.hydrationToken+=1;let i=this.hydrationToken;return this.hydrationRenderVersion=e,this.observer=this.intersectionObserverFactory(e=>{e.forEach(e=>{e.isIntersecting&&this.enqueueShell(e.target)})},{root:n,rootMargin:this.renderer.isLargeDocument?`180px 0px`:`420px 0px`}),r.forEach(e=>this.observer.observe(e)),this.requestAnimationFrameFn(()=>{this.isHydrationCurrent(e,t,i)&&(this.hydrateVisibleShells(),this.renderer.updateHydrationPhase())}),r.length}hydrateVisibleShells(){let e=this.renderer.previewElement,t=this.renderer.previewContainer;if(this.renderer.hydrationPaused||!e||!t)return;let n=this.renderer.isLargeDocument?180:420;Array.from(e.querySelectorAll(this.shellSelector)).forEach(e=>{this.isNearViewportFn(e,t,n)&&this.enqueueShell(e,{prioritize:!0})})}enqueueShell(e,{prioritize:t=!1}={}){!e?.isConnected||this.isShellHydrated(e)||this.isShellQueued(e)||(e.dataset[this.datasetKeys.queued]=`true`,t?this.pendingShells.unshift(e):this.pendingShells.push(e),!this.renderer.hydrationPaused&&(this.renderer.updateHydrationPhase(),this.scheduleHydration()))}scheduleHydration(){this.renderer.hydrationPaused||this.hydrationInProgress||this.idleId!==null||(this.idleId=this.requestIdleRenderFn(()=>{this.idleId=null,this.flushHydrationQueue()},500))}async flushHydrationQueue(){if(this.renderer.hydrationPaused||this.hydrationInProgress)return;let e=this.hydrationToken,t=this.hydrationRenderVersion,n=[];for(;this.pendingShells.length>0&&n.length<this.batchSize;){let e=this.pendingShells.shift();!e?.isConnected||this.isShellHydrated(e)||(this.removeDatasetValue(e,`queued`),n.push(e))}if(n.length===0){this.renderer.updateHydrationPhase();return}this.hydrationInProgress=!0,this.renderer.setPhase(`hydrating`);let r;try{r=await this.prepareHydrationBatch(n)}catch(t){if(e!==this.hydrationToken)return;this.handlePrepareHydrationBatchError(n,t),this.hydrationInProgress=!1,this.renderer.updateHydrationPhase();return}for(let i of n){if(e!==this.hydrationToken)return;await this.hydrateShell(i,r,{hydrationToken:e,renderVersion:t})}e===this.hydrationToken&&(this.hydrationInProgress=!1,this.pendingShells.length>0&&this.scheduleHydration(),this.renderer.updateHydrationPhase())}async prepareHydrationBatch(){return null}handlePrepareHydrationBatchError(e,t){}async hydrateShell(){throw Error(`hydrateShell must be implemented by subclasses`)}markShellHydrated(e){this.markShellRendered(e),e.dataset[this.datasetKeys.hydrated]=`true`,e.dataset[this.datasetKeys.instanceId]=String(++this.instanceCounter)}isShellHydrated(e){return e?.dataset?.[this.datasetKeys.hydrated]===`true`}removeDatasetValue(e,t){let n=this.datasetKeys[t];!n||!e||(e.removeAttribute?.(this.attributeNames[t]),e.dataset&&delete e.dataset[n])}isShellQueued(e){return e?.dataset?.[this.datasetKeys.queued]===`true`}async fetchSource(e){let t=String(e??``).trim();if(!t)throw Error(`Missing ${this.filePathLabel} file path`);if(this.fileInflightRequests.has(t))return this.fileInflightRequests.get(t);if(typeof this.loadFileSource!=`function`)throw Error(`Missing ${this.filePathLabel} source loader`);let n=this.loadFileSource(t).finally(()=>{this.fileInflightRequests.delete(t)});return this.fileInflightRequests.set(t,n),n}},Pt=class extends Nt{constructor(e,{loadFileSource:t=null}={}){super(e,{batchSize:2,datasetKeys:{hydrated:`mermaidHydrated`,instanceId:`mermaidInstanceId`,key:`mermaidKey`,label:`mermaidLabel`,queued:`mermaidQueued`,sourceHash:`mermaidSourceHash`,sourceLine:`sourceLine`,sourceLineEnd:`sourceLineEnd`,target:`mermaidTarget`},filePathLabel:`Mermaid`,loadFileSource:t,shellClassName:`mermaid-shell`,sourceClassName:`mermaid-source`}),this.currentTheme=document.documentElement?.dataset.theme===`light`?`light`:`dark`,this.diagramChrome=e.diagramChrome,this.loader=null,this.runtime=null}cancelHydration({preserveActiveShell:e=!1}={}){super.cancelHydration(),e||this.diagramChrome?.cancelActiveShell?.(`mermaid`)}applyTheme(e){this.currentTheme=e;let t=this.runtime;t&&(this.configureMermaid(t),this.resetHydratedShells())}configureMermaid(e){e.initialize({startOnLoad:!1,htmlLabels:!1,flowchart:{defaultRenderer:`dagre-wrapper`,htmlLabels:!1,useMaxWidth:!0},class:{defaultRenderer:`dagre-wrapper`,useMaxWidth:!0},theme:this.currentTheme===`dark`?`dark`:`default`,themeVariables:this.currentTheme===`dark`?{background:`#11161d`,clusterBkg:`#141a22`,edgeLabelBackground:`#11161d`,lineColor:`#9aa7b4`,mainBkg:`#171d26`,nodeBorder:`#303c4b`,primaryBorderColor:`#60a5fa`,primaryColor:`#172a45`,primaryTextColor:`#e6edf3`,secondaryColor:`#1c2530`,tertiaryColor:`#11161d`,titleColor:`#e6edf3`}:{}})}ensureMermaid(){return this.runtime?(this.configureMermaid(this.runtime),Promise.resolve(this.runtime)):(this.loader||=e(()=>import(`./mermaid.core-CLZBlpIW.js`).then(e=>{let t=e?.default;if(!t)throw Error(`Mermaid runtime failed to initialize`);return this.runtime=t,this.configureMermaid(t),t}),__vite__mapDeps([4,3,5,6,2,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]),import.meta.url).catch(e=>{throw this.loader=null,this.runtime=null,Error(e instanceof Error?e.message:`Failed to load Mermaid runtime`)}),this.loader)}handleReconcile({restoredMaximizedShell:e}){e&&document.body.classList.add(`mermaid-maximized-open`),this.diagramChrome?.syncActiveShell?.()}async prepareHydrationBatch(){return this.ensureMermaid()}handlePrepareHydrationBatchError(e,t){console.warn(`[preview] Mermaid runtime failed to load:`,t)}createRenderHost(){let e=document.createElement(`div`);return e.style.position=`fixed`,e.style.left=`-10000px`,e.style.top=`0`,e.style.width=`1200px`,e.style.visibility=`hidden`,e.style.pointerEvents=`none`,document.body.appendChild(e),e}async hydrateShell(e,t,{hydrationToken:n,renderVersion:r}={}){if(!t||!e?.isConnected||this.isShellHydrated(e)||!this.isHydrationCurrent(r,e,n))return;let i=e.querySelector(`.mermaid-source`);i||(i=document.createElement(`span`),i.className=`mermaid-source`,i.hidden=!0,e.appendChild(i));let a=i.textContent??``;try{if(!a.trim()&&e.dataset.mermaidTarget){if(a=await this.fetchSource(e.dataset.mermaidTarget),!e.isConnected)return;i.textContent=a}if(!a.trim())throw Error(e.dataset.mermaidTarget?`Mermaid file is empty`:`Mermaid source is empty`);if(!this.isHydrationCurrent(r,e,n))return;let o=a;a=this.prepareSource(a),e.querySelector(`.mermaid-placeholder-card`)?.remove();let s=document.createElement(`div`);s.className=`mermaid mermaid-render-node`,s.id=e.dataset.mermaidKey||`mermaid-${Date.now()}`;let c=e.getAttribute(`data-source-line`),l=e.getAttribute(`data-source-line-end`);c&&s.setAttribute(`data-source-line`,c),l&&s.setAttribute(`data-source-line-end`,l),s.textContent=a;let u=this.createRenderHost();try{if(u.appendChild(s),await t.run({nodes:[s]}),!this.isHydrationCurrent(r,e,n)||!s.isConnected||s.parentElement!==u)return;this.enhanceDiagram(e,s,o),this.markShellHydrated(e)}finally{u.remove()}}catch(t){if(console.warn(`[preview] Mermaid render failed:`,t),!this.isHydrationCurrent(r,e,n)||this.markShellError(e,t))return;if(this.diagramChrome?.destroyShell?.(e),e.querySelector(`:scope > .mermaid-toolbar`)?.remove(),e.querySelector(`:scope > .mermaid-frame`)?.remove(),e.querySelector(`:scope > .mermaid-render-node`)?.remove(),!e.querySelector(`.mermaid-placeholder-card`)){let n=e.dataset.mermaidKey||`mermaid`,r=it(t);i?.after(dt({key:n,kind:`mermaid`,label:e.dataset.mermaidLabel||`Mermaid diagram`,message:r}))}}}prepareSource(e){let t=String(e??``);if(!/%%\{[\s\S]*?\binit\s*:/m.test(t)){let e=this.getPreviewInitConfig(t);e&&(t=`%%{init: ${JSON.stringify(e)}}%%\n${t}`)}if(!/^\s*gantt\b/m.test(t)||/\btodayMarker\b/.test(t))return t;let n=t.split(`
5
- `),r=n.findIndex(e=>/^\s*gantt\b/.test(e));return r===-1?t:(n.splice(r+1,0,` todayMarker off`),n.join(`
6
- `))}getPreviewInitConfig(e){return/^\s*stateDiagram(?:-v2)?\b/m.test(e)||/^\s*classDiagram\b/m.test(e)||/^\s*gantt\b/m.test(e)?{htmlLabels:!1}:null}resetHydratedShells(){let e=this.renderer.previewElement;if(!e)return;let t=Array.from(e.querySelectorAll(`.mermaid-shell[data-mermaid-hydrated="true"]`)),n=this.diagramChrome?.syncActiveShell?.();n?.classList?.contains(`mermaid-shell`)&&!t.includes(n)&&t.push(n),t.length!==0&&t.forEach(e=>{this.diagramChrome?.destroyShell?.(e),this.clearShellOutput(e),e.querySelector(`:scope > .mermaid-toolbar`)?.remove(),e.querySelector(`:scope > .mermaid-frame`)?.remove(),e.querySelector(`:scope > .mermaid-render-node`)?.remove(),e.querySelector(`.mermaid-placeholder-card`)||e.querySelector(`.mermaid-source`)?.after(ot(e.dataset.mermaidKey||`mermaid`)),this.enqueueShell(e,{prioritize:!0})})}async renderExportSvgMarkup(e){let t=await this.ensureMermaid();try{return await kt(t,e._diagramRenderedSource??e.querySelector(`.mermaid-source`)?.textContent??``)}finally{this.configureMermaid(t)}}enhanceDiagram(e,t,n=``){let r=t.querySelector(`svg`);if(!r){t.remove();return}let{width:i,height:a}=ft(r);t.remove(),this.diagramChrome.mount(e,{baseHeight:a,baseWidth:i,diagramElement:r,exportFileNames:()=>Tt({currentFilePath:this.renderer.getSourceFilePath?.()??``,diagramKind:`mermaid`,sourceLine:e.getAttribute(`data-source-line`)||``,targetPath:e.dataset.mermaidTarget||``}),exportSvgMarkup:()=>this.renderExportSvgMarkup(e),kind:`mermaid`,sourceSelector:`.mermaid-source`}),e._diagramRenderedSource=n}},Ft=class extends Nt{constructor(e,{loadFileSource:t=null,renderClient:n=null}={}){super(e,{batchSize:2,datasetKeys:{hydrated:`plantumlHydrated`,instanceId:`plantumlInstanceId`,key:`plantumlKey`,label:`plantumlLabel`,queued:`plantumlQueued`,sourceHash:`plantumlSourceHash`,sourceLine:`sourceLine`,sourceLineEnd:`sourceLineEnd`,target:`plantumlTarget`},filePathLabel:`PlantUML`,loadFileSource:t,shellClassName:`plantuml-shell`,sourceClassName:`plantuml-source`}),this.diagramChrome=e.diagramChrome,this.renderClient=n,this.svgCache=new Map,this.svgInflightRequests=new Map}cancelHydration({preserveActiveShell:e=!1}={}){super.cancelHydration(),e||this.diagramChrome?.cancelActiveShell?.(`plantuml`)}handleReconcile({restoredMaximizedShell:e}){e&&document.body.classList.add(`plantuml-maximized-open`),this.diagramChrome?.syncActiveShell?.()}async hydrateShell(e,t,{hydrationToken:n,renderVersion:r}={}){if(!e?.isConnected||this.isShellHydrated(e)||!this.isHydrationCurrent(r,e,n))return;let i=e.querySelector(`.plantuml-source`);i||(i=document.createElement(`span`),i.className=`plantuml-source`,i.hidden=!0,e.appendChild(i)),e.querySelector(`.plantuml-placeholder-card`)?.remove();try{let t=i.textContent??``;if(!t.trim()&&e.dataset.plantumlTarget){if(t=await this.fetchSource(e.dataset.plantumlTarget),!e.isConnected)return;i.textContent=t}if(!t.trim())throw Error(e.dataset.plantumlTarget?`PlantUML file is empty`:`PlantUML source is empty`);if(!this.isHydrationCurrent(r,e,n))return;let a=await this.fetchSvg(t);if(!this.isHydrationCurrent(r,e,n))return;this.enhanceDiagram(e,a),this.markShellHydrated(e)}catch(t){if(console.warn(`[preview] PlantUML render failed:`,t),!this.isHydrationCurrent(r,e,n)||this.markShellError(e,t))return;let a=e.dataset.plantumlKey||`plantuml`,o=it(t);e.querySelector(`:scope > .plantuml-toolbar`)?.remove(),e.querySelector(`:scope > .plantuml-frame`)?.remove(),e.querySelector(`.plantuml-placeholder-card`)||i?.after(dt({key:a,kind:`plantuml`,label:e.dataset.plantumlLabel||`PlantUML diagram`,message:o}))}}async fetchSvg(e){let t=e;if(this.svgCache.has(t))return this.svgCache.get(t);if(this.svgInflightRequests.has(t))return this.svgInflightRequests.get(t);let n=this.renderClient.renderSvg(e).then(e=>{let n=nt(e);return this.svgCache.set(t,n),n}).finally(()=>{this.svgInflightRequests.delete(t)});return this.svgInflightRequests.set(t,n),n}resetShell(e,{clearCache:t=!1,message:n=`Renders server-side when visible`}={}){let r=e.querySelector(`.plantuml-source`)?.textContent??``;t&&r&&(this.svgCache.delete(r),this.svgInflightRequests.delete(r)),this.diagramChrome?.destroyShell?.(e),this.clearShellOutput(e),e.removeAttribute(`data-plantuml-instance-id`),e.removeAttribute(`data-plantuml-queued`),e.classList.remove(`is-maximized`),this.diagramChrome?.syncBodyMaximizedClasses?.(),e.querySelector(`:scope > .plantuml-toolbar`)?.remove(),e.querySelector(`:scope > .plantuml-frame`)?.remove(),e.querySelector(`.plantuml-placeholder-card`)||e.querySelector(`.plantuml-source`)?.after(lt(e.dataset.plantumlKey||`plantuml`,n))}enhanceDiagram(e,t){let n=document.createElement(`div`);n.innerHTML=t;let r=n.querySelector(`svg`);if(!r)throw Error(`Renderer returned invalid SVG`);let{width:i,height:a}=ut(r);this.diagramChrome.mount(e,{baseHeight:a,baseWidth:i,diagramElement:r,exportFileNames:()=>Tt({currentFilePath:this.renderer.getSourceFilePath?.()??``,diagramKind:`plantuml`,sourceLine:e.getAttribute(`data-source-line`)||``,targetPath:e.dataset.plantumlTarget||``}),exportSvgMarkup:()=>Et(r),kind:`plantuml`,onReload:()=>{this.resetShell(e,{clearCache:!0,message:`Refreshing…`}),this.enqueueShell(e,{prioritize:!0})},sourceSelector:`.plantuml-source`})}},It={copy:`
7
- <svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
8
- <path d="M5.5 5.5h6.8v8h-6.8z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
9
- <path d="M3.7 10.5H3a1 1 0 0 1-1-1v-6a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v.7" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
10
- </svg>
11
- `,download:`
12
- <svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
13
- <path d="M8 2.2v7.2" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
14
- <path d="M5.3 7.2 8 10l2.7-2.8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
15
- <path d="M3 12.8h10" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
16
- </svg>
17
- `,edit:`
18
- <svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
19
- <path d="M11.8 1.8a1.5 1.5 0 0 1 2.1 2.1l-7.2 7.2-3.2.9.9-3.2z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
20
- <path d="M10.7 2.9l2.4 2.4" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
21
- </svg>
22
- `,fit:`
23
- <svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
24
- <path d="M5.5 6.2V3H2.3M10.5 6.2V3h3.2M10.5 9.8V13h3.2M5.5 9.8V13H2.3" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
25
- <path d="M5.5 6.2h5M5.5 9.8h5" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
26
- </svg>
27
- `,maximize:`
28
- <svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
29
- <path d="M6 2H2v4M10 2h4v4M14 10v4h-4M2 10v4h4" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
30
- </svg>
31
- `,refresh:`
32
- <svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
33
- <path d="M13 4.5V1.8M13 1.8h-2.7M13 11.5v2.7M13 14.2h-2.7" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
34
- <path d="M12.3 4.2A5.3 5.3 0 1 0 13 11.8" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
35
- </svg>
36
- `,restore:`
37
- <svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
38
- <path d="M6 5V2H2M10 5V2h4M10 11v3h4M6 11v3H2" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
39
- <path d="M4.5 4.5h7v7h-7z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
40
- </svg>
41
- `};function V(e,t){if(!(e instanceof HTMLElement))return;let n=It[t];if(!n){e.classList.remove(`is-icon-only`),e.classList.remove(`ui-preview-action--icon-only`);return}e.classList.add(`is-icon-only`),e.classList.add(`ui-preview-action--icon-only`),e.dataset.icon=t,e.innerHTML=n.trim()}var Lt=Object.freeze({animationDurationMs:160,default:1,max:3,min:.1,step:.1,wheelSensitivity:.01}),Rt=Object.freeze({mermaid:{...Lt,fitMax:Lt.max,min:.5},plantuml:{...Lt,fitMax:Lt.default}}),zt=Object.freeze({mermaid:{bodyClassName:`mermaid-maximized-open`,buttonClassName:`mermaid-zoom-btn ui-preview-action`,frameClassName:`mermaid-frame diagram-preview-frame`,maximizeButtonClassName:`mermaid-maximize-btn`,maximizedRootClassName:`mermaid-maximized-root`,maximizedRootDatasetKey:`mermaidMaximizedRoot`,toolbarClassName:`mermaid-toolbar diagram-preview-toolbar`,zoomLabelClassName:`mermaid-zoom-label diagram-preview-zoom-label`},plantuml:{bodyClassName:`plantuml-maximized-open`,buttonClassName:`plantuml-tool-btn ui-preview-action`,frameClassName:`plantuml-frame diagram-preview-frame`,maximizeButtonClassName:`plantuml-maximize-btn`,maximizedRootClassName:`plantuml-maximized-root`,maximizedRootDatasetKey:`plantumlMaximizedRoot`,toolbarClassName:`plantuml-toolbar diagram-preview-toolbar`,zoomLabelClassName:`plantuml-zoom-label diagram-preview-zoom-label`}});function Bt(e){return zt[e]??zt.mermaid}function Vt(e){return Rt[e]??Rt.mermaid}function Ht(e){return e instanceof SVGSVGElement}var Ut=class{constructor({documentRef:e=document,toastController:t=null,windowRef:n=window}={}){this.document=e,this.window=n,this.toastController=t,this.activeMaximizedShell=null,this.maximizedRoots=new Map,this.resizeObservers=new Set,this.shellControllers=new WeakMap,this.shellViewStates=new WeakMap,this.shellRefits=new WeakMap}destroy(){this.destroyAllShells(),this.resizeObservers.forEach(e=>e.disconnect()),this.resizeObservers.clear(),this.maximizedRoots.forEach(e=>e.remove()),this.maximizedRoots.clear(),this.activeMaximizedShell=null}destroyAllShells(){this.resizeObservers.forEach(e=>e.disconnect()),this.resizeObservers.clear(),this.activeMaximizedShell=null,this.document.body.classList.remove(`mermaid-maximized-open`,`plantuml-maximized-open`)}destroyShell(e){this.shellControllers.get(e)?.destroy?.(),this.shellControllers.delete(e),this.shellViewStates.delete(e),this.shellRefits.delete(e),this.activeMaximizedShell===e&&(this.restoreShellMount(e),this.activeMaximizedShell=null),this.syncBodyMaximizedClasses()}captureShellViewState(e){let t=this.shellControllers.get(e)?.getViewState?.()??null;return t&&this.shellViewStates.set(e,t),t}getShellViewState(e){return this.shellViewStates.get(e)??this.shellControllers.get(e)?.getViewState?.()??null}cancelActiveShell(e){let t=this.syncActiveShell();if(!t?.classList?.contains(`${e}-shell`))return;let n=this.shellControllers.get(t);this.restoreShellMount(t),t.classList.remove(`is-maximized`),this.activeMaximizedShell=null,n?.syncMaximizeButtonState?.(),n?.scheduleResetZoomToFit?.({force:!0}),this.syncBodyMaximizedClasses()}clearActiveShell(){this.activeMaximizedShell=null,this.maximizedRoots.forEach(e=>{e.childElementCount===0&&(e.hidden=!0)}),this.document.body.classList.remove(`mermaid-maximized-open`,`plantuml-maximized-open`)}syncActiveShell(){return this.activeMaximizedShell?.isConnected&&this.activeMaximizedShell.classList.contains(`is-maximized`)?this.activeMaximizedShell:(this.activeMaximizedShell=null,this.maximizedRoots.forEach(e=>{e.childElementCount===0&&(e.hidden=!0)}),null)}scheduleActiveRefit({kind:e=null,root:t=null}={}){let n=this.syncActiveShell();if(n){this.shellRefits.get(n)?.({force:!0});return}let r=e?`.${e}-shell[data-${e}-hydrated="true"]`:`.mermaid-shell[data-mermaid-hydrated="true"], .plantuml-shell[data-plantuml-hydrated="true"]`;Array.from(t?.querySelectorAll?.(r)??[]).forEach(e=>{this.shellRefits.get(e)?.()})}ensureMaximizedRoot(e){let t=Bt(e),n=this.maximizedRoots.get(e);if(n?.isConnected&&n.parentElement===this.document.body)return n;let r=this.document.body.querySelector(`[data-${e}-maximized-root="true"]`);return r||(r=this.document.createElement(`div`),r.dataset[t.maximizedRootDatasetKey]=`true`,r.className=t.maximizedRootClassName,this.document.body.appendChild(r)),this.maximizedRoots.set(e,r),r}mountShellInMaximizedRoot(e,t){let n=this.ensureMaximizedRoot(t);n.hidden=!1,e._diagramChromeRestoreParent=e.parentElement||null,e._diagramChromeRestoreNextSibling=e.nextSibling||null,n.appendChild(e)}restoreShellMount(e){if(!e)return;let t=e._diagramChromeRestoreParent,n=e._diagramChromeRestoreNextSibling;t?.isConnected&&(n?.parentElement===t?t.insertBefore(e,n):t.appendChild(e)),e._diagramChromeRestoreParent=null,e._diagramChromeRestoreNextSibling=null,this.maximizedRoots.forEach(e=>{e.childElementCount===0&&(e.hidden=!0)})}syncBodyMaximizedClasses(){let e=this.syncActiveShell();for(let[t,n]of Object.entries(zt))this.document.body.classList.toggle(n.bodyClassName,!!e?.classList?.contains(`${t}-shell`))}createButton(e,t,n,{icon:r=``}={}){let i=Bt(e),a=this.document.createElement(`button`);return a.type=`button`,a.className=i.buttonClassName,a.setAttribute(`aria-label`,n),a.title=n,r?V(a,r):a.textContent=t,a}createToolbar({kind:e,includeReload:t=!1}){let n=Bt(e),r=this.document.createElement(`div`);r.className=n.toolbarClassName;let i=this.document.createElement(`div`);i.className=`diagram-preview-toolbar-group`;let a=this.document.createElement(`div`);a.className=`diagram-preview-toolbar-group diagram-preview-toolbar-group--actions`;let o=this.createButton(e,`−`,`Zoom out`),s=this.createButton(e,`+`,`Zoom in`),c=this.createButton(e,``,`Reset zoom`,{icon:`fit`}),l=this.createButton(e,``,`Copy image`,{icon:`copy`}),u=this.createButton(e,``,`Download SVG`,{icon:`download`}),d=t?this.createButton(e,``,`Reload diagram`,{icon:`refresh`}):null,f=this.createButton(e,``,`Maximize diagram`,{icon:`maximize`});f.classList.add(n.maximizeButtonClassName);let p=this.document.createElement(`span`);return p.className=n.zoomLabelClassName,p.setAttribute(`aria-live`,`polite`),i.append(o,p,c,s),a.append(l,u),d&&a.append(d),a.append(f),r.append(i,a),{copyButton:l,decreaseButton:o,downloadButton:u,increaseButton:s,maximizeButton:f,reloadButton:d,resetButton:c,toolbar:r,zoomLabel:p}}attachShellResizeObserver(e,t,n){if(typeof ResizeObserver!=`function`||!e?.isConnected||!(t instanceof HTMLElement))return null;let r=new ResizeObserver(()=>n());return r.observe(t),r.observe(e),this.resizeObservers.add(r),r}async copyExportImage(e,t){try{let{pngFileName:n}=t(),r=await At(await e());try{await jt(r),this.toastController?.show?.(`Diagram copied`)}catch{Ce(r,n),this.toastController?.show?.(`Clipboard image copy is unavailable here. Downloaded PNG instead.`)}}catch{this.toastController?.show?.(`Failed to copy diagram`)}}async downloadExportSvg(e,t){try{let{svgFileName:n}=t(),r=new Blob([await e()],{type:`image/svg+xml;charset=utf-8`});Ce(r,n),this.toastController?.show?.(`Diagram download started`)}catch{this.toastController?.show?.(`Failed to download diagram`)}}syncMaximizeButtonState(e,t){let n=e.classList.contains(`is-maximized`);V(t,n?`restore`:`maximize`);let r=n?`Restore diagram size`:`Maximize diagram`;t.setAttribute(`aria-label`,r),t.title=r}setMaximizedState(e,t,n,r,i){if(i){let i=this.syncActiveShell();if(i&&i!==e){let e=this.shellControllers.get(i);this.restoreShellMount(i),i.classList.remove(`is-maximized`),this.activeMaximizedShell=null,e?.scheduleResetZoomToFit?.({force:!0}),e?.syncMaximizeButtonState?.()}this.mountShellInMaximizedRoot(e,t),e.classList.add(`is-maximized`),this.activeMaximizedShell=e,this.syncMaximizeButtonState(e,n),this.syncBodyMaximizedClasses(),r({force:!0});return}this.restoreShellMount(e),e.classList.remove(`is-maximized`),this.activeMaximizedShell===e&&(this.activeMaximizedShell=null),this.syncMaximizeButtonState(e,n),this.syncBodyMaximizedClasses(),r({force:!0})}mount(e,{baseHeight:t,baseWidth:n,diagramElement:r,exportFileNames:i,exportSvgMarkup:a,kind:o,onReload:s=null,sourceSelector:c}={}){if(!e?.isConnected||!Ht(r))return null;let l=Bt(o),u=Vt(o),d=e.querySelector(l.frameClassName.split(` `).map(e=>`.${e}`).join(``)),f=d?st(d).width:0,p=this.getShellViewState(e);this.destroyShell(e);let{copyButton:m,decreaseButton:h,downloadButton:g,increaseButton:_,maximizeButton:v,reloadButton:ee,resetButton:te,toolbar:ne,zoomLabel:y}=this.createToolbar({includeReload:typeof s==`function`,kind:o}),x=this.document.createElement(`div`);x.className=l.frameClassName;let S=!!(p&&(p.scrollLeft>0||p.scrollTop>0)),C=!!(S&&d?.isConnected&&d.clientWidth>0&&d.clientHeight>0),w=!!(C&&!e.classList.contains(`is-maximized`)&&!e.style.position);w&&(e.style.position=`relative`),S&&!C&&(x.style.visibility=`hidden`),C&&Object.assign(x.style,{height:`${d.clientHeight}px`,left:`0`,pointerEvents:`none`,position:`absolute`,top:`0`,visibility:`hidden`,width:`${d.clientWidth}px`});let T=u.default,E=null,D=null,O=null,k=null,A=null,j=!!(p?.hasManualZoom||p?.scrollLeft>0||p?.scrollTop>0),M=f>0&&Number.isFinite(n)&&n>0,N=Number.isFinite(p?.zoom),re=M?f:0,ie=!1;r.style.maxWidth=`none`;let ae=()=>{let e=st(x);if(!Number.isFinite(n)||n<=0||e.width<=0)return u.default;let t=e.width/n;return!Number.isFinite(t)||t<=0?u.default:b(t,u.min,u.fitMax)},P=e=>{T=b(e,u.min,u.max),r.style.width=`${n*T}px`,r.style.height=`${t*T}px`,y.textContent=`${Math.round(T*100)}%`,h.disabled=T<=u.min,_.disabled=T>=u.max},oe=N?b(p.zoom,u.min,u.max):M?b(f/n,u.min,u.fitMax):u.default,se=()=>({x:x.scrollLeft+x.clientWidth/2,y:x.scrollTop+x.clientHeight/2}),ce=(e,t,n,r)=>{if(e===0)return;let i=t/e;x.scrollLeft=n.x*i-r.x,x.scrollTop=n.y*i-r.y},le=(e,t,n)=>{ce(e,t,n,{x:x.clientWidth/2,y:x.clientHeight/2})},ue=e=>{let t=b(e,u.min,u.max);if(E){D=t;return}let n=T;if(t===n)return;D=t;let r=se(),i=performance.now(),a=e=>{let t=b((e-i)/u.animationDurationMs,0,1),o=rt(t),s=n+(D-n)*o;if(P(s),le(n,s,r),t<1){E=this.window.requestAnimationFrame(a);return}E=null;let c=D;D=null,P(c),le(n,c,r)};E=this.window.requestAnimationFrame(a)},F=()=>{E&&=(this.window.cancelAnimationFrame(E),null),D=null},de=e=>{j=!0,ue((D??T)+e)},fe=()=>{let e=ae();j=!1,re=st(x).width,A=null,F(),P(e),x.scrollLeft=0,x.scrollTop=0},I=({force:t=!1}={})=>{ie||=t,O&&this.window.cancelAnimationFrame(O),O=this.window.requestAnimationFrame(()=>{if(O=null,!e.isConnected)return;let t=ie;ie=!1;let n=st(x).width,r=Math.abs(n-re)>1;!t&&j||!t&&n>0&&re>0&&!r||fe()})},pe=this.attachShellResizeObserver(e,x,()=>I()),me=(e,t)=>{let n=x.getBoundingClientRect();return{x:Number(e)-n.left,y:Number(t)-n.top}},he=e=>{if(!e||e.length!==2)return null;let t=e[0],n=e[1],r=me((t.clientX+n.clientX)/2,(t.clientY+n.clientY)/2),i=Math.hypot(n.clientX-t.clientX,n.clientY-t.clientY);return!Number.isFinite(i)||i<=0?null:{center:r,distance:i}},ge=e=>{let t=he(e);return t?(F(),A={contentPoint:{x:x.scrollLeft+t.center.x,y:x.scrollTop+t.center.y},distance:t.distance,zoom:T},!0):!1},_e=e=>{let t=he(e);return!t||!A&&!ge(e)?!1:(j=!0,P(A.zoom*(t.distance/A.distance)),ce(A.zoom,T,A.contentPoint,t.center),!0)};h.addEventListener(`click`,()=>de(-u.step)),_.addEventListener(`click`,()=>de(u.step)),x.addEventListener(`wheel`,e=>{if(!e.ctrlKey)return;e.preventDefault();let t=Number.isFinite(e.deltaY)?e.deltaY:0,n=b(-t*u.wheelSensitivity,-u.step/2,u.step/2);n!==0&&de(n)},{passive:!1}),x.addEventListener(`touchstart`,e=>{e.touches.length===2&&ge(e.touches)},{passive:!0}),x.addEventListener(`touchmove`,e=>{e.touches.length===2&&_e(e.touches)&&e.preventDefault()},{passive:!1});let ve=e=>{e.touches.length!==2&&(A=null)};x.addEventListener(`touchend`,ve),x.addEventListener(`touchcancel`,ve),te.addEventListener(`click`,()=>{I({force:!0})}),m.addEventListener(`click`,()=>this.copyExportImage(a,i)),g.addEventListener(`click`,()=>this.downloadExportSvg(a,i)),ee?.addEventListener(`click`,()=>s()),v.addEventListener(`click`,()=>{this.setMaximizedState(e,o,v,I,!e.classList.contains(`is-maximized`))}),x.appendChild(r);let L=c?e.querySelector(c):null,ye=L?[L,ne,x]:[ne,x];L&&(L.hidden=!0),C?e.append(x):e.replaceChildren(...ye),P(oe);let be=()=>{let e=Math.max(0,x.scrollWidth-x.clientWidth),t=Math.max(0,x.scrollHeight-x.clientHeight),n=b(p.scrollLeft??0,0,e),r=b(p.scrollTop??0,0,t);return x.scrollLeft=n,x.scrollTop=r,x.clientWidth>0&&x.clientHeight>0&&x.scrollLeft===n&&x.scrollTop===r};C?(be(),k=this.window.requestAnimationFrame(()=>{k=null,e.replaceChildren(...ye),x.removeAttribute(`style`),w&&(e.style.position=``),P(oe),be()})):S&&(be()?x.style.visibility=``:this.window.requestAnimationFrame(()=>{x.isConnected&&(be(),x.style.visibility=``)}));let xe={destroy:()=>{E&&this.window.cancelAnimationFrame(E),O&&this.window.cancelAnimationFrame(O),k&&this.window.cancelAnimationFrame(k),pe?.disconnect?.(),this.resizeObservers.delete(pe)},getViewState:()=>({hasManualZoom:j,scrollLeft:x.scrollLeft,scrollTop:x.scrollTop,zoom:T}),scheduleResetZoomToFit:I,syncMaximizeButtonState:()=>this.syncMaximizeButtonState(e,v)};return this.shellControllers.set(e,xe),this.shellRefits.set(e,I),this.syncMaximizeButtonState(e,v),!M&&!N&&I({force:!0}),xe}};function Wt(){return new Worker(new URL(``+new URL(`preview-render-worker-BmN79bVc.js`,import.meta.url).href,``+import.meta.url),{type:`module`})}var Gt=class{constructor({attachmentApiPath:t=`/api/attachment`,cancelIdleRenderFn:n=z,compilePreviewDocumentLoader:r=()=>e(()=>import(`./preview-render-compiler-BQ_3h9vD.js`),__vite__mapDeps([26,27,28,2,29,30,31]),import.meta.url),createWorkerFn:i=Wt,getFileList:a,getSourceFilePath:o=null,getWikiLinkAutoCreate:s=null,idleTimeoutMs:c=500,requestIdleRenderFn:l=R}={}){this.attachmentApiPath=t,this.cancelIdleRenderFn=n,this.compilePreviewDocumentLoader=r,this.createWorkerFn=i,this.getFileList=a,this.getSourceFilePath=o,this.getWikiLinkAutoCreate=s,this.idleTimeoutMs=c,this.requestIdleRenderFn=l,this.worker=null,this.workerDisabled=!1,this.workerJob=null,this.workerPrewarmId=null,this.handleWorkerMessage=e=>{if(!this.workerJob||e.data?.renderVersion!==this.workerJob.renderVersion)return;let t=this.workerJob;if(this.workerJob=null,e.data?.error){t.reject(Error(e.data.error));return}t.resolve({html:e.data.html,stats:e.data.stats})},this.handleWorkerError=e=>{let t=Error(e.message||`Preview worker failed`);this.workerJob&&=(this.workerJob.reject(t),null),this.reset(`Preview worker failed`,{disable:!0})}}hasPendingJob(){return this.workerJob!==null}schedulePrewarm({timeout:e=this.idleTimeoutMs}={}){this.workerDisabled||this.worker||this.workerPrewarmId!==null||(this.workerPrewarmId=this.requestIdleRenderFn(()=>{this.workerPrewarmId=null,this.ensureWorker()},e))}ensureWorker(){if(this.workerDisabled)return null;if(this.worker)return this.worker;try{return this.worker=this.createWorkerFn(),this.worker.addEventListener(`message`,this.handleWorkerMessage),this.worker.addEventListener(`error`,this.handleWorkerError),this.worker}catch{return this.workerDisabled=!0,null}}async compile(e,t,{frontmatterCollapsed:n=!1,frontmatterInteractive:r=!1}={}){if(this.ensureWorker()){this.workerJob&&this.reset(`Superseded preview render`);let i=this.ensureWorker();return new Promise((a,o)=>{this.workerJob={reject:o,renderVersion:t,resolve:a},i.postMessage({attachmentApiPath:this.attachmentApiPath,fileList:this.getFileList?.()??[],frontmatterCollapsed:n,frontmatterInteractive:r,markdownText:e,renderVersion:t,sourceFilePath:this.getSourceFilePath?.()??``,wikiLinkAutoCreate:this.getWikiLinkAutoCreate?.()??!0})})}let{compilePreviewDocument:i}=await this.compilePreviewDocumentLoader();return i({attachmentApiPath:this.attachmentApiPath,fileList:this.getFileList?.()??[],frontmatterCollapsed:n,frontmatterInteractive:r,markdownText:e,sourceFilePath:this.getSourceFilePath?.()??``,wikiLinkAutoCreate:this.getWikiLinkAutoCreate?.()??!0})}cancelWorkerJob(e){this.workerJob&&=(this.workerJob.reject(Error(e)),null)}reset(e,{disable:t=!1}={}){this.cancelWorkerJob(e),this.worker&&=(this.worker.removeEventListener(`message`,this.handleWorkerMessage),this.worker.removeEventListener(`error`,this.handleWorkerError),this.worker.terminate(),null),t&&(this.workerDisabled=!0)}destroy(e=`Preview renderer destroyed`){this.workerPrewarmId!==null&&this.cancelIdleRenderFn(this.workerPrewarmId),this.workerPrewarmId=null,this.reset(e)}},Kt=class{constructor({cancelAnimationFrameFn:e=e=>cancelAnimationFrame(e),cancelIdleRenderFn:t=z,clearTimeoutFn:n=e=>clearTimeout(e),getRenderProfileFn:r=te,idleTimeoutMs:i=500,requestAnimationFrameFn:a=e=>requestAnimationFrame(e),requestIdleRenderFn:o=R,setTimeoutFn:s=(e,t)=>setTimeout(e,t)}={}){this.cancelAnimationFrameFn=e,this.cancelIdleRenderFn=t,this.clearTimeoutFn=n,this.getRenderProfileFn=r,this.idleTimeoutMs=i,this.requestAnimationFrameFn=a,this.requestIdleRenderFn=o,this.setTimeoutFn=s,this.frameId=null,this.idleId=null,this.timeoutId=null}queue({markdownText:e,onRenderRequested:t,renderVersion:n}){let r=this.getRenderProfileFn(e);this.cancel();let i=()=>{this.frameId=this.requestAnimationFrameFn(()=>{this.frameId=null,this.timeoutId=null,t?.(e,n)})},a=()=>{if(r.deferUntilIdle){this.idleId=this.requestIdleRenderFn(()=>{this.idleId=null,i()},this.idleTimeoutMs);return}i()};this.timeoutId=this.setTimeoutFn(a,r.debounceMs)}cancel(){this.clearTimeoutFn(this.timeoutId),this.frameId&&this.cancelAnimationFrameFn(this.frameId),this.cancelIdleRenderFn(this.idleId),this.frameId=null,this.idleId=null,this.timeoutId=null}destroy(){this.cancel()}},qt=class{constructor({getContent:e,getFileList:t,getSourceFilePath:n,getWikiLinkAutoCreate:r=null,loadFileSource:i=null,onAfterRenderCommit:a,onBeforeRenderCommit:o,onPreviewLayoutChange:s,onRenderComplete:c,outlineController:l,plantUmlRenderClient:u=null,previewContainer:d,previewElement:f,toastController:p=null}){this.getContent=e,this.getFileList=t,this.getSourceFilePath=n,this.getWikiLinkAutoCreate=r,this.loadFileSource=i,this.onAfterRenderCommit=a,this.onBeforeRenderCommit=o,this.onPreviewLayoutChange=s,this.onRenderComplete=c,this.outlineController=l,this.plantUmlRenderClient=u,this.previewContainer=d,this.previewElement=f,this.toastController=p,this.renderHost=null,this.pendingRenderVersion=0,this.activeRenderVersion=0,this.readyRenderVersion=0,this.currentStats=null,this.isLargeDocument=!1,this.hydrationPaused=!1,this.frontmatterCollapsed=!1,this.handlePreviewClick=e=>{if(e.target.closest(`.frontmatter-toggle`)){e.preventDefault(),this.frontmatterCollapsed=!this.frontmatterCollapsed,this.applyFrontmatterState(),this.handleFrontmatterLayoutChange();return}let t=e.target.closest(`.mermaid-placeholder-btn`);if(t){let n=t.closest(`.mermaid-shell`);if(!n)return;e.preventDefault(),t.closest(`.diagram-preview-error-card`)?this.mermaidHydrator.retryShell(n):this.mermaidHydrator.enqueueShell(n,{prioritize:!0});return}let n=e.target.closest(`.plantuml-placeholder-btn`);if(n){let t=n.closest(`.plantuml-shell`);if(!t)return;e.preventDefault(),n.closest(`.diagram-preview-error-card`)?this.plantUmlHydrator.retryShell(t):this.plantUmlHydrator.enqueueShell(t,{prioritize:!0})}},this.handleWindowResize=()=>{this.scheduleActiveMermaidRefit(),this.scheduleActivePlantUmlRefit()},this.diagramChrome=new Ut({toastController:p}),this.mermaidHydrator=new Pt(this,{loadFileSource:i}),this.plantUmlHydrator=new Ft(this,{loadFileSource:i,renderClient:u}),this.renderScheduler=new Kt({getRenderProfileFn:te}),this.renderExecutor=new Gt({attachmentApiPath:F(`/attachment`),getFileList:()=>this.getFileList?.()??[],getSourceFilePath:()=>this.getSourceFilePath?.()??``,getWikiLinkAutoCreate:()=>this.getWikiLinkAutoCreate?.()??!0,idleTimeoutMs:500}),this.previewElement?.addEventListener(`click`,this.handlePreviewClick),window.addEventListener(`resize`,this.handleWindowResize),this.setPhase(`ready`)}ensureRenderHost(){if(!this.previewElement)return null;if(this.renderHost?.isConnected&&this.renderHost.parentElement===this.previewElement)return this.renderHost;let e=this.previewElement.querySelector(`[data-preview-render-host="true"]`);return e||(e=document.createElement(`div`),e.dataset.previewRenderHost=`true`,this.previewElement.appendChild(e)),this.renderHost=e,this.renderHost}normalizePreviewChildren(e=this.renderHost){this.previewElement&&Array.from(this.previewElement.children).forEach(t=>{t!==e&&t.dataset.drawioOverlayRoot!==`true`&&t.dataset.excalidrawOverlayRoot!==`true`&&t.dataset.videoOverlayRoot!==`true`&&t.remove()})}getReservedPreviewHeight(){let e=this.renderHost?.getBoundingClientRect?.().height??0,t=this.previewContainer?.clientHeight??0;return Math.max(Math.round(e),Math.round(t),320)}beginDocumentLoad(){this.renderScheduler.cancel(),this.mermaidHydrator.cancelHydration(),this.plantUmlHydrator.cancelHydration(),this.mermaidHydrator.clearPreservedShells(),this.plantUmlHydrator.clearPreservedShells(),this.diagramChrome.clearActiveShell(),this.onBeforeRenderCommit?.(this.previewElement),this.pendingRenderVersion+=1,this.activeRenderVersion=this.pendingRenderVersion,this.readyRenderVersion=0,this.currentStats=null,this.isLargeDocument=!1,this.frontmatterCollapsed=!1,this.renderExecutor.hasPendingJob()&&this.renderExecutor.reset(`Document changed`);let e=this.ensureRenderHost();this.normalizePreviewChildren(e);let t=this.getReservedPreviewHeight();e&&(e.replaceChildren(),e.style.minHeight=`${t}px`);let n=document.createElement(`div`);n.className=`preview-shell`,n.style.minHeight=`${t}px`,n.textContent=`Rendering preview…`,e?.append(n),this.setPhase(`shell`)}applyTheme(e){let t=document.getElementById(`hljs-theme`);if(t){let{darkHref:n,lightHref:r}=t.dataset;t.href=e===`dark`?n:r}this.mermaidHydrator.applyTheme(e)}queueRender(){let e=this.getContent();this.renderScheduler.cancel(),this.mermaidHydrator.markPending(),this.plantUmlHydrator.markPending(),this.pendingRenderVersion+=1;let t=this.pendingRenderVersion;this.renderScheduler.queue({markdownText:e,onRenderRequested:(e,t)=>{this.render(e,t)},renderVersion:t})}async render(e=this.getContent(),t=this.pendingRenderVersion){if(this.previewElement)try{let n=await this.renderExecutor.compile(e,t,{frontmatterCollapsed:this.frontmatterCollapsed,frontmatterInteractive:!0});if(t!==this.pendingRenderVersion)return;this.commitBaseRender(n,t)}catch(e){if(t!==this.pendingRenderVersion)return;console.warn(`[preview] Failed to render preview:`,e)}}destroy(){this.renderScheduler.destroy(),this.diagramChrome.destroy(),this.mermaidHydrator.destroy(),this.plantUmlHydrator.destroy(),this.renderExecutor.destroy(),this.previewElement?.removeEventListener(`click`,this.handlePreviewClick),window.removeEventListener(`resize`,this.handleWindowResize)}setPhase(e){this.previewElement&&(this.previewElement.dataset.renderPhase=e)}scheduleActiveMermaidRefit(){this.diagramChrome.scheduleActiveRefit({kind:`mermaid`,root:this.previewElement})}scheduleActivePlantUmlRefit(){this.diagramChrome.scheduleActiveRefit({kind:`plantuml`,root:this.previewElement})}setHydrationPaused(e){if(this.hydrationPaused=!!e,this.hydrationPaused){this.mermaidHydrator.cancelPendingIdleWork(),this.plantUmlHydrator.cancelPendingIdleWork();return}this.mermaidHydrator.hydrateVisibleShells(),this.mermaidHydrator.scheduleHydration(),this.plantUmlHydrator.hydrateVisibleShells(),this.plantUmlHydrator.scheduleHydration(),this.updateHydrationPhase()}scheduleWorkerPrewarm({timeout:e=500}={}){this.renderExecutor.schedulePrewarm({timeout:e})}commitBaseRender({html:e,stats:t},n){this.activeRenderVersion=n,this.readyRenderVersion=0,this.currentStats=t,this.isLargeDocument=ne(t),this.mermaidHydrator.cancelHydration({preserveActiveShell:!0}),this.plantUmlHydrator.cancelHydration({preserveActiveShell:!0}),document.body.classList.remove(`mermaid-maximized-open`),document.body.classList.remove(`plantuml-maximized-open`),this.mermaidHydrator.preserveHydratedShellsForCommit(),this.plantUmlHydrator.preserveHydratedShellsForCommit(),this.onBeforeRenderCommit?.(this.previewElement);let r=this.ensureRenderHost();this.normalizePreviewChildren(r),r&&(r.innerHTML=e),this.applyFrontmatterState(),this.mermaidHydrator.reconcileHydratedShells(),this.plantUmlHydrator.reconcileHydratedShells(),this.setPhase(`base`),this.outlineController.refresh(),this.onAfterRenderCommit?.(this.previewElement,{...t,isLargeDocument:this.isLargeDocument,renderVersion:n});let i=this.mermaidHydrator.setupHydration(n),a=this.plantUmlHydrator.setupHydration(n);i===0&&a===0&&this.notifyReady()}applyFrontmatterState(){let e=this.renderHost?.querySelector?.(`.frontmatter-block`);if(!(e instanceof HTMLElement))return;let t=this.frontmatterCollapsed,n=e.querySelector(`.frontmatter-toggle`),r=e.querySelector(`.frontmatter-summary`),i=e.querySelector(`.frontmatter-content`);e.dataset.collapsed=t?`true`:`false`,n instanceof HTMLButtonElement&&(n.setAttribute(`aria-expanded`,t?`false`:`true`),n.textContent=t?`Show`:`Hide`),r instanceof HTMLElement&&(r.hidden=!t),i instanceof HTMLElement&&(i.hidden=t)}handleFrontmatterLayoutChange(){this.outlineController.refresh(),this.onPreviewLayoutChange?.({isLargeDocument:this.isLargeDocument,renderVersion:this.activeRenderVersion,stats:this.currentStats})}updateHydrationPhase(){if(this.hydrationPaused&&(this.mermaidHydrator.hasPendingWork()||this.plantUmlHydrator.hasPendingWork())){this.setPhase(`base`);return}if(this.mermaidHydrator.hasPendingWork()||this.plantUmlHydrator.hasPendingWork()){this.setPhase(`hydrating`);return}this.notifyReady()}notifyReady(){this.renderHost&&(this.renderHost.style.minHeight=``),this.setPhase(`ready`),this.readyRenderVersion!==this.activeRenderVersion&&(this.readyRenderVersion=this.activeRenderVersion,this.onRenderComplete?.({isLargeDocument:this.isLargeDocument,stats:this.currentStats}))}};async function Jt(e){if(e.quickSwitcher)return e.quickSwitcher;e.quickSwitcherModulePromise||=e.loadQuickSwitcherController();let t;try{t=await e.quickSwitcherModulePromise}catch(t){throw e.quickSwitcherModulePromise=null,console.error(`[quick-switcher] Failed to load file search.`,t),e.toastController?.show?.(`Failed to load file search. Try again.`,{dismissible:!0}),t}return e.quickSwitcher||=new t({getFileList:()=>e.fileExplorer.flatFiles,getFileMetadata:()=>e.fileExplorer.fileEntries,getRecentFiles:()=>e.preferences?.getRecentFiles?.()??[],getSearchConfig:()=>e.runtimeConfig.search??{},onFileSelect:t=>e.workspaceRouteController.handleFileSelection(t,{closeSidebarOnMobile:!0,revealInTree:!e.isMobileViewport()}),onTextMatchSelect:t=>{t?.file&&e.navigation.navigateToFile(t.file,{column:t.column,drawioMode:t.kind===`drawio`?`text`:null,line:t.line,matchLength:t.matchLength})},searchText:t=>e.vaultApiClient.searchText(t)}),e.quickSwitcher}async function Yt(e){try{(await Jt(e)).toggle()}catch{}}var Xt=class{constructor({backlinksPanel:e,clearInitialFileBootstrap:t,clearStaticPreviewDocument:n=null,closeSidebarOnMobile:r,drawioEmbed:i,elements:a,excalidrawEmbed:o,fileHistoryView:s=null,fileExplorer:c,getIsTabActive:l,getSessionLoadToken:u,gitDiffView:d,gitPanel:f,imageLightbox:p=null,lobby:m,navigation:h,previewRenderer:g,renderAvatars:_,renderPresence:v,requestPreviewRouteAnchor:ee=null,resetPreviewMode:te,scrollSyncController:ne,setSession:y,setSessionLoadToken:b,setSidebarTab:x,setSidebarVisibility:S,setCurrentFilePath:C,showGitCommit:w,showGitDiff:T,showGitFileHistory:E,showGitFilePreview:D,showGitHistory:O,syncMainChrome:k,videoEmbed:A,workspaceCoordinator:j,layoutController:M}){this.backlinksPanel=e,this.clearInitialFileBootstrap=t,this.clearStaticPreviewDocument=n,this.closeSidebarOnMobile=r,this.drawioEmbed=i??{setHydrationPaused(){}},this.elements=a,this.excalidrawEmbed=o,this.fileHistoryView=s,this.fileExplorer=c,this.getIsTabActive=l,this.getSessionLoadToken=u,this.gitDiffView=d,this.gitPanel=f,this.imageLightbox=p,this.lobby=m,this.navigation=h,this.previewRenderer=g,this.renderAvatars=_,this.renderPresence=v,this.requestPreviewRouteAnchor=ee,this.resetPreviewMode=te,this.scrollSyncController=ne,this.setSession=y,this.setSessionLoadToken=b,this.setSidebarTab=x,this.setSidebarVisibility=S??(()=>{}),this.setCurrentFilePath=C,this.showGitCommit=w,this.showGitDiff=T,this.showGitFileHistory=E,this.showGitFilePreview=D,this.showGitHistory=O,this.syncMainChrome=k,this.videoEmbed=A,this.workspaceCoordinator=j,this.layoutController=M,this.pendingTreeRevealPath=null,this.preserveSidebarTabRoutePath=null}async handleHashChange(){if(!this.getIsTabActive())return;let e=this.navigation.getHashRoute(),t=e.type===`file`?e.filePath:null;if(await this.prepareActiveExcalidrawDisconnect(t)){if(e.type===`empty`){this.requestPreviewRouteAnchor?.(null),this.gitPanel.setSelection(),this.showEmptyState(),this.syncMainChrome({mode:`empty`,title:`CollabMD`});return}if(e.type===`git-diff`){this.requestPreviewRouteAnchor?.(null),this.setSidebarTab(`git`),await this.showGitDiff(e);return}if(e.type===`git-file-history`){this.requestPreviewRouteAnchor?.(null),this.setSidebarTab(`files`),await this.showGitFileHistory(e);return}if(e.type===`git-file-preview`){this.requestPreviewRouteAnchor?.(null),this.setSidebarTab(`files`),await this.showGitFilePreview(e);return}if(e.type===`git-history`){this.requestPreviewRouteAnchor?.(null),this.setSidebarTab(`git`),await this.showGitHistory();return}if(e.type===`git-commit`){this.requestPreviewRouteAnchor?.(null),this.setSidebarTab(`git`),await this.showGitCommit(e);return}this.preserveSidebarTabRoutePath===e.filePath?this.preserveSidebarTabRoutePath=null:(this.preserveSidebarTabRoutePath=null,this.setSidebarTab(`files`)),await this.openFile(e.filePath,{drawioMode:e.drawioMode||null})&&(this.revealEditorMatch(e),this.requestPreviewRouteAnchor?.(e.anchor??null,e.filePath))}}showEmptyState(){this.gitDiffView.hide(),this.fileHistoryView?.hide?.(),this.workspaceCoordinator.cleanupSession(),this.clearStaticPreviewDocument?.(),this.setSession(null),this.setSessionLoadToken(this.getSessionLoadToken()+1),this.clearInitialFileBootstrap(),this.resetPreviewMode(),this.elements.outlineToggle?.classList.remove(`hidden`),this.elements.markdownToolbar?.classList.add(`hidden`),this.setCurrentFilePath(null),this.lobby.setCurrentFile(null),this.fileExplorer.setActiveFile(null),this.elements.emptyState?.classList.remove(`hidden`),this.elements.editorPage?.classList.add(`hidden`),this.elements.diffPage?.classList.add(`hidden`),this.elements.previewContent&&(this.elements.previewContent.innerHTML=``,this.elements.previewContent.dataset.renderPhase=`ready`),this.videoEmbed?.reconcileEmbeds(this.elements.previewContent),this.resetPreviewSurface(),this.renderAvatars(),this.renderPresence(),this.backlinksPanel.clear(),this.elements.activeFileName&&(this.elements.activeFileName.textContent=`CollabMD`)}showDiffState(){this.fileHistoryView?.hide?.(),this.setSessionLoadToken(this.getSessionLoadToken()+1),this.clearInitialFileBootstrap(),this.clearStaticPreviewDocument?.(),this.workspaceCoordinator.cleanupSession(),this.setSession(null),this.resetPreviewMode(),this.layoutController.reset(),this.setCurrentFilePath(null),this.lobby.setCurrentFile(null),this.fileExplorer.setActiveFile(null),this.elements.emptyState?.classList.add(`hidden`),this.elements.editorPage?.classList.add(`hidden`),this.elements.diffPage?.classList.remove(`hidden`),this.elements.previewContent&&(this.elements.previewContent.innerHTML=``,this.elements.previewContent.dataset.renderPhase=`ready`),this.videoEmbed?.reconcileEmbeds(this.elements.previewContent),this.resetPreviewSurface(),this.elements.outlineToggle?.classList.add(`hidden`),this.elements.markdownToolbar?.classList.add(`hidden`),this.renderAvatars(),this.renderPresence(),this.backlinksPanel.clear()}showFileHistoryState(e){this.gitDiffView.hide(),this.setSessionLoadToken(this.getSessionLoadToken()+1),this.clearInitialFileBootstrap(),this.clearStaticPreviewDocument?.(),this.workspaceCoordinator.cleanupSession(),this.setSession(null),this.resetPreviewMode(),this.layoutController.reset(),this.setCurrentFilePath(e),this.lobby.setCurrentFile(null),this.fileExplorer.setActiveFile(e),this.elements.emptyState?.classList.add(`hidden`),this.elements.editorPage?.classList.add(`hidden`),this.elements.diffPage?.classList.remove(`hidden`),this.elements.previewContent&&(this.elements.previewContent.innerHTML=``,this.elements.previewContent.dataset.renderPhase=`ready`),this.videoEmbed?.reconcileEmbeds(this.elements.previewContent),this.resetPreviewSurface(),this.elements.outlineToggle?.classList.add(`hidden`),this.elements.markdownToolbar?.classList.add(`hidden`),this.renderAvatars(),this.renderPresence(),this.backlinksPanel.clear()}showPreviewOnlyState(e){this.gitDiffView.hide(),this.fileHistoryView?.hide?.(),this.setSessionLoadToken(this.getSessionLoadToken()+1),this.clearInitialFileBootstrap(),this.clearStaticPreviewDocument?.(),this.workspaceCoordinator.cleanupSession(),this.setSession(null),this.resetPreviewMode(),this.layoutController.reset(),this.setCurrentFilePath(e),this.lobby.setCurrentFile(null),this.fileExplorer.setActiveFile(e),this.elements.emptyState?.classList.add(`hidden`),this.elements.editorPage?.classList.remove(`hidden`),this.elements.diffPage?.classList.add(`hidden`),this.elements.previewContent&&(this.elements.previewContent.innerHTML=``,this.elements.previewContent.dataset.renderPhase=`ready`),this.videoEmbed?.reconcileEmbeds(this.elements.previewContent),this.resetPreviewSurface(),this.elements.markdownToolbar?.classList.add(`hidden`),this.renderAvatars(),this.renderPresence(),this.backlinksPanel.clear()}async openFile(e,t={}){let n=this.pendingTreeRevealPath===e;return n&&(this.pendingTreeRevealPath=null),this.imageLightbox?.close?.(),this.gitPanel.setSelection(),this.gitDiffView.hide(),this.fileHistoryView?.hide?.(),this.clearStaticPreviewDocument?.(),this.syncMainChrome({mode:`editor`}),await this.workspaceCoordinator.openFile(e,t),this.setSession(this.workspaceCoordinator.getSession()),n&&this.revealFileInTree(e,{clearSearch:!0}),!0}async prepareActiveExcalidrawDisconnect(e=null){let t=this.workspaceCoordinator.stateStore?.get?.(`currentFilePath`)||null;return t&&t!==e&&this.workspaceCoordinator.isExcalidrawFile?.(t)&&!await this.excalidrawEmbed.prepareFileDisconnect(t,{timeoutMs:1e4})?(this.navigation.navigateToFile(t),!1):!0}preserveSidebarTabForNextFileRoute(e){this.preserveSidebarTabRoutePath=e||null}cleanupSession(){this.workspaceCoordinator.cleanupSession(),this.setSession(this.workspaceCoordinator.getSession())}handleFileSelection(e,{closeSidebarOnMobile:t=!1,revealInTree:n=!1}={}){let r=this.navigation.getHashRoute?.()??null,i=r?.type===`file`&&r.filePath===e&&!r.drawioMode;if(n&&(this.pendingTreeRevealPath=e,i)){this.pendingTreeRevealPath=null,this.revealFileInTree(e,{clearSearch:!0});return}t&&!n&&this.closeSidebarOnMobile(),this.navigation.navigateToFile(e)}revealFileInTree(e,{clearSearch:t=!1}={}){this.setSidebarTab(`files`),this.setSidebarVisibility(!0),this.fileExplorer.revealFile?.(e,{clearSearch:t})}revealEditorMatch(e={}){if(!Number.isFinite(e.line))return!1;let t=this.workspaceCoordinator.getSession?.();return t?.revealSearchMatch?.({column:e.column,length:e.matchLength,line:e.line})??t?.scrollToLine?.(e.line,.2)??!1}resetPreviewSurface(){this.imageLightbox?.close?.(),this.previewRenderer.setHydrationPaused(!1),this.drawioEmbed.setHydrationPaused(!1),this.excalidrawEmbed.setHydrationPaused(!1),this.videoEmbed?.detachForCommit(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks()}},Zt=class{constructor({getFileList:e,navigation:t,refreshExplorer:n,toastController:r,vaultApiClient:i,wikiLinkAutoCreate:a=!0}){this.getFileList=e,this.navigation=t,this.refreshExplorer=n,this.toastController=r,this.vaultApiClient=i,this.wikiLinkAutoCreate=a}handleWikiLinkClick(e){let t=ee(e,this.getFileList());if(t){this.navigation.navigateToFile(t);return}if(!this.wikiLinkAutoCreate){this.toastController.show(`Wiki-link target does not exist`);return}let n=this.normalizeNewWikiFilePath(e);if(!n){this.toastController.show(`Cannot create an empty wiki-link target`);return}this.createAndOpenFile(n,e)}normalizeNewWikiFilePath(e){let t=k(e);return t?t.endsWith(`.md`)?t:`${t}.md`:null}async createAndOpenFile(e,t){try{await this.vaultApiClient.createFile({content:re(t||e),path:e}),await this.refreshExplorer(),this.navigation.navigateToFile(e)}catch(e){this.toastController.show(`Failed to create file: ${e.message}`)}}},Qt=class{constructor({backlinksPanel:e,basesPreview:t=null,drawioEmbed:r,elements:i,excalidrawEmbed:a,getDisplayName:o,getSession:s,isDrawioFile:c,isExcalidrawFile:l,isBaseFile:u,isImageFile:d,isPdfFile:f,isMermaidFile:p,isPlantUmlFile:m,layoutController:h,outlineController:g,previewRenderer:_,pdfPreview:v=null,schedulePreviewLayoutSync:ee,scrollSyncController:te,structurizrPreview:ne=null,videoEmbed:y}){this.backlinksPanel=e,this.basesPreview=t??{reconcileEmbeds(){},renderStandalone(){}},this.drawioEmbed=r??{detachForCommit(){},hydrateVisibleEmbeds(){},reconcileEmbeds(){},setHydrationPaused(){},syncLayout(){},updateLocalUser(){},updateTheme(){}},this.elements=i,this.excalidrawEmbed=a,this.getDisplayName=o,this.getSession=s,this.isDrawioFile=c??(()=>!1),this.isExcalidrawFile=l??(()=>!1),this.isBaseFile=u??n,this.isImageFile=d??(()=>!1),this.isPdfFile=f??(()=>!1),this.isMermaidFile=p??(()=>!1),this.isPlantUmlFile=m??(()=>!1),this.layoutController=h,this.outlineController=g,this.previewRenderer=_,this.pdfPreview=v??{cancel(){},render(){}},this.schedulePreviewLayoutSyncCallback=ee,this.scrollSyncController=te,this.structurizrPreview=ne??{queueSync(){},render:async()=>!1,reset(){}},this.videoEmbed=y}createDiagramPreviewDocument(e,t=``){let n=String(t??``),r=Math.max(...n.match(/`+/g)?.map(e=>e.length)??[0]),i="`".repeat(Math.max(3,r+1));return`${i}${e}\n${n}\n${i}`}getPreviewSource(e,{drawioMode:t=null}={}){let n=this.getSession()?.getText()??``;return this.isMermaidFile(e)?this.createDiagramPreviewDocument(`mermaid`,n):this.isPlantUmlFile(e)?this.createDiagramPreviewDocument(`plantuml`,n):this.isDrawioFile(e)&&t===`text`?this.createDiagramPreviewDocument(`xml`,n):n}resetPreviewMode(){this.pdfPreview.cancel(),this.elements.previewContent?.classList.remove(`is-drawio-file-preview`),this.elements.previewContent?.classList.remove(`is-excalidraw-file-preview`),this.elements.previewContent?.classList.remove(`is-base-file-preview`),this.elements.previewContent?.classList.remove(`is-image-file-preview`),this.elements.previewContent?.classList.remove(`is-pdf-file-preview`),this.elements.previewContent?.classList.remove(`is-mermaid-file-preview`),this.elements.previewContent?.classList.remove(`is-plantuml-file-preview`),this.elements.previewContent?.classList.remove(`is-structurizr-file-preview`),this.structurizrPreview.reset()}syncFileChrome(e,{drawioMode:t=null,preferPreviewForBase:n=!1}={}){let r=this.isDrawioFile(e),i=this.isExcalidrawFile(e),a=this.isBaseFile(e),o=this.isImageFile(e),s=this.isPdfFile(e),c=_(e),l=this.isMermaidFile(e),d=this.isPlantUmlFile(e),p=u(e),m=f(e),h=i||r&&t!==`text`;if(this.backlinksPanel.setDisplayMode?.(h?`header`:`dock`),this.elements.editorFindButton?.classList.toggle(`hidden`,!c),this.elements.markdownToolbar?.classList.toggle(`hidden`,!c),this.elements.exportMenuGroup?.classList.toggle(`hidden`,!c),this.elements.outlineToggle?.classList.toggle(`hidden`,m||o||s||a),this.elements.previewContent?.classList.toggle(`is-mermaid-file-preview`,l),this.elements.previewContent?.classList.toggle(`is-plantuml-file-preview`,d),this.elements.previewContent?.classList.toggle(`is-structurizr-file-preview`,p),p&&(this.outlineController.close(),this.backlinksPanel.clear()),r&&t!==`text`||i||o||s||a&&n){this.layoutController.setView(`preview`,{persist:!1}),this.outlineController.close(),this.backlinksPanel.clear();return}(l||d)&&(this.outlineController.close(),this.backlinksPanel.clear())}renderExcalidrawFilePreview(e){let t=this.elements.previewContent;if(!t)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode(),t.classList.add(`is-excalidraw-file-preview`);let n=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(n);let r=document.createElement(`div`);r.className=`excalidraw-embed-placeholder`,r.dataset.embedKey=`${e}#file-preview`,r.dataset.embedLabel=this.getDisplayName(e),r.dataset.embedTarget=e;let i=document.createElement(`div`);i.className=`preview-shell`,i.textContent=`Loading Excalidraw preview…`,r.appendChild(i),n&&(n.replaceChildren(r),n.style.minHeight=``),t.dataset.renderPhase=`ready`,this.outlineController.refresh(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.videoEmbed?.reconcileEmbeds(t),this.drawioEmbed.reconcileEmbeds(t),this.excalidrawEmbed.reconcileEmbeds(t,{isLargeDocument:!1}),this.drawioEmbed.hydrateVisibleEmbeds(),this.excalidrawEmbed.hydrateVisibleEmbeds(),this.schedulePreviewLayoutSyncCallback({delayMs:0})}renderDrawioFilePreview(e){let t=this.elements.previewContent;if(!t)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode(),t.classList.add(`is-drawio-file-preview`);let n=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(n);let r=document.createElement(`div`);r.className=`drawio-embed-placeholder`,r.dataset.drawioKey=`${e}#file-preview`,r.dataset.drawioLabel=this.getDisplayName(e),r.dataset.drawioMode=`edit`,r.dataset.drawioTarget=e;let i=document.createElement(`div`);i.className=`preview-shell`,i.textContent=`Loading draw.io preview…`,r.appendChild(i),n&&(n.replaceChildren(r),n.style.minHeight=``),t.dataset.renderPhase=`ready`,this.outlineController.refresh(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.videoEmbed?.reconcileEmbeds(t),this.drawioEmbed.reconcileEmbeds(t),this.drawioEmbed.hydrateVisibleEmbeds(),this.schedulePreviewLayoutSyncCallback({delayMs:0})}renderImageFilePreview(e){let t=this.elements.previewContent;if(!t)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode(),t.classList.add(`is-image-file-preview`);let n=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(n);let r=document.createElement(`figure`);r.className=`image-file-preview-shell`;let i=document.createElement(`img`);i.className=`image-file-preview-image`,i.alt=this.getDisplayName(e),i.src=F(`/attachment?path=${encodeURIComponent(e)}`),r.appendChild(i),n&&(n.replaceChildren(r),n.style.minHeight=``),t.dataset.renderPhase=`ready`,this.outlineController.refresh(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.videoEmbed?.reconcileEmbeds(t),this.schedulePreviewLayoutSyncCallback({delayMs:0})}renderPdfFilePreview(e){let t=this.elements.previewContent;if(!t)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode(),t.classList.add(`is-pdf-file-preview`);let n=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(n),n&&(this.pdfPreview.render({filePath:e,renderHost:n}),n.style.minHeight=``),t.dataset.renderPhase=`ready`,this.outlineController.close(),this.backlinksPanel.clear(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.videoEmbed?.reconcileEmbeds(t),this.schedulePreviewLayoutSyncCallback({delayMs:0})}async renderBaseFilePreview(e,{source:t=null}={}){let n=this.elements.previewContent;if(!n)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode(),n.classList.add(`is-base-file-preview`);let r=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(r),r&&(r.style.minHeight=``),await this.basesPreview.renderStandalone({filePath:e,renderHost:r,source:typeof t==`string`?t:this.getSession()?.getText?.()??null}),n.dataset.renderPhase=`ready`,this.outlineController.close(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.videoEmbed?.reconcileEmbeds(n),this.schedulePreviewLayoutSyncCallback({delayMs:0})}async renderStructurizrFilePreview(e,{source:t=null}={}){let n=this.elements.previewContent;if(!n)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode(),n.classList.add(`is-structurizr-file-preview`);let r=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(r),r&&(r.style.minHeight=``),await this.structurizrPreview.render({filePath:e,renderHost:r,source:typeof t==`string`?t:this.getSession()?.getText?.()??``}),n.dataset.renderPhase=`ready`,this.outlineController.close(),this.backlinksPanel.clear(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.videoEmbed?.reconcileEmbeds(n),this.schedulePreviewLayoutSyncCallback({delayMs:0})}renderTextFilePreview({content:e=``}={}){let t=this.elements.previewContent;if(!t)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode();let n=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(n);let r=document.createElement(`div`);r.className=`preview-shell`;let i=document.createElement(`pre`),a=document.createElement(`code`);a.textContent=String(e??``),i.appendChild(a),r.appendChild(i),n&&(n.replaceChildren(r),n.style.minHeight=``),t.dataset.renderPhase=`ready`,this.outlineController.close(),this.backlinksPanel.clear(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.videoEmbed?.reconcileEmbeds(t),this.schedulePreviewLayoutSyncCallback({delayMs:0})}createResizeHandler(e){let t=null;return()=>{clearTimeout(t),t=setTimeout(()=>{e?.(),this.schedulePreviewLayoutSyncCallback({delayMs:0})},100)}}initializePreviewLayoutObserver(e=()=>{}){if(typeof ResizeObserver!=`function`||!this.elements.previewContent)return null;let t=new ResizeObserver(()=>{e()});return t.observe(this.elements.previewContent),t}schedulePreviewLayoutSync({hydrationPaused:e,previewLayoutSyncTimer:t,setPendingPreviewLayoutSync:n,setPreviewLayoutSyncTimer:r,delayMs:i=120}){if(e){n(!0);return}clearTimeout(t),r(setTimeout(()=>{r(null);let t=!!this.getSession(),i=this.elements.previewContent?.classList?.contains?.(`is-drawio-file-preview`)??!1,a=this.elements.previewContent?.classList?.contains?.(`is-excalidraw-file-preview`)??!1;if(!(!t&&!i&&!a||!this.elements.previewContent)&&this.elements.previewContent.dataset.renderPhase!==`shell`){if(e){n(!0);return}this.videoEmbed?.syncLayout(),this.drawioEmbed.syncLayout(),this.excalidrawEmbed.syncLayout(),!((i||a)&&!t)&&(this.scrollSyncController.invalidatePreviewBlocks(),this.scrollSyncController.warmPreviewBlocks({onReady:()=>{this.getSession()&&(this.scrollSyncController.realignAfterLayoutChange(),this.outlineController.scheduleActiveHeadingUpdate())}}))}},i))}handleEditorScrollActivityChange({isActive:e,pendingPreviewLayoutSync:t,previewLayoutSyncTimer:n,setHydrationPaused:r,setPendingPreviewLayoutSync:i,setPreviewLayoutSyncTimer:a}){let o=!!e;if(r(o),this.previewRenderer.setHydrationPaused(o),this.drawioEmbed.setHydrationPaused(o),this.excalidrawEmbed.setHydrationPaused(o),o){clearTimeout(n),a(null),i(!0);return}t&&(i(!1),this.schedulePreviewLayoutSync({delayMs:0,hydrationPaused:!1,previewLayoutSyncTimer:null,setPendingPreviewLayoutSync:i,setPreviewLayoutSyncTimer:a}))}},$t=300,en=20,tn=50;function nn(e=``){let t=String(e??``).replace(/^#/,``);if(!t)return``;try{return decodeURIComponent(t)}catch{return t}}function rn(e){try{let t=e?.contentDocument,n=t?.querySelector(`.joint-layers`),r=t?.querySelector(`#diagram-viewport`),i=n?new DOMMatrixReadOnly(getComputedStyle(n).transform).a:0;return{scrollLeft:r?.scrollLeft??0,scrollTop:r?.scrollTop??0,zoom:Number.isFinite(i)&&i>0?i:null}}catch{return null}}var an=class{constructor({enabled:e=!1,syncWorkspace:t}){this.enabled=!!e,this.syncWorkspace=t,this.iframe=null,this.shell=null,this.status=null,this.maximizeButton=null,this.filePath=null,this.viewKey=``,this.lastVersion=null,this.syncTimer=null,this.syncToken=0,this.frameFitTimer=null,this.frameHost=null,this.pendingIframe=null,this.pendingVersion=null,this.handleFrameLoad=e=>{let t=e?.currentTarget||this.iframe;if(t)try{t===this.iframe&&(this.viewKey=nn(t.contentWindow?.location?.hash||``)||this.viewKey,t.contentWindow?.addEventListener(`hashchange`,this.handleFrameHashChange)),this.prepareFrame(t)}catch{t===this.pendingIframe&&this.commitPendingIframe(t)}},this.handleFrameHashChange=()=>{try{this.viewKey=nn(this.iframe?.contentWindow?.location?.hash||``)||this.viewKey}catch{}}}setStatus(e=``,{error:t=!1}={}){this.status&&(this.status.textContent=e,this.status.hidden=!e,this.status.classList.toggle(`is-error`,t))}prepareFrame(e=this.iframe){if(!e?.contentDocument?.head){e===this.pendingIframe&&this.commitPendingIframe(e);return}e.contentWindow?.dispatchEvent(new Event(`resize`)),this.scheduleFrameFit(e,e===this.pendingIframe?()=>this.commitPendingIframe(e):null)}fitFrameToCanvas(e=this.iframe){let t=e?.contentDocument,n=t?.querySelector(`#diagram-canvas`);if(!n||e===this.pendingIframe&&!t.querySelector(`.joint-layers`))return!1;try{let t=e?.contentWindow?.structurizr?.diagram;t?.setEmbedded?.(!0),t?.resize?.(),t?.zoomToWidthOrHeight?.()}catch{}let{width:r,height:i}=n.getBoundingClientRect();return!(!r||!i)}disposeFrame(e){if(e){try{e.contentWindow?.removeEventListener?.(`hashchange`,this.handleFrameHashChange)}catch{}e.removeEventListener(`load`,this.handleFrameLoad),e.remove()}}discardPendingIframe(){this.pendingIframe&&(clearTimeout(this.frameFitTimer),this.frameFitTimer=null,this.disposeFrame(this.pendingIframe),this.pendingIframe=null,this.pendingVersion=null)}commitPendingIframe(e){if(e!==this.pendingIframe||!this.shell?.isConnected)return;let t=this.iframe,n=this.pendingVersion,r=rn(t);if(this.pendingIframe=null,this.pendingVersion=null,r?.zoom)try{e.contentWindow?.structurizr?.diagram?.zoomTo?.(r.zoom)}catch{}try{let t=e.contentDocument?.querySelector(`#diagram-viewport`);t&&r&&(t.scrollLeft=r.scrollLeft,t.scrollTop=r.scrollTop)}catch{}this.disposeFrame(t),e.style.visibility=``,e.style.pointerEvents=``,e.removeAttribute(`aria-hidden`),this.iframe=e,this.lastVersion=n;try{this.viewKey=nn(e.contentWindow?.location?.hash||``)||this.viewKey,e.contentWindow?.addEventListener(`hashchange`,this.handleFrameHashChange)}catch{}this.setStatus(``)}createIframe(){let e=document.createElement(`iframe`);return e.className=`structurizr-preview-iframe`,e.title=`Structurizr architecture diagram`,e.loading=`eager`,e.referrerPolicy=`same-origin`,e.addEventListener(`load`,this.handleFrameLoad),e}syncMaximizeButtonState(){if(!this.maximizeButton||!this.shell)return;let e=this.shell.classList.contains(`is-maximized`);V(this.maximizeButton,e?`restore`:`maximize`);let t=e?`Restore diagram size`:`Maximize diagram`;this.maximizeButton.title=t,this.maximizeButton.setAttribute(`aria-label`,t)}setMaximized(e){let t=!!e;this.shell?.classList.toggle(`is-maximized`,t),document.body?.classList.toggle(`structurizr-maximized-open`,t),this.syncMaximizeButtonState(),this.iframe?.contentWindow?.dispatchEvent(new Event(`resize`))}scheduleFrameFit(e=this.iframe,t=null){if(!e)return;clearTimeout(this.frameFitTimer);let n=0,r=()=>{if(this.frameFitTimer=null,this.fitFrameToCanvas(e)||n>=en){t?.();return}n+=1,this.frameFitTimer=setTimeout(r,tn)};r()}mount(e,t){if(this.filePath&&this.filePath!==t&&(this.setMaximized(!1),this.discardPendingIframe(),this.disposeFrame(this.iframe),this.iframe=null,this.lastVersion=null,this.viewKey=``),this.filePath=t,this.shell?.isConnected&&this.shell.parentElement===e)return;clearTimeout(this.frameFitTimer),this.frameFitTimer=null,this.shell=document.createElement(`section`),this.shell.className=`structurizr-preview-shell diagram-preview-shell`,this.shell.dataset.structurizrPreview=`true`;let n=document.createElement(`div`);n.className=`structurizr-preview-header diagram-preview-toolbar`;let r=document.createElement(`span`);r.className=`structurizr-preview-label`,r.textContent=String(t).split(`/`).pop()?.replace(/\.dsl$/i,``)||`Structurizr`,this.maximizeButton=document.createElement(`button`),this.maximizeButton.type=`button`,this.maximizeButton.className=`structurizr-preview-btn ui-preview-action ui-preview-action--icon-only`,this.maximizeButton.dataset.action=`toggle-maximize`,this.maximizeButton.addEventListener(`click`,e=>{e.preventDefault(),this.setMaximized(!this.shell?.classList.contains(`is-maximized`))}),n.append(r,this.maximizeButton),this.syncMaximizeButtonState(),this.status=document.createElement(`div`),this.status.className=`structurizr-preview-status`,this.status.setAttribute(`aria-live`,`polite`),this.status.setAttribute(`role`,`status`),this.status.hidden=!0,this.frameHost=document.createElement(`div`),this.frameHost.className=`structurizr-preview-stage`,this.shell.append(n,this.status,this.frameHost),e?.replaceChildren(this.shell),this.iframe=null,this.pendingIframe=null,this.pendingVersion=null,this.lastVersion=null}async render({filePath:e,renderHost:t,source:n=``}){return this.mount(t,e),this.syncNow({filePath:e,source:String(n??``)})}queueSync({filePath:e,source:t=``}={}){clearTimeout(this.syncTimer),this.syncTimer=setTimeout(()=>{this.syncTimer=null,this.syncNow({filePath:e,source:String(t??``)})},$t)}async syncNow({filePath:e,source:t=``}={}){if(e!==this.filePath)return!1;let n=++this.syncToken;if(!this.enabled)return this.setStatus(`Structurizr preview is not configured. Start CollabMD with --local-structurizr.`,{error:!0}),!1;this.iframe||this.setStatus(`Validating Structurizr workspace…`);try{let r=await this.syncWorkspace({path:e,source:t});if(n!==this.syncToken||e!==this.filePath)return!1;let i=r?.version||null,a=_e(`/workspace/1/diagrams`),o=this.viewKey?`#${encodeURIComponent(this.viewKey)}`:``;if(!this.iframe){let e=this.createIframe();this.iframe=e,this.frameHost?.appendChild(e),e.src=`${a}${o}`,this.lastVersion=i}else if(i!==this.lastVersion){this.discardPendingIframe();let e=this.createIframe();e.style.visibility=`hidden`,e.style.pointerEvents=`none`,e.setAttribute(`aria-hidden`,`true`),this.pendingIframe=e,this.pendingVersion=i,this.frameHost?.appendChild(e),e.src=`${a}${o}`}return this.setStatus(``),!0}catch(t){return n!==this.syncToken||e!==this.filePath||this.setStatus(t?.message||`Failed to load Structurizr workspace.`,{error:!0}),!1}}reset(){this.setMaximized(!1),clearTimeout(this.syncTimer),this.syncTimer=null,clearTimeout(this.frameFitTimer),this.frameFitTimer=null,this.syncToken+=1,this.discardPendingIframe(),this.disposeFrame(this.iframe),this.iframe=null,this.frameHost=null,this.shell=null,this.status=null,this.maximizeButton=null,this.filePath=null,this.lastVersion=null,this.viewKey=``}},on=150;function sn(e){return new Promise(t=>{setTimeout(t,e)})}var cn=class{constructor({attachEditorScroller:e,beginDocumentLoad:t,cleanupAfterSessionDestroy:n,createEditorSession:r,getDisplayName:i,getFileList:a,getLineWrappingEnabled:o,getVimModeEnabled:s,getLocalUser:c,getStoredUserName:l,getTheme:u,isBaseFile:d,isDrawioFile:f,isExcalidrawFile:p,isImageFile:m,isPdfFile:h,isMermaidFile:g,isPlantUmlFile:_,isStructurizrWorkspaceFile:v,isTabActive:ee,loadBootstrapContent:te=null,loadEditorSessionClass:ne,loadBacklinks:y,onBeforeFileOpen:b,onConnectionChange:x,onContentChange:S,onCommentsChange:C,onFileAwarenessChange:w,onFileOpenError:T,onFileOpenReady:E,onImagePaste:D,onSelectionChange:O,onSessionAssigned:k=null,onFileOpenMetric:A=null,onRenderBasePreview:j,onRenderExcalidrawPreview:M,onRenderDrawioPreview:N,onRenderImagePreview:re,onRenderPdfPreview:ie,onRenderStructurizrPreview:ae,onSyncWrapToggle:P,onUpdateActiveFile:oe,onUpdateCurrentFile:se,onUpdateLobbyCurrentFile:ce,onUpdateVisibleChrome:le,onViewModeReset:ue,renderPresence:F,scrollContainerForSession:de,shouldUseDrawioPreview:fe=null,showEditorLoading:I,stateStore:pe}){this.attachEditorScroller=e,this.beginDocumentLoad=t,this.cleanupAfterSessionDestroy=n,this.createEditorSession=r,this.getDisplayName=i,this.getFileList=a,this.getLineWrappingEnabled=o,this.getVimModeEnabled=s??(()=>!1),this.getLocalUser=c,this.getStoredUserName=l,this.getTheme=u,this.isBaseFile=d??(()=>!1),this.isDrawioFile=f??(()=>!1),this.isExcalidrawFile=p??(()=>!1),this.isImageFile=m??(()=>!1),this.isPdfFile=h??(()=>!1),this.isMermaidFile=g??(()=>!1),this.isPlantUmlFile=_??(()=>!1),this.isStructurizrWorkspaceFile=v??(()=>!1),this.isTabActive=ee,this.loadBootstrapContent=te,this.loadEditorSessionClassPort=ne,this.loadBacklinks=y,this.onBeforeFileOpen=b,this.onConnectionChange=x,this.onContentChange=S,this.onCommentsChange=C,this.onFileAwarenessChange=w,this.onFileOpenError=T,this.onFileOpenReady=E,this.onImagePaste=D,this.onSelectionChange=O,this.onSessionAssigned=k,this.onFileOpenMetric=A,this.onRenderBasePreview=j,this.onRenderDrawioPreview=N,this.onRenderExcalidrawPreview=M,this.onRenderImagePreview=re,this.onRenderPdfPreview=ie,this.onRenderStructurizrPreview=ae,this.onSyncWrapToggle=P,this.onUpdateActiveFile=oe,this.onUpdateCurrentFile=se,this.onUpdateLobbyCurrentFile=ce,this.onUpdateVisibleChrome=le,this.onViewModeReset=ue,this.renderPresence=F,this.scrollContainerForSession=de,this.shouldUseDrawioPreview=fe??(()=>!0),this.showEditorLoading=I,this.stateStore=pe,this.session=null}getSession(){return this.session}loadEditorSessionClass(){return this.loadEditorSessionClassPort()}waitForNextPaint(){return new Promise(e=>{requestAnimationFrame(()=>{requestAnimationFrame(e)})})}reportFileOpenMetric(e,t,n={}){this.onFileOpenMetric?.(e,{filePath:this.stateStore.currentFilePath,loadToken:t,...n})}cleanupSession(){this.session?.destroy(),this.session=null,this.attachEditorScroller(null),this.cleanupAfterSessionDestroy()}prepareForFileOpen(e,{drawioMode:n=null,resetConnectionState:r=!0}={}){return this.onViewModeReset(),this.onBeforeFileOpen(),this.stateStore.connectionHelpShown=!1,r&&(this.stateStore.connectionState={status:`connecting`,unreachable:!1}),this.stateStore.currentDrawioMode=n??null,this.stateStore.currentFilePath=e,this.onUpdateCurrentFile(e),this.onUpdateLobbyCurrentFile(e),this.onUpdateActiveFile(e),this.onUpdateVisibleChrome(e,{displayName:this.getDisplayName(e),drawioMode:n,isMarkdown:_(e)}),this.showEditorLoading(),this.beginDocumentLoad(),this.renderPresence(),{supportsBacklinks:t(e)}}finalizeFileOpen({isBase:e=!1,isDrawio:t=!1,filePath:r,isExcalidraw:i=!1,isImage:a=!1,isPdf:o=!1,supportsBacklinks:s}){i&&this.onRenderExcalidrawPreview(r),(e||n(r))&&this.onRenderBasePreview(r),t&&this.onRenderDrawioPreview(r),a&&this.onRenderImagePreview(r),o&&this.onRenderPdfPreview(r),this.isStructurizrWorkspaceFile(r)&&this.onRenderStructurizrPreview(r,{source:this.session?.getText?.()??``}),this.onSyncWrapToggle(),s&&this.loadBacklinks(r)}async openFile(e,{drawioMode:t=null}={}){if(!this.isTabActive())return;let n=t??null,r=this.stateStore.currentDrawioMode??null,i=this.isDrawioFile(e)&&t!==`text`&&this.shouldUseDrawioPreview(e),a=this.isExcalidrawFile(e),o=this.isBaseFile(e),s=this.isImageFile(e),c=this.isPdfFile(e),l=this.isMermaidFile(e),u=this.isPlantUmlFile(e),d=this.isStructurizrWorkspaceFile(e);if(e===this.stateStore.currentFilePath&&n===r&&(this.session||i||a||s||c)){this.onUpdateActiveFile(e),this.onUpdateLobbyCurrentFile(e);return}let f=++this.stateStore.sessionLoadToken,p=performance.now();this.cleanupSession();let m=this.prepareForFileOpen(e,{drawioMode:n,resetConnectionState:!i&&!a&&!s&&!c});if(this.reportFileOpenMetric(`open_started`,f,{filePath:e}),i||a||s||c){if(this.onSessionAssigned?.(null),f!==this.stateStore.sessionLoadToken)return;this.onFileOpenReady(null),this.finalizeFileOpen({filePath:e,isBase:o,isDrawio:i,isExcalidraw:a,isImage:s,isPdf:c,session:null,supportsBacklinks:m.supportsBacklinks});return}let h=await this.loadEditorSessionClass(),g=this.createEditorSession(h,{filePath:e,getFileList:this.getFileList,lineWrappingEnabled:this.getLineWrappingEnabled(),localUser:this.getLocalUser(),vimModeEnabled:this.getVimModeEnabled(),onAwarenessChange:e=>this.onFileAwarenessChange(e),onConnectionChange:e=>this.onConnectionChange(e),onCommentsChange:e=>this.onCommentsChange?.(e),onContentChange:()=>{a||this.onContentChange({isBase:o,isMermaid:l,isPlantUml:u,isStructurizrWorkspace:d})},onImagePaste:e=>this.onImagePaste?.(e),preferredUserName:this.getStoredUserName(),onSelectionChange:e=>this.onSelectionChange?.(e),theme:this.getTheme()});this.session=g,this.onSessionAssigned?.(g);try{let t=!1,n=!1,r=!1,i=async r=>{t||f!==this.stateStore.sessionLoadToken||(t=!0,this.attachEditorScroller(this.scrollContainerForSession(g)),g.applyTheme(this.getTheme()),this.onFileOpenReady(g),this.reportFileOpenMetric(`editor_ready`,f,{reason:r}),g.requestMeasure(),await this.waitForNextPaint(),!(n||f!==this.stateStore.sessionLoadToken)&&(n=!0,this.finalizeFileOpen({filePath:e,isBase:o,isExcalidraw:a,session:g,supportsBacklinks:m.supportsBacklinks})))},s=this.loadBootstrapContent?(async()=>{this.reportFileOpenMetric(`bootstrap_fetch_started`,f);try{let t=await this.loadBootstrapContent(e);return this.reportFileOpenMetric(`bootstrap_fetch_completed`,f,{found:t!==null}),t}catch(e){return this.reportFileOpenMetric(`bootstrap_fetch_completed`,f,{error:e.message,found:!1}),null}})():Promise.resolve(null),c=g.initialize(e),l=(async()=>(await c,f!==this.stateStore.sessionLoadToken||(await g.waitForInitialSync(null),f!==this.stateStore.sessionLoadToken)?!1:(r=!0,g.activateCollaborativeView?.(),this.attachEditorScroller(this.scrollContainerForSession(g)),g.applyTheme(this.getTheme()),this.reportFileOpenMetric(`initial_sync_complete`,f),g.ensureInitialContent?.(),t?g.requestMeasure():await i(`live-sync`),!0)))(),u=(async()=>{let n=await s;if(n===null||r||t||f!==this.stateStore.sessionLoadToken)return!1;let a=performance.now()-p,o=Math.max(0,on-a);return o>0&&await Promise.race([l.then(e=>e?`live-sync`:`stale`),sn(o).then(()=>`timeout`)])===`live-sync`||r||t||f!==this.stateStore.sessionLoadToken||!g.showBootstrapContent({content:n,filePath:e})&&!g.hasBootstrapContent?.()?!1:(this.reportFileOpenMetric(`bootstrap_shown`,f),await i(`bootstrap`),!0)})();if(await c,f!==this.stateStore.sessionLoadToken){g.destroy();return}if(await Promise.all([l,u]),f!==this.stateStore.sessionLoadToken){g.destroy();return}t||(g.ensureInitialContent?.(),await i(`post-initialize`))}catch(e){if(console.error(`[app] Failed to initialize editor:`,e),g.destroy(),this.attachEditorScroller(null),this.session===g&&(this.session=null),f!==this.stateStore.sessionLoadToken)return;this.onFileOpenError()}}};function ln(e=document){return{currentUserName:e.getElementById(`currentUserName`),chatContainer:e.getElementById(`chatContainer`),chatEmptyState:e.getElementById(`chatEmptyState`),chatForm:e.getElementById(`chatForm`),chatInput:e.getElementById(`chatInput`),chatMessages:e.getElementById(`chatMessages`),chatPanel:e.getElementById(`chatPanel`),chatCloseButton:e.getElementById(`chatCloseBtn`),chatStatus:e.getElementById(`chatStatus`),chatToastContainer:e.getElementById(`chatToastContainer`),chatNotificationButton:e.getElementById(`chatNotificationBtn`),chatNotificationMuteButton:e.getElementById(`chatNotificationMuteBtn`),chatNotificationStatus:e.getElementById(`chatNotificationStatus`),chatToggleBadge:e.getElementById(`chatToggleBadge`),chatToggleButton:e.getElementById(`chatToggleBtn`),gitCommitCancel:e.getElementById(`gitCommitCancel`),gitCommitCopy:e.getElementById(`gitCommitCopy`),gitCommitDialog:e.getElementById(`gitCommitDialog`),gitCommitForm:e.getElementById(`gitCommitForm`),gitCommitInput:e.getElementById(`gitCommitInput`),gitCommitSubmit:e.getElementById(`gitCommitSubmit`),gitCommitTitle:e.getElementById(`gitCommitTitle`),gitResetCancel:e.getElementById(`gitResetCancel`),gitResetCopy:e.getElementById(`gitResetCopy`),gitResetDialog:e.getElementById(`gitResetDialog`),gitResetFileName:e.getElementById(`gitResetFileName`),gitResetSubmit:e.getElementById(`gitResetSubmit`),gitResetTitle:e.getElementById(`gitResetTitle`),displayNameCancel:e.getElementById(`displayNameCancel`),displayNameCopy:e.getElementById(`displayNameCopy`),displayNameDialog:e.getElementById(`displayNameDialog`),displayNameForm:e.getElementById(`displayNameForm`),displayNameInput:e.getElementById(`displayNameInput`),displayNameSubmit:e.getElementById(`displayNameSubmit`),displayNameTitle:e.getElementById(`displayNameTitle`),editNameButton:e.getElementById(`editNameBtn`),editorFindButton:e.getElementById(`editorFindBtn`),editorContainer:e.getElementById(`editorContainer`),exportDocxButton:e.getElementById(`exportDocxBtn`),exportHtmlButton:e.getElementById(`exportHtmlBtn`),exportMenuGroup:e.getElementById(`exportMenuGroup`),exportPdfButton:e.getElementById(`exportPdfBtn`),markdownToolbar:e.getElementById(`markdownToolbar`),editorPage:e.getElementById(`editor-page`),diffPage:e.getElementById(`diff-page`),fileSearch:e.getElementById(`fileSearch`),fileHistoryButton:e.getElementById(`fileHistoryBtn`),fileHistoryButtonLabel:e.getElementById(`fileHistoryBtnLabel`),filesSidebarTab:e.getElementById(`filesSidebarTab`),gitSearch:e.getElementById(`gitSearch`),gitSearchInput:e.getElementById(`gitSearchInput`),gitSidebarTab:e.getElementById(`gitSidebarTab`),gitOperationStatus:e.getElementById(`gitOperationStatus`),lineInfo:e.getElementById(`lineInfo`),mobileViewToggle:e.getElementById(`mobileViewToggle`),previewContent:e.getElementById(`previewContent`),previewContainer:e.getElementById(`previewContainer`),presencePanel:e.getElementById(`presencePanel`),presencePanelList:e.getElementById(`presencePanelList`),presencePanelStatus:e.getElementById(`presencePanelStatus`),searchFilesButton:e.getElementById(`searchFilesBtn`),toolbarSearchButton:e.getElementById(`toolbarSearchBtn`),shareButton:e.getElementById(`shareBtn`),toastContainer:e.getElementById(`toastContainer`),toggleWrapButton:e.getElementById(`toggleWrapBtn`),toggleVimModeButton:e.getElementById(`toggleVimModeBtn`),userAvatars:e.getElementById(`userAvatars`),userCount:e.getElementById(`userCount`),wrapToggleLabel:e.getElementById(`wrapToggleLabel`),vimModeToggleLabel:e.getElementById(`vimModeToggleLabel`),activeFileName:e.getElementById(`activeFileName`),sidebarToggle:e.getElementById(`sidebarToggle`),sidebarClose:e.getElementById(`sidebarClose`),sidebarBackdrop:e.getElementById(`sidebarBackdrop`),sidebar:e.getElementById(`sidebar`),sidebarResizer:e.getElementById(`sidebarResizer`),emptyState:e.getElementById(`emptyState`),emptyStateNewFileBtn:e.getElementById(`emptyStateNewFileBtn`),emptyStateSearchBtn:e.getElementById(`emptyStateSearchBtn`),backlinksPanel:e.getElementById(`backlinksPanel`),backlinksHeaderPanel:e.getElementById(`backlinksHeaderPanel`),backlinksInlinePanel:e.getElementById(`backlinksInlinePanel`),commentSelectionButton:e.getElementById(`commentSelectionBtn`),commentsDrawer:e.getElementById(`commentsDrawer`),commentsDrawerEmpty:e.getElementById(`commentsDrawerEmpty`),commentsDrawerList:e.getElementById(`commentsDrawerList`),commentsSidebarTab:e.getElementById(`commentsSidebarTab`),commentsToggleButton:e.getElementById(`commentsToggle`),commentOverviewPanel:e.getElementById(`commentOverviewPanel`),outlineToggle:e.getElementById(`outlineToggle`),tabLockCopy:e.getElementById(`tabLockCopy`),tabLockOverlay:e.getElementById(`tabLockOverlay`),tabLockTakeoverButton:e.getElementById(`tabLockTakeoverBtn`),tabLockTitle:e.getElementById(`tabLockTitle`),toolbarCenter:e.getElementById(`toolbarCenter`),toolbarDiffBadge:e.getElementById(`toolbarDiffBadge`),toolbarOverflowMenu:e.getElementById(`toolbarOverflowMenu`),toolbarOverflowToggle:e.getElementById(`toolbarOverflowToggle`),toolbarViewToggle:e.getElementById(`toolbarViewToggle`),sidebarTabs:e.getElementById(`sidebarTabs`)}}var un=`collabmd-chat-alerts-muted-until`,dn=36e5;function fn(e){return e.lobby?.getConnectionState?.()??{status:`connected`,unreachable:!1}}function pn(e){return e.scrollHeight-e.scrollTop-e.clientHeight<=24}function mn(){try{let e=Number(globalThis.localStorage?.getItem(un));return!Number.isFinite(e)||e<=Date.now()?(globalThis.localStorage?.removeItem(un),0):e}catch{return 0}}function hn(e){try{e>0?globalThis.localStorage?.setItem(un,String(e)):globalThis.localStorage?.removeItem(un)}catch{}}var gn={updateChatMessages(e,{initial:t=!1}={}){let n=new Set(this.chatMessageIds),r=this.lobby.getLocalUser()?.peerId??null;if(this.chatMessages=e,this.chatMessageIds=new Set(e.map(e=>e.id)),!this.chatInitialSyncComplete){t&&(this.chatInitialSyncComplete=!0),this.renderChat();return}let i=e.filter(e=>!n.has(e.id)&&e.peerId&&e.peerId!==r);this.chatIsOpen?this.chatUnreadCount=0:i.length>0&&(this.chatUnreadCount+=i.length);for(let e of i)this.maybeNotifyChatMessage(e);this.renderChat()},toggleChatPanel(){if(this.chatIsOpen){this.closeChatPanel({restoreFocus:!0});return}this.openChatPanel()},openChatPanel(){this.chatIsOpen=!0,this.chatUnreadCount=0,this.renderChat({stickToBottom:!0}),requestAnimationFrame(()=>{this.elements.chatInput?.focus()})},closeChatPanel({restoreFocus:e=!1}={}){this.chatIsOpen&&(this.chatIsOpen=!1,this.renderChat({messagesChanged:!1}),e&&requestAnimationFrame(()=>this.elements.chatToggleButton?.focus()))},handleChatSubmit(){let e=fn(this);if(this.isTabActive===!1||e.status!==`connected`)return;let t=this.elements.chatInput;if(t){if(!this.lobby.sendChatMessage(t.value)){t.focus();return}if(t.value=``,!this.chatIsOpen){this.openChatPanel();return}this.renderChat({stickToBottom:!0})}},renderChat({messagesChanged:e=!0,stickToBottom:t=!1}={}){this.elements.chatContainer?.classList.toggle(`is-open`,this.chatIsOpen),this.elements.chatPanel?.classList.toggle(`hidden`,!this.chatIsOpen),this.syncChatToggleButton(),this.syncChatNotificationButton();let n=this.elements.chatMessages,r=this.elements.chatEmptyState,i=fn(this),a=i.status===`connected`,o=a&&this.chatInitialSyncComplete&&this.isTabActive!==!1;this.elements.chatStatus&&(this.elements.chatStatus.textContent=this.chatInitialSyncComplete?a?`${this.globalUsers.length} online`:i.unreachable?`Server unreachable`:`Reconnecting...`:`Syncing...`);let s=this.elements.chatForm?.querySelector?.(`button[type="submit"]`);if(s&&(s.disabled=!o,s.title=o?`Send message`:`Chat is unavailable while disconnected`),!n||!this.chatIsOpen||!e)return;if(this.chatMessages.length===0){n.replaceChildren(),r?.classList.remove(`hidden`),n.classList.add(`hidden`);return}r?.classList.add(`hidden`),n.classList.remove(`hidden`);let c=t||pn(n),l=document.createDocumentFragment();this.chatMessages.forEach(e=>{l.appendChild(this.createChatMessageElement(e))}),n.replaceChildren(l),c&&this.scrollChatToBottom()},createChatMessageElement(e){let t=document.createElement(`article`),n=e.peerId===this.lobby.getLocalUser()?.peerId;t.className=`chat-message`,t.classList.toggle(`is-local`,n);let r=document.createElement(`div`);r.className=`chat-message-avatar`;let i=e.userColor||`var(--color-primary-active)`;r.style.backgroundColor=i,r.style.color=Te(e.userColor),r.textContent=(e.userName||`?`).charAt(0).toUpperCase(),r.setAttribute(`aria-hidden`,`true`);let a=document.createElement(`div`);a.className=`chat-message-body`;let o=document.createElement(`div`);o.className=`chat-message-meta`;let s=document.createElement(`span`);s.className=`chat-message-author`,s.textContent=n?`${e.userName} (you)`:e.userName;let c=document.createElement(`span`);c.className=`chat-message-time`,c.textContent=this.formatChatTimestamp(e.createdAt),o.append(s,c);let l=this.getChatMessageFileLabel(e.filePath);if(l){let e=document.createElement(`span`);e.className=`ui-pill chat-message-file`,e.textContent=l,o.append(e)}let u=document.createElement(`p`);return u.className=`chat-message-text`,u.textContent=e.text,a.append(o,u),t.append(r,a),t},scrollChatToBottom(){let e=this.elements.chatMessages;e&&requestAnimationFrame(()=>{e.scrollTop=e.scrollHeight})},formatChatTimestamp(e){if(!Number.isFinite(e))return``;try{return this.chatTimeFormatter.format(new Date(e))}catch{return``}},getChatMessageFileLabel(e){return e?this.getDisplayName(e):``},formatChatToastMessage(e){let t=e?.userName||`Someone`,n=String(e?.text??``).replace(/\s+/g,` `).trim();return`${t}: ${n.length>88?`${n.slice(0,85).trimEnd()}...`:n}`},syncChatNotificationButton(){let e=this.elements.chatNotificationButton,t=this.elements.chatNotificationMuteButton,n=this.elements.chatNotificationStatus;if(!e&&!t&&!n)return;let r=this.notifications?.getPermission?.()??`unsupported`,i=r===`granted`,a=i&&mn()>0,o=r===`denied`,s=i?{text:a?`Alerts muted`:`Alerts on`,label:a?`Desktop alerts muted`:`Desktop alerts enabled`}:o?{text:`Alerts blocked`,label:`Desktop alerts blocked in browser settings`}:null;if(e&&(e.classList.toggle(`hidden`,r!=="default"),e.disabled=!1,e.removeAttribute(`aria-pressed`),e.textContent=`Enable desktop alerts`,e.title=`Allow desktop alerts for new chat messages`),t){t.classList.toggle(`hidden`,!i),t.disabled=!1,t.setAttribute(`aria-pressed`,String(a));let e=a?`Unmute desktop alerts`:`Mute desktop alerts for one hour`;t.setAttribute(`aria-label`,e),t.title=e}n&&(n.classList.toggle(`hidden`,!s),n.textContent=s?.text??``,s?(n.setAttribute(`aria-label`,s.label),n.title=s.label):(n.removeAttribute(`aria-label`),n.removeAttribute(`title`)),n.classList.toggle(`ui-status-badge--accent`,i&&!a),n.classList.toggle(`ui-status-badge--muted`,o||a))},async handleChatNotificationToggle(){let e=await this.notifications?.requestPermission?.();if(this.syncChatNotificationButton(),e!==`granted`){if(e===`denied`){(this.chatToastController??this.toastController)?.show(`Desktop alerts are blocked. Allow them in browser site settings.`,{duration:5e3,tone:`warning`});return}e===`unsupported`&&(this.chatToastController??this.toastController)?.show(`This browser does not support desktop alerts.`,{duration:5e3,tone:`warning`})}},toggleChatNotificationMute(){hn(mn()>0?0:Date.now()+dn),this.renderChat({messagesChanged:!1})},syncChatToggleButton(){let e=this.elements.chatToggleButton,t=this.elements.chatToggleBadge;if(!e)return;let n=this.chatUnreadCount>0,r=n&&!this.chatIsOpen;e.classList.toggle(`is-active`,this.chatIsOpen),e.classList.toggle(`is-unread`,r),e.setAttribute(`aria-controls`,`chatPanel`),e.setAttribute(`aria-expanded`,String(this.chatIsOpen)),e.setAttribute(`aria-label`,n?`Open team chat, ${this.chatUnreadCount} unread`:`Open team chat`),e.title=this.chatUnreadCount>0?`Team chat (${this.chatUnreadCount} unread)`:`Team chat`,t&&(t.classList.toggle(`hidden`,!n),t.textContent=this.chatUnreadCount>9?`9+`:String(this.chatUnreadCount))},maybeNotifyChatMessage(e){if(!this.chatInitialSyncComplete||this.isTabActive===!1||this.chatIsOpen||mn()>0)return;let t=!!(globalThis.document?.hidden||globalThis.document?.visibilityState===`hidden`),n=typeof globalThis.document?.hasFocus==`function`?globalThis.document.hasFocus():!t,r=null;(t||!n)&&(r=this.notifications?.show?.({body:String(e?.text??``).replace(/\s+/g,` `).trim(),onClick:()=>{window.focus?.(),r?.close?.(),this.openChatPanel()},tag:`collabmd-chat-${e?.id??`message`}`,title:`New message from ${e?.userName||`Someone`}`})),!r&&(this.chatToastController??this.toastController).show(this.formatChatToastMessage(e),4e3)}},_n={createCommentThread(e){let t=this.session?.createCommentThread(e);return t&&this.scheduleCommentOverviewRefresh(),t},replyToCommentThread(e,t){let n=this.session?.replyToCommentThread(e,t);return n&&this.scheduleCommentOverviewRefresh(),n},resolveCommentThread(e){let t=this.session?.deleteCommentThread(e);return t&&this.scheduleCommentOverviewRefresh(),t},getCommentFileKind(e=this.currentFilePath){return m(e)||`markdown`},syncCommentChrome(e=this.currentFilePath){let t=v(e)&&!this.isExcalidrawFile(e);this.commentUi.setCurrentFile(e,{fileKind:this.getCommentFileKind(e),supported:t}),this.handleCommentThreadsChange(this.session?.getCommentThreads?.()??[]),this.handleCommentSelectionChange(this.session?.getCurrentSelectionCommentAnchor?.()??null)},handleCommentSelectionChange(e){this.commentUi.setSelectionAnchor(e)},handleCommentThreadsChange(e=[]){this.commentUi.setThreads(e),this.focusPendingCommentOverviewThread()},handleCommentEditorContentChange(){this.commentUi.handleEditorContentChange()},refreshCommentUiLayout(){this.commentUi.refreshLayout()},scheduleCommentOverviewRefresh({delayMs:e=900}={}){clearTimeout(this._commentOverviewRefreshTimer),this._commentOverviewRefreshTimer=setTimeout(()=>{this._commentOverviewRefreshTimer=null,this._commentOverviewStale=!1,this.commentsOverview?.refresh?.()},e)},handleCommentOverviewWorkspaceTreeChange(){this._commentOverviewStale=!0,this.activeSidebarTab===`comments`&&this.scheduleCommentOverviewRefresh({delayMs:0})},refreshCommentOverviewForSidebarOpen(){this._commentOverviewStale=!1,this.commentsOverview?.refresh?.()},async openCommentOverviewThread({anchor:e=null,filePath:t,threadId:n}={}){if(!t||!n)return;let r=m(t)===`excalidraw`,i=Number.isFinite(e?.startLine)?e.startLine:null;if(r||(this._pendingCommentOverviewFocus={attempts:0,filePath:t,line:i,threadId:n}),this.setSidebarTab(`comments`),this.setSidebarVisibility(!0),this.workspaceRouteController?.preserveSidebarTabForNextFileRoute?.(t),this.navigation.navigateToFile(t,r?void 0:{line:i}),(this.currentFilePath!==t||!this.session)&&await this.workspaceRouteController.openFile(t),this.setSidebarTab(`comments`),this.setSidebarVisibility(!0),r){this.excalidrawEmbed?.openCommentThread?.(t,n),this.closeSidebarOnMobile?.();return}this.focusPendingCommentOverviewThread(),this.closeSidebarOnMobile?.()},focusPendingCommentOverviewThread(){let e=this._pendingCommentOverviewFocus;return!e||e.filePath!==this.currentFilePath?!1:(Number.isFinite(e.line)&&this.session?.scrollToLine?.(e.line,.2),this.commentUi.openThreadFromOverview?.(e.threadId)?(this._pendingCommentOverviewFocus=null,this.setSidebarTab(`comments`),!0):e.attempts>=8?(this._pendingCommentOverviewFocus=null,!1):(e.attempts+=1,clearTimeout(this._commentOverviewFocusTimer),this._commentOverviewFocusTimer=setTimeout(()=>{this._commentOverviewFocusTimer=null,this.focusPendingCommentOverviewThread()},120),!1))}},vn=`collabmd-export-page`,yn=`collabmd-export-host`,bn=500,xn=6e4,Sn=new Map,Cn=null;function wn(){return`export-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Tn(e){return[`html`,`pdf`].includes(e)?e:`docx`}function En({filePath:e,format:t,jobId:n}){let r=new URL(se(`/export-document.html`),window.location.origin);return r.searchParams.set(`action`,Tn(t)),r.searchParams.set(`job`,n),e&&r.searchParams.set(`file`,e),r.toString()}function Dn({fileList:e=[],filePath:t,format:n,jobId:r,markdownText:i=``,title:a=``}){return{action:Tn(n),fileList:Array.isArray(e)?e.slice():[],filePath:String(t??``),jobId:r,markdownText:String(i??``),source:yn,title:String(a??``),type:`bootstrap`}}function On(e){e&&(e.closePollId&&window.clearInterval(e.closePollId),e.timeoutId&&window.clearTimeout(e.timeoutId))}function kn(e,{notifyError:t=!1,message:n=``}={}){let r=Sn.get(e);r&&(On(r),Sn.delete(e),t&&n&&Cn?.(n))}function An({onError:e=null}={}){Cn=typeof e==`function`?e:null,!window.__collabmdExportBridgeInitialized&&(window.addEventListener(`message`,e=>{if(e.origin!==window.location.origin)return;let t=e.data;if(!t||t.source!==vn)return;let n=String(t.jobId??``).trim();if(!n)return;let r=Sn.get(n);if(r){if(t.type===`ready`){if(r.window?.closed){kn(n,{message:`Export window was closed before the export completed`,notifyError:!0});return}try{r.window?.postMessage(r.payload,window.location.origin)}catch(e){kn(n,{message:e instanceof Error?e.message:`Failed to send export data`,notifyError:!0})}return}(t.type===`complete`||t.type===`error`)&&kn(n,{message:t.type===`error`&&t.message?String(t.message):``,notifyError:t.type===`error`&&!!t.message})}}),window.__collabmdExportBridgeInitialized=!0)}async function jn({fileList:e=[],filePath:t,format:n,markdownText:r=``,title:i=``}={}){let a=String(t??``).trim();if(!a)throw Error(`No markdown note is open`);let o=wn(),s=En({filePath:a,format:n,jobId:o}),c=window.open(s,`_blank`);if(!c)throw Error(`Export popup was blocked`);return Sn.set(o,{closePollId:window.setInterval(()=>{c.closed&&kn(o,{message:`Export window was closed before the export completed`,notifyError:!0})},bn),payload:Dn({fileList:e,filePath:a,format:n,jobId:o,markdownText:r,title:i}),timeoutId:window.setTimeout(()=>{kn(o,{message:`Export timed out before it completed`,notifyError:!0})},xn),window:c}),c.focus?.(),o}var Mn={initializeExportBridge(){this._exportBridgeInitialized||=(An({onError:e=>{this.toastController?.show(e)}}),!0)},async handleExportRequest(e){let t=String(this.currentFilePath??``).trim();if(!_(t))return this.toastController?.show(`Export is available for markdown notes only`),!1;try{return await jn({fileList:this.fileExplorer?.flatDocumentFiles??[],filePath:t,format:e,markdownText:this.session?.getText?.()??``,title:this.getDisplayName(t)}),!0}catch(e){return this.toastController?.show(e instanceof Error?e.message:`Failed to start export`),!1}}};function Nn(e=[]){return Array.from(new Set((e??[]).filter(Boolean)))}function Pn(e=[]){return Array.from(new Map((e??[]).filter(e=>e?.oldPath&&e?.newPath&&e.oldPath!==e.newPath).map(e=>[`${e.oldPath}:${e.newPath}`,{newPath:e.newPath,oldPath:e.oldPath}])).values())}function Fn(e=[]){return(e??[]).filter(e=>e?.path&&Number.isFinite(e?.from)&&Number.isFinite(e?.to)).map(e=>({from:Math.max(0,Math.round(e.from)),path:e.path,to:Math.max(0,Math.round(e.to))}))}function In({changedPaths:e=[],deletedPaths:t=[],refreshExplorer:n=!0,renamedPaths:r=[]}={}){return{changedPaths:Nn(e),deletedPaths:Nn(t),refreshExplorer:n!==!1,renamedPaths:Pn(r)}}function Ln(e){return!e||typeof e!=`object`||typeof e.id!=`string`?null:{action:typeof e.action==`string`?e.action:`workspace`,createdAt:Number.isFinite(e.createdAt)?e.createdAt:Date.now(),highlightRanges:Fn(e.highlightRanges),id:e.id,origin:typeof e.origin==`string`?e.origin:`api`,reloadRequiredPaths:Nn(e.reloadRequiredPaths),requestId:typeof e.requestId==`string`?e.requestId:null,sourceRef:typeof e.sourceRef==`string`?e.sourceRef:null,workspaceChange:In(e.workspaceChange)}}var Rn={formatPullBackupToast(e=null){let t=Number(e?.fileCount||0);return t===1?`Pulled latest changes. 1 overlapping local file was backed up.`:t>1?`Pulled latest changes. ${t} overlapping local files were backed up.`:`Pulled latest changes. Overlapping local changes were recorded in a pull backup.`},setGitOperationStatus(e=``){let t=this.elements.gitOperationStatus;if(!t)return;let n=String(e??``).trim();t.textContent=n,t.classList.toggle(`hidden`,!n)},async runGitActionWithStatus(e,t){this.setGitOperationStatus(e);try{return await t()}finally{this.setGitOperationStatus(``)}},handleGitDiffSelection(e,{closeSidebarOnMobile:t=!1,scope:n=`working-tree`}={}){t&&this.closeSidebarOnMobile(),this.navigation.navigateToGitDiff({filePath:e,scope:n})},handleGitCommitSelection(e,{closeSidebarOnMobile:t=!1,historyFilePath:n=null,path:r=null}={}){t&&this.closeSidebarOnMobile(),this.navigation.navigateToGitCommit({hash:e,historyFilePath:n,path:r})},handleGitHistorySelection({closeSidebarOnMobile:e=!1}={}){e&&this.closeSidebarOnMobile(),this.navigation.navigateToGitHistory()},handleGitFileHistorySelection(e=this.currentFilePath,{closeSidebarOnMobile:t=!1}={}){t&&this.closeSidebarOnMobile(),e&&this.navigation.navigateToGitFileHistory({filePath:e})},handleGitFilePreviewSelection({hash:e,path:t,currentFilePath:n=null,closeSidebarOnMobile:r=!1}={}){r&&this.closeSidebarOnMobile(),!(!e||!t)&&this.navigation.navigateToGitFilePreview({hash:e,path:t,currentFilePath:n})},handleGitRepoChange(e,t=null){this.gitRepoAvailable=!!e,this.elements.sidebarTabs?.classList.remove(`hidden`),this.elements.gitSidebarTab?.classList.toggle(`hidden`,!this.gitRepoAvailable);let n=e&&t?.summary?.changedFiles>0;if(this.elements.gitSidebarTab?.classList.toggle(`has-changes`,n),this.gitDiffView.setRepoStatus(this.gitRepoAvailable?t:null),!this.gitRepoAvailable&&this.activeSidebarTab===`git`){this.syncFileHistoryButton({mode:this.navigation.getHashRoute().type===`git-file-preview`?`history-preview`:`editor`}),this.setSidebarTab(`files`);return}let r=this.navigation.getHashRoute().type;this.gitRepoAvailable&&(r===`git-diff`||r===`git-commit`||r===`git-history`)&&this.activeSidebarTab!==`git`&&this.setSidebarTab(`git`),this.syncFileHistoryButton({filePath:this.currentFilePath,mode:r===`git-file-preview`?`history-preview`:r===`file`?`editor`:`empty`})},syncFileHistoryButton({filePath:e=this.currentFilePath,mode:t=`editor`}={}){let n=this.elements.fileHistoryButton,r=this.elements.fileHistoryButtonLabel;if(!(!n||!r)){if(!(this.gitRepoAvailable&&this.supportsFileHistory?.(e))){n.classList.add(`hidden`);return}if(n.classList.remove(`hidden`),t===`history-preview`){r.textContent=`Back to History`,n.setAttribute(`aria-label`,`Back to file history`),n.title=`Back to file history`;return}if(t!==`editor`){n.classList.add(`hidden`);return}r.textContent=`History`,n.setAttribute(`aria-label`,`Open file history`),n.title=`View file history`}},syncMainChrome({badgeLabel:e=``,mode:t,title:n=null}={}){let r=t===`diff`||t===`history`||t===`history-preview`;this.elements.toolbarViewToggle?.classList.toggle(`hidden`,r),this.elements.mobileViewToggle?.classList.toggle(`hidden`,r),this.elements.userCount?.classList.toggle(`hidden`,r),this.elements.toolbarDiffBadge?.classList.toggle(`hidden`,!e),this.elements.toolbarDiffBadge&&(this.elements.toolbarDiffBadge.textContent=e),n&&this.elements.activeFileName&&(this.elements.activeFileName.textContent=n),this.syncFileHistoryButton({filePath:this.currentFilePath,mode:t})},async showGitDiff({filePath:e=null,scope:t=`all`}={}){this.clearStaticPreviewDocument?.(),this.gitPanel.setSelection(e?{path:e,scope:t,source:`workspace`}:{}),this.gitPanel.setMode(`changes`),this.showDiffState(),this.syncMainChrome({badgeLabel:`Diff`,mode:`diff`,title:this.gitDiffView.getToolbarTitle({filePath:e,scope:t})}),this.syncFileHistoryButton({filePath:e,mode:`diff`}),await this.gitDiffView.openWorkspaceDiff({filePath:e,scope:t})},async showGitCommit({hash:e,path:t=null,historyFilePath:n=null}={}){this.clearStaticPreviewDocument?.(),this.gitPanel.setMode(`history`),this.gitPanel.setSelection(e?{commitHash:e,path:t,source:`commit`}:{source:`commit`}),this.showDiffState(),this.syncMainChrome({badgeLabel:`Diff`,mode:`diff`,title:this.gitDiffView.getToolbarTitle({commitHash:e,path:t,source:`commit`})}),this.syncFileHistoryButton({filePath:t,mode:`diff`}),await this.gitDiffView.openCommitDiff({hash:e,historyFilePath:n,path:t})},async showGitHistory(){this.clearStaticPreviewDocument?.(),this.gitPanel.setMode(`history`),this.gitPanel.setSelection({source:`commit`}),this.workspaceRouteController?.showEmptyState?.(),this.syncMainChrome({mode:`empty`,title:`Git History`}),this.syncFileHistoryButton({mode:`empty`})},async showGitFileHistory({filePath:e=null}={}){if(!e){this.workspaceRouteController?.showEmptyState?.();return}this.clearStaticPreviewDocument?.(),this.commentUi?.attachSession?.(null),this.commentUi?.setCurrentFile?.(e,{fileKind:this.getCommentFileKind(e),supported:!1}),this.handleCommentThreadsChange?.([]),this.handleCommentSelectionChange?.(null),this.workspaceRouteController?.showFileHistoryState?.(e),this.syncMainChrome({badgeLabel:`History`,mode:`history`,title:this.getDisplayName(e)}),this.syncFileHistoryButton({filePath:e,mode:`history`}),await this.fileHistoryView.openFileHistory({filePath:e})},async _loadGitFileSnapshot({hash:e,filePath:t,resolvedCurrentFilePath:n}){let r=await this.gitApiClient.readFileSnapshot({hash:e,path:t});if(this.setStaticPreviewDocument?.({...r,currentFilePath:n}),this.workspacePreviewController.resetPreviewMode(),this.elements.markdownToolbar?.classList.add(`hidden`),this.elements.outlineToggle?.classList.toggle(`hidden`,r.fileKind!==`markdown`),r.fileKind===`markdown`||r.fileKind===`mermaid`||r.fileKind===`plantuml`){r.fileKind===`mermaid`?this.elements.previewContent?.classList.add(`is-mermaid-file-preview`):r.fileKind===`plantuml`&&this.elements.previewContent?.classList.add(`is-plantuml-file-preview`),this.previewRenderer.beginDocumentLoad(),this.previewRenderer.queueRender();return}this.elements.outlineToggle?.classList.add(`hidden`),this.workspacePreviewController.renderTextFilePreview({content:r.content,filePath:n})},_handleGitFilePreviewError(e,t){console.error(`[git-preview] Failed to load file snapshot:`,e),this.clearStaticPreviewDocument?.(),this.toastController.show(`Failed to load historical file preview`),this.workspacePreviewController.renderTextFilePreview({content:`Failed to load historical file preview.`,filePath:t}),this.elements.outlineToggle?.classList.add(`hidden`)},async showGitFilePreview({hash:e,filePath:t=null,currentFilePath:n=null}={}){let r=String(n??``).trim()||t;if(!e||!t||!r){this.workspaceRouteController?.showEmptyState?.();return}this.commentUi?.attachSession?.(null),this.commentUi?.setCurrentFile?.(r,{fileKind:this.getCommentFileKind(r),supported:!1}),this.handleCommentThreadsChange?.([]),this.handleCommentSelectionChange?.(null),this.workspaceRouteController?.showPreviewOnlyState?.(r),this.layoutController.setView(`preview`,{persist:!1}),this.syncMainChrome({badgeLabel:`History Preview`,mode:`history-preview`,title:this.getDisplayName(r)}),this.syncFileHistoryButton({filePath:r,mode:`history-preview`});try{await this._loadGitFileSnapshot({hash:e,filePath:t,resolvedCurrentFilePath:r})}catch(e){this._handleGitFilePreviewError(e,r)}},async postGitAction(e,t){let n=crypto.randomUUID();this.pendingWorkspaceRequestIds?.add(n);try{switch(e){case`stage`:return await this.gitApiClient.stageFile({path:t.path,requestId:n});case`unstage`:return await this.gitApiClient.unstageFile({path:t.path,requestId:n});case`push`:return await this.gitApiClient.pushBranch({requestId:n});case`pull`:return await this.gitApiClient.pullBranch({requestId:n});case`reset-file`:return await this.gitApiClient.resetFile({path:t.path,requestId:n});case`commit`:return await this.gitApiClient.commit({message:t.message,requestId:n});default:throw Error(`Unsupported git action: ${e}`)}}catch(e){throw this.pendingWorkspaceRequestIds?.delete(n),e}},async refreshWorkspaceAfterGitAction({filePath:e=null,preferredScope:t=null}={}){await this.fileExplorer.refresh(),await this.refreshGitAfterAction({filePath:e,preferredScope:t})},async refreshGitAfterAction({filePath:e=null,preferredScope:t=null}={}){await this.gitPanel.refresh({force:!0});let n=this.navigation.getHashRoute();if(n.type===`git-history`){await this.showGitHistory();return}if(n.type===`git-file-history`){await this.showGitFileHistory({filePath:n.filePath});return}if(n.type===`git-file-preview`){await this.showGitFilePreview({hash:n.hash,filePath:n.filePath,currentFilePath:n.currentFilePath});return}if(n.type===`git-commit`){await this.showGitCommit({hash:n.hash,path:n.path,historyFilePath:n.historyFilePath});return}if(n.type!==`git-diff`)return;let r=e??n.filePath,i=t??n.scope;if(i!==n.scope||r!==n.filePath){this.navigation.navigateToGitDiff({filePath:r,scope:i});return}await this.showGitDiff({filePath:n.filePath,scope:n.scope})},async finalizeGitAction({action:e,filePath:t=null,preferredScope:n=null,result:r={},showLocalFileToast:i=!1}={}){let a=In(r.workspaceChange);return await this.refreshWorkspaceAfterGitAction({filePath:t,preferredScope:n}),this.handleWorkspaceChangeForCurrentFile(a,{action:e,local:!0,showToast:i}),a},handleWorkspaceChangeForCurrentFile(e,{action:t=`git`,local:n=!1,showToast:r=!0}={}){let i=this.currentFilePath;if(!i)return!1;let a=e.deletedPaths.includes(i),o=e.renamedPaths.find(e=>e.oldPath===i);if(!a&&!o)return!1;if(!r)return o?this.navigation.navigateToFile(o.newPath):this.navigation.navigateToFile(null),!0;let s=this.getDisplayName(i);return o?(this.navigation.navigateToFile(o.newPath),this.toastController.show(n?`${s} moved to ${this.getDisplayName(o.newPath)}`:`${s} moved on disk`),!0):(this.navigation.navigateToFile(null),this.toastController.show(n?`${s} was removed by ${t}`:`${s} was removed after a ${t} operation`),!0)},async handleIncomingWorkspaceEvent(e){if(!this.isTabActive||!e)return;if(e.requestId&&this.pendingWorkspaceRequestIds?.has(e.requestId)){this.pendingWorkspaceRequestIds.delete(e.requestId);return}let t=In(e.workspaceChange);e.origin===`git`&&await this.refreshGitAfterAction(),this.handleWorkspaceChangeForCurrentFile(t,{action:e.action||e.origin||`workspace`,local:!1,showToast:!0});let n=[...t.changedPaths,...t.deletedPaths,...t.renamedPaths.flatMap(e=>[e.oldPath,e.newPath])].some(e=>/(?:\.dsl$|(?:^|\/)workspace\.json$)/iu.test(e));if(this.currentFilePath&&this.isStructurizrWorkspaceFile?.(this.currentFilePath)&&n&&this.structurizrPreview?.queueSync({filePath:this.currentFilePath,source:this.session?.getText?.()??``}),e.origin===`filesystem`&&this.currentFilePath&&t.changedPaths.includes(this.currentFilePath)){let n=t.changedPaths.length===1&&Array.isArray(e.highlightRanges)?e.highlightRanges.find(e=>e.path===this.currentFilePath):null;n&&this.session?.flashExternalUpdate?.(n)||this.toastController.show(`${this.getDisplayName(this.currentFilePath)} updated from disk`)}this.currentFilePath&&Array.isArray(e.reloadRequiredPaths)&&e.reloadRequiredPaths.includes(this.currentFilePath)&&this.toastController.show(`${this.getDisplayName(this.currentFilePath)} needs a manual reload`)},async stageGitFile(e,{scope:t=`working-tree`}={}){e&&await this.runGitActionWithStatus(`Staging changes...`,async()=>{let n=await this.postGitAction(`stage`,{path:e});await this.finalizeGitAction({action:`stage`,filePath:e,preferredScope:t===`all`?`all`:`staged`,result:n})})},async unstageGitFile(e,{scope:t=`staged`}={}){e&&await this.runGitActionWithStatus(`Unstaging changes...`,async()=>{let n=await this.postGitAction(`unstage`,{path:e});await this.finalizeGitAction({action:`unstage`,filePath:e,preferredScope:t===`all`?`all`:`working-tree`,result:n})})},async pushGitBranch(){await this.runGitActionWithStatus(`Pushing branch...`,async()=>{try{let e=await this.postGitAction(`push`,{});await this.finalizeGitAction({action:`push`,result:e})}catch(e){this.toastController.show(e.message||`Failed to push branch`)}})},async pullGitBranch(){await this.runGitActionWithStatus(`Pulling branch...`,async()=>{try{let e=await this.postGitAction(`pull`,{});await this.finalizeGitAction({action:`pull`,result:e,showLocalFileToast:!0}),e.pullBackup&&this.toastController.show(this.formatPullBackupToast(e.pullBackup),5e3)}catch(e){if(e?.code===`pull_conflicted_commits`){this.toastController.show(`Cannot pull automatically because local and remote commits conflict.`,5e3);return}if(e?.code===`pull_conflicted_after_autostash`){this.toastController.show(`Pull updated the branch, but reapplying local changes caused conflicts. Review the conflicted files and the pull backup summary.`,6e3);return}this.toastController.show(e.message||`Failed to pull branch`)}})},openGitResetDialog(e){if(!this.isTabActive||!e)return;let t=this.elements.gitResetDialog;!t||!this.elements.gitResetFileName||(this.pendingGitResetPath=e,this.elements.gitResetTitle&&(this.elements.gitResetTitle.textContent=`Reset file to current branch`),this.elements.gitResetCopy&&(this.elements.gitResetCopy.textContent=`Restore this file from the current checked-out branch. If this branch does not contain the file, the file will be deleted locally.`),this.elements.gitResetFileName.value=e,this.elements.gitResetSubmit&&(this.elements.gitResetSubmit.textContent=`Reset File`),this.elements.gitResetSubmit?.toggleAttribute(`disabled`,!1),!t.open&&(typeof t.showModal==`function`?t.showModal():t.setAttribute(`open`,`true`)))},async handleGitResetSubmit(){let e=this.pendingGitResetPath,t=this.elements.gitResetDialog,n=this.elements.gitResetSubmit;if(!(!e||!t)){n?.toggleAttribute(`disabled`,!0),n&&(n.textContent=`Resetting...`);try{await this.runGitActionWithStatus(`Resetting file...`,async()=>{let t=await this.postGitAction(`reset-file`,{path:e});await this.finalizeGitAction({action:`reset`,filePath:e,result:t,showLocalFileToast:!0})}),t.close()}catch(e){this.toastController.show(e.message||`Failed to reset file`)}finally{n&&(n.textContent=`Reset File`),n?.toggleAttribute(`disabled`,!1)}}},openGitCommitDialog(){if(!this.isTabActive)return;let e=this.elements.gitCommitDialog,t=this.elements.gitCommitInput;if(!(!e||!t)){if(this.elements.gitCommitTitle&&(this.elements.gitCommitTitle.textContent=`Commit staged changes`),this.elements.gitCommitCopy){let e=Number(this.gitPanel.status?.summary?.staged||0);this.elements.gitCommitCopy.textContent=e>0?`${e} staged file${e===1?``:`s`} will be included.`:`All staged changes will be included.`}this.elements.gitCommitSubmit&&(this.elements.gitCommitSubmit.textContent=`Commit staged changes`),t.value=``,!e.open&&(typeof e.showModal==`function`?e.showModal():e.setAttribute(`open`,`true`),requestAnimationFrame(()=>{t.focus(),t.select()}))}},async handleGitCommitSubmit(){let e=this.elements.gitCommitDialog,t=this.elements.gitCommitInput,n=this.elements.gitCommitSubmit,r=String(t?.value??``).trim();if(!(!e||!t)){if(!r){t.focus(),this.toastController.show(`Commit message cannot be empty`);return}n?.toggleAttribute(`disabled`,!0),n&&(n.textContent=`Committing...`);try{await this.runGitActionWithStatus(`Committing changes...`,async()=>{let e=await this.postGitAction(`commit`,{message:r});await this.finalizeGitAction({action:`commit`,result:e})}),e.close()}catch(e){this.toastController.show(e.message||`Failed to commit staged changes`)}finally{n&&(n.textContent=`Commit staged changes`),n?.toggleAttribute(`disabled`,!1)}}}},zn=5;function Bn(e,t){return String(e?.name??``).localeCompare(String(t?.name??``),void 0,{sensitivity:`base`})}function Vn(e){let t=!!e.session,n=!!(e.currentFilePath&&e.isDrawioFile?.(e.currentFilePath)),r=!!(e.currentFilePath&&e.isExcalidrawFile?.(e.currentFilePath)),i=!!(e.currentFilePath&&e.isImageFile?.(e.currentFilePath)),a=!!(e.currentFilePath&&e.isPdfFile?.(e.currentFilePath));return!t&&(!e.currentFilePath||n||r||i||a)?e.lobby?.getConnectionState?.()??e.connectionState:e.connectionState}function Hn(e,t){let n=[...e],r=n.findIndex(e=>e.isLocal);if(r>0){let[e]=n.splice(r,1);n.unshift(e)}let i=n.findIndex(e=>!e.isLocal&&e.clientId===t),a=+!!n[0]?.isLocal;if(i>a){let[e]=n.splice(i,1);n.splice(a,0,e)}return n}function Un(e,t){let n=e.filter(e=>e.isLocal).sort(Bn),r=e.filter(e=>!e.isLocal),i=r.filter(e=>e.clientId===t).sort(Bn),a=r.filter(e=>e.clientId!==t).sort(Bn);return[...n,...i,...a]}function Wn(e,t){return t.currentFile&&t.currentFile===e.currentFilePath?`Here`:t.currentFile?e.getDisplayName(t.currentFile):`No file`}var Gn={updateGlobalUsers(e){this.globalUsers=e,this.syncFollowedUser(),this.renderAvatars(),this.renderChat({messagesChanged:!1}),this.renderPresence(),this.syncCurrentUserName()},updateFileAwareness(e){this.syncFollowedUser()},renderPresence(){let e=this.elements.userCount;if(!e)return;let t=Vn(this),n=this.globalUsers.length>0;if(t.status!==`connected`&&(this.presencePanelOpen=!1),e.type=`button`,e.setAttribute(`aria-controls`,`presencePanel`),e.setAttribute(`aria-expanded`,String(this.presencePanelOpen)),e.classList.toggle(`is-active`,this.presencePanelOpen),t.status===`connected`){e.textContent=`${this.globalUsers.length} online`,e.style.opacity=`1`,e.disabled=!n,e.setAttribute(`aria-label`,`Show ${this.globalUsers.length} online users`),this.renderPresencePanel();return}if(t.status===`connecting`){e.textContent=t.unreachable?`Unreachable`:`Connecting...`,e.style.opacity=`0.6`,e.disabled=!0,e.setAttribute(`aria-label`,e.textContent),this.renderPresencePanel();return}e.textContent=`Offline`,e.style.opacity=`0.6`,e.disabled=!0,e.setAttribute(`aria-label`,`Offline`),this.renderPresencePanel()},renderAvatars(){let e=this.elements.userAvatars;if(!e)return;e.replaceChildren();let t=Hn(this.globalUsers,this.followedUserClientId);if(t.slice(0,zn).forEach(t=>{let n=document.createElement(t.isLocal?`div`:`button`);n.className=`user-avatar`,n.classList.toggle(`is-local`,t.isLocal),n.style.backgroundColor=t.color,n.style.color=Te(t.color),n.classList.toggle(`is-following`,t.clientId===this.followedUserClientId);let r=document.createElement(`span`);r.className=`user-avatar-initial`,r.textContent=t.name.charAt(0).toUpperCase(),n.appendChild(r);let i=t.currentFile&&t.currentFile===this.currentFilePath,a=t.currentFile?this.getDisplayName(t.currentFile):`No file`;if(t.isLocal){let e=document.createElement(`span`);e.className=`user-avatar-self-label`,e.textContent=`You`,n.appendChild(e),n.title=`${t.name} (you) — ${a}`,n.setAttribute(`role`,`img`),n.setAttribute(`aria-label`,`${t.name} (you) — ${a}`)}else{n.type=`button`,n.classList.add(`user-avatar-button`),i||n.classList.add(`different-file`);let e=t.clientId===this.followedUserClientId?`Stop following ${t.name}`:i?`Follow ${t.name}`:`Follow ${t.name} — ${a}`;n.title=e,n.setAttribute(`aria-label`,e),n.addEventListener(`click`,()=>this.toggleFollowUser(t.clientId))}e.appendChild(n)}),t.length>zn){let n=document.createElement(`button`);n.type=`button`,n.className=`user-avatar user-avatar-button user-avatar-overflow-trigger`,n.style.backgroundColor=`var(--color-surface-dynamic)`,n.style.color=`var(--color-text-muted)`,n.setAttribute(`aria-controls`,`presencePanel`),n.setAttribute(`aria-expanded`,String(this.presencePanelOpen)),n.setAttribute(`aria-label`,`Show ${t.length} online users`),n.setAttribute(`data-presence-panel-trigger`,`true`),n.title=`Show ${t.length} online users`,n.addEventListener(`click`,()=>this.openPresencePanel());let r=document.createElement(`span`);r.className=`user-avatar-initial`,r.textContent=`+${t.length-zn}`,n.appendChild(r),e.appendChild(n)}},openPresencePanel(){Vn(this).status===`connected`&&this.globalUsers.length!==0&&(this.presencePanelOpen=!0,this.closeChatPanel?.(),this.closeToolbarOverflowMenu?.(),this.renderAvatars(),this.renderPresence())},closePresencePanel(){this.presencePanelOpen&&(this.presencePanelOpen=!1,this.renderAvatars(),this.renderPresence())},togglePresencePanel(){if(this.presencePanelOpen){this.closePresencePanel();return}this.openPresencePanel()},renderPresencePanel(){let e=this.elements.presencePanel,t=this.elements.presencePanelList,n=this.elements.presencePanelStatus;if(!e||!t||(e.classList.toggle(`hidden`,!this.presencePanelOpen),e.setAttribute(`aria-hidden`,String(!this.presencePanelOpen)),!this.presencePanelOpen))return;let r=Un(this.globalUsers,this.followedUserClientId),i=Vn(this);if(n){if(i.status===`connected`){let e=this.globalUsers.filter(e=>!e.isLocal).length;n.textContent=e===0?`You’re the only person here right now.`:`${e} ${e===1?`teammate`:`teammates`} online. Select someone to follow.`}else n.textContent=i.status===`connecting`?i.unreachable?`Server unreachable.`:`Connecting presence...`:`Presence is offline.`}if(t.replaceChildren(),r.length===0){let e=document.createElement(`div`);e.className=`presence-panel-empty-state`,e.textContent=i.status===`connected`?`Nobody else is here yet.`:`Presence will appear here when the connection is active.`,t.appendChild(e);return}let a=document.createDocumentFragment();r.forEach(e=>{let t=document.createElement(`article`);t.className=`presence-panel-user`,t.classList.toggle(`is-local`,e.isLocal),t.classList.toggle(`is-following`,e.clientId===this.followedUserClientId);let n=document.createElement(e.isLocal?`div`:`button`);n.className=`presence-panel-user-button`;let r=document.createElement(`span`);r.className=`presence-panel-user-avatar`,r.style.backgroundColor=e.color,r.style.color=Te(e.color),r.textContent=e.name.charAt(0).toUpperCase(),r.setAttribute(`aria-hidden`,`true`);let i=document.createElement(`span`);i.className=`presence-panel-user-body`;let o=document.createElement(`span`);o.className=`presence-panel-user-topline`;let s=document.createElement(`span`);if(s.className=`presence-panel-user-name`,s.textContent=e.name,o.appendChild(s),e.isLocal){let e=document.createElement(`span`);e.className=`presence-panel-user-badge`,e.textContent=`You`,o.appendChild(e)}else if(e.clientId===this.followedUserClientId){let e=document.createElement(`span`);e.className=`presence-panel-user-badge`,e.textContent=`Following`,o.appendChild(e)}let c=document.createElement(`span`);if(c.className=`presence-panel-user-file`,c.textContent=Wn(this,e),i.append(o,c),n.append(r,i),e.isLocal)n.setAttribute(`role`,`group`),n.setAttribute(`aria-label`,`${e.name} (you) — ${c.textContent}`);else{let t=e.clientId===this.followedUserClientId;n.type=`button`,n.setAttribute(`aria-label`,t?`Keep following ${e.name}`:`Follow ${e.name} — ${c.textContent}`),n.addEventListener(`click`,()=>{this.startFollowingUser(e.clientId,{closePanel:!0})})}if(t.appendChild(n),!e.isLocal&&e.clientId===this.followedUserClientId){let n=document.createElement(`button`);n.type=`button`,n.className=`presence-panel-user-stop`,n.textContent=`Stop`,n.setAttribute(`aria-label`,`Stop following ${e.name}`),n.addEventListener(`click`,e=>{e.stopPropagation(),this.stopFollowingUser({closePanel:!0})}),t.appendChild(n)}a.appendChild(t)}),t.appendChild(a)},startFollowingUser(e,{closePanel:t=!1}={}){if(!e)return;let n=this.globalUsers.find(t=>t.clientId===e&&!t.isLocal);if(n){if(this.followedUserClientId=e,this.followedCursorSignature=``,t&&this.presencePanelOpen?this.closePresencePanel():(this.renderAvatars(),this.renderPresencePanel()),n.currentFile&&n.currentFile!==this.currentFilePath){this.navigation.navigateToFile(n.currentFile,{preserveFollow:!0});return}requestAnimationFrame(()=>{this.followedUserClientId===e&&this.followUserCursor(n,{force:!0})})}},toggleFollowUser(e){if(e){if(this.followedUserClientId===e){this.stopFollowingUser();return}this.startFollowingUser(e)}},stopFollowingUser({closePanel:e=!1}={}){this.followedUserClientId&&(this.currentFilePath&&this.isExcalidrawFile?.(this.currentFilePath)&&this.excalidrawEmbed?.setFollowedUser(this.currentFilePath,null),this.followedUserClientId=null,this.followedCursorSignature=``,e&&this.presencePanelOpen?this.closePresencePanel():(this.renderAvatars(),this.renderPresencePanel()))},syncFollowedUser(){if(!this.followedUserClientId)return;let e=this.globalUsers.find(e=>e.clientId===this.followedUserClientId);if(!e||e.isLocal){this.stopFollowingUser();return}if(e.currentFile&&e.currentFile!==this.currentFilePath){this.navigation.navigateToFile(e.currentFile,{preserveFollow:!0});return}this.followUserCursor(e)},followUserCursor(e,{force:t=!1}={}){if(this.currentFilePath&&this.isExcalidrawFile?.(this.currentFilePath)){this.followExcalidrawUser(e,{force:t});return}let n=this.resolveFileClientId(e.peerId),r=n==null?null:this.session?.getUserViewport(n),i=n==null?null:this.session?.getUserCursor(n),a=i?.cursorHead??null,o=i?.cursorLine??null,s=i?.cursorAnchor??null,c=r?.topLine??null,l=r?.viewportRatio??.35;if(!e||c==null&&(a==null||o==null)){this.followedCursorSignature=``;return}let u=`${e.clientId}:${c??`no-viewport`}:${s??`no-anchor`}:${a??`no-head`}`;!t&&u===this.followedCursorSignature||(n!=null&&this.session?.scrollToUserViewport(n)||n!=null&&this.session?.scrollToUserCursor(n,`center`)||a!=null&&this.session?.scrollToPosition(a,`center`)||o!=null&&this.session?.scrollToLine(o,l))&&(this.followedCursorSignature=u)},followExcalidrawUser(e,{force:t=!1}={}){if(!e?.peerId||!this.currentFilePath){this.followedCursorSignature=``;return}let n=`excalidraw:${this.currentFilePath}:${e.peerId}`;!t&&n===this.followedCursorSignature||Promise.resolve(this.excalidrawEmbed?.setFollowedUser(this.currentFilePath,e.peerId)).then(t=>{t!==!1&&this.followedUserClientId===e.clientId&&(this.followedCursorSignature=n)}).catch(()=>{})},resolveFileClientId(e){if(!e||!this.session?.awareness)return null;for(let[t,n]of this.session.awareness.getStates())if(n.user?.peerId===e)return t;return null}};function Kn(){return this.runtimeConfig?.auth?.strategy===`oidc`&&this.runtimeConfig?.auth?.provider===`google`}function qn({mode:e=`edit`}={}){if(this.isIdentityManagedByAuth()||!this.isTabActive)return;let t=this.elements.displayNameDialog,n=this.elements.displayNameInput,r=this.elements.displayNameTitle,i=this.elements.displayNameCopy,a=this.elements.displayNameCancel,o=this.elements.displayNameSubmit;if(!t||!n)return;let s=e===`onboarding`;r&&(r.textContent=s?`Choose your display name`:`Update display name`),i&&(i.textContent=s?`Pick a name collaborators will see. You can skip for now and continue as a guest.`:`Your name will be visible to everyone editing this vault.`),a&&(a.textContent=s?`Skip for now`:`Cancel`),o&&(o.textContent=s?`Continue`:`Save name`),n.value=s?``:this.getCurrentUserName(),!t.open&&(typeof t.showModal==`function`?t.showModal():t.setAttribute(`open`,`true`),requestAnimationFrame(()=>{n.focus(),n.select()}))}function Jn(){!this.isTabActive||this._hasPromptedForDisplayName||this.getStoredUserName()||this.isIdentityManagedByAuth()||(this._hasPromptedForDisplayName=!0,requestAnimationFrame(()=>{this.openDisplayNameDialog({mode:`onboarding`})}))}function Yn(){if(this.isIdentityManagedByAuth())return;let e=this.elements.displayNameInput,t=this.elements.displayNameDialog;if(!e||!t)return;let n=this.session?this.session.setUserName(e.value):Ee(e.value);if(!n){e.focus(),this.toastController.show(`Name must be 1-24 characters`);return}this.preferences.setUserName(n),this.lobby.setUserName(n);let r=this.lobby.getLocalUser();this.drawioEmbed?.updateLocalUser(r),this.excalidrawEmbed?.updateLocalUser(r),this.syncCurrentUserName(),this.renderChat(),t.close()}function Xn(){return this.globalUsers.find(e=>e.isLocal)??this.session?.getLocalUser()??this.lobby?.getLocalUser()??null}function Zn(){return this.getCurrentUser()?.name??this.getStoredUserName()??``}function Qn(){return this.preferences.getUserName()}function $n(){let e=this.elements.currentUserName;if(!e)return;let t=this.getCurrentUserName();e.textContent=t||`Set name`,e.classList.toggle(`has-name`,!!t),this.isIdentityManagedByAuth()||this.elements.editNameButton?.setAttribute(`aria-label`,`${t||`Set name`}. Change display name`)}function er(){let e=this.isIdentityManagedByAuth();this.elements.editNameButton?.classList.toggle(`hidden`,e),this.elements.editNameButton?.toggleAttribute(`disabled`,e),e&&this.elements.displayNameDialog?.open&&this.elements.displayNameDialog.close()}var tr={getCurrentUser:Xn,getCurrentUserName:Zn,getStoredUserName:Qn,handleDisplayNameSubmit:Yn,isIdentityManagedByAuth:Kn,openDisplayNameDialog:qn,promptForDisplayNameIfNeeded:Jn,syncCurrentUserName:$n,syncIdentityManagementUi:er},nr=0,rr=2e3,ir=8,ar=`
42
- <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true" focusable="false">
43
- <rect x="8" y="8" width="11" height="11" rx="2" fill="none" stroke="currentColor" stroke-width="2"/>
44
- <path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
45
- </svg>
46
- `,or=`
47
- <svg viewBox="0 0 24 24" width="15" height="15" aria-hidden="true" focusable="false">
48
- <path d="M10 13.5 14 9.5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
49
- <path d="M9.35 7.55 10.6 6.3a4.2 4.2 0 0 1 5.95 5.95l-1.25 1.25" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
50
- <path d="m14.65 16.45-1.25 1.25a4.2 4.2 0 0 1-5.95-5.95L8.7 10.5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
51
- </svg>
52
- `;function sr(){this.initializeExportBridge?.(),this.renderMarkdownToolbar?.(),this.initializeVisualViewportBinding?.(),this.themeController.initialize(),this.previewRenderer.applyTheme(this.themeController.getTheme()),this.previewRenderer.scheduleWorkerPrewarm(),this.scheduleEditorSessionPrewarm?.(),this.outlineController.initialize(),this.layoutController.initialize(),this.scrollSyncController.initialize(),this.fileExplorer.initialize(),this.gitPanel.initialize(),this.gitDiffView.initialize(),this.fileHistoryView.initialize(),this.commentsOverview?.initialize?.(),this.initializePreviewLayoutObserver(),this.syncIdentityManagementUi(),this.syncCurrentUserName(),this.syncWrapToggle(),this.syncVimModeToggle(),this.syncToolbarOverflowVisibility?.(),this.syncFileHistoryButton({mode:`empty`}),this.renderChat(),this.elements.chatInput?.setAttribute(`maxlength`,String(this.lobbyChatMessageMaxLength)),this.bindEvents(),this.initializeSidebarResizer?.(),this.restoreSidebarState(),this.initializeVersionMonitoring(),this.tabActivityLock.initialize(),this.tabActivityLock.tryActivate(),window.addEventListener(`hashchange`,()=>this.workspaceRouteController.handleHashChange());let e=this.createResizeHandler();window.addEventListener(`resize`,()=>{e(),this.syncToolbarOverflowVisibility?.()}),this.fileExplorerReadyPromise=this.fileExplorer.refresh().then(()=>{if(this.fileExplorerReady=!0,this.commentsOverview?.refresh?.(),this.runtimeConfig?.gitEnabled!==!1&&this.gitPanel.refresh({force:!0}),this.isTabActive)return this.workspaceRouteController.handleHashChange()})}function cr(){this.versionMonitor?.start()}function lr(){let e=document.documentElement,t=window.visualViewport;if(e){if(!t){e.style.setProperty(`--app-viewport-height`,`100dvh`),e.style.setProperty(`--app-viewport-offset-top`,`0px`);return}e.style.setProperty(`--app-viewport-height`,`${Math.round(t.height)}px`),e.style.setProperty(`--app-viewport-offset-top`,`${Math.round(t.offsetTop)}px`)}}function ur(){this.syncVisualViewportBounds?.();let e=window.visualViewport;if(!e)return;let t=()=>this.syncVisualViewportBounds?.();e.addEventListener(`resize`,t,{passive:!0}),e.addEventListener(`scroll`,t,{passive:!0}),window.addEventListener(`orientationchange`,t)}function dr(e=null){if(this._reloadPromptShown)return;this._reloadPromptShown=!0;let t=String(e?.build?.packageVersion??this.runtimeConfig?.build?.packageVersion??``).trim(),n=t?`Version ${t} is available. Reload to update.`:`A new version is available. Reload to update.`;this.toastController.show(n,{actionLabel:`Reload`,dismissible:!0,duration:nr,onAction:()=>window.location.reload()})}function fr(){let e=()=>{this.toggleQuickSwitcher(),this.closeToolbarOverflowMenu?.()};this.elements.shareButton?.addEventListener(`click`,()=>{this.copyCurrentLink(),this.closeToolbarOverflowMenu?.()}),this.elements.toolbarSearchButton?.addEventListener(`click`,e),this.elements.searchFilesButton?.addEventListener(`click`,e),this.elements.exportHtmlButton?.addEventListener(`click`,()=>{this.handleExportRequest?.(`html`),this.closeToolbarOverflowMenu?.()}),this.elements.exportDocxButton?.addEventListener(`click`,()=>{this.handleExportRequest?.(`docx`),this.closeToolbarOverflowMenu?.()}),this.elements.exportPdfButton?.addEventListener(`click`,()=>{this.handleExportRequest?.(`pdf`),this.closeToolbarOverflowMenu?.()}),this.elements.fileHistoryButton?.addEventListener(`click`,()=>{let e=this.navigation.getHashRoute();if(e.type===`git-file-preview`){this.handleGitFileHistorySelection(e.currentFilePath??e.filePath,{closeSidebarOnMobile:!0}),this.closeToolbarOverflowMenu?.();return}this.handleGitFileHistorySelection(this.currentFilePath,{closeSidebarOnMobile:!0}),this.closeToolbarOverflowMenu?.()}),this.elements.editNameButton?.addEventListener(`click`,()=>{this.openDisplayNameDialog(),this.closeToolbarOverflowMenu?.()})}function pr(){this.elements.displayNameCancel?.addEventListener(`click`,()=>{this.elements.displayNameDialog?.close()}),this.elements.gitCommitCancel?.addEventListener(`click`,()=>{this.elements.gitCommitDialog?.close()}),this.elements.gitResetCancel?.addEventListener(`click`,()=>{this.elements.gitResetDialog?.close()}),this.elements.gitResetSubmit?.addEventListener(`click`,()=>{this.handleGitResetSubmit()}),this.elements.gitCommitDialog?.addEventListener(`close`,()=>{this.elements.gitCommitInput&&(this.elements.gitCommitInput.value=``),this.elements.gitCommitSubmit&&(this.elements.gitCommitSubmit.textContent=`Commit staged changes`)}),this.elements.gitResetDialog?.addEventListener(`close`,()=>{this.pendingGitResetPath=null,this.elements.gitResetFileName&&(this.elements.gitResetFileName.value=``),this.elements.gitResetSubmit&&(this.elements.gitResetSubmit.textContent=`Reset File`)}),this.elements.displayNameForm?.addEventListener(`submit`,e=>{e.preventDefault(),this.handleDisplayNameSubmit()}),this.elements.gitCommitForm?.addEventListener(`submit`,e=>{e.preventDefault(),this.handleGitCommitSubmit()})}function mr(){let e=()=>this.stopFollowingUser?.();this.elements.editorContainer?.addEventListener(`pointerdown`,e),this.elements.editorContainer?.addEventListener(`keydown`,e),this.elements.editorContainer?.addEventListener(`wheel`,e,{passive:!0}),this.elements.previewContainer?.addEventListener(`pointerdown`,e),this.elements.previewContainer?.addEventListener(`wheel`,e,{passive:!0}),this.elements.emptyStateNewFileBtn?.addEventListener(`click`,()=>{this.fileExplorer.actionController.openRootCreateMenu({anchor:this.elements.emptyStateNewFileBtn})}),this.elements.emptyStateSearchBtn?.addEventListener(`click`,()=>{this.toggleQuickSwitcher()}),this.elements.chatToggleButton?.addEventListener(`click`,()=>{this.closePresencePanel?.(),this.toggleChatPanel(),this.closeToolbarOverflowMenu?.()}),this.elements.chatNotificationButton?.addEventListener(`click`,()=>{this.handleChatNotificationToggle()}),this.elements.chatNotificationMuteButton?.addEventListener(`click`,()=>{this.toggleChatNotificationMute()}),this.elements.chatCloseButton?.addEventListener(`click`,()=>{this.closeChatPanel({restoreFocus:!0})}),this.elements.chatForm?.addEventListener(`submit`,e=>{e.preventDefault(),this.handleChatSubmit()}),fr.call(this),pr.call(this),this.elements.markdownToolbar?.addEventListener(`click`,e=>{this.handleMarkdownToolbarClick?.(e)}),this.elements.markdownToolbar?.addEventListener(`keydown`,e=>{this.handleMarkdownToolbarKeydown?.(e)}),this.elements.tabLockTakeoverButton?.addEventListener(`click`,()=>{this.handleTabTakeover()}),this.elements.toggleWrapButton?.addEventListener(`click`,()=>{this.toggleLineWrapping()}),this.elements.toggleVimModeButton?.addEventListener(`click`,()=>{this.toggleVimMode()}),this.elements.userCount?.addEventListener(`click`,e=>{e.preventDefault(),this.togglePresencePanel?.()}),this.elements.editorFindButton?.addEventListener(`click`,()=>{this.runEditorCommand?.(`openSearch`)}),this.elements.toolbarOverflowToggle?.addEventListener(`click`,e=>{e.preventDefault(),this.closePresencePanel?.(),this.toggleToolbarOverflowMenu()}),this.elements.toolbarOverflowMenu?.addEventListener(`click`,e=>{let t=e.target instanceof Element?e.target.closest(`button`):null;t&&t!==this.elements.toggleVimModeButton&&this.closeToolbarOverflowMenu()}),this.elements.previewContent?.addEventListener(`click`,e=>{this.handlePreviewContentClick?.(e)}),this.elements.sidebarToggle?.addEventListener(`click`,()=>{this.closeToolbarOverflowMenu(),this.toggleSidebar()}),this.elements.sidebarClose?.addEventListener(`click`,()=>{this.closeSidebarOnMobile()}),this.elements.sidebarBackdrop?.addEventListener(`click`,()=>{this.closeSidebarOnMobile()}),this.elements.filesSidebarTab?.addEventListener(`click`,()=>{this.setSidebarTab(`files`)}),this.elements.gitSidebarTab?.addEventListener(`click`,()=>{this.gitRepoAvailable&&this.setSidebarTab(`git`)}),this.elements.commentsSidebarTab?.addEventListener(`click`,()=>{this.setSidebarTab(`comments`)}),document.addEventListener(`pointerdown`,e=>{this.handleDocumentPointerDown(e)}),document.addEventListener(`keydown`,e=>{this.handleDocumentKeydown(e)},{capture:!0})}function hr(e){this.handleMarkdownToolbarDocumentPointerDown?.(e);let t=e.target instanceof Element?e.target:null;this.toolbarOverflowOpen&&!this.elements.toolbarOverflowMenu?.contains(t)&&!this.elements.toolbarOverflowToggle?.contains(t)&&this.closeToolbarOverflowMenu(),this.presencePanelOpen&&!this.elements.presencePanel?.contains(t)&&!t?.closest?.(`[data-presence-panel-trigger="true"]`)&&this.closePresencePanel?.(),this.chatIsOpen&&(this.elements.chatContainer?.contains(t)||this.closeChatPanel({restoreFocus:!1}))}function gr(e){if(e.key===`Escape`&&this.stopFollowingUser?.(),e.key===`Escape`&&this.toolbarOverflowOpen){this.closeToolbarOverflowMenu();return}if(e.key===`Escape`&&this.presencePanelOpen){this.closePresencePanel?.();return}if(e.key===`Escape`&&this.chatIsOpen){this.closeChatPanel({restoreFocus:!0});return}E(e)&&(e.preventDefault(),e.stopPropagation(),this.toggleQuickSwitcher())}function _r(e,t){let n=e.closest(`ul, ol`);return n instanceof Element&&n.parentElement===t}function vr(e){return!e.closest(`input[data-task-checkbox="true"]`)&&!!e.closest(`a, button, input, select, textarea, summary, [contenteditable="true"], [role="button"], [role="link"]`)}function yr(e){let t=window.getSelection();return!!(!t?.isCollapsed&&e.contains(t.anchorNode)&&e.contains(t.focusNode))}function br(e=``){let t=String(e??``).trim();if(!t)return``;try{return decodeURIComponent(t)}catch{return t}}function xr(e,t,{behavior:n=`smooth`}={}){if(!e||!t)return;let r=e.getBoundingClientRect(),i=t.getBoundingClientRect(),a=e.scrollTop+(i.top-r.top);e.scrollTo({behavior:n,top:Math.max(a,0)})}async function Sr(e){await navigator.clipboard.writeText(e)}function Cr(e){if(!(e instanceof HTMLElement))return``;let t=e.cloneNode(!0);return t instanceof HTMLElement?(t.querySelectorAll(`.preview-heading-link-button`).forEach(e=>e.remove()),t.textContent.replace(/\s+/g,` `).trim()):e.textContent.trim()}function wr(){return globalThis.performance?.now?.()??Date.now()}function Tr(e,t,{behavior:n=`auto`}={}){if(!(e instanceof HTMLElement)||!t)return!1;if(this.outlineController?.navigateToHeading?.(e,t,{behavior:n}))return!0;let r=this.elements.previewContainer??document.getElementById(`previewContainer`);if(!r)return!1;this.scrollSyncController?.suspendSync?.(250),xr(r,e,{behavior:n});let i=Number.parseInt(e.getAttribute(`data-source-line`)||``,10);return Number.isFinite(i)&&this.session?.scrollToLine?.(i,0),!0}function Er(e){if(!this.currentFilePath||!e)return``;let t=new URL(window.location.href);return t.hash=de(this.currentFilePath,{anchor:e,drawioMode:this.currentDrawioMode??null}),t.toString()}async function Dr(e){let t=this.createPreviewHeadingLinkUrl(e);if(!t){this.toastController.show(`Failed to copy section link`);return}try{await Sr(t),this.toastController.show(`Section link copied`)}catch{this.toastController.show(`Failed to copy section link`)}}async function Or(e){let t=e?.closest(`.preview-code-block`)?.querySelector(`:scope > pre > code`);if(t instanceof HTMLElement)try{await Sr(t.textContent),this.toastController.show(`Code copied`)}catch{this.toastController.show(`Failed to copy code`)}}function kr(){this.elements.previewContent?.querySelectorAll(`pre > code`).forEach(e=>{let t=e.parentElement,n=document.createElement(`div`);n.className=`preview-code-block`,n.innerHTML=`
53
- <div class="preview-code-actions">
54
- <button type="button" class="ui-button ui-button--secondary ui-button--compact preview-code-copy-button" aria-label="Copy code" title="Copy code">
55
- ${ar}<span data-preview-code-copy-label>Copy</span>
56
- </button>
57
- </div>`,t.replaceWith(n),n.append(t)})}function Ar(){let e=this.elements.previewContent?.querySelectorAll?.(`h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]`)??[];Array.from(e).forEach(e=>{if(!(e instanceof HTMLElement)||!e.id)return;let t=Cr(e),n=e.querySelector(`:scope > .preview-heading-link-button`);n instanceof HTMLButtonElement||(n=document.createElement(`button`),n.type=`button`,n.className=`ui-icon-button preview-heading-link-button`,n.innerHTML=or,e.appendChild(n)),n.dataset.previewHeadingAnchor=e.id,n.setAttribute(`aria-label`,`Copy link to ${t}`),n.setAttribute(`title`,`Copy link to this section`)})}function jr(e,t=this.currentFilePath){let n=String(e??``).trim();return this._pendingPreviewRouteAnchor=n?{applied:!1,appliedCount:0,anchorId:n,filePath:t??this.currentFilePath??null,stabilizeUntil:wr()+rr}:null,this._pendingPreviewRouteAnchor?this.applyPendingPreviewRouteAnchor({behavior:`auto`,clearMissing:!1}):!1}function Mr({allowExpired:e=!1,behavior:t=`auto`,clearMissing:n=!1}={}){let r=this._pendingPreviewRouteAnchor;if(!r)return!1;if(!e&&r.applied&&r.stabilizeUntil<=wr())return this._pendingPreviewRouteAnchor=null,!1;if(r.filePath&&this.currentFilePath&&r.filePath!==this.currentFilePath)return!1;let i=document.getElementById(r.anchorId);return!(i instanceof HTMLElement)||!this.elements.previewContent?.contains(i)?(!r.applied&&n&&r.filePath&&r.filePath===this.currentFilePath&&(this._pendingPreviewRouteAnchor=null),!1):this.navigatePreviewHeading(i,r.anchorId,{behavior:t})?(r.applied=!0,r.appliedCount=(r.appliedCount??0)+1,r.stabilizeUntil=wr()+rr,r.appliedCount>=ir&&(this._pendingPreviewRouteAnchor=null),!0):!1}function Nr(e){if(!(e.target instanceof Element))return;let t=e.target.closest(`button.preview-code-copy-button`);if(t instanceof HTMLButtonElement){e.preventDefault(),this.copyPreviewCodeBlock(t);return}let n=e.target.closest(`button.preview-heading-link-button[data-preview-heading-anchor]`);if(n instanceof HTMLButtonElement){e.preventDefault(),this.copyPreviewHeadingLink(n.dataset.previewHeadingAnchor||``);return}let r=e.target.closest(`a.wiki-link[data-wiki-target]`);if(r){e.preventDefault(),this.wikiLinkFileController.handleWikiLinkClick(r.dataset.wikiTarget);return}let i=e.target.closest(`a[href]`),a=i?.getAttribute(`href`)?.trim()||``;if(i&&a.startsWith(`#`)&&!le(a)){if(e.preventDefault(),a===`#`||a.toLowerCase()===`#top`){this.scrollSyncController?.suspendSync?.(250),(this.elements.previewContainer??document.getElementById(`previewContainer`))?.scrollTo({top:0,behavior:`smooth`});return}let t=br(a.slice(1));if(!t)return;let n=document.getElementById(t);if(!n||!this.elements.previewContent?.contains(n))return;this.navigatePreviewHeading(n,t,{behavior:`smooth`});return}let o=e.target.closest(`.task-list-item[data-source-line]`);if(!o||_r(e.target,o)||vr(e.target)||yr(o))return;e.preventDefault();let s=Number.parseInt(o.getAttribute(`data-source-line`)||``,10);Number.isFinite(s)&&this.session?.toggleTaskListItem?.(s)}function Pr(e){this.toolbarOverflowOpen=!!e,this.elements.toolbarOverflowToggle?.setAttribute(`aria-expanded`,String(this.toolbarOverflowOpen)),this.elements.toolbarOverflowToggle?.classList.toggle(`active`,this.toolbarOverflowOpen),this.elements.toolbarOverflowToggle?.closest(`.toolbar-right`)?.classList.toggle(`is-overflow-open`,this.toolbarOverflowOpen),this.toolbarOverflowOpen||this.elements.toolbarOverflowMenu?.querySelectorAll(`details[open]`).forEach(e=>{e.removeAttribute(`open`)})}function Fr(){let e=this.elements.toolbarOverflowToggle;e&&(e.classList.remove(`hidden`),e.hidden=!1,e.setAttribute(`aria-hidden`,`false`))}function Ir(){this.setToolbarOverflowOpen(!1)}function Lr(){this.setToolbarOverflowOpen(!this.toolbarOverflowOpen)}function Rr(e){this.previewRenderer.applyTheme(e),!this.isExcalidrawFile(this.currentFilePath)&&!this.isImageFile?.(this.currentFilePath)&&!this.isPdfFile?.(this.currentFilePath)&&!this.isStructurizrWorkspaceFile?.(this.currentFilePath)&&this.previewRenderer.queueRender(),this.session?.applyTheme(e),this.excalidrawEmbed.updateTheme(e),this.drawioEmbed.updateTheme(e),this.pdfPreview?.setTheme(e)}function zr(e){this.connectionState=e,e?.firstConnection&&this.recordFileOpenMetric?.(`ws_connected`,{status:e.status}),this.renderPresence(),this.renderChat({messagesChanged:!1}),e.unreachable&&!this.connectionHelpShown&&(this.connectionHelpShown=!0,this.toastController.show(`Cannot reach server at ${e.wsBaseUrl}`,6e3))}function Br(){let e=!(this.session?.isLineWrappingEnabled()??this.getStoredLineWrapping());this.session?.setLineWrapping(e),this.preferences.setLineWrappingEnabled(e),this.syncWrapToggle(e),this.session?.requestMeasure(),this.scrollSyncController.syncPreviewToEditor()}function Vr(){return this.preferences.getLineWrappingEnabled()}function Hr(){let e=!(this.session?.isVimModeEnabled?.()??this.getStoredVimMode());this.session?.setVimMode?.(e),this.preferences.setVimModeEnabled(e),this.syncVimModeToggle(e)}function Ur(){return this.preferences.getVimModeEnabled()}function Wr(e){let t=e??this.session?.isVimModeEnabled?.()??this.getStoredVimMode(),n=this.elements.vimModeToggleLabel,r=this.elements.toggleVimModeButton;n&&(n.textContent=t?`On`:`Off`),r&&(r.setAttribute(`aria-label`,`${t?`Disable`:`Enable`} Vim keybindings`),r.setAttribute(`title`,`${t?`Disable`:`Enable`} Vim keybindings`),r.setAttribute(`aria-pressed`,String(t)))}function Gr(e){let t=e??this.session?.isLineWrappingEnabled()??this.getStoredLineWrapping(),n=this.elements.wrapToggleLabel,r=this.elements.toggleWrapButton,i=t?`Wrap on`:`Wrap off`;n&&(n.textContent=i),r&&r.setAttribute(`aria-label`,`${i}. ${t?`Disable line wrap`:`Enable line wrap`}`)}function Kr(){clearTimeout(this._backlinkRefreshTimer),this._backlinkRefreshTimer=setTimeout(()=>{t(this.currentFilePath)&&this.backlinksPanel.load(this.currentFilePath)},2e3)}function qr(){this.elements.editorContainer&&(this.elements.editorContainer.classList.add(`is-loading-editor`),this.elements.editorContainer.innerHTML=`
58
- <div class="editor-loading" id="editorLoading">
59
- <div class="loading-spinner"></div>
60
- <span class="loading-text">Loading file...</span>
61
- </div>`)}function Jr(){this.elements.editorContainer&&(this.elements.editorContainer.classList.remove(`is-loading-editor`),this.elements.editorContainer.querySelector(`#editorLoading`)?.remove())}function Yr(){this.elements.editorContainer&&(this.elements.editorContainer.classList.remove(`is-loading-editor`),this.elements.editorContainer.innerHTML=`
62
- <div class="editor-loading" id="editorLoading">
63
- <span class="loading-text">Failed to load file</span>
64
- </div>`)}function Xr(){document.documentElement.removeAttribute(`data-initial-file-requested`)}var Zr={applyPendingPreviewRouteAnchor:Mr,bindEvents:mr,clearInitialFileBootstrap:Xr,closeToolbarOverflowMenu:Ir,copyPreviewCodeBlock:Or,copyPreviewHeadingLink:Dr,createPreviewHeadingLinkUrl:Er,getStoredLineWrapping:Vr,getStoredVimMode:Ur,handleConnectionChange:zr,handleDocumentKeydown:gr,handleDocumentPointerDown:hr,handlePreviewContentClick:Nr,handleThemeChange:Rr,hideEditorLoading:Jr,initialize:sr,initializeVisualViewportBinding:ur,initializeVersionMonitoring:cr,isPlainQuickSwitcherShortcut:E,navigatePreviewHeading:Tr,promptForVersionReload:dr,requestPreviewRouteAnchor:jr,scheduleBacklinkRefresh:Kr,setToolbarOverflowOpen:Pr,showEditorLoadError:Yr,showEditorLoading:qr,syncPreviewCodeCopyButtons:kr,syncPreviewHeadingLinkButtons:Ar,syncVisualViewportBounds:lr,syncToolbarOverflowVisibility:Fr,syncVimModeToggle:Wr,syncWrapToggle:Gr,toggleToolbarOverflowMenu:Lr,toggleLineWrapping:Br,toggleVimMode:Hr},Qr=260,$r=220,ei=420,ti=16;function ni(){let e=this.elements.sidebar,t=this.elements.sidebarResizer;if(!e||!t)return;let n=Qr,r=null,i=0,a=Qr,o=e=>Math.round(Math.max($r,Math.min(ei,e))),s=r=>{n=o(r),e.style.setProperty(`--sidebar-width`,`${n}px`),t.setAttribute(`aria-valuenow`,String(n))},c=t=>{(t?.pointerId==null||t.pointerId===r)&&r!==null&&(r=null,e.classList.remove(`is-resizing`),document.body.style.cursor=``,document.body.style.userSelect=``)};s(Qr),t.addEventListener(`pointerdown`,o=>{this.isMobileViewport()||e.classList.contains(`collapsed`)||(r=o.pointerId,i=o.clientX,a=e.getBoundingClientRect().width||n,e.classList.add(`is-resizing`),document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`,t.setPointerCapture?.(o.pointerId),o.preventDefault())}),t.addEventListener(`pointermove`,e=>{e.pointerId===r&&s(a+e.clientX-i)}),t.addEventListener(`pointerup`,c),t.addEventListener(`pointercancel`,c),t.addEventListener(`lostpointercapture`,c),t.addEventListener(`keydown`,t=>{if(!(this.isMobileViewport()||e.classList.contains(`collapsed`))){if(t.key===`ArrowLeft`||t.key===`ArrowRight`){t.preventDefault(),s(n+(t.key===`ArrowRight`?ti:-16));return}(t.key===`Home`||t.key===`End`)&&(t.preventDefault(),s(t.key===`Home`?$r:ei))}})}function ri(){return this.mobileBreakpointQuery.matches}function ii(){let e=this.elements.sidebar;!e||!this.isMobileViewport()||e.classList.contains(`collapsed`)||this.setSidebarVisibility(!1)}function ai(){let e=this.elements.sidebar;if(!e)return;let t=e.classList.contains(`collapsed`);this.setSidebarVisibility(t)}function oi(){if(!this.elements.sidebar)return;let e=this.isMobileViewport(),t=this.preferences.getSidebarVisible(),n=!0;t===`true`?n=!0:(t===`false`||e)&&(n=!1),this.applySidebarVisibility(n)}function si(e){this.applySidebarVisibility(e),this.preferences.setSidebarVisible(e)}function ci(e){let t=this.elements.sidebar;if(!t)return;let n=this.isMobileViewport(),r=!e,i=r&&n,a=e&&n;t.classList.toggle(`collapsed`,r),t.toggleAttribute(`hidden`,i),t.setAttribute(`aria-hidden`,r?`true`:`false`),t.inert=r;let o=this.elements.sidebarBackdrop;o?.toggleAttribute(`hidden`,!a),o?.setAttribute(`aria-hidden`,a?`false`:`true`),o&&(o.inert=!a)}function li(e){let t=e===`git`&&this.gitRepoAvailable?`git`:e===`comments`?`comments`:`files`;this.activeSidebarTab=t,this.elements.filesSidebarTab?.classList.toggle(`active`,t===`files`),this.elements.commentsSidebarTab?.classList.toggle(`active`,t===`comments`),this.elements.gitSidebarTab?.classList.toggle(`active`,t===`git`),document.getElementById(`fileTree`)?.classList.toggle(`hidden`,t!==`files`),this.elements.fileSearch?.classList.toggle(`hidden`,t!==`files`),this.elements.commentOverviewPanel?.classList.toggle(`hidden`,t!==`comments`),this.elements.gitSearch?.classList.toggle(`hidden`,t!==`git`),document.getElementById(`gitPanel`)?.classList.toggle(`active`,t===`git`),document.getElementById(`gitPanel`)?.classList.toggle(`hidden`,t!==`git`),this.gitPanel.setActive(t===`git`),t===`comments`&&this.refreshCommentOverviewForSidebarOpen?.()}var ui={applySidebarVisibility:ci,closeSidebarOnMobile:ii,initializeSidebarResizer:ni,isMobileViewport:ri,restoreSidebarState:oi,setSidebarTab:li,setSidebarVisibility:si,toggleSidebar:ai};function di(){this.tabActivityLock.tryActivate({takeover:!0})}function fi({takeover:e=!1}={}){let t=!this.isTabActive;this.isTabActive=!0,this.hideTabLockOverlay(),this.lobby.provider||this.lobby.connect(),this.workspaceSync.provider||this.workspaceSync.connect(),t&&(this.fileExplorerReady&&this.workspaceRouteController.handleHashChange(),this.promptForDisplayNameIfNeeded()),e&&this.toastController.show(`This tab is now active`)}async function pi({reason:e}={}){let t=this.isTabActive,n=this.currentFilePath,r=!!(n&&this.isExcalidrawFile?.(n));this.isTabActive=!1,this.elements.displayNameDialog?.open&&this.elements.displayNameDialog.close(),this.lobby.disconnect(),this.workspaceSync.disconnect(),this.globalUsers=[],this.chatMessages=[],this.chatMessageIds.clear(),this.chatUnreadCount=0,this.chatInitialSyncComplete=!1,this.presencePanelOpen=!1,this.followedUserClientId=null,this.followedCursorSignature=``,this.connectionState={status:`disconnected`,unreachable:!1},this.showTabLockOverlay({reason:e}),r&&await this.excalidrawEmbed.prepareFileDisconnect(n),this.showEmptyState(),this.renderChat(),t&&e===`taken-over`&&this.toastController.show(`Another tab took over this session`)}function mi({reason:e}={}){let t=this.elements.tabLockOverlay,n=this.elements.tabLockTitle,r=this.elements.tabLockCopy;t&&(n&&(n.textContent=e===`taken-over`?`This tab is no longer active`:`This vault is active in another tab`),r&&(r.textContent=e===`taken-over`?`Another tab took over the live session. This tab is now disconnected until you explicitly take over here again.`:`To avoid duplicate presence and chat, only one tab can stay connected at a time. Use the other tab, or take over the session here.`),t.classList.remove(`hidden`))}function hi(){this.elements.tabLockOverlay?.classList.add(`hidden`)}var gi={handleTabActivated:fi,handleTabBlocked:pi,handleTabTakeover:di,hideTabLockOverlay:hi,showTabLockOverlay:mi},H=Object.freeze({bold:`
65
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
66
- <path d="M7 5h6a4 4 0 0 1 0 8H7z"/>
67
- <path d="M7 13h7a4 4 0 0 1 0 8H7z"/>
68
- </svg>
69
- `,italic:`
70
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
71
- <path d="M14 4h6"/>
72
- <path d="M4 20h6"/>
73
- <path d="M14 4 10 20"/>
74
- </svg>
75
- `,strikethrough:`
76
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
77
- <path d="M6 6.5c1.4-1.2 3.2-1.9 5.4-1.9 3.1 0 5.6 1.4 5.6 3.9 0 2.1-1.7 3-4.3 3.5l-2.4.5c-2.7.5-4.3 1.6-4.3 3.6 0 2.7 2.7 4.2 6 4.2 2.1 0 4.2-.6 5.7-1.8"/>
78
- <path d="M3 12h18"/>
79
- </svg>
80
- `,link:`
81
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
82
- <path d="M10 13a5 5 0 0 0 7.54.54l2.92-2.92a5 5 0 0 0-7.07-7.07L11.5 5.4"/>
83
- <path d="M14 11a5 5 0 0 0-7.54-.54L3.54 13.38a5 5 0 1 0 7.07 7.07L12.5 18.6"/>
84
- </svg>
85
- `,image:`
86
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
87
- <rect x="3" y="5" width="18" height="14" rx="2"/>
88
- <circle cx="9" cy="10" r="1.5"/>
89
- <path d="m21 16-5.5-5.5L7 19"/>
90
- </svg>
91
- `,video:`
92
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
93
- <rect x="3" y="5" width="18" height="14" rx="2"/>
94
- <path d="m10 9 5 3-5 3z" fill="currentColor" stroke="none"/>
95
- </svg>
96
- `,table:`
97
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
98
- <rect x="3" y="5" width="18" height="14" rx="1"/>
99
- <path d="M3 10h18"/>
100
- <path d="M9 5v14"/>
101
- <path d="M15 5v14"/>
102
- </svg>
103
- `,code:`
104
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
105
- <path d="m8 9-4 3 4 3"/>
106
- <path d="m16 9 4 3-4 3"/>
107
- <path d="m13 6-2 12"/>
108
- </svg>
109
- `,horizontalRule:`
110
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
111
- <path d="M4 12h16"/>
112
- <path d="M9 8h6"/>
113
- <path d="M9 16h6"/>
114
- </svg>
115
- `,indent:`
116
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
117
- <path d="M4 6h16"/>
118
- <path d="M10 12h10"/>
119
- <path d="M10 18h10"/>
120
- <path d="m4 9 4 3-4 3"/>
121
- </svg>
122
- `,outdent:`
123
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
124
- <path d="M4 6h16"/>
125
- <path d="M10 12h10"/>
126
- <path d="M10 18h10"/>
127
- <path d="m8 9-4 3 4 3"/>
128
- </svg>
129
- `,redo:`
130
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
131
- <path d="M21 7v6h-6"/>
132
- <path d="M20 13a8 8 0 0 0-14-3"/>
133
- </svg>
134
- `,undo:`
135
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
136
- <path d="M3 7v6h6"/>
137
- <path d="M4 13a8 8 0 0 1 14-3"/>
138
- </svg>
139
- `,chevronDown:`
140
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
141
- <path d="m6 9 6 6 6-6"/>
142
- </svg>
143
- `}),_i=Object.freeze([{action:`paragraph`,label:`Paragraph`,shortLabel:`P`,title:`Paragraph`},{action:`heading-1`,label:`Heading 1`,shortLabel:`H1`,title:`Heading 1`},{action:`heading-2`,label:`Heading 2`,shortLabel:`H2`,title:`Heading 2`},{action:`heading-3`,label:`Heading 3`,shortLabel:`H3`,title:`Heading 3`},{action:`heading-4`,label:`Heading 4`,shortLabel:`H4`,title:`Heading 4`},{action:`heading-5`,label:`Heading 5`,shortLabel:`H5`,title:`Heading 5`},{action:`heading-6`,label:`Heading 6`,shortLabel:`H6`,title:`Heading 6`},{action:`quote`,label:`Quote`,shortLabel:`Quote`,title:`Block quote`},{action:`bullet-list`,label:`Bullet list`,shortLabel:`List`,title:`Bullet list`},{action:`numbered-list`,label:`Numbered list`,shortLabel:`1.`,title:`Numbered list`},{action:`task-list`,label:`Task list`,shortLabel:`Task`,title:`Task list`},{action:`code-block`,label:`Code block`,shortLabel:`Code`,title:`Code block`}]),vi=Object.freeze([{action:`bold`,label:`Bold`,title:`Bold`,icon:H.bold},{action:`italic`,label:`Italic`,title:`Italic`,icon:H.italic},{action:`strikethrough`,label:`Strikethrough`,title:`Strikethrough`,icon:H.strikethrough},{action:`code`,label:`Inline code`,title:`Inline code`,icon:H.code}]),yi=Object.freeze([{commandId:`undo`,label:`Undo`,title:`Undo`,icon:H.undo},{commandId:`redo`,label:`Redo`,title:`Redo`,icon:H.redo},{commandId:`indentMore`,label:`Indent`,title:`Indent`,icon:H.indent},{commandId:`indentLess`,label:`Outdent`,title:`Outdent`,icon:H.outdent}]),bi=Object.freeze([{action:`link`,label:`Insert link`,title:`Insert link`,icon:H.link},{action:`image`,label:`Insert image`,title:`Insert image`,icon:H.image},{action:`video`,label:`Insert video`,title:`Insert video`,icon:H.video}]),xi=Object.freeze([{action:`table`,label:`Insert table`,title:`Insert table`,icon:H.table},{action:`horizontal-rule`,label:`Insert horizontal rule`,title:`Insert horizontal rule`,icon:H.horizontalRule}]),Si=Object.freeze([{kind:`buttons`,groupLabel:`Edit`,actions:yi,mobileOnly:!0},{kind:`block-menu`,actions:_i},{kind:`buttons`,groupLabel:`Inline formatting`,actions:vi},{kind:`buttons`,groupLabel:`Media and links`,actions:bi},{kind:`buttons`,groupLabel:`Insert`,actions:xi}]),Ci=[..._i,...vi,...bi,...xi],wi=new Map(Ci.map(e=>[e.action,e]));function Ti(e){return wi.get(e)??null}function Ei(){return _i}function Di(e){return _i.some(t=>t.action===e)}function Oi(e){return Ti(e)?.shortLabel??`P`}function ki(){return H}var Ai=`image/png,image/jpeg,image/webp,image/gif,image/svg+xml`,ji=`paragraph`;function Mi(e){return e===`heading`?`heading-2`:String(e??``).trim()}function Ni(e){return e.map(e=>`<button type="button" class="ui-icon-button ui-icon-button--toolbar ui-toolbar-action" ${e.commandId?`data-editor-command="${y(e.commandId)}"`:`data-markdown-action="${y(e.action)}"`} aria-label="${y(e.label)}" title="${y(e.title)}">${e.icon}</button>`).join(``)}function Pi(e){return`
144
- <div class="markdown-toolbar-block-menu-shell">
145
- <button
146
- type="button"
147
- class="ui-button ui-button--ghost markdown-toolbar-block-trigger"
148
- data-markdown-block-menu-toggle
149
- aria-haspopup="menu"
150
- aria-expanded="false"
151
- title="Block formatting"
152
- >
153
- <span class="markdown-toolbar-block-trigger-label" data-markdown-block-trigger-label>${y(Oi(e))}</span>
154
- <span class="markdown-toolbar-block-trigger-icon" aria-hidden="true">${ki().chevronDown}</span>
155
- </button>
156
- </div>
157
- `}function Fi(e){return Ei().map(t=>{let n=t.action===e;return`
158
- <button
159
- type="button"
160
- class="markdown-toolbar-menu-item${n?` is-active`:``}"
161
- data-markdown-block-action="${y(t.action)}"
162
- role="menuitemradio"
163
- aria-checked="${n?`true`:`false`}"
164
- title="${y(t.title)}"
165
- >
166
- <span class="markdown-toolbar-menu-item-label">${y(t.label)}</span>
167
- <span class="markdown-toolbar-menu-item-shortcut">${y(t.shortLabel)}</span>
168
- </button>
169
- `}).join(``)}function Ii(e){return Si.map(t=>t.kind===`block-menu`?Pi(e):`
170
- <div class="markdown-toolbar-group${t.mobileOnly?` markdown-toolbar-group--mobile-only`:``}" role="group" aria-label="${y(t.groupLabel)}">
171
- ${Ni(t.actions)}
172
- </div>
173
- `).join(``)}function Li(){let e=Mi(this._activeMarkdownBlockAction||ji);return Di(e)?e:ji}function Ri(){let e=this.elements?.markdownToolbar;e&&(e.innerHTML=Ii(this.getActiveMarkdownBlockAction()),this.renderMarkdownBlockMenuPopover(),this.syncMarkdownToolbarBlockUi())}function zi(){return this._markdownBlockMenuPopover??null}function Bi(){let e=this.elements?.editorContainer??document.body,t=this.getMarkdownBlockMenuPopover();t?t.parentElement!==e&&e?.appendChild(t):(t=document.createElement(`div`),t.className=`markdown-toolbar-popover hidden`,t.innerHTML=`<div class="markdown-toolbar-menu" data-markdown-block-menu role="menu" aria-label="Block formatting"></div>`,t.addEventListener(`click`,e=>{this.handleMarkdownToolbarClick?.(e)}),t.addEventListener(`keydown`,e=>{this.handleMarkdownToolbarKeydown?.(e)}),e?.appendChild(t),this._markdownBlockMenuPopover=t);let n=t.querySelector(`[data-markdown-block-menu]`);n&&(n.innerHTML=Fi(this.getActiveMarkdownBlockAction()))}function Vi(){let e=this.elements?.markdownToolbar;if(!e)return;let t=this.getActiveMarkdownBlockAction(),n=Ti(t),r=e.querySelector(`[data-markdown-block-trigger-label]`);r&&(r.textContent=Oi(t));let i=e.querySelector(`[data-markdown-block-menu-toggle]`);i&&n&&(i.setAttribute(`aria-label`,`${n.label}. Block formatting`),i.setAttribute(`title`,`${n.label}. Block formatting`));let a=Array.from(this.getMarkdownBlockMenuPopover()?.querySelectorAll(`[data-markdown-block-action]`)??[]);[...e.querySelectorAll(`[data-markdown-block-action]`),...a].forEach(e=>{let n=e.getAttribute(`data-markdown-block-action`)===t;e.classList.toggle(`is-active`,n),e.setAttribute(`aria-checked`,n?`true`:`false`)})}function Hi(e){let t=Mi(e);Di(t)&&(this._activeMarkdownBlockAction=t,this.syncMarkdownToolbarBlockUi())}function Ui(){return!!this.elements?.markdownToolbar?.classList.contains(`is-menu-open`)}function Wi(){let e=this.getMarkdownBlockMenuPopover(),t=this.elements?.markdownToolbar?.querySelector(`[data-markdown-block-menu-toggle]`),n=e?.parentElement;if(!e||!t||!(n instanceof HTMLElement))return;let r=t.getBoundingClientRect(),i=n.getBoundingClientRect(),a=e.getBoundingClientRect(),o=a.width||176,s=a.height||240,c=r.left-i.left,l=Math.max(8,i.width-o-8),u=r.bottom-i.top+6,d=u+s<=i.height-8;e.style.left=`${Math.max(8,Math.min(c,l))}px`,e.style.top=`${d?u:Math.max(8,r.top-i.top-s-6)}px`}function Gi(){let e=this.elements?.markdownToolbar;e&&(this.renderMarkdownBlockMenuPopover(),e.classList.add(`is-menu-open`),this.getMarkdownBlockMenuPopover()?.classList.remove(`hidden`),e.querySelector(`[data-markdown-block-menu-toggle]`)?.setAttribute(`aria-expanded`,`true`),this.positionMarkdownBlockMenu())}function Ki(){let e=this.elements?.markdownToolbar;e&&(e.classList.remove(`is-menu-open`),this.getMarkdownBlockMenuPopover()?.classList.add(`hidden`),e.querySelector(`[data-markdown-block-menu-toggle]`)?.setAttribute(`aria-expanded`,`false`))}function qi(){if(this.isMarkdownBlockMenuOpen()){this.closeMarkdownBlockMenu();return}this.openMarkdownBlockMenu()}function Ji(e){let t=e.target instanceof Element?e.target:null;if(!t)return;let n=t.closest(`[data-editor-command]`)?.getAttribute(`data-editor-command`);if(n){e.preventDefault(),this.runEditorCommand(n);return}if(t.closest(`[data-markdown-block-menu-toggle]`)){e.preventDefault(),this.toggleMarkdownBlockMenu();return}let r=t.closest(`[data-markdown-block-action]`);if(r){e.preventDefault();let t=r.getAttribute(`data-markdown-block-action`);this.closeMarkdownBlockMenu(),t&&this.applyMarkdownToolbarAction(t);return}let i=t.closest(`[data-markdown-action]`)?.getAttribute(`data-markdown-action`);i&&this.applyMarkdownToolbarAction(i)}function Yi(e){if(!this.isMarkdownBlockMenuOpen()){e.target instanceof Element&&e.target.closest(`[data-markdown-block-menu-toggle]`)&&[`ArrowDown`,`Enter`,` `].includes(e.key)&&(e.preventDefault(),this.openMarkdownBlockMenu(),this.getMarkdownBlockMenuPopover()?.querySelector(`[data-markdown-block-action]`)?.focus());return}if(e.key===`Escape`){e.preventDefault(),this.closeMarkdownBlockMenu(),this.elements?.markdownToolbar?.querySelector(`[data-markdown-block-menu-toggle]`)?.focus();return}let t=Array.from(this.getMarkdownBlockMenuPopover()?.querySelectorAll(`[data-markdown-block-action]`)??[]);if(t.length===0)return;let n=t.findIndex(t=>t===e.target);n<0||(e.key===`ArrowDown`?(e.preventDefault(),t[(n+1)%t.length]?.focus()):e.key===`ArrowUp`&&(e.preventDefault(),t[(n-1+t.length)%t.length]?.focus()))}function Xi(e){this.isMarkdownBlockMenuOpen()&&(this.elements?.markdownToolbar?.contains(e.target)||this.getMarkdownBlockMenuPopover()?.contains(e.target)||this.closeMarkdownBlockMenu())}function Zi(e){if(!this.session||!_(this.currentFilePath))return;if(e===`image`){this.handleToolbarImageInsert();return}let t=Mi(e);if(!this.session.applyMarkdownToolbarAction(t)){this.toastController.show(`Formatting action is unavailable`);return}Di(t)&&this.setActiveMarkdownBlockAction(t)}function Qi(e){return this.session?.runEditorCommand?.(e)?!0:(this.toastController.show(`Editor action is unavailable`),!1)}async function $i(){let[e]=await xe({accept:Ai});e&&await this.handleEditorImageInsert(e)}async function ea(e){if(!this.session||!_(this.currentFilePath))return console.warn(`[ui] Ignoring image insert because there is no active markdown session.`,{currentFilePath:this.currentFilePath,hasSession:!!this.session}),!1;let t=this.currentFilePath,n=this.session;try{console.debug(`[ui] Uploading image attachment.`,{fileName:e?.name||``,size:e?.size??null,sourcePath:t,type:e?.type||``});let r=await this.vaultApiClient.uploadImageAttachment({file:e,fileName:e?.name||``,sourcePath:t});return await this.fileExplorer.refresh(),this.currentFilePath===t&&this.session&&this.session===n&&typeof r?.markdown==`string`&&(console.debug(`[ui] Inserting uploaded image markdown into the editor.`,{sourcePath:t,storedPath:r.path??``}),this.session.insertText(r.markdown)),!0}catch(e){return console.error(`[ui] Failed to insert image attachment:`,e),this.toastController.show(e.message||`Failed to upload image`),!1}}async function ta(){try{await navigator.clipboard.writeText(window.location.href),this.toastController.show(`Link copied`)}catch{this.toastController.show(`Failed to copy link`)}}var na={applyMarkdownToolbarAction:Zi,copyCurrentLink:ta,closeMarkdownBlockMenu:Ki,getActiveMarkdownBlockAction:Li,getMarkdownBlockMenuPopover:zi,handleEditorImageInsert:ea,handleMarkdownToolbarClick:Ji,handleMarkdownToolbarDocumentPointerDown:Xi,handleMarkdownToolbarKeydown:Yi,handleToolbarImageInsert:$i,isMarkdownBlockMenuOpen:Ui,openMarkdownBlockMenu:Gi,positionMarkdownBlockMenu:Wi,renderMarkdownBlockMenuPopover:Bi,renderMarkdownToolbar:Ri,runEditorCommand:Qi,setActiveMarkdownBlockAction:Hi,syncMarkdownToolbarBlockUi:Vi,toggleMarkdownBlockMenu:qi},ra={isBaseFile:n,isDrawioFile:h,isExcalidrawFile:r,isImageFile:l,isPdfFile:a,isMermaidFile:i,isPlantUmlFile:p,isStructurizrWorkspaceFile:u,getPreviewSource(){let e=this.getStaticPreviewDocument?.(),t=e?.currentFilePath??e?.filePath??null;return e&&t&&t===this.currentFilePath?this.isMermaidFile(this.currentFilePath)?this.workspacePreviewController.createDiagramPreviewDocument(`mermaid`,e.content):this.isPlantUmlFile(this.currentFilePath)?this.workspacePreviewController.createDiagramPreviewDocument(`plantuml`,e.content):String(e.content??``):this.workspacePreviewController.getPreviewSource(this.currentFilePath,{drawioMode:this.currentDrawioMode??null})},getStaticPreviewDocument(){return this._staticPreviewDocument??null},setStaticPreviewDocument(e){let t=e?.filePath??e?.path??null,n=e?.currentFilePath??t;this._staticPreviewDocument=e?{content:String(e.content??``),currentFilePath:n,fileKind:e.fileKind??m(t),filePath:t,hash:e.hash??null}:null},clearStaticPreviewDocument(){this._staticPreviewDocument=null},supportsFileHistory(e){let t=m(e);return t!==null&&t!==`image`&&t!==`pdf`},getDisplayName(e){return o(String(e??``).split(`/`).pop())},handleLayoutViewRequest(e){return!this.currentFilePath||!this.isDrawioFile(this.currentFilePath)?!0:this.currentDrawioMode===`text`?e!==`preview`||(this.layoutController.isMobileViewport?.()&&this.layoutController.primeView(e),this.navigation.navigateToFile(this.currentFilePath),!1):e===`preview`||(this.layoutController.primeView(e),this.navigation.navigateToFile(this.currentFilePath,{drawioMode:`text`}),!1)},renderBaseFilePreview(e,t){return clearTimeout(this._basePreviewRenderTimer),this._basePreviewRenderTimer=null,this.workspacePreviewController.renderBaseFilePreview(e,t)},scheduleBaseFilePreview(e,t){let n=this.sessionLoadToken;clearTimeout(this._basePreviewRenderTimer),this._basePreviewRenderTimer=setTimeout(()=>{this._basePreviewRenderTimer=null,e===this.currentFilePath&&n===this.sessionLoadToken&&this.renderBaseFilePreview(e,t)},180)},createResizeHandler(){return this.workspacePreviewController.createResizeHandler(()=>this.restoreSidebarState())},initializePreviewLayoutObserver(){this._previewLayoutResizeObserver?.disconnect(),this._previewLayoutResizeObserver=this.workspacePreviewController.initializePreviewLayoutObserver(()=>this.schedulePreviewLayoutSync())},schedulePreviewLayoutSync({delayMs:e=120}={}){this.workspacePreviewController.schedulePreviewLayoutSync({delayMs:e,hydrationPaused:this._previewHydrationPaused,previewLayoutSyncTimer:this._previewLayoutSyncTimer,setPendingPreviewLayoutSync:e=>{this._pendingPreviewLayoutSync=e},setPreviewLayoutSyncTimer:e=>{this._previewLayoutSyncTimer=e}})},handleEditorScrollActivityChange(e){this.workspacePreviewController.handleEditorScrollActivityChange({isActive:e,pendingPreviewLayoutSync:this._pendingPreviewLayoutSync,previewLayoutSyncTimer:this._previewLayoutSyncTimer,setHydrationPaused:e=>{this._previewHydrationPaused=e},setPendingPreviewLayoutSync:e=>{this._pendingPreviewLayoutSync=e},setPreviewLayoutSyncTimer:e=>{this._previewLayoutSyncTimer=e}})},showEmptyState(){clearTimeout(this._previewLayoutSyncTimer),this._previewLayoutSyncTimer=null,this._pendingPreviewLayoutSync=!1,this._previewHydrationPaused=!1,this.workspaceRouteController.showEmptyState()},showDiffState(){clearTimeout(this._previewLayoutSyncTimer),this._previewLayoutSyncTimer=null,this._pendingPreviewLayoutSync=!1,this._previewHydrationPaused=!1,this.workspaceRouteController.showDiffState()}},ia=`__lobby__`;function aa(e){return String(e??``).replace(/\s+/g,` `).trim().slice(0,280)||null}function oa(e){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${e||`user`}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function sa(e){if(!e||typeof e!=`object`||typeof e.id!=`string`)return null;let t=e.workspaceChange&&typeof e.workspaceChange==`object`?e.workspaceChange:{};return{action:typeof e.action==`string`?e.action:`git`,createdAt:Number.isFinite(e.createdAt)?e.createdAt:Date.now(),id:e.id,peerId:typeof e.peerId==`string`?e.peerId:null,sourceRef:typeof e.sourceRef==`string`?e.sourceRef:null,workspaceChange:{changedPaths:Array.isArray(t.changedPaths)?t.changedPaths.filter(Boolean):[],deletedPaths:Array.isArray(t.deletedPaths)?t.deletedPaths.filter(Boolean):[],refreshExplorer:t.refreshExplorer!==!1,renamedPaths:Array.isArray(t.renamedPaths)?t.renamedPaths.filter(e=>e?.oldPath&&e?.newPath):[]}}}var ca=class{constructor({preferredUserName:e,onChange:t,onChatChange:n,onWorkspaceEvent:r}){this.onChange=t,this.onChatChange=n,this.onWorkspaceEvent=r,this.wsBaseUrl=ce(),this.ydoc=new L,this.chatMessages=this.ydoc.getArray(`chat-messages`),this.workspaceEvents=this.ydoc.getArray(`workspace-events`),this.provider=null,this.awareness=null,this.localUser=Oe(e),this.currentFile=null,this._connected=!1,this._didInitialSync=!1,this.seenWorkspaceEventIds=new Set,this.handleAwarenessChange=()=>{this._emitChange()},this.handleChatMessagesChange=()=>{this._emitChatChange()},this.handleWorkspaceEventsChange=()=>{this._emitWorkspaceEvents()}}connect(){this.provider||(this._didInitialSync=!1,this.provider=new ve(this.wsBaseUrl,ia,this.ydoc,{disableBc:!0,maxBackoffTime:5e3}),ye(this.provider),this.awareness=this.provider.awareness,this.awareness.setLocalStateField(`user`,this.localUser),this.awareness.setLocalStateField(`currentFile`,this.currentFile),this.awareness.on(`change`,this.handleAwarenessChange),this.chatMessages.observe(this.handleChatMessagesChange),this.workspaceEvents.observe(this.handleWorkspaceEventsChange),this.provider.on(`status`,({status:e})=>{this._connected=e===`connected`,this._emitChange()}),this.provider.on(`sync`,e=>{!e||this._didInitialSync||(this._didInitialSync=!0,this._primeWorkspaceEventCache(),this._emitChange(),this._emitChatChange({initial:!0}))}))}setCurrentFile(e){this.currentFile=e,this.awareness&&this.awareness.setLocalStateField(`currentFile`,e)}setUserName(e){e&&(this.localUser={...this.localUser,name:e},this.awareness&&this.awareness.setLocalStateField(`user`,this.localUser))}getLocalUser(){return this.localUser}sendChatMessage(e){let t=aa(e);if(!t)return null;let n={createdAt:Date.now(),filePath:this.currentFile??null,id:oa(this.localUser.peerId),peerId:this.localUser.peerId,text:t,userColor:this.localUser.color,userName:this.localUser.name};return this.ydoc.transact(()=>{this.chatMessages.push([n]);let e=this.chatMessages.length-40;e>0&&this.chatMessages.delete(0,e)},`lobby-chat-message`),n}sendWorkspaceEvent({action:e=`git`,sourceRef:t=null,workspaceChange:n={}}={}){let r=sa({action:e,createdAt:Date.now(),id:oa(this.localUser.peerId),peerId:this.localUser.peerId,sourceRef:t,workspaceChange:n});return r?(this.ydoc.transact(()=>{this.workspaceEvents.push([r]);let e=this.workspaceEvents.length-40;e>0&&this.workspaceEvents.delete(0,e)},`lobby-workspace-event`),this.seenWorkspaceEventIds.add(r.id),r):null}getMessages(){return this.chatMessages.toArray().filter(e=>e&&typeof e.id==`string`&&typeof e.peerId==`string`&&typeof e.text==`string`&&typeof e.userName==`string`)}getUsers(){if(!this.awareness)return[];let e=[];return this.awareness.getStates().forEach((t,n)=>{t.user&&e.push({...t.user,clientId:n,currentFile:t.currentFile??null,isLocal:n===this.awareness.clientID})}),e}getConnectionState(){return this._connected?{status:`connected`,unreachable:!1}:this.provider?{status:`connecting`,unreachable:!1}:{status:`disconnected`,unreachable:!1}}disconnect(){this.provider&&(this.awareness?.off(`change`,this.handleAwarenessChange),this.chatMessages?.unobserve(this.handleChatMessagesChange),this.workspaceEvents?.unobserve(this.handleWorkspaceEventsChange)),this.provider?.disconnect(),this.provider?.destroy(),this.provider=null,this.awareness=null,this._connected=!1,this._didInitialSync=!1,this.seenWorkspaceEventIds.clear()}destroy(){this.disconnect(),this.ydoc?.destroy(),this.ydoc=null}_emitChange(){this.onChange?.(this.getUsers())}_emitChatChange(e={}){this.onChatChange?.(this.getMessages(),e)}_primeWorkspaceEventCache(){this.workspaceEvents.toArray().forEach(e=>{let t=sa(e);t&&this.seenWorkspaceEventIds.add(t.id)})}_emitWorkspaceEvents(){if(!this._didInitialSync){this._primeWorkspaceEventCache();return}this.workspaceEvents.toArray().forEach(e=>{let t=sa(e);!t||this.seenWorkspaceEventIds.has(t.id)||(this.seenWorkspaceEventIds.add(t.id),t.peerId!==this.localUser.peerId&&this.onWorkspaceEvent?.(t))})}};function la(e,t,n){try{return e.getItem(t)??n}catch{return n}}function ua(e,t,n){try{e.setItem(t,n)}catch{}}var da=20,fa=class{constructor({fileTreeShowExtensionsKey:e,lineWrappingKey:t,recentFilesKey:n=`collabmd-recent-files`,vimModeKey:r=`collabmd-editor-vim-mode`,sidebarVisibleKey:i,userNameKey:a,storage:o=globalThis.localStorage}){this.fileTreeShowExtensionsKey=e,this.lineWrappingKey=t,this.recentFilesKey=n,this.sidebarVisibleKey=i,this.storage=o,this.userNameKey=a,this.vimModeKey=r}getUserName(){return la(this.storage,this.userNameKey,``)||``}setUserName(e){ua(this.storage,this.userNameKey,e)}getFileTreeShowExtensions(){return la(this.storage,this.fileTreeShowExtensionsKey,null)===`true`}setFileTreeShowExtensions(e){ua(this.storage,this.fileTreeShowExtensionsKey,e?`true`:`false`)}getLineWrappingEnabled(){return la(this.storage,this.lineWrappingKey,null)!==`false`}setLineWrappingEnabled(e){ua(this.storage,this.lineWrappingKey,String(e))}getVimModeEnabled(){return la(this.storage,this.vimModeKey,null)===`true`}setVimModeEnabled(e){ua(this.storage,this.vimModeKey,String(e))}getRecentFiles(){let e=la(this.storage,this.recentFilesKey,`[]`);try{let t=JSON.parse(e);return Array.isArray(t)?[...new Set(t.filter(e=>typeof e==`string`&&e))]:[]}catch{return[]}}recordRecentFile(e){if(!e)return;let t=[e,...this.getRecentFiles().filter(t=>t!==e)];ua(this.storage,this.recentFilesKey,JSON.stringify(t.slice(0,da)))}getSidebarVisible(){return la(this.storage,this.sidebarVisibleKey,null)}setSidebarVisible(e){ua(this.storage,this.sidebarVisibleKey,e?`true`:`false`)}},pa=class{getApi(){return typeof globalThis.Notification==`function`?globalThis.Notification:null}getPermission(){return this.getApi()?.permission??`unsupported`}async requestPermission(){let e=this.getApi();if(!e||typeof e.requestPermission!=`function`)return`unsupported`;if(e.permission!=="default")return e.permission;try{return await e.requestPermission()}catch{return e.permission??`default`}}show({body:e,onClick:t,tag:n,title:r}={}){let i=this.getApi();if(!i||i.permission!==`granted`||!e)return null;try{let a=new i(r,{body:e,renotify:!0,tag:n});return t&&(a.onclick=t),a}catch{return null}}},ma=6e4;function ha(e){return String(e?.build?.id??e?.buildId??``).trim()}var ga=class{constructor({currentBuildId:e=``,documentRef:t=globalThis.document??null,fetchImpl:n=globalThis.fetch?.bind(globalThis),intervalMs:r=ma,onUpdateAvailable:i=null,runtimeConfig:a={basePath:``},versionUrl:o=null,windowRef:s=globalThis.window??globalThis}={}){this.currentBuildId=String(e??``).trim(),this.documentRef=t,this.fetchImpl=n,this.intervalHandle=null,this.intervalMs=Math.max(5e3,Number(r)||ma),this.isChecking=!1,this.onUpdateAvailable=typeof i==`function`?i:null,this.runtimeConfig=a,this.updateDetected=!1,this.versionUrl=o||_e(`/version.json`,a),this.windowRef=s,this.handleFocus=()=>{this.checkNow({force:!0})},this.handleVisibilityChange=()=>{this.documentRef?.hidden||this.checkNow({force:!0})}}start(){!this.fetchImpl||this.intervalHandle||(this.documentRef?.addEventListener?.(`visibilitychange`,this.handleVisibilityChange),this.windowRef?.addEventListener?.(`focus`,this.handleFocus),this.intervalHandle=this.windowRef?.setInterval?.(()=>{this.checkNow()},this.intervalMs)??null,this.checkNow({force:!0}))}stop(){this.intervalHandle&&=(this.windowRef?.clearInterval?.(this.intervalHandle),null),this.documentRef?.removeEventListener?.(`visibilitychange`,this.handleVisibilityChange),this.windowRef?.removeEventListener?.(`focus`,this.handleFocus)}async checkNow({force:e=!1}={}){if(!this.fetchImpl||this.isChecking||this.updateDetected||!e&&this.documentRef?.hidden)return!1;this.isChecking=!0;try{let e=await this.fetchImpl(this.versionUrl,{cache:`no-store`,headers:{Accept:`application/json`}});if(!e?.ok)return!1;let t=await e.json().catch(()=>null),n=ha(t);return n?this.currentBuildId?n!==this.currentBuildId&&(this.updateDetected=!0,this.onUpdateAvailable?.(t),!0):(this.currentBuildId=n,!1):!1}catch{return!1}finally{this.isChecking=!1}}};function _a(e={}){let t=new URLSearchParams;return Object.entries(e).forEach(([e,n])=>{n!=null&&n!==``&&t.set(e,String(n))}),t}var va=new class{async readStatus({force:e=!1}={}){let t=await fetch(F(`/git/status${e?`?force=true`:``}`));return N(t,`Failed to load git status`)}async readPullBackups(){let e=await fetch(F(`/git/pull-backups`));return N(e,`Failed to load pull backups`)}async readHistory({limit:e,offset:t}={}){let n=_a({limit:e,offset:t}),r=await fetch(F(`/git/history?${n.toString()}`));return N(r,`Failed to load git history`)}async readFileHistory({path:e,limit:t,offset:n}={}){let r=_a({limit:t,offset:n,path:e}),i=await fetch(F(`/git/file-history?${r.toString()}`));return N(i,`Failed to load file history`)}async readDiff({allowLargePatch:e=!1,metaOnly:t=!1,path:n=null,scope:r=`all`}={}){let i=_a({allowLargePatch:e?`true`:null,metaOnly:t?`true`:null,path:n,scope:r}),a=await fetch(F(`/git/diff?${i.toString()}`));return N(a,`Failed to load git diff`)}async readCommit({allowLargePatch:e=!1,hash:t,metaOnly:n=!1,path:r=null}={}){let i=_a({allowLargePatch:e?`true`:null,hash:t,metaOnly:n?`true`:null,path:r}),a=await fetch(F(`/git/commit?${i.toString()}`));return N(a,`Failed to load git commit`)}async readFileSnapshot({hash:e,path:t}={}){let n=_a({hash:e,path:t}),r=await fetch(F(`/git/file-snapshot?${n.toString()}`));return N(r,`Failed to load historical file preview`)}getFileAttachmentUrl({hash:e,path:t}={}){let n=_a({hash:e,path:t});return F(`/git/file-attachment?${n.toString()}`)}async stageFile({path:e,requestId:t=null}={}){return this.#e(`/git/stage`,{path:e},{requestId:t,fallbackError:`Failed to stage file`})}async unstageFile({path:e,requestId:t=null}={}){return this.#e(`/git/unstage`,{path:e},{requestId:t,fallbackError:`Failed to unstage file`})}async pushBranch({requestId:e=null}={}){return this.#e(`/git/push`,{},{requestId:e,fallbackError:`Failed to push branch`})}async pullBranch({requestId:e=null}={}){return this.#e(`/git/pull`,{},{requestId:e,fallbackError:`Failed to pull branch`})}async resetFile({path:e,requestId:t=null}={}){return this.#e(`/git/reset-file`,{path:e},{requestId:t,fallbackError:`Failed to reset file`})}async commit({message:e,requestId:t=null}={}){return this.#e(`/git/commit`,{message:e},{requestId:t,fallbackError:`Failed to commit staged changes`})}async#e(e,t,{fallbackError:n,requestId:r=null}={}){let i=await fetch(F(e),{body:JSON.stringify(t),headers:A(r,{"Content-Type":`application/json`}),method:`POST`});return N(i,n)}},ya=`collabmd-active-tab-lock`,ba=`collabmd-tab-id`,xa=`collabmd-tab-lock`,Sa=4e3;function Ca(){return Date.now()}function wa(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`tab-${Ca()}-${Math.random().toString(36).slice(2,10)}`}function Ta(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}var Ea=class{constructor({heartbeatIntervalMs:e=Sa,onBlocked:t,onActivated:n,onStolen:r}={}){this.heartbeatIntervalMs=e,this.staleAfterMs=e*3,this.onBlocked=t,this.onActivated=n,this.onStolen=r,this.tabId=this.getOrCreateTabId(),this.channel=null,this.heartbeatTimer=null,this.isOwner=!1,this.handleStorageEvent=this.handleStorageEvent.bind(this),this.handlePageHide=this.handlePageHide.bind(this)}initialize(){window.addEventListener(`storage`,this.handleStorageEvent),window.addEventListener(`pagehide`,this.handlePageHide),`BroadcastChannel`in globalThis&&(this.channel=new BroadcastChannel(xa),this.channel.addEventListener(`message`,e=>{this.handleChannelMessage(e.data)}))}destroy(){this.release(),window.removeEventListener(`storage`,this.handleStorageEvent),window.removeEventListener(`pagehide`,this.handlePageHide),this.channel?.close(),this.channel=null}tryActivate({takeover:e=!1}={}){let t=this.readLock();return this.isFreshLock(t)&&t.tabId!==this.tabId&&!e?(this.isOwner=!1,this.stopHeartbeat(),this.onBlocked?.({reason:`active-elsewhere`,ownerTabId:t.tabId}),!1):(this.writeLock(),this.startHeartbeat(),this.isOwner=!0,this.channel?.postMessage({type:`claimed`,takeover:e,tabId:this.tabId}),this.onActivated?.({takeover:e}),!0)}release(){this.readLock()?.tabId===this.tabId&&(localStorage.removeItem(ya),this.channel?.postMessage({type:`released`,tabId:this.tabId})),this.isOwner=!1,this.stopHeartbeat()}getOrCreateTabId(){try{let e=window.sessionStorage.getItem(ba);if(e)return e;let t=wa();return window.sessionStorage.setItem(ba,t),t}catch{return wa()}}readLock(){try{return Ta(window.localStorage.getItem(ya))}catch{return null}}isFreshLock(e){return!!(e&&typeof e.tabId==`string`&&Number.isFinite(e.updatedAt)&&Ca()-e.updatedAt<this.staleAfterMs)}writeLock(){try{window.localStorage.setItem(ya,JSON.stringify({tabId:this.tabId,updatedAt:Ca()}))}catch{}}startHeartbeat(){this.stopHeartbeat(),this.writeLock(),this.heartbeatTimer=window.setInterval(()=>{if(!this.isOwner){this.stopHeartbeat();return}this.writeLock()},this.heartbeatIntervalMs)}stopHeartbeat(){this.heartbeatTimer&&=(window.clearInterval(this.heartbeatTimer),null)}handleStorageEvent(e){if(e.key!==ya)return;let t=Ta(e.newValue);this.handleExternalLockChange(t)}handleChannelMessage(e){!e||typeof e!=`object`||e.tabId===this.tabId||e.type===`claimed`&&this.handleExternalLockChange(this.readLock())}handleExternalLockChange(e){this.isOwner&&this.isFreshLock(e)&&e.tabId!==this.tabId&&(this.isOwner=!1,this.stopHeartbeat(),this.onStolen?.({ownerTabId:e.tabId}))}handlePageHide(){this.release()}},Da=`__workspace__`;function Oa(e=``){return String(e??``).trim().replace(/\\/g,`/`).split(`/`).filter(Boolean).join(`/`)}function ka(e=``){let t=Oa(e);if(!t)return``;let n=t.lastIndexOf(`/`);return n>=0?t.slice(0,n):``}function Aa(e={}){return ka(e?.path??``)}function ja(e){if(!e?.path||!e?.type)return null;if(e.nodeType===`directory`||e.type===`directory`)return{children:[],name:e.name,path:e.path,type:`directory`};let t={name:e.name,path:e.path,type:e.type},n=Number(e.mtimeMs);return Number.isFinite(n)&&(t.mtimeMs=n),t}function Ma(e=[]){return e.sort((e,t)=>e.type===`directory`&&t.type!==`directory`?-1:e.type!==`directory`&&t.type===`directory`?1:e.name.localeCompare(t.name,void 0,{sensitivity:`base`})),e.forEach(e=>{Array.isArray(e.children)&&Ma(e.children)}),e}function Na(e){return e instanceof Map?e:new Map(Object.entries(e??{}))}function Pa(e=[],t=`asc`){let n=t===`desc`?-1:1;return[...e].sort((e,t)=>{let r=e.split(`/`).length-t.split(`/`).length;return r===0?e.localeCompare(t,void 0,{sensitivity:`base`})*n:r*n})}var Fa=class{constructor(){this.entriesByPath=new Map,this.nodesByPath=new Map,this.nodeParentPathByPath=new Map,this.roots=[]}reset(e){return this.entriesByPath=Na(e),this.nodesByPath=new Map,this.nodeParentPathByPath=new Map,this.roots=[],this.entriesByPath.forEach(e=>{let t=ja(e);t&&this.nodesByPath.set(e.path,t)}),Pa(Array.from(this.nodesByPath.keys())).forEach(e=>{let t=this.nodesByPath.get(e);t&&this.attachNode(e,t,Aa(this.entriesByPath.get(e)))}),Ma(this.roots),this.roots}getTree(){return this.roots}applyMapChanges(e,t){let n=[],r=[];return e.forEach((e,t)=>{e.action===`delete`?n.push(t):r.push(t)}),Pa(n,`desc`).forEach(e=>{this.removeEntry(e)}),Pa(r).forEach(e=>{this.upsertEntry(e,t.get(e))}),Ma(this.roots),this.roots}removeEntry(e){let t=this.nodesByPath.get(e);if(!t){this.entriesByPath.delete(e),this.nodeParentPathByPath.delete(e);return}this.detachNode(e,t),this.nodesByPath.delete(e),this.entriesByPath.delete(e),this.nodeParentPathByPath.delete(e)}upsertEntry(e,t){if(!t?.path||!t?.type){this.removeEntry(e);return}let n=ja(t);if(!n){this.removeEntry(e);return}let r=this.nodesByPath.get(e);!r||r.type===`directory`!=(n.type===`directory`)?(r&&this.detachNode(e,r),r=n,this.nodesByPath.set(e,r)):(r.name=n.name,r.path=n.path,r.type=n.type,n.mtimeMs===void 0?delete r.mtimeMs:r.mtimeMs=n.mtimeMs,r.type===`directory`&&!Array.isArray(r.children)&&(r.children=[]),r.type!==`directory`&&Array.isArray(r.children)&&delete r.children),this.entriesByPath.set(e,t),this.attachNode(e,r,Aa(t)),r.type===`directory`&&this.rehomeChildren(e)}detachNode(e,t){let n=this.nodeParentPathByPath.get(e)||``,r=n?this.nodesByPath.get(n)?.children:this.roots,i=r?.indexOf?.(t)??-1;i>=0&&r.splice(i,1),this.nodeParentPathByPath.delete(e)}attachNode(e,t,n=``){let r=this.nodesByPath.get(n)?.type===`directory`?n:``,i=this.nodeParentPathByPath.get(e);if(i===r)return;i!==void 0&&this.detachNode(e,t);let a=r?this.nodesByPath.get(r)?.children:this.roots;a.includes(t)||a.push(t),this.nodeParentPathByPath.set(e,r)}rehomeChildren(e){this.entriesByPath.forEach((t,n)=>{if(Aa(t)!==e)return;let r=this.nodesByPath.get(n);r&&this.attachNode(n,r,e)})}},Ia=class{constructor({onTreeChange:e=()=>{},onWorkspaceEvent:t=()=>{}}={}){this.onTreeChange=e,this.onWorkspaceEvent=t,this.ydoc=new L,this.entries=this.ydoc.getMap(`entries`),this.events=this.ydoc.getArray(`events`),this.provider=null,this._didInitialSync=!1,this.seenEventIds=new Set,this.treeModel=new Fa,this.handleEntriesChange=e=>{!this._didInitialSync||!e||this.onTreeChange(this.treeModel.applyMapChanges(e.changes.keys,this.entries),{changedPaths:Array.from(e.changes.keys.keys()),reset:!1})},this.handleEventsChange=()=>{if(!this._didInitialSync){this.primeEventCache();return}this.events.toArray().forEach(e=>{let t=Ln(e);!t||this.seenEventIds.has(t.id)||(this.seenEventIds.add(t.id),this.onWorkspaceEvent(t))})}}connect(){this.provider||(this._didInitialSync=!1,this.provider=new ve(ce(),Da,this.ydoc,{disableBc:!0,maxBackoffTime:5e3}),ye(this.provider),this.entries.observe(this.handleEntriesChange),this.events.observe(this.handleEventsChange),this.provider.on(`sync`,e=>{!e||this._didInitialSync||(this._didInitialSync=!0,this.primeEventCache(),this.onTreeChange(this.treeModel.reset(this.entries.toJSON()),{changedPaths:[],reset:!0}))}))}primeEventCache(){this.events.toArray().forEach(e=>{let t=Ln(e);t&&this.seenEventIds.add(t.id)})}disconnect(){this.entries.unobserve(this.handleEntriesChange),this.events.unobserve(this.handleEventsChange),this.provider?.disconnect(),this.provider?.destroy(),this.provider=null,this._didInitialSync=!1,this.seenEventIds.clear(),this.treeModel.reset(new Map)}destroy(){this.disconnect(),this.ydoc.destroy()}},La=class{constructor({documentRef:e=document,headerPanelElement:t=null,inlinePanelElement:n=null,loadBacklinks:r=null,onFileSelect:i,panelElement:a}){this.documentRef=e,this.headerPanel=t,this.panelRoot=a,this.inlinePanel=n,this.loadBacklinks=r,this.onFileSelect=i,this._expanded=!1,this._currentFile=null,this._displayMode=`dock`,this._fetchController=null,this._backlinks=[],this._pendingOutsidePointer=null;let o=this.panelRoot?.querySelector(`[data-backlinks-variant="dock"]`)??this.panelRoot;this.panels=[this._createPanelRef(o,this.panelRoot),this._createPanelRef(this.headerPanel,this.headerPanel),this._createPanelRef(this.inlinePanel,this.inlinePanel)].filter(Boolean),this.handleDocumentPointerDown=e=>{if(!this._expanded)return;let t=e?.target;if(t&&this.panels.some(({panel:e})=>e?.contains?.(t))){this._pendingOutsidePointer=null;return}(e?.pointerType!==`mouse`||e?.button===0)&&(this._pendingOutsidePointer={pointerId:e?.pointerId??`mouse`,startX:Number(e?.clientX??0),startY:Number(e?.clientY??0)})},this.handleDocumentPointerMove=e=>{if(!this._pendingOutsidePointer)return;let t=Math.abs(Number(e?.clientX??0)-this._pendingOutsidePointer.startX),n=Math.abs(Number(e?.clientY??0)-this._pendingOutsidePointer.startY);(t>10||n>10)&&(this._pendingOutsidePointer=null)},this.handleDocumentPointerEnd=e=>{if(!this._expanded||!this._pendingOutsidePointer)return;let t=e?.target;if(t&&this.panels.some(({panel:e})=>e?.contains?.(t))){this._pendingOutsidePointer=null;return}this._pendingOutsidePointer=null,this.close()},this.handleDocumentKeyDown=e=>{!this._expanded||e?.key!==`Escape`||(e.preventDefault?.(),this.close())},this.bindEvents()}bindEvents(){this.panels.forEach(e=>{e.header?.addEventListener(`click`,()=>{this._backlinks.length!==0&&(this._expanded=!this._expanded,this._pendingOutsidePointer=null,this._applyExpandState())})}),this.documentRef?.addEventListener?.(`pointerdown`,this.handleDocumentPointerDown),this.documentRef?.addEventListener?.(`pointermove`,this.handleDocumentPointerMove,{passive:!0}),this.documentRef?.addEventListener?.(`pointerup`,this.handleDocumentPointerEnd),this.documentRef?.addEventListener?.(`pointercancel`,this.handleDocumentPointerEnd),this.documentRef?.addEventListener?.(`keydown`,this.handleDocumentKeyDown)}async load(e){let t=e!==this._currentFile;if(this._currentFile=e,t&&(this._expanded=!1),!e){this._backlinks=[],this._render();return}this._fetchController?.abort(),this._fetchController=new AbortController;try{let t=await this.loadBacklinks(e,{signal:this._fetchController.signal});if(this._currentFile!==e)return;this._backlinks=t}catch(e){if(e.name===`AbortError`)return;console.warn(`[backlinks] Failed to load:`,e.message),this._backlinks=[]}this._render()}setDisplayMode(e=`dock`){let t=e===`header`?`header`:`dock`;this._displayMode!==t&&(this._displayMode=t,this._expanded=!1,this._pendingOutsidePointer=null,this._render())}clear(){this._currentFile=null,this._backlinks=[],this._expanded=!1,this._render()}close(){this._expanded&&(this._expanded=!1,this._pendingOutsidePointer=null,this._applyExpandState())}_createPanelRef(e,t=e){return e?{panel:e,header:e.querySelector(`.backlinks-header`),toggle:e.querySelector(`.backlinks-toggle`),countBadge:e.querySelector(`.backlinks-count`),body:e.querySelector(`.backlinks-body`),list:e.querySelector(`.backlinks-list`),root:t}:null}_render(){let e=this._backlinks.length,t=e===1?`Linked Mention`:`Linked Mentions`,n=!!this._currentFile&&e>0;n||(this._expanded=!1),this.panels.forEach(r=>{let i=n&&this._shouldShowPanel(r);r.root?.classList?.toggle?.(`hidden`,!i),r.countBadge.textContent=n?String(e):``,r.toggle.textContent=t,r.header?.classList.toggle(`backlinks-header-empty`,!i),i?this._renderList(r.list):r.list.innerHTML=``}),this._applyExpandState()}_shouldShowPanel(e){let t=e.panel?.getAttribute?.(`data-backlinks-variant`)??``;return t===`header`?this._displayMode===`header`:t!==`dock`||this._displayMode===`dock`}_renderList(e){if(!e)return;e.innerHTML=``;let t=this.documentRef?.createDocumentFragment?.(),n=t??e;this._backlinks.forEach(e=>{n.appendChild(this._createBacklinkItem(e))}),t&&e.appendChild(t)}_createBacklinkItem(e){let t=o(e.file.split(`/`).pop()),n=e.file.includes(`/`)?e.file.substring(0,e.file.lastIndexOf(`/`)):``,r=this.documentRef.createElement(`button`);r.type=`button`,r.className=`backlink-item`,r.addEventListener(`click`,()=>{this.close(),this.onFileSelect?.(e.file)});let i=this.documentRef.createElement(`div`);if(i.className=`backlink-file-name`,i.innerHTML=`
174
- <svg class="backlink-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
175
- <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
176
- <polyline points="14 2 14 8 20 8"/>
177
- </svg>
178
- <span>${y(t)}</span>
179
- ${n?`<span class="backlink-dir">${y(n)}</span>`:``}
180
- `,r.appendChild(i),e.contexts.slice(0,3).forEach(e=>{let t=this.documentRef.createElement(`div`);t.className=`backlink-context`,t.textContent=e,r.appendChild(t)}),e.contexts.length>3){let t=this.documentRef.createElement(`div`);t.className=`backlink-context backlink-more`,t.textContent=`+${e.contexts.length-3} more`,r.appendChild(t)}return r}_applyExpandState(){this.panels.forEach(e=>{let t=this._expanded&&this._backlinks.length>0&&this._shouldShowPanel(e);e.panel.classList.toggle(`expanded`,t),e.header?.setAttribute(`aria-expanded`,String(t)),e.header?.setAttribute(`aria-disabled`,String(this._backlinks.length===0)),e.body?.setAttribute(`aria-hidden`,String(!t)),e.body?.toggleAttribute(`inert`,!t)})}};function Ra(e){return Array.isArray(e)?e:[]}function za({copy:e,title:t,tone:n=``}){let r=document.createElement(`div`);r.className=`comment-overview-empty ui-empty-state ui-empty-state--compact`,n&&(r.dataset.tone=n);let i=document.createElement(`p`);i.className=`ui-empty-state-title`,i.textContent=t;let a=document.createElement(`p`);return a.className=`ui-empty-state-copy`,a.textContent=e,r.append(i,a),r}var Ba=class{constructor({panelElement:e,toastController:t=null,vaultApiClient:n,onOverviewChange:r=null,onThreadSelect:i=null}){this.panel=e,this.toastController=t,this.vaultApiClient=n,this.onOverviewChange=r,this.onThreadSelect=i,this.overview={files:[],generatedAt:0,totalThreadCount:0},this.loading=!1,this.errorMessage=``,this.refreshPromise=null,this.timeFormatter=new Intl.DateTimeFormat(void 0,{day:`numeric`,hour:`numeric`,minute:`2-digit`,month:`short`})}initialize(){this.render()}getThreadCounts(){return new Map(Ra(this.overview.files).map(e=>[e.filePath,Number(e.threadCount||0)]))}async refresh(){return this.refreshPromise?this.refreshPromise:(this.loading=!0,this.render(),this.refreshPromise=(async()=>{try{let e=await this.vaultApiClient.readCommentOverview();this.errorMessage=``,this.setOverview(e?.overview??e??{},{render:!1})}catch(e){console.error(`[comments] Failed to load comment overview:`,e.message),this.errorMessage=`Unable to load open comments.`,this.toastController?.show?.(`Failed to load comments`)}finally{this.loading=!1,this.refreshPromise=null,this.render()}})(),this.refreshPromise)}setOverview(e={},{render:t=!0}={}){this.errorMessage=``,this.overview={files:Ra(e.files),generatedAt:Number(e.generatedAt||0),totalThreadCount:Number(e.totalThreadCount||0)},this.onOverviewChange?.(this.overview,{threadCounts:this.getThreadCounts()}),t&&this.render()}render(){if(!this.panel)return;if(this.panel.replaceChildren(),this.errorMessage){let e=za({copy:this.errorMessage,title:`Comments unavailable`,tone:`error`});e.setAttribute(`role`,`alert`),this.panel.appendChild(e);return}if(this.loading&&Ra(this.overview.files).length===0){let e=za({copy:`Checking the vault for active threads…`,title:`Loading comments`});e.setAttribute(`role`,`status`),this.panel.appendChild(e);return}let e=Ra(this.overview.files);if(e.length===0){let e=za({copy:`Open comments from any document will appear here.`,title:`You’re all caught up`});this.panel.appendChild(e);return}let t=document.createDocumentFragment();e.forEach(e=>{t.appendChild(this.createFileGroup(e))}),this.panel.appendChild(t)}createFileGroup(e){let t=document.createElement(`section`);t.className=`comment-overview-file`;let n=document.createElement(`div`);n.className=`comment-overview-file-header`;let r=document.createElement(`div`);r.className=`comment-overview-file-title-wrap`;let i=document.createElement(`h3`);i.className=`comment-overview-file-title`,i.textContent=o(w(e.filePath));let a=document.createElement(`span`);a.className=`comment-overview-file-path`,a.textContent=M(e.filePath)||e.filePath;let s=document.createElement(`span`);return s.className=`comment-overview-file-count`,s.textContent=String(e.threadCount||Ra(e.threads).length),r.append(i,a),n.append(r,s),t.appendChild(n),Ra(e.threads).forEach(n=>{t.appendChild(this.createThreadButton(e.filePath,n))}),t}createThreadButton(e,t){let n=Number(t.messageCount||0),r=Ne({authorName:t.latestMessage?.userName||t.createdByName||`Anonymous`,lineLabel:Je(t.anchor),messageCount:n,previewBody:t.latestMessage?.bodyPreview||``,quote:t.anchor?.quote||`Source anchored comment`,timestamp:this.formatTimestamp(t.latestActivityAt)});return r.addEventListener(`click`,()=>{this.onThreadSelect?.({anchor:t.anchor,filePath:e,threadId:t.id})}),r}formatTimestamp(e){if(!Number.isFinite(e))return``;try{return this.timeFormatter.format(new Date(e))}catch{return``}}};function Va(...e){return e.flat().flatMap(e=>e&&typeof e==`object`?Object.keys(e).filter(t=>e[t]):e||[]).join(` `)}function U(e={}){return Va(`ui-input`,e.extra??[])}function W(e={}){let{variant:t=`secondary`,size:n=`md`,toggle:r=!1,toolbar:i=!1,action:a=!1,wide:o=!1,surface:s=!1,pill:c=!1,hidden:l=!1,active:u=!1,extra:d=[]}=e;return Va(`ui-button`,t&&`ui-button--${t}`,n!==`md`&&`ui-button--${n}`,{"ui-button--toggle":r,"ui-button--toolbar":i,"ui-button--action":a,"ui-button--wide":o,"ui-button--surface":s,"ui-button--pill":c,active:u,hidden:l},d)}function Ha(){if(this.cardRoot?.isConnected&&this.cardRoot.parentElement===document.body)return this.cardRoot;let e=document.createElement(`div`);return e.className=`comment-card-root hidden`,document.body.appendChild(e),this.cardRoot=e,e}function Ua(e=`editor`,t=null,n=null){let r=n?.anchor??this.session?.getCurrentSelectionCommentAnchor?.();if(!r)return;this.selectionAnchor=r,this.reactionPicker=null;let i=e===`editor`&&t?`editor-chip`:e,a=t??(e===`toolbar`?this.commentSelectionButton?.getBoundingClientRect?.():this.session?.getCommentAnchorClientRect?.(r));this.activeCard={anchor:r,composerDraft:null,mode:`create`,origin:i,previewRange:n?.range??null,replyThreadId:null,sourceRect:a??null},this.render()}function Wa(e,{anchor:t,origin:n,sourceRect:r}){this.reactionPicker=null,this.activeCard={anchor:t,groupKey:e.key,groupThreadIds:e.threads.map(e=>e.id),mode:`group`,origin:n,replyDrafts:{},replyThreadId:null,sourceRect:r},this.renderDrawer(),this.renderCard()}function Ga(){let e=this.activeCard?.mode===`create`&&this.activeCard.origin===`preview`;this.activeCard=null,this.pendingCardFocusElement=null,this.reactionPicker=null,this.renderCard(),e&&this.clearPreviewSelection(),this.scheduleLayoutRefresh()}function Ka(){return this.activeCard?this.activeCard.origin===`editor`?this.session?.getCommentAnchorClientRect?.(this.activeCard.anchor)??this.activeCard.sourceRect:this.activeCard.origin===`editor-chip`?this.activeCard.sourceRect:this.activeCard.origin===`preview`?Ke(Array.from(this.activeCard.previewRange?.getClientRects?.()??[]))||(this.resolvePreviewTarget(this.activeCard.anchor)?.bubbleRect??this.activeCard.sourceRect):this.activeCard.origin===`toolbar`?this.commentSelectionButton?.getBoundingClientRect?.()??this.activeCard.sourceRect:this.activeCard.sourceRect:null}function qa(e){return e instanceof HTMLTextAreaElement?{selectionDirection:e.selectionDirection??`none`,selectionEnd:e.selectionEnd,selectionStart:e.selectionStart,value:e.value}:null}function Ja(){if(!this.activeCard)return;let e=this.cardRoot?.querySelector(`.comment-card-input`),t=qa(e);if(t){if(this.activeCard.mode===`create`){this.activeCard.composerDraft=t;return}this.activeCard.mode===`group`&&this.activeCard.replyThreadId&&(this.activeCard.replyDrafts={...this.activeCard.replyDrafts??{},[this.activeCard.replyThreadId]:t})}}function Ya(e,t=null){return{element:e,selectionDirection:t?.selectionDirection??`none`,selectionEnd:Number.isInteger(t?.selectionEnd)?t.selectionEnd:null,selectionStart:Number.isInteger(t?.selectionStart)?t.selectionStart:null}}function Xa(){let e=this.ensureCardRoot();if(this.captureActiveCardDraft(),e.replaceChildren(),e.classList.toggle(`hidden`,!this.activeCard),!this.activeCard){this.pendingCardFocusElement=null,e.style.visibility=``;return}this.pendingCardFocusElement=null;let t=document.createElement(`section`);t.className=`comment-card`,t.addEventListener(`click`,e=>{!this.reactionPicker||e.target?.closest?.(`.comment-reaction-picker-wrap`)||(this.reactionPicker=null,requestAnimationFrame(()=>{this.activeCard&&this.renderCard()}))});let n=document.createElement(`div`);n.className=`ui-record-header comment-card-header`;let r=document.createElement(`div`);r.className=`comment-card-title-wrap`;let i=document.createElement(`h3`);i.className=`comment-card-title`,i.textContent=this.activeCard.mode===`create`?`New comment`:`Comment threads`;let a=document.createElement(`p`);a.className=`comment-card-meta`,a.textContent=Je(this.activeCard.anchor),r.append(i,a);let o=document.createElement(`button`);o.type=`button`,o.className=W({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-card-close`]}),o.setAttribute(`aria-label`,`Close comments`),o.textContent=`Close`,o.addEventListener(`click`,()=>this.closeCard()),n.append(r,o),t.appendChild(n);let s=document.createElement(`div`);if(s.className=`comment-card-scroll`,this.activeCard.mode===`create`&&this.activeCard.anchor?.fallbackToLines){let e=document.createElement(`p`);e.className=`comment-card-anchor-note`,e.textContent=`Exact preview mapping was unavailable. This comment will be anchored to ${Je(this.activeCard.anchor).toLowerCase()}.`,s.appendChild(e)}if(this.activeCard.anchor?.quote){let e=document.createElement(`p`);e.className=`comment-card-quote`,e.textContent=this.activeCard.anchor.quote,s.appendChild(e)}if(this.activeCard.mode===`create`)s.appendChild(this.createComposer());else{let e=this.getThreadGroups().find(e=>e.key===this.activeCard.groupKey);if(!e){this.closeCard();return}e.threads.forEach(e=>{s.appendChild(this.createThreadElement(e))})}e.style.visibility=`hidden`,t.appendChild(s),e.appendChild(t),this.updateReactionPickerPosition(t),this.positionCard(t),e.style.visibility=``,this.flushPendingCardFocus(),this.scheduleLayoutRefresh()}function Za(e){let t=ze(e);if(!t)return;let{picker:n,scroll:r,wrap:i}=t;n.classList.remove(`is-upward`),n.style.maxHeight=``;let a=i.getBoundingClientRect(),o=r.getBoundingClientRect(),s=n.getBoundingClientRect(),c=window.innerHeight-12,l=Math.min(o.bottom,c),u=Math.max(o.top,12),d=Math.max(l-a.bottom-8,0),f=Math.max(a.top-u-8,0),p=s.height>d&&f>d,m=Math.max(p?f:d,120);n.classList.toggle(`is-upward`,p),n.style.maxHeight=`${m}px`}function Qa(){let e=this.cardRoot?.firstElementChild;if(!e||!this.activeCard){this.cardRoot&&(this.cardRoot.style.visibility=``);return}this.positionCard(e),this.cardRoot.style.visibility=``,this.flushPendingCardFocus()}function $a(){let e=document.createElement(`form`);e.className=`comment-card-form`;let t=document.createElement(`textarea`);t.className=U({extra:`comment-card-input`}),t.rows=4,t.maxLength=De,t.placeholder=`Add context, feedback, or a question...`,t.value=this.activeCard?.composerDraft?.value??``;let n=document.createElement(`div`);n.className=`ui-record-actions comment-card-actions`;let r=document.createElement(`button`);r.type=`button`,r.className=W({variant:`secondary`}),r.textContent=`Cancel`,r.addEventListener(`click`,()=>this.closeCard());let i=document.createElement(`button`);return i.type=`submit`,i.className=W({variant:`primary`}),i.textContent=`Post comment`,n.append(r,i),e.append(t,n),e.addEventListener(`submit`,async e=>{if(e.preventDefault(),!await this.onCreateThread?.({anchor:this.activeCard?.anchor,body:t.value})){t.focus();return}this.closeCard()}),this.pendingCardFocusElement=Ya(t,this.activeCard?.composerDraft),e}function eo(e){let t=document.createElement(`article`);t.className=`comment-thread-card`;let n=document.createElement(`div`);n.className=`ui-record-actions comment-thread-card-actions`;let r=document.createElement(`button`);r.type=`button`,r.className=W({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-thread-card-action`]});let i=this.activeCard?.replyThreadId===e.id;r.classList.toggle(`is-active`,i),r.textContent=`Reply`,r.setAttribute(`aria-pressed`,String(i)),r.setAttribute(`aria-label`,i?`Cancel reply`:`Reply to thread`),r.title=i?`Cancel reply`:`Reply to thread`,r.addEventListener(`click`,()=>{i&&this.activeCard?.replyDrafts?.[e.id]&&delete this.activeCard.replyDrafts[e.id],this.activeCard={...this.activeCard,replyThreadId:i?null:e.id},this.renderCard()});let a=document.createElement(`button`);return a.type=`button`,a.className=W({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-thread-card-action`,`is-danger`]}),a.textContent=`Resolve`,a.addEventListener(`click`,async()=>{await this.onResolveThread?.(e.id)}),n.append(r,a),e.messages.forEach((r,i)=>{t.appendChild(this.createMessageElement(e,r,{actions:i===0?n:null,isThreadStart:i===0}))}),this.activeCard?.replyThreadId===e.id&&t.appendChild(this.createReplyComposer(e)),t}function to(e,t,{actions:n=null,isThreadStart:r=!1}={}){let i=document.createElement(`div`);i.className=`comment-message-card`,i.classList.toggle(`is-thread-start`,r);let a=document.createElement(`div`);a.className=`ui-record-meta comment-message-card-meta`;let o=document.createElement(`span`);o.className=`comment-message-card-author`,o.textContent=t.userName;let s=document.createElement(`span`);s.className=`comment-message-card-time`,s.textContent=this.formatTimestamp(t.createdAt);let c=Fe(t.body,`comment-message-card-body comment-markdown`);return a.append(o,s),n&&a.appendChild(n),i.append(a,c),i.appendChild(this.createReactionBar(e,t)),i}function no(e,t){let n=this.session?.getLocalUser?.()?.userId??``,r=document.createElement(`div`);r.className=`comment-reaction-bar`;let i=new Set((t.reactions??[]).map(e=>e.emoji)),a=document.createElement(`div`);a.className=`comment-reaction-chips`,(t.reactions??[]).forEach(r=>{let i=document.createElement(`button`);i.type=`button`,i.className=`ui-chip-button ui-chip-button--comment comment-reaction-chip`,i.classList.toggle(`is-active`,Re(r,n)),i.setAttribute(`aria-pressed`,String(Re(r,n))),i.title=r.users?.map(e=>e.userName).join(`, `)||r.emoji;let o=document.createElement(`span`);o.className=`comment-reaction-chip-emoji`,o.textContent=r.emoji;let s=document.createElement(`span`);s.className=`comment-reaction-chip-count`,s.textContent=Ie(r),i.append(o,s),i.addEventListener(`click`,async()=>{await this.onToggleReaction?.(e.id,t.id,r.emoji)}),a.appendChild(i)});let o=document.createElement(`div`);o.className=`comment-reaction-actions`,He.filter(e=>!i.has(e)).forEach(n=>{o.appendChild(this.createQuickReactionButton(e,t,n))});let s=document.createElement(`div`);s.className=`comment-reaction-picker-wrap`;let c=document.createElement(`button`);return c.type=`button`,c.className=`ui-chip-button ui-chip-button--comment comment-reaction-more-trigger`,c.dataset.reactionPickerToggle=`true`,c.setAttribute(`aria-expanded`,String(Ye(this.reactionPicker,e.id,t.id))),c.textContent=`More`,c.addEventListener(`click`,()=>{let n=Ye(this.reactionPicker,e.id,t.id);this.reactionPicker=n?null:{messageId:t.id,threadId:e.id},this.renderCard()}),s.appendChild(c),Ye(this.reactionPicker,e.id,t.id)&&s.appendChild(this.createReactionPicker(e,t)),o.appendChild(s),r.append(a,o),r}function ro(e,t,n){let r=document.createElement(`button`);return r.type=`button`,r.className=`ui-icon-chip ui-icon-chip--comment comment-reaction-quick-add`,r.textContent=n,r.title=`React with ${n}`,r.addEventListener(`click`,async()=>{await this.onToggleReaction?.(e.id,t.id,n)}),r}function io(e,t){let n=document.createElement(`div`);n.className=`comment-reaction-picker`;let r=document.createElement(`div`);return r.className=`comment-reaction-picker-grid`,qe.forEach(n=>{r.appendChild(this.createReactionPickerButton(e,t,n))}),n.appendChild(r),n}function ao(e,t,n){let r=document.createElement(`button`);return r.type=`button`,r.className=`ui-icon-chip ui-icon-chip--comment comment-reaction-picker-btn`,r.textContent=n,r.title=`React with ${n}`,r.addEventListener(`click`,async()=>{await this.onToggleReaction?.(e.id,t.id,n)&&(this.reactionPicker=null,this.renderCard())}),r}function oo(e){let t=document.createElement(`form`);t.className=`comment-reply-form`;let n=this.activeCard?.replyDrafts?.[e.id]??null,r=document.createElement(`textarea`);r.className=U({extra:`comment-card-input`}),r.rows=3,r.maxLength=De,r.placeholder=`Reply to thread...`,r.value=n?.value??``;let i=document.createElement(`div`);i.className=`ui-record-actions comment-card-actions`;let a=document.createElement(`button`);a.type=`button`,a.className=W({variant:`secondary`}),a.textContent=`Cancel`,a.addEventListener(`click`,()=>{this.activeCard?.replyDrafts?.[e.id]&&delete this.activeCard.replyDrafts[e.id],this.activeCard={...this.activeCard,replyThreadId:null},this.renderCard()});let o=document.createElement(`button`);return o.type=`submit`,o.className=W({variant:`primary`}),o.textContent=`Reply`,i.append(a,o),t.append(r,i),this.pendingCardFocusElement=Ya(r,n),t.addEventListener(`submit`,async t=>{if(t.preventDefault(),!await this.onReplyToThread?.(e.id,r.value)){r.focus();return}this.activeCard?.replyDrafts?.[e.id]&&delete this.activeCard.replyDrafts[e.id],this.activeCard={...this.activeCard,replyThreadId:null},this.renderCard()}),t}function so(e){let t=this.updateCardSourceRect(),n=window.innerWidth,r=window.innerHeight,i=e.getBoundingClientRect(),a=b((n-i.width)/2,16,n-i.width-16),o=b((r-i.height)/4,16,r-i.height-16),s=a,c=o;t&&(s=b(t.left,16,n-Math.min(i.width,520)-16),c=t.bottom+14,c+i.height>r-16&&(c=Math.max(t.top-i.height-14,16))),this.cardRoot.style.left=`${s}px`,this.cardRoot.style.top=`${c}px`,this.cardRoot.style.width=`${Math.min(Math.max(i.width,520),n-32)}px`}function co(){let e=this.pendingCardFocusElement,t=e instanceof HTMLElement?e:e?.element;if(!(t instanceof HTMLElement)||!t.isConnected){this.pendingCardFocusElement=null;return}this.pendingCardFocusElement=null;let n=()=>{if(!t.isConnected)return;let n=document.activeElement;n instanceof HTMLElement&&this.editorContainer?.contains(n)&&n.blur(),t.focus({preventScroll:!0}),t instanceof HTMLTextAreaElement&&Number.isInteger(e?.selectionStart)&&Number.isInteger(e?.selectionEnd)&&t.setSelectionRange(e.selectionStart,e.selectionEnd,e.selectionDirection??`none`)};n(),document.activeElement!==t&&requestAnimationFrame(()=>{n(),document.activeElement!==t&&setTimeout(()=>{n()},50)})}var lo={captureActiveCardDraft:Ja,closeCard:Ga,createComposer:$a,createPendingFocusTarget:Ya,createMessageElement:to,createQuickReactionButton:ro,createReactionBar:no,createReactionPicker:io,createReactionPickerButton:ao,createReplyComposer:oo,createTextareaDraft:qa,createThreadElement:eo,ensureCardRoot:Ha,flushPendingCardFocus:co,openComposerForSelection:Ua,openThreadGroup:Wa,positionCard:so,renderCard:Xa,repositionActiveCard:Qa,updateCardSourceRect:Ka,updateReactionPickerPosition:Za};function uo(e,t,n){e.classList.toggle(`is-active`,t),e.classList.toggle(`is-hovered`,n),e.classList.toggle(`is-passive`,!t&&!n)}function fo(){let e=this.getThreadGroups();this.renderEditorLayer(e),this.renderPreviewLayer(e),this.repositionActiveCard()}function po(){this.layoutFrame||=requestAnimationFrame(()=>{this.layoutFrame=0,this.refreshLayout()})}function mo(){if(this.editorLayer?.isConnected&&this.editorLayer.parentElement===this.editorContainer)return this.editorLayer;let e=document.createElement(`div`);return e.className=`comment-editor-layer`,this.editorContainer?.appendChild(e),this.editorLayer=e,e}function ho(e=this.getThreadGroups()){let t=this.ensureEditorLayer();if(!this.supported||!this.session){t.childElementCount>0&&t.replaceChildren();return}let n=this.editorContainer?.getBoundingClientRect?.();if(!n){t.childElementCount>0&&t.replaceChildren();return}let r=new Map(Array.from(t.querySelectorAll(`.comment-editor-badge`)).map(e=>[e.dataset.commentEditorGroupKey,e])),i=new Set,a=[];e.forEach(e=>{let o=this.session.getCommentAnchorClientRect?.(e.anchor);if(!o)return;let s=je(o,n);if(s.bottom<0||s.top>n.height)return;let c=r.get(e.key);c||(c=document.createElement(`button`),c.type=`button`,c.className=`ui-state-marker ui-state-marker--comment comment-editor-badge`,c.dataset.commentEditorGroupKey=e.key,c.addEventListener(`pointerdown`,e=>{e.preventDefault()}),c.addEventListener(`pointerenter`,()=>{this.updateHoveredEditorGroups([c.dataset.commentEditorGroupKey])}),c.addEventListener(`pointerleave`,()=>{this.updateHoveredEditorGroups([])}),c.addEventListener(`focusin`,()=>{this.updateHoveredEditorGroups([c.dataset.commentEditorGroupKey])}),c.addEventListener(`focusout`,()=>{this.updateHoveredEditorGroups([])}),c.addEventListener(`click`,()=>{let e=c.commentGroup;e&&this.openThreadGroup(e,{anchor:e.anchor,origin:`editor`,sourceRect:c.commentSourceRect})}),t.appendChild(c)),c.commentGroup=e,c.commentSourceRect=o,c.dataset.count!==String(e.threads.length)&&(c.dataset.count=String(e.threads.length),c.replaceChildren(Be(e.threads.length)));let l=this.activeCard?.groupKey===e.key,u=this.hoveredEditorGroupKeys.includes(e.key);uo(c,l,u),c.setAttribute(`aria-label`,`${e.threads.length} comment thread${e.threads.length===1?``:`s`}`);let d=Math.max(s.top,8);c.style.top=`${d}px`,c.style.left=`${Math.max(n.width-36,8)}px`,c.title=`${e.threads.length} comment${e.threads.length===1?``:`s`}`,i.add(e.key),a.push(d)}),r.forEach((e,t)=>{i.has(t)||e.remove()});let o=t.querySelector(`.comment-selection-chip`);if(!this.committedSelectionAnchor||this.activeCard?.mode===`create`){o?.remove();return}let s=this.session.getCommentAnchorClientRect?.(this.committedSelectionAnchor),c=this.session.getSelectionChipClientRect?.(this.committedSelectionAnchor)??s;if(!c){o?.remove();return}let l=je(c,n);if(l.bottom<0||l.top>n.height){o?.remove();return}let u=b(l.top,8,Math.max(n.height-36,8));for(;a.some(e=>Math.abs(e-u)<32);)u=b(u+36,8,Math.max(n.height-36,8));o||(o=document.createElement(`button`),o.type=`button`,o.className=`ui-selection-pill ui-selection-pill--comment comment-selection-chip`,o.textContent=`Comment`,o.addEventListener(`pointerdown`,e=>{e.preventDefault(),e.stopPropagation(),this.openComposerForSelection(`editor`,o.getBoundingClientRect())}),t.appendChild(o)),o.style.top=`${u}px`,o.style.right=`12px`}function go(){if(this.previewLayer?.isConnected&&this.previewLayer.parentElement===this.previewElement)return this.previewLayer;let e=document.createElement(`div`);e.className=`comment-preview-highlights`;let t=document.createElement(`div`);return t.className=`comment-preview-layer`,this.previewElement?.append(e,t),this.previewHighlightLayer=e,this.previewLayer=t,t}function _o(e){let t=this.previewLayer?.querySelector(`.comment-preview-selection-chip`),n=this.activeCard?.mode===`create`?null:this.previewSelection;if(!n){t?.remove();return}let r=Ke(Array.from(n.range?.getClientRects?.()??[]))||n.rect;if(!r){t?.remove();return}t||(t=document.createElement(`button`),t.type=`button`,t.className=`ui-chip-button ui-chip-button--comment comment-preview-selection-chip`,t.textContent=`Comment`,t.setAttribute(`aria-label`,`Comment on selected preview text`),t.addEventListener(`pointerdown`,e=>{e.preventDefault(),e.stopPropagation()}),t.addEventListener(`click`,()=>{this.openComposerForSelection(`preview`,t.getBoundingClientRect(),t.previewSelection)}),this.previewLayer?.appendChild(t)),t.previewSelection=n,t.style.left=`${b(r.left-e.left,8,Math.max(this.previewElement.clientWidth-88,8))}px`,t.style.top=`${b(r.bottom-e.top+8,8,Math.max(this.previewElement.clientHeight-36,8))}px`}function vo(e=this.getThreadGroups()){if(this.ensurePreviewLayer(),!this.supported||!this.previewElement){this.previewLayer?.childElementCount>0&&this.previewLayer.replaceChildren(),this.previewHighlightLayer?.childElementCount>0&&this.previewHighlightLayer.replaceChildren(),this.previewHoverRegions=[];return}let t=this.previewElement.getBoundingClientRect(),n={diagramShells:Array.from(this.previewElement.querySelectorAll(`.mermaid-shell, .plantuml-shell`)),sourceBlocks:Array.from(this.previewElement.querySelectorAll(`[data-source-line]`)).filter(e=>Me(e))},r=new Map(Array.from(this.previewHighlightLayer?.querySelectorAll(`[data-comment-preview-highlight-key]`)??[]).map(e=>[e.dataset.commentPreviewHighlightKey,e])),i=new Set,a=({groupKey:e=``,isActive:n,isHovered:a,key:o,rect:s})=>{let c=r.get(o);c||(c=document.createElement(`div`),c.className=`comment-preview-highlight`,c.dataset.commentPreviewHighlightKey=o,this.previewHighlightLayer?.appendChild(c)),e?(c.dataset.commentPreviewGroupKey=e,c.dataset.commentPreviewGroupKeys=e):(delete c.dataset.commentPreviewGroupKey,delete c.dataset.commentPreviewGroupKeys),uo(c,n,a),c.style.left=`${s.left-t.left}px`,c.style.top=`${s.top-t.top}px`,c.style.width=`${s.width}px`,c.style.height=`${s.height}px`,i.add(o)};if(this.activeCard?.mode===`create`&&this.activeCard.origin===`preview`){let e=Array.from(this.activeCard.previewRange?.getClientRects?.()??[]);(e.length>0?e:[this.resolvePreviewTarget(this.activeCard.anchor,n)?.bubbleRect].filter(Boolean)).forEach((e,t)=>{a({isActive:!0,isHovered:!1,key:`selection:${t}`,rect:e})})}let o=[];e.forEach(e=>{let t=this.resolvePreviewTarget(e.anchor,n);if(!t?.bubbleRect)return;o.push({key:e.key,rects:t.hoverRects?.length>0?t.hoverRects:[t.bubbleRect]});let r=this.activeCard?.groupKey===e.key,i=this.hoveredPreviewGroupKeys.includes(e.key);t.highlightRects?.forEach((t,n)=>{a({groupKey:e.key,isActive:r,isHovered:i,key:`${e.key}:highlight:${n}`,rect:t})})}),_o.call(this,t),r.forEach((e,t)=>{i.has(t)||e.remove()}),this.previewHoverRegions=o,this.lastPreviewPointerPosition&&this.updateHoveredPreviewGroups(this.getPreviewGroupKeysAtPoint(this.lastPreviewPointerPosition.x,this.lastPreviewPointerPosition.y))}function yo(){this.previewSelection=null,window.getSelection()?.removeAllRanges(),this.scheduleLayoutRefresh()}function bo(e,{diagramShells:t=null,sourceBlocks:n=null}={}){if(!this.previewElement||!e)return null;let r=(t??Array.from(this.previewElement.querySelectorAll(`.mermaid-shell, .plantuml-shell`))).find(t=>Ze(t,e));if(r){let e=r.getBoundingClientRect();return{bubbleRect:e,highlightRects:[],hoverRects:[e]}}let i=(n??Array.from(this.previewElement.querySelectorAll(`[data-source-line]`)).filter(e=>Me(e))).filter(t=>Ze(t,e));if(e.kind===`text`&&e.quote){let t=i.map(t=>({element:t,range:Ve(t,e.quote)})).filter(e=>e.range);if(t.length===1){let e=Array.from(t[0].range.getClientRects());return{bubbleRect:Ke(e)||t[0].element.getBoundingClientRect(),highlightRects:e,hoverRects:e}}}let a=i[0];if(!a)return null;let o=a.getBoundingClientRect();return{bubbleRect:o,highlightRects:[],hoverRects:[o]}}function xo(e){if(!(e instanceof Node))return[];let t=e.closest?.(`[data-comment-preview-group-keys]`);return t?.dataset?.commentPreviewGroupKey?[t.dataset.commentPreviewGroupKey]:ke(String(t?.dataset?.commentPreviewGroupKeys??``).split(/\s+/).filter(Boolean)).split(` `).filter(Boolean)}function So(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))return[];let n=document.elementFromPoint(e,t),r=this.getPreviewGroupKeysForTarget(n);if(r.length>0)return r;let i=this.previewHoverRegions.filter(n=>n.rects.some(n=>Ae(e,t,n))).map(e=>e.key);return Pe(i)}function Co(e=[]){let t=Pe(e),n=t.join(` `);n!==this.hoveredPreviewGroupKeysSignature&&(this.hoveredPreviewGroupKeys=t,this.hoveredPreviewGroupKeysSignature=n,this.syncHoveredCommentClasses())}function wo(e=[]){let t=Pe(e),n=t.join(` `);n!==this.hoveredEditorGroupKeysSignature&&(this.hoveredEditorGroupKeys=t,this.hoveredEditorGroupKeysSignature=n,this.syncHoveredCommentClasses())}function To(){this.editorLayer?.querySelectorAll(`.comment-editor-badge`).forEach(e=>{let t=e.dataset.commentEditorGroupKey;uo(e,this.activeCard?.groupKey===t,this.hoveredEditorGroupKeys.includes(t))}),[...Array.from(this.previewLayer?.querySelectorAll(`[data-comment-preview-group-key]`)??[]),...Array.from(this.previewHighlightLayer?.querySelectorAll(`[data-comment-preview-group-key]`)??[])].forEach(e=>{let t=e.dataset.commentPreviewGroupKey;uo(e,this.activeCard?.groupKey===t,this.hoveredPreviewGroupKeys.includes(t))})}function Eo(e){this.updateHoveredPreviewGroups(this.getPreviewGroupKeysForTarget(e))}var Do={clearPreviewSelection:yo,ensureEditorLayer:mo,ensurePreviewLayer:go,getPreviewGroupKeysAtPoint:So,getPreviewGroupKeysForTarget:xo,refreshLayout:fo,renderEditorLayer:ho,renderPreviewLayer:vo,resolvePreviewTarget:bo,scheduleLayoutRefresh:po,syncHoveredCommentClasses:To,syncHoveredPreviewGroupsFromTarget:Eo,updateHoveredEditorGroups:wo,updateHoveredPreviewGroups:Co};function Oo(){this.renderToolbar(),this.renderDrawer(),this.renderCard(),this.scheduleLayoutRefresh()}function ko(){let e=this.threads.length,t=this.supported&&!!this.session;if(this.commentSelectionButton?.classList.toggle(`hidden`,!t),this.commentsToggleButton?.classList.toggle(`hidden`,!this.supported),this.commentSelectionButton&&(this.commentSelectionButton.disabled=!this.selectionAnchor),this.commentsToggleButton){this.commentsToggleButton.classList.toggle(`active`,this.drawerOpen),this.commentsToggleButton.setAttribute(`aria-expanded`,String(this.drawerOpen));let t=e>0?`Comments ${e}`:`Comments`,n=this.commentsToggleButton.querySelector(`.ui-action-label`);n?n.textContent=t:this.commentsToggleButton.textContent=t}}function Ao(){if(!this.commentsDrawer||!this.commentsDrawerList||(this.commentsDrawer.classList.toggle(`hidden`,!this.supported||!this.drawerOpen),!this.supported||!this.drawerOpen))return;this.commentsDrawerList.replaceChildren();let e=this.getThreadGroups();if(this.commentsDrawerEmpty?.classList.toggle(`hidden`,e.length>0),e.length===0)return;let t=document.createDocumentFragment();e.forEach(e=>{let n=We(e),r=e.threads.reduce((e,t)=>e+(Array.isArray(t.messages)?t.messages.length:0),0),i=Ne({authorName:n?.userName||e.threads[0]?.createdByName||`Anonymous`,buttonClassName:`comment-overview-thread comments-drawer-item`,footerClassName:`comment-overview-thread-footer comments-drawer-item-footer`,headerClassName:`comment-overview-thread-header comments-drawer-item-header`,lineClassName:`comment-overview-thread-line comments-drawer-item-title`,lineLabel:Je(e.anchor),messageCount:r,previewBody:n?.body||``,previewClassName:`comment-markdown comment-overview-thread-preview comments-drawer-item-preview`,quote:e.anchor?.quote||e.anchor?.excerpt||`Source anchored comment`,quoteClassName:`comment-overview-thread-quote comments-drawer-item-quote`,timestamp:n?this.formatTimestamp(n.createdAt):``});i.classList.toggle(`is-active`,this.activeCard?.groupKey===e.key),i.addEventListener(`pointerdown`,e=>{e.preventDefault()}),i.addEventListener(`click`,()=>{this.onNavigateToLine?.(e.anchor?.startLine??1),this.mobileBreakpointQuery?.matches&&this.setDrawerOpen(!1),this.openThreadGroup(e,{anchor:e.anchor,origin:`editor`,sourceRect:this.session?.getCommentAnchorClientRect?.(e.anchor)??i.getBoundingClientRect()})}),t.appendChild(i)}),this.commentsDrawerList.appendChild(t)}function jo(e){if(!Number.isFinite(e))return``;try{return this.timeFormatter.format(new Date(e))}catch{return``}}var Mo={formatTimestamp:jo,render:Oo,renderDrawer:Ao,renderToolbar:ko};function No(e){this.session?.getScrollContainer?.()?.removeEventListener(`scroll`,this.handleEditorScroll),this.session=e,this.selectionAnchor=e?.getCurrentSelectionCommentAnchor?.()??null,this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.previewSelection=null,this.reactionPicker=null,this.clearSelectionRevealTimer(),this.pointerSelecting=!1,e?.getScrollContainer?.()?.addEventListener(`scroll`,this.handleEditorScroll,{passive:!0}),this.render()}function Po(e,{fileKind:t=`markdown`,supported:n=!1}={}){let r=this.currentFile!==e;this.currentFile=e,this.fileKind=t,this.supported=!!(e&&n),r&&(this.drawerOpen=!1,this.threads=[],this.selectionAnchor=null,this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.clearSelectionRevealTimer(),this.pointerSelecting=!1,this.activeCard=null,this.updateHoveredEditorGroups([]),this.updateHoveredPreviewGroups([]),this.previewHoverRegions=[],this.lastPreviewPointerPosition=null,this.previewSelection=null,this.reactionPicker=null),this.supported||(this.drawerOpen=!1,this.activeCard=null,this.threads=[],this.selectionAnchor=null,this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.clearSelectionRevealTimer(),this.pointerSelecting=!1,this.updateHoveredEditorGroups([]),this.updateHoveredPreviewGroups([]),this.previewHoverRegions=[],this.lastPreviewPointerPosition=null,this.previewSelection=null,this.reactionPicker=null),this.render()}function Fo(e){if(this.selectionAnchor=this.supported?e:null,!this.supported||!this.selectionAnchor){this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.clearSelectionRevealTimer(),this.renderToolbar(),this.scheduleLayoutRefresh();return}if(!Qe(this.selectionAnchor)){this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.clearSelectionRevealTimer(),this.renderToolbar(),this.scheduleLayoutRefresh();return}if(this.pendingSelectionAnchor=this.selectionAnchor,this.activeCard?.mode===`create`){this.clearSelectionRevealTimer(),this.renderToolbar(),this.scheduleLayoutRefresh();return}if(this.pointerSelecting){this.clearSelectionRevealTimer(),this.committedSelectionAnchor=null,this.renderToolbar(),this.scheduleLayoutRefresh();return}if(Ge(this.committedSelectionAnchor,this.selectionAnchor)){this.renderToolbar(),this.scheduleLayoutRefresh();return}this.scheduleSelectionReveal(this.selectionAnchor),this.renderToolbar(),this.scheduleLayoutRefresh()}function Io(){this.activeCard?.mode!==`create`&&(this.clearSelectionRevealTimer(),this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.scheduleLayoutRefresh())}function Lo(e=[]){this.threads=Xe(e);let t=this.getThreadGroups();if(this.activeCard?.mode===`group`){let e=Array.isArray(this.activeCard.groupThreadIds)?this.activeCard.groupThreadIds:[],n=t.find(e=>e.key===this.activeCard.groupKey)??t.find(t=>t.threads.length===e.length&&t.threads.every(t=>e.includes(t.id)));n?(this.activeCard={...this.activeCard,anchor:n.anchor,groupKey:n.key,groupThreadIds:n.threads.map(e=>e.id)},this.activeCard.replyThreadId&&!n.threads.some(e=>e.id===this.activeCard.replyThreadId)&&(this.activeCard.replyThreadId=null)):this.activeCard=null}this.reactionPicker&&!this.threads.some(e=>e.id===this.reactionPicker.threadId&&e.messages?.some(e=>e.id===this.reactionPicker.messageId))&&(this.reactionPicker=null),this.render()}function Ro(e){let t=!!e;t!==this.drawerOpen&&(t&&this.onWillOpenDrawer?.(),this.drawerOpen=t,this.render())}function zo(){this.setDrawerOpen(!1)}function Bo(e){if(!e||!this.supported)return!1;let t=this.getThreadGroups().find(t=>t.threads.some(t=>t.id===e));return t?(this.onNavigateToLine?.(t.anchor?.startLine??1),this.openThreadGroup(t,{anchor:t.anchor,origin:`editor`,sourceRect:this.session?.getCommentAnchorClientRect?.(t.anchor)??null}),!0):!1}function Vo(){let e=new Map;return this.threads.forEach(t=>{let n=Le(t.anchor),r=e.get(n);if(r){r.threads.push(t);return}e.set(n,{anchor:t.anchor,key:n,threads:[t]})}),Array.from(e.values()).sort((e,t)=>(e.anchor?.startLine??0)-(t.anchor?.startLine??0))}function Ho(){this.selectionRevealTimer&&=(clearTimeout(this.selectionRevealTimer),0)}function Uo(e){this.clearSelectionRevealTimer(),this.selectionRevealTimer=window.setTimeout(()=>{this.selectionRevealTimer=0,!(this.pointerSelecting||this.activeCard?.mode===`create`||!Ge(this.pendingSelectionAnchor,e))&&(this.committedSelectionAnchor=e,this.scheduleLayoutRefresh())},150)}var Wo={attachSession:No,clearSelectionRevealTimer:Ho,closeDrawer:zo,getThreadGroups:Vo,handleEditorContentChange:Io,openThreadFromOverview:Bo,scheduleSelectionReveal:Uo,setCurrentFile:Po,setDrawerOpen:Ro,setSelectionAnchor:Fo,setThreads:Lo},Go=class{constructor({commentSelectionButton:e,commentsDrawer:t,commentsDrawerEmpty:n,commentsDrawerList:r,commentsToggleButton:i,editorContainer:a,mobileBreakpointQuery:o=window.matchMedia(`(max-width: 768px)`),onWillOpenDrawer:s,onCreateThread:c,onNavigateToLine:l,onReplyToThread:u,onToggleReaction:d,onResolveThread:f,previewContainer:p,previewElement:m}){this.commentSelectionButton=e,this.commentsDrawer=t,this.commentsDrawerEmpty=n,this.commentsDrawerList=r,this.commentsToggleButton=i,this.editorContainer=a,this.mobileBreakpointQuery=o,this.onWillOpenDrawer=s,this.onCreateThread=c,this.onNavigateToLine=l,this.onReplyToThread=u,this.onToggleReaction=d,this.onResolveThread=f,this.previewContainer=p,this.previewElement=m,this.currentFile=null,this.fileKind=`markdown`,this.supported=!1,this.drawerOpen=!1,this.threads=[],this.selectionAnchor=null,this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.selectionRevealTimer=0,this.pointerSelecting=!1,this.session=null,this.activeCard=null,this.hoveredEditorGroupKeys=[],this.hoveredEditorGroupKeysSignature=``,this.hoveredPreviewGroupKeys=[],this.hoveredPreviewGroupKeysSignature=``,this.previewHoverRegions=[],this.lastPreviewPointerPosition=null,this.previewSelection=null,this.editorLayer=null,this.previewLayer=null,this.previewHighlightLayer=null,this.cardRoot=null,this.pendingCardFocusElement=null,this.reactionPicker=null,this.layoutFrame=0,this.timeFormatter=new Intl.DateTimeFormat(void 0,{day:`numeric`,hour:`numeric`,minute:`2-digit`,month:`short`}),this.handleEditorScroll=()=>this.scheduleLayoutRefresh(),this.handlePreviewScroll=()=>this.scheduleLayoutRefresh(),this.handleWindowResize=()=>this.scheduleLayoutRefresh(),this.handlePreviewPointerMove=e=>{this.lastPreviewPointerPosition={x:e.clientX,y:e.clientY},this.updateHoveredPreviewGroups(this.getPreviewGroupKeysAtPoint(e.clientX,e.clientY))},this.handlePreviewPointerLeave=()=>{this.lastPreviewPointerPosition=null,this.updateHoveredPreviewGroups([])},this.handlePreviewFocusIn=e=>{this.updateHoveredPreviewGroups(this.getPreviewGroupKeysForTarget(e.target))},this.handlePreviewFocusOut=e=>{this.updateHoveredPreviewGroups(this.getPreviewGroupKeysForTarget(e.relatedTarget))},this.handleDocumentSelectionChange=()=>{if(this.activeCard?.mode===`create`&&this.activeCard.origin===`preview`)return;let e=this.supported&&this.fileKind===`markdown`?Ue(window.getSelection(),this.previewElement,this.session?.getText?.()??``):null;!e&&!this.previewSelection||(this.previewSelection=e,this.scheduleLayoutRefresh())},this.handleCommentSelectionButtonPointerDown=e=>{e.preventDefault()},this.handleEditorPointerDown=e=>{e.button!==0||!this.supported||!this.session||!e.target?.closest?.(`.cm-editor`)||e.target?.closest?.(`.comment-editor-layer`)||(this.pointerSelecting=!0,this.clearSelectionRevealTimer(),this.committedSelectionAnchor&&(this.committedSelectionAnchor=null,this.scheduleLayoutRefresh()))},this.handleDocumentPointerUp=()=>{this.pointerSelecting&&requestAnimationFrame(()=>{let e=this.supported?this.session?.getCurrentSelectionCommentAnchor?.()??null:null;this.pointerSelecting=!1,this.selectionAnchor=e,this.renderToolbar(),this.pendingSelectionAnchor=Qe(e)?e:null,this.clearSelectionRevealTimer(),this.committedSelectionAnchor=Qe(e)&&this.activeCard?.mode!==`create`?e:null,this.scheduleLayoutRefresh()})},this.handleEditorFocusOut=e=>{let t=e.relatedTarget;t instanceof Node&&(this.editorContainer?.contains(t)||this.cardRoot?.contains(t)||this.commentSelectionButton?.contains(t))||(this.clearSelectionRevealTimer(),this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.scheduleLayoutRefresh())},this.handleDocumentPointerDown=e=>{let t=e.target;if(this.activeCard&&this.cardRoot){if(this.cardRoot.contains(t))return;this.closeCard()}this.drawerOpen&&(t instanceof Node&&(this.commentsDrawer?.contains(t)||this.commentsToggleButton?.contains(t))||this.closeDrawer())},this.handleDocumentKeyDown=e=>{if(e.key===`Escape`&&this.reactionPicker){this.reactionPicker=null,this.renderCard();return}e.key===`Escape`&&this.activeCard&&this.closeCard(),e.key===`Escape`&&this.previewSelection&&this.clearPreviewSelection(),e.key===`Escape`&&this.committedSelectionAnchor&&(this.clearSelectionRevealTimer(),this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.scheduleLayoutRefresh())},this.commentSelectionButton?.addEventListener(`pointerdown`,this.handleCommentSelectionButtonPointerDown),this.commentSelectionButton?.addEventListener(`click`,()=>{this.openComposerForSelection(`toolbar`)}),this.commentsToggleButton?.addEventListener(`click`,()=>{this.setDrawerOpen(!this.drawerOpen)}),this.previewContainer?.addEventListener(`scroll`,this.handlePreviewScroll,{passive:!0}),this.previewElement?.addEventListener(`pointermove`,this.handlePreviewPointerMove,{passive:!0}),this.previewElement?.addEventListener(`pointerleave`,this.handlePreviewPointerLeave),this.previewElement?.addEventListener(`focusin`,this.handlePreviewFocusIn),this.previewElement?.addEventListener(`focusout`,this.handlePreviewFocusOut),this.editorContainer?.addEventListener(`pointerdown`,this.handleEditorPointerDown),this.editorContainer?.addEventListener(`focusout`,this.handleEditorFocusOut),window.addEventListener(`resize`,this.handleWindowResize),document.addEventListener(`pointerup`,this.handleDocumentPointerUp),document.addEventListener(`pointercancel`,this.handleDocumentPointerUp),document.addEventListener(`pointerdown`,this.handleDocumentPointerDown),document.addEventListener(`keydown`,this.handleDocumentKeyDown),document.addEventListener(`selectionchange`,this.handleDocumentSelectionChange)}destroy(){this.layoutFrame&&=(cancelAnimationFrame(this.layoutFrame),0),this.attachSession(null),this.previewContainer?.removeEventListener(`scroll`,this.handlePreviewScroll),this.previewElement?.removeEventListener(`pointermove`,this.handlePreviewPointerMove),this.previewElement?.removeEventListener(`pointerleave`,this.handlePreviewPointerLeave),this.previewElement?.removeEventListener(`focusin`,this.handlePreviewFocusIn),this.previewElement?.removeEventListener(`focusout`,this.handlePreviewFocusOut),this.commentSelectionButton?.removeEventListener(`pointerdown`,this.handleCommentSelectionButtonPointerDown),this.editorContainer?.removeEventListener(`pointerdown`,this.handleEditorPointerDown),this.editorContainer?.removeEventListener(`focusout`,this.handleEditorFocusOut),window.removeEventListener(`resize`,this.handleWindowResize),document.removeEventListener(`pointerup`,this.handleDocumentPointerUp),document.removeEventListener(`pointercancel`,this.handleDocumentPointerUp),document.removeEventListener(`pointerdown`,this.handleDocumentPointerDown),document.removeEventListener(`keydown`,this.handleDocumentKeyDown),document.removeEventListener(`selectionchange`,this.handleDocumentSelectionChange),this.previewHoverRegions=[],this.previewSelection=null,this.cardRoot?.remove(),this.editorLayer?.remove(),this.previewLayer?.remove(),this.pendingCardFocusElement=null}};Object.assign(Go.prototype,Wo,Mo,Do,lo);function Ko(){return typeof window>`u`||typeof window.matchMedia!=`function`?{matches:!1}:window.matchMedia(`(max-width: 768px)`)}function qo(e){return typeof HTMLElement>`u`||!(e instanceof HTMLElement)?[]:Array.from(e.querySelectorAll(`.create-menu-item`))}var Jo=class{constructor({mobileBreakpointQuery:e=Ko()}={}){this.mobileBreakpointQuery=e,this.activeAnchor=null,this.desktopMenu=null,this.mobileBackdrop=null,this.mobileSheet=null,this.documentPointerDownHandler=null,this.windowResizeHandler=null,this.boundClose=()=>this.close()}isMobileViewport(){return!!this.mobileBreakpointQuery?.matches}isOpen(){return!!(this.desktopMenu||this.mobileSheet)}toggle(e={}){if(this.isOpen()){this.close();return}this.open(e)}open({anchor:e=null,items:t=[],title:n=`Create`}={}){if(this.close({restoreFocus:!1}),!(!Array.isArray(t)||t.length===0)){if(this.activeAnchor=typeof HTMLElement<`u`&&e instanceof HTMLElement?e:null,this.activeAnchor?.setAttribute(`aria-expanded`,`true`),this.isMobileViewport()){this.openMobileSheet({items:t,title:n});return}this.openDesktopMenu({anchor:this.activeAnchor,items:t,title:n})}}close({restoreFocus:e=!0}={}){this.desktopMenu&&=(this.desktopMenu.remove(),null),this.mobileBackdrop&&=(this.mobileBackdrop.remove(),null),this.mobileSheet&&=(this.mobileSheet.remove(),null),this.documentPointerDownHandler&&=(document.removeEventListener(`pointerdown`,this.documentPointerDownHandler),null),this.windowResizeHandler&&typeof window<`u`&&window.removeEventListener(`resize`,this.windowResizeHandler),this.windowResizeHandler=null;let t=this.activeAnchor;this.activeAnchor?.setAttribute(`aria-expanded`,`false`),this.activeAnchor=null,e&&t?.focus?.()}openDesktopMenu({anchor:e,items:t,title:n}){let r=document.createElement(`div`);r.className=`create-menu`,r.setAttribute(`role`,`menu`),r.setAttribute(`aria-label`,n),this.renderMenuItems(r,t),document.body.appendChild(r),this.positionDesktopMenu(r,e),r.addEventListener(`keydown`,e=>{this.handleDesktopMenuKeyDown(e,r)}),this.documentPointerDownHandler=t=>{r.contains(t.target)||e?.contains?.(t.target)||this.close()},this.windowResizeHandler=this.boundClose,setTimeout(()=>{document.addEventListener(`pointerdown`,this.documentPointerDownHandler)},0),typeof window<`u`&&window.addEventListener(`resize`,this.windowResizeHandler),this.desktopMenu=r,qo(r)[0]?.focus()}openMobileSheet({items:e,title:t}){let n=document.createElement(`button`);n.type=`button`,n.className=`file-action-sheet-backdrop`,n.setAttribute(`aria-label`,`Close ${t.toLowerCase()} menu`);let r=document.createElement(`div`);r.className=`file-action-sheet create-action-sheet`;let i=document.createElement(`div`);i.className=`create-action-sheet-header`,i.textContent=t,r.appendChild(i),this.renderMenuItems(r,e,{mobile:!0});let a=document.createElement(`button`);a.type=`button`,a.className=W({variant:`ghost`,extra:[`file-action-sheet-item`,`create-action-sheet-cancel`]}),a.textContent=`Cancel`,a.addEventListener(`click`,()=>{this.close()}),r.appendChild(a),n.addEventListener(`click`,()=>{this.close()}),document.body.append(n,r),this.mobileBackdrop=n,this.mobileSheet=r}renderMenuItems(e,t,{mobile:n=!1}={}){let r=null;t.forEach(t=>{if(t.group&&t.group!==r){let i=document.createElement(`div`);i.className=n?`create-action-sheet-group`:`create-menu-group`,i.textContent=t.group,e.appendChild(i),r=t.group}let i=document.createElement(`button`);i.type=`button`,i.className=n?W({variant:`ghost`,extra:[`file-action-sheet-item`,`create-action-sheet-item`,`create-action-sheet-option`]}):`create-menu-item`,i.setAttribute(`role`,n?`button`:`menuitem`),i.dataset.actionId=t.id;let a=document.createElement(`span`);a.className=`create-menu-item-icon`,a.setAttribute(`aria-hidden`,`true`),a.innerHTML=t.icon||``,i.appendChild(a);let o=document.createElement(`span`);o.className=`create-menu-item-copy`;let s=document.createElement(`span`);s.className=`create-menu-item-label`,s.textContent=t.label,o.appendChild(s);let c=t.meta||t.hint;if(c){let e=document.createElement(`span`);e.className=`create-menu-item-meta`,e.textContent=c,o.appendChild(e)}i.appendChild(o),i.addEventListener(`click`,()=>{this.close({restoreFocus:!1}),t.onSelect?.()}),e.appendChild(i)})}positionDesktopMenu(e,t){let n=e.getBoundingClientRect(),r=t?.getBoundingClientRect?.(),i=r?.left??8,a=Math.max(8,window.innerWidth-n.width-8),o=Math.max(8,Math.min(i,a)),s=(r?.bottom??8)+8,c=window.innerHeight-n.height-8;s>c&&r&&(s=Math.max(8,r.top-n.height-8)),e.style.left=`${o}px`,e.style.top=`${Math.max(8,s)}px`}handleDesktopMenuKeyDown(e,t){let n=qo(t);if(n.length===0)return;let r=Math.max(0,n.indexOf(document.activeElement));switch(e.key){case`ArrowDown`:e.preventDefault(),n[(r+1)%n.length]?.focus();break;case`ArrowUp`:e.preventDefault(),n[(r-1+n.length)%n.length]?.focus();break;case`Home`:e.preventDefault(),n[0]?.focus();break;case`End`:e.preventDefault(),n[n.length-1]?.focus();break;case`Escape`:e.preventDefault(),this.close();break;case`Tab`:this.close({restoreFocus:!1})}}};function Yo(e,t,n){return e===t?n:`${n}${e.slice(t.length)}`}function Xo(e,t,n){return`${e} ${e===1?t:n}`}var Zo=g.join(`,`);function Qo(){return JSON.stringify({type:`excalidraw`,version:2,source:`collabmd`,elements:[],appState:{viewBackgroundColor:`#ffffff`,gridSize:null},files:{}})}function $o(e,t){return t?{...e,requestId:t}:e}var es=class{constructor({mobileBreakpointQuery:e=typeof window<`u`&&typeof window.matchMedia==`function`?window.matchMedia(`(max-width: 768px)`):{matches:!1},onFileDelete:t,onFileSelect:n,onShowFileExtensionsChange:r,pendingWorkspaceRequestIds:i=null,showFileExtensions:a=!1,state:o,toastController:s,vaultClient:c,view:l,refresh:u}){this.onFileDelete=t,this.onFileSelect=n,this.onShowFileExtensionsChange=r,this.pendingWorkspaceRequestIds=i,this.showFileExtensions=!!a,this.state=o,this.toastController=s,this.vaultClient=c,this.view=l,this.refresh=u,this.createButton=document.getElementById(`sidebarCreateBtn`),this.fileExplorerOptionsButton=document.getElementById(`fileExplorerOptionsBtn`),this.actionDialog=document.getElementById(`fileActionDialog`),this.actionForm=document.getElementById(`fileActionForm`),this.actionTitle=document.getElementById(`fileActionTitle`),this.actionCopy=document.getElementById(`fileActionCopy`),this.actionField=document.getElementById(`fileActionField`),this.actionLabel=document.getElementById(`fileActionLabel`),this.actionInput=document.getElementById(`fileActionInput`),this.actionHint=document.getElementById(`fileActionHint`),this.actionNote=document.getElementById(`fileActionNote`),this.actionCancelButton=document.getElementById(`fileActionCancel`),this.actionSubmitButton=document.getElementById(`fileActionSubmit`),this.createMenu=new Jo({mobileBreakpointQuery:e}),this.fileExplorerOptionsMenu=new Jo({mobileBreakpointQuery:e}),this.pendingAction=null,this.actionBusy=!1}initialize(){this.createButton?.addEventListener(`click`,()=>{this.openRootCreateMenu({anchor:this.createButton})}),this.fileExplorerOptionsButton?.addEventListener(`click`,()=>{this.openFileExplorerOptionsMenu({anchor:this.fileExplorerOptionsButton})}),this.actionCancelButton?.addEventListener(`click`,()=>this.closeActionDialog()),this.actionForm?.addEventListener(`submit`,e=>{e.preventDefault(),this.handleActionSubmit()}),this.actionDialog?.addEventListener(`close`,()=>this.resetActionDialog())}getCreateActions({parentDir:e=``}={}){return[{contextLabel:`Upload files`,group:`File`,hint:`Supported vault files`,icon:this.getCreateActionIcon(`upload`),id:`upload`,label:`Upload files`,meta:`Multiple`,onSelect:()=>{this.handleUploadFiles({parentDir:e})}},{contextLabel:`New markdown file`,group:`Note`,hint:`Markdown`,icon:this.getCreateActionIcon(`markdown`),id:`markdown`,label:`Markdown note`,meta:`.md`,onSelect:()=>this.handleNewFile({parentDir:e})},{contextLabel:`New base file`,group:`Note`,hint:`Base`,icon:this.getCreateActionIcon(`base`),id:`base`,label:`Base file`,meta:`.base`,onSelect:()=>this.handleNewBase({parentDir:e})},{contextLabel:`New Excalidraw drawing`,group:`Diagram`,hint:`Excalidraw`,icon:this.getCreateActionIcon(`excalidraw`),id:`excalidraw`,label:`Excalidraw drawing`,meta:`.excalidraw`,onSelect:()=>this.handleNewDrawing({parentDir:e})},{contextLabel:`New draw.io diagram`,group:`Diagram`,hint:`draw.io`,icon:this.getCreateActionIcon(`drawio`),id:`drawio`,label:`draw.io diagram`,meta:`.drawio`,onSelect:()=>this.handleNewDrawio({parentDir:e})},{contextLabel:`New Mermaid diagram`,group:`Diagram`,hint:`Mermaid`,icon:this.getCreateActionIcon(`mermaid`),id:`mermaid`,label:`Mermaid diagram`,meta:`.mmd`,onSelect:()=>this.handleNewMermaid({parentDir:e})},{contextLabel:`New PlantUML diagram`,group:`Diagram`,hint:`PlantUML`,icon:this.getCreateActionIcon(`plantuml`),id:`plantuml`,label:`PlantUML diagram`,meta:`.puml`,onSelect:()=>this.handleNewPlantUml({parentDir:e})},{contextLabel:`New Structurizr workspace`,group:`Diagram`,hint:`Structurizr DSL`,icon:this.getCreateActionIcon(`structurizr`),id:`structurizr`,label:`Structurizr workspace`,meta:`.dsl`,onSelect:()=>this.handleNewStructurizr({parentDir:e})},{contextLabel:`New folder`,group:`Structure`,hint:`Folder`,icon:this.getCreateActionIcon(`folder`),id:`folder`,label:`Folder`,meta:`folder`,onSelect:()=>this.handleNewFolder({parentDir:e})}]}createContextMenuItems(e=``){return this.getCreateActions({parentDir:e}).map(e=>({label:e.contextLabel,onSelect:e.onSelect}))}getDirectoryContextMenuItems(e){return[...this.createContextMenuItems(e),{label:`Rename / move`,onSelect:()=>this.handleRenameDirectory(e)},{label:`Download`,onSelect:()=>this.handleDownloadDirectory(e)},{label:`Delete`,danger:!0,onSelect:()=>this.handleDeleteDirectory(e)}]}getFileContextMenuItems(e){return[{label:`Rename / move`,onSelect:()=>this.handleRenameFile(e)},{label:`Download`,onSelect:()=>this.handleDownloadFile(e)},{label:`Delete`,danger:!0,onSelect:()=>this.handleDelete(e)}]}showToast(e){e&&this.toastController?.show(String(e))}getCreateActionIcon(e){switch(e){case`upload`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 16V4"/><path d="m7 9 5-5 5 5"/><path d="M5 20h14"/></svg>`;case`base`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 4h7l5 5v11a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"/><path d="M14 4v5h5"/><path d="M8 13h8"/><path d="M8 17h6"/><path d="M8 9h3"/></svg>`;case`drawio`:case`plantuml`:case`structurizr`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="7" height="6" rx="1"/><rect x="14" y="4" width="7" height="6" rx="1"/><rect x="8.5" y="14" width="7" height="6" rx="1"/><path d="M10 7h4"/><path d="M17.5 10v2.5"/><path d="M6.5 10v2.5"/><path d="M6.5 12.5h11"/></svg>`;case`excalidraw`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19l7-7 3 3-7 7-3-3z"/><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><path d="M2 2l7.586 7.586"/><circle cx="11" cy="11" r="2"/></svg>`;case`folder`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>`;case`mermaid`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 7.5c0-1.38 1.12-2.5 2.5-2.5 1.04 0 1.93.64 2.3 1.56A2.5 2.5 0 0 1 14 8.5v1"/><path d="M19 16.5c0 1.38-1.12 2.5-2.5 2.5-1.04 0-1.93-.64-2.3-1.56A2.5 2.5 0 0 1 10 15.5v-1"/><path d="M8 10.5h8"/><path d="M8 13.5h8"/><path d="M10 8.5v7"/><path d="M14 8.5v7"/></svg>`;default:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>`}}showError(e,t){this.showToast(t?.message?`${e}: ${t.message}`:e)}createPendingWorkspaceRequestId(){if(!this.pendingWorkspaceRequestIds)return null;let e=crypto.randomUUID();return this.pendingWorkspaceRequestIds.add(e),e}clearPendingWorkspaceRequestId(e){e&&this.pendingWorkspaceRequestIds?.delete(e)}async runWorkspaceMutation(e){let t=this.createPendingWorkspaceRequestId();try{return await e(t)}catch(e){throw this.clearPendingWorkspaceRequestId(t),e}}openActionDialog({title:e,copy:t,label:n=`Path`,hint:r=``,note:i=``,placeholder:a=``,value:o=``,submitLabel:s=`Save`,destructive:c=!1,requiresInput:l=!0,emptyMessage:u=`A value is required`,onSubmit:d}){!this.actionDialog||!this.actionTitle||!this.actionCopy||!this.actionSubmitButton||!this.actionCancelButton||l&&!this.actionInput||(this.actionDialog.open&&(typeof this.actionDialog.close==`function`?this.actionDialog.close():(this.actionDialog.removeAttribute(`open`),this.resetActionDialog())),this.pendingAction={requiresInput:l,emptyMessage:u,onSubmit:d},this.createMenu.close({restoreFocus:!1}),this.fileExplorerOptionsMenu.close({restoreFocus:!1}),this.view?.removeContextMenu?.(),this.actionTitle.textContent=e,this.actionCopy.textContent=t,this.actionField&&(this.actionField.hidden=!l),this.actionLabel&&(this.actionLabel.textContent=n),this.actionInput&&(this.actionInput.value=o,this.actionInput.placeholder=a,this.actionInput.required=l,this.actionInput.disabled=!1),this.actionHint&&(this.actionHint.textContent=r,this.actionHint.hidden=!l||!r),this.actionNote&&(this.actionNote.textContent=i,this.actionNote.hidden=!i,this.actionNote.classList.toggle(`is-danger`,c)),this.actionSubmitButton.textContent=s,this.actionSubmitButton.disabled=!1,this.actionSubmitButton.classList.toggle(`ui-button--primary`,!c),this.actionSubmitButton.classList.toggle(`ui-button--danger`,c),this.actionCancelButton.disabled=!1,typeof this.actionDialog.showModal==`function`?this.actionDialog.showModal():this.actionDialog.setAttribute(`open`,`true`),requestAnimationFrame(()=>{if(!l||!this.actionInput){this.actionSubmitButton.focus();return}this.actionInput.focus(),o&&this.actionInput.select()}))}resetActionDialog(){this.pendingAction=null,this.actionBusy=!1,this.actionField&&(this.actionField.hidden=!1),this.actionLabel&&(this.actionLabel.textContent=`Path`),this.actionInput&&(this.actionInput.value=``,this.actionInput.placeholder=``,this.actionInput.required=!0,this.actionInput.disabled=!1),this.actionHint&&(this.actionHint.textContent=``,this.actionHint.hidden=!0),this.actionNote&&(this.actionNote.textContent=``,this.actionNote.hidden=!0,this.actionNote.classList.remove(`is-danger`)),this.actionSubmitButton&&(this.actionSubmitButton.textContent=`Save`,this.actionSubmitButton.disabled=!1,this.actionSubmitButton.className=W({variant:`primary`})),this.actionCancelButton&&(this.actionCancelButton.disabled=!1)}closeActionDialog(){if(this.actionDialog){if(this.actionDialog.open&&typeof this.actionDialog.close==`function`){this.actionDialog.close();return}this.actionDialog.removeAttribute(`open`),this.resetActionDialog()}}setActionDialogBusy(e){this.actionBusy=e,this.actionInput&&(this.actionInput.disabled=e||!(this.pendingAction?.requiresInput??!0)),this.actionCancelButton&&(this.actionCancelButton.disabled=e),this.actionSubmitButton&&(this.actionSubmitButton.disabled=e)}async handleActionSubmit(){if(!this.pendingAction?.onSubmit||this.actionBusy)return;let e=this.pendingAction.requiresInput,t=e?this.actionInput?.value.trim()??``:void 0;if(e&&!t){this.showToast(this.pendingAction.emptyMessage),this.actionInput?.focus();return}this.setActionDialogBusy(!0);let n;try{n=await this.pendingAction.onSubmit(t)}catch(e){this.showError(`Failed to complete action`,e)}if(this.setActionDialogBusy(!1),n!==!1){this.closeActionDialog();return}e&&this.actionInput&&(this.actionInput.focus(),this.actionInput.select())}async uploadVaultFiles(e=[],{parentDir:t=``}={}){let n=k(t),r=!1;for(let t of Array.from(e??[])){let e=w(t?.name),i=D(n,e);if(!e||!s(i)){this.showToast(`Unsupported file type: ${e||`unnamed file`}`);continue}try{await this.runWorkspaceMutation(e=>this.vaultClient.uploadFile({file:t,path:i,requestId:e})),r=!0,this.state.expandDirectoryPath(i,{includeLeaf:!1})}catch(t){this.showToast(`${e}: ${t?.message||`Failed to upload file`}`)}}return r&&await this.refresh(),r}async handleUploadFiles({parentDir:e=``}={}){let t=await xe({accept:Zo,multiple:!0});return t.length!==0&&this.uploadVaultFiles(t,{parentDir:e})}async createVaultFile(e,t,{openAfterCreate:n=!1,errorMessage:r=`Failed to create file`}={}){try{return await this.runWorkspaceMutation(n=>this.vaultClient.createFile($o({content:t,path:e},n))),this.state.expandDirectoryPath(e,{includeLeaf:!1}),await this.refresh(),n&&this.onFileSelect?.(e),!0}catch(e){return this.showToast(e?.message||r),!1}}async createDirectory(e){let t=k(e);if(!t)return this.showToast(`Folder path is required`),!1;try{return await this.runWorkspaceMutation(e=>this.vaultClient.createDirectory(t,$o({},e))),this.state.expandDirectoryPath(t),await this.refresh(),!0}catch(e){return this.showToast(e?.message||`Failed to create folder`),!1}}async renameVaultFile(e,t,n){let r=k(t);if(!r)return this.showToast(`File path is required`),!1;let i=d(r);if(i&&i.toLowerCase()!==String(n??``).toLowerCase())return this.showToast(`File type changes are not supported during rename. Keep the ${n} extension.`),!1;let a=i?r:`${r}${n}`;if(!w(a))return this.showToast(`File path is required`),!1;if(a===e)return!0;try{return await this.runWorkspaceMutation(t=>this.vaultClient.renameFile($o({newPath:a,oldPath:e},t))),this.state.expandDirectoryPath(a,{includeLeaf:!1}),await this.refresh(),this.state.activeFilePath===e&&(this.state.activeFilePath=a,this.onFileSelect?.(a)),!0}catch(e){return this.showToast(e?.message||`Failed to rename`),!1}}async renameDirectory(e,t){let n=k(t);if(!n)return this.showToast(`Folder path is required`),!1;if(n===e)return!0;try{if(await this.runWorkspaceMutation(t=>this.vaultClient.renameDirectory($o({newPath:n,oldPath:e},t))),this.state.replaceExpandedDirectoryPrefix(e,n),this.state.expandDirectoryPath(n),await this.refresh(),this.state.activeFilePath&&this.state.activeFilePath.startsWith(`${e}/`)){let t=Yo(this.state.activeFilePath,e,n);this.state.activeFilePath=t,this.onFileSelect?.(t)}return!0}catch(e){return this.showToast(e?.message||`Failed to rename folder`),!1}}async deleteVaultFile(e){try{return await this.runWorkspaceMutation(t=>this.vaultClient.deleteFile(e,$o({},t))),await this.refresh(),this.state.activeFilePath===e&&(this.state.activeFilePath=null,this.onFileDelete?.(e)),!0}catch(e){return this.showToast(e?.message||`Failed to delete`),!1}}async deleteDirectory(e,{recursive:t=!1}={}){try{await this.runWorkspaceMutation(n=>this.vaultClient.deleteDirectory(e,$o({recursive:t},n)));let n=this.state.activeFilePath;return await this.refresh(),this.state.removeExpandedDirectoryPrefix(e),n&&n.startsWith(`${e}/`)&&(this.state.activeFilePath=null,this.onFileDelete?.(n)),!0}catch(e){return this.showToast(e?.message||`Failed to delete folder`),!1}}planMoveEntryByDrop({destinationDirectory:e=``,sourcePath:t=``,sourceType:n=`file`}={}){let r=k(t),i=k(e),a=M(r),o=w(r);return!r||!o?{ok:!1,reason:`Invalid item to move`}:a===i?{ok:!1,reason:`Item is already in that folder`}:n===`directory`?i===r?{ok:!1,reason:`A folder cannot be moved into itself`}:i.startsWith(`${r}/`)?{ok:!1,reason:`A folder cannot be moved into one of its descendants`}:{nextPath:D(i,o),ok:!0}:{extension:d(r)||`.md`,nextPath:D(i,o),ok:!0}}canMoveEntryByDrop(e={}){return this.planMoveEntryByDrop(e).ok}async moveEntryByDrop(e={}){let t=this.planMoveEntryByDrop(e);return t.ok?e.sourceType===`directory`?this.renameDirectory(e.sourcePath,t.nextPath):this.renameVaultFile(e.sourcePath,t.nextPath,t.extension):(this.showToast(t.reason),!1)}async downloadFileEntry(e){try{return await this.vaultClient.downloadFile(e),!0}catch(e){return this.showToast(e?.message||`Failed to download file`),!1}}async downloadDirectoryEntry(e){try{return await this.vaultClient.downloadDirectory(e),!0}catch(e){return this.showToast(e?.message||`Failed to download folder`),!1}}getCreateContext(e=``){let t=k(e);return{hintPrefix:t?`Use "/" to create nested items under this folder.`:`Use "/" to place it inside a folder.`,inputLabelSuffix:t?`name or path`:`path`,note:t?`Parent folder: ${t}`:``,normalizedParentDir:t}}openRootCreateMenu({anchor:e=this.createButton}={}){this.openCreateMenu({anchor:e,parentDir:``})}openCreateMenu({anchor:e=this.createButton,parentDir:t=``}={}){this.view?.removeContextMenu?.(),this.fileExplorerOptionsMenu.close({restoreFocus:!1}),this.createMenu.toggle({anchor:e,items:this.getCreateActions({parentDir:t}),title:`Create`})}openFileExplorerOptionsMenu({anchor:e=this.fileExplorerOptionsButton}={}){this.view?.removeContextMenu?.(),this.createMenu.close({restoreFocus:!1}),this.fileExplorerOptionsMenu.toggle({anchor:e,items:[{icon:`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6S2 12 2 12Z"></path><circle cx="12" cy="12" r="2.5"></circle></svg>`,id:`show-file-extensions`,label:`Show file extensions`,meta:this.showFileExtensions?`On`:`Off`,onSelect:()=>{this.showFileExtensions=!this.showFileExtensions,this.onShowFileExtensionsChange?.(this.showFileExtensions)}}],title:`File explorer options`})}handleNewFile({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create markdown file`,copy:t.normalizedParentDir?`Add a new note inside the selected folder. It opens immediately after creation.`:`Add a new note to the vault. It opens immediately after creation.`,label:`File ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".md" is added automatically.`,note:t.note,placeholder:t.normalizedParentDir?`my-note`:`notes/my-note`,submitLabel:`Create file`,emptyMessage:`File path is required`,onSubmit:e=>{let n=k(e);if(!n)return this.showToast(`File path is required`),!1;let r=C(D(t.normalizedParentDir,n),`.md`);return this.createVaultFile(r,re(r),{errorMessage:`Failed to create file`,openAfterCreate:!0})}})}handleNewBase({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create base file`,copy:t.normalizedParentDir?"Add a new `.base` file inside the selected folder. It opens immediately after creation.":"Add a new `.base` file to the vault. It opens immediately after creation.",label:`Base ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".base" is added automatically.`,note:t.note,placeholder:t.normalizedParentDir?`table-view`:`views/table-view`,submitLabel:`Create base`,emptyMessage:`Base path is required`,onSubmit:e=>{let n=k(e);if(!n)return this.showToast(`Base path is required`),!1;let r=x(D(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create base file`,openAfterCreate:!0})}})}handleNewFolder({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create folder`,copy:t.normalizedParentDir?`Add a new folder inside the selected folder.`:`Add a new folder to organize notes and diagrams.`,label:`Folder ${t.inputLabelSuffix}`,hint:t.hintPrefix,note:t.note,placeholder:t.normalizedParentDir?`archive`:`notes/archive`,submitLabel:`Create folder`,emptyMessage:`Folder path is required`,onSubmit:e=>this.createDirectory(D(t.normalizedParentDir,e))})}handleNewDrawing({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create Excalidraw drawing`,copy:t.normalizedParentDir?`Start a new drawing inside the selected folder.`:`Start a new drawing file in the vault.`,label:`Drawing ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".excalidraw" is added automatically.`,note:t.note,placeholder:t.normalizedParentDir?`architecture`:`diagrams/architecture`,submitLabel:`Create drawing`,emptyMessage:`Drawing path is required`,onSubmit:e=>{let n=k(e);if(!n)return this.showToast(`Drawing path is required`),!1;let r=C(D(t.normalizedParentDir,n),`.excalidraw`);return this.createVaultFile(r,Qo(),{errorMessage:`Failed to create drawing`,openAfterCreate:!0})}})}handleNewMermaid({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create Mermaid diagram`,copy:t.normalizedParentDir?"Create a new `.mmd` or `.mermaid` file inside the selected folder.":"Create a new `.mmd` or `.mermaid` file with starter diagram content.",label:`Diagram ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".mmd" is added automatically unless you enter ".mermaid".`,note:t.note,placeholder:t.normalizedParentDir?`flow`:`diagrams/flow`,submitLabel:`Create diagram`,emptyMessage:`Diagram path is required`,onSubmit:e=>{let n=k(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=S(D(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create Mermaid diagram`,openAfterCreate:!0})}})}handleNewDrawio({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create draw.io diagram`,copy:t.normalizedParentDir?"Create a new `.drawio` diagram inside the selected folder.":"Create a new `.drawio` diagram with a native starter document.",label:`Diagram ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".drawio" is added automatically.`,note:t.note,placeholder:t.normalizedParentDir?`architecture`:`diagrams/architecture`,submitLabel:`Create diagram`,emptyMessage:`Diagram path is required`,onSubmit:e=>{let n=k(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=j(D(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create draw.io diagram`,openAfterCreate:!0})}})}handleNewPlantUml({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create PlantUML diagram`,copy:t.normalizedParentDir?"Create a new `.puml` or `.plantuml` file inside the selected folder.":"Create a new `.puml` or `.plantuml` file with starter diagram content.",label:`Diagram ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".puml" is added automatically unless you enter ".plantuml".`,note:t.note,placeholder:t.normalizedParentDir?`sequence-flow`:`diagrams/sequence-flow`,submitLabel:`Create diagram`,emptyMessage:`Diagram path is required`,onSubmit:e=>{let n=k(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=O(D(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create PlantUML diagram`,openAfterCreate:!0})}})}handleNewStructurizr({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create Structurizr workspace`,copy:t.normalizedParentDir?`Create a collaborative C4 workspace inside the selected folder.`:`Create a collaborative C4 workspace in the vault.`,label:`Workspace ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".dsl" is added automatically. workspace.dsl is conventional; any workspace .dsl file can render.`,note:t.note,placeholder:`workspace`,submitLabel:`Create workspace`,emptyMessage:`Workspace path is required`,onSubmit:e=>{let n=k(e);if(!n)return this.showToast(`Workspace path is required`),!1;let r=ae(D(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create Structurizr workspace`,openAfterCreate:!0})}})}handleRenameFile(e){let t=d(e)||`.md`;this.openActionDialog({title:`Rename or move file`,copy:`Update the relative path without changing the file type.`,label:`Path`,hint:`Use "/" to move the file into another folder. ${t} is kept automatically.`,value:e,submitLabel:`Save file path`,emptyMessage:`File path is required`,onSubmit:n=>this.renameVaultFile(e,n,t)})}handleRenameDirectory(e){this.openActionDialog({title:`Rename or move folder`,copy:`Update the relative path for this folder and everything inside it.`,label:`Path`,hint:`Use "/" to move the folder into another location in the vault.`,value:e,submitLabel:`Save folder path`,emptyMessage:`Folder path is required`,onSubmit:t=>this.renameDirectory(e,t)})}handleDelete(e){this.openActionDialog({title:`Delete file`,copy:`This permanently removes the file from the vault.`,note:e,submitLabel:`Delete file`,destructive:!0,requiresInput:!1,onSubmit:()=>this.deleteVaultFile(e)})}handleDeleteDirectory(e){let{directoryCount:t,fileCount:n}=this.state.getDirectoryDescendantSummary(e),r=t>0||n>0,i=r?`This will permanently remove ${Xo(n,`file`,`files`)} and ${Xo(t,`nested folder`,`nested folders`)} inside this folder.`:`This permanently removes the empty folder from the vault.`;this.openActionDialog({title:r?`Delete folder and contents`:`Delete folder`,copy:i,note:e,submitLabel:r?`Delete folder and contents`:`Delete folder`,destructive:!0,requiresInput:!1,onSubmit:()=>this.deleteDirectory(e,{recursive:r})})}handleDownloadFile(e){this.downloadFileEntry(e)}handleDownloadDirectory(e){this.downloadDirectoryEntry(e)}};function ts(e,t=[],n=[],r=[]){for(let i of e)if(!(!i?.path||!i?.type)){if(n.push({lowerPath:String(i.path).toLowerCase(),name:i.name,path:i.path,type:i.type}),i.type===`file`||i.type===`base`||i.type===`excalidraw`||i.type===`drawio`||i.type===`mermaid`||i.type===`plantuml`||i.type===`structurizr`||i.type===`pdf`||i.type===`image`){t.push(i.path),r.push({mtimeMs:i.mtimeMs,path:i.path});continue}i.type===`directory`&&Array.isArray(i.children)&&ts(i.children,t,n,r)}return{fileEntries:r,files:t,searchEntries:n}}function ns(e,t){for(let n of e??[]){if(n?.path===t)return n;if(n?.type===`directory`&&Array.isArray(n.children)){let e=ns(n.children,t);if(e)return e}}return null}function rs(e){let t=0,n=0;for(let r of e?.children??[]){if(r?.type===`directory`){t+=1;let e=rs(r);t+=e.directoryCount,n+=e.fileCount;continue}n+=1}return{directoryCount:t,fileCount:n}}function is(e,t,n){return e===t?n:`${n}${e.slice(t.length)}`}var as=class{constructor(){this.tree=[],this.flatFiles=[],this.flatFileEntries=[],this.flatSearchEntries=[],this.activeFilePath=null,this.expandedDirs=new Set,this.searchQuery=``}setTree(e){this.tree=Array.isArray(e)?e:[];let t=ts(this.tree,[],[],[]);this.flatFiles=t.files,this.flatFileEntries=t.fileEntries,this.flatSearchEntries=t.searchEntries}setSearchQuery(e){this.searchQuery=String(e??``)}getSearchMatches(){let e=this.searchQuery.trim().toLowerCase();return e?this.flatSearchEntries.filter(t=>t.type!==`directory`&&t.lowerPath.includes(e)).map(e=>({name:e.name,path:e.path,type:e.type})):[]}getNode(e){return ns(this.tree,e)}getDirectoryDescendantSummary(e){let t=this.getNode(e);return!t||t.type!==`directory`?{directoryCount:0,fileCount:0}:rs(t)}setActiveFile(e){this.activeFilePath=e||null,e&&this.expandDirectoryPath(e,{includeLeaf:!1})}toggleDirectory(e){return this.expandedDirs.has(e)?(this.expandedDirs.delete(e),!1):(this.expandedDirs.add(e),!0)}expandDirectoryPath(e,{includeLeaf:t=!0}={}){let n=k(e);if(!n)return;let r=n.split(`/`),i=t?r.length:Math.max(r.length-1,0),a=``;for(let e=0;e<i;e+=1)a=a?`${a}/${r[e]}`:r[e],this.expandedDirs.add(a)}replaceExpandedDirectoryPrefix(e,t){let n=new Set;this.expandedDirs.forEach(r=>{if(r===e||r.startsWith(`${e}/`)){n.add(is(r,e,t));return}n.add(r)}),this.expandedDirs=n}removeExpandedDirectoryPrefix(e){let t=new Set;this.expandedDirs.forEach(n=>{n===e||n.startsWith(`${e}/`)||t.add(n)}),this.expandedDirs=t}};function os(e=[],t=``){for(let n of e){if(n.path===t)return n;if(n.type===`directory`&&Array.isArray(n.children)){let e=os(n.children,t);if(e)return e}}return null}var ss=420,cs=10,ls=700,us=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onEntryDrop:t,onDirectoryToggle:n,onFileContextMenu:r,onFileSelect:i,onSearchChange:a,onTreeContextMenu:o,onValidateDrop:s}){this.onEntryDrop=t,this.onDirectoryToggle=n,this.onFileContextMenu=r,this.onFileSelect=i,this.onSearchChange=a,this.onTreeContextMenu=o,this.onValidateDrop=s,this.mobileBreakpointQuery=e,this.treeContainer=document.getElementById(`fileTree`),this.searchInput=document.getElementById(`fileSearchInput`),this.searchStatus=document.getElementById(`fileSearchStatus`),this.renderedDirectoryWrappers=new Map,this.renderedChildContainers=new Map,this.renderedFileItems=new Map,this.lastRenderMode=`tree`,this.longPressTimer=0,this.longPressContext=null,this.suppressedActivationTarget=null,this.contextMenuCloseHandler=null,this.actionSheetCloseHandler=null,this.dragSource=null,this.currentSearchQuery=``,this.activeDropTarget=null,this.invalidDropAttempt=null,this.autoExpandTimer=0,this.autoExpandTargetPath=``,this.rootDropZone=null,this.threadCounts=new Map,this.showFileExtensions=!1}initialize(){this.searchInput?.addEventListener(`input`,e=>{this.onSearchChange?.(e.target.value)}),this.treeContainer?.addEventListener(`contextmenu`,e=>{e.target.closest(`.file-tree-item`)||(e.preventDefault(),this.onTreeContextMenu?.(e))}),this.treeContainer?.addEventListener(`pointerdown`,e=>{e.target.closest(`.file-tree-item`)||this.startLongPress(e,()=>{this.onTreeContextMenu?.({clientX:Number(e.clientX||0),clientY:Number(e.clientY||0),preventDefault(){},target:this.treeContainer})},this.treeContainer)}),this.treeContainer?.addEventListener(`pointermove`,e=>{this.handleLongPressPointerMove(e)},{passive:!0}),this.treeContainer?.addEventListener(`pointerup`,()=>{this.cancelLongPress()}),this.treeContainer?.addEventListener(`pointercancel`,()=>{this.cancelLongPress()}),this.treeContainer?.addEventListener(`scroll`,()=>{this.cancelLongPress()},{passive:!0}),this.treeContainer?.addEventListener(`dragover`,e=>{this.handleTreeDragOver(e)}),this.treeContainer?.addEventListener(`drop`,e=>{this.handleTreeDrop(e)}),this.treeContainer?.addEventListener(`dragleave`,e=>{this.handleTreeDragLeave(e)})}updateSearchStatus(e,t=null){if(!this.searchStatus)return;let n=String(e??``).trim()&&Number.isInteger(t)?`${t} match${t===1?``:`es`}`:``;this.searchStatus.textContent=n,this.searchStatus.classList.toggle(`hidden`,!n)}revealFile(e){this.renderedFileItems.get(e)?.scrollIntoView({block:`nearest`})}setActiveFile(e){if(this.treeContainer?.querySelector(`.file-tree-file.active`)?.classList.remove(`active`),!e)return!0;let t=this.renderedFileItems.get(e);return t?.classList.add(`active`),!!t}setThreadCounts(e){this.threadCounts=e instanceof Map?e:new Map,this.renderedFileItems.forEach((e,t)=>{let n=Number(this.threadCounts.get(t)??0)||0,r=e.querySelector(`.file-tree-comment-count`);if(e.classList.toggle(`has-comments`,n>0),e.setAttribute(`aria-label`,`${t}${n>0?`, ${n} open comment thread${n===1?``:`s`}`:``}`),n<=0){delete e.dataset.threadCount,r?.remove();return}e.dataset.threadCount=String(n),r||(r=document.createElement(`span`),r.className=`file-tree-comment-count`,e.appendChild(r)),r.textContent=String(n),r.setAttribute(`aria-hidden`,`true`)})}render({activeFilePath:e,changedPaths:t=null,expandedDirs:n,reset:r=!1,searchMatches:i,searchQuery:a,showFileExtensions:o=!1,threadCounts:s=new Map,tree:c}){if(!this.treeContainer)return;if(this.threadCounts=s instanceof Map?s:new Map,this.showFileExtensions=!!o,this.currentSearchQuery=String(a??``).trim(),this.currentSearchQuery&&this.clearDragFeedback(),this.searchInput&&this.searchInput.value!==a&&(this.searchInput.value=a),this.updateSearchStatus(a,this.currentSearchQuery?i.length:null),this.currentSearchQuery){this.lastRenderMode=`search`,this.renderSearchResults(i,e);return}if(r||this.lastRenderMode!==`tree`||!Array.isArray(t)||t.length===0){this.renderFullTree(c,{activeFilePath:e,expandedDirs:n}),this.lastRenderMode=`tree`;return}let l=Array.from(new Set(t.map(e=>M(e)))).sort((e,t)=>e.split(`/`).length-t.split(`/`).length).filter((e,t,n)=>!n.slice(0,t).some(t=>t&&e.startsWith(`${t}/`)));if(l.includes(``)){this.renderFullTree(c,{activeFilePath:e,expandedDirs:n}),this.lastRenderMode=`tree`;return}for(let t of l)if(!this.rerenderDirectoryBranch(t,c,{activeFilePath:e,expandedDirs:n})){this.renderFullTree(c,{activeFilePath:e,expandedDirs:n}),this.lastRenderMode=`tree`;return}this.lastRenderMode=`tree`}renderSearchResults(e,t){if(!this.treeContainer)return;if(this.resetTreeIndexes(),this.treeContainer.innerHTML=``,this.rootDropZone=null,e.length===0){this.treeContainer.innerHTML=`<div class="file-tree-empty">No matches</div>`;return}let n=document.createDocumentFragment();for(let r of e)n.appendChild(this.createFileItem({activeFilePath:t,depth:0,filePath:r.path,fileType:r.type||(c(r.path)??`file`),name:r.name||w(r.path),searchResult:!0}));this.treeContainer.appendChild(n)}renderFullTree(e,{activeFilePath:t,expandedDirs:n}){if(this.resetTreeIndexes(),this.treeContainer.innerHTML=``,this.rootDropZone=null,e.length===0){this.treeContainer.innerHTML=`<div class="file-tree-empty">No vault files found</div>`;return}let r=document.createDocumentFragment();r.appendChild(this.createRootDropZone()),this.renderNodes(e,r,{activeFilePath:t,depth:0,expandedDirs:n}),this.treeContainer.appendChild(r)}resetTreeIndexes(){this.renderedDirectoryWrappers.clear(),this.renderedChildContainers.clear(),this.renderedFileItems.clear()}renderNodes(e,t,{activeFilePath:n,depth:r,expandedDirs:i}){for(let a of e){if(a.type===`directory`){t.appendChild(this.createDirectoryItem(a,{activeFilePath:n,depth:r,expandedDirs:i}));continue}t.appendChild(this.createFileItem({activeFilePath:n,depth:r,filePath:a.path,fileType:a.type,name:a.name}))}}createDirectoryItem(e,{activeFilePath:t,depth:n,expandedDirs:r}){let i=document.createElement(`div`);i.className=`file-tree-group`;let a=document.createElement(`button`);a.className=`file-tree-item file-tree-dir`,a.title=e.path,a.setAttribute(`aria-label`,e.path),a.style.setProperty(`--depth`,n),a.dataset.depth=n;let o=r.has(e.path);if(a.setAttribute(`aria-expanded`,String(o)),a.dataset.path=e.path,a.dataset.entryType=`directory`,a.innerHTML=`
181
- <svg class="file-tree-chevron${o?` expanded`:``}" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 18 15 12 9 6"/></svg>
182
- <svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>
183
- <span class="file-tree-name">${y(e.name)}</span>
184
- `,this.configureDragSource(a,{path:e.path,type:`directory`}),this.bindDirectoryDropTarget(a,e.path),a.addEventListener(`click`,t=>{this.consumeSuppressedActivation(a,t)||this.onDirectoryToggle?.(e.path)}),a.addEventListener(`contextmenu`,t=>{t.preventDefault(),this.onFileContextMenu?.(t,{directoryPath:e.path,type:`directory`})}),this.bindLongPress(a,()=>{this.onFileContextMenu?.(this.createLongPressEvent(a),{directoryPath:e.path,type:`directory`})}),i.appendChild(a),this.renderedDirectoryWrappers.set(e.path,i),o&&Array.isArray(e.children)){let a=document.createElement(`div`);a.className=`file-tree-children`,this.renderedChildContainers.set(e.path,a),this.renderNodes(e.children,a,{activeFilePath:t,depth:n+1,expandedDirs:r}),i.appendChild(a)}else this.renderedChildContainers.delete(e.path);return i}rerenderDirectoryBranch(e,t,{activeFilePath:n,expandedDirs:r}){let i=this.renderedDirectoryWrappers.get(e),a=os(t,e);if(!i||a?.type!==`directory`)return!1;let o=i.querySelector(`.file-tree-dir`),s=r.has(e);o?.setAttribute(`aria-expanded`,String(s)),o?.querySelector(`.file-tree-chevron`)?.classList.toggle(`expanded`,s);let c=Number(o?.dataset.depth??0),l=this.renderedChildContainers.get(e)??i.querySelector(`.file-tree-children`);return this.clearRenderedDescendants(e),s?(l?l.innerHTML=``:(l=document.createElement(`div`),l.className=`file-tree-children`,i.appendChild(l)),this.renderedChildContainers.set(e,l),this.renderNodes(a.children??[],l,{activeFilePath:n,depth:c+1,expandedDirs:r}),!0):(l?.remove(),this.renderedChildContainers.delete(e),!0)}clearRenderedDescendants(e){let t=`${e}/`;Array.from(this.renderedDirectoryWrappers.keys()).forEach(e=>{e.startsWith(t)&&this.renderedDirectoryWrappers.delete(e)}),Array.from(this.renderedChildContainers.keys()).forEach(e=>{e.startsWith(t)&&this.renderedChildContainers.delete(e)}),Array.from(this.renderedFileItems.keys()).forEach(e=>{e.startsWith(t)&&this.renderedFileItems.delete(e)})}createFileItem({activeFilePath:e,depth:t,filePath:n,fileType:r=`file`,name:i,searchResult:a=!1}){let s=document.createElement(`button`),c=M(n);s.className=`file-tree-item file-tree-file${a?` file-tree-search-result`:``}`,s.title=n;let l=Number(this.threadCounts.get(n)??0);s.setAttribute(`aria-label`,`${n}${l>0?`, ${l} open comment thread${l===1?``:`s`}`:``}`);let u=r===`drawio`,d=r===`excalidraw`,f=r===`base`,p=r===`image`,m=r===`pdf`,h=r===`mermaid`,g=r===`plantuml`,_=r===`structurizr`;f&&s.classList.add(`is-base`),u&&s.classList.add(`is-drawio`),d&&s.classList.add(`is-excalidraw`),p&&s.classList.add(`is-image`),m&&s.classList.add(`is-pdf`),h&&s.classList.add(`is-mermaid`),g&&s.classList.add(`is-plantuml`),_&&s.classList.add(`is-structurizr`),n===e&&s.classList.add(`active`),l>0&&s.classList.add(`has-comments`),s.style.setProperty(`--depth`,t),s.dataset.depth=t,s.dataset.path=n,s.dataset.entryType=`file`,l>0&&(s.dataset.threadCount=String(l));let v=this.showFileExtensions||a?String(i??``):o(i),ee=a?`<span class="file-tree-search-copy">
185
- <span class="file-tree-name">${y(v)}</span>
186
- ${c?`<span class="file-tree-search-path">${y(c)}</span>`:``}
187
- </span>`:`<span class="file-tree-name">${y(v)}</span>`;return s.innerHTML=`
188
- ${pt(n)}
189
- ${ee}
190
- ${l>0?`<span class="file-tree-comment-count" aria-hidden="true">${l}</span>`:``}
191
- `,this.configureDragSource(s,{path:n,type:`file`}),s.addEventListener(`click`,e=>{this.consumeSuppressedActivation(s,e)||this.onFileSelect?.(n)}),s.addEventListener(`contextmenu`,e=>{e.preventDefault(),this.onFileContextMenu?.(e,{filePath:n,type:`file`})}),this.bindLongPress(s,()=>{this.onFileContextMenu?.(this.createLongPressEvent(s),{filePath:n,type:`file`})}),this.renderedFileItems.set(n,s),s}isMobileViewport(){return!!this.mobileBreakpointQuery?.matches}isDragAndDropEnabled(){return!this.isMobileViewport()&&!this.currentSearchQuery}configureDragSource(e,t){if(!(e instanceof HTMLElement))return;let n=this.isDragAndDropEnabled();e.draggable=n,n&&(e.addEventListener(`dragstart`,n=>{this.dragSource={path:t.path,type:t.type},document.body?.classList.add(`is-file-tree-dragging`),this.treeContainer&&(this.treeContainer.dataset.dragActive=`true`),e.classList.add(`is-dragging`),n.dataTransfer&&(n.dataTransfer.effectAllowed=`move`,n.dataTransfer.setData(`text/plain`,t.path))}),e.addEventListener(`dragend`,()=>{e.classList.remove(`is-dragging`);let t=this.dragSource;this.invalidDropAttempt&&t&&this.onEntryDrop?.(this.invalidDropAttempt),this.dragSource=null,this.invalidDropAttempt=null,this.clearDragFeedback()}),t.type===`file`&&(e.addEventListener(`dragenter`,e=>{this.handleNonDropTargetDragOver(e)}),e.addEventListener(`dragover`,e=>{this.handleNonDropTargetDragOver(e)})))}bindDirectoryDropTarget(e,t){!(e instanceof HTMLElement)||this.isMobileViewport()||(e.addEventListener(`dragenter`,n=>{this.handleDirectoryDragEnter(n,e,t)}),e.addEventListener(`dragover`,n=>{this.handleDirectoryDragOver(n,e,t)}),e.addEventListener(`drop`,e=>{this.handleDirectoryDrop(e,t)}))}createRootDropZone(){let e=document.createElement(`div`);return e.className=`file-tree-root-drop-zone`,e.textContent=`Drop here to move to vault root`,e.addEventListener(`dragenter`,e=>{this.handleRootZoneDragEnter(e)}),e.addEventListener(`dragover`,e=>{this.handleRootZoneDragOver(e)}),e.addEventListener(`drop`,e=>{this.handleRootZoneDrop(e)}),this.rootDropZone=e,e}validateDrop(e){return!this.dragSource||this.currentSearchQuery?!1:this.onValidateDrop?.({destinationDirectory:e,sourcePath:this.dragSource.path,sourceType:this.dragSource.type})===!0}setDropTarget(e){if(this.activeDropTarget?.element&&this.activeDropTarget.element!==e?.element&&this.activeDropTarget.element.classList.remove(`is-drop-target`,`is-drop-invalid`),this.activeDropTarget?.root&&!e?.root&&this.treeContainer?.classList.remove(`is-drop-target-root`,`is-drop-invalid`),this.activeDropTarget?.rootZone&&!e?.rootZone&&this.rootDropZone?.classList.remove(`is-drop-target`,`is-drop-invalid`),this.activeDropTarget=e,!e||e.isValid?this.invalidDropAttempt=null:this.dragSource&&(this.invalidDropAttempt={destinationDirectory:e.destinationDirectory||``,sourcePath:this.dragSource.path,sourceType:this.dragSource.type}),e){if(e.root){this.treeContainer?.classList.toggle(`is-drop-target-root`,e.isValid),this.treeContainer?.classList.toggle(`is-drop-invalid`,!e.isValid);return}if(e.rootZone){this.rootDropZone?.classList.toggle(`is-drop-target`,e.isValid),this.rootDropZone?.classList.toggle(`is-drop-invalid`,!e.isValid);return}e.element.classList.toggle(`is-drop-target`,e.isValid),e.element.classList.toggle(`is-drop-invalid`,!e.isValid)}}scheduleAutoExpand(e,t){e.getAttribute(`aria-expanded`)!==`true`&&this.autoExpandTargetPath!==t&&(this.cancelAutoExpand(),this.autoExpandTargetPath=t,this.autoExpandTimer=window.setTimeout(()=>{this.autoExpandTimer=0,this.autoExpandTargetPath=``,e.isConnected&&e.getAttribute(`aria-expanded`)!==`true`&&this.onDirectoryToggle?.(t)},ls))}cancelAutoExpand(){this.autoExpandTimer&&=(window.clearTimeout(this.autoExpandTimer),0),this.autoExpandTargetPath=``}clearDragFeedback(){this.cancelAutoExpand(),this.setDropTarget(null),document.body?.classList.remove(`is-file-tree-dragging`),this.treeContainer&&delete this.treeContainer.dataset.dragActive}handleDirectoryDragEnter(e,t,n){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let r=this.validateDrop(n);this.setDropTarget({destinationDirectory:n,element:t,isValid:r,root:!1}),r?this.scheduleAutoExpand(t,n):this.cancelAutoExpand()}handleDirectoryDragOver(e,t,n){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let r=this.validateDrop(n);e.dataTransfer&&(e.dataTransfer.dropEffect=r?`move`:`none`),this.setDropTarget({destinationDirectory:n,element:t,isValid:r,root:!1}),r?this.scheduleAutoExpand(t,n):this.cancelAutoExpand()}handleDirectoryDrop(e,t){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let n={destinationDirectory:t,sourcePath:this.dragSource.path,sourceType:this.dragSource.type};this.clearDragFeedback(),this.onEntryDrop?.(n)}handleTreeDragOver(e){if(!this.dragSource||!this.treeContainer||e.target.closest(`.file-tree-dir`)||e.target.closest(`.file-tree-item`))return;e.preventDefault(),this.cancelAutoExpand();let t=this.validateDrop(``);e.dataTransfer&&(e.dataTransfer.dropEffect=t?`move`:`none`),this.setDropTarget({destinationDirectory:``,element:this.treeContainer,isValid:t,root:!0})}handleTreeDrop(e){if(!this.dragSource||!this.treeContainer||e.target.closest(`.file-tree-dir`)||e.target.closest(`.file-tree-item`))return;e.preventDefault();let t={destinationDirectory:``,sourcePath:this.dragSource.path,sourceType:this.dragSource.type};this.clearDragFeedback(),this.onEntryDrop?.(t)}handleTreeDragLeave(e){if(!this.dragSource||!this.treeContainer)return;let t=e.relatedTarget;t&&this.treeContainer.contains(t)||this.clearDragFeedback()}handleRootZoneDragEnter(e){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let t=this.validateDrop(``);this.cancelAutoExpand(),this.setDropTarget({destinationDirectory:``,element:this.rootDropZone,isValid:t,rootZone:!0})}handleRootZoneDragOver(e){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let t=this.validateDrop(``);e.dataTransfer&&(e.dataTransfer.dropEffect=t?`move`:`none`),this.cancelAutoExpand(),this.setDropTarget({destinationDirectory:``,element:this.rootDropZone,isValid:t,rootZone:!0})}handleRootZoneDrop(e){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let t={destinationDirectory:``,sourcePath:this.dragSource.path,sourceType:this.dragSource.type};this.clearDragFeedback(),this.onEntryDrop?.(t)}handleNonDropTargetDragOver(e){this.dragSource&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect=`none`),this.clearDragFeedback())}bindLongPress(e,t){!(e instanceof HTMLElement)||typeof t!=`function`||(e.addEventListener(`pointerdown`,n=>{this.startLongPress(n,t,e)}),e.addEventListener(`pointermove`,e=>{this.handleLongPressPointerMove(e)},{passive:!0}),e.addEventListener(`pointerup`,()=>{this.cancelLongPress()}),e.addEventListener(`pointercancel`,()=>{this.cancelLongPress()}),e.addEventListener(`pointerleave`,()=>{this.cancelLongPress()}))}startLongPress(e,t,n=null){this.isMobileViewport()&&[`touch`,`pen`].includes(String(e.pointerType||``))&&Number(e.button??0)===0&&(this.cancelLongPress(),this.longPressContext={callback:t,pointerId:e.pointerId,startX:Number(e.clientX||0),startY:Number(e.clientY||0),target:n??e.currentTarget??e.target??null},this.longPressTimer=window.setTimeout(()=>{let e=this.longPressContext;this.longPressTimer=0,e&&(this.suppressedActivationTarget=e.target,e.callback(),this.longPressContext=null)},ss))}handleLongPressPointerMove(e){if(!this.longPressContext||e.pointerId!==this.longPressContext.pointerId)return;let t=Math.abs(Number(e.clientX||0)-this.longPressContext.startX),n=Math.abs(Number(e.clientY||0)-this.longPressContext.startY);(t>cs||n>cs)&&this.cancelLongPress()}cancelLongPress(){this.longPressTimer&&=(window.clearTimeout(this.longPressTimer),0),this.longPressContext=null}createLongPressEvent(e){return{clientX:this.longPressContext?.startX??0,clientY:this.longPressContext?.startY??0,preventDefault(){},stopPropagation(){},target:e}}consumeSuppressedActivation(e,t){return this.suppressedActivationTarget===e&&(this.suppressedActivationTarget=null,t?.preventDefault?.(),t?.stopPropagation?.(),!0)}showContextMenu(e,t){if(this.removeContextMenu(),!Array.isArray(t)||t.length===0)return;if(this.isMobileViewport()){this.showActionSheet(t);return}let n=document.createElement(`div`);n.className=`file-context-menu`;for(let e of t){let t=document.createElement(`button`);t.className=`file-context-item${e.danger?` file-context-danger`:``}`,t.textContent=e.label,t.addEventListener(`click`,()=>{this.removeContextMenu(),e.onSelect?.()}),n.appendChild(t)}document.body.appendChild(n);let r=n.getBoundingClientRect(),i=Math.max(8,window.innerWidth-r.width-8),a=Math.max(8,window.innerHeight-r.height-8);n.style.left=`${Math.max(8,Math.min(e.clientX,i))}px`,n.style.top=`${Math.max(8,Math.min(e.clientY,a))}px`;let o=e=>{n.contains(e.target)||this.removeContextMenu()};this.contextMenuCloseHandler=o,setTimeout(()=>document.addEventListener(`click`,o),0)}showActionSheet(e){let t=document.createElement(`button`);t.type=`button`,t.className=`file-action-sheet-backdrop`,t.setAttribute(`aria-label`,`Close file actions`);let n=document.createElement(`div`);n.className=`file-action-sheet`,e.forEach(e=>{let t=document.createElement(`button`);t.type=`button`,t.className=W({variant:`secondary`,extra:[`file-action-sheet-item`,e.danger?`file-context-danger`:``]}),t.textContent=e.label,t.addEventListener(`click`,()=>{this.removeContextMenu(),e.onSelect?.()}),n.appendChild(t)});let r=document.createElement(`button`);r.type=`button`,r.className=W({variant:`ghost`,extra:`file-action-sheet-item`}),r.textContent=`Cancel`,r.addEventListener(`click`,()=>{this.removeContextMenu()}),n.appendChild(r),t.addEventListener(`click`,()=>{this.removeContextMenu()}),document.body.append(t,n),this.actionSheetCloseHandler=()=>{t.remove(),n.remove(),this.actionSheetCloseHandler=null}}removeContextMenu(){this.cancelLongPress(),this.clearDragFeedback(),document.querySelectorAll(`.file-context-menu`).forEach(e=>e.remove()),this.contextMenuCloseHandler&&=(document.removeEventListener(`click`,this.contextMenuCloseHandler),null),this.actionSheetCloseHandler?.()}},ds=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onFileSelect:t,onFileDelete:n,pendingWorkspaceRequestIds:r=null,onShowFileExtensionsChange:i,showFileExtensions:a=!1,toastController:o,vaultClient:s}){this.onFileSelect=t,this.onFileDelete=n,this.onShowFileExtensionsChange=i,this.toastController=o,this.vaultClient=s,this.state=new as,this.showFileExtensions=!!a,this.threadCounts=new Map,this.view=new us({mobileBreakpointQuery:e,onDirectoryToggle:e=>{this.state.toggleDirectory(e),this.view.rerenderDirectoryBranch(e,this.state.tree,{activeFilePath:this.state.activeFilePath,expandedDirs:this.state.expandedDirs})||this.renderTree()},onEntryDrop:e=>this.actionController.moveEntryByDrop(e),onFileContextMenu:(e,t)=>{if(t.type===`directory`){this.view.showContextMenu(e,this.actionController.getDirectoryContextMenuItems(t.directoryPath));return}this.view.showContextMenu(e,this.actionController.getFileContextMenuItems(t.filePath))},onFileSelect:e=>{this.onFileSelect?.(e)},onValidateDrop:e=>this.actionController.canMoveEntryByDrop(e),onSearchChange:e=>{this.state.setSearchQuery(e),this.renderTree()},onTreeContextMenu:e=>{this.view.showContextMenu(e,this.actionController.createContextMenuItems())}}),this.actionController=new es({mobileBreakpointQuery:e,onFileDelete:this.onFileDelete,onFileSelect:this.onFileSelect,onShowFileExtensionsChange:e=>{this.showFileExtensions=!!e,this.onShowFileExtensionsChange?.(this.showFileExtensions),this.renderTree()},pendingWorkspaceRequestIds:r,showFileExtensions:this.showFileExtensions,refresh:()=>this.refresh(),state:this.state,toastController:this.toastController,vaultClient:this.vaultClient,view:this.view})}initialize(){this.view.initialize(),this.actionController.initialize()}async refresh(){try{let e=await this.vaultClient.readTree();this.setTree(e.tree||[])}catch(e){console.error(`[explorer] Failed to load file tree:`,e.message)}}setTree(e,{changedPaths:t=null,reset:n=!1}={}){this.state.setTree(e),this.renderTree({changedPaths:t,reset:n})}setActiveFile(e){let t=this.state.expandedDirs.size;if(this.state.setActiveFile(e),this.state.searchQuery){this.view.setActiveFile(e);return}(this.state.expandedDirs.size!==t||!this.view.setActiveFile(e))&&this.renderTree()}setThreadCounts(e=new Map){this.threadCounts=e instanceof Map?new Map(e):new Map(Object.entries(e??{})),this.view.setThreadCounts(this.threadCounts)}revealFile(e,{clearSearch:t=!1}={}){t&&this.state.setSearchQuery(``),this.state.setActiveFile(e),this.renderTree({reset:t}),this.view.revealFile(e)}get flatFiles(){return this.state.flatFiles}get fileEntries(){return this.state.flatFileEntries}get flatDocumentFiles(){return this.state.flatFiles.filter(e=>!l(e))}renderTree({changedPaths:e=null,reset:t=!1}={}){this.view.render({activeFilePath:this.state.activeFilePath,changedPaths:e,expandedDirs:this.state.expandedDirs,reset:t,searchMatches:this.state.getSearchMatches(),searchQuery:this.state.searchQuery,showFileExtensions:this.showFileExtensions,threadCounts:this.threadCounts,tree:this.state.tree})}},fs=30;function ps(e=``){let t=w(e),n=M(e);return n?`
192
- <span class="file-history-path">${y(t)}</span>
193
- <span class="file-history-dir">${y(n)}</span>
194
- `:`<span class="file-history-path">${y(t)}</span>`}function ms(e={}){let t=[String(e.authorName||`Unknown`),String(e.relativeDateLabel||``)];return e.status===`renamed`&&e.oldPath&&t.push(`Renamed from ${e.oldPath}`),t.filter(Boolean).map(e=>y(e)).join(` · `)}function hs(e={}){return e.type===`local`?`local`:`commit:${String(e.hash||``).trim()}:${String(e.pathAtCommit||``).trim()}`}function gs(){return{commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0}}var _s=class{constructor({diffRenderer:e=null,gitApiClient:t=null,onOpenCommitDiff:n=()=>{},onOpenFile:r=()=>{},onOpenPreview:i=()=>{},onOpenWorkspaceDiff:a=()=>{},toastController:o=null}={}){this.diffRenderer=e,this.gitApiClient=t,this.onOpenCommitDiff=n,this.onOpenFile=r,this.onOpenPreview=i,this.onOpenWorkspaceDiff=a,this.toastController=o,this.page=document.getElementById(`diff-page`),this.content=document.getElementById(`diffContent`),this.fileIndicator=document.getElementById(`diffFileIndicator`),this.openEditorButton=document.getElementById(`diffOpenEditorBtn`),this.primaryActionButton=document.getElementById(`diffPrimaryActionBtn`),this.commitButton=document.getElementById(`diffCommitBtn`),this.backToHistoryButton=document.getElementById(`diffBackToHistoryBtn`),this.gitActionsGroup=document.getElementById(`diffGitActionsGroup`),this.editorActionsGroup=document.getElementById(`diffEditorActionsGroup`),this.actionsDivider=document.getElementById(`diffToolbarDivider`),this.stats=document.getElementById(`diffStats`),this.prevButton=document.getElementById(`diffPrevBtn`),this.nextButton=document.getElementById(`diffNextBtn`),this.layoutToggle=document.getElementById(`diffLayoutToggle`),this.modeButtons=Array.from(document.querySelectorAll(`[data-diff-mode]`)),this.isActive=!1,this.currentFilePath=null,this.localChanges=null,this.history=gs(),this.diffMode=`unified`,this.selectedEntryKey=null,this.detailCache=new Map,this.detailErrors=new Map,this.historyListElement=null,this.historyListScrollTop=0,this.loadingEntryKey=null,this.selectionRequestToken=0}initialize(){this.openEditorButton?.addEventListener(`click`,()=>{this.isActive&&this.currentFilePath&&this.onOpenFile?.(this.currentFilePath)}),this.modeButtons.forEach(e=>{e.addEventListener(`click`,()=>{if(!this.isActive)return;let t=e.getAttribute(`data-diff-mode`);!t||t===this.diffMode||(this.diffMode=t,this.render())})}),this.content?.addEventListener(`click`,e=>{if(!this.isActive)return;let t=e.target instanceof Element?e.target.closest(`[data-file-history-select]`):null;if(t){let e=this.findEntryByKey(t.getAttribute(`data-file-history-select`));e&&this.selectEntry(e);return}if(e.target instanceof Element&&e.target.closest(`[data-file-history-open-selected-diff]`)){this.openSelectedDiff();return}if(e.target instanceof Element&&e.target.closest(`[data-file-history-open-selected-preview]`)){this.openSelectedPreview();return}e.target instanceof Element&&e.target.closest(`[data-file-history-load-more]`)&&this.loadMore()})}hide(){this.isActive=!1,this.page?.classList.add(`hidden`),this.content?.classList.remove(`diff-content--history`),this.content&&(this.content.innerHTML=``),this.currentFilePath=null,this.localChanges=null,this.history=gs(),this.selectedEntryKey=null,this.loadingEntryKey=null,this.detailCache.clear(),this.detailErrors.clear(),this.historyListElement=null,this.historyListScrollTop=0,this.selectionRequestToken=0}getEntries(){let e=[];this.localChanges&&e.push({...this.localChanges,key:`local`,label:`Local changes`,pathAtCommit:this.currentFilePath,type:`local`});for(let t of this.history.commits??[])e.push({...t,key:hs({...t,type:`commit`}),type:`commit`});return e}findEntryByKey(e){return this.getEntries().find(t=>t.key===e)??null}getSelectedEntry(){return this.findEntryByKey(this.selectedEntryKey)}getDefaultEntry(){return this.getEntries()[0]??null}getSelectedDetailState(){let e=this.getSelectedEntry();return e?{detail:this.detailCache.get(e.key)??null,entry:e,error:this.detailErrors.get(e.key)??``,loading:this.loadingEntryKey===e.key}:null}async openFileHistory({filePath:e}){this.isActive=!0,this.currentFilePath=String(e??``).trim()||null,this.localChanges=null,this.history={...gs(),loading:!0},this.selectedEntryKey=null,this.loadingEntryKey=null,this.detailCache.clear(),this.detailErrors.clear(),this.historyListElement=null,this.historyListScrollTop=0,this.selectionRequestToken=0,this.renderLoading();try{let[e,t]=await Promise.all([this.loadLocalChanges().catch(()=>null),this.fetchHistoryPage({offset:0})]);this.localChanges=e,this.history=t;let n=this.getDefaultEntry();return n?(await this.selectEntry(n),{history:t,localChanges:e}):(this.render(),{history:t,localChanges:e})}catch(e){return console.error(`[file-history] Failed to load file history:`,e),this.toastController?.show(`Failed to load file history`),this.localChanges=null,this.history={...gs(),error:`Failed to load file history`,loaded:!0},this.render(),{history:this.history,localChanges:null}}}async loadLocalChanges(){if(!this.currentFilePath)return null;let e=await this.gitApiClient.readDiff({metaOnly:!0,path:this.currentFilePath,scope:`all`}),t=e.files?.[0];return t?{...t,summary:e.summary??{additions:Number(t.stats?.additions||0),deletions:Number(t.stats?.deletions||0),filesChanged:1}}:null}async fetchHistoryPage({offset:e=0}={}){if(!this.currentFilePath)return{...gs(),loaded:!0};let t=await this.gitApiClient.readFileHistory({limit:fs,offset:e,path:this.currentFilePath}),n=Array.isArray(t.commits)?t.commits:[];return{commits:n,error:``,hasMore:!!t.hasMore,loaded:!0,loading:!1,loadingMore:!1,offset:e+n.length}}async loadSelectedDetail(e){if(!e)return null;if(e.type===`local`){let t=await this.gitApiClient.readDiff({path:this.currentFilePath||``,scope:`all`});return{detail:t.files?.[0]??null,summary:t.summary??e.summary??null}}let t=await this.gitApiClient.readCommit({hash:e.hash||``,path:e.pathAtCommit||``});return{commit:t.commit??null,detail:t.files?.[0]??null,summary:t.summary??null}}async selectEntry(e){if(!e)return null;let t=e.key||hs(e);this.selectedEntryKey=t,this.detailErrors.delete(t);let n=this.detailCache.get(t);if(n)return this.loadingEntryKey=null,this.render(),n;this.loadingEntryKey=t,this.render();let r=++this.selectionRequestToken;try{let n=await this.loadSelectedDetail(e);return this.detailCache.set(t,n),this.detailErrors.delete(t),r===this.selectionRequestToken&&this.selectedEntryKey===t&&(this.loadingEntryKey=null,this.render()),n}catch(n){return console.error(`[file-history] Failed to load selected diff:`,n),this.toastController?.show(e.type===`local`?`Failed to load local diff`:`Failed to load commit diff`),this.detailErrors.set(t,e.type===`local`?`Failed to load local diff`:`Failed to load commit diff`),r===this.selectionRequestToken&&this.selectedEntryKey===t&&(this.loadingEntryKey=null,this.render()),null}}async loadMore(){if(!(!this.currentFilePath||this.history.loading||this.history.loadingMore||!this.history.hasMore)){this.history={...this.history,error:``,loadingMore:!0},this.render();try{let e=await this.fetchHistoryPage({offset:this.history.offset});this.history={commits:[...this.history.commits,...e.commits],error:``,hasMore:e.hasMore,loaded:!0,loading:!1,loadingMore:!1,offset:e.offset},this.render()}catch(e){console.error(`[file-history] Failed to load more history:`,e),this.toastController?.show(`Failed to load file history`),this.history={...this.history,error:`Failed to load file history`,loadingMore:!1},this.render()}}}openSelectedDiff(){let e=this.getSelectedEntry();if(e){if(e.type===`local`){this.onOpenWorkspaceDiff?.(this.currentFilePath);return}this.onOpenCommitDiff?.(e.hash,{historyFilePath:this.currentFilePath,path:e.pathAtCommit})}}openSelectedPreview(){let e=this.getSelectedEntry();!e||e.type!==`commit`||this.onOpenPreview?.({currentFilePath:this.currentFilePath,hash:e.hash,path:e.pathAtCommit})}renderDiffFileHeader(e={}){return typeof this.diffRenderer?.renderFileHeader==`function`?this.diffRenderer.renderFileHeader(e):`
195
- <div class="diff-file-header">
196
- <span class="diff-file-path">${y(e.path||this.currentFilePath||``)}</span>
197
- </div>
198
- `}renderDiffMarkup(e={}){if(typeof this.diffRenderer?.renderDiffDetail==`function`){let t=this.diffRenderer.mode;this.diffRenderer.mode=this.diffMode;let n=this.diffRenderer.renderDiffDetail(e,0,{includeHeader:!0});return this.diffRenderer.mode=t,n}return`
199
- ${this.renderDiffFileHeader(e)}
200
- <div class="diff-empty-state">Diff renderer unavailable.</div>
201
- `}syncToolbar(){let e=this.getSelectedDetailState(),t=e?.entry??null,n=e?.detail?.summary??t?.summary??(t?{additions:Number(t.additions||0),deletions:Number(t.deletions||0)}:null),r=!!t;this.syncToolbarIndicators(t,n,r),this.syncToolbarButtonStates(r)}syncToolbarIndicators(e,t,n){let r=Number(t?.additions||0),i=Number(t?.deletions||0);this.fileIndicator&&(this.fileIndicator.textContent=e?.type===`commit`?e.shortHash||`Commit`:e?.type===`local`?`Local changes`:`History`),this.stats&&(this.stats.innerHTML=`
202
- <span class="ui-stat-token ui-stat-token--add diff-stats-add">+${r}</span>
203
- <span class="ui-stat-token ui-stat-token--del diff-stats-del">-${i}</span>
204
- `,this.stats.classList.toggle(`hidden`,!n))}syncToolbarButtonStates(e){this.backToHistoryButton?.classList.add(`hidden`),this.gitActionsGroup?.classList.add(`hidden`),this.layoutToggle?.classList.add(`hidden`),this.prevButton?.classList.add(`hidden`),this.nextButton?.classList.add(`hidden`),this.actionsDivider?.classList.add(`hidden`),this.editorActionsGroup?.classList.remove(`hidden`),this.modeButtons.forEach(t=>{t.classList.toggle(`hidden`,!e),t.classList.toggle(`active`,t.getAttribute(`data-diff-mode`)===this.diffMode)}),this.openEditorButton?.toggleAttribute(`disabled`,!this.currentFilePath),this.openEditorButton&&(this.openEditorButton.textContent=`Open File`),this.primaryActionButton?.toggleAttribute(`disabled`,!0),this.commitButton?.toggleAttribute(`disabled`,!0)}renderLoading(){this.isActive&&(this.page?.classList.remove(`hidden`),this.content&&(this.content.classList.add(`diff-content--history`),this.content.innerHTML=`<div class="git-panel-empty">Loading file history...</div>`),this.historyListElement=null,this.syncToolbar())}renderEmpty(e){this.isActive&&(this.page?.classList.remove(`hidden`),this.content&&(this.content.classList.add(`diff-content--history`),this.content.innerHTML=`<div class="git-panel-empty">${y(e)}</div>`),this.historyListElement=null,this.syncToolbar())}captureListScroll(){this.historyListElement&&(this.historyListScrollTop=Number(this.historyListElement.scrollTop||0))}restoreListScroll(){if(!this.content?.querySelector){this.historyListElement=null;return}let e=this.content.querySelector(`[data-file-history-list]`);this.historyListElement=e??null,e&&(e.scrollTop=this.historyListScrollTop,e.addEventListener(`scroll`,()=>{this.historyListScrollTop=Number(e.scrollTop||0)},{passive:!0}))}renderScopeLabels(e={}){let t=[];return e.hasStagedChanges&&t.push(`staged`),e.hasWorkingTreeChanges&&t.push(`working tree`),e.hasUntrackedChanges&&t.push(`untracked`),t.length>0?t.join(` · `):`working tree`}renderHistoryItem(e={}){let t=e.key===this.selectedEntryKey,n=Number(e.additions??e.summary?.additions??0),r=Number(e.deletions??e.summary?.deletions??0),i=e.type===`local`?`Live workspace`:ms(e),a=e.type===`local`?`Local changes`:e.subject||e.shortHash||`Commit`,o=e.type===`local`?`<span class="ui-pill-badge ui-pill-badge--accent file-history-item-badge">Live</span>`:`<span class="ui-pill-badge ui-pill-badge--code file-history-item-badge">${y(e.shortHash||``)}</span>`;return`
205
- <button
206
- class="ui-record-surface file-history-item${t?` active`:``}${e.type===`local`?` file-history-item-local`:``}"
207
- type="button"
208
- data-file-history-select="${y(e.key)}"
209
- aria-current="${t?`true`:`false`}"
210
- >
211
- <span class="file-history-item-top">
212
- <span class="file-history-item-copy">
213
- <span class="file-history-item-title">${y(a)}</span>
214
- <span class="file-history-item-meta">${e.type===`local`?y(this.renderScopeLabels(e)):i}</span>
215
- </span>
216
- ${o}
217
- </span>
218
- <span class="file-history-item-stats">
219
- <span class="git-change-add">+${n}</span>
220
- <span class="git-change-del">-${r}</span>
221
- </span>
222
- </button>
223
- `}renderSelectedHeader(e){let t=e?.entry;return t?`
224
- <div class="file-history-detail-header">
225
- <div class="file-history-detail-copy">
226
- <span class="file-history-detail-kicker">${t.type===`local`?`Live workspace`:`Commit ${y(t.shortHash||``)}`}</span>
227
- <h2 class="file-history-detail-title">${t.type===`local`?`Local changes`:y(t.subject||t.shortHash||`Commit`)}</h2>
228
- <p class="file-history-detail-meta">${t.type===`local`?y(this.renderScopeLabels(t)):ms(t)}</p>
229
- </div>
230
- <div class="file-history-detail-actions">
231
- <button
232
- class="${W({variant:`secondary`,action:!0,surface:!0})}"
233
- type="button"
234
- data-file-history-open-selected-diff
235
- >
236
- Open Standalone Diff
237
- </button>
238
- ${t.type===`commit`?`
239
- <button
240
- class="${W({variant:`primary`,action:!0})}"
241
- type="button"
242
- data-file-history-open-selected-preview
243
- >
244
- Preview File
245
- </button>
246
- `:``}
247
- </div>
248
- </div>
249
- `:`
250
- <div class="file-history-detail-header">
251
- <div class="file-history-detail-copy">
252
- <span class="file-history-detail-kicker">History</span>
253
- <h2 class="file-history-detail-title">No selection</h2>
254
- <p class="file-history-detail-meta">Choose a history item to inspect the file diff.</p>
255
- </div>
256
- </div>
257
- `}renderSelectedBody(e){let t=e?.entry;return t?e.loading?`
258
- <section class="diff-file-block file-history-diff-block">
259
- ${this.renderDiffFileHeader({path:t.pathAtCommit||this.currentFilePath||``})}
260
- <div class="diff-empty-state">Loading diff...</div>
261
- </section>
262
- `:e.error?`
263
- <section class="diff-file-block file-history-diff-block">
264
- ${this.renderDiffFileHeader({path:t.pathAtCommit||this.currentFilePath||``})}
265
- <div class="diff-empty-state">${y(e.error)}</div>
266
- </section>
267
- `:e.detail?.detail?`
268
- <section class="diff-file-block file-history-diff-block">
269
- ${this.renderDiffMarkup(e.detail.detail)}
270
- </section>
271
- `:`<div class="diff-empty-state">No diff available for this history item.</div>`:`<div class="diff-empty-state">Select a history entry to inspect this file.</div>`}render(){if(!this.isActive)return;if(this.page?.classList.remove(`hidden`),this.captureListScroll(),this.syncToolbar(),!this.currentFilePath){this.renderEmpty(`No file selected.`);return}if(this.history.loading&&!this.history.loaded){this.renderLoading();return}if(!(this.localChanges||(this.history.commits?.length??0)>0)){this.renderEmpty(this.history.error||`No history found for this file.`);return}if(!this.content)return;this.content.classList.add(`diff-content--history`);let e=this.getSelectedDetailState();this.content.innerHTML=`
272
- <section class="file-history-shell">
273
- <aside class="file-history-sidebar" aria-label="File history entries">
274
- <header class="file-history-sidebar-header">
275
- <span class="file-history-kicker">File history</span>
276
- <div class="file-history-title">${ps(this.currentFilePath)}</div>
277
- <p class="file-history-sidebar-copy">Select an entry to inspect the exact changes for this file.</p>
278
- </header>
279
- <div class="file-history-list" data-file-history-list>
280
- ${this.getEntries().map(e=>this.renderHistoryItem(e)).join(``)}
281
- </div>
282
- ${this.history.hasMore?`
283
- <div class="git-history-footer file-history-footer">
284
- <button
285
- class="${W({variant:`secondary`,size:`compact`,action:!0,surface:!0,extra:`git-history-load-more`})}"
286
- type="button"
287
- data-file-history-load-more
288
- ${this.history.loadingMore?`disabled`:``}
289
- >
290
- ${this.history.loadingMore?`Loading...`:`Load More`}
291
- </button>
292
- </div>
293
- `:``}
294
- </aside>
295
- <section class="file-history-detail">
296
- ${this.renderSelectedHeader(e)}
297
- <div class="file-history-detail-body">
298
- ${this.renderSelectedBody(e)}
299
- </div>
300
- </section>
301
- </section>
302
- `,this.restoreListScroll()}};function vs(e={}){return Va(`ui-segmented-control`,{"ui-segmented-control--pill":e.pill,hidden:e.hidden},e.extra??[])}function ys(e={}){return Va(`ui-segmented-btn`,{active:e.active,hidden:e.hidden},e.extra??[])}function bs(){return`base-${Math.random().toString(36).slice(2,10)}`}function xs(e=``){return/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/iu.test(String(e??``).trim())}function Ss(e=``){return/^https?:\/\/.+\.(?:png|jpe?g|webp|gif|svg)(?:[?#].*)?$/iu.test(String(e??``).trim())}function Cs(e){return Object.prototype.toString.call(e)===`[object Object]`}function ws(e=`and`){return{children:[],conjunction:e,type:`group`}}function Ts(e,t,n){let r=e.image||t.find(e=>[`cover`,`image`].includes(String(e.id??``).toLowerCase()))?.id||null;return r?n.cells[r]??null:null}function G(e){return String(e?.text??``)}function Es(e=``){return F(`/attachment?path=${encodeURIComponent(e)}`)}function Ds(e={}){if(e?.type===`image`&&e.path)return Es(e.path);if(e?.type===`link`){if(e.external&&Ss(e.url))return e.url;if(e.path&&l(e.path))return Es(e.path)}let t=G(e);return Ss(t)?t:l(t)?Es(t):``}function Os(e={}){let t=e?.type||`string`;if(t===`empty`)return`<span class="bases-value bases-value-empty">—</span>`;if(t===`boolean`)return`<span class="bases-value bases-value-boolean">${e.value?`True`:`False`}</span>`;if(t===`image`&&e.path)return`<img class="bases-inline-image" src="${y(Es(e.path))}" alt="${y(G(e))}">`;if(t===`list`)return`<span class="bases-value-list">${(e.items??[]).map(e=>`<span class="bases-value-pill">${Os(e)}</span>`).join(``)}</span>`;if(t===`link`){if(e.external&&e.url)return`<a class="bases-link" href="${y(e.url)}" target="_blank" rel="noopener noreferrer">${y(G(e))}</a>`;if(e.path)return`<button type="button" class="${y(W({variant:`secondary`,size:`compact`,pill:!0,extra:[`bases-link`,`bases-link-button`]}))}" data-base-open-file="${y(e.path)}">${y(G(e))}</button>`}if(t===`file`&&e.path)return`<button type="button" class="${y(W({variant:`secondary`,size:`compact`,pill:!0,extra:[`bases-link`,`bases-link-button`]}))}" data-base-open-file="${y(e.path)}">${y(G(e))}</button>`;let n=G(e);return`<span class="bases-value">${y(n)}</span>`}function ks(e,t){let n=t?.cells?.[e.id]??null;return t?.path&&n&&n.type!==`empty`&&(e.id===`file.name`||e.id===`file.basename`)?`<button type="button" class="${y(W({variant:`secondary`,size:`compact`,pill:!0,extra:[`bases-link`,`bases-link-button`]}))}" data-base-open-file="${y(t.path)}">${y(G(n))}</button>`:Os(n)}function As(e=[]){return!Array.isArray(e)||e.length===0?``:`<div class="bases-summaries">${e.map(e=>`<div class="bases-summary"><span class="bases-summary-label">${y(e.label)}</span><span class="bases-summary-value">${y(G(e.value))}</span></div>`).join(``)}</div>`}function js(e,t){return t.map(t=>`<section class="bases-group"><header class="bases-group-header"><h3>${y(t.label)}</h3>${As(t.summaries)}</header><div class="bases-table-shell"><table class="bases-table"><thead><tr>${e.map(e=>`<th>${y(e.label)}</th>`).join(``)}</tr></thead><tbody>${(t.rows??[]).map(t=>`<tr>${e.map(e=>`<td>${ks(e,t)}</td>`).join(``)}</tr>`).join(``)}</tbody></table></div></section>`).join(``)}function Ms(e,t){return t.map(t=>`<section class="bases-group"><header class="bases-group-header"><h3>${y(t.label)}</h3>${As(t.summaries)}</header><ul class="bases-list">${(t.rows??[]).map(t=>`<li class="bases-list-item">${e.map(e=>{let n=t.cells[e.id];return!n||n.type===`empty`?``:`<span class="bases-list-field"><strong>${y(e.label)}:</strong> ${ks(e,t)}</span>`}).join(``)}</li>`).join(``)}</ul></section>`).join(``)}function Ns(e,t,n){return t.map(t=>`<section class="bases-group"><header class="bases-group-header"><h3>${y(t.label)}</h3>${As(t.summaries)}</header><div class="bases-cards">${(t.rows??[]).map(t=>{let r=Ts(n,e,t),i=G(r),a=``;if(xs(i))a=`<div class="bases-card-media bases-card-media-color" style="--bases-card-swatch:${y(i)}"></div>`;else{let e=Ds(r);e&&(a=`<img class="bases-card-media" src="${y(e)}" alt="${y(i)}">`)}return`<article class="bases-card">${a}<div class="bases-card-body">${e.map(e=>{let n=t.cells[e.id];return!n||n.type===`empty`?``:`<div class="bases-card-field"><div class="bases-card-label">${y(e.label)}</div><div class="bases-card-value">${ks(e,t)}</div></div>`}).join(``)}</div></article>`}).join(``)}</div></section>`).join(``)}function Ps(e){if(!e.view.supported)return`<div class="bases-unsupported">CollabMD parsed this view but does not render the <code>${y(e.view.type)}</code> layout yet.</div>`;switch(e.view.type){case`cards`:return Ns(e.columns,e.groups,e.view);case`list`:return Ms(e.columns,e.groups);default:return js(e.columns,e.groups)}}function Fs(e){return(e.views??[]).map(t=>`<button type="button" class="${y(ys({active:t.id===e.view.id,extra:`bases-view-tab`}))}" data-base-view="${y(t.id)}">${y(t.name)}</button>`).join(``)}function K(e){return e?.meta??{}}function Is(e){return K(e).availableProperties??[]}function Ls(e){let t=K(e).activeViewConfig?.order;return Array.isArray(t)&&t.length>0?[...t]:Array.isArray(e?.columns)?e.columns.map(e=>e.id).filter(Boolean):[]}function Rs(e,t=``){return Is(e).find(e=>e.id===t)??null}function zs(e,t=``){return Rs(e,t)?.filterOperators??[`is`,`is not`,`contains`,`does not contain`,`is empty`,`is not empty`]}function q(e){let t=K(e).activeViewConfig??{};return{filters:t.filters??null,groupBy:t.groupBy??null,order:Array.isArray(t.order)?[...t.order]:[],sort:Array.isArray(t.sort)?t.sort.map(e=>({...e})):[]}}function Bs(e){return!!(e?.payload?.path&&e?.payload?.sourcePath&&e.payload.path===e.payload.sourcePath)}function Vs(e,t,n,r){let i=n.ui?.openPanel===t,a=!!K(r).editable;return`<button type="button" class="${y(W({variant:i?`primary`:`secondary`,pill:!0,extra:[`bases-toolbar-btn`,i?`is-active`:``]}))}" data-base-panel="${y(t)}"${a?``:` disabled`}>${y(e)}</button>`}function Hs(e,t=``){if(!e||e.type!==`group`||!t)return e;let n=(e.children??[]).flatMap(e=>{if(e?.type===`group`){let n=Hs(e,t);return n?[n]:[]}return e?.propertyId===t?[]:[e]});return{...e,children:n}}function Us(e,t=``,n=e?.result){let r=K(n).activeViewConfig?.filters??null,i=X(r),a=t&&i?Zs(Hs(i,t),n):r;return JSON.stringify({filters:a,path:e?.payload?.path??``,source:e?.payload?.source??null,sourcePath:e?.payload?.sourcePath??``,view:n?.view?.id??e?.payload?.view??``})}function Ws(e,t=``,n=e?.result){let r=e?.propertyValueOptions?.get(t)??null;return r&&r.cacheKey===Us(e,t,n)?r.values??[]:[]}function Gs(e,t){return[Vs(`Sort`,`sort`,t,e),Vs(`Filter`,`filter`,t,e),Vs(`Properties`,`properties`,t,e)].join(``)}function Ks(e,{allowBlank:t=!1,selected:n=``}={}){let r=[];return t&&r.push(`<option value=""${n?``:` selected`}>Property</option>`),Is(e).forEach(e=>{r.push(`<option value="${y(e.id)}"${e.id===n?` selected`:``}>${y(e.label)}</option>`)}),r.join(``)}function qs(e){let t=q(e),n=Rs(e,t.groupBy?.property)?.sortDirections??[{id:`asc`,label:`A → Z`},{id:`desc`,label:`Z → A`}],r=t.sort??[];return`
303
- <section class="bases-panel-card">
304
- <div class="bases-panel-section">
305
- <div class="bases-panel-title">Group by</div>
306
- <div class="bases-sort-row">
307
- <select class="${y(U({extra:`bases-select bases-sort-property`}))}" data-base-group-by-property>
308
- ${Ks(e,{allowBlank:!0,selected:t.groupBy?.property??``})}
309
- </select>
310
- <select class="${y(U({extra:`bases-select bases-sort-direction`}))}" data-base-group-by-direction${t.groupBy?.property?``:` disabled`}>
311
- ${n.map(e=>`<option value="${y(e.id)}"${e.id===(t.groupBy?.direction??`asc`)?` selected`:``}>${y(e.label)}</option>`).join(``)}
312
- </select>
313
- <button type="button" class="${y(W({variant:`secondary`,size:`compact`}))}" data-base-clear-group-by${t.groupBy?.property?``:` disabled`}>Clear</button>
314
- </div>
315
- </div>
316
- <div class="bases-panel-section">
317
- <div class="bases-panel-title">Sort by</div>
318
- <div class="bases-sort-list">
319
- ${r.map((t,n)=>{let i=Rs(e,t.property)?.sortDirections??[{id:`asc`,label:`A → Z`},{id:`desc`,label:`Z → A`}];return`
320
- <div class="bases-sort-row">
321
- <select class="${y(U({extra:`bases-select bases-sort-property`}))}" data-base-sort-property="${n}">
322
- ${Ks(e,{selected:t.property})}
323
- </select>
324
- <select class="${y(U({extra:`bases-select bases-sort-direction`}))}" data-base-sort-direction="${n}">
325
- ${i.map(e=>`<option value="${y(e.id)}"${e.id===t.direction?` selected`:``}>${y(e.label)}</option>`).join(``)}
326
- </select>
327
- <button type="button" class="${y(W({variant:`secondary`,size:`compact`}))}" data-base-sort-move="${n}:up"${n===0?` disabled`:``}>↑</button>
328
- <button type="button" class="${y(W({variant:`secondary`,size:`compact`}))}" data-base-sort-move="${n}:down"${n===r.length-1?` disabled`:``}>↓</button>
329
- <button type="button" class="${y(W({variant:`secondary`,size:`compact`}))}" data-base-sort-delete="${n}">Delete</button>
330
- </div>
331
- `}).join(``)}
332
- </div>
333
- <button type="button" class="${y(W({variant:`secondary`,size:`compact`}))}" data-base-sort-add>Add sort</button>
334
- </div>
335
- </section>
336
- `}function Js(e=[]){return e.join(`.`)}function J(e=``){return String(e??``).split(`.`).filter(e=>e!==``).map(e=>Number.parseInt(e,10)).filter(Number.isFinite)}function Ys(e=``){return JSON.stringify(String(e??``))}function Y(e=``,t=`text`,n=`is`){let r=String(e??``).trim();return!r&&n!==`is`&&n!==`is not`?`""`:t===`boolean`?r===`false`?`false`:`true`:t===`number`&&Number.isFinite(Number(r))?String(Number(r)):Ys(r)}function Xs(e,t=null){if(!e?.propertyId||!e?.operator)return``;let n=e.propertyId,r=t?.valueType??`text`;switch(e.operator){case`contains`:return`${n}.contains(${Y(e.value,r,e.operator)})`;case`does not contain`:return`!${n}.contains(${Y(e.value,r,e.operator)})`;case`starts with`:return`${n}.startsWith(${Y(e.value,r,e.operator)})`;case`ends with`:return`${n}.endsWith(${Y(e.value,r,e.operator)})`;case`is`:return`${n} == ${Y(e.value,r,e.operator)}`;case`is not`:return`${n} != ${Y(e.value,r,e.operator)}`;case`>`:case`>=`:case`<`:case`<=`:return`${n} ${e.operator} ${Y(e.value,r,e.operator)}`;case`is empty`:return`${n}.isEmpty()`;case`is not empty`:return`!${n}.isEmpty()`;default:return``}}function Zs(e,t){if(!e||e.type!==`group`)return null;let n=(e.children??[]).map(e=>e?.type===`group`?Zs(e,t):Xs(e,Rs(t,e?.propertyId))).filter(Boolean);return n.length===0?null:e.conjunction===`not`?{not:n}:{[e.conjunction]:n}}function Qs(e=``){let t=String(e??``).trim();return t?t===`true`||t===`false`?t:t===`null`?``:/^-?\d+(?:\.\d+)?$/u.test(t)?t:t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).replace(/\\(["'])/gu,`$1`):t:``}function $s(e=``){let t=String(e??``).trim(),n=[[/^!([A-Za-z0-9_.]+)\.isEmpty\(\)$/u,(e,t)=>({operator:`is not empty`,propertyId:t,type:`rule`,value:``})],[/^([A-Za-z0-9_.]+)\.isEmpty\(\)$/u,(e,t)=>({operator:`is empty`,propertyId:t,type:`rule`,value:``})],[/^!([A-Za-z0-9_.]+)\.contains\((.+)\)$/u,(e,t,n)=>({operator:`does not contain`,propertyId:t,type:`rule`,value:Qs(n)})],[/^([A-Za-z0-9_.]+)\.contains\((.+)\)$/u,(e,t,n)=>({operator:`contains`,propertyId:t,type:`rule`,value:Qs(n)})],[/^([A-Za-z0-9_.]+)\.startsWith\((.+)\)$/u,(e,t,n)=>({operator:`starts with`,propertyId:t,type:`rule`,value:Qs(n)})],[/^([A-Za-z0-9_.]+)\.endsWith\((.+)\)$/u,(e,t,n)=>({operator:`ends with`,propertyId:t,type:`rule`,value:Qs(n)})],[/^([A-Za-z0-9_.]+)\s*(==|!=|>=|<=|>|<)\s*(.+)$/u,(e,t,n,r)=>({operator:{"!=":`is not`,"==":`is`,"<":`<`,"<=":`<=`,">":`>`,">=":`>=`}[n]??n,propertyId:t,type:`rule`,value:Qs(r)})]];for(let[e,r]of n){let n=t.match(e);if(n)return r(...n)}return null}function X(e){if(!e)return ws(`and`);if(typeof e==`string`){let t=$s(e);return t?{children:[t],conjunction:`and`,type:`group`}:null}if(!Cs(e))return null;if(Array.isArray(e.and)){let t=e.and.map(e=>X(e)).flatMap(e=>e?.type===`group`&&e.conjunction===`and`&&e.children?.length===1&&e.children[0]?.type===`rule`?e.children:[e]);return t.every(Boolean)?{children:t,conjunction:`and`,type:`group`}:null}if(Array.isArray(e.or)){let t=e.or.map(e=>X(e)).flatMap(e=>e?.type===`group`&&e.conjunction===`and`&&e.children?.length===1&&e.children[0]?.type===`rule`?e.children:[e]);return t.every(Boolean)?{children:t,conjunction:`or`,type:`group`}:null}if(e.not!=null){let t=(Array.isArray(e.not)?e.not:(()=>{let t=X(e.not);return t?t.type===`group`&&t.conjunction===`or`?t.children??[]:[t]:[]})()).flatMap(e=>{let t=e?.type?e:X(e);return t?t.type===`group`&&t.conjunction===`and`&&t.children?.length===1&&t.children[0]?.type===`rule`?t.children:[t]:[null]});return t.every(Boolean)?{children:t,conjunction:`not`,type:`group`}:null}return null}function ec(e){return e?typeof e==`string`?e:JSON.stringify(e,null,2):``}function tc(e=``){let t=String(e??``).trim();return t?t.startsWith(`{`)||t.startsWith(`[`)?JSON.parse(t):t:null}function nc(e,t=[]){let n=e;for(let e of t)n=n?.children?.[e];return n??null}function Z(e,t=[],n){if(t.length===0)return n(e);let[r,...i]=t;return{...e,children:(e.children??[]).map((e,t)=>t===r?Z(e,i,n):e)}}function rc(e,t=[]){if(t.length===0)return e;let n=t.slice(0,-1),r=t[t.length-1];return Z(e,n,e=>({...e,children:(e.children??[]).filter((e,t)=>t!==r)}))}function ic(e,t=[],n){return Z(e,t,e=>({...e,children:[...e.children??[],n]}))}function ac(e,t=``){return Ks(e,{allowBlank:!0,selected:t})}function oc(e={}){return String(e?.text??e?.value??``).trim()}function sc(e,t){return e.ui.builderFilter??X(q(t).filters)??ws(`and`)}function cc(e,t,n,r){let i=Js(n),a=zs(e,t.propertyId),o=String(t.value??``).trim().toLowerCase(),s=Ws(r,t.propertyId,e).map(e=>({count:e?.count,text:oc(e)})).filter((e,t,n)=>e.text&&n.findIndex(t=>t.text===e.text)===t),c=s.some(e=>e.text.toLowerCase()===o),l=s.filter(e=>!o||e.text.toLowerCase().includes(o)),u=!o||c?s:l.length>0?l:s,d=u.length>0&&![`is empty`,`is not empty`].includes(t.operator);return{encodedPath:i,operators:a,suggestionListId:`bases-filter-suggestions-${y(r.key)}-${y(i.replace(/\./g,`-`))}`,suggestionsEnabled:d,valueInputClasses:U({extra:d?`bases-filter-value bases-filter-value--suggestions`:`bases-filter-value`}),valueSuggestions:u,valueDisabled:[`is empty`,`is not empty`].includes(t.operator)}}function lc(e,t=``){return e.suggestionsEnabled?`
337
- <div class="bases-filter-suggestion-list" id="${e.suggestionListId}" role="listbox">
338
- ${e.valueSuggestions.slice(0,8).map(n=>`
339
- <button
340
- type="button"
341
- class="bases-filter-suggestion"
342
- data-base-filter-suggestion="${y(e.encodedPath)}"
343
- data-base-filter-suggestion-value="${y(n.text)}"
344
- role="option"
345
- aria-selected="${n.text===String(t??``)?`true`:`false`}"
346
- >
347
- <span class="bases-filter-suggestion-label">${y(n.text)}</span>
348
- ${n.count==null?``:`<span class="bases-filter-suggestion-meta">${y(String(n.count))}</span>`}
349
- </button>
350
- `).join(``)}
351
- </div>
352
- `:``}function uc(e,t,n,r){let i=cc(e,t,n,r);return`
353
- <div class="bases-filter-value-combobox${i.suggestionsEnabled?` has-suggestions`:``}">
354
- <input class="${y(i.valueInputClasses)}" type="text" value="${y(t.value??``)}" data-base-filter-value="${y(i.encodedPath)}"${i.suggestionsEnabled?` aria-controls="${i.suggestionListId}" aria-haspopup="listbox" aria-autocomplete="list" autocomplete="off"`:``}${i.valueDisabled?` disabled`:``}>
355
- ${lc(i,t.value??``)}
356
- </div>
357
- `}function dc(e,t,n,r){let i=cc(e,t,n,r);return`
358
- <div class="bases-filter-row">
359
- <select class="${y(U({extra:`bases-select bases-filter-property`}))}" data-base-filter-property="${y(i.encodedPath)}">
360
- ${ac(e,t.propertyId)}
361
- </select>
362
- <select class="${y(U({extra:`bases-select bases-filter-operator`}))}" data-base-filter-operator="${y(i.encodedPath)}">
363
- ${i.operators.map(e=>`<option value="${y(e)}"${e===t.operator?` selected`:``}>${y(e)}</option>`).join(``)}
364
- </select>
365
- ${uc(e,t,n,r)}
366
- <button type="button" class="${y(W({variant:`secondary`,size:`compact`}))}" data-base-filter-remove="${y(i.encodedPath)}">Delete</button>
367
- </div>
368
- `}function fc(e,t,n,{fallbackToFullRender:r=!0}={}){let i=xc(e)?.querySelector?.(`[data-base-panel-slot]`)??null,a=Js(n),o=i?.querySelector?.(`[data-base-filter-value="${a}"]`)??null,s=o?.parentElement?.classList?.contains(`bases-filter-value-combobox`)?o.parentElement:null,c=nc(sc(e,t),n);if(!o||!s||!c||c.type!==`rule`||typeof o.insertAdjacentHTML!=`function`)return r&&wc(e,t),!1;let l=cc(t,c,n,e);return s.classList.toggle(`has-suggestions`,l.suggestionsEnabled),o.className=l.valueInputClasses,o.disabled=l.valueDisabled,o.value!==String(c.value??``)&&(o.value=String(c.value??``)),l.suggestionsEnabled?(o.setAttribute(`aria-controls`,l.suggestionListId),o.setAttribute(`aria-haspopup`,`listbox`),o.setAttribute(`aria-autocomplete`,`list`),o.setAttribute(`autocomplete`,`off`)):(o.removeAttribute(`aria-controls`),o.removeAttribute(`aria-haspopup`),o.removeAttribute(`aria-autocomplete`),o.removeAttribute(`autocomplete`)),s.querySelector(`.bases-filter-suggestion-list`)?.remove?.(),l.suggestionsEnabled&&o.insertAdjacentHTML(`afterend`,lc(l,c.value??``)),!0}function pc(e,t,n=[]){if(e){if(e.type===`rule`){t(e,n);return}(e.children??[]).forEach((e,r)=>{pc(e,t,[...n,r])})}}function mc(e,t,n,r,{isRoot:i=!1}={}){let a=Js(n);return`
369
- <div class="bases-filter-group"${i?` data-base-filter-root`:``}>
370
- <div class="bases-filter-group-header">
371
- <select class="${y(U({extra:`bases-select bases-filter-conjunction`}))}" data-base-filter-conjunction="${y(a)}">
372
- ${[`and`,`or`,`not`].map(e=>`<option value="${e}"${t.conjunction===e?` selected`:``}>${y({and:`All the following are true`,not:`None of the following are true`,or:`Any of the following are true`}[e])}</option>`).join(``)}
373
- </select>
374
- ${i?``:`<button type="button" class="${y(W({variant:`secondary`,size:`compact`}))}" data-base-filter-remove="${y(a)}">Delete group</button>`}
375
- </div>
376
- <div class="bases-filter-children">
377
- ${(t.children??[]).map((t,i)=>t?.type===`group`?mc(e,t,[...n,i],r):dc(e,t,[...n,i],r)).join(``)}
378
- </div>
379
- <div class="bases-filter-actions-row">
380
- <button type="button" class="${y(W({variant:`secondary`,size:`compact`}))}" data-base-filter-add-rule="${y(a)}">Add filter</button>
381
- <button type="button" class="${y(W({variant:`secondary`,size:`compact`}))}" data-base-filter-add-group="${y(a)}">Add filter group</button>
382
- </div>
383
- </div>
384
- `}function hc(e,t){let n=q(e).filters,r=t.ui.builderFilter??X(n);t.ui.builderFilter??(t.ui.builderFilter=r);let i=r?t.ui.filterMode??`builder`:`advanced`,a=t.ui.rawFilterText??ec(n);return`
385
- <section class="bases-panel-card">
386
- <div class="bases-panel-title-row">
387
- <div class="bases-panel-title">This view</div>
388
- ${r?`
389
- <div class="bases-toggle-row">
390
- <button type="button" class="${y(W({variant:i===`builder`?`primary`:`secondary`,size:`compact`}))}" data-base-filter-mode="builder">Builder</button>
391
- <button type="button" class="${y(W({variant:i===`advanced`?`primary`:`secondary`,size:`compact`}))}" data-base-filter-mode="advanced">Advanced</button>
392
- </div>
393
- `:``}
394
- </div>
395
- ${i===`advanced`?`
396
- <label class="bases-filter-advanced-label">
397
- <textarea class="${y(U({extra:`bases-filter-advanced`}))}" data-base-filter-advanced>${y(a)}</textarea>
398
- </label>
399
- <div class="bases-filter-actions-row">
400
- <button type="button" class="${y(W({variant:`primary`,size:`compact`}))}" data-base-filter-save-advanced>Save filter</button>
401
- </div>
402
- `:mc(e,r??ws(`and`),[],t,{isRoot:!0})}
403
- </section>
404
- `}function gc(e,t){let n=String(t.ui.propertySearch??``).trim().toLowerCase(),r=new Set(Ls(e)),i=Is(e).filter(e=>!n||e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n));return`
405
- <section class="bases-panel-card">
406
- <label class="bases-properties-search">
407
- <input class="${y(U({extra:`bases-properties-search-input`}))}" type="search" value="${y(t.ui.propertySearch??``)}" placeholder="Find property" data-base-properties-search>
408
- </label>
409
- <div class="bases-properties-list" data-base-properties-list>
410
- ${i.map(e=>`
411
- <label class="bases-property-option">
412
- <input type="checkbox" data-base-property-toggle="${y(e.id)}"${r.has(e.id)?` checked`:``}>
413
- <span class="bases-property-option-label">${y(e.label)}</span>
414
- <span class="bases-property-option-meta">${y(e.kind)}</span>
415
- </label>
416
- `).join(``)}
417
- </div>
418
- </section>
419
- `}function _c(e){let t=e?.querySelector?.(`[data-base-properties-list]`)??null,n=e?.querySelector?.(`[data-base-properties-search]`)??null,r=typeof document<`u`?document.activeElement:null,i=null;if(n&&r===n){let e=typeof n.selectionStart==`number`?n.selectionStart:null;i={selectionEnd:typeof n.selectionEnd==`number`?n.selectionEnd:e,selectionStart:e,type:`properties-search`}}else if(r?.dataset?.baseFilterValue!=null){let t=String(r.dataset.baseFilterValue),n=e?.querySelector?.(`[data-base-filter-value="${t}"]`)??null;if(n&&r===n){let e=typeof n.selectionStart==`number`?n.selectionStart:null;i={path:t,selectionEnd:typeof n.selectionEnd==`number`?n.selectionEnd:e,selectionStart:e,type:`filter-value`}}}return{focusedControl:i,propertiesListScrollTop:t?t.scrollTop:null}}function vc(e,t){if(t){if(t.propertiesListScrollTop!=null){let n=e?.querySelector?.(`[data-base-properties-list]`)??null;n&&(n.scrollTop=t.propertiesListScrollTop)}if(t.focusedControl?.type===`properties-search`){let n=e?.querySelector?.(`[data-base-properties-search]`)??null;n&&(n.focus?.(),typeof n.setSelectionRange==`function`&&t.focusedControl.selectionStart!=null&&n.setSelectionRange(t.focusedControl.selectionStart,t.focusedControl.selectionEnd??t.focusedControl.selectionStart));return}if(t.focusedControl?.type===`filter-value`&&t.focusedControl.path!=null){let n=e?.querySelector?.(`[data-base-filter-value="${t.focusedControl.path}"]`)??null;n&&(n.focus?.(),typeof n.setSelectionRange==`function`&&t.focusedControl.selectionStart!=null&&n.setSelectionRange(t.focusedControl.selectionStart,t.focusedControl.selectionEnd??t.focusedControl.selectionStart))}}}function yc(e,t){if(!t.ui?.openPanel)return``;if(!K(e).editable)return`<section class="bases-panel-card"><div class="bases-readonly-note">Inline base previews are read-only. Open the .base file to edit its sort, filter, and properties.</div></section>`;switch(t.ui.openPanel){case`filter`:return hc(e,t);case`properties`:return gc(e,t);default:return qs(e)}}function bc(e,t){return`
420
- <section class="bases-shell" data-base-shell-key="${y(t.key)}">
421
- <header class="bases-toolbar">
422
- <div class="bases-toolbar-main">
423
- <div class="${y(vs({pill:!0,extra:`bases-tabs`}))}" data-base-tabs>
424
- ${Fs(e)}
425
- </div>
426
- <div class="bases-meta" data-base-meta>${y(String(e.totalRows??0))} results</div>
427
- </div>
428
- <div class="bases-toolbar-actions">
429
- <div class="bases-toolbar-edit-actions" data-base-action-slot>${Gs(e,t)}</div>
430
- <label class="bases-search-shell" aria-label="Search this base">
431
- <svg class="bases-search-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
432
- <circle cx="11" cy="11" r="7"></circle>
433
- <path d="m20 20-3.5-3.5"></path>
434
- </svg>
435
- <input class="${y(U({extra:`bases-search-input`}))}" type="search" value="${y(t.search)}" placeholder="Search this base" aria-label="Search this base">
436
- </label>
437
- <button type="button" class="${y(W({variant:`secondary`,pill:!0,extra:`bases-export-btn`}))}">Export CSV</button>
438
- </div>
439
- </header>
440
- <div class="bases-panels" data-base-panel-slot>${yc(e,t)}</div>
441
- <div data-base-summary-slot>${As(e.summaries)}</div>
442
- <div class="bases-content" data-base-content>${Ps(e)}</div>
443
- </section>
444
- `}function xc(e){return e?.placeholder?.querySelector?e.placeholder.querySelector(`[data-base-shell-key="${e.key}"]`)??e.placeholder.querySelector(`.bases-shell`):null}function Sc(e){e?.classList&&(e.classList.add(`is-hydrated`),e.classList.remove(`diagram-preview-shell`))}function Cc(e,t,{actions:n=!0,body:r=!0,meta:i=!0,panel:a=!0,summary:o=!0,tabs:s=!0}={}){let c=xc(e);if(!c?.querySelector){e.placeholder.innerHTML=bc(t,e),Sc(e.placeholder);return}let l=c.querySelector(`[data-base-tabs]`);s&&l&&(l.innerHTML=Fs(t));let u=c.querySelector(`[data-base-meta]`);i&&u&&(u.textContent=`${String(t.totalRows??0)} results`);let d=c.querySelector(`[data-base-action-slot]`);n&&d&&(d.innerHTML=Gs(t,e));let f=c.querySelector(`[data-base-panel-slot]`);if(a&&f){let n=_c(f);f.innerHTML=yc(t,e),vc(f,n)}let p=c.querySelector(`[data-base-summary-slot]`);o&&p&&(p.innerHTML=As(t.summaries));let m=c.querySelector(`[data-base-content]`);r&&m&&(m.innerHTML=Ps(t));let h=c.querySelector(`.bases-search-input`);h&&h.value!==e.search&&(h.value=e.search)}function wc(e,t){Cc(e,t,{actions:!1,body:!1,meta:!1,summary:!1,tabs:!1})}var Tc=class{constructor({getActiveFilePath:e=()=>``,getSession:t=()=>null,onOpenFile:n,previewElement:r,replaceBaseSource:i=null,toastController:a,vaultApiClient:o}){this.getActiveFilePath=e,this.getSession=t,this.onOpenFile=n,this.previewElement=r,this.replaceBaseSource=i,this.toastController=a,this.vaultApiClient=o,this.entries=new Map,this.searchTimers=new Map,this.applyFilterSuggestion=(e,t,n)=>{this.updateBuilderFilter(e,e=>Z(e,t,e=>({...e,value:n})))},this.persistBuilderFilter=e=>{let t=sc(e,e.result);e.ui.builderFilter=t,this.updateViewConfig(e,n=>(n.filters=Zs(t,e.result),n))},this.handlePointerDown=e=>{let t=e.target.closest(`[data-base-filter-suggestion]`);if(!t)return;let n=e.target.closest(`[data-base-shell-key]`),r=n?this.entries.get(n.dataset.baseShellKey||``):null;if(!r)return;e.preventDefault();let i=J(t.dataset.baseFilterSuggestion||``),a=t.dataset.baseFilterSuggestionValue||``;this.applyFilterSuggestion(r,i,a)},this.handleClick=e=>{let t=e.target.closest(`[data-base-open-file]`);if(t){e.preventDefault(),this.onOpenFile?.(t.dataset.baseOpenFile||``);return}let n=e.target.closest(`[data-base-shell-key]`),r=n?this.entries.get(n.dataset.baseShellKey||``):null;if(!r)return;let i=e.target.closest(`.bases-view-tab`);if(i){r.payload.view=i.dataset.baseView||``,r.ui.openPanel=``,this.renderEntry(r);return}let a=e.target.closest(`[data-base-panel]`);if(a){let e=a.dataset.basePanel||``;r.ui.openPanel=r.ui.openPanel===e?``:e,r.ui.rawFilterText=ec(q(r.result).filters),wc(r,r.result);return}if(e.target.closest(`.bases-export-btn`)){this.exportEntry(r);return}if(e.target.closest(`[data-base-sort-add]`)){this.updateViewConfig(r,e=>{let t=new Set((e.sort??[]).map(e=>e.property)),n=Is(r.result).find(e=>!t.has(e.id))?.id??`file.name`;return e.sort=[...e.sort??[],{direction:`asc`,property:n}],e});return}let o=e.target.closest(`[data-base-sort-delete]`);if(o){let e=Number.parseInt(o.dataset.baseSortDelete||``,10);this.updateViewConfig(r,t=>(t.sort=(t.sort??[]).filter((t,n)=>n!==e),t));return}let s=e.target.closest(`[data-base-sort-move]`);if(s){let[e,t]=String(s.dataset.baseSortMove||``).split(`:`),n=Number.parseInt(e,10);this.updateViewConfig(r,e=>{let r=[...e.sort??[]],i=t===`up`?n-1:n+1;return i<0||i>=r.length?e:([r[n],r[i]]=[r[i],r[n]],e.sort=r,e)});return}if(e.target.closest(`[data-base-clear-group-by]`)){this.updateViewConfig(r,e=>(e.groupBy=null,e));return}let c=e.target.closest(`[data-base-filter-mode]`);if(c){r.ui.filterMode=c.dataset.baseFilterMode||`builder`,r.ui.filterMode===`advanced`&&(r.ui.rawFilterText=ec(q(r.result).filters),r.ui.builderFilter=null),wc(r,r.result);return}if(e.target.closest(`[data-base-filter-save-advanced]`)){this.saveAdvancedFilter(r);return}let l=e.target.closest(`[data-base-filter-add-rule]`);if(l){let e=J(l.dataset.baseFilterAddRule||``);this.updateBuilderFilter(r,t=>ic(t,e,{operator:`is`,propertyId:Is(r.result)[0]?.id??`file.name`,type:`rule`,value:``}));return}let u=e.target.closest(`[data-base-filter-add-group]`);if(u){let e=J(u.dataset.baseFilterAddGroup||``);this.updateBuilderFilter(r,t=>ic(t,e,ws(`and`)));return}let d=e.target.closest(`[data-base-filter-remove]`);if(d){let e=J(d.dataset.baseFilterRemove||``);this.updateBuilderFilter(r,t=>rc(t,e));return}let f=e.target.closest(`[data-base-filter-suggestion]`);if(f){if(e.preventDefault?.(),e.detail!=null&&e.detail!==0)return;let t=J(f.dataset.baseFilterSuggestion||``),n=f.dataset.baseFilterSuggestionValue||``;this.applyFilterSuggestion(r,t,n)}},this.handleInput=e=>{let t=e.target.closest(`.bases-search-input`);if(t){let e=t.closest(`[data-base-shell-key]`),n=e?this.entries.get(e.dataset.baseShellKey||``):null;if(!n)return;n.search=t.value||``,clearTimeout(this.searchTimers.get(n.key)),this.searchTimers.set(n.key,setTimeout(()=>{n.payload.search=n.search,this.renderEntry(n)},180));return}let n=e.target.closest(`[data-base-properties-search]`);if(n){let e=n.closest(`[data-base-shell-key]`),t=e?this.entries.get(e.dataset.baseShellKey||``):null;if(!t)return;t.ui.propertySearch=n.value||``,wc(t,t.result);return}let r=e.target.closest(`[data-base-filter-advanced]`);if(r){let e=r.closest(`[data-base-shell-key]`),t=e?this.entries.get(e.dataset.baseShellKey||``):null;if(!t)return;t.ui.rawFilterText=r.value||``;return}let i=e.target.closest(`[data-base-filter-value]`);if(i){let e=i.closest(`[data-base-shell-key]`),t=e?this.entries.get(e.dataset.baseShellKey||``):null;if(!t)return;let n=J(i.dataset.baseFilterValue||``),r=t.ui.builderFilter??X(q(t.result).filters)??ws(`and`);t.ui.builderFilter=Z(r,n,e=>({...e,value:i.value||``})),fc(t,t.result,n)}},this.handleChange=e=>{let t=e.target.closest(`[data-base-shell-key]`),n=t?this.entries.get(t.dataset.baseShellKey||``):null;if(!n)return;let r=e.target.closest(`[data-base-group-by-property]`);if(r){this.updateViewConfig(n,e=>(e.groupBy=r.value?{direction:e.groupBy?.direction??`asc`,property:r.value}:null,e));return}let i=e.target.closest(`[data-base-group-by-direction]`);if(i){this.updateViewConfig(n,e=>(e.groupBy=e.groupBy?.property?{direction:i.value||`asc`,property:e.groupBy.property}:null,e));return}let a=e.target.closest(`[data-base-sort-property]`);if(a){let e=Number.parseInt(a.dataset.baseSortProperty||``,10);this.updateViewConfig(n,t=>(t.sort=(t.sort??[]).map((t,n)=>n===e?{...t,property:a.value}:t),t));return}let o=e.target.closest(`[data-base-sort-direction]`);if(o){let e=Number.parseInt(o.dataset.baseSortDirection||``,10);this.updateViewConfig(n,t=>(t.sort=(t.sort??[]).map((t,n)=>n===e?{...t,direction:o.value||`asc`}:t),t));return}let s=e.target.closest(`[data-base-property-toggle]`);if(s){let e=s.dataset.basePropertyToggle||``;this.updateViewConfig(n,t=>{let r=t.order?.length>0?[...t.order]:Ls(n.result),i=r.indexOf(e);return s.checked&&i===-1&&r.push(e),!s.checked&&i>=0&&r.splice(i,1),t.order=r,t});return}let c=e.target.closest(`[data-base-filter-conjunction]`);if(c){let e=J(c.dataset.baseFilterConjunction||``);this.updateBuilderFilter(n,t=>Z(t,e,e=>({...e,conjunction:c.value||`and`})));return}let l=e.target.closest(`[data-base-filter-property]`);if(l){let e=J(l.dataset.baseFilterProperty||``);(async()=>{await this.updateBuilderFilter(n,t=>Z(t,e,e=>{let t=zs(n.result,l.value)[0]??`is`;return{...e,operator:t,propertyId:l.value,value:``}})),await this.ensurePropertyValues(n,l.value)})();return}let u=e.target.closest(`[data-base-filter-operator]`);if(u){let e=J(u.dataset.baseFilterOperator||``);this.updateBuilderFilter(n,t=>Z(t,e,e=>({...e,operator:u.value||`is`})));return}e.target.closest(`[data-base-filter-value]`)&&this.persistBuilderFilter(n)},this.handleFocusIn=e=>{let t=e.target.closest(`[data-base-filter-value]`);if(!t)return;let n=t.closest(`[data-base-shell-key]`),r=n?this.entries.get(n.dataset.baseShellKey||``):null;if(!r)return;let i=J(t.dataset.baseFilterValue||``),a=X(q(r.result).filters),o=a?nc(a,i):null;o?.propertyId&&this.ensurePropertyValues(r,o.propertyId)},this.previewElement?.addEventListener(`pointerdown`,this.handlePointerDown),this.previewElement?.addEventListener(`click`,this.handleClick),this.previewElement?.addEventListener(`input`,this.handleInput),this.previewElement?.addEventListener(`change`,this.handleChange),this.previewElement?.addEventListener(`focusin`,this.handleFocusIn)}ensureEntryState(e){e.ui||={builderFilter:null,filterMode:`builder`,openPanel:``,propertySearch:``,rawFilterText:``},Object.prototype.hasOwnProperty.call(e.ui,`builderFilter`)||(e.ui.builderFilter=null),e.propertyValueOptions||=new Map}destroy(){this.previewElement?.removeEventListener(`pointerdown`,this.handlePointerDown),this.previewElement?.removeEventListener(`click`,this.handleClick),this.previewElement?.removeEventListener(`input`,this.handleInput),this.previewElement?.removeEventListener(`change`,this.handleChange),this.previewElement?.removeEventListener(`focusin`,this.handleFocusIn),this.searchTimers.forEach(e=>clearTimeout(e)),this.searchTimers.clear(),this.entries.clear()}reconcileEmbeds(e=this.previewElement){e&&Array.from(e.querySelectorAll(`.bases-embed-placeholder[data-base-key]`)).forEach(e=>{let t=e.dataset.baseKey||bs(),n=this.entries.get(t),r={path:e.dataset.basePath||``,search:``,source:e.dataset.baseSource||null,sourcePath:e.dataset.baseSourcePath||``,view:e.dataset.baseView||``},i=n??{key:t,payload:r,placeholder:e,propertyValueOptions:new Map,requestVersion:0,result:null,search:``,ui:{builderFilter:null,filterMode:`builder`,openPanel:``,propertySearch:``,rawFilterText:``}};i.payload=r,i.placeholder=e,this.entries.set(t,i),this.renderEntry(i)})}async renderStandalone({filePath:e,renderHost:t,source:n=null}){let r=`standalone:${e}`,i=this.entries.get(r)??{key:r,payload:{path:e,search:``,source:n,sourcePath:e,view:``},placeholder:t,propertyValueOptions:new Map,requestVersion:0,result:null,search:``,ui:{builderFilter:null,filterMode:`builder`,openPanel:``,propertySearch:``,rawFilterText:``}};i.placeholder=t,i.payload.path=e,i.payload.source=typeof n==`string`?n:null,i.payload.sourcePath=e,this.entries.set(r,i),await this.renderEntry(i)}async renderEntry(e){if(this.ensureEntryState(e),!e?.placeholder?.isConnected)return;let t=(e.requestVersion??0)+1;e.requestVersion=t;let n=!!xc(e);n||(e.placeholder.innerHTML=`<div class="preview-shell">Loading base…</div>`);try{let n=await this.vaultApiClient.queryBase({activeFilePath:this.getActiveFilePath?.()??``,...e.payload});if(t!==e.requestVersion||!e?.placeholder?.isConnected)return;e.result=n.result,e.ui.builderFilter=X(q(e.result).filters),e.ui.rawFilterText||(e.ui.rawFilterText=ec(q(e.result).filters)),Cc(e,e.result)}catch(r){if(t!==e.requestVersion||!e?.placeholder?.isConnected)return;if(n){let t=xc(e)?.querySelector?.(`[data-base-content]`)??null;if(t){t.innerHTML=`<div class="preview-shell">Failed to load base: ${y(r.message||`Unknown error`)}</div>`;return}}e.placeholder.innerHTML=`<div class="preview-shell">Failed to load base: ${y(r.message||`Unknown error`)}</div>`}}async exportEntry(e){this.ensureEntryState(e);try{let t=await this.vaultApiClient.exportBaseCsv({activeFilePath:this.getActiveFilePath?.()??``,...e.payload});Ce(t.blob,Se(t.contentDisposition,`base.csv`),{removeDelayMs:0,revokeDelayMs:0})}catch(e){this.toastController?.show?.(e.message||`Failed to export base CSV`)}}async ensurePropertyValues(e,t=``){if(this.ensureEntryState(e),!t)return;let n=Us(e,t);if((e.propertyValueOptions.get(t)??null)?.cacheKey!==n)try{let r=await this.vaultApiClient.queryBasePropertyValues({activeFilePath:this.getActiveFilePath?.()??``,...e.payload,propertyId:t});if(e.propertyValueOptions.set(t,{cacheKey:n,values:r.result?.values??[]}),e.result&&e.ui.openPanel===`filter`){let n=!1;pc(sc(e,e.result),(r,i)=>{r.propertyId===t&&(n=fc(e,e.result,i,{fallbackToFullRender:!1})||n)}),n||wc(e,e.result)}}catch{e.propertyValueOptions.set(t,{cacheKey:n,values:[]})}}async applyTransformedSource(e,t){if(this.ensureEntryState(e),Bs(e)){e.payload.source=t.source,this.replaceBaseSource?.({path:e.payload.path,source:t.source});return}await this.vaultApiClient.writeFile({content:t.source,path:e.payload.path}),e.payload.source=null}async updateViewConfig(e,t){if(this.ensureEntryState(e),!e?.result||!K(e.result).editable)return;let n=t(q(e.result));try{let t=(await this.vaultApiClient.transformBase({activeFilePath:this.getActiveFilePath?.()??``,mutation:{config:n,type:`set-view-config`,view:e.result.view.id},...e.payload})).result;await this.applyTransformedSource(e,t),e.result=t.result,e.ui.rawFilterText=ec(q(e.result).filters),Cc(e,e.result)}catch(e){this.toastController?.show?.(e.message||`Failed to update base`)}}async updateBuilderFilter(e,t){this.ensureEntryState(e);let n=t(e.ui.builderFilter??X(q(e.result).filters)??ws(`and`));e.ui.builderFilter=n,await this.updateViewConfig(e,t=>(t.filters=Zs(n,e.result),t))}async saveAdvancedFilter(e){this.ensureEntryState(e);try{let t=tc(e.ui.rawFilterText??``);e.ui.builderFilter=X(t),await this.updateViewConfig(e,e=>(e.filters=t,e))}catch(e){this.toastController?.show?.(e.message||`Invalid advanced filter`)}}},Ec=`https://viewer.diagrams.net/js/viewer-static.min.js`,Dc=null;function Oc(){return window.GraphViewer?.processElements?Promise.resolve(window.GraphViewer):Dc||(Dc=new Promise((e,t)=>{let n=document.querySelector(`script[data-collabmd-drawio-viewer]`),r=n instanceof HTMLScriptElement?n:document.createElement(`script`),i=()=>{r.removeEventListener(`error`,a),r.removeEventListener(`load`,o)},a=()=>{i(),Dc=null,t(Error(`Failed to load draw.io viewer`))},o=()=>{if(i(),!window.GraphViewer?.processElements){Dc=null,t(Error(`draw.io viewer did not initialize`));return}e(window.GraphViewer)};r.addEventListener(`error`,a,{once:!0}),r.addEventListener(`load`,o,{once:!0}),n?window.GraphViewer?.processElements&&o():(r.src=Ec,r.async=!0,r.dataset.collabmdDrawioViewer=`true`,document.head.append(r))}),Dc)}function kc({ariaLabel:e=``,className:t=`drawio-viewer-frame`,onActivate:n=null,source:r=``,theme:i=`dark`}={}){let a=document.createElement(`div`);return a.className=t,e&&a.setAttribute(`aria-label`,e),typeof n==`function`&&(a.dataset.action=`open-file`,a.setAttribute(`role`,`button`),a.setAttribute(`tabindex`,`0`),a.addEventListener(`click`,e=>{e.preventDefault(),n()}),a.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),n())})),a.dataset.mxgraph=JSON.stringify({"check-visible-state":!1,center:!0,border:0,"dark-mode":i===`light`?`light`:`dark`,editable:!1,fit:1,lightbox:!1,nav:!1,resize:!1,tooltips:!1,xml:String(r??``)}),a}async function Ac(e,t={}){let n=await Oc(),r=kc(t);return e.replaceChildren(r),typeof n.createViewerForElement==`function`?n.createViewerForElement(r):n.processElements(),r}var jc=360,Mc=class{constructor({getLocalUser:e,getTheme:t,onOpenFile:n=null,onOpenTextFile:r=null,onToggleQuickSwitcher:i=null,previewContainer:a,previewElement:o,toastController:s,vaultApiClient:c}){this.getLocalUser=e,this.getTheme=t,this.onOpenFile=n,this.onOpenTextFile=r,this.onToggleQuickSwitcher=i,this.previewContainer=a,this.previewElement=o,this.toastController=s,this.vaultApiClient=c,this.embedEntries=new Map,this.hydrationQueue=[],this.hydrationIdleId=null,this.hydrationPaused=!1,this.instanceCounter=0,this.maximizedEntry=null,this.overlayRoot=null,this._onMessage=this._onMessage.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onPreviewClick=this._onPreviewClick.bind(this),window.addEventListener(`message`,this._onMessage),window.addEventListener(`keydown`,this._onKeyDown),this.previewElement?.addEventListener(`click`,this._onPreviewClick)}destroy(){window.removeEventListener(`message`,this._onMessage),window.removeEventListener(`keydown`,this._onKeyDown),this.previewElement?.removeEventListener(`click`,this._onPreviewClick),z(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this._exitMaximizedEntry(),document.body.classList.remove(`drawio-maximized-open`),this.embedEntries.forEach(e=>e.wrapper?.remove()),this.embedEntries.clear(),this.overlayRoot?.remove(),this.overlayRoot=null}detachForCommit(){z(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this._exitMaximizedEntry(),this.overlayRoot&&(this.overlayRoot.hidden=!0),this.embedEntries.forEach(e=>{e.queued=!1,e.placeholder=null})}setHydrationPaused(e){this.hydrationPaused=!!e,this.hydrationPaused||this.hydrateVisibleEmbeds()}reconcileEmbeds(e){this._exitMaximizedEntry();let t=Array.from(e.querySelectorAll(`.drawio-embed-placeholder[data-drawio-key]`)).map(e=>({filePath:e.dataset.drawioTarget||``,key:e.dataset.drawioKey||``,label:e.dataset.drawioLabel||e.dataset.drawioTarget||``,mode:e.dataset.drawioMode===`edit`?`edit`:`view`,placeholder:e})),n=new Map;t.forEach(e=>{let t=this.embedEntries.get(e.key)||null,r=t&&this.entryMatchesDescriptor(t,e)?t:this.createEntry(e);t&&t!==r&&this.destroyEntry(t),r.filePath=e.filePath,r.key=e.key,r.label=e.label,r.mode=e.mode,r.placeholder=e.placeholder,n.set(e.key,r)}),this.embedEntries.forEach((e,t)=>{n.has(t)||this.destroyEntry(e)}),this.embedEntries=n,this.embedEntries.forEach(e=>{e.wrapper?this.attachWrapper(e):e.queued=!1}),this.hydrationPaused||this.hydrateVisibleEmbeds(),this.syncLayout()}createEntry(e){return{...e,iframe:null,imageElement:null,inlineHeightPx:null,instanceId:``,queued:!1,viewerElement:null,wrapper:null}}entryMatchesDescriptor(e,t){return!!(e&&e.filePath===t.filePath&&e.mode===t.mode)}hydrateVisibleEmbeds(){this.embedEntries.forEach(e=>{e.wrapper||!e.placeholder?.isConnected||(e.mode===`edit`||we(e.placeholder,this.previewContainer,jc))&&this.enqueueHydration(e)})}enqueueHydration(e){e.queued||(e.queued=!0,this.hydrationQueue.push(e),this.hydrationIdleId===null&&(this.hydrationIdleId=R(()=>{this.hydrationIdleId=null,this.hydrationQueue.splice(0).forEach(e=>{e.queued=!1,this.hydrateEntry(e)})},200)))}hydrateEntry(e){if(!(!e.placeholder?.isConnected||e.wrapper)){if(e.mode===`view`){this.hydrateViewerEntry(e);return}this.hydrateIframeEntry(e)}}hydrateIframeEntry(e){if(!e.placeholder?.isConnected||e.wrapper)return;let t=document.createElement(`div`);t.className=`drawio-embed diagram-preview-shell${e.mode===`edit`?` is-direct-file`:``}`,t.dataset.file=e.filePath,t.dataset.drawioKey=e.key;let n=document.createElement(`div`);n.className=`drawio-embed-header diagram-preview-toolbar`;let r=document.createElement(`span`);r.className=`drawio-embed-icon`,r.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="7" height="6" rx="1"/><rect x="14" y="4" width="7" height="6" rx="1"/><rect x="8.5" y="14" width="7" height="6" rx="1"/><path d="M10 7h4"/><path d="M17.5 10v2.5"/><path d="M6.5 10v2.5"/><path d="M6.5 12.5h11"/></svg>`;let i=document.createElement(`span`);i.className=`drawio-embed-label`,i.textContent=e.label.replace(/\.drawio$/i,``),n.append(r,i),e.mode!==`edit`&&n.appendChild(this.createOpenButton(e)),n.appendChild(this.createMaximizeButton(e,t));let a=document.createElement(`iframe`);a.className=`drawio-embed-iframe`,a.loading=`lazy`,a.referrerPolicy=`strict-origin-when-cross-origin`,e.instanceId=`drawio-${++this.instanceCounter}`,a.dataset.instanceId=e.instanceId,a.src=this.buildIframeUrl(e),t.append(n,a),e.iframe=a,e.wrapper=t,this.attachWrapper(e)}async hydrateViewerEntry(e){if(!e.placeholder?.isConnected||e.wrapper)return;let t=document.createElement(`div`);t.className=`drawio-embed diagram-preview-shell is-static-preview`,t.dataset.file=e.filePath,t.dataset.drawioKey=e.key;let n=document.createElement(`div`);n.className=`drawio-embed-header diagram-preview-toolbar`;let r=document.createElement(`span`);r.className=`drawio-embed-icon`,r.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="7" height="6" rx="1"/><rect x="14" y="4" width="7" height="6" rx="1"/><rect x="8.5" y="14" width="7" height="6" rx="1"/><path d="M10 7h4"/><path d="M17.5 10v2.5"/><path d="M6.5 10v2.5"/><path d="M6.5 12.5h11"/></svg>`;let i=document.createElement(`span`);i.className=`drawio-embed-label`,i.textContent=e.label.replace(/\.drawio$/i,``),n.append(r,i),n.append(this.createOpenButton(e),this.createMaximizeButton(e,t));let a=document.createElement(`div`);a.className=`drawio-viewer-shell`,a.dataset.filePath=e.filePath;let o=document.createElement(`div`);o.className=`preview-shell`,o.textContent=`Rendering draw.io preview…`,a.appendChild(o),t.append(n,a),e.iframe=null,e.wrapper=t,e.viewerElement=a,this.attachWrapper(e);try{await this.renderViewerEntry(e),this.syncEntryLayout(e)}catch(t){this.renderViewerFallback(e,t instanceof Error?t.message:`Failed to render draw.io preview`),this.syncEntryLayout(e)}}async renderViewerEntry(e){let{content:t}=await this.vaultApiClient.readFile(e.filePath);if(!e.wrapper?.isConnected||!e.viewerElement?.isConnected)return;let n=this.getTheme?.()===`light`?`light`:`dark`;e.viewerElement=await Ac(e.wrapper.querySelector(`.drawio-viewer-shell`)??e.viewerElement,{ariaLabel:`Open ${e.label.replace(/\.drawio$/i,``)}`,className:`mxgraph drawio-viewer-frame`,onActivate:()=>this.onOpenFile?.(e.filePath),source:String(t??``),theme:n})}buildIframeUrl(e){let t=new URL(se(`/drawio-editor.html`)),n=this.getLocalUser?.()??{};return t.searchParams.set(`file`,e.filePath),t.searchParams.set(`hostMode`,e.mode===`edit`?`file-preview`:`embed`),t.searchParams.set(`instanceId`,e.instanceId),t.searchParams.set(`mode`,e.mode===`edit`?`edit`:`view`),t.searchParams.set(`theme`,this.getTheme?.()===`light`?`light`:`dark`),n.name&&t.searchParams.set(`userName`,n.name),n.peerId&&t.searchParams.set(`peerId`,n.peerId),e.mode===`edit`&&t.searchParams.set(`leaseRoom`,be(e.filePath)),t.toString()}updateTheme(e){this.embedEntries.forEach(t=>{t.iframe?.contentWindow&&t.iframe.contentWindow.postMessage({source:`collabmd-host`,theme:e,type:`set-theme`},window.location.origin),t.mode===`view`&&t.wrapper?.isConnected&&t.viewerElement?.isConnected&&this.renderViewerEntry(t).catch(e=>{this.renderViewerFallback(t,e instanceof Error?e.message:`Failed to render draw.io preview`)})})}updateLocalUser(){}syncLayout(){this.embedEntries.forEach(e=>{e.wrapper&&!this.shouldInlineEntry(e)&&this.syncEntryLayout(e)})}attachWrapper(e){let t=e.placeholder?.isConnected?e.placeholder:this.findPlaceholder(e);if(!t)return;if(e.placeholder=t,this.syncMountedEntryMetadata(e),this.shouldInlineEntry(e)){e.wrapper.style.position=``,e.wrapper.style.top=``,e.wrapper.style.left=``,e.wrapper.style.width=``,e.wrapper.style.margin=``,e.wrapper.style.pointerEvents=`auto`,t.replaceWith(e.wrapper),e.placeholder=null;return}let n=this.ensureOverlayRoot();n.hidden=!1,e.wrapper?.parentElement!==n&&n.appendChild(e.wrapper),this.syncEntryLayout(e)}destroyEntry(e){this.maximizedEntry?.key===e?.key&&this._exitMaximizedEntry(),this.resetPlaceholderLayout(e),e?.wrapper?.remove(),e&&(e.placeholder=null,e.wrapper=null,e.iframe=null,e.viewerElement=null)}findPlaceholder(e){return this.previewElement?.querySelector?.(`.drawio-embed-placeholder[data-drawio-key="${e.key}"]`)??null}ensureOverlayRoot(){if(this.overlayRoot?.isConnected&&this.overlayRoot.parentElement===this.previewElement)return this.overlayRoot;let e=this.previewElement?.querySelector?.(`[data-drawio-overlay-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.drawioOverlayRoot=`true`,e.className=`drawio-embed-overlay-root`,this.previewElement?.appendChild(e)),this.overlayRoot=e,e}shouldInlineEntry(e){return e?.key===`${e?.filePath}#file-preview`}syncMountedEntryMetadata(e){e.wrapper&&(e.wrapper.dataset.drawioKey=e.key,e.wrapper.dataset.file=e.filePath,e.wrapper.classList.toggle(`is-direct-file`,this.shouldInlineEntry(e))),e.iframe&&(e.iframe.title=`draw.io: ${e.filePath}`)}resetPlaceholderLayout(e){!e?.placeholder?.isConnected||this.shouldInlineEntry(e)||(e.placeholder.classList.remove(`is-hydrated`),e.placeholder.removeAttribute(`data-drawio-hydrated`),e.placeholder.style.height=``,e.placeholder.style.pointerEvents=``)}syncEntryLayout(e){if(!e?.wrapper||this.shouldInlineEntry(e))return;let t=e.placeholder?.isConnected?e.placeholder:this.findPlaceholder(e);if(!t)return;e.placeholder=t,t.classList.add(`is-hydrated`),t.dataset.drawioHydrated=`true`,t.style.pointerEvents=`none`;let n=e.wrapper.classList.contains(`is-maximized`),r=e.wrapper.offsetHeight||Math.ceil(e.wrapper.getBoundingClientRect?.().height||0)||e.inlineHeightPx||420;if(n||(e.inlineHeightPx=r),t.style.height=`${Math.ceil(e.inlineHeightPx||r)}px`,e.wrapper.style.pointerEvents=`auto`,n){e.wrapper.style.position=``,e.wrapper.style.top=``,e.wrapper.style.left=``,e.wrapper.style.width=`auto`,e.wrapper.style.height=`auto`,e.wrapper.style.minHeight=`0`,e.wrapper.style.margin=``;return}e.wrapper.style.position=`absolute`,e.wrapper.style.top=`${t.offsetTop}px`,e.wrapper.style.left=`${t.offsetLeft}px`,e.wrapper.style.width=`${t.offsetWidth}px`,e.wrapper.style.margin=`0`}createOpenButton(e){let t=document.createElement(`button`);return t.type=`button`,t.className=`drawio-embed-btn ui-preview-action ui-preview-action--icon-only`,t.dataset.action=`open-file`,t.dataset.filePath=e.filePath,t.title=`Edit in draw.io`,t.setAttribute(`aria-label`,`Edit in draw.io`),V(t,`edit`),t.addEventListener(`click`,t=>{t.preventDefault(),this.onOpenFile?.(e.filePath)}),t}createMaximizeButton(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`drawio-embed-btn ui-preview-action ui-preview-action--icon-only`,n.dataset.action=`toggle-maximize`,n.dataset.filePath=e.filePath,n.dataset.drawioKey=e.key,n.addEventListener(`click`,n=>{n.preventDefault(),this.maximizedEntry?.key===e.key?this._exitMaximizedEntry():this._enterMaximizedEntry(e,t),this._syncMaximizeButtons()}),(()=>{let t=this.maximizedEntry?.key===e.key;V(n,t?`restore`:`maximize`),n.title=t?`Restore diagram size`:`Maximize diagram`,n.setAttribute(`aria-label`,t?`Restore diagram size`:`Maximize diagram`)})(),n}_enterMaximizedEntry(e,t=e?.wrapper){if(!(!e?.wrapper||e.wrapper!==t)&&this.maximizedEntry?.key!==e.key){if(this._exitMaximizedEntry(),e.wrapper.parentElement){let t=document.createElement(`div`);t.className=`drawio-maximize-spacer`,t.style.height=`${Math.ceil(e.wrapper.getBoundingClientRect().height)}px`,e.maximizeSpacer=t,e.wrapper.parentElement.insertBefore(t,e.wrapper)}e.wrapper.classList.add(`is-maximized`),e.wrapper.dataset.drawioMaximized=`true`,e.wrapper.style.width=`auto`,e.wrapper.style.height=`auto`,e.wrapper.style.minHeight=`0`,document.body.classList.add(`drawio-maximized-open`),this.maximizedEntry=e,this.overlayRoot?.classList.add(`has-maximized-entry`),this.syncEntryLayout(e)}}_exitMaximizedEntry(){let e=this.maximizedEntry;if(!e?.wrapper){this.maximizedEntry=null,document.body.classList.remove(`drawio-maximized-open`);return}let{maximizeSpacer:t}=e;e.wrapper.classList.remove(`is-maximized`),delete e.wrapper.dataset.drawioMaximized,e.wrapper.style.width=``,e.wrapper.style.height=``,e.wrapper.style.minHeight=``,t?.parentElement&&t.remove(),e.maximizeSpacer=null,e.restoreParent=null,e.restoreNextSibling=null,this.maximizedEntry=null,document.body.classList.remove(`drawio-maximized-open`),this.overlayRoot?.classList.remove(`has-maximized-entry`),this.syncEntryLayout(e)}_syncMaximizeButtons(){this.embedEntries.forEach(e=>{let t=e.wrapper?.querySelector(`.drawio-embed-btn[data-action="toggle-maximize"]`);if(!(t instanceof HTMLElement))return;let n=this.maximizedEntry?.key===e.key;V(t,n?`restore`:`maximize`),t.title=n?`Restore diagram size`:`Maximize diagram`,t.setAttribute(`aria-label`,n?`Restore diagram size`:`Maximize diagram`)})}_findEntryByInstanceId(e){for(let t of this.embedEntries.values())if(t.instanceId===e)return t;return null}_isMessageFromEntry(e,t){return!!(t?.iframe?.contentWindow&&e.source===t.iframe.contentWindow)}_onMessage(e){if(e.origin!==window.location.origin)return;let t=e.data;if(!t||t.source!==`drawio-editor`)return;let n=this._findEntryByInstanceId(t.instanceId);if(n&&this._isMessageFromEntry(e,n)){if(t.type===`fallback-text`){if(n.mode===`view`){this.renderViewerFallback(n,`Failed to render draw.io preview`);return}this.onOpenTextFile?.(n.filePath);return}if(t.type===`error`){if(n.mode===`view`){this.renderViewerFallback(n,t.message||`Failed to load draw.io preview`);return}this.toastController?.show?.(t.message||`Failed to load draw.io`);return}if(t.type===`request-open-file`){this.onOpenFile?.(n.filePath);return}t.type===`request-toggle-quick-switcher`&&this.onToggleQuickSwitcher?.()}}_onPreviewClick(e){let t=e.target.closest(`.drawio-embed-placeholder-btn`);if(t){let n=t.closest(`.drawio-embed-placeholder`)?.dataset.drawioKey||``,r=this.embedEntries.get(n);r&&(e.preventDefault(),this.hydrateEntry(r));return}}_onKeyDown(e){e.key===`Escape`&&(this._exitMaximizedEntry(),this._syncMaximizeButtons())}renderViewerFallback(e,t){if(!e.wrapper)return;let n=e.wrapper.querySelector(`.drawio-viewer-shell, .drawio-viewer-frame`);if(!n)return;let r=document.createElement(`div`);r.className=`preview-shell`,r.textContent=t,n.replaceChildren(r),e.viewerElement=r}};function Nc(e,t){let n=new Map;t.forEach(t=>{let r=e.get(t.key)??{filePath:t.filePath,iframe:null,instanceId:null,key:t.key,label:t.label,placeholder:t.placeholder,queued:!1,wrapper:null};r.filePath=t.filePath,r.key=t.key,r.label=t.label,r.placeholder=t.placeholder,n.set(t.key,r)});let r=[];return e.forEach((e,t)=>{n.has(t)||r.push(e)}),{nextEntries:n,removedEntries:r}}var Pc=420,Fc=500,Ic=15e3,Lc=800,Rc=3,zc=200,Bc=`/excalidraw-editor.html`;function Vc(e,t){let n=e?.querySelectorAll?.(`.excalidraw-embed-placeholder[data-embed-key]`);return Array.from(n||[]).find(e=>e.dataset?.embedKey===t)||null}var Hc=class{constructor({getTheme:e,getLocalUser:t,onOpenFile:n=null,onStopFollowing:r=null,onToggleQuickSwitcher:i=null,previewContainer:a,previewElement:o,toastController:s}){this.getTheme=e,this.getLocalUser=t,this.onOpenFile=n,this.onStopFollowing=r,this.onToggleQuickSwitcher=i,this.previewContainer=a,this.previewElement=o,this.toastController=s,this.embedEntries=new Map,this.hydrationQueue=[],this.hydrationIdleId=null,this.hydrationPaused=!1,this.hydrationInProgress=!1,this.instanceCounter=0,this.isLargeDocument=!1,this.maximizedEmbed=null,this.overlayRoot=null,this.warmCacheRoot=null,this.warmEntry=null,this.placeholderObserver=null,this.followedPeerIdsByFilePath=new Map,this.pendingDisconnectRequests=new Map,this.disconnectRequestCounter=0,this._onMessage=this._onMessage.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onPreviewClick=this._onPreviewClick.bind(this),window.addEventListener(`message`,this._onMessage),window.addEventListener(`keydown`,this._onKeyDown),this.previewElement?.addEventListener(`click`,this._onPreviewClick)}destroy(){window.removeEventListener(`message`,this._onMessage),window.removeEventListener(`keydown`,this._onKeyDown),this.previewElement?.removeEventListener(`click`,this._onPreviewClick),this._disconnectPlaceholderObserver(),z(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this._exitMaximizedEmbed(),document.body.classList.remove(`excalidraw-maximized-open`),this.embedEntries.forEach(e=>{this._clearEntryBootTimeout(e),e.resizerCleanup?.(),e.resizerCleanup=null,e.wrapper?.remove(),e.placeholder=null}),this.embedEntries.clear(),this.warmEntry&&=(this._clearEntryBootTimeout(this.warmEntry),this.warmEntry.resizerCleanup?.(),this.warmEntry.resizerCleanup=null,this.warmEntry.wrapper?.remove(),null),this.pendingDisconnectRequests.forEach(e=>{e.resolve(!1)}),this.pendingDisconnectRequests.clear(),this.followedPeerIdsByFilePath.clear(),this.overlayRoot?.remove(),this.overlayRoot=null,this.warmCacheRoot?.remove(),this.warmCacheRoot=null}async setFollowedUser(e,t=null){if(!e)return!1;this.followedPeerIdsByFilePath.set(e,t||null);let n=this._findEntryByFilePath(e);return!n||(n.wrapper||await this._hydrateEntry(n),n.followedPeerId=this.followedPeerIdsByFilePath.get(e)??null,this._syncEntryFollowState(n),!0)}detachForCommit(){this._disconnectPlaceholderObserver(),z(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this.hydrationInProgress=!1,this._exitMaximizedEmbed(),this.overlayRoot&&(this.overlayRoot.hidden=!0),this.embedEntries.forEach(e=>{e.queued=!1,e.placeholder=null})}setHydrationPaused(e){if(this.hydrationPaused=!!e,this.hydrationPaused){z(this.hydrationIdleId),this.hydrationIdleId=null;return}this.hydrateVisibleEmbeds(),this._scheduleHydration()}reconcileEmbeds(e,{isLargeDocument:t=!1}={}){this.isLargeDocument=!!t,this._disconnectPlaceholderObserver(),z(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this.hydrationInProgress=!1;let n=Array.from(e.querySelectorAll(`.excalidraw-embed-placeholder[data-embed-key]`)).map(e=>({filePath:e.dataset.embedTarget,key:e.dataset.embedKey,label:e.dataset.embedLabel||e.dataset.embedTarget,placeholder:e})),{nextEntries:r,removedEntries:i}=Nc(this.embedEntries,n);this._captureWarmEntry(i),this._adoptReusableEntries(r,i),i.forEach(e=>this._destroyEntry(e)),this.embedEntries=r,this._ensurePlaceholderObserver(),this.embedEntries.forEach(e=>{if(e.queued=!1,e.followedPeerId=this.followedPeerIdsByFilePath.get(e.filePath),e.wrapper){this._hydrateEntry(e);return}e.placeholder&&this.placeholderObserver?.observe(e.placeholder)}),this.hydrationPaused||this.hydrateVisibleEmbeds(),this.syncLayout()}hydrateVisibleEmbeds(){if(this.hydrationPaused)return;let e=this.isLargeDocument?180:420;this.embedEntries.forEach(t=>{t.wrapper||!t.placeholder?.isConnected||we(t.placeholder,this.previewContainer,e)&&this._enqueueHydration(t,{prioritize:!0})})}updateTheme(e){this._forEachManagedEntry(t=>{this._postMessageToEntry(t,{source:`collabmd-host`,type:`set-theme`,theme:e})})}updateLocalUser(e){this._forEachManagedEntry(t=>{this._syncEntryUser(t,e)})}openCommentThread(e,t){if(!e||!t)return!1;let n=this._findEntryByFilePath(e);return n?(n.pendingCommentThreadId=t,n.isReady?this._postPendingCommentThread(n):n.wrapper||this._enqueueHydration(n,{prioritize:!0}),!0):!1}prepareFileDisconnect(e,{timeoutMs:t=1e4}={}){let n=this._findEntryByFilePath(e);if(!n?.iframe?.contentWindow)return Promise.resolve(!0);let r=`disconnect-${++this.disconnectRequestCounter}`;return new Promise(e=>{let i=t=>{if(!this.pendingDisconnectRequests.has(r))return;let n=this.pendingDisconnectRequests.get(r);window.clearTimeout(n.timeoutId),this.pendingDisconnectRequests.delete(r),e(t)},a=window.setTimeout(()=>{if(!window.confirm(`This diagram has not reconnected, so its latest queued changes may not be saved. Discard pending changes and leave?`)){this._postMessageToEntry(n,{source:`collabmd-host`,type:`cancel-disconnect`,requestId:r}),this.toastController?.show?.(`Stayed on the diagram while it reconnects`),i(!1);return}this._postMessageToEntry(n,{source:`collabmd-host`,type:`discard-and-disconnect`,requestId:r});let e=this.pendingDisconnectRequests.get(r);e&&(e.timeoutId=window.setTimeout(()=>i(!0),1e3))},t);this.pendingDisconnectRequests.set(r,{entry:n,resolve:i,timeoutId:a}),this._postMessageToEntry(n,{source:`collabmd-host`,type:`prepare-disconnect`,requestId:r})})}_ensurePlaceholderObserver(){this.previewContainer&&(this.placeholderObserver=new IntersectionObserver(e=>{e.forEach(e=>{if(!e.isIntersecting)return;let t=this.embedEntries.get(e.target.dataset.embedKey);t&&this._enqueueHydration(t)})},{root:this.previewContainer,rootMargin:this.isLargeDocument?`180px 0px`:`420px 0px`}))}_disconnectPlaceholderObserver(){this.placeholderObserver&&=(this.placeholderObserver.disconnect(),null)}_enqueueHydration(e,{prioritize:t=!1}={}){if(!(!e||e.wrapper||e.queued)&&(e.queued=!0,t?this.hydrationQueue.unshift(e.key):this.hydrationQueue.push(e.key),!this.hydrationPaused)){if(t&&!this.hydrationInProgress&&this.hydrationIdleId===null){this._flushHydrationQueue();return}this._scheduleHydration()}}_scheduleHydration(){this.hydrationPaused||this.hydrationInProgress||this.hydrationIdleId!==null||(this.hydrationIdleId=R(()=>{this.hydrationIdleId=null,this._flushHydrationQueue()},Fc))}async _flushHydrationQueue(){if(this.hydrationPaused||this.hydrationInProgress)return;let e=null;for(;this.hydrationQueue.length>0&&!e;){let t=this.hydrationQueue.shift(),n=this.embedEntries.get(t);if(!n||n.wrapper||!n.placeholder?.isConnected){n&&(n.queued=!1);continue}e=n}e&&(this.hydrationInProgress=!0,e.queued=!1,await this._hydrateEntry(e),this.hydrationInProgress=!1,this.hydrationQueue.length>0&&this._scheduleHydration())}async _hydrateEntry(e){if(!(!e.placeholder?.isConnected&&!e.wrapper)){if(e.isParked=!1,!e.wrapper){let t=this._createEmbedContainer(e);e.header=t.header,e.wrapper=t.wrapper,e.iframe=t.iframe,e.labelElement=t.labelElement,e.maxButton=t.maxButton,e.openButton=t.openButton,e.instanceId=t.instanceId,e.resizerCleanup=t.resizerCleanup,e.isReady=!1,e.bootFilePath=e.filePath,e.bootMode=this._getEntryMode(e),e.loadedFilePath=e.bootFilePath,e.loadedMode=e.bootMode,e.bootAttempts=(e.bootAttempts??0)+1,this._armEntryBootTimeout(e)}e.followedPeerId=this.followedPeerIdsByFilePath.get(e.filePath),this._updateEmbedLabel(e),this._entryNeedsHardReload(e)&&this._reloadEntry(e),this._attachWrapper(e)}}_attachWrapper(e){let t=e.placeholder?.isConnected?e.placeholder:Vc(this.previewElement,e.key);if(!t)return;if(e.placeholder=t,this._syncMountedEntryMetadata(e),this._shouldInlineFilePreview(e)){e.wrapper.style.position=``,e.wrapper.style.top=``,e.wrapper.style.left=``,e.wrapper.style.width=``,e.wrapper.style.margin=``,e.wrapper.style.pointerEvents=`auto`,t.replaceWith(e.wrapper),e.placeholder=null;return}let n=this._ensureOverlayRoot();n.hidden=!1,e.wrapper?.parentElement!==n&&n.appendChild(e.wrapper),this._syncEntryLayout(e)}_adoptReusableEntries(e,t){e.forEach((n,r)=>{if(n.wrapper||n.iframe)return;let i=this._claimReusableEntry(n,t);i&&(i.filePath=n.filePath,i.key=n.key,i.label=n.label,i.placeholder=n.placeholder,i.queued=!1,e.set(r,i))})}_destroyEntry(e){this.pendingDisconnectRequests.forEach((t,n)=>{t.entry===e&&(t.resolve(!1),this.pendingDisconnectRequests.delete(n))}),this.maximizedEmbed?.wrapper===e.wrapper&&this._exitMaximizedEmbed(),this._clearEntryBootTimeout(e),e.resizerCleanup?.(),e.resizerCleanup=null,this.warmEntry===e&&(this.warmEntry=null),this._resetPlaceholderLayout(e),this._setEntryLoadingState(e,!1),e.wrapper?.remove(),e.placeholder=null}_armEntryBootTimeout(e,t=Ic){this._clearEntryBootTimeout(e),e.bootTimerId=window.setTimeout(()=>{this._handleEntryBootTimeout(e)},t)}_clearEntryBootTimeout(e){e?.bootTimerId&&(window.clearTimeout(e.bootTimerId),e.bootTimerId=null)}async _handleEntryBootTimeout(e){if(e?.iframe?.isConnected){if((e.bootAttempts??0)>=Rc){this._clearEntryBootTimeout(e),this.toastController?.show(`Excalidraw embed timed out: ${e.label}`);return}await this._retryEntryBootstrap(e)}}async _retryEntryBootstrap(e){e&&(this._clearEntryBootTimeout(e),this._resetPlaceholderLayout(e),this._setEntryLoadingState(e,!1),this.maximizedEmbed?.wrapper===e.wrapper&&this._exitMaximizedEmbed(),e.wrapper?.remove(),e.wrapper=null,e.iframe=null,e.header=null,e.labelElement=null,e.maxButton=null,e.openButton=null,e.instanceId=null,e.isReady=!1,e.isParked=!1,e.bootFilePath=null,e.bootMode=null,e.loadedFilePath=null,e.loadedMode=null,await this._hydrateEntry(e))}_findEntryByContentWindow(e){if(!e)return null;for(let t of this.embedEntries.values())if(t.iframe?.contentWindow===e)return t;return this.warmEntry?.iframe?.contentWindow===e?this.warmEntry:null}_findEntryByFilePath(e){if(!e)return null;for(let t of this.embedEntries.values())if(t.filePath===e)return t;return this.warmEntry?.filePath===e?this.warmEntry:null}_updateEmbedLabel(e){e.labelElement&&(e.labelElement.textContent=e.label.replace(/\.excalidraw$/i,``))}_syncMountedEntryMetadata(e){e.wrapper&&(e.wrapper.dataset.embedKey=e.key,e.wrapper.dataset.file=e.filePath,e.wrapper.classList.toggle(`is-direct-file`,this._isFilePreviewEntry(e))),e.iframe&&(e.iframe.title=`Excalidraw: ${e.filePath}`),e.openButton&&(this._isFilePreviewEntry(e)?e.openButton.remove():!e.openButton.isConnected&&e.header&&e.header.insertBefore(e.openButton,e.maxButton||null))}_buildIframeUrl(e){let t=new URL(se(Bc)),n=this.getTheme?.()||`dark`;t.searchParams.set(`file`,e.filePath),t.searchParams.set(`theme`,n),t.searchParams.set(`boot`,e.instanceId||``),this._isFilePreviewEntry(e)||t.searchParams.set(`mode`,`preview`);let r=this.getLocalUser?.();r?.name&&t.searchParams.set(`userName`,r.name),r?.color&&t.searchParams.set(`userColor`,r.color),r?.colorLight&&t.searchParams.set(`userColorLight`,r.colorLight),r?.peerId&&t.searchParams.set(`userPeerId`,r.peerId);let i=new URLSearchParams(window.location.search),a=pe();return a&&t.searchParams.set(`server`,a),i.get(`test`)===`1`&&t.searchParams.set(`test`,`1`),i.has(`syncTimeoutMs`)&&t.searchParams.set(`syncTimeoutMs`,i.get(`syncTimeoutMs`)),i.get(`excalidrawDebug`)===`1`&&t.searchParams.set(`excalidrawDebug`,`1`),t}_createEmbedContainer(e){let t=document.createElement(`div`);t.className=`excalidraw-embed diagram-preview-shell`,t.dataset.embedKey=e.key,t.dataset.file=e.filePath;let n=document.createElement(`div`);n.className=`excalidraw-embed-header diagram-preview-toolbar`;let r=document.createElement(`span`);r.className=`excalidraw-embed-icon`,r.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19l7-7 3 3-7 7-3-3z"/><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><path d="M2 2l7.586 7.586"/><circle cx="11" cy="11" r="2"/></svg>`;let i=document.createElement(`span`);i.className=`excalidraw-embed-label`,i.textContent=e.label.replace(/\.excalidraw$/i,``);let a=document.createElement(`button`);a.type=`button`,a.className=`excalidraw-embed-btn ui-preview-action ui-preview-action--icon-only`,a.title=`Edit in Excalidraw`,a.setAttribute(`aria-label`,`Edit in Excalidraw`),V(a,`edit`);let o=document.createElement(`button`);o.type=`button`,o.className=`excalidraw-embed-btn ui-preview-action ui-preview-action--icon-only`,o.title=`Maximize diagram`,o.setAttribute(`aria-label`,`Maximize diagram`),V(o,`maximize`),n.append(r,i),this._isFilePreviewEntry(e)||n.append(a),n.append(o);let s=document.createElement(`iframe`);s.className=`excalidraw-embed-iframe`,s.dataset.instanceId=String(++this.instanceCounter),e.instanceId=s.dataset.instanceId,s.src=this._buildIframeUrl(e).toString(),s.setAttribute(`loading`,`eager`),s.title=`Excalidraw: ${e.filePath}`,s.style.height=`${Pc}px`;let c=document.createElement(`div`);c.className=`excalidraw-embed-resizer`,c.title=`Drag to resize`;let l=this._setupResizer(c,s,()=>{this._syncEntryLayout(e),this._requestPreviewViewportFit(e)});t.append(n,s,c);let u=!1,d=`${Pc}px`,f=()=>{V(o,u?`restore`:`maximize`),o.title=u?`Restore diagram size`:`Maximize diagram`,o.setAttribute(`aria-label`,u?`Restore diagram size`:`Maximize diagram`)},p=()=>{u&&(u=!1,t.classList.remove(`is-maximized`),f(),document.body.classList.remove(`excalidraw-maximized-open`),this._restoreMaximizedEntryLayout(e),s.style.height=d,this.maximizedEmbed?.wrapper===t&&(this.maximizedEmbed=null),this._syncEntryLayout(e),this._requestPreviewViewportFit(e))},m=()=>{u||(this._exitMaximizedEmbed(),u=!0,d=s.style.height||`${Pc}px`,this._enterMaximizedEntryLayout(e),t.classList.add(`is-maximized`),f(),document.body.classList.add(`excalidraw-maximized-open`),this.maximizedEmbed={wrapper:t,exit:p},this._syncEntryLayout(e),this._requestPreviewViewportFit(e))};return o.addEventListener(`click`,()=>{u?p():m()}),a.addEventListener(`click`,t=>{t.preventDefault(),this._exitMaximizedEmbed(),this.onOpenFile?.(e.filePath)}),f(),{header:n,iframe:s,instanceId:s.dataset.instanceId,labelElement:i,maxButton:o,openButton:a,resizerCleanup:l,wrapper:t}}_ensureWarmCacheRoot(){if(this.warmCacheRoot?.isConnected&&this.warmCacheRoot.parentElement===document.body)return this.warmCacheRoot;let e=document.body.querySelector(`[data-excalidraw-warm-cache-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.excalidrawWarmCacheRoot=`true`,e.className=`excalidraw-warm-cache-root`,document.body.appendChild(e)),this.warmCacheRoot=e,e}_setupResizer(e,t,n=null){let r=0,i=0,a=!1,o=e=>{let n=e.clientY-r,a=Math.min(Math.max(i+n,zc),Lc);t.style.height=`${a}px`,t.style.pointerEvents=`none`},s=()=>{a&&(a=!1,t.style.pointerEvents=``,document.removeEventListener(`pointermove`,o),document.removeEventListener(`pointerup`,c))},c=()=>{s(),n?.()},l=e=>{e.preventDefault(),a=!0,r=e.clientY,i=t.offsetHeight,document.addEventListener(`pointermove`,o),document.addEventListener(`pointerup`,c)};return e.addEventListener(`pointerdown`,l),()=>{e.removeEventListener?.(`pointerdown`,l),s()}}_ensureOverlayRoot(){if(this.overlayRoot?.isConnected&&this.overlayRoot.parentElement===this.previewElement)return this.overlayRoot;let e=this.previewElement?.querySelector(`[data-excalidraw-overlay-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.excalidrawOverlayRoot=`true`,e.className=`excalidraw-embed-overlay-root`,this.previewElement?.appendChild(e)),this.overlayRoot=e,e}_isFilePreviewEntry(e){return e?.key===`${e?.filePath}#file-preview`}_getEntryMode(e){return this._isFilePreviewEntry(e)?`edit`:`preview`}_shouldInlineFilePreview(e){return this._isFilePreviewEntry(e)}_entryNeedsHardReload(e){let t=this._getEntryMode(e);return!!(e?.wrapper&&e.iframe&&(e.isReady?e.loadedFilePath!==e.filePath||e.loadedMode!==t:e.bootFilePath!==e.filePath||e.bootMode!==t))}_setEntryLoadingState(e,t){e?.wrapper&&(e.wrapper.classList.toggle(`is-loading`,!!t),e.wrapper.setAttribute(`aria-busy`,t?`true`:`false`))}_forEachManagedEntry(e){let t=new Set;this.embedEntries.forEach(n=>{!n||t.has(n)||(t.add(n),e(n))}),this.warmEntry&&!t.has(this.warmEntry)&&e(this.warmEntry)}_claimEntryFromRemovedEntries(e,t){let n=e.findIndex(e=>(e.wrapper||e.iframe)&&t(e));if(n<0)return null;let[r]=e.splice(n,1);return r}_claimReusableEntry(e,t){let n=this._getEntryMode(e);return this._claimEntryFromRemovedEntries(t,t=>t.filePath===e.filePath&&this._getEntryMode(t)===n)||(this._isFilePreviewEntry(e)?this._claimEntryFromRemovedEntries(t,t=>t.filePath===e.filePath)||this._claimWarmEntry()||this._claimEntryFromRemovedEntries(t,e=>this._isFilePreviewEntry(e)):null)}_claimWarmEntry(){let e=this.warmEntry;return e?(this.warmEntry=null,e):null}_captureWarmEntry(e){let t=this._claimEntryFromRemovedEntries(e,e=>this._isFilePreviewEntry(e));t&&(this.warmEntry&&this.warmEntry!==t&&this._destroyEntry(this.warmEntry),this.warmEntry=t,this._parkWarmEntry(t))}_parkWarmEntry(e){if(!e?.wrapper)return;this.maximizedEmbed?.wrapper===e.wrapper&&this._exitMaximizedEmbed();let t=this._ensureWarmCacheRoot();this._setEntryLoadingState(e,!1),e.isParked=!0,e.isReady=!1,e.bootFilePath=null,e.bootMode=null,e.loadedFilePath=null,e.loadedMode=null,e.placeholder=null,e.wrapper.parentElement!==t&&t.appendChild(e.wrapper),this._postMessageToEntry(e,{source:`collabmd-host`,type:`park-room`})}_reloadEntry(e){e?.iframe&&(this._clearEntryBootTimeout(e),this._setEntryLoadingState(e,!0),e.isReady=!1,e.bootAttempts=(e.bootAttempts??0)+1,e.bootFilePath=e.filePath,e.bootMode=this._getEntryMode(e),e.loadedFilePath=null,e.loadedMode=null,e.iframe.src=this._buildIframeUrl(e).toString(),this._armEntryBootTimeout(e))}_resetPlaceholderLayout(e){!e?.placeholder?.isConnected||this._shouldInlineFilePreview(e)||(e.placeholder.classList.remove(`is-hydrated`),e.placeholder.removeAttribute(`data-embed-hydrated`),e.placeholder.style.height=``,e.placeholder.style.pointerEvents=``)}_enterMaximizedEntryLayout(e){if(e?.wrapper){if(this._shouldInlineFilePreview(e)&&e.wrapper.parentElement&&!e.maximizeSpacer){let t=document.createElement(`div`);t.className=`excalidraw-maximize-spacer`,t.style.height=`${Math.ceil(e.wrapper.getBoundingClientRect().height)}px`,e.maximizeSpacer=t,e.wrapper.parentElement.insertBefore(t,e.wrapper)}e.wrapper.dataset.excalidrawMaximized=`true`,e.wrapper.style.position=``,e.wrapper.style.top=``,e.wrapper.style.left=``,e.wrapper.style.width=`auto`,e.wrapper.style.height=`auto`,e.wrapper.style.minHeight=`0`,e.wrapper.style.margin=`0`,this.overlayRoot?.classList.add(`has-maximized-entry`)}}_restoreMaximizedEntryLayout(e){if(!e?.wrapper)return;let{maximizeSpacer:t}=e;delete e.wrapper.dataset.excalidrawMaximized,e.wrapper.style.width=``,e.wrapper.style.height=``,e.wrapper.style.minHeight=``,t?.parentElement&&t.remove(),e.maximizeSpacer=null,this.overlayRoot?.classList.remove(`has-maximized-entry`)}_syncEntryLayout(e){if(!e?.wrapper||this._shouldInlineFilePreview(e))return;let t=e.placeholder?.isConnected?e.placeholder:Vc(this.previewElement,e.key);if(!t)return;e.placeholder=t,t.classList.add(`is-hydrated`),t.dataset.embedHydrated=`true`,t.style.pointerEvents=`none`,this._isFilePreviewEntry(e)&&t.childElementCount>0&&t.replaceChildren();let n=e.wrapper.classList.contains(`is-maximized`),r=e.wrapper.querySelector(`.excalidraw-embed-header`)?.offsetHeight||0,i=e.iframe?.offsetHeight||Number.parseFloat(e.iframe?.style.height||``)||Pc,a=n?0:e.wrapper.querySelector(`.excalidraw-embed-resizer`)?.offsetHeight||0,o=Math.ceil(r+i+a);if(n||(e.inlineHeightPx=o),t.style.height=`${Math.ceil(e.inlineHeightPx||o||Pc)}px`,e.wrapper.style.pointerEvents=`auto`,n){e.wrapper.style.position=``,e.wrapper.style.top=``,e.wrapper.style.left=``,e.wrapper.style.width=`auto`,e.wrapper.style.height=`auto`,e.wrapper.style.minHeight=`0`,e.wrapper.style.margin=`0`;return}e.wrapper.style.position=`absolute`,e.wrapper.style.top=`${t.offsetTop}px`,e.wrapper.style.left=`${t.offsetLeft}px`,e.wrapper.style.width=`${t.offsetWidth}px`,e.wrapper.style.height=``,e.wrapper.style.minHeight=``,e.wrapper.style.margin=`0`}syncLayout(){this.embedEntries.forEach(e=>{e.wrapper&&!this._shouldInlineFilePreview(e)&&this._syncEntryLayout(e)})}_onPreviewClick(e){let t=e.target.closest(`.excalidraw-embed-placeholder-btn`);if(!t)return;e.preventDefault();let n=this.embedEntries.get(t.dataset.embedKey);n&&this._hydrateEntry(n)}_onMessage(e){if(e.origin!==window.location.origin)return;let t=e.data;if(!t||t.source!==`excalidraw-editor`)return;let n=this._findEntryByContentWindow(e.source);if(n){if(t.type===`ready`){if(n.isParked)return;n.isReady=!0,this._clearEntryBootTimeout(n),n.loadedFilePath=n.bootFilePath||n.filePath,n.loadedMode=n.bootMode||this._getEntryMode(n),this._setEntryLoadingState(n,!1),this._syncEntryUser(n),this._postMessageToEntry(n,{source:`collabmd-host`,type:`set-theme`,theme:this.getTheme?.()||`dark`}),this._syncEntryFollowState(n),this._postPendingCommentThread?.(n),this._entryNeedsHardReload(n)&&this._hydrateEntry(n);return}if(t.type===`request-toggle-quick-switcher`){this.onToggleQuickSwitcher?.();return}if(t.type===`stop-following`){this.onStopFollowing?.();return}if(t.type===`error`){if(n.isParked)return;n.isReady=!1,this._handleEntryBootTimeout(n);return}if(t.type===`disconnect-ready`){let e=this.pendingDisconnectRequests.get(t.requestId);e?.entry===n&&e.resolve(!0);return}if(t.type===`disconnect-blocked`){n.authorityState=t.state||`reconnecting-readonly`,this.toastController?.show?.(`Waiting for the diagram to reconnect before leaving`);return}if(t.type===`excalidraw-authority-state`){n.authorityState=t.state||`closed`,n.hasPendingWrites=!!t.hasPendingWrites;return}t.type===`park-blocked`&&(n.authorityState=t.state||`reconnecting-readonly`)}}_onKeyDown(e){e.key===`Escape`&&this._exitMaximizedEmbed()}_exitMaximizedEmbed(){this.maximizedEmbed?.exit&&this.maximizedEmbed.exit(),this.maximizedEmbed=null,document.body.classList.remove(`excalidraw-maximized-open`)}_postMessageToEntry(e,t){e?.iframe?.contentWindow?.postMessage(t,window.location.origin)}_postPendingCommentThread(e){!e?.isReady||!e.pendingCommentThreadId||(this._postMessageToEntry(e,{source:`collabmd-host`,threadId:e.pendingCommentThreadId,type:`open-comment-thread`}),e.pendingCommentThreadId=null)}_requestPreviewViewportFit(e){this._isFilePreviewEntry(e)||this._postMessageToEntry(e,{source:`collabmd-host`,type:`fit-preview-viewport`})}_syncEntryUser(e,t=null){let n=t||this.getLocalUser?.();n&&this._postMessageToEntry(e,{source:`collabmd-host`,type:`set-user`,user:{color:n.color||``,colorLight:n.colorLight||``,name:n.name||``,peerId:n.peerId||``}})}_syncEntryFollowState(e){!e?.isReady||e.followedPeerId===void 0||this._postMessageToEntry(e,{source:`collabmd-host`,type:`follow-user`,peerId:e.followedPeerId})}},Uc=Object.freeze({".gif":`GIF`,".jpeg":`JPEG`,".jpg":`JPEG`,".png":`PNG`,".svg":`SVG`,".webp":`WebP`});function Wc(e=null){return e?.fileKind||m(e?.path)||null}function Gc(e=``){let t=String(e??``).toLowerCase(),n=Object.keys(Uc).find(e=>t.endsWith(e));return n?Uc[n]:`Image`}function Kc(e=``){try{let t=JSON.parse(String(e??``));return!t||typeof t!=`object`||!Array.isArray(t.elements)?null:t}catch{return null}}function qc(e=[]){if(e.length===0)return null;let t=e.join(`
445
- `);return Kc(t)?t:e.find(e=>Kc(e))??null}function Jc(e={}){let t=[],n=[];for(let r of e.hunks??[])for(let e of r.lines??[])e.type===`context`?(t.push(e.content),n.push(e.content)):e.type===`deletion`?t.push(e.content):e.type===`addition`&&n.push(e.content);let r=qc(t),i=qc(n),a=e.status===`added`||e.status===`untracked`,o=e.status===`deleted`;return{after:o?null:Kc(i),before:a?null:Kc(r),afterSource:o?``:i||``,beforeSource:a?``:r||``}}function Yc(e=null){return Array.isArray(e?.elements)?e.elements.filter(e=>e&&!e.isDeleted):[]}function Xc(e){if(!e||typeof e!=`object`)return``;let t={...e};return delete t.version,delete t.versionNonce,JSON.stringify(t)}function Zc(e,t){if(!e&&!t)return null;let n=new Map(Yc(e).map(e=>[e.id,e])),r=new Map(Yc(t).map(e=>[e.id,e])),i=0,a=0,o=0;for(let[e,t]of r)n.has(e)?Xc(n.get(e))!==Xc(t)&&(o+=1):i+=1;for(let e of n.keys())r.has(e)||(a+=1);return{added:i,afterCount:r.size,beforeCount:n.size,removed:a,updated:o}}function Qc(e){let t=Number(e);return!Number.isFinite(t)||t<0?``:t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(+(t<10240))} KB`:`${(t/1048576).toFixed(1)} MB`}function $c(e){return/<(?:mxfile|mxGraphModel|diagram)\b/iu.test(String(e??``))}function el(e){return String(e??``).replace(/>\s*</gu,`>
446
- <`).trim()}function tl(e=[]){if(e.length===0)return``;let t=e.join(`
447
- `);return $c(t)?t:e.find(e=>$c(e))??``}function nl(e={}){let t=[],n=[];for(let r of e.hunks??[])for(let e of r.lines??[])e.type===`context`?(t.push(e.content),n.push(e.content)):e.type===`deletion`?t.push(e.content):e.type===`addition`&&n.push(e.content);let r=typeof e.drawioBeforeSource==`string`?e.drawioBeforeSource:tl(t),i=typeof e.drawioAfterSource==`string`?e.drawioAfterSource:tl(n),a=e.status===`added`||e.status===`untracked`;return{after:e.status===`deleted`?``:i,before:a?``:r}}function rl(e){return String(e??``).replace(/&quot;/gu,`"`).replace(/&apos;/gu,`'`).replace(/&amp;/gu,`&`).replace(/&lt;/gu,`<`).replace(/&gt;/gu,`>`)}function il(e){let t=new Map,n=/<mxCell\b([^>]*?)(?:\/|>([\s\S]*?)<\/mxCell\s*)>/giu,r;for(;(r=n.exec(String(e??``)))!==null;){let e=rl(r[1].match(/\bid\s*=\s*(['"])(.*?)\1/iu)?.[2]||``);if(!e||e===`0`||e===`1`)continue;let n=`${r[1]}${r[2]||``}`.replace(/\s+/gu,` `).trim();t.set(e,n)}return t}function al(e){return/<mxGraphModel\b/iu.test(String(e??``))&&il(e).size===0}function ol(e,t){if(!e&&!t)return null;let n=il(e),r=il(t),i=n.size>0||r.size>0,a=0,o=0,s=0;if(i){for(let[e,t]of r)n.has(e)?n.get(e)!==t&&(s+=1):a+=1;for(let e of n.keys())r.has(e)||(o+=1);e!==t&&a===0&&o===0&&s===0&&(s=1)}else{let n=!!e,r=!!t;a=!n&&r?1:0,o=n&&!r?1:0,s=n&&r&&e!==t?1:0}return{added:a,afterCount:r.size,beforeCount:n.size,cellBased:i,removed:o,updated:s}}function sl(e){return`diff-section-${encodeURIComponent(String(e??``)).replace(/%/g,`_`)}`}function cl(e){switch(e){case`added`:case`untracked`:return`ui-status-badge--success`;case`deleted`:return`ui-status-badge--danger`;case`renamed`:return`ui-status-badge--accent`;default:return`ui-status-badge--warning`}}function ll(e=!1){return`<svg class="diff-section-chevron${e?` collapsed`:``}" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg>`}function ul(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n}function dl(e,t,n){let r=0,i=Math.min(e.length,t.length)-n;for(;r<i;){let n=e.length-1-r,i=t.length-1-r;if(e[n]!==t[i])break;r+=1}return r}function fl(e,t){let n=ul(e,t),r=dl(e,t,n),i=Math.max(n,e.length-r),a=Math.max(n,t.length-r);return{leftHtml:`${y(e.slice(0,n))}${i>n?`<span class="diff-highlight-del">${y(e.slice(n,i))}</span>`:``}${y(e.slice(i))}`,rightHtml:`${y(t.slice(0,n))}${a>n?`<span class="diff-highlight-add">${y(t.slice(n,a))}</span>`:``}${y(t.slice(a))}`}}function pl(e=[]){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.type===`context`||r.type===`note`){t.push({additions:[],context:[r],deletions:[]});continue}if(r.type!==`deletion`&&r.type!==`addition`)continue;let i=[],a=[];for(;n<e.length&&e[n].type===`deletion`;)i.push(e[n]),n+=1;for(;n<e.length&&e[n].type===`addition`;)a.push(e[n]),n+=1;--n,t.push({additions:a,context:[],deletions:i})}return t}function ml(e,t,n){let r=Number.isInteger(e.oldLine)?e.oldLine:``,i=Number.isInteger(e.newLine)?e.newLine:``,a=e.type===`note`?`note`:e.type,o=e.type===`context`||e.type===`note`?` `:t;return`
448
- <div class="diff-line ${a}">
449
- <div class="diff-line-numbers">
450
- <span class="diff-line-num">${r}</span>
451
- <span class="diff-line-num">${i}</span>
452
- </div>
453
- <div class="diff-line-prefix">${y(o)}</div>
454
- <div class="diff-line-content">${n}</div>
455
- </div>
456
- `}function hl(e,t){let n=e?y(e.content):``,r=t?y(t.content):``;if(e&&t&&e.type===`deletion`&&t.type===`addition`){let i=fl(e.content,t.content);n=i.leftHtml,r=i.rightHtml}return`
457
- <div class="diff-split-row">
458
- <div class="diff-split-line ${e?.type||`empty`}">
459
- <span class="diff-split-num">${Number.isInteger(e?.oldLine)?e.oldLine:``}</span>
460
- <span class="diff-split-content">${n}</span>
461
- </div>
462
- <div class="diff-split-line ${t?.type||`empty`}">
463
- <span class="diff-split-num">${Number.isInteger(t?.newLine)?t.newLine:``}</span>
464
- <span class="diff-split-content">${r}</span>
465
- </div>
466
- </div>
467
- `}var gl=class{constructor({getTheme:e=()=>`dark`,gitApiClient:t=null,onBackToHistory:n=null,onCommitStaged:r=null,onOpenFile:i=null,onStageFile:a=null,onUnstageFile:o=null,toastController:s=null,vaultApiClient:c=null}={}){this.getTheme=e,this.gitApiClient=t,this.onBackToHistory=n,this.onCommitStaged=r,this.onOpenFile=i,this.onStageFile=a,this.onUnstageFile=o,this.toastController=s,this.vaultApiClient=c,this.page=document.getElementById(`diff-page`),this.content=document.getElementById(`diffContent`),this.scrollContainer=document.getElementById(`diffScroll`),this.fileIndicator=document.getElementById(`diffFileIndicator`),this.openEditorButton=document.getElementById(`diffOpenEditorBtn`),this.primaryActionButton=document.getElementById(`diffPrimaryActionBtn`),this.commitButton=document.getElementById(`diffCommitBtn`),this.backToHistoryButton=document.getElementById(`diffBackToHistoryBtn`),this.gitActionsGroup=document.getElementById(`diffGitActionsGroup`),this.editorActionsGroup=document.getElementById(`diffEditorActionsGroup`),this.actionsDivider=document.getElementById(`diffToolbarDivider`),this.stats=document.getElementById(`diffStats`),this.prevButton=document.getElementById(`diffPrevBtn`),this.nextButton=document.getElementById(`diffNextBtn`),this.layoutToggle=document.getElementById(`diffLayoutToggle`),this.modeButtons=Array.from(document.querySelectorAll(`[data-diff-mode]`)),this.layoutButtons=Array.from(document.querySelectorAll(`[data-diff-layout]`)),this.isActive=!1,this.mode=`unified`,this.layoutMode=`focused`,this.source=`workspace`,this.data=null,this.currentIndex=0,this.activeFilePath=null,this.fileCache=new Map,this.fileErrors=new Map,this.loadingFiles=new Set,this.collapsedFiles=new Set,this.fileLoadPromises=new Map,this.excalidrawPreviewPayloads=new Map,this.excalidrawPreviewCounter=0,this.drawioPreviewPayloads=new Map,this.drawioPreviewCounter=0,this.requestScope=`all`,this.commitHash=null,this.commitBaseRef=null,this.commitMeta=null,this.historyFilePath=null,this.pendingAction=null,this.repoStatus=null}initialize(){this.prevButton?.addEventListener(`click`,()=>{this.isActive&&this.navigateFile(-1)}),this.nextButton?.addEventListener(`click`,()=>{this.isActive&&this.navigateFile(1)}),this.backToHistoryButton?.addEventListener(`click`,()=>{this.isActive&&this.commitMeta?.hash&&this.onBackToHistory?.({hash:this.commitMeta.hash,historyFilePath:this.historyFilePath})}),this.openEditorButton?.addEventListener(`click`,()=>{if(!this.isActive||this.source!==`workspace`)return;let e=this.getCurrentFile();e?.path&&this.onOpenFile?.(e.path)}),this.primaryActionButton?.addEventListener(`click`,()=>{if(!this.isActive)return;let e=this.getPrimaryAction();e&&this.handleFileAction(e)}),this.commitButton?.addEventListener(`click`,()=>{this.isActive&&this.handleFileAction(`commit`)}),this.content?.addEventListener(`click`,e=>{if(!this.isActive)return;let t=e.target instanceof Element?e.target.closest(`[data-load-full-diff]`):null;if(t){let e=t.getAttribute(`data-diff-file-path`)||this.activeFilePath;e&&this.loadFileForPath(e,{forceFullPatch:!0});return}let n=e.target instanceof Element?e.target.closest(`[data-diff-section-toggle]`):null;if(n){let e=n.getAttribute(`data-diff-section-toggle`);e&&this.toggleFileSection(e);return}let r=e.target instanceof Element?e.target.closest(`[data-diff-index-path]`):null;if(r){let e=r.getAttribute(`data-diff-index-path`);e&&this.handleIndexSelection(e)}}),this.modeButtons.forEach(e=>{e.addEventListener(`click`,()=>{if(!this.isActive)return;let t=e.getAttribute(`data-diff-mode`);!t||t===this.mode||(this.mode=t,this.render())})}),this.layoutButtons.forEach(e=>{e.addEventListener(`click`,()=>{if(!this.isActive)return;let t=e.getAttribute(`data-diff-layout`);!t||t===this.layoutMode||this.setLayoutMode(t)})}),this.scrollContainer?.addEventListener(`scroll`,()=>{this.isActive&&this.handleScrollSelection()})}hide(){this.isActive=!1,this.page?.classList.add(`hidden`),this.content&&(this.content.innerHTML=``),this.data=null,this.source=`workspace`,this.layoutMode=`focused`,this.currentIndex=0,this.activeFilePath=null,this.fileCache.clear(),this.fileErrors.clear(),this.loadingFiles.clear(),this.collapsedFiles.clear(),this.fileLoadPromises.clear(),this.excalidrawPreviewPayloads.clear(),this.drawioPreviewPayloads.clear(),this.requestScope=`all`,this.commitHash=null,this.commitBaseRef=null,this.commitMeta=null,this.historyFilePath=null,this.pendingAction=null,this.repoStatus=null}async openWorkspaceDiff({filePath:e=null,scope:t=`all`}={}){this.isActive=!0,this.source=`workspace`,this.layoutMode=`focused`,this.commitHash=null,this.commitBaseRef=null,this.commitMeta=null,this.historyFilePath=null,this.activeFilePath=e,this.fileCache.clear(),this.fileErrors.clear(),this.loadingFiles.clear(),this.collapsedFiles.clear(),this.fileLoadPromises.clear(),this.excalidrawPreviewPayloads.clear(),this.drawioPreviewPayloads.clear(),this.requestScope=t,this.renderLoading(`Loading diff summary...`);try{let n=await this.gitApiClient.readDiff({metaOnly:!0,path:e,scope:t});this.data=n;let r=e?Math.max(0,n.files.findIndex(t=>t.path===e)):0;return this.currentIndex=r,this.activeFilePath=n.files?.[r]?.path??null,(n.files?.length??0)===0?(this.render(),n):(await this.loadCurrentFile(),n)}catch(e){return console.error(`[git-diff] Failed to load diff:`,e),this.toastController?.show(`Failed to load git diff`),this.data={files:[],metaOnly:!1,source:`workspace`,summary:{additions:0,deletions:0,filesChanged:0}},this.renderEmpty(`Failed to load git diff`),this.data}}async openCommitDiff({hash:e,path:t=null,historyFilePath:n=null}={}){this.isActive=!0,this.source=`commit`,this.layoutMode=`stacked`,this.commitHash=String(e??``).trim()||null,this.commitBaseRef=null,this.commitMeta=null,this.historyFilePath=String(n??``).trim()||null,this.activeFilePath=t||null,this.fileCache.clear(),this.fileErrors.clear(),this.loadingFiles.clear(),this.collapsedFiles.clear(),this.fileLoadPromises.clear(),this.excalidrawPreviewPayloads.clear(),this.drawioPreviewPayloads.clear(),this.requestScope=`all`,this.renderLoading(`Loading commit summary...`);try{let e=await this.gitApiClient.readCommit({hash:this.commitHash||``,metaOnly:!0});this.data=e,this.commitMeta=e.commit??null,this.commitBaseRef=e.baseRef||null;let n=t?Math.max(0,e.files.findIndex(e=>e.path===t)):0;return this.currentIndex=n,this.activeFilePath=e.files?.[n]?.path??null,this.collapsedFiles=new Set((e.files??[]).map(e=>e.path).filter(e=>e&&e!==this.activeFilePath)),(e.files?.length??0)===0?(this.render(),e):(this.activeFilePath&&await this.loadFileForPath(this.activeFilePath,{render:!1}),this.render(),e)}catch(e){return console.error(`[git-diff] Failed to load commit:`,e),this.toastController?.show(`Failed to load git commit`),this.data={commit:null,files:[],metaOnly:!1,source:`commit`,summary:{additions:0,deletions:0,filesChanged:0}},this.commitMeta=null,this.renderEmpty(`Failed to load git commit`),this.data}}async open(e={}){return this.openWorkspaceDiff(e)}async setLayoutMode(e){let t=e===`stacked`?`stacked`:`focused`;if(this.source!==`commit`){this.layoutMode=`focused`,this.render();return}if(this.layoutMode=t,this.activeFilePath&&this.setActiveFilePath(this.activeFilePath),this.layoutMode===`focused`){await this.loadCurrentFile();return}this.activeFilePath&&(this.collapsedFiles.delete(this.activeFilePath),await this.loadFileForPath(this.activeFilePath,{render:!1})),this.render()}navigateFile(e){if(!this.data?.files?.length||this.source===`commit`&&this.layoutMode===`stacked`)return;let t=Math.max(0,Math.min(this.currentIndex+e,this.data.files.length-1));t!==this.currentIndex&&(this.currentIndex=t,this.activeFilePath=this.data.files[t]?.path??null,this.scrollContainer?.scrollTo({top:0,behavior:`auto`}),this.loadCurrentFile())}renderLoading(e=`Loading git diff...`){this.isActive&&(this.page?.classList.remove(`hidden`),this.content&&(this.content.innerHTML=`<div class="diff-empty-state">${y(e)}</div>`),this.data=null,this.syncToolbar())}renderEmpty(e){this.isActive&&(this.page?.classList.remove(`hidden`),this.content&&(this.content.innerHTML=`<div class="diff-empty-state">${y(e)}</div>`),this.syncToolbar())}renderUnifiedHunk(e){let t=[];for(let n of pl(e.lines)){if(n.context.length>0){for(let e of n.context)t.push(ml(e,` `,y(e.content)));continue}let e=Math.max(n.deletions.length,n.additions.length);for(let r=0;r<e;r+=1){let e=n.deletions[r]??null,i=n.additions[r]??null,a=e&&i?fl(e.content,i.content):null;e&&t.push(ml(e,`-`,a?.leftHtml??y(e.content))),i&&t.push(ml(i,`+`,a?.rightHtml??y(i.content)))}}return`
468
- <div class="diff-hunk-header">${y(e.header)}</div>
469
- ${t.join(``)}
470
- `}getGitImageUrl(e,t){return!e||!t?``:typeof this.gitApiClient?.getFileAttachmentUrl==`function`?this.gitApiClient.getFileAttachmentUrl({hash:e,path:t}):F(`/git/file-attachment?hash=${encodeURIComponent(e)}&path=${encodeURIComponent(t)}`)}getCurrentImageUrl(e){return e?F(`/attachment?path=${encodeURIComponent(e)}`):``}getImageDiffSources(e){let t=e.status===`added`||e.status===`untracked`,n=e.status===`deleted`,r=e.oldPath||e.path,i=e.path;return this.source===`commit`?{after:n?``:this.getGitImageUrl(this.commitHash,i),before:t?``:this.getGitImageUrl(this.commitBaseRef,r)}:{after:n?``:this.getCurrentImageUrl(i),before:t?``:this.getGitImageUrl(`HEAD`,r)}}renderImagePane({file:e,label:t,source:n,emptyLabel:r}){let i=n?`<img class="diff-media-image" src="${y(n)}" alt="${y(`${t} ${e.path}`)}" loading="lazy" decoding="async">`:`<div class="diff-media-empty"><span class="diff-media-empty-icon" aria-hidden="true">—</span><span>${y(r)}</span></div>`;return`
471
- <div class="diff-media-pane">
472
- <div class="diff-media-pane-header">
473
- <span class="diff-media-pane-label">${y(t)}</span>
474
- <span class="diff-media-pane-meta">${y(Gc(e.path))}</span>
475
- </div>
476
- <div class="diff-media-canvas">${i}</div>
477
- </div>
478
- `}renderImageDiff(e){let t=this.getImageDiffSources(e),n=Qc(e.byteLength);return`
479
- <section class="diff-special diff-media-diff" aria-label="Image diff">
480
- <div class="diff-special-header">
481
- <div>
482
- <span class="diff-special-eyebrow">Binary preview</span>
483
- <h2 class="diff-special-title">Image comparison</h2>
484
- </div>
485
- <span class="diff-special-note">${y(Gc(e.path))}${n?` · ${y(n)}`:``}</span>
486
- </div>
487
- <div class="diff-media-grid">
488
- ${this.renderImagePane({emptyLabel:`No previous image`,file:e,label:`Before`,source:t.before})}
489
- ${this.renderImagePane({emptyLabel:`No image in this revision`,file:e,label:`After`,source:t.after})}
490
- </div>
491
- <p class="diff-special-footnote">Image bytes are shown as a visual comparison instead of a text patch.</p>
492
- </section>
493
- `}registerExcalidrawPreview(e){if(!e)return``;this.excalidrawPreviewCounter+=1;let t=`diff-excalidraw-preview-${this.excalidrawPreviewCounter.toString(36)}`;return this.excalidrawPreviewPayloads.set(t,e),t}renderExcalidrawPane({label:e,scene:t,source:n,emptyLabel:r}){let i=this.registerExcalidrawPreview(t),a=t?`
494
- <div class="diff-excalidraw-preview" data-diff-excalidraw-preview="${y(i)}">
495
- <span class="diff-excalidraw-preview-loading">Rendering diagram…</span>
496
- </div>
497
- `:`<div class="diff-excalidraw-preview diff-excalidraw-preview--empty"><span>${y(r)}</span></div>`,o=n?`
498
- <details class="diff-excalidraw-source">
499
- <summary>Structured scene</summary>
500
- <pre>${y(n)}</pre>
501
- </details>
502
- `:``;return`
503
- <div class="diff-excalidraw-pane">
504
- <div class="diff-excalidraw-pane-header">
505
- <span class="diff-media-pane-label">${y(e)}</span>
506
- <span class="diff-media-pane-meta">${t?`${Yc(t).length} elements`:`—`}</span>
507
- </div>
508
- ${a}
509
- ${o}
510
- </div>
511
- `}renderExcalidrawDiff(e){let t=Jc(e),n=Zc(t.before,t.after)??{added:0,afterCount:0,beforeCount:0,removed:0,updated:0},r=!!(t.before||t.after),i=e.tooLarge&&e.canLoadFullPatch?`<button class="${W({variant:`secondary`,extra:`diff-load-full-btn`})}" type="button" data-load-full-diff data-diff-file-path="${y(e.path)}">Load full diff</button>`:``;return`
512
- <section class="diff-special diff-excalidraw-diff" aria-label="Excalidraw diff">
513
- <div class="diff-special-header">
514
- <div>
515
- <span class="diff-special-eyebrow">Diagram-aware preview</span>
516
- <h2 class="diff-special-title">Excalidraw scene changes</h2>
517
- </div>
518
- <span class="diff-special-note">${r?`${n.afterCount} visible elements`:`Scene preview unavailable`}</span>
519
- </div>
520
- <div class="diff-scene-summary" aria-label="Scene change summary">
521
- <span class="diff-scene-stat diff-scene-stat--add"><strong>+${n.added}</strong><span>added</span></span>
522
- <span class="diff-scene-stat diff-scene-stat--update"><strong>~${n.updated}</strong><span>updated</span></span>
523
- <span class="diff-scene-stat diff-scene-stat--remove"><strong>-${n.removed}</strong><span>removed</span></span>
524
- </div>
525
- <div class="diff-excalidraw-grid">
526
- ${this.renderExcalidrawPane({emptyLabel:`No previous scene`,label:`Before`,scene:t.before,source:t.beforeSource?JSON.stringify(t.before||Kc(t.beforeSource),null,2):``})}
527
- ${this.renderExcalidrawPane({emptyLabel:e.tooLarge?`Load the full diff to preview this scene`:`No scene in this revision`,label:`After`,scene:t.after,source:t.afterSource?JSON.stringify(t.after||Kc(t.afterSource),null,2):``})}
528
- </div>
529
- ${i}
530
- <p class="diff-special-footnote">The preview compares drawable elements by id; expand “Structured scene” when you need the underlying JSON.</p>
531
- </section>
532
- `}async readDrawioSource({hash:e=null,path:t=null,current:n=!1}={}){if(!t)return``;try{if(n){let e=await this.vaultApiClient?.readFile?.(t);return typeof e?.content==`string`?e.content:``}if(!e||typeof this.gitApiClient?.readFileSnapshot!=`function`)return``;let r=await this.gitApiClient.readFileSnapshot({hash:e,path:t});return typeof r?.content==`string`?r.content:``}catch{return``}}async enrichDrawioDetail(e){let t=nl(e),n=t.before,r=t.after,i=e.status===`added`||e.status===`untracked`,a=e.status===`deleted`,o=e.oldPath||e.path,s=e.path;return!i&&!$c(n)&&(n=await this.readDrawioSource({current:!1,hash:this.source===`commit`?this.commitBaseRef:`HEAD`,path:o})),!a&&!$c(r)&&(r=await this.readDrawioSource({current:this.source!==`commit`,hash:this.source===`commit`?this.commitHash:null,path:s})),{...e,drawioAfterSource:r,drawioBeforeSource:n}}registerDrawioPreview(e){if(!e)return``;this.drawioPreviewCounter+=1;let t=`diff-drawio-preview-${this.drawioPreviewCounter.toString(36)}`;return this.drawioPreviewPayloads.set(t,e),t}renderDrawioPane({emptyLabel:e,label:t,source:n}){let r=al(n),i=r?``:this.registerDrawioPreview(n),a=n&&!r?`
533
- <div class="diff-drawio-preview" data-diff-drawio-preview="${y(i)}">
534
- <span class="diff-drawio-preview-loading">Rendering draw.io preview…</span>
535
- </div>
536
- `:`<div class="diff-drawio-preview diff-drawio-preview--empty"><span>${y(r?`No drawable cells`:e)}</span></div>`,o=n?`
537
- <details class="diff-drawio-source">
538
- <summary>XML source</summary>
539
- <pre>${y(el(n))}</pre>
540
- </details>
541
- `:``;return`
542
- <div class="diff-drawio-pane">
543
- <div class="diff-drawio-pane-header">
544
- <span class="diff-media-pane-label">${y(t)}</span>
545
- <span class="diff-media-pane-meta">draw.io</span>
546
- </div>
547
- ${a}
548
- ${o}
549
- </div>
550
- `}renderDrawioDiff(e){let t=nl(e),n=ol(t.before,t.after)??{added:0,afterCount:0,beforeCount:0,cellBased:!1,removed:0,updated:0},r=t.before||t.after?n.cellBased?`${n.afterCount} drawable cells`:`Source-level comparison`:`Preview unavailable`,i=e.tooLarge&&e.canLoadFullPatch?`<button class="${W({variant:`secondary`,extra:`diff-load-full-btn`})}" type="button" data-load-full-diff data-diff-file-path="${y(e.path)}">Load full diff</button>`:``;return`
551
- <section class="diff-special diff-drawio-diff" aria-label="draw.io diff">
552
- <div class="diff-special-header">
553
- <div>
554
- <span class="diff-special-eyebrow">Diagram-aware preview</span>
555
- <h2 class="diff-special-title">draw.io diagram changes</h2>
556
- </div>
557
- <span class="diff-special-note">${y(r)}</span>
558
- </div>
559
- <div class="diff-scene-summary" aria-label="draw.io change summary">
560
- <span class="diff-scene-stat diff-scene-stat--add"><strong>+${n.added}</strong><span>added</span></span>
561
- <span class="diff-scene-stat diff-scene-stat--update"><strong>~${n.updated}</strong><span>updated</span></span>
562
- <span class="diff-scene-stat diff-scene-stat--remove"><strong>-${n.removed}</strong><span>removed</span></span>
563
- </div>
564
- <div class="diff-drawio-grid">
565
- ${this.renderDrawioPane({emptyLabel:`No previous diagram`,label:`Before`,source:t.before})}
566
- ${this.renderDrawioPane({emptyLabel:e.tooLarge?`Load the full diff to preview this diagram`:`No diagram in this revision`,label:`After`,source:t.after})}
567
- </div>
568
- ${i}
569
- <p class="diff-special-footnote">Both revisions use the draw.io viewer; expand “XML source” when you need the underlying document.</p>
570
- </section>
571
- `}async hydrateExcalidrawPreviews(){if(this.excalidrawPreviewPayloads.size===0||!this.content)return;let t;try{({exportToSvg:t}=await e(()=>import(`./prod-VxdGZ5Ly.js`),__vite__mapDeps([32,33,2,3,34,35,36,37,38,39]),import.meta.url))}catch(e){console.warn(`[git-diff] Excalidraw preview renderer unavailable:`,e);return}for(let[e,n]of this.excalidrawPreviewPayloads){let r=this.content.querySelector?.(`[data-diff-excalidraw-preview="${e}"]`);if(r)try{let e=await t({appState:{exportBackground:!0,exportWithDarkMode:!1,viewBackgroundColor:n.appState?.viewBackgroundColor||`#ffffff`},elements:Yc(n),exportPadding:24,files:n.files||null});r.replaceChildren(e),r.classList.add(`is-ready`)}catch(e){console.warn(`[git-diff] Failed to render Excalidraw scene preview:`,e),r.textContent=`Visual preview unavailable`,r.classList.add(`is-error`)}}}async hydrateDrawioPreviews(){if(!(this.drawioPreviewPayloads.size===0||!this.content))for(let[e,t]of this.drawioPreviewPayloads){let n=this.content.querySelector?.(`[data-diff-drawio-preview="${e}"]`);if(n)try{await Ac(n,{ariaLabel:`draw.io diagram diff preview`,className:`mxgraph drawio-viewer-frame diff-drawio-viewer-frame`,source:t,theme:this.getTheme?.()===`light`?`light`:`dark`}),n.classList.add(`is-ready`)}catch(e){console.warn(`[git-diff] Failed to render draw.io diagram preview:`,e),n.textContent=`Visual preview unavailable`,n.classList.add(`is-error`)}}}renderFileHeader(e){let t=Wc(e)===`image`?`<span class="diff-file-header-kind">${y(Gc(e.path))} image</span>`:`<span class="diff-file-header-stats"><span class="ui-stat-token ui-stat-token--add diff-stats-add">+${e.stats?.additions??0}</span><span class="ui-stat-token ui-stat-token--del diff-stats-del">-${e.stats?.deletions??0}</span></span>`;return`
572
- <div class="diff-file-header">
573
- <span class="diff-file-path">${y(e.path)}</span>
574
- <span class="ui-status-badge ${cl(e.status)}">${y(e.status)}</span>
575
- ${t}
576
- </div>
577
- `}renderUnifiedFileBody(e){return`
578
- ${e.isBinary?`<div class="diff-binary-message">${y(e.binaryMessage||`Binary file changed`)}</div>`:``}
579
- ${e.hunks.map(e=>this.renderUnifiedHunk(e)).join(``)}
580
- `}renderSplitFileBody(e){return`
581
- <div class="diff-split">
582
- <div class="diff-split-pane">
583
- <div class="diff-split-pane-header">Before</div>
584
- ${e.hunks.map(e=>{let t=[];for(let n of pl(e.lines)){if(n.context.length>0){for(let e of n.context)t.push(hl(e,e));continue}let e=Math.max(n.deletions.length,n.additions.length);for(let r=0;r<e;r+=1)t.push(hl(n.deletions[r]??null,n.additions[r]??null))}return`
585
- <div class="diff-split-hunk">${y(e.header)}</div>
586
- ${t.join(``)}
587
- `}).join(``)}
588
- </div>
589
- </div>
590
- `}renderDiffDetail(e,t,{includeHeader:n=!0}={}){if(!e)return`<div class="diff-empty-state">Select a file to load its diff.</div>`;let r=Wc(e);if(r===`image`)return`${n?this.renderFileHeader(e):``}${this.renderImageDiff(e)}`;if(r===`excalidraw`)return`${n?this.renderFileHeader(e):``}${this.renderExcalidrawDiff(e)}`;if(r===`drawio`)return`${n?this.renderFileHeader(e):``}${this.renderDrawioDiff(e)}`;if(e.tooLarge)return`
591
- ${n?this.renderFileHeader(e):``}
592
- <div class="diff-limit-card">
593
- <strong>Large diff withheld</strong>
594
- <span>This file diff is large enough to impact rendering performance.</span>
595
- <button class="${W({variant:`secondary`,extra:`diff-load-full-btn`})}" type="button" data-load-full-diff data-diff-file-path="${y(e.path)}">Load full diff</button>
596
- </div>
597
- `;let i=this.mode===`split`?this.renderSplitFileBody(e,t):this.renderUnifiedFileBody(e,t);return`${n?this.renderFileHeader(e):``}${i}`}renderFocusedFileBody(){let e=this.getCurrentFile();if(!e)return`<div class="diff-empty-state">No changes to display.</div>`;if(this.isFileLoading(e.path))return`
598
- <section class="diff-file-block">
599
- ${this.renderFileHeader(e)}
600
- <div class="diff-empty-state">Loading file diff...</div>
601
- </section>
602
- `;let t=this.fileErrors.get(e.path);return t?`
603
- <section class="diff-file-block">
604
- ${this.renderFileHeader(e)}
605
- <div class="diff-empty-state">${y(t)}</div>
606
- </section>
607
- `:`
608
- <section class="diff-file-block" data-diff-file-index="${this.currentIndex}">
609
- ${this.renderDiffDetail(this.getFileDetail(e.path)??e,this.currentIndex)}
610
- </section>
611
- `}renderCommitHeader(){return this.source!==`commit`||!this.commitMeta?``:`
612
- <section class="diff-commit-header">
613
- <div class="diff-commit-subject">${y(this.commitMeta.subject||this.commitMeta.shortHash||`Commit`)}</div>
614
- <div class="diff-commit-meta">
615
- <span>${y(this.commitMeta.shortHash||``)}</span>
616
- <span>${y(this.commitMeta.authorName||`Unknown`)}</span>
617
- <span title="${y(this.commitMeta.authoredAt||``)}">${y(this.commitMeta.relativeDateLabel||``)}</span>
618
- ${this.commitMeta.isMergeCommit?`<span>Merge commit</span>`:``}
619
- </div>
620
- <div class="diff-commit-meta diff-commit-meta-secondary">
621
- <span>${y(this.commitMeta.hash||``)}</span>
622
- <span>${Number(this.data?.summary?.filesChanged||0)} file${Number(this.data?.summary?.filesChanged||0)===1?``:`s`}</span>
623
- </div>
624
- </section>
625
- `}renderCommitIndex(){return`
626
- <aside class="diff-commit-index" aria-label="Changed files in commit">
627
- <div class="diff-commit-index-header">Changed Files</div>
628
- <div class="diff-commit-index-list">
629
- ${(this.data?.files??[]).map((e,t)=>{let n=this.activeFilePath===e.path,r=M(e.path);return`
630
- <button
631
- class="ui-record-surface diff-index-item${n?` active`:``}"
632
- type="button"
633
- data-diff-index-path="${y(e.path)}"
634
- aria-current="${n?`true`:`false`}"
635
- >
636
- <span class="ui-record-header diff-index-item-top">
637
- <span class="ui-record-title diff-index-item-name">${y(w(e.path))}</span>
638
- <span class="ui-status-badge ${cl(e.status)}">${y(e.status)}</span>
639
- </span>
640
- ${r?`<span class="ui-record-subtitle diff-index-item-path">${y(r)}</span>`:``}
641
- <span class="ui-record-meta diff-index-item-meta">
642
- <span>${t+1}</span>
643
- <span class="ui-stat-token ui-stat-token--add diff-stats-add">+${e.stats?.additions??0}</span>
644
- <span class="ui-stat-token ui-stat-token--del diff-stats-del">-${e.stats?.deletions??0}</span>
645
- </span>
646
- </button>
647
- `}).join(``)}
648
- </div>
649
- </aside>
650
- `}renderStackedSection(e,t){let n=this.isFileCollapsed(e.path),r=this.activeFilePath===e.path,i=this.isFileLoading(e.path),a=this.fileErrors.get(e.path),o=this.getFileDetail(e.path)??e,s=n?``:i?`<div class="diff-empty-state">Loading file diff...</div>`:a?`<div class="diff-empty-state">${y(a)}</div>`:this.renderDiffDetail(o,t,{includeHeader:!1});return`
651
- <section
652
- class="diff-commit-section${r?` active`:``}${n?` collapsed`:``}"
653
- id="${sl(e.path)}"
654
- data-diff-section-path="${y(e.path)}"
655
- >
656
- <button
657
- class="diff-commit-section-header"
658
- type="button"
659
- data-diff-section-toggle="${y(e.path)}"
660
- >
661
- <span class="diff-commit-section-main">
662
- ${ll(n)}
663
- <span class="diff-commit-section-copy">
664
- <span class="diff-commit-section-name">${y(w(e.path))}</span>
665
- ${M(e.path)?`<span class="diff-commit-section-path">${y(M(e.path))}</span>`:``}
666
- </span>
667
- </span>
668
- <span class="diff-commit-section-meta">
669
- <span class="ui-status-badge ${cl(e.status)}">${y(e.status)}</span>
670
- <span class="ui-stat-token ui-stat-token--add diff-stats-add">+${e.stats?.additions??0}</span>
671
- <span class="ui-stat-token ui-stat-token--del diff-stats-del">-${e.stats?.deletions??0}</span>
672
- </span>
673
- </button>
674
- <div class="diff-commit-section-body${n?` hidden`:``}">
675
- ${s}
676
- </div>
677
- </section>
678
- `}renderCommitBody(){return this.layoutMode===`focused`?`
679
- <div class="diff-commit-shell diff-commit-shell-focused">
680
- ${this.renderCommitIndex()}
681
- <div class="diff-commit-main">
682
- ${this.renderFocusedFileBody()}
683
- </div>
684
- </div>
685
- `:`
686
- <div class="diff-commit-shell diff-commit-shell-stacked">
687
- ${this.renderCommitIndex()}
688
- <div class="diff-commit-main">
689
- <div class="diff-commit-sections">
690
- ${(this.data?.files??[]).map((e,t)=>this.renderStackedSection(e,t)).join(``)}
691
- </div>
692
- </div>
693
- </div>
694
- `}getCurrentFile(){let e=this.data?.files??[];return e.length===0?null:e[this.currentIndex]??e[0]??null}getFileByPath(e){return(this.data?.files??[]).find(t=>t.path===e)??null}setActiveFilePath(e,{syncIndex:t=!0}={}){if(this.activeFilePath=e,!t)return;let n=Math.max(0,(this.data?.files??[]).findIndex(t=>t.path===e));n>=0&&(this.currentIndex=n)}getCacheKeyForPath(e){return e?this.source===`commit`?`commit:${this.commitHash}:${e}`:`workspace:${this.requestScope}:${e}`:null}getCurrentCacheKey(){return this.getCacheKeyForPath(this.getCurrentFile()?.path??null)}getCurrentFileDetail(){let e=this.getCurrentCacheKey();return e?this.fileCache.get(e):null}getFileDetail(e){let t=this.getCacheKeyForPath(e);return t?this.fileCache.get(t):null}isFileCollapsed(e){return this.collapsedFiles.has(e)}isFileLoading(e){return this.loadingFiles.has(e)}getCurrentActionState(){if(this.source===`commit`)return{canCommit:!1,canStage:!1,canUnstage:!1};let e=this.getCurrentFile(),t=this.getCurrentFileDetail()??e,n=Number(this.repoStatus?.summary?.staged||0);return t?.path?{canCommit:n>0,canStage:!!(t.hasWorkingTreeChanges||t.hasUntrackedChanges),canUnstage:!!t.hasStagedChanges}:{canCommit:n>0,canStage:!1,canUnstage:!1}}getPrimaryAction(){if(this.source===`commit`)return null;let e=this.getCurrentActionState();return e.canStage&&!e.canUnstage?`stage`:e.canUnstage&&!e.canStage||this.requestScope===`staged`&&e.canUnstage?`unstage`:e.canStage?`stage`:e.canUnstage?`unstage`:null}async handleFileAction(e){if(this.source===`commit`)return;let t=this.getCurrentFile();if(!(!t?.path||this.pendingAction)){this.pendingAction=e,this.syncToolbar();try{e===`stage`?await this.onStageFile?.(t.path,{scope:this.requestScope}):e===`unstage`?await this.onUnstageFile?.(t.path,{scope:this.requestScope}):e===`commit`&&await this.onCommitStaged?.()}finally{this.pendingAction=null,this.syncToolbar()}}}setRepoStatus(e){this.repoStatus=e,this.syncToolbar()}async handleIndexSelection(e){if(this.getFileByPath(e)){if(this.setActiveFilePath(e),this.source===`commit`&&this.layoutMode===`stacked`){this.collapsedFiles.delete(e),await this.loadFileForPath(e,{render:!1}),this.render(),this.scrollToFileSection(e);return}await this.loadFileForPath(e)}}async toggleFileSection(e){if(this.source===`commit`&&this.layoutMode===`stacked`){if(this.setActiveFilePath(e),this.collapsedFiles.has(e)){this.collapsedFiles.delete(e),await this.loadFileForPath(e,{render:!1}),this.render(),this.scrollToFileSection(e);return}this.collapsedFiles.add(e),this.render()}}scrollToFileSection(e){if(!this.content)return;let t=sl(e),n=()=>{let e=document.getElementById?.(t)??null;if(e){if(this.scrollContainer?.scrollTo&&this.scrollContainer.getBoundingClientRect&&e.getBoundingClientRect){let t=this.scrollContainer.getBoundingClientRect(),n=e.getBoundingClientRect(),r=Number(this.scrollContainer.scrollTop)||0,i=Math.max(0,r+(n.top-t.top)-8);this.scrollContainer.scrollTo({top:i,behavior:`smooth`});return}e.scrollIntoView?.({behavior:`smooth`,block:`start`})}};if(typeof requestAnimationFrame==`function`){requestAnimationFrame(n);return}setTimeout(n,0)}handleScrollSelection(){if(this.source!==`commit`||this.layoutMode!==`stacked`||!this.scrollContainer||!this.content)return;let e=Array.from(this.content.querySelectorAll?.(`[data-diff-section-path]`)??[]);if(e.length===0)return;let t=this.scrollContainer.getBoundingClientRect?.();if(!t)return;let n=t.top+120,r=null;for(let t of e){let e=t.getBoundingClientRect?.();if(!e)continue;let i=t.getAttribute?.(`data-diff-section-path`);if(i){if(e.top<=n)r=i;else if(r)break;else{r=i;break}}}r&&r!==this.activeFilePath&&(this.setActiveFilePath(r),this.render())}async loadCurrentFile({forceFullPatch:e=!1}={}){let t=this.getCurrentFile();return t?.path?this.loadFileForPath(t.path,{forceFullPatch:e}):(this.render(),null)}async loadFileForPath(e,{forceFullPatch:t=!1,render:n=!0}={}){let r=this.getFileByPath(e);if(!r?.path)return n&&this.render(),null;this.setActiveFilePath(e);let i=this.getCacheKeyForPath(e),a=i?this.fileCache.get(i):null;if(a&&(!a.tooLarge||!t))return n&&this.render(),a;let o=`${e}:${t?`full`:`partial`}`;if(this.fileLoadPromises.has(o))return this.fileLoadPromises.get(o);this.loadingFiles.add(e),this.fileErrors.delete(e),n&&this.render();let s=(async()=>{try{let n;if(this.source===`commit`){let i=await this.gitApiClient.readCommit({allowLargePatch:t,hash:this.commitHash||``,path:e});n={...r,...i.files?.[0]??{}}}else{let i=await this.gitApiClient.readDiff({allowLargePatch:t,path:e,scope:this.requestScope});n={...r,...i.files?.[0]??{}}}return Wc(n)===`drawio`&&(n=await this.enrichDrawioDetail(n)),i&&this.fileCache.set(i,n),this.fileErrors.delete(e),n}catch(t){console.error(`[git-diff] Failed to load file diff:`,t);let n=this.source===`commit`?`Failed to load commit file diff`:`Failed to load file diff`;return this.fileErrors.set(e,n),this.toastController?.show(n),null}finally{this.loadingFiles.delete(e),this.fileLoadPromises.delete(o),this.render()}})();return this.fileLoadPromises.set(o,s),s}syncToolbar(){let e=this.data?.files?.length??0,t=e===0?0:this.currentIndex+1,n=this.source===`commit`,r=n&&this.layoutMode===`stacked`;if(this.fileIndicator&&(r?this.fileIndicator.textContent=`${e} file${e===1?``:`s`}`:this.fileIndicator.textContent=e>0?`${t} / ${e} files`:`0 / 0 files`),this.stats){let e=(this.data?.files??[]).filter(e=>Wc(e)===`image`).reduce((e,t)=>({additions:e.additions+Number(t.stats?.additions||0),deletions:e.deletions+Number(t.stats?.deletions||0)}),{additions:0,deletions:0}),t=this.data?.files??[],n=t.length>0&&t.every(e=>Wc(e)===`image`),r=Number(this.data?.summary?.additions??0),i=Number(this.data?.summary?.deletions??0),a=n?0:Math.max(0,r-e.additions),o=n?0:Math.max(0,i-e.deletions);this.stats.innerHTML=`
695
- <span class="ui-stat-token ui-stat-token--add diff-stats-add">+${a}</span>
696
- <span class="ui-stat-token ui-stat-token--del diff-stats-del">-${o}</span>
697
- `}this.modeButtons.forEach(e=>{e.classList.remove(`hidden`),e.classList.toggle(`active`,e.getAttribute(`data-diff-mode`)===this.mode)}),this.layoutButtons.forEach(e=>{e.classList.toggle(`active`,e.getAttribute(`data-diff-layout`)===this.layoutMode)});let i=!!this.getCurrentFile()?.path,a=this.getCurrentActionState(),o=this.getPrimaryAction();this.backToHistoryButton?.classList.toggle(`hidden`,!n),this.gitActionsGroup?.classList.toggle(`hidden`,n),this.editorActionsGroup?.classList.toggle(`hidden`,n),this.actionsDivider?.classList.toggle(`hidden`,n),this.layoutToggle?.classList.toggle(`hidden`,!n),this.stats?.classList.remove(`hidden`),this.openEditorButton&&(this.openEditorButton.textContent=`Open in Editor`),this.openEditorButton?.toggleAttribute(`disabled`,!i||n),this.primaryActionButton&&(this.primaryActionButton.textContent=this.pendingAction===o?`Working...`:o===`unstage`?`Unstage`:`Stage`,this.primaryActionButton.toggleAttribute(`disabled`,n||!i||!o||!!this.pendingAction)),this.commitButton&&(this.commitButton.textContent=this.pendingAction===`commit`?`Working...`:`Commit Staged`),this.commitButton?.toggleAttribute(`disabled`,n||!a.canCommit||!!this.pendingAction),this.prevButton?.classList.remove(`hidden`),this.nextButton?.classList.remove(`hidden`),this.prevButton?.classList.toggle(`hidden`,r),this.nextButton?.classList.toggle(`hidden`,r),this.prevButton?.toggleAttribute(`disabled`,r||this.currentIndex<=0),this.nextButton?.toggleAttribute(`disabled`,r||e===0||this.currentIndex>=e-1)}render(){if(this.isActive){if(this.page?.classList.remove(`hidden`),(this.data?.files??[]).length===0){this.renderEmpty(this.source===`commit`?`No commit changes to display.`:`No changes to display.`);return}this.content&&(this.excalidrawPreviewPayloads.clear(),this.drawioPreviewPayloads.clear(),this.source===`commit`?this.content.innerHTML=`${this.renderCommitHeader()}${this.renderCommitBody()}`:this.content.innerHTML=this.renderFocusedFileBody(),this.syncToolbar(),this.hydrateExcalidrawPreviews(),this.hydrateDrawioPreviews())}}getToolbarTitle({commitHash:e=null,filePath:t=null,path:n=null,scope:r=`all`,source:i=`workspace`}={}){return i===`commit`||this.source===`commit`?this.layoutMode===`stacked`?this.commitMeta?.shortHash?`Commit ${this.commitMeta.shortHash}`:e?`Commit ${String(e).slice(0,7)}`:`Commit Diff`:n?w(n):this.activeFilePath?w(this.activeFilePath):this.commitMeta?.shortHash?`Commit ${this.commitMeta.shortHash}`:e?`Commit ${String(e).slice(0,7)}`:`Commit Diff`:t?w(t):r===`staged`?`Staged Changes`:r===`working-tree`?`Working Tree Changes`:`All Changes`}},_l=30,vl=1e4;function yl(){return`<svg class="git-file-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>`}function bl(){return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="18" cy="18" r="3"/><circle cx="6" cy="6" r="3"/><path d="M13 6h3a2 2 0 0 1 2 2v7"/><path d="M6 9v12"/></svg>`}function xl(e){return`<svg class="git-section-chevron${e?` collapsed`:``}" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg>`}function Sl(e){switch(e){case`commit`:return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>`;case`pull`:return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14"/><path d="m18 13-6 6-6-6"/></svg>`;case`push`:return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 19V5"/><path d="m6 11 6-6 6 6"/></svg>`;case`unstage`:return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 12H8"/><path d="m12 16-4-4 4-4"/></svg>`;case`reset`:return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 12a9 9 0 1 0 3-6.7"/><path d="M3 4v5h5"/></svg>`;default:return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14"/><path d="M5 12h14"/></svg>`}}function Cl(e){switch(e){case`added`:return`ui-status-badge--success`;case`deleted`:return`ui-status-badge--danger`;case`renamed`:return`ui-status-badge--accent`;case`untracked`:return`ui-status-badge--muted`;default:return`ui-status-badge--warning`}}function wl(e={},t={}){let n=Number(e.additions||0),r=Number(e.deletions||0);return Number(e.changedFiles||0)>0||n>0||r>0?`
698
- <span class="git-change-stats" aria-label="Local diff summary">
699
- <span class="git-change-add">+${n}</span>
700
- <span class="git-change-del">-${r}</span>
701
- </span>
702
- `:t.upstream||Number(t.ahead||0)>0||Number(t.behind||0)>0?`
703
- <span class="git-sync-info" aria-label="Remote sync status">
704
- <span class="git-sync-metric git-sync-metric--ahead">&#8593;${Number(t.ahead||0)}</span>
705
- <span class="git-sync-metric git-sync-metric--behind">&#8595;${Number(t.behind||0)}</span>
706
- </span>
707
- `:`<span class="git-sync-info git-sync-info-muted">Clean</span>`}function Tl(e={}){let t=String(e.subject||``).trim()||e.shortHash||`Commit`;return y(t)}var El=class{constructor({enabled:e=!0,gitApiClient:t=null,onCommitStaged:n=()=>{},onOpenPullBackup:r=()=>{},onPullBranch:i=()=>{},onPushBranch:a=()=>{},onRepoChange:o=()=>{},onResetFile:s=()=>{},onSelectCommit:c=()=>{},onSelectDiff:l=()=>{},onStageFile:u=()=>{},onUnstageFile:d=()=>{},onViewAllDiff:f=()=>{},searchInput:p=null,toastController:m=null}={}){this.enabled=e,this.gitApiClient=t,this.onCommitStaged=n,this.onOpenPullBackup=r,this.onPullBranch=i,this.onPushBranch=a,this.onRepoChange=o,this.onResetFile=s,this.onSelectCommit=c,this.onSelectDiff=l,this.onStageFile=u,this.onUnstageFile=d,this.onViewAllDiff=f,this.searchInput=p,this.toastController=m,this.panel=document.getElementById(`gitPanel`),this.pullBackups=[],this.status=null,this.active=!1,this.refreshTimer=null,this.searchQuery=``,this.panelMode=`changes`,this.collapsedSections=new Set,this.selection={commitHash:null,path:null,scope:null,source:`workspace`},this.pendingActionKey=null,this.history={commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0}}_handlePanelModeClick(e){let t=e.target instanceof Element?e.target.closest(`[data-git-panel-mode]`):null;if(t){let e=t.getAttribute(`data-git-panel-mode`);return(e===`changes`||e===`history`)&&this.setMode(e),!0}return!1}_handleSectionToggleClick(e){let t=e.target instanceof Element?e.target.closest(`[data-git-section-toggle]`):null;return t?(this.toggleSection(t.getAttribute(`data-git-section-toggle`)),!0):!1}_handleCommitHistoryClick(e){let t=e.target instanceof Element?e.target.closest(`[data-git-commit-hash]`):null;if(t&&!e.target.closest(`[data-git-history-load-more]`)){let e=t.getAttribute(`data-git-commit-hash`);return e&&this.onSelectCommit(e,{path:this.selection.commitHash===e?this.selection.path:null}),!0}return!1}_handleFileSelectionClick(e){let t=e.target instanceof Element?e.target.closest(`[data-git-path]`):null;if(t&&!e.target.closest(`[data-git-file-action]`)){let e=t.getAttribute(`data-git-path`);return e&&this.onSelectDiff(e,{scope:t.getAttribute(`data-git-scope`)||`working-tree`}),!0}return!1}_handleFileActionClick(e){let t=e.target instanceof Element?e.target.closest(`[data-git-file-action]`):null;if(t){let n=t.getAttribute(`data-git-file-action`),r=t.getAttribute(`data-git-path`);return n&&r&&(e.preventDefault(),e.stopPropagation(),this.handleFileAction(n,r,t.getAttribute(`data-git-scope`)||`working-tree`)),!0}return!1}_handlePanelClick(e){if(this._handlePanelModeClick(e)||this._handleSectionToggleClick(e)||this._handleCommitHistoryClick(e))return;if(e.target instanceof Element&&e.target.closest(`[data-git-history-load-more]`)){this.loadMoreHistory();return}if(this._handleFileSelectionClick(e))return;let t=e.target instanceof Element?e.target.closest(`[data-git-pull-backup-path]`):null;if(t){let e=t.getAttribute(`data-git-pull-backup-path`);e&&this.onOpenPullBackup(e);return}if(this._handleFileActionClick(e))return;if(e.target instanceof Element&&e.target.closest(`[data-git-view-all]`)){this.onViewAllDiff();return}if(e.target instanceof Element&&e.target.closest(`[data-git-commit-staged]`)){this.handleCommitStaged();return}let n=e.target instanceof Element?e.target.closest(`[data-git-sync-action]`):null;if(n){let e=n.getAttribute(`data-git-sync-action`);(e===`pull`||e===`push`)&&this.handleSyncAction(e)}}initialize(){this.panel?.addEventListener(`click`,e=>{this._handlePanelClick(e)}),this.searchInput?.addEventListener(`input`,e=>{this.searchQuery=String(e.target?.value??``).trim().toLowerCase(),this.render()}),this.syncSearchUi()}setActive(e){let t=!!e;if(!(this.active===t&&(!t||this.refreshTimer||this.panelMode===`history`))){if(this.active=t,!this.active){this.stopStatusPolling();return}this.syncSearchUi(),this.refresh({force:!1,includeHistory:this.panelMode===`history`}),this.panelMode===`changes`?this.ensureStatusPolling():this.stopStatusPolling()}}async setMode(e,{forceHistoryRefresh:t=!1}={}){let n=e===`history`?`history`:`changes`,r=this.panelMode!==n;if(this.panelMode=n,this.syncSearchUi(),this.render(),this.active){if(this.panelMode===`changes`){this.ensureStatusPolling(),r&&await this.refresh({force:!1,includeHistory:!1});return}this.stopStatusPolling(),(t||r||!this.history.loaded)&&await this.refreshHistory({force:t||r})}}setSelection({commitHash:e=null,path:t=null,scope:n=null,source:r=`workspace`}={}){this.selection={commitHash:e,path:t,scope:n,source:r},(r===`commit`||e)&&(this.panelMode=`history`,this.syncSearchUi()),this.render()}toggleSection(e){e&&(this.collapsedSections.has(e)?this.collapsedSections.delete(e):this.collapsedSections.add(e),this.render())}ensureStatusPolling(){this.refreshTimer||!this.active||this.panelMode!==`changes`||(this.refreshTimer=setInterval(()=>{this.refresh({force:!1,includeHistory:!1})},vl))}stopStatusPolling(){clearInterval(this.refreshTimer),this.refreshTimer=null}syncSearchUi(){this.searchInput&&(this.searchInput.setAttribute(`placeholder`,this.panelMode===`history`?`Filter loaded commits...`:`Search changes...`),this.searchInput.setAttribute(`aria-label`,this.panelMode===`history`?`Filter loaded commits`:`Search changed files`))}async refresh({force:e=!1,includeHistory:t=this.panelMode===`history`}={}){let n=await this.refreshStatus({force:e});return t&&n.isGitRepo&&await this.refreshHistory({force:e}),n}async refreshStatus({force:e=!1}={}){if(!this.enabled)return this.status={isGitRepo:!1,sections:[],summary:{changedFiles:0}},this.pullBackups=[],this.history={...this.history,commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0},this.onRepoChange(!1,this.status),this.render(),this.status;try{let t=await this.gitApiClient.readStatus({force:e});if(this.status=t,this.pullBackups=[],t.isGitRepo)try{let e=await this.gitApiClient.readPullBackups();this.pullBackups=Array.isArray(e.backups)?e.backups:[]}catch(e){console.error(`[git-panel] Failed to load pull backups:`,e)}else this.history={...this.history,commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0};return this.onRepoChange(!!t.isGitRepo,t),this.render(),t}catch(e){return console.error(`[git-panel] Failed to load git status:`,e),this.toastController?.show(`Failed to load git status`),this.status={isGitRepo:!1,sections:[],summary:{changedFiles:0}},this.pullBackups=[],this.history={...this.history,commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0},this.onRepoChange(!1,this.status),this.render(),this.status}}async refreshHistory({force:e=!1}={}){if(!this.status?.isGitRepo)return this.history={...this.history,commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0},this.render(),this.history;if(this.history.loading&&!e)return this.history;this.history={...this.history,error:``,loading:!0,loadingMore:!1},e&&(this.history={...this.history,commits:[],hasMore:!1,loaded:!1,offset:0}),this.render();try{let e=await this.gitApiClient.readHistory({limit:_l,offset:0});return this.history={commits:Array.isArray(e.commits)?e.commits:[],error:``,hasMore:!!e.hasMore,loaded:!0,loading:!1,loadingMore:!1,offset:Array.isArray(e.commits)?e.commits.length:0},this.render(),this.history}catch(e){return console.error(`[git-panel] Failed to load git history:`,e),this.toastController?.show(`Failed to load git history`),this.history={...this.history,error:`Failed to load git history`,loading:!1,loadingMore:!1},this.render(),this.history}}async loadMoreHistory(){if(!(!this.status?.isGitRepo||this.history.loading||this.history.loadingMore||!this.history.hasMore)){this.history={...this.history,error:``,loadingMore:!0},this.render();try{let e=await this.gitApiClient.readHistory({limit:_l,offset:this.history.offset}),t=Array.isArray(e.commits)?e.commits:[];this.history={commits:[...this.history.commits,...t],error:``,hasMore:!!e.hasMore,loaded:!0,loading:!1,loadingMore:!1,offset:this.history.offset+t.length},this.render()}catch(e){console.error(`[git-panel] Failed to load more git history:`,e),this.toastController?.show(`Failed to load git history`),this.history={...this.history,error:`Failed to load git history`,loadingMore:!1},this.render()}}}filterFiles(e=[]){return this.searchQuery?e.filter(e=>e.path.toLowerCase().includes(this.searchQuery)||String(e.oldPath||``).toLowerCase().includes(this.searchQuery)):e}filterCommits(e=[]){return this.searchQuery?e.filter(e=>String(e.subject||``).toLowerCase().includes(this.searchQuery)||String(e.shortHash||``).toLowerCase().includes(this.searchQuery)||String(e.authorName||``).toLowerCase().includes(this.searchQuery)):e}async handleFileAction(e,t,n){let r=`${e}:${n}:${t}`;if(this.pendingActionKey!==r){this.pendingActionKey=r,this.render();try{e===`stage`?await this.onStageFile(t,{scope:n}):e===`unstage`?await this.onUnstageFile(t,{scope:n}):e===`reset`&&await this.onResetFile(t,{scope:n})}finally{this.pendingActionKey=null,this.render()}}}async handleCommitStaged(){let e=`commit-staged`;if(this.pendingActionKey!==e){this.pendingActionKey=e,this.render();try{await this.onCommitStaged()}finally{this.pendingActionKey=null,this.render()}}}async handleSyncAction(e){let t=`sync:${e}`;if(this.pendingActionKey!==t){this.pendingActionKey=t,this.render();try{e===`pull`?await this.onPullBranch():e===`push`&&await this.onPushBranch()}finally{this.pendingActionKey=null,this.render()}}}renderSection(e){let t=this.filterFiles(e.files);if(t.length===0)return``;let n=this.collapsedSections.has(e.key);return`
708
- <section class="git-section">
709
- <button class="git-section-header" type="button" data-git-section-toggle="${y(e.key)}">
710
- ${xl(n)}
711
- ${y(e.label)}
712
- <span class="ui-pill-badge ui-pill-badge--count ui-pill-badge--muted git-section-count">${t.length}</span>
713
- </button>
714
- <div class="git-file-list${n?` hidden`:``}">
715
- ${t.map(e=>this.renderFile(e)).join(``)}
716
- </div>
717
- </section>
718
- `}renderPullBackupsSection(){return!Array.isArray(this.pullBackups)||this.pullBackups.length===0?``:`
719
- <section class="git-section">
720
- <button class="git-section-header" type="button" data-git-section-toggle="pull-backups">
721
- ${xl(this.collapsedSections.has(`pull-backups`))}
722
- Pull Backups
723
- <span class="ui-pill-badge ui-pill-badge--count ui-pill-badge--muted git-section-count">${this.pullBackups.length}</span>
724
- </button>
725
- <div class="git-file-list${this.collapsedSections.has(`pull-backups`)?` hidden`:``}">
726
- ${this.pullBackups.map(e=>this.renderPullBackup(e)).join(``)}
727
- </div>
728
- </section>
729
- `}renderPullBackup(e){let t=String(e?.createdAt||``).replace(`T`,` `).replace(/\.\d+Z?$/u,`Z`),n=Number(e?.fileCount||0);return`
730
- <div class="ui-item-row git-file-row">
731
- <button
732
- class="ui-item-main git-file-item"
733
- type="button"
734
- data-git-pull-backup-path="${y(e.summaryPath||``)}"
735
- >
736
- ${yl()}
737
- <span class="ui-item-copy git-file-copy">
738
- <span class="ui-item-title git-file-name">Pull backup ${y(e.id||``)}</span>
739
- <span class="ui-item-subtitle git-file-path">${y(`${t} · ${e.branch||`HEAD`} · ${n} file${n===1?``:`s`}`)}</span>
740
- </span>
741
- <span class="ui-status-badge ui-status-badge--warning">BK</span>
742
- </button>
743
- </div>
744
- `}renderFile(e){let t=this.selection.source===`workspace`&&this.selection.path===e.path&&this.selection.scope===e.scope,n=M(e.path),r=w(e.path),i=String(e.path||``),a=Cl(e.status),o=e.scope===`staged`?{label:`Unstage`,value:`unstage`}:{label:`Stage`,value:`stage`},s=`${o.value}:${e.scope}:${e.path}`,c=this.pendingActionKey===s,l=`reset:${e.scope}:${e.path}`,u=this.pendingActionKey===l;return`
745
- <div class="ui-item-row git-file-row${t?` active`:``}">
746
- <button
747
- class="ui-item-main git-file-item${t?` active`:``}"
748
- type="button"
749
- data-git-path="${y(e.path)}"
750
- data-git-scope="${y(e.scope)}"
751
- title="${y(i)}"
752
- >
753
- ${yl()}
754
- <span class="ui-item-copy git-file-copy">
755
- <span class="ui-item-title git-file-name">${y(r)}</span>
756
- ${n?`<span class="ui-item-subtitle git-file-path">${y(n)}</span>`:``}
757
- </span>
758
- <span class="ui-status-badge ${a}">${y(e.code)}</span>
759
- </button>
760
- <div class="ui-item-actions git-file-actions">
761
- <button
762
- class="ui-icon-button ui-action-icon ui-action-icon--surface"
763
- type="button"
764
- data-git-file-action="reset"
765
- data-git-path="${y(e.path)}"
766
- data-git-scope="${y(e.scope)}"
767
- aria-label="Reset ${y(r)}"
768
- title="Reset to current branch"
769
- ${u?`disabled`:``}
770
- >
771
- ${u?`...`:Sl(`reset`)}
772
- </button>
773
- <button
774
- class="ui-icon-button ui-action-icon ui-action-icon--surface"
775
- type="button"
776
- data-git-file-action="${o.value}"
777
- data-git-path="${y(e.path)}"
778
- data-git-scope="${y(e.scope)}"
779
- aria-label="${y(o.label)} ${y(r)}"
780
- title="${y(o.label)}"
781
- ${c?`disabled`:``}
782
- >
783
- ${c?`...`:Sl(o.value)}
784
- </button>
785
- </div>
786
- </div>
787
- `}renderPanelModes(){return`
788
- <div class="${vs({pill:!0,extra:`git-panel-mode-switch`})}" role="tablist" aria-label="Git panel modes">
789
- <button
790
- class="${ys({active:this.panelMode===`changes`,extra:`git-panel-mode-btn`})}"
791
- type="button"
792
- data-git-panel-mode="changes"
793
- aria-selected="${this.panelMode===`changes`}"
794
- >
795
- Changes
796
- </button>
797
- <button
798
- class="${ys({active:this.panelMode===`history`,extra:`git-panel-mode-btn`})}"
799
- type="button"
800
- data-git-panel-mode="history"
801
- aria-selected="${this.panelMode===`history`}"
802
- >
803
- History
804
- </button>
805
- </div>
806
- `}renderHistoryRow(e){let t=this.selection.source===`commit`&&this.selection.commitHash===e.hash,n=Number(e.filesChanged||0);return`
807
- <button
808
- class="ui-record-surface git-history-row${t?` active`:``}"
809
- type="button"
810
- data-git-commit-hash="${y(e.hash||``)}"
811
- title="${y(e.authoredAt||``)}"
812
- >
813
- <span class="ui-record-header git-history-row-top">
814
- <span class="ui-record-title git-history-subject">${Tl(e)}</span>
815
- <span class="ui-pill-badge ui-pill-badge--code git-history-hash">${y(e.shortHash||``)}</span>
816
- </span>
817
- <span class="ui-record-meta git-history-row-meta">
818
- <span>${y(e.authorName||`Unknown`)}</span>
819
- <span>${y(e.relativeDateLabel||``)}</span>
820
- <span>${n} file${n===1?``:`s`}</span>
821
- ${e.isMergeCommit?`<span>Merge</span>`:``}
822
- </span>
823
- <span class="ui-record-meta git-history-row-stats">
824
- <span class="git-change-add">+${Number(e.additions||0)}</span>
825
- <span class="git-change-del">-${Number(e.deletions||0)}</span>
826
- </span>
827
- </button>
828
- `}renderHistoryPanel(){let e=this.filterCommits(this.history.commits);return this.history.loading&&!this.history.loaded?`<div class="git-panel-empty">Loading git history...</div>`:this.history.error&&!this.history.loaded?`<div class="git-panel-empty">${y(this.history.error)}</div>`:this.history.loaded&&e.length===0&&this.history.commits.length===0?`<div class="git-panel-empty">No commits yet on this branch.</div>`:this.history.loaded&&e.length===0?`<div class="git-panel-empty">No loaded commits match your filter.</div>`:`
829
- <div class="git-history-list">
830
- ${e.map(e=>this.renderHistoryRow(e)).join(``)}
831
- </div>
832
- ${this.history.hasMore?`
833
- <div class="git-history-footer">
834
- <button
835
- class="${W({variant:`secondary`,size:`compact`,action:!0,surface:!0,extra:`git-history-load-more`})}"
836
- type="button"
837
- data-git-history-load-more
838
- ${this.history.loadingMore?`disabled`:``}
839
- >
840
- ${this.history.loadingMore?`Loading...`:`Load More`}
841
- </button>
842
- </div>
843
- `:``}
844
- `}renderChangesPanel(){let e=this.renderPullBackupsSection(),t=(this.status.sections??[]).map(e=>this.renderSection(e)).filter(Boolean).join(``),n=!!this.status.summary?.changedFiles,r=Number(this.status.summary?.staged||0)>0,i=this.pendingActionKey===`commit-staged`;return`
845
- ${e}
846
- ${t||`<div class="git-panel-empty">${this.searchQuery&&n?`No changes match your filter.`:`No local changes`}</div>`}
847
- ${n?`
848
- <div class="git-panel-footer">
849
- <div class="git-panel-footer-actions">
850
- <button class="${W({variant:`secondary`,size:`compact`,action:!0,surface:!0})}" type="button" data-git-view-all>
851
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M2 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
852
- View Full Diff
853
- </button>
854
- <button
855
- class="${W({variant:`primary`,action:!0,wide:!0,extra:`git-footer-commit-btn`})}"
856
- type="button"
857
- data-git-commit-staged
858
- ${!r||i?`disabled`:``}
859
- >
860
- ${i?`Working...`:`Commit Staged`}
861
- </button>
862
- </div>
863
- </div>
864
- `:``}
865
- `}renderEmpty(e){this.panel&&(this.panel.innerHTML=`
866
- <div class="git-panel-empty ui-empty-state ui-empty-state--compact">
867
- <p class="ui-empty-state-copy">${y(e)}</p>
868
- </div>
869
- `)}render(){if(!this.panel)return;if(!this.status){this.renderEmpty(`Loading git status...`);return}if(!this.status.isGitRepo){this.renderEmpty(`Git is unavailable for this vault.`);return}let e=this.status.branch??{},t=!!e.upstream,n=this.pendingActionKey===`sync:pull`,r=this.pendingActionKey===`sync:push`;this.panel.innerHTML=`
870
- <div class="git-branch-bar">
871
- <div class="git-branch-meta">
872
- <span class="git-branch-name">
873
- ${bl()}
874
- ${y(e.name||`HEAD`)}
875
- </span>
876
- ${wl(this.status.summary,e)}
877
- </div>
878
- <div class="git-branch-actions" role="group" aria-label="Remote sync actions">
879
- <button
880
- class="${W({variant:`secondary`,size:`compact`,pill:!0,surface:!0,extra:`ui-action-pill`})}"
881
- type="button"
882
- data-git-sync-action="pull"
883
- title="${t?`Pull remote changes`:`No upstream branch configured`}"
884
- aria-label="Pull branch"
885
- ${!t||n?`disabled`:``}
886
- >
887
- ${n?`...`:`${Sl(`pull`)}<span>Pull</span>`}
888
- </button>
889
- <button
890
- class="${W({variant:`secondary`,size:`compact`,pill:!0,surface:!0,extra:`ui-action-pill`})}"
891
- type="button"
892
- data-git-sync-action="push"
893
- title="${t?`Push local commits`:`No upstream branch configured`}"
894
- aria-label="Push branch"
895
- ${!t||r?`disabled`:``}
896
- >
897
- ${r?`...`:`${Sl(`push`)}<span>Push</span>`}
898
- </button>
899
- </div>
900
- ${this.renderPanelModes()}
901
- </div>
902
- ${this.panelMode===`history`?this.renderHistoryPanel():this.renderChangesPanel()}
903
- `}},Dl=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onMeasureEditor:t,onViewRequest:n=null}){this.mobileBreakpointQuery=e,this.onMeasureEditor=t,this.onViewRequest=n,this.preferredView=`split`,this.mobileShowsEditor=!this.isMobileViewport(),this.currentView=this.mobileShowsEditor?this.preferredView:`preview`,this.editorLayout=document.getElementById(`editorLayout`),this.editorPane=document.getElementById(`editorPane`),this.previewPane=document.getElementById(`previewPane`),this.mobileToggleButton=document.getElementById(`mobileViewToggle`),this.resizer=document.getElementById(`resizer`),this.viewButtons=Array.from(document.querySelectorAll(`.view-btn`))}isMobileViewport(){return this.mobileBreakpointQuery.matches}initialize(){this.viewButtons.forEach(e=>{e.addEventListener(`click`,()=>{this.onViewRequest?.(e.dataset.view)!==!1&&this.setView(e.dataset.view)})}),this.mobileToggleButton?.addEventListener(`click`,()=>this.toggleMobileView()),this.initializeResizer(),this.restorePreferredView()}primeView(e){if(e){if(this.isMobileViewport()){this.mobileShowsEditor=e!==`preview`;return}this.preferredView=e}}reset(){this.restorePreferredView(),this.editorPane&&(this.editorPane.style.flex=``),this.previewPane&&(this.previewPane.style.flex=``),this.updateResizerValue()}restorePreferredView(){let e=this.isMobileViewport()?this.mobileShowsEditor?`split`:`preview`:this.preferredView;this.applyView(e),this.updateMobileToggleButton(this.mobileShowsEditor?`Preview`:`Editor`)}applyView(e){this.currentView=e,this.editorLayout?.setAttribute(`data-view`,e),this.syncViewButtons()}setView(e,{persist:t=!0}={}){e&&(t&&(this.preferredView=e),this.applyView(e),(e===`split`||e===`editor`)&&this.scheduleEditorMeasure())}toggleMobileView(){let e=!this.mobileShowsEditor,t=e?`split`:`preview`;this.onViewRequest?.(t)!==!1&&(this.mobileShowsEditor=e,this.applyView(t),this.updateMobileToggleButton(this.mobileShowsEditor?`Preview`:`Editor`),this.mobileShowsEditor&&this.scheduleEditorMeasure())}scheduleEditorMeasure(){this.onMeasureEditor&&setTimeout(()=>this.onMeasureEditor(),50)}updateMobileToggleButton(e){this.mobileToggleButton&&(this.mobileToggleButton.innerHTML=`${e===`Editor`?`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="8" y1="8" x2="16" y2="8"/><line x1="8" y1="12" x2="14" y2="12"/><line x1="8" y1="16" x2="12" y2="16"/></svg>`:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>`}<span class="ui-toolbar-button-label">${e}</span>`)}syncViewButtons(){this.viewButtons.forEach(e=>{let t=e.dataset.view===this.currentView;e.classList.toggle(`active`,t),e.setAttribute(`aria-pressed`,String(t))})}updateResizerValue(){if(!this.resizer||!this.editorLayout||!this.editorPane)return;let e=this.editorLayout.offsetWidth;if(!Number.isFinite(e)||e<=0)return;let t=Math.round(this.editorPane.offsetWidth/e*100);this.resizer.setAttribute(`aria-valuenow`,String(Math.max(20,Math.min(80,t))))}applyEditorPaneWidth(e){if(!this.editorLayout||!this.editorPane||!this.previewPane)return;let t=this.editorLayout.offsetWidth;if(!Number.isFinite(t)||t<=0)return;let n=Math.max(200,Math.min(t-200,e))/t*100;this.editorPane.style.flex=`0 0 ${n}%`,this.previewPane.style.flex=`1`,this.updateResizerValue()}initializeResizer(){if(!this.resizer||!this.editorLayout||!this.editorPane||!this.previewPane)return;let e=!1,t=0,n=0;this.resizer.addEventListener(`mousedown`,r=>{e=!0,t=r.clientX,n=this.editorPane.offsetWidth,this.resizer.classList.add(`dragging`),document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`,r.preventDefault()}),document.addEventListener(`mousemove`,r=>{if(!e)return;let i=r.clientX-t;this.applyEditorPaneWidth(n+i)}),document.addEventListener(`mouseup`,()=>{e&&(e=!1,this.resizer.classList.remove(`dragging`),document.body.style.cursor=``,document.body.style.userSelect=``,this.scheduleEditorMeasure())}),this.resizer.addEventListener(`keydown`,e=>{let t=this.editorLayout.offsetWidth;if(!Number.isFinite(t)||t<=0)return;let n=Math.max(24,Math.round(t*.05));if(e.key===`ArrowLeft`){e.preventDefault(),this.applyEditorPaneWidth(this.editorPane.offsetWidth-n),this.scheduleEditorMeasure();return}if(e.key===`ArrowRight`){e.preventDefault(),this.applyEditorPaneWidth(this.editorPane.offsetWidth+n),this.scheduleEditorMeasure();return}if(e.key===`Home`){e.preventDefault(),this.applyEditorPaneWidth(t*.2),this.scheduleEditorMeasure();return}e.key===`End`&&(e.preventDefault(),this.applyEditorPaneWidth(t*.8),this.scheduleEditorMeasure())}),this.updateResizerValue()}},Ol=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onNavigateToHeading:t,onWillOpen:n}={}){this.outlineOpen=!1,this.activeHeadingFrame=null,this.activeHeadingId=null,this.headings=[],this.pinnedHeadingId=null,this.pdfOutline=null,this.onNavigateToPdfOutline=null,this.onNavigateToHeading=t,this.onWillOpen=n,this.panel=document.getElementById(`outlinePanel`),this.closeButton=document.getElementById(`outlineClose`),this.navigation=document.getElementById(`outlineNav`),this.previewContainer=document.getElementById(`previewContainer`),this.toggleButton=document.getElementById(`outlineToggle`),this.mobileBreakpointQuery=e,this.handlePreviewScroll=()=>this.scheduleActiveHeadingUpdate(),this.handleDocumentPointerDown=e=>{if(!this.outlineOpen)return;let t=e.target;t instanceof Node&&(this.panel?.contains(t)||this.toggleButton?.contains(t))||this.close()}}initialize(){this.toggleButton?.addEventListener(`click`,()=>this.toggle()),this.closeButton?.addEventListener(`click`,()=>this.close()),document.addEventListener(`pointerdown`,this.handleDocumentPointerDown)}toggle(){this.setOpenState(!this.outlineOpen)}close(){this.setOpenState(!1)}setOpenState(e){if(e&&!this.outlineOpen&&this.onWillOpen?.(),this.outlineOpen=e,this.panel?.classList.toggle(`hidden`,!this.outlineOpen),this.toggleButton?.classList.toggle(`active`,this.outlineOpen),this.panel?.setAttribute(`aria-hidden`,String(!this.outlineOpen)),this.toggleButton?.setAttribute(`aria-expanded`,String(this.outlineOpen)),this.outlineOpen){this.refresh();return}this.cleanup()}refresh(){if(!this.navigation)return;if(!this.outlineOpen){this.cleanup();return}if(this.pdfOutline){this.renderPdfOutline();return}let e=document.getElementById(`previewContent`)?.querySelectorAll(`h1, h2, h3, h4, h5, h6`)??[];if(e.length===0){this.navigation.innerHTML=`<div class="outline-empty">No headings found</div>`,this.cleanup();return}let t=Array.from(e).map((e,t)=>(e.id||=`heading-${t}-${e.textContent.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,40)}`,{id:e.id,level:Number.parseInt(e.tagName[1],10),sourceLine:Number.parseInt(e.getAttribute(`data-source-line`)||``,10),text:e.textContent.trim()}));this.navigation.innerHTML=t.map(e=>`<button class="outline-item" data-level="${e.level}" data-target="${e.id}"${Number.isFinite(e.sourceLine)?` data-source-line="${e.sourceLine}"`:``} title="${e.text.replace(/"/g,`&quot;`)}">${e.text}</button>`).join(``),this.navigation.querySelectorAll(`.outline-item`).forEach(e=>{e.addEventListener(`click`,()=>{let t=document.getElementById(e.dataset.target);this.navigateToHeading(t,e.dataset.target,{behavior:`auto`}),this.mobileBreakpointQuery.matches&&this.close()})}),this.observeHeadings(Array.from(e))}setPdfOutline(e,t){if(this.cleanup(),this.pdfOutline=Array.isArray(e)&&e.length>0?e:null,this.onNavigateToPdfOutline=this.pdfOutline?t:null,this.activeHeadingId=null,this.toggleButton?.classList.toggle(`hidden`,!this.pdfOutline),!this.pdfOutline){this.navigation?.replaceChildren(),this.close();return}this.outlineOpen&&this.renderPdfOutline()}clearPdfOutline(){this.pdfOutline=null,this.onNavigateToPdfOutline=null,this.activeHeadingId=null,this.pinnedHeadingId=null,this.navigation?.replaceChildren(),this.toggleButton?.classList.add(`hidden`),this.close()}renderPdfOutline(){if(!this.navigation||!this.pdfOutline)return;this.cleanup(),this.navigation.replaceChildren();let e=document.createDocumentFragment(),t=0,n=(r,i=1)=>{r.forEach(r=>{if(!r||typeof r!=`object`)return;let a=String(r.title??``).trim();if(a){let n=`pdf-outline-${t}`,o=document.createElement(`button`);o.type=`button`,o.className=`outline-item`,o.dataset.level=String(Math.min(i,6)),o.dataset.target=n,o.title=a,o.textContent=a,o.addEventListener(`click`,()=>{this.setActiveItem(n,{behavior:`auto`}),this.onNavigateToPdfOutline?.(r),this.mobileBreakpointQuery.matches&&this.close()}),e.appendChild(o),t+=1}Array.isArray(r.items)&&n(r.items,Math.min(i+1,6))})};if(n(this.pdfOutline),e.childNodes.length===0){this.navigation.innerHTML=`<div class="outline-empty">No outline found</div>`;return}this.navigation.appendChild(e)}cleanup({preservePinnedHeading:e=!1}={}){this.activeHeadingFrame&&=(cancelAnimationFrame(this.activeHeadingFrame),null),this.previewContainer?.removeEventListener(`scroll`,this.handlePreviewScroll),this.headings=[],e||(this.pinnedHeadingId=null)}setActiveItem(e,{scrollIntoView:t=!0,behavior:n=`smooth`}={}){this.activeHeadingId=e,this.navigation?.querySelectorAll(`.outline-item`).forEach(t=>{t.classList.toggle(`active`,t.dataset.target===e)}),t&&this.navigation?.querySelector(`.outline-item.active`)?.scrollIntoView({behavior:n,block:`nearest`})}observeHeadings(e){if(this.cleanup({preservePinnedHeading:!0}),!this.previewContainer||e.length===0)return;this.headings=e,this.previewContainer.addEventListener(`scroll`,this.handlePreviewScroll,{passive:!0});let t=this.getPinnedHeading();if(t){this.setActiveItem(t.id,{behavior:`auto`,scrollIntoView:!0});return}this.updateActiveHeading()}scheduleActiveHeadingUpdate(){this.activeHeadingFrame||=requestAnimationFrame(()=>{this.activeHeadingFrame=null,this.updateActiveHeading()})}updateActiveHeading(){if(!this.previewContainer||this.headings.length===0)return;let e=this.getPinnedHeading();if(e&&this.shouldKeepPinnedHeadingActive(e)){this.setActiveItem(e.id,{behavior:`auto`,scrollIntoView:!0});return}this.pinnedHeadingId=null;let t=this.previewContainer.scrollTop,n=this.headings[0];for(let e of this.headings){if(this.getHeadingScrollTop(e)>t)break;n=e}this.setActiveItem(n.id,{behavior:`auto`,scrollIntoView:!0})}getHeadingScrollTop(e){if(!this.previewContainer)return 0;let t=this.previewContainer.getBoundingClientRect(),n=e.getBoundingClientRect();return this.previewContainer.scrollTop+(n.top-t.top)}getPinnedHeading(){return this.pinnedHeadingId?this.headings.find(e=>e.id===this.pinnedHeadingId)??null:null}shouldKeepPinnedHeadingActive(e){if(!this.previewContainer||!e?.isConnected)return!1;let t=this.getHeadingScrollTop(e)-this.previewContainer.scrollTop,n=t+e.getBoundingClientRect().height,r=this.previewContainer.clientHeight*.45;return n>-48&&t<r}notifyHeadingNavigation(e,t){if(!e)return;let n=Number.parseInt(e.getAttribute(`data-source-line`)||``,10);this.onNavigateToHeading?.({headingId:t,sourceLine:Number.isFinite(n)?n:null})}navigateToHeading(e,t,{behavior:n=`auto`}={}){return!e||!t?!1:(this.pinnedHeadingId=t,this.notifyHeadingNavigation(e,t),this.scrollHeadingIntoView(e,{behavior:n}),this.setActiveItem(t,{behavior:n}),!0)}scrollHeadingIntoView(e,{behavior:t=`smooth`}={}){if(!e||!this.previewContainer)return;let n=this.previewContainer.getBoundingClientRect(),r=e.getBoundingClientRect(),i=this.previewContainer.scrollTop+(r.top-n.top);this.previewContainer.scrollTo({behavior:t,top:Math.max(i,0)})}},kl=.35,Al=120,jl=12,Ml=2;function Nl(e){return Math.max(e.scrollHeight-e.clientHeight,0)}function Pl(e){return Math.max(e,0)}function Fl(e){return Math.max(e.clientHeight*kl,jl)}function Il(e){return(e?.scrollTop??0)<=Ml}function Ll(e,t){let n=e.getBoundingClientRect();return t.getBoundingClientRect().top-n.top+e.scrollTop}function Rl(e){return!e.querySelector(`[data-source-line]`)}var zl=class{constructor({getEditorLineNumber:e,onEditorScrollActivityChange:t,previewContainer:n,previewElement:r,scrollEditorToLine:i}){this.getEditorLineNumber=e,this.onEditorScrollActivityChange=t,this.previewContainer=n,this.previewElement=r,this.scrollEditorToLine=i,this.editorScroller=null,this.editorScrollActive=!1,this.editorScrollIdleTimer=null,this.lockedElements=new Set,this.pendingSync=null,this.frameId=null,this.previewBlocks=null,this.previewBlocksWarmId=null,this.previewBlocksReadyCallbacks=[],this.largeDocumentMode=!1,this.lastInteractionSource=`editor`,this.suspendedUntil=0,this.handleEditorScroll=()=>{if(!(!this.editorScroller||this.lockedElements.has(this.editorScroller)||this.isSuspended())){if(this.lastInteractionSource=`editor`,this.largeDocumentMode){this.setEditorScrollActive(!0),this.scheduleEditorScrollIdle(),this.scheduleSync(this.editorScroller,this.previewContainer,{preferApproximateMapping:!0});return}this.scheduleSync(this.editorScroller,this.previewContainer)}},this.handlePreviewScroll=()=>{!this.previewContainer||this.lockedElements.has(this.previewContainer)||this.isSuspended()||(this.lastInteractionSource=`preview`,this.scheduleSync(this.previewContainer,this.editorScroller))}}initialize(){this.previewContainer?.addEventListener(`scroll`,this.handlePreviewScroll,{passive:!0})}attachEditorScroller(e){this.editorScroller!==e&&(this.editorScroller?.removeEventListener(`scroll`,this.handleEditorScroll),this.editorScroller=e,this.editorScroller?.addEventListener(`scroll`,this.handleEditorScroll,{passive:!0}))}syncPreviewToEditor(){this.lastInteractionSource=`editor`,this.sync(this.editorScroller,this.previewContainer)}syncEditorToPreview(){this.lastInteractionSource=`preview`,this.sync(this.previewContainer,this.editorScroller)}destroy(){this.previewContainer?.removeEventListener(`scroll`,this.handlePreviewScroll),this.editorScroller?.removeEventListener(`scroll`,this.handleEditorScroll),this.editorScroller=null,clearTimeout(this.editorScrollIdleTimer),this.editorScrollIdleTimer=null,this.pendingSync=null,this.previewBlocks=null,z(this.previewBlocksWarmId),this.previewBlocksWarmId=null,this.previewBlocksReadyCallbacks=[],this.lockedElements.clear(),this.editorScrollActive=!1,this.lastInteractionSource=`editor`,this.suspendedUntil=0,this.frameId&&=(cancelAnimationFrame(this.frameId),null)}scheduleSync(e,t,{preferApproximateMapping:n=!1}={}){!e||!t||this.lockedElements.has(e)||this.isSuspended()||(this.pendingSync={preferApproximateMapping:n,source:e,target:t},!this.frameId&&(this.frameId=requestAnimationFrame(()=>{if(this.frameId=null,!this.pendingSync)return;let{preferApproximateMapping:e,source:t,target:n}=this.pendingSync;this.pendingSync=null,this.sync(t,n,{preferApproximateMapping:e})})))}invalidatePreviewBlocks(){this.previewBlocks=null,z(this.previewBlocksWarmId),this.previewBlocksWarmId=null,this.previewBlocksReadyCallbacks=[]}setLargeDocumentMode(e){this.largeDocumentMode=!!e,this.largeDocumentMode||(clearTimeout(this.editorScrollIdleTimer),this.editorScrollIdleTimer=null,this.setEditorScrollActive(!1))}warmPreviewBlocks({onReady:e}={}){if(typeof e==`function`&&(this.previewBlocks?e(this.previewBlocks):this.previewBlocksReadyCallbacks.push(e)),!this.largeDocumentMode){this.previewBlocks||=this.buildPreviewBlocks(),this.flushPreviewBlocksReadyCallbacks();return}this.previewBlocks||this.previewBlocksWarmId!==null||(this.previewBlocksWarmId=R(()=>{this.previewBlocksWarmId=null,this.previewBlocks=this.buildPreviewBlocks(),this.flushPreviewBlocksReadyCallbacks()},500))}realignAfterLayoutChange(){let e=()=>{if(this.lastInteractionSource===`preview`){this.syncEditorToPreview();return}this.syncPreviewToEditor()};if(this.largeDocumentMode&&!this.previewBlocks){this.warmPreviewBlocks({onReady:()=>e()});return}e()}suspendSync(e=250){this.suspendedUntil=performance.now()+e}isSuspended(){return performance.now()<this.suspendedUntil}flushPreviewBlocksReadyCallbacks(){this.previewBlocksReadyCallbacks.length!==0&&this.previewBlocksReadyCallbacks.splice(0).forEach(e=>{try{e(this.previewBlocks??[])}catch(e){console.warn(`[scroll-sync] Preview block callback failed:`,e)}})}setEditorScrollActive(e){this.editorScrollActive!==e&&(this.editorScrollActive=e,this.onEditorScrollActivityChange?.(e))}scheduleEditorScrollIdle(){clearTimeout(this.editorScrollIdleTimer),this.editorScrollIdleTimer=setTimeout(()=>{this.editorScrollIdleTimer=null,this.setEditorScrollActive(!1),this.syncPreviewToEditor()},Al)}sync(e,t,{preferApproximateMapping:n=!1}={}){if(!e||!t||this.lockedElements.has(e)||this.isSuspended())return;if(!n&&e===this.editorScroller&&t===this.previewContainer){let e=this.getPreviewScrollTopForEditorLine();if(e!==null){this.setScrollTop(t,e);return}}if(e===this.previewContainer&&t===this.editorScroller){let e=this.getEditorLineNumberForPreviewScroll();if(e!==null){this.lockedElements.add(t),this.scrollEditorToLine?.(e,kl),requestAnimationFrame(()=>{this.lockedElements.delete(t)});return}}let r=Nl(e),i=Nl(t),a=r>0?e.scrollTop/r:0,o=i>0?i*a:0;this.setScrollTop(t,o)}setScrollTop(e,t){this.lockedElements.add(e),e.scrollTop=Pl(t),requestAnimationFrame(()=>{this.lockedElements.delete(e)})}getPreviewScrollTopForEditorLine(){if(Il(this.editorScroller))return 0;let e=this.getEditorLineNumber?.();if(!Number.isFinite(e))return null;let t=this.getPreviewBlocks();if(t.length===0||!this.previewContainer)return null;let{block:n,index:r}=this.findBlockForLine(t,e),i=this.getPreviewSpan(t,r),a=Math.max(n.end-n.start,1),o=b((e-n.start)/a,0,1),s=Nl(this.previewContainer),c=Fl(this.previewContainer);return b(n.top+i*o-c,0,s)}getEditorLineNumberForPreviewScroll(){if(!this.previewContainer)return null;let e=this.getPreviewBlocks();if(e.length===0)return null;let t=this.previewContainer.scrollTop+Fl(this.previewContainer),{block:n,index:r}=this.findBlockForScrollTop(e,t),i=this.getPreviewSpan(e,r),a=Math.max(n.end-n.start,1),o=i>0?b((t-n.top)/i,0,1):0;return Math.round(n.start+a*o)}getPreviewBlocks(){return this.previewBlocks?this.previewBlocks:!this.previewContainer||!this.previewElement||this.largeDocumentMode?[]:(this.previewBlocks=this.buildPreviewBlocks(),this.previewBlocks)}buildPreviewBlocks(){let e=Array.from(this.previewElement.querySelectorAll(`[data-source-line]`)).map(e=>{let t=Number.parseInt(e.getAttribute(`data-source-line`)||``,10),n=Number.parseInt(e.getAttribute(`data-source-line-end`)||``,10);return Number.isFinite(t)?{element:e,end:Number.isFinite(n)?Math.max(n,t+1):t+1,start:t,top:Ll(this.previewContainer,e)}:null}).filter(Boolean).sort((e,t)=>e.top-t.top||e.start-t.start||e.end-t.end),t=e.filter(e=>Rl(e.element)),n=t.length>0?t:e;return n.filter((e,t)=>{let r=n[t-1];return!r||Math.abs(r.top-e.top)>1||r.start!==e.start||r.end!==e.end})}findBlockForLine(e,t){let n=null,r=-1;for(let i=0;i<e.length;i+=1){let a=e[i];if(t>=a.start&&t<a.end){if(!n){n=a,r=i;continue}let e=n.end-n.start,t=a.end-a.start;(t<e||t===e&&a.start>=n.start)&&(n=a,r=i)}}if(n)return{block:n,index:r};let i=0;for(let n=0;n<e.length&&!(e[n].start>t);n+=1)i=n;return{block:e[i],index:i}}findBlockForScrollTop(e,t){for(let n=0;n<e.length;n+=1)if(t<this.getPreviewSpan(e,n)+e[n].top)return{block:e[n],index:n};let n=e.length-1;return{block:e[n],index:n}}getPreviewSpan(e,t){if(!this.previewContainer)return 1;let n=e[t],r=e[t+1],i=n.element.getBoundingClientRect().height;if(!r){let e=Nl(this.previewContainer);return Math.max(e-n.top+this.previewContainer.clientHeight,i,1)}return Math.max(r.top-n.top,i,1)}},Bl=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>`,Vl=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>`,Hl=class{constructor({storageKey:e=`collabmd-theme`,onChange:t}){this.storageKey=e,this.onChange=t,this.currentTheme=`dark`}initialize(){this.currentTheme=this.readPreferredTheme(),this.applyTheme(),document.querySelectorAll(`[data-theme-toggle]`).forEach(e=>{e.addEventListener(`click`,()=>this.toggle())})}getTheme(){return this.currentTheme}toggle(){this.currentTheme=this.currentTheme===`dark`?`light`:`dark`,this.persistTheme(),this.applyTheme()}readPreferredTheme(){try{let e=window.localStorage.getItem(this.storageKey);if(e===`light`||e===`dark`)return e}catch{}return window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`}persistTheme(){try{window.localStorage.setItem(this.storageKey,this.currentTheme)}catch{}}applyTheme(){document.documentElement.setAttribute(`data-theme`,this.currentTheme),this.updateToggleIcons(),this.onChange?.(this.currentTheme)}updateToggleIcons(){let e=this.currentTheme===`dark`?`Dark`:`Light`,t=this.currentTheme===`dark`?`light`:`dark`,n=this.currentTheme===`dark`?Vl:Bl;document.querySelectorAll(`[data-theme-toggle]`).forEach(r=>{let i=r.querySelector(`[data-theme-toggle-icon]`),a=r.querySelector(`[data-theme-toggle-state]`);i?i.innerHTML=n:r.innerHTML=n,a&&(a.textContent=e,a.dataset.theme=this.currentTheme),r.setAttribute(`aria-label`,`Theme: ${e}. Switch to ${t} mode`),r.setAttribute(`title`,`Theme: ${e}. Switch to ${t} mode`)})}},Ul=class{constructor(e){this.container=e}show(e,t=3e3){if(!this.container)return null;let n=typeof t==`number`?{duration:t}:{...t??{}},r=Number(n.duration)>0?Number(n.duration):0,i=document.createElement(`div`);i.className=`toast`,typeof n.tone==`string`&&n.tone&&(i.dataset.tone=n.tone);let a=document.createElement(`span`);a.className=`toast__message`,a.textContent=e,i.appendChild(a);let o=()=>{!i.isConnected||i.classList.contains(`leaving`)||(i.classList.add(`leaving`),i.addEventListener(`animationend`,()=>i.remove(),{once:!0}))};if(n.actionLabel&&typeof n.onAction==`function`){let e=document.createElement(`button`);e.className=`toast__action`,e.type=`button`,e.textContent=n.actionLabel,e.addEventListener(`click`,()=>{n.onAction(),n.closeOnAction!==!1&&o()}),i.appendChild(e)}if(n.dismissible){let e=document.createElement(`button`);e.className=`toast__dismiss`,e.type=`button`,e.setAttribute(`aria-label`,`Dismiss notification`),e.textContent=`Close`,e.addEventListener(`click`,o),i.appendChild(e)}return this.container.appendChild(i),r>0&&setTimeout(o,r),i}},Wl=16/9,Gl=240,Kl=720,ql=180;function Jl(e){return Math.max(ql,Math.min(Kl,Math.ceil(e||Gl)))}var Yl=class{constructor({previewElement:e}){this.previewElement=e,this.embedEntries=new Map,this.overlayRoot=null}destroy(){this.embedEntries.forEach(e=>{e.hydrateFrameId&&=(cancelAnimationFrame(e.hydrateFrameId),null),e.wrapper?.remove(),e.placeholder=null}),this.embedEntries.clear(),this.overlayRoot?.remove(),this.overlayRoot=null}detachForCommit(){this.embedEntries.forEach(e=>{e.placeholder=null})}reconcileEmbeds(e=this.previewElement){if(this.previewElement=e,!e)return;let t=Array.from(e.querySelectorAll(`.video-embed-placeholder[data-video-embed-key]`)).map(e=>({filePath:e.dataset.videoEmbedSource,key:e.dataset.videoEmbedKey,label:e.dataset.videoEmbedLabel||`Embedded video`,placeholder:e,source:e.dataset.videoEmbedSource||``,kind:e.dataset.videoEmbedKind||``,url:e.dataset.videoEmbedUrl||``,mimeType:e.dataset.videoEmbedMimeType||``})),{nextEntries:n,removedEntries:r}=Nc(this.embedEntries,t);r.forEach(e=>this._destroyEntry(e)),this.embedEntries=n,this.embedEntries.forEach(e=>{e.aspectRatio=e.aspectRatio||Wl,e.kind=e.placeholder?.dataset.videoEmbedKind||e.kind,e.label=e.placeholder?.dataset.videoEmbedLabel||e.label,e.mimeType=e.placeholder?.dataset.videoEmbedMimeType||e.mimeType,e.source=e.placeholder?.dataset.videoEmbedSource||e.source,e.url=e.placeholder?.dataset.videoEmbedUrl||e.url,e.wrapper||this._createEmbed(e),this._attachWrapper(e)}),this.syncLayout(),this.embedEntries.size===0&&(this.overlayRoot?.remove(),this.overlayRoot=null)}syncLayout(){this.embedEntries.forEach(e=>{e.wrapper&&this._syncEntryLayout(e)})}_destroyEntry(e){e.hydrateFrameId&&=(cancelAnimationFrame(e.hydrateFrameId),null),e.wrapper?.remove(),e.placeholder=null}_createEmbed(e){let t=document.createElement(`div`);if(t.className=`video-embed video-embed-shell diagram-preview-shell is-${e.kind}`,e.kind===`youtube`){let n=document.createElement(`div`);n.className=`video-embed-frame video-embed-frame-youtube`;let r=document.createElement(`iframe`);r.className=`video-embed-iframe`,r.title=e.label||`Embedded YouTube video`,r.referrerPolicy=`strict-origin-when-cross-origin`,r.allow=`accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share`,r.allowFullscreen=!0,n.appendChild(r),t.appendChild(n),e.mediaElement=r}else{let n=document.createElement(`video`);n.className=`video-embed-player`,n.controls=!0,n.preload=`metadata`,n.playsInline=!0,e.label&&(n.title=e.label,n.setAttribute(`aria-label`,e.label));let r=document.createElement(`source`);r.src=e.url,e.mimeType&&(r.type=e.mimeType),n.appendChild(r),n.addEventListener(`loadedmetadata`,()=>{Number.isFinite(n.videoWidth)&&Number.isFinite(n.videoHeight)&&n.videoWidth>0&&n.videoHeight>0&&(e.aspectRatio=n.videoWidth/n.videoHeight,this._syncEntryLayout(e))}),t.appendChild(n),e.mediaElement=n}e.wrapper=t}_attachWrapper(e){let t=e.placeholder?.isConnected?e.placeholder:this.previewElement?.querySelector(`.video-embed-placeholder[data-video-embed-key="${e.key}"]`);if(!t)return;e.placeholder=t,t.classList.add(`is-hydrated`),t.dataset.videoEmbedHydrated=`true`,t.style.pointerEvents=`none`;let n=this._ensureOverlayRoot();e.wrapper?.parentElement!==n&&n.appendChild(e.wrapper)}_syncEntryLayout(e){let t=e.placeholder?.isConnected?e.placeholder:this.previewElement?.querySelector(`.video-embed-placeholder[data-video-embed-key="${e.key}"]`);if(!t||!e.wrapper)return;e.placeholder=t;let n=t.offsetWidth||t.clientWidth||0;if(n<=0&&e.inlineHeightPx)return;let r=Jl(n>0?n/(e.aspectRatio||Wl):e.inlineHeightPx);e.inlineHeightPx=r,Q(t,`height`,`${r}px`),Q(e.wrapper,`position`,`absolute`),Q(e.wrapper,`top`,`${t.offsetTop}px`),Q(e.wrapper,`left`,`${t.offsetLeft}px`),Q(e.wrapper,`width`,`${t.offsetWidth}px`),Q(e.wrapper,`height`,`${r}px`),Q(e.wrapper,`margin`,`0`),Q(e.wrapper,`pointerEvents`,`auto`),this._hydrateEntryMedia(e)}_ensureOverlayRoot(){let e=this.previewElement?.querySelector(`[data-video-overlay-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.videoOverlayRoot=`true`,e.className=`video-embed-overlay-root`,this.previewElement?.appendChild(e)),this.overlayRoot=e,e}_hydrateEntryMedia(e){if(e.kind!==`youtube`)return;let t=e.mediaElement;t instanceof HTMLIFrameElement&&(!e.url||t.getAttribute(`src`)===e.url||e.wrapper?.offsetWidth<=0||e.wrapper?.offsetHeight<=0||(e.hydrateFrameId||=requestAnimationFrame(()=>{if(e.hydrateFrameId=null,!e.url||t.getAttribute(`src`)===e.url)return;let n=Math.round(e.wrapper?.offsetWidth||0),r=Math.round(e.wrapper?.offsetHeight||0);n<=0||r<=0||(t.width=String(n),t.height=String(r),t.src=e.url)})))}};function Q(e,t,n){!e||e.style[t]===n||(e.style[t]=n)}var $=1,Xl=6,Zl=.25,Ql=2,$l=6;function eu(e){let t=Number(e);return Number.isFinite(t)?Math.min(Xl,Math.max($,Math.round(t*100)/100)):$}function tu(e,{contentSize:t=0,scale:n=1,viewportSize:r=0}={}){let i=Number(e),a=Number(t),o=Number(n),s=Number(r);if(!Number.isFinite(i)||!Number.isFinite(a)||!Number.isFinite(o)||!Number.isFinite(s))return 0;let c=(a*o-s)/2;return c<=0?0:Math.min(Math.max(i,-c),c)}function nu(e){return!!e?.ctrlKey}var ru=class{constructor({previewElement:e,documentRef:t=document,windowRef:n=window}){this.previewElement=e,this.document=t,this.window=n,this.overlayRoot=null,this.viewport=null,this.imageElement=null,this.zoomLabel=null,this.titleElement=null,this.isOpen=!1,this.scale=$,this.offsetX=0,this.offsetY=0,this.activePointerId=null,this.dragStartX=0,this.dragStartY=0,this.dragOriginX=0,this.dragOriginY=0,this.touchPointers=new Map,this.pinchPointerIds=[],this.pinchStartDistance=0,this.pinchStartScale=$,this.pinchStartOffsetX=0,this.pinchStartOffsetY=0,this.pinchStartCenter={x:0,y:0},this.didDrag=!1,this.resetButton=null,this.handlePreviewClick=e=>{let t=e.target;if(!(t instanceof this.window.Element))return;let n=t.closest(`img`);!n||!this.previewElement?.contains(n)||n.closest(`[data-video-overlay-root="true"], [data-excalidraw-overlay-root="true"]`)||(e.preventDefault(),e.stopImmediatePropagation?.(),this.openFromImage(n))},this.handleKeyDown=e=>{if(this.isOpen){if(e.key===`Escape`){e.preventDefault(),this.close();return}if(e.key===`+`||e.key===`=`){e.preventDefault(),this.zoomBy(Zl);return}if(e.key===`-`){e.preventDefault(),this.zoomBy(-.25);return}e.key===`0`&&(e.preventDefault(),this.resetView())}},this.handleWindowResize=()=>{this.isOpen&&(this.clampOffsets(),this.syncTransform())},this.previewElement?.addEventListener(`click`,this.handlePreviewClick),this.document.addEventListener(`keydown`,this.handleKeyDown),this.window.addEventListener(`resize`,this.handleWindowResize)}destroy(){this.previewElement?.removeEventListener(`click`,this.handlePreviewClick),this.document.removeEventListener(`keydown`,this.handleKeyDown),this.window.removeEventListener(`resize`,this.handleWindowResize),this.close(),this.overlayRoot?.remove(),this.overlayRoot=null,this.viewport=null,this.imageElement=null,this.zoomLabel=null,this.titleElement=null,this.resetButton=null}openFromImage(e){let t=e?.currentSrc||e?.getAttribute?.(`src`)||``;return t?(this.ensureOverlayRoot(),this.resetView(),this.titleElement.textContent=e.getAttribute(`alt`)||`Image preview`,this.imageElement.src=t,this.imageElement.alt=e.getAttribute(`alt`)||``,this.overlayRoot.hidden=!1,this.isOpen=!0,this.document.body.classList.add(`image-lightbox-open`),this.syncTransform(),this.overlayRoot.focus?.(),!0):!1}close(){!this.isOpen&&!this.overlayRoot||(this.stopDrag(),this.touchPointers.clear(),this.pinchPointerIds=[],this.pinchStartDistance=0,this.didDrag=!1,this.viewport?.classList?.remove(`is-dragging`),this.overlayRoot&&(this.overlayRoot.hidden=!0),this.isOpen=!1,this.document.body.classList.remove(`image-lightbox-open`))}resetView(){this.scale=$,this.offsetX=0,this.offsetY=0,this.syncTransform()}zoomBy(e){this.setScale(this.scale+e)}setScale(e){this.scale=eu(e),this.clampOffsets(),this.syncTransform()}capturePointer(e){try{this.viewport?.setPointerCapture?.(e)}catch{}}releasePointer(e){try{this.viewport?.releasePointerCapture?.(e)}catch{}}getViewportPointFromClient(e,t){if(!this.viewport)return{x:0,y:0};let n=this.viewport.getBoundingClientRect();return{x:Number(e)-n.left-n.width/2,y:Number(t)-n.top-n.height/2}}setScaleAroundViewportPoint(e,t,{originScale:n=this.scale,originOffsetX:r=this.offsetX,originOffsetY:i=this.offsetY,targetViewportPoint:a=t}={}){let o=eu(e),s=Number(n)>0?Number(n):$,c=Number.isFinite(t?.x)?t.x:0,l=Number.isFinite(t?.y)?t.y:0,u=Number.isFinite(a?.x)?a.x:c,d=Number.isFinite(a?.y)?a.y:l;this.scale=o,this.offsetX=u-(c-r)/s*o,this.offsetY=d-(l-i)/s*o,this.clampOffsets(),this.syncTransform()}startDrag(e,t,n){return!this.viewport||this.scale<=$?!1:(this.activePointerId=e,this.dragStartX=t,this.dragStartY=n,this.dragOriginX=this.offsetX,this.dragOriginY=this.offsetY,this.viewport.classList.add(`is-dragging`),this.capturePointer(e),!0)}stopDrag(e=this.activePointerId){e===this.activePointerId&&(this.activePointerId=null),this.viewport?.classList?.remove(`is-dragging`),e!==null&&this.releasePointer(e),this.imageElement&&(this.imageElement.style.cursor=this.scale>$?`grab`:`zoom-in`)}updateDrag(e,t,n){return!this.isOpen||this.activePointerId!==e?!1:(!this.didDrag&&(Math.abs(t-this.dragStartX)>=$l||Math.abs(n-this.dragStartY)>=$l)&&(this.didDrag=!0),this.offsetX=this.dragOriginX+(t-this.dragStartX),this.offsetY=this.dragOriginY+(n-this.dragStartY),this.clampOffsets(),this.syncTransform(),!0)}getTrackedTouchPointers(){return Array.from(this.touchPointers.values())}getActivePinchPointers(){if(this.pinchPointerIds.length===2){let e=this.pinchPointerIds.map(e=>this.touchPointers.get(e)).filter(Boolean);if(e.length===2)return e}return this.getTrackedTouchPointers().slice(0,2)}startPinchGesture(){let[e,t]=this.getActivePinchPointers();if(!e||!t)return!1;this.stopDrag(),this.pinchPointerIds=[e.pointerId,t.pointerId],this.pinchStartDistance=Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)||1,this.pinchStartScale=this.scale,this.pinchStartOffsetX=this.offsetX,this.pinchStartOffsetY=this.offsetY;let n=this.getViewportPointFromClient((e.clientX+t.clientX)/2,(e.clientY+t.clientY)/2);return this.pinchStartCenter=n,!0}updatePinchGesture(){let[e,t]=this.getActivePinchPointers();if(!e||!t)return!1;let n=Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY);if(!Number.isFinite(n)||n<=0)return!1;let r=this.getViewportPointFromClient((e.clientX+t.clientX)/2,(e.clientY+t.clientY)/2),i=this.pinchStartScale*(n/this.pinchStartDistance);return this.setScaleAroundViewportPoint(i,this.pinchStartCenter,{originScale:this.pinchStartScale,originOffsetX:this.pinchStartOffsetX,originOffsetY:this.pinchStartOffsetY,targetViewportPoint:r}),!this.didDrag&&(Math.abs(n-this.pinchStartDistance)>=$l||Math.abs(r.x-this.pinchStartCenter.x)>=$l||Math.abs(r.y-this.pinchStartCenter.y)>=$l)&&(this.didDrag=!0),!0}syncTouchGestureAfterPointerChange(){if(this.touchPointers.size>=2){this.startPinchGesture();return}if(this.pinchPointerIds=[],this.pinchStartDistance=0,this.touchPointers.size===1&&this.scale>$){let[e]=this.getTrackedTouchPointers();this.startDrag(e.pointerId,e.clientX,e.clientY);return}this.stopDrag()}clampOffsets(){if(!this.viewport||!this.imageElement){this.offsetX=0,this.offsetY=0;return}this.offsetX=tu(this.offsetX,{contentSize:this.imageElement.offsetWidth||0,scale:this.scale,viewportSize:this.viewport.clientWidth||0}),this.offsetY=tu(this.offsetY,{contentSize:this.imageElement.offsetHeight||0,scale:this.scale,viewportSize:this.viewport.clientHeight||0})}syncTransform(){this.imageElement&&(this.imageElement.style.transform=`translate3d(${this.offsetX}px, ${this.offsetY}px, 0) scale(${this.scale})`,this.imageElement.style.cursor=this.scale>$?`grab`:`zoom-in`,this.zoomLabel&&(this.zoomLabel.textContent=`${Math.round(this.scale*100)}%`),this.resetButton&&(this.resetButton.disabled=this.scale<=$&&this.offsetX===0&&this.offsetY===0))}ensureOverlayRoot(){if(this.overlayRoot?.isConnected&&this.overlayRoot.parentElement===this.document.body)return this.overlayRoot;let e=this.document.createElement(`div`);e.className=`image-lightbox-root`,e.dataset.imageLightboxRoot=`true`,e.hidden=!0,e.tabIndex=-1;let t=this.document.createElement(`button`);t.className=`image-lightbox-backdrop`,t.type=`button`,t.setAttribute(`aria-label`,`Close image preview`),t.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.close()});let n=this.document.createElement(`div`);n.className=`image-lightbox-shell`,n.setAttribute(`role`,`dialog`),n.setAttribute(`aria-modal`,`true`),n.setAttribute(`aria-label`,`Image preview`),n.addEventListener(`click`,e=>e.stopPropagation()),n.addEventListener(`pointerdown`,e=>e.stopPropagation());let r=this.document.createElement(`div`);r.className=`image-lightbox-toolbar`;let i=this.document.createElement(`div`);i.className=`image-lightbox-title`,i.textContent=`Image preview`;let a=this.document.createElement(`div`);a.className=`image-lightbox-controls`;let o=this.createControlButton(`-`,`Zoom out`,()=>this.zoomBy(-.25)),s=this.document.createElement(`span`);s.className=`image-lightbox-zoom-label`,s.textContent=`100%`;let c=this.createControlButton(`+`,`Zoom in`,()=>this.zoomBy(Zl)),l=this.createControlButton(`Reset`,`Reset zoom and position`,()=>this.resetView()),u=this.createControlButton(`Close`,`Close image preview`,()=>this.close());a.append(o,s,c,l,u),r.append(i,a);let d=this.document.createElement(`div`);d.className=`image-lightbox-viewport`;let f=this.document.createElement(`img`);f.className=`image-lightbox-image`,f.alt=``,f.addEventListener(`load`,()=>{this.clampOffsets(),this.syncTransform()}),d.addEventListener(`wheel`,e=>{if(!this.isOpen)return;if(nu(e)){e.preventDefault(),this.zoomBy(e.deltaY<0?Zl:-.25);return}if(this.scale<=$)return;let t=Number.isFinite(e.deltaX)?e.deltaX:0,n=Number.isFinite(e.deltaY)?e.deltaY:0;(t!==0||n!==0)&&(e.preventDefault(),this.offsetX-=t,this.offsetY-=n,this.clampOffsets(),this.syncTransform())},{passive:!1}),d.addEventListener(`pointerdown`,e=>{if(this.isOpen){if(e.pointerType===`touch`){this.touchPointers.size===0&&(this.didDrag=!1),this.touchPointers.set(e.pointerId,{clientX:e.clientX,clientY:e.clientY,pointerId:e.pointerId}),this.capturePointer(e.pointerId),this.syncTouchGestureAfterPointerChange(),(this.touchPointers.size>1||this.scale>$)&&e.preventDefault();return}this.scale<=$||e.button!==0||(this.didDrag=!1,this.startDrag(e.pointerId,e.clientX,e.clientY),e.preventDefault())}}),d.addEventListener(`pointermove`,e=>{if(this.isOpen){if(e.pointerType===`touch`&&this.touchPointers.has(e.pointerId)){if(this.touchPointers.set(e.pointerId,{clientX:e.clientX,clientY:e.clientY,pointerId:e.pointerId}),this.touchPointers.size>=2){this.updatePinchGesture(),e.preventDefault();return}this.updateDrag(e.pointerId,e.clientX,e.clientY)&&e.preventDefault();return}this.updateDrag(e.pointerId,e.clientX,e.clientY)}});let p=e=>{if(e.pointerType===`touch`){this.touchPointers.delete(e.pointerId),this.releasePointer(e.pointerId),this.activePointerId===e.pointerId&&this.stopDrag(e.pointerId),this.syncTouchGestureAfterPointerChange();return}this.activePointerId===e.pointerId&&this.stopDrag(e.pointerId)};return d.addEventListener(`pointerup`,p),d.addEventListener(`pointercancel`,p),d.addEventListener(`lostpointercapture`,p),f.addEventListener(`click`,e=>{if(this.isOpen){if(e.preventDefault(),e.stopPropagation(),this.didDrag){this.didDrag=!1;return}this.scale<=$&&this.setScale(Ql)}}),d.appendChild(f),n.append(r,d),e.append(t,n),this.document.body.appendChild(e),this.overlayRoot=e,this.viewport=d,this.imageElement=f,this.zoomLabel=s,this.titleElement=i,this.resetButton=l,this.syncTransform(),e}createControlButton(e,t,n,{className:r=``}={}){let i=this.document.createElement(`button`);return i.className=`image-lightbox-btn ${r}`.trim(),i.type=`button`,i.setAttribute(`aria-label`,t),i.textContent=e,i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n(e)}),i}},iu=[gn,_n,Mn,Rn,Gn,{...Zr,...ui,...tr,...na,...gi},ra],au=class{constructor(){for(let e of iu)for(let[t,n]of Object.entries(e))t in this||(this[t]=n);this.elements=ln(document),this.runtimeConfig=fe(),this.activeSidebarTab=`files`,this.chatInitialSyncComplete=!1,this.chatIsOpen=!1,this.chatMessageIds=new Set,this.chatMessages=[],this.chatUnreadCount=0,this.connectionHelpShown=!1,this.connectionState={status:`disconnected`,unreachable:!1},this.currentDrawioMode=null,this.currentFilePath=null,this.fileExplorerReady=!1,this.followedCursorSignature=``,this.followedUserClientId=null,this.gitRepoAvailable=!1,this.globalUsers=[],this.isTabActive=!1,this.presencePanelOpen=!1,this.sessionLoadToken=0,this.navigation={getHashRoute:ge,navigateToFile:(e,t={})=>{let{preserveFollow:n=!1,...r}=t;!n&&e!==this.currentFilePath&&this.stopFollowingUser(),me(e,r)},navigateToGitCommit:ue,navigateToGitDiff:P,navigateToGitFileHistory:I,navigateToGitFilePreview:he,navigateToGitHistory:oe},this.preferences=new fa({fileTreeShowExtensionsKey:`collabmd-file-tree-show-extensions`,lineWrappingKey:`collabmd-editor-line-wrap`,recentFilesKey:`collabmd-recent-files`,vimModeKey:`collabmd-editor-vim-mode`,sidebarVisibleKey:`collabmd-sidebar-visible`,userNameKey:`collabmd-user-name`}),this.notifications=new pa,this.gitApiClient=va,this.vaultApiClient=ie,this._session=null,this._hasPromptedForDisplayName=!1,this._basePreviewRenderTimer=null,this._backlinkRefreshTimer=null,this._pendingPreviewLayoutSync=!1,this._previewHydrationPaused=!1,this._previewLayoutResizeObserver=null,this._previewLayoutSyncTimer=null,this._reloadPromptShown=!1,this._staticPreviewDocument=null,this.pendingGitResetPath=null,this.chatTimeFormatter=new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`2-digit`}),this.lobbyChatMessageMaxLength=280,this.quickSwitcher=null,this.quickSwitcherModulePromise=null,this.fileExplorerReadyPromise=Promise.resolve(),this.mobileBreakpointQuery=window.matchMedia(`(max-width: 768px)`),this.pendingWorkspaceRequestIds=new Set,this._fileOpenPerf=null,this.versionMonitor=new ga({currentBuildId:this.runtimeConfig.build?.id,onUpdateAvailable:e=>this.promptForVersionReload(e),runtimeConfig:this.runtimeConfig}),this.lobby=new ca({preferredUserName:this.getStoredUserName(),onChange:e=>this.updateGlobalUsers(e),onChatChange:(e,t)=>this.updateChatMessages(e,t)}),this.workspaceSync=new Ia({onTreeChange:(e,t={})=>{this.fileExplorer.setTree(e,t),this.handleCommentOverviewWorkspaceTreeChange?.(),this.fileExplorerReady=!0},onWorkspaceEvent:e=>{this.handleIncomingWorkspaceEvent(e)}}),this.toastController=new Ul(this.elements.toastContainer),this.chatToastController=new Ul(this.elements.chatToastContainer),this.fileExplorer=new ds({mobileBreakpointQuery:this.mobileBreakpointQuery,onFileDelete:()=>this.navigation.navigateToFile(null),onFileSelect:e=>this.workspaceRouteController.handleFileSelection(e,{closeSidebarOnMobile:!0}),onShowFileExtensionsChange:e=>{this.preferences.setFileTreeShowExtensions(e)},pendingWorkspaceRequestIds:this.pendingWorkspaceRequestIds,showFileExtensions:this.preferences.getFileTreeShowExtensions(),toastController:this.toastController,vaultClient:this.vaultApiClient}),this.commentsOverview=new Ba({onOverviewChange:(e,{threadCounts:t})=>{this.fileExplorer.setThreadCounts(t)},onThreadSelect:e=>this.openCommentOverviewThread(e),panelElement:this.elements.commentOverviewPanel,toastController:this.toastController,vaultApiClient:this.vaultApiClient}),this.gitPanel=new El({enabled:this.runtimeConfig.gitEnabled!==!1,gitApiClient:this.gitApiClient,onCommitStaged:()=>this.openGitCommitDialog(),onOpenPullBackup:e=>e&&this.navigation.navigateToFile(e),onPullBranch:()=>this.pullGitBranch(),onPushBranch:()=>this.pushGitBranch(),onRepoChange:(e,t)=>this.handleGitRepoChange(e,t),onResetFile:(e,{scope:t})=>this.openGitResetDialog(e,{scope:t}),onSelectCommit:(e,{path:t})=>this.handleGitCommitSelection(e,{closeSidebarOnMobile:!0,path:t}),onSelectDiff:(e,{scope:t})=>this.handleGitDiffSelection(e,{closeSidebarOnMobile:!0,scope:t}),onStageFile:(e,{scope:t})=>this.stageGitFile(e,{scope:t}),onUnstageFile:(e,{scope:t})=>this.unstageGitFile(e,{scope:t}),onViewAllDiff:()=>this.handleGitDiffSelection(null,{closeSidebarOnMobile:!0,scope:`all`}),searchInput:this.elements.gitSearchInput,toastController:this.toastController}),this.outlineController=new Ol({mobileBreakpointQuery:this.mobileBreakpointQuery,onNavigateToHeading:({sourceLine:e})=>{Number.isFinite(e)&&(this.scrollSyncController.suspendSync(250),this.session?.scrollToLine(e,0))},onWillOpen:()=>this.commentUi?.closeDrawer()}),this.videoEmbed=new Yl({previewElement:this.elements.previewContent}),this.basesPreview=new Tc({getActiveFilePath:()=>this.currentFilePath,getSession:()=>this.session,onOpenFile:e=>e&&this.navigation.navigateToFile(e),previewElement:this.elements.previewContent,replaceBaseSource:({path:e,source:t})=>{e&&e===this.currentFilePath&&this.session?.replaceText?.(t)},toastController:this.toastController,vaultApiClient:this.vaultApiClient}),this.imageLightbox=new ru({previewElement:this.elements.previewContent}),this.previewRenderer=new qt({getContent:()=>this.getPreviewSource(),getFileList:()=>this.fileExplorer.flatDocumentFiles,getWikiLinkAutoCreate:()=>this.runtimeConfig.wikiLinkAutoCreate!==!1,loadFileSource:async e=>{let t=await this.vaultApiClient.readFile(e);return String(t?.content??``)},getSourceFilePath:()=>this.currentFilePath,onAfterRenderCommit:(e,t)=>{this.recordFileOpenMetric(`preview_committed`,{chars:t?.chars??0,renderVersion:t?.renderVersion??0}),this.videoEmbed.reconcileEmbeds(this.elements.previewContent),this.basesPreview.reconcileEmbeds(this.elements.previewContent),this.drawioEmbed.reconcileEmbeds(this.elements.previewContent),this.excalidrawEmbed.reconcileEmbeds(this.elements.previewContent,{isLargeDocument:t.isLargeDocument}),this.scrollSyncController.setLargeDocumentMode(t.isLargeDocument),this.syncPreviewCodeCopyButtons(),this.syncPreviewHeadingLinkButtons(),this.applyPendingPreviewRouteAnchor({behavior:`auto`,clearMissing:!0}),this.schedulePreviewLayoutSync({delayMs:0}),this.refreshCommentUiLayout()},onBeforeRenderCommit:()=>{this.videoEmbed.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit()},onPreviewLayoutChange:()=>{this.scrollSyncController.invalidatePreviewBlocks(),this.applyPendingPreviewRouteAnchor({behavior:`auto`,clearMissing:!1}),this.schedulePreviewLayoutSync({delayMs:0}),this.refreshCommentUiLayout()},onRenderComplete:()=>{this.applyPendingPreviewRouteAnchor({allowExpired:!0,behavior:`auto`,clearMissing:!0}),this.schedulePreviewLayoutSync({delayMs:0}),this.refreshCommentUiLayout()},outlineController:this.outlineController,plantUmlRenderClient:this.vaultApiClient,previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent,toastController:this.toastController}),this.themeController=new Hl({onChange:e=>this.handleThemeChange(e)}),this.layoutController=new Dl({mobileBreakpointQuery:this.mobileBreakpointQuery,onMeasureEditor:()=>this.session?.requestMeasure(),onViewRequest:e=>this.handleLayoutViewRequest(e)}),this.scrollSyncController=new zl({getEditorLineNumber:()=>this.session?.getTopVisibleLineNumber(.35)??1,onEditorScrollActivityChange:e=>this.handleEditorScrollActivityChange(e),previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent,scrollEditorToLine:(e,t)=>this.session?.scrollToLine(e,t)}),this.pdfPreview=new ht({getTheme:()=>this.themeController.getTheme()}),this.backlinksPanel=new La({headerPanelElement:this.elements.backlinksHeaderPanel,inlinePanelElement:this.elements.backlinksInlinePanel,loadBacklinks:(e,t={})=>this.vaultApiClient.readBacklinks(e,t),onFileSelect:e=>this.workspaceRouteController.handleFileSelection(e,{closeSidebarOnMobile:!0}),panelElement:this.elements.backlinksPanel}),this.excalidrawEmbed=new Hc({getLocalUser:()=>this.lobby.getLocalUser(),getTheme:()=>this.themeController.getTheme(),onOpenFile:e=>e&&this.navigation.navigateToFile(e),onStopFollowing:()=>this.stopFollowingUser(),onToggleQuickSwitcher:()=>{this.toggleQuickSwitcher()},previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent,toastController:this.toastController}),this.drawioEmbed=new Mc({getLocalUser:()=>this.lobby.getLocalUser(),getTheme:()=>this.themeController.getTheme(),onOpenFile:e=>e&&this.navigation.navigateToFile(e),onOpenTextFile:e=>e&&this.navigation.navigateToFile(e,{drawioMode:`text`}),onToggleQuickSwitcher:()=>{this.toggleQuickSwitcher()},previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent,toastController:this.toastController,vaultApiClient:this.vaultApiClient}),this.commentUi=new Go({commentSelectionButton:this.elements.commentSelectionButton,commentsDrawer:this.elements.commentsDrawer,commentsDrawerEmpty:this.elements.commentsDrawerEmpty,commentsDrawerList:this.elements.commentsDrawerList,commentsToggleButton:this.elements.commentsToggleButton,editorContainer:this.elements.editorContainer,onWillOpenDrawer:()=>this.outlineController.close(),previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent,onCreateThread:({anchor:e,body:t})=>this.createCommentThread({anchor:e,body:t}),onNavigateToLine:e=>{let t=this.session;this.scrollSyncController.suspendSync(250),t?.scrollToLine(e,.2)&&requestAnimationFrame(()=>{this.session===t&&(this.scrollSyncController.suspendSync(0),this.scrollSyncController.syncPreviewToEditor())})},onReplyToThread:(e,t)=>this.replyToCommentThread(e,t),onToggleReaction:(e,t,n)=>this.session?.toggleCommentReaction(e,t,n),onResolveThread:e=>this.resolveCommentThread(e)}),this.structurizrPreview=new an({enabled:this.runtimeConfig.structurizrEnabled===!0,syncWorkspace:e=>this.vaultApiClient.syncStructurizrWorkspace(e)}),this.workspacePreviewController=new Qt({backlinksPanel:this.backlinksPanel,basesPreview:this.basesPreview,drawioEmbed:this.drawioEmbed,elements:this.elements,excalidrawEmbed:this.excalidrawEmbed,getDisplayName:e=>this.getDisplayName(e),getSession:()=>this.session,isBaseFile:e=>this.isBaseFile(e),isDrawioFile:e=>this.isDrawioFile(e),isExcalidrawFile:e=>this.isExcalidrawFile(e),isImageFile:e=>this.isImageFile(e),isPdfFile:e=>this.isPdfFile(e),isMermaidFile:e=>this.isMermaidFile(e),isPlantUmlFile:e=>this.isPlantUmlFile(e),layoutController:this.layoutController,structurizrPreview:this.structurizrPreview,outlineController:this.outlineController,pdfPreview:this.pdfPreview,previewRenderer:this.previewRenderer,schedulePreviewLayoutSync:e=>this.schedulePreviewLayoutSync(e),scrollSyncController:this.scrollSyncController,videoEmbed:this.videoEmbed}),this.wikiLinkFileController=new Zt({getFileList:()=>this.fileExplorer.flatDocumentFiles,navigation:this.navigation,refreshExplorer:()=>this.fileExplorer.refresh(),toastController:this.toastController,vaultApiClient:this.vaultApiClient,wikiLinkAutoCreate:this.runtimeConfig.wikiLinkAutoCreate!==!1}),this.gitDiffView=new gl({getTheme:()=>this.themeController.getTheme(),gitApiClient:this.gitApiClient,onBackToHistory:({historyFilePath:e}={})=>{if(e){this.navigation.navigateToGitFileHistory({filePath:e});return}this.navigation.navigateToGitHistory()},onCommitStaged:()=>this.openGitCommitDialog(),onOpenFile:e=>e&&this.navigation.navigateToFile(e),onStageFile:(e,{scope:t})=>this.stageGitFile(e,{scope:t}),onUnstageFile:(e,{scope:t})=>this.unstageGitFile(e,{scope:t}),toastController:this.toastController,vaultApiClient:this.vaultApiClient}),this.fileHistoryView=new _s({diffRenderer:this.gitDiffView,gitApiClient:this.gitApiClient,onOpenCommitDiff:(e,{historyFilePath:t,path:n})=>this.handleGitCommitSelection(e,{closeSidebarOnMobile:!1,historyFilePath:t,path:n}),onOpenFile:e=>e&&this.navigation.navigateToFile(e),onOpenPreview:({hash:e,path:t,currentFilePath:n})=>this.handleGitFilePreviewSelection({hash:e,path:t,currentFilePath:n}),onOpenWorkspaceDiff:e=>this.handleGitDiffSelection(e,{closeSidebarOnMobile:!1,scope:`all`}),toastController:this.toastController}),this.tabActivityLock=new Ea({onActivated:({takeover:e})=>this.handleTabActivated({takeover:e}),onBlocked:()=>this.handleTabBlocked({reason:`active-elsewhere`}),onStolen:()=>this.handleTabBlocked({reason:`taken-over`})}),this.workspaceCoordinator=new cn({attachEditorScroller:e=>this.scrollSyncController.attachEditorScroller(e),beginDocumentLoad:()=>this.previewRenderer.beginDocumentLoad(),cleanupAfterSessionDestroy:()=>{this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.outlineController.cleanup(),this.followedCursorSignature=``,clearTimeout(this._backlinkRefreshTimer)},createEditorSession:(e,t)=>new e({editorContainer:this.elements.editorContainer,getFileList:t.getFileList,initialTheme:t.theme,lineInfoElement:this.elements.lineInfo,lineWrappingEnabled:t.lineWrappingEnabled,localUser:t.localUser,vimModeEnabled:t.vimModeEnabled,onImagePaste:t.onImagePaste,onAwarenessChange:t.onAwarenessChange,onCommentsChange:t.onCommentsChange,onConnectionChange:t.onConnectionChange,onContentChange:t.onContentChange,onSelectionChange:t.onSelectionChange,preferredUserName:t.preferredUserName}),getDisplayName:e=>this.getDisplayName(e),getFileList:()=>this.fileExplorer.flatDocumentFiles,getLineWrappingEnabled:()=>this.getStoredLineWrapping(),getVimModeEnabled:()=>this.getStoredVimMode(),getLocalUser:()=>this.lobby.getLocalUser(),getStoredUserName:()=>this.getStoredUserName(),getTheme:()=>this.themeController.getTheme(),isBaseFile:e=>this.isBaseFile(e),isDrawioFile:e=>this.isDrawioFile(e),isExcalidrawFile:e=>this.isExcalidrawFile(e),isImageFile:e=>this.isImageFile(e),isPdfFile:e=>this.isPdfFile(e),isMermaidFile:e=>this.isMermaidFile(e),isPlantUmlFile:e=>this.isPlantUmlFile(e),isStructurizrWorkspaceFile:e=>this.isStructurizrWorkspaceFile(e),isTabActive:()=>this.isTabActive,loadBootstrapContent:async e=>{let t=await this.vaultApiClient.readFile(e);return typeof t?.content==`string`?t.content:null},loadEditorSessionClass:()=>this.loadEditorSessionClass(),loadBacklinks:e=>this.backlinksPanel.load(e),onBeforeFileOpen:()=>{clearTimeout(this._basePreviewRenderTimer),this._basePreviewRenderTimer=null,this.session=null,this.commentUi.attachSession(null),this.layoutController.reset(),this.workspacePreviewController.resetPreviewMode(),this.elements.emptyState?.classList.add(`hidden`),this.elements.editorPage?.classList.remove(`hidden`),this.elements.diffPage?.classList.add(`hidden`),this.clearInitialFileBootstrap()},onConnectionChange:e=>this.handleConnectionChange(e),onContentChange:({isBase:e,isMermaid:t,isPlantUml:n,isStructurizrWorkspace:r})=>{if(this.handleCommentEditorContentChange(),e){this.scheduleBaseFilePreview(this.currentFilePath,{source:this.session?.getText?.()??``});return}if(r){this.structurizrPreview.queueSync({filePath:this.currentFilePath,source:this.session?.getText?.()??``});return}this.previewRenderer.queueRender(),!t&&!n&&this.scheduleBacklinkRefresh()},onCommentsChange:e=>this.handleCommentThreadsChange(e),onFileAwarenessChange:e=>this.updateFileAwareness(e),onFileOpenError:()=>{this.showEditorLoadError(),this.syncWrapToggle(),this.toastController.show(`Failed to initialize editor`)},onFileOpenReady:()=>{this.hideEditorLoading(),this.currentFilePath&&this.preferences.recordRecentFile(this.currentFilePath)},onSelectionChange:e=>this.handleCommentSelectionChange(e),onImagePaste:e=>this.handleEditorImageInsert(e),onFileOpenMetric:(e,t)=>this.recordFileOpenMetric(e,t),onSessionAssigned:e=>{this.session=e,this.commentUi.attachSession(e)},onRenderDrawioPreview:e=>this.workspacePreviewController.renderDrawioFilePreview(e),onRenderBasePreview:e=>this.renderBaseFilePreview(e),onRenderExcalidrawPreview:e=>this.workspacePreviewController.renderExcalidrawFilePreview(e),onRenderImagePreview:e=>this.workspacePreviewController.renderImageFilePreview(e),onRenderPdfPreview:e=>this.workspacePreviewController.renderPdfFilePreview(e),onRenderStructurizrPreview:(e,t)=>this.workspacePreviewController.renderStructurizrFilePreview(e,t),onSyncWrapToggle:()=>this.syncWrapToggle(),onUpdateActiveFile:e=>this.fileExplorer.setActiveFile(e),onUpdateCurrentFile:e=>{this.currentFilePath=e},onUpdateLobbyCurrentFile:e=>this.lobby.setCurrentFile(e),onUpdateVisibleChrome:(e,{displayName:t})=>{this.workspacePreviewController.syncFileChrome(e,{drawioMode:this.currentDrawioMode,preferPreviewForBase:this.isBaseFile(e)}),this.syncCommentChrome(e),this.syncFileHistoryButton({filePath:e,mode:`editor`}),this.elements.activeFileName&&(this.elements.activeFileName.textContent=t)},onViewModeReset:()=>this.workspacePreviewController.resetPreviewMode(),renderPresence:()=>this.renderPresence(),scrollContainerForSession:e=>e.getScrollContainer(),shouldUseDrawioPreview:()=>!!this.runtimeConfig.drawioBaseUrl,showEditorLoading:()=>this.showEditorLoading(),stateStore:this}),this.workspaceRouteController=new Xt({backlinksPanel:this.backlinksPanel,clearInitialFileBootstrap:()=>this.clearInitialFileBootstrap(),clearStaticPreviewDocument:()=>this.clearStaticPreviewDocument(),closeSidebarOnMobile:()=>this.closeSidebarOnMobile(),drawioEmbed:this.drawioEmbed,elements:this.elements,excalidrawEmbed:this.excalidrawEmbed,fileHistoryView:this.fileHistoryView,fileExplorer:this.fileExplorer,getIsTabActive:()=>this.isTabActive,getSessionLoadToken:()=>this.sessionLoadToken,gitDiffView:this.gitDiffView,gitPanel:this.gitPanel,imageLightbox:this.imageLightbox,layoutController:this.layoutController,lobby:this.lobby,navigation:this.navigation,previewRenderer:this.previewRenderer,requestPreviewRouteAnchor:(e,t)=>this.requestPreviewRouteAnchor(e,t),renderAvatars:()=>this.renderAvatars(),renderPresence:()=>this.renderPresence(),resetPreviewMode:()=>this.workspacePreviewController.resetPreviewMode(),scrollSyncController:this.scrollSyncController,setCurrentFilePath:e=>{this.currentFilePath=e,e||(this.commentUi.setCurrentFile(null,{supported:!1}),this.handleCommentThreadsChange([]),this.handleCommentSelectionChange(null))},setSession:e=>{this.session=e,this.commentUi.attachSession(e)},setSessionLoadToken:e=>{this.sessionLoadToken=e},setSidebarTab:e=>this.setSidebarTab(e),setSidebarVisibility:e=>this.setSidebarVisibility(e),showGitCommit:e=>this.showGitCommit(e),showGitDiff:e=>this.showGitDiff(e),showGitFileHistory:e=>this.showGitFileHistory(e),showGitFilePreview:e=>this.showGitFilePreview(e),showGitHistory:()=>this.showGitHistory(),syncMainChrome:e=>this.syncMainChrome(e),videoEmbed:this.videoEmbed,workspaceCoordinator:this.workspaceCoordinator})}get session(){return this._session}set session(e){this._session=e}publishFileOpenPerf(){typeof window>`u`||(window.__COLLABMD_PERF__??={},window.__COLLABMD_PERF__.fileOpen=this._fileOpenPerf?{...this._fileOpenPerf,details:{...this._fileOpenPerf.details},marks:{...this._fileOpenPerf.marks}}:null)}recordFileOpenMetric(e,t={}){if(e===`open_started`){this._fileOpenPerf={details:{filePath:t.filePath||this.currentFilePath||``,loadToken:t.loadToken??0},marks:{open_started:performance.now()}},this.publishFileOpenPerf();return}this._fileOpenPerf&&(t.loadToken??this._fileOpenPerf.details.loadToken)===this._fileOpenPerf.details.loadToken&&(this._fileOpenPerf.marks[e]=performance.now(),t.filePath&&(this._fileOpenPerf.details.filePath=t.filePath),Object.entries(t).forEach(([e,t])=>{e!==`filePath`&&e!==`loadToken`&&(this._fileOpenPerf.details[e]=t)}),this.publishFileOpenPerf())}loadEditorSessionClass(){return this._editorSessionModulePromise||=e(()=>import(`./editor-session-DfZuRgB_.js`).then(e=>e.EditorSession),__vite__mapDeps([40,3,41,42,43,44,45,46,47,48,49,29,50,51,52,53]),import.meta.url),this._editorSessionModulePromise}scheduleEditorSessionPrewarm({timeout:e=1500}={}){if(this._editorSessionModulePromise||this._editorSessionPrewarmHandle)return;let t=()=>{this._editorSessionPrewarmHandle=null,this.loadEditorSessionClass()};if(typeof window.requestIdleCallback==`function`){this._editorSessionPrewarmHandle=window.requestIdleCallback(t,{timeout:e});return}this._editorSessionPrewarmHandle=window.setTimeout(t,0)}loadQuickSwitcherController(){return e(()=>import(`./quick-switcher-controller-ButWPmCI.js`).then(e=>e.QuickSwitcherController),__vite__mapDeps([54,29,31,55]),import.meta.url)}async ensureQuickSwitcher(){return Jt(this)}async toggleQuickSwitcher(){return Yt(this)}};async function ou(){await T(),new au().initialize()}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{ou()},{once:!0}):ou();