autumnnote 1.0.0 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -2
- package/dist/autumnnote.css +1 -1
- package/dist/autumnnote.es.js +2366 -1994
- package/dist/autumnnote.es.js.map +1 -1
- package/dist/autumnnote.umd.js +29 -29
- package/dist/autumnnote.umd.js.map +1 -1
- package/package.json +3 -3
- package/src/js/core/sanitise.js +43 -0
- package/src/js/editing/History.js +10 -2
- package/src/js/editing/Style.js +65 -4
- package/src/js/editing/Typing.js +243 -37
- package/src/js/index.js +1 -1
- package/src/js/index.umd.js +12 -0
- package/src/js/module/Buttons.js +15 -5
- package/src/js/module/CodeTooltip.js +18 -7
- package/src/js/module/Codeview.js +6 -1
- package/src/js/module/ContextMenu.js +13 -6
- package/src/js/module/Editor.js +70 -2
- package/src/js/module/IconDialog.js +27 -13
- package/src/js/module/ImageResizer.js +22 -3
- package/src/js/module/ImageTooltip.js +37 -10
- package/src/js/module/Placeholder.js +2 -1
- package/src/js/module/Statusbar.js +16 -2
- package/src/js/module/TableTooltip.js +119 -23
- package/src/js/module/Toolbar.js +103 -17
- package/src/js/module/VideoDialog.js +3 -3
- package/src/js/module/VideoResizer.js +22 -3
- package/src/js/module/VideoTooltip.js +73 -0
- package/src/js/renderer.js +5 -0
- package/src/js/settings.js +4 -0
- package/src/styles/autumnnote.scss +61 -31
- package/types/index.d.ts +4 -4
package/dist/autumnnote.umd.js
CHANGED
|
@@ -1,35 +1,35 @@
|
|
|
1
|
-
(function(p,J){typeof exports=="object"&&typeof module<"u"?J(exports):typeof define=="function"&&define.amd?define(["exports"],J):(p=typeof globalThis<"u"?globalThis:p||self,J(p.AutumnNote={}))})(this,function(p){"use strict";function J(n,t,e){return Math.min(Math.max(n,t),e)}function ft(n,t){let e;return function(...i){clearTimeout(e),e=setTimeout(()=>n.apply(this,i),t)}}function Ne(n,t){let e=0;return function(...i){const s=Date.now();if(s-e>=t)return e=s,n.apply(this,i)}}function ze(...n){return t=>n.reduceRight((e,i)=>i(e),t)}function He(n){return n}function $e(n){return n==null}function De(n){return typeof n=="string"}function Pe(n){return typeof n=="function"}function it(n,t){const e={};for(const i of Object.keys(n))e[i]=Array.isArray(n[i])?[...n[i]]:n[i];if(st(n)&&st(t))for(const i of Object.keys(t))st(t[i])?i in n?e[i]=it(n[i],t[i]):e[i]=it({},t[i]):Array.isArray(t[i])?e[i]=[...t[i]]:e[i]=t[i];return e}function st(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Oe(n){return n?{top:Math.round(n.top),left:Math.round(n.left),width:Math.round(n.width),height:Math.round(n.height),bottom:Math.round(n.bottom),right:Math.round(n.right)}:null}const gt=1,yt=3,M=n=>n&&n.nodeType===gt,ht=n=>n&&n.nodeType===yt,_t=n=>M(n)&&/^(area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$/i.test(n.nodeName),bt=n=>M(n)&&/^(p|div|li|h[1-6]|blockquote|td|th|pre)$/i.test(n.nodeName),vt=n=>M(n)&&/^(li)$/i.test(n.nodeName),Fe=n=>M(n)&&/^(ul|ol)$/i.test(n.nodeName),We=n=>M(n)&&n.nodeName.toUpperCase()==="TABLE",Ue=n=>M(n)&&/^(a|abbr|acronym|b|bdo|big|br|button|cite|code|dfn|em|i|img|input|kbd|label|map|object|output|q|s|samp|select|small|span|strong|sub|sup|textarea|time|tt|u|var)$/i.test(n.nodeName),wt=n=>M(n)&&n.isContentEditable,qe=n=>M(n)&&n.nodeName.toUpperCase()==="A",Ve=n=>M(n)&&n.nodeName.toUpperCase()==="IMG";function nt(n,t,e){let i=n;for(;i&&i!==e;){if(t(i))return i;i=i.parentNode}return null}function dt(n,t){return nt(n,bt,t)}function Ye(n,t){const e=[];let i=n.parentNode;for(;i&&i!==t;)e.push(i),i=i.parentNode;return e}function Ke(n){return Array.from(n.childNodes)}function Xe(n){let t=n.previousSibling;for(;t&&!M(t);)t=t.previousSibling;return t}function Ge(n){let t=n.nextSibling;for(;t&&!M(t);)t=t.nextSibling;return t}function c(n,t={},e=[]){const i=document.createElement(n);for(const[s,o]of Object.entries(t))i.setAttribute(s,o);for(const s of e)typeof s=="string"?i.appendChild(document.createTextNode(s)):i.appendChild(s);return i}function Je(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function Qe(n){const t=n.parentNode;if(t){for(;n.firstChild;)t.insertBefore(n.firstChild,n);t.removeChild(n)}}function Ze(n,t){return n.parentNode.insertBefore(t,n),t.appendChild(n),t}function ti(n,t){t.nextSibling?t.parentNode.insertBefore(n,t.nextSibling):t.parentNode.appendChild(n)}function ei(n){return ht(n)?n.nodeValue:n.textContent||""}function ii(n){return ht(n)?!n.nodeValue:_t(n)?!1:!n.textContent.trim()&&!n.querySelector("img, video, hr, table")}function si(n){return n.outerHTML}function ni(n){const t=document.createRange();t.selectNodeContents(n),t.collapse(!1);const e=window.getSelection();e&&(e.removeAllRanges(),e.addRange(t))}function oi(n){return!!nt(n,wt)}function d(n,t,e,i){return n.addEventListener(t,e,i),()=>n.removeEventListener(t,e,i)}function O(n,t){const e='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',i=()=>Array.from(n.querySelectorAll(e)).filter(o=>!o.closest('[style*="display: none"]')&&!o.closest('[style*="display:none"]')),s=o=>{if(o.key==="Escape"){o.stopPropagation(),t&&t();return}if(o.key!=="Tab")return;const a=i();if(!a.length)return;const l=a[0],r=a[a.length-1];o.shiftKey?document.activeElement===l&&(o.preventDefault(),r.focus()):document.activeElement===r&&(o.preventDefault(),l.focus())};return document.addEventListener("keydown",s),()=>document.removeEventListener("keydown",s)}class ot{constructor(t,e,i,s){this.sc=t,this.so=e,this.ec=i,this.eo=s}isCollapsed(){return this.sc===this.ec&&this.so===this.eo}toNativeRange(){const t=document.createRange();try{t.setStart(this.sc,this.so),t.setEnd(this.ec,this.eo)}catch{}return t}select(){const t=window.getSelection();t&&(t.removeAllRanges(),t.addRange(this.toNativeRange()))}commonAncestor(){const e=this.toNativeRange().commonAncestorContainer;return M(e)?e:e.parentElement}blockNode(t){return nt(this.sc,e=>M(e)&&e!==t,t)}toString(){return this.toNativeRange().toString()}getClientRects(){const t=this.toNativeRange().getClientRects();return t.length>0?t[t.length-1]:null}insertNode(t){this.toNativeRange().insertNode(t)}}function pt(n){return new ot(n.startContainer,n.startOffset,n.endContainer,n.endOffset)}function ut(n){const t=window.getSelection();if(!t||t.rangeCount===0)return null;const e=t.getRangeAt(0);return n&&!n.contains(e.commonAncestorContainer)?null:pt(e)}function ai(n){return new ot(n,0,n,n.childNodes.length)}function li(n,t=0){return new ot(n,t,n,t)}function ri(n){const t=window.getSelection();return!t||t.rangeCount===0?!1:n.contains(t.getRangeAt(0).commonAncestorContainer)}function Y(n){const t=window.getSelection();if(!t||t.rangeCount===0){n(null);return}const e=t.getRangeAt(0).cloneRange();n(pt(e)),t.removeAllRanges(),t.addRange(e)}function ci(n,t){const e=n.splitText(t);return[n,e]}function I(n,t=null){return document.execCommand(n,!1,t)}const xt=()=>I("bold"),kt=()=>I("italic"),Ct=()=>I("underline"),Tt=()=>I("strikeThrough"),It=()=>I("superscript"),St=()=>I("subscript"),Et=n=>I("foreColor",n),Bt=n=>I("hiliteColor",n),Rt=n=>I("fontName",n);function At(n,t=document){I("fontSize","7"),t.querySelectorAll('font[size="7"]').forEach(e=>{const i=document.createElement("span");for(i.style.fontSize=n,e.parentNode.insertBefore(i,e);e.firstChild;)i.appendChild(e.firstChild);e.parentNode.removeChild(e)})}const Lt=n=>I("formatBlock",`<${n}>`),Mt=()=>I("justifyLeft"),jt=()=>I("justifyCenter"),Nt=()=>I("justifyRight"),zt=()=>I("justifyFull"),Ht=()=>I("indent"),$t=()=>I("outdent"),Dt=()=>I("insertUnorderedList"),Pt=()=>I("insertOrderedList");function hi(n){const t=window.getSelection();if(!t||t.rangeCount===0)return;const e=t.getRangeAt(0),i=new Set(["P","DIV","H1","H2","H3","H4","H5","H6","LI","BLOCKQUOTE","PRE","TD","TH"]),s=r=>{let h=r instanceof Element?r:r.parentElement;for(;h;){if(i.has(h.tagName))return h;h=h.parentElement}return null};if(e.collapsed){const r=s(e.startContainer);r&&(r.style.lineHeight=n);return}const o=new Set,a=document.createNodeIterator(e.commonAncestorContainer,NodeFilter.SHOW_TEXT,null);let l;for(;l=a.nextNode();)if(e.intersectsNode(l)){const r=s(l);r&&o.add(r)}if(o.size===0){const r=s(e.commonAncestorContainer);r&&o.add(r)}o.forEach(r=>{r.style.lineHeight=n})}function di(n){const t=window.getSelection();if(!t||!t.rangeCount)return;const e=t.getRangeAt(0);let i=e.commonAncestorContainer;i.nodeType===3&&(i=i.parentElement);const s=i&&i.closest?i.closest("code"):null;if(s&&!s.closest("pre")){const o=s.parentNode;for(;s.firstChild;)o.insertBefore(s.firstChild,s);o.removeChild(s),n&&n.normalize()}else{if(e.collapsed)return;try{const o=document.createElement("code");e.surroundContents(o)}catch{const o=e.extractContents(),a=document.createElement("code");a.appendChild(o),e.insertNode(a)}}}function pi(){const n=window.getSelection();if(!n||!n.rangeCount)return!1;let t=n.getRangeAt(0).commonAncestorContainer;t.nodeType===3&&(t=t.parentElement);const e=t&&t.closest?t.closest("code"):null;return!!(e&&!e.closest("pre"))}function ui(){const n=window.getSelection();if(!n||!n.rangeCount)return;let e=n.getRangeAt(0).commonAncestorContainer;e.nodeType===3&&(e=e.parentElement);const i=e&&e.closest?e.closest(".an-checklist li"):null;if(i){const s=i.closest(".an-checklist"),o=Array.from(i.childNodes).filter(r=>!(r.nodeType===1&&r.tagName==="INPUT")).map(r=>r.textContent).join("").replace(/\u00a0/g," ").trim(),a=document.createElement("p");a.textContent=o||" ",s.parentNode.insertBefore(a,s.nextSibling),s.removeChild(i),s.children.length===0&&s.remove();const l=document.createRange();l.setStart(a,0),l.collapse(!0),n.removeAllRanges(),n.addRange(l)}else I("insertHTML",'<ul class="an-checklist"><li><input type="checkbox" contenteditable="false"> </li></ul>')}function mi(){const n=window.getSelection();if(!n||!n.rangeCount)return!1;let t=n.getRangeAt(0).commonAncestorContainer;return t.nodeType===3&&(t=t.parentElement),!!(t&&t.closest&&t.closest(".an-checklist li"))}function S(n,t,e,i,s,o){return{name:n,icon:t,tooltip:e,action:i,isActive:s,isDisabled:o}}const Ot=S("bold","bold","Bold (Ctrl+B)",()=>xt(),()=>document.queryCommandState("bold")),Ft=S("italic","italic","Italic (Ctrl+I)",()=>kt(),()=>document.queryCommandState("italic")),Wt=S("underline","underline","Underline (Ctrl+U)",()=>Ct(),()=>document.queryCommandState("underline")),Ut=S("strikethrough","strikethrough","Strikethrough",()=>Tt(),()=>document.queryCommandState("strikeThrough")),qt=S("superscript","superscript","Superscript",()=>It(),()=>document.queryCommandState("superscript")),Vt=S("subscript","subscript","Subscript",()=>St(),()=>document.queryCommandState("subscript")),Yt=S("alignLeft","align-left","Align Left",()=>Mt()),Kt=S("alignCenter","align-center","Align Center",()=>jt()),Xt=S("alignRight","align-right","Align Right",()=>Nt()),Gt=S("alignJustify","align-justify","Justify",()=>zt()),Jt=S("ul","list-ul","Unordered List",()=>Dt()),Qt=S("ol","list-ol","Ordered List",()=>Pt()),Zt=S("indent","indent","Indent",()=>Ht()),te=S("outdent","outdent","Outdent",()=>$t()),ee=S("undo","undo","Undo (Ctrl+Z)",n=>n.invoke("editor.undo"),void 0,n=>!n.invoke("editor.canUndo")),ie=S("redo","redo","Redo (Ctrl+Y)",n=>n.invoke("editor.redo"),void 0,n=>!n.invoke("editor.canRedo")),se=S("hr","minus","Horizontal Rule",()=>I("insertHorizontalRule")),ne=S("link","link","Insert Link",n=>n.invoke("linkDialog.show")),oe=S("image","image","Insert Image",n=>n.invoke("imageDialog.show")),ae=S("video","video","Insert Video",n=>n.invoke("videoDialog.show")),le=S("emoji","emoji","Insert Emoji",n=>n.invoke("emojiDialog.show")),re=S("icon","icon","Insert FA Icon",n=>n.invoke("iconDialog.show")),ce={name:"table",type:"grid",icon:"table",tooltip:"Insert Table",action:(n,t,e)=>{n.invoke("editor.insertTable",e,t),n.invoke("editor.afterCommand")}},he={name:"fontSize",type:"select",tooltip:"Font Size",placeholder:"Size",selectClass:"an-select-narrow",items:["8px","10px","11px","12px","13px","14px","16px","18px","20px","24px","28px","32px","36px","48px","72px"],action:(n,t)=>At(t,n.layoutInfo.editable),getValue:n=>{try{const t=window.getSelection();if(t&&t.rangeCount){let i=t.getRangeAt(0).startContainer;for(i.nodeType===3&&(i=i.parentElement);i&&!i.style;)i=i.parentElement;const s=i&&i.style.fontSize||"";if(s)return s}const e=n&&n.layoutInfo&&n.layoutInfo.editable;return e&&e.style.fontSize||""}catch{return""}}},de=S("removeFormat","remove-format","Remove Format",()=>I("removeFormat")),fi=S("direction","direction","Toggle Text Direction (LTR / RTL)",n=>{const t=n.layoutInfo.editable,i=(t.getAttribute("dir")||"ltr")==="ltr"?"rtl":"ltr";t.setAttribute("dir",i),t.style.textAlign=i==="rtl"?"right":"left",n.invoke("editor.afterCommand")}),pe={name:"fontFamily",type:"select",tooltip:"Font Family",action:(n,t)=>Rt(t),getValue:()=>{try{return document.queryCommandValue("fontName")||""}catch{return""}}},ue={name:"paragraphStyle",type:"select",tooltip:"Paragraph Style",placeholder:"Style",selectClass:"an-select-style",items:[{value:"p",label:"Normal"},{value:"h1",label:"H1"},{value:"h2",label:"H2"},{value:"h3",label:"H3"},{value:"h4",label:"H4"},{value:"h5",label:"H5"},{value:"h6",label:"H6"},{value:"blockquote",label:"Quote"},{value:"pre",label:"Code"}],action:(n,t)=>Lt(t),getValue:()=>{try{const n=document.queryCommandValue("formatBlock").toLowerCase().replace(/[<>]/g,"");return n==="div"?"p":n||"p"}catch{return""}}},me={name:"lineHeight",type:"select",tooltip:"Line Height",placeholder:"↕ Line",selectClass:"an-select-narrow",items:["1.0","1.15","1.5","1.75","2.0","2.5","3.0"],action:(n,t)=>hi(t),getValue:()=>{try{const n=window.getSelection();if(!n||!n.rangeCount)return"";const t=new Set(["P","DIV","H1","H2","H3","H4","H5","H6","LI","BLOCKQUOTE","PRE","TD","TH"]);let e=n.getRangeAt(0).startContainer;for(e.nodeType===3&&(e=e.parentElement);e&&!t.has(e.tagName);)e=e.parentElement;return e&&e.style.lineHeight||""}catch{return""}}},fe=S("codeview","code","HTML Code View",n=>n.invoke("codeview.toggle"),n=>n.invoke("codeview.isActive")),ge=S("fullscreen","expand","Fullscreen",n=>n.invoke("fullscreen.toggle"),n=>n.invoke("fullscreen.isActive")),ye=S("shortcuts","keyboard","Keyboard Shortcuts (Shift+?)",n=>n.invoke("shortcutsDialog.show")),_e=S("find","search","Find (Ctrl+F)",n=>n.invoke("findReplace.show","find")),gi=S("findReplace","find-replace","Find & Replace (Ctrl+H)",n=>n.invoke("findReplace.show","replace")),be=S("inlineCode","inline-code","Inline Code (Ctrl+`)",n=>n.invoke("editor.inlineCode"),()=>pi()),ve=S("checklist","checklist","Checklist",n=>n.invoke("editor.toggleChecklist"),()=>mi()),we=S("print","print","Print",n=>n.invoke("editor.print")),xe={name:"foreColor",type:"colorpicker",icon:"foreColor",tooltip:"Text Color",defaultColor:"#e11d48",action:(n,t)=>Et(t)},ke={name:"backColor",type:"colorpicker",icon:"backColor",tooltip:"Highlight Color",defaultColor:"#fbbf24",action:(n,t)=>Bt(t)},Ce=[[ue,pe,he,me],[ee,ie],[Ot,Ft,Wt,Ut,be],[qt,Vt],[xe,ke],[Yt,Kt,Xt,Gt],[Jt,Qt,ve,Zt,te],[se,ne,oe,ae,ce,le,re],[de,fe,ge,_e,we,ye]],F={placeholder:"",height:200,minHeight:100,maxHeight:0,focus:!1,resizable:!0,toolbar:Ce,useBootstrap:!1,toolbarButtonClass:"btn btn-sm btn-light",useFontAwesome:!0,fontAwesomeClass:"fas",pasteAsPlainText:!1,pasteCleanHTML:!0,pasteStripAttributes:!1,allowImageUpload:!0,maxImageSize:5,tabSize:4,onChange:null,onFocus:null,onBlur:null,onInit:null,onImageUpload:null,onImageError:null,stickyToolbar:!1,stickyToolbarOffset:0,theme:"light",codeHighlight:!0,codeHighlightCDN:"https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0",markdownPaste:!0,historyLimit:100,defaultFontFamily:"Arial",defaultFontSize:"14px",fontFamilies:["Arial","Arial Black","Comic Sans MS","Courier New","Georgia","Impact","Tahoma","Times New Roman","Trebuchet MS","Verdana"],readOnly:!1,spellcheck:!0,direction:"ltr",toolbarOverflow:"wrap",autoSave:!1,autoSaveKey:"autumnnote-autosave",maxChars:0,maxWords:0,tableHeaderRow:!1,onSelectionChange:null,colorSwatches:[],onPaste:null,onDestroy:null,onCharLimitReached:null,onWordLimitReached:null},Te=["script","style","iframe","object","embed","form","input","button"],yi=["href","src","action","formaction"];function W(n,{allowIframes:t=!1}={}){const e=new DOMParser().parseFromString(`<body>${n||""}</body>`,"text/html");return(t?Te.filter(s=>s!=="iframe"):Te).forEach(s=>{e.querySelectorAll(s).forEach(o=>o.remove())}),e.querySelectorAll("*").forEach(s=>{Array.from(s.attributes).forEach(o=>{if(o.name.startsWith("on")){s.removeAttribute(o.name);return}if(yi.includes(o.name)){const a=o.value.trim();if(/^(javascript|vbscript):/i.test(a)){s.removeAttribute(o.name);return}/^data:/i.test(a)&&!(o.name==="src"&&s.tagName==="IMG")&&s.removeAttribute(o.name)}})}),e.body.innerHTML}function mt(n,{allowData:t=!1}={}){const e=(n||"").trim();return/^(javascript|vbscript):/i.test(e)||!t&&/^data:/i.test(e)?null:n}function _i(n,t){const e=c("div",{class:"an-container"}),i=c("div",{class:"an-editable",contenteditable:t.readOnly?"false":"true",spellcheck:String(t.spellcheck!==!1),"aria-multiline":"true","aria-label":"Rich text editor",role:"textbox"});let s="";if(t.autoSave&&t.autoSaveKey)try{s=localStorage.getItem(t.autoSaveKey)||""}catch{}s||(s=n.tagName==="TEXTAREA"?(n.value||"").trim():(n.innerHTML||"").trim()),i.innerHTML=W(s,{allowIframes:!0});const o=t.defaultFontFamily||t.fontFamilies&&t.fontFamilies[0];return o&&(i.style.fontFamily=o),t.defaultFontSize&&(i.style.fontSize=t.defaultFontSize),t.height?i.style.minHeight=`${t.height}px`:t.minHeight&&(i.style.minHeight=`${t.minHeight}px`),t.maxHeight&&(i.style.maxHeight=`${t.maxHeight}px`),e.appendChild(i),t.theme==="dark"&&e.classList.add("an-theme-dark"),t.readOnly&&e.classList.add("an-disabled"),t.direction==="rtl"&&(i.setAttribute("dir","rtl"),e.classList.add("an-dir-rtl")),t.toolbarOverflow==="scroll"&&e.classList.add("an-toolbar-overflow-scroll"),t.stickyToolbar&&(e.classList.add("an-sticky-toolbar"),t.stickyToolbarOffset&&e.style.setProperty("--an-sticky-top",`${t.stickyToolbarOffset}px`)),n.style.display="none",n.insertAdjacentElement("afterend",e),{container:e,editable:i}}class bi{constructor(t,e=100){this.editable=t,this._limit=e,this.stack=[],this.stackOffset=-1,this._savePoint()}_serialize(){return this.editable.innerHTML}_serializeSelection(){const t=window.getSelection();if(!t||t.rangeCount===0)return null;const e=t.getRangeAt(0);return this.editable.contains(e.startContainer)?{start:this._charOffset(e.startContainer,e.startOffset),end:this._charOffset(e.endContainer,e.endOffset)}:null}_charOffset(t,e){let i=0;const s=document.createTreeWalker(this.editable,NodeFilter.SHOW_TEXT,null);let o;for(;o=s.nextNode();){if(o===t)return i+e;i+=o.length}return i}_restoreSelection(t){if(!t)return;let e=null,i=0,s=null,o=0,a=0;const l=document.createTreeWalker(this.editable,NodeFilter.SHOW_TEXT,null);let r;for(;r=l.nextNode();){const h=r.length;if(!e&&a+h>=t.start&&(e=r,i=t.start-a),!s&&a+h>=t.end){s=r,o=t.end-a;break}a+=h}if(e){s||(s=e,o=i);try{const h=document.createRange();h.setStart(e,i),h.setEnd(s,o);const u=window.getSelection();u.removeAllRanges(),u.addRange(h)}catch{}}}_savePoint(){this.stackOffset<this.stack.length-1&&(this.stack=this.stack.slice(0,this.stackOffset+1));const t=this._serialize(),{html:e,images:i}=this._tokenizeImages(t);this.stack.push({html:e,images:i,sel:this._serializeSelection()}),this.stack.length>this._limit?this.stack.shift():this.stackOffset++}_restore(t){t&&(this.editable.innerHTML=this._detokenizeImages(t),this._restoreSelection(t.sel))}_tokenizeImages(t){const e={};let i=0;return{html:t.replace(/data:[^;]+;base64,[^"' >]*/g,o=>{const a=`__asn_img_${i}__`;return e[a]=o,i++,a}),images:e}}_detokenizeImages(t){return!t.images||Object.keys(t.images).length===0?t.html:t.html.replace(/__asn_img_\d+__/g,e=>t.images[e]||e)}recordUndo(){const t=this._serialize(),{html:e}=this._tokenizeImages(t),i=this.stack[this.stackOffset];i&&i.html===e||this._savePoint()}undo(){this.stackOffset<=0||(this.stackOffset--,this._restore(this.stack[this.stackOffset]))}redo(){this.stackOffset>=this.stack.length-1||(this.stackOffset++,this._restore(this.stack[this.stackOffset]))}reset(){this.stack=[],this.stackOffset=-1,this._savePoint()}canUndo(){return this.stackOffset>0}canRedo(){return this.stackOffset<this.stack.length-1}}function vi(n,t,e={}){const{headerRow:i=!1}=e,s=c("table",{class:"an-table"});if(i&&t>0){const l=c("thead"),r=c("tr");for(let h=0;h<n;h++){const u=c("th",{},[" "]);r.appendChild(u)}l.appendChild(r),s.appendChild(l)}const o=i?Math.max(t-1,1):t,a=c("tbody");s.appendChild(a);for(let l=0;l<o;l++){const r=c("tr");for(let h=0;h<n;h++){const u=c("td",{},[" "]);r.appendChild(u)}a.appendChild(r)}return s}function wi(n,t,e={}){const i=vi(n,t,e);I("insertHTML",i.outerHTML)}const Q={BACKSPACE:"Backspace",TAB:"Tab",ENTER:"Enter",ESCAPE:"Escape",SPACE:" ",PAGE_UP:"PageUp",PAGE_DOWN:"PageDown",END:"End",HOME:"Home",LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",DOWN:"ArrowDown",DELETE:"Delete",NUM0:"0",NUM1:"1",NUM2:"2",NUM3:"3",NUM4:"4",NUM5:"5",NUM6:"6",NUM7:"7",NUM8:"8",B:"b",E:"e",I:"i",J:"j",K:"k",L:"l",R:"r",S:"s",U:"u",V:"v",Y:"y",Z:"z",SLASH:"/",PERIOD:"."};function K(n,t){return n.key===t||n.key===t.toUpperCase()}function N(n,t){return(n.ctrlKey||n.metaKey)&&K(n,t)}function xi(n,t,e={}){if(K(n,Q.TAB)){const i=ut(t);if(!i)return!1;const s=dt(i.sc,t);if(s&&vt(s))return n.preventDefault(),n.shiftKey?I("outdent"):I("indent"),!0;if(s&&s.nodeName.toUpperCase()==="PRE")return n.preventDefault(),I("insertText"," "),!0;if(e.tabSize)return n.preventDefault(),I("insertText"," ".repeat(e.tabSize)),!0}if(K(n,Q.ENTER)&&n.shiftKey)return n.preventDefault(),I("insertLineBreak"),!0;if(K(n,Q.ENTER)&&!n.shiftKey){const i=ut(t);if(!i)return!1;const s=i.sc,o=s.nodeType===3?s.parentElement:s,a=o&&o.closest&&o.closest(".an-checklist li");if(a){n.preventDefault();const r=a.closest(".an-checklist"),h=window.getSelection(),u=h.getRangeAt(0),m=document.createRange();m.setStart(u.endContainer,u.endOffset),m.setEnd(a,a.childNodes.length);const g=m.extractContents();if(Array.from(a.childNodes).filter(f=>!(f.nodeType===1&&f.tagName==="INPUT")).map(f=>f.textContent).join("").replace(/\u00a0/g," ").trim()){const f=document.createElement("li"),_=document.createElement("input");_.type="checkbox",_.setAttribute("contenteditable","false"),f.appendChild(_);let k;g.textContent.length>0?(f.appendChild(g),k=f.childNodes[1]):(k=document.createTextNode(" "),f.appendChild(k)),a.insertAdjacentElement("afterend",f);const C=document.createRange();C.setStart(k,0),C.collapse(!0),h.removeAllRanges(),h.addRange(C)}else{const f=document.createElement("p"),_=g.textContent.replace(/\u00a0/g," ").trim();f.textContent=_||" ",r.parentNode.insertBefore(f,r.nextSibling),a.remove(),r.children.length===0&&r.remove();const k=document.createRange();k.setStart(f,0),k.collapse(!0),h.removeAllRanges(),h.addRange(k)}return!0}const l=dt(i.sc,t);if(l&&l.nodeName.toUpperCase()==="BLOCKQUOTE"){const r=i.toNativeRange();if(r.setEnd(l,l.childNodes.length),r.toString()===""&&i.isCollapsed())return n.preventDefault(),I("formatBlock","<p>"),!0}}return!1}function ki(n){const t=new DOMParser().parseFromString(`<body>${n||""}</body>`,"text/html");return at(t.body).replace(/\n{3,}/g,`
|
|
1
|
+
(function(K,D){typeof exports=="object"&&typeof module<"u"?module.exports=D():typeof define=="function"&&define.amd?define(D):(K=typeof globalThis<"u"?globalThis:K||self,K.AutumnNote=D())})(this,function(){"use strict";function K(n,e){let t;return function(...i){clearTimeout(t),t=setTimeout(()=>n.apply(this,i),e)}}function D(n,e){const t={};for(const i of Object.keys(n))t[i]=Array.isArray(n[i])?[...n[i]]:n[i];if(he(n)&&he(e))for(const i of Object.keys(e))he(e[i])?i in n?t[i]=D(n[i],e[i]):t[i]=D({},e[i]):Array.isArray(e[i])?t[i]=[...e[i]]:t[i]=e[i];return t}function he(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}const Xe=1,se=n=>n&&n.nodeType===Xe,Ye=n=>se(n)&&/^(p|div|li|h[1-6]|blockquote|td|th|pre)$/i.test(n.nodeName),Ke=n=>se(n)&&/^(li)$/i.test(n.nodeName);function me(n,e,t){let i=n;for(;i&&i!==t;){if(e(i))return i;i=i.parentNode}return null}function fe(n,e){return me(n,Ye,e)}function c(n,e={},t=[]){const i=document.createElement(n);for(const[s,o]of Object.entries(e))i.setAttribute(s,o);for(const s of t)typeof s=="string"?i.appendChild(document.createTextNode(s)):i.appendChild(s);return i}function d(n,e,t,i){return n.addEventListener(e,t,i),()=>n.removeEventListener(e,t,i)}function O(n,e){const t='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',i=()=>Array.from(n.querySelectorAll(t)).filter(o=>!o.closest('[style*="display: none"]')&&!o.closest('[style*="display:none"]')),s=o=>{if(o.key==="Escape"){o.stopPropagation(),e&&e();return}if(o.key!=="Tab")return;const a=i();if(!a.length)return;const r=a[0],l=a[a.length-1];o.shiftKey?document.activeElement===r&&(o.preventDefault(),l.focus()):document.activeElement===l&&(o.preventDefault(),r.focus())};return document.addEventListener("keydown",s),()=>document.removeEventListener("keydown",s)}class Ge{constructor(e,t,i,s){this.sc=e,this.so=t,this.ec=i,this.eo=s}isCollapsed(){return this.sc===this.ec&&this.so===this.eo}toNativeRange(){const e=document.createRange();try{e.setStart(this.sc,this.so),e.setEnd(this.ec,this.eo)}catch{}return e}select(){const e=window.getSelection();e&&(e.removeAllRanges(),e.addRange(this.toNativeRange()))}commonAncestor(){const t=this.toNativeRange().commonAncestorContainer;return se(t)?t:t.parentElement}blockNode(e){return me(this.sc,t=>se(t)&&t!==e,e)}toString(){return this.toNativeRange().toString()}getClientRects(){const e=this.toNativeRange().getClientRects();return e.length>0?e[e.length-1]:null}insertNode(e){this.toNativeRange().insertNode(e)}}function ge(n){return new Ge(n.startContainer,n.startOffset,n.endContainer,n.endOffset)}function _e(n){const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0);return n&&!n.contains(t.commonAncestorContainer)?null:ge(t)}function G(n){const e=window.getSelection();if(!e||e.rangeCount===0){n(null);return}const t=e.getRangeAt(0).cloneRange();n(ge(t)),e.removeAllRanges(),e.addRange(t)}function S(n,e=null){return document.execCommand(n,!1,e)}const ye=()=>S("bold"),be=()=>S("italic");function ve(){const n=window.getSelection();if(!n||!n.rangeCount)return;let e=n.getRangeAt(0).commonAncestorContainer;e.nodeType===3&&(e=e.parentElement);const t=e&&e.closest&&e.closest("u"),i=document.queryCommandState("underline");if(t&&!i){const s=t.parentNode;for(;t.firstChild;)s.insertBefore(t.firstChild,t);s.removeChild(t);return}S("underline")}const we=()=>S("strikeThrough"),xe=()=>S("superscript"),Ce=()=>S("subscript"),ke=n=>S("foreColor",n),Te=n=>S("hiliteColor",n),Se=n=>S("fontName",n);function Ie(n,e=document){S("fontSize","7"),e.querySelectorAll('font[size="7"]').forEach(t=>{const i=document.createElement("span");for(i.style.fontSize=n,t.parentNode.insertBefore(i,t);t.firstChild;)i.appendChild(t.firstChild);t.parentNode.removeChild(t)})}const Ee=n=>S("formatBlock",`<${n}>`),Re=()=>S("justifyLeft"),Ae=()=>S("justifyCenter"),Le=()=>S("justifyRight"),Be=()=>S("justifyFull"),Me=()=>S("indent"),Ne=()=>S("outdent"),je=()=>S("insertUnorderedList"),ze=()=>S("insertOrderedList");function Qe(n){const e=window.getSelection();if(!e||e.rangeCount===0)return;const t=e.getRangeAt(0),i=new Set(["P","DIV","H1","H2","H3","H4","H5","H6","LI","BLOCKQUOTE","PRE","TD","TH"]),s=l=>{let h=l instanceof Element?l:l.parentElement;for(;h;){if(i.has(h.tagName))return h;h=h.parentElement}return null};if(t.collapsed){const l=s(t.startContainer);l&&(l.style.lineHeight=n);return}const o=new Set,a=document.createNodeIterator(t.commonAncestorContainer,NodeFilter.SHOW_TEXT,null);let r;for(;r=a.nextNode();)if(t.intersectsNode(r)){const l=s(r);l&&o.add(l)}if(o.size===0){const l=s(t.commonAncestorContainer);l&&o.add(l)}o.forEach(l=>{l.style.lineHeight=n})}function Ze(n){const e=window.getSelection();if(!e||!e.rangeCount)return;const t=e.getRangeAt(0);let i=t.commonAncestorContainer;i.nodeType===3&&(i=i.parentElement);const s=i&&i.closest?i.closest("code"):null;if(s&&!s.closest("pre")){const o=s.parentNode;for(;s.firstChild;)o.insertBefore(s.firstChild,s);o.removeChild(s),n&&n.normalize()}else{if(t.collapsed)return;try{const o=document.createElement("code");t.surroundContents(o);const a=document.createRange();a.selectNodeContents(o),e.removeAllRanges(),e.addRange(a)}catch{const o=t.extractContents(),a=document.createElement("code");a.appendChild(o),t.insertNode(a);const r=document.createRange();r.selectNodeContents(a),e.removeAllRanges(),e.addRange(r)}}}function Je(){const n=window.getSelection();if(!n||!n.rangeCount)return!1;let e=n.getRangeAt(0).commonAncestorContainer;e.nodeType===3&&(e=e.parentElement);const t=e&&e.closest?e.closest("code"):null;return!!(t&&!t.closest("pre"))}function et(){const n=window.getSelection();if(!n||!n.rangeCount)return;let t=n.getRangeAt(0).commonAncestorContainer;t.nodeType===3&&(t=t.parentElement);const i=t&&t.closest?t.closest(".an-checklist li"):null;if(i){const s=i.closest(".an-checklist"),o=Array.from(i.childNodes).filter(h=>!(h.nodeType===1&&h.tagName==="INPUT")).map(h=>h.textContent).join("").replace(/\u00a0/g," ").trim(),a=document.createElement("p");a.textContent=o||" ",s.parentNode.insertBefore(a,s.nextSibling),s.removeChild(i),s.children.length===0&&s.remove();const r=document.createRange(),l=a.firstChild||a;r.setStart(l,0),r.collapse(!0),n.removeAllRanges(),n.addRange(r)}else{const s="data-an-new-cli";S("insertHTML",`<ul class="an-checklist"><li ${s}><input type="checkbox" contenteditable="false"></li></ul>`);const o=document.querySelector(`[${s}]`);if(o){o.removeAttribute(s);const a=o.querySelector('input[type="checkbox"]');if(a){let r=a.nextSibling;!r||r.nodeType!==Node.TEXT_NODE?(r=document.createTextNode(""),o.appendChild(r)):r.textContent||(r.textContent="");const l=document.createRange();l.setStart(r,0),l.collapse(!0),n.removeAllRanges(),n.addRange(l)}}}}function tt(){const n=window.getSelection();if(!n||!n.rangeCount)return!1;let e=n.getRangeAt(0).commonAncestorContainer;return e.nodeType===3&&(e=e.parentElement),!!(e&&e.closest&&e.closest(".an-checklist li"))}function E(n,e,t,i,s,o){return{name:n,icon:e,tooltip:t,action:i,isActive:s,isDisabled:o}}const it=E("bold","bold","Bold (Ctrl+B)",()=>ye(),()=>document.queryCommandState("bold")),st=E("italic","italic","Italic (Ctrl+I)",()=>be(),()=>document.queryCommandState("italic")),ot=E("underline","underline","Underline (Ctrl+U)",()=>ve(),()=>{if(document.queryCommandState("underline"))return!0;const n=window.getSelection();if(!n||!n.rangeCount)return!1;let e=n.getRangeAt(0).commonAncestorContainer;return e.nodeType===3&&(e=e.parentElement),!!(e&&e.closest&&e.closest("u"))}),nt=E("strikethrough","strikethrough","Strikethrough",()=>we(),()=>document.queryCommandState("strikeThrough")),at=E("superscript","superscript","Superscript",()=>xe(),()=>document.queryCommandState("superscript")),lt=E("subscript","subscript","Subscript",()=>Ce(),()=>document.queryCommandState("subscript")),rt=E("alignLeft","align-left","Align Left",()=>Re()),ct=E("alignCenter","align-center","Align Center",()=>Ae()),ht=E("alignRight","align-right","Align Right",()=>Le()),dt=E("alignJustify","align-justify","Justify",()=>Be()),pt=E("ul","list-ul","Unordered List",()=>je()),ut=E("ol","list-ol","Ordered List",()=>ze()),mt=E("indent","indent","Indent",()=>Me()),ft=E("outdent","outdent","Outdent",()=>Ne()),gt=E("undo","undo","Undo (Ctrl+Z)",n=>n.invoke("editor.undo"),void 0,n=>!n.invoke("editor.canUndo")),_t=E("redo","redo","Redo (Ctrl+Y)",n=>n.invoke("editor.redo"),void 0,n=>!n.invoke("editor.canRedo")),yt=E("hr","minus","Horizontal Rule",()=>S("insertHorizontalRule")),bt=E("link","link","Insert Link",n=>n.invoke("linkDialog.show")),vt=E("image","image","Insert Image",n=>n.invoke("imageDialog.show")),wt=E("video","video","Insert Video",n=>n.invoke("videoDialog.show")),xt=E("emoji","emoji","Insert Emoji",n=>n.invoke("emojiDialog.show")),Ct=E("icon","icon","Insert FA Icon",n=>n.invoke("iconDialog.show")),kt={name:"table",type:"grid",icon:"table",tooltip:"Insert Table",action:(n,e,t)=>{n.invoke("editor.insertTable",t,e),n.invoke("editor.afterCommand")}},Tt={name:"fontSize",type:"select",tooltip:"Font Size",placeholder:"Size",selectClass:"an-select-narrow",items:["8px","10px","11px","12px","13px","14px","16px","18px","20px","24px","28px","32px","36px","48px","72px"],action:(n,e)=>Ie(e,n.layoutInfo.editable),getValue:n=>{try{const e=window.getSelection();if(e&&e.rangeCount){let i=e.getRangeAt(0).startContainer;for(i.nodeType===3&&(i=i.parentElement);i&&i.nodeType===1&&!i.style.fontSize;)i=i.parentElement;const s=i&&i.style&&i.style.fontSize?i.style.fontSize:"";if(s)return s}const t=n&&n.layoutInfo&&n.layoutInfo.editable;return t&&t.style.fontSize||""}catch{return""}}},St=E("removeFormat","remove-format","Remove Format",()=>S("removeFormat")),It={name:"fontFamily",type:"select",tooltip:"Font Family",action:(n,e)=>Se(e),getValue:()=>{try{return document.queryCommandValue("fontName")||""}catch{return""}}},Et={name:"paragraphStyle",type:"select",tooltip:"Paragraph Style",placeholder:"Style",selectClass:"an-select-style",items:[{value:"p",label:"Normal"},{value:"h1",label:"H1"},{value:"h2",label:"H2"},{value:"h3",label:"H3"},{value:"h4",label:"H4"},{value:"h5",label:"H5"},{value:"h6",label:"H6"},{value:"blockquote",label:"Quote"},{value:"pre",label:"Code"}],action:(n,e)=>Ee(e),getValue:()=>{try{const n=document.queryCommandValue("formatBlock").toLowerCase().replace(/[<>]/g,"");return n==="div"?"p":n||"p"}catch{return""}}},Rt={name:"lineHeight",type:"select",tooltip:"Line Height",placeholder:"↕ Line",selectClass:"an-select-narrow",items:["1.0","1.15","1.5","1.75","2.0","2.5","3.0"],action:(n,e)=>Qe(e),getValue:()=>{try{const n=window.getSelection();if(!n||!n.rangeCount)return"";const e=new Set(["P","DIV","H1","H2","H3","H4","H5","H6","LI","BLOCKQUOTE","PRE","TD","TH"]);let t=n.getRangeAt(0).startContainer;for(t.nodeType===3&&(t=t.parentElement);t&&!e.has(t.tagName);)t=t.parentElement;return t&&(t.style.lineHeight||getComputedStyle(t).lineHeight)||""}catch{return""}}},At=E("codeview","code","HTML Code View",n=>n.invoke("codeview.toggle"),n=>n.invoke("codeview.isActive")),Lt=E("fullscreen","expand","Fullscreen",n=>n.invoke("fullscreen.toggle"),n=>n.invoke("fullscreen.isActive")),Bt=E("shortcuts","keyboard","Keyboard Shortcuts (Ctrl+Shift+/)",n=>n.invoke("shortcutsDialog.show")),Mt=E("find","search","Find (Ctrl+F)",n=>n.invoke("findReplace.show","find")),Nt=E("inlineCode","inline-code","Inline Code (Ctrl+`)",n=>n.invoke("editor.inlineCode"),()=>Je()),jt=E("checklist","checklist","Checklist",n=>n.invoke("editor.toggleChecklist"),()=>tt()),zt=E("print","print","Print",n=>n.invoke("editor.print")),F={placeholder:"",height:200,minHeight:100,maxHeight:0,focus:!1,resizable:!0,toolbar:[[Et,It,Tt,Rt],[gt,_t],[it,st,ot,nt,Nt],[at,lt],[{name:"foreColor",type:"colorpicker",icon:"foreColor",tooltip:"Text Color",defaultColor:"#e11d48",action:(n,e)=>ke(e)},{name:"backColor",type:"colorpicker",icon:"backColor",tooltip:"Highlight Color",defaultColor:"#fbbf24",action:(n,e)=>Te(e)}],[rt,ct,ht,dt],[pt,ut,jt,mt,ft],[yt,bt,vt,wt,kt,xt,Ct],[St,At,Lt,Mt,zt,Bt]],useBootstrap:!1,toolbarButtonClass:"btn btn-sm btn-light",useFontAwesome:!0,fontAwesomeClass:"fas",pasteAsPlainText:!1,pasteCleanHTML:!0,pasteStripAttributes:!1,allowImageUpload:!0,maxImageSize:5,tabSize:4,onChange:null,onFocus:null,onBlur:null,onInit:null,onImageUpload:null,onImageError:null,stickyToolbar:!1,stickyToolbarOffset:0,theme:"light",codeHighlight:!0,codeHighlightCDN:"https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0",markdownPaste:!0,historyLimit:100,defaultFontFamily:"Arial",defaultFontSize:"14px",fontFamilies:["Arial","Arial Black","Comic Sans MS","Courier New","Georgia","Impact","Tahoma","Times New Roman","Trebuchet MS","Verdana"],readOnly:!1,spellcheck:!0,direction:"ltr",toolbarOverflow:"wrap",autoSave:!1,autoSaveKey:"autumnnote-autosave",maxChars:0,maxWords:0,tableHeaderRow:!1,onSelectionChange:null,colorSwatches:[],onPaste:null,onDestroy:null,onCharLimitReached:null,onWordLimitReached:null,focusColor:null},He=["script","style","iframe","object","embed","form","input","button"],Ht=["href","src","action","formaction"],$t=new Set(["www.youtube.com","youtube.com","m.youtube.com","www.youtube-nocookie.com","youtube-nocookie.com","player.vimeo.com"]);function W(n,{allowIframes:e=!1}={}){const t=new DOMParser().parseFromString(`<body>${n||""}</body>`,"text/html");return(e?He.filter(s=>s!=="iframe"):He).forEach(s=>{t.querySelectorAll(s).forEach(o=>o.remove())}),t.querySelectorAll("*").forEach(s=>{Array.from(s.attributes).forEach(o=>{if(o.name.startsWith("on")){s.removeAttribute(o.name);return}if(Ht.includes(o.name)){const a=o.value.trim();if(/^(javascript|vbscript):/i.test(a)){s.removeAttribute(o.name);return}/^data:/i.test(a)&&!(o.name==="src"&&s.tagName==="IMG")&&s.removeAttribute(o.name)}if(s.tagName==="IFRAME"){if(o.name==="srcdoc"){s.removeAttribute(o.name);return}if(o.name==="src"){Pt(o.value)||s.removeAttribute(o.name);return}}})}),t.body.innerHTML}function Pt(n){const e=(n||"").trim();if(!e||e.startsWith("//")||e.startsWith("/"))return!1;try{const t=new URL(e);return t.protocol!=="https:"?!1:$t.has(t.hostname.toLowerCase())}catch{return!1}}function $e(n,{allowData:e=!1}={}){const t=(n||"").trim();return/^(javascript|vbscript):/i.test(t)||!e&&/^data:/i.test(t)?null:n}function Dt(n,e){const t=c("div",{class:"an-container"}),i=c("div",{class:"an-editable",contenteditable:e.readOnly?"false":"true",spellcheck:String(e.spellcheck!==!1),"aria-multiline":"true","aria-label":"Rich text editor",role:"textbox"});let s="";if(e.autoSave&&e.autoSaveKey)try{s=localStorage.getItem(e.autoSaveKey)||""}catch{}s||(s=n.tagName==="TEXTAREA"?(n.value||"").trim():(n.innerHTML||"").trim()),i.innerHTML=W(s,{allowIframes:!0});const o=e.defaultFontFamily||e.fontFamilies&&e.fontFamilies[0];return o&&(i.style.fontFamily=o),e.defaultFontSize&&(i.style.fontSize=e.defaultFontSize),e.height?i.style.minHeight=`${e.height}px`:e.minHeight&&(i.style.minHeight=`${e.minHeight}px`),e.maxHeight&&(i.style.maxHeight=`${e.maxHeight}px`),t.appendChild(i),e.theme==="dark"&&t.classList.add("an-theme-dark"),e.readOnly&&t.classList.add("an-disabled"),e.direction==="rtl"&&(i.setAttribute("dir","rtl"),t.classList.add("an-dir-rtl")),e.toolbarOverflow==="scroll"&&t.classList.add("an-toolbar-overflow-scroll"),e.stickyToolbar&&(t.classList.add("an-sticky-toolbar"),e.stickyToolbarOffset&&t.style.setProperty("--an-sticky-top",`${e.stickyToolbarOffset}px`)),e.focusColor&&t.style.setProperty("--an-focus-color",e.focusColor),n.style.display="none",n.insertAdjacentElement("afterend",t),{container:t,editable:i}}class Ot{constructor(e,t=100){this.editable=e,this._limit=t,this.stack=[],this.stackOffset=-1,this._savePoint()}_serialize(){return this.editable.innerHTML}_serializeSelection(){const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0);return this.editable.contains(t.startContainer)?{start:this._charOffset(t.startContainer,t.startOffset),end:this._charOffset(t.endContainer,t.endOffset)}:null}_charOffset(e,t){let i=0;const s=document.createTreeWalker(this.editable,NodeFilter.SHOW_TEXT,null);let o;for(;o=s.nextNode();){if(o===e)return i+t;i+=o.length}return 0}_restoreSelection(e){if(!e)return;let t=null,i=0,s=null,o=0,a=0;const r=document.createTreeWalker(this.editable,NodeFilter.SHOW_TEXT,null);let l;for(;l=r.nextNode();){const h=l.length;if(!t&&a+h>=e.start&&(t=l,i=e.start-a),!s&&a+h>=e.end){s=l,o=e.end-a;break}a+=h}if(!t){const h=document.createTreeWalker(this.editable,NodeFilter.SHOW_TEXT,null);let p=null;for(;p=h.nextNode();)t=p;i=t?t.length:0,s=t,o=i}s||(s=t,o=i);try{const h=document.createRange();h.setStart(t,i),h.setEnd(s,o);const p=window.getSelection();p.removeAllRanges(),p.addRange(h)}catch{}}_savePoint(){this.stackOffset<this.stack.length-1&&(this.stack=this.stack.slice(0,this.stackOffset+1));const e=this._serialize(),{html:t,images:i}=this._tokenizeImages(e);this.stack.push({html:t,images:i,sel:this._serializeSelection()}),this.stack.length>this._limit?this.stack.shift():this.stackOffset++}_restore(e){e&&(this.editable.innerHTML=this._detokenizeImages(e),this._restoreSelection(e.sel))}_tokenizeImages(e){const t={};let i=0;return{html:e.replace(/data:[^;]+;base64,[^"' >]*/g,o=>{const a=`__asn_img_${i}__`;return t[a]=o,i++,a}),images:t}}_detokenizeImages(e){return!e.images||Object.keys(e.images).length===0?e.html:e.html.replace(/__asn_img_\d+__/g,t=>e.images[t]||t)}recordUndo(){const e=this._serialize(),{html:t}=this._tokenizeImages(e),i=this.stack[this.stackOffset];i&&i.html===t||this._savePoint()}undo(){this.stackOffset<=0||(this.stackOffset--,this._restore(this.stack[this.stackOffset]))}redo(){this.stackOffset>=this.stack.length-1||(this.stackOffset++,this._restore(this.stack[this.stackOffset]))}reset(){this.stack=[],this.stackOffset=-1,this._savePoint()}canUndo(){return this.stackOffset>0}canRedo(){return this.stackOffset<this.stack.length-1}}function Ft(n,e,t={}){const{headerRow:i=!1}=t,s=c("table",{class:"an-table"});if(i&&e>0){const r=c("thead"),l=c("tr");for(let h=0;h<n;h++){const p=c("th",{},[" "]);l.appendChild(p)}r.appendChild(l),s.appendChild(r)}const o=i?Math.max(e-1,1):e,a=c("tbody");s.appendChild(a);for(let r=0;r<o;r++){const l=c("tr");for(let h=0;h<n;h++){const p=c("td",{},[" "]);l.appendChild(p)}a.appendChild(l)}return s}function Wt(n,e,t={}){const i=Ft(n,e,t);S("insertHTML",i.outerHTML)}const P={BACKSPACE:"Backspace",TAB:"Tab",ENTER:"Enter",ESCAPE:"Escape",LEFT:"ArrowLeft",RIGHT:"ArrowRight"};function $(n,e){return n.key===e||n.key===e.toUpperCase()}function N(n,e){return(n.ctrlKey||n.metaKey)&&$(n,e)}function Ut(n,e,t={}){const i=a=>!!(a&&a.nodeName==="I"&&/\bfa-/.test(a.className||"")),s=a=>!!(a&&a.nodeType===Node.TEXT_NODE&&(a.textContent===""||a.textContent==="")),o=a=>{const r=window.getSelection();if(!r)return!1;const l=document.createRange();return a(l),l.collapse(!0),r.removeAllRanges(),r.addRange(l),!0};if($(n,P.BACKSPACE)){const a=window.getSelection();if(a&&a.rangeCount>0){const r=a.getRangeAt(0);if(r.collapsed&&r.startContainer.nodeType===Node.TEXT_NODE){const l=r.startContainer;if(r.startOffset===0&&i(l.previousSibling))return n.preventDefault(),l.previousSibling.remove(),!0;if(r.startOffset===1&&l.textContent===""&&i(l.previousSibling))return n.preventDefault(),l.previousSibling.remove(),l.remove(),!0}}return!1}if($(n,P.LEFT)||$(n,P.RIGHT)){const a=window.getSelection();if(!a||a.rangeCount===0)return!1;const r=a.getRangeAt(0);if(!r.collapsed)return!1;const l=r.startContainer,h=$(n,P.LEFT);if(l.nodeType===Node.TEXT_NODE){const p=l;if(h&&r.startOffset===1&&p.textContent===""&&i(p.previousSibling))return n.preventDefault(),o(m=>m.setStartBefore(p.previousSibling));if(h&&r.startOffset===0&&i(p.previousSibling))return n.preventDefault(),o(m=>m.setStartBefore(p.previousSibling));if(h&&r.startOffset===0&&s(p.previousSibling)&&i(p.previousSibling.previousSibling))return n.preventDefault(),o(m=>m.setStartBefore(p.previousSibling.previousSibling));if(!h&&r.startOffset===p.textContent.length&&i(p.nextSibling)){const m=p.nextSibling,u=m.nextSibling;if(n.preventDefault(),u&&u.nodeType===Node.TEXT_NODE){const f=(u.textContent||"").startsWith("")?1:0;return o(g=>g.setStart(u,Math.min(f,u.textContent.length)))}return o(f=>f.setStartAfter(m))}if(!h&&r.startOffset===p.textContent.length&&s(p.nextSibling)&&i(p.nextSibling.nextSibling)){const m=p.nextSibling.nextSibling,u=m.nextSibling;if(n.preventDefault(),u&&u.nodeType===Node.TEXT_NODE){const f=(u.textContent||"").startsWith("")?1:0;return o(g=>g.setStart(u,Math.min(f,u.textContent.length)))}return o(f=>f.setStartAfter(m))}}if(l.nodeType===Node.ELEMENT_NODE){const p=l;if(h&&r.startOffset>0){const m=p.childNodes[r.startOffset-1];if(i(m))return n.preventDefault(),o(u=>u.setStartBefore(m));if(s(m)&&i(m.previousSibling))return n.preventDefault(),o(u=>u.setStartBefore(m.previousSibling))}if(!h&&r.startOffset<p.childNodes.length){const m=p.childNodes[r.startOffset];if(i(m)){const u=m.nextSibling;if(n.preventDefault(),u&&u.nodeType===Node.TEXT_NODE){const f=(u.textContent||"").startsWith("")?1:0;return o(g=>g.setStart(u,Math.min(f,u.textContent.length)))}return o(f=>f.setStartAfter(m))}if(s(m)&&i(m.nextSibling)){const u=m.nextSibling,f=u.nextSibling;if(n.preventDefault(),f&&f.nodeType===Node.TEXT_NODE){const g=(f.textContent||"").startsWith("")?1:0;return o(b=>b.setStart(f,Math.min(g,f.textContent.length)))}return o(g=>g.setStartAfter(u))}}}}if($(n,P.TAB)){const a=_e(e);if(!a)return!1;const r=fe(a.sc,e);if(r&&Ke(r))return n.preventDefault(),n.shiftKey?S("outdent"):S("indent"),!0;if(r&&r.nodeName.toUpperCase()==="PRE")return n.shiftKey?!1:(n.preventDefault(),S("insertText"," "),!0);if(t.tabSize)return n.shiftKey?!1:(n.preventDefault(),S("insertText"," ".repeat(t.tabSize)),!0)}if($(n,P.ENTER)&&n.shiftKey)return n.preventDefault(),S("insertLineBreak"),!0;if($(n,P.ENTER)&&!n.shiftKey){const a=_e(e);if(!a)return!1;const r=a.sc,l=r.nodeType===3?r.parentElement:r;if(l&&l.nodeName==="I"&&/\bfa-/.test(l.className||"")){const u=document.createRange();u.setStartAfter(l),u.collapse(!0);const f=window.getSelection();return f&&(f.removeAllRanges(),f.addRange(u)),!1}const h=l&&l.closest&&l.closest(".an-video-wrapper");if(h){n.preventDefault();const u=document.createElement("p");u.innerHTML=" ",h.parentNode.insertBefore(u,h.nextSibling);const f=document.createRange();f.setStart(u,0),f.collapse(!0);const g=window.getSelection();return g.removeAllRanges(),g.addRange(f),!0}const p=l&&l.closest&&l.closest(".an-checklist li");if(p){n.preventDefault();const u=p.closest(".an-checklist"),f=window.getSelection();let g=f.getRangeAt(0);if(!(k=>Array.from(k.childNodes).filter(I=>!(I.nodeType===1&&I.tagName==="INPUT")).map(I=>I.textContent).join("").replace(/[\u00a0\u200B]/g," ").trim())(p)){const k=document.createElement("p");k.innerHTML=" ",u.parentNode.insertBefore(k,u.nextSibling),p.remove(),u.children.length===0&&u.remove();const I=document.createRange();return I.setStart(k.firstChild,0),I.collapse(!0),f.removeAllRanges(),f.addRange(I),!0}g.collapsed||(g.deleteContents(),g=f.getRangeAt(0));const C=document.createRange();C.setStart(g.startContainer,g.startOffset),C.setEnd(p,p.childNodes.length);const T=C.extractContents(),v=document.createElement("li"),_=document.createElement("input");_.type="checkbox",_.setAttribute("contenteditable","false"),v.appendChild(_),T.textContent.replace(/[\u00a0\u200B]/g,"").length>0&&v.appendChild(T);let y=v.childNodes[1];(!y||y.nodeType!==Node.TEXT_NODE)&&(y=document.createTextNode(""),v.appendChild(y)),p.insertAdjacentElement("afterend",v);const w=document.createRange();return w.setStart(y,0),w.collapse(!0),f.removeAllRanges(),f.addRange(w),!0}const m=fe(a.sc,e);if(m&&m.nodeName.toUpperCase()==="BLOCKQUOTE"){const u=a.toNativeRange();if(u.setEnd(m,m.childNodes.length),u.toString()===""&&a.isCollapsed())return n.preventDefault(),S("formatBlock","<p>"),!0}}return!1}function qt(n){const e=new DOMParser().parseFromString(`<body>${n||""}</body>`,"text/html");return oe(e.body).replace(/\n{3,}/g,`
|
|
2
2
|
|
|
3
|
-
`).trim()}function
|
|
3
|
+
`).trim()}function oe(n){if(n.nodeType===3)return n.textContent.replace(/\s+/g," ");if(n.nodeType!==1)return"";const e=n.nodeName.toLowerCase(),t=()=>Array.from(n.childNodes).map(oe).join("");switch(e){case"p":case"div":return`
|
|
4
4
|
|
|
5
|
-
${
|
|
5
|
+
${t()}
|
|
6
6
|
|
|
7
7
|
`;case"br":return`
|
|
8
8
|
`;case"h1":return`
|
|
9
9
|
|
|
10
|
-
# ${
|
|
10
|
+
# ${t()}
|
|
11
11
|
|
|
12
12
|
`;case"h2":return`
|
|
13
13
|
|
|
14
|
-
## ${
|
|
14
|
+
## ${t()}
|
|
15
15
|
|
|
16
16
|
`;case"h3":return`
|
|
17
17
|
|
|
18
|
-
### ${
|
|
18
|
+
### ${t()}
|
|
19
19
|
|
|
20
20
|
`;case"h4":return`
|
|
21
21
|
|
|
22
|
-
#### ${
|
|
22
|
+
#### ${t()}
|
|
23
23
|
|
|
24
24
|
`;case"h5":return`
|
|
25
25
|
|
|
26
|
-
##### ${
|
|
26
|
+
##### ${t()}
|
|
27
27
|
|
|
28
28
|
`;case"h6":return`
|
|
29
29
|
|
|
30
|
-
###### ${
|
|
30
|
+
###### ${t()}
|
|
31
31
|
|
|
32
|
-
`;case"strong":case"b":return`**${
|
|
32
|
+
`;case"strong":case"b":return`**${t()}**`;case"em":case"i":return`*${t()}*`;case"del":case"s":case"strike":return`~~${t()}~~`;case"sup":return`^${t()}`;case"sub":return`~${t()}`;case"code":return n.closest("pre")?t():`\`${t()}\``;case"pre":{const i=n.querySelector("code"),s=(i&&i.className||"").match(/language-(\S+)/),o=s?s[1]:"",a=(i||n).textContent||"";return`
|
|
33
33
|
|
|
34
34
|
\`\`\`${o}
|
|
35
35
|
${a}
|
|
@@ -37,38 +37,38 @@ ${a}
|
|
|
37
37
|
|
|
38
38
|
`}case"blockquote":return`
|
|
39
39
|
|
|
40
|
-
${
|
|
40
|
+
${t().trim().split(`
|
|
41
41
|
`).map(s=>`> ${s}`).join(`
|
|
42
42
|
`)}
|
|
43
43
|
|
|
44
|
-
`;case"a":{const i=n.getAttribute("href")||"";return`[${
|
|
44
|
+
`;case"a":{const i=n.getAttribute("href")||"";return`[${t()}](${i})`}case"img":{const i=n.getAttribute("src")||"";return``}case"ul":{const i=Array.from(n.querySelectorAll(":scope > li"));return i.length?`
|
|
45
45
|
|
|
46
|
-
${i.map(s=>`- ${
|
|
46
|
+
${i.map(s=>`- ${oe(s).trim()}`).join(`
|
|
47
47
|
`)}
|
|
48
48
|
|
|
49
|
-
`:
|
|
49
|
+
`:t()}case"ol":{const i=Array.from(n.querySelectorAll(":scope > li"));return i.length?`
|
|
50
50
|
|
|
51
|
-
${i.map((s,o)=>`${o+1}. ${
|
|
51
|
+
${i.map((s,o)=>`${o+1}. ${oe(s).trim()}`).join(`
|
|
52
52
|
`)}
|
|
53
53
|
|
|
54
|
-
`:
|
|
54
|
+
`:t()}case"li":return t();case"hr":return`
|
|
55
55
|
|
|
56
56
|
---
|
|
57
57
|
|
|
58
|
-
`;case"table":{const i=Array.from(n.querySelectorAll("tr"));if(!i.length)return
|
|
58
|
+
`;case"table":{const i=Array.from(n.querySelectorAll("tr"));if(!i.length)return t();const s=i.map(l=>Array.from(l.querySelectorAll("th, td")).map(h=>h.textContent.trim().replace(/\|/g,"\\|"))),o=Math.max(...s.map(l=>l.length)),a=l=>{const h=[...l];for(;h.length<o;)h.push("");return h};let r=`
|
|
59
59
|
|
|
60
|
-
`;
|
|
61
|
-
`,
|
|
62
|
-
`;for(let
|
|
63
|
-
`;return
|
|
64
|
-
`}default:return
|
|
60
|
+
`;r+=`| ${a(s[0]).join(" | ")} |
|
|
61
|
+
`,r+=`| ${Array(o).fill("---").join(" | ")} |
|
|
62
|
+
`;for(let l=1;l<s.length;l++)r+=`| ${a(s[l]).join(" | ")} |
|
|
63
|
+
`;return r+`
|
|
64
|
+
`}default:return t()}}function Vt(n){return/^#{1,6} \S|^\s*[-*+] \S|^\s*\d+\. \S|^> \S|\*{2}.+?\*{2}|^```/m.test(n)}function Pe(n){const e=n.replace(/\r\n/g,`
|
|
65
65
|
`).replace(/\r/g,`
|
|
66
66
|
`).split(`
|
|
67
|
-
`),
|
|
68
|
-
`)}</code></pre>`),i++;continue}if(/^(-{3,}|\*{3,}|_{3,})\s*$/.test(s)){e.push("<hr>"),i++;continue}const a=s.match(/^(#{1,6})\s+(.+)$/);if(a){const r=a[1].length;e.push(`<h${r}>${U(a[2])}</h${r}>`),i++;continue}if(s.startsWith("> ")){const r=[];for(;i<t.length&&t[i].startsWith("> ");)r.push(t[i].slice(2)),i++;e.push(`<blockquote>${r.map(U).join("<br>")}</blockquote>`);continue}if(/^[-*+] /.test(s)){const r=[];for(;i<t.length&&/^[-*+] /.test(t[i]);)r.push(`<li>${U(t[i].slice(2))}</li>`),i++;e.push(`<ul>${r.join("")}</ul>`);continue}if(/^\d+\. /.test(s)){const r=[];for(;i<t.length&&/^\d+\. /.test(t[i]);)r.push(`<li>${U(t[i].replace(/^\d+\. /,""))}</li>`),i++;e.push(`<ol>${r.join("")}</ol>`);continue}if(s.trim()===""){i++;continue}if(/^\|.+\|/.test(s)&&i+1<t.length&&/^\|[\s|:-]+\|/.test(t[i+1])){const r=Se(s);i+=2;const h=[];for(;i<t.length&&/^\|.+\|/.test(t[i]);)h.push(Se(t[i])),i++;const u=`<thead><tr>${r.map(g=>`<th>${U(g)}</th>`).join("")}</tr></thead>`,m=h.length?`<tbody>${h.map(g=>`<tr>${g.map(w=>`<td>${U(w)}</td>`).join("")}</tr>`).join("")}</tbody>`:"";e.push(`<table>${u}${m}</table>`);continue}const l=[];for(;i<t.length&&t[i].trim()!==""&&!/^(#{1,6} |> |[-*+] |\d+\. |```|---\s*$|\*{3}\s*$|_{3}\s*$)/.test(t[i])&&!/^\|.+\|/.test(t[i]);)l.push(t[i]),i++;l.length&&e.push(`<p>${U(l.join(" "))}</p>`)}return e.join("")}function Se(n){return n.replace(/^\|/,"").replace(/\|$/,"").split("|").map(t=>t.trim())}function U(n){return n=n.replace(/!\[([^\]]*)\]\(([^)]+)\)/g,(t,e,i)=>`<img src="${lt(i)}" alt="${lt(e)}" class="an-image">`),n=n.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(t,e,i)=>`<a href="${lt(i)}">${$(e)}</a>`),n=n.replace(/\*{3}(.+?)\*{3}/g,(t,e)=>`<strong><em>${$(e)}</em></strong>`),n=n.replace(/_{3}(.+?)_{3}/g,(t,e)=>`<strong><em>${$(e)}</em></strong>`),n=n.replace(/\*{2}(.+?)\*{2}/g,(t,e)=>`<strong>${$(e)}</strong>`),n=n.replace(/_{2}(.+?)_{2}/g,(t,e)=>`<strong>${$(e)}</strong>`),n=n.replace(/\*([^*\n]+?)\*/g,(t,e)=>`<em>${$(e)}</em>`),n=n.replace(/_([^_\n]+?)_/g,(t,e)=>`<em>${$(e)}</em>`),n=n.replace(/~~(.+?)~~/g,(t,e)=>`<del>${$(e)}</del>`),n=n.replace(/`([^`]+)`/g,(t,e)=>`<code>${$(e)}</code>`),n}function $(n){return String(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function lt(n){return String(n).replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class Ti{constructor(t){this.context=t,this.options=t.options,this._history=null,this._disposers=[],this._snapshotTimer=null}initialize(){const t=this.context.layoutInfo.editable;return this._history=new bi(t,this.options.historyLimit||100),this._bindEvents(t),this}destroy(){this._disposers.forEach(t=>t()),this._disposers=[],this._history=null,clearTimeout(this._snapshotTimer),this._snapshotTimer=null}_bindEvents(t){const e=l=>this._onKeydown(l),i=()=>this.afterCommand(),s=l=>this._enforceLimit(l),o=()=>{if(!this.context._alive)return;const l=window.getSelection();l&&l.rangeCount>0&&t.contains(l.anchorNode)&&(this.context.invoke("toolbar.refresh"),typeof this.options.onSelectionChange=="function"&&this.options.onSelectionChange(this.context))},a=l=>{l.target.type==="checkbox"&&l.target.closest(".an-checklist")&&this.afterCommand()};this._disposers.push(d(t,"keydown",e),d(t,"beforeinput",s),d(t,"input",i),d(document,"selectionchange",o),d(t,"click",a))}_onKeydown(t){const e=this.context.layoutInfo.editable;if(!xi(t,e,this.options)){if(N(t,"z")&&!t.shiftKey){t.preventDefault(),this.undo();return}if(N(t,"z")&&t.shiftKey||N(t,"y")){t.preventDefault(),this.redo();return}if(N(t,"b")){t.preventDefault(),this.bold();return}if(N(t,"i")){t.preventDefault(),this.italic();return}if(N(t,"u")){t.preventDefault(),this.underline();return}if(N(t,"k")){t.preventDefault(),this.context.invoke("linkDialog.show");return}if(N(t,"v")&&t.shiftKey){this.context.invoke("clipboard.setForcePlain",!0);return}if(t.key==="?"&&t.shiftKey&&!t.ctrlKey&&!t.metaKey){t.preventDefault(),this.context.invoke("shortcutsDialog.show");return}if(N(t,"f")){t.preventDefault(),this.context.invoke("findReplace.show","find");return}N(t,"h")&&(t.preventDefault(),this.context.invoke("findReplace.show","replace")),N(t,"`")&&(t.preventDefault(),this.inlineCode())}}_enforceLimit(t){const e=this.options.maxChars||0,i=this.options.maxWords||0;if(!e&&!i)return;const s=t.inputType||"";if(s.startsWith("delete")||s==="historyUndo"||s==="historyRedo"||s==="insertFromPaste"||s==="insertFromDrop"||!s.startsWith("insert"))return;const o=this.context.layoutInfo.editable.innerText||"",a=o.replace(/\n/g,"").length;if(e&&a>=e){t.preventDefault(),typeof this.options.onCharLimitReached=="function"&&this.options.onCharLimitReached(this.context);return}i&&(t.data===" "||s==="insertParagraph"||s==="insertLineBreak")&&(o.trim()?o.trim().split(/\s+/).length:0)>=i&&(t.preventDefault(),typeof this.options.onWordLimitReached=="function"&&this.options.onWordLimitReached(this.context))}afterCommand(){this.context.invoke("toolbar.refresh"),this.context.invoke("statusbar.update"),this._scheduleSnapshot()}_scheduleSnapshot(){clearTimeout(this._snapshotTimer),this._snapshotTimer=setTimeout(()=>{this._snapshotTimer=null,this._history&&this._history.recordUndo(),this.context.triggerEvent("change",this.getHTML())},400)}focus(){this.context.layoutInfo.editable.focus()}getHTML(){const t=this.context.layoutInfo.editable.innerHTML.replace(/\u200B/g,"");return this.context.invoke("clipboard.resolveImages",t)??t}setHTML(t){this.context.layoutInfo.editable.innerHTML=W(t),this._history&&this._history.reset(),this.afterCommand()}getText(){return this.context.layoutInfo.editable.innerText||""}setText(t){this.context.layoutInfo.editable.textContent=t,this._history&&this._history.reset(),this.afterCommand()}clear(){this.setHTML("")}clearHistory(){this._history&&this._history.reset()}isEmpty(){const t=(this.context.layoutInfo.editable.innerText||"").trim().replace(/\u00a0/g,""),e=!!this.context.layoutInfo.editable.querySelector("img, video, iframe, table");return!t&&!e}insertHTML(t){t&&(I("insertHTML",W(t)),this.afterCommand())}insertText(t){t&&(I("insertText",t),this.afterCommand())}setMarkdown(t){this.setHTML(Ie(t||""))}getMarkdown(){return ki(this.getHTML())}undo(){this._history&&(clearTimeout(this._snapshotTimer),this._snapshotTimer=null,this._history.undo(),this.context.invoke("toolbar.refresh"),this.context.invoke("statusbar.update"),this.context.triggerEvent("change",this.getHTML()))}redo(){this._history&&(clearTimeout(this._snapshotTimer),this._snapshotTimer=null,this._history.redo(),this.context.invoke("toolbar.refresh"),this.context.invoke("statusbar.update"),this.context.triggerEvent("change",this.getHTML()))}canUndo(){return this._history?this._history.canUndo():!1}canRedo(){return this._history?this._history.canRedo():!1}bold(){xt(),this.afterCommand()}italic(){kt(),this.afterCommand()}underline(){Ct(),this.afterCommand()}strikethrough(){Tt(),this.afterCommand()}superscript(){It(),this.afterCommand()}subscript(){St(),this.afterCommand()}justifyLeft(){Mt(),this.afterCommand()}justifyCenter(){jt(),this.afterCommand()}justifyRight(){Nt(),this.afterCommand()}justifyFull(){zt(),this.afterCommand()}indent(){Ht(),this.afterCommand()}outdent(){$t(),this.afterCommand()}insertUL(){Dt(),this.afterCommand()}insertOL(){Pt(),this.afterCommand()}inlineCode(){di(this.context.layoutInfo.editable),this.afterCommand()}toggleChecklist(){ui(),this.afterCommand()}print(){this.context.print()}formatBlock(t){Lt(t),this.afterCommand()}foreColor(t){Et(t),this.afterCommand()}backColor(t){Bt(t),this.afterCommand()}fontName(t){Rt(t),this.afterCommand()}fontSize(t){At(t,this.context.layoutInfo.editable),this.afterCommand()}insertHr(){I("insertHorizontalRule"),this.afterCommand()}insertLink(t,e,i=!1){const s=window.getSelection();if(!s||s.rangeCount===0)return;const o=mt(t);if(!o)return;if(s.toString().trim().length>0){if(I("createLink",o),i){const l=this._getClosestAnchor();l&&(l.setAttribute("target","_blank"),l.setAttribute("rel","noopener noreferrer"))}}else{const l=this._escapeAttr(e||o);I("insertHTML",`<a href="${this._escapeAttr(o)}"${i?' target="_blank" rel="noopener noreferrer"':""}>${l}</a>`)}this.afterCommand()}unlink(){I("unlink"),this.afterCommand()}insertImage(t,e="",i=""){const s=mt(t,{allowData:!0});if(!s)return;const a={left:"float:left;margin:0 1em 1em 0",center:"display:block;margin:0 auto",right:"float:right;margin:0 0 1em 1em"}[i]||"",l=a?` style="${a}"`:"";I("insertHTML",`<img src="${this._escapeAttr(s)}" alt="${this._escapeAttr(e)}" class="an-image"${l}>`),this.afterCommand()}insertVideo(t){t&&(I("insertHTML",t),this.afterCommand())}insertTable(t,e){wi(t,e,{headerRow:this.context.options.tableHeaderRow}),this.afterCommand()}_getClosestAnchor(){const t=window.getSelection();if(!t||t.rangeCount===0)return null;let e=t.getRangeAt(0).startContainer;for(;e;){if(e.nodeName==="A")return e;e=e.parentNode}return null}_escapeAttr(t){return String(t??"").replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}}class Ii{constructor(t){this.context=t,this.options=t.options,this.el=null,this._disposers=[]}initialize(){return this.el=c("div",{class:"an-toolbar"}),this._faReady=this._detectFontAwesome(),this._buildButtons(),this._btnMap=new Map((this.options.toolbar||[]).flat().map(t=>[t.name,t])),this}destroy(){this._disposers.forEach(t=>t()),this._disposers=[],this.el&&this.el.parentNode&&this.el.parentNode.removeChild(this.el),this.el=null}_buildButtons(){(this.options.toolbar||[]).forEach(e=>{const i=c("div",{class:"an-btn-group"});e.forEach(s=>{let o;s.type==="select"?o=this._createSelect(s):s.type==="grid"?o=this._createGridPicker(s):s.type==="colorpicker"?o=this._createColorPicker(s):o=this._createButton(s),i.appendChild(o)}),this.el.appendChild(i)})}_createGridPicker(t){const s=c("div",{class:"an-table-picker-wrap"}),a=!!this.options.useBootstrap?this.options.toolbarButtonClass||"btn btn-sm btn-light":"an-btn",l=c("button",{type:"button",class:a,title:t.tooltip||"","data-btn":t.name,"aria-label":t.tooltip||t.name,"aria-haspopup":"true","aria-expanded":"false"});if(this._faReady){const b=this.options.fontAwesomeClass||"fas";l.innerHTML=`<i class="${b} fa-table" aria-hidden="true"></i>`}else{const b='stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"';l.innerHTML=`<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" ${b} style="display:block"><rect x="3" y="3" width="18" height="18" rx="1"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="3" y1="15" x2="21" y2="15"/><line x1="9" y1="3" x2="9" y2="21"/><line x1="15" y1="3" x2="15" y2="21"/></svg>`}const r=c("div",{class:"an-table-picker-popup",role:"dialog","aria-label":"Select table size"}),h=c("div",{class:"an-table-grid"}),u=c("div",{class:"an-table-label"});u.textContent="Insert Table";const m=[];for(let b=1;b<=10;b++)for(let T=1;T<=10;T++){const E=c("div",{class:"an-table-cell","data-row":String(b),"data-col":String(T)});m.push(E),h.appendChild(E)}r.appendChild(h),r.appendChild(u);let g=!1;const w=(b,T)=>{m.forEach(E=>{const z=+E.getAttribute("data-row"),P=+E.getAttribute("data-col");E.classList.toggle("active",z<=b&&P<=T)}),u.textContent=b&&T?`${b} × ${T}`:"Insert Table"},f=()=>{g=!0,r.style.display="block",l.setAttribute("aria-expanded","true")},_=()=>{g=!1,r.style.display="none",l.setAttribute("aria-expanded","false"),w(0,0)},k=d(l,"click",b=>{b.stopPropagation(),g?_():f()}),C=d(h,"mouseover",b=>{const T=b.target.closest(".an-table-cell");T&&w(+T.getAttribute("data-row"),+T.getAttribute("data-col"))}),v=d(h,"mouseleave",()=>w(0,0)),y=d(h,"click",b=>{const T=b.target.closest(".an-table-cell");if(!T)return;const E=+T.getAttribute("data-row"),z=+T.getAttribute("data-col");_(),this.context.invoke("editor.focus"),t.action(this.context,E,z)}),x=d(document,"click",()=>{g&&_()});return this._disposers.push(k,C,v,y,x),s.appendChild(l),s.appendChild(r),s}_createColorPicker(t){const e=["#000000","#434343","#666666","#999999","#b7b7b7","#cccccc","#efefef","#ffffff","#ff0000","#ff9900","#ffff00","#00ff00","#00ffff","#4a86e8","#9900ff","#ff00ff","#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#c9daf8","#d9d2e9","#ead1dc"];let i=t.defaultColor||"#000000";const s=c("div",{class:"an-color-picker-wrap"}),a=!!this.options.useBootstrap?this.options.toolbarButtonClass||"btn btn-sm btn-light":"an-btn",l=c("button",{type:"button",class:`${a} an-color-btn`,title:t.tooltip||"","data-btn":t.name,"aria-label":t.tooltip||t.name}),r='stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"',h=t.name==="foreColor"?`<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" ${r} style="display:block"><path d="M4 20L12 4L20 20"/><line x1="7.5" y1="14" x2="16.5" y2="14"/></svg>`:`<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" ${r} style="display:block"><path d="M3 21v-4l9-9 4 4-9 9z"/><path d="M12 8l4 4"/></svg>`;l.innerHTML=h;const u=c("span",{class:"an-color-strip"});u.style.background=i,l.appendChild(u);const m=c("button",{type:"button",class:`${a} an-color-arrow`,title:`Choose ${t.name==="foreColor"?"text":"highlight"} color`,"aria-haspopup":"true","aria-expanded":"false"});m.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8" viewBox="0 0 24 24" fill="currentColor" stroke="none" style="display:block"><path d="M7 10l5 5 5-5H7z"/></svg>';const g=c("div",{class:"an-color-popup"});g.style.display="none";const w=c("div",{class:"an-color-swatches"}),f=Array.isArray(this.options.colorSwatches)?this.options.colorSwatches:[];[...new Set([...f,...e])].forEach(B=>{const L=c("div",{class:"an-color-swatch",title:B,"data-color":B});L.style.background=B,w.appendChild(L)});const k=c("div",{class:"an-color-custom"}),C=c("input",{type:"color",value:i,title:"Custom color"}),v=c("span",{},["Custom color"]);k.appendChild(C),k.appendChild(v),g.appendChild(w),g.appendChild(k);let y=!1;const x=()=>{y=!0,g.style.display="block",m.setAttribute("aria-expanded","true")},b=()=>{y=!1,g.style.display="none",m.setAttribute("aria-expanded","false")},T=B=>{i=B,u.style.background=B,C.value=B,this.context.invoke("editor.focus"),t.action(this.context,B),this.context.invoke("editor.afterCommand"),b()},E=d(l,"click",B=>{B.preventDefault(),this.context.invoke("editor.focus"),t.action(this.context,i),this.context.invoke("editor.afterCommand")}),z=d(m,"click",B=>{B.stopPropagation(),y?b():x()}),P=d(w,"click",B=>{const L=B.target.closest(".an-color-swatch");L&&T(L.dataset.color)}),Z=d(C,"change",B=>{T(B.target.value)}),tt=d(document,"click",B=>{y&&!s.contains(B.target)&&b()}),et=d(g,"click",B=>B.stopPropagation());return this._disposers.push(E,z,P,Z,tt,et),s.appendChild(l),s.appendChild(m),s.appendChild(g),s}_createSelect(t){const e=t.name==="fontFamily"?this.options.fontFamilies||[]:t.items||[],i=t.selectClass?`an-select ${t.selectClass}`:"an-select",s=c("select",{class:i,title:t.tooltip||"","data-btn":t.name,"aria-label":t.tooltip||t.name}),o=t.placeholder||"Font",a=c("option",{value:""},[o]);s.appendChild(a),e.forEach(r=>{const h=typeof r=="object"?r.value:r,u=typeof r=="object"?r.label:r,m=c("option",{value:h},[u]);t.name==="fontFamily"&&(m.style.fontFamily=h),s.appendChild(m)});const l=d(s,"change",r=>{const h=r.target.value;h&&(this.context.invoke("editor.focus"),t.action(this.context,h),this.context.invoke("editor.afterCommand"))});return this._disposers.push(l),s}_createButton(t){const i=!!this.options.useBootstrap?this.options.toolbarButtonClass||"btn btn-sm btn-light":"an-btn",s=t.className?` ${t.className}`:"",o=`${i}${s}`,a=c("button",{type:"button",class:o,title:t.tooltip||"","data-btn":t.name,"aria-label":t.tooltip||t.name}),l='stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"',r=f=>`<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" ${l} style="display:block">${f}</svg>`,h=new Map([["bold",r('<path d="M6 4h8a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"/><path d="M6 12h9a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"/>')],["italic",r('<line x1="19" y1="4" x2="10" y2="4"/><line x1="14" y1="20" x2="5" y2="20"/><line x1="15" y1="4" x2="9" y2="20"/>')],["underline",r('<path d="M6 3v7a6 6 0 0 0 6 6 6 6 0 0 0 6-6V3"/><line x1="4" y1="21" x2="20" y2="21"/>')],["strikethrough",r('<path d="M17.3 12H6.7"/><path d="M10 6.5C10 5.1 11.1 4 12.5 4c1.4 0 2.5 1.1 2.5 2.5 0 .8-.4 1.5-1 2"/><path d="M14 17.5C14 19 12.9 20 11.5 20 10.1 20 9 18.9 9 17.5c0-.8.4-1.5 1-2"/>')],["superscript",r('<path d="m4 19 8-8"/><path d="m12 19-8-8"/><path d="M20 12h-4c0-1.5.44-2 1.5-2.5S20 8.33 20 7.25C20 6 19 5 17.5 5S15 6 15 7"/>')],["subscript",r('<path d="m4 5 8 8"/><path d="m12 5-8 8"/><path d="M20 21h-4c0-1.5.44-2 1.5-2.5S20 17.33 20 16.25C20 15 19 14 17.5 14S15 15 15 16"/>')],["align-left",r('<line x1="21" y1="6" x2="3" y2="6"/><line x1="15" y1="12" x2="3" y2="12"/><line x1="17" y1="18" x2="3" y2="18"/>')],["align-center",r('<line x1="21" y1="6" x2="3" y2="6"/><line x1="18" y1="12" x2="6" y2="12"/><line x1="21" y1="18" x2="3" y2="18"/>')],["align-right",r('<line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="12" x2="9" y2="12"/><line x1="21" y1="18" x2="7" y2="18"/>')],["align-justify",r('<line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="12" x2="3" y2="12"/><line x1="21" y1="18" x2="3" y2="18"/>')],["list-ul",r('<line x1="9" y1="6" x2="20" y2="6"/><line x1="9" y1="12" x2="20" y2="12"/><line x1="9" y1="18" x2="20" y2="18"/><circle cx="4" cy="6" r="1" fill="currentColor" stroke="none"/><circle cx="4" cy="12" r="1" fill="currentColor" stroke="none"/><circle cx="4" cy="18" r="1" fill="currentColor" stroke="none"/>')],["list-ol",r('<line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/><path d="M4 6h1V3"/><path d="M4 10h2l-2 2h2"/><path d="M4 16.5A1.5 1.5 0 0 1 5.5 15a1.5 1.5 0 0 1 0 3H4"/>')],["indent",r('<polyline points="3 8 7 12 3 16"/><line x1="21" y1="12" x2="11" y2="12"/><line x1="21" y1="6" x2="11" y2="6"/><line x1="21" y1="18" x2="11" y2="18"/>')],["outdent",r('<polyline points="7 8 3 12 7 16"/><line x1="21" y1="12" x2="11" y2="12"/><line x1="21" y1="6" x2="11" y2="6"/><line x1="21" y1="18" x2="11" y2="18"/>')],["undo",r('<path d="M3 7v6h6"/><path d="M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13"/>')],["redo",r('<path d="M21 7v6h-6"/><path d="M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3L21 13"/>')],["minus",r('<line x1="5" y1="12" x2="19" y2="12"/>')],["link",r('<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>')],["image",r('<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/>')],["video",r('<polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2"/>')],["table",r('<rect x="3" y="3" width="18" height="18" rx="1"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="3" y1="15" x2="21" y2="15"/><line x1="9" y1="3" x2="9" y2="21"/><line x1="15" y1="3" x2="15" y2="21"/>')],["emoji",r('<circle cx="12" cy="12" r="10"/><path d="M8.5 14.5s1.5 2.5 3.5 2.5 3.5-2.5 3.5-2.5"/><circle cx="9" cy="9" r="1.5" fill="currentColor" stroke="none"/><circle cx="15" cy="9" r="1.5" fill="currentColor" stroke="none"/>')],["icon",r('<circle cx="8" cy="8" r="3"/><circle cx="16" cy="8" r="3"/><rect x="5" y="13" width="6" height="6" rx="1"/><rect x="13" y="13" width="6" height="6" rx="1"/>')],["code",r('<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>')],["expand",r('<polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/>')],["foreColor",r('<path d="M4 20L12 4L20 20"/><line x1="7.5" y1="14" x2="16.5" y2="14"/>')],["backColor",r('<path d="M3 21v-4l9-9 4 4-9 9z"/><path d="M12 8l4 4"/>')],["keyboard",r('<rect x="2" y="6" width="20" height="12" rx="2"/><line x1="6" y1="10" x2="6" y2="10" stroke-width="2.5"/><line x1="10" y1="10" x2="10" y2="10" stroke-width="2.5"/><line x1="14" y1="10" x2="14" y2="10" stroke-width="2.5"/><line x1="18" y1="10" x2="18" y2="10" stroke-width="2.5"/><line x1="8" y1="14" x2="16" y2="14" stroke-width="2"/>')],["caption",r('<rect x="3" y="3" width="18" height="11" rx="2"/><line x1="6" y1="18" x2="18" y2="18"/><line x1="9" y1="21" x2="15" y2="21"/>')],["remove-format",r('<path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21"/><path d="M22 21H7"/><path d="m5 11 9 9"/>')],["direction",r('<path d="M12 20V4"/><path d="m9 7-3 3 3 3"/><path d="M4 10h8"/><path d="m15 7 3 3-3 3"/><path d="M20 10h-8"/>')],["search",r('<circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>')],["find-replace",r('<circle cx="10" cy="10" r="6"/><line x1="18" y1="18" x2="14.35" y2="14.35"/><path d="M16 19h6"/><path d="M19 16v6"/>')],["inline-code",r('<path d="M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1"/><path d="M16 3h1a2 2 0 0 1 2 2v5c0 1.1.9 2 2 2a2 2 0 0 1-2 2v5a2 2 0 0 1-2 2h-1"/>')],["checklist",r('<rect x="3" y="4" width="5" height="5" rx="1"/><path d="m4 6.5 1 1 2-2"/><rect x="3" y="13" width="5" height="5" rx="1"/><line x1="10" y1="6.5" x2="21" y2="6.5"/><line x1="10" y1="15.5" x2="21" y2="15.5"/>')],["print",r('<path d="M6 9V2h12v7"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/>')]]),u=this.options.fontAwesomeClass||"fas",m=new Map([["bold","fa-bold"],["italic","fa-italic"],["underline","fa-underline"],["strikethrough","fa-strikethrough"],["superscript","fa-superscript"],["subscript","fa-subscript"],["align-left","fa-align-left"],["align-center","fa-align-center"],["align-right","fa-align-right"],["align-justify","fa-align-justify"],["list-ul","fa-list-ul"],["list-ol","fa-list-ol"],["indent","fa-indent"],["outdent","fa-outdent"],["undo","fa-rotate-left"],["redo","fa-rotate-right"],["minus","fa-minus"],["link","fa-link"],["image","fa-image"],["code","fa-code"],["expand","fa-expand"],["emoji","fa-face-smile"],["icon","fa-icons"],["foreColor","fa-font"],["backColor","fa-highlighter"],["keyboard","fa-keyboard"],["remove-format","fa-remove-format"],["direction","fa-arrow-right-arrow-left"],["search","fa-magnifying-glass"],["find-replace","fa-magnifying-glass-plus"],["inline-code","fa-code"],["checklist","fa-list-check"],["print","fa-print"]]);if(this._faReady){const f=m.get(t.icon)||m.get(t.name)||null;f?a.innerHTML=`<i class="${u} ${f}" aria-hidden="true"></i>`:h.has(t.icon)?a.innerHTML=h.get(t.icon):a.textContent=t.icon||t.name}else h.has(t.icon)?a.innerHTML=h.get(t.icon):h.has(t.name)?a.innerHTML=h.get(t.name):a.textContent=t.icon||t.name;const w=d(a,"click",f=>{f.preventDefault(),this.context.invoke("editor.focus"),t.action(this.context),this.context.invoke("editor.afterCommand"),this.refresh()});return this._disposers.push(w),a}_detectFontAwesome(){if(!this.options.useFontAwesome)return!1;if(document.querySelector(".fa, .fas, .far, .fal, .fab, .fa-solid"))return!0;const t=Array.from(document.querySelectorAll('link[rel="stylesheet"]')).map(e=>e.href||"").join(" ");return/fontawesome|font-awesome|use\.fontawesome|all\.css/.test(t)}refresh(){if(!this.el)return;const t=this._btnMap||new Map;this.el.querySelectorAll("button[data-btn]").forEach(e=>{const i=t.get(e.getAttribute("data-btn"));i&&typeof i.isActive=="function"&&e.classList.toggle("active",!!i.isActive(this.context)),i&&typeof i.isDisabled=="function"&&(e.disabled=!!i.isDisabled(this.context))}),this.el.querySelectorAll("select[data-btn]").forEach(e=>{const i=t.get(e.getAttribute("data-btn"));if(!i||typeof i.getValue!="function")return;let s=(i.getValue(this.context)||"").replace(/["']/g,"").trim();s||(s=this.options.defaultFontFamily||this.options.fontFamilies&&this.options.fontFamilies[0]||"");const o=Array.from(e.options).find(a=>a.value&&a.value.toLowerCase()===s.toLowerCase());e.value=o?o.value:""})}show(){this.el&&(this.el.style.display="")}hide(){this.el&&(this.el.style.display="none")}}const Ee=typeof Intl<"u"&&typeof Intl.Segmenter=="function"?new Intl.Segmenter(void 0,{granularity:"word"}):null;function Be(n){const t=n.trim();if(!t)return 0;if(Ee){let e=0;for(const i of Ee.segment(t))i.isWordLike&&e++;return e}return t.split(/\s+/).length}function Re(n,t,e){if(!e){n.classList.remove("an-count-warn","an-count-exceeded");return}t>e?(n.classList.add("an-count-exceeded"),n.classList.remove("an-count-warn")):t>=e*.9?(n.classList.add("an-count-warn"),n.classList.remove("an-count-exceeded")):n.classList.remove("an-count-warn","an-count-exceeded")}class Si{constructor(t){this.context=t,this.options=t.options,this.el=null,this._disposers=[],this._wordCountEl=null,this._charCountEl=null}initialize(){if(this.el=c("div",{class:"an-statusbar"}),this.options.resizable!==!1){const e=c("div",{class:"an-resize-handle",title:"Resize editor","aria-hidden":"true"});this._bindResize(e),this.el.appendChild(e)}this._wordCountEl=c("span",{class:"an-word-count"}),this._charCountEl=c("span",{class:"an-char-count"});const t=c("div",{class:"an-status-info"});return t.appendChild(this._wordCountEl),t.appendChild(this._charCountEl),this.el.appendChild(t),this._bindContentEvents(),this.update(),this}destroy(){this._disposers.forEach(t=>t()),this._disposers=[],this._dragDisposers&&(this._dragDisposers.forEach(t=>t()),this._dragDisposers=null),this.el&&this.el.parentNode&&this.el.parentNode.removeChild(this.el),this.el=null}_bindResize(t){let e=0,i=0;const s=this.context.layoutInfo.container,o=f=>{const _=f-e,k=this.options.minHeight||100;s.style.height=`${Math.max(k,i+_)}px`},a=f=>o(f.clientY),l=()=>{document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",l),this._dragDisposers=null},r=f=>{e=f.clientY,i=s.offsetHeight,document.addEventListener("mousemove",a),document.addEventListener("mouseup",l),this._dragDisposers=[()=>document.removeEventListener("mousemove",a),()=>document.removeEventListener("mouseup",l)],f.preventDefault()},h=f=>{const _=f.touches[0];_&&(f.preventDefault(),o(_.clientY))},u=()=>{document.removeEventListener("touchmove",h),document.removeEventListener("touchend",u),this._dragDisposers=null},m=f=>{const _=f.touches[0];_&&(e=_.clientY,i=s.offsetHeight,document.addEventListener("touchmove",h,{passive:!1}),document.addEventListener("touchend",u),this._dragDisposers=[()=>document.removeEventListener("touchmove",h),()=>document.removeEventListener("touchend",u)])},g=d(t,"mousedown",r),w=d(t,"touchstart",m);this._disposers.push(g,w)}_bindContentEvents(){const t=this.context.layoutInfo.editable,e=ft(()=>this.update(),200),i=d(t,"input",e);this._disposers.push(i)}update(){if(!this._wordCountEl||!this._charCountEl)return;const e=this.context.layoutInfo.editable.innerText||"",i=Be(e),s=e.replace(/\n/g,"").length,o=this.options.maxWords||0,a=this.options.maxChars||0;this._wordCountEl.textContent=o?`Words: ${i}/${o}`:`Words: ${i}`,this._charCountEl.textContent=a?`Chars: ${s}/${a}`:`Chars: ${s}`,Re(this._wordCountEl,i,o),Re(this._charCountEl,s,a)}getWordCount(){const t=this.context.layoutInfo.editable;return Be(t.innerText||"")}getCharCount(){return(this.context.layoutInfo.editable.innerText||"").replace(/\n/g,"").length}}class Ei{constructor(t){this.context=t,this.options=t.options,this._disposers=[]}initialize(){this._blobRegistry=new Map,this._forcePlain=!1;const t=this.context.layoutInfo.editable;return this._disposers.push(d(t,"paste",e=>this._onPaste(e)),d(t,"dragover",e=>this._onDragover(e)),d(t,"drop",e=>this._onDrop(e))),this._mutationObserver=new MutationObserver(e=>{for(const i of e)for(const s of i.removedNodes)this._revokeRemovedBlobs(s)}),this._mutationObserver.observe(t,{childList:!0,subtree:!0}),this}destroy(){this._disposers.forEach(t=>t()),this._disposers=[],this._mutationObserver&&(this._mutationObserver.disconnect(),this._mutationObserver=null),this._blobRegistry&&(this._blobRegistry.forEach((t,e)=>URL.revokeObjectURL(e)),this._blobRegistry.clear())}_revokeRemovedBlobs(t){if(!this._blobRegistry||!this._blobRegistry.size)return;const e=[];t.nodeName==="IMG"?e.push(t):t.querySelectorAll&&e.push(...t.querySelectorAll("img")),e.forEach(i=>{const s=i.getAttribute("src")||"";s.startsWith("blob:")&&this._blobRegistry.has(s)&&(URL.revokeObjectURL(s),this._blobRegistry.delete(s))})}_cleanWordHtml(t){return t.replace(/<!--\[if[\s\S]*?\[endif\]-->/gi,"").replace(/<xml[\s\S]*?<\/xml>/gi,"").replace(/<\?xml[\s\S]*?\?>/gi,"").replace(/<\/?(o|w|m|v|st1):[a-z][^>]*>/gi,"").replace(/\s+class="Mso[^"]*"/gi,"").replace(/\s+style="([^"]*)"/gi,(e,i)=>{const s=i.split(";").map(o=>o.trim()).filter(o=>o&&!/^mso-/i.test(o)&&!/^(tab-stops|margin-[a-z]+-alt)/i.test(o)).join("; ");return s?` style="${s}"`:""}).replace(/<p[^>]*>\s*( )?\s*<\/p>/gi,"")}_cleanSocialHtml(t){const e=new DOMParser().parseFromString(`<body>${t}</body>`,"text/html"),i=new Set(["span","div"]);let s=!0;for(;s;)s=!1,e.querySelectorAll("span, div").forEach(o=>{if(!i.has(o.tagName.toLowerCase())||o.querySelector("a, strong, em, b, i, ul, ol, li, table, img, blockquote, pre, code, h1, h2, h3, h4, h5, h6"))return;const a=o.parentNode;if(a){for(;o.firstChild;)a.insertBefore(o.firstChild,o);a.removeChild(o),s=!0}});return e.querySelectorAll("*").forEach(o=>{o.removeAttribute("class"),o.removeAttribute("id"),Array.from(o.attributes).filter(a=>a.name.startsWith("data-")||a.name.startsWith("aria-")).forEach(a=>o.removeAttribute(a.name))}),e.body.innerHTML}_stripAttributes(t){const e=new DOMParser().parseFromString(`<body>${t}</body>`,"text/html"),i=new Set(["href","src","alt","target","rel","colspan","rowspan","type"]);return e.querySelectorAll("*").forEach(s=>{Array.from(s.attributes).filter(o=>!i.has(o.name)).forEach(o=>s.removeAttribute(o.name))}),e.body.innerHTML}setForcePlain(t){this._forcePlain=!!t}_onPaste(t){const e=t.clipboardData||window.clipboardData;if(!e)return;const i=this._forcePlain;if(this._forcePlain=!1,e.items){const s=Array.from(e.items).filter(o=>o.kind==="file"&&o.type.startsWith("image/"));if(s.length>0){t.preventDefault();const o=s.map(a=>a.getAsFile()).filter(Boolean);this._insertImageFiles(o);return}}if(typeof this.options.onPaste=="function"&&this.options.onPaste({text:e.getData("text/plain")||"",html:e.types.includes("text/html")?e.getData("text/html"):null}),i||this.options.pasteAsPlainText){t.preventDefault();const o=e.getData("text/plain").split(/\r?\n/).map(a=>`<p>${this._escapeHTML(a)||"<br>"}</p>`).join("");I("insertHTML",o),this.context.invoke("editor.afterCommand");return}if(this.options.markdownPaste!==!1&&!e.types.includes("text/html")){const s=e.getData("text/plain");if(s&&Ci(s)){t.preventDefault();const o=W(Ie(s));I("insertHTML",o),this.context.invoke("editor.afterCommand");return}}if(this.options.pasteCleanHTML!==!1&&e.types.includes("text/html")){t.preventDefault();const s=e.getData("text/html"),o=/<[a-z]+:[a-z]/i.test(s)||/class="Mso/i.test(s)||/\bmso-/i.test(s),a=/\bdata-testid\b/.test(s)||/class="[^"]*\b(?:x[a-z0-9]{6,}|r-[a-z0-9]{3,})\b/.test(s);let l=s;o?l=this._cleanWordHtml(l):a&&(l=this._cleanSocialHtml(l)),l=W(l),this.options.pasteStripAttributes&&(l=this._stripAttributes(l)),I("insertHTML",l),this.context.invoke("editor.afterCommand");return}}_onDragover(t){if(!t.dataTransfer)return;Array.from(t.dataTransfer.types||[]).includes("Files")&&(t.preventDefault(),t.dataTransfer.dropEffect="copy")}_onDrop(t){const e=t.dataTransfer;if(!e||!e.files||e.files.length===0)return;const i=Array.from(e.files).filter(s=>s.type.startsWith("image/"));i.length!==0&&(t.preventDefault(),t.stopPropagation(),this._placeCaretAtPoint(t.clientX,t.clientY),this._insertImageFiles(i))}_insertImageFiles(t){if(!t||t.length===0)return;if(typeof this.options.onImageUpload=="function"){this.options.onImageUpload(t);return}const e=(this.options.maxImageSize||5)*1024*1024;t.forEach(i=>{if(!i||!i.type.startsWith("image/"))return;if(i.size>e){const o=`Image "${i.name}" exceeds the ${this.options.maxImageSize||5} MB size limit.`;this.context.triggerEvent("imageError",{file:i,message:o}),console.warn(`[AutumnNote] ${o}`);return}const s=i.name.replace(/\.[^.]+$/,"");this._compressImage(i).then(o=>{const a=this._dataUrlToBlob(o),l=URL.createObjectURL(a);this._blobRegistry.set(l,o),this.context.invoke("editor.insertImage",l,s)}).catch(o=>{var l;const a=`Image "${i.name}" could not be processed.`;this.context.triggerEvent("imageError",{file:i,message:a,error:o}),(typeof process>"u"||((l=process.env)==null?void 0:l.NODE_ENV)!=="production")&&console.warn("[AutumnNote]",a,o)})})}resolveImages(t){return!this._blobRegistry||!this._blobRegistry.size?t:t.replace(/blob:[^"'> \t\n\r]*/g,e=>this._blobRegistry.get(e)||e)}_dataUrlToBlob(t){const[e,i]=t.split(","),s=e.match(/:(.*?);/)[1],o=atob(i),a=new Uint8Array(o.length);for(let l=0;l<o.length;l++)a[l]=o.charCodeAt(l);return new Blob([a],{type:s})}_compressImage(t){return new Promise(s=>{const o=URL.createObjectURL(t),a=new Image;a.onload=()=>{URL.revokeObjectURL(o);let{width:l,height:r}=a;(l>1920||r>1920)&&(l>=r?(r=Math.round(r*1920/l),l=1920):(l=Math.round(l*1920/r),r=1920));const h=document.createElement("canvas");h.width=l,h.height=r;const u=h.getContext("2d");if(!u){const g=new FileReader;g.onload=w=>s(w.target.result),g.readAsDataURL(t);return}u.drawImage(a,0,0,l,r);const m=h.toDataURL("image/webp",.85);s(m.startsWith("data:image/webp")?m:h.toDataURL("image/jpeg",.85))},a.onerror=()=>{URL.revokeObjectURL(o);const l=new FileReader;l.onload=r=>s(r.target.result),l.readAsDataURL(t)},a.src=o})}_placeCaretAtPoint(t,e){let i;if(document.caretRangeFromPoint)i=document.caretRangeFromPoint(t,e);else if(document.caretPositionFromPoint){const o=document.caretPositionFromPoint(t,e);o&&(i=document.createRange(),i.setStart(o.offsetNode,o.offset),i.collapse(!0))}if(!i)return;const s=window.getSelection();s&&(s.removeAllRanges(),s.addRange(i))}_escapeHTML(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}}class Bi{constructor(t){this.context=t,this.options=t.options,this._disposers=[]}initialize(){const t=this.context.layoutInfo.editable,e=this.options.placeholder||"";e&&(t.dataset.placeholder=e);const i=()=>this._update(),s=d(t,"input",i),o=d(t,"focus",i),a=d(t,"blur",i);return this._disposers.push(s,o,a),this._update(),this}destroy(){this._disposers.forEach(t=>t()),this._disposers=[]}_update(){const t=this.context.layoutInfo.editable,e=!t.textContent.trim()&&!t.querySelector("img, table, hr");t.classList.toggle("an-placeholder",e)}}class Ri{constructor(t){this.context=t,this.options=t.options,this._active=!1,this._textarea=null,this._disposers=[]}initialize(){return this}destroy(){this._disposers.forEach(t=>t()),this._disposers=[],this._textarea&&this._textarea.parentNode&&this._textarea.parentNode.removeChild(this._textarea),this._textarea=null}toggle(){this._active?this.deactivate():this.activate()}isActive(){return this._active}activate(){if(this._active)return;const{editable:t}=this.context.layoutInfo,e=t.innerHTML;this._textarea=c("textarea",{class:"an-codeview",spellcheck:"false",autocomplete:"off",autocorrect:"off",autocapitalize:"off"}),this._textarea.value=this._prettyPrint(e),t.style.display="none",t.parentNode.insertBefore(this._textarea,t.nextSibling),this._active=!0,this.context.invoke("toolbar.refresh")}deactivate(){if(!this._active||!this._textarea)return;const{editable:t}=this.context.layoutInfo;t.innerHTML=W(this._textarea.value,{allowIframes:!0}),this._textarea.parentNode.removeChild(this._textarea),this._textarea=null,t.style.display="",this._active=!1,this.context.invoke("toolbar.refresh"),this.context.invoke("editor.afterCommand")}_prettyPrint(t){const e=/^<(a|abbr|b|bdo|br|button|cite|code|dfn|em|i|img|input|kbd|label|output|q|samp|select|small|span|strong|sub|sup|textarea|time|tt|u|var)([\s>/])/i;let i=0;return t.replace(/>\s*</g,`>
|
|
69
|
-
<`).split(`
|
|
70
|
-
`).map(s=>{const o=s.trim();if(!o)return"";/^<\//.test(o)&&(i=Math.max(0,i-1));const a=" ".repeat(i)+o;return/^<[^/!][^>]*[^/]>/.test(o)&&!
|
|
71
|
-
`)}}class Ai{constructor(t){this.context=t,this._active=!1,this._disposers=[],this._prevHeight=""}initialize(){const t=d(document,"keydown",e=>{this._active&&K(e,Q.ESCAPE)&&this.deactivate()});return this._disposers.push(t),this}destroy(){this._disposers.forEach(t=>t()),this._disposers=[],this._active&&this.deactivate()}toggle(){this._active?this.deactivate():this.activate()}isActive(){return this._active}activate(){if(this._active)return;const t=this.context.layoutInfo.container;this._prevHeight=t.style.height,t.classList.add("an-fullscreen"),t.style.height="",document.body.style.overflow="hidden",this._active=!0,this.context.invoke("toolbar.refresh")}deactivate(){if(!this._active)return;const t=this.context.layoutInfo.container;t.classList.remove("an-fullscreen"),t.style.height=this._prevHeight,document.body.style.overflow="",this._active=!1,this.context.invoke("toolbar.refresh")}}class Li{constructor(t){this.context=t,this.options=t.options,this._dialog=null,this._disposers=[],this._savedRange=null}initialize(){return this._dialog=this._buildDialog(),document.body.appendChild(this._dialog),this}destroy(){this._disposers.forEach(t=>t()),this._disposers=[],this._dialog&&this._dialog.parentNode&&this._dialog.parentNode.removeChild(this._dialog),this._dialog=null}show(){Y(t=>{this._savedRange=t}),this._prefill(),this._open()}_buildDialog(){const t=c("div",{class:"an-dialog-overlay",role:"dialog","aria-modal":"true","aria-label":"Insert link"}),e=c("div",{class:"an-dialog-box"}),i=c("h3",{class:"an-dialog-title"});i.textContent="Insert Link";const s=c("label",{class:"an-label"});s.textContent="URL";const o=c("input",{type:"url",class:"an-input",placeholder:"https://",id:"an-link-url",name:"url",autocomplete:"off"});this._urlInput=o;const a=c("label",{class:"an-label"});a.textContent="Display Text";const l=c("input",{type:"text",class:"an-input",placeholder:"Link text",id:"an-link-text",name:"linkText",autocomplete:"off"});this._textInput=l;const r=c("label",{class:"an-label an-label-inline"}),h=c("input",{type:"checkbox",id:"an-link-newtab",name:"openInNewTab"});this._tabCheckbox=h,r.appendChild(h),r.appendChild(document.createTextNode(" Open in new tab"));const u=c("div",{class:"an-dialog-actions"}),m=c("button",{type:"button",class:"an-btn an-btn-primary"});m.textContent="Insert";const g=c("button",{type:"button",class:"an-btn"});g.textContent="Cancel",u.appendChild(m),u.appendChild(g),e.append(i,s,o,a,l,r,u),t.appendChild(e);const w=d(m,"click",()=>this._onInsert()),f=d(g,"click",()=>this._close()),_=d(t,"click",v=>{v.target===t&&this._close()}),k=d(o,"keydown",v=>{v.key==="Enter"&&(v.preventDefault(),this._onInsert())}),C=d(l,"keydown",v=>{v.key==="Enter"&&(v.preventDefault(),this._onInsert())});return this._disposers.push(w,f,_,k,C),t}_prefill(){const t=window.getSelection();let e=null;if(t&&t.rangeCount>0){let i=t.getRangeAt(0).startContainer;for(;i;){if(i.nodeName==="A"){e=i;break}i=i.parentNode}}e?(this._urlInput.value=e.getAttribute("href")||"",this._textInput.value=e.textContent||"",this._tabCheckbox.checked=e.getAttribute("target")==="_blank"):(this._urlInput.value="",this._textInput.value=t?t.toString():"",this._tabCheckbox.checked=!1)}_onInsert(){let t=this._urlInput.value.trim();const e=this._textInput.value.trim(),i=this._tabCheckbox.checked;if(!t){this._urlInput.focus();return}/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(t)||(t="https://"+t);try{const s=new URL(t);if(/^javascript:/i.test(s.protocol)||/^vbscript:/i.test(s.protocol)||/^data:/i.test(s.protocol)){this._urlInput.focus();return}}catch{this._urlInput.focus();return}this._savedRange&&this._savedRange.select(),this.context.invoke("editor.insertLink",t,e,i),this._close()}_open(){this._dialog&&(this._dialog.style.display="flex",this._removeTrap=O(this._dialog,()=>this._close()),setTimeout(()=>this._urlInput&&this._urlInput.focus(),50))}_close(){this._dialog&&(this._dialog.style.display="none"),this._removeTrap&&(this._removeTrap(),this._removeTrap=null),this._savedRange=null}}class Mi{constructor(t){this.context=t,this.options=t.options,this._dialog=null,this._disposers=[],this._savedRange=null}initialize(){return this._dialog=this._buildDialog(),document.body.appendChild(this._dialog),this}destroy(){this._disposers.forEach(t=>t()),this._disposers=[],this._dialog&&this._dialog.parentNode&&this._dialog.parentNode.removeChild(this._dialog),this._dialog=null}show(){Y(t=>{this._savedRange=t}),this._urlInput.value="",this._altInput.value="",this._fileInput&&(this._fileInput.value=""),this._open()}_buildDialog(){const t=c("div",{class:"an-dialog-overlay",role:"dialog","aria-modal":"true","aria-label":"Insert image"}),e=c("div",{class:"an-dialog-box"}),i=c("h3",{class:"an-dialog-title"});i.textContent="Insert Image";const s=c("label",{class:"an-label"});s.textContent="Image URL";const o=c("input",{type:"url",class:"an-input",placeholder:"https://example.com/image.png",autocomplete:"off"});this._urlInput=o;const a=c("label",{class:"an-label"});a.textContent="Alt Text";const l=c("input",{type:"text",class:"an-input",placeholder:"Describe the image",autocomplete:"off"});this._altInput=l,e.append(i,s,o,a,l);const r=c("label",{class:"an-label"});r.textContent="Alignment";const h=c("div",{class:"an-align-row"});if([{value:"",label:"None"},{value:"left",label:"Left"},{value:"center",label:"Center"},{value:"right",label:"Right"}].forEach(({value:y,label:x})=>{const b=`an-align-${y||"none"}`,T=c("input",{type:"radio",name:"an-img-align",id:b,value:y});y===""&&(T.checked=!0);const E=c("label",{for:b,class:"an-align-label"});E.textContent=x,h.append(T,E)}),this._alignRow=h,e.append(r,h),this.options.allowImageUpload!==!1){const y=c("label",{class:"an-label"});y.textContent="Or upload a file";const x=c("input",{type:"file",class:"an-input",accept:"image/*"});this._fileInput=x;const b=d(x,"change",()=>this._onFileChange());this._disposers.push(b),e.append(y,x)}const m=c("div",{class:"an-dialog-actions"}),g=c("button",{type:"button",class:"an-btn an-btn-primary"});g.textContent="Insert";const w=c("button",{type:"button",class:"an-btn"});w.textContent="Cancel",m.appendChild(g),m.appendChild(w),e.append(m),t.appendChild(e);const f=d(g,"click",()=>this._onInsert()),_=d(w,"click",()=>this._close()),k=d(t,"click",y=>{y.target===t&&this._close()}),C=d(o,"keydown",y=>{y.key==="Enter"&&(y.preventDefault(),this._onInsert())}),v=d(l,"keydown",y=>{y.key==="Enter"&&(y.preventDefault(),this._onInsert())});return this._disposers.push(f,_,k,C,v),t}_onFileChange(){const t=this._fileInput&&this._fileInput.files&&this._fileInput.files[0];if(!t||!t.type.startsWith("image/"))return;const e=(this.options.maxImageSize||5)*1024*1024;if(t.size>e){const s=`Image file is too large. Maximum allowed size is ${this.options.maxImageSize||5} MB.`;console.warn("[AutumnNote] ImageDialog:",s),this.context.triggerEvent("imageError",{file:t,message:s}),this._fileInput.value="";return}const i=new FileReader;i.onload=s=>{this._urlInput.value=s.target.result},i.readAsDataURL(t)}_onInsert(){const t=this._urlInput.value.trim(),e=this._altInput.value.trim(),i=this._alignRow&&this._alignRow.querySelector('input[name="an-img-align"]:checked'),s=i?i.value:"";if(!t){this._urlInput.focus();return}this._savedRange&&this._savedRange.select(),this.context.invoke("editor.insertImage",t,e,s),this._close()}_open(){this._dialog&&(this._dialog.style.display="flex",this._removeTrap=O(this._dialog,()=>this._close()),setTimeout(()=>this._urlInput&&this._urlInput.focus(),50))}_close(){this._dialog&&(this._dialog.style.display="none"),this._removeTrap&&(this._removeTrap(),this._removeTrap=null),this._savedRange=null}}class ji{constructor(t){this.context=t,this.options=t.options,this._dialog=null,this._disposers=[],this._savedRange=null}initialize(){return this._dialog=this._buildDialog(),document.body.appendChild(this._dialog),this}destroy(){this._disposers.forEach(t=>t()),this._disposers=[],this._dialog&&this._dialog.parentNode&&this._dialog.parentNode.removeChild(this._dialog),this._dialog=null}show(){Y(t=>{this._savedRange=t}),this._urlInput.value="",this._widthInput.value="560",this._hintEl.textContent="",this._open()}_buildDialog(){const t=c("div",{class:"an-dialog-overlay",role:"dialog","aria-modal":"true","aria-label":"Insert video"}),e=c("div",{class:"an-dialog-box"}),i=c("h3",{class:"an-dialog-title"});i.textContent="Insert Video";const s=c("label",{class:"an-label"});s.textContent="Video URL";const o=c("input",{type:"url",class:"an-input",placeholder:"YouTube, Vimeo, or direct .mp4 URL",autocomplete:"off"});this._urlInput=o;const a=c("p",{class:"an-dialog-hint"});this._hintEl=a;const l=c("label",{class:"an-label"});l.textContent="Width (px)";const r=c("input",{type:"number",class:"an-input",placeholder:"560",min:"80",max:"1920",value:"560"});this._widthInput=r;const h=c("div",{class:"an-dialog-actions"}),u=c("button",{type:"button",class:"an-btn an-btn-primary"});u.textContent="Insert";const m=c("button",{type:"button",class:"an-btn"});m.textContent="Cancel",h.appendChild(u),h.appendChild(m),e.append(i,s,o,a,l,r,h),t.appendChild(e);const g=d(o,"input",()=>{const C=this._parseVideoUrl(o.value.trim());a.textContent=C?`Detected: ${C.type}`:o.value?"Unknown format — will try direct video embed":""}),w=d(u,"click",()=>this._onInsert()),f=d(m,"click",()=>this._close()),_=d(t,"click",C=>{C.target===t&&this._close()}),k=d(o,"keydown",C=>{C.key==="Enter"&&(C.preventDefault(),this._onInsert())});return this._disposers.push(g,w,f,_,k),t}_onInsert(){const t=this._urlInput.value.trim(),e=Math.max(80,parseInt(this._widthInput.value,10)||560);if(!t){this._urlInput.focus();return}const i=this._buildEmbedHtml(t,e);if(!i){this._hintEl.textContent="Invalid URL — please enter a valid video link.",this._urlInput.focus();return}this._savedRange&&this._savedRange.select(),this.context.invoke("editor.insertVideo",i),this._close()}_open(){this._dialog&&(this._dialog.style.display="flex",this._removeTrap=O(this._dialog,()=>this._close()),setTimeout(()=>this._urlInput&&this._urlInput.focus(),50))}_close(){this._dialog&&(this._dialog.style.display="none"),this._removeTrap&&(this._removeTrap(),this._removeTrap=null),this._savedRange=null}_parseVideoUrl(t){if(!t)return null;try{const a=new URL(t);if(/^javascript:/i.test(a.protocol)||/^vbscript:/i.test(a.protocol))return null}catch{return null}const e=t.match(/(?:youtube\.com\/watch\?(?:.*&)?v=|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/);if(e)return{type:"YouTube",embedUrl:`https://www.youtube.com/embed/${e[1]}`};const i=t.match(/youtu\.be\/([a-zA-Z0-9_-]{11})/);if(i)return{type:"YouTube",embedUrl:`https://www.youtube.com/embed/${i[1]}`};const s=t.match(/youtube\.com\/shorts\/([a-zA-Z0-9_-]{11})/);if(s)return{type:"YouTube Shorts",embedUrl:`https://www.youtube.com/embed/${s[1]}`};const o=t.match(/vimeo\.com\/(\d+)/);return o?{type:"Vimeo",embedUrl:`https://player.vimeo.com/video/${o[1]}`}:/\.(mp4|webm|ogg|ogv|mov)(#.*|\?.*)?$/i.test(t)?{type:"Direct video",embedUrl:t}:null}_buildEmbedHtml(t,e){const i=this._parseVideoUrl(t),s=Math.round(e*9/16);if(i&&(i.type==="YouTube"||i.type==="YouTube Shorts"||i.type==="Vimeo")){const l=`${i.type} video player`;return`<div class="an-video-wrapper" style="position:relative;display:inline-block;max-width:100%"><iframe src="${i.embedUrl}" width="${e}" height="${s}" title="${l}" frameborder="0" allowfullscreen allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" style="display:block;max-width:100%"></iframe><div class="an-video-shield"></div></div>`}if(i&&i.type==="Direct video")return`<div class="an-video-wrapper" style="position:relative;display:inline-block;max-width:100%"><video src="${i.embedUrl.replace(/"/g,"%22")}" width="${e}" height="${s}" controls style="display:block;max-width:100%"></video><div class="an-video-shield"></div></div>`;const o=(()=>{try{const l=new URL(t);return/^javascript:/i.test(l.protocol)||/^vbscript:/i.test(l.protocol)?null:t}catch{return null}})();return o?`<div class="an-video-wrapper" style="position:relative;display:inline-block;max-width:100%"><video src="${o.replace(/"/g,"%22")}" width="${e}" height="${s}" controls style="display:block;max-width:100%"></video><div class="an-video-shield"></div></div>`:null}}const Ni=[{pos:"nw",cursor:"nw-resize"},{pos:"n",cursor:"n-resize"},{pos:"ne",cursor:"ne-resize"},{pos:"e",cursor:"e-resize"},{pos:"se",cursor:"se-resize"},{pos:"s",cursor:"s-resize"},{pos:"sw",cursor:"sw-resize"},{pos:"w",cursor:"w-resize"}];class zi{constructor(t){this.context=t,this._activeImg=null,this._overlay=null,this._disposers=[]}initialize(){this._overlay=this._buildOverlay(),document.body.appendChild(this._overlay);const t=this.context.layoutInfo.editable;return this._disposers.push(d(t,"click",e=>this._onEditorClick(e)),d(t,"contextmenu",e=>{const i=e.target.closest("img");i&&this._select(i)}),d(document,"click",e=>this._onDocClick(e)),d(window,"scroll",()=>this._updateOverlayPosition(),{passive:!0}),d(window,"resize",()=>this._updateOverlayPosition()),d(t,"scroll",()=>this._updateOverlayPosition(),{passive:!0})),this}destroy(){this._disposers.forEach(t=>t()),this._disposers=[],this._dragDisposers&&(this._dragDisposers.forEach(t=>t()),this._dragDisposers=null),this._deselect(),this._overlay&&this._overlay.parentNode&&this._overlay.parentNode.removeChild(this._overlay),this._overlay=null}getActiveImage(){return this._activeImg}updateOverlay(){this._updateOverlayPosition()}deselect(){this._deselect()}_buildOverlay(){const t=document.createElement("div");return t.className="an-image-resizer",t.style.display="none",Ni.forEach(({pos:e})=>{const i=document.createElement("div");i.className=`an-resize-handle an-resize-${e}`,i.dataset.handle=e,this._disposers.push(d(i,"mousedown",s=>{s.preventDefault(),s.stopPropagation(),this._startResize(s,e)})),t.appendChild(i)}),t}_onEditorClick(t){const e=t.target.closest("img");e&&(t.preventDefault(),this._select(e))}_onDocClick(t){this._activeImg&&t.target!==this._activeImg&&(this._overlay&&this._overlay.contains(t.target)||t.target.closest(".an-contextmenu")||this._deselect())}_select(t){this._activeImg&&this._activeImg!==t&&this._activeImg.classList.remove("an-image-selected"),this._activeImg=t,t.classList.add("an-image-selected"),this._updateOverlayPosition(),this._overlay.style.display="block"}_deselect(){this._activeImg&&(this._activeImg.classList.remove("an-image-selected"),this._activeImg=null),this._overlay&&(this._overlay.style.display="none")}_updateOverlayPosition(){if(!this._activeImg||!this._overlay)return;const t=this._activeImg.getBoundingClientRect();this._overlay.style.left=`${t.left}px`,this._overlay.style.top=`${t.top}px`,this._overlay.style.width=`${t.width}px`,this._overlay.style.height=`${t.height}px`}_startResize(t,e){const i=this._activeImg;if(!i)return;const s=t.clientX,o=t.clientY,a=i.offsetWidth||i.naturalWidth||100,l=i.offsetHeight||i.naturalHeight||100,r=a/l,h=e.length===2,u=this.context.layoutInfo.editable,m=w=>{const f=w.clientX-s,_=w.clientY-o,k=u.clientWidth||1/0;let C=a,v=l;e.includes("e")&&(C=Math.max(20,a+f)),e.includes("w")&&(C=Math.max(20,a-f)),e.includes("s")&&(v=Math.max(20,l+_)),e.includes("n")&&(v=Math.max(20,l-_)),C=Math.min(C,k),h&&(Math.abs(f)>=Math.abs(_)||(C=Math.min(Math.max(20,Math.round(v*r)),k)),v=Math.max(20,Math.round(C/r))),i.style.width=`${C}px`,i.style.height=`${v}px`,this._updateOverlayPosition()},g=()=>{document.removeEventListener("mousemove",m),document.removeEventListener("mouseup",g),this._dragDisposers=null,this.context.invoke("editor.afterCommand")};document.addEventListener("mousemove",m),document.addEventListener("mouseup",g),this._dragDisposers=[()=>document.removeEventListener("mousemove",m),()=>document.removeEventListener("mouseup",g)]}}const Hi=[{pos:"nw",cursor:"nw-resize"},{pos:"n",cursor:"n-resize"},{pos:"ne",cursor:"ne-resize"},{pos:"e",cursor:"e-resize"},{pos:"se",cursor:"se-resize"},{pos:"s",cursor:"s-resize"},{pos:"sw",cursor:"sw-resize"},{pos:"w",cursor:"w-resize"}];class $i{constructor(t){this.context=t,this._activeWrapper=null,this._overlay=null,this._disposers=[]}initialize(){this._overlay=this._buildOverlay(),document.body.appendChild(this._overlay);const t=this.context.layoutInfo.editable;return this._disposers.push(d(t,"click",e=>this._onEditorClick(e)),d(t,"contextmenu",e=>{const i=this._findWrapper(e.target);i&&this._select(i)}),d(document,"click",e=>this._onDocClick(e)),d(window,"scroll",()=>this._updateOverlayPosition(),{passive:!0}),d(window,"resize",()=>this._updateOverlayPosition()),d(t,"scroll",()=>this._updateOverlayPosition(),{passive:!0})),this}destroy(){this._disposers.forEach(t=>t()),this._disposers=[],this._dragDisposers&&(this._dragDisposers.forEach(t=>t()),this._dragDisposers=null),this._deselect(),this._overlay&&this._overlay.parentNode&&this._overlay.parentNode.removeChild(this._overlay),this._overlay=null}getActiveWrapper(){return this._activeWrapper}updateOverlay(){this._updateOverlayPosition()}deselect(){this._deselect()}_findWrapper(t){if(!t||!(t instanceof Element))return null;if(t.classList&&t.classList.contains("an-video-wrapper"))return t;const e=t.closest(".an-video-wrapper");return e||null}_buildOverlay(){const t=document.createElement("div");return t.className="an-video-resizer",t.style.display="none",Hi.forEach(({pos:e})=>{const i=document.createElement("div");i.className=`an-resize-handle an-resize-${e}`,i.dataset.handle=e,this._disposers.push(d(i,"mousedown",s=>{s.preventDefault(),s.stopPropagation(),this._startResize(s,e)})),t.appendChild(i)}),t}_onEditorClick(t){const e=this._findWrapper(t.target);e&&(t.preventDefault(),this._select(e))}_onDocClick(t){this._activeWrapper&&(this._activeWrapper.contains(t.target)||this._overlay&&this._overlay.contains(t.target)||t.target.closest(".an-contextmenu")||this._deselect())}_select(t){this._activeWrapper&&this._activeWrapper!==t&&this._activeWrapper.classList.remove("an-video-selected"),this._activeWrapper=t,t.classList.add("an-video-selected"),this._updateOverlayPosition(),this._overlay.style.display="block"}_deselect(){this._activeWrapper&&(this._activeWrapper.classList.remove("an-video-selected"),this._activeWrapper=null),this._overlay&&(this._overlay.style.display="none")}_updateOverlayPosition(){if(!this._activeWrapper||!this._overlay)return;const t=this._activeWrapper.getBoundingClientRect();this._overlay.style.left=`${t.left}px`,this._overlay.style.top=`${t.top}px`,this._overlay.style.width=`${t.width}px`,this._overlay.style.height=`${t.height}px`}_startResize(t,e){const i=this._activeWrapper;if(!i)return;const s=i.querySelector("iframe, video"),o=t.clientX,a=t.clientY,l=i.offsetWidth||560,r=i.offsetHeight||315,h=l/r,u=e.length===2,m=this.context.layoutInfo.editable,g=f=>{const _=f.clientX-o,k=f.clientY-a,C=m.clientWidth||1/0;let v=l,y=r;e.includes("e")&&(v=Math.max(80,l+_)),e.includes("w")&&(v=Math.max(80,l-_)),e.includes("s")&&(y=Math.max(45,r+k)),e.includes("n")&&(y=Math.max(45,r-k)),v=Math.min(v,C),u&&(Math.abs(_)>=Math.abs(k)||(v=Math.min(Math.max(80,Math.round(y*h)),C)),y=Math.max(45,Math.round(v/h))),i.style.width=`${v}px`,i.style.height=`${y}px`,s&&(s.width=v,s.height=y,s.style.width=`${v}px`,s.style.height=`${y}px`),this._updateOverlayPosition()},w=()=>{document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",w),this._dragDisposers=null,this.context.invoke("editor.afterCommand")};document.addEventListener("mousemove",g),document.addEventListener("mouseup",w),this._dragDisposers=[()=>document.removeEventListener("mousemove",g),()=>document.removeEventListener("mouseup",w)]}}const rt={open:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>',edit:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>',unlink:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18.84 12.25l1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71"/><path d="M5.17 11.75l-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71"/><line x1="8" y1="2" x2="8" y2="5"/><line x1="2" y1="8" x2="5" y2="8"/><line x1="16" y1="19" x2="16" y2="22"/><line x1="19" y1="16" x2="22" y2="16"/></svg>',copy:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>'},Di=120,Pi=200;class Oi{constructor(t){this.context=t,this._el=null,this._activeAnchor=null,this._showTimer=null,this._hideTimer=null,this._disposers=[]}initialize(){this._el=this._buildTooltip(),document.body.appendChild(this._el);const t=this.context.layoutInfo.editable;return this._disposers.push(d(t,"mouseover",e=>{const i=e.target.closest("a[href]");i&&t.contains(i)&&this._scheduleShow(i)}),d(t,"mouseout",e=>{const i=e.relatedTarget;(!i||!t.contains(i)&&!this._el.contains(i))&&this._scheduleHide()})),this}destroy(){this._clearTimers(),this._disposers.forEach(t=>t()),this._disposers=[],this._el&&this._el.parentNode&&this._el.parentNode.removeChild(this._el),this._el=null}_buildTooltip(){const t=c("div",{class:"an-link-tooltip",role:"toolbar","aria-label":"Link actions"});return t.style.display="none",this._urlLabel=c("span",{class:"an-link-tooltip-url"}),t.appendChild(this._urlLabel),t.appendChild(c("div",{class:"an-link-tooltip-sep"})),this._openBtn=this._makeBtn(rt.open,"Open link",()=>this._openLink()),this._copyBtn=this._makeBtn(rt.copy,"Copy URL",()=>this._copyLink()),this._editBtn=this._makeBtn(rt.edit,"Edit link",()=>this._editLink()),this._unlinkBtn=this._makeBtn(rt.unlink,"Remove link",()=>this._unlink()),t.appendChild(this._openBtn),t.appendChild(this._copyBtn),t.appendChild(this._editBtn),t.appendChild(this._unlinkBtn),this._disposers.push(d(t,"mouseenter",()=>this._clearTimers()),d(t,"mouseleave",()=>this._scheduleHide())),t}_makeBtn(t,e,i){const s=c("button",{type:"button",class:"an-link-tooltip-btn",title:e});return s.innerHTML=t,this._disposers.push(d(s,"click",o=>{o.preventDefault(),o.stopPropagation(),i()})),s}_scheduleShow(t){this._activeAnchor===t&&this._el.style.display!=="none"||(clearTimeout(this._hideTimer),this._hideTimer=null,clearTimeout(this._showTimer),this._showTimer=setTimeout(()=>{this._activeAnchor=t,this._show(t)},Di))}_scheduleHide(){clearTimeout(this._showTimer),this._showTimer=null,!this._hideTimer&&(this._hideTimer=setTimeout(()=>{this._hide()},Pi))}_show(t){const e=t.getAttribute("href")||"";this._urlLabel.textContent=this._truncateUrl(e),this._urlLabel.title=e,this._el.style.display="flex",this._positionNear(t)}_hide(){this._el.style.display="none",this._activeAnchor=null,this._clearTimers()}_clearTimers(){clearTimeout(this._showTimer),clearTimeout(this._hideTimer),this._showTimer=null,this._hideTimer=null}_positionNear(t){const e=t.getBoundingClientRect(),i=this._el.offsetWidth||260,s=this._el.offsetHeight||34,o=6;let a=e.bottom+o,l=e.left;a+s>window.innerHeight-o&&(a=e.top-s-o),l+i>window.innerWidth-o&&(l=window.innerWidth-i-o),l<o&&(l=o),this._el.style.top=`${a}px`,this._el.style.left=`${l}px`}_truncateUrl(t){try{const e=new URL(t),i=e.host+(e.pathname!=="/"?e.pathname:"");return i.length>48?i.slice(0,48)+"…":i}catch{return t.length>48?t.slice(0,48)+"…":t}}_openLink(){const t=this._activeAnchor&&this._activeAnchor.getAttribute("href");t&&window.open(t,"_blank","noopener,noreferrer"),this._hide()}_copyLink(){const t=this._activeAnchor&&this._activeAnchor.getAttribute("href");t&&navigator.clipboard.writeText(t).catch(()=>{const e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e)}),this._copyBtn&&(this._copyBtn.classList.add("an-link-tooltip-btn--copied"),setTimeout(()=>this._copyBtn&&this._copyBtn.classList.remove("an-link-tooltip-btn--copied"),1e3))}_editLink(){const t=this._activeAnchor;if(!t)return;this._hide();const e=window.getSelection(),i=document.createRange();i.selectNodeContents(t),e.removeAllRanges(),e.addRange(i),this.context.invoke("linkDialog.show")}_unlink(){const t=this._activeAnchor;if(!t)return;this._hide();const e=window.getSelection(),i=document.createRange();i.selectNode(t),e.removeAllRanges(),e.addRange(i),document.execCommand("unlink"),this.context.invoke("editor.afterCommand")}}const q={floatLeft:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="8" height="8" rx="1"/><line x1="12" y1="6" x2="22" y2="6"/><line x1="12" y1="9" x2="22" y2="9"/><line x1="12" y1="12" x2="22" y2="12"/><line x1="2" y1="16" x2="22" y2="16"/><line x1="2" y1="20" x2="18" y2="20"/></svg>',floatRight:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="14" y="4" width="8" height="8" rx="1"/><line x1="2" y1="6" x2="12" y2="6"/><line x1="2" y1="9" x2="12" y2="9"/><line x1="2" y1="12" x2="12" y2="12"/><line x1="2" y1="16" x2="22" y2="16"/><line x1="2" y1="20" x2="18" y2="20"/></svg>',floatNone:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="8" height="8" rx="1"/><line x1="3" y1="15" x2="21" y2="15"/><line x1="3" y1="19" x2="17" y2="19"/></svg>',alignCenter:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="4" width="10" height="8" rx="1"/><line x1="3" y1="16" x2="21" y2="16"/><line x1="6" y1="20" x2="18" y2="20"/></svg>',originalSize:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>',deleteImg:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>',caption:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="11" rx="2"/><line x1="6" y1="18" x2="18" y2="18"/><line x1="9" y1="21" x2="15" y2="21"/></svg>'},Fi=100,Wi=180;class Ui{constructor(t){this.context=t,this._el=null,this._activeImg=null,this._showTimer=null,this._hideTimer=null,this._disposers=[]}initialize(){this._el=this._buildTooltip(),document.body.appendChild(this._el);const t=this.context.layoutInfo.editable;return this._disposers.push(d(t,"mouseover",e=>{const i=e.target.closest("img");i&&t.contains(i)&&this._scheduleShow(i)}),d(t,"mouseout",e=>{const i=e.relatedTarget;(!i||!t.contains(i)&&!this._el.contains(i))&&this._scheduleHide()}),d(document,"click",e=>{this._activeImg&&!this._activeImg.contains(e.target)&&!this._el.contains(e.target)&&this._hide()})),this}destroy(){this._clearTimers(),this._disposers.forEach(t=>t()),this._disposers=[],this._el&&this._el.parentNode&&this._el.parentNode.removeChild(this._el),this._el=null}_buildTooltip(){const t=c("div",{class:"an-link-tooltip an-image-tooltip",role:"toolbar","aria-label":"Image actions"});return t.style.display="none",this._label=c("span",{class:"an-link-tooltip-url"}),this._label.textContent="Image",t.appendChild(this._label),t.appendChild(c("div",{class:"an-link-tooltip-sep"})),this._floatLeftBtn=this._makeBtn(q.floatLeft,"Float Left",()=>this._setFloat("left")),this._floatNoneBtn=this._makeBtn(q.floatNone,"No Float",()=>this._setFloat("")),this._alignCenterBtn=this._makeBtn(q.alignCenter,"Align Center",()=>this._setCenter()),this._floatRightBtn=this._makeBtn(q.floatRight,"Float Right",()=>this._setFloat("right")),t.appendChild(this._floatLeftBtn),t.appendChild(this._floatNoneBtn),t.appendChild(this._alignCenterBtn),t.appendChild(this._floatRightBtn),t.appendChild(c("div",{class:"an-link-tooltip-sep"})),this._originalBtn=this._makeBtn(q.originalSize,"Original Size",()=>this._resetSize()),t.appendChild(this._originalBtn),t.appendChild(c("div",{class:"an-link-tooltip-sep"})),this._captionBtn=this._makeBtn(q.caption,"Add / Edit Caption",()=>this._toggleCaption()),t.appendChild(this._captionBtn),t.appendChild(c("div",{class:"an-link-tooltip-sep"})),this._deleteBtn=this._makeBtn(q.deleteImg,"Delete Image",()=>this._delete(),!0),t.appendChild(this._deleteBtn),this._disposers.push(d(t,"mouseenter",()=>this._clearTimers()),d(t,"mouseleave",()=>this._scheduleHide())),t}_makeBtn(t,e,i,s=!1){const o=c("button",{type:"button",class:s?"an-link-tooltip-btn an-link-tooltip-btn--danger":"an-link-tooltip-btn",title:e});return o.innerHTML=t,this._disposers.push(d(o,"click",a=>{a.preventDefault(),a.stopPropagation(),i()})),o}_scheduleShow(t){this._activeImg===t&&this._el.style.display!=="none"||(clearTimeout(this._hideTimer),this._hideTimer=null,clearTimeout(this._showTimer),this._showTimer=setTimeout(()=>{this._activeImg=t,this._show(t)},Fi))}_scheduleHide(){clearTimeout(this._showTimer),this._showTimer=null,!this._hideTimer&&(this._hideTimer=setTimeout(()=>this._hide(),Wi))}_show(t){this._el.style.display="flex",this._positionNear(t)}_hide(){this._el.style.display="none",this._activeImg=null,this._clearTimers()}_clearTimers(){clearTimeout(this._showTimer),clearTimeout(this._hideTimer),this._showTimer=null,this._hideTimer=null}_positionNear(t){const e=t.getBoundingClientRect(),i=this._el.offsetWidth||220,s=this._el.offsetHeight||32,o=6;let a=e.bottom+o,l=e.left+(e.width-i)/2;a+s>window.innerHeight-o&&(a=e.top-s-o),l+i>window.innerWidth-o&&(l=window.innerWidth-i-o),l<o&&(l=o),this._el.style.top=`${a}px`,this._el.style.left=`${l}px`}_setFloat(t){const e=this._activeImg;e&&(e.style.float=t,e.style.display="",e.style.marginLeft=t==="right"?"12px":"",e.style.marginRight=t==="left"?"12px":"",this.context.invoke("editor.afterCommand"),this.context.invoke("imageResizer.updateOverlay"),this._positionNear(e))}_setCenter(){const t=this._activeImg;t&&(t.style.float="",t.style.display="block",t.style.marginLeft="auto",t.style.marginRight="auto",this.context.invoke("editor.afterCommand"),this.context.invoke("imageResizer.updateOverlay"),this._positionNear(t))}_resetSize(){const t=this._activeImg;t&&(t.style.width="",t.style.height="",this.context.invoke("editor.afterCommand"),this.context.invoke("imageResizer.updateOverlay"),this._positionNear(t))}_delete(){const t=this._activeImg;t&&(this._hide(),this.context.invoke("imageResizer.deselect"),t.parentNode&&t.parentNode.removeChild(t),this.context.invoke("editor.afterCommand"))}_toggleCaption(){const t=this._activeImg;if(!t)return;const e=t.closest("figure.an-figure");if(e){const l=e.querySelector("figcaption.an-figcaption");if(l){this._hide();const r=document.createRange();r.selectNodeContents(l);const h=window.getSelection();h&&(h.removeAllRanges(),h.addRange(r))}return}const i=document.createElement("figure");i.className="an-figure";const s=document.createElement("figcaption");s.className="an-figcaption",s.textContent="Caption",t.parentNode.insertBefore(i,t),i.appendChild(t),i.appendChild(s);const o=document.createRange();o.selectNodeContents(s);const a=window.getSelection();a&&(a.removeAllRanges(),a.addRange(o)),this.context.invoke("editor.afterCommand"),this._hide()}}const X={floatLeft:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="8" height="8" rx="1"/><line x1="12" y1="6" x2="22" y2="6"/><line x1="12" y1="9" x2="22" y2="9"/><line x1="12" y1="12" x2="22" y2="12"/><line x1="2" y1="16" x2="22" y2="16"/><line x1="2" y1="20" x2="18" y2="20"/></svg>',floatRight:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="14" y="4" width="8" height="8" rx="1"/><line x1="2" y1="6" x2="12" y2="6"/><line x1="2" y1="9" x2="12" y2="9"/><line x1="2" y1="12" x2="12" y2="12"/><line x1="2" y1="16" x2="22" y2="16"/><line x1="2" y1="20" x2="18" y2="20"/></svg>',floatNone:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="8" height="8" rx="1"/><line x1="3" y1="15" x2="21" y2="15"/><line x1="3" y1="19" x2="17" y2="19"/></svg>',alignCenter:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="4" width="10" height="8" rx="1"/><line x1="3" y1="16" x2="21" y2="16"/><line x1="6" y1="20" x2="18" y2="20"/></svg>',originalSize:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>',deleteVideo:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>'},qi=100,Vi=180;class Yi{constructor(t){this.context=t,this._el=null,this._activeWrapper=null,this._showTimer=null,this._hideTimer=null,this._disposers=[]}initialize(){this._el=this._buildTooltip(),document.body.appendChild(this._el);const t=this.context.layoutInfo.editable;return this._disposers.push(d(t,"mouseover",e=>{const i=e.target.closest(".an-video-wrapper");i&&t.contains(i)&&this._scheduleShow(i)}),d(t,"mouseout",e=>{const i=e.relatedTarget;(!i||!t.contains(i)&&!this._el.contains(i))&&this._scheduleHide()}),d(document,"click",e=>{this._activeWrapper&&!this._activeWrapper.contains(e.target)&&!this._el.contains(e.target)&&this._hide()})),this}destroy(){this._clearTimers(),this._disposers.forEach(t=>t()),this._disposers=[],this._el&&this._el.parentNode&&this._el.parentNode.removeChild(this._el),this._el=null}_buildTooltip(){const t=c("div",{class:"an-link-tooltip an-video-tooltip",role:"toolbar","aria-label":"Video actions"});return t.style.display="none",this._label=c("span",{class:"an-link-tooltip-url"}),this._label.textContent="Video",t.appendChild(this._label),t.appendChild(c("div",{class:"an-link-tooltip-sep"})),this._floatLeftBtn=this._makeBtn(X.floatLeft,"Float Left",()=>this._setFloat("left")),this._floatNoneBtn=this._makeBtn(X.floatNone,"No Float",()=>this._setFloat("")),this._alignCenterBtn=this._makeBtn(X.alignCenter,"Align Center",()=>this._setCenter()),this._floatRightBtn=this._makeBtn(X.floatRight,"Float Right",()=>this._setFloat("right")),t.appendChild(this._floatLeftBtn),t.appendChild(this._floatNoneBtn),t.appendChild(this._alignCenterBtn),t.appendChild(this._floatRightBtn),t.appendChild(c("div",{class:"an-link-tooltip-sep"})),this._originalBtn=this._makeBtn(X.originalSize,"Original Size",()=>this._resetSize()),t.appendChild(this._originalBtn),t.appendChild(c("div",{class:"an-link-tooltip-sep"})),this._deleteBtn=this._makeBtn(X.deleteVideo,"Delete Video",()=>this._delete(),!0),t.appendChild(this._deleteBtn),this._disposers.push(d(t,"mouseenter",()=>this._clearTimers()),d(t,"mouseleave",()=>this._scheduleHide())),t}_makeBtn(t,e,i,s=!1){const o=c("button",{type:"button",class:s?"an-link-tooltip-btn an-link-tooltip-btn--danger":"an-link-tooltip-btn",title:e});return o.innerHTML=t,this._disposers.push(d(o,"click",a=>{a.preventDefault(),a.stopPropagation(),i()})),o}_scheduleShow(t){this._activeWrapper===t&&this._el.style.display!=="none"||(clearTimeout(this._hideTimer),this._hideTimer=null,clearTimeout(this._showTimer),this._showTimer=setTimeout(()=>{this._activeWrapper=t,this._show(t)},qi))}_scheduleHide(){clearTimeout(this._showTimer),this._showTimer=null,!this._hideTimer&&(this._hideTimer=setTimeout(()=>this._hide(),Vi))}_show(t){this._el.style.display="flex",this._positionNear(t)}_hide(){this._el.style.display="none",this._activeWrapper=null,this._clearTimers()}_clearTimers(){clearTimeout(this._showTimer),clearTimeout(this._hideTimer),this._showTimer=null,this._hideTimer=null}_positionNear(t){const e=t.getBoundingClientRect(),i=this._el.offsetWidth||220,s=this._el.offsetHeight||32,o=6;let a=e.bottom+o,l=e.left+(e.width-i)/2;a+s>window.innerHeight-o&&(a=e.top-s-o),l+i>window.innerWidth-o&&(l=window.innerWidth-i-o),l<o&&(l=o),this._el.style.top=`${a}px`,this._el.style.left=`${l}px`}_setFloat(t){const e=this._activeWrapper;e&&(e.style.float=t,e.style.display=t?"inline-block":"",e.style.marginLeft=t==="right"?"12px":"",e.style.marginRight=t==="left"?"12px":"",this.context.invoke("editor.afterCommand"),this.context.invoke("videoResizer.updateOverlay"),this._positionNear(e))}_setCenter(){const t=this._activeWrapper;t&&(t.style.float="",t.style.display="block",t.style.marginLeft="auto",t.style.marginRight="auto",this.context.invoke("editor.afterCommand"),this.context.invoke("videoResizer.updateOverlay"),this._positionNear(t))}_resetSize(){const t=this._activeWrapper;if(!t)return;const e=t.querySelector("iframe, video");t.style.width="",t.style.height="",e&&(e.removeAttribute("width"),e.removeAttribute("height"),e.style.width="",e.style.height=""),this.context.invoke("editor.afterCommand"),this.context.invoke("videoResizer.updateOverlay"),this._positionNear(t)}_delete(){const t=this._activeWrapper;t&&(this._hide(),this.context.invoke("videoResizer.deselect"),t.parentNode&&t.parentNode.removeChild(t),this.context.invoke("editor.afterCommand"))}}const Ki=120,Xi=200,D={rowAbove:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="1"/><line x1="3" y1="12" x2="21" y2="12"/><path d="M12 3v7"/><path d="M9 7l3-4 3 4"/></svg>',rowBelow:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="1"/><line x1="3" y1="12" x2="21" y2="12"/><path d="M12 12v7"/><path d="M9 17l3 4 3-4"/></svg>',deleteRow:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="1"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="15" y1="15" x2="21" y2="21"/><line x1="21" y1="15" x2="15" y2="21"/></svg>',colLeft:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="1"/><line x1="12" y1="3" x2="12" y2="21"/><path d="M3 12h7"/><path d="M7 8l-4 4 4 4"/></svg>',colRight:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="1"/><line x1="12" y1="3" x2="12" y2="21"/><path d="M12 12h9"/><path d="M17 8l4 4-4 4"/></svg>',deleteCol:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="1"/><line x1="12" y1="3" x2="12" y2="21"/><line x1="15" y1="6" x2="21" y2="12"/><line x1="21" y1="6" x2="15" y2="12"/></svg>',mergeCells:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="7" width="8" height="10" rx="1"/><rect x="14" y="7" width="8" height="10" rx="1"/><path d="M10 12h4"/><path d="M12 10l2 2-2 2"/></svg>',colWidth:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="7" y1="4" x2="7" y2="20"/><line x1="17" y1="4" x2="17" y2="20"/><line x1="7" y1="12" x2="17" y2="12"/><path d="M10 9l-3 3 3 3"/><path d="M14 9l3 3-3 3"/></svg>',rowHeight:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="4" y1="7" x2="20" y2="7"/><line x1="4" y1="17" x2="20" y2="17"/><line x1="12" y1="7" x2="12" y2="17"/><path d="M9 10l3-3 3 3"/><path d="M9 14l3 3 3-3"/></svg>',deleteTable:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="1"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="3" y1="15" x2="21" y2="15"/><line x1="9" y1="3" x2="9" y2="21"/><line x1="15" y1="3" x2="15" y2="21"/><line x1="16" y1="16" x2="22" y2="22" stroke="#ef4444"/><line x1="22" y1="16" x2="16" y2="22" stroke="#ef4444"/></svg>'};class Gi{constructor(t){this.context=t,this._el=null,this._activeTable=null,this._activeCell=null,this._showTimer=null,this._hideTimer=null,this._disposers=[],this._sizePopover=null,this._sizeApply=null,this._sizeTitleEl=null,this._sizeInputEl=null}initialize(){this._el=this._buildTooltip(),document.body.appendChild(this._el),this._sizePopover=this._buildSizePopover(),document.body.appendChild(this._sizePopover);const t=this.context.layoutInfo.editable;return this._disposers.push(d(t,"mouseover",e=>{const i=e.target.closest("table");if(i&&t.contains(i)){const s=e.target.closest("td, th");s&&(this._activeCell=s),this._scheduleShow(i)}}),d(t,"mouseout",e=>{const i=e.relatedTarget;(!i||!t.contains(i)&&!this._el.contains(i)&&!(this._sizePopover&&this._sizePopover.contains(i)))&&this._scheduleHide()}),d(document,"click",e=>{this._activeTable&&!this._activeTable.contains(e.target)&&!this._el.contains(e.target)&&!(this._sizePopover&&this._sizePopover.contains(e.target))&&this._hide()})),this._initResize(),this}_initResize(){const t=this.context.layoutInfo.editable,e=6;let i=null,s=null,o=!1,a=null,l=0,r=0,h=0,u=0,m=-1,g=null,w=null;const f=()=>{i&&(i.style.cursor="",i=null),s=null},_=y=>{if(o)return;const x=y.target.closest("td, th");if(!x||!t.contains(x)){f();return}const b=x.getBoundingClientRect(),T=Math.abs(y.clientX-b.right)<e,E=Math.abs(y.clientY-b.bottom)<e;T&&E||T?(x.style.cursor="col-resize",i=x,s="col"):E?(x.style.cursor="row-resize",i=x,s="row"):f()},k=y=>{!i||!s||(o=!0,a=s,l=y.clientX,r=y.clientY,w=i.closest("table"),a==="col"?(h=i.offsetWidth,m=Array.from(i.closest("tr").cells).indexOf(i),document.body.style.cursor="col-resize"):(g=i.closest("tr"),u=g?g.offsetHeight:40,document.body.style.cursor="row-resize"),document.body.style.userSelect="none",y.preventDefault(),y.stopPropagation())},C=y=>{if(o)if(a==="col"){const x=Math.max(30,h+(y.clientX-l));w&&m>=0&&Array.from(w.querySelectorAll("tr")).forEach(b=>{const T=b.cells[m];T&&(T.style.width=`${x}px`,T.style.minWidth=`${x}px`)})}else{const x=Math.max(20,u+(y.clientY-r));g&&Array.from(g.cells).forEach(b=>{b.style.height=`${x}px`,b.style.minHeight=`${x}px`})}},v=()=>{o&&(o=!1,document.body.style.userSelect="",document.body.style.cursor="",a=null,w=null,g=null,m=-1,this.context.invoke("editor.afterCommand"))};this._disposers.push(d(t,"mousemove",_),d(t,"mousedown",k),d(document,"mousemove",C),d(document,"mouseup",v))}destroy(){this._clearTimers(),this._disposers.forEach(t=>t()),this._disposers=[],this._el&&this._el.parentNode&&this._el.parentNode.removeChild(this._el),this._el=null,this._sizePopover&&this._sizePopover.parentNode&&this._sizePopover.parentNode.removeChild(this._sizePopover),this._sizePopover=null}_buildTooltip(){const t=c("div",{class:"an-link-tooltip an-table-tooltip",role:"toolbar","aria-label":"Table actions"});return t.style.display="none",this._label=c("span",{class:"an-link-tooltip-url"}),this._label.textContent="Table",t.appendChild(this._label),t.appendChild(this._sep()),t.appendChild(this._makeBtn(D.rowAbove,"Add Row Above",()=>this._addRow("above"))),t.appendChild(this._makeBtn(D.rowBelow,"Add Row Below",()=>this._addRow("below"))),t.appendChild(this._makeBtn(D.deleteRow,"Delete Row",()=>this._deleteRow())),t.appendChild(this._sep()),t.appendChild(this._makeBtn(D.colLeft,"Add Column Left",()=>this._addColumn("left"))),t.appendChild(this._makeBtn(D.colRight,"Add Column Right",()=>this._addColumn("right"))),t.appendChild(this._makeBtn(D.deleteCol,"Delete Column",()=>this._deleteColumn())),t.appendChild(this._sep()),t.appendChild(this._makeBtn(D.mergeCells,"Merge Cells",()=>this._mergeCells())),t.appendChild(this._sep()),t.appendChild(this._makeBtn(D.colWidth,"Column Width",()=>this._openSizePopover("col"))),t.appendChild(this._makeBtn(D.rowHeight,"Row Height",()=>this._openSizePopover("row"))),t.appendChild(this._sep()),t.appendChild(this._makeBtn(D.deleteTable,"Delete Table",()=>this._deleteTable(),!0)),this._disposers.push(d(t,"mouseenter",()=>this._clearTimers()),d(t,"mouseleave",()=>{this._sizePopover&&this._sizePopover.style.display!=="none"||this._scheduleHide()})),t}_sep(){return c("div",{class:"an-link-tooltip-sep"})}_makeBtn(t,e,i,s=!1){const o=c("button",{type:"button",class:s?"an-link-tooltip-btn an-link-tooltip-btn--danger":"an-link-tooltip-btn",title:e});return o.innerHTML=t,this._disposers.push(d(o,"click",a=>{a.preventDefault(),a.stopPropagation(),i()})),o}_scheduleShow(t){this._activeTable===t&&this._el.style.display!=="none"||(clearTimeout(this._hideTimer),this._hideTimer=null,clearTimeout(this._showTimer),this._showTimer=setTimeout(()=>{this._activeTable=t,this._show()},Ki))}_scheduleHide(){clearTimeout(this._showTimer),this._showTimer=null,!this._hideTimer&&(this._hideTimer=setTimeout(()=>this._hide(),Xi))}_show(){this._activeTable&&(this._el.style.display="flex",this._positionNear(this._activeTable))}_hide(){this._el.style.display="none",this._activeTable=null,this._activeCell=null,this._clearTimers(),this._hideSizePopover()}_clearTimers(){clearTimeout(this._showTimer),clearTimeout(this._hideTimer),this._showTimer=null,this._hideTimer=null}_positionNear(t){if(!t)return;const e=t.getBoundingClientRect(),i=this._el.offsetWidth||400,s=this._el.offsetHeight||30,o=6;let a=e.left+(e.width-i)/2,l=e.top-s-o;l<o&&(l=e.bottom+o),a+i>window.innerWidth-o&&(a=window.innerWidth-i-o),a<o&&(a=o),this._el.style.left=`${a}px`,this._el.style.top=`${l}px`}_getCell(){return this._activeCell||this._activeTable&&this._activeTable.querySelector("td, th")}_addRow(t){var l;const e=this._getCell();if(!e)return;const i=e.closest("tr");if(!i)return;const s=Array.from(i.cells).reduce((r,h)=>r+(h.colSpan||1),0),o=document.createElement("tr"),a=Array.from(i.cells);for(let r=0;r<s;r++){const h=c("td",{},[" "]),u=a[r];u&&u.style.width&&(h.style.width=u.style.width),u&&u.style.minWidth&&(h.style.minWidth=u.style.minWidth),o.appendChild(h)}t==="above"?(l=i.parentElement)==null||l.insertBefore(o,i):i.insertAdjacentElement("afterend",o),this._positionNear(this._activeTable),this.context.invoke("editor.afterCommand")}_addColumn(t){const e=this._getCell();if(!e)return;const i=e.closest("tr"),s=e.closest("table");if(!i||!s)return;const o=Array.from(i.cells).indexOf(e);Array.from(s.querySelectorAll("tr")).forEach(a=>{const l=Array.from(a.cells),r=a.closest("thead")!==null,h=c(r?"th":"td",{},[" "]),u=t==="left"?l[o]:l[o+1]||null;a.insertBefore(h,u)}),this._positionNear(this._activeTable),this.context.invoke("editor.afterCommand")}_deleteRow(){var a;const t=this._getCell();if(!t)return;const e=t.closest("tr"),i=t.closest("table");if(!e||!i)return;const s=i.querySelector("tbody");(s?s.querySelectorAll("tr").length:i.querySelectorAll("tr").length)<=1&&e.closest("tbody")||(this._activeCell=null,(a=e.parentElement)==null||a.removeChild(e),this._positionNear(this._activeTable),this.context.invoke("editor.afterCommand"))}_deleteColumn(){const t=this._getCell();if(!t)return;const e=t.closest("tr"),i=t.closest("table");if(!e||!i||e.cells.length<=1)return;const s=Array.from(e.cells).indexOf(t);this._activeCell=null,Array.from(i.querySelectorAll("tr")).forEach(o=>{const a=o.cells[s];a&&o.removeChild(a)}),this._positionNear(this._activeTable),this.context.invoke("editor.afterCommand")}_mergeCells(){const t=this._getCell();if(!t)return;const e=t.closest("tr");if(!e)return;const i=window.getSelection();if(!i||i.rangeCount===0)return;const s=i.getRangeAt(0),o=Array.from(e.cells).filter(l=>{try{return s.intersectsNode(l)}catch{return!1}});if(o.length<2)return;const a=o[0];a.colSpan=o.reduce((l,r)=>l+(r.colSpan||1),0),a.innerHTML=o.map(l=>l.innerHTML).join(""),o.slice(1).forEach(l=>e.removeChild(l)),this.context.invoke("editor.afterCommand")}_deleteTable(){const t=this._activeTable;t&&(this._hide(),t.parentNode&&t.parentNode.removeChild(t),this.context.invoke("editor.afterCommand"))}_buildSizePopover(){const t=c("div",{class:"an-size-popover"});t.style.display="none";const e=c("div",{class:"an-size-popover-title"}),i=c("div",{class:"an-size-popover-body"}),s=c("input",{type:"number",class:"an-size-input",min:"1",max:"2000",step:"1"}),o=c("span",{class:"an-size-unit"},["px"]);i.appendChild(s),i.appendChild(o);const a=c("div",{class:"an-size-popover-actions"}),l=c("button",{type:"button",class:"an-btn"});l.textContent="Cancel";const r=c("button",{type:"button",class:"an-btn an-btn-primary"});r.textContent="Apply",a.appendChild(l),a.appendChild(r),t.appendChild(e),t.appendChild(i),t.appendChild(a),this._sizeTitleEl=e,this._sizeInputEl=s,this._sizeApply=null;const h=d(r,"click",()=>{const _=parseInt(this._sizeInputEl.value,10);_>0&&typeof this._sizeApply=="function"&&this._sizeApply(_),this._hideSizePopover()}),u=d(l,"click",()=>this._hideSizePopover()),m=d(s,"keydown",_=>{_.key==="Enter"&&(_.preventDefault(),r.click()),_.key==="Escape"&&this._hideSizePopover()}),g=d(document,"click",_=>{this._sizePopover&&this._sizePopover.style.display!=="none"&&!this._sizePopover.contains(_.target)&&!this._el.contains(_.target)&&this._hideSizePopover()}),w=d(t,"mouseenter",()=>this._clearTimers()),f=d(t,"mouseleave",()=>this._scheduleHide());return this._disposers.push(h,u,m,g,w,f),t}_openSizePopover(t){const e=this._getCell();if(!e||!this._sizePopover)return;const i=t==="col";this._sizeTitleEl.textContent=i?"Column Width (px)":"Row Height (px)",this._sizeInputEl.value=i?e.offsetWidth||120:e.closest("tr")&&e.closest("tr").offsetHeight||40,this._sizeApply=s=>{if(i){const o=e.closest("table"),a=Array.from(e.closest("tr").cells).indexOf(e);Array.from(o.querySelectorAll("tr")).forEach(l=>{const r=l.cells[a];r&&(r.style.width=`${s}px`,r.style.minWidth=`${s}px`)})}else{const o=e.closest("tr");o&&Array.from(o.cells).forEach(a=>{a.style.height=`${s}px`,a.style.minHeight=`${s}px`})}this.context.invoke("editor.afterCommand")},this._sizePopover.style.display="block",requestAnimationFrame(()=>{if(!this._sizePopover||!this._el)return;const s=this._el.getBoundingClientRect(),o=this._sizePopover.offsetWidth||220,a=this._sizePopover.offsetHeight||110;let l=s.left,r=s.bottom+6;l+o>window.innerWidth-8&&(l=window.innerWidth-o-8),r+a>window.innerHeight-8&&(r=s.top-a-6),this._sizePopover.style.left=`${l}px`,this._sizePopover.style.top=`${r}px`,this._sizeInputEl&&(this._sizeInputEl.focus(),this._sizeInputEl.select())})}_hideSizePopover(){this._sizePopover&&(this._sizePopover.style.display="none"),this._sizeApply=null}}const Ji=100,Qi=180,ct={copy:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>',wrapOn:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="6" x2="21" y2="6"/><path d="M3 12h15a3 3 0 0 1 0 6H3"/><polyline points="6 15 3 18 6 21"/></svg>',toParagraph:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 4v16"/><path d="M17 4v16"/><path d="M9 4h8a4 4 0 0 1 0 8H9V4z"/></svg>',deleteCode:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>'};class Zi{constructor(t){this.context=t,this._el=null,this._activePre=null,this._showTimer=null,this._hideTimer=null,this._disposers=[],this._copyBtn=null,this._langSelect=null,this._prismScript=null}initialize(){this._el=this._buildTooltip(),document.body.appendChild(this._el),this._ensurePrism();const t=this.context.layoutInfo.editable;return this._disposers.push(d(t,"mouseover",e=>{const i=e.target.closest("pre");i&&t.contains(i)&&this._scheduleShow(i)}),d(t,"mouseout",e=>{const i=e.relatedTarget;(!i||!t.contains(i)&&!this._el.contains(i))&&this._scheduleHide()}),d(document,"click",e=>{this._activePre&&!this._activePre.contains(e.target)&&!this._el.contains(e.target)&&this._hide()})),this}destroy(){this._clearTimers(),this._disposers.forEach(t=>t()),this._disposers=[],this._el&&this._el.parentNode&&this._el.parentNode.removeChild(this._el),this._el=null}_buildTooltip(){const t=c("div",{class:"an-link-tooltip an-code-tooltip",role:"toolbar","aria-label":"Code block actions"});return t.style.display="none",this._label=c("span",{class:"an-link-tooltip-url"}),this._label.textContent="Code",t.appendChild(this._label),t.appendChild(this._sep()),this._langSelect=c("select",{class:"an-code-lang-select",title:"Syntax Language","aria-label":"Syntax language"}),[["","Plain text"],["javascript","JavaScript"],["typescript","TypeScript"],["python","Python"],["html","HTML"],["css","CSS"],["json","JSON"],["xml","XML"],["bash","Bash / Shell"],["sql","SQL"],["java","Java"],["csharp","C#"],["php","PHP"],["ruby","Ruby"],["go","Go"],["rust","Rust"],["cpp","C++"],["c","C"],["kotlin","Kotlin"],["swift","Swift"]].forEach(([i,s])=>{const o=c("option",{value:i});o.textContent=s,this._langSelect.appendChild(o)}),this._disposers.push(d(this._langSelect,"change",()=>this._onLangChange())),t.appendChild(this._langSelect),t.appendChild(this._sep()),this._copyBtn=this._makeBtn(ct.copy,"Copy Code",()=>this._copyCode()),t.appendChild(this._copyBtn),t.appendChild(this._sep()),this._wrapBtn=this._makeBtn(ct.wrapOn,"Toggle Word Wrap",()=>this._toggleWrap()),t.appendChild(this._wrapBtn),t.appendChild(this._sep()),t.appendChild(this._makeBtn(ct.toParagraph,"Convert to Paragraph",()=>this._toParagraph())),t.appendChild(this._sep()),t.appendChild(this._makeBtn(ct.deleteCode,"Delete Code Block",()=>this._delete(),!0)),this._disposers.push(d(t,"mouseenter",()=>this._clearTimers()),d(t,"mouseleave",()=>this._scheduleHide())),t}_sep(){return c("div",{class:"an-link-tooltip-sep"})}_makeBtn(t,e,i,s=!1){const o=c("button",{type:"button",class:s?"an-link-tooltip-btn an-link-tooltip-btn--danger":"an-link-tooltip-btn",title:e});return o.innerHTML=t,this._disposers.push(d(o,"click",a=>{a.preventDefault(),a.stopPropagation(),i()})),o}_scheduleShow(t){this._activePre===t&&this._el.style.display!=="none"||(clearTimeout(this._hideTimer),this._hideTimer=null,clearTimeout(this._showTimer),this._showTimer=setTimeout(()=>{this._activePre=t,this._syncWrapBtn(),this._syncLangSelect(),this._show(t)},Ji))}_scheduleHide(){clearTimeout(this._showTimer),this._showTimer=null,!this._hideTimer&&(this._hideTimer=setTimeout(()=>this._hide(),Qi))}_show(t){this._el.style.display="flex",this._positionNear(t)}_hide(){this._el.style.display="none",this._activePre=null,this._clearTimers()}_clearTimers(){clearTimeout(this._showTimer),clearTimeout(this._hideTimer),this._showTimer=null,this._hideTimer=null}_positionNear(t){const e=t.getBoundingClientRect(),i=this._el.offsetWidth||260,s=this._el.offsetHeight||32,o=6;let a=e.top-s-o,l=e.left+(e.width-i)/2;a<o&&(a=e.bottom+o),l+i>window.innerWidth-o&&(l=window.innerWidth-i-o),l<o&&(l=o),this._el.style.top=`${a+window.scrollY}px`,this._el.style.left=`${l+window.scrollX}px`}_syncWrapBtn(){if(!this._activePre||!this._wrapBtn)return;const t=(this._activePre.style.whiteSpace||"").includes("pre-wrap")||window.getComputedStyle(this._activePre).whiteSpace==="pre-wrap";this._wrapBtn.classList.toggle("active",t),this._wrapBtn.title=t?"Disable Word Wrap":"Enable Word Wrap"}_syncLangSelect(){if(!this._activePre||!this._langSelect)return;const t=this._activePre.querySelector("code"),e=this._activePre.getAttribute("data-language")||"",i=t&&(t.className.match(/language-(\S+)/)||[])[1]||"";this._langSelect.value=e||i||""}_copyCode(){const t=this._activePre;if(!t)return;const e=t.textContent||"";if(navigator.clipboard)navigator.clipboard.writeText(e).then(()=>this._flashCopied()).catch(()=>{});else{const i=document.createElement("textarea");i.value=e,i.style.cssText="position:fixed;opacity:0;top:0;left:0",document.body.appendChild(i),i.select();try{document.execCommand("copy"),this._flashCopied()}catch{}document.body.removeChild(i)}}_flashCopied(){if(!this._copyBtn)return;const t=this._copyBtn.innerHTML;this._copyBtn.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',this._copyBtn.classList.add("an-link-tooltip-btn--copied"),setTimeout(()=>{this._copyBtn&&(this._copyBtn.innerHTML=t,this._copyBtn.classList.remove("an-link-tooltip-btn--copied"))},1400)}_toggleWrap(){const t=this._activePre;if(!t)return;const e=t.style.whiteSpace==="pre-wrap";t.style.whiteSpace=e?"pre":"pre-wrap",this._syncWrapBtn(),this.context.invoke("editor.afterCommand"),this._positionNear(t)}_onLangChange(){const t=this._activePre;if(!t)return;const e=this._langSelect.value;let i=t.querySelector("code");i||(i=document.createElement("code"),i.innerHTML=t.innerHTML,t.innerHTML="",t.appendChild(i)),i.className=e?`language-${e}`:"",t.className=e?`language-${e}`:"",e?t.setAttribute("data-language",e):t.removeAttribute("data-language");const s=()=>{i.querySelectorAll("br").forEach(o=>o.replaceWith(`
|
|
72
|
-
`)),window.Prism.highlightElement(i),this.context.invoke("editor.afterCommand")};if(
|
|
73
|
-
`),s=document.createElement("p");i.forEach((o,a)=>{a>0&&s.appendChild(document.createElement("br")),s.appendChild(document.createTextNode(o))}),t.parentNode.replaceChild(s,t),this._hide(),this.context.invoke("editor.afterCommand")}_delete(){const t=this._activePre;t&&(this._hide(),t.parentNode&&t.parentNode.removeChild(t),this.context.invoke("editor.afterCommand"))}}const ts=[{id:"smileys",label:"Smileys"},{id:"people",label:"People"},{id:"animals",label:"Animals"},{id:"food",label:"Food"},{id:"travel",label:"Travel"},{id:"objects",label:"Objects"},{id:"symbols",label:"Symbols"}],es=[["😀","grin smile happy face","smileys"],["😃","happy smile big eyes","smileys"],["😄","grinning smile laugh","smileys"],["😁","beaming smile grin","smileys"],["😆","laughing lol","smileys"],["😅","sweat grin awkward","smileys"],["🤣","rolling laugh rofl","smileys"],["😂","tears laugh cry joy","smileys"],["🙂","slight smile","smileys"],["🙃","upside down smile","smileys"],["😉","wink","smileys"],["😊","blush smile happy","smileys"],["😇","innocent halo angel","smileys"],["🥰","hearts love adore","smileys"],["😍","heart eyes love","smileys"],["🤩","star eyes excited wow","smileys"],["😘","kiss blow love","smileys"],["😋","yum delicious tongue","smileys"],["😛","tongue stuck out","smileys"],["😜","wink tongue crazy","smileys"],["🤪","zany crazy wild","smileys"],["😝","squint tongue","smileys"],["🤑","money mouth","smileys"],["🤗","hugging hug","smileys"],["🤔","thinking hmm","smileys"],["🤨","raised eyebrow","smileys"],["😐","neutral face","smileys"],["😶","no mouth","smileys"],["😏","smirk","smileys"],["😒","unamused","smileys"],["🙄","roll eyes","smileys"],["😬","grimace","smileys"],["😔","pensive sad","smileys"],["😪","sleepy tired","smileys"],["😴","sleeping zzz","smileys"],["🤤","drool","smileys"],["😷","mask sick","smileys"],["🤒","sick thermometer","smileys"],["🤕","hurt bandage","smileys"],["🤢","nausea sick","smileys"],["🤮","vomit sick","smileys"],["🤧","sneeze cold","smileys"],["🥵","hot sweat","smileys"],["🥶","cold freeze","smileys"],["😵","dizzy dead","smileys"],["🤯","mind blown","smileys"],["🤠","cowboy hat","smileys"],["🥳","party celebrate","smileys"],["😎","cool sunglasses","smileys"],["🤓","nerd glasses","smileys"],["🧐","monocle curious","smileys"],["😕","confused","smileys"],["😟","worried","smileys"],["🙁","frown sad","smileys"],["☹️","sad frown","smileys"],["😮","surprised open mouth","smileys"],["😲","astonished","smileys"],["🥺","pleading begging puppy eyes","smileys"],["😢","cry sad tear","smileys"],["😭","sob cry loudly","smileys"],["😱","scream horror fear","smileys"],["😡","angry red pouting","smileys"],["😠","angry mad","smileys"],["🤬","cursing swear","smileys"],["😈","devil evil smile","smileys"],["👿","devil angry evil","smileys"],["💀","skull death","smileys"],["☠️","skull crossbones","smileys"],["💩","poop","smileys"],["🤡","clown","smileys"],["👻","ghost boo","smileys"],["👽","alien ufo","smileys"],["🤖","robot","smileys"],["👋","wave hello hi hand","people"],["🤚","raised back hand","people"],["✋","raised hand stop","people"],["🖖","vulcan salute spock","people"],["👌","ok perfect fine","people"],["✌️","peace victory fingers","people"],["🤞","fingers crossed luck","people"],["🤟","love you gesture","people"],["🤘","sign of horns rock","people"],["🤙","call me hand","people"],["👈","point left","people"],["👉","point right","people"],["👆","point up","people"],["👇","point down","people"],["☝️","index pointing up","people"],["👍","thumbs up like good","people"],["👎","thumbs down dislike bad","people"],["✊","raised fist punch","people"],["👊","oncoming fist punch","people"],["👏","clap applause","people"],["🙌","celebrate raise hands","people"],["🤝","handshake deal","people"],["🙏","pray hope please thanks","people"],["💅","nail polish","people"],["💪","flexed bicep strong muscle","people"],["👀","eyes look see","people"],["👁️","eye","people"],["👅","tongue","people"],["👶","baby","people"],["🧒","child","people"],["👦","boy","people"],["👧","girl","people"],["🧑","person adult","people"],["👨","man","people"],["👩","woman","people"],["🧔","beard man","people"],["🧓","older person","people"],["👴","old man","people"],["👵","old woman","people"],["❤️","heart love red","people"],["🧡","orange heart love","people"],["💛","yellow heart love","people"],["💚","green heart love","people"],["💙","blue heart love","people"],["💜","purple heart love","people"],["🖤","black heart","people"],["🤍","white heart","people"],["🤎","brown heart","people"],["💔","broken heart","people"],["❣️","exclamation heart","people"],["💕","two hearts love","people"],["💞","revolving hearts","people"],["💓","beating heart","people"],["💗","growing heart","people"],["💖","sparkling heart","people"],["💘","heart arrow","people"],["💝","heart ribbon","people"],["💬","speech bubble comment chat","people"],["💭","thought bubble","people"],["💯","100 hundred percent perfect","people"],["💢","anger symbol mad","people"],["💤","zzz sleep","people"],["🐶","dog puppy","animals"],["🐱","cat kitten","animals"],["🐭","mouse","animals"],["🐹","hamster","animals"],["🐰","rabbit bunny","animals"],["🦊","fox","animals"],["🐻","bear","animals"],["🐼","panda","animals"],["🐨","koala","animals"],["🐯","tiger","animals"],["🦁","lion","animals"],["🐮","cow","animals"],["🐷","pig","animals"],["🐸","frog","animals"],["🐵","monkey","animals"],["🙈","see no evil monkey","animals"],["🙉","hear no evil monkey","animals"],["🙊","speak no evil monkey","animals"],["🐔","chicken hen","animals"],["🐧","penguin","animals"],["🐦","bird","animals"],["🦆","duck","animals"],["🦅","eagle","animals"],["🦉","owl","animals"],["🦇","bat","animals"],["🐺","wolf","animals"],["🐴","horse","animals"],["🦄","unicorn","animals"],["🐝","bee","animals"],["🦋","butterfly","animals"],["🐌","snail","animals"],["🐞","ladybug","animals"],["🐢","turtle","animals"],["🐍","snake","animals"],["🦎","lizard","animals"],["🐊","crocodile","animals"],["🐟","fish","animals"],["🐠","tropical fish","animals"],["🦈","shark","animals"],["🐬","dolphin","animals"],["🐳","whale","animals"],["🐙","octopus","animals"],["🦑","squid","animals"],["🦀","crab","animals"],["🌸","cherry blossom flower","animals"],["🌺","hibiscus flower","animals"],["🌻","sunflower","animals"],["🌹","rose flower","animals"],["🌷","tulip flower","animals"],["🍀","four leaf clover luck","animals"],["🌿","herb leaf green","animals"],["🌱","seedling sprout","animals"],["🌲","evergreen tree pine","animals"],["🌳","deciduous tree","animals"],["🌴","palm tree","animals"],["🍄","mushroom","animals"],["🌾","sheaf wheat","animals"],["🐾","paw prints animal","animals"],["🍎","apple red","food"],["🍊","orange tangerine","food"],["🍋","lemon yellow","food"],["🍇","grapes","food"],["🍓","strawberry","food"],["🫐","blueberry","food"],["🍒","cherry","food"],["🍑","peach","food"],["🥭","mango","food"],["🍍","pineapple","food"],["🥥","coconut","food"],["🥝","kiwi","food"],["🍅","tomato","food"],["🥑","avocado","food"],["🍆","eggplant aubergine","food"],["🥕","carrot","food"],["🌽","corn","food"],["🥦","broccoli","food"],["🥬","leafy green","food"],["🧄","garlic","food"],["🥜","peanut nut","food"],["🍞","bread loaf","food"],["🥐","croissant","food"],["🧀","cheese","food"],["🍳","egg fry cooking","food"],["🥚","egg","food"],["🥞","pancake","food"],["🧇","waffle","food"],["🥓","bacon","food"],["🥩","meat steak","food"],["🍗","chicken leg","food"],["🌭","hotdog","food"],["🍔","burger hamburger","food"],["🍟","fries french","food"],["🍕","pizza","food"],["🌮","taco","food"],["🌯","burrito wrap","food"],["🍜","noodles ramen","food"],["🍝","spaghetti pasta","food"],["🍣","sushi","food"],["🍱","bento box","food"],["🍦","ice cream soft serve","food"],["🍩","donut","food"],["🍪","cookie","food"],["🎂","birthday cake","food"],["🍰","cake slice","food"],["🧁","cupcake","food"],["🍫","chocolate","food"],["🍬","candy","food"],["🍭","lollipop","food"],["☕","coffee hot","food"],["🍵","tea hot","food"],["🧋","bubble tea boba","food"],["🥤","cup straw drink","food"],["🍷","wine red","food"],["🍸","cocktail martini","food"],["🍺","beer mug","food"],["🍻","clinking beer mugs","food"],["🥂","champagne toast celebrate","food"],["🧃","juice box","food"],["🧊","ice cube","food"],["🚀","rocket space","travel"],["🛸","ufo flying saucer","travel"],["✈️","airplane plane fly","travel"],["🚁","helicopter","travel"],["🚂","train locomotive","travel"],["🚄","bullet train fast","travel"],["🚇","subway metro","travel"],["🚌","bus","travel"],["🚑","ambulance","travel"],["🚒","fire truck","travel"],["🚓","police car","travel"],["🚕","taxi cab","travel"],["🚗","car automobile red","travel"],["🚙","suv car","travel"],["🚚","truck delivery","travel"],["🚜","tractor farm","travel"],["🏎️","racing car fast","travel"],["🏍️","motorcycle","travel"],["🚲","bicycle bike","travel"],["🛴","scooter kick","travel"],["⛵","sailboat boat","travel"],["🚢","ship cruise","travel"],["🏠","house home","travel"],["🏢","office building","travel"],["🏥","hospital","travel"],["🏦","bank","travel"],["🏪","store shop convenience","travel"],["🏫","school","travel"],["🏰","castle european","travel"],["🏯","japanese castle","travel"],["🗼","tokyo tower","travel"],["🗽","statue liberty new york","travel"],["⛪","church","travel"],["🕌","mosque","travel"],["⛩️","shinto shrine","travel"],["⛲","fountain","travel"],["⛺","tent camping","travel"],["🌁","fog foggy bridge","travel"],["🌃","night city stars","travel"],["🏙️","cityscape city buildings","travel"],["🌅","sunrise morning","travel"],["🌈","rainbow colorful","travel"],["⛰️","mountain","travel"],["🏔️","snow mountain","travel"],["🗻","mount fuji","travel"],["🏕️","camping tent","travel"],["🗺️","world map","travel"],["🧭","compass navigation","travel"],["🌍","earth europe africa globe","travel"],["🌎","earth americas globe","travel"],["🌏","earth asia globe","travel"],["🌐","globe internet web","travel"],["💎","diamond gem jewel","objects"],["💍","ring engagement","objects"],["👑","crown royal king queen","objects"],["🎩","top hat magic","objects"],["💼","briefcase work business","objects"],["👜","handbag purse","objects"],["🎒","backpack bag school","objects"],["👓","glasses eyewear","objects"],["🕶️","sunglasses cool","objects"],["💡","light bulb idea","objects"],["🔦","flashlight torch","objects"],["🕯️","candle light","objects"],["🔋","battery charge","objects"],["💻","laptop computer","objects"],["🖥️","desktop monitor computer","objects"],["📱","phone mobile cell","objects"],["⌨️","keyboard type","objects"],["🖱️","mouse computer click","objects"],["📺","television tv","objects"],["📷","camera photo","objects"],["📹","video camera","objects"],["🎥","movie camera film","objects"],["☎️","telephone phone","objects"],["⏰","alarm clock wake","objects"],["⌚","watch time","objects"],["🔑","key","objects"],["🗝️","old key","objects"],["🔒","lock closed","objects"],["🔓","unlock open","objects"],["🔨","hammer tool","objects"],["🔧","wrench tool","objects"],["🔩","bolt nut","objects"],["⚙️","gear setting","objects"],["🧲","magnet attract","objects"],["📚","books stack library","objects"],["📖","book open read","objects"],["📝","memo write note","objects"],["✏️","pencil write edit","objects"],["📌","pushpin tack","objects"],["📎","paperclip attach","objects"],["📊","bar chart graph","objects"],["📈","chart up growth trend","objects"],["📉","chart down loss decline","objects"],["📅","calendar date","objects"],["📦","package box","objects"],["📫","mailbox closed","objects"],["📧","email envelope","objects"],["🎁","gift present","objects"],["🎀","ribbon bow","objects"],["🎉","party celebrate confetti","objects"],["🎊","confetti celebrate","objects"],["🔮","crystal ball magic fortune","objects"],["🪄","magic wand","objects"],["🎯","target bullseye dart","objects"],["🎲","dice game board","objects"],["🎮","video game controller","objects"],["🎭","theater masks drama","objects"],["🎨","art palette paint","objects"],["🎬","clapper film movie","objects"],["🎤","microphone sing karaoke","objects"],["🎧","headphones music listen","objects"],["🎵","music note","objects"],["🎶","music notes","objects"],["🎸","guitar electric","objects"],["🎹","piano keyboard music","objects"],["🥁","drum percussion","objects"],["🎷","saxophone jazz","objects"],["🎺","trumpet","objects"],["🎻","violin","objects"],["⚽","soccer ball football","objects"],["🏀","basketball","objects"],["🏈","american football","objects"],["⚾","baseball","objects"],["🎾","tennis","objects"],["🏐","volleyball","objects"],["🏆","trophy winner award","objects"],["🥇","gold medal first","objects"],["🏅","sports medal","objects"],["✅","check green done success","symbols"],["❌","cross x no cancel","symbols"],["⭕","circle red","symbols"],["⛔","no entry stop","symbols"],["🚫","prohibited no banned","symbols"],["⚠️","warning caution danger","symbols"],["❗","exclamation red important","symbols"],["❓","question mark","symbols"],["‼️","double exclamation","symbols"],["💯","100 hundred percent perfect","symbols"],["🔴","red circle dot","symbols"],["🟠","orange circle","symbols"],["🟡","yellow circle","symbols"],["🟢","green circle","symbols"],["🔵","blue circle","symbols"],["🟣","purple circle","symbols"],["⚫","black circle","symbols"],["⚪","white circle","symbols"],["🟤","brown circle","symbols"],["🔺","red triangle up","symbols"],["🔻","red triangle down","symbols"],["🔷","blue diamond large","symbols"],["🔶","orange diamond large","symbols"],["🔹","blue diamond small","symbols"],["🔸","orange diamond small","symbols"],["⭐","star yellow","symbols"],["🌟","glowing star shine","symbols"],["✨","sparkles shine","symbols"],["💫","dizzy star spin","symbols"],["⚡","lightning bolt energy power","symbols"],["🔥","fire hot flame","symbols"],["💥","explosion boom","symbols"],["❄️","snowflake cold ice winter","symbols"],["🌊","wave water ocean sea","symbols"],["💨","wind blow dash","symbols"],["🌀","cyclone tornado spiral","symbols"],["♻️","recycle loop green","symbols"],["✔️","check tick done","symbols"],["➕","plus add","symbols"],["➖","minus subtract","symbols"],["➗","divide division","symbols"],["✖️","multiply times cross","symbols"],["▶️","play button right","symbols"],["⏸️","pause","symbols"],["⏹️","stop square","symbols"],["⏩","fast forward","symbols"],["⏪","rewind fast backward","symbols"],["🔔","bell notification","symbols"],["🔕","bell slash mute","symbols"],["🔊","speaker volume high","symbols"],["🔇","mute silent no sound","symbols"],["📢","loudspeaker announcement","symbols"],["📣","megaphone cheer","symbols"],["🏳️","white flag","symbols"],["🏴","black flag","symbols"],["🚩","red flag","symbols"],["🏁","checkered flag finish race","symbols"],["🆕","new badge","symbols"],["🆓","free badge","symbols"],["🆒","cool badge","symbols"],["🔝","top arrow","symbols"],["🔙","back arrow","symbols"],["ℹ️","information info","symbols"],["📍","pin location map","symbols"],["🔗","link chain","symbols"],["©️","copyright","symbols"],["®️","registered trademark","symbols"],["™️","trademark","symbols"],["#️⃣","hash number","symbols"],["0️⃣","zero number","symbols"],["1️⃣","one number","symbols"],["2️⃣","two number","symbols"],["3️⃣","three number","symbols"],["4️⃣","four number","symbols"],["5️⃣","five number","symbols"]];class is{constructor(t){this.context=t,this._dialog=null,this._disposers=[],this._savedRange=null,this._activeCat="all"}initialize(){return this}destroy(){this._disposers.forEach(t=>t()),this._disposers=[],this._dialog&&this._dialog.parentNode&&this._dialog.parentNode.removeChild(this._dialog),this._dialog=null}show(){this._dialog||(this._dialog=this._buildDialog(),document.body.appendChild(this._dialog)),Y(t=>{this._savedRange=t}),this._activeCat="all",this._searchInput.value="",this._updateCatTabs(),this._filterEmojis("","all"),this._open()}_buildDialog(){const t=c("div",{class:"an-dialog-overlay",role:"dialog","aria-modal":"true","aria-label":"Insert emoji"}),e=c("div",{class:"an-dialog-box an-emoji-box"}),i=c("div",{class:"an-icon-title-row"}),s=c("h3",{class:"an-dialog-title"});s.textContent="Insert Emoji";const o=c("button",{type:"button",class:"an-icon-close","aria-label":"Close"});o.innerHTML="×",i.append(s,o);const a=c("input",{type:"search",class:"an-input an-icon-search",placeholder:"Search emojis…",autocomplete:"off"});this._searchInput=a;const l=c("div",{class:"an-icon-cats"}),r=c("button",{type:"button",class:"an-icon-cat active","data-cat":"all"});r.textContent="All",l.appendChild(r),ts.forEach(({id:v,label:y})=>{const x=c("button",{type:"button",class:"an-icon-cat","data-cat":v});x.textContent=y,l.appendChild(x)}),this._catBar=l;const h=c("div",{class:"an-emoji-grid"});es.forEach(([v,y,x])=>{const b=c("button",{type:"button",class:"an-emoji-cell","data-char":v,"data-keywords":y,"data-cat":x,title:y.split(" ").slice(0,2).join(" ")});b.textContent=v,h.appendChild(b)}),this._grid=h;const u=c("div",{class:"an-dialog-actions"}),m=c("button",{type:"button",class:"an-btn"});m.textContent="Cancel",u.appendChild(m),e.append(i,a,l,h,u),t.appendChild(e);const g=d(o,"click",()=>this._close()),w=d(m,"click",()=>this._close()),f=d(t,"click",v=>{v.target===t&&this._close()}),_=d(a,"input",()=>this._filterEmojis(a.value,this._activeCat)),k=d(l,"click",v=>{const y=v.target.closest("[data-cat]");y&&(this._activeCat=y.dataset.cat,this._updateCatTabs(),this._filterEmojis(this._searchInput.value,this._activeCat))}),C=d(h,"click",v=>{const y=v.target.closest(".an-emoji-cell");y&&this._onEmojiClick(y.dataset.char)});return this._disposers.push(g,w,f,_,k,C),t}_updateCatTabs(){this._catBar.querySelectorAll(".an-icon-cat").forEach(t=>{t.classList.toggle("active",t.dataset.cat===this._activeCat)})}_filterEmojis(t,e){const i=(t||"").trim().toLowerCase();let s=0;this._grid.querySelectorAll(".an-emoji-cell").forEach(a=>{const l=!e||e==="all"||a.dataset.cat===e,r=!i||a.dataset.keywords.includes(i)||a.dataset.char===i,h=l&&r;a.style.display=h?"":"none",h&&s++});let o=this._grid.querySelector(".an-icon-empty");o||(o=c("div",{class:"an-icon-empty"}),o.textContent="No emojis found",this._grid.appendChild(o)),o.style.display=s>0?"none":""}_onEmojiClick(t){const e=this._savedRange,i=this.context.layoutInfo.editable;e&&e.select();const s=window.getSelection();let o=s&&s.rangeCount>0?s.getRangeAt(0):null;o||(o=document.createRange(),o.selectNodeContents(i),o.collapse(!1)),o.deleteContents();const a=document.createTextNode(t);o.insertNode(a),o.setStartAfter(a),o.collapse(!0),s&&(s.removeAllRanges(),s.addRange(o)),this._close(),i.focus(),this.context.invoke("editor.afterCommand")}_open(){this._dialog&&(this._dialog.style.display="flex",this._removeTrap=O(this._dialog,()=>this._close()),setTimeout(()=>this._searchInput&&this._searchInput.focus(),50))}_close(){this._dialog&&(this._dialog.style.display="none"),this._removeTrap&&(this._removeTrap(),this._removeTrap=null),this._savedRange=null}}const ss=[{id:"popular",label:"Popular"},{id:"interface",label:"Interface"},{id:"navigation",label:"Navigation"},{id:"media",label:"Media"},{id:"communication",label:"Communication"},{id:"files",label:"Files"},{id:"people",label:"People"},{id:"objects",label:"Objects"}],ns=[["house","popular"],["star","popular"],["heart","popular"],["check","popular"],["xmark","popular"],["plus","popular"],["minus","popular"],["magnifying-glass","popular"],["gear","popular"],["bell","popular"],["user","popular"],["envelope","popular"],["phone","popular"],["calendar","popular"],["clock","popular"],["lock","popular"],["eye","popular"],["eye-slash","popular"],["trash","popular"],["pen","popular"],["bookmark","popular"],["flag","popular"],["thumbs-up","popular"],["thumbs-down","popular"],["circle-info","popular"],["triangle-exclamation","popular"],["circle-check","popular"],["circle-xmark","popular"],["share","popular"],["download","popular"],["upload","popular"],["tag","popular"],["bars","interface"],["ellipsis","interface"],["ellipsis-vertical","interface"],["list","interface"],["table-cells","interface"],["table-list","interface"],["grip","interface"],["filter","interface"],["sort","interface"],["arrows-rotate","interface"],["rotate","interface"],["rotate-left","interface"],["rotate-right","interface"],["copy","interface"],["floppy-disk","interface"],["print","interface"],["link","interface"],["code","interface"],["expand","interface"],["compress","interface"],["cloud","interface"],["lock-open","interface"],["key","interface"],["shield","interface"],["shield-halved","interface"],["sliders","interface"],["toggle-on","interface"],["square-check","interface"],["circle-plus","interface"],["circle-minus","interface"],["arrow-right","navigation"],["arrow-left","navigation"],["arrow-up","navigation"],["arrow-down","navigation"],["chevron-right","navigation"],["chevron-left","navigation"],["chevron-up","navigation"],["chevron-down","navigation"],["angle-right","navigation"],["angle-left","navigation"],["angle-up","navigation"],["angle-down","navigation"],["angles-right","navigation"],["angles-left","navigation"],["location-dot","navigation"],["compass","navigation"],["map","navigation"],["map-pin","navigation"],["route","navigation"],["circle-arrow-right","navigation"],["circle-arrow-left","navigation"],["arrow-trend-up","navigation"],["arrow-trend-down","navigation"],["right-from-bracket","navigation"],["right-to-bracket","navigation"],["play","media"],["pause","media"],["stop","media"],["forward","media"],["backward","media"],["forward-step","media"],["backward-step","media"],["volume-high","media"],["volume-low","media"],["volume-xmark","media"],["volume-off","media"],["music","media"],["headphones","media"],["microphone","media"],["microphone-slash","media"],["film","media"],["camera","media"],["camera-rotate","media"],["video","media"],["image","media"],["images","media"],["photo-film","media"],["podcast","media"],["radio","media"],["comment","communication"],["comments","communication"],["comment-dots","communication"],["message","communication"],["paper-plane","communication"],["reply","communication"],["reply-all","communication"],["at","communication"],["hashtag","communication"],["wifi","communication"],["signal","communication"],["rss","communication"],["share-nodes","communication"],["inbox","communication"],["phone-volume","communication"],["mobile","communication"],["mobile-screen","communication"],["laptop","communication"],["desktop","communication"],["tower-broadcast","communication"],["file","files"],["file-lines","files"],["folder","files"],["folder-open","files"],["folder-plus","files"],["folder-minus","files"],["file-image","files"],["file-pdf","files"],["file-code","files"],["file-zipper","files"],["file-audio","files"],["file-video","files"],["file-arrow-up","files"],["file-arrow-down","files"],["database","files"],["box","files"],["box-open","files"],["hard-drive","files"],["server","files"],["user","people"],["users","people"],["user-group","people"],["user-plus","people"],["user-minus","people"],["user-check","people"],["user-xmark","people"],["user-tie","people"],["user-shield","people"],["user-secret","people"],["person","people"],["person-running","people"],["person-walking","people"],["child","people"],["handshake","people"],["hand","people"],["hands-holding","people"],["people-group","people"],["pencil","objects"],["paintbrush","objects"],["eraser","objects"],["scissors","objects"],["wrench","objects"],["screwdriver","objects"],["hammer","objects"],["toolbox","objects"],["graduation-cap","objects"],["book","objects"],["book-open","objects"],["glasses","objects"],["microscope","objects"],["flask","objects"],["stethoscope","objects"],["hospital","objects"],["building","objects"],["city","objects"],["car","objects"],["truck","objects"],["plane","objects"],["train","objects"],["bicycle","objects"],["bus","objects"],["rocket","objects"],["briefcase","objects"],["cart-shopping","objects"],["bag-shopping","objects"],["credit-card","objects"],["money-bill","objects"],["chart-bar","objects"],["chart-line","objects"],["chart-pie","objects"],["bolt","objects"],["sun","objects"],["moon","objects"],["snowflake","objects"],["fire","objects"],["droplet","objects"],["leaf","objects"],["tree","objects"],["earth-americas","objects"],["globe","objects"],["award","objects"],["trophy","objects"],["gift","objects"],["puzzle-piece","objects"]];class os{constructor(t){this.context=t,this._dialog=null,this._disposers=[],this._savedRange=null,this._selectedIcon=null,this._activeCat="all"}initialize(){return this._ensureFontAwesome(),this}_ensureFontAwesome(){if(document.getElementById("an-fontawesome-css"))return;const t=Array.from(document.querySelectorAll('link[rel="stylesheet"]')).map(i=>i.href||"").join(" ");if(/fontawesome|font-awesome/.test(t)||document.querySelector(".fa-solid, .fas, .far, .fab"))return;const e=document.createElement("link");e.id="an-fontawesome-css",e.rel="stylesheet",e.href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css",e.crossOrigin="anonymous",e.referrerPolicy="no-referrer",document.head.appendChild(e)}destroy(){this._disposers.forEach(t=>t()),this._disposers=[],this._dialog&&this._dialog.parentNode&&this._dialog.parentNode.removeChild(this._dialog),this._dialog=null}show(){this._dialog||(this._dialog=this._buildDialog(),document.body.appendChild(this._dialog)),Y(t=>{this._savedRange=t}),this._selectedIcon=null,this._activeCat="all",this._searchInput.value="",this._updateCatTabs(),this._filterIcons("","all"),this._updatePreview(null),this._open()}_buildDialog(){const t=c("div",{class:"an-dialog-overlay",role:"dialog","aria-modal":"true","aria-label":"Insert FA icon"}),e=c("div",{class:"an-dialog-box an-icon-box"}),i=c("div",{class:"an-icon-title-row"}),s=c("h3",{class:"an-dialog-title"});s.textContent="Insert FA Icon";const o=c("button",{type:"button",class:"an-icon-close","aria-label":"Close"});o.innerHTML="×",i.append(s,o);const a=c("input",{type:"search",class:"an-input an-icon-search",placeholder:"Search icons…",autocomplete:"off"});this._searchInput=a;const l=c("div",{class:"an-icon-cats"}),r=c("button",{type:"button",class:"an-icon-cat active","data-cat":"all"});r.textContent="All",l.appendChild(r),ss.forEach(({id:R,label:j})=>{const H=c("button",{type:"button",class:"an-icon-cat","data-cat":R});H.textContent=j,l.appendChild(H)}),this._catBar=l;const h=c("div",{class:"an-icon-grid"});ns.forEach(([R,j])=>{const H=c("button",{type:"button",class:"an-icon-cell","data-name":R,"data-cat":j,title:R}),Es=c("i",{class:"fa-solid fa-"+R,"aria-hidden":"true"}),je=c("span");je.textContent=R,H.append(Es,je),h.appendChild(H)}),this._grid=h;const u=c("div",{class:"an-icon-options"}),m=c("label",{class:"an-label"});m.textContent="Style";const g=c("select",{class:"an-input an-icon-option-select"});[["fa-solid","Solid"],["fa-regular","Regular"],["fa-light","Light (Pro)"]].forEach(([R,j])=>{const H=c("option",{value:R});H.textContent=j,g.appendChild(H)}),g.value="fa-solid",this._styleSelect=g;const w=c("label",{class:"an-label"});w.textContent="Size";const f=c("select",{class:"an-input an-icon-option-select"});[["","Inherit"],["0.75em","0.75em"],["1em","1em"],["1.25em","1.25em"],["1.5em","1.5em"],["2em","2em"],["3em","3em"]].forEach(([R,j])=>{const H=c("option",{value:R});R==="1em"&&(H.selected=!0),H.textContent=j,f.appendChild(H)}),this._sizeSelect=f;const _=c("label",{class:"an-label"});_.textContent="Color";const k=c("input",{type:"color",class:"an-icon-color",value:"#000000"});this._colorInput=k;const C=c("label",{class:"an-label an-label-inline an-icon-use-color"}),v=c("input",{type:"checkbox",checked:""});this._useColorCb=v,C.append(v,document.createTextNode(" Use color")),u.append(m,g,w,f,_,k,C);const y=c("div",{class:"an-icon-preview"}),x=c("span",{class:"an-icon-preview-hint"});x.textContent="Select an icon",y.appendChild(x),this._preview=y;const b=c("div",{class:"an-dialog-actions"}),T=c("button",{type:"button",class:"an-btn an-btn-primary",disabled:""});T.textContent="Insert FA Icon";const E=c("button",{type:"button",class:"an-btn"});E.textContent="Cancel",b.append(T,E),this._insertBtn=T,e.append(i,a,l,h,u,y,b),t.appendChild(e);const z=d(o,"click",()=>this._close()),P=d(E,"click",()=>this._close()),Z=d(T,"click",()=>this._onInsert()),tt=d(t,"click",R=>{R.target===t&&this._close()}),et=d(a,"input",()=>this._filterIcons(a.value,this._activeCat)),B=d(l,"click",R=>{const j=R.target.closest("[data-cat]");j&&(this._activeCat=j.dataset.cat,this._updateCatTabs(),this._filterIcons(this._searchInput.value,this._activeCat))}),L=d(h,"click",R=>{const j=R.target.closest(".an-icon-cell");j&&this._selectIcon(j.dataset.name)}),Cs=d(g,"change",()=>this._updatePreview(this._selectedIcon)),Ts=d(f,"change",()=>this._updatePreview(this._selectedIcon)),Is=d(k,"input",()=>this._updatePreview(this._selectedIcon)),Ss=d(v,"change",()=>this._updatePreview(this._selectedIcon));return this._disposers.push(z,P,Z,tt,et,B,L,Cs,Ts,Is,Ss),t}_updateCatTabs(){this._catBar.querySelectorAll(".an-icon-cat").forEach(t=>{t.classList.toggle("active",t.dataset.cat===this._activeCat)})}_filterIcons(t,e){const i=(t||"").trim().toLowerCase();let s=0;this._grid.querySelectorAll(".an-icon-cell").forEach(a=>{const l=a.dataset.name,r=a.dataset.cat,h=!e||e==="all"||r===e,u=!i||l.includes(i),m=h&&u;a.style.display=m?"":"none",m&&s++});let o=this._grid.querySelector(".an-icon-empty");o||(o=c("div",{class:"an-icon-empty"}),o.textContent="No icons found",this._grid.appendChild(o)),o.style.display=s>0?"none":""}_selectIcon(t){this._selectedIcon=t,this._grid.querySelectorAll(".an-icon-cell").forEach(e=>{e.classList.toggle("active",e.dataset.name===t)}),this._insertBtn.removeAttribute("disabled"),this._updatePreview(t)}_updatePreview(t){if(!this._preview)return;if(!t){this._preview.innerHTML='<span class="an-icon-preview-hint">Select an icon</span>';return}const e=this._styleSelect&&this._styleSelect.value||"fa-solid",i=this._sizeSelect&&this._sizeSelect.value||"1em",o=(this._useColorCb?this._useColorCb.checked:!1)&&this._colorInput?this._colorInput.value:"",a=[`font-size:${i}`,o?`color:${o}`:""].filter(Boolean).join(";");this._preview.innerHTML=`<i class="${e} fa-${t}" aria-hidden="true"${a?` style="${a}"`:""}></i><div class="an-icon-preview-name">${e} fa-${t}</div>`}_onInsert(){if(!this._selectedIcon)return;const t=this._styleSelect&&this._styleSelect.value||"fa-solid",e=this._sizeSelect&&this._sizeSelect.value||"",s=(this._useColorCb?this._useColorCb.checked:!1)&&this._colorInput?this._colorInput.value:"",o=[e?`font-size:${e}`:"",s?`color:${s}`:""].filter(Boolean),a=document.createElement("i");a.className=`${t} fa-${this._selectedIcon}`,a.setAttribute("aria-hidden","true"),o.length&&a.setAttribute("style",o.join(";"));const l=this._savedRange,r=this.context.layoutInfo.editable;l&&l.select();const h=window.getSelection();let u=h&&h.rangeCount>0?h.getRangeAt(0):null;u||(u=document.createRange(),u.selectNodeContents(r),u.collapse(!1)),u.deleteContents(),u.insertNode(a);const m=document.createTextNode("");a.parentNode.insertBefore(m,a.nextSibling),u.setStart(m,1),u.collapse(!0),h&&(h.removeAllRanges(),h.addRange(u)),this._close(),r.focus(),this.context.invoke("editor.afterCommand")}_open(){this._dialog&&(this._dialog.style.display="flex",this._removeTrap=O(this._dialog,()=>this._close()),setTimeout(()=>this._searchInput&&this._searchInput.focus(),50))}_close(){this._dialog&&(this._dialog.style.display="none"),this._removeTrap&&(this._removeTrap(),this._removeTrap=null),this._savedRange=null,this._selectedIcon=null}}const A={undo:'<svg xmlns="http://www.w3.org/2000/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="M3 7v6h6"/><path d="M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13"/></svg>',redo:'<svg xmlns="http://www.w3.org/2000/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="M21 7v6h-6"/><path d="M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3L21 13"/></svg>',cut:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="20" r="3"/><circle cx="6" cy="4" r="3"/><line x1="19" y1="5" x2="6" y2="19"/><line x1="19" y1="19" x2="13.5" y2="13.5"/></svg>',copy:'<svg xmlns="http://www.w3.org/2000/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="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>',paste:'<svg xmlns="http://www.w3.org/2000/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="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><rect x="8" y="2" width="8" height="4" rx="1"/></svg>',bold:'<svg xmlns="http://www.w3.org/2000/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="M6 4h8a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"/><path d="M6 12h9a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"/></svg>',italic:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="4" x2="10" y2="4"/><line x1="14" y1="20" x2="5" y2="20"/><line x1="15" y1="4" x2="9" y2="20"/></svg>',underline:'<svg xmlns="http://www.w3.org/2000/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="M6 3v7a6 6 0 0 0 6 6 6 6 0 0 0 6-6V3"/><line x1="4" y1="21" x2="20" y2="21"/></svg>',link:'<svg xmlns="http://www.w3.org/2000/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="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>',image:'<svg xmlns="http://www.w3.org/2000/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="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>',video:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2"/></svg>',copyFormat:'<svg xmlns="http://www.w3.org/2000/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="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>',pasteFormat:'<svg xmlns="http://www.w3.org/2000/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="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><rect x="8" y="2" width="8" height="4" rx="1"/><path d="m9 14 2 2 4-4"/></svg>',removeFormat:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21"/><path d="M22 21H7"/><path d="m5 11 9 9"/></svg>',table:'<svg xmlns="http://www.w3.org/2000/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="3" width="18" height="18" rx="1"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="3" y1="15" x2="21" y2="15"/><line x1="9" y1="3" x2="9" y2="21"/><line x1="15" y1="3" x2="15" y2="21"/></svg>'},as=[{name:"undo",label:"Undo",icon:A.undo,action:n=>n.invoke("editor.undo")},{name:"redo",label:"Redo",icon:A.redo,action:n=>n.invoke("editor.redo")},{separator:!0},{name:"cut",label:"Cut",icon:A.cut,action:()=>document.execCommand("cut")},{name:"copy",label:"Copy",icon:A.copy,action:()=>document.execCommand("copy")},{name:"paste",label:"Paste",icon:A.paste,action:n=>{if(!navigator.clipboard)return;const t=n.layoutInfo&&n.layoutInfo.editable;if(!t)return;const e=(i,s)=>{if(t.focus(),i){const o=W(i);document.execCommand("insertHTML",!1,o)}else s&&document.execCommand("insertText",!1,s);n.invoke("editor.afterCommand")};typeof navigator.clipboard.read=="function"?navigator.clipboard.read().then(i=>{for(const s of i)if(s.types.includes("text/html")){s.getType("text/html").then(o=>o.text()).then(o=>e(o,null));return}navigator.clipboard.readText().then(s=>e(null,s)).catch(()=>{})}).catch(()=>{navigator.clipboard.readText().then(i=>e(null,i)).catch(()=>{})}):typeof navigator.clipboard.readText=="function"&&navigator.clipboard.readText().then(i=>e(null,i)).catch(()=>{})}},{separator:!0},{name:"bold",label:"Bold",icon:A.bold,action:n=>n.invoke("editor.bold")},{name:"italic",label:"Italic",icon:A.italic,action:n=>n.invoke("editor.italic")},{name:"underline",label:"Underline",icon:A.underline,action:n=>n.invoke("editor.underline")},{separator:!0},{name:"copyFormat",label:"Copy Format",icon:A.copyFormat,action:n=>n.invoke("contextMenu.copyFormat")},{name:"pasteFormat",label:"Paste Format",icon:A.pasteFormat,action:n=>n.invoke("contextMenu.pasteFormat"),disabled:n=>!n.invoke("contextMenu.hasCopiedFormat")},{name:"removeFormat",label:"Remove Format",icon:A.removeFormat,action:n=>n.invoke("contextMenu.removeFormat")},{separator:!0},{name:"link",label:"Insert Link",icon:A.link,action:n=>n.invoke("linkDialog.show")},{name:"image",label:"Insert Image",icon:A.image,action:n=>n.invoke("imageDialog.show")},{name:"video",label:"Insert Video",icon:A.video,action:n=>n.invoke("videoDialog.show")},{name:"table",label:"Insert Table",icon:A.table,tableGrid:!0}];class ls{constructor(t){this.context=t,this.options=t.options||{},this._items=this.options.contextMenu&&this.options.contextMenu.items||as,this.el=null,this._disposers=[],this._menuDisposers=[],this._lastX=0,this._lastY=0,this._copiedFormat=null,this._savedRange=null}initialize(){this.el=c("div",{class:"an-contextmenu",role:"menu","aria-hidden":"true"}),this.el.style.display="none",document.body.appendChild(this.el),this._renderItems(this._items);const t=this.context.layoutInfo&&this.context.layoutInfo.editable;return t&&this._disposers.push(d(t,"contextmenu",e=>this._onContextMenu(e))),this._disposers.push(d(document,"click",e=>this._maybeHide(e))),this._disposers.push(d(document,"keydown",e=>{e.key==="Escape"&&this.hide()})),this._disposers.push(d(window,"scroll",()=>this.hide(),{passive:!0})),this}destroy(){this._menuDisposers.forEach(t=>{try{t()}catch{}}),this._menuDisposers=[],this._disposers.forEach(t=>{try{t()}catch{}}),this._disposers=[],this.el&&this.el.parentNode&&this.el.parentNode.removeChild(this.el),this.el=null}_renderItems(t){this._menuDisposers.forEach(e=>e()),this._menuDisposers=[],this.el&&(this.el.innerHTML="",t.forEach(e=>{if(e.separator||e.sep){this.el.appendChild(c("div",{class:"an-context-sep"}));return}if(e.back){const o=c("button",{type:"button",class:"an-context-back"}),a=c("span",{class:"an-context-icon","aria-hidden":"true"});a.innerHTML=A.back,o.appendChild(a),o.appendChild(c("span",{class:"an-context-label"},[e.label||"Back"]));const l=d(o,"click",r=>{r.stopPropagation(),this._renderItems(e.navigate()),this._reposition()});this._menuDisposers.push(l),this.el.appendChild(o);return}if(e.navigate){const o=c("button",{type:"button",class:"an-context-item an-context-submenu","data-name":e.name||""});if(e.icon){const r=c("span",{class:"an-context-icon","aria-hidden":"true"});r.innerHTML=e.icon,o.appendChild(r)}o.appendChild(c("span",{class:"an-context-label"},[e.label||e.name]));const a=c("span",{class:"an-context-chevron","aria-hidden":"true"});a.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>',o.appendChild(a);const l=d(o,"click",r=>{r.stopPropagation(),this._renderItems(e.navigate()),this._reposition()});this._menuDisposers.push(l),this.el.appendChild(o);return}if(e.tableGrid){const l=c("div",{class:"an-context-table-wrap"}),r=c("button",{type:"button",class:"an-context-item an-context-submenu","data-name":e.name||"table"});if(e.icon){const x=c("span",{class:"an-context-icon","aria-hidden":"true"});x.innerHTML=e.icon,r.appendChild(x)}r.appendChild(c("span",{class:"an-context-label"},[e.label||"Insert Table"]));const h=c("span",{class:"an-context-chevron","aria-hidden":"true"});h.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>',r.appendChild(h);const u=c("div",{class:"an-context-table-grid-panel"});u.style.display="none";const m=c("div",{class:"an-table-grid"});m.style.gridTemplateColumns="repeat(8, 16px)";const g=c("div",{class:"an-table-label"});g.textContent="Insert Table";const w=[];for(let x=1;x<=8;x++)for(let b=1;b<=8;b++){const T=c("div",{class:"an-table-cell","data-row":String(x),"data-col":String(b)});T.style.width="16px",T.style.height="16px",w.push(T),m.appendChild(T)}const f=(x,b)=>{w.forEach(T=>{T.classList.toggle("active",+T.dataset.row<=x&&+T.dataset.col<=b)}),g.textContent=x&&b?`${b} × ${x}`:"Insert Table"};u.appendChild(m),u.appendChild(g);let _=!1;const k=d(r,"click",x=>{x.stopPropagation(),_=!_,u.style.display=_?"":"none",h.style.transform=_?"rotate(90deg)":"",this._reposition()});this._menuDisposers.push(k);const C=d(m,"mousemove",x=>{const b=x.target.closest("[data-row]");b&&f(+b.dataset.row,+b.dataset.col)}),v=d(m,"mouseleave",()=>f(0,0)),y=d(m,"click",x=>{const b=x.target.closest("[data-row]");if(!b)return;const T=+b.dataset.row,E=+b.dataset.col,z=this.context.layoutInfo&&this.context.layoutInfo.editable;if(z&&this._savedRange){z.focus();const P=window.getSelection();P.removeAllRanges(),P.addRange(this._savedRange.cloneRange())}this.hide(),this.context.invoke("editor.insertTable",E,T)});this._menuDisposers.push(C,v,y),l.appendChild(r),l.appendChild(u),this.el.appendChild(l);return}const i=c("button",{type:"button",class:"an-context-item","data-name":e.name||""});if((typeof e.disabled=="function"?e.disabled(this.context):e.disabled)&&(i.disabled=!0),e.icon){const o=c("span",{class:"an-context-icon","aria-hidden":"true"});o.innerHTML=e.icon,i.appendChild(o)}i.appendChild(c("span",{class:"an-context-label"},[e.label||e.name]));const s=d(i,"click",o=>{o.stopPropagation(),this.hide();try{e.action(this.context)}catch(a){console.error(a)}});this._menuDisposers.push(s),this.el.appendChild(i)}))}_onContextMenu(t){const e=this.context.layoutInfo&&this.context.layoutInfo.editable;if(!e||!e.contains(t.target))return;t.preventDefault(),this._lastX=t.clientX,this._lastY=t.clientY;const i=window.getSelection();this._savedRange=i&&i.rangeCount>0?i.getRangeAt(0).cloneRange():null,this._renderItems(this._items),this.showAt(t.clientX,t.clientY)}_maybeHide(t){this.el&&(this.el.contains(t.target)||this.hide())}showAt(t,e){this.el&&(this.el.style.display="block",this._reposition(t,e),this.el.setAttribute("aria-hidden","false"))}_reposition(t,e){if(!this.el)return;const i=t!==void 0?t:this._lastX,s=e!==void 0?e:this._lastY,o=this.el.getBoundingClientRect();let a=i,l=s;a+o.width>window.innerWidth&&(a=window.innerWidth-o.width-8),l+o.height>window.innerHeight&&(l=window.innerHeight-o.height-8),this.el.style.left=`${a}px`,this.el.style.top=`${l}px`}hide(){this.el&&(this.el.style.display="none",this.el.setAttribute("aria-hidden","true"))}hasCopiedFormat(){return!!this._copiedFormat}copyFormat(){const t=this._savedRange;if(!t)return;const e=this.context.layoutInfo&&this.context.layoutInfo.editable;let i=t.startContainer;if(i.nodeType===Node.TEXT_NODE&&(i=i.parentElement),!i||!e||!e.contains(i))return;const s=window.getComputedStyle(i),o=this._findExplicitStyle(i,e,"fontFamily"),a=this._findExplicitStyle(i,e,"fontSize");this._copiedFormat={bold:parseInt(s.fontWeight,10)>=700,italic:s.fontStyle==="italic"||s.fontStyle==="oblique",underline:(s.textDecorationLine||"").includes("underline"),strikethrough:(s.textDecorationLine||"").includes("line-through"),fontFamily:o,fontSize:a,color:this._isDefaultColor(s.color)?null:s.color,backgroundColor:s.backgroundColor}}_findExplicitStyle(t,e,i){let s=t;for(;s&&s!==e&&s!==document.body;){if(s.style&&s.style[i])return s.style[i];if(s.nodeName==="FONT"){if(i==="fontFamily"&&s.getAttribute("face"))return s.getAttribute("face");if(i==="fontSize"&&s.getAttribute("size"))return null}s=s.parentElement}return null}_isDefaultColor(t){return!t||t==="rgb(0, 0, 0)"||t==="rgba(0, 0, 0, 0)"||t==="transparent"}pasteFormat(){if(!this._copiedFormat||!this._savedRange)return;const t=this._copiedFormat,e=this.context.layoutInfo&&this.context.layoutInfo.editable;if(!e)return;e.focus();const i=window.getSelection();if(i.removeAllRanges(),i.addRange(this._savedRange.cloneRange()),document.execCommand("removeFormat"),t.bold&&document.execCommand("bold"),t.italic&&document.execCommand("italic"),t.underline&&document.execCommand("underline"),t.strikethrough&&document.execCommand("strikeThrough"),t.color&&document.execCommand("foreColor",!1,t.color),(o=>!o||o==="rgba(0, 0, 0, 0)"||o==="transparent")(t.backgroundColor)||document.execCommand("hiliteColor",!1,t.backgroundColor),t.fontSize){const o=`fs-${Date.now()}`;document.execCommand("fontSize",!1,"7"),e.querySelectorAll('font[size="7"]').forEach(a=>a.setAttribute("data-an-tmp",o)),e.querySelectorAll(`[data-an-tmp="${o}"]`).forEach(a=>{const l=document.createElement("span");for(l.style.fontSize=t.fontSize,a.parentNode.insertBefore(l,a);a.firstChild;)l.appendChild(a.firstChild);a.parentNode.removeChild(a)})}t.fontFamily&&document.execCommand("fontName",!1,t.fontFamily),this.context.invoke("editor.afterCommand")}removeFormat(){if(!this._savedRange)return;const t=this.context.layoutInfo&&this.context.layoutInfo.editable;if(!t)return;t.focus();const e=window.getSelection();e.removeAllRanges(),e.addRange(this._savedRange.cloneRange()),document.execCommand("removeFormat");const i=e.getRangeAt(0),s=i.commonAncestorContainer,o=s.nodeType===Node.TEXT_NODE?s.parentElement:s,a=document.createNodeIterator(o,NodeFilter.SHOW_ELEMENT);let l;for(;l=a.nextNode();)if(!(!t.contains(l)||l===t))try{i.intersectsNode(l)&&l.removeAttribute("style")}catch{}this.context.invoke("editor.afterCommand")}}const rs=[{category:"Text Formatting",items:[{keys:"Ctrl + B",action:"Bold"},{keys:"Ctrl + I",action:"Italic"},{keys:"Ctrl + U",action:"Underline"},{keys:"Ctrl + K",action:"Insert / edit link"}]},{category:"History",items:[{keys:"Ctrl + Z",action:"Undo"},{keys:"Ctrl + Y / Ctrl + Shift + Z",action:"Redo"}]},{category:"Selection & Navigation",items:[{keys:"Ctrl + A",action:"Select all content"},{keys:"Tab",action:"Indent list item / insert spaces"},{keys:"Shift + Tab",action:"Outdent list item"}]},{category:"Clipboard",items:[{keys:"Ctrl + Shift + V",action:"Paste as plain text"}]},{category:"Find & Replace",items:[{keys:"Ctrl + F",action:"Find in document"},{keys:"Ctrl + H",action:"Find & Replace"}]},{category:"Editor",items:[{keys:"Shift + ?",action:"Show this keyboard shortcuts dialog"}]}];class cs{constructor(t){this.context=t,this._dialog=null,this._closeBtn=null,this._disposers=[]}initialize(){return this._dialog=this._buildDialog(),document.body.appendChild(this._dialog),this}destroy(){this._disposers.forEach(t=>t()),this._disposers=[],this._dialog&&this._dialog.parentNode&&this._dialog.parentNode.removeChild(this._dialog),this._dialog=null}show(){this._dialog&&(this._dialog.style.display="flex",this._removeTrap=O(this._dialog,()=>this._close()),setTimeout(()=>this._closeBtn&&this._closeBtn.focus(),50))}_close(){this._dialog&&(this._dialog.style.display="none"),this._removeTrap&&(this._removeTrap(),this._removeTrap=null)}_buildDialog(){const t=c("div",{class:"an-dialog-overlay",role:"dialog","aria-modal":"true","aria-label":"Keyboard Shortcuts"}),e=c("div",{class:"an-dialog-box an-shortcuts-box"}),i=c("div",{class:"an-icon-title-row"}),s=c("h3",{class:"an-dialog-title"});s.textContent="Keyboard Shortcuts";const o=c("button",{type:"button",class:"an-icon-close","aria-label":"Close"});o.textContent="×",this._closeBtn=o,i.append(s,o),e.appendChild(i),rs.forEach(({category:r,items:h})=>{const u=c("div",{class:"an-shortcuts-cat"});u.textContent=r,e.appendChild(u);const m=c("div",{class:"an-shortcuts-table"});h.forEach(({keys:g,action:w})=>{const f=c("div",{class:"an-shortcuts-row"}),_=c("span",{class:"an-shortcuts-key"});_.textContent=g;const k=c("span",{class:"an-shortcuts-action"});k.textContent=w,f.append(_,k),m.appendChild(f)}),e.appendChild(m)}),t.appendChild(e);const a=d(o,"click",()=>this._close()),l=d(t,"click",r=>{r.target===t&&this._close()});return this._disposers.push(a,l),t}}class hs{constructor(t){this.context=t,this._dialog=null,this._findInput=null,this._replaceInput=null,this._caseCheckbox=null,this._counterEl=null,this._closeBtn=null,this._matches=[],this._currentIndex=-1,this._caseSensitive=!1,this._mode="find",this._disposers=[],this._removeTrap=null,this._focusTimer=null}initialize(){return this._dialog=this._buildDialog(),document.body.appendChild(this._dialog),this}destroy(){clearTimeout(this._focusTimer),this._focusTimer=null,this._clearHighlights(),this._disposers.forEach(t=>t()),this._disposers=[],this._dialog&&this._dialog.parentNode&&this._dialog.parentNode.removeChild(this._dialog),this._dialog=null}show(t="find"){this._mode=t,this._updateMode(),this._open(),clearTimeout(this._focusTimer),this._focusTimer=setTimeout(()=>{this._findInput&&(this._findInput.select(),this._findInput.focus())},50)}_open(){if(this._dialog){if(this._dialog.style.display==="flex"){this._findInput&&this._findInput.focus();return}this._dialog.style.display="flex",this._removeTrap&&(this._removeTrap(),this._removeTrap=null),this._removeTrap=O(this._dialog,()=>this._close())}}_close(){this._clearHighlights(),this._dialog&&(this._dialog.style.display="none"),this._removeTrap&&(this._removeTrap(),this._removeTrap=null),this.context.invoke("editor.focus")}_updateMode(){if(!this._dialog)return;const t=this._dialog.querySelector(".an-fr-replace-row"),e=this._dialog.querySelector(".an-fr-replace-actions"),i=this._dialog.querySelector(".an-dialog-title"),s=this._mode==="replace";t&&(t.style.display=s?"":"none"),e&&(e.style.display=s?"":"none"),i&&(i.textContent=s?"Find & Replace":"Find")}_buildDialog(){const t=c("div",{class:"an-dialog-overlay an-fr-dialog",role:"dialog","aria-modal":"true","aria-label":"Find and Replace"}),e=c("div",{class:"an-dialog-box"}),i=c("div",{class:"an-icon-title-row"}),s=c("h3",{class:"an-dialog-title"});s.textContent="Find";const o=c("button",{type:"button",class:"an-icon-close","aria-label":"Close"});o.textContent="×",this._closeBtn=o,i.append(s,o),e.appendChild(i);const a=c("div",{class:"an-fr-find-row"}),l=c("input",{type:"text",class:"an-input",placeholder:"Find…","aria-label":"Search text"});this._findInput=l,a.appendChild(l),e.appendChild(a);const r=c("div",{class:"an-fr-options-row"}),h=c("label",{class:"an-label an-label-inline"}),u=c("input",{type:"checkbox","aria-label":"Case sensitive"});this._caseCheckbox=u,h.append(u,document.createTextNode(" Case sensitive"));const m=c("span",{class:"an-fr-counter"});this._counterEl=m,r.append(h,m),e.appendChild(r);const g=c("div",{class:"an-dialog-actions an-fr-find-actions"}),w=c("button",{type:"button",class:"an-btn"});w.textContent="← Prev";const f=c("button",{type:"button",class:"an-btn an-btn-primary"});f.textContent="Next →",g.append(w,f),e.appendChild(g);const _=c("div",{class:"an-fr-replace-row"});_.style.display="none";const k=c("input",{type:"text",class:"an-input",placeholder:"Replace with…","aria-label":"Replace with"});this._replaceInput=k,_.appendChild(k),e.appendChild(_);const C=c("div",{class:"an-dialog-actions an-fr-replace-actions"});C.style.display="none";const v=c("button",{type:"button",class:"an-btn"});v.textContent="Replace";const y=c("button",{type:"button",class:"an-btn an-btn-primary"});y.textContent="Replace All",C.append(v,y),e.appendChild(C),t.appendChild(e);const x=d(o,"click",()=>this._close()),b=d(t,"click",L=>{L.target===t&&this._close()}),T=d(l,"input",()=>this._onSearch()),E=d(u,"change",()=>{this._caseSensitive=u.checked,this._onSearch()}),z=d(f,"click",()=>this._next()),P=d(w,"click",()=>this._prev()),Z=d(v,"click",()=>this._replace()),tt=d(y,"click",()=>this._replaceAll()),et=d(l,"keydown",L=>{L.key==="Enter"&&(L.preventDefault(),L.shiftKey?this._prev():this._next())}),B=d(k,"keydown",L=>{L.key==="Enter"&&(L.preventDefault(),this._replace())});return this._disposers.push(x,b,T,E,z,P,Z,tt,et,B),t}_onSearch(){this._clearHighlights();const t=this._findInput?this._findInput.value:"";if(!t){this._updateCounter();return}this._findAndHighlight(t),this._updateCounter()}_findAndHighlight(t){const e=this.context.layoutInfo.editable;if(!e)return;const i=this._findRawMatches(t,e);if(i.length!==0){this._currentIndex=0;for(let s=i.length-1;s>=0;s--){const{node:o,start:a,end:l}=i[s];try{const r=document.createRange();r.setStart(o,a),r.setEnd(o,l);const h=document.createElement("mark");h.className="an-highlight",r.surroundContents(h),this._matches.unshift({mark:h})}catch{this._matches.unshift({mark:null})}}this._matches=this._matches.filter(s=>s.mark),this._matches.length!==0&&this._matches[0]&&this._matches[0].mark&&(this._matches[0].mark.className="an-highlight an-highlight-current",this._matches[0].mark.scrollIntoView({block:"center",behavior:"smooth"}))}}_findRawMatches(t,e){const i=[],s=this._caseSensitive?"g":"gi",o=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(o,s),l=document.createTreeWalker(e,4);let r;for(;r=l.nextNode();){a.lastIndex=0;let h;for(;(h=a.exec(r.textContent))!==null;)i.push({node:r,start:h.index,end:h.index+h[0].length})}return i}_next(){this._matches.length!==0&&(this._currentIndex=(this._currentIndex+1)%this._matches.length,this._scrollToMatch(this._currentIndex),this._updateCounter())}_prev(){this._matches.length!==0&&(this._currentIndex=(this._currentIndex-1+this._matches.length)%this._matches.length,this._scrollToMatch(this._currentIndex),this._updateCounter())}_scrollToMatch(t){const e=this._matches[t];!e||!e.mark||(this._matches.forEach((i,s)=>{i.mark&&(i.mark.className=s===t?"an-highlight an-highlight-current":"an-highlight")}),e.mark.scrollIntoView({block:"center",behavior:"smooth"}))}_replace(){if(this._matches.length===0||this._currentIndex<0)return;const t=this._matches[this._currentIndex];if(!t||!t.mark||!t.mark.parentNode)return;const e=this._replaceInput?this._replaceInput.value:"",i=t.mark.parentNode,s=document.createTextNode(e);i.insertBefore(s,t.mark),i.removeChild(t.mark),i.normalize(),this.context.invoke("editor.afterCommand");const o=this._currentIndex;this._onSearch(),this._matches.length>0&&(this._currentIndex=Math.min(o,this._matches.length-1),this._scrollToMatch(this._currentIndex),this._updateCounter())}_replaceAll(){if(this._matches.length===0)return;const t=this._replaceInput?this._replaceInput.value:"";this._matches.forEach(({mark:e})=>{if(!e||!e.parentNode)return;const i=document.createTextNode(t);e.parentNode.insertBefore(i,e),e.parentNode.removeChild(e)}),this.context.layoutInfo.editable&&this.context.layoutInfo.editable.normalize(),this._matches=[],this._currentIndex=-1,this.context.invoke("editor.afterCommand"),this._onSearch()}_clearHighlights(){const t=this.context.layoutInfo.editable;t&&(t.querySelectorAll("mark.an-highlight").forEach(e=>{const i=e.parentNode;if(i){for(;e.firstChild;)i.insertBefore(e.firstChild,e);i.removeChild(e)}}),t.normalize(),this._matches=[],this._currentIndex=-1)}_updateCounter(){if(!this._counterEl)return;const t=this._matches.length;if(t===0){const e=this._findInput?this._findInput.value:"";this._counterEl.textContent=e?"No results":""}else this._counterEl.textContent=`${this._currentIndex+1} / ${t}`}}const Ae=new Map;class Le{constructor(t,e={}){this.targetEl=t,this.options=it(F,e),this.layoutInfo={},this._listeners=new Map,this._modules=new Map,this._disposers=[],this._alive=!1}initialize(){const{container:t,editable:e}=_i(this.targetEl,this.options);this.layoutInfo.container=t,this.layoutInfo.editable=e,this._registerModules();const i=this._modules.get("toolbar");i&&i.el&&(t.insertBefore(i.el,e),this.layoutInfo.toolbar=i.el);const s=this._modules.get("statusbar");return s&&s.el&&(t.appendChild(s.el),this.layoutInfo.statusbar=s.el),this._bindEditorEvents(e),this.options.focus&&e.focus(),this._alive=!0,this.invoke("toolbar.refresh"),typeof this.options.onInit=="function"&&this.options.onInit(this),this}_registerModules(){const t=(e,i)=>{const s=new i(this);s.initialize(),this._modules.set(e,s)};t("editor",Ti),t("toolbar",Ii),t("statusbar",Si),t("clipboard",Ei),t("contextMenu",ls),t("placeholder",Bi),t("codeview",Ri),t("fullscreen",Ai),t("linkDialog",Li),t("imageDialog",Mi),t("videoDialog",ji),t("imageResizer",zi),t("videoResizer",$i),t("linkTooltip",Oi),t("imageTooltip",Ui),t("videoTooltip",Yi),t("tableTooltip",Gi),t("codeTooltip",Zi),t("emojiDialog",is),t("iconDialog",os),t("shortcutsDialog",cs),t("findReplace",hs);for(const[e,i]of Ae)t(e,i)}registerModule(t,e){if(this._modules.has(t))return this;const i=new e(this);return i.initialize(),this._modules.set(t,i),this}_bindEditorEvents(t){const e=d(t,"focus",()=>{this.layoutInfo.container.classList.add("an-focused"),typeof this.options.onFocus=="function"&&this.options.onFocus(this)}),i=d(t,"blur",()=>{this.layoutInfo.container.classList.remove("an-focused"),this._syncToTarget(),typeof this.options.onBlur=="function"&&this.options.onBlur(this)}),s=this.on("change",()=>this._syncToTarget());if(this._disposers.push(e,i,s),this.options.autoSave&&this.options.autoSaveKey){const o=this.on("change",()=>{try{localStorage.setItem(this.options.autoSaveKey,this.getHTML())}catch{}});this._disposers.push(o)}}invoke(t,...e){var a,l;const[i,s]=t.split("."),o=this._modules.get(i);if(!o){(typeof process>"u"||((a=process.env)==null?void 0:a.NODE_ENV)!=="production")&&console.warn(`[AutumnNote] invoke: module "${i}" not found (path: "${t}")`);return}if(typeof o[s]!="function"){(typeof process>"u"||((l=process.env)==null?void 0:l.NODE_ENV)!=="production")&&console.warn(`[AutumnNote] invoke: method "${s}" not found on module "${i}" (path: "${t}")`);return}return o[s](...e)}on(t,e){return this._listeners.has(t)||this._listeners.set(t,[]),this._listeners.get(t).push(e),()=>this.off(t,e)}off(t,e){const i=this._listeners.get(t);if(!i)return;const s=i.indexOf(e);s!==-1&&i.splice(s,1)}triggerEvent(t,...e){(this._listeners.get(t)||[]).forEach(o=>o(...e));const s="on"+t.charAt(0).toUpperCase()+t.slice(1);typeof this.options[s]=="function"&&this.options[s](...e)}getHTML(){return this.invoke("editor.getHTML")}setHTML(t){this.invoke("editor.setHTML",t)}getText(){return this.invoke("editor.getText")}setText(t){this.invoke("editor.setText",t)}clear(){this.invoke("editor.clear")}clearHistory(){this.invoke("editor.clearHistory")}isEmpty(){return this.invoke("editor.isEmpty")}insertHTML(t){this.invoke("editor.insertHTML",t)}insertText(t){this.invoke("editor.insertText",t)}setMarkdown(t){this.invoke("editor.setMarkdown",t)}getMarkdown(){return this.invoke("editor.getMarkdown")}getWordCount(){return this.invoke("statusbar.getWordCount")??0}getCharCount(){return this.invoke("statusbar.getCharCount")??0}downloadHTML(t="document.html"){this._download(this.getHTML(),t,"text/html")}downloadText(t="document.txt"){this._download(this.getText(),t,"text/plain")}downloadMarkdown(t="document.md"){this._download(this.getMarkdown(),t,"text/markdown")}_download(t,e,i){const s=new Blob([t],{type:i}),o=URL.createObjectURL(s),a=document.createElement("a");a.href=o,a.download=e,a.style.display="none",document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(o)}print(t=""){const e=this.getHTML(),i=(t||"").replace(/</g,"<").replace(/>/g,">"),s=window.open("","_blank");s&&(s.document.write(`<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>${i}</title><style>body{font-family:system-ui,-apple-system,"Segoe UI",Roboto,Arial,sans-serif;font-size:14px;line-height:1.6;padding:20mm;color:#111827;}ul.an-checklist{list-style:none;padding-left:0;}ul.an-checklist li{padding-left:24px;position:relative;margin:2px 0;}ul.an-checklist li input[type="checkbox"]{position:absolute;left:0;top:3px;}code{background:#f3f4f6;border-radius:3px;padding:.1em .35em;font-family:monospace;}pre{background:#f3f4f6;padding:.75em 1em;border-radius:4px;overflow-x:auto;}table{border-collapse:collapse;}td,th{border:1px solid #d1d5db;padding:4px 8px;}</style></head><body>${e}</body></html>`),s.document.close(),s.onload=()=>{s.print()})}setDisabled(t){const e=this.layoutInfo.editable;t?(e.setAttribute("contenteditable","false"),this.layoutInfo.container.classList.add("an-disabled")):(e.setAttribute("contenteditable","true"),this.layoutInfo.container.classList.remove("an-disabled"))}destroy(){if(!this._alive)return;this._modules.forEach(e=>{typeof e.destroy=="function"&&e.destroy()}),this._modules.clear(),this._disposers.forEach(e=>e()),this._disposers=[];const t=this.layoutInfo.container;t&&t.parentNode&&(this.targetEl.style.display="",t.parentNode.removeChild(t)),typeof this.options.onDestroy=="function"&&this.options.onDestroy(this),this._alive=!1,this._listeners.clear()}_syncToTarget(){(this.targetEl.tagName==="TEXTAREA"||this.targetEl.tagName==="INPUT")&&(this.targetEl.value=this.getHTML())}}function ds(n){return n[n.length-1]}function ps(n){return n[0]}function us(n,t=1){return n.slice(0,n.length-t)}function ms(n,t=1){return n.slice(t)}function fs(n){return n.reduce((t,e)=>t.concat(e),[])}function gs(n){return[...new Set(n)]}function ys(n,t){const e=[];for(let i=0;i<n.length;i+=t)e.push(n.slice(i,i+t));return e}function _s(n,t){return n.reduce((e,i)=>{const s=t(i);return e[s]||(e[s]=[]),e[s].push(i),e},{})}function bs(n,t){return n.every(t)}function vs(n,t){return n.some(t)}const V=navigator.userAgent,ws={isChrome:/Chrome\//.test(V),isFF:/Firefox\//.test(V),isSafari:/^((?!chrome|android).)*safari/i.test(V),isEdge:/Edg\//.test(V),isMac:/Macintosh/.test(V),isMobile:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(V),isTouch:"ontouchstart"in window||navigator.maxTouchPoints>0,modifierKey:/Macintosh/.test(V)?"metaKey":"ctrlKey"},xs={...F},G=new WeakMap,ks={create(n,t={}){const i=Me(n).map(s=>{if(G.has(s))return G.get(s);const o=new Le(s,t);return o.initialize(),G.set(s,o),o});return i.length===1?i[0]:i},destroy(n){Me(n).forEach(t=>{const e=G.get(t);e&&(e.destroy(),G.delete(t))})},getInstance(n){const t=typeof n=="string"?document.querySelector(n):n;return t&&G.get(t)||null},get defaults(){return{...F}},setDefaults(n){Object.assign(F,n)},resetDefaults(){Object.keys(F).forEach(n=>delete F[n]),Object.assign(F,xs)},registerModule(n,t){Ae.set(n,t)},version:"1.0.0"};function Me(n){return typeof n=="string"?Array.from(document.querySelectorAll(n)):n instanceof Element?[n]:n instanceof NodeList||Array.isArray(n)?Array.from(n):[]}p.Context=Le,p.ELEMENT_NODE=gt,p.TEXT_NODE=yt,p.WrappedRange=ot,p.alignCenterBtn=Kt,p.alignJustifyBtn=Gt,p.alignLeftBtn=Yt,p.alignRightBtn=Xt,p.all=bs,p.ancestors=Ye,p.any=vs,p.backColorBtn=ke,p.boldBtn=Ot,p.checklistBtn=ve,p.children=Ke,p.chunk=ys,p.clamp=J,p.closest=nt,p.closestPara=dt,p.codeviewBtn=fe,p.collapsedRange=li,p.compose=ze,p.createElement=c,p.currentRange=ut,p.debounce=ft,p.default=ks,p.defaultOptions=F,p.defaultToolbar=Ce,p.directionBtn=fi,p.emojiBtn=le,p.env=ws,p.findBtn=_e,p.findReplaceBtn=gi,p.first=ps,p.flatten=fs,p.fontFamilyBtn=pe,p.fontSizeBtn=he,p.foreColorBtn=xe,p.fromNativeRange=pt,p.fullscreenBtn=ge,p.groupBy=_s,p.hrBtn=se,p.iconBtn=re,p.identity=He,p.imageBtn=oe,p.indentBtn=Zt,p.initial=us,p.inlineCodeBtn=be,p.insertAfter=ti,p.isAnchor=qe,p.isEditable=wt,p.isElement=M,p.isEmpty=ii,p.isFunction=Pe,p.isImage=Ve,p.isInline=Ue,p.isInsideEditable=oi,p.isKey=K,p.isLi=vt,p.isList=Fe,p.isModifier=N,p.isNil=$e,p.isPara=bt,p.isPlainObject=st,p.isSelectionInside=ri,p.isString=De,p.isTable=We,p.isText=ht,p.isVoid=_t,p.italicBtn=Ft,p.key=Q,p.last=ds,p.lineHeightBtn=me,p.linkBtn=ne,p.mergeDeep=it,p.nextElement=Ge,p.nodeValue=ei,p.olBtn=Qt,p.on=d,p.outdentBtn=te,p.outerHtml=si,p.paragraphStyleBtn=ue,p.placeCaret=ni,p.prevElement=Xe,p.printBtn=we,p.rangeFromElement=ai,p.rect2bnd=Oe,p.redoBtn=ie,p.remove=Je,p.removeFormatBtn=de,p.sanitiseHTML=W,p.sanitiseUrl=mt,p.shortcutsBtn=ye,p.splitText=ci,p.strikeBtn=Ut,p.subscriptBtn=Vt,p.superscriptBtn=qt,p.tableBtn=ce,p.tail=ms,p.throttle=Ne,p.trapFocus=O,p.ulBtn=Jt,p.underlineBtn=Wt,p.undoBtn=ee,p.unique=gs,p.unwrap=Qe,p.videoBtn=ae,p.withSavedRange=Y,p.wrap=Ze,Object.defineProperties(p,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
67
|
+
`),t=[];let i=0;for(;i<e.length;){const s=e[i],o=s.match(/^```(\S*)$/);if(o){const l=o[1],h=[];for(i++;i<e.length&&!e[i].startsWith("```");)h.push(z(e[i])),i++;const p=l?` class="language-${ne(l)}"`:"";t.push(`<pre><code${p}>${h.join(`
|
|
68
|
+
`)}</code></pre>`),i++;continue}if(/^(-{3,}|\*{3,}|_{3,})\s*$/.test(s)){t.push("<hr>"),i++;continue}const a=s.match(/^(#{1,6})\s+(.+)$/);if(a){const l=a[1].length;t.push(`<h${l}>${U(a[2])}</h${l}>`),i++;continue}if(s.startsWith("> ")){const l=[];for(;i<e.length&&e[i].startsWith("> ");)l.push(e[i].slice(2)),i++;t.push(`<blockquote>${l.map(U).join("<br>")}</blockquote>`);continue}if(/^[-*+] /.test(s)){const l=[];for(;i<e.length&&/^[-*+] /.test(e[i]);)l.push(`<li>${U(e[i].slice(2))}</li>`),i++;t.push(`<ul>${l.join("")}</ul>`);continue}if(/^\d+\. /.test(s)){const l=[];for(;i<e.length&&/^\d+\. /.test(e[i]);)l.push(`<li>${U(e[i].replace(/^\d+\. /,""))}</li>`),i++;t.push(`<ol>${l.join("")}</ol>`);continue}if(s.trim()===""){i++;continue}if(/^\|.+\|/.test(s)&&i+1<e.length&&/^\|[\s|:-]+\|/.test(e[i+1])){const l=De(s);i+=2;const h=[];for(;i<e.length&&/^\|.+\|/.test(e[i]);)h.push(De(e[i])),i++;const p=`<thead><tr>${l.map(u=>`<th>${U(u)}</th>`).join("")}</tr></thead>`,m=h.length?`<tbody>${h.map(u=>`<tr>${u.map(f=>`<td>${U(f)}</td>`).join("")}</tr>`).join("")}</tbody>`:"";t.push(`<table>${p}${m}</table>`);continue}const r=[];for(;i<e.length&&e[i].trim()!==""&&!/^(#{1,6} |> |[-*+] |\d+\. |```|---\s*$|\*{3}\s*$|_{3}\s*$)/.test(e[i])&&!/^\|.+\|/.test(e[i]);)r.push(e[i]),i++;r.length&&t.push(`<p>${U(r.join(" "))}</p>`)}return t.join("")}function De(n){return n.replace(/^\|/,"").replace(/\|$/,"").split("|").map(e=>e.trim())}function U(n){return n=n.replace(/!\[([^\]]*)\]\(([^)]+)\)/g,(e,t,i)=>`<img src="${ne(i)}" alt="${ne(t)}" class="an-image">`),n=n.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(e,t,i)=>`<a href="${ne(i)}">${z(t)}</a>`),n=n.replace(/\*{3}(.+?)\*{3}/g,(e,t)=>`<strong><em>${z(t)}</em></strong>`),n=n.replace(/_{3}(.+?)_{3}/g,(e,t)=>`<strong><em>${z(t)}</em></strong>`),n=n.replace(/\*{2}(.+?)\*{2}/g,(e,t)=>`<strong>${z(t)}</strong>`),n=n.replace(/_{2}(.+?)_{2}/g,(e,t)=>`<strong>${z(t)}</strong>`),n=n.replace(/\*([^*\n]+?)\*/g,(e,t)=>`<em>${z(t)}</em>`),n=n.replace(/_([^_\n]+?)_/g,(e,t)=>`<em>${z(t)}</em>`),n=n.replace(/~~(.+?)~~/g,(e,t)=>`<del>${z(t)}</del>`),n=n.replace(/`([^`]+)`/g,(e,t)=>`<code>${z(t)}</code>`),n}function z(n){return String(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function ne(n){return String(n).replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class Xt{constructor(e){this.context=e,this.options=e.options,this._history=null,this._disposers=[],this._snapshotTimer=null}initialize(){const e=this.context.layoutInfo.editable;return this._history=new Ot(e,this.options.historyLimit||100),this._bindEvents(e),this}destroy(){this._disposers.forEach(e=>e()),this._disposers=[],this._history=null,clearTimeout(this._snapshotTimer),this._snapshotTimer=null}_bindEvents(e){const t=l=>this._onKeydown(l),i=()=>this.afterCommand(),s=l=>this._enforceLimit(l),o=()=>{if(!this.context._alive)return;const l=window.getSelection();l&&l.rangeCount>0&&e.contains(l.anchorNode)&&(this.context.invoke("toolbar.refresh"),typeof this.options.onSelectionChange=="function"&&this.options.onSelectionChange(this.context))},a=l=>{l.target.type==="checkbox"&&l.target.closest(".an-checklist")&&this.afterCommand()},r=l=>{const h=window.getSelection();if(!h||!h.rangeCount)return;const p=h.getRangeAt(0);if(!p.collapsed)return;const m=p.startContainer;if(m.nodeType!==Node.ELEMENT_NODE)return;const u=m.matches&&m.matches(".an-checklist li")?m:null;if(!u)return;const f=u.querySelector('input[type="checkbox"]');if(!f)return;if(l&&l.type==="mouseup"){let C=null;if(document.caretRangeFromPoint)C=document.caretRangeFromPoint(l.clientX,l.clientY);else if(document.caretPositionFromPoint){const T=document.caretPositionFromPoint(l.clientX,l.clientY);T&&(C=document.createRange(),C.setStart(T.offsetNode,T.offset))}if(C&&e.contains(C.startContainer)&&C.startContainer!==u){C.collapse(!0),h.removeAllRanges(),h.addRange(C);return}}const g=document.createRange();let b=null;for(const C of u.childNodes)if(C!==f&&C.nodeType===Node.TEXT_NODE){b=C;break}b?g.setStart(b,0):g.setStartAfter(f),g.collapse(!0),h.removeAllRanges(),h.addRange(g)};this._disposers.push(d(e,"keydown",t),d(e,"beforeinput",s),d(e,"input",i),d(document,"selectionchange",o),d(e,"click",a),d(e,"mouseup",r),d(e,"keyup",r))}_onKeydown(e){const t=this.context.layoutInfo.editable;if(!Ut(e,t,this.options)){if(N(e,"z")&&!e.shiftKey){e.preventDefault(),this.undo();return}if(N(e,"z")&&e.shiftKey||N(e,"y")){e.preventDefault(),this.redo();return}if(N(e,"b")){e.preventDefault(),this.bold();return}if(N(e,"i")){e.preventDefault(),this.italic();return}if(N(e,"u")){e.preventDefault(),this.underline();return}if(N(e,"k")){e.preventDefault(),this.context.invoke("linkDialog.show");return}if(N(e,"v")&&e.shiftKey){this.context.invoke("clipboard.setForcePlain",!0);return}if(e.key==="/"&&e.shiftKey&&e.ctrlKey&&!e.metaKey){e.preventDefault(),this.context.invoke("shortcutsDialog.show");return}if(N(e,"f")){e.preventDefault(),this.context.invoke("findReplace.show","find");return}N(e,"h")&&(e.preventDefault(),this.context.invoke("findReplace.show","replace")),N(e,"`")&&(e.preventDefault(),this.inlineCode())}}_enforceLimit(e){const t=this.options.maxChars||0,i=this.options.maxWords||0;if(!t&&!i)return;const s=e.inputType||"";if(s.startsWith("delete")||s==="historyUndo"||s==="historyRedo"||s==="insertFromPaste"||s==="insertFromDrop"||!s.startsWith("insert"))return;const o=this.context.layoutInfo.editable.innerText||"",a=o.replace(/\n/g,"").length;if(t&&a>=t){e.preventDefault(),typeof this.options.onCharLimitReached=="function"&&this.options.onCharLimitReached(this.context);return}i&&(e.data===" "||s==="insertParagraph"||s==="insertLineBreak")&&(o.trim()?o.trim().split(/\s+/).length:0)>=i&&(e.preventDefault(),typeof this.options.onWordLimitReached=="function"&&this.options.onWordLimitReached(this.context))}afterCommand(){this.context.invoke("toolbar.refresh"),this.context.invoke("statusbar.update"),this._scheduleSnapshot()}_scheduleSnapshot(){clearTimeout(this._snapshotTimer),this._snapshotTimer=setTimeout(()=>{this._snapshotTimer=null,this._history&&this._history.recordUndo(),this.context.triggerEvent("change",this.getHTML())},400)}focus(){this.context.layoutInfo.editable.focus()}getHTML(){const e=this.context.layoutInfo.editable.innerHTML.replace(/\u200B/g,"");return this.context.invoke("clipboard.resolveImages",e)??e}setHTML(e){this.context.layoutInfo.editable.innerHTML=W(e),this._history&&this._history.reset(),this.afterCommand()}getText(){return this.context.layoutInfo.editable.innerText||""}setText(e){this.context.layoutInfo.editable.textContent=e,this._history&&this._history.reset(),this.afterCommand()}clear(){this.setHTML("")}clearHistory(){this._history&&this._history.reset()}isEmpty(){const e=(this.context.layoutInfo.editable.innerText||"").trim().replace(/\u00a0/g,""),t=!!this.context.layoutInfo.editable.querySelector("img, video, iframe, table");return!e&&!t}insertHTML(e){e&&(S("insertHTML",W(e)),this.afterCommand())}insertText(e){e&&(S("insertText",e),this.afterCommand())}setMarkdown(e){this.setHTML(Pe(e||""))}getMarkdown(){return qt(this.getHTML())}undo(){this._history&&(clearTimeout(this._snapshotTimer),this._snapshotTimer=null,this._history.undo(),this.context.invoke("toolbar.refresh"),this.context.invoke("statusbar.update"),this.context.triggerEvent("change",this.getHTML()))}redo(){this._history&&(clearTimeout(this._snapshotTimer),this._snapshotTimer=null,this._history.redo(),this.context.invoke("toolbar.refresh"),this.context.invoke("statusbar.update"),this.context.triggerEvent("change",this.getHTML()))}canUndo(){return this._history?this._history.canUndo():!1}canRedo(){return this._history?this._history.canRedo():!1}bold(){ye(),this.afterCommand()}italic(){be(),this.afterCommand()}underline(){ve(),this.afterCommand()}strikethrough(){we(),this.afterCommand()}superscript(){xe(),this.afterCommand()}subscript(){Ce(),this.afterCommand()}justifyLeft(){Re(),this.afterCommand()}justifyCenter(){Ae(),this.afterCommand()}justifyRight(){Le(),this.afterCommand()}justifyFull(){Be(),this.afterCommand()}indent(){Me(),this.afterCommand()}outdent(){Ne(),this.afterCommand()}insertUL(){je(),this.afterCommand()}insertOL(){ze(),this.afterCommand()}inlineCode(){Ze(this.context.layoutInfo.editable),this.afterCommand()}toggleChecklist(){et(),this.afterCommand()}print(){this.context.print()}formatBlock(e){Ee(e),this.afterCommand()}foreColor(e){ke(e),this.afterCommand()}backColor(e){Te(e),this.afterCommand()}fontName(e){Se(e),this.afterCommand()}fontSize(e){Ie(e,this.context.layoutInfo.editable),this.afterCommand()}insertHr(){S("insertHorizontalRule"),this.afterCommand()}insertLink(e,t,i=!1){const s=window.getSelection();if(!s||s.rangeCount===0)return;const o=$e(e);if(!o)return;if(s.toString().trim().length>0){if(S("createLink",o),i){const r=this._getClosestAnchor();r&&(r.setAttribute("target","_blank"),r.setAttribute("rel","noopener noreferrer"))}}else{const r=this._escapeAttr(t||o);S("insertHTML",`<a href="${this._escapeAttr(o)}"${i?' target="_blank" rel="noopener noreferrer"':""}>${r}</a>`)}this.afterCommand()}unlink(){S("unlink"),this.afterCommand()}insertImage(e,t="",i=""){const s=$e(e,{allowData:!0});if(!s)return;const a={left:"float:left;margin:0 1em 1em 0",center:"display:block;margin:0 auto",right:"float:right;margin:0 0 1em 1em"}[i]||"",r=a?` style="${a}"`:"";S("insertHTML",`<img src="${this._escapeAttr(s)}" alt="${this._escapeAttr(t)}" class="an-image"${r}>`),this.afterCommand()}insertVideo(e){e&&(S("insertHTML",e),this.afterCommand())}insertTable(e,t){Wt(e,t,{headerRow:this.context.options.tableHeaderRow}),this.afterCommand()}_getClosestAnchor(){const e=window.getSelection();if(!e||e.rangeCount===0)return null;let t=e.getRangeAt(0).startContainer;for(;t;){if(t.nodeName==="A")return t;t=t.parentNode}return null}_escapeAttr(e){return String(e??"").replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}}let Q=null;class Yt{constructor(e){this.context=e,this.options=e.options,this.el=null,this._disposers=[],this._colorPickerClosers=[]}initialize(){return this.el=c("div",{class:"an-toolbar"}),this._faReady=this._detectFontAwesome(),this._buildButtons(),this._btnMap=new Map((this.options.toolbar||[]).flat().map(e=>[e.name,e])),this}destroy(){this._disposers.forEach(e=>e()),this._disposers=[],this.el&&this.el.parentNode&&this.el.parentNode.removeChild(this.el),this.el=null}_buildButtons(){(this.options.toolbar||[]).forEach(t=>{const i=c("div",{class:"an-btn-group"});t.forEach(s=>{let o;s.type==="select"?o=this._createSelect(s):s.type==="grid"?o=this._createGridPicker(s):s.type==="colorpicker"?o=this._createColorPicker(s):o=this._createButton(s),i.appendChild(o)}),this.el.appendChild(i)})}_createGridPicker(e){const s=c("div",{class:"an-table-picker-wrap"}),a=!!this.options.useBootstrap?this.options.toolbarButtonClass||"btn btn-sm btn-light":"an-btn",r=c("button",{type:"button",class:a,title:e.tooltip||"","data-btn":e.name,"aria-label":e.tooltip||e.name,"aria-haspopup":"true","aria-expanded":"false"});if(this._faReady){const w=this.options.fontAwesomeClass||"fas";r.innerHTML=`<i class="${w} fa-table" aria-hidden="true"></i>`}else{const w='stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"';r.innerHTML=`<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" ${w} style="display:block"><rect x="3" y="3" width="18" height="18" rx="1"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="3" y1="15" x2="21" y2="15"/><line x1="9" y1="3" x2="9" y2="21"/><line x1="15" y1="3" x2="15" y2="21"/></svg>`}const l=c("div",{class:"an-table-picker-popup",role:"dialog","aria-label":"Select table size"}),h=c("div",{class:"an-table-grid"}),p=c("div",{class:"an-table-label"});p.textContent="Insert Table";const m=[];for(let w=1;w<=10;w++)for(let k=1;k<=10;k++){const I=c("div",{class:"an-table-cell","data-row":String(w),"data-col":String(k)});m.push(I),h.appendChild(I)}l.appendChild(h),l.appendChild(p);let u=!1;const f=(w,k)=>{m.forEach(I=>{const A=+I.getAttribute("data-row"),j=+I.getAttribute("data-col");I.classList.toggle("active",A<=w&&j<=k)}),p.textContent=w&&k?`${w} × ${k}`:"Insert Table"},g=()=>{u=!0,l.style.display="block",r.setAttribute("aria-expanded","true")},b=()=>{u=!1,l.style.display="none",r.setAttribute("aria-expanded","false"),f(0,0)},C=d(r,"click",w=>{w.stopPropagation(),u?b():g()}),T=d(h,"mouseover",w=>{const k=w.target.closest(".an-table-cell");k&&f(+k.getAttribute("data-row"),+k.getAttribute("data-col"))}),v=d(h,"mouseleave",()=>f(0,0)),_=d(h,"click",w=>{const k=w.target.closest(".an-table-cell");if(!k)return;const I=+k.getAttribute("data-row"),A=+k.getAttribute("data-col");b(),this.context.invoke("editor.focus"),e.action(this.context,I,A)}),y=d(document,"click",()=>{u&&b()});return this._disposers.push(C,T,v,_,y),s.appendChild(r),s.appendChild(l),s}_createColorPicker(e){const t=["#000000","#434343","#666666","#999999","#b7b7b7","#cccccc","#efefef","#ffffff","#ff0000","#ff9900","#ffff00","#00ff00","#00ffff","#4a86e8","#9900ff","#ff00ff","#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#c9daf8","#d9d2e9","#ead1dc"];let i=e.defaultColor||"#000000";const s=c("div",{class:"an-color-picker-wrap"}),a=!!this.options.useBootstrap?this.options.toolbarButtonClass||"btn btn-sm btn-light":"an-btn",r=c("button",{type:"button",class:`${a} an-color-btn`,title:e.tooltip||"","data-btn":e.name,"aria-label":e.tooltip||e.name}),l='stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"',h=e.name==="foreColor"?`<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" ${l} style="display:block"><path d="M4 20L12 4L20 20"/><line x1="7.5" y1="14" x2="16.5" y2="14"/></svg>`:`<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" ${l} style="display:block"><path d="M3 21v-4l9-9 4 4-9 9z"/><path d="M12 8l4 4"/></svg>`;r.innerHTML=h;const p=c("span",{class:"an-color-strip"});p.style.background=i,r.appendChild(p);const m=c("button",{type:"button",class:`${a} an-color-arrow`,title:`Choose ${e.name==="foreColor"?"text":"highlight"} color`,"aria-haspopup":"true","aria-expanded":"false"});m.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8" viewBox="0 0 24 24" fill="currentColor" stroke="none" style="display:block"><path d="M7 10l5 5 5-5H7z"/></svg>';const u=c("div",{class:"an-color-popup"});u.style.display="none";const f=c("div",{class:"an-color-swatches"}),g=Array.isArray(this.options.colorSwatches)?this.options.colorSwatches:[];[...new Set([...g,...t])].forEach(x=>{const R=c("div",{class:"an-color-swatch",title:x,"data-color":x});R.style.background=x,f.appendChild(R)});const C=c("div",{class:"an-color-custom"}),T=c("input",{type:"color",value:i,title:"Custom color"}),v=c("span",{},["Custom color"]);C.appendChild(T),C.appendChild(v),u.appendChild(f),u.appendChild(C);let _=!1,y=null;const w=()=>{const x=window.getSelection();y=x&&x.rangeCount?x.getRangeAt(0).cloneRange():null},k=()=>{if(!y)return;const x=window.getSelection();x&&(x.removeAllRanges(),x.addRange(y))},I=()=>{this._colorPickerClosers.forEach(ce=>{ce!==A&&ce()}),w(),_=!0;const x=m.getBoundingClientRect(),R=184;let B=x.left;B+R>window.innerWidth&&(B=x.right-R),u.style.top=`${x.bottom+4}px`,u.style.left=`${Math.max(4,B)}px`,u.style.display="block",m.setAttribute("aria-expanded","true")},A=()=>{_=!1,u.style.display="none",u.style.top="",u.style.left="",m.setAttribute("aria-expanded","false")},j=x=>{i=x,p.style.background=x,T.value=x,k(),e.action(this.context,x),this.context.invoke("editor.afterCommand"),A()},J=d(r,"click",x=>{x.preventDefault(),k(),e.action(this.context,i),this.context.invoke("editor.afterCommand")}),ee=d(m,"mousedown",x=>{x.preventDefault()}),te=d(m,"click",x=>{x.stopPropagation(),_?A():I()}),ie=d(f,"mousedown",x=>{x.preventDefault()}),M=d(f,"click",x=>{const R=x.target.closest(".an-color-swatch");R&&j(R.dataset.color)}),de=d(T,"change",x=>{j(x.target.value)}),pe=d(document,"click",x=>{_&&!s.contains(x.target)&&!u.contains(x.target)&&A()}),ue=d(u,"click",x=>x.stopPropagation()),Y=()=>{_&&A()};return document.addEventListener("scroll",Y,{passive:!0,capture:!0}),window.addEventListener("resize",Y,{passive:!0}),this._disposers.push(J,ee,te,ie,M,de,pe,ue,()=>document.removeEventListener("scroll",Y,{capture:!0}),()=>window.removeEventListener("resize",Y),()=>{u.parentNode&&u.parentNode.removeChild(u)}),this._colorPickerClosers.push(A),this._disposers.push(()=>{const x=this._colorPickerClosers.indexOf(A);x!==-1&&this._colorPickerClosers.splice(x,1)}),s.appendChild(r),s.appendChild(m),document.body.appendChild(u),s}_createSelect(e){const t=e.name==="fontFamily"?this.options.fontFamilies||[]:e.items||[],i=e.selectClass?`an-select ${e.selectClass}`:"an-select",s=c("select",{class:i,title:e.tooltip||"","data-btn":e.name,"aria-label":e.tooltip||e.name}),o=e.placeholder||"Font",a=c("option",{value:"",disabled:"",hidden:""},[o]);s.appendChild(a),t.forEach(l=>{const h=typeof l=="object"?l.value:l,p=typeof l=="object"?l.label:l,m=typeof l=="object"&&!!l.disabled,u={value:h};m&&(u.disabled="");const f=c("option",u,[p]);e.name==="fontFamily"&&!m&&(f.style.fontFamily=h),s.appendChild(f)});const r=d(s,"change",l=>{const h=l.target.value,p=l.target.options[l.target.selectedIndex];!h||p.disabled||(this.context.invoke("editor.focus"),e.action(this.context,h),this.context.invoke("editor.afterCommand"))});return this._disposers.push(r),s}_createButton(e){const i=!!this.options.useBootstrap?this.options.toolbarButtonClass||"btn btn-sm btn-light":"an-btn",s=e.className?` ${e.className}`:"",o=`${i}${s}`,a=c("button",{type:"button",class:o,title:e.tooltip||"","data-btn":e.name,"aria-label":e.tooltip||e.name}),r='stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"',l=g=>`<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" ${r} style="display:block">${g}</svg>`,h=new Map([["bold",l('<path d="M6 4h8a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"/><path d="M6 12h9a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"/>')],["italic",l('<line x1="19" y1="4" x2="10" y2="4"/><line x1="14" y1="20" x2="5" y2="20"/><line x1="15" y1="4" x2="9" y2="20"/>')],["underline",l('<path d="M6 3v7a6 6 0 0 0 6 6 6 6 0 0 0 6-6V3"/><line x1="4" y1="21" x2="20" y2="21"/>')],["strikethrough",l('<path d="M17.3 12H6.7"/><path d="M10 6.5C10 5.1 11.1 4 12.5 4c1.4 0 2.5 1.1 2.5 2.5 0 .8-.4 1.5-1 2"/><path d="M14 17.5C14 19 12.9 20 11.5 20 10.1 20 9 18.9 9 17.5c0-.8.4-1.5 1-2"/>')],["superscript",l('<path d="m4 19 8-8"/><path d="m12 19-8-8"/><path d="M20 12h-4c0-1.5.44-2 1.5-2.5S20 8.33 20 7.25C20 6 19 5 17.5 5S15 6 15 7"/>')],["subscript",l('<path d="m4 5 8 8"/><path d="m12 5-8 8"/><path d="M20 21h-4c0-1.5.44-2 1.5-2.5S20 17.33 20 16.25C20 15 19 14 17.5 14S15 15 15 16"/>')],["align-left",l('<line x1="21" y1="6" x2="3" y2="6"/><line x1="15" y1="12" x2="3" y2="12"/><line x1="17" y1="18" x2="3" y2="18"/>')],["align-center",l('<line x1="21" y1="6" x2="3" y2="6"/><line x1="18" y1="12" x2="6" y2="12"/><line x1="21" y1="18" x2="3" y2="18"/>')],["align-right",l('<line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="12" x2="9" y2="12"/><line x1="21" y1="18" x2="7" y2="18"/>')],["align-justify",l('<line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="12" x2="3" y2="12"/><line x1="21" y1="18" x2="3" y2="18"/>')],["list-ul",l('<line x1="9" y1="6" x2="20" y2="6"/><line x1="9" y1="12" x2="20" y2="12"/><line x1="9" y1="18" x2="20" y2="18"/><circle cx="4" cy="6" r="1" fill="currentColor" stroke="none"/><circle cx="4" cy="12" r="1" fill="currentColor" stroke="none"/><circle cx="4" cy="18" r="1" fill="currentColor" stroke="none"/>')],["list-ol",l('<line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/><path d="M4 6h1V3"/><path d="M4 10h2l-2 2h2"/><path d="M4 16.5A1.5 1.5 0 0 1 5.5 15a1.5 1.5 0 0 1 0 3H4"/>')],["indent",l('<polyline points="3 8 7 12 3 16"/><line x1="21" y1="12" x2="11" y2="12"/><line x1="21" y1="6" x2="11" y2="6"/><line x1="21" y1="18" x2="11" y2="18"/>')],["outdent",l('<polyline points="7 8 3 12 7 16"/><line x1="21" y1="12" x2="11" y2="12"/><line x1="21" y1="6" x2="11" y2="6"/><line x1="21" y1="18" x2="11" y2="18"/>')],["undo",l('<path d="M3 7v6h6"/><path d="M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13"/>')],["redo",l('<path d="M21 7v6h-6"/><path d="M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3L21 13"/>')],["minus",l('<line x1="5" y1="12" x2="19" y2="12"/>')],["link",l('<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>')],["image",l('<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/>')],["video",l('<polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2"/>')],["table",l('<rect x="3" y="3" width="18" height="18" rx="1"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="3" y1="15" x2="21" y2="15"/><line x1="9" y1="3" x2="9" y2="21"/><line x1="15" y1="3" x2="15" y2="21"/>')],["emoji",l('<circle cx="12" cy="12" r="10"/><path d="M8.5 14.5s1.5 2.5 3.5 2.5 3.5-2.5 3.5-2.5"/><circle cx="9" cy="9" r="1.5" fill="currentColor" stroke="none"/><circle cx="15" cy="9" r="1.5" fill="currentColor" stroke="none"/>')],["icon",l('<circle cx="8" cy="8" r="3"/><circle cx="16" cy="8" r="3"/><rect x="5" y="13" width="6" height="6" rx="1"/><rect x="13" y="13" width="6" height="6" rx="1"/>')],["code",l('<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>')],["expand",l('<polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/>')],["foreColor",l('<path d="M4 20L12 4L20 20"/><line x1="7.5" y1="14" x2="16.5" y2="14"/>')],["backColor",l('<path d="M3 21v-4l9-9 4 4-9 9z"/><path d="M12 8l4 4"/>')],["keyboard",l('<rect x="2" y="6" width="20" height="12" rx="2"/><line x1="6" y1="10" x2="6" y2="10" stroke-width="2.5"/><line x1="10" y1="10" x2="10" y2="10" stroke-width="2.5"/><line x1="14" y1="10" x2="14" y2="10" stroke-width="2.5"/><line x1="18" y1="10" x2="18" y2="10" stroke-width="2.5"/><line x1="8" y1="14" x2="16" y2="14" stroke-width="2"/>')],["caption",l('<rect x="3" y="3" width="18" height="11" rx="2"/><line x1="6" y1="18" x2="18" y2="18"/><line x1="9" y1="21" x2="15" y2="21"/>')],["remove-format",l('<path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21"/><path d="M22 21H7"/><path d="m5 11 9 9"/>')],["direction",l('<path d="M12 20V4"/><path d="m9 7-3 3 3 3"/><path d="M4 10h8"/><path d="m15 7 3 3-3 3"/><path d="M20 10h-8"/>')],["search",l('<circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>')],["find-replace",l('<circle cx="10" cy="10" r="6"/><line x1="18" y1="18" x2="14.35" y2="14.35"/><path d="M16 19h6"/><path d="M19 16v6"/>')],["inline-code",l('<path d="M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1"/><path d="M16 3h1a2 2 0 0 1 2 2v5c0 1.1.9 2 2 2a2 2 0 0 1-2 2v5a2 2 0 0 1-2 2h-1"/>')],["checklist",l('<rect x="3" y="4" width="5" height="5" rx="1"/><path d="m4 6.5 1 1 2-2"/><rect x="3" y="13" width="5" height="5" rx="1"/><line x1="10" y1="6.5" x2="21" y2="6.5"/><line x1="10" y1="15.5" x2="21" y2="15.5"/>')],["print",l('<path d="M6 9V2h12v7"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/>')]]),p=this.options.fontAwesomeClass||"fas",m=new Map([["bold","fa-bold"],["italic","fa-italic"],["underline","fa-underline"],["strikethrough","fa-strikethrough"],["superscript","fa-superscript"],["subscript","fa-subscript"],["align-left","fa-align-left"],["align-center","fa-align-center"],["align-right","fa-align-right"],["align-justify","fa-align-justify"],["list-ul","fa-list-ul"],["list-ol","fa-list-ol"],["indent","fa-indent"],["outdent","fa-outdent"],["undo","fa-rotate-left"],["redo","fa-rotate-right"],["minus","fa-minus"],["link","fa-link"],["image","fa-image"],["code","fa-code"],["expand","fa-expand"],["emoji","fa-face-smile"],["icon","fa-icons"],["foreColor","fa-font"],["backColor","fa-highlighter"],["keyboard","fa-keyboard"],["remove-format","fa-remove-format"],["direction","fa-arrow-right-arrow-left"],["search","fa-magnifying-glass"],["find-replace","fa-magnifying-glass-plus"],["inline-code","fa-code"],["checklist","fa-list-check"],["print","fa-print"]]);if(this._faReady){const g=m.get(e.icon)||m.get(e.name)||null;g?a.innerHTML=`<i class="${p} ${g}" aria-hidden="true"></i>`:h.has(e.icon)?a.innerHTML=h.get(e.icon):a.textContent=e.icon||e.name}else h.has(e.icon)?a.innerHTML=h.get(e.icon):h.has(e.name)?a.innerHTML=h.get(e.name):a.textContent=e.icon||e.name;const f=d(a,"click",g=>{g.preventDefault(),this.context.invoke("editor.focus"),e.action(this.context),this.context.invoke("editor.afterCommand"),this.refresh()});return this._disposers.push(f),a}_detectFontAwesome(){if(!this.options.useFontAwesome)return!1;if(Q!==null)return Q;if(document.querySelector(".fa, .fas, .far, .fal, .fab, .fa-solid"))return Q=!0,!0;const e=Array.from(document.querySelectorAll('link[rel="stylesheet"]')).filter(t=>t.id!=="an-fontawesome-css").map(t=>t.href||"").join(" ");return Q=/fontawesome|font-awesome|use\.fontawesome|all\.css/.test(e),Q}refresh(){if(!this.el)return;const e=this._btnMap||new Map;this.el.querySelectorAll("button[data-btn]").forEach(t=>{const i=e.get(t.getAttribute("data-btn"));i&&typeof i.isActive=="function"&&t.classList.toggle("active",!!i.isActive(this.context)),i&&typeof i.isDisabled=="function"&&(t.disabled=!!i.isDisabled(this.context))}),this.el.querySelectorAll("select[data-btn]").forEach(t=>{const i=e.get(t.getAttribute("data-btn"));if(!i||typeof i.getValue!="function")return;let s=(i.getValue(this.context)||"").replace(/["']/g,"").trim();s||(s=this.options.defaultFontFamily||this.options.fontFamilies&&this.options.fontFamilies[0]||"");const o=Array.from(t.options).find(a=>a.value&&a.value.toLowerCase()===s.toLowerCase());t.value=o?o.value:""})}show(){this.el&&(this.el.style.display="")}hide(){this.el&&(this.el.style.display="none")}}const Oe=typeof Intl<"u"&&typeof Intl.Segmenter=="function"?new Intl.Segmenter(void 0,{granularity:"word"}):null;function Fe(n){const e=n.trim();if(!e)return 0;if(Oe){let t=0;for(const i of Oe.segment(e))i.isWordLike&&t++;return t}return e.split(/\s+/).length}function We(n,e,t){if(!t){n.classList.remove("an-count-warn","an-count-exceeded");return}e>t?(n.classList.add("an-count-exceeded"),n.classList.remove("an-count-warn")):e>=t*.9?(n.classList.add("an-count-warn"),n.classList.remove("an-count-exceeded")):n.classList.remove("an-count-warn","an-count-exceeded")}class Kt{constructor(e){this.context=e,this.options=e.options,this.el=null,this._disposers=[],this._wordCountEl=null,this._charCountEl=null}initialize(){if(this.el=c("div",{class:"an-statusbar"}),this.options.resizable!==!1){const t=c("div",{class:"an-resize-handle",title:"Resize editor","aria-hidden":"true"});this._bindResize(t),this.el.appendChild(t)}this._wordCountEl=c("span",{class:"an-word-count"}),this._charCountEl=c("span",{class:"an-char-count"});const e=c("div",{class:"an-status-info"});return e.appendChild(this._wordCountEl),e.appendChild(this._charCountEl),this.el.appendChild(e),this._bindContentEvents(),this.update(),this}destroy(){this._disposers.forEach(e=>e()),this._disposers=[],this._dragDisposers&&(this._dragDisposers.forEach(e=>e()),this._dragDisposers=null),this.el&&this.el.parentNode&&this.el.parentNode.removeChild(this.el),this.el=null}_bindResize(e){let t=0,i=0;const s=this.context.layoutInfo.container,o=g=>{const b=g-t,C=40,T=Array.from(s.children).filter(_=>!_.classList.contains("an-editable")).reduce((_,y)=>_+y.offsetHeight,0),v=Math.max(this.options.minHeight||100,T+C);s.style.height=`${Math.max(v,i+b)}px`},a=g=>o(g.clientY),r=()=>{document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",r),this._dragDisposers=null},l=g=>{t=g.clientY,i=s.offsetHeight,this.context.layoutInfo.editable.style.minHeight="",document.addEventListener("mousemove",a),document.addEventListener("mouseup",r),this._dragDisposers=[()=>document.removeEventListener("mousemove",a),()=>document.removeEventListener("mouseup",r)],g.preventDefault()},h=g=>{const b=g.touches[0];b&&(g.preventDefault(),o(b.clientY))},p=()=>{document.removeEventListener("touchmove",h),document.removeEventListener("touchend",p),this._dragDisposers=null},m=g=>{const b=g.touches[0];b&&(t=b.clientY,i=s.offsetHeight,this.context.layoutInfo.editable.style.minHeight="",document.addEventListener("touchmove",h,{passive:!1}),document.addEventListener("touchend",p),this._dragDisposers=[()=>document.removeEventListener("touchmove",h),()=>document.removeEventListener("touchend",p)])},u=d(e,"mousedown",l),f=d(e,"touchstart",m);this._disposers.push(u,f)}_bindContentEvents(){const e=this.context.layoutInfo.editable,t=K(()=>this.update(),200),i=d(e,"input",t);this._disposers.push(i)}update(){if(!this._wordCountEl||!this._charCountEl)return;const t=this.context.layoutInfo.editable.innerText||"",i=Fe(t),s=t.replace(/\n/g,"").length,o=this.options.maxWords||0,a=this.options.maxChars||0;this._wordCountEl.textContent=o?`Words: ${i}/${o}`:`Words: ${i}`,this._charCountEl.textContent=a?`Chars: ${s}/${a}`:`Chars: ${s}`,We(this._wordCountEl,i,o),We(this._charCountEl,s,a)}getWordCount(){const e=this.context.layoutInfo.editable;return Fe(e.innerText||"")}getCharCount(){return(this.context.layoutInfo.editable.innerText||"").replace(/\n/g,"").length}}class Gt{constructor(e){this.context=e,this.options=e.options,this._disposers=[]}initialize(){this._blobRegistry=new Map,this._forcePlain=!1;const e=this.context.layoutInfo.editable;return this._disposers.push(d(e,"paste",t=>this._onPaste(t)),d(e,"dragover",t=>this._onDragover(t)),d(e,"drop",t=>this._onDrop(t))),this._mutationObserver=new MutationObserver(t=>{for(const i of t)for(const s of i.removedNodes)this._revokeRemovedBlobs(s)}),this._mutationObserver.observe(e,{childList:!0,subtree:!0}),this}destroy(){this._disposers.forEach(e=>e()),this._disposers=[],this._mutationObserver&&(this._mutationObserver.disconnect(),this._mutationObserver=null),this._blobRegistry&&(this._blobRegistry.forEach((e,t)=>URL.revokeObjectURL(t)),this._blobRegistry.clear())}_revokeRemovedBlobs(e){if(!this._blobRegistry||!this._blobRegistry.size)return;const t=[];e.nodeName==="IMG"?t.push(e):e.querySelectorAll&&t.push(...e.querySelectorAll("img")),t.forEach(i=>{const s=i.getAttribute("src")||"";s.startsWith("blob:")&&this._blobRegistry.has(s)&&(URL.revokeObjectURL(s),this._blobRegistry.delete(s))})}_cleanWordHtml(e){return e.replace(/<!--\[if[\s\S]*?\[endif\]-->/gi,"").replace(/<xml[\s\S]*?<\/xml>/gi,"").replace(/<\?xml[\s\S]*?\?>/gi,"").replace(/<\/?(o|w|m|v|st1):[a-z][^>]*>/gi,"").replace(/\s+class="Mso[^"]*"/gi,"").replace(/\s+style="([^"]*)"/gi,(t,i)=>{const s=i.split(";").map(o=>o.trim()).filter(o=>o&&!/^mso-/i.test(o)&&!/^(tab-stops|margin-[a-z]+-alt)/i.test(o)).join("; ");return s?` style="${s}"`:""}).replace(/<p[^>]*>\s*( )?\s*<\/p>/gi,"")}_cleanSocialHtml(e){const t=new DOMParser().parseFromString(`<body>${e}</body>`,"text/html"),i=new Set(["span","div"]);let s=!0;for(;s;)s=!1,t.querySelectorAll("span, div").forEach(o=>{if(!i.has(o.tagName.toLowerCase())||o.querySelector("a, strong, em, b, i, ul, ol, li, table, img, blockquote, pre, code, h1, h2, h3, h4, h5, h6"))return;const a=o.parentNode;if(a){for(;o.firstChild;)a.insertBefore(o.firstChild,o);a.removeChild(o),s=!0}});return t.querySelectorAll("*").forEach(o=>{o.removeAttribute("class"),o.removeAttribute("id"),Array.from(o.attributes).filter(a=>a.name.startsWith("data-")||a.name.startsWith("aria-")).forEach(a=>o.removeAttribute(a.name))}),t.body.innerHTML}_stripAttributes(e){const t=new DOMParser().parseFromString(`<body>${e}</body>`,"text/html"),i=new Set(["href","src","alt","target","rel","colspan","rowspan","type"]);return t.querySelectorAll("*").forEach(s=>{Array.from(s.attributes).filter(o=>!i.has(o.name)).forEach(o=>s.removeAttribute(o.name))}),t.body.innerHTML}setForcePlain(e){this._forcePlain=!!e}_onPaste(e){const t=e.clipboardData||window.clipboardData;if(!t)return;const i=this._forcePlain;if(this._forcePlain=!1,t.items){const s=Array.from(t.items).filter(o=>o.kind==="file"&&o.type.startsWith("image/"));if(s.length>0){e.preventDefault();const o=s.map(a=>a.getAsFile()).filter(Boolean);this._insertImageFiles(o);return}}if(typeof this.options.onPaste=="function"&&this.options.onPaste({text:t.getData("text/plain")||"",html:t.types.includes("text/html")?t.getData("text/html"):null}),i||this.options.pasteAsPlainText){e.preventDefault();const o=t.getData("text/plain").split(/\r?\n/).map(a=>`<p>${this._escapeHTML(a)||"<br>"}</p>`).join("");S("insertHTML",o),this.context.invoke("editor.afterCommand");return}if(this.options.markdownPaste!==!1&&!t.types.includes("text/html")){const s=t.getData("text/plain");if(s&&Vt(s)){e.preventDefault();const o=W(Pe(s));S("insertHTML",o),this.context.invoke("editor.afterCommand");return}}if(this.options.pasteCleanHTML!==!1&&t.types.includes("text/html")){e.preventDefault();const s=t.getData("text/html"),o=/<[a-z]+:[a-z]/i.test(s)||/class="Mso/i.test(s)||/\bmso-/i.test(s),a=/\bdata-testid\b/.test(s)||/class="[^"]*\b(?:x[a-z0-9]{6,}|r-[a-z0-9]{3,})\b/.test(s);let r=s;o?r=this._cleanWordHtml(r):a&&(r=this._cleanSocialHtml(r)),r=W(r),this.options.pasteStripAttributes&&(r=this._stripAttributes(r)),S("insertHTML",r),this.context.invoke("editor.afterCommand");return}}_onDragover(e){if(!e.dataTransfer)return;Array.from(e.dataTransfer.types||[]).includes("Files")&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")}_onDrop(e){const t=e.dataTransfer;if(!t||!t.files||t.files.length===0)return;const i=Array.from(t.files).filter(s=>s.type.startsWith("image/"));i.length!==0&&(e.preventDefault(),e.stopPropagation(),this._placeCaretAtPoint(e.clientX,e.clientY),this._insertImageFiles(i))}_insertImageFiles(e){if(!e||e.length===0)return;if(typeof this.options.onImageUpload=="function"){this.options.onImageUpload(e);return}const t=(this.options.maxImageSize||5)*1024*1024;e.forEach(i=>{if(!i||!i.type.startsWith("image/"))return;if(i.size>t){const o=`Image "${i.name}" exceeds the ${this.options.maxImageSize||5} MB size limit.`;this.context.triggerEvent("imageError",{file:i,message:o}),console.warn(`[AutumnNote] ${o}`);return}const s=i.name.replace(/\.[^.]+$/,"");this._compressImage(i).then(o=>{const a=this._dataUrlToBlob(o),r=URL.createObjectURL(a);this._blobRegistry.set(r,o),this.context.invoke("editor.insertImage",r,s)}).catch(o=>{var r;const a=`Image "${i.name}" could not be processed.`;this.context.triggerEvent("imageError",{file:i,message:a,error:o}),(typeof process>"u"||((r=process.env)==null?void 0:r.NODE_ENV)!=="production")&&console.warn("[AutumnNote]",a,o)})})}resolveImages(e){return!this._blobRegistry||!this._blobRegistry.size?e:e.replace(/blob:[^"'> \t\n\r]*/g,t=>this._blobRegistry.get(t)||t)}_dataUrlToBlob(e){const[t,i]=e.split(","),s=t.match(/:(.*?);/)[1],o=atob(i),a=new Uint8Array(o.length);for(let r=0;r<o.length;r++)a[r]=o.charCodeAt(r);return new Blob([a],{type:s})}_compressImage(e){return new Promise(s=>{const o=URL.createObjectURL(e),a=new Image;a.onload=()=>{URL.revokeObjectURL(o);let{width:r,height:l}=a;(r>1920||l>1920)&&(r>=l?(l=Math.round(l*1920/r),r=1920):(r=Math.round(r*1920/l),l=1920));const h=document.createElement("canvas");h.width=r,h.height=l;const p=h.getContext("2d");if(!p){const u=new FileReader;u.onload=f=>s(f.target.result),u.readAsDataURL(e);return}p.drawImage(a,0,0,r,l);const m=h.toDataURL("image/webp",.85);s(m.startsWith("data:image/webp")?m:h.toDataURL("image/jpeg",.85))},a.onerror=()=>{URL.revokeObjectURL(o);const r=new FileReader;r.onload=l=>s(l.target.result),r.readAsDataURL(e)},a.src=o})}_placeCaretAtPoint(e,t){let i;if(document.caretRangeFromPoint)i=document.caretRangeFromPoint(e,t);else if(document.caretPositionFromPoint){const o=document.caretPositionFromPoint(e,t);o&&(i=document.createRange(),i.setStart(o.offsetNode,o.offset),i.collapse(!0))}if(!i)return;const s=window.getSelection();s&&(s.removeAllRanges(),s.addRange(i))}_escapeHTML(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}}class Qt{constructor(e){this.context=e,this.options=e.options,this._disposers=[]}initialize(){const e=this.context.layoutInfo.editable,t=this.options.placeholder||"";t&&(e.dataset.placeholder=t);const i=()=>this._update(),s=d(e,"input",i),o=d(e,"focus",i),a=d(e,"blur",i);return this._disposers.push(s,o,a),this._update(),this}destroy(){this._disposers.forEach(e=>e()),this._disposers=[]}_update(){const e=this.context.layoutInfo.editable,t=document.activeElement===e,i=!e.textContent.trim()&&!e.querySelector("img, table, hr");e.classList.toggle("an-placeholder",i&&!t)}}class Zt{constructor(e){this.context=e,this.options=e.options,this._active=!1,this._textarea=null,this._disposers=[]}initialize(){return this}destroy(){this._disposers.forEach(e=>e()),this._disposers=[],this._textarea&&this._textarea.parentNode&&this._textarea.parentNode.removeChild(this._textarea),this._textarea=null}toggle(){this._active?this.deactivate():this.activate()}isActive(){return this._active}activate(){if(this._active)return;const{editable:e}=this.context.layoutInfo,t=e.innerHTML;this._textarea=c("textarea",{class:"an-codeview",spellcheck:"false",autocomplete:"off",autocorrect:"off",autocapitalize:"off"}),this._textarea.value=this._prettyPrint(t),e.style.display="none",e.parentNode.insertBefore(this._textarea,e.nextSibling),this._active=!0,this.context.invoke("toolbar.refresh")}deactivate(){if(!this._active||!this._textarea)return;const{editable:e}=this.context.layoutInfo;e.innerHTML=W(this._textarea.value,{allowIframes:!0}),this._textarea.parentNode.removeChild(this._textarea),this._textarea=null,e.style.display="",this._active=!1,this.context.invoke("toolbar.refresh"),this.context.invoke("editor.afterCommand")}_prettyPrint(e){const t=/^<(a|abbr|b|bdo|br|button|cite|code|dfn|em|i|img|input|kbd|label|output|q|samp|select|small|span|strong|sub|sup|textarea|time|tt|u|var)([\s>/])/i;let i=0;return e.replace(/>\s*</g,(s,o,a)=>{const r=a.slice(o+1);return t.test(r.trimStart())?"><":`>
|
|
69
|
+
<`}).split(`
|
|
70
|
+
`).map(s=>{const o=s.trim();if(!o)return"";/^<\//.test(o)&&(i=Math.max(0,i-1));const a=" ".repeat(i)+o;return/^<[^/!][^>]*[^/]>/.test(o)&&!t.test(o)&&!/^<(br|hr|img|input|link|meta)/.test(o)&&i++,a}).filter(Boolean).join(`
|
|
71
|
+
`)}}class Jt{constructor(e){this.context=e,this._active=!1,this._disposers=[],this._prevHeight=""}initialize(){const e=d(document,"keydown",t=>{this._active&&$(t,P.ESCAPE)&&this.deactivate()});return this._disposers.push(e),this}destroy(){this._disposers.forEach(e=>e()),this._disposers=[],this._active&&this.deactivate()}toggle(){this._active?this.deactivate():this.activate()}isActive(){return this._active}activate(){if(this._active)return;const e=this.context.layoutInfo.container;this._prevHeight=e.style.height,e.classList.add("an-fullscreen"),e.style.height="",document.body.style.overflow="hidden",this._active=!0,this.context.invoke("toolbar.refresh")}deactivate(){if(!this._active)return;const e=this.context.layoutInfo.container;e.classList.remove("an-fullscreen"),e.style.height=this._prevHeight,document.body.style.overflow="",this._active=!1,this.context.invoke("toolbar.refresh")}}class ei{constructor(e){this.context=e,this.options=e.options,this._dialog=null,this._disposers=[],this._savedRange=null}initialize(){return this._dialog=this._buildDialog(),document.body.appendChild(this._dialog),this}destroy(){this._disposers.forEach(e=>e()),this._disposers=[],this._dialog&&this._dialog.parentNode&&this._dialog.parentNode.removeChild(this._dialog),this._dialog=null}show(){G(e=>{this._savedRange=e}),this._prefill(),this._open()}_buildDialog(){const e=c("div",{class:"an-dialog-overlay",role:"dialog","aria-modal":"true","aria-label":"Insert link"}),t=c("div",{class:"an-dialog-box"}),i=c("h3",{class:"an-dialog-title"});i.textContent="Insert Link";const s=c("label",{class:"an-label"});s.textContent="URL";const o=c("input",{type:"url",class:"an-input",placeholder:"https://",id:"an-link-url",name:"url",autocomplete:"off"});this._urlInput=o;const a=c("label",{class:"an-label"});a.textContent="Display Text";const r=c("input",{type:"text",class:"an-input",placeholder:"Link text",id:"an-link-text",name:"linkText",autocomplete:"off"});this._textInput=r;const l=c("label",{class:"an-label an-label-inline"}),h=c("input",{type:"checkbox",id:"an-link-newtab",name:"openInNewTab"});this._tabCheckbox=h,l.appendChild(h),l.appendChild(document.createTextNode(" Open in new tab"));const p=c("div",{class:"an-dialog-actions"}),m=c("button",{type:"button",class:"an-btn an-btn-primary"});m.textContent="Insert";const u=c("button",{type:"button",class:"an-btn"});u.textContent="Cancel",p.appendChild(m),p.appendChild(u),t.append(i,s,o,a,r,l,p),e.appendChild(t);const f=d(m,"click",()=>this._onInsert()),g=d(u,"click",()=>this._close()),b=d(e,"click",v=>{v.target===e&&this._close()}),C=d(o,"keydown",v=>{v.key==="Enter"&&(v.preventDefault(),this._onInsert())}),T=d(r,"keydown",v=>{v.key==="Enter"&&(v.preventDefault(),this._onInsert())});return this._disposers.push(f,g,b,C,T),e}_prefill(){const e=window.getSelection();let t=null;if(e&&e.rangeCount>0){let i=e.getRangeAt(0).startContainer;for(;i;){if(i.nodeName==="A"){t=i;break}i=i.parentNode}}t?(this._urlInput.value=t.getAttribute("href")||"",this._textInput.value=t.textContent||"",this._tabCheckbox.checked=t.getAttribute("target")==="_blank"):(this._urlInput.value="",this._textInput.value=e?e.toString():"",this._tabCheckbox.checked=!1)}_onInsert(){let e=this._urlInput.value.trim();const t=this._textInput.value.trim(),i=this._tabCheckbox.checked;if(!e){this._urlInput.focus();return}/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(e)||(e="https://"+e);try{const s=new URL(e);if(/^javascript:/i.test(s.protocol)||/^vbscript:/i.test(s.protocol)||/^data:/i.test(s.protocol)){this._urlInput.focus();return}}catch{this._urlInput.focus();return}this._savedRange&&this._savedRange.select(),this.context.invoke("editor.insertLink",e,t,i),this._close()}_open(){this._dialog&&(this._dialog.style.display="flex",this._removeTrap=O(this._dialog,()=>this._close()),setTimeout(()=>this._urlInput&&this._urlInput.focus(),50))}_close(){this._dialog&&(this._dialog.style.display="none"),this._removeTrap&&(this._removeTrap(),this._removeTrap=null),this._savedRange=null}}class ti{constructor(e){this.context=e,this.options=e.options,this._dialog=null,this._disposers=[],this._savedRange=null}initialize(){return this._dialog=this._buildDialog(),document.body.appendChild(this._dialog),this}destroy(){this._disposers.forEach(e=>e()),this._disposers=[],this._dialog&&this._dialog.parentNode&&this._dialog.parentNode.removeChild(this._dialog),this._dialog=null}show(){G(e=>{this._savedRange=e}),this._urlInput.value="",this._altInput.value="",this._fileInput&&(this._fileInput.value=""),this._open()}_buildDialog(){const e=c("div",{class:"an-dialog-overlay",role:"dialog","aria-modal":"true","aria-label":"Insert image"}),t=c("div",{class:"an-dialog-box"}),i=c("h3",{class:"an-dialog-title"});i.textContent="Insert Image";const s=c("label",{class:"an-label"});s.textContent="Image URL";const o=c("input",{type:"url",class:"an-input",placeholder:"https://example.com/image.png",autocomplete:"off"});this._urlInput=o;const a=c("label",{class:"an-label"});a.textContent="Alt Text";const r=c("input",{type:"text",class:"an-input",placeholder:"Describe the image",autocomplete:"off"});this._altInput=r,t.append(i,s,o,a,r);const l=c("label",{class:"an-label"});l.textContent="Alignment";const h=c("div",{class:"an-align-row"});if([{value:"",label:"None"},{value:"left",label:"Left"},{value:"center",label:"Center"},{value:"right",label:"Right"}].forEach(({value:_,label:y})=>{const w=`an-align-${_||"none"}`,k=c("input",{type:"radio",name:"an-img-align",id:w,value:_});_===""&&(k.checked=!0);const I=c("label",{for:w,class:"an-align-label"});I.textContent=y,h.append(k,I)}),this._alignRow=h,t.append(l,h),this.options.allowImageUpload!==!1){const _=c("label",{class:"an-label"});_.textContent="Or upload a file";const y=c("input",{type:"file",class:"an-input",accept:"image/*"});this._fileInput=y;const w=d(y,"change",()=>this._onFileChange());this._disposers.push(w),t.append(_,y)}const m=c("div",{class:"an-dialog-actions"}),u=c("button",{type:"button",class:"an-btn an-btn-primary"});u.textContent="Insert";const f=c("button",{type:"button",class:"an-btn"});f.textContent="Cancel",m.appendChild(u),m.appendChild(f),t.append(m),e.appendChild(t);const g=d(u,"click",()=>this._onInsert()),b=d(f,"click",()=>this._close()),C=d(e,"click",_=>{_.target===e&&this._close()}),T=d(o,"keydown",_=>{_.key==="Enter"&&(_.preventDefault(),this._onInsert())}),v=d(r,"keydown",_=>{_.key==="Enter"&&(_.preventDefault(),this._onInsert())});return this._disposers.push(g,b,C,T,v),e}_onFileChange(){const e=this._fileInput&&this._fileInput.files&&this._fileInput.files[0];if(!e||!e.type.startsWith("image/"))return;const t=(this.options.maxImageSize||5)*1024*1024;if(e.size>t){const s=`Image file is too large. Maximum allowed size is ${this.options.maxImageSize||5} MB.`;console.warn("[AutumnNote] ImageDialog:",s),this.context.triggerEvent("imageError",{file:e,message:s}),this._fileInput.value="";return}const i=new FileReader;i.onload=s=>{this._urlInput.value=s.target.result},i.readAsDataURL(e)}_onInsert(){const e=this._urlInput.value.trim(),t=this._altInput.value.trim(),i=this._alignRow&&this._alignRow.querySelector('input[name="an-img-align"]:checked'),s=i?i.value:"";if(!e){this._urlInput.focus();return}this._savedRange&&this._savedRange.select(),this.context.invoke("editor.insertImage",e,t,s),this._close()}_open(){this._dialog&&(this._dialog.style.display="flex",this._removeTrap=O(this._dialog,()=>this._close()),setTimeout(()=>this._urlInput&&this._urlInput.focus(),50))}_close(){this._dialog&&(this._dialog.style.display="none"),this._removeTrap&&(this._removeTrap(),this._removeTrap=null),this._savedRange=null}}class ii{constructor(e){this.context=e,this.options=e.options,this._dialog=null,this._disposers=[],this._savedRange=null}initialize(){return this._dialog=this._buildDialog(),document.body.appendChild(this._dialog),this}destroy(){this._disposers.forEach(e=>e()),this._disposers=[],this._dialog&&this._dialog.parentNode&&this._dialog.parentNode.removeChild(this._dialog),this._dialog=null}show(){G(e=>{this._savedRange=e}),this._urlInput.value="",this._widthInput.value="560",this._hintEl.textContent="",this._open()}_buildDialog(){const e=c("div",{class:"an-dialog-overlay",role:"dialog","aria-modal":"true","aria-label":"Insert video"}),t=c("div",{class:"an-dialog-box"}),i=c("h3",{class:"an-dialog-title"});i.textContent="Insert Video";const s=c("label",{class:"an-label"});s.textContent="Video URL";const o=c("input",{type:"url",class:"an-input",placeholder:"YouTube, Vimeo, or direct .mp4 URL",autocomplete:"off"});this._urlInput=o;const a=c("p",{class:"an-dialog-hint"});this._hintEl=a;const r=c("label",{class:"an-label"});r.textContent="Width (px)";const l=c("input",{type:"number",class:"an-input",placeholder:"560",min:"80",max:"1920",value:"560"});this._widthInput=l;const h=c("div",{class:"an-dialog-actions"}),p=c("button",{type:"button",class:"an-btn an-btn-primary"});p.textContent="Insert";const m=c("button",{type:"button",class:"an-btn"});m.textContent="Cancel",h.appendChild(p),h.appendChild(m),t.append(i,s,o,a,r,l,h),e.appendChild(t);const u=d(o,"input",()=>{const T=this._parseVideoUrl(o.value.trim());a.textContent=T?`Detected: ${T.type}`:o.value?"Unknown format — will try direct video embed":""}),f=d(p,"click",()=>this._onInsert()),g=d(m,"click",()=>this._close()),b=d(e,"click",T=>{T.target===e&&this._close()}),C=d(o,"keydown",T=>{T.key==="Enter"&&(T.preventDefault(),this._onInsert())});return this._disposers.push(u,f,g,b,C),e}_onInsert(){const e=this._urlInput.value.trim(),t=Math.max(80,parseInt(this._widthInput.value,10)||560);if(!e){this._urlInput.focus();return}const i=this._buildEmbedHtml(e,t);if(!i){this._hintEl.textContent="Invalid URL — please enter a valid video link.",this._urlInput.focus();return}this._savedRange&&this._savedRange.select(),this.context.invoke("editor.insertVideo",i),this._close()}_open(){this._dialog&&(this._dialog.style.display="flex",this._removeTrap=O(this._dialog,()=>this._close()),setTimeout(()=>this._urlInput&&this._urlInput.focus(),50))}_close(){this._dialog&&(this._dialog.style.display="none"),this._removeTrap&&(this._removeTrap(),this._removeTrap=null),this._savedRange=null}_parseVideoUrl(e){if(!e)return null;try{const a=new URL(e);if(/^javascript:/i.test(a.protocol)||/^vbscript:/i.test(a.protocol))return null}catch{return null}const t=e.match(/(?:youtube\.com\/watch\?(?:.*&)?v=|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/);if(t)return{type:"YouTube",embedUrl:`https://www.youtube.com/embed/${t[1]}`};const i=e.match(/youtu\.be\/([a-zA-Z0-9_-]{11})/);if(i)return{type:"YouTube",embedUrl:`https://www.youtube.com/embed/${i[1]}`};const s=e.match(/youtube\.com\/shorts\/([a-zA-Z0-9_-]{11})/);if(s)return{type:"YouTube Shorts",embedUrl:`https://www.youtube.com/embed/${s[1]}`};const o=e.match(/vimeo\.com\/(\d+)/);return o?{type:"Vimeo",embedUrl:`https://player.vimeo.com/video/${o[1]}`}:/\.(mp4|webm|ogg|ogv|mov)(#.*|\?.*)?$/i.test(e)?{type:"Direct video",embedUrl:e}:null}_buildEmbedHtml(e,t){const i=this._parseVideoUrl(e),s=Math.round(t*9/16);if(i&&(i.type==="YouTube"||i.type==="YouTube Shorts"||i.type==="Vimeo")){const r=`${i.type} video player`;return`<div class="an-video-wrapper" style="position:relative;display:block;width:${t}px;max-width:100%"><iframe src="${i.embedUrl}" width="${t}" height="${s}" title="${r}" frameborder="0" allowfullscreen allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" style="display:block;max-width:100%"></iframe><div class="an-video-shield"></div></div>`}if(i&&i.type==="Direct video"){const r=i.embedUrl.replace(/"/g,"%22");return`<div class="an-video-wrapper" style="position:relative;display:block;width:${t}px;max-width:100%"><video src="${r}" width="${t}" height="${s}" controls style="display:block;max-width:100%"></video><div class="an-video-shield"></div></div>`}const o=(()=>{try{const r=new URL(e);return/^javascript:/i.test(r.protocol)||/^vbscript:/i.test(r.protocol)?null:e}catch{return null}})();if(!o)return null;const a=o.replace(/"/g,"%22");return`<div class="an-video-wrapper" style="position:relative;display:block;width:${t}px;max-width:100%"><video src="${a}" width="${t}" height="${s}" controls style="display:block;max-width:100%"></video><div class="an-video-shield"></div></div>`}}const si=[{pos:"nw",cursor:"nw-resize"},{pos:"n",cursor:"n-resize"},{pos:"ne",cursor:"ne-resize"},{pos:"e",cursor:"e-resize"},{pos:"se",cursor:"se-resize"},{pos:"s",cursor:"s-resize"},{pos:"sw",cursor:"sw-resize"},{pos:"w",cursor:"w-resize"}];class oi{constructor(e){this.context=e,this._activeImg=null,this._overlay=null,this._disposers=[],this._positionRaf=null}initialize(){this._overlay=this._buildOverlay();const e=this.context.layoutInfo.editable.closest(".an-container")||document.body;e.appendChild(this._overlay),this._container=e;const t=this.context.layoutInfo.editable;return this._disposers.push(d(t,"click",i=>this._onEditorClick(i)),d(t,"contextmenu",i=>{const s=i.target.closest("img");s&&this._select(s)}),d(document,"click",i=>this._onDocClick(i)),d(window,"scroll",()=>this._updateOverlayPosition(),{passive:!0}),d(window,"resize",()=>this._updateOverlayPosition()),d(t,"scroll",()=>this._updateOverlayPosition(),{passive:!0})),this}destroy(){this._disposers.forEach(e=>e()),this._disposers=[],this._dragDisposers&&(this._dragDisposers.forEach(e=>e()),this._dragDisposers=null),this._positionRaf&&(cancelAnimationFrame(this._positionRaf),this._positionRaf=null),this._deselect(),this._overlay&&this._overlay.parentNode&&this._overlay.parentNode.removeChild(this._overlay),this._overlay=null}getActiveImage(){return this._activeImg}updateOverlay(){this._updateOverlayPosition()}deselect(){this._deselect()}_buildOverlay(){const e=document.createElement("div");return e.className="an-image-resizer",e.style.display="none",si.forEach(({pos:t})=>{const i=document.createElement("div");i.className=`an-resize-handle an-resize-${t}`,i.dataset.handle=t,this._disposers.push(d(i,"mousedown",s=>{s.preventDefault(),s.stopPropagation(),this._startResize(s,t)})),e.appendChild(i)}),e}_onEditorClick(e){const t=e.target.closest("img");t&&(e.preventDefault(),this._select(t))}_onDocClick(e){this._activeImg&&e.target!==this._activeImg&&(this._overlay&&this._overlay.contains(e.target)||e.target.closest(".an-contextmenu")||this._deselect())}_select(e){this._activeImg&&this._activeImg!==e&&this._activeImg.classList.remove("an-image-selected"),this._activeImg=e,e.classList.add("an-image-selected"),this._updateOverlayPosition(),this._overlay.style.display="block"}_deselect(){this._activeImg&&(this._activeImg.classList.remove("an-image-selected"),this._activeImg=null),this._overlay&&(this._overlay.style.display="none")}_updateOverlayPosition(){this._positionRaf&&cancelAnimationFrame(this._positionRaf),this._positionRaf=requestAnimationFrame(()=>{this._positionRaf=null,this._updateOverlayPositionNow()})}_updateOverlayPositionNow(){if(!this._activeImg||!this._overlay)return;const e=this._overlay.offsetParent||this._container,t=e.getBoundingClientRect(),i=this._activeImg.getBoundingClientRect(),s=i.left-t.left+e.scrollLeft,o=i.top-t.top+e.scrollTop;this._overlay.style.left=`${s}px`,this._overlay.style.top=`${o}px`,this._overlay.style.width=`${i.width}px`,this._overlay.style.height=`${i.height}px`}_startResize(e,t){const i=this._activeImg;if(!i)return;const s=e.clientX,o=e.clientY,a=i.offsetWidth||i.naturalWidth||100,r=i.offsetHeight||i.naturalHeight||100,l=a/r,h=t.length===2,p=this.context.layoutInfo.editable,m=f=>{const g=f.clientX-s,b=f.clientY-o,C=p.clientWidth||1/0;let T=a,v=r;t.includes("e")&&(T=Math.max(20,a+g)),t.includes("w")&&(T=Math.max(20,a-g)),t.includes("s")&&(v=Math.max(20,r+b)),t.includes("n")&&(v=Math.max(20,r-b)),T=Math.min(T,C),h&&(Math.abs(g)>=Math.abs(b)||(T=Math.min(Math.max(20,Math.round(v*l)),C)),v=Math.max(20,Math.round(T/l))),i.style.width=`${T}px`,i.style.height=`${v}px`,this._updateOverlayPosition()},u=()=>{document.removeEventListener("mousemove",m),document.removeEventListener("mouseup",u),this._dragDisposers=null,this.context.invoke("editor.afterCommand")};document.addEventListener("mousemove",m),document.addEventListener("mouseup",u),this._dragDisposers=[()=>document.removeEventListener("mousemove",m),()=>document.removeEventListener("mouseup",u)]}}const ni=[{pos:"nw",cursor:"nw-resize"},{pos:"n",cursor:"n-resize"},{pos:"ne",cursor:"ne-resize"},{pos:"e",cursor:"e-resize"},{pos:"se",cursor:"se-resize"},{pos:"s",cursor:"s-resize"},{pos:"sw",cursor:"sw-resize"},{pos:"w",cursor:"w-resize"}];class ai{constructor(e){this.context=e,this._activeWrapper=null,this._overlay=null,this._disposers=[],this._positionRaf=null}initialize(){this._overlay=this._buildOverlay();const e=this.context.layoutInfo.editable.closest(".an-container")||document.body;e.appendChild(this._overlay),this._container=e;const t=this.context.layoutInfo.editable;return this._disposers.push(d(t,"click",i=>this._onEditorClick(i)),d(t,"contextmenu",i=>{const s=this._findWrapper(i.target);s&&this._select(s)}),d(document,"click",i=>this._onDocClick(i)),d(window,"scroll",()=>this._updateOverlayPosition(),{passive:!0}),d(window,"resize",()=>this._updateOverlayPosition()),d(t,"scroll",()=>this._updateOverlayPosition(),{passive:!0})),this}destroy(){this._disposers.forEach(e=>e()),this._disposers=[],this._dragDisposers&&(this._dragDisposers.forEach(e=>e()),this._dragDisposers=null),this._positionRaf&&(cancelAnimationFrame(this._positionRaf),this._positionRaf=null),this._deselect(),this._overlay&&this._overlay.parentNode&&this._overlay.parentNode.removeChild(this._overlay),this._overlay=null}getActiveWrapper(){return this._activeWrapper}updateOverlay(){this._updateOverlayPosition()}deselect(){this._deselect()}_findWrapper(e){if(!e||!(e instanceof Element))return null;if(e.classList&&e.classList.contains("an-video-wrapper"))return e;const t=e.closest(".an-video-wrapper");return t||null}_buildOverlay(){const e=document.createElement("div");return e.className="an-video-resizer",e.style.display="none",ni.forEach(({pos:t})=>{const i=document.createElement("div");i.className=`an-resize-handle an-resize-${t}`,i.dataset.handle=t,this._disposers.push(d(i,"mousedown",s=>{s.preventDefault(),s.stopPropagation(),this._startResize(s,t)})),e.appendChild(i)}),e}_onEditorClick(e){const t=this._findWrapper(e.target);t&&(e.preventDefault(),this._select(t))}_onDocClick(e){this._activeWrapper&&(this._activeWrapper.contains(e.target)||this._overlay&&this._overlay.contains(e.target)||e.target.closest(".an-contextmenu")||this._deselect())}_select(e){this._activeWrapper&&this._activeWrapper!==e&&this._activeWrapper.classList.remove("an-video-selected"),this._activeWrapper=e,e.classList.add("an-video-selected"),this._updateOverlayPosition(),this._overlay.style.display="block"}_deselect(){this._activeWrapper&&(this._activeWrapper.classList.remove("an-video-selected"),this._activeWrapper=null),this._overlay&&(this._overlay.style.display="none")}_updateOverlayPosition(){this._positionRaf&&cancelAnimationFrame(this._positionRaf),this._positionRaf=requestAnimationFrame(()=>{this._positionRaf=null,this._updateOverlayPositionNow()})}_updateOverlayPositionNow(){if(!this._activeWrapper||!this._overlay)return;const e=this._overlay.offsetParent||this._container,t=e.getBoundingClientRect(),i=this._activeWrapper.getBoundingClientRect(),s=i.left-t.left+e.scrollLeft,o=i.top-t.top+e.scrollTop;this._overlay.style.left=`${s}px`,this._overlay.style.top=`${o}px`,this._overlay.style.width=`${i.width}px`,this._overlay.style.height=`${i.height}px`}_startResize(e,t){const i=this._activeWrapper;if(!i)return;const s=i.querySelector("iframe, video"),o=e.clientX,a=e.clientY,r=i.offsetWidth||560,l=i.offsetHeight||315,h=r/l,p=t.length===2,m=this.context.layoutInfo.editable,u=g=>{const b=g.clientX-o,C=g.clientY-a,T=m.clientWidth||1/0;let v=r,_=l;t.includes("e")&&(v=Math.max(80,r+b)),t.includes("w")&&(v=Math.max(80,r-b)),t.includes("s")&&(_=Math.max(45,l+C)),t.includes("n")&&(_=Math.max(45,l-C)),v=Math.min(v,T),p&&(Math.abs(b)>=Math.abs(C)||(v=Math.min(Math.max(80,Math.round(_*h)),T)),_=Math.max(45,Math.round(v/h))),i.style.width=`${v}px`,i.style.height=`${_}px`,s&&(s.width=v,s.height=_,s.style.width=`${v}px`,s.style.height=`${_}px`),this._updateOverlayPosition()},f=()=>{document.removeEventListener("mousemove",u),document.removeEventListener("mouseup",f),this._dragDisposers=null,this.context.invoke("editor.afterCommand")};document.addEventListener("mousemove",u),document.addEventListener("mouseup",f),this._dragDisposers=[()=>document.removeEventListener("mousemove",u),()=>document.removeEventListener("mouseup",f)]}}const ae={open:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>',edit:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>',unlink:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18.84 12.25l1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71"/><path d="M5.17 11.75l-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71"/><line x1="8" y1="2" x2="8" y2="5"/><line x1="2" y1="8" x2="5" y2="8"/><line x1="16" y1="19" x2="16" y2="22"/><line x1="19" y1="16" x2="22" y2="16"/></svg>',copy:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>'},li=120,ri=200;class ci{constructor(e){this.context=e,this._el=null,this._activeAnchor=null,this._showTimer=null,this._hideTimer=null,this._disposers=[]}initialize(){this._el=this._buildTooltip(),document.body.appendChild(this._el);const e=this.context.layoutInfo.editable;return this._disposers.push(d(e,"mouseover",t=>{const i=t.target.closest("a[href]");i&&e.contains(i)&&this._scheduleShow(i)}),d(e,"mouseout",t=>{const i=t.relatedTarget;(!i||!e.contains(i)&&!this._el.contains(i))&&this._scheduleHide()})),this}destroy(){this._clearTimers(),this._disposers.forEach(e=>e()),this._disposers=[],this._el&&this._el.parentNode&&this._el.parentNode.removeChild(this._el),this._el=null}_buildTooltip(){const e=c("div",{class:"an-link-tooltip",role:"toolbar","aria-label":"Link actions"});return e.style.display="none",this._urlLabel=c("span",{class:"an-link-tooltip-url"}),e.appendChild(this._urlLabel),e.appendChild(c("div",{class:"an-link-tooltip-sep"})),this._openBtn=this._makeBtn(ae.open,"Open link",()=>this._openLink()),this._copyBtn=this._makeBtn(ae.copy,"Copy URL",()=>this._copyLink()),this._editBtn=this._makeBtn(ae.edit,"Edit link",()=>this._editLink()),this._unlinkBtn=this._makeBtn(ae.unlink,"Remove link",()=>this._unlink()),e.appendChild(this._openBtn),e.appendChild(this._copyBtn),e.appendChild(this._editBtn),e.appendChild(this._unlinkBtn),this._disposers.push(d(e,"mouseenter",()=>this._clearTimers()),d(e,"mouseleave",()=>this._scheduleHide())),e}_makeBtn(e,t,i){const s=c("button",{type:"button",class:"an-link-tooltip-btn",title:t});return s.innerHTML=e,this._disposers.push(d(s,"click",o=>{o.preventDefault(),o.stopPropagation(),i()})),s}_scheduleShow(e){this._activeAnchor===e&&this._el.style.display!=="none"||(clearTimeout(this._hideTimer),this._hideTimer=null,clearTimeout(this._showTimer),this._showTimer=setTimeout(()=>{this._activeAnchor=e,this._show(e)},li))}_scheduleHide(){clearTimeout(this._showTimer),this._showTimer=null,!this._hideTimer&&(this._hideTimer=setTimeout(()=>{this._hide()},ri))}_show(e){const t=e.getAttribute("href")||"";this._urlLabel.textContent=this._truncateUrl(t),this._urlLabel.title=t,this._el.style.display="flex",this._positionNear(e)}_hide(){this._el.style.display="none",this._activeAnchor=null,this._clearTimers()}_clearTimers(){clearTimeout(this._showTimer),clearTimeout(this._hideTimer),this._showTimer=null,this._hideTimer=null}_positionNear(e){const t=e.getBoundingClientRect(),i=this._el.offsetWidth||260,s=this._el.offsetHeight||34,o=6;let a=t.bottom+o,r=t.left;a+s>window.innerHeight-o&&(a=t.top-s-o),r+i>window.innerWidth-o&&(r=window.innerWidth-i-o),r<o&&(r=o),this._el.style.top=`${a}px`,this._el.style.left=`${r}px`}_truncateUrl(e){try{const t=new URL(e),i=t.host+(t.pathname!=="/"?t.pathname:"");return i.length>48?i.slice(0,48)+"…":i}catch{return e.length>48?e.slice(0,48)+"…":e}}_openLink(){const e=this._activeAnchor&&this._activeAnchor.getAttribute("href");e&&window.open(e,"_blank","noopener,noreferrer"),this._hide()}_copyLink(){const e=this._activeAnchor&&this._activeAnchor.getAttribute("href");e&&navigator.clipboard.writeText(e).catch(()=>{const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t)}),this._copyBtn&&(this._copyBtn.classList.add("an-link-tooltip-btn--copied"),setTimeout(()=>this._copyBtn&&this._copyBtn.classList.remove("an-link-tooltip-btn--copied"),1e3))}_editLink(){const e=this._activeAnchor;if(!e)return;this._hide();const t=window.getSelection(),i=document.createRange();i.selectNodeContents(e),t.removeAllRanges(),t.addRange(i),this.context.invoke("linkDialog.show")}_unlink(){const e=this._activeAnchor;if(!e)return;this._hide();const t=window.getSelection(),i=document.createRange();i.selectNode(e),t.removeAllRanges(),t.addRange(i),document.execCommand("unlink"),this.context.invoke("editor.afterCommand")}}const q={floatLeft:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="8" height="8" rx="1"/><line x1="12" y1="6" x2="22" y2="6"/><line x1="12" y1="9" x2="22" y2="9"/><line x1="12" y1="12" x2="22" y2="12"/><line x1="2" y1="16" x2="22" y2="16"/><line x1="2" y1="20" x2="18" y2="20"/></svg>',floatRight:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="14" y="4" width="8" height="8" rx="1"/><line x1="2" y1="6" x2="12" y2="6"/><line x1="2" y1="9" x2="12" y2="9"/><line x1="2" y1="12" x2="12" y2="12"/><line x1="2" y1="16" x2="22" y2="16"/><line x1="2" y1="20" x2="18" y2="20"/></svg>',floatNone:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="8" height="8" rx="1"/><line x1="3" y1="15" x2="21" y2="15"/><line x1="3" y1="19" x2="17" y2="19"/></svg>',alignCenter:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="4" width="10" height="8" rx="1"/><line x1="3" y1="16" x2="21" y2="16"/><line x1="6" y1="20" x2="18" y2="20"/></svg>',originalSize:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>',deleteImg:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>',caption:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="11" rx="2"/><line x1="6" y1="18" x2="18" y2="18"/><line x1="9" y1="21" x2="15" y2="21"/></svg>'},hi=100,di=180;class pi{constructor(e){this.context=e,this._el=null,this._activeImg=null,this._showTimer=null,this._hideTimer=null,this._disposers=[]}initialize(){this._el=this._buildTooltip(),document.body.appendChild(this._el);const e=this.context.layoutInfo.editable;return this._disposers.push(d(e,"mouseover",t=>{const i=t.target.closest("img");i&&e.contains(i)&&!i.closest("a[href]")&&this._scheduleShow(i)}),d(e,"mouseout",t=>{const i=t.relatedTarget;(!i||!e.contains(i)&&!this._el.contains(i))&&this._scheduleHide()}),d(document,"click",t=>{this._activeImg&&!this._activeImg.contains(t.target)&&!this._el.contains(t.target)&&this._hide()})),this}destroy(){this._clearTimers(),this._disposers.forEach(e=>e()),this._disposers=[],this._el&&this._el.parentNode&&this._el.parentNode.removeChild(this._el),this._el=null}_buildTooltip(){const e=c("div",{class:"an-link-tooltip an-image-tooltip",role:"toolbar","aria-label":"Image actions"});return e.style.display="none",this._label=c("span",{class:"an-link-tooltip-url"}),this._label.textContent="Image",e.appendChild(this._label),e.appendChild(c("div",{class:"an-link-tooltip-sep"})),this._floatLeftBtn=this._makeBtn(q.floatLeft,"Float Left",()=>this._setFloat("left")),this._floatNoneBtn=this._makeBtn(q.floatNone,"No Float",()=>this._setFloat("")),this._alignCenterBtn=this._makeBtn(q.alignCenter,"Align Center",()=>this._setCenter()),this._floatRightBtn=this._makeBtn(q.floatRight,"Float Right",()=>this._setFloat("right")),e.appendChild(this._floatLeftBtn),e.appendChild(this._floatNoneBtn),e.appendChild(this._alignCenterBtn),e.appendChild(this._floatRightBtn),e.appendChild(c("div",{class:"an-link-tooltip-sep"})),this._originalBtn=this._makeBtn(q.originalSize,"Original Size",()=>this._resetSize()),e.appendChild(this._originalBtn),e.appendChild(c("div",{class:"an-link-tooltip-sep"})),this._captionBtn=this._makeBtn(q.caption,"Add / Edit Caption",()=>this._toggleCaption()),e.appendChild(this._captionBtn),e.appendChild(c("div",{class:"an-link-tooltip-sep"})),this._deleteBtn=this._makeBtn(q.deleteImg,"Delete Image",()=>this._delete(),!0),e.appendChild(this._deleteBtn),this._disposers.push(d(e,"mouseenter",()=>this._clearTimers()),d(e,"mouseleave",()=>this._scheduleHide())),e}_makeBtn(e,t,i,s=!1){const o=c("button",{type:"button",class:s?"an-link-tooltip-btn an-link-tooltip-btn--danger":"an-link-tooltip-btn",title:t});return o.innerHTML=e,this._disposers.push(d(o,"click",a=>{a.preventDefault(),a.stopPropagation(),i()})),o}_scheduleShow(e){this._activeImg===e&&this._el.style.display!=="none"||(clearTimeout(this._hideTimer),this._hideTimer=null,clearTimeout(this._showTimer),this._showTimer=setTimeout(()=>{this._activeImg=e,this._show(e)},hi))}_scheduleHide(){clearTimeout(this._showTimer),this._showTimer=null,!this._hideTimer&&(this._hideTimer=setTimeout(()=>this._hide(),di))}_show(e){this._el.style.display="flex",this._positionNear(e)}_hide(){this._el.style.display="none",this._activeImg=null,this._clearTimers()}_clearTimers(){clearTimeout(this._showTimer),clearTimeout(this._hideTimer),this._showTimer=null,this._hideTimer=null}_positionNear(e){const t=e.getBoundingClientRect(),i=this._el.offsetWidth||220,s=this._el.offsetHeight||32,o=6;let a=t.bottom+o,r=t.left+(t.width-i)/2;a+s>window.innerHeight-o&&(a=t.top-s-o),r+i>window.innerWidth-o&&(r=window.innerWidth-i-o),r<o&&(r=o),this._el.style.top=`${a}px`,this._el.style.left=`${r}px`}_setFloat(e){const t=this._activeImg;if(!t)return;const i=t.closest("figure.an-figure")||t;i.style.float=e,i.style.display="",i.style.marginLeft=e==="right"?"12px":"",i.style.marginRight=e==="left"?"12px":"",this.context.invoke("editor.afterCommand"),this.context.invoke("imageResizer.updateOverlay"),this._positionNear(t)}_setCenter(){const e=this._activeImg;if(!e)return;const t=e.closest("figure.an-figure")||e;t.style.float="",t.style.display="block",t.style.marginLeft="auto",t.style.marginRight="auto",this.context.invoke("editor.afterCommand"),this.context.invoke("imageResizer.updateOverlay"),this._positionNear(e)}_resetSize(){const e=this._activeImg;e&&(e.style.width="",e.style.height="",this.context.invoke("editor.afterCommand"),this.context.invoke("imageResizer.updateOverlay"),this._positionNear(e))}_delete(){const e=this._activeImg;if(!e)return;this._hide(),this.context.invoke("imageResizer.deselect");const t=e.closest("figure.an-figure");t&&t.parentNode?t.parentNode.removeChild(t):e.parentNode&&e.parentNode.removeChild(e),this.context.invoke("editor.afterCommand")}_toggleCaption(){const e=this._activeImg;if(!e)return;const t=e.closest("figure.an-figure");if(t){const r=t.querySelector("figcaption.an-figcaption");if(r){this._hide();const l=document.createRange();l.selectNodeContents(r);const h=window.getSelection();h&&(h.removeAllRanges(),h.addRange(l))}return}const i=document.createElement("figure");i.className="an-figure",e.style.float?(i.style.float=e.style.float,i.style.marginLeft=e.style.marginLeft,i.style.marginRight=e.style.marginRight,e.style.float="",e.style.marginLeft="",e.style.marginRight=""):e.style.display==="block"&&e.style.marginLeft==="auto"&&(i.style.display="block",i.style.marginLeft="auto",i.style.marginRight="auto",e.style.display="",e.style.marginLeft="",e.style.marginRight="");const s=document.createElement("figcaption");s.className="an-figcaption",s.textContent="Caption",e.parentNode.insertBefore(i,e),i.appendChild(e),i.appendChild(s);const o=document.createRange();o.selectNodeContents(s);const a=window.getSelection();a&&(a.removeAllRanges(),a.addRange(o)),this.context.invoke("editor.afterCommand"),this.context.invoke("imageResizer.updateOverlay"),this._hide()}}const V={floatLeft:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="8" height="8" rx="1"/><line x1="12" y1="6" x2="22" y2="6"/><line x1="12" y1="9" x2="22" y2="9"/><line x1="12" y1="12" x2="22" y2="12"/><line x1="2" y1="16" x2="22" y2="16"/><line x1="2" y1="20" x2="18" y2="20"/></svg>',floatRight:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="14" y="4" width="8" height="8" rx="1"/><line x1="2" y1="6" x2="12" y2="6"/><line x1="2" y1="9" x2="12" y2="9"/><line x1="2" y1="12" x2="12" y2="12"/><line x1="2" y1="16" x2="22" y2="16"/><line x1="2" y1="20" x2="18" y2="20"/></svg>',floatNone:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="8" height="8" rx="1"/><line x1="3" y1="15" x2="21" y2="15"/><line x1="3" y1="19" x2="17" y2="19"/></svg>',alignCenter:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="4" width="10" height="8" rx="1"/><line x1="3" y1="16" x2="21" y2="16"/><line x1="6" y1="20" x2="18" y2="20"/></svg>',originalSize:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>',deleteVideo:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>',preview:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>'},ui=100,mi=180;class fi{constructor(e){this.context=e,this._el=null,this._activeWrapper=null,this._showTimer=null,this._hideTimer=null,this._disposers=[],this._previewMode=!1,this._previewClickOff=null}initialize(){this._el=this._buildTooltip(),document.body.appendChild(this._el);const e=this.context.layoutInfo.editable;return this._disposers.push(d(e,"mouseover",t=>{const i=t.target.closest(".an-video-wrapper");i&&e.contains(i)&&this._scheduleShow(i)}),d(e,"mouseout",t=>{const i=t.relatedTarget;(!i||!e.contains(i)&&!this._el.contains(i))&&this._scheduleHide()}),d(document,"click",t=>{this._activeWrapper&&!this._activeWrapper.contains(t.target)&&!this._el.contains(t.target)&&this._hide()})),this}destroy(){this._previewMode&&this._exitPreview(),this._clearTimers(),this._disposers.forEach(e=>e()),this._disposers=[],this._el&&this._el.parentNode&&this._el.parentNode.removeChild(this._el),this._el=null}_buildTooltip(){const e=c("div",{class:"an-link-tooltip an-video-tooltip",role:"toolbar","aria-label":"Video actions"});return e.style.display="none",this._label=c("span",{class:"an-link-tooltip-url"}),this._label.textContent="Video",e.appendChild(this._label),e.appendChild(c("div",{class:"an-link-tooltip-sep"})),this._floatLeftBtn=this._makeBtn(V.floatLeft,"Float Left",()=>this._setFloat("left")),this._floatNoneBtn=this._makeBtn(V.floatNone,"No Float",()=>this._setFloat("")),this._alignCenterBtn=this._makeBtn(V.alignCenter,"Align Center",()=>this._setCenter()),this._floatRightBtn=this._makeBtn(V.floatRight,"Float Right",()=>this._setFloat("right")),e.appendChild(this._floatLeftBtn),e.appendChild(this._floatNoneBtn),e.appendChild(this._alignCenterBtn),e.appendChild(this._floatRightBtn),e.appendChild(c("div",{class:"an-link-tooltip-sep"})),this._originalBtn=this._makeBtn(V.originalSize,"Original Size",()=>this._resetSize()),e.appendChild(this._originalBtn),e.appendChild(c("div",{class:"an-link-tooltip-sep"})),this._previewBtn=this._makeBtn(V.preview,"Preview Video",()=>this._togglePreview()),e.appendChild(this._previewBtn),e.appendChild(c("div",{class:"an-link-tooltip-sep"})),this._deleteBtn=this._makeBtn(V.deleteVideo,"Delete Video",()=>this._delete(),!0),e.appendChild(this._deleteBtn),this._disposers.push(d(e,"mouseenter",()=>this._clearTimers()),d(e,"mouseleave",()=>this._scheduleHide())),e}_makeBtn(e,t,i,s=!1){const o=c("button",{type:"button",class:s?"an-link-tooltip-btn an-link-tooltip-btn--danger":"an-link-tooltip-btn",title:t});return o.innerHTML=e,this._disposers.push(d(o,"click",a=>{a.preventDefault(),a.stopPropagation(),i()})),o}_scheduleShow(e){this._activeWrapper===e&&this._el.style.display!=="none"||(clearTimeout(this._hideTimer),this._hideTimer=null,clearTimeout(this._showTimer),this._showTimer=setTimeout(()=>{this._activeWrapper=e,this._show(e)},ui))}_scheduleHide(){this._previewMode||(clearTimeout(this._showTimer),this._showTimer=null,!this._hideTimer&&(this._hideTimer=setTimeout(()=>this._hide(),mi)))}_show(e){this._el.style.display="flex",this._positionNear(e)}_hide(){this._previewMode&&this._exitPreview(),this._el.style.display="none",this._activeWrapper=null,this._clearTimers()}_clearTimers(){clearTimeout(this._showTimer),clearTimeout(this._hideTimer),this._showTimer=null,this._hideTimer=null}_positionNear(e){const t=e.getBoundingClientRect(),i=this._el.offsetWidth||220,s=this._el.offsetHeight||32,o=6;let a=t.bottom+o,r=t.left+(t.width-i)/2;a+s>window.innerHeight-o&&(a=t.top-s-o),r+i>window.innerWidth-o&&(r=window.innerWidth-i-o),r<o&&(r=o),this._el.style.top=`${a}px`,this._el.style.left=`${r}px`}_setFloat(e){const t=this._activeWrapper;t&&(t.style.float=e,t.style.display=e?"inline-block":"",t.style.marginLeft=e==="right"?"12px":"",t.style.marginRight=e==="left"?"12px":"",this.context.invoke("editor.afterCommand"),this.context.invoke("videoResizer.updateOverlay"),this._positionNear(t))}_setCenter(){const e=this._activeWrapper;e&&(e.style.float="",e.style.display="block",e.style.marginLeft="auto",e.style.marginRight="auto",this.context.invoke("editor.afterCommand"),this.context.invoke("videoResizer.updateOverlay"),this._positionNear(e))}_resetSize(){const e=this._activeWrapper;if(!e)return;const t=e.querySelector("iframe, video");e.style.width="",e.style.height="",t&&(t.removeAttribute("width"),t.removeAttribute("height"),t.style.width="",t.style.height=""),this.context.invoke("editor.afterCommand"),this.context.invoke("videoResizer.updateOverlay"),this._positionNear(e)}_delete(){const e=this._activeWrapper;e&&(this._hide(),this.context.invoke("videoResizer.deselect"),e.parentNode&&e.parentNode.removeChild(e),this.context.invoke("editor.afterCommand"))}_togglePreview(){this._previewMode?this._exitPreview():this._enterPreview()}_enterPreview(){const e=this._activeWrapper;if(!e)return;this._previewMode=!0;const t=e.querySelector(".an-video-shield");t&&(t.style.display="none"),this.context.invoke("videoResizer.deselect"),this._previewBtn.classList.add("an-link-tooltip-btn--copied"),this._previewBtn.title="Exit Preview",this._previewClickOff=i=>{!e.contains(i.target)&&!this._el.contains(i.target)&&this._exitPreview()},document.addEventListener("mousedown",this._previewClickOff,!0)}_exitPreview(){this._previewMode=!1;const e=this._activeWrapper;if(e){const t=e.querySelector(".an-video-shield");t&&(t.style.display="")}this._previewBtn.classList.remove("an-link-tooltip-btn--copied"),this._previewBtn.title="Preview Video",this._previewClickOff&&(document.removeEventListener("mousedown",this._previewClickOff,!0),this._previewClickOff=null)}}const gi=120,_i=200;function Z(n){const e=n.closest("tr");if(!e)return-1;let t=0;for(const i of e.cells){if(i===n)return t;t+=i.colSpan||1}return-1}function le(n,e){let t=0;for(const i of n.cells){if(t===e)return i;if(t>e)break;t+=i.colSpan||1}return null}function yi(n,e){let t=0;for(const i of n.cells)if(t+=i.colSpan||1,t>e){const s=i.nextElementSibling;return s&&s.tagName==="TD"||s&&s.tagName==="TH"?s:null}return null}const H={rowAbove:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="1"/><line x1="3" y1="12" x2="21" y2="12"/><path d="M12 3v7"/><path d="M9 7l3-4 3 4"/></svg>',rowBelow:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="1"/><line x1="3" y1="12" x2="21" y2="12"/><path d="M12 12v7"/><path d="M9 17l3 4 3-4"/></svg>',deleteRow:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="1"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="15" y1="15" x2="21" y2="21"/><line x1="21" y1="15" x2="15" y2="21"/></svg>',colLeft:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="1"/><line x1="12" y1="3" x2="12" y2="21"/><path d="M3 12h7"/><path d="M7 8l-4 4 4 4"/></svg>',colRight:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="1"/><line x1="12" y1="3" x2="12" y2="21"/><path d="M12 12h9"/><path d="M17 8l4 4-4 4"/></svg>',deleteCol:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="1"/><line x1="12" y1="3" x2="12" y2="21"/><line x1="15" y1="6" x2="21" y2="12"/><line x1="21" y1="6" x2="15" y2="12"/></svg>',mergeCells:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="7" width="8" height="10" rx="1"/><rect x="14" y="7" width="8" height="10" rx="1"/><path d="M10 12h4"/><path d="M12 10l2 2-2 2"/></svg>',colWidth:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="7" y1="4" x2="7" y2="20"/><line x1="17" y1="4" x2="17" y2="20"/><line x1="7" y1="12" x2="17" y2="12"/><path d="M10 9l-3 3 3 3"/><path d="M14 9l3 3-3 3"/></svg>',rowHeight:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="4" y1="7" x2="20" y2="7"/><line x1="4" y1="17" x2="20" y2="17"/><line x1="12" y1="7" x2="12" y2="17"/><path d="M9 10l3-3 3 3"/><path d="M9 14l3 3 3-3"/></svg>',deleteTable:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="1"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="3" y1="15" x2="21" y2="15"/><line x1="9" y1="3" x2="9" y2="21"/><line x1="15" y1="3" x2="15" y2="21"/><line x1="16" y1="16" x2="22" y2="22" stroke="#ef4444"/><line x1="22" y1="16" x2="16" y2="22" stroke="#ef4444"/></svg>'};class bi{constructor(e){this.context=e,this._el=null,this._activeTable=null,this._activeCell=null,this._showTimer=null,this._hideTimer=null,this._disposers=[],this._sizePopover=null,this._sizeApply=null,this._sizeTitleEl=null,this._sizeInputEl=null}initialize(){this._el=this._buildTooltip(),document.body.appendChild(this._el),this._sizePopover=this._buildSizePopover(),document.body.appendChild(this._sizePopover);const e=this.context.layoutInfo.editable;return this._disposers.push(d(e,"mouseover",t=>{const i=t.target.closest("table");if(i&&e.contains(i)){const s=t.target.closest("td, th");s&&(this._activeCell=s),this._scheduleShow(i)}}),d(e,"mouseout",t=>{const i=t.relatedTarget;(!i||!e.contains(i)&&!this._el.contains(i)&&!(this._sizePopover&&this._sizePopover.contains(i)))&&this._scheduleHide()}),d(document,"click",t=>{this._activeTable&&!this._activeTable.contains(t.target)&&!this._el.contains(t.target)&&!(this._sizePopover&&this._sizePopover.contains(t.target))&&this._hide()})),this._initResize(),this}_initResize(){const e=this.context.layoutInfo.editable,t=6;let i=null,s=null,o=!1,a=null,r=0,l=0,h=0,p=0,m=-1,u=null,f=null;const g=()=>{i&&(i.style.cursor="",i=null),s=null},b=_=>{if(o)return;const y=_.target.closest("td, th");if(!y||!e.contains(y)){g();return}i&&i!==y&&(i.style.cursor="");const w=y.getBoundingClientRect(),k=Math.abs(_.clientX-w.right)<t,I=Math.abs(_.clientY-w.bottom)<t;k&&I||k?(y.style.cursor="col-resize",i=y,s="col"):I?(y.style.cursor="row-resize",i=y,s="row"):g()},C=_=>{!i||!s||(o=!0,a=s,r=_.clientX,l=_.clientY,f=i.closest("table"),a==="col"?(h=i.offsetWidth,m=Z(i),document.body.style.cursor="col-resize"):(u=i.closest("tr"),p=u?u.offsetHeight:40,document.body.style.cursor="row-resize"),document.body.style.userSelect="none",_.preventDefault(),_.stopPropagation())},T=_=>{if(o)if(a==="col"){const y=Math.max(30,h+(_.clientX-r));f&&m>=0&&Array.from(f.querySelectorAll("tr")).forEach(w=>{const k=le(w,m);k&&(k.style.width=`${y}px`,k.style.minWidth=`${y}px`)})}else{const y=Math.max(20,p+(_.clientY-l));u&&Array.from(u.cells).forEach(w=>{w.style.height=`${y}px`,w.style.minHeight=`${y}px`})}},v=()=>{o&&(o=!1,document.body.style.userSelect="",document.body.style.cursor="",a=null,f=null,u=null,m=-1,this.context.invoke("editor.afterCommand"))};this._disposers.push(d(e,"mousemove",b),d(e,"mousedown",C),d(document,"mousemove",T),d(document,"mouseup",v))}destroy(){this._clearTimers(),this._disposers.forEach(e=>e()),this._disposers=[],this._el&&this._el.parentNode&&this._el.parentNode.removeChild(this._el),this._el=null,this._sizePopover&&this._sizePopover.parentNode&&this._sizePopover.parentNode.removeChild(this._sizePopover),this._sizePopover=null}_buildTooltip(){const e=c("div",{class:"an-link-tooltip an-table-tooltip",role:"toolbar","aria-label":"Table actions"});return e.style.display="none",this._label=c("span",{class:"an-link-tooltip-url"}),this._label.textContent="Table",e.appendChild(this._label),e.appendChild(this._sep()),e.appendChild(this._makeBtn(H.rowAbove,"Add Row Above",()=>this._addRow("above"))),e.appendChild(this._makeBtn(H.rowBelow,"Add Row Below",()=>this._addRow("below"))),e.appendChild(this._makeBtn(H.deleteRow,"Delete Row",()=>this._deleteRow())),e.appendChild(this._sep()),e.appendChild(this._makeBtn(H.colLeft,"Add Column Left",()=>this._addColumn("left"))),e.appendChild(this._makeBtn(H.colRight,"Add Column Right",()=>this._addColumn("right"))),e.appendChild(this._makeBtn(H.deleteCol,"Delete Column",()=>this._deleteColumn())),e.appendChild(this._sep()),e.appendChild(this._makeBtn(H.mergeCells,"Merge Cells",()=>this._mergeCells())),e.appendChild(this._sep()),e.appendChild(this._makeBtn(H.colWidth,"Column Width",()=>this._openSizePopover("col"))),e.appendChild(this._makeBtn(H.rowHeight,"Row Height",()=>this._openSizePopover("row"))),e.appendChild(this._sep()),e.appendChild(this._makeBtn(H.deleteTable,"Delete Table",()=>this._deleteTable(),!0)),this._disposers.push(d(e,"mouseenter",()=>this._clearTimers()),d(e,"mouseleave",()=>{this._sizePopover&&this._sizePopover.style.display!=="none"||this._scheduleHide()})),e}_sep(){return c("div",{class:"an-link-tooltip-sep"})}_makeBtn(e,t,i,s=!1){const o=c("button",{type:"button",class:s?"an-link-tooltip-btn an-link-tooltip-btn--danger":"an-link-tooltip-btn",title:t});return o.innerHTML=e,this._disposers.push(d(o,"click",a=>{a.preventDefault(),a.stopPropagation(),i()})),o}_scheduleShow(e){this._activeTable===e&&this._el.style.display!=="none"||(clearTimeout(this._hideTimer),this._hideTimer=null,clearTimeout(this._showTimer),this._showTimer=setTimeout(()=>{this._activeTable=e,this._show()},gi))}_scheduleHide(){clearTimeout(this._showTimer),this._showTimer=null,!this._hideTimer&&(this._hideTimer=setTimeout(()=>this._hide(),_i))}_show(){this._activeTable&&(this._el.style.display="flex",this._positionNear(this._activeTable))}_hide(){this._el.style.display="none",this._activeTable=null,this._activeCell=null,this._clearTimers(),this._hideSizePopover()}_clearTimers(){clearTimeout(this._showTimer),clearTimeout(this._hideTimer),this._showTimer=null,this._hideTimer=null}_positionNear(e){if(!e)return;const t=e.getBoundingClientRect(),i=this._el.offsetWidth||400,s=this._el.offsetHeight||30,o=6;let a=t.left+(t.width-i)/2,r=t.top-s-o;r<o&&(r=t.bottom+o),a+i>window.innerWidth-o&&(a=window.innerWidth-i-o),a<o&&(a=o),this._el.style.left=`${a}px`,this._el.style.top=`${r}px`}_getCell(){const e=window.getSelection();if(e&&e.rangeCount){let t=e.getRangeAt(0).commonAncestorContainer;t.nodeType===3&&(t=t.parentElement);const i=t&&t.closest&&t.closest("td, th");if(i&&this._activeTable&&this._activeTable.contains(i))return i}return this._activeCell||this._activeTable&&this._activeTable.querySelector("td, th")}_addRow(e){var r;const t=this._getCell();if(!t)return;const i=t.closest("tr");if(!i)return;const s=Array.from(i.cells).reduce((l,h)=>l+(h.colSpan||1),0),o=document.createElement("tr"),a=Array.from(i.cells);for(let l=0;l<s;l++){const h=c("td",{},[" "]),p=a[l];p&&p.style.width&&(h.style.width=p.style.width),p&&p.style.minWidth&&(h.style.minWidth=p.style.minWidth),o.appendChild(h)}e==="above"?(r=i.parentElement)==null||r.insertBefore(o,i):i.insertAdjacentElement("afterend",o),this._positionNear(this._activeTable),this.context.invoke("editor.afterCommand")}_addColumn(e){const t=this._getCell();if(!t)return;const i=t.closest("table");if(!i)return;const s=Z(t);Array.from(i.querySelectorAll("tr")).forEach(o=>{const a=o.closest("thead")!==null,r=c(a?"th":"td",{},[" "]);if(e==="left"){const l=le(o,s);o.insertBefore(r,l)}else{const l=yi(o,s);o.insertBefore(r,l)}}),this._positionNear(this._activeTable),this.context.invoke("editor.afterCommand")}_deleteRow(){var a;const e=this._getCell();if(!e)return;const t=e.closest("tr"),i=e.closest("table");if(!t||!i)return;const s=i.querySelector("tbody");(s?s.querySelectorAll("tr").length:i.querySelectorAll("tr").length)<=1&&t.closest("tbody")||(this._activeCell=null,(a=t.parentElement)==null||a.removeChild(t),this._positionNear(this._activeTable),this.context.invoke("editor.afterCommand"))}_deleteColumn(){const e=this._getCell();if(!e)return;const t=e.closest("table");if(!t)return;const i=e.closest("tr");if(i&&i.cells.length<=1)return;const s=Z(e);this._activeCell=null,Array.from(t.querySelectorAll("tr")).forEach(o=>{const a=le(o,s);a&&o.removeChild(a)}),this._positionNear(this._activeTable),this.context.invoke("editor.afterCommand")}_mergeCells(){const e=this._getCell();if(!e)return;const t=window.getSelection();if(!t||t.rangeCount===0)return;const i=t.getRangeAt(0),s=e.closest("table");if(!s)return;const a=Array.from(s.querySelectorAll("td, th")).filter(l=>{try{return i.intersectsNode(l)}catch{return!1}});if(a.length<2)return;const r=[...new Set(a.map(l=>l.closest("tr")))];if(r.length===1){const l=r[0],h=Array.from(l.cells).filter(m=>a.includes(m));if(h.length<2)return;const p=h[0];p.colSpan=h.reduce((m,u)=>m+(u.colSpan||1),0),p.innerHTML=h.map(m=>m.innerHTML).join(""),h.slice(1).forEach(m=>l.removeChild(m))}else{if([...new Set(a.map(p=>Z(p)))].length!==1)return;const h=a[0];h.rowSpan=a.reduce((p,m)=>p+(m.rowSpan||1),0),h.innerHTML=a.map(p=>p.innerHTML).join(""),a.slice(1).forEach(p=>{p.closest("tr")&&p.closest("tr").removeChild(p)})}this.context.invoke("editor.afterCommand")}_deleteTable(){const e=this._activeTable;e&&(this._hide(),e.parentNode&&e.parentNode.removeChild(e),this.context.invoke("editor.afterCommand"))}_buildSizePopover(){const e=c("div",{class:"an-size-popover"});e.style.display="none";const t=c("div",{class:"an-size-popover-title"}),i=c("div",{class:"an-size-popover-body"}),s=c("input",{type:"number",class:"an-size-input",min:"1",max:"2000",step:"1"}),o=c("span",{class:"an-size-unit"},["px"]);i.appendChild(s),i.appendChild(o);const a=c("div",{class:"an-size-popover-actions"}),r=c("button",{type:"button",class:"an-btn"});r.textContent="Cancel";const l=c("button",{type:"button",class:"an-btn an-btn-primary"});l.textContent="Apply",a.appendChild(r),a.appendChild(l),e.appendChild(t),e.appendChild(i),e.appendChild(a),this._sizeTitleEl=t,this._sizeInputEl=s,this._sizeApply=null;const h=d(l,"click",()=>{const b=parseInt(this._sizeInputEl.value,10);b>0&&typeof this._sizeApply=="function"&&this._sizeApply(b),this._hideSizePopover()}),p=d(r,"click",()=>this._hideSizePopover()),m=d(s,"keydown",b=>{b.key==="Enter"&&(b.preventDefault(),l.click()),b.key==="Escape"&&this._hideSizePopover()}),u=d(document,"click",b=>{this._sizePopover&&this._sizePopover.style.display!=="none"&&!this._sizePopover.contains(b.target)&&!this._el.contains(b.target)&&this._hideSizePopover()}),f=d(e,"mouseenter",()=>this._clearTimers()),g=d(e,"mouseleave",()=>this._scheduleHide());return this._disposers.push(h,p,m,u,f,g),e}_openSizePopover(e){const t=this._getCell();if(!t||!this._sizePopover)return;const i=e==="col";this._sizeTitleEl.textContent=i?"Column Width (px)":"Row Height (px)",this._sizeInputEl.value=i?t.offsetWidth||120:t.closest("tr")&&t.closest("tr").offsetHeight||40,this._sizeApply=s=>{if(i){const o=t.closest("table"),a=Z(t);Array.from(o.querySelectorAll("tr")).forEach(r=>{const l=le(r,a);l&&(l.style.width=`${s}px`,l.style.minWidth=`${s}px`)})}else{const o=t.closest("tr");o&&Array.from(o.cells).forEach(a=>{a.style.height=`${s}px`,a.style.minHeight=`${s}px`})}this.context.invoke("editor.afterCommand")},this._sizePopover.style.display="block",requestAnimationFrame(()=>{if(!this._sizePopover||!this._el)return;const s=this._el.getBoundingClientRect(),o=this._sizePopover.offsetWidth||220,a=this._sizePopover.offsetHeight||110;let r=s.left,l=s.bottom+6;r+o>window.innerWidth-8&&(r=window.innerWidth-o-8),l+a>window.innerHeight-8&&(l=s.top-a-6),this._sizePopover.style.left=`${r}px`,this._sizePopover.style.top=`${l}px`,this._sizeInputEl&&(this._sizeInputEl.focus(),this._sizeInputEl.select())})}_hideSizePopover(){this._sizePopover&&(this._sizePopover.style.display="none"),this._sizeApply=null}}const vi=100,wi=180,re={copy:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>',wrapOn:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="6" x2="21" y2="6"/><path d="M3 12h15a3 3 0 0 1 0 6H3"/><polyline points="6 15 3 18 6 21"/></svg>',toParagraph:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 4v16"/><path d="M17 4v16"/><path d="M9 4h8a4 4 0 0 1 0 8H9V4z"/></svg>',deleteCode:'<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>'};class xi{constructor(e){this.context=e,this._el=null,this._activePre=null,this._showTimer=null,this._hideTimer=null,this._disposers=[],this._copyBtn=null,this._langSelect=null,this._prismScript=null}initialize(){this._el=this._buildTooltip(),document.body.appendChild(this._el),this._ensurePrism();const e=this.context.layoutInfo.editable;return this._disposers.push(d(e,"mouseover",t=>{const i=t.target.closest("pre");i&&e.contains(i)&&this._scheduleShow(i)}),d(e,"mouseout",t=>{const i=t.relatedTarget;(!i||!e.contains(i)&&!this._el.contains(i))&&this._scheduleHide()}),d(document,"click",t=>{this._activePre&&!this._activePre.contains(t.target)&&!this._el.contains(t.target)&&this._hide()})),this}destroy(){this._clearTimers(),this._disposers.forEach(e=>e()),this._disposers=[],this._el&&this._el.parentNode&&this._el.parentNode.removeChild(this._el),this._el=null}_buildTooltip(){const e=c("div",{class:"an-link-tooltip an-code-tooltip",role:"toolbar","aria-label":"Code block actions"});return e.style.display="none",this._label=c("span",{class:"an-link-tooltip-url"}),this._label.textContent="Code",e.appendChild(this._label),e.appendChild(this._sep()),this._langSelect=c("select",{class:"an-code-lang-select",title:"Syntax Language","aria-label":"Syntax language"}),[["","Plain text"],["javascript","JavaScript"],["typescript","TypeScript"],["python","Python"],["html","HTML"],["css","CSS"],["json","JSON"],["xml","XML"],["bash","Bash / Shell"],["sql","SQL"],["java","Java"],["csharp","C#"],["php","PHP"],["ruby","Ruby"],["go","Go"],["rust","Rust"],["cpp","C++"],["c","C"],["kotlin","Kotlin"],["swift","Swift"]].forEach(([i,s])=>{const o=c("option",{value:i});o.textContent=s,this._langSelect.appendChild(o)}),this._disposers.push(d(this._langSelect,"change",()=>this._onLangChange())),e.appendChild(this._langSelect),e.appendChild(this._sep()),this._copyBtn=this._makeBtn(re.copy,"Copy Code",()=>this._copyCode()),e.appendChild(this._copyBtn),e.appendChild(this._sep()),this._wrapBtn=this._makeBtn(re.wrapOn,"Toggle Word Wrap",()=>this._toggleWrap()),e.appendChild(this._wrapBtn),e.appendChild(this._sep()),e.appendChild(this._makeBtn(re.toParagraph,"Convert to Paragraph",()=>this._toParagraph())),e.appendChild(this._sep()),e.appendChild(this._makeBtn(re.deleteCode,"Delete Code Block",()=>this._delete(),!0)),this._disposers.push(d(e,"mouseenter",()=>this._clearTimers()),d(e,"mouseleave",()=>this._scheduleHide())),e}_sep(){return c("div",{class:"an-link-tooltip-sep"})}_makeBtn(e,t,i,s=!1){const o=c("button",{type:"button",class:s?"an-link-tooltip-btn an-link-tooltip-btn--danger":"an-link-tooltip-btn",title:t});return o.innerHTML=e,this._disposers.push(d(o,"click",a=>{a.preventDefault(),a.stopPropagation(),i()})),o}_scheduleShow(e){this._activePre===e&&this._el.style.display!=="none"||(clearTimeout(this._hideTimer),this._hideTimer=null,clearTimeout(this._showTimer),this._showTimer=setTimeout(()=>{this._activePre=e,this._syncWrapBtn(),this._syncLangSelect(),this._show(e)},vi))}_scheduleHide(){clearTimeout(this._showTimer),this._showTimer=null,!this._hideTimer&&(this._hideTimer=setTimeout(()=>this._hide(),wi))}_show(e){this._el.style.display="flex",this._positionNear(e)}_hide(){this._el.style.display="none",this._activePre=null,this._clearTimers()}_clearTimers(){clearTimeout(this._showTimer),clearTimeout(this._hideTimer),this._showTimer=null,this._hideTimer=null}_positionNear(e){const t=e.getBoundingClientRect(),i=this._el.offsetWidth||260,s=this._el.offsetHeight||32,o=6;let a=t.top-s-o,r=t.left+(t.width-i)/2;a<o&&(a=t.bottom+o),r+i>window.innerWidth-o&&(r=window.innerWidth-i-o),r<o&&(r=o),this._el.style.top=`${a}px`,this._el.style.left=`${r}px`}_syncWrapBtn(){if(!this._activePre||!this._wrapBtn)return;const e=(this._activePre.style.whiteSpace||"").includes("pre-wrap")||window.getComputedStyle(this._activePre).whiteSpace==="pre-wrap";this._wrapBtn.classList.toggle("active",e),this._wrapBtn.title=e?"Disable Word Wrap":"Enable Word Wrap"}_syncLangSelect(){if(!this._activePre||!this._langSelect)return;const e=this._activePre.querySelector("code"),t=this._activePre.getAttribute("data-language")||"",i=e&&(e.className.match(/language-(\S+)/)||[])[1]||"";this._langSelect.value=t||i||""}_copyCode(){const e=this._activePre;if(!e)return;const t=e.textContent||"";if(navigator.clipboard)navigator.clipboard.writeText(t).then(()=>this._flashCopied()).catch(()=>{});else{const i=document.createElement("textarea");i.value=t,i.style.cssText="position:fixed;opacity:0;top:0;left:0",document.body.appendChild(i),i.select();try{document.execCommand("copy"),this._flashCopied()}catch{}document.body.removeChild(i)}}_flashCopied(){if(!this._copyBtn)return;const e=this._copyBtn.innerHTML;this._copyBtn.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',this._copyBtn.classList.add("an-link-tooltip-btn--copied"),setTimeout(()=>{this._copyBtn&&(this._copyBtn.innerHTML=e,this._copyBtn.classList.remove("an-link-tooltip-btn--copied"))},1400)}_toggleWrap(){const e=this._activePre;if(!e)return;const t=e.style.whiteSpace==="pre-wrap";e.style.whiteSpace=t?"pre":"pre-wrap",this._syncWrapBtn(),this.context.invoke("editor.afterCommand"),this._positionNear(e)}_onLangChange(){const e=this._activePre;if(!e)return;const t=this._langSelect.value;let i=e.querySelector("code");i||(i=document.createElement("code"),i.innerHTML=e.innerHTML,e.innerHTML="",e.appendChild(i)),i.className=t?`language-${t}`:"",e.className=t?`language-${t}`:"",t?e.setAttribute("data-language",t):e.removeAttribute("data-language");const s=()=>{i.querySelectorAll("br").forEach(o=>o.replaceWith(`
|
|
72
|
+
`)),window.Prism.highlightElement(i),this.context.invoke("editor.afterCommand")};if(t){if(typeof window.Prism<"u"){if(window.Prism.languages[t]){s();return}this._loadPrismComponent(t,s);return}else if(this._prismScript){this._prismScript.addEventListener("load",()=>{window.Prism.languages[t]?s():this._loadPrismComponent(t,s)},{once:!0});return}}this.context.invoke("editor.afterCommand")}_ensurePrism(){if(!this.context.options.codeHighlight||window.Prism)return;const e=this.context.options.codeHighlightCDN||"https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0",t=`${e}/themes/prism-tomorrow.min.css`,i=`${e}/prism.min.js`;if(!document.querySelector(`link[href="${t}"]`)){const a=document.createElement("link");a.rel="stylesheet",a.href=t,document.head.appendChild(a)}const s=document.querySelector(`script[src="${i}"]`);if(s){this._prismScript=window.Prism?null:s;return}const o=document.createElement("script");o.dataset.manual="",o.src=i,this._prismScript=o,o.addEventListener("load",()=>{this._prismScript=null},{once:!0}),document.head.appendChild(o)}_loadPrismComponent(e,t){const s=`${this.context.options.codeHighlightCDN||"https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0"}/components/prism-${e}.min.js`;if(document.querySelector(`script[src="${s}"]`)){const a=setInterval(()=>{window.Prism&&window.Prism.languages[e]&&(clearInterval(a),t())},50);setTimeout(()=>clearInterval(a),3e3);return}const o=document.createElement("script");o.src=s,o.addEventListener("load",t,{once:!0}),document.head.appendChild(o)}_toParagraph(){const e=this._activePre;if(!e||!this.context.layoutInfo.editable)return;const i=(e.textContent||"").split(`
|
|
73
|
+
`),s=document.createElement("p");i.forEach((o,a)=>{a>0&&s.appendChild(document.createElement("br")),s.appendChild(document.createTextNode(o))}),e.parentNode.replaceChild(s,e),this._hide(),this.context.invoke("editor.afterCommand")}_delete(){const e=this._activePre;e&&(this._hide(),e.parentNode&&e.parentNode.removeChild(e),this.context.invoke("editor.afterCommand"))}}const Ci=[{id:"smileys",label:"Smileys"},{id:"people",label:"People"},{id:"animals",label:"Animals"},{id:"food",label:"Food"},{id:"travel",label:"Travel"},{id:"objects",label:"Objects"},{id:"symbols",label:"Symbols"}],ki=[["😀","grin smile happy face","smileys"],["😃","happy smile big eyes","smileys"],["😄","grinning smile laugh","smileys"],["😁","beaming smile grin","smileys"],["😆","laughing lol","smileys"],["😅","sweat grin awkward","smileys"],["🤣","rolling laugh rofl","smileys"],["😂","tears laugh cry joy","smileys"],["🙂","slight smile","smileys"],["🙃","upside down smile","smileys"],["😉","wink","smileys"],["😊","blush smile happy","smileys"],["😇","innocent halo angel","smileys"],["🥰","hearts love adore","smileys"],["😍","heart eyes love","smileys"],["🤩","star eyes excited wow","smileys"],["😘","kiss blow love","smileys"],["😋","yum delicious tongue","smileys"],["😛","tongue stuck out","smileys"],["😜","wink tongue crazy","smileys"],["🤪","zany crazy wild","smileys"],["😝","squint tongue","smileys"],["🤑","money mouth","smileys"],["🤗","hugging hug","smileys"],["🤔","thinking hmm","smileys"],["🤨","raised eyebrow","smileys"],["😐","neutral face","smileys"],["😶","no mouth","smileys"],["😏","smirk","smileys"],["😒","unamused","smileys"],["🙄","roll eyes","smileys"],["😬","grimace","smileys"],["😔","pensive sad","smileys"],["😪","sleepy tired","smileys"],["😴","sleeping zzz","smileys"],["🤤","drool","smileys"],["😷","mask sick","smileys"],["🤒","sick thermometer","smileys"],["🤕","hurt bandage","smileys"],["🤢","nausea sick","smileys"],["🤮","vomit sick","smileys"],["🤧","sneeze cold","smileys"],["🥵","hot sweat","smileys"],["🥶","cold freeze","smileys"],["😵","dizzy dead","smileys"],["🤯","mind blown","smileys"],["🤠","cowboy hat","smileys"],["🥳","party celebrate","smileys"],["😎","cool sunglasses","smileys"],["🤓","nerd glasses","smileys"],["🧐","monocle curious","smileys"],["😕","confused","smileys"],["😟","worried","smileys"],["🙁","frown sad","smileys"],["☹️","sad frown","smileys"],["😮","surprised open mouth","smileys"],["😲","astonished","smileys"],["🥺","pleading begging puppy eyes","smileys"],["😢","cry sad tear","smileys"],["😭","sob cry loudly","smileys"],["😱","scream horror fear","smileys"],["😡","angry red pouting","smileys"],["😠","angry mad","smileys"],["🤬","cursing swear","smileys"],["😈","devil evil smile","smileys"],["👿","devil angry evil","smileys"],["💀","skull death","smileys"],["☠️","skull crossbones","smileys"],["💩","poop","smileys"],["🤡","clown","smileys"],["👻","ghost boo","smileys"],["👽","alien ufo","smileys"],["🤖","robot","smileys"],["👋","wave hello hi hand","people"],["🤚","raised back hand","people"],["✋","raised hand stop","people"],["🖖","vulcan salute spock","people"],["👌","ok perfect fine","people"],["✌️","peace victory fingers","people"],["🤞","fingers crossed luck","people"],["🤟","love you gesture","people"],["🤘","sign of horns rock","people"],["🤙","call me hand","people"],["👈","point left","people"],["👉","point right","people"],["👆","point up","people"],["👇","point down","people"],["☝️","index pointing up","people"],["👍","thumbs up like good","people"],["👎","thumbs down dislike bad","people"],["✊","raised fist punch","people"],["👊","oncoming fist punch","people"],["👏","clap applause","people"],["🙌","celebrate raise hands","people"],["🤝","handshake deal","people"],["🙏","pray hope please thanks","people"],["💅","nail polish","people"],["💪","flexed bicep strong muscle","people"],["👀","eyes look see","people"],["👁️","eye","people"],["👅","tongue","people"],["👶","baby","people"],["🧒","child","people"],["👦","boy","people"],["👧","girl","people"],["🧑","person adult","people"],["👨","man","people"],["👩","woman","people"],["🧔","beard man","people"],["🧓","older person","people"],["👴","old man","people"],["👵","old woman","people"],["❤️","heart love red","people"],["🧡","orange heart love","people"],["💛","yellow heart love","people"],["💚","green heart love","people"],["💙","blue heart love","people"],["💜","purple heart love","people"],["🖤","black heart","people"],["🤍","white heart","people"],["🤎","brown heart","people"],["💔","broken heart","people"],["❣️","exclamation heart","people"],["💕","two hearts love","people"],["💞","revolving hearts","people"],["💓","beating heart","people"],["💗","growing heart","people"],["💖","sparkling heart","people"],["💘","heart arrow","people"],["💝","heart ribbon","people"],["💬","speech bubble comment chat","people"],["💭","thought bubble","people"],["💯","100 hundred percent perfect","people"],["💢","anger symbol mad","people"],["💤","zzz sleep","people"],["🐶","dog puppy","animals"],["🐱","cat kitten","animals"],["🐭","mouse","animals"],["🐹","hamster","animals"],["🐰","rabbit bunny","animals"],["🦊","fox","animals"],["🐻","bear","animals"],["🐼","panda","animals"],["🐨","koala","animals"],["🐯","tiger","animals"],["🦁","lion","animals"],["🐮","cow","animals"],["🐷","pig","animals"],["🐸","frog","animals"],["🐵","monkey","animals"],["🙈","see no evil monkey","animals"],["🙉","hear no evil monkey","animals"],["🙊","speak no evil monkey","animals"],["🐔","chicken hen","animals"],["🐧","penguin","animals"],["🐦","bird","animals"],["🦆","duck","animals"],["🦅","eagle","animals"],["🦉","owl","animals"],["🦇","bat","animals"],["🐺","wolf","animals"],["🐴","horse","animals"],["🦄","unicorn","animals"],["🐝","bee","animals"],["🦋","butterfly","animals"],["🐌","snail","animals"],["🐞","ladybug","animals"],["🐢","turtle","animals"],["🐍","snake","animals"],["🦎","lizard","animals"],["🐊","crocodile","animals"],["🐟","fish","animals"],["🐠","tropical fish","animals"],["🦈","shark","animals"],["🐬","dolphin","animals"],["🐳","whale","animals"],["🐙","octopus","animals"],["🦑","squid","animals"],["🦀","crab","animals"],["🌸","cherry blossom flower","animals"],["🌺","hibiscus flower","animals"],["🌻","sunflower","animals"],["🌹","rose flower","animals"],["🌷","tulip flower","animals"],["🍀","four leaf clover luck","animals"],["🌿","herb leaf green","animals"],["🌱","seedling sprout","animals"],["🌲","evergreen tree pine","animals"],["🌳","deciduous tree","animals"],["🌴","palm tree","animals"],["🍄","mushroom","animals"],["🌾","sheaf wheat","animals"],["🐾","paw prints animal","animals"],["🍎","apple red","food"],["🍊","orange tangerine","food"],["🍋","lemon yellow","food"],["🍇","grapes","food"],["🍓","strawberry","food"],["🫐","blueberry","food"],["🍒","cherry","food"],["🍑","peach","food"],["🥭","mango","food"],["🍍","pineapple","food"],["🥥","coconut","food"],["🥝","kiwi","food"],["🍅","tomato","food"],["🥑","avocado","food"],["🍆","eggplant aubergine","food"],["🥕","carrot","food"],["🌽","corn","food"],["🥦","broccoli","food"],["🥬","leafy green","food"],["🧄","garlic","food"],["🥜","peanut nut","food"],["🍞","bread loaf","food"],["🥐","croissant","food"],["🧀","cheese","food"],["🍳","egg fry cooking","food"],["🥚","egg","food"],["🥞","pancake","food"],["🧇","waffle","food"],["🥓","bacon","food"],["🥩","meat steak","food"],["🍗","chicken leg","food"],["🌭","hotdog","food"],["🍔","burger hamburger","food"],["🍟","fries french","food"],["🍕","pizza","food"],["🌮","taco","food"],["🌯","burrito wrap","food"],["🍜","noodles ramen","food"],["🍝","spaghetti pasta","food"],["🍣","sushi","food"],["🍱","bento box","food"],["🍦","ice cream soft serve","food"],["🍩","donut","food"],["🍪","cookie","food"],["🎂","birthday cake","food"],["🍰","cake slice","food"],["🧁","cupcake","food"],["🍫","chocolate","food"],["🍬","candy","food"],["🍭","lollipop","food"],["☕","coffee hot","food"],["🍵","tea hot","food"],["🧋","bubble tea boba","food"],["🥤","cup straw drink","food"],["🍷","wine red","food"],["🍸","cocktail martini","food"],["🍺","beer mug","food"],["🍻","clinking beer mugs","food"],["🥂","champagne toast celebrate","food"],["🧃","juice box","food"],["🧊","ice cube","food"],["🚀","rocket space","travel"],["🛸","ufo flying saucer","travel"],["✈️","airplane plane fly","travel"],["🚁","helicopter","travel"],["🚂","train locomotive","travel"],["🚄","bullet train fast","travel"],["🚇","subway metro","travel"],["🚌","bus","travel"],["🚑","ambulance","travel"],["🚒","fire truck","travel"],["🚓","police car","travel"],["🚕","taxi cab","travel"],["🚗","car automobile red","travel"],["🚙","suv car","travel"],["🚚","truck delivery","travel"],["🚜","tractor farm","travel"],["🏎️","racing car fast","travel"],["🏍️","motorcycle","travel"],["🚲","bicycle bike","travel"],["🛴","scooter kick","travel"],["⛵","sailboat boat","travel"],["🚢","ship cruise","travel"],["🏠","house home","travel"],["🏢","office building","travel"],["🏥","hospital","travel"],["🏦","bank","travel"],["🏪","store shop convenience","travel"],["🏫","school","travel"],["🏰","castle european","travel"],["🏯","japanese castle","travel"],["🗼","tokyo tower","travel"],["🗽","statue liberty new york","travel"],["⛪","church","travel"],["🕌","mosque","travel"],["⛩️","shinto shrine","travel"],["⛲","fountain","travel"],["⛺","tent camping","travel"],["🌁","fog foggy bridge","travel"],["🌃","night city stars","travel"],["🏙️","cityscape city buildings","travel"],["🌅","sunrise morning","travel"],["🌈","rainbow colorful","travel"],["⛰️","mountain","travel"],["🏔️","snow mountain","travel"],["🗻","mount fuji","travel"],["🏕️","camping tent","travel"],["🗺️","world map","travel"],["🧭","compass navigation","travel"],["🌍","earth europe africa globe","travel"],["🌎","earth americas globe","travel"],["🌏","earth asia globe","travel"],["🌐","globe internet web","travel"],["💎","diamond gem jewel","objects"],["💍","ring engagement","objects"],["👑","crown royal king queen","objects"],["🎩","top hat magic","objects"],["💼","briefcase work business","objects"],["👜","handbag purse","objects"],["🎒","backpack bag school","objects"],["👓","glasses eyewear","objects"],["🕶️","sunglasses cool","objects"],["💡","light bulb idea","objects"],["🔦","flashlight torch","objects"],["🕯️","candle light","objects"],["🔋","battery charge","objects"],["💻","laptop computer","objects"],["🖥️","desktop monitor computer","objects"],["📱","phone mobile cell","objects"],["⌨️","keyboard type","objects"],["🖱️","mouse computer click","objects"],["📺","television tv","objects"],["📷","camera photo","objects"],["📹","video camera","objects"],["🎥","movie camera film","objects"],["☎️","telephone phone","objects"],["⏰","alarm clock wake","objects"],["⌚","watch time","objects"],["🔑","key","objects"],["🗝️","old key","objects"],["🔒","lock closed","objects"],["🔓","unlock open","objects"],["🔨","hammer tool","objects"],["🔧","wrench tool","objects"],["🔩","bolt nut","objects"],["⚙️","gear setting","objects"],["🧲","magnet attract","objects"],["📚","books stack library","objects"],["📖","book open read","objects"],["📝","memo write note","objects"],["✏️","pencil write edit","objects"],["📌","pushpin tack","objects"],["📎","paperclip attach","objects"],["📊","bar chart graph","objects"],["📈","chart up growth trend","objects"],["📉","chart down loss decline","objects"],["📅","calendar date","objects"],["📦","package box","objects"],["📫","mailbox closed","objects"],["📧","email envelope","objects"],["🎁","gift present","objects"],["🎀","ribbon bow","objects"],["🎉","party celebrate confetti","objects"],["🎊","confetti celebrate","objects"],["🔮","crystal ball magic fortune","objects"],["🪄","magic wand","objects"],["🎯","target bullseye dart","objects"],["🎲","dice game board","objects"],["🎮","video game controller","objects"],["🎭","theater masks drama","objects"],["🎨","art palette paint","objects"],["🎬","clapper film movie","objects"],["🎤","microphone sing karaoke","objects"],["🎧","headphones music listen","objects"],["🎵","music note","objects"],["🎶","music notes","objects"],["🎸","guitar electric","objects"],["🎹","piano keyboard music","objects"],["🥁","drum percussion","objects"],["🎷","saxophone jazz","objects"],["🎺","trumpet","objects"],["🎻","violin","objects"],["⚽","soccer ball football","objects"],["🏀","basketball","objects"],["🏈","american football","objects"],["⚾","baseball","objects"],["🎾","tennis","objects"],["🏐","volleyball","objects"],["🏆","trophy winner award","objects"],["🥇","gold medal first","objects"],["🏅","sports medal","objects"],["✅","check green done success","symbols"],["❌","cross x no cancel","symbols"],["⭕","circle red","symbols"],["⛔","no entry stop","symbols"],["🚫","prohibited no banned","symbols"],["⚠️","warning caution danger","symbols"],["❗","exclamation red important","symbols"],["❓","question mark","symbols"],["‼️","double exclamation","symbols"],["💯","100 hundred percent perfect","symbols"],["🔴","red circle dot","symbols"],["🟠","orange circle","symbols"],["🟡","yellow circle","symbols"],["🟢","green circle","symbols"],["🔵","blue circle","symbols"],["🟣","purple circle","symbols"],["⚫","black circle","symbols"],["⚪","white circle","symbols"],["🟤","brown circle","symbols"],["🔺","red triangle up","symbols"],["🔻","red triangle down","symbols"],["🔷","blue diamond large","symbols"],["🔶","orange diamond large","symbols"],["🔹","blue diamond small","symbols"],["🔸","orange diamond small","symbols"],["⭐","star yellow","symbols"],["🌟","glowing star shine","symbols"],["✨","sparkles shine","symbols"],["💫","dizzy star spin","symbols"],["⚡","lightning bolt energy power","symbols"],["🔥","fire hot flame","symbols"],["💥","explosion boom","symbols"],["❄️","snowflake cold ice winter","symbols"],["🌊","wave water ocean sea","symbols"],["💨","wind blow dash","symbols"],["🌀","cyclone tornado spiral","symbols"],["♻️","recycle loop green","symbols"],["✔️","check tick done","symbols"],["➕","plus add","symbols"],["➖","minus subtract","symbols"],["➗","divide division","symbols"],["✖️","multiply times cross","symbols"],["▶️","play button right","symbols"],["⏸️","pause","symbols"],["⏹️","stop square","symbols"],["⏩","fast forward","symbols"],["⏪","rewind fast backward","symbols"],["🔔","bell notification","symbols"],["🔕","bell slash mute","symbols"],["🔊","speaker volume high","symbols"],["🔇","mute silent no sound","symbols"],["📢","loudspeaker announcement","symbols"],["📣","megaphone cheer","symbols"],["🏳️","white flag","symbols"],["🏴","black flag","symbols"],["🚩","red flag","symbols"],["🏁","checkered flag finish race","symbols"],["🆕","new badge","symbols"],["🆓","free badge","symbols"],["🆒","cool badge","symbols"],["🔝","top arrow","symbols"],["🔙","back arrow","symbols"],["ℹ️","information info","symbols"],["📍","pin location map","symbols"],["🔗","link chain","symbols"],["©️","copyright","symbols"],["®️","registered trademark","symbols"],["™️","trademark","symbols"],["#️⃣","hash number","symbols"],["0️⃣","zero number","symbols"],["1️⃣","one number","symbols"],["2️⃣","two number","symbols"],["3️⃣","three number","symbols"],["4️⃣","four number","symbols"],["5️⃣","five number","symbols"]];class Ti{constructor(e){this.context=e,this._dialog=null,this._disposers=[],this._savedRange=null,this._activeCat="all"}initialize(){return this}destroy(){this._disposers.forEach(e=>e()),this._disposers=[],this._dialog&&this._dialog.parentNode&&this._dialog.parentNode.removeChild(this._dialog),this._dialog=null}show(){this._dialog||(this._dialog=this._buildDialog(),document.body.appendChild(this._dialog)),G(e=>{this._savedRange=e}),this._activeCat="all",this._searchInput.value="",this._updateCatTabs(),this._filterEmojis("","all"),this._open()}_buildDialog(){const e=c("div",{class:"an-dialog-overlay",role:"dialog","aria-modal":"true","aria-label":"Insert emoji"}),t=c("div",{class:"an-dialog-box an-emoji-box"}),i=c("div",{class:"an-icon-title-row"}),s=c("h3",{class:"an-dialog-title"});s.textContent="Insert Emoji";const o=c("button",{type:"button",class:"an-icon-close","aria-label":"Close"});o.innerHTML="×",i.append(s,o);const a=c("input",{type:"search",class:"an-input an-icon-search",placeholder:"Search emojis…",autocomplete:"off"});this._searchInput=a;const r=c("div",{class:"an-icon-cats"}),l=c("button",{type:"button",class:"an-icon-cat active","data-cat":"all"});l.textContent="All",r.appendChild(l),Ci.forEach(({id:v,label:_})=>{const y=c("button",{type:"button",class:"an-icon-cat","data-cat":v});y.textContent=_,r.appendChild(y)}),this._catBar=r;const h=c("div",{class:"an-emoji-grid"});ki.forEach(([v,_,y])=>{const w=c("button",{type:"button",class:"an-emoji-cell","data-char":v,"data-keywords":_,"data-cat":y,title:_.split(" ").slice(0,2).join(" ")});w.textContent=v,h.appendChild(w)}),this._grid=h;const p=c("div",{class:"an-dialog-actions"}),m=c("button",{type:"button",class:"an-btn"});m.textContent="Cancel",p.appendChild(m),t.append(i,a,r,h,p),e.appendChild(t);const u=d(o,"click",()=>this._close()),f=d(m,"click",()=>this._close()),g=d(e,"click",v=>{v.target===e&&this._close()}),b=d(a,"input",()=>this._filterEmojis(a.value,this._activeCat)),C=d(r,"click",v=>{const _=v.target.closest("[data-cat]");_&&(this._activeCat=_.dataset.cat,this._updateCatTabs(),this._filterEmojis(this._searchInput.value,this._activeCat))}),T=d(h,"click",v=>{const _=v.target.closest(".an-emoji-cell");_&&this._onEmojiClick(_.dataset.char)});return this._disposers.push(u,f,g,b,C,T),e}_updateCatTabs(){this._catBar.querySelectorAll(".an-icon-cat").forEach(e=>{e.classList.toggle("active",e.dataset.cat===this._activeCat)})}_filterEmojis(e,t){const i=(e||"").trim().toLowerCase();let s=0;this._grid.querySelectorAll(".an-emoji-cell").forEach(a=>{const r=!t||t==="all"||a.dataset.cat===t,l=!i||a.dataset.keywords.includes(i)||a.dataset.char===i,h=r&&l;a.style.display=h?"":"none",h&&s++});let o=this._grid.querySelector(".an-icon-empty");o||(o=c("div",{class:"an-icon-empty"}),o.textContent="No emojis found",this._grid.appendChild(o)),o.style.display=s>0?"none":""}_onEmojiClick(e){const t=this._savedRange,i=this.context.layoutInfo.editable;t&&t.select();const s=window.getSelection();let o=s&&s.rangeCount>0?s.getRangeAt(0):null;o||(o=document.createRange(),o.selectNodeContents(i),o.collapse(!1)),o.deleteContents();const a=document.createTextNode(e);o.insertNode(a),o.setStartAfter(a),o.collapse(!0),s&&(s.removeAllRanges(),s.addRange(o)),this._close(),i.focus(),this.context.invoke("editor.afterCommand")}_open(){this._dialog&&(this._dialog.style.display="flex",this._removeTrap=O(this._dialog,()=>this._close()),setTimeout(()=>this._searchInput&&this._searchInput.focus(),50))}_close(){this._dialog&&(this._dialog.style.display="none"),this._removeTrap&&(this._removeTrap(),this._removeTrap=null),this._savedRange=null}}const Si=[{id:"popular",label:"Popular"},{id:"interface",label:"Interface"},{id:"navigation",label:"Navigation"},{id:"media",label:"Media"},{id:"communication",label:"Communication"},{id:"files",label:"Files"},{id:"people",label:"People"},{id:"objects",label:"Objects"}],Ii=[["house","popular"],["star","popular"],["heart","popular"],["check","popular"],["xmark","popular"],["plus","popular"],["minus","popular"],["magnifying-glass","popular"],["gear","popular"],["bell","popular"],["user","popular"],["envelope","popular"],["phone","popular"],["calendar","popular"],["clock","popular"],["lock","popular"],["eye","popular"],["eye-slash","popular"],["trash","popular"],["pen","popular"],["bookmark","popular"],["flag","popular"],["thumbs-up","popular"],["thumbs-down","popular"],["circle-info","popular"],["triangle-exclamation","popular"],["circle-check","popular"],["circle-xmark","popular"],["share","popular"],["download","popular"],["upload","popular"],["tag","popular"],["bars","interface"],["ellipsis","interface"],["ellipsis-vertical","interface"],["list","interface"],["table-cells","interface"],["table-list","interface"],["grip","interface"],["filter","interface"],["sort","interface"],["arrows-rotate","interface"],["rotate","interface"],["rotate-left","interface"],["rotate-right","interface"],["copy","interface"],["floppy-disk","interface"],["print","interface"],["link","interface"],["code","interface"],["expand","interface"],["compress","interface"],["cloud","interface"],["lock-open","interface"],["key","interface"],["shield","interface"],["shield-halved","interface"],["sliders","interface"],["toggle-on","interface"],["square-check","interface"],["circle-plus","interface"],["circle-minus","interface"],["arrow-right","navigation"],["arrow-left","navigation"],["arrow-up","navigation"],["arrow-down","navigation"],["chevron-right","navigation"],["chevron-left","navigation"],["chevron-up","navigation"],["chevron-down","navigation"],["angle-right","navigation"],["angle-left","navigation"],["angle-up","navigation"],["angle-down","navigation"],["angles-right","navigation"],["angles-left","navigation"],["location-dot","navigation"],["compass","navigation"],["map","navigation"],["map-pin","navigation"],["route","navigation"],["circle-arrow-right","navigation"],["circle-arrow-left","navigation"],["arrow-trend-up","navigation"],["arrow-trend-down","navigation"],["right-from-bracket","navigation"],["right-to-bracket","navigation"],["play","media"],["pause","media"],["stop","media"],["forward","media"],["backward","media"],["forward-step","media"],["backward-step","media"],["volume-high","media"],["volume-low","media"],["volume-xmark","media"],["volume-off","media"],["music","media"],["headphones","media"],["microphone","media"],["microphone-slash","media"],["film","media"],["camera","media"],["camera-rotate","media"],["video","media"],["image","media"],["images","media"],["photo-film","media"],["podcast","media"],["radio","media"],["comment","communication"],["comments","communication"],["comment-dots","communication"],["message","communication"],["paper-plane","communication"],["reply","communication"],["reply-all","communication"],["at","communication"],["hashtag","communication"],["wifi","communication"],["signal","communication"],["rss","communication"],["share-nodes","communication"],["inbox","communication"],["phone-volume","communication"],["mobile","communication"],["mobile-screen","communication"],["laptop","communication"],["desktop","communication"],["tower-broadcast","communication"],["file","files"],["file-lines","files"],["folder","files"],["folder-open","files"],["folder-plus","files"],["folder-minus","files"],["file-image","files"],["file-pdf","files"],["file-code","files"],["file-zipper","files"],["file-audio","files"],["file-video","files"],["file-arrow-up","files"],["file-arrow-down","files"],["database","files"],["box","files"],["box-open","files"],["hard-drive","files"],["server","files"],["user","people"],["users","people"],["user-group","people"],["user-plus","people"],["user-minus","people"],["user-check","people"],["user-xmark","people"],["user-tie","people"],["user-shield","people"],["user-secret","people"],["person","people"],["person-running","people"],["person-walking","people"],["child","people"],["handshake","people"],["hand","people"],["hands-holding","people"],["people-group","people"],["pencil","objects"],["paintbrush","objects"],["eraser","objects"],["scissors","objects"],["wrench","objects"],["screwdriver","objects"],["hammer","objects"],["toolbox","objects"],["graduation-cap","objects"],["book","objects"],["book-open","objects"],["glasses","objects"],["microscope","objects"],["flask","objects"],["stethoscope","objects"],["hospital","objects"],["building","objects"],["city","objects"],["car","objects"],["truck","objects"],["plane","objects"],["train","objects"],["bicycle","objects"],["bus","objects"],["rocket","objects"],["briefcase","objects"],["cart-shopping","objects"],["bag-shopping","objects"],["credit-card","objects"],["money-bill","objects"],["chart-bar","objects"],["chart-line","objects"],["chart-pie","objects"],["bolt","objects"],["sun","objects"],["moon","objects"],["snowflake","objects"],["fire","objects"],["droplet","objects"],["leaf","objects"],["tree","objects"],["earth-americas","objects"],["globe","objects"],["award","objects"],["trophy","objects"],["gift","objects"],["puzzle-piece","objects"]];class Ei{constructor(e){this.context=e,this._dialog=null,this._disposers=[],this._savedRange=null,this._selectedIcon=null,this._activeCat="all"}initialize(){return this._ensureFontAwesome(),this}_ensureFontAwesome(){if(document.getElementById("an-fontawesome-css"))return;const e=Array.from(document.querySelectorAll('link[rel="stylesheet"]')).map(i=>i.href||"").join(" ");if(/fontawesome|font-awesome/.test(e)||document.querySelector(".fa-solid, .fas, .far, .fab"))return;const t=document.createElement("link");t.id="an-fontawesome-css",t.rel="stylesheet",t.href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css",t.crossOrigin="anonymous",t.referrerPolicy="no-referrer",document.head.appendChild(t)}destroy(){this._disposers.forEach(e=>e()),this._disposers=[],this._dialog&&this._dialog.parentNode&&this._dialog.parentNode.removeChild(this._dialog),this._dialog=null}show(){this._dialog||(this._dialog=this._buildDialog(),document.body.appendChild(this._dialog)),G(e=>{this._savedRange=e}),this._selectedIcon=null,this._activeCat="all",this._searchInput.value="",this._grid.querySelectorAll(".an-icon-cell.active").forEach(e=>e.classList.remove("active")),this._insertBtn.setAttribute("disabled",""),this._updateCatTabs(),this._filterIcons("","all"),this._updatePreview(null),this._open()}_buildDialog(){const e=c("div",{class:"an-dialog-overlay",role:"dialog","aria-modal":"true","aria-label":"Insert FA icon"}),t=c("div",{class:"an-dialog-box an-icon-box"}),i=c("div",{class:"an-icon-title-row"}),s=c("h3",{class:"an-dialog-title"});s.textContent="Insert FA Icon";const o=c("button",{type:"button",class:"an-icon-close","aria-label":"Close"});o.innerHTML="×",i.append(s,o);const a=c("input",{type:"search",class:"an-input an-icon-search",placeholder:"Search icons…",autocomplete:"off"});this._searchInput=a;const r=c("div",{class:"an-icon-cats"}),l=c("button",{type:"button",class:"an-icon-cat active","data-cat":"all"});l.textContent="All",r.appendChild(l),Si.forEach(({id:x,label:R})=>{const B=c("button",{type:"button",class:"an-icon-cat","data-cat":x});B.textContent=R,r.appendChild(B)}),this._catBar=r;const h=c("div",{class:"an-icon-grid"});Ii.forEach(([x,R])=>{const B=c("button",{type:"button",class:"an-icon-cell","data-name":x,"data-cat":R,title:x}),ce=c("i",{class:"fa-solid fa-"+x,"aria-hidden":"true"}),Ve=c("span");Ve.textContent=x,B.append(ce,Ve),h.appendChild(B)}),this._grid=h;const p=c("div",{class:"an-icon-options"}),m=c("label",{class:"an-label"});m.textContent="Style";const u=c("select",{class:"an-input an-icon-option-select"});[["fa-solid","Solid"],["fa-regular","Regular"],["fa-light","Light (Pro)"]].forEach(([x,R])=>{const B=c("option",{value:x});B.textContent=R,u.appendChild(B)}),u.value="fa-solid",this._styleSelect=u;const f=c("label",{class:"an-label"});f.textContent="Size";const g=c("select",{class:"an-input an-icon-option-select"});[["","Inherit"],["0.75em","0.75em"],["1em","1em"],["1.25em","1.25em"],["1.5em","1.5em"],["2em","2em"],["3em","3em"]].forEach(([x,R])=>{const B=c("option",{value:x});x==="1em"&&(B.selected=!0),B.textContent=R,g.appendChild(B)}),this._sizeSelect=g;const b=c("label",{class:"an-label"});b.textContent="Color";const C=c("input",{type:"color",class:"an-icon-color",value:"#000000"});this._colorInput=C;const T=c("label",{class:"an-label an-label-inline an-icon-use-color"}),v=c("input",{type:"checkbox",checked:""});this._useColorCb=v,T.append(v,document.createTextNode(" Use color")),p.append(m,u,f,g,b,C,T);const _=c("div",{class:"an-icon-preview"}),y=c("span",{class:"an-icon-preview-hint"});y.textContent="Select an icon",_.appendChild(y),this._preview=_;const w=c("div",{class:"an-dialog-actions"}),k=c("button",{type:"button",class:"an-btn an-btn-primary",disabled:""});k.textContent="Insert FA Icon";const I=c("button",{type:"button",class:"an-btn"});I.textContent="Cancel",w.append(k,I),this._insertBtn=k,t.append(i,a,r,h,p,_,w),e.appendChild(t);const A=d(o,"click",()=>this._close()),j=d(I,"click",()=>this._close()),J=d(k,"click",()=>this._onInsert()),ee=d(e,"click",x=>{x.target===e&&this._close()}),te=d(a,"input",()=>this._filterIcons(a.value,this._activeCat)),ie=d(r,"click",x=>{const R=x.target.closest("[data-cat]");R&&(this._activeCat=R.dataset.cat,this._updateCatTabs(),this._filterIcons(this._searchInput.value,this._activeCat))}),M=d(h,"click",x=>{const R=x.target.closest(".an-icon-cell");R&&this._selectIcon(R.dataset.name)}),de=d(u,"change",()=>this._updatePreview(this._selectedIcon)),pe=d(g,"change",()=>this._updatePreview(this._selectedIcon)),ue=d(C,"input",()=>this._updatePreview(this._selectedIcon)),Y=d(v,"change",()=>this._updatePreview(this._selectedIcon));return this._disposers.push(A,j,J,ee,te,ie,M,de,pe,ue,Y),e}_updateCatTabs(){this._catBar.querySelectorAll(".an-icon-cat").forEach(e=>{e.classList.toggle("active",e.dataset.cat===this._activeCat)})}_filterIcons(e,t){const i=(e||"").trim().toLowerCase();let s=0;this._grid.querySelectorAll(".an-icon-cell").forEach(a=>{const r=a.dataset.name,l=a.dataset.cat,h=!t||t==="all"||l===t,p=!i||r.includes(i),m=h&&p;a.style.display=m?"":"none",m&&s++});let o=this._grid.querySelector(".an-icon-empty");o||(o=c("div",{class:"an-icon-empty"}),o.textContent="No icons found",this._grid.appendChild(o)),o.style.display=s>0?"none":""}_selectIcon(e){this._selectedIcon=e,this._grid.querySelectorAll(".an-icon-cell").forEach(t=>{t.classList.toggle("active",t.dataset.name===e)}),this._insertBtn.removeAttribute("disabled"),this._updatePreview(e)}_updatePreview(e){if(!this._preview)return;if(!e){this._preview.innerHTML='<span class="an-icon-preview-hint">Select an icon</span>';return}const t=this._styleSelect&&this._styleSelect.value||"fa-solid",i=this._sizeSelect&&this._sizeSelect.value||"1em",o=(this._useColorCb?this._useColorCb.checked:!1)&&this._colorInput?this._colorInput.value:"",a=[`font-size:${i}`,o?`color:${o}`:""].filter(Boolean).join(";");this._preview.innerHTML=`<i class="${t} fa-${e}" aria-hidden="true"${a?` style="${a}"`:""}></i><div class="an-icon-preview-name">${t} fa-${e}</div>`}_onInsert(){if(!this._selectedIcon)return;const e=this._styleSelect&&this._styleSelect.value||"fa-solid",t=this._sizeSelect&&this._sizeSelect.value||"",s=(this._useColorCb?this._useColorCb.checked:!1)&&this._colorInput?this._colorInput.value:"",o=[t?`font-size:${t}`:"",s?`color:${s}`:""].filter(Boolean),a=document.createElement("i");a.className=`${e} fa-${this._selectedIcon}`,a.setAttribute("aria-hidden","true"),a.setAttribute("contenteditable","false"),o.length&&a.setAttribute("style",o.join(";"));const r=this._savedRange,l=this.context.layoutInfo.editable;r&&r.select();const h=window.getSelection();let p=h&&h.rangeCount>0?h.getRangeAt(0):null;p||(p=document.createRange(),p.selectNodeContents(l),p.collapse(!1)),p.deleteContents(),p.insertNode(a);let m=a.nextSibling;!m||m.nodeType!==Node.TEXT_NODE?(m=document.createTextNode(""),a.parentNode.insertBefore(m,a.nextSibling)):m.textContent||(m.textContent="");const u=(m.textContent||"").startsWith("")?1:0,f=document.createRange();f.setStart(m,Math.min(u,m.textContent.length)),f.collapse(!0),h&&(h.removeAllRanges(),h.addRange(f)),this._close(),l.focus(),h&&(h.removeAllRanges(),h.addRange(f)),this.context.invoke("editor.afterCommand")}_open(){this._dialog&&(this._dialog.style.display="flex",this._removeTrap=O(this._dialog,()=>this._close()),setTimeout(()=>this._searchInput&&this._searchInput.focus(),50))}_close(){this._dialog&&(this._dialog.style.display="none"),this._removeTrap&&(this._removeTrap(),this._removeTrap=null),this._savedRange=null,this._selectedIcon=null}}const L={undo:'<svg xmlns="http://www.w3.org/2000/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="M3 7v6h6"/><path d="M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13"/></svg>',redo:'<svg xmlns="http://www.w3.org/2000/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="M21 7v6h-6"/><path d="M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3L21 13"/></svg>',cut:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="20" r="3"/><circle cx="6" cy="4" r="3"/><line x1="19" y1="5" x2="6" y2="19"/><line x1="19" y1="19" x2="13.5" y2="13.5"/></svg>',copy:'<svg xmlns="http://www.w3.org/2000/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="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>',paste:'<svg xmlns="http://www.w3.org/2000/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="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><rect x="8" y="2" width="8" height="4" rx="1"/></svg>',bold:'<svg xmlns="http://www.w3.org/2000/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="M6 4h8a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"/><path d="M6 12h9a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"/></svg>',italic:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="4" x2="10" y2="4"/><line x1="14" y1="20" x2="5" y2="20"/><line x1="15" y1="4" x2="9" y2="20"/></svg>',underline:'<svg xmlns="http://www.w3.org/2000/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="M6 3v7a6 6 0 0 0 6 6 6 6 0 0 0 6-6V3"/><line x1="4" y1="21" x2="20" y2="21"/></svg>',link:'<svg xmlns="http://www.w3.org/2000/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="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>',image:'<svg xmlns="http://www.w3.org/2000/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="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>',video:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2"/></svg>',copyFormat:'<svg xmlns="http://www.w3.org/2000/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="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>',pasteFormat:'<svg xmlns="http://www.w3.org/2000/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="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><rect x="8" y="2" width="8" height="4" rx="1"/><path d="m9 14 2 2 4-4"/></svg>',removeFormat:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21"/><path d="M22 21H7"/><path d="m5 11 9 9"/></svg>',table:'<svg xmlns="http://www.w3.org/2000/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="3" width="18" height="18" rx="1"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="3" y1="15" x2="21" y2="15"/><line x1="9" y1="3" x2="9" y2="21"/><line x1="15" y1="3" x2="15" y2="21"/></svg>'},Ri=[{name:"undo",label:"Undo",icon:L.undo,action:n=>n.invoke("editor.undo")},{name:"redo",label:"Redo",icon:L.redo,action:n=>n.invoke("editor.redo")},{separator:!0},{name:"cut",label:"Cut",icon:L.cut,action:()=>document.execCommand("cut")},{name:"copy",label:"Copy",icon:L.copy,action:()=>document.execCommand("copy")},{name:"paste",label:"Paste",icon:L.paste,action:n=>{if(!navigator.clipboard)return;const e=n.layoutInfo&&n.layoutInfo.editable;if(!e)return;const t=(i,s)=>{if(e.focus(),i){const o=W(i);document.execCommand("insertHTML",!1,o)}else s&&document.execCommand("insertText",!1,s);n.invoke("editor.afterCommand")};typeof navigator.clipboard.read=="function"?navigator.clipboard.read().then(i=>{for(const s of i)if(s.types.includes("text/html")){s.getType("text/html").then(o=>o.text()).then(o=>t(o,null));return}navigator.clipboard.readText().then(s=>t(null,s)).catch(()=>{})}).catch(()=>{navigator.clipboard.readText().then(i=>t(null,i)).catch(()=>{})}):typeof navigator.clipboard.readText=="function"&&navigator.clipboard.readText().then(i=>t(null,i)).catch(()=>{})}},{separator:!0},{name:"bold",label:"Bold",icon:L.bold,action:n=>n.invoke("editor.bold")},{name:"italic",label:"Italic",icon:L.italic,action:n=>n.invoke("editor.italic")},{name:"underline",label:"Underline",icon:L.underline,action:n=>n.invoke("editor.underline")},{separator:!0},{name:"copyFormat",label:"Copy Format",icon:L.copyFormat,action:n=>n.invoke("contextMenu.copyFormat")},{name:"pasteFormat",label:"Paste Format",icon:L.pasteFormat,action:n=>n.invoke("contextMenu.pasteFormat"),disabled:n=>!n.invoke("contextMenu.hasCopiedFormat")},{name:"removeFormat",label:"Remove Format",icon:L.removeFormat,action:n=>n.invoke("contextMenu.removeFormat")},{separator:!0},{name:"link",label:"Insert Link",icon:L.link,action:n=>n.invoke("linkDialog.show")},{name:"image",label:"Insert Image",icon:L.image,action:n=>n.invoke("imageDialog.show")},{name:"video",label:"Insert Video",icon:L.video,action:n=>n.invoke("videoDialog.show")},{name:"table",label:"Insert Table",icon:L.table,tableGrid:!0}];class Ai{constructor(e){this.context=e,this.options=e.options||{},this._items=this.options.contextMenu&&this.options.contextMenu.items||Ri,this.el=null,this._disposers=[],this._menuDisposers=[],this._lastX=0,this._lastY=0,this._copiedFormat=null,this._savedRange=null}initialize(){this.el=c("div",{class:"an-contextmenu",role:"menu","aria-hidden":"true"}),this.el.style.display="none",document.body.appendChild(this.el),this._renderItems(this._items);const e=this.context.layoutInfo&&this.context.layoutInfo.editable;return e&&this._disposers.push(d(e,"contextmenu",t=>this._onContextMenu(t))),this._disposers.push(d(document,"click",t=>this._maybeHide(t))),this._disposers.push(d(document,"keydown",t=>{t.key==="Escape"&&this.hide()})),this._disposers.push(d(window,"scroll",()=>this.hide(),{passive:!0})),this}destroy(){this._menuDisposers.forEach(e=>{try{e()}catch{}}),this._menuDisposers=[],this._disposers.forEach(e=>{try{e()}catch{}}),this._disposers=[],this.el&&this.el.parentNode&&this.el.parentNode.removeChild(this.el),this.el=null}_renderItems(e){this._menuDisposers.forEach(t=>t()),this._menuDisposers=[],this.el&&(this.el.innerHTML="",e.forEach(t=>{if(t.separator||t.sep){this.el.appendChild(c("div",{class:"an-context-sep"}));return}if(t.back){const o=c("button",{type:"button",class:"an-context-back"}),a=c("span",{class:"an-context-icon","aria-hidden":"true"});a.innerHTML=L.back,o.appendChild(a),o.appendChild(c("span",{class:"an-context-label"},[t.label||"Back"]));const r=d(o,"click",l=>{l.stopPropagation(),this._renderItems(t.navigate()),this._reposition()});this._menuDisposers.push(r),this.el.appendChild(o);return}if(t.navigate){const o=c("button",{type:"button",class:"an-context-item an-context-submenu","data-name":t.name||""});if(t.icon){const l=c("span",{class:"an-context-icon","aria-hidden":"true"});l.innerHTML=t.icon,o.appendChild(l)}o.appendChild(c("span",{class:"an-context-label"},[t.label||t.name]));const a=c("span",{class:"an-context-chevron","aria-hidden":"true"});a.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>',o.appendChild(a);const r=d(o,"click",l=>{l.stopPropagation(),this._renderItems(t.navigate()),this._reposition()});this._menuDisposers.push(r),this.el.appendChild(o);return}if(t.tableGrid){const r=c("div",{class:"an-context-table-wrap"}),l=c("button",{type:"button",class:"an-context-item an-context-submenu","data-name":t.name||"table"});if(t.icon){const y=c("span",{class:"an-context-icon","aria-hidden":"true"});y.innerHTML=t.icon,l.appendChild(y)}l.appendChild(c("span",{class:"an-context-label"},[t.label||"Insert Table"]));const h=c("span",{class:"an-context-chevron","aria-hidden":"true"});h.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>',l.appendChild(h);const p=c("div",{class:"an-context-table-grid-panel"});p.style.display="none";const m=c("div",{class:"an-table-grid"});m.style.gridTemplateColumns="repeat(8, 16px)";const u=c("div",{class:"an-table-label"});u.textContent="Insert Table";const f=[];for(let y=1;y<=8;y++)for(let w=1;w<=8;w++){const k=c("div",{class:"an-table-cell","data-row":String(y),"data-col":String(w)});k.style.width="16px",k.style.height="16px",f.push(k),m.appendChild(k)}const g=(y,w)=>{f.forEach(k=>{k.classList.toggle("active",+k.dataset.row<=y&&+k.dataset.col<=w)}),u.textContent=y&&w?`${w} × ${y}`:"Insert Table"};p.appendChild(m),p.appendChild(u);let b=!1;const C=d(l,"click",y=>{y.stopPropagation(),b=!b,p.style.display=b?"":"none",h.style.transform=b?"rotate(90deg)":"",this._reposition()});this._menuDisposers.push(C);const T=d(m,"mousemove",y=>{const w=y.target.closest("[data-row]");w&&g(+w.dataset.row,+w.dataset.col)}),v=d(m,"mouseleave",()=>g(0,0)),_=d(m,"click",y=>{const w=y.target.closest("[data-row]");if(!w)return;const k=+w.dataset.row,I=+w.dataset.col,A=this.context.layoutInfo&&this.context.layoutInfo.editable;if(A&&this._savedRange){A.focus();const j=window.getSelection();j.removeAllRanges(),j.addRange(this._savedRange.cloneRange())}this.hide(),this.context.invoke("editor.insertTable",I,k)});this._menuDisposers.push(T,v,_),r.appendChild(l),r.appendChild(p),this.el.appendChild(r);return}const i=c("button",{type:"button",class:"an-context-item","data-name":t.name||""});if((typeof t.disabled=="function"?t.disabled(this.context):t.disabled)&&(i.disabled=!0),t.icon){const o=c("span",{class:"an-context-icon","aria-hidden":"true"});o.innerHTML=t.icon,i.appendChild(o)}i.appendChild(c("span",{class:"an-context-label"},[t.label||t.name]));const s=d(i,"click",o=>{o.stopPropagation(),this.hide();try{t.action(this.context)}catch(a){console.error(a)}});this._menuDisposers.push(s),this.el.appendChild(i)}))}_onContextMenu(e){const t=this.context.layoutInfo&&this.context.layoutInfo.editable;if(!t||!t.contains(e.target))return;e.preventDefault(),this._lastX=e.clientX,this._lastY=e.clientY;const i=window.getSelection();this._savedRange=i&&i.rangeCount>0?i.getRangeAt(0).cloneRange():null,this._renderItems(this._items),this.showAt(e.clientX,e.clientY)}_maybeHide(e){this.el&&(this.el.contains(e.target)||this.hide())}showAt(e,t){this.el&&(this.el.style.display="block",this._reposition(e,t),this.el.setAttribute("aria-hidden","false"))}_reposition(e,t){if(!this.el)return;const i=e!==void 0?e:this._lastX,s=t!==void 0?t:this._lastY,o=this.el.getBoundingClientRect();let a=i,r=s;a+o.width>window.innerWidth&&(a=window.innerWidth-o.width-8),r+o.height>window.innerHeight&&(r=window.innerHeight-o.height-8),this.el.style.left=`${a}px`,this.el.style.top=`${r}px`}hide(){this.el&&(this.el.style.display="none",this.el.setAttribute("aria-hidden","true"))}hasCopiedFormat(){return!!this._copiedFormat}copyFormat(){const e=this._savedRange;if(!e)return;const t=this.context.layoutInfo&&this.context.layoutInfo.editable;let i=e.startContainer;if(i.nodeType===Node.TEXT_NODE&&(i=i.parentElement),!i||!t||!t.contains(i))return;const s=window.getComputedStyle(i),o=this._findExplicitStyle(i,t,"fontFamily"),a=this._findExplicitStyle(i,t,"fontSize");this._copiedFormat={bold:parseInt(s.fontWeight,10)>=700,italic:s.fontStyle==="italic"||s.fontStyle==="oblique",underline:(s.textDecorationLine||"").includes("underline"),strikethrough:(s.textDecorationLine||"").includes("line-through"),fontFamily:o,fontSize:a,color:this._isDefaultColor(s.color)?null:s.color,backgroundColor:s.backgroundColor}}_findExplicitStyle(e,t,i){let s=e;for(;s&&s!==t&&s!==document.body;){if(s.style&&s.style[i])return s.style[i];if(s.nodeName==="FONT"){if(i==="fontFamily"&&s.getAttribute("face"))return s.getAttribute("face");if(i==="fontSize"&&s.getAttribute("size"))return null}s=s.parentElement}return null}_isDefaultColor(e){return!e||e==="rgb(0, 0, 0)"||e==="rgba(0, 0, 0, 0)"||e==="transparent"}pasteFormat(){if(!this._copiedFormat||!this._savedRange)return;const e=this._copiedFormat,t=this.context.layoutInfo&&this.context.layoutInfo.editable;if(!t)return;t.focus();const i=window.getSelection();if(i.removeAllRanges(),i.addRange(this._savedRange.cloneRange()),document.execCommand("removeFormat"),e.bold&&document.execCommand("bold"),e.italic&&document.execCommand("italic"),e.underline&&document.execCommand("underline"),e.strikethrough&&document.execCommand("strikeThrough"),e.color&&document.execCommand("foreColor",!1,e.color),(o=>!o||o==="rgba(0, 0, 0, 0)"||o==="transparent")(e.backgroundColor)||document.execCommand("hiliteColor",!1,e.backgroundColor),e.fontFamily&&document.execCommand("fontName",!1,e.fontFamily),e.fontSize){const o=`fs-${Date.now()}`,a=new Set(t.querySelectorAll('font[size="7"]'));document.execCommand("fontSize",!1,"7"),t.querySelectorAll('font[size="7"]').forEach(r=>{a.has(r)||r.setAttribute("data-an-tmp",o)}),t.querySelectorAll(`[data-an-tmp="${o}"]`).forEach(r=>{const l=document.createElement("span");for(l.style.fontSize=e.fontSize,r.parentNode.insertBefore(l,r);r.firstChild;)l.appendChild(r.firstChild);r.parentNode.removeChild(r)})}this.context.invoke("editor.afterCommand")}removeFormat(){if(!this._savedRange)return;const e=this.context.layoutInfo&&this.context.layoutInfo.editable;if(!e)return;e.focus();const t=window.getSelection();t.removeAllRanges(),t.addRange(this._savedRange.cloneRange()),document.execCommand("removeFormat");const i=t.getRangeAt(0),s=i.commonAncestorContainer,o=s.nodeType===Node.TEXT_NODE?s.parentElement:s,a=document.createNodeIterator(o,NodeFilter.SHOW_ELEMENT);let r;for(;r=a.nextNode();)if(!(!e.contains(r)||r===e))try{i.intersectsNode(r)&&r.removeAttribute("style")}catch{}this.context.invoke("editor.afterCommand")}}const Li=[{category:"Text Formatting",items:[{keys:"Ctrl + B",action:"Bold"},{keys:"Ctrl + I",action:"Italic"},{keys:"Ctrl + U",action:"Underline"},{keys:"Ctrl + K",action:"Insert / edit link"}]},{category:"History",items:[{keys:"Ctrl + Z",action:"Undo"},{keys:"Ctrl + Y / Ctrl + Shift + Z",action:"Redo"}]},{category:"Selection & Navigation",items:[{keys:"Ctrl + A",action:"Select all content"},{keys:"Tab",action:"Indent list item / insert spaces"},{keys:"Shift + Tab",action:"Outdent list item"}]},{category:"Clipboard",items:[{keys:"Ctrl + Shift + V",action:"Paste as plain text"}]},{category:"Find & Replace",items:[{keys:"Ctrl + F",action:"Find in document"},{keys:"Ctrl + H",action:"Find & Replace"}]},{category:"Editor",items:[{keys:"Shift + ?",action:"Show this keyboard shortcuts dialog"}]}];class Bi{constructor(e){this.context=e,this._dialog=null,this._closeBtn=null,this._disposers=[]}initialize(){return this._dialog=this._buildDialog(),document.body.appendChild(this._dialog),this}destroy(){this._disposers.forEach(e=>e()),this._disposers=[],this._dialog&&this._dialog.parentNode&&this._dialog.parentNode.removeChild(this._dialog),this._dialog=null}show(){this._dialog&&(this._dialog.style.display="flex",this._removeTrap=O(this._dialog,()=>this._close()),setTimeout(()=>this._closeBtn&&this._closeBtn.focus(),50))}_close(){this._dialog&&(this._dialog.style.display="none"),this._removeTrap&&(this._removeTrap(),this._removeTrap=null)}_buildDialog(){const e=c("div",{class:"an-dialog-overlay",role:"dialog","aria-modal":"true","aria-label":"Keyboard Shortcuts"}),t=c("div",{class:"an-dialog-box an-shortcuts-box"}),i=c("div",{class:"an-icon-title-row"}),s=c("h3",{class:"an-dialog-title"});s.textContent="Keyboard Shortcuts";const o=c("button",{type:"button",class:"an-icon-close","aria-label":"Close"});o.textContent="×",this._closeBtn=o,i.append(s,o),t.appendChild(i),Li.forEach(({category:l,items:h})=>{const p=c("div",{class:"an-shortcuts-cat"});p.textContent=l,t.appendChild(p);const m=c("div",{class:"an-shortcuts-table"});h.forEach(({keys:u,action:f})=>{const g=c("div",{class:"an-shortcuts-row"}),b=c("span",{class:"an-shortcuts-key"});b.textContent=u;const C=c("span",{class:"an-shortcuts-action"});C.textContent=f,g.append(b,C),m.appendChild(g)}),t.appendChild(m)}),e.appendChild(t);const a=d(o,"click",()=>this._close()),r=d(e,"click",l=>{l.target===e&&this._close()});return this._disposers.push(a,r),e}}class Mi{constructor(e){this.context=e,this._dialog=null,this._findInput=null,this._replaceInput=null,this._caseCheckbox=null,this._counterEl=null,this._closeBtn=null,this._matches=[],this._currentIndex=-1,this._caseSensitive=!1,this._mode="find",this._disposers=[],this._removeTrap=null,this._focusTimer=null}initialize(){return this._dialog=this._buildDialog(),document.body.appendChild(this._dialog),this}destroy(){clearTimeout(this._focusTimer),this._focusTimer=null,this._clearHighlights(),this._disposers.forEach(e=>e()),this._disposers=[],this._dialog&&this._dialog.parentNode&&this._dialog.parentNode.removeChild(this._dialog),this._dialog=null}show(e="find"){this._mode=e,this._updateMode(),this._open(),clearTimeout(this._focusTimer),this._focusTimer=setTimeout(()=>{this._findInput&&(this._findInput.select(),this._findInput.focus())},50)}_open(){if(this._dialog){if(this._dialog.style.display==="flex"){this._findInput&&this._findInput.focus();return}this._dialog.style.display="flex",this._removeTrap&&(this._removeTrap(),this._removeTrap=null),this._removeTrap=O(this._dialog,()=>this._close())}}_close(){this._clearHighlights(),this._dialog&&(this._dialog.style.display="none"),this._removeTrap&&(this._removeTrap(),this._removeTrap=null),this.context.invoke("editor.focus")}_updateMode(){if(!this._dialog)return;const e=this._dialog.querySelector(".an-fr-replace-row"),t=this._dialog.querySelector(".an-fr-replace-actions"),i=this._dialog.querySelector(".an-dialog-title"),s=this._mode==="replace";e&&(e.style.display=s?"":"none"),t&&(t.style.display=s?"":"none"),i&&(i.textContent=s?"Find & Replace":"Find")}_buildDialog(){const e=c("div",{class:"an-dialog-overlay an-fr-dialog",role:"dialog","aria-modal":"true","aria-label":"Find and Replace"}),t=c("div",{class:"an-dialog-box"}),i=c("div",{class:"an-icon-title-row"}),s=c("h3",{class:"an-dialog-title"});s.textContent="Find";const o=c("button",{type:"button",class:"an-icon-close","aria-label":"Close"});o.textContent="×",this._closeBtn=o,i.append(s,o),t.appendChild(i);const a=c("div",{class:"an-fr-find-row"}),r=c("input",{type:"text",class:"an-input",placeholder:"Find…","aria-label":"Search text"});this._findInput=r,a.appendChild(r),t.appendChild(a);const l=c("div",{class:"an-fr-options-row"}),h=c("label",{class:"an-label an-label-inline"}),p=c("input",{type:"checkbox","aria-label":"Case sensitive"});this._caseCheckbox=p,h.append(p,document.createTextNode(" Case sensitive"));const m=c("span",{class:"an-fr-counter"});this._counterEl=m,l.append(h,m),t.appendChild(l);const u=c("div",{class:"an-dialog-actions an-fr-find-actions"}),f=c("button",{type:"button",class:"an-btn"});f.textContent="← Prev";const g=c("button",{type:"button",class:"an-btn an-btn-primary"});g.textContent="Next →",u.append(f,g),t.appendChild(u);const b=c("div",{class:"an-fr-replace-row"});b.style.display="none";const C=c("input",{type:"text",class:"an-input",placeholder:"Replace with…","aria-label":"Replace with"});this._replaceInput=C,b.appendChild(C),t.appendChild(b);const T=c("div",{class:"an-dialog-actions an-fr-replace-actions"});T.style.display="none";const v=c("button",{type:"button",class:"an-btn"});v.textContent="Replace";const _=c("button",{type:"button",class:"an-btn an-btn-primary"});_.textContent="Replace All",T.append(v,_),t.appendChild(T),e.appendChild(t);const y=d(o,"click",()=>this._close()),w=d(e,"click",M=>{M.target===e&&this._close()}),k=d(r,"input",()=>this._onSearch()),I=d(p,"change",()=>{this._caseSensitive=p.checked,this._onSearch()}),A=d(g,"click",()=>this._next()),j=d(f,"click",()=>this._prev()),J=d(v,"click",()=>this._replace()),ee=d(_,"click",()=>this._replaceAll()),te=d(r,"keydown",M=>{M.key==="Enter"&&(M.preventDefault(),M.shiftKey?this._prev():this._next())}),ie=d(C,"keydown",M=>{M.key==="Enter"&&(M.preventDefault(),this._replace())});return this._disposers.push(y,w,k,I,A,j,J,ee,te,ie),e}_onSearch(){this._clearHighlights();const e=this._findInput?this._findInput.value:"";if(!e){this._updateCounter();return}this._findAndHighlight(e),this._updateCounter()}_findAndHighlight(e){const t=this.context.layoutInfo.editable;if(!t)return;const i=this._findRawMatches(e,t);if(i.length!==0){this._currentIndex=0;for(let s=i.length-1;s>=0;s--){const{node:o,start:a,end:r}=i[s];try{const l=document.createRange();l.setStart(o,a),l.setEnd(o,r);const h=document.createElement("mark");h.className="an-highlight",l.surroundContents(h),this._matches.unshift({mark:h})}catch{this._matches.unshift({mark:null})}}this._matches=this._matches.filter(s=>s.mark),this._matches.length!==0&&this._matches[0]&&this._matches[0].mark&&(this._matches[0].mark.className="an-highlight an-highlight-current",this._matches[0].mark.scrollIntoView({block:"center",behavior:"smooth"}))}}_findRawMatches(e,t){const i=[],s=this._caseSensitive?"g":"gi",o=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(o,s),r=document.createTreeWalker(t,4);let l;for(;l=r.nextNode();){a.lastIndex=0;let h;for(;(h=a.exec(l.textContent))!==null;)i.push({node:l,start:h.index,end:h.index+h[0].length})}return i}_next(){this._matches.length!==0&&(this._currentIndex=(this._currentIndex+1)%this._matches.length,this._scrollToMatch(this._currentIndex),this._updateCounter())}_prev(){this._matches.length!==0&&(this._currentIndex=(this._currentIndex-1+this._matches.length)%this._matches.length,this._scrollToMatch(this._currentIndex),this._updateCounter())}_scrollToMatch(e){const t=this._matches[e];!t||!t.mark||(this._matches.forEach((i,s)=>{i.mark&&(i.mark.className=s===e?"an-highlight an-highlight-current":"an-highlight")}),t.mark.scrollIntoView({block:"center",behavior:"smooth"}))}_replace(){if(this._matches.length===0||this._currentIndex<0)return;const e=this._matches[this._currentIndex];if(!e||!e.mark||!e.mark.parentNode)return;const t=this._replaceInput?this._replaceInput.value:"",i=e.mark.parentNode,s=document.createTextNode(t);i.insertBefore(s,e.mark),i.removeChild(e.mark),i.normalize(),this.context.invoke("editor.afterCommand");const o=this._currentIndex;this._onSearch(),this._matches.length>0&&(this._currentIndex=Math.min(o,this._matches.length-1),this._scrollToMatch(this._currentIndex),this._updateCounter())}_replaceAll(){if(this._matches.length===0)return;const e=this._replaceInput?this._replaceInput.value:"";this._matches.forEach(({mark:t})=>{if(!t||!t.parentNode)return;const i=document.createTextNode(e);t.parentNode.insertBefore(i,t),t.parentNode.removeChild(t)}),this.context.layoutInfo.editable&&this.context.layoutInfo.editable.normalize(),this._matches=[],this._currentIndex=-1,this.context.invoke("editor.afterCommand"),this._onSearch()}_clearHighlights(){const e=this.context.layoutInfo.editable;e&&(e.querySelectorAll("mark.an-highlight").forEach(t=>{const i=t.parentNode;if(i){for(;t.firstChild;)i.insertBefore(t.firstChild,t);i.removeChild(t)}}),e.normalize(),this._matches=[],this._currentIndex=-1)}_updateCounter(){if(!this._counterEl)return;const e=this._matches.length;if(e===0){const t=this._findInput?this._findInput.value:"";this._counterEl.textContent=t?"No results":""}else this._counterEl.textContent=`${this._currentIndex+1} / ${e}`}}const Ue=new Map;class Ni{constructor(e,t={}){this.targetEl=e,this.options=D(F,t),this.layoutInfo={},this._listeners=new Map,this._modules=new Map,this._disposers=[],this._alive=!1}initialize(){const{container:e,editable:t}=Dt(this.targetEl,this.options);this.layoutInfo.container=e,this.layoutInfo.editable=t,this._registerModules();const i=this._modules.get("toolbar");i&&i.el&&(e.insertBefore(i.el,t),this.layoutInfo.toolbar=i.el);const s=this._modules.get("statusbar");return s&&s.el&&(e.appendChild(s.el),this.layoutInfo.statusbar=s.el),this._bindEditorEvents(t),this.options.focus&&t.focus(),this._alive=!0,this.invoke("toolbar.refresh"),typeof this.options.onInit=="function"&&this.options.onInit(this),this}_registerModules(){const e=(t,i)=>{const s=new i(this);s.initialize(),this._modules.set(t,s)};e("editor",Xt),e("toolbar",Yt),e("statusbar",Kt),e("clipboard",Gt),e("contextMenu",Ai),e("placeholder",Qt),e("codeview",Zt),e("fullscreen",Jt),e("linkDialog",ei),e("imageDialog",ti),e("videoDialog",ii),e("imageResizer",oi),e("videoResizer",ai),e("linkTooltip",ci),e("imageTooltip",pi),e("videoTooltip",fi),e("tableTooltip",bi),e("codeTooltip",xi),e("emojiDialog",Ti),e("iconDialog",Ei),e("shortcutsDialog",Bi),e("findReplace",Mi);for(const[t,i]of Ue)e(t,i)}registerModule(e,t){if(this._modules.has(e))return this;const i=new t(this);return i.initialize(),this._modules.set(e,i),this}_bindEditorEvents(e){const t=d(e,"focus",()=>{this.layoutInfo.container.classList.add("an-focused"),typeof this.options.onFocus=="function"&&this.options.onFocus(this)}),i=d(e,"blur",()=>{this.layoutInfo.container.classList.remove("an-focused"),this._syncToTarget(),typeof this.options.onBlur=="function"&&this.options.onBlur(this)}),s=this.on("change",()=>this._syncToTarget());if(this._disposers.push(t,i,s),this.options.autoSave&&this.options.autoSaveKey){const o=this.on("change",()=>{try{localStorage.setItem(this.options.autoSaveKey,this.getHTML())}catch{}});this._disposers.push(o)}}invoke(e,...t){var a,r;const[i,s]=e.split("."),o=this._modules.get(i);if(!o){(typeof process>"u"||((a=process.env)==null?void 0:a.NODE_ENV)!=="production")&&console.warn(`[AutumnNote] invoke: module "${i}" not found (path: "${e}")`);return}if(typeof o[s]!="function"){(typeof process>"u"||((r=process.env)==null?void 0:r.NODE_ENV)!=="production")&&console.warn(`[AutumnNote] invoke: method "${s}" not found on module "${i}" (path: "${e}")`);return}return o[s](...t)}on(e,t){return this._listeners.has(e)||this._listeners.set(e,[]),this._listeners.get(e).push(t),()=>this.off(e,t)}off(e,t){const i=this._listeners.get(e);if(!i)return;const s=i.indexOf(t);s!==-1&&i.splice(s,1)}triggerEvent(e,...t){(this._listeners.get(e)||[]).forEach(o=>o(...t));const s="on"+e.charAt(0).toUpperCase()+e.slice(1);typeof this.options[s]=="function"&&this.options[s](...t)}getHTML(){return this.invoke("editor.getHTML")}setHTML(e){this.invoke("editor.setHTML",e)}getText(){return this.invoke("editor.getText")}setText(e){this.invoke("editor.setText",e)}clear(){this.invoke("editor.clear")}clearHistory(){this.invoke("editor.clearHistory")}isEmpty(){return this.invoke("editor.isEmpty")}insertHTML(e){this.invoke("editor.insertHTML",e)}insertText(e){this.invoke("editor.insertText",e)}setMarkdown(e){this.invoke("editor.setMarkdown",e)}getMarkdown(){return this.invoke("editor.getMarkdown")}getWordCount(){return this.invoke("statusbar.getWordCount")??0}getCharCount(){return this.invoke("statusbar.getCharCount")??0}downloadHTML(e="document.html"){this._download(this.getHTML(),e,"text/html")}downloadText(e="document.txt"){this._download(this.getText(),e,"text/plain")}downloadMarkdown(e="document.md"){this._download(this.getMarkdown(),e,"text/markdown")}_download(e,t,i){const s=new Blob([e],{type:i}),o=URL.createObjectURL(s),a=document.createElement("a");a.href=o,a.download=t,a.style.display="none",document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(o)}print(e=""){const t=this.getHTML(),i=(e||"").replace(/</g,"<").replace(/>/g,">"),s=window.open("","_blank");s&&(s.document.write(`<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>${i}</title><style>body{font-family:system-ui,-apple-system,"Segoe UI",Roboto,Arial,sans-serif;font-size:14px;line-height:1.6;padding:20mm;color:#111827;}ul.an-checklist{list-style:none;padding-left:0;}ul.an-checklist li{padding-left:24px;position:relative;margin:2px 0;}ul.an-checklist li input[type="checkbox"]{position:absolute;left:0;top:3px;}code{background:#f3f4f6;border-radius:3px;padding:.1em .35em;font-family:monospace;}pre{background:#f3f4f6;padding:.75em 1em;border-radius:4px;overflow-x:auto;}table{border-collapse:collapse;}td,th{border:1px solid #d1d5db;padding:4px 8px;}</style></head><body>${t}</body></html>`),s.document.close(),s.onload=()=>{s.print()})}setDisabled(e){const t=this.layoutInfo.editable;e?(t.setAttribute("contenteditable","false"),this.layoutInfo.container.classList.add("an-disabled")):(t.setAttribute("contenteditable","true"),this.layoutInfo.container.classList.remove("an-disabled"))}destroy(){if(!this._alive)return;this._modules.forEach(t=>{typeof t.destroy=="function"&&t.destroy()}),this._modules.clear(),this._disposers.forEach(t=>t()),this._disposers=[];const e=this.layoutInfo.container;e&&e.parentNode&&(this.targetEl.style.display="",e.parentNode.removeChild(e)),typeof this.options.onDestroy=="function"&&this.options.onDestroy(this),this._alive=!1,this._listeners.clear()}_syncToTarget(){(this.targetEl.tagName==="TEXTAREA"||this.targetEl.tagName==="INPUT")&&(this.targetEl.value=this.getHTML())}}const ji={...F},X=new WeakMap,zi={create(n,e={}){const i=qe(n).map(s=>{if(X.has(s))return X.get(s);const o=new Ni(s,e);return o.initialize(),X.set(s,o),o});return i.length===1?i[0]:i},destroy(n){qe(n).forEach(e=>{const t=X.get(e);t&&(t.destroy(),X.delete(e))})},getInstance(n){const e=typeof n=="string"?document.querySelector(n):n;return e&&X.get(e)||null},get defaults(){return{...F}},setDefaults(n){Object.assign(F,n)},resetDefaults(){Object.keys(F).forEach(n=>delete F[n]),Object.assign(F,ji)},registerModule(n,e){Ue.set(n,e)},version:"1.0.1"};function qe(n){return typeof n=="string"?Array.from(document.querySelectorAll(n)):n instanceof Element?[n]:n instanceof NodeList||Array.isArray(n)?Array.from(n):[]}return zi});
|
|
74
74
|
//# sourceMappingURL=autumnnote.umd.js.map
|