collabmd 0.1.26 → 0.1.27

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.
@@ -126,7 +126,7 @@ import{t as e}from"./preload-helper-I1wKxk_B.js";import{a as t,i as n,n as r,r a
126
126
  <svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
127
127
  <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"/>
128
128
  </svg>
129
- `,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 Pr(){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 Fr(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 Ir(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 Lr(){this.activeCard=null,this.pendingCardFocusElement=null,this.reactionPicker=null,this.renderCard(),this.scheduleLayoutRefresh()}function Rr(){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 zr(){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=mr(this.activeCard.anchor),r.append(i,a);let o=document.createElement(`button`);o.type=`button`,o.className=`ui-button ui-button--compact btn btn-ghost ui-pill-button 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 Br(e){let t=wr(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 Vr(){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 Hr(){let e=document.createElement(`form`);e.className=`comment-card-form`;let t=document.createElement(`textarea`);t.className=`input comment-card-input`,t.rows=4,t.maxLength=ie,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=`ui-button btn btn-secondary`,r.textContent=`Cancel`,r.addEventListener(`click`,()=>this.closeCard());let i=document.createElement(`button`);return i.type=`submit`,i.className=`ui-button btn btn-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 Ur(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=`ui-button ui-button--compact btn btn-ghost ui-pill-button 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=`ui-button ui-button--compact btn btn-ghost ui-pill-button 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=`ui-button ui-button--compact btn btn-ghost ui-pill-button 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 Wr(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=br(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 Gr(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`,xr(r,n)),i.setAttribute(`aria-pressed`,String(xr(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=Sr(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`,cr.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(Cr(this.reactionPicker,e.id,t.id))),c.textContent=`More`,c.addEventListener(`click`,()=>{this.reactionPicker=Cr(this.reactionPicker,e.id,t.id)?null:{messageId:t.id,threadId:e.id},this.renderCard()}),s.appendChild(c),Cr(this.reactionPicker,e.id,t.id)&&s.appendChild(this.createReactionPicker(e,t)),o.appendChild(s),r.append(a,o),r}function Kr(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 qr(e,t){let n=document.createElement(`div`);n.className=`comment-reaction-picker`;let r=document.createElement(`div`);return r.className=`comment-reaction-picker-grid`,lr.forEach(n=>{r.appendChild(this.createReactionPickerButton(e,t,n))}),n.appendChild(r),n}function Jr(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 Yr(e){let t=document.createElement(`form`);t.className=`comment-reply-form`;let n=document.createElement(`textarea`);n.className=`input comment-card-input`,n.rows=3,n.maxLength=ie,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=`ui-button btn btn-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=`ui-button btn btn-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 Xr(e){let t=this.updateCardSourceRect(),n=window.innerWidth,r=window.innerHeight,i=e.getBoundingClientRect(),a=K((n-i.width)/2,16,n-i.width-16),o=K((r-i.height)/4,16,r-i.height-16),s=a,c=o;t&&(s=K(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 Zr(){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 Qr={closeCard:Lr,createComposer:Hr,createMessageElement:Wr,createQuickReactionButton:Kr,createReactionBar:Gr,createReactionPicker:qr,createReactionPickerButton:Jr,createReplyComposer:Yr,createThreadElement:Ur,ensureCardRoot:Pr,flushPendingCardFocus:Zr,openComposerForSelection:Fr,openThreadGroup:Ir,positionCard:Xr,renderCard:zr,repositionActiveCard:Vr,updateCardSourceRect:Rr,updateReactionPickerPosition:Br};function $r(){this.renderEditorLayer(),this.renderPreviewLayer(),this.repositionActiveCard()}function ei(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 ti(){this.layoutFrame||=requestAnimationFrame(()=>{this.layoutFrame=0,this.refreshLayout()})}function ni(){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 ri(){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=Or(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(Nr(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=Or(a,t);if(o.bottom<0||o.top>t.height)return;let s=K(o.top,8,Math.max(t.height-36,8));for(;r.some(e=>Math.abs(e-s)<32);)s=K(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 ii(){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 ai(){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(Nr(t.threads.length));let d=K(o.bubbleRect.top-e.top,6,Math.max(this.previewElement.clientHeight-30,6));for(;n.some(e=>Math.abs(e-d)<26);)d=K(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 oi(e){if(!this.previewElement||!e)return null;let t=Array.from(this.previewElement.querySelectorAll(`.mermaid-shell, .plantuml-shell`)).find(t=>Tr(t,e));if(t)return{bubbleRect:t.getBoundingClientRect(),highlightRects:[],hoverRects:[t.getBoundingClientRect()]};let n=Array.from(this.previewElement.querySelectorAll(`[data-source-line]`)).filter(t=>gr(t)&&Tr(t,e));if(e.kind===`text`&&e.quote){let t=n.map(t=>({element:t,range:Dr(t,e.quote)})).filter(e=>e.range);if(t.length===1){let e=Array.from(t[0].range.getClientRects());return{bubbleRect:kr(e)||t[0].element.getBoundingClientRect(),highlightRects:e,hoverRects:e}}}let r=n[0];return r?{bubbleRect:r.getBoundingClientRect(),highlightRects:[],hoverRects:[r.getBoundingClientRect()]}:null}function si(e){if(!(e instanceof Node))return[];let t=e.closest?.(`[data-comment-preview-group-keys]`);return Mr(String(t?.dataset?.commentPreviewGroupKeys??``).split(/\s+/).filter(Boolean)).split(` `).filter(Boolean)}function ci(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:jr(this.previewHoverRegions.filter(n=>n.rects.some(n=>Ar(e,t,n))).map(e=>e.key))}function li(e=[]){let t=jr(e),n=t.join(` `);n!==this.hoveredPreviewGroupKeysSignature&&(this.hoveredPreviewGroupKeys=t,this.hoveredPreviewGroupKeysSignature=n,this.scheduleLayoutRefresh())}function ui(e=[]){let t=jr(e),n=t.join(` `);n!==this.hoveredEditorGroupKeysSignature&&(this.hoveredEditorGroupKeys=t,this.hoveredEditorGroupKeysSignature=n,this.scheduleLayoutRefresh())}function di(e){this.updateHoveredPreviewGroups(this.getPreviewGroupKeysForTarget(e))}function fi(){let e=this.previewContainer?.clientWidth??this.previewElement?.clientWidth??0;return window.innerWidth>=769&&e>=400}var pi={ensureEditorLayer:ni,ensurePreviewLayer:ii,getPreviewGroupKeysAtPoint:ci,getPreviewGroupKeysForTarget:si,refreshLayout:$r,renderEditorLayer:ri,renderPreviewLayer:ai,resolvePreviewTarget:oi,scheduleLayoutRefresh:ti,shouldRenderPassivePreviewMarkers:fi,syncHoveredPreviewGroupsFromTarget:di,syncPreviewRailLayout:ei,updateHoveredEditorGroups:ui,updateHoveredPreviewGroups:li};function mi(){this.renderToolbar(),this.renderDrawer(),this.renderCard(),this.scheduleLayoutRefresh()}function hi(){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 gi(){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=mr(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=yr(e),c=br(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 _i(e){if(!Number.isFinite(e))return``;try{return this.timeFormatter.format(new Date(e))}catch{return``}}var vi={formatTimestamp:_i,render:mi,renderDrawer:gi,renderToolbar:hi};function yi(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 bi(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 xi(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(!fr(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(pr(this.committedSelectionAnchor,this.selectionAnchor)){this.renderToolbar(),this.scheduleLayoutRefresh();return}this.scheduleSelectionReveal(this.selectionAnchor),this.renderToolbar(),this.scheduleLayoutRefresh()}function Si(){this.activeCard?.mode!==`create`&&(this.clearSelectionRevealTimer(),this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.scheduleLayoutRefresh())}function Ci(e=[]){this.threads=ur(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 wi(e){let t=!!e;t!==this.drawerOpen&&(t&&this.onWillOpenDrawer?.(),this.drawerOpen=t,this.render())}function Ti(){this.setDrawerOpen(!1)}function Ei(){let e=new Map;return this.threads.forEach(t=>{let n=hr(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 Di(){this.selectionRevealTimer&&=(clearTimeout(this.selectionRevealTimer),0)}function Oi(e){this.clearSelectionRevealTimer(),this.selectionRevealTimer=window.setTimeout(()=>{this.selectionRevealTimer=0,!(this.pointerSelecting||this.activeCard?.mode===`create`||!pr(this.pendingSelectionAnchor,e))&&(this.committedSelectionAnchor=e,this.scheduleLayoutRefresh())},150)}var ki={attachSession:yi,clearSelectionRevealTimer:Di,closeDrawer:Ti,getThreadGroups:Ei,handleEditorContentChange:Si,scheduleSelectionReveal:Oi,setCurrentFile:bi,setDrawerOpen:wi,setSelectionAnchor:xi,setThreads:Ci},Ai=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=fr(e)?e:null,this.clearSelectionRevealTimer(),this.committedSelectionAnchor=fr(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(Ai.prototype,ki,vi,pi,Qr);var ji=360,Mi=`https://viewer.diagrams.net/js/viewer-static.min.js`,q=null;function Ni(e,t){return typeof window.requestIdleCallback==`function`?window.requestIdleCallback(e,{timeout:t}):window.setTimeout(()=>e({didTimeout:!1,timeRemaining:()=>0}),1)}function Pi(e){if(e!==null){if(typeof window.cancelIdleCallback==`function`){window.cancelIdleCallback(e);return}window.clearTimeout(e)}}function Fi(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 Ii(){return window.GraphViewer?.processElements?Promise.resolve(window.GraphViewer):q||(q=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(),q=null,t(Error(`Failed to load draw.io viewer`))},o=()=>{if(i(),!window.GraphViewer?.processElements){q=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=Mi,r.async=!0,r.dataset.collabmdDrawioViewer=`true`,document.head.append(r))}),q)}var Li=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._onMessage=this._onMessage.bind(this),this._onPreviewClick=this._onPreviewClick.bind(this),window.addEventListener(`message`,this._onMessage),this.previewElement?.addEventListener(`click`,this._onPreviewClick)}destroy(){window.removeEventListener(`message`,this._onMessage),this.previewElement?.removeEventListener(`click`,this._onPreviewClick),Pi(this.hydrationIdleId),this.hydrationIdleId=null,this.hydrationQueue=[],this.embedEntries.forEach(e=>e.wrapper?.remove()),this.embedEntries.clear()}detachForCommit(){Pi(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){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`||Fi(e.placeholder,this.previewContainer,ji))&&this.enqueueHydration(e)})}enqueueHydration(e){e.queued||(e.queued=!0,this.hydrationQueue.push(e),this.hydrationIdleId===null&&(this.hydrationIdleId=Ni(()=>{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${e.mode===`edit`?` is-direct-file`:``}`,t.dataset.file=e.filePath;let n=document.createElement(`div`);n.className=`drawio-embed-header`;let r=document.createElement(`span`);if(r.className=`drawio-embed-label`,r.textContent=e.label.replace(/\.drawio$/i,``),n.appendChild(r),e.mode!==`edit`){let t=document.createElement(`button`);t.type=`button`,t.className=`drawio-embed-btn`,t.dataset.action=`open-file`,t.dataset.filePath=e.filePath,t.textContent=`Open`,n.appendChild(t)}let i=document.createElement(`iframe`);i.className=`drawio-embed-iframe`,i.loading=`lazy`,i.referrerPolicy=`strict-origin-when-cross-origin`,e.instanceId=`drawio-${++this.instanceCounter}`,i.dataset.instanceId=e.instanceId,i.src=this.buildIframeUrl(e),t.append(n,i),e.iframe=i,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 is-static-preview`,t.dataset.file=e.filePath;let n=document.createElement(`div`);n.className=`drawio-embed-header`;let r=document.createElement(`span`);r.className=`drawio-embed-label`,r.textContent=e.label.replace(/\.drawio$/i,``),n.appendChild(r);let i=document.createElement(`button`);i.type=`button`,i.className=`drawio-embed-btn`,i.dataset.action=`open-file`,i.dataset.filePath=e.filePath,i.textContent=`Open`,n.appendChild(i);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([ee.readFile(e.filePath),Ii()]);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.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(S(`/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`,te(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(){}_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.renderExportFallback(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}let n=e.target.closest(`.drawio-embed-btn[data-action="open-file"]`);n&&(e.preventDefault(),this.onOpenFile?.(n.dataset.filePath||``));let r=e.target.closest(`.drawio-viewer-frame[data-action="open-file"]`);r&&(e.preventDefault(),this.onOpenFile?.(r.dataset.filePath||``))}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 Ri(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,reusedFromEmbed:!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 J=420,zi=500,Bi=15e3,Vi=800,Hi=3,Ui=200,Wi=`/excalidraw-editor.html`;function Gi(e,t){return typeof window.requestIdleCallback==`function`?window.requestIdleCallback(e,{timeout:t}):window.setTimeout(()=>{e({didTimeout:!1,timeRemaining:()=>0})},1)}function Ki(e){if(e!==null){if(typeof window.cancelIdleCallback==`function`){window.cancelIdleCallback(e);return}window.clearTimeout(e)}}function qi(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 Ji=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.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(),Ki(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.pendingDisconnectRequests.forEach(e=>{e.resolve(!1)}),this.pendingDisconnectRequests.clear(),this.followedPeerIdsByFilePath.clear(),this.overlayRoot?.remove(),this.overlayRoot=null,this.maximizedRoot?.remove(),this.maximizedRoot=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(),Ki(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){Ki(this.hydrationIdleId),this.hydrationIdleId=null;return}this.hydrateVisibleEmbeds(),this._scheduleHydration()}reconcileEmbeds(e,{isLargeDocument:t=!1}={}){this.isLargeDocument=!!t,this._disconnectPlaceholderObserver(),Ki(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}=Ri(this.embedEntries,n);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._updateEmbedLabel(e),this._attachWrapper(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||qi(t.placeholder,this.previewContainer,e)&&this._enqueueHydration(t,{prioritize:!0})})}updateTheme(e){this.embedEntries.forEach(t=>{this._postMessageToEntry(t,{source:`collabmd-host`,type:`set-theme`,theme:e})})}updateLocalUser(e){this.embedEntries.forEach(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=Gi(()=>{this.hydrationIdleId=null,this._flushHydrationQueue()},zi))}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.wrapper){let t=this._createEmbedContainer(e);e.wrapper=t.wrapper,e.iframe=t.iframe,e.labelElement=t.labelElement,e.instanceId=t.instanceId,e.isReady=!1,e.bootAttempts=(e.bootAttempts??0)+1,this._armEntryBootTimeout(e)}e.followedPeerId=this.followedPeerIdsByFilePath.get(e.filePath),this._updateEmbedLabel(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=t.findIndex(e=>e.filePath===n.filePath&&this._getEntryMode(e)===this._getEntryMode(n)&&(e.wrapper||e.iframe));if(i<0)return;let[a]=t.splice(i,1);a.filePath=n.filePath,a.key=n.key,a.label=n.label,a.placeholder=n.placeholder,a.queued=!1,a.reusedFromEmbed=this._isFilePreviewEntry(n),e.set(r,a)})}_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._resetPlaceholderLayout(e),e.wrapper?.remove(),e.placeholder=null}_armEntryBootTimeout(e){this._clearEntryBootTimeout(e),e.bootTimerId=window.setTimeout(()=>{this._handleEntryBootTimeout(e)},Bi)}_clearEntryBootTimeout(e){e?.bootTimerId&&(window.clearTimeout(e.bootTimerId),e.bootTimerId=null)}async _handleEntryBootTimeout(e){if(e?.iframe?.isConnected){if((e.bootAttempts??0)>=Hi){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.maximizedEmbed?.wrapper===e.wrapper&&this._exitMaximizedEmbed(),e.wrapper?.remove(),e.wrapper=null,e.iframe=null,e.labelElement=null,e.instanceId=null,e.isReady=!1,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 null}_findEntryByFilePath(e){if(!e)return null;for(let t of this.embedEntries.values())if(t.filePath===e)return t;return 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.iframe&&(e.iframe.title=`Excalidraw: ${e.filePath}`)}_buildIframeUrl(e){let t=new URL(S(Wi)),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`),L(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`),L(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=`${J}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=`${J}px`,d=()=>{L(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||`${J}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(),{iframe:s,instanceId:s.dataset.instanceId,labelElement:i,wrapper:t}}_setupResizer(e,t,n=null){let r=0,i=0,a=e=>{let n=e.clientY-r,a=Math.min(Math.max(i+n,Ui),Vi);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)&&!e?.reusedFromEmbed}_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||``)||J,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||J)}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`){n.isReady=!0,this._clearEntryBootTimeout(n),this._syncEntryUser(n),this._postMessageToEntry(n,{source:`collabmd-host`,type:`set-theme`,theme:this.getTheme?.()||`dark`}),this._syncEntryFollowState(n);return}if(t.type===`error`){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 Yi(){return typeof window>`u`||typeof window.matchMedia!=`function`?{matches:!1}:window.matchMedia(`(max-width: 768px)`)}function Xi(e){return typeof HTMLElement>`u`||!(e instanceof HTMLElement)?[]:Array.from(e.querySelectorAll(`.create-menu-item`))}var Zi=class{constructor({mobileBreakpointQuery:e=Yi()}={}){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,Xi(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=`ui-button btn btn-ghost 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?`ui-button btn btn-ghost 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=Xi(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 Qi(e){return String(e??``).replace(/\/+$/u,``).split(`/`).filter(Boolean).pop()||``}function $i(e,t,n){return e===t?n:`${n}${e.slice(t.length)}`}function ea(e,t,n){return`${e} ${e===1?t:n}`}function ta(){return JSON.stringify({type:`excalidraw`,version:2,source:`collabmd`,elements:[],appState:{viewBackgroundColor:`#ffffff`,gridSize:null},files:{}})}function Y(e,t){return t?{...e,requestId:t}:e}var na=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 Zi({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 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:`Delete`,danger:!0,onSelect:()=>this.handleDeleteDirectory(e)}]}getFileContextMenuItems(e){return[{label:`Rename / move`,onSelect:()=>this.handleRenameFile(e)},{label:`Delete`,danger:!0,onSelect:()=>this.handleDelete(e)}]}showToast(e){e&&this.toastController?.show(String(e))}getCreateActionIcon(e){switch(e){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 De(e,t)}createPendingWorkspaceRequestId(){if(!this.pendingWorkspaceRequestIds)return null;let e=Je();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(`btn-primary`,!c),this.actionSubmitButton.classList.toggle(`btn-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.classList.add(`btn-primary`),this.actionSubmitButton.classList.remove(`btn-danger`)),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=!1;try{n=await this.pendingAction.onSubmit(t)}catch(e){n=!1,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(Y({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=H(e);if(!t)return this.showToast(`Folder path is required`),!1;try{return await this.runWorkspaceMutation(e=>this.vaultClient.createDirectory(t,Y({},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=H(t);if(!r)return this.showToast(`File path is required`),!1;let i=o(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(!Qi(a))return this.showToast(`File path is required`),!1;if(a===e)return!0;try{return await this.runWorkspaceMutation(t=>this.vaultClient.renameFile(Y({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=H(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(Y({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=$i(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,Y({},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,Y({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}}getCreateContext(e=``){let t=H(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=H(e);if(!n)return this.showToast(`File path is required`),!1;let r=this.ensureExtension(U(t.normalizedParentDir,n),`.md`);return this.createVaultFile(r,Oe(r),{errorMessage:`Failed to create 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(U(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=H(e);if(!n)return this.showToast(`Drawing path is required`),!1;let r=this.ensureExtension(U(t.normalizedParentDir,n),`.excalidraw`);return this.createVaultFile(r,ta(),{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=H(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=ke(U(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=H(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=Ae(U(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=H(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=je(U(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create PlantUML diagram`,openAfterCreate:!0})}})}handleRenameFile(e){let t=o(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 ${ea(n,`file`,`files`)} and ${ea(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})})}};function ra(e,t=[],n=[]){for(let r of e)if(!(!r?.path||!r?.type)){if(n.push({name:r.name,path:r.path,type:r.type}),r.type===`file`||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)&&ra(r.children,t,n)}return{files:t,searchEntries:n}}function ia(e,t){for(let n of e??[]){if(n?.path===t)return n;if(n?.type===`directory`&&Array.isArray(n.children)){let e=ia(n.children,t);if(e)return e}}return null}function aa(e){let t=0,n=0;for(let r of e?.children??[]){if(r?.type===`directory`){t+=1;let e=aa(r);t+=e.directoryCount,n+=e.fileCount;continue}n+=1}return{directoryCount:t,fileCount:n}}function oa(e,t,n){return e===t?n:`${n}${e.slice(t.length)}`}var sa=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=ra(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.path.toLowerCase().includes(this.searchQuery)):[]}getNode(e){return ia(this.tree,e)}getDirectoryDescendantSummary(e){let t=this.getNode(e);return!t||t.type!==`directory`?{directoryCount:0,fileCount:0}:aa(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=H(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(oa(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 ca(e){return String(e??``).replace(/\/+$/u,``).split(`/`).filter(Boolean).pop()||``}function la(e){let t=String(e??``).replace(/\/+$/u,``),n=t.lastIndexOf(`/`);return n>=0?t.slice(0,n):``}function ua(e=[],t=``){for(let n of e){if(n.path===t)return n;if(n.type===`directory`&&Array.isArray(n.children)){let e=ua(n.children,t);if(e)return e}}return null}var da=420,fa=10,pa=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onDirectorySelect:t,onDirectoryToggle:n,onFileContextMenu:r,onFileSelect:i,onSearchChange:a,onTreeContextMenu:o}){this.onDirectorySelect=t,this.onDirectoryToggle=n,this.onFileContextMenu=r,this.onFileSelect=i,this.onSearchChange=a,this.onTreeContextMenu=o,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}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})}render({activeFilePath:e,changedPaths:t=null,expandedDirs:n,reset:r=!1,searchMatches:i,searchQuery:a,tree:o}){if(!this.treeContainer)return;if(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=>la(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=``,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||(v(r.path)??`file`),name:r.name||ca(r.path)}))}this.treeContainer.appendChild(n)}renderFullTree(e,{activeFilePath:t,expandedDirs:n}){if(this.resetTreeIndexes(),this.treeContainer.innerHTML=``,e.length===0){this.treeContainer.innerHTML=`<div class="file-tree-empty">No vault files found</div>`;return}let r=document.createDocumentFragment();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.innerHTML=`
129
+ `,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 Pr(){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 Fr(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 Ir(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 Lr(){this.activeCard=null,this.pendingCardFocusElement=null,this.reactionPicker=null,this.renderCard(),this.scheduleLayoutRefresh()}function Rr(){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 zr(){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=mr(this.activeCard.anchor),r.append(i,a);let o=document.createElement(`button`);o.type=`button`,o.className=`ui-button ui-button--compact btn btn-ghost ui-pill-button 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 Br(e){let t=wr(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 Vr(){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 Hr(){let e=document.createElement(`form`);e.className=`comment-card-form`;let t=document.createElement(`textarea`);t.className=`input comment-card-input`,t.rows=4,t.maxLength=ie,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=`ui-button btn btn-secondary`,r.textContent=`Cancel`,r.addEventListener(`click`,()=>this.closeCard());let i=document.createElement(`button`);return i.type=`submit`,i.className=`ui-button btn btn-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 Ur(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=`ui-button ui-button--compact btn btn-ghost ui-pill-button 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=`ui-button ui-button--compact btn btn-ghost ui-pill-button 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=`ui-button ui-button--compact btn btn-ghost ui-pill-button 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 Wr(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=br(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 Gr(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`,xr(r,n)),i.setAttribute(`aria-pressed`,String(xr(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=Sr(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`,cr.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(Cr(this.reactionPicker,e.id,t.id))),c.textContent=`More`,c.addEventListener(`click`,()=>{this.reactionPicker=Cr(this.reactionPicker,e.id,t.id)?null:{messageId:t.id,threadId:e.id},this.renderCard()}),s.appendChild(c),Cr(this.reactionPicker,e.id,t.id)&&s.appendChild(this.createReactionPicker(e,t)),o.appendChild(s),r.append(a,o),r}function Kr(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 qr(e,t){let n=document.createElement(`div`);n.className=`comment-reaction-picker`;let r=document.createElement(`div`);return r.className=`comment-reaction-picker-grid`,lr.forEach(n=>{r.appendChild(this.createReactionPickerButton(e,t,n))}),n.appendChild(r),n}function Jr(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 Yr(e){let t=document.createElement(`form`);t.className=`comment-reply-form`;let n=document.createElement(`textarea`);n.className=`input comment-card-input`,n.rows=3,n.maxLength=ie,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=`ui-button btn btn-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=`ui-button btn btn-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 Xr(e){let t=this.updateCardSourceRect(),n=window.innerWidth,r=window.innerHeight,i=e.getBoundingClientRect(),a=K((n-i.width)/2,16,n-i.width-16),o=K((r-i.height)/4,16,r-i.height-16),s=a,c=o;t&&(s=K(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 Zr(){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 Qr={closeCard:Lr,createComposer:Hr,createMessageElement:Wr,createQuickReactionButton:Kr,createReactionBar:Gr,createReactionPicker:qr,createReactionPickerButton:Jr,createReplyComposer:Yr,createThreadElement:Ur,ensureCardRoot:Pr,flushPendingCardFocus:Zr,openComposerForSelection:Fr,openThreadGroup:Ir,positionCard:Xr,renderCard:zr,repositionActiveCard:Vr,updateCardSourceRect:Rr,updateReactionPickerPosition:Br};function $r(){this.renderEditorLayer(),this.renderPreviewLayer(),this.repositionActiveCard()}function ei(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 ti(){this.layoutFrame||=requestAnimationFrame(()=>{this.layoutFrame=0,this.refreshLayout()})}function ni(){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 ri(){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=Or(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(Nr(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=Or(a,t);if(o.bottom<0||o.top>t.height)return;let s=K(o.top,8,Math.max(t.height-36,8));for(;r.some(e=>Math.abs(e-s)<32);)s=K(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 ii(){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 ai(){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(Nr(t.threads.length));let d=K(o.bubbleRect.top-e.top,6,Math.max(this.previewElement.clientHeight-30,6));for(;n.some(e=>Math.abs(e-d)<26);)d=K(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 oi(e){if(!this.previewElement||!e)return null;let t=Array.from(this.previewElement.querySelectorAll(`.mermaid-shell, .plantuml-shell`)).find(t=>Tr(t,e));if(t)return{bubbleRect:t.getBoundingClientRect(),highlightRects:[],hoverRects:[t.getBoundingClientRect()]};let n=Array.from(this.previewElement.querySelectorAll(`[data-source-line]`)).filter(t=>gr(t)&&Tr(t,e));if(e.kind===`text`&&e.quote){let t=n.map(t=>({element:t,range:Dr(t,e.quote)})).filter(e=>e.range);if(t.length===1){let e=Array.from(t[0].range.getClientRects());return{bubbleRect:kr(e)||t[0].element.getBoundingClientRect(),highlightRects:e,hoverRects:e}}}let r=n[0];return r?{bubbleRect:r.getBoundingClientRect(),highlightRects:[],hoverRects:[r.getBoundingClientRect()]}:null}function si(e){if(!(e instanceof Node))return[];let t=e.closest?.(`[data-comment-preview-group-keys]`);return Mr(String(t?.dataset?.commentPreviewGroupKeys??``).split(/\s+/).filter(Boolean)).split(` `).filter(Boolean)}function ci(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:jr(this.previewHoverRegions.filter(n=>n.rects.some(n=>Ar(e,t,n))).map(e=>e.key))}function li(e=[]){let t=jr(e),n=t.join(` `);n!==this.hoveredPreviewGroupKeysSignature&&(this.hoveredPreviewGroupKeys=t,this.hoveredPreviewGroupKeysSignature=n,this.scheduleLayoutRefresh())}function ui(e=[]){let t=jr(e),n=t.join(` `);n!==this.hoveredEditorGroupKeysSignature&&(this.hoveredEditorGroupKeys=t,this.hoveredEditorGroupKeysSignature=n,this.scheduleLayoutRefresh())}function di(e){this.updateHoveredPreviewGroups(this.getPreviewGroupKeysForTarget(e))}function fi(){let e=this.previewContainer?.clientWidth??this.previewElement?.clientWidth??0;return window.innerWidth>=769&&e>=400}var pi={ensureEditorLayer:ni,ensurePreviewLayer:ii,getPreviewGroupKeysAtPoint:ci,getPreviewGroupKeysForTarget:si,refreshLayout:$r,renderEditorLayer:ri,renderPreviewLayer:ai,resolvePreviewTarget:oi,scheduleLayoutRefresh:ti,shouldRenderPassivePreviewMarkers:fi,syncHoveredPreviewGroupsFromTarget:di,syncPreviewRailLayout:ei,updateHoveredEditorGroups:ui,updateHoveredPreviewGroups:li};function mi(){this.renderToolbar(),this.renderDrawer(),this.renderCard(),this.scheduleLayoutRefresh()}function hi(){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 gi(){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=mr(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=yr(e),c=br(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 _i(e){if(!Number.isFinite(e))return``;try{return this.timeFormatter.format(new Date(e))}catch{return``}}var vi={formatTimestamp:_i,render:mi,renderDrawer:gi,renderToolbar:hi};function yi(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 bi(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 xi(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(!fr(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(pr(this.committedSelectionAnchor,this.selectionAnchor)){this.renderToolbar(),this.scheduleLayoutRefresh();return}this.scheduleSelectionReveal(this.selectionAnchor),this.renderToolbar(),this.scheduleLayoutRefresh()}function Si(){this.activeCard?.mode!==`create`&&(this.clearSelectionRevealTimer(),this.pendingSelectionAnchor=null,this.committedSelectionAnchor=null,this.scheduleLayoutRefresh())}function Ci(e=[]){this.threads=ur(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 wi(e){let t=!!e;t!==this.drawerOpen&&(t&&this.onWillOpenDrawer?.(),this.drawerOpen=t,this.render())}function Ti(){this.setDrawerOpen(!1)}function Ei(){let e=new Map;return this.threads.forEach(t=>{let n=hr(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 Di(){this.selectionRevealTimer&&=(clearTimeout(this.selectionRevealTimer),0)}function Oi(e){this.clearSelectionRevealTimer(),this.selectionRevealTimer=window.setTimeout(()=>{this.selectionRevealTimer=0,!(this.pointerSelecting||this.activeCard?.mode===`create`||!pr(this.pendingSelectionAnchor,e))&&(this.committedSelectionAnchor=e,this.scheduleLayoutRefresh())},150)}var ki={attachSession:yi,clearSelectionRevealTimer:Di,closeDrawer:Ti,getThreadGroups:Ei,handleEditorContentChange:Si,scheduleSelectionReveal:Oi,setCurrentFile:bi,setDrawerOpen:wi,setSelectionAnchor:xi,setThreads:Ci},Ai=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=fr(e)?e:null,this.clearSelectionRevealTimer(),this.committedSelectionAnchor=fr(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(Ai.prototype,ki,vi,pi,Qr);var ji=360,Mi=`https://viewer.diagrams.net/js/viewer-static.min.js`,q=null;function Ni(e,t){return typeof window.requestIdleCallback==`function`?window.requestIdleCallback(e,{timeout:t}):window.setTimeout(()=>e({didTimeout:!1,timeRemaining:()=>0}),1)}function Pi(e){if(e!==null){if(typeof window.cancelIdleCallback==`function`){window.cancelIdleCallback(e);return}window.clearTimeout(e)}}function Fi(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 Ii(){return window.GraphViewer?.processElements?Promise.resolve(window.GraphViewer):q||(q=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(),q=null,t(Error(`Failed to load draw.io viewer`))},o=()=>{if(i(),!window.GraphViewer?.processElements){q=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=Mi,r.async=!0,r.dataset.collabmdDrawioViewer=`true`,document.head.append(r))}),q)}var Li=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),Pi(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(){Pi(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`||Fi(e.placeholder,this.previewContainer,ji))&&this.enqueueHydration(e)})}enqueueHydration(e){e.queued||(e.queued=!0,this.hydrationQueue.push(e),this.hydrationIdleId===null&&(this.hydrationIdleId=Ni(()=>{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([ee.readFile(e.filePath),Ii()]);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(S(`/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`,te(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`),L(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;L(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;L(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 Ri(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,reusedFromEmbed:!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 J=420,zi=500,Bi=15e3,Vi=800,Hi=3,Ui=200,Wi=`/excalidraw-editor.html`;function Gi(e,t){return typeof window.requestIdleCallback==`function`?window.requestIdleCallback(e,{timeout:t}):window.setTimeout(()=>{e({didTimeout:!1,timeRemaining:()=>0})},1)}function Ki(e){if(e!==null){if(typeof window.cancelIdleCallback==`function`){window.cancelIdleCallback(e);return}window.clearTimeout(e)}}function qi(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 Ji=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.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(),Ki(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.pendingDisconnectRequests.forEach(e=>{e.resolve(!1)}),this.pendingDisconnectRequests.clear(),this.followedPeerIdsByFilePath.clear(),this.overlayRoot?.remove(),this.overlayRoot=null,this.maximizedRoot?.remove(),this.maximizedRoot=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(),Ki(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){Ki(this.hydrationIdleId),this.hydrationIdleId=null;return}this.hydrateVisibleEmbeds(),this._scheduleHydration()}reconcileEmbeds(e,{isLargeDocument:t=!1}={}){this.isLargeDocument=!!t,this._disconnectPlaceholderObserver(),Ki(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}=Ri(this.embedEntries,n);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._updateEmbedLabel(e),this._attachWrapper(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||qi(t.placeholder,this.previewContainer,e)&&this._enqueueHydration(t,{prioritize:!0})})}updateTheme(e){this.embedEntries.forEach(t=>{this._postMessageToEntry(t,{source:`collabmd-host`,type:`set-theme`,theme:e})})}updateLocalUser(e){this.embedEntries.forEach(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=Gi(()=>{this.hydrationIdleId=null,this._flushHydrationQueue()},zi))}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.wrapper){let t=this._createEmbedContainer(e);e.wrapper=t.wrapper,e.iframe=t.iframe,e.labelElement=t.labelElement,e.instanceId=t.instanceId,e.isReady=!1,e.bootAttempts=(e.bootAttempts??0)+1,this._armEntryBootTimeout(e)}e.followedPeerId=this.followedPeerIdsByFilePath.get(e.filePath),this._updateEmbedLabel(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=t.findIndex(e=>e.filePath===n.filePath&&this._getEntryMode(e)===this._getEntryMode(n)&&(e.wrapper||e.iframe));if(i<0)return;let[a]=t.splice(i,1);a.filePath=n.filePath,a.key=n.key,a.label=n.label,a.placeholder=n.placeholder,a.queued=!1,a.reusedFromEmbed=this._isFilePreviewEntry(n),e.set(r,a)})}_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._resetPlaceholderLayout(e),e.wrapper?.remove(),e.placeholder=null}_armEntryBootTimeout(e){this._clearEntryBootTimeout(e),e.bootTimerId=window.setTimeout(()=>{this._handleEntryBootTimeout(e)},Bi)}_clearEntryBootTimeout(e){e?.bootTimerId&&(window.clearTimeout(e.bootTimerId),e.bootTimerId=null)}async _handleEntryBootTimeout(e){if(e?.iframe?.isConnected){if((e.bootAttempts??0)>=Hi){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.maximizedEmbed?.wrapper===e.wrapper&&this._exitMaximizedEmbed(),e.wrapper?.remove(),e.wrapper=null,e.iframe=null,e.labelElement=null,e.instanceId=null,e.isReady=!1,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 null}_findEntryByFilePath(e){if(!e)return null;for(let t of this.embedEntries.values())if(t.filePath===e)return t;return 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.iframe&&(e.iframe.title=`Excalidraw: ${e.filePath}`)}_buildIframeUrl(e){let t=new URL(S(Wi)),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`),L(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`),L(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=`${J}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=`${J}px`,d=()=>{L(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||`${J}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(),{iframe:s,instanceId:s.dataset.instanceId,labelElement:i,wrapper:t}}_setupResizer(e,t,n=null){let r=0,i=0,a=e=>{let n=e.clientY-r,a=Math.min(Math.max(i+n,Ui),Vi);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)&&!e?.reusedFromEmbed}_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||``)||J,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||J)}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`){n.isReady=!0,this._clearEntryBootTimeout(n),this._syncEntryUser(n),this._postMessageToEntry(n,{source:`collabmd-host`,type:`set-theme`,theme:this.getTheme?.()||`dark`}),this._syncEntryFollowState(n);return}if(t.type===`error`){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 Yi(){return typeof window>`u`||typeof window.matchMedia!=`function`?{matches:!1}:window.matchMedia(`(max-width: 768px)`)}function Xi(e){return typeof HTMLElement>`u`||!(e instanceof HTMLElement)?[]:Array.from(e.querySelectorAll(`.create-menu-item`))}var Zi=class{constructor({mobileBreakpointQuery:e=Yi()}={}){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,Xi(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=`ui-button btn btn-ghost 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?`ui-button btn btn-ghost 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=Xi(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 Qi(e){return String(e??``).replace(/\/+$/u,``).split(`/`).filter(Boolean).pop()||``}function $i(e,t,n){return e===t?n:`${n}${e.slice(t.length)}`}function ea(e,t,n){return`${e} ${e===1?t:n}`}function ta(){return JSON.stringify({type:`excalidraw`,version:2,source:`collabmd`,elements:[],appState:{viewBackgroundColor:`#ffffff`,gridSize:null},files:{}})}function Y(e,t){return t?{...e,requestId:t}:e}var na=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 Zi({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 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:`Delete`,danger:!0,onSelect:()=>this.handleDeleteDirectory(e)}]}getFileContextMenuItems(e){return[{label:`Rename / move`,onSelect:()=>this.handleRenameFile(e)},{label:`Delete`,danger:!0,onSelect:()=>this.handleDelete(e)}]}showToast(e){e&&this.toastController?.show(String(e))}getCreateActionIcon(e){switch(e){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 De(e,t)}createPendingWorkspaceRequestId(){if(!this.pendingWorkspaceRequestIds)return null;let e=Je();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(`btn-primary`,!c),this.actionSubmitButton.classList.toggle(`btn-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.classList.add(`btn-primary`),this.actionSubmitButton.classList.remove(`btn-danger`)),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=!1;try{n=await this.pendingAction.onSubmit(t)}catch(e){n=!1,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(Y({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=H(e);if(!t)return this.showToast(`Folder path is required`),!1;try{return await this.runWorkspaceMutation(e=>this.vaultClient.createDirectory(t,Y({},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=H(t);if(!r)return this.showToast(`File path is required`),!1;let i=o(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(!Qi(a))return this.showToast(`File path is required`),!1;if(a===e)return!0;try{return await this.runWorkspaceMutation(t=>this.vaultClient.renameFile(Y({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=H(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(Y({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=$i(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,Y({},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,Y({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}}getCreateContext(e=``){let t=H(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=H(e);if(!n)return this.showToast(`File path is required`),!1;let r=this.ensureExtension(U(t.normalizedParentDir,n),`.md`);return this.createVaultFile(r,Oe(r),{errorMessage:`Failed to create 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(U(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=H(e);if(!n)return this.showToast(`Drawing path is required`),!1;let r=this.ensureExtension(U(t.normalizedParentDir,n),`.excalidraw`);return this.createVaultFile(r,ta(),{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=H(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=ke(U(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=H(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=Ae(U(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=H(e);if(!n)return this.showToast(`Diagram path is required`),!1;let r=je(U(t.normalizedParentDir,n));return this.createVaultFile(r.path,r.content,{errorMessage:`Failed to create PlantUML diagram`,openAfterCreate:!0})}})}handleRenameFile(e){let t=o(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 ${ea(n,`file`,`files`)} and ${ea(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})})}};function ra(e,t=[],n=[]){for(let r of e)if(!(!r?.path||!r?.type)){if(n.push({name:r.name,path:r.path,type:r.type}),r.type===`file`||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)&&ra(r.children,t,n)}return{files:t,searchEntries:n}}function ia(e,t){for(let n of e??[]){if(n?.path===t)return n;if(n?.type===`directory`&&Array.isArray(n.children)){let e=ia(n.children,t);if(e)return e}}return null}function aa(e){let t=0,n=0;for(let r of e?.children??[]){if(r?.type===`directory`){t+=1;let e=aa(r);t+=e.directoryCount,n+=e.fileCount;continue}n+=1}return{directoryCount:t,fileCount:n}}function oa(e,t,n){return e===t?n:`${n}${e.slice(t.length)}`}var sa=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=ra(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.path.toLowerCase().includes(this.searchQuery)):[]}getNode(e){return ia(this.tree,e)}getDirectoryDescendantSummary(e){let t=this.getNode(e);return!t||t.type!==`directory`?{directoryCount:0,fileCount:0}:aa(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=H(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(oa(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 ca(e){return String(e??``).replace(/\/+$/u,``).split(`/`).filter(Boolean).pop()||``}function la(e){let t=String(e??``).replace(/\/+$/u,``),n=t.lastIndexOf(`/`);return n>=0?t.slice(0,n):``}function ua(e=[],t=``){for(let n of e){if(n.path===t)return n;if(n.type===`directory`&&Array.isArray(n.children)){let e=ua(n.children,t);if(e)return e}}return null}var da=420,fa=10,pa=class{constructor({mobileBreakpointQuery:e=window.matchMedia(`(max-width: 768px)`),onDirectorySelect:t,onDirectoryToggle:n,onFileContextMenu:r,onFileSelect:i,onSearchChange:a,onTreeContextMenu:o}){this.onDirectorySelect=t,this.onDirectoryToggle=n,this.onFileContextMenu=r,this.onFileSelect=i,this.onSearchChange=a,this.onTreeContextMenu=o,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}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})}render({activeFilePath:e,changedPaths:t=null,expandedDirs:n,reset:r=!1,searchMatches:i,searchQuery:a,tree:o}){if(!this.treeContainer)return;if(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=>la(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=``,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||(v(r.path)??`file`),name:r.name||ca(r.path)}))}this.treeContainer.appendChild(n)}renderFullTree(e,{activeFilePath:t,expandedDirs:n}){if(this.resetTreeIndexes(),this.treeContainer.innerHTML=``,e.length===0){this.treeContainer.innerHTML=`<div class="file-tree-empty">No vault files found</div>`;return}let r=document.createDocumentFragment();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.innerHTML=`
130
130
  <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>
131
131
  <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>
132
132
  <span class="file-tree-name">${h(e.name)}</span>
@@ -15,10 +15,10 @@
15
15
  document.documentElement.setAttribute('data-initial-file-requested', 'true');
16
16
  }
17
17
  </script>
18
- <script type="module" crossorigin src="./assets/index-GE56R5t4.js"></script>
18
+ <script type="module" crossorigin src="./assets/index-D4FS-o13.js"></script>
19
19
  <link rel="modulepreload" crossorigin href="./assets/runtime-config-loader-DwWsKc1-.js">
20
20
  <link rel="modulepreload" crossorigin href="./assets/preload-helper-I1wKxk_B.js">
21
- <link rel="stylesheet" crossorigin href="./assets/index-C95nV7Tl.css">
21
+ <link rel="stylesheet" crossorigin href="./assets/index-DRgeOr4A.css">
22
22
  </head>
23
23
  <body>
24
24
  <a href="#editorContainer" class="sr-only skip-link">Skip to editor</a>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "collabmd",
3
- "version": "0.1.26",
3
+ "version": "0.1.27",
4
4
  "type": "module",
5
5
  "description": "Collaborative markdown vault — like Obsidian, but online. Serve any directory of markdown files for realtime collaborative editing.",
6
6
  "repository": {