collabmd 0.1.33 → 0.1.34
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/dist/client/assets/{index-Czg_KL-i.js → index-BLrtj9YM.js} +2 -2
- package/dist/client/assets/{main-DeowJOSp.js → main-CfSHaGes.js} +86 -86
- package/dist/client/index.html +1 -1
- package/package.json +2 -1
- package/src/client/application/app-shell/git-feature.js +44 -36
- package/src/client/application/app-shell/ui-feature-shell.js +84 -63
- package/src/client/presentation/excalidraw-embed-controller.js +4 -1
- package/src/client/presentation/file-history-view-controller.js +9 -1
- package/src/client/presentation/git-panel-controller.js +101 -91
- package/src/server/domain/backlink-index.js +41 -22
- package/src/server/infrastructure/http/create-request-handler.js +63 -28
- package/src/server/infrastructure/http/create-vault-api-command-handler.js +275 -256
- package/src/server/infrastructure/http/create-vault-api-query-handler.js +255 -233
- package/src/server/infrastructure/persistence/vault-file-store.js +68 -12
|
@@ -24,14 +24,14 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
24
24
|
`),path:n}}function Re(e){let t=F(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(`
|
|
25
25
|
`),path:n}}function ze(e){let t=F(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(`
|
|
26
26
|
`),path:n}}function Be(e){let t=F(e),n=s(t)?t:`${t}.puml`;return{content:[`@startuml`,`Alice -> Bob: Hello`,`@enduml`,``].join(`
|
|
27
|
-
`),path:n}}var Ve=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=F(e);return t?t.endsWith(`.md`)?t:`${t}.md`:null}async createAndOpenFile(e,t){try{await this.vaultApiClient.createFile({content:Ie(t||e),path:e}),await this.refreshExplorer(),this.navigation.navigateToFile(e)}catch(e){this.toastController.show(`Failed to create file: ${e.message}`)}}},He=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=T(`/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}))}},Ue=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)}},We=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()}},Ge=150;function Ke(e){return new Promise(t=>{setTimeout(t,e)})}var qe=class{constructor({attachEditorScroller:e,beginDocumentLoad:t,cleanupAfterSessionDestroy:n,createEditorSession:r,getDisplayName:i,getFileList:a,getLineWrappingEnabled:o,getLocalUser:s,getStoredUserName:c,getTheme:l,isBaseFile:u,isDrawioFile:d,isExcalidrawFile:f,isImageFile:p,isMermaidFile:m,isPlantUmlFile:h,isTabActive:g,loadBootstrapContent:_=null,loadEditorSessionClass:v,loadBacklinks:y,onBeforeFileOpen:b,onConnectionChange:x,onContentChange:ee,onCommentsChange:S,onFileAwarenessChange:te,onFileOpenError:C,onFileOpenReady:w,onImagePaste:ne,onSelectionChange:re,onSessionAssigned:T=null,onFileOpenMetric:ie=null,onRenderBasePreview:E,onRenderExcalidrawPreview:D,onRenderDrawioPreview:O,onRenderImagePreview:ae,onSyncWrapToggle:k,onUpdateActiveFile:A,onUpdateCurrentFile:oe,onUpdateLobbyCurrentFile:se,onUpdateVisibleChrome:ce,onViewModeReset:le,renderPresence:j,scrollContainerForSession:ue,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=ee,this.onCommentsChange=S,this.onFileAwarenessChange=te,this.onFileOpenError=C,this.onFileOpenReady=w,this.onImagePaste=ne,this.onSelectionChange=re,this.onSessionAssigned=T,this.onFileOpenMetric=ie,this.onRenderBasePreview=E,this.onRenderExcalidrawPreview=D,this.onSyncWrapToggle=k,this.onUpdateActiveFile=A,this.onUpdateCurrentFile=oe,this.onUpdateLobbyCurrentFile=se,this.onUpdateVisibleChrome=ce,this.renderPresence=j,this.shouldUseDrawioPreview=de??(()=>!0),this.stateStore=pe,this.session=null,this.lifecycle=new Ue({attachEditorScroller:e,createEditorSession:r,loadEditorSessionClass:()=>this.loadEditorSessionClassPort(),scrollContainerForSession:ue}),this.chromeController=new We({beginDocumentLoad:t,getDisplayName:i,loadBacklinks:y,onBeforeFileOpen:b,onRenderDrawioPreview:O,onFileOpenError:C,onFileOpenReady:w,onRenderBasePreview:E,onRenderExcalidrawPreview:D,onRenderImagePreview:ae,onSyncWrapToggle:k,onUpdateActiveFile:A,onUpdateCurrentFile:oe,onUpdateLobbyCurrentFile:se,onUpdateVisibleChrome:ce,onViewModeReset:le,renderPresence:j,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,Ge-a);return o>0&&await Promise.race([l.then(e=>e?`live-sync`:`stale`),Ke(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()}}},Je=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,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 Ye(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`),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 L={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)}},Xe={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()}},Ze=`collabmd-export-page`,Qe=`collabmd-export-host`,$e=500,et=6e4,tt=new Map,nt=null;function rt(){return`export-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function it(e){return e===`pdf`?`pdf`:`docx`}function at({filePath:e,format:t,jobId:n}){let r=new URL(w(`/export-document.html`),window.location.origin);return r.searchParams.set(`action`,it(t)),r.searchParams.set(`job`,n),e&&r.searchParams.set(`file`,e),r.toString()}function ot({fileList:e=[],filePath:t,format:n,jobId:r,markdownText:i=``,title:a=``}){return{action:it(n),fileList:Array.isArray(e)?e.slice():[],filePath:String(t??``),jobId:r,markdownText:String(i??``),source:Qe,title:String(a??``),type:`bootstrap`}}function st(e){e&&(e.closePollId&&window.clearInterval(e.closePollId),e.timeoutId&&window.clearTimeout(e.timeoutId))}function ct(e,{notifyError:t=!1,message:n=``}={}){let r=tt.get(e);r&&(st(r),tt.delete(e),t&&n&&nt?.(n))}function lt({onError:e=null}={}){nt=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!==Ze)return;let n=String(t.jobId??``).trim();if(!n)return;let r=tt.get(n);if(r){if(t.type===`ready`){if(r.window?.closed){ct(n,{message:`Export window was closed before the export completed`,notifyError:!0});return}try{r.window?.postMessage(r.payload,window.location.origin)}catch(e){ct(n,{message:e instanceof Error?e.message:`Failed to send export data`,notifyError:!0})}return}(t.type===`complete`||t.type===`error`)&&ct(n,{message:t.type===`error`&&t.message?String(t.message):``,notifyError:t.type===`error`&&!!t.message})}}),window.__collabmdExportBridgeInitialized=!0)}async function ut({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=rt(),s=at({filePath:a,format:n,jobId:o}),c=window.open(s,`_blank`);if(!c)throw Error(`Export popup was blocked`);return tt.set(o,{closePollId:window.setInterval(()=>{c.closed&&ct(o,{message:`Export window was closed before the export completed`,notifyError:!0})},$e),payload:ot({fileList:e,filePath:a,format:n,jobId:o,markdownText:r,title:i}),timeoutId:window.setTimeout(()=>{ct(o,{message:`Export timed out before it completed`,notifyError:!0})},et),window:c}),c.focus?.(),o}var dt={initializeExportBridge(){this._exportBridgeInitialized||=(lt({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 ut({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 ft(e=[]){return Array.from(new Set((e??[]).filter(Boolean)))}function pt(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 mt(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 ht({changedPaths:e=[],deletedPaths:t=[],refreshExplorer:n=!0,renamedPaths:r=[]}={}){return{changedPaths:ft(e),deletedPaths:ft(t),refreshExplorer:n!==!1,renamedPaths:pt(r)}}function gt(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:mt(e.highlightRanges),id:e.id,origin:typeof e.origin==`string`?e.origin:`api`,reloadRequiredPaths:ft(e.reloadRequiredPaths),requestId:typeof e.requestId==`string`?e.requestId:null,sourceRef:typeof e.sourceRef==`string`?e.sourceRef:null,workspaceChange:ht(e.workspaceChange)}}function _t(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`workspace-${Date.now()}-${Math.random().toString(16).slice(2,10)}`}function vt(e={}){return ht(e)}var R={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 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{let n=await this.gitApiClient.readFileSnapshot({hash:e,path:t});if(this.setStaticPreviewDocument?.({...n,currentFilePath:r}),this.resetPreviewMode(),this.elements.markdownToolbar?.classList.add(`hidden`),this.elements.outlineToggle?.classList.toggle(`hidden`,n.fileKind!==`markdown`),n.fileKind===`markdown`||n.fileKind===`mermaid`||n.fileKind===`plantuml`){n.fileKind===`mermaid`?this.elements.previewContent?.classList.add(`is-mermaid-file-preview`):n.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:n.content,filePath:r})}catch(e){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:r}),this.elements.outlineToggle?.classList.add(`hidden`)}},async postGitAction(e,t){let n=_t();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=vt(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=vt(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)}}}},z={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=!!this.session,n=!!(this.currentFilePath&&this.isDrawioFile?.(this.currentFilePath)),r=!!(this.currentFilePath&&this.isExcalidrawFile?.(this.currentFilePath)),i=!!(this.currentFilePath&&this.isImageFile?.(this.currentFilePath)),a=!t&&(!this.currentFilePath||n||r||i)?this.lobby?.getConnectionState?.()??this.connectionState:this.connectionState;if(a.status===`connected`){e.textContent=`${this.globalUsers.length} online`,e.style.opacity=`1`;return}if(a.status===`connecting`){e.textContent=a.unreachable?`Unreachable`:`Connecting...`,e.style.opacity=`0.6`;return}e.textContent=`Offline`,e.style.opacity=`0.6`},renderAvatars(){let e=this.elements.userAvatars;if(!e)return;e.innerHTML=``;let t=[...this.globalUsers],n=t.findIndex(e=>e.isLocal);if(n>0){let[e]=t.splice(n,1);t.unshift(e)}let r=t.findIndex(e=>!e.isLocal&&e.clientId===this.followedUserClientId),i=t[0]?.isLocal?1:0;if(r>i){let[e]=t.splice(r,1);t.splice(i,0,e)}if(t.slice(0,5).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>5){let n=document.createElement(`div`);n.className=`user-avatar`,n.style.backgroundColor=`var(--color-surface-dynamic)`,n.style.color=`var(--color-text-muted)`;let r=document.createElement(`span`);r.className=`user-avatar-initial`,r.textContent=`+${t.length-5}`,n.appendChild(r),e.appendChild(n)}},toggleFollowUser(e){if(!e)return;if(this.followedUserClientId===e){this.stopFollowingUser();return}let t=this.globalUsers.find(t=>t.clientId===e&&!t.isLocal);if(t){if(this.followedUserClientId=e,this.followedCursorSignature=``,this.renderAvatars(),t.currentFile&&t.currentFile!==this.currentFilePath){this.navigation.navigateToFile(t.currentFile);return}requestAnimationFrame(()=>{this.followedUserClientId===e&&this.followUserCursor(t,{force:!0})})}},stopFollowingUser(){this.followedUserClientId&&(this.currentFilePath&&this.isExcalidrawFile?.(this.currentFilePath)&&this.excalidrawEmbed?.setFollowedUser(this.currentFilePath,null),this.followedUserClientId=null,this.followedCursorSignature=``,this.renderAvatars())},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 yt(){return this.runtimeConfig?.auth?.strategy===`oidc`&&this.runtimeConfig?.auth?.provider===`google`}function bt({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 xt(){!this.isTabActive||this._hasPromptedForDisplayName||this.getStoredUserName()||this.isIdentityManagedByAuth()||(this._hasPromptedForDisplayName=!0,requestAnimationFrame(()=>{this.openDisplayNameDialog({mode:`onboarding`})}))}function St(){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):Se(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 Ct(){return this.globalUsers.find(e=>e.isLocal)??this.session?.getLocalUser()??this.lobby?.getLocalUser()??null}function wt(){return this.getCurrentUser()?.name??this.getStoredUserName()??``}function Tt(){return this.preferences.getUserName()}function Et(){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 Dt(){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 Ot={getCurrentUser:Ct,getCurrentUserName:wt,getStoredUserName:Tt,handleDisplayNameSubmit:St,isIdentityManagedByAuth:yt,openDisplayNameDialog:bt,promptForDisplayNameIfNeeded:xt,syncCurrentUserName:Et,syncIdentityManagementUi:Dt},kt=0;function At(){this.initializeExportBridge?.(),this.renderMarkdownToolbar?.(),this.initializeVisualViewportBinding?.(),this.themeController.initialize(),this.previewRenderer.applyTheme(this.themeController.getTheme()),this.previewRenderer.scheduleWorkerPrewarm(),this.scheduleEditorSessionPrewarm?.(),this.outlineController.initialize(),this.layoutController.initialize(),this.scrollSyncController.initialize(),this.fileExplorer.initialize(),this.gitPanel.initialize(),this.gitDiffView.initialize(),this.fileHistoryView.initialize(),this.initializePreviewLayoutObserver(),this.syncIdentityManagementUi(),this.syncCurrentUserName(),this.syncWrapToggle(),this.syncToolbarOverflowVisibility?.(),this.syncChatNotificationButton(),this.syncFileHistoryButton({mode:`empty`}),this.renderChat(),this.gitPanel.refresh({force:!0}),this.elements.chatInput?.setAttribute(`maxlength`,String(this.lobbyChatMessageMaxLength)),this.bindEvents(),this.restoreSidebarState(),this.initializeVersionMonitoring(),this.tabActivityLock.initialize(),this.tabActivityLock.tryActivate(),window.addEventListener(`hashchange`,()=>this.handleHashChange());let e=this.createResizeHandler();window.addEventListener(`resize`,()=>{e(),this.syncToolbarOverflowVisibility?.()}),this.fileExplorerReadyPromise=this.fileExplorer.refresh().then(()=>{if(this.fileExplorerReady=!0,this.isTabActive)return this.handleHashChange()})}function jt(){this.versionMonitor?.start()}function Mt(){let e=document.documentElement,t=window.visualViewport;if(e){if(!t){e.style.setProperty(`--app-viewport-height`,`100dvh`),e.style.setProperty(`--app-viewport-offset-top`,`0px`);return}e.style.setProperty(`--app-viewport-height`,`${Math.round(t.height)}px`),e.style.setProperty(`--app-viewport-offset-top`,`${Math.round(t.offsetTop)}px`)}}function Nt(){this.syncVisualViewportBounds?.();let e=window.visualViewport;if(!e)return;let t=()=>this.syncVisualViewportBounds?.();e.addEventListener(`resize`,t,{passive:!0}),e.addEventListener(`scroll`,t,{passive:!0}),window.addEventListener(`orientationchange`,t)}function Pt(e=null){if(this._reloadPromptShown)return;this._reloadPromptShown=!0;let t=String(e?.build?.packageVersion??this.runtimeConfig?.build?.packageVersion??``).trim(),n=t?`Version ${t} is available. Reload to update.`:`A new version is available. Reload to update.`;this.toastController.show(n,{actionLabel:`Reload`,dismissible:!0,duration:kt,onAction:()=>window.location.reload()})}function Ft(){this.elements.emptyStateNewFileBtn?.addEventListener(`click`,()=>{this.fileExplorer.actionController.openRootCreateMenu({anchor:this.elements.emptyStateNewFileBtn})}),this.elements.emptyStateSearchBtn?.addEventListener(`click`,()=>{this.toggleQuickSwitcher()}),this.elements.chatToggleButton?.addEventListener(`click`,()=>{this.toggleChatPanel(),this.closeToolbarOverflowMenu?.()}),this.elements.chatForm?.addEventListener(`submit`,e=>{e.preventDefault(),this.handleChatSubmit()}),this.elements.chatNotificationButton?.addEventListener(`click`,()=>{this.handleChatNotificationToggle()}),this.elements.shareButton?.addEventListener(`click`,()=>{this.copyCurrentLink(),this.closeToolbarOverflowMenu?.()}),this.elements.searchFilesButton?.addEventListener(`click`,()=>{this.toggleQuickSwitcher(),this.closeToolbarOverflowMenu?.()}),this.elements.exportDocxButton?.addEventListener(`click`,()=>{this.handleExportRequest?.(`docx`),this.closeToolbarOverflowMenu?.()}),this.elements.exportPdfButton?.addEventListener(`click`,()=>{this.handleExportRequest?.(`pdf`),this.closeToolbarOverflowMenu?.()}),this.elements.fileHistoryButton?.addEventListener(`click`,()=>{let e=this.navigation.getHashRoute();if(e.type===`git-file-preview`){this.handleGitFileHistorySelection(e.currentFilePath??e.filePath,{closeSidebarOnMobile:!0}),this.closeToolbarOverflowMenu?.();return}this.handleGitFileHistorySelection(this.currentFilePath,{closeSidebarOnMobile:!0}),this.closeToolbarOverflowMenu?.()}),this.elements.editNameButton?.addEventListener(`click`,()=>{this.openDisplayNameDialog(),this.closeToolbarOverflowMenu?.()}),this.elements.displayNameCancel?.addEventListener(`click`,()=>{this.elements.displayNameDialog?.close()}),this.elements.gitCommitCancel?.addEventListener(`click`,()=>{this.elements.gitCommitDialog?.close()}),this.elements.gitResetCancel?.addEventListener(`click`,()=>{this.elements.gitResetDialog?.close()}),this.elements.gitResetSubmit?.addEventListener(`click`,()=>{this.handleGitResetSubmit()}),this.elements.gitCommitDialog?.addEventListener(`close`,()=>{this.elements.gitCommitInput&&(this.elements.gitCommitInput.value=``),this.elements.gitCommitSubmit&&(this.elements.gitCommitSubmit.textContent=`Commit staged changes`)}),this.elements.gitResetDialog?.addEventListener(`close`,()=>{this.pendingGitResetPath=null,this.elements.gitResetFileName&&(this.elements.gitResetFileName.value=``),this.elements.gitResetSubmit&&(this.elements.gitResetSubmit.textContent=`Reset File`)}),this.elements.markdownToolbar?.addEventListener(`click`,e=>{this.handleMarkdownToolbarClick?.(e)}),this.elements.markdownToolbar?.addEventListener(`keydown`,e=>{this.handleMarkdownToolbarKeydown?.(e)}),this.elements.displayNameForm?.addEventListener(`submit`,e=>{e.preventDefault(),this.handleDisplayNameSubmit()}),this.elements.gitCommitForm?.addEventListener(`submit`,e=>{e.preventDefault(),this.handleGitCommitSubmit()}),this.elements.tabLockTakeoverButton?.addEventListener(`click`,()=>{this.handleTabTakeover()}),this.elements.toggleWrapButton?.addEventListener(`click`,()=>{this.toggleLineWrapping()}),this.elements.editorFindButton?.addEventListener(`click`,()=>{this.runEditorCommand?.(`openSearch`)}),this.elements.toolbarOverflowToggle?.addEventListener(`click`,e=>{e.preventDefault(),this.toggleToolbarOverflowMenu()}),this.elements.toolbarOverflowMenu?.addEventListener(`click`,e=>{e.target instanceof Element&&e.target.closest(`button`)&&this.closeToolbarOverflowMenu()}),this.elements.previewContent?.addEventListener(`click`,e=>{this.handlePreviewContentClick?.(e)}),this.elements.sidebarToggle?.addEventListener(`click`,()=>{this.closeToolbarOverflowMenu(),this.toggleSidebar()}),this.elements.sidebarClose?.addEventListener(`click`,()=>{this.closeSidebarOnMobile()}),this.elements.filesSidebarTab?.addEventListener(`click`,()=>{this.setSidebarTab(`files`)}),this.elements.gitSidebarTab?.addEventListener(`click`,()=>{this.gitRepoAvailable&&this.setSidebarTab(`git`)}),document.addEventListener(`pointerdown`,e=>{this.handleMarkdownToolbarDocumentPointerDown?.(e),this.toolbarOverflowOpen&&!this.elements.toolbarOverflowMenu?.contains(e.target)&&!this.elements.toolbarOverflowToggle?.contains(e.target)&&this.closeToolbarOverflowMenu(),this.chatIsOpen&&(this.elements.chatContainer?.contains(e.target)||this.closeChatPanel())}),document.addEventListener(`keydown`,e=>{if(e.key===`Escape`&&this.toolbarOverflowOpen){this.closeToolbarOverflowMenu();return}if(e.key===`Escape`&&this.chatIsOpen){this.closeChatPanel();return}(e.metaKey||e.ctrlKey)&&e.key===`k`&&(e.preventDefault(),this.toggleQuickSwitcher())})}function It(e,t){let n=e.closest(`ul, ol`);return n instanceof Element&&n.parentElement===t}function Lt(e){return e.closest(`input[data-task-checkbox="true"]`)?!1:!!e.closest(`a, button, input, select, textarea, summary, [contenteditable="true"], [role="button"], [role="link"]`)}function Rt(e){if(!(e.target instanceof Element))return;let t=e.target.closest(`a.wiki-link[data-wiki-target]`);if(t){e.preventDefault(),this.handleWikiLinkClick(t.dataset.wikiTarget);return}let n=e.target.closest(`.task-list-item[data-source-line]`);if(!n||It(e.target,n)||Lt(e.target))return;e.preventDefault();let r=Number.parseInt(n.getAttribute(`data-source-line`)||``,10);Number.isFinite(r)&&this.session?.toggleTaskListItem?.(r)}function zt(e){this.toolbarOverflowOpen=!!e,this.elements.toolbarOverflowToggle?.setAttribute(`aria-expanded`,String(this.toolbarOverflowOpen)),this.elements.toolbarOverflowToggle?.classList.toggle(`active`,this.toolbarOverflowOpen),this.elements.toolbarOverflowToggle?.closest(`.toolbar-right`)?.classList.toggle(`is-overflow-open`,this.toolbarOverflowOpen),this.toolbarOverflowOpen||this.elements.toolbarOverflowMenu?.querySelectorAll(`details[open]`).forEach(e=>{e.removeAttribute(`open`)})}function Bt(){let e=this.elements.toolbarOverflowToggle;e&&(e.classList.remove(`hidden`),e.hidden=!1,e.setAttribute(`aria-hidden`,`false`))}function Vt(){this.setToolbarOverflowOpen(!1)}function Ht(){this.setToolbarOverflowOpen(!this.toolbarOverflowOpen)}function Ut(e){this.previewRenderer.applyTheme(e),!this.isExcalidrawFile(this.currentFilePath)&&!this.isImageFile?.(this.currentFilePath)&&this.previewRenderer.queueRender(),this.session?.applyTheme(e),this.excalidrawEmbed.updateTheme(e),this.drawioEmbed.updateTheme(e)}function Wt(e){this.connectionState=e,e?.firstConnection&&this.recordFileOpenMetric?.(`ws_connected`,{status:e.status}),this.renderPresence(),e.unreachable&&!this.connectionHelpShown&&(this.connectionHelpShown=!0,this.toastController.show(`Cannot reach server at ${e.wsBaseUrl}`,6e3))}function Gt(){let e=!(this.session?.isLineWrappingEnabled()??this.getStoredLineWrapping());this.session?.setLineWrapping(e),this.preferences.setLineWrappingEnabled(e),this.syncWrapToggle(e),this.session?.requestMeasure(),this.scrollSyncController.syncPreviewToEditor()}function Kt(){return this.preferences.getLineWrappingEnabled()}function qt(e){let t=e??this.session?.isLineWrappingEnabled()??this.getStoredLineWrapping(),n=this.elements.wrapToggleLabel,r=this.elements.toggleWrapButton,i=t?`Wrap on`:`Wrap off`;n&&(n.textContent=i),r&&r.setAttribute(`aria-label`,`${i}. ${t?`Disable line wrap`:`Enable line wrap`}`)}function Jt(){clearTimeout(this._backlinkRefreshTimer),this._backlinkRefreshTimer=setTimeout(()=>{m(this.currentFilePath)&&this.backlinksPanel.load(this.currentFilePath)},2e3)}function Yt(){this.elements.editorContainer&&(this.elements.editorContainer.classList.add(`is-loading-editor`),this.elements.editorContainer.innerHTML=`
|
|
27
|
+
`),path:n}}var Ve=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=F(e);return t?t.endsWith(`.md`)?t:`${t}.md`:null}async createAndOpenFile(e,t){try{await this.vaultApiClient.createFile({content:Ie(t||e),path:e}),await this.refreshExplorer(),this.navigation.navigateToFile(e)}catch(e){this.toastController.show(`Failed to create file: ${e.message}`)}}},He=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=T(`/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}))}},Ue=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)}},We=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()}},Ge=150;function Ke(e){return new Promise(t=>{setTimeout(t,e)})}var qe=class{constructor({attachEditorScroller:e,beginDocumentLoad:t,cleanupAfterSessionDestroy:n,createEditorSession:r,getDisplayName:i,getFileList:a,getLineWrappingEnabled:o,getLocalUser:s,getStoredUserName:c,getTheme:l,isBaseFile:u,isDrawioFile:d,isExcalidrawFile:f,isImageFile:p,isMermaidFile:m,isPlantUmlFile:h,isTabActive:g,loadBootstrapContent:_=null,loadEditorSessionClass:v,loadBacklinks:y,onBeforeFileOpen:b,onConnectionChange:x,onContentChange:ee,onCommentsChange:S,onFileAwarenessChange:te,onFileOpenError:C,onFileOpenReady:w,onImagePaste:ne,onSelectionChange:re,onSessionAssigned:T=null,onFileOpenMetric:ie=null,onRenderBasePreview:E,onRenderExcalidrawPreview:D,onRenderDrawioPreview:O,onRenderImagePreview:ae,onSyncWrapToggle:k,onUpdateActiveFile:A,onUpdateCurrentFile:oe,onUpdateLobbyCurrentFile:se,onUpdateVisibleChrome:ce,onViewModeReset:le,renderPresence:j,scrollContainerForSession:ue,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=ee,this.onCommentsChange=S,this.onFileAwarenessChange=te,this.onFileOpenError=C,this.onFileOpenReady=w,this.onImagePaste=ne,this.onSelectionChange=re,this.onSessionAssigned=T,this.onFileOpenMetric=ie,this.onRenderBasePreview=E,this.onRenderExcalidrawPreview=D,this.onSyncWrapToggle=k,this.onUpdateActiveFile=A,this.onUpdateCurrentFile=oe,this.onUpdateLobbyCurrentFile=se,this.onUpdateVisibleChrome=ce,this.renderPresence=j,this.shouldUseDrawioPreview=de??(()=>!0),this.stateStore=pe,this.session=null,this.lifecycle=new Ue({attachEditorScroller:e,createEditorSession:r,loadEditorSessionClass:()=>this.loadEditorSessionClassPort(),scrollContainerForSession:ue}),this.chromeController=new We({beginDocumentLoad:t,getDisplayName:i,loadBacklinks:y,onBeforeFileOpen:b,onRenderDrawioPreview:O,onFileOpenError:C,onFileOpenReady:w,onRenderBasePreview:E,onRenderExcalidrawPreview:D,onRenderImagePreview:ae,onSyncWrapToggle:k,onUpdateActiveFile:A,onUpdateCurrentFile:oe,onUpdateLobbyCurrentFile:se,onUpdateVisibleChrome:ce,onViewModeReset:le,renderPresence:j,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,Ge-a);return o>0&&await Promise.race([l.then(e=>e?`live-sync`:`stale`),Ke(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()}}},Je=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,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 Ye(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`),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 L={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)}},Xe={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()}},Ze=`collabmd-export-page`,Qe=`collabmd-export-host`,$e=500,et=6e4,tt=new Map,nt=null;function rt(){return`export-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function it(e){return e===`pdf`?`pdf`:`docx`}function at({filePath:e,format:t,jobId:n}){let r=new URL(w(`/export-document.html`),window.location.origin);return r.searchParams.set(`action`,it(t)),r.searchParams.set(`job`,n),e&&r.searchParams.set(`file`,e),r.toString()}function ot({fileList:e=[],filePath:t,format:n,jobId:r,markdownText:i=``,title:a=``}){return{action:it(n),fileList:Array.isArray(e)?e.slice():[],filePath:String(t??``),jobId:r,markdownText:String(i??``),source:Qe,title:String(a??``),type:`bootstrap`}}function st(e){e&&(e.closePollId&&window.clearInterval(e.closePollId),e.timeoutId&&window.clearTimeout(e.timeoutId))}function ct(e,{notifyError:t=!1,message:n=``}={}){let r=tt.get(e);r&&(st(r),tt.delete(e),t&&n&&nt?.(n))}function lt({onError:e=null}={}){nt=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!==Ze)return;let n=String(t.jobId??``).trim();if(!n)return;let r=tt.get(n);if(r){if(t.type===`ready`){if(r.window?.closed){ct(n,{message:`Export window was closed before the export completed`,notifyError:!0});return}try{r.window?.postMessage(r.payload,window.location.origin)}catch(e){ct(n,{message:e instanceof Error?e.message:`Failed to send export data`,notifyError:!0})}return}(t.type===`complete`||t.type===`error`)&&ct(n,{message:t.type===`error`&&t.message?String(t.message):``,notifyError:t.type===`error`&&!!t.message})}}),window.__collabmdExportBridgeInitialized=!0)}async function ut({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=rt(),s=at({filePath:a,format:n,jobId:o}),c=window.open(s,`_blank`);if(!c)throw Error(`Export popup was blocked`);return tt.set(o,{closePollId:window.setInterval(()=>{c.closed&&ct(o,{message:`Export window was closed before the export completed`,notifyError:!0})},$e),payload:ot({fileList:e,filePath:a,format:n,jobId:o,markdownText:r,title:i}),timeoutId:window.setTimeout(()=>{ct(o,{message:`Export timed out before it completed`,notifyError:!0})},et),window:c}),c.focus?.(),o}var dt={initializeExportBridge(){this._exportBridgeInitialized||=(lt({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 ut({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 ft(e=[]){return Array.from(new Set((e??[]).filter(Boolean)))}function pt(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 mt(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 ht({changedPaths:e=[],deletedPaths:t=[],refreshExplorer:n=!0,renamedPaths:r=[]}={}){return{changedPaths:ft(e),deletedPaths:ft(t),refreshExplorer:n!==!1,renamedPaths:pt(r)}}function gt(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:mt(e.highlightRanges),id:e.id,origin:typeof e.origin==`string`?e.origin:`api`,reloadRequiredPaths:ft(e.reloadRequiredPaths),requestId:typeof e.requestId==`string`?e.requestId:null,sourceRef:typeof e.sourceRef==`string`?e.sourceRef:null,workspaceChange:ht(e.workspaceChange)}}function _t(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`workspace-${Date.now()}-${Math.random().toString(16).slice(2,10)}`}function vt(e={}){return ht(e)}var R={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=_t();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=vt(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=vt(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)}}}},z={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=!!this.session,n=!!(this.currentFilePath&&this.isDrawioFile?.(this.currentFilePath)),r=!!(this.currentFilePath&&this.isExcalidrawFile?.(this.currentFilePath)),i=!!(this.currentFilePath&&this.isImageFile?.(this.currentFilePath)),a=!t&&(!this.currentFilePath||n||r||i)?this.lobby?.getConnectionState?.()??this.connectionState:this.connectionState;if(a.status===`connected`){e.textContent=`${this.globalUsers.length} online`,e.style.opacity=`1`;return}if(a.status===`connecting`){e.textContent=a.unreachable?`Unreachable`:`Connecting...`,e.style.opacity=`0.6`;return}e.textContent=`Offline`,e.style.opacity=`0.6`},renderAvatars(){let e=this.elements.userAvatars;if(!e)return;e.innerHTML=``;let t=[...this.globalUsers],n=t.findIndex(e=>e.isLocal);if(n>0){let[e]=t.splice(n,1);t.unshift(e)}let r=t.findIndex(e=>!e.isLocal&&e.clientId===this.followedUserClientId),i=t[0]?.isLocal?1:0;if(r>i){let[e]=t.splice(r,1);t.splice(i,0,e)}if(t.slice(0,5).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>5){let n=document.createElement(`div`);n.className=`user-avatar`,n.style.backgroundColor=`var(--color-surface-dynamic)`,n.style.color=`var(--color-text-muted)`;let r=document.createElement(`span`);r.className=`user-avatar-initial`,r.textContent=`+${t.length-5}`,n.appendChild(r),e.appendChild(n)}},toggleFollowUser(e){if(!e)return;if(this.followedUserClientId===e){this.stopFollowingUser();return}let t=this.globalUsers.find(t=>t.clientId===e&&!t.isLocal);if(t){if(this.followedUserClientId=e,this.followedCursorSignature=``,this.renderAvatars(),t.currentFile&&t.currentFile!==this.currentFilePath){this.navigation.navigateToFile(t.currentFile);return}requestAnimationFrame(()=>{this.followedUserClientId===e&&this.followUserCursor(t,{force:!0})})}},stopFollowingUser(){this.followedUserClientId&&(this.currentFilePath&&this.isExcalidrawFile?.(this.currentFilePath)&&this.excalidrawEmbed?.setFollowedUser(this.currentFilePath,null),this.followedUserClientId=null,this.followedCursorSignature=``,this.renderAvatars())},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 yt(){return this.runtimeConfig?.auth?.strategy===`oidc`&&this.runtimeConfig?.auth?.provider===`google`}function bt({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 xt(){!this.isTabActive||this._hasPromptedForDisplayName||this.getStoredUserName()||this.isIdentityManagedByAuth()||(this._hasPromptedForDisplayName=!0,requestAnimationFrame(()=>{this.openDisplayNameDialog({mode:`onboarding`})}))}function St(){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):Se(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 Ct(){return this.globalUsers.find(e=>e.isLocal)??this.session?.getLocalUser()??this.lobby?.getLocalUser()??null}function wt(){return this.getCurrentUser()?.name??this.getStoredUserName()??``}function Tt(){return this.preferences.getUserName()}function Et(){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 Dt(){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 Ot={getCurrentUser:Ct,getCurrentUserName:wt,getStoredUserName:Tt,handleDisplayNameSubmit:St,isIdentityManagedByAuth:yt,openDisplayNameDialog:bt,promptForDisplayNameIfNeeded:xt,syncCurrentUserName:Et,syncIdentityManagementUi:Dt},kt=0;function At(){this.initializeExportBridge?.(),this.renderMarkdownToolbar?.(),this.initializeVisualViewportBinding?.(),this.themeController.initialize(),this.previewRenderer.applyTheme(this.themeController.getTheme()),this.previewRenderer.scheduleWorkerPrewarm(),this.scheduleEditorSessionPrewarm?.(),this.outlineController.initialize(),this.layoutController.initialize(),this.scrollSyncController.initialize(),this.fileExplorer.initialize(),this.gitPanel.initialize(),this.gitDiffView.initialize(),this.fileHistoryView.initialize(),this.initializePreviewLayoutObserver(),this.syncIdentityManagementUi(),this.syncCurrentUserName(),this.syncWrapToggle(),this.syncToolbarOverflowVisibility?.(),this.syncChatNotificationButton(),this.syncFileHistoryButton({mode:`empty`}),this.renderChat(),this.gitPanel.refresh({force:!0}),this.elements.chatInput?.setAttribute(`maxlength`,String(this.lobbyChatMessageMaxLength)),this.bindEvents(),this.restoreSidebarState(),this.initializeVersionMonitoring(),this.tabActivityLock.initialize(),this.tabActivityLock.tryActivate(),window.addEventListener(`hashchange`,()=>this.handleHashChange());let e=this.createResizeHandler();window.addEventListener(`resize`,()=>{e(),this.syncToolbarOverflowVisibility?.()}),this.fileExplorerReadyPromise=this.fileExplorer.refresh().then(()=>{if(this.fileExplorerReady=!0,this.isTabActive)return this.handleHashChange()})}function jt(){this.versionMonitor?.start()}function Mt(){let e=document.documentElement,t=window.visualViewport;if(e){if(!t){e.style.setProperty(`--app-viewport-height`,`100dvh`),e.style.setProperty(`--app-viewport-offset-top`,`0px`);return}e.style.setProperty(`--app-viewport-height`,`${Math.round(t.height)}px`),e.style.setProperty(`--app-viewport-offset-top`,`${Math.round(t.offsetTop)}px`)}}function Nt(){this.syncVisualViewportBounds?.();let e=window.visualViewport;if(!e)return;let t=()=>this.syncVisualViewportBounds?.();e.addEventListener(`resize`,t,{passive:!0}),e.addEventListener(`scroll`,t,{passive:!0}),window.addEventListener(`orientationchange`,t)}function Pt(e=null){if(this._reloadPromptShown)return;this._reloadPromptShown=!0;let t=String(e?.build?.packageVersion??this.runtimeConfig?.build?.packageVersion??``).trim(),n=t?`Version ${t} is available. Reload to update.`:`A new version is available. Reload to update.`;this.toastController.show(n,{actionLabel:`Reload`,dismissible:!0,duration:kt,onAction:()=>window.location.reload()})}function Ft(){this.elements.shareButton?.addEventListener(`click`,()=>{this.copyCurrentLink(),this.closeToolbarOverflowMenu?.()}),this.elements.searchFilesButton?.addEventListener(`click`,()=>{this.toggleQuickSwitcher(),this.closeToolbarOverflowMenu?.()}),this.elements.exportDocxButton?.addEventListener(`click`,()=>{this.handleExportRequest?.(`docx`),this.closeToolbarOverflowMenu?.()}),this.elements.exportPdfButton?.addEventListener(`click`,()=>{this.handleExportRequest?.(`pdf`),this.closeToolbarOverflowMenu?.()}),this.elements.fileHistoryButton?.addEventListener(`click`,()=>{let e=this.navigation.getHashRoute();if(e.type===`git-file-preview`){this.handleGitFileHistorySelection(e.currentFilePath??e.filePath,{closeSidebarOnMobile:!0}),this.closeToolbarOverflowMenu?.();return}this.handleGitFileHistorySelection(this.currentFilePath,{closeSidebarOnMobile:!0}),this.closeToolbarOverflowMenu?.()}),this.elements.editNameButton?.addEventListener(`click`,()=>{this.openDisplayNameDialog(),this.closeToolbarOverflowMenu?.()})}function It(){this.elements.displayNameCancel?.addEventListener(`click`,()=>{this.elements.displayNameDialog?.close()}),this.elements.gitCommitCancel?.addEventListener(`click`,()=>{this.elements.gitCommitDialog?.close()}),this.elements.gitResetCancel?.addEventListener(`click`,()=>{this.elements.gitResetDialog?.close()}),this.elements.gitResetSubmit?.addEventListener(`click`,()=>{this.handleGitResetSubmit()}),this.elements.gitCommitDialog?.addEventListener(`close`,()=>{this.elements.gitCommitInput&&(this.elements.gitCommitInput.value=``),this.elements.gitCommitSubmit&&(this.elements.gitCommitSubmit.textContent=`Commit staged changes`)}),this.elements.gitResetDialog?.addEventListener(`close`,()=>{this.pendingGitResetPath=null,this.elements.gitResetFileName&&(this.elements.gitResetFileName.value=``),this.elements.gitResetSubmit&&(this.elements.gitResetSubmit.textContent=`Reset File`)}),this.elements.displayNameForm?.addEventListener(`submit`,e=>{e.preventDefault(),this.handleDisplayNameSubmit()}),this.elements.gitCommitForm?.addEventListener(`submit`,e=>{e.preventDefault(),this.handleGitCommitSubmit()})}function Lt(){this.elements.emptyStateNewFileBtn?.addEventListener(`click`,()=>{this.fileExplorer.actionController.openRootCreateMenu({anchor:this.elements.emptyStateNewFileBtn})}),this.elements.emptyStateSearchBtn?.addEventListener(`click`,()=>{this.toggleQuickSwitcher()}),this.elements.chatToggleButton?.addEventListener(`click`,()=>{this.toggleChatPanel(),this.closeToolbarOverflowMenu?.()}),this.elements.chatForm?.addEventListener(`submit`,e=>{e.preventDefault(),this.handleChatSubmit()}),this.elements.chatNotificationButton?.addEventListener(`click`,()=>{this.handleChatNotificationToggle()}),Ft.call(this),It.call(this),this.elements.markdownToolbar?.addEventListener(`click`,e=>{this.handleMarkdownToolbarClick?.(e)}),this.elements.markdownToolbar?.addEventListener(`keydown`,e=>{this.handleMarkdownToolbarKeydown?.(e)}),this.elements.tabLockTakeoverButton?.addEventListener(`click`,()=>{this.handleTabTakeover()}),this.elements.toggleWrapButton?.addEventListener(`click`,()=>{this.toggleLineWrapping()}),this.elements.editorFindButton?.addEventListener(`click`,()=>{this.runEditorCommand?.(`openSearch`)}),this.elements.toolbarOverflowToggle?.addEventListener(`click`,e=>{e.preventDefault(),this.toggleToolbarOverflowMenu()}),this.elements.toolbarOverflowMenu?.addEventListener(`click`,e=>{e.target instanceof Element&&e.target.closest(`button`)&&this.closeToolbarOverflowMenu()}),this.elements.previewContent?.addEventListener(`click`,e=>{this.handlePreviewContentClick?.(e)}),this.elements.sidebarToggle?.addEventListener(`click`,()=>{this.closeToolbarOverflowMenu(),this.toggleSidebar()}),this.elements.sidebarClose?.addEventListener(`click`,()=>{this.closeSidebarOnMobile()}),this.elements.filesSidebarTab?.addEventListener(`click`,()=>{this.setSidebarTab(`files`)}),this.elements.gitSidebarTab?.addEventListener(`click`,()=>{this.gitRepoAvailable&&this.setSidebarTab(`git`)}),document.addEventListener(`pointerdown`,e=>{this.handleDocumentPointerDown(e)}),document.addEventListener(`keydown`,e=>{this.handleDocumentKeydown(e)})}function Rt(e){this.handleMarkdownToolbarDocumentPointerDown?.(e),this.toolbarOverflowOpen&&!this.elements.toolbarOverflowMenu?.contains(e.target)&&!this.elements.toolbarOverflowToggle?.contains(e.target)&&this.closeToolbarOverflowMenu(),this.chatIsOpen&&(this.elements.chatContainer?.contains(e.target)||this.closeChatPanel())}function zt(e){if(e.key===`Escape`&&this.toolbarOverflowOpen){this.closeToolbarOverflowMenu();return}if(e.key===`Escape`&&this.chatIsOpen){this.closeChatPanel();return}(e.metaKey||e.ctrlKey)&&e.key===`k`&&(e.preventDefault(),this.toggleQuickSwitcher())}function Bt(e,t){let n=e.closest(`ul, ol`);return n instanceof Element&&n.parentElement===t}function Vt(e){return e.closest(`input[data-task-checkbox="true"]`)?!1:!!e.closest(`a, button, input, select, textarea, summary, [contenteditable="true"], [role="button"], [role="link"]`)}function Ht(e){if(!(e.target instanceof Element))return;let t=e.target.closest(`a.wiki-link[data-wiki-target]`);if(t){e.preventDefault(),this.handleWikiLinkClick(t.dataset.wikiTarget);return}let n=e.target.closest(`.task-list-item[data-source-line]`);if(!n||Bt(e.target,n)||Vt(e.target))return;e.preventDefault();let r=Number.parseInt(n.getAttribute(`data-source-line`)||``,10);Number.isFinite(r)&&this.session?.toggleTaskListItem?.(r)}function Ut(e){this.toolbarOverflowOpen=!!e,this.elements.toolbarOverflowToggle?.setAttribute(`aria-expanded`,String(this.toolbarOverflowOpen)),this.elements.toolbarOverflowToggle?.classList.toggle(`active`,this.toolbarOverflowOpen),this.elements.toolbarOverflowToggle?.closest(`.toolbar-right`)?.classList.toggle(`is-overflow-open`,this.toolbarOverflowOpen),this.toolbarOverflowOpen||this.elements.toolbarOverflowMenu?.querySelectorAll(`details[open]`).forEach(e=>{e.removeAttribute(`open`)})}function Wt(){let e=this.elements.toolbarOverflowToggle;e&&(e.classList.remove(`hidden`),e.hidden=!1,e.setAttribute(`aria-hidden`,`false`))}function Gt(){this.setToolbarOverflowOpen(!1)}function Kt(){this.setToolbarOverflowOpen(!this.toolbarOverflowOpen)}function qt(e){this.previewRenderer.applyTheme(e),!this.isExcalidrawFile(this.currentFilePath)&&!this.isImageFile?.(this.currentFilePath)&&this.previewRenderer.queueRender(),this.session?.applyTheme(e),this.excalidrawEmbed.updateTheme(e),this.drawioEmbed.updateTheme(e)}function Jt(e){this.connectionState=e,e?.firstConnection&&this.recordFileOpenMetric?.(`ws_connected`,{status:e.status}),this.renderPresence(),e.unreachable&&!this.connectionHelpShown&&(this.connectionHelpShown=!0,this.toastController.show(`Cannot reach server at ${e.wsBaseUrl}`,6e3))}function Yt(){let e=!(this.session?.isLineWrappingEnabled()??this.getStoredLineWrapping());this.session?.setLineWrapping(e),this.preferences.setLineWrappingEnabled(e),this.syncWrapToggle(e),this.session?.requestMeasure(),this.scrollSyncController.syncPreviewToEditor()}function Xt(){return this.preferences.getLineWrappingEnabled()}function Zt(e){let t=e??this.session?.isLineWrappingEnabled()??this.getStoredLineWrapping(),n=this.elements.wrapToggleLabel,r=this.elements.toggleWrapButton,i=t?`Wrap on`:`Wrap off`;n&&(n.textContent=i),r&&r.setAttribute(`aria-label`,`${i}. ${t?`Disable line wrap`:`Enable line wrap`}`)}function Qt(){clearTimeout(this._backlinkRefreshTimer),this._backlinkRefreshTimer=setTimeout(()=>{m(this.currentFilePath)&&this.backlinksPanel.load(this.currentFilePath)},2e3)}function $t(){this.elements.editorContainer&&(this.elements.editorContainer.classList.add(`is-loading-editor`),this.elements.editorContainer.innerHTML=`
|
|
28
28
|
<div class="editor-loading" id="editorLoading">
|
|
29
29
|
<div class="loading-spinner"></div>
|
|
30
30
|
<span class="loading-text">Loading file...</span>
|
|
31
|
-
</div>`)}function
|
|
31
|
+
</div>`)}function en(){this.elements.editorContainer&&(this.elements.editorContainer.classList.remove(`is-loading-editor`),this.elements.editorContainer.querySelector(`#editorLoading`)?.remove())}function tn(){this.elements.editorContainer&&(this.elements.editorContainer.classList.remove(`is-loading-editor`),this.elements.editorContainer.innerHTML=`
|
|
32
32
|
<div class="editor-loading" id="editorLoading">
|
|
33
33
|
<span class="loading-text">Failed to load file</span>
|
|
34
|
-
</div>`)}function
|
|
34
|
+
</div>`)}function nn(){document.documentElement.removeAttribute(`data-initial-file-requested`)}var rn={bindEvents:Lt,clearInitialFileBootstrap:nn,closeToolbarOverflowMenu:Gt,getStoredLineWrapping:Xt,handleConnectionChange:Jt,handleDocumentKeydown:zt,handleDocumentPointerDown:Rt,handlePreviewContentClick:Ht,handleThemeChange:qt,hideEditorLoading:en,initialize:At,initializeVisualViewportBinding:Nt,initializeVersionMonitoring:jt,promptForVersionReload:Pt,scheduleBacklinkRefresh:Qt,setToolbarOverflowOpen:Ut,showEditorLoadError:tn,showEditorLoading:$t,syncVisualViewportBounds:Mt,syncToolbarOverflowVisibility:Wt,syncWrapToggle:Zt,toggleToolbarOverflowMenu:Kt,toggleLineWrapping:Yt};function an(){return this.mobileBreakpointQuery.matches}function on(){let e=this.elements.sidebar;!e||!this.isMobileViewport()||e.classList.contains(`collapsed`)||this.setSidebarVisibility(!1)}function sn(){let e=this.elements.sidebar;if(!e)return;let t=e.classList.contains(`collapsed`);this.setSidebarVisibility(t)}function cn(){if(!this.elements.sidebar)return;let e=this.isMobileViewport(),t=this.preferences.getSidebarVisible(),n=!0;t===`true`?n=!0:(t===`false`||e)&&(n=!1),this.applySidebarVisibility(n)}function ln(e){this.applySidebarVisibility(e),this.preferences.setSidebarVisible(e)}function un(e){let t=this.elements.sidebar;if(!t)return;let n=!e,r=n&&this.isMobileViewport();t.classList.toggle(`collapsed`,n),t.toggleAttribute(`hidden`,r),t.setAttribute(`aria-hidden`,r?`true`:`false`),t.inert=n}function dn(e){let t=e===`git`&&this.gitRepoAvailable?`git`:`files`;this.activeSidebarTab=t,this.elements.filesSidebarTab?.classList.toggle(`active`,t===`files`),this.elements.gitSidebarTab?.classList.toggle(`active`,t===`git`),document.getElementById(`fileTree`)?.classList.toggle(`hidden`,t!==`files`),this.elements.fileSearch?.classList.toggle(`hidden`,t!==`files`),this.elements.gitSearch?.classList.toggle(`hidden`,t!==`git`),document.getElementById(`gitPanel`)?.classList.toggle(`active`,t===`git`),document.getElementById(`gitPanel`)?.classList.toggle(`hidden`,t!==`git`),this.gitPanel.setActive(t===`git`)}var fn={applySidebarVisibility:un,closeSidebarOnMobile:on,isMobileViewport:an,restoreSidebarState:cn,setSidebarTab:dn,setSidebarVisibility:ln,toggleSidebar:sn};function pn(){this.tabActivityLock.tryActivate({takeover:!0})}function mn({takeover:e=!1}={}){let t=!this.isTabActive;this.isTabActive=!0,this.hideTabLockOverlay(),this.lobby.provider||this.lobby.connect(),this.workspaceSync.provider||this.workspaceSync.connect(),t&&(this.fileExplorerReady&&this.handleHashChange(),this.promptForDisplayNameIfNeeded()),e&&this.toastController.show(`This tab is now active`)}async function hn({reason:e}={}){let t=this.isTabActive,n=this.currentFilePath,r=!!(n&&this.isExcalidrawFile?.(n));this.isTabActive=!1,this.elements.displayNameDialog?.open&&this.elements.displayNameDialog.close(),this.lobby.disconnect(),this.workspaceSync.disconnect(),this.globalUsers=[],this.chatMessages=[],this.chatMessageIds.clear(),this.chatUnreadCount=0,this.chatInitialSyncComplete=!1,this.followedUserClientId=null,this.followedCursorSignature=``,this.connectionState={status:`disconnected`,unreachable:!1},this.showTabLockOverlay({reason:e}),r&&await this.excalidrawEmbed.prepareFileDisconnect(n),this.showEmptyState(),this.renderChat(),t&&e===`taken-over`&&this.toastController.show(`Another tab took over this session`)}function gn({reason:e}={}){let t=this.elements.tabLockOverlay,n=this.elements.tabLockTitle,r=this.elements.tabLockCopy;t&&(n&&(n.textContent=e===`taken-over`?`This tab is no longer active`:`This vault is active in another tab`),r&&(r.textContent=e===`taken-over`?`Another tab took over the live session. This tab is now disconnected until you explicitly take over here again.`:`To avoid duplicate presence and chat, only one tab can stay connected at a time. Use the other tab, or take over the session here.`),t.classList.remove(`hidden`))}function _n(){this.elements.tabLockOverlay?.classList.add(`hidden`)}var vn={handleTabActivated:mn,handleTabBlocked:hn,handleTabTakeover:pn,hideTabLockOverlay:_n,showTabLockOverlay:gn},B=Object.freeze({bold:`
|
|
35
35
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
36
36
|
<path d="M7 5h6a4 4 0 0 1 0 8H7z"/>
|
|
37
37
|
<path d="M7 13h7a4 4 0 0 1 0 8H7z"/>
|
|
@@ -110,7 +110,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
110
110
|
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
111
111
|
<path d="m6 9 6 6 6-6"/>
|
|
112
112
|
</svg>
|
|
113
|
-
`}),
|
|
113
|
+
`}),yn=Object.freeze([{action:`paragraph`,label:`Paragraph`,shortLabel:`P`,title:`Paragraph`},{action:`heading-1`,label:`Heading 1`,shortLabel:`H1`,title:`Heading 1`},{action:`heading-2`,label:`Heading 2`,shortLabel:`H2`,title:`Heading 2`},{action:`heading-3`,label:`Heading 3`,shortLabel:`H3`,title:`Heading 3`},{action:`heading-4`,label:`Heading 4`,shortLabel:`H4`,title:`Heading 4`},{action:`heading-5`,label:`Heading 5`,shortLabel:`H5`,title:`Heading 5`},{action:`heading-6`,label:`Heading 6`,shortLabel:`H6`,title:`Heading 6`},{action:`quote`,label:`Quote`,shortLabel:`Quote`,title:`Block quote`},{action:`bullet-list`,label:`Bullet list`,shortLabel:`List`,title:`Bullet list`},{action:`numbered-list`,label:`Numbered list`,shortLabel:`1.`,title:`Numbered list`},{action:`task-list`,label:`Task list`,shortLabel:`Task`,title:`Task list`},{action:`code-block`,label:`Code block`,shortLabel:`Code`,title:`Code block`}]),bn=Object.freeze([{action:`bold`,label:`Bold`,title:`Bold`,icon:B.bold},{action:`italic`,label:`Italic`,title:`Italic`,icon:B.italic},{action:`strikethrough`,label:`Strikethrough`,title:`Strikethrough`,icon:B.strikethrough},{action:`code`,label:`Inline code`,title:`Inline code`,icon:B.code}]),xn=Object.freeze([{commandId:`undo`,label:`Undo`,title:`Undo`,icon:B.undo},{commandId:`redo`,label:`Redo`,title:`Redo`,icon:B.redo},{commandId:`indentMore`,label:`Indent`,title:`Indent`,icon:B.indent},{commandId:`indentLess`,label:`Outdent`,title:`Outdent`,icon:B.outdent}]),Sn=Object.freeze([{action:`link`,label:`Insert link`,title:`Insert link`,icon:B.link},{action:`image`,label:`Insert image`,title:`Insert image`,icon:B.image},{action:`video`,label:`Insert video`,title:`Insert video`,icon:B.video}]),Cn=Object.freeze([{action:`table`,label:`Insert table`,title:`Insert table`,icon:B.table},{action:`horizontal-rule`,label:`Insert horizontal rule`,title:`Insert horizontal rule`,icon:B.horizontalRule}]),wn=Object.freeze([{kind:`buttons`,groupLabel:`Edit`,actions:xn,mobileOnly:!0},{kind:`block-menu`,actions:yn},{kind:`buttons`,groupLabel:`Inline formatting`,actions:bn},{kind:`buttons`,groupLabel:`Media and links`,actions:Sn},{kind:`buttons`,groupLabel:`Insert`,actions:Cn}]),Tn=[...yn,...bn,...Sn,...Cn],En=new Map(Tn.map(e=>[e.action,e]));function Dn(e){return En.get(e)??null}function On(){return yn}function kn(e){return yn.some(t=>t.action===e)}function An(e){return Dn(e)?.shortLabel??`P`}function jn(){return B}var Mn=`image/png,image/jpeg,image/webp,image/gif,image/svg+xml`,Nn=`paragraph`;function V(e){return String(e??``).replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`)}function Pn(e){return e===`heading`?`heading-2`:String(e??``).trim()}function Fn(e){return e.map(e=>`<button type="button" class="ui-icon-button ui-icon-button--toolbar ui-toolbar-action" ${e.commandId?`data-editor-command="${V(e.commandId)}"`:`data-markdown-action="${V(e.action)}"`} aria-label="${V(e.label)}" title="${V(e.title)}">${e.icon}</button>`).join(``)}function In(e){return`
|
|
114
114
|
<div class="markdown-toolbar-block-menu-shell">
|
|
115
115
|
<button
|
|
116
116
|
type="button"
|
|
@@ -120,11 +120,11 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
120
120
|
aria-expanded="false"
|
|
121
121
|
title="Block formatting"
|
|
122
122
|
>
|
|
123
|
-
<span class="markdown-toolbar-block-trigger-label" data-markdown-block-trigger-label>${V(
|
|
124
|
-
<span class="markdown-toolbar-block-trigger-icon" aria-hidden="true">${
|
|
123
|
+
<span class="markdown-toolbar-block-trigger-label" data-markdown-block-trigger-label>${V(An(e))}</span>
|
|
124
|
+
<span class="markdown-toolbar-block-trigger-icon" aria-hidden="true">${jn().chevronDown}</span>
|
|
125
125
|
</button>
|
|
126
126
|
</div>
|
|
127
|
-
`}function
|
|
127
|
+
`}function Ln(e){return On().map(t=>{let n=t.action===e;return`
|
|
128
128
|
<button
|
|
129
129
|
type="button"
|
|
130
130
|
class="markdown-toolbar-menu-item${n?` is-active`:``}"
|
|
@@ -136,24 +136,24 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
136
136
|
<span class="markdown-toolbar-menu-item-label">${V(t.label)}</span>
|
|
137
137
|
<span class="markdown-toolbar-menu-item-shortcut">${V(t.shortLabel)}</span>
|
|
138
138
|
</button>
|
|
139
|
-
`}).join(``)}function
|
|
139
|
+
`}).join(``)}function Rn(e){return wn.map(t=>t.kind===`block-menu`?In(e):`
|
|
140
140
|
<div class="markdown-toolbar-group${t.mobileOnly?` markdown-toolbar-group--mobile-only`:``}" role="group" aria-label="${V(t.groupLabel)}">
|
|
141
|
-
${
|
|
141
|
+
${Fn(t.actions)}
|
|
142
142
|
</div>
|
|
143
|
-
`).join(``)}function Fn(){let e=An(this._activeMarkdownBlockAction||kn);return Tn(e)?e:kn}function In(){let e=this.elements?.markdownToolbar;e&&(e.innerHTML=Pn(this.getActiveMarkdownBlockAction()),this.renderMarkdownBlockMenuPopover(),this.syncMarkdownToolbarBlockUi())}function Ln(){return this._markdownBlockMenuPopover??null}function Rn(){let e=this.elements?.editorContainer??document.body,t=this.getMarkdownBlockMenuPopover();t?t.parentElement!==e&&e?.appendChild(t):(t=document.createElement(`div`),t.className=`markdown-toolbar-popover hidden`,t.innerHTML=`<div class="markdown-toolbar-menu" data-markdown-block-menu role="menu" aria-label="Block formatting"></div>`,t.addEventListener(`click`,e=>{this.handleMarkdownToolbarClick?.(e)}),t.addEventListener(`keydown`,e=>{this.handleMarkdownToolbarKeydown?.(e)}),e?.appendChild(t),this._markdownBlockMenuPopover=t);let n=t.querySelector(`[data-markdown-block-menu]`);n&&(n.innerHTML=Nn(this.getActiveMarkdownBlockAction()))}function zn(){let e=this.elements?.markdownToolbar;if(!e)return;let t=this.getActiveMarkdownBlockAction(),n=Cn(t),r=e.querySelector(`[data-markdown-block-trigger-label]`);r&&(r.textContent=En(t));let i=e.querySelector(`[data-markdown-block-menu-toggle]`);i&&n&&(i.setAttribute(`aria-label`,`${n.label}. Block formatting`),i.setAttribute(`title`,`${n.label}. Block formatting`));let a=Array.from(this.getMarkdownBlockMenuPopover()?.querySelectorAll(`[data-markdown-block-action]`)??[]);[...e.querySelectorAll(`[data-markdown-block-action]`),...a].forEach(e=>{let n=e.getAttribute(`data-markdown-block-action`)===t;e.classList.toggle(`is-active`,n),e.setAttribute(`aria-checked`,n?`true`:`false`)})}function Bn(e){let t=An(e);Tn(t)&&(this._activeMarkdownBlockAction=t,this.syncMarkdownToolbarBlockUi())}function Vn(){return!!this.elements?.markdownToolbar?.classList.contains(`is-menu-open`)}function Hn(){let e=this.getMarkdownBlockMenuPopover(),t=this.elements?.markdownToolbar?.querySelector(`[data-markdown-block-menu-toggle]`),n=e?.parentElement;if(!e||!t||!(n instanceof HTMLElement))return;let r=t.getBoundingClientRect(),i=n.getBoundingClientRect(),a=e.getBoundingClientRect(),o=a.width||176,s=a.height||240,c=r.left-i.left,l=Math.max(8,i.width-o-8),u=r.bottom-i.top+6,d=u+s<=i.height-8;e.style.left=`${Math.max(8,Math.min(c,l))}px`,e.style.top=`${d?u:Math.max(8,r.top-i.top-s-6)}px`}function Un(){let e=this.elements?.markdownToolbar;e&&(this.renderMarkdownBlockMenuPopover(),e.classList.add(`is-menu-open`),this.getMarkdownBlockMenuPopover()?.classList.remove(`hidden`),e.querySelector(`[data-markdown-block-menu-toggle]`)?.setAttribute(`aria-expanded`,`true`),this.positionMarkdownBlockMenu())}function Wn(){let e=this.elements?.markdownToolbar;e&&(e.classList.remove(`is-menu-open`),this.getMarkdownBlockMenuPopover()?.classList.add(`hidden`),e.querySelector(`[data-markdown-block-menu-toggle]`)?.setAttribute(`aria-expanded`,`false`))}function Gn(){if(this.isMarkdownBlockMenuOpen()){this.closeMarkdownBlockMenu();return}this.openMarkdownBlockMenu()}function Kn(e){let t=e.target instanceof Element?e.target:null;if(!t)return;let n=t.closest(`[data-editor-command]`)?.getAttribute(`data-editor-command`);if(n){e.preventDefault(),this.runEditorCommand(n);return}if(t.closest(`[data-markdown-block-menu-toggle]`)){e.preventDefault(),this.toggleMarkdownBlockMenu();return}let r=t.closest(`[data-markdown-block-action]`);if(r){e.preventDefault();let t=r.getAttribute(`data-markdown-block-action`);this.closeMarkdownBlockMenu(),t&&this.applyMarkdownToolbarAction(t);return}let i=t.closest(`[data-markdown-action]`)?.getAttribute(`data-markdown-action`);i&&this.applyMarkdownToolbarAction(i)}function qn(e){if(!this.isMarkdownBlockMenuOpen()){e.target instanceof Element&&e.target.closest(`[data-markdown-block-menu-toggle]`)&&[`ArrowDown`,`Enter`,` `].includes(e.key)&&(e.preventDefault(),this.openMarkdownBlockMenu(),this.getMarkdownBlockMenuPopover()?.querySelector(`[data-markdown-block-action]`)?.focus());return}if(e.key===`Escape`){e.preventDefault(),this.closeMarkdownBlockMenu(),this.elements?.markdownToolbar?.querySelector(`[data-markdown-block-menu-toggle]`)?.focus();return}let t=Array.from(this.getMarkdownBlockMenuPopover()?.querySelectorAll(`[data-markdown-block-action]`)??[]);if(t.length===0)return;let n=t.findIndex(t=>t===e.target);n<0||(e.key===`ArrowDown`?(e.preventDefault(),t[(n+1)%t.length]?.focus()):e.key===`ArrowUp`&&(e.preventDefault(),t[(n-1+t.length)%t.length]?.focus()))}function Jn(e){this.isMarkdownBlockMenuOpen()&&(this.elements?.markdownToolbar?.contains(e.target)||this.getMarkdownBlockMenuPopover()?.contains(e.target)||this.closeMarkdownBlockMenu())}function Yn(e){if(!this.session||!u(this.currentFilePath))return;if(e===`image`){this.handleToolbarImageInsert();return}let t=An(e);if(!this.session.applyMarkdownToolbarAction(t)){this.toastController.show(`Formatting action is unavailable`);return}Tn(t)&&this.setActiveMarkdownBlockAction(t)}function Xn(e){return this.session?.runEditorCommand?.(e)?!0:(this.toastController.show(`Editor action is unavailable`),!1)}async function Zn(){let e=await this.pickImageFile();e&&await this.handleEditorImageInsert(e)}function Qn(){return new Promise(e=>{let t=document.createElement(`input`);t.type=`file`,t.accept=On,t.style.position=`fixed`,t.style.left=`-9999px`,document.body.appendChild(t);let n=!1,r=null,i=i=>{n||(n=!0,r&&window.clearTimeout(r),window.removeEventListener(`focus`,a),t.remove(),e(i))},a=()=>{r=window.setTimeout(()=>{n||t.files?.length||i(null)},250)};t.addEventListener(`change`,()=>{i(t.files?.[0]??null)},{once:!0}),t.addEventListener(`cancel`,()=>{i(null)},{once:!0}),window.addEventListener(`focus`,a,{once:!0}),t.click()})}async function $n(e){if(!this.session||!u(this.currentFilePath))return console.warn(`[ui] Ignoring image insert because there is no active markdown session.`,{currentFilePath:this.currentFilePath,hasSession:!!this.session}),!1;let t=this.currentFilePath,n=this.session;try{console.debug(`[ui] Uploading image attachment.`,{fileName:e?.name||``,size:e?.size??null,sourcePath:t,type:e?.type||``});let r=await this.vaultApiClient.uploadImageAttachment({file:e,fileName:e?.name||``,sourcePath:t});return await this.fileExplorer.refresh(),this.currentFilePath===t&&this.session&&this.session===n&&typeof r?.markdown==`string`&&(console.debug(`[ui] Inserting uploaded image markdown into the editor.`,{sourcePath:t,storedPath:r.path??``}),this.session.insertText(r.markdown)),!0}catch(e){return console.error(`[ui] Failed to insert image attachment:`,e),this.toastController.show(e.message||`Failed to upload image`),!1}}async function er(){try{await navigator.clipboard.writeText(window.location.href),this.toastController.show(`Link copied`)}catch{this.toastController.show(`Failed to copy link`)}}var tr={applyMarkdownToolbarAction:Yn,copyCurrentLink:er,closeMarkdownBlockMenu:Wn,getActiveMarkdownBlockAction:Fn,getMarkdownBlockMenuPopover:Ln,handleEditorImageInsert:$n,handleMarkdownToolbarClick:Kn,handleMarkdownToolbarDocumentPointerDown:Jn,handleMarkdownToolbarKeydown:qn,handleToolbarImageInsert:Zn,isMarkdownBlockMenuOpen:Vn,openMarkdownBlockMenu:Un,positionMarkdownBlockMenu:Hn,renderMarkdownBlockMenuPopover:Rn,pickImageFile:Qn,renderMarkdownToolbar:In,runEditorCommand:Xn,setActiveMarkdownBlockAction:Bn,syncMarkdownToolbarBlockUi:zn,toggleMarkdownBlockMenu:Gn},H={...$t,...cn,...Ot,...tr,...mn},U={isExcalidrawFile(e){return g(e)},isBaseFile(e){return l(e)},isDrawioFile(e){return p(e)},isImageFile(e){return o(e)},isMermaidFile(e){return v(e)},isPlantUmlFile(e){return s(e)},createDiagramPreviewDocument(e,t=``){return this.workspacePreviewController.createDiagramPreviewDocument(e,t)},getPreviewSource(){let e=this.getStaticPreviewDocument?.(),t=e?.currentFilePath??e?.filePath??null;return e&&t&&t===this.currentFilePath?this.isMermaidFile(this.currentFilePath)?this.createDiagramPreviewDocument(`mermaid`,e.content):this.isPlantUmlFile(this.currentFilePath)?this.createDiagramPreviewDocument(`plantuml`,e.content):String(e.content??``):this.workspacePreviewController.getPreviewSource(this.currentFilePath,{drawioMode:this.currentDrawioMode??null})},getStaticPreviewDocument(){return this._staticPreviewDocument??null},setStaticPreviewDocument(e){let t=e?.filePath??e?.path??null,n=e?.currentFilePath??t;this._staticPreviewDocument=e?{content:String(e.content??``),currentFilePath:n,fileKind:e.fileKind??f(t),filePath:t,hash:e.hash??null}:null},clearStaticPreviewDocument(){this._staticPreviewDocument=null},supportsFileHistory(e){let t=f(e);return t!==null&&t!==`image`},getDisplayName(e){return c(String(e??``).split(`/`).pop())},resetPreviewMode(){this.workspacePreviewController.resetPreviewMode()},syncFileChrome(e,t={}){this.workspacePreviewController.syncFileChrome(e,t)},handleLayoutViewRequest(e){return!this.currentFilePath||!this.isDrawioFile(this.currentFilePath)?!0:this.currentDrawioMode===`text`?e===`preview`?(this.layoutController.isMobileViewport?.()&&this.layoutController.primeView(e),this.navigation.navigateToFile(this.currentFilePath),!1):!0:e===`preview`?!0:(this.layoutController.primeView(e),this.navigation.navigateToFile(this.currentFilePath,{drawioMode:`text`}),!1)},renderExcalidrawFilePreview(e){this.workspacePreviewController.renderExcalidrawFilePreview(e)},renderDrawioFilePreview(e){this.workspacePreviewController.renderDrawioFilePreview(e)},renderImageFilePreview(e){this.workspacePreviewController.renderImageFilePreview(e)},renderBaseFilePreview(e){return this.workspacePreviewController.renderBaseFilePreview(e)},renderTextFilePreview(e){this.workspacePreviewController.renderTextFilePreview(e)},createResizeHandler(){return this.workspacePreviewController.createResizeHandler(()=>this.restoreSidebarState())},initializePreviewLayoutObserver(){this._previewLayoutResizeObserver?.disconnect(),this._previewLayoutResizeObserver=this.workspacePreviewController.initializePreviewLayoutObserver(()=>this.schedulePreviewLayoutSync())},schedulePreviewLayoutSync({delayMs:e=120}={}){this.workspacePreviewController.schedulePreviewLayoutSync({delayMs:e,hydrationPaused:this._previewHydrationPaused,previewLayoutSyncTimer:this._previewLayoutSyncTimer,setPendingPreviewLayoutSync:e=>{this._pendingPreviewLayoutSync=e},setPreviewLayoutSyncTimer:e=>{this._previewLayoutSyncTimer=e}})},handleEditorScrollActivityChange(e){this.workspacePreviewController.handleEditorScrollActivityChange({isActive:e,pendingPreviewLayoutSync:this._pendingPreviewLayoutSync,previewLayoutSyncTimer:this._previewLayoutSyncTimer,setHydrationPaused:e=>{this._previewHydrationPaused=e},setPendingPreviewLayoutSync:e=>{this._pendingPreviewLayoutSync=e},setPreviewLayoutSyncTimer:e=>{this._previewLayoutSyncTimer=e}})},async handleHashChange(){await this.workspaceRouteController.handleHashChange()},showEmptyState(){clearTimeout(this._previewLayoutSyncTimer),this._previewLayoutSyncTimer=null,this._pendingPreviewLayoutSync=!1,this._previewHydrationPaused=!1,this.workspaceRouteController.showEmptyState()},showDiffState(){clearTimeout(this._previewLayoutSyncTimer),this._previewLayoutSyncTimer=null,this._pendingPreviewLayoutSync=!1,this._previewHydrationPaused=!1,this.workspaceRouteController.showDiffState()},async openFile(e){await this.workspaceRouteController.openFile(e)},cleanupSession(){this.workspaceRouteController.cleanupSession()},handleWikiLinkClick(e){this.wikiLinkFileController.handleWikiLinkClick(e)},normalizeNewWikiFilePath(e){return this.wikiLinkFileController.normalizeNewWikiFilePath(e)},async createAndOpenFile(e,t){await this.wikiLinkFileController.createAndOpenFile(e,t)},handleFileSelection(e,{closeSidebarOnMobile:t=!1}={}){this.workspaceRouteController.handleFileSelection(e,{closeSidebarOnMobile:t})}},nr=`__lobby__`;function rr(e){return String(e??``).replace(/\s+/g,` `).trim().slice(0,280)||null}function ir(e){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${e||`user`}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function ar(e){if(!e||typeof e!=`object`||typeof e.id!=`string`)return null;let t=e.workspaceChange&&typeof e.workspaceChange==`object`?e.workspaceChange:{};return{action:typeof e.action==`string`?e.action:`git`,createdAt:Number.isFinite(e.createdAt)?e.createdAt:Date.now(),id:e.id,peerId:typeof e.peerId==`string`?e.peerId:null,sourceRef:typeof e.sourceRef==`string`?e.sourceRef:null,workspaceChange:{changedPaths:Array.isArray(t.changedPaths)?t.changedPaths.filter(Boolean):[],deletedPaths:Array.isArray(t.deletedPaths)?t.deletedPaths.filter(Boolean):[],refreshExplorer:t.refreshExplorer!==!1,renamedPaths:Array.isArray(t.renamedPaths)?t.renamedPaths.filter(e=>e?.oldPath&&e?.newPath):[]}}}var or=class{constructor({preferredUserName:e,onChange:t,onChatChange:n,onWorkspaceEvent:r}){this.onChange=t,this.onChatChange=n,this.onWorkspaceEvent=r,this.wsBaseUrl=ne(),this.ydoc=new oe,this.chatMessages=this.ydoc.getArray(`chat-messages`),this.workspaceEvents=this.ydoc.getArray(`workspace-events`),this.provider=null,this.awareness=null,this.localUser=we(e),this.currentFile=null,this._connected=!1,this._didInitialSync=!1,this.seenWorkspaceEventIds=new Set,this.handleAwarenessChange=()=>{this._emitChange()},this.handleChatMessagesChange=()=>{this._emitChatChange()},this.handleWorkspaceEventsChange=()=>{this._emitWorkspaceEvents()}}connect(){this.provider||(this._didInitialSync=!1,this.provider=new A(this.wsBaseUrl,nr,this.ydoc,{disableBc:!0,maxBackoffTime:5e3}),se(this.provider),this.awareness=this.provider.awareness,this.awareness.setLocalStateField(`user`,this.localUser),this.awareness.setLocalStateField(`currentFile`,this.currentFile),this.awareness.on(`change`,this.handleAwarenessChange),this.chatMessages.observe(this.handleChatMessagesChange),this.workspaceEvents.observe(this.handleWorkspaceEventsChange),this.provider.on(`status`,({status:e})=>{this._connected=e===`connected`}),this.provider.on(`sync`,e=>{!e||this._didInitialSync||(this._didInitialSync=!0,this._primeWorkspaceEventCache(),this._emitChange(),this._emitChatChange({initial:!0}))}))}setCurrentFile(e){this.currentFile=e,this.awareness&&this.awareness.setLocalStateField(`currentFile`,e)}setUserName(e){e&&(this.localUser={...this.localUser,name:e},this.awareness&&this.awareness.setLocalStateField(`user`,this.localUser))}getLocalUser(){return this.localUser}sendChatMessage(e){let t=rr(e);if(!t)return null;let n={createdAt:Date.now(),filePath:this.currentFile??null,id:ir(this.localUser.peerId),peerId:this.localUser.peerId,text:t,userColor:this.localUser.color,userName:this.localUser.name};return this.ydoc.transact(()=>{this.chatMessages.push([n]);let e=this.chatMessages.length-40;e>0&&this.chatMessages.delete(0,e)},`lobby-chat-message`),n}sendWorkspaceEvent({action:e=`git`,sourceRef:t=null,workspaceChange:n={}}={}){let r=ar({action:e,createdAt:Date.now(),id:ir(this.localUser.peerId),peerId:this.localUser.peerId,sourceRef:t,workspaceChange:n});return r?(this.ydoc.transact(()=>{this.workspaceEvents.push([r]);let e=this.workspaceEvents.length-40;e>0&&this.workspaceEvents.delete(0,e)},`lobby-workspace-event`),this.seenWorkspaceEventIds.add(r.id),r):null}getMessages(){return this.chatMessages.toArray().filter(e=>e&&typeof e.id==`string`&&typeof e.peerId==`string`&&typeof e.text==`string`&&typeof e.userName==`string`)}getUsers(){if(!this.awareness)return[];let e=[];return this.awareness.getStates().forEach((t,n)=>{t.user&&e.push({...t.user,clientId:n,currentFile:t.currentFile??null,isLocal:n===this.awareness.clientID})}),e}getConnectionState(){return this._connected?{status:`connected`,unreachable:!1}:this.provider?{status:`connecting`,unreachable:!1}:{status:`disconnected`,unreachable:!1}}disconnect(){this.provider&&(this.awareness?.off(`change`,this.handleAwarenessChange),this.chatMessages?.unobserve(this.handleChatMessagesChange),this.workspaceEvents?.unobserve(this.handleWorkspaceEventsChange)),this.provider?.disconnect(),this.provider?.destroy(),this.provider=null,this.awareness=null,this._connected=!1,this._didInitialSync=!1,this.seenWorkspaceEventIds.clear()}destroy(){this.disconnect(),this.ydoc?.destroy(),this.ydoc=null}_emitChange(){this.onChange?.(this.getUsers())}_emitChatChange(e={}){this.onChatChange?.(this.getMessages(),e)}_primeWorkspaceEventCache(){this.workspaceEvents.toArray().forEach(e=>{let t=ar(e);t&&this.seenWorkspaceEventIds.add(t.id)})}_emitWorkspaceEvents(){if(!this._didInitialSync){this._primeWorkspaceEventCache();return}this.workspaceEvents.toArray().forEach(e=>{let t=ar(e);!t||this.seenWorkspaceEventIds.has(t.id)||(this.seenWorkspaceEventIds.add(t.id),t.peerId!==this.localUser.peerId&&this.onWorkspaceEvent?.(t))})}},sr=class{getHashRoute(){return ae()}navigateToFile(e,t){D(e,t)}navigateToGitDiff(e){te(e)}navigateToGitCommit(e){re(e)}navigateToGitHistory(){C()}navigateToGitFileHistory(e){E(e)}navigateToGitFilePreview(e){O(e)}},cr=class{constructor({NotificationImpl:e=globalThis.Notification,focusWindow:t=()=>globalThis.window?.focus?.()}={}){this.NotificationImpl=e,this.focusWindow=t}getPermission(){return typeof this.NotificationImpl==`function`?this.NotificationImpl.permission:`unsupported`}async requestPermission(){return typeof this.NotificationImpl==`function`?this.NotificationImpl.requestPermission():`unsupported`}createNotification({body:e,onClick:t,tag:n,title:r}){if(typeof this.NotificationImpl!=`function`)return null;let i=new this.NotificationImpl(r,{body:e,tag:n});return typeof t==`function`&&i.addEventListener(`click`,()=>{this.focusWindow(),t()}),i}},lr=class{constructor({chatNotificationsKey:e,lineWrappingKey:t,sidebarVisibleKey:n,userNameKey:r,storage:i=globalThis.localStorage}){this.chatNotificationsKey=e,this.lineWrappingKey=t,this.sidebarVisibleKey=n,this.storage=i,this.userNameKey=r}getUserName(){try{return this.storage.getItem(this.userNameKey)||``}catch{return``}}setUserName(e){try{this.storage.setItem(this.userNameKey,e)}catch{}}getLineWrappingEnabled(){try{return this.storage.getItem(this.lineWrappingKey)!==`false`}catch{return!0}}setLineWrappingEnabled(e){try{this.storage.setItem(this.lineWrappingKey,String(e))}catch{}}getSidebarVisible(){try{return this.storage.getItem(this.sidebarVisibleKey)}catch{return null}}setSidebarVisible(e){try{this.storage.setItem(this.sidebarVisibleKey,e?`true`:`false`)}catch{}}getChatNotificationsEnabled(){try{return this.storage.getItem(this.chatNotificationsKey)===`true`}catch{return!1}}setChatNotificationsEnabled(e){try{this.storage.setItem(this.chatNotificationsKey,String(e))}catch{}}},ur=6e4;function dr(e){return String(e?.build?.id??e?.buildId??``).trim()}var fr=class{constructor({currentBuildId:e=``,documentRef:t=globalThis.document??null,fetchImpl:n=globalThis.fetch?.bind(globalThis),intervalMs:r=ur,onUpdateAvailable:i=null,runtimeConfig:a={basePath:``},versionUrl:o=null,windowRef:s=globalThis.window??globalThis}={}){this.currentBuildId=String(e??``).trim(),this.documentRef=t,this.fetchImpl=n,this.intervalHandle=null,this.intervalMs=Math.max(5e3,Number(r)||ur),this.isChecking=!1,this.onUpdateAvailable=typeof i==`function`?i:null,this.runtimeConfig=a,this.updateDetected=!1,this.versionUrl=o||k(`/version.json`,a),this.windowRef=s,this.handleFocus=()=>{this.checkNow({force:!0})},this.handleVisibilityChange=()=>{this.documentRef?.hidden||this.checkNow({force:!0})}}start(){!this.fetchImpl||this.intervalHandle||(this.documentRef?.addEventListener?.(`visibilitychange`,this.handleVisibilityChange),this.windowRef?.addEventListener?.(`focus`,this.handleFocus),this.intervalHandle=this.windowRef?.setInterval?.(()=>{this.checkNow()},this.intervalMs)??null,this.checkNow({force:!0}))}stop(){this.intervalHandle&&=(this.windowRef?.clearInterval?.(this.intervalHandle),null),this.documentRef?.removeEventListener?.(`visibilitychange`,this.handleVisibilityChange),this.windowRef?.removeEventListener?.(`focus`,this.handleFocus)}async checkNow({force:e=!1}={}){if(!this.fetchImpl||this.isChecking||this.updateDetected||!e&&this.documentRef?.hidden)return!1;this.isChecking=!0;try{let e=await this.fetchImpl(this.versionUrl,{cache:`no-store`,headers:{Accept:`application/json`}});if(!e?.ok)return!1;let t=await e.json().catch(()=>null),n=dr(t);return n?this.currentBuildId?n===this.currentBuildId?!1:(this.updateDetected=!0,this.onUpdateAvailable?.(t),!0):(this.currentBuildId=n,!1):!1}catch{return!1}finally{this.isChecking=!1}}},pr=new class{async readBacklinks(e,{signal:t}={}){let n=await fetch(T(`/backlinks?file=${encodeURIComponent(e)}`),{signal:t}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error||`Failed to load backlinks`);return Array.isArray(r.backlinks)?r.backlinks:[]}};function mr(e,t={}){let n={...t};return e&&(n[`X-CollabMD-Request-Id`]=String(e)),n}async function W(e,t){let n=await e.json().catch(()=>({}));if(!e.ok||n.ok===!1){let r=Error(n.error||t);throw r.status=e.status,r.body=n,typeof n?.code==`string`&&(r.code=n.code),r}return n}function hr(e={}){let t=new URLSearchParams;return Object.entries(e).forEach(([e,n])=>{n==null||n===``||t.set(e,String(n))}),t}var gr=new class{async readStatus({force:e=!1}={}){return W(await fetch(T(`/git/status${e?`?force=true`:``}`)),`Failed to load git status`)}async readPullBackups(){return W(await fetch(T(`/git/pull-backups`)),`Failed to load pull backups`)}async readHistory({limit:e,offset:t}={}){let n=hr({limit:e,offset:t});return W(await fetch(T(`/git/history?${n.toString()}`)),`Failed to load git history`)}async readFileHistory({path:e,limit:t,offset:n}={}){let r=hr({limit:t,offset:n,path:e});return W(await fetch(T(`/git/file-history?${r.toString()}`)),`Failed to load file history`)}async readDiff({allowLargePatch:e=!1,metaOnly:t=!1,path:n=null,scope:r=`all`}={}){let i=hr({allowLargePatch:e?`true`:null,metaOnly:t?`true`:null,path:n,scope:r});return W(await fetch(T(`/git/diff?${i.toString()}`)),`Failed to load git diff`)}async readCommit({allowLargePatch:e=!1,hash:t,metaOnly:n=!1,path:r=null}={}){let i=hr({allowLargePatch:e?`true`:null,hash:t,metaOnly:n?`true`:null,path:r});return W(await fetch(T(`/git/commit?${i.toString()}`)),`Failed to load git commit`)}async readFileSnapshot({hash:e,path:t}={}){let n=hr({hash:e,path:t});return W(await fetch(T(`/git/file-snapshot?${n.toString()}`)),`Failed to load historical file preview`)}async stageFile({path:e,requestId:t=null}={}){return this.#e(`/git/stage`,{path:e},{requestId:t,fallbackError:`Failed to stage file`})}async unstageFile({path:e,requestId:t=null}={}){return this.#e(`/git/unstage`,{path:e},{requestId:t,fallbackError:`Failed to unstage file`})}async pushBranch({requestId:e=null}={}){return this.#e(`/git/push`,{},{requestId:e,fallbackError:`Failed to push branch`})}async pullBranch({requestId:e=null}={}){return this.#e(`/git/pull`,{},{requestId:e,fallbackError:`Failed to pull branch`})}async resetFile({path:e,requestId:t=null}={}){return this.#e(`/git/reset-file`,{path:e},{requestId:t,fallbackError:`Failed to reset file`})}async commit({message:e,requestId:t=null}={}){return this.#e(`/git/commit`,{message:e},{requestId:t,fallbackError:`Failed to commit staged changes`})}async#e(e,t,{fallbackError:n,requestId:r=null}={}){return W(await fetch(T(e),{body:JSON.stringify(t),headers:mr(r,{"Content-Type":`application/json`}),method:`POST`}),n)}},_r=new class{async renderSvg(e){let t=await fetch(T(`/plantuml/render`),{body:JSON.stringify({source:e}),headers:{"Content-Type":`application/json`},method:`POST`}),n=await t.json().catch(()=>null);if(!t.ok||!n?.ok||typeof n.svg!=`string`)throw Error(n?.error||`Failed to render PlantUML`);return n.svg}},vr=`collabmd-active-tab-lock`,yr=`collabmd-tab-id`,br=`collabmd-tab-lock`,xr=4e3;function Sr(){return Date.now()}function Cr(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`tab-${Sr()}-${Math.random().toString(36).slice(2,10)}`}function wr(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}var Tr=class{constructor({heartbeatIntervalMs:e=xr,onBlocked:t,onActivated:n,onStolen:r}={}){this.heartbeatIntervalMs=e,this.staleAfterMs=e*3,this.onBlocked=t,this.onActivated=n,this.onStolen=r,this.tabId=this.getOrCreateTabId(),this.channel=null,this.heartbeatTimer=null,this.isOwner=!1,this.handleStorageEvent=this.handleStorageEvent.bind(this),this.handlePageHide=this.handlePageHide.bind(this)}initialize(){window.addEventListener(`storage`,this.handleStorageEvent),window.addEventListener(`pagehide`,this.handlePageHide),`BroadcastChannel`in globalThis&&(this.channel=new BroadcastChannel(br),this.channel.addEventListener(`message`,e=>{this.handleChannelMessage(e.data)}))}destroy(){this.release(),window.removeEventListener(`storage`,this.handleStorageEvent),window.removeEventListener(`pagehide`,this.handlePageHide),this.channel?.close(),this.channel=null}tryActivate({takeover:e=!1}={}){let t=this.readLock();return this.isFreshLock(t)&&t.tabId!==this.tabId&&!e?(this.isOwner=!1,this.stopHeartbeat(),this.onBlocked?.({reason:`active-elsewhere`,ownerTabId:t.tabId}),!1):(this.writeLock(),this.startHeartbeat(),this.isOwner=!0,this.channel?.postMessage({type:`claimed`,takeover:e,tabId:this.tabId}),this.onActivated?.({takeover:e}),!0)}release(){this.readLock()?.tabId===this.tabId&&(localStorage.removeItem(vr),this.channel?.postMessage({type:`released`,tabId:this.tabId})),this.isOwner=!1,this.stopHeartbeat()}getOrCreateTabId(){try{let e=window.sessionStorage.getItem(yr);if(e)return e;let t=Cr();return window.sessionStorage.setItem(yr,t),t}catch{return Cr()}}readLock(){try{return wr(window.localStorage.getItem(vr))}catch{return null}}isFreshLock(e){return!!(e&&typeof e.tabId==`string`&&Number.isFinite(e.updatedAt)&&Sr()-e.updatedAt<this.staleAfterMs)}writeLock(){try{window.localStorage.setItem(vr,JSON.stringify({tabId:this.tabId,updatedAt:Sr()}))}catch{}}startHeartbeat(){this.stopHeartbeat(),this.writeLock(),this.heartbeatTimer=window.setInterval(()=>{if(!this.isOwner){this.stopHeartbeat();return}this.writeLock()},this.heartbeatIntervalMs)}stopHeartbeat(){this.heartbeatTimer&&=(window.clearInterval(this.heartbeatTimer),null)}handleStorageEvent(e){if(e.key!==vr)return;let t=wr(e.newValue);this.handleExternalLockChange(t)}handleChannelMessage(e){!e||typeof e!=`object`||e.tabId===this.tabId||e.type===`claimed`&&this.handleExternalLockChange(this.readLock())}handleExternalLockChange(e){this.isOwner&&this.isFreshLock(e)&&e.tabId!==this.tabId&&(this.isOwner=!1,this.stopHeartbeat(),this.onStolen?.({ownerTabId:e.tabId}))}handlePageHide(){this.release()}},Er=`__workspace__`;function Dr(e){return!e?.path||!e?.type?null:e.nodeType===`directory`||e.type===`directory`?{children:[],name:e.name,path:e.path,type:`directory`}:{name:e.name,path:e.path,type:e.type}}function Or(e=[]){return e.sort((e,t)=>e.type===`directory`&&t.type!==`directory`?-1:e.type!==`directory`&&t.type===`directory`?1:e.name.localeCompare(t.name,void 0,{sensitivity:`base`})),e.forEach(e=>{Array.isArray(e.children)&&Or(e.children)}),e}function kr(e){return e instanceof Map?e:new Map(Object.entries(e??{}))}function Ar(e=[],t=`asc`){let n=t===`desc`?-1:1;return[...e].sort((e,t)=>{let r=e.split(`/`).length-t.split(`/`).length;return r===0?e.localeCompare(t,void 0,{sensitivity:`base`})*n:r*n})}var jr=class{constructor(){this.entriesByPath=new Map,this.nodesByPath=new Map,this.nodeParentPathByPath=new Map,this.roots=[]}reset(e){return this.entriesByPath=kr(e),this.nodesByPath=new Map,this.nodeParentPathByPath=new Map,this.roots=[],this.entriesByPath.forEach(e=>{let t=Dr(e);t&&this.nodesByPath.set(e.path,t)}),Ar(Array.from(this.nodesByPath.keys())).forEach(e=>{let t=this.nodesByPath.get(e);t&&this.attachNode(e,t,this.entriesByPath.get(e)?.parentPath||``)}),Or(this.roots),this.roots}getTree(){return this.roots}applyMapChanges(e,t){let n=[],r=[];return e.forEach((e,t)=>{e.action===`delete`?n.push(t):r.push(t)}),Ar(n,`desc`).forEach(e=>{this.removeEntry(e)}),Ar(r).forEach(e=>{this.upsertEntry(e,t.get(e))}),Or(this.roots),this.roots}removeEntry(e){let t=this.nodesByPath.get(e);if(!t){this.entriesByPath.delete(e),this.nodeParentPathByPath.delete(e);return}this.detachNode(e,t),this.nodesByPath.delete(e),this.entriesByPath.delete(e),this.nodeParentPathByPath.delete(e)}upsertEntry(e,t){if(!t?.path||!t?.type){this.removeEntry(e);return}let n=Dr(t);if(!n){this.removeEntry(e);return}let r=this.nodesByPath.get(e);!r||r.type===`directory`!=(n.type===`directory`)?(r&&this.detachNode(e,r),r=n,this.nodesByPath.set(e,r)):(r.name=n.name,r.path=n.path,r.type=n.type,r.type===`directory`&&!Array.isArray(r.children)&&(r.children=[]),r.type!==`directory`&&Array.isArray(r.children)&&delete r.children),this.entriesByPath.set(e,t),this.attachNode(e,r,t.parentPath||``),r.type===`directory`&&this.rehomeChildren(e)}detachNode(e,t){let n=this.nodeParentPathByPath.get(e)||``,r=n?this.nodesByPath.get(n)?.children:this.roots,i=r?.indexOf?.(t)??-1;i>=0&&r.splice(i,1),this.nodeParentPathByPath.delete(e)}attachNode(e,t,n=``){let r=this.nodesByPath.get(n)?.type===`directory`?n:``,i=this.nodeParentPathByPath.get(e);if(i===r)return;i!==void 0&&this.detachNode(e,t);let a=r?this.nodesByPath.get(r)?.children:this.roots;a.includes(t)||a.push(t),this.nodeParentPathByPath.set(e,r)}rehomeChildren(e){this.entriesByPath.forEach((t,n)=>{if(t?.parentPath!==e)return;let r=this.nodesByPath.get(n);r&&this.attachNode(n,r,e)})}},Mr=class{constructor({onTreeChange:e=()=>{},onWorkspaceEvent:t=()=>{}}={}){this.onTreeChange=e,this.onWorkspaceEvent=t,this.ydoc=new oe,this.entries=this.ydoc.getMap(`entries`),this.events=this.ydoc.getArray(`events`),this.provider=null,this._didInitialSync=!1,this.seenEventIds=new Set,this.treeModel=new jr,this.handleEntriesChange=e=>{!this._didInitialSync||!e||this.onTreeChange(this.treeModel.applyMapChanges(e.changes.keys,this.entries),{changedPaths:Array.from(e.changes.keys.keys()),reset:!1})},this.handleEventsChange=()=>{if(!this._didInitialSync){this.primeEventCache();return}this.events.toArray().forEach(e=>{let t=gt(e);!t||this.seenEventIds.has(t.id)||(this.seenEventIds.add(t.id),this.onWorkspaceEvent(t))})}}connect(){this.provider||(this._didInitialSync=!1,this.provider=new A(ne(),Er,this.ydoc,{disableBc:!0,maxBackoffTime:5e3}),se(this.provider),this.entries.observe(this.handleEntriesChange),this.events.observe(this.handleEventsChange),this.provider.on(`sync`,e=>{!e||this._didInitialSync||(this._didInitialSync=!0,this.primeEventCache(),this.onTreeChange(this.treeModel.reset(this.entries.toJSON()),{changedPaths:[],reset:!0}))}))}primeEventCache(){this.events.toArray().forEach(e=>{let t=gt(e);t&&this.seenEventIds.add(t.id)})}disconnect(){this.entries.unobserve(this.handleEntriesChange),this.events.unobserve(this.handleEventsChange),this.provider?.disconnect(),this.provider?.destroy(),this.provider=null,this._didInitialSync=!1,this.seenEventIds.clear(),this.treeModel.reset(new Map)}destroy(){this.disconnect(),this.ydoc.destroy()}},Nr=class{constructor({documentRef:e=document,headerPanelElement:t=null,inlinePanelElement:n=null,loadBacklinks:r=null,onFileSelect:i,panelElement:a}){this.documentRef=e,this.headerPanel=t,this.panelRoot=a,this.inlinePanel=n,this.loadBacklinks=r,this.onFileSelect=i,this._expanded=!1,this._currentFile=null,this._displayMode=`dock`,this._fetchController=null,this._backlinks=[],this._pendingOutsidePointer=null;let o=this.panelRoot?.querySelector(`[data-backlinks-variant="dock"]`)??this.panelRoot;this.panels=[this._createPanelRef(o,this.panelRoot),this._createPanelRef(this.headerPanel,this.headerPanel),this._createPanelRef(this.inlinePanel,this.inlinePanel)].filter(Boolean),this.handleDocumentPointerDown=e=>{if(!this._expanded)return;let t=e?.target;if(t&&this.panels.some(({panel:e})=>e?.contains?.(t))){this._pendingOutsidePointer=null;return}e?.pointerType===`mouse`&&e?.button!==0||(this._pendingOutsidePointer={pointerId:e?.pointerId??`mouse`,startX:Number(e?.clientX??0),startY:Number(e?.clientY??0)})},this.handleDocumentPointerMove=e=>{if(!this._pendingOutsidePointer)return;let t=Math.abs(Number(e?.clientX??0)-this._pendingOutsidePointer.startX),n=Math.abs(Number(e?.clientY??0)-this._pendingOutsidePointer.startY);(t>10||n>10)&&(this._pendingOutsidePointer=null)},this.handleDocumentPointerEnd=e=>{if(!this._expanded||!this._pendingOutsidePointer)return;let t=e?.target;if(t&&this.panels.some(({panel:e})=>e?.contains?.(t))){this._pendingOutsidePointer=null;return}this._pendingOutsidePointer=null,this.close()},this.handleDocumentKeyDown=e=>{!this._expanded||e?.key!==`Escape`||(e.preventDefault?.(),this.close())},this.bindEvents()}bindEvents(){this.panels.forEach(e=>{e.header?.addEventListener(`click`,()=>{this._backlinks.length!==0&&(this._expanded=!this._expanded,this._pendingOutsidePointer=null,this._applyExpandState())})}),this.documentRef?.addEventListener?.(`pointerdown`,this.handleDocumentPointerDown),this.documentRef?.addEventListener?.(`pointermove`,this.handleDocumentPointerMove,{passive:!0}),this.documentRef?.addEventListener?.(`pointerup`,this.handleDocumentPointerEnd),this.documentRef?.addEventListener?.(`pointercancel`,this.handleDocumentPointerEnd),this.documentRef?.addEventListener?.(`keydown`,this.handleDocumentKeyDown)}async load(e){let t=e!==this._currentFile;if(this._currentFile=e,t&&(this._expanded=!1),!e){this._backlinks=[],this._render();return}this._fetchController?.abort(),this._fetchController=new AbortController;try{let t=await this.loadBacklinks(e,{signal:this._fetchController.signal});if(this._currentFile!==e)return;this._backlinks=t}catch(e){if(e.name===`AbortError`)return;console.warn(`[backlinks] Failed to load:`,e.message),this._backlinks=[]}this._render()}setDisplayMode(e=`dock`){let t=e===`header`?`header`:`dock`;this._displayMode!==t&&(this._displayMode=t,this._expanded=!1,this._pendingOutsidePointer=null,this._render())}clear(){this._currentFile=null,this._backlinks=[],this._expanded=!1,this._render()}close(){this._expanded&&(this._expanded=!1,this._pendingOutsidePointer=null,this._applyExpandState())}_createPanelRef(e,t=e){return e?{panel:e,header:e.querySelector(`.backlinks-header`),toggle:e.querySelector(`.backlinks-toggle`),countBadge:e.querySelector(`.backlinks-count`),body:e.querySelector(`.backlinks-body`),list:e.querySelector(`.backlinks-list`),root:t}:null}_render(){let e=this._backlinks.length,t=e===1?`Linked Mention`:`Linked Mentions`,n=!!this._currentFile&&e>0;n||(this._expanded=!1),this.panels.forEach(r=>{let i=n&&this._shouldShowPanel(r);r.root?.classList?.toggle?.(`hidden`,!i),r.countBadge.textContent=n?String(e):``,r.toggle.textContent=t,r.header?.classList.toggle(`backlinks-header-empty`,!i),i?this._renderList(r.list):r.list.innerHTML=``}),this._applyExpandState()}_shouldShowPanel(e){let t=e.panel?.getAttribute?.(`data-backlinks-variant`)??``;return t===`header`?this._displayMode===`header`:t===`dock`?this._displayMode===`dock`:!0}_renderList(e){if(!e)return;e.innerHTML=``;let t=this.documentRef?.createDocumentFragment?.(),n=t??e;this._backlinks.forEach(e=>{n.appendChild(this._createBacklinkItem(e))}),t&&e.appendChild(t)}_createBacklinkItem(e){let t=c(e.file.split(`/`).pop()),n=e.file.includes(`/`)?e.file.substring(0,e.file.lastIndexOf(`/`)):``,r=this.documentRef.createElement(`button`);r.type=`button`,r.className=`backlink-item`,r.addEventListener(`click`,()=>{this.close(),this.onFileSelect?.(e.file)});let i=this.documentRef.createElement(`div`);if(i.className=`backlink-file-name`,i.innerHTML=`
|
|
143
|
+
`).join(``)}function zn(){let e=Pn(this._activeMarkdownBlockAction||Nn);return kn(e)?e:Nn}function Bn(){let e=this.elements?.markdownToolbar;e&&(e.innerHTML=Rn(this.getActiveMarkdownBlockAction()),this.renderMarkdownBlockMenuPopover(),this.syncMarkdownToolbarBlockUi())}function Vn(){return this._markdownBlockMenuPopover??null}function Hn(){let e=this.elements?.editorContainer??document.body,t=this.getMarkdownBlockMenuPopover();t?t.parentElement!==e&&e?.appendChild(t):(t=document.createElement(`div`),t.className=`markdown-toolbar-popover hidden`,t.innerHTML=`<div class="markdown-toolbar-menu" data-markdown-block-menu role="menu" aria-label="Block formatting"></div>`,t.addEventListener(`click`,e=>{this.handleMarkdownToolbarClick?.(e)}),t.addEventListener(`keydown`,e=>{this.handleMarkdownToolbarKeydown?.(e)}),e?.appendChild(t),this._markdownBlockMenuPopover=t);let n=t.querySelector(`[data-markdown-block-menu]`);n&&(n.innerHTML=Ln(this.getActiveMarkdownBlockAction()))}function Un(){let e=this.elements?.markdownToolbar;if(!e)return;let t=this.getActiveMarkdownBlockAction(),n=Dn(t),r=e.querySelector(`[data-markdown-block-trigger-label]`);r&&(r.textContent=An(t));let i=e.querySelector(`[data-markdown-block-menu-toggle]`);i&&n&&(i.setAttribute(`aria-label`,`${n.label}. Block formatting`),i.setAttribute(`title`,`${n.label}. Block formatting`));let a=Array.from(this.getMarkdownBlockMenuPopover()?.querySelectorAll(`[data-markdown-block-action]`)??[]);[...e.querySelectorAll(`[data-markdown-block-action]`),...a].forEach(e=>{let n=e.getAttribute(`data-markdown-block-action`)===t;e.classList.toggle(`is-active`,n),e.setAttribute(`aria-checked`,n?`true`:`false`)})}function Wn(e){let t=Pn(e);kn(t)&&(this._activeMarkdownBlockAction=t,this.syncMarkdownToolbarBlockUi())}function Gn(){return!!this.elements?.markdownToolbar?.classList.contains(`is-menu-open`)}function Kn(){let e=this.getMarkdownBlockMenuPopover(),t=this.elements?.markdownToolbar?.querySelector(`[data-markdown-block-menu-toggle]`),n=e?.parentElement;if(!e||!t||!(n instanceof HTMLElement))return;let r=t.getBoundingClientRect(),i=n.getBoundingClientRect(),a=e.getBoundingClientRect(),o=a.width||176,s=a.height||240,c=r.left-i.left,l=Math.max(8,i.width-o-8),u=r.bottom-i.top+6,d=u+s<=i.height-8;e.style.left=`${Math.max(8,Math.min(c,l))}px`,e.style.top=`${d?u:Math.max(8,r.top-i.top-s-6)}px`}function qn(){let e=this.elements?.markdownToolbar;e&&(this.renderMarkdownBlockMenuPopover(),e.classList.add(`is-menu-open`),this.getMarkdownBlockMenuPopover()?.classList.remove(`hidden`),e.querySelector(`[data-markdown-block-menu-toggle]`)?.setAttribute(`aria-expanded`,`true`),this.positionMarkdownBlockMenu())}function Jn(){let e=this.elements?.markdownToolbar;e&&(e.classList.remove(`is-menu-open`),this.getMarkdownBlockMenuPopover()?.classList.add(`hidden`),e.querySelector(`[data-markdown-block-menu-toggle]`)?.setAttribute(`aria-expanded`,`false`))}function Yn(){if(this.isMarkdownBlockMenuOpen()){this.closeMarkdownBlockMenu();return}this.openMarkdownBlockMenu()}function Xn(e){let t=e.target instanceof Element?e.target:null;if(!t)return;let n=t.closest(`[data-editor-command]`)?.getAttribute(`data-editor-command`);if(n){e.preventDefault(),this.runEditorCommand(n);return}if(t.closest(`[data-markdown-block-menu-toggle]`)){e.preventDefault(),this.toggleMarkdownBlockMenu();return}let r=t.closest(`[data-markdown-block-action]`);if(r){e.preventDefault();let t=r.getAttribute(`data-markdown-block-action`);this.closeMarkdownBlockMenu(),t&&this.applyMarkdownToolbarAction(t);return}let i=t.closest(`[data-markdown-action]`)?.getAttribute(`data-markdown-action`);i&&this.applyMarkdownToolbarAction(i)}function Zn(e){if(!this.isMarkdownBlockMenuOpen()){e.target instanceof Element&&e.target.closest(`[data-markdown-block-menu-toggle]`)&&[`ArrowDown`,`Enter`,` `].includes(e.key)&&(e.preventDefault(),this.openMarkdownBlockMenu(),this.getMarkdownBlockMenuPopover()?.querySelector(`[data-markdown-block-action]`)?.focus());return}if(e.key===`Escape`){e.preventDefault(),this.closeMarkdownBlockMenu(),this.elements?.markdownToolbar?.querySelector(`[data-markdown-block-menu-toggle]`)?.focus();return}let t=Array.from(this.getMarkdownBlockMenuPopover()?.querySelectorAll(`[data-markdown-block-action]`)??[]);if(t.length===0)return;let n=t.findIndex(t=>t===e.target);n<0||(e.key===`ArrowDown`?(e.preventDefault(),t[(n+1)%t.length]?.focus()):e.key===`ArrowUp`&&(e.preventDefault(),t[(n-1+t.length)%t.length]?.focus()))}function Qn(e){this.isMarkdownBlockMenuOpen()&&(this.elements?.markdownToolbar?.contains(e.target)||this.getMarkdownBlockMenuPopover()?.contains(e.target)||this.closeMarkdownBlockMenu())}function $n(e){if(!this.session||!u(this.currentFilePath))return;if(e===`image`){this.handleToolbarImageInsert();return}let t=Pn(e);if(!this.session.applyMarkdownToolbarAction(t)){this.toastController.show(`Formatting action is unavailable`);return}kn(t)&&this.setActiveMarkdownBlockAction(t)}function er(e){return this.session?.runEditorCommand?.(e)?!0:(this.toastController.show(`Editor action is unavailable`),!1)}async function tr(){let e=await this.pickImageFile();e&&await this.handleEditorImageInsert(e)}function nr(){return new Promise(e=>{let t=document.createElement(`input`);t.type=`file`,t.accept=Mn,t.style.position=`fixed`,t.style.left=`-9999px`,document.body.appendChild(t);let n=!1,r=null,i=i=>{n||(n=!0,r&&window.clearTimeout(r),window.removeEventListener(`focus`,a),t.remove(),e(i))},a=()=>{r=window.setTimeout(()=>{n||t.files?.length||i(null)},250)};t.addEventListener(`change`,()=>{i(t.files?.[0]??null)},{once:!0}),t.addEventListener(`cancel`,()=>{i(null)},{once:!0}),window.addEventListener(`focus`,a,{once:!0}),t.click()})}async function rr(e){if(!this.session||!u(this.currentFilePath))return console.warn(`[ui] Ignoring image insert because there is no active markdown session.`,{currentFilePath:this.currentFilePath,hasSession:!!this.session}),!1;let t=this.currentFilePath,n=this.session;try{console.debug(`[ui] Uploading image attachment.`,{fileName:e?.name||``,size:e?.size??null,sourcePath:t,type:e?.type||``});let r=await this.vaultApiClient.uploadImageAttachment({file:e,fileName:e?.name||``,sourcePath:t});return await this.fileExplorer.refresh(),this.currentFilePath===t&&this.session&&this.session===n&&typeof r?.markdown==`string`&&(console.debug(`[ui] Inserting uploaded image markdown into the editor.`,{sourcePath:t,storedPath:r.path??``}),this.session.insertText(r.markdown)),!0}catch(e){return console.error(`[ui] Failed to insert image attachment:`,e),this.toastController.show(e.message||`Failed to upload image`),!1}}async function ir(){try{await navigator.clipboard.writeText(window.location.href),this.toastController.show(`Link copied`)}catch{this.toastController.show(`Failed to copy link`)}}var ar={applyMarkdownToolbarAction:$n,copyCurrentLink:ir,closeMarkdownBlockMenu:Jn,getActiveMarkdownBlockAction:zn,getMarkdownBlockMenuPopover:Vn,handleEditorImageInsert:rr,handleMarkdownToolbarClick:Xn,handleMarkdownToolbarDocumentPointerDown:Qn,handleMarkdownToolbarKeydown:Zn,handleToolbarImageInsert:tr,isMarkdownBlockMenuOpen:Gn,openMarkdownBlockMenu:qn,positionMarkdownBlockMenu:Kn,renderMarkdownBlockMenuPopover:Hn,pickImageFile:nr,renderMarkdownToolbar:Bn,runEditorCommand:er,setActiveMarkdownBlockAction:Wn,syncMarkdownToolbarBlockUi:Un,toggleMarkdownBlockMenu:Yn},H={...rn,...fn,...Ot,...ar,...vn},U={isExcalidrawFile(e){return g(e)},isBaseFile(e){return l(e)},isDrawioFile(e){return p(e)},isImageFile(e){return o(e)},isMermaidFile(e){return v(e)},isPlantUmlFile(e){return s(e)},createDiagramPreviewDocument(e,t=``){return this.workspacePreviewController.createDiagramPreviewDocument(e,t)},getPreviewSource(){let e=this.getStaticPreviewDocument?.(),t=e?.currentFilePath??e?.filePath??null;return e&&t&&t===this.currentFilePath?this.isMermaidFile(this.currentFilePath)?this.createDiagramPreviewDocument(`mermaid`,e.content):this.isPlantUmlFile(this.currentFilePath)?this.createDiagramPreviewDocument(`plantuml`,e.content):String(e.content??``):this.workspacePreviewController.getPreviewSource(this.currentFilePath,{drawioMode:this.currentDrawioMode??null})},getStaticPreviewDocument(){return this._staticPreviewDocument??null},setStaticPreviewDocument(e){let t=e?.filePath??e?.path??null,n=e?.currentFilePath??t;this._staticPreviewDocument=e?{content:String(e.content??``),currentFilePath:n,fileKind:e.fileKind??f(t),filePath:t,hash:e.hash??null}:null},clearStaticPreviewDocument(){this._staticPreviewDocument=null},supportsFileHistory(e){let t=f(e);return t!==null&&t!==`image`},getDisplayName(e){return c(String(e??``).split(`/`).pop())},resetPreviewMode(){this.workspacePreviewController.resetPreviewMode()},syncFileChrome(e,t={}){this.workspacePreviewController.syncFileChrome(e,t)},handleLayoutViewRequest(e){return!this.currentFilePath||!this.isDrawioFile(this.currentFilePath)?!0:this.currentDrawioMode===`text`?e===`preview`?(this.layoutController.isMobileViewport?.()&&this.layoutController.primeView(e),this.navigation.navigateToFile(this.currentFilePath),!1):!0:e===`preview`?!0:(this.layoutController.primeView(e),this.navigation.navigateToFile(this.currentFilePath,{drawioMode:`text`}),!1)},renderExcalidrawFilePreview(e){this.workspacePreviewController.renderExcalidrawFilePreview(e)},renderDrawioFilePreview(e){this.workspacePreviewController.renderDrawioFilePreview(e)},renderImageFilePreview(e){this.workspacePreviewController.renderImageFilePreview(e)},renderBaseFilePreview(e){return this.workspacePreviewController.renderBaseFilePreview(e)},renderTextFilePreview(e){this.workspacePreviewController.renderTextFilePreview(e)},createResizeHandler(){return this.workspacePreviewController.createResizeHandler(()=>this.restoreSidebarState())},initializePreviewLayoutObserver(){this._previewLayoutResizeObserver?.disconnect(),this._previewLayoutResizeObserver=this.workspacePreviewController.initializePreviewLayoutObserver(()=>this.schedulePreviewLayoutSync())},schedulePreviewLayoutSync({delayMs:e=120}={}){this.workspacePreviewController.schedulePreviewLayoutSync({delayMs:e,hydrationPaused:this._previewHydrationPaused,previewLayoutSyncTimer:this._previewLayoutSyncTimer,setPendingPreviewLayoutSync:e=>{this._pendingPreviewLayoutSync=e},setPreviewLayoutSyncTimer:e=>{this._previewLayoutSyncTimer=e}})},handleEditorScrollActivityChange(e){this.workspacePreviewController.handleEditorScrollActivityChange({isActive:e,pendingPreviewLayoutSync:this._pendingPreviewLayoutSync,previewLayoutSyncTimer:this._previewLayoutSyncTimer,setHydrationPaused:e=>{this._previewHydrationPaused=e},setPendingPreviewLayoutSync:e=>{this._pendingPreviewLayoutSync=e},setPreviewLayoutSyncTimer:e=>{this._previewLayoutSyncTimer=e}})},async handleHashChange(){await this.workspaceRouteController.handleHashChange()},showEmptyState(){clearTimeout(this._previewLayoutSyncTimer),this._previewLayoutSyncTimer=null,this._pendingPreviewLayoutSync=!1,this._previewHydrationPaused=!1,this.workspaceRouteController.showEmptyState()},showDiffState(){clearTimeout(this._previewLayoutSyncTimer),this._previewLayoutSyncTimer=null,this._pendingPreviewLayoutSync=!1,this._previewHydrationPaused=!1,this.workspaceRouteController.showDiffState()},async openFile(e){await this.workspaceRouteController.openFile(e)},cleanupSession(){this.workspaceRouteController.cleanupSession()},handleWikiLinkClick(e){this.wikiLinkFileController.handleWikiLinkClick(e)},normalizeNewWikiFilePath(e){return this.wikiLinkFileController.normalizeNewWikiFilePath(e)},async createAndOpenFile(e,t){await this.wikiLinkFileController.createAndOpenFile(e,t)},handleFileSelection(e,{closeSidebarOnMobile:t=!1}={}){this.workspaceRouteController.handleFileSelection(e,{closeSidebarOnMobile:t})}},or=`__lobby__`;function sr(e){return String(e??``).replace(/\s+/g,` `).trim().slice(0,280)||null}function cr(e){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${e||`user`}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function lr(e){if(!e||typeof e!=`object`||typeof e.id!=`string`)return null;let t=e.workspaceChange&&typeof e.workspaceChange==`object`?e.workspaceChange:{};return{action:typeof e.action==`string`?e.action:`git`,createdAt:Number.isFinite(e.createdAt)?e.createdAt:Date.now(),id:e.id,peerId:typeof e.peerId==`string`?e.peerId:null,sourceRef:typeof e.sourceRef==`string`?e.sourceRef:null,workspaceChange:{changedPaths:Array.isArray(t.changedPaths)?t.changedPaths.filter(Boolean):[],deletedPaths:Array.isArray(t.deletedPaths)?t.deletedPaths.filter(Boolean):[],refreshExplorer:t.refreshExplorer!==!1,renamedPaths:Array.isArray(t.renamedPaths)?t.renamedPaths.filter(e=>e?.oldPath&&e?.newPath):[]}}}var ur=class{constructor({preferredUserName:e,onChange:t,onChatChange:n,onWorkspaceEvent:r}){this.onChange=t,this.onChatChange=n,this.onWorkspaceEvent=r,this.wsBaseUrl=ne(),this.ydoc=new oe,this.chatMessages=this.ydoc.getArray(`chat-messages`),this.workspaceEvents=this.ydoc.getArray(`workspace-events`),this.provider=null,this.awareness=null,this.localUser=we(e),this.currentFile=null,this._connected=!1,this._didInitialSync=!1,this.seenWorkspaceEventIds=new Set,this.handleAwarenessChange=()=>{this._emitChange()},this.handleChatMessagesChange=()=>{this._emitChatChange()},this.handleWorkspaceEventsChange=()=>{this._emitWorkspaceEvents()}}connect(){this.provider||(this._didInitialSync=!1,this.provider=new A(this.wsBaseUrl,or,this.ydoc,{disableBc:!0,maxBackoffTime:5e3}),se(this.provider),this.awareness=this.provider.awareness,this.awareness.setLocalStateField(`user`,this.localUser),this.awareness.setLocalStateField(`currentFile`,this.currentFile),this.awareness.on(`change`,this.handleAwarenessChange),this.chatMessages.observe(this.handleChatMessagesChange),this.workspaceEvents.observe(this.handleWorkspaceEventsChange),this.provider.on(`status`,({status:e})=>{this._connected=e===`connected`}),this.provider.on(`sync`,e=>{!e||this._didInitialSync||(this._didInitialSync=!0,this._primeWorkspaceEventCache(),this._emitChange(),this._emitChatChange({initial:!0}))}))}setCurrentFile(e){this.currentFile=e,this.awareness&&this.awareness.setLocalStateField(`currentFile`,e)}setUserName(e){e&&(this.localUser={...this.localUser,name:e},this.awareness&&this.awareness.setLocalStateField(`user`,this.localUser))}getLocalUser(){return this.localUser}sendChatMessage(e){let t=sr(e);if(!t)return null;let n={createdAt:Date.now(),filePath:this.currentFile??null,id:cr(this.localUser.peerId),peerId:this.localUser.peerId,text:t,userColor:this.localUser.color,userName:this.localUser.name};return this.ydoc.transact(()=>{this.chatMessages.push([n]);let e=this.chatMessages.length-40;e>0&&this.chatMessages.delete(0,e)},`lobby-chat-message`),n}sendWorkspaceEvent({action:e=`git`,sourceRef:t=null,workspaceChange:n={}}={}){let r=lr({action:e,createdAt:Date.now(),id:cr(this.localUser.peerId),peerId:this.localUser.peerId,sourceRef:t,workspaceChange:n});return r?(this.ydoc.transact(()=>{this.workspaceEvents.push([r]);let e=this.workspaceEvents.length-40;e>0&&this.workspaceEvents.delete(0,e)},`lobby-workspace-event`),this.seenWorkspaceEventIds.add(r.id),r):null}getMessages(){return this.chatMessages.toArray().filter(e=>e&&typeof e.id==`string`&&typeof e.peerId==`string`&&typeof e.text==`string`&&typeof e.userName==`string`)}getUsers(){if(!this.awareness)return[];let e=[];return this.awareness.getStates().forEach((t,n)=>{t.user&&e.push({...t.user,clientId:n,currentFile:t.currentFile??null,isLocal:n===this.awareness.clientID})}),e}getConnectionState(){return this._connected?{status:`connected`,unreachable:!1}:this.provider?{status:`connecting`,unreachable:!1}:{status:`disconnected`,unreachable:!1}}disconnect(){this.provider&&(this.awareness?.off(`change`,this.handleAwarenessChange),this.chatMessages?.unobserve(this.handleChatMessagesChange),this.workspaceEvents?.unobserve(this.handleWorkspaceEventsChange)),this.provider?.disconnect(),this.provider?.destroy(),this.provider=null,this.awareness=null,this._connected=!1,this._didInitialSync=!1,this.seenWorkspaceEventIds.clear()}destroy(){this.disconnect(),this.ydoc?.destroy(),this.ydoc=null}_emitChange(){this.onChange?.(this.getUsers())}_emitChatChange(e={}){this.onChatChange?.(this.getMessages(),e)}_primeWorkspaceEventCache(){this.workspaceEvents.toArray().forEach(e=>{let t=lr(e);t&&this.seenWorkspaceEventIds.add(t.id)})}_emitWorkspaceEvents(){if(!this._didInitialSync){this._primeWorkspaceEventCache();return}this.workspaceEvents.toArray().forEach(e=>{let t=lr(e);!t||this.seenWorkspaceEventIds.has(t.id)||(this.seenWorkspaceEventIds.add(t.id),t.peerId!==this.localUser.peerId&&this.onWorkspaceEvent?.(t))})}},dr=class{getHashRoute(){return ae()}navigateToFile(e,t){D(e,t)}navigateToGitDiff(e){te(e)}navigateToGitCommit(e){re(e)}navigateToGitHistory(){C()}navigateToGitFileHistory(e){E(e)}navigateToGitFilePreview(e){O(e)}},fr=class{constructor({NotificationImpl:e=globalThis.Notification,focusWindow:t=()=>globalThis.window?.focus?.()}={}){this.NotificationImpl=e,this.focusWindow=t}getPermission(){return typeof this.NotificationImpl==`function`?this.NotificationImpl.permission:`unsupported`}async requestPermission(){return typeof this.NotificationImpl==`function`?this.NotificationImpl.requestPermission():`unsupported`}createNotification({body:e,onClick:t,tag:n,title:r}){if(typeof this.NotificationImpl!=`function`)return null;let i=new this.NotificationImpl(r,{body:e,tag:n});return typeof t==`function`&&i.addEventListener(`click`,()=>{this.focusWindow(),t()}),i}},pr=class{constructor({chatNotificationsKey:e,lineWrappingKey:t,sidebarVisibleKey:n,userNameKey:r,storage:i=globalThis.localStorage}){this.chatNotificationsKey=e,this.lineWrappingKey=t,this.sidebarVisibleKey=n,this.storage=i,this.userNameKey=r}getUserName(){try{return this.storage.getItem(this.userNameKey)||``}catch{return``}}setUserName(e){try{this.storage.setItem(this.userNameKey,e)}catch{}}getLineWrappingEnabled(){try{return this.storage.getItem(this.lineWrappingKey)!==`false`}catch{return!0}}setLineWrappingEnabled(e){try{this.storage.setItem(this.lineWrappingKey,String(e))}catch{}}getSidebarVisible(){try{return this.storage.getItem(this.sidebarVisibleKey)}catch{return null}}setSidebarVisible(e){try{this.storage.setItem(this.sidebarVisibleKey,e?`true`:`false`)}catch{}}getChatNotificationsEnabled(){try{return this.storage.getItem(this.chatNotificationsKey)===`true`}catch{return!1}}setChatNotificationsEnabled(e){try{this.storage.setItem(this.chatNotificationsKey,String(e))}catch{}}},mr=6e4;function hr(e){return String(e?.build?.id??e?.buildId??``).trim()}var gr=class{constructor({currentBuildId:e=``,documentRef:t=globalThis.document??null,fetchImpl:n=globalThis.fetch?.bind(globalThis),intervalMs:r=mr,onUpdateAvailable:i=null,runtimeConfig:a={basePath:``},versionUrl:o=null,windowRef:s=globalThis.window??globalThis}={}){this.currentBuildId=String(e??``).trim(),this.documentRef=t,this.fetchImpl=n,this.intervalHandle=null,this.intervalMs=Math.max(5e3,Number(r)||mr),this.isChecking=!1,this.onUpdateAvailable=typeof i==`function`?i:null,this.runtimeConfig=a,this.updateDetected=!1,this.versionUrl=o||k(`/version.json`,a),this.windowRef=s,this.handleFocus=()=>{this.checkNow({force:!0})},this.handleVisibilityChange=()=>{this.documentRef?.hidden||this.checkNow({force:!0})}}start(){!this.fetchImpl||this.intervalHandle||(this.documentRef?.addEventListener?.(`visibilitychange`,this.handleVisibilityChange),this.windowRef?.addEventListener?.(`focus`,this.handleFocus),this.intervalHandle=this.windowRef?.setInterval?.(()=>{this.checkNow()},this.intervalMs)??null,this.checkNow({force:!0}))}stop(){this.intervalHandle&&=(this.windowRef?.clearInterval?.(this.intervalHandle),null),this.documentRef?.removeEventListener?.(`visibilitychange`,this.handleVisibilityChange),this.windowRef?.removeEventListener?.(`focus`,this.handleFocus)}async checkNow({force:e=!1}={}){if(!this.fetchImpl||this.isChecking||this.updateDetected||!e&&this.documentRef?.hidden)return!1;this.isChecking=!0;try{let e=await this.fetchImpl(this.versionUrl,{cache:`no-store`,headers:{Accept:`application/json`}});if(!e?.ok)return!1;let t=await e.json().catch(()=>null),n=hr(t);return n?this.currentBuildId?n===this.currentBuildId?!1:(this.updateDetected=!0,this.onUpdateAvailable?.(t),!0):(this.currentBuildId=n,!1):!1}catch{return!1}finally{this.isChecking=!1}}},_r=new class{async readBacklinks(e,{signal:t}={}){let n=await fetch(T(`/backlinks?file=${encodeURIComponent(e)}`),{signal:t}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error||`Failed to load backlinks`);return Array.isArray(r.backlinks)?r.backlinks:[]}};function vr(e,t={}){let n={...t};return e&&(n[`X-CollabMD-Request-Id`]=String(e)),n}async function W(e,t){let n=await e.json().catch(()=>({}));if(!e.ok||n.ok===!1){let r=Error(n.error||t);throw r.status=e.status,r.body=n,typeof n?.code==`string`&&(r.code=n.code),r}return n}function yr(e={}){let t=new URLSearchParams;return Object.entries(e).forEach(([e,n])=>{n==null||n===``||t.set(e,String(n))}),t}var br=new class{async readStatus({force:e=!1}={}){return W(await fetch(T(`/git/status${e?`?force=true`:``}`)),`Failed to load git status`)}async readPullBackups(){return W(await fetch(T(`/git/pull-backups`)),`Failed to load pull backups`)}async readHistory({limit:e,offset:t}={}){let n=yr({limit:e,offset:t});return W(await fetch(T(`/git/history?${n.toString()}`)),`Failed to load git history`)}async readFileHistory({path:e,limit:t,offset:n}={}){let r=yr({limit:t,offset:n,path:e});return W(await fetch(T(`/git/file-history?${r.toString()}`)),`Failed to load file history`)}async readDiff({allowLargePatch:e=!1,metaOnly:t=!1,path:n=null,scope:r=`all`}={}){let i=yr({allowLargePatch:e?`true`:null,metaOnly:t?`true`:null,path:n,scope:r});return W(await fetch(T(`/git/diff?${i.toString()}`)),`Failed to load git diff`)}async readCommit({allowLargePatch:e=!1,hash:t,metaOnly:n=!1,path:r=null}={}){let i=yr({allowLargePatch:e?`true`:null,hash:t,metaOnly:n?`true`:null,path:r});return W(await fetch(T(`/git/commit?${i.toString()}`)),`Failed to load git commit`)}async readFileSnapshot({hash:e,path:t}={}){let n=yr({hash:e,path:t});return W(await fetch(T(`/git/file-snapshot?${n.toString()}`)),`Failed to load historical file preview`)}async stageFile({path:e,requestId:t=null}={}){return this.#e(`/git/stage`,{path:e},{requestId:t,fallbackError:`Failed to stage file`})}async unstageFile({path:e,requestId:t=null}={}){return this.#e(`/git/unstage`,{path:e},{requestId:t,fallbackError:`Failed to unstage file`})}async pushBranch({requestId:e=null}={}){return this.#e(`/git/push`,{},{requestId:e,fallbackError:`Failed to push branch`})}async pullBranch({requestId:e=null}={}){return this.#e(`/git/pull`,{},{requestId:e,fallbackError:`Failed to pull branch`})}async resetFile({path:e,requestId:t=null}={}){return this.#e(`/git/reset-file`,{path:e},{requestId:t,fallbackError:`Failed to reset file`})}async commit({message:e,requestId:t=null}={}){return this.#e(`/git/commit`,{message:e},{requestId:t,fallbackError:`Failed to commit staged changes`})}async#e(e,t,{fallbackError:n,requestId:r=null}={}){return W(await fetch(T(e),{body:JSON.stringify(t),headers:vr(r,{"Content-Type":`application/json`}),method:`POST`}),n)}},xr=new class{async renderSvg(e){let t=await fetch(T(`/plantuml/render`),{body:JSON.stringify({source:e}),headers:{"Content-Type":`application/json`},method:`POST`}),n=await t.json().catch(()=>null);if(!t.ok||!n?.ok||typeof n.svg!=`string`)throw Error(n?.error||`Failed to render PlantUML`);return n.svg}},Sr=`collabmd-active-tab-lock`,Cr=`collabmd-tab-id`,wr=`collabmd-tab-lock`,Tr=4e3;function Er(){return Date.now()}function Dr(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`tab-${Er()}-${Math.random().toString(36).slice(2,10)}`}function Or(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}var kr=class{constructor({heartbeatIntervalMs:e=Tr,onBlocked:t,onActivated:n,onStolen:r}={}){this.heartbeatIntervalMs=e,this.staleAfterMs=e*3,this.onBlocked=t,this.onActivated=n,this.onStolen=r,this.tabId=this.getOrCreateTabId(),this.channel=null,this.heartbeatTimer=null,this.isOwner=!1,this.handleStorageEvent=this.handleStorageEvent.bind(this),this.handlePageHide=this.handlePageHide.bind(this)}initialize(){window.addEventListener(`storage`,this.handleStorageEvent),window.addEventListener(`pagehide`,this.handlePageHide),`BroadcastChannel`in globalThis&&(this.channel=new BroadcastChannel(wr),this.channel.addEventListener(`message`,e=>{this.handleChannelMessage(e.data)}))}destroy(){this.release(),window.removeEventListener(`storage`,this.handleStorageEvent),window.removeEventListener(`pagehide`,this.handlePageHide),this.channel?.close(),this.channel=null}tryActivate({takeover:e=!1}={}){let t=this.readLock();return this.isFreshLock(t)&&t.tabId!==this.tabId&&!e?(this.isOwner=!1,this.stopHeartbeat(),this.onBlocked?.({reason:`active-elsewhere`,ownerTabId:t.tabId}),!1):(this.writeLock(),this.startHeartbeat(),this.isOwner=!0,this.channel?.postMessage({type:`claimed`,takeover:e,tabId:this.tabId}),this.onActivated?.({takeover:e}),!0)}release(){this.readLock()?.tabId===this.tabId&&(localStorage.removeItem(Sr),this.channel?.postMessage({type:`released`,tabId:this.tabId})),this.isOwner=!1,this.stopHeartbeat()}getOrCreateTabId(){try{let e=window.sessionStorage.getItem(Cr);if(e)return e;let t=Dr();return window.sessionStorage.setItem(Cr,t),t}catch{return Dr()}}readLock(){try{return Or(window.localStorage.getItem(Sr))}catch{return null}}isFreshLock(e){return!!(e&&typeof e.tabId==`string`&&Number.isFinite(e.updatedAt)&&Er()-e.updatedAt<this.staleAfterMs)}writeLock(){try{window.localStorage.setItem(Sr,JSON.stringify({tabId:this.tabId,updatedAt:Er()}))}catch{}}startHeartbeat(){this.stopHeartbeat(),this.writeLock(),this.heartbeatTimer=window.setInterval(()=>{if(!this.isOwner){this.stopHeartbeat();return}this.writeLock()},this.heartbeatIntervalMs)}stopHeartbeat(){this.heartbeatTimer&&=(window.clearInterval(this.heartbeatTimer),null)}handleStorageEvent(e){if(e.key!==Sr)return;let t=Or(e.newValue);this.handleExternalLockChange(t)}handleChannelMessage(e){!e||typeof e!=`object`||e.tabId===this.tabId||e.type===`claimed`&&this.handleExternalLockChange(this.readLock())}handleExternalLockChange(e){this.isOwner&&this.isFreshLock(e)&&e.tabId!==this.tabId&&(this.isOwner=!1,this.stopHeartbeat(),this.onStolen?.({ownerTabId:e.tabId}))}handlePageHide(){this.release()}},Ar=`__workspace__`;function jr(e){return!e?.path||!e?.type?null:e.nodeType===`directory`||e.type===`directory`?{children:[],name:e.name,path:e.path,type:`directory`}:{name:e.name,path:e.path,type:e.type}}function Mr(e=[]){return e.sort((e,t)=>e.type===`directory`&&t.type!==`directory`?-1:e.type!==`directory`&&t.type===`directory`?1:e.name.localeCompare(t.name,void 0,{sensitivity:`base`})),e.forEach(e=>{Array.isArray(e.children)&&Mr(e.children)}),e}function Nr(e){return e instanceof Map?e:new Map(Object.entries(e??{}))}function Pr(e=[],t=`asc`){let n=t===`desc`?-1:1;return[...e].sort((e,t)=>{let r=e.split(`/`).length-t.split(`/`).length;return r===0?e.localeCompare(t,void 0,{sensitivity:`base`})*n:r*n})}var Fr=class{constructor(){this.entriesByPath=new Map,this.nodesByPath=new Map,this.nodeParentPathByPath=new Map,this.roots=[]}reset(e){return this.entriesByPath=Nr(e),this.nodesByPath=new Map,this.nodeParentPathByPath=new Map,this.roots=[],this.entriesByPath.forEach(e=>{let t=jr(e);t&&this.nodesByPath.set(e.path,t)}),Pr(Array.from(this.nodesByPath.keys())).forEach(e=>{let t=this.nodesByPath.get(e);t&&this.attachNode(e,t,this.entriesByPath.get(e)?.parentPath||``)}),Mr(this.roots),this.roots}getTree(){return this.roots}applyMapChanges(e,t){let n=[],r=[];return e.forEach((e,t)=>{e.action===`delete`?n.push(t):r.push(t)}),Pr(n,`desc`).forEach(e=>{this.removeEntry(e)}),Pr(r).forEach(e=>{this.upsertEntry(e,t.get(e))}),Mr(this.roots),this.roots}removeEntry(e){let t=this.nodesByPath.get(e);if(!t){this.entriesByPath.delete(e),this.nodeParentPathByPath.delete(e);return}this.detachNode(e,t),this.nodesByPath.delete(e),this.entriesByPath.delete(e),this.nodeParentPathByPath.delete(e)}upsertEntry(e,t){if(!t?.path||!t?.type){this.removeEntry(e);return}let n=jr(t);if(!n){this.removeEntry(e);return}let r=this.nodesByPath.get(e);!r||r.type===`directory`!=(n.type===`directory`)?(r&&this.detachNode(e,r),r=n,this.nodesByPath.set(e,r)):(r.name=n.name,r.path=n.path,r.type=n.type,r.type===`directory`&&!Array.isArray(r.children)&&(r.children=[]),r.type!==`directory`&&Array.isArray(r.children)&&delete r.children),this.entriesByPath.set(e,t),this.attachNode(e,r,t.parentPath||``),r.type===`directory`&&this.rehomeChildren(e)}detachNode(e,t){let n=this.nodeParentPathByPath.get(e)||``,r=n?this.nodesByPath.get(n)?.children:this.roots,i=r?.indexOf?.(t)??-1;i>=0&&r.splice(i,1),this.nodeParentPathByPath.delete(e)}attachNode(e,t,n=``){let r=this.nodesByPath.get(n)?.type===`directory`?n:``,i=this.nodeParentPathByPath.get(e);if(i===r)return;i!==void 0&&this.detachNode(e,t);let a=r?this.nodesByPath.get(r)?.children:this.roots;a.includes(t)||a.push(t),this.nodeParentPathByPath.set(e,r)}rehomeChildren(e){this.entriesByPath.forEach((t,n)=>{if(t?.parentPath!==e)return;let r=this.nodesByPath.get(n);r&&this.attachNode(n,r,e)})}},Ir=class{constructor({onTreeChange:e=()=>{},onWorkspaceEvent:t=()=>{}}={}){this.onTreeChange=e,this.onWorkspaceEvent=t,this.ydoc=new oe,this.entries=this.ydoc.getMap(`entries`),this.events=this.ydoc.getArray(`events`),this.provider=null,this._didInitialSync=!1,this.seenEventIds=new Set,this.treeModel=new Fr,this.handleEntriesChange=e=>{!this._didInitialSync||!e||this.onTreeChange(this.treeModel.applyMapChanges(e.changes.keys,this.entries),{changedPaths:Array.from(e.changes.keys.keys()),reset:!1})},this.handleEventsChange=()=>{if(!this._didInitialSync){this.primeEventCache();return}this.events.toArray().forEach(e=>{let t=gt(e);!t||this.seenEventIds.has(t.id)||(this.seenEventIds.add(t.id),this.onWorkspaceEvent(t))})}}connect(){this.provider||(this._didInitialSync=!1,this.provider=new A(ne(),Ar,this.ydoc,{disableBc:!0,maxBackoffTime:5e3}),se(this.provider),this.entries.observe(this.handleEntriesChange),this.events.observe(this.handleEventsChange),this.provider.on(`sync`,e=>{!e||this._didInitialSync||(this._didInitialSync=!0,this.primeEventCache(),this.onTreeChange(this.treeModel.reset(this.entries.toJSON()),{changedPaths:[],reset:!0}))}))}primeEventCache(){this.events.toArray().forEach(e=>{let t=gt(e);t&&this.seenEventIds.add(t.id)})}disconnect(){this.entries.unobserve(this.handleEntriesChange),this.events.unobserve(this.handleEventsChange),this.provider?.disconnect(),this.provider?.destroy(),this.provider=null,this._didInitialSync=!1,this.seenEventIds.clear(),this.treeModel.reset(new Map)}destroy(){this.disconnect(),this.ydoc.destroy()}},Lr=class{constructor({documentRef:e=document,headerPanelElement:t=null,inlinePanelElement:n=null,loadBacklinks:r=null,onFileSelect:i,panelElement:a}){this.documentRef=e,this.headerPanel=t,this.panelRoot=a,this.inlinePanel=n,this.loadBacklinks=r,this.onFileSelect=i,this._expanded=!1,this._currentFile=null,this._displayMode=`dock`,this._fetchController=null,this._backlinks=[],this._pendingOutsidePointer=null;let o=this.panelRoot?.querySelector(`[data-backlinks-variant="dock"]`)??this.panelRoot;this.panels=[this._createPanelRef(o,this.panelRoot),this._createPanelRef(this.headerPanel,this.headerPanel),this._createPanelRef(this.inlinePanel,this.inlinePanel)].filter(Boolean),this.handleDocumentPointerDown=e=>{if(!this._expanded)return;let t=e?.target;if(t&&this.panels.some(({panel:e})=>e?.contains?.(t))){this._pendingOutsidePointer=null;return}e?.pointerType===`mouse`&&e?.button!==0||(this._pendingOutsidePointer={pointerId:e?.pointerId??`mouse`,startX:Number(e?.clientX??0),startY:Number(e?.clientY??0)})},this.handleDocumentPointerMove=e=>{if(!this._pendingOutsidePointer)return;let t=Math.abs(Number(e?.clientX??0)-this._pendingOutsidePointer.startX),n=Math.abs(Number(e?.clientY??0)-this._pendingOutsidePointer.startY);(t>10||n>10)&&(this._pendingOutsidePointer=null)},this.handleDocumentPointerEnd=e=>{if(!this._expanded||!this._pendingOutsidePointer)return;let t=e?.target;if(t&&this.panels.some(({panel:e})=>e?.contains?.(t))){this._pendingOutsidePointer=null;return}this._pendingOutsidePointer=null,this.close()},this.handleDocumentKeyDown=e=>{!this._expanded||e?.key!==`Escape`||(e.preventDefault?.(),this.close())},this.bindEvents()}bindEvents(){this.panels.forEach(e=>{e.header?.addEventListener(`click`,()=>{this._backlinks.length!==0&&(this._expanded=!this._expanded,this._pendingOutsidePointer=null,this._applyExpandState())})}),this.documentRef?.addEventListener?.(`pointerdown`,this.handleDocumentPointerDown),this.documentRef?.addEventListener?.(`pointermove`,this.handleDocumentPointerMove,{passive:!0}),this.documentRef?.addEventListener?.(`pointerup`,this.handleDocumentPointerEnd),this.documentRef?.addEventListener?.(`pointercancel`,this.handleDocumentPointerEnd),this.documentRef?.addEventListener?.(`keydown`,this.handleDocumentKeyDown)}async load(e){let t=e!==this._currentFile;if(this._currentFile=e,t&&(this._expanded=!1),!e){this._backlinks=[],this._render();return}this._fetchController?.abort(),this._fetchController=new AbortController;try{let t=await this.loadBacklinks(e,{signal:this._fetchController.signal});if(this._currentFile!==e)return;this._backlinks=t}catch(e){if(e.name===`AbortError`)return;console.warn(`[backlinks] Failed to load:`,e.message),this._backlinks=[]}this._render()}setDisplayMode(e=`dock`){let t=e===`header`?`header`:`dock`;this._displayMode!==t&&(this._displayMode=t,this._expanded=!1,this._pendingOutsidePointer=null,this._render())}clear(){this._currentFile=null,this._backlinks=[],this._expanded=!1,this._render()}close(){this._expanded&&(this._expanded=!1,this._pendingOutsidePointer=null,this._applyExpandState())}_createPanelRef(e,t=e){return e?{panel:e,header:e.querySelector(`.backlinks-header`),toggle:e.querySelector(`.backlinks-toggle`),countBadge:e.querySelector(`.backlinks-count`),body:e.querySelector(`.backlinks-body`),list:e.querySelector(`.backlinks-list`),root:t}:null}_render(){let e=this._backlinks.length,t=e===1?`Linked Mention`:`Linked Mentions`,n=!!this._currentFile&&e>0;n||(this._expanded=!1),this.panels.forEach(r=>{let i=n&&this._shouldShowPanel(r);r.root?.classList?.toggle?.(`hidden`,!i),r.countBadge.textContent=n?String(e):``,r.toggle.textContent=t,r.header?.classList.toggle(`backlinks-header-empty`,!i),i?this._renderList(r.list):r.list.innerHTML=``}),this._applyExpandState()}_shouldShowPanel(e){let t=e.panel?.getAttribute?.(`data-backlinks-variant`)??``;return t===`header`?this._displayMode===`header`:t===`dock`?this._displayMode===`dock`:!0}_renderList(e){if(!e)return;e.innerHTML=``;let t=this.documentRef?.createDocumentFragment?.(),n=t??e;this._backlinks.forEach(e=>{n.appendChild(this._createBacklinkItem(e))}),t&&e.appendChild(t)}_createBacklinkItem(e){let t=c(e.file.split(`/`).pop()),n=e.file.includes(`/`)?e.file.substring(0,e.file.lastIndexOf(`/`)):``,r=this.documentRef.createElement(`button`);r.type=`button`,r.className=`backlink-item`,r.addEventListener(`click`,()=>{this.close(),this.onFileSelect?.(e.file)});let i=this.documentRef.createElement(`div`);if(i.className=`backlink-file-name`,i.innerHTML=`
|
|
144
144
|
<svg class="backlink-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
145
145
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
146
146
|
<polyline points="14 2 14 8 20 8"/>
|
|
147
147
|
</svg>
|
|
148
148
|
<span>${b(t)}</span>
|
|
149
149
|
${n?`<span class="backlink-dir">${b(n)}</span>`:``}
|
|
150
|
-
`,r.appendChild(i),e.contexts.slice(0,3).forEach(e=>{let t=this.documentRef.createElement(`div`);t.className=`backlink-context`,t.textContent=e,r.appendChild(t)}),e.contexts.length>3){let t=this.documentRef.createElement(`div`);t.className=`backlink-context backlink-more`,t.textContent=`+${e.contexts.length-3} more`,r.appendChild(t)}return r}_applyExpandState(){this.panels.forEach(e=>{let t=this._expanded&&this._backlinks.length>0&&this._shouldShowPanel(e);e.panel.classList.toggle(`expanded`,t),e.header?.setAttribute(`aria-expanded`,String(t)),e.header?.setAttribute(`aria-disabled`,String(this._backlinks.length===0)),e.body?.setAttribute(`aria-hidden`,String(!t)),e.body?.toggleAttribute(`inert`,!t)})}};function
|
|
150
|
+
`,r.appendChild(i),e.contexts.slice(0,3).forEach(e=>{let t=this.documentRef.createElement(`div`);t.className=`backlink-context`,t.textContent=e,r.appendChild(t)}),e.contexts.length>3){let t=this.documentRef.createElement(`div`);t.className=`backlink-context backlink-more`,t.textContent=`+${e.contexts.length-3} more`,r.appendChild(t)}return r}_applyExpandState(){this.panels.forEach(e=>{let t=this._expanded&&this._backlinks.length>0&&this._shouldShowPanel(e);e.panel.classList.toggle(`expanded`,t),e.header?.setAttribute(`aria-expanded`,String(t)),e.header?.setAttribute(`aria-disabled`,String(this._backlinks.length===0)),e.body?.setAttribute(`aria-hidden`,String(!t)),e.body?.toggleAttribute(`inert`,!t)})}};function Rr(...e){let t=[];for(let n of e)if(n){if(Array.isArray(n)){let e=Rr(...n);e&&t.push(e);continue}if(typeof n==`object`){Object.entries(n).forEach(([e,n])=>{n&&t.push(e)});continue}t.push(String(n))}return t.join(` `)}function G(e={}){let{variant:t=`secondary`,size:n=`md`,toggle:r=!1,toolbar:i=!1,action:a=!1,wide:o=!1,surface:s=!1,pill:c=!1,hidden:l=!1,active:u=!1,extra:d=[]}=e;return Rr(`ui-button`,t&&`ui-button--${t}`,n!==`md`&&`ui-button--${n}`,{"ui-button--toggle":r,"ui-button--toolbar":i,"ui-button--action":a,"ui-button--wide":o,"ui-button--surface":s,"ui-button--pill":c,active:u,hidden:l},d)}function zr(e={}){let{toolbar:t=!1,action:n=!1,surface:r=!1,hidden:i=!1,extra:a=[]}=e;return Rr(`ui-icon-button`,{"ui-icon-button--toolbar":t,"ui-icon-button--action":n,"ui-icon-button--surface":r,hidden:i},a)}function K(e={}){return Rr(`ui-input`,e.extra??[])}function Br(e={}){return Rr(`ui-segmented-control`,{"ui-segmented-control--pill":e.pill,hidden:e.hidden},e.extra??[])}function q(e={}){return Rr(`ui-segmented-btn`,{active:e.active,hidden:e.hidden},e.extra??[])}function Vr(){return`base-${Math.random().toString(36).slice(2,10)}`}function Hr(e=``){return/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/iu.test(String(e??``).trim())}function Ur(e=``){return/^https?:\/\/.+\.(?:png|jpe?g|webp|gif|svg)(?:[?#].*)?$/iu.test(String(e??``).trim())}function Wr(e){return Object.prototype.toString.call(e)===`[object Object]`}function Gr(e=`and`){return{children:[],conjunction:e,type:`group`}}function Kr(e,t,n){let r=e.image||t.find(e=>[`cover`,`image`].includes(String(e.id??``).toLowerCase()))?.id||null;return r?n.cells[r]??null:null}function J(e){return String(e?.text??``)}function qr(e=``){return T(`/attachment?path=${encodeURIComponent(e)}`)}function Jr(e={}){if(e?.type===`image`&&e.path)return qr(e.path);if(e?.type===`link`){if(e.external&&Ur(e.url))return e.url;if(e.path&&o(e.path))return qr(e.path)}let t=J(e);return Ur(t)?t:o(t)?qr(t):``}function Yr(e={}){let t=e?.type||`string`;if(t===`empty`)return`<span class="bases-value bases-value-empty">—</span>`;if(t===`boolean`)return`<span class="bases-value bases-value-boolean">${e.value?`True`:`False`}</span>`;if(t===`image`&&e.path)return`<img class="bases-inline-image" src="${b(qr(e.path))}" alt="${b(J(e))}">`;if(t===`list`)return`<span class="bases-value-list">${(e.items??[]).map(e=>`<span class="bases-value-pill">${Yr(e)}</span>`).join(``)}</span>`;if(t===`link`){if(e.external&&e.url)return`<a class="bases-link" href="${b(e.url)}" target="_blank" rel="noopener noreferrer">${b(J(e))}</a>`;if(e.path)return`<button type="button" class="${b(G({variant:`secondary`,size:`compact`,pill:!0,extra:[`bases-link`,`bases-link-button`]}))}" data-base-open-file="${b(e.path)}">${b(J(e))}</button>`}return t===`file`&&e.path?`<button type="button" class="${b(G({variant:`secondary`,size:`compact`,pill:!0,extra:[`bases-link`,`bases-link-button`]}))}" data-base-open-file="${b(e.path)}">${b(J(e))}</button>`:`<span class="bases-value">${b(J(e))}</span>`}function Xr(e,t){let n=t?.cells?.[e.id]??null;return t?.path&&n&&n.type!==`empty`&&(e.id===`file.name`||e.id===`file.basename`)?`<button type="button" class="${b(G({variant:`secondary`,size:`compact`,pill:!0,extra:[`bases-link`,`bases-link-button`]}))}" data-base-open-file="${b(t.path)}">${b(J(n))}</button>`:Yr(n)}function Zr(e=[]){return!Array.isArray(e)||e.length===0?``:`<div class="bases-summaries">${e.map(e=>`<div class="bases-summary"><span class="bases-summary-label">${b(e.label)}</span><span class="bases-summary-value">${b(J(e.value))}</span></div>`).join(``)}</div>`}function Qr(e,t){return t.map(t=>`<section class="bases-group"><header class="bases-group-header"><h3>${b(t.label)}</h3>${Zr(t.summaries)}</header><div class="bases-table-shell"><table class="bases-table"><thead><tr>${e.map(e=>`<th>${b(e.label)}</th>`).join(``)}</tr></thead><tbody>${(t.rows??[]).map(t=>`<tr>${e.map(e=>`<td>${Xr(e,t)}</td>`).join(``)}</tr>`).join(``)}</tbody></table></div></section>`).join(``)}function $r(e,t){return t.map(t=>`<section class="bases-group"><header class="bases-group-header"><h3>${b(t.label)}</h3>${Zr(t.summaries)}</header><ul class="bases-list">${(t.rows??[]).map(t=>`<li class="bases-list-item">${e.map(e=>{let n=t.cells[e.id];return!n||n.type===`empty`?``:`<span class="bases-list-field"><strong>${b(e.label)}:</strong> ${Xr(e,t)}</span>`}).join(``)}</li>`).join(``)}</ul></section>`).join(``)}function ei(e,t,n){return t.map(t=>`<section class="bases-group"><header class="bases-group-header"><h3>${b(t.label)}</h3>${Zr(t.summaries)}</header><div class="bases-cards">${(t.rows??[]).map(t=>{let r=Kr(n,e,t),i=J(r),a=``;if(Hr(i))a=`<div class="bases-card-media bases-card-media-color" style="--bases-card-swatch:${b(i)}"></div>`;else{let e=Jr(r);e&&(a=`<img class="bases-card-media" src="${b(e)}" alt="${b(i)}">`)}return`<article class="bases-card">${a}<div class="bases-card-body">${e.map(e=>{let n=t.cells[e.id];return!n||n.type===`empty`?``:`<div class="bases-card-field"><div class="bases-card-label">${b(e.label)}</div><div class="bases-card-value">${Xr(e,t)}</div></div>`}).join(``)}</div></article>`}).join(``)}</div></section>`).join(``)}function ti(e){if(!e.view.supported)return`<div class="bases-unsupported">CollabMD parsed this view but does not render the <code>${b(e.view.type)}</code> layout yet.</div>`;switch(e.view.type){case`cards`:return ei(e.columns,e.groups,e.view);case`list`:return $r(e.columns,e.groups);default:return Qr(e.columns,e.groups)}}function ni(e){return(e.views??[]).map(t=>`<button type="button" class="${b(q({active:t.id===e.view.id,extra:`bases-view-tab`}))}" data-base-view="${b(t.id)}">${b(t.name)}</button>`).join(``)}function ri(e){return e?.meta??{}}function ii(e){return ri(e).availableProperties??[]}function ai(e){let t=ri(e).activeViewConfig?.order;return Array.isArray(t)&&t.length>0?[...t]:Array.isArray(e?.columns)?e.columns.map(e=>e.id).filter(Boolean):[]}function oi(e,t=``){return ii(e).find(e=>e.id===t)??null}function si(e,t=``){return oi(e,t)?.filterOperators??[`is`,`is not`,`contains`,`does not contain`,`is empty`,`is not empty`]}function Y(e){let t=ri(e).activeViewConfig??{};return{filters:t.filters??null,groupBy:t.groupBy??null,order:Array.isArray(t.order)?[...t.order]:[],sort:Array.isArray(t.sort)?t.sort.map(e=>({...e})):[]}}function ci(e){return!!(e?.payload?.path&&e?.payload?.sourcePath&&e.payload.path===e.payload.sourcePath)}function li(e,t,n,r){let i=n.ui?.openPanel===t,a=!!ri(r).editable;return`<button type="button" class="${b(G({variant:i?`primary`:`secondary`,pill:!0,extra:[`bases-toolbar-btn`,i?`is-active`:``]}))}" data-base-panel="${b(t)}"${a?``:` disabled`}>${b(e)}</button>`}function ui(e,t=``){if(!e||e.type!==`group`||!t)return e;let n=(e.children??[]).flatMap(e=>{if(e?.type===`group`){let n=ui(e,t);return n?[n]:[]}return e?.propertyId===t?[]:[e]});return{...e,children:n}}function di(e,t=``,n=e?.result){let r=ri(n).activeViewConfig?.filters??null,i=Z(r),a=t&&i?bi(ui(i,t),n):r;return JSON.stringify({filters:a,path:e?.payload?.path??``,source:e?.payload?.source??null,sourcePath:e?.payload?.sourcePath??``,view:n?.view?.id??e?.payload?.view??``})}function fi(e,t=``,n=e?.result){let r=e?.propertyValueOptions?.get(t)??null;return r&&r.cacheKey===di(e,t,n)?r.values??[]:[]}function pi(e,t){return[li(`Sort`,`sort`,t,e),li(`Filter`,`filter`,t,e),li(`Properties`,`properties`,t,e)].join(``)}function mi(e,{allowBlank:t=!1,selected:n=``}={}){let r=[];return t&&r.push(`<option value=""${n?``:` selected`}>Property</option>`),ii(e).forEach(e=>{r.push(`<option value="${b(e.id)}"${e.id===n?` selected`:``}>${b(e.label)}</option>`)}),r.join(``)}function hi(e){let t=Y(e),n=oi(e,t.groupBy?.property)?.sortDirections??[{id:`asc`,label:`A → Z`},{id:`desc`,label:`Z → A`}],r=t.sort??[];return`
|
|
151
151
|
<section class="bases-panel-card">
|
|
152
152
|
<div class="bases-panel-section">
|
|
153
153
|
<div class="bases-panel-title">Group by</div>
|
|
154
154
|
<div class="bases-sort-row">
|
|
155
155
|
<select class="${b(K({extra:`bases-select bases-sort-property`}))}" data-base-group-by-property>
|
|
156
|
-
${
|
|
156
|
+
${mi(e,{allowBlank:!0,selected:t.groupBy?.property??``})}
|
|
157
157
|
</select>
|
|
158
158
|
<select class="${b(K({extra:`bases-select bases-sort-direction`}))}" data-base-group-by-direction${t.groupBy?.property?``:` disabled`}>
|
|
159
159
|
${n.map(e=>`<option value="${b(e.id)}"${e.id===(t.groupBy?.direction??`asc`)?` selected`:``}>${b(e.label)}</option>`).join(``)}
|
|
@@ -164,10 +164,10 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
164
164
|
<div class="bases-panel-section">
|
|
165
165
|
<div class="bases-panel-title">Sort by</div>
|
|
166
166
|
<div class="bases-sort-list">
|
|
167
|
-
${r.map((t,n)=>{let i=
|
|
167
|
+
${r.map((t,n)=>{let i=oi(e,t.property)?.sortDirections??[{id:`asc`,label:`A → Z`},{id:`desc`,label:`Z → A`}];return`
|
|
168
168
|
<div class="bases-sort-row">
|
|
169
169
|
<select class="${b(K({extra:`bases-select bases-sort-property`}))}" data-base-sort-property="${n}">
|
|
170
|
-
${
|
|
170
|
+
${mi(e,{selected:t.property})}
|
|
171
171
|
</select>
|
|
172
172
|
<select class="${b(K({extra:`bases-select bases-sort-direction`}))}" data-base-sort-direction="${n}">
|
|
173
173
|
${i.map(e=>`<option value="${b(e.id)}"${e.id===t.direction?` selected`:``}>${b(e.label)}</option>`).join(``)}
|
|
@@ -181,7 +181,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
181
181
|
<button type="button" class="${b(G({variant:`secondary`,size:`compact`}))}" data-base-sort-add>Add sort</button>
|
|
182
182
|
</div>
|
|
183
183
|
</section>
|
|
184
|
-
`}function
|
|
184
|
+
`}function gi(e=[]){return e.join(`.`)}function X(e=``){return String(e??``).split(`.`).filter(e=>e!==``).map(e=>Number.parseInt(e,10)).filter(Number.isFinite)}function _i(e=``){return JSON.stringify(String(e??``))}function vi(e=``,t=`text`,n=`is`){let r=String(e??``).trim();return!r&&n!==`is`&&n!==`is not`?`""`:t===`boolean`?r===`false`?`false`:`true`:t===`number`&&Number.isFinite(Number(r))?String(Number(r)):_i(r)}function yi(e,t=null){if(!e?.propertyId||!e?.operator)return``;let n=e.propertyId,r=t?.valueType??`text`;switch(e.operator){case`contains`:return`${n}.contains(${vi(e.value,r,e.operator)})`;case`does not contain`:return`!${n}.contains(${vi(e.value,r,e.operator)})`;case`starts with`:return`${n}.startsWith(${vi(e.value,r,e.operator)})`;case`ends with`:return`${n}.endsWith(${vi(e.value,r,e.operator)})`;case`is`:return`${n} == ${vi(e.value,r,e.operator)}`;case`is not`:return`${n} != ${vi(e.value,r,e.operator)}`;case`>`:case`>=`:case`<`:case`<=`:return`${n} ${e.operator} ${vi(e.value,r,e.operator)}`;case`is empty`:return`${n}.isEmpty()`;case`is not empty`:return`!${n}.isEmpty()`;default:return``}}function bi(e,t){if(!e||e.type!==`group`)return null;let n=(e.children??[]).map(e=>e?.type===`group`?bi(e,t):yi(e,oi(t,e?.propertyId))).filter(Boolean);return n.length===0?null:e.conjunction===`not`?{not:n}:{[e.conjunction]:n}}function xi(e=``){let t=String(e??``).trim();return t?t===`true`||t===`false`?t:t===`null`?``:/^-?\d+(?:\.\d+)?$/u.test(t)?t:t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).replace(/\\(["'])/gu,`$1`):t:``}function Si(e=``){let t=String(e??``).trim(),n=[[/^!([A-Za-z0-9_.]+)\.isEmpty\(\)$/u,(e,t)=>({operator:`is not empty`,propertyId:t,type:`rule`,value:``})],[/^([A-Za-z0-9_.]+)\.isEmpty\(\)$/u,(e,t)=>({operator:`is empty`,propertyId:t,type:`rule`,value:``})],[/^!([A-Za-z0-9_.]+)\.contains\((.+)\)$/u,(e,t,n)=>({operator:`does not contain`,propertyId:t,type:`rule`,value:xi(n)})],[/^([A-Za-z0-9_.]+)\.contains\((.+)\)$/u,(e,t,n)=>({operator:`contains`,propertyId:t,type:`rule`,value:xi(n)})],[/^([A-Za-z0-9_.]+)\.startsWith\((.+)\)$/u,(e,t,n)=>({operator:`starts with`,propertyId:t,type:`rule`,value:xi(n)})],[/^([A-Za-z0-9_.]+)\.endsWith\((.+)\)$/u,(e,t,n)=>({operator:`ends with`,propertyId:t,type:`rule`,value:xi(n)})],[/^([A-Za-z0-9_.]+)\s*(==|!=|>=|<=|>|<)\s*(.+)$/u,(e,t,n,r)=>({operator:{"!=":`is not`,"==":`is`,"<":`<`,"<=":`<=`,">":`>`,">=":`>=`}[n]??n,propertyId:t,type:`rule`,value:xi(r)})]];for(let[e,r]of n){let n=t.match(e);if(n)return r(...n)}return null}function Z(e){if(!e)return Gr(`and`);if(typeof e==`string`){let t=Si(e);return t?{children:[t],conjunction:`and`,type:`group`}:null}if(!Wr(e))return null;if(Array.isArray(e.and)){let t=e.and.map(e=>Z(e)).flatMap(e=>e?.type===`group`&&e.conjunction===`and`&&e.children?.length===1&&e.children[0]?.type===`rule`?e.children:[e]);return t.every(Boolean)?{children:t,conjunction:`and`,type:`group`}:null}if(Array.isArray(e.or)){let t=e.or.map(e=>Z(e)).flatMap(e=>e?.type===`group`&&e.conjunction===`and`&&e.children?.length===1&&e.children[0]?.type===`rule`?e.children:[e]);return t.every(Boolean)?{children:t,conjunction:`or`,type:`group`}:null}if(e.not!=null){let t=(Array.isArray(e.not)?e.not:(()=>{let t=Z(e.not);return t?t.type===`group`&&t.conjunction===`or`?t.children??[]:[t]:[]})()).flatMap(e=>{let t=e?.type?e:Z(e);return t?t.type===`group`&&t.conjunction===`and`&&t.children?.length===1&&t.children[0]?.type===`rule`?t.children:[t]:[null]});return t.every(Boolean)?{children:t,conjunction:`not`,type:`group`}:null}return null}function Ci(e){return e?typeof e==`string`?e:JSON.stringify(e,null,2):``}function wi(e=``){let t=String(e??``).trim();return t?t.startsWith(`{`)||t.startsWith(`[`)?JSON.parse(t):t:null}function Ti(e,t=[]){let n=e;for(let e of t)n=n?.children?.[e];return n??null}function Ei(e,t=[],n){if(t.length===0)return n(e);let[r,...i]=t;return{...e,children:(e.children??[]).map((e,t)=>t===r?Ei(e,i,n):e)}}function Di(e,t=[]){if(t.length===0)return e;let n=t.slice(0,-1),r=t[t.length-1];return Ei(e,n,e=>({...e,children:(e.children??[]).filter((e,t)=>t!==r)}))}function Oi(e,t=[],n){return Ei(e,t,e=>({...e,children:[...e.children??[],n]}))}function ki(e,t=``){return mi(e,{allowBlank:!0,selected:t})}function Ai(e={}){return String(e?.text??e?.value??``).trim()}function ji(e,t){return e.ui.builderFilter??Z(Y(t).filters)??Gr(`and`)}function Mi(e,t,n,r){let i=gi(n),a=si(e,t.propertyId),o=String(t.value??``).trim().toLowerCase(),s=fi(r,t.propertyId,e).map(e=>({count:e?.count,text:Ai(e)})).filter((e,t,n)=>e.text&&n.findIndex(t=>t.text===e.text)===t),c=s.some(e=>e.text.toLowerCase()===o),l=s.filter(e=>!o||e.text.toLowerCase().includes(o)),u=!o||c?s:l.length>0?l:s,d=u.length>0&&![`is empty`,`is not empty`].includes(t.operator);return{encodedPath:i,operators:a,suggestionListId:`bases-filter-suggestions-${b(r.key)}-${b(i.replace(/\./g,`-`))}`,suggestionsEnabled:d,valueInputClasses:K({extra:d?`bases-filter-value bases-filter-value--suggestions`:`bases-filter-value`}),valueSuggestions:u,valueDisabled:[`is empty`,`is not empty`].includes(t.operator)}}function Ni(e,t=``){return e.suggestionsEnabled?`
|
|
185
185
|
<div class="bases-filter-suggestion-list" id="${e.suggestionListId}" role="listbox">
|
|
186
186
|
${e.valueSuggestions.slice(0,8).map(n=>`
|
|
187
187
|
<button
|
|
@@ -197,23 +197,23 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
197
197
|
</button>
|
|
198
198
|
`).join(``)}
|
|
199
199
|
</div>
|
|
200
|
-
`:``}function
|
|
200
|
+
`:``}function Pi(e,t,n,r){let i=Mi(e,t,n,r);return`
|
|
201
201
|
<div class="bases-filter-value-combobox${i.suggestionsEnabled?` has-suggestions`:``}">
|
|
202
202
|
<input class="${b(i.valueInputClasses)}" type="text" value="${b(t.value??``)}" data-base-filter-value="${b(i.encodedPath)}"${i.suggestionsEnabled?` aria-controls="${i.suggestionListId}" aria-haspopup="listbox" aria-autocomplete="list" autocomplete="off"`:``}${i.valueDisabled?` disabled`:``}>
|
|
203
|
-
${
|
|
203
|
+
${Ni(i,t.value??``)}
|
|
204
204
|
</div>
|
|
205
|
-
`}function
|
|
205
|
+
`}function Fi(e,t,n,r){let i=Mi(e,t,n,r);return`
|
|
206
206
|
<div class="bases-filter-row">
|
|
207
207
|
<select class="${b(K({extra:`bases-select bases-filter-property`}))}" data-base-filter-property="${b(i.encodedPath)}">
|
|
208
|
-
${
|
|
208
|
+
${ki(e,t.propertyId)}
|
|
209
209
|
</select>
|
|
210
210
|
<select class="${b(K({extra:`bases-select bases-filter-operator`}))}" data-base-filter-operator="${b(i.encodedPath)}">
|
|
211
211
|
${i.operators.map(e=>`<option value="${b(e)}"${e===t.operator?` selected`:``}>${b(e)}</option>`).join(``)}
|
|
212
212
|
</select>
|
|
213
|
-
${
|
|
213
|
+
${Pi(e,t,n,r)}
|
|
214
214
|
<button type="button" class="${b(G({variant:`secondary`,size:`compact`}))}" data-base-filter-remove="${b(i.encodedPath)}">Delete</button>
|
|
215
215
|
</div>
|
|
216
|
-
`}function
|
|
216
|
+
`}function Ii(e,t,n,{fallbackToFullRender:r=!0}={}){let i=Gi(e)?.querySelector?.(`[data-base-panel-slot]`)??null,a=gi(n),o=i?.querySelector?.(`[data-base-filter-value="${a}"]`)??null,s=o?.parentElement?.classList?.contains(`bases-filter-value-combobox`)?o.parentElement:null,c=Ti(ji(e,t),n);if(!o||!s||!c||c.type!==`rule`||typeof o.insertAdjacentHTML!=`function`)return r&&qi(e,t),!1;let l=Mi(t,c,n,e);return s.classList.toggle(`has-suggestions`,l.suggestionsEnabled),o.className=l.valueInputClasses,o.disabled=l.valueDisabled,o.value!==String(c.value??``)&&(o.value=String(c.value??``)),l.suggestionsEnabled?(o.setAttribute(`aria-controls`,l.suggestionListId),o.setAttribute(`aria-haspopup`,`listbox`),o.setAttribute(`aria-autocomplete`,`list`),o.setAttribute(`autocomplete`,`off`)):(o.removeAttribute(`aria-controls`),o.removeAttribute(`aria-haspopup`),o.removeAttribute(`aria-autocomplete`),o.removeAttribute(`autocomplete`)),s.querySelector(`.bases-filter-suggestion-list`)?.remove?.(),l.suggestionsEnabled&&o.insertAdjacentHTML(`afterend`,Ni(l,c.value??``)),!0}function Li(e,t,n=[]){if(e){if(e.type===`rule`){t(e,n);return}(e.children??[]).forEach((e,r)=>{Li(e,t,[...n,r])})}}function Ri(e,t,n,r,{isRoot:i=!1}={}){let a=gi(n);return`
|
|
217
217
|
<div class="bases-filter-group"${i?` data-base-filter-root`:``}>
|
|
218
218
|
<div class="bases-filter-group-header">
|
|
219
219
|
<select class="${b(K({extra:`bases-select bases-filter-conjunction`}))}" data-base-filter-conjunction="${b(a)}">
|
|
@@ -222,14 +222,14 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
222
222
|
${i?``:`<button type="button" class="${b(G({variant:`secondary`,size:`compact`}))}" data-base-filter-remove="${b(a)}">Delete group</button>`}
|
|
223
223
|
</div>
|
|
224
224
|
<div class="bases-filter-children">
|
|
225
|
-
${(t.children??[]).map((t,i)=>t?.type===`group`?
|
|
225
|
+
${(t.children??[]).map((t,i)=>t?.type===`group`?Ri(e,t,[...n,i],r):Fi(e,t,[...n,i],r)).join(``)}
|
|
226
226
|
</div>
|
|
227
227
|
<div class="bases-filter-actions-row">
|
|
228
228
|
<button type="button" class="${b(G({variant:`secondary`,size:`compact`}))}" data-base-filter-add-rule="${b(a)}">Add filter</button>
|
|
229
229
|
<button type="button" class="${b(G({variant:`secondary`,size:`compact`}))}" data-base-filter-add-group="${b(a)}">Add filter group</button>
|
|
230
230
|
</div>
|
|
231
231
|
</div>
|
|
232
|
-
`}function
|
|
232
|
+
`}function zi(e,t){let n=Y(e).filters,r=t.ui.builderFilter??Z(n);t.ui.builderFilter??(t.ui.builderFilter=r);let i=r?t.ui.filterMode??`builder`:`advanced`,a=t.ui.rawFilterText??Ci(n);return`
|
|
233
233
|
<section class="bases-panel-card">
|
|
234
234
|
<div class="bases-panel-title-row">
|
|
235
235
|
<div class="bases-panel-title">This view</div>
|
|
@@ -247,9 +247,9 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
247
247
|
<div class="bases-filter-actions-row">
|
|
248
248
|
<button type="button" class="${b(G({variant:`primary`,size:`compact`}))}" data-base-filter-save-advanced>Save filter</button>
|
|
249
249
|
</div>
|
|
250
|
-
`:
|
|
250
|
+
`:Ri(e,r??Gr(`and`),[],t,{isRoot:!0})}
|
|
251
251
|
</section>
|
|
252
|
-
`}function
|
|
252
|
+
`}function Bi(e,t){let n=String(t.ui.propertySearch??``).trim().toLowerCase(),r=new Set(ai(e)),i=ii(e).filter(e=>!n||e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n));return`
|
|
253
253
|
<section class="bases-panel-card">
|
|
254
254
|
<label class="bases-properties-search">
|
|
255
255
|
<input class="${b(K({extra:`bases-properties-search-input`}))}" type="search" value="${b(t.ui.propertySearch??``)}" placeholder="Find property" data-base-properties-search>
|
|
@@ -264,17 +264,17 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
264
264
|
`).join(``)}
|
|
265
265
|
</div>
|
|
266
266
|
</section>
|
|
267
|
-
`}function
|
|
267
|
+
`}function Vi(e){let t=e?.querySelector?.(`[data-base-properties-list]`)??null,n=e?.querySelector?.(`[data-base-properties-search]`)??null,r=typeof document<`u`?document.activeElement:null,i=null;if(n&&r===n){let e=typeof n.selectionStart==`number`?n.selectionStart:null;i={selectionEnd:typeof n.selectionEnd==`number`?n.selectionEnd:e,selectionStart:e,type:`properties-search`}}else if(r?.dataset?.baseFilterValue!=null){let t=String(r.dataset.baseFilterValue),n=e?.querySelector?.(`[data-base-filter-value="${t}"]`)??null;if(n&&r===n){let e=typeof n.selectionStart==`number`?n.selectionStart:null;i={path:t,selectionEnd:typeof n.selectionEnd==`number`?n.selectionEnd:e,selectionStart:e,type:`filter-value`}}}return{focusedControl:i,propertiesListScrollTop:t?t.scrollTop:null}}function Hi(e,t){if(t){if(t.propertiesListScrollTop!=null){let n=e?.querySelector?.(`[data-base-properties-list]`)??null;n&&(n.scrollTop=t.propertiesListScrollTop)}if(t.focusedControl?.type===`properties-search`){let n=e?.querySelector?.(`[data-base-properties-search]`)??null;n&&(n.focus?.(),typeof n.setSelectionRange==`function`&&t.focusedControl.selectionStart!=null&&n.setSelectionRange(t.focusedControl.selectionStart,t.focusedControl.selectionEnd??t.focusedControl.selectionStart));return}if(t.focusedControl?.type===`filter-value`&&t.focusedControl.path!=null){let n=e?.querySelector?.(`[data-base-filter-value="${t.focusedControl.path}"]`)??null;n&&(n.focus?.(),typeof n.setSelectionRange==`function`&&t.focusedControl.selectionStart!=null&&n.setSelectionRange(t.focusedControl.selectionStart,t.focusedControl.selectionEnd??t.focusedControl.selectionStart))}}}function Ui(e,t){if(!t.ui?.openPanel)return``;if(!ri(e).editable)return`<section class="bases-panel-card"><div class="bases-readonly-note">Inline base previews are read-only. Open the .base file to edit its sort, filter, and properties.</div></section>`;switch(t.ui.openPanel){case`filter`:return zi(e,t);case`properties`:return Bi(e,t);default:return hi(e)}}function Wi(e,t){return`
|
|
268
268
|
<section class="bases-shell" data-base-shell-key="${b(t.key)}">
|
|
269
269
|
<header class="bases-toolbar">
|
|
270
270
|
<div class="bases-toolbar-main">
|
|
271
|
-
<div class="${b(
|
|
272
|
-
${
|
|
271
|
+
<div class="${b(Br({pill:!0,extra:`bases-tabs`}))}" data-base-tabs>
|
|
272
|
+
${ni(e)}
|
|
273
273
|
</div>
|
|
274
274
|
<div class="bases-meta" data-base-meta>${b(String(e.totalRows??0))} results</div>
|
|
275
275
|
</div>
|
|
276
276
|
<div class="bases-toolbar-actions">
|
|
277
|
-
<div class="bases-toolbar-edit-actions" data-base-action-slot>${
|
|
277
|
+
<div class="bases-toolbar-edit-actions" data-base-action-slot>${pi(e,t)}</div>
|
|
278
278
|
<label class="bases-search-shell" aria-label="Search this base">
|
|
279
279
|
<svg class="bases-search-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
280
280
|
<circle cx="11" cy="11" r="7"></circle>
|
|
@@ -285,38 +285,38 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
285
285
|
<button type="button" class="${b(G({variant:`secondary`,pill:!0,extra:`bases-export-btn`}))}">Export CSV</button>
|
|
286
286
|
</div>
|
|
287
287
|
</header>
|
|
288
|
-
<div class="bases-panels" data-base-panel-slot>${
|
|
289
|
-
<div data-base-summary-slot>${
|
|
290
|
-
<div class="bases-content" data-base-content>${
|
|
288
|
+
<div class="bases-panels" data-base-panel-slot>${Ui(e,t)}</div>
|
|
289
|
+
<div data-base-summary-slot>${Zr(e.summaries)}</div>
|
|
290
|
+
<div class="bases-content" data-base-content>${ti(e)}</div>
|
|
291
291
|
</section>
|
|
292
|
-
`}function Vi(e){return e?.placeholder?.querySelector?e.placeholder.querySelector(`[data-base-shell-key="${e.key}"]`)??e.placeholder.querySelector(`.bases-shell`):null}function Hi(e){e?.classList&&(e.classList.add(`is-hydrated`),e.classList.remove(`diagram-preview-shell`))}function Ui(e,t){let n=Vi(e);if(!n?.querySelector){e.placeholder.innerHTML=Bi(t,e),Hi(e.placeholder);return}let r=n.querySelector(`[data-base-tabs]`);r&&(r.innerHTML=Qr(t));let i=n.querySelector(`[data-base-meta]`);i&&(i.textContent=`${String(t.totalRows??0)} results`);let a=n.querySelector(`[data-base-action-slot]`);a&&(a.innerHTML=li(t,e));let o=n.querySelector(`[data-base-panel-slot]`);if(o){let n=Li(o);o.innerHTML=zi(t,e),Ri(o,n)}let s=n.querySelector(`[data-base-summary-slot]`);s&&(s.innerHTML=qr(t.summaries));let c=n.querySelector(`[data-base-content]`);c&&(c.innerHTML=Zr(t));let l=n.querySelector(`.bases-search-input`);l&&l.value!==e.search&&(l.value=e.search)}function Wi(e,t=`base.csv`){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(n),0)}function Gi(e=``){let t=e.match(/filename\*=UTF-8''([^;]+)/iu);return t?decodeURIComponent(t[1]):e.match(/filename="([^"]+)"/iu)?.[1]||`base.csv`}var Ki=class{constructor({getActiveFilePath:e=()=>``,getSession:t=()=>null,onOpenFile:n,previewElement:r,replaceBaseSource:i=null,toastController:a,vaultApiClient:o}){this.getActiveFilePath=e,this.getSession=t,this.onOpenFile=n,this.previewElement=r,this.replaceBaseSource=i,this.toastController=a,this.vaultApiClient=o,this.entries=new Map,this.searchTimers=new Map,this.applyFilterSuggestion=(e,t,n)=>{this.updateBuilderFilter(e,e=>Si(e,t,e=>({...e,value:n})))},this.persistBuilderFilter=e=>{let t=Di(e,e.result);e.ui.builderFilter=t,this.updateViewConfig(e,n=>(n.filters=gi(t,e.result),n))},this.handlePointerDown=e=>{let t=e.target.closest(`[data-base-filter-suggestion]`);if(!t)return;let n=e.target.closest(`[data-base-shell-key]`),r=n?this.entries.get(n.dataset.baseShellKey||``):null;if(!r)return;e.preventDefault();let i=X(t.dataset.baseFilterSuggestion||``),a=t.dataset.baseFilterSuggestionValue||``;this.applyFilterSuggestion(r,i,a)},this.handleClick=e=>{let t=e.target.closest(`[data-base-open-file]`);if(t){e.preventDefault(),this.onOpenFile?.(t.dataset.baseOpenFile||``);return}let n=e.target.closest(`[data-base-shell-key]`),r=n?this.entries.get(n.dataset.baseShellKey||``):null;if(!r)return;let i=e.target.closest(`.bases-view-tab`);if(i){r.payload.view=i.dataset.baseView||``,r.ui.openPanel=``,this.renderEntry(r);return}let a=e.target.closest(`[data-base-panel]`);if(a){let e=a.dataset.basePanel||``;r.ui.openPanel=r.ui.openPanel===e?``:e,r.ui.rawFilterText=yi(Y(r.result).filters),Ui(r,r.result);return}if(e.target.closest(`.bases-export-btn`)){this.exportEntry(r);return}if(e.target.closest(`[data-base-sort-add]`)){this.updateViewConfig(r,e=>{let t=new Set((e.sort??[]).map(e=>e.property)),n=ei(r.result).find(e=>!t.has(e.id))?.id??`file.name`;return e.sort=[...e.sort??[],{direction:`asc`,property:n}],e});return}let o=e.target.closest(`[data-base-sort-delete]`);if(o){let e=Number.parseInt(o.dataset.baseSortDelete||``,10);this.updateViewConfig(r,t=>(t.sort=(t.sort??[]).filter((t,n)=>n!==e),t));return}let s=e.target.closest(`[data-base-sort-move]`);if(s){let[e,t]=String(s.dataset.baseSortMove||``).split(`:`),n=Number.parseInt(e,10);this.updateViewConfig(r,e=>{let r=[...e.sort??[]],i=t===`up`?n-1:n+1;return i<0||i>=r.length?e:([r[n],r[i]]=[r[i],r[n]],e.sort=r,e)});return}if(e.target.closest(`[data-base-clear-group-by]`)){this.updateViewConfig(r,e=>(e.groupBy=null,e));return}let c=e.target.closest(`[data-base-filter-mode]`);if(c){r.ui.filterMode=c.dataset.baseFilterMode||`builder`,r.ui.filterMode===`advanced`&&(r.ui.rawFilterText=yi(Y(r.result).filters),r.ui.builderFilter=null),Ui(r,r.result);return}if(e.target.closest(`[data-base-filter-save-advanced]`)){this.saveAdvancedFilter(r);return}let l=e.target.closest(`[data-base-filter-add-rule]`);if(l){let e=X(l.dataset.baseFilterAddRule||``);this.updateBuilderFilter(r,t=>wi(t,e,{operator:`is`,propertyId:ei(r.result)[0]?.id??`file.name`,type:`rule`,value:``}));return}let u=e.target.closest(`[data-base-filter-add-group]`);if(u){let e=X(u.dataset.baseFilterAddGroup||``);this.updateBuilderFilter(r,t=>wi(t,e,Vr(`and`)));return}let d=e.target.closest(`[data-base-filter-remove]`);if(d){let e=X(d.dataset.baseFilterRemove||``);this.updateBuilderFilter(r,t=>Ci(t,e));return}let f=e.target.closest(`[data-base-filter-suggestion]`);if(f){if(e.preventDefault?.(),e.detail!=null&&e.detail!==0)return;let t=X(f.dataset.baseFilterSuggestion||``),n=f.dataset.baseFilterSuggestionValue||``;this.applyFilterSuggestion(r,t,n)}},this.handleInput=e=>{let t=e.target.closest(`.bases-search-input`);if(t){let e=t.closest(`[data-base-shell-key]`),n=e?this.entries.get(e.dataset.baseShellKey||``):null;if(!n)return;n.search=t.value||``,clearTimeout(this.searchTimers.get(n.key)),this.searchTimers.set(n.key,setTimeout(()=>{n.payload.search=n.search,this.renderEntry(n)},180));return}let n=e.target.closest(`[data-base-properties-search]`);if(n){let e=n.closest(`[data-base-shell-key]`),t=e?this.entries.get(e.dataset.baseShellKey||``):null;if(!t)return;t.ui.propertySearch=n.value||``,Ui(t,t.result);return}let r=e.target.closest(`[data-base-filter-advanced]`);if(r){let e=r.closest(`[data-base-shell-key]`),t=e?this.entries.get(e.dataset.baseShellKey||``):null;if(!t)return;t.ui.rawFilterText=r.value||``;return}let i=e.target.closest(`[data-base-filter-value]`);if(i){let e=i.closest(`[data-base-shell-key]`),t=e?this.entries.get(e.dataset.baseShellKey||``):null;if(!t)return;let n=X(i.dataset.baseFilterValue||``),r=t.ui.builderFilter??Z(Y(t.result).filters)??Vr(`and`);t.ui.builderFilter=Si(r,n,e=>({...e,value:i.value||``})),Mi(t,t.result,n)}},this.handleChange=e=>{let t=e.target.closest(`[data-base-shell-key]`),n=t?this.entries.get(t.dataset.baseShellKey||``):null;if(!n)return;let r=e.target.closest(`[data-base-group-by-property]`);if(r){this.updateViewConfig(n,e=>(e.groupBy=r.value?{direction:e.groupBy?.direction??`asc`,property:r.value}:null,e));return}let i=e.target.closest(`[data-base-group-by-direction]`);if(i){this.updateViewConfig(n,e=>(e.groupBy=e.groupBy?.property?{direction:i.value||`asc`,property:e.groupBy.property}:null,e));return}let a=e.target.closest(`[data-base-sort-property]`);if(a){let e=Number.parseInt(a.dataset.baseSortProperty||``,10);this.updateViewConfig(n,t=>(t.sort=(t.sort??[]).map((t,n)=>n===e?{...t,property:a.value}:t),t));return}let o=e.target.closest(`[data-base-sort-direction]`);if(o){let e=Number.parseInt(o.dataset.baseSortDirection||``,10);this.updateViewConfig(n,t=>(t.sort=(t.sort??[]).map((t,n)=>n===e?{...t,direction:o.value||`asc`}:t),t));return}let s=e.target.closest(`[data-base-property-toggle]`);if(s){let e=s.dataset.basePropertyToggle||``;this.updateViewConfig(n,t=>{let r=t.order?.length>0?[...t.order]:ti(n.result),i=r.indexOf(e);return s.checked&&i===-1&&r.push(e),!s.checked&&i>=0&&r.splice(i,1),t.order=r,t});return}let c=e.target.closest(`[data-base-filter-conjunction]`);if(c){let e=X(c.dataset.baseFilterConjunction||``);this.updateBuilderFilter(n,t=>Si(t,e,e=>({...e,conjunction:c.value||`and`})));return}let l=e.target.closest(`[data-base-filter-property]`);if(l){let e=X(l.dataset.baseFilterProperty||``);(async()=>{await this.updateBuilderFilter(n,t=>Si(t,e,e=>{let t=ri(n.result,l.value)[0]??`is`;return{...e,operator:t,propertyId:l.value,value:``}})),await this.ensurePropertyValues(n,l.value)})();return}let u=e.target.closest(`[data-base-filter-operator]`);if(u){let e=X(u.dataset.baseFilterOperator||``);this.updateBuilderFilter(n,t=>Si(t,e,e=>({...e,operator:u.value||`is`})));return}e.target.closest(`[data-base-filter-value]`)&&this.persistBuilderFilter(n)},this.handleFocusIn=e=>{let t=e.target.closest(`[data-base-filter-value]`);if(!t)return;let n=t.closest(`[data-base-shell-key]`),r=n?this.entries.get(n.dataset.baseShellKey||``):null;if(!r)return;let i=X(t.dataset.baseFilterValue||``),a=Z(Y(r.result).filters),o=a?xi(a,i):null;o?.propertyId&&this.ensurePropertyValues(r,o.propertyId)},this.previewElement?.addEventListener(`pointerdown`,this.handlePointerDown),this.previewElement?.addEventListener(`click`,this.handleClick),this.previewElement?.addEventListener(`input`,this.handleInput),this.previewElement?.addEventListener(`change`,this.handleChange),this.previewElement?.addEventListener(`focusin`,this.handleFocusIn)}ensureEntryState(e){e.ui||={builderFilter:null,filterMode:`builder`,openPanel:``,propertySearch:``,rawFilterText:``},Object.prototype.hasOwnProperty.call(e.ui,`builderFilter`)||(e.ui.builderFilter=null),e.propertyValueOptions||=new Map}destroy(){this.previewElement?.removeEventListener(`pointerdown`,this.handlePointerDown),this.previewElement?.removeEventListener(`click`,this.handleClick),this.previewElement?.removeEventListener(`input`,this.handleInput),this.previewElement?.removeEventListener(`change`,this.handleChange),this.previewElement?.removeEventListener(`focusin`,this.handleFocusIn),this.searchTimers.forEach(e=>clearTimeout(e)),this.searchTimers.clear(),this.entries.clear()}reconcileEmbeds(e=this.previewElement){e&&Array.from(e.querySelectorAll(`.bases-embed-placeholder[data-base-key]`)).forEach(e=>{let t=e.dataset.baseKey||Lr(),n=this.entries.get(t),r={path:e.dataset.basePath||``,search:``,source:e.dataset.baseSource||null,sourcePath:e.dataset.baseSourcePath||``,view:e.dataset.baseView||``},i=n??{key:t,payload:r,placeholder:e,propertyValueOptions:new Map,requestVersion:0,result:null,search:``,ui:{builderFilter:null,filterMode:`builder`,openPanel:``,propertySearch:``,rawFilterText:``}};i.payload=r,i.placeholder=e,this.entries.set(t,i),this.renderEntry(i)})}async renderStandalone({filePath:e,renderHost:t,source:n=null}){let r=`standalone:${e}`,i=this.entries.get(r)??{key:r,payload:{path:e,search:``,source:n,sourcePath:e,view:``},placeholder:t,propertyValueOptions:new Map,requestVersion:0,result:null,search:``,ui:{builderFilter:null,filterMode:`builder`,openPanel:``,propertySearch:``,rawFilterText:``}};i.placeholder=t,i.payload.path=e,i.payload.source=typeof n==`string`?n:null,i.payload.sourcePath=e,this.entries.set(r,i),await this.renderEntry(i)}async renderEntry(e){if(this.ensureEntryState(e),!e?.placeholder?.isConnected)return;let t=(e.requestVersion??0)+1;e.requestVersion=t;let n=!!Vi(e);n||(e.placeholder.innerHTML=`<div class="preview-shell">Loading base…</div>`);try{let n=await this.vaultApiClient.queryBase({activeFilePath:this.getActiveFilePath?.()??``,...e.payload});if(t!==e.requestVersion||!e?.placeholder?.isConnected)return;e.result=n.result,e.ui.builderFilter=Z(Y(e.result).filters),e.ui.rawFilterText||(e.ui.rawFilterText=yi(Y(e.result).filters)),Ui(e,e.result)}catch(r){if(t!==e.requestVersion||!e?.placeholder?.isConnected)return;if(n){let t=Vi(e)?.querySelector?.(`[data-base-content]`)??null;if(t){t.innerHTML=`<div class="preview-shell">Failed to load base: ${b(r.message||`Unknown error`)}</div>`;return}}e.placeholder.innerHTML=`<div class="preview-shell">Failed to load base: ${b(r.message||`Unknown error`)}</div>`}}async exportEntry(e){this.ensureEntryState(e);try{let t=await this.vaultApiClient.exportBaseCsv({activeFilePath:this.getActiveFilePath?.()??``,...e.payload});Wi(t.blob,Gi(t.contentDisposition))}catch(e){this.toastController?.show?.(e.message||`Failed to export base CSV`)}}async ensurePropertyValues(e,t=``){if(this.ensureEntryState(e),!t)return;let n=si(e,t);if((e.propertyValueOptions.get(t)??null)?.cacheKey!==n)try{let r=await this.vaultApiClient.queryBasePropertyValues({activeFilePath:this.getActiveFilePath?.()??``,...e.payload,propertyId:t});if(e.propertyValueOptions.set(t,{cacheKey:n,values:r.result?.values??[]}),e.result&&e.ui.openPanel===`filter`){let n=!1;Ni(Di(e,e.result),(r,i)=>{r.propertyId===t&&(n=Mi(e,e.result,i,{fallbackToFullRender:!1})||n)}),n||Ui(e,e.result)}}catch{e.propertyValueOptions.set(t,{cacheKey:n,values:[]})}}async applyTransformedSource(e,t){if(this.ensureEntryState(e),ii(e)){e.payload.source=t.source,this.replaceBaseSource?.({path:e.payload.path,source:t.source});return}await this.vaultApiClient.writeFile({content:t.source,path:e.payload.path}),e.payload.source=null}async updateViewConfig(e,t){if(this.ensureEntryState(e),!e?.result||!$r(e.result).editable)return;let n=t(Y(e.result));try{let t=(await this.vaultApiClient.transformBase({activeFilePath:this.getActiveFilePath?.()??``,mutation:{config:n,type:`set-view-config`,view:e.result.view.id},...e.payload})).result;await this.applyTransformedSource(e,t),e.result=t.result,e.ui.rawFilterText=yi(Y(e.result).filters),Ui(e,e.result)}catch(e){this.toastController?.show?.(e.message||`Failed to update base`)}}async updateBuilderFilter(e,t){this.ensureEntryState(e);let n=t(e.ui.builderFilter??Z(Y(e.result).filters)??Vr(`and`));e.ui.builderFilter=n,await this.updateViewConfig(e,t=>(t.filters=gi(n,e.result),t))}async saveAdvancedFilter(e){this.ensureEntryState(e);try{let t=bi(e.ui.rawFilterText??``);e.ui.builderFilter=Z(t),await this.updateViewConfig(e,e=>(e.filters=t,e))}catch(e){this.toastController?.show?.(e.message||`Invalid advanced filter`)}}};function qi(e,t,n,r,i,a){return e?.(t,n,r,i,a)??a.renderToken(t,n,r)}function Ji(e=``){return`<p>${b(String(e??``)).replace(/\n/g,`<br>`)}</p>`}function Yi(){let e=t({breaks:!0,highlight(e,t){try{return t&&n.getLanguage(t)?n.highlight(e,{ignoreIllegals:!0,language:t}).value:n.highlightAuto(e).value}catch{return b(e)}},html:!1,linkify:!0,typographer:!0}),r=e.renderer.rules.link_open,i=e.renderer.rules.table_open,a=e.renderer.rules.table_close;return e.renderer.rules.link_open=(e,t,n,i,a)=>(e[t].attrSet(`target`,`_blank`),e[t].attrSet(`rel`,`noopener noreferrer`),qi(r,e,t,n,i,a)),e.renderer.rules.table_open=(e,t,n,r,a)=>`<div class="comment-markdown-table">${qi(i,e,t,n,r,a)}`,e.renderer.rules.table_close=(e,t,n,r,i)=>`${qi(a,e,t,n,r,i)}</div>`,e}var Xi=Yi();function Zi(e=``){let t=String(e??``);try{return Xi.render(t)}catch{return Ji(t)}}var Qi=Object.freeze([`👍`,`❤️`,`🎉`,`👀`,`🚀`]),$i=Object.freeze([`😂`,`🔥`,`✅`,`🙏`,`💡`,`🤔`,`👏`,`😄`,`🎯`,`🙌`]);function ea(e,t,n){return Math.min(Math.max(e,t),n)}function ta(e=[]){return[...e].sort((e,t)=>(e.anchor?.startLine??0)-(t.anchor?.startLine??0)||e.createdAt-t.createdAt)}function na(e){return e?.anchorKind||e?.kind||`line`}function ra(e){return na(e)===`text`&&Number.isFinite(e?.startIndex)&&Number.isFinite(e?.endIndex)&&e.endIndex>e.startIndex}function ia(e,t){return e===t?!0:!e||!t?!1:na(e)===na(t)&&(e.startIndex??null)===(t.startIndex??null)&&(e.endIndex??null)===(t.endIndex??null)&&(e.startLine??null)===(t.startLine??null)&&(e.endLine??null)===(t.endLine??null)&&(e.anchorQuote??e.quote??``)===(t.anchorQuote??t.quote??``)}function aa(e){return e?((e.kind||e.anchorKind)===`text`&&e.quote,e.startLine===e.endLine?`Line ${e.startLine}`:`Lines ${e.startLine}-${e.endLine}`):`No source anchor`}function oa(e={}){return[e.kind||e.anchorKind||`line`,e.startLine??0,e.endLine??0,e.quote||``].join(`::`)}function sa(e){return e&&!e.querySelector(`[data-source-line]`)}function ca(e){let t=Number.parseInt(e||``,10);return Number.isFinite(t)?t:null}function la(e=[]){return e.reduce((e,t)=>e?(t?.createdAt??0)>=(e?.createdAt??0)?t:e:t,null)}function ua(e){return e?.threads?.reduce((e,t)=>{let n=la(t?.messages??[]);return n&&(n.createdAt??0)>=(e?.createdAt??0)?n:e},null)}function da(e,t=`comment-markdown`){let n=document.createElement(`div`);return n.className=t,n.innerHTML=Zi(e),n}function fa(e,t){return!!(t&&e?.users?.some(e=>e?.userId===t))}function pa(e){return String(Array.isArray(e?.users)?e.users.length:0)}function ma(e,t,n){return e?.threadId===t&&e?.messageId===n}function ha(e){let t=e?.querySelector?.(`.comment-reaction-picker`),n=t?.closest?.(`.comment-reaction-picker-wrap`),r=e?.querySelector?.(`.comment-card-scroll`);return!(t instanceof HTMLElement)||!(n instanceof HTMLElement)||!(r instanceof HTMLElement)?null:{picker:t,scroll:r,wrap:n}}function ga(e,t){let n=ca(e?.getAttribute?.(`data-source-line`)),r=ca(e?.getAttribute?.(`data-source-line-end`))??n;return!n||!r||!t?!1:t.startLine<=r&&t.endLine>=n}function _a(e){let t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=``,r=[],i=!0;for(;t.nextNode();){let e=t.currentNode,a=e.textContent||``;for(let t=0;t<a.length;t+=1){let o=a[t];if(/\s/.test(o)){if(i)continue;n+=` `,r.push({node:e,offset:t}),i=!0;continue}n+=o,r.push({node:e,offset:t}),i=!1}}for(;n.endsWith(` `);)n=n.slice(0,-1),r.pop();return{map:r,normalized:n}}function va(e,t){let n=xe(t);if(!e||!n)return null;let r=_a(e);if(!r.normalized)return null;let i=r.normalized.indexOf(n);if(i<0||r.normalized.indexOf(n,i+1)>=0)return null;let a=r.map[i],o=r.map[i+n.length-1];if(!a||!o)return null;let s=document.createRange();return s.setStart(a.node,a.offset),s.setEnd(o.node,o.offset+1),s}function ya(e,t){return{bottom:e.bottom-t.top,height:e.height,left:e.left-t.left,right:e.right-t.left,top:e.top-t.top,width:e.width}}function ba(e=[]){if(!Array.isArray(e)||e.length===0)return null;let t=Math.min(...e.map(e=>e.left)),n=Math.min(...e.map(e=>e.top)),r=Math.max(...e.map(e=>e.right)),i=Math.max(...e.map(e=>e.bottom));return{bottom:i,height:i-n,left:t,right:r,top:n,width:r-t}}function xa(e,t,n){return n?e>=n.left&&e<=n.right&&t>=n.top&&t<=n.bottom:!1}function Sa(e=[]){return[...new Set(e.filter(Boolean))].sort()}function Ca(e=[]){return Sa(e).join(` `)}function wa(e){let t=document.createDocumentFragment(),n=document.createElement(`span`);if(n.className=`comment-marker-icon`,n.setAttribute(`aria-hidden`,`true`),n.innerHTML=`
|
|
292
|
+
`}function Gi(e){return e?.placeholder?.querySelector?e.placeholder.querySelector(`[data-base-shell-key="${e.key}"]`)??e.placeholder.querySelector(`.bases-shell`):null}function Ki(e){e?.classList&&(e.classList.add(`is-hydrated`),e.classList.remove(`diagram-preview-shell`))}function qi(e,t){let n=Gi(e);if(!n?.querySelector){e.placeholder.innerHTML=Wi(t,e),Ki(e.placeholder);return}let r=n.querySelector(`[data-base-tabs]`);r&&(r.innerHTML=ni(t));let i=n.querySelector(`[data-base-meta]`);i&&(i.textContent=`${String(t.totalRows??0)} results`);let a=n.querySelector(`[data-base-action-slot]`);a&&(a.innerHTML=pi(t,e));let o=n.querySelector(`[data-base-panel-slot]`);if(o){let n=Vi(o);o.innerHTML=Ui(t,e),Hi(o,n)}let s=n.querySelector(`[data-base-summary-slot]`);s&&(s.innerHTML=Zr(t.summaries));let c=n.querySelector(`[data-base-content]`);c&&(c.innerHTML=ti(t));let l=n.querySelector(`.bases-search-input`);l&&l.value!==e.search&&(l.value=e.search)}function Ji(e,t=`base.csv`){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(n),0)}function Yi(e=``){let t=e.match(/filename\*=UTF-8''([^;]+)/iu);return t?decodeURIComponent(t[1]):e.match(/filename="([^"]+)"/iu)?.[1]||`base.csv`}var Xi=class{constructor({getActiveFilePath:e=()=>``,getSession:t=()=>null,onOpenFile:n,previewElement:r,replaceBaseSource:i=null,toastController:a,vaultApiClient:o}){this.getActiveFilePath=e,this.getSession=t,this.onOpenFile=n,this.previewElement=r,this.replaceBaseSource=i,this.toastController=a,this.vaultApiClient=o,this.entries=new Map,this.searchTimers=new Map,this.applyFilterSuggestion=(e,t,n)=>{this.updateBuilderFilter(e,e=>Ei(e,t,e=>({...e,value:n})))},this.persistBuilderFilter=e=>{let t=ji(e,e.result);e.ui.builderFilter=t,this.updateViewConfig(e,n=>(n.filters=bi(t,e.result),n))},this.handlePointerDown=e=>{let t=e.target.closest(`[data-base-filter-suggestion]`);if(!t)return;let n=e.target.closest(`[data-base-shell-key]`),r=n?this.entries.get(n.dataset.baseShellKey||``):null;if(!r)return;e.preventDefault();let i=X(t.dataset.baseFilterSuggestion||``),a=t.dataset.baseFilterSuggestionValue||``;this.applyFilterSuggestion(r,i,a)},this.handleClick=e=>{let t=e.target.closest(`[data-base-open-file]`);if(t){e.preventDefault(),this.onOpenFile?.(t.dataset.baseOpenFile||``);return}let n=e.target.closest(`[data-base-shell-key]`),r=n?this.entries.get(n.dataset.baseShellKey||``):null;if(!r)return;let i=e.target.closest(`.bases-view-tab`);if(i){r.payload.view=i.dataset.baseView||``,r.ui.openPanel=``,this.renderEntry(r);return}let a=e.target.closest(`[data-base-panel]`);if(a){let e=a.dataset.basePanel||``;r.ui.openPanel=r.ui.openPanel===e?``:e,r.ui.rawFilterText=Ci(Y(r.result).filters),qi(r,r.result);return}if(e.target.closest(`.bases-export-btn`)){this.exportEntry(r);return}if(e.target.closest(`[data-base-sort-add]`)){this.updateViewConfig(r,e=>{let t=new Set((e.sort??[]).map(e=>e.property)),n=ii(r.result).find(e=>!t.has(e.id))?.id??`file.name`;return e.sort=[...e.sort??[],{direction:`asc`,property:n}],e});return}let o=e.target.closest(`[data-base-sort-delete]`);if(o){let e=Number.parseInt(o.dataset.baseSortDelete||``,10);this.updateViewConfig(r,t=>(t.sort=(t.sort??[]).filter((t,n)=>n!==e),t));return}let s=e.target.closest(`[data-base-sort-move]`);if(s){let[e,t]=String(s.dataset.baseSortMove||``).split(`:`),n=Number.parseInt(e,10);this.updateViewConfig(r,e=>{let r=[...e.sort??[]],i=t===`up`?n-1:n+1;return i<0||i>=r.length?e:([r[n],r[i]]=[r[i],r[n]],e.sort=r,e)});return}if(e.target.closest(`[data-base-clear-group-by]`)){this.updateViewConfig(r,e=>(e.groupBy=null,e));return}let c=e.target.closest(`[data-base-filter-mode]`);if(c){r.ui.filterMode=c.dataset.baseFilterMode||`builder`,r.ui.filterMode===`advanced`&&(r.ui.rawFilterText=Ci(Y(r.result).filters),r.ui.builderFilter=null),qi(r,r.result);return}if(e.target.closest(`[data-base-filter-save-advanced]`)){this.saveAdvancedFilter(r);return}let l=e.target.closest(`[data-base-filter-add-rule]`);if(l){let e=X(l.dataset.baseFilterAddRule||``);this.updateBuilderFilter(r,t=>Oi(t,e,{operator:`is`,propertyId:ii(r.result)[0]?.id??`file.name`,type:`rule`,value:``}));return}let u=e.target.closest(`[data-base-filter-add-group]`);if(u){let e=X(u.dataset.baseFilterAddGroup||``);this.updateBuilderFilter(r,t=>Oi(t,e,Gr(`and`)));return}let d=e.target.closest(`[data-base-filter-remove]`);if(d){let e=X(d.dataset.baseFilterRemove||``);this.updateBuilderFilter(r,t=>Di(t,e));return}let f=e.target.closest(`[data-base-filter-suggestion]`);if(f){if(e.preventDefault?.(),e.detail!=null&&e.detail!==0)return;let t=X(f.dataset.baseFilterSuggestion||``),n=f.dataset.baseFilterSuggestionValue||``;this.applyFilterSuggestion(r,t,n)}},this.handleInput=e=>{let t=e.target.closest(`.bases-search-input`);if(t){let e=t.closest(`[data-base-shell-key]`),n=e?this.entries.get(e.dataset.baseShellKey||``):null;if(!n)return;n.search=t.value||``,clearTimeout(this.searchTimers.get(n.key)),this.searchTimers.set(n.key,setTimeout(()=>{n.payload.search=n.search,this.renderEntry(n)},180));return}let n=e.target.closest(`[data-base-properties-search]`);if(n){let e=n.closest(`[data-base-shell-key]`),t=e?this.entries.get(e.dataset.baseShellKey||``):null;if(!t)return;t.ui.propertySearch=n.value||``,qi(t,t.result);return}let r=e.target.closest(`[data-base-filter-advanced]`);if(r){let e=r.closest(`[data-base-shell-key]`),t=e?this.entries.get(e.dataset.baseShellKey||``):null;if(!t)return;t.ui.rawFilterText=r.value||``;return}let i=e.target.closest(`[data-base-filter-value]`);if(i){let e=i.closest(`[data-base-shell-key]`),t=e?this.entries.get(e.dataset.baseShellKey||``):null;if(!t)return;let n=X(i.dataset.baseFilterValue||``),r=t.ui.builderFilter??Z(Y(t.result).filters)??Gr(`and`);t.ui.builderFilter=Ei(r,n,e=>({...e,value:i.value||``})),Ii(t,t.result,n)}},this.handleChange=e=>{let t=e.target.closest(`[data-base-shell-key]`),n=t?this.entries.get(t.dataset.baseShellKey||``):null;if(!n)return;let r=e.target.closest(`[data-base-group-by-property]`);if(r){this.updateViewConfig(n,e=>(e.groupBy=r.value?{direction:e.groupBy?.direction??`asc`,property:r.value}:null,e));return}let i=e.target.closest(`[data-base-group-by-direction]`);if(i){this.updateViewConfig(n,e=>(e.groupBy=e.groupBy?.property?{direction:i.value||`asc`,property:e.groupBy.property}:null,e));return}let a=e.target.closest(`[data-base-sort-property]`);if(a){let e=Number.parseInt(a.dataset.baseSortProperty||``,10);this.updateViewConfig(n,t=>(t.sort=(t.sort??[]).map((t,n)=>n===e?{...t,property:a.value}:t),t));return}let o=e.target.closest(`[data-base-sort-direction]`);if(o){let e=Number.parseInt(o.dataset.baseSortDirection||``,10);this.updateViewConfig(n,t=>(t.sort=(t.sort??[]).map((t,n)=>n===e?{...t,direction:o.value||`asc`}:t),t));return}let s=e.target.closest(`[data-base-property-toggle]`);if(s){let e=s.dataset.basePropertyToggle||``;this.updateViewConfig(n,t=>{let r=t.order?.length>0?[...t.order]:ai(n.result),i=r.indexOf(e);return s.checked&&i===-1&&r.push(e),!s.checked&&i>=0&&r.splice(i,1),t.order=r,t});return}let c=e.target.closest(`[data-base-filter-conjunction]`);if(c){let e=X(c.dataset.baseFilterConjunction||``);this.updateBuilderFilter(n,t=>Ei(t,e,e=>({...e,conjunction:c.value||`and`})));return}let l=e.target.closest(`[data-base-filter-property]`);if(l){let e=X(l.dataset.baseFilterProperty||``);(async()=>{await this.updateBuilderFilter(n,t=>Ei(t,e,e=>{let t=si(n.result,l.value)[0]??`is`;return{...e,operator:t,propertyId:l.value,value:``}})),await this.ensurePropertyValues(n,l.value)})();return}let u=e.target.closest(`[data-base-filter-operator]`);if(u){let e=X(u.dataset.baseFilterOperator||``);this.updateBuilderFilter(n,t=>Ei(t,e,e=>({...e,operator:u.value||`is`})));return}e.target.closest(`[data-base-filter-value]`)&&this.persistBuilderFilter(n)},this.handleFocusIn=e=>{let t=e.target.closest(`[data-base-filter-value]`);if(!t)return;let n=t.closest(`[data-base-shell-key]`),r=n?this.entries.get(n.dataset.baseShellKey||``):null;if(!r)return;let i=X(t.dataset.baseFilterValue||``),a=Z(Y(r.result).filters),o=a?Ti(a,i):null;o?.propertyId&&this.ensurePropertyValues(r,o.propertyId)},this.previewElement?.addEventListener(`pointerdown`,this.handlePointerDown),this.previewElement?.addEventListener(`click`,this.handleClick),this.previewElement?.addEventListener(`input`,this.handleInput),this.previewElement?.addEventListener(`change`,this.handleChange),this.previewElement?.addEventListener(`focusin`,this.handleFocusIn)}ensureEntryState(e){e.ui||={builderFilter:null,filterMode:`builder`,openPanel:``,propertySearch:``,rawFilterText:``},Object.prototype.hasOwnProperty.call(e.ui,`builderFilter`)||(e.ui.builderFilter=null),e.propertyValueOptions||=new Map}destroy(){this.previewElement?.removeEventListener(`pointerdown`,this.handlePointerDown),this.previewElement?.removeEventListener(`click`,this.handleClick),this.previewElement?.removeEventListener(`input`,this.handleInput),this.previewElement?.removeEventListener(`change`,this.handleChange),this.previewElement?.removeEventListener(`focusin`,this.handleFocusIn),this.searchTimers.forEach(e=>clearTimeout(e)),this.searchTimers.clear(),this.entries.clear()}reconcileEmbeds(e=this.previewElement){e&&Array.from(e.querySelectorAll(`.bases-embed-placeholder[data-base-key]`)).forEach(e=>{let t=e.dataset.baseKey||Vr(),n=this.entries.get(t),r={path:e.dataset.basePath||``,search:``,source:e.dataset.baseSource||null,sourcePath:e.dataset.baseSourcePath||``,view:e.dataset.baseView||``},i=n??{key:t,payload:r,placeholder:e,propertyValueOptions:new Map,requestVersion:0,result:null,search:``,ui:{builderFilter:null,filterMode:`builder`,openPanel:``,propertySearch:``,rawFilterText:``}};i.payload=r,i.placeholder=e,this.entries.set(t,i),this.renderEntry(i)})}async renderStandalone({filePath:e,renderHost:t,source:n=null}){let r=`standalone:${e}`,i=this.entries.get(r)??{key:r,payload:{path:e,search:``,source:n,sourcePath:e,view:``},placeholder:t,propertyValueOptions:new Map,requestVersion:0,result:null,search:``,ui:{builderFilter:null,filterMode:`builder`,openPanel:``,propertySearch:``,rawFilterText:``}};i.placeholder=t,i.payload.path=e,i.payload.source=typeof n==`string`?n:null,i.payload.sourcePath=e,this.entries.set(r,i),await this.renderEntry(i)}async renderEntry(e){if(this.ensureEntryState(e),!e?.placeholder?.isConnected)return;let t=(e.requestVersion??0)+1;e.requestVersion=t;let n=!!Gi(e);n||(e.placeholder.innerHTML=`<div class="preview-shell">Loading base…</div>`);try{let n=await this.vaultApiClient.queryBase({activeFilePath:this.getActiveFilePath?.()??``,...e.payload});if(t!==e.requestVersion||!e?.placeholder?.isConnected)return;e.result=n.result,e.ui.builderFilter=Z(Y(e.result).filters),e.ui.rawFilterText||(e.ui.rawFilterText=Ci(Y(e.result).filters)),qi(e,e.result)}catch(r){if(t!==e.requestVersion||!e?.placeholder?.isConnected)return;if(n){let t=Gi(e)?.querySelector?.(`[data-base-content]`)??null;if(t){t.innerHTML=`<div class="preview-shell">Failed to load base: ${b(r.message||`Unknown error`)}</div>`;return}}e.placeholder.innerHTML=`<div class="preview-shell">Failed to load base: ${b(r.message||`Unknown error`)}</div>`}}async exportEntry(e){this.ensureEntryState(e);try{let t=await this.vaultApiClient.exportBaseCsv({activeFilePath:this.getActiveFilePath?.()??``,...e.payload});Ji(t.blob,Yi(t.contentDisposition))}catch(e){this.toastController?.show?.(e.message||`Failed to export base CSV`)}}async ensurePropertyValues(e,t=``){if(this.ensureEntryState(e),!t)return;let n=di(e,t);if((e.propertyValueOptions.get(t)??null)?.cacheKey!==n)try{let r=await this.vaultApiClient.queryBasePropertyValues({activeFilePath:this.getActiveFilePath?.()??``,...e.payload,propertyId:t});if(e.propertyValueOptions.set(t,{cacheKey:n,values:r.result?.values??[]}),e.result&&e.ui.openPanel===`filter`){let n=!1;Li(ji(e,e.result),(r,i)=>{r.propertyId===t&&(n=Ii(e,e.result,i,{fallbackToFullRender:!1})||n)}),n||qi(e,e.result)}}catch{e.propertyValueOptions.set(t,{cacheKey:n,values:[]})}}async applyTransformedSource(e,t){if(this.ensureEntryState(e),ci(e)){e.payload.source=t.source,this.replaceBaseSource?.({path:e.payload.path,source:t.source});return}await this.vaultApiClient.writeFile({content:t.source,path:e.payload.path}),e.payload.source=null}async updateViewConfig(e,t){if(this.ensureEntryState(e),!e?.result||!ri(e.result).editable)return;let n=t(Y(e.result));try{let t=(await this.vaultApiClient.transformBase({activeFilePath:this.getActiveFilePath?.()??``,mutation:{config:n,type:`set-view-config`,view:e.result.view.id},...e.payload})).result;await this.applyTransformedSource(e,t),e.result=t.result,e.ui.rawFilterText=Ci(Y(e.result).filters),qi(e,e.result)}catch(e){this.toastController?.show?.(e.message||`Failed to update base`)}}async updateBuilderFilter(e,t){this.ensureEntryState(e);let n=t(e.ui.builderFilter??Z(Y(e.result).filters)??Gr(`and`));e.ui.builderFilter=n,await this.updateViewConfig(e,t=>(t.filters=bi(n,e.result),t))}async saveAdvancedFilter(e){this.ensureEntryState(e);try{let t=wi(e.ui.rawFilterText??``);e.ui.builderFilter=Z(t),await this.updateViewConfig(e,e=>(e.filters=t,e))}catch(e){this.toastController?.show?.(e.message||`Invalid advanced filter`)}}};function Zi(e,t,n,r,i,a){return e?.(t,n,r,i,a)??a.renderToken(t,n,r)}function Qi(e=``){return`<p>${b(String(e??``)).replace(/\n/g,`<br>`)}</p>`}function $i(){let e=t({breaks:!0,highlight(e,t){try{return t&&n.getLanguage(t)?n.highlight(e,{ignoreIllegals:!0,language:t}).value:n.highlightAuto(e).value}catch{return b(e)}},html:!1,linkify:!0,typographer:!0}),r=e.renderer.rules.link_open,i=e.renderer.rules.table_open,a=e.renderer.rules.table_close;return e.renderer.rules.link_open=(e,t,n,i,a)=>(e[t].attrSet(`target`,`_blank`),e[t].attrSet(`rel`,`noopener noreferrer`),Zi(r,e,t,n,i,a)),e.renderer.rules.table_open=(e,t,n,r,a)=>`<div class="comment-markdown-table">${Zi(i,e,t,n,r,a)}`,e.renderer.rules.table_close=(e,t,n,r,i)=>`${Zi(a,e,t,n,r,i)}</div>`,e}var ea=$i();function ta(e=``){let t=String(e??``);try{return ea.render(t)}catch{return Qi(t)}}var na=Object.freeze([`👍`,`❤️`,`🎉`,`👀`,`🚀`]),ra=Object.freeze([`😂`,`🔥`,`✅`,`🙏`,`💡`,`🤔`,`👏`,`😄`,`🎯`,`🙌`]);function ia(e,t,n){return Math.min(Math.max(e,t),n)}function aa(e=[]){return[...e].sort((e,t)=>(e.anchor?.startLine??0)-(t.anchor?.startLine??0)||e.createdAt-t.createdAt)}function oa(e){return e?.anchorKind||e?.kind||`line`}function sa(e){return oa(e)===`text`&&Number.isFinite(e?.startIndex)&&Number.isFinite(e?.endIndex)&&e.endIndex>e.startIndex}function ca(e,t){return e===t?!0:!e||!t?!1:oa(e)===oa(t)&&(e.startIndex??null)===(t.startIndex??null)&&(e.endIndex??null)===(t.endIndex??null)&&(e.startLine??null)===(t.startLine??null)&&(e.endLine??null)===(t.endLine??null)&&(e.anchorQuote??e.quote??``)===(t.anchorQuote??t.quote??``)}function la(e){return e?((e.kind||e.anchorKind)===`text`&&e.quote,e.startLine===e.endLine?`Line ${e.startLine}`:`Lines ${e.startLine}-${e.endLine}`):`No source anchor`}function ua(e={}){return[e.kind||e.anchorKind||`line`,e.startLine??0,e.endLine??0,e.quote||``].join(`::`)}function da(e){return e&&!e.querySelector(`[data-source-line]`)}function fa(e){let t=Number.parseInt(e||``,10);return Number.isFinite(t)?t:null}function pa(e=[]){return e.reduce((e,t)=>e?(t?.createdAt??0)>=(e?.createdAt??0)?t:e:t,null)}function ma(e){return e?.threads?.reduce((e,t)=>{let n=pa(t?.messages??[]);return n&&(n.createdAt??0)>=(e?.createdAt??0)?n:e},null)}function ha(e,t=`comment-markdown`){let n=document.createElement(`div`);return n.className=t,n.innerHTML=ta(e),n}function ga(e,t){return!!(t&&e?.users?.some(e=>e?.userId===t))}function _a(e){return String(Array.isArray(e?.users)?e.users.length:0)}function va(e,t,n){return e?.threadId===t&&e?.messageId===n}function ya(e){let t=e?.querySelector?.(`.comment-reaction-picker`),n=t?.closest?.(`.comment-reaction-picker-wrap`),r=e?.querySelector?.(`.comment-card-scroll`);return!(t instanceof HTMLElement)||!(n instanceof HTMLElement)||!(r instanceof HTMLElement)?null:{picker:t,scroll:r,wrap:n}}function ba(e,t){let n=fa(e?.getAttribute?.(`data-source-line`)),r=fa(e?.getAttribute?.(`data-source-line-end`))??n;return!n||!r||!t?!1:t.startLine<=r&&t.endLine>=n}function xa(e){let t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=``,r=[],i=!0;for(;t.nextNode();){let e=t.currentNode,a=e.textContent||``;for(let t=0;t<a.length;t+=1){let o=a[t];if(/\s/.test(o)){if(i)continue;n+=` `,r.push({node:e,offset:t}),i=!0;continue}n+=o,r.push({node:e,offset:t}),i=!1}}for(;n.endsWith(` `);)n=n.slice(0,-1),r.pop();return{map:r,normalized:n}}function Sa(e,t){let n=xe(t);if(!e||!n)return null;let r=xa(e);if(!r.normalized)return null;let i=r.normalized.indexOf(n);if(i<0||r.normalized.indexOf(n,i+1)>=0)return null;let a=r.map[i],o=r.map[i+n.length-1];if(!a||!o)return null;let s=document.createRange();return s.setStart(a.node,a.offset),s.setEnd(o.node,o.offset+1),s}function Ca(e,t){return{bottom:e.bottom-t.top,height:e.height,left:e.left-t.left,right:e.right-t.left,top:e.top-t.top,width:e.width}}function wa(e=[]){if(!Array.isArray(e)||e.length===0)return null;let t=Math.min(...e.map(e=>e.left)),n=Math.min(...e.map(e=>e.top)),r=Math.max(...e.map(e=>e.right)),i=Math.max(...e.map(e=>e.bottom));return{bottom:i,height:i-n,left:t,right:r,top:n,width:r-t}}function Ta(e,t,n){return n?e>=n.left&&e<=n.right&&t>=n.top&&t<=n.bottom:!1}function Ea(e=[]){return[...new Set(e.filter(Boolean))].sort()}function Da(e=[]){return Ea(e).join(` `)}function Oa(e){let t=document.createDocumentFragment(),n=document.createElement(`span`);if(n.className=`comment-marker-icon`,n.setAttribute(`aria-hidden`,`true`),n.innerHTML=`
|
|
293
293
|
<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
294
294
|
<path d="M3 4.75A1.75 1.75 0 0 1 4.75 3h6.5A1.75 1.75 0 0 1 13 4.75v4.5A1.75 1.75 0 0 1 11.25 11H8.9L6.5 13v-2H4.75A1.75 1.75 0 0 1 3 9.25v-4.5Z" stroke="currentColor" stroke-width="1.35" stroke-linejoin="round"/>
|
|
295
295
|
</svg>
|
|
296
|
-
`,t.appendChild(n),e>1){let n=document.createElement(`span`);n.className=`comment-marker-count`,n.textContent=String(e),t.appendChild(n)}return t}function Ta(){if(this.cardRoot?.isConnected&&this.cardRoot.parentElement===document.body)return this.cardRoot;let e=document.createElement(`div`);return e.className=`comment-card-root hidden`,document.body.appendChild(e),this.cardRoot=e,e}function Ea(e=`editor`,t=null){let n=this.session?.getCurrentSelectionCommentAnchor?.();n&&(this.selectionAnchor=n,this.reactionPicker=null,this.activeCard={anchor:n,mode:`create`,origin:e===`editor`&&t?`editor-chip`:e,replyThreadId:null,sourceRect:t??(e===`toolbar`?this.commentSelectionButton?.getBoundingClientRect?.():this.session?.getCommentAnchorClientRect?.(n))},this.render())}function Da(e,{anchor:t,origin:n,sourceRect:r}){this.reactionPicker=null,this.activeCard={anchor:t,groupKey:e.key,mode:`group`,origin:n,replyThreadId:null,sourceRect:r},this.renderDrawer(),this.renderCard()}function Oa(){this.activeCard=null,this.pendingCardFocusElement=null,this.reactionPicker=null,this.renderCard(),this.scheduleLayoutRefresh()}function ka(){return this.activeCard?this.activeCard.origin===`editor`?this.session?.getCommentAnchorClientRect?.(this.activeCard.anchor)??this.activeCard.sourceRect:this.activeCard.origin===`editor-chip`?this.activeCard.sourceRect:this.activeCard.origin===`preview`?this.resolvePreviewTarget(this.activeCard.anchor)?.bubbleRect??this.activeCard.sourceRect:this.activeCard.origin===`toolbar`?this.commentSelectionButton?.getBoundingClientRect?.()??this.activeCard.sourceRect:this.activeCard.sourceRect:null}function Aa(){let e=this.ensureCardRoot();if(e.replaceChildren(),e.classList.toggle(`hidden`,!this.activeCard),!this.activeCard){this.pendingCardFocusElement=null,e.style.visibility=``;return}this.pendingCardFocusElement=null;let t=document.createElement(`section`);t.className=`comment-card`,t.addEventListener(`click`,e=>{!this.reactionPicker||e.target?.closest?.(`.comment-reaction-picker-wrap`)||(this.reactionPicker=null,requestAnimationFrame(()=>{this.activeCard&&this.renderCard()}))});let n=document.createElement(`div`);n.className=`ui-record-header comment-card-header`;let r=document.createElement(`div`);r.className=`comment-card-title-wrap`;let i=document.createElement(`h3`);i.className=`comment-card-title`,i.textContent=this.activeCard.mode===`create`?`New comment`:`Comment threads`;let a=document.createElement(`p`);a.className=`comment-card-meta`,a.textContent=aa(this.activeCard.anchor),r.append(i,a);let o=document.createElement(`button`);o.type=`button`,o.className=G({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-card-close`]}),o.setAttribute(`aria-label`,`Close comments`),o.textContent=`Close`,o.addEventListener(`click`,()=>this.closeCard()),n.append(r,o),t.appendChild(n);let s=document.createElement(`div`);if(s.className=`comment-card-scroll`,this.activeCard.anchor?.quote){let e=document.createElement(`p`);e.className=`comment-card-quote`,e.textContent=this.activeCard.anchor.quote,s.appendChild(e)}if(this.activeCard.mode===`create`)s.appendChild(this.createComposer());else{let e=this.getThreadGroups().find(e=>e.key===this.activeCard.groupKey);if(!e){this.closeCard();return}e.threads.forEach(e=>{s.appendChild(this.createThreadElement(e))})}e.style.visibility=`hidden`,t.appendChild(s),e.appendChild(t),this.updateReactionPickerPosition(t),this.positionCard(t),e.style.visibility=``,this.flushPendingCardFocus(),this.scheduleLayoutRefresh()}function ja(e){let t=ha(e);if(!t)return;let{picker:n,scroll:r,wrap:i}=t;n.classList.remove(`is-upward`),n.style.maxHeight=``;let a=i.getBoundingClientRect(),o=r.getBoundingClientRect(),s=n.getBoundingClientRect(),c=window.innerHeight-12,l=Math.min(o.bottom,c),u=Math.max(o.top,12),d=Math.max(l-a.bottom-8,0),f=Math.max(a.top-u-8,0),p=s.height>d&&f>d,m=Math.max(p?f:d,120);n.classList.toggle(`is-upward`,p),n.style.maxHeight=`${m}px`}function Ma(){let e=this.cardRoot?.firstElementChild;if(!e||!this.activeCard){this.cardRoot&&(this.cardRoot.style.visibility=``);return}this.positionCard(e),this.cardRoot.style.visibility=``,this.flushPendingCardFocus()}function Na(){let e=document.createElement(`form`);e.className=`comment-card-form`;let t=document.createElement(`textarea`);t.className=K({extra:`comment-card-input`}),t.rows=4,t.maxLength=Ce,t.placeholder=`Add context, feedback, or a question...`;let n=document.createElement(`div`);n.className=`ui-record-actions comment-card-actions`;let r=document.createElement(`button`);r.type=`button`,r.className=G({variant:`secondary`}),r.textContent=`Cancel`,r.addEventListener(`click`,()=>this.closeCard());let i=document.createElement(`button`);return i.type=`submit`,i.className=G({variant:`primary`}),i.textContent=`Post comment`,n.append(r,i),e.append(t,n),e.addEventListener(`submit`,async e=>{if(e.preventDefault(),!await this.onCreateThread?.({anchor:this.activeCard?.anchor,body:t.value})){t.focus();return}this.closeCard()}),this.pendingCardFocusElement=t,e}function Pa(e){let t=document.createElement(`article`);t.className=`comment-thread-card`;let n=document.createElement(`div`);n.className=`ui-record-header comment-thread-card-header`;let r=document.createElement(`div`);r.className=`comment-thread-card-heading`;let i=document.createElement(`span`);i.className=`comment-thread-card-author`,i.textContent=e.createdByName;let a=document.createElement(`span`);a.className=`comment-thread-card-time`,a.textContent=this.formatTimestamp(e.createdAt);let o=document.createElement(`div`);o.className=`ui-record-actions comment-thread-card-actions`;let s=document.createElement(`button`);s.type=`button`,s.className=G({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-thread-card-action`]}),s.textContent=`Jump`,s.addEventListener(`click`,()=>this.onNavigateToLine?.(e.anchor?.startLine??1));let c=document.createElement(`button`);c.type=`button`,c.className=G({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-thread-card-action`]});let l=this.activeCard?.replyThreadId===e.id;c.classList.toggle(`is-active`,l),c.textContent=`Reply`,c.setAttribute(`aria-pressed`,String(l)),c.setAttribute(`aria-label`,l?`Cancel reply`:`Reply to thread`),c.title=l?`Cancel reply`:`Reply to thread`,c.addEventListener(`click`,()=>{this.activeCard={...this.activeCard,replyThreadId:l?null:e.id},this.renderCard()});let u=document.createElement(`button`);return u.type=`button`,u.className=G({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-thread-card-action`,`is-danger`]}),u.textContent=`Resolve`,u.addEventListener(`click`,async()=>{await this.onResolveThread?.(e.id)}),o.append(s,c,u),r.append(i,a),n.append(r,o),t.append(n),e.messages.forEach(n=>{t.appendChild(this.createMessageElement(e,n))}),this.activeCard?.replyThreadId===e.id&&t.appendChild(this.createReplyComposer(e)),t}function Fa(e,t){let n=document.createElement(`div`);n.className=`comment-message-card`;let r=document.createElement(`div`);r.className=`ui-record-meta comment-message-card-meta`;let i=document.createElement(`span`);i.className=`comment-message-card-author`,i.textContent=t.userName;let a=document.createElement(`span`);a.className=`comment-message-card-time`,a.textContent=this.formatTimestamp(t.createdAt);let o=da(t.body,`comment-message-card-body comment-markdown`);return r.append(i,a),n.append(r,o),n.appendChild(this.createReactionBar(e,t)),n}function Ia(e,t){let n=this.session?.getLocalUser?.()?.userId??``,r=document.createElement(`div`);r.className=`comment-reaction-bar`;let i=new Set((t.reactions??[]).map(e=>e.emoji)),a=document.createElement(`div`);a.className=`comment-reaction-chips`,(t.reactions??[]).forEach(r=>{let i=document.createElement(`button`);i.type=`button`,i.className=`ui-chip-button ui-chip-button--comment comment-reaction-chip`,i.classList.toggle(`is-active`,fa(r,n)),i.setAttribute(`aria-pressed`,String(fa(r,n))),i.title=r.users?.map(e=>e.userName).join(`, `)||r.emoji;let o=document.createElement(`span`);o.className=`comment-reaction-chip-emoji`,o.textContent=r.emoji;let s=document.createElement(`span`);s.className=`comment-reaction-chip-count`,s.textContent=pa(r),i.append(o,s),i.addEventListener(`click`,async()=>{await this.onToggleReaction?.(e.id,t.id,r.emoji)}),a.appendChild(i)});let o=document.createElement(`div`);o.className=`comment-reaction-actions`,Qi.filter(e=>!i.has(e)).forEach(n=>{o.appendChild(this.createQuickReactionButton(e,t,n))});let s=document.createElement(`div`);s.className=`comment-reaction-picker-wrap`;let c=document.createElement(`button`);return c.type=`button`,c.className=`ui-chip-button ui-chip-button--comment comment-reaction-more-trigger`,c.dataset.reactionPickerToggle=`true`,c.setAttribute(`aria-expanded`,String(ma(this.reactionPicker,e.id,t.id))),c.textContent=`More`,c.addEventListener(`click`,()=>{this.reactionPicker=ma(this.reactionPicker,e.id,t.id)?null:{messageId:t.id,threadId:e.id},this.renderCard()}),s.appendChild(c),ma(this.reactionPicker,e.id,t.id)&&s.appendChild(this.createReactionPicker(e,t)),o.appendChild(s),r.append(a,o),r}function La(e,t,n){let r=document.createElement(`button`);return r.type=`button`,r.className=`ui-icon-chip ui-icon-chip--comment comment-reaction-quick-add`,r.textContent=n,r.title=`React with ${n}`,r.addEventListener(`click`,async()=>{await this.onToggleReaction?.(e.id,t.id,n)}),r}function Ra(e,t){let n=document.createElement(`div`);n.className=`comment-reaction-picker`;let r=document.createElement(`div`);return r.className=`comment-reaction-picker-grid`,$i.forEach(n=>{r.appendChild(this.createReactionPickerButton(e,t,n))}),n.appendChild(r),n}function za(e,t,n){let r=document.createElement(`button`);return r.type=`button`,r.className=`ui-icon-chip ui-icon-chip--comment comment-reaction-picker-btn`,r.textContent=n,r.title=`React with ${n}`,r.addEventListener(`click`,async()=>{await this.onToggleReaction?.(e.id,t.id,n)&&(this.reactionPicker=null,this.renderCard())}),r}function Ba(e){let t=document.createElement(`form`);t.className=`comment-reply-form`;let n=document.createElement(`textarea`);n.className=K({extra:`comment-card-input`}),n.rows=3,n.maxLength=Ce,n.placeholder=`Reply to thread...`;let r=document.createElement(`div`);r.className=`ui-record-actions comment-card-actions`;let i=document.createElement(`button`);i.type=`button`,i.className=G({variant:`secondary`}),i.textContent=`Cancel`,i.addEventListener(`click`,()=>{this.activeCard={...this.activeCard,replyThreadId:null},this.renderCard()});let a=document.createElement(`button`);return a.type=`submit`,a.className=G({variant:`primary`}),a.textContent=`Reply`,r.append(i,a),t.append(n,r),this.pendingCardFocusElement=n,t.addEventListener(`submit`,async t=>{if(t.preventDefault(),!await this.onReplyToThread?.(e.id,n.value)){n.focus();return}this.activeCard={...this.activeCard,replyThreadId:null},this.renderCard()}),t}function Va(e){let t=this.updateCardSourceRect(),n=window.innerWidth,r=window.innerHeight,i=e.getBoundingClientRect(),a=ea((n-i.width)/2,16,n-i.width-16),o=ea((r-i.height)/4,16,r-i.height-16),s=a,c=o;t&&(s=ea(t.left,16,n-Math.min(i.width,520)-16),c=t.bottom+14,c+i.height>r-16&&(c=Math.max(t.top-i.height-14,16))),this.cardRoot.style.left=`${s}px`,this.cardRoot.style.top=`${c}px`,this.cardRoot.style.width=`${Math.min(Math.max(i.width,520),n-32)}px`}function Ha(){let e=this.pendingCardFocusElement;if(!(e instanceof HTMLElement)||!e.isConnected){this.pendingCardFocusElement=null;return}this.pendingCardFocusElement=null;let t=()=>{if(!e.isConnected)return;let t=document.activeElement;t instanceof HTMLElement&&this.editorContainer?.contains(t)&&t.blur(),e.focus({preventScroll:!0})};t(),document.activeElement!==e&&requestAnimationFrame(()=>{t(),document.activeElement!==e&&setTimeout(()=>{t()},50)})}var Ua={closeCard:Oa,createComposer:Na,createMessageElement:Fa,createQuickReactionButton:La,createReactionBar:Ia,createReactionPicker:Ra,createReactionPickerButton:za,createReplyComposer:Ba,createThreadElement:Pa,ensureCardRoot:Ta,flushPendingCardFocus:Ha,openComposerForSelection:Ea,openThreadGroup:Da,positionCard:Va,renderCard:Aa,repositionActiveCard:Ma,updateCardSourceRect:ka,updateReactionPickerPosition:ja};function Wa(){this.renderEditorLayer(),this.renderPreviewLayer(),this.repositionActiveCard()}function Ga(e=0){if(!this.previewElement)return!1;let t=this.supported&&e>0,n=0,r=0;if(t){let t=getComputedStyle(this.previewElement),i=Number.parseFloat(t.getPropertyValue(`--preview-comment-rail-reserved`))||0,a=Number.parseFloat(t.paddingRight)||0,o=Number.parseFloat(t.getPropertyValue(`--preview-comment-rail-inset`))||0,s=Math.max(a-i,0),c=Math.max(e+o-s,0),l=this.previewContainer?.getBoundingClientRect(),u=this.previewElement.getBoundingClientRect(),d=l?Math.max(l.right-u.right,0):0;r=Math.min(d,c),n=Math.max(c-r,0)}let i=`${Math.ceil(n)}px`,a=`${Math.floor(r)}px`,o=this.previewElement.style.getPropertyValue(`--preview-comment-rail-reserved`)!==i||this.previewElement.style.getPropertyValue(`--preview-comment-rail-offset`)!==a;return o&&(this.previewElement.style.setProperty(`--preview-comment-rail-reserved`,i),this.previewElement.style.setProperty(`--preview-comment-rail-offset`,a)),o}function Ka(){this.layoutFrame||=requestAnimationFrame(()=>{this.layoutFrame=0,this.refreshLayout()})}function qa(){if(this.editorLayer?.isConnected&&this.editorLayer.parentElement===this.editorContainer)return this.editorLayer;let e=document.createElement(`div`);return e.className=`comment-editor-layer`,this.editorContainer?.appendChild(e),this.editorLayer=e,e}function Ja(){let e=this.ensureEditorLayer();if(e.replaceChildren(),!this.supported||!this.session)return;let t=this.editorContainer?.getBoundingClientRect?.();if(!t)return;let n=this.getThreadGroups(),r=[];if(n.forEach(n=>{let i=this.session.getCommentAnchorClientRect?.(n.anchor);if(!i)return;let a=ya(i,t);if(a.bottom<0||a.top>t.height)return;let o=document.createElement(`button`);o.type=`button`,o.className=`ui-state-marker ui-state-marker--comment comment-editor-badge`,o.dataset.count=String(n.threads.length);let s=this.activeCard?.groupKey===n.key,c=this.hoveredEditorGroupKeys.includes(n.key);o.classList.toggle(`is-active`,s),o.classList.toggle(`is-hovered`,c),o.classList.toggle(`is-passive`,!s&&!c),o.setAttribute(`aria-label`,`${n.threads.length} comment thread${n.threads.length===1?``:`s`}`),o.appendChild(wa(n.threads.length));let l=Math.max(a.top,8);o.style.top=`${l}px`,o.style.left=`${Math.max(t.width-36,8)}px`,o.title=`${n.threads.length} comment${n.threads.length===1?``:`s`}`,o.addEventListener(`pointerdown`,e=>{e.preventDefault()}),o.addEventListener(`pointerenter`,()=>{this.updateHoveredEditorGroups([n.key])}),o.addEventListener(`pointerleave`,()=>{this.updateHoveredEditorGroups([])}),o.addEventListener(`focusin`,()=>{this.updateHoveredEditorGroups([n.key])}),o.addEventListener(`focusout`,()=>{this.updateHoveredEditorGroups([])}),o.addEventListener(`click`,()=>{this.openThreadGroup(n,{anchor:n.anchor,origin:`editor`,sourceRect:i})}),e.appendChild(o),r.push(l)}),!this.committedSelectionAnchor||this.activeCard?.mode===`create`)return;let i=this.session.getCommentAnchorClientRect?.(this.committedSelectionAnchor),a=this.session.getSelectionChipClientRect?.(this.committedSelectionAnchor)??i;if(!a)return;let o=ya(a,t);if(o.bottom<0||o.top>t.height)return;let s=ea(o.top,8,Math.max(t.height-36,8));for(;r.some(e=>Math.abs(e-s)<32);)s=ea(s+36,8,Math.max(t.height-36,8));let c=document.createElement(`button`);c.type=`button`,c.className=`ui-selection-pill ui-selection-pill--comment comment-selection-chip`,c.textContent=`Comment`,c.style.top=`${s}px`,c.style.right=`12px`,c.addEventListener(`pointerdown`,e=>{e.preventDefault(),e.stopPropagation(),this.openComposerForSelection(`editor`,c.getBoundingClientRect())}),e.appendChild(c)}function Ya(){if(this.previewLayer?.isConnected&&this.previewLayer.parentElement===this.previewElement)return this.previewLayer;let e=document.createElement(`div`);e.className=`comment-preview-highlights`;let t=document.createElement(`div`);return t.className=`comment-preview-layer`,this.previewElement?.append(e,t),this.previewHighlightLayer=e,this.previewLayer=t,t}function Xa(){if(this.ensurePreviewLayer(),this.previewLayer?.replaceChildren(),this.previewHighlightLayer?.replaceChildren(),!this.supported||!this.previewElement){this.previewHoverRegions=[],this.syncPreviewRailLayout(0);return}let e=this.previewElement.getBoundingClientRect(),t=this.getThreadGroups(),n=[],r=[],i=this.shouldRenderPassivePreviewMarkers(),a=[];t.forEach(t=>{let o=this.resolvePreviewTarget(t.anchor);if(!o?.bubbleRect)return;r.push({key:t.key,rects:o.hoverRects?.length>0?o.hoverRects:[o.bubbleRect]});let s=this.activeCard?.groupKey===t.key,c=this.hoveredPreviewGroupKeys.includes(t.key),l=s||c;if(o.highlightRects?.forEach(t=>{let n=document.createElement(`div`);n.className=`comment-preview-highlight`,n.classList.toggle(`is-active`,s),n.classList.toggle(`is-hovered`,c),n.classList.toggle(`is-passive`,!l),n.style.left=`${t.left-e.left}px`,n.style.top=`${t.top-e.top}px`,n.style.width=`${t.width}px`,n.style.height=`${t.height}px`,this.previewHighlightLayer?.appendChild(n)}),!i&&!l)return;let u=document.createElement(`button`);u.type=`button`,u.className=`ui-state-marker ui-state-marker--comment comment-preview-badge`,u.dataset.commentPreviewGroupKeys=t.key,u.classList.toggle(`is-active`,s),u.classList.toggle(`is-hovered`,c),u.classList.toggle(`is-passive`,!l),u.setAttribute(`aria-label`,`${t.threads.length} comment thread${t.threads.length===1?``:`s`}`),u.appendChild(wa(t.threads.length));let d=ea(o.bubbleRect.top-e.top,6,Math.max(this.previewElement.clientHeight-30,6));for(;n.some(e=>Math.abs(e-d)<26);)d=ea(d+30,6,Math.max(this.previewElement.clientHeight-30,6));u.style.top=`${d}px`,u.title=`${t.threads.length} comment${t.threads.length===1?``:`s`}`,u.addEventListener(`pointerdown`,e=>{e.preventDefault()}),u.addEventListener(`click`,()=>{this.openThreadGroup(t,{anchor:t.anchor,origin:`preview`,sourceRect:u.getBoundingClientRect()})}),this.previewLayer?.appendChild(u),n.push(d),a.push(u)}),this.previewHoverRegions=r;let o=a.reduce((e,t)=>Math.max(e,t.offsetWidth||28),0);this.syncPreviewRailLayout(o)&&this.scheduleLayoutRefresh(),this.lastPreviewPointerPosition&&this.updateHoveredPreviewGroups(this.getPreviewGroupKeysAtPoint(this.lastPreviewPointerPosition.x,this.lastPreviewPointerPosition.y))}function Za(e){if(!this.previewElement||!e)return null;let t=Array.from(this.previewElement.querySelectorAll(`.mermaid-shell, .plantuml-shell`)).find(t=>ga(t,e));if(t)return{bubbleRect:t.getBoundingClientRect(),highlightRects:[],hoverRects:[t.getBoundingClientRect()]};let n=Array.from(this.previewElement.querySelectorAll(`[data-source-line]`)).filter(t=>sa(t)&&ga(t,e));if(e.kind===`text`&&e.quote){let t=n.map(t=>({element:t,range:va(t,e.quote)})).filter(e=>e.range);if(t.length===1){let e=Array.from(t[0].range.getClientRects());return{bubbleRect:ba(e)||t[0].element.getBoundingClientRect(),highlightRects:e,hoverRects:e}}}let r=n[0];return r?{bubbleRect:r.getBoundingClientRect(),highlightRects:[],hoverRects:[r.getBoundingClientRect()]}:null}function Qa(e){if(!(e instanceof Node))return[];let t=e.closest?.(`[data-comment-preview-group-keys]`);return Ca(String(t?.dataset?.commentPreviewGroupKeys??``).split(/\s+/).filter(Boolean)).split(` `).filter(Boolean)}function $a(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))return[];let n=document.elementFromPoint(e,t),r=this.getPreviewGroupKeysForTarget(n);return r.length>0?r:Sa(this.previewHoverRegions.filter(n=>n.rects.some(n=>xa(e,t,n))).map(e=>e.key))}function eo(e=[]){let t=Sa(e),n=t.join(` `);n!==this.hoveredPreviewGroupKeysSignature&&(this.hoveredPreviewGroupKeys=t,this.hoveredPreviewGroupKeysSignature=n,this.scheduleLayoutRefresh())}function to(e=[]){let t=Sa(e),n=t.join(` `);n!==this.hoveredEditorGroupKeysSignature&&(this.hoveredEditorGroupKeys=t,this.hoveredEditorGroupKeysSignature=n,this.scheduleLayoutRefresh())}function no(e){this.updateHoveredPreviewGroups(this.getPreviewGroupKeysForTarget(e))}function ro(){let e=this.previewContainer?.clientWidth??this.previewElement?.clientWidth??0;return window.innerWidth>=769&&e>=400}var io={ensureEditorLayer:qa,ensurePreviewLayer:Ya,getPreviewGroupKeysAtPoint:$a,getPreviewGroupKeysForTarget:Qa,refreshLayout:Wa,renderEditorLayer:Ja,renderPreviewLayer:Xa,resolvePreviewTarget:Za,scheduleLayoutRefresh:Ka,shouldRenderPassivePreviewMarkers:ro,syncHoveredPreviewGroupsFromTarget:no,syncPreviewRailLayout:Ga,updateHoveredEditorGroups:to,updateHoveredPreviewGroups:eo};function ao(){this.renderToolbar(),this.renderDrawer(),this.renderCard(),this.scheduleLayoutRefresh()}function oo(){let e=this.threads.length,t=this.supported&&!!this.session;if(this.commentSelectionButton?.classList.toggle(`hidden`,!t),this.commentsToggleButton?.classList.toggle(`hidden`,!this.supported),this.commentSelectionButton&&(this.commentSelectionButton.disabled=!this.selectionAnchor),this.commentsToggleButton){this.commentsToggleButton.classList.toggle(`active`,this.drawerOpen),this.commentsToggleButton.setAttribute(`aria-expanded`,String(this.drawerOpen));let t=e>0?`Comments ${e}`:`Comments`,n=this.commentsToggleButton.querySelector(`.ui-action-label`);n?n.textContent=t:this.commentsToggleButton.textContent=t}}function so(){if(!this.commentsDrawer||!this.commentsDrawerList)return;this.commentsDrawer.classList.toggle(`hidden`,!this.supported||!this.drawerOpen),this.commentsDrawerList.replaceChildren();let e=this.getThreadGroups();if(this.commentsDrawerEmpty?.classList.toggle(`hidden`,e.length>0),!this.supported||e.length===0)return;let t=document.createDocumentFragment();e.forEach(e=>{let n=document.createElement(`button`);n.type=`button`,n.className=`ui-record-surface comments-drawer-item`,n.classList.toggle(`is-active`,this.activeCard?.groupKey===e.key),n.addEventListener(`pointerdown`,e=>{e.preventDefault()}),n.addEventListener(`click`,()=>{this.openThreadGroup(e,{anchor:e.anchor,origin:`drawer`,sourceRect:n.getBoundingClientRect()})});let r=document.createElement(`div`);r.className=`ui-record-header comments-drawer-item-header`;let i=document.createElement(`span`);i.className=`comments-drawer-item-title`,i.textContent=aa(e.anchor);let a=document.createElement(`span`);a.className=`ui-pill-badge ui-pill-badge--count ui-pill-badge--accent comments-drawer-item-count`,a.textContent=String(e.threads.length),r.append(i,a);let o=document.createElement(`p`);o.className=`comments-drawer-item-quote`,o.textContent=e.anchor.quote||e.anchor.excerpt||`Source anchored comment`;let s=ua(e),c=da(s?.body||``,`comment-markdown comments-drawer-item-preview`),l=document.createElement(`div`);l.className=`ui-record-meta comments-drawer-item-footer`;let u=document.createElement(`span`);u.textContent=`${e.threads.length} thread${e.threads.length===1?``:`s`}`;let d=document.createElement(`span`);d.className=`comments-drawer-item-updated`,d.textContent=s?`${s.userName} • ${this.formatTimestamp(s.createdAt)}`:``,l.append(u,d),n.append(r,o,c,l),t.appendChild(n)}),this.commentsDrawerList.appendChild(t)}function co(e){if(!Number.isFinite(e))return``;try{return this.timeFormatter.format(new Date(e))}catch{return``}}var lo={formatTimestamp:co,render:ao,renderDrawer:so,renderToolbar:oo};function uo(e){this.session?.getScrollContainer?.()?.removeEventListener(`scroll`,this.handleEditorScroll),this.session=e,this.selectionAnchor=e?.getCurrentSelectionCommentAnchor?.()??null,this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.reactionPicker=null,this.clearSelectionRevealTimer(),this.pointerSelecting=!1,e?.getScrollContainer?.()?.addEventListener(`scroll`,this.handleEditorScroll,{passive:!0}),this.render()}function fo(e,{fileKind:t=`markdown`,supported:n=!1}={}){let r=this.currentFile!==e;this.currentFile=e,this.fileKind=t,this.supported=!!(e&&n),r&&(this.drawerOpen=!1,this.threads=[],this.selectionAnchor=null,this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.clearSelectionRevealTimer(),this.pointerSelecting=!1,this.activeCard=null,this.updateHoveredEditorGroups([]),this.updateHoveredPreviewGroups([]),this.previewHoverRegions=[],this.lastPreviewPointerPosition=null,this.reactionPicker=null),this.supported||(this.drawerOpen=!1,this.activeCard=null,this.threads=[],this.selectionAnchor=null,this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.clearSelectionRevealTimer(),this.pointerSelecting=!1,this.updateHoveredEditorGroups([]),this.updateHoveredPreviewGroups([]),this.previewHoverRegions=[],this.lastPreviewPointerPosition=null,this.reactionPicker=null),this.render()}function po(e){if(this.selectionAnchor=this.supported?e:null,!this.supported||!this.selectionAnchor){this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.clearSelectionRevealTimer(),this.renderToolbar(),this.scheduleLayoutRefresh();return}if(!ra(this.selectionAnchor)){this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.clearSelectionRevealTimer(),this.renderToolbar(),this.scheduleLayoutRefresh();return}if(this.pendingSelectionAnchor=this.selectionAnchor,this.activeCard?.mode===`create`){this.clearSelectionRevealTimer(),this.renderToolbar(),this.scheduleLayoutRefresh();return}if(this.pointerSelecting){this.clearSelectionRevealTimer(),this.committedSelectionAnchor=null,this.renderToolbar(),this.scheduleLayoutRefresh();return}if(ia(this.committedSelectionAnchor,this.selectionAnchor)){this.renderToolbar(),this.scheduleLayoutRefresh();return}this.scheduleSelectionReveal(this.selectionAnchor),this.renderToolbar(),this.scheduleLayoutRefresh()}function mo(){this.activeCard?.mode!==`create`&&(this.clearSelectionRevealTimer(),this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.scheduleLayoutRefresh())}function ho(e=[]){this.threads=ta(e),this.activeCard?.mode===`group`&&!this.getThreadGroups().some(e=>e.key===this.activeCard.groupKey)&&(this.activeCard=null),this.reactionPicker&&!this.threads.some(e=>e.id===this.reactionPicker.threadId&&e.messages?.some(e=>e.id===this.reactionPicker.messageId))&&(this.reactionPicker=null),this.render()}function go(e){let t=!!e;t!==this.drawerOpen&&(t&&this.onWillOpenDrawer?.(),this.drawerOpen=t,this.render())}function _o(){this.setDrawerOpen(!1)}function vo(){let e=new Map;return this.threads.forEach(t=>{let n=oa(t.anchor),r=e.get(n);if(r){r.threads.push(t);return}e.set(n,{anchor:t.anchor,key:n,threads:[t]})}),Array.from(e.values()).sort((e,t)=>(e.anchor?.startLine??0)-(t.anchor?.startLine??0))}function yo(){this.selectionRevealTimer&&=(clearTimeout(this.selectionRevealTimer),0)}function bo(e){this.clearSelectionRevealTimer(),this.selectionRevealTimer=window.setTimeout(()=>{this.selectionRevealTimer=0,!(this.pointerSelecting||this.activeCard?.mode===`create`||!ia(this.pendingSelectionAnchor,e))&&(this.committedSelectionAnchor=e,this.scheduleLayoutRefresh())},150)}var xo={attachSession:uo,clearSelectionRevealTimer:yo,closeDrawer:_o,getThreadGroups:vo,handleEditorContentChange:mo,scheduleSelectionReveal:bo,setCurrentFile:fo,setDrawerOpen:go,setSelectionAnchor:po,setThreads:ho},So=class{constructor({commentSelectionButton:e,commentsDrawer:t,commentsDrawerEmpty:n,commentsDrawerList:r,commentsToggleButton:i,editorContainer:a,onWillOpenDrawer:o,onCreateThread:s,onNavigateToLine:c,onReplyToThread:l,onToggleReaction:u,onResolveThread:d,previewContainer:f,previewElement:p}){this.commentSelectionButton=e,this.commentsDrawer=t,this.commentsDrawerEmpty=n,this.commentsDrawerList=r,this.commentsToggleButton=i,this.editorContainer=a,this.onWillOpenDrawer=o,this.onCreateThread=s,this.onNavigateToLine=c,this.onReplyToThread=l,this.onToggleReaction=u,this.onResolveThread=d,this.previewContainer=f,this.previewElement=p,this.currentFile=null,this.fileKind=`markdown`,this.supported=!1,this.drawerOpen=!1,this.threads=[],this.selectionAnchor=null,this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.selectionRevealTimer=0,this.pointerSelecting=!1,this.session=null,this.activeCard=null,this.hoveredEditorGroupKeys=[],this.hoveredEditorGroupKeysSignature=``,this.hoveredPreviewGroupKeys=[],this.hoveredPreviewGroupKeysSignature=``,this.previewHoverRegions=[],this.lastPreviewPointerPosition=null,this.editorLayer=null,this.previewLayer=null,this.previewHighlightLayer=null,this.cardRoot=null,this.pendingCardFocusElement=null,this.reactionPicker=null,this.layoutFrame=0,this.timeFormatter=new Intl.DateTimeFormat(void 0,{day:`numeric`,hour:`numeric`,minute:`2-digit`,month:`short`}),this.handleEditorScroll=()=>this.scheduleLayoutRefresh(),this.handlePreviewScroll=()=>this.scheduleLayoutRefresh(),this.handleWindowResize=()=>this.scheduleLayoutRefresh(),this.handlePreviewPointerMove=e=>{this.lastPreviewPointerPosition={x:e.clientX,y:e.clientY},this.updateHoveredPreviewGroups(this.getPreviewGroupKeysAtPoint(e.clientX,e.clientY))},this.handlePreviewPointerLeave=()=>{this.lastPreviewPointerPosition=null,this.updateHoveredPreviewGroups([])},this.handlePreviewFocusIn=e=>{this.updateHoveredPreviewGroups(this.getPreviewGroupKeysForTarget(e.target))},this.handlePreviewFocusOut=e=>{this.updateHoveredPreviewGroups(this.getPreviewGroupKeysForTarget(e.relatedTarget))},this.handleCommentSelectionButtonPointerDown=e=>{e.preventDefault()},this.handleEditorPointerDown=e=>{e.button!==0||!this.supported||!this.session||!e.target?.closest?.(`.cm-editor`)||e.target?.closest?.(`.comment-editor-layer`)||(this.pointerSelecting=!0,this.clearSelectionRevealTimer(),this.committedSelectionAnchor&&(this.committedSelectionAnchor=null,this.scheduleLayoutRefresh()))},this.handleDocumentPointerUp=()=>{this.pointerSelecting&&requestAnimationFrame(()=>{let e=this.supported?this.session?.getCurrentSelectionCommentAnchor?.()??null:null;this.pointerSelecting=!1,this.selectionAnchor=e,this.renderToolbar(),this.pendingSelectionAnchor=ra(e)?e:null,this.clearSelectionRevealTimer(),this.committedSelectionAnchor=ra(e)&&this.activeCard?.mode!==`create`?e:null,this.scheduleLayoutRefresh()})},this.handleEditorFocusOut=e=>{let t=e.relatedTarget;t instanceof Node&&(this.editorContainer?.contains(t)||this.cardRoot?.contains(t)||this.commentSelectionButton?.contains(t))||(this.clearSelectionRevealTimer(),this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.scheduleLayoutRefresh())},this.handleDocumentPointerDown=e=>{let t=e.target;if(this.activeCard&&this.cardRoot){if(this.cardRoot.contains(t))return;this.closeCard()}this.drawerOpen&&(t instanceof Node&&(this.commentsDrawer?.contains(t)||this.commentsToggleButton?.contains(t))||this.closeDrawer())},this.handleDocumentKeyDown=e=>{if(e.key===`Escape`&&this.reactionPicker){this.reactionPicker=null,this.renderCard();return}e.key===`Escape`&&this.activeCard&&this.closeCard(),e.key===`Escape`&&this.committedSelectionAnchor&&(this.clearSelectionRevealTimer(),this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.scheduleLayoutRefresh())},this.commentSelectionButton?.addEventListener(`pointerdown`,this.handleCommentSelectionButtonPointerDown),this.commentSelectionButton?.addEventListener(`click`,()=>{this.openComposerForSelection(`toolbar`)}),this.commentsToggleButton?.addEventListener(`click`,()=>{this.setDrawerOpen(!this.drawerOpen)}),this.previewContainer?.addEventListener(`scroll`,this.handlePreviewScroll,{passive:!0}),this.previewElement?.addEventListener(`pointermove`,this.handlePreviewPointerMove,{passive:!0}),this.previewElement?.addEventListener(`pointerleave`,this.handlePreviewPointerLeave),this.previewElement?.addEventListener(`focusin`,this.handlePreviewFocusIn),this.previewElement?.addEventListener(`focusout`,this.handlePreviewFocusOut),this.editorContainer?.addEventListener(`pointerdown`,this.handleEditorPointerDown),this.editorContainer?.addEventListener(`focusout`,this.handleEditorFocusOut),window.addEventListener(`resize`,this.handleWindowResize),document.addEventListener(`pointerup`,this.handleDocumentPointerUp),document.addEventListener(`pointercancel`,this.handleDocumentPointerUp),document.addEventListener(`pointerdown`,this.handleDocumentPointerDown),document.addEventListener(`keydown`,this.handleDocumentKeyDown)}destroy(){this.layoutFrame&&=(cancelAnimationFrame(this.layoutFrame),0),this.attachSession(null),this.previewContainer?.removeEventListener(`scroll`,this.handlePreviewScroll),this.previewElement?.removeEventListener(`pointermove`,this.handlePreviewPointerMove),this.previewElement?.removeEventListener(`pointerleave`,this.handlePreviewPointerLeave),this.previewElement?.removeEventListener(`focusin`,this.handlePreviewFocusIn),this.previewElement?.removeEventListener(`focusout`,this.handlePreviewFocusOut),this.commentSelectionButton?.removeEventListener(`pointerdown`,this.handleCommentSelectionButtonPointerDown),this.editorContainer?.removeEventListener(`pointerdown`,this.handleEditorPointerDown),this.editorContainer?.removeEventListener(`focusout`,this.handleEditorFocusOut),window.removeEventListener(`resize`,this.handleWindowResize),document.removeEventListener(`pointerup`,this.handleDocumentPointerUp),document.removeEventListener(`pointercancel`,this.handleDocumentPointerUp),document.removeEventListener(`pointerdown`,this.handleDocumentPointerDown),document.removeEventListener(`keydown`,this.handleDocumentKeyDown),this.previewHoverRegions=[],this.cardRoot?.remove(),this.editorLayer?.remove(),this.previewLayer?.remove(),this.pendingCardFocusElement=null}};Object.assign(So.prototype,xo,lo,io,Ua);var Co=360,wo=`https://viewer.diagrams.net/js/viewer-static.min.js`,To=null;function Eo(e,t){return typeof window.requestIdleCallback==`function`?window.requestIdleCallback(e,{timeout:t}):window.setTimeout(()=>e({didTimeout:!1,timeRemaining:()=>0}),1)}function Do(e){if(e!==null){if(typeof window.cancelIdleCallback==`function`){window.cancelIdleCallback(e);return}window.clearTimeout(e)}}function Oo(e,t,n){if(!e||!t)return!1;let r=t.getBoundingClientRect(),i=e.getBoundingClientRect();return i.bottom>=r.top-n&&i.top<=r.bottom+n}function ko(){return window.GraphViewer?.processElements?Promise.resolve(window.GraphViewer):To||(To=new Promise((e,t)=>{let n=document.querySelector(`script[data-collabmd-drawio-viewer]`),r=n instanceof HTMLScriptElement?n:document.createElement(`script`),i=()=>{r.removeEventListener(`error`,a),r.removeEventListener(`load`,o)},a=()=>{i(),To=null,t(Error(`Failed to load draw.io viewer`))},o=()=>{if(i(),!window.GraphViewer?.processElements){To=null,t(Error(`draw.io viewer did not initialize`));return}e(window.GraphViewer)};r.addEventListener(`error`,a,{once:!0}),r.addEventListener(`load`,o,{once:!0}),n?window.GraphViewer?.processElements&&o():(r.src=wo,r.async=!0,r.dataset.collabmdDrawioViewer=`true`,document.head.append(r))}),To)}var Ao=class{constructor({getLocalUser:e,getTheme:t,onOpenFile:n=null,onOpenTextFile:r=null,previewContainer:i,previewElement:a,toastController:o}){this.getLocalUser=e,this.getTheme=t,this.onOpenFile=n,this.onOpenTextFile=r,this.previewContainer=i,this.previewElement=a,this.toastController=o,this.embedEntries=new Map,this.hydrationQueue=[],this.hydrationIdleId=null,this.hydrationPaused=!1,this.instanceCounter=0,this.maximizedEntry=null,this.maximizedRoot=null,this._onMessage=this._onMessage.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onPreviewClick=this._onPreviewClick.bind(this),window.addEventListener(`message`,this._onMessage),window.addEventListener(`keydown`,this._onKeyDown),this.previewElement?.addEventListener(`click`,this._onPreviewClick)}destroy(){window.removeEventListener(`message`,this._onMessage),window.removeEventListener(`keydown`,this._onKeyDown),this.previewElement?.removeEventListener(`click`,this._onPreviewClick),Do(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this._exitMaximizedEntry(),document.body.classList.remove(`drawio-maximized-open`),this.embedEntries.forEach(e=>e.wrapper?.remove()),this.embedEntries.clear(),this.maximizedRoot?.remove(),this.maximizedRoot=null}detachForCommit(){Do(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this.embedEntries.forEach(e=>{e.placeholder=null})}setHydrationPaused(e){this.hydrationPaused=!!e,this.hydrationPaused||this.hydrateVisibleEmbeds()}reconcileEmbeds(e){this._exitMaximizedEntry();let t=Array.from(e.querySelectorAll(`.drawio-embed-placeholder[data-drawio-key]`)).map(e=>({filePath:e.dataset.drawioTarget||``,key:e.dataset.drawioKey||``,label:e.dataset.drawioLabel||e.dataset.drawioTarget||``,mode:e.dataset.drawioMode===`edit`?`edit`:`view`,placeholder:e})),n=new Map;t.forEach(e=>{let t=this.embedEntries.get(e.key)||null,r=t?{...t,...e}:{...e,iframe:null,imageElement:null,instanceId:``,queued:!1,viewerElement:null,wrapper:null};n.set(e.key,r)}),this.embedEntries.forEach((e,t)=>{n.has(t)||e.wrapper?.remove()}),this.embedEntries=n,this.embedEntries.forEach(e=>{e.wrapper?e.placeholder?.replaceWith(e.wrapper):e.queued=!1}),this.hydrationPaused||this.hydrateVisibleEmbeds()}hydrateVisibleEmbeds(){this.embedEntries.forEach(e=>{e.wrapper||!e.placeholder?.isConnected||(e.mode===`edit`||Oo(e.placeholder,this.previewContainer,Co))&&this.enqueueHydration(e)})}enqueueHydration(e){e.queued||(e.queued=!0,this.hydrationQueue.push(e),this.hydrationIdleId===null&&(this.hydrationIdleId=Eo(()=>{this.hydrationIdleId=null,this.hydrationQueue.splice(0).forEach(e=>{e.queued=!1,this.hydrateEntry(e)})},200)))}hydrateEntry(e){if(!(!e.placeholder?.isConnected||e.wrapper)){if(e.mode===`view`){this.hydrateViewerEntry(e);return}this.hydrateIframeEntry(e)}}hydrateIframeEntry(e){if(!e.placeholder?.isConnected||e.wrapper)return;let t=document.createElement(`div`);t.className=`drawio-embed diagram-preview-shell${e.mode===`edit`?` is-direct-file`:``}`,t.dataset.file=e.filePath,t.dataset.drawioKey=e.key;let n=document.createElement(`div`);n.className=`drawio-embed-header diagram-preview-toolbar`;let r=document.createElement(`span`);r.className=`drawio-embed-icon`,r.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="7" height="6" rx="1"/><rect x="14" y="4" width="7" height="6" rx="1"/><rect x="8.5" y="14" width="7" height="6" rx="1"/><path d="M10 7h4"/><path d="M17.5 10v2.5"/><path d="M6.5 10v2.5"/><path d="M6.5 12.5h11"/></svg>`;let i=document.createElement(`span`);i.className=`drawio-embed-label`,i.textContent=e.label.replace(/\.drawio$/i,``),n.append(r,i),e.mode!==`edit`&&n.appendChild(this.createOpenButton(e)),n.appendChild(this.createMaximizeButton(e,t));let a=document.createElement(`iframe`);a.className=`drawio-embed-iframe`,a.loading=`lazy`,a.referrerPolicy=`strict-origin-when-cross-origin`,e.instanceId=`drawio-${++this.instanceCounter}`,a.dataset.instanceId=e.instanceId,a.src=this.buildIframeUrl(e),t.append(n,a),e.iframe=a,e.wrapper=t,e.placeholder.replaceWith(t)}async hydrateViewerEntry(e){if(!e.placeholder?.isConnected||e.wrapper)return;let t=document.createElement(`div`);t.className=`drawio-embed diagram-preview-shell is-static-preview`,t.dataset.file=e.filePath,t.dataset.drawioKey=e.key;let n=document.createElement(`div`);n.className=`drawio-embed-header diagram-preview-toolbar`;let r=document.createElement(`span`);r.className=`drawio-embed-icon`,r.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="7" height="6" rx="1"/><rect x="14" y="4" width="7" height="6" rx="1"/><rect x="8.5" y="14" width="7" height="6" rx="1"/><path d="M10 7h4"/><path d="M17.5 10v2.5"/><path d="M6.5 10v2.5"/><path d="M6.5 12.5h11"/></svg>`;let i=document.createElement(`span`);i.className=`drawio-embed-label`,i.textContent=e.label.replace(/\.drawio$/i,``),n.append(r,i),n.append(this.createOpenButton(e),this.createMaximizeButton(e,t));let a=document.createElement(`div`);a.className=`drawio-viewer-shell`,a.dataset.filePath=e.filePath;let o=document.createElement(`div`);o.className=`preview-shell`,o.textContent=`Rendering draw.io preview…`,a.appendChild(o),t.append(n,a),e.iframe=null,e.wrapper=t,e.viewerElement=a,e.placeholder.replaceWith(t);try{await this.renderViewerEntry(e)}catch(t){this.renderViewerFallback(e,t instanceof Error?t.message:`Failed to render draw.io preview`)}}async renderViewerEntry(e){let[{content:t},n]=await Promise.all([S.readFile(e.filePath),ko()]);if(!e.wrapper?.isConnected||!e.viewerElement?.isConnected)return;let r=this.getTheme?.()===`light`?`light`:`dark`,i=document.createElement(`div`);i.className=`mxgraph drawio-viewer-frame`,i.dataset.action=`open-file`,i.dataset.filePath=e.filePath,i.setAttribute(`role`,`button`),i.setAttribute(`tabindex`,`0`),i.setAttribute(`aria-label`,`Open ${e.label.replace(/\.drawio$/i,``)}`),i.addEventListener(`click`,t=>{t.preventDefault(),this.onOpenFile?.(e.filePath)}),i.addEventListener(`keydown`,t=>{t.key!==`Enter`&&t.key!==` `||(t.preventDefault(),this.onOpenFile?.(e.filePath))}),i.dataset.mxgraph=JSON.stringify({"check-visible-state":!1,center:!0,border:0,"dark-mode":r,editable:!1,fit:1,lightbox:!1,nav:!1,resize:!1,toolbar:``,tooltips:!1,xml:String(t??``)}),e.viewerElement.replaceChildren(i),e.viewerElement=i,n.processElements()}buildIframeUrl(e){let t=new URL(w(`/drawio-editor.html`)),n=this.getLocalUser?.()??{};return t.searchParams.set(`file`,e.filePath),t.searchParams.set(`hostMode`,e.mode===`edit`?`file-preview`:`embed`),t.searchParams.set(`instanceId`,e.instanceId),t.searchParams.set(`mode`,e.mode===`edit`?`edit`:`view`),t.searchParams.set(`theme`,this.getTheme?.()===`light`?`light`:`dark`),n.name&&t.searchParams.set(`userName`,n.name),n.peerId&&t.searchParams.set(`peerId`,n.peerId),e.mode===`edit`&&t.searchParams.set(`leaseRoom`,ce(e.filePath)),t.toString()}updateTheme(e){this.embedEntries.forEach(t=>{t.iframe?.contentWindow&&t.iframe.contentWindow.postMessage({source:`collabmd-host`,theme:e,type:`set-theme`},window.location.origin),t.mode===`view`&&t.wrapper?.isConnected&&t.viewerElement?.isConnected&&this.renderViewerEntry(t).catch(e=>{this.renderViewerFallback(t,e instanceof Error?e.message:`Failed to render draw.io preview`)})})}updateLocalUser(){}syncLayout(){}createOpenButton(e){let t=document.createElement(`button`);return t.type=`button`,t.className=`drawio-embed-btn ui-preview-action ui-preview-action--icon-only`,t.dataset.action=`open-file`,t.dataset.filePath=e.filePath,t.title=`Edit in draw.io`,t.setAttribute(`aria-label`,`Edit in draw.io`),P(t,`edit`),t.addEventListener(`click`,t=>{t.preventDefault(),this.onOpenFile?.(e.filePath)}),t}createMaximizeButton(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`drawio-embed-btn ui-preview-action ui-preview-action--icon-only`,n.dataset.action=`toggle-maximize`,n.dataset.filePath=e.filePath,n.dataset.drawioKey=e.key,n.addEventListener(`click`,n=>{n.preventDefault(),this.maximizedEntry?.key===e.key?this._exitMaximizedEntry():this._enterMaximizedEntry(e,t),this._syncMaximizeButtons()}),(()=>{let t=this.maximizedEntry?.key===e.key;P(n,t?`restore`:`maximize`),n.title=t?`Restore diagram size`:`Maximize diagram`,n.setAttribute(`aria-label`,t?`Restore diagram size`:`Maximize diagram`)})(),n}_ensureMaximizedRoot(){if(this.maximizedRoot?.isConnected&&this.maximizedRoot.parentElement===document.body)return this.maximizedRoot;let e=document.body.querySelector(`[data-drawio-maximized-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.drawioMaximizedRoot=`true`,e.className=`drawio-maximized-root`,document.body.appendChild(e)),this.maximizedRoot=e,e}_enterMaximizedEntry(e,t=e?.wrapper){if(!e?.wrapper||e.wrapper!==t||this.maximizedEntry?.key===e.key)return;this._exitMaximizedEntry();let n=this._ensureMaximizedRoot(),r=e.wrapper.parentElement;if(!r)return;let i=document.createElement(`div`);i.className=`drawio-maximize-spacer`,i.style.height=`${Math.ceil(e.wrapper.getBoundingClientRect().height)}px`,e.maximizeSpacer=i,e.restoreParent=r,e.restoreNextSibling=e.wrapper.nextSibling||null,r.insertBefore(i,e.wrapper),n.hidden=!1,n.appendChild(e.wrapper),e.wrapper.classList.add(`is-maximized`),document.body.classList.add(`drawio-maximized-open`),this.maximizedEntry=e}_exitMaximizedEntry(){let e=this.maximizedEntry;if(!e?.wrapper){this.maximizedEntry=null,document.body.classList.remove(`drawio-maximized-open`);return}let{maximizeSpacer:t,restoreNextSibling:n,restoreParent:r}=e;e.wrapper.classList.remove(`is-maximized`),t?.parentElement?t.replaceWith(e.wrapper):r?.isConnected&&(n?.parentElement===r?r.insertBefore(e.wrapper,n):r.appendChild(e.wrapper)),e.maximizeSpacer=null,e.restoreParent=null,e.restoreNextSibling=null,this.maximizedEntry=null,document.body.classList.remove(`drawio-maximized-open`),this.maximizedRoot&&this.maximizedRoot.childElementCount===0&&(this.maximizedRoot.hidden=!0)}_syncMaximizeButtons(){this.embedEntries.forEach(e=>{let t=e.wrapper?.querySelector(`.drawio-embed-btn[data-action="toggle-maximize"]`);if(!(t instanceof HTMLElement))return;let n=this.maximizedEntry?.key===e.key;P(t,n?`restore`:`maximize`),t.title=n?`Restore diagram size`:`Maximize diagram`,t.setAttribute(`aria-label`,n?`Restore diagram size`:`Maximize diagram`)})}_findEntryByInstanceId(e){for(let t of this.embedEntries.values())if(t.instanceId===e)return t;return null}_onMessage(e){let t=e.data;if(!t||t.source!==`drawio-editor`)return;let n=this._findEntryByInstanceId(t.instanceId);if(n){if(t.type===`fallback-text`){if(n.mode===`view`){this.renderViewerFallback(n,`Failed to render draw.io preview`);return}this.onOpenTextFile?.(n.filePath);return}if(t.type===`error`){if(n.mode===`view`){this.renderViewerFallback(n,t.message||`Failed to load draw.io preview`);return}this.toastController?.show?.(t.message||`Failed to load draw.io`);return}t.type===`request-open-file`&&this.onOpenFile?.(n.filePath)}}_onPreviewClick(e){let t=e.target.closest(`.drawio-embed-placeholder-btn`);if(t){let n=t.closest(`.drawio-embed-placeholder`)?.dataset.drawioKey||``,r=this.embedEntries.get(n);r&&(e.preventDefault(),this.hydrateEntry(r));return}}_onKeyDown(e){e.key===`Escape`&&(this._exitMaximizedEntry(),this._syncMaximizeButtons())}renderViewerFallback(e,t){if(!e.wrapper)return;let n=e.wrapper.querySelector(`.drawio-viewer-shell, .drawio-viewer-frame`);if(!n)return;let r=document.createElement(`div`);r.className=`preview-shell`,r.textContent=t,n.replaceChildren(r),e.viewerElement=r}};function jo(e,t){let n=new Map;t.forEach(t=>{let r=e.get(t.key)??{filePath:t.filePath,iframe:null,instanceId:null,key:t.key,label:t.label,placeholder:t.placeholder,queued:!1,wrapper:null};r.filePath=t.filePath,r.key=t.key,r.label=t.label,r.placeholder=t.placeholder,n.set(t.key,r)});let r=[];return e.forEach((e,t)=>{n.has(t)||r.push(e)}),{nextEntries:n,removedEntries:r}}var Mo=420,No=500,Po=15e3,Fo=800,Io=3,Lo=200,Ro=`/excalidraw-editor.html`;function zo(e,t){return typeof window.requestIdleCallback==`function`?window.requestIdleCallback(e,{timeout:t}):window.setTimeout(()=>{e({didTimeout:!1,timeRemaining:()=>0})},1)}function Bo(e){if(e!==null){if(typeof window.cancelIdleCallback==`function`){window.cancelIdleCallback(e);return}window.clearTimeout(e)}}function Vo(e,t,n){if(!e||!t)return!1;let r=t.getBoundingClientRect(),i=e.getBoundingClientRect();return i.bottom>=r.top-n&&i.top<=r.bottom+n}var Ho=class{constructor({getTheme:e,getLocalUser:t,onOpenFile:n=null,previewContainer:r,previewElement:i,toastController:a}){this.getTheme=e,this.getLocalUser=t,this.onOpenFile=n,this.previewContainer=r,this.previewElement=i,this.toastController=a,this.embedEntries=new Map,this.hydrationQueue=[],this.hydrationIdleId=null,this.hydrationPaused=!1,this.hydrationInProgress=!1,this.instanceCounter=0,this.isLargeDocument=!1,this.maximizedEmbed=null,this.overlayRoot=null,this.maximizedRoot=null,this.warmCacheRoot=null,this.warmEntry=null,this.placeholderObserver=null,this.followedPeerIdsByFilePath=new Map,this.pendingDisconnectRequests=new Map,this.disconnectRequestCounter=0,this._onMessage=this._onMessage.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onPreviewClick=this._onPreviewClick.bind(this),window.addEventListener(`message`,this._onMessage),window.addEventListener(`keydown`,this._onKeyDown),this.previewElement?.addEventListener(`click`,this._onPreviewClick)}destroy(){window.removeEventListener(`message`,this._onMessage),window.removeEventListener(`keydown`,this._onKeyDown),this.previewElement?.removeEventListener(`click`,this._onPreviewClick),this._disconnectPlaceholderObserver(),Bo(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this._exitMaximizedEmbed(),document.body.classList.remove(`excalidraw-maximized-open`),this.embedEntries.forEach(e=>{this._clearEntryBootTimeout(e),e.wrapper?.remove(),e.placeholder=null}),this.embedEntries.clear(),this.warmEntry&&=(this._clearEntryBootTimeout(this.warmEntry),this.warmEntry.wrapper?.remove(),null),this.pendingDisconnectRequests.forEach(e=>{e.resolve(!1)}),this.pendingDisconnectRequests.clear(),this.followedPeerIdsByFilePath.clear(),this.overlayRoot?.remove(),this.overlayRoot=null,this.maximizedRoot?.remove(),this.maximizedRoot=null,this.warmCacheRoot?.remove(),this.warmCacheRoot=null}async setFollowedUser(e,t=null){if(!e)return!1;this.followedPeerIdsByFilePath.set(e,t||null);let n=this._findEntryByFilePath(e);return n?(n.wrapper||await this._hydrateEntry(n),n.followedPeerId=this.followedPeerIdsByFilePath.get(e)??null,this._syncEntryFollowState(n),!0):!0}detachForCommit(){this._disconnectPlaceholderObserver(),Bo(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this.hydrationInProgress=!1,this.overlayRoot&&(this.overlayRoot.hidden=!0),this.maximizedRoot&&(this.maximizedRoot.hidden=!0),this.embedEntries.forEach(e=>{e.queued=!1,e.placeholder=null})}setHydrationPaused(e){if(this.hydrationPaused=!!e,this.hydrationPaused){Bo(this.hydrationIdleId),this.hydrationIdleId=null;return}this.hydrateVisibleEmbeds(),this._scheduleHydration()}reconcileEmbeds(e,{isLargeDocument:t=!1}={}){this.isLargeDocument=!!t,this._disconnectPlaceholderObserver(),Bo(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this.hydrationInProgress=!1;let n=Array.from(e.querySelectorAll(`.excalidraw-embed-placeholder[data-embed-key]`)).map(e=>({filePath:e.dataset.embedTarget,key:e.dataset.embedKey,label:e.dataset.embedLabel||e.dataset.embedTarget,placeholder:e})),{nextEntries:r,removedEntries:i}=jo(this.embedEntries,n);this._captureWarmEntry(i),this._adoptReusableEntries(r,i),i.forEach(e=>this._destroyEntry(e)),this.embedEntries=r,this._ensurePlaceholderObserver(),this.embedEntries.forEach(e=>{if(e.queued=!1,e.followedPeerId=this.followedPeerIdsByFilePath.get(e.filePath),e.wrapper){this._hydrateEntry(e);return}e.placeholder&&this.placeholderObserver?.observe(e.placeholder)}),this.hydrationPaused||this.hydrateVisibleEmbeds(),this.syncLayout()}hydrateVisibleEmbeds(){if(this.hydrationPaused)return;let e=this.isLargeDocument?180:420;this.embedEntries.forEach(t=>{t.wrapper||!t.placeholder?.isConnected||Vo(t.placeholder,this.previewContainer,e)&&this._enqueueHydration(t,{prioritize:!0})})}updateTheme(e){this._forEachManagedEntry(t=>{this._postMessageToEntry(t,{source:`collabmd-host`,type:`set-theme`,theme:e})})}updateLocalUser(e){this._forEachManagedEntry(t=>{this._syncEntryUser(t,e)})}prepareFileDisconnect(e,{timeoutMs:t=250}={}){let n=this._findEntryByFilePath(e);if(!n?.iframe?.contentWindow)return Promise.resolve(!1);let r=`disconnect-${++this.disconnectRequestCounter}`;return new Promise(e=>{let i=t=>{if(!this.pendingDisconnectRequests.has(r))return;let n=this.pendingDisconnectRequests.get(r);window.clearTimeout(n.timeoutId),this.pendingDisconnectRequests.delete(r),e(t)},a=window.setTimeout(()=>{i(!1)},t);this.pendingDisconnectRequests.set(r,{entry:n,resolve:i,timeoutId:a}),this._postMessageToEntry(n,{source:`collabmd-host`,type:`prepare-disconnect`,requestId:r})})}_ensurePlaceholderObserver(){this.previewContainer&&(this.placeholderObserver=new IntersectionObserver(e=>{e.forEach(e=>{if(!e.isIntersecting)return;let t=this.embedEntries.get(e.target.dataset.embedKey);t&&this._enqueueHydration(t)})},{root:this.previewContainer,rootMargin:this.isLargeDocument?`180px 0px`:`420px 0px`}))}_disconnectPlaceholderObserver(){this.placeholderObserver&&=(this.placeholderObserver.disconnect(),null)}_enqueueHydration(e,{prioritize:t=!1}={}){if(!(!e||e.wrapper||e.queued)&&(e.queued=!0,t?this.hydrationQueue.unshift(e.key):this.hydrationQueue.push(e.key),!this.hydrationPaused)){if(t&&!this.hydrationInProgress&&this.hydrationIdleId===null){this._flushHydrationQueue();return}this._scheduleHydration()}}_scheduleHydration(){this.hydrationPaused||this.hydrationInProgress||this.hydrationIdleId!==null||(this.hydrationIdleId=zo(()=>{this.hydrationIdleId=null,this._flushHydrationQueue()},No))}async _flushHydrationQueue(){if(this.hydrationPaused||this.hydrationInProgress)return;let e=null;for(;this.hydrationQueue.length>0&&!e;){let t=this.hydrationQueue.shift(),n=this.embedEntries.get(t);if(!n||n.wrapper||!n.placeholder?.isConnected){n&&(n.queued=!1);continue}e=n}e&&(this.hydrationInProgress=!0,e.queued=!1,await this._hydrateEntry(e),this.hydrationInProgress=!1,this.hydrationQueue.length>0&&this._scheduleHydration())}async _hydrateEntry(e){if(!(!e.placeholder?.isConnected&&!e.wrapper)){if(e.isParked=!1,!e.wrapper){let t=this._createEmbedContainer(e);e.header=t.header,e.wrapper=t.wrapper,e.iframe=t.iframe,e.labelElement=t.labelElement,e.maxButton=t.maxButton,e.openButton=t.openButton,e.instanceId=t.instanceId,e.isReady=!1,e.bootFilePath=e.filePath,e.bootMode=this._getEntryMode(e),e.loadedFilePath=e.bootFilePath,e.loadedMode=e.bootMode,e.bootAttempts=(e.bootAttempts??0)+1,this._armEntryBootTimeout(e)}e.followedPeerId=this.followedPeerIdsByFilePath.get(e.filePath),this._updateEmbedLabel(e),this._entryNeedsHardReload(e)&&this._reloadEntry(e),this._attachWrapper(e)}}_attachWrapper(e){let t=e.placeholder?.isConnected?e.placeholder:this.previewElement?.querySelector(`.excalidraw-embed-placeholder[data-embed-key="${e.key}"]`);if(!t)return;if(e.placeholder=t,this._syncMountedEntryMetadata(e),this._shouldInlineFilePreview(e)){e.wrapper.style.position=``,e.wrapper.style.top=``,e.wrapper.style.left=``,e.wrapper.style.width=``,e.wrapper.style.margin=``,e.wrapper.style.pointerEvents=`auto`,t.replaceWith(e.wrapper),e.placeholder=null;return}let n=this._ensureOverlayRoot();n.hidden=!1,e.wrapper?.parentElement!==n&&n.appendChild(e.wrapper),this._syncEntryLayout(e)}_adoptReusableEntries(e,t){e.forEach((n,r)=>{if(n.wrapper||n.iframe)return;let i=this._claimReusableEntry(n,t);i&&(i.filePath=n.filePath,i.key=n.key,i.label=n.label,i.placeholder=n.placeholder,i.queued=!1,e.set(r,i))})}_destroyEntry(e){this.pendingDisconnectRequests.forEach((t,n)=>{t.entry===e&&(t.resolve(!1),this.pendingDisconnectRequests.delete(n))}),this.maximizedEmbed?.wrapper===e.wrapper&&this._exitMaximizedEmbed(),this._clearEntryBootTimeout(e),this.warmEntry===e&&(this.warmEntry=null),this._resetPlaceholderLayout(e),this._setEntryLoadingState(e,!1),e.wrapper?.remove(),e.placeholder=null}_armEntryBootTimeout(e,t=Po){this._clearEntryBootTimeout(e),e.bootTimerId=window.setTimeout(()=>{this._handleEntryBootTimeout(e)},t)}_clearEntryBootTimeout(e){e?.bootTimerId&&(window.clearTimeout(e.bootTimerId),e.bootTimerId=null)}async _handleEntryBootTimeout(e){if(e?.iframe?.isConnected){if((e.bootAttempts??0)>=Io){this._clearEntryBootTimeout(e),this.toastController?.show(`Excalidraw embed timed out: ${e.label}`);return}await this._retryEntryBootstrap(e)}}async _retryEntryBootstrap(e){e&&(this._clearEntryBootTimeout(e),this._resetPlaceholderLayout(e),this._setEntryLoadingState(e,!1),this.maximizedEmbed?.wrapper===e.wrapper&&this._exitMaximizedEmbed(),e.wrapper?.remove(),e.wrapper=null,e.iframe=null,e.header=null,e.labelElement=null,e.maxButton=null,e.openButton=null,e.instanceId=null,e.isReady=!1,e.isParked=!1,e.bootFilePath=null,e.bootMode=null,e.loadedFilePath=null,e.loadedMode=null,await this._hydrateEntry(e))}_findEntryByContentWindow(e){if(!e)return null;for(let t of this.embedEntries.values())if(t.iframe?.contentWindow===e)return t;return this.warmEntry?.iframe?.contentWindow===e?this.warmEntry:null}_findEntryByFilePath(e){if(!e)return null;for(let t of this.embedEntries.values())if(t.filePath===e)return t;return this.warmEntry?.filePath===e?this.warmEntry:null}_updateEmbedLabel(e){e.labelElement&&(e.labelElement.textContent=e.label.replace(/\.excalidraw$/i,``))}_syncMountedEntryMetadata(e){e.wrapper&&(e.wrapper.dataset.embedKey=e.key,e.wrapper.dataset.file=e.filePath,e.wrapper.classList.toggle(`is-direct-file`,this._isFilePreviewEntry(e))),e.iframe&&(e.iframe.title=`Excalidraw: ${e.filePath}`),e.openButton&&(this._isFilePreviewEntry(e)?e.openButton.remove():!e.openButton.isConnected&&e.header&&e.header.insertBefore(e.openButton,e.maxButton||null))}_buildIframeUrl(e){let t=new URL(w(Ro)),n=this.getTheme?.()||`dark`;t.searchParams.set(`file`,e.filePath),t.searchParams.set(`theme`,n),t.searchParams.set(`boot`,e.instanceId||``),this._isFilePreviewEntry(e)||t.searchParams.set(`mode`,`preview`);let r=this.getLocalUser?.();r?.name&&t.searchParams.set(`userName`,r.name),r?.color&&t.searchParams.set(`userColor`,r.color),r?.colorLight&&t.searchParams.set(`userColorLight`,r.colorLight),r?.peerId&&t.searchParams.set(`userPeerId`,r.peerId);let i=new URLSearchParams(window.location.search),a=i.get(`server`);return a&&t.searchParams.set(`server`,a),i.get(`test`)===`1`&&t.searchParams.set(`test`,`1`),i.has(`syncTimeoutMs`)&&t.searchParams.set(`syncTimeoutMs`,i.get(`syncTimeoutMs`)),t}_createEmbedContainer(e){let t=document.createElement(`div`);t.className=`excalidraw-embed diagram-preview-shell`,t.dataset.embedKey=e.key,t.dataset.file=e.filePath;let n=document.createElement(`div`);n.className=`excalidraw-embed-header diagram-preview-toolbar`;let r=document.createElement(`span`);r.className=`excalidraw-embed-icon`,r.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19l7-7 3 3-7 7-3-3z"/><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><path d="M2 2l7.586 7.586"/><circle cx="11" cy="11" r="2"/></svg>`;let i=document.createElement(`span`);i.className=`excalidraw-embed-label`,i.textContent=e.label.replace(/\.excalidraw$/i,``);let a=document.createElement(`button`);a.type=`button`,a.className=`excalidraw-embed-btn ui-preview-action ui-preview-action--icon-only`,a.title=`Edit in Excalidraw`,a.setAttribute(`aria-label`,`Edit in Excalidraw`),P(a,`edit`);let o=document.createElement(`button`);o.type=`button`,o.className=`excalidraw-embed-btn ui-preview-action ui-preview-action--icon-only`,o.title=`Maximize diagram`,o.setAttribute(`aria-label`,`Maximize diagram`),P(o,`maximize`),n.append(r,i),this._isFilePreviewEntry(e)||n.append(a),n.append(o);let s=document.createElement(`iframe`);s.className=`excalidraw-embed-iframe`,s.dataset.instanceId=String(++this.instanceCounter),e.instanceId=s.dataset.instanceId,s.src=this._buildIframeUrl(e).toString(),s.setAttribute(`loading`,`eager`),s.title=`Excalidraw: ${e.filePath}`,s.style.height=`${Mo}px`;let c=document.createElement(`div`);c.className=`excalidraw-embed-resizer`,c.title=`Drag to resize`,this._setupResizer(c,s,()=>this._syncEntryLayout(e)),t.append(n,s,c);let l=!1,u=`${Mo}px`,d=()=>{P(o,l?`restore`:`maximize`),o.title=l?`Restore diagram size`:`Maximize diagram`,o.setAttribute(`aria-label`,l?`Restore diagram size`:`Maximize diagram`)},f=()=>{l&&(l=!1,t.classList.remove(`is-maximized`),d(),document.body.classList.remove(`excalidraw-maximized-open`),this._restoreWrapperMount(e),s.style.height=u,this.maximizedEmbed?.wrapper===t&&(this.maximizedEmbed=null),this._syncEntryLayout(e))},p=()=>{l||(this._exitMaximizedEmbed(),l=!0,u=s.style.height||`${Mo}px`,this._mountWrapperInMaximizedRoot(e),t.classList.add(`is-maximized`),d(),document.body.classList.add(`excalidraw-maximized-open`),this.maximizedEmbed={wrapper:t,exit:f},this._syncEntryLayout(e))};return o.addEventListener(`click`,()=>{l?f():p()}),a.addEventListener(`click`,()=>{this.onOpenFile?.(e.filePath)}),d(),{header:n,iframe:s,instanceId:s.dataset.instanceId,labelElement:i,maxButton:o,openButton:a,wrapper:t}}_ensureWarmCacheRoot(){if(this.warmCacheRoot?.isConnected&&this.warmCacheRoot.parentElement===document.body)return this.warmCacheRoot;let e=document.body.querySelector(`[data-excalidraw-warm-cache-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.excalidrawWarmCacheRoot=`true`,e.className=`excalidraw-warm-cache-root`,document.body.appendChild(e)),this.warmCacheRoot=e,e}_setupResizer(e,t,n=null){let r=0,i=0,a=e=>{let n=e.clientY-r,a=Math.min(Math.max(i+n,Lo),Fo);t.style.height=`${a}px`,t.style.pointerEvents=`none`},o=()=>{t.style.pointerEvents=``,document.removeEventListener(`pointermove`,a),document.removeEventListener(`pointerup`,o),n?.()};e.addEventListener(`pointerdown`,e=>{e.preventDefault(),r=e.clientY,i=t.offsetHeight,document.addEventListener(`pointermove`,a),document.addEventListener(`pointerup`,o)})}_ensureOverlayRoot(){if(this.overlayRoot?.isConnected&&this.overlayRoot.parentElement===this.previewElement)return this.overlayRoot;let e=this.previewElement?.querySelector(`[data-excalidraw-overlay-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.excalidrawOverlayRoot=`true`,e.className=`excalidraw-embed-overlay-root`,this.previewElement?.appendChild(e)),this.overlayRoot=e,e}_ensureMaximizedRoot(){if(this.maximizedRoot?.isConnected&&this.maximizedRoot.parentElement===document.body)return this.maximizedRoot;let e=document.body.querySelector(`[data-excalidraw-maximized-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.excalidrawMaximizedRoot=`true`,e.className=`excalidraw-maximized-root`,document.body.appendChild(e)),this.maximizedRoot=e,e}_isFilePreviewEntry(e){return e?.key===`${e?.filePath}#file-preview`}_getEntryMode(e){return this._isFilePreviewEntry(e)?`edit`:`preview`}_shouldInlineFilePreview(e){return this._isFilePreviewEntry(e)}_entryNeedsHardReload(e){let t=this._getEntryMode(e);return!!(e?.wrapper&&e.iframe&&(e.isReady?e.loadedFilePath!==e.filePath||e.loadedMode!==t:e.bootFilePath!==e.filePath||e.bootMode!==t))}_setEntryLoadingState(e,t){e?.wrapper&&(e.wrapper.classList.toggle(`is-loading`,!!t),e.wrapper.setAttribute(`aria-busy`,t?`true`:`false`))}_forEachManagedEntry(e){let t=new Set;this.embedEntries.forEach(n=>{!n||t.has(n)||(t.add(n),e(n))}),this.warmEntry&&!t.has(this.warmEntry)&&e(this.warmEntry)}_claimEntryFromRemovedEntries(e,t){let n=e.findIndex(e=>(e.wrapper||e.iframe)&&t(e));if(n<0)return null;let[r]=e.splice(n,1);return r}_claimReusableEntry(e,t){let n=this._getEntryMode(e);return this._claimEntryFromRemovedEntries(t,t=>t.filePath===e.filePath&&this._getEntryMode(t)===n)||(this._isFilePreviewEntry(e)?this._claimEntryFromRemovedEntries(t,t=>t.filePath===e.filePath)||this._claimWarmEntry()||this._claimEntryFromRemovedEntries(t,e=>this._isFilePreviewEntry(e)):null)}_claimWarmEntry(){let e=this.warmEntry;return e?(this.warmEntry=null,e):null}_captureWarmEntry(e){let t=this._claimEntryFromRemovedEntries(e,e=>this._isFilePreviewEntry(e));t&&(this.warmEntry&&this.warmEntry!==t&&this._destroyEntry(this.warmEntry),this.warmEntry=t,this._parkWarmEntry(t))}_parkWarmEntry(e){if(!e?.wrapper)return;this.maximizedEmbed?.wrapper===e.wrapper&&this._exitMaximizedEmbed();let t=this._ensureWarmCacheRoot();this._setEntryLoadingState(e,!1),e.isParked=!0,e.isReady=!1,e.bootFilePath=null,e.bootMode=null,e.loadedFilePath=null,e.loadedMode=null,e.placeholder=null,e.wrapper.parentElement!==t&&t.appendChild(e.wrapper),this._postMessageToEntry(e,{source:`collabmd-host`,type:`park-room`})}_reloadEntry(e){e?.iframe&&(this._clearEntryBootTimeout(e),this._setEntryLoadingState(e,!0),e.isReady=!1,e.bootAttempts=(e.bootAttempts??0)+1,e.bootFilePath=e.filePath,e.bootMode=this._getEntryMode(e),e.loadedFilePath=null,e.loadedMode=null,e.iframe.src=this._buildIframeUrl(e).toString(),this._armEntryBootTimeout(e))}_resetPlaceholderLayout(e){!e?.placeholder?.isConnected||this._shouldInlineFilePreview(e)||(e.placeholder.classList.remove(`is-hydrated`),e.placeholder.removeAttribute(`data-embed-hydrated`),e.placeholder.style.height=``,e.placeholder.style.pointerEvents=``)}_mountWrapperInMaximizedRoot(e){if(!e?.wrapper)return;let t=this._ensureMaximizedRoot();t.hidden=!1,e.restoreParent=e.wrapper.parentElement||null,e.restoreNextSibling=e.wrapper.nextSibling||null,e.wrapper.style.position=``,e.wrapper.style.top=``,e.wrapper.style.left=``,e.wrapper.style.width=``,e.wrapper.style.margin=``,e.wrapper.parentElement!==t&&t.appendChild(e.wrapper)}_restoreWrapperMount(e){if(e?.wrapper){if(this._shouldInlineFilePreview(e)){let{restoreParent:t,restoreNextSibling:n}=e;t?.isConnected&&(n?.parentElement===t?t.insertBefore(e.wrapper,n):t.appendChild(e.wrapper))}else{let t=this._ensureOverlayRoot();t.hidden=!1,e.wrapper.parentElement!==t&&t.appendChild(e.wrapper)}e.restoreParent=null,e.restoreNextSibling=null,this.maximizedRoot&&this.maximizedRoot.childElementCount===0&&(this.maximizedRoot.hidden=!0)}}_syncEntryLayout(e){if(!e?.wrapper||this._shouldInlineFilePreview(e))return;let t=e.placeholder?.isConnected?e.placeholder:this.previewElement?.querySelector(`.excalidraw-embed-placeholder[data-embed-key="${e.key}"]`);if(!t)return;e.placeholder=t,t.classList.add(`is-hydrated`),t.dataset.embedHydrated=`true`,t.style.pointerEvents=`none`,this._isFilePreviewEntry(e)&&t.childElementCount>0&&t.replaceChildren();let n=e.wrapper.classList.contains(`is-maximized`),r=e.wrapper.querySelector(`.excalidraw-embed-header`)?.offsetHeight||0,i=e.iframe?.offsetHeight||Number.parseFloat(e.iframe?.style.height||``)||Mo,a=n?0:e.wrapper.querySelector(`.excalidraw-embed-resizer`)?.offsetHeight||0,o=Math.ceil(r+i+a);if(n||(e.inlineHeightPx=o),t.style.height=`${Math.ceil(e.inlineHeightPx||o||Mo)}px`,e.wrapper.style.pointerEvents=`auto`,n){e.wrapper.style.position=``,e.wrapper.style.top=``,e.wrapper.style.left=``,e.wrapper.style.width=``,e.wrapper.style.margin=``;return}e.wrapper.style.position=`absolute`,e.wrapper.style.top=`${t.offsetTop}px`,e.wrapper.style.left=`${t.offsetLeft}px`,e.wrapper.style.width=`${t.offsetWidth}px`,e.wrapper.style.margin=`0`}syncLayout(){this.embedEntries.forEach(e=>{e.wrapper&&!this._shouldInlineFilePreview(e)&&this._syncEntryLayout(e)})}_onPreviewClick(e){let t=e.target.closest(`.excalidraw-embed-placeholder-btn`);if(!t)return;e.preventDefault();let n=this.embedEntries.get(t.dataset.embedKey);n&&this._hydrateEntry(n)}_onMessage(e){if(e.origin!==window.location.origin)return;let t=e.data;if(!t||t.source!==`excalidraw-editor`)return;let n=this._findEntryByContentWindow(e.source);if(n){if(t.type===`ready`){if(n.isParked)return;n.isReady=!0,this._clearEntryBootTimeout(n),n.loadedFilePath=n.bootFilePath||n.filePath,n.loadedMode=n.bootMode||this._getEntryMode(n),this._setEntryLoadingState(n,!1),this._syncEntryUser(n),this._postMessageToEntry(n,{source:`collabmd-host`,type:`set-theme`,theme:this.getTheme?.()||`dark`}),this._syncEntryFollowState(n),this._entryNeedsHardReload(n)&&this._hydrateEntry(n);return}if(t.type===`error`){if(n.isParked)return;n.isReady=!1,this._handleEntryBootTimeout(n);return}if(t.type===`disconnect-ready`){let e=this.pendingDisconnectRequests.get(t.requestId);e?.entry===n&&e.resolve(!0)}}}_onKeyDown(e){e.key===`Escape`&&this._exitMaximizedEmbed()}_exitMaximizedEmbed(){this.maximizedEmbed?.exit&&this.maximizedEmbed.exit(),this.maximizedEmbed=null,document.body.classList.remove(`excalidraw-maximized-open`)}_postMessageToEntry(e,t){e?.iframe?.contentWindow?.postMessage(t,window.location.origin)}_syncEntryUser(e,t=null){let n=t||this.getLocalUser?.();n&&this._postMessageToEntry(e,{source:`collabmd-host`,type:`set-user`,user:{color:n.color||``,colorLight:n.colorLight||``,name:n.name||``,peerId:n.peerId||``}})}_syncEntryFollowState(e){!e?.isReady||e.followedPeerId===void 0||this._postMessageToEntry(e,{source:`collabmd-host`,type:`follow-user`,peerId:e.followedPeerId})}};function Uo(){return typeof window>`u`||typeof window.matchMedia!=`function`?{matches:!1}:window.matchMedia(`(max-width: 768px)`)}function Wo(e){return typeof HTMLElement>`u`||!(e instanceof HTMLElement)?[]:Array.from(e.querySelectorAll(`.create-menu-item`))}var Go=class{constructor({mobileBreakpointQuery:e=Uo()}={}){this.mobileBreakpointQuery=e,this.activeAnchor=null,this.desktopMenu=null,this.mobileBackdrop=null,this.mobileSheet=null,this.documentPointerDownHandler=null,this.windowResizeHandler=null,this.boundClose=()=>this.close()}isMobileViewport(){return!!this.mobileBreakpointQuery?.matches}isOpen(){return!!(this.desktopMenu||this.mobileSheet)}toggle(e={}){if(this.isOpen()){this.close();return}this.open(e)}open({anchor:e=null,items:t=[],title:n=`Create`}={}){if(this.close({restoreFocus:!1}),!(!Array.isArray(t)||t.length===0)){if(this.activeAnchor=typeof HTMLElement<`u`&&e instanceof HTMLElement?e:null,this.activeAnchor?.setAttribute(`aria-expanded`,`true`),this.isMobileViewport()){this.openMobileSheet({items:t,title:n});return}this.openDesktopMenu({anchor:this.activeAnchor,items:t,title:n})}}close({restoreFocus:e=!0}={}){this.desktopMenu&&=(this.desktopMenu.remove(),null),this.mobileBackdrop&&=(this.mobileBackdrop.remove(),null),this.mobileSheet&&=(this.mobileSheet.remove(),null),this.documentPointerDownHandler&&=(document.removeEventListener(`pointerdown`,this.documentPointerDownHandler),null),this.windowResizeHandler&&typeof window<`u`&&window.removeEventListener(`resize`,this.windowResizeHandler),this.windowResizeHandler=null;let t=this.activeAnchor;this.activeAnchor?.setAttribute(`aria-expanded`,`false`),this.activeAnchor=null,e&&t?.focus?.()}openDesktopMenu({anchor:e,items:t,title:n}){let r=document.createElement(`div`);r.className=`create-menu`,r.setAttribute(`role`,`menu`),r.setAttribute(`aria-label`,n),this.renderMenuItems(r,t),document.body.appendChild(r),this.positionDesktopMenu(r,e),r.addEventListener(`keydown`,e=>{this.handleDesktopMenuKeyDown(e,r)}),this.documentPointerDownHandler=t=>{r.contains(t.target)||e?.contains?.(t.target)||this.close()},this.windowResizeHandler=this.boundClose,setTimeout(()=>{document.addEventListener(`pointerdown`,this.documentPointerDownHandler)},0),typeof window<`u`&&window.addEventListener(`resize`,this.windowResizeHandler),this.desktopMenu=r,Wo(r)[0]?.focus()}openMobileSheet({items:e,title:t}){let n=document.createElement(`button`);n.type=`button`,n.className=`file-action-sheet-backdrop`,n.setAttribute(`aria-label`,`Close ${t.toLowerCase()} menu`);let r=document.createElement(`div`);r.className=`file-action-sheet create-action-sheet`;let i=document.createElement(`div`);i.className=`create-action-sheet-header`,i.textContent=t,r.appendChild(i),this.renderMenuItems(r,e,{mobile:!0});let a=document.createElement(`button`);a.type=`button`,a.className=G({variant:`ghost`,extra:[`file-action-sheet-item`,`create-action-sheet-cancel`]}),a.textContent=`Cancel`,a.addEventListener(`click`,()=>{this.close()}),r.appendChild(a),n.addEventListener(`click`,()=>{this.close()}),document.body.append(n,r),this.mobileBackdrop=n,this.mobileSheet=r}renderMenuItems(e,t,{mobile:n=!1}={}){let r=null;t.forEach(t=>{if(t.group&&t.group!==r){let i=document.createElement(`div`);i.className=n?`create-action-sheet-group`:`create-menu-group`,i.textContent=t.group,e.appendChild(i),r=t.group}let i=document.createElement(`button`);i.type=`button`,i.className=n?G({variant:`ghost`,extra:[`file-action-sheet-item`,`create-action-sheet-item`,`create-action-sheet-option`]}):`create-menu-item`,i.setAttribute(`role`,n?`button`:`menuitem`),i.dataset.actionId=t.id;let a=document.createElement(`span`);a.className=`create-menu-item-icon`,a.setAttribute(`aria-hidden`,`true`),a.innerHTML=t.icon||``,i.appendChild(a);let o=document.createElement(`span`);o.className=`create-menu-item-copy`;let s=document.createElement(`span`);s.className=`create-menu-item-label`,s.textContent=t.label,o.appendChild(s);let c=t.meta||t.hint;if(c){let e=document.createElement(`span`);e.className=`create-menu-item-meta`,e.textContent=c,o.appendChild(e)}i.appendChild(o),i.addEventListener(`click`,()=>{this.close({restoreFocus:!1}),t.onSelect?.()}),e.appendChild(i)})}positionDesktopMenu(e,t){let n=e.getBoundingClientRect(),r=t?.getBoundingClientRect?.(),i=r?.left??8,a=Math.max(8,window.innerWidth-n.width-8),o=Math.max(8,Math.min(i,a)),s=(r?.bottom??8)+8,c=window.innerHeight-n.height-8;s>c&&r&&(s=Math.max(8,r.top-n.height-8)),e.style.left=`${o}px`,e.style.top=`${Math.max(8,s)}px`}handleDesktopMenuKeyDown(e,t){let n=Wo(t);if(n.length===0)return;let r=Math.max(0,n.indexOf(document.activeElement));switch(e.key){case`ArrowDown`:e.preventDefault(),n[(r+1)%n.length]?.focus();break;case`ArrowUp`:e.preventDefault(),n[(r-1+n.length)%n.length]?.focus();break;case`Home`:e.preventDefault(),n[0]?.focus();break;case`End`:e.preventDefault(),n[n.length-1]?.focus();break;case`Escape`:e.preventDefault(),this.close();break;case`Tab`:this.close({restoreFocus:!1});break}}};function Ko(e){return String(e??``).replace(/\/+$/u,``).split(`/`).filter(Boolean).pop()||``}function qo(e){let t=String(e??``).replace(/\/+$/u,``),n=t.lastIndexOf(`/`);return n>=0?t.slice(0,n):``}function Jo(e,t,n){return e===t?n:`${n}${e.slice(t.length)}`}function Yo(e,t,n){return`${e} ${e===1?t:n}`}function Xo(){return JSON.stringify({type:`excalidraw`,version:2,source:`collabmd`,elements:[],appState:{viewBackgroundColor:`#ffffff`,gridSize:null},files:{}})}function Zo(e,t){return t?{...e,requestId:t}:e}var Qo=class{constructor({mobileBreakpointQuery:e=typeof window<`u`&&typeof window.matchMedia==`function`?window.matchMedia(`(max-width: 768px)`):{matches:!1},onFileDelete:t,onFileSelect:n,pendingWorkspaceRequestIds:r=null,state:i,toastController:a,vaultClient:o,view:s,refresh:c}){this.onFileDelete=t,this.onFileSelect=n,this.pendingWorkspaceRequestIds=r,this.state=i,this.toastController=a,this.vaultClient=o,this.view=s,this.refresh=c,this.createButton=document.getElementById(`sidebarCreateBtn`),this.refreshButton=document.getElementById(`refreshFilesBtn`),this.actionDialog=document.getElementById(`fileActionDialog`),this.actionForm=document.getElementById(`fileActionForm`),this.actionTitle=document.getElementById(`fileActionTitle`),this.actionCopy=document.getElementById(`fileActionCopy`),this.actionField=document.getElementById(`fileActionField`),this.actionLabel=document.getElementById(`fileActionLabel`),this.actionInput=document.getElementById(`fileActionInput`),this.actionHint=document.getElementById(`fileActionHint`),this.actionNote=document.getElementById(`fileActionNote`),this.actionCancelButton=document.getElementById(`fileActionCancel`),this.actionSubmitButton=document.getElementById(`fileActionSubmit`),this.createMenu=new Go({mobileBreakpointQuery:e}),this.pendingAction=null,this.actionBusy=!1}initialize(){this.createButton?.addEventListener(`click`,()=>{this.openRootCreateMenu({anchor:this.createButton})}),this.refreshButton?.addEventListener(`click`,()=>this.refresh()),this.actionCancelButton?.addEventListener(`click`,()=>this.closeActionDialog()),this.actionForm?.addEventListener(`submit`,e=>{e.preventDefault(),this.handleActionSubmit()}),this.actionDialog?.addEventListener(`close`,()=>this.resetActionDialog())}getCreateActions({parentDir:e=``}={}){return[{contextLabel:`New markdown file`,group:`Note`,hint:`Markdown`,icon:this.getCreateActionIcon(`markdown`),id:`markdown`,label:`Markdown note`,meta:`.md`,onSelect:()=>this.handleNewFile({parentDir:e})},{contextLabel:`New base file`,group:`Note`,hint:`Base`,icon:this.getCreateActionIcon(`base`),id:`base`,label:`Base file`,meta:`.base`,onSelect:()=>this.handleNewBase({parentDir:e})},{contextLabel:`New Excalidraw drawing`,group:`Diagram`,hint:`Excalidraw`,icon:this.getCreateActionIcon(`excalidraw`),id:`excalidraw`,label:`Excalidraw drawing`,meta:`.excalidraw`,onSelect:()=>this.handleNewDrawing({parentDir:e})},{contextLabel:`New draw.io diagram`,group:`Diagram`,hint:`draw.io`,icon:this.getCreateActionIcon(`drawio`),id:`drawio`,label:`draw.io diagram`,meta:`.drawio`,onSelect:()=>this.handleNewDrawio({parentDir:e})},{contextLabel:`New Mermaid diagram`,group:`Diagram`,hint:`Mermaid`,icon:this.getCreateActionIcon(`mermaid`),id:`mermaid`,label:`Mermaid diagram`,meta:`.mmd`,onSelect:()=>this.handleNewMermaid({parentDir:e})},{contextLabel:`New PlantUML diagram`,group:`Diagram`,hint:`PlantUML`,icon:this.getCreateActionIcon(`plantuml`),id:`plantuml`,label:`PlantUML diagram`,meta:`.puml`,onSelect:()=>this.handleNewPlantUml({parentDir:e})},{contextLabel:`New folder`,group:`Structure`,hint:`Folder`,icon:this.getCreateActionIcon(`folder`),id:`folder`,label:`Folder`,meta:`folder`,onSelect:()=>this.handleNewFolder({parentDir:e})}]}createContextMenuItems(e=``){return this.getCreateActions({parentDir:e}).map(e=>({label:e.contextLabel,onSelect:e.onSelect}))}getDirectoryContextMenuItems(e){return[...this.createContextMenuItems(e),{label:`Rename / move`,onSelect:()=>this.handleRenameDirectory(e)},{label:`Download`,onSelect:()=>this.handleDownloadDirectory(e)},{label:`Delete`,danger:!0,onSelect:()=>this.handleDeleteDirectory(e)}]}getFileContextMenuItems(e){return[{label:`Rename / move`,onSelect:()=>this.handleRenameFile(e)},{label:`Download`,onSelect:()=>this.handleDownloadFile(e)},{label:`Delete`,danger:!0,onSelect:()=>this.handleDelete(e)}]}showToast(e){e&&this.toastController?.show(String(e))}getCreateActionIcon(e){switch(e){case`base`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 4h7l5 5v11a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"/><path d="M14 4v5h5"/><path d="M8 13h8"/><path d="M8 17h6"/><path d="M8 9h3"/></svg>`;case`drawio`:case`plantuml`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="7" height="6" rx="1"/><rect x="14" y="4" width="7" height="6" rx="1"/><rect x="8.5" y="14" width="7" height="6" rx="1"/><path d="M10 7h4"/><path d="M17.5 10v2.5"/><path d="M6.5 10v2.5"/><path d="M6.5 12.5h11"/></svg>`;case`excalidraw`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19l7-7 3 3-7 7-3-3z"/><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><path d="M2 2l7.586 7.586"/><circle cx="11" cy="11" r="2"/></svg>`;case`folder`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>`;case`mermaid`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 7.5c0-1.38 1.12-2.5 2.5-2.5 1.04 0 1.93.64 2.3 1.56A2.5 2.5 0 0 1 14 8.5v1"/><path d="M19 16.5c0 1.38-1.12 2.5-2.5 2.5-1.04 0-1.93-.64-2.3-1.56A2.5 2.5 0 0 1 10 15.5v-1"/><path d="M8 10.5h8"/><path d="M8 13.5h8"/><path d="M10 8.5v7"/><path d="M14 8.5v7"/></svg>`;default:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>`}}showError(e,t){this.showToast(t?.message?`${e}: ${t.message}`:e)}ensureExtension(e,t){return Fe(e,t)}createPendingWorkspaceRequestId(){if(!this.pendingWorkspaceRequestIds)return null;let e=_t();return this.pendingWorkspaceRequestIds.add(e),e}clearPendingWorkspaceRequestId(e){e&&this.pendingWorkspaceRequestIds?.delete(e)}async runWorkspaceMutation(e){let t=this.createPendingWorkspaceRequestId();try{return await e(t)}catch(e){throw this.clearPendingWorkspaceRequestId(t),e}}openActionDialog({title:e,copy:t,label:n=`Path`,hint:r=``,note:i=``,placeholder:a=``,value:o=``,submitLabel:s=`Save`,destructive:c=!1,requiresInput:l=!0,emptyMessage:u=`A value is required`,onSubmit:d}){!this.actionDialog||!this.actionTitle||!this.actionCopy||!this.actionSubmitButton||!this.actionCancelButton||l&&!this.actionInput||(this.actionDialog.open&&(typeof this.actionDialog.close==`function`?this.actionDialog.close():(this.actionDialog.removeAttribute(`open`),this.resetActionDialog())),this.pendingAction={requiresInput:l,emptyMessage:u,onSubmit:d},this.createMenu.close({restoreFocus:!1}),this.view?.removeContextMenu?.(),this.actionTitle.textContent=e,this.actionCopy.textContent=t,this.actionField&&(this.actionField.hidden=!l),this.actionLabel&&(this.actionLabel.textContent=n),this.actionInput&&(this.actionInput.value=o,this.actionInput.placeholder=a,this.actionInput.required=l,this.actionInput.disabled=!1),this.actionHint&&(this.actionHint.textContent=r,this.actionHint.hidden=!l||!r),this.actionNote&&(this.actionNote.textContent=i,this.actionNote.hidden=!i,this.actionNote.classList.toggle(`is-danger`,c)),this.actionSubmitButton.textContent=s,this.actionSubmitButton.disabled=!1,this.actionSubmitButton.classList.toggle(`ui-button--primary`,!c),this.actionSubmitButton.classList.toggle(`ui-button--danger`,c),this.actionCancelButton.disabled=!1,typeof this.actionDialog.showModal==`function`?this.actionDialog.showModal():this.actionDialog.setAttribute(`open`,`true`),requestAnimationFrame(()=>{if(!l||!this.actionInput){this.actionSubmitButton.focus();return}this.actionInput.focus(),o&&this.actionInput.select()}))}resetActionDialog(){this.pendingAction=null,this.actionBusy=!1,this.actionField&&(this.actionField.hidden=!1),this.actionLabel&&(this.actionLabel.textContent=`Path`),this.actionInput&&(this.actionInput.value=``,this.actionInput.placeholder=``,this.actionInput.required=!0,this.actionInput.disabled=!1),this.actionHint&&(this.actionHint.textContent=``,this.actionHint.hidden=!0),this.actionNote&&(this.actionNote.textContent=``,this.actionNote.hidden=!0,this.actionNote.classList.remove(`is-danger`)),this.actionSubmitButton&&(this.actionSubmitButton.textContent=`Save`,this.actionSubmitButton.disabled=!1,this.actionSubmitButton.className=G({variant:`primary`})),this.actionCancelButton&&(this.actionCancelButton.disabled=!1)}closeActionDialog(){if(this.actionDialog){if(this.actionDialog.open&&typeof this.actionDialog.close==`function`){this.actionDialog.close();return}this.actionDialog.removeAttribute(`open`),this.resetActionDialog()}}setActionDialogBusy(e){this.actionBusy=e,this.actionInput&&(this.actionInput.disabled=e||!(this.pendingAction?.requiresInput??!0)),this.actionCancelButton&&(this.actionCancelButton.disabled=e),this.actionSubmitButton&&(this.actionSubmitButton.disabled=e)}async handleActionSubmit(){if(!this.pendingAction?.onSubmit||this.actionBusy)return;let e=this.pendingAction.requiresInput,t=e?this.actionInput?.value.trim()??``:void 0;if(e&&!t){this.showToast(this.pendingAction.emptyMessage),this.actionInput?.focus();return}this.setActionDialogBusy(!0);let n;try{n=await this.pendingAction.onSubmit(t)}catch(e){this.showError(`Failed to complete action`,e)}if(this.setActionDialogBusy(!1),n!==!1){this.closeActionDialog();return}e&&this.actionInput&&(this.actionInput.focus(),this.actionInput.select())}async createVaultFile(e,t,{openAfterCreate:n=!1,errorMessage:r=`Failed to create file`}={}){try{return await this.runWorkspaceMutation(n=>this.vaultClient.createFile(Zo({content:t,path:e},n))),this.state.expandDirectoryPath(e,{includeLeaf:!1}),await this.refresh(),n&&this.onFileSelect?.(e),!0}catch(e){return this.showToast(e?.message||r),!1}}async createDirectory(e){let t=F(e);if(!t)return this.showToast(`Folder path is required`),!1;try{return await this.runWorkspaceMutation(e=>this.vaultClient.createDirectory(t,Zo({},e))),this.state.expandDirectoryPath(t),await this.refresh(),!0}catch(e){return this.showToast(e?.message||`Failed to create folder`),!1}}async renameVaultFile(e,t,n){let r=F(t);if(!r)return this.showToast(`File path is required`),!1;let i=_(r);if(i&&i.toLowerCase()!==String(n??``).toLowerCase())return this.showToast(`File type changes are not supported during rename. Keep the ${n} extension.`),!1;let a=i?r:`${r}${n}`;if(!Ko(a))return this.showToast(`File path is required`),!1;if(a===e)return!0;try{return await this.runWorkspaceMutation(t=>this.vaultClient.renameFile(Zo({newPath:a,oldPath:e},t))),this.state.expandDirectoryPath(a,{includeLeaf:!1}),await this.refresh(),this.state.activeFilePath===e&&(this.state.activeFilePath=a,this.onFileSelect?.(a)),!0}catch(e){return this.showToast(e?.message||`Failed to rename`),!1}}async renameDirectory(e,t){let n=F(t);if(!n)return this.showToast(`Folder path is required`),!1;if(n===e)return!0;try{if(await this.runWorkspaceMutation(t=>this.vaultClient.renameDirectory(Zo({newPath:n,oldPath:e},t))),this.state.replaceExpandedDirectoryPrefix(e,n),this.state.expandDirectoryPath(n),await this.refresh(),this.state.activeFilePath&&this.state.activeFilePath.startsWith(`${e}/`)){let t=Jo(this.state.activeFilePath,e,n);this.state.activeFilePath=t,this.onFileSelect?.(t)}return!0}catch(e){return this.showToast(e?.message||`Failed to rename folder`),!1}}async deleteVaultFile(e){try{return await this.runWorkspaceMutation(t=>this.vaultClient.deleteFile(e,Zo({},t))),await this.refresh(),this.state.activeFilePath===e&&(this.state.activeFilePath=null,this.onFileDelete?.(e)),!0}catch(e){return this.showToast(e?.message||`Failed to delete`),!1}}async deleteDirectory(e,{recursive:t=!1}={}){try{await this.runWorkspaceMutation(n=>this.vaultClient.deleteDirectory(e,Zo({recursive:t},n)));let n=this.state.activeFilePath;return await this.refresh(),this.state.removeExpandedDirectoryPrefix(e),n&&n.startsWith(`${e}/`)&&(this.state.activeFilePath=null,this.onFileDelete?.(n)),!0}catch(e){return this.showToast(e?.message||`Failed to delete folder`),!1}}planMoveEntryByDrop({destinationDirectory:e=``,sourcePath:t=``,sourceType:n=`file`}={}){let r=F(t),i=F(e),a=qo(r),o=Ko(r);return!r||!o?{ok:!1,reason:`Invalid item to move`}:a===i?{ok:!1,reason:`Item is already in that folder`}:n===`directory`?i===r?{ok:!1,reason:`A folder cannot be moved into itself`}:i.startsWith(`${r}/`)?{ok:!1,reason:`A folder cannot be moved into one of its descendants`}:{nextPath:I(i,o),ok:!0}:{extension:_(r)||`.md`,nextPath:I(i,o),ok:!0}}canMoveEntryByDrop(e={}){return this.planMoveEntryByDrop(e).ok}async moveEntryByDrop(e={}){let t=this.planMoveEntryByDrop(e);return t.ok?e.sourceType===`directory`?this.renameDirectory(e.sourcePath,t.nextPath):this.renameVaultFile(e.sourcePath,t.nextPath,t.extension):(this.showToast(t.reason),!1)}async downloadFileEntry(e){try{return await this.vaultClient.downloadFile(e),!0}catch(e){return this.showToast(e?.message||`Failed to download file`),!1}}async downloadDirectoryEntry(e){try{return await this.vaultClient.downloadDirectory(e),!0}catch(e){return this.showToast(e?.message||`Failed to download folder`),!1}}getCreateContext(e=``){let t=F(e);return{hintPrefix:t?`Use "/" to create nested items under this folder.`:`Use "/" to place it inside a folder.`,inputLabelSuffix:t?`name or path`:`path`,note:t?`Parent folder: ${t}`:``,normalizedParentDir:t}}openRootCreateMenu({anchor:e=this.createButton}={}){this.openCreateMenu({anchor:e,parentDir:``})}openCreateMenu({anchor:e=this.createButton,parentDir:t=``}={}){this.view?.removeContextMenu?.(),this.createMenu.toggle({anchor:e,items:this.getCreateActions({parentDir:t}),title:`Create`})}handleNewFile({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create markdown file`,copy:t.normalizedParentDir?`Add a new note inside the selected folder. It opens immediately after creation.`:`Add a new note to the vault. It opens immediately after creation.`,label:`File ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".md" is added automatically.`,note:t.note,placeholder:t.normalizedParentDir?`my-note`:`notes/my-note`,submitLabel:`Create file`,emptyMessage:`File path is required`,onSubmit:e=>{let n=F(e);if(!n)return this.showToast(`File path is required`),!1;let r=this.ensureExtension(I(t.normalizedParentDir,n),`.md`);return this.createVaultFile(r,Ie(r),{errorMessage:`Failed to create file`,openAfterCreate:!0})}})}handleNewBase({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create base file`,copy:t.normalizedParentDir?"Add a new `.base` file inside the selected folder. It opens immediately after creation.":"Add a new `.base` file to the vault. It opens immediately after creation.",label:`Base ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".base" is added automatically.`,note:t.note,placeholder:t.normalizedParentDir?`table-view`:`views/table-view`,submitLabel:`Create base`,emptyMessage:`Base path is required`,onSubmit:e=>{let n=F(e);if(!n)return this.showToast(`Base path is required`),!1;let r=Le(I(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create base file`,openAfterCreate:!0})}})}handleNewFolder({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create folder`,copy:t.normalizedParentDir?`Add a new folder inside the selected folder.`:`Add a new folder to organize notes and diagrams.`,label:`Folder ${t.inputLabelSuffix}`,hint:t.hintPrefix,note:t.note,placeholder:t.normalizedParentDir?`archive`:`notes/archive`,submitLabel:`Create folder`,emptyMessage:`Folder path is required`,onSubmit:e=>this.createDirectory(I(t.normalizedParentDir,e))})}handleNewDrawing({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create Excalidraw drawing`,copy:t.normalizedParentDir?`Start a new drawing inside the selected folder.`:`Start a new drawing file in the vault.`,label:`Drawing ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".excalidraw" is added automatically.`,note:t.note,placeholder:t.normalizedParentDir?`architecture`:`diagrams/architecture`,submitLabel:`Create drawing`,emptyMessage:`Drawing path is required`,onSubmit:e=>{let n=F(e);if(!n)return this.showToast(`Drawing path is required`),!1;let r=this.ensureExtension(I(t.normalizedParentDir,n),`.excalidraw`);return this.createVaultFile(r,Xo(),{errorMessage:`Failed to create drawing`,openAfterCreate:!0})}})}handleNewMermaid({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create Mermaid diagram`,copy:t.normalizedParentDir?"Create a new `.mmd` or `.mermaid` file inside the selected folder.":"Create a new `.mmd` or `.mermaid` file with starter diagram content.",label:`Diagram ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".mmd" is added automatically unless you enter ".mermaid".`,note:t.note,placeholder:t.normalizedParentDir?`flow`:`diagrams/flow`,submitLabel:`Create diagram`,emptyMessage:`Diagram path is required`,onSubmit:e=>{let n=F(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=Re(I(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create Mermaid diagram`,openAfterCreate:!0})}})}handleNewDrawio({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create draw.io diagram`,copy:t.normalizedParentDir?"Create a new `.drawio` diagram inside the selected folder.":"Create a new `.drawio` diagram with a native starter document.",label:`Diagram ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".drawio" is added automatically.`,note:t.note,placeholder:t.normalizedParentDir?`architecture`:`diagrams/architecture`,submitLabel:`Create diagram`,emptyMessage:`Diagram path is required`,onSubmit:e=>{let n=F(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=ze(I(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create draw.io diagram`,openAfterCreate:!0})}})}handleNewPlantUml({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create PlantUML diagram`,copy:t.normalizedParentDir?"Create a new `.puml` or `.plantuml` file inside the selected folder.":"Create a new `.puml` or `.plantuml` file with starter diagram content.",label:`Diagram ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".puml" is added automatically unless you enter ".plantuml".`,note:t.note,placeholder:t.normalizedParentDir?`sequence-flow`:`diagrams/sequence-flow`,submitLabel:`Create diagram`,emptyMessage:`Diagram path is required`,onSubmit:e=>{let n=F(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=Be(I(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create PlantUML diagram`,openAfterCreate:!0})}})}handleRenameFile(e){let t=_(e)||`.md`;this.openActionDialog({title:`Rename or move file`,copy:`Update the relative path without changing the file type.`,label:`Path`,hint:`Use "/" to move the file into another folder. ${t} is kept automatically.`,value:e,submitLabel:`Save file path`,emptyMessage:`File path is required`,onSubmit:n=>this.renameVaultFile(e,n,t)})}handleRenameDirectory(e){this.openActionDialog({title:`Rename or move folder`,copy:`Update the relative path for this folder and everything inside it.`,label:`Path`,hint:`Use "/" to move the folder into another location in the vault.`,value:e,submitLabel:`Save folder path`,emptyMessage:`Folder path is required`,onSubmit:t=>this.renameDirectory(e,t)})}handleDelete(e){this.openActionDialog({title:`Delete file`,copy:`This permanently removes the file from the vault.`,note:e,submitLabel:`Delete file`,destructive:!0,requiresInput:!1,onSubmit:()=>this.deleteVaultFile(e)})}handleDeleteDirectory(e){let{directoryCount:t,fileCount:n}=this.state.getDirectoryDescendantSummary(e),r=t>0||n>0,i=r?`This will permanently remove ${Yo(n,`file`,`files`)} and ${Yo(t,`nested folder`,`nested folders`)} inside this folder.`:`This permanently removes the empty folder from the vault.`;this.openActionDialog({title:r?`Delete folder and contents`:`Delete folder`,copy:i,note:e,submitLabel:r?`Delete folder and contents`:`Delete folder`,destructive:!0,requiresInput:!1,onSubmit:()=>this.deleteDirectory(e,{recursive:r})})}handleDownloadFile(e){this.downloadFileEntry(e)}handleDownloadDirectory(e){this.downloadDirectoryEntry(e)}};function $o(e,t=[],n=[]){for(let r of e)if(!(!r?.path||!r?.type)){if(n.push({lowerPath:String(r.path).toLowerCase(),name:r.name,path:r.path,type:r.type}),r.type===`file`||r.type===`base`||r.type===`excalidraw`||r.type===`drawio`||r.type===`mermaid`||r.type===`plantuml`||r.type===`image`){t.push(r.path);continue}r.type===`directory`&&Array.isArray(r.children)&&$o(r.children,t,n)}return{files:t,searchEntries:n}}function es(e,t){for(let n of e??[]){if(n?.path===t)return n;if(n?.type===`directory`&&Array.isArray(n.children)){let e=es(n.children,t);if(e)return e}}return null}function ts(e){let t=0,n=0;for(let r of e?.children??[]){if(r?.type===`directory`){t+=1;let e=ts(r);t+=e.directoryCount,n+=e.fileCount;continue}n+=1}return{directoryCount:t,fileCount:n}}function ns(e,t,n){return e===t?n:`${n}${e.slice(t.length)}`}var rs=class{constructor(){this.tree=[],this.flatFiles=[],this.flatSearchEntries=[],this.activeFilePath=null,this.expandedDirs=new Set,this.searchQuery=``}setTree(e){this.tree=Array.isArray(e)?e:[];let t=$o(this.tree,[],[]);this.flatFiles=t.files,this.flatSearchEntries=t.searchEntries}setSearchQuery(e){this.searchQuery=String(e??``).trim().toLowerCase()}getSearchMatches(){return this.searchQuery?this.flatSearchEntries.filter(e=>e.lowerPath.includes(this.searchQuery)).map(e=>({name:e.name,path:e.path,type:e.type})):[]}getNode(e){return es(this.tree,e)}getDirectoryDescendantSummary(e){let t=this.getNode(e);return!t||t.type!==`directory`?{directoryCount:0,fileCount:0}:ts(t)}setActiveFile(e){this.activeFilePath=e||null,e&&this.expandDirectoryPath(e,{includeLeaf:!1})}toggleDirectory(e){return this.expandedDirs.has(e)?(this.expandedDirs.delete(e),!1):(this.expandedDirs.add(e),!0)}expandDirectoryPath(e,{includeLeaf:t=!0}={}){let n=F(e);if(!n)return;let r=n.split(`/`),i=t?r.length:Math.max(r.length-1,0),a=``;for(let e=0;e<i;e+=1)a=a?`${a}/${r[e]}`:r[e],this.expandedDirs.add(a)}replaceExpandedDirectoryPrefix(e,t){let n=new Set;this.expandedDirs.forEach(r=>{if(r===e||r.startsWith(`${e}/`)){n.add(ns(r,e,t));return}n.add(r)}),this.expandedDirs=n}removeExpandedDirectoryPrefix(e){let t=new Set;this.expandedDirs.forEach(n=>{n===e||n.startsWith(`${e}/`)||t.add(n)}),this.expandedDirs=t}};function is(e){return String(e??``).replace(/\/+$/u,``).split(`/`).filter(Boolean).pop()||``}function as(e){let t=String(e??``).replace(/\/+$/u,``),n=t.lastIndexOf(`/`);return n>=0?t.slice(0,n):``}function os(e=[],t=``){for(let n of e){if(n.path===t)return n;if(n.type===`directory`&&Array.isArray(n.children)){let e=os(n.children,t);if(e)return e}}return null}var ss=420,cs=10,ls=700,us=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onEntryDrop:t,onDirectorySelect:n,onDirectoryToggle:r,onFileContextMenu:i,onFileSelect:a,onSearchChange:o,onTreeContextMenu:s,onValidateDrop:c}){this.onEntryDrop=t,this.onDirectorySelect=n,this.onDirectoryToggle=r,this.onFileContextMenu=i,this.onFileSelect=a,this.onSearchChange=o,this.onTreeContextMenu=s,this.onValidateDrop=c,this.mobileBreakpointQuery=e,this.treeContainer=document.getElementById(`fileTree`),this.searchInput=document.getElementById(`fileSearchInput`),this.renderedDirectoryWrappers=new Map,this.renderedChildContainers=new Map,this.lastRenderMode=`tree`,this.longPressTimer=0,this.longPressContext=null,this.suppressedActivationTarget=null,this.contextMenuCloseHandler=null,this.actionSheetCloseHandler=null,this.dragSource=null,this.currentSearchQuery=``,this.activeDropTarget=null,this.invalidDropAttempt=null,this.autoExpandTimer=0,this.autoExpandTargetPath=``,this.rootDropZone=null}initialize(){this.searchInput?.addEventListener(`input`,e=>{this.onSearchChange?.(e.target.value)}),this.treeContainer?.addEventListener(`contextmenu`,e=>{e.target.closest(`.file-tree-item`)||(e.preventDefault(),this.onTreeContextMenu?.(e))}),this.treeContainer?.addEventListener(`pointerdown`,e=>{e.target.closest(`.file-tree-item`)||this.startLongPress(e,()=>{this.onTreeContextMenu?.({clientX:Number(e.clientX||0),clientY:Number(e.clientY||0),preventDefault(){},target:this.treeContainer})},this.treeContainer)}),this.treeContainer?.addEventListener(`pointermove`,e=>{this.handleLongPressPointerMove(e)},{passive:!0}),this.treeContainer?.addEventListener(`pointerup`,()=>{this.cancelLongPress()}),this.treeContainer?.addEventListener(`pointercancel`,()=>{this.cancelLongPress()}),this.treeContainer?.addEventListener(`scroll`,()=>{this.cancelLongPress()},{passive:!0}),this.treeContainer?.addEventListener(`dragover`,e=>{this.handleTreeDragOver(e)}),this.treeContainer?.addEventListener(`drop`,e=>{this.handleTreeDrop(e)}),this.treeContainer?.addEventListener(`dragleave`,e=>{this.handleTreeDragLeave(e)})}render({activeFilePath:e,changedPaths:t=null,expandedDirs:n,reset:r=!1,searchMatches:i,searchQuery:a,tree:o}){if(!this.treeContainer)return;if(this.currentSearchQuery=String(a??``),this.currentSearchQuery&&this.clearDragFeedback(),this.searchInput&&this.searchInput.value!==a&&(this.searchInput.value=a),a){this.lastRenderMode=`search`,this.renderSearchResults(i,e);return}if(r||this.lastRenderMode!==`tree`||!Array.isArray(t)||t.length===0){this.renderFullTree(o,{activeFilePath:e,expandedDirs:n}),this.lastRenderMode=`tree`;return}let s=Array.from(new Set(t.map(e=>as(e)))).sort((e,t)=>e.split(`/`).length-t.split(`/`).length).filter((e,t,n)=>!n.slice(0,t).some(t=>t&&e.startsWith(`${t}/`)));if(s.includes(``)){this.renderFullTree(o,{activeFilePath:e,expandedDirs:n}),this.lastRenderMode=`tree`;return}for(let t of s)if(!this.rerenderDirectoryBranch(t,o,{activeFilePath:e,expandedDirs:n})){this.renderFullTree(o,{activeFilePath:e,expandedDirs:n}),this.lastRenderMode=`tree`;return}this.lastRenderMode=`tree`}renderSearchResults(e,t){if(!this.treeContainer)return;if(this.resetTreeIndexes(),this.treeContainer.innerHTML=``,this.rootDropZone=null,e.length===0){this.treeContainer.innerHTML=`<div class="file-tree-empty">No matches</div>`;return}let n=document.createDocumentFragment();for(let r of e){if(r.type===`directory`){n.appendChild(this.createSearchDirectoryItem(r));continue}n.appendChild(this.createFileItem({activeFilePath:t,depth:0,filePath:r.path,fileType:r.type||(h(r.path)??`file`),name:r.name||is(r.path)}))}this.treeContainer.appendChild(n)}renderFullTree(e,{activeFilePath:t,expandedDirs:n}){if(this.resetTreeIndexes(),this.treeContainer.innerHTML=``,this.rootDropZone=null,e.length===0){this.treeContainer.innerHTML=`<div class="file-tree-empty">No vault files found</div>`;return}let r=document.createDocumentFragment();r.appendChild(this.createRootDropZone()),this.renderNodes(e,r,{activeFilePath:t,depth:0,expandedDirs:n}),this.treeContainer.appendChild(r)}resetTreeIndexes(){this.renderedDirectoryWrappers.clear(),this.renderedChildContainers.clear()}renderNodes(e,t,{activeFilePath:n,depth:r,expandedDirs:i}){for(let a of e){if(a.type===`directory`){t.appendChild(this.createDirectoryItem(a,{activeFilePath:n,depth:r,expandedDirs:i}));continue}t.appendChild(this.createFileItem({activeFilePath:n,depth:r,filePath:a.path,fileType:a.type,name:a.name}))}}createDirectoryItem(e,{activeFilePath:t,depth:n,expandedDirs:r}){let i=document.createElement(`div`);i.className=`file-tree-group`;let a=document.createElement(`button`);a.className=`file-tree-item file-tree-dir`,a.style.setProperty(`--depth`,n),a.dataset.depth=n;let o=r.has(e.path);if(a.setAttribute(`aria-expanded`,String(o)),a.dataset.path=e.path,a.dataset.entryType=`directory`,a.innerHTML=`
|
|
296
|
+
`,t.appendChild(n),e>1){let n=document.createElement(`span`);n.className=`comment-marker-count`,n.textContent=String(e),t.appendChild(n)}return t}function ka(){if(this.cardRoot?.isConnected&&this.cardRoot.parentElement===document.body)return this.cardRoot;let e=document.createElement(`div`);return e.className=`comment-card-root hidden`,document.body.appendChild(e),this.cardRoot=e,e}function Aa(e=`editor`,t=null){let n=this.session?.getCurrentSelectionCommentAnchor?.();n&&(this.selectionAnchor=n,this.reactionPicker=null,this.activeCard={anchor:n,mode:`create`,origin:e===`editor`&&t?`editor-chip`:e,replyThreadId:null,sourceRect:t??(e===`toolbar`?this.commentSelectionButton?.getBoundingClientRect?.():this.session?.getCommentAnchorClientRect?.(n))},this.render())}function ja(e,{anchor:t,origin:n,sourceRect:r}){this.reactionPicker=null,this.activeCard={anchor:t,groupKey:e.key,mode:`group`,origin:n,replyThreadId:null,sourceRect:r},this.renderDrawer(),this.renderCard()}function Ma(){this.activeCard=null,this.pendingCardFocusElement=null,this.reactionPicker=null,this.renderCard(),this.scheduleLayoutRefresh()}function Na(){return this.activeCard?this.activeCard.origin===`editor`?this.session?.getCommentAnchorClientRect?.(this.activeCard.anchor)??this.activeCard.sourceRect:this.activeCard.origin===`editor-chip`?this.activeCard.sourceRect:this.activeCard.origin===`preview`?this.resolvePreviewTarget(this.activeCard.anchor)?.bubbleRect??this.activeCard.sourceRect:this.activeCard.origin===`toolbar`?this.commentSelectionButton?.getBoundingClientRect?.()??this.activeCard.sourceRect:this.activeCard.sourceRect:null}function Pa(){let e=this.ensureCardRoot();if(e.replaceChildren(),e.classList.toggle(`hidden`,!this.activeCard),!this.activeCard){this.pendingCardFocusElement=null,e.style.visibility=``;return}this.pendingCardFocusElement=null;let t=document.createElement(`section`);t.className=`comment-card`,t.addEventListener(`click`,e=>{!this.reactionPicker||e.target?.closest?.(`.comment-reaction-picker-wrap`)||(this.reactionPicker=null,requestAnimationFrame(()=>{this.activeCard&&this.renderCard()}))});let n=document.createElement(`div`);n.className=`ui-record-header comment-card-header`;let r=document.createElement(`div`);r.className=`comment-card-title-wrap`;let i=document.createElement(`h3`);i.className=`comment-card-title`,i.textContent=this.activeCard.mode===`create`?`New comment`:`Comment threads`;let a=document.createElement(`p`);a.className=`comment-card-meta`,a.textContent=la(this.activeCard.anchor),r.append(i,a);let o=document.createElement(`button`);o.type=`button`,o.className=G({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-card-close`]}),o.setAttribute(`aria-label`,`Close comments`),o.textContent=`Close`,o.addEventListener(`click`,()=>this.closeCard()),n.append(r,o),t.appendChild(n);let s=document.createElement(`div`);if(s.className=`comment-card-scroll`,this.activeCard.anchor?.quote){let e=document.createElement(`p`);e.className=`comment-card-quote`,e.textContent=this.activeCard.anchor.quote,s.appendChild(e)}if(this.activeCard.mode===`create`)s.appendChild(this.createComposer());else{let e=this.getThreadGroups().find(e=>e.key===this.activeCard.groupKey);if(!e){this.closeCard();return}e.threads.forEach(e=>{s.appendChild(this.createThreadElement(e))})}e.style.visibility=`hidden`,t.appendChild(s),e.appendChild(t),this.updateReactionPickerPosition(t),this.positionCard(t),e.style.visibility=``,this.flushPendingCardFocus(),this.scheduleLayoutRefresh()}function Fa(e){let t=ya(e);if(!t)return;let{picker:n,scroll:r,wrap:i}=t;n.classList.remove(`is-upward`),n.style.maxHeight=``;let a=i.getBoundingClientRect(),o=r.getBoundingClientRect(),s=n.getBoundingClientRect(),c=window.innerHeight-12,l=Math.min(o.bottom,c),u=Math.max(o.top,12),d=Math.max(l-a.bottom-8,0),f=Math.max(a.top-u-8,0),p=s.height>d&&f>d,m=Math.max(p?f:d,120);n.classList.toggle(`is-upward`,p),n.style.maxHeight=`${m}px`}function Ia(){let e=this.cardRoot?.firstElementChild;if(!e||!this.activeCard){this.cardRoot&&(this.cardRoot.style.visibility=``);return}this.positionCard(e),this.cardRoot.style.visibility=``,this.flushPendingCardFocus()}function La(){let e=document.createElement(`form`);e.className=`comment-card-form`;let t=document.createElement(`textarea`);t.className=K({extra:`comment-card-input`}),t.rows=4,t.maxLength=Ce,t.placeholder=`Add context, feedback, or a question...`;let n=document.createElement(`div`);n.className=`ui-record-actions comment-card-actions`;let r=document.createElement(`button`);r.type=`button`,r.className=G({variant:`secondary`}),r.textContent=`Cancel`,r.addEventListener(`click`,()=>this.closeCard());let i=document.createElement(`button`);return i.type=`submit`,i.className=G({variant:`primary`}),i.textContent=`Post comment`,n.append(r,i),e.append(t,n),e.addEventListener(`submit`,async e=>{if(e.preventDefault(),!await this.onCreateThread?.({anchor:this.activeCard?.anchor,body:t.value})){t.focus();return}this.closeCard()}),this.pendingCardFocusElement=t,e}function Ra(e){let t=document.createElement(`article`);t.className=`comment-thread-card`;let n=document.createElement(`div`);n.className=`ui-record-header comment-thread-card-header`;let r=document.createElement(`div`);r.className=`comment-thread-card-heading`;let i=document.createElement(`span`);i.className=`comment-thread-card-author`,i.textContent=e.createdByName;let a=document.createElement(`span`);a.className=`comment-thread-card-time`,a.textContent=this.formatTimestamp(e.createdAt);let o=document.createElement(`div`);o.className=`ui-record-actions comment-thread-card-actions`;let s=document.createElement(`button`);s.type=`button`,s.className=G({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-thread-card-action`]}),s.textContent=`Jump`,s.addEventListener(`click`,()=>this.onNavigateToLine?.(e.anchor?.startLine??1));let c=document.createElement(`button`);c.type=`button`,c.className=G({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-thread-card-action`]});let l=this.activeCard?.replyThreadId===e.id;c.classList.toggle(`is-active`,l),c.textContent=`Reply`,c.setAttribute(`aria-pressed`,String(l)),c.setAttribute(`aria-label`,l?`Cancel reply`:`Reply to thread`),c.title=l?`Cancel reply`:`Reply to thread`,c.addEventListener(`click`,()=>{this.activeCard={...this.activeCard,replyThreadId:l?null:e.id},this.renderCard()});let u=document.createElement(`button`);return u.type=`button`,u.className=G({variant:`ghost`,size:`compact`,pill:!0,extra:[`ui-action-pill`,`comment-thread-card-action`,`is-danger`]}),u.textContent=`Resolve`,u.addEventListener(`click`,async()=>{await this.onResolveThread?.(e.id)}),o.append(s,c,u),r.append(i,a),n.append(r,o),t.append(n),e.messages.forEach(n=>{t.appendChild(this.createMessageElement(e,n))}),this.activeCard?.replyThreadId===e.id&&t.appendChild(this.createReplyComposer(e)),t}function za(e,t){let n=document.createElement(`div`);n.className=`comment-message-card`;let r=document.createElement(`div`);r.className=`ui-record-meta comment-message-card-meta`;let i=document.createElement(`span`);i.className=`comment-message-card-author`,i.textContent=t.userName;let a=document.createElement(`span`);a.className=`comment-message-card-time`,a.textContent=this.formatTimestamp(t.createdAt);let o=ha(t.body,`comment-message-card-body comment-markdown`);return r.append(i,a),n.append(r,o),n.appendChild(this.createReactionBar(e,t)),n}function Ba(e,t){let n=this.session?.getLocalUser?.()?.userId??``,r=document.createElement(`div`);r.className=`comment-reaction-bar`;let i=new Set((t.reactions??[]).map(e=>e.emoji)),a=document.createElement(`div`);a.className=`comment-reaction-chips`,(t.reactions??[]).forEach(r=>{let i=document.createElement(`button`);i.type=`button`,i.className=`ui-chip-button ui-chip-button--comment comment-reaction-chip`,i.classList.toggle(`is-active`,ga(r,n)),i.setAttribute(`aria-pressed`,String(ga(r,n))),i.title=r.users?.map(e=>e.userName).join(`, `)||r.emoji;let o=document.createElement(`span`);o.className=`comment-reaction-chip-emoji`,o.textContent=r.emoji;let s=document.createElement(`span`);s.className=`comment-reaction-chip-count`,s.textContent=_a(r),i.append(o,s),i.addEventListener(`click`,async()=>{await this.onToggleReaction?.(e.id,t.id,r.emoji)}),a.appendChild(i)});let o=document.createElement(`div`);o.className=`comment-reaction-actions`,na.filter(e=>!i.has(e)).forEach(n=>{o.appendChild(this.createQuickReactionButton(e,t,n))});let s=document.createElement(`div`);s.className=`comment-reaction-picker-wrap`;let c=document.createElement(`button`);return c.type=`button`,c.className=`ui-chip-button ui-chip-button--comment comment-reaction-more-trigger`,c.dataset.reactionPickerToggle=`true`,c.setAttribute(`aria-expanded`,String(va(this.reactionPicker,e.id,t.id))),c.textContent=`More`,c.addEventListener(`click`,()=>{this.reactionPicker=va(this.reactionPicker,e.id,t.id)?null:{messageId:t.id,threadId:e.id},this.renderCard()}),s.appendChild(c),va(this.reactionPicker,e.id,t.id)&&s.appendChild(this.createReactionPicker(e,t)),o.appendChild(s),r.append(a,o),r}function Va(e,t,n){let r=document.createElement(`button`);return r.type=`button`,r.className=`ui-icon-chip ui-icon-chip--comment comment-reaction-quick-add`,r.textContent=n,r.title=`React with ${n}`,r.addEventListener(`click`,async()=>{await this.onToggleReaction?.(e.id,t.id,n)}),r}function Ha(e,t){let n=document.createElement(`div`);n.className=`comment-reaction-picker`;let r=document.createElement(`div`);return r.className=`comment-reaction-picker-grid`,ra.forEach(n=>{r.appendChild(this.createReactionPickerButton(e,t,n))}),n.appendChild(r),n}function Ua(e,t,n){let r=document.createElement(`button`);return r.type=`button`,r.className=`ui-icon-chip ui-icon-chip--comment comment-reaction-picker-btn`,r.textContent=n,r.title=`React with ${n}`,r.addEventListener(`click`,async()=>{await this.onToggleReaction?.(e.id,t.id,n)&&(this.reactionPicker=null,this.renderCard())}),r}function Wa(e){let t=document.createElement(`form`);t.className=`comment-reply-form`;let n=document.createElement(`textarea`);n.className=K({extra:`comment-card-input`}),n.rows=3,n.maxLength=Ce,n.placeholder=`Reply to thread...`;let r=document.createElement(`div`);r.className=`ui-record-actions comment-card-actions`;let i=document.createElement(`button`);i.type=`button`,i.className=G({variant:`secondary`}),i.textContent=`Cancel`,i.addEventListener(`click`,()=>{this.activeCard={...this.activeCard,replyThreadId:null},this.renderCard()});let a=document.createElement(`button`);return a.type=`submit`,a.className=G({variant:`primary`}),a.textContent=`Reply`,r.append(i,a),t.append(n,r),this.pendingCardFocusElement=n,t.addEventListener(`submit`,async t=>{if(t.preventDefault(),!await this.onReplyToThread?.(e.id,n.value)){n.focus();return}this.activeCard={...this.activeCard,replyThreadId:null},this.renderCard()}),t}function Ga(e){let t=this.updateCardSourceRect(),n=window.innerWidth,r=window.innerHeight,i=e.getBoundingClientRect(),a=ia((n-i.width)/2,16,n-i.width-16),o=ia((r-i.height)/4,16,r-i.height-16),s=a,c=o;t&&(s=ia(t.left,16,n-Math.min(i.width,520)-16),c=t.bottom+14,c+i.height>r-16&&(c=Math.max(t.top-i.height-14,16))),this.cardRoot.style.left=`${s}px`,this.cardRoot.style.top=`${c}px`,this.cardRoot.style.width=`${Math.min(Math.max(i.width,520),n-32)}px`}function Ka(){let e=this.pendingCardFocusElement;if(!(e instanceof HTMLElement)||!e.isConnected){this.pendingCardFocusElement=null;return}this.pendingCardFocusElement=null;let t=()=>{if(!e.isConnected)return;let t=document.activeElement;t instanceof HTMLElement&&this.editorContainer?.contains(t)&&t.blur(),e.focus({preventScroll:!0})};t(),document.activeElement!==e&&requestAnimationFrame(()=>{t(),document.activeElement!==e&&setTimeout(()=>{t()},50)})}var qa={closeCard:Ma,createComposer:La,createMessageElement:za,createQuickReactionButton:Va,createReactionBar:Ba,createReactionPicker:Ha,createReactionPickerButton:Ua,createReplyComposer:Wa,createThreadElement:Ra,ensureCardRoot:ka,flushPendingCardFocus:Ka,openComposerForSelection:Aa,openThreadGroup:ja,positionCard:Ga,renderCard:Pa,repositionActiveCard:Ia,updateCardSourceRect:Na,updateReactionPickerPosition:Fa};function Ja(){this.renderEditorLayer(),this.renderPreviewLayer(),this.repositionActiveCard()}function Ya(e=0){if(!this.previewElement)return!1;let t=this.supported&&e>0,n=0,r=0;if(t){let t=getComputedStyle(this.previewElement),i=Number.parseFloat(t.getPropertyValue(`--preview-comment-rail-reserved`))||0,a=Number.parseFloat(t.paddingRight)||0,o=Number.parseFloat(t.getPropertyValue(`--preview-comment-rail-inset`))||0,s=Math.max(a-i,0),c=Math.max(e+o-s,0),l=this.previewContainer?.getBoundingClientRect(),u=this.previewElement.getBoundingClientRect(),d=l?Math.max(l.right-u.right,0):0;r=Math.min(d,c),n=Math.max(c-r,0)}let i=`${Math.ceil(n)}px`,a=`${Math.floor(r)}px`,o=this.previewElement.style.getPropertyValue(`--preview-comment-rail-reserved`)!==i||this.previewElement.style.getPropertyValue(`--preview-comment-rail-offset`)!==a;return o&&(this.previewElement.style.setProperty(`--preview-comment-rail-reserved`,i),this.previewElement.style.setProperty(`--preview-comment-rail-offset`,a)),o}function Xa(){this.layoutFrame||=requestAnimationFrame(()=>{this.layoutFrame=0,this.refreshLayout()})}function Za(){if(this.editorLayer?.isConnected&&this.editorLayer.parentElement===this.editorContainer)return this.editorLayer;let e=document.createElement(`div`);return e.className=`comment-editor-layer`,this.editorContainer?.appendChild(e),this.editorLayer=e,e}function Qa(){let e=this.ensureEditorLayer();if(e.replaceChildren(),!this.supported||!this.session)return;let t=this.editorContainer?.getBoundingClientRect?.();if(!t)return;let n=this.getThreadGroups(),r=[];if(n.forEach(n=>{let i=this.session.getCommentAnchorClientRect?.(n.anchor);if(!i)return;let a=Ca(i,t);if(a.bottom<0||a.top>t.height)return;let o=document.createElement(`button`);o.type=`button`,o.className=`ui-state-marker ui-state-marker--comment comment-editor-badge`,o.dataset.count=String(n.threads.length);let s=this.activeCard?.groupKey===n.key,c=this.hoveredEditorGroupKeys.includes(n.key);o.classList.toggle(`is-active`,s),o.classList.toggle(`is-hovered`,c),o.classList.toggle(`is-passive`,!s&&!c),o.setAttribute(`aria-label`,`${n.threads.length} comment thread${n.threads.length===1?``:`s`}`),o.appendChild(Oa(n.threads.length));let l=Math.max(a.top,8);o.style.top=`${l}px`,o.style.left=`${Math.max(t.width-36,8)}px`,o.title=`${n.threads.length} comment${n.threads.length===1?``:`s`}`,o.addEventListener(`pointerdown`,e=>{e.preventDefault()}),o.addEventListener(`pointerenter`,()=>{this.updateHoveredEditorGroups([n.key])}),o.addEventListener(`pointerleave`,()=>{this.updateHoveredEditorGroups([])}),o.addEventListener(`focusin`,()=>{this.updateHoveredEditorGroups([n.key])}),o.addEventListener(`focusout`,()=>{this.updateHoveredEditorGroups([])}),o.addEventListener(`click`,()=>{this.openThreadGroup(n,{anchor:n.anchor,origin:`editor`,sourceRect:i})}),e.appendChild(o),r.push(l)}),!this.committedSelectionAnchor||this.activeCard?.mode===`create`)return;let i=this.session.getCommentAnchorClientRect?.(this.committedSelectionAnchor),a=this.session.getSelectionChipClientRect?.(this.committedSelectionAnchor)??i;if(!a)return;let o=Ca(a,t);if(o.bottom<0||o.top>t.height)return;let s=ia(o.top,8,Math.max(t.height-36,8));for(;r.some(e=>Math.abs(e-s)<32);)s=ia(s+36,8,Math.max(t.height-36,8));let c=document.createElement(`button`);c.type=`button`,c.className=`ui-selection-pill ui-selection-pill--comment comment-selection-chip`,c.textContent=`Comment`,c.style.top=`${s}px`,c.style.right=`12px`,c.addEventListener(`pointerdown`,e=>{e.preventDefault(),e.stopPropagation(),this.openComposerForSelection(`editor`,c.getBoundingClientRect())}),e.appendChild(c)}function $a(){if(this.previewLayer?.isConnected&&this.previewLayer.parentElement===this.previewElement)return this.previewLayer;let e=document.createElement(`div`);e.className=`comment-preview-highlights`;let t=document.createElement(`div`);return t.className=`comment-preview-layer`,this.previewElement?.append(e,t),this.previewHighlightLayer=e,this.previewLayer=t,t}function eo(){if(this.ensurePreviewLayer(),this.previewLayer?.replaceChildren(),this.previewHighlightLayer?.replaceChildren(),!this.supported||!this.previewElement){this.previewHoverRegions=[],this.syncPreviewRailLayout(0);return}let e=this.previewElement.getBoundingClientRect(),t=this.getThreadGroups(),n=[],r=[],i=this.shouldRenderPassivePreviewMarkers(),a=[];t.forEach(t=>{let o=this.resolvePreviewTarget(t.anchor);if(!o?.bubbleRect)return;r.push({key:t.key,rects:o.hoverRects?.length>0?o.hoverRects:[o.bubbleRect]});let s=this.activeCard?.groupKey===t.key,c=this.hoveredPreviewGroupKeys.includes(t.key),l=s||c;if(o.highlightRects?.forEach(t=>{let n=document.createElement(`div`);n.className=`comment-preview-highlight`,n.classList.toggle(`is-active`,s),n.classList.toggle(`is-hovered`,c),n.classList.toggle(`is-passive`,!l),n.style.left=`${t.left-e.left}px`,n.style.top=`${t.top-e.top}px`,n.style.width=`${t.width}px`,n.style.height=`${t.height}px`,this.previewHighlightLayer?.appendChild(n)}),!i&&!l)return;let u=document.createElement(`button`);u.type=`button`,u.className=`ui-state-marker ui-state-marker--comment comment-preview-badge`,u.dataset.commentPreviewGroupKeys=t.key,u.classList.toggle(`is-active`,s),u.classList.toggle(`is-hovered`,c),u.classList.toggle(`is-passive`,!l),u.setAttribute(`aria-label`,`${t.threads.length} comment thread${t.threads.length===1?``:`s`}`),u.appendChild(Oa(t.threads.length));let d=ia(o.bubbleRect.top-e.top,6,Math.max(this.previewElement.clientHeight-30,6));for(;n.some(e=>Math.abs(e-d)<26);)d=ia(d+30,6,Math.max(this.previewElement.clientHeight-30,6));u.style.top=`${d}px`,u.title=`${t.threads.length} comment${t.threads.length===1?``:`s`}`,u.addEventListener(`pointerdown`,e=>{e.preventDefault()}),u.addEventListener(`click`,()=>{this.openThreadGroup(t,{anchor:t.anchor,origin:`preview`,sourceRect:u.getBoundingClientRect()})}),this.previewLayer?.appendChild(u),n.push(d),a.push(u)}),this.previewHoverRegions=r;let o=a.reduce((e,t)=>Math.max(e,t.offsetWidth||28),0);this.syncPreviewRailLayout(o)&&this.scheduleLayoutRefresh(),this.lastPreviewPointerPosition&&this.updateHoveredPreviewGroups(this.getPreviewGroupKeysAtPoint(this.lastPreviewPointerPosition.x,this.lastPreviewPointerPosition.y))}function to(e){if(!this.previewElement||!e)return null;let t=Array.from(this.previewElement.querySelectorAll(`.mermaid-shell, .plantuml-shell`)).find(t=>ba(t,e));if(t)return{bubbleRect:t.getBoundingClientRect(),highlightRects:[],hoverRects:[t.getBoundingClientRect()]};let n=Array.from(this.previewElement.querySelectorAll(`[data-source-line]`)).filter(t=>da(t)&&ba(t,e));if(e.kind===`text`&&e.quote){let t=n.map(t=>({element:t,range:Sa(t,e.quote)})).filter(e=>e.range);if(t.length===1){let e=Array.from(t[0].range.getClientRects());return{bubbleRect:wa(e)||t[0].element.getBoundingClientRect(),highlightRects:e,hoverRects:e}}}let r=n[0];return r?{bubbleRect:r.getBoundingClientRect(),highlightRects:[],hoverRects:[r.getBoundingClientRect()]}:null}function no(e){if(!(e instanceof Node))return[];let t=e.closest?.(`[data-comment-preview-group-keys]`);return Da(String(t?.dataset?.commentPreviewGroupKeys??``).split(/\s+/).filter(Boolean)).split(` `).filter(Boolean)}function ro(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))return[];let n=document.elementFromPoint(e,t),r=this.getPreviewGroupKeysForTarget(n);return r.length>0?r:Ea(this.previewHoverRegions.filter(n=>n.rects.some(n=>Ta(e,t,n))).map(e=>e.key))}function io(e=[]){let t=Ea(e),n=t.join(` `);n!==this.hoveredPreviewGroupKeysSignature&&(this.hoveredPreviewGroupKeys=t,this.hoveredPreviewGroupKeysSignature=n,this.scheduleLayoutRefresh())}function ao(e=[]){let t=Ea(e),n=t.join(` `);n!==this.hoveredEditorGroupKeysSignature&&(this.hoveredEditorGroupKeys=t,this.hoveredEditorGroupKeysSignature=n,this.scheduleLayoutRefresh())}function oo(e){this.updateHoveredPreviewGroups(this.getPreviewGroupKeysForTarget(e))}function so(){let e=this.previewContainer?.clientWidth??this.previewElement?.clientWidth??0;return window.innerWidth>=769&&e>=400}var co={ensureEditorLayer:Za,ensurePreviewLayer:$a,getPreviewGroupKeysAtPoint:ro,getPreviewGroupKeysForTarget:no,refreshLayout:Ja,renderEditorLayer:Qa,renderPreviewLayer:eo,resolvePreviewTarget:to,scheduleLayoutRefresh:Xa,shouldRenderPassivePreviewMarkers:so,syncHoveredPreviewGroupsFromTarget:oo,syncPreviewRailLayout:Ya,updateHoveredEditorGroups:ao,updateHoveredPreviewGroups:io};function lo(){this.renderToolbar(),this.renderDrawer(),this.renderCard(),this.scheduleLayoutRefresh()}function uo(){let e=this.threads.length,t=this.supported&&!!this.session;if(this.commentSelectionButton?.classList.toggle(`hidden`,!t),this.commentsToggleButton?.classList.toggle(`hidden`,!this.supported),this.commentSelectionButton&&(this.commentSelectionButton.disabled=!this.selectionAnchor),this.commentsToggleButton){this.commentsToggleButton.classList.toggle(`active`,this.drawerOpen),this.commentsToggleButton.setAttribute(`aria-expanded`,String(this.drawerOpen));let t=e>0?`Comments ${e}`:`Comments`,n=this.commentsToggleButton.querySelector(`.ui-action-label`);n?n.textContent=t:this.commentsToggleButton.textContent=t}}function fo(){if(!this.commentsDrawer||!this.commentsDrawerList)return;this.commentsDrawer.classList.toggle(`hidden`,!this.supported||!this.drawerOpen),this.commentsDrawerList.replaceChildren();let e=this.getThreadGroups();if(this.commentsDrawerEmpty?.classList.toggle(`hidden`,e.length>0),!this.supported||e.length===0)return;let t=document.createDocumentFragment();e.forEach(e=>{let n=document.createElement(`button`);n.type=`button`,n.className=`ui-record-surface comments-drawer-item`,n.classList.toggle(`is-active`,this.activeCard?.groupKey===e.key),n.addEventListener(`pointerdown`,e=>{e.preventDefault()}),n.addEventListener(`click`,()=>{this.openThreadGroup(e,{anchor:e.anchor,origin:`drawer`,sourceRect:n.getBoundingClientRect()})});let r=document.createElement(`div`);r.className=`ui-record-header comments-drawer-item-header`;let i=document.createElement(`span`);i.className=`comments-drawer-item-title`,i.textContent=la(e.anchor);let a=document.createElement(`span`);a.className=`ui-pill-badge ui-pill-badge--count ui-pill-badge--accent comments-drawer-item-count`,a.textContent=String(e.threads.length),r.append(i,a);let o=document.createElement(`p`);o.className=`comments-drawer-item-quote`,o.textContent=e.anchor.quote||e.anchor.excerpt||`Source anchored comment`;let s=ma(e),c=ha(s?.body||``,`comment-markdown comments-drawer-item-preview`),l=document.createElement(`div`);l.className=`ui-record-meta comments-drawer-item-footer`;let u=document.createElement(`span`);u.textContent=`${e.threads.length} thread${e.threads.length===1?``:`s`}`;let d=document.createElement(`span`);d.className=`comments-drawer-item-updated`,d.textContent=s?`${s.userName} • ${this.formatTimestamp(s.createdAt)}`:``,l.append(u,d),n.append(r,o,c,l),t.appendChild(n)}),this.commentsDrawerList.appendChild(t)}function po(e){if(!Number.isFinite(e))return``;try{return this.timeFormatter.format(new Date(e))}catch{return``}}var mo={formatTimestamp:po,render:lo,renderDrawer:fo,renderToolbar:uo};function ho(e){this.session?.getScrollContainer?.()?.removeEventListener(`scroll`,this.handleEditorScroll),this.session=e,this.selectionAnchor=e?.getCurrentSelectionCommentAnchor?.()??null,this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.reactionPicker=null,this.clearSelectionRevealTimer(),this.pointerSelecting=!1,e?.getScrollContainer?.()?.addEventListener(`scroll`,this.handleEditorScroll,{passive:!0}),this.render()}function go(e,{fileKind:t=`markdown`,supported:n=!1}={}){let r=this.currentFile!==e;this.currentFile=e,this.fileKind=t,this.supported=!!(e&&n),r&&(this.drawerOpen=!1,this.threads=[],this.selectionAnchor=null,this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.clearSelectionRevealTimer(),this.pointerSelecting=!1,this.activeCard=null,this.updateHoveredEditorGroups([]),this.updateHoveredPreviewGroups([]),this.previewHoverRegions=[],this.lastPreviewPointerPosition=null,this.reactionPicker=null),this.supported||(this.drawerOpen=!1,this.activeCard=null,this.threads=[],this.selectionAnchor=null,this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.clearSelectionRevealTimer(),this.pointerSelecting=!1,this.updateHoveredEditorGroups([]),this.updateHoveredPreviewGroups([]),this.previewHoverRegions=[],this.lastPreviewPointerPosition=null,this.reactionPicker=null),this.render()}function _o(e){if(this.selectionAnchor=this.supported?e:null,!this.supported||!this.selectionAnchor){this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.clearSelectionRevealTimer(),this.renderToolbar(),this.scheduleLayoutRefresh();return}if(!sa(this.selectionAnchor)){this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.clearSelectionRevealTimer(),this.renderToolbar(),this.scheduleLayoutRefresh();return}if(this.pendingSelectionAnchor=this.selectionAnchor,this.activeCard?.mode===`create`){this.clearSelectionRevealTimer(),this.renderToolbar(),this.scheduleLayoutRefresh();return}if(this.pointerSelecting){this.clearSelectionRevealTimer(),this.committedSelectionAnchor=null,this.renderToolbar(),this.scheduleLayoutRefresh();return}if(ca(this.committedSelectionAnchor,this.selectionAnchor)){this.renderToolbar(),this.scheduleLayoutRefresh();return}this.scheduleSelectionReveal(this.selectionAnchor),this.renderToolbar(),this.scheduleLayoutRefresh()}function vo(){this.activeCard?.mode!==`create`&&(this.clearSelectionRevealTimer(),this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.scheduleLayoutRefresh())}function yo(e=[]){this.threads=aa(e),this.activeCard?.mode===`group`&&!this.getThreadGroups().some(e=>e.key===this.activeCard.groupKey)&&(this.activeCard=null),this.reactionPicker&&!this.threads.some(e=>e.id===this.reactionPicker.threadId&&e.messages?.some(e=>e.id===this.reactionPicker.messageId))&&(this.reactionPicker=null),this.render()}function bo(e){let t=!!e;t!==this.drawerOpen&&(t&&this.onWillOpenDrawer?.(),this.drawerOpen=t,this.render())}function xo(){this.setDrawerOpen(!1)}function So(){let e=new Map;return this.threads.forEach(t=>{let n=ua(t.anchor),r=e.get(n);if(r){r.threads.push(t);return}e.set(n,{anchor:t.anchor,key:n,threads:[t]})}),Array.from(e.values()).sort((e,t)=>(e.anchor?.startLine??0)-(t.anchor?.startLine??0))}function Co(){this.selectionRevealTimer&&=(clearTimeout(this.selectionRevealTimer),0)}function wo(e){this.clearSelectionRevealTimer(),this.selectionRevealTimer=window.setTimeout(()=>{this.selectionRevealTimer=0,!(this.pointerSelecting||this.activeCard?.mode===`create`||!ca(this.pendingSelectionAnchor,e))&&(this.committedSelectionAnchor=e,this.scheduleLayoutRefresh())},150)}var To={attachSession:ho,clearSelectionRevealTimer:Co,closeDrawer:xo,getThreadGroups:So,handleEditorContentChange:vo,scheduleSelectionReveal:wo,setCurrentFile:go,setDrawerOpen:bo,setSelectionAnchor:_o,setThreads:yo},Eo=class{constructor({commentSelectionButton:e,commentsDrawer:t,commentsDrawerEmpty:n,commentsDrawerList:r,commentsToggleButton:i,editorContainer:a,onWillOpenDrawer:o,onCreateThread:s,onNavigateToLine:c,onReplyToThread:l,onToggleReaction:u,onResolveThread:d,previewContainer:f,previewElement:p}){this.commentSelectionButton=e,this.commentsDrawer=t,this.commentsDrawerEmpty=n,this.commentsDrawerList=r,this.commentsToggleButton=i,this.editorContainer=a,this.onWillOpenDrawer=o,this.onCreateThread=s,this.onNavigateToLine=c,this.onReplyToThread=l,this.onToggleReaction=u,this.onResolveThread=d,this.previewContainer=f,this.previewElement=p,this.currentFile=null,this.fileKind=`markdown`,this.supported=!1,this.drawerOpen=!1,this.threads=[],this.selectionAnchor=null,this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.selectionRevealTimer=0,this.pointerSelecting=!1,this.session=null,this.activeCard=null,this.hoveredEditorGroupKeys=[],this.hoveredEditorGroupKeysSignature=``,this.hoveredPreviewGroupKeys=[],this.hoveredPreviewGroupKeysSignature=``,this.previewHoverRegions=[],this.lastPreviewPointerPosition=null,this.editorLayer=null,this.previewLayer=null,this.previewHighlightLayer=null,this.cardRoot=null,this.pendingCardFocusElement=null,this.reactionPicker=null,this.layoutFrame=0,this.timeFormatter=new Intl.DateTimeFormat(void 0,{day:`numeric`,hour:`numeric`,minute:`2-digit`,month:`short`}),this.handleEditorScroll=()=>this.scheduleLayoutRefresh(),this.handlePreviewScroll=()=>this.scheduleLayoutRefresh(),this.handleWindowResize=()=>this.scheduleLayoutRefresh(),this.handlePreviewPointerMove=e=>{this.lastPreviewPointerPosition={x:e.clientX,y:e.clientY},this.updateHoveredPreviewGroups(this.getPreviewGroupKeysAtPoint(e.clientX,e.clientY))},this.handlePreviewPointerLeave=()=>{this.lastPreviewPointerPosition=null,this.updateHoveredPreviewGroups([])},this.handlePreviewFocusIn=e=>{this.updateHoveredPreviewGroups(this.getPreviewGroupKeysForTarget(e.target))},this.handlePreviewFocusOut=e=>{this.updateHoveredPreviewGroups(this.getPreviewGroupKeysForTarget(e.relatedTarget))},this.handleCommentSelectionButtonPointerDown=e=>{e.preventDefault()},this.handleEditorPointerDown=e=>{e.button!==0||!this.supported||!this.session||!e.target?.closest?.(`.cm-editor`)||e.target?.closest?.(`.comment-editor-layer`)||(this.pointerSelecting=!0,this.clearSelectionRevealTimer(),this.committedSelectionAnchor&&(this.committedSelectionAnchor=null,this.scheduleLayoutRefresh()))},this.handleDocumentPointerUp=()=>{this.pointerSelecting&&requestAnimationFrame(()=>{let e=this.supported?this.session?.getCurrentSelectionCommentAnchor?.()??null:null;this.pointerSelecting=!1,this.selectionAnchor=e,this.renderToolbar(),this.pendingSelectionAnchor=sa(e)?e:null,this.clearSelectionRevealTimer(),this.committedSelectionAnchor=sa(e)&&this.activeCard?.mode!==`create`?e:null,this.scheduleLayoutRefresh()})},this.handleEditorFocusOut=e=>{let t=e.relatedTarget;t instanceof Node&&(this.editorContainer?.contains(t)||this.cardRoot?.contains(t)||this.commentSelectionButton?.contains(t))||(this.clearSelectionRevealTimer(),this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.scheduleLayoutRefresh())},this.handleDocumentPointerDown=e=>{let t=e.target;if(this.activeCard&&this.cardRoot){if(this.cardRoot.contains(t))return;this.closeCard()}this.drawerOpen&&(t instanceof Node&&(this.commentsDrawer?.contains(t)||this.commentsToggleButton?.contains(t))||this.closeDrawer())},this.handleDocumentKeyDown=e=>{if(e.key===`Escape`&&this.reactionPicker){this.reactionPicker=null,this.renderCard();return}e.key===`Escape`&&this.activeCard&&this.closeCard(),e.key===`Escape`&&this.committedSelectionAnchor&&(this.clearSelectionRevealTimer(),this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.scheduleLayoutRefresh())},this.commentSelectionButton?.addEventListener(`pointerdown`,this.handleCommentSelectionButtonPointerDown),this.commentSelectionButton?.addEventListener(`click`,()=>{this.openComposerForSelection(`toolbar`)}),this.commentsToggleButton?.addEventListener(`click`,()=>{this.setDrawerOpen(!this.drawerOpen)}),this.previewContainer?.addEventListener(`scroll`,this.handlePreviewScroll,{passive:!0}),this.previewElement?.addEventListener(`pointermove`,this.handlePreviewPointerMove,{passive:!0}),this.previewElement?.addEventListener(`pointerleave`,this.handlePreviewPointerLeave),this.previewElement?.addEventListener(`focusin`,this.handlePreviewFocusIn),this.previewElement?.addEventListener(`focusout`,this.handlePreviewFocusOut),this.editorContainer?.addEventListener(`pointerdown`,this.handleEditorPointerDown),this.editorContainer?.addEventListener(`focusout`,this.handleEditorFocusOut),window.addEventListener(`resize`,this.handleWindowResize),document.addEventListener(`pointerup`,this.handleDocumentPointerUp),document.addEventListener(`pointercancel`,this.handleDocumentPointerUp),document.addEventListener(`pointerdown`,this.handleDocumentPointerDown),document.addEventListener(`keydown`,this.handleDocumentKeyDown)}destroy(){this.layoutFrame&&=(cancelAnimationFrame(this.layoutFrame),0),this.attachSession(null),this.previewContainer?.removeEventListener(`scroll`,this.handlePreviewScroll),this.previewElement?.removeEventListener(`pointermove`,this.handlePreviewPointerMove),this.previewElement?.removeEventListener(`pointerleave`,this.handlePreviewPointerLeave),this.previewElement?.removeEventListener(`focusin`,this.handlePreviewFocusIn),this.previewElement?.removeEventListener(`focusout`,this.handlePreviewFocusOut),this.commentSelectionButton?.removeEventListener(`pointerdown`,this.handleCommentSelectionButtonPointerDown),this.editorContainer?.removeEventListener(`pointerdown`,this.handleEditorPointerDown),this.editorContainer?.removeEventListener(`focusout`,this.handleEditorFocusOut),window.removeEventListener(`resize`,this.handleWindowResize),document.removeEventListener(`pointerup`,this.handleDocumentPointerUp),document.removeEventListener(`pointercancel`,this.handleDocumentPointerUp),document.removeEventListener(`pointerdown`,this.handleDocumentPointerDown),document.removeEventListener(`keydown`,this.handleDocumentKeyDown),this.previewHoverRegions=[],this.cardRoot?.remove(),this.editorLayer?.remove(),this.previewLayer?.remove(),this.pendingCardFocusElement=null}};Object.assign(Eo.prototype,To,mo,co,qa);var Do=360,Oo=`https://viewer.diagrams.net/js/viewer-static.min.js`,ko=null;function Ao(e,t){return typeof window.requestIdleCallback==`function`?window.requestIdleCallback(e,{timeout:t}):window.setTimeout(()=>e({didTimeout:!1,timeRemaining:()=>0}),1)}function jo(e){if(e!==null){if(typeof window.cancelIdleCallback==`function`){window.cancelIdleCallback(e);return}window.clearTimeout(e)}}function Mo(e,t,n){if(!e||!t)return!1;let r=t.getBoundingClientRect(),i=e.getBoundingClientRect();return i.bottom>=r.top-n&&i.top<=r.bottom+n}function No(){return window.GraphViewer?.processElements?Promise.resolve(window.GraphViewer):ko||(ko=new Promise((e,t)=>{let n=document.querySelector(`script[data-collabmd-drawio-viewer]`),r=n instanceof HTMLScriptElement?n:document.createElement(`script`),i=()=>{r.removeEventListener(`error`,a),r.removeEventListener(`load`,o)},a=()=>{i(),ko=null,t(Error(`Failed to load draw.io viewer`))},o=()=>{if(i(),!window.GraphViewer?.processElements){ko=null,t(Error(`draw.io viewer did not initialize`));return}e(window.GraphViewer)};r.addEventListener(`error`,a,{once:!0}),r.addEventListener(`load`,o,{once:!0}),n?window.GraphViewer?.processElements&&o():(r.src=Oo,r.async=!0,r.dataset.collabmdDrawioViewer=`true`,document.head.append(r))}),ko)}var Po=class{constructor({getLocalUser:e,getTheme:t,onOpenFile:n=null,onOpenTextFile:r=null,previewContainer:i,previewElement:a,toastController:o}){this.getLocalUser=e,this.getTheme=t,this.onOpenFile=n,this.onOpenTextFile=r,this.previewContainer=i,this.previewElement=a,this.toastController=o,this.embedEntries=new Map,this.hydrationQueue=[],this.hydrationIdleId=null,this.hydrationPaused=!1,this.instanceCounter=0,this.maximizedEntry=null,this.maximizedRoot=null,this._onMessage=this._onMessage.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onPreviewClick=this._onPreviewClick.bind(this),window.addEventListener(`message`,this._onMessage),window.addEventListener(`keydown`,this._onKeyDown),this.previewElement?.addEventListener(`click`,this._onPreviewClick)}destroy(){window.removeEventListener(`message`,this._onMessage),window.removeEventListener(`keydown`,this._onKeyDown),this.previewElement?.removeEventListener(`click`,this._onPreviewClick),jo(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this._exitMaximizedEntry(),document.body.classList.remove(`drawio-maximized-open`),this.embedEntries.forEach(e=>e.wrapper?.remove()),this.embedEntries.clear(),this.maximizedRoot?.remove(),this.maximizedRoot=null}detachForCommit(){jo(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this.embedEntries.forEach(e=>{e.placeholder=null})}setHydrationPaused(e){this.hydrationPaused=!!e,this.hydrationPaused||this.hydrateVisibleEmbeds()}reconcileEmbeds(e){this._exitMaximizedEntry();let t=Array.from(e.querySelectorAll(`.drawio-embed-placeholder[data-drawio-key]`)).map(e=>({filePath:e.dataset.drawioTarget||``,key:e.dataset.drawioKey||``,label:e.dataset.drawioLabel||e.dataset.drawioTarget||``,mode:e.dataset.drawioMode===`edit`?`edit`:`view`,placeholder:e})),n=new Map;t.forEach(e=>{let t=this.embedEntries.get(e.key)||null,r=t?{...t,...e}:{...e,iframe:null,imageElement:null,instanceId:``,queued:!1,viewerElement:null,wrapper:null};n.set(e.key,r)}),this.embedEntries.forEach((e,t)=>{n.has(t)||e.wrapper?.remove()}),this.embedEntries=n,this.embedEntries.forEach(e=>{e.wrapper?e.placeholder?.replaceWith(e.wrapper):e.queued=!1}),this.hydrationPaused||this.hydrateVisibleEmbeds()}hydrateVisibleEmbeds(){this.embedEntries.forEach(e=>{e.wrapper||!e.placeholder?.isConnected||(e.mode===`edit`||Mo(e.placeholder,this.previewContainer,Do))&&this.enqueueHydration(e)})}enqueueHydration(e){e.queued||(e.queued=!0,this.hydrationQueue.push(e),this.hydrationIdleId===null&&(this.hydrationIdleId=Ao(()=>{this.hydrationIdleId=null,this.hydrationQueue.splice(0).forEach(e=>{e.queued=!1,this.hydrateEntry(e)})},200)))}hydrateEntry(e){if(!(!e.placeholder?.isConnected||e.wrapper)){if(e.mode===`view`){this.hydrateViewerEntry(e);return}this.hydrateIframeEntry(e)}}hydrateIframeEntry(e){if(!e.placeholder?.isConnected||e.wrapper)return;let t=document.createElement(`div`);t.className=`drawio-embed diagram-preview-shell${e.mode===`edit`?` is-direct-file`:``}`,t.dataset.file=e.filePath,t.dataset.drawioKey=e.key;let n=document.createElement(`div`);n.className=`drawio-embed-header diagram-preview-toolbar`;let r=document.createElement(`span`);r.className=`drawio-embed-icon`,r.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="7" height="6" rx="1"/><rect x="14" y="4" width="7" height="6" rx="1"/><rect x="8.5" y="14" width="7" height="6" rx="1"/><path d="M10 7h4"/><path d="M17.5 10v2.5"/><path d="M6.5 10v2.5"/><path d="M6.5 12.5h11"/></svg>`;let i=document.createElement(`span`);i.className=`drawio-embed-label`,i.textContent=e.label.replace(/\.drawio$/i,``),n.append(r,i),e.mode!==`edit`&&n.appendChild(this.createOpenButton(e)),n.appendChild(this.createMaximizeButton(e,t));let a=document.createElement(`iframe`);a.className=`drawio-embed-iframe`,a.loading=`lazy`,a.referrerPolicy=`strict-origin-when-cross-origin`,e.instanceId=`drawio-${++this.instanceCounter}`,a.dataset.instanceId=e.instanceId,a.src=this.buildIframeUrl(e),t.append(n,a),e.iframe=a,e.wrapper=t,e.placeholder.replaceWith(t)}async hydrateViewerEntry(e){if(!e.placeholder?.isConnected||e.wrapper)return;let t=document.createElement(`div`);t.className=`drawio-embed diagram-preview-shell is-static-preview`,t.dataset.file=e.filePath,t.dataset.drawioKey=e.key;let n=document.createElement(`div`);n.className=`drawio-embed-header diagram-preview-toolbar`;let r=document.createElement(`span`);r.className=`drawio-embed-icon`,r.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="7" height="6" rx="1"/><rect x="14" y="4" width="7" height="6" rx="1"/><rect x="8.5" y="14" width="7" height="6" rx="1"/><path d="M10 7h4"/><path d="M17.5 10v2.5"/><path d="M6.5 10v2.5"/><path d="M6.5 12.5h11"/></svg>`;let i=document.createElement(`span`);i.className=`drawio-embed-label`,i.textContent=e.label.replace(/\.drawio$/i,``),n.append(r,i),n.append(this.createOpenButton(e),this.createMaximizeButton(e,t));let a=document.createElement(`div`);a.className=`drawio-viewer-shell`,a.dataset.filePath=e.filePath;let o=document.createElement(`div`);o.className=`preview-shell`,o.textContent=`Rendering draw.io preview…`,a.appendChild(o),t.append(n,a),e.iframe=null,e.wrapper=t,e.viewerElement=a,e.placeholder.replaceWith(t);try{await this.renderViewerEntry(e)}catch(t){this.renderViewerFallback(e,t instanceof Error?t.message:`Failed to render draw.io preview`)}}async renderViewerEntry(e){let[{content:t},n]=await Promise.all([S.readFile(e.filePath),No()]);if(!e.wrapper?.isConnected||!e.viewerElement?.isConnected)return;let r=this.getTheme?.()===`light`?`light`:`dark`,i=document.createElement(`div`);i.className=`mxgraph drawio-viewer-frame`,i.dataset.action=`open-file`,i.dataset.filePath=e.filePath,i.setAttribute(`role`,`button`),i.setAttribute(`tabindex`,`0`),i.setAttribute(`aria-label`,`Open ${e.label.replace(/\.drawio$/i,``)}`),i.addEventListener(`click`,t=>{t.preventDefault(),this.onOpenFile?.(e.filePath)}),i.addEventListener(`keydown`,t=>{t.key!==`Enter`&&t.key!==` `||(t.preventDefault(),this.onOpenFile?.(e.filePath))}),i.dataset.mxgraph=JSON.stringify({"check-visible-state":!1,center:!0,border:0,"dark-mode":r,editable:!1,fit:1,lightbox:!1,nav:!1,resize:!1,toolbar:``,tooltips:!1,xml:String(t??``)}),e.viewerElement.replaceChildren(i),e.viewerElement=i,n.processElements()}buildIframeUrl(e){let t=new URL(w(`/drawio-editor.html`)),n=this.getLocalUser?.()??{};return t.searchParams.set(`file`,e.filePath),t.searchParams.set(`hostMode`,e.mode===`edit`?`file-preview`:`embed`),t.searchParams.set(`instanceId`,e.instanceId),t.searchParams.set(`mode`,e.mode===`edit`?`edit`:`view`),t.searchParams.set(`theme`,this.getTheme?.()===`light`?`light`:`dark`),n.name&&t.searchParams.set(`userName`,n.name),n.peerId&&t.searchParams.set(`peerId`,n.peerId),e.mode===`edit`&&t.searchParams.set(`leaseRoom`,ce(e.filePath)),t.toString()}updateTheme(e){this.embedEntries.forEach(t=>{t.iframe?.contentWindow&&t.iframe.contentWindow.postMessage({source:`collabmd-host`,theme:e,type:`set-theme`},window.location.origin),t.mode===`view`&&t.wrapper?.isConnected&&t.viewerElement?.isConnected&&this.renderViewerEntry(t).catch(e=>{this.renderViewerFallback(t,e instanceof Error?e.message:`Failed to render draw.io preview`)})})}updateLocalUser(){}syncLayout(){}createOpenButton(e){let t=document.createElement(`button`);return t.type=`button`,t.className=`drawio-embed-btn ui-preview-action ui-preview-action--icon-only`,t.dataset.action=`open-file`,t.dataset.filePath=e.filePath,t.title=`Edit in draw.io`,t.setAttribute(`aria-label`,`Edit in draw.io`),P(t,`edit`),t.addEventListener(`click`,t=>{t.preventDefault(),this.onOpenFile?.(e.filePath)}),t}createMaximizeButton(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`drawio-embed-btn ui-preview-action ui-preview-action--icon-only`,n.dataset.action=`toggle-maximize`,n.dataset.filePath=e.filePath,n.dataset.drawioKey=e.key,n.addEventListener(`click`,n=>{n.preventDefault(),this.maximizedEntry?.key===e.key?this._exitMaximizedEntry():this._enterMaximizedEntry(e,t),this._syncMaximizeButtons()}),(()=>{let t=this.maximizedEntry?.key===e.key;P(n,t?`restore`:`maximize`),n.title=t?`Restore diagram size`:`Maximize diagram`,n.setAttribute(`aria-label`,t?`Restore diagram size`:`Maximize diagram`)})(),n}_ensureMaximizedRoot(){if(this.maximizedRoot?.isConnected&&this.maximizedRoot.parentElement===document.body)return this.maximizedRoot;let e=document.body.querySelector(`[data-drawio-maximized-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.drawioMaximizedRoot=`true`,e.className=`drawio-maximized-root`,document.body.appendChild(e)),this.maximizedRoot=e,e}_enterMaximizedEntry(e,t=e?.wrapper){if(!e?.wrapper||e.wrapper!==t||this.maximizedEntry?.key===e.key)return;this._exitMaximizedEntry();let n=this._ensureMaximizedRoot(),r=e.wrapper.parentElement;if(!r)return;let i=document.createElement(`div`);i.className=`drawio-maximize-spacer`,i.style.height=`${Math.ceil(e.wrapper.getBoundingClientRect().height)}px`,e.maximizeSpacer=i,e.restoreParent=r,e.restoreNextSibling=e.wrapper.nextSibling||null,r.insertBefore(i,e.wrapper),n.hidden=!1,n.appendChild(e.wrapper),e.wrapper.classList.add(`is-maximized`),document.body.classList.add(`drawio-maximized-open`),this.maximizedEntry=e}_exitMaximizedEntry(){let e=this.maximizedEntry;if(!e?.wrapper){this.maximizedEntry=null,document.body.classList.remove(`drawio-maximized-open`);return}let{maximizeSpacer:t,restoreNextSibling:n,restoreParent:r}=e;e.wrapper.classList.remove(`is-maximized`),t?.parentElement?t.replaceWith(e.wrapper):r?.isConnected&&(n?.parentElement===r?r.insertBefore(e.wrapper,n):r.appendChild(e.wrapper)),e.maximizeSpacer=null,e.restoreParent=null,e.restoreNextSibling=null,this.maximizedEntry=null,document.body.classList.remove(`drawio-maximized-open`),this.maximizedRoot&&this.maximizedRoot.childElementCount===0&&(this.maximizedRoot.hidden=!0)}_syncMaximizeButtons(){this.embedEntries.forEach(e=>{let t=e.wrapper?.querySelector(`.drawio-embed-btn[data-action="toggle-maximize"]`);if(!(t instanceof HTMLElement))return;let n=this.maximizedEntry?.key===e.key;P(t,n?`restore`:`maximize`),t.title=n?`Restore diagram size`:`Maximize diagram`,t.setAttribute(`aria-label`,n?`Restore diagram size`:`Maximize diagram`)})}_findEntryByInstanceId(e){for(let t of this.embedEntries.values())if(t.instanceId===e)return t;return null}_onMessage(e){let t=e.data;if(!t||t.source!==`drawio-editor`)return;let n=this._findEntryByInstanceId(t.instanceId);if(n){if(t.type===`fallback-text`){if(n.mode===`view`){this.renderViewerFallback(n,`Failed to render draw.io preview`);return}this.onOpenTextFile?.(n.filePath);return}if(t.type===`error`){if(n.mode===`view`){this.renderViewerFallback(n,t.message||`Failed to load draw.io preview`);return}this.toastController?.show?.(t.message||`Failed to load draw.io`);return}t.type===`request-open-file`&&this.onOpenFile?.(n.filePath)}}_onPreviewClick(e){let t=e.target.closest(`.drawio-embed-placeholder-btn`);if(t){let n=t.closest(`.drawio-embed-placeholder`)?.dataset.drawioKey||``,r=this.embedEntries.get(n);r&&(e.preventDefault(),this.hydrateEntry(r));return}}_onKeyDown(e){e.key===`Escape`&&(this._exitMaximizedEntry(),this._syncMaximizeButtons())}renderViewerFallback(e,t){if(!e.wrapper)return;let n=e.wrapper.querySelector(`.drawio-viewer-shell, .drawio-viewer-frame`);if(!n)return;let r=document.createElement(`div`);r.className=`preview-shell`,r.textContent=t,n.replaceChildren(r),e.viewerElement=r}};function Fo(e,t){let n=new Map;t.forEach(t=>{let r=e.get(t.key)??{filePath:t.filePath,iframe:null,instanceId:null,key:t.key,label:t.label,placeholder:t.placeholder,queued:!1,wrapper:null};r.filePath=t.filePath,r.key=t.key,r.label=t.label,r.placeholder=t.placeholder,n.set(t.key,r)});let r=[];return e.forEach((e,t)=>{n.has(t)||r.push(e)}),{nextEntries:n,removedEntries:r}}var Io=420,Lo=500,Ro=15e3,zo=800,Bo=3,Vo=200,Ho=`/excalidraw-editor.html`;function Uo(e,t){return typeof window.requestIdleCallback==`function`?window.requestIdleCallback(e,{timeout:t}):window.setTimeout(()=>{e({didTimeout:!1,timeRemaining:()=>0})},1)}function Wo(e){if(e!==null){if(typeof window.cancelIdleCallback==`function`){window.cancelIdleCallback(e);return}window.clearTimeout(e)}}function Go(e,t,n){if(!e||!t)return!1;let r=t.getBoundingClientRect(),i=e.getBoundingClientRect();return i.bottom>=r.top-n&&i.top<=r.bottom+n}var Ko=class{constructor({getTheme:e,getLocalUser:t,onOpenFile:n=null,previewContainer:r,previewElement:i,toastController:a}){this.getTheme=e,this.getLocalUser=t,this.onOpenFile=n,this.previewContainer=r,this.previewElement=i,this.toastController=a,this.embedEntries=new Map,this.hydrationQueue=[],this.hydrationIdleId=null,this.hydrationPaused=!1,this.hydrationInProgress=!1,this.instanceCounter=0,this.isLargeDocument=!1,this.maximizedEmbed=null,this.overlayRoot=null,this.maximizedRoot=null,this.warmCacheRoot=null,this.warmEntry=null,this.placeholderObserver=null,this.followedPeerIdsByFilePath=new Map,this.pendingDisconnectRequests=new Map,this.disconnectRequestCounter=0,this._onMessage=this._onMessage.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onPreviewClick=this._onPreviewClick.bind(this),window.addEventListener(`message`,this._onMessage),window.addEventListener(`keydown`,this._onKeyDown),this.previewElement?.addEventListener(`click`,this._onPreviewClick)}destroy(){window.removeEventListener(`message`,this._onMessage),window.removeEventListener(`keydown`,this._onKeyDown),this.previewElement?.removeEventListener(`click`,this._onPreviewClick),this._disconnectPlaceholderObserver(),Wo(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this._exitMaximizedEmbed(),document.body.classList.remove(`excalidraw-maximized-open`),this.embedEntries.forEach(e=>{this._clearEntryBootTimeout(e),e.wrapper?.remove(),e.placeholder=null}),this.embedEntries.clear(),this.warmEntry&&=(this._clearEntryBootTimeout(this.warmEntry),this.warmEntry.wrapper?.remove(),null),this.pendingDisconnectRequests.forEach(e=>{e.resolve(!1)}),this.pendingDisconnectRequests.clear(),this.followedPeerIdsByFilePath.clear(),this.overlayRoot?.remove(),this.overlayRoot=null,this.maximizedRoot?.remove(),this.maximizedRoot=null,this.warmCacheRoot?.remove(),this.warmCacheRoot=null}async setFollowedUser(e,t=null){if(!e)return!1;this.followedPeerIdsByFilePath.set(e,t||null);let n=this._findEntryByFilePath(e);return n?(n.wrapper||await this._hydrateEntry(n),n.followedPeerId=this.followedPeerIdsByFilePath.get(e)??null,this._syncEntryFollowState(n),!0):!0}detachForCommit(){this._disconnectPlaceholderObserver(),Wo(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this.hydrationInProgress=!1,this._exitMaximizedEmbed(),this.overlayRoot&&(this.overlayRoot.hidden=!0),this.maximizedRoot&&(this.maximizedRoot.hidden=!0),this.embedEntries.forEach(e=>{e.queued=!1,e.placeholder=null})}setHydrationPaused(e){if(this.hydrationPaused=!!e,this.hydrationPaused){Wo(this.hydrationIdleId),this.hydrationIdleId=null;return}this.hydrateVisibleEmbeds(),this._scheduleHydration()}reconcileEmbeds(e,{isLargeDocument:t=!1}={}){this.isLargeDocument=!!t,this._disconnectPlaceholderObserver(),Wo(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this.hydrationInProgress=!1;let n=Array.from(e.querySelectorAll(`.excalidraw-embed-placeholder[data-embed-key]`)).map(e=>({filePath:e.dataset.embedTarget,key:e.dataset.embedKey,label:e.dataset.embedLabel||e.dataset.embedTarget,placeholder:e})),{nextEntries:r,removedEntries:i}=Fo(this.embedEntries,n);this._captureWarmEntry(i),this._adoptReusableEntries(r,i),i.forEach(e=>this._destroyEntry(e)),this.embedEntries=r,this._ensurePlaceholderObserver(),this.embedEntries.forEach(e=>{if(e.queued=!1,e.followedPeerId=this.followedPeerIdsByFilePath.get(e.filePath),e.wrapper){this._hydrateEntry(e);return}e.placeholder&&this.placeholderObserver?.observe(e.placeholder)}),this.hydrationPaused||this.hydrateVisibleEmbeds(),this.syncLayout()}hydrateVisibleEmbeds(){if(this.hydrationPaused)return;let e=this.isLargeDocument?180:420;this.embedEntries.forEach(t=>{t.wrapper||!t.placeholder?.isConnected||Go(t.placeholder,this.previewContainer,e)&&this._enqueueHydration(t,{prioritize:!0})})}updateTheme(e){this._forEachManagedEntry(t=>{this._postMessageToEntry(t,{source:`collabmd-host`,type:`set-theme`,theme:e})})}updateLocalUser(e){this._forEachManagedEntry(t=>{this._syncEntryUser(t,e)})}prepareFileDisconnect(e,{timeoutMs:t=250}={}){let n=this._findEntryByFilePath(e);if(!n?.iframe?.contentWindow)return Promise.resolve(!1);let r=`disconnect-${++this.disconnectRequestCounter}`;return new Promise(e=>{let i=t=>{if(!this.pendingDisconnectRequests.has(r))return;let n=this.pendingDisconnectRequests.get(r);window.clearTimeout(n.timeoutId),this.pendingDisconnectRequests.delete(r),e(t)},a=window.setTimeout(()=>{i(!1)},t);this.pendingDisconnectRequests.set(r,{entry:n,resolve:i,timeoutId:a}),this._postMessageToEntry(n,{source:`collabmd-host`,type:`prepare-disconnect`,requestId:r})})}_ensurePlaceholderObserver(){this.previewContainer&&(this.placeholderObserver=new IntersectionObserver(e=>{e.forEach(e=>{if(!e.isIntersecting)return;let t=this.embedEntries.get(e.target.dataset.embedKey);t&&this._enqueueHydration(t)})},{root:this.previewContainer,rootMargin:this.isLargeDocument?`180px 0px`:`420px 0px`}))}_disconnectPlaceholderObserver(){this.placeholderObserver&&=(this.placeholderObserver.disconnect(),null)}_enqueueHydration(e,{prioritize:t=!1}={}){if(!(!e||e.wrapper||e.queued)&&(e.queued=!0,t?this.hydrationQueue.unshift(e.key):this.hydrationQueue.push(e.key),!this.hydrationPaused)){if(t&&!this.hydrationInProgress&&this.hydrationIdleId===null){this._flushHydrationQueue();return}this._scheduleHydration()}}_scheduleHydration(){this.hydrationPaused||this.hydrationInProgress||this.hydrationIdleId!==null||(this.hydrationIdleId=Uo(()=>{this.hydrationIdleId=null,this._flushHydrationQueue()},Lo))}async _flushHydrationQueue(){if(this.hydrationPaused||this.hydrationInProgress)return;let e=null;for(;this.hydrationQueue.length>0&&!e;){let t=this.hydrationQueue.shift(),n=this.embedEntries.get(t);if(!n||n.wrapper||!n.placeholder?.isConnected){n&&(n.queued=!1);continue}e=n}e&&(this.hydrationInProgress=!0,e.queued=!1,await this._hydrateEntry(e),this.hydrationInProgress=!1,this.hydrationQueue.length>0&&this._scheduleHydration())}async _hydrateEntry(e){if(!(!e.placeholder?.isConnected&&!e.wrapper)){if(e.isParked=!1,!e.wrapper){let t=this._createEmbedContainer(e);e.header=t.header,e.wrapper=t.wrapper,e.iframe=t.iframe,e.labelElement=t.labelElement,e.maxButton=t.maxButton,e.openButton=t.openButton,e.instanceId=t.instanceId,e.isReady=!1,e.bootFilePath=e.filePath,e.bootMode=this._getEntryMode(e),e.loadedFilePath=e.bootFilePath,e.loadedMode=e.bootMode,e.bootAttempts=(e.bootAttempts??0)+1,this._armEntryBootTimeout(e)}e.followedPeerId=this.followedPeerIdsByFilePath.get(e.filePath),this._updateEmbedLabel(e),this._entryNeedsHardReload(e)&&this._reloadEntry(e),this._attachWrapper(e)}}_attachWrapper(e){let t=e.placeholder?.isConnected?e.placeholder:this.previewElement?.querySelector(`.excalidraw-embed-placeholder[data-embed-key="${e.key}"]`);if(!t)return;if(e.placeholder=t,this._syncMountedEntryMetadata(e),this._shouldInlineFilePreview(e)){e.wrapper.style.position=``,e.wrapper.style.top=``,e.wrapper.style.left=``,e.wrapper.style.width=``,e.wrapper.style.margin=``,e.wrapper.style.pointerEvents=`auto`,t.replaceWith(e.wrapper),e.placeholder=null;return}let n=this._ensureOverlayRoot();n.hidden=!1,e.wrapper?.parentElement!==n&&n.appendChild(e.wrapper),this._syncEntryLayout(e)}_adoptReusableEntries(e,t){e.forEach((n,r)=>{if(n.wrapper||n.iframe)return;let i=this._claimReusableEntry(n,t);i&&(i.filePath=n.filePath,i.key=n.key,i.label=n.label,i.placeholder=n.placeholder,i.queued=!1,e.set(r,i))})}_destroyEntry(e){this.pendingDisconnectRequests.forEach((t,n)=>{t.entry===e&&(t.resolve(!1),this.pendingDisconnectRequests.delete(n))}),this.maximizedEmbed?.wrapper===e.wrapper&&this._exitMaximizedEmbed(),this._clearEntryBootTimeout(e),this.warmEntry===e&&(this.warmEntry=null),this._resetPlaceholderLayout(e),this._setEntryLoadingState(e,!1),e.wrapper?.remove(),e.placeholder=null}_armEntryBootTimeout(e,t=Ro){this._clearEntryBootTimeout(e),e.bootTimerId=window.setTimeout(()=>{this._handleEntryBootTimeout(e)},t)}_clearEntryBootTimeout(e){e?.bootTimerId&&(window.clearTimeout(e.bootTimerId),e.bootTimerId=null)}async _handleEntryBootTimeout(e){if(e?.iframe?.isConnected){if((e.bootAttempts??0)>=Bo){this._clearEntryBootTimeout(e),this.toastController?.show(`Excalidraw embed timed out: ${e.label}`);return}await this._retryEntryBootstrap(e)}}async _retryEntryBootstrap(e){e&&(this._clearEntryBootTimeout(e),this._resetPlaceholderLayout(e),this._setEntryLoadingState(e,!1),this.maximizedEmbed?.wrapper===e.wrapper&&this._exitMaximizedEmbed(),e.wrapper?.remove(),e.wrapper=null,e.iframe=null,e.header=null,e.labelElement=null,e.maxButton=null,e.openButton=null,e.instanceId=null,e.isReady=!1,e.isParked=!1,e.bootFilePath=null,e.bootMode=null,e.loadedFilePath=null,e.loadedMode=null,await this._hydrateEntry(e))}_findEntryByContentWindow(e){if(!e)return null;for(let t of this.embedEntries.values())if(t.iframe?.contentWindow===e)return t;return this.warmEntry?.iframe?.contentWindow===e?this.warmEntry:null}_findEntryByFilePath(e){if(!e)return null;for(let t of this.embedEntries.values())if(t.filePath===e)return t;return this.warmEntry?.filePath===e?this.warmEntry:null}_updateEmbedLabel(e){e.labelElement&&(e.labelElement.textContent=e.label.replace(/\.excalidraw$/i,``))}_syncMountedEntryMetadata(e){e.wrapper&&(e.wrapper.dataset.embedKey=e.key,e.wrapper.dataset.file=e.filePath,e.wrapper.classList.toggle(`is-direct-file`,this._isFilePreviewEntry(e))),e.iframe&&(e.iframe.title=`Excalidraw: ${e.filePath}`),e.openButton&&(this._isFilePreviewEntry(e)?e.openButton.remove():!e.openButton.isConnected&&e.header&&e.header.insertBefore(e.openButton,e.maxButton||null))}_buildIframeUrl(e){let t=new URL(w(Ho)),n=this.getTheme?.()||`dark`;t.searchParams.set(`file`,e.filePath),t.searchParams.set(`theme`,n),t.searchParams.set(`boot`,e.instanceId||``),this._isFilePreviewEntry(e)||t.searchParams.set(`mode`,`preview`);let r=this.getLocalUser?.();r?.name&&t.searchParams.set(`userName`,r.name),r?.color&&t.searchParams.set(`userColor`,r.color),r?.colorLight&&t.searchParams.set(`userColorLight`,r.colorLight),r?.peerId&&t.searchParams.set(`userPeerId`,r.peerId);let i=new URLSearchParams(window.location.search),a=i.get(`server`);return a&&t.searchParams.set(`server`,a),i.get(`test`)===`1`&&t.searchParams.set(`test`,`1`),i.has(`syncTimeoutMs`)&&t.searchParams.set(`syncTimeoutMs`,i.get(`syncTimeoutMs`)),t}_createEmbedContainer(e){let t=document.createElement(`div`);t.className=`excalidraw-embed diagram-preview-shell`,t.dataset.embedKey=e.key,t.dataset.file=e.filePath;let n=document.createElement(`div`);n.className=`excalidraw-embed-header diagram-preview-toolbar`;let r=document.createElement(`span`);r.className=`excalidraw-embed-icon`,r.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19l7-7 3 3-7 7-3-3z"/><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><path d="M2 2l7.586 7.586"/><circle cx="11" cy="11" r="2"/></svg>`;let i=document.createElement(`span`);i.className=`excalidraw-embed-label`,i.textContent=e.label.replace(/\.excalidraw$/i,``);let a=document.createElement(`button`);a.type=`button`,a.className=`excalidraw-embed-btn ui-preview-action ui-preview-action--icon-only`,a.title=`Edit in Excalidraw`,a.setAttribute(`aria-label`,`Edit in Excalidraw`),P(a,`edit`);let o=document.createElement(`button`);o.type=`button`,o.className=`excalidraw-embed-btn ui-preview-action ui-preview-action--icon-only`,o.title=`Maximize diagram`,o.setAttribute(`aria-label`,`Maximize diagram`),P(o,`maximize`),n.append(r,i),this._isFilePreviewEntry(e)||n.append(a),n.append(o);let s=document.createElement(`iframe`);s.className=`excalidraw-embed-iframe`,s.dataset.instanceId=String(++this.instanceCounter),e.instanceId=s.dataset.instanceId,s.src=this._buildIframeUrl(e).toString(),s.setAttribute(`loading`,`eager`),s.title=`Excalidraw: ${e.filePath}`,s.style.height=`${Io}px`;let c=document.createElement(`div`);c.className=`excalidraw-embed-resizer`,c.title=`Drag to resize`,this._setupResizer(c,s,()=>this._syncEntryLayout(e)),t.append(n,s,c);let l=!1,u=`${Io}px`,d=()=>{P(o,l?`restore`:`maximize`),o.title=l?`Restore diagram size`:`Maximize diagram`,o.setAttribute(`aria-label`,l?`Restore diagram size`:`Maximize diagram`)},f=()=>{l&&(l=!1,t.classList.remove(`is-maximized`),d(),document.body.classList.remove(`excalidraw-maximized-open`),this._restoreWrapperMount(e),s.style.height=u,this.maximizedEmbed?.wrapper===t&&(this.maximizedEmbed=null),this._syncEntryLayout(e))},p=()=>{l||(this._exitMaximizedEmbed(),l=!0,u=s.style.height||`${Io}px`,this._mountWrapperInMaximizedRoot(e),t.classList.add(`is-maximized`),d(),document.body.classList.add(`excalidraw-maximized-open`),this.maximizedEmbed={wrapper:t,exit:f},this._syncEntryLayout(e))};return o.addEventListener(`click`,()=>{l?f():p()}),a.addEventListener(`click`,t=>{t.preventDefault(),this._exitMaximizedEmbed(),this.onOpenFile?.(e.filePath)}),d(),{header:n,iframe:s,instanceId:s.dataset.instanceId,labelElement:i,maxButton:o,openButton:a,wrapper:t}}_ensureWarmCacheRoot(){if(this.warmCacheRoot?.isConnected&&this.warmCacheRoot.parentElement===document.body)return this.warmCacheRoot;let e=document.body.querySelector(`[data-excalidraw-warm-cache-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.excalidrawWarmCacheRoot=`true`,e.className=`excalidraw-warm-cache-root`,document.body.appendChild(e)),this.warmCacheRoot=e,e}_setupResizer(e,t,n=null){let r=0,i=0,a=e=>{let n=e.clientY-r,a=Math.min(Math.max(i+n,Vo),zo);t.style.height=`${a}px`,t.style.pointerEvents=`none`},o=()=>{t.style.pointerEvents=``,document.removeEventListener(`pointermove`,a),document.removeEventListener(`pointerup`,o),n?.()};e.addEventListener(`pointerdown`,e=>{e.preventDefault(),r=e.clientY,i=t.offsetHeight,document.addEventListener(`pointermove`,a),document.addEventListener(`pointerup`,o)})}_ensureOverlayRoot(){if(this.overlayRoot?.isConnected&&this.overlayRoot.parentElement===this.previewElement)return this.overlayRoot;let e=this.previewElement?.querySelector(`[data-excalidraw-overlay-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.excalidrawOverlayRoot=`true`,e.className=`excalidraw-embed-overlay-root`,this.previewElement?.appendChild(e)),this.overlayRoot=e,e}_ensureMaximizedRoot(){if(this.maximizedRoot?.isConnected&&this.maximizedRoot.parentElement===document.body)return this.maximizedRoot;let e=document.body.querySelector(`[data-excalidraw-maximized-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.excalidrawMaximizedRoot=`true`,e.className=`excalidraw-maximized-root`,document.body.appendChild(e)),this.maximizedRoot=e,e}_isFilePreviewEntry(e){return e?.key===`${e?.filePath}#file-preview`}_getEntryMode(e){return this._isFilePreviewEntry(e)?`edit`:`preview`}_shouldInlineFilePreview(e){return this._isFilePreviewEntry(e)}_entryNeedsHardReload(e){let t=this._getEntryMode(e);return!!(e?.wrapper&&e.iframe&&(e.isReady?e.loadedFilePath!==e.filePath||e.loadedMode!==t:e.bootFilePath!==e.filePath||e.bootMode!==t))}_setEntryLoadingState(e,t){e?.wrapper&&(e.wrapper.classList.toggle(`is-loading`,!!t),e.wrapper.setAttribute(`aria-busy`,t?`true`:`false`))}_forEachManagedEntry(e){let t=new Set;this.embedEntries.forEach(n=>{!n||t.has(n)||(t.add(n),e(n))}),this.warmEntry&&!t.has(this.warmEntry)&&e(this.warmEntry)}_claimEntryFromRemovedEntries(e,t){let n=e.findIndex(e=>(e.wrapper||e.iframe)&&t(e));if(n<0)return null;let[r]=e.splice(n,1);return r}_claimReusableEntry(e,t){let n=this._getEntryMode(e);return this._claimEntryFromRemovedEntries(t,t=>t.filePath===e.filePath&&this._getEntryMode(t)===n)||(this._isFilePreviewEntry(e)?this._claimEntryFromRemovedEntries(t,t=>t.filePath===e.filePath)||this._claimWarmEntry()||this._claimEntryFromRemovedEntries(t,e=>this._isFilePreviewEntry(e)):null)}_claimWarmEntry(){let e=this.warmEntry;return e?(this.warmEntry=null,e):null}_captureWarmEntry(e){let t=this._claimEntryFromRemovedEntries(e,e=>this._isFilePreviewEntry(e));t&&(this.warmEntry&&this.warmEntry!==t&&this._destroyEntry(this.warmEntry),this.warmEntry=t,this._parkWarmEntry(t))}_parkWarmEntry(e){if(!e?.wrapper)return;this.maximizedEmbed?.wrapper===e.wrapper&&this._exitMaximizedEmbed();let t=this._ensureWarmCacheRoot();this._setEntryLoadingState(e,!1),e.isParked=!0,e.isReady=!1,e.bootFilePath=null,e.bootMode=null,e.loadedFilePath=null,e.loadedMode=null,e.placeholder=null,e.wrapper.parentElement!==t&&t.appendChild(e.wrapper),this._postMessageToEntry(e,{source:`collabmd-host`,type:`park-room`})}_reloadEntry(e){e?.iframe&&(this._clearEntryBootTimeout(e),this._setEntryLoadingState(e,!0),e.isReady=!1,e.bootAttempts=(e.bootAttempts??0)+1,e.bootFilePath=e.filePath,e.bootMode=this._getEntryMode(e),e.loadedFilePath=null,e.loadedMode=null,e.iframe.src=this._buildIframeUrl(e).toString(),this._armEntryBootTimeout(e))}_resetPlaceholderLayout(e){!e?.placeholder?.isConnected||this._shouldInlineFilePreview(e)||(e.placeholder.classList.remove(`is-hydrated`),e.placeholder.removeAttribute(`data-embed-hydrated`),e.placeholder.style.height=``,e.placeholder.style.pointerEvents=``)}_mountWrapperInMaximizedRoot(e){if(!e?.wrapper)return;let t=this._ensureMaximizedRoot();t.hidden=!1,e.restoreParent=e.wrapper.parentElement||null,e.restoreNextSibling=e.wrapper.nextSibling||null,e.wrapper.style.position=``,e.wrapper.style.top=``,e.wrapper.style.left=``,e.wrapper.style.width=``,e.wrapper.style.margin=``,e.wrapper.parentElement!==t&&t.appendChild(e.wrapper)}_restoreWrapperMount(e){if(e?.wrapper){if(this._shouldInlineFilePreview(e)){let{restoreParent:t,restoreNextSibling:n}=e;t?.isConnected&&(n?.parentElement===t?t.insertBefore(e.wrapper,n):t.appendChild(e.wrapper))}else{let t=this._ensureOverlayRoot();t.hidden=!1,e.wrapper.parentElement!==t&&t.appendChild(e.wrapper)}e.restoreParent=null,e.restoreNextSibling=null,this.maximizedRoot&&this.maximizedRoot.childElementCount===0&&(this.maximizedRoot.hidden=!0)}}_syncEntryLayout(e){if(!e?.wrapper||this._shouldInlineFilePreview(e))return;let t=e.placeholder?.isConnected?e.placeholder:this.previewElement?.querySelector(`.excalidraw-embed-placeholder[data-embed-key="${e.key}"]`);if(!t)return;e.placeholder=t,t.classList.add(`is-hydrated`),t.dataset.embedHydrated=`true`,t.style.pointerEvents=`none`,this._isFilePreviewEntry(e)&&t.childElementCount>0&&t.replaceChildren();let n=e.wrapper.classList.contains(`is-maximized`),r=e.wrapper.querySelector(`.excalidraw-embed-header`)?.offsetHeight||0,i=e.iframe?.offsetHeight||Number.parseFloat(e.iframe?.style.height||``)||Io,a=n?0:e.wrapper.querySelector(`.excalidraw-embed-resizer`)?.offsetHeight||0,o=Math.ceil(r+i+a);if(n||(e.inlineHeightPx=o),t.style.height=`${Math.ceil(e.inlineHeightPx||o||Io)}px`,e.wrapper.style.pointerEvents=`auto`,n){e.wrapper.style.position=``,e.wrapper.style.top=``,e.wrapper.style.left=``,e.wrapper.style.width=``,e.wrapper.style.margin=``;return}e.wrapper.style.position=`absolute`,e.wrapper.style.top=`${t.offsetTop}px`,e.wrapper.style.left=`${t.offsetLeft}px`,e.wrapper.style.width=`${t.offsetWidth}px`,e.wrapper.style.margin=`0`}syncLayout(){this.embedEntries.forEach(e=>{e.wrapper&&!this._shouldInlineFilePreview(e)&&this._syncEntryLayout(e)})}_onPreviewClick(e){let t=e.target.closest(`.excalidraw-embed-placeholder-btn`);if(!t)return;e.preventDefault();let n=this.embedEntries.get(t.dataset.embedKey);n&&this._hydrateEntry(n)}_onMessage(e){if(e.origin!==window.location.origin)return;let t=e.data;if(!t||t.source!==`excalidraw-editor`)return;let n=this._findEntryByContentWindow(e.source);if(n){if(t.type===`ready`){if(n.isParked)return;n.isReady=!0,this._clearEntryBootTimeout(n),n.loadedFilePath=n.bootFilePath||n.filePath,n.loadedMode=n.bootMode||this._getEntryMode(n),this._setEntryLoadingState(n,!1),this._syncEntryUser(n),this._postMessageToEntry(n,{source:`collabmd-host`,type:`set-theme`,theme:this.getTheme?.()||`dark`}),this._syncEntryFollowState(n),this._entryNeedsHardReload(n)&&this._hydrateEntry(n);return}if(t.type===`error`){if(n.isParked)return;n.isReady=!1,this._handleEntryBootTimeout(n);return}if(t.type===`disconnect-ready`){let e=this.pendingDisconnectRequests.get(t.requestId);e?.entry===n&&e.resolve(!0)}}}_onKeyDown(e){e.key===`Escape`&&this._exitMaximizedEmbed()}_exitMaximizedEmbed(){this.maximizedEmbed?.exit&&this.maximizedEmbed.exit(),this.maximizedEmbed=null,document.body.classList.remove(`excalidraw-maximized-open`)}_postMessageToEntry(e,t){e?.iframe?.contentWindow?.postMessage(t,window.location.origin)}_syncEntryUser(e,t=null){let n=t||this.getLocalUser?.();n&&this._postMessageToEntry(e,{source:`collabmd-host`,type:`set-user`,user:{color:n.color||``,colorLight:n.colorLight||``,name:n.name||``,peerId:n.peerId||``}})}_syncEntryFollowState(e){!e?.isReady||e.followedPeerId===void 0||this._postMessageToEntry(e,{source:`collabmd-host`,type:`follow-user`,peerId:e.followedPeerId})}};function qo(){return typeof window>`u`||typeof window.matchMedia!=`function`?{matches:!1}:window.matchMedia(`(max-width: 768px)`)}function Jo(e){return typeof HTMLElement>`u`||!(e instanceof HTMLElement)?[]:Array.from(e.querySelectorAll(`.create-menu-item`))}var Yo=class{constructor({mobileBreakpointQuery:e=qo()}={}){this.mobileBreakpointQuery=e,this.activeAnchor=null,this.desktopMenu=null,this.mobileBackdrop=null,this.mobileSheet=null,this.documentPointerDownHandler=null,this.windowResizeHandler=null,this.boundClose=()=>this.close()}isMobileViewport(){return!!this.mobileBreakpointQuery?.matches}isOpen(){return!!(this.desktopMenu||this.mobileSheet)}toggle(e={}){if(this.isOpen()){this.close();return}this.open(e)}open({anchor:e=null,items:t=[],title:n=`Create`}={}){if(this.close({restoreFocus:!1}),!(!Array.isArray(t)||t.length===0)){if(this.activeAnchor=typeof HTMLElement<`u`&&e instanceof HTMLElement?e:null,this.activeAnchor?.setAttribute(`aria-expanded`,`true`),this.isMobileViewport()){this.openMobileSheet({items:t,title:n});return}this.openDesktopMenu({anchor:this.activeAnchor,items:t,title:n})}}close({restoreFocus:e=!0}={}){this.desktopMenu&&=(this.desktopMenu.remove(),null),this.mobileBackdrop&&=(this.mobileBackdrop.remove(),null),this.mobileSheet&&=(this.mobileSheet.remove(),null),this.documentPointerDownHandler&&=(document.removeEventListener(`pointerdown`,this.documentPointerDownHandler),null),this.windowResizeHandler&&typeof window<`u`&&window.removeEventListener(`resize`,this.windowResizeHandler),this.windowResizeHandler=null;let t=this.activeAnchor;this.activeAnchor?.setAttribute(`aria-expanded`,`false`),this.activeAnchor=null,e&&t?.focus?.()}openDesktopMenu({anchor:e,items:t,title:n}){let r=document.createElement(`div`);r.className=`create-menu`,r.setAttribute(`role`,`menu`),r.setAttribute(`aria-label`,n),this.renderMenuItems(r,t),document.body.appendChild(r),this.positionDesktopMenu(r,e),r.addEventListener(`keydown`,e=>{this.handleDesktopMenuKeyDown(e,r)}),this.documentPointerDownHandler=t=>{r.contains(t.target)||e?.contains?.(t.target)||this.close()},this.windowResizeHandler=this.boundClose,setTimeout(()=>{document.addEventListener(`pointerdown`,this.documentPointerDownHandler)},0),typeof window<`u`&&window.addEventListener(`resize`,this.windowResizeHandler),this.desktopMenu=r,Jo(r)[0]?.focus()}openMobileSheet({items:e,title:t}){let n=document.createElement(`button`);n.type=`button`,n.className=`file-action-sheet-backdrop`,n.setAttribute(`aria-label`,`Close ${t.toLowerCase()} menu`);let r=document.createElement(`div`);r.className=`file-action-sheet create-action-sheet`;let i=document.createElement(`div`);i.className=`create-action-sheet-header`,i.textContent=t,r.appendChild(i),this.renderMenuItems(r,e,{mobile:!0});let a=document.createElement(`button`);a.type=`button`,a.className=G({variant:`ghost`,extra:[`file-action-sheet-item`,`create-action-sheet-cancel`]}),a.textContent=`Cancel`,a.addEventListener(`click`,()=>{this.close()}),r.appendChild(a),n.addEventListener(`click`,()=>{this.close()}),document.body.append(n,r),this.mobileBackdrop=n,this.mobileSheet=r}renderMenuItems(e,t,{mobile:n=!1}={}){let r=null;t.forEach(t=>{if(t.group&&t.group!==r){let i=document.createElement(`div`);i.className=n?`create-action-sheet-group`:`create-menu-group`,i.textContent=t.group,e.appendChild(i),r=t.group}let i=document.createElement(`button`);i.type=`button`,i.className=n?G({variant:`ghost`,extra:[`file-action-sheet-item`,`create-action-sheet-item`,`create-action-sheet-option`]}):`create-menu-item`,i.setAttribute(`role`,n?`button`:`menuitem`),i.dataset.actionId=t.id;let a=document.createElement(`span`);a.className=`create-menu-item-icon`,a.setAttribute(`aria-hidden`,`true`),a.innerHTML=t.icon||``,i.appendChild(a);let o=document.createElement(`span`);o.className=`create-menu-item-copy`;let s=document.createElement(`span`);s.className=`create-menu-item-label`,s.textContent=t.label,o.appendChild(s);let c=t.meta||t.hint;if(c){let e=document.createElement(`span`);e.className=`create-menu-item-meta`,e.textContent=c,o.appendChild(e)}i.appendChild(o),i.addEventListener(`click`,()=>{this.close({restoreFocus:!1}),t.onSelect?.()}),e.appendChild(i)})}positionDesktopMenu(e,t){let n=e.getBoundingClientRect(),r=t?.getBoundingClientRect?.(),i=r?.left??8,a=Math.max(8,window.innerWidth-n.width-8),o=Math.max(8,Math.min(i,a)),s=(r?.bottom??8)+8,c=window.innerHeight-n.height-8;s>c&&r&&(s=Math.max(8,r.top-n.height-8)),e.style.left=`${o}px`,e.style.top=`${Math.max(8,s)}px`}handleDesktopMenuKeyDown(e,t){let n=Jo(t);if(n.length===0)return;let r=Math.max(0,n.indexOf(document.activeElement));switch(e.key){case`ArrowDown`:e.preventDefault(),n[(r+1)%n.length]?.focus();break;case`ArrowUp`:e.preventDefault(),n[(r-1+n.length)%n.length]?.focus();break;case`Home`:e.preventDefault(),n[0]?.focus();break;case`End`:e.preventDefault(),n[n.length-1]?.focus();break;case`Escape`:e.preventDefault(),this.close();break;case`Tab`:this.close({restoreFocus:!1});break}}};function Xo(e){return String(e??``).replace(/\/+$/u,``).split(`/`).filter(Boolean).pop()||``}function Zo(e){let t=String(e??``).replace(/\/+$/u,``),n=t.lastIndexOf(`/`);return n>=0?t.slice(0,n):``}function Qo(e,t,n){return e===t?n:`${n}${e.slice(t.length)}`}function $o(e,t,n){return`${e} ${e===1?t:n}`}function es(){return JSON.stringify({type:`excalidraw`,version:2,source:`collabmd`,elements:[],appState:{viewBackgroundColor:`#ffffff`,gridSize:null},files:{}})}function ts(e,t){return t?{...e,requestId:t}:e}var ns=class{constructor({mobileBreakpointQuery:e=typeof window<`u`&&typeof window.matchMedia==`function`?window.matchMedia(`(max-width: 768px)`):{matches:!1},onFileDelete:t,onFileSelect:n,pendingWorkspaceRequestIds:r=null,state:i,toastController:a,vaultClient:o,view:s,refresh:c}){this.onFileDelete=t,this.onFileSelect=n,this.pendingWorkspaceRequestIds=r,this.state=i,this.toastController=a,this.vaultClient=o,this.view=s,this.refresh=c,this.createButton=document.getElementById(`sidebarCreateBtn`),this.refreshButton=document.getElementById(`refreshFilesBtn`),this.actionDialog=document.getElementById(`fileActionDialog`),this.actionForm=document.getElementById(`fileActionForm`),this.actionTitle=document.getElementById(`fileActionTitle`),this.actionCopy=document.getElementById(`fileActionCopy`),this.actionField=document.getElementById(`fileActionField`),this.actionLabel=document.getElementById(`fileActionLabel`),this.actionInput=document.getElementById(`fileActionInput`),this.actionHint=document.getElementById(`fileActionHint`),this.actionNote=document.getElementById(`fileActionNote`),this.actionCancelButton=document.getElementById(`fileActionCancel`),this.actionSubmitButton=document.getElementById(`fileActionSubmit`),this.createMenu=new Yo({mobileBreakpointQuery:e}),this.pendingAction=null,this.actionBusy=!1}initialize(){this.createButton?.addEventListener(`click`,()=>{this.openRootCreateMenu({anchor:this.createButton})}),this.refreshButton?.addEventListener(`click`,()=>this.refresh()),this.actionCancelButton?.addEventListener(`click`,()=>this.closeActionDialog()),this.actionForm?.addEventListener(`submit`,e=>{e.preventDefault(),this.handleActionSubmit()}),this.actionDialog?.addEventListener(`close`,()=>this.resetActionDialog())}getCreateActions({parentDir:e=``}={}){return[{contextLabel:`New markdown file`,group:`Note`,hint:`Markdown`,icon:this.getCreateActionIcon(`markdown`),id:`markdown`,label:`Markdown note`,meta:`.md`,onSelect:()=>this.handleNewFile({parentDir:e})},{contextLabel:`New base file`,group:`Note`,hint:`Base`,icon:this.getCreateActionIcon(`base`),id:`base`,label:`Base file`,meta:`.base`,onSelect:()=>this.handleNewBase({parentDir:e})},{contextLabel:`New Excalidraw drawing`,group:`Diagram`,hint:`Excalidraw`,icon:this.getCreateActionIcon(`excalidraw`),id:`excalidraw`,label:`Excalidraw drawing`,meta:`.excalidraw`,onSelect:()=>this.handleNewDrawing({parentDir:e})},{contextLabel:`New draw.io diagram`,group:`Diagram`,hint:`draw.io`,icon:this.getCreateActionIcon(`drawio`),id:`drawio`,label:`draw.io diagram`,meta:`.drawio`,onSelect:()=>this.handleNewDrawio({parentDir:e})},{contextLabel:`New Mermaid diagram`,group:`Diagram`,hint:`Mermaid`,icon:this.getCreateActionIcon(`mermaid`),id:`mermaid`,label:`Mermaid diagram`,meta:`.mmd`,onSelect:()=>this.handleNewMermaid({parentDir:e})},{contextLabel:`New PlantUML diagram`,group:`Diagram`,hint:`PlantUML`,icon:this.getCreateActionIcon(`plantuml`),id:`plantuml`,label:`PlantUML diagram`,meta:`.puml`,onSelect:()=>this.handleNewPlantUml({parentDir:e})},{contextLabel:`New folder`,group:`Structure`,hint:`Folder`,icon:this.getCreateActionIcon(`folder`),id:`folder`,label:`Folder`,meta:`folder`,onSelect:()=>this.handleNewFolder({parentDir:e})}]}createContextMenuItems(e=``){return this.getCreateActions({parentDir:e}).map(e=>({label:e.contextLabel,onSelect:e.onSelect}))}getDirectoryContextMenuItems(e){return[...this.createContextMenuItems(e),{label:`Rename / move`,onSelect:()=>this.handleRenameDirectory(e)},{label:`Download`,onSelect:()=>this.handleDownloadDirectory(e)},{label:`Delete`,danger:!0,onSelect:()=>this.handleDeleteDirectory(e)}]}getFileContextMenuItems(e){return[{label:`Rename / move`,onSelect:()=>this.handleRenameFile(e)},{label:`Download`,onSelect:()=>this.handleDownloadFile(e)},{label:`Delete`,danger:!0,onSelect:()=>this.handleDelete(e)}]}showToast(e){e&&this.toastController?.show(String(e))}getCreateActionIcon(e){switch(e){case`base`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 4h7l5 5v11a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"/><path d="M14 4v5h5"/><path d="M8 13h8"/><path d="M8 17h6"/><path d="M8 9h3"/></svg>`;case`drawio`:case`plantuml`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="7" height="6" rx="1"/><rect x="14" y="4" width="7" height="6" rx="1"/><rect x="8.5" y="14" width="7" height="6" rx="1"/><path d="M10 7h4"/><path d="M17.5 10v2.5"/><path d="M6.5 10v2.5"/><path d="M6.5 12.5h11"/></svg>`;case`excalidraw`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19l7-7 3 3-7 7-3-3z"/><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><path d="M2 2l7.586 7.586"/><circle cx="11" cy="11" r="2"/></svg>`;case`folder`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>`;case`mermaid`:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 7.5c0-1.38 1.12-2.5 2.5-2.5 1.04 0 1.93.64 2.3 1.56A2.5 2.5 0 0 1 14 8.5v1"/><path d="M19 16.5c0 1.38-1.12 2.5-2.5 2.5-1.04 0-1.93-.64-2.3-1.56A2.5 2.5 0 0 1 10 15.5v-1"/><path d="M8 10.5h8"/><path d="M8 13.5h8"/><path d="M10 8.5v7"/><path d="M14 8.5v7"/></svg>`;default:return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>`}}showError(e,t){this.showToast(t?.message?`${e}: ${t.message}`:e)}ensureExtension(e,t){return Fe(e,t)}createPendingWorkspaceRequestId(){if(!this.pendingWorkspaceRequestIds)return null;let e=_t();return this.pendingWorkspaceRequestIds.add(e),e}clearPendingWorkspaceRequestId(e){e&&this.pendingWorkspaceRequestIds?.delete(e)}async runWorkspaceMutation(e){let t=this.createPendingWorkspaceRequestId();try{return await e(t)}catch(e){throw this.clearPendingWorkspaceRequestId(t),e}}openActionDialog({title:e,copy:t,label:n=`Path`,hint:r=``,note:i=``,placeholder:a=``,value:o=``,submitLabel:s=`Save`,destructive:c=!1,requiresInput:l=!0,emptyMessage:u=`A value is required`,onSubmit:d}){!this.actionDialog||!this.actionTitle||!this.actionCopy||!this.actionSubmitButton||!this.actionCancelButton||l&&!this.actionInput||(this.actionDialog.open&&(typeof this.actionDialog.close==`function`?this.actionDialog.close():(this.actionDialog.removeAttribute(`open`),this.resetActionDialog())),this.pendingAction={requiresInput:l,emptyMessage:u,onSubmit:d},this.createMenu.close({restoreFocus:!1}),this.view?.removeContextMenu?.(),this.actionTitle.textContent=e,this.actionCopy.textContent=t,this.actionField&&(this.actionField.hidden=!l),this.actionLabel&&(this.actionLabel.textContent=n),this.actionInput&&(this.actionInput.value=o,this.actionInput.placeholder=a,this.actionInput.required=l,this.actionInput.disabled=!1),this.actionHint&&(this.actionHint.textContent=r,this.actionHint.hidden=!l||!r),this.actionNote&&(this.actionNote.textContent=i,this.actionNote.hidden=!i,this.actionNote.classList.toggle(`is-danger`,c)),this.actionSubmitButton.textContent=s,this.actionSubmitButton.disabled=!1,this.actionSubmitButton.classList.toggle(`ui-button--primary`,!c),this.actionSubmitButton.classList.toggle(`ui-button--danger`,c),this.actionCancelButton.disabled=!1,typeof this.actionDialog.showModal==`function`?this.actionDialog.showModal():this.actionDialog.setAttribute(`open`,`true`),requestAnimationFrame(()=>{if(!l||!this.actionInput){this.actionSubmitButton.focus();return}this.actionInput.focus(),o&&this.actionInput.select()}))}resetActionDialog(){this.pendingAction=null,this.actionBusy=!1,this.actionField&&(this.actionField.hidden=!1),this.actionLabel&&(this.actionLabel.textContent=`Path`),this.actionInput&&(this.actionInput.value=``,this.actionInput.placeholder=``,this.actionInput.required=!0,this.actionInput.disabled=!1),this.actionHint&&(this.actionHint.textContent=``,this.actionHint.hidden=!0),this.actionNote&&(this.actionNote.textContent=``,this.actionNote.hidden=!0,this.actionNote.classList.remove(`is-danger`)),this.actionSubmitButton&&(this.actionSubmitButton.textContent=`Save`,this.actionSubmitButton.disabled=!1,this.actionSubmitButton.className=G({variant:`primary`})),this.actionCancelButton&&(this.actionCancelButton.disabled=!1)}closeActionDialog(){if(this.actionDialog){if(this.actionDialog.open&&typeof this.actionDialog.close==`function`){this.actionDialog.close();return}this.actionDialog.removeAttribute(`open`),this.resetActionDialog()}}setActionDialogBusy(e){this.actionBusy=e,this.actionInput&&(this.actionInput.disabled=e||!(this.pendingAction?.requiresInput??!0)),this.actionCancelButton&&(this.actionCancelButton.disabled=e),this.actionSubmitButton&&(this.actionSubmitButton.disabled=e)}async handleActionSubmit(){if(!this.pendingAction?.onSubmit||this.actionBusy)return;let e=this.pendingAction.requiresInput,t=e?this.actionInput?.value.trim()??``:void 0;if(e&&!t){this.showToast(this.pendingAction.emptyMessage),this.actionInput?.focus();return}this.setActionDialogBusy(!0);let n;try{n=await this.pendingAction.onSubmit(t)}catch(e){this.showError(`Failed to complete action`,e)}if(this.setActionDialogBusy(!1),n!==!1){this.closeActionDialog();return}e&&this.actionInput&&(this.actionInput.focus(),this.actionInput.select())}async createVaultFile(e,t,{openAfterCreate:n=!1,errorMessage:r=`Failed to create file`}={}){try{return await this.runWorkspaceMutation(n=>this.vaultClient.createFile(ts({content:t,path:e},n))),this.state.expandDirectoryPath(e,{includeLeaf:!1}),await this.refresh(),n&&this.onFileSelect?.(e),!0}catch(e){return this.showToast(e?.message||r),!1}}async createDirectory(e){let t=F(e);if(!t)return this.showToast(`Folder path is required`),!1;try{return await this.runWorkspaceMutation(e=>this.vaultClient.createDirectory(t,ts({},e))),this.state.expandDirectoryPath(t),await this.refresh(),!0}catch(e){return this.showToast(e?.message||`Failed to create folder`),!1}}async renameVaultFile(e,t,n){let r=F(t);if(!r)return this.showToast(`File path is required`),!1;let i=_(r);if(i&&i.toLowerCase()!==String(n??``).toLowerCase())return this.showToast(`File type changes are not supported during rename. Keep the ${n} extension.`),!1;let a=i?r:`${r}${n}`;if(!Xo(a))return this.showToast(`File path is required`),!1;if(a===e)return!0;try{return await this.runWorkspaceMutation(t=>this.vaultClient.renameFile(ts({newPath:a,oldPath:e},t))),this.state.expandDirectoryPath(a,{includeLeaf:!1}),await this.refresh(),this.state.activeFilePath===e&&(this.state.activeFilePath=a,this.onFileSelect?.(a)),!0}catch(e){return this.showToast(e?.message||`Failed to rename`),!1}}async renameDirectory(e,t){let n=F(t);if(!n)return this.showToast(`Folder path is required`),!1;if(n===e)return!0;try{if(await this.runWorkspaceMutation(t=>this.vaultClient.renameDirectory(ts({newPath:n,oldPath:e},t))),this.state.replaceExpandedDirectoryPrefix(e,n),this.state.expandDirectoryPath(n),await this.refresh(),this.state.activeFilePath&&this.state.activeFilePath.startsWith(`${e}/`)){let t=Qo(this.state.activeFilePath,e,n);this.state.activeFilePath=t,this.onFileSelect?.(t)}return!0}catch(e){return this.showToast(e?.message||`Failed to rename folder`),!1}}async deleteVaultFile(e){try{return await this.runWorkspaceMutation(t=>this.vaultClient.deleteFile(e,ts({},t))),await this.refresh(),this.state.activeFilePath===e&&(this.state.activeFilePath=null,this.onFileDelete?.(e)),!0}catch(e){return this.showToast(e?.message||`Failed to delete`),!1}}async deleteDirectory(e,{recursive:t=!1}={}){try{await this.runWorkspaceMutation(n=>this.vaultClient.deleteDirectory(e,ts({recursive:t},n)));let n=this.state.activeFilePath;return await this.refresh(),this.state.removeExpandedDirectoryPrefix(e),n&&n.startsWith(`${e}/`)&&(this.state.activeFilePath=null,this.onFileDelete?.(n)),!0}catch(e){return this.showToast(e?.message||`Failed to delete folder`),!1}}planMoveEntryByDrop({destinationDirectory:e=``,sourcePath:t=``,sourceType:n=`file`}={}){let r=F(t),i=F(e),a=Zo(r),o=Xo(r);return!r||!o?{ok:!1,reason:`Invalid item to move`}:a===i?{ok:!1,reason:`Item is already in that folder`}:n===`directory`?i===r?{ok:!1,reason:`A folder cannot be moved into itself`}:i.startsWith(`${r}/`)?{ok:!1,reason:`A folder cannot be moved into one of its descendants`}:{nextPath:I(i,o),ok:!0}:{extension:_(r)||`.md`,nextPath:I(i,o),ok:!0}}canMoveEntryByDrop(e={}){return this.planMoveEntryByDrop(e).ok}async moveEntryByDrop(e={}){let t=this.planMoveEntryByDrop(e);return t.ok?e.sourceType===`directory`?this.renameDirectory(e.sourcePath,t.nextPath):this.renameVaultFile(e.sourcePath,t.nextPath,t.extension):(this.showToast(t.reason),!1)}async downloadFileEntry(e){try{return await this.vaultClient.downloadFile(e),!0}catch(e){return this.showToast(e?.message||`Failed to download file`),!1}}async downloadDirectoryEntry(e){try{return await this.vaultClient.downloadDirectory(e),!0}catch(e){return this.showToast(e?.message||`Failed to download folder`),!1}}getCreateContext(e=``){let t=F(e);return{hintPrefix:t?`Use "/" to create nested items under this folder.`:`Use "/" to place it inside a folder.`,inputLabelSuffix:t?`name or path`:`path`,note:t?`Parent folder: ${t}`:``,normalizedParentDir:t}}openRootCreateMenu({anchor:e=this.createButton}={}){this.openCreateMenu({anchor:e,parentDir:``})}openCreateMenu({anchor:e=this.createButton,parentDir:t=``}={}){this.view?.removeContextMenu?.(),this.createMenu.toggle({anchor:e,items:this.getCreateActions({parentDir:t}),title:`Create`})}handleNewFile({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create markdown file`,copy:t.normalizedParentDir?`Add a new note inside the selected folder. It opens immediately after creation.`:`Add a new note to the vault. It opens immediately after creation.`,label:`File ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".md" is added automatically.`,note:t.note,placeholder:t.normalizedParentDir?`my-note`:`notes/my-note`,submitLabel:`Create file`,emptyMessage:`File path is required`,onSubmit:e=>{let n=F(e);if(!n)return this.showToast(`File path is required`),!1;let r=this.ensureExtension(I(t.normalizedParentDir,n),`.md`);return this.createVaultFile(r,Ie(r),{errorMessage:`Failed to create file`,openAfterCreate:!0})}})}handleNewBase({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create base file`,copy:t.normalizedParentDir?"Add a new `.base` file inside the selected folder. It opens immediately after creation.":"Add a new `.base` file to the vault. It opens immediately after creation.",label:`Base ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".base" is added automatically.`,note:t.note,placeholder:t.normalizedParentDir?`table-view`:`views/table-view`,submitLabel:`Create base`,emptyMessage:`Base path is required`,onSubmit:e=>{let n=F(e);if(!n)return this.showToast(`Base path is required`),!1;let r=Le(I(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create base file`,openAfterCreate:!0})}})}handleNewFolder({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create folder`,copy:t.normalizedParentDir?`Add a new folder inside the selected folder.`:`Add a new folder to organize notes and diagrams.`,label:`Folder ${t.inputLabelSuffix}`,hint:t.hintPrefix,note:t.note,placeholder:t.normalizedParentDir?`archive`:`notes/archive`,submitLabel:`Create folder`,emptyMessage:`Folder path is required`,onSubmit:e=>this.createDirectory(I(t.normalizedParentDir,e))})}handleNewDrawing({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create Excalidraw drawing`,copy:t.normalizedParentDir?`Start a new drawing inside the selected folder.`:`Start a new drawing file in the vault.`,label:`Drawing ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".excalidraw" is added automatically.`,note:t.note,placeholder:t.normalizedParentDir?`architecture`:`diagrams/architecture`,submitLabel:`Create drawing`,emptyMessage:`Drawing path is required`,onSubmit:e=>{let n=F(e);if(!n)return this.showToast(`Drawing path is required`),!1;let r=this.ensureExtension(I(t.normalizedParentDir,n),`.excalidraw`);return this.createVaultFile(r,es(),{errorMessage:`Failed to create drawing`,openAfterCreate:!0})}})}handleNewMermaid({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create Mermaid diagram`,copy:t.normalizedParentDir?"Create a new `.mmd` or `.mermaid` file inside the selected folder.":"Create a new `.mmd` or `.mermaid` file with starter diagram content.",label:`Diagram ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".mmd" is added automatically unless you enter ".mermaid".`,note:t.note,placeholder:t.normalizedParentDir?`flow`:`diagrams/flow`,submitLabel:`Create diagram`,emptyMessage:`Diagram path is required`,onSubmit:e=>{let n=F(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=Re(I(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create Mermaid diagram`,openAfterCreate:!0})}})}handleNewDrawio({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create draw.io diagram`,copy:t.normalizedParentDir?"Create a new `.drawio` diagram inside the selected folder.":"Create a new `.drawio` diagram with a native starter document.",label:`Diagram ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".drawio" is added automatically.`,note:t.note,placeholder:t.normalizedParentDir?`architecture`:`diagrams/architecture`,submitLabel:`Create diagram`,emptyMessage:`Diagram path is required`,onSubmit:e=>{let n=F(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=ze(I(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create draw.io diagram`,openAfterCreate:!0})}})}handleNewPlantUml({parentDir:e=``}={}){let t=this.getCreateContext(e);this.openActionDialog({title:`Create PlantUML diagram`,copy:t.normalizedParentDir?"Create a new `.puml` or `.plantuml` file inside the selected folder.":"Create a new `.puml` or `.plantuml` file with starter diagram content.",label:`Diagram ${t.inputLabelSuffix}`,hint:`${t.hintPrefix} ".puml" is added automatically unless you enter ".plantuml".`,note:t.note,placeholder:t.normalizedParentDir?`sequence-flow`:`diagrams/sequence-flow`,submitLabel:`Create diagram`,emptyMessage:`Diagram path is required`,onSubmit:e=>{let n=F(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=Be(I(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create PlantUML diagram`,openAfterCreate:!0})}})}handleRenameFile(e){let t=_(e)||`.md`;this.openActionDialog({title:`Rename or move file`,copy:`Update the relative path without changing the file type.`,label:`Path`,hint:`Use "/" to move the file into another folder. ${t} is kept automatically.`,value:e,submitLabel:`Save file path`,emptyMessage:`File path is required`,onSubmit:n=>this.renameVaultFile(e,n,t)})}handleRenameDirectory(e){this.openActionDialog({title:`Rename or move folder`,copy:`Update the relative path for this folder and everything inside it.`,label:`Path`,hint:`Use "/" to move the folder into another location in the vault.`,value:e,submitLabel:`Save folder path`,emptyMessage:`Folder path is required`,onSubmit:t=>this.renameDirectory(e,t)})}handleDelete(e){this.openActionDialog({title:`Delete file`,copy:`This permanently removes the file from the vault.`,note:e,submitLabel:`Delete file`,destructive:!0,requiresInput:!1,onSubmit:()=>this.deleteVaultFile(e)})}handleDeleteDirectory(e){let{directoryCount:t,fileCount:n}=this.state.getDirectoryDescendantSummary(e),r=t>0||n>0,i=r?`This will permanently remove ${$o(n,`file`,`files`)} and ${$o(t,`nested folder`,`nested folders`)} inside this folder.`:`This permanently removes the empty folder from the vault.`;this.openActionDialog({title:r?`Delete folder and contents`:`Delete folder`,copy:i,note:e,submitLabel:r?`Delete folder and contents`:`Delete folder`,destructive:!0,requiresInput:!1,onSubmit:()=>this.deleteDirectory(e,{recursive:r})})}handleDownloadFile(e){this.downloadFileEntry(e)}handleDownloadDirectory(e){this.downloadDirectoryEntry(e)}};function rs(e,t=[],n=[]){for(let r of e)if(!(!r?.path||!r?.type)){if(n.push({lowerPath:String(r.path).toLowerCase(),name:r.name,path:r.path,type:r.type}),r.type===`file`||r.type===`base`||r.type===`excalidraw`||r.type===`drawio`||r.type===`mermaid`||r.type===`plantuml`||r.type===`image`){t.push(r.path);continue}r.type===`directory`&&Array.isArray(r.children)&&rs(r.children,t,n)}return{files:t,searchEntries:n}}function is(e,t){for(let n of e??[]){if(n?.path===t)return n;if(n?.type===`directory`&&Array.isArray(n.children)){let e=is(n.children,t);if(e)return e}}return null}function as(e){let t=0,n=0;for(let r of e?.children??[]){if(r?.type===`directory`){t+=1;let e=as(r);t+=e.directoryCount,n+=e.fileCount;continue}n+=1}return{directoryCount:t,fileCount:n}}function os(e,t,n){return e===t?n:`${n}${e.slice(t.length)}`}var ss=class{constructor(){this.tree=[],this.flatFiles=[],this.flatSearchEntries=[],this.activeFilePath=null,this.expandedDirs=new Set,this.searchQuery=``}setTree(e){this.tree=Array.isArray(e)?e:[];let t=rs(this.tree,[],[]);this.flatFiles=t.files,this.flatSearchEntries=t.searchEntries}setSearchQuery(e){this.searchQuery=String(e??``).trim().toLowerCase()}getSearchMatches(){return this.searchQuery?this.flatSearchEntries.filter(e=>e.lowerPath.includes(this.searchQuery)).map(e=>({name:e.name,path:e.path,type:e.type})):[]}getNode(e){return is(this.tree,e)}getDirectoryDescendantSummary(e){let t=this.getNode(e);return!t||t.type!==`directory`?{directoryCount:0,fileCount:0}:as(t)}setActiveFile(e){this.activeFilePath=e||null,e&&this.expandDirectoryPath(e,{includeLeaf:!1})}toggleDirectory(e){return this.expandedDirs.has(e)?(this.expandedDirs.delete(e),!1):(this.expandedDirs.add(e),!0)}expandDirectoryPath(e,{includeLeaf:t=!0}={}){let n=F(e);if(!n)return;let r=n.split(`/`),i=t?r.length:Math.max(r.length-1,0),a=``;for(let e=0;e<i;e+=1)a=a?`${a}/${r[e]}`:r[e],this.expandedDirs.add(a)}replaceExpandedDirectoryPrefix(e,t){let n=new Set;this.expandedDirs.forEach(r=>{if(r===e||r.startsWith(`${e}/`)){n.add(os(r,e,t));return}n.add(r)}),this.expandedDirs=n}removeExpandedDirectoryPrefix(e){let t=new Set;this.expandedDirs.forEach(n=>{n===e||n.startsWith(`${e}/`)||t.add(n)}),this.expandedDirs=t}};function cs(e){return String(e??``).replace(/\/+$/u,``).split(`/`).filter(Boolean).pop()||``}function ls(e){let t=String(e??``).replace(/\/+$/u,``),n=t.lastIndexOf(`/`);return n>=0?t.slice(0,n):``}function us(e=[],t=``){for(let n of e){if(n.path===t)return n;if(n.type===`directory`&&Array.isArray(n.children)){let e=us(n.children,t);if(e)return e}}return null}var ds=420,fs=10,ps=700,ms=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onEntryDrop:t,onDirectorySelect:n,onDirectoryToggle:r,onFileContextMenu:i,onFileSelect:a,onSearchChange:o,onTreeContextMenu:s,onValidateDrop:c}){this.onEntryDrop=t,this.onDirectorySelect=n,this.onDirectoryToggle=r,this.onFileContextMenu=i,this.onFileSelect=a,this.onSearchChange=o,this.onTreeContextMenu=s,this.onValidateDrop=c,this.mobileBreakpointQuery=e,this.treeContainer=document.getElementById(`fileTree`),this.searchInput=document.getElementById(`fileSearchInput`),this.renderedDirectoryWrappers=new Map,this.renderedChildContainers=new Map,this.lastRenderMode=`tree`,this.longPressTimer=0,this.longPressContext=null,this.suppressedActivationTarget=null,this.contextMenuCloseHandler=null,this.actionSheetCloseHandler=null,this.dragSource=null,this.currentSearchQuery=``,this.activeDropTarget=null,this.invalidDropAttempt=null,this.autoExpandTimer=0,this.autoExpandTargetPath=``,this.rootDropZone=null}initialize(){this.searchInput?.addEventListener(`input`,e=>{this.onSearchChange?.(e.target.value)}),this.treeContainer?.addEventListener(`contextmenu`,e=>{e.target.closest(`.file-tree-item`)||(e.preventDefault(),this.onTreeContextMenu?.(e))}),this.treeContainer?.addEventListener(`pointerdown`,e=>{e.target.closest(`.file-tree-item`)||this.startLongPress(e,()=>{this.onTreeContextMenu?.({clientX:Number(e.clientX||0),clientY:Number(e.clientY||0),preventDefault(){},target:this.treeContainer})},this.treeContainer)}),this.treeContainer?.addEventListener(`pointermove`,e=>{this.handleLongPressPointerMove(e)},{passive:!0}),this.treeContainer?.addEventListener(`pointerup`,()=>{this.cancelLongPress()}),this.treeContainer?.addEventListener(`pointercancel`,()=>{this.cancelLongPress()}),this.treeContainer?.addEventListener(`scroll`,()=>{this.cancelLongPress()},{passive:!0}),this.treeContainer?.addEventListener(`dragover`,e=>{this.handleTreeDragOver(e)}),this.treeContainer?.addEventListener(`drop`,e=>{this.handleTreeDrop(e)}),this.treeContainer?.addEventListener(`dragleave`,e=>{this.handleTreeDragLeave(e)})}render({activeFilePath:e,changedPaths:t=null,expandedDirs:n,reset:r=!1,searchMatches:i,searchQuery:a,tree:o}){if(!this.treeContainer)return;if(this.currentSearchQuery=String(a??``),this.currentSearchQuery&&this.clearDragFeedback(),this.searchInput&&this.searchInput.value!==a&&(this.searchInput.value=a),a){this.lastRenderMode=`search`,this.renderSearchResults(i,e);return}if(r||this.lastRenderMode!==`tree`||!Array.isArray(t)||t.length===0){this.renderFullTree(o,{activeFilePath:e,expandedDirs:n}),this.lastRenderMode=`tree`;return}let s=Array.from(new Set(t.map(e=>ls(e)))).sort((e,t)=>e.split(`/`).length-t.split(`/`).length).filter((e,t,n)=>!n.slice(0,t).some(t=>t&&e.startsWith(`${t}/`)));if(s.includes(``)){this.renderFullTree(o,{activeFilePath:e,expandedDirs:n}),this.lastRenderMode=`tree`;return}for(let t of s)if(!this.rerenderDirectoryBranch(t,o,{activeFilePath:e,expandedDirs:n})){this.renderFullTree(o,{activeFilePath:e,expandedDirs:n}),this.lastRenderMode=`tree`;return}this.lastRenderMode=`tree`}renderSearchResults(e,t){if(!this.treeContainer)return;if(this.resetTreeIndexes(),this.treeContainer.innerHTML=``,this.rootDropZone=null,e.length===0){this.treeContainer.innerHTML=`<div class="file-tree-empty">No matches</div>`;return}let n=document.createDocumentFragment();for(let r of e){if(r.type===`directory`){n.appendChild(this.createSearchDirectoryItem(r));continue}n.appendChild(this.createFileItem({activeFilePath:t,depth:0,filePath:r.path,fileType:r.type||(h(r.path)??`file`),name:r.name||cs(r.path)}))}this.treeContainer.appendChild(n)}renderFullTree(e,{activeFilePath:t,expandedDirs:n}){if(this.resetTreeIndexes(),this.treeContainer.innerHTML=``,this.rootDropZone=null,e.length===0){this.treeContainer.innerHTML=`<div class="file-tree-empty">No vault files found</div>`;return}let r=document.createDocumentFragment();r.appendChild(this.createRootDropZone()),this.renderNodes(e,r,{activeFilePath:t,depth:0,expandedDirs:n}),this.treeContainer.appendChild(r)}resetTreeIndexes(){this.renderedDirectoryWrappers.clear(),this.renderedChildContainers.clear()}renderNodes(e,t,{activeFilePath:n,depth:r,expandedDirs:i}){for(let a of e){if(a.type===`directory`){t.appendChild(this.createDirectoryItem(a,{activeFilePath:n,depth:r,expandedDirs:i}));continue}t.appendChild(this.createFileItem({activeFilePath:n,depth:r,filePath:a.path,fileType:a.type,name:a.name}))}}createDirectoryItem(e,{activeFilePath:t,depth:n,expandedDirs:r}){let i=document.createElement(`div`);i.className=`file-tree-group`;let a=document.createElement(`button`);a.className=`file-tree-item file-tree-dir`,a.style.setProperty(`--depth`,n),a.dataset.depth=n;let o=r.has(e.path);if(a.setAttribute(`aria-expanded`,String(o)),a.dataset.path=e.path,a.dataset.entryType=`directory`,a.innerHTML=`
|
|
297
297
|
<svg class="file-tree-chevron${o?` expanded`:``}" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 18 15 12 9 6"/></svg>
|
|
298
298
|
<svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>
|
|
299
299
|
<span class="file-tree-name">${b(e.name)}</span>
|
|
300
300
|
`,this.configureDragSource(a,{path:e.path,type:`directory`}),this.bindDirectoryDropTarget(a,e.path),a.addEventListener(`click`,t=>{this.consumeSuppressedActivation(a,t)||this.onDirectoryToggle?.(e.path)}),a.addEventListener(`contextmenu`,t=>{t.preventDefault(),this.onFileContextMenu?.(t,{directoryPath:e.path,type:`directory`})}),this.bindLongPress(a,()=>{this.onFileContextMenu?.(this.createLongPressEvent(a),{directoryPath:e.path,type:`directory`})}),i.appendChild(a),this.renderedDirectoryWrappers.set(e.path,i),o&&Array.isArray(e.children)){let a=document.createElement(`div`);a.className=`file-tree-children`,this.renderedChildContainers.set(e.path,a),this.renderNodes(e.children,a,{activeFilePath:t,depth:n+1,expandedDirs:r}),i.appendChild(a)}else this.renderedChildContainers.delete(e.path);return i}createSearchDirectoryItem(e){let t=document.createElement(`button`);return t.className=`file-tree-item file-tree-dir`,t.style.setProperty(`--depth`,0),t.dataset.depth=0,t.dataset.path=e.path,t.dataset.entryType=`directory`,t.innerHTML=`
|
|
301
301
|
<svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>
|
|
302
|
-
<span class="file-tree-name">${b(e.name||
|
|
303
|
-
`,t.addEventListener(`click`,n=>{this.consumeSuppressedActivation(t,n)||this.onDirectorySelect?.(e.path)}),t.addEventListener(`contextmenu`,t=>{t.preventDefault(),this.onFileContextMenu?.(t,{directoryPath:e.path,type:`directory`})}),this.bindLongPress(t,()=>{this.onFileContextMenu?.(this.createLongPressEvent(t),{directoryPath:e.path,type:`directory`})}),t}rerenderDirectoryBranch(e,t,{activeFilePath:n,expandedDirs:r}){let i=this.renderedDirectoryWrappers.get(e),a=
|
|
302
|
+
<span class="file-tree-name">${b(e.name||cs(e.path))}</span>
|
|
303
|
+
`,t.addEventListener(`click`,n=>{this.consumeSuppressedActivation(t,n)||this.onDirectorySelect?.(e.path)}),t.addEventListener(`contextmenu`,t=>{t.preventDefault(),this.onFileContextMenu?.(t,{directoryPath:e.path,type:`directory`})}),this.bindLongPress(t,()=>{this.onFileContextMenu?.(this.createLongPressEvent(t),{directoryPath:e.path,type:`directory`})}),t}rerenderDirectoryBranch(e,t,{activeFilePath:n,expandedDirs:r}){let i=this.renderedDirectoryWrappers.get(e),a=us(t,e);if(!i||a?.type!==`directory`)return!1;let o=i.querySelector(`.file-tree-dir`),s=r.has(e);o?.setAttribute(`aria-expanded`,String(s)),o?.querySelector(`.file-tree-chevron`)?.classList.toggle(`expanded`,s);let c=Number(o?.dataset.depth??0),l=this.renderedChildContainers.get(e)??i.querySelector(`.file-tree-children`);return this.clearRenderedDescendants(e),s?(l?l.innerHTML=``:(l=document.createElement(`div`),l.className=`file-tree-children`,i.appendChild(l)),this.renderedChildContainers.set(e,l),this.renderNodes(a.children??[],l,{activeFilePath:n,depth:c+1,expandedDirs:r}),!0):(l?.remove(),this.renderedChildContainers.delete(e),!0)}clearRenderedDescendants(e){let t=`${e}/`;Array.from(this.renderedDirectoryWrappers.keys()).forEach(e=>{e.startsWith(t)&&this.renderedDirectoryWrappers.delete(e)}),Array.from(this.renderedChildContainers.keys()).forEach(e=>{e.startsWith(t)&&this.renderedChildContainers.delete(e)})}createFileItem({activeFilePath:e,depth:t,filePath:n,fileType:r=`file`,name:i}){let a=document.createElement(`button`);a.className=`file-tree-item file-tree-file`;let o=r===`drawio`,s=r===`excalidraw`,l=r===`base`,u=r===`image`,d=r===`mermaid`,f=r===`plantuml`;return l&&a.classList.add(`is-base`),o&&a.classList.add(`is-drawio`),s&&a.classList.add(`is-excalidraw`),u&&a.classList.add(`is-image`),d&&a.classList.add(`is-mermaid`),f&&a.classList.add(`is-plantuml`),n===e&&a.classList.add(`active`),a.style.setProperty(`--depth`,t),a.dataset.depth=t,a.dataset.path=n,a.dataset.entryType=`file`,a.innerHTML=`
|
|
304
304
|
${this.getFileIconSvg({isBase:l,isDrawio:o,isExcalidraw:s,isImage:u,isMermaid:d,isPlantUml:f})}
|
|
305
305
|
<span class="file-tree-name">${b(c(i))}</span>
|
|
306
|
-
`,this.configureDragSource(a,{path:n,type:`file`}),a.addEventListener(`click`,e=>{this.consumeSuppressedActivation(a,e)||this.onFileSelect?.(n)}),a.addEventListener(`contextmenu`,e=>{e.preventDefault(),this.onFileContextMenu?.(e,{filePath:n,type:`file`})}),this.bindLongPress(a,()=>{this.onFileContextMenu?.(this.createLongPressEvent(a),{filePath:n,type:`file`})}),a}isMobileViewport(){return!!this.mobileBreakpointQuery?.matches}isDragAndDropEnabled(){return!this.isMobileViewport()&&!this.currentSearchQuery}configureDragSource(e,t){if(!(e instanceof HTMLElement))return;let n=this.isDragAndDropEnabled();e.draggable=n,n&&(e.addEventListener(`dragstart`,n=>{this.dragSource={path:t.path,type:t.type},document.body?.classList.add(`is-file-tree-dragging`),this.treeContainer&&(this.treeContainer.dataset.dragActive=`true`),e.classList.add(`is-dragging`),n.dataTransfer&&(n.dataTransfer.effectAllowed=`move`,n.dataTransfer.setData(`text/plain`,t.path))}),e.addEventListener(`dragend`,()=>{e.classList.remove(`is-dragging`);let t=this.dragSource;this.invalidDropAttempt&&t&&this.onEntryDrop?.(this.invalidDropAttempt),this.dragSource=null,this.invalidDropAttempt=null,this.clearDragFeedback()}),t.type===`file`&&(e.addEventListener(`dragenter`,e=>{this.handleNonDropTargetDragOver(e)}),e.addEventListener(`dragover`,e=>{this.handleNonDropTargetDragOver(e)})))}bindDirectoryDropTarget(e,t){!(e instanceof HTMLElement)||this.isMobileViewport()||(e.addEventListener(`dragenter`,n=>{this.handleDirectoryDragEnter(n,e,t)}),e.addEventListener(`dragover`,n=>{this.handleDirectoryDragOver(n,e,t)}),e.addEventListener(`drop`,e=>{this.handleDirectoryDrop(e,t)}))}createRootDropZone(){let e=document.createElement(`div`);return e.className=`file-tree-root-drop-zone`,e.textContent=`Drop here to move to vault root`,e.addEventListener(`dragenter`,e=>{this.handleRootZoneDragEnter(e)}),e.addEventListener(`dragover`,e=>{this.handleRootZoneDragOver(e)}),e.addEventListener(`drop`,e=>{this.handleRootZoneDrop(e)}),this.rootDropZone=e,e}validateDrop(e){return!this.dragSource||this.currentSearchQuery?!1:this.onValidateDrop?.({destinationDirectory:e,sourcePath:this.dragSource.path,sourceType:this.dragSource.type})===!0}setDropTarget(e){if(this.activeDropTarget?.element&&this.activeDropTarget.element!==e?.element&&this.activeDropTarget.element.classList.remove(`is-drop-target`,`is-drop-invalid`),this.activeDropTarget?.root&&!e?.root&&this.treeContainer?.classList.remove(`is-drop-target-root`,`is-drop-invalid`),this.activeDropTarget?.rootZone&&!e?.rootZone&&this.rootDropZone?.classList.remove(`is-drop-target`,`is-drop-invalid`),this.activeDropTarget=e,!e||e.isValid?this.invalidDropAttempt=null:this.dragSource&&(this.invalidDropAttempt={destinationDirectory:e.destinationDirectory||``,sourcePath:this.dragSource.path,sourceType:this.dragSource.type}),e){if(e.root){this.treeContainer?.classList.toggle(`is-drop-target-root`,e.isValid),this.treeContainer?.classList.toggle(`is-drop-invalid`,!e.isValid);return}if(e.rootZone){this.rootDropZone?.classList.toggle(`is-drop-target`,e.isValid),this.rootDropZone?.classList.toggle(`is-drop-invalid`,!e.isValid);return}e.element.classList.toggle(`is-drop-target`,e.isValid),e.element.classList.toggle(`is-drop-invalid`,!e.isValid)}}scheduleAutoExpand(e,t){e.getAttribute(`aria-expanded`)===`true`||this.autoExpandTargetPath===t||(this.cancelAutoExpand(),this.autoExpandTargetPath=t,this.autoExpandTimer=window.setTimeout(()=>{this.autoExpandTimer=0,this.autoExpandTargetPath=``,e.isConnected&&e.getAttribute(`aria-expanded`)!==`true`&&this.onDirectoryToggle?.(t)},ls))}cancelAutoExpand(){this.autoExpandTimer&&=(window.clearTimeout(this.autoExpandTimer),0),this.autoExpandTargetPath=``}clearDragFeedback(){this.cancelAutoExpand(),this.setDropTarget(null),document.body?.classList.remove(`is-file-tree-dragging`),this.treeContainer&&delete this.treeContainer.dataset.dragActive}handleDirectoryDragEnter(e,t,n){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let r=this.validateDrop(n);this.setDropTarget({destinationDirectory:n,element:t,isValid:r,root:!1}),r?this.scheduleAutoExpand(t,n):this.cancelAutoExpand()}handleDirectoryDragOver(e,t,n){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let r=this.validateDrop(n);e.dataTransfer&&(e.dataTransfer.dropEffect=r?`move`:`none`),this.setDropTarget({destinationDirectory:n,element:t,isValid:r,root:!1}),r?this.scheduleAutoExpand(t,n):this.cancelAutoExpand()}handleDirectoryDrop(e,t){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let n={destinationDirectory:t,sourcePath:this.dragSource.path,sourceType:this.dragSource.type};this.clearDragFeedback(),this.onEntryDrop?.(n)}handleTreeDragOver(e){if(!this.dragSource||!this.treeContainer||e.target.closest(`.file-tree-dir`)||e.target.closest(`.file-tree-item`))return;e.preventDefault(),this.cancelAutoExpand();let t=this.validateDrop(``);e.dataTransfer&&(e.dataTransfer.dropEffect=t?`move`:`none`),this.setDropTarget({destinationDirectory:``,element:this.treeContainer,isValid:t,root:!0})}handleTreeDrop(e){if(!this.dragSource||!this.treeContainer||e.target.closest(`.file-tree-dir`)||e.target.closest(`.file-tree-item`))return;e.preventDefault();let t={destinationDirectory:``,sourcePath:this.dragSource.path,sourceType:this.dragSource.type};this.clearDragFeedback(),this.onEntryDrop?.(t)}handleTreeDragLeave(e){if(!this.dragSource||!this.treeContainer)return;let t=e.relatedTarget;t&&this.treeContainer.contains(t)||this.clearDragFeedback()}handleRootZoneDragEnter(e){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let t=this.validateDrop(``);this.cancelAutoExpand(),this.setDropTarget({destinationDirectory:``,element:this.rootDropZone,isValid:t,rootZone:!0})}handleRootZoneDragOver(e){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let t=this.validateDrop(``);e.dataTransfer&&(e.dataTransfer.dropEffect=t?`move`:`none`),this.cancelAutoExpand(),this.setDropTarget({destinationDirectory:``,element:this.rootDropZone,isValid:t,rootZone:!0})}handleRootZoneDrop(e){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let t={destinationDirectory:``,sourcePath:this.dragSource.path,sourceType:this.dragSource.type};this.clearDragFeedback(),this.onEntryDrop?.(t)}handleNonDropTargetDragOver(e){this.dragSource&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect=`none`),this.clearDragFeedback())}bindLongPress(e,t){!(e instanceof HTMLElement)||typeof t!=`function`||(e.addEventListener(`pointerdown`,n=>{this.startLongPress(n,t,e)}),e.addEventListener(`pointermove`,e=>{this.handleLongPressPointerMove(e)},{passive:!0}),e.addEventListener(`pointerup`,()=>{this.cancelLongPress()}),e.addEventListener(`pointercancel`,()=>{this.cancelLongPress()}),e.addEventListener(`pointerleave`,()=>{this.cancelLongPress()}))}startLongPress(e,t,n=null){this.isMobileViewport()&&[`touch`,`pen`].includes(String(e.pointerType||``))&&Number(e.button??0)===0&&(this.cancelLongPress(),this.longPressContext={callback:t,pointerId:e.pointerId,startX:Number(e.clientX||0),startY:Number(e.clientY||0),target:n??e.currentTarget??e.target??null},this.longPressTimer=window.setTimeout(()=>{let e=this.longPressContext;this.longPressTimer=0,e&&(this.suppressedActivationTarget=e.target,e.callback(),this.longPressContext=null)},ss))}handleLongPressPointerMove(e){if(!this.longPressContext||e.pointerId!==this.longPressContext.pointerId)return;let t=Math.abs(Number(e.clientX||0)-this.longPressContext.startX),n=Math.abs(Number(e.clientY||0)-this.longPressContext.startY);(t>cs||n>cs)&&this.cancelLongPress()}cancelLongPress(){this.longPressTimer&&=(window.clearTimeout(this.longPressTimer),0),this.longPressContext=null}createLongPressEvent(e){return{clientX:this.longPressContext?.startX??0,clientY:this.longPressContext?.startY??0,preventDefault(){},stopPropagation(){},target:e}}consumeSuppressedActivation(e,t){return this.suppressedActivationTarget===e?(this.suppressedActivationTarget=null,t?.preventDefault?.(),t?.stopPropagation?.(),!0):!1}getFileIconSvg({isBase:e,isDrawio:t,isExcalidraw:n,isImage:r,isMermaid:i,isPlantUml:a}){return e?`<svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 4h7l5 5v11a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"/><path d="M14 4v5h5"/><path d="M8 13h8"/><path d="M8 17h6"/><path d="M8 9h3"/></svg>`:t?`<svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="7" height="6" rx="1"/><rect x="14" y="4" width="7" height="6" rx="1"/><rect x="8.5" y="14" width="7" height="6" rx="1"/><path d="M10 7h4"/><path d="M17.5 10v2.5"/><path d="M6.5 10v2.5"/><path d="M6.5 12.5h11"/></svg>`:n?`<svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19l7-7 3 3-7 7-3-3z"/><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><path d="M2 2l7.586 7.586"/><circle cx="11" cy="11" r="2"/></svg>`:r?`<svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="9" cy="10" r="1.5"/><path d="m21 16-5-5L7 20"/><path d="m14 14 2 2"/></svg>`:i?`<svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 7.5c0-1.38 1.12-2.5 2.5-2.5 1.04 0 1.93.64 2.3 1.56A2.5 2.5 0 0 1 14 8.5v1"/><path d="M19 16.5c0 1.38-1.12 2.5-2.5 2.5-1.04 0-1.93-.64-2.3-1.56A2.5 2.5 0 0 1 10 15.5v-1"/><path d="M8 10.5h8"/><path d="M8 13.5h8"/><path d="M10 8.5v7"/><path d="M14 8.5v7"/></svg>`:a?`<svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="7" height="6" rx="1"/><rect x="14" y="4" width="7" height="6" rx="1"/><rect x="8.5" y="14" width="7" height="6" rx="1"/><path d="M10 7h4"/><path d="M17.5 10v2.5"/><path d="M6.5 10v2.5"/><path d="M6.5 12.5h11"/></svg>`:`<svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>`}showContextMenu(e,t){if(this.removeContextMenu(),!Array.isArray(t)||t.length===0)return;if(this.isMobileViewport()){this.showActionSheet(t);return}let n=document.createElement(`div`);n.className=`file-context-menu`;for(let e of t){let t=document.createElement(`button`);t.className=`file-context-item${e.danger?` file-context-danger`:``}`,t.textContent=e.label,t.addEventListener(`click`,()=>{this.removeContextMenu(),e.onSelect?.()}),n.appendChild(t)}document.body.appendChild(n);let r=n.getBoundingClientRect(),i=Math.max(8,window.innerWidth-r.width-8),a=Math.max(8,window.innerHeight-r.height-8);n.style.left=`${Math.max(8,Math.min(e.clientX,i))}px`,n.style.top=`${Math.max(8,Math.min(e.clientY,a))}px`;let o=e=>{n.contains(e.target)||this.removeContextMenu()};this.contextMenuCloseHandler=o,setTimeout(()=>document.addEventListener(`click`,o),0)}showActionSheet(e){let t=document.createElement(`button`);t.type=`button`,t.className=`file-action-sheet-backdrop`,t.setAttribute(`aria-label`,`Close file actions`);let n=document.createElement(`div`);n.className=`file-action-sheet`,e.forEach(e=>{let t=document.createElement(`button`);t.type=`button`,t.className=G({variant:`secondary`,extra:[`file-action-sheet-item`,e.danger?`file-context-danger`:``]}),t.textContent=e.label,t.addEventListener(`click`,()=>{this.removeContextMenu(),e.onSelect?.()}),n.appendChild(t)});let r=document.createElement(`button`);r.type=`button`,r.className=G({variant:`ghost`,extra:`file-action-sheet-item`}),r.textContent=`Cancel`,r.addEventListener(`click`,()=>{this.removeContextMenu()}),n.appendChild(r),t.addEventListener(`click`,()=>{this.removeContextMenu()}),document.body.append(t,n),this.actionSheetCloseHandler=()=>{t.remove(),n.remove(),this.actionSheetCloseHandler=null}}removeContextMenu(){this.cancelLongPress(),this.clearDragFeedback(),document.querySelectorAll(`.file-context-menu`).forEach(e=>e.remove()),this.contextMenuCloseHandler&&=(document.removeEventListener(`click`,this.contextMenuCloseHandler),null),this.actionSheetCloseHandler?.()}},ds=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onFileSelect:t,onFileDelete:n,pendingWorkspaceRequestIds:r=null,toastController:i,vaultClient:a=S}){this.onFileSelect=t,this.onFileDelete=n,this.toastController=i,this.vaultClient=a,this.state=new rs,this.view=new us({mobileBreakpointQuery:e,onDirectorySelect:e=>{this.state.expandDirectoryPath(e),this.state.setSearchQuery(``),this.renderTree({reset:!0})},onDirectoryToggle:e=>{this.state.toggleDirectory(e),this.renderTree()},onEntryDrop:e=>this.actionController.moveEntryByDrop(e),onFileContextMenu:(e,t)=>{if(t.type===`directory`){this.view.showContextMenu(e,this.actionController.getDirectoryContextMenuItems(t.directoryPath));return}this.view.showContextMenu(e,this.actionController.getFileContextMenuItems(t.filePath))},onFileSelect:e=>{this.onFileSelect?.(e)},onValidateDrop:e=>this.actionController.canMoveEntryByDrop(e),onSearchChange:e=>{this.state.setSearchQuery(e),this.renderTree()},onTreeContextMenu:e=>{this.view.showContextMenu(e,this.actionController.createContextMenuItems())}}),this.actionController=new Qo({mobileBreakpointQuery:e,onFileDelete:this.onFileDelete,onFileSelect:this.onFileSelect,pendingWorkspaceRequestIds:r,refresh:()=>this.refresh(),state:this.state,toastController:this.toastController,vaultClient:this.vaultClient,view:this.view})}initialize(){this.view.initialize(),this.actionController.initialize()}async refresh(){try{let e=await this.vaultClient.readTree();this.setTree(e.tree||[])}catch(e){console.error(`[explorer] Failed to load file tree:`,e.message)}}setTree(e,{changedPaths:t=null,reset:n=!1}={}){this.state.setTree(e),this.renderTree({changedPaths:t,reset:n})}setActiveFile(e){this.state.setActiveFile(e),this.renderTree()}get flatFiles(){return this.state.flatFiles}get flatDocumentFiles(){return this.state.flatFiles.filter(e=>!o(e))}renderTree({changedPaths:e=null,reset:t=!1}={}){this.view.render({activeFilePath:this.state.activeFilePath,changedPaths:e,expandedDirs:this.state.expandedDirs,reset:t,searchMatches:this.state.getSearchMatches(),searchQuery:this.state.searchQuery,tree:this.state.tree})}},fs=30;function ps(e){return String(e??``).split(`/`).pop()||``}function ms(e){let t=String(e??``).split(`/`);return t.pop(),t.join(`/`)}function hs(e=``){let t=ps(e),n=ms(e);return n?`
|
|
306
|
+
`,this.configureDragSource(a,{path:n,type:`file`}),a.addEventListener(`click`,e=>{this.consumeSuppressedActivation(a,e)||this.onFileSelect?.(n)}),a.addEventListener(`contextmenu`,e=>{e.preventDefault(),this.onFileContextMenu?.(e,{filePath:n,type:`file`})}),this.bindLongPress(a,()=>{this.onFileContextMenu?.(this.createLongPressEvent(a),{filePath:n,type:`file`})}),a}isMobileViewport(){return!!this.mobileBreakpointQuery?.matches}isDragAndDropEnabled(){return!this.isMobileViewport()&&!this.currentSearchQuery}configureDragSource(e,t){if(!(e instanceof HTMLElement))return;let n=this.isDragAndDropEnabled();e.draggable=n,n&&(e.addEventListener(`dragstart`,n=>{this.dragSource={path:t.path,type:t.type},document.body?.classList.add(`is-file-tree-dragging`),this.treeContainer&&(this.treeContainer.dataset.dragActive=`true`),e.classList.add(`is-dragging`),n.dataTransfer&&(n.dataTransfer.effectAllowed=`move`,n.dataTransfer.setData(`text/plain`,t.path))}),e.addEventListener(`dragend`,()=>{e.classList.remove(`is-dragging`);let t=this.dragSource;this.invalidDropAttempt&&t&&this.onEntryDrop?.(this.invalidDropAttempt),this.dragSource=null,this.invalidDropAttempt=null,this.clearDragFeedback()}),t.type===`file`&&(e.addEventListener(`dragenter`,e=>{this.handleNonDropTargetDragOver(e)}),e.addEventListener(`dragover`,e=>{this.handleNonDropTargetDragOver(e)})))}bindDirectoryDropTarget(e,t){!(e instanceof HTMLElement)||this.isMobileViewport()||(e.addEventListener(`dragenter`,n=>{this.handleDirectoryDragEnter(n,e,t)}),e.addEventListener(`dragover`,n=>{this.handleDirectoryDragOver(n,e,t)}),e.addEventListener(`drop`,e=>{this.handleDirectoryDrop(e,t)}))}createRootDropZone(){let e=document.createElement(`div`);return e.className=`file-tree-root-drop-zone`,e.textContent=`Drop here to move to vault root`,e.addEventListener(`dragenter`,e=>{this.handleRootZoneDragEnter(e)}),e.addEventListener(`dragover`,e=>{this.handleRootZoneDragOver(e)}),e.addEventListener(`drop`,e=>{this.handleRootZoneDrop(e)}),this.rootDropZone=e,e}validateDrop(e){return!this.dragSource||this.currentSearchQuery?!1:this.onValidateDrop?.({destinationDirectory:e,sourcePath:this.dragSource.path,sourceType:this.dragSource.type})===!0}setDropTarget(e){if(this.activeDropTarget?.element&&this.activeDropTarget.element!==e?.element&&this.activeDropTarget.element.classList.remove(`is-drop-target`,`is-drop-invalid`),this.activeDropTarget?.root&&!e?.root&&this.treeContainer?.classList.remove(`is-drop-target-root`,`is-drop-invalid`),this.activeDropTarget?.rootZone&&!e?.rootZone&&this.rootDropZone?.classList.remove(`is-drop-target`,`is-drop-invalid`),this.activeDropTarget=e,!e||e.isValid?this.invalidDropAttempt=null:this.dragSource&&(this.invalidDropAttempt={destinationDirectory:e.destinationDirectory||``,sourcePath:this.dragSource.path,sourceType:this.dragSource.type}),e){if(e.root){this.treeContainer?.classList.toggle(`is-drop-target-root`,e.isValid),this.treeContainer?.classList.toggle(`is-drop-invalid`,!e.isValid);return}if(e.rootZone){this.rootDropZone?.classList.toggle(`is-drop-target`,e.isValid),this.rootDropZone?.classList.toggle(`is-drop-invalid`,!e.isValid);return}e.element.classList.toggle(`is-drop-target`,e.isValid),e.element.classList.toggle(`is-drop-invalid`,!e.isValid)}}scheduleAutoExpand(e,t){e.getAttribute(`aria-expanded`)===`true`||this.autoExpandTargetPath===t||(this.cancelAutoExpand(),this.autoExpandTargetPath=t,this.autoExpandTimer=window.setTimeout(()=>{this.autoExpandTimer=0,this.autoExpandTargetPath=``,e.isConnected&&e.getAttribute(`aria-expanded`)!==`true`&&this.onDirectoryToggle?.(t)},ps))}cancelAutoExpand(){this.autoExpandTimer&&=(window.clearTimeout(this.autoExpandTimer),0),this.autoExpandTargetPath=``}clearDragFeedback(){this.cancelAutoExpand(),this.setDropTarget(null),document.body?.classList.remove(`is-file-tree-dragging`),this.treeContainer&&delete this.treeContainer.dataset.dragActive}handleDirectoryDragEnter(e,t,n){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let r=this.validateDrop(n);this.setDropTarget({destinationDirectory:n,element:t,isValid:r,root:!1}),r?this.scheduleAutoExpand(t,n):this.cancelAutoExpand()}handleDirectoryDragOver(e,t,n){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let r=this.validateDrop(n);e.dataTransfer&&(e.dataTransfer.dropEffect=r?`move`:`none`),this.setDropTarget({destinationDirectory:n,element:t,isValid:r,root:!1}),r?this.scheduleAutoExpand(t,n):this.cancelAutoExpand()}handleDirectoryDrop(e,t){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let n={destinationDirectory:t,sourcePath:this.dragSource.path,sourceType:this.dragSource.type};this.clearDragFeedback(),this.onEntryDrop?.(n)}handleTreeDragOver(e){if(!this.dragSource||!this.treeContainer||e.target.closest(`.file-tree-dir`)||e.target.closest(`.file-tree-item`))return;e.preventDefault(),this.cancelAutoExpand();let t=this.validateDrop(``);e.dataTransfer&&(e.dataTransfer.dropEffect=t?`move`:`none`),this.setDropTarget({destinationDirectory:``,element:this.treeContainer,isValid:t,root:!0})}handleTreeDrop(e){if(!this.dragSource||!this.treeContainer||e.target.closest(`.file-tree-dir`)||e.target.closest(`.file-tree-item`))return;e.preventDefault();let t={destinationDirectory:``,sourcePath:this.dragSource.path,sourceType:this.dragSource.type};this.clearDragFeedback(),this.onEntryDrop?.(t)}handleTreeDragLeave(e){if(!this.dragSource||!this.treeContainer)return;let t=e.relatedTarget;t&&this.treeContainer.contains(t)||this.clearDragFeedback()}handleRootZoneDragEnter(e){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let t=this.validateDrop(``);this.cancelAutoExpand(),this.setDropTarget({destinationDirectory:``,element:this.rootDropZone,isValid:t,rootZone:!0})}handleRootZoneDragOver(e){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let t=this.validateDrop(``);e.dataTransfer&&(e.dataTransfer.dropEffect=t?`move`:`none`),this.cancelAutoExpand(),this.setDropTarget({destinationDirectory:``,element:this.rootDropZone,isValid:t,rootZone:!0})}handleRootZoneDrop(e){if(!this.dragSource)return;e.preventDefault(),e.stopPropagation();let t={destinationDirectory:``,sourcePath:this.dragSource.path,sourceType:this.dragSource.type};this.clearDragFeedback(),this.onEntryDrop?.(t)}handleNonDropTargetDragOver(e){this.dragSource&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer&&(e.dataTransfer.dropEffect=`none`),this.clearDragFeedback())}bindLongPress(e,t){!(e instanceof HTMLElement)||typeof t!=`function`||(e.addEventListener(`pointerdown`,n=>{this.startLongPress(n,t,e)}),e.addEventListener(`pointermove`,e=>{this.handleLongPressPointerMove(e)},{passive:!0}),e.addEventListener(`pointerup`,()=>{this.cancelLongPress()}),e.addEventListener(`pointercancel`,()=>{this.cancelLongPress()}),e.addEventListener(`pointerleave`,()=>{this.cancelLongPress()}))}startLongPress(e,t,n=null){this.isMobileViewport()&&[`touch`,`pen`].includes(String(e.pointerType||``))&&Number(e.button??0)===0&&(this.cancelLongPress(),this.longPressContext={callback:t,pointerId:e.pointerId,startX:Number(e.clientX||0),startY:Number(e.clientY||0),target:n??e.currentTarget??e.target??null},this.longPressTimer=window.setTimeout(()=>{let e=this.longPressContext;this.longPressTimer=0,e&&(this.suppressedActivationTarget=e.target,e.callback(),this.longPressContext=null)},ds))}handleLongPressPointerMove(e){if(!this.longPressContext||e.pointerId!==this.longPressContext.pointerId)return;let t=Math.abs(Number(e.clientX||0)-this.longPressContext.startX),n=Math.abs(Number(e.clientY||0)-this.longPressContext.startY);(t>fs||n>fs)&&this.cancelLongPress()}cancelLongPress(){this.longPressTimer&&=(window.clearTimeout(this.longPressTimer),0),this.longPressContext=null}createLongPressEvent(e){return{clientX:this.longPressContext?.startX??0,clientY:this.longPressContext?.startY??0,preventDefault(){},stopPropagation(){},target:e}}consumeSuppressedActivation(e,t){return this.suppressedActivationTarget===e?(this.suppressedActivationTarget=null,t?.preventDefault?.(),t?.stopPropagation?.(),!0):!1}getFileIconSvg({isBase:e,isDrawio:t,isExcalidraw:n,isImage:r,isMermaid:i,isPlantUml:a}){return e?`<svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 4h7l5 5v11a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"/><path d="M14 4v5h5"/><path d="M8 13h8"/><path d="M8 17h6"/><path d="M8 9h3"/></svg>`:t?`<svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="7" height="6" rx="1"/><rect x="14" y="4" width="7" height="6" rx="1"/><rect x="8.5" y="14" width="7" height="6" rx="1"/><path d="M10 7h4"/><path d="M17.5 10v2.5"/><path d="M6.5 10v2.5"/><path d="M6.5 12.5h11"/></svg>`:n?`<svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19l7-7 3 3-7 7-3-3z"/><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><path d="M2 2l7.586 7.586"/><circle cx="11" cy="11" r="2"/></svg>`:r?`<svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="9" cy="10" r="1.5"/><path d="m21 16-5-5L7 20"/><path d="m14 14 2 2"/></svg>`:i?`<svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 7.5c0-1.38 1.12-2.5 2.5-2.5 1.04 0 1.93.64 2.3 1.56A2.5 2.5 0 0 1 14 8.5v1"/><path d="M19 16.5c0 1.38-1.12 2.5-2.5 2.5-1.04 0-1.93-.64-2.3-1.56A2.5 2.5 0 0 1 10 15.5v-1"/><path d="M8 10.5h8"/><path d="M8 13.5h8"/><path d="M10 8.5v7"/><path d="M14 8.5v7"/></svg>`:a?`<svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="7" height="6" rx="1"/><rect x="14" y="4" width="7" height="6" rx="1"/><rect x="8.5" y="14" width="7" height="6" rx="1"/><path d="M10 7h4"/><path d="M17.5 10v2.5"/><path d="M6.5 10v2.5"/><path d="M6.5 12.5h11"/></svg>`:`<svg class="file-tree-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>`}showContextMenu(e,t){if(this.removeContextMenu(),!Array.isArray(t)||t.length===0)return;if(this.isMobileViewport()){this.showActionSheet(t);return}let n=document.createElement(`div`);n.className=`file-context-menu`;for(let e of t){let t=document.createElement(`button`);t.className=`file-context-item${e.danger?` file-context-danger`:``}`,t.textContent=e.label,t.addEventListener(`click`,()=>{this.removeContextMenu(),e.onSelect?.()}),n.appendChild(t)}document.body.appendChild(n);let r=n.getBoundingClientRect(),i=Math.max(8,window.innerWidth-r.width-8),a=Math.max(8,window.innerHeight-r.height-8);n.style.left=`${Math.max(8,Math.min(e.clientX,i))}px`,n.style.top=`${Math.max(8,Math.min(e.clientY,a))}px`;let o=e=>{n.contains(e.target)||this.removeContextMenu()};this.contextMenuCloseHandler=o,setTimeout(()=>document.addEventListener(`click`,o),0)}showActionSheet(e){let t=document.createElement(`button`);t.type=`button`,t.className=`file-action-sheet-backdrop`,t.setAttribute(`aria-label`,`Close file actions`);let n=document.createElement(`div`);n.className=`file-action-sheet`,e.forEach(e=>{let t=document.createElement(`button`);t.type=`button`,t.className=G({variant:`secondary`,extra:[`file-action-sheet-item`,e.danger?`file-context-danger`:``]}),t.textContent=e.label,t.addEventListener(`click`,()=>{this.removeContextMenu(),e.onSelect?.()}),n.appendChild(t)});let r=document.createElement(`button`);r.type=`button`,r.className=G({variant:`ghost`,extra:`file-action-sheet-item`}),r.textContent=`Cancel`,r.addEventListener(`click`,()=>{this.removeContextMenu()}),n.appendChild(r),t.addEventListener(`click`,()=>{this.removeContextMenu()}),document.body.append(t,n),this.actionSheetCloseHandler=()=>{t.remove(),n.remove(),this.actionSheetCloseHandler=null}}removeContextMenu(){this.cancelLongPress(),this.clearDragFeedback(),document.querySelectorAll(`.file-context-menu`).forEach(e=>e.remove()),this.contextMenuCloseHandler&&=(document.removeEventListener(`click`,this.contextMenuCloseHandler),null),this.actionSheetCloseHandler?.()}},hs=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onFileSelect:t,onFileDelete:n,pendingWorkspaceRequestIds:r=null,toastController:i,vaultClient:a=S}){this.onFileSelect=t,this.onFileDelete=n,this.toastController=i,this.vaultClient=a,this.state=new ss,this.view=new ms({mobileBreakpointQuery:e,onDirectorySelect:e=>{this.state.expandDirectoryPath(e),this.state.setSearchQuery(``),this.renderTree({reset:!0})},onDirectoryToggle:e=>{this.state.toggleDirectory(e),this.renderTree()},onEntryDrop:e=>this.actionController.moveEntryByDrop(e),onFileContextMenu:(e,t)=>{if(t.type===`directory`){this.view.showContextMenu(e,this.actionController.getDirectoryContextMenuItems(t.directoryPath));return}this.view.showContextMenu(e,this.actionController.getFileContextMenuItems(t.filePath))},onFileSelect:e=>{this.onFileSelect?.(e)},onValidateDrop:e=>this.actionController.canMoveEntryByDrop(e),onSearchChange:e=>{this.state.setSearchQuery(e),this.renderTree()},onTreeContextMenu:e=>{this.view.showContextMenu(e,this.actionController.createContextMenuItems())}}),this.actionController=new ns({mobileBreakpointQuery:e,onFileDelete:this.onFileDelete,onFileSelect:this.onFileSelect,pendingWorkspaceRequestIds:r,refresh:()=>this.refresh(),state:this.state,toastController:this.toastController,vaultClient:this.vaultClient,view:this.view})}initialize(){this.view.initialize(),this.actionController.initialize()}async refresh(){try{let e=await this.vaultClient.readTree();this.setTree(e.tree||[])}catch(e){console.error(`[explorer] Failed to load file tree:`,e.message)}}setTree(e,{changedPaths:t=null,reset:n=!1}={}){this.state.setTree(e),this.renderTree({changedPaths:t,reset:n})}setActiveFile(e){this.state.setActiveFile(e),this.renderTree()}get flatFiles(){return this.state.flatFiles}get flatDocumentFiles(){return this.state.flatFiles.filter(e=>!o(e))}renderTree({changedPaths:e=null,reset:t=!1}={}){this.view.render({activeFilePath:this.state.activeFilePath,changedPaths:e,expandedDirs:this.state.expandedDirs,reset:t,searchMatches:this.state.getSearchMatches(),searchQuery:this.state.searchQuery,tree:this.state.tree})}},gs=30;function _s(e){return String(e??``).split(`/`).pop()||``}function vs(e){let t=String(e??``).split(`/`);return t.pop(),t.join(`/`)}function ys(e=``){let t=_s(e),n=vs(e);return n?`
|
|
307
307
|
<span class="file-history-path">${b(t)}</span>
|
|
308
308
|
<span class="file-history-dir">${b(n)}</span>
|
|
309
|
-
`:`<span class="file-history-path">${b(t)}</span>`}function
|
|
309
|
+
`:`<span class="file-history-path">${b(t)}</span>`}function bs(e={}){let t=[String(e.authorName||`Unknown`),String(e.relativeDateLabel||``)];return e.status===`renamed`&&e.oldPath&&t.push(`Renamed from ${e.oldPath}`),t.filter(Boolean).map(e=>b(e)).join(` · `)}function xs(e={}){return e.type===`local`?`local`:`commit:${String(e.hash||``).trim()}:${String(e.pathAtCommit||``).trim()}`}function Ss(){return{commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0}}var Cs=class{constructor({diffRenderer:e=null,gitApiClient:t=null,onOpenCommitDiff:n=()=>{},onOpenFile:r=()=>{},onOpenPreview:i=()=>{},onOpenWorkspaceDiff:a=()=>{},toastController:o=null}={}){this.diffRenderer=e,this.gitApiClient=t,this.onOpenCommitDiff=n,this.onOpenFile=r,this.onOpenPreview=i,this.onOpenWorkspaceDiff=a,this.toastController=o,this.page=document.getElementById(`diff-page`),this.content=document.getElementById(`diffContent`),this.fileIndicator=document.getElementById(`diffFileIndicator`),this.openEditorButton=document.getElementById(`diffOpenEditorBtn`),this.primaryActionButton=document.getElementById(`diffPrimaryActionBtn`),this.commitButton=document.getElementById(`diffCommitBtn`),this.backToHistoryButton=document.getElementById(`diffBackToHistoryBtn`),this.gitActionsGroup=document.getElementById(`diffGitActionsGroup`),this.editorActionsGroup=document.getElementById(`diffEditorActionsGroup`),this.actionsDivider=document.getElementById(`diffToolbarDivider`),this.stats=document.getElementById(`diffStats`),this.prevButton=document.getElementById(`diffPrevBtn`),this.nextButton=document.getElementById(`diffNextBtn`),this.layoutToggle=document.getElementById(`diffLayoutToggle`),this.modeButtons=Array.from(document.querySelectorAll(`[data-diff-mode]`)),this.isActive=!1,this.currentFilePath=null,this.localChanges=null,this.history=Ss(),this.diffMode=`unified`,this.selectedEntryKey=null,this.detailCache=new Map,this.detailErrors=new Map,this.historyListElement=null,this.historyListScrollTop=0,this.loadingEntryKey=null,this.selectionRequestToken=0}initialize(){this.openEditorButton?.addEventListener(`click`,()=>{this.isActive&&this.currentFilePath&&this.onOpenFile?.(this.currentFilePath)}),this.modeButtons.forEach(e=>{e.addEventListener(`click`,()=>{if(!this.isActive)return;let t=e.getAttribute(`data-diff-mode`);!t||t===this.diffMode||(this.diffMode=t,this.render())})}),this.content?.addEventListener(`click`,e=>{if(!this.isActive)return;let t=e.target instanceof Element?e.target.closest(`[data-file-history-select]`):null;if(t){let e=this.findEntryByKey(t.getAttribute(`data-file-history-select`));e&&this.selectEntry(e);return}if(e.target instanceof Element&&e.target.closest(`[data-file-history-open-selected-diff]`)){this.openSelectedDiff();return}if(e.target instanceof Element&&e.target.closest(`[data-file-history-open-selected-preview]`)){this.openSelectedPreview();return}e.target instanceof Element&&e.target.closest(`[data-file-history-load-more]`)&&this.loadMore()})}hide(){this.isActive=!1,this.page?.classList.add(`hidden`),this.content?.classList.remove(`diff-content--history`),this.content&&(this.content.innerHTML=``),this.currentFilePath=null,this.localChanges=null,this.history=Ss(),this.selectedEntryKey=null,this.loadingEntryKey=null,this.detailCache.clear(),this.detailErrors.clear(),this.historyListElement=null,this.historyListScrollTop=0,this.selectionRequestToken=0}getEntries(){let e=[];this.localChanges&&e.push({...this.localChanges,key:`local`,label:`Local changes`,pathAtCommit:this.currentFilePath,type:`local`});for(let t of this.history.commits??[])e.push({...t,key:xs({...t,type:`commit`}),type:`commit`});return e}findEntryByKey(e){return this.getEntries().find(t=>t.key===e)??null}getSelectedEntry(){return this.findEntryByKey(this.selectedEntryKey)}getDefaultEntry(){return this.getEntries()[0]??null}getSelectedDetailState(){let e=this.getSelectedEntry();return e?{detail:this.detailCache.get(e.key)??null,entry:e,error:this.detailErrors.get(e.key)??``,loading:this.loadingEntryKey===e.key}:null}async openFileHistory({filePath:e}){this.isActive=!0,this.currentFilePath=String(e??``).trim()||null,this.localChanges=null,this.history={...Ss(),loading:!0},this.selectedEntryKey=null,this.loadingEntryKey=null,this.detailCache.clear(),this.detailErrors.clear(),this.historyListElement=null,this.historyListScrollTop=0,this.selectionRequestToken=0,this.renderLoading();try{let[e,t]=await Promise.all([this.loadLocalChanges().catch(()=>null),this.fetchHistoryPage({offset:0})]);this.localChanges=e,this.history=t;let n=this.getDefaultEntry();return n?(await this.selectEntry(n),{history:t,localChanges:e}):(this.render(),{history:t,localChanges:e})}catch(e){return console.error(`[file-history] Failed to load file history:`,e),this.toastController?.show(`Failed to load file history`),this.localChanges=null,this.history={...Ss(),error:`Failed to load file history`,loaded:!0},this.render(),{history:this.history,localChanges:null}}}async loadLocalChanges(){if(!this.currentFilePath)return null;let e=await this.gitApiClient.readDiff({metaOnly:!0,path:this.currentFilePath,scope:`all`}),t=e.files?.[0];return t?{...t,summary:e.summary??{additions:Number(t.stats?.additions||0),deletions:Number(t.stats?.deletions||0),filesChanged:1}}:null}async fetchHistoryPage({offset:e=0}={}){if(!this.currentFilePath)return{...Ss(),loaded:!0};let t=await this.gitApiClient.readFileHistory({limit:gs,offset:e,path:this.currentFilePath}),n=Array.isArray(t.commits)?t.commits:[];return{commits:n,error:``,hasMore:!!t.hasMore,loaded:!0,loading:!1,loadingMore:!1,offset:e+n.length}}async loadSelectedDetail(e){if(!e)return null;if(e.type===`local`){let t=await this.gitApiClient.readDiff({path:this.currentFilePath||``,scope:`all`});return{detail:t.files?.[0]??null,summary:t.summary??e.summary??null}}let t=await this.gitApiClient.readCommit({hash:e.hash||``,path:e.pathAtCommit||``});return{commit:t.commit??null,detail:t.files?.[0]??null,summary:t.summary??null}}async selectEntry(e){if(!e)return null;let t=e.key||xs(e);this.selectedEntryKey=t,this.detailErrors.delete(t);let n=this.detailCache.get(t);if(n)return this.loadingEntryKey=null,this.render(),n;this.loadingEntryKey=t,this.render();let r=++this.selectionRequestToken;try{let n=await this.loadSelectedDetail(e);return this.detailCache.set(t,n),this.detailErrors.delete(t),r===this.selectionRequestToken&&this.selectedEntryKey===t&&(this.loadingEntryKey=null,this.render()),n}catch(n){return console.error(`[file-history] Failed to load selected diff:`,n),this.toastController?.show(e.type===`local`?`Failed to load local diff`:`Failed to load commit diff`),this.detailErrors.set(t,e.type===`local`?`Failed to load local diff`:`Failed to load commit diff`),r===this.selectionRequestToken&&this.selectedEntryKey===t&&(this.loadingEntryKey=null,this.render()),null}}async loadMore(){if(!(!this.currentFilePath||this.history.loading||this.history.loadingMore||!this.history.hasMore)){this.history={...this.history,error:``,loadingMore:!0},this.render();try{let e=await this.fetchHistoryPage({offset:this.history.offset});this.history={commits:[...this.history.commits,...e.commits],error:``,hasMore:e.hasMore,loaded:!0,loading:!1,loadingMore:!1,offset:e.offset},this.render()}catch(e){console.error(`[file-history] Failed to load more history:`,e),this.toastController?.show(`Failed to load file history`),this.history={...this.history,error:`Failed to load file history`,loadingMore:!1},this.render()}}}openSelectedDiff(){let e=this.getSelectedEntry();if(e){if(e.type===`local`){this.onOpenWorkspaceDiff?.(this.currentFilePath);return}this.onOpenCommitDiff?.(e.hash,{historyFilePath:this.currentFilePath,path:e.pathAtCommit})}}openSelectedPreview(){let e=this.getSelectedEntry();!e||e.type!==`commit`||this.onOpenPreview?.({currentFilePath:this.currentFilePath,hash:e.hash,path:e.pathAtCommit})}renderDiffFileHeader(e={}){return typeof this.diffRenderer?.renderFileHeader==`function`?this.diffRenderer.renderFileHeader(e):`
|
|
310
310
|
<div class="diff-file-header">
|
|
311
311
|
<span class="diff-file-path">${b(e.path||this.currentFilePath||``)}</span>
|
|
312
312
|
</div>
|
|
313
313
|
`}renderDiffMarkup(e={}){if(typeof this.diffRenderer?.renderDiffDetail==`function`){let t=this.diffRenderer.mode;this.diffRenderer.mode=this.diffMode;let n=this.diffRenderer.renderDiffDetail(e,0,{includeHeader:!0});return this.diffRenderer.mode=t,n}return`
|
|
314
314
|
${this.renderDiffFileHeader(e)}
|
|
315
315
|
<div class="diff-empty-state">Diff renderer unavailable.</div>
|
|
316
|
-
`}syncToolbar(){let e=this.getSelectedDetailState(),t=e?.entry??null,n=e?.detail?.summary??t?.summary??(t?{additions:Number(t.additions||0),deletions:Number(t.deletions||0)}:null),r=Number(
|
|
316
|
+
`}syncToolbar(){let e=this.getSelectedDetailState(),t=e?.entry??null,n=e?.detail?.summary??t?.summary??(t?{additions:Number(t.additions||0),deletions:Number(t.deletions||0)}:null),r=!!t;this.syncToolbarIndicators(t,n,r),this.syncToolbarButtonStates(r)}syncToolbarIndicators(e,t,n){let r=Number(t?.additions||0),i=Number(t?.deletions||0);this.fileIndicator&&(this.fileIndicator.textContent=e?.type===`commit`?e.shortHash||`Commit`:e?.type===`local`?`Local changes`:`History`),this.stats&&(this.stats.innerHTML=`
|
|
317
317
|
<span class="ui-stat-token ui-stat-token--add diff-stats-add">+${r}</span>
|
|
318
318
|
<span class="ui-stat-token ui-stat-token--del diff-stats-del">-${i}</span>
|
|
319
|
-
`,this.stats.classList.toggle(`hidden`,!
|
|
319
|
+
`,this.stats.classList.toggle(`hidden`,!n))}syncToolbarButtonStates(e){this.backToHistoryButton?.classList.add(`hidden`),this.gitActionsGroup?.classList.add(`hidden`),this.layoutToggle?.classList.add(`hidden`),this.prevButton?.classList.add(`hidden`),this.nextButton?.classList.add(`hidden`),this.actionsDivider?.classList.add(`hidden`),this.editorActionsGroup?.classList.remove(`hidden`),this.modeButtons.forEach(t=>{t.classList.toggle(`hidden`,!e),t.classList.toggle(`active`,t.getAttribute(`data-diff-mode`)===this.diffMode)}),this.openEditorButton?.toggleAttribute(`disabled`,!this.currentFilePath),this.openEditorButton&&(this.openEditorButton.textContent=`Open File`),this.primaryActionButton?.toggleAttribute(`disabled`,!0),this.commitButton?.toggleAttribute(`disabled`,!0)}renderLoading(){this.isActive&&(this.page?.classList.remove(`hidden`),this.content&&(this.content.classList.add(`diff-content--history`),this.content.innerHTML=`<div class="git-panel-empty">Loading file history...</div>`),this.historyListElement=null,this.syncToolbar())}renderEmpty(e){this.isActive&&(this.page?.classList.remove(`hidden`),this.content&&(this.content.classList.add(`diff-content--history`),this.content.innerHTML=`<div class="git-panel-empty">${b(e)}</div>`),this.historyListElement=null,this.syncToolbar())}captureListScroll(){this.historyListElement&&(this.historyListScrollTop=Number(this.historyListElement.scrollTop||0))}restoreListScroll(){if(!this.content?.querySelector){this.historyListElement=null;return}let e=this.content.querySelector(`[data-file-history-list]`);this.historyListElement=e??null,e&&(e.scrollTop=this.historyListScrollTop,e.addEventListener(`scroll`,()=>{this.historyListScrollTop=Number(e.scrollTop||0)},{passive:!0}))}renderScopeLabels(e={}){let t=[];return e.hasStagedChanges&&t.push(`staged`),e.hasWorkingTreeChanges&&t.push(`working tree`),e.hasUntrackedChanges&&t.push(`untracked`),t.length>0?t.join(` · `):`working tree`}renderHistoryItem(e={}){let t=e.key===this.selectedEntryKey,n=Number(e.additions??e.summary?.additions??0),r=Number(e.deletions??e.summary?.deletions??0),i=e.type===`local`?`Live workspace`:bs(e),a=e.type===`local`?`Local changes`:e.subject||e.shortHash||`Commit`,o=e.type===`local`?`<span class="ui-pill-badge ui-pill-badge--accent file-history-item-badge">Live</span>`:`<span class="ui-pill-badge ui-pill-badge--code file-history-item-badge">${b(e.shortHash||``)}</span>`;return`
|
|
320
320
|
<button
|
|
321
321
|
class="ui-record-surface file-history-item${t?` active`:``}${e.type===`local`?` file-history-item-local`:``}"
|
|
322
322
|
type="button"
|
|
@@ -340,7 +340,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
340
340
|
<div class="file-history-detail-copy">
|
|
341
341
|
<span class="file-history-detail-kicker">${t.type===`local`?`Live workspace`:`Commit ${b(t.shortHash||``)}`}</span>
|
|
342
342
|
<h2 class="file-history-detail-title">${t.type===`local`?`Local changes`:b(t.subject||t.shortHash||`Commit`)}</h2>
|
|
343
|
-
<p class="file-history-detail-meta">${t.type===`local`?b(this.renderScopeLabels(t)):
|
|
343
|
+
<p class="file-history-detail-meta">${t.type===`local`?b(this.renderScopeLabels(t)):bs(t)}</p>
|
|
344
344
|
</div>
|
|
345
345
|
<div class="file-history-detail-actions">
|
|
346
346
|
<button
|
|
@@ -388,7 +388,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
388
388
|
<aside class="file-history-sidebar" aria-label="File history entries">
|
|
389
389
|
<header class="file-history-sidebar-header">
|
|
390
390
|
<span class="file-history-kicker">File history</span>
|
|
391
|
-
<div class="file-history-title">${
|
|
391
|
+
<div class="file-history-title">${ys(this.currentFilePath)}</div>
|
|
392
392
|
<p class="file-history-sidebar-copy">Select an entry to inspect the exact changes for this file.</p>
|
|
393
393
|
</header>
|
|
394
394
|
<div class="file-history-list" data-file-history-list>
|
|
@@ -414,7 +414,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
414
414
|
</div>
|
|
415
415
|
</section>
|
|
416
416
|
</section>
|
|
417
|
-
`,this.restoreListScroll()}};function
|
|
417
|
+
`,this.restoreListScroll()}};function ws(e){return String(e??``).split(`/`).pop()||``}function Ts(e){let t=String(e??``).split(`/`);return t.pop(),t.join(`/`)}function Es(e){return`diff-section-${encodeURIComponent(String(e??``)).replace(/%/g,`_`)}`}function Ds(e){switch(e){case`added`:case`untracked`:return`ui-status-badge--success`;case`deleted`:return`ui-status-badge--danger`;case`renamed`:return`ui-status-badge--accent`;default:return`ui-status-badge--warning`}}function Os(e=!1){return`<svg class="diff-section-chevron${e?` collapsed`:``}" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg>`}function ks(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n}function As(e,t,n){let r=0,i=Math.min(e.length,t.length)-n;for(;r<i;){let n=e.length-1-r,i=t.length-1-r;if(e[n]!==t[i])break;r+=1}return r}function js(e,t){let n=ks(e,t),r=As(e,t,n),i=Math.max(n,e.length-r),a=Math.max(n,t.length-r);return{leftHtml:`${b(e.slice(0,n))}${i>n?`<span class="diff-highlight-del">${b(e.slice(n,i))}</span>`:``}${b(e.slice(i))}`,rightHtml:`${b(t.slice(0,n))}${a>n?`<span class="diff-highlight-add">${b(t.slice(n,a))}</span>`:``}${b(t.slice(a))}`}}function Ms(e=[]){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.type===`context`||r.type===`note`){t.push({additions:[],context:[r],deletions:[]});continue}if(r.type!==`deletion`&&r.type!==`addition`)continue;let i=[],a=[];for(;n<e.length&&e[n].type===`deletion`;)i.push(e[n]),n+=1;for(;n<e.length&&e[n].type===`addition`;)a.push(e[n]),n+=1;--n,t.push({additions:a,context:[],deletions:i})}return t}function Ns(e,t,n){let r=Number.isInteger(e.oldLine)?e.oldLine:``,i=Number.isInteger(e.newLine)?e.newLine:``;return`
|
|
418
418
|
<div class="diff-line ${e.type===`note`?`note`:e.type}">
|
|
419
419
|
<div class="diff-line-numbers">
|
|
420
420
|
<span class="diff-line-num">${r}</span>
|
|
@@ -423,7 +423,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
423
423
|
<div class="diff-line-prefix">${b(e.type===`context`||e.type===`note`?` `:t)}</div>
|
|
424
424
|
<div class="diff-line-content">${n}</div>
|
|
425
425
|
</div>
|
|
426
|
-
`}function
|
|
426
|
+
`}function Ps(e,t){let n=e?b(e.content):``,r=t?b(t.content):``;if(e&&t&&e.type===`deletion`&&t.type===`addition`){let i=js(e.content,t.content);n=i.leftHtml,r=i.rightHtml}return`
|
|
427
427
|
<div class="diff-split-row">
|
|
428
428
|
<div class="diff-split-line ${e?.type||`empty`}">
|
|
429
429
|
<span class="diff-split-num">${Number.isInteger(e?.oldLine)?e.oldLine:``}</span>
|
|
@@ -434,13 +434,13 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
434
434
|
<span class="diff-split-content">${r}</span>
|
|
435
435
|
</div>
|
|
436
436
|
</div>
|
|
437
|
-
`}var
|
|
437
|
+
`}var Fs=class{constructor({gitApiClient:e=null,onBackToHistory:t=null,onCommitStaged:n=null,onOpenFile:r=null,onStageFile:i=null,onUnstageFile:a=null,toastController:o=null}={}){this.gitApiClient=e,this.onBackToHistory=t,this.onCommitStaged=n,this.onOpenFile=r,this.onStageFile=i,this.onUnstageFile=a,this.toastController=o,this.page=document.getElementById(`diff-page`),this.content=document.getElementById(`diffContent`),this.scrollContainer=document.getElementById(`diffScroll`),this.fileIndicator=document.getElementById(`diffFileIndicator`),this.openEditorButton=document.getElementById(`diffOpenEditorBtn`),this.primaryActionButton=document.getElementById(`diffPrimaryActionBtn`),this.commitButton=document.getElementById(`diffCommitBtn`),this.backToHistoryButton=document.getElementById(`diffBackToHistoryBtn`),this.gitActionsGroup=document.getElementById(`diffGitActionsGroup`),this.editorActionsGroup=document.getElementById(`diffEditorActionsGroup`),this.actionsDivider=document.getElementById(`diffToolbarDivider`),this.stats=document.getElementById(`diffStats`),this.prevButton=document.getElementById(`diffPrevBtn`),this.nextButton=document.getElementById(`diffNextBtn`),this.layoutToggle=document.getElementById(`diffLayoutToggle`),this.modeButtons=Array.from(document.querySelectorAll(`[data-diff-mode]`)),this.layoutButtons=Array.from(document.querySelectorAll(`[data-diff-layout]`)),this.isActive=!1,this.mode=`unified`,this.layoutMode=`focused`,this.source=`workspace`,this.data=null,this.currentIndex=0,this.activeFilePath=null,this.fileCache=new Map,this.fileErrors=new Map,this.loadingFiles=new Set,this.collapsedFiles=new Set,this.fileLoadPromises=new Map,this.requestScope=`all`,this.commitHash=null,this.commitMeta=null,this.historyFilePath=null,this.pendingAction=null,this.repoStatus=null}initialize(){this.prevButton?.addEventListener(`click`,()=>{this.isActive&&this.navigateFile(-1)}),this.nextButton?.addEventListener(`click`,()=>{this.isActive&&this.navigateFile(1)}),this.backToHistoryButton?.addEventListener(`click`,()=>{this.isActive&&this.commitMeta?.hash&&this.onBackToHistory?.({hash:this.commitMeta.hash,historyFilePath:this.historyFilePath})}),this.openEditorButton?.addEventListener(`click`,()=>{if(!this.isActive||this.source!==`workspace`)return;let e=this.getCurrentFile();e?.path&&this.onOpenFile?.(e.path)}),this.primaryActionButton?.addEventListener(`click`,()=>{if(!this.isActive)return;let e=this.getPrimaryAction();e&&this.handleFileAction(e)}),this.commitButton?.addEventListener(`click`,()=>{this.isActive&&this.handleFileAction(`commit`)}),this.content?.addEventListener(`click`,e=>{if(!this.isActive)return;let t=e.target instanceof Element?e.target.closest(`[data-load-full-diff]`):null;if(t){let e=t.getAttribute(`data-diff-file-path`)||this.activeFilePath;e&&this.loadFileForPath(e,{forceFullPatch:!0});return}let n=e.target instanceof Element?e.target.closest(`[data-diff-section-toggle]`):null;if(n){let e=n.getAttribute(`data-diff-section-toggle`);e&&this.toggleFileSection(e);return}let r=e.target instanceof Element?e.target.closest(`[data-diff-index-path]`):null;if(r){let e=r.getAttribute(`data-diff-index-path`);e&&this.handleIndexSelection(e)}}),this.modeButtons.forEach(e=>{e.addEventListener(`click`,()=>{if(!this.isActive)return;let t=e.getAttribute(`data-diff-mode`);!t||t===this.mode||(this.mode=t,this.render())})}),this.layoutButtons.forEach(e=>{e.addEventListener(`click`,()=>{if(!this.isActive)return;let t=e.getAttribute(`data-diff-layout`);!t||t===this.layoutMode||this.setLayoutMode(t)})}),this.scrollContainer?.addEventListener(`scroll`,()=>{this.isActive&&this.handleScrollSelection()})}hide(){this.isActive=!1,this.page?.classList.add(`hidden`),this.content&&(this.content.innerHTML=``),this.data=null,this.source=`workspace`,this.layoutMode=`focused`,this.currentIndex=0,this.activeFilePath=null,this.fileCache.clear(),this.fileErrors.clear(),this.loadingFiles.clear(),this.collapsedFiles.clear(),this.fileLoadPromises.clear(),this.requestScope=`all`,this.commitHash=null,this.commitMeta=null,this.historyFilePath=null,this.pendingAction=null,this.repoStatus=null}async openWorkspaceDiff({filePath:e=null,scope:t=`all`}={}){this.isActive=!0,this.source=`workspace`,this.layoutMode=`focused`,this.commitHash=null,this.commitMeta=null,this.historyFilePath=null,this.activeFilePath=e,this.fileCache.clear(),this.fileErrors.clear(),this.loadingFiles.clear(),this.collapsedFiles.clear(),this.fileLoadPromises.clear(),this.requestScope=t,this.renderLoading(`Loading diff summary...`);try{let n=await this.gitApiClient.readDiff({metaOnly:!0,path:e,scope:t});this.data=n;let r=e?Math.max(0,n.files.findIndex(t=>t.path===e)):0;return this.currentIndex=r,this.activeFilePath=n.files?.[r]?.path??null,(n.files?.length??0)===0?(this.render(),n):(await this.loadCurrentFile(),n)}catch(e){return console.error(`[git-diff] Failed to load diff:`,e),this.toastController?.show(`Failed to load git diff`),this.data={files:[],metaOnly:!1,source:`workspace`,summary:{additions:0,deletions:0,filesChanged:0}},this.renderEmpty(`Failed to load git diff`),this.data}}async openCommitDiff({hash:e,path:t=null,historyFilePath:n=null}={}){this.isActive=!0,this.source=`commit`,this.layoutMode=`stacked`,this.commitHash=String(e??``).trim()||null,this.commitMeta=null,this.historyFilePath=String(n??``).trim()||null,this.activeFilePath=t||null,this.fileCache.clear(),this.fileErrors.clear(),this.loadingFiles.clear(),this.collapsedFiles.clear(),this.fileLoadPromises.clear(),this.requestScope=`all`,this.renderLoading(`Loading commit summary...`);try{let e=await this.gitApiClient.readCommit({hash:this.commitHash||``,metaOnly:!0});this.data=e,this.commitMeta=e.commit??null;let n=t?Math.max(0,e.files.findIndex(e=>e.path===t)):0;return this.currentIndex=n,this.activeFilePath=e.files?.[n]?.path??null,this.collapsedFiles=new Set((e.files??[]).map(e=>e.path).filter(e=>e&&e!==this.activeFilePath)),(e.files?.length??0)===0?(this.render(),e):(this.activeFilePath&&await this.loadFileForPath(this.activeFilePath,{render:!1}),this.render(),e)}catch(e){return console.error(`[git-diff] Failed to load commit:`,e),this.toastController?.show(`Failed to load git commit`),this.data={commit:null,files:[],metaOnly:!1,source:`commit`,summary:{additions:0,deletions:0,filesChanged:0}},this.commitMeta=null,this.renderEmpty(`Failed to load git commit`),this.data}}async open(e={}){return this.openWorkspaceDiff(e)}async setLayoutMode(e){let t=e===`stacked`?`stacked`:`focused`;if(this.source!==`commit`){this.layoutMode=`focused`,this.render();return}if(this.layoutMode=t,this.activeFilePath&&this.setActiveFilePath(this.activeFilePath),this.layoutMode===`focused`){await this.loadCurrentFile();return}this.activeFilePath&&(this.collapsedFiles.delete(this.activeFilePath),await this.loadFileForPath(this.activeFilePath,{render:!1})),this.render()}navigateFile(e){if(!this.data?.files?.length||this.source===`commit`&&this.layoutMode===`stacked`)return;let t=Math.max(0,Math.min(this.currentIndex+e,this.data.files.length-1));t!==this.currentIndex&&(this.currentIndex=t,this.activeFilePath=this.data.files[t]?.path??null,this.scrollContainer?.scrollTo({top:0,behavior:`auto`}),this.loadCurrentFile())}renderLoading(e=`Loading git diff...`){this.isActive&&(this.page?.classList.remove(`hidden`),this.content&&(this.content.innerHTML=`<div class="diff-empty-state">${b(e)}</div>`),this.data=null,this.syncToolbar())}renderEmpty(e){this.isActive&&(this.page?.classList.remove(`hidden`),this.content&&(this.content.innerHTML=`<div class="diff-empty-state">${b(e)}</div>`),this.syncToolbar())}renderUnifiedHunk(e){let t=[];for(let n of Ms(e.lines)){if(n.context.length>0){for(let e of n.context)t.push(Ns(e,` `,b(e.content)));continue}let e=Math.max(n.deletions.length,n.additions.length);for(let r=0;r<e;r+=1){let e=n.deletions[r]??null,i=n.additions[r]??null,a=e&&i?js(e.content,i.content):null;e&&t.push(Ns(e,`-`,a?.leftHtml??b(e.content))),i&&t.push(Ns(i,`+`,a?.rightHtml??b(i.content)))}}return`
|
|
438
438
|
<div class="diff-hunk-header">${b(e.header)}</div>
|
|
439
439
|
${t.join(``)}
|
|
440
440
|
`}renderFileHeader(e){return`
|
|
441
441
|
<div class="diff-file-header">
|
|
442
442
|
<span class="diff-file-path">${b(e.path)}</span>
|
|
443
|
-
<span class="ui-status-badge ${
|
|
443
|
+
<span class="ui-status-badge ${Ds(e.status)}">${b(e.status)}</span>
|
|
444
444
|
<span class="diff-file-header-stats"><span class="ui-stat-token ui-stat-token--add diff-stats-add">+${e.stats?.additions??0}</span><span class="ui-stat-token ui-stat-token--del diff-stats-del">-${e.stats?.deletions??0}</span></span>
|
|
445
445
|
</div>
|
|
446
446
|
`}renderUnifiedFileBody(e){return`
|
|
@@ -450,7 +450,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
450
450
|
<div class="diff-split">
|
|
451
451
|
<div class="diff-split-pane">
|
|
452
452
|
<div class="diff-split-pane-header">Before</div>
|
|
453
|
-
${e.hunks.map(e=>{let t=[];for(let n of
|
|
453
|
+
${e.hunks.map(e=>{let t=[];for(let n of Ms(e.lines)){if(n.context.length>0){for(let e of n.context)t.push(Ps(e,e));continue}let e=Math.max(n.deletions.length,n.additions.length);for(let r=0;r<e;r+=1)t.push(Ps(n.deletions[r]??null,n.additions[r]??null))}return`
|
|
454
454
|
<div class="diff-split-hunk">${b(e.header)}</div>
|
|
455
455
|
${t.join(``)}
|
|
456
456
|
`}).join(``)}
|
|
@@ -495,7 +495,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
495
495
|
<aside class="diff-commit-index" aria-label="Changed files in commit">
|
|
496
496
|
<div class="diff-commit-index-header">Changed Files</div>
|
|
497
497
|
<div class="diff-commit-index-list">
|
|
498
|
-
${(this.data?.files??[]).map((e,t)=>{let n=this.activeFilePath===e.path,r=
|
|
498
|
+
${(this.data?.files??[]).map((e,t)=>{let n=this.activeFilePath===e.path,r=Ts(e.path);return`
|
|
499
499
|
<button
|
|
500
500
|
class="ui-record-surface diff-index-item${n?` active`:``}"
|
|
501
501
|
type="button"
|
|
@@ -503,8 +503,8 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
503
503
|
aria-current="${n?`true`:`false`}"
|
|
504
504
|
>
|
|
505
505
|
<span class="ui-record-header diff-index-item-top">
|
|
506
|
-
<span class="ui-record-title diff-index-item-name">${b(
|
|
507
|
-
<span class="ui-status-badge ${
|
|
506
|
+
<span class="ui-record-title diff-index-item-name">${b(ws(e.path))}</span>
|
|
507
|
+
<span class="ui-status-badge ${Ds(e.status)}">${b(e.status)}</span>
|
|
508
508
|
</span>
|
|
509
509
|
${r?`<span class="ui-record-subtitle diff-index-item-path">${b(r)}</span>`:``}
|
|
510
510
|
<span class="ui-record-meta diff-index-item-meta">
|
|
@@ -519,7 +519,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
519
519
|
`}renderStackedSection(e,t){let n=this.isFileCollapsed(e.path),r=this.activeFilePath===e.path,i=this.isFileLoading(e.path),a=this.fileErrors.get(e.path),o=this.getFileDetail(e.path)??e,s=n?``:i?`<div class="diff-empty-state">Loading file diff...</div>`:a?`<div class="diff-empty-state">${b(a)}</div>`:this.renderDiffDetail(o,t,{includeHeader:!1});return`
|
|
520
520
|
<section
|
|
521
521
|
class="diff-commit-section${r?` active`:``}${n?` collapsed`:``}"
|
|
522
|
-
id="${
|
|
522
|
+
id="${Es(e.path)}"
|
|
523
523
|
data-diff-section-path="${b(e.path)}"
|
|
524
524
|
>
|
|
525
525
|
<button
|
|
@@ -528,14 +528,14 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
528
528
|
data-diff-section-toggle="${b(e.path)}"
|
|
529
529
|
>
|
|
530
530
|
<span class="diff-commit-section-main">
|
|
531
|
-
${
|
|
531
|
+
${Os(n)}
|
|
532
532
|
<span class="diff-commit-section-copy">
|
|
533
|
-
<span class="diff-commit-section-name">${b(
|
|
534
|
-
${
|
|
533
|
+
<span class="diff-commit-section-name">${b(ws(e.path))}</span>
|
|
534
|
+
${Ts(e.path)?`<span class="diff-commit-section-path">${b(Ts(e.path))}</span>`:``}
|
|
535
535
|
</span>
|
|
536
536
|
</span>
|
|
537
537
|
<span class="diff-commit-section-meta">
|
|
538
|
-
<span class="ui-status-badge ${
|
|
538
|
+
<span class="ui-status-badge ${Ds(e.status)}">${b(e.status)}</span>
|
|
539
539
|
<span class="ui-stat-token ui-stat-token--add diff-stats-add">+${e.stats?.additions??0}</span>
|
|
540
540
|
<span class="ui-stat-token ui-stat-token--del diff-stats-del">-${e.stats?.deletions??0}</span>
|
|
541
541
|
</span>
|
|
@@ -560,10 +560,10 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
560
560
|
</div>
|
|
561
561
|
</div>
|
|
562
562
|
</div>
|
|
563
|
-
`}getCurrentFile(){let e=this.data?.files??[];return e.length===0?null:e[this.currentIndex]??e[0]??null}getFileByPath(e){return(this.data?.files??[]).find(t=>t.path===e)??null}setActiveFilePath(e,{syncIndex:t=!0}={}){if(this.activeFilePath=e,!t)return;let n=Math.max(0,(this.data?.files??[]).findIndex(t=>t.path===e));n>=0&&(this.currentIndex=n)}getCacheKeyForPath(e){return e?this.source===`commit`?`commit:${this.commitHash}:${e}`:`workspace:${this.requestScope}:${e}`:null}getCurrentCacheKey(){return this.getCacheKeyForPath(this.getCurrentFile()?.path??null)}getCurrentFileDetail(){let e=this.getCurrentCacheKey();return e?this.fileCache.get(e):null}getFileDetail(e){let t=this.getCacheKeyForPath(e);return t?this.fileCache.get(t):null}isFileCollapsed(e){return this.collapsedFiles.has(e)}isFileLoading(e){return this.loadingFiles.has(e)}getCurrentActionState(){if(this.source===`commit`)return{canCommit:!1,canStage:!1,canUnstage:!1};let e=this.getCurrentFile(),t=this.getCurrentFileDetail()??e,n=Number(this.repoStatus?.summary?.staged||0);return t?.path?{canCommit:n>0,canStage:!!(t.hasWorkingTreeChanges||t.hasUntrackedChanges),canUnstage:!!t.hasStagedChanges}:{canCommit:n>0,canStage:!1,canUnstage:!1}}getPrimaryAction(){if(this.source===`commit`)return null;let e=this.getCurrentActionState();return e.canStage&&!e.canUnstage?`stage`:e.canUnstage&&!e.canStage||this.requestScope===`staged`&&e.canUnstage?`unstage`:e.canStage?`stage`:e.canUnstage?`unstage`:null}async handleFileAction(e){if(this.source===`commit`)return;let t=this.getCurrentFile();if(!(!t?.path||this.pendingAction)){this.pendingAction=e,this.syncToolbar();try{e===`stage`?await this.onStageFile?.(t.path,{scope:this.requestScope}):e===`unstage`?await this.onUnstageFile?.(t.path,{scope:this.requestScope}):e===`commit`&&await this.onCommitStaged?.()}finally{this.pendingAction=null,this.syncToolbar()}}}setRepoStatus(e){this.repoStatus=e,this.syncToolbar()}async handleIndexSelection(e){if(this.getFileByPath(e)){if(this.setActiveFilePath(e),this.source===`commit`&&this.layoutMode===`stacked`){this.collapsedFiles.delete(e),await this.loadFileForPath(e,{render:!1}),this.render(),this.scrollToFileSection(e);return}await this.loadFileForPath(e)}}async toggleFileSection(e){if(!(this.source!==`commit`||this.layoutMode!==`stacked`)){if(this.setActiveFilePath(e),this.collapsedFiles.has(e)){this.collapsedFiles.delete(e),await this.loadFileForPath(e,{render:!1}),this.render(),this.scrollToFileSection(e);return}this.collapsedFiles.add(e),this.render()}}scrollToFileSection(e){if(!this.content)return;let t=
|
|
563
|
+
`}getCurrentFile(){let e=this.data?.files??[];return e.length===0?null:e[this.currentIndex]??e[0]??null}getFileByPath(e){return(this.data?.files??[]).find(t=>t.path===e)??null}setActiveFilePath(e,{syncIndex:t=!0}={}){if(this.activeFilePath=e,!t)return;let n=Math.max(0,(this.data?.files??[]).findIndex(t=>t.path===e));n>=0&&(this.currentIndex=n)}getCacheKeyForPath(e){return e?this.source===`commit`?`commit:${this.commitHash}:${e}`:`workspace:${this.requestScope}:${e}`:null}getCurrentCacheKey(){return this.getCacheKeyForPath(this.getCurrentFile()?.path??null)}getCurrentFileDetail(){let e=this.getCurrentCacheKey();return e?this.fileCache.get(e):null}getFileDetail(e){let t=this.getCacheKeyForPath(e);return t?this.fileCache.get(t):null}isFileCollapsed(e){return this.collapsedFiles.has(e)}isFileLoading(e){return this.loadingFiles.has(e)}getCurrentActionState(){if(this.source===`commit`)return{canCommit:!1,canStage:!1,canUnstage:!1};let e=this.getCurrentFile(),t=this.getCurrentFileDetail()??e,n=Number(this.repoStatus?.summary?.staged||0);return t?.path?{canCommit:n>0,canStage:!!(t.hasWorkingTreeChanges||t.hasUntrackedChanges),canUnstage:!!t.hasStagedChanges}:{canCommit:n>0,canStage:!1,canUnstage:!1}}getPrimaryAction(){if(this.source===`commit`)return null;let e=this.getCurrentActionState();return e.canStage&&!e.canUnstage?`stage`:e.canUnstage&&!e.canStage||this.requestScope===`staged`&&e.canUnstage?`unstage`:e.canStage?`stage`:e.canUnstage?`unstage`:null}async handleFileAction(e){if(this.source===`commit`)return;let t=this.getCurrentFile();if(!(!t?.path||this.pendingAction)){this.pendingAction=e,this.syncToolbar();try{e===`stage`?await this.onStageFile?.(t.path,{scope:this.requestScope}):e===`unstage`?await this.onUnstageFile?.(t.path,{scope:this.requestScope}):e===`commit`&&await this.onCommitStaged?.()}finally{this.pendingAction=null,this.syncToolbar()}}}setRepoStatus(e){this.repoStatus=e,this.syncToolbar()}async handleIndexSelection(e){if(this.getFileByPath(e)){if(this.setActiveFilePath(e),this.source===`commit`&&this.layoutMode===`stacked`){this.collapsedFiles.delete(e),await this.loadFileForPath(e,{render:!1}),this.render(),this.scrollToFileSection(e);return}await this.loadFileForPath(e)}}async toggleFileSection(e){if(!(this.source!==`commit`||this.layoutMode!==`stacked`)){if(this.setActiveFilePath(e),this.collapsedFiles.has(e)){this.collapsedFiles.delete(e),await this.loadFileForPath(e,{render:!1}),this.render(),this.scrollToFileSection(e);return}this.collapsedFiles.add(e),this.render()}}scrollToFileSection(e){if(!this.content)return;let t=Es(e),n=()=>{let e=document.getElementById?.(t)??null;if(e){if(this.scrollContainer?.scrollTo&&this.scrollContainer.getBoundingClientRect&&e.getBoundingClientRect){let t=this.scrollContainer.getBoundingClientRect(),n=e.getBoundingClientRect(),r=Number(this.scrollContainer.scrollTop)||0,i=Math.max(0,r+(n.top-t.top)-8);this.scrollContainer.scrollTo({top:i,behavior:`smooth`});return}e.scrollIntoView?.({behavior:`smooth`,block:`start`})}};if(typeof requestAnimationFrame==`function`){requestAnimationFrame(n);return}setTimeout(n,0)}handleScrollSelection(){if(this.source!==`commit`||this.layoutMode!==`stacked`||!this.scrollContainer||!this.content)return;let e=Array.from(this.content.querySelectorAll?.(`[data-diff-section-path]`)??[]);if(e.length===0)return;let t=this.scrollContainer.getBoundingClientRect?.();if(!t)return;let n=t.top+120,r=null;for(let t of e){let e=t.getBoundingClientRect?.();if(!e)continue;let i=t.getAttribute?.(`data-diff-section-path`);if(i)if(e.top<=n)r=i;else if(r)break;else{r=i;break}}r&&r!==this.activeFilePath&&(this.setActiveFilePath(r),this.render())}async loadCurrentFile({forceFullPatch:e=!1}={}){let t=this.getCurrentFile();return t?.path?this.loadFileForPath(t.path,{forceFullPatch:e}):(this.render(),null)}async loadFileForPath(e,{forceFullPatch:t=!1,render:n=!0}={}){let r=this.getFileByPath(e);if(!r?.path)return n&&this.render(),null;this.setActiveFilePath(e);let i=this.getCacheKeyForPath(e),a=i?this.fileCache.get(i):null;if(a&&(!a.tooLarge||!t))return n&&this.render(),a;let o=`${e}:${t?`full`:`partial`}`;if(this.fileLoadPromises.has(o))return this.fileLoadPromises.get(o);this.loadingFiles.add(e),this.fileErrors.delete(e),n&&this.render();let s=(async()=>{try{let n;if(this.source===`commit`){let i=await this.gitApiClient.readCommit({allowLargePatch:t,hash:this.commitHash||``,path:e});n={...r,...i.files?.[0]??{}}}else{let i=await this.gitApiClient.readDiff({allowLargePatch:t,path:e,scope:this.requestScope});n={...r,...i.files?.[0]??{}}}return i&&this.fileCache.set(i,n),this.fileErrors.delete(e),n}catch(t){console.error(`[git-diff] Failed to load file diff:`,t);let n=this.source===`commit`?`Failed to load commit file diff`:`Failed to load file diff`;return this.fileErrors.set(e,n),this.toastController?.show(n),null}finally{this.loadingFiles.delete(e),this.fileLoadPromises.delete(o),this.render()}})();return this.fileLoadPromises.set(o,s),s}syncToolbar(){let e=this.data?.files?.length??0,t=e===0?0:this.currentIndex+1,n=this.source===`commit`,r=n&&this.layoutMode===`stacked`;if(this.fileIndicator&&(r?this.fileIndicator.textContent=`${e} file${e===1?``:`s`}`:this.fileIndicator.textContent=e>0?`${t} / ${e} files`:`0 / 0 files`),this.stats){let e=this.data?.summary?.additions??0,t=this.data?.summary?.deletions??0;this.stats.innerHTML=`
|
|
564
564
|
<span class="ui-stat-token ui-stat-token--add diff-stats-add">+${e}</span>
|
|
565
565
|
<span class="ui-stat-token ui-stat-token--del diff-stats-del">-${t}</span>
|
|
566
|
-
`}this.modeButtons.forEach(e=>{e.classList.remove(`hidden`),e.classList.toggle(`active`,e.getAttribute(`data-diff-mode`)===this.mode)}),this.layoutButtons.forEach(e=>{e.classList.toggle(`active`,e.getAttribute(`data-diff-layout`)===this.layoutMode)});let i=!!this.getCurrentFile()?.path,a=this.getCurrentActionState(),o=this.getPrimaryAction();this.backToHistoryButton?.classList.toggle(`hidden`,!n),this.gitActionsGroup?.classList.toggle(`hidden`,n),this.editorActionsGroup?.classList.toggle(`hidden`,n),this.actionsDivider?.classList.toggle(`hidden`,n),this.layoutToggle?.classList.toggle(`hidden`,!n),this.stats?.classList.remove(`hidden`),this.openEditorButton&&(this.openEditorButton.textContent=`Open in Editor`),this.openEditorButton?.toggleAttribute(`disabled`,!i||n),this.primaryActionButton&&(this.primaryActionButton.textContent=this.pendingAction===o?`Working...`:o===`unstage`?`Unstage`:`Stage`,this.primaryActionButton.toggleAttribute(`disabled`,n||!i||!o||!!this.pendingAction)),this.commitButton&&(this.commitButton.textContent=this.pendingAction===`commit`?`Working...`:`Commit Staged`),this.commitButton?.toggleAttribute(`disabled`,n||!a.canCommit||!!this.pendingAction),this.prevButton?.classList.remove(`hidden`),this.nextButton?.classList.remove(`hidden`),this.prevButton?.classList.toggle(`hidden`,r),this.nextButton?.classList.toggle(`hidden`,r),this.prevButton?.toggleAttribute(`disabled`,r||this.currentIndex<=0),this.nextButton?.toggleAttribute(`disabled`,r||e===0||this.currentIndex>=e-1)}render(){if(this.isActive){if(this.page?.classList.remove(`hidden`),(this.data?.files??[]).length===0){this.renderEmpty(this.source===`commit`?`No commit changes to display.`:`No changes to display.`);return}this.content&&(this.source===`commit`?this.content.innerHTML=`${this.renderCommitHeader()}${this.renderCommitBody()}`:this.content.innerHTML=this.renderFocusedFileBody(),this.syncToolbar())}}getToolbarTitle({commitHash:e=null,filePath:t=null,path:n=null,scope:r=`all`,source:i=`workspace`}={}){return i===`commit`||this.source===`commit`?this.layoutMode===`stacked`?this.commitMeta?.shortHash?`Commit ${this.commitMeta.shortHash}`:e?`Commit ${String(e).slice(0,7)}`:`Commit Diff`:n?
|
|
566
|
+
`}this.modeButtons.forEach(e=>{e.classList.remove(`hidden`),e.classList.toggle(`active`,e.getAttribute(`data-diff-mode`)===this.mode)}),this.layoutButtons.forEach(e=>{e.classList.toggle(`active`,e.getAttribute(`data-diff-layout`)===this.layoutMode)});let i=!!this.getCurrentFile()?.path,a=this.getCurrentActionState(),o=this.getPrimaryAction();this.backToHistoryButton?.classList.toggle(`hidden`,!n),this.gitActionsGroup?.classList.toggle(`hidden`,n),this.editorActionsGroup?.classList.toggle(`hidden`,n),this.actionsDivider?.classList.toggle(`hidden`,n),this.layoutToggle?.classList.toggle(`hidden`,!n),this.stats?.classList.remove(`hidden`),this.openEditorButton&&(this.openEditorButton.textContent=`Open in Editor`),this.openEditorButton?.toggleAttribute(`disabled`,!i||n),this.primaryActionButton&&(this.primaryActionButton.textContent=this.pendingAction===o?`Working...`:o===`unstage`?`Unstage`:`Stage`,this.primaryActionButton.toggleAttribute(`disabled`,n||!i||!o||!!this.pendingAction)),this.commitButton&&(this.commitButton.textContent=this.pendingAction===`commit`?`Working...`:`Commit Staged`),this.commitButton?.toggleAttribute(`disabled`,n||!a.canCommit||!!this.pendingAction),this.prevButton?.classList.remove(`hidden`),this.nextButton?.classList.remove(`hidden`),this.prevButton?.classList.toggle(`hidden`,r),this.nextButton?.classList.toggle(`hidden`,r),this.prevButton?.toggleAttribute(`disabled`,r||this.currentIndex<=0),this.nextButton?.toggleAttribute(`disabled`,r||e===0||this.currentIndex>=e-1)}render(){if(this.isActive){if(this.page?.classList.remove(`hidden`),(this.data?.files??[]).length===0){this.renderEmpty(this.source===`commit`?`No commit changes to display.`:`No changes to display.`);return}this.content&&(this.source===`commit`?this.content.innerHTML=`${this.renderCommitHeader()}${this.renderCommitBody()}`:this.content.innerHTML=this.renderFocusedFileBody(),this.syncToolbar())}}getToolbarTitle({commitHash:e=null,filePath:t=null,path:n=null,scope:r=`all`,source:i=`workspace`}={}){return i===`commit`||this.source===`commit`?this.layoutMode===`stacked`?this.commitMeta?.shortHash?`Commit ${this.commitMeta.shortHash}`:e?`Commit ${String(e).slice(0,7)}`:`Commit Diff`:n?ws(n):this.activeFilePath?ws(this.activeFilePath):this.commitMeta?.shortHash?`Commit ${this.commitMeta.shortHash}`:e?`Commit ${String(e).slice(0,7)}`:`Commit Diff`:t?ws(t):r===`staged`?`Staged Changes`:r===`working-tree`?`Working Tree Changes`:`All Changes`}},Is=30,Ls=1e4;function Rs(e){let t=String(e??``).split(`/`);return t.pop(),t.join(`/`)}function zs(e){return String(e??``).split(`/`).pop()||``}function Bs(){return`<svg class="git-file-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>`}function Vs(){return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="18" cy="18" r="3"/><circle cx="6" cy="6" r="3"/><path d="M13 6h3a2 2 0 0 1 2 2v7"/><path d="M6 9v12"/></svg>`}function Hs(e){return`<svg class="git-section-chevron${e?` collapsed`:``}" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg>`}function Us(e){switch(e){case`commit`:return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>`;case`pull`:return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14"/><path d="m18 13-6 6-6-6"/></svg>`;case`push`:return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 19V5"/><path d="m6 11 6-6 6 6"/></svg>`;case`unstage`:return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 12H8"/><path d="m12 16-4-4 4-4"/></svg>`;case`reset`:return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 12a9 9 0 1 0 3-6.7"/><path d="M3 4v5h5"/></svg>`;default:return`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14"/><path d="M5 12h14"/></svg>`}}function Ws(e){switch(e){case`added`:return`ui-status-badge--success`;case`deleted`:return`ui-status-badge--danger`;case`renamed`:return`ui-status-badge--accent`;case`untracked`:return`ui-status-badge--muted`;default:return`ui-status-badge--warning`}}function Gs(e={},t={}){let n=Number(e.additions||0),r=Number(e.deletions||0);return Number(e.changedFiles||0)>0||n>0||r>0?`
|
|
567
567
|
<span class="git-change-stats" aria-label="Local diff summary">
|
|
568
568
|
<span class="git-change-add">+${n}</span>
|
|
569
569
|
<span class="git-change-del">-${r}</span>
|
|
@@ -573,10 +573,10 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
573
573
|
<span class="git-sync-metric git-sync-metric--ahead">↑${Number(t.ahead||0)}</span>
|
|
574
574
|
<span class="git-sync-metric git-sync-metric--behind">↓${Number(t.behind||0)}</span>
|
|
575
575
|
</span>
|
|
576
|
-
`:`<span class="git-sync-info git-sync-info-muted">Clean</span>`}function
|
|
576
|
+
`:`<span class="git-sync-info git-sync-info-muted">Clean</span>`}function Ks(e={}){return b(String(e.subject||``).trim()||e.shortHash||`Commit`)}var qs=class{constructor({enabled:e=!0,gitApiClient:t=null,onCommitStaged:n=()=>{},onOpenPullBackup:r=()=>{},onPullBranch:i=()=>{},onPushBranch:a=()=>{},onRepoChange:o=()=>{},onResetFile:s=()=>{},onSelectCommit:c=()=>{},onSelectDiff:l=()=>{},onStageFile:u=()=>{},onUnstageFile:d=()=>{},onViewAllDiff:f=()=>{},searchInput:p=null,toastController:m=null}={}){this.enabled=e,this.gitApiClient=t,this.onCommitStaged=n,this.onOpenPullBackup=r,this.onPullBranch=i,this.onPushBranch=a,this.onRepoChange=o,this.onResetFile=s,this.onSelectCommit=c,this.onSelectDiff=l,this.onStageFile=u,this.onUnstageFile=d,this.onViewAllDiff=f,this.searchInput=p,this.toastController=m,this.panel=document.getElementById(`gitPanel`),this.pullBackups=[],this.status=null,this.active=!1,this.refreshTimer=null,this.searchQuery=``,this.panelMode=`changes`,this.collapsedSections=new Set,this.selection={commitHash:null,path:null,scope:null,source:`workspace`},this.pendingActionKey=null,this.history={commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0}}_handlePanelModeClick(e){let t=e.target instanceof Element?e.target.closest(`[data-git-panel-mode]`):null;if(t){let e=t.getAttribute(`data-git-panel-mode`);return(e===`changes`||e===`history`)&&this.setMode(e),!0}return!1}_handleSectionToggleClick(e){let t=e.target instanceof Element?e.target.closest(`[data-git-section-toggle]`):null;return t?(this.toggleSection(t.getAttribute(`data-git-section-toggle`)),!0):!1}_handleCommitHistoryClick(e){let t=e.target instanceof Element?e.target.closest(`[data-git-commit-hash]`):null;if(t&&!e.target.closest(`[data-git-history-load-more]`)){let e=t.getAttribute(`data-git-commit-hash`);return e&&this.onSelectCommit(e,{path:this.selection.commitHash===e?this.selection.path:null}),!0}return!1}_handleFileSelectionClick(e){let t=e.target instanceof Element?e.target.closest(`[data-git-path]`):null;if(t&&!e.target.closest(`[data-git-file-action]`)){let e=t.getAttribute(`data-git-path`);return e&&this.onSelectDiff(e,{scope:t.getAttribute(`data-git-scope`)||`working-tree`}),!0}return!1}_handleFileActionClick(e){let t=e.target instanceof Element?e.target.closest(`[data-git-file-action]`):null;if(t){let n=t.getAttribute(`data-git-file-action`),r=t.getAttribute(`data-git-path`);return n&&r&&(e.preventDefault(),e.stopPropagation(),this.handleFileAction(n,r,t.getAttribute(`data-git-scope`)||`working-tree`)),!0}return!1}_handlePanelClick(e){if(this._handlePanelModeClick(e)||this._handleSectionToggleClick(e)||this._handleCommitHistoryClick(e))return;if(e.target instanceof Element&&e.target.closest(`[data-git-history-load-more]`)){this.loadMoreHistory();return}if(this._handleFileSelectionClick(e))return;let t=e.target instanceof Element?e.target.closest(`[data-git-pull-backup-path]`):null;if(t){let e=t.getAttribute(`data-git-pull-backup-path`);e&&this.onOpenPullBackup(e);return}if(this._handleFileActionClick(e))return;if(e.target instanceof Element&&e.target.closest(`[data-git-view-all]`)){this.onViewAllDiff();return}if(e.target instanceof Element&&e.target.closest(`[data-git-commit-staged]`)){this.handleCommitStaged();return}let n=e.target instanceof Element?e.target.closest(`[data-git-sync-action]`):null;if(n){let e=n.getAttribute(`data-git-sync-action`);(e===`pull`||e===`push`)&&this.handleSyncAction(e)}}initialize(){this.panel?.addEventListener(`click`,e=>{this._handlePanelClick(e)}),this.searchInput?.addEventListener(`input`,e=>{this.searchQuery=String(e.target?.value??``).trim().toLowerCase(),this.render()}),this.syncSearchUi()}setActive(e){let t=!!e;if(!(this.active===t&&(!t||this.refreshTimer||this.panelMode===`history`))){if(this.active=t,!this.active){this.stopStatusPolling();return}this.syncSearchUi(),this.refresh({force:!1,includeHistory:this.panelMode===`history`}),this.panelMode===`changes`?this.ensureStatusPolling():this.stopStatusPolling()}}async setMode(e,{forceHistoryRefresh:t=!1}={}){let n=e===`history`?`history`:`changes`,r=this.panelMode!==n;if(this.panelMode=n,this.syncSearchUi(),this.render(),this.active){if(this.panelMode===`changes`){this.ensureStatusPolling(),r&&await this.refresh({force:!1,includeHistory:!1});return}this.stopStatusPolling(),(t||r||!this.history.loaded)&&await this.refreshHistory({force:t||r})}}setSelection({commitHash:e=null,path:t=null,scope:n=null,source:r=`workspace`}={}){this.selection={commitHash:e,path:t,scope:n,source:r},(r===`commit`||e)&&(this.panelMode=`history`,this.syncSearchUi()),this.render()}toggleSection(e){e&&(this.collapsedSections.has(e)?this.collapsedSections.delete(e):this.collapsedSections.add(e),this.render())}ensureStatusPolling(){this.refreshTimer||!this.active||this.panelMode!==`changes`||(this.refreshTimer=setInterval(()=>{this.refresh({force:!1,includeHistory:!1})},Ls))}stopStatusPolling(){clearInterval(this.refreshTimer),this.refreshTimer=null}syncSearchUi(){this.searchInput&&(this.searchInput.setAttribute(`placeholder`,this.panelMode===`history`?`Filter loaded commits...`:`Search changes...`),this.searchInput.setAttribute(`aria-label`,this.panelMode===`history`?`Filter loaded commits`:`Search changed files`))}async refresh({force:e=!1,includeHistory:t=this.panelMode===`history`}={}){let n=await this.refreshStatus({force:e});return t&&n.isGitRepo&&await this.refreshHistory({force:e}),n}async refreshStatus({force:e=!1}={}){if(!this.enabled)return this.status={isGitRepo:!1,sections:[],summary:{changedFiles:0}},this.pullBackups=[],this.history={...this.history,commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0},this.onRepoChange(!1,this.status),this.render(),this.status;try{let t=await this.gitApiClient.readStatus({force:e});if(this.status=t,this.pullBackups=[],t.isGitRepo)try{let e=await this.gitApiClient.readPullBackups();this.pullBackups=Array.isArray(e.backups)?e.backups:[]}catch(e){console.error(`[git-panel] Failed to load pull backups:`,e)}else this.history={...this.history,commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0};return this.onRepoChange(!!t.isGitRepo,t),this.render(),t}catch(e){return console.error(`[git-panel] Failed to load git status:`,e),this.toastController?.show(`Failed to load git status`),this.status={isGitRepo:!1,sections:[],summary:{changedFiles:0}},this.pullBackups=[],this.history={...this.history,commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0},this.onRepoChange(!1,this.status),this.render(),this.status}}async refreshHistory({force:e=!1}={}){if(!this.status?.isGitRepo)return this.history={...this.history,commits:[],error:``,hasMore:!1,loaded:!1,loading:!1,loadingMore:!1,offset:0},this.render(),this.history;if(this.history.loading&&!e)return this.history;this.history={...this.history,error:``,loading:!0,loadingMore:!1},e&&(this.history={...this.history,commits:[],hasMore:!1,loaded:!1,offset:0}),this.render();try{let e=await this.gitApiClient.readHistory({limit:Is,offset:0});return this.history={commits:Array.isArray(e.commits)?e.commits:[],error:``,hasMore:!!e.hasMore,loaded:!0,loading:!1,loadingMore:!1,offset:Array.isArray(e.commits)?e.commits.length:0},this.render(),this.history}catch(e){return console.error(`[git-panel] Failed to load git history:`,e),this.toastController?.show(`Failed to load git history`),this.history={...this.history,error:`Failed to load git history`,loading:!1,loadingMore:!1},this.render(),this.history}}async loadMoreHistory(){if(!(!this.status?.isGitRepo||this.history.loading||this.history.loadingMore||!this.history.hasMore)){this.history={...this.history,error:``,loadingMore:!0},this.render();try{let e=await this.gitApiClient.readHistory({limit:Is,offset:this.history.offset}),t=Array.isArray(e.commits)?e.commits:[];this.history={commits:[...this.history.commits,...t],error:``,hasMore:!!e.hasMore,loaded:!0,loading:!1,loadingMore:!1,offset:this.history.offset+t.length},this.render()}catch(e){console.error(`[git-panel] Failed to load more git history:`,e),this.toastController?.show(`Failed to load git history`),this.history={...this.history,error:`Failed to load git history`,loadingMore:!1},this.render()}}}filterFiles(e=[]){return this.searchQuery?e.filter(e=>e.path.toLowerCase().includes(this.searchQuery)||String(e.oldPath||``).toLowerCase().includes(this.searchQuery)):e}filterCommits(e=[]){return this.searchQuery?e.filter(e=>String(e.subject||``).toLowerCase().includes(this.searchQuery)||String(e.shortHash||``).toLowerCase().includes(this.searchQuery)||String(e.authorName||``).toLowerCase().includes(this.searchQuery)):e}async handleFileAction(e,t,n){let r=`${e}:${n}:${t}`;if(this.pendingActionKey!==r){this.pendingActionKey=r,this.render();try{e===`stage`?await this.onStageFile(t,{scope:n}):e===`unstage`?await this.onUnstageFile(t,{scope:n}):e===`reset`&&await this.onResetFile(t,{scope:n})}finally{this.pendingActionKey=null,this.render()}}}async handleCommitStaged(){let e=`commit-staged`;if(this.pendingActionKey!==e){this.pendingActionKey=e,this.render();try{await this.onCommitStaged()}finally{this.pendingActionKey=null,this.render()}}}async handleSyncAction(e){let t=`sync:${e}`;if(this.pendingActionKey!==t){this.pendingActionKey=t,this.render();try{e===`pull`?await this.onPullBranch():e===`push`&&await this.onPushBranch()}finally{this.pendingActionKey=null,this.render()}}}renderSection(e){let t=this.filterFiles(e.files);if(t.length===0)return``;let n=this.collapsedSections.has(e.key);return`
|
|
577
577
|
<section class="git-section">
|
|
578
578
|
<button class="git-section-header" type="button" data-git-section-toggle="${b(e.key)}">
|
|
579
|
-
${
|
|
579
|
+
${Hs(n)}
|
|
580
580
|
${b(e.label)}
|
|
581
581
|
<span class="ui-pill-badge ui-pill-badge--count ui-pill-badge--muted git-section-count">${t.length}</span>
|
|
582
582
|
</button>
|
|
@@ -587,7 +587,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
587
587
|
`}renderPullBackupsSection(){return!Array.isArray(this.pullBackups)||this.pullBackups.length===0?``:`
|
|
588
588
|
<section class="git-section">
|
|
589
589
|
<button class="git-section-header" type="button" data-git-section-toggle="pull-backups">
|
|
590
|
-
${
|
|
590
|
+
${Hs(this.collapsedSections.has(`pull-backups`))}
|
|
591
591
|
Pull Backups
|
|
592
592
|
<span class="ui-pill-badge ui-pill-badge--count ui-pill-badge--muted git-section-count">${this.pullBackups.length}</span>
|
|
593
593
|
</button>
|
|
@@ -602,7 +602,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
602
602
|
type="button"
|
|
603
603
|
data-git-pull-backup-path="${b(e.summaryPath||``)}"
|
|
604
604
|
>
|
|
605
|
-
${
|
|
605
|
+
${Bs()}
|
|
606
606
|
<span class="ui-item-copy git-file-copy">
|
|
607
607
|
<span class="ui-item-title git-file-name">Pull backup ${b(e.id||``)}</span>
|
|
608
608
|
<span class="ui-item-subtitle git-file-path">${b(`${t} · ${e.branch||`HEAD`} · ${n} file${n===1?``:`s`}`)}</span>
|
|
@@ -610,7 +610,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
610
610
|
<span class="ui-status-badge ui-status-badge--warning">BK</span>
|
|
611
611
|
</button>
|
|
612
612
|
</div>
|
|
613
|
-
`}renderFile(e){let t=this.selection.source===`workspace`&&this.selection.path===e.path&&this.selection.scope===e.scope,n=
|
|
613
|
+
`}renderFile(e){let t=this.selection.source===`workspace`&&this.selection.path===e.path&&this.selection.scope===e.scope,n=Rs(e.path),r=zs(e.path),i=Ws(e.status),a=e.scope===`staged`?{label:`Unstage`,value:`unstage`}:{label:`Stage`,value:`stage`},o=`${a.value}:${e.scope}:${e.path}`,s=this.pendingActionKey===o,c=`reset:${e.scope}:${e.path}`,l=this.pendingActionKey===c;return`
|
|
614
614
|
<div class="ui-item-row git-file-row${t?` active`:``}">
|
|
615
615
|
<button
|
|
616
616
|
class="ui-item-main git-file-item${t?` active`:``}"
|
|
@@ -618,7 +618,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
618
618
|
data-git-path="${b(e.path)}"
|
|
619
619
|
data-git-scope="${b(e.scope)}"
|
|
620
620
|
>
|
|
621
|
-
${
|
|
621
|
+
${Bs()}
|
|
622
622
|
<span class="ui-item-copy git-file-copy">
|
|
623
623
|
<span class="ui-item-title git-file-name">${b(r)}</span>
|
|
624
624
|
${n?`<span class="ui-item-subtitle git-file-path">${b(n)}</span>`:``}
|
|
@@ -636,7 +636,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
636
636
|
title="Reset to current branch"
|
|
637
637
|
${l?`disabled`:``}
|
|
638
638
|
>
|
|
639
|
-
${l?`...`:
|
|
639
|
+
${l?`...`:Us(`reset`)}
|
|
640
640
|
</button>
|
|
641
641
|
<button
|
|
642
642
|
class="ui-icon-button ui-action-icon ui-action-icon--surface"
|
|
@@ -648,12 +648,12 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
648
648
|
title="${b(a.label)}"
|
|
649
649
|
${s?`disabled`:``}
|
|
650
650
|
>
|
|
651
|
-
${s?`...`:
|
|
651
|
+
${s?`...`:Us(a.value)}
|
|
652
652
|
</button>
|
|
653
653
|
</div>
|
|
654
654
|
</div>
|
|
655
655
|
`}renderPanelModes(){return`
|
|
656
|
-
<div class="${
|
|
656
|
+
<div class="${Br({pill:!0,extra:`git-panel-mode-switch`})}" role="tablist" aria-label="Git panel modes">
|
|
657
657
|
<button
|
|
658
658
|
class="${q({active:this.panelMode===`changes`,extra:`git-panel-mode-btn`})}"
|
|
659
659
|
type="button"
|
|
@@ -679,7 +679,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
679
679
|
title="${b(e.authoredAt||``)}"
|
|
680
680
|
>
|
|
681
681
|
<span class="ui-record-header git-history-row-top">
|
|
682
|
-
<span class="ui-record-title git-history-subject">${
|
|
682
|
+
<span class="ui-record-title git-history-subject">${Ks(e)}</span>
|
|
683
683
|
<span class="ui-pill-badge ui-pill-badge--code git-history-hash">${b(e.shortHash||``)}</span>
|
|
684
684
|
</span>
|
|
685
685
|
<span class="ui-record-meta git-history-row-meta">
|
|
@@ -734,10 +734,10 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
734
734
|
<div class="git-branch-bar">
|
|
735
735
|
<div class="git-branch-meta">
|
|
736
736
|
<span class="git-branch-name">
|
|
737
|
-
${
|
|
737
|
+
${Vs()}
|
|
738
738
|
${b(e.name||`HEAD`)}
|
|
739
739
|
</span>
|
|
740
|
-
${
|
|
740
|
+
${Gs(this.status.summary,e)}
|
|
741
741
|
</div>
|
|
742
742
|
<div class="git-branch-actions" role="group" aria-label="Remote sync actions">
|
|
743
743
|
<button
|
|
@@ -748,7 +748,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
748
748
|
aria-label="Pull branch"
|
|
749
749
|
${!t||n?`disabled`:``}
|
|
750
750
|
>
|
|
751
|
-
${n?`...`:`${
|
|
751
|
+
${n?`...`:`${Us(`pull`)}<span>Pull</span>`}
|
|
752
752
|
</button>
|
|
753
753
|
<button
|
|
754
754
|
class="${G({variant:`secondary`,size:`compact`,pill:!0,surface:!0,extra:`ui-action-pill`})}"
|
|
@@ -758,14 +758,14 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
758
758
|
aria-label="Push branch"
|
|
759
759
|
${!t||r?`disabled`:``}
|
|
760
760
|
>
|
|
761
|
-
${r?`...`:`${
|
|
761
|
+
${r?`...`:`${Us(`push`)}<span>Push</span>`}
|
|
762
762
|
</button>
|
|
763
763
|
</div>
|
|
764
764
|
${this.renderPanelModes()}
|
|
765
765
|
</div>
|
|
766
766
|
${this.panelMode===`history`?this.renderHistoryPanel():this.renderChangesPanel()}
|
|
767
|
-
`}},Ws=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onMeasureEditor:t,onViewRequest:n=null}){this.mobileBreakpointQuery=e,this.onMeasureEditor=t,this.onViewRequest=n,this.preferredView=`split`,this.mobileShowsEditor=!this.isMobileViewport(),this.currentView=this.mobileShowsEditor?this.preferredView:`preview`,this.editorLayout=document.getElementById(`editorLayout`),this.editorPane=document.getElementById(`editorPane`),this.previewPane=document.getElementById(`previewPane`),this.mobileToggleButton=document.getElementById(`mobileViewToggle`),this.resizer=document.getElementById(`resizer`),this.viewButtons=Array.from(document.querySelectorAll(`.view-btn`))}isMobileViewport(){return this.mobileBreakpointQuery.matches}initialize(){this.viewButtons.forEach(e=>{e.addEventListener(`click`,()=>{this.onViewRequest?.(e.dataset.view)!==!1&&this.setView(e.dataset.view)})}),this.mobileToggleButton?.addEventListener(`click`,()=>this.toggleMobileView()),this.initializeResizer(),this.restorePreferredView()}primeView(e){if(e){if(this.isMobileViewport()){this.mobileShowsEditor=e!==`preview`;return}this.preferredView=e}}reset(){this.restorePreferredView(),this.editorPane&&(this.editorPane.style.flex=``),this.previewPane&&(this.previewPane.style.flex=``),this.updateResizerValue()}restorePreferredView(){let e=this.isMobileViewport()?this.mobileShowsEditor?`split`:`preview`:this.preferredView;this.applyView(e),this.updateMobileToggleButton(this.mobileShowsEditor?`Preview`:`Editor`)}applyView(e){this.currentView=e,this.editorLayout?.setAttribute(`data-view`,e),this.syncViewButtons()}setView(e,{persist:t=!0}={}){e&&(t&&(this.preferredView=e),this.applyView(e),(e===`split`||e===`editor`)&&this.scheduleEditorMeasure())}toggleMobileView(){let e=!this.mobileShowsEditor,t=e?`split`:`preview`;this.onViewRequest?.(t)!==!1&&(this.mobileShowsEditor=e,this.applyView(t),this.updateMobileToggleButton(this.mobileShowsEditor?`Preview`:`Editor`),this.mobileShowsEditor&&this.scheduleEditorMeasure())}scheduleEditorMeasure(){this.onMeasureEditor&&setTimeout(()=>this.onMeasureEditor(),50)}updateMobileToggleButton(e){this.mobileToggleButton&&(this.mobileToggleButton.innerHTML=`${e===`Editor`?`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="8" y1="8" x2="16" y2="8"/><line x1="8" y1="12" x2="14" y2="12"/><line x1="8" y1="16" x2="12" y2="16"/></svg>`:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>`}<span class="ui-toolbar-button-label">${e}</span>`)}syncViewButtons(){this.viewButtons.forEach(e=>{let t=e.dataset.view===this.currentView;e.classList.toggle(`active`,t),e.setAttribute(`aria-pressed`,String(t))})}updateResizerValue(){if(!this.resizer||!this.editorLayout||!this.editorPane)return;let e=this.editorLayout.offsetWidth;if(!Number.isFinite(e)||e<=0)return;let t=Math.round(this.editorPane.offsetWidth/e*100);this.resizer.setAttribute(`aria-valuenow`,String(Math.max(20,Math.min(80,t))))}applyEditorPaneWidth(e){if(!this.editorLayout||!this.editorPane||!this.previewPane)return;let t=this.editorLayout.offsetWidth;if(!Number.isFinite(t)||t<=0)return;let n=Math.max(200,Math.min(t-200,e))/t*100;this.editorPane.style.flex=`0 0 ${n}%`,this.previewPane.style.flex=`1`,this.updateResizerValue()}initializeResizer(){if(!this.resizer||!this.editorLayout||!this.editorPane||!this.previewPane)return;let e=!1,t=0,n=0;this.resizer.addEventListener(`mousedown`,r=>{e=!0,t=r.clientX,n=this.editorPane.offsetWidth,this.resizer.classList.add(`dragging`),document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`,r.preventDefault()}),document.addEventListener(`mousemove`,r=>{if(!e)return;let i=r.clientX-t;this.applyEditorPaneWidth(n+i)}),document.addEventListener(`mouseup`,()=>{e&&(e=!1,this.resizer.classList.remove(`dragging`),document.body.style.cursor=``,document.body.style.userSelect=``,this.scheduleEditorMeasure())}),this.resizer.addEventListener(`keydown`,e=>{let t=this.editorLayout.offsetWidth;if(!Number.isFinite(t)||t<=0)return;let n=Math.max(24,Math.round(t*.05));if(e.key===`ArrowLeft`){e.preventDefault(),this.applyEditorPaneWidth(this.editorPane.offsetWidth-n),this.scheduleEditorMeasure();return}if(e.key===`ArrowRight`){e.preventDefault(),this.applyEditorPaneWidth(this.editorPane.offsetWidth+n),this.scheduleEditorMeasure();return}if(e.key===`Home`){e.preventDefault(),this.applyEditorPaneWidth(t*.2),this.scheduleEditorMeasure();return}e.key===`End`&&(e.preventDefault(),this.applyEditorPaneWidth(t*.8),this.scheduleEditorMeasure())}),this.updateResizerValue()}},Gs=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onNavigateToHeading:t,onWillOpen:n}={}){this.outlineOpen=!1,this.activeHeadingFrame=null,this.activeHeadingId=null,this.headings=[],this.pinnedHeadingId=null,this.onNavigateToHeading=t,this.onWillOpen=n,this.panel=document.getElementById(`outlinePanel`),this.navigation=document.getElementById(`outlineNav`),this.previewContainer=document.getElementById(`previewContainer`),this.toggleButton=document.getElementById(`outlineToggle`),this.mobileBreakpointQuery=e,this.handlePreviewScroll=()=>this.scheduleActiveHeadingUpdate(),this.handleDocumentPointerDown=e=>{if(!this.outlineOpen)return;let t=e.target;t instanceof Node&&(this.panel?.contains(t)||this.toggleButton?.contains(t))||this.close()}}initialize(){this.toggleButton?.addEventListener(`click`,()=>this.toggle()),document.addEventListener(`pointerdown`,this.handleDocumentPointerDown)}toggle(){this.setOpenState(!this.outlineOpen)}close(){this.setOpenState(!1)}setOpenState(e){if(e&&!this.outlineOpen&&this.onWillOpen?.(),this.outlineOpen=e,this.panel?.classList.toggle(`hidden`,!this.outlineOpen),this.toggleButton?.classList.toggle(`active`,this.outlineOpen),this.outlineOpen){this.refresh();return}this.cleanup()}refresh(){if(!this.navigation)return;if(!this.outlineOpen){this.cleanup();return}let e=document.getElementById(`previewContent`)?.querySelectorAll(`h1, h2, h3, h4, h5, h6`)??[];if(e.length===0){this.navigation.innerHTML=`<div class="outline-empty">No headings found</div>`,this.cleanup();return}let t=Array.from(e).map((e,t)=>(e.id||=`heading-${t}-${e.textContent.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,40)}`,{id:e.id,level:Number.parseInt(e.tagName[1],10),sourceLine:Number.parseInt(e.getAttribute(`data-source-line`)||``,10),text:e.textContent.trim()}));this.navigation.innerHTML=t.map(e=>`<button class="outline-item" data-level="${e.level}" data-target="${e.id}"${Number.isFinite(e.sourceLine)?` data-source-line="${e.sourceLine}"`:``} title="${e.text.replace(/"/g,`"`)}">${e.text}</button>`).join(``),this.navigation.querySelectorAll(`.outline-item`).forEach(e=>{e.addEventListener(`click`,()=>{let t=document.getElementById(e.dataset.target);this.pinnedHeadingId=e.dataset.target,this.notifyHeadingNavigation(t,e.dataset.target),this.scrollHeadingIntoView(t,{behavior:`auto`}),this.setActiveItem(e.dataset.target,{behavior:`auto`}),this.mobileBreakpointQuery.matches&&this.close()})}),this.observeHeadings(Array.from(e))}cleanup(){this.activeHeadingFrame&&=(cancelAnimationFrame(this.activeHeadingFrame),null),this.previewContainer?.removeEventListener(`scroll`,this.handlePreviewScroll),this.headings=[],this.pinnedHeadingId=null}setActiveItem(e,{scrollIntoView:t=!0,behavior:n=`smooth`}={}){this.activeHeadingId=e,this.navigation?.querySelectorAll(`.outline-item`).forEach(t=>{t.classList.toggle(`active`,t.dataset.target===e)}),t&&this.navigation?.querySelector(`.outline-item.active`)?.scrollIntoView({behavior:n,block:`nearest`})}observeHeadings(e){this.cleanup(),!(!this.previewContainer||e.length===0)&&(this.headings=e,this.previewContainer.addEventListener(`scroll`,this.handlePreviewScroll,{passive:!0}),this.updateActiveHeading())}scheduleActiveHeadingUpdate(){this.activeHeadingFrame||=requestAnimationFrame(()=>{this.activeHeadingFrame=null,this.updateActiveHeading()})}updateActiveHeading(){if(!this.previewContainer||this.headings.length===0)return;let e=this.getPinnedHeading();if(e&&this.shouldKeepPinnedHeadingActive(e)){this.setActiveItem(e.id,{behavior:`auto`,scrollIntoView:!0});return}this.pinnedHeadingId=null;let t=this.previewContainer.scrollTop,n=this.headings[0];for(let e of this.headings){if(this.getHeadingScrollTop(e)>t)break;n=e}this.setActiveItem(n.id,{behavior:`auto`,scrollIntoView:!0})}getHeadingScrollTop(e){if(!this.previewContainer)return 0;let t=this.previewContainer.getBoundingClientRect(),n=e.getBoundingClientRect();return this.previewContainer.scrollTop+(n.top-t.top)}getPinnedHeading(){return this.pinnedHeadingId?this.headings.find(e=>e.id===this.pinnedHeadingId)??null:null}shouldKeepPinnedHeadingActive(e){if(!this.previewContainer||!e?.isConnected)return!1;let t=this.getHeadingScrollTop(e)-this.previewContainer.scrollTop,n=t+e.getBoundingClientRect().height,r=this.previewContainer.clientHeight*.45;return n>-48&&t<r}notifyHeadingNavigation(e,t){if(!e)return;let n=Number.parseInt(e.getAttribute(`data-source-line`)||``,10);this.onNavigateToHeading?.({headingId:t,sourceLine:Number.isFinite(n)?n:null})}scrollHeadingIntoView(e,{behavior:t=`smooth`}={}){if(!e||!this.previewContainer)return;let n=this.previewContainer.getBoundingClientRect(),r=e.getBoundingClientRect(),i=this.previewContainer.scrollTop+(r.top-n.top);this.previewContainer.scrollTo({behavior:t,top:Math.max(i,0)})}},Ks=.35,qs=120,Js=12,Ys=2;function Xs(e){return Math.max(e.scrollHeight-e.clientHeight,0)}function Zs(e){return Math.max(e,0)}function Qs(e){return Math.max(e.clientHeight*Ks,Js)}function $s(e){return(e?.scrollTop??0)<=Ys}function ec(e,t){let n=e.getBoundingClientRect();return t.getBoundingClientRect().top-n.top+e.scrollTop}function tc(e){return!e.querySelector(`[data-source-line]`)}function nc(e){return typeof window.requestIdleCallback==`function`?window.requestIdleCallback(e,{timeout:500}):window.setTimeout(()=>{e({didTimeout:!1,timeRemaining:()=>0})},1)}function rc(e){if(e!==null){if(typeof window.cancelIdleCallback==`function`){window.cancelIdleCallback(e);return}window.clearTimeout(e)}}var ic=class{constructor({getEditorLineNumber:e,onEditorScrollActivityChange:t,previewContainer:n,previewElement:r,scrollEditorToLine:i}){this.getEditorLineNumber=e,this.onEditorScrollActivityChange=t,this.previewContainer=n,this.previewElement=r,this.scrollEditorToLine=i,this.editorScroller=null,this.editorScrollActive=!1,this.editorScrollIdleTimer=null,this.lockedElements=new Set,this.pendingSync=null,this.frameId=null,this.previewBlocks=null,this.previewBlocksWarmId=null,this.previewBlocksReadyCallbacks=[],this.largeDocumentMode=!1,this.lastInteractionSource=`editor`,this.suspendedUntil=0,this.handleEditorScroll=()=>{if(!(!this.editorScroller||this.lockedElements.has(this.editorScroller)||this.isSuspended())){if(this.lastInteractionSource=`editor`,this.largeDocumentMode){this.setEditorScrollActive(!0),this.scheduleEditorScrollIdle(),this.scheduleSync(this.editorScroller,this.previewContainer,{preferApproximateMapping:!0});return}this.scheduleSync(this.editorScroller,this.previewContainer)}},this.handlePreviewScroll=()=>{!this.previewContainer||this.lockedElements.has(this.previewContainer)||this.isSuspended()||(this.lastInteractionSource=`preview`,this.scheduleSync(this.previewContainer,this.editorScroller))}}initialize(){this.previewContainer?.addEventListener(`scroll`,this.handlePreviewScroll,{passive:!0})}attachEditorScroller(e){this.editorScroller!==e&&(this.editorScroller?.removeEventListener(`scroll`,this.handleEditorScroll),this.editorScroller=e,this.editorScroller?.addEventListener(`scroll`,this.handleEditorScroll,{passive:!0}))}syncPreviewToEditor(){this.lastInteractionSource=`editor`,this.sync(this.editorScroller,this.previewContainer)}syncEditorToPreview(){this.lastInteractionSource=`preview`,this.sync(this.previewContainer,this.editorScroller)}destroy(){this.previewContainer?.removeEventListener(`scroll`,this.handlePreviewScroll),this.editorScroller?.removeEventListener(`scroll`,this.handleEditorScroll),this.editorScroller=null,clearTimeout(this.editorScrollIdleTimer),this.editorScrollIdleTimer=null,this.pendingSync=null,this.previewBlocks=null,rc(this.previewBlocksWarmId),this.previewBlocksWarmId=null,this.previewBlocksReadyCallbacks=[],this.lockedElements.clear(),this.editorScrollActive=!1,this.lastInteractionSource=`editor`,this.suspendedUntil=0,this.frameId&&=(cancelAnimationFrame(this.frameId),null)}scheduleSync(e,t,{preferApproximateMapping:n=!1}={}){!e||!t||this.lockedElements.has(e)||this.isSuspended()||(this.pendingSync={preferApproximateMapping:n,source:e,target:t},!this.frameId&&(this.frameId=requestAnimationFrame(()=>{if(this.frameId=null,!this.pendingSync)return;let{preferApproximateMapping:e,source:t,target:n}=this.pendingSync;this.pendingSync=null,this.sync(t,n,{preferApproximateMapping:e})})))}invalidatePreviewBlocks(){this.previewBlocks=null,rc(this.previewBlocksWarmId),this.previewBlocksWarmId=null,this.previewBlocksReadyCallbacks=[]}setLargeDocumentMode(e){this.largeDocumentMode=!!e,this.largeDocumentMode||(clearTimeout(this.editorScrollIdleTimer),this.editorScrollIdleTimer=null,this.setEditorScrollActive(!1))}warmPreviewBlocks({onReady:e}={}){if(typeof e==`function`&&(this.previewBlocks?e(this.previewBlocks):this.previewBlocksReadyCallbacks.push(e)),!this.largeDocumentMode){this.previewBlocks||=this.buildPreviewBlocks(),this.flushPreviewBlocksReadyCallbacks();return}this.previewBlocks||this.previewBlocksWarmId!==null||(this.previewBlocksWarmId=nc(()=>{this.previewBlocksWarmId=null,this.previewBlocks=this.buildPreviewBlocks(),this.flushPreviewBlocksReadyCallbacks()}))}realignAfterLayoutChange(){let e=()=>{if(this.lastInteractionSource===`preview`){this.syncEditorToPreview();return}this.syncPreviewToEditor()};if(this.largeDocumentMode&&!this.previewBlocks){this.warmPreviewBlocks({onReady:()=>e()});return}e()}suspendSync(e=250){this.suspendedUntil=performance.now()+e}isSuspended(){return performance.now()<this.suspendedUntil}flushPreviewBlocksReadyCallbacks(){this.previewBlocksReadyCallbacks.length!==0&&this.previewBlocksReadyCallbacks.splice(0).forEach(e=>{try{e(this.previewBlocks??[])}catch(e){console.warn(`[scroll-sync] Preview block callback failed:`,e)}})}setEditorScrollActive(e){this.editorScrollActive!==e&&(this.editorScrollActive=e,this.onEditorScrollActivityChange?.(e))}scheduleEditorScrollIdle(){clearTimeout(this.editorScrollIdleTimer),this.editorScrollIdleTimer=setTimeout(()=>{this.editorScrollIdleTimer=null,this.setEditorScrollActive(!1),this.syncPreviewToEditor()},qs)}sync(e,t,{preferApproximateMapping:n=!1}={}){if(!e||!t||this.lockedElements.has(e)||this.isSuspended())return;if(!n&&e===this.editorScroller&&t===this.previewContainer){let e=this.getPreviewScrollTopForEditorLine();if(e!==null){this.setScrollTop(t,e);return}}if(e===this.previewContainer&&t===this.editorScroller){let e=this.getEditorLineNumberForPreviewScroll();if(e!==null){this.lockedElements.add(t),this.scrollEditorToLine?.(e,Ks),requestAnimationFrame(()=>{this.lockedElements.delete(t)});return}}let r=Xs(e),i=Xs(t),a=r>0?e.scrollTop/r:0,o=i>0?i*a:0;this.setScrollTop(t,o)}setScrollTop(e,t){this.lockedElements.add(e),e.scrollTop=Zs(t),requestAnimationFrame(()=>{this.lockedElements.delete(e)})}getPreviewScrollTopForEditorLine(){if($s(this.editorScroller))return 0;let e=this.getEditorLineNumber?.();if(!Number.isFinite(e))return null;let t=this.getPreviewBlocks();if(t.length===0||!this.previewContainer)return null;let{block:n,index:r}=this.findBlockForLine(t,e),i=this.getPreviewSpan(t,r),a=Math.max(n.end-n.start,1),o=x((e-n.start)/a,0,1),s=Xs(this.previewContainer),c=Qs(this.previewContainer);return x(n.top+i*o-c,0,s)}getEditorLineNumberForPreviewScroll(){if(!this.previewContainer)return null;let e=this.getPreviewBlocks();if(e.length===0)return null;let t=this.previewContainer.scrollTop+Qs(this.previewContainer),{block:n,index:r}=this.findBlockForScrollTop(e,t),i=this.getPreviewSpan(e,r),a=Math.max(n.end-n.start,1),o=i>0?x((t-n.top)/i,0,1):0;return Math.round(n.start+a*o)}getPreviewBlocks(){return this.previewBlocks?this.previewBlocks:!this.previewContainer||!this.previewElement||this.largeDocumentMode?[]:(this.previewBlocks=this.buildPreviewBlocks(),this.previewBlocks)}buildPreviewBlocks(){let e=Array.from(this.previewElement.querySelectorAll(`[data-source-line]`)).map(e=>{let t=Number.parseInt(e.getAttribute(`data-source-line`)||``,10),n=Number.parseInt(e.getAttribute(`data-source-line-end`)||``,10);return Number.isFinite(t)?{element:e,end:Number.isFinite(n)?Math.max(n,t+1):t+1,start:t,top:ec(this.previewContainer,e)}:null}).filter(Boolean).sort((e,t)=>e.top-t.top||e.start-t.start||e.end-t.end),t=e.filter(e=>tc(e.element)),n=t.length>0?t:e;return n.filter((e,t)=>{let r=n[t-1];return!r||Math.abs(r.top-e.top)>1||r.start!==e.start||r.end!==e.end})}findBlockForLine(e,t){let n=null,r=-1;for(let i=0;i<e.length;i+=1){let a=e[i];if(t>=a.start&&t<a.end){if(!n){n=a,r=i;continue}let e=n.end-n.start,t=a.end-a.start;(t<e||t===e&&a.start>=n.start)&&(n=a,r=i)}}if(n)return{block:n,index:r};let i=0;for(let n=0;n<e.length&&!(e[n].start>t);n+=1)i=n;return{block:e[i],index:i}}findBlockForScrollTop(e,t){for(let n=0;n<e.length;n+=1)if(t<this.getPreviewSpan(e,n)+e[n].top)return{block:e[n],index:n};let n=e.length-1;return{block:e[n],index:n}}getPreviewSpan(e,t){if(!this.previewContainer)return 1;let n=e[t],r=e[t+1],i=n.element.getBoundingClientRect().height;if(!r){let e=Xs(this.previewContainer);return Math.max(e-n.top+this.previewContainer.clientHeight,i,1)}return Math.max(r.top-n.top,i,1)}},ac=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>`,oc=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>`,sc=class{constructor({storageKey:e=`collabmd-theme`,onChange:t}){this.storageKey=e,this.onChange=t,this.currentTheme=`dark`}initialize(){this.currentTheme=this.readPreferredTheme(),this.applyTheme(),document.querySelectorAll(`[data-theme-toggle]`).forEach(e=>{e.addEventListener(`click`,()=>this.toggle())})}getTheme(){return this.currentTheme}toggle(){this.currentTheme=this.currentTheme===`dark`?`light`:`dark`,this.persistTheme(),this.applyTheme()}readPreferredTheme(){try{let e=window.localStorage.getItem(this.storageKey);if(e===`light`||e===`dark`)return e}catch{}return window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`}persistTheme(){try{window.localStorage.setItem(this.storageKey,this.currentTheme)}catch{}}applyTheme(){document.documentElement.setAttribute(`data-theme`,this.currentTheme),this.updateToggleIcons(),this.onChange?.(this.currentTheme)}updateToggleIcons(){let e=this.currentTheme===`dark`?`Dark`:`Light`,t=this.currentTheme===`dark`?`light`:`dark`,n=this.currentTheme===`dark`?oc:ac;document.querySelectorAll(`[data-theme-toggle]`).forEach(r=>{let i=r.querySelector(`[data-theme-toggle-icon]`),a=r.querySelector(`[data-theme-toggle-state]`);i?i.innerHTML=n:r.innerHTML=n,a&&(a.textContent=e,a.dataset.theme=this.currentTheme),r.setAttribute(`aria-label`,`Theme: ${e}. Switch to ${t} mode`),r.setAttribute(`title`,`Theme: ${e}. Switch to ${t} mode`)})}},cc=class{constructor(e){this.container=e}show(e,t=3e3){if(!this.container)return null;let n=typeof t==`number`?{duration:t}:{...t??{}},r=Number(n.duration)>0?Number(n.duration):0,i=document.createElement(`div`);i.className=`toast`;let a=document.createElement(`span`);a.className=`toast__message`,a.textContent=e,i.appendChild(a);let o=()=>{!i.isConnected||i.classList.contains(`leaving`)||(i.classList.add(`leaving`),i.addEventListener(`animationend`,()=>i.remove(),{once:!0}))};if(n.actionLabel&&typeof n.onAction==`function`){let e=document.createElement(`button`);e.className=`toast__action`,e.type=`button`,e.textContent=n.actionLabel,e.addEventListener(`click`,()=>{n.onAction(),n.closeOnAction!==!1&&o()}),i.appendChild(e)}if(n.dismissible){let e=document.createElement(`button`);e.className=`toast__dismiss`,e.type=`button`,e.setAttribute(`aria-label`,`Dismiss notification`),e.textContent=`Close`,e.addEventListener(`click`,o),i.appendChild(e)}return this.container.appendChild(i),r>0&&setTimeout(o,r),i}},lc=16/9,uc=240,dc=720,fc=180;function pc(e){return Math.max(fc,Math.min(dc,Math.ceil(e||uc)))}var mc=class{constructor({previewElement:e}){this.previewElement=e,this.embedEntries=new Map,this.overlayRoot=null}destroy(){this.embedEntries.forEach(e=>{e.hydrateFrameId&&=(cancelAnimationFrame(e.hydrateFrameId),null),e.wrapper?.remove(),e.placeholder=null}),this.embedEntries.clear(),this.overlayRoot?.remove(),this.overlayRoot=null}detachForCommit(){this.embedEntries.forEach(e=>{e.placeholder=null})}reconcileEmbeds(e=this.previewElement){if(this.previewElement=e,!e)return;let t=Array.from(e.querySelectorAll(`.video-embed-placeholder[data-video-embed-key]`)).map(e=>({filePath:e.dataset.videoEmbedSource,key:e.dataset.videoEmbedKey,label:e.dataset.videoEmbedLabel||`Embedded video`,placeholder:e,source:e.dataset.videoEmbedSource||``,kind:e.dataset.videoEmbedKind||``,url:e.dataset.videoEmbedUrl||``,mimeType:e.dataset.videoEmbedMimeType||``})),{nextEntries:n,removedEntries:r}=jo(this.embedEntries,t);r.forEach(e=>this._destroyEntry(e)),this.embedEntries=n,this.embedEntries.forEach(e=>{e.aspectRatio=e.aspectRatio||lc,e.kind=e.placeholder?.dataset.videoEmbedKind||e.kind,e.label=e.placeholder?.dataset.videoEmbedLabel||e.label,e.mimeType=e.placeholder?.dataset.videoEmbedMimeType||e.mimeType,e.source=e.placeholder?.dataset.videoEmbedSource||e.source,e.url=e.placeholder?.dataset.videoEmbedUrl||e.url,e.wrapper||this._createEmbed(e),this._attachWrapper(e)}),this.syncLayout(),this.embedEntries.size===0&&(this.overlayRoot?.remove(),this.overlayRoot=null)}syncLayout(){this.embedEntries.forEach(e=>{e.wrapper&&this._syncEntryLayout(e)})}_destroyEntry(e){e.hydrateFrameId&&=(cancelAnimationFrame(e.hydrateFrameId),null),e.wrapper?.remove(),e.placeholder=null}_createEmbed(e){let t=document.createElement(`div`);if(t.className=`video-embed video-embed-shell diagram-preview-shell is-${e.kind}`,e.kind===`youtube`){let n=document.createElement(`div`);n.className=`video-embed-frame video-embed-frame-youtube`;let r=document.createElement(`iframe`);r.className=`video-embed-iframe`,r.title=e.label||`Embedded YouTube video`,r.referrerPolicy=`strict-origin-when-cross-origin`,r.allow=`accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share`,r.allowFullscreen=!0,n.appendChild(r),t.appendChild(n),e.mediaElement=r}else{let n=document.createElement(`video`);n.className=`video-embed-player`,n.controls=!0,n.preload=`metadata`,n.playsInline=!0,e.label&&(n.title=e.label,n.setAttribute(`aria-label`,e.label));let r=document.createElement(`source`);r.src=e.url,e.mimeType&&(r.type=e.mimeType),n.appendChild(r),n.addEventListener(`loadedmetadata`,()=>{Number.isFinite(n.videoWidth)&&Number.isFinite(n.videoHeight)&&n.videoWidth>0&&n.videoHeight>0&&(e.aspectRatio=n.videoWidth/n.videoHeight,this._syncEntryLayout(e))}),t.appendChild(n),e.mediaElement=n}e.wrapper=t}_attachWrapper(e){let t=e.placeholder?.isConnected?e.placeholder:this.previewElement?.querySelector(`.video-embed-placeholder[data-video-embed-key="${e.key}"]`);if(!t)return;e.placeholder=t,t.classList.add(`is-hydrated`),t.dataset.videoEmbedHydrated=`true`,t.style.pointerEvents=`none`;let n=this._ensureOverlayRoot();e.wrapper?.parentElement!==n&&n.appendChild(e.wrapper)}_syncEntryLayout(e){let t=e.placeholder?.isConnected?e.placeholder:this.previewElement?.querySelector(`.video-embed-placeholder[data-video-embed-key="${e.key}"]`);if(!t||!e.wrapper)return;e.placeholder=t;let n=t.offsetWidth||t.clientWidth||0;if(n<=0&&e.inlineHeightPx)return;let r=pc(n>0?n/(e.aspectRatio||lc):e.inlineHeightPx);e.inlineHeightPx=r,hc(t,`height`,`${r}px`),hc(e.wrapper,`position`,`absolute`),hc(e.wrapper,`top`,`${t.offsetTop}px`),hc(e.wrapper,`left`,`${t.offsetLeft}px`),hc(e.wrapper,`width`,`${t.offsetWidth}px`),hc(e.wrapper,`height`,`${r}px`),hc(e.wrapper,`margin`,`0`),hc(e.wrapper,`pointerEvents`,`auto`),this._hydrateEntryMedia(e)}_ensureOverlayRoot(){let e=this.previewElement?.querySelector(`[data-video-overlay-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.videoOverlayRoot=`true`,e.className=`video-embed-overlay-root`,this.previewElement?.appendChild(e)),this.overlayRoot=e,e}_hydrateEntryMedia(e){if(e.kind!==`youtube`)return;let t=e.mediaElement;t instanceof HTMLIFrameElement&&(!e.url||t.getAttribute(`src`)===e.url||e.wrapper?.offsetWidth<=0||e.wrapper?.offsetHeight<=0||(e.hydrateFrameId||=requestAnimationFrame(()=>{if(e.hydrateFrameId=null,!e.url||t.getAttribute(`src`)===e.url)return;let n=Math.round(e.wrapper?.offsetWidth||0),r=Math.round(e.wrapper?.offsetHeight||0);n<=0||r<=0||(t.width=String(n),t.height=String(r),t.src=e.url)})))}};function hc(e,t,n){!e||e.style[t]===n||(e.style[t]=n)}var Q=1,gc=6,_c=.25,vc=2,yc=6;function bc(e){let t=Number(e);return Number.isFinite(t)?Math.min(gc,Math.max(Q,Math.round(t*100)/100)):Q}function xc(e,{contentSize:t=0,scale:n=1,viewportSize:r=0}={}){let i=Number(e),a=Number(t),o=Number(n),s=Number(r);if(!Number.isFinite(i)||!Number.isFinite(a)||!Number.isFinite(o)||!Number.isFinite(s))return 0;let c=(a*o-s)/2;return c<=0?0:Math.min(Math.max(i,-c),c)}var Sc=class{constructor({previewElement:e,documentRef:t=document,windowRef:n=window}){this.previewElement=e,this.document=t,this.window=n,this.overlayRoot=null,this.viewport=null,this.imageElement=null,this.zoomLabel=null,this.titleElement=null,this.isOpen=!1,this.scale=Q,this.offsetX=0,this.offsetY=0,this.activePointerId=null,this.dragStartX=0,this.dragStartY=0,this.dragOriginX=0,this.dragOriginY=0,this.didDrag=!1,this.resetButton=null,this.handlePreviewClick=e=>{let t=e.target;if(!(t instanceof this.window.Element))return;let n=t.closest(`img`);!n||!this.previewElement?.contains(n)||n.closest(`[data-video-overlay-root="true"], [data-excalidraw-overlay-root="true"]`)||(e.preventDefault(),e.stopImmediatePropagation?.(),this.openFromImage(n))},this.handleKeyDown=e=>{if(this.isOpen){if(e.key===`Escape`){e.preventDefault(),this.close();return}if(e.key===`+`||e.key===`=`){e.preventDefault(),this.zoomBy(_c);return}if(e.key===`-`){e.preventDefault(),this.zoomBy(-_c);return}e.key===`0`&&(e.preventDefault(),this.resetView())}},this.handleWindowResize=()=>{this.isOpen&&(this.clampOffsets(),this.syncTransform())},this.previewElement?.addEventListener(`click`,this.handlePreviewClick),this.document.addEventListener(`keydown`,this.handleKeyDown),this.window.addEventListener(`resize`,this.handleWindowResize)}destroy(){this.previewElement?.removeEventListener(`click`,this.handlePreviewClick),this.document.removeEventListener(`keydown`,this.handleKeyDown),this.window.removeEventListener(`resize`,this.handleWindowResize),this.close(),this.overlayRoot?.remove(),this.overlayRoot=null,this.viewport=null,this.imageElement=null,this.zoomLabel=null,this.titleElement=null,this.resetButton=null}openFromImage(e){let t=e?.currentSrc||e?.getAttribute?.(`src`)||``;return t?(this.ensureOverlayRoot(),this.resetView(),this.titleElement.textContent=e.getAttribute(`alt`)||`Image preview`,this.imageElement.src=t,this.imageElement.alt=e.getAttribute(`alt`)||``,this.overlayRoot.hidden=!1,this.isOpen=!0,this.document.body.classList.add(`image-lightbox-open`),this.syncTransform(),this.overlayRoot.focus?.(),!0):!1}close(){!this.isOpen&&!this.overlayRoot||(this.activePointerId=null,this.didDrag=!1,this.viewport?.classList?.remove(`is-dragging`),this.overlayRoot&&(this.overlayRoot.hidden=!0),this.isOpen=!1,this.document.body.classList.remove(`image-lightbox-open`))}resetView(){this.scale=Q,this.offsetX=0,this.offsetY=0,this.syncTransform()}zoomBy(e){this.setScale(this.scale+e)}setScale(e){this.scale=bc(e),this.clampOffsets(),this.syncTransform()}clampOffsets(){if(!this.viewport||!this.imageElement){this.offsetX=0,this.offsetY=0;return}this.offsetX=xc(this.offsetX,{contentSize:this.imageElement.offsetWidth||0,scale:this.scale,viewportSize:this.viewport.clientWidth||0}),this.offsetY=xc(this.offsetY,{contentSize:this.imageElement.offsetHeight||0,scale:this.scale,viewportSize:this.viewport.clientHeight||0})}syncTransform(){this.imageElement&&(this.imageElement.style.transform=`translate3d(${this.offsetX}px, ${this.offsetY}px, 0) scale(${this.scale})`,this.imageElement.style.cursor=this.scale>Q?`grab`:`zoom-in`,this.zoomLabel&&(this.zoomLabel.textContent=`${Math.round(this.scale*100)}%`),this.resetButton&&(this.resetButton.disabled=this.scale<=Q&&this.offsetX===0&&this.offsetY===0))}ensureOverlayRoot(){if(this.overlayRoot?.isConnected&&this.overlayRoot.parentElement===this.document.body)return this.overlayRoot;let e=this.document.createElement(`div`);e.className=`image-lightbox-root`,e.dataset.imageLightboxRoot=`true`,e.hidden=!0,e.tabIndex=-1;let t=this.document.createElement(`button`);t.className=`image-lightbox-backdrop`,t.type=`button`,t.setAttribute(`aria-label`,`Close image preview`),t.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.close()});let n=this.document.createElement(`div`);n.className=`image-lightbox-shell`,n.setAttribute(`role`,`dialog`),n.setAttribute(`aria-modal`,`true`),n.setAttribute(`aria-label`,`Image preview`),n.addEventListener(`click`,e=>e.stopPropagation()),n.addEventListener(`pointerdown`,e=>e.stopPropagation());let r=this.document.createElement(`div`);r.className=`image-lightbox-toolbar`;let i=this.document.createElement(`div`);i.className=`image-lightbox-title`,i.textContent=`Image preview`;let a=this.document.createElement(`div`);a.className=`image-lightbox-controls`;let o=this.document.createElement(`span`);o.className=`image-lightbox-zoom-label`,o.textContent=`100%`;let s=this.createControlButton(`Reset`,`Reset zoom and position`,()=>this.resetView()),c=this.createControlButton(`Close`,`Close image preview`,()=>this.close());a.append(o,s,c),r.append(i,a);let l=this.document.createElement(`div`);l.className=`image-lightbox-viewport`;let u=this.document.createElement(`img`);u.className=`image-lightbox-image`,u.alt=``,u.addEventListener(`load`,()=>{this.clampOffsets(),this.syncTransform()}),l.addEventListener(`wheel`,e=>{this.isOpen&&(e.preventDefault(),this.zoomBy(e.deltaY<0?_c:-_c))},{passive:!1}),l.addEventListener(`pointerdown`,e=>{!this.isOpen||this.scale<=Q||e.button!==0||(this.activePointerId=e.pointerId,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.dragOriginX=this.offsetX,this.dragOriginY=this.offsetY,this.didDrag=!1,l.classList.add(`is-dragging`),l.setPointerCapture?.(e.pointerId),e.preventDefault())}),l.addEventListener(`pointermove`,e=>{!this.isOpen||this.activePointerId!==e.pointerId||(!this.didDrag&&(Math.abs(e.clientX-this.dragStartX)>=yc||Math.abs(e.clientY-this.dragStartY)>=yc)&&(this.didDrag=!0),this.offsetX=this.dragOriginX+(e.clientX-this.dragStartX),this.offsetY=this.dragOriginY+(e.clientY-this.dragStartY),this.clampOffsets(),this.syncTransform())});let d=e=>{this.activePointerId===e.pointerId&&(this.activePointerId=null,l.classList.remove(`is-dragging`),l.releasePointerCapture?.(e.pointerId),this.imageElement.style.cursor=this.scale>Q?`grab`:`zoom-in`)};return l.addEventListener(`pointerup`,d),l.addEventListener(`pointercancel`,d),u.addEventListener(`click`,e=>{if(this.isOpen){if(e.preventDefault(),e.stopPropagation(),this.didDrag){this.didDrag=!1;return}this.scale<=Q&&this.setScale(vc)}}),l.appendChild(u),n.append(r,l),e.append(t,n),this.document.body.appendChild(e),this.overlayRoot=e,this.viewport=l,this.imageElement=u,this.zoomLabel=o,this.titleElement=i,this.resetButton=s,this.syncTransform(),e}createControlButton(e,t,n,{className:r=``}={}){let i=this.document.createElement(`button`);return i.className=`image-lightbox-btn ${r}`.trim(),i.type=`button`,i.setAttribute(`aria-label`,t),i.textContent=e,i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n(e)}),i}},Cc=globalThis,wc=e=>e,Tc=Cc.trustedTypes,Ec=Tc?Tc.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,Dc=`$lit$`,Oc=`lit$${Math.random().toFixed(9).slice(2)}$`,kc=`?`+Oc,Ac=`<${kc}>`,jc=document,Mc=()=>jc.createComment(``),Nc=e=>e===null||typeof e!=`object`&&typeof e!=`function`,Pc=Array.isArray,Fc=e=>Pc(e)||typeof e?.[Symbol.iterator]==`function`,Ic=`[
|
|
768
|
-
\f\r]`,
|
|
767
|
+
`}},Js=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onMeasureEditor:t,onViewRequest:n=null}){this.mobileBreakpointQuery=e,this.onMeasureEditor=t,this.onViewRequest=n,this.preferredView=`split`,this.mobileShowsEditor=!this.isMobileViewport(),this.currentView=this.mobileShowsEditor?this.preferredView:`preview`,this.editorLayout=document.getElementById(`editorLayout`),this.editorPane=document.getElementById(`editorPane`),this.previewPane=document.getElementById(`previewPane`),this.mobileToggleButton=document.getElementById(`mobileViewToggle`),this.resizer=document.getElementById(`resizer`),this.viewButtons=Array.from(document.querySelectorAll(`.view-btn`))}isMobileViewport(){return this.mobileBreakpointQuery.matches}initialize(){this.viewButtons.forEach(e=>{e.addEventListener(`click`,()=>{this.onViewRequest?.(e.dataset.view)!==!1&&this.setView(e.dataset.view)})}),this.mobileToggleButton?.addEventListener(`click`,()=>this.toggleMobileView()),this.initializeResizer(),this.restorePreferredView()}primeView(e){if(e){if(this.isMobileViewport()){this.mobileShowsEditor=e!==`preview`;return}this.preferredView=e}}reset(){this.restorePreferredView(),this.editorPane&&(this.editorPane.style.flex=``),this.previewPane&&(this.previewPane.style.flex=``),this.updateResizerValue()}restorePreferredView(){let e=this.isMobileViewport()?this.mobileShowsEditor?`split`:`preview`:this.preferredView;this.applyView(e),this.updateMobileToggleButton(this.mobileShowsEditor?`Preview`:`Editor`)}applyView(e){this.currentView=e,this.editorLayout?.setAttribute(`data-view`,e),this.syncViewButtons()}setView(e,{persist:t=!0}={}){e&&(t&&(this.preferredView=e),this.applyView(e),(e===`split`||e===`editor`)&&this.scheduleEditorMeasure())}toggleMobileView(){let e=!this.mobileShowsEditor,t=e?`split`:`preview`;this.onViewRequest?.(t)!==!1&&(this.mobileShowsEditor=e,this.applyView(t),this.updateMobileToggleButton(this.mobileShowsEditor?`Preview`:`Editor`),this.mobileShowsEditor&&this.scheduleEditorMeasure())}scheduleEditorMeasure(){this.onMeasureEditor&&setTimeout(()=>this.onMeasureEditor(),50)}updateMobileToggleButton(e){this.mobileToggleButton&&(this.mobileToggleButton.innerHTML=`${e===`Editor`?`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="8" y1="8" x2="16" y2="8"/><line x1="8" y1="12" x2="14" y2="12"/><line x1="8" y1="16" x2="12" y2="16"/></svg>`:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>`}<span class="ui-toolbar-button-label">${e}</span>`)}syncViewButtons(){this.viewButtons.forEach(e=>{let t=e.dataset.view===this.currentView;e.classList.toggle(`active`,t),e.setAttribute(`aria-pressed`,String(t))})}updateResizerValue(){if(!this.resizer||!this.editorLayout||!this.editorPane)return;let e=this.editorLayout.offsetWidth;if(!Number.isFinite(e)||e<=0)return;let t=Math.round(this.editorPane.offsetWidth/e*100);this.resizer.setAttribute(`aria-valuenow`,String(Math.max(20,Math.min(80,t))))}applyEditorPaneWidth(e){if(!this.editorLayout||!this.editorPane||!this.previewPane)return;let t=this.editorLayout.offsetWidth;if(!Number.isFinite(t)||t<=0)return;let n=Math.max(200,Math.min(t-200,e))/t*100;this.editorPane.style.flex=`0 0 ${n}%`,this.previewPane.style.flex=`1`,this.updateResizerValue()}initializeResizer(){if(!this.resizer||!this.editorLayout||!this.editorPane||!this.previewPane)return;let e=!1,t=0,n=0;this.resizer.addEventListener(`mousedown`,r=>{e=!0,t=r.clientX,n=this.editorPane.offsetWidth,this.resizer.classList.add(`dragging`),document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`,r.preventDefault()}),document.addEventListener(`mousemove`,r=>{if(!e)return;let i=r.clientX-t;this.applyEditorPaneWidth(n+i)}),document.addEventListener(`mouseup`,()=>{e&&(e=!1,this.resizer.classList.remove(`dragging`),document.body.style.cursor=``,document.body.style.userSelect=``,this.scheduleEditorMeasure())}),this.resizer.addEventListener(`keydown`,e=>{let t=this.editorLayout.offsetWidth;if(!Number.isFinite(t)||t<=0)return;let n=Math.max(24,Math.round(t*.05));if(e.key===`ArrowLeft`){e.preventDefault(),this.applyEditorPaneWidth(this.editorPane.offsetWidth-n),this.scheduleEditorMeasure();return}if(e.key===`ArrowRight`){e.preventDefault(),this.applyEditorPaneWidth(this.editorPane.offsetWidth+n),this.scheduleEditorMeasure();return}if(e.key===`Home`){e.preventDefault(),this.applyEditorPaneWidth(t*.2),this.scheduleEditorMeasure();return}e.key===`End`&&(e.preventDefault(),this.applyEditorPaneWidth(t*.8),this.scheduleEditorMeasure())}),this.updateResizerValue()}},Ys=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onNavigateToHeading:t,onWillOpen:n}={}){this.outlineOpen=!1,this.activeHeadingFrame=null,this.activeHeadingId=null,this.headings=[],this.pinnedHeadingId=null,this.onNavigateToHeading=t,this.onWillOpen=n,this.panel=document.getElementById(`outlinePanel`),this.navigation=document.getElementById(`outlineNav`),this.previewContainer=document.getElementById(`previewContainer`),this.toggleButton=document.getElementById(`outlineToggle`),this.mobileBreakpointQuery=e,this.handlePreviewScroll=()=>this.scheduleActiveHeadingUpdate(),this.handleDocumentPointerDown=e=>{if(!this.outlineOpen)return;let t=e.target;t instanceof Node&&(this.panel?.contains(t)||this.toggleButton?.contains(t))||this.close()}}initialize(){this.toggleButton?.addEventListener(`click`,()=>this.toggle()),document.addEventListener(`pointerdown`,this.handleDocumentPointerDown)}toggle(){this.setOpenState(!this.outlineOpen)}close(){this.setOpenState(!1)}setOpenState(e){if(e&&!this.outlineOpen&&this.onWillOpen?.(),this.outlineOpen=e,this.panel?.classList.toggle(`hidden`,!this.outlineOpen),this.toggleButton?.classList.toggle(`active`,this.outlineOpen),this.outlineOpen){this.refresh();return}this.cleanup()}refresh(){if(!this.navigation)return;if(!this.outlineOpen){this.cleanup();return}let e=document.getElementById(`previewContent`)?.querySelectorAll(`h1, h2, h3, h4, h5, h6`)??[];if(e.length===0){this.navigation.innerHTML=`<div class="outline-empty">No headings found</div>`,this.cleanup();return}let t=Array.from(e).map((e,t)=>(e.id||=`heading-${t}-${e.textContent.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,40)}`,{id:e.id,level:Number.parseInt(e.tagName[1],10),sourceLine:Number.parseInt(e.getAttribute(`data-source-line`)||``,10),text:e.textContent.trim()}));this.navigation.innerHTML=t.map(e=>`<button class="outline-item" data-level="${e.level}" data-target="${e.id}"${Number.isFinite(e.sourceLine)?` data-source-line="${e.sourceLine}"`:``} title="${e.text.replace(/"/g,`"`)}">${e.text}</button>`).join(``),this.navigation.querySelectorAll(`.outline-item`).forEach(e=>{e.addEventListener(`click`,()=>{let t=document.getElementById(e.dataset.target);this.pinnedHeadingId=e.dataset.target,this.notifyHeadingNavigation(t,e.dataset.target),this.scrollHeadingIntoView(t,{behavior:`auto`}),this.setActiveItem(e.dataset.target,{behavior:`auto`}),this.mobileBreakpointQuery.matches&&this.close()})}),this.observeHeadings(Array.from(e))}cleanup(){this.activeHeadingFrame&&=(cancelAnimationFrame(this.activeHeadingFrame),null),this.previewContainer?.removeEventListener(`scroll`,this.handlePreviewScroll),this.headings=[],this.pinnedHeadingId=null}setActiveItem(e,{scrollIntoView:t=!0,behavior:n=`smooth`}={}){this.activeHeadingId=e,this.navigation?.querySelectorAll(`.outline-item`).forEach(t=>{t.classList.toggle(`active`,t.dataset.target===e)}),t&&this.navigation?.querySelector(`.outline-item.active`)?.scrollIntoView({behavior:n,block:`nearest`})}observeHeadings(e){this.cleanup(),!(!this.previewContainer||e.length===0)&&(this.headings=e,this.previewContainer.addEventListener(`scroll`,this.handlePreviewScroll,{passive:!0}),this.updateActiveHeading())}scheduleActiveHeadingUpdate(){this.activeHeadingFrame||=requestAnimationFrame(()=>{this.activeHeadingFrame=null,this.updateActiveHeading()})}updateActiveHeading(){if(!this.previewContainer||this.headings.length===0)return;let e=this.getPinnedHeading();if(e&&this.shouldKeepPinnedHeadingActive(e)){this.setActiveItem(e.id,{behavior:`auto`,scrollIntoView:!0});return}this.pinnedHeadingId=null;let t=this.previewContainer.scrollTop,n=this.headings[0];for(let e of this.headings){if(this.getHeadingScrollTop(e)>t)break;n=e}this.setActiveItem(n.id,{behavior:`auto`,scrollIntoView:!0})}getHeadingScrollTop(e){if(!this.previewContainer)return 0;let t=this.previewContainer.getBoundingClientRect(),n=e.getBoundingClientRect();return this.previewContainer.scrollTop+(n.top-t.top)}getPinnedHeading(){return this.pinnedHeadingId?this.headings.find(e=>e.id===this.pinnedHeadingId)??null:null}shouldKeepPinnedHeadingActive(e){if(!this.previewContainer||!e?.isConnected)return!1;let t=this.getHeadingScrollTop(e)-this.previewContainer.scrollTop,n=t+e.getBoundingClientRect().height,r=this.previewContainer.clientHeight*.45;return n>-48&&t<r}notifyHeadingNavigation(e,t){if(!e)return;let n=Number.parseInt(e.getAttribute(`data-source-line`)||``,10);this.onNavigateToHeading?.({headingId:t,sourceLine:Number.isFinite(n)?n:null})}scrollHeadingIntoView(e,{behavior:t=`smooth`}={}){if(!e||!this.previewContainer)return;let n=this.previewContainer.getBoundingClientRect(),r=e.getBoundingClientRect(),i=this.previewContainer.scrollTop+(r.top-n.top);this.previewContainer.scrollTo({behavior:t,top:Math.max(i,0)})}},Xs=.35,Zs=120,Qs=12,$s=2;function ec(e){return Math.max(e.scrollHeight-e.clientHeight,0)}function tc(e){return Math.max(e,0)}function nc(e){return Math.max(e.clientHeight*Xs,Qs)}function rc(e){return(e?.scrollTop??0)<=$s}function ic(e,t){let n=e.getBoundingClientRect();return t.getBoundingClientRect().top-n.top+e.scrollTop}function ac(e){return!e.querySelector(`[data-source-line]`)}function oc(e){return typeof window.requestIdleCallback==`function`?window.requestIdleCallback(e,{timeout:500}):window.setTimeout(()=>{e({didTimeout:!1,timeRemaining:()=>0})},1)}function sc(e){if(e!==null){if(typeof window.cancelIdleCallback==`function`){window.cancelIdleCallback(e);return}window.clearTimeout(e)}}var cc=class{constructor({getEditorLineNumber:e,onEditorScrollActivityChange:t,previewContainer:n,previewElement:r,scrollEditorToLine:i}){this.getEditorLineNumber=e,this.onEditorScrollActivityChange=t,this.previewContainer=n,this.previewElement=r,this.scrollEditorToLine=i,this.editorScroller=null,this.editorScrollActive=!1,this.editorScrollIdleTimer=null,this.lockedElements=new Set,this.pendingSync=null,this.frameId=null,this.previewBlocks=null,this.previewBlocksWarmId=null,this.previewBlocksReadyCallbacks=[],this.largeDocumentMode=!1,this.lastInteractionSource=`editor`,this.suspendedUntil=0,this.handleEditorScroll=()=>{if(!(!this.editorScroller||this.lockedElements.has(this.editorScroller)||this.isSuspended())){if(this.lastInteractionSource=`editor`,this.largeDocumentMode){this.setEditorScrollActive(!0),this.scheduleEditorScrollIdle(),this.scheduleSync(this.editorScroller,this.previewContainer,{preferApproximateMapping:!0});return}this.scheduleSync(this.editorScroller,this.previewContainer)}},this.handlePreviewScroll=()=>{!this.previewContainer||this.lockedElements.has(this.previewContainer)||this.isSuspended()||(this.lastInteractionSource=`preview`,this.scheduleSync(this.previewContainer,this.editorScroller))}}initialize(){this.previewContainer?.addEventListener(`scroll`,this.handlePreviewScroll,{passive:!0})}attachEditorScroller(e){this.editorScroller!==e&&(this.editorScroller?.removeEventListener(`scroll`,this.handleEditorScroll),this.editorScroller=e,this.editorScroller?.addEventListener(`scroll`,this.handleEditorScroll,{passive:!0}))}syncPreviewToEditor(){this.lastInteractionSource=`editor`,this.sync(this.editorScroller,this.previewContainer)}syncEditorToPreview(){this.lastInteractionSource=`preview`,this.sync(this.previewContainer,this.editorScroller)}destroy(){this.previewContainer?.removeEventListener(`scroll`,this.handlePreviewScroll),this.editorScroller?.removeEventListener(`scroll`,this.handleEditorScroll),this.editorScroller=null,clearTimeout(this.editorScrollIdleTimer),this.editorScrollIdleTimer=null,this.pendingSync=null,this.previewBlocks=null,sc(this.previewBlocksWarmId),this.previewBlocksWarmId=null,this.previewBlocksReadyCallbacks=[],this.lockedElements.clear(),this.editorScrollActive=!1,this.lastInteractionSource=`editor`,this.suspendedUntil=0,this.frameId&&=(cancelAnimationFrame(this.frameId),null)}scheduleSync(e,t,{preferApproximateMapping:n=!1}={}){!e||!t||this.lockedElements.has(e)||this.isSuspended()||(this.pendingSync={preferApproximateMapping:n,source:e,target:t},!this.frameId&&(this.frameId=requestAnimationFrame(()=>{if(this.frameId=null,!this.pendingSync)return;let{preferApproximateMapping:e,source:t,target:n}=this.pendingSync;this.pendingSync=null,this.sync(t,n,{preferApproximateMapping:e})})))}invalidatePreviewBlocks(){this.previewBlocks=null,sc(this.previewBlocksWarmId),this.previewBlocksWarmId=null,this.previewBlocksReadyCallbacks=[]}setLargeDocumentMode(e){this.largeDocumentMode=!!e,this.largeDocumentMode||(clearTimeout(this.editorScrollIdleTimer),this.editorScrollIdleTimer=null,this.setEditorScrollActive(!1))}warmPreviewBlocks({onReady:e}={}){if(typeof e==`function`&&(this.previewBlocks?e(this.previewBlocks):this.previewBlocksReadyCallbacks.push(e)),!this.largeDocumentMode){this.previewBlocks||=this.buildPreviewBlocks(),this.flushPreviewBlocksReadyCallbacks();return}this.previewBlocks||this.previewBlocksWarmId!==null||(this.previewBlocksWarmId=oc(()=>{this.previewBlocksWarmId=null,this.previewBlocks=this.buildPreviewBlocks(),this.flushPreviewBlocksReadyCallbacks()}))}realignAfterLayoutChange(){let e=()=>{if(this.lastInteractionSource===`preview`){this.syncEditorToPreview();return}this.syncPreviewToEditor()};if(this.largeDocumentMode&&!this.previewBlocks){this.warmPreviewBlocks({onReady:()=>e()});return}e()}suspendSync(e=250){this.suspendedUntil=performance.now()+e}isSuspended(){return performance.now()<this.suspendedUntil}flushPreviewBlocksReadyCallbacks(){this.previewBlocksReadyCallbacks.length!==0&&this.previewBlocksReadyCallbacks.splice(0).forEach(e=>{try{e(this.previewBlocks??[])}catch(e){console.warn(`[scroll-sync] Preview block callback failed:`,e)}})}setEditorScrollActive(e){this.editorScrollActive!==e&&(this.editorScrollActive=e,this.onEditorScrollActivityChange?.(e))}scheduleEditorScrollIdle(){clearTimeout(this.editorScrollIdleTimer),this.editorScrollIdleTimer=setTimeout(()=>{this.editorScrollIdleTimer=null,this.setEditorScrollActive(!1),this.syncPreviewToEditor()},Zs)}sync(e,t,{preferApproximateMapping:n=!1}={}){if(!e||!t||this.lockedElements.has(e)||this.isSuspended())return;if(!n&&e===this.editorScroller&&t===this.previewContainer){let e=this.getPreviewScrollTopForEditorLine();if(e!==null){this.setScrollTop(t,e);return}}if(e===this.previewContainer&&t===this.editorScroller){let e=this.getEditorLineNumberForPreviewScroll();if(e!==null){this.lockedElements.add(t),this.scrollEditorToLine?.(e,Xs),requestAnimationFrame(()=>{this.lockedElements.delete(t)});return}}let r=ec(e),i=ec(t),a=r>0?e.scrollTop/r:0,o=i>0?i*a:0;this.setScrollTop(t,o)}setScrollTop(e,t){this.lockedElements.add(e),e.scrollTop=tc(t),requestAnimationFrame(()=>{this.lockedElements.delete(e)})}getPreviewScrollTopForEditorLine(){if(rc(this.editorScroller))return 0;let e=this.getEditorLineNumber?.();if(!Number.isFinite(e))return null;let t=this.getPreviewBlocks();if(t.length===0||!this.previewContainer)return null;let{block:n,index:r}=this.findBlockForLine(t,e),i=this.getPreviewSpan(t,r),a=Math.max(n.end-n.start,1),o=x((e-n.start)/a,0,1),s=ec(this.previewContainer),c=nc(this.previewContainer);return x(n.top+i*o-c,0,s)}getEditorLineNumberForPreviewScroll(){if(!this.previewContainer)return null;let e=this.getPreviewBlocks();if(e.length===0)return null;let t=this.previewContainer.scrollTop+nc(this.previewContainer),{block:n,index:r}=this.findBlockForScrollTop(e,t),i=this.getPreviewSpan(e,r),a=Math.max(n.end-n.start,1),o=i>0?x((t-n.top)/i,0,1):0;return Math.round(n.start+a*o)}getPreviewBlocks(){return this.previewBlocks?this.previewBlocks:!this.previewContainer||!this.previewElement||this.largeDocumentMode?[]:(this.previewBlocks=this.buildPreviewBlocks(),this.previewBlocks)}buildPreviewBlocks(){let e=Array.from(this.previewElement.querySelectorAll(`[data-source-line]`)).map(e=>{let t=Number.parseInt(e.getAttribute(`data-source-line`)||``,10),n=Number.parseInt(e.getAttribute(`data-source-line-end`)||``,10);return Number.isFinite(t)?{element:e,end:Number.isFinite(n)?Math.max(n,t+1):t+1,start:t,top:ic(this.previewContainer,e)}:null}).filter(Boolean).sort((e,t)=>e.top-t.top||e.start-t.start||e.end-t.end),t=e.filter(e=>ac(e.element)),n=t.length>0?t:e;return n.filter((e,t)=>{let r=n[t-1];return!r||Math.abs(r.top-e.top)>1||r.start!==e.start||r.end!==e.end})}findBlockForLine(e,t){let n=null,r=-1;for(let i=0;i<e.length;i+=1){let a=e[i];if(t>=a.start&&t<a.end){if(!n){n=a,r=i;continue}let e=n.end-n.start,t=a.end-a.start;(t<e||t===e&&a.start>=n.start)&&(n=a,r=i)}}if(n)return{block:n,index:r};let i=0;for(let n=0;n<e.length&&!(e[n].start>t);n+=1)i=n;return{block:e[i],index:i}}findBlockForScrollTop(e,t){for(let n=0;n<e.length;n+=1)if(t<this.getPreviewSpan(e,n)+e[n].top)return{block:e[n],index:n};let n=e.length-1;return{block:e[n],index:n}}getPreviewSpan(e,t){if(!this.previewContainer)return 1;let n=e[t],r=e[t+1],i=n.element.getBoundingClientRect().height;if(!r){let e=ec(this.previewContainer);return Math.max(e-n.top+this.previewContainer.clientHeight,i,1)}return Math.max(r.top-n.top,i,1)}},lc=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>`,uc=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>`,dc=class{constructor({storageKey:e=`collabmd-theme`,onChange:t}){this.storageKey=e,this.onChange=t,this.currentTheme=`dark`}initialize(){this.currentTheme=this.readPreferredTheme(),this.applyTheme(),document.querySelectorAll(`[data-theme-toggle]`).forEach(e=>{e.addEventListener(`click`,()=>this.toggle())})}getTheme(){return this.currentTheme}toggle(){this.currentTheme=this.currentTheme===`dark`?`light`:`dark`,this.persistTheme(),this.applyTheme()}readPreferredTheme(){try{let e=window.localStorage.getItem(this.storageKey);if(e===`light`||e===`dark`)return e}catch{}return window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`}persistTheme(){try{window.localStorage.setItem(this.storageKey,this.currentTheme)}catch{}}applyTheme(){document.documentElement.setAttribute(`data-theme`,this.currentTheme),this.updateToggleIcons(),this.onChange?.(this.currentTheme)}updateToggleIcons(){let e=this.currentTheme===`dark`?`Dark`:`Light`,t=this.currentTheme===`dark`?`light`:`dark`,n=this.currentTheme===`dark`?uc:lc;document.querySelectorAll(`[data-theme-toggle]`).forEach(r=>{let i=r.querySelector(`[data-theme-toggle-icon]`),a=r.querySelector(`[data-theme-toggle-state]`);i?i.innerHTML=n:r.innerHTML=n,a&&(a.textContent=e,a.dataset.theme=this.currentTheme),r.setAttribute(`aria-label`,`Theme: ${e}. Switch to ${t} mode`),r.setAttribute(`title`,`Theme: ${e}. Switch to ${t} mode`)})}},fc=class{constructor(e){this.container=e}show(e,t=3e3){if(!this.container)return null;let n=typeof t==`number`?{duration:t}:{...t??{}},r=Number(n.duration)>0?Number(n.duration):0,i=document.createElement(`div`);i.className=`toast`;let a=document.createElement(`span`);a.className=`toast__message`,a.textContent=e,i.appendChild(a);let o=()=>{!i.isConnected||i.classList.contains(`leaving`)||(i.classList.add(`leaving`),i.addEventListener(`animationend`,()=>i.remove(),{once:!0}))};if(n.actionLabel&&typeof n.onAction==`function`){let e=document.createElement(`button`);e.className=`toast__action`,e.type=`button`,e.textContent=n.actionLabel,e.addEventListener(`click`,()=>{n.onAction(),n.closeOnAction!==!1&&o()}),i.appendChild(e)}if(n.dismissible){let e=document.createElement(`button`);e.className=`toast__dismiss`,e.type=`button`,e.setAttribute(`aria-label`,`Dismiss notification`),e.textContent=`Close`,e.addEventListener(`click`,o),i.appendChild(e)}return this.container.appendChild(i),r>0&&setTimeout(o,r),i}},pc=16/9,mc=240,hc=720,gc=180;function _c(e){return Math.max(gc,Math.min(hc,Math.ceil(e||mc)))}var vc=class{constructor({previewElement:e}){this.previewElement=e,this.embedEntries=new Map,this.overlayRoot=null}destroy(){this.embedEntries.forEach(e=>{e.hydrateFrameId&&=(cancelAnimationFrame(e.hydrateFrameId),null),e.wrapper?.remove(),e.placeholder=null}),this.embedEntries.clear(),this.overlayRoot?.remove(),this.overlayRoot=null}detachForCommit(){this.embedEntries.forEach(e=>{e.placeholder=null})}reconcileEmbeds(e=this.previewElement){if(this.previewElement=e,!e)return;let t=Array.from(e.querySelectorAll(`.video-embed-placeholder[data-video-embed-key]`)).map(e=>({filePath:e.dataset.videoEmbedSource,key:e.dataset.videoEmbedKey,label:e.dataset.videoEmbedLabel||`Embedded video`,placeholder:e,source:e.dataset.videoEmbedSource||``,kind:e.dataset.videoEmbedKind||``,url:e.dataset.videoEmbedUrl||``,mimeType:e.dataset.videoEmbedMimeType||``})),{nextEntries:n,removedEntries:r}=Fo(this.embedEntries,t);r.forEach(e=>this._destroyEntry(e)),this.embedEntries=n,this.embedEntries.forEach(e=>{e.aspectRatio=e.aspectRatio||pc,e.kind=e.placeholder?.dataset.videoEmbedKind||e.kind,e.label=e.placeholder?.dataset.videoEmbedLabel||e.label,e.mimeType=e.placeholder?.dataset.videoEmbedMimeType||e.mimeType,e.source=e.placeholder?.dataset.videoEmbedSource||e.source,e.url=e.placeholder?.dataset.videoEmbedUrl||e.url,e.wrapper||this._createEmbed(e),this._attachWrapper(e)}),this.syncLayout(),this.embedEntries.size===0&&(this.overlayRoot?.remove(),this.overlayRoot=null)}syncLayout(){this.embedEntries.forEach(e=>{e.wrapper&&this._syncEntryLayout(e)})}_destroyEntry(e){e.hydrateFrameId&&=(cancelAnimationFrame(e.hydrateFrameId),null),e.wrapper?.remove(),e.placeholder=null}_createEmbed(e){let t=document.createElement(`div`);if(t.className=`video-embed video-embed-shell diagram-preview-shell is-${e.kind}`,e.kind===`youtube`){let n=document.createElement(`div`);n.className=`video-embed-frame video-embed-frame-youtube`;let r=document.createElement(`iframe`);r.className=`video-embed-iframe`,r.title=e.label||`Embedded YouTube video`,r.referrerPolicy=`strict-origin-when-cross-origin`,r.allow=`accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share`,r.allowFullscreen=!0,n.appendChild(r),t.appendChild(n),e.mediaElement=r}else{let n=document.createElement(`video`);n.className=`video-embed-player`,n.controls=!0,n.preload=`metadata`,n.playsInline=!0,e.label&&(n.title=e.label,n.setAttribute(`aria-label`,e.label));let r=document.createElement(`source`);r.src=e.url,e.mimeType&&(r.type=e.mimeType),n.appendChild(r),n.addEventListener(`loadedmetadata`,()=>{Number.isFinite(n.videoWidth)&&Number.isFinite(n.videoHeight)&&n.videoWidth>0&&n.videoHeight>0&&(e.aspectRatio=n.videoWidth/n.videoHeight,this._syncEntryLayout(e))}),t.appendChild(n),e.mediaElement=n}e.wrapper=t}_attachWrapper(e){let t=e.placeholder?.isConnected?e.placeholder:this.previewElement?.querySelector(`.video-embed-placeholder[data-video-embed-key="${e.key}"]`);if(!t)return;e.placeholder=t,t.classList.add(`is-hydrated`),t.dataset.videoEmbedHydrated=`true`,t.style.pointerEvents=`none`;let n=this._ensureOverlayRoot();e.wrapper?.parentElement!==n&&n.appendChild(e.wrapper)}_syncEntryLayout(e){let t=e.placeholder?.isConnected?e.placeholder:this.previewElement?.querySelector(`.video-embed-placeholder[data-video-embed-key="${e.key}"]`);if(!t||!e.wrapper)return;e.placeholder=t;let n=t.offsetWidth||t.clientWidth||0;if(n<=0&&e.inlineHeightPx)return;let r=_c(n>0?n/(e.aspectRatio||pc):e.inlineHeightPx);e.inlineHeightPx=r,yc(t,`height`,`${r}px`),yc(e.wrapper,`position`,`absolute`),yc(e.wrapper,`top`,`${t.offsetTop}px`),yc(e.wrapper,`left`,`${t.offsetLeft}px`),yc(e.wrapper,`width`,`${t.offsetWidth}px`),yc(e.wrapper,`height`,`${r}px`),yc(e.wrapper,`margin`,`0`),yc(e.wrapper,`pointerEvents`,`auto`),this._hydrateEntryMedia(e)}_ensureOverlayRoot(){let e=this.previewElement?.querySelector(`[data-video-overlay-root="true"]`);return e||(e=document.createElement(`div`),e.dataset.videoOverlayRoot=`true`,e.className=`video-embed-overlay-root`,this.previewElement?.appendChild(e)),this.overlayRoot=e,e}_hydrateEntryMedia(e){if(e.kind!==`youtube`)return;let t=e.mediaElement;t instanceof HTMLIFrameElement&&(!e.url||t.getAttribute(`src`)===e.url||e.wrapper?.offsetWidth<=0||e.wrapper?.offsetHeight<=0||(e.hydrateFrameId||=requestAnimationFrame(()=>{if(e.hydrateFrameId=null,!e.url||t.getAttribute(`src`)===e.url)return;let n=Math.round(e.wrapper?.offsetWidth||0),r=Math.round(e.wrapper?.offsetHeight||0);n<=0||r<=0||(t.width=String(n),t.height=String(r),t.src=e.url)})))}};function yc(e,t,n){!e||e.style[t]===n||(e.style[t]=n)}var Q=1,bc=6,xc=.25,Sc=2,Cc=6;function wc(e){let t=Number(e);return Number.isFinite(t)?Math.min(bc,Math.max(Q,Math.round(t*100)/100)):Q}function Tc(e,{contentSize:t=0,scale:n=1,viewportSize:r=0}={}){let i=Number(e),a=Number(t),o=Number(n),s=Number(r);if(!Number.isFinite(i)||!Number.isFinite(a)||!Number.isFinite(o)||!Number.isFinite(s))return 0;let c=(a*o-s)/2;return c<=0?0:Math.min(Math.max(i,-c),c)}var Ec=class{constructor({previewElement:e,documentRef:t=document,windowRef:n=window}){this.previewElement=e,this.document=t,this.window=n,this.overlayRoot=null,this.viewport=null,this.imageElement=null,this.zoomLabel=null,this.titleElement=null,this.isOpen=!1,this.scale=Q,this.offsetX=0,this.offsetY=0,this.activePointerId=null,this.dragStartX=0,this.dragStartY=0,this.dragOriginX=0,this.dragOriginY=0,this.didDrag=!1,this.resetButton=null,this.handlePreviewClick=e=>{let t=e.target;if(!(t instanceof this.window.Element))return;let n=t.closest(`img`);!n||!this.previewElement?.contains(n)||n.closest(`[data-video-overlay-root="true"], [data-excalidraw-overlay-root="true"]`)||(e.preventDefault(),e.stopImmediatePropagation?.(),this.openFromImage(n))},this.handleKeyDown=e=>{if(this.isOpen){if(e.key===`Escape`){e.preventDefault(),this.close();return}if(e.key===`+`||e.key===`=`){e.preventDefault(),this.zoomBy(xc);return}if(e.key===`-`){e.preventDefault(),this.zoomBy(-xc);return}e.key===`0`&&(e.preventDefault(),this.resetView())}},this.handleWindowResize=()=>{this.isOpen&&(this.clampOffsets(),this.syncTransform())},this.previewElement?.addEventListener(`click`,this.handlePreviewClick),this.document.addEventListener(`keydown`,this.handleKeyDown),this.window.addEventListener(`resize`,this.handleWindowResize)}destroy(){this.previewElement?.removeEventListener(`click`,this.handlePreviewClick),this.document.removeEventListener(`keydown`,this.handleKeyDown),this.window.removeEventListener(`resize`,this.handleWindowResize),this.close(),this.overlayRoot?.remove(),this.overlayRoot=null,this.viewport=null,this.imageElement=null,this.zoomLabel=null,this.titleElement=null,this.resetButton=null}openFromImage(e){let t=e?.currentSrc||e?.getAttribute?.(`src`)||``;return t?(this.ensureOverlayRoot(),this.resetView(),this.titleElement.textContent=e.getAttribute(`alt`)||`Image preview`,this.imageElement.src=t,this.imageElement.alt=e.getAttribute(`alt`)||``,this.overlayRoot.hidden=!1,this.isOpen=!0,this.document.body.classList.add(`image-lightbox-open`),this.syncTransform(),this.overlayRoot.focus?.(),!0):!1}close(){!this.isOpen&&!this.overlayRoot||(this.activePointerId=null,this.didDrag=!1,this.viewport?.classList?.remove(`is-dragging`),this.overlayRoot&&(this.overlayRoot.hidden=!0),this.isOpen=!1,this.document.body.classList.remove(`image-lightbox-open`))}resetView(){this.scale=Q,this.offsetX=0,this.offsetY=0,this.syncTransform()}zoomBy(e){this.setScale(this.scale+e)}setScale(e){this.scale=wc(e),this.clampOffsets(),this.syncTransform()}clampOffsets(){if(!this.viewport||!this.imageElement){this.offsetX=0,this.offsetY=0;return}this.offsetX=Tc(this.offsetX,{contentSize:this.imageElement.offsetWidth||0,scale:this.scale,viewportSize:this.viewport.clientWidth||0}),this.offsetY=Tc(this.offsetY,{contentSize:this.imageElement.offsetHeight||0,scale:this.scale,viewportSize:this.viewport.clientHeight||0})}syncTransform(){this.imageElement&&(this.imageElement.style.transform=`translate3d(${this.offsetX}px, ${this.offsetY}px, 0) scale(${this.scale})`,this.imageElement.style.cursor=this.scale>Q?`grab`:`zoom-in`,this.zoomLabel&&(this.zoomLabel.textContent=`${Math.round(this.scale*100)}%`),this.resetButton&&(this.resetButton.disabled=this.scale<=Q&&this.offsetX===0&&this.offsetY===0))}ensureOverlayRoot(){if(this.overlayRoot?.isConnected&&this.overlayRoot.parentElement===this.document.body)return this.overlayRoot;let e=this.document.createElement(`div`);e.className=`image-lightbox-root`,e.dataset.imageLightboxRoot=`true`,e.hidden=!0,e.tabIndex=-1;let t=this.document.createElement(`button`);t.className=`image-lightbox-backdrop`,t.type=`button`,t.setAttribute(`aria-label`,`Close image preview`),t.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),this.close()});let n=this.document.createElement(`div`);n.className=`image-lightbox-shell`,n.setAttribute(`role`,`dialog`),n.setAttribute(`aria-modal`,`true`),n.setAttribute(`aria-label`,`Image preview`),n.addEventListener(`click`,e=>e.stopPropagation()),n.addEventListener(`pointerdown`,e=>e.stopPropagation());let r=this.document.createElement(`div`);r.className=`image-lightbox-toolbar`;let i=this.document.createElement(`div`);i.className=`image-lightbox-title`,i.textContent=`Image preview`;let a=this.document.createElement(`div`);a.className=`image-lightbox-controls`;let o=this.document.createElement(`span`);o.className=`image-lightbox-zoom-label`,o.textContent=`100%`;let s=this.createControlButton(`Reset`,`Reset zoom and position`,()=>this.resetView()),c=this.createControlButton(`Close`,`Close image preview`,()=>this.close());a.append(o,s,c),r.append(i,a);let l=this.document.createElement(`div`);l.className=`image-lightbox-viewport`;let u=this.document.createElement(`img`);u.className=`image-lightbox-image`,u.alt=``,u.addEventListener(`load`,()=>{this.clampOffsets(),this.syncTransform()}),l.addEventListener(`wheel`,e=>{this.isOpen&&(e.preventDefault(),this.zoomBy(e.deltaY<0?xc:-xc))},{passive:!1}),l.addEventListener(`pointerdown`,e=>{!this.isOpen||this.scale<=Q||e.button!==0||(this.activePointerId=e.pointerId,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.dragOriginX=this.offsetX,this.dragOriginY=this.offsetY,this.didDrag=!1,l.classList.add(`is-dragging`),l.setPointerCapture?.(e.pointerId),e.preventDefault())}),l.addEventListener(`pointermove`,e=>{!this.isOpen||this.activePointerId!==e.pointerId||(!this.didDrag&&(Math.abs(e.clientX-this.dragStartX)>=Cc||Math.abs(e.clientY-this.dragStartY)>=Cc)&&(this.didDrag=!0),this.offsetX=this.dragOriginX+(e.clientX-this.dragStartX),this.offsetY=this.dragOriginY+(e.clientY-this.dragStartY),this.clampOffsets(),this.syncTransform())});let d=e=>{this.activePointerId===e.pointerId&&(this.activePointerId=null,l.classList.remove(`is-dragging`),l.releasePointerCapture?.(e.pointerId),this.imageElement.style.cursor=this.scale>Q?`grab`:`zoom-in`)};return l.addEventListener(`pointerup`,d),l.addEventListener(`pointercancel`,d),u.addEventListener(`click`,e=>{if(this.isOpen){if(e.preventDefault(),e.stopPropagation(),this.didDrag){this.didDrag=!1;return}this.scale<=Q&&this.setScale(Sc)}}),l.appendChild(u),n.append(r,l),e.append(t,n),this.document.body.appendChild(e),this.overlayRoot=e,this.viewport=l,this.imageElement=u,this.zoomLabel=o,this.titleElement=i,this.resetButton=s,this.syncTransform(),e}createControlButton(e,t,n,{className:r=``}={}){let i=this.document.createElement(`button`);return i.className=`image-lightbox-btn ${r}`.trim(),i.type=`button`,i.setAttribute(`aria-label`,t),i.textContent=e,i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n(e)}),i}},Dc=globalThis,Oc=e=>e,kc=Dc.trustedTypes,Ac=kc?kc.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,jc=`$lit$`,Mc=`lit$${Math.random().toFixed(9).slice(2)}$`,Nc=`?`+Mc,Pc=`<${Nc}>`,Fc=document,Ic=()=>Fc.createComment(``),Lc=e=>e===null||typeof e!=`object`&&typeof e!=`function`,Rc=Array.isArray,zc=e=>Rc(e)||typeof e?.[Symbol.iterator]==`function`,Bc=`[
|
|
768
|
+
\f\r]`,Vc=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Hc=/-->/g,Uc=/>/g,Wc=RegExp(`>|${Bc}(?:([^\\s"'>=/]+)(${Bc}*=${Bc}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),Gc=/'/g,Kc=/"/g,qc=/^(?:script|style|textarea|title)$/i,Jc=(e=>(t,...n)=>({_$litType$:e,strings:t,values:n}))(1),Yc=Symbol.for(`lit-noChange`),$=Symbol.for(`lit-nothing`),Xc=new WeakMap,Zc=Fc.createTreeWalker(Fc,129);function Qc(e,t){if(!Rc(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return Ac===void 0?t:Ac.createHTML(t)}var $c=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=Vc;for(let t=0;t<n;t++){let n=e[t],s,c,l=-1,u=0;for(;u<n.length&&(o.lastIndex=u,c=o.exec(n),c!==null);)u=o.lastIndex,o===Vc?c[1]===`!--`?o=Hc:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=Wc):(qc.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=Wc):o=Uc:o===Wc?c[0]===`>`?(o=i??Vc,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?Wc:c[3]===`"`?Kc:Gc):o===Kc||o===Gc?o=Wc:o===Hc||o===Uc?o=Vc:(o=Wc,i=void 0);let d=o===Wc&&e[t+1].startsWith(`/>`)?` `:``;a+=o===Vc?n+Pc:l>=0?(r.push(s),n.slice(0,l)+jc+n.slice(l)+Mc+d):n+Mc+(l===-2?t:d)}return[Qc(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},el=class e{constructor({strings:t,_$litType$:n},r){let i;this.parts=[];let a=0,o=0,s=t.length-1,c=this.parts,[l,u]=$c(t,n);if(this.el=e.createElement(l,r),Zc.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=Zc.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(jc)){let t=u[o++],n=i.getAttribute(e).split(Mc),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?al:r[1]===`?`?ol:r[1]===`@`?sl:il}),i.removeAttribute(e)}else e.startsWith(Mc)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(qc.test(i.tagName)){let e=i.textContent.split(Mc),t=e.length-1;if(t>0){i.textContent=kc?kc.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],Ic()),Zc.nextNode(),c.push({type:2,index:++a});i.append(e[t],Ic())}}}else if(i.nodeType===8)if(i.data===Nc)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(Mc,e+1))!==-1;)c.push({type:7,index:a}),e+=Mc.length-1}a++}}static createElement(e,t){let n=Fc.createElement(`template`);return n.innerHTML=e,n}};function tl(e,t,n=e,r){if(t===Yc)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=Lc(t)?void 0:t._$litDirective$;return i?.constructor!==a&&(i?._$AO?.(!1),a===void 0?i=void 0:(i=new a(e),i._$AT(e,n,r)),r===void 0?n._$Cl=i:(n._$Co??=[])[r]=i),i!==void 0&&(t=tl(e,i._$AS(e,t.values),i,r)),t}var nl=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??Fc).importNode(t,!0);Zc.currentNode=r;let i=Zc.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new rl(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new cl(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=Zc.nextNode(),a++)}return Zc.currentNode=Fc,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings===void 0?n._$AI(e[t]):(n._$AI(e,n,t),t+=n.strings.length-2)),t++}},rl=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=$,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=tl(this,e,t),Lc(e)?e===$||e==null||e===``?(this._$AH!==$&&this._$AR(),this._$AH=$):e!==this._$AH&&e!==Yc&&this._(e):e._$litType$===void 0?e.nodeType===void 0?zc(e)?this.k(e):this._(e):this.T(e):this.$(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==$&&Lc(this._$AH)?this._$AA.nextSibling.data=e:this.T(Fc.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n==`number`?this._$AC(e):(n.el===void 0&&(n.el=el.createElement(Qc(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new nl(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=Xc.get(e.strings);return t===void 0&&Xc.set(e.strings,t=new el(e)),t}k(t){Rc(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,r,i=0;for(let a of t)i===n.length?n.push(r=new e(this.O(Ic()),this.O(Ic()),this,this.options)):r=n[i],r._$AI(a),i++;i<n.length&&(this._$AR(r&&r._$AB.nextSibling,i),n.length=i)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let t=Oc(e).nextSibling;Oc(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},il=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,i){this.type=1,this._$AH=$,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=i,n.length>2||n[0]!==``||n[1]!==``?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=$}_$AI(e,t=this,n,r){let i=this.strings,a=!1;if(i===void 0)e=tl(this,e,t,0),a=!Lc(e)||e!==this._$AH&&e!==Yc,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=tl(this,r[n+o],t,o),s===Yc&&(s=this._$AH[o]),a||=!Lc(s)||s!==this._$AH[o],s===$?e=$:e!==$&&(e+=(s??``)+i[o+1]),this._$AH[o]=s}a&&!r&&this.j(e)}j(e){e===$?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??``)}},al=class extends il{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===$?void 0:e}},ol=class extends il{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==$)}},sl=class extends il{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=tl(this,e,t,0)??$)===Yc)return;let n=this._$AH,r=e===$&&n!==$||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==$&&(n===$||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH==`function`?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},cl=class{constructor(e,t,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){tl(this,e)}},ll=Dc.litHtmlPolyfillSupport;ll?.(el,rl),(Dc.litHtmlVersions??=[]).push(`3.3.2`);var ul=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new rl(t.insertBefore(Ic(),e),e,void 0,n??{})}return i._$AI(e),i};function dl(e={}){let{tone:t=`accent`,count:n=!1,hidden:r=!1,extra:i=[]}=e;return Rr(`ui-pill-badge`,t&&`ui-pill-badge--${t}`,{"ui-pill-badge--count":n,hidden:r},i)}function fl(){return Jc`
|
|
769
769
|
<a href="#editorContainer" class="sr-only skip-link">Skip to editor</a>
|
|
770
770
|
|
|
771
771
|
<div class="app-shell">
|
|
@@ -781,7 +781,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
781
781
|
<span class="sidebar-title">CollabMD</span>
|
|
782
782
|
</div>
|
|
783
783
|
<div class="sidebar-actions">
|
|
784
|
-
<button class=${
|
|
784
|
+
<button class=${zr({extra:`sidebar-close-btn`})} id="sidebarClose" aria-label="Close sidebar" title="Close sidebar">
|
|
785
785
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
786
786
|
<line x1="18" y1="6" x2="6" y2="18"></line>
|
|
787
787
|
<line x1="6" y1="6" x2="18" y2="18"></line>
|
|
@@ -803,7 +803,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
803
803
|
<span class="sidebar-create-btn-label">Create</span>
|
|
804
804
|
</button>
|
|
805
805
|
</div>
|
|
806
|
-
<button class=${
|
|
806
|
+
<button class=${zr()} id="refreshFilesBtn" aria-label="Refresh" title="Refresh file list">
|
|
807
807
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
808
808
|
<polyline points="23 4 23 10 17 10"></polyline>
|
|
809
809
|
<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path>
|
|
@@ -866,14 +866,14 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
866
866
|
</button>
|
|
867
867
|
<div class="toolbar-room-info">
|
|
868
868
|
<span class="toolbar-room-name" id="activeFileName">CollabMD</span>
|
|
869
|
-
<span class=${
|
|
870
|
-
<span class=${
|
|
871
|
-
<span class=${
|
|
869
|
+
<span class=${dl({tone:`accent`,extra:`toolbar-badge`})} id="userCount"></span>
|
|
870
|
+
<span class=${dl({tone:`accent`,hidden:!0,extra:`toolbar-badge`})} id="toolbarDiffBadge">Diff</span>
|
|
871
|
+
<span class=${dl({tone:`accent`,hidden:!0,extra:`toolbar-badge`})} id="gitOperationStatus" aria-live="polite" aria-atomic="true"></span>
|
|
872
872
|
</div>
|
|
873
873
|
</div>
|
|
874
874
|
|
|
875
875
|
<div class="toolbar-center" id="toolbarCenter">
|
|
876
|
-
<div class=${
|
|
876
|
+
<div class=${Br({extra:`view-toggle`})} role="group" aria-label="View mode">
|
|
877
877
|
<button class=${q({active:!0,extra:`view-btn`})} data-view="split" aria-label="Split view" aria-pressed="true" title="Split view">
|
|
878
878
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
879
879
|
<rect x="3" y="3" width="18" height="18" rx="2"></rect>
|
|
@@ -914,7 +914,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
914
914
|
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
|
|
915
915
|
</svg>
|
|
916
916
|
<span class="ui-toolbar-button-label">Chat</span>
|
|
917
|
-
<span class=${
|
|
917
|
+
<span class=${dl({tone:`solid`,count:!0,hidden:!0,extra:`chat-toggle-badge`})} id="chatToggleBadge">0</span>
|
|
918
918
|
</button>
|
|
919
919
|
<div class="toast-container chat-toast-container" id="chatToastContainer" aria-live="polite" aria-atomic="true"></div>
|
|
920
920
|
|
|
@@ -1040,7 +1040,7 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
1040
1040
|
</svg>
|
|
1041
1041
|
</span>
|
|
1042
1042
|
<span class="ui-toolbar-button-label">Theme</span>
|
|
1043
|
-
<span class=${
|
|
1043
|
+
<span class=${dl({tone:`muted`,extra:`toolbar-theme-state`})} data-theme-toggle-state>Dark</span>
|
|
1044
1044
|
</button>
|
|
1045
1045
|
</div>
|
|
1046
1046
|
</div>
|
|
@@ -1211,13 +1211,13 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
1211
1211
|
<div class="diff-toolbar">
|
|
1212
1212
|
<div class="diff-toolbar-left">
|
|
1213
1213
|
<div class="diff-file-nav">
|
|
1214
|
-
<button class=${
|
|
1214
|
+
<button class=${zr({action:!0})} id="diffPrevBtn" type="button" disabled aria-label="Previous changed file">
|
|
1215
1215
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true">
|
|
1216
1216
|
<polyline points="15 18 9 12 15 6"></polyline>
|
|
1217
1217
|
</svg>
|
|
1218
1218
|
</button>
|
|
1219
1219
|
<span class="diff-file-indicator" id="diffFileIndicator">0 / 0 files</span>
|
|
1220
|
-
<button class=${
|
|
1220
|
+
<button class=${zr({action:!0})} id="diffNextBtn" type="button" disabled aria-label="Next changed file">
|
|
1221
1221
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true">
|
|
1222
1222
|
<polyline points="9 18 15 12 9 6"></polyline>
|
|
1223
1223
|
</svg>
|
|
@@ -1248,11 +1248,11 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
1248
1248
|
<span class="ui-stat-token ui-stat-token--add diff-stats-add">+0</span>
|
|
1249
1249
|
<span class="ui-stat-token ui-stat-token--del diff-stats-del">-0</span>
|
|
1250
1250
|
</div>
|
|
1251
|
-
<div class=${
|
|
1251
|
+
<div class=${Br({hidden:!0,extra:`diff-layout-toggle`})} id="diffLayoutToggle" role="group" aria-label="Commit diff layout">
|
|
1252
1252
|
<button class=${q({extra:`view-btn diff-layout-btn`})} data-diff-layout="stacked" type="button">Stacked</button>
|
|
1253
1253
|
<button class=${q({active:!0,extra:`view-btn diff-layout-btn`})} data-diff-layout="focused" type="button">Focused</button>
|
|
1254
1254
|
</div>
|
|
1255
|
-
<div class=${
|
|
1255
|
+
<div class=${Br({extra:`diff-mode-toggle`})} role="group" aria-label="Diff view mode">
|
|
1256
1256
|
<button class=${q({active:!0,extra:`view-btn diff-mode-btn`})} data-diff-mode="unified" type="button">Unified</button>
|
|
1257
1257
|
<button class=${q({extra:`view-btn diff-mode-btn`})} data-diff-mode="split" type="button">Split</button>
|
|
1258
1258
|
</div>
|
|
@@ -1365,4 +1365,4 @@ import{t as e}from"./preload-helper-Bo9GmnuQ.js";import{a as t,i as n,n as r,r a
|
|
|
1365
1365
|
<div class="qs-hint" id="quickSwitcherHint">Type to search files</div>
|
|
1366
1366
|
</div>
|
|
1367
1367
|
</div>
|
|
1368
|
-
`}function ll(e=document){let t=e.getElementById(`appRoot`);if(!t)throw Error(`App shell root element #appRoot is missing.`);return ol(cl(),t),t}var ul=class{updateChatMessages(...e){return L.updateChatMessages.apply(this,e)}toggleChatPanel(...e){return L.toggleChatPanel.apply(this,e)}openChatPanel(...e){return L.openChatPanel.apply(this,e)}closeChatPanel(...e){return L.closeChatPanel.apply(this,e)}handleChatSubmit(...e){return L.handleChatSubmit.apply(this,e)}renderChat(...e){return L.renderChat.apply(this,e)}createChatMessageElement(...e){return L.createChatMessageElement.apply(this,e)}scrollChatToBottom(...e){return L.scrollChatToBottom.apply(this,e)}formatChatTimestamp(...e){return L.formatChatTimestamp.apply(this,e)}getChatMessageFileLabel(...e){return L.getChatMessageFileLabel.apply(this,e)}formatChatToastMessage(...e){return L.formatChatToastMessage.apply(this,e)}syncChatToggleButton(...e){return L.syncChatToggleButton.apply(this,e)}syncChatNotificationButton(...e){return L.syncChatNotificationButton.apply(this,e)}handleChatNotificationToggle(...e){return L.handleChatNotificationToggle.apply(this,e)}maybeNotifyChatMessage(...e){return L.maybeNotifyChatMessage.apply(this,e)}maybeShowBrowserChatNotification(...e){return L.maybeShowBrowserChatNotification.apply(this,e)}getCommentFileKind(...e){return Xe.getCommentFileKind.apply(this,e)}syncCommentChrome(...e){return Xe.syncCommentChrome.apply(this,e)}handleCommentSelectionChange(...e){return Xe.handleCommentSelectionChange.apply(this,e)}handleCommentThreadsChange(...e){return Xe.handleCommentThreadsChange.apply(this,e)}handleCommentEditorContentChange(...e){return Xe.handleCommentEditorContentChange.apply(this,e)}refreshCommentUiLayout(...e){return Xe.refreshCommentUiLayout.apply(this,e)}initializeExportBridge(...e){return dt.initializeExportBridge.apply(this,e)}handleExportRequest(...e){return dt.handleExportRequest.apply(this,e)}formatPullBackupToast(...e){return R.formatPullBackupToast.apply(this,e)}setGitOperationStatus(...e){return R.setGitOperationStatus.apply(this,e)}runGitActionWithStatus(...e){return R.runGitActionWithStatus.apply(this,e)}handleGitDiffSelection(...e){return R.handleGitDiffSelection.apply(this,e)}handleGitCommitSelection(...e){return R.handleGitCommitSelection.apply(this,e)}handleGitHistorySelection(...e){return R.handleGitHistorySelection.apply(this,e)}handleGitFileHistorySelection(...e){return R.handleGitFileHistorySelection.apply(this,e)}handleGitFilePreviewSelection(...e){return R.handleGitFilePreviewSelection.apply(this,e)}handleGitRepoChange(...e){return R.handleGitRepoChange.apply(this,e)}syncFileHistoryButton(...e){return R.syncFileHistoryButton.apply(this,e)}syncMainChrome(...e){return R.syncMainChrome.apply(this,e)}showGitDiff(...e){return R.showGitDiff.apply(this,e)}showGitCommit(...e){return R.showGitCommit.apply(this,e)}showGitHistory(...e){return R.showGitHistory.apply(this,e)}showGitFileHistory(...e){return R.showGitFileHistory.apply(this,e)}showGitFilePreview(...e){return R.showGitFilePreview.apply(this,e)}postGitAction(...e){return R.postGitAction.apply(this,e)}refreshWorkspaceAfterGitAction(...e){return R.refreshWorkspaceAfterGitAction.apply(this,e)}refreshGitAfterAction(...e){return R.refreshGitAfterAction.apply(this,e)}finalizeGitAction(...e){return R.finalizeGitAction.apply(this,e)}handleWorkspaceChangeForCurrentFile(...e){return R.handleWorkspaceChangeForCurrentFile.apply(this,e)}handleIncomingWorkspaceEvent(...e){return R.handleIncomingWorkspaceEvent.apply(this,e)}stageGitFile(...e){return R.stageGitFile.apply(this,e)}unstageGitFile(...e){return R.unstageGitFile.apply(this,e)}pushGitBranch(...e){return R.pushGitBranch.apply(this,e)}pullGitBranch(...e){return R.pullGitBranch.apply(this,e)}openGitResetDialog(...e){return R.openGitResetDialog.apply(this,e)}handleGitResetSubmit(...e){return R.handleGitResetSubmit.apply(this,e)}openGitCommitDialog(...e){return R.openGitCommitDialog.apply(this,e)}handleGitCommitSubmit(...e){return R.handleGitCommitSubmit.apply(this,e)}updateGlobalUsers(...e){return z.updateGlobalUsers.apply(this,e)}updateFileAwareness(...e){return z.updateFileAwareness.apply(this,e)}renderPresence(...e){return z.renderPresence.apply(this,e)}renderAvatars(...e){return z.renderAvatars.apply(this,e)}toggleFollowUser(...e){return z.toggleFollowUser.apply(this,e)}stopFollowingUser(...e){return z.stopFollowingUser.apply(this,e)}syncFollowedUser(...e){return z.syncFollowedUser.apply(this,e)}followUserCursor(...e){return z.followUserCursor.apply(this,e)}followExcalidrawUser(...e){return z.followExcalidrawUser.apply(this,e)}resolveFileClientId(...e){return z.resolveFileClientId.apply(this,e)}bindEvents(...e){return H.bindEvents.apply(this,e)}clearInitialFileBootstrap(...e){return H.clearInitialFileBootstrap.apply(this,e)}closeToolbarOverflowMenu(...e){return H.closeToolbarOverflowMenu.apply(this,e)}getStoredLineWrapping(...e){return H.getStoredLineWrapping.apply(this,e)}handleConnectionChange(...e){return H.handleConnectionChange.apply(this,e)}handlePreviewContentClick(...e){return H.handlePreviewContentClick.apply(this,e)}handleThemeChange(...e){return H.handleThemeChange.apply(this,e)}hideEditorLoading(...e){return H.hideEditorLoading.apply(this,e)}initialize(...e){return H.initialize.apply(this,e)}initializeVisualViewportBinding(...e){return H.initializeVisualViewportBinding.apply(this,e)}initializeVersionMonitoring(...e){return H.initializeVersionMonitoring.apply(this,e)}promptForVersionReload(...e){return H.promptForVersionReload.apply(this,e)}scheduleBacklinkRefresh(...e){return H.scheduleBacklinkRefresh.apply(this,e)}setToolbarOverflowOpen(...e){return H.setToolbarOverflowOpen.apply(this,e)}showEditorLoadError(...e){return H.showEditorLoadError.apply(this,e)}showEditorLoading(...e){return H.showEditorLoading.apply(this,e)}syncVisualViewportBounds(...e){return H.syncVisualViewportBounds.apply(this,e)}syncToolbarOverflowVisibility(...e){return H.syncToolbarOverflowVisibility.apply(this,e)}syncWrapToggle(...e){return H.syncWrapToggle.apply(this,e)}toggleToolbarOverflowMenu(...e){return H.toggleToolbarOverflowMenu.apply(this,e)}toggleLineWrapping(...e){return H.toggleLineWrapping.apply(this,e)}applySidebarVisibility(...e){return H.applySidebarVisibility.apply(this,e)}closeSidebarOnMobile(...e){return H.closeSidebarOnMobile.apply(this,e)}isMobileViewport(...e){return H.isMobileViewport.apply(this,e)}restoreSidebarState(...e){return H.restoreSidebarState.apply(this,e)}setSidebarTab(...e){return H.setSidebarTab.apply(this,e)}setSidebarVisibility(...e){return H.setSidebarVisibility.apply(this,e)}toggleSidebar(...e){return H.toggleSidebar.apply(this,e)}getCurrentUser(...e){return H.getCurrentUser.apply(this,e)}getCurrentUserName(...e){return H.getCurrentUserName.apply(this,e)}getStoredUserName(...e){return H.getStoredUserName.apply(this,e)}handleDisplayNameSubmit(...e){return H.handleDisplayNameSubmit.apply(this,e)}isIdentityManagedByAuth(...e){return H.isIdentityManagedByAuth.apply(this,e)}openDisplayNameDialog(...e){return H.openDisplayNameDialog.apply(this,e)}promptForDisplayNameIfNeeded(...e){return H.promptForDisplayNameIfNeeded.apply(this,e)}syncCurrentUserName(...e){return H.syncCurrentUserName.apply(this,e)}syncIdentityManagementUi(...e){return H.syncIdentityManagementUi.apply(this,e)}applyMarkdownToolbarAction(...e){return H.applyMarkdownToolbarAction.apply(this,e)}copyCurrentLink(...e){return H.copyCurrentLink.apply(this,e)}closeMarkdownBlockMenu(...e){return H.closeMarkdownBlockMenu.apply(this,e)}getActiveMarkdownBlockAction(...e){return H.getActiveMarkdownBlockAction.apply(this,e)}getMarkdownBlockMenuPopover(...e){return H.getMarkdownBlockMenuPopover.apply(this,e)}handleEditorImageInsert(...e){return H.handleEditorImageInsert.apply(this,e)}handleMarkdownToolbarClick(...e){return H.handleMarkdownToolbarClick.apply(this,e)}handleMarkdownToolbarDocumentPointerDown(...e){return H.handleMarkdownToolbarDocumentPointerDown.apply(this,e)}handleMarkdownToolbarKeydown(...e){return H.handleMarkdownToolbarKeydown.apply(this,e)}handleToolbarImageInsert(...e){return H.handleToolbarImageInsert.apply(this,e)}isMarkdownBlockMenuOpen(...e){return H.isMarkdownBlockMenuOpen.apply(this,e)}openMarkdownBlockMenu(...e){return H.openMarkdownBlockMenu.apply(this,e)}positionMarkdownBlockMenu(...e){return H.positionMarkdownBlockMenu.apply(this,e)}renderMarkdownBlockMenuPopover(...e){return H.renderMarkdownBlockMenuPopover.apply(this,e)}pickImageFile(...e){return H.pickImageFile.apply(this,e)}renderMarkdownToolbar(...e){return H.renderMarkdownToolbar.apply(this,e)}runEditorCommand(...e){return H.runEditorCommand.apply(this,e)}setActiveMarkdownBlockAction(...e){return H.setActiveMarkdownBlockAction.apply(this,e)}syncMarkdownToolbarBlockUi(...e){return H.syncMarkdownToolbarBlockUi.apply(this,e)}toggleMarkdownBlockMenu(...e){return H.toggleMarkdownBlockMenu.apply(this,e)}handleTabActivated(...e){return H.handleTabActivated.apply(this,e)}handleTabBlocked(...e){return H.handleTabBlocked.apply(this,e)}handleTabTakeover(...e){return H.handleTabTakeover.apply(this,e)}hideTabLockOverlay(...e){return H.hideTabLockOverlay.apply(this,e)}showTabLockOverlay(...e){return H.showTabLockOverlay.apply(this,e)}isExcalidrawFile(...e){return U.isExcalidrawFile.apply(this,e)}isBaseFile(...e){return U.isBaseFile.apply(this,e)}isDrawioFile(...e){return U.isDrawioFile.apply(this,e)}isImageFile(...e){return U.isImageFile.apply(this,e)}isMermaidFile(...e){return U.isMermaidFile.apply(this,e)}isPlantUmlFile(...e){return U.isPlantUmlFile.apply(this,e)}createDiagramPreviewDocument(...e){return U.createDiagramPreviewDocument.apply(this,e)}getPreviewSource(...e){return U.getPreviewSource.apply(this,e)}getStaticPreviewDocument(...e){return U.getStaticPreviewDocument.apply(this,e)}setStaticPreviewDocument(...e){return U.setStaticPreviewDocument.apply(this,e)}clearStaticPreviewDocument(...e){return U.clearStaticPreviewDocument.apply(this,e)}supportsFileHistory(...e){return U.supportsFileHistory.apply(this,e)}getDisplayName(...e){return U.getDisplayName.apply(this,e)}resetPreviewMode(...e){return U.resetPreviewMode.apply(this,e)}syncFileChrome(...e){return U.syncFileChrome.apply(this,e)}handleLayoutViewRequest(...e){return U.handleLayoutViewRequest.apply(this,e)}renderExcalidrawFilePreview(...e){return U.renderExcalidrawFilePreview.apply(this,e)}renderDrawioFilePreview(...e){return U.renderDrawioFilePreview.apply(this,e)}renderImageFilePreview(...e){return U.renderImageFilePreview.apply(this,e)}renderBaseFilePreview(...e){return U.renderBaseFilePreview.apply(this,e)}renderTextFilePreview(...e){return U.renderTextFilePreview.apply(this,e)}createResizeHandler(...e){return U.createResizeHandler.apply(this,e)}initializePreviewLayoutObserver(...e){return U.initializePreviewLayoutObserver.apply(this,e)}schedulePreviewLayoutSync(...e){return U.schedulePreviewLayoutSync.apply(this,e)}handleEditorScrollActivityChange(...e){return U.handleEditorScrollActivityChange.apply(this,e)}handleHashChange(...e){return U.handleHashChange.apply(this,e)}showEmptyState(...e){return U.showEmptyState.apply(this,e)}showDiffState(...e){return U.showDiffState.apply(this,e)}openFile(...e){return U.openFile.apply(this,e)}cleanupSession(...e){return U.cleanupSession.apply(this,e)}handleWikiLinkClick(...e){return U.handleWikiLinkClick.apply(this,e)}normalizeNewWikiFilePath(...e){return U.normalizeNewWikiFilePath.apply(this,e)}createAndOpenFile(...e){return U.createAndOpenFile.apply(this,e)}handleFileSelection(...e){return U.handleFileSelection.apply(this,e)}constructor(){ll(document),this.elements=Ye(document),this.runtimeConfig=ie(),this.stateStore=new Je,this.navigation=new sr,this.preferences=new lr({chatNotificationsKey:`collabmd-chat-notifications-enabled`,lineWrappingKey:`collabmd-editor-line-wrap`,sidebarVisibleKey:`collabmd-sidebar-visible`,userNameKey:`collabmd-user-name`}),this.notifications=new cr,this.backlinksApiClient=pr,this.gitApiClient=gr,this.plantUmlApiClient=_r,this.vaultApiClient=S,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 fr({currentBuildId:this.runtimeConfig.build?.id,onUpdateAvailable:e=>this.promptForVersionReload(e),runtimeConfig:this.runtimeConfig}),this.lobby=new or({preferredUserName:this.getStoredUserName(),onChange:e=>this.updateGlobalUsers(e),onChatChange:(e,t)=>this.updateChatMessages(e,t)}),this.workspaceSync=new Mr({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 cc(this.elements.toastContainer),this.chatToastController=new cc(this.elements.chatToastContainer),this.fileExplorer=new ds({mobileBreakpointQuery:this.mobileBreakpointQuery,onFileDelete:()=>this.navigation.navigateToFile(null),onFileSelect:e=>this.handleFileSelection(e,{closeSidebarOnMobile:!0}),pendingWorkspaceRequestIds:this.pendingWorkspaceRequestIds,toastController:this.toastController}),this.gitPanel=new Us({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 Gs({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 mc({previewElement:this.elements.previewContent}),this.basesPreview=new Ki({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 Sc({previewElement:this.elements.previewContent}),this.previewRenderer=new Ne({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.schedulePreviewLayoutSync({delayMs:0}),this.refreshCommentUiLayout()},onBeforeRenderCommit:()=>{this.videoEmbed.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit()},onPreviewLayoutChange:()=>{this.scrollSyncController.invalidatePreviewBlocks(),this.schedulePreviewLayoutSync({delayMs:0}),this.refreshCommentUiLayout()},onRenderComplete:()=>{this.videoEmbed.syncLayout(),this.drawioEmbed.syncLayout(),this.excalidrawEmbed.syncLayout(),this.schedulePreviewLayoutSync({delayMs:0}),this.refreshCommentUiLayout()},outlineController:this.outlineController,plantUmlRenderClient:this.plantUmlApiClient,previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent}),this.themeController=new sc({onChange:e=>this.handleThemeChange(e)}),this.layoutController=new Ws({mobileBreakpointQuery:this.mobileBreakpointQuery,onMeasureEditor:()=>this.session?.requestMeasure(),onViewRequest:e=>this.handleLayoutViewRequest(e)}),this.scrollSyncController=new ic({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 Nr({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 Ho({getLocalUser:()=>this.lobby.getLocalUser(),getTheme:()=>this.themeController.getTheme(),onOpenFile:e=>e&&this.navigation.navigateToFile(e),previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent,toastController:this.toastController}),this.drawioEmbed=new Ao({getLocalUser:()=>this.lobby.getLocalUser(),getTheme:()=>this.themeController.getTheme(),onOpenFile:e=>e&&this.navigation.navigateToFile(e),onOpenTextFile:e=>e&&this.navigation.navigateToFile(e,{drawioMode:`text`}),previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent,toastController:this.toastController}),this.commentUi=new So({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 He({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 Ve({getFileList:()=>this.fileExplorer.flatDocumentFiles,navigation:this.navigation,refreshExplorer:()=>this.fileExplorer.refresh(),toastController:this.toastController,vaultApiClient:this.vaultApiClient}),this.gitDiffView=new js({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 ys({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 Tr({onActivated:({takeover:e})=>this.handleTabActivated({takeover:e}),onBlocked:()=>this.handleTabBlocked({reason:`active-elsewhere`}),onStolen:()=>this.handleTabBlocked({reason:`taken-over`})}),this.workspaceCoordinator=new qe({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 Pe({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,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),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 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-Dzy_85Wp.js`).then(e=>e.EditorSession),__vite__mapDeps([28,1,29,30,31,32,33,34,35,36,37,38,39,40,27]),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)}async ensureQuickSwitcher(){if(this.quickSwitcher)return this.quickSwitcher;this.quickSwitcherModulePromise||=e(()=>import(`./quick-switcher-controller-DcyllYpm.js`).then(e=>e.QuickSwitcherController),__vite__mapDeps([41,26,27]),import.meta.url);let t=await this.quickSwitcherModulePromise;return this.quickSwitcher||=new t({getFileList:()=>this.fileExplorer.flatFiles,onFileSelect:e=>this.handleFileSelection(e,{closeSidebarOnMobile:!0})}),this.quickSwitcher}async toggleQuickSwitcher(){(await this.ensureQuickSwitcher()).toggle()}};async function dl(){await ee(),new ul().initialize()}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{dl()},{once:!0}):dl();
|
|
1368
|
+
`}function pl(e=document){let t=e.getElementById(`appRoot`);if(!t)throw Error(`App shell root element #appRoot is missing.`);return ul(fl(),t),t}var ml=class{updateChatMessages(...e){return L.updateChatMessages.apply(this,e)}toggleChatPanel(...e){return L.toggleChatPanel.apply(this,e)}openChatPanel(...e){return L.openChatPanel.apply(this,e)}closeChatPanel(...e){return L.closeChatPanel.apply(this,e)}handleChatSubmit(...e){return L.handleChatSubmit.apply(this,e)}renderChat(...e){return L.renderChat.apply(this,e)}createChatMessageElement(...e){return L.createChatMessageElement.apply(this,e)}scrollChatToBottom(...e){return L.scrollChatToBottom.apply(this,e)}formatChatTimestamp(...e){return L.formatChatTimestamp.apply(this,e)}getChatMessageFileLabel(...e){return L.getChatMessageFileLabel.apply(this,e)}formatChatToastMessage(...e){return L.formatChatToastMessage.apply(this,e)}syncChatToggleButton(...e){return L.syncChatToggleButton.apply(this,e)}syncChatNotificationButton(...e){return L.syncChatNotificationButton.apply(this,e)}handleChatNotificationToggle(...e){return L.handleChatNotificationToggle.apply(this,e)}maybeNotifyChatMessage(...e){return L.maybeNotifyChatMessage.apply(this,e)}maybeShowBrowserChatNotification(...e){return L.maybeShowBrowserChatNotification.apply(this,e)}getCommentFileKind(...e){return Xe.getCommentFileKind.apply(this,e)}syncCommentChrome(...e){return Xe.syncCommentChrome.apply(this,e)}handleCommentSelectionChange(...e){return Xe.handleCommentSelectionChange.apply(this,e)}handleCommentThreadsChange(...e){return Xe.handleCommentThreadsChange.apply(this,e)}handleCommentEditorContentChange(...e){return Xe.handleCommentEditorContentChange.apply(this,e)}refreshCommentUiLayout(...e){return Xe.refreshCommentUiLayout.apply(this,e)}initializeExportBridge(...e){return dt.initializeExportBridge.apply(this,e)}handleExportRequest(...e){return dt.handleExportRequest.apply(this,e)}formatPullBackupToast(...e){return R.formatPullBackupToast.apply(this,e)}setGitOperationStatus(...e){return R.setGitOperationStatus.apply(this,e)}runGitActionWithStatus(...e){return R.runGitActionWithStatus.apply(this,e)}handleGitDiffSelection(...e){return R.handleGitDiffSelection.apply(this,e)}handleGitCommitSelection(...e){return R.handleGitCommitSelection.apply(this,e)}handleGitHistorySelection(...e){return R.handleGitHistorySelection.apply(this,e)}handleGitFileHistorySelection(...e){return R.handleGitFileHistorySelection.apply(this,e)}handleGitFilePreviewSelection(...e){return R.handleGitFilePreviewSelection.apply(this,e)}handleGitRepoChange(...e){return R.handleGitRepoChange.apply(this,e)}syncFileHistoryButton(...e){return R.syncFileHistoryButton.apply(this,e)}syncMainChrome(...e){return R.syncMainChrome.apply(this,e)}showGitDiff(...e){return R.showGitDiff.apply(this,e)}showGitCommit(...e){return R.showGitCommit.apply(this,e)}showGitHistory(...e){return R.showGitHistory.apply(this,e)}showGitFileHistory(...e){return R.showGitFileHistory.apply(this,e)}showGitFilePreview(...e){return R.showGitFilePreview.apply(this,e)}postGitAction(...e){return R.postGitAction.apply(this,e)}refreshWorkspaceAfterGitAction(...e){return R.refreshWorkspaceAfterGitAction.apply(this,e)}refreshGitAfterAction(...e){return R.refreshGitAfterAction.apply(this,e)}finalizeGitAction(...e){return R.finalizeGitAction.apply(this,e)}handleWorkspaceChangeForCurrentFile(...e){return R.handleWorkspaceChangeForCurrentFile.apply(this,e)}handleIncomingWorkspaceEvent(...e){return R.handleIncomingWorkspaceEvent.apply(this,e)}stageGitFile(...e){return R.stageGitFile.apply(this,e)}unstageGitFile(...e){return R.unstageGitFile.apply(this,e)}pushGitBranch(...e){return R.pushGitBranch.apply(this,e)}pullGitBranch(...e){return R.pullGitBranch.apply(this,e)}openGitResetDialog(...e){return R.openGitResetDialog.apply(this,e)}handleGitResetSubmit(...e){return R.handleGitResetSubmit.apply(this,e)}openGitCommitDialog(...e){return R.openGitCommitDialog.apply(this,e)}handleGitCommitSubmit(...e){return R.handleGitCommitSubmit.apply(this,e)}updateGlobalUsers(...e){return z.updateGlobalUsers.apply(this,e)}updateFileAwareness(...e){return z.updateFileAwareness.apply(this,e)}renderPresence(...e){return z.renderPresence.apply(this,e)}renderAvatars(...e){return z.renderAvatars.apply(this,e)}toggleFollowUser(...e){return z.toggleFollowUser.apply(this,e)}stopFollowingUser(...e){return z.stopFollowingUser.apply(this,e)}syncFollowedUser(...e){return z.syncFollowedUser.apply(this,e)}followUserCursor(...e){return z.followUserCursor.apply(this,e)}followExcalidrawUser(...e){return z.followExcalidrawUser.apply(this,e)}resolveFileClientId(...e){return z.resolveFileClientId.apply(this,e)}bindEvents(...e){return H.bindEvents.apply(this,e)}clearInitialFileBootstrap(...e){return H.clearInitialFileBootstrap.apply(this,e)}closeToolbarOverflowMenu(...e){return H.closeToolbarOverflowMenu.apply(this,e)}getStoredLineWrapping(...e){return H.getStoredLineWrapping.apply(this,e)}handleConnectionChange(...e){return H.handleConnectionChange.apply(this,e)}handlePreviewContentClick(...e){return H.handlePreviewContentClick.apply(this,e)}handleThemeChange(...e){return H.handleThemeChange.apply(this,e)}hideEditorLoading(...e){return H.hideEditorLoading.apply(this,e)}initialize(...e){return H.initialize.apply(this,e)}initializeVisualViewportBinding(...e){return H.initializeVisualViewportBinding.apply(this,e)}initializeVersionMonitoring(...e){return H.initializeVersionMonitoring.apply(this,e)}promptForVersionReload(...e){return H.promptForVersionReload.apply(this,e)}scheduleBacklinkRefresh(...e){return H.scheduleBacklinkRefresh.apply(this,e)}setToolbarOverflowOpen(...e){return H.setToolbarOverflowOpen.apply(this,e)}showEditorLoadError(...e){return H.showEditorLoadError.apply(this,e)}showEditorLoading(...e){return H.showEditorLoading.apply(this,e)}syncVisualViewportBounds(...e){return H.syncVisualViewportBounds.apply(this,e)}syncToolbarOverflowVisibility(...e){return H.syncToolbarOverflowVisibility.apply(this,e)}syncWrapToggle(...e){return H.syncWrapToggle.apply(this,e)}toggleToolbarOverflowMenu(...e){return H.toggleToolbarOverflowMenu.apply(this,e)}toggleLineWrapping(...e){return H.toggleLineWrapping.apply(this,e)}applySidebarVisibility(...e){return H.applySidebarVisibility.apply(this,e)}closeSidebarOnMobile(...e){return H.closeSidebarOnMobile.apply(this,e)}isMobileViewport(...e){return H.isMobileViewport.apply(this,e)}restoreSidebarState(...e){return H.restoreSidebarState.apply(this,e)}setSidebarTab(...e){return H.setSidebarTab.apply(this,e)}setSidebarVisibility(...e){return H.setSidebarVisibility.apply(this,e)}toggleSidebar(...e){return H.toggleSidebar.apply(this,e)}getCurrentUser(...e){return H.getCurrentUser.apply(this,e)}getCurrentUserName(...e){return H.getCurrentUserName.apply(this,e)}getStoredUserName(...e){return H.getStoredUserName.apply(this,e)}handleDisplayNameSubmit(...e){return H.handleDisplayNameSubmit.apply(this,e)}isIdentityManagedByAuth(...e){return H.isIdentityManagedByAuth.apply(this,e)}openDisplayNameDialog(...e){return H.openDisplayNameDialog.apply(this,e)}promptForDisplayNameIfNeeded(...e){return H.promptForDisplayNameIfNeeded.apply(this,e)}syncCurrentUserName(...e){return H.syncCurrentUserName.apply(this,e)}syncIdentityManagementUi(...e){return H.syncIdentityManagementUi.apply(this,e)}applyMarkdownToolbarAction(...e){return H.applyMarkdownToolbarAction.apply(this,e)}copyCurrentLink(...e){return H.copyCurrentLink.apply(this,e)}closeMarkdownBlockMenu(...e){return H.closeMarkdownBlockMenu.apply(this,e)}getActiveMarkdownBlockAction(...e){return H.getActiveMarkdownBlockAction.apply(this,e)}getMarkdownBlockMenuPopover(...e){return H.getMarkdownBlockMenuPopover.apply(this,e)}handleEditorImageInsert(...e){return H.handleEditorImageInsert.apply(this,e)}handleMarkdownToolbarClick(...e){return H.handleMarkdownToolbarClick.apply(this,e)}handleMarkdownToolbarDocumentPointerDown(...e){return H.handleMarkdownToolbarDocumentPointerDown.apply(this,e)}handleMarkdownToolbarKeydown(...e){return H.handleMarkdownToolbarKeydown.apply(this,e)}handleToolbarImageInsert(...e){return H.handleToolbarImageInsert.apply(this,e)}isMarkdownBlockMenuOpen(...e){return H.isMarkdownBlockMenuOpen.apply(this,e)}openMarkdownBlockMenu(...e){return H.openMarkdownBlockMenu.apply(this,e)}positionMarkdownBlockMenu(...e){return H.positionMarkdownBlockMenu.apply(this,e)}renderMarkdownBlockMenuPopover(...e){return H.renderMarkdownBlockMenuPopover.apply(this,e)}pickImageFile(...e){return H.pickImageFile.apply(this,e)}renderMarkdownToolbar(...e){return H.renderMarkdownToolbar.apply(this,e)}runEditorCommand(...e){return H.runEditorCommand.apply(this,e)}setActiveMarkdownBlockAction(...e){return H.setActiveMarkdownBlockAction.apply(this,e)}syncMarkdownToolbarBlockUi(...e){return H.syncMarkdownToolbarBlockUi.apply(this,e)}toggleMarkdownBlockMenu(...e){return H.toggleMarkdownBlockMenu.apply(this,e)}handleTabActivated(...e){return H.handleTabActivated.apply(this,e)}handleTabBlocked(...e){return H.handleTabBlocked.apply(this,e)}handleTabTakeover(...e){return H.handleTabTakeover.apply(this,e)}hideTabLockOverlay(...e){return H.hideTabLockOverlay.apply(this,e)}showTabLockOverlay(...e){return H.showTabLockOverlay.apply(this,e)}isExcalidrawFile(...e){return U.isExcalidrawFile.apply(this,e)}isBaseFile(...e){return U.isBaseFile.apply(this,e)}isDrawioFile(...e){return U.isDrawioFile.apply(this,e)}isImageFile(...e){return U.isImageFile.apply(this,e)}isMermaidFile(...e){return U.isMermaidFile.apply(this,e)}isPlantUmlFile(...e){return U.isPlantUmlFile.apply(this,e)}createDiagramPreviewDocument(...e){return U.createDiagramPreviewDocument.apply(this,e)}getPreviewSource(...e){return U.getPreviewSource.apply(this,e)}getStaticPreviewDocument(...e){return U.getStaticPreviewDocument.apply(this,e)}setStaticPreviewDocument(...e){return U.setStaticPreviewDocument.apply(this,e)}clearStaticPreviewDocument(...e){return U.clearStaticPreviewDocument.apply(this,e)}supportsFileHistory(...e){return U.supportsFileHistory.apply(this,e)}getDisplayName(...e){return U.getDisplayName.apply(this,e)}resetPreviewMode(...e){return U.resetPreviewMode.apply(this,e)}syncFileChrome(...e){return U.syncFileChrome.apply(this,e)}handleLayoutViewRequest(...e){return U.handleLayoutViewRequest.apply(this,e)}renderExcalidrawFilePreview(...e){return U.renderExcalidrawFilePreview.apply(this,e)}renderDrawioFilePreview(...e){return U.renderDrawioFilePreview.apply(this,e)}renderImageFilePreview(...e){return U.renderImageFilePreview.apply(this,e)}renderBaseFilePreview(...e){return U.renderBaseFilePreview.apply(this,e)}renderTextFilePreview(...e){return U.renderTextFilePreview.apply(this,e)}createResizeHandler(...e){return U.createResizeHandler.apply(this,e)}initializePreviewLayoutObserver(...e){return U.initializePreviewLayoutObserver.apply(this,e)}schedulePreviewLayoutSync(...e){return U.schedulePreviewLayoutSync.apply(this,e)}handleEditorScrollActivityChange(...e){return U.handleEditorScrollActivityChange.apply(this,e)}handleHashChange(...e){return U.handleHashChange.apply(this,e)}showEmptyState(...e){return U.showEmptyState.apply(this,e)}showDiffState(...e){return U.showDiffState.apply(this,e)}openFile(...e){return U.openFile.apply(this,e)}cleanupSession(...e){return U.cleanupSession.apply(this,e)}handleWikiLinkClick(...e){return U.handleWikiLinkClick.apply(this,e)}normalizeNewWikiFilePath(...e){return U.normalizeNewWikiFilePath.apply(this,e)}createAndOpenFile(...e){return U.createAndOpenFile.apply(this,e)}handleFileSelection(...e){return U.handleFileSelection.apply(this,e)}constructor(){pl(document),this.elements=Ye(document),this.runtimeConfig=ie(),this.stateStore=new Je,this.navigation=new dr,this.preferences=new pr({chatNotificationsKey:`collabmd-chat-notifications-enabled`,lineWrappingKey:`collabmd-editor-line-wrap`,sidebarVisibleKey:`collabmd-sidebar-visible`,userNameKey:`collabmd-user-name`}),this.notifications=new fr,this.backlinksApiClient=_r,this.gitApiClient=br,this.plantUmlApiClient=xr,this.vaultApiClient=S,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 gr({currentBuildId:this.runtimeConfig.build?.id,onUpdateAvailable:e=>this.promptForVersionReload(e),runtimeConfig:this.runtimeConfig}),this.lobby=new ur({preferredUserName:this.getStoredUserName(),onChange:e=>this.updateGlobalUsers(e),onChatChange:(e,t)=>this.updateChatMessages(e,t)}),this.workspaceSync=new Ir({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 fc(this.elements.toastContainer),this.chatToastController=new fc(this.elements.chatToastContainer),this.fileExplorer=new hs({mobileBreakpointQuery:this.mobileBreakpointQuery,onFileDelete:()=>this.navigation.navigateToFile(null),onFileSelect:e=>this.handleFileSelection(e,{closeSidebarOnMobile:!0}),pendingWorkspaceRequestIds:this.pendingWorkspaceRequestIds,toastController:this.toastController}),this.gitPanel=new qs({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 Ys({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 vc({previewElement:this.elements.previewContent}),this.basesPreview=new Xi({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 Ec({previewElement:this.elements.previewContent}),this.previewRenderer=new Ne({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.schedulePreviewLayoutSync({delayMs:0}),this.refreshCommentUiLayout()},onBeforeRenderCommit:()=>{this.videoEmbed.detachForCommit(),this.drawioEmbed.detachForCommit(),this.excalidrawEmbed.detachForCommit()},onPreviewLayoutChange:()=>{this.scrollSyncController.invalidatePreviewBlocks(),this.schedulePreviewLayoutSync({delayMs:0}),this.refreshCommentUiLayout()},onRenderComplete:()=>{this.videoEmbed.syncLayout(),this.drawioEmbed.syncLayout(),this.excalidrawEmbed.syncLayout(),this.schedulePreviewLayoutSync({delayMs:0}),this.refreshCommentUiLayout()},outlineController:this.outlineController,plantUmlRenderClient:this.plantUmlApiClient,previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent}),this.themeController=new dc({onChange:e=>this.handleThemeChange(e)}),this.layoutController=new Js({mobileBreakpointQuery:this.mobileBreakpointQuery,onMeasureEditor:()=>this.session?.requestMeasure(),onViewRequest:e=>this.handleLayoutViewRequest(e)}),this.scrollSyncController=new cc({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 Lr({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 Ko({getLocalUser:()=>this.lobby.getLocalUser(),getTheme:()=>this.themeController.getTheme(),onOpenFile:e=>e&&this.navigation.navigateToFile(e),previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent,toastController:this.toastController}),this.drawioEmbed=new Po({getLocalUser:()=>this.lobby.getLocalUser(),getTheme:()=>this.themeController.getTheme(),onOpenFile:e=>e&&this.navigation.navigateToFile(e),onOpenTextFile:e=>e&&this.navigation.navigateToFile(e,{drawioMode:`text`}),previewContainer:this.elements.previewContainer,previewElement:this.elements.previewContent,toastController:this.toastController}),this.commentUi=new Eo({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 He({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 Ve({getFileList:()=>this.fileExplorer.flatDocumentFiles,navigation:this.navigation,refreshExplorer:()=>this.fileExplorer.refresh(),toastController:this.toastController,vaultApiClient:this.vaultApiClient}),this.gitDiffView=new Fs({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 Cs({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 kr({onActivated:({takeover:e})=>this.handleTabActivated({takeover:e}),onBlocked:()=>this.handleTabBlocked({reason:`active-elsewhere`}),onStolen:()=>this.handleTabBlocked({reason:`taken-over`})}),this.workspaceCoordinator=new qe({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 Pe({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,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),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 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-Dzy_85Wp.js`).then(e=>e.EditorSession),__vite__mapDeps([28,1,29,30,31,32,33,34,35,36,37,38,39,40,27]),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)}async ensureQuickSwitcher(){if(this.quickSwitcher)return this.quickSwitcher;this.quickSwitcherModulePromise||=e(()=>import(`./quick-switcher-controller-DcyllYpm.js`).then(e=>e.QuickSwitcherController),__vite__mapDeps([41,26,27]),import.meta.url);let t=await this.quickSwitcherModulePromise;return this.quickSwitcher||=new t({getFileList:()=>this.fileExplorer.flatFiles,onFileSelect:e=>this.handleFileSelection(e,{closeSidebarOnMobile:!0})}),this.quickSwitcher}async toggleQuickSwitcher(){(await this.ensureQuickSwitcher()).toggle()}};async function hl(){await ee(),new ml().initialize()}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{hl()},{once:!0}):hl();
|