markon-core 0.15.14

markon core - Mark it on.
var g=typeof window<"u"&&window.__MARKON_I18N__?.t||(s=>s),N={t(s,...t){let e=typeof window<"u"&&window.__MARKON_I18N__?.t||null;return e?e(s,...t):s}},u={BREAKPOINTS:{WIDE_SCREEN:1400},DIMENSIONS:{NOTE_CARD_WIDTH:280,NOTE_CARD_RIGHT_MARGIN:40,HEADING_TOP_MARGIN:64,HEADING_TOP_MARGIN_TIGHT:5,POPOVER_OFFSET:10},THRESHOLDS:{NOTE_CLUSTER:50,NOTE_MIN_SPACING:32,HEADING_SCROLL_THRESHOLD:40},WEBSOCKET:{INITIAL_RECONNECT_DELAY:1e3,MAX_RECONNECT_DELAY:3e4,STABLE_CONNECTION_THRESHOLD:5e3},ANIMATION:{RESIZE_DEBOUNCE:150,PANEL_TRANSITION:200},UNDO:{MAX_STACK_SIZE:50},SHORTCUTS:{HELP:{key:"?",ctrl:!1,shift:!1,desc:g("web.kbd.help"),cat:"global"},THEME_PANEL:{key:"t",ctrl:!1,shift:!1,desc:g("web.kbd.theme"),cat:"global"},UNDO:{key:"z",ctrl:!0,shift:!1,desc:g("web.kbd.undo"),cat:"core"},REDO:{key:"z",ctrl:!0,shift:!0,desc:g("web.kbd.redo"),cat:"core"},REDO_ALT:{key:"y",ctrl:!0,shift:!1,desc:g("web.kbd.redo.alt"),cat:"core"},ESCAPE:{key:"Escape",ctrl:!1,shift:!1,desc:g("web.kbd.escape"),cat:"core"},TOGGLE_TOC:{key:"\\",ctrl:!0,shift:!1,desc:g("web.kbd.toc"),cat:"core"},SEARCH:{key:"/",ctrl:!1,shift:!1,desc:g("web.kbd.search"),cat:"search",feature:"workspace_spotlight"},EXPORT_NOTES:{key:"x",ctrl:!1,shift:!1,desc:g("web.kbd.exportnotes"),cat:"core"},WORKSPACE_NAVIGATOR:{key:"g",ctrl:!1,shift:!1,desc:g("web.kbd.workspace_nav"),cat:"search",feature:"workspace_spotlight"},PREV_HEADING:{key:"k",ctrl:!1,shift:!1,desc:g("web.kbd.prevheading"),cat:"nav"},NEXT_HEADING:{key:"j",ctrl:!1,shift:!1,desc:g("web.kbd.nextheading"),cat:"nav"},PREV_ANNOTATION:{key:"k",ctrl:!0,shift:!1,desc:g("web.kbd.prevanno"),cat:"nav"},NEXT_ANNOTATION:{key:"j",ctrl:!0,shift:!1,desc:g("web.kbd.nextanno"),cat:"nav"},SCROLL_HALF_PAGE_DOWN:{key:" ",ctrl:!1,shift:!1,desc:g("web.kbd.scroll"),cat:"nav"},TOGGLE_SECTION_COLLAPSE:{key:"o",ctrl:!1,shift:!1,desc:g("web.kbd.collapse"),cat:"viewed"},TOGGLE_VIEWED:{key:"v",ctrl:!1,shift:!1,desc:g("web.kbd.viewed"),cat:"viewed"},EDIT:{key:"e",ctrl:!1,shift:!1,desc:g("web.kbd.edit"),cat:"edit"},TOGGLE_LIVE_ACTIVE:{key:"l",ctrl:!1,shift:!1,desc:g("web.kbd.live.active"),cat:"live"},TOGGLE_LIVE_OFF:{key:"l",ctrl:!1,shift:!0,desc:g("web.kbd.live.off"),cat:"live"},TOGGLE_CHAT:{key:"c",ctrl:!1,shift:!1,desc:g("web.kbd.chat"),cat:"chat"},TOGGLE_CHAT_ALT:{key:"c",ctrl:!1,shift:!0,desc:g("web.kbd.chat.alt"),cat:"chat"},DIFF_TOGGLE_VIEW:{key:"m",ctrl:!1,shift:!1,desc:g("web.kbd.diff.view"),cat:"diff"},DIFF_NEXT_FILE:{key:"n",ctrl:!1,shift:!1,desc:g("web.kbd.diff.nextfile"),cat:"diff"},DIFF_PREV_FILE:{key:"p",ctrl:!1,shift:!1,desc:g("web.kbd.diff.prevfile"),cat:"diff"},VISUAL_ZOOM_IN:{key:"+",ctrl:!1,shift:!1,desc:g("web.kbd.visual.zoom_in"),cat:"visual",feature:"visual_zoom_in"},VISUAL_ZOOM_IN_ALT:{key:"=",ctrl:!1,shift:!1,desc:g("web.kbd.visual.zoom_in"),cat:"visual",feature:"visual_zoom_in"},VISUAL_ZOOM_OUT:{key:"-",ctrl:!1,shift:!1,desc:g("web.kbd.visual.zoom_out"),cat:"visual"},VISUAL_ZOOM_RESET:{key:"0",ctrl:!1,shift:!1,desc:g("web.kbd.visual.reset"),cat:"visual",feature:"visual_reset"},VISUAL_ZOOM_RESET_ALT:{key:"r",ctrl:!1,shift:!1,desc:g("web.kbd.visual.reset"),cat:"visual",feature:"visual_reset"},VISUAL_ZOOM_FIT:{key:"f",ctrl:!1,shift:!1,desc:g("web.kbd.visual.fit"),cat:"visual",feature:"visual_fit"},VISUAL_ZOOM_FIT_CMD:{key:"0",ctrl:!0,shift:!1,desc:g("web.kbd.visual.fit"),cat:"visual",feature:"visual_fit"},VISUAL_ZOOM_TOOL:{key:"z",ctrl:!1,shift:!1,desc:g("web.kbd.visual.tool"),cat:"visual"},VISUAL_ZOOM_TOOL_OUT:{key:"z",ctrl:!1,shift:!0,desc:g("web.kbd.visual.tool_out"),cat:"visual"},VISUAL_ZOOM_CLOSE:{key:"Escape",ctrl:!1,shift:!1,desc:g("web.kbd.visual.close"),cat:"visual",feature:"ESCAPE"}},STORAGE_KEYS:{ANNOTATIONS:s=>`markon-annotations-${s}`,VIEWED:s=>`markon-viewed-${s}`,LIVE_POS:"markon-live-pos",LIVE_COLOR:"markon-user-color",IDENTITY_NAME:"markon-user-name",LIVE_MODE:"markon-live-mode",CLIENT_ID:"markon-client-id",CHAT_POS:"markon-chat-pos",CHAT_SIZE:"markon-chat-size",NOTE_INPUT_OFFSET:"markon-note-input-offset",NOTE_INPUT_SIZE:"markon-note-input-size",POPOVER_OFFSET:"markon-popover-offset",SHORTCUTS_HELP_POS:"markon-shortcuts-help-pos",WORKSPACE_SPOTLIGHT_POS:"markon-workspace-spotlight-pos"},SELECTORS:{MARKDOWN_BODY:".markdown-body",HEADINGS:"h1, h2, h3, h4, h5, h6",TOC_CONTAINER:"#toc-container",TOC_ICON:"#toc-icon",HIGHLIGHT_CLASSES:".highlight-orange, .highlight-green, .highlight-yellow, .strikethrough"},SKIP_ELEMENTS:{IDS:new Set(["toc"]),CLASSES:new Set(["back-link","toc","selection-popover","note-card-margin","note-popup"])},META_TAGS:{FILE_PATH:"file-path",WORKSPACE_ID:"workspace-id",SHARED_ANNOTATION:"shared-annotation",ENABLE_SEARCH:"enable-search",ENABLE_VIEWED:"enable-viewed",ENABLE_EDIT:"enable-edit",ENABLE_LIVE:"enable-live",ENABLE_CHAT:"enable-chat",DEFAULT_CHAT_MODE:"default-chat-mode",CHAT_ONLY:"chat-only"},WS_MESSAGE_TYPES:{ALL_ANNOTATIONS:"all_annotations",NEW_ANNOTATION:"new_annotation",DELETE_ANNOTATION:"delete_annotation",CLEAR_ANNOTATIONS:"clear_annotations",VIEWED_STATE:"viewed_state",UPDATE_VIEWED_STATE:"update_viewed_state",LIVE_ACTION:"live_action",FILE_CHANGED:"file_changed"},COLLABORATION:{COLORS:["#3451B2","#E64560","#27AE60","#F39C12","#8E44AD","#0EA5E9","#EC4899","#14B8A6"],SYNC_DEBOUNCE:100},ANNOTATION_TYPES:{STRIKETHROUGH:"strikethrough",HAS_NOTE:"has-note"},HTML_TAGS:{HIGHLIGHT:"span",STRIKETHROUGH:"s"},BLOCK_TAGS:["P","DIV","LI","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","PRE","TD","TH"]};if(typeof window<"u"&&window.__MARKON_SHORTCUTS__){let s=Object.entries(window.__MARKON_SHORTCUTS__);for(let[t,e]of s)u.SHORTCUTS[t]&&Object.assign(u.SHORTCUTS[t],e)}Object.freeze(u);Object.freeze(u.BREAKPOINTS);Object.freeze(u.DIMENSIONS);Object.freeze(u.THRESHOLDS);Object.freeze(u.WEBSOCKET);Object.freeze(u.ANIMATION);Object.freeze(u.UNDO);Object.freeze(u.SHORTCUTS);Object.freeze(u.SELECTORS);Object.freeze(u.SKIP_ELEMENTS);Object.freeze(u.META_TAGS);Object.freeze(u.WS_MESSAGE_TYPES);Object.freeze(u.COLLABORATION);Object.freeze(u.ANNOTATION_TYPES);Object.freeze(u.HTML_TAGS);async function I(s){try{if(navigator.clipboard&&navigator.clipboard.writeText)return await navigator.clipboard.writeText(s),!0}catch{}try{let t=document.createElement("textarea");t.value=s,t.style.position="fixed",t.style.opacity="0",t.style.pointerEvents="none",document.body.appendChild(t),t.select();let e=document.execCommand("copy");return t.remove(),e}catch{return!1}}function ot(s,t,e=1200){let n=document.createElement("span");n.className="markon-copy-flash",n.textContent=t,document.body.appendChild(n);let o=s.getBoundingClientRect();n.style.top=`${o.top+o.height/2}px`,n.style.left=`${o.left}px`,requestAnimationFrame(()=>n.classList.add("is-visible")),window.setTimeout(()=>{n.classList.remove("is-visible"),window.setTimeout(()=>n.remove(),200)},e)}var At='<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 8.5l3.2 3.2L13 4.5"/></svg>';function it(s,t=1100){s.dataset.copiedOriginal===void 0&&(s.dataset.copiedOriginal=s.innerHTML),s.dataset.copiedTimer&&window.clearTimeout(Number(s.dataset.copiedTimer)),s.innerHTML=At,s.classList.add("is-copied");let e=window.setTimeout(()=>{s.innerHTML=s.dataset.copiedOriginal??"",s.classList.remove("is-copied"),delete s.dataset.copiedOriginal,delete s.dataset.copiedTimer},t);s.dataset.copiedTimer=String(e)}function st(s,t,e=1500){s.dataset.flashOriginal===void 0&&(s.dataset.flashOriginal=s.textContent??""),s.dataset.flashTimer&&window.clearTimeout(Number(s.dataset.flashTimer)),s.textContent=t,s.classList.add("is-flashing");let n=window.setTimeout(()=>{s.textContent=s.dataset.flashOriginal??"",s.classList.remove("is-flashing"),delete s.dataset.flashOriginal,delete s.dataset.flashTimer},e);s.dataset.flashTimer=String(n)}var H={getBlockParent(s,t){let e=s.nodeType===3?s.parentElement:s;for(;e&&e!==t;){if(u.BLOCK_TAGS.includes(e.tagName))return e;e=e.parentElement}return null},findLastTextNode(s){let t=null,e=n=>{if(n.nodeType===3&&(n.textContent??"").trim())t=n;else if(n.nodeType===1)for(let o of n.childNodes)e(o)};return e(s),t},shouldSkip(s){if(s.nodeType!==1)return!1;let t=s;return t.id&&u.SKIP_ELEMENTS.IDS.has(t.id)?!0:t.className&&typeof t.className=="string"?t.className.split(" ").some(e=>u.SKIP_ELEMENTS.CLASSES.has(e)):!1},getHeight(s,t=80){let e=s.offsetHeight;return e>0?e:t},onOutsideClick(s,t,{ignore:e}={}){let n=i=>{s.contains(i.target)||e?.(i.target)||t(i)},o=()=>document.removeEventListener("click",n,!0);return document.addEventListener("click",n,!0),o}},R={get(s){return document.querySelector(`meta[name="${s}"]`)?.getAttribute("content")??null},flag(s){return this.get(s)==="true"}};function Lt(s){return s.split("/").filter((t,e,n)=>t!==""||e>0&&e<n.length-1).map(encodeURIComponent).join("/")}function Nt(s){return encodeURIComponent(s.trim().replace(/^\/+|\/+$/g,""))}function Ot(s){let t=Nt(s);return t?`/${t}/`:"/"}function rt(s,t=""){let e=t.trim().replace(/^\/+/,""),n=Ot(s);return e?`${n}${Lt(e)}`:n}var xt="note-",kt=/^anno-[A-Za-z0-9-]{1,64}$/;function Ct(s){return kt.test(s)}function _t(s){return Ct(s)?`${xt}${encodeURIComponent(s)}`:""}function at(s,t,e){let n=_t(e);if(!n)return"";let o=new URL(rt(s,t),window.location.origin);return o.hash=n,o.toString()}var O=class{static isMac(){return navigator.platform.toUpperCase().includes("MAC")}static isNarrowScreen(){return window.innerWidth<=u.BREAKPOINTS.WIDE_SCREEN}static isWideScreen(){return window.innerWidth>u.BREAKPOINTS.WIDE_SCREEN}};var lt={uuid(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`},short(){return Math.random().toString(36).slice(2,11)}},d=class s{static#t=!0;static enable(){s.#t=!0}static disable(){s.#t=!1}static log(t,e,...n){s.#t&&console.log(`[${t}]`,e,...n)}static warn(t,e,...n){s.#t&&console.warn(`[${t}]`,e,...n)}static error(t,e,...n){console.error(`[${t}]`,e,...n)}};var F=class{},P=class extends F{async load(t){try{let e=localStorage.getItem(t);return e?JSON.parse(e):null}catch(e){return d.error("LocalStorage","Failed to load data:",t,e),null}}async save(t,e){try{localStorage.setItem(t,JSON.stringify(e)),d.log("LocalStorage","Saved data:",t)}catch(n){d.error("LocalStorage","Failed to save data:",t,n)}}async delete(t){try{localStorage.removeItem(t),d.log("LocalStorage","Deleted data:",t)}catch(e){d.error("LocalStorage","Failed to delete data:",t,e)}}},x=class extends F{#t;#n=new Map;constructor(t){super(),this.#t=t}async load(t){return this.#n.get(t)??null}async save(t,e){this.#n.set(t,e),this.#t&&this.#t.isConnected()?this.#e(t,"save")===u.WS_MESSAGE_TYPES.UPDATE_VIEWED_STATE&&(await this.#t.sendWithOpId({type:"update_viewed_state",state:e}),d.log("SharedStorage","Saved viewed state via WebSocket")):d.warn("SharedStorage","WebSocket not connected, data cached locally")}async saveSingleAnnotation(t){if(this.#t&&this.#t.isConnected()){let e=await this.#t.sendWithOpId({type:"new_annotation",annotation:t});return d.log("SharedStorage","Saved annotation via WebSocket:",t.id),e}return d.warn("SharedStorage","WebSocket not connected, annotation not saved"),null}async delete(t){this.#n.delete(t),this.#t&&this.#t.isConnected()&&(t.includes("annotations")?(await this.#t.sendWithOpId({type:"clear_annotations"}),d.log("SharedStorage","Sent clear annotations via WebSocket")):t.includes("viewed")&&(await this.#t.sendWithOpId({type:"update_viewed_state",state:{}}),d.log("SharedStorage","Sent clear viewed state via WebSocket")))}async deleteSingleAnnotation(t){if(this.#t&&this.#t.isConnected()){let e=await this.#t.sendWithOpId({type:"delete_annotation",id:t});return d.log("SharedStorage","Deleted annotation via WebSocket:",t),e}return d.warn("SharedStorage","WebSocket not connected, annotation not deleted"),null}updateCache(t,e){this.#n.set(t,e),d.log("SharedStorage","Cache updated:",t)}clearCache(t=null){t?this.#n.delete(t):this.#n.clear()}#e(t,e){return t.includes("annotations")?e==="save"?u.WS_MESSAGE_TYPES.NEW_ANNOTATION:e==="delete"?u.WS_MESSAGE_TYPES.DELETE_ANNOTATION:u.WS_MESSAGE_TYPES.ALL_ANNOTATIONS:t.includes("viewed")?u.WS_MESSAGE_TYPES.UPDATE_VIEWED_STATE:null}},B=class{#t;#n;#e;constructor(t,e=!1,n=null){this.#n=t,this.#e=e,e&&n?(this.#t=new x(n),d.log("StorageManager","Using shared storage strategy")):(this.#t=new P,d.log("StorageManager","Using local storage strategy"))}static async loadLocalAnnotations(t){let e=new P,n=u.STORAGE_KEYS.ANNOTATIONS(t);return await e.load(n)??[]}static async saveLocalAnnotations(t,e){let n=new P,o=u.STORAGE_KEYS.ANNOTATIONS(t);await n.save(o,e)}async loadAnnotations(){let t=u.STORAGE_KEYS.ANNOTATIONS(this.#n);return await this.#t.load(t)??[]}async saveAnnotations(t){let e=u.STORAGE_KEYS.ANNOTATIONS(this.#n);await this.#t.save(e,t)}async saveAnnotation(t){if(this.#e&&this.#t instanceof x)return this.#t.saveSingleAnnotation(t);let e=await this.loadAnnotations(),n=e.findIndex(o=>o.id===t.id);return n>=0?e[n]=t:e.push(t),await this.saveAnnotations(e),null}async deleteAnnotation(t){if(this.#e&&this.#t instanceof x)return this.#t.deleteSingleAnnotation(t);let n=(await this.loadAnnotations()).filter(o=>o.id!==t);return await this.saveAnnotations(n),null}async clearAnnotations(){let t=u.STORAGE_KEYS.ANNOTATIONS(this.#n);return await this.#t.delete(t),null}async loadViewedState(){let t=u.STORAGE_KEYS.VIEWED(this.#n);return await this.#t.load(t)??{}}async saveViewedState(t){let e=u.STORAGE_KEYS.VIEWED(this.#n);await this.#t.save(e,t)}async clearViewedState(){let t=u.STORAGE_KEYS.VIEWED(this.#n);await this.#t.delete(t)}updateCache(t,e){this.#t instanceof x&&this.#t.updateCache(t,e)}isSharedMode(){return this.#e}getFilePath(){return this.#n}};var j=u.STORAGE_KEYS.LIVE_COLOR,z=u.STORAGE_KEYS.IDENTITY_NAME;function It(){let s=u.COLLABORATION.COLORS,t=Math.floor(Math.random()*s.length);return s[t]??s[0]??"#3451B2"}var ct={color(){let s=localStorage.getItem(j);return s||(s=It(),localStorage.setItem(j,s)),s},setColor(s){localStorage.setItem(j,s)},name(){return localStorage.getItem(z)??""},setName(s){let t=s.trim();t?localStorage.setItem(z,t):localStorage.removeItem(z)},author(){let s={color:this.color()},t=this.name();return t&&(s.name=t),s}};function dt(s,t){let e=[],n="",o=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,t?{acceptNode:r=>t(r)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}:null),i=o.nextNode();for(;i;){let r=i;e.push({node:r,start:n.length}),n+=r.data,i=o.nextNode()}return{text:n,segments:e}}function ht(s,t,e,n){if(e.nodeType===Node.TEXT_NODE){let a=s.find(l=>l.node===e);return a?a.start+n:0}let o=e.childNodes[n]??null;if(o){for(let a of s)if(o===a.node||o.nodeType!==Node.TEXT_NODE&&o.contains(a.node)||o.compareDocumentPosition(a.node)&Node.DOCUMENT_POSITION_FOLLOWING)return a.start;return t}let i=s.filter(a=>e.contains(a.node)),r=i[i.length-1];return r?r.start+r.node.data.length:t}function Ht(s,t,e){let n=a=>s.find(l=>a>=l.start&&a<=l.start+l.node.data.length),o=n(t),i=n(e);if(!o||!i)return null;let r=document.createRange();return r.setStart(o.node,t-o.start),r.setEnd(i.node,e-i.start),r}function Rt(s,t){let e=0;for(;e<s.length&&e<t.length&&s[s.length-1-e]===t[t.length-1-e];)e++;return e}function Pt(s,t){let e=0;for(;e<s.length&&e<t.length&&s[e]===t[e];)e++;return e}var X={describe(s,t,e){let{text:n,segments:o}=dt(s,e),i=ht(o,n.length,t.startContainer,t.startOffset),r=ht(o,n.length,t.endContainer,t.endOffset);return{position:i,exact:n.slice(i,r),prefix:n.slice(Math.max(0,i-32),i),suffix:n.slice(r,r+32)}},anchor(s,t,e,n){if(!t.exact)return null;let{text:o,segments:i}=dt(s,e),r=[];for(let h=o.indexOf(t.exact);h!==-1;h=o.indexOf(t.exact,h+1))r.push(h);if(r.length===0)return null;let a=n?.ignorePosition?0:1,l=r[0]??0,c=-1/0;for(let h of r){let f=o.slice(Math.max(0,h-t.prefix.length),h),E=o.slice(h+t.exact.length,h+t.exact.length+t.suffix.length),m=Rt(f,t.prefix)+Pt(E,t.suffix)-a*Math.abs(h-t.position)/1e4;m>c&&(c=m,l=h)}return Ht(i,l,l+t.exact.length)}};var G=class{#t=[];#n;#e;#s=null;#i;constructor(t,e,n){this.#n=t,this.#e=e,this.#i=n}setRoot(t){this.#e=t}async load(){this.#t=await this.#n.loadAnnotations(),d.log("AnnotationManager",`Loaded ${this.#t.length} annotations`)}getAll(){return[...this.#t]}getById(t){return this.#t.find(e=>e.id===t)??null}replaceAll(t){this.#t=[...t],this.#o("replace",t),d.log("AnnotationManager",`Replaced annotations in memory: ${t.length}`)}getAllInDocumentOrder(){let t=new Map,e=0;return this.#e.querySelectorAll("[data-annotation-id]").forEach(n=>{let o=n.dataset.annotationId;o&&!t.has(o)&&t.set(o,e++)}),[...this.#t].sort((n,o)=>{let i=t.get(n.id)??Number.POSITIVE_INFINITY,r=t.get(o.id)??Number.POSITIVE_INFINITY;if(i!==r)return i-r;let a=typeof n.anchor.position=="number"?n.anchor.position:Number.POSITIVE_INFINITY,l=typeof o.anchor.position=="number"?o.anchor.position:Number.POSITIVE_INFINITY;return a!==l?a-l:n.createdAt-o.createdAt})}getAllInSection(t){let n=Array.from(this.#e.querySelectorAll("h1, h2, h3, h4, h5, h6")).find(i=>i.id===t)?.closest(".heading-section");if(!n||!this.#e.contains(n))return[];let o=new Set;return n.querySelectorAll("[data-annotation-id]").forEach(i=>{let r=i.dataset.annotationId;r&&o.add(r)}),this.getAllInDocumentOrder().filter(i=>o.has(i.id))}headingForAnnotation(t){let e=this.#e.querySelector(`[data-annotation-id="${t}"]`);if(!e)return null;let n=e;for(;n;){let o=n.previousElementSibling;for(;o;){if(/^H[1-6]$/.test(o.tagName)){let i=o.cloneNode(!0);return i.querySelectorAll(".viewed-checkbox-label, .viewed-toolbar, .section-actions, .section-action, .section-action-separator").forEach(r=>r.remove()),{level:parseInt(o.tagName.substring(1),10),text:(i.textContent??"").trim()}}o=o.previousElementSibling}if(n=n.parentElement,n===this.#e)break}return null}getGroupedByHeading(t){let e=t?new Set(t):null,n=this.getAllInDocumentOrder().filter(r=>!e||e.has(r.id)),o=[],i=null;return n.forEach(r=>{let a=this.headingForAnnotation(r.id),l=a?`${a.level}|${a.text}`:"\0none";l!==i&&(o.push({heading:a,items:[]}),i=l);let c=o[o.length-1];c&&c.items.push(r)}),o}formatAnnotation(t){let e=t.text.trim().split(/\r?\n/).map(n=>`> ${n}`);return t.note&&t.note.trim()&&e.push("",t.note.trim()),e.join(`
`)+`
`}formatAsMarkdown(t={}){let e=t.ids?new Set(t.ids):null,n=this.getAllInDocumentOrder().filter(r=>!e||e.has(r.id));if(n.length===0)return"";let o=r=>r.replace(/\r?\n/g,`
> `),i=[];return n.forEach(r=>{i.push(`"${r.text.trim()}"`),r.note&&r.note.trim()&&i.push(`> ${o(r.note.trim())}`),i.push("")}),i.join(`
`).trimEnd()+`
`}async add(t,e=!1){let n=this.#t.findIndex(i=>i.id===t.id);n>=0?this.#t[n]=t:this.#t.push(t);let o=null;return e||(o=await this.#n.saveAnnotation(t)),this.#o("add",t),d.log("AnnotationManager",`Added annotation: ${t.id}${e?" (from remote)":""}`),o}async delete(t,e=!1){let n=this.#t.findIndex(i=>i.id===t);if(n<0)return d.warn("AnnotationManager",`Annotation not found: ${t}`),null;let o=this.#t[n];return o?(this.#t.splice(n,1),e||await this.#n.deleteAnnotation(t),this.#o("delete",o),d.log("AnnotationManager",`Deleted annotation: ${t}${e?" (from remote)":""}`),o):null}async clear(t=!1){let e=[...this.#t];this.#t=[],t||await this.#n.clearAnnotations(),this.#o("clear",e),d.log("AnnotationManager",`Cleared all annotations${t?" (from remote)":""}`)}applyToDOM(t=null){let e=t??this.#t;if(e.length===0)return;let n=[...e].sort((o,i)=>o.anchor.position-i.anchor.position);n.forEach(o=>this.#a(o)),d.log("AnnotationManager",`Applied ${n.length} annotations to DOM`)}clearDOM(){this.#e.querySelectorAll("[data-annotation-id]").forEach(t=>this.#r(t)),d.log("AnnotationManager","Cleared annotations from DOM")}removeFromDOM(t){this.#e.querySelectorAll(`[data-annotation-id="${t}"]`).forEach(e=>this.#r(e)),d.log("AnnotationManager",`Removed annotation from DOM: ${t}`)}#r(t){let e=t.parentNode;if(e){for(;t.firstChild;)e.insertBefore(t.firstChild,t);e.removeChild(t),e.normalize?.()}}createAnnotation(t,e,n,o=null){let i=X.describe(this.#e,t,this.#i);return{id:`anno-${lt.uuid()}`,type:e,tagName:n,anchor:i,text:i.exact,note:o,createdAt:Date.now(),author:ct.author()}}onChange(t){this.#s=t}#a(t){if(this.#e.querySelector(`[data-annotation-id="${t.id}"]`))return;let n=X.anchor(this.#e,t.anchor,this.#i,this.#i?{ignorePosition:!0}:void 0);if(!n){d.warn("AnnotationManager",`Anchor text not found (orphaned): ${t.id}`);return}try{this.#l(n,t)}catch(o){d.error("AnnotationManager",`Failed to apply annotation ${t.id}:`,o)}}#l(t,e){let n=t.startContainer,o=t.endContainer,i=t.startOffset,r=t.endOffset,a=t.commonAncestorContainer,l=a.nodeType===3?a.parentNode:a;if(!l)return;let c=this.#i,h=[],f=document.createTreeWalker(l,NodeFilter.SHOW_TEXT,c?{acceptNode:m=>c(m)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}:null),E=f.nextNode();for(;E;){let m=E;if(t.intersectsNode(m)){let p=m===n?i:0,T=m===o?r:m.length;p<T&&h.push({node:m,start:p,end:T})}E=f.nextNode()}if(h.length!==0)for(let{node:m,start:p,end:T}of h){let w=m;T<w.length&&w.splitText(T),p>0&&(w=w.splitText(p));let y=document.createElement(e.tagName);y.className=e.type,y.dataset.annotationId=e.id,e.author?.color&&y.style.setProperty("--anno-author",e.author.color),e.author?.name&&(y.dataset.authorName=e.author.name),y.dataset.authorTime=String(e.createdAt),e.note&&(y.dataset.note=e.note,y.classList.add("has-note"));let _=w.parentNode;_&&(_.insertBefore(y,w),y.appendChild(w))}}#o(t,e){this.#s&&this.#s({action:t,data:e,annotations:this.getAll()})}};var b={normalize(s){return s.replace(/\s+/g," ").trim()},decodeEntities(s){return s.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&#39;/g,"'")},escape(s){let t=document.createElement("div");return t.textContent=s,t.innerHTML},escapeRegex(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}};function ut(s,t,e="text/markdown"){let n=new Blob([t],{type:`${e};charset=utf-8`}),o=URL.createObjectURL(n),i=document.createElement("a");i.href=o,i.download=s,i.style.display="none",document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(o),0)}function mt(s,t="notes"){return`${(s??"").trim().replace(/^.*[\\/]/,"").replace(/\.[^.]+$/,"").replace(/[\s]+/gu,"-").replace(/[^\p{L}\p{N}\-_.]+/gu,"").replace(/^[-.]+|[-.]+$/g,"")||t}.md`}var $t=window.__MARKON_I18N__?.t||(s=>s),Dt=6500,Ft=260,Bt=()=>{let s=document.querySelector(".markon-notification-stack");return s||(s=document.createElement("div"),s.className="markon-notification-stack",s.setAttribute("aria-live","polite"),s.setAttribute("aria-atomic","false"),document.body.appendChild(s),s)},Gt=()=>{let s=document.querySelector(".markon-notification-stack");s&&s.children.length===0&&s.remove()};function gt(s,t={}){let e=s.trim();if(!e)return null;let n=document.createElement("div");n.className=`markon-notification markon-modal-frame is-${t.variant??"info"}`,n.setAttribute("role","status");let o=document.createElement("div");o.className="markon-notification-content";let i=document.createElement("span");i.className="markon-notification-dot",i.setAttribute("aria-hidden","true");let r=document.createElement("div");r.className="markon-notification-body";let a=t.title?.trim();if(a){let p=document.createElement("div");p.className="markon-notification-title",p.textContent=a,r.appendChild(p)}let l=document.createElement("div");if(l.className="markon-notification-message",l.textContent=e,r.appendChild(l),o.append(i,r),t.dismissible??!0){let p=document.createElement("button");p.className="markon-notification-close",p.type="button",p.setAttribute("aria-label",$t("web.notification.dismiss")),p.textContent="\xD7",o.appendChild(p),p.addEventListener("click",()=>E())}n.appendChild(o),Bt().appendChild(n);let h=!1,f=null,E=()=>{h||(h=!0,f!==null&&window.clearTimeout(f),n.style.maxHeight=`${n.offsetHeight}px`,requestAnimationFrame(()=>{n.classList.remove("is-visible"),n.classList.add("is-leaving"),n.style.maxHeight="0px"}),window.setTimeout(()=>{n.remove(),Gt()},Ft))};requestAnimationFrame(()=>{n.style.maxHeight=`${n.scrollHeight}px`,n.classList.add("is-visible")});let m=t.duration??Dt;return m>0&&(f=window.setTimeout(E,m)),{element:n,dismiss:E}}var v=(s,...t)=>N.t(s,...t),ft="markon.editor.split",pt="markon.editor.layout",Wt=22.4,W=class{#t;#n=null;#e=null;#s=null;#i=null;#r=null;#a=null;#l=!1;#o="";#d=null;#c=null;#u=null;#f="edit";#h="split";#v=!1;#m=null;#g="edit";#T="notes.md";#b=null;#E=null;#p(t={}){let e=this.#E?.signal;return e?{...t,signal:e}:t}constructor(t){this.#t=t,d.log("EditorManager","Initialized for file:",t)}isDirty(){return this.#l}isOpen(){return this.#n!==null}async open(t={}){this.#g=t.mode??"edit",this.#b=t.onBack??null;let e;if(this.#g==="export")e=t.content??"",this.#T=mt(t.exportFileName);else if(e=await this.#w(),e===null){d.error("EditorManager","Failed to fetch file content"),alert("Failed to load file content. Please ensure edit feature is enabled.");return}this.#o=e,this.#O(e),this.#M(),this.#H(),document.documentElement.classList.add("markon-scroll-lock"),t.line&&t.line>0?this.#F(t.line):t.selectedText?.trim()?this.#D(t.selectedText.trim()):this.#y(),d.log("EditorManager",`Editor opened (${this.#g} mode)`)}close(){if(this.#n){if(this.#g==="edit"&&this.#l&&!confirm("You have unsaved changes. Close anyway?"))return;document.removeEventListener("keydown",this.#A),this.#m&&(this.#m(),this.#m=null),this.#E?.abort(),this.#E=null,document.body.style.cursor="",document.body.style.userSelect="",this.#c!==null&&(clearTimeout(this.#c),this.#c=null);let t=this.#g==="export";this.#n.remove(),this.#n=null,document.documentElement.classList.remove("markon-scroll-lock"),this.#e=null,this.#s=null,this.#r=null,this.#a=null,this.#d=null,this.#l=!1,this.#o="",t||window.location.reload(),d.log("EditorManager","Editor closed")}}async save(){if(!this.#e)return;let t=this.#e.value;if(this.#g==="export"){ut(this.#T,t),this.#r&&st(this.#r,v("web.export.downloaded")),this.#o=t,this.#l=!1;return}await this.#N(t)&&(this.#o=t,this.#l=!1,this.#C(),this.#_())}async#w(){try{let t=document.getElementById("original-markdown-data");return t?JSON.parse(t.textContent??'""'):(d.warn("EditorManager","Original Markdown not found in page"),"")}catch(t){return d.error("EditorManager","Error fetching content:",t),null}}async#N(t){try{this.#I(!0);let e=R.get(u.META_TAGS.WORKSPACE_ID)??"",n=R.get("save-token")??"",o={workspace_id:e,file_path:this.#t,content:t},i=await fetch("/api/save",{method:"POST",headers:{"Content-Type":"application/json","X-Markon-Token":n},body:JSON.stringify(o)});if(!i.ok){let a=await i.text();return d.error("EditorManager","Save failed:",i.status,a),this.#S(a||`Server error (${i.status})`),!1}let r=await i.json();return r.success?(d.log("EditorManager","File saved successfully"),!0):(d.error("EditorManager","Save failed:",r.message),this.#S(r.message??""),!1)}catch(e){d.error("EditorManager","Save error:",e);let n=e instanceof Error?e.message:String(e);return alert(`Error saving file: ${n}`),!1}finally{this.#I(!1)}}#S(t){t.includes("read-only")?alert(v("web.editor.err.readonly")):t.includes("Access denied")?alert(v("web.editor.err.denied")):t.includes("not enabled")?alert(v("web.editor.err.disabled")):t.includes("Only Markdown")?alert(v("web.editor.err.notmd")):alert(`${v("web.editor.err.save")}${t}`)}#O(t){let e=this.#g==="export",n=e?this.#T:this.#t,o=e&&this.#b?`<button class="editor-back-btn">${v("web.export.back")}</button>`:"",i=e?`<button class="editor-copy-btn">${v("web.export.copytext")}</button>`:"",r=e?`<button class="editor-save-btn editor-download-btn">${v("web.export.download")}</button>`:`<button class="editor-save-btn" style="display: none;">${v("web.editor.save")}</button>`,a=document.createElement("div");a.className=e?"editor-modal editor-modal-export":"editor-modal",a.innerHTML=`
            <div class="editor-header">
                <button class="editor-close" title="${v("web.editor.close.tip")}">\u2715</button>
                ${o}
                <span class="editor-file-name">${b.escape(n)}</span>
                <div class="editor-tab-bar">
                    <button class="editor-tab editor-tab-edit active" data-tab="edit">Edit</button>
                    <button class="editor-tab editor-tab-preview" data-tab="preview">Preview</button>
                </div>
                <div class="editor-layout-toggle" title="Toggle layout">
                    <button class="editor-layout-btn" data-layout="split" title="Split view">
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
                            <rect x="1" y="2" width="6" height="12" rx="1" stroke="currentColor" stroke-width="1.5"/>
                            <rect x="9" y="2" width="6" height="12" rx="1" stroke="currentColor" stroke-width="1.5"/>
                        </svg>
                    </button>
                    <button class="editor-layout-btn" data-layout="full" title="Full-width editor">
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
                            <rect x="1" y="2" width="14" height="12" rx="1" stroke="currentColor" stroke-width="1.5"/>
                        </svg>
                    </button>
                </div>
                ${i}
                ${r}
            </div>
            <div class="editor-body">
                <div class="editor-split">
                    <div class="editor-pane editor-pane-source">
                        <div class="editor-container">
                            <div class="editor-line-numbers"></div>
                            <div class="editor-text-container">
                                <pre class="editor-highlight-layer"><code></code></pre>
                                <textarea class="editor-textarea" spellcheck="false"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="editor-split-divider" title="Drag to resize"></div>
                    <div class="editor-pane editor-pane-preview">
                        <div class="editor-preview-content markdown-body"></div>
                    </div>
                </div>
            </div>
        `,document.body.appendChild(a),this.#n=a,this.#e=a.querySelector(".editor-textarea"),this.#s=a.querySelector(".editor-line-numbers"),this.#i=a.querySelector(".editor-highlight-layer code"),this.#r=a.querySelector(".editor-save-btn"),this.#a=a.querySelector(".editor-close"),this.#d=a.querySelector(".editor-preview-content"),this.#e&&(this.#e.value=t),this.#Y(),this.#E=new AbortController,this.#q(),this.#j(),this.#$(),this.#L(0),this.#z(),this.#X(),this.#k()}#M(){this.#a?.addEventListener("click",()=>{this.close()}),this.#r?.addEventListener("click",()=>{this.save()});let t=this.#n?.querySelector(".editor-copy-btn"),e=()=>!!this.#e&&this.#e.selectionStart!==this.#e.selectionEnd,n=()=>{t&&(t.textContent=v(e()?"web.export.copyselection":"web.export.copytext"))};if(t?.addEventListener("click",()=>{let a=this.#e;if(!a||!t)return;let l=e()?a.value.slice(a.selectionStart,a.selectionEnd):a.value;I(l).then(c=>{t.textContent=v(c?"web.export.copied":"web.export.failed"),t.classList.add("is-flashing"),window.setTimeout(()=>{t.classList.remove("is-flashing"),n()},1500)})}),n(),this.#n?.querySelector(".editor-back-btn")?.addEventListener("click",()=>{let a=this.#b;this.close(),a?.()}),!this.#e)return;let o=this.#e;["select","keyup","mouseup"].forEach(a=>o.addEventListener(a,n)),o.addEventListener("keydown",a=>{(a.ctrlKey||a.metaKey)&&a.key==="s"&&(a.preventDefault(),this.save())}),document.addEventListener("keydown",this.#A),o.addEventListener("scroll",()=>{this.#s&&(this.#s.scrollTop=o.scrollTop),this.#i&&this.#i.parentElement&&(this.#i.parentElement.scrollTop=o.scrollTop,this.#i.parentElement.scrollLeft=o.scrollLeft)});let i=null,r=-1;o.addEventListener("input",()=>{this.#l=o.value!==this.#o,this.#C(),this.#_(),i===null&&(i=requestAnimationFrame(()=>{i=null;let a=o.value.split(`
`).length;a!==r&&(r=a,this.#H()),this.#$()}),this.#L(150))})}#A=t=>{t.key==="Escape"&&this.#n&&this.close()};#y(){this.#e&&(this.#e.focus(),this.#e.setSelectionRange(0,0))}#C(){this.#g!=="export"&&this.#r&&(this.#l?(this.#r.style.display="block",this.#r.classList.add("has-changes")):(this.#r.style.display="none",this.#r.classList.remove("has-changes")))}#_(){if(this.#g==="export")return;let t=this.#n?.querySelector(".editor-file-name");if(!t)return;let e=this.#t.replace(/\*$/,"");this.#l?t.textContent=e+"*":t.textContent=e}#I(t){this.#r&&(this.#r.disabled=t,this.#r.textContent=t?"Saving...":v("web.editor.save.tip"))}#H(){if(!this.#e||!this.#s)return;let t=this.#e.value.split(`
`).length,e=this.#s;for(;e.childElementCount>t;)e.lastElementChild?.remove();for(let n=e.childElementCount+1;n<=t;n++){let o=document.createElement("div");o.className="editor-line-number",o.textContent=String(n),e.appendChild(o)}}#D(t){if(!this.#e)return;let e=this.#e.value,n=this.#B(e,t);if(n!==-1){this.#e.focus();let o=this.#G(e,n,t);this.#e.setSelectionRange(n,n+o);let r=e.substring(0,n).split(`
`).length;this.#R(r),d.log("EditorManager",`Selected text at index ${n}, line ${r}`)}else d.warn("EditorManager",`Text not found: "${t}"`),this.#y(),gt(v("web.editor.selection_not_found"),{variant:"warning"})}#F(t){if(!this.#e)return;let e=this.#e.value.split(`
`),n=Math.min(t,e.length),o=e.slice(0,n-1).reduce((r,a)=>r+a.length+1,0),i=o+(e[n-1]||"").length;this.#e.focus(),this.#e.setSelectionRange(o,i),this.#R(n),d.log("EditorManager",`Jumped to line ${n}`)}#R(t){this.#e&&(this.#e.scrollTop=Math.max(0,(t-3)*Wt),this.#s&&(this.#s.scrollTop=this.#e.scrollTop))}#B(t,e){let n=t.indexOf(e);if(n!==-1)return n;let o=e.split(/\s+/).filter(r=>r.length>0);if(o.length>1){let r=o.map(c=>b.escapeRegex(c)).join("[\\s`*_\\[\\]()]*"),a=new RegExp(r,"i"),l=t.match(a);if(l)return t.indexOf(l[0])}let i=e.replace(/`/g,"").replace(/\*\*/g,"").replace(/__/g,"").replace(/\*/g,"").replace(/_/g,"").trim();return i!==e&&(n=t.indexOf(i),n!==-1)?n:-1}#G(t,e,n){if(t.substring(e,e+n.length)===n)return n.length;let i=b.normalize(n),r=i.length,a=n.length*3,l=t.substring(e,e+a),c="",h=0,f=!1,E=!1;for(let m=0;m<l.length;m++){let p=l[m],T=l[m+1];if(p==="`"){f=!f,h++;continue}if(p==="["){E=!0,h++;continue}if(E){if(p==="]"&&(T==="("||T==="[")){h++;continue}if(p===")"&&l.substring(Math.max(0,m-10),m).includes("](")){E=!1,h++;continue}}if(!f&&(p==="*"||p==="_")&&(p===T||T&&T!==" "&&T!==`
`)){h++;continue}c+=p??"",h++;let w=b.normalize(c);if(w===i)return h;if(w.length>r*1.5)break}return Math.min(n.length,l.length)}#L(t=150){this.#c!==null&&clearTimeout(this.#c),this.#c=setTimeout(()=>{this.#c=null,this.#W()},t)}async#W(){if(!this.#d||!this.#e)return;let t=this.#e.value;try{let e=await fetch("/api/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t})});if(!e.ok)return;let n=await e.json();this.#d.innerHTML=n.html,n.has_math&&this.#K()}catch(e){d.warn("EditorManager","Preview update failed:",e)}}#K(){if(this.#d){if(window.markonRenderMath){window.markonRenderMath(this.#d);return}this.#U().then(()=>{this.#d&&window.markonRenderMath?.(this.#d)})}}#U(){return window.markonRenderMath?Promise.resolve():this.#u?this.#u:(this.#V("/_/js/katex/katex.min.css"),this.#u=this.#P("/_/js/katex/katex.min.js").then(()=>this.#P("/_/js/math-render.js")).catch(t=>{this.#u=null,d.warn("EditorManager","Math renderer failed to load:",t)}),this.#u)}#V(t){if(document.querySelector(`link[rel="stylesheet"][href="${t}"]`))return;let e=document.createElement("link");e.rel="stylesheet",e.href=t,document.head.appendChild(e)}#P(t){return document.querySelector(`script[src="${t}"]`)?Promise.resolve():new Promise((e,n)=>{let o=document.createElement("script");o.src=t,o.onload=()=>e(),o.onerror=()=>n(new Error(`Failed to load ${t}`)),document.head.appendChild(o)})}#Y(){let t=this.#n?.querySelector(".editor-split");if(!t)return;let e=localStorage.getItem(ft),n=e?parseFloat(e):50,o=Math.min(80,Math.max(20,n));t.style.setProperty("--editor-split-left",`${o}%`)}#q(){let t=this.#n?.querySelector(".editor-split-divider"),e=this.#n?.querySelector(".editor-split");if(!t||!e)return;let n=!1,o=i=>{if(!n)return;let r=e.getBoundingClientRect(),a=(i-r.left)/r.width*100;a=Math.min(80,Math.max(20,a)),e.style.setProperty("--editor-split-left",`${a}%`),localStorage.setItem(ft,a.toString())};t.addEventListener("mousedown",i=>{n=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none",i.preventDefault()}),document.addEventListener("mousemove",i=>o(i.clientX),this.#p()),document.addEventListener("mouseup",()=>{n&&(n=!1,document.body.style.cursor="",document.body.style.userSelect="")},this.#p()),t.addEventListener("touchstart",i=>{n=!0,i.preventDefault()},{passive:!1}),document.addEventListener("touchmove",i=>{let r=i.touches[0];n&&r&&o(r.clientX)},this.#p({passive:!0})),document.addEventListener("touchend",()=>{n=!1},this.#p())}#j(){let t=this.#n?.querySelectorAll(".editor-tab"),e=this.#n?.querySelector(".editor-pane-source"),n=this.#n?.querySelector(".editor-pane-preview");!t||!e||!n||(window.innerWidth<=768&&(e.style.display="flex",n.style.display="none"),window.addEventListener("resize",()=>{window.innerWidth>768?(e.style.display="",n.style.display=""):this.#f==="edit"?(e.style.display="flex",n.style.display="none"):(e.style.display="none",n.style.display="flex")},this.#p()),t.forEach(o=>{o.addEventListener("click",()=>{let i=o.dataset.tab;i!=="edit"&&i!=="preview"||(this.#f=i,t.forEach(r=>r.classList.toggle("active",r.dataset.tab===this.#f)),window.innerWidth<=768&&(this.#f==="edit"?(e.style.display="flex",n.style.display="none"):(e.style.display="none",n.style.display="flex",this.#L(0))))})}))}#z(){let t=localStorage.getItem(pt);this.#h=t==="full"?"full":"split",this.#x(this.#h)}#x(t){if(!this.#n)return;let e=this.#n.querySelector(".editor-split"),n=this.#n.querySelector(".editor-split-divider"),o=this.#n.querySelector(".editor-pane-preview"),i=this.#n.querySelector(".editor-pane-source");t==="full"?(e&&e.classList.add("editor-layout-full"),window.innerWidth>768&&(n&&(n.style.display="none"),o&&(o.style.display="none"),i&&(i.style.width="100%"))):(e&&e.classList.remove("editor-layout-full"),window.innerWidth>768&&(n&&(n.style.display=""),o&&(o.style.display=""),i&&(i.style.width=""))),this.#n.querySelectorAll(".editor-layout-btn").forEach(r=>{r.classList.toggle("active",r.dataset.layout===t)})}#X(){let t=this.#n?.querySelectorAll(".editor-layout-btn");t&&(t.forEach(e=>{e.addEventListener("click",()=>{let n=e.dataset.layout;n!=="split"&&n!=="full"||n!==this.#h&&(this.#h=n,localStorage.setItem(pt,n),this.#x(n),this.#k(),n==="split"&&this.#L(0))})}),window.addEventListener("resize",()=>{this.#x(this.#h),this.#k()},this.#p()))}#k(){if(this.#m&&(this.#m(),this.#m=null),this.#h!=="split"||window.innerWidth<=768)return;let t=this.#e,e=this.#n?.querySelector(".editor-pane-preview");if(!t||!e)return;let n=(r,a)=>{if(this.#v)return;let l=r.scrollHeight-r.clientHeight;if(l<=0)return;let c=r.scrollTop/l,h=a.scrollHeight-a.clientHeight;h<=0||(this.#v=!0,a.scrollTop=c*h,requestAnimationFrame(()=>{this.#v=!1}))},o=()=>n(t,e),i=()=>n(e,t);t.addEventListener("scroll",o,{passive:!0}),e.addEventListener("scroll",i,{passive:!0}),this.#m=()=>{t.removeEventListener("scroll",o),e.removeEventListener("scroll",i)}}#$(){if(!this.#e||!this.#i)return;let t=this.#e.value,e=this.#J(t);this.#i.innerHTML=e+`
`}#J(t){let e=b.escape(t);return e=e.replace(/^(#{1,6})\s+(.+)$/gm,'<span class="md-header">$1</span> <span class="md-header-text">$2</span>').replace(/(\*\*|__)(.*?)\1/g,'<span class="md-bold">$1$2$1</span>').replace(/(\*|_)(.*?)\1/g,'<span class="md-italic">$1$2$1</span>').replace(/`([^`]+)`/g,'<span class="md-code">`$1`</span>').replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<span class="md-link">[$1]($2)</span>').replace(/!\[([^\]]*)\]\(([^)]+)\)/g,'<span class="md-image">![$1]($2)</span>').replace(/^(&gt;+)\s+(.+)$/gm,'<span class="md-quote">$1 $2</span>').replace(/^([\s]*)([-*+])\s+(.+)$/gm,'$1<span class="md-list">$2</span> $3').replace(/^([\s]*)(\d+\.)\s+(.+)$/gm,'$1<span class="md-list">$2</span> $3').replace(/^([-*_]{3,})$/gm,'<span class="md-hr">$1</span>').replace(/^```(\w*)$/gm,'<span class="md-code-fence">```$1</span>'),e}};var K=class{#t;#n;constructor(t){this.#t=Array.from({length:t},(e,n)=>n),this.#n=Array(t).fill(0)}#e(t,e){let n=t[e];if(n===void 0)throw new RangeError(`UnionFind index ${e} is outside bounds`);return n}find(t){let e=this.#e(this.#t,t);return e!==t&&(this.#t[t]=this.find(e)),this.#e(this.#t,t)}union(t,e){let n=this.find(t),o=this.find(e);if(n===o)return;let i=this.#e(this.#n,n),r=this.#e(this.#n,o);i<r?this.#t[n]=o:i>r?this.#t[o]=n:(this.#t[o]=n,this.#n[n]=i+1)}};var Et=".section-content-hidden",Kt=["h1.section-collapsed","h2.section-collapsed","h3.section-collapsed","h4.section-collapsed","h5.section-collapsed","h6.section-collapsed"].join(","),U=class{calculate(t){if(t.length===0)return[];let e=this.#t(t),n=e.filter(i=>i.visible),o=this.#n(n);return this.#s(n,o),this.#i(n),e}anchorElementFor(t){return this.#a(t).element}anchorRectFor(t){return this.anchorElementFor(t).getBoundingClientRect()}isAnchorInViewport(t){let e=this.#a(t);return e.resolved&&this.#r(e.element.getBoundingClientRect())}#t(t){let e=window.scrollY||window.pageYOffset;return t.map((n,o)=>{let i=this.#a(n),r=i.element,a=r.getBoundingClientRect(),l=a.top+e,c=n.element.offsetHeight||80;return{element:n.element,anchorElement:r,idealTop:l,currentTop:l,height:c,index:o,id:n.highlightId,visible:i.resolved&&this.#r(a)}})}#n(t){let e=new K(t.length),n=t.map((i,r)=>({idx:r,idealTop:i.idealTop})).sort((i,r)=>i.idealTop-r.idealTop);for(let i=0;i<n.length-1;i++){let r=n[i],a=n[i+1];!r||!a||Math.abs(a.idealTop-r.idealTop)<=u.THRESHOLDS.NOTE_CLUSTER&&e.union(r.idx,a.idx)}let o=new Map;return t.forEach((i,r)=>{let a=e.find(r),l=o.get(a);l||(l=[],o.set(a,l)),l.push(r)}),o}#e(t,e){let n=t[e];if(!n)throw new RangeError(`Note index ${e} is outside layout input`);return n}#s(t,e){e.forEach(n=>{if(n.length>1){let i=Math.min(...n.map(r=>this.#e(t,r).idealTop));n.sort((r,a)=>r-a),n.forEach(r=>{let a=this.#e(t,r);a.currentTop=i,i+=a.height+u.THRESHOLDS.NOTE_MIN_SPACING})}})}#i(t){for(let e=1;e<t.length;e++){let n=t[e-1],o=t[e];if(!n||!o)continue;let i=n.currentTop+n.height+u.THRESHOLDS.NOTE_MIN_SPACING;o.currentTop<i&&(o.currentTop=i)}}#r(t){let e=document.documentElement.clientHeight||window.innerHeight;return t.bottom>=0&&t.top<=e}#a(t){if(!this.#l(t.highlightElement))return{element:t.highlightElement,resolved:!0};let e=this.#o(t.highlightElement);return{element:e??t.highlightElement,resolved:e!==null}}#l(t){return t.closest(Et)!==null}#o(t){let e=t.closest(".markdown-body")??document.body,n=Array.from(e.querySelectorAll(Kt)).filter(o=>!o.closest(Et)).filter(o=>this.#d(o,t));return n.sort((o,i)=>this.#c(i)-this.#c(o)),n[0]??null}#d(t,e){let n=this.#c(t),o=t.nextElementSibling;for(;o;){if(this.#c(o)<=n)return!1;if(o===e||o.contains(e))return!0;o=o.nextElementSibling}return!1}#c(t){let e=/^H([1-6])$/i.exec(t.tagName);return e?.[1]?Number(e[1]):Number.POSITIVE_INFINITY}};var $=(s,...t)=>N.t(s,...t),vt="http://www.w3.org/2000/svg",J='viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"',Ut=`<svg ${J}><rect x="5.5" y="5.5" width="8" height="8" rx="1.5"/><path d="M3.5 10.5H3a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1h6.5a1 1 0 0 1 1 1v.5"/></svg>`,Vt='viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"',Yt=`<svg ${Vt}><path d="M6.4 9.6l3.2-3.2"/><path d="M9 4.2l.7-.7a2.45 2.45 0 1 1 3.5 3.5l-1.55 1.55a2.45 2.45 0 0 1-3.4.08"/><path d="M7 11.8l-.7.7a2.45 2.45 0 1 1-3.5-3.5l1.55-1.55a2.45 2.45 0 0 1 3.4-.08"/></svg>`,qt=`<svg ${J}><path d="M2.5 13.5l1-3.2 7.3-7.3a1.3 1.3 0 0 1 1.8 1.8l-7.3 7.3z"/><path d="M9.5 4.5l2 2"/></svg>`,jt=`<svg ${J}><path d="M3 4.5h10"/><path d="M6.5 4.5V3a1 1 0 0 1 1-1h1a1 1 0 0 1 1 1v1.5"/><path d="M4.5 4.5l.6 8a1 1 0 0 0 1 .9h3.8a1 1 0 0 0 1-.9l.6-8"/><path d="M6.8 7v4M9.2 7v4"/></svg>`;function zt(s){let t=s,e="";for(;/[.,;:!?)]$/.test(t);)e=t.slice(-1)+e,t=t.slice(0,-1);return{core:t,tail:e}}function Tt(s){let t=/\bhttps?:\/\/[^\s<>"'`]+/gi,e=[],n=0;for(let o of s.matchAll(t)){let i=o[0]??"",r=o.index??0,{core:a,tail:l}=zt(i);if(!a)continue;try{let h=new URL(a);if(h.protocol!=="http:"&&h.protocol!=="https:")continue}catch{continue}e.push(b.escape(s.slice(n,r)));let c=b.escape(a);e.push(`<a href="${c}" target="_blank" rel="noopener noreferrer">${c}</a>`),e.push(b.escape(l)),n=r+i.length}return e.push(b.escape(s.slice(n))),e.join("")}var V=class{#t;#n;#e=[];#s;#i=null;#r=null;#a=null;#l=null;#o=!1;#d;#c=null;constructor(t,e,n={}){this.#t=t,this.#n=e,this.#s=new U,this.#d=n.marginCards??!0}setMarkdownBody(t){this.#n=t}render(){this.clear();let t=this.#n.querySelectorAll(".has-note[data-annotation-id]"),e=this.#v(t);if(e.length===0)return;let n=this.#t.getAll(),o=new Map(n.map(i=>[i.id,i]));if(e.forEach(i=>{let r=i.dataset.annotationId;if(!r)return;let a=o.get(r);if(!a?.note)return;let l=this.#g(a);this.#d&&document.body.appendChild(l),this.#e.push({element:l,highlightId:a.id,highlightElement:i,note:a.note})}),!this.#d){d.log("NoteManager",`Tracked ${this.#e.length} notes (popup-only)`);return}this.#T(),this.#i&&(this.#e.some(r=>r.highlightId===this.#i)?(this.#w(this.#i),this.#M()):(this.#i=null,this.#y())),d.log("NoteManager",`Rendered ${this.#e.length} note cards`)}clear(){document.querySelectorAll(".note-card-margin").forEach(t=>t.remove()),this.#e=[]}getNoteCardsData(){return[...this.#e]}onActiveChange(t){this.#c=t}setupResponsiveLayout(){if(this.#o){this.#f();return}this.#o=!0;let t=()=>this.#u();window.addEventListener("scroll",t,{passive:!0}),window.addEventListener("resize",()=>{this.#u(),O.isNarrowScreen()&&document.querySelector(".note-popup")?.remove()}),document.addEventListener("markon:viewed-ready",()=>this.#u(),{once:!0}),this.#f(),d.log("NoteManager","Responsive layout setup complete")}#u(){this.#l===null&&(this.#l=window.requestAnimationFrame(()=>{this.#l=null,this.#T(),this.#M()}))}#f(){this.#u(),window.requestAnimationFrame(()=>this.#u()),window.viewedManager?.ready.then(()=>{this.#u()}).catch(()=>{}),typeof document<"u"&&document.fonts&&document.fonts.ready.then(()=>{this.#u()}).catch(()=>{})}#h(t){if(!document.body.classList.contains("markon-shared")||!t.author)return"";let e=(t.author.color||"").trim(),n=/^#[0-9a-f]{3,8}$/i.test(e)?e:"var(--markon-fg-muted)",o=t.author.name||$("web.author.anon"),i=new Date(t.createdAt),r=l=>String(l).padStart(2,"0"),a=`${i.getMonth()+1}/${i.getDate()} ${r(i.getHours())}:${r(i.getMinutes())}`;return`<div class="note-author"><span class="note-author-dot" style="background:${n}"></span><span class="note-author-name">${b.escape(o)}</span><span class="note-author-time">${a}</span></div>`}#v(t){let e=new Map;return t.forEach(n=>{let o=n.dataset.annotationId;if(!o)return;let i=!1,r=n.parentElement;for(;r&&r!==this.#n;){if(r.classList&&r.classList.contains("has-note")){i=!0;break}r=r.parentElement}e.has(o)&&i||e.set(o,n)}),Array.from(e.values())}#m(t){let e=$("web.note.edit"),n=$("web.note.delete"),o=$("web.export.copyitem"),i=$("web.note.copylink");return`
            <div class="note-actions">
                <button class="note-copy" data-annotation-id="${t}" title="${o}" aria-label="${o}">${Ut}</button>
                <button class="note-link" data-annotation-id="${t}" title="${i}" aria-label="${i}">${Yt}</button>
                <button class="note-edit" data-annotation-id="${t}" title="${e}" aria-label="${e}">${qt}</button>
                <button class="note-delete" data-annotation-id="${t}" title="${n}" aria-label="${n}">${jt}</button>
            </div>
        `}#g(t){let e=document.createElement("div");return e.className="note-card-margin",e.dataset.annotationId=t.id,e.innerHTML=`
            ${this.#m(t.id)}
            <div class="note-content">${Tt(t.note??"")}</div>
            ${this.#h(t)}
        `,e.style.position="absolute",e}#T(){this.#e.length!==0&&(O.isWideScreen()?this.#b():this.#E())}#b(){document.body.offsetHeight;let t=this.#s.calculate(this.#e),e=getComputedStyle(document.documentElement),n=parseFloat(e.getPropertyValue("--markon-note-width"))||u.DIMENSIONS.NOTE_CARD_WIDTH,o=parseFloat(e.getPropertyValue("--markon-rail-edge-gap"))||u.DIMENSIONS.NOTE_CARD_RIGHT_MARGIN,r=(document.documentElement.clientWidth||window.innerWidth)-n-o;t.forEach(a=>{if(!a.visible){a.element.style.display="none";return}a.element.style.left=`${r}px`,a.element.style.top=`${a.currentTop}px`,a.element.style.display="block"}),d.log("NoteManager",`Wide screen layout applied to ${t.length} notes`)}#E(){this.#e.forEach(t=>{t.element.style.display="none"}),d.log("NoteManager","Narrow screen layout applied (cards hidden)")}setActive(t){if(this.#i===t){this.clearActive();return}let e=this.#i,n=this.#N(t);this.#p(),this.#i=t,this.#S(t,e,n),this.#w(t),this.#M()}clearActive(){let t=this.#i;this.#p(),this.#i=null,t&&this.#S(null,t,null),this.#y()}getActiveAnnotationId(){return this.#i}#p(){document.querySelectorAll(".has-note.highlight-active, .note-card-margin.highlight-active").forEach(t=>t.classList.remove("highlight-active"))}#w(t){document.querySelector(`.note-card-margin[data-annotation-id="${t}"]`)?.classList.add("highlight-active"),this.#n.querySelectorAll(`.has-note[data-annotation-id="${t}"]`).forEach(n=>n.classList.add("highlight-active"))}#N(t){return this.#e.find(e=>e.highlightId===t)?.highlightElement??null}#S(t,e,n){this.#c?.({annotationId:t,previousAnnotationId:e,sourceElement:n})}#O(){if(this.#r&&document.body.contains(this.#r))return this.#r;let t=document.createElementNS(vt,"svg");t.classList.add("note-connector-svg"),t.setAttribute("aria-hidden","true"),t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.pointerEvents="none",t.style.overflow="visible";let e=document.createElementNS(vt,"path");return e.classList.add("note-connector-path"),e.setAttribute("fill","none"),t.appendChild(e),document.body.appendChild(t),this.#r=t,this.#a=e,t}#M(){let t=this.#i;if(!t||!O.isWideScreen()){this.#y();return}let e=this.#e.find(Mt=>Mt.highlightId===t);if(!e){this.#y();return}let n=e.element.getBoundingClientRect();if(n.width===0&&n.height===0){this.#y();return}let o=this.#A(t,e);if(!o){this.#y();return}let i=o,r=window.scrollX||window.pageXOffset,a=window.scrollY||window.pageYOffset,l=i.right+r,c=i.top+i.height/2+a,h=n.left+r,f=n.top+n.height/2+a,E=Math.max(40,(h-l)*.5),m=l+E,p=c,T=h-E,w=f,y=this.#O(),_=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth),nt=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);y.setAttribute("width",String(_)),y.setAttribute("height",String(nt)),y.setAttribute("viewBox",`0 0 ${_} ${nt}`),this.#a&&(this.#a.setAttribute("d",`M ${l} ${c} C ${m} ${p}, ${T} ${w}, ${h} ${f}`),this.#a.classList.add("is-visible"))}#A(t,e){let n=this.#s.anchorElementFor(e);if(n!==e.highlightElement)return n.getBoundingClientRect();let o=this.#n.querySelectorAll(`.has-note[data-annotation-id="${t}"]`),i=null;return o.forEach(r=>{let a=r.getClientRects();if(a.length===0)return;let l=a[a.length-1];l&&(!i||l.bottom>i.bottom)&&(i=l)}),i}#y(){this.#a?.classList.remove("is-visible")}showNotePopup(t,e){let n=document.querySelector(".note-popup");n&&n.remove();let o=this.#e.find(h=>h.highlightId===e);if(!o)return;let i=document.createElement("div");i.className="note-popup markon-modal-frame",i.dataset.annotationId=e,i.innerHTML=`
            ${this.#m(e)}
            <div class="note-content">${Tt(o.note)}</div>
        `;let r=t.getBoundingClientRect();i.style.position="absolute",i.style.left=`${r.left+window.scrollX}px`,i.style.top=`${r.bottom+window.scrollY+10}px`,document.body.appendChild(i);let a=h=>{let f=h.target;!i.contains(f)&&!o.highlightElement.contains(f)&&(i.remove(),document.removeEventListener("click",a),d.log("NoteManager","Note popup closed by clicking outside"))};setTimeout(()=>{document.addEventListener("click",a)},0);let l=10,c=i.getBoundingClientRect();c.right>=window.innerWidth&&(i.style.left="auto",i.style.right=`${l}px`,c=i.getBoundingClientRect()),c.bottom>window.innerHeight&&(i.style.top=`${r.top+window.scrollY-c.height-l}px`),d.log("NoteManager",`Showed note popup for annotation: ${e}`)}};var S={getAbsolute(s){let t=s.getBoundingClientRect(),e=window.scrollY||window.pageYOffset,n=window.scrollX||window.pageXOffset;return{left:t.left+n,top:t.top+e,right:t.right+n,bottom:t.bottom+e}},constrainToViewport(s,t,e,n,o={}){let i=o.margin??10,r=o.fixed?0:window.scrollX||window.pageXOffset,a=o.fixed?0:window.scrollY||window.pageYOffset,l=s,c=t;return l<r+i&&(l=r+i),l+e>window.innerWidth+r-i&&(l=window.innerWidth+r-e-i),c<a+i&&(c=a+i),c+n>window.innerHeight+a-i&&(c=window.innerHeight+a-n-i),{left:l,top:c}},smartScrollToHeading(s){let t=s.closest(".heading-section")??s;if(!(t instanceof HTMLElement))return;let e=t.offsetHeight,n=window.innerHeight;if(e<=n){let o=n-e,i=o>=u.DIMENSIONS.HEADING_TOP_MARGIN?u.DIMENSIONS.HEADING_TOP_MARGIN:o/2,r=t.getBoundingClientRect().top+window.scrollY-i;window.scrollTo({top:r,behavior:"smooth"})}else{let o=t.getBoundingClientRect().top+window.scrollY-u.DIMENSIONS.HEADING_TOP_MARGIN_TIGHT;window.scrollTo({top:o,behavior:"smooth"})}}};var C=["button","input","textarea","select","option","a[href]",'[contenteditable="true"]',"[data-no-drag]"].join(", "),Xt=(s,t=C)=>!t||!(s instanceof Node)?!1:!!(s instanceof Element?s:s.parentElement)?.closest(t),k=class{#t;#n=[];#e;#s=!1;#i=0;#r=0;#a=0;#l=0;#o={};#d="";#c=!1;constructor(t,e={}){this.#t=t,this.#e={storageKey:null,handle:null,onDragEnd:null,saveOffset:!1,restoreOffset:!1,savePosition:!1,restorePosition:!1,fixed:!1,margin:10,nonDragSelector:C,handleClassName:null,...e},this.#u()}#u(){if(typeof this.#e.handle=="string"?this.#n=Array.from(this.#t.querySelectorAll(this.#e.handle)):this.#n=[this.#e.handle??this.#t],this.#n.length===0){d.warn("Draggable","Handle element not found");return}if(this.#e.handleClassName)for(let t of this.#n)t.classList.add(this.#e.handleClassName);this.#e.restorePosition?this.#b():this.#e.restoreOffset&&this.#g(),this.#o.mousedown=t=>this.#f(t),this.#o.mousemove=t=>this.#h(t),this.#o.mouseup=()=>this.#v(),this.#o.touchstart=t=>this.#f(t),this.#o.touchmove=t=>this.#h(t),this.#o.touchend=()=>this.#v();for(let t of this.#n)t.addEventListener("mousedown",this.#o.mousedown),t.addEventListener("touchstart",this.#o.touchstart,{passive:!1})}#f(t){if(t instanceof MouseEvent&&t.button!==0||Xt(t.target,this.#e.nonDragSelector))return;this.#s=!0;let e=this.#w(t);this.#i=e.x,this.#r=e.y;let n=this.#E();this.#a=n.left,this.#l=n.top,this.#t.style.cursor="grabbing";for(let o of this.#n)o.classList.add("is-dragging");this.#d=document.body.style.userSelect,this.#c=!0,document.body.style.userSelect="none",this.#o.mousemove&&document.addEventListener("mousemove",this.#o.mousemove),this.#o.mouseup&&document.addEventListener("mouseup",this.#o.mouseup),this.#o.touchmove&&document.addEventListener("touchmove",this.#o.touchmove,{passive:!1}),this.#o.touchend&&document.addEventListener("touchend",this.#o.touchend),t.preventDefault()}#h(t){if(!this.#s)return;let e=this.#w(t),n=e.x-this.#i,o=e.y-this.#r,i=this.#a+n,r=this.#l+o;({left:i,top:r}=S.constrainToViewport(i,r,this.#t.offsetWidth,this.#t.offsetHeight,{fixed:this.#e.fixed,margin:this.#e.margin})),this.#p(i,r)}#v(){if(this.#s){this.#s=!1,this.#t.style.cursor="";for(let t of this.#n)t.classList.remove("is-dragging");if(this.#c&&(document.body.style.userSelect=this.#d,this.#c=!1),this.#o.mousemove&&document.removeEventListener("mousemove",this.#o.mousemove),this.#o.mouseup&&document.removeEventListener("mouseup",this.#o.mouseup),this.#o.touchmove&&document.removeEventListener("touchmove",this.#o.touchmove),this.#o.touchend&&document.removeEventListener("touchend",this.#o.touchend),this.#e.saveOffset&&this.#e.storageKey&&this.#m(),this.#e.savePosition&&this.#e.storageKey&&this.#T(),this.#e.onDragEnd){let t=parseFloat(this.#t.style.left)||0,e=parseFloat(this.#t.style.top)||0;this.#e.onDragEnd(t,e)}}}#m(){let t=parseFloat(this.#t.style.left)||0,e=parseFloat(this.#t.style.top)||0,n=parseFloat(this.#t.dataset.originalLeft??""),o=parseFloat(this.#t.dataset.originalTop??"");if(!isNaN(n)&&!isNaN(o)&&this.#e.storageKey){let i={dx:t-n,dy:e-o};localStorage.setItem(this.#e.storageKey,JSON.stringify(i)),d.log("Draggable",`Saved offset to ${this.#e.storageKey}:`,i)}}#g(){if(!this.#e.storageKey)return;let t=parseFloat(this.#t.dataset.originalLeft??""),e=parseFloat(this.#t.dataset.originalTop??"");if(!(!Number.isFinite(t)||!Number.isFinite(e)))try{let n=JSON.parse(localStorage.getItem(this.#e.storageKey)||"null");if(!n||typeof n!="object")return;let o=n,i=typeof o.dx=="number"?o.dx:0,r=typeof o.dy=="number"?o.dy:0;if(!Number.isFinite(i)||!Number.isFinite(r))return;let a=S.constrainToViewport(t+i,e+r,this.#t.offsetWidth,this.#t.offsetHeight,{fixed:this.#e.fixed,margin:this.#e.margin});this.#p(a.left,a.top)}catch{}}#T(){if(!this.#e.storageKey)return;let t=parseFloat(this.#t.style.left),e=parseFloat(this.#t.style.top);!Number.isFinite(t)||!Number.isFinite(e)||(localStorage.setItem(this.#e.storageKey,JSON.stringify({left:t,top:e})),d.log("Draggable",`Saved position to ${this.#e.storageKey}`))}#b(){if(this.#e.storageKey)try{let t=JSON.parse(localStorage.getItem(this.#e.storageKey)||"null");if(!t||typeof t!="object")return;let e=t,n=typeof e.left=="number"?e.left:e.x,o=typeof e.top=="number"?e.top:e.y;if(typeof n!="number"||typeof o!="number")return;let i=S.constrainToViewport(n,o,this.#t.offsetWidth,this.#t.offsetHeight,{fixed:this.#e.fixed,margin:this.#e.margin});this.#p(i.left,i.top)}catch{}}#E(){let t=this.#t.getBoundingClientRect(),e=this.#e.fixed?0:window.scrollX||window.pageXOffset,n=this.#e.fixed?0:window.scrollY||window.pageYOffset,o=parseFloat(this.#t.style.left),i=parseFloat(this.#t.style.top),r=Number.isFinite(o)?o:t.left+e,a=Number.isFinite(i)?i:t.top+n;return this.#p(r,a),{left:r,top:a}}#p(t,e){this.#t.style.position=this.#e.fixed?"fixed":"absolute",this.#t.style.left=`${t}px`,this.#t.style.top=`${e}px`,this.#t.style.right="auto",this.#t.style.bottom="auto",this.#t.style.margin="0",this.#t.style.transform="none"}#w(t){if(t.type==="touchstart"||t.type==="touchmove"){let n=t,o=n.touches[0]??n.changedTouches[0];if(!o){let i=this.#E();return{x:i.left,y:i.top}}return this.#e.fixed?{x:o.clientX,y:o.clientY}:{x:o.pageX,y:o.pageY}}let e=t;return this.#e.fixed?{x:e.clientX,y:e.clientY}:{x:e.pageX,y:e.pageY}}destroy(){for(let t of this.#n)this.#o.mousedown&&t.removeEventListener("mousedown",this.#o.mousedown),this.#o.touchstart&&t.removeEventListener("touchstart",this.#o.touchstart),this.#e.handleClassName&&t.classList.remove(this.#e.handleClassName),t.classList.remove("is-dragging");this.#s&&(this.#o.mousemove&&document.removeEventListener("mousemove",this.#o.mousemove),this.#o.mouseup&&document.removeEventListener("mouseup",this.#o.mouseup),this.#o.touchmove&&document.removeEventListener("touchmove",this.#o.touchmove),this.#o.touchend&&document.removeEventListener("touchend",this.#o.touchend)),this.#t.style.cursor="",this.#c&&(document.body.style.userSelect=this.#d,this.#c=!1),d.log("Draggable","Destroyed")}};var M=(s,...t)=>N.t(s,...t),Y=class{#t;#n=null;#e=null;#s;#i=null;#r=null;#a;#l;#o;#d;constructor(t,e={}){this.#s=t,this.#a=e.enableEdit??!1,this.#l=e.enableChat??!1,this.#o=e.enableNote??!0,this.#d=e.reject,this.#f()}setMarkdownBody(t){this.#s=t}show(t,e=null){let n=t.toString();this.#n=t.cloneRange(),this.#e=e;let o=n.trim().length>0;this.#h(e,o),this.#u(t.getBoundingClientRect())}hide(){this.#t.style.display="none",this.#n=null,this.#e=null,this.#r&&(this.#r.destroy(),this.#r=null),d.log("PopoverManager","Popover hidden")}isVisible(){return this.#t.style.display!=="none"}getCurrentSelection(){return this.#n}getCurrentHighlightedElement(){return this.#e}onAction(t){this.#i=t}handleSelection(t){let e=t.target;if(e&&this.#t.contains(e)||e&&typeof e.closest=="function"&&e.closest("#toc-container, .markon-live-container")||document.body.dataset.markonLiveRemote)return;let n=window.getSelection();if(!n)return;if(n.toString().trim().length===0){e&&!this.#t.contains(e)&&this.hide();return}let i=n.getRangeAt(0),r=i.commonAncestorContainer,a=r.nodeType===3?r.parentElement:r;if(!a||!this.#s.contains(a)||this.#m(a))return;if(this.#c(i.startContainer)){this.hide();return}if(this.#g(i)){d.log("PopoverManager","Selection spans multiple blocks, trimming to first block");let c=this.#T(i);if(c){if(c.toString().trim().length===0){d.log("PopoverManager","Trimmed selection has no text content, hiding"),this.hide();return}let f=c.startContainer,E=f.nodeType===3?f.parentElement:f;if(!E){this.hide();return}if(this.#m(E)){d.log("PopoverManager","Trimmed selection starts in UI element, hiding"),this.hide();return}if(this.#c(c.startContainer)){d.log("PopoverManager","Trimmed selection starts in non-annotatable side, hiding"),this.hide();return}n.removeAllRanges(),n.addRange(c);let m=E.closest(u.SELECTORS.HIGHLIGHT_CLASSES);this.show(c,m)}return}let l=a.closest(u.SELECTORS.HIGHLIGHT_CLASSES);this.show(i,l)}#c(t){return!!t&&!!this.#d?.(t)}handleHighlightClick(t){if(!t.isConnected){d.log("PopoverManager","handleHighlightClick: ignored detached element");return}if(this.isVisible()){d.log("PopoverManager","handleHighlightClick: ignored because popover is already visible");return}this.#e=t,this.#h(t,!1),this.#u(t.getBoundingClientRect())}#u(t){this.#t.style.visibility="hidden",this.#t.style.display="block";let e=this.#t.offsetHeight,n=this.#t.offsetWidth,o=window.pageXOffset||document.documentElement.scrollLeft,i=window.pageYOffset||document.documentElement.scrollTop,r=u.DIMENSIONS.POPOVER_OFFSET,a=t.left+o+t.width/2-n/2,l=t.bottom+i+r,c=window.innerHeight-t.bottom,h=t.top;c<e+r+20&&(h>c||h>e+r+20)&&(l=t.top+i-e-r),{left:a,top:l}=S.constrainToViewport(a,l,n,e);let f=a,E=l,m=this.#E();m&&(a+=m.dx,l+=m.dy,{left:a,top:l}=S.constrainToViewport(a,l,n,e)),this.#t.dataset.originalLeft=String(f),this.#t.dataset.originalTop=String(E),this.#t.style.left=`${a}px`,this.#t.style.top=`${l}px`,this.#t.style.visibility="visible",this.#b()}#f(){this.#t=document.createElement("div"),this.#t.className="selection-popover",this.#h(null),document.body.appendChild(this.#t),this.#t.addEventListener("click",t=>{let n=t.target?.closest("[data-action]")?.dataset.action;n&&(this.#i&&this.#i(n,{selection:this.#n,highlightedElement:this.#e,shiftKey:t.shiftKey}),this.hide())})}#h(t,e=!1){d.log("PopoverManager",`#updateContent called: highlightedElement=${!!t}, hasSelection=${e}`);let n=this.#a&&e?'<span class="popover-separator">|</span><button data-action="edit">Edit</button>':"",o=this.#l&&e?`<span class="popover-separator">|</span><button data-action="chat">${M("web.chat.discuss")}</button>`:"",i=this.#o?`<button data-action="add-note">${M("web.annot.note")}</button>`:"",r=this.#o?`<span class="popover-separator">|</span>${i}`:"",a='<span class="popover-drag-handle" aria-hidden="true"></span>';if(t){let l=this.#v(t);e?(d.log("PopoverManager","Showing: Unhighlight + Note + Edit + Chat"),this.#t.innerHTML=`
                    ${a}
                    ${l}
                    <button data-action="unhighlight">${M("web.annot.unhighlight")}</button>
                    ${r}
                    ${n}
                    ${o}
                `):(d.log("PopoverManager","Showing: Unhighlight"),this.#t.innerHTML=`${a}${l}<button data-action="unhighlight">${M("web.annot.unhighlight")}</button>`)}else this.#t.innerHTML=`
                ${a}
                <button data-action="highlight-orange">${M("web.annot.orange")}</button>
                <button data-action="highlight-green">${M("web.annot.green")}</button>
                <button data-action="highlight-yellow">${M("web.annot.yellow")}</button>
                <button data-action="strikethrough">${M("web.annot.strike")}</button>
                ${r}
                ${n}
                ${o}
            `}#v(t){if(!document.body.classList.contains("markon-shared"))return"";let e=t,n=e.style.getPropertyValue("--anno-author").trim(),o=/^#[0-9a-f]{3,8}$/i.test(n)?n:"var(--markon-fg-muted)",i=e.dataset.authorName||M("web.author.anon"),r="",a=Number(e.dataset.authorTime);if(a){let l=new Date(a),c=h=>String(h).padStart(2,"0");r=`${l.getMonth()+1}/${l.getDate()} ${c(l.getHours())}:${c(l.getMinutes())}`}return`<span class="popover-author"><span class="popover-author-dot" style="background:${o}"></span><span class="popover-author-name">${b.escape(i)}</span>`+(r?`<span class="popover-author-time">${r}</span>`:"")+'</span><span class="popover-separator">|</span>'}#m(t){return!!(t.closest(".selection-popover")||t.closest(".note-input-modal")||t.closest(".note-card-margin")||t.closest(".note-popup")||t.closest(".confirm-dialog")||t.closest(".md-diff-ui")||t.closest(".viewed-checkbox")||t.closest(".viewed-checkbox-label")||t.closest(".viewed-text")||t.closest(".viewed-toolbar")||t.closest(".section-toggle-btn"))}#g(t){let e=H.getBlockParent(t.startContainer,this.#s),n=H.getBlockParent(t.endContainer,this.#s);return e!==n&&!!e&&!!n}#T(t){let e=H.getBlockParent(t.startContainer,this.#s);if(!e)return null;let n=H.findLastTextNode(e);if(!n)return null;try{let o=t.cloneRange();return o.setEnd(n,n.length),o}catch(o){return d.warn("PopoverManager","Failed to trim selection:",o),null}}#b(){this.#r&&this.#r.destroy(),this.#r=new k(this.#t,{storageKey:u.STORAGE_KEYS.POPOVER_OFFSET,handle:".popover-drag-handle",saveOffset:!0,onDragEnd:(t,e)=>{d.log("PopoverManager",`Popover dragged to (${t}, ${e})`)}})}#E(){try{let t=localStorage.getItem(u.STORAGE_KEYS.POPOVER_OFFSET);if(t){let e=JSON.parse(t);if(e&&typeof e=="object"&&"dx"in e&&"dy"in e&&typeof e.dx=="number"&&typeof e.dy=="number")return e}}catch(t){d.warn("PopoverManager","Failed to load saved offset:",t)}return null}};var A=window.__MARKON_I18N__?.t||(s=>s),Jt="markon-modal-drag-handle";var Zt=`${C}, .markon-modal-frame > *`;var Qt=(s,t)=>new k(s,{handle:t.handle,storageKey:t.storageKey??null,saveOffset:t.storageMode==="offset"&&!!t.storageKey,restoreOffset:t.storageMode==="offset"&&!!t.storageKey,savePosition:(t.storageMode??"position")==="position"&&!!t.storageKey,restorePosition:(t.storageMode??"position")==="position"&&!!t.storageKey,fixed:!0,margin:t.margin??10,nonDragSelector:t.nonDragSelector??C,handleClassName:Jt}),q=class{#t=null;#n;#e={};#s=null;constructor(t){this.#n={className:"",closeOnOutsideClick:!0,closeOnEscape:!0,draggable:!0,dragHandle:null,dragStorageKey:null,dragStorageMode:"position",...t}}show(t=null){if(this.#i(),this.#t=this.create(),this.#t.hasAttribute("role")||this.#t.setAttribute("role","dialog"),this.#t.hasAttribute("aria-modal")||this.#t.setAttribute("aria-modal","true"),document.body.appendChild(this.#t),t&&this.#r(t),this.#n.draggable){let e=this.#n.dragHandle??this.#t;this.#s=Qt(this.#t,{handle:e,storageKey:this.#n.dragStorageKey,storageMode:this.#n.dragStorageMode,nonDragSelector:this.#n.dragHandle?C:Zt})}this.#a(),setTimeout(()=>this.#o(),0),d.log("Modal",`Showed ${this.#n.className}`)}close(){this.#t&&(this.#s?.destroy(),this.#s=null,this.#t.remove(),this.#t=null),this.#l(),d.log("Modal",`Closed ${this.#n.className}`)}getElement(){return this.#t}#i(){let t=document.querySelector(`.${this.#n.className}`);t&&t.remove()}#r(t){if(!this.#t)return;let e=t.getBoundingClientRect(),n=this.#t.offsetWidth,o=this.#t.offsetHeight,i=getComputedStyle(this.#t).position==="fixed",r=i?0:window.pageXOffset||document.documentElement.scrollLeft,a=i?0:window.pageYOffset||document.documentElement.scrollTop,l=e.left+r,c=e.bottom+a+5;window.innerHeight-e.bottom<o+10&&(c=e.top+a-o-5),{left:l,top:c}=S.constrainToViewport(l,c,n,o,{fixed:i}),this.#t.style.left=`${l}px`,this.#t.style.top=`${c}px`,this.#t.dataset.originalLeft=String(l),this.#t.dataset.originalTop=String(c)}#a(){this.#n.closeOnEscape&&(this.#e.keydown=t=>{t.key==="Escape"&&(t.preventDefault(),typeof this.cancel=="function"?this.cancel():this.close())},document.addEventListener("keydown",this.#e.keydown)),this.#n.closeOnOutsideClick&&(this.#e.click=t=>{this.#t&&(this.#t.contains(t.target)||(typeof this.cancel=="function"?this.cancel():this.close()))},setTimeout(()=>{this.#e.click&&document.addEventListener("click",this.#e.click)},0))}#l(){this.#e.keydown&&document.removeEventListener("keydown",this.#e.keydown),this.#e.click&&document.removeEventListener("click",this.#e.click)}#o(){if(!this.#t)return;let t=this.#t.querySelector("input, textarea, button");t&&t.focus({preventScroll:!0})}},Z=class extends q{#t;#n;#e;#s=null;#i=!1;constructor(t={}){super({className:"note-input-modal",dragHandle:".note-input-drag-region",dragStorageKey:u.STORAGE_KEYS.NOTE_INPUT_OFFSET,dragStorageMode:"offset",...t}),this.#t=t.onSave??(()=>{}),this.#n=t.onCancel??(()=>{}),this.#e=t.initialValue??""}show(t=null){super.show(t);let e=this.getElement();e&&(this.#r(e),this.#o(e),this.#a(e))}close(){this.#s?.disconnect(),this.#s=null,this.#i=!1,super.close()}create(){let t=document.createElement("div");t.className="note-input-modal markon-modal-frame",t.innerHTML=`
            <span class="note-input-drag-region note-input-drag-top" aria-hidden="true"></span>
            <span class="note-input-drag-region note-input-drag-right" aria-hidden="true"></span>
            <span class="note-input-drag-region note-input-drag-bottom" aria-hidden="true"></span>
            <span class="note-input-drag-region note-input-drag-left" aria-hidden="true"></span>
            <div class="note-input-field">
                <textarea class="note-textarea" placeholder="${A("web.modal.note.placeholder")}"></textarea>
                <div class="note-input-actions">
                    <button class="note-cancel" type="button" title="${A("web.modal.cancel")}" aria-label="${A("web.modal.cancel")}">
                        <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
                            <path d="M6 6l12 12M18 6L6 18"></path>
                        </svg>
                    </button>
                    <button class="note-save" type="button" title="${A("web.modal.save")}" aria-label="${A("web.modal.save")}" disabled>
                        <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
                            <path d="M12 19V5M6.5 10.5 12 5l5.5 5.5"></path>
                        </svg>
                    </button>
                </div>
            </div>
        `;let e=t.querySelector(".note-textarea");e.value=this.#e;let n=t.querySelector(".note-cancel"),o=t.querySelector(".note-save"),i=()=>{let a=e.value.trim().length>0;o.disabled=!a};i(),e.addEventListener("input",i),this.#e&&setTimeout(()=>e.select(),0),n.addEventListener("click",()=>{this.#n(),this.close()});let r=()=>{let a=e.value.trim();a&&(this.#t(a),this.close())};return o.addEventListener("click",r),e.addEventListener("keydown",a=>{a.key==="Enter"&&!a.shiftKey&&!a.ctrlKey&&(a.preventDefault(),r())}),t}cancel(){this.#n(),this.close()}#r(t){try{let e=JSON.parse(localStorage.getItem(u.STORAGE_KEYS.NOTE_INPUT_SIZE)||"null");if(!e||typeof e!="object")return;let n=e,o=typeof n.width=="number"?n.width:NaN,i=typeof n.height=="number"?n.height:NaN;if(!Number.isFinite(o)||!Number.isFinite(i))return;let{width:r,height:a}=this.#l(t,o,i);t.style.width=`${r}px`,t.style.height=`${a}px`}catch{}}#a(t){if(typeof ResizeObserver>"u")return;let e=Math.round(t.offsetWidth),n=Math.round(t.offsetHeight);this.#i=!1,window.setTimeout(()=>{this.#i=!0},0),this.#s=new ResizeObserver(()=>{if(!this.#i){e=Math.round(t.offsetWidth),n=Math.round(t.offsetHeight);return}let o=Math.round(t.offsetWidth),i=Math.round(t.offsetHeight);Math.abs(o-e)<2&&Math.abs(i-n)<2||(e=o,n=i,localStorage.setItem(u.STORAGE_KEYS.NOTE_INPUT_SIZE,JSON.stringify({width:o,height:i})),this.#o(t))}),this.#s.observe(t)}#l(t,e,n){let o=getComputedStyle(t),i=parseFloat(o.minWidth)||0,r=parseFloat(o.minHeight)||0,a=Math.max(i,window.innerWidth-24),l=Math.max(r,window.innerHeight-24);return{width:Math.min(Math.max(e,i),a),height:Math.min(Math.max(n,r),l)}}#o(t){let e=parseFloat(t.style.left),n=parseFloat(t.style.top);if(!Number.isFinite(e)||!Number.isFinite(n))return;let o=S.constrainToViewport(e,n,t.offsetWidth,t.offsetHeight,{fixed:!0,margin:10});t.style.left=`${o.left}px`,t.style.top=`${o.top}px`}},Q=class extends q{#t;#n;#e;#s;#i;constructor(t={}){super({className:"confirm-dialog",...t}),this.#t=t.message??A("web.modal.confirm"),this.#n=t.onConfirm??(()=>{}),this.#e=t.onCancel??(()=>{}),this.#s=t.confirmText??A("web.modal.ok"),this.#i=t.cancelText??A("web.modal.cancel")}create(){let t=document.createElement("div");t.className="confirm-dialog markon-modal-frame",t.innerHTML=`
            <p class="confirm-message"></p>
            <div class="confirm-actions">
                <button class="confirm-cancel">${this.#i}</button>
                <button class="confirm-ok">${this.#s}</button>
            </div>
        `,t.querySelector(".confirm-message").textContent=this.#t;let e=t.querySelector(".confirm-cancel"),n=t.querySelector(".confirm-ok");return e.addEventListener("click",()=>{this.#e(),this.close()}),n.addEventListener("click",()=>{d.log("ConfirmModal","OK button clicked, executing callback"),(async()=>{try{await this.#n(),d.log("ConfirmModal","Callback completed successfully")}catch(o){d.error("ConfirmModal","Callback failed:",o)}this.close()})()}),t}},D=class{static showNoteInput(t={}){let e=new Z(t);return e.show(t.anchorElement??null),e}static showConfirm(t={}){let e=new Q(t);return e.show(t.anchorElement??null),e}};function bt(s,t,e=null,n=A("web.modal.ok")){return D.showConfirm({message:s,onConfirm:t,anchorElement:e,confirmText:n})}var te=[".md-diff-change-card-old",".md-diff-block.is-deleted",".md-diff-item-old",".git-diff-word-del",".md-diff-gap",".md-diff-gap-label",".md-diff-file-header",".md-diff-diagnostics"].join(",");function yt(s){return s.nodeType===Node.ELEMENT_NODE?s:s.parentElement}function tt(s){return!!yt(s)?.closest(te)}function L(s){return s.querySelector(".md-diff-file-body")??s}function wt(s){return yt(s)?.closest(".md-diff-file-section[data-abs-path]")??null}var ee="[data-md-diff-content]",ne=s=>!!s.note&&s.note.trim()!=="",oe=s=>`# ${s.replace(/\r?\n/g," ").trim()||"Untitled file"}`,et=class{#t;#n;#e=new Map;#s=null;constructor(t){this.#t=t,this.#n=new Y(t,{enableEdit:!1,enableChat:!1,enableNote:!0,reject:tt}),this.#n.onAction((e,n)=>{this.#o(e,n)}),this.#u()}onBodyRendered(t){let e=t.closest(".md-diff-file-section[data-abs-path]"),n=e?.dataset.absPath;if(!e||!n)return;let o=this.#i(n,e),i=L(e);o.ready.then(()=>{i.isConnected&&(o.annotationManager.setRoot(i),o.noteManager.setMarkdownBody(i),o.annotationManager.applyToDOM(),o.noteManager.render())})}onContentRendered(){document.querySelector(".note-popup")?.remove()}async exportNotes(t){let e=await this.#r();if(!e.length)return!1;let n=e.map(o=>`${oe(o.path)}

${o.markdown.trimEnd()}`).join(`

`)+`
`;return this.#s||(this.#s=new W(window.location.pathname||"notes")),await this.#s.open({mode:"export",content:n,exportFileName:"notes"}),!0}async notesCount(){return(await this.#r()).reduce((e,n)=>e+n.count,0)}#i(t,e){let n=this.#e.get(t);if(n)return n;let o=new B(t,!1,null),i=L(e),r=new G(o,i,tt),a=new V(r,i,{marginCards:!1});return n={absPath:t,filePath:e.dataset.filePath||t,storage:o,annotationManager:r,noteManager:a,ready:r.load()},this.#e.set(t,n),n}async#r(){let t=[...this.#t.querySelectorAll(".md-diff-file-section[data-abs-path]")],e=[];for(let n of t){let o=n.dataset.absPath;if(!o)continue;let i=this.#i(o,n);await i.ready;let r=i.annotationManager.getAll().filter(ne).map(l=>l.id);if(!r.length)continue;let a=i.annotationManager.formatAsMarkdown({ids:r});a.trim()&&e.push({path:n.dataset.filePath||o,markdown:a,count:r.length})}return e}#a(t){for(let e of this.#e.values())if(e.annotationManager.getById(t))return e;return null}#l(t){if(!t)return null;let e=wt(t),n=e?.dataset.absPath;return!e||!n?null:{ctx:this.#i(n,e),section:e}}async#o(t,e){let{selection:n,highlightedElement:o}=e;if(t==="unhighlight"){let l=o instanceof HTMLElement?o:null,c=l?.dataset.annotationId,h=l?this.#l(l):null;c&&h&&(await h.ctx.annotationManager.delete(c),h.ctx.annotationManager.removeFromDOM(c),h.ctx.noteManager.render(),this.#h()),window.getSelection()?.removeAllRanges();return}if(!n)return;let i=this.#l(n.startContainer);if(!i)return;let{ctx:r,section:a}=i;if(t.startsWith("highlight-")||t==="strikethrough"){let l=t==="strikethrough"?u.HTML_TAGS.STRIKETHROUGH:u.HTML_TAGS.HIGHLIGHT,c=r.annotationManager.createAnnotation(n,t,l);await this.#d(r,a,c),window.getSelection()?.removeAllRanges();return}if(t==="add-note"){this.#c(r,a,n);return}}async#d(t,e,n){await t.annotationManager.add(n),t.annotationManager.setRoot(L(e)),t.annotationManager.applyToDOM([n]),t.noteManager.setMarkdownBody(L(e)),t.noteManager.render(),this.#h()}#c(t,e,n,o=null){let i=n.getBoundingClientRect(),r={getBoundingClientRect:()=>i};D.showNoteInput({anchorElement:r,initialValue:o?o.note??"":"",onSave:a=>{(async()=>{if(a)if(o)o.note=a,await t.annotationManager.add(o),t.annotationManager.removeFromDOM(o.id),t.annotationManager.setRoot(L(e)),t.annotationManager.applyToDOM([o]),t.noteManager.setMarkdownBody(L(e)),t.noteManager.render(),this.#h();else{let l=t.annotationManager.createAnnotation(n,u.ANNOTATION_TYPES.HAS_NOTE,u.HTML_TAGS.HIGHLIGHT,a);await this.#d(t,e,l)}else o&&(await t.annotationManager.delete(o.id),t.annotationManager.removeFromDOM(o.id),t.noteManager.render(),this.#h());window.getSelection()?.removeAllRanges()})()},onCancel:()=>{window.getSelection()?.removeAllRanges()}})}#u(){document.addEventListener("mouseup",e=>this.#n.handleSelection(e)),document.addEventListener("touchend",e=>this.#n.handleSelection(e)),document.addEventListener("click",e=>{this.#f(e)});let t=e=>{let n=e.target;n?.closest(".selection-popover")||n?.closest(".note-input-modal")||n?.closest(".note-popup")||n?.closest(".confirm-dialog")||this.#n.isVisible()&&(this.#n.hide(),window.getSelection()?.removeAllRanges())};document.addEventListener("mousedown",t),document.addEventListener("touchstart",t,{passive:!0})}async#f(t){let e=t.target;if(!e)return;let n=e.closest(".note-copy"),o=e.closest(".note-link"),i=e.closest(".note-edit"),r=e.closest(".note-delete");if(n){let c=n.dataset.annotationId,h=c?this.#a(c):null,f=c&&h?h.annotationManager.getById(c):null;f&&h&&await I(h.annotationManager.formatAnnotation(f)),t.stopPropagation();return}if(o){let c=o.dataset.annotationId,h=c?this.#a(c):null,f=c&&h?h.annotationManager.getById(c):null,E=R.get(u.META_TAGS.WORKSPACE_ID),m="";c&&h&&f?.note?.trim()&&E&&(m=at(E,h.filePath,c)),(m?await I(m):!1)?it(o):ot(o,"Copy failed"),t.stopPropagation();return}if(i){let c=i.dataset.annotationId,h=c?this.#a(c):null,f=c&&h?h.annotationManager.getById(c):null;if(c&&h&&f){document.querySelector(".note-popup")?.remove();let E=this.#t.querySelector(`[data-annotation-id="${c}"]`),m=E?E.closest(".md-diff-file-section[data-abs-path]"):null;if(E&&m){let p=document.createRange();p.selectNodeContents(E),this.#c(h,m,p,f)}}t.stopPropagation();return}if(r){let c=r.dataset.annotationId,h=c?this.#a(c):null;c&&h&&bt("Delete this note?",async()=>{await h.annotationManager.delete(c),h.annotationManager.removeFromDOM(c),h.noteManager.render(),document.querySelector(".note-popup")?.remove(),this.#h()},r,"Delete"),t.stopPropagation();return}let a=e.closest(".has-note");if(a){let c=a.dataset.annotationId,h=c?this.#a(c):null;c&&h&&(h.noteManager.showNotePopup(a,c),t.stopPropagation());return}let l=e.closest(u.SELECTORS.HIGHLIGHT_CLASSES);l&&this.#n.handleHighlightClick(l)}#h(){document.dispatchEvent(new CustomEvent("markon:diff-notes-count-changed"))}},St=()=>{let s=document.querySelector(ee);if(!s)return;let t=new et(s);window.markonDiffAnnotations={onBodyRendered:e=>t.onBodyRendered(e),onContentRendered:()=>t.onContentRendered(),exportNotes:e=>t.exportNotes(e),notesCount:()=>t.notesCount()},document.dispatchEvent(new CustomEvent("markon:diff-annotations-ready"))};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",St,{once:!0}):St();