collabmd 0.1.44 → 0.1.45

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 (170) hide show
  1. package/dist/client/assets/{chunk-AXR3VHVW-0GTk_evH.js → chunk-ERSWUTIN-ME9RVNel.js} +3 -3
  2. package/dist/client/assets/{chunk-CZQZEIFA-DT3N9fo7.js → chunk-YGJVY4SA-CjSe7Bx7.js} +2 -2
  3. package/dist/client/assets/{comment-threads-D-iKphIp.js → comment-threads-DDegmaFO.js} +1 -1
  4. package/dist/client/assets/drawio-editor-ClE8jpoG.js +9 -0
  5. package/dist/client/assets/drawioEditor-CXaTM9Ds.js +2 -0
  6. package/dist/client/assets/editor-session-GTwZS6Df.js +16 -0
  7. package/dist/client/assets/embedded-editor-base-CiNEc8vy.css +1 -0
  8. package/dist/client/assets/{en-GADW4C6J-DQ6zyCEM.js → en-7NFCYGKX-BrgYZAEe.js} +1 -1
  9. package/dist/client/assets/{excalidraw-editor-BHu6k8d4.js → excalidraw-editor-BZVM81BO.js} +2 -2
  10. package/dist/client/assets/excalidraw-editor-CyGwOhLz.css +1 -0
  11. package/dist/client/assets/excalidraw-scene-C8n9CHsK.js +176 -0
  12. package/dist/client/assets/excalidrawEditor-DxJanCze.js +2 -0
  13. package/dist/client/assets/export-page-CUfws2T-.js +39 -0
  14. package/dist/client/assets/exportDocument-BCuxqXDY.js +2 -0
  15. package/dist/client/assets/exportDocument-DV-OX74E.css +1 -0
  16. package/dist/client/assets/image-QXRYHUNP-lfTHE3bb.js +1 -0
  17. package/dist/client/assets/index-C3YnUgMD.css +1 -0
  18. package/dist/client/assets/index-D2wXraJ1.js +2 -0
  19. package/dist/client/assets/main-DtiGz7uI.js +795 -0
  20. package/dist/client/assets/modulepreload-polyfill-P2Xu9kJm.js +1 -0
  21. package/dist/client/assets/preview-diagram-utils-txBCoW8d.js +1 -0
  22. package/dist/client/assets/quick-switcher-controller-shW_6vPY.js +12 -0
  23. package/dist/client/assets/room-CQLoqtMo.js +1 -0
  24. package/dist/client/assets/runtime-config-DSGmGE9V.js +1 -0
  25. package/dist/client/assets/vault-api-client-C6bcGwy-.js +5 -0
  26. package/dist/client/assets/{yjs-provider-reset-guard-Cox4nxwu.js → yjs-provider-reset-guard-DE0vINDP.js} +1 -1
  27. package/dist/client/drawio-editor.html +3 -2
  28. package/dist/client/excalidraw-editor.html +3 -2
  29. package/dist/client/export-document.html +4 -3
  30. package/dist/client/index.html +97 -27
  31. package/package.json +10 -12
  32. package/src/client/app/drawio-editor-entry.js +0 -3
  33. package/src/client/app/drawio-editor.html +1 -0
  34. package/src/client/app/excalidraw-editor-entry.js +0 -3
  35. package/src/client/app/excalidraw-editor.html +1 -0
  36. package/src/client/app/export-document-entry.js +0 -3
  37. package/src/client/app/export-document.html +1 -0
  38. package/src/client/app/index.html +94 -24
  39. package/src/client/app/main-entry.js +0 -5
  40. package/src/client/application/app-shell/chat-feature.js +180 -124
  41. package/src/client/application/app-shell/comments-feature.js +1 -1
  42. package/src/client/application/app-shell/git-feature.js +4 -9
  43. package/src/client/application/app-shell/presence-feature.js +16 -10
  44. package/src/client/application/app-shell/ui-feature-shell.js +33 -15
  45. package/src/client/application/app-shell/ui-feature-sidebar.js +74 -1
  46. package/src/client/application/app-shell/ui-feature-tab-activity.js +2 -2
  47. package/src/client/application/app-shell/workspace-feature.js +22 -83
  48. package/src/client/application/app-shell-elements.js +7 -1
  49. package/src/client/application/diagram-chrome.js +161 -166
  50. package/src/client/application/diagram-preview-export.js +7 -34
  51. package/src/client/application/diagram-preview-hydrator.js +1 -19
  52. package/src/client/application/markdown-frontmatter.js +0 -2
  53. package/src/client/application/mermaid-preview-hydrator.js +1 -14
  54. package/src/client/application/plantuml-preview-hydrator.js +0 -10
  55. package/src/client/application/preview-diagram-utils.js +31 -2
  56. package/src/client/application/preview-render-compiler.js +2 -1
  57. package/src/client/application/preview-renderer.js +2 -2
  58. package/src/client/application/quick-switcher-loader.js +3 -1
  59. package/src/client/application/workspace-preview-controller.js +0 -3
  60. package/src/client/bootstrap/collabmd-app-shell.js +125 -39
  61. package/src/client/domain/excalidraw-collaboration.js +0 -2
  62. package/src/client/domain/room.js +38 -0
  63. package/src/client/export/export-pipeline.js +6 -34
  64. package/src/client/infrastructure/auth-client.js +4 -10
  65. package/src/client/infrastructure/browser-notification-port.js +33 -20
  66. package/src/client/infrastructure/browser-preferences-port.js +36 -9
  67. package/src/client/infrastructure/editor-view-adapter.js +87 -3
  68. package/src/client/infrastructure/lobby-presence.js +1 -0
  69. package/src/client/infrastructure/vault-api-client.js +25 -0
  70. package/src/client/infrastructure/workspace-sync-client.js +13 -1
  71. package/src/client/presentation/comment-overview-controller.js +18 -53
  72. package/src/client/presentation/comment-ui/comment-ui-card.js +1 -12
  73. package/src/client/presentation/comment-ui/comment-ui-layout.js +242 -219
  74. package/src/client/presentation/comment-ui/comment-ui-render.js +32 -45
  75. package/src/client/presentation/comment-ui/comment-ui-shared.js +65 -14
  76. package/src/client/presentation/comment-ui-controller.js +5 -1
  77. package/src/client/presentation/file-action-controller.js +32 -0
  78. package/src/client/presentation/file-explorer-controller.js +33 -3
  79. package/src/client/presentation/file-explorer-view.js +49 -5
  80. package/src/client/presentation/file-tree-state.js +10 -4
  81. package/src/client/presentation/quick-switcher-controller.js +243 -72
  82. package/src/client/presentation/quick-switcher-text-search.js +2 -2
  83. package/src/client/presentation/toast-controller.js +3 -0
  84. package/src/client/styles/components/feedback.css +6 -0
  85. package/src/client/styles/features/collaboration-chat.css +49 -53
  86. package/src/client/styles/features/collaboration-presence.css +9 -7
  87. package/src/client/styles/features/comment-card.css +25 -11
  88. package/src/client/styles/features/comment-overlays.css +0 -4
  89. package/src/client/styles/features/comment-overview.css +44 -21
  90. package/src/client/styles/features/comments-drawer.css +2 -100
  91. package/src/client/styles/features/diagram-preview.css +5 -18
  92. package/src/client/styles/features/embedded-preview.css +8 -33
  93. package/src/client/styles/features/quick-switcher.css +8 -0
  94. package/src/client/styles/foundation/tokens.css +1 -0
  95. package/src/client/styles/layout/editor-page.css +40 -0
  96. package/src/client/styles/layout/responsive.css +31 -1
  97. package/src/client/styles/layout/shell.css +25 -6
  98. package/src/client/styles/layout/sidebar.css +47 -15
  99. package/src/client/styles/overrides/codemirror.css +217 -15
  100. package/src/server/application/workspace-reconciliation.js +1 -1
  101. package/src/server/create-app-server.js +2 -3
  102. package/src/server/domain/bases/base-query-service.js +1 -77
  103. package/src/server/domain/comment-overview.js +10 -3
  104. package/src/server/domain/docx-exporter.js +24 -33
  105. package/src/server/domain/ripgrep-search-service.js +3 -1
  106. package/src/server/domain/workspace-state.js +32 -11
  107. package/src/server/infrastructure/git/diff-service.js +24 -13
  108. package/src/server/infrastructure/git/git-service.js +40 -10
  109. package/src/server/infrastructure/git/history-service.js +42 -29
  110. package/src/server/infrastructure/git/path-utils.js +1 -1
  111. package/src/server/infrastructure/git/responses.js +0 -95
  112. package/src/server/infrastructure/github/github-app-client.js +22 -15
  113. package/src/server/infrastructure/http/create-request-handler.js +2 -8
  114. package/src/server/infrastructure/http/create-vault-api-command-handler.js +5 -5
  115. package/src/server/infrastructure/http/http-errors.js +7 -1
  116. package/dist/client/assets/bases-preview-controller-2pLHk0uk.js +0 -143
  117. package/dist/client/assets/button-BCEiw4Rw.js +0 -1
  118. package/dist/client/assets/diagram-action-icons-aa_KOv9h.js +0 -36
  119. package/dist/client/assets/drawio-editor-DDvFoarP.js +0 -9
  120. package/dist/client/assets/drawio-embed-controller-BD1GTRwn.js +0 -1
  121. package/dist/client/assets/drawioEditor-Bu5grlH5.js +0 -2
  122. package/dist/client/assets/editor-session-DGlpiAsK.js +0 -16
  123. package/dist/client/assets/embedded-editor-base-C9roKYpW.css +0 -1
  124. package/dist/client/assets/excalidraw-editor-Cr_184EF.css +0 -1
  125. package/dist/client/assets/excalidraw-embed-controller-y2fenN_g.js +0 -1
  126. package/dist/client/assets/excalidraw-embed-reconciler-DGiagExg.js +0 -1
  127. package/dist/client/assets/excalidraw-scene-BvsQ6mLP.js +0 -176
  128. package/dist/client/assets/excalidrawEditor-4vFE--Uw.js +0 -2
  129. package/dist/client/assets/export-page-Cby8JzPO.js +0 -39
  130. package/dist/client/assets/exportDocument-C9v-bc7I.css +0 -1
  131. package/dist/client/assets/exportDocument-CRHCfsdo.js +0 -2
  132. package/dist/client/assets/file-history-view-controller-BDjEV9xJ.js +0 -112
  133. package/dist/client/assets/git-diff-view-controller-DgdM1aqb.js +0 -150
  134. package/dist/client/assets/git-panel-controller-BDTR2HVp.js +0 -207
  135. package/dist/client/assets/image-XGD7JQR6-XDUWHRpO.js +0 -1
  136. package/dist/client/assets/index-7xOyXDhP.css +0 -1
  137. package/dist/client/assets/index-Bz1KuQ6y.js +0 -2
  138. package/dist/client/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  139. package/dist/client/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  140. package/dist/client/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  141. package/dist/client/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  142. package/dist/client/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  143. package/dist/client/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  144. package/dist/client/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  145. package/dist/client/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  146. package/dist/client/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
  147. package/dist/client/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
  148. package/dist/client/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  149. package/dist/client/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  150. package/dist/client/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  151. package/dist/client/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  152. package/dist/client/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
  153. package/dist/client/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
  154. package/dist/client/assets/main-Ci07m9oP.js +0 -152
  155. package/dist/client/assets/preview-diagram-utils-n_bbJA9V.js +0 -1
  156. package/dist/client/assets/quick-switcher-controller-CoiYvllm.js +0 -12
  157. package/dist/client/assets/room-CDrmIdDt.js +0 -1
  158. package/dist/client/assets/runtime-config-CDgeuPWN.js +0 -1
  159. package/dist/client/assets/runtime-config-loader-BHGniHP5.js +0 -1
  160. package/dist/client/assets/runtime-paths-DvpihCEq.js +0 -1
  161. package/dist/client/assets/segmented-control-DJrHSz8M.js +0 -1
  162. package/dist/client/assets/vault-api-client-sLB2bo56.js +0 -1
  163. package/dist/client/assets/vault-paths-CVkuh0j-.js +0 -5
  164. package/src/client/bootstrap/lazy-controller-feature.js +0 -433
  165. package/src/client/infrastructure/backlinks-api-client.js +0 -16
  166. package/src/client/infrastructure/plantuml-api-client.js +0 -19
  167. package/src/client/infrastructure/runtime-config-loader.js +0 -56
  168. package/src/server/infrastructure/git/command-runner.js +0 -49
  169. package/src/server/infrastructure/git/errors.js +0 -8
  170. package/src/server/infrastructure/http/create-esm-proxy-handler.js +0 -130
@@ -1,152 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./mermaid.core-DN-lF51U.js","./preload-helper-HclGiUj8.js","./chunk-Y2CYZVJY-DsF7k-Jl.js","./src-oBChb5qS.js","./rolldown-runtime-Dd_uD5pT.js","./chunk-I66GZJ75-CVFiiffQ.js","./chunk-NSK5VX7P-TLH37VXI.js","./dist-B_J_HbC0.js","./chunk-3NCLNEKW-Y2Jf_LI-.js","./chunk-4I5QYGJK-CCB2YcIH.js","./chunk-WRU74C26-h6_XkD3_.js","./chunk-7BUUIJ7U-Bb538aSH.js","./chunk-UBXNYLIW-Bhk-PbFK.js","./chunk-W5SLKNZC-BdNSCxZ9.js","./chunk-QR6OTTB3-CDAA_5Ib.js","./rough.esm-Dy-Kn_BL.js","./chunk-7Z6QIM7H-BP9Pdsm9.js","./line-B_S_S8kV.js","./path-fybaL0A-.js","./array-BifhSqXX.js","./chunk-J7OUQ5F2-4CEb7pvH.js","./chunk-ZIRB5QZD-O39ZBUk3.js","./preview-render-compiler-csGM5ZFz.js","./preview-render-compiler-BSaQO_p3.js","./preview-render-profile-BZzGSg6K.js","./file-kind-BKPOIRPE.js","./vault-utils-wdQ0RNR9.js","./bases-preview-controller-2pLHk0uk.js","./runtime-paths-DvpihCEq.js","./browser-utils-CKtI_rZl.js","./button-BCEiw4Rw.js","./segmented-control-DJrHSz8M.js","./drawio-embed-controller-BD1GTRwn.js","./drawio-room-yBUzk-vg.js","./diagram-action-icons-aa_KOv9h.js","./excalidraw-embed-controller-y2fenN_g.js","./excalidraw-embed-reconciler-DGiagExg.js","./git-panel-controller-BDTR2HVp.js","./vault-paths-CVkuh0j-.js","./git-diff-view-controller-DgdM1aqb.js","./file-history-view-controller-BDjEV9xJ.js","./editor-session-DGlpiAsK.js","./dist-C11hHqv_.js","./dist-BqCsFpx4.js","./dist-BIkPRZO7.js","./dist-JYEDRrPT.js","./dist-MvcV4190.js","./dist-CnL7Y2sM.js","./dist-CYZmbokb.js","./dist-DtbjNB28.js","./dist-GrygD2zE.js","./runtime-config-CDgeuPWN.js","./yjs-provider-reset-guard-Cox4nxwu.js","./room-CDrmIdDt.js","./comment-threads-D-iKphIp.js","./quick-switcher-controller-CoiYvllm.js"])))=>i.map(i=>d[i]);
2
- import{t as e}from"./preload-helper-HclGiUj8.js";import{a as t,i as n,n as r,o as i,r as a}from"./preview-render-profile-BZzGSg6K.js";import{a as o,c as s,d as c,f as l,i as u,l as d,m as f,n as p,o as m,p as h,r as g,s as _,t as v,u as y}from"./file-kind-BKPOIRPE.js";import{n as b,t as x}from"./vault-utils-wdQ0RNR9.js";import{a as ee,i as te,n as S,r as C,t as w}from"./vault-api-client-sLB2bo56.js";import{a as T,i as E,n as D,r as O}from"./runtime-paths-DvpihCEq.js";import{a as k,c as A,i as j,l as M,n as N,o as ne,r as re,s as ie,t as P,u as F}from"./runtime-config-CDgeuPWN.js";import{n as ae,r as I,t as oe}from"./yjs-provider-reset-guard-Cox4nxwu.js";import{a as se,c as L,i as R,l as z,n as ce,o as le,r as ue,s as de,t as B,u as V}from"./vault-paths-CVkuh0j-.js";import{a as H,n as U,r as fe,t as W}from"./browser-utils-CKtI_rZl.js";import{r as G,t as pe}from"./room-CDrmIdDt.js";import{a as me,c as he,d as ge,f as K,i as _e,l as ve,n as ye,o as be,r as xe,s as Se,t as Ce,u as we}from"./preview-diagram-utils-n_bbJA9V.js";import{o as Te,s as Ee,t as De}from"./comment-threads-D-iKphIp.js";import{t as Oe}from"./diagram-action-icons-aa_KOv9h.js";import{r as ke,t as q}from"./button-BCEiw4Rw.js";import{t as Ae}from"./excalidraw-embed-reconciler-DGiagExg.js";var je=Object.freeze({htmlLabels:!1,flowchart:{defaultRenderer:`dagre-wrapper`,htmlLabels:!1,useMaxWidth:!0},class:{defaultRenderer:`dagre-wrapper`,htmlLabels:!1,useMaxWidth:!0},startOnLoad:!1,theme:`default`}),Me=/^\s*%%\{\s*(?:init|initialize)\s*:[\s\S]*?\}%%\s*\n?/gim,Ne=0;function Pe(e){return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(e)}`}function Fe(){return Ne+=1,`mermaid-export-${Ne.toString(36)}`}function Ie(e){let t=Number.parseFloat(e.getAttribute(`width`)||``),n=Number.parseFloat(e.getAttribute(`height`)||``),r=(e.getAttribute(`viewBox`)||``).split(/\s+/u).map(e=>Number.parseFloat(e));return{height:Number.isFinite(n)&&n>0?n:Number.isFinite(r[3])&&r[3]>0?r[3]:800,width:Number.isFinite(t)&&t>0?t:Number.isFinite(r[2])&&r[2]>0?r[2]:1200}}function Le(e){return new Promise((t,n)=>{let r=new Image;r.decoding=`async`,r.addEventListener(`load`,()=>t(r),{once:!0}),r.addEventListener(`error`,()=>n(Error(`Failed to load image: ${e}`)),{once:!0}),r.src=e})}async function Re(e){if(typeof e.toBlob==`function`){let t=await new Promise(t=>e.toBlob(t,`image/png`));if(t instanceof Blob)return t}return ze(e.toDataURL(`image/png`))}function ze(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 Be(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}=Ie(t);return t.setAttribute(`width`,String(Math.max(1,Math.ceil(n)))),t.setAttribute(`height`,String(Math.max(1,Math.ceil(r)))),t}function Ve(e,{padding:t=16}={}){let n=Be(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 He({currentFilePath:e=``,diagramKind:t=`diagram`,sourceLine:n=``,targetPath:r=``}={}){let i=L(r);if(i)return l(i)||`${t}-diagram`;let a=L(e),o=l(a)||`document`;return t===`mermaid`&&y(e)||t===`plantuml`&&c(e)?o:n?`${o}-${t}-L${n}`:`${o}-${t}`}function Ue(e={}){let t=He(e);return{baseName:t,pngFileName:`${t}.png`,svgFileName:`${t}.svg`}}function We(e){let t=Be(e);return we(t)}function Ge(e,t={}){return we(Ve(e,t))}function Ke(e){let t=String(e??``).replace(Me,``);if(t=`%%{init: ${JSON.stringify(je)}}%%\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 qe(e,t){if(!e?.initialize||!e?.run)throw Error(`Mermaid runtime is unavailable`);e.initialize(je);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=Fe(),r.textContent=Ke(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 Ge(i,{padding:24})}finally{n.remove()}}async function Je(e){let t=ve(e),n=await Le(Pe(t)),r=document.createElement(`div`);r.innerHTML=t;let i=r.querySelector(`svg`),{width:a,height:o}=i?Ie(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),Re(s)}async function Ye(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 Xe(e){return`data-${e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`}var Ze=class{constructor(e,{batchSize:t,datasetKeys:n,fetchFn:r=null,loadFileSource:i=null,filePathLabel:a,requestIdleRenderFn:o=H,cancelIdleRenderFn:s=W,intersectionObserverFactory:c=(e,t)=>new IntersectionObserver(e,t),isNearViewportFn:l=fe,requestAnimationFrameFn:u=e=>requestAnimationFrame(e),shellClassName:d,sourceClassName:f}){this.renderer=e,this.batchSize=t,this.datasetKeys=n,this.loadFileSource=i??this.createLegacyFileSourceLoader(r),this.filePathLabel=a,this.requestIdleRenderFn=o,this.cancelIdleRenderFn=s,this.intersectionObserverFactory=c,this.isNearViewportFn=l,this.requestAnimationFrameFn=u,this.shellClassName=d,this.sourceClassName=f,this.shellSelector=`.${d}`,this.sourceSelector=`.${f}`,this.attributeNames=Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Xe(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}createLegacyFileSourceLoader(e){return typeof e==`function`?async t=>{let n=await e(D(`/file?path=${encodeURIComponent(t)}`)),r=await n.json().catch(()=>({}));if(!n.ok||r?.ok===!1)throw Error(r?.error||`Failed to load ${this.filePathLabel.toLowerCase()} source`);return String(r?.content??``)}:null}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(!ge({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}={}){K(e,t,this.attributeNames.sourceLine),K(e,t,this.attributeNames.sourceLineEnd),K(e,t,this.attributeNames.key),K(e,t,this.attributeNames.target),K(e,t,this.attributeNames.label),K(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=Se(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(Ce({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}},Qe=class extends Ze{constructor(e,{fetchFn:t=null,loadFileSource:n=null}={}){super(e,{batchSize:2,datasetKeys:{hydrated:`mermaidHydrated`,instanceId:`mermaidInstanceId`,key:`mermaidKey`,label:`mermaidLabel`,queued:`mermaidQueued`,sourceHash:`mermaidSourceHash`,sourceLine:`sourceLine`,sourceLineEnd:`sourceLineEnd`,target:`mermaidTarget`},fetchFn:t,filePathLabel:`Mermaid`,loadFileSource:n,shellClassName:`mermaid-shell`,sourceClassName:`mermaid-source`}),this.renderer=e,this.currentTheme=document.documentElement?.dataset.theme===`light`?`light`:`dark`,this.diagramChrome=e.diagramChrome,this.loader=null,this.runtime=null}destroy(){this.cancelHydration(),this.clearPreservedShells()}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-DN-lF51U.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([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]),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=Se(t);i?.after(Ce({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(ye(e.dataset.mermaidKey||`mermaid`)),this.enqueueShell(e,{prioritize:!0})})}async renderExportSvgMarkup(e){let t=await this.ensureMermaid();try{return await qe(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}=he(r);t.remove(),this.diagramChrome.mount(e,{baseHeight:a,baseWidth:i,diagramElement:r,exportFileNames:()=>Ue({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}scheduleActiveRefit(){this.diagramChrome?.scheduleActiveRefit?.({kind:`mermaid`,root:this.renderer.previewElement})}},$e=class extends Ze{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.renderer=e,this.diagramChrome=e.diagramChrome,this.renderClient=n,this.svgCache=new Map,this.svgInflightRequests=new Map}destroy(){this.cancelHydration(),this.clearPreservedShells()}cancelHydration({preserveActiveShell:e=!1}={}){super.cancelHydration(),e||this.diagramChrome?.cancelActiveShell?.(`plantuml`)}scheduleActiveRefit(){this.diagramChrome?.scheduleActiveRefitOnNextFrame?.()}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=Se(t);e.querySelector(`:scope > .plantuml-toolbar`)?.remove(),e.querySelector(`:scope > .plantuml-frame`)?.remove(),e.querySelector(`.plantuml-placeholder-card`)||i?.after(Ce({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=ve(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(xe(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}=be(r);this.diagramChrome.mount(e,{baseHeight:a,baseWidth:i,diagramElement:r,exportFileNames:()=>Ue({currentFilePath:this.renderer.getSourceFilePath?.()??``,diagramKind:`plantuml`,sourceLine:e.getAttribute(`data-source-line`)||``,targetPath:e.dataset.plantumlTarget||``}),exportSvgMarkup:()=>We(r),kind:`plantuml`,onReload:()=>{this.resetShell(e,{clearCache:!0,message:`Refreshing…`}),this.enqueueShell(e,{prioritize:!0})},sourceSelector:`.plantuml-source`})}},et=Object.freeze({animationDurationMs:160,default:1,max:3,min:.1,step:.1}),tt=Object.freeze({mermaid:{...et,fitMax:et.max,min:.5},plantuml:{...et,fitMax:et.default}}),nt=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 rt(e){return nt[e]??nt.mermaid}function it(e){return tt[e]??tt.mermaid}function at(e){return e instanceof SVGSVGElement}var ot=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,this.resizeFrameId=null}destroy(){this.destroyAllShells(),this.resizeObservers.forEach(e=>e.disconnect()),this.resizeObservers.clear(),this.maximizedRoots.forEach(e=>e.remove()),this.maximizedRoots.clear(),this.resizeFrameId&&=(this.window.cancelAnimationFrame(this.resizeFrameId),null),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)?.()})}scheduleActiveRefitOnNextFrame(){this.resizeFrameId&&this.window.cancelAnimationFrame(this.resizeFrameId),this.resizeFrameId=this.window.requestAnimationFrame(()=>{this.resizeFrameId=null,this.scheduleActiveRefit()})}ensureMaximizedRoot(e){let t=rt(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(nt))this.document.body.classList.toggle(n.bodyClassName,!!e?.classList?.contains(`${t}-shell`))}createButton(e,t,n,{icon:r=``}={}){let i=rt(e),a=this.document.createElement(`button`);return a.type=`button`,a.className=i.buttonClassName,a.setAttribute(`aria-label`,n),a.title=n,r?Oe(a,r):a.textContent=t,a}createToolbar({kind:e,includeReload:t=!1}){let n=rt(e),r=this.document.createElement(`div`);r.className=n.toolbarClassName;let i=this.document.createElement(`div`);i.className=`diagram-preview-toolbar-group diagram-preview-toolbar-group--zoom`;let a=this.document.createElement(`div`);a.className=`diagram-preview-toolbar-group diagram-preview-toolbar-group--actions`;let o=this.createButton(e,`-`,`Zoom out`);o.textContent=`−`;let 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 Je(await e());try{await Ye(r),this.toastController?.show?.(`Diagram copied`)}catch{U(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`});U(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`);Oe(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||!at(r))return null;let l=rt(o),u=it(o),d=e.querySelector(l.frameClassName.split(` `).map(e=>`.${e}`).join(``)),f=d?me(d).width:0,p=this.getShellViewState(e);this.destroyShell(e);let{copyButton:m,decreaseButton:h,downloadButton:g,increaseButton:_,maximizeButton:v,reloadButton:y,resetButton:b,toolbar:ee,zoomLabel:te}=this.createToolbar({includeReload:typeof s==`function`,kind:o}),S=this.document.createElement(`div`);S.className=l.frameClassName;let C=!!(p&&(p.scrollLeft>0||p.scrollTop>0)),w=!!(C&&d?.isConnected&&d.clientWidth>0&&d.clientHeight>0),T=!!(w&&!e.classList.contains(`is-maximized`)&&!e.style.position);T&&(e.style.position=`relative`),C&&!w&&(S.style.visibility=`hidden`),w&&Object.assign(S.style,{height:`${d.clientHeight}px`,left:`0`,pointerEvents:`none`,position:`absolute`,top:`0`,visibility:`hidden`,width:`${d.clientWidth}px`});let E=u.default,D=1,O=null,k=null,A=null,j=null,M=!!(p?.hasManualZoom||p?.scrollLeft>0||p?.scrollTop>0),N=f>0&&Number.isFinite(n)&&n>0,ne=Number.isFinite(p?.zoom),re=N?f:0,ie=!1,P=!1,F=null,ae=0,I=0,oe=0,se=0;r.style.display=`block`,r.style.margin=`0 auto`,r.style.maxWidth=`none`;let L=()=>{let e=me(S);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:x(t,u.min,u.fitMax)},R=e=>{E=x(e,u.min,u.max),r.style.width=`${n*E}px`,r.style.height=`${t*E}px`,te.textContent=`${Math.round(E*100)}%`,h.disabled=E<=u.min,_.disabled=E>=u.max;let i=me(S),a=n*E>i.width||t*E>i.height;S.classList.toggle(`is-pannable`,a),r.style.margin=a?`0`:`0 auto`},z=ne?x(p.zoom,u.min,u.max):N?x(f/n,u.min,u.fitMax):u.default;R(z);let ce=()=>({x:S.scrollLeft+S.clientWidth/2,y:S.scrollTop+S.clientHeight/2}),le=(e,t,n)=>{if(e===0)return;let r=t/e;S.scrollLeft=n.x*r-S.clientWidth/2,S.scrollTop=n.y*r-S.clientHeight/2},ue=e=>{let t=x(e,u.min,u.max),n=E;if(t===n)return;let r=ce(),i=performance.now();O&&this.window.cancelAnimationFrame(O);let a=e=>{let o=x((e-i)/u.animationDurationMs,0,1),s=_e(o),c=n+(t-n)*s;if(R(c),le(n,c,r),o<1){O=this.window.requestAnimationFrame(a);return}O=null,R(t),le(n,t,r)};O=this.window.requestAnimationFrame(a)},de=e=>{M=!0,ue(E+e)},B=({animate:e=!1}={})=>{if(D=L(),M=!1,re=me(S).width,e&&Math.abs(D-E)>.001){ue(D);return}O&&=(this.window.cancelAnimationFrame(O),null),R(D),S.scrollLeft=0,S.scrollTop=0},V=({force:t=!1}={})=>{ie||=t,k&&this.window.cancelAnimationFrame(k),A&&this.window.cancelAnimationFrame(A),k=this.window.requestAnimationFrame(()=>{A=this.window.requestAnimationFrame(()=>{A=this.window.requestAnimationFrame(()=>{if(A=null,k=null,!e.isConnected)return;let t=ie;ie=!1;let n=me(S).width,r=Math.abs(n-re)>1;!t&&M||!t&&n>0&&re>0&&!r||B()})})})},H=this.attachShellResizeObserver(e,S,()=>V());h.addEventListener(`click`,()=>de(-u.step)),_.addEventListener(`click`,()=>de(u.step)),b.addEventListener(`click`,()=>{V({force:!0})}),m.addEventListener(`click`,()=>this.copyExportImage(a,i)),g.addEventListener(`click`,()=>this.downloadExportSvg(a,i)),y?.addEventListener(`click`,()=>s()),v.addEventListener(`click`,()=>{this.setMaximizedState(e,o,v,V,!e.classList.contains(`is-maximized`))});let U=()=>{if(P){if(P=!1,S.classList.remove(`is-dragging`),this.window.removeEventListener(`pointerup`,U,!0),this.window.removeEventListener(`pointercancel`,U,!0),this.window.removeEventListener(`mouseup`,U,!0),this.window.removeEventListener(`touchend`,U,!0),this.window.removeEventListener(`touchcancel`,U,!0),this.window.removeEventListener(`blur`,U,!0),F!==null&&typeof S.releasePointerCapture==`function`)try{S.releasePointerCapture(F)}catch{}F=null}};S.addEventListener(`pointerdown`,e=>{if(!(e.button!==0||!S.classList.contains(`is-pannable`))){if(O&&=(this.window.cancelAnimationFrame(O),null),P=!0,F=e.pointerId,ae=e.clientX,I=e.clientY,oe=S.scrollLeft,se=S.scrollTop,S.classList.add(`is-dragging`),this.window.addEventListener(`pointerup`,U,!0),this.window.addEventListener(`pointercancel`,U,!0),this.window.addEventListener(`mouseup`,U,!0),this.window.addEventListener(`touchend`,U,!0),this.window.addEventListener(`touchcancel`,U,!0),this.window.addEventListener(`blur`,U,!0),typeof S.setPointerCapture==`function`)try{S.setPointerCapture(e.pointerId)}catch{}e.preventDefault()}}),S.addEventListener(`pointermove`,e=>{P&&(S.scrollLeft=oe-(e.clientX-ae),S.scrollTop=se-(e.clientY-I))}),S.addEventListener(`pointerup`,U),S.addEventListener(`pointercancel`,U),S.addEventListener(`lostpointercapture`,U),S.addEventListener(`mouseleave`,U),S.addEventListener(`mouseup`,U),S.addEventListener(`touchend`,U),S.addEventListener(`touchcancel`,U),S.appendChild(r);let fe=c?e.querySelector(c):null,W=fe?[fe,ee,S]:[ee,S];fe&&(fe.hidden=!0),w?e.append(S):e.replaceChildren(...W),R(z);let G=()=>{let e=Math.max(0,S.scrollWidth-S.clientWidth),t=Math.max(0,S.scrollHeight-S.clientHeight),n=x(p.scrollLeft??0,0,e),r=x(p.scrollTop??0,0,t);return S.scrollLeft=n,S.scrollTop=r,S.clientWidth>0&&S.clientHeight>0&&S.scrollLeft===n&&S.scrollTop===r};w?(G(),j=this.window.requestAnimationFrame(()=>{j=null,e.replaceChildren(...W),S.removeAttribute(`style`),T&&(e.style.position=``),R(z),G()})):C&&(G()?S.style.visibility=``:this.window.requestAnimationFrame(()=>{S.isConnected&&(G(),S.style.visibility=``)}));let pe={destroy:()=>{U(),O&&this.window.cancelAnimationFrame(O),k&&this.window.cancelAnimationFrame(k),A&&this.window.cancelAnimationFrame(A),j&&this.window.cancelAnimationFrame(j),H?.disconnect?.(),this.resizeObservers.delete(H)},getViewState:()=>({hasManualZoom:M,scrollLeft:S.scrollLeft,scrollTop:S.scrollTop,zoom:E}),scheduleResetZoomToFit:V,syncMaximizeButtonState:()=>this.syncMaximizeButtonState(e,v)};return this.shellControllers.set(e,pe),this.shellRefits.set(e,V),this.syncMaximizeButtonState(e,v),!N&&!ne&&V({force:!0}),pe}};function st(){return new Worker(new URL(``+new URL(`preview-render-worker-B42LWvrD.js`,import.meta.url).href,``+import.meta.url),{type:`module`})}var ct=class{constructor({attachmentApiPath:t=`/api/attachment`,cancelIdleRenderFn:n=W,compilePreviewDocumentLoader:r=()=>e(()=>import(`./preview-render-compiler-csGM5ZFz.js`),__vite__mapDeps([22,23,24,4,25,26]),import.meta.url),createWorkerFn:i=st,getFileList:a,getSourceFilePath:o=null,getWikiLinkAutoCreate:s=null,idleTimeoutMs:c=500,requestIdleRenderFn:l=H}={}){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)}},lt=class{constructor({cancelAnimationFrameFn:e=e=>cancelAnimationFrame(e),cancelIdleRenderFn:t=W,clearTimeoutFn:n=e=>clearTimeout(e),getRenderProfileFn:i=r,idleTimeoutMs:a=500,requestAnimationFrameFn:o=e=>requestAnimationFrame(e),requestIdleRenderFn:s=H,setTimeoutFn:c=(e,t)=>setTimeout(e,t)}={}){this.cancelAnimationFrameFn=e,this.cancelIdleRenderFn=t,this.clearTimeoutFn=n,this.getRenderProfileFn=i,this.idleTimeoutMs=a,this.requestAnimationFrameFn=o,this.requestIdleRenderFn=s,this.setTimeoutFn=c,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()}},ut=class{constructor({getContent:e,getFileList:t,getSourceFilePath:n,getWikiLinkAutoCreate:i=null,loadFileSource:a=null,onAfterRenderCommit:o,onBeforeRenderCommit:s,onPreviewLayoutChange:c,onRenderComplete:l,outlineController:u,plantUmlRenderClient:d=null,previewContainer:f,previewElement:p,toastController:m=null}){this.getContent=e,this.getFileList=t,this.getSourceFilePath=n,this.getWikiLinkAutoCreate=i,this.loadFileSource=a,this.onAfterRenderCommit=o,this.onBeforeRenderCommit=s,this.onPreviewLayoutChange=c,this.onRenderComplete=l,this.outlineController=u,this.plantUmlRenderClient=d,this.previewContainer=f,this.previewElement=p,this.toastController=m,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.mermaidHydrator.scheduleActiveRefit(),this.plantUmlHydrator.scheduleActiveRefit()},this.diagramChrome=new ot({toastController:m}),this.mermaidHydrator=new Qe(this,{loadFileSource:a}),this.plantUmlHydrator=new $e(this,{loadFileSource:a,renderClient:d}),this.renderScheduler=new lt({getRenderProfileFn:r}),this.renderExecutor=new ct({attachmentApiPath:D(`/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=a(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),o=this.plantUmlHydrator.setupHydration(n);i===0&&o===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 dt(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,getSearchConfig:()=>e.runtimeConfig.search??{},onFileSelect:t=>e.handleFileSelection(t,{closeSidebarOnMobile:!0,revealInTree:!0}),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 ft(e){try{(await dt(e)).toggle()}catch{}}var pt=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:y=null,resetPreviewMode:b,scrollSyncController:x,setSession:ee,setSessionLoadToken:te,setSidebarTab:S,setSidebarVisibility:C,setCurrentFilePath:w,showGitCommit:T,showGitDiff:E,showGitFileHistory:D,showGitFilePreview:O,showGitHistory:k,syncMainChrome:A,videoEmbed:j,workspaceCoordinator:M,layoutController:N}){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=y,this.resetPreviewMode=b,this.scrollSyncController=x,this.setSession=ee,this.setSessionLoadToken=te,this.setSidebarTab=S,this.setSidebarVisibility=C??(()=>{}),this.setCurrentFilePath=w,this.showGitCommit=T,this.showGitDiff=E,this.showGitFileHistory=D,this.showGitFilePreview=O,this.showGitHistory=k,this.syncMainChrome=A,this.videoEmbed=j,this.workspaceCoordinator=M,this.layoutController=N,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()}},mt=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=n(e,this.getFileList());if(t){this.navigation.navigateToFile(t);return}if(!this.wikiLinkAutoCreate){this.toastController.show(`Wiki-link target does not exist`);return}let r=this.normalizeNewWikiFilePath(e);if(!r){this.toastController.show(`Cannot create an empty wiki-link target`);return}this.createAndOpenFile(r,e)}normalizeNewWikiFilePath(e){let t=V(e);return t?t.endsWith(`.md`)?t:`${t}.md`:null}async createAndOpenFile(e,t){try{await this.vaultApiClient.createFile({content:R(t||e),path:e}),await this.refreshExplorer(),this.navigation.navigateToFile(e)}catch(e){this.toastController.show(`Failed to create file: ${e.message}`)}}},ht=class{constructor({backlinksPanel:e,basesPreview:t=null,drawioEmbed:n,elements:r,excalidrawEmbed:i,getDisplayName:a,getSession:o,isDrawioFile:s,isExcalidrawFile:c,isBaseFile:l,isImageFile:d,isMermaidFile:f,isPlantUmlFile:p,layoutController:m,outlineController:h,previewRenderer:g,schedulePreviewLayoutSync:_,scrollSyncController:v,videoEmbed:y}){this.backlinksPanel=e,this.basesPreview=t??{reconcileEmbeds(){},renderStandalone(){}},this.drawioEmbed=n??{detachForCommit(){},hydrateVisibleEmbeds(){},reconcileEmbeds(){},setHydrationPaused(){},syncLayout(){},updateLocalUser(){},updateTheme(){}},this.elements=r,this.excalidrawEmbed=i,this.getDisplayName=a,this.getSession=o,this.isDrawioFile=s??(()=>!1),this.isExcalidrawFile=c??(()=>!1),this.isBaseFile=l??u,this.isImageFile=d??(()=>!1),this.isMermaidFile=f??(()=>!1),this.isPlantUmlFile=p??(()=>!1),this.layoutController=m,this.outlineController=h,this.previewRenderer=g,this.schedulePreviewLayoutSyncCallback=_,this.scrollSyncController=v,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.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-mermaid-file-preview`),this.elements.previewContent?.classList.remove(`is-plantuml-file-preview`)}syncFileChrome(e,{drawioMode:t=null,preferPreviewForBase:n=!1}={}){let r=this.isDrawioFile(e),i=this.isExcalidrawFile(e),a=this.isBaseFile(e),s=this.isImageFile(e),c=d(e),l=this.isMermaidFile(e),u=this.isPlantUmlFile(e),f=o(e),p=i||r&&t!==`text`;if(this.backlinksPanel.setDisplayMode?.(p?`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`,f||s||a),this.elements.previewContent?.classList.toggle(`is-mermaid-file-preview`,l),this.elements.previewContent?.classList.toggle(`is-plantuml-file-preview`,u),r&&t!==`text`||i||s||a&&n){this.layoutController.setView(`preview`,{persist:!1}),this.outlineController.close(),this.backlinksPanel.clear();return}(l||u)&&(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=D(`/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})}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.replaceChildren(),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})}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.previewRenderer.scheduleActiveMermaidRefit(),this.previewRenderer.scheduleActivePlantUmlRefit(),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}))}},gt=150;function _t(e){return new Promise(t=>{setTimeout(t,e)})}var vt=class{constructor({attachEditorScroller:e,beginDocumentLoad:t,cleanupAfterSessionDestroy:n,createEditorSession:r,getDisplayName:i,getFileList:a,getLineWrappingEnabled:o,getLocalUser:s,getStoredUserName:c,getTheme:l,isBaseFile:u,isDrawioFile:d,isExcalidrawFile:f,isImageFile:p,isMermaidFile:m,isPlantUmlFile:h,isTabActive:g,loadBootstrapContent:_=null,loadEditorSessionClass:v,loadBacklinks:y,onBeforeFileOpen:b,onConnectionChange:x,onContentChange:ee,onCommentsChange:te,onFileAwarenessChange:S,onFileOpenError:C,onFileOpenReady:w,onImagePaste:T,onSelectionChange:E,onSessionAssigned:D=null,onFileOpenMetric:O=null,onRenderBasePreview:k,onRenderExcalidrawPreview:A,onRenderDrawioPreview:j,onRenderImagePreview:M,onSyncWrapToggle:N,onUpdateActiveFile:ne,onUpdateCurrentFile:re,onUpdateLobbyCurrentFile:ie,onUpdateVisibleChrome:P,onViewModeReset:F,renderPresence:ae,scrollContainerForSession:I,shouldUseDrawioPreview:oe=null,showEditorLoading:se,stateStore:L}){this.attachEditorScroller=e,this.beginDocumentLoad=t,this.cleanupAfterSessionDestroy=n,this.createEditorSession=r,this.getDisplayName=i,this.getFileList=a,this.getLineWrappingEnabled=o,this.getLocalUser=s,this.getStoredUserName=c,this.getTheme=l,this.isBaseFile=u??(()=>!1),this.isDrawioFile=d??(()=>!1),this.isExcalidrawFile=f??(()=>!1),this.isImageFile=p??(()=>!1),this.isMermaidFile=m??(()=>!1),this.isPlantUmlFile=h??(()=>!1),this.isTabActive=g,this.loadBootstrapContent=_,this.loadEditorSessionClassPort=v,this.loadBacklinks=y,this.onBeforeFileOpen=b,this.onConnectionChange=x,this.onContentChange=ee,this.onCommentsChange=te,this.onFileAwarenessChange=S,this.onFileOpenError=C,this.onFileOpenReady=w,this.onImagePaste=T,this.onSelectionChange=E,this.onSessionAssigned=D,this.onFileOpenMetric=O,this.onRenderBasePreview=k,this.onRenderDrawioPreview=j,this.onRenderExcalidrawPreview=A,this.onRenderImagePreview=M,this.onSyncWrapToggle=N,this.onUpdateActiveFile=ne,this.onUpdateCurrentFile=re,this.onUpdateLobbyCurrentFile=ie,this.onUpdateVisibleChrome=P,this.onViewModeReset=F,this.renderPresence=ae,this.scrollContainerForSession=I,this.shouldUseDrawioPreview=oe??(()=>!0),this.showEditorLoading=se,this.stateStore=L,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:t=null,resetConnectionState:n=!0}={}){return this.onViewModeReset(),this.onBeforeFileOpen(),this.stateStore.connectionHelpShown=!1,n&&(this.stateStore.connectionState={status:`connecting`,unreachable:!1}),this.stateStore.currentDrawioMode=t??null,this.stateStore.currentFilePath=e,this.onUpdateCurrentFile(e),this.onUpdateLobbyCurrentFile(e),this.onUpdateActiveFile(e),this.onUpdateVisibleChrome(e,{displayName:this.getDisplayName(e),drawioMode:t,isMarkdown:d(e)}),this.showEditorLoading(),this.beginDocumentLoad(),this.renderPresence(),{supportsBacklinks:h(e)}}finalizeFileOpen({isBase:e=!1,isDrawio:t=!1,filePath:n,isExcalidraw:r=!1,isImage:i=!1,supportsBacklinks:a}){r&&this.onRenderExcalidrawPreview(n),(e||u(n))&&this.onRenderBasePreview(n),t&&this.onRenderDrawioPreview(n),i&&this.onRenderImagePreview(n),this.onSyncWrapToggle(),a&&this.loadBacklinks(n)}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.isMermaidFile(e),l=this.isPlantUmlFile(e);if(e===this.stateStore.currentFilePath&&n===r&&(this.session||i||a||s)){this.onUpdateActiveFile(e),this.onUpdateLobbyCurrentFile(e);return}let u=++this.stateStore.sessionLoadToken,d=performance.now();this.cleanupSession();let f=this.prepareForFileOpen(e,{drawioMode:n,resetConnectionState:!i&&!a&&!s});if(this.reportFileOpenMetric(`open_started`,u,{filePath:e}),i||a||s){if(this.onSessionAssigned?.(null),u!==this.stateStore.sessionLoadToken)return;this.onFileOpenReady(null),this.finalizeFileOpen({filePath:e,isBase:o,isDrawio:i,isExcalidraw:a,isImage:s,session:null,supportsBacklinks:f.supportsBacklinks});return}let p=await this.loadEditorSessionClass(),m=this.createEditorSession(p,{filePath:e,getFileList:this.getFileList,lineWrappingEnabled:this.getLineWrappingEnabled(),localUser:this.getLocalUser(),onAwarenessChange:e=>this.onFileAwarenessChange(e),onConnectionChange:e=>this.onConnectionChange(e),onCommentsChange:e=>this.onCommentsChange?.(e),onContentChange:()=>{a||this.onContentChange({isBase:o,isMermaid:c,isPlantUml:l})},onImagePaste:e=>this.onImagePaste?.(e),preferredUserName:this.getStoredUserName(),onSelectionChange:e=>this.onSelectionChange?.(e),theme:this.getTheme()});this.session=m,this.onSessionAssigned?.(m);try{let t=!1,n=!1,r=!1,i=async r=>{t||u!==this.stateStore.sessionLoadToken||(t=!0,this.attachEditorScroller(this.scrollContainerForSession(m)),m.applyTheme(this.getTheme()),this.onFileOpenReady(m),this.reportFileOpenMetric(`editor_ready`,u,{reason:r}),m.requestMeasure(),await this.waitForNextPaint(),!(n||u!==this.stateStore.sessionLoadToken)&&(n=!0,this.finalizeFileOpen({filePath:e,isBase:o,isExcalidraw:a,session:m,supportsBacklinks:f.supportsBacklinks})))},s=this.loadBootstrapContent?(async()=>{this.reportFileOpenMetric(`bootstrap_fetch_started`,u);try{let t=await this.loadBootstrapContent(e);return this.reportFileOpenMetric(`bootstrap_fetch_completed`,u,{found:t!==null}),t}catch(e){return this.reportFileOpenMetric(`bootstrap_fetch_completed`,u,{error:e.message,found:!1}),null}})():Promise.resolve(null),c=m.initialize(e),l=(async()=>(await c,u!==this.stateStore.sessionLoadToken||(await m.waitForInitialSync(null),u!==this.stateStore.sessionLoadToken)?!1:(r=!0,m.activateCollaborativeView?.(),this.attachEditorScroller(this.scrollContainerForSession(m)),m.applyTheme(this.getTheme()),this.reportFileOpenMetric(`initial_sync_complete`,u),m.ensureInitialContent?.(),t?m.requestMeasure():await i(`live-sync`),!0)))(),p=(async()=>{let n=await s;if(n===null||r||t||u!==this.stateStore.sessionLoadToken)return!1;let a=performance.now()-d,o=Math.max(0,gt-a);return o>0&&await Promise.race([l.then(e=>e?`live-sync`:`stale`),_t(o).then(()=>`timeout`)])===`live-sync`||r||t||u!==this.stateStore.sessionLoadToken||!m.showBootstrapContent({content:n,filePath:e})&&!m.hasBootstrapContent?.()?!1:(this.reportFileOpenMetric(`bootstrap_shown`,u),await i(`bootstrap`),!0)})();if(await c,u!==this.stateStore.sessionLoadToken){m.destroy();return}if(await Promise.all([l,p]),u!==this.stateStore.sessionLoadToken){m.destroy();return}t||(m.ensureInitialContent?.(),await i(`post-initialize`))}catch(e){if(console.error(`[app] Failed to initialize editor:`,e),m.destroy(),this.attachEditorScroller(null),this.session===m&&(this.session=null),u!==this.stateStore.sessionLoadToken)return;this.onFileOpenError()}}};function yt(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`),chatNotificationButton:e.getElementById(`chatNotificationBtn`),chatPanel:e.getElementById(`chatPanel`),chatStatus:e.getElementById(`chatStatus`),chatToastContainer:e.getElementById(`chatToastContainer`),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`),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`),shareButton:e.getElementById(`shareBtn`),toastContainer:e.getElementById(`toastContainer`),toggleWrapButton:e.getElementById(`toggleWrapBtn`),userAvatars:e.getElementById(`userAvatars`),userCount:e.getElementById(`userCount`),wrapToggleLabel:e.getElementById(`wrapToggleLabel`),activeFileName:e.getElementById(`activeFileName`),sidebarToggle:e.getElementById(`sidebarToggle`),sidebarClose:e.getElementById(`sidebarClose`),sidebarBackdrop:e.getElementById(`sidebarBackdrop`),sidebar:e.getElementById(`sidebar`),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`),sidebarTabs:e.getElementById(`sidebarTabs`)}}var bt={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();return}this.openChatPanel()},openChatPanel(){this.chatIsOpen=!0,this.chatUnreadCount=0,this.renderChat(),requestAnimationFrame(()=>{this.elements.chatInput?.focus(),this.scrollChatToBottom()})},closeChatPanel(){this.chatIsOpen&&(this.chatIsOpen=!1,this.renderChat())},handleChatSubmit(){if(!this.isTabActive)return;let e=this.elements.chatInput;if(e){if(!this.lobby.sendChatMessage(e.value)){e.focus();return}if(e.value=``,!this.chatIsOpen){this.openChatPanel();return}this.renderChat()}},renderChat(){this.elements.chatContainer?.classList.toggle(`is-open`,this.chatIsOpen),this.elements.chatPanel?.classList.toggle(`hidden`,!this.chatIsOpen),this.syncChatToggleButton(),this.syncChatNotificationButton();let e=this.elements.chatMessages,t=this.elements.chatEmptyState;if(this.elements.chatStatus&&(this.elements.chatStatus.textContent=this.chatInitialSyncComplete?`${this.globalUsers.length} online`:`Syncing...`),!e)return;if(e.replaceChildren(),this.chatMessages.length===0){t?.classList.remove(`hidden`),e.classList.add(`hidden`);return}t?.classList.add(`hidden`),e.classList.remove(`hidden`);let n=document.createDocumentFragment();this.chatMessages.forEach(e=>{n.appendChild(this.createChatMessageElement(e))}),e.appendChild(n),this.chatIsOpen&&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`,r.style.backgroundColor=e.userColor||`var(--color-primary)`,r.textContent=(e.userName||`?`).charAt(0).toUpperCase(),r.setAttribute(`aria-hidden`,`true`);let i=document.createElement(`div`);i.className=`chat-message-body`;let a=document.createElement(`div`);a.className=`chat-message-meta`;let o=document.createElement(`span`);o.className=`chat-message-author`,o.textContent=n?`${e.userName} (you)`:e.userName;let s=document.createElement(`span`);s.className=`chat-message-time`,s.textContent=this.formatChatTimestamp(e.createdAt),a.append(o,s);let c=this.getChatMessageFileLabel(e.filePath);if(c){let e=document.createElement(`span`);e.className=`chat-message-file`,e.textContent=c,a.append(e)}let l=document.createElement(`p`);return l.className=`chat-message-text`,l.textContent=e.text,i.append(a,l),t.append(r,i),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}`},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-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))},syncChatNotificationButton(){let e=this.elements.chatNotificationButton;if(!e)return;let t=this.notifications.getPermission();this.chatNotificationPermission=t;let n=`Enable alerts`,r=`Enable browser notifications for new chat messages`,i=!1;t===`unsupported`?(n=`Alerts unavailable`,r=`Browser notifications are unavailable here`):t===`denied`?(n=`Alerts off`,r=`Browser notifications are blocked for this site`):t===`granted`&&(i=this.chatNotificationsEnabled,n=i?`Alerts on`:`Alerts off`,r=i?`Disable browser notifications for chat`:`Enable browser notifications for chat`),e.textContent=n,e.title=r,e.setAttribute(`aria-pressed`,String(i)),e.classList.toggle(`is-enabled`,i),e.classList.toggle(`is-blocked`,t===`denied`)},async handleChatNotificationToggle(){let e=this.notifications.getPermission();if(this.chatNotificationPermission=e,e===`unsupported`){this.toastController.show(`Browser notifications are unavailable here`),this.syncChatNotificationButton();return}if(e===`denied`){this.chatNotificationsEnabled=!1,this.preferences.setChatNotificationsEnabled(!1),this.toastController.show(`Browser notifications are blocked for this site`),this.syncChatNotificationButton();return}if(e==="default"){let e=await this.notifications.requestPermission();if(this.chatNotificationPermission=e,e!==`granted`){this.chatNotificationsEnabled=!1,this.preferences.setChatNotificationsEnabled(!1),e===`denied`&&this.toastController.show(`Browser notifications were blocked`),this.syncChatNotificationButton();return}this.chatNotificationsEnabled=!0,this.preferences.setChatNotificationsEnabled(!0),this.syncChatNotificationButton();return}this.chatNotificationsEnabled=!this.chatNotificationsEnabled,this.preferences.setChatNotificationsEnabled(this.chatNotificationsEnabled),this.syncChatNotificationButton()},maybeNotifyChatMessage(e){if(this.chatInitialSyncComplete){if(document.hidden){this.maybeShowBrowserChatNotification(e);return}!this.isTabActive||this.chatIsOpen||(this.chatToastController??this.toastController).show(this.formatChatToastMessage(e),4e3)}},maybeShowBrowserChatNotification(e){if(!this.chatNotificationsEnabled||this.notifications.getPermission()!==`granted`)return;let t=`CollabMD chat • ${e.userName}`,n=this.getChatMessageFileLabel(e.filePath),r=n?`${n}: ${e.text}`:e.text,i=this.notifications.createNotification({body:r,onClick:()=>{e.filePath&&this.navigation.navigateToFile(e.filePath)},tag:`collabmd-chat-${e.id}`,title:t});i&&setTimeout(()=>{i.close?.()},6e3)}},xt={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 p(e)||`markdown`},syncCommentChrome(e=this.currentFilePath){let t=f(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=Number.isFinite(e?.startLine)?e.startLine:null;this._pendingCommentOverviewFocus={attempts:0,filePath:t,line:r,threadId:n},this.setSidebarTab(`comments`),this.setSidebarVisibility(!0),this.workspaceRouteController?.preserveSidebarTabForNextFileRoute?.(t),this.navigation.navigateToFile(t,{line:r}),(this.currentFilePath!==t||!this.session)&&await this.openFile(t),this.setSidebarTab(`comments`),this.setSidebarVisibility(!0),this.focusPendingCommentOverviewThread()},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`),this.setSidebarVisibility(!0),!0):e.attempts>=8?(this._pendingCommentOverviewFocus=null,this.setSidebarTab(`comments`),this.setSidebarVisibility(!0),!1):(e.attempts+=1,clearTimeout(this._commentOverviewFocusTimer),this._commentOverviewFocusTimer=setTimeout(()=>{this._commentOverviewFocusTimer=null,this.focusPendingCommentOverviewThread()},120),!1))}},St=`collabmd-export-page`,Ct=`collabmd-export-host`,wt=500,Tt=6e4,Et=new Map,Dt=null;function Ot(){return`export-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function kt(e){return e===`pdf`?`pdf`:`docx`}function At({filePath:e,format:t,jobId:n}){let r=new URL(E(`/export-document.html`),window.location.origin);return r.searchParams.set(`action`,kt(t)),r.searchParams.set(`job`,n),e&&r.searchParams.set(`file`,e),r.toString()}function jt({fileList:e=[],filePath:t,format:n,jobId:r,markdownText:i=``,title:a=``}){return{action:kt(n),fileList:Array.isArray(e)?e.slice():[],filePath:String(t??``),jobId:r,markdownText:String(i??``),source:Ct,title:String(a??``),type:`bootstrap`}}function Mt(e){e&&(e.closePollId&&window.clearInterval(e.closePollId),e.timeoutId&&window.clearTimeout(e.timeoutId))}function Nt(e,{notifyError:t=!1,message:n=``}={}){let r=Et.get(e);r&&(Mt(r),Et.delete(e),t&&n&&Dt?.(n))}function Pt({onError:e=null}={}){Dt=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!==St)return;let n=String(t.jobId??``).trim();if(!n)return;let r=Et.get(n);if(r){if(t.type===`ready`){if(r.window?.closed){Nt(n,{message:`Export window was closed before the export completed`,notifyError:!0});return}try{r.window?.postMessage(r.payload,window.location.origin)}catch(e){Nt(n,{message:e instanceof Error?e.message:`Failed to send export data`,notifyError:!0})}return}(t.type===`complete`||t.type===`error`)&&Nt(n,{message:t.type===`error`&&t.message?String(t.message):``,notifyError:t.type===`error`&&!!t.message})}}),window.__collabmdExportBridgeInitialized=!0)}async function Ft({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=Ot(),s=At({filePath:a,format:n,jobId:o}),c=window.open(s,`_blank`);if(!c)throw Error(`Export popup was blocked`);return Et.set(o,{closePollId:window.setInterval(()=>{c.closed&&Nt(o,{message:`Export window was closed before the export completed`,notifyError:!0})},wt),payload:jt({fileList:e,filePath:a,format:n,jobId:o,markdownText:r,title:i}),timeoutId:window.setTimeout(()=>{Nt(o,{message:`Export timed out before it completed`,notifyError:!0})},Tt),window:c}),c.focus?.(),o}var It={initializeExportBridge(){this._exportBridgeInitialized||=(Pt({onError:e=>{this.toastController?.show(e)}}),!0)},async handleExportRequest(e){let t=String(this.currentFilePath??``).trim();if(!d(t))return this.toastController?.show(`Export is available for markdown notes only`),!1;try{return await Ft({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 Lt(e=[]){return Array.from(new Set((e??[]).filter(Boolean)))}function Rt(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 zt(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 Bt({changedPaths:e=[],deletedPaths:t=[],refreshExplorer:n=!0,renamedPaths:r=[]}={}){return{changedPaths:Lt(e),deletedPaths:Lt(t),refreshExplorer:n!==!1,renamedPaths:Rt(r)}}function Vt(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:zt(e.highlightRanges),id:e.id,origin:typeof e.origin==`string`?e.origin:`api`,reloadRequiredPaths:Lt(e.reloadRequiredPaths),requestId:typeof e.requestId==`string`?e.requestId:null,sourceRef:typeof e.sourceRef==`string`?e.sourceRef:null,workspaceChange:Bt(e.workspaceChange)}}var Ht={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.toolbarCenter?.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`}={}){await this.ensureGitControllers?.(),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}={}){await this.ensureGitControllers?.(),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(){await this.ensureGitControllers?.(),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(await this.ensureGitControllers?.(),!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.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.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.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.ensureGitControllers?.(),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=Bt(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=Bt(e.workspaceChange);if(e.origin===`git`&&await this.refreshGitAfterAction(),this.handleWorkspaceChangeForCurrentFile(t,{action:e.action||e.origin||`workspace`,local:!1,showToast:!0}),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_diverged_ff_only`){this.toastController.show(`Cannot pull because local and remote commits have diverged. Fast-forward only pull is not possible.`,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)}}}},Ut=5;function Wt(e,t){return String(e?.name??``).localeCompare(String(t?.name??``),void 0,{sensitivity:`base`})}function Gt(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));return!t&&(!e.currentFilePath||n||r||i)?e.lobby?.getConnectionState?.()??e.connectionState:e.connectionState}function Kt(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 qt(e,t){let n=e.filter(e=>e.isLocal).sort(Wt),r=e.filter(e=>!e.isLocal),i=r.filter(e=>e.clientId===t).sort(Wt),a=r.filter(e=>e.clientId!==t).sort(Wt);return[...n,...i,...a]}function Jt(e,t){return t.currentFile&&t.currentFile===e.currentFilePath?`Here`:t.currentFile?e.getDisplayName(t.currentFile):`No file`}var Yt={updateGlobalUsers(e){this.globalUsers=e,this.syncFollowedUser(),this.renderAvatars(),this.renderChat(),this.renderPresence(),this.syncCurrentUserName()},updateFileAwareness(e){this.syncFollowedUser()},renderPresence(){let e=this.elements.userCount;if(!e)return;let t=Gt(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=Kt(this.globalUsers,this.followedUserClientId);if(t.slice(0,Ut).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.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>Ut){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-Ut}`,n.appendChild(r),e.appendChild(n)}this.renderPresencePanel()},openPresencePanel(){Gt(this).status===`connected`&&this.globalUsers.length!==0&&(this.presencePanelOpen=!0,this.closeChatPanel?.(),this.closeToolbarOverflowMenu?.(),this.renderAvatars(),this.renderPresence(),this.renderPresencePanel())},closePresencePanel(){this.presencePanelOpen&&(this.presencePanelOpen=!1,this.renderAvatars(),this.renderPresence(),this.renderPresencePanel())},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)return;e.classList.toggle(`hidden`,!this.presencePanelOpen),e.setAttribute(`aria-hidden`,String(!this.presencePanelOpen));let r=qt(this.globalUsers,this.followedUserClientId),i=Gt(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.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=Jt(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=``,this.renderAvatars(),t&&this.closePresencePanel(),n.currentFile&&n.currentFile!==this.currentFilePath){this.navigation.navigateToFile(n.currentFile);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=``,this.renderAvatars(),e&&this.closePresencePanel())},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);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 Xt(){return this.runtimeConfig?.auth?.strategy===`oidc`&&this.runtimeConfig?.auth?.provider===`google`}function Zt({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 Qt(){!this.isTabActive||this._hasPromptedForDisplayName||this.getStoredUserName()||this.isIdentityManagedByAuth()||(this._hasPromptedForDisplayName=!0,requestAnimationFrame(()=>{this.openDisplayNameDialog({mode:`onboarding`})}))}function $t(){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):G(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 en(){return this.globalUsers.find(e=>e.isLocal)??this.session?.getLocalUser()??this.lobby?.getLocalUser()??null}function tn(){return this.getCurrentUser()?.name??this.getStoredUserName()??``}function nn(){return this.preferences.getUserName()}function rn(){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 an(){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 on={getCurrentUser:en,getCurrentUserName:tn,getStoredUserName:nn,handleDisplayNameSubmit:$t,isIdentityManagedByAuth:Xt,openDisplayNameDialog:Zt,promptForDisplayNameIfNeeded:Qt,syncCurrentUserName:rn,syncIdentityManagementUi:an},sn=0,cn=2e3,ln=8,un=`
7
- <svg viewBox="0 0 24 24" width="15" height="15" aria-hidden="true" focusable="false">
8
- <path d="M10 13.5 14 9.5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
9
- <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"/>
10
- <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"/>
11
- </svg>
12
- `;function dn(){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.commentsOverview?.initialize?.(),this.initializePreviewLayoutObserver(),this.syncIdentityManagementUi(),this.syncCurrentUserName(),this.syncWrapToggle(),this.syncToolbarOverflowVisibility?.(),this.syncChatNotificationButton(),this.syncFileHistoryButton({mode:`empty`}),this.renderChat(),this.elements.chatInput?.setAttribute(`maxlength`,String(this.lobbyChatMessageMaxLength)),this.bindEvents(),this.restoreSidebarState(),this.initializeVersionMonitoring(),this.tabActivityLock.initialize(),this.tabActivityLock.tryActivate(),window.addEventListener(`hashchange`,()=>this.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.scheduleGitControllerPrewarm?.(),this.isTabActive)return this.handleHashChange()})}function fn(){this.versionMonitor?.start()}function pn(){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 mn(){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 hn(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:sn,onAction:()=>window.location.reload()})}function gn(){this.elements.shareButton?.addEventListener(`click`,()=>{this.copyCurrentLink(),this.closeToolbarOverflowMenu?.()}),this.elements.searchFilesButton?.addEventListener(`click`,()=>{this.toggleQuickSwitcher(),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 _n(){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 vn(){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.chatForm?.addEventListener(`submit`,e=>{e.preventDefault(),this.handleChatSubmit()}),this.elements.chatNotificationButton?.addEventListener(`click`,()=>{this.handleChatNotificationToggle()}),gn.call(this),_n.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.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=>{e.target instanceof Element&&e.target.closest(`button`)&&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 yn(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())}function bn(e){if(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();return}te(e)&&(e.preventDefault(),e.stopPropagation(),this.toggleQuickSwitcher())}function xn(e,t){let n=e.closest(`ul, ol`);return n instanceof Element&&n.parentElement===t}function Sn(e){return!e.closest(`input[data-task-checkbox="true"]`)&&!!e.closest(`a, button, input, select, textarea, summary, [contenteditable="true"], [role="button"], [role="link"]`)}function Cn(e){let t=window.getSelection();return!!(!t?.isCollapsed&&e.contains(t.anchorNode)&&e.contains(t.focusNode))}function wn(e=``){let t=String(e??``).trim();if(!t)return``;try{return decodeURIComponent(t)}catch{return t}}function Tn(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 En(e){await navigator.clipboard.writeText(e)}function Dn(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 On(){return globalThis.performance?.now?.()??Date.now()}function kn(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),Tn(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 An(e){if(!this.currentFilePath||!e)return``;let t=new URL(window.location.href);return t.hash=M(this.currentFilePath,{anchor:e,drawioMode:this.currentDrawioMode??null}),t.toString()}async function jn(e){let t=this.createPreviewHeadingLinkUrl(e);if(!t){this.toastController.show(`Failed to copy section link`);return}try{await En(t),this.toastController.show(`Section link copied`)}catch{this.toastController.show(`Failed to copy section link`)}}function Mn(){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=Dn(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=un,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 Nn(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:On()+cn}:null,this._pendingPreviewRouteAnchor?this.applyPendingPreviewRouteAnchor({behavior:`auto`,clearMissing:!1}):!1}function Pn({allowExpired:e=!1,behavior:t=`auto`,clearMissing:n=!1}={}){let r=this._pendingPreviewRouteAnchor;if(!r)return!1;if(!e&&r.applied&&r.stabilizeUntil<=On())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=On()+cn,r.appliedCount>=ln&&(this._pendingPreviewRouteAnchor=null),!0):!1}function Fn(e){if(!(e.target instanceof Element))return;let t=e.target.closest(`button.preview-heading-link-button[data-preview-heading-anchor]`);if(t instanceof HTMLButtonElement){e.preventDefault(),this.copyPreviewHeadingLink(t.dataset.previewHeadingAnchor||``);return}let n=e.target.closest(`a.wiki-link[data-wiki-target]`);if(n){e.preventDefault(),this.handleWikiLinkClick(n.dataset.wikiTarget);return}let r=e.target.closest(`a[href]`),i=r?.getAttribute(`href`)?.trim()||``;if(r&&i.startsWith(`#`)&&!F(i)){if(e.preventDefault(),i===`#`||i.toLowerCase()===`#top`){this.scrollSyncController?.suspendSync?.(250),(this.elements.previewContainer??document.getElementById(`previewContainer`))?.scrollTo({top:0,behavior:`smooth`});return}let t=wn(i.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 a=e.target.closest(`.task-list-item[data-source-line]`);if(!a||xn(e.target,a)||Sn(e.target)||Cn(a))return;e.preventDefault();let o=Number.parseInt(a.getAttribute(`data-source-line`)||``,10);Number.isFinite(o)&&this.session?.toggleTaskListItem?.(o)}function In(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 Ln(){let e=this.elements.toolbarOverflowToggle;e&&(e.classList.remove(`hidden`),e.hidden=!1,e.setAttribute(`aria-hidden`,`false`))}function Rn(){this.setToolbarOverflowOpen(!1)}function zn(){this.setToolbarOverflowOpen(!this.toolbarOverflowOpen)}function Bn(e){this.previewRenderer.applyTheme(e),!this.isExcalidrawFile(this.currentFilePath)&&!this.isImageFile?.(this.currentFilePath)&&this.previewRenderer.queueRender(),this.session?.applyTheme(e),this.excalidrawEmbed.updateTheme(e),this.drawioEmbed.updateTheme(e)}function Vn(e){this.connectionState=e,e?.firstConnection&&this.recordFileOpenMetric?.(`ws_connected`,{status:e.status}),this.renderPresence(),e.unreachable&&!this.connectionHelpShown&&(this.connectionHelpShown=!0,this.toastController.show(`Cannot reach server at ${e.wsBaseUrl}`,6e3))}function Hn(){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 Un(){return this.preferences.getLineWrappingEnabled()}function Wn(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 Gn(){clearTimeout(this._backlinkRefreshTimer),this._backlinkRefreshTimer=setTimeout(()=>{h(this.currentFilePath)&&this.backlinksPanel.load(this.currentFilePath)},2e3)}function Kn(){this.elements.editorContainer&&(this.elements.editorContainer.classList.add(`is-loading-editor`),this.elements.editorContainer.innerHTML=`
13
- <div class="editor-loading" id="editorLoading">
14
- <div class="loading-spinner"></div>
15
- <span class="loading-text">Loading file...</span>
16
- </div>`)}function qn(){this.elements.editorContainer&&(this.elements.editorContainer.classList.remove(`is-loading-editor`),this.elements.editorContainer.querySelector(`#editorLoading`)?.remove())}function Jn(){this.elements.editorContainer&&(this.elements.editorContainer.classList.remove(`is-loading-editor`),this.elements.editorContainer.innerHTML=`
17
- <div class="editor-loading" id="editorLoading">
18
- <span class="loading-text">Failed to load file</span>
19
- </div>`)}function Yn(){document.documentElement.removeAttribute(`data-initial-file-requested`)}var Xn={applyPendingPreviewRouteAnchor:Pn,bindEvents:vn,clearInitialFileBootstrap:Yn,closeToolbarOverflowMenu:Rn,copyPreviewHeadingLink:jn,createPreviewHeadingLinkUrl:An,getStoredLineWrapping:Un,handleConnectionChange:Vn,handleDocumentKeydown:bn,handleDocumentPointerDown:yn,handlePreviewContentClick:Fn,handleThemeChange:Bn,hideEditorLoading:qn,initialize:dn,initializeVisualViewportBinding:mn,initializeVersionMonitoring:fn,isPlainQuickSwitcherShortcut:te,navigatePreviewHeading:kn,promptForVersionReload:hn,requestPreviewRouteAnchor:Nn,scheduleBacklinkRefresh:Gn,setToolbarOverflowOpen:In,showEditorLoadError:Jn,showEditorLoading:Kn,syncPreviewHeadingLinkButtons:Mn,syncVisualViewportBounds:pn,syncToolbarOverflowVisibility:Ln,syncWrapToggle:Wn,toggleToolbarOverflowMenu:zn,toggleLineWrapping:Hn};function Zn(){return this.mobileBreakpointQuery.matches}function Qn(){let e=this.elements.sidebar;!e||!this.isMobileViewport()||e.classList.contains(`collapsed`)||this.setSidebarVisibility(!1)}function $n(){let e=this.elements.sidebar;if(!e)return;let t=e.classList.contains(`collapsed`);this.setSidebarVisibility(t)}function er(){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 tr(e){this.applySidebarVisibility(e),this.preferences.setSidebarVisible(e)}function nr(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 rr(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 ir={applySidebarVisibility:nr,closeSidebarOnMobile:Qn,isMobileViewport:Zn,restoreSidebarState:er,setSidebarTab:rr,setSidebarVisibility:tr,toggleSidebar:$n};function ar(){this.tabActivityLock.tryActivate({takeover:!0})}function or({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.handleHashChange(),this.promptForDisplayNameIfNeeded()),e&&this.toastController.show(`This tab is now active`)}async function sr({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 cr({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 lr(){this.elements.tabLockOverlay?.classList.add(`hidden`)}var ur={handleTabActivated:or,handleTabBlocked:sr,handleTabTakeover:ar,hideTabLockOverlay:lr,showTabLockOverlay:cr},J=Object.freeze({bold:`
20
- <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">
21
- <path d="M7 5h6a4 4 0 0 1 0 8H7z"/>
22
- <path d="M7 13h7a4 4 0 0 1 0 8H7z"/>
23
- </svg>
24
- `,italic:`
25
- <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">
26
- <path d="M14 4h6"/>
27
- <path d="M4 20h6"/>
28
- <path d="M14 4 10 20"/>
29
- </svg>
30
- `,strikethrough:`
31
- <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">
32
- <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"/>
33
- <path d="M3 12h18"/>
34
- </svg>
35
- `,link:`
36
- <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">
37
- <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"/>
38
- <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"/>
39
- </svg>
40
- `,image:`
41
- <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">
42
- <rect x="3" y="5" width="18" height="14" rx="2"/>
43
- <circle cx="9" cy="10" r="1.5"/>
44
- <path d="m21 16-5.5-5.5L7 19"/>
45
- </svg>
46
- `,video:`
47
- <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">
48
- <rect x="3" y="5" width="18" height="14" rx="2"/>
49
- <path d="m10 9 5 3-5 3z" fill="currentColor" stroke="none"/>
50
- </svg>
51
- `,table:`
52
- <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">
53
- <rect x="3" y="5" width="18" height="14" rx="1"/>
54
- <path d="M3 10h18"/>
55
- <path d="M9 5v14"/>
56
- <path d="M15 5v14"/>
57
- </svg>
58
- `,code:`
59
- <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">
60
- <path d="m8 9-4 3 4 3"/>
61
- <path d="m16 9 4 3-4 3"/>
62
- <path d="m13 6-2 12"/>
63
- </svg>
64
- `,horizontalRule:`
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="M4 12h16"/>
67
- <path d="M9 8h6"/>
68
- <path d="M9 16h6"/>
69
- </svg>
70
- `,indent:`
71
- <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">
72
- <path d="M4 6h16"/>
73
- <path d="M10 12h10"/>
74
- <path d="M10 18h10"/>
75
- <path d="m4 9 4 3-4 3"/>
76
- </svg>
77
- `,outdent:`
78
- <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">
79
- <path d="M4 6h16"/>
80
- <path d="M10 12h10"/>
81
- <path d="M10 18h10"/>
82
- <path d="m8 9-4 3 4 3"/>
83
- </svg>
84
- `,redo:`
85
- <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">
86
- <path d="M21 7v6h-6"/>
87
- <path d="M20 13a8 8 0 0 0-14-3"/>
88
- </svg>
89
- `,undo:`
90
- <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">
91
- <path d="M3 7v6h6"/>
92
- <path d="M4 13a8 8 0 0 1 14-3"/>
93
- </svg>
94
- `,chevronDown:`
95
- <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">
96
- <path d="m6 9 6 6 6-6"/>
97
- </svg>
98
- `}),dr=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`}]),fr=Object.freeze([{action:`bold`,label:`Bold`,title:`Bold`,icon:J.bold},{action:`italic`,label:`Italic`,title:`Italic`,icon:J.italic},{action:`strikethrough`,label:`Strikethrough`,title:`Strikethrough`,icon:J.strikethrough},{action:`code`,label:`Inline code`,title:`Inline code`,icon:J.code}]),pr=Object.freeze([{commandId:`undo`,label:`Undo`,title:`Undo`,icon:J.undo},{commandId:`redo`,label:`Redo`,title:`Redo`,icon:J.redo},{commandId:`indentMore`,label:`Indent`,title:`Indent`,icon:J.indent},{commandId:`indentLess`,label:`Outdent`,title:`Outdent`,icon:J.outdent}]),mr=Object.freeze([{action:`link`,label:`Insert link`,title:`Insert link`,icon:J.link},{action:`image`,label:`Insert image`,title:`Insert image`,icon:J.image},{action:`video`,label:`Insert video`,title:`Insert video`,icon:J.video}]),hr=Object.freeze([{action:`table`,label:`Insert table`,title:`Insert table`,icon:J.table},{action:`horizontal-rule`,label:`Insert horizontal rule`,title:`Insert horizontal rule`,icon:J.horizontalRule}]),gr=Object.freeze([{kind:`buttons`,groupLabel:`Edit`,actions:pr,mobileOnly:!0},{kind:`block-menu`,actions:dr},{kind:`buttons`,groupLabel:`Inline formatting`,actions:fr},{kind:`buttons`,groupLabel:`Media and links`,actions:mr},{kind:`buttons`,groupLabel:`Insert`,actions:hr}]),_r=[...dr,...fr,...mr,...hr],vr=new Map(_r.map(e=>[e.action,e]));function yr(e){return vr.get(e)??null}function br(){return dr}function xr(e){return dr.some(t=>t.action===e)}function Sr(e){return yr(e)?.shortLabel??`P`}function Cr(){return J}var wr=`image/png,image/jpeg,image/webp,image/gif,image/svg+xml`,Tr=`paragraph`;function Er(e){return e===`heading`?`heading-2`:String(e??``).trim()}function Dr(e){return e.map(e=>`<button type="button" class="ui-icon-button ui-icon-button--toolbar ui-toolbar-action" ${e.commandId?`data-editor-command="${b(e.commandId)}"`:`data-markdown-action="${b(e.action)}"`} aria-label="${b(e.label)}" title="${b(e.title)}">${e.icon}</button>`).join(``)}function Or(e){return`
99
- <div class="markdown-toolbar-block-menu-shell">
100
- <button
101
- type="button"
102
- class="ui-button ui-button--ghost markdown-toolbar-block-trigger"
103
- data-markdown-block-menu-toggle
104
- aria-haspopup="menu"
105
- aria-expanded="false"
106
- title="Block formatting"
107
- >
108
- <span class="markdown-toolbar-block-trigger-label" data-markdown-block-trigger-label>${b(Sr(e))}</span>
109
- <span class="markdown-toolbar-block-trigger-icon" aria-hidden="true">${Cr().chevronDown}</span>
110
- </button>
111
- </div>
112
- `}function kr(e){return br().map(t=>{let n=t.action===e;return`
113
- <button
114
- type="button"
115
- class="markdown-toolbar-menu-item${n?` is-active`:``}"
116
- data-markdown-block-action="${b(t.action)}"
117
- role="menuitemradio"
118
- aria-checked="${n?`true`:`false`}"
119
- title="${b(t.title)}"
120
- >
121
- <span class="markdown-toolbar-menu-item-label">${b(t.label)}</span>
122
- <span class="markdown-toolbar-menu-item-shortcut">${b(t.shortLabel)}</span>
123
- </button>
124
- `}).join(``)}function Ar(e){return gr.map(t=>t.kind===`block-menu`?Or(e):`
125
- <div class="markdown-toolbar-group${t.mobileOnly?` markdown-toolbar-group--mobile-only`:``}" role="group" aria-label="${b(t.groupLabel)}">
126
- ${Dr(t.actions)}
127
- </div>
128
- `).join(``)}function jr(){let e=Er(this._activeMarkdownBlockAction||Tr);return xr(e)?e:Tr}function Mr(){let e=this.elements?.markdownToolbar;e&&(e.innerHTML=Ar(this.getActiveMarkdownBlockAction()),this.renderMarkdownBlockMenuPopover(),this.syncMarkdownToolbarBlockUi())}function Nr(){return this._markdownBlockMenuPopover??null}function Pr(){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=kr(this.getActiveMarkdownBlockAction()))}function Fr(){let e=this.elements?.markdownToolbar;if(!e)return;let t=this.getActiveMarkdownBlockAction(),n=yr(t),r=e.querySelector(`[data-markdown-block-trigger-label]`);r&&(r.textContent=Sr(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 Ir(e){let t=Er(e);xr(t)&&(this._activeMarkdownBlockAction=t,this.syncMarkdownToolbarBlockUi())}function Lr(){return!!this.elements?.markdownToolbar?.classList.contains(`is-menu-open`)}function Rr(){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 zr(){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 Br(){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 Vr(){if(this.isMarkdownBlockMenuOpen()){this.closeMarkdownBlockMenu();return}this.openMarkdownBlockMenu()}function Hr(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 Ur(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 Wr(e){this.isMarkdownBlockMenuOpen()&&(this.elements?.markdownToolbar?.contains(e.target)||this.getMarkdownBlockMenuPopover()?.contains(e.target)||this.closeMarkdownBlockMenu())}function Gr(e){if(!this.session||!d(this.currentFilePath))return;if(e===`image`){this.handleToolbarImageInsert();return}let t=Er(e);if(!this.session.applyMarkdownToolbarAction(t)){this.toastController.show(`Formatting action is unavailable`);return}xr(t)&&this.setActiveMarkdownBlockAction(t)}function Kr(e){return this.session?.runEditorCommand?.(e)?!0:(this.toastController.show(`Editor action is unavailable`),!1)}async function qr(){let e=await this.pickImageFile();e&&await this.handleEditorImageInsert(e)}function Jr(){return new Promise(e=>{let t=document.createElement(`input`);t.type=`file`,t.accept=wr,t.style.position=`fixed`,t.style.left=`-9999px`,document.body.appendChild(t);let n=!1,r=null,i=i=>{n||(n=!0,r&&window.clearTimeout(r),window.removeEventListener(`focus`,a),t.remove(),e(i))},a=()=>{r=window.setTimeout(()=>{n||t.files?.length||i(null)},250)};t.addEventListener(`change`,()=>{i(t.files?.[0]??null)},{once:!0}),t.addEventListener(`cancel`,()=>{i(null)},{once:!0}),window.addEventListener(`focus`,a,{once:!0}),t.click()})}async function Yr(e){if(!this.session||!d(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 Xr(){try{await navigator.clipboard.writeText(window.location.href),this.toastController.show(`Link copied`)}catch{this.toastController.show(`Failed to copy link`)}}var Zr={applyMarkdownToolbarAction:Gr,copyCurrentLink:Xr,closeMarkdownBlockMenu:Br,getActiveMarkdownBlockAction:jr,getMarkdownBlockMenuPopover:Nr,handleEditorImageInsert:Yr,handleMarkdownToolbarClick:Hr,handleMarkdownToolbarDocumentPointerDown:Wr,handleMarkdownToolbarKeydown:Ur,handleToolbarImageInsert:qr,isMarkdownBlockMenuOpen:Lr,openMarkdownBlockMenu:zr,positionMarkdownBlockMenu:Rr,renderMarkdownBlockMenuPopover:Pr,pickImageFile:Jr,renderMarkdownToolbar:Mr,runEditorCommand:Kr,setActiveMarkdownBlockAction:Ir,syncMarkdownToolbarBlockUi:Fr,toggleMarkdownBlockMenu:Vr},Qr={isExcalidrawFile(e){return _(e)},isBaseFile(e){return u(e)},isDrawioFile(e){return m(e)},isImageFile(e){return s(e)},isMermaidFile(e){return y(e)},isPlantUmlFile(e){return c(e)},createDiagramPreviewDocument(e,t=``){return this.workspacePreviewController.createDiagramPreviewDocument(e,t)},getPreviewSource(){let e=this.getStaticPreviewDocument?.(),t=e?.currentFilePath??e?.filePath??null;return e&&t&&t===this.currentFilePath?this.isMermaidFile(this.currentFilePath)?this.createDiagramPreviewDocument(`mermaid`,e.content):this.isPlantUmlFile(this.currentFilePath)?this.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??p(t),filePath:t,hash:e.hash??null}:null},clearStaticPreviewDocument(){this._staticPreviewDocument=null},supportsFileHistory(e){let t=p(e);return t!==null&&t!==`image`},getDisplayName(e){return l(String(e??``).split(`/`).pop())},resetPreviewMode(){this.workspacePreviewController.resetPreviewMode()},syncFileChrome(e,t={}){this.workspacePreviewController.syncFileChrome(e,t)},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)},renderExcalidrawFilePreview(e){this.workspacePreviewController.renderExcalidrawFilePreview(e)},renderDrawioFilePreview(e){this.workspacePreviewController.renderDrawioFilePreview(e)},renderImageFilePreview(e){this.workspacePreviewController.renderImageFilePreview(e)},renderBaseFilePreview(e){return this.workspacePreviewController.renderBaseFilePreview(e)},renderTextFilePreview(e){this.workspacePreviewController.renderTextFilePreview(e)},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}})},async handleHashChange(){await this.workspaceRouteController.handleHashChange()},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()},async openFile(e){await this.workspaceRouteController.openFile(e)},cleanupSession(){this.workspaceRouteController.cleanupSession()},handleWikiLinkClick(e){this.wikiLinkFileController.handleWikiLinkClick(e)},normalizeNewWikiFilePath(e){return this.wikiLinkFileController.normalizeNewWikiFilePath(e)},async createAndOpenFile(e,t){await this.wikiLinkFileController.createAndOpenFile(e,t)},handleFileSelection(e,{closeSidebarOnMobile:t=!1,revealInTree:n=!1}={}){this.workspaceRouteController.handleFileSelection(e,{closeSidebarOnMobile:t,revealInTree:n})}},$r=`__lobby__`;function ei(e){return String(e??``).replace(/\s+/g,` `).trim().slice(0,280)||null}function ti(e){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${e||`user`}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function ni(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 ri=class{constructor({preferredUserName:e,onChange:t,onChatChange:n,onWorkspaceEvent:r}){this.onChange=t,this.onChatChange=n,this.onWorkspaceEvent=r,this.wsBaseUrl=T(),this.ydoc=new I,this.chatMessages=this.ydoc.getArray(`chat-messages`),this.workspaceEvents=this.ydoc.getArray(`workspace-events`),this.provider=null,this.awareness=null,this.localUser=pe(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 ae(this.wsBaseUrl,$r,this.ydoc,{disableBc:!0,maxBackoffTime:5e3}),oe(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.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=ei(e);if(!t)return null;let n={createdAt:Date.now(),filePath:this.currentFile??null,id:ti(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=ni({action:e,createdAt:Date.now(),id:ti(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=ni(e);t&&this.seenWorkspaceEventIds.add(t.id)})}_emitWorkspaceEvents(){if(!this._didInitialSync){this._primeWorkspaceEventCache();return}this.workspaceEvents.toArray().forEach(e=>{let t=ni(e);!t||this.seenWorkspaceEventIds.has(t.id)||(this.seenWorkspaceEventIds.add(t.id),t.peerId!==this.localUser.peerId&&this.onWorkspaceEvent?.(t))})}},ii=class{constructor({NotificationImpl:e=globalThis.Notification,focusWindow:t=()=>globalThis.window?.focus?.()}={}){this.NotificationImpl=e,this.focusWindow=t}getPermission(){return typeof this.NotificationImpl==`function`?this.NotificationImpl.permission:`unsupported`}async requestPermission(){return typeof this.NotificationImpl==`function`?this.NotificationImpl.requestPermission():`unsupported`}createNotification({body:e,onClick:t,tag:n,title:r}){if(typeof this.NotificationImpl!=`function`)return null;let i=new this.NotificationImpl(r,{body:e,tag:n});return typeof t==`function`&&i.addEventListener(`click`,()=>{this.focusWindow(),t()}),i}};function ai(e,t,n){try{return e.getItem(t)??n}catch{return n}}function oi(e,t,n){try{e.setItem(t,n)}catch{}}var si=class{constructor({chatNotificationsKey:e,lineWrappingKey:t,sidebarVisibleKey:n,userNameKey:r,storage:i=globalThis.localStorage}){this.chatNotificationsKey=e,this.lineWrappingKey=t,this.sidebarVisibleKey=n,this.storage=i,this.userNameKey=r}getUserName(){return ai(this.storage,this.userNameKey,``)||``}setUserName(e){oi(this.storage,this.userNameKey,e)}getLineWrappingEnabled(){return ai(this.storage,this.lineWrappingKey,null)!==`false`}setLineWrappingEnabled(e){oi(this.storage,this.lineWrappingKey,String(e))}getSidebarVisible(){return ai(this.storage,this.sidebarVisibleKey,null)}setSidebarVisible(e){oi(this.storage,this.sidebarVisibleKey,e?`true`:`false`)}getChatNotificationsEnabled(){return ai(this.storage,this.chatNotificationsKey,null)===`true`}setChatNotificationsEnabled(e){oi(this.storage,this.chatNotificationsKey,String(e))}},ci=6e4;function li(e){return String(e?.build?.id??e?.buildId??``).trim()}var ui=class{constructor({currentBuildId:e=``,documentRef:t=globalThis.document??null,fetchImpl:n=globalThis.fetch?.bind(globalThis),intervalMs:r=ci,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)||ci),this.isChecking=!1,this.onUpdateAvailable=typeof i==`function`?i:null,this.runtimeConfig=a,this.updateDetected=!1,this.versionUrl=o||O(`/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=li(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}}},di={async readBacklinks(e,{signal:t}={}){let n=await fetch(D(`/backlinks?file=${encodeURIComponent(e)}`),{signal:t}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error||`Failed to load backlinks`);return Array.isArray(r.backlinks)?r.backlinks:[]}};function fi(e={}){let t=new URLSearchParams;return Object.entries(e).forEach(([e,n])=>{n!=null&&n!==``&&t.set(e,String(n))}),t}var pi=new class{async readStatus({force:e=!1}={}){let t=await fetch(D(`/git/status${e?`?force=true`:``}`));return C(t,`Failed to load git status`)}async readPullBackups(){let e=await fetch(D(`/git/pull-backups`));return C(e,`Failed to load pull backups`)}async readHistory({limit:e,offset:t}={}){let n=fi({limit:e,offset:t}),r=await fetch(D(`/git/history?${n.toString()}`));return C(r,`Failed to load git history`)}async readFileHistory({path:e,limit:t,offset:n}={}){let r=fi({limit:t,offset:n,path:e}),i=await fetch(D(`/git/file-history?${r.toString()}`));return C(i,`Failed to load file history`)}async readDiff({allowLargePatch:e=!1,metaOnly:t=!1,path:n=null,scope:r=`all`}={}){let i=fi({allowLargePatch:e?`true`:null,metaOnly:t?`true`:null,path:n,scope:r}),a=await fetch(D(`/git/diff?${i.toString()}`));return C(a,`Failed to load git diff`)}async readCommit({allowLargePatch:e=!1,hash:t,metaOnly:n=!1,path:r=null}={}){let i=fi({allowLargePatch:e?`true`:null,hash:t,metaOnly:n?`true`:null,path:r}),a=await fetch(D(`/git/commit?${i.toString()}`));return C(a,`Failed to load git commit`)}async readFileSnapshot({hash:e,path:t}={}){let n=fi({hash:e,path:t}),r=await fetch(D(`/git/file-snapshot?${n.toString()}`));return C(r,`Failed to load historical file preview`)}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(D(e),{body:JSON.stringify(t),headers:S(r,{"Content-Type":`application/json`}),method:`POST`});return C(i,n)}},mi={async renderSvg(e){let t=await fetch(D(`/plantuml/render`),{body:JSON.stringify({source:e}),headers:{"Content-Type":`application/json`},method:`POST`}),n=await t.json().catch(()=>null);if(!t.ok||!n?.ok||typeof n.svg!=`string`)throw Error(n?.error||`Failed to render PlantUML`);return n.svg}},hi=`collabmd-active-tab-lock`,gi=`collabmd-tab-id`,_i=`collabmd-tab-lock`,vi=4e3;function yi(){return Date.now()}function bi(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`tab-${yi()}-${Math.random().toString(36).slice(2,10)}`}function xi(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}var Si=class{constructor({heartbeatIntervalMs:e=vi,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(_i),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(hi),this.channel?.postMessage({type:`released`,tabId:this.tabId})),this.isOwner=!1,this.stopHeartbeat()}getOrCreateTabId(){try{let e=window.sessionStorage.getItem(gi);if(e)return e;let t=bi();return window.sessionStorage.setItem(gi,t),t}catch{return bi()}}readLock(){try{return xi(window.localStorage.getItem(hi))}catch{return null}}isFreshLock(e){return!!(e&&typeof e.tabId==`string`&&Number.isFinite(e.updatedAt)&&yi()-e.updatedAt<this.staleAfterMs)}writeLock(){try{window.localStorage.setItem(hi,JSON.stringify({tabId:this.tabId,updatedAt:yi()}))}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!==hi)return;let t=xi(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()}},Ci=`__workspace__`;function wi(e=``){return String(e??``).trim().replace(/\\/g,`/`).split(`/`).filter(Boolean).join(`/`)}function Ti(e=``){let t=wi(e);if(!t)return``;let n=t.lastIndexOf(`/`);return n>=0?t.slice(0,n):``}function Ei(e={}){return Ti(e?.path??``)}function Di(e){return!e?.path||!e?.type?null:e.nodeType===`directory`||e.type===`directory`?{children:[],name:e.name,path:e.path,type:`directory`}:{name:e.name,path:e.path,type:e.type}}function Oi(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)&&Oi(e.children)}),e}function ki(e){return e instanceof Map?e:new Map(Object.entries(e??{}))}function Ai(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 ji=class{constructor(){this.entriesByPath=new Map,this.nodesByPath=new Map,this.nodeParentPathByPath=new Map,this.roots=[]}reset(e){return this.entriesByPath=ki(e),this.nodesByPath=new Map,this.nodeParentPathByPath=new Map,this.roots=[],this.entriesByPath.forEach(e=>{let t=Di(e);t&&this.nodesByPath.set(e.path,t)}),Ai(Array.from(this.nodesByPath.keys())).forEach(e=>{let t=this.nodesByPath.get(e);t&&this.attachNode(e,t,Ei(this.entriesByPath.get(e)))}),Oi(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)}),Ai(n,`desc`).forEach(e=>{this.removeEntry(e)}),Ai(r).forEach(e=>{this.upsertEntry(e,t.get(e))}),Oi(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=Di(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,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,Ei(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(Ei(t)!==e)return;let r=this.nodesByPath.get(n);r&&this.attachNode(n,r,e)})}},Mi=class{constructor({onTreeChange:e=()=>{},onWorkspaceEvent:t=()=>{}}={}){this.onTreeChange=e,this.onWorkspaceEvent=t,this.ydoc=new I,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 ji,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=Vt(e);!t||this.seenEventIds.has(t.id)||(this.seenEventIds.add(t.id),this.onWorkspaceEvent(t))})}}connect(){this.provider||(this._didInitialSync=!1,this.provider=new ae(T(),Ci,this.ydoc,{disableBc:!0,maxBackoffTime:5e3}),oe(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=Vt(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()}},Ni=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=l(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=`
129
- <svg class="backlink-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
130
- <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
131
- <polyline points="14 2 14 8 20 8"/>
132
- </svg>
133
- <span>${b(t)}</span>
134
- ${n?`<span class="backlink-dir">${b(n)}</span>`:``}
135
- `,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 Y(e){return Array.isArray(e)?e:[]}function Pi(e={}){let t=Number(e.startLine||0),n=Number(e.endLine||t);return!Number.isFinite(t)||t<=0?`No source anchor`:t===n?`Line ${t}`:`Lines ${t}-${n}`}function Fi({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 Ii=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(Y(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??{})}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={}){this.errorMessage=``,this.overview={files:Y(e.files),generatedAt:Number(e.generatedAt||0),totalThreadCount:Number(e.totalThreadCount||0)},this.onOverviewChange?.(this.overview,{threadCounts:this.getThreadCounts()}),this.render()}render(){if(!this.panel)return;if(this.panel.replaceChildren(),this.errorMessage){let e=Fi({copy:this.errorMessage,title:`Comments unavailable`,tone:`error`});e.setAttribute(`role`,`alert`),this.panel.appendChild(e);return}if(this.loading&&Y(this.overview.files).length===0){let e=Fi({copy:`Checking the vault for active threads…`,title:`Loading comments`});e.setAttribute(`role`,`status`),this.panel.appendChild(e);return}let e=Y(this.overview.files);if(e.length===0){let e=Fi({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=l(L(e.filePath));let a=document.createElement(`span`);a.className=`comment-overview-file-path`,a.textContent=z(e.filePath)||e.filePath;let o=document.createElement(`span`);return o.className=`comment-overview-file-count`,o.textContent=String(e.threadCount||Y(e.threads).length),r.append(i,a),n.append(r,o),t.appendChild(n),Y(e.threads).forEach(n=>{t.appendChild(this.createThreadButton(e.filePath,n))}),t}createThreadButton(e,t){let n=document.createElement(`button`);n.type=`button`,n.className=`comment-overview-thread`,n.addEventListener(`click`,()=>{this.onThreadSelect?.({anchor:t.anchor,filePath:e,threadId:t.id})});let r=document.createElement(`div`);r.className=`comment-overview-thread-header`;let i=document.createElement(`span`);i.className=`comment-overview-thread-line`,i.textContent=Pi(t.anchor);let a=document.createElement(`span`);a.className=`comment-overview-thread-meta`,a.textContent=this.formatTimestamp(t.latestActivityAt),r.append(i,a);let o=document.createElement(`div`);o.className=`comment-overview-thread-body`;let s=document.createElement(`span`);s.className=`comment-overview-thread-quote`,s.textContent=t.anchor?.quote||`Source anchored comment`;let c=document.createElement(`p`);c.className=`comment-overview-thread-preview`,c.textContent=t.latestMessage?.bodyPreview||``,o.append(c,s);let l=document.createElement(`div`);l.className=`comment-overview-thread-footer`;let u=document.createElement(`span`);u.className=`comment-overview-thread-author`,u.textContent=t.latestMessage?.userName||t.createdByName||`Anonymous`;let d=document.createElement(`span`);d.className=`comment-overview-thread-message-count`;let f=Number(t.messageCount||0);return d.textContent=`${f} message${f===1?``:`s`}`,l.append(u,d),n.append(r,o,l),n}formatTimestamp(e){if(!Number.isFinite(e))return``;try{return this.timeFormatter.format(new Date(e))}catch{return``}}};function Li(e,t,n,r,i,a){return e?.(t,n,r,i,a)??a.renderToken(t,n,r)}function Ri(e=``){return`<p>${b(String(e??``)).replace(/\n/g,`<br>`)}</p>`}function zi(){let e=i({breaks:!0,highlight(e,n){try{return n&&t.getLanguage(n)?t.highlight(e,{ignoreIllegals:!0,language:n}).value:t.highlightAuto(e).value}catch{return b(e)}},html:!1,linkify:!0,typographer:!0}),n=e.renderer.rules.link_open,r=e.renderer.rules.table_open,a=e.renderer.rules.table_close;return e.renderer.rules.link_open=(e,t,r,i,a)=>(e[t].attrSet(`target`,`_blank`),e[t].attrSet(`rel`,`noopener noreferrer`),Li(n,e,t,r,i,a)),e.renderer.rules.table_open=(e,t,n,i,a)=>`<div class="comment-markdown-table">${Li(r,e,t,n,i,a)}`,e.renderer.rules.table_close=(e,t,n,r,i)=>`${Li(a,e,t,n,r,i)}</div>`,e}var Bi=zi();function Vi(e=``){let t=String(e??``);try{return Bi.render(t)}catch{return Ri(t)}}var Hi=Object.freeze([`👍`,`❤️`,`🎉`,`👀`,`🚀`]),Ui=Object.freeze([`😂`,`🔥`,`✅`,`🙏`,`💡`,`🤔`,`👏`,`😄`,`🎯`,`🙌`]);function Wi(e=[]){return[...e].sort((e,t)=>(e.anchor?.startLine??0)-(t.anchor?.startLine??0)||e.createdAt-t.createdAt)}function Gi(e){return e?.anchorKind||e?.kind||`line`}function Ki(e){return Gi(e)===`text`&&Number.isFinite(e?.startIndex)&&Number.isFinite(e?.endIndex)&&e.endIndex>e.startIndex}function qi(e,t){return e===t?!0:!e||!t?!1:Gi(e)===Gi(t)&&(e.startIndex??null)===(t.startIndex??null)&&(e.endIndex??null)===(t.endIndex??null)&&(e.startLine??null)===(t.startLine??null)&&(e.endLine??null)===(t.endLine??null)&&(e.anchorQuote??e.quote??``)===(t.anchorQuote??t.quote??``)}function Ji(e){return e?((e.kind||e.anchorKind)===`text`&&e.quote,e.startLine===e.endLine?`Line ${e.startLine}`:`Lines ${e.startLine}-${e.endLine}`):`No source anchor`}function Yi(e={}){return[e.kind||e.anchorKind||`line`,e.startLine??0,e.endLine??0,e.quote||``].join(`::`)}function Xi(e){return e&&!e.querySelector(`[data-source-line]`)}function Zi(e){let t=Number.parseInt(e||``,10);return Number.isFinite(t)?t:null}function Qi(e=[]){return e.reduce((e,t)=>e?(t?.createdAt??0)>=(e?.createdAt??0)?t:e:t,null)}function $i(e){return e?.threads?.reduce((e,t)=>{let n=Qi(t?.messages??[]);return n&&(n.createdAt??0)>=(e?.createdAt??0)?n:e},null)}function ea(e,t=`comment-markdown`){let n=document.createElement(`div`);return n.className=t,n.innerHTML=Vi(e),n}function ta(e,t){return!!(t&&e?.users?.some(e=>e?.userId===t))}function na(e){return String(Array.isArray(e?.users)?e.users.length:0)}function ra(e,t,n){return e?.threadId===t&&e?.messageId===n}function ia(e){let t=e?.querySelector?.(`.comment-reaction-picker`),n=t?.closest?.(`.comment-reaction-picker-wrap`),r=e?.querySelector?.(`.comment-card-scroll`);return!(t instanceof HTMLElement)||!(n instanceof HTMLElement)||!(r instanceof HTMLElement)?null:{picker:t,scroll:r,wrap:n}}function aa(e,t){let n=Zi(e?.getAttribute?.(`data-source-line`)),r=Zi(e?.getAttribute?.(`data-source-line-end`))??n;return!n||!r||!t?!1:t.startLine<=r&&t.endLine>=n}function oa(e,t,n=``){if(!e||e.isCollapsed||e.rangeCount===0||!t?.contains(e.anchorNode)||!t.contains(e.focusNode))return null;let r=e.getRangeAt(0),i=String(e.toString()).trim(),a=Te(i),o=r.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?r.commonAncestorContainer:r.commonAncestorContainer.parentElement;if(!a||o?.closest?.(`.diagram-preview-shell`))return null;let s=Array.from(t.querySelectorAll(`[data-source-line]`)).filter(e=>Xi(e)&&r.intersectsNode(e));if(s.length===0)return null;let c=String(n).split(`
136
- `),l=Math.min(Math.max(Math.min(...s.map(e=>Zi(e.getAttribute(`data-source-line`))??c.length)),1),c.length),u=Math.min(Math.max(...s.map(e=>Zi(e.getAttribute(`data-source-line-end`))??Zi(e.getAttribute(`data-source-line`))??1)),c.length),d=c.slice(0,l-1).reduce((e,t)=>e+t.length+1,0),f=c.slice(l-1,u).reduce((e,t,n)=>e+t.length+(n===0?0:1),d),p=`line`,m=d,h=f,g=!0;if(s.length===1){let e=String(n).slice(d,f),t=e.indexOf(i);t>=0&&t===e.lastIndexOf(i)&&(p=`text`,m=d+t,h=m+i.length,g=!1)}let _=e=>String(n).slice(0,e).split(`
137
- `).length,v=g?l:_(m),y=g?u:_(Math.max(h-1,m)),b=ua(Array.from(r.getClientRects()))||ua(s.map(e=>e.getBoundingClientRect()));return{anchor:{anchorKind:p,anchorQuote:a,endIndex:h,endLine:y,fallbackToLines:g,kind:p,quote:a,startIndex:m,startLine:v},range:r.cloneRange(),rect:b}}function sa(e){let t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=``,r=[],i=!0;for(;t.nextNode();){let e=t.currentNode,a=e.textContent||``;for(let t=0;t<a.length;t+=1){let o=a[t];if(/\s/.test(o)){if(i)continue;n+=` `,r.push({node:e,offset:t}),i=!0;continue}n+=o,r.push({node:e,offset:t}),i=!1}}for(;n.endsWith(` `);)n=n.slice(0,-1),r.pop();return{map:r,normalized:n}}function ca(e,t){let n=Ee(t);if(!e||!n)return null;let r=sa(e);if(!r.normalized)return null;let i=r.normalized.indexOf(n);if(i<0||r.normalized.indexOf(n,i+1)>=0)return null;let a=r.map[i],o=r.map[i+n.length-1];if(!a||!o)return null;let s=document.createRange();return s.setStart(a.node,a.offset),s.setEnd(o.node,o.offset+1),s}function la(e,t){return{bottom:e.bottom-t.top,height:e.height,left:e.left-t.left,right:e.right-t.left,top:e.top-t.top,width:e.width}}function ua(e=[]){if(!Array.isArray(e)||e.length===0)return null;let t=Math.min(...e.map(e=>e.left)),n=Math.min(...e.map(e=>e.top)),r=Math.max(...e.map(e=>e.right)),i=Math.max(...e.map(e=>e.bottom));return{bottom:i,height:i-n,left:t,right:r,top:n,width:r-t}}function da(e,t,n){return n?e>=n.left&&e<=n.right&&t>=n.top&&t<=n.bottom:!1}function fa(e=[]){return[...new Set(e.filter(Boolean))].sort()}function pa(e=[]){return fa(e).join(` `)}function ma(e){let t=document.createDocumentFragment(),n=document.createElement(`span`);if(n.className=`comment-marker-icon`,n.setAttribute(`aria-hidden`,`true`),n.innerHTML=`
138
- <svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
139
- <path d="M3 4.75A1.75 1.75 0 0 1 4.75 3h6.5A1.75 1.75 0 0 1 13 4.75v4.5A1.75 1.75 0 0 1 11.25 11H8.9L6.5 13v-2H4.75A1.75 1.75 0 0 1 3 9.25v-4.5Z" stroke="currentColor" stroke-width="1.35" stroke-linejoin="round"/>
140
- </svg>
141
- `,t.appendChild(n),e>1){let n=document.createElement(`span`);n.className=`comment-marker-count`,n.textContent=String(e),t.appendChild(n)}return t}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 ga(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 _a(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 va(){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 ya(){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`?ua(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 ba(e){return e instanceof HTMLTextAreaElement?{selectionDirection:e.selectionDirection??`none`,selectionEnd:e.selectionEnd,selectionStart:e.selectionStart,value:e.value}:null}function xa(){if(!this.activeCard)return;let e=this.cardRoot?.querySelector(`.comment-card-input`),t=ba(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 Sa(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 Ca(){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=Ji(this.activeCard.anchor),r.append(i,a);let o=document.createElement(`button`);o.type=`button`,o.className=q({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 ${Ji(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 wa(e){let t=ia(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 Ta(){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 Ea(){let e=document.createElement(`form`);e.className=`comment-card-form`;let t=document.createElement(`textarea`);t.className=ke({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=q({variant:`secondary`}),r.textContent=`Cancel`,r.addEventListener(`click`,()=>this.closeCard());let i=document.createElement(`button`);return i.type=`submit`,i.className=q({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=Sa(t,this.activeCard?.composerDraft),e}function Da(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=q({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-thread-card-action`]}),r.textContent=`Jump`,r.addEventListener(`click`,()=>this.onNavigateToLine?.(e.anchor?.startLine??1));let i=document.createElement(`button`);i.type=`button`,i.className=q({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-thread-card-action`]});let a=this.activeCard?.replyThreadId===e.id;i.classList.toggle(`is-active`,a),i.textContent=`Reply`,i.setAttribute(`aria-pressed`,String(a)),i.setAttribute(`aria-label`,a?`Cancel reply`:`Reply to thread`),i.title=a?`Cancel reply`:`Reply to thread`,i.addEventListener(`click`,()=>{a&&this.activeCard?.replyDrafts?.[e.id]&&delete this.activeCard.replyDrafts[e.id],this.activeCard={...this.activeCard,replyThreadId:a?null:e.id},this.renderCard()});let o=document.createElement(`button`);return o.type=`button`,o.className=q({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-thread-card-action`,`is-danger`]}),o.textContent=`Resolve`,o.addEventListener(`click`,async()=>{await this.onResolveThread?.(e.id)}),n.append(r,i,o),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 Oa(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=ea(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 ka(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`,ta(r,n)),i.setAttribute(`aria-pressed`,String(ta(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=na(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`,Hi.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(ra(this.reactionPicker,e.id,t.id))),c.textContent=`More`,c.addEventListener(`click`,()=>{let n=ra(this.reactionPicker,e.id,t.id);this.reactionPicker=n?null:{messageId:t.id,threadId:e.id},this.renderCard()}),s.appendChild(c),ra(this.reactionPicker,e.id,t.id)&&s.appendChild(this.createReactionPicker(e,t)),o.appendChild(s),r.append(a,o),r}function Aa(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 ja(e,t){let n=document.createElement(`div`);n.className=`comment-reaction-picker`;let r=document.createElement(`div`);return r.className=`comment-reaction-picker-grid`,Ui.forEach(n=>{r.appendChild(this.createReactionPickerButton(e,t,n))}),n.appendChild(r),n}function Ma(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 Na(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=ke({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=q({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=q({variant:`primary`}),o.textContent=`Reply`,i.append(a,o),t.append(r,i),this.pendingCardFocusElement=Sa(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 Pa(e){let t=this.updateCardSourceRect(),n=window.innerWidth,r=window.innerHeight,i=e.getBoundingClientRect(),a=x((n-i.width)/2,16,n-i.width-16),o=x((r-i.height)/4,16,r-i.height-16),s=a,c=o;t&&(s=x(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 Fa(){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 Ia={captureActiveCardDraft:xa,closeCard:va,createComposer:Ea,createPendingFocusTarget:Sa,createMessageElement:Oa,createQuickReactionButton:Aa,createReactionBar:ka,createReactionPicker:ja,createReactionPickerButton:Ma,createReplyComposer:Na,createTextareaDraft:ba,createThreadElement:Da,ensureCardRoot:ha,flushPendingCardFocus:Fa,openComposerForSelection:ga,openThreadGroup:_a,positionCard:Pa,renderCard:Ca,repositionActiveCard:Ta,updateCardSourceRect:ya,updateReactionPickerPosition:wa};function La(){this.renderEditorLayer(),this.renderPreviewLayer(),this.repositionActiveCard()}function Ra(e=0){if(!this.previewElement)return!1;let t=this.supported&&e>0,n=0,r=0;if(t){let t=getComputedStyle(this.previewElement),i=Number.parseFloat(t.getPropertyValue(`--preview-comment-rail-reserved`))||0,a=Number.parseFloat(t.paddingRight)||0,o=Number.parseFloat(t.getPropertyValue(`--preview-comment-rail-inset`))||0,s=Math.max(a-i,0),c=Math.max(e+o-s,0),l=this.previewContainer?.getBoundingClientRect(),u=this.previewElement.getBoundingClientRect(),d=l?Math.max(l.right-u.right,0):0;r=Math.min(d,c),n=Math.max(c-r,0)}let i=`${Math.ceil(n)}px`,a=`${Math.floor(r)}px`,o=this.previewElement.style.getPropertyValue(`--preview-comment-rail-reserved`)!==i||this.previewElement.style.getPropertyValue(`--preview-comment-rail-offset`)!==a;return o&&(this.previewElement.style.setProperty(`--preview-comment-rail-reserved`,i),this.previewElement.style.setProperty(`--preview-comment-rail-offset`,a)),o}function za(){this.layoutFrame||=requestAnimationFrame(()=>{this.layoutFrame=0,this.refreshLayout()})}function Ba(){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 Va(){let e=this.ensureEditorLayer();if(e.replaceChildren(),!this.supported||!this.session)return;let t=this.editorContainer?.getBoundingClientRect?.();if(!t)return;let n=this.getThreadGroups(),r=[];if(n.forEach(n=>{let i=this.session.getCommentAnchorClientRect?.(n.anchor);if(!i)return;let a=la(i,t);if(a.bottom<0||a.top>t.height)return;let o=document.createElement(`button`);o.type=`button`,o.className=`ui-state-marker ui-state-marker--comment comment-editor-badge`,o.dataset.count=String(n.threads.length);let s=this.activeCard?.groupKey===n.key,c=this.hoveredEditorGroupKeys.includes(n.key);o.classList.toggle(`is-active`,s),o.classList.toggle(`is-hovered`,c),o.classList.toggle(`is-passive`,!s&&!c),o.setAttribute(`aria-label`,`${n.threads.length} comment thread${n.threads.length===1?``:`s`}`),o.appendChild(ma(n.threads.length));let l=Math.max(a.top,8);o.style.top=`${l}px`,o.style.left=`${Math.max(t.width-36,8)}px`,o.title=`${n.threads.length} comment${n.threads.length===1?``:`s`}`,o.addEventListener(`pointerdown`,e=>{e.preventDefault()}),o.addEventListener(`pointerenter`,()=>{this.updateHoveredEditorGroups([n.key])}),o.addEventListener(`pointerleave`,()=>{this.updateHoveredEditorGroups([])}),o.addEventListener(`focusin`,()=>{this.updateHoveredEditorGroups([n.key])}),o.addEventListener(`focusout`,()=>{this.updateHoveredEditorGroups([])}),o.addEventListener(`click`,()=>{this.openThreadGroup(n,{anchor:n.anchor,origin:`editor`,sourceRect:i})}),e.appendChild(o),r.push(l)}),!this.committedSelectionAnchor||this.activeCard?.mode===`create`)return;let i=this.session.getCommentAnchorClientRect?.(this.committedSelectionAnchor),a=this.session.getSelectionChipClientRect?.(this.committedSelectionAnchor)??i;if(!a)return;let o=la(a,t);if(o.bottom<0||o.top>t.height)return;let s=x(o.top,8,Math.max(t.height-36,8));for(;r.some(e=>Math.abs(e-s)<32);)s=x(s+36,8,Math.max(t.height-36,8));let c=document.createElement(`button`);c.type=`button`,c.className=`ui-selection-pill ui-selection-pill--comment comment-selection-chip`,c.textContent=`Comment`,c.style.top=`${s}px`,c.style.right=`12px`,c.addEventListener(`pointerdown`,e=>{e.preventDefault(),e.stopPropagation(),this.openComposerForSelection(`editor`,c.getBoundingClientRect())}),e.appendChild(c)}function Ha(){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 Ua(){if(this.ensurePreviewLayer(),this.previewLayer?.replaceChildren(),this.previewHighlightLayer?.replaceChildren(),!this.supported||!this.previewElement){this.previewHoverRegions=[],this.syncPreviewRailLayout(0);return}let e=this.previewElement.getBoundingClientRect();if(this.activeCard?.mode===`create`&&this.activeCard.origin===`preview`){let t=Array.from(this.activeCard.previewRange?.getClientRects?.()??[]);(t.length>0?t:[this.resolvePreviewTarget(this.activeCard.anchor)?.bubbleRect].filter(Boolean)).forEach(t=>{let n=document.createElement(`div`);n.className=`comment-preview-highlight is-active`,n.style.left=`${t.left-e.left}px`,n.style.top=`${t.top-e.top}px`,n.style.width=`${t.width}px`,n.style.height=`${t.height}px`,this.previewHighlightLayer?.appendChild(n)})}let t=this.getThreadGroups(),n=[],r=[],i=this.shouldRenderPassivePreviewMarkers(),a=[];if(t.forEach(t=>{let o=this.resolvePreviewTarget(t.anchor);if(!o?.bubbleRect)return;r.push({key:t.key,rects:o.hoverRects?.length>0?o.hoverRects:[o.bubbleRect]});let s=this.activeCard?.groupKey===t.key,c=this.hoveredPreviewGroupKeys.includes(t.key),l=s||c;if(o.highlightRects?.forEach(t=>{let n=document.createElement(`div`);n.className=`comment-preview-highlight`,n.classList.toggle(`is-active`,s),n.classList.toggle(`is-hovered`,c),n.classList.toggle(`is-passive`,!l),n.style.left=`${t.left-e.left}px`,n.style.top=`${t.top-e.top}px`,n.style.width=`${t.width}px`,n.style.height=`${t.height}px`,this.previewHighlightLayer?.appendChild(n)}),!i&&!l)return;let u=document.createElement(`button`);u.type=`button`,u.className=`ui-state-marker ui-state-marker--comment comment-preview-badge`,u.dataset.commentPreviewGroupKeys=t.key,u.classList.toggle(`is-active`,s),u.classList.toggle(`is-hovered`,c),u.classList.toggle(`is-passive`,!l),u.setAttribute(`aria-label`,`${t.threads.length} comment thread${t.threads.length===1?``:`s`}`),u.appendChild(ma(t.threads.length));let d=x(o.bubbleRect.top-e.top,6,Math.max(this.previewElement.clientHeight-30,6));for(;n.some(e=>Math.abs(e-d)<26);)d=x(d+30,6,Math.max(this.previewElement.clientHeight-30,6));u.style.top=`${d}px`,u.title=`${t.threads.length} comment${t.threads.length===1?``:`s`}`,u.addEventListener(`pointerdown`,e=>{e.preventDefault()}),u.addEventListener(`click`,()=>{this.openThreadGroup(t,{anchor:t.anchor,origin:`preview`,sourceRect:u.getBoundingClientRect()})}),this.previewLayer?.appendChild(u),n.push(d),a.push(u)}),this.previewSelection&&this.activeCard?.mode!==`create`){let t=this.previewSelection,n=ua(Array.from(t.range?.getClientRects?.()??[]))||t.rect;if(n){let r=document.createElement(`button`);r.type=`button`,r.className=`ui-chip-button ui-chip-button--comment comment-preview-selection-chip`,r.textContent=`Comment`,r.setAttribute(`aria-label`,`Comment on selected preview text`),r.style.left=`${x(n.left-e.left,8,Math.max(this.previewElement.clientWidth-88,8))}px`,r.style.top=`${x(n.bottom-e.top+8,8,Math.max(this.previewElement.clientHeight-36,8))}px`,r.addEventListener(`pointerdown`,e=>{e.preventDefault(),e.stopPropagation()}),r.addEventListener(`click`,()=>{this.openComposerForSelection(`preview`,r.getBoundingClientRect(),t)}),this.previewLayer?.appendChild(r)}}this.previewHoverRegions=r;let o=a.reduce((e,t)=>Math.max(e,t.offsetWidth||28),0);this.syncPreviewRailLayout(o)&&this.scheduleLayoutRefresh(),this.lastPreviewPointerPosition&&this.updateHoveredPreviewGroups(this.getPreviewGroupKeysAtPoint(this.lastPreviewPointerPosition.x,this.lastPreviewPointerPosition.y))}function Wa(){this.previewSelection=null,window.getSelection()?.removeAllRanges(),this.scheduleLayoutRefresh()}function Ga(e){if(!this.previewElement||!e)return null;let t=Array.from(this.previewElement.querySelectorAll(`.mermaid-shell, .plantuml-shell`)).find(t=>aa(t,e));if(t)return{bubbleRect:t.getBoundingClientRect(),highlightRects:[],hoverRects:[t.getBoundingClientRect()]};let n=Array.from(this.previewElement.querySelectorAll(`[data-source-line]`)).filter(t=>Xi(t)&&aa(t,e));if(e.kind===`text`&&e.quote){let t=n.map(t=>({element:t,range:ca(t,e.quote)})).filter(e=>e.range);if(t.length===1){let e=Array.from(t[0].range.getClientRects());return{bubbleRect:ua(e)||t[0].element.getBoundingClientRect(),highlightRects:e,hoverRects:e}}}let r=n[0];return r?{bubbleRect:r.getBoundingClientRect(),highlightRects:[],hoverRects:[r.getBoundingClientRect()]}:null}function Ka(e){if(!(e instanceof Node))return[];let t=e.closest?.(`[data-comment-preview-group-keys]`);return pa(String(t?.dataset?.commentPreviewGroupKeys??``).split(/\s+/).filter(Boolean)).split(` `).filter(Boolean)}function qa(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))return[];let n=document.elementFromPoint(e,t),r=this.getPreviewGroupKeysForTarget(n);return r.length>0?r:fa(this.previewHoverRegions.filter(n=>n.rects.some(n=>da(e,t,n))).map(e=>e.key))}function Ja(e=[]){let t=fa(e),n=t.join(` `);n!==this.hoveredPreviewGroupKeysSignature&&(this.hoveredPreviewGroupKeys=t,this.hoveredPreviewGroupKeysSignature=n,this.scheduleLayoutRefresh())}function Ya(e=[]){let t=fa(e),n=t.join(` `);n!==this.hoveredEditorGroupKeysSignature&&(this.hoveredEditorGroupKeys=t,this.hoveredEditorGroupKeysSignature=n,this.scheduleLayoutRefresh())}function Xa(e){this.updateHoveredPreviewGroups(this.getPreviewGroupKeysForTarget(e))}function Za(){let e=this.previewContainer?.clientWidth??this.previewElement?.clientWidth??0;return window.innerWidth>=769&&e>=400}var Qa={clearPreviewSelection:Wa,ensureEditorLayer:Ba,ensurePreviewLayer:Ha,getPreviewGroupKeysAtPoint:qa,getPreviewGroupKeysForTarget:Ka,refreshLayout:La,renderEditorLayer:Va,renderPreviewLayer:Ua,resolvePreviewTarget:Ga,scheduleLayoutRefresh:za,shouldRenderPassivePreviewMarkers:Za,syncHoveredPreviewGroupsFromTarget:Xa,syncPreviewRailLayout:Ra,updateHoveredEditorGroups:Ya,updateHoveredPreviewGroups:Ja};function $a(){this.renderToolbar(),this.renderDrawer(),this.renderCard(),this.scheduleLayoutRefresh()}function eo(){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 to(){if(!this.commentsDrawer||!this.commentsDrawerList)return;this.commentsDrawer.classList.toggle(`hidden`,!this.supported||!this.drawerOpen),this.commentsDrawerList.replaceChildren();let e=this.getThreadGroups();if(this.commentsDrawerEmpty?.classList.toggle(`hidden`,e.length>0),!this.supported||e.length===0)return;let t=document.createDocumentFragment();e.forEach(e=>{let n=document.createElement(`button`);n.type=`button`,n.className=`ui-record-surface comments-drawer-item`,n.classList.toggle(`is-active`,this.activeCard?.groupKey===e.key),n.addEventListener(`pointerdown`,e=>{e.preventDefault()}),n.addEventListener(`click`,()=>{this.onNavigateToLine?.(e.anchor?.startLine??1),this.openThreadGroup(e,{anchor:e.anchor,origin:`drawer`,sourceRect:n.getBoundingClientRect()})});let r=document.createElement(`div`);r.className=`ui-record-header comments-drawer-item-header`;let i=document.createElement(`span`);i.className=`comments-drawer-item-title`,i.textContent=Ji(e.anchor);let a=document.createElement(`span`);a.className=`ui-pill-badge ui-pill-badge--count ui-pill-badge--accent comments-drawer-item-count`,a.textContent=String(e.threads.length),r.append(i,a);let o=document.createElement(`p`);o.className=`comments-drawer-item-quote`,o.textContent=e.anchor.quote||e.anchor.excerpt||`Source anchored comment`;let s=$i(e),c=ea(s?.body||``,`comment-markdown comments-drawer-item-preview`),l=document.createElement(`div`);l.className=`ui-record-meta comments-drawer-item-footer`;let u=document.createElement(`span`);u.textContent=`${e.threads.length} thread${e.threads.length===1?``:`s`}`;let d=document.createElement(`span`);d.className=`comments-drawer-item-updated`,d.textContent=s?`${s.userName} • ${this.formatTimestamp(s.createdAt)}`:``,l.append(u,d),n.append(r,o,c,l),t.appendChild(n)}),this.commentsDrawerList.appendChild(t)}function no(e){if(!Number.isFinite(e))return``;try{return this.timeFormatter.format(new Date(e))}catch{return``}}var ro={formatTimestamp:no,render:$a,renderDrawer:to,renderToolbar:eo};function io(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 ao(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 oo(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(!Ki(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(qi(this.committedSelectionAnchor,this.selectionAnchor)){this.renderToolbar(),this.scheduleLayoutRefresh();return}this.scheduleSelectionReveal(this.selectionAnchor),this.renderToolbar(),this.scheduleLayoutRefresh()}function so(){this.activeCard?.mode!==`create`&&(this.clearSelectionRevealTimer(),this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.scheduleLayoutRefresh())}function co(e=[]){this.threads=Wi(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 lo(e){let t=!!e;t!==this.drawerOpen&&(t&&this.onWillOpenDrawer?.(),this.drawerOpen=t,this.render())}function uo(){this.setDrawerOpen(!1)}function fo(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 po(){let e=new Map;return this.threads.forEach(t=>{let n=Yi(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 mo(){this.selectionRevealTimer&&=(clearTimeout(this.selectionRevealTimer),0)}function ho(e){this.clearSelectionRevealTimer(),this.selectionRevealTimer=window.setTimeout(()=>{this.selectionRevealTimer=0,!(this.pointerSelecting||this.activeCard?.mode===`create`||!qi(this.pendingSelectionAnchor,e))&&(this.committedSelectionAnchor=e,this.scheduleLayoutRefresh())},150)}var go={attachSession:io,clearSelectionRevealTimer:mo,closeDrawer:uo,getThreadGroups:po,handleEditorContentChange:so,openThreadFromOverview:fo,scheduleSelectionReveal:ho,setCurrentFile:ao,setDrawerOpen:lo,setSelectionAnchor:oo,setThreads:co},_o=class{constructor({commentSelectionButton:e,commentsDrawer:t,commentsDrawerEmpty:n,commentsDrawerList:r,commentsToggleButton:i,editorContainer:a,onWillOpenDrawer:o,onCreateThread:s,onNavigateToLine:c,onReplyToThread:l,onToggleReaction:u,onResolveThread:d,previewContainer:f,previewElement:p}){this.commentSelectionButton=e,this.commentsDrawer=t,this.commentsDrawerEmpty=n,this.commentsDrawerList=r,this.commentsToggleButton=i,this.editorContainer=a,this.onWillOpenDrawer=o,this.onCreateThread=s,this.onNavigateToLine=c,this.onReplyToThread=l,this.onToggleReaction=u,this.onResolveThread=d,this.previewContainer=f,this.previewElement=p,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=()=>{(this.activeCard?.mode!==`create`||this.activeCard.origin!==`preview`)&&(this.previewSelection=this.supported&&this.fileKind===`markdown`?oa(window.getSelection(),this.previewElement,this.session?.getText?.()??``):null,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=Ki(e)?e:null,this.clearSelectionRevealTimer(),this.committedSelectionAnchor=Ki(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(_o.prototype,go,ro,Qa,Ia);function vo(){return typeof window>`u`||typeof window.matchMedia!=`function`?{matches:!1}:window.matchMedia(`(max-width: 768px)`)}function yo(e){return typeof HTMLElement>`u`||!(e instanceof HTMLElement)?[]:Array.from(e.querySelectorAll(`.create-menu-item`))}var bo=class{constructor({mobileBreakpointQuery:e=vo()}={}){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,yo(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=q({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?q({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=yo(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 xo(e,t,n){return e===t?n:`${n}${e.slice(t.length)}`}function So(e,t,n){return`${e} ${e===1?t:n}`}function Co(){return JSON.stringify({type:`excalidraw`,version:2,source:`collabmd`,elements:[],appState:{viewBackgroundColor:`#ffffff`,gridSize:null},files:{}})}function X(e,t){return t?{...e,requestId:t}:e}var wo=class{constructor({mobileBreakpointQuery:e=typeof window<`u`&&typeof window.matchMedia==`function`?window.matchMedia(`(max-width: 768px)`):{matches:!1},onFileDelete:t,onFileSelect:n,pendingWorkspaceRequestIds:r=null,state:i,toastController:a,vaultClient:o,view:s,refresh:c}){this.onFileDelete=t,this.onFileSelect=n,this.pendingWorkspaceRequestIds=r,this.state=i,this.toastController=a,this.vaultClient=o,this.view=s,this.refresh=c,this.createButton=document.getElementById(`sidebarCreateBtn`),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 bo({mobileBreakpointQuery:e}),this.pendingAction=null,this.actionBusy=!1}initialize(){this.createButton?.addEventListener(`click`,()=>{this.openRootCreateMenu({anchor:this.createButton})}),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:`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 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`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`: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.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=q({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 createVaultFile(e,t,{openAfterCreate:n=!1,errorMessage:r=`Failed to create file`}={}){try{return await this.runWorkspaceMutation(n=>this.vaultClient.createFile(X({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=V(e);if(!t)return this.showToast(`Folder path is required`),!1;try{return await this.runWorkspaceMutation(e=>this.vaultClient.createDirectory(t,X({},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=V(t);if(!r)return this.showToast(`File path is required`),!1;let i=v(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(!L(a))return this.showToast(`File path is required`),!1;if(a===e)return!0;try{return await this.runWorkspaceMutation(t=>this.vaultClient.renameFile(X({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=V(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(X({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=xo(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,X({},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,X({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=V(t),i=V(e),a=z(r),o=L(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:B(i,o),ok:!0}:{extension:v(r)||`.md`,nextPath:B(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=V(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.createMenu.toggle({anchor:e,items:this.getCreateActions({parentDir:t}),title:`Create`})}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=V(e);if(!n)return this.showToast(`File path is required`),!1;let r=de(B(t.normalizedParentDir,n),`.md`);return this.createVaultFile(r,R(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=V(e);if(!n)return this.showToast(`Base path is required`),!1;let r=ce(B(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(B(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=V(e);if(!n)return this.showToast(`Drawing path is required`),!1;let r=de(B(t.normalizedParentDir,n),`.excalidraw`);return this.createVaultFile(r,Co(),{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=V(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=se(B(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=V(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=ue(B(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=V(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=le(B(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create PlantUML diagram`,openAfterCreate:!0})}})}handleRenameFile(e){let t=v(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 ${So(n,`file`,`files`)} and ${So(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 To(e,t=[],n=[]){for(let r of e)if(!(!r?.path||!r?.type)){if(n.push({lowerPath:String(r.path).toLowerCase(),name:r.name,path:r.path,type:r.type}),r.type===`file`||r.type===`base`||r.type===`excalidraw`||r.type===`drawio`||r.type===`mermaid`||r.type===`plantuml`||r.type===`image`){t.push(r.path);continue}r.type===`directory`&&Array.isArray(r.children)&&To(r.children,t,n)}return{files:t,searchEntries:n}}function Eo(e,t){for(let n of e??[]){if(n?.path===t)return n;if(n?.type===`directory`&&Array.isArray(n.children)){let e=Eo(n.children,t);if(e)return e}}return null}function Do(e){let t=0,n=0;for(let r of e?.children??[]){if(r?.type===`directory`){t+=1;let e=Do(r);t+=e.directoryCount,n+=e.fileCount;continue}n+=1}return{directoryCount:t,fileCount:n}}function Oo(e,t,n){return e===t?n:`${n}${e.slice(t.length)}`}var ko=class{constructor(){this.tree=[],this.flatFiles=[],this.flatSearchEntries=[],this.activeFilePath=null,this.expandedDirs=new Set,this.searchQuery=``}setTree(e){this.tree=Array.isArray(e)?e:[];let t=To(this.tree,[],[]);this.flatFiles=t.files,this.flatSearchEntries=t.searchEntries}setSearchQuery(e){this.searchQuery=String(e??``).trim().toLowerCase()}getSearchMatches(){return this.searchQuery?this.flatSearchEntries.filter(e=>e.lowerPath.includes(this.searchQuery)).map(e=>({name:e.name,path:e.path,type:e.type})):[]}getNode(e){return Eo(this.tree,e)}getDirectoryDescendantSummary(e){let t=this.getNode(e);return!t||t.type!==`directory`?{directoryCount:0,fileCount:0}:Do(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=V(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(Oo(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 Ao(e=[],t=``){for(let n of e){if(n.path===t)return n;if(n.type===`directory`&&Array.isArray(n.children)){let e=Ao(n.children,t);if(e)return e}}return null}var jo=420,Mo=10,No=700,Po=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onEntryDrop:t,onDirectorySelect:n,onDirectoryToggle:r,onFileContextMenu:i,onFileSelect:a,onSearchChange:o,onTreeContextMenu:s,onValidateDrop:c}){this.onEntryDrop=t,this.onDirectorySelect=n,this.onDirectoryToggle=r,this.onFileContextMenu=i,this.onFileSelect=a,this.onSearchChange=o,this.onTreeContextMenu=s,this.onValidateDrop=c,this.mobileBreakpointQuery=e,this.treeContainer=document.getElementById(`fileTree`),this.searchInput=document.getElementById(`fileSearchInput`),this.renderedDirectoryWrappers=new Map,this.renderedChildContainers=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}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)})}revealFile(e){Array.from(this.treeContainer?.querySelectorAll(`.file-tree-file`)??[]).find(t=>t.dataset.path===e)?.scrollIntoView({block:`nearest`})}render({activeFilePath:e,changedPaths:t=null,expandedDirs:n,reset:r=!1,searchMatches:i,searchQuery:a,threadCounts:o=new Map,tree:s}){if(!this.treeContainer)return;if(this.threadCounts=o instanceof Map?o:new Map,this.currentSearchQuery=String(a??``),this.currentSearchQuery&&this.clearDragFeedback(),this.searchInput&&this.searchInput.value!==a&&(this.searchInput.value=a),a){this.lastRenderMode=`search`,this.renderSearchResults(i,e);return}if(r||this.lastRenderMode!==`tree`||!Array.isArray(t)||t.length===0){this.renderFullTree(s,{activeFilePath:e,expandedDirs:n}),this.lastRenderMode=`tree`;return}let c=Array.from(new Set(t.map(e=>z(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(c.includes(``)){this.renderFullTree(s,{activeFilePath:e,expandedDirs:n}),this.lastRenderMode=`tree`;return}for(let t of c)if(!this.rerenderDirectoryBranch(t,s,{activeFilePath:e,expandedDirs:n})){this.renderFullTree(s,{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){if(r.type===`directory`){n.appendChild(this.createSearchDirectoryItem(r));continue}n.appendChild(this.createFileItem({activeFilePath:t,depth:0,filePath:r.path,fileType:r.type||(g(r.path)??`file`),name:r.name||L(r.path)}))}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()}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.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=`
142
- <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>
143
- <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>
144
- <span class="file-tree-name">${b(e.name)}</span>
145
- `,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}createSearchDirectoryItem(e){let t=document.createElement(`button`);return t.className=`file-tree-item file-tree-dir`,t.style.setProperty(`--depth`,0),t.dataset.depth=0,t.dataset.path=e.path,t.dataset.entryType=`directory`,t.innerHTML=`
146
- <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>
147
- <span class="file-tree-name">${b(e.name||L(e.path))}</span>
148
- `,t.addEventListener(`click`,n=>{this.consumeSuppressedActivation(t,n)||this.onDirectorySelect?.(e.path)}),t.addEventListener(`contextmenu`,t=>{t.preventDefault(),this.onFileContextMenu?.(t,{directoryPath:e.path,type:`directory`})}),this.bindLongPress(t,()=>{this.onFileContextMenu?.(this.createLongPressEvent(t),{directoryPath:e.path,type:`directory`})}),t}rerenderDirectoryBranch(e,t,{activeFilePath:n,expandedDirs:r}){let i=this.renderedDirectoryWrappers.get(e),a=Ao(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)})}createFileItem({activeFilePath:e,depth:t,filePath:n,fileType:r=`file`,name:i}){let a=document.createElement(`button`);a.className=`file-tree-item file-tree-file`;let o=Number(this.threadCounts.get(n)??0),s=r===`drawio`,c=r===`excalidraw`,u=r===`base`,d=r===`image`,f=r===`mermaid`,p=r===`plantuml`;return u&&a.classList.add(`is-base`),s&&a.classList.add(`is-drawio`),c&&a.classList.add(`is-excalidraw`),d&&a.classList.add(`is-image`),f&&a.classList.add(`is-mermaid`),p&&a.classList.add(`is-plantuml`),n===e&&a.classList.add(`active`),o>0&&a.classList.add(`has-comments`),a.style.setProperty(`--depth`,t),a.dataset.depth=t,a.dataset.path=n,a.dataset.entryType=`file`,o>0&&(a.dataset.threadCount=String(o)),a.innerHTML=`
149
- ${this.getFileIconSvg({isBase:u,isDrawio:s,isExcalidraw:c,isImage:d,isMermaid:f,isPlantUml:p})}
150
- <span class="file-tree-name">${b(l(i))}</span>
151
- ${o>0?`<span class="file-tree-comment-count" aria-label="${o} open comment thread${o===1?``:`s`}">${o}</span>`:``}
152
- `,this.configureDragSource(a,{path:n,type:`file`}),a.addEventListener(`click`,e=>{this.consumeSuppressedActivation(a,e)||this.onFileSelect?.(n)}),a.addEventListener(`contextmenu`,e=>{e.preventDefault(),this.onFileContextMenu?.(e,{filePath:n,type:`file`})}),this.bindLongPress(a,()=>{this.onFileContextMenu?.(this.createLongPressEvent(a),{filePath:n,type:`file`})}),a}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)},No))}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)},jo))}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>Mo||n>Mo)&&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)}getFileIconSvg({isBase:e,isDrawio:t,isExcalidraw:n,isImage:r,isMermaid:i,isPlantUml:a}){return e?`<svg class="file-tree-icon" 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>`:t?`<svg class="file-tree-icon" 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>`:n?`<svg class="file-tree-icon" 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>`:r?`<svg class="file-tree-icon" 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="18" height="16" rx="2"/><circle cx="9" cy="10" r="1.5"/><path d="m21 16-5-5L7 20"/><path d="m14 14 2 2"/></svg>`:i?`<svg class="file-tree-icon" 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>`:a?`<svg class="file-tree-icon" 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>`:`<svg class="file-tree-icon" 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>`}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=q({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=q({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?.()}},Fo=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onFileSelect:t,onFileDelete:n,pendingWorkspaceRequestIds:r=null,toastController:i,vaultClient:a}){this.onFileSelect=t,this.onFileDelete=n,this.toastController=i,this.vaultClient=a,this.state=new ko,this.threadCounts=new Map,this.view=new Po({mobileBreakpointQuery:e,onDirectorySelect:e=>{this.state.expandDirectoryPath(e),this.state.setSearchQuery(``),this.renderTree({reset:!0})},onDirectoryToggle:e=>{this.state.toggleDirectory(e),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 wo({mobileBreakpointQuery:e,onFileDelete:this.onFileDelete,onFileSelect:this.onFileSelect,pendingWorkspaceRequestIds:r,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){this.state.setActiveFile(e),this.renderTree()}setThreadCounts(e=new Map){this.threadCounts=e instanceof Map?new Map(e):new Map(Object.entries(e??{})),this.renderTree()}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 flatDocumentFiles(){return this.state.flatFiles.filter(e=>!s(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,threadCounts:this.threadCounts,tree:this.state.tree})}},Io=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()}},Lo=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.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}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))}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)})}},Ro=.35,zo=120,Bo=12,Vo=2;function Ho(e){return Math.max(e.scrollHeight-e.clientHeight,0)}function Uo(e){return Math.max(e,0)}function Wo(e){return Math.max(e.clientHeight*Ro,Bo)}function Go(e){return(e?.scrollTop??0)<=Vo}function Ko(e,t){let n=e.getBoundingClientRect();return t.getBoundingClientRect().top-n.top+e.scrollTop}function qo(e){return!e.querySelector(`[data-source-line]`)}var Jo=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,W(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,W(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=H(()=>{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()},zo)}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,Ro),requestAnimationFrame(()=>{this.lockedElements.delete(t)});return}}let r=Ho(e),i=Ho(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=Uo(t),requestAnimationFrame(()=>{this.lockedElements.delete(e)})}getPreviewScrollTopForEditorLine(){if(Go(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=x((e-n.start)/a,0,1),s=Ho(this.previewContainer),c=Wo(this.previewContainer);return x(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+Wo(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?x((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:Ko(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=>qo(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=Ho(this.previewContainer);return Math.max(e-n.top+this.previewContainer.clientHeight,i,1)}return Math.max(r.top-n.top,i,1)}},Yo=`<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>`,Xo=`<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>`,Zo=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`?Xo:Yo;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`)})}},Qo=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`;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}},$o=16/9,es=240,ts=720,ns=180;function rs(e){return Math.max(ns,Math.min(ts,Math.ceil(e||es)))}var is=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}=Ae(this.embedEntries,t);r.forEach(e=>this._destroyEntry(e)),this.embedEntries=n,this.embedEntries.forEach(e=>{e.aspectRatio=e.aspectRatio||$o,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=rs(n>0?n/(e.aspectRatio||$o):e.inlineHeightPx);e.inlineHeightPx=r,Z(t,`height`,`${r}px`),Z(e.wrapper,`position`,`absolute`),Z(e.wrapper,`top`,`${t.offsetTop}px`),Z(e.wrapper,`left`,`${t.offsetLeft}px`),Z(e.wrapper,`width`,`${t.offsetWidth}px`),Z(e.wrapper,`height`,`${r}px`),Z(e.wrapper,`margin`,`0`),Z(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 Z(e,t,n){!e||e.style[t]===n||(e.style[t]=n)}var Q=1,as=6,os=.25,ss=2,cs=6;function ls(e){let t=Number(e);return Number.isFinite(t)?Math.min(as,Math.max(Q,Math.round(t*100)/100)):Q}function us(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 ds(e){return!!e?.ctrlKey}var fs=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=Q,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=Q,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(os);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=Q,this.offsetX=0,this.offsetY=0,this.syncTransform()}zoomBy(e){this.setScale(this.scale+e)}setScale(e){this.scale=ls(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=ls(e),s=Number(n)>0?Number(n):Q,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<=Q?!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>Q?`grab`:`zoom-in`)}updateDrag(e,t,n){return!this.isOpen||this.activePointerId!==e?!1:(!this.didDrag&&(Math.abs(t-this.dragStartX)>=cs||Math.abs(n-this.dragStartY)>=cs)&&(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)>=cs||Math.abs(r.x-this.pinchStartCenter.x)>=cs||Math.abs(r.y-this.pinchStartCenter.y)>=cs)&&(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>Q){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=us(this.offsetX,{contentSize:this.imageElement.offsetWidth||0,scale:this.scale,viewportSize:this.viewport.clientWidth||0}),this.offsetY=us(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>Q?`grab`:`zoom-in`,this.zoomLabel&&(this.zoomLabel.textContent=`${Math.round(this.scale*100)}%`),this.resetButton&&(this.resetButton.disabled=this.scale<=Q&&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(os)),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(ds(e)){e.preventDefault(),this.zoomBy(e.deltaY<0?os:-.25);return}if(this.scale<=Q)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>Q)&&e.preventDefault();return}this.scale<=Q||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<=Q&&this.setScale(ss)}}),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}};function $({createController:e,fallback:t={},loadController:n,onControllerReady:r=null,shouldLoad:i=()=>!0}){let a=null,o=null,s=async()=>a||(o||=n().then(t=>(a=e(t),r?.(a),a)).catch(e=>{throw o=null,e}),o),c=new Proxy({},{get(e,n){if(n!==`then`&&typeof n==`string`){if(n===`ensure`)return s;if(n===`current`)return a;if(a&&n in a){let e=a[n];return typeof e==`function`?e.bind(a):e}if(Object.hasOwn(t,n)){let e=t[n];return typeof e==`function`?e.bind(c):e}return(...e)=>{if(i(n,e))return s().then(t=>{let r=t[n];return typeof r==`function`?r.apply(t,e):r})}}}});return c}function ps(e,t){return!!e?.querySelector?.(t)}var ms=[bt,xt,It,Ht,{reportLazyControllerError(e,t){console.error(`[lazy-controller] Failed to load ${e}.`,t),this.toastController?.show?.(`Failed to load ${e}. Try again.`,{dismissible:!0})},loadBasesPreviewController(){return e(()=>import(`./bases-preview-controller-2pLHk0uk.js`).then(e=>e.BasesPreviewController),__vite__mapDeps([27,25,26,28,29,30,31]),import.meta.url)},loadDrawioEmbedController(){return e(()=>import(`./drawio-embed-controller-BD1GTRwn.js`).then(e=>e.DrawioEmbedController),__vite__mapDeps([32,28,33,29,34]),import.meta.url)},loadExcalidrawEmbedController(){return e(()=>import(`./excalidraw-embed-controller-y2fenN_g.js`).then(e=>e.ExcalidrawEmbedController),__vite__mapDeps([35,28,29,34,36]),import.meta.url)},loadGitPanelController(){return e(()=>import(`./git-panel-controller-BDTR2HVp.js`).then(e=>e.GitPanelController),__vite__mapDeps([37,26,38,25,30,31]),import.meta.url)},loadGitDiffViewController(){return e(()=>import(`./git-diff-view-controller-DgdM1aqb.js`).then(e=>e.GitDiffViewController),__vite__mapDeps([39,26,38,25,30]),import.meta.url)},loadFileHistoryViewController(){return e(()=>import(`./file-history-view-controller-BDjEV9xJ.js`).then(e=>e.FileHistoryViewController),__vite__mapDeps([40,26,38,25,30]),import.meta.url)},createLazyBasesPreviewController(){let e;return e=$({createController:e=>new e({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}),fallback:{destroy:()=>{},reconcileEmbeds:(t=this.elements.previewContent)=>{ps(t,`.bases-embed-placeholder[data-base-key]`)&&e.ensure().then(e=>e.reconcileEmbeds(t)).catch(e=>this.reportLazyControllerError(`Bases preview`,e))},renderStandalone:async t=>(await e.ensure()).renderStandalone(t)},loadController:()=>this.loadBasesPreviewController(),shouldLoad:e=>e===`renderStandalone`}),e},createLazyDrawioEmbedController(){let e={hydrationPaused:!1,theme:null},t;return t=$({createController:e=>new e({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}),fallback:{destroy:()=>{},detachForCommit:()=>{},hydrateVisibleEmbeds:()=>{},reconcileEmbeds:(e=this.elements.previewContent)=>{ps(e,`.drawio-embed-placeholder[data-drawio-key]`)&&t.ensure().then(t=>{t.reconcileEmbeds(e),t.hydrateVisibleEmbeds(),t.syncLayout()}).catch(e=>this.reportLazyControllerError(`Draw.io preview`,e))},setHydrationPaused:t=>{e.hydrationPaused=!!t},syncLayout:()=>{},updateLocalUser:()=>{},updateTheme:t=>{e.theme=t}},loadController:()=>this.loadDrawioEmbedController(),onControllerReady:t=>{t.setHydrationPaused(e.hydrationPaused),e.theme&&t.updateTheme(e.theme)}}),t},createLazyExcalidrawEmbedController(){let e={hydrationPaused:!1,localUser:null,theme:null},t;return t=$({createController:e=>new e({getLocalUser:()=>this.lobby.getLocalUser(),getTheme:()=>this.themeController.getTheme(),onOpenFile:e=>e&&this.navigation.navigateToFile(e),onToggleQuickSwitcher:()=>{this.toggleQuickSwitcher()},previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent,toastController:this.toastController}),fallback:{destroy:()=>{},detachForCommit:()=>{},hydrateVisibleEmbeds:()=>{},prepareFileDisconnect:async()=>!1,reconcileEmbeds:(e=this.elements.previewContent,n={})=>{ps(e,`.excalidraw-embed-placeholder[data-embed-key]`)&&t.ensure().then(t=>{t.reconcileEmbeds(e,n),t.hydrateVisibleEmbeds(),t.syncLayout()}).catch(e=>this.reportLazyControllerError(`Excalidraw preview`,e))},setHydrationPaused:t=>{e.hydrationPaused=!!t},syncLayout:()=>{},updateLocalUser:t=>{e.localUser=t},updateTheme:t=>{e.theme=t}},loadController:()=>this.loadExcalidrawEmbedController(),onControllerReady:t=>{t.setHydrationPaused(e.hydrationPaused),e.theme&&t.updateTheme(e.theme),e.localUser&&t.updateLocalUser(e.localUser)}}),t},createLazyGitPanelController(){let e={active:!1,mode:`changes`,selection:{}},t;return t=$({createController:e=>new e({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}),fallback:{initialize:()=>{},refresh:async e=>(await t.ensure()).refresh(e),setActive:n=>{e.active=!!n,e.active&&t.ensure().catch(e=>this.reportLazyControllerError(`Git panel`,e))},setMode:n=>{e.mode=n,e.active&&t.ensure().catch(e=>this.reportLazyControllerError(`Git panel`,e))},setSelection:(n={})=>{e.selection=n,e.active&&t.ensure().catch(e=>this.reportLazyControllerError(`Git panel`,e))},status:null},loadController:()=>this.loadGitPanelController(),onControllerReady:t=>{t.initialize(),t.setMode(e.mode),t.setSelection(e.selection),t.setActive(e.active),e.active&&t.refresh({force:!0})}}),t},createLazyGitDiffViewController(){let e={repoStatus:null},t;return t=$({createController:e=>new e({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}),fallback:{getToolbarTitle:({commitHash:e=null,filePath:t=null,path:n=null,scope:r=`all`,source:i=`workspace`}={})=>i===`commit`?n?L(n)||String(n??``)||`File`:e?`Commit ${String(e).slice(0,7)}`:`Commit Diff`:t?L(t)||String(t??``)||`File`:r===`staged`?`Staged Changes`:r===`working-tree`?`Working Tree Changes`:`All Changes`,hide:()=>{},initialize:()=>{},setRepoStatus:t=>{e.repoStatus=t}},loadController:()=>this.loadGitDiffViewController(),onControllerReady:t=>{t.initialize(),t.setRepoStatus(e.repoStatus)}}),t},createLazyFileHistoryViewController(){let e;return e=$({createController:e=>new e({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}),fallback:{hide:()=>{},initialize:()=>{}},loadController:()=>this.loadFileHistoryViewController(),onControllerReady:e=>{e.initialize()}}),e},async ensureGitControllers(){await Promise.all([this.gitPanel.ensure(),this.gitDiffView.ensure(),this.fileHistoryView.ensure()])},scheduleGitControllerPrewarm({timeout:e=2500}={}){if(this.runtimeConfig.gitEnabled===!1||this._gitControllerPrewarmHandle)return;let t=()=>{this._gitControllerPrewarmHandle=null,this.gitPanel.ensure().then(e=>e.refresh({force:!0})).catch(e=>this.reportLazyControllerError(`Git tools`,e))};if(typeof window.requestIdleCallback==`function`){this._gitControllerPrewarmHandle=window.requestIdleCallback(t,{timeout:e});return}this._gitControllerPrewarmHandle=window.setTimeout(t,0)}},Yt,{...Xn,...ir,...on,...Zr,...ur},Qr],hs=class{constructor(){for(let e of ms)for(let[t,n]of Object.entries(e))t in this||(this[t]=n);this.elements=yt(document),this.runtimeConfig=N(),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:P,navigateToFile:re,navigateToGitCommit:j,navigateToGitDiff:k,navigateToGitFileHistory:ne,navigateToGitFilePreview:ie,navigateToGitHistory:A},this.preferences=new si({chatNotificationsKey:`collabmd-chat-notifications-enabled`,lineWrappingKey:`collabmd-editor-line-wrap`,sidebarVisibleKey:`collabmd-sidebar-visible`,userNameKey:`collabmd-user-name`}),this.notifications=new ii,this.backlinksApiClient=di,this.gitApiClient=pi,this.plantUmlApiClient=mi,this.vaultApiClient=w,this._session=null,this._hasPromptedForDisplayName=!1,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.chatNotificationsEnabled=this.preferences.getChatNotificationsEnabled(),this.chatNotificationPermission=this.notifications.getPermission(),this.lobbyChatMessageMaxLength=280,this.quickSwitcher=null,this.quickSwitcherModulePromise=null,this.fileExplorerReadyPromise=Promise.resolve(),this._gitControllerPrewarmHandle=null,this.mobileBreakpointQuery=window.matchMedia(`(max-width: 768px)`),this.pendingWorkspaceRequestIds=new Set,this._fileOpenPerf=null,this.versionMonitor=new ui({currentBuildId:this.runtimeConfig.build?.id,onUpdateAvailable:e=>this.promptForVersionReload(e),runtimeConfig:this.runtimeConfig}),this.lobby=new ri({preferredUserName:this.getStoredUserName(),onChange:e=>this.updateGlobalUsers(e),onChatChange:(e,t)=>this.updateChatMessages(e,t)}),this.workspaceSync=new Mi({onTreeChange:(e,t={})=>{let n=this.fileExplorerReady;this.fileExplorer.setTree(e,t),this.handleCommentOverviewWorkspaceTreeChange?.(),this.fileExplorerReady=!0,!n&&this.isTabActive&&this.handleHashChange()},onWorkspaceEvent:e=>{this.handleIncomingWorkspaceEvent(e)}}),this.toastController=new Qo(this.elements.toastContainer),this.chatToastController=new Qo(this.elements.chatToastContainer),this.fileExplorer=new Fo({mobileBreakpointQuery:this.mobileBreakpointQuery,onFileDelete:()=>this.navigation.navigateToFile(null),onFileSelect:e=>this.handleFileSelection(e,{closeSidebarOnMobile:!0}),pendingWorkspaceRequestIds:this.pendingWorkspaceRequestIds,toastController:this.toastController,vaultClient:this.vaultApiClient}),this.commentsOverview=new Ii({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=this.createLazyGitPanelController(),this.outlineController=new Lo({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 is({previewElement:this.elements.previewContent}),this.basesPreview=this.createLazyBasesPreviewController(),this.imageLightbox=new fs({previewElement:this.elements.previewContent}),this.previewRenderer=new ut({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.videoEmbed.syncLayout(),this.basesPreview.reconcileEmbeds(this.elements.previewContent),this.drawioEmbed.reconcileEmbeds(this.elements.previewContent),this.drawioEmbed.syncLayout(),this.excalidrawEmbed.reconcileEmbeds(this.elements.previewContent,{isLargeDocument:t.isLargeDocument}),this.excalidrawEmbed.syncLayout(),this.scrollSyncController.setLargeDocumentMode(t.isLargeDocument),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.videoEmbed.syncLayout(),this.drawioEmbed.syncLayout(),this.excalidrawEmbed.syncLayout(),this.applyPendingPreviewRouteAnchor({allowExpired:!0,behavior:`auto`,clearMissing:!0}),this.schedulePreviewLayoutSync({delayMs:0}),this.refreshCommentUiLayout()},outlineController:this.outlineController,plantUmlRenderClient:this.plantUmlApiClient,previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent,toastController:this.toastController}),this.themeController=new Zo({onChange:e=>this.handleThemeChange(e)}),this.layoutController=new Io({mobileBreakpointQuery:this.mobileBreakpointQuery,onMeasureEditor:()=>this.session?.requestMeasure(),onViewRequest:e=>this.handleLayoutViewRequest(e)}),this.scrollSyncController=new Jo({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.backlinksPanel=new Ni({headerPanelElement:this.elements.backlinksHeaderPanel,inlinePanelElement:this.elements.backlinksInlinePanel,loadBacklinks:(e,t={})=>this.backlinksApiClient.readBacklinks(e,t),onFileSelect:e=>this.handleFileSelection(e,{closeSidebarOnMobile:!0}),panelElement:this.elements.backlinksPanel}),this.excalidrawEmbed=this.createLazyExcalidrawEmbedController(),this.drawioEmbed=this.createLazyDrawioEmbedController(),this.commentUi=new _o({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.workspacePreviewController=new ht({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),isMermaidFile:e=>this.isMermaidFile(e),isPlantUmlFile:e=>this.isPlantUmlFile(e),layoutController:this.layoutController,outlineController:this.outlineController,previewRenderer:this.previewRenderer,schedulePreviewLayoutSync:e=>this.schedulePreviewLayoutSync(e),scrollSyncController:this.scrollSyncController,videoEmbed:this.videoEmbed}),this.wikiLinkFileController=new mt({getFileList:()=>this.fileExplorer.flatDocumentFiles,navigation:this.navigation,refreshExplorer:()=>this.fileExplorer.refresh(),toastController:this.toastController,vaultApiClient:this.vaultApiClient,wikiLinkAutoCreate:this.runtimeConfig.wikiLinkAutoCreate!==!1}),this.gitDiffView=this.createLazyGitDiffViewController(),this.fileHistoryView=this.createLazyFileHistoryViewController(),this.tabActivityLock=new Si({onActivated:({takeover:e})=>this.handleTabActivated({takeover:e}),onBlocked:()=>this.handleTabBlocked({reason:`active-elsewhere`}),onStolen:()=>this.handleTabBlocked({reason:`taken-over`})}),this.workspaceCoordinator=new vt({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,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(),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),isMermaidFile:e=>this.isMermaidFile(e),isPlantUmlFile:e=>this.isPlantUmlFile(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:()=>{this.session=null,this.commentUi.attachSession(null),this.layoutController.reset(),this.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})=>{if(this.handleCommentEditorContentChange(),e){this.renderBaseFilePreview(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()},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.renderDrawioFilePreview(e),onRenderBasePreview:e=>this.renderBaseFilePreview(e),onRenderExcalidrawPreview:e=>this.renderExcalidrawFilePreview(e),onRenderImagePreview:e=>this.renderImageFilePreview(e),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.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.resetPreviewMode(),renderPresence:()=>this.renderPresence(),scrollContainerForSession:e=>e.getScrollContainer(),shouldUseDrawioPreview:()=>!!this.runtimeConfig.drawioBaseUrl,showEditorLoading:()=>this.showEditorLoading(),stateStore:this}),this.workspaceRouteController=new pt({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.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}),this.chatNotificationPermission!==`granted`&&(this.chatNotificationsEnabled=!1)}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-DGlpiAsK.js`).then(e=>e.EditorSession),__vite__mapDeps([41,1,42,43,44,45,46,47,48,49,50,25,28,51,52,53,54]),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-CoiYvllm.js`).then(e=>e.QuickSwitcherController),__vite__mapDeps([55,25,26]),import.meta.url)}async ensureQuickSwitcher(){return dt(this)}async toggleQuickSwitcher(){return ft(this)}};async function gs(){await ee(),new hs().initialize()}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{gs()},{once:!0}):gs();