collabmd 0.1.37 → 0.1.39
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.
- package/README.md +1 -0
- package/dist/client/assets/{CodeMirrorEditor-UCMRAMCV-DnBV8gCm.js → CodeMirrorEditor-UCMRAMCV-75Zi8U_A.js} +1 -1
- package/dist/client/assets/{dist-BPEi1dEF.js → dist-1SMeCZhf.js} +1 -1
- package/dist/client/assets/{dist-Dbg8P4C5.js → dist-8EAyH6_p.js} +1 -1
- package/dist/client/assets/{dist-BEKQo64E.js → dist-B7XQNod9.js} +1 -1
- package/dist/client/assets/dist-BCzW2jDH.js +1 -0
- package/dist/client/assets/{dist-CQVTTk81.js → dist-BEk5kTf_.js} +1 -1
- package/dist/client/assets/dist-BOn786F3.js +1 -0
- package/dist/client/assets/{dist-Bn8WRPs1.js → dist-BXiFOexW.js} +1 -1
- package/dist/client/assets/{dist-v3i1ifes.js → dist-Bp_j2hKC.js} +1 -1
- package/dist/client/assets/dist-BwUX6zpo.js +1 -0
- package/dist/client/assets/{dist-DwvSvkOE.js → dist-Bz-8_JmE.js} +1 -1
- package/dist/client/assets/{dist-CBEw2W2P.js → dist-CH3l6nVf.js} +1 -1
- package/dist/client/assets/{dist-DQiph4qx.js → dist-CIt_ogHO.js} +1 -1
- package/dist/client/assets/{dist-BOP-dC-R.js → dist-CQZDuOJ9.js} +1 -1
- package/dist/client/assets/{dist-DdAqzGFU.js → dist-CRyP6okk.js} +1 -1
- package/dist/client/assets/dist-D-ixVAsS2.js +1 -0
- package/dist/client/assets/{dist-Brrlevif.js → dist-D8d0IGSI.js} +1 -1
- package/dist/client/assets/{dist-DZ2t5lUX.js → dist-Das5WX49.js} +1 -1
- package/dist/client/assets/{dist-CaMl1R6P.js → dist-DplP0BiK.js} +1 -1
- package/dist/client/assets/{dist-BE8C_ouo.js → dist-DwgKARew.js} +1 -1
- package/dist/client/assets/dist-GgGgSSbl.js +1 -0
- package/dist/client/assets/{dist-D34Xzrah.js → dist-NcJIpTJ8.js} +1 -1
- package/dist/client/assets/dist-QktK6LIH.js +1 -0
- package/dist/client/assets/{dist-BiCgLddE.js → dist-ZuMKSK7c.js} +1 -1
- package/dist/client/assets/{dist-DPCUH5MO.js → dist-_THc9HiJ.js} +1 -1
- package/dist/client/assets/{dist-mPPUaHhq.js → dist-bkoMCmF7.js} +1 -1
- package/dist/client/assets/{dist-B98fHn5m.js → dist-eAgBpkKv.js} +1 -1
- package/dist/client/assets/{dist-BScEL4VP.js → dist-fpFkgu34.js} +1 -1
- package/dist/client/assets/{dist-aE0_04fl.js → dist-tRNsnttY.js} +1 -1
- package/dist/client/assets/{dist-DWRyOl2w.js → dist-uyVGTnZh.js} +1 -1
- package/dist/client/assets/{dist-CJWCCWEW.js → dist-yy8SO13g.js} +1 -1
- package/dist/client/assets/{drawio-editor-B65ntu5E.js → drawio-editor-B_Sr8Z_Z.js} +1 -1
- package/dist/client/assets/{drawioEditor-ChF0ZKUh.js → drawioEditor-DBSyP3_d.js} +2 -2
- package/dist/client/assets/editor-session-C1scHGLl.js +16 -0
- package/dist/client/assets/{embedded-editor-base-CgEkjNYn.css → embedded-editor-base-Bb8ywn1e.css} +1 -1
- package/dist/client/assets/excalidraw-editor-B0XXVLHd.js +9 -0
- package/dist/client/assets/{excalidraw-scene-MyNAJi2A.js → excalidraw-scene-wAbVSY1L.js} +2 -2
- package/dist/client/assets/{excalidrawEditor-BT9hmN5y.js → excalidrawEditor-37sk03H8.js} +2 -2
- package/dist/client/assets/{export-page-9MSUmliH.js → export-page-Bnk-YQp-.js} +1 -1
- package/dist/client/assets/{exportDocument-W3oYiIU3.js → exportDocument-WQNApAbg.js} +2 -2
- package/dist/client/assets/{index-D8NvI6X_.js → index-BoKmcqkH.js} +2 -2
- package/dist/client/assets/{main-CuQn72Cc.js → main-BKumyd95.js} +5 -5
- package/dist/client/assets/preview-render-compiler-9SmLUP5V.js +1 -0
- package/dist/client/assets/{preview-render-compiler-BCaqHl2M.js → preview-render-compiler-IUtgIlOM.js} +1 -1
- package/dist/client/assets/{preview-render-worker-yfayDDfY.js → preview-render-worker-BwQ5sPy9.js} +1 -1
- package/dist/client/assets/runtime-config-BcUbZKho.js +1 -0
- package/dist/client/assets/{vault-api-client-CGLEvxZo.js → vault-api-client-BDKKvtOF.js} +1 -1
- package/dist/client/drawio-editor.html +1 -1
- package/dist/client/excalidraw-editor.html +1 -1
- package/dist/client/export-document.html +1 -1
- package/dist/client/index.html +1 -1
- package/docker-compose.yml +1 -0
- package/package.json +6 -6
- package/src/client/application/preview-render-compiler.js +12 -1
- package/src/client/application/preview-render-executor.js +4 -0
- package/src/client/application/preview-render-worker.js +2 -0
- package/src/client/application/preview-renderer.js +5 -2
- package/src/client/application/wiki-link-file-controller.js +7 -0
- package/src/client/bootstrap/collabmd-app-shell.js +2 -0
- package/src/client/domain/excalidraw-collaboration.js +50 -0
- package/src/client/domain/excalidraw-scene-reconcile.js +38 -0
- package/src/client/domain/mermaid-language.js +179 -0
- package/src/client/domain/runtime-paths.js +1 -0
- package/src/client/excalidraw-editor.js +76 -47
- package/src/client/infrastructure/editor-view-adapter.js +7 -2
- package/src/client/infrastructure/excalidraw-room-client.js +139 -27
- package/src/client/styles/surfaces/embedded-editor-base.css +2 -1
- package/src/domain/excalidraw-room-codec.js +1 -17
- package/src/server/config/env.js +1 -0
- package/src/server/infrastructure/http/create-static-handler.js +2 -0
- package/dist/client/assets/dist-BfVljg0L2.js +0 -1
- package/dist/client/assets/dist-CcG3Y7Wp.js +0 -1
- package/dist/client/assets/dist-CghBwrO3.js +0 -1
- package/dist/client/assets/dist-Csbx9lQ-.js +0 -1
- package/dist/client/assets/dist-DLyohOXi.js +0 -1
- package/dist/client/assets/dist-WXLmfDGg.js +0 -1
- package/dist/client/assets/editor-session-YtGVwK3v.js +0 -16
- package/dist/client/assets/excalidraw-editor-Co4KOVfJ.js +0 -9
- package/dist/client/assets/preview-render-compiler-kjMajWKn.js +0 -1
- package/dist/client/assets/runtime-config-Bf8nxVez.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./mermaid-runtime-BGlnoUXY.js","./preload-helper-Bo9GmnuQ.js","./chunk-U2HBQHQK-BBXgsocS.js","./src-BuiVcSz-.js","./chunk-YHkbxXgt.js","./chunk-5PVQY5BW-ciE7eHID.js","./dist-wkd-N1L5.js","./chunk-ICPOFSXX-DqJi89rc.js","./_baseFor-BSErPbF2.js","./isEmpty-CpfhGGBo.js","./chunk-336JU56O-DvrrHsJT.js","./chunk-5FUZZQ4R-CxIIxXPy.js","./chunk-X2U36JSP-D3OEPG7k.js","./chunk-ZZ45TVLE-DGIhE_ST.js","./rough.esm-BU2knLt9.js","./chunk-ENJZ2VHE-BQj_1YA_.js","./line-BCItEgq3.js","./path-DIlZIGue.js","./array-B3agRrCs.js","./chunk-BSJP7CBP-D2KkrA_B.js","./chunk-426QAEUC-CEbmCgux.js","./chunk-XPW4576I-BUfyrOtN.js","./preview-render-compiler-
|
|
2
|
-
import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r as i}from"./preview-render-profile-Bf6R7v4w.js";import{a,c as o,d as s,f as c,i as l,l as u,m as d,n as f,o as p,p as m,r as h,s as g,t as _,u as v}from"./file-kind-DmKq2MvD.js";import{i as y,n as b,t as x}from"./vault-utils-CRpy8MQz.js";import{n as S,r as C,t as w}from"./vault-api-client-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./mermaid-runtime-BGlnoUXY.js","./preload-helper-Bo9GmnuQ.js","./chunk-U2HBQHQK-BBXgsocS.js","./src-BuiVcSz-.js","./chunk-YHkbxXgt.js","./chunk-5PVQY5BW-ciE7eHID.js","./dist-wkd-N1L5.js","./chunk-ICPOFSXX-DqJi89rc.js","./_baseFor-BSErPbF2.js","./isEmpty-CpfhGGBo.js","./chunk-336JU56O-DvrrHsJT.js","./chunk-5FUZZQ4R-CxIIxXPy.js","./chunk-X2U36JSP-D3OEPG7k.js","./chunk-ZZ45TVLE-DGIhE_ST.js","./rough.esm-BU2knLt9.js","./chunk-ENJZ2VHE-BQj_1YA_.js","./line-BCItEgq3.js","./path-DIlZIGue.js","./array-B3agRrCs.js","./chunk-BSJP7CBP-D2KkrA_B.js","./chunk-426QAEUC-CEbmCgux.js","./chunk-XPW4576I-BUfyrOtN.js","./preview-render-compiler-9SmLUP5V.js","./preview-render-compiler-IUtgIlOM.js","./preview-render-profile-Bf6R7v4w.js","./vault-utils-CRpy8MQz.js","./file-kind-DmKq2MvD.js","./editor-session-C1scHGLl.js","./dist-QktK6LIH.js","./dist-DplP0BiK.js","./dist-Bz-8_JmE.js","./dist-D8d0IGSI.js","./dist-BXiFOexW.js","./dist-yy8SO13g.js","./dist-NcJIpTJ8.js","./dist-bkoMCmF7.js","./dist-fpFkgu34.js","./yjs-provider-reset-guard-DSPzcvAO.js","./runtime-config-BcUbZKho.js","./room-z2w9b96b.js","./quick-switcher-controller-B1erSgJ1.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r as i}from"./preview-render-profile-Bf6R7v4w.js";import{a,c as o,d as s,f as c,i as l,l as u,m as d,n as f,o as p,p as m,r as h,s as g,t as _,u as v}from"./file-kind-DmKq2MvD.js";import{i as y,n as b,t as x}from"./vault-utils-CRpy8MQz.js";import{n as S,r as C,t as w}from"./vault-api-client-BDKKvtOF.js";import{a as T,c as ee,d as E,f as te,i as ne,l as re,m as ie,n as D,o as ae,p as O,r as oe,s as se,t as ce,u as k}from"./runtime-config-BcUbZKho.js";import{n as le,r as ue,t as A}from"./yjs-provider-reset-guard-DSPzcvAO.js";import{r as j}from"./drawio-room-1i6Nn0_Z.js";import{a as de,c as fe,d as pe,f as M,g as me,h as he,i as ge,l as _e,m as ve,n as N,o as ye,p as be,r as xe,s as Se,t as P,u as Ce}from"./preview-diagram-utils-Nqpp4FNV.js";import{l as we,n as Te,r as Ee,t as De}from"./room-z2w9b96b.js";var Oe={copy:`
|
|
3
3
|
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
|
4
4
|
<path d="M5.5 5.5h6.8v8h-6.8z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
5
5
|
<path d="M3.7 10.5H3a1 1 0 0 1-1-1v-6a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v.7" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.4"/>
|
|
@@ -38,11 +38,11 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
38
38
|
`),n=e.findIndex(e=>/^\s*gantt\b/.test(e));n!==-1&&(e.splice(n+1,0,` todayMarker off`),t=e.join(`
|
|
39
39
|
`))}return t}async function Ke(e,t){if(!e?.initialize||!e?.run)throw Error(`Mermaid runtime is unavailable`);e.initialize(ke);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=Pe(),r.textContent=Ge(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 We(i,{padding:24})}finally{n.remove()}}async function qe(e){let t=be(e),n=await Ie(Ne(t)),r=document.createElement(`div`);r.innerHTML=t;let i=r.querySelector(`svg`),{width:a,height:o}=i?Fe(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),Le(s)}function Je(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.style.display=`none`,document.body.appendChild(r),r.click(),window.setTimeout(()=>{r.remove(),URL.revokeObjectURL(n)},3e4)}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=M,cancelIdleRenderFn:s=xe,intersectionObserverFactory:c=(e,t)=>new IntersectionObserver(e,t),isNearViewportFn:l=Ce,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.instanceCounter=0,this.preservedShells=new Map,this.fileInflightRequests=new Map}createLegacyFileSourceLoader(e){return typeof e==`function`?async t=>{let n=await e(E(`/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.preservedShells.clear()}cancelHydration(){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.clear()}hasPendingWork(){return this.hydrationInProgress||this.pendingShells.length>0}preserveHydratedShellsForCommit(){this.preservedShells.clear();let e=this.renderer.previewElement;e&&Array.from(e.querySelectorAll(`${this.shellSelector}[${this.attributeNames.hydrated}="true"][${this.attributeNames.key}]`)).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&&e.remove(),this.preservedShells.set(t,{key:t,shell:e,source:n,target:r}))})}reconcileHydratedShells(){let e=this.renderer.previewElement;if(!e||this.preservedShells.size===0){this.preservedShells.clear();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.get(n):null;r&&he({nextSource:e.querySelector(this.sourceSelector)?.textContent??``,nextTarget:e.dataset[this.datasetKeys.target]??``,preservedSource:r.source,preservedTarget:r.target})&&(this.syncPreservedShell(r.shell,e),e.replaceWith(r.shell),t||=r.shell.classList.contains(`is-maximized`),this.preservedShells.delete(n))}),this.preservedShells.clear(),this.handleReconcile({restoredMaximizedShell:t})}handleReconcile(){}syncPreservedShell(e,t){me(e,t,this.attributeNames.sourceLine),me(e,t,this.attributeNames.sourceLineEnd),me(e,t,this.attributeNames.key),me(e,t,this.attributeNames.target),me(e,t,this.attributeNames.label),me(e,t,this.attributeNames.sourceHash),e.classList.add(this.shellClassName),e.dataset[this.datasetKeys.hydrated]=`true`,this.removeDatasetValue(e,`queued`);let n=t.querySelector(this.sourceSelector),r=e.querySelector(this.sourceSelector);if(!r&&n&&(r=n.cloneNode(!0),e.prepend(r)),r&&n){let e=n.textContent??``;(e||!t.dataset[this.datasetKeys.target])&&(r.textContent=e),r.hidden=!0}}setupHydration(e){let t=this.renderer.previewElement,n=this.renderer.previewContainer;if(!t||!n)return 0;let r=Array.from(t.querySelectorAll(this.shellSelector));return r.length===0?0:(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(()=>{e===this.renderer.activeRenderVersion&&(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=[];for(;this.pendingShells.length>0&&e.length<this.batchSize;){let t=this.pendingShells.shift();!t?.isConnected||this.isShellHydrated(t)||(this.removeDatasetValue(t,`queued`),e.push(t))}if(e.length===0){this.renderer.updateHydrationPhase();return}this.hydrationInProgress=!0,this.renderer.setPhase(`hydrating`);let t;try{t=await this.prepareHydrationBatch(e)}catch(t){this.handlePrepareHydrationBatchError(e,t),this.hydrationInProgress=!1,this.renderer.updateHydrationPhase();return}for(let n of e)await this.hydrateShell(n,t);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){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.loader=null,this.runtime=null,this.shellRefits=new WeakMap,this.shellResizeObservers=new WeakMap,this.resizeObservers=new Set,this.activeMaximizedShell=null,this.maximizedRoot=null}destroy(){this.cancelHydration(),this.preservedShells.clear(),this.clearActiveShell(),this.disconnectResizeObservers(),this.maximizedRoot?.remove(),this.maximizedRoot=null}cancelHydration(){super.cancelHydration();let e=this.syncActiveShell();e&&(this.restoreShellMount(e),e.classList.remove(`is-maximized`),this.clearActiveShell(),document.body.classList.remove(`mermaid-maximized-open`))}clearActiveShell(){this.activeMaximizedShell=null,this.maximizedRoot&&this.maximizedRoot.childElementCount===0&&(this.maximizedRoot.hidden=!0)}disconnectResizeObservers(){this.resizeObservers.forEach(e=>e.disconnect()),this.resizeObservers.clear(),this.shellResizeObservers=new WeakMap}disconnectShellResizeObserver(e){let t=this.shellResizeObservers.get(e);t&&(t.disconnect(),this.resizeObservers.delete(t),this.shellResizeObservers.delete(e))}attachShellResizeObserver(e,t,n){if(this.disconnectShellResizeObserver(e),typeof ResizeObserver!=`function`||!e?.isConnected||!(t instanceof HTMLElement))return;let r=new ResizeObserver(()=>n());r.observe(t),r.observe(e),this.shellResizeObservers.set(e,r),this.resizeObservers.add(r)}syncActiveShell(){return this.activeMaximizedShell?.isConnected&&this.activeMaximizedShell.classList.contains(`is-maximized`)?this.activeMaximizedShell:(this.clearActiveShell(),null)}ensureMaximizedRoot(){if(this.maximizedRoot?.isConnected&&this.maximizedRoot.parentElement===document.body)return this.maximizedRoot;let e=document.body.querySelector(`[data-mermaid-maximized-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.mermaidMaximizedRoot=`true`,e.className=`mermaid-maximized-root`,document.body.appendChild(e)),this.maximizedRoot=e,e}mountShellInMaximizedRoot(e){if(!e)return;let t=this.ensureMaximizedRoot();t.hidden=!1,e._mermaidRestoreParent=e.parentElement||null,e._mermaidRestoreNextSibling=e.nextSibling||null,t.appendChild(e)}restoreShellMount(e){if(!e)return;let t=e._mermaidRestoreParent,n=e._mermaidRestoreNextSibling;t?.isConnected&&(n?.parentElement===t?t.insertBefore(e,n):t.appendChild(e)),e._mermaidRestoreParent=null,e._mermaidRestoreNextSibling=null,this.maximizedRoot&&this.maximizedRoot.childElementCount===0&&(this.maximizedRoot.hidden=!0)}applyTheme(e){this.currentTheme=e;let t=this.runtime;t&&(this.configureMermaid(t),this.resetHydratedShells())}configureMermaid(e){e.initialize({startOnLoad:!1,flowchart:{defaultRenderer:`dagre-wrapper`,useMaxWidth:!0},class:{defaultRenderer:`dagre-wrapper`,useMaxWidth:!0},theme:this.currentTheme===`dark`?`dark`:`default`,themeVariables:this.currentTheme===`dark`?{background:`#161822`,clusterBkg:`#1a1c28`,edgeLabelBackground:`#161822`,lineColor:`#8b8ba0`,mainBkg:`#1c1e2c`,nodeBorder:`#383a50`,primaryBorderColor:`#383a50`,primaryColor:`#818cf8`,primaryTextColor:`#e2e2ea`,secondaryColor:`#1c1e2c`,tertiaryColor:`#161822`,titleColor:`#e2e2ea`}:{}})}ensureMermaid(){return this.runtime?(this.configureMermaid(this.runtime),Promise.resolve(this.runtime)):(this.loader||=e(()=>import(`./mermaid-runtime-BGlnoUXY.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.syncActiveShell()}async prepareHydrationBatch(){return this.ensureMermaid()}handlePrepareHydrationBatchError(e,t){console.warn(`[preview] Mermaid runtime failed to load:`,t)}async hydrateShell(e,t){if(!t||!e?.isConnected||this.isShellHydrated(e))return;let n=e.querySelector(`.mermaid-source`);n||(n=document.createElement(`span`),n.className=`mermaid-source`,n.hidden=!0,e.appendChild(n));let r=n.textContent??``;try{if(!r.trim()&&e.dataset.mermaidTarget){if(r=await this.fetchSource(e.dataset.mermaidTarget),!e.isConnected)return;n.textContent=r}if(!r.trim())throw Error(e.dataset.mermaidTarget?`Mermaid file is empty`:`Mermaid source is empty`);r=this.prepareSource(r),e.querySelector(`.mermaid-placeholder-card`)?.remove();let i=document.createElement(`div`);i.className=`mermaid mermaid-render-node`,i.id=e.dataset.mermaidKey||`mermaid-${Date.now()}`;let a=e.getAttribute(`data-source-line`),o=e.getAttribute(`data-source-line-end`);if(a&&i.setAttribute(`data-source-line`,a),o&&i.setAttribute(`data-source-line-end`,o),i.textContent=r,e.appendChild(i),await t.run({nodes:[i]}),!i.isConnected||e!==i.parentElement)return;this.enhanceDiagram(e,i),this.markShellHydrated(e)}catch(t){console.warn(`[preview] Mermaid render failed:`,t),e.querySelector(`:scope > .mermaid-toolbar`)?.remove(),e.querySelector(`:scope > .mermaid-frame`)?.remove(),e.querySelector(`:scope > .mermaid-render-node`)?.remove(),e.querySelector(`.mermaid-placeholder-card`)||n?.after(de(e.dataset.mermaidKey||`mermaid`,{label:e.dataset.mermaidLabel||`Mermaid diagram`,message:t instanceof Error?t.message:`Render failed`}))}}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(`
|
|
40
40
|
`),r=n.findIndex(e=>/^\s*gantt\b/.test(e));return r===-1?t:(n.splice(r+1,0,` todayMarker off`),n.join(`
|
|
41
|
-
`))}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.syncActiveShell();n&&!t.includes(n)&&t.push(n),t.length!==0&&t.forEach(e=>{this.disconnectShellResizeObserver(e),this.shellRefits.delete(e),e.removeAttribute(`data-mermaid-hydrated`),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(ge(e.dataset.mermaidKey||`mermaid`)),this.enqueueShell(e,{prioritize:!0})})}async renderExportSvgMarkup(e){let t=await this.ensureMermaid();try{return await Ke(t,e.querySelector(`.mermaid-source`)?.textContent??``)}finally{this.configureMermaid(t)}}async copyExportImage(e,t){try{let{pngFileName:n}=t(),r=await qe(await this.renderExportSvgMarkup(e));try{await Ye(r),this.renderer.toastController?.show?.(`Diagram copied`)}catch{Je(r,n),this.renderer.toastController?.show?.(`Clipboard image copy is unavailable here. Downloaded PNG instead.`)}}catch{this.renderer.toastController?.show?.(`Failed to copy diagram`)}}async downloadExportSvg(e,t){try{let{svgFileName:n}=t();Je(new Blob([await this.renderExportSvgMarkup(e)],{type:`image/svg+xml;charset=utf-8`}),n),this.renderer.toastController?.show?.(`Diagram download started`)}catch{this.renderer.toastController?.show?.(`Failed to download diagram`)}}enhanceDiagram(e,t){let n=t.querySelector(`svg`);if(!n){t.remove();return}let r=document.createElement(`div`);r.className=`mermaid-toolbar diagram-preview-toolbar`;let i=document.createElement(`div`);i.className=`diagram-preview-toolbar-group diagram-preview-toolbar-group--zoom`;let a=document.createElement(`div`);a.className=`diagram-preview-toolbar-group diagram-preview-toolbar-group--actions`;let o=this.createZoomButton(`−`,`Zoom out`),s=this.createZoomButton(`+`,`Zoom in`),c=this.createZoomButton(``,`Reset zoom`,{icon:`fit`}),l=this.createZoomButton(``,`Copy image`,{icon:`copy`}),u=this.createZoomButton(``,`Download SVG`,{icon:`download`}),d=this.createZoomButton(``,`Maximize diagram`,{icon:`maximize`});d.classList.add(`mermaid-maximize-btn`);let f=document.createElement(`span`);f.className=`mermaid-zoom-label diagram-preview-zoom-label`,f.setAttribute(`aria-live`,`polite`),i.append(o,f,c,s),a.append(l,u,d),r.append(i,a);let p=document.createElement(`div`);p.className=`mermaid-frame diagram-preview-frame`;let{width:m,height:h}=pe(n),g=P.default,_=1,v=null,y=null,b=null,S=!1,C=0,w=!1,T=null,ee=0,E=0,te=0,ne=0;n.style.display=`block`,n.style.margin=`0 auto`,n.style.maxWidth=`none`;let re=()=>He({currentFilePath:this.renderer.getSourceFilePath?.()??``,diagramKind:`mermaid`,sourceLine:e.getAttribute(`data-source-line`)||``,targetPath:e.dataset.mermaidTarget||``}),ie=()=>{let e=fe(p);if(!Number.isFinite(m)||m<=0||e.width<=0)return P.default;let t=e.width/m;return!Number.isFinite(t)||t<=0?P.default:x(t,P.min,P.max)},D=e=>{g=x(e,P.min,P.max),n.style.width=`${m*g}px`,n.style.height=`${h*g}px`,f.textContent=`${Math.round(g*100)}%`,o.disabled=g<=P.min,s.disabled=g>=P.max;let t=fe(p),r=m*g>t.width||h*g>t.height;p.classList.toggle(`is-pannable`,r),n.style.margin=r?`0`:`0 auto`},ae=()=>({x:p.scrollLeft+p.clientWidth/2,y:p.scrollTop+p.clientHeight/2}),O=(e,t,n)=>{if(e===0)return;let r=t/e;p.scrollLeft=n.x*r-p.clientWidth/2,p.scrollTop=n.y*r-p.clientHeight/2},oe=e=>{let t=x(e,P.min,P.max),n=g;if(t===n)return;let r=ae(),i=performance.now();v&&cancelAnimationFrame(v);let a=e=>{let o=x((e-i)/P.animationDurationMs,0,1),s=Se(o),c=n+(t-n)*s;if(D(c),O(n,c,r),o<1){v=requestAnimationFrame(a);return}v=null,D(t),O(n,t,r)};v=requestAnimationFrame(a)},se=e=>{S=!0,oe(g+e)},ce=({animate:e=!1}={})=>{if(_=ie(),S=!1,C=fe(p).width,e&&Math.abs(_-g)>.001){oe(_);return}v&&=(cancelAnimationFrame(v),null),D(_),p.scrollLeft=0,p.scrollTop=0},k=({force:t=!1}={})=>{y&&cancelAnimationFrame(y),b&&cancelAnimationFrame(b),y=requestAnimationFrame(()=>{b=requestAnimationFrame(()=>{b=requestAnimationFrame(()=>{if(b=null,y=null,!e.isConnected)return;let n=fe(p).width,r=Math.abs(n-C)>1;!t&&S||!t&&n>0&&C>0&&!r||ce()})})})};this.shellRefits.set(e,k),this.attachShellResizeObserver(e,p,()=>k()),o.addEventListener(`click`,()=>se(-P.step)),s.addEventListener(`click`,()=>se(P.step)),c.addEventListener(`click`,()=>{k({force:!0})}),l.addEventListener(`click`,()=>this.copyExportImage(e,re)),u.addEventListener(`click`,()=>this.downloadExportSvg(e,re));let le=()=>{let t=e.classList.contains(`is-maximized`);F(d,t?`restore`:`maximize`);let n=t?`Restore diagram size`:`Maximize diagram`;d.setAttribute(`aria-label`,n),d.title=n},ue=t=>{if(t){let t=this.syncActiveShell();if(t&&t!==e){this.restoreShellMount(t),t.classList.remove(`is-maximized`),this.activeMaximizedShell===t&&this.clearActiveShell(),this.shellRefits.get(t)?.();let e=t.querySelector(`.mermaid-maximize-btn`);e&&(F(e,`maximize`),e.setAttribute(`aria-label`,`Maximize diagram`),e.title=`Maximize diagram`)}this.mountShellInMaximizedRoot(e),e.classList.add(`is-maximized`),this.activeMaximizedShell=e,document.body.classList.add(`mermaid-maximized-open`),le(),k({force:!0});return}this.restoreShellMount(e),e.classList.remove(`is-maximized`),this.activeMaximizedShell===e&&this.clearActiveShell(),this.syncActiveShell()||document.body.classList.remove(`mermaid-maximized-open`),le(),k({force:!0})};le(),d.addEventListener(`click`,()=>{ue(!e.classList.contains(`is-maximized`))});let A=()=>{if(w){if(w=!1,p.classList.remove(`is-dragging`),window.removeEventListener(`pointerup`,A,!0),window.removeEventListener(`pointercancel`,A,!0),window.removeEventListener(`mouseup`,A,!0),window.removeEventListener(`touchend`,A,!0),window.removeEventListener(`touchcancel`,A,!0),window.removeEventListener(`blur`,A,!0),T!==null&&typeof p.releasePointerCapture==`function`)try{p.releasePointerCapture(T)}catch{}T=null}};p.addEventListener(`pointerdown`,e=>{if(!(e.button!==0||!p.classList.contains(`is-pannable`))){if(v&&=(cancelAnimationFrame(v),null),w=!0,T=e.pointerId,ee=e.clientX,E=e.clientY,te=p.scrollLeft,ne=p.scrollTop,p.classList.add(`is-dragging`),window.addEventListener(`pointerup`,A,!0),window.addEventListener(`pointercancel`,A,!0),window.addEventListener(`mouseup`,A,!0),window.addEventListener(`touchend`,A,!0),window.addEventListener(`touchcancel`,A,!0),window.addEventListener(`blur`,A,!0),typeof p.setPointerCapture==`function`)try{p.setPointerCapture(e.pointerId)}catch{}e.preventDefault()}}),p.addEventListener(`pointermove`,e=>{w&&(p.scrollLeft=te-(e.clientX-ee),p.scrollTop=ne-(e.clientY-E))}),p.addEventListener(`pointerup`,A),p.addEventListener(`pointercancel`,A),p.addEventListener(`lostpointercapture`,A),p.addEventListener(`mouseleave`,A),p.addEventListener(`mouseup`,A),p.addEventListener(`touchend`,A),p.addEventListener(`touchcancel`,A),p.appendChild(n);let j=e.querySelector(`.mermaid-source`);t.remove(),e.replaceChildren(),j&&(j.hidden=!0,e.appendChild(j)),e.append(r,p),k({force:!0})}scheduleActiveRefit(){let e=this.syncActiveShell();if(e){this.shellRefits.get(e)?.();return}let t=this.renderer.previewElement;t&&Array.from(t.querySelectorAll(`.mermaid-shell[data-mermaid-hydrated="true"]`)).forEach(e=>{this.shellRefits.get(e)?.()})}createZoomButton(e,t,{icon:n=``}={}){let r=document.createElement(`button`);return r.type=`button`,r.className=`mermaid-zoom-btn ui-preview-action`,r.setAttribute(`aria-label`,t),r.title=t,n?F(r,n):r.textContent=e,r}},$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.renderClient=n,this.svgCache=new Map,this.svgInflightRequests=new Map,this.shellRefits=new WeakMap,this.shellResizeObservers=new WeakMap,this.resizeObservers=new Set,this.activeMaximizedShell=null,this.maximizedRoot=null,this.resizeFrameId=null}destroy(){this.cancelHydration(),this.preservedShells.clear(),this.clearActiveShell(),this.resizeFrameId&&=(cancelAnimationFrame(this.resizeFrameId),null),this.disconnectResizeObservers(),this.maximizedRoot?.remove(),this.maximizedRoot=null}disconnectResizeObservers(){this.resizeObservers.forEach(e=>e.disconnect()),this.resizeObservers.clear(),this.shellResizeObservers=new WeakMap}disconnectShellResizeObserver(e){let t=this.shellResizeObservers.get(e);t&&(t.disconnect(),this.resizeObservers.delete(t),this.shellResizeObservers.delete(e))}attachShellResizeObserver(e,t,n){if(this.disconnectShellResizeObserver(e),typeof ResizeObserver!=`function`||!e?.isConnected||!(t instanceof HTMLElement))return;let r=new ResizeObserver(()=>n());r.observe(t),r.observe(e),this.shellResizeObservers.set(e,r),this.resizeObservers.add(r)}clearActiveShell(){this.activeMaximizedShell=null,this.maximizedRoot&&this.maximizedRoot.childElementCount===0&&(this.maximizedRoot.hidden=!0)}syncActiveShell(){return this.activeMaximizedShell?.isConnected&&this.activeMaximizedShell.classList.contains(`is-maximized`)?this.activeMaximizedShell:(this.clearActiveShell(),null)}scheduleActiveRefit(){this.resizeFrameId&&cancelAnimationFrame(this.resizeFrameId),this.resizeFrameId=requestAnimationFrame(()=>{this.resizeFrameId=null;let e=this.syncActiveShell();e&&this.shellRefits.get(e)?.()})}handleReconcile({restoredMaximizedShell:e}){e&&document.body.classList.add(`plantuml-maximized-open`),this.syncActiveShell()}ensureMaximizedRoot(){if(this.maximizedRoot?.isConnected&&this.maximizedRoot.parentElement===document.body)return this.maximizedRoot;let e=document.body.querySelector(`[data-plantuml-maximized-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.plantumlMaximizedRoot=`true`,e.className=`plantuml-maximized-root`,document.body.appendChild(e)),this.maximizedRoot=e,e}mountShellInMaximizedRoot(e){if(!e)return;let t=this.ensureMaximizedRoot();t.hidden=!1,e._plantumlRestoreParent=e.parentElement||null,e._plantumlRestoreNextSibling=e.nextSibling||null,t.appendChild(e)}restoreShellMount(e){if(!e)return;let t=e._plantumlRestoreParent,n=e._plantumlRestoreNextSibling;t?.isConnected&&(n?.parentElement===t?t.insertBefore(e,n):t.appendChild(e)),e._plantumlRestoreParent=null,e._plantumlRestoreNextSibling=null,this.maximizedRoot&&this.maximizedRoot.childElementCount===0&&(this.maximizedRoot.hidden=!0)}async hydrateShell(e){if(!e?.isConnected||this.isShellHydrated(e))return;let t=e.querySelector(`.plantuml-source`);t||(t=document.createElement(`span`),t.className=`plantuml-source`,t.hidden=!0,e.appendChild(t)),e.querySelector(`.plantuml-placeholder-card`)?.remove();try{let n=t.textContent??``;if(!n.trim()&&e.dataset.plantumlTarget){if(n=await this.fetchSource(e.dataset.plantumlTarget),!e.isConnected)return;t.textContent=n}if(!n.trim())throw Error(e.dataset.plantumlTarget?`PlantUML file is empty`:`PlantUML source is empty`);let r=await this.fetchSvg(n);if(!e.isConnected)return;this.enhanceDiagram(e,r),this.markShellHydrated(e)}catch(n){console.warn(`[preview] PlantUML render failed:`,n),e.querySelector(`:scope > .plantuml-toolbar`)?.remove(),e.querySelector(`:scope > .plantuml-frame`)?.remove(),e.querySelector(`.plantuml-placeholder-card`)||t?.after(ye(e.dataset.plantumlKey||`plantuml`,n instanceof Error?n.message:`Render failed`))}}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=be(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.disconnectShellResizeObserver(e),this.shellRefits.delete(e),this.activeMaximizedShell===e&&(this.restoreShellMount(e),this.clearActiveShell()),e.removeAttribute(`data-plantuml-hydrated`),e.removeAttribute(`data-plantuml-instance-id`),e.removeAttribute(`data-plantuml-queued`),e.classList.remove(`is-maximized`),this.syncActiveShell()||document.body.classList.remove(`plantuml-maximized-open`),e.querySelector(`:scope > .plantuml-toolbar`)?.remove(),e.querySelector(`:scope > .plantuml-frame`)?.remove(),e.querySelector(`.plantuml-placeholder-card`)||e.querySelector(`.plantuml-source`)?.after(ye(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 i=document.createElement(`div`);i.className=`plantuml-toolbar diagram-preview-toolbar`;let a=document.createElement(`div`);a.className=`diagram-preview-toolbar-group diagram-preview-toolbar-group--zoom`;let o=document.createElement(`div`);o.className=`diagram-preview-toolbar-group diagram-preview-toolbar-group--actions`;let s=document.createElement(`div`);s.className=`plantuml-frame diagram-preview-frame`;let c=this.createToolButton(`−`,`Zoom out`),l=this.createToolButton(`+`,`Zoom in`),u=this.createToolButton(``,`Reset zoom`,{icon:`fit`}),d=this.createToolButton(``,`Copy image`,{icon:`copy`}),f=this.createToolButton(``,`Download SVG`,{icon:`download`}),p=this.createToolButton(``,`Reload diagram`,{icon:`refresh`}),m=this.createToolButton(``,`Maximize diagram`,{icon:`maximize`});m.classList.add(`plantuml-maximize-btn`);let h=document.createElement(`span`);h.className=`plantuml-zoom-label diagram-preview-zoom-label`,h.setAttribute(`aria-live`,`polite`),a.append(c,h,u,l),o.append(d,f,p,m),i.append(a,o);let{width:g,height:_}=_e(r),v=N.default,y=1,b=null,S=null,C=null,w=!1,T=0,ee=!1,E=!1,te=null,ne=0,re=0,ie=0,D=0;r.style.display=`block`,r.style.margin=`0 auto`,r.style.maxWidth=`none`;let ae=()=>Ue(r),O=()=>He({currentFilePath:this.renderer.getSourceFilePath?.()??``,diagramKind:`plantuml`,sourceLine:e.getAttribute(`data-source-line`)||``,targetPath:e.dataset.plantumlTarget||``}),oe=()=>{let e=fe(s);return!Number.isFinite(g)||g<=0||e.width<=0?N.default:x(Math.min(N.default,e.width/g),N.min,N.max)},se=e=>{v=x(e,N.min,N.max),r.style.width=`${g*v}px`,r.style.height=`${_*v}px`,h.textContent=`${Math.round(v*100)}%`,c.disabled=v<=N.min,l.disabled=v>=N.max;let t=fe(s),n=g*v>t.width||_*v>t.height;s.classList.toggle(`is-pannable`,n)},ce=()=>({x:s.scrollLeft+s.clientWidth/2,y:s.scrollTop+s.clientHeight/2}),k=(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},le=e=>{let t=x(e,N.min,N.max),n=v;if(t===n)return;let r=ce(),i=performance.now();b&&cancelAnimationFrame(b);let a=e=>{let o=x((e-i)/N.animationDurationMs,0,1),s=Se(o),c=n+(t-n)*s;if(se(c),k(n,c,r),o<1){b=requestAnimationFrame(a);return}b=null,se(t),k(n,t,r)};b=requestAnimationFrame(a)},ue=e=>{w=!0,le(v+e)},A=({animate:e=!1}={})=>{if(y=oe(),w=!1,T=fe(s).width,e&&Math.abs(y-v)>.001){le(y);return}b&&=(cancelAnimationFrame(b),null),se(y),s.scrollLeft=0,s.scrollTop=0},j=({force:t=!1}={})=>{ee||=t,S&&cancelAnimationFrame(S),C&&cancelAnimationFrame(C),S=requestAnimationFrame(()=>{C=requestAnimationFrame(()=>{C=requestAnimationFrame(()=>{if(C=null,S=null,!e.isConnected)return;let t=ee;ee=!1;let n=fe(s).width,r=Math.abs(n-T)>1;!t&&w||!t&&n>0&&T>0&&!r||A()})})})};this.shellRefits.set(e,j),this.attachShellResizeObserver(e,s,()=>j()),c.addEventListener(`click`,()=>ue(-N.step)),l.addEventListener(`click`,()=>ue(N.step)),u.addEventListener(`click`,()=>{j({force:!0})}),d.addEventListener(`click`,async()=>{try{let{pngFileName:e}=O(),t=await qe(ae());try{await Ye(t),this.renderer.toastController?.show?.(`Diagram copied`)}catch{Je(t,e),this.renderer.toastController?.show?.(`Clipboard image copy is unavailable here. Downloaded PNG instead.`)}}catch{this.renderer.toastController?.show?.(`Failed to copy diagram`)}}),f.addEventListener(`click`,()=>{try{let{svgFileName:e}=O();Je(new Blob([ae()],{type:`image/svg+xml;charset=utf-8`}),e),this.renderer.toastController?.show?.(`Diagram download started`)}catch{this.renderer.toastController?.show?.(`Failed to download diagram`)}});let de=()=>{let t=e.classList.contains(`is-maximized`);F(m,t?`restore`:`maximize`);let n=t?`Restore diagram size`:`Maximize diagram`;m.setAttribute(`aria-label`,n),m.title=n},pe=t=>{if(t){let t=this.syncActiveShell();if(t&&t!==e){this.restoreShellMount(t),t.classList.remove(`is-maximized`),this.activeMaximizedShell===t&&this.clearActiveShell(),this.shellRefits.get(t)?.();let e=t.querySelector(`.plantuml-maximize-btn`);e&&(F(e,`maximize`),e.setAttribute(`aria-label`,`Maximize diagram`),e.title=`Maximize diagram`)}this.mountShellInMaximizedRoot(e),e.classList.add(`is-maximized`),this.activeMaximizedShell=e,document.body.classList.add(`plantuml-maximized-open`),de(),j({force:!0});return}this.restoreShellMount(e),e.classList.remove(`is-maximized`),this.activeMaximizedShell===e&&this.clearActiveShell(),this.syncActiveShell()||document.body.classList.remove(`plantuml-maximized-open`),de(),j({force:!0})};p.addEventListener(`click`,()=>{this.resetShell(e,{clearCache:!0,message:`Refreshing…`}),this.enqueueShell(e,{prioritize:!0})}),de(),m.addEventListener(`click`,()=>{pe(!e.classList.contains(`is-maximized`))});let M=()=>{if(E){if(E=!1,s.classList.remove(`is-dragging`),window.removeEventListener(`pointerup`,M,!0),window.removeEventListener(`pointercancel`,M,!0),window.removeEventListener(`mouseup`,M,!0),window.removeEventListener(`touchend`,M,!0),window.removeEventListener(`touchcancel`,M,!0),window.removeEventListener(`blur`,M,!0),te!==null&&typeof s.releasePointerCapture==`function`)try{s.releasePointerCapture(te)}catch{}te=null}};s.addEventListener(`pointerdown`,e=>{if(!(e.button!==0||!s.classList.contains(`is-pannable`))){if(b&&=(cancelAnimationFrame(b),null),E=!0,te=e.pointerId,ne=e.clientX,re=e.clientY,ie=s.scrollLeft,D=s.scrollTop,s.classList.add(`is-dragging`),window.addEventListener(`pointerup`,M,!0),window.addEventListener(`pointercancel`,M,!0),window.addEventListener(`mouseup`,M,!0),window.addEventListener(`touchend`,M,!0),window.addEventListener(`touchcancel`,M,!0),window.addEventListener(`blur`,M,!0),typeof s.setPointerCapture==`function`)try{s.setPointerCapture(e.pointerId)}catch{}e.preventDefault()}}),s.addEventListener(`pointermove`,e=>{E&&(s.scrollLeft=ie-(e.clientX-ne),s.scrollTop=D-(e.clientY-re))}),s.addEventListener(`pointerup`,M),s.addEventListener(`pointercancel`,M),s.addEventListener(`lostpointercapture`,M),s.addEventListener(`mouseleave`,M),s.addEventListener(`mouseup`,M),s.addEventListener(`touchend`,M),s.addEventListener(`touchcancel`,M),s.appendChild(r);let me=e.querySelector(`.plantuml-source`);e.replaceChildren(),me&&(me.hidden=!0,e.appendChild(me)),e.append(i,s),y=oe(),se(y)}createToolButton(e,t,{icon:n=``}={}){let r=document.createElement(`button`);return r.type=`button`,r.className=`plantuml-tool-btn ui-preview-action`,r.setAttribute(`aria-label`,t),r.title=t,n?F(r,n):r.textContent=e,r}};function et(){return new Worker(new URL(``+new URL(`preview-render-worker-yfayDDfY.js`,import.meta.url).href,``+import.meta.url),{type:`module`})}var tt=class{constructor({attachmentApiPath:t=`/api/attachment`,cancelIdleRenderFn:n=xe,compilePreviewDocumentLoader:r=()=>e(()=>import(`./preview-render-compiler-kjMajWKn.js`),__vite__mapDeps([22,23,24,4,25,26]),import.meta.url),createWorkerFn:i=et,getFileList:a,getSourceFilePath:o=null,idleTimeoutMs:s=500,requestIdleRenderFn:c=M}={}){this.attachmentApiPath=t,this.cancelIdleRenderFn=n,this.compilePreviewDocumentLoader=r,this.createWorkerFn=i,this.getFileList=a,this.getSourceFilePath=o,this.idleTimeoutMs=s,this.requestIdleRenderFn=c,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?.()??``})})}let{compilePreviewDocument:i}=await this.compilePreviewDocumentLoader();return i({attachmentApiPath:this.attachmentApiPath,fileList:this.getFileList?.()??[],frontmatterCollapsed:n,frontmatterInteractive:r,markdownText:e,sourceFilePath:this.getSourceFilePath?.()??``})}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)}},nt=class{constructor({cancelAnimationFrameFn:e=e=>cancelAnimationFrame(e),cancelIdleRenderFn:t=xe,clearTimeoutFn:n=e=>clearTimeout(e),getRenderProfileFn:i=r,idleTimeoutMs:a=500,requestAnimationFrameFn:o=e=>requestAnimationFrame(e),requestIdleRenderFn:s=M,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()}},rt=class{constructor({getContent:e,getFileList:t,loadFileSource:n=null,getSourceFilePath:i,onAfterRenderCommit:a,onBeforeRenderCommit:o,onPreviewLayoutChange:s,onRenderComplete:c,outlineController:l,plantUmlRenderClient:u=null,previewContainer:d,previewElement:f,toastController:p=null}){this.getContent=e,this.getFileList=t,this.loadFileSource=n,this.getSourceFilePath=i,this.onAfterRenderCommit=a,this.onBeforeRenderCommit=o,this.onPreviewLayoutChange=s,this.onRenderComplete=c,this.outlineController=l,this.plantUmlRenderClient=u,this.previewContainer=d,this.previewElement=f,this.toastController=p,this.renderHost=null,this.pendingRenderVersion=0,this.activeRenderVersion=0,this.readyRenderVersion=0,this.currentStats=null,this.isLargeDocument=!1,this.hydrationPaused=!1,this.frontmatterCollapsed=!1,this.handlePreviewClick=e=>{if(e.target.closest(`.frontmatter-toggle`)){e.preventDefault(),this.frontmatterCollapsed=!this.frontmatterCollapsed,this.applyFrontmatterState(),this.handleFrontmatterLayoutChange();return}let t=e.target.closest(`.mermaid-placeholder-btn`);if(t){let n=t.closest(`.mermaid-shell`);if(!n)return;e.preventDefault(),this.enqueueMermaidShell(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(),this.enqueuePlantUmlShell(t,{prioritize:!0})}},this.handleWindowResize=()=>{this.mermaidHydrator.scheduleActiveRefit(),this.plantUmlHydrator.scheduleActiveRefit()},this.mermaidHydrator=new Qe(this,{loadFileSource:n}),this.plantUmlHydrator=new $e(this,{loadFileSource:n,renderClient:u}),this.renderScheduler=new nt({getRenderProfileFn:r}),this.renderExecutor=new tt({attachmentApiPath:E(`/attachment`),getFileList:()=>this.getFileList?.()??[],getSourceFilePath:()=>this.getSourceFilePath?.()??``,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.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.cancelScheduledRender(),this.cancelMermaidHydration(),this.cancelPlantUmlHydration(),this.mermaidHydrator.clearPreservedShells(),this.plantUmlHydrator.clearPreservedShells(),this.clearActivePlantUmlShell(),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.resetWorker(`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)}configureMermaid(e){this.mermaidHydrator.configureMermaid(e)}ensureMermaid(){return this.mermaidHydrator.ensureMermaid()}queueRender(){let e=this.getContent();this.cancelScheduledRender(),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.compilePreview(e,t);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.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)}cancelScheduledRender(){this.renderScheduler.cancel()}cancelMermaidHydration(){this.mermaidHydrator.cancelHydration()}cancelPlantUmlHydration(){this.plantUmlHydrator.cancelHydration()}clearActivePlantUmlShell(){this.plantUmlHydrator.clearActiveShell()}scheduleActiveMermaidRefit(){this.mermaidHydrator.scheduleActiveRefit()}syncActivePlantUmlShell(){return this.plantUmlHydrator.syncActiveShell()}scheduleActivePlantUmlRefit(){this.plantUmlHydrator.scheduleActiveRefit()}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()}resetWorker(e,{disable:t=!1}={}){this.renderExecutor.reset(e,{disable:t})}scheduleWorkerPrewarm({timeout:e=500}={}){this.renderExecutor.schedulePrewarm({timeout:e})}async compilePreview(e,t){return this.renderExecutor.compile(e,t,{frontmatterCollapsed:this.frontmatterCollapsed,frontmatterInteractive:!0})}commitBaseRender({html:e,stats:t},n){this.activeRenderVersion=n,this.readyRenderVersion=0,this.currentStats=t,this.isLargeDocument=i(t),this.cancelMermaidHydration(),this.cancelPlantUmlHydration(),document.body.classList.remove(`mermaid-maximized-open`),document.body.classList.remove(`plantuml-maximized-open`),this.preserveHydratedMermaidsForCommit(),this.preserveHydratedPlantUmlsForCommit(),this.onBeforeRenderCommit?.(this.previewElement);let r=this.ensureRenderHost();this.normalizePreviewChildren(r),r&&(r.innerHTML=e),this.applyFrontmatterState(),this.reconcileHydratedMermaids(),this.reconcileHydratedPlantUmls(),this.setPhase(`base`),this.outlineController.refresh(),this.onAfterRenderCommit?.(this.previewElement,{...t,isLargeDocument:this.isLargeDocument,renderVersion:n});let a=this.setupMermaidHydration(n),o=this.setupPlantUmlHydration(n);a===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})}preserveHydratedMermaidsForCommit(){this.mermaidHydrator.preserveHydratedShellsForCommit()}preserveHydratedPlantUmlsForCommit(){this.plantUmlHydrator.preserveHydratedShellsForCommit()}reconcileHydratedMermaids(){this.mermaidHydrator.reconcileHydratedShells()}reconcileHydratedPlantUmls(){this.plantUmlHydrator.reconcileHydratedShells()}syncPreservedMermaidShell(e,t){this.mermaidHydrator.syncPreservedShell(e,t)}syncPreservedPlantUmlShell(e,t){this.plantUmlHydrator.syncPreservedShell(e,t)}setupMermaidHydration(e){return this.mermaidHydrator.setupHydration(e)}hydrateVisibleMermaids(){this.mermaidHydrator.hydrateVisibleShells()}enqueueMermaidShell(e,{prioritize:t=!1}={}){this.mermaidHydrator.enqueueShell(e,{prioritize:t})}scheduleMermaidHydration(){this.mermaidHydrator.scheduleHydration()}async flushMermaidHydrationQueue(){await this.mermaidHydrator.flushHydrationQueue()}async hydrateMermaidShell(e,t){await this.mermaidHydrator.hydrateShell(e,t)}resetHydratedMermaids(){this.mermaidHydrator.resetHydratedShells()}setupPlantUmlHydration(e){return this.plantUmlHydrator.setupHydration(e)}hydrateVisiblePlantUmls(){this.plantUmlHydrator.hydrateVisibleShells()}enqueuePlantUmlShell(e,{prioritize:t=!1}={}){this.plantUmlHydrator.enqueueShell(e,{prioritize:t})}schedulePlantUmlHydration(){this.plantUmlHydrator.scheduleHydration()}async flushPlantUmlHydrationQueue(){await this.plantUmlHydrator.flushHydrationQueue()}async hydratePlantUmlShell(e){await this.plantUmlHydrator.hydrateShell(e)}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 fetchPlantUmlSvg(e){return this.plantUmlHydrator.fetchSvg(e)}async fetchPlantUmlSource(e){return this.plantUmlHydrator.fetchSource(e)}async fetchMermaidSource(e){return this.mermaidHydrator.fetchSource(e)}resetPlantUmlShell(e,{clearCache:t=!1,message:n=`Renders server-side when visible`}={}){this.plantUmlHydrator.resetShell(e,{clearCache:t,message:n})}enhancePlantUmlDiagram(e,t){this.plantUmlHydrator.enhanceDiagram(e,t)}enhanceMermaidDiagram(e,t){this.mermaidHydrator.enhanceDiagram(e,t)}createMermaidZoomButton(e,t){return this.mermaidHydrator.createZoomButton(e,t)}createPlantUmlToolButton(e,t){return this.plantUmlHydrator.createToolButton(e,t)}};async function it(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,onFileSelect:t=>e.handleFileSelection(t,{closeSidebarOnMobile:!0,revealInTree:!0})}),e.quickSwitcher}async function at(e){try{(await it(e)).toggle()}catch{}}var ot=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:S,setSessionLoadToken:C,setSidebarTab:w,setSidebarVisibility:T,setCurrentFilePath:ee,showGitCommit:E,showGitDiff:te,showGitFileHistory:ne,showGitFilePreview:re,showGitHistory:ie,syncMainChrome:D,videoEmbed:ae,workspaceCoordinator:O,layoutController:oe}){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=S,this.setSessionLoadToken=C,this.setSidebarTab=w,this.setSidebarVisibility=T??(()=>{}),this.setCurrentFilePath=ee,this.showGitCommit=E,this.showGitDiff=te,this.showGitFileHistory=ne,this.showGitFilePreview=re,this.showGitHistory=ie,this.syncMainChrome=D,this.videoEmbed=ae,this.workspaceCoordinator=O,this.layoutController=oe,this.pendingTreeRevealPath=null}async handleHashChange(){if(!this.getIsTabActive())return;let e=this.navigation.getHashRoute();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.setSidebarTab(`files`),await this.openFile(e.filePath,{drawioMode:e.drawioMode||null}),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;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})}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})}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()}};function I(e){let t=String(e??``).trim().replace(/\\/g,`/`).replace(/^\/+/u,``).split(`/`).map(e=>e.trim()).filter(Boolean);return t.some(e=>e===`.`||e===`..`)?``:t.join(`/`)}function L(e,t){let n=I(e),r=I(t);return n?r?`${n}/${r}`:n:r}function st(e,t){return e.toLowerCase().endsWith(t.toLowerCase())?e:`${e}${t}`}function ct(e){return`# ${c(String(e??``).split(`/`).pop()||``)||`Untitled`}\n\n`}function lt(e){let t=I(e),n=l(t)?t:`${t}.base`;return{content:[`views:`,` - type: table`,` name: Table`,` order:`,` - file.name`,``].join(`
|
|
41
|
+
`))}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.syncActiveShell();n&&!t.includes(n)&&t.push(n),t.length!==0&&t.forEach(e=>{this.disconnectShellResizeObserver(e),this.shellRefits.delete(e),e.removeAttribute(`data-mermaid-hydrated`),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(ge(e.dataset.mermaidKey||`mermaid`)),this.enqueueShell(e,{prioritize:!0})})}async renderExportSvgMarkup(e){let t=await this.ensureMermaid();try{return await Ke(t,e.querySelector(`.mermaid-source`)?.textContent??``)}finally{this.configureMermaid(t)}}async copyExportImage(e,t){try{let{pngFileName:n}=t(),r=await qe(await this.renderExportSvgMarkup(e));try{await Ye(r),this.renderer.toastController?.show?.(`Diagram copied`)}catch{Je(r,n),this.renderer.toastController?.show?.(`Clipboard image copy is unavailable here. Downloaded PNG instead.`)}}catch{this.renderer.toastController?.show?.(`Failed to copy diagram`)}}async downloadExportSvg(e,t){try{let{svgFileName:n}=t();Je(new Blob([await this.renderExportSvgMarkup(e)],{type:`image/svg+xml;charset=utf-8`}),n),this.renderer.toastController?.show?.(`Diagram download started`)}catch{this.renderer.toastController?.show?.(`Failed to download diagram`)}}enhanceDiagram(e,t){let n=t.querySelector(`svg`);if(!n){t.remove();return}let r=document.createElement(`div`);r.className=`mermaid-toolbar diagram-preview-toolbar`;let i=document.createElement(`div`);i.className=`diagram-preview-toolbar-group diagram-preview-toolbar-group--zoom`;let a=document.createElement(`div`);a.className=`diagram-preview-toolbar-group diagram-preview-toolbar-group--actions`;let o=this.createZoomButton(`−`,`Zoom out`),s=this.createZoomButton(`+`,`Zoom in`),c=this.createZoomButton(``,`Reset zoom`,{icon:`fit`}),l=this.createZoomButton(``,`Copy image`,{icon:`copy`}),u=this.createZoomButton(``,`Download SVG`,{icon:`download`}),d=this.createZoomButton(``,`Maximize diagram`,{icon:`maximize`});d.classList.add(`mermaid-maximize-btn`);let f=document.createElement(`span`);f.className=`mermaid-zoom-label diagram-preview-zoom-label`,f.setAttribute(`aria-live`,`polite`),i.append(o,f,c,s),a.append(l,u,d),r.append(i,a);let p=document.createElement(`div`);p.className=`mermaid-frame diagram-preview-frame`;let{width:m,height:h}=pe(n),g=P.default,_=1,v=null,y=null,b=null,S=!1,C=0,w=!1,T=null,ee=0,E=0,te=0,ne=0;n.style.display=`block`,n.style.margin=`0 auto`,n.style.maxWidth=`none`;let re=()=>He({currentFilePath:this.renderer.getSourceFilePath?.()??``,diagramKind:`mermaid`,sourceLine:e.getAttribute(`data-source-line`)||``,targetPath:e.dataset.mermaidTarget||``}),ie=()=>{let e=fe(p);if(!Number.isFinite(m)||m<=0||e.width<=0)return P.default;let t=e.width/m;return!Number.isFinite(t)||t<=0?P.default:x(t,P.min,P.max)},D=e=>{g=x(e,P.min,P.max),n.style.width=`${m*g}px`,n.style.height=`${h*g}px`,f.textContent=`${Math.round(g*100)}%`,o.disabled=g<=P.min,s.disabled=g>=P.max;let t=fe(p),r=m*g>t.width||h*g>t.height;p.classList.toggle(`is-pannable`,r),n.style.margin=r?`0`:`0 auto`},ae=()=>({x:p.scrollLeft+p.clientWidth/2,y:p.scrollTop+p.clientHeight/2}),O=(e,t,n)=>{if(e===0)return;let r=t/e;p.scrollLeft=n.x*r-p.clientWidth/2,p.scrollTop=n.y*r-p.clientHeight/2},oe=e=>{let t=x(e,P.min,P.max),n=g;if(t===n)return;let r=ae(),i=performance.now();v&&cancelAnimationFrame(v);let a=e=>{let o=x((e-i)/P.animationDurationMs,0,1),s=Se(o),c=n+(t-n)*s;if(D(c),O(n,c,r),o<1){v=requestAnimationFrame(a);return}v=null,D(t),O(n,t,r)};v=requestAnimationFrame(a)},se=e=>{S=!0,oe(g+e)},ce=({animate:e=!1}={})=>{if(_=ie(),S=!1,C=fe(p).width,e&&Math.abs(_-g)>.001){oe(_);return}v&&=(cancelAnimationFrame(v),null),D(_),p.scrollLeft=0,p.scrollTop=0},k=({force:t=!1}={})=>{y&&cancelAnimationFrame(y),b&&cancelAnimationFrame(b),y=requestAnimationFrame(()=>{b=requestAnimationFrame(()=>{b=requestAnimationFrame(()=>{if(b=null,y=null,!e.isConnected)return;let n=fe(p).width,r=Math.abs(n-C)>1;!t&&S||!t&&n>0&&C>0&&!r||ce()})})})};this.shellRefits.set(e,k),this.attachShellResizeObserver(e,p,()=>k()),o.addEventListener(`click`,()=>se(-P.step)),s.addEventListener(`click`,()=>se(P.step)),c.addEventListener(`click`,()=>{k({force:!0})}),l.addEventListener(`click`,()=>this.copyExportImage(e,re)),u.addEventListener(`click`,()=>this.downloadExportSvg(e,re));let le=()=>{let t=e.classList.contains(`is-maximized`);F(d,t?`restore`:`maximize`);let n=t?`Restore diagram size`:`Maximize diagram`;d.setAttribute(`aria-label`,n),d.title=n},ue=t=>{if(t){let t=this.syncActiveShell();if(t&&t!==e){this.restoreShellMount(t),t.classList.remove(`is-maximized`),this.activeMaximizedShell===t&&this.clearActiveShell(),this.shellRefits.get(t)?.();let e=t.querySelector(`.mermaid-maximize-btn`);e&&(F(e,`maximize`),e.setAttribute(`aria-label`,`Maximize diagram`),e.title=`Maximize diagram`)}this.mountShellInMaximizedRoot(e),e.classList.add(`is-maximized`),this.activeMaximizedShell=e,document.body.classList.add(`mermaid-maximized-open`),le(),k({force:!0});return}this.restoreShellMount(e),e.classList.remove(`is-maximized`),this.activeMaximizedShell===e&&this.clearActiveShell(),this.syncActiveShell()||document.body.classList.remove(`mermaid-maximized-open`),le(),k({force:!0})};le(),d.addEventListener(`click`,()=>{ue(!e.classList.contains(`is-maximized`))});let A=()=>{if(w){if(w=!1,p.classList.remove(`is-dragging`),window.removeEventListener(`pointerup`,A,!0),window.removeEventListener(`pointercancel`,A,!0),window.removeEventListener(`mouseup`,A,!0),window.removeEventListener(`touchend`,A,!0),window.removeEventListener(`touchcancel`,A,!0),window.removeEventListener(`blur`,A,!0),T!==null&&typeof p.releasePointerCapture==`function`)try{p.releasePointerCapture(T)}catch{}T=null}};p.addEventListener(`pointerdown`,e=>{if(!(e.button!==0||!p.classList.contains(`is-pannable`))){if(v&&=(cancelAnimationFrame(v),null),w=!0,T=e.pointerId,ee=e.clientX,E=e.clientY,te=p.scrollLeft,ne=p.scrollTop,p.classList.add(`is-dragging`),window.addEventListener(`pointerup`,A,!0),window.addEventListener(`pointercancel`,A,!0),window.addEventListener(`mouseup`,A,!0),window.addEventListener(`touchend`,A,!0),window.addEventListener(`touchcancel`,A,!0),window.addEventListener(`blur`,A,!0),typeof p.setPointerCapture==`function`)try{p.setPointerCapture(e.pointerId)}catch{}e.preventDefault()}}),p.addEventListener(`pointermove`,e=>{w&&(p.scrollLeft=te-(e.clientX-ee),p.scrollTop=ne-(e.clientY-E))}),p.addEventListener(`pointerup`,A),p.addEventListener(`pointercancel`,A),p.addEventListener(`lostpointercapture`,A),p.addEventListener(`mouseleave`,A),p.addEventListener(`mouseup`,A),p.addEventListener(`touchend`,A),p.addEventListener(`touchcancel`,A),p.appendChild(n);let j=e.querySelector(`.mermaid-source`);t.remove(),e.replaceChildren(),j&&(j.hidden=!0,e.appendChild(j)),e.append(r,p),k({force:!0})}scheduleActiveRefit(){let e=this.syncActiveShell();if(e){this.shellRefits.get(e)?.();return}let t=this.renderer.previewElement;t&&Array.from(t.querySelectorAll(`.mermaid-shell[data-mermaid-hydrated="true"]`)).forEach(e=>{this.shellRefits.get(e)?.()})}createZoomButton(e,t,{icon:n=``}={}){let r=document.createElement(`button`);return r.type=`button`,r.className=`mermaid-zoom-btn ui-preview-action`,r.setAttribute(`aria-label`,t),r.title=t,n?F(r,n):r.textContent=e,r}},$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.renderClient=n,this.svgCache=new Map,this.svgInflightRequests=new Map,this.shellRefits=new WeakMap,this.shellResizeObservers=new WeakMap,this.resizeObservers=new Set,this.activeMaximizedShell=null,this.maximizedRoot=null,this.resizeFrameId=null}destroy(){this.cancelHydration(),this.preservedShells.clear(),this.clearActiveShell(),this.resizeFrameId&&=(cancelAnimationFrame(this.resizeFrameId),null),this.disconnectResizeObservers(),this.maximizedRoot?.remove(),this.maximizedRoot=null}disconnectResizeObservers(){this.resizeObservers.forEach(e=>e.disconnect()),this.resizeObservers.clear(),this.shellResizeObservers=new WeakMap}disconnectShellResizeObserver(e){let t=this.shellResizeObservers.get(e);t&&(t.disconnect(),this.resizeObservers.delete(t),this.shellResizeObservers.delete(e))}attachShellResizeObserver(e,t,n){if(this.disconnectShellResizeObserver(e),typeof ResizeObserver!=`function`||!e?.isConnected||!(t instanceof HTMLElement))return;let r=new ResizeObserver(()=>n());r.observe(t),r.observe(e),this.shellResizeObservers.set(e,r),this.resizeObservers.add(r)}clearActiveShell(){this.activeMaximizedShell=null,this.maximizedRoot&&this.maximizedRoot.childElementCount===0&&(this.maximizedRoot.hidden=!0)}syncActiveShell(){return this.activeMaximizedShell?.isConnected&&this.activeMaximizedShell.classList.contains(`is-maximized`)?this.activeMaximizedShell:(this.clearActiveShell(),null)}scheduleActiveRefit(){this.resizeFrameId&&cancelAnimationFrame(this.resizeFrameId),this.resizeFrameId=requestAnimationFrame(()=>{this.resizeFrameId=null;let e=this.syncActiveShell();e&&this.shellRefits.get(e)?.()})}handleReconcile({restoredMaximizedShell:e}){e&&document.body.classList.add(`plantuml-maximized-open`),this.syncActiveShell()}ensureMaximizedRoot(){if(this.maximizedRoot?.isConnected&&this.maximizedRoot.parentElement===document.body)return this.maximizedRoot;let e=document.body.querySelector(`[data-plantuml-maximized-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.plantumlMaximizedRoot=`true`,e.className=`plantuml-maximized-root`,document.body.appendChild(e)),this.maximizedRoot=e,e}mountShellInMaximizedRoot(e){if(!e)return;let t=this.ensureMaximizedRoot();t.hidden=!1,e._plantumlRestoreParent=e.parentElement||null,e._plantumlRestoreNextSibling=e.nextSibling||null,t.appendChild(e)}restoreShellMount(e){if(!e)return;let t=e._plantumlRestoreParent,n=e._plantumlRestoreNextSibling;t?.isConnected&&(n?.parentElement===t?t.insertBefore(e,n):t.appendChild(e)),e._plantumlRestoreParent=null,e._plantumlRestoreNextSibling=null,this.maximizedRoot&&this.maximizedRoot.childElementCount===0&&(this.maximizedRoot.hidden=!0)}async hydrateShell(e){if(!e?.isConnected||this.isShellHydrated(e))return;let t=e.querySelector(`.plantuml-source`);t||(t=document.createElement(`span`),t.className=`plantuml-source`,t.hidden=!0,e.appendChild(t)),e.querySelector(`.plantuml-placeholder-card`)?.remove();try{let n=t.textContent??``;if(!n.trim()&&e.dataset.plantumlTarget){if(n=await this.fetchSource(e.dataset.plantumlTarget),!e.isConnected)return;t.textContent=n}if(!n.trim())throw Error(e.dataset.plantumlTarget?`PlantUML file is empty`:`PlantUML source is empty`);let r=await this.fetchSvg(n);if(!e.isConnected)return;this.enhanceDiagram(e,r),this.markShellHydrated(e)}catch(n){console.warn(`[preview] PlantUML render failed:`,n),e.querySelector(`:scope > .plantuml-toolbar`)?.remove(),e.querySelector(`:scope > .plantuml-frame`)?.remove(),e.querySelector(`.plantuml-placeholder-card`)||t?.after(ye(e.dataset.plantumlKey||`plantuml`,n instanceof Error?n.message:`Render failed`))}}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=be(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.disconnectShellResizeObserver(e),this.shellRefits.delete(e),this.activeMaximizedShell===e&&(this.restoreShellMount(e),this.clearActiveShell()),e.removeAttribute(`data-plantuml-hydrated`),e.removeAttribute(`data-plantuml-instance-id`),e.removeAttribute(`data-plantuml-queued`),e.classList.remove(`is-maximized`),this.syncActiveShell()||document.body.classList.remove(`plantuml-maximized-open`),e.querySelector(`:scope > .plantuml-toolbar`)?.remove(),e.querySelector(`:scope > .plantuml-frame`)?.remove(),e.querySelector(`.plantuml-placeholder-card`)||e.querySelector(`.plantuml-source`)?.after(ye(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 i=document.createElement(`div`);i.className=`plantuml-toolbar diagram-preview-toolbar`;let a=document.createElement(`div`);a.className=`diagram-preview-toolbar-group diagram-preview-toolbar-group--zoom`;let o=document.createElement(`div`);o.className=`diagram-preview-toolbar-group diagram-preview-toolbar-group--actions`;let s=document.createElement(`div`);s.className=`plantuml-frame diagram-preview-frame`;let c=this.createToolButton(`−`,`Zoom out`),l=this.createToolButton(`+`,`Zoom in`),u=this.createToolButton(``,`Reset zoom`,{icon:`fit`}),d=this.createToolButton(``,`Copy image`,{icon:`copy`}),f=this.createToolButton(``,`Download SVG`,{icon:`download`}),p=this.createToolButton(``,`Reload diagram`,{icon:`refresh`}),m=this.createToolButton(``,`Maximize diagram`,{icon:`maximize`});m.classList.add(`plantuml-maximize-btn`);let h=document.createElement(`span`);h.className=`plantuml-zoom-label diagram-preview-zoom-label`,h.setAttribute(`aria-live`,`polite`),a.append(c,h,u,l),o.append(d,f,p,m),i.append(a,o);let{width:g,height:_}=_e(r),v=N.default,y=1,b=null,S=null,C=null,w=!1,T=0,ee=!1,E=!1,te=null,ne=0,re=0,ie=0,D=0;r.style.display=`block`,r.style.margin=`0 auto`,r.style.maxWidth=`none`;let ae=()=>Ue(r),O=()=>He({currentFilePath:this.renderer.getSourceFilePath?.()??``,diagramKind:`plantuml`,sourceLine:e.getAttribute(`data-source-line`)||``,targetPath:e.dataset.plantumlTarget||``}),oe=()=>{let e=fe(s);return!Number.isFinite(g)||g<=0||e.width<=0?N.default:x(Math.min(N.default,e.width/g),N.min,N.max)},se=e=>{v=x(e,N.min,N.max),r.style.width=`${g*v}px`,r.style.height=`${_*v}px`,h.textContent=`${Math.round(v*100)}%`,c.disabled=v<=N.min,l.disabled=v>=N.max;let t=fe(s),n=g*v>t.width||_*v>t.height;s.classList.toggle(`is-pannable`,n)},ce=()=>({x:s.scrollLeft+s.clientWidth/2,y:s.scrollTop+s.clientHeight/2}),k=(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},le=e=>{let t=x(e,N.min,N.max),n=v;if(t===n)return;let r=ce(),i=performance.now();b&&cancelAnimationFrame(b);let a=e=>{let o=x((e-i)/N.animationDurationMs,0,1),s=Se(o),c=n+(t-n)*s;if(se(c),k(n,c,r),o<1){b=requestAnimationFrame(a);return}b=null,se(t),k(n,t,r)};b=requestAnimationFrame(a)},ue=e=>{w=!0,le(v+e)},A=({animate:e=!1}={})=>{if(y=oe(),w=!1,T=fe(s).width,e&&Math.abs(y-v)>.001){le(y);return}b&&=(cancelAnimationFrame(b),null),se(y),s.scrollLeft=0,s.scrollTop=0},j=({force:t=!1}={})=>{ee||=t,S&&cancelAnimationFrame(S),C&&cancelAnimationFrame(C),S=requestAnimationFrame(()=>{C=requestAnimationFrame(()=>{C=requestAnimationFrame(()=>{if(C=null,S=null,!e.isConnected)return;let t=ee;ee=!1;let n=fe(s).width,r=Math.abs(n-T)>1;!t&&w||!t&&n>0&&T>0&&!r||A()})})})};this.shellRefits.set(e,j),this.attachShellResizeObserver(e,s,()=>j()),c.addEventListener(`click`,()=>ue(-N.step)),l.addEventListener(`click`,()=>ue(N.step)),u.addEventListener(`click`,()=>{j({force:!0})}),d.addEventListener(`click`,async()=>{try{let{pngFileName:e}=O(),t=await qe(ae());try{await Ye(t),this.renderer.toastController?.show?.(`Diagram copied`)}catch{Je(t,e),this.renderer.toastController?.show?.(`Clipboard image copy is unavailable here. Downloaded PNG instead.`)}}catch{this.renderer.toastController?.show?.(`Failed to copy diagram`)}}),f.addEventListener(`click`,()=>{try{let{svgFileName:e}=O();Je(new Blob([ae()],{type:`image/svg+xml;charset=utf-8`}),e),this.renderer.toastController?.show?.(`Diagram download started`)}catch{this.renderer.toastController?.show?.(`Failed to download diagram`)}});let de=()=>{let t=e.classList.contains(`is-maximized`);F(m,t?`restore`:`maximize`);let n=t?`Restore diagram size`:`Maximize diagram`;m.setAttribute(`aria-label`,n),m.title=n},pe=t=>{if(t){let t=this.syncActiveShell();if(t&&t!==e){this.restoreShellMount(t),t.classList.remove(`is-maximized`),this.activeMaximizedShell===t&&this.clearActiveShell(),this.shellRefits.get(t)?.();let e=t.querySelector(`.plantuml-maximize-btn`);e&&(F(e,`maximize`),e.setAttribute(`aria-label`,`Maximize diagram`),e.title=`Maximize diagram`)}this.mountShellInMaximizedRoot(e),e.classList.add(`is-maximized`),this.activeMaximizedShell=e,document.body.classList.add(`plantuml-maximized-open`),de(),j({force:!0});return}this.restoreShellMount(e),e.classList.remove(`is-maximized`),this.activeMaximizedShell===e&&this.clearActiveShell(),this.syncActiveShell()||document.body.classList.remove(`plantuml-maximized-open`),de(),j({force:!0})};p.addEventListener(`click`,()=>{this.resetShell(e,{clearCache:!0,message:`Refreshing…`}),this.enqueueShell(e,{prioritize:!0})}),de(),m.addEventListener(`click`,()=>{pe(!e.classList.contains(`is-maximized`))});let M=()=>{if(E){if(E=!1,s.classList.remove(`is-dragging`),window.removeEventListener(`pointerup`,M,!0),window.removeEventListener(`pointercancel`,M,!0),window.removeEventListener(`mouseup`,M,!0),window.removeEventListener(`touchend`,M,!0),window.removeEventListener(`touchcancel`,M,!0),window.removeEventListener(`blur`,M,!0),te!==null&&typeof s.releasePointerCapture==`function`)try{s.releasePointerCapture(te)}catch{}te=null}};s.addEventListener(`pointerdown`,e=>{if(!(e.button!==0||!s.classList.contains(`is-pannable`))){if(b&&=(cancelAnimationFrame(b),null),E=!0,te=e.pointerId,ne=e.clientX,re=e.clientY,ie=s.scrollLeft,D=s.scrollTop,s.classList.add(`is-dragging`),window.addEventListener(`pointerup`,M,!0),window.addEventListener(`pointercancel`,M,!0),window.addEventListener(`mouseup`,M,!0),window.addEventListener(`touchend`,M,!0),window.addEventListener(`touchcancel`,M,!0),window.addEventListener(`blur`,M,!0),typeof s.setPointerCapture==`function`)try{s.setPointerCapture(e.pointerId)}catch{}e.preventDefault()}}),s.addEventListener(`pointermove`,e=>{E&&(s.scrollLeft=ie-(e.clientX-ne),s.scrollTop=D-(e.clientY-re))}),s.addEventListener(`pointerup`,M),s.addEventListener(`pointercancel`,M),s.addEventListener(`lostpointercapture`,M),s.addEventListener(`mouseleave`,M),s.addEventListener(`mouseup`,M),s.addEventListener(`touchend`,M),s.addEventListener(`touchcancel`,M),s.appendChild(r);let me=e.querySelector(`.plantuml-source`);e.replaceChildren(),me&&(me.hidden=!0,e.appendChild(me)),e.append(i,s),y=oe(),se(y)}createToolButton(e,t,{icon:n=``}={}){let r=document.createElement(`button`);return r.type=`button`,r.className=`plantuml-tool-btn ui-preview-action`,r.setAttribute(`aria-label`,t),r.title=t,n?F(r,n):r.textContent=e,r}};function et(){return new Worker(new URL(``+new URL(`preview-render-worker-BwQ5sPy9.js`,import.meta.url).href,``+import.meta.url),{type:`module`})}var tt=class{constructor({attachmentApiPath:t=`/api/attachment`,cancelIdleRenderFn:n=xe,compilePreviewDocumentLoader:r=()=>e(()=>import(`./preview-render-compiler-9SmLUP5V.js`),__vite__mapDeps([22,23,24,4,25,26]),import.meta.url),createWorkerFn:i=et,getFileList:a,getSourceFilePath:o=null,getWikiLinkAutoCreate:s=null,idleTimeoutMs:c=500,requestIdleRenderFn:l=M}={}){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)}},nt=class{constructor({cancelAnimationFrameFn:e=e=>cancelAnimationFrame(e),cancelIdleRenderFn:t=xe,clearTimeoutFn:n=e=>clearTimeout(e),getRenderProfileFn:i=r,idleTimeoutMs:a=500,requestAnimationFrameFn:o=e=>requestAnimationFrame(e),requestIdleRenderFn:s=M,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()}},rt=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(),this.enqueueMermaidShell(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(),this.enqueuePlantUmlShell(t,{prioritize:!0})}},this.handleWindowResize=()=>{this.mermaidHydrator.scheduleActiveRefit(),this.plantUmlHydrator.scheduleActiveRefit()},this.mermaidHydrator=new Qe(this,{loadFileSource:a}),this.plantUmlHydrator=new $e(this,{loadFileSource:a,renderClient:d}),this.renderScheduler=new nt({getRenderProfileFn:r}),this.renderExecutor=new tt({attachmentApiPath:E(`/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.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.cancelScheduledRender(),this.cancelMermaidHydration(),this.cancelPlantUmlHydration(),this.mermaidHydrator.clearPreservedShells(),this.plantUmlHydrator.clearPreservedShells(),this.clearActivePlantUmlShell(),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.resetWorker(`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)}configureMermaid(e){this.mermaidHydrator.configureMermaid(e)}ensureMermaid(){return this.mermaidHydrator.ensureMermaid()}queueRender(){let e=this.getContent();this.cancelScheduledRender(),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.compilePreview(e,t);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.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)}cancelScheduledRender(){this.renderScheduler.cancel()}cancelMermaidHydration(){this.mermaidHydrator.cancelHydration()}cancelPlantUmlHydration(){this.plantUmlHydrator.cancelHydration()}clearActivePlantUmlShell(){this.plantUmlHydrator.clearActiveShell()}scheduleActiveMermaidRefit(){this.mermaidHydrator.scheduleActiveRefit()}syncActivePlantUmlShell(){return this.plantUmlHydrator.syncActiveShell()}scheduleActivePlantUmlRefit(){this.plantUmlHydrator.scheduleActiveRefit()}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()}resetWorker(e,{disable:t=!1}={}){this.renderExecutor.reset(e,{disable:t})}scheduleWorkerPrewarm({timeout:e=500}={}){this.renderExecutor.schedulePrewarm({timeout:e})}async compilePreview(e,t){return this.renderExecutor.compile(e,t,{frontmatterCollapsed:this.frontmatterCollapsed,frontmatterInteractive:!0})}commitBaseRender({html:e,stats:t},n){this.activeRenderVersion=n,this.readyRenderVersion=0,this.currentStats=t,this.isLargeDocument=i(t),this.cancelMermaidHydration(),this.cancelPlantUmlHydration(),document.body.classList.remove(`mermaid-maximized-open`),document.body.classList.remove(`plantuml-maximized-open`),this.preserveHydratedMermaidsForCommit(),this.preserveHydratedPlantUmlsForCommit(),this.onBeforeRenderCommit?.(this.previewElement);let r=this.ensureRenderHost();this.normalizePreviewChildren(r),r&&(r.innerHTML=e),this.applyFrontmatterState(),this.reconcileHydratedMermaids(),this.reconcileHydratedPlantUmls(),this.setPhase(`base`),this.outlineController.refresh(),this.onAfterRenderCommit?.(this.previewElement,{...t,isLargeDocument:this.isLargeDocument,renderVersion:n});let a=this.setupMermaidHydration(n),o=this.setupPlantUmlHydration(n);a===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})}preserveHydratedMermaidsForCommit(){this.mermaidHydrator.preserveHydratedShellsForCommit()}preserveHydratedPlantUmlsForCommit(){this.plantUmlHydrator.preserveHydratedShellsForCommit()}reconcileHydratedMermaids(){this.mermaidHydrator.reconcileHydratedShells()}reconcileHydratedPlantUmls(){this.plantUmlHydrator.reconcileHydratedShells()}syncPreservedMermaidShell(e,t){this.mermaidHydrator.syncPreservedShell(e,t)}syncPreservedPlantUmlShell(e,t){this.plantUmlHydrator.syncPreservedShell(e,t)}setupMermaidHydration(e){return this.mermaidHydrator.setupHydration(e)}hydrateVisibleMermaids(){this.mermaidHydrator.hydrateVisibleShells()}enqueueMermaidShell(e,{prioritize:t=!1}={}){this.mermaidHydrator.enqueueShell(e,{prioritize:t})}scheduleMermaidHydration(){this.mermaidHydrator.scheduleHydration()}async flushMermaidHydrationQueue(){await this.mermaidHydrator.flushHydrationQueue()}async hydrateMermaidShell(e,t){await this.mermaidHydrator.hydrateShell(e,t)}resetHydratedMermaids(){this.mermaidHydrator.resetHydratedShells()}setupPlantUmlHydration(e){return this.plantUmlHydrator.setupHydration(e)}hydrateVisiblePlantUmls(){this.plantUmlHydrator.hydrateVisibleShells()}enqueuePlantUmlShell(e,{prioritize:t=!1}={}){this.plantUmlHydrator.enqueueShell(e,{prioritize:t})}schedulePlantUmlHydration(){this.plantUmlHydrator.scheduleHydration()}async flushPlantUmlHydrationQueue(){await this.plantUmlHydrator.flushHydrationQueue()}async hydratePlantUmlShell(e){await this.plantUmlHydrator.hydrateShell(e)}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 fetchPlantUmlSvg(e){return this.plantUmlHydrator.fetchSvg(e)}async fetchPlantUmlSource(e){return this.plantUmlHydrator.fetchSource(e)}async fetchMermaidSource(e){return this.mermaidHydrator.fetchSource(e)}resetPlantUmlShell(e,{clearCache:t=!1,message:n=`Renders server-side when visible`}={}){this.plantUmlHydrator.resetShell(e,{clearCache:t,message:n})}enhancePlantUmlDiagram(e,t){this.plantUmlHydrator.enhanceDiagram(e,t)}enhanceMermaidDiagram(e,t){this.mermaidHydrator.enhanceDiagram(e,t)}createMermaidZoomButton(e,t){return this.mermaidHydrator.createZoomButton(e,t)}createPlantUmlToolButton(e,t){return this.plantUmlHydrator.createToolButton(e,t)}};async function it(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,onFileSelect:t=>e.handleFileSelection(t,{closeSidebarOnMobile:!0,revealInTree:!0})}),e.quickSwitcher}async function at(e){try{(await it(e)).toggle()}catch{}}var ot=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:S,setSessionLoadToken:C,setSidebarTab:w,setSidebarVisibility:T,setCurrentFilePath:ee,showGitCommit:E,showGitDiff:te,showGitFileHistory:ne,showGitFilePreview:re,showGitHistory:ie,syncMainChrome:D,videoEmbed:ae,workspaceCoordinator:O,layoutController:oe}){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=S,this.setSessionLoadToken=C,this.setSidebarTab=w,this.setSidebarVisibility=T??(()=>{}),this.setCurrentFilePath=ee,this.showGitCommit=E,this.showGitDiff=te,this.showGitFileHistory=ne,this.showGitFilePreview=re,this.showGitHistory=ie,this.syncMainChrome=D,this.videoEmbed=ae,this.workspaceCoordinator=O,this.layoutController=oe,this.pendingTreeRevealPath=null}async handleHashChange(){if(!this.getIsTabActive())return;let e=this.navigation.getHashRoute();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.setSidebarTab(`files`),await this.openFile(e.filePath,{drawioMode:e.drawioMode||null}),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;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})}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})}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()}};function I(e){let t=String(e??``).trim().replace(/\\/g,`/`).replace(/^\/+/u,``).split(`/`).map(e=>e.trim()).filter(Boolean);return t.some(e=>e===`.`||e===`..`)?``:t.join(`/`)}function L(e,t){let n=I(e),r=I(t);return n?r?`${n}/${r}`:n:r}function st(e,t){return e.toLowerCase().endsWith(t.toLowerCase())?e:`${e}${t}`}function ct(e){return`# ${c(String(e??``).split(`/`).pop()||``)||`Untitled`}\n\n`}function lt(e){let t=I(e),n=l(t)?t:`${t}.base`;return{content:[`views:`,` - type: table`,` name: Table`,` order:`,` - file.name`,``].join(`
|
|
42
42
|
`),path:n}}function ut(e){let t=I(e),n=v(t)?t:`${t}.mmd`;return{content:[`flowchart TD`,` A[Start] --> B{Decide}`,` B -->|Yes| C[Ship it]`,` B -->|No| D[Revise]`,``].join(`
|
|
43
43
|
`),path:n}}function dt(e){let t=I(e),n=p(t)?t:`${t}.drawio`;return{content:[`<mxfile host="app.diagrams.net" modified="2026-01-01T00:00:00.000Z" agent="CollabMD" version="24.7.17">`,` <diagram id="page-1" name="Page-1">`,` <mxGraphModel dx="1200" dy="800" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0">`,` <root>`,` <mxCell id="0" />`,` <mxCell id="1" parent="0" />`,` </root>`,` </mxGraphModel>`,` </diagram>`,`</mxfile>`,``].join(`
|
|
44
44
|
`),path:n}}function ft(e){let t=I(e),n=s(t)?t:`${t}.puml`;return{content:[`@startuml`,`Alice -> Bob: Hello`,`@enduml`,``].join(`
|
|
45
|
-
`),path:n}}var pt=class{constructor({getFileList:e,navigation:t,refreshExplorer:n,toastController:r,vaultApiClient:i}){this.getFileList=e,this.navigation=t,this.refreshExplorer=n,this.toastController=r,this.vaultApiClient=i}handleWikiLinkClick(e){let t=y(e,this.getFileList());if(t){this.navigation.navigateToFile(t);return}let n=this.normalizeNewWikiFilePath(e);if(!n){this.toastController.show(`Cannot create an empty wiki-link target`);return}this.createAndOpenFile(n,e)}normalizeNewWikiFilePath(e){let t=I(e);return t?t.endsWith(`.md`)?t:`${t}.md`:null}async createAndOpenFile(e,t){try{await this.vaultApiClient.createFile({content:ct(t||e),path:e}),await this.refreshExplorer(),this.navigation.navigateToFile(e)}catch(e){this.toastController.show(`Failed to create file: ${e.message}`)}}},mt=class{constructor({backlinksPanel:e,basesPreview:t=null,drawioEmbed:n,elements:r,excalidrawEmbed:i,getDisplayName:a,getSession:o,isDrawioFile:s,isExcalidrawFile:c,isBaseFile:u,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=u??l,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),o=this.isBaseFile(e),s=this.isImageFile(e),c=u(e),l=this.isMermaidFile(e),d=this.isPlantUmlFile(e),f=a(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||o),this.elements.previewContent?.classList.toggle(`is-mermaid-file-preview`,l),this.elements.previewContent?.classList.toggle(`is-plantuml-file-preview`,d),r&&t!==`text`||i||s||o&&n){this.layoutController.setView(`preview`,{persist:!1}),this.outlineController.close(),this.backlinksPanel.clear();return}(l||d)&&(this.outlineController.close(),this.backlinksPanel.clear())}renderExcalidrawFilePreview(e){let t=this.elements.previewContent;if(!t)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode(),t.classList.add(`is-excalidraw-file-preview`);let n=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(n);let r=document.createElement(`div`);r.className=`excalidraw-embed-placeholder`,r.dataset.embedKey=`${e}#file-preview`,r.dataset.embedLabel=this.getDisplayName(e),r.dataset.embedTarget=e;let i=document.createElement(`div`);i.className=`preview-shell`,i.textContent=`Loading Excalidraw preview…`,r.appendChild(i),n&&(n.replaceChildren(r),n.style.minHeight=``),t.dataset.renderPhase=`ready`,this.outlineController.refresh(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.videoEmbed?.reconcileEmbeds(t),this.drawioEmbed.reconcileEmbeds(t),this.excalidrawEmbed.reconcileEmbeds(t,{isLargeDocument:!1}),this.drawioEmbed.hydrateVisibleEmbeds(),this.excalidrawEmbed.hydrateVisibleEmbeds(),this.schedulePreviewLayoutSyncCallback({delayMs:0})}renderDrawioFilePreview(e){let t=this.elements.previewContent;if(!t)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode(),t.classList.add(`is-drawio-file-preview`);let n=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(n);let r=document.createElement(`div`);r.className=`drawio-embed-placeholder`,r.dataset.drawioKey=`${e}#file-preview`,r.dataset.drawioLabel=this.getDisplayName(e),r.dataset.drawioMode=`edit`,r.dataset.drawioTarget=e;let i=document.createElement(`div`);i.className=`preview-shell`,i.textContent=`Loading draw.io preview…`,r.appendChild(i),n&&(n.replaceChildren(r),n.style.minHeight=``),t.dataset.renderPhase=`ready`,this.outlineController.refresh(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.videoEmbed?.reconcileEmbeds(t),this.drawioEmbed.reconcileEmbeds(t),this.drawioEmbed.hydrateVisibleEmbeds(),this.schedulePreviewLayoutSyncCallback({delayMs:0})}renderImageFilePreview(e){let t=this.elements.previewContent;if(!t)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode(),t.classList.add(`is-image-file-preview`);let n=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(n);let r=document.createElement(`figure`);r.className=`image-file-preview-shell`;let i=document.createElement(`img`);i.className=`image-file-preview-image`,i.alt=this.getDisplayName(e),i.src=E(`/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}))}},ht=class{constructor({attachEditorScroller:e,createEditorSession:t,loadEditorSessionClass:n,scrollContainerForSession:r}){this.attachEditorScroller=e,this.createEditorSession=t,this.loadEditorSessionClass=n,this.scrollContainerForSession=r}async createSession(e){let t=await this.loadEditorSessionClass();return this.createEditorSession(t,e)}attachSessionScroller(e){this.attachEditorScroller(this.scrollContainerForSession(e))}clearSessionScroller(){this.attachEditorScroller(null)}},gt=class{constructor({beginDocumentLoad:e,getDisplayName:t,loadBacklinks:n,onBeforeFileOpen:r,onRenderDrawioPreview:i,onFileOpenError:a,onFileOpenReady:o,onRenderBasePreview:s,onRenderExcalidrawPreview:c,onRenderImagePreview:l,onSyncWrapToggle:u,onUpdateActiveFile:d,onUpdateCurrentFile:f,onUpdateLobbyCurrentFile:p,onUpdateVisibleChrome:m,onViewModeReset:h,renderPresence:g,showEditorLoading:_,stateStore:v}){this.beginDocumentLoad=e??(()=>{}),this.getDisplayName=t??(e=>e),this.loadBacklinks=n??(()=>{}),this.onBeforeFileOpen=r??(()=>{}),this.onRenderDrawioPreview=i??(()=>{}),this.onFileOpenError=a??(()=>{}),this.onFileOpenReady=o??(()=>{}),this.onRenderBasePreview=s??(()=>{}),this.onRenderExcalidrawPreview=c??(()=>{}),this.onRenderImagePreview=l??(()=>{}),this.onSyncWrapToggle=u??(()=>{}),this.onUpdateActiveFile=d??(()=>{}),this.onUpdateCurrentFile=f??(()=>{}),this.onUpdateLobbyCurrentFile=p??(()=>{}),this.onUpdateVisibleChrome=m??(()=>{}),this.onViewModeReset=h??(()=>{}),this.renderPresence=g??(()=>{}),this.showEditorLoading=_??(()=>{}),this.stateStore=v}prepareForFileOpen(e,{drawioMode:t=null,resetConnectionState:n=!0}={}){return this.onViewModeReset(),this.onBeforeFileOpen(),this.stateStore.set(`connectionHelpShown`,!1),n&&this.stateStore.set(`connectionState`,{status:`connecting`,unreachable:!1}),this.stateStore.set(`currentDrawioMode`,t??null),this.stateStore.set(`currentFilePath`,e),this.onUpdateCurrentFile(e),this.onUpdateLobbyCurrentFile(e),this.onUpdateActiveFile(e),this.onUpdateVisibleChrome(e,{displayName:this.getDisplayName(e),drawioMode:t,isMarkdown:u(e)}),this.showEditorLoading(),this.beginDocumentLoad(),this.renderPresence(),{supportsBacklinks:m(e)}}markFileOpenReady(e){this.onFileOpenReady(e)}finalizeFileOpen({isBase:e=!1,isDrawio:t=!1,filePath:n,isExcalidraw:r=!1,isImage:i=!1,supportsBacklinks:a}){r&&this.onRenderExcalidrawPreview(n),(e||l(n))&&this.onRenderBasePreview(n),t&&this.onRenderDrawioPreview(n),i&&this.onRenderImagePreview(n),this.onSyncWrapToggle(),a&&this.loadBacklinks(n)}handleFileOpenError(){this.onFileOpenError()}},_t=150;function vt(e){return new Promise(t=>{setTimeout(t,e)})}var yt=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:S,onCommentsChange:C,onFileAwarenessChange:w,onFileOpenError:T,onFileOpenReady:ee,onImagePaste:E,onSelectionChange:te,onSessionAssigned:ne=null,onFileOpenMetric:re=null,onRenderBasePreview:ie,onRenderExcalidrawPreview:D,onRenderDrawioPreview:ae,onRenderImagePreview:O,onSyncWrapToggle:oe,onUpdateActiveFile:se,onUpdateCurrentFile:ce,onUpdateLobbyCurrentFile:k,onUpdateVisibleChrome:le,onViewModeReset:ue,renderPresence:A,scrollContainerForSession:j,shouldUseDrawioPreview:de=null,showEditorLoading:fe,stateStore:pe}){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=S,this.onCommentsChange=C,this.onFileAwarenessChange=w,this.onFileOpenError=T,this.onFileOpenReady=ee,this.onImagePaste=E,this.onSelectionChange=te,this.onSessionAssigned=ne,this.onFileOpenMetric=re,this.onRenderBasePreview=ie,this.onRenderExcalidrawPreview=D,this.onSyncWrapToggle=oe,this.onUpdateActiveFile=se,this.onUpdateCurrentFile=ce,this.onUpdateLobbyCurrentFile=k,this.onUpdateVisibleChrome=le,this.renderPresence=A,this.shouldUseDrawioPreview=de??(()=>!0),this.stateStore=pe,this.session=null,this.lifecycle=new ht({attachEditorScroller:e,createEditorSession:r,loadEditorSessionClass:()=>this.loadEditorSessionClassPort(),scrollContainerForSession:j}),this.chromeController=new gt({beginDocumentLoad:t,getDisplayName:i,loadBacklinks:y,onBeforeFileOpen:b,onRenderDrawioPreview:ae,onFileOpenError:T,onFileOpenReady:ee,onRenderBasePreview:ie,onRenderExcalidrawPreview:D,onRenderImagePreview:O,onSyncWrapToggle:oe,onUpdateActiveFile:se,onUpdateCurrentFile:ce,onUpdateLobbyCurrentFile:k,onUpdateVisibleChrome:le,onViewModeReset:ue,renderPresence:A,showEditorLoading:fe,stateStore:pe})}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.get(`currentFilePath`),loadToken:t,...n})}cleanupSession(){this.session?.destroy(),this.session=null,this.lifecycle.clearSessionScroller(),this.cleanupAfterSessionDestroy()}async openFile(e,{drawioMode:t=null}={}){if(!this.isTabActive())return;let n=t??null,r=this.stateStore.get(`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.get(`currentFilePath`)&&n===r&&(this.session||i||a||s)){this.onUpdateActiveFile(e),this.onUpdateLobbyCurrentFile(e);return}let u=this.stateStore.nextSessionLoadToken(),d=performance.now();this.cleanupSession();let f=this.chromeController.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.get(`sessionLoadToken`))return;this.chromeController.markFileOpenReady(null),this.chromeController.finalizeFileOpen({filePath:e,isBase:o,isDrawio:i,isExcalidraw:a,isImage:s,session:null,supportsBacklinks:f.supportsBacklinks});return}let p=await this.lifecycle.createSession({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=p,this.onSessionAssigned?.(p);try{let t=!1,n=!1,r=!1,i=async r=>{t||u!==this.stateStore.get(`sessionLoadToken`)||(t=!0,this.lifecycle.attachSessionScroller(p),p.applyTheme(this.getTheme()),this.chromeController.markFileOpenReady(p),this.reportFileOpenMetric(`editor_ready`,u,{reason:r}),p.requestMeasure(),await this.waitForNextPaint(),!(n||u!==this.stateStore.get(`sessionLoadToken`))&&(n=!0,this.chromeController.finalizeFileOpen({filePath:e,isBase:o,isExcalidraw:a,session:p,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=p.initialize(e),l=(async()=>(await c,u!==this.stateStore.get(`sessionLoadToken`)||(await p.waitForInitialSync(null),u!==this.stateStore.get(`sessionLoadToken`))?!1:(r=!0,p.activateCollaborativeView?.(),this.lifecycle.attachSessionScroller(p),p.applyTheme(this.getTheme()),this.reportFileOpenMetric(`initial_sync_complete`,u),p.ensureInitialContent?.(),t?p.requestMeasure():await i(`live-sync`),!0)))(),m=(async()=>{let n=await s;if(n===null||r||t||u!==this.stateStore.get(`sessionLoadToken`))return!1;let a=performance.now()-d,o=Math.max(0,_t-a);return o>0&&await Promise.race([l.then(e=>e?`live-sync`:`stale`),vt(o).then(()=>`timeout`)])===`live-sync`||r||t||u!==this.stateStore.get(`sessionLoadToken`)||!p.showBootstrapContent({content:n,filePath:e})&&!p.hasBootstrapContent?.()?!1:(this.reportFileOpenMetric(`bootstrap_shown`,u),await i(`bootstrap`),!0)})();if(await c,u!==this.stateStore.get(`sessionLoadToken`)){p.destroy();return}if(await Promise.all([l,m]),u!==this.stateStore.get(`sessionLoadToken`)){p.destroy();return}t||(p.ensureInitialContent?.(),await i(`post-initialize`))}catch(e){if(console.error(`[app] Failed to initialize editor:`,e),p.destroy(),this.lifecycle.clearSessionScroller(),this.session===p&&(this.session=null),u!==this.stateStore.get(`sessionLoadToken`))return;this.chromeController.handleFileOpenError()}}},bt=class{constructor(e={}){this.state={activeSidebarTab:`files`,chatInitialSyncComplete:!1,chatIsOpen:!1,chatMessageIds:new Set,chatMessages:[],chatUnreadCount:0,connectionHelpShown:!1,connectionState:{status:`disconnected`,unreachable:!1},currentDrawioMode:null,currentFilePath:null,fileExplorerReady:!1,followedCursorSignature:``,followedUserClientId:null,gitRepoAvailable:!1,globalUsers:[],isTabActive:!1,presencePanelOpen:!1,sessionLoadToken:0,...e}}get(e){return this.state[e]}set(e,t){return this.state[e]=t,t}nextSessionLoadToken(){let e=Number(this.state.sessionLoadToken||0)+1;return this.state.sessionLoadToken=e,e}replaceChatState({initialSyncComplete:e,isOpen:t,messageIds:n,messages:r,unreadCount:i}){this.state.chatMessages=Array.isArray(r)?r:[],this.state.chatMessageIds=n instanceof Set?n:new Set,this.state.chatUnreadCount=Number.isFinite(i)?i:0,this.state.chatIsOpen=!!t,this.state.chatInitialSyncComplete=!!e}};function xt(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`),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`),commentsToggleButton:e.getElementById(`commentsToggle`),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 R={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=`No alerts`,r=`Browser notifications are unavailable here`):t===`denied`?(n=`Alerts blocked`,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)}},St={getCommentFileKind(e=this.currentFilePath){return f(e)||`markdown`},syncCommentChrome(e=this.currentFilePath){let t=d(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)},handleCommentEditorContentChange(){this.commentUi.handleEditorContentChange()},refreshCommentUiLayout(){this.commentUi.refreshLayout()}},Ct=`collabmd-export-page`,wt=`collabmd-export-host`,Tt=500,Et=6e4,Dt=new Map,Ot=null;function kt(){return`export-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function At(e){return e===`pdf`?`pdf`:`docx`}function jt({filePath:e,format:t,jobId:n}){let r=new URL(O(`/export-document.html`),window.location.origin);return r.searchParams.set(`action`,At(t)),r.searchParams.set(`job`,n),e&&r.searchParams.set(`file`,e),r.toString()}function Mt({fileList:e=[],filePath:t,format:n,jobId:r,markdownText:i=``,title:a=``}){return{action:At(n),fileList:Array.isArray(e)?e.slice():[],filePath:String(t??``),jobId:r,markdownText:String(i??``),source:wt,title:String(a??``),type:`bootstrap`}}function Nt(e){e&&(e.closePollId&&window.clearInterval(e.closePollId),e.timeoutId&&window.clearTimeout(e.timeoutId))}function Pt(e,{notifyError:t=!1,message:n=``}={}){let r=Dt.get(e);r&&(Nt(r),Dt.delete(e),t&&n&&Ot?.(n))}function Ft({onError:e=null}={}){Ot=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!==Ct)return;let n=String(t.jobId??``).trim();if(!n)return;let r=Dt.get(n);if(r){if(t.type===`ready`){if(r.window?.closed){Pt(n,{message:`Export window was closed before the export completed`,notifyError:!0});return}try{r.window?.postMessage(r.payload,window.location.origin)}catch(e){Pt(n,{message:e instanceof Error?e.message:`Failed to send export data`,notifyError:!0})}return}(t.type===`complete`||t.type===`error`)&&Pt(n,{message:t.type===`error`&&t.message?String(t.message):``,notifyError:t.type===`error`&&!!t.message})}}),window.__collabmdExportBridgeInitialized=!0)}async function It({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=kt(),s=jt({filePath:a,format:n,jobId:o}),c=window.open(s,`_blank`);if(!c)throw Error(`Export popup was blocked`);return Dt.set(o,{closePollId:window.setInterval(()=>{c.closed&&Pt(o,{message:`Export window was closed before the export completed`,notifyError:!0})},Tt),payload:Mt({fileList:e,filePath:a,format:n,jobId:o,markdownText:r,title:i}),timeoutId:window.setTimeout(()=>{Pt(o,{message:`Export timed out before it completed`,notifyError:!0})},Et),window:c}),c.focus?.(),o}var Lt={initializeExportBridge(){this._exportBridgeInitialized||=(Ft({onError:e=>{this.toastController?.show(e)}}),!0)},async handleExportRequest(e){let t=String(this.currentFilePath??``).trim();if(!u(t))return this.toastController?.show(`Export is available for markdown notes only`),!1;try{return await It({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 Rt(e=[]){return Array.from(new Set((e??[]).filter(Boolean)))}function zt(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 Bt(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 Vt({changedPaths:e=[],deletedPaths:t=[],refreshExplorer:n=!0,renamedPaths:r=[]}={}){return{changedPaths:Rt(e),deletedPaths:Rt(t),refreshExplorer:n!==!1,renamedPaths:zt(r)}}function Ht(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:Bt(e.highlightRanges),id:e.id,origin:typeof e.origin==`string`?e.origin:`api`,reloadRequiredPaths:Rt(e.reloadRequiredPaths),requestId:typeof e.requestId==`string`?e.requestId:null,sourceRef:typeof e.sourceRef==`string`?e.sourceRef:null,workspaceChange:Vt(e.workspaceChange)}}function Ut(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`workspace-${Date.now()}-${Math.random().toString(16).slice(2,10)}`}function Wt(e={}){return Vt(e)}var z={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.toggle(`hidden`,!this.gitRepoAvailable),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`}={}){this.clearStaticPreviewDocument?.(),this.gitPanel.setSelection(e?{path:e,scope:t,source:`workspace`}:{}),this.gitPanel.setMode(`changes`),this.showDiffState(),this.syncMainChrome({badgeLabel:`Diff`,mode:`diff`,title:this.gitDiffView.getToolbarTitle({filePath:e,scope:t})}),this.syncFileHistoryButton({filePath:e,mode:`diff`}),await this.gitDiffView.openWorkspaceDiff({filePath:e,scope:t})},async showGitCommit({hash:e,path:t=null,historyFilePath:n=null}={}){this.clearStaticPreviewDocument?.(),this.gitPanel.setMode(`history`),this.gitPanel.setSelection(e?{commitHash:e,path:t,source:`commit`}:{source:`commit`}),this.showDiffState(),this.syncMainChrome({badgeLabel:`Diff`,mode:`diff`,title:this.gitDiffView.getToolbarTitle({commitHash:e,path:t,source:`commit`})}),this.syncFileHistoryButton({filePath:t,mode:`diff`}),await this.gitDiffView.openCommitDiff({hash:e,historyFilePath:n,path:t})},async showGitHistory(){this.clearStaticPreviewDocument?.(),this.gitPanel.setMode(`history`),this.gitPanel.setSelection({source:`commit`}),this.workspaceRouteController?.showEmptyState?.(),this.syncMainChrome({mode:`empty`,title:`Git History`}),this.syncFileHistoryButton({mode:`empty`})},async showGitFileHistory({filePath:e=null}={}){if(!e){this.workspaceRouteController?.showEmptyState?.();return}this.clearStaticPreviewDocument?.(),this.commentUi?.attachSession?.(null),this.commentUi?.setCurrentFile?.(e,{fileKind:this.getCommentFileKind(e),supported:!1}),this.handleCommentThreadsChange?.([]),this.handleCommentSelectionChange?.(null),this.workspaceRouteController?.showFileHistoryState?.(e),this.syncMainChrome({badgeLabel:`History`,mode:`history`,title:this.getDisplayName(e)}),this.syncFileHistoryButton({filePath:e,mode:`history`}),await this.fileHistoryView.openFileHistory({filePath:e})},async _loadGitFileSnapshot({hash:e,filePath:t,resolvedCurrentFilePath:n}){let r=await this.gitApiClient.readFileSnapshot({hash:e,path:t});if(this.setStaticPreviewDocument?.({...r,currentFilePath:n}),this.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=Ut();this.pendingWorkspaceRequestIds?.add(n);try{switch(e){case`stage`:return await this.gitApiClient.stageFile({path:t.path,requestId:n});case`unstage`:return await this.gitApiClient.unstageFile({path:t.path,requestId:n});case`push`:return await this.gitApiClient.pushBranch({requestId:n});case`pull`:return await this.gitApiClient.pullBranch({requestId:n});case`reset-file`:return await this.gitApiClient.resetFile({path:t.path,requestId:n});case`commit`:return await this.gitApiClient.commit({message:t.message,requestId:n});default:throw Error(`Unsupported git action: ${e}`)}}catch(e){throw this.pendingWorkspaceRequestIds?.delete(n),e}},async refreshWorkspaceAfterGitAction({filePath:e=null,preferredScope:t=null}={}){await this.fileExplorer.refresh(),await this.refreshGitAfterAction({filePath:e,preferredScope:t})},async refreshGitAfterAction({filePath:e=null,preferredScope:t=null}={}){await this.gitPanel.refresh({force:!0});let n=this.navigation.getHashRoute();if(n.type===`git-history`){await this.showGitHistory();return}if(n.type===`git-file-history`){await this.showGitFileHistory({filePath:n.filePath});return}if(n.type===`git-file-preview`){await this.showGitFilePreview({hash:n.hash,filePath:n.filePath,currentFilePath:n.currentFilePath});return}if(n.type===`git-commit`){await this.showGitCommit({hash:n.hash,path:n.path,historyFilePath:n.historyFilePath});return}if(n.type!==`git-diff`)return;let r=e??n.filePath,i=t??n.scope;if(i!==n.scope||r!==n.filePath){this.navigation.navigateToGitDiff({filePath:r,scope:i});return}await this.showGitDiff({filePath:n.filePath,scope:n.scope})},async finalizeGitAction({action:e,filePath:t=null,preferredScope:n=null,result:r={},showLocalFileToast:i=!1}={}){let a=Wt(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=Wt(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)}}}},Gt=5;function Kt(e,t){return String(e?.name??``).localeCompare(String(t?.name??``),void 0,{sensitivity:`base`})}function qt(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 Jt(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 Yt(e,t){let n=e.filter(e=>e.isLocal).sort(Kt),r=e.filter(e=>!e.isLocal),i=r.filter(e=>e.clientId===t).sort(Kt),a=r.filter(e=>e.clientId!==t).sort(Kt);return[...n,...i,...a]}function Xt(e,t){return t.currentFile&&t.currentFile===e.currentFilePath?`Here`:t.currentFile?e.getDisplayName(t.currentFile):`No file`}var B={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=qt(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=Jt(this.globalUsers,this.followedUserClientId);if(t.slice(0,Gt).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>Gt){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-Gt}`,n.appendChild(r),e.appendChild(n)}this.renderPresencePanel()},openPresencePanel(){qt(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=Yt(this.globalUsers,this.followedUserClientId),i=qt(this);if(n&&(i.status===`connected`?n.textContent=`${this.globalUsers.length} online. Click someone to follow.`:i.status===`connecting`?n.textContent=i.unreachable?`Server unreachable.`:`Connecting presence...`:n.textContent=`Presence is offline.`),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=Xt(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 Zt(){return this.runtimeConfig?.auth?.strategy===`oidc`&&this.runtimeConfig?.auth?.provider===`google`}function Qt({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 $t(){!this.isTabActive||this._hasPromptedForDisplayName||this.getStoredUserName()||this.isIdentityManagedByAuth()||(this._hasPromptedForDisplayName=!0,requestAnimationFrame(()=>{this.openDisplayNameDialog({mode:`onboarding`})}))}function en(){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):Te(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 tn(){return this.globalUsers.find(e=>e.isLocal)??this.session?.getLocalUser()??this.lobby?.getLocalUser()??null}function nn(){return this.getCurrentUser()?.name??this.getStoredUserName()??``}function rn(){return this.preferences.getUserName()}function an(){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 on(){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 sn={getCurrentUser:tn,getCurrentUserName:nn,getStoredUserName:rn,handleDisplayNameSubmit:en,isIdentityManagedByAuth:Zt,openDisplayNameDialog:Qt,promptForDisplayNameIfNeeded:$t,syncCurrentUserName:an,syncIdentityManagementUi:on},cn=0,ln=2e3,un=8,dn=`
|
|
45
|
+
`),path:n}}var pt=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=y(e,this.getFileList());if(t){this.navigation.navigateToFile(t);return}if(!this.wikiLinkAutoCreate){this.toastController.show(`Wiki-link target does not exist`);return}let n=this.normalizeNewWikiFilePath(e);if(!n){this.toastController.show(`Cannot create an empty wiki-link target`);return}this.createAndOpenFile(n,e)}normalizeNewWikiFilePath(e){let t=I(e);return t?t.endsWith(`.md`)?t:`${t}.md`:null}async createAndOpenFile(e,t){try{await this.vaultApiClient.createFile({content:ct(t||e),path:e}),await this.refreshExplorer(),this.navigation.navigateToFile(e)}catch(e){this.toastController.show(`Failed to create file: ${e.message}`)}}},mt=class{constructor({backlinksPanel:e,basesPreview:t=null,drawioEmbed:n,elements:r,excalidrawEmbed:i,getDisplayName:a,getSession:o,isDrawioFile:s,isExcalidrawFile:c,isBaseFile:u,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=u??l,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),o=this.isBaseFile(e),s=this.isImageFile(e),c=u(e),l=this.isMermaidFile(e),d=this.isPlantUmlFile(e),f=a(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||o),this.elements.previewContent?.classList.toggle(`is-mermaid-file-preview`,l),this.elements.previewContent?.classList.toggle(`is-plantuml-file-preview`,d),r&&t!==`text`||i||s||o&&n){this.layoutController.setView(`preview`,{persist:!1}),this.outlineController.close(),this.backlinksPanel.clear();return}(l||d)&&(this.outlineController.close(),this.backlinksPanel.clear())}renderExcalidrawFilePreview(e){let t=this.elements.previewContent;if(!t)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode(),t.classList.add(`is-excalidraw-file-preview`);let n=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(n);let r=document.createElement(`div`);r.className=`excalidraw-embed-placeholder`,r.dataset.embedKey=`${e}#file-preview`,r.dataset.embedLabel=this.getDisplayName(e),r.dataset.embedTarget=e;let i=document.createElement(`div`);i.className=`preview-shell`,i.textContent=`Loading Excalidraw preview…`,r.appendChild(i),n&&(n.replaceChildren(r),n.style.minHeight=``),t.dataset.renderPhase=`ready`,this.outlineController.refresh(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.videoEmbed?.reconcileEmbeds(t),this.drawioEmbed.reconcileEmbeds(t),this.excalidrawEmbed.reconcileEmbeds(t,{isLargeDocument:!1}),this.drawioEmbed.hydrateVisibleEmbeds(),this.excalidrawEmbed.hydrateVisibleEmbeds(),this.schedulePreviewLayoutSyncCallback({delayMs:0})}renderDrawioFilePreview(e){let t=this.elements.previewContent;if(!t)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode(),t.classList.add(`is-drawio-file-preview`);let n=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(n);let r=document.createElement(`div`);r.className=`drawio-embed-placeholder`,r.dataset.drawioKey=`${e}#file-preview`,r.dataset.drawioLabel=this.getDisplayName(e),r.dataset.drawioMode=`edit`,r.dataset.drawioTarget=e;let i=document.createElement(`div`);i.className=`preview-shell`,i.textContent=`Loading draw.io preview…`,r.appendChild(i),n&&(n.replaceChildren(r),n.style.minHeight=``),t.dataset.renderPhase=`ready`,this.outlineController.refresh(),this.scrollSyncController.setLargeDocumentMode(!1),this.scrollSyncController.invalidatePreviewBlocks(),this.videoEmbed?.reconcileEmbeds(t),this.drawioEmbed.reconcileEmbeds(t),this.drawioEmbed.hydrateVisibleEmbeds(),this.schedulePreviewLayoutSyncCallback({delayMs:0})}renderImageFilePreview(e){let t=this.elements.previewContent;if(!t)return;this.videoEmbed?.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit(),this.resetPreviewMode(),t.classList.add(`is-image-file-preview`);let n=this.previewRenderer.ensureRenderHost();this.previewRenderer.normalizePreviewChildren(n);let r=document.createElement(`figure`);r.className=`image-file-preview-shell`;let i=document.createElement(`img`);i.className=`image-file-preview-image`,i.alt=this.getDisplayName(e),i.src=E(`/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}))}},ht=class{constructor({attachEditorScroller:e,createEditorSession:t,loadEditorSessionClass:n,scrollContainerForSession:r}){this.attachEditorScroller=e,this.createEditorSession=t,this.loadEditorSessionClass=n,this.scrollContainerForSession=r}async createSession(e){let t=await this.loadEditorSessionClass();return this.createEditorSession(t,e)}attachSessionScroller(e){this.attachEditorScroller(this.scrollContainerForSession(e))}clearSessionScroller(){this.attachEditorScroller(null)}},gt=class{constructor({beginDocumentLoad:e,getDisplayName:t,loadBacklinks:n,onBeforeFileOpen:r,onRenderDrawioPreview:i,onFileOpenError:a,onFileOpenReady:o,onRenderBasePreview:s,onRenderExcalidrawPreview:c,onRenderImagePreview:l,onSyncWrapToggle:u,onUpdateActiveFile:d,onUpdateCurrentFile:f,onUpdateLobbyCurrentFile:p,onUpdateVisibleChrome:m,onViewModeReset:h,renderPresence:g,showEditorLoading:_,stateStore:v}){this.beginDocumentLoad=e??(()=>{}),this.getDisplayName=t??(e=>e),this.loadBacklinks=n??(()=>{}),this.onBeforeFileOpen=r??(()=>{}),this.onRenderDrawioPreview=i??(()=>{}),this.onFileOpenError=a??(()=>{}),this.onFileOpenReady=o??(()=>{}),this.onRenderBasePreview=s??(()=>{}),this.onRenderExcalidrawPreview=c??(()=>{}),this.onRenderImagePreview=l??(()=>{}),this.onSyncWrapToggle=u??(()=>{}),this.onUpdateActiveFile=d??(()=>{}),this.onUpdateCurrentFile=f??(()=>{}),this.onUpdateLobbyCurrentFile=p??(()=>{}),this.onUpdateVisibleChrome=m??(()=>{}),this.onViewModeReset=h??(()=>{}),this.renderPresence=g??(()=>{}),this.showEditorLoading=_??(()=>{}),this.stateStore=v}prepareForFileOpen(e,{drawioMode:t=null,resetConnectionState:n=!0}={}){return this.onViewModeReset(),this.onBeforeFileOpen(),this.stateStore.set(`connectionHelpShown`,!1),n&&this.stateStore.set(`connectionState`,{status:`connecting`,unreachable:!1}),this.stateStore.set(`currentDrawioMode`,t??null),this.stateStore.set(`currentFilePath`,e),this.onUpdateCurrentFile(e),this.onUpdateLobbyCurrentFile(e),this.onUpdateActiveFile(e),this.onUpdateVisibleChrome(e,{displayName:this.getDisplayName(e),drawioMode:t,isMarkdown:u(e)}),this.showEditorLoading(),this.beginDocumentLoad(),this.renderPresence(),{supportsBacklinks:m(e)}}markFileOpenReady(e){this.onFileOpenReady(e)}finalizeFileOpen({isBase:e=!1,isDrawio:t=!1,filePath:n,isExcalidraw:r=!1,isImage:i=!1,supportsBacklinks:a}){r&&this.onRenderExcalidrawPreview(n),(e||l(n))&&this.onRenderBasePreview(n),t&&this.onRenderDrawioPreview(n),i&&this.onRenderImagePreview(n),this.onSyncWrapToggle(),a&&this.loadBacklinks(n)}handleFileOpenError(){this.onFileOpenError()}},_t=150;function vt(e){return new Promise(t=>{setTimeout(t,e)})}var yt=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:S,onCommentsChange:C,onFileAwarenessChange:w,onFileOpenError:T,onFileOpenReady:ee,onImagePaste:E,onSelectionChange:te,onSessionAssigned:ne=null,onFileOpenMetric:re=null,onRenderBasePreview:ie,onRenderExcalidrawPreview:D,onRenderDrawioPreview:ae,onRenderImagePreview:O,onSyncWrapToggle:oe,onUpdateActiveFile:se,onUpdateCurrentFile:ce,onUpdateLobbyCurrentFile:k,onUpdateVisibleChrome:le,onViewModeReset:ue,renderPresence:A,scrollContainerForSession:j,shouldUseDrawioPreview:de=null,showEditorLoading:fe,stateStore:pe}){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=S,this.onCommentsChange=C,this.onFileAwarenessChange=w,this.onFileOpenError=T,this.onFileOpenReady=ee,this.onImagePaste=E,this.onSelectionChange=te,this.onSessionAssigned=ne,this.onFileOpenMetric=re,this.onRenderBasePreview=ie,this.onRenderExcalidrawPreview=D,this.onSyncWrapToggle=oe,this.onUpdateActiveFile=se,this.onUpdateCurrentFile=ce,this.onUpdateLobbyCurrentFile=k,this.onUpdateVisibleChrome=le,this.renderPresence=A,this.shouldUseDrawioPreview=de??(()=>!0),this.stateStore=pe,this.session=null,this.lifecycle=new ht({attachEditorScroller:e,createEditorSession:r,loadEditorSessionClass:()=>this.loadEditorSessionClassPort(),scrollContainerForSession:j}),this.chromeController=new gt({beginDocumentLoad:t,getDisplayName:i,loadBacklinks:y,onBeforeFileOpen:b,onRenderDrawioPreview:ae,onFileOpenError:T,onFileOpenReady:ee,onRenderBasePreview:ie,onRenderExcalidrawPreview:D,onRenderImagePreview:O,onSyncWrapToggle:oe,onUpdateActiveFile:se,onUpdateCurrentFile:ce,onUpdateLobbyCurrentFile:k,onUpdateVisibleChrome:le,onViewModeReset:ue,renderPresence:A,showEditorLoading:fe,stateStore:pe})}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.get(`currentFilePath`),loadToken:t,...n})}cleanupSession(){this.session?.destroy(),this.session=null,this.lifecycle.clearSessionScroller(),this.cleanupAfterSessionDestroy()}async openFile(e,{drawioMode:t=null}={}){if(!this.isTabActive())return;let n=t??null,r=this.stateStore.get(`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.get(`currentFilePath`)&&n===r&&(this.session||i||a||s)){this.onUpdateActiveFile(e),this.onUpdateLobbyCurrentFile(e);return}let u=this.stateStore.nextSessionLoadToken(),d=performance.now();this.cleanupSession();let f=this.chromeController.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.get(`sessionLoadToken`))return;this.chromeController.markFileOpenReady(null),this.chromeController.finalizeFileOpen({filePath:e,isBase:o,isDrawio:i,isExcalidraw:a,isImage:s,session:null,supportsBacklinks:f.supportsBacklinks});return}let p=await this.lifecycle.createSession({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=p,this.onSessionAssigned?.(p);try{let t=!1,n=!1,r=!1,i=async r=>{t||u!==this.stateStore.get(`sessionLoadToken`)||(t=!0,this.lifecycle.attachSessionScroller(p),p.applyTheme(this.getTheme()),this.chromeController.markFileOpenReady(p),this.reportFileOpenMetric(`editor_ready`,u,{reason:r}),p.requestMeasure(),await this.waitForNextPaint(),!(n||u!==this.stateStore.get(`sessionLoadToken`))&&(n=!0,this.chromeController.finalizeFileOpen({filePath:e,isBase:o,isExcalidraw:a,session:p,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=p.initialize(e),l=(async()=>(await c,u!==this.stateStore.get(`sessionLoadToken`)||(await p.waitForInitialSync(null),u!==this.stateStore.get(`sessionLoadToken`))?!1:(r=!0,p.activateCollaborativeView?.(),this.lifecycle.attachSessionScroller(p),p.applyTheme(this.getTheme()),this.reportFileOpenMetric(`initial_sync_complete`,u),p.ensureInitialContent?.(),t?p.requestMeasure():await i(`live-sync`),!0)))(),m=(async()=>{let n=await s;if(n===null||r||t||u!==this.stateStore.get(`sessionLoadToken`))return!1;let a=performance.now()-d,o=Math.max(0,_t-a);return o>0&&await Promise.race([l.then(e=>e?`live-sync`:`stale`),vt(o).then(()=>`timeout`)])===`live-sync`||r||t||u!==this.stateStore.get(`sessionLoadToken`)||!p.showBootstrapContent({content:n,filePath:e})&&!p.hasBootstrapContent?.()?!1:(this.reportFileOpenMetric(`bootstrap_shown`,u),await i(`bootstrap`),!0)})();if(await c,u!==this.stateStore.get(`sessionLoadToken`)){p.destroy();return}if(await Promise.all([l,m]),u!==this.stateStore.get(`sessionLoadToken`)){p.destroy();return}t||(p.ensureInitialContent?.(),await i(`post-initialize`))}catch(e){if(console.error(`[app] Failed to initialize editor:`,e),p.destroy(),this.lifecycle.clearSessionScroller(),this.session===p&&(this.session=null),u!==this.stateStore.get(`sessionLoadToken`))return;this.chromeController.handleFileOpenError()}}},bt=class{constructor(e={}){this.state={activeSidebarTab:`files`,chatInitialSyncComplete:!1,chatIsOpen:!1,chatMessageIds:new Set,chatMessages:[],chatUnreadCount:0,connectionHelpShown:!1,connectionState:{status:`disconnected`,unreachable:!1},currentDrawioMode:null,currentFilePath:null,fileExplorerReady:!1,followedCursorSignature:``,followedUserClientId:null,gitRepoAvailable:!1,globalUsers:[],isTabActive:!1,presencePanelOpen:!1,sessionLoadToken:0,...e}}get(e){return this.state[e]}set(e,t){return this.state[e]=t,t}nextSessionLoadToken(){let e=Number(this.state.sessionLoadToken||0)+1;return this.state.sessionLoadToken=e,e}replaceChatState({initialSyncComplete:e,isOpen:t,messageIds:n,messages:r,unreadCount:i}){this.state.chatMessages=Array.isArray(r)?r:[],this.state.chatMessageIds=n instanceof Set?n:new Set,this.state.chatUnreadCount=Number.isFinite(i)?i:0,this.state.chatIsOpen=!!t,this.state.chatInitialSyncComplete=!!e}};function xt(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`),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`),commentsToggleButton:e.getElementById(`commentsToggle`),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 R={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=`No alerts`,r=`Browser notifications are unavailable here`):t===`denied`?(n=`Alerts blocked`,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)}},St={getCommentFileKind(e=this.currentFilePath){return f(e)||`markdown`},syncCommentChrome(e=this.currentFilePath){let t=d(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)},handleCommentEditorContentChange(){this.commentUi.handleEditorContentChange()},refreshCommentUiLayout(){this.commentUi.refreshLayout()}},Ct=`collabmd-export-page`,wt=`collabmd-export-host`,Tt=500,Et=6e4,Dt=new Map,Ot=null;function kt(){return`export-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function At(e){return e===`pdf`?`pdf`:`docx`}function jt({filePath:e,format:t,jobId:n}){let r=new URL(O(`/export-document.html`),window.location.origin);return r.searchParams.set(`action`,At(t)),r.searchParams.set(`job`,n),e&&r.searchParams.set(`file`,e),r.toString()}function Mt({fileList:e=[],filePath:t,format:n,jobId:r,markdownText:i=``,title:a=``}){return{action:At(n),fileList:Array.isArray(e)?e.slice():[],filePath:String(t??``),jobId:r,markdownText:String(i??``),source:wt,title:String(a??``),type:`bootstrap`}}function Nt(e){e&&(e.closePollId&&window.clearInterval(e.closePollId),e.timeoutId&&window.clearTimeout(e.timeoutId))}function Pt(e,{notifyError:t=!1,message:n=``}={}){let r=Dt.get(e);r&&(Nt(r),Dt.delete(e),t&&n&&Ot?.(n))}function Ft({onError:e=null}={}){Ot=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!==Ct)return;let n=String(t.jobId??``).trim();if(!n)return;let r=Dt.get(n);if(r){if(t.type===`ready`){if(r.window?.closed){Pt(n,{message:`Export window was closed before the export completed`,notifyError:!0});return}try{r.window?.postMessage(r.payload,window.location.origin)}catch(e){Pt(n,{message:e instanceof Error?e.message:`Failed to send export data`,notifyError:!0})}return}(t.type===`complete`||t.type===`error`)&&Pt(n,{message:t.type===`error`&&t.message?String(t.message):``,notifyError:t.type===`error`&&!!t.message})}}),window.__collabmdExportBridgeInitialized=!0)}async function It({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=kt(),s=jt({filePath:a,format:n,jobId:o}),c=window.open(s,`_blank`);if(!c)throw Error(`Export popup was blocked`);return Dt.set(o,{closePollId:window.setInterval(()=>{c.closed&&Pt(o,{message:`Export window was closed before the export completed`,notifyError:!0})},Tt),payload:Mt({fileList:e,filePath:a,format:n,jobId:o,markdownText:r,title:i}),timeoutId:window.setTimeout(()=>{Pt(o,{message:`Export timed out before it completed`,notifyError:!0})},Et),window:c}),c.focus?.(),o}var Lt={initializeExportBridge(){this._exportBridgeInitialized||=(Ft({onError:e=>{this.toastController?.show(e)}}),!0)},async handleExportRequest(e){let t=String(this.currentFilePath??``).trim();if(!u(t))return this.toastController?.show(`Export is available for markdown notes only`),!1;try{return await It({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 Rt(e=[]){return Array.from(new Set((e??[]).filter(Boolean)))}function zt(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 Bt(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 Vt({changedPaths:e=[],deletedPaths:t=[],refreshExplorer:n=!0,renamedPaths:r=[]}={}){return{changedPaths:Rt(e),deletedPaths:Rt(t),refreshExplorer:n!==!1,renamedPaths:zt(r)}}function Ht(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:Bt(e.highlightRanges),id:e.id,origin:typeof e.origin==`string`?e.origin:`api`,reloadRequiredPaths:Rt(e.reloadRequiredPaths),requestId:typeof e.requestId==`string`?e.requestId:null,sourceRef:typeof e.sourceRef==`string`?e.sourceRef:null,workspaceChange:Vt(e.workspaceChange)}}function Ut(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`workspace-${Date.now()}-${Math.random().toString(16).slice(2,10)}`}function Wt(e={}){return Vt(e)}var z={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.toggle(`hidden`,!this.gitRepoAvailable),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`}={}){this.clearStaticPreviewDocument?.(),this.gitPanel.setSelection(e?{path:e,scope:t,source:`workspace`}:{}),this.gitPanel.setMode(`changes`),this.showDiffState(),this.syncMainChrome({badgeLabel:`Diff`,mode:`diff`,title:this.gitDiffView.getToolbarTitle({filePath:e,scope:t})}),this.syncFileHistoryButton({filePath:e,mode:`diff`}),await this.gitDiffView.openWorkspaceDiff({filePath:e,scope:t})},async showGitCommit({hash:e,path:t=null,historyFilePath:n=null}={}){this.clearStaticPreviewDocument?.(),this.gitPanel.setMode(`history`),this.gitPanel.setSelection(e?{commitHash:e,path:t,source:`commit`}:{source:`commit`}),this.showDiffState(),this.syncMainChrome({badgeLabel:`Diff`,mode:`diff`,title:this.gitDiffView.getToolbarTitle({commitHash:e,path:t,source:`commit`})}),this.syncFileHistoryButton({filePath:t,mode:`diff`}),await this.gitDiffView.openCommitDiff({hash:e,historyFilePath:n,path:t})},async showGitHistory(){this.clearStaticPreviewDocument?.(),this.gitPanel.setMode(`history`),this.gitPanel.setSelection({source:`commit`}),this.workspaceRouteController?.showEmptyState?.(),this.syncMainChrome({mode:`empty`,title:`Git History`}),this.syncFileHistoryButton({mode:`empty`})},async showGitFileHistory({filePath:e=null}={}){if(!e){this.workspaceRouteController?.showEmptyState?.();return}this.clearStaticPreviewDocument?.(),this.commentUi?.attachSession?.(null),this.commentUi?.setCurrentFile?.(e,{fileKind:this.getCommentFileKind(e),supported:!1}),this.handleCommentThreadsChange?.([]),this.handleCommentSelectionChange?.(null),this.workspaceRouteController?.showFileHistoryState?.(e),this.syncMainChrome({badgeLabel:`History`,mode:`history`,title:this.getDisplayName(e)}),this.syncFileHistoryButton({filePath:e,mode:`history`}),await this.fileHistoryView.openFileHistory({filePath:e})},async _loadGitFileSnapshot({hash:e,filePath:t,resolvedCurrentFilePath:n}){let r=await this.gitApiClient.readFileSnapshot({hash:e,path:t});if(this.setStaticPreviewDocument?.({...r,currentFilePath:n}),this.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=Ut();this.pendingWorkspaceRequestIds?.add(n);try{switch(e){case`stage`:return await this.gitApiClient.stageFile({path:t.path,requestId:n});case`unstage`:return await this.gitApiClient.unstageFile({path:t.path,requestId:n});case`push`:return await this.gitApiClient.pushBranch({requestId:n});case`pull`:return await this.gitApiClient.pullBranch({requestId:n});case`reset-file`:return await this.gitApiClient.resetFile({path:t.path,requestId:n});case`commit`:return await this.gitApiClient.commit({message:t.message,requestId:n});default:throw Error(`Unsupported git action: ${e}`)}}catch(e){throw this.pendingWorkspaceRequestIds?.delete(n),e}},async refreshWorkspaceAfterGitAction({filePath:e=null,preferredScope:t=null}={}){await this.fileExplorer.refresh(),await this.refreshGitAfterAction({filePath:e,preferredScope:t})},async refreshGitAfterAction({filePath:e=null,preferredScope:t=null}={}){await this.gitPanel.refresh({force:!0});let n=this.navigation.getHashRoute();if(n.type===`git-history`){await this.showGitHistory();return}if(n.type===`git-file-history`){await this.showGitFileHistory({filePath:n.filePath});return}if(n.type===`git-file-preview`){await this.showGitFilePreview({hash:n.hash,filePath:n.filePath,currentFilePath:n.currentFilePath});return}if(n.type===`git-commit`){await this.showGitCommit({hash:n.hash,path:n.path,historyFilePath:n.historyFilePath});return}if(n.type!==`git-diff`)return;let r=e??n.filePath,i=t??n.scope;if(i!==n.scope||r!==n.filePath){this.navigation.navigateToGitDiff({filePath:r,scope:i});return}await this.showGitDiff({filePath:n.filePath,scope:n.scope})},async finalizeGitAction({action:e,filePath:t=null,preferredScope:n=null,result:r={},showLocalFileToast:i=!1}={}){let a=Wt(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=Wt(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)}}}},Gt=5;function Kt(e,t){return String(e?.name??``).localeCompare(String(t?.name??``),void 0,{sensitivity:`base`})}function qt(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 Jt(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 Yt(e,t){let n=e.filter(e=>e.isLocal).sort(Kt),r=e.filter(e=>!e.isLocal),i=r.filter(e=>e.clientId===t).sort(Kt),a=r.filter(e=>e.clientId!==t).sort(Kt);return[...n,...i,...a]}function Xt(e,t){return t.currentFile&&t.currentFile===e.currentFilePath?`Here`:t.currentFile?e.getDisplayName(t.currentFile):`No file`}var B={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=qt(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=Jt(this.globalUsers,this.followedUserClientId);if(t.slice(0,Gt).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>Gt){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-Gt}`,n.appendChild(r),e.appendChild(n)}this.renderPresencePanel()},openPresencePanel(){qt(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=Yt(this.globalUsers,this.followedUserClientId),i=qt(this);if(n&&(i.status===`connected`?n.textContent=`${this.globalUsers.length} online. Click someone to follow.`:i.status===`connecting`?n.textContent=i.unreachable?`Server unreachable.`:`Connecting presence...`:n.textContent=`Presence is offline.`),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=Xt(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 Zt(){return this.runtimeConfig?.auth?.strategy===`oidc`&&this.runtimeConfig?.auth?.provider===`google`}function Qt({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 $t(){!this.isTabActive||this._hasPromptedForDisplayName||this.getStoredUserName()||this.isIdentityManagedByAuth()||(this._hasPromptedForDisplayName=!0,requestAnimationFrame(()=>{this.openDisplayNameDialog({mode:`onboarding`})}))}function en(){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):Te(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 tn(){return this.globalUsers.find(e=>e.isLocal)??this.session?.getLocalUser()??this.lobby?.getLocalUser()??null}function nn(){return this.getCurrentUser()?.name??this.getStoredUserName()??``}function rn(){return this.preferences.getUserName()}function an(){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 on(){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 sn={getCurrentUser:tn,getCurrentUserName:nn,getStoredUserName:rn,handleDisplayNameSubmit:en,isIdentityManagedByAuth:Zt,openDisplayNameDialog:Qt,promptForDisplayNameIfNeeded:$t,syncCurrentUserName:an,syncIdentityManagementUi:on},cn=0,ln=2e3,un=8,dn=`
|
|
46
46
|
<svg viewBox="0 0 24 24" width="15" height="15" aria-hidden="true" focusable="false">
|
|
47
47
|
<path d="M10 13.5 14 9.5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
|
|
48
48
|
<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"/>
|
|
@@ -1407,4 +1407,4 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
1407
1407
|
<div class="qs-hint" id="quickSwitcherHint">Type to search files</div>
|
|
1408
1408
|
</div>
|
|
1409
1409
|
</div>
|
|
1410
|
-
`}function pu(e=document){let t=e.getElementById(`appRoot`);if(!t)throw Error(`App shell root element #appRoot is missing.`);return uu(fu(),t),t}var mu=class{updateChatMessages(...e){return R.updateChatMessages.apply(this,e)}toggleChatPanel(...e){return R.toggleChatPanel.apply(this,e)}openChatPanel(...e){return R.openChatPanel.apply(this,e)}closeChatPanel(...e){return R.closeChatPanel.apply(this,e)}handleChatSubmit(...e){return R.handleChatSubmit.apply(this,e)}renderChat(...e){return R.renderChat.apply(this,e)}createChatMessageElement(...e){return R.createChatMessageElement.apply(this,e)}scrollChatToBottom(...e){return R.scrollChatToBottom.apply(this,e)}formatChatTimestamp(...e){return R.formatChatTimestamp.apply(this,e)}getChatMessageFileLabel(...e){return R.getChatMessageFileLabel.apply(this,e)}formatChatToastMessage(...e){return R.formatChatToastMessage.apply(this,e)}syncChatToggleButton(...e){return R.syncChatToggleButton.apply(this,e)}syncChatNotificationButton(...e){return R.syncChatNotificationButton.apply(this,e)}handleChatNotificationToggle(...e){return R.handleChatNotificationToggle.apply(this,e)}maybeNotifyChatMessage(...e){return R.maybeNotifyChatMessage.apply(this,e)}maybeShowBrowserChatNotification(...e){return R.maybeShowBrowserChatNotification.apply(this,e)}getCommentFileKind(...e){return St.getCommentFileKind.apply(this,e)}syncCommentChrome(...e){return St.syncCommentChrome.apply(this,e)}handleCommentSelectionChange(...e){return St.handleCommentSelectionChange.apply(this,e)}handleCommentThreadsChange(...e){return St.handleCommentThreadsChange.apply(this,e)}handleCommentEditorContentChange(...e){return St.handleCommentEditorContentChange.apply(this,e)}refreshCommentUiLayout(...e){return St.refreshCommentUiLayout.apply(this,e)}initializeExportBridge(...e){return Lt.initializeExportBridge.apply(this,e)}handleExportRequest(...e){return Lt.handleExportRequest.apply(this,e)}formatPullBackupToast(...e){return z.formatPullBackupToast.apply(this,e)}setGitOperationStatus(...e){return z.setGitOperationStatus.apply(this,e)}runGitActionWithStatus(...e){return z.runGitActionWithStatus.apply(this,e)}handleGitDiffSelection(...e){return z.handleGitDiffSelection.apply(this,e)}handleGitCommitSelection(...e){return z.handleGitCommitSelection.apply(this,e)}handleGitHistorySelection(...e){return z.handleGitHistorySelection.apply(this,e)}handleGitFileHistorySelection(...e){return z.handleGitFileHistorySelection.apply(this,e)}handleGitFilePreviewSelection(...e){return z.handleGitFilePreviewSelection.apply(this,e)}handleGitRepoChange(...e){return z.handleGitRepoChange.apply(this,e)}syncFileHistoryButton(...e){return z.syncFileHistoryButton.apply(this,e)}syncMainChrome(...e){return z.syncMainChrome.apply(this,e)}showGitDiff(...e){return z.showGitDiff.apply(this,e)}showGitCommit(...e){return z.showGitCommit.apply(this,e)}showGitHistory(...e){return z.showGitHistory.apply(this,e)}showGitFileHistory(...e){return z.showGitFileHistory.apply(this,e)}showGitFilePreview(...e){return z.showGitFilePreview.apply(this,e)}postGitAction(...e){return z.postGitAction.apply(this,e)}refreshWorkspaceAfterGitAction(...e){return z.refreshWorkspaceAfterGitAction.apply(this,e)}refreshGitAfterAction(...e){return z.refreshGitAfterAction.apply(this,e)}finalizeGitAction(...e){return z.finalizeGitAction.apply(this,e)}handleWorkspaceChangeForCurrentFile(...e){return z.handleWorkspaceChangeForCurrentFile.apply(this,e)}handleIncomingWorkspaceEvent(...e){return z.handleIncomingWorkspaceEvent.apply(this,e)}stageGitFile(...e){return z.stageGitFile.apply(this,e)}unstageGitFile(...e){return z.unstageGitFile.apply(this,e)}pushGitBranch(...e){return z.pushGitBranch.apply(this,e)}pullGitBranch(...e){return z.pullGitBranch.apply(this,e)}openGitResetDialog(...e){return z.openGitResetDialog.apply(this,e)}handleGitResetSubmit(...e){return z.handleGitResetSubmit.apply(this,e)}openGitCommitDialog(...e){return z.openGitCommitDialog.apply(this,e)}handleGitCommitSubmit(...e){return z.handleGitCommitSubmit.apply(this,e)}updateGlobalUsers(...e){return B.updateGlobalUsers.apply(this,e)}updateFileAwareness(...e){return B.updateFileAwareness.apply(this,e)}closePresencePanel(...e){return B.closePresencePanel.apply(this,e)}openPresencePanel(...e){return B.openPresencePanel.apply(this,e)}renderPresence(...e){return B.renderPresence.apply(this,e)}renderAvatars(...e){return B.renderAvatars.apply(this,e)}renderPresencePanel(...e){return B.renderPresencePanel.apply(this,e)}startFollowingUser(...e){return B.startFollowingUser.apply(this,e)}toggleFollowUser(...e){return B.toggleFollowUser.apply(this,e)}togglePresencePanel(...e){return B.togglePresencePanel.apply(this,e)}stopFollowingUser(...e){return B.stopFollowingUser.apply(this,e)}syncFollowedUser(...e){return B.syncFollowedUser.apply(this,e)}followUserCursor(...e){return B.followUserCursor.apply(this,e)}followExcalidrawUser(...e){return B.followExcalidrawUser.apply(this,e)}resolveFileClientId(...e){return B.resolveFileClientId.apply(this,e)}bindEvents(...e){return U.bindEvents.apply(this,e)}clearInitialFileBootstrap(...e){return U.clearInitialFileBootstrap.apply(this,e)}closeToolbarOverflowMenu(...e){return U.closeToolbarOverflowMenu.apply(this,e)}applyPendingPreviewRouteAnchor(...e){return U.applyPendingPreviewRouteAnchor.apply(this,e)}copyPreviewHeadingLink(...e){return U.copyPreviewHeadingLink.apply(this,e)}createPreviewHeadingLinkUrl(...e){return U.createPreviewHeadingLinkUrl.apply(this,e)}getStoredLineWrapping(...e){return U.getStoredLineWrapping.apply(this,e)}handleConnectionChange(...e){return U.handleConnectionChange.apply(this,e)}handleDocumentKeydown(...e){return U.handleDocumentKeydown.apply(this,e)}handleDocumentPointerDown(...e){return U.handleDocumentPointerDown.apply(this,e)}handlePreviewContentClick(...e){return U.handlePreviewContentClick.apply(this,e)}handleThemeChange(...e){return U.handleThemeChange.apply(this,e)}hideEditorLoading(...e){return U.hideEditorLoading.apply(this,e)}initialize(...e){return U.initialize.apply(this,e)}initializeVisualViewportBinding(...e){return U.initializeVisualViewportBinding.apply(this,e)}initializeVersionMonitoring(...e){return U.initializeVersionMonitoring.apply(this,e)}navigatePreviewHeading(...e){return U.navigatePreviewHeading.apply(this,e)}promptForVersionReload(...e){return U.promptForVersionReload.apply(this,e)}requestPreviewRouteAnchor(...e){return U.requestPreviewRouteAnchor.apply(this,e)}scheduleBacklinkRefresh(...e){return U.scheduleBacklinkRefresh.apply(this,e)}setToolbarOverflowOpen(...e){return U.setToolbarOverflowOpen.apply(this,e)}showEditorLoadError(...e){return U.showEditorLoadError.apply(this,e)}showEditorLoading(...e){return U.showEditorLoading.apply(this,e)}syncPreviewHeadingLinkButtons(...e){return U.syncPreviewHeadingLinkButtons.apply(this,e)}syncVisualViewportBounds(...e){return U.syncVisualViewportBounds.apply(this,e)}syncToolbarOverflowVisibility(...e){return U.syncToolbarOverflowVisibility.apply(this,e)}syncWrapToggle(...e){return U.syncWrapToggle.apply(this,e)}toggleToolbarOverflowMenu(...e){return U.toggleToolbarOverflowMenu.apply(this,e)}toggleLineWrapping(...e){return U.toggleLineWrapping.apply(this,e)}applySidebarVisibility(...e){return U.applySidebarVisibility.apply(this,e)}closeSidebarOnMobile(...e){return U.closeSidebarOnMobile.apply(this,e)}isMobileViewport(...e){return U.isMobileViewport.apply(this,e)}restoreSidebarState(...e){return U.restoreSidebarState.apply(this,e)}setSidebarTab(...e){return U.setSidebarTab.apply(this,e)}setSidebarVisibility(...e){return U.setSidebarVisibility.apply(this,e)}toggleSidebar(...e){return U.toggleSidebar.apply(this,e)}getCurrentUser(...e){return U.getCurrentUser.apply(this,e)}getCurrentUserName(...e){return U.getCurrentUserName.apply(this,e)}getStoredUserName(...e){return U.getStoredUserName.apply(this,e)}handleDisplayNameSubmit(...e){return U.handleDisplayNameSubmit.apply(this,e)}isIdentityManagedByAuth(...e){return U.isIdentityManagedByAuth.apply(this,e)}openDisplayNameDialog(...e){return U.openDisplayNameDialog.apply(this,e)}promptForDisplayNameIfNeeded(...e){return U.promptForDisplayNameIfNeeded.apply(this,e)}syncCurrentUserName(...e){return U.syncCurrentUserName.apply(this,e)}syncIdentityManagementUi(...e){return U.syncIdentityManagementUi.apply(this,e)}applyMarkdownToolbarAction(...e){return U.applyMarkdownToolbarAction.apply(this,e)}copyCurrentLink(...e){return U.copyCurrentLink.apply(this,e)}closeMarkdownBlockMenu(...e){return U.closeMarkdownBlockMenu.apply(this,e)}getActiveMarkdownBlockAction(...e){return U.getActiveMarkdownBlockAction.apply(this,e)}getMarkdownBlockMenuPopover(...e){return U.getMarkdownBlockMenuPopover.apply(this,e)}handleEditorImageInsert(...e){return U.handleEditorImageInsert.apply(this,e)}handleMarkdownToolbarClick(...e){return U.handleMarkdownToolbarClick.apply(this,e)}handleMarkdownToolbarDocumentPointerDown(...e){return U.handleMarkdownToolbarDocumentPointerDown.apply(this,e)}handleMarkdownToolbarKeydown(...e){return U.handleMarkdownToolbarKeydown.apply(this,e)}handleToolbarImageInsert(...e){return U.handleToolbarImageInsert.apply(this,e)}isMarkdownBlockMenuOpen(...e){return U.isMarkdownBlockMenuOpen.apply(this,e)}openMarkdownBlockMenu(...e){return U.openMarkdownBlockMenu.apply(this,e)}positionMarkdownBlockMenu(...e){return U.positionMarkdownBlockMenu.apply(this,e)}renderMarkdownBlockMenuPopover(...e){return U.renderMarkdownBlockMenuPopover.apply(this,e)}pickImageFile(...e){return U.pickImageFile.apply(this,e)}renderMarkdownToolbar(...e){return U.renderMarkdownToolbar.apply(this,e)}runEditorCommand(...e){return U.runEditorCommand.apply(this,e)}setActiveMarkdownBlockAction(...e){return U.setActiveMarkdownBlockAction.apply(this,e)}syncMarkdownToolbarBlockUi(...e){return U.syncMarkdownToolbarBlockUi.apply(this,e)}toggleMarkdownBlockMenu(...e){return U.toggleMarkdownBlockMenu.apply(this,e)}handleTabActivated(...e){return U.handleTabActivated.apply(this,e)}handleTabBlocked(...e){return U.handleTabBlocked.apply(this,e)}handleTabTakeover(...e){return U.handleTabTakeover.apply(this,e)}hideTabLockOverlay(...e){return U.hideTabLockOverlay.apply(this,e)}showTabLockOverlay(...e){return U.showTabLockOverlay.apply(this,e)}isExcalidrawFile(...e){return W.isExcalidrawFile.apply(this,e)}isBaseFile(...e){return W.isBaseFile.apply(this,e)}isDrawioFile(...e){return W.isDrawioFile.apply(this,e)}isImageFile(...e){return W.isImageFile.apply(this,e)}isMermaidFile(...e){return W.isMermaidFile.apply(this,e)}isPlantUmlFile(...e){return W.isPlantUmlFile.apply(this,e)}createDiagramPreviewDocument(...e){return W.createDiagramPreviewDocument.apply(this,e)}getPreviewSource(...e){return W.getPreviewSource.apply(this,e)}getStaticPreviewDocument(...e){return W.getStaticPreviewDocument.apply(this,e)}setStaticPreviewDocument(...e){return W.setStaticPreviewDocument.apply(this,e)}clearStaticPreviewDocument(...e){return W.clearStaticPreviewDocument.apply(this,e)}supportsFileHistory(...e){return W.supportsFileHistory.apply(this,e)}getDisplayName(...e){return W.getDisplayName.apply(this,e)}resetPreviewMode(...e){return W.resetPreviewMode.apply(this,e)}syncFileChrome(...e){return W.syncFileChrome.apply(this,e)}handleLayoutViewRequest(...e){return W.handleLayoutViewRequest.apply(this,e)}renderExcalidrawFilePreview(...e){return W.renderExcalidrawFilePreview.apply(this,e)}renderDrawioFilePreview(...e){return W.renderDrawioFilePreview.apply(this,e)}renderImageFilePreview(...e){return W.renderImageFilePreview.apply(this,e)}renderBaseFilePreview(...e){return W.renderBaseFilePreview.apply(this,e)}renderTextFilePreview(...e){return W.renderTextFilePreview.apply(this,e)}createResizeHandler(...e){return W.createResizeHandler.apply(this,e)}initializePreviewLayoutObserver(...e){return W.initializePreviewLayoutObserver.apply(this,e)}schedulePreviewLayoutSync(...e){return W.schedulePreviewLayoutSync.apply(this,e)}handleEditorScrollActivityChange(...e){return W.handleEditorScrollActivityChange.apply(this,e)}handleHashChange(...e){return W.handleHashChange.apply(this,e)}showEmptyState(...e){return W.showEmptyState.apply(this,e)}showDiffState(...e){return W.showDiffState.apply(this,e)}openFile(...e){return W.openFile.apply(this,e)}cleanupSession(...e){return W.cleanupSession.apply(this,e)}handleWikiLinkClick(...e){return W.handleWikiLinkClick.apply(this,e)}normalizeNewWikiFilePath(...e){return W.normalizeNewWikiFilePath.apply(this,e)}createAndOpenFile(...e){return W.createAndOpenFile.apply(this,e)}handleFileSelection(...e){return W.handleFileSelection.apply(this,e)}constructor(){pu(document),this.elements=xt(document),this.runtimeConfig=D(),this.stateStore=new bt,this.navigation=new ri,this.preferences=new ai({chatNotificationsKey:`collabmd-chat-notifications-enabled`,lineWrappingKey:`collabmd-editor-line-wrap`,sidebarVisibleKey:`collabmd-sidebar-visible`,userNameKey:`collabmd-user-name`}),this.notifications=new ii,this.backlinksApiClient=li,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.mobileBreakpointQuery=window.matchMedia(`(max-width: 768px)`),this.pendingWorkspaceRequestIds=new Set,this._fileOpenPerf=null,this.versionMonitor=new ci({currentBuildId:this.runtimeConfig.build?.id,onUpdateAvailable:e=>this.promptForVersionReload(e),runtimeConfig:this.runtimeConfig}),this.lobby=new ni({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.fileExplorerReady=!0,!n&&this.isTabActive&&this.handleHashChange()},onWorkspaceEvent:e=>{this.handleIncomingWorkspaceEvent(e)}}),this.toastController=new dl(this.elements.toastContainer),this.chatToastController=new dl(this.elements.chatToastContainer),this.fileExplorer=new mc({mobileBreakpointQuery:this.mobileBreakpointQuery,onFileDelete:()=>this.navigation.navigateToFile(null),onFileSelect:e=>this.handleFileSelection(e,{closeSidebarOnMobile:!0}),pendingWorkspaceRequestIds:this.pendingWorkspaceRequestIds,toastController:this.toastController}),this.gitPanel=new Kc({enabled:this.runtimeConfig.gitEnabled!==!1,gitApiClient:this.gitApiClient,onCommitStaged:()=>this.openGitCommitDialog(),onOpenPullBackup:e=>e&&this.navigation.navigateToFile(e),onPullBranch:()=>this.pullGitBranch(),onPushBranch:()=>this.pushGitBranch(),onRepoChange:(e,t)=>this.handleGitRepoChange(e,t),onResetFile:(e,{scope:t})=>this.openGitResetDialog(e,{scope:t}),onSelectCommit:(e,{path:t})=>this.handleGitCommitSelection(e,{closeSidebarOnMobile:!0,path:t}),onSelectDiff:(e,{scope:t})=>this.handleGitDiffSelection(e,{closeSidebarOnMobile:!0,scope:t}),onStageFile:(e,{scope:t})=>this.stageGitFile(e,{scope:t}),onUnstageFile:(e,{scope:t})=>this.unstageGitFile(e,{scope:t}),onViewAllDiff:()=>this.handleGitDiffSelection(null,{closeSidebarOnMobile:!0,scope:`all`}),searchInput:this.elements.gitSearchInput,toastController:this.toastController}),this.outlineController=new Jc({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 _l({previewElement:this.elements.previewContent}),this.basesPreview=new Ka({getActiveFilePath:()=>this.currentFilePath,getSession:()=>this.session,onOpenFile:e=>e&&this.navigation.navigateToFile(e),previewElement:this.elements.previewContent,replaceBaseSource:({path:e,source:t})=>{e&&e===this.currentFilePath&&this.session?.replaceText?.(t)},toastController:this.toastController,vaultApiClient:this.vaultApiClient}),this.imageLightbox=new El({previewElement:this.elements.previewContent}),this.previewRenderer=new rt({getContent:()=>this.getPreviewSource(),getFileList:()=>this.fileExplorer.flatDocumentFiles,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 ul({onChange:e=>this.handleThemeChange(e)}),this.layoutController=new qc({mobileBreakpointQuery:this.mobileBreakpointQuery,onMeasureEditor:()=>this.session?.requestMeasure(),onViewRequest:e=>this.handleLayoutViewRequest(e)}),this.scrollSyncController=new sl({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=new Gs({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}),this.drawioEmbed=new Ns({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}),this.commentUi=new Ts({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.session?.createCommentThread({anchor:e,body:t}),onNavigateToLine:e=>{this.scrollSyncController.suspendSync(250),this.session?.scrollToLine(e,.2)},onReplyToThread:(e,t)=>this.session?.replyToCommentThread(e,t),onToggleReaction:(e,t,n)=>this.session?.toggleCommentReaction(e,t,n),onResolveThread:e=>this.session?.deleteCommentThread(e)}),this.workspacePreviewController=new mt({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 pt({getFileList:()=>this.fileExplorer.flatDocumentFiles,navigation:this.navigation,refreshExplorer:()=>this.fileExplorer.refresh(),toastController:this.toastController,vaultApiClient:this.vaultApiClient}),this.gitDiffView=new Pc({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}),this.fileHistoryView=new Sc({diffRenderer:this.gitDiffView,gitApiClient:this.gitApiClient,onOpenCommitDiff:(e,{historyFilePath:t,path:n})=>this.handleGitCommitSelection(e,{closeSidebarOnMobile:!1,historyFilePath:t,path:n}),onOpenFile:e=>e&&this.navigation.navigateToFile(e),onOpenPreview:({hash:e,path:t,currentFilePath:n})=>this.handleGitFilePreviewSelection({hash:e,path:t,currentFilePath:n}),onOpenWorkspaceDiff:e=>this.handleGitDiffSelection(e,{closeSidebarOnMobile:!1,scope:`all`}),toastController:this.toastController}),this.tabActivityLock=new Si({onActivated:({takeover:e})=>this.handleTabActivated({takeover:e}),onBlocked:()=>this.handleTabBlocked({reason:`active-elsewhere`}),onStolen:()=>this.handleTabBlocked({reason:`taken-over`})}),this.workspaceCoordinator=new yt({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.stateStore}),this.workspaceRouteController=new ot({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}get currentFilePath(){return this.stateStore.get(`currentFilePath`)}set currentFilePath(e){this.stateStore.set(`currentFilePath`,e)}get currentDrawioMode(){return this.stateStore.get(`currentDrawioMode`)}set currentDrawioMode(e){this.stateStore.set(`currentDrawioMode`,e??null)}get globalUsers(){return this.stateStore.get(`globalUsers`)}set globalUsers(e){this.stateStore.set(`globalUsers`,e)}get connectionState(){return this.stateStore.get(`connectionState`)}set connectionState(e){this.stateStore.set(`connectionState`,e)}get sessionLoadToken(){return this.stateStore.get(`sessionLoadToken`)}set sessionLoadToken(e){this.stateStore.set(`sessionLoadToken`,e)}get connectionHelpShown(){return this.stateStore.get(`connectionHelpShown`)}set connectionHelpShown(e){this.stateStore.set(`connectionHelpShown`,e)}get chatMessages(){return this.stateStore.get(`chatMessages`)}set chatMessages(e){this.stateStore.set(`chatMessages`,e)}get chatMessageIds(){return this.stateStore.get(`chatMessageIds`)}set chatMessageIds(e){this.stateStore.set(`chatMessageIds`,e)}get chatUnreadCount(){return this.stateStore.get(`chatUnreadCount`)}set chatUnreadCount(e){this.stateStore.set(`chatUnreadCount`,e)}get chatIsOpen(){return this.stateStore.get(`chatIsOpen`)}set chatIsOpen(e){this.stateStore.set(`chatIsOpen`,e)}get chatInitialSyncComplete(){return this.stateStore.get(`chatInitialSyncComplete`)}set chatInitialSyncComplete(e){this.stateStore.set(`chatInitialSyncComplete`,e)}get isTabActive(){return this.stateStore.get(`isTabActive`)}set isTabActive(e){this.stateStore.set(`isTabActive`,e)}get fileExplorerReady(){return this.stateStore.get(`fileExplorerReady`)}set fileExplorerReady(e){this.stateStore.set(`fileExplorerReady`,e)}get gitRepoAvailable(){return this.stateStore.get(`gitRepoAvailable`)}set gitRepoAvailable(e){this.stateStore.set(`gitRepoAvailable`,e)}get activeSidebarTab(){return this.stateStore.get(`activeSidebarTab`)}set activeSidebarTab(e){this.stateStore.set(`activeSidebarTab`,e)}get presencePanelOpen(){return this.stateStore.get(`presencePanelOpen`)}set presencePanelOpen(e){this.stateStore.set(`presencePanelOpen`,e)}get followedUserClientId(){return this.stateStore.get(`followedUserClientId`)}set followedUserClientId(e){this.stateStore.set(`followedUserClientId`,e)}get followedCursorSignature(){return this.stateStore.get(`followedCursorSignature`)}set followedCursorSignature(e){this.stateStore.set(`followedCursorSignature`,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-YtGVwK3v.js`).then(e=>e.EditorSession),__vite__mapDeps([27,1,28,29,30,31,32,33,34,35,36,37,38,39,26]),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-B1erSgJ1.js`).then(e=>e.QuickSwitcherController),__vite__mapDeps([40,25,26]),import.meta.url)}async ensureQuickSwitcher(){return it(this)}async toggleQuickSwitcher(){return at(this)}};async function hu(){await C(),new mu().initialize()}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{hu()},{once:!0}):hu();
|
|
1410
|
+
`}function pu(e=document){let t=e.getElementById(`appRoot`);if(!t)throw Error(`App shell root element #appRoot is missing.`);return uu(fu(),t),t}var mu=class{updateChatMessages(...e){return R.updateChatMessages.apply(this,e)}toggleChatPanel(...e){return R.toggleChatPanel.apply(this,e)}openChatPanel(...e){return R.openChatPanel.apply(this,e)}closeChatPanel(...e){return R.closeChatPanel.apply(this,e)}handleChatSubmit(...e){return R.handleChatSubmit.apply(this,e)}renderChat(...e){return R.renderChat.apply(this,e)}createChatMessageElement(...e){return R.createChatMessageElement.apply(this,e)}scrollChatToBottom(...e){return R.scrollChatToBottom.apply(this,e)}formatChatTimestamp(...e){return R.formatChatTimestamp.apply(this,e)}getChatMessageFileLabel(...e){return R.getChatMessageFileLabel.apply(this,e)}formatChatToastMessage(...e){return R.formatChatToastMessage.apply(this,e)}syncChatToggleButton(...e){return R.syncChatToggleButton.apply(this,e)}syncChatNotificationButton(...e){return R.syncChatNotificationButton.apply(this,e)}handleChatNotificationToggle(...e){return R.handleChatNotificationToggle.apply(this,e)}maybeNotifyChatMessage(...e){return R.maybeNotifyChatMessage.apply(this,e)}maybeShowBrowserChatNotification(...e){return R.maybeShowBrowserChatNotification.apply(this,e)}getCommentFileKind(...e){return St.getCommentFileKind.apply(this,e)}syncCommentChrome(...e){return St.syncCommentChrome.apply(this,e)}handleCommentSelectionChange(...e){return St.handleCommentSelectionChange.apply(this,e)}handleCommentThreadsChange(...e){return St.handleCommentThreadsChange.apply(this,e)}handleCommentEditorContentChange(...e){return St.handleCommentEditorContentChange.apply(this,e)}refreshCommentUiLayout(...e){return St.refreshCommentUiLayout.apply(this,e)}initializeExportBridge(...e){return Lt.initializeExportBridge.apply(this,e)}handleExportRequest(...e){return Lt.handleExportRequest.apply(this,e)}formatPullBackupToast(...e){return z.formatPullBackupToast.apply(this,e)}setGitOperationStatus(...e){return z.setGitOperationStatus.apply(this,e)}runGitActionWithStatus(...e){return z.runGitActionWithStatus.apply(this,e)}handleGitDiffSelection(...e){return z.handleGitDiffSelection.apply(this,e)}handleGitCommitSelection(...e){return z.handleGitCommitSelection.apply(this,e)}handleGitHistorySelection(...e){return z.handleGitHistorySelection.apply(this,e)}handleGitFileHistorySelection(...e){return z.handleGitFileHistorySelection.apply(this,e)}handleGitFilePreviewSelection(...e){return z.handleGitFilePreviewSelection.apply(this,e)}handleGitRepoChange(...e){return z.handleGitRepoChange.apply(this,e)}syncFileHistoryButton(...e){return z.syncFileHistoryButton.apply(this,e)}syncMainChrome(...e){return z.syncMainChrome.apply(this,e)}showGitDiff(...e){return z.showGitDiff.apply(this,e)}showGitCommit(...e){return z.showGitCommit.apply(this,e)}showGitHistory(...e){return z.showGitHistory.apply(this,e)}showGitFileHistory(...e){return z.showGitFileHistory.apply(this,e)}showGitFilePreview(...e){return z.showGitFilePreview.apply(this,e)}postGitAction(...e){return z.postGitAction.apply(this,e)}refreshWorkspaceAfterGitAction(...e){return z.refreshWorkspaceAfterGitAction.apply(this,e)}refreshGitAfterAction(...e){return z.refreshGitAfterAction.apply(this,e)}finalizeGitAction(...e){return z.finalizeGitAction.apply(this,e)}handleWorkspaceChangeForCurrentFile(...e){return z.handleWorkspaceChangeForCurrentFile.apply(this,e)}handleIncomingWorkspaceEvent(...e){return z.handleIncomingWorkspaceEvent.apply(this,e)}stageGitFile(...e){return z.stageGitFile.apply(this,e)}unstageGitFile(...e){return z.unstageGitFile.apply(this,e)}pushGitBranch(...e){return z.pushGitBranch.apply(this,e)}pullGitBranch(...e){return z.pullGitBranch.apply(this,e)}openGitResetDialog(...e){return z.openGitResetDialog.apply(this,e)}handleGitResetSubmit(...e){return z.handleGitResetSubmit.apply(this,e)}openGitCommitDialog(...e){return z.openGitCommitDialog.apply(this,e)}handleGitCommitSubmit(...e){return z.handleGitCommitSubmit.apply(this,e)}updateGlobalUsers(...e){return B.updateGlobalUsers.apply(this,e)}updateFileAwareness(...e){return B.updateFileAwareness.apply(this,e)}closePresencePanel(...e){return B.closePresencePanel.apply(this,e)}openPresencePanel(...e){return B.openPresencePanel.apply(this,e)}renderPresence(...e){return B.renderPresence.apply(this,e)}renderAvatars(...e){return B.renderAvatars.apply(this,e)}renderPresencePanel(...e){return B.renderPresencePanel.apply(this,e)}startFollowingUser(...e){return B.startFollowingUser.apply(this,e)}toggleFollowUser(...e){return B.toggleFollowUser.apply(this,e)}togglePresencePanel(...e){return B.togglePresencePanel.apply(this,e)}stopFollowingUser(...e){return B.stopFollowingUser.apply(this,e)}syncFollowedUser(...e){return B.syncFollowedUser.apply(this,e)}followUserCursor(...e){return B.followUserCursor.apply(this,e)}followExcalidrawUser(...e){return B.followExcalidrawUser.apply(this,e)}resolveFileClientId(...e){return B.resolveFileClientId.apply(this,e)}bindEvents(...e){return U.bindEvents.apply(this,e)}clearInitialFileBootstrap(...e){return U.clearInitialFileBootstrap.apply(this,e)}closeToolbarOverflowMenu(...e){return U.closeToolbarOverflowMenu.apply(this,e)}applyPendingPreviewRouteAnchor(...e){return U.applyPendingPreviewRouteAnchor.apply(this,e)}copyPreviewHeadingLink(...e){return U.copyPreviewHeadingLink.apply(this,e)}createPreviewHeadingLinkUrl(...e){return U.createPreviewHeadingLinkUrl.apply(this,e)}getStoredLineWrapping(...e){return U.getStoredLineWrapping.apply(this,e)}handleConnectionChange(...e){return U.handleConnectionChange.apply(this,e)}handleDocumentKeydown(...e){return U.handleDocumentKeydown.apply(this,e)}handleDocumentPointerDown(...e){return U.handleDocumentPointerDown.apply(this,e)}handlePreviewContentClick(...e){return U.handlePreviewContentClick.apply(this,e)}handleThemeChange(...e){return U.handleThemeChange.apply(this,e)}hideEditorLoading(...e){return U.hideEditorLoading.apply(this,e)}initialize(...e){return U.initialize.apply(this,e)}initializeVisualViewportBinding(...e){return U.initializeVisualViewportBinding.apply(this,e)}initializeVersionMonitoring(...e){return U.initializeVersionMonitoring.apply(this,e)}navigatePreviewHeading(...e){return U.navigatePreviewHeading.apply(this,e)}promptForVersionReload(...e){return U.promptForVersionReload.apply(this,e)}requestPreviewRouteAnchor(...e){return U.requestPreviewRouteAnchor.apply(this,e)}scheduleBacklinkRefresh(...e){return U.scheduleBacklinkRefresh.apply(this,e)}setToolbarOverflowOpen(...e){return U.setToolbarOverflowOpen.apply(this,e)}showEditorLoadError(...e){return U.showEditorLoadError.apply(this,e)}showEditorLoading(...e){return U.showEditorLoading.apply(this,e)}syncPreviewHeadingLinkButtons(...e){return U.syncPreviewHeadingLinkButtons.apply(this,e)}syncVisualViewportBounds(...e){return U.syncVisualViewportBounds.apply(this,e)}syncToolbarOverflowVisibility(...e){return U.syncToolbarOverflowVisibility.apply(this,e)}syncWrapToggle(...e){return U.syncWrapToggle.apply(this,e)}toggleToolbarOverflowMenu(...e){return U.toggleToolbarOverflowMenu.apply(this,e)}toggleLineWrapping(...e){return U.toggleLineWrapping.apply(this,e)}applySidebarVisibility(...e){return U.applySidebarVisibility.apply(this,e)}closeSidebarOnMobile(...e){return U.closeSidebarOnMobile.apply(this,e)}isMobileViewport(...e){return U.isMobileViewport.apply(this,e)}restoreSidebarState(...e){return U.restoreSidebarState.apply(this,e)}setSidebarTab(...e){return U.setSidebarTab.apply(this,e)}setSidebarVisibility(...e){return U.setSidebarVisibility.apply(this,e)}toggleSidebar(...e){return U.toggleSidebar.apply(this,e)}getCurrentUser(...e){return U.getCurrentUser.apply(this,e)}getCurrentUserName(...e){return U.getCurrentUserName.apply(this,e)}getStoredUserName(...e){return U.getStoredUserName.apply(this,e)}handleDisplayNameSubmit(...e){return U.handleDisplayNameSubmit.apply(this,e)}isIdentityManagedByAuth(...e){return U.isIdentityManagedByAuth.apply(this,e)}openDisplayNameDialog(...e){return U.openDisplayNameDialog.apply(this,e)}promptForDisplayNameIfNeeded(...e){return U.promptForDisplayNameIfNeeded.apply(this,e)}syncCurrentUserName(...e){return U.syncCurrentUserName.apply(this,e)}syncIdentityManagementUi(...e){return U.syncIdentityManagementUi.apply(this,e)}applyMarkdownToolbarAction(...e){return U.applyMarkdownToolbarAction.apply(this,e)}copyCurrentLink(...e){return U.copyCurrentLink.apply(this,e)}closeMarkdownBlockMenu(...e){return U.closeMarkdownBlockMenu.apply(this,e)}getActiveMarkdownBlockAction(...e){return U.getActiveMarkdownBlockAction.apply(this,e)}getMarkdownBlockMenuPopover(...e){return U.getMarkdownBlockMenuPopover.apply(this,e)}handleEditorImageInsert(...e){return U.handleEditorImageInsert.apply(this,e)}handleMarkdownToolbarClick(...e){return U.handleMarkdownToolbarClick.apply(this,e)}handleMarkdownToolbarDocumentPointerDown(...e){return U.handleMarkdownToolbarDocumentPointerDown.apply(this,e)}handleMarkdownToolbarKeydown(...e){return U.handleMarkdownToolbarKeydown.apply(this,e)}handleToolbarImageInsert(...e){return U.handleToolbarImageInsert.apply(this,e)}isMarkdownBlockMenuOpen(...e){return U.isMarkdownBlockMenuOpen.apply(this,e)}openMarkdownBlockMenu(...e){return U.openMarkdownBlockMenu.apply(this,e)}positionMarkdownBlockMenu(...e){return U.positionMarkdownBlockMenu.apply(this,e)}renderMarkdownBlockMenuPopover(...e){return U.renderMarkdownBlockMenuPopover.apply(this,e)}pickImageFile(...e){return U.pickImageFile.apply(this,e)}renderMarkdownToolbar(...e){return U.renderMarkdownToolbar.apply(this,e)}runEditorCommand(...e){return U.runEditorCommand.apply(this,e)}setActiveMarkdownBlockAction(...e){return U.setActiveMarkdownBlockAction.apply(this,e)}syncMarkdownToolbarBlockUi(...e){return U.syncMarkdownToolbarBlockUi.apply(this,e)}toggleMarkdownBlockMenu(...e){return U.toggleMarkdownBlockMenu.apply(this,e)}handleTabActivated(...e){return U.handleTabActivated.apply(this,e)}handleTabBlocked(...e){return U.handleTabBlocked.apply(this,e)}handleTabTakeover(...e){return U.handleTabTakeover.apply(this,e)}hideTabLockOverlay(...e){return U.hideTabLockOverlay.apply(this,e)}showTabLockOverlay(...e){return U.showTabLockOverlay.apply(this,e)}isExcalidrawFile(...e){return W.isExcalidrawFile.apply(this,e)}isBaseFile(...e){return W.isBaseFile.apply(this,e)}isDrawioFile(...e){return W.isDrawioFile.apply(this,e)}isImageFile(...e){return W.isImageFile.apply(this,e)}isMermaidFile(...e){return W.isMermaidFile.apply(this,e)}isPlantUmlFile(...e){return W.isPlantUmlFile.apply(this,e)}createDiagramPreviewDocument(...e){return W.createDiagramPreviewDocument.apply(this,e)}getPreviewSource(...e){return W.getPreviewSource.apply(this,e)}getStaticPreviewDocument(...e){return W.getStaticPreviewDocument.apply(this,e)}setStaticPreviewDocument(...e){return W.setStaticPreviewDocument.apply(this,e)}clearStaticPreviewDocument(...e){return W.clearStaticPreviewDocument.apply(this,e)}supportsFileHistory(...e){return W.supportsFileHistory.apply(this,e)}getDisplayName(...e){return W.getDisplayName.apply(this,e)}resetPreviewMode(...e){return W.resetPreviewMode.apply(this,e)}syncFileChrome(...e){return W.syncFileChrome.apply(this,e)}handleLayoutViewRequest(...e){return W.handleLayoutViewRequest.apply(this,e)}renderExcalidrawFilePreview(...e){return W.renderExcalidrawFilePreview.apply(this,e)}renderDrawioFilePreview(...e){return W.renderDrawioFilePreview.apply(this,e)}renderImageFilePreview(...e){return W.renderImageFilePreview.apply(this,e)}renderBaseFilePreview(...e){return W.renderBaseFilePreview.apply(this,e)}renderTextFilePreview(...e){return W.renderTextFilePreview.apply(this,e)}createResizeHandler(...e){return W.createResizeHandler.apply(this,e)}initializePreviewLayoutObserver(...e){return W.initializePreviewLayoutObserver.apply(this,e)}schedulePreviewLayoutSync(...e){return W.schedulePreviewLayoutSync.apply(this,e)}handleEditorScrollActivityChange(...e){return W.handleEditorScrollActivityChange.apply(this,e)}handleHashChange(...e){return W.handleHashChange.apply(this,e)}showEmptyState(...e){return W.showEmptyState.apply(this,e)}showDiffState(...e){return W.showDiffState.apply(this,e)}openFile(...e){return W.openFile.apply(this,e)}cleanupSession(...e){return W.cleanupSession.apply(this,e)}handleWikiLinkClick(...e){return W.handleWikiLinkClick.apply(this,e)}normalizeNewWikiFilePath(...e){return W.normalizeNewWikiFilePath.apply(this,e)}createAndOpenFile(...e){return W.createAndOpenFile.apply(this,e)}handleFileSelection(...e){return W.handleFileSelection.apply(this,e)}constructor(){pu(document),this.elements=xt(document),this.runtimeConfig=D(),this.stateStore=new bt,this.navigation=new ri,this.preferences=new ai({chatNotificationsKey:`collabmd-chat-notifications-enabled`,lineWrappingKey:`collabmd-editor-line-wrap`,sidebarVisibleKey:`collabmd-sidebar-visible`,userNameKey:`collabmd-user-name`}),this.notifications=new ii,this.backlinksApiClient=li,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.mobileBreakpointQuery=window.matchMedia(`(max-width: 768px)`),this.pendingWorkspaceRequestIds=new Set,this._fileOpenPerf=null,this.versionMonitor=new ci({currentBuildId:this.runtimeConfig.build?.id,onUpdateAvailable:e=>this.promptForVersionReload(e),runtimeConfig:this.runtimeConfig}),this.lobby=new ni({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.fileExplorerReady=!0,!n&&this.isTabActive&&this.handleHashChange()},onWorkspaceEvent:e=>{this.handleIncomingWorkspaceEvent(e)}}),this.toastController=new dl(this.elements.toastContainer),this.chatToastController=new dl(this.elements.chatToastContainer),this.fileExplorer=new mc({mobileBreakpointQuery:this.mobileBreakpointQuery,onFileDelete:()=>this.navigation.navigateToFile(null),onFileSelect:e=>this.handleFileSelection(e,{closeSidebarOnMobile:!0}),pendingWorkspaceRequestIds:this.pendingWorkspaceRequestIds,toastController:this.toastController}),this.gitPanel=new Kc({enabled:this.runtimeConfig.gitEnabled!==!1,gitApiClient:this.gitApiClient,onCommitStaged:()=>this.openGitCommitDialog(),onOpenPullBackup:e=>e&&this.navigation.navigateToFile(e),onPullBranch:()=>this.pullGitBranch(),onPushBranch:()=>this.pushGitBranch(),onRepoChange:(e,t)=>this.handleGitRepoChange(e,t),onResetFile:(e,{scope:t})=>this.openGitResetDialog(e,{scope:t}),onSelectCommit:(e,{path:t})=>this.handleGitCommitSelection(e,{closeSidebarOnMobile:!0,path:t}),onSelectDiff:(e,{scope:t})=>this.handleGitDiffSelection(e,{closeSidebarOnMobile:!0,scope:t}),onStageFile:(e,{scope:t})=>this.stageGitFile(e,{scope:t}),onUnstageFile:(e,{scope:t})=>this.unstageGitFile(e,{scope:t}),onViewAllDiff:()=>this.handleGitDiffSelection(null,{closeSidebarOnMobile:!0,scope:`all`}),searchInput:this.elements.gitSearchInput,toastController:this.toastController}),this.outlineController=new Jc({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 _l({previewElement:this.elements.previewContent}),this.basesPreview=new Ka({getActiveFilePath:()=>this.currentFilePath,getSession:()=>this.session,onOpenFile:e=>e&&this.navigation.navigateToFile(e),previewElement:this.elements.previewContent,replaceBaseSource:({path:e,source:t})=>{e&&e===this.currentFilePath&&this.session?.replaceText?.(t)},toastController:this.toastController,vaultApiClient:this.vaultApiClient}),this.imageLightbox=new El({previewElement:this.elements.previewContent}),this.previewRenderer=new rt({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 ul({onChange:e=>this.handleThemeChange(e)}),this.layoutController=new qc({mobileBreakpointQuery:this.mobileBreakpointQuery,onMeasureEditor:()=>this.session?.requestMeasure(),onViewRequest:e=>this.handleLayoutViewRequest(e)}),this.scrollSyncController=new sl({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=new Gs({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}),this.drawioEmbed=new Ns({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}),this.commentUi=new Ts({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.session?.createCommentThread({anchor:e,body:t}),onNavigateToLine:e=>{this.scrollSyncController.suspendSync(250),this.session?.scrollToLine(e,.2)},onReplyToThread:(e,t)=>this.session?.replyToCommentThread(e,t),onToggleReaction:(e,t,n)=>this.session?.toggleCommentReaction(e,t,n),onResolveThread:e=>this.session?.deleteCommentThread(e)}),this.workspacePreviewController=new mt({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 pt({getFileList:()=>this.fileExplorer.flatDocumentFiles,navigation:this.navigation,refreshExplorer:()=>this.fileExplorer.refresh(),toastController:this.toastController,vaultApiClient:this.vaultApiClient,wikiLinkAutoCreate:this.runtimeConfig.wikiLinkAutoCreate!==!1}),this.gitDiffView=new Pc({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}),this.fileHistoryView=new Sc({diffRenderer:this.gitDiffView,gitApiClient:this.gitApiClient,onOpenCommitDiff:(e,{historyFilePath:t,path:n})=>this.handleGitCommitSelection(e,{closeSidebarOnMobile:!1,historyFilePath:t,path:n}),onOpenFile:e=>e&&this.navigation.navigateToFile(e),onOpenPreview:({hash:e,path:t,currentFilePath:n})=>this.handleGitFilePreviewSelection({hash:e,path:t,currentFilePath:n}),onOpenWorkspaceDiff:e=>this.handleGitDiffSelection(e,{closeSidebarOnMobile:!1,scope:`all`}),toastController:this.toastController}),this.tabActivityLock=new Si({onActivated:({takeover:e})=>this.handleTabActivated({takeover:e}),onBlocked:()=>this.handleTabBlocked({reason:`active-elsewhere`}),onStolen:()=>this.handleTabBlocked({reason:`taken-over`})}),this.workspaceCoordinator=new yt({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.stateStore}),this.workspaceRouteController=new ot({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}get currentFilePath(){return this.stateStore.get(`currentFilePath`)}set currentFilePath(e){this.stateStore.set(`currentFilePath`,e)}get currentDrawioMode(){return this.stateStore.get(`currentDrawioMode`)}set currentDrawioMode(e){this.stateStore.set(`currentDrawioMode`,e??null)}get globalUsers(){return this.stateStore.get(`globalUsers`)}set globalUsers(e){this.stateStore.set(`globalUsers`,e)}get connectionState(){return this.stateStore.get(`connectionState`)}set connectionState(e){this.stateStore.set(`connectionState`,e)}get sessionLoadToken(){return this.stateStore.get(`sessionLoadToken`)}set sessionLoadToken(e){this.stateStore.set(`sessionLoadToken`,e)}get connectionHelpShown(){return this.stateStore.get(`connectionHelpShown`)}set connectionHelpShown(e){this.stateStore.set(`connectionHelpShown`,e)}get chatMessages(){return this.stateStore.get(`chatMessages`)}set chatMessages(e){this.stateStore.set(`chatMessages`,e)}get chatMessageIds(){return this.stateStore.get(`chatMessageIds`)}set chatMessageIds(e){this.stateStore.set(`chatMessageIds`,e)}get chatUnreadCount(){return this.stateStore.get(`chatUnreadCount`)}set chatUnreadCount(e){this.stateStore.set(`chatUnreadCount`,e)}get chatIsOpen(){return this.stateStore.get(`chatIsOpen`)}set chatIsOpen(e){this.stateStore.set(`chatIsOpen`,e)}get chatInitialSyncComplete(){return this.stateStore.get(`chatInitialSyncComplete`)}set chatInitialSyncComplete(e){this.stateStore.set(`chatInitialSyncComplete`,e)}get isTabActive(){return this.stateStore.get(`isTabActive`)}set isTabActive(e){this.stateStore.set(`isTabActive`,e)}get fileExplorerReady(){return this.stateStore.get(`fileExplorerReady`)}set fileExplorerReady(e){this.stateStore.set(`fileExplorerReady`,e)}get gitRepoAvailable(){return this.stateStore.get(`gitRepoAvailable`)}set gitRepoAvailable(e){this.stateStore.set(`gitRepoAvailable`,e)}get activeSidebarTab(){return this.stateStore.get(`activeSidebarTab`)}set activeSidebarTab(e){this.stateStore.set(`activeSidebarTab`,e)}get presencePanelOpen(){return this.stateStore.get(`presencePanelOpen`)}set presencePanelOpen(e){this.stateStore.set(`presencePanelOpen`,e)}get followedUserClientId(){return this.stateStore.get(`followedUserClientId`)}set followedUserClientId(e){this.stateStore.set(`followedUserClientId`,e)}get followedCursorSignature(){return this.stateStore.get(`followedCursorSignature`)}set followedCursorSignature(e){this.stateStore.set(`followedCursorSignature`,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-C1scHGLl.js`).then(e=>e.EditorSession),__vite__mapDeps([27,1,28,29,30,31,32,33,34,35,36,37,38,39,26]),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-B1erSgJ1.js`).then(e=>e.QuickSwitcherController),__vite__mapDeps([40,25,26]),import.meta.url)}async ensureQuickSwitcher(){return it(this)}async toggleQuickSwitcher(){return at(this)}};async function hu(){await C(),new mu().initialize()}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{hu()},{once:!0}):hu();
|