l&&" "!==n[l])&&new RegExp(`^\\s{${l},}`).test(n)){p.push(""),a++;continue}}break}if(i){if(new RegExp(`^(\\s{0,${r}})\\d+\\.\\s`).test(t))break}else if(new RegExp(`^(\\s{0,${r}})[-*+]\\s`).test(t))break;if(D.test(t)||I.test(t)||R.test(t)||V.test(t))break;const n=t.match(new RegExp(`^(\\s{${l},})([-*+])\\s`)),o=t.match(new RegExp(`^(\\s{${l},})(\\d+)\\.\\s`));if(n||o){const t=!!o,r=t?o[2]:n[2],i=t?o[1].length:n[1].length,s=t?parseInt(o[2],10):void 0,l=ie(e,a,r,i,t);m.push({type:t?"ol":"ul",items:l.items,start:s}),a=l.endIdx;continue}t.length>l&&""===t.slice(0,l).trim()?p.push(t.slice(l)):p.push(t),a++}p.length&&(d=d?d+"\n"+p.join("\n"):p.join("\n")),s.push({type:"listItem",text:d,checked:h,task:u,subTokens:m.length?m:void 0})}return{items:s,endIdx:a}},oe=e=>N.test(e)&&/-/.test(e),se=e=>e.replace(/^\s*\|?\s*|\s*\|?\s*$/g,"").split(/\s*\|\s*/).map(e=>/^:/.test(e)&&/:$/.test(e)?"center":/:$/.test(e)?"right":(/^:/.test(e),"left")),ae=(e,n,r)=>{switch(e.type){case"heading":{const t=X(e.text);return`${G(e.text,n)}`}case"paragraph":return`${G(e.text,n)}
`;case"hr":return"
";case"quote":return`${re(e.content,n)}
`;case"code":return ce(e.content,e.lang,n,e.attrs);case"ul":return`${e.items.map(e=>le(e,n)).join("")}
`;case"ol":{const t=e.start||1;return`1?` start="${t}"`:""}>${e.items.map((e,r)=>le(e,n,t>1?r+t:void 0)).join("")}
`}case"table":return de(e,n);case"defList":{let t="";return t+=`- ${G(e.term,n)}
`,e.defs.forEach(e=>{t+=`- ${G(e,n)}
`}),t+"
"}case"mathBlock":return`${t(e.content)}
`;default:return`${e.content?"string"==typeof e.content?G(e.content,n):t(String(e.content)):""}
`}},le=(e,t,n)=>{if(e.task){let n=` ${G(e.text,t)}`;return e.subTokens&&(n+="\n"+e.subTokens.map(e=>ae(e,t)).join("\n")),n+""}let r=null!=n?``:"";return r+=G(e.text,t),e.subTokens&&(r+="\n"+e.subTokens.map(e=>ae(e,t)).join("\n")),r+""},ce=(e,n,r,i)=>{if("mermaid"===n)return``;const o=n?` class="language-${t(n)}"`:"",s=i?.title?`${t(i.title)}
`:"";if(r.highlight&&"function"==typeof r.highlight&&n)try{const t=r.highlight(e,n);if("string"==typeof t)return`${s}${t}
`}catch(e){}return`${s}${t(e)}
`},de=(e,t)=>{const n=e=>{const t=[];let n="",r=!1;for(let i=0;i0&&""===t[0]&&t.shift(),t.length>0&&""===t[t.length-1]&&t.pop(),t},r=n(e.header),i=e.align||[],o=e=>i[e]&&"left"!==i[e]?` style="text-align:${i[e]}"`:"";let s='';return s+=r.map((e,n)=>`| ${G(e,t)} | `).join(""),s+="
",s+=e.rows.map(e=>`${n(e).map((e,n)=>`| ${G(e,t)} | `).join("")}
`).join(""),s+"
"},he=(e,n)=>{if(!e)return"";const r=[];let i=ue(e,r);const o=[];return i=i.replace(/&(?:[a-zA-Z][a-zA-Z0-9]{1,31}|#\d{1,7}|#x[0-9a-fA-F]{1,6});/g,e=>(o.push(e),`${o.length-1}`)),i=i.replace(//g,e=>(o.push(e),`${o.length-1}`)),i=t(i),i=i.replace(/\u0005(\d+)\u0005/g,(e,t)=>o[+t]||e),i=me(i,r,n),i=i.replace(/\u0000(\d+)\u0000/g,(e,n)=>{const i=r[+n];return i?`${t(i.content)}`:e}),i=i.replace(/:([\w+-]+):/g,(e,t)=>U[t]||e),i=i.replace(/ \n/g,"
\n"),i=i.replace(/\n/g,"
"),i},ue=(e,t)=>{let n="",r=0;for(;r{const i=new Map;return e=(e=e.replace(/\u0000\d+\u0000/g,e=>{const t=`${i.size}`;return i.set(t,e),t})).replace(pe,e=>{const n=e;if(n.startsWith("***"))return`${n.slice(3,-3)}`;if(n.startsWith("___"))return`${n.slice(3,-3)}`;if(n.startsWith("){const e=n.match(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+['"](.+?)['"])?\s*\)/);if(!e)return n;const r=Z(e[2]);if(!r)return t(n);const i=e[3]?` title="${e[3]}"`:"";return`
`}if(n.startsWith("![")&&n.includes("][")){const e=n.match(/!\[([^\]]*)\]\[([^\]]*)\]/);if(!e)return n;const i=(e[2]||e[1]).toLowerCase();if(r.refs&&r.refs[i])try{const o=JSON.parse(r.refs[i]),s=Z(o.url);if(!s)return t(n);const a=o.title?` title="${o.title}"`:"";return`
`}catch(t){return`
`}return`
`}if(n.startsWith("[")&&n.includes("](")){const e=n.match(/\[([^\]]+)\]\(([^)\s]+)(?:\s+['"](.+?)['"])?\s*\)/);if(!e)return n;const t=Z(e[2]);return t?`${he(e[1],r)}`:n}if(n.startsWith("[")&&n.includes("][")){const e=n.match(/\[([^\]]+)\]\[([^\]]*)\]/);if(!e)return n;const i=(e[2]||e[1]).toLowerCase();if(r.refs&&r.refs[i])try{const o=JSON.parse(r.refs[i]),s=Z(o.url);return s?`${e[1]}`:t(n)}catch(e){return t(n)}return t(n)}if(n.startsWith("<http")){const e=n.slice(4,-4);return`${e}`}if(n.startsWith("**"))return`${n.slice(2,-2)}`;if(n.startsWith("__"))return`${n.slice(2,-2)}`;if(n.startsWith("~~"))return`${n.slice(2,-2)}`;if(n.startsWith("=="))return`${n.slice(2,-2)}`;if(n.startsWith("*")&&!n.startsWith("**")&&!n.startsWith("***"))return`${n.slice(1,-1)}`;if(n.startsWith("_")&&!n.startsWith("__")&&!n.startsWith("___"))return`${n.slice(1,-1)}`;if(n.startsWith("^")&&!n.startsWith("^^"))return`${n.slice(1,-1)}`;if(n.startsWith("~")&&!n.startsWith("~~"))return`${n.slice(1,-1)}`;if(n.startsWith("$")&&!n.startsWith("$$"))return`${t(n.slice(1,-1))}`;if(/^\[\^/.test(n)){const e=n.slice(2,-1);return``}if(n.startsWith("\\")&&2===n.length){const e=n[1];return/[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]/.test(e)?e:n}return n}),e.replace(/\u0003(\d+)\u0003/g,e=>i.get(e)||e)};class ge{constructor(){this.plugins=new Map}register(e,t){return this.plugins.has(e)?this:t&&"object"==typeof t&&(t.name||e)?(this.plugins.set(e,{version:t.version||"0.0.0",description:t.description||"",depends:t.depends||[],priority:t.priority||0,...t,name:e,enabled:!0}),this):this}unregister(e){return this.plugins.delete(e),this}get(e){return this.plugins.get(e)||null}has(e){return this.plugins.has(e)}getAll(){return Array.from(this.plugins.values())}getNames(){return Array.from(this.plugins.keys())}enable(e){const t=this.plugins.get(e);return t&&(t.enabled=!0),this}disable(e){const t=this.plugins.get(e);return t&&(t.enabled=!1),this}isEnabled(e){const t=this.plugins.get(e);return!!t&&t.enabled}destroy(){this.plugins.clear()}}const fe=new ge,ve=e=>{const t=new Map;e.forEach(e=>t.set(e.name,e));const n=new Map,r=new Map;e.forEach(e=>{n.set(e.name,0),r.set(e.name,[])}),e.forEach(e=>{(e.depends||[]).forEach(i=>{t.has(i)&&(r.get(i).push(e.name),n.set(e.name,(n.get(e.name)||0)+1))})});const i=[];n.forEach((e,t)=>{0===e&&i.push(t)});const o=[];for(;i.length;){i.sort((e,n)=>(t.get(n).priority||0)-(t.get(e).priority||0));const e=i.shift();o.push(t.get(e)),(r.get(e)||[]).forEach(e=>{n.set(e,n.get(e)-1),0===n.get(e)&&i.push(e)})}return o.length!==e.length?e:o},be=(e={},t={})=>{const n=[],r={...t};for(const[i,o]of Object.entries(e)){const e=t[i];if(o.required&&null==e)n.push(`"${i}" is required`);else if(void 0!==e||void 0===o.default){if(void 0!==e&&o.type){const t=Array.isArray(e)?"array":typeof e;t!==o.type&&n.push(`"${i}" expected ${o.type}, got ${t}`)}if(void 0!==e&&o.enum&&!o.enum.includes(e)&&n.push(`"${i}" must be one of [${o.enum.join(", ")}]`),void 0!==e&&"function"==typeof o.validator)try{const t=o.validator(e);!0!==t&&n.push(`"${i}": ${t}`)}catch(e){n.push(`"${i}": ${e.message}`)}}else r[i]=o.default}return{valid:0===n.length,errors:n,patched:r}},ye={autoSave:{name:"autoSave",version:"0.1.1",description:"Auto-save to localStorage",priority:100,install(e,t){if(!e||"function"!=typeof e.getValue)return;const n=t||this,r=n.key||"me-draft-"+(e.id||""),i=n.delay||1e3,o={_timer:null},s=()=>{o._timer&&(clearTimeout(o._timer),o._timer=null);try{localStorage.setItem(r,e.getValue()),"function"==typeof e._emit&&e._emit("autosave",{key:r,value:e.getValue()})}catch(e){}},a=()=>{o._timer&&clearTimeout(o._timer),o._timer=setTimeout(s,i)},l=s,c=s;e.on("change",a),e.on("blur",l),e.on("save",c),e.restoreDraft=()=>{try{const t=localStorage.getItem(r);return null!=t&&e.setValue(t),t}catch(e){return null}},e.clearDraft=()=>{try{localStorage.removeItem(r)}catch(e){}return e},e.getDraftKey=()=>r,e.__autoSaveCleanup={state:o,_onInput:a,_onBlur:l,_onSave:c,save:s}},destroy(e){const t=e.__autoSaveCleanup;t&&(t.state._timer&&(clearTimeout(t.state._timer),t.state._timer=null),e&&"function"==typeof e.off&&(t._onInput&&e.off("change",t._onInput),t._onBlur&&e.off("blur",t._onBlur),t._onSave&&e.off("save",t._onSave)),delete e.__autoSaveCleanup)}},exportTool:{name:"exportTool",version:"0.1.0",description:"Export Markdown/HTML",priority:50,install(e){if(!e||"function"!=typeof e.getValue)return;const t=(e,t,n)=>{if("undefined"==typeof document)return;const r=new Blob([t],{type:n+";charset=utf-8"}),i=URL.createObjectURL(r),o=document.createElement("a");o.href=i,o.download=e,document.body.appendChild(o),o.click(),document.body.removeChild(o),setTimeout(()=>URL.revokeObjectURL(i),0)},n=()=>{const e=new Date,t=e=>String(e).padStart(2,"0");return`${e.getFullYear()}${t(e.getMonth()+1)}${t(e.getDate())}-${t(e.getHours())}${t(e.getMinutes())}`};e.exportMarkdown=r=>(t(r||`metona-${n()}.md`,e.getValue(),"text/markdown"),e),e.exportHTML=(r,i={})=>{const o=i.title||"Document",s=i.css||"",a="function"==typeof e.getHTML?e.getHTML():"",l=!1!==i.embedCSS?'':"";return t(r||`metona-${n()}.html`,`\n\n\n\n\n${o}\n${s?``:""}${l}\n\n\n${a}\n\n`,"text/html"),e}},destroy(){}},searchReplace:{name:"searchReplace",version:"0.2.0",description:"Search & Replace (Ctrl+F/H)",priority:80,install(e){if(!e||!e.textarea||"undefined"==typeof document)return;if(!document.getElementById("me-search-style")){const e=document.createElement("style");e.id="me-search-style",e.textContent=".me-search{position:absolute;top:8px;right:12px;z-index:20;display:flex;flex-direction:column;gap:6px;padding:8px;background:var(--md-toolbar-bg,#f8f9fa);border:1px solid var(--md-border,rgba(0,0,0,0.1));border-radius:8px;box-shadow:0 8px 24px -8px rgba(0,0,0,0.2);font-size:13px;min-width:280px}.me-search-row{display:flex;gap:4px;align-items:center}.me-search input{flex:1;min-width:0;padding:4px 8px;border:1px solid var(--md-border,rgba(0,0,0,0.15));border-radius:4px;background:var(--md-textarea-bg,#fff);color:var(--md-text,#1f2937);font-size:13px}.me-search input:focus{outline:none;border-color:var(--md-accent,#3b82f6)}.me-search button{padding:4px 8px;border:1px solid var(--md-border,rgba(0,0,0,0.15));background:var(--md-bg,#fff);color:var(--md-text,#1f2937);border-radius:4px;cursor:pointer;font-size:12px;line-height:1}.me-search button:hover{background:var(--md-accent,#3b82f6);color:#fff;border-color:var(--md-accent,#3b82f6)}.me-search .me-search-count{color:var(--md-muted,#6b7280);font-size:12px;min-width:60px;text-align:center}.me-search .me-search-close{padding:2px 6px}",document.head.appendChild(e)}const t={_panel:null,_regexMode:!1,_cleanup:null},n=()=>{if(!t._panel)return;const e="1"===t._panel.dataset.replace,n=t._panel.querySelector(".me-search-replace-row");n&&(n.style.display=e?"flex":"none")},r=()=>{t._cleanup&&(t._cleanup(),t._cleanup=null),t._panel=null,e&&e.textarea&&e.textarea.focus()},i=i=>{if(t._panel){t._panel.dataset.replace=i?"1":"0",n();const e=t._panel.querySelector(".me-search-find");return void(e&&(e.focus(),e.select()))}const o=e.textarea.value.substring(e.textarea.selectionStart,e.textarea.selectionEnd),s=document.createElement("div");var a;s.className="me-search",s.dataset.replace=i?"1":"0",s.innerHTML=`/g,">")}"/>
`,e.el.appendChild(s),t._panel=s,n(),t._regexMode=!1;const l=s.querySelector(".me-search-find"),c=s.querySelector(".me-search-replace"),d=s.querySelector(".me-search-count"),h=s.querySelector(".me-search-regex");h.addEventListener("click",()=>{t._regexMode=!t._regexMode,h.classList.toggle("me-active",t._regexMode),p=u()});const u=()=>{const n=l.value;if(!n)return d.textContent="",[];const r=[];let i=0;if(t._regexMode)try{const t=new RegExp(n,"g");let i;for(;null!==(i=t.exec(e.textarea.value));)r.push(i.index),0===i[0].length&&t.lastIndex++}catch(e){return d.textContent="err",[]}else for(;;){const t=e.textarea.value.indexOf(n,i);if(-1===t)break;r.push(t),i=t+n.length}return d.textContent=r.length?`${r.length}`:"0",r};let p=[];const m=(t,n)=>{e.textarea.focus(),e.textarea.setSelectionRange(t,t+(n||l.value.length))},g=()=>{if(p=u(),!p.length)return;const n=e.textarea.selectionEnd,r=t._regexMode?(()=>{try{const t=new RegExp(l.value).exec(e.textarea.value.substring(n));return t?t[0].length:l.value.length}catch(e){return l.value.length}})():l.value.length;let i=p.find(e=>e>=n);null==i&&(i=p[0]),m(i,r)},f=()=>{if(p=u(),!p.length)return;const n=e.textarea.selectionStart,r=t._regexMode?(()=>{try{const t=new RegExp(l.value).exec(e.textarea.value.substring(Math.max(0,n-100),n+100));return t?t[0].length:l.value.length}catch(e){return l.value.length}})():l.value.length;let i=-1;for(let e=p.length-1;e>=0;e--)if(p[e]{const n=l.value,r=c.value;if(!n)return;const i=e.textarea,o=i.selectionStart,s=i.selectionEnd,a=i.value.substring(o,s);if(t._regexMode)try{new RegExp(n).test(a)&&(i.value=i.value.substring(0,o)+r+i.value.substring(s),i.setSelectionRange(o,o+r.length))}catch(e){}else a===n&&(i.value=i.value.substring(0,o)+r+i.value.substring(s),i.setSelectionRange(o,o+r.length));e._value=i.value,"function"==typeof e._pushHistory&&e._pushHistory(),"function"==typeof e._render&&e._render(),"function"==typeof e._emit&&e._emit("change",e._value),g()};l.addEventListener("input",()=>{p=u()}),l.addEventListener("keydown",e=>{"Enter"===e.key&&(e.preventDefault(),e.shiftKey?f():g()),"Escape"===e.key&&(e.preventDefault(),r())}),c.addEventListener("keydown",e=>{"Enter"===e.key&&(e.preventDefault(),v()),"Escape"===e.key&&(e.preventDefault(),r())}),s.querySelector(".me-search-next").addEventListener("click",g),s.querySelector(".me-search-prev").addEventListener("click",f),s.querySelector(".me-search-close").addEventListener("click",()=>r()),s.querySelector(".me-search-replace-one").addEventListener("click",v),s.querySelector(".me-search-replace-all").addEventListener("click",()=>{const n=l.value,r=c.value;if(!n)return;const i=e.textarea;if(t._regexMode)try{i.value=i.value.replace(new RegExp(n,"g"),r)}catch(e){return}else i.value=i.value.split(n).join(r);i.setSelectionRange(0,0),e._value=i.value,"function"==typeof e._pushHistory&&e._pushHistory(),"function"==typeof e._render&&e._render(),"function"==typeof e._emit&&e._emit("change",e._value),u()}),l.focus(),l.select(),t._cleanup=()=>{s.parentNode&&s.parentNode.removeChild(s)}},o=e=>{if(!e.ctrlKey&&!e.metaKey)return;const n=e.key.toLowerCase();"f"===n?(e.preventDefault(),i(!1)):"h"===n?(e.preventDefault(),i(!0)):"escape"===n&&t._panel&&r()};e.textarea.addEventListener("keydown",o),e.__srState=t,e.__srOpen=i,e.__srClose=r,e.__srKeydown=o},destroy(e){const t=e.__srState;t&&(t._cleanup&&(t._cleanup(),t._cleanup=null),t._panel=null);const n=e.__srKeydown;n&&e&&e.textarea&&e.textarea.removeEventListener("keydown",n),delete e.__srState,delete e.__srOpen,delete e.__srClose,delete e.__srKeydown}},imagePaste:{name:"imagePaste",version:"0.2.0",description:"Paste image as base64",priority:60,install(e){if(!e||!e.textarea||"undefined"==typeof document)return;const t=t=>{const n=t.clipboardData?.items;if(n)for(const r of n)if(r.type?.startsWith("image/")){t.preventDefault();const n=new FileReader;n.onload=()=>{e.insert(`\n`)},n.readAsDataURL(r.getAsFile());break}};e.textarea.addEventListener("paste",t),e.__ipOnPaste=t},destroy(e){const t=e.__ipOnPaste;t&&e?.textarea&&e.textarea.removeEventListener("paste",t),delete e.__ipOnPaste}},shortcutHelp:{name:"shortcutHelp",version:"0.2.0",description:"Press ? to show shortcuts",priority:200,install(e){if(!e||!e.textarea||"undefined"==typeof document)return;if(!document.getElementById("me-shortcut-style")){const e=document.createElement("style");e.id="me-shortcut-style",e.textContent=".me-shortcut-overlay{position:fixed;top:0;left:0;right:0;bottom:0;z-index:50;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center}.me-shortcut-panel{background:var(--md-bg,#fff);border-radius:12px;padding:24px;max-width:560px;width:90%;max-height:80vh;overflow-y:auto;box-shadow:0 12px 40px rgba(0,0,0,0.3)}.me-shortcut-panel h3{font-size:16px;margin:0 0 16px;color:var(--md-text)}.me-shortcut-panel table{width:100%;border-collapse:collapse;font-size:13px}.me-shortcut-panel td{padding:6px 10px;border-bottom:1px solid var(--md-border)}.me-shortcut-panel td:first-child{font-family:var(--md-mono);font-size:12px;color:var(--md-accent);white-space:nowrap;width:40%}.me-shortcut-panel .me-shortcut-close{position:absolute;top:16px;right:20px;background:none;border:none;font-size:20px;cursor:pointer;color:var(--md-muted)}",document.head.appendChild(e)}let t=null;const n=()=>{t&&(t.remove(),t=null)},r=()=>{if(t)return void n();const e=[["Ctrl+B",b("bold")||"Bold"],["Ctrl+I",b("italic")||"Italic"],["Ctrl+U",b("underline")||"Underline"],["Ctrl+K",b("link")||"Link"],["Ctrl+E",b("code")||"Code"],["Ctrl+1/2/3",b("h1")||"Heading"],["Ctrl+Q",b("quote")||"Quote"],["Ctrl+Z",b("undo")||"Undo"],["Ctrl+Y",b("redo")||"Redo"],["Ctrl+S",b("save")||"Save"],["Ctrl+F",b("search")||"Search"],["Ctrl+H",b("replace")||"Replace"],["Tab",b("indent")||"Indent"],["Shift+Tab",b("outdent")||"Outdent"],["?",b("close")||"Shortcuts"]];let r="";e.forEach(([e,t])=>{r+=`| ${e} | ${t} |
`});const i=document.createElement("div");i.className="me-shortcut-overlay",i.innerHTML=`⌨️ ${b("close")||"Shortcuts"}
`,i.addEventListener("click",e=>{(e.target===i||e.target.classList.contains("me-shortcut-close"))&&n()}),document.body.appendChild(i),t=i},i=e=>{"?"!==e.key||e.ctrlKey||e.metaKey||e.altKey||(e.preventDefault(),r()),"Escape"===e.key&&t&&n()};e.textarea.addEventListener("keydown",i),e.__shState={_panel:t,_open:r,_close:n,_onKeydown:i}},destroy(e){const t=e.__shState;t&&t._panel&&t._panel.remove();const n=e.__shState?._onKeydown;n&&e?.textarea&&e.textarea.removeEventListener("keydown",n),delete e.__shState}},fileSystem:{name:"fileSystem",version:"0.2.0",description:"File System Access API",priority:90,install(e){if(!e||"function"!=typeof e.getValue)return;const t="undefined"!=typeof window&&"function"==typeof window.showOpenFilePicker;let n=null;e.openFile=async(r={})=>{if(!t)return e.toast?.("File System Access API not supported",{type:"warning"}),null;try{const[t]=await window.showOpenFilePicker({types:[{accept:{"text/markdown":[".md",".txt",".markdown"]}}],...r});n=t;const i=await t.getFile(),o=await i.text();return e.setValue(o),e._emit?.("fileOpened",{name:i.name,handle:t}),{name:i.name,content:o,handle:t}}catch(e){return e.name,null}},e.saveFile=async(r={})=>{let i=n;if(!i||r.saveAs){if(!t)return e.toast?.("File System Access API not supported",{type:"warning"}),!1;try{i=await window.showSaveFilePicker({types:[{accept:{"text/markdown":[".md"]}}],suggestedName:r.name||"document.md"}),n=i}catch(e){return e.name,!1}}try{const t=await i.createWritable();return await t.write(e.getValue()),await t.close(),e._emit?.("fileSaved",{handle:i}),!0}catch(t){return n=null,!r.saveAs&&e.saveFile({...r,saveAs:!0})}},e.saveFileAs=t=>e.saveFile({saveAs:!0,name:t}),e.getFileHandle=()=>n,e.__fsCleanup={getHandle:()=>n}},destroy(e){e&&(delete e.openFile,delete e.saveFile,delete e.saveFileAs,delete e.getFileHandle),delete e.__fsCleanup}}},xe={createManager:()=>new ge,manager:fe,register:(e,t)=>fe.register(e,t),unregister:e=>fe.unregister(e),get:e=>fe.get(e),has:e=>fe.has(e),getAll:()=>fe.getAll(),getNames:()=>fe.getNames(),enable:e=>fe.enable(e),disable:e=>fe.disable(e),isEnabled:e=>fe.isEnabled(e),getPreset:e=>ye[e]?{...ye[e]}:null,getAllPresets:()=>Object.keys(ye).reduce((e,t)=>(e[t]={...ye[t]},e),{}),createPlugin:(e={})=>{const t={name:e.name||"custom",version:e.version||"0.0.0",description:e.description||"",depends:e.depends||[],priority:e.priority||0,install:()=>{},destroy:()=>{},...e};return"function"!=typeof t.install&&(t.install=()=>{}),"function"!=typeof t.destroy&&(t.destroy=()=>{}),t},validatePlugin:e=>{const t=[];return e&&"object"==typeof e||t.push("plugin must be an object"),e&&!e.name&&t.push("plugin must have a name"),e&&e.install&&"function"!=typeof e.install&&t.push("install must be a function"),{valid:0===t.length,errors:t}},topologicalSort:ve,validateConfig:be};let _e="auto",we=new Set,ke=null;const Ee=()=>"undefined"==typeof window?"light":"undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",Ce=()=>{"undefined"!=typeof window&&window.matchMedia&&(ke&&(ke(),ke=null),ke=(()=>{if("undefined"==typeof window||!window.matchMedia)return()=>{};const e=window.matchMedia("(prefers-color-scheme: dark)"),t=e=>(e.matches,void("auto"===_e&&Ae("auto")));return e.addEventListener("change",t),()=>e.removeEventListener("change",t)})())},Te=e=>e&&"auto"!==e?e:Ee(),Se=e=>{const t=Te(e),n=s[t];return n&&"object"==typeof n?n:s.light},Le=(e,t)=>{if("undefined"==typeof document||!e||"object"!=typeof e)return;const n=t||document.documentElement,r={"--md-bg":e.bg,"--md-text":e.text,"--md-border":e.border,"--md-shadow":e.shadow,"--md-hover-shadow":e.hoverShadow,"--md-toolbar-bg":e.toolbarBg||e.bg,"--md-textarea-bg":e.textareaBg||e.bg,"--md-preview-bg":e.previewBg||e.bg,"--md-code-bg":e.codeBg||"rgba(127,127,127,0.1)","--md-code-text":e.codeText||e.text,"--md-accent":e.accent||"#3b82f6","--md-muted":e.muted||"#9ca3af"};for(const[e,t]of Object.entries(r))null!=t&&n.style.setProperty(e,String(t));e.progressBg&&n.style.setProperty("--md-progress-bg",e.progressBg),e.closeHoverBg&&n.style.setProperty("--md-close-hover-bg",e.closeHoverBg)},Me=e=>{const t=e||document.documentElement;if("undefined"==typeof document)return{};const n=getComputedStyle(t),r={};return["--md-bg","--md-text","--md-border","--md-shadow","--md-hover-shadow","--md-toolbar-bg","--md-textarea-bg","--md-preview-bg","--md-code-bg","--md-code-text","--md-accent","--md-muted"].forEach(e=>{const t=n.getPropertyValue(e).trim();t&&(r[e]=t)}),r},$e=(e,t)=>{const n=t||document.documentElement;if("undefined"==typeof document)return"";const r=e.startsWith("--")?e:`--md-${e}`;return getComputedStyle(n).getPropertyValue(r).trim()},Ae=e=>{_e=e;const t=Te(e);"undefined"!=typeof document&&(document.documentElement.setAttribute("data-md-theme",t),document.documentElement.classList.remove("md-theme-light","md-theme-dark","md-theme-auto","md-theme-warm"),document.documentElement.classList.add(`md-theme-${t}`),Le(Se(e))),Pe(e,t)},ze=e=>{Ae(e),He(e)},Ie=()=>Te(_e),He=e=>{if("undefined"!=typeof localStorage)try{localStorage.setItem("metona-editor-theme",e)}catch(e){}},Be=()=>{if("undefined"!=typeof localStorage)try{return localStorage.getItem("metona-editor-theme")||"auto"}catch(e){}return"auto"},Pe=(e,t)=>{we.forEach(n=>{try{n(e,t)}catch(e){}})},Re=(e,t)=>{if("undefined"==typeof document||"undefined"==typeof MutationObserver)return()=>{};const{element:n=document.documentElement,attr:r="data-theme",classMap:i=null,callback:o=null}=e,s=()=>{if("function"==typeof o)return o(n);const e=n.getAttribute(r);if(e)return e;if(i)for(const[e,t]of Object.entries(i))if(n.classList.contains(e))return t;return n.getAttribute("data-md-theme")||null};let a=s();a&&t(a);const l=new MutationObserver(()=>{const e=s();e&&e!==a&&(a=e,t(e))});return l.observe(n,{attributes:!0,attributeFilter:[r,"class","data-md-theme"]}),()=>l.disconnect()},De=(e,t)=>{if("undefined"==typeof document||!e)return()=>{};const n=()=>{let t=e.parentElement;for(;t;){const e=t.getAttribute("data-md-theme");if(e)return e;if(t.classList.contains("theme-dark")||t.classList.contains("dark"))return"dark";if(t.classList.contains("theme-light")||t.classList.contains("light"))return"light";t=t.parentElement}if(e.parentElement){const t=getComputedStyle(e.parentElement).getPropertyValue("--md-bg").trim()||getComputedStyle(e.parentElement).backgroundColor;if(t){const e=t.match(/\d+/g);if(e&&e.length>=3)return(299*parseInt(e[0])+587*parseInt(e[1])+114*parseInt(e[2]))/1e3<128?"dark":"light"}}return null},r=n();r&&t(r);const i=new MutationObserver(()=>{const e=n();e&&t(e)});let o=e.parentElement;for(;o&&(i.observe(o,{attributes:!0,attributeFilter:["class","data-md-theme","data-theme"]}),o=o.parentElement,o!==document.documentElement););return()=>i.disconnect()},Fe=(e,t)=>{if("function"==typeof e){const n=()=>{try{const n=e();n&&t(n)}catch(e){}};n();const r=setInterval(n,500);return()=>clearInterval(r)}if("string"==typeof e&&"undefined"!=typeof document){const n=document.querySelector(e);return n?Re({element:n,attr:"data-theme"},t):()=>{}}return()=>{}},je=e=>{let t=e.config?.theme||_e||"auto";const n=n=>{t=n;const r=Te(n),i=Se(n);return e.el&&(["me-theme-light","me-theme-dark","me-theme-warm"].forEach(t=>e.el.classList.remove(t)),"auto"!==r&&e.el.classList.add(`me-theme-${r}`),e.el.setAttribute("data-md-theme",r),Le(i,e.el)),"function"==typeof e._emit&&e._emit("themeChange",{theme:n,resolved:r,config:i}),"function"==typeof e.refresh&&e.refresh(),t};return n(t),{apply:n,get:()=>t,set:e=>n(e),toggle:()=>{const e=Te(t);return n("dark"===e?"light":"dark")},getResolved:()=>Te(t),getConfig:()=>Se(t),getVars:()=>e.el?Me(e.el):{},syncWithElement:(e,t={})=>Re({element:e,attr:t.attr||"data-theme",classMap:t.classMap,callback:t.callback},e=>n(e)),adopt:()=>e.container?De(e.container,e=>n(e)):()=>{},watch:e=>Fe(e,e=>n(e))}},Oe={light:{name:"浅色",description:"明亮清晰",config:s.light},dark:{name:"深色",description:"护眼暗色",config:s.dark},auto:{name:"自动",description:"跟随系统",config:"auto"},warm:{name:"暖色",description:"温馨暖色",config:s.warm}};for(const[e,t]of Object.entries(Oe))"auto"!==e&&"auto"!==t.config&&(s[e]=t.config);const Ne={getSystemTheme:Ee,resolveTheme:Te,getThemeConfig:Se,watchSystemTheme:Ce,unwatchSystemTheme:()=>{ke&&(ke(),ke=null)},applyTheme:Ae,getCurrentTheme:()=>_e,getResolvedTheme:Ie,switchTheme:ze,toggleTheme:()=>{const e=Ie();ze("dark"===e?"light":"dark")},resetToAuto:()=>{ze("auto")},initTheme:()=>{Ae(Be()),Ce()},saveTheme:He,loadTheme:Be,addThemeListener:e=>(we.add(e),()=>{we.delete(e)}),removeThemeListener:e=>{we.delete(e)},clearThemeListeners:()=>{we.clear()},registerTheme:(e,t={})=>{const n=t.extends||"light",r=s[n]||s.light;s[e]={bg:t.bg||r.bg,text:t.text||r.text,border:t.border||r.border,shadow:t.shadow||r.shadow,hoverShadow:t.hoverShadow||r.hoverShadow,toolbarBg:t.toolbarBg||r.toolbarBg||r.bg,textareaBg:t.textareaBg||r.textareaBg||r.bg,previewBg:t.previewBg||r.previewBg||r.bg,codeBg:t.codeBg||r.codeBg,codeText:t.codeText||r.codeText,accent:t.accent||r.accent,muted:t.muted||r.muted,progressBg:t.progressBg||r.progressBg,closeHoverBg:t.closeHoverBg||r.closeHoverBg}},unregisterTheme:e=>{"light"!==e&&"dark"!==e&&"auto"!==e&&"warm"!==e&&delete s[e]},getAllThemes:()=>({...s}),getThemeNames:()=>Object.keys(s),hasTheme:e=>e in s,setThemeVariables:Le,exportCSSVars:Me,getCSSVariable:$e,applyThemeToElement:(e,t)=>{if(!t||"undefined"==typeof document)return;const n=Te(e);t.setAttribute("data-md-theme",n),t.classList.remove("md-theme-light","md-theme-dark","md-theme-auto","md-theme-warm"),"auto"!==n&&t.classList.add(`md-theme-${n}`),Le(Se(e),t)},followExternalTheme:Re,adoptFromParent:De,watch:Fe,createInstanceTheme:je},We=["edit","split","preview"],qe={success:"✓",error:"✗",warning:"⚠",info:"ℹ"},Ve={"(":")","[":"]","{":"}",'"':'"',"'":"'","`":"`","*":"*",_:"_"};class Ue{static on(e,t){return this._hooks.has(e)||this._hooks.set(e,[]),this._hooks.get(e).push(t),()=>this.off(e,t)}static off(e,t){const n=this._hooks.get(e);n&&this._hooks.set(e,n.filter(e=>e!==t))}static trigger(e,t){const n=this._hooks.get(e);n&&n.forEach(e=>{try{e(t)}catch(e){}})}constructor(e,t={}){if("undefined"==typeof window||"undefined"==typeof document)return this._destroyed=!0,this._value=t.value||"",this;if(this.id=t.id||"me-"+Date.now().toString(36)+"-"+Math.random().toString(36).slice(2,8),this.container="string"==typeof e?document.querySelector(e):e,!this.container)return this._destroyed=!0,this;this.config={...o,...t},t.style&&"object"==typeof t.style&&(this.config.style={...o.style,...t.style}),this._value=this.config.value||"",this._mode=We.includes(this.config.mode)?this.config.mode:"split",this._history=[],this._historyIndex=-1,this._cleanups=[],this._plugins=[],this._listeners={},this._renderRaf=null,this._historyTimer=null,this._fullscreen=!1,this._destroyed=!1,this._lastRenderedValue=null,this._shortcuts=[],this._contextMenuItems=[],this._customActions={},this._outlineTimer=null,this._zenMode=!1,this._wordWrap=!0,this._syncing=!1,this._zenMouseHandler=null,this._floatingToolbar=null,this._selectionTimer=null,this._floatingEnabled=!1!==this.config.floatingToolbar,this._renderFn="function"==typeof this.config.render?this.config.render:re,this._highlightFn="function"==typeof this.config.highlight?this.config.highlight:null,Ue.trigger("beforeCreate",this),"undefined"!=typeof document&&(d&&document.getElementById("metona-editor-styles")||(d=document.createElement("style"),d.id="metona-editor-styles",d.textContent=':root{--md-bg:#ffffff;--md-text:#1f2937;--md-border:rgba(0,0,0,0.08);--md-shadow:0 10px 36px -10px rgba(0,0,0,0.18),0 4px 14px -4px rgba(0,0,0,0.08);--md-hover-shadow:0 14px 48px -10px rgba(0,0,0,0.22),0 6px 18px -4px rgba(0,0,0,0.10);--md-toolbar-bg:rgba(248,249,250,0.92);--md-textarea-bg:#ffffff;--md-preview-bg:#ffffff;--md-code-bg:rgba(243,244,246,1);--md-code-text:#1f2937;--md-accent:#3b82f6;--md-muted:#6b7280;--md-radius:10px;--md-font:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei","Hiragino Sans GB",sans-serif;--md-mono:"SF Mono","Cascadia Code","Consolas","Liberation Mono","Courier New",monospace}\n.me-wrapper{display:flex;flex-direction:column;box-sizing:border-box;border:1px solid var(--md-border);border-radius:var(--md-radius);overflow:hidden;background:var(--md-bg);color:var(--md-text);box-shadow:var(--md-shadow);font-family:var(--md-font);font-size:14px;line-height:1.6;position:relative;transition:box-shadow .25s,border-color .25s;width:100%}\n.me-wrapper:hover{box-shadow:var(--md-hover-shadow)}\n.me-wrapper.me-disabled{opacity:.6;pointer-events:none}\n.me-wrapper *{box-sizing:border-box}\n.me-wrapper.me-fullscreen{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;z-index:9999;border-radius:0;border:0}\n.me-toolbar{display:flex;align-items:center;flex-wrap:wrap;gap:2px;padding:6px 8px;background:var(--md-toolbar-bg);border-bottom:1px solid var(--md-border);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);min-height:40px}\n.me-btn{display:inline-flex;align-items:center;justify-content:center;width:30px;height:30px;padding:0;border:0;border-radius:6px;background:transparent;color:var(--md-text);cursor:pointer;transition:background .15s,color .15s,transform .1s;flex-shrink:0}\n.me-btn:hover{background:var(--md-code-bg);color:var(--md-accent)}\n.me-btn:active{transform:scale(.92)}\n.me-btn.me-active{background:var(--md-accent);color:#fff}\n.me-btn:disabled{opacity:.35;cursor:not-allowed;pointer-events:none}\n.me-btn:focus-visible{outline:2px solid var(--md-accent);outline-offset:2px}\n.me-btn:focus:not(:focus-visible){outline:none}\n.me-btn svg{width:17px;height:17px;display:block}\n.me-btn span{font-size:12px;font-weight:500}\n.me-toolbar-sep{display:inline-block;width:1px;height:20px;background:var(--md-border);margin:0 4px;flex-shrink:0}\n.me-toolbar-group{display:inline-flex;gap:2px;margin-left:auto;padding-left:6px;border-left:1px solid var(--md-border)}\n.me-toolbar-group .me-btn{width:auto;padding:0 8px}\n.me-body{display:flex;flex:1;min-height:0;position:relative}\n.me-editor-pane,.me-preview-pane{flex:1 1 50%;min-width:0;overflow:hidden;position:relative}\n.me-editor-inner{display:flex;height:100%;overflow:hidden;position:relative}\n.me-gutter{flex:0 0 auto;min-width:36px;padding:16px 8px 16px 6px;overflow:hidden;background:var(--md-code-bg);border-right:1px solid var(--md-border);color:var(--md-muted);font-family:var(--md-mono);font-size:13.5px;line-height:1.7;text-align:right;user-select:none;white-space:pre}\n.me-gutter-line{padding-right:4px}\n.me-gutter-active{color:var(--md-accent);font-weight:600;background:rgba(59,130,246,.08);border-radius:3px}\n.me-divider{flex:0 0 1px;background:var(--md-border);cursor:col-resize;position:relative}\n.me-divider::after{content:\'\';position:absolute;top:0;bottom:0;left:-3px;right:-3px}\n.me-divider:hover{background:var(--md-accent)}\n.me-textarea{width:100%;height:100%;padding:16px 18px;border:0;outline:0;resize:none;background:var(--md-textarea-bg);color:var(--md-text);font-family:var(--md-mono);font-size:13.5px;line-height:1.7;display:block;white-space:pre-wrap;word-wrap:break-word;position:relative;z-index:1}\n.me-textarea::placeholder{color:var(--md-muted);opacity:.7}\n.me-textarea:focus{outline:0}\n.me-preview-pane{overflow:auto;background:var(--md-preview-bg)}\n.me-preview{padding:18px 22px;max-width:100%;word-wrap:break-word;overflow-wrap:break-word}\n.me-body.me-mode-edit .me-preview-pane,.me-body.me-mode-edit .me-divider{display:none}\n.me-body.me-mode-edit .me-editor-pane{flex:1 1 100%}\n.me-body.me-mode-preview .me-editor-pane,.me-body.me-mode-preview .me-divider{display:none}\n.me-body.me-mode-preview .me-preview-pane{flex:1 1 100%}\n.me-preview>:first-child{margin-top:0}\n.me-preview>:last-child{margin-bottom:0}\n.me-preview h1,.me-preview h2,.me-preview h3,.me-preview h4,.me-preview h5,.me-preview h6{margin:1.4em 0 .6em;font-weight:650;line-height:1.3}\n.me-preview h1{font-size:1.9em;padding-bottom:.3em;border-bottom:1px solid var(--md-border)}\n.me-preview h2{font-size:1.55em;padding-bottom:.3em;border-bottom:1px solid var(--md-border)}\n.me-preview h3{font-size:1.3em}\n.me-preview h4{font-size:1.12em}\n.me-preview h5{font-size:1em}\n.me-preview h6{font-size:.9em;color:var(--md-muted)}\n.me-preview p{margin:.7em 0}\n.me-preview a{color:var(--md-accent);text-decoration:none}\n.me-preview a:hover{text-decoration:underline}\n.me-preview strong{font-weight:650}\n.me-preview em{font-style:italic}\n.me-preview del{text-decoration:line-through;opacity:.75}\n.me-preview ul,.me-preview ol{margin:.6em 0;padding-left:1.6em}\n.me-preview li{margin:.25em 0}\n.me-preview li.me-task-item{list-style:none;margin-left:-1.4em}\n.me-preview li.me-task-item input{margin-right:.5em;vertical-align:middle}\n.me-preview blockquote{margin:.8em 0;padding:.4em 1em;border-left:3px solid var(--md-accent);background:var(--md-code-bg);border-radius:0 6px 6px 0;color:var(--md-text)}\n.me-preview blockquote>:first-child{margin-top:0}\n.me-preview blockquote>:last-child{margin-bottom:0}\n.me-preview hr{border:0;height:1px;background:var(--md-border);margin:1.6em 0}\n.me-preview code{font-family:var(--md-mono);font-size:.88em;padding:.15em .4em;background:var(--md-code-bg);color:var(--md-code-text);border-radius:4px}\n.me-preview pre{margin:.9em 0;padding:14px 16px;background:var(--md-code-bg);border-radius:8px;overflow-x:auto;border:1px solid var(--md-border)}\n.me-code-title{font-family:var(--md-mono);font-size:.85em;padding:8px 14px;background:var(--md-border);border-radius:8px 8px 0 0;color:var(--md-text);margin:.9em 0 -0.9em;font-weight:600}\n.me-code-title+pre{margin-top:0;border-radius:0 0 8px 8px;border-top:none}\n.me-preview pre code{padding:0;background:transparent;color:var(--md-code-text);font-size:.9em;line-height:1.6;border-radius:0}\n.me-preview img{max-width:100%;height:auto;border-radius:6px;vertical-align:middle}\n.me-table-wrap{overflow-x:auto;margin:.9em 0}\n.me-preview table{border-collapse:collapse;width:100%;font-size:.93em;display:block}\n.me-preview th,.me-preview td{border:1px solid var(--md-border);padding:7px 12px;text-align:left}\n.me-preview th{background:var(--md-code-bg);font-weight:600}\n.me-preview tr:nth-child(even) td{background:var(--md-code-bg)}\n.me-statusbar{display:flex;align-items:center;justify-content:flex-end;gap:14px;padding:4px 12px;border-top:1px solid var(--md-border);background:var(--md-toolbar-bg);color:var(--md-muted);font-size:12px;min-height:26px}\n.me-statusbar:empty{display:none}\n.me-wrapper:focus-within{border-color:var(--md-accent)}\n.me-textarea:focus-visible{outline:0}\n@media(prefers-reduced-motion:reduce){.me-wrapper,.me-btn,.me-textarea{transition:none!important}}\n.me-wrapper.me-fullscreen .me-preview,.me-wrapper.me-fullscreen .me-textarea{font-size:15px}\n.me-wrapper.me-readonly .me-textarea{background:var(--md-code-bg);cursor:default;opacity:.88}\n.me-wrapper.me-readonly .me-toolbar{opacity:.75}\n.me-wrapper.me-readonly .me-btn:disabled{opacity:.3;cursor:not-allowed;pointer-events:none}\n.me-preview mark{background:rgba(250,204,21,.3);color:inherit;padding:.1em .2em;border-radius:3px}\n.me-preview sup{font-size:.75em;vertical-align:super;line-height:1}\n.me-preview sub{font-size:.75em;vertical-align:sub;line-height:1}\n.me-preview .me-math-block{display:block;margin:1.2em 0;padding:12px 16px;background:var(--md-code-bg);border-radius:8px;overflow-x:auto;font-family:var(--md-mono);font-size:.95em;text-align:center}\n.me-preview .me-math-inline{font-family:var(--md-mono);font-size:.95em;padding:.05em .2em}\n.me-preview dl{margin:.8em 0}\n.me-preview dt{font-weight:650;margin:.6em 0 .2em}\n.me-preview dd{margin:0 0 .3em 1.6em;color:var(--md-text)}\n.me-preview .me-footnote-ref a{font-size:.75em;vertical-align:super;text-decoration:none;color:var(--md-accent)}\n.me-preview .me-footnotes{margin-top:2em;border-top:1px solid var(--md-border);padding-top:.8em;font-size:.9em;color:var(--md-muted)}\n.me-preview .me-footnotes hr{display:none}\n.me-preview .me-footnotes ol{padding-left:1.2em}\n.me-preview .me-footnote-item{margin:.3em 0}\n.me-preview .me-footnote-backref{text-decoration:none;color:var(--md-accent);margin-right:.4em}\n.me-toast{position:absolute;bottom:16px;right:16px;z-index:30;display:flex;align-items:center;gap:8px;padding:10px 16px;border-radius:8px;font-size:13px;pointer-events:auto;cursor:pointer;opacity:0;transform:translateY(12px);transition:opacity .3s,transform .3s;box-shadow:0 6px 20px rgba(0,0,0,.15);max-width:360px}\n.me-toast.me-toast-enter{opacity:1;transform:translateY(0)}\n.me-toast.me-toast-leave{opacity:0;transform:translateY(12px)}\n.me-toast-success{background:#10b981;color:#fff}\n.me-toast-error{background:#ef4444;color:#fff}\n.me-toast-warning{background:#f59e0b;color:#fff}\n.me-toast-info{background:var(--md-accent,#3b82f6);color:#fff}\n.me-toast-icon{font-weight:700;font-size:16px;flex-shrink:0}\n.me-toast-msg{line-height:1.4}\n.me-context-menu{position:fixed;z-index:40;min-width:180px;padding:4px 0;background:var(--md-bg);border:1px solid var(--md-border);border-radius:8px;box-shadow:0 8px 28px rgba(0,0,0,.18);font-size:13px}\n.me-context-menu-item{display:flex;align-items:center;justify-content:space-between;padding:6px 14px;cursor:pointer;color:var(--md-text);transition:background .1s}\n.me-context-menu-item:hover{background:var(--md-code-bg);color:var(--md-accent)}\n.me-context-menu-sep{height:1px;background:var(--md-border);margin:4px 0}\n.me-context-menu-shortcut{color:var(--md-muted);font-size:11px;margin-left:24px}\n.me-context-menu-item.me-disabled{opacity:.4;cursor:not-allowed;pointer-events:none}\n.me-outline{position:absolute;top:0;right:0;width:220px;height:100%;overflow-y:auto;background:var(--md-preview-bg);border-left:1px solid var(--md-border);padding:12px 14px;font-size:13px;z-index:15}\n.me-outline-title{font-weight:650;margin-bottom:8px;padding-bottom:6px;border-bottom:1px solid var(--md-border);color:var(--md-text)}\n.me-outline ul{list-style:none;padding:0;margin:0}\n.me-outline li{margin:2px 0}\n.me-outline a{color:var(--md-muted);text-decoration:none;display:block;padding:2px 6px;border-radius:4px;transition:background .1s,color .1s}\n.me-outline a:hover{background:var(--md-code-bg);color:var(--md-accent)}\n.me-outline a.me-outline-active{background:var(--md-accent);color:#fff;font-weight:600}\n.me-outline-l1 a{font-weight:600;color:var(--md-text)}\n.me-outline-l2 a{padding-left:12px}\n.me-outline-l3 a{padding-left:20px;font-size:12px}\n.me-outline-l4 a{padding-left:28px;font-size:12px}\n.me-wrapper.me-zen .me-body{max-width:820px;margin:0 auto}\n.me-wrapper.me-zen .me-textarea{font-size:15px;line-height:1.8}\n.me-sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}\n@media print{.me-wrapper{border:0!important;box-shadow:none!important}\n.me-toolbar,.me-statusbar,.me-divider{display:none!important}\n.me-body.me-mode-split .me-editor-pane{display:none}\n.me-body.me-mode-split .me-preview-pane{flex:1 1 100%!important}\n.me-preview{padding:0!important;font-size:11pt}\n.me-wrapper.me-fullscreen{position:static!important;width:auto!important;height:auto!important}}\n[dir=rtl] .me-gutter{border-right:none;border-left:1px solid var(--md-border);text-align:left}\n[dir=rtl] .me-gutter-line{padding-right:0;padding-left:4px}\n[dir=rtl] .me-toolbar-group{margin-left:0;margin-right:auto;padding-left:0;padding-right:6px;border-left:none;border-right:1px solid var(--md-border)}\n[dir=rtl] .me-outline{right:auto;left:0;border-left:none;border-right:1px solid var(--md-border)}\n[dir=rtl] .me-outline-l2 a{padding-left:0;padding-right:12px}\n[dir=rtl] .me-outline-l3 a{padding-left:0;padding-right:20px}\n[dir=rtl] .me-outline-l4 a{padding-left:0;padding-right:28px}\n[dir=rtl] .me-preview blockquote{border-left:none;border-right:3px solid var(--md-accent);border-radius:6px 0 0 6px}\n[dir=rtl] .me-preview ul,[dir=rtl] .me-preview ol{padding-left:0;padding-right:1.6em}\n[dir=rtl] .me-preview li.me-task-item{margin-left:0;margin-right:-1.4em}\n[dir=rtl] .me-preview dd{margin-left:0;margin-right:1.6em}\n[dir=rtl] .me-preview .me-footnotes ol{padding-left:0;padding-right:1.2em}\n[dir=rtl] .me-preview .me-footnote-backref{margin-right:0;margin-left:.4em}\n[dir=rtl] .me-search{right:auto;left:12px}\n[dir=rtl] .me-toast{right:auto;left:16px}\n[dir=rtl] .me-context-menu-shortcut{margin-left:0;margin-right:24px}\n[dir=rtl] .me-statusbar{justify-content:flex-start}',document.head.appendChild(d))),this._buildDOM(),this._themeCtx=je(this),this._i18nCtx=$(this),t.theme&&"undefined"!=typeof document&&document.documentElement.setAttribute("data-md-theme",Te(t.theme));const n=Se(this.config.theme);if(Le(n,this.el),this._buildToolbar(),this._updateModeButtons(),this._bindToolbarKeyboard(),this._initAriaLive(),this._bindEvents(),this._bindContextMenu(),this._trackOutlineScroll(),!1!==this.config.floatingToolbar&&this._initFloatingToolbar(),this.textarea.value=this._value,this._pushHistory(),this._render(),this._updateWordCount(),Array.isArray(this.config.plugins)){const e=this.config.plugins.map(e=>"string"==typeof e?{...ye[e],_isStringRef:!0}:e).filter(Boolean);ve(e).forEach(e=>this.use(e))}if(this.config.autofocus&&!this.config.readOnly&&this.focus(),"function"==typeof this.config.onCreate)try{this.config.onCreate(this)}catch(e){}Ue.trigger("afterCreate",this)}_buildDOM(){const e=document.createElement("div");var t;e.className=`me-wrapper me-theme-${t=this.config.theme,t&&"auto"!==t?t:Te("auto")}`,this.config.readOnly&&e.classList.add("me-readonly"),e.dataset.id=this.id,e.setAttribute("role","application"),e.setAttribute("aria-label",b("edit")),this.config.className&&this.config.className.split(/\s+/).filter(Boolean).forEach(t=>e.classList.add(t));const n=this.config.height;e.style.height="number"==typeof n?`${n}px`:n||"400px",this.config.style&&"object"==typeof this.config.style&&Object.entries(this.config.style).forEach(([t,n])=>{n&&(e.style[t]=n)});const r=document.createElement("div");r.className="me-toolbar",r.setAttribute("role","toolbar");const i=document.createElement("div");i.className=`me-body me-mode-${this._mode}`;const o=document.createElement("div");o.className="me-editor-pane";const s=document.createElement("div");s.className="me-editor-inner";const a=document.createElement("div");a.className="me-gutter",this.config.lineNumbers||(a.style.display="none"),s.appendChild(a);const l=document.createElement("textarea");l.className="me-textarea",l.spellcheck=!!this.config.spellcheck,l.readOnly=!!this.config.readOnly,l.style.tabSize=String(this.config.tabSize||2),l.placeholder=this.config.placeholder||b("placeholder"),l.setAttribute("aria-label",b("edit")),s.appendChild(l),o.appendChild(s);const c=document.createElement("div");c.className="me-divider",c.setAttribute("role","separator");const d=document.createElement("div");d.className="me-preview-pane",d.setAttribute("role","region"),d.setAttribute("aria-label",b("preview"));const h=document.createElement("div");h.className="me-preview",d.appendChild(h),i.appendChild(o),i.appendChild(c),i.appendChild(d),e.appendChild(r),e.appendChild(i);let u=null;this.config.wordCount&&(u=document.createElement("div"),u.className="me-statusbar",e.appendChild(u)),this.container.appendChild(e),this.el=e,this.toolbarEl=r,this.bodyEl=i,this.editorPane=o,this.editorInner=s,this.gutter=a,this.previewPane=d,this.dividerEl=c,this.textarea=l,this.previewEl=h,this.statusEl=u,this._restoreDividerPosition()}_buildToolbar(){const e=this.config.toolbar;if(!e||!Array.isArray(e)||0===e.length)return;const t=[];if(e.forEach(e=>{if("|"===e){const e=document.createElement("span");return e.className="me-toolbar-sep",void this.toolbarEl.appendChild(e)}"edit"!==e&&"split"!==e&&"preview"!==e&&"fullscreen"!==e?this.toolbarEl.appendChild(this._createBtn(e)):t.push(e)}),t.length){const e=document.createElement("div");e.className="me-toolbar-group",t.forEach(t=>{const n=this._createBtn(t);"edit"!==t&&"split"!==t&&"preview"!==t||(n.dataset.mode=t,t===this._mode&&n.classList.add("me-active")),e.appendChild(n)}),this.toolbarEl.appendChild(e)}}_createBtn(e){const r=document.createElement("button");r.type="button",r.className=`me-btn me-btn-${e}`,r.dataset.action=e;const i=b(e)||e;return r.title=i,r.setAttribute("aria-label",i),r.innerHTML=n[e]||`${t(e)}`,r}_bindEvents(){const e=this.textarea,t=()=>{const t=this._value;if(this._value=e.value,Ue.trigger("beforeChange",this),this._emit("beforeChange",t,this._value),this._scheduleRender(),this._scheduleHistory(),this._updateWordCount(),this._renderGutter(),this._updateOutline(),this._emit("input",this._value),this._emit("change",this._value),"function"==typeof this.config.onInput)try{this.config.onInput(this._value,this)}catch(e){}if("function"==typeof this.config.onChange)try{this.config.onChange(this._value,this)}catch(e){}this._emit("afterChange",this._value),Ue.trigger("afterChange",this)};e.addEventListener("input",t);const n=e=>{"Enter"!==e.key||e.shiftKey||e.ctrlKey||e.metaKey||this._handleSmartEnter(e),this._handleKeydown(e)};e.addEventListener("keydown",n);const r=e=>this._handleBracketAutoClose(e);e.addEventListener("keypress",r);const i=()=>{this._updateCurrentLine()};e.addEventListener("click",i),e.addEventListener("keyup",i);const o=()=>{this._syncScroll()};e.addEventListener("scroll",o);const s=()=>{if(!this.config.syncScroll||"split"!==this._mode)return;if(this._syncing)return;this._syncing=!0;const t=this.previewPane.scrollHeight-this.previewPane.clientHeight;if(t<=0)return void(this._syncing=!1);const n=this.previewPane.scrollTop/t,r=e.scrollHeight-e.clientHeight;if(e.scrollTop=n*r,this.gutter){const e=this.gutter.scrollHeight-this.gutter.clientHeight;this.gutter.scrollTop=e>0?n*e:n*r}requestAnimationFrame(()=>{this._syncing=!1})};this.previewPane.addEventListener("scroll",s);const a=()=>{if(this._emit("focus"),"function"==typeof this.config.onFocus)try{this.config.onFocus(this)}catch(e){}},l=()=>{if(this._emit("blur"),"function"==typeof this.config.onBlur)try{this.config.onBlur(this)}catch(e){}};e.addEventListener("focus",a),e.addEventListener("blur",l),this.previewEl.addEventListener("click",e=>{const t=e.target.closest("a");if(!t)return;const n=t.getAttribute("href");if(n&&!n.startsWith("#"))if(e.preventDefault(),this._emit("linkClick",{href:n,text:t.textContent}),"function"!=typeof this.config.onLinkClick)window.open(n,"_blank","noopener");else try{this.config.onLinkClick(n,t.textContent,this)}catch(e){}});const c=e=>{const t=e.target.closest(".me-btn");if(!t)return;const n=t.dataset.mode;if(n)return void this.setMode(n);const r=t.dataset.action;r&&this.exec(r)};this.toolbarEl.addEventListener("click",c);const d=e=>this._bindDividerDrag(e);this.dividerEl.addEventListener("pointerdown",d),this._bindDragDrop(),this._cleanups.push(()=>{e.removeEventListener("input",t),e.removeEventListener("keydown",n),e.removeEventListener("keypress",r),e.removeEventListener("scroll",o),this.previewPane.removeEventListener("scroll",s),e.removeEventListener("click",i),e.removeEventListener("keyup",i),e.removeEventListener("focus",a),e.removeEventListener("blur",l),this.toolbarEl.removeEventListener("click",c),this.dividerEl.removeEventListener("pointerdown",d)})}_handleKeydown(e){if("Tab"===e.key)return e.preventDefault(),void this._handleTab(e.shiftKey);if(this._shortcuts.length)for(const t of this._shortcuts){const n=t.ctrl?e.ctrlKey||e.metaKey:!e.ctrlKey&&!e.metaKey,r=t.shift?e.shiftKey:!e.shiftKey,i=t.alt?e.altKey:!e.altKey;if(e.key.toLowerCase()===t.key&&n&&r&&i){if(e.preventDefault(),"string"==typeof t.handler)this.exec(t.handler);else if("function"==typeof t.handler)try{t.handler(this)}catch(e){}return}}if(!e.ctrlKey&&!e.metaKey)return;const t=e.key.toLowerCase(),n={b:"bold",i:"italic",k:"link",u:"underline",e:"code",1:"h1",2:"h2",3:"h3",q:"quote"};if("z"!==t||e.shiftKey)if("z"===t&&e.shiftKey||"y"===t)e.preventDefault(),this.redo();else if("s"===t){if(e.preventDefault(),this._emit("save",this._value),"function"==typeof this.config.onSave)try{this.config.onSave(this._value,this)}catch(e){}}else n[t]&&(e.preventDefault(),this.exec(n[t]));else e.preventDefault(),this.undo()}_handleTab(e){const t=this.textarea,n=t.selectionStart,r=t.selectionEnd,i=this.config.tabSize||0,o=i>0?" ".repeat(i):"\t";if(n===r)t.value=t.value.slice(0,n)+o+t.value.slice(r),t.selectionStart=t.selectionEnd=n+o.length;else{const i=t.value.lastIndexOf("\n",n-1)+1,s=t.value.slice(i,r).split("\n");let a;a=e?s.map(e=>e.replace(/^(\t| {1,4})/,"")).join("\n"):s.map(e=>o+e).join("\n"),t.value=t.value.slice(0,i)+a+t.value.slice(r),t.selectionStart=i,t.selectionEnd=i+a.length}this._value=t.value,this._pushHistory(),this._render(),this._emit("change",this._value)}_bindDividerDrag(e){if("split"!==this._mode)return;e.preventDefault();const t=e.clientX,n=this.editorPane.getBoundingClientRect().width,r=this.bodyEl.getBoundingClientRect().width;if(r<=0)return;const i=this.dividerEl,o=e=>{const o=e.clientX-t;let s=n+o;const a=r-80-i.offsetWidth;s=Math.max(80,Math.min(a,s));const l=s/r*100;this.editorPane.style.flex=`0 0 ${l}%`,this.previewPane.style.flex=`1 1 ${100-l}%`},s=()=>{window.removeEventListener("pointermove",o),window.removeEventListener("pointerup",s),this._saveDividerPosition()};window.addEventListener("pointermove",o),window.addEventListener("pointerup",s)}_saveDividerPosition(){try{const e=this.editorPane.style.flex;e&&localStorage.setItem("metona-editor-divider",e)}catch(e){}}_restoreDividerPosition(){try{const e=localStorage.getItem("metona-editor-divider");e&&"split"===this._mode&&(this.editorPane.style.flex=e,this.previewPane.style.flex="1 1 auto")}catch(e){}}_scheduleRender(){this._renderRaf||(this._renderRaf=requestAnimationFrame(()=>{this._renderRaf=null,this._render()}))}_render(){if("edit"===this._mode)return;if(this._lastRenderedValue===this._value)return;let e;this._lastRenderedValue=this._value,Ue.trigger("beforeRender",this),this._emit("beforeRender",this);try{e=this._renderFn(this._value,{highlight:this._highlightFn||void 0,locale:f()})}catch(n){e=`${b("renderError")}: ${t(n.message)}
`}if("function"==typeof this.config.sanitize)try{e=this.config.sanitize(e)}catch(e){}this.previewEl.innerHTML=e,this._renderGutter(),Ue.trigger("afterRender",this),this._emit("afterRender",this)}_renderGutter(){if(!this.config.lineNumbers||!this.gutter)return;const e=this._value?this._value.split("\n").length:1,t=this.gutter.children.length;if(t!==e)if(t${r}`;this.gutter.insertAdjacentHTML("beforeend",n)}else for(;this.gutter.children.length>e;)this.gutter.removeChild(this.gutter.lastChild)}_updateCurrentLine(){if(!this.gutter)return;const e=this.textarea.selectionStart,t=this._value.substring(0,e).split("\n").length,n=this.gutter.querySelector(".me-gutter-active");n&&n.classList.remove("me-gutter-active");const r=this.gutter.children[t-1];r&&r.classList.add("me-gutter-active")}_handleSmartEnter(e){const t=this.textarea,n=t.selectionStart,r=t.value,i=r.lastIndexOf("\n",n-1)+1,o=r.slice(i,n),s=o.match(/^(\s*)([-*+]|\d+\.)\s(.*)/);if(s){const o=s[1],a=s[2];if(!s[3].trim())return e.preventDefault(),t.value=r.slice(0,i)+"\n"+r.slice(n),t.selectionStart=t.selectionEnd=i,this._value=t.value,this._pushHistory(),this._renderGutter(),void this._emit("change",this._value);let l=a;if(/^\d+\.$/.test(a)){const e=parseInt(a,10);isNaN(e)||(l=e+1+".")}e.preventDefault();const c="\n"+o+l+" ";return t.value=r.slice(0,n)+c+r.slice(t.selectionEnd),t.selectionStart=t.selectionEnd=n+c.length,this._value=t.value,this._pushHistory(),this._renderGutter(),void this._emit("change",this._value)}const a=o.match(/^(\s*>+\s?)(.*)/);if(a){const o=a[1];if(!a[2].trim())return e.preventDefault(),t.value=r.slice(0,i)+"\n"+r.slice(n),t.selectionStart=t.selectionEnd=i,this._value=t.value,this._pushHistory(),this._renderGutter(),void this._emit("change",this._value);e.preventDefault();const s="\n"+o;t.value=r.slice(0,n)+s+r.slice(t.selectionEnd),t.selectionStart=t.selectionEnd=n+s.length,this._value=t.value,this._pushHistory(),this._renderGutter(),this._emit("change",this._value)}}_handleBracketAutoClose(e){if(!this.config.autoBrackets)return;const t=this.textarea,n=e.key,r=Ve[n];if(!r)return;const i=t.selectionStart,o=t.selectionEnd;if(i!==o){e.preventDefault();const s=t.value.slice(i,o),a=n+s+r;return t.value=t.value.slice(0,i)+a+t.value.slice(o),t.selectionStart=i+1,t.selectionEnd=i+1+s.length,this._value=t.value,this._pushHistory(),void this._emit("change",this._value)}const s=t.value[i]||"";if(n===r){if(s===r)return e.preventDefault(),void(t.selectionStart=t.selectionEnd=i+1);if(/\w/.test(s))return}e.preventDefault();const a=n+r;t.value=t.value.slice(0,i)+a+t.value.slice(o),t.selectionStart=t.selectionEnd=i+1,this._value=t.value,this._pushHistory(),this._emit("change",this._value)}_bindDragDrop(){const e=this.textarea;if(!e)return;const t=e=>{e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy")},n=e=>{e.preventDefault();const t=e.dataTransfer?.files;if(t&&t.length)return void Array.from(t).forEach(e=>{if(e.type.startsWith("image/")){const t=new FileReader;t.onload=()=>{this.insert(`\n`)},t.readAsDataURL(e)}else if(e.type.startsWith("text/")||/\.(md|txt|js|ts|json|css|html|xml|yml|yaml)$/i.test(e.name)){const t=new FileReader;t.onload=()=>this.insert(t.result),t.readAsText(e)}});const n=e.dataTransfer?.getData("text/plain");n&&this.insert(n)};e.addEventListener("dragover",t),e.addEventListener("drop",n),this._cleanups.push(()=>{e.removeEventListener("dragover",t),e.removeEventListener("drop",n)})}_buildOutline(){if(!this.config.outline||!this.previewEl)return;const e=this.el.querySelector(".me-outline");e&&e.remove();const n=[],r=/]*>(.+?)<\/h\1>/gi;let i;for(;null!==(i=r.exec(this.previewEl.innerHTML));)n.push({level:parseInt(i[1],10),id:i[2],text:i[3].replace(/<[^>]+>/g,"")});if(!n.length)return;const o=document.createElement("div");o.className="me-outline",o.innerHTML=`${b("outline")||"大纲"}
`;const s=(e,n)=>{let r="",i=0;for(;i${t(o.text)}`;const a=[];let l=i+1;for(;lo.level;)a.push(e[l]),l++;a.length&&(r+=s(a,o.level+1)),r+="",i=l>i+1?l:i+1}return r+"
"};o.innerHTML+=s(n,1),this.el.appendChild(o),o.addEventListener("click",e=>{const t=e.target.closest("a");if(!t)return;e.preventDefault();const n=t.getAttribute("href").slice(1),r=this.previewEl.querySelector("#"+CSS.escape(n));if(r){r.scrollIntoView({behavior:"smooth",block:"start"});const e=this._value.indexOf(r.textContent||"");-1!==e&&(this.textarea.focus(),this.textarea.setSelectionRange(e,e))}})}_updateOutline(){this.config.outline&&(this._outlineTimer&&clearTimeout(this._outlineTimer),this._outlineTimer=setTimeout(()=>this._buildOutline(),300))}_trackOutlineScroll(){if(!this.config.outline||!this.previewPane)return;let e=!1;const t=()=>{e||(e=!0,requestAnimationFrame(()=>{if(e=!1,!this.el)return;const t=this.el.querySelector(".me-outline");if(!t)return;const n=this.previewEl.querySelectorAll("h1, h2, h3, h4, h5, h6");let r="";const i=this.previewPane.scrollTop+80;n.forEach(e=>{e.offsetTop<=i&&(r=e.id)}),t.querySelectorAll("a").forEach(e=>{e.classList.toggle("me-outline-active",e.getAttribute("href")==="#"+r)})}))};this.previewPane.addEventListener("scroll",t,{passive:!0}),this._cleanups.push(()=>this.previewPane.removeEventListener("scroll",t))}_scheduleHistory(){this._historyTimer&&clearTimeout(this._historyTimer),this._historyTimer=setTimeout(()=>this._pushHistory(),this.config.historyDebounce||400)}_pushHistory(){if(this._history[this._historyIndex]===this._value)return;this._history=this._history.slice(0,this._historyIndex+1),this._history.push(this._value);const e=this.config.historyLimit>0?this.config.historyLimit:100;for(;this._history.length>e;)this._history.shift();this._historyIndex=this._history.length-1}undo(){return this._historyIndex<=0||(this._historyIndex--,this._applyHistory()),this}redo(){return this._historyIndex>=this._history.length-1||(this._historyIndex++,this._applyHistory()),this}canUndo(){return this._historyIndex>0}canRedo(){return this._historyIndexthis._wrapSelection("**","**"),italic:()=>this._wrapSelection("*","*"),strikethrough:()=>this._wrapSelection("~~","~~"),underline:()=>this._wrapSelection("",""),code:()=>this._wrapSelection("`","`"),h1:()=>this._toggleLinePrefix("# "),h2:()=>this._toggleLinePrefix("## "),h3:()=>this._toggleLinePrefix("### "),quote:()=>this._toggleLinePrefix("> "),ul:()=>this._toggleLinePrefix("- "),ol:()=>this._toggleLinePrefix("1. "),indent:()=>this._handleTab(!1),outdent:()=>this._handleTab(!0),hr:()=>this._insertBlock("\n---\n"),link:()=>this._insertLink(),image:()=>this._insertImage(),table:()=>this._insertTable(),undo:()=>this.undo(),redo:()=>this.redo(),edit:()=>this.setMode("edit"),split:()=>this.setMode("split"),preview:()=>this.setMode("preview"),fullscreen:()=>this.toggleFullscreen(),zen:()=>this.toggleZen(),wordwrap:()=>this.toggleWordWrap(),formatTable:()=>this._formatTable()}[e];if(n)return n.apply(this,t),this;if(this._customActions&&"function"==typeof this._customActions[e])try{this._customActions[e].apply(this,t)}catch(e){}return this}_wrapSelection(e,t){const n=this.textarea,r=n.selectionStart,i=n.selectionEnd,o=n.value.slice(r,i),s=o||"text",a=e+s+t;n.value=n.value.slice(0,r)+a+n.value.slice(i),n.focus(),o?(n.selectionStart=r+e.length,n.selectionEnd=r+e.length+s.length):n.selectionStart=n.selectionEnd=r+e.length,this._value=n.value,this._pushHistory(),this._render(),this._updateWordCount(),this._emit("change",this._value)}_toggleLinePrefix(e){const t=this.textarea,n=t.selectionStart,r=t.value.lastIndexOf("\n",n-1)+1,i=t.value.indexOf("\n",n),o=-1===i?t.value.length:i,s=t.value.slice(r,o),a=s.match(/^(#{1,6}\s*|>\s*|[-*+]\s*|\d+\.\s*)/);let l;l=a&&a[0]===e?s.slice(e.length):a?e+s.slice(a[0].length):e+s,t.value=t.value.slice(0,r)+l+t.value.slice(o),t.focus(),t.selectionStart=t.selectionEnd=r+l.length,this._value=t.value,this._pushHistory(),this._render(),this._updateWordCount(),this._emit("change",this._value)}_insertBlock(e){const t=this.textarea,n=t.selectionStart,r=t.value.slice(0,n),i=(r&&!r.endsWith("\n")?"\n":"")+e;t.value=t.value.slice(0,n)+i+t.value.slice(t.selectionEnd),t.focus();const o=n+i.length;t.selectionStart=t.selectionEnd=o,this._value=t.value,this._pushHistory(),this._render(),this._updateWordCount(),this._emit("change",this._value)}_insertLink(){const e=this.textarea,t=e.selectionStart,n=e.selectionEnd,r=e.value.slice(t,n)||b("link")||"link",i=`[${r}](https://)`;e.value=e.value.slice(0,t)+i+e.value.slice(n),e.focus(),e.selectionStart=t+r.length+3,e.selectionEnd=e.selectionStart+8,this._value=e.value,this._pushHistory(),this._render(),this._emit("change",this._value)}_insertImage(){const e=this.textarea,t=e.selectionStart,n=e.selectionEnd,r=e.value.slice(t,n)||b("image")||"image",i=``;e.value=e.value.slice(0,t)+i+e.value.slice(n),e.focus(),e.selectionStart=t+r.length+4,e.selectionEnd=e.selectionStart+8,this._value=e.value,this._pushHistory(),this._render(),this._emit("change",this._value)}_insertTable(e=3,t=3){let n=`| ${Array.from({length:t},(e,t)=>`${b("tableCols")||"列"}${t+1}`).join(" | ")} |\n| ${Array.from({length:t},()=>"---").join(" | ")} |\n`;for(let r=1;r" ").join(" | ")} |\n`;this._insertBlock("\n"+n)}_formatTable(){const e=this.textarea,t=e.selectionStart,n=e.value.substring(0,t),r=e.value.substring(t),i=n.lastIndexOf("\n\n"),o=r.indexOf("\n\n"),s=-1===i?0:i+2,a=-1===o?e.value.length:t+o,l=e.value.substring(s,a).split("\n").filter(e=>e.includes("|"));if(l.length<2)return;const c=l.map(e=>e.replace(/^\s*\|?\s*|\s*\|?\s*$/g,"").split(/\s*\|\s*/)),d=Math.max(...c.map(e=>e.length)),h=Array(d).fill(3);c.forEach(e=>{e.forEach((e,t)=>{h[t]=Math.max(h[t],e.trim().length)})});const u=(e,t)=>{const n=t-e.length;return e+" ".repeat(Math.max(0,n))},p=c.map(e=>{const t=[];for(let n=0;n{const r=n,i=r.dataset.mode,o=r.dataset.action;if(i)return r.classList.toggle("me-active",i===this._mode),void(r.disabled=!1);r.disabled="fullscreen"!==o&&(t||!!e)&&!("undo"===o||"redo"===o)})}toggleFullscreen(){this._fullscreen=!this._fullscreen,this.el.classList.toggle("me-fullscreen",this._fullscreen);const e=this.toolbarEl.querySelector(".me-btn-fullscreen");if(e&&(e.title=this._fullscreen?b("fullscreenExit")||"退出全屏":b("fullscreen")||"全屏"),this._emit("fullscreen",this._fullscreen),"function"==typeof this.config.onFullscreen)try{this.config.onFullscreen(this._fullscreen,this)}catch(e){}return this}isFullscreen(){return this._fullscreen}exitFullscreen(){return this._fullscreen&&this.toggleFullscreen(),this}toggleZen(){return this._zenMode=!this._zenMode,this.el&&this.el.classList.toggle("me-zen",this._zenMode),this._zenMode&&this.toolbarEl?(this._zenMouseHandler=e=>{this.toolbarEl.style.opacity=e.clientY<40?"1":"0",this.toolbarEl.style.pointerEvents=e.clientY<40?"auto":"none"},this.toolbarEl.style.transition="opacity 0.2s",this.toolbarEl.style.opacity="0",this.toolbarEl.style.pointerEvents="none",document.addEventListener("mousemove",this._zenMouseHandler),this.statusEl&&(this.statusEl.style.display="none")):(this._zenMouseHandler&&(document.removeEventListener("mousemove",this._zenMouseHandler),this._zenMouseHandler=null),this.toolbarEl&&(this.toolbarEl.style.opacity="",this.toolbarEl.style.pointerEvents="",this.toolbarEl.style.transition=""),this.statusEl&&(this.statusEl.style.display="")),this._emit("zenChange",this._zenMode),this}isZen(){return this._zenMode}toggleWordWrap(){return this._wordWrap=!this._wordWrap,this.textarea&&(this.textarea.style.whiteSpace=this._wordWrap?"pre-wrap":"pre"),this}setWordWrap(e){return this._wordWrap=!!e,this.textarea&&(this.textarea.style.whiteSpace=this._wordWrap?"pre-wrap":"pre"),this}isWordWrap(){return this._wordWrap}_initFloatingToolbar(){if("undefined"==typeof document)return;if(!document.getElementById("me-float-style")){const e=document.createElement("style");e.id="me-float-style",e.textContent=".me-float-toolbar{position:absolute;z-index:25;display:flex;gap:4px;padding:4px 6px;background:var(--md-toolbar-bg,#f8f9fa);border:1px solid var(--md-border,rgba(0,0,0,0.1));border-radius:8px;box-shadow:0 8px 24px -8px rgba(0,0,0,0.2);opacity:0;transform:translateY(4px);transition:opacity .15s,transform .15s;pointer-events:none}.me-float-toolbar.me-visible{opacity:1;transform:translateY(0);pointer-events:auto}.me-float-toolbar .me-btn{width:28px;height:28px}",document.head.appendChild(e)}if(!this._floatingEnabled)return;const e=this.textarea,t=()=>{if(this._destroyed||this.config.readOnly||!this._floatingEnabled)return;const t=e.selectionStart;if(t===e.selectionEnd)return void this._hideFloatingToolbar();this._floatingToolbar&&this._floatingToolbar.parentNode||this._buildFloatingToolbar();const n=e.getBoundingClientRect(),r=e.value.substring(0,t).split("\n").length-1,i=parseInt(getComputedStyle(e).lineHeight,10)||22,o=parseInt(getComputedStyle(e).paddingTop,10)||16,s=e.scrollTop;let a=n.top+o+r*i-s-36-4;an.bottom&&(a=n.bottom-36-4);let l=n.left+8*("backward"!==e.selectionDirection?(e.selectionEnd-e.selectionStart)/2:0)+10;lc&&(l=c),this._floatingToolbar.style.top=a+"px",this._floatingToolbar.style.left=l+"px",this._floatingToolbar.classList.add("me-visible")},n=()=>{this._hideFloatingToolbar()};let r=e.selectionStart,i=e.selectionEnd;this._selectionTimer=setInterval(()=>{if(this._destroyed||!document.body.contains(e)||!this._floatingEnabled)return;const t=e.selectionStart,n=e.selectionEnd;if(t!==r||n!==i){r=t,i=n;const e=this._value.slice(t,n);this._emit("selectionChange",{start:t,end:n,text:e})}},500),this._cleanups.push(()=>{this._selectionTimer&&(clearInterval(this._selectionTimer),this._selectionTimer=null)}),e.addEventListener("mouseup",()=>{this._floatingEnabled&&setTimeout(t,0)}),e.addEventListener("keyup",()=>{this._floatingEnabled&&(e.selectionStart!==e.selectionEnd?setTimeout(t,0):setTimeout(n,0),this._emit("cursorMove",this.getCursorPosition()))}),e.addEventListener("blur",()=>setTimeout(n,300)),e.addEventListener("click",()=>{e.selectionStart===e.selectionEnd&&setTimeout(n,0)})}toggleFloatingToolbar(){if(this._floatingEnabled=!this._floatingEnabled,this._floatingEnabled){if(!this._selectionTimer){const e=this.textarea;this._selectionTimer=setInterval(()=>{!this._destroyed&&this._floatingEnabled&&(e.selectionStart,e.selectionEnd)},500),this._cleanups.push(()=>{this._selectionTimer&&(clearInterval(this._selectionTimer),this._selectionTimer=null)})}}else this._selectionTimer&&(clearInterval(this._selectionTimer),this._selectionTimer=null),this._floatingToolbar&&(this._floatingToolbar.parentNode&&this._floatingToolbar.parentNode.removeChild(this._floatingToolbar),this._floatingToolbar=null);return this}isFloatingToolbar(){return this._floatingEnabled}_buildFloatingToolbar(){const e=document.createElement("div");e.className="me-float-toolbar",["bold","italic","code","link","strikethrough"].forEach(t=>{const n=this._createBtn(t);n.addEventListener("mousedown",e=>{e.preventDefault(),e.stopPropagation(),this.exec(t),setTimeout(()=>this.textarea.focus(),0)}),e.appendChild(n)}),this.editorPane.appendChild(e),this._floatingToolbar=e}_hideFloatingToolbar(){this._floatingToolbar&&this._floatingToolbar.classList.remove("me-visible")}_bindToolbarKeyboard(){if(!this.toolbarEl)return;const e=e=>{const t=[...this.toolbarEl.querySelectorAll(".me-btn:not(:disabled)")];if(!t.length)return;const n=t.indexOf(document.activeElement);-1!==n&&("ArrowRight"===e.key?(e.preventDefault(),t[(n+1)%t.length].focus()):"ArrowLeft"===e.key?(e.preventDefault(),t[(n-1+t.length)%t.length].focus()):"Home"===e.key?(e.preventDefault(),t[0].focus()):"End"===e.key&&(e.preventDefault(),t[t.length-1].focus()))};this.toolbarEl.addEventListener("keydown",e),this._cleanups.push(()=>this.toolbarEl.removeEventListener("keydown",e))}_initAriaLive(){if(!this.el)return;const e=document.createElement("div");e.className="me-sr-only",e.setAttribute("aria-live","polite"),e.setAttribute("aria-atomic","true"),this.el.appendChild(e),this._ariaLive=e}_announce(e){this._ariaLive&&(this._ariaLive.textContent="",requestAnimationFrame(()=>{this._ariaLive.textContent=e}))}_syncScroll(){if(this._syncing)return;this._syncing=!0;const e=this.textarea;if(!e)return void(this._syncing=!1);const t=e.scrollHeight-e.clientHeight;if(t<=0)return void(this._syncing=!1);const n=e.scrollTop/t;if(this.gutter){const t=this.gutter.scrollHeight-this.gutter.clientHeight;this.gutter.scrollTop=t>0?n*t:e.scrollTop}if(this.config.syncScroll&&"split"===this._mode&&this.previewPane){const e=this.previewPane.scrollHeight-this.previewPane.clientHeight;e>0&&(this.previewPane.scrollTop=n*e)}requestAnimationFrame(()=>{this._syncing=!1})}_updateWordCount(){if(!this.config.wordCount||!this.statusEl)return;const e=this._value||"",t=e.length,n=(e.match(/[\u4e00-\u9fa5]/g)||[]).length+(e.replace(/[\u4e00-\u9fa5]/g," ").match(/[a-zA-Z0-9]+/g)||[]).length,r=e?e.split("\n").length:0,i=Math.max(1,Math.ceil(n/300));this.statusEl.textContent=[`${b("characters")}: ${t}`,`${b("words")}: ${n}`,`${b("lines")}: ${r}`,`${b("readingTime")}: ${i} ${b("minutes")}`].join(" · ")}getStats(){const e=this._value||"",t=(e.match(/[\u4e00-\u9fa5]/g)||[]).length,n=(e.replace(/[\u4e00-\u9fa5]/g," ").match(/[a-zA-Z0-9]+/g)||[]).length;return{characters:e.length,words:t+n,chineseChars:t,englishWords:n,lines:e?e.split("\n").length:0,readingTime:Math.max(1,Math.ceil((t+n)/300))}}getSelectedText(){return this.textarea?this._value.slice(this.textarea.selectionStart,this.textarea.selectionEnd):""}getCursorPosition(){if(!this.textarea)return{line:1,column:0};const e=this.textarea.selectionStart,t=this._value.substring(0,e),n=t.split("\n").length,r=e-t.lastIndexOf("\n")-1;return{line:n,column:r<0?0:r}}setCursorPosition(e,t=0){if(!this.textarea)return this;const n=this._value.split("\n"),r=Math.max(1,Math.min(e,n.length));let i=0;for(let e=0;e=t.length?"":t[n]}getValue(){return this._destroyed?"":this._value}setValue(e,t={}){if(this._destroyed)return this;if(Ue.trigger("beforeChange",this),this._emit("beforeChange",this._value,e),this._value=e||"",this.textarea.value=this._value,t.silent||this._pushHistory(),this._render(),this._renderGutter(),this._updateWordCount(),this._updateOutline(),this.gutter&&(this.gutter.scrollTop=0),this.textarea.scrollTop=0,!t.silent&&(this._emit("change",this._value),"function"==typeof this.config.onChange))try{this.config.onChange(this._value,this)}catch(e){}return this._emit("afterChange",this._value),Ue.trigger("afterChange",this),this}getHTML(){Ue.trigger("beforeRender",this),this._emit("beforeRender",this);let e=this._renderFn(this._value,{highlight:this._highlightFn||void 0,locale:f()});if("function"==typeof this.config.sanitize)try{e=this.config.sanitize(e)}catch(e){}return Ue.trigger("afterRender",this),this._emit("afterRender",this),e}refresh(){return this._lastRenderedValue=null,this._render(),this}copyAsMarkdown(){return"undefined"!=typeof navigator&&navigator.clipboard&&navigator.clipboard.writeText(this._value).then(()=>this._emit("copy",{type:"markdown"})).catch(()=>{}),this}copyAsHTML(){const e=this.getHTML();if("undefined"!=typeof navigator&&navigator.clipboard){const t=new Blob([e],{type:"text/html"}),n=new ClipboardItem({"text/html":t,"text/plain":new Blob([this._value],{type:"text/plain"})});navigator.clipboard.write([n]).then(()=>this._emit("copy",{type:"html"})).catch(()=>{})}return this}insert(e,t={}){const n=this.textarea,r=n.selectionStart,i=n.selectionEnd;return n.value=n.value.slice(0,r)+e+n.value.slice(t.replace?i:r),n.focus(),n.selectionStart=n.selectionEnd=r+e.length,this._value=n.value,this._pushHistory(),this._render(),this._updateWordCount(),this._emit("change",this._value),this}wrap(e,t){return this._wrapSelection(e,t||e),this}focus(){return this.textarea&&this.textarea.focus(),this}blur(){return this.textarea&&this.textarea.blur(),this}enable(){return this.textarea&&(this.textarea.disabled=!1),this.el&&this.el.classList.remove("me-disabled"),this}disable(){return this.textarea&&(this.textarea.disabled=!0),this.el&&this.el.classList.add("me-disabled"),this}isDisabled(){return!!this.textarea&&this.textarea.disabled}setReadOnly(e){return this.config.readOnly=!!e,this.textarea&&(this.textarea.readOnly=!!e),this.el&&this.el.classList.toggle("me-readonly",!!e),this._updateModeButtons(),this}isReadOnly(){return!!this.config.readOnly}on(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),()=>this.off(e,t)}off(e,t){const n=this._listeners[e];return n&&(this._listeners[e]=n.filter(e=>e!==t)),this}_emit(e,...t){const n=this._listeners[e];n&&n.forEach(e=>{try{e(...t,this)}catch(e){}})}use(e,t={}){let n=e;if("string"==typeof e&&(n=ye[e],!n))return this;if(!n||"object"!=typeof n)return this;const r={...n,...t};if("function"==typeof r.install)try{const e=r.install(this,t);e&&"function"==typeof e.then&&e.catch(e=>{})}catch(e){}return this._plugins.push(r),this}unuse(e){const t=this._plugins.findIndex(t=>t.name===e);if(-1===t)return this;const n=this._plugins[t];if("function"==typeof n.destroy)try{n.destroy(this)}catch(e){}return this._plugins.splice(t,1),this}getPlugins(){return[...this._plugins]}addToolbarButton(e){if(!e||!e.action)return this;const n=document.createElement("button");return n.type="button",n.className=`me-btn me-btn-custom-${e.action}`,n.title=e.title||e.action,n.setAttribute("aria-label",e.title||e.action),n.innerHTML=e.icon||`${t(e.text||e.action)}`,"function"==typeof e.onClick?n.addEventListener("click",t=>{t.stopPropagation(),e.onClick(this)}):e.action&&(n.dataset.action=e.action,this._customActions=this._customActions||{},this._customActions[e.action]=e.handler),this.toolbarEl.insertBefore(n,this.toolbarEl.querySelector(".me-toolbar-group")||null),this}registerShortcut(e,t,n=""){if(!e)return this;const r=e.toLowerCase().split("+"),i=r.pop(),o=r.includes("ctrl")||r.includes("cmd"),s=r.includes("shift"),a=r.includes("alt"),l=r.includes("meta");return this._shortcuts.push({combo:e,key:i,ctrl:o,shift:s,alt:a,meta:l,handler:t,description:n}),this}unregisterShortcut(e){return this._shortcuts=this._shortcuts.filter(t=>t.combo!==e),this}getShortcuts(){return[...this._shortcuts]}configureToolbar(e){return this.toolbarEl?(this.config.toolbar=e,this.toolbarEl.innerHTML="",this._buildToolbar(),this):this}removeToolbarButton(e){if(!this.toolbarEl)return this;const t=this.toolbarEl.querySelector(`.me-btn[data-action="${e}"], .me-btn[data-mode="${e}"]`);return t&&t.remove(),this}registerContextMenu(e=[]){return this._contextMenuItems=e,this}_bindContextMenu(){if(!this.el)return;const e=e=>{const t=document.querySelector(".me-context-menu");t&&t.remove(),this._showContextMenu(e)};this.el.addEventListener("contextmenu",e),this._cleanups.push(()=>this.el.removeEventListener("contextmenu",e))}_showContextMenu(e){e.preventDefault();const t=this.textarea,n=t&&t.selectionStart!==t.selectionEnd,r=[{label:b("undo")||"Undo",action:"undo",shortcut:"Ctrl+Z",disabled:!this.canUndo()},{label:b("redo")||"Redo",action:"redo",shortcut:"Ctrl+Y",disabled:!this.canRedo()},{sep:!0},{label:b("cut")||"Cut",action:"cut",shortcut:"Ctrl+X",disabled:!n},{label:b("copy")||"Copy",action:"copy",shortcut:"Ctrl+C",disabled:!n},{label:b("paste")||"Paste",action:"paste",shortcut:"Ctrl+V",disabled:!!this.config.readOnly},{label:b("selectAll")||"Select All",action:"selectAll",shortcut:"Ctrl+A"}];this._contextMenuItems.length&&(r.push({sep:!0}),this._contextMenuItems.forEach(e=>r.push(e)));const i=document.createElement("div");i.className="me-context-menu",i.style.left=e.clientX+"px",i.style.top=e.clientY+"px",requestAnimationFrame(()=>{const t=i.getBoundingClientRect();t.right>window.innerWidth&&(i.style.left=e.clientX-t.width+"px"),t.bottom>window.innerHeight&&(i.style.top=e.clientY-t.height+"px")}),r.forEach(e=>{if(e.sep){const e=document.createElement("div");return e.className="me-context-menu-sep",void i.appendChild(e)}const t=document.createElement("div");t.className="me-context-menu-item",e.disabled&&t.classList.add("me-disabled"),t.innerHTML=`${e.label}${e.shortcut?``:""}`,t.addEventListener("click",t=>{t.stopPropagation(),e.disabled||(e.onClick?e.onClick():e.action&&this._execContextAction(e.action),this._hideContextMenu())}),i.appendChild(t)}),document.body.appendChild(i),document.addEventListener("click",e=>{i.contains(e.target)||this._hideContextMenu()},{once:!0}),document.addEventListener("keydown",e=>{"Escape"===e.key&&this._hideContextMenu()},{once:!0})}_hideContextMenu(){const e=document.querySelector(".me-context-menu");e&&e.remove()}_execContextAction(e){const t=this.textarea;if(t)switch(e){case"undo":this.undo();break;case"redo":this.redo();break;case"cut":document.execCommand("cut");break;case"copy":document.execCommand("copy");break;case"paste":document.execCommand("paste");break;case"selectAll":t.focus(),t.select();break;default:this.exec(e)}}toast(e,n={}){if(!this.el||"undefined"==typeof document)return this;const{type:r="info",duration:i=3e3,animation:o="fade"}=n,s=document.createElement("div");s.className=`me-toast me-toast-${r} me-toast-${o}`,s.innerHTML=`${qe[r]||""}${t(String(e))}`,this.el.appendChild(s),requestAnimationFrame(()=>{s.classList.add("me-toast-enter")});const a=()=>{s.classList.remove("me-toast-enter"),s.classList.add("me-toast-leave"),setTimeout(()=>{s.parentNode&&s.parentNode.removeChild(s)},300)};return i>0&&setTimeout(a,i),s.addEventListener("click",a),this}setLocale(e){return this._i18nCtx&&this._i18nCtx.set(e),this}getLocale(){return this._i18nCtx?this._i18nCtx.get():f()}t(e,t){return this._i18nCtx?this._i18nCtx.t(e,t):b(e,t)}setTheme(e){return e?(this.config.theme=e,this._themeCtx&&this._themeCtx.set(e),this):this}getTheme(){return this._themeCtx?this._themeCtx.get():this.config.theme||"auto"}getThemeContext(){return this._themeCtx||null}getStatus(){return{id:this.id,mode:this._mode,theme:this.getTheme(),locale:f(),fullscreen:this._fullscreen,readOnly:this.config.readOnly||!1,disabled:!!this.textarea&&this.textarea.disabled,destroyed:this._destroyed,plugins:this._plugins.map(e=>e.name||"custom")}}destroy(){if(!this._destroyed){if(Ue.trigger("beforeDestroy",this),this._renderRaf&&cancelAnimationFrame(this._renderRaf),this._historyTimer&&clearTimeout(this._historyTimer),this._outlineTimer&&clearTimeout(this._outlineTimer),this._selectionTimer&&(clearInterval(this._selectionTimer),this._selectionTimer=null),this._cleanups.forEach(e=>{try{e()}catch(e){}}),this._cleanups=[],this._shortcuts=[],this._contextMenuItems=[],this._customActions={},this._floatingToolbar&&this._floatingToolbar.parentNode&&this._floatingToolbar.parentNode.removeChild(this._floatingToolbar),this._floatingToolbar=null,this.el&&this.el.querySelectorAll(".me-toast").forEach(e=>e.remove()),this._plugins.forEach(e=>{if("function"==typeof e.destroy)try{e.destroy(this)}catch(e){}}),this._plugins=[],this.el&&this.el.parentNode&&this.el.parentNode.removeChild(this.el),this.el=null,this.textarea=null,this.previewEl=null,this._destroyed=!0,"function"==typeof this.config.onDestroy)try{this.config.onDestroy(this)}catch(e){}this._emit("destroy"),this._listeners={},Ue.trigger("afterDestroy",this)}}isDestroyed(){return this._destroyed}}Ue._hooks=new Map;const Ke=new Map;for(const[e,t]of Object.entries(a))Ke.set(e,t);const Ge={register(e,t){Ke.set(e,{name:e,enter:t.enter||{},leave:t.leave||{},duration:t.duration||300,easing:t.easing||"cubic-bezier(0.4, 0, 0.2, 1)"})},unregister(e){Ke.delete(e)},get:e=>Ke.get(e)||a[e]||null,getAnimationNames:()=>Array.from(Ke.keys()),getActiveCount:()=>0,cancelAll(){},reset(){Ke.clear();for(const[e,t]of Object.entries(a))Ke.set(e,t)},destroy(){Ke.clear()}},Ye="0.2.3",Ze=[];function Xe(e,t={}){return new Ue(e,t)}function Qe(e,t={}){let n=e;if("string"==typeof e&&(n=ye[e],!n))return ot;if(!n||"object"!=typeof n)return ot;const r=t&&"object"==typeof t&&Object.keys(t).length>0?{...n,...t}:n;return Ze.push(r),ot}function Je(e,t){return Ue.on(e,t)}function et(e,t){return Ue.off(e,t),ot}function tt(e,t){return Ne&&"function"==typeof Ne.switchTheme&&Ne.switchTheme(e),ot}function nt(e){return A&&"function"==typeof A.setCurrentLocale&&A.setCurrentLocale(e),ot}function rt(){if(Ne){try{Ne.clearThemeListeners()}catch(e){}try{Ne.unwatchSystemTheme()}catch(e){}}if(A)try{A.clearLocaleListeners()}catch(e){}if(Ge)try{Ge.cancelAll()}catch(e){}Ze.length=0}function it(){return{version:Ye,theme:Ne&&"function"==typeof Ne.getCurrentTheme?Ne.getCurrentTheme():"auto",locale:A&&"function"==typeof A.getCurrentLocale?A.getCurrentLocale():"zh-CN",globalPlugins:Ze.map(e=>e.name||"custom"),presetPlugins:Object.keys(ye||{})}}Ue.on("beforeCreate",e=>{e&&!e.isDestroyed()&&Ze.forEach(t=>{try{e.use(t)}catch(e){}})});try{"function"==typeof Ne.initTheme&&Ne.initTheme(),"function"==typeof A.initI18n&&A.initI18n()}catch(e){}const ot={VERSION:Ye,version:Ye,MarkdownEditor:Ue,Editor:Ue,create:Xe,use:Qe,on:Je,off:et,setTheme:tt,setLocale:nt,destroy:rt,getStatus:it,parseMarkdown:re,parseTokens:te,renderTokens:ne,safeUrl:Z,slugify:X,clearRenderCache:Y,registerBlockHandler:J,themes:Ne,i18n:A,animations:Ge,plugins:xe,presetPlugins:ye,topologicalSort:ve,validateConfig:be,createInstanceI18n:$,loadRemote:w,exportCSSVars:Me,getCSSVariable:$e,followExternalTheme:Re,adoptFromParent:De,createInstanceTheme:je,DEFAULTS:o,ICONS:n,THEMES:s,EDIT_MODES:l,DEFAULT_TOOLBAR:i,TOOLBAR_ACTIONS:c};"undefined"!=typeof window&&(window.MeEditor=ot),e.DEFAULTS=o,e.DEFAULT_TOOLBAR=i,e.EDIT_MODES=l,e.Editor=Ue,e.ICONS=n,e.MarkdownEditor=Ue,e.MeEditor=ot,e.THEMES=s,e.TOOLBAR_ACTIONS=c,e.VERSION=Ye,e.adoptFromParent=De,e.animationUtils=Ge,e.api=ot,e.clearRenderCache=Y,e.create=Xe,e.createInstanceI18n=$,e.createInstanceTheme=je,e.default=ot,e.destroy=rt,e.exportCSSVars=Me,e.followExternalTheme=Re,e.getCSSVariable=$e,e.getStatus=it,e.i18nUtils=A,e.loadRemote=w,e.meEditor=ot,e.off=et,e.on=Je,e.parseMarkdown=re,e.parseTokens=te,e.pluginUtils=xe,e.presetPlugins=ye,e.registerBlockHandler=J,e.renderTokens=ne,e.safeUrl=Z,e.setLocale=nt,e.setTheme=tt,e.slugify=X,e.themeUtils=Ne,e.topologicalSort=ve,e.use=Qe,e.validateConfig=be,Object.defineProperty(e,"__esModule",{value:!0})});
+!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).MeEditor={})}(this,function(e){"use strict";const t=e=>{const t=String(null==e?"":e);if("undefined"==typeof document)return t.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'");const n=document.createElement("div");return n.textContent=t,n.innerHTML},n={bold:'',italic:'',underline:'',strikethrough:'',h1:'',h2:'',h3:'',quote:'',code:'',link:'',image:'',table:'',ul:'',ol:'',indent:'',outdent:'',hr:'',undo:'',redo:'',preview:'',split:'',edit:'',fullscreen:'',theme:''},r={"zh-CN":{bold:"粗体",italic:"斜体",underline:"下划线",strikethrough:"删除线",h1:"标题1",h2:"标题2",h3:"标题3",quote:"引用",code:"代码",link:"链接",image:"图片",table:"表格",ul:"无序列表",ol:"有序列表",indent:"增加缩进",outdent:"减少缩进",hr:"分隔线",undo:"撤销",redo:"重做",edit:"编辑",split:"分屏",preview:"预览",fullscreen:"全屏",fullscreenExit:"退出全屏",theme:"主题",light:"亮色",dark:"暗色",auto:"自动",warm:"暖色",wordCount:"字数统计",characters:"字符",words:"词数",lines:"行数",readingTime:"阅读",minutes:"分钟",placeholder:"开始输入 Markdown...",empty:"暂无内容",copied:"已复制",copyContent:"复制内容",copyHTML:"复制 HTML",copySuccess:"复制成功",copyFailed:"复制失败",clearContent:"清空内容",clearConfirm:"确定要清空所有内容吗?",linkPlaceholder:"请输入链接地址",imagePlaceholder:"请输入图片地址",altPlaceholder:"请输入替代文本",tableRows:"行数",tableCols:"列数",confirm:"确认",cancel:"取消",exportMarkdown:"导出 Markdown",exportHTML:"导出 HTML",search:"搜索",replace:"替换",replaceAll:"全部替换",searchPlaceholder:"查找内容",replacePlaceholder:"替换为",findNext:"查找下一个",findPrev:"查找上一个",matchCase:"区分大小写",wholeWord:"全字匹配",close:"关闭",open:"打开",save:"保存",saved:"已保存",saving:"保存中...",delete:"删除",confirmDelete:"确定要删除吗?",unsavedChanges:"有未保存的更改",error:"错误",success:"成功",warning:"警告",info:"信息",loading:"加载中...",retry:"重试",renderError:"渲染失败",outline:"大纲",cut:"剪切",copy:"复制",paste:"粘贴",selectAll:"全选"},"en-US":{bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",h1:"Heading 1",h2:"Heading 2",h3:"Heading 3",quote:"Quote",code:"Code",link:"Link",image:"Image",table:"Table",ul:"Bullet List",ol:"Numbered List",indent:"Indent",outdent:"Outdent",hr:"Horizontal Rule",undo:"Undo",redo:"Redo",edit:"Edit",split:"Split",preview:"Preview",fullscreen:"Fullscreen",fullscreenExit:"Exit Fullscreen",theme:"Theme",light:"Light",dark:"Dark",auto:"Auto",warm:"Warm",wordCount:"Word Count",characters:"Characters",words:"Words",lines:"Lines",readingTime:"Reading",minutes:"min",placeholder:"Start typing Markdown...",empty:"No content",copied:"Copied",copyContent:"Copy Content",copyHTML:"Copy HTML",copySuccess:"Copied successfully",copyFailed:"Copy failed",clearContent:"Clear Content",clearConfirm:"Clear all content?",linkPlaceholder:"Enter link URL",imagePlaceholder:"Enter image URL",altPlaceholder:"Enter alt text",tableRows:"Rows",tableCols:"Columns",confirm:"Confirm",cancel:"Cancel",exportMarkdown:"Export Markdown",exportHTML:"Export HTML",search:"Search",replace:"Replace",replaceAll:"Replace All",searchPlaceholder:"Find",replacePlaceholder:"Replace with",findNext:"Find Next",findPrev:"Find Previous",matchCase:"Match Case",wholeWord:"Whole Word",close:"Close",open:"Open",save:"Save",saved:"Saved",saving:"Saving...",delete:"Delete",confirmDelete:"Are you sure you want to delete?",unsavedChanges:"You have unsaved changes",error:"Error",success:"Success",warning:"Warning",info:"Info",loading:"Loading...",retry:"Retry",renderError:"Render failed",outline:"Outline",cut:"Cut",copy:"Copy",paste:"Paste",selectAll:"Select All"},ja:{bold:"太字",italic:"斜体",underline:"下線",strikethrough:"打ち消し線",h1:"見出し1",h2:"見出し2",h3:"見出し3",quote:"引用",code:"コード",link:"リンク",image:"画像",table:"表",ul:"箇条書き",ol:"番号付きリスト",indent:"インデント",outdent:"インデント解除",hr:"水平線",undo:"元に戻す",redo:"やり直し",edit:"編集",split:"分割",preview:"プレビュー",fullscreen:"全画面",fullscreenExit:"全画面解除",theme:"テーマ",light:"ライト",dark:"ダーク",auto:"自動",warm:"ウォーム",wordCount:"文字数",characters:"文字",words:"単語",lines:"行",readingTime:"読了時間",minutes:"分",placeholder:"Markdownを入力...",empty:"内容なし",copied:"コピー済み",copyContent:"内容をコピー",copyHTML:"HTMLをコピー",copySuccess:"コピー成功",copyFailed:"コピー失敗",clearContent:"内容をクリア",clearConfirm:"すべての内容をクリアしますか?",linkPlaceholder:"リンクURLを入力",imagePlaceholder:"画像URLを入力",altPlaceholder:"代替テキストを入力",tableRows:"行",tableCols:"列",confirm:"確認",cancel:"キャンセル",exportMarkdown:"Markdownエクスポート",exportHTML:"HTMLエクスポート",search:"検索",replace:"置換",replaceAll:"すべて置換",searchPlaceholder:"検索",replacePlaceholder:"置換後",findNext:"次を検索",findPrev:"前を検索",matchCase:"大文字小文字",wholeWord:"単語単位",close:"閉じる",open:"開く",save:"保存",saved:"保存済み",saving:"保存中...",delete:"削除",confirmDelete:"削除してもよろしいですか?",unsavedChanges:"未保存の変更があります",error:"エラー",success:"成功",warning:"警告",info:"情報",loading:"読み込み中...",retry:"再試行",renderError:"レンダリング失敗",outline:"アウトライン",cut:"切り取り",copy:"コピー",paste:"貼り付け",selectAll:"すべて選択"},ko:{bold:"굵게",italic:"기울임",underline:"밑줄",strikethrough:"취소선",h1:"제목1",h2:"제목2",h3:"제목3",quote:"인용",code:"코드",link:"링크",image:"이미지",table:"표",ul:"순서 없는 목록",ol:"순서 있는 목록",indent:"들여쓰기",outdent:"내어쓰기",hr:"수평선",undo:"실행 취소",redo:"다시 실행",edit:"편집",split:"분할",preview:"미리보기",fullscreen:"전체 화면",fullscreenExit:"전체 화면 종료",theme:"테마",light:"라이트",dark:"다크",auto:"자동",warm:"웜",wordCount:"글자 수",characters:"글자",words:"단어",lines:"줄",readingTime:"읽기 시간",minutes:"분",placeholder:"Markdown 입력...",empty:"내용 없음",copied:"복사됨",copyContent:"내용 복사",copyHTML:"HTML 복사",copySuccess:"복사 성공",copyFailed:"복사 실패",clearContent:"내용 지우기",clearConfirm:"모든 내용을 지우시겠습니까?",linkPlaceholder:"링크 URL 입력",imagePlaceholder:"이미지 URL 입력",altPlaceholder:"대체 텍스트 입력",tableRows:"행",tableCols:"열",confirm:"확인",cancel:"취소",exportMarkdown:"Markdown 내보내기",exportHTML:"HTML 내보내기",search:"검색",replace:"바꾸기",replaceAll:"모두 바꾸기",searchPlaceholder:"찾기",replacePlaceholder:"바꿀 내용",findNext:"다음 찾기",findPrev:"이전 찾기",matchCase:"대소문자 구분",wholeWord:"단어 단위",close:"닫기",open:"열기",save:"저장",saved:"저장됨",saving:"저장 중...",delete:"삭제",confirmDelete:"삭제하시겠습니까?",unsavedChanges:"저장되지 않은 변경 사항이 있습니다",error:"오류",success:"성공",warning:"경고",info:"정보",loading:"로딩 중...",retry:"재시도",renderError:"렌더링 실패",outline:"개요",cut:"잘라내기",copy:"복사",paste:"붙여넣기",selectAll:"전체 선택"},fr:{bold:"Gras",italic:"Italique",underline:"Souligné",strikethrough:"Barré",h1:"Titre 1",h2:"Titre 2",h3:"Titre 3",quote:"Citation",code:"Code",link:"Lien",image:"Image",table:"Tableau",ul:"Liste à puces",ol:"Liste numérotée",indent:"Indenter",outdent:"Désindenter",hr:"Ligne horizontale",undo:"Annuler",redo:"Rétablir",edit:"Éditer",split:"Fractionné",preview:"Aperçu",fullscreen:"Plein écran",fullscreenExit:"Quitter plein écran",theme:"Thème",light:"Clair",dark:"Sombre",auto:"Auto",warm:"Chaud",wordCount:"Nombre de mots",characters:"Caractères",words:"Mots",lines:"Lignes",readingTime:"Lecture",minutes:"min",placeholder:"Commencez à taper Markdown...",empty:"Aucun contenu",copied:"Copié",copyContent:"Copier le contenu",copyHTML:"Copier HTML",copySuccess:"Copié avec succès",copyFailed:"Échec de la copie",clearContent:"Effacer le contenu",clearConfirm:"Effacer tout le contenu ?",linkPlaceholder:"Entrez l'URL du lien",imagePlaceholder:"Entrez l'URL de l'image",altPlaceholder:"Entrez le texte alternatif",tableRows:"Lignes",tableCols:"Colonnes",confirm:"Confirmer",cancel:"Annuler",exportMarkdown:"Exporter Markdown",exportHTML:"Exporter HTML",search:"Rechercher",replace:"Remplacer",replaceAll:"Tout remplacer",searchPlaceholder:"Rechercher",replacePlaceholder:"Remplacer par",findNext:"Suivant",findPrev:"Précédent",matchCase:"Respecter la casse",wholeWord:"Mot entier",close:"Fermer",open:"Ouvrir",save:"Enregistrer",saved:"Enregistré",saving:"Enregistrement...",delete:"Supprimer",confirmDelete:"Confirmer la suppression ?",unsavedChanges:"Modifications non enregistrées",error:"Erreur",success:"Succès",warning:"Avertissement",info:"Info",loading:"Chargement...",retry:"Réessayer",renderError:"Échec du rendu",outline:"Plan",cut:"Couper",copy:"Copier",paste:"Coller",selectAll:"Tout sélectionner"},de:{bold:"Fett",italic:"Kursiv",underline:"Unterstrichen",strikethrough:"Durchgestrichen",h1:"Überschrift 1",h2:"Überschrift 2",h3:"Überschrift 3",quote:"Zitat",code:"Code",link:"Link",image:"Bild",table:"Tabelle",ul:"Aufzählung",ol:"Nummerierte Liste",indent:"Einrücken",outdent:"Ausrücken",hr:"Trennlinie",undo:"Rückgängig",redo:"Wiederholen",edit:"Bearbeiten",split:"Geteilt",preview:"Vorschau",fullscreen:"Vollbild",fullscreenExit:"Vollbild beenden",theme:"Design",light:"Hell",dark:"Dunkel",auto:"Auto",warm:"Warm",wordCount:"Wörter",characters:"Zeichen",words:"Wörter",lines:"Zeilen",readingTime:"Lesezeit",minutes:"min",placeholder:"Markdown eingeben...",empty:"Kein Inhalt",copied:"Kopiert",copyContent:"Inhalt kopieren",copyHTML:"HTML kopieren",copySuccess:"Erfolgreich kopiert",copyFailed:"Kopieren fehlgeschlagen",clearContent:"Inhalt löschen",clearConfirm:"Gesamten Inhalt löschen?",linkPlaceholder:"Link-URL eingeben",imagePlaceholder:"Bild-URL eingeben",altPlaceholder:"Alternativtext eingeben",tableRows:"Zeilen",tableCols:"Spalten",confirm:"Bestätigen",cancel:"Abbrechen",exportMarkdown:"Markdown exportieren",exportHTML:"HTML exportieren",search:"Suchen",replace:"Ersetzen",replaceAll:"Alle ersetzen",searchPlaceholder:"Suchen",replacePlaceholder:"Ersetzen mit",findNext:"Nächstes",findPrev:"Vorheriges",matchCase:"Groß-/Kleinschreibung",wholeWord:"Ganzes Wort",close:"Schließen",open:"Öffnen",save:"Speichern",saved:"Gespeichert",saving:"Speichern...",delete:"Löschen",confirmDelete:"Wirklich löschen?",unsavedChanges:"Ungespeicherte Änderungen",error:"Fehler",success:"Erfolg",warning:"Warnung",info:"Info",loading:"Laden...",retry:"Wiederholen",renderError:"Rendern fehlgeschlagen",outline:"Gliederung",cut:"Ausschneiden",copy:"Kopieren",paste:"Einfügen",selectAll:"Alles auswählen"}},i=["bold","italic","strikethrough","code","|","h1","h2","h3","|","quote","ul","ol","|","link","image","table","hr","|","undo","redo","|","edit","split","preview","fullscreen"],o=Object.freeze({value:"",placeholder:"",mode:"split",height:400,toolbar:i,wordCount:!0,autofocus:!1,spellcheck:!1,historyLimit:100,historyDebounce:400,syncScroll:!0,tabSize:2,readOnly:!1,lineNumbers:!0,outline:!1,autoBrackets:!0,zenMode:!1,wordWrap:!0,maxLength:0,theme:"auto",locale:"zh-CN",render:null,highlight:null,sanitize:null,className:"",style:{},plugins:[],onChange:null,onInput:null,onFocus:null,onBlur:null,onSave:null,onModeChange:null,onFullscreen:null,onCreate:null,onDestroy:null,onLinkClick:null,floatingToolbar:!0}),s={light:{bg:"rgba(255, 255, 255, 0.96)",text:"#1f2937",border:"rgba(0, 0, 0, 0.08)",shadow:"0 10px 36px -10px rgba(0, 0, 0, 0.18), 0 4px 14px -4px rgba(0, 0, 0, 0.08)",hoverShadow:"0 14px 48px -10px rgba(0, 0, 0, 0.22), 0 6px 18px -4px rgba(0, 0, 0, 0.10)",toolbarBg:"rgba(248, 249, 250, 0.92)",textareaBg:"#ffffff",previewBg:"#ffffff",codeBg:"rgba(243, 244, 246, 1)",codeText:"#1f2937",accent:"#3b82f6",muted:"#6b7280"},dark:{bg:"rgba(28, 32, 40, 0.94)",text:"#e6e8eb",border:"rgba(255, 255, 255, 0.1)",shadow:"0 10px 36px -10px rgba(0, 0, 0, 0.6), 0 4px 14px -4px rgba(0, 0, 0, 0.4)",hoverShadow:"0 14px 48px -8px rgba(0, 0, 0, 0.6), 0 6px 18px -4px rgba(0, 0, 0, 0.4)",toolbarBg:"rgba(22, 26, 33, 0.92)",textareaBg:"#1c2028",previewBg:"#1c2028",codeBg:"rgba(15, 18, 24, 1)",codeText:"#e6e8eb",accent:"#60a5fa",muted:"#9ca3af"},auto:"auto",warm:{bg:"rgba(255, 251, 235, 0.96)",text:"#78350f",border:"rgba(245, 158, 11, 0.2)",shadow:"0 10px 36px -10px rgba(245, 158, 11, 0.18), 0 4px 14px -4px rgba(245, 158, 11, 0.08)",hoverShadow:"0 14px 48px -10px rgba(245, 158, 11, 0.22), 0 6px 18px -4px rgba(245, 158, 11, 0.10)",toolbarBg:"rgba(254, 243, 199, 0.92)",textareaBg:"#fffbeb",previewBg:"#fffbeb",codeBg:"rgba(254, 215, 170, 0.6)",codeText:"#78350f",accent:"#d97706",muted:"#a16207",progressBg:"rgba(217, 119, 6, 0.15)",closeHoverBg:"rgba(217, 119, 6, 0.2)"}},a={slide:{enter:{transform:"translateX(80px)",opacity:"0"},leave:{transform:"translateX(120%)",opacity:"0"},duration:400,easing:"cubic-bezier(0.25, 0.46, 0.45, 0.94)"},fade:{enter:{opacity:"0",filter:"blur(3px)"},leave:{opacity:"0",filter:"blur(3px)"},duration:500,easing:"ease"},scale:{enter:{transform:"scale(0.55)",opacity:"0"},leave:{transform:"scale(0.55)",opacity:"0"},duration:450,easing:"cubic-bezier(0.34, 1.56, 0.64, 1)"},bounce:{enter:{transform:"translateY(-80px)",opacity:"0"},leave:{transform:"translateY(20px)",opacity:"0"},duration:650,easing:"ease"},flip:{enter:{transform:"perspective(500px) rotateX(-90deg)",opacity:"0"},leave:{transform:"perspective(500px) rotateX(90deg)",opacity:"0"},duration:500,easing:"cubic-bezier(0.25, 0.46, 0.45, 0.94)"},rotate:{enter:{transform:"rotate(-25deg) scale(0.6)",opacity:"0"},leave:{transform:"rotate(25deg) scale(0.6)",opacity:"0"},duration:500,easing:"cubic-bezier(0.25, 0.46, 0.45, 0.94)"},zoom:{enter:{transform:"scale(0.1)",opacity:"0"},leave:{transform:"scale(0.1)",opacity:"0"},duration:500,easing:"cubic-bezier(0.34, 1.56, 0.64, 1)"}},l=["edit","split","preview"],c=["bold","italic","strikethrough","underline","code","h1","h2","h3","quote","ul","ol","indent","outdent","hr","link","image","table","undo","redo","edit","split","preview","fullscreen"];let d=null,h="zh-CN",u=new Set,p="zh-CN";const m={zh:()=>"other",en:e=>1===e?"one":"other",ru:e=>{const t=e%10,n=e%100;return 1===t&&11!==n?"one":t>=2&&t<=4&&!(n>=12&&n<=14)?"few":0===t||t>=5&&t<=9||n>=11&&n<=14?"many":"other"}},g=(e,t)=>{const n=e.split("-")[0].toLowerCase();return(m[n]||m.en)(Math.abs(t))},f=()=>h,v=e=>{let t=e;r[t]||(t=p),h=t,T(t),S(t)},b=(e,t={},n)=>{const r=n||h;let i=y(r,e);if(i&&"object"==typeof i&&void 0!==t.count&&(i=i[g(r,t.count)]||i.other||e),"string"==typeof i)return x(i,t);if(r!==p){let n=y(p,e);if(n&&"object"==typeof n&&void 0!==t.count&&(n=n[g(p,t.count)]||n.other),"string"==typeof n)return x(n,t)}return e},y=(e,t)=>{const n=r[e];if(!n)return;const i=t.split(".");let o=n;for(const e of i){if(!o||"object"!=typeof o||!(e in o))return;o=o[e]}return o},x=(e,t)=>e.replace(/\{(\w+)\}/g,(e,n)=>void 0!==t[n]?String(t[n]):e),_=(e,t)=>{r[e]||(r[e]={}),k(r[e],t)},w=async(e,t)=>{try{const n=await fetch(e);if(!n.ok)throw new Error(`HTTP ${n.status}`);const r=await n.json();return _(t,r),!0}catch(e){return!1}},k=(e,t)=>{for(const n in t)t[n]instanceof Object&&n in e&&e[n]instanceof Object&&!Array.isArray(t[n])?k(e[n],t[n]):e[n]=t[n];return e},E=e=>e in r,C=e=>{const t=e.split("-")[0].toLowerCase();return["ar","he","fa","ur","yi","ps","sd","ug","dv","ku","syr"].includes(t)?"rtl":"ltr"},T=e=>{u.forEach(t=>{try{t(e)}catch(e){}})},S=e=>{if("undefined"!=typeof localStorage)try{localStorage.setItem("metona-editor-locale",e)}catch(e){}},L=()=>{if("undefined"!=typeof localStorage)try{return localStorage.getItem("metona-editor-locale")||M()}catch(e){}return M()},M=()=>{if("undefined"!=typeof navigator){const e=navigator.language||navigator.userLanguage;if(e&&E(e))return e;const t=e?.split("-")[0];if(t&&E(t))return t}return p},$=e=>{let t=e.config?.locale||h||"zh-CN";const n=(e,n={})=>b(e,n,t);return{set:r=>r&&t!==r?(t=r,e.el&&(e.el.setAttribute("lang",r),e.el.setAttribute("dir",C(r))),e.textarea&&(e.textarea.placeholder=n("placeholder")||"",e.textarea.setAttribute("aria-label",n("edit")||""),e.textarea.setAttribute("dir",C(r))),"function"==typeof e._emit&&e._emit("localeChange",{locale:r,direction:C(r)}),e.toolbarEl&&e.toolbarEl.querySelectorAll(".me-btn").forEach(e=>{const t=e.dataset.action||e.dataset.mode;if(t){const r=n(t);r&&r!==t&&(e.title=r,e.setAttribute("aria-label",r))}}),t):t,get:()=>t,getDirection:()=>C(t),t:n,formatNumber:(e,n)=>{try{return new Intl.NumberFormat(t,n).format(e)}catch(t){return String(e)}},formatDate:(e,n)=>{try{return new Intl.DateTimeFormat(t,n).format(e instanceof Date?e:new Date(e))}catch(t){return String(e)}}}};r["zh-CN"],r["en-US"],r.ja,r.ko,r.fr,r.de;const A={t:b,getCurrentLocale:f,setCurrentLocale:v,switchLocale:e=>{v(e)},getFallbackLocale:()=>p,setFallbackLocale:e=>{p=e},hasTranslation:e=>void 0!==y(h,e)||void 0!==y(p,e),getTranslations:e=>r[e]||{},addTranslations:_,loadRemote:w,getSupportedLocales:()=>Object.keys(r),isLocaleSupported:E,getLocaleName:e=>({"zh-CN":"简体中文","zh-TW":"繁體中文","en-US":"English (US)","en-GB":"English (UK)",ja:"日本語",ko:"한국어",fr:"Français",de:"Deutsch",es:"Español",pt:"Português",ru:"Русский",ar:"العربية",hi:"हिन्दी",th:"ไทย",vi:"Tiếng Việt",id:"Bahasa Indonesia",tr:"Türkçe",it:"Italiano",nl:"Nederlands",pl:"Polski"}[e]||e),getLocaleDirection:C,formatNumber:(e,t={})=>{try{return new Intl.NumberFormat(h,t).format(e)}catch(t){return String(e)}},formatCurrency:(e,t="USD",n={})=>{try{return new Intl.NumberFormat(h,{style:"currency",currency:t,...n}).format(e)}catch(t){return String(e)}},formatDate:(e,t={})=>{try{const n=e instanceof Date?e:new Date(e);return new Intl.DateTimeFormat(h,t).format(n)}catch(t){return String(e)}},addLocaleListener:e=>(u.add(e),()=>{u.delete(e)}),removeLocaleListener:e=>{u.delete(e)},clearLocaleListeners:()=>{u.clear()},initI18n:()=>{const e=L();v(e)},saveLocale:S,loadLocale:L,getDefaultLocale:M,createInstanceI18n:$},z=/^\s*$/,I=/^(#{1,6})\s+(.+?)(?:\s+#{1,6})?\s*$/,H=/^={3,}\s*$/,B=/^-{3,}\s*$/,P=/^(\s{0,3})(`{3,}|~{3,})\s*([\w+#.-]*)(\s+[^\n]*?)?\s*$/,R=/^\s{0,3}([-*_])(\s*\1){2,}\s*$/,D=/^\s{0,3}>\s?/,F=/^(\s*)([-*+])\s/,j=/^(\s*)(\d+)\.\s/,O=/^\[([ xX])\]\s+(.*)$/,N=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/,W=/^( {4}|\t)/,q=/^:\s+/,V=/^\[\^([^\]]+)\]:\s*/,U={smile:"😊",grinning:"😀",joy:"😂",rofl:"🤣",wink:"😉",blush:"😊",innocent:"😇",heart_eyes:"😍",kissing_heart:"😘",yum:"😋",stuck_out_tongue:"😛",sunglasses:"😎",smirk:"😏",unamused:"😒",disappointed:"😞",worried:"😟",confused:"😕",cry:"😢",sob:"😭",scream:"😱",angry:"😠",rage:"💢",triumph:"😤",sleepy:"😪",dizzy_face:"😵",zipper_mouth:"🤐",nerd:"🤓",thinking:"🤔",rolling_eyes:"🙄",expressionless:"😑",thumbsup:"👍",thumbsdown:"👎",clap:"👏",pray:"🙏",muscle:"💪",ok:"👌",point_up:"👆",point_down:"👇",point_left:"👈",point_right:"👉",raised_hands:"🙌",wave:"👋",punch:"👊",crossed_fingers:"🤞",heart:"❤️",broken_heart:"💔",star:"⭐",star2:"🌟",fire:"🔥",rocket:"🚀",check:"✅",cross:"❌",warning:"⚠️",info:"ℹ️",question:"❓",exclamation:"❗",bangbang:"‼️",grey_exclamation:"❕",bulb:"💡",book:"📖",memo:"📝",pin:"📌",link:"🔗",lock:"🔒",unlock:"🔓",key:"🔑",hammer:"🔨",wrench:"🔧",gear:"⚙️",tools:"🛠️",magnet:"🧲",zap:"⚡",cloud:"☁️",sun:"☀️",moon:"🌙",rain:"🌧️",snow:"❄️",umbrella:"☂️",rainbow:"🌈",tornado:"🌪️",fog:"🌫️",droplet:"💧",coffee:"☕",pizza:"🍕",cake:"🎂",beer:"🍺",wine:"🍷",hamburger:"🍔",fries:"🍟",apple:"🍎",banana:"🍌",grapes:"🍇",watermelon:"🍉",strawberry:"🍓",peach:"🍑",cherry:"🍒",taco:"🌮",tada:"🎉",gift:"🎁",crown:"👑",gem:"💎",ring:"💍",confetti:"🎊",balloon:"🎈",ribbon:"🎀",medal:"🏅",trophy:"🏆",eye:"👁️",ear:"👂",nose:"👃",tongue:"👅",lips:"👄",brain:"🧠",speech:"💬",thought:"💭",anger:"💢",sweat:"💦",one:"1️⃣",two:"2️⃣",three:"3️⃣",four:"4️⃣",five:"5️⃣",six:"6️⃣",seven:"7️⃣",eight:"8️⃣",nine:"9️⃣",zero:"0️⃣",arrow_up:"⬆️",arrow_down:"⬇️",arrow_left:"⬅️",arrow_right:"➡️",arrow_upper_right:"↗️",arrow_lower_right:"↘️",arrow_lower_left:"↙️",arrow_upper_left:"↖️",computer:"💻",phone:"📱",battery:"🔋",electric_plug:"🔌",copyright:"©️",registered:"®️",tm:"™️",hundred:"💯",boom:"💥",dash:"💨",hole:"🕳️",bomb:"💣",email:"📧",phone2:"📞",clock:"🕐",hourglass:"⏳",calendar:"📅",money:"💰",shopping:"🛒",package:"📦",mailbox:"📫",art:"🎨",music:"🎵",movie:"🎬",game:"🎮",sport:"⚽",earth:"🌍",house:"🏠",car:"🚗",airplane:"✈️",ship:"🚢"},K=new Map,G=(e,t)=>{if(!e)return"";if(!t.highlight&&e.length<600){const n=K.get(e);if(void 0!==n)return n;const r=he(e,t);if(K.size>=300){const e=K.keys().next().value;K.delete(e)}return K.set(e,r),r}return he(e,t)},Y=()=>{K.clear()},Z=e=>{if(!e)return"";const t=String(e).trim();if(/^(javascript|vbscript|file):/i.test(t))return"";if(/^data:/i.test(t)){if(!/^data:image\//i.test(t))return"";if(t.length>5e5)return""}return t},X=e=>String(e).normalize("NFKC").toLowerCase().replace(/[^\w\u4e00-\u9fff\u3400-\u4dbf\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"heading",Q=[],J=e=>{Q.push(e),Q.sort((e,t)=>e.priority-t.priority)},ee=e=>!!(z.test(e)||P.test(e)||I.test(e)||R.test(e)||D.test(e)||F.test(e)||j.test(e)||V.test(e)||q.test(e)||/^\$\$/.test(e));J({name:"refDef",priority:.1,test:e=>{if(/^\[\^/.test(e))return null;return e.match(/^\[([^\]]+)\]:\s*(?:<(\S+)>|(\S+))(?:\s+['"\(](.*?)['"\)])?\s*$/)||null},parse:(e,t,n,r,i,o)=>{const s=n[1].toLowerCase(),a=n[2]||n[3]||"",l=n[4]||"";return a&&o&&(o[s]=JSON.stringify({url:a,title:l})),{token:null,newIndex:t+1}}}),J({name:"blank",priority:0,test:e=>!!z.test(e)||null,parse:(e,t)=>({token:null,newIndex:t+1})}),J({name:"fencedCode",priority:1,test:e=>{const t=e.match(P);return t?(t[4]||"").includes("`")?null:t:null},parse:(e,t,n)=>{const r=n[2][0],i=n[2].length,o=n[3]||"",s=(n[4]||"").trim(),a=s?s.split(/\s+/).filter(Boolean):[],l={};for(let e=0;e=i)break;c.push(e[d]),d++}return dW.test(e)&&!(I.test(e)||D.test(e)||F.test(e)||j.test(e))||null,parse:(e,t)=>{const n=[];for(;te.match(I),parse:(e,t,n)=>({token:{type:"heading",level:n[1].length,text:n[2]},newIndex:t+1})}),J({name:"setextH1",priority:4,test:(e,t,n)=>n+1>=t.length?null:H.test(t[n+1])&&!(z.test(e)||F.test(e)||j.test(e)||D.test(e)||/^\s*`{3,}/.test(e))||null,parse:(e,t)=>({token:{type:"heading",level:1,text:e[t]},newIndex:t+2})}),J({name:"setextH2",priority:5,test:(e,t,n)=>n+1>=t.length?null:B.test(t[n+1])&&!(z.test(e)||F.test(e)||j.test(e)||D.test(e)||/^\s*`{3,}/.test(e))||null,parse:(e,t)=>({token:{type:"heading",level:2,text:e[t]},newIndex:t+2})}),J({name:"hr",priority:6,test:e=>!!R.test(e)||null,parse:(e,t)=>({token:{type:"hr"},newIndex:t+1})}),J({name:"blockquote",priority:7,test:e=>!!D.test(e)||null,parse:(e,t)=>{const n=[];for(;t!/\|/.test(e)||n+1>=t.length?null:oe(t[n+1])?{header:e,align:se(t[n+1])}:null,parse:(e,t,n)=>{let r=t+2;const i=[];for(;re.match(F),parse:(e,t,n)=>{const{items:r,endIdx:i}=ie(e,t,n[2],n[1].length,!1);return{token:{type:"ul",items:r},newIndex:i}}}),J({name:"ol",priority:10,test:e=>e.match(j),parse:(e,t,n)=>{const r=parseInt(n[2],10),{items:i,endIdx:o}=ie(e,t,n[2],n[1].length,!0);return{token:{type:"ol",items:i,start:r},newIndex:o}}}),J({name:"footnoteDef",priority:11,test:e=>e.match(V),parse:(e,t,n,r,i)=>{const o=n[1],s=[e[t].slice(n[0].length)];let a=t+1;for(;a!!q.test(e)||null,parse:(e,t,n,r)=>{const i=r.length>0&&"paragraph"===r[r.length-1].type?r.pop().text:"",o=[e[t].replace(q,"")];let s=t+1;for(;s!!/^\$\$/.test(e)||null,parse:(e,t)=>{const n=e[t].match(/^\$\$([\s\S]+?)\$\$\s*$/);if(n)return{token:{type:"mathBlock",content:n[1]},newIndex:t+1};const r=[e[t].replace(/^\$\$/,"")];let i=t+1;for(;i{if(null==e)return{tokens:[],footnotes:{},refs:{}};const t=String(e).replace(/\r\n?/g,"\n").split("\n"),n=[],r={},i={};let o=0;for(;o{let r=e.map(e=>ae(e,t)).join("\n");const i=Object.keys(n);return i.length&&(r+='\n"),r},re=(e,t={})=>{const{tokens:n,footnotes:r,refs:i}=te(e);return ne(n,{...t,refs:i},r)},ie=(e,t,n,r,i,o)=>{const s=[];let a=t;const l=r+(i?String(n).length+2:2);for(;al&&" "!==n[l])&&new RegExp(`^\\s{${l},}`).test(n)){p.push(""),a++;continue}}break}if(i){if(new RegExp(`^(\\s{0,${r}})\\d+\\.\\s`).test(t))break}else if(new RegExp(`^(\\s{0,${r}})[-*+]\\s`).test(t))break;if(D.test(t)||I.test(t)||R.test(t)||V.test(t))break;const n=t.match(new RegExp(`^(\\s{${l},})([-*+])\\s`)),o=t.match(new RegExp(`^(\\s{${l},})(\\d+)\\.\\s`));if(n||o){const t=!!o,r=t?o[2]:n[2],i=t?o[1].length:n[1].length,s=t?parseInt(o[2],10):void 0,l=ie(e,a,r,i,t);m.push({type:t?"ol":"ul",items:l.items,start:s}),a=l.endIdx;continue}t.length>l&&""===t.slice(0,l).trim()?p.push(t.slice(l)):p.push(t),a++}p.length&&(d=d?d+"\n"+p.join("\n"):p.join("\n")),s.push({type:"listItem",text:d,checked:h,task:u,subTokens:m.length?m:void 0})}return{items:s,endIdx:a}},oe=e=>N.test(e)&&/-/.test(e),se=e=>e.replace(/^\s*\|?\s*|\s*\|?\s*$/g,"").split(/\s*\|\s*/).map(e=>/^:/.test(e)&&/:$/.test(e)?"center":/:$/.test(e)?"right":(/^:/.test(e),"left")),ae=(e,n,r)=>{switch(e.type){case"heading":{const t=X(e.text);return`${G(e.text,n)}`}case"paragraph":return`${G(e.text,n)}
`;case"hr":return"
";case"quote":return`${re(e.content,n)}
`;case"code":return ce(e.content,e.lang,n,e.attrs);case"ul":return`${e.items.map(e=>le(e,n)).join("")}
`;case"ol":{const t=e.start||1;return`1?` start="${t}"`:""}>${e.items.map((e,r)=>le(e,n,t>1?r+t:void 0)).join("")}
`}case"table":return de(e,n);case"defList":{let t="";return t+=`- ${G(e.term,n)}
`,e.defs.forEach(e=>{t+=`- ${G(e,n)}
`}),t+"
"}case"mathBlock":return`${t(e.content)}
`;default:return`${e.content?"string"==typeof e.content?G(e.content,n):t(String(e.content)):""}
`}},le=(e,t,n)=>{if(e.task){let n=` ${G(e.text,t)}`;return e.subTokens&&(n+="\n"+e.subTokens.map(e=>ae(e,t)).join("\n")),n+""}let r=null!=n?``:"";return r+=G(e.text,t),e.subTokens&&(r+="\n"+e.subTokens.map(e=>ae(e,t)).join("\n")),r+""},ce=(e,n,r,i)=>{if("mermaid"===n)return``;const o=n?` class="language-${t(n)}"`:"",s=i?.title?`${t(i.title)}
`:"";if(r.highlight&&"function"==typeof r.highlight&&n)try{const t=r.highlight(e,n);if("string"==typeof t)return`${s}${t}
`}catch(e){}return`${s}${t(e)}
`},de=(e,t)=>{const n=e=>{const t=[];let n="",r=!1;for(let i=0;i0&&""===t[0]&&t.shift(),t.length>0&&""===t[t.length-1]&&t.pop(),t},r=n(e.header),i=e.align||[],o=e=>i[e]&&"left"!==i[e]?` style="text-align:${i[e]}"`:"";let s='';return s+=r.map((e,n)=>`| ${G(e,t)} | `).join(""),s+="
",s+=e.rows.map(e=>`${n(e).map((e,n)=>`| ${G(e,t)} | `).join("")}
`).join(""),s+"
"},he=(e,n)=>{if(!e)return"";const r=[];let i=ue(e,r);const o=[];return i=i.replace(/&(?:[a-zA-Z][a-zA-Z0-9]{1,31}|#\d{1,7}|#x[0-9a-fA-F]{1,6});/g,e=>(o.push(e),`${o.length-1}`)),i=i.replace(//g,e=>(o.push(e),`${o.length-1}`)),i=t(i),i=i.replace(/\u0005(\d+)\u0005/g,(e,t)=>o[+t]||e),i=me(i,r,n),i=i.replace(/\u0000(\d+)\u0000/g,(e,n)=>{const i=r[+n];return i?`${t(i.content)}`:e}),i=i.replace(/:([\w+-]+):/g,(e,t)=>U[t]||e),i=i.replace(/ \n/g,"
\n"),i=i.replace(/\n/g,"
"),i},ue=(e,t)=>{let n="",r=0;for(;r{const i=new Map;return e=(e=e.replace(/\u0000\d+\u0000/g,e=>{const t=`${i.size}`;return i.set(t,e),t})).replace(pe,e=>{const n=e;if(n.startsWith("***"))return`${n.slice(3,-3)}`;if(n.startsWith("___"))return`${n.slice(3,-3)}`;if(n.startsWith("){const e=n.match(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+['"](.+?)['"])?\s*\)/);if(!e)return n;const r=Z(e[2]);if(!r)return t(n);const i=e[3]?` title="${e[3]}"`:"";return`
`}if(n.startsWith("![")&&n.includes("][")){const e=n.match(/!\[([^\]]*)\]\[([^\]]*)\]/);if(!e)return n;const i=(e[2]||e[1]).toLowerCase();if(r.refs&&r.refs[i])try{const o=JSON.parse(r.refs[i]),s=Z(o.url);if(!s)return t(n);const a=o.title?` title="${o.title}"`:"";return`
`}catch(t){return`
`}return`
`}if(n.startsWith("[")&&n.includes("](")){const e=n.match(/\[([^\]]+)\]\(([^)\s]+)(?:\s+['"](.+?)['"])?\s*\)/);if(!e)return n;const t=Z(e[2]);return t?`${he(e[1],r)}`:n}if(n.startsWith("[")&&n.includes("][")){const e=n.match(/\[([^\]]+)\]\[([^\]]*)\]/);if(!e)return n;const i=(e[2]||e[1]).toLowerCase();if(r.refs&&r.refs[i])try{const o=JSON.parse(r.refs[i]),s=Z(o.url);return s?`${e[1]}`:t(n)}catch(e){return t(n)}return t(n)}if(n.startsWith("<http")){const e=n.slice(4,-4);return`${e}`}if(n.startsWith("**"))return`${n.slice(2,-2)}`;if(n.startsWith("__"))return`${n.slice(2,-2)}`;if(n.startsWith("~~"))return`${n.slice(2,-2)}`;if(n.startsWith("=="))return`${n.slice(2,-2)}`;if(n.startsWith("*")&&!n.startsWith("**")&&!n.startsWith("***"))return`${n.slice(1,-1)}`;if(n.startsWith("_")&&!n.startsWith("__")&&!n.startsWith("___"))return`${n.slice(1,-1)}`;if(n.startsWith("^")&&!n.startsWith("^^"))return`${n.slice(1,-1)}`;if(n.startsWith("~")&&!n.startsWith("~~"))return`${n.slice(1,-1)}`;if(n.startsWith("$")&&!n.startsWith("$$"))return`${t(n.slice(1,-1))}`;if(/^\[\^/.test(n)){const e=n.slice(2,-1);return``}if(n.startsWith("\\")&&2===n.length){const e=n[1];return/[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]/.test(e)?e:n}return n}),e.replace(/\u0003(\d+)\u0003/g,e=>i.get(e)||e)};class ge{constructor(){this.plugins=new Map}register(e,t){return this.plugins.has(e)?this:t&&"object"==typeof t&&(t.name||e)?(this.plugins.set(e,{version:t.version||"0.0.0",description:t.description||"",depends:t.depends||[],priority:t.priority||0,...t,name:e,enabled:!0}),this):this}unregister(e){return this.plugins.delete(e),this}get(e){return this.plugins.get(e)||null}has(e){return this.plugins.has(e)}getAll(){return Array.from(this.plugins.values())}getNames(){return Array.from(this.plugins.keys())}enable(e){const t=this.plugins.get(e);return t&&(t.enabled=!0),this}disable(e){const t=this.plugins.get(e);return t&&(t.enabled=!1),this}isEnabled(e){const t=this.plugins.get(e);return!!t&&t.enabled}destroy(){this.plugins.clear()}}const fe=new ge,ve=e=>{const t=new Map;e.forEach(e=>t.set(e.name,e));const n=new Map,r=new Map;e.forEach(e=>{n.set(e.name,0),r.set(e.name,[])}),e.forEach(e=>{(e.depends||[]).forEach(i=>{t.has(i)&&(r.get(i).push(e.name),n.set(e.name,(n.get(e.name)||0)+1))})});const i=[];n.forEach((e,t)=>{0===e&&i.push(t)});const o=[];for(;i.length;){i.sort((e,n)=>(t.get(n).priority||0)-(t.get(e).priority||0));const e=i.shift();o.push(t.get(e)),(r.get(e)||[]).forEach(e=>{n.set(e,n.get(e)-1),0===n.get(e)&&i.push(e)})}return o.length!==e.length?e:o},be=(e={},t={})=>{const n=[],r={...t};for(const[i,o]of Object.entries(e)){const e=t[i];if(o.required&&null==e)n.push(`"${i}" is required`);else if(void 0!==e||void 0===o.default){if(void 0!==e&&o.type){const t=Array.isArray(e)?"array":typeof e;t!==o.type&&n.push(`"${i}" expected ${o.type}, got ${t}`)}if(void 0!==e&&o.enum&&!o.enum.includes(e)&&n.push(`"${i}" must be one of [${o.enum.join(", ")}]`),void 0!==e&&"function"==typeof o.validator)try{const t=o.validator(e);!0!==t&&n.push(`"${i}": ${t}`)}catch(e){n.push(`"${i}": ${e.message}`)}}else r[i]=o.default}return{valid:0===n.length,errors:n,patched:r}},ye={autoSave:{name:"autoSave",version:"0.1.1",description:"Auto-save to localStorage",priority:100,install(e,t){if(!e||"function"!=typeof e.getValue)return;const n=t||this,r=n.key||"me-draft-"+(e.id||""),i=n.delay||1e3,o={_timer:null},s=()=>{o._timer&&(clearTimeout(o._timer),o._timer=null);try{localStorage.setItem(r,e.getValue()),"function"==typeof e._emit&&e._emit("autosave",{key:r,value:e.getValue()})}catch(e){}},a=()=>{o._timer&&clearTimeout(o._timer),o._timer=setTimeout(s,i)},l=s,c=s;e.on("change",a),e.on("blur",l),e.on("save",c),e.restoreDraft=()=>{try{const t=localStorage.getItem(r);return null!=t&&e.setValue(t),t}catch(e){return null}},e.clearDraft=()=>{try{localStorage.removeItem(r)}catch(e){}return e},e.getDraftKey=()=>r,e.__autoSaveCleanup={state:o,_onInput:a,_onBlur:l,_onSave:c,save:s}},destroy(e){const t=e.__autoSaveCleanup;t&&(t.state._timer&&(clearTimeout(t.state._timer),t.state._timer=null),e&&"function"==typeof e.off&&(t._onInput&&e.off("change",t._onInput),t._onBlur&&e.off("blur",t._onBlur),t._onSave&&e.off("save",t._onSave)),delete e.__autoSaveCleanup)}},exportTool:{name:"exportTool",version:"0.1.0",description:"Export Markdown/HTML",priority:50,install(e){if(!e||"function"!=typeof e.getValue)return;const t=(e,t,n)=>{if("undefined"==typeof document)return;const r=new Blob([t],{type:n+";charset=utf-8"}),i=URL.createObjectURL(r),o=document.createElement("a");o.href=i,o.download=e,document.body.appendChild(o),o.click(),document.body.removeChild(o),setTimeout(()=>URL.revokeObjectURL(i),0)},n=()=>{const e=new Date,t=e=>String(e).padStart(2,"0");return`${e.getFullYear()}${t(e.getMonth()+1)}${t(e.getDate())}-${t(e.getHours())}${t(e.getMinutes())}`};e.exportMarkdown=r=>(t(r||`metona-${n()}.md`,e.getValue(),"text/markdown"),e),e.exportHTML=(r,i={})=>{const o=i.title||"Document",s=i.css||"",a="function"==typeof e.getHTML?e.getHTML():"",l=!1!==i.embedCSS?'':"";return t(r||`metona-${n()}.html`,`\n\n\n\n\n${o}\n${s?``:""}${l}\n\n\n${a}\n\n`,"text/html"),e}},destroy(){}},searchReplace:{name:"searchReplace",version:"0.2.0",description:"Search & Replace (Ctrl+F/H)",priority:80,install(e){if(!e||!e.textarea||"undefined"==typeof document)return;if(!document.getElementById("me-search-style")){const e=document.createElement("style");e.id="me-search-style",e.textContent=".me-search{position:absolute;top:8px;right:12px;z-index:20;display:flex;flex-direction:column;gap:6px;padding:8px;background:var(--md-toolbar-bg,#f8f9fa);border:1px solid var(--md-border,rgba(0,0,0,0.1));border-radius:8px;box-shadow:0 8px 24px -8px rgba(0,0,0,0.2);font-size:13px;min-width:280px}.me-search-row{display:flex;gap:4px;align-items:center}.me-search input{flex:1;min-width:0;padding:4px 8px;border:1px solid var(--md-border,rgba(0,0,0,0.15));border-radius:4px;background:var(--md-textarea-bg,#fff);color:var(--md-text,#1f2937);font-size:13px}.me-search input:focus{outline:none;border-color:var(--md-accent,#3b82f6)}.me-search button{padding:4px 8px;border:1px solid var(--md-border,rgba(0,0,0,0.15));background:var(--md-bg,#fff);color:var(--md-text,#1f2937);border-radius:4px;cursor:pointer;font-size:12px;line-height:1}.me-search button:hover{background:var(--md-accent,#3b82f6);color:#fff;border-color:var(--md-accent,#3b82f6)}.me-search .me-search-count{color:var(--md-muted,#6b7280);font-size:12px;min-width:60px;text-align:center}.me-search .me-search-close{padding:2px 6px}",document.head.appendChild(e)}const t={_panel:null,_regexMode:!1,_cleanup:null},n=()=>{if(!t._panel)return;const e="1"===t._panel.dataset.replace,n=t._panel.querySelector(".me-search-replace-row");n&&(n.style.display=e?"flex":"none")},r=()=>{t._cleanup&&(t._cleanup(),t._cleanup=null),t._panel=null,e&&e.textarea&&e.textarea.focus()},i=i=>{if(t._panel){t._panel.dataset.replace=i?"1":"0",n();const e=t._panel.querySelector(".me-search-find");return void(e&&(e.focus(),e.select()))}const o=e.textarea.value.substring(e.textarea.selectionStart,e.textarea.selectionEnd),s=document.createElement("div");var a;s.className="me-search",s.dataset.replace=i?"1":"0",s.innerHTML=`/g,">")}"/>
`,e.el.appendChild(s),t._panel=s,n(),t._regexMode=!1;const l=s.querySelector(".me-search-find"),c=s.querySelector(".me-search-replace"),d=s.querySelector(".me-search-count"),h=s.querySelector(".me-search-regex");h.addEventListener("click",()=>{t._regexMode=!t._regexMode,h.classList.toggle("me-active",t._regexMode),p=u()});const u=()=>{const n=l.value;if(!n)return d.textContent="",[];const r=[];let i=0;if(t._regexMode)try{const t=new RegExp(n,"g");let i;for(;null!==(i=t.exec(e.textarea.value));)r.push(i.index),0===i[0].length&&t.lastIndex++}catch(e){return d.textContent="err",[]}else for(;;){const t=e.textarea.value.indexOf(n,i);if(-1===t)break;r.push(t),i=t+n.length}return d.textContent=r.length?`${r.length}`:"0",r};let p=[];const m=(t,n)=>{e.textarea.focus(),e.textarea.setSelectionRange(t,t+(n||l.value.length))},g=()=>{if(p=u(),!p.length)return;const n=e.textarea.selectionEnd,r=t._regexMode?(()=>{try{const t=new RegExp(l.value).exec(e.textarea.value.substring(n));return t?t[0].length:l.value.length}catch(e){return l.value.length}})():l.value.length;let i=p.find(e=>e>=n);null==i&&(i=p[0]),m(i,r)},f=()=>{if(p=u(),!p.length)return;const n=e.textarea.selectionStart,r=t._regexMode?(()=>{try{const t=new RegExp(l.value).exec(e.textarea.value.substring(Math.max(0,n-100),n+100));return t?t[0].length:l.value.length}catch(e){return l.value.length}})():l.value.length;let i=-1;for(let e=p.length-1;e>=0;e--)if(p[e]{const n=l.value,r=c.value;if(!n)return;const i=e.textarea,o=i.selectionStart,s=i.selectionEnd,a=i.value.substring(o,s);if(t._regexMode)try{new RegExp(n).test(a)&&(i.value=i.value.substring(0,o)+r+i.value.substring(s),i.setSelectionRange(o,o+r.length))}catch(e){}else a===n&&(i.value=i.value.substring(0,o)+r+i.value.substring(s),i.setSelectionRange(o,o+r.length));e._value=i.value,"function"==typeof e._pushHistory&&e._pushHistory(),"function"==typeof e._render&&e._render(),"function"==typeof e._emit&&e._emit("change",e._value),g()};l.addEventListener("input",()=>{p=u()}),l.addEventListener("keydown",e=>{"Enter"===e.key&&(e.preventDefault(),e.shiftKey?f():g()),"Escape"===e.key&&(e.preventDefault(),r())}),c.addEventListener("keydown",e=>{"Enter"===e.key&&(e.preventDefault(),v()),"Escape"===e.key&&(e.preventDefault(),r())}),s.querySelector(".me-search-next").addEventListener("click",g),s.querySelector(".me-search-prev").addEventListener("click",f),s.querySelector(".me-search-close").addEventListener("click",()=>r()),s.querySelector(".me-search-replace-one").addEventListener("click",v),s.querySelector(".me-search-replace-all").addEventListener("click",()=>{const n=l.value,r=c.value;if(!n)return;const i=e.textarea;if(t._regexMode)try{i.value=i.value.replace(new RegExp(n,"g"),r)}catch(e){return}else i.value=i.value.split(n).join(r);i.setSelectionRange(0,0),e._value=i.value,"function"==typeof e._pushHistory&&e._pushHistory(),"function"==typeof e._render&&e._render(),"function"==typeof e._emit&&e._emit("change",e._value),u()}),l.focus(),l.select(),t._cleanup=()=>{s.parentNode&&s.parentNode.removeChild(s)}},o=e=>{if(!e.ctrlKey&&!e.metaKey)return;const n=e.key.toLowerCase();"f"===n?(e.preventDefault(),i(!1)):"h"===n?(e.preventDefault(),i(!0)):"escape"===n&&t._panel&&r()};e.textarea.addEventListener("keydown",o),e.__srState=t,e.__srOpen=i,e.__srClose=r,e.__srKeydown=o},destroy(e){const t=e.__srState;t&&(t._cleanup&&(t._cleanup(),t._cleanup=null),t._panel=null);const n=e.__srKeydown;n&&e&&e.textarea&&e.textarea.removeEventListener("keydown",n),delete e.__srState,delete e.__srOpen,delete e.__srClose,delete e.__srKeydown}},imagePaste:{name:"imagePaste",version:"0.2.0",description:"Paste image as base64",priority:60,install(e){if(!e||!e.textarea||"undefined"==typeof document)return;const t=t=>{const n=t.clipboardData?.items;if(n)for(const r of n)if(r.type?.startsWith("image/")){t.preventDefault();const n=new FileReader;n.onload=()=>{e.insert(`\n`)},n.readAsDataURL(r.getAsFile());break}};e.textarea.addEventListener("paste",t),e.__ipOnPaste=t},destroy(e){const t=e.__ipOnPaste;t&&e?.textarea&&e.textarea.removeEventListener("paste",t),delete e.__ipOnPaste}},shortcutHelp:{name:"shortcutHelp",version:"0.2.0",description:"Press ? to show shortcuts",priority:200,install(e){if(!e||!e.textarea||"undefined"==typeof document)return;if(!document.getElementById("me-shortcut-style")){const e=document.createElement("style");e.id="me-shortcut-style",e.textContent=".me-shortcut-overlay{position:fixed;top:0;left:0;right:0;bottom:0;z-index:50;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center}.me-shortcut-panel{background:var(--md-bg,#fff);border-radius:12px;padding:24px;max-width:560px;width:90%;max-height:80vh;overflow-y:auto;box-shadow:0 12px 40px rgba(0,0,0,0.3)}.me-shortcut-panel h3{font-size:16px;margin:0 0 16px;color:var(--md-text)}.me-shortcut-panel table{width:100%;border-collapse:collapse;font-size:13px}.me-shortcut-panel td{padding:6px 10px;border-bottom:1px solid var(--md-border)}.me-shortcut-panel td:first-child{font-family:var(--md-mono);font-size:12px;color:var(--md-accent);white-space:nowrap;width:40%}.me-shortcut-panel .me-shortcut-close{position:absolute;top:16px;right:20px;background:none;border:none;font-size:20px;cursor:pointer;color:var(--md-muted)}",document.head.appendChild(e)}let t=null;const n=()=>{t&&(t.remove(),t=null)},r=()=>{if(t)return void n();const e=[["Ctrl+B",b("bold")||"Bold"],["Ctrl+I",b("italic")||"Italic"],["Ctrl+U",b("underline")||"Underline"],["Ctrl+K",b("link")||"Link"],["Ctrl+E",b("code")||"Code"],["Ctrl+1/2/3",b("h1")||"Heading"],["Ctrl+Q",b("quote")||"Quote"],["Ctrl+Z",b("undo")||"Undo"],["Ctrl+Y",b("redo")||"Redo"],["Ctrl+S",b("save")||"Save"],["Ctrl+F",b("search")||"Search"],["Ctrl+H",b("replace")||"Replace"],["Tab",b("indent")||"Indent"],["Shift+Tab",b("outdent")||"Outdent"],["?",b("close")||"Shortcuts"]];let r="";e.forEach(([e,t])=>{r+=`| ${e} | ${t} |
`});const i=document.createElement("div");i.className="me-shortcut-overlay",i.innerHTML=`⌨️ ${b("close")||"Shortcuts"}
`,i.addEventListener("click",e=>{(e.target===i||e.target.classList.contains("me-shortcut-close"))&&n()}),document.body.appendChild(i),t=i},i=e=>{"?"!==e.key||e.ctrlKey||e.metaKey||e.altKey||(e.preventDefault(),r()),"Escape"===e.key&&t&&n()};e.textarea.addEventListener("keydown",i),e.__shState={_panel:t,_open:r,_close:n,_onKeydown:i}},destroy(e){const t=e.__shState;t&&t._panel&&t._panel.remove();const n=e.__shState?._onKeydown;n&&e?.textarea&&e.textarea.removeEventListener("keydown",n),delete e.__shState}},fileSystem:{name:"fileSystem",version:"0.2.0",description:"File System Access API",priority:90,install(e){if(!e||"function"!=typeof e.getValue)return;const t="undefined"!=typeof window&&"function"==typeof window.showOpenFilePicker;let n=null;e.openFile=async(r={})=>{if(!t)return e.toast?.("File System Access API not supported",{type:"warning"}),null;try{const[t]=await window.showOpenFilePicker({types:[{accept:{"text/markdown":[".md",".txt",".markdown"]}}],...r});n=t;const i=await t.getFile(),o=await i.text();return e.setValue(o),e._emit?.("fileOpened",{name:i.name,handle:t}),{name:i.name,content:o,handle:t}}catch(e){return e.name,null}},e.saveFile=async(r={})=>{let i=n;if(!i||r.saveAs){if(!t)return e.toast?.("File System Access API not supported",{type:"warning"}),!1;try{i=await window.showSaveFilePicker({types:[{accept:{"text/markdown":[".md"]}}],suggestedName:r.name||"document.md"}),n=i}catch(e){return e.name,!1}}try{const t=await i.createWritable();return await t.write(e.getValue()),await t.close(),e._emit?.("fileSaved",{handle:i}),!0}catch(t){return n=null,!r.saveAs&&e.saveFile({...r,saveAs:!0})}},e.saveFileAs=t=>e.saveFile({saveAs:!0,name:t}),e.getFileHandle=()=>n,e.__fsCleanup={getHandle:()=>n}},destroy(e){e&&(delete e.openFile,delete e.saveFile,delete e.saveFileAs,delete e.getFileHandle),delete e.__fsCleanup}}},xe={createManager:()=>new ge,manager:fe,register:(e,t)=>fe.register(e,t),unregister:e=>fe.unregister(e),get:e=>fe.get(e),has:e=>fe.has(e),getAll:()=>fe.getAll(),getNames:()=>fe.getNames(),enable:e=>fe.enable(e),disable:e=>fe.disable(e),isEnabled:e=>fe.isEnabled(e),getPreset:e=>ye[e]?{...ye[e]}:null,getAllPresets:()=>Object.keys(ye).reduce((e,t)=>(e[t]={...ye[t]},e),{}),createPlugin:(e={})=>{const t={name:e.name||"custom",version:e.version||"0.0.0",description:e.description||"",depends:e.depends||[],priority:e.priority||0,install:()=>{},destroy:()=>{},...e};return"function"!=typeof t.install&&(t.install=()=>{}),"function"!=typeof t.destroy&&(t.destroy=()=>{}),t},validatePlugin:e=>{const t=[];return e&&"object"==typeof e||t.push("plugin must be an object"),e&&!e.name&&t.push("plugin must have a name"),e&&e.install&&"function"!=typeof e.install&&t.push("install must be a function"),{valid:0===t.length,errors:t}},topologicalSort:ve,validateConfig:be};let _e="auto",we=new Set,ke=null;const Ee=()=>"undefined"==typeof window?"light":"undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",Ce=()=>{"undefined"!=typeof window&&window.matchMedia&&(ke&&(ke(),ke=null),ke=(()=>{if("undefined"==typeof window||!window.matchMedia)return()=>{};const e=window.matchMedia("(prefers-color-scheme: dark)"),t=e=>(e.matches,void("auto"===_e&&Ae("auto")));return e.addEventListener("change",t),()=>e.removeEventListener("change",t)})())},Te=e=>e&&"auto"!==e?e:Ee(),Se=e=>{const t=Te(e),n=s[t];return n&&"object"==typeof n?n:s.light},Le=(e,t)=>{if("undefined"==typeof document||!e||"object"!=typeof e)return;const n=t||document.documentElement,r={"--md-bg":e.bg,"--md-text":e.text,"--md-border":e.border,"--md-shadow":e.shadow,"--md-hover-shadow":e.hoverShadow,"--md-toolbar-bg":e.toolbarBg||e.bg,"--md-textarea-bg":e.textareaBg||e.bg,"--md-preview-bg":e.previewBg||e.bg,"--md-code-bg":e.codeBg||"rgba(127,127,127,0.1)","--md-code-text":e.codeText||e.text,"--md-accent":e.accent||"#3b82f6","--md-muted":e.muted||"#9ca3af"};for(const[e,t]of Object.entries(r))null!=t&&n.style.setProperty(e,String(t));e.progressBg&&n.style.setProperty("--md-progress-bg",e.progressBg),e.closeHoverBg&&n.style.setProperty("--md-close-hover-bg",e.closeHoverBg)},Me=e=>{const t=e||document.documentElement;if("undefined"==typeof document)return{};const n=getComputedStyle(t),r={};return["--md-bg","--md-text","--md-border","--md-shadow","--md-hover-shadow","--md-toolbar-bg","--md-textarea-bg","--md-preview-bg","--md-code-bg","--md-code-text","--md-accent","--md-muted"].forEach(e=>{const t=n.getPropertyValue(e).trim();t&&(r[e]=t)}),r},$e=(e,t)=>{const n=t||document.documentElement;if("undefined"==typeof document)return"";const r=e.startsWith("--")?e:`--md-${e}`;return getComputedStyle(n).getPropertyValue(r).trim()},Ae=e=>{_e=e;const t=Te(e);"undefined"!=typeof document&&(document.documentElement.setAttribute("data-md-theme",t),document.documentElement.classList.remove("md-theme-light","md-theme-dark","md-theme-auto","md-theme-warm"),document.documentElement.classList.add(`md-theme-${t}`),Le(Se(e))),Pe(e,t)},ze=e=>{Ae(e),He(e)},Ie=()=>Te(_e),He=e=>{if("undefined"!=typeof localStorage)try{localStorage.setItem("metona-editor-theme",e)}catch(e){}},Be=()=>{if("undefined"!=typeof localStorage)try{return localStorage.getItem("metona-editor-theme")||"auto"}catch(e){}return"auto"},Pe=(e,t)=>{we.forEach(n=>{try{n(e,t)}catch(e){}})},Re=(e,t)=>{if("undefined"==typeof document||"undefined"==typeof MutationObserver)return()=>{};const{element:n=document.documentElement,attr:r="data-theme",classMap:i=null,callback:o=null}=e,s=()=>{if("function"==typeof o)return o(n);const e=n.getAttribute(r);if(e)return e;if(i)for(const[e,t]of Object.entries(i))if(n.classList.contains(e))return t;return n.getAttribute("data-md-theme")||null};let a=s();a&&t(a);const l=new MutationObserver(()=>{const e=s();e&&e!==a&&(a=e,t(e))});return l.observe(n,{attributes:!0,attributeFilter:[r,"class","data-md-theme"]}),()=>l.disconnect()},De=(e,t)=>{if("undefined"==typeof document||!e)return()=>{};const n=()=>{let t=e.parentElement;for(;t;){const e=t.getAttribute("data-md-theme");if(e)return e;if(t.classList.contains("theme-dark")||t.classList.contains("dark"))return"dark";if(t.classList.contains("theme-light")||t.classList.contains("light"))return"light";t=t.parentElement}if(e.parentElement){const t=getComputedStyle(e.parentElement).getPropertyValue("--md-bg").trim()||getComputedStyle(e.parentElement).backgroundColor;if(t){const e=t.match(/\d+/g);if(e&&e.length>=3)return(299*parseInt(e[0])+587*parseInt(e[1])+114*parseInt(e[2]))/1e3<128?"dark":"light"}}return null},r=n();r&&t(r);const i=new MutationObserver(()=>{const e=n();e&&t(e)});let o=e.parentElement;for(;o&&(i.observe(o,{attributes:!0,attributeFilter:["class","data-md-theme","data-theme"]}),o=o.parentElement,o!==document.documentElement););return()=>i.disconnect()},Fe=(e,t)=>{if("function"==typeof e){const n=()=>{try{const n=e();n&&t(n)}catch(e){}};n();const r=setInterval(n,500);return()=>clearInterval(r)}if("string"==typeof e&&"undefined"!=typeof document){const n=document.querySelector(e);return n?Re({element:n,attr:"data-theme"},t):()=>{}}return()=>{}},je=e=>{let t=e.config?.theme||_e||"auto";const n=n=>{t=n;const r=Te(n),i=Se(n);return e.el&&(["me-theme-light","me-theme-dark","me-theme-warm"].forEach(t=>e.el.classList.remove(t)),"auto"!==r&&e.el.classList.add(`me-theme-${r}`),e.el.setAttribute("data-md-theme",r),Le(i,e.el)),"function"==typeof e._emit&&e._emit("themeChange",{theme:n,resolved:r,config:i}),"function"==typeof e.refresh&&e.refresh(),t};return n(t),{apply:n,get:()=>t,set:e=>n(e),toggle:()=>{const e=Te(t);return n("dark"===e?"light":"dark")},getResolved:()=>Te(t),getConfig:()=>Se(t),getVars:()=>e.el?Me(e.el):{},syncWithElement:(e,t={})=>Re({element:e,attr:t.attr||"data-theme",classMap:t.classMap,callback:t.callback},e=>n(e)),adopt:()=>e.container?De(e.container,e=>n(e)):()=>{},watch:e=>Fe(e,e=>n(e))}},Oe={light:{name:"浅色",description:"明亮清晰",config:s.light},dark:{name:"深色",description:"护眼暗色",config:s.dark},auto:{name:"自动",description:"跟随系统",config:"auto"},warm:{name:"暖色",description:"温馨暖色",config:s.warm}};for(const[e,t]of Object.entries(Oe))"auto"!==e&&"auto"!==t.config&&(s[e]=t.config);const Ne={getSystemTheme:Ee,resolveTheme:Te,getThemeConfig:Se,watchSystemTheme:Ce,unwatchSystemTheme:()=>{ke&&(ke(),ke=null)},applyTheme:Ae,getCurrentTheme:()=>_e,getResolvedTheme:Ie,switchTheme:ze,toggleTheme:()=>{const e=Ie();ze("dark"===e?"light":"dark")},resetToAuto:()=>{ze("auto")},initTheme:()=>{Ae(Be()),Ce()},saveTheme:He,loadTheme:Be,addThemeListener:e=>(we.add(e),()=>{we.delete(e)}),removeThemeListener:e=>{we.delete(e)},clearThemeListeners:()=>{we.clear()},registerTheme:(e,t={})=>{const n=t.extends||"light",r=s[n]||s.light;s[e]={bg:t.bg||r.bg,text:t.text||r.text,border:t.border||r.border,shadow:t.shadow||r.shadow,hoverShadow:t.hoverShadow||r.hoverShadow,toolbarBg:t.toolbarBg||r.toolbarBg||r.bg,textareaBg:t.textareaBg||r.textareaBg||r.bg,previewBg:t.previewBg||r.previewBg||r.bg,codeBg:t.codeBg||r.codeBg,codeText:t.codeText||r.codeText,accent:t.accent||r.accent,muted:t.muted||r.muted,progressBg:t.progressBg||r.progressBg,closeHoverBg:t.closeHoverBg||r.closeHoverBg}},unregisterTheme:e=>{"light"!==e&&"dark"!==e&&"auto"!==e&&"warm"!==e&&delete s[e]},getAllThemes:()=>({...s}),getThemeNames:()=>Object.keys(s),hasTheme:e=>e in s,setThemeVariables:Le,exportCSSVars:Me,getCSSVariable:$e,applyThemeToElement:(e,t)=>{if(!t||"undefined"==typeof document)return;const n=Te(e);t.setAttribute("data-md-theme",n),t.classList.remove("md-theme-light","md-theme-dark","md-theme-auto","md-theme-warm"),"auto"!==n&&t.classList.add(`md-theme-${n}`),Le(Se(e),t)},followExternalTheme:Re,adoptFromParent:De,watch:Fe,createInstanceTheme:je},We=["edit","split","preview"],qe={success:"✓",error:"✗",warning:"⚠",info:"ℹ"},Ve={"(":")","[":"]","{":"}",'"':'"',"'":"'","`":"`","*":"*",_:"_"};class Ue{static on(e,t){return this._hooks.has(e)||this._hooks.set(e,[]),this._hooks.get(e).push(t),()=>this.off(e,t)}static off(e,t){const n=this._hooks.get(e);n&&this._hooks.set(e,n.filter(e=>e!==t))}static trigger(e,t){const n=this._hooks.get(e);n&&n.forEach(e=>{try{e(t)}catch(e){}})}constructor(e,t={}){if("undefined"==typeof window||"undefined"==typeof document)return this._destroyed=!0,this._value=t.value||"",this;if(this.id=t.id||"me-"+Date.now().toString(36)+"-"+Math.random().toString(36).slice(2,8),this.container="string"==typeof e?document.querySelector(e):e,!this.container)return this._destroyed=!0,this;this.config={...o,...t},t.style&&"object"==typeof t.style&&(this.config.style={...o.style,...t.style}),this._value=this.config.value||"",this._mode=We.includes(this.config.mode)?this.config.mode:"split",this._history=[],this._historyIndex=-1,this._cleanups=[],this._plugins=[],this._listeners={},this._renderRaf=null,this._historyTimer=null,this._fullscreen=!1,this._destroyed=!1,this._lastRenderedValue=null,this._shortcuts=[],this._contextMenuItems=[],this._customActions={},this._outlineTimer=null,this._zenMode=!1,this._wordWrap=!0,this._syncing=!1,this._zenMouseHandler=null,this._floatingToolbar=null,this._selectionTimer=null,this._floatingEnabled=!1!==this.config.floatingToolbar,this._renderFn="function"==typeof this.config.render?this.config.render:re,this._highlightFn="function"==typeof this.config.highlight?this.config.highlight:null,Ue.trigger("beforeCreate",this),"undefined"!=typeof document&&(d&&document.getElementById("metona-editor-styles")||(d=document.createElement("style"),d.id="metona-editor-styles",d.textContent=':root{--md-bg:#ffffff;--md-text:#1f2937;--md-border:rgba(0,0,0,0.08);--md-shadow:0 10px 36px -10px rgba(0,0,0,0.18),0 4px 14px -4px rgba(0,0,0,0.08);--md-hover-shadow:0 14px 48px -10px rgba(0,0,0,0.22),0 6px 18px -4px rgba(0,0,0,0.10);--md-toolbar-bg:rgba(248,249,250,0.92);--md-textarea-bg:#ffffff;--md-preview-bg:#ffffff;--md-code-bg:rgba(243,244,246,1);--md-code-text:#1f2937;--md-accent:#3b82f6;--md-muted:#6b7280;--md-radius:10px;--md-font:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei","Hiragino Sans GB",sans-serif;--md-mono:"SF Mono","Cascadia Code","Consolas","Liberation Mono","Courier New",monospace}\n.me-wrapper{display:flex;flex-direction:column;box-sizing:border-box;border:1px solid var(--md-border);border-radius:var(--md-radius);overflow:hidden;background:var(--md-bg);color:var(--md-text);box-shadow:var(--md-shadow);font-family:var(--md-font);font-size:14px;line-height:1.6;position:relative;transition:box-shadow .25s,border-color .25s;width:100%}\n.me-wrapper:hover{box-shadow:var(--md-hover-shadow)}\n.me-wrapper.me-disabled{opacity:.6;pointer-events:none}\n.me-wrapper *{box-sizing:border-box}\n.me-wrapper.me-fullscreen{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;z-index:9999;border-radius:0;border:0}\n.me-toolbar{display:flex;align-items:center;flex-wrap:wrap;gap:2px;padding:6px 8px;background:var(--md-toolbar-bg);border-bottom:1px solid var(--md-border);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);min-height:40px}\n.me-btn{display:inline-flex;align-items:center;justify-content:center;width:30px;height:30px;padding:0;border:0;border-radius:6px;background:transparent;color:var(--md-text);cursor:pointer;transition:background .15s,color .15s,transform .1s;flex-shrink:0}\n.me-btn:hover{background:var(--md-code-bg);color:var(--md-accent)}\n.me-btn:active{transform:scale(.92)}\n.me-btn.me-active{background:var(--md-accent);color:#fff}\n.me-btn:disabled{opacity:.35;cursor:not-allowed;pointer-events:none}\n.me-btn:focus-visible{outline:2px solid var(--md-accent);outline-offset:2px}\n.me-btn:focus:not(:focus-visible){outline:none}\n.me-btn svg{width:17px;height:17px;display:block}\n.me-btn span{font-size:12px;font-weight:500}\n.me-toolbar-sep{display:inline-block;width:1px;height:20px;background:var(--md-border);margin:0 4px;flex-shrink:0}\n.me-toolbar-group{display:inline-flex;gap:2px;margin-left:auto;padding-left:6px;border-left:1px solid var(--md-border)}\n.me-toolbar-group .me-btn{width:auto;padding:0 8px}\n.me-body{display:flex;flex:1;min-height:0;position:relative}\n.me-editor-pane,.me-preview-pane{flex:1 1 50%;min-width:0;overflow:hidden;position:relative}\n.me-editor-inner{display:flex;height:100%;overflow:hidden;position:relative}\n.me-gutter{flex:0 0 auto;min-width:36px;padding:16px 8px 16px 6px;overflow:hidden;background:var(--md-code-bg);border-right:1px solid var(--md-border);color:var(--md-muted);font-family:var(--md-mono);font-size:13.5px;line-height:1.7;text-align:right;user-select:none;white-space:pre}\n.me-gutter-line{padding-right:4px}\n.me-gutter-active{color:var(--md-accent);font-weight:600;background:rgba(59,130,246,.08);border-radius:3px}\n.me-divider{flex:0 0 1px;background:var(--md-border);cursor:col-resize;position:relative}\n.me-divider::after{content:\'\';position:absolute;top:0;bottom:0;left:-3px;right:-3px}\n.me-divider:hover{background:var(--md-accent)}\n.me-textarea{width:100%;height:100%;padding:16px 18px;border:0;outline:0;resize:none;background:var(--md-textarea-bg);color:var(--md-text);font-family:var(--md-mono);font-size:13.5px;line-height:1.7;display:block;white-space:pre-wrap;word-wrap:break-word;position:relative;z-index:1}\n.me-textarea::placeholder{color:var(--md-muted);opacity:.7}\n.me-textarea:focus{outline:0}\n.me-preview-pane{overflow:auto;background:var(--md-preview-bg)}\n.me-preview{padding:18px 22px;max-width:100%;word-wrap:break-word;overflow-wrap:break-word}\n.me-body.me-mode-edit .me-preview-pane,.me-body.me-mode-edit .me-divider{display:none}\n.me-body.me-mode-edit .me-editor-pane{flex:1 1 100%}\n.me-body.me-mode-preview .me-editor-pane,.me-body.me-mode-preview .me-divider{display:none}\n.me-body.me-mode-preview .me-preview-pane{flex:1 1 100%}\n.me-preview>:first-child{margin-top:0}\n.me-preview>:last-child{margin-bottom:0}\n.me-preview h1,.me-preview h2,.me-preview h3,.me-preview h4,.me-preview h5,.me-preview h6{margin:1.4em 0 .6em;font-weight:650;line-height:1.3}\n.me-preview h1{font-size:1.9em;padding-bottom:.3em;border-bottom:1px solid var(--md-border)}\n.me-preview h2{font-size:1.55em;padding-bottom:.3em;border-bottom:1px solid var(--md-border)}\n.me-preview h3{font-size:1.3em}\n.me-preview h4{font-size:1.12em}\n.me-preview h5{font-size:1em}\n.me-preview h6{font-size:.9em;color:var(--md-muted)}\n.me-preview p{margin:.7em 0}\n.me-preview a{color:var(--md-accent);text-decoration:none}\n.me-preview a:hover{text-decoration:underline}\n.me-preview strong{font-weight:650}\n.me-preview em{font-style:italic}\n.me-preview del{text-decoration:line-through;opacity:.75}\n.me-preview ul,.me-preview ol{margin:.6em 0;padding-left:1.6em}\n.me-preview li{margin:.25em 0}\n.me-preview li.me-task-item{list-style:none;margin-left:-1.4em}\n.me-preview li.me-task-item input{margin-right:.5em;vertical-align:middle}\n.me-preview blockquote{margin:.8em 0;padding:.4em 1em;border-left:3px solid var(--md-accent);background:var(--md-code-bg);border-radius:0 6px 6px 0;color:var(--md-text)}\n.me-preview blockquote>:first-child{margin-top:0}\n.me-preview blockquote>:last-child{margin-bottom:0}\n.me-preview hr{border:0;height:1px;background:var(--md-border);margin:1.6em 0}\n.me-preview code{font-family:var(--md-mono);font-size:.88em;padding:.15em .4em;background:var(--md-code-bg);color:var(--md-code-text);border-radius:4px}\n.me-preview pre{margin:.9em 0;padding:14px 16px;background:var(--md-code-bg);border-radius:8px;overflow-x:auto;border:1px solid var(--md-border)}\n.me-code-title{font-family:var(--md-mono);font-size:.85em;padding:8px 14px;background:var(--md-border);border-radius:8px 8px 0 0;color:var(--md-text);margin:.9em 0 -0.9em;font-weight:600}\n.me-code-title+pre{margin-top:0;border-radius:0 0 8px 8px;border-top:none}\n.me-preview pre code{padding:0;background:transparent;color:var(--md-code-text);font-size:.9em;line-height:1.6;border-radius:0}\n.me-preview img{max-width:100%;height:auto;border-radius:6px;vertical-align:middle}\n.me-table-wrap{overflow-x:auto;margin:.9em 0}\n.me-preview table{border-collapse:collapse;width:100%;font-size:.93em;display:block}\n.me-preview th,.me-preview td{border:1px solid var(--md-border);padding:7px 12px;text-align:left}\n.me-preview th{background:var(--md-code-bg);font-weight:600}\n.me-preview tr:nth-child(even) td{background:var(--md-code-bg)}\n.me-statusbar{display:flex;align-items:center;justify-content:flex-end;gap:14px;padding:4px 12px;border-top:1px solid var(--md-border);background:var(--md-toolbar-bg);color:var(--md-muted);font-size:12px;min-height:26px}\n.me-statusbar:empty{display:none}\n.me-wrapper:focus-within{border-color:var(--md-accent)}\n.me-textarea:focus-visible{outline:0}\n@media(prefers-reduced-motion:reduce){.me-wrapper,.me-btn,.me-textarea{transition:none!important}}\n.me-wrapper.me-fullscreen .me-preview,.me-wrapper.me-fullscreen .me-textarea{font-size:15px}\n.me-wrapper.me-readonly .me-textarea{background:var(--md-code-bg);cursor:default;opacity:.88}\n.me-wrapper.me-readonly .me-toolbar{opacity:.75}\n.me-wrapper.me-readonly .me-btn:disabled{opacity:.3;cursor:not-allowed;pointer-events:none}\n.me-preview mark{background:rgba(250,204,21,.3);color:inherit;padding:.1em .2em;border-radius:3px}\n.me-preview sup{font-size:.75em;vertical-align:super;line-height:1}\n.me-preview sub{font-size:.75em;vertical-align:sub;line-height:1}\n.me-preview .me-math-block{display:block;margin:1.2em 0;padding:12px 16px;background:var(--md-code-bg);border-radius:8px;overflow-x:auto;font-family:var(--md-mono);font-size:.95em;text-align:center}\n.me-preview .me-math-inline{font-family:var(--md-mono);font-size:.95em;padding:.05em .2em}\n.me-preview dl{margin:.8em 0}\n.me-preview dt{font-weight:650;margin:.6em 0 .2em}\n.me-preview dd{margin:0 0 .3em 1.6em;color:var(--md-text)}\n.me-preview .me-footnote-ref a{font-size:.75em;vertical-align:super;text-decoration:none;color:var(--md-accent)}\n.me-preview .me-footnotes{margin-top:2em;border-top:1px solid var(--md-border);padding-top:.8em;font-size:.9em;color:var(--md-muted)}\n.me-preview .me-footnotes hr{display:none}\n.me-preview .me-footnotes ol{padding-left:1.2em}\n.me-preview .me-footnote-item{margin:.3em 0}\n.me-preview .me-footnote-backref{text-decoration:none;color:var(--md-accent);margin-right:.4em}\n.me-toast{position:absolute;bottom:16px;right:16px;z-index:30;display:flex;align-items:center;gap:8px;padding:10px 16px;border-radius:8px;font-size:13px;pointer-events:auto;cursor:pointer;opacity:0;transform:translateY(12px);transition:opacity .3s,transform .3s;box-shadow:0 6px 20px rgba(0,0,0,.15);max-width:360px}\n.me-toast.me-toast-enter{opacity:1;transform:translateY(0)}\n.me-toast.me-toast-leave{opacity:0;transform:translateY(12px)}\n.me-toast-success{background:#10b981;color:#fff}\n.me-toast-error{background:#ef4444;color:#fff}\n.me-toast-warning{background:#f59e0b;color:#fff}\n.me-toast-info{background:var(--md-accent,#3b82f6);color:#fff}\n.me-toast-icon{font-weight:700;font-size:16px;flex-shrink:0}\n.me-toast-msg{line-height:1.4}\n.me-context-menu{position:fixed;z-index:40;min-width:180px;padding:4px 0;background:var(--md-bg);border:1px solid var(--md-border);border-radius:8px;box-shadow:0 8px 28px rgba(0,0,0,.18);font-size:13px}\n.me-context-menu-item{display:flex;align-items:center;justify-content:space-between;padding:6px 14px;cursor:pointer;color:var(--md-text);transition:background .1s}\n.me-context-menu-item:hover{background:var(--md-code-bg);color:var(--md-accent)}\n.me-context-menu-sep{height:1px;background:var(--md-border);margin:4px 0}\n.me-context-menu-shortcut{color:var(--md-muted);font-size:11px;margin-left:24px}\n.me-context-menu-item.me-disabled{opacity:.4;cursor:not-allowed;pointer-events:none}\n.me-outline{position:absolute;top:0;right:0;width:220px;height:100%;overflow-y:auto;background:var(--md-preview-bg);border-left:1px solid var(--md-border);padding:12px 14px;font-size:13px;z-index:15}\n.me-outline-title{font-weight:650;margin-bottom:8px;padding-bottom:6px;border-bottom:1px solid var(--md-border);color:var(--md-text)}\n.me-outline ul{list-style:none;padding:0;margin:0}\n.me-outline li{margin:2px 0}\n.me-outline a{color:var(--md-muted);text-decoration:none;display:block;padding:2px 6px;border-radius:4px;transition:background .1s,color .1s}\n.me-outline a:hover{background:var(--md-code-bg);color:var(--md-accent)}\n.me-outline a.me-outline-active{background:var(--md-accent);color:#fff;font-weight:600}\n.me-outline-l1 a{font-weight:600;color:var(--md-text)}\n.me-outline-l2 a{padding-left:12px}\n.me-outline-l3 a{padding-left:20px;font-size:12px}\n.me-outline-l4 a{padding-left:28px;font-size:12px}\n.me-wrapper.me-zen .me-body{max-width:820px;margin:0 auto}\n.me-wrapper.me-zen .me-textarea{font-size:15px;line-height:1.8}\n.me-sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}\n@media print{.me-wrapper{border:0!important;box-shadow:none!important}\n.me-toolbar,.me-statusbar,.me-divider{display:none!important}\n.me-body.me-mode-split .me-editor-pane{display:none}\n.me-body.me-mode-split .me-preview-pane{flex:1 1 100%!important}\n.me-preview{padding:0!important;font-size:11pt}\n.me-wrapper.me-fullscreen{position:static!important;width:auto!important;height:auto!important}}\n[dir=rtl] .me-gutter{border-right:none;border-left:1px solid var(--md-border);text-align:left}\n[dir=rtl] .me-gutter-line{padding-right:0;padding-left:4px}\n[dir=rtl] .me-toolbar-group{margin-left:0;margin-right:auto;padding-left:0;padding-right:6px;border-left:none;border-right:1px solid var(--md-border)}\n[dir=rtl] .me-outline{right:auto;left:0;border-left:none;border-right:1px solid var(--md-border)}\n[dir=rtl] .me-outline-l2 a{padding-left:0;padding-right:12px}\n[dir=rtl] .me-outline-l3 a{padding-left:0;padding-right:20px}\n[dir=rtl] .me-outline-l4 a{padding-left:0;padding-right:28px}\n[dir=rtl] .me-preview blockquote{border-left:none;border-right:3px solid var(--md-accent);border-radius:6px 0 0 6px}\n[dir=rtl] .me-preview ul,[dir=rtl] .me-preview ol{padding-left:0;padding-right:1.6em}\n[dir=rtl] .me-preview li.me-task-item{margin-left:0;margin-right:-1.4em}\n[dir=rtl] .me-preview dd{margin-left:0;margin-right:1.6em}\n[dir=rtl] .me-preview .me-footnotes ol{padding-left:0;padding-right:1.2em}\n[dir=rtl] .me-preview .me-footnote-backref{margin-right:0;margin-left:.4em}\n[dir=rtl] .me-search{right:auto;left:12px}\n[dir=rtl] .me-toast{right:auto;left:16px}\n[dir=rtl] .me-context-menu-shortcut{margin-left:0;margin-right:24px}\n[dir=rtl] .me-statusbar{justify-content:flex-start}',document.head.appendChild(d))),this._buildDOM(),this._themeCtx=je(this),this._i18nCtx=$(this),t.theme&&"undefined"!=typeof document&&document.documentElement.setAttribute("data-md-theme",Te(t.theme));const n=Se(this.config.theme);if(Le(n,this.el),this._buildToolbar(),this._updateModeButtons(),this._bindToolbarKeyboard(),this._initAriaLive(),this._bindEvents(),this._bindContextMenu(),this._trackOutlineScroll(),!1!==this.config.floatingToolbar&&this._initFloatingToolbar(),this.textarea.value=this._value,this._pushHistory(),this._render(),this._updateWordCount(),Array.isArray(this.config.plugins)){const e=this.config.plugins.map(e=>"string"==typeof e?{...ye[e],_isStringRef:!0}:e).filter(Boolean);ve(e).forEach(e=>this.use(e))}if(this.config.autofocus&&!this.config.readOnly&&this.focus(),"function"==typeof this.config.onCreate)try{this.config.onCreate(this)}catch(e){}Ue.trigger("afterCreate",this)}_buildDOM(){const e=document.createElement("div");var t;e.className=`me-wrapper me-theme-${t=this.config.theme,t&&"auto"!==t?t:Te("auto")}`,this.config.readOnly&&e.classList.add("me-readonly"),e.dataset.id=this.id,e.setAttribute("role","application"),e.setAttribute("aria-label",b("edit")),this.config.className&&this.config.className.split(/\s+/).filter(Boolean).forEach(t=>e.classList.add(t));const n=this.config.height;e.style.height="number"==typeof n?`${n}px`:n||"400px",this.config.style&&"object"==typeof this.config.style&&Object.entries(this.config.style).forEach(([t,n])=>{n&&(e.style[t]=n)});const r=document.createElement("div");r.className="me-toolbar",r.setAttribute("role","toolbar");const i=document.createElement("div");i.className=`me-body me-mode-${this._mode}`;const o=document.createElement("div");o.className="me-editor-pane";const s=document.createElement("div");s.className="me-editor-inner";const a=document.createElement("div");a.className="me-gutter",this.config.lineNumbers||(a.style.display="none"),s.appendChild(a);const l=document.createElement("textarea");l.className="me-textarea",l.spellcheck=!!this.config.spellcheck,l.readOnly=!!this.config.readOnly,l.style.tabSize=String(this.config.tabSize||2),l.placeholder=this.config.placeholder||b("placeholder"),l.setAttribute("aria-label",b("edit")),s.appendChild(l),o.appendChild(s);const c=document.createElement("div");c.className="me-divider",c.setAttribute("role","separator");const d=document.createElement("div");d.className="me-preview-pane",d.setAttribute("role","region"),d.setAttribute("aria-label",b("preview"));const h=document.createElement("div");h.className="me-preview",d.appendChild(h),i.appendChild(o),i.appendChild(c),i.appendChild(d),e.appendChild(r),e.appendChild(i);let u=null;this.config.wordCount&&(u=document.createElement("div"),u.className="me-statusbar",e.appendChild(u)),this.container.appendChild(e),this.el=e,this.toolbarEl=r,this.bodyEl=i,this.editorPane=o,this.editorInner=s,this.gutter=a,this.previewPane=d,this.dividerEl=c,this.textarea=l,this.previewEl=h,this.statusEl=u,this._restoreDividerPosition()}_buildToolbar(){const e=this.config.toolbar;if(!e||!Array.isArray(e)||0===e.length)return;const t=[];if(e.forEach(e=>{if("|"===e){const e=document.createElement("span");return e.className="me-toolbar-sep",void this.toolbarEl.appendChild(e)}"edit"!==e&&"split"!==e&&"preview"!==e&&"fullscreen"!==e?this.toolbarEl.appendChild(this._createBtn(e)):t.push(e)}),t.length){const e=document.createElement("div");e.className="me-toolbar-group",t.forEach(t=>{const n=this._createBtn(t);"edit"!==t&&"split"!==t&&"preview"!==t||(n.dataset.mode=t,t===this._mode&&n.classList.add("me-active")),e.appendChild(n)}),this.toolbarEl.appendChild(e)}}_createBtn(e){const r=document.createElement("button");r.type="button",r.className=`me-btn me-btn-${e}`,r.dataset.action=e;const i=b(e)||e;return r.title=i,r.setAttribute("aria-label",i),r.innerHTML=n[e]||`${t(e)}`,r}_bindEvents(){const e=this.textarea,t=()=>{const t=this._value;if(this._value=e.value,Ue.trigger("beforeChange",this),this._emit("beforeChange",t,this._value),this._scheduleRender(),this._scheduleHistory(),this._updateWordCount(),this._renderGutter(),this._updateOutline(),this._emit("input",this._value),this._emit("change",this._value),"function"==typeof this.config.onInput)try{this.config.onInput(this._value,this)}catch(e){}if("function"==typeof this.config.onChange)try{this.config.onChange(this._value,this)}catch(e){}this._emit("afterChange",this._value),Ue.trigger("afterChange",this)};e.addEventListener("input",t);const n=e=>{"Enter"!==e.key||e.shiftKey||e.ctrlKey||e.metaKey||this._handleSmartEnter(e),this._handleKeydown(e)};e.addEventListener("keydown",n);const r=e=>this._handleBracketAutoClose(e);e.addEventListener("keypress",r);const i=()=>{this._updateCurrentLine()};e.addEventListener("click",i),e.addEventListener("keyup",i);const o=()=>{this._syncScroll()};e.addEventListener("scroll",o);const s=()=>{if(!this.config.syncScroll||"split"!==this._mode)return;if(this._syncing)return;this._syncing=!0;const t=this.previewPane.scrollHeight-this.previewPane.clientHeight;if(t<=0)return void(this._syncing=!1);const n=this.previewPane.scrollTop/t,r=e.scrollHeight-e.clientHeight;if(e.scrollTop=n*r,this.gutter){const e=this.gutter.scrollHeight-this.gutter.clientHeight;this.gutter.scrollTop=e>0?n*e:n*r}requestAnimationFrame(()=>{this._syncing=!1})};this.previewPane.addEventListener("scroll",s);const a=()=>{if(this._emit("focus"),"function"==typeof this.config.onFocus)try{this.config.onFocus(this)}catch(e){}},l=()=>{if(this._emit("blur"),"function"==typeof this.config.onBlur)try{this.config.onBlur(this)}catch(e){}};e.addEventListener("focus",a),e.addEventListener("blur",l),this.previewEl.addEventListener("click",e=>{const t=e.target.closest("a");if(!t)return;const n=t.getAttribute("href");if(n&&!n.startsWith("#"))if(e.preventDefault(),this._emit("linkClick",{href:n,text:t.textContent}),"function"!=typeof this.config.onLinkClick)window.open(n,"_blank","noopener");else try{this.config.onLinkClick(n,t.textContent,this)}catch(e){}});const c=e=>{const t=e.target.closest(".me-btn");if(!t)return;const n=t.dataset.mode;if(n)return void this.setMode(n);const r=t.dataset.action;r&&this.exec(r)};this.toolbarEl.addEventListener("click",c);const d=e=>this._bindDividerDrag(e);this.dividerEl.addEventListener("pointerdown",d),this._bindDragDrop(),this._cleanups.push(()=>{e.removeEventListener("input",t),e.removeEventListener("keydown",n),e.removeEventListener("keypress",r),e.removeEventListener("scroll",o),this.previewPane.removeEventListener("scroll",s),e.removeEventListener("click",i),e.removeEventListener("keyup",i),e.removeEventListener("focus",a),e.removeEventListener("blur",l),this.toolbarEl.removeEventListener("click",c),this.dividerEl.removeEventListener("pointerdown",d)})}_handleKeydown(e){if("Tab"===e.key)return e.preventDefault(),void this._handleTab(e.shiftKey);if(this._shortcuts.length)for(const t of this._shortcuts){const n=t.ctrl?e.ctrlKey||e.metaKey:!e.ctrlKey&&!e.metaKey,r=t.shift?e.shiftKey:!e.shiftKey,i=t.alt?e.altKey:!e.altKey;if(e.key.toLowerCase()===t.key&&n&&r&&i){if(e.preventDefault(),"string"==typeof t.handler)this.exec(t.handler);else if("function"==typeof t.handler)try{t.handler(this)}catch(e){}return}}if(!e.ctrlKey&&!e.metaKey)return;const t=e.key.toLowerCase(),n={b:"bold",i:"italic",k:"link",u:"underline",e:"code",1:"h1",2:"h2",3:"h3",q:"quote"};if("z"!==t||e.shiftKey)if("z"===t&&e.shiftKey||"y"===t)e.preventDefault(),this.redo();else if("s"===t){if(e.preventDefault(),this._emit("save",this._value),"function"==typeof this.config.onSave)try{this.config.onSave(this._value,this)}catch(e){}}else n[t]&&(e.preventDefault(),this.exec(n[t]));else e.preventDefault(),this.undo()}_handleTab(e){const t=this.textarea,n=t.selectionStart,r=t.selectionEnd,i=this.config.tabSize||0,o=i>0?" ".repeat(i):"\t";if(n===r)t.value=t.value.slice(0,n)+o+t.value.slice(r),t.selectionStart=t.selectionEnd=n+o.length;else{const i=t.value.lastIndexOf("\n",n-1)+1,s=t.value.slice(i,r).split("\n");let a;a=e?s.map(e=>e.replace(/^(\t| {1,4})/,"")).join("\n"):s.map(e=>o+e).join("\n"),t.value=t.value.slice(0,i)+a+t.value.slice(r),t.selectionStart=i,t.selectionEnd=i+a.length}this._value=t.value,this._pushHistory(),this._render(),this._emit("change",this._value)}_bindDividerDrag(e){if("split"!==this._mode)return;e.preventDefault();const t=e.clientX,n=this.editorPane.getBoundingClientRect().width,r=this.bodyEl.getBoundingClientRect().width;if(r<=0)return;const i=this.dividerEl,o=e=>{const o=e.clientX-t;let s=n+o;const a=r-80-i.offsetWidth;s=Math.max(80,Math.min(a,s));const l=s/r*100;this.editorPane.style.flex=`0 0 ${l}%`,this.previewPane.style.flex=`1 1 ${100-l}%`},s=()=>{window.removeEventListener("pointermove",o),window.removeEventListener("pointerup",s),this._saveDividerPosition()};window.addEventListener("pointermove",o),window.addEventListener("pointerup",s)}_saveDividerPosition(){try{const e=this.editorPane.style.flex;e&&localStorage.setItem("metona-editor-divider",e)}catch(e){}}_restoreDividerPosition(){try{const e=localStorage.getItem("metona-editor-divider");e&&"split"===this._mode&&(this.editorPane.style.flex=e,this.previewPane.style.flex="1 1 auto")}catch(e){}}_scheduleRender(){this._renderRaf||(this._renderRaf=requestAnimationFrame(()=>{this._renderRaf=null,this._render()}))}_render(){if("edit"===this._mode)return;if(this._lastRenderedValue===this._value)return;let e;this._lastRenderedValue=this._value,Ue.trigger("beforeRender",this),this._emit("beforeRender",this);try{e=this._renderFn(this._value,{highlight:this._highlightFn||void 0,locale:f()})}catch(n){e=`${b("renderError")}: ${t(n.message)}
`}if("function"==typeof this.config.sanitize)try{e=this.config.sanitize(e)}catch(e){}this.previewEl.innerHTML=e,this._renderGutter(),Ue.trigger("afterRender",this),this._emit("afterRender",this)}_renderGutter(){if(!this.config.lineNumbers||!this.gutter)return;const e=this._value?this._value.split("\n").length:1,t=this.gutter.children.length;if(t!==e)if(t${r}`;this.gutter.insertAdjacentHTML("beforeend",n)}else for(;this.gutter.children.length>e;)this.gutter.removeChild(this.gutter.lastChild)}_updateCurrentLine(){if(!this.gutter)return;const e=this.textarea.selectionStart,t=this._value.substring(0,e).split("\n").length,n=this.gutter.querySelector(".me-gutter-active");n&&n.classList.remove("me-gutter-active");const r=this.gutter.children[t-1];r&&r.classList.add("me-gutter-active")}_handleSmartEnter(e){const t=this.textarea,n=t.selectionStart,r=t.value,i=r.lastIndexOf("\n",n-1)+1,o=r.slice(i,n),s=o.match(/^(\s*)([-*+]|\d+\.)\s(.*)/);if(s){const o=s[1],a=s[2];if(!s[3].trim())return e.preventDefault(),t.value=r.slice(0,i)+"\n"+r.slice(n),t.selectionStart=t.selectionEnd=i,this._value=t.value,this._pushHistory(),this._renderGutter(),void this._emit("change",this._value);let l=a;if(/^\d+\.$/.test(a)){const e=parseInt(a,10);isNaN(e)||(l=e+1+".")}e.preventDefault();const c="\n"+o+l+" ";return t.value=r.slice(0,n)+c+r.slice(t.selectionEnd),t.selectionStart=t.selectionEnd=n+c.length,this._value=t.value,this._pushHistory(),this._renderGutter(),void this._emit("change",this._value)}const a=o.match(/^(\s*>+\s?)(.*)/);if(a){const o=a[1];if(!a[2].trim())return e.preventDefault(),t.value=r.slice(0,i)+"\n"+r.slice(n),t.selectionStart=t.selectionEnd=i,this._value=t.value,this._pushHistory(),this._renderGutter(),void this._emit("change",this._value);e.preventDefault();const s="\n"+o;t.value=r.slice(0,n)+s+r.slice(t.selectionEnd),t.selectionStart=t.selectionEnd=n+s.length,this._value=t.value,this._pushHistory(),this._renderGutter(),this._emit("change",this._value)}}_handleBracketAutoClose(e){if(!this.config.autoBrackets)return;const t=this.textarea,n=e.key,r=Ve[n];if(!r)return;const i=t.selectionStart,o=t.selectionEnd;if(i!==o){e.preventDefault();const s=t.value.slice(i,o),a=n+s+r;return t.value=t.value.slice(0,i)+a+t.value.slice(o),t.selectionStart=i+1,t.selectionEnd=i+1+s.length,this._value=t.value,this._pushHistory(),void this._emit("change",this._value)}const s=t.value[i]||"";if(n===r){if(s===r)return e.preventDefault(),void(t.selectionStart=t.selectionEnd=i+1);if(/\w/.test(s))return}e.preventDefault();const a=n+r;t.value=t.value.slice(0,i)+a+t.value.slice(o),t.selectionStart=t.selectionEnd=i+1,this._value=t.value,this._pushHistory(),this._emit("change",this._value)}_bindDragDrop(){const e=this.textarea;if(!e)return;const t=e=>{e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy")},n=e=>{e.preventDefault();const t=e.dataTransfer?.files;if(t&&t.length)return void Array.from(t).forEach(e=>{if(e.type.startsWith("image/")){const t=new FileReader;t.onload=()=>{this.insert(`\n`)},t.readAsDataURL(e)}else if(e.type.startsWith("text/")||/\.(md|txt|js|ts|json|css|html|xml|yml|yaml)$/i.test(e.name)){const t=new FileReader;t.onload=()=>this.insert(t.result),t.readAsText(e)}});const n=e.dataTransfer?.getData("text/plain");n&&this.insert(n)};e.addEventListener("dragover",t),e.addEventListener("drop",n),this._cleanups.push(()=>{e.removeEventListener("dragover",t),e.removeEventListener("drop",n)})}_buildOutline(){if(!this.config.outline||!this.previewEl)return;const e=this.el.querySelector(".me-outline");e&&e.remove();const n=[],r=/]*>(.+?)<\/h\1>/gi;let i;for(;null!==(i=r.exec(this.previewEl.innerHTML));)n.push({level:parseInt(i[1],10),id:i[2],text:i[3].replace(/<[^>]+>/g,"")});if(!n.length)return;const o=document.createElement("div");o.className="me-outline",o.innerHTML=`${b("outline")||"大纲"}
`;const s=(e,n)=>{let r="",i=0;for(;i${t(o.text)}`;const a=[];let l=i+1;for(;lo.level;)a.push(e[l]),l++;a.length&&(r+=s(a,o.level+1)),r+="",i=l>i+1?l:i+1}return r+"
"};o.innerHTML+=s(n,1),this.el.appendChild(o),o.addEventListener("click",e=>{const t=e.target.closest("a");if(!t)return;e.preventDefault();const n=t.getAttribute("href").slice(1),r=this.previewEl.querySelector("#"+CSS.escape(n));if(r){r.scrollIntoView({behavior:"smooth",block:"start"});const e=this._value.indexOf(r.textContent||"");-1!==e&&(this.textarea.focus(),this.textarea.setSelectionRange(e,e))}})}_updateOutline(){this.config.outline&&(this._outlineTimer&&clearTimeout(this._outlineTimer),this._outlineTimer=setTimeout(()=>this._buildOutline(),300))}_trackOutlineScroll(){if(!this.config.outline||!this.previewPane)return;let e=!1;const t=()=>{e||(e=!0,requestAnimationFrame(()=>{if(e=!1,!this.el)return;const t=this.el.querySelector(".me-outline");if(!t)return;const n=this.previewEl.querySelectorAll("h1, h2, h3, h4, h5, h6");let r="";const i=this.previewPane.scrollTop+80;n.forEach(e=>{e.offsetTop<=i&&(r=e.id)}),t.querySelectorAll("a").forEach(e=>{e.classList.toggle("me-outline-active",e.getAttribute("href")==="#"+r)})}))};this.previewPane.addEventListener("scroll",t,{passive:!0}),this._cleanups.push(()=>this.previewPane.removeEventListener("scroll",t))}_scheduleHistory(){this._historyTimer&&clearTimeout(this._historyTimer),this._historyTimer=setTimeout(()=>this._pushHistory(),this.config.historyDebounce||400)}_pushHistory(){if(this._history[this._historyIndex]===this._value)return;this._history=this._history.slice(0,this._historyIndex+1),this._history.push(this._value);const e=this.config.historyLimit>0?this.config.historyLimit:100;for(;this._history.length>e;)this._history.shift();this._historyIndex=this._history.length-1}undo(){return this._historyIndex<=0||(this._historyIndex--,this._applyHistory()),this}redo(){return this._historyIndex>=this._history.length-1||(this._historyIndex++,this._applyHistory()),this}canUndo(){return this._historyIndex>0}canRedo(){return this._historyIndexthis._wrapSelection("**","**"),italic:()=>this._wrapSelection("*","*"),strikethrough:()=>this._wrapSelection("~~","~~"),underline:()=>this._wrapSelection("",""),code:()=>this._wrapSelection("`","`"),h1:()=>this._toggleLinePrefix("# "),h2:()=>this._toggleLinePrefix("## "),h3:()=>this._toggleLinePrefix("### "),quote:()=>this._toggleLinePrefix("> "),ul:()=>this._toggleLinePrefix("- "),ol:()=>this._toggleLinePrefix("1. "),indent:()=>this._handleTab(!1),outdent:()=>this._handleTab(!0),hr:()=>this._insertBlock("\n---\n"),link:()=>this._insertLink(),image:()=>this._insertImage(),table:()=>this._insertTable(),undo:()=>this.undo(),redo:()=>this.redo(),edit:()=>this.setMode("edit"),split:()=>this.setMode("split"),preview:()=>this.setMode("preview"),fullscreen:()=>this.toggleFullscreen(),zen:()=>this.toggleZen(),wordwrap:()=>this.toggleWordWrap(),formatTable:()=>this._formatTable()}[e];if(n)return n.apply(this,t),this;if(this._customActions&&"function"==typeof this._customActions[e])try{this._customActions[e].apply(this,t)}catch(e){}return this}_wrapSelection(e,t){const n=this.textarea,r=n.selectionStart,i=n.selectionEnd,o=n.value.slice(r,i),s=o||"text",a=e+s+t;n.value=n.value.slice(0,r)+a+n.value.slice(i),n.focus(),o?(n.selectionStart=r+e.length,n.selectionEnd=r+e.length+s.length):n.selectionStart=n.selectionEnd=r+e.length,this._value=n.value,this._pushHistory(),this._render(),this._updateWordCount(),this._emit("change",this._value)}_toggleLinePrefix(e){const t=this.textarea,n=t.selectionStart,r=t.value.lastIndexOf("\n",n-1)+1,i=t.value.indexOf("\n",n),o=-1===i?t.value.length:i,s=t.value.slice(r,o),a=s.match(/^(#{1,6}\s*|>\s*|[-*+]\s*|\d+\.\s*)/);let l;l=a&&a[0]===e?s.slice(e.length):a?e+s.slice(a[0].length):e+s,t.value=t.value.slice(0,r)+l+t.value.slice(o),t.focus(),t.selectionStart=t.selectionEnd=r+l.length,this._value=t.value,this._pushHistory(),this._render(),this._updateWordCount(),this._emit("change",this._value)}_insertBlock(e){const t=this.textarea,n=t.selectionStart,r=t.value.slice(0,n),i=(r&&!r.endsWith("\n")?"\n":"")+e;t.value=t.value.slice(0,n)+i+t.value.slice(t.selectionEnd),t.focus();const o=n+i.length;t.selectionStart=t.selectionEnd=o,this._value=t.value,this._pushHistory(),this._render(),this._updateWordCount(),this._emit("change",this._value)}_insertLink(){const e=this.textarea,t=e.selectionStart,n=e.selectionEnd,r=e.value.slice(t,n)||b("link")||"link",i=`[${r}](https://)`;e.value=e.value.slice(0,t)+i+e.value.slice(n),e.focus(),e.selectionStart=t+r.length+3,e.selectionEnd=e.selectionStart+8,this._value=e.value,this._pushHistory(),this._render(),this._emit("change",this._value)}_insertImage(){const e=this.textarea,t=e.selectionStart,n=e.selectionEnd,r=e.value.slice(t,n)||b("image")||"image",i=``;e.value=e.value.slice(0,t)+i+e.value.slice(n),e.focus(),e.selectionStart=t+r.length+4,e.selectionEnd=e.selectionStart+8,this._value=e.value,this._pushHistory(),this._render(),this._emit("change",this._value)}_insertTable(e=3,t=3){let n=`| ${Array.from({length:t},(e,t)=>`${b("tableCols")||"列"}${t+1}`).join(" | ")} |\n| ${Array.from({length:t},()=>"---").join(" | ")} |\n`;for(let r=1;r" ").join(" | ")} |\n`;this._insertBlock("\n"+n)}_formatTable(){const e=this.textarea,t=e.selectionStart,n=e.value.substring(0,t),r=e.value.substring(t),i=n.lastIndexOf("\n\n"),o=r.indexOf("\n\n"),s=-1===i?0:i+2,a=-1===o?e.value.length:t+o,l=e.value.substring(s,a).split("\n").filter(e=>e.includes("|"));if(l.length<2)return;const c=l.map(e=>e.replace(/^\s*\|?\s*|\s*\|?\s*$/g,"").split(/\s*\|\s*/)),d=Math.max(...c.map(e=>e.length)),h=Array(d).fill(3);c.forEach(e=>{e.forEach((e,t)=>{h[t]=Math.max(h[t],e.trim().length)})});const u=(e,t)=>{const n=t-e.length;return e+" ".repeat(Math.max(0,n))},p=c.map(e=>{const t=[];for(let n=0;n{const r=n,i=r.dataset.mode,o=r.dataset.action;if(i)return r.classList.toggle("me-active",i===this._mode),void(r.disabled=!1);r.disabled="fullscreen"!==o&&(t||!!e)&&!("undo"===o||"redo"===o)})}toggleFullscreen(){this._fullscreen=!this._fullscreen,this.el.classList.toggle("me-fullscreen",this._fullscreen);const e=this.toolbarEl.querySelector(".me-btn-fullscreen");if(e&&(e.title=this._fullscreen?b("fullscreenExit")||"退出全屏":b("fullscreen")||"全屏"),this._emit("fullscreen",this._fullscreen),"function"==typeof this.config.onFullscreen)try{this.config.onFullscreen(this._fullscreen,this)}catch(e){}return this}isFullscreen(){return this._fullscreen}exitFullscreen(){return this._fullscreen&&this.toggleFullscreen(),this}toggleZen(){return this._zenMode=!this._zenMode,this.el&&this.el.classList.toggle("me-zen",this._zenMode),this._zenMode&&this.toolbarEl?(this._zenMouseHandler=e=>{this.toolbarEl.style.opacity=e.clientY<40?"1":"0",this.toolbarEl.style.pointerEvents=e.clientY<40?"auto":"none"},this.toolbarEl.style.transition="opacity 0.2s",this.toolbarEl.style.opacity="0",this.toolbarEl.style.pointerEvents="none",document.addEventListener("mousemove",this._zenMouseHandler),this.statusEl&&(this.statusEl.style.display="none")):(this._zenMouseHandler&&(document.removeEventListener("mousemove",this._zenMouseHandler),this._zenMouseHandler=null),this.toolbarEl&&(this.toolbarEl.style.opacity="",this.toolbarEl.style.pointerEvents="",this.toolbarEl.style.transition=""),this.statusEl&&(this.statusEl.style.display="")),this._emit("zenChange",this._zenMode),this}isZen(){return this._zenMode}toggleWordWrap(){return this._wordWrap=!this._wordWrap,this.textarea&&(this.textarea.style.whiteSpace=this._wordWrap?"pre-wrap":"pre"),this}setWordWrap(e){return this._wordWrap=!!e,this.textarea&&(this.textarea.style.whiteSpace=this._wordWrap?"pre-wrap":"pre"),this}isWordWrap(){return this._wordWrap}_initFloatingToolbar(){if("undefined"==typeof document)return;if(!document.getElementById("me-float-style")){const e=document.createElement("style");e.id="me-float-style",e.textContent=".me-float-toolbar{position:absolute;z-index:25;display:flex;gap:4px;padding:4px 6px;background:var(--md-toolbar-bg,#f8f9fa);border:1px solid var(--md-border,rgba(0,0,0,0.1));border-radius:8px;box-shadow:0 8px 24px -8px rgba(0,0,0,0.2);opacity:0;transform:translateY(4px);transition:opacity .15s,transform .15s;pointer-events:none}.me-float-toolbar.me-visible{opacity:1;transform:translateY(0);pointer-events:auto}.me-float-toolbar .me-btn{width:28px;height:28px}",document.head.appendChild(e)}if(!this._floatingEnabled)return;const e=this.textarea,t=()=>{if(this._destroyed||this.config.readOnly||!this._floatingEnabled)return;const t=e.selectionStart;if(t===e.selectionEnd)return void this._hideFloatingToolbar();this._floatingToolbar&&this._floatingToolbar.parentNode||this._buildFloatingToolbar();const n=e.getBoundingClientRect(),r=e.value.substring(0,t).split("\n").length-1,i=parseInt(getComputedStyle(e).lineHeight,10)||22,o=parseInt(getComputedStyle(e).paddingTop,10)||16,s=e.scrollTop,a=n.top+o+r*i-s;let l=a-36-4;ld&&(c=d),this._floatingToolbar.style.top=l+"px",this._floatingToolbar.style.left=c+"px",this._floatingToolbar.classList.add("me-visible")},n=()=>{this._hideFloatingToolbar()};let r=e.selectionStart,i=e.selectionEnd;this._selectionTimer=setInterval(()=>{if(this._destroyed||!document.body.contains(e)||!this._floatingEnabled)return;const t=e.selectionStart,n=e.selectionEnd;if(t!==r||n!==i){r=t,i=n;const e=this._value.slice(t,n);this._emit("selectionChange",{start:t,end:n,text:e})}},500),this._cleanups.push(()=>{this._selectionTimer&&(clearInterval(this._selectionTimer),this._selectionTimer=null)}),e.addEventListener("mouseup",()=>{this._floatingEnabled&&setTimeout(t,0)}),e.addEventListener("keyup",()=>{this._floatingEnabled&&(e.selectionStart!==e.selectionEnd?setTimeout(t,0):setTimeout(n,0),this._emit("cursorMove",this.getCursorPosition()))}),e.addEventListener("blur",()=>setTimeout(n,300)),e.addEventListener("click",()=>{e.selectionStart===e.selectionEnd&&setTimeout(n,0)})}toggleFloatingToolbar(){if(this._floatingEnabled=!this._floatingEnabled,this._floatingEnabled){if(!this._selectionTimer){const e=this.textarea;this._selectionTimer=setInterval(()=>{!this._destroyed&&this._floatingEnabled&&(e.selectionStart,e.selectionEnd)},500),this._cleanups.push(()=>{this._selectionTimer&&(clearInterval(this._selectionTimer),this._selectionTimer=null)})}}else this._selectionTimer&&(clearInterval(this._selectionTimer),this._selectionTimer=null),this._floatingToolbar&&(this._floatingToolbar.parentNode&&this._floatingToolbar.parentNode.removeChild(this._floatingToolbar),this._floatingToolbar=null);return this}isFloatingToolbar(){return this._floatingEnabled}_buildFloatingToolbar(){const e=document.createElement("div");e.className="me-float-toolbar",["bold","italic","code","link","strikethrough"].forEach(t=>{const n=this._createBtn(t);n.addEventListener("mousedown",e=>{e.preventDefault(),e.stopPropagation(),this.exec(t),setTimeout(()=>this.textarea.focus(),0)}),e.appendChild(n)}),this.editorPane.appendChild(e),this._floatingToolbar=e}_hideFloatingToolbar(){this._floatingToolbar&&this._floatingToolbar.classList.remove("me-visible")}_bindToolbarKeyboard(){if(!this.toolbarEl)return;const e=e=>{const t=[...this.toolbarEl.querySelectorAll(".me-btn:not(:disabled)")];if(!t.length)return;const n=t.indexOf(document.activeElement);-1!==n&&("ArrowRight"===e.key?(e.preventDefault(),t[(n+1)%t.length].focus()):"ArrowLeft"===e.key?(e.preventDefault(),t[(n-1+t.length)%t.length].focus()):"Home"===e.key?(e.preventDefault(),t[0].focus()):"End"===e.key&&(e.preventDefault(),t[t.length-1].focus()))};this.toolbarEl.addEventListener("keydown",e),this._cleanups.push(()=>this.toolbarEl.removeEventListener("keydown",e))}_initAriaLive(){if(!this.el)return;const e=document.createElement("div");e.className="me-sr-only",e.setAttribute("aria-live","polite"),e.setAttribute("aria-atomic","true"),this.el.appendChild(e),this._ariaLive=e}_announce(e){this._ariaLive&&(this._ariaLive.textContent="",requestAnimationFrame(()=>{this._ariaLive.textContent=e}))}_syncScroll(){if(this._syncing)return;this._syncing=!0;const e=this.textarea;if(!e)return void(this._syncing=!1);const t=e.scrollHeight-e.clientHeight;if(t<=0)return void(this._syncing=!1);const n=e.scrollTop/t;if(this.gutter){const t=this.gutter.scrollHeight-this.gutter.clientHeight;this.gutter.scrollTop=t>0?n*t:e.scrollTop}if(this.config.syncScroll&&"split"===this._mode&&this.previewPane){const e=this.previewPane.scrollHeight-this.previewPane.clientHeight;e>0&&(this.previewPane.scrollTop=n*e)}requestAnimationFrame(()=>{this._syncing=!1})}_updateWordCount(){if(!this.config.wordCount||!this.statusEl)return;const e=this._value||"",t=e.length,n=(e.match(/[\u4e00-\u9fa5]/g)||[]).length+(e.replace(/[\u4e00-\u9fa5]/g," ").match(/[a-zA-Z0-9]+/g)||[]).length,r=e?e.split("\n").length:0,i=Math.max(1,Math.ceil(n/300));this.statusEl.textContent=[`${b("characters")}: ${t}`,`${b("words")}: ${n}`,`${b("lines")}: ${r}`,`${b("readingTime")}: ${i} ${b("minutes")}`].join(" · ")}getStats(){const e=this._value||"",t=(e.match(/[\u4e00-\u9fa5]/g)||[]).length,n=(e.replace(/[\u4e00-\u9fa5]/g," ").match(/[a-zA-Z0-9]+/g)||[]).length;return{characters:e.length,words:t+n,chineseChars:t,englishWords:n,lines:e?e.split("\n").length:0,readingTime:Math.max(1,Math.ceil((t+n)/300))}}getSelectedText(){return this.textarea?this._value.slice(this.textarea.selectionStart,this.textarea.selectionEnd):""}getCursorPosition(){if(!this.textarea)return{line:1,column:0};const e=this.textarea.selectionStart,t=this._value.substring(0,e),n=t.split("\n").length,r=e-t.lastIndexOf("\n")-1;return{line:n,column:r<0?0:r}}setCursorPosition(e,t=0){if(!this.textarea)return this;const n=this._value.split("\n"),r=Math.max(1,Math.min(e,n.length));let i=0;for(let e=0;e=t.length?"":t[n]}getValue(){return this._destroyed?"":this._value}setValue(e,t={}){if(this._destroyed)return this;if(Ue.trigger("beforeChange",this),this._emit("beforeChange",this._value,e),this._value=e||"",this.textarea.value=this._value,t.silent||this._pushHistory(),this._render(),this._renderGutter(),this._updateWordCount(),this._updateOutline(),this.gutter&&(this.gutter.scrollTop=0),this.textarea.scrollTop=0,!t.silent&&(this._emit("change",this._value),"function"==typeof this.config.onChange))try{this.config.onChange(this._value,this)}catch(e){}return this._emit("afterChange",this._value),Ue.trigger("afterChange",this),this}getHTML(){Ue.trigger("beforeRender",this),this._emit("beforeRender",this);let e=this._renderFn(this._value,{highlight:this._highlightFn||void 0,locale:f()});if("function"==typeof this.config.sanitize)try{e=this.config.sanitize(e)}catch(e){}return Ue.trigger("afterRender",this),this._emit("afterRender",this),e}refresh(){return this._lastRenderedValue=null,this._render(),this}copyAsMarkdown(){return"undefined"!=typeof navigator&&navigator.clipboard&&navigator.clipboard.writeText(this._value).then(()=>this._emit("copy",{type:"markdown"})).catch(()=>{}),this}copyAsHTML(){const e=this.getHTML();if("undefined"!=typeof navigator&&navigator.clipboard){const t=new Blob([e],{type:"text/html"}),n=new ClipboardItem({"text/html":t,"text/plain":new Blob([this._value],{type:"text/plain"})});navigator.clipboard.write([n]).then(()=>this._emit("copy",{type:"html"})).catch(()=>{})}return this}insert(e,t={}){const n=this.textarea,r=n.selectionStart,i=n.selectionEnd;return n.value=n.value.slice(0,r)+e+n.value.slice(t.replace?i:r),n.focus(),n.selectionStart=n.selectionEnd=r+e.length,this._value=n.value,this._pushHistory(),this._render(),this._updateWordCount(),this._emit("change",this._value),this}wrap(e,t){return this._wrapSelection(e,t||e),this}focus(){return this.textarea&&this.textarea.focus(),this}blur(){return this.textarea&&this.textarea.blur(),this}enable(){return this.textarea&&(this.textarea.disabled=!1),this.el&&this.el.classList.remove("me-disabled"),this}disable(){return this.textarea&&(this.textarea.disabled=!0),this.el&&this.el.classList.add("me-disabled"),this}isDisabled(){return!!this.textarea&&this.textarea.disabled}setReadOnly(e){return this.config.readOnly=!!e,this.textarea&&(this.textarea.readOnly=!!e),this.el&&this.el.classList.toggle("me-readonly",!!e),this._updateModeButtons(),this}isReadOnly(){return!!this.config.readOnly}on(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),()=>this.off(e,t)}off(e,t){const n=this._listeners[e];return n&&(this._listeners[e]=n.filter(e=>e!==t)),this}_emit(e,...t){const n=this._listeners[e];n&&n.forEach(e=>{try{e(...t,this)}catch(e){}})}use(e,t={}){let n=e;if("string"==typeof e&&(n=ye[e],!n))return this;if(!n||"object"!=typeof n)return this;const r={...n,...t};if("function"==typeof r.install)try{const e=r.install(this,t);e&&"function"==typeof e.then&&e.catch(e=>{})}catch(e){}return this._plugins.push(r),this}unuse(e){const t=this._plugins.findIndex(t=>t.name===e);if(-1===t)return this;const n=this._plugins[t];if("function"==typeof n.destroy)try{n.destroy(this)}catch(e){}return this._plugins.splice(t,1),this}getPlugins(){return[...this._plugins]}addToolbarButton(e){if(!e||!e.action)return this;const n=document.createElement("button");return n.type="button",n.className=`me-btn me-btn-custom-${e.action}`,n.title=e.title||e.action,n.setAttribute("aria-label",e.title||e.action),n.innerHTML=e.icon||`${t(e.text||e.action)}`,"function"==typeof e.onClick?n.addEventListener("click",t=>{t.stopPropagation(),e.onClick(this)}):e.action&&(n.dataset.action=e.action,this._customActions=this._customActions||{},this._customActions[e.action]=e.handler),this.toolbarEl.insertBefore(n,this.toolbarEl.querySelector(".me-toolbar-group")||null),this}registerShortcut(e,t,n=""){if(!e)return this;const r=e.toLowerCase().split("+"),i=r.pop(),o=r.includes("ctrl")||r.includes("cmd"),s=r.includes("shift"),a=r.includes("alt"),l=r.includes("meta");return this._shortcuts.push({combo:e,key:i,ctrl:o,shift:s,alt:a,meta:l,handler:t,description:n}),this}unregisterShortcut(e){return this._shortcuts=this._shortcuts.filter(t=>t.combo!==e),this}getShortcuts(){return[...this._shortcuts]}configureToolbar(e){return this.toolbarEl?(this.config.toolbar=e,this.toolbarEl.innerHTML="",this._buildToolbar(),this):this}removeToolbarButton(e){if(!this.toolbarEl)return this;const t=this.toolbarEl.querySelector(`.me-btn[data-action="${e}"], .me-btn[data-mode="${e}"]`);return t&&t.remove(),this}registerContextMenu(e=[]){return this._contextMenuItems=e,this}_bindContextMenu(){if(!this.el)return;const e=e=>{const t=document.querySelector(".me-context-menu");t&&t.remove(),this._showContextMenu(e)};this.el.addEventListener("contextmenu",e),this._cleanups.push(()=>this.el.removeEventListener("contextmenu",e))}_showContextMenu(e){e.preventDefault();const t=this.textarea,n=t&&t.selectionStart!==t.selectionEnd,r=[{label:b("undo")||"Undo",action:"undo",shortcut:"Ctrl+Z",disabled:!this.canUndo()},{label:b("redo")||"Redo",action:"redo",shortcut:"Ctrl+Y",disabled:!this.canRedo()},{sep:!0},{label:b("cut")||"Cut",action:"cut",shortcut:"Ctrl+X",disabled:!n},{label:b("copy")||"Copy",action:"copy",shortcut:"Ctrl+C",disabled:!n},{label:b("paste")||"Paste",action:"paste",shortcut:"Ctrl+V",disabled:!!this.config.readOnly},{label:b("selectAll")||"Select All",action:"selectAll",shortcut:"Ctrl+A"}];this._contextMenuItems.length&&(r.push({sep:!0}),this._contextMenuItems.forEach(e=>r.push(e)));const i=document.createElement("div");i.className="me-context-menu",i.style.left=e.clientX+"px",i.style.top=e.clientY+"px",requestAnimationFrame(()=>{const t=i.getBoundingClientRect();t.right>window.innerWidth&&(i.style.left=e.clientX-t.width+"px"),t.bottom>window.innerHeight&&(i.style.top=e.clientY-t.height+"px")}),r.forEach(e=>{if(e.sep){const e=document.createElement("div");return e.className="me-context-menu-sep",void i.appendChild(e)}const t=document.createElement("div");t.className="me-context-menu-item",e.disabled&&t.classList.add("me-disabled"),t.innerHTML=`${e.label}${e.shortcut?``:""}`,t.addEventListener("click",t=>{t.stopPropagation(),e.disabled||(e.onClick?e.onClick():e.action&&this._execContextAction(e.action),this._hideContextMenu())}),i.appendChild(t)}),document.body.appendChild(i),document.addEventListener("click",e=>{i.contains(e.target)||this._hideContextMenu()},{once:!0}),document.addEventListener("keydown",e=>{"Escape"===e.key&&this._hideContextMenu()},{once:!0})}_hideContextMenu(){const e=document.querySelector(".me-context-menu");e&&e.remove()}_execContextAction(e){const t=this.textarea;if(t)switch(e){case"undo":this.undo();break;case"redo":this.redo();break;case"cut":document.execCommand("cut");break;case"copy":document.execCommand("copy");break;case"paste":document.execCommand("paste");break;case"selectAll":t.focus(),t.select();break;default:this.exec(e)}}toast(e,n={}){if(!this.el||"undefined"==typeof document)return this;const{type:r="info",duration:i=3e3,animation:o="fade"}=n,s=document.createElement("div");s.className=`me-toast me-toast-${r} me-toast-${o}`,s.innerHTML=`${qe[r]||""}${t(String(e))}`,this.el.appendChild(s),requestAnimationFrame(()=>{s.classList.add("me-toast-enter")});const a=()=>{s.classList.remove("me-toast-enter"),s.classList.add("me-toast-leave"),setTimeout(()=>{s.parentNode&&s.parentNode.removeChild(s)},300)};return i>0&&setTimeout(a,i),s.addEventListener("click",a),this}setLocale(e){return this._i18nCtx&&this._i18nCtx.set(e),this}getLocale(){return this._i18nCtx?this._i18nCtx.get():f()}t(e,t){return this._i18nCtx?this._i18nCtx.t(e,t):b(e,t)}setTheme(e){return e?(this.config.theme=e,this._themeCtx&&this._themeCtx.set(e),this):this}getTheme(){return this._themeCtx?this._themeCtx.get():this.config.theme||"auto"}getThemeContext(){return this._themeCtx||null}getStatus(){return{id:this.id,mode:this._mode,theme:this.getTheme(),locale:f(),fullscreen:this._fullscreen,readOnly:this.config.readOnly||!1,disabled:!!this.textarea&&this.textarea.disabled,destroyed:this._destroyed,plugins:this._plugins.map(e=>e.name||"custom")}}destroy(){if(!this._destroyed){if(Ue.trigger("beforeDestroy",this),this._renderRaf&&cancelAnimationFrame(this._renderRaf),this._historyTimer&&clearTimeout(this._historyTimer),this._outlineTimer&&clearTimeout(this._outlineTimer),this._selectionTimer&&(clearInterval(this._selectionTimer),this._selectionTimer=null),this._cleanups.forEach(e=>{try{e()}catch(e){}}),this._cleanups=[],this._shortcuts=[],this._contextMenuItems=[],this._customActions={},this._floatingToolbar&&this._floatingToolbar.parentNode&&this._floatingToolbar.parentNode.removeChild(this._floatingToolbar),this._floatingToolbar=null,this.el&&this.el.querySelectorAll(".me-toast").forEach(e=>e.remove()),this._plugins.forEach(e=>{if("function"==typeof e.destroy)try{e.destroy(this)}catch(e){}}),this._plugins=[],this.el&&this.el.parentNode&&this.el.parentNode.removeChild(this.el),this.el=null,this.textarea=null,this.previewEl=null,this._destroyed=!0,"function"==typeof this.config.onDestroy)try{this.config.onDestroy(this)}catch(e){}this._emit("destroy"),this._listeners={},Ue.trigger("afterDestroy",this)}}isDestroyed(){return this._destroyed}}Ue._hooks=new Map;const Ke=new Map;for(const[e,t]of Object.entries(a))Ke.set(e,t);const Ge={register(e,t){Ke.set(e,{name:e,enter:t.enter||{},leave:t.leave||{},duration:t.duration||300,easing:t.easing||"cubic-bezier(0.4, 0, 0.2, 1)"})},unregister(e){Ke.delete(e)},get:e=>Ke.get(e)||a[e]||null,getAnimationNames:()=>Array.from(Ke.keys()),getActiveCount:()=>0,cancelAll(){},reset(){Ke.clear();for(const[e,t]of Object.entries(a))Ke.set(e,t)},destroy(){Ke.clear()}},Ye="0.2.3",Ze=[];function Xe(e,t={}){return new Ue(e,t)}function Qe(e,t={}){let n=e;if("string"==typeof e&&(n=ye[e],!n))return ot;if(!n||"object"!=typeof n)return ot;const r=t&&"object"==typeof t&&Object.keys(t).length>0?{...n,...t}:n;return Ze.push(r),ot}function Je(e,t){return Ue.on(e,t)}function et(e,t){return Ue.off(e,t),ot}function tt(e,t){return Ne&&"function"==typeof Ne.switchTheme&&Ne.switchTheme(e),ot}function nt(e){return A&&"function"==typeof A.setCurrentLocale&&A.setCurrentLocale(e),ot}function rt(){if(Ne){try{Ne.clearThemeListeners()}catch(e){}try{Ne.unwatchSystemTheme()}catch(e){}}if(A)try{A.clearLocaleListeners()}catch(e){}if(Ge)try{Ge.cancelAll()}catch(e){}Ze.length=0}function it(){return{version:Ye,theme:Ne&&"function"==typeof Ne.getCurrentTheme?Ne.getCurrentTheme():"auto",locale:A&&"function"==typeof A.getCurrentLocale?A.getCurrentLocale():"zh-CN",globalPlugins:Ze.map(e=>e.name||"custom"),presetPlugins:Object.keys(ye||{})}}Ue.on("beforeCreate",e=>{e&&!e.isDestroyed()&&Ze.forEach(t=>{try{e.use(t)}catch(e){}})});try{"function"==typeof Ne.initTheme&&Ne.initTheme(),"function"==typeof A.initI18n&&A.initI18n()}catch(e){}const ot={VERSION:Ye,version:Ye,MarkdownEditor:Ue,Editor:Ue,create:Xe,use:Qe,on:Je,off:et,setTheme:tt,setLocale:nt,destroy:rt,getStatus:it,parseMarkdown:re,parseTokens:te,renderTokens:ne,safeUrl:Z,slugify:X,clearRenderCache:Y,registerBlockHandler:J,themes:Ne,i18n:A,animations:Ge,plugins:xe,presetPlugins:ye,topologicalSort:ve,validateConfig:be,createInstanceI18n:$,loadRemote:w,exportCSSVars:Me,getCSSVariable:$e,followExternalTheme:Re,adoptFromParent:De,createInstanceTheme:je,DEFAULTS:o,ICONS:n,THEMES:s,EDIT_MODES:l,DEFAULT_TOOLBAR:i,TOOLBAR_ACTIONS:c};"undefined"!=typeof window&&(window.MeEditor=ot),e.DEFAULTS=o,e.DEFAULT_TOOLBAR=i,e.EDIT_MODES=l,e.Editor=Ue,e.ICONS=n,e.MarkdownEditor=Ue,e.MeEditor=ot,e.THEMES=s,e.TOOLBAR_ACTIONS=c,e.VERSION=Ye,e.adoptFromParent=De,e.animationUtils=Ge,e.api=ot,e.clearRenderCache=Y,e.create=Xe,e.createInstanceI18n=$,e.createInstanceTheme=je,e.default=ot,e.destroy=rt,e.exportCSSVars=Me,e.followExternalTheme=Re,e.getCSSVariable=$e,e.getStatus=it,e.i18nUtils=A,e.loadRemote=w,e.meEditor=ot,e.off=et,e.on=Je,e.parseMarkdown=re,e.parseTokens=te,e.pluginUtils=xe,e.presetPlugins=ye,e.registerBlockHandler=J,e.renderTokens=ne,e.safeUrl=Z,e.setLocale=nt,e.setTheme=tt,e.slugify=X,e.themeUtils=Ne,e.topologicalSort=ve,e.use=Qe,e.validateConfig=be,Object.defineProperty(e,"__esModule",{value:!0})});
diff --git a/src/core.ts b/src/core.ts
index 0ef3a60..493792a 100644
--- a/src/core.ts
+++ b/src/core.ts
@@ -737,12 +737,17 @@ export class MarkdownEditor {
const paddingTop = parseInt(getComputedStyle(ta).paddingTop, 10) || 16;
const scrollOffset = ta.scrollTop;
- // Place toolbar just above the selected line (4px gap)
+ // Line top relative to textarea content area
+ const lineTop = rect.top + paddingTop + currentLine * lineHeight - scrollOffset;
const toolbarHeight = 36;
- let top = rect.top + paddingTop + currentLine * lineHeight - scrollOffset - toolbarHeight - 4;
- // Clamp: don't go above textarea
- if (top < rect.top) top = rect.top + 4;
- if (top + toolbarHeight > rect.bottom) top = rect.bottom - toolbarHeight - 4;
+ const gap = 4;
+
+ // Try above first
+ let top = lineTop - toolbarHeight - gap;
+ // If not enough room above, place below the selection
+ if (top < rect.top + gap) {
+ top = lineTop + lineHeight + gap;
+ }
// Center horizontally near the middle of selection
let left = rect.left + (ta.selectionDirection !== 'backward' ? (ta.selectionEnd - ta.selectionStart) / 2 : 0) * 8 + 10;