@editora/core 1.0.13 → 1.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,15 @@
1
- (function(P,$){typeof exports=="object"&&typeof module!="undefined"?$(exports):typeof define=="function"&&define.amd?define(["exports"],$):(P=typeof globalThis!="undefined"?globalThis:P||self,$(P.EditoraCore={}))})(this,(function(P){"use strict";class ${constructor(){this.loadedPlugins=new Map,this.pluginRegistry=new Map}register(e,t){this.pluginRegistry.set(e,t)}async load(e,t){if(this.loadedPlugins.has(e))return this.loadedPlugins.get(e);const n=this.pluginRegistry.get(e);if(!n)return console.warn(`Plugin not found: ${e}`),null;const i=await n();return t&&this.applyPluginConfig(i,t),this.loadedPlugins.set(e,i),i}async loadMultiple(e,t){return(await Promise.all(e.map(i=>this.load(i,t)))).filter(i=>i!==null)}async parsePluginString(e,t){const n=e.split(/\s+/).filter(Boolean);return this.loadMultiple(n,t)}applyPluginConfig(e,t){e.__pluginConfig=t}unload(e){this.loadedPlugins.delete(e)}clear(){this.loadedPlugins.clear()}getLoadedPlugins(){return Array.from(this.loadedPlugins.values())}getRegisteredPluginNames(){return Array.from(this.pluginRegistry.keys())}isLoaded(e){return this.loadedPlugins.has(e)}}class Q{constructor(e,t,n){this.doc=e,this.selection=t,this.schema=n}static create(e,t){const n=t||e.node("doc",{},[e.node("paragraph")]);return new Q(n,{anchor:0,head:0},e)}apply(e,t){return new Q(e,t||this.selection,this.schema)}}class wt{constructor(e,t){this.nodes=new Map(Object.entries(e)),this.marks=new Map(Object.entries(t))}node(e,t,n){return{type:e,attrs:t,content:n}}text(e,t){return{type:"text",text:e,marks:t}}}class Et{constructor(){this.plugins=[],this.pluginConfigs=new Map}register(e,t){this.plugins.push(e),t&&this.pluginConfigs.set(e.name,t);const n=this.pluginConfigs.get(e.name)||e.config;if(e.initialize)try{e.initialize(n)}catch(i){console.error(`Failed to initialize plugin "${e.name}":`,i)}if(e.init&&e.init!==e.initialize)try{e.init(n)}catch(i){console.error(`Failed to run init hook for plugin "${e.name}":`,i)}}unregister(e){const t=this.plugins.findIndex(n=>n.name===e);if(t>-1){const n=this.plugins[t];n.destroy&&n.destroy(),this.plugins.splice(t,1),this.pluginConfigs.delete(e)}}getPlugin(e){return this.plugins.find(t=>t.name===e)}getPluginConfig(e){return this.pluginConfigs.get(e)}buildSchema(){const e={},t={};return this.plugins.forEach(n=>{n.nodes&&Object.assign(e,n.nodes),n.marks&&Object.assign(t,n.marks)}),new wt(e,t)}getCommands(){const e={};return this.plugins.forEach(t=>{t.commands&&Object.assign(e,t.commands)}),e}getToolbarItems(){return this.plugins.flatMap(e=>e.toolbar||[])}async executePluginCommand(e,t,...n){const i=this.getPlugin(e);if(!i)throw new Error(`Plugin not found: ${e}`);const o=this.getPluginConfig(e)||i.config||{},r=o.mode||"local";try{switch(r){case"local":return i.executeLocal?i.executeLocal(t,...n):null;case"api":if(!i.executeAPI)throw new Error(`Plugin ${e} does not support API mode`);return await i.executeAPI(t,...n);case"hybrid":if(i.executeHybrid)return await i.executeHybrid(t,...n);try{if(i.executeAPI)return await i.executeAPI(t,...n)}catch(a){if(console.warn(`API execution failed for ${e}, falling back to local`,a),i.executeLocal&&o.fallbackToLocal!==!1)return i.executeLocal(t,...n);throw a}break;default:throw new Error(`Unknown plugin mode: ${r}`)}}catch(a){throw console.error(`Error executing command ${t} on plugin ${e}:`,a),a}}async destroyAll(){const e=this.plugins.filter(t=>t.destroy).map(t=>t.destroy());await Promise.all(e),this.plugins=[],this.pluginConfigs.clear()}}class Tt{constructor(e={}){this.commands=new Map,Object.entries(e).forEach(([t,n])=>{this.register(t,n)})}register(e,t){this.commands.has(e)&&console.warn(`Command ${e} is being overwritten`),this.commands.set(e,t)}unregister(e){this.commands.delete(e)}get(e){return this.commands.get(e)}has(e){return this.commands.has(e)}getCommandNames(){return Array.from(this.commands.keys())}clear(){this.commands.clear()}}class St{constructor(e={}){this.listeners=new Map,this.isReadonly=!1,this.isDestroyed=!1,this.isReadonly=e.readonly||!1,this.pluginManager=new Et,e.plugins&&Array.isArray(e.plugins)&&e.plugins.forEach(n=>this.pluginManager.register(n));const t=this.pluginManager.buildSchema();this.state=Q.create(t),this.commandRegistry=new Tt(this.pluginManager.getCommands())}execCommand(e,t){if(this.isReadonly)return console.warn("Cannot execute commands in readonly mode"),!1;if(this.isDestroyed)return console.warn("Cannot execute commands on destroyed editor"),!1;const n=this.commandRegistry.get(e);if(!n)return console.warn(`Command not found: ${e}`),!1;let i;return t!==void 0?i=n(this.state,t):i=n(this.state),i instanceof Promise?(i.then(o=>{o&&typeof o=="object"&&"doc"in o&&"selection"in o&&(this.setState(o),this.emit("change",this.state))}).catch(o=>{console.error(`Async command failed: ${e}`,o)}),!0):i&&typeof i=="object"&&"doc"in i&&"selection"in i?(this.setState(i),this.emit("change",this.state),!0):i!==!1&&i!=null}setState(e){this.isDestroyed||(this.state=e,this.emit("stateChange",e))}getState(){return this.state}setReadonly(e){this.isReadonly=e,this.emit("readonlyChange",e)}isReadOnly(){return this.isReadonly}on(e,t){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t),()=>{const n=this.listeners.get(e);if(n){const i=n.indexOf(t);i>-1&&n.splice(i,1)}}}emit(e,...t){const n=this.listeners.get(e);n&&n.forEach(i=>{try{i(...t)}catch(o){console.error(`Error in ${e} handler:`,o)}})}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.listeners.clear(),this.emit("destroy"))}isEditorDestroyed(){return this.isDestroyed}}class kt{setLastCommandTrigger(e,t){if(typeof window=="undefined"||!e)return;const n=t||e.getAttribute("data-command")||void 0;n&&(window.__editoraLastCommandButton=e,window.__editoraLastCommand=n)}constructor(e,t,n){this.config=e,this.plugins=t,this.pluginLoader=n}setCommandHandler(e){this.commandHandler=e}parseToolbarString(e){const t=[],n=e.split("|").map(a=>a.trim()),i=this.getAvailableToolbarItems(),o=new Map;i.forEach(a=>{a.command&&o.set(a.command,a),a.type==="group"&&a.label&&o.set(a.label,a)});const r={bold:"toggleBold",italic:"toggleItalic",underline:"toggleUnderline",strikethrough:"toggleStrikethrough",bullist:"toggleBulletList",numlist:"toggleOrderedList",checklist:"toggleChecklist",link:"openLinkDialog",image:"openImageDialog",table:"insertTable",trackChanges:"toggleTrackChanges",acceptTrackChanges:"acceptAllTrackChanges",rejectTrackChanges:"rejectAllTrackChanges",anchor:"insertAnchor",code:"toggleSourceView",blockquote:"toggleBlockquote",undo:"undo",redo:"redo",textColor:"openTextColorPicker",backgroundColor:"openBackgroundColorPicker",fontSize:"fontSize",fontFamily:"setFontFamily",lineHeight:"setLineHeight",heading:"setBlockType",paragraph:"setParagraph",textAlignment:"setTextAlignment",direction:"setDirectionLTR",indent:"increaseIndent",outdent:"decreaseIndent",capitalization:"setCapitalization",math:"insertMath",specialCharacters:"insertSpecialCharacter",emojis:"openEmojiDialog",embedIframe:"openEmbedIframeDialog",fullscreen:"toggleFullscreen",preview:"togglePreview",print:"print",a11yChecker:"toggleA11yChecker",spellCheck:"toggleSpellCheck",comments:"addComment",showHideComments:"toggleComments",toggleComments:"toggleComments",footnote:"insertFootnote",mergeTags:"insertMergeTag",dataBinding:"openDataBindingDialog",dataBindingPreview:"openDataBindingDialog",contentRules:"toggleContentRulesPanel",contentRulesAudit:"runContentRulesAudit",contentRulesRealtime:"toggleContentRulesRealtime",mention:"insertMention",slash:"openSlashCommands",slashCommands:"openSlashCommands",pageBreak:"insertPageBreak",template:"insertTemplate",importWord:"importWord",exportWord:"exportWord",exportPdf:"exportPdf",insertImage:"insertImage",insertVideo:"insertVideo",codeBlock:"insertCodeBlock"};return n.forEach(a=>{const l=[];a.split(/\s+/).filter(Boolean).forEach(h=>{if(h==="direction"){const g=o.get("setDirectionLTR"),f=o.get("setDirectionRTL");g&&l.push({id:"directionLTR",label:g.label,command:g.command,icon:g.icon,type:g.type||"button",options:g.options}),f&&l.push({id:"directionRTL",label:f.label,command:f.command,icon:f.icon,type:f.type||"button",options:f.options});return}if(h==="comments"){const g=o.get("addComment"),f=o.get("toggleComments");g&&l.push({id:"addComment",label:g.label,command:g.command,icon:g.icon,type:g.type||"button",options:g.options}),f&&l.push({id:"toggleComments",label:f.label,command:f.command,icon:f.icon,type:f.type||"button",options:f.options});return}const u=r[h]||h;let d=o.get(u);d||(d=o.get(h)),d&&l.push({id:h,label:d.label,command:d.command,icon:d.icon,type:d.type==="separator"?"separator":d.type||"button",options:d.options,items:d.items})}),l.length>0&&t.push(l)}),t}getAvailableToolbarItems(){return this.plugins.flatMap(t=>t.toolbar||[])}render(e){this.container=e,e.innerHTML="",e.className="editora-toolbar",this.config.sticky&&e.classList.add("editora-toolbar-sticky"),this.config.position&&e.classList.add(`editora-toolbar-${this.config.position}`);const t=this.config.items||this.getDefaultToolbarString(),n=this.parseToolbarString(t);n.forEach((i,o)=>{const r=document.createElement("div");if(r.className="editora-toolbar-group",i.forEach(a=>{this.appendToolbarButton(r,a)}),e.appendChild(r),o<n.length-1){const a=document.createElement("div");a.className="editora-toolbar-separator",e.appendChild(a)}})}appendToolbarButton(e,t){if(t.type==="separator"){const n=document.createElement("div");n.className="editora-toolbar-separator",e.appendChild(n)}else if(t.type==="dropdown"){const n=this.createDropdown(t);e.appendChild(n)}else if(t.type==="inline-menu"){const n=this.createInlineMenu(t);e.appendChild(n)}else if(t.type==="group"&&t.items&&t.items.length){const n=this.createGroupButton(t);e.appendChild(n)}else if(t.type==="input"){const n=this.createInput(t);e.appendChild(n)}else{const n=this.createButton(t);e.appendChild(n)}}createGroupButton(e){const t=document.createElement("div"),n=e.label.toLowerCase().replace(/\s+/g,"-");if(t.className=`editora-toolbar-group-button ${n}`,t.title=e.label,e.icon)if(e.icon.startsWith("<svg")&&e.icon.endsWith("</svg>")){const i=document.createElement("span");i.className="editora-toolbar-icon",i.innerHTML=e.icon,t.appendChild(i)}else t.innerHTML=e.icon;if(e.items&&e.items.length){const i=document.createElement("div");i.className=`editora-toolbar-group-items ${n}`,e.items.forEach(o=>{this.appendToolbarButton(i,o)}),t.appendChild(i)}return t}createInput(e){const t=document.createElement("input");return t.className=`editora-toolbar-input ${e.label.toLowerCase().replace(/\s+/g,"-")}`,t.type="text",t.title=e.label,t.placeholder=e.placeholder||"",e.command&&t.setAttribute("data-command",e.command),e.active&&t.classList.add("active"),e.disabled&&(t.disabled=!0),t.addEventListener("click",n=>{n.preventDefault(),this.setLastCommandTrigger(t,e.command),this.commandHandler&&e.command&&this.commandHandler(e.command)}),t}createButton(e){const t=document.createElement("button");if(t.className="editora-toolbar-button",t.type="button",t.title=e.label,e.command&&t.setAttribute("data-command",e.command),e.icon)if(e.icon.startsWith("<svg")&&e.icon.endsWith("</svg>")){const n=document.createElement("span");n.className="editora-toolbar-icon",n.innerHTML=e.icon,t.appendChild(n)}else t.innerHTML=e.icon;else t.textContent=e.label;return e.active&&t.classList.add("active"),e.disabled&&(t.disabled=!0),t.addEventListener("click",n=>{n.preventDefault(),this.commandHandler&&e.command&&this.commandHandler(e.command)}),t}createDropdown(e){const t=document.createElement("div");t.className="editora-toolbar-dropdown";const n=document.createElement("button");n.className="editora-toolbar-button editora-toolbar-dropdown-trigger",n.type="button",n.textContent=e.label;const i=document.createElement("div");i.className="editora-toolbar-dropdown-menu",i.style.display="none",e.options&&e.options.forEach(a=>{const l=document.createElement("button");l.className="editora-toolbar-dropdown-item",l.type="button",l.textContent=a.label,l.setAttribute("data-value",a.value),l.addEventListener("click",c=>{c.preventDefault(),this.setLastCommandTrigger(n,e.command),this.commandHandler&&e.command&&this.commandHandler(e.command,a.value),i.style.display="none"}),i.appendChild(l)}),n.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.setLastCommandTrigger(n,e.command);const l=i.style.display==="block";i.style.display=l?"none":"block"});const o=a=>{t.contains(a.target)||(i.style.display="none")},r=a=>{a.key==="Escape"&&(i.style.display="none")};return document.addEventListener("mousedown",o,!0),document.addEventListener("keydown",r),t._cleanupDropdown=()=>{document.removeEventListener("mousedown",o,!0),document.removeEventListener("keydown",r)},t.appendChild(n),t.appendChild(i),t}createInlineMenu(e){const t=document.createElement("div");t.className="editora-toolbar-dropdown editora-toolbar-inline-menu";const n=document.createElement("button");if(n.className="editora-toolbar-button",n.type="button",n.title=e.label,e.icon)if(e.icon.startsWith("<svg")&&e.icon.endsWith("</svg>")){const a=document.createElement("span");a.className="editora-toolbar-icon",a.innerHTML=e.icon,n.appendChild(a)}else n.innerHTML=e.icon;else n.textContent=e.label;const i=document.createElement("div");i.className="editora-toolbar-dropdown-menu",i.style.display="none",e.options&&e.options.forEach(a=>{const l=document.createElement("button");l.className="editora-toolbar-dropdown-item",l.type="button",l.textContent=a.label,l.setAttribute("data-value",a.value),l.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),this.setLastCommandTrigger(n,e.command),this.commandHandler&&e.command&&this.commandHandler(e.command,a.value),i.style.display="none"}),i.appendChild(l)}),n.addEventListener("click",a=>{var c;a.preventDefault(),a.stopPropagation(),this.setLastCommandTrigger(n,e.command);const l=(c=this.container)==null?void 0:c.querySelectorAll(".editora-toolbar-dropdown-menu");l==null||l.forEach(h=>{h!==i&&(h.style.display="none")}),i.style.display=i.style.display==="none"?"block":"none"});const o=a=>{t.contains(a.target)||(i.style.display="none")},r=a=>{a.key==="Escape"&&(i.style.display="none")};return document.addEventListener("mousedown",o,!0),document.addEventListener("keydown",r),t._cleanupDropdown=()=>{document.removeEventListener("mousedown",o,!0),document.removeEventListener("keydown",r)},t.appendChild(n),t.appendChild(i),t}getDefaultToolbarString(){return this.getAvailableToolbarItems().map(t=>t.command).join(" ")}updateButtonState(e,t){if(!this.container)return;const n=this.container.querySelector(`[data-command="${e}"]`);n&&(t.active!==void 0&&n.classList.toggle("active",t.active),t.disabled!==void 0&&(n.disabled=t.disabled))}destroy(){this.container&&(this.container.querySelectorAll(".editora-toolbar-dropdown").forEach(t=>{const n=t._cleanupDropdown;n&&n()}),this.container.innerHTML=""),this.commandHandler=void 0}}class Mt{constructor(e){this.visible=!1,this.config=e}create(e){const t=document.createElement("div");return t.className="editora-floating-toolbar",t.style.display="none",t.style.position="absolute",t.style.zIndex="1000",this.container=t,e.appendChild(t),t}show(e,t){this.container&&(this.container.style.display="block",this.container.style.left=`${e}px`,this.container.style.top=`${t}px`,this.visible=!0)}hide(){this.container&&(this.container.style.display="none",this.visible=!1)}updatePosition(e,t){!this.container||!this.visible||(this.container.style.left=`${e}px`,this.container.style.top=`${t}px`)}isVisible(){return this.visible}destroy(){this.container&&this.container.parentNode&&this.container.parentNode.removeChild(this.container),this.container=void 0,this.visible=!1}}class Lt{constructor(e={}){this.statusInfo={},this.config=e}create(e){const t=document.createElement("div");return t.className="editora-statusbar",this.config.position&&t.classList.add(`editora-statusbar-${this.config.position}`),this.container=t,e.appendChild(t),t}update(e){this.statusInfo={...this.statusInfo,...e},this.render()}render(){if(!this.container)return;this.container.innerHTML="";const e=document.createElement("div");e.className="editora-statusbar-left";const t=document.createElement("div");t.className="editora-statusbar-right";const n=[];if(this.statusInfo.selectionInfo){const o=this.statusInfo.selectionInfo;o.startLine===o.endLine&&o.startColumn===o.endColumn?n.push(`Ln ${o.startLine}, Col ${o.startColumn}`):(o.startLine===o.endLine?n.push(`Ln ${o.startLine}, Col ${o.startColumn}-${o.endColumn}`):n.push(`Ln ${o.startLine}:${o.startColumn} - ${o.endLine}:${o.endColumn}`),n.push(`${o.selectedChars} chars selected`))}else if(this.statusInfo.cursorPosition){const o=this.statusInfo.cursorPosition;n.push(`Ln ${o.line}, Col ${o.column}`)}this.statusInfo.language&&n.push(this.statusInfo.language);const i=[];this.statusInfo.wordCount!==void 0&&i.push(`${this.statusInfo.wordCount} words`),this.statusInfo.charCount!==void 0&&i.push(`${this.statusInfo.charCount} chars`),this.statusInfo.lineCount!==void 0&&i.push(`${this.statusInfo.lineCount} lines`),this.statusInfo.custom&&Object.entries(this.statusInfo.custom).forEach(([o,r])=>{i.push(`${o}: ${r}`)}),n.forEach((o,r)=>{const a=document.createElement("span");if(a.className="editora-statusbar-item",a.textContent=o,e.appendChild(a),r<n.length-1){const l=document.createElement("span");l.className="editora-statusbar-separator",l.textContent="|",e.appendChild(l)}}),i.forEach((o,r)=>{const a=document.createElement("span");if(a.className="editora-statusbar-item",a.textContent=o,t.appendChild(a),r<i.length-1){const l=document.createElement("span");l.className="editora-statusbar-separator",l.textContent="|",t.appendChild(l)}}),this.container.appendChild(e),this.container.appendChild(t)}destroy(){this.container&&this.container.parentNode&&this.container.parentNode.removeChild(this.container),this.container=void 0}}function At(s,e){const t=s.textContent||"",n=Rt(s,e.startContainer,e.startOffset),o=t.substring(0,n).split(`
2
- `),r=o.length,a=o[o.length-1].length+1;return{line:r,column:a}}function Rt(s,e,t){var r;let n=0;const i=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null);let o=i.firstChild();for(;o;){if(o===e){n+=t;break}else o.nodeType===Node.TEXT_NODE&&(n+=((r=o.textContent)==null?void 0:r.length)||0);o=i.nextNode()}return n}function It(s){var n,i;const e=s.querySelectorAll("div, p, br, h1, h2, h3, h4, h5, h6, blockquote, li, pre");let t=1;if(e.length>0){t=e.length;const o=e[e.length-1];(o.tagName==="BR"||((n=o.innerHTML)==null?void 0:n.trim())===""||((i=o.textContent)==null?void 0:i.trim())==="")&&t++}else{const r=(s.textContent||"").split(`
3
- `).length;t=Math.max(1,r)}return t}function Ht(s){const e=s.trim()?s.trim().split(/\s+/).length:0,t=s.length;return{words:e,chars:t}}function Ot(s,e){const t=s.toString();return{startLine:e.line,startColumn:e.column,endLine:e.line,endColumn:e.column+t.length,selectedChars:t.length,selectedWords:t.trim().split(/\s+/).filter(Boolean).length}}class Nt{constructor(e){this.shortcuts=new Map,this.enabled=!0,this.isMac=typeof navigator!="undefined"&&navigator.platform.toUpperCase().indexOf("MAC")>=0,(e==null?void 0:e.enabled)===!1&&(this.enabled=!1),this.registerDefaultShortcuts(),e!=null&&e.shortcuts&&e.shortcuts.forEach(t=>this.registerShortcut(t)),e!=null&&e.customShortcuts&&Object.values(e.customShortcuts).forEach(t=>{this.registerShortcut(t)})}registerDefaultShortcuts(){this.registerShortcut({key:"b",ctrl:!this.isMac,meta:this.isMac,command:"toggleBold",description:"Bold",preventDefault:!0}),this.registerShortcut({key:"i",ctrl:!this.isMac,meta:this.isMac,command:"toggleItalic",description:"Italic",preventDefault:!0}),this.registerShortcut({key:"u",ctrl:!this.isMac,meta:this.isMac,command:"toggleUnderline",description:"Underline",preventDefault:!0}),this.registerShortcut({key:"d",ctrl:!this.isMac,meta:this.isMac,command:"toggleStrikethrough",description:"Strikethrough",preventDefault:!0}),this.registerShortcut({key:"z",ctrl:!this.isMac,meta:this.isMac,command:"undo",description:"Undo",preventDefault:!0}),this.registerShortcut({key:"z",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"redo",description:"Redo",preventDefault:!0}),this.registerShortcut({key:"y",ctrl:!this.isMac,meta:this.isMac,command:"redo",description:"Redo",preventDefault:!0});for(let e=1;e<=6;e++)this.registerShortcut({key:String(e),ctrl:!this.isMac,meta:this.isMac,alt:!0,command:"setBlockType",params:`h${e}`,description:`Heading ${e}`,preventDefault:!0});this.registerShortcut({key:"7",ctrl:!this.isMac,meta:this.isMac,alt:!0,command:"setBlockType",params:"p",description:"Paragraph",preventDefault:!0}),this.registerShortcut({key:"7",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"toggleOrderedList",description:"Numbered List",preventDefault:!0}),this.registerShortcut({key:"8",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"toggleBulletList",description:"Bullet List",preventDefault:!0}),this.registerShortcut({key:"k",ctrl:!this.isMac,meta:this.isMac,command:"openLinkDialog",description:"Insert/Edit Link",preventDefault:!0}),this.registerShortcut({key:"e",ctrl:!this.isMac,meta:this.isMac,alt:!0,command:"insertCodeBlock",description:"Code Block",preventDefault:!0}),this.registerShortcut({key:"q",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"toggleBlockquote",description:"Blockquote",preventDefault:!0}),this.registerShortcut({key:"l",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"setTextAlignment",params:"left",description:"Align Left",preventDefault:!0}),this.registerShortcut({key:"e",ctrl:!this.isMac,meta:this.isMac,shift:!0,alt:!0,command:"setTextAlignment",params:"center",description:"Align Center",preventDefault:!0}),this.registerShortcut({key:"r",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"setTextAlignment",params:"right",description:"Align Right",preventDefault:!0}),this.registerShortcut({key:"j",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"setTextAlignment",params:"justify",description:"Justify",preventDefault:!0}),this.registerShortcut({key:"\\",ctrl:!this.isMac,meta:this.isMac,command:"clearFormatting",description:"Clear Formatting",preventDefault:!0}),this.registerShortcut({key:"]",ctrl:!this.isMac,meta:this.isMac,command:"increaseIndent",description:"Indent",preventDefault:!0}),this.registerShortcut({key:"[",ctrl:!this.isMac,meta:this.isMac,command:"decreaseIndent",description:"Outdent",preventDefault:!0}),this.registerShortcut({key:"g",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"insertImage",description:"Insert Image",preventDefault:!0}),this.registerShortcut({key:"t",ctrl:!this.isMac,meta:this.isMac,shift:!0,alt:!0,command:"insertTable",description:"Insert Table",preventDefault:!0}),this.registerShortcut({key:"f11",command:"toggleFullscreen",description:"Toggle Fullscreen",preventDefault:!0}),this.registerShortcut({key:"p",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"togglePreview",description:"Preview",preventDefault:!0}),this.registerShortcut({key:"p",ctrl:!this.isMac,meta:this.isMac,command:"print",description:"Print",preventDefault:!0}),this.registerShortcut({key:"s",ctrl:!this.isMac,meta:this.isMac,shift:!0,alt:!0,command:"insertSpecialCharacter",description:"Insert Special Character",preventDefault:!0}),this.registerShortcut({key:"m",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"insertEmoji",description:"Insert Emoji",preventDefault:!0}),this.registerShortcut({key:"9",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"toggleChecklist",description:"Checklist",preventDefault:!0}),this.registerShortcut({key:"a",ctrl:!this.isMac,meta:this.isMac,shift:!0,alt:!0,command:"toggleA11yChecker",description:"Accessibility Checker",preventDefault:!0}),this.registerShortcut({key:"F7",command:"toggleSpellCheck",description:"Spell Check",preventDefault:!0}),this.registerShortcut({key:"m",ctrl:!this.isMac,meta:this.isMac,alt:!0,command:"insertMath",description:"Insert Math",preventDefault:!0}),this.registerShortcut({key:"f",ctrl:!this.isMac,meta:this.isMac,alt:!0,command:"insertFootnote",description:"Insert Footnote",preventDefault:!0})}registerShortcut(e){const t=this.getShortcutKey(e);this.shortcuts.set(t,e)}unregisterShortcut(e){const t=this.getShortcutKey(e);this.shortcuts.delete(t)}getShortcutKey(e){const t=[];return e.ctrl&&t.push("ctrl"),e.alt&&t.push("alt"),e.shift&&t.push("shift"),e.meta&&t.push("meta"),t.push(e.key.toLowerCase()),t.join("+")}getEventKey(e){const t=[];return e.ctrlKey&&t.push("ctrl"),e.altKey&&t.push("alt"),e.shiftKey&&t.push("shift"),e.metaKey&&t.push("meta"),t.push(e.key.toLowerCase()),t.join("+")}handleKeyDown(e,t){if(!this.enabled)return!1;const n=this.getEventKey(e),i=this.shortcuts.get(n);return i?(i.preventDefault!==!1&&(e.preventDefault(),e.stopPropagation()),t(i.command,i.params),!0):!1}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}getAllShortcuts(){return Array.from(this.shortcuts.values())}getShortcutForCommand(e){return Array.from(this.shortcuts.values()).find(t=>t.command===e)}getShortcutDescription(e){const t=[];this.isMac?(e.meta&&t.push("⌘"),e.ctrl&&t.push("⌃"),e.alt&&t.push("⌥"),e.shift&&t.push("⇧")):(e.ctrl&&t.push("Ctrl"),e.alt&&t.push("Alt"),e.shift&&t.push("Shift"));const n=e.key.length===1?e.key.toUpperCase():e.key;return t.push(n),t.join("+")}getShortcutsHelp(){const e=this.getAllShortcuts(),t=new Map;e.forEach(i=>{const o=this.getShortcutCategory(i.command);t.has(o)||t.set(o,[]),t.get(o).push(i)});let n=`# Keyboard Shortcuts
1
+ (function($,F){typeof exports=="object"&&typeof module!="undefined"?F(exports):typeof define=="function"&&define.amd?define(["exports"],F):($=typeof globalThis!="undefined"?globalThis:$||self,F($.EditoraCore={}))})(this,(function($){"use strict";class F{constructor(){this.loadedPlugins=new Map,this.pluginRegistry=new Map}register(e,t){this.pluginRegistry.set(e,t)}async load(e,t){if(this.loadedPlugins.has(e))return this.loadedPlugins.get(e);const n=this.pluginRegistry.get(e);if(!n)return console.warn(`Plugin not found: ${e}`),null;const i=await n();return t&&this.applyPluginConfig(i,t),this.loadedPlugins.set(e,i),i}async loadMultiple(e,t){return(await Promise.all(e.map(i=>this.load(i,t)))).filter(i=>i!==null)}async parsePluginString(e,t){const n=e.split(/\s+/).filter(Boolean);return this.loadMultiple(n,t)}applyPluginConfig(e,t){e.__pluginConfig=t}unload(e){this.loadedPlugins.delete(e)}clear(){this.loadedPlugins.clear()}getLoadedPlugins(){return Array.from(this.loadedPlugins.values())}getRegisteredPluginNames(){return Array.from(this.pluginRegistry.keys())}isLoaded(e){return this.loadedPlugins.has(e)}}class X{constructor(e,t,n){this.doc=e,this.selection=t,this.schema=n}static create(e,t){const n=t||e.node("doc",{},[e.node("paragraph")]);return new X(n,{anchor:0,head:0},e)}apply(e,t){return new X(e,t||this.selection,this.schema)}}class Ct{constructor(e,t){this.nodes=new Map(Object.entries(e)),this.marks=new Map(Object.entries(t))}node(e,t,n){return{type:e,attrs:t,content:n}}text(e,t){return{type:"text",text:e,marks:t}}}class Et{constructor(){this.plugins=[],this.pluginConfigs=new Map}register(e,t){this.plugins.push(e),t&&this.pluginConfigs.set(e.name,t);const n=this.pluginConfigs.get(e.name)||e.config;if(e.initialize)try{e.initialize(n)}catch(i){console.error(`Failed to initialize plugin "${e.name}":`,i)}if(e.init&&e.init!==e.initialize)try{e.init(n)}catch(i){console.error(`Failed to run init hook for plugin "${e.name}":`,i)}}unregister(e){const t=this.plugins.findIndex(n=>n.name===e);if(t>-1){const n=this.plugins[t];n.destroy&&n.destroy(),this.plugins.splice(t,1),this.pluginConfigs.delete(e)}}getPlugin(e){return this.plugins.find(t=>t.name===e)}getPluginConfig(e){return this.pluginConfigs.get(e)}buildSchema(){const e={},t={};return this.plugins.forEach(n=>{n.nodes&&Object.assign(e,n.nodes),n.marks&&Object.assign(t,n.marks)}),new Ct(e,t)}getCommands(){const e={};return this.plugins.forEach(t=>{t.commands&&Object.assign(e,t.commands)}),e}getToolbarItems(){return this.plugins.flatMap(e=>e.toolbar||[])}async executePluginCommand(e,t,...n){const i=this.getPlugin(e);if(!i)throw new Error(`Plugin not found: ${e}`);const o=this.getPluginConfig(e)||i.config||{},r=o.mode||"local";try{switch(r){case"local":return i.executeLocal?i.executeLocal(t,...n):null;case"api":if(!i.executeAPI)throw new Error(`Plugin ${e} does not support API mode`);return await i.executeAPI(t,...n);case"hybrid":if(i.executeHybrid)return await i.executeHybrid(t,...n);try{if(i.executeAPI)return await i.executeAPI(t,...n)}catch(a){if(console.warn(`API execution failed for ${e}, falling back to local`,a),i.executeLocal&&o.fallbackToLocal!==!1)return i.executeLocal(t,...n);throw a}break;default:throw new Error(`Unknown plugin mode: ${r}`)}}catch(a){throw console.error(`Error executing command ${t} on plugin ${e}:`,a),a}}async destroyAll(){const e=this.plugins.filter(t=>t.destroy).map(t=>t.destroy());await Promise.all(e),this.plugins=[],this.pluginConfigs.clear()}}class Tt{constructor(e={}){this.commands=new Map,Object.entries(e).forEach(([t,n])=>{this.register(t,n)})}register(e,t){this.commands.has(e)&&console.warn(`Command ${e} is being overwritten`),this.commands.set(e,t)}unregister(e){this.commands.delete(e)}get(e){return this.commands.get(e)}has(e){return this.commands.has(e)}getCommandNames(){return Array.from(this.commands.keys())}clear(){this.commands.clear()}}class St{constructor(e={}){this.listeners=new Map,this.isReadonly=!1,this.isDestroyed=!1,this.isReadonly=e.readonly||!1,this.pluginManager=new Et,e.plugins&&Array.isArray(e.plugins)&&e.plugins.forEach(n=>this.pluginManager.register(n));const t=this.pluginManager.buildSchema();this.state=X.create(t),this.commandRegistry=new Tt(this.pluginManager.getCommands())}execCommand(e,...t){if(this.isReadonly)return console.warn("Cannot execute commands in readonly mode"),!1;if(this.isDestroyed)return console.warn("Cannot execute commands on destroyed editor"),!1;const n=this.commandRegistry.get(e);if(!n)return console.warn(`Command not found: ${e}`),!1;let i;return t.length===0?i=n(this.state):t.length===1?i=n(this.state,t[0]):i=n(this.state,...t),i instanceof Promise?(i.then(o=>{o&&typeof o=="object"&&"doc"in o&&"selection"in o&&(this.setState(o),this.emit("change",this.state))}).catch(o=>{console.error(`Async command failed: ${e}`,o)}),!0):i&&typeof i=="object"&&"doc"in i&&"selection"in i?(this.setState(i),this.emit("change",this.state),!0):i!==!1&&i!=null}setState(e){this.isDestroyed||(this.state=e,this.emit("stateChange",e))}getState(){return this.state}setReadonly(e){this.isReadonly=e,this.emit("readonlyChange",e)}isReadOnly(){return this.isReadonly}on(e,t){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t),()=>{const n=this.listeners.get(e);if(n){const i=n.indexOf(t);i>-1&&n.splice(i,1)}}}emit(e,...t){const n=this.listeners.get(e);n&&n.forEach(i=>{try{i(...t)}catch(o){console.error(`Error in ${e} handler:`,o)}})}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.listeners.clear(),this.emit("destroy"))}isEditorDestroyed(){return this.isDestroyed}}class kt{setLastCommandTrigger(e,t){if(typeof window=="undefined"||!e)return;const n=t||e.getAttribute("data-command")||void 0;n&&(window.__editoraLastCommandButton=e,window.__editoraLastCommand=n)}constructor(e,t,n){this.config=e,this.plugins=t,this.pluginLoader=n}setCommandHandler(e){this.commandHandler=e}parseToolbarString(e){const t=[],n=e.split("|").map(a=>a.trim()),i=this.getAvailableToolbarItems(),o=new Map;i.forEach(a=>{a.command&&o.set(a.command,a),a.type==="group"&&a.label&&o.set(a.label,a)});const r={bold:"toggleBold",italic:"toggleItalic",underline:"toggleUnderline",strikethrough:"toggleStrikethrough",bullist:"toggleBulletList",numlist:"toggleOrderedList",checklist:"toggleChecklist",link:"openLinkDialog",image:"openImageDialog",table:"insertTable",trackChanges:"toggleTrackChanges",acceptTrackChanges:"acceptAllTrackChanges",rejectTrackChanges:"rejectAllTrackChanges",anchor:"insertAnchor",code:"toggleSourceView",blockquote:"toggleBlockquote",undo:"undo",redo:"redo",textColor:"openTextColorPicker",backgroundColor:"openBackgroundColorPicker",fontSize:"fontSize",fontFamily:"setFontFamily",lineHeight:"setLineHeight",heading:"setBlockType",paragraph:"setParagraph",textAlignment:"setTextAlignment",direction:"setDirectionLTR",indent:"increaseIndent",outdent:"decreaseIndent",capitalization:"setCapitalization",math:"insertMath",specialCharacters:"insertSpecialCharacter",emojis:"openEmojiDialog",embedIframe:"openEmbedIframeDialog",fullscreen:"toggleFullscreen",preview:"togglePreview",print:"print",a11yChecker:"toggleA11yChecker",spellCheck:"toggleSpellCheck",comments:"addComment",showHideComments:"toggleComments",toggleComments:"toggleComments",footnote:"insertFootnote",mergeTags:"insertMergeTag",dataBinding:"openDataBindingDialog",dataBindingPreview:"openDataBindingDialog",contentRules:"toggleContentRulesPanel",contentRulesAudit:"runContentRulesAudit",contentRulesRealtime:"toggleContentRulesRealtime",mention:"insertMention",slash:"openSlashCommands",slashCommands:"openSlashCommands",pageBreak:"insertPageBreak",template:"insertTemplate",importWord:"importWord",exportWord:"exportWord",exportPdf:"exportPdf",insertImage:"insertImage",insertVideo:"insertVideo",codeBlock:"insertCodeBlock"};return n.forEach(a=>{const l=[];a.split(/\s+/).filter(Boolean).forEach(h=>{if(h==="direction"){const p=o.get("setDirectionLTR"),u=o.get("setDirectionRTL");p&&l.push({id:"directionLTR",label:p.label,command:p.command,icon:p.icon,type:p.type||"button",options:p.options}),u&&l.push({id:"directionRTL",label:u.label,command:u.command,icon:u.icon,type:u.type||"button",options:u.options});return}if(h==="comments"){const p=o.get("addComment"),u=o.get("toggleComments");p&&l.push({id:"addComment",label:p.label,command:p.command,icon:p.icon,type:p.type||"button",options:p.options}),u&&l.push({id:"toggleComments",label:u.label,command:u.command,icon:u.icon,type:u.type||"button",options:u.options});return}const d=r[h]||h;let f=o.get(d);f||(f=o.get(h)),f&&l.push({id:h,label:f.label,command:f.command,icon:f.icon,type:f.type==="separator"?"separator":f.type||"button",options:f.options,items:f.items})}),l.length>0&&t.push(l)}),t}getAvailableToolbarItems(){return this.plugins.flatMap(t=>t.toolbar||[])}render(e){this.container=e,e.innerHTML="",e.className="editora-toolbar",this.config.sticky&&e.classList.add("editora-toolbar-sticky"),this.config.position&&e.classList.add(`editora-toolbar-${this.config.position}`);const t=this.config.items||this.getDefaultToolbarString(),n=this.parseToolbarString(t);n.forEach((i,o)=>{const r=document.createElement("div");if(r.className="editora-toolbar-group",i.forEach(a=>{this.appendToolbarButton(r,a)}),e.appendChild(r),o<n.length-1){const a=document.createElement("div");a.className="editora-toolbar-separator",e.appendChild(a)}})}appendToolbarButton(e,t){if(t.type==="separator"){const n=document.createElement("div");n.className="editora-toolbar-separator",e.appendChild(n)}else if(t.type==="dropdown"){const n=this.createDropdown(t);e.appendChild(n)}else if(t.type==="inline-menu"){const n=this.createInlineMenu(t);e.appendChild(n)}else if(t.type==="group"&&t.items&&t.items.length){const n=this.createGroupButton(t);e.appendChild(n)}else if(t.type==="input"){const n=this.createInput(t);e.appendChild(n)}else{const n=this.createButton(t);e.appendChild(n)}}createGroupButton(e){const t=document.createElement("div"),n=e.label.toLowerCase().replace(/\s+/g,"-");if(t.className=`editora-toolbar-group-button ${n}`,t.title=e.label,e.icon)if(e.icon.startsWith("<svg")&&e.icon.endsWith("</svg>")){const i=document.createElement("span");i.className="editora-toolbar-icon",i.innerHTML=e.icon,t.appendChild(i)}else t.innerHTML=e.icon;if(e.items&&e.items.length){const i=document.createElement("div");i.className=`editora-toolbar-group-items ${n}`,e.items.forEach(o=>{this.appendToolbarButton(i,o)}),t.appendChild(i)}return t}createInput(e){const t=document.createElement("input");return t.className=`editora-toolbar-input ${e.label.toLowerCase().replace(/\s+/g,"-")}`,t.type="text",t.title=e.label,t.placeholder=e.placeholder||"",e.command&&t.setAttribute("data-command",e.command),e.active&&t.classList.add("active"),e.disabled&&(t.disabled=!0),t.addEventListener("click",n=>{n.preventDefault(),this.setLastCommandTrigger(t,e.command),this.commandHandler&&e.command&&this.commandHandler(e.command)}),t}createButton(e){const t=document.createElement("button");if(t.className="editora-toolbar-button",t.type="button",t.title=e.label,e.command&&t.setAttribute("data-command",e.command),e.icon)if(e.icon.startsWith("<svg")&&e.icon.endsWith("</svg>")){const n=document.createElement("span");n.className="editora-toolbar-icon",n.innerHTML=e.icon,t.appendChild(n)}else t.innerHTML=e.icon;else t.textContent=e.label;return e.active&&t.classList.add("active"),e.disabled&&(t.disabled=!0),t.addEventListener("click",n=>{n.preventDefault(),this.commandHandler&&e.command&&this.commandHandler(e.command)}),t}createDropdown(e){const t=document.createElement("div");t.className="editora-toolbar-dropdown";const n=document.createElement("button");n.className="editora-toolbar-button editora-toolbar-dropdown-trigger",n.type="button",n.textContent=e.label;const i=document.createElement("div");i.className="editora-toolbar-dropdown-menu",i.style.display="none",e.options&&e.options.forEach(a=>{const l=document.createElement("button");l.className="editora-toolbar-dropdown-item",l.type="button",l.textContent=a.label,l.setAttribute("data-value",a.value),l.addEventListener("click",c=>{c.preventDefault(),this.setLastCommandTrigger(n,e.command),this.commandHandler&&e.command&&this.commandHandler(e.command,a.value),i.style.display="none"}),i.appendChild(l)}),n.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.setLastCommandTrigger(n,e.command);const l=i.style.display==="block";i.style.display=l?"none":"block"});const o=a=>{t.contains(a.target)||(i.style.display="none")},r=a=>{a.key==="Escape"&&(i.style.display="none")};return document.addEventListener("mousedown",o,!0),document.addEventListener("keydown",r),t._cleanupDropdown=()=>{document.removeEventListener("mousedown",o,!0),document.removeEventListener("keydown",r)},t.appendChild(n),t.appendChild(i),t}createInlineMenu(e){const t=document.createElement("div");t.className="editora-toolbar-dropdown editora-toolbar-inline-menu";const n=document.createElement("button");if(n.className="editora-toolbar-button",n.type="button",n.title=e.label,e.icon)if(e.icon.startsWith("<svg")&&e.icon.endsWith("</svg>")){const a=document.createElement("span");a.className="editora-toolbar-icon",a.innerHTML=e.icon,n.appendChild(a)}else n.innerHTML=e.icon;else n.textContent=e.label;const i=document.createElement("div");i.className="editora-toolbar-dropdown-menu",i.style.display="none",e.options&&e.options.forEach(a=>{const l=document.createElement("button");l.className="editora-toolbar-dropdown-item",l.type="button",l.textContent=a.label,l.setAttribute("data-value",a.value),l.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),this.setLastCommandTrigger(n,e.command),this.commandHandler&&e.command&&this.commandHandler(e.command,a.value),i.style.display="none"}),i.appendChild(l)}),n.addEventListener("click",a=>{var c;a.preventDefault(),a.stopPropagation(),this.setLastCommandTrigger(n,e.command);const l=(c=this.container)==null?void 0:c.querySelectorAll(".editora-toolbar-dropdown-menu");l==null||l.forEach(h=>{h!==i&&(h.style.display="none")}),i.style.display=i.style.display==="none"?"block":"none"});const o=a=>{t.contains(a.target)||(i.style.display="none")},r=a=>{a.key==="Escape"&&(i.style.display="none")};return document.addEventListener("mousedown",o,!0),document.addEventListener("keydown",r),t._cleanupDropdown=()=>{document.removeEventListener("mousedown",o,!0),document.removeEventListener("keydown",r)},t.appendChild(n),t.appendChild(i),t}getDefaultToolbarString(){return this.getAvailableToolbarItems().map(t=>t.command).join(" ")}updateButtonState(e,t){if(!this.container)return;const n=this.container.querySelector(`[data-command="${e}"]`);n&&(t.active!==void 0&&n.classList.toggle("active",t.active),t.disabled!==void 0&&(n.disabled=t.disabled))}destroy(){this.container&&(this.container.querySelectorAll(".editora-toolbar-dropdown").forEach(t=>{const n=t._cleanupDropdown;n&&n()}),this.container.innerHTML=""),this.commandHandler=void 0}}class Mt{constructor(e){this.visible=!1,this.config=e}create(e){const t=document.createElement("div");return t.className="editora-floating-toolbar",t.style.display="none",t.style.position="absolute",t.style.zIndex="1000",this.container=t,e.appendChild(t),t}show(e,t){this.container&&(this.container.style.display="block",this.container.style.left=`${e}px`,this.container.style.top=`${t}px`,this.visible=!0)}hide(){this.container&&(this.container.style.display="none",this.visible=!1)}updatePosition(e,t){!this.container||!this.visible||(this.container.style.left=`${e}px`,this.container.style.top=`${t}px`)}isVisible(){return this.visible}destroy(){this.container&&this.container.parentNode&&this.container.parentNode.removeChild(this.container),this.container=void 0,this.visible=!1}}class Lt{constructor(e={}){this.statusInfo={},this.config=e}create(e){const t=document.createElement("div");return t.className="editora-statusbar",this.config.position&&t.classList.add(`editora-statusbar-${this.config.position}`),this.container=t,e.appendChild(t),t}update(e){this.statusInfo={...this.statusInfo,...e},this.render()}render(){if(!this.container)return;this.container.innerHTML="";const e=document.createElement("div");e.className="editora-statusbar-left";const t=document.createElement("div");t.className="editora-statusbar-right";const n=[];if(this.statusInfo.selectionInfo){const o=this.statusInfo.selectionInfo;o.startLine===o.endLine&&o.startColumn===o.endColumn?n.push(`Ln ${o.startLine}, Col ${o.startColumn}`):(o.startLine===o.endLine?n.push(`Ln ${o.startLine}, Col ${o.startColumn}-${o.endColumn}`):n.push(`Ln ${o.startLine}:${o.startColumn} - ${o.endLine}:${o.endColumn}`),n.push(`${o.selectedChars} chars selected`))}else if(this.statusInfo.cursorPosition){const o=this.statusInfo.cursorPosition;n.push(`Ln ${o.line}, Col ${o.column}`)}this.statusInfo.language&&n.push(this.statusInfo.language);const i=[];this.statusInfo.wordCount!==void 0&&i.push(`${this.statusInfo.wordCount} words`),this.statusInfo.charCount!==void 0&&i.push(`${this.statusInfo.charCount} chars`),this.statusInfo.lineCount!==void 0&&i.push(`${this.statusInfo.lineCount} lines`),this.statusInfo.custom&&Object.entries(this.statusInfo.custom).forEach(([o,r])=>{i.push(`${o}: ${r}`)}),n.forEach((o,r)=>{const a=document.createElement("span");if(a.className="editora-statusbar-item",a.textContent=o,e.appendChild(a),r<n.length-1){const l=document.createElement("span");l.className="editora-statusbar-separator",l.textContent="|",e.appendChild(l)}}),i.forEach((o,r)=>{const a=document.createElement("span");if(a.className="editora-statusbar-item",a.textContent=o,t.appendChild(a),r<i.length-1){const l=document.createElement("span");l.className="editora-statusbar-separator",l.textContent="|",t.appendChild(l)}}),this.container.appendChild(e),this.container.appendChild(t)}destroy(){this.container&&this.container.parentNode&&this.container.parentNode.removeChild(this.container),this.container=void 0}}function Rt(s,e){const t=s.textContent||"",n=At(s,e.startContainer,e.startOffset),o=t.substring(0,n).split(`
2
+ `),r=o.length,a=o[o.length-1].length+1;return{line:r,column:a}}function At(s,e,t){var r;let n=0;const i=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null);let o=i.firstChild();for(;o;){if(o===e){n+=t;break}else o.nodeType===Node.TEXT_NODE&&(n+=((r=o.textContent)==null?void 0:r.length)||0);o=i.nextNode()}return n}function It(s){var n,i;const e=s.querySelectorAll("div, p, br, h1, h2, h3, h4, h5, h6, blockquote, li, pre");let t=1;if(e.length>0){t=e.length;const o=e[e.length-1];(o.tagName==="BR"||((n=o.innerHTML)==null?void 0:n.trim())===""||((i=o.textContent)==null?void 0:i.trim())==="")&&t++}else{const r=(s.textContent||"").split(`
3
+ `).length;t=Math.max(1,r)}return t}function Ot(s){const e=s.trim()?s.trim().split(/\s+/).length:0,t=s.length;return{words:e,chars:t}}function Ht(s,e){const t=s.toString();return{startLine:e.line,startColumn:e.column,endLine:e.line,endColumn:e.column+t.length,selectedChars:t.length,selectedWords:t.trim().split(/\s+/).filter(Boolean).length}}class Nt{constructor(e){this.shortcuts=new Map,this.enabled=!0,this.isMac=typeof navigator!="undefined"&&navigator.platform.toUpperCase().indexOf("MAC")>=0,(e==null?void 0:e.enabled)===!1&&(this.enabled=!1),this.registerDefaultShortcuts(),e!=null&&e.shortcuts&&e.shortcuts.forEach(t=>this.registerShortcut(t)),e!=null&&e.customShortcuts&&Object.values(e.customShortcuts).forEach(t=>{this.registerShortcut(t)})}registerDefaultShortcuts(){this.registerShortcut({key:"b",ctrl:!this.isMac,meta:this.isMac,command:"toggleBold",description:"Bold",preventDefault:!0}),this.registerShortcut({key:"i",ctrl:!this.isMac,meta:this.isMac,command:"toggleItalic",description:"Italic",preventDefault:!0}),this.registerShortcut({key:"u",ctrl:!this.isMac,meta:this.isMac,command:"toggleUnderline",description:"Underline",preventDefault:!0}),this.registerShortcut({key:"d",ctrl:!this.isMac,meta:this.isMac,command:"toggleStrikethrough",description:"Strikethrough",preventDefault:!0}),this.registerShortcut({key:"z",ctrl:!this.isMac,meta:this.isMac,command:"undo",description:"Undo",preventDefault:!0}),this.registerShortcut({key:"z",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"redo",description:"Redo",preventDefault:!0}),this.registerShortcut({key:"y",ctrl:!this.isMac,meta:this.isMac,command:"redo",description:"Redo",preventDefault:!0});for(let e=1;e<=6;e++)this.registerShortcut({key:String(e),ctrl:!this.isMac,meta:this.isMac,alt:!0,command:"setBlockType",params:`h${e}`,description:`Heading ${e}`,preventDefault:!0});this.registerShortcut({key:"7",ctrl:!this.isMac,meta:this.isMac,alt:!0,command:"setBlockType",params:"p",description:"Paragraph",preventDefault:!0}),this.registerShortcut({key:"7",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"toggleOrderedList",description:"Numbered List",preventDefault:!0}),this.registerShortcut({key:"8",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"toggleBulletList",description:"Bullet List",preventDefault:!0}),this.registerShortcut({key:"k",ctrl:!this.isMac,meta:this.isMac,command:"openLinkDialog",description:"Insert/Edit Link",preventDefault:!0}),this.registerShortcut({key:"e",ctrl:!this.isMac,meta:this.isMac,alt:!0,command:"insertCodeBlock",description:"Code Block",preventDefault:!0}),this.registerShortcut({key:"q",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"toggleBlockquote",description:"Blockquote",preventDefault:!0}),this.registerShortcut({key:"l",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"setTextAlignment",params:"left",description:"Align Left",preventDefault:!0}),this.registerShortcut({key:"e",ctrl:!this.isMac,meta:this.isMac,shift:!0,alt:!0,command:"setTextAlignment",params:"center",description:"Align Center",preventDefault:!0}),this.registerShortcut({key:"r",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"setTextAlignment",params:"right",description:"Align Right",preventDefault:!0}),this.registerShortcut({key:"j",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"setTextAlignment",params:"justify",description:"Justify",preventDefault:!0}),this.registerShortcut({key:"\\",ctrl:!this.isMac,meta:this.isMac,command:"clearFormatting",description:"Clear Formatting",preventDefault:!0}),this.registerShortcut({key:"]",ctrl:!this.isMac,meta:this.isMac,command:"increaseIndent",description:"Indent",preventDefault:!0}),this.registerShortcut({key:"[",ctrl:!this.isMac,meta:this.isMac,command:"decreaseIndent",description:"Outdent",preventDefault:!0}),this.registerShortcut({key:"g",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"insertImage",description:"Insert Image",preventDefault:!0}),this.registerShortcut({key:"t",ctrl:!this.isMac,meta:this.isMac,shift:!0,alt:!0,command:"insertTable",description:"Insert Table",preventDefault:!0}),this.registerShortcut({key:"f11",command:"toggleFullscreen",description:"Toggle Fullscreen",preventDefault:!0}),this.registerShortcut({key:"p",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"togglePreview",description:"Preview",preventDefault:!0}),this.registerShortcut({key:"p",ctrl:!this.isMac,meta:this.isMac,command:"print",description:"Print",preventDefault:!0}),this.registerShortcut({key:"s",ctrl:!this.isMac,meta:this.isMac,shift:!0,alt:!0,command:"insertSpecialCharacter",description:"Insert Special Character",preventDefault:!0}),this.registerShortcut({key:"m",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"insertEmoji",description:"Insert Emoji",preventDefault:!0}),this.registerShortcut({key:"9",ctrl:!this.isMac,meta:this.isMac,shift:!0,command:"toggleChecklist",description:"Checklist",preventDefault:!0}),this.registerShortcut({key:"a",ctrl:!this.isMac,meta:this.isMac,shift:!0,alt:!0,command:"toggleA11yChecker",description:"Accessibility Checker",preventDefault:!0}),this.registerShortcut({key:"F7",command:"toggleSpellCheck",description:"Spell Check",preventDefault:!0}),this.registerShortcut({key:"m",ctrl:!this.isMac,meta:this.isMac,alt:!0,command:"insertMath",description:"Insert Math",preventDefault:!0}),this.registerShortcut({key:"f",ctrl:!this.isMac,meta:this.isMac,alt:!0,command:"insertFootnote",description:"Insert Footnote",preventDefault:!0})}registerShortcut(e){const t=this.getShortcutKey(e);this.shortcuts.set(t,e)}unregisterShortcut(e){const t=this.getShortcutKey(e);this.shortcuts.delete(t)}getShortcutKey(e){const t=[];return e.ctrl&&t.push("ctrl"),e.alt&&t.push("alt"),e.shift&&t.push("shift"),e.meta&&t.push("meta"),t.push(e.key.toLowerCase()),t.join("+")}getEventKey(e){const t=[];return e.ctrlKey&&t.push("ctrl"),e.altKey&&t.push("alt"),e.shiftKey&&t.push("shift"),e.metaKey&&t.push("meta"),t.push(e.key.toLowerCase()),t.join("+")}handleKeyDown(e,t){if(!this.enabled)return!1;const n=this.getEventKey(e),i=this.shortcuts.get(n);return i?(i.preventDefault!==!1&&(e.preventDefault(),e.stopPropagation()),t(i.command,i.params),!0):!1}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}getAllShortcuts(){return Array.from(this.shortcuts.values())}getShortcutForCommand(e){return Array.from(this.shortcuts.values()).find(t=>t.command===e)}getShortcutDescription(e){const t=[];this.isMac?(e.meta&&t.push("⌘"),e.ctrl&&t.push("⌃"),e.alt&&t.push("⌥"),e.shift&&t.push("⇧")):(e.ctrl&&t.push("Ctrl"),e.alt&&t.push("Alt"),e.shift&&t.push("Shift"));const n=e.key.length===1?e.key.toUpperCase():e.key;return t.push(n),t.join("+")}getShortcutsHelp(){const e=this.getAllShortcuts(),t=new Map;e.forEach(i=>{const o=this.getShortcutCategory(i.command);t.has(o)||t.set(o,[]),t.get(o).push(i)});let n=`# Keyboard Shortcuts
4
4
 
5
5
  `;return t.forEach((i,o)=>{n+=`## ${o}
6
6
 
7
7
  `,i.forEach(r=>{const a=this.getShortcutDescription(r);n+=`- **${a}**: ${r.description||r.command}
8
8
  `}),n+=`
9
- `}),n}getShortcutCategory(e){return e.includes("toggle")&&(e.includes("Bold")||e.includes("Italic")||e.includes("Underline")||e.includes("Strike")||e.includes("Code")||e.includes("Super")||e.includes("Sub"))?"Text Formatting":e.includes("Heading")||e.includes("Paragraph")?"Block Formatting":e.includes("List")||e.includes("Checklist")?"Lists":e.includes("Alignment")||e.includes("Indent")?"Alignment & Indentation":e.includes("undo")||e.includes("redo")?"History":e.includes("insert")?"Insert":e.includes("find")||e.includes("replace")?"Find & Replace":e.includes("Accessibility")||e.includes("spell")?"Tools":"Other"}}const Dt=["p","br","strong","em","u","s","strike","del","b","i","h1","h2","h3","h4","h5","h6","ul","ol","li","a","img","video","audio","iframe","table","thead","tbody","tr","th","td","blockquote","pre","code","span","div","section","sup","sub","hr"],Pt={"*":["class","style","id","data-*","role","aria-*","tabindex","contenteditable","spellcheck","dir","lang"],a:["href","target","rel","title"],img:["src","alt","width","height","loading"],video:["src","controls","width","height","autoplay","loop","muted"],audio:["src","controls","autoplay","loop","muted"],iframe:["src","width","height","name","title","longdesc","allow","allowfullscreen","frameborder","scrolling","loading","referrerpolicy"],table:["border","cellpadding","cellspacing"],td:["colspan","rowspan","align","valign"],th:["colspan","rowspan","align","valign"]};function Ne(s,e,t){if((e==null?void 0:e.sanitize)===!1)return s;const n=e!=null&&e.allowedTags&&e.allowedTags.length>0?e.allowedTags:Dt,o=!!(e!=null&&e.allowedAttributes)&&Object.keys(e.allowedAttributes).length>0?e.allowedAttributes:Pt,r=document.createElement("div");return r.innerHTML=s,De(r,n,o),r.innerHTML}function De(s,e,t){const n=Array.from(s.childNodes);for(const i of n)if(i.nodeType===Node.ELEMENT_NODE){const o=i,r=o.tagName.toLowerCase();if(!e.includes(r)){for(;o.firstChild;)s.insertBefore(o.firstChild,o);s.removeChild(o);continue}$t(o,t),De(o,e,t)}else i.nodeType!==Node.TEXT_NODE&&s.removeChild(i)}function $t(s,e){const t=s.tagName.toLowerCase(),n=Array.from(s.attributes),i=e[t]||[],o=e["*"]||[],r=[...i,...o];for(const a of n){const l=a.name.toLowerCase();let c=!1;r.includes(l)&&(c=!0);for(const h of r)if(h.endsWith("*")){const u=h.slice(0,-1);if(l.startsWith(u)){c=!0;break}}(l.startsWith("on")||l==="javascript:"||l==="href"&&a.value.trim().toLowerCase().startsWith("javascript:")||l==="src"&&a.value.trim().toLowerCase().startsWith("javascript:"))&&(c=!1),l==="dir"&&!["ltr","rtl","auto"].includes(a.value.trim().toLowerCase())&&(c=!1),c||s.removeAttribute(a.name)}s.hasAttribute("href")&&(s.getAttribute("href")||"").trim().toLowerCase().startsWith("javascript:")&&s.removeAttribute("href"),s.hasAttribute("src")&&(s.getAttribute("src")||"").trim().toLowerCase().startsWith("javascript:")&&s.removeAttribute("src")}function Ft(s,e,t){return(t==null?void 0:t.sanitizeOnPaste)===!1?s:Ne(s,e)}function Bt(s,e,t){return(t==null?void 0:t.sanitizeOnInput)===!1?s:Ne(s,e)}const Ie=class Ie{static resolve(e){const t={};if(Object.assign(t,this.EDITOR_DEFAULTS),e.pluginDefaults&&Object.assign(t,e.pluginDefaults),e.attributes){const n=this.parseAttributes(e.attributes);Object.assign(t,n)}return e.jsConfig&&Object.assign(t,e.jsConfig),this.normalizeConfig(t)}static normalizeConfig(e){const t={...e};if(t.toolbarFloating!==void 0||t.toolbarSticky!==void 0){const r=typeof t.toolbar=="object"&&t.toolbar?{...t.toolbar}:typeof t.toolbar=="string"?{items:t.toolbar}:{};t.toolbarFloating!==void 0&&(r.floating=!!t.toolbarFloating),t.toolbarSticky!==void 0&&(r.sticky=!!t.toolbarSticky),t.toolbar=r}if(t.toolbarItems!==void 0&&typeof t.toolbar=="object"&&t.toolbar&&(t.toolbar.items=t.toolbarItems),t.autosaveEnabled!==void 0||t.autosaveIntervalMs!==void 0||t.autosaveStorageKey!==void 0||t.autosaveProvider!==void 0||t.autosaveApiUrl!==void 0){const r=typeof t.autosave=="object"&&t.autosave?{...t.autosave}:{};t.autosaveEnabled!==void 0&&(r.enabled=!!t.autosaveEnabled),t.autosaveIntervalMs!==void 0&&(r.intervalMs=Number(t.autosaveIntervalMs)),t.autosaveStorageKey!==void 0&&(r.storageKey=t.autosaveStorageKey),t.autosaveProvider!==void 0&&(r.provider=t.autosaveProvider),t.autosaveApiUrl!==void 0&&(r.apiUrl=t.autosaveApiUrl),t.autosave=r}const n={enabled:!1,intervalMs:3e4,storageKey:"rte-autosave",provider:"localStorage",apiUrl:""};if(typeof t.autosave=="boolean")t.autosave={...n,enabled:t.autosave};else if(typeof t.autosave=="object"&&t.autosave){const r={...n,...t.autosave};r.intervalMs===void 0&&r.interval!==void 0&&(r.intervalMs=Number(r.interval)),r.enabled===void 0&&(r.enabled=!0),(!Number.isFinite(r.intervalMs)||r.intervalMs<=0)&&(r.intervalMs=n.intervalMs),t.autosave=r}else t.autosave=n;if(t.languageLocale!==void 0||t.languageDirection!==void 0){const r=typeof t.language=="object"&&t.language?{...t.language}:{};t.languageLocale!==void 0&&(r.locale=t.languageLocale),t.languageDirection!==void 0&&(r.direction=t.languageDirection),t.language=r}const i={locale:"en",direction:"ltr"};if(typeof t.language=="string"?t.language={locale:t.language,direction:i.direction}:typeof t.language=="object"&&t.language?t.language={...i,...t.language}:t.language=i,t.spellcheckEnabled!==void 0||t.spellcheckProvider!==void 0||t.spellcheckApiUrl!==void 0){const r=typeof t.spellcheck=="object"&&t.spellcheck?{...t.spellcheck}:{};t.spellcheckEnabled!==void 0&&(r.enabled=!!t.spellcheckEnabled),t.spellcheckProvider!==void 0&&(r.provider=t.spellcheckProvider),t.spellcheckApiUrl!==void 0&&(r.apiUrl=t.spellcheckApiUrl),t.spellcheck=r}const o={enabled:!1,provider:"browser",apiUrl:""};if(typeof t.spellcheck=="boolean")t.spellcheck={...o,enabled:t.spellcheck};else if(typeof t.spellcheck=="object"&&t.spellcheck){const r={...o,...t.spellcheck};!r.provider&&r.mode&&(r.provider=r.mode==="local"?"browser":"api"),r.enabled===void 0&&(r.enabled=!!(r.mode||r.provider||r.apiUrl)),t.spellcheck=r}else t.spellcheck=o;return t.contextMenuEnabled!==void 0&&(t.contextMenu={enabled:!!t.contextMenuEnabled}),typeof t.contextMenu=="boolean"?t.contextMenu={enabled:t.contextMenu}:typeof t.contextMenu=="object"&&t.contextMenu?t.contextMenu={enabled:t.contextMenu.enabled!==!1}:t.contextMenu={enabled:!0},(t.pasteClean!==void 0||t.pasteKeepFormatting!==void 0||t.pasteConvertWord!==void 0)&&(t.paste={...t.paste||{},...t.pasteClean!==void 0?{clean:!!t.pasteClean}:{},...t.pasteKeepFormatting!==void 0?{keepFormatting:!!t.pasteKeepFormatting}:{},...t.pasteConvertWord!==void 0?{convertWord:!!t.pasteConvertWord}:{}}),t.paste={clean:!0,keepFormatting:!1,convertWord:!0,...t.paste||{}},t.contentConfig={allowedTags:[],allowedAttributes:{},sanitize:!0,...t.contentConfig||{}},(t.securitySanitizeOnPaste!==void 0||t.securitySanitizeOnInput!==void 0)&&(t.security={...t.security||{},...t.securitySanitizeOnPaste!==void 0?{sanitizeOnPaste:!!t.securitySanitizeOnPaste}:{},...t.securitySanitizeOnInput!==void 0?{sanitizeOnInput:!!t.securitySanitizeOnInput}:{}}),t.security={sanitizeOnPaste:!0,sanitizeOnInput:!0,...t.security||{}},(t.accessibilityEnableAria!==void 0||t.accessibilityKeyboardNavigation!==void 0||t.accessibilityChecker!==void 0)&&(t.accessibility={...t.accessibility||{},...t.accessibilityEnableAria!==void 0?{enableARIA:!!t.accessibilityEnableAria}:{},...t.accessibilityKeyboardNavigation!==void 0?{keyboardNavigation:!!t.accessibilityKeyboardNavigation}:{},...t.accessibilityChecker!==void 0?{checker:!!t.accessibilityChecker}:{}}),typeof t.accessibility=="boolean"&&(t.accessibility={enableARIA:t.accessibility,keyboardNavigation:t.accessibility,checker:!1}),t.accessibility={enableARIA:!0,keyboardNavigation:!0,checker:!1,...t.accessibility||{}},(t.performanceDebounceInputMs!==void 0||t.performanceViewportOnlyScan!==void 0)&&(t.performance={...t.performance||{},...t.performanceDebounceInputMs!==void 0?{debounceInputMs:Number(t.performanceDebounceInputMs)}:{},...t.performanceViewportOnlyScan!==void 0?{viewportOnlyScan:!!t.performanceViewportOnlyScan}:{}}),typeof t.performance=="boolean"&&(t.performance={debounceInputMs:100,viewportOnlyScan:t.performance}),t.performance={debounceInputMs:100,viewportOnlyScan:!0,...t.performance||{}},(typeof t.performance.debounceInputMs!="number"||!Number.isFinite(t.performance.debounceInputMs)||t.performance.debounceInputMs<0)&&(t.performance.debounceInputMs=100),t}static parseAttributes(e){const t={};for(const[n,i]of Object.entries(e)){const o=this.kebabToCamel(n);t[o]=this.parseAttributeValue(i)}return t}static parseAttributeValue(e){if(e==="true")return!0;if(e==="false")return!1;if(/^\d+$/.test(e))return parseInt(e,10);if(/^\d+\.\d+$/.test(e))return parseFloat(e);if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return e}return e}static kebabToCamel(e){return e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}static validate(e){const t=[];return e.height!==void 0&&typeof e.height=="number"&&e.height<0&&t.push("height must be a positive number"),e.width!==void 0&&typeof e.width=="number"&&e.width<0&&t.push("width must be a positive number"),e.plugins!==void 0&&!Array.isArray(e.plugins)&&typeof e.plugins!="string"&&t.push("plugins must be an array or string"),e.theme!==void 0&&typeof e.theme!="string"&&t.push("theme must be a string"),{valid:t.length===0,errors:t}}static getDefaults(){return{...this.EDITOR_DEFAULTS}}static merge(...e){const t={};for(const n of e)for(const[i,o]of Object.entries(n))o!=null&&(typeof o=="object"&&!Array.isArray(o)&&t[i]?t[i]=this.merge(t[i],o):t[i]=o);return t}};Ie.EDITOR_DEFAULTS={height:400,width:"100%",readonly:!1,disabled:!1,menubar:!0,toolbar:!0,plugins:[],theme:"light",content:"",placeholder:"Start typing...",autofocus:!1,autosave:!1,accessibility:{enableARIA:!0,keyboardNavigation:!0,checker:!1},performance:{debounceInputMs:100,viewportOnlyScan:!0},spellcheck:{enabled:!1,provider:"browser",apiUrl:""},language:{locale:"en",direction:"ltr"},contextMenu:{enabled:!0},contentConfig:{allowedTags:[],allowedAttributes:{},sanitize:!0},paste:{clean:!0,keepFormatting:!1,convertWord:!0},security:{sanitizeOnPaste:!0,sanitizeOnInput:!0},statusbar:!1};let ae=Ie;const zt='.editora-editor{display:flex;flex-direction:column;border:1px solid #ddd;border-radius:4px;background:#fff;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,sans-serif;font-size:14px;overflow:hidden}.editora-editor *{box-sizing:border-box}.editora-theme-light{background:#fff;color:#333}.editora-theme-dark{--editora-dark-toolbar-bg-start: #353d48;--editora-dark-toolbar-bg-end: #2d3540;--editora-dark-button-bg-start: #46505f;--editora-dark-button-bg-end: #3b4553;--editora-dark-button-hover-start: #525d6d;--editora-dark-button-hover-end: #465262;--editora-dark-button-active-start: #5eaaf6;--editora-dark-button-active-end: #4a95de;--editora-dark-border: #475263;--editora-dark-border-strong: #566275;--editora-dark-text: #e1e9f5;--editora-dark-text-strong: #f3f7ff;--editora-dark-text-muted: #aeb9cc;--editora-dark-surface: #1d242d;--editora-dark-content: #1f2732;background:linear-gradient(180deg,#1b2330,#1c2430);color:var(--editora-dark-text);border-color:var(--editora-dark-border)}.editora-toolbar{display:flex;align-items:center;gap:4px;padding:8px;background:#f5f5f5;border-bottom:1px solid #ddd;flex-wrap:wrap}.editora-theme-dark .editora-toolbar{background:linear-gradient(180deg,var(--editora-dark-toolbar-bg-start) 0%,var(--editora-dark-toolbar-bg-end) 100%);border-bottom-color:var(--editora-dark-border);box-shadow:inset 0 1px #ffffff0d}.editora-toolbar-sticky{position:sticky;top:0;z-index:100;position:-webkit-sticky}.editora-toolbar-group{display:flex;align-items:center;gap:2px}.editora-toolbar-button{padding:6px 12px;border:1px solid #ccc;background:#fff;cursor:pointer;border-radius:3px;font-weight:600;font-size:14px;height:30px;display:flex;align-items:center;white-space:nowrap}.editora-toolbar-group-button{display:flex;align-items:center}.editora-toolbar-input.font-size{width:40px;padding:.25rem;text-align:center;font-size:14px;background:#fff;border:1px solid var(--rte-color-border-light);border-radius:var(--rte-radius-sm)}.editora-toolbar-group-items{display:flex;align-items:center;border:1px solid #ccc;.editora-toolbar-button{border:none;border-radius:0;&:first-child{border-right:1px solid #ccc;border-top-left-radius:3px;border-bottom-left-radius:3px}&:last-child{border:0px solid #ccc;border-radius:0!important}&:hover{background:#e0e0e0;border-color:#ccc}}}.editora-theme-dark .editora-toolbar-button{background:linear-gradient(180deg,var(--editora-dark-button-bg-start) 0%,var(--editora-dark-button-bg-end) 100%);border-color:var(--editora-dark-border-strong);color:var(--editora-dark-text);box-shadow:inset 0 1px #ffffff14,0 1px 1px #00000059}.editora-theme-dark .editora-toolbar-group-items{border-color:var(--editora-dark-border-strong);background:linear-gradient(180deg,var(--editora-dark-button-bg-start) 0%,var(--editora-dark-button-bg-end) 100%)}.editora-theme-dark .editora-toolbar-group-items .editora-toolbar-button:first-child{border-right-color:#566275}.editora-theme-dark .editora-toolbar-group-items .editora-toolbar-button:last-child{border-left-color:#566275}.editora-theme-dark .editora-toolbar-input.font-size{background-color:#2e3642;color:var(--editora-dark-text-strong);border-color:var(--editora-dark-border-strong);caret-color:var(--editora-dark-text-strong)}.editora-theme-dark .editora-toolbar-input.font-size::placeholder{color:var(--editora-dark-text-strong);opacity:1}.editora-toolbar-button:hover{background:#e0e0e0;border-color:#ccc}.editora-theme-dark .editora-toolbar-button:hover{background:linear-gradient(180deg,var(--editora-dark-button-hover-start) 0%,var(--editora-dark-button-hover-end) 100%);border-color:#66748a;color:var(--editora-dark-text-strong)}.editora-toolbar-button:active,.editora-toolbar-button.active{background:#d0d0d0;border-color:#999}.editora-theme-dark .editora-toolbar-button:active,.editora-theme-dark .editora-toolbar-button.active{background:linear-gradient(180deg,var(--editora-dark-button-active-start) 0%,var(--editora-dark-button-active-end) 100%);border-color:#67adf4;color:#0f1b2a}.editora-theme-dark .editora-toolbar-button:disabled{background:#313946;border-color:#424d5e;color:#7f8ca1}.editora-theme-dark .editora-toolbar-button[data-command=insertTable],.editora-theme-dark .editora-toolbar-button[data-command=print],.editora-theme-dark .editora-toolbar-button[data-command=toggleSpellCheck],.editora-theme-dark .editora-toolbar-button[data-command=toggleA11yChecker],.editora-theme-dark .editora-toolbar-button[data-command=setDirectionLTR],.editora-theme-dark .editora-toolbar-button[data-command=setDirectionRTL]{color:#f1f6ff}.editora-toolbar-button:disabled{opacity:.5;cursor:not-allowed}.editora-toolbar-icon{display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;line-height:1}.editora-toolbar-button svg,.editora-toolbar-icon svg{width:20px;height:20px;display:block;color:currentColor;fill:currentColor}.editora-theme-dark .editora-toolbar-icon,.editora-theme-dark .editora-toolbar-icon *{color:inherit}.editora-theme-dark :is(.editora-toolbar-button,.editora-toolbar-icon) svg :is([stroke="#000" i],[stroke="#000000" i],[stroke=black i],[stroke="#0f0f0f" i],[stroke="#111111" i],[style*="stroke:#000" i],[style*="stroke: #000" i],[style*="stroke:black" i],[style*="stroke: black" i],[style*="stroke:#0f0f0f" i],[style*="stroke: #0f0f0f" i]){stroke:currentColor!important}.editora-theme-dark :is(.editora-toolbar-button,.editora-toolbar-icon) svg :is([fill="#000" i],[fill="#000000" i],[fill=black i],[fill="#0f0f0f" i],[fill="#111111" i],[style*="fill:#000" i],[style*="fill: #000" i],[style*="fill:black" i],[style*="fill: black" i],[style*="fill:#0f0f0f" i],[style*="fill: #0f0f0f" i]){fill:currentColor!important}.editora-toolbar-separator{width:1px;height:24px;background:#ddd;margin:0 4px}.editora-theme-dark .editora-toolbar-separator{background:#4d596b}.editora-toolbar-dropdown{position:relative}.editora-toolbar-dropdown-menu{position:absolute;top:100%;left:0;min-width:150px;margin-top:4px;padding:4px 0;background:#fff;border:1px solid #ddd;border-radius:4px;box-shadow:0 2px 8px #00000026;z-index:1000}.editora-theme-dark .editora-toolbar-dropdown-menu{background:#29323d;border-color:#4d596b;box-shadow:0 8px 20px #00000073}.editora-toolbar-dropdown-item{display:block;width:100%;padding:8px 12px;border:none;background:transparent;color:#333;text-align:left;cursor:pointer;font-size:13px;transition:background .15s ease}.editora-theme-dark .editora-toolbar-dropdown-item{color:#d7deea}.editora-toolbar-dropdown-item:hover{background:#f5f5f5}.editora-theme-dark .editora-toolbar-dropdown-item:hover{background:#3a4554;color:#f0f6ff}.editora-content{flex:1;min-height:200px;padding:16px;outline:none;overflow-y:auto;line-height:1.6}.editora-theme-dark .editora-content{color:#ecf3ff;background:linear-gradient(180deg,var(--editora-dark-content) 0%,#1c232e 100%)}.editora-content:empty:before{content:attr(data-placeholder);color:#999;pointer-events:none}.editora-theme-dark .editora-content:empty:before{color:#8f9bb0}.editora-content h1{font-size:2em;margin:.67em 0;font-weight:600}.editora-content h2{font-size:1.5em;margin:.75em 0;font-weight:600}.editora-content h3{font-size:1.17em;margin:.83em 0;font-weight:600}.editora-content p{margin:1em 0}.editora-theme-dark .editora-content,.editora-theme-dark .editora-content :is(p,span,div,li,ul,ol,td,th,h1,h2,h3,h4,h5,h6,strong,em,u,s,small,sub,sup,blockquote,code,pre,a){color:#ecf3ff}.editora-content ul,.editora-content ol{margin:1em 0;padding-left:2em}.editora-content a{color:#06c;text-decoration:underline}.editora-theme-dark .editora-content a{color:#ecf3ff}.editora-content code{padding:2px 4px;background:#f5f5f5;border-radius:3px;font-family:Monaco,Menlo,Consolas,monospace;font-size:.9em}.editora-theme-dark .editora-content code{background:#1e1e1e}.editora-content pre{padding:12px;background:#f5f5f5;border-radius:4px;overflow-x:auto;margin:1em 0}.editora-theme-dark .editora-content pre{background:#1e1e1e}.editora-theme-dark .rte-code-block{background:linear-gradient(180deg,#212a36,#1b2430)!important;border-color:#4f5b70!important;color:#e7effc!important}.editora-theme-dark .rte-code-block code{color:#e7effc!important}.editora-theme-dark .rte-code-block:before{background:#111927!important;color:#dce8ff!important}.editora-theme-dark .rte-code-block .rte-code-copy{background:#2b3441!important;border-color:#5a667b!important;color:#dce8ff!important}.editora-content blockquote{margin:1em 0;padding-left:1em;border-left:4px solid #ddd;color:#666}.editora-theme-dark .editora-content blockquote{border-left-color:#3c3c3c;color:#ecf3ff}.editora-floating-toolbar{position:absolute;padding:4px;background:#fff;border:1px solid #ddd;border-radius:4px;box-shadow:0 2px 8px #00000026;z-index:1000}.editora-theme-dark .editora-floating-toolbar{background:#29323d;border-color:#4d596b;box-shadow:0 8px 20px #00000073}.editora-statusbar-container{display:flex;flex-direction:column}.editora-statusbar-left{display:flex;align-items:center;gap:8px}.editora-statusbar-right{display:flex;align-items:center;gap:8px;margin-left:auto}.editora-statusbar{display:flex;align-items:center;gap:12px;padding:6px 12px;background:#f5f5f5;border-top:1px solid #ddd;font-size:12px;color:#666}.editora-theme-dark .editora-statusbar{background:linear-gradient(180deg,#2c3440,#252d37);border-top-color:#3f4a5b;color:#d7deea}.editora-statusbar-item{white-space:nowrap}.editora-statusbar-separator{color:#ddd}.editora-theme-dark .editora-statusbar-separator{color:#566275}.editora-editor[readonly] .editora-content{background:#fafafa;cursor:not-allowed}.editora-theme-dark.editora-editor[readonly] .editora-content{background:#1a1a1a}.editora-editor:focus-within{border-color:#06c;box-shadow:0 0 0 3px #0066cc1a}.editora-theme-dark.editora-editor:focus-within{border-color:#4db8ff;box-shadow:0 0 0 3px #4db8ff1a}.editora-editor[disabled]{opacity:.6;pointer-events:none}@media(max-width:768px){.editora-toolbar{padding:4px}.editora-toolbar-button{min-width:28px;min-height:28px;padding:4px 8px;font-size:12px}.editora-content{padding:12px}}.editora-content ::selection{background:#06c3}.editora-theme-dark .editora-content ::selection{background:#4db8ff33}.editora-content table{border-collapse:collapse;width:100%;margin:1em 0}.editora-content th,.editora-content td{border:1px solid #ddd;padding:8px 12px;text-align:left}.editora-theme-dark .editora-content th,.editora-theme-dark .editora-content td{border-color:#3c3c3c}.editora-content th{background:#f5f5f5;font-weight:600}.editora-theme-dark .editora-content th{background:#252526}.editora-content img{max-width:100%;height:auto;border-radius:4px;display:block}.editora-content video{max-width:100%;height:auto;border-radius:4px;display:block}.editora-editor.loading{opacity:.7;pointer-events:none}.editora-editor.loading:after{content:"";position:absolute;top:50%;left:50%;width:24px;height:24px;margin:-12px 0 0 -12px;border:3px solid #ddd;border-top-color:#06c;border-radius:50%;animation:editora-spin .8s linear infinite}@keyframes editora-spin{to{transform:rotate(360deg)}}.toolbar-container-wrapper{display:flex;align-items:center;background:#fff;border-bottom:1px solid #e0e0e0;padding:0;margin:0;width:100%;box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif;font-size:14px;line-height:1.5;position:relative}.toolbar-container-wrapper[data-toolbar-sticky=true]{position:sticky;top:0;z-index:999;box-shadow:0 2px 4px #0000001a}.toolbar-container-wrapper[data-toolbar-floating=true]{position:fixed;top:0;left:0;right:0;z-index:1000;box-shadow:0 4px 12px #00000026}.toolbar-container-wrapper[data-toolbar-position=bottom]{border-bottom:none;border-top:1px solid #e0e0e0}.toolbar-container-wrapper .toolbar-wrapper{display:flex;width:100%;padding:8px;gap:4px;flex-wrap:wrap;align-items:center}.toolbar-container-wrapper .toolbar{display:flex;width:100%;gap:4px;flex-wrap:wrap;align-items:center}.toolbar-container-wrapper .toolbar-container{display:flex;gap:4px;flex-wrap:wrap;align-items:center;flex:1;position:relative}.toolbar-container-wrapper .toolbar-item{display:flex;align-items:center;gap:2px}.toolbar-container-wrapper .toolbar-button{padding:6px 10px;border:1px solid #d1d5db;background:#fff;border-radius:4px;cursor:pointer;font-size:13px;display:flex;align-items:center;justify-content:center;gap:4px;transition:all .15s ease;min-height:32px;white-space:nowrap}.toolbar-container-wrapper .toolbar-button:hover{background-color:#f3f4f6;border-color:#9ca3af}.toolbar-container-wrapper .toolbar-button:active,.toolbar-container-wrapper .toolbar-button[data-active=true]{background-color:#06c;color:#fff;border-color:#0052a3;box-shadow:inset 0 1px 3px #0000001a}.toolbar-container-wrapper .toolbar-button:disabled{opacity:.5;cursor:not-allowed;background-color:#f9fafb}.toolbar-container-wrapper .toolbar-more-button{padding:6px 8px;font-size:16px;font-weight:500;line-height:1}.toolbar-container-wrapper .toolbar-separator{width:1px;height:24px;background-color:#d1d5db;margin:0 4px}.toolbar-container-wrapper .toolbar-icon{display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;flex-shrink:0}.toolbar-container-wrapper .toolbar-icon svg{width:100%;height:100%}.toolbar-container-wrapper .toolbar-dropdown{position:relative;display:flex;align-items:center}.toolbar-container-wrapper .toolbar-dropdown-arrow{font-size:10px;margin-left:2px;line-height:1}.toolbar-container-wrapper .toolbar-dropdown-menu{position:absolute;top:100%;left:0;background:#fff;border:1px solid #d1d5db;border-radius:6px;box-shadow:0 4px 12px #00000026;z-index:1000;min-width:160px;padding:4px 0;margin-top:4px;display:none}.toolbar-container-wrapper .toolbar-dropdown-menu.show{display:block}.toolbar-container-wrapper .toolbar-dropdown-item{display:block;width:100%;padding:8px 12px;border:none;background:transparent;text-align:left;cursor:pointer;font-size:13px;color:#1f2937;transition:background-color .15s ease;font-family:inherit}.toolbar-container-wrapper .toolbar-dropdown-item:hover{background-color:#f3f4f6}.toolbar-container-wrapper .toolbar-dropdown-item:active{background-color:#e5e7eb}.toolbar-container-wrapper .toolbar-input{padding:6px 8px;border:1px solid #d1d5db;border-radius:4px;font-size:13px;font-family:inherit;background-color:#fff;color:#1f2937;transition:all .15s ease}.toolbar-container-wrapper .toolbar-input:focus{outline:none;border-color:#06c;box-shadow:0 0 0 3px #0066cc1a;background-color:#fff}.toolbar-container-wrapper .toolbar-input::placeholder{color:#9ca3af}.toolbar-overflow-menu{animation:slideDown .2s ease-out}@keyframes slideDown{0%{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}.toolbar-overflow-item{transition:background-color .15s ease}.floating-toolbar{user-select:none;-webkit-user-select:none;font-family:system-ui,-apple-system,sans-serif;font-size:14px;animation:fadeInUp .15s ease-out}@keyframes fadeInUp{0%{opacity:0;transform:translate(-50%) translateY(10px)}to{opacity:1;transform:translate(-50%) translateY(0)}}.floating-toolbar-btn{display:flex;align-items:center;justify-content:center;width:32px;height:32px;border:none;background:transparent;border-radius:4px;color:#495057;cursor:pointer;font-size:14px;font-weight:500;transition:all .15s ease;outline:none}.floating-toolbar-btn:hover{background:#f8f9fa;color:#212529}.floating-toolbar-btn:active{background:#e9ecef;transform:scale(.95)}.floating-toolbar-btn.floating-toolbar-toggle{color:#dc3545;font-weight:700}.floating-toolbar-btn.floating-toolbar-toggle:hover{background:#f8d7da;color:#721c24}.floating-toolbar-separator{width:1px;height:20px;background:#e1e5e9;margin:0 2px}@media(max-width:768px){.toolbar-container-wrapper .toolbar-button{padding:5px 8px;font-size:12px;min-height:28px}.toolbar-container-wrapper .toolbar-icon{width:16px;height:16px}.toolbar-container-wrapper .toolbar-dropdown-menu{min-width:140px}.toolbar-container-wrapper .toolbar-dropdown-item{padding:6px 10px;font-size:12px}.floating-toolbar{padding:4px;gap:2px}.floating-toolbar-btn{width:28px;height:28px;font-size:12px}}@media(max-width:480px){.toolbar-container-wrapper{padding:4px}.toolbar-container-wrapper .toolbar-wrapper{padding:4px;gap:2px}.toolbar-container-wrapper .toolbar-button{padding:4px 6px;font-size:11px;min-height:24px}.toolbar-container-wrapper .toolbar-icon{width:14px;height:14px}}.floating-toolbar{pointer-events:auto}.floating-toolbar{max-width:calc(100vw - 20px);overflow-x:auto}@media(prefers-color-scheme:dark){.floating-toolbar{background:#2d3748;border-color:#4a5568;color:#e2e8f0}.floating-toolbar-btn:hover{background:#4a5568;color:#f7fafc}.floating-toolbar-btn:active{background:#718096}.floating-toolbar-separator{background:#4a5568}}';let X;const _t="__editoraCommandEditorRoot",jt="__editoraLastCommandButton",Pe="editora-editor, [data-editora-editor], .rte-editor, .editora-editor",$e=".rte-content, .editora-content",le=new Set;let I=null,Fe=!1,ce=null,he=null;function Be(s){if(!(s instanceof HTMLElement))return!1;const e=s;return typeof e.execCommand=="function"&&(e.tagName.toLowerCase()==="editora-editor"||e.classList.contains("editora-editor")||e.hasAttribute("data-editora-editor"))}function Ut(s){return s?s.nodeType===Node.ELEMENT_NODE?s:s.parentElement:null}function _(s){if(!s)return null;if(Be(s))return s;const e=s.matches(Pe)?s:s.closest(Pe);return!e||!Be(e)?null:e}function Wt(){var i;if(typeof window=="undefined")return null;const s=window[_t];if(s instanceof HTMLElement){const o=_(s);if(o)return o;const r=s.matches($e)?s:s.querySelector($e);if(r){const a=_(r);if(a)return a}}const e=window[jt];if(e instanceof HTMLElement){const o=_(e);if(o)return o}const t=document.activeElement;if(t){const o=_(t);if(o)return o}const n=(i=window.getSelection)==null?void 0:i.call(window);if(n&&n.rangeCount>0){const o=_(Ut(n.getRangeAt(0).startContainer));if(o)return o}if(I&&I.isConnected)return I;for(const o of le)if(o.isConnected)return o;return null}function Vt(){if(typeof window=="undefined"||Fe)return;ce=typeof window.executeEditorCommand=="function"?window.executeEditorCommand.bind(window):null,he=typeof window.execEditorCommand=="function"?window.execEditorCommand.bind(window):null;const s=(e,t)=>{const n=Wt();return n?n.execCommand(e,t):ce?ce(e,t):he?he(e,t):!1};window.executeEditorCommand=s,window.execEditorCommand=s,Fe=!0}function Kt(){const s="editora-webcomponent-styles";if(!document.getElementById(s)){const e=document.createElement("style");e.id=s,e.textContent=zt,document.head.appendChild(e)}}function qt(){if(!X){const s=L.__globalPluginLoader;s?X=s:X=new $}return X}class L extends HTMLElement{constructor(){if(super(),this.pluginLoader=qt(),this.config={},this.isInitialized=!1,this.keyboardShortcutManager=new Nt,this.lastAutosavedContent="",this.loadedPlugins=[],this.lastBeforeInputType=null,Kt(),!this.hasAttribute("data-initial-content")){const e=this.innerHTML.trim();e&&this.setAttribute("data-initial-content",e)}}static get observedAttributes(){return["height","width","menubar","plugins","toolbar","toolbar-items","toolbar-floating","toolbar-sticky","readonly","disabled","theme","placeholder","autofocus","autosave","autosave-enabled","autosave-interval-ms","autosave-storage-key","autosave-provider","autosave-api-url","accessibility","accessibility-enable-aria","accessibility-keyboard-navigation","accessibility-checker","performance","performance-debounce-input-ms","performance-viewport-only-scan","language","language-locale","language-direction","spellcheck","spellcheck-enabled","spellcheck-provider","context-menu","context-menu-enabled","paste","paste-clean","paste-keep-formatting","paste-convert-word","security","security-sanitize-on-paste","security-sanitize-on-input","statusbar"]}connectedCallback(){this.config=this.resolveConfig(),this.waitForPluginLoader().then(()=>{setTimeout(async()=>{await this.initialize()},0)})}async waitForPluginLoader(){if(L.__globalPluginLoader){this.pluginLoader=L.__globalPluginLoader;return}return new Promise(e=>{const t=()=>{L.__globalPluginLoader?(this.pluginLoader=L.__globalPluginLoader,e()):setTimeout(t,0)};t()})}disconnectedCallback(){this.destroy()}attributeChangedCallback(e,t,n){t!==n&&(this.config=this.resolveConfig(),this.handleAttributeChange(e,n))}async setConfig(e){this.jsConfig=e,this.config=this.resolveConfig(),this.isConnected&&(this.destroy(),await this.waitForPluginLoader(),await this.initialize())}async initialize(){var n;if(this.querySelector(".editora-toolbar")||this.isInitialized)return;this.setAttribute("data-editora-editor","true"),le.add(this),I||(I=this),Vt(),this.config.height&&(this.style.height=typeof this.config.height=="number"?`${this.config.height}px`:this.config.height),this.config.width&&(this.style.width=typeof this.config.width=="number"?`${this.config.width}px`:this.config.width),this.classList.add("editora-editor"),this.config.theme&&this.classList.add(`editora-theme-${this.config.theme}`);const e=await this.loadPlugins();this.loadedPlugins=e,e.forEach(i=>{if(i.init&&typeof i.init=="function")try{i.init({editorElement:this})}catch(o){console.error(`[RichTextEditor] Error initializing plugin ${i.name}:`,o)}});const t=(n=this.restoreAutosavedContent())!=null?n:this.getAttribute("data-initial-content")||"";this.engine=new St({content:t,plugins:e,readonly:this.config.readonly}),this.createUI(e,t),this.setupEventListeners(),this.startAutosave(),this.isInitialized=!0,this.dispatchEvent(new CustomEvent("editor-ready",{detail:{api:this.getAPI()},bubbles:!0}))}getInitialContent(){if(this.config.content)return this.config.content;const e=this.querySelector("[slot]");return e?e.innerHTML:this.hasChildNodes()?Array.from(this.childNodes).map(n=>n.nodeType===Node.TEXT_NODE?n.textContent:n.nodeType===Node.ELEMENT_NODE?n.outerHTML:"").join("").trim():""}async loadPlugins(){this.pluginLoader||await this.waitForPluginLoader();const e=[],t=this.config.plugins&&(typeof this.config.plugins=="string"&&this.config.plugins.length>0||Array.isArray(this.config.plugins)&&this.config.plugins.length>0),i=this.getAccessibilityConfig().checker===!0;if(t){if(typeof this.config.plugins=="string"){const o=this.config.plugins.split(/\s+/).filter(Boolean);i&&!o.includes("a11yChecker")&&o.push("a11yChecker");for(const r of o){const a=await this.pluginLoader.load(r,this.getPluginLoadConfig(r));a&&e.push(a)}}else if(Array.isArray(this.config.plugins)){for(const o of this.config.plugins)if(typeof o=="string"){const r=await this.pluginLoader.load(o,this.getPluginLoadConfig(o));r&&e.push(r)}else e.push(o);if(i&&!e.some(o=>(o==null?void 0:o.name)==="a11yChecker")){const o=await this.pluginLoader.load("a11yChecker",this.getPluginLoadConfig("a11yChecker"));o&&e.push(o)}}}else{const o=this.pluginLoader.getRegisteredPluginNames();for(const r of o){const a=await this.pluginLoader.load(r,this.getPluginLoadConfig(r));a&&e.push(a)}}return e}resolveToolbarItems(){const e=this.config.toolbarItems;if(typeof e=="string")return e;if(Array.isArray(e))return e.join(" ");const t=this.config.toolbar;if(typeof t=="string")return t;if(!t||typeof t!="object")return;const n=t.items;if(typeof n=="string")return n;if(Array.isArray(n))return n.join(" ")}isToolbarStickyEnabled(){const e=this.config.toolbar;return!e||typeof e!="object"?!1:!!e.sticky}isToolbarFloatingEnabled(){const e=this.config.toolbar;return!e||typeof e!="object"?!1:!!e.floating}isStatusbarEnabled(){const e=this.config.statusbar;return typeof e=="boolean"?e:e&&typeof e=="object"?e.enabled!==!1:!1}getStatusbarPosition(){const e=this.config.statusbar;return e&&typeof e=="object"&&e.position==="top"?"top":"bottom"}getLanguageConfig(){const e=this.config.language;return typeof e=="string"?{locale:e,direction:"ltr"}:e&&typeof e=="object"?{locale:e.locale||"en",direction:e.direction==="rtl"?"rtl":"ltr"}:{locale:"en",direction:"ltr"}}getAccessibilityConfig(){const e=this.config.accessibility;return typeof e=="boolean"?{enableARIA:e,keyboardNavigation:e,checker:!1}:e&&typeof e=="object"?{enableARIA:e.enableARIA!==!1,keyboardNavigation:e.keyboardNavigation!==!1,checker:!!e.checker}:{enableARIA:!0,keyboardNavigation:!0,checker:!1}}getPerformanceConfig(){var t;const e=this.config.performance;if(typeof e=="boolean")return{debounceInputMs:100,viewportOnlyScan:e};if(e&&typeof e=="object"){const n=Number((t=e.debounceInputMs)!=null?t:100);return{debounceInputMs:Number.isFinite(n)&&n>=0?n:100,viewportOnlyScan:e.viewportOnlyScan!==!1}}return{debounceInputMs:100,viewportOnlyScan:!0}}isEditorInViewport(){if(!this.contentElement||typeof window=="undefined")return!0;const e=this.contentElement.getBoundingClientRect();return e.bottom>=0&&e.top<=window.innerHeight}applyAccessibilitySettings(){if(!this.contentElement)return;const e=this.getAccessibilityConfig();if(e.enableARIA){this.contentElement.setAttribute("role","textbox"),this.contentElement.setAttribute("aria-multiline","true"),this.contentElement.setAttribute("aria-disabled",this.config.readonly?"true":"false");const t=typeof this.config.placeholder=="string"?this.config.placeholder.trim():"";t?this.contentElement.setAttribute("aria-label",t):this.contentElement.removeAttribute("aria-label")}else this.contentElement.removeAttribute("role"),this.contentElement.removeAttribute("aria-multiline"),this.contentElement.removeAttribute("aria-disabled"),this.contentElement.removeAttribute("aria-label");this.contentElement.tabIndex=e.keyboardNavigation?0:-1}applyLanguageSettings(){if(!this.contentElement)return;const e=this.getLanguageConfig();this.contentElement.setAttribute("lang",e.locale),this.contentElement.setAttribute("dir",e.direction)}getSpellcheckConfig(){const e=this.config.spellcheck;if(typeof e=="boolean")return{enabled:e,provider:"browser"};if(e&&typeof e=="object"){const t=e.provider||"browser";return{enabled:!!e.enabled,provider:t,mode:e.mode}}return{enabled:!1,provider:"browser"}}applySpellcheckSettings(){if(!this.contentElement)return;const e=this.getSpellcheckConfig(),t=e.enabled&&e.provider==="browser";this.contentElement.spellcheck=t,this.contentElement.setAttribute("spellcheck",t?"true":"false")}executeCommand(e,t){var o;typeof window!="undefined"&&(window.__editoraCommandEditorRoot=this);const n={editorElement:this,contentElement:this.contentElement,toolbarElement:this.toolbarElement},i=this.loadedPlugins.find(r=>r.commands&&r.commands[e]);if(i&&i.commands){const r=i.commands[e];if(typeof r=="function")try{return r(e==="toggleFullscreen"?this:t,n),!0}catch(a){return console.error(`[RichTextEditor] Error executing native command ${e}:`,a),!1}}return((o=this.engine)==null?void 0:o.execCommand(e,t))||!1}getPluginLoadConfig(e){const t=this.config.pluginConfig;if(t&&typeof t=="object"){const o=t[e];if(o&&typeof o=="object")return o}const n={spellCheck:["spellcheck","spellCheck"],trackChanges:["trackchanges","track-changes","trackChanges"],versionDiff:["versiondiff","version-diff","versionDiff"],"version-diff":["versiondiff","version-diff","versionDiff"],conditionalContent:["conditionalcontent","conditional-content","conditionalContent"],"conditional-content":["conditionalcontent","conditional-content","conditionalContent"],dataBinding:["databinding","data-binding","dataBinding"],"data-binding":["databinding","data-binding","dataBinding"],contentRules:["contentrules","content-rules","contentRules"],"content-rules":["contentrules","content-rules","contentRules"],mentions:["mention","mentions"],mention:["mention","mentions"],slashCommands:["slashcommands","slash-commands","slashCommands"],"slash-commands":["slashcommands","slash-commands","slashCommands"],formatPainter:["formatpainter","format-painter","formatPainter"],"format-painter":["formatpainter","format-painter","formatPainter"]},i=[e,e.toLowerCase(),...n[e]||[]];for(const o of i){const r=this.config[o];if(r&&typeof r=="object"&&!Array.isArray(r))return r}}getContentSanitizeConfig(){const e=this.config.contentConfig;return e&&typeof e=="object"?e:{sanitize:!0}}getSecurityConfig(){const e=this.config.security;return e&&typeof e=="object"?e:{sanitizeOnPaste:!0,sanitizeOnInput:!0}}getAutosaveConfig(){var t,n;const e=this.config.autosave;if(typeof e=="boolean")return{enabled:e,intervalMs:3e4,storageKey:"rte-autosave",provider:"localStorage"};if(e&&typeof e=="object"){const i=Number((n=(t=e.intervalMs)!=null?t:e.interval)!=null?n:3e4);return{enabled:!!e.enabled,intervalMs:Number.isFinite(i)&&i>0?i:3e4,storageKey:String(e.storageKey||"rte-autosave"),provider:e.provider||"localStorage",apiUrl:e.apiUrl}}return{enabled:!1,intervalMs:3e4,storageKey:"rte-autosave",provider:"localStorage"}}persistAutosave(e){const t=this.getAutosaveConfig();if(t.enabled&&e!==this.lastAutosavedContent){if(this.lastAutosavedContent=e,t.provider==="localStorage"){try{localStorage.setItem(t.storageKey,e),localStorage.setItem(`${t.storageKey}-timestamp`,Date.now().toString())}catch(n){console.error("[RichTextEditor] Failed to save autosave content to localStorage:",n)}return}t.provider==="api"&&t.apiUrl&&fetch(t.apiUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:e,timestamp:Date.now()})}).catch(n=>{console.error("[RichTextEditor] Failed to save autosave content to API:",n)})}}restoreAutosavedContent(){const e=this.getAutosaveConfig();if(!e.enabled||e.provider!=="localStorage")return null;try{const t=localStorage.getItem(e.storageKey);if(t)return this.lastAutosavedContent=t,t}catch(t){console.error("[RichTextEditor] Failed to restore autosaved content:",t)}return null}stopAutosave(){this.autosaveTimer&&(clearInterval(this.autosaveTimer),this.autosaveTimer=void 0)}startAutosave(){this.stopAutosave();const e=this.getAutosaveConfig();!e.enabled||!this.contentElement||(this.autosaveTimer=setInterval(()=>{var t;this.persistAutosave(((t=this.contentElement)==null?void 0:t.innerHTML)||"")},e.intervalMs))}insertHTMLAtSelection(e){if(!this.contentElement)return;const t=window.getSelection();if(t&&t.rangeCount>0){const n=t.getRangeAt(0);n.deleteContents();const i=document.createElement("div");i.innerHTML=e;const o=document.createDocumentFragment();for(;i.firstChild;)o.appendChild(i.firstChild);n.insertNode(o),n.collapse(!1),t.removeAllRanges(),t.addRange(n)}else this.contentElement.focus(),document.execCommand("insertHTML",!1,e)}createUI(e,t){const n=this.querySelector('[slot="toolbar"]'),i=this.querySelector('[slot="statusbar"]');this.innerHTML="",this.config.toolbar!==!1&&!n?(this.toolbarElement=document.createElement("div"),this.toolbarElement.className="editora-toolbar-container",this.appendChild(this.toolbarElement),this.toolbar=new kt({items:this.resolveToolbarItems(),sticky:this.isToolbarStickyEnabled(),position:"top"},e,this.pluginLoader),this.toolbar.setCommandHandler((o,r)=>{var a;if(this.contentElement){this.contentElement.focus();const l=window.getSelection();if(!l||l.rangeCount===0||!this.contentElement.contains(l.anchorNode)){const c=document.createRange(),h=this.contentElement.lastChild||this.contentElement;h.nodeType===Node.TEXT_NODE?c.setStart(h,((a=h.textContent)==null?void 0:a.length)||0):h.nodeType===Node.ELEMENT_NODE?(c.selectNodeContents(h),c.collapse(!1)):c.setStart(this.contentElement,0),c.collapse(!0),l==null||l.removeAllRanges(),l==null||l.addRange(c)}}return this.executeCommand(o,r)}),this.toolbar.render(this.toolbarElement)):n&&this.appendChild(n),this.contentElement=document.createElement("div"),this.contentElement.className="editora-content rte-content",this.contentElement.contentEditable=this.config.readonly?"false":"true",this.applyLanguageSettings(),this.applyAccessibilitySettings(),this.applySpellcheckSettings(),this.config.placeholder&&this.contentElement.setAttribute("data-placeholder",this.config.placeholder);try{document.execCommand("defaultParagraphSeparator",!1,"p")}catch(o){console.warn("defaultParagraphSeparator not supported:",o)}if(t){const o=document.createElement("div");o.innerHTML=t.trim(),!Array.from(o.childNodes).some(a=>{if(a.nodeType===Node.ELEMENT_NODE){const l=a.tagName;return["P","DIV","H1","H2","H3","H4","H5","H6","UL","OL","BLOCKQUOTE","PRE"].includes(l)}return!1})&&t.trim()?this.contentElement.innerHTML=`<p>${t.trim()}</p>`:this.contentElement.innerHTML=t}else this.config.placeholder?this.contentElement.innerHTML="":this.contentElement.innerHTML="<p><br></p>";this.appendChild(this.contentElement),this.isToolbarFloatingEnabled()&&(this.floatingToolbar=new Mt({enabled:!0}),this.floatingToolbar.create(this)),i?this.appendChild(i):this.isStatusbarEnabled()&&(this.statusBarElement=document.createElement("div"),this.statusBarElement.className="editora-statusbar-container",this.appendChild(this.statusBarElement),this.statusBar=new Lt({position:this.getStatusbarPosition()}),this.statusBar.create(this.statusBarElement)),this.config.autofocus&&setTimeout(()=>{var o;return(o=this.contentElement)==null?void 0:o.focus()},0)}setupEventListeners(){if(!this.contentElement||!this.engine)return;const e=this.keyboardShortcutManager;this.contentElement.addEventListener("beforeinput",n=>{this.lastBeforeInputType=n.inputType||null}),this.contentElement.addEventListener("input",()=>{if(!this.contentElement)return;let n=this.contentElement.innerHTML;const i=this.getPerformanceConfig(),o=this.getContentSanitizeConfig(),r=this.getSecurityConfig(),a=this.lastBeforeInputType;if(this.lastBeforeInputType=null,r.sanitizeOnInput!==!1&&o.sanitize!==!1&&!a){const h=Bt(n,o,r);if(h!==n){const u=window.getSelection(),d=u&&u.rangeCount>0?u.getRangeAt(0):null;if(this.contentElement.innerHTML=h,d&&u)try{u.removeAllRanges(),u.addRange(d)}catch(g){}n=h}}this.contentChangeDebounceTimer&&clearTimeout(this.contentChangeDebounceTimer);const c=()=>{this.dispatchEvent(new CustomEvent("content-change",{detail:{html:n},bubbles:!0}))};i.debounceInputMs>0?this.contentChangeDebounceTimer=setTimeout(c,i.debounceInputMs):c(),this.updateStatusBar()}),this.contentElement.addEventListener("contextmenu",n=>{const i=this.config.contextMenu;(i===!1||typeof i=="object"&&i!==null&&i.enabled===!1)&&n.preventDefault()}),this.contentElement.addEventListener("paste",n=>{var h,u;if(n.__editoraSmartPasteHandled===!0||n.defaultPrevented)return;n.preventDefault();const i=this.config.paste||{};let o=((h=n.clipboardData)==null?void 0:h.getData("text/html"))||"";const r=((u=n.clipboardData)==null?void 0:u.getData("text/plain"))||"",a=this.getContentSanitizeConfig(),l=this.getSecurityConfig(),c=!!o&&/class=["'][^"']*Mso|xmlns:w=|urn:schemas-microsoft-com:office/i.test(o);if((i.clean||!i.keepFormatting)&&r){document.execCommand("insertText",!1,r);return}if(i.convertWord===!1&&c&&r){document.execCommand("insertText",!1,r);return}if(o){l.sanitizeOnPaste!==!1&&a.sanitize!==!1&&(o=Ft(o,a,l)),this.insertHTMLAtSelection(o);return}r&&document.execCommand("insertText",!1,r)}),this.contentElement.addEventListener("focus",()=>{I=this,this.dispatchEvent(new Event("editor-focus",{bubbles:!0})),this.updateStatusBar()}),this.contentElement.addEventListener("blur",()=>{this.contentChangeDebounceTimer&&(clearTimeout(this.contentChangeDebounceTimer),this.contentChangeDebounceTimer=void 0),this.contentElement&&this.dispatchEvent(new CustomEvent("content-change",{detail:{html:this.contentElement.innerHTML},bubbles:!0})),this.dispatchEvent(new Event("editor-blur",{bubbles:!0})),this.updateFloatingToolbar(),this.updateStatusBar()}),this.contentElement.addEventListener("keydown",n=>{this.getAccessibilityConfig().keyboardNavigation&&e.handleKeyDown(n,(o,r)=>{this.executeCommand(o,r)})});const t=()=>{const n=this.getSelectionRangeInEditor(),i=document.activeElement,o=!!i&&!!this.contentElement&&(i===this.contentElement||this.contentElement.contains(i));this.getPerformanceConfig().viewportOnlyScan&&!this.isEditorInViewport()&&!o||!n&&!o||(this.updateFloatingToolbar(),this.updateStatusBar())};this.selectionChangeHandler=t,document.addEventListener("selectionchange",this.selectionChangeHandler)}getSelectionRangeInEditor(){if(!this.contentElement)return null;const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0),n=t.commonAncestorContainer;return this.contentElement.contains(n)?t:null}isSelectionBackward(e){if(!e.anchorNode||!e.focusNode)return!1;try{const t=document.createRange();return t.setStart(e.anchorNode,e.anchorOffset),t.setEnd(e.focusNode,e.focusOffset),t.collapsed}catch(t){return!1}}getSelectionAnchorRect(e,t){const n=Array.from(t.getClientRects()).filter(o=>o.width>0||o.height>0);return n.length===0?t.getBoundingClientRect():this.isSelectionBackward(e)?n[0]:n[n.length-1]}updateFloatingToolbar(){if(!this.floatingToolbar||!this.contentElement)return;if(this.config.readonly||this.contentElement.contentEditable==="false"||this.contentElement.getAttribute("data-readonly")==="true"||this.getAttribute("readonly")==="true"||this.getAttribute("data-readonly")==="true"){this.floatingToolbar.hide();return}const t=this.getPerformanceConfig(),n=document.activeElement===this.contentElement||!!this.contentElement&&this.contentElement.contains(document.activeElement);if(t.viewportOnlyScan&&!this.isEditorInViewport()&&!n){this.floatingToolbar.hide();return}const i=this.getSelectionRangeInEditor();if(!i){this.floatingToolbar.hide();return}if(i.collapsed){this.floatingToolbar.hide();return}const o=window.getSelection();if(!o){this.floatingToolbar.hide();return}const r=this.getSelectionAnchorRect(o,i);if(!r){this.floatingToolbar.hide();return}this.floatingToolbar.show(r.left,r.top-40)}updateStatusBar(){if(!this.statusBar||!this.contentElement)return;const e=this.getPerformanceConfig(),t=document.activeElement===this.contentElement||this.contentElement.contains(document.activeElement);if(e.viewportOnlyScan&&!this.isEditorInViewport()&&!t)return;const n=this.contentElement.textContent||"",{words:i,chars:o}=Ht(n),r=It(this.contentElement);let a,l;const c=this.getSelectionRangeInEditor();c&&(a=At(this.contentElement,c),c.collapsed||(l=Ot(c,a),a=void 0)),this.statusBar.update({wordCount:i,charCount:o,lineCount:r,cursorPosition:a,selectionInfo:l})}handleAttributeChange(e,t){switch(e){case"readonly":this.contentElement&&(this.contentElement.contentEditable=t==="true"?"false":"true",this.applyAccessibilitySettings()),this.engine&&this.engine.setReadonly(t==="true");break;case"theme":this.classList.forEach(n=>{n.startsWith("editora-theme-")&&this.classList.remove(n)}),t&&this.classList.add(`editora-theme-${t}`);break;case"placeholder":this.contentElement&&(this.contentElement.setAttribute("data-placeholder",t),this.applyAccessibilitySettings());break;case"accessibility":case"accessibility-enable-aria":case"accessibility-keyboard-navigation":case"accessibility-checker":this.applyAccessibilitySettings();break;case"performance":case"performance-debounce-input-ms":case"performance-viewport-only-scan":break;case"language":case"language-locale":case"language-direction":this.applyLanguageSettings();break;case"spellcheck":case"spellcheck-enabled":case"spellcheck-provider":this.applySpellcheckSettings();break;case"autosave":case"autosave-enabled":case"autosave-interval-ms":case"autosave-storage-key":case"autosave-provider":case"autosave-api-url":this.startAutosave();break;case"security":case"security-sanitize-on-paste":case"security-sanitize-on-input":case"paste":case"paste-clean":case"paste-keep-formatting":case"paste-convert-word":case"context-menu":case"context-menu-enabled":break;case"toolbar":case"toolbar-items":case"toolbar-floating":case"toolbar-sticky":case"plugins":case"statusbar":this.isConnected&&(this.destroy(),this.waitForPluginLoader().then(()=>{this.initialize().catch(n=>{console.error("[RichTextEditor] Error during attribute change re-initialization:",n)})}));break}}resolveConfig(){const e={};for(let t=0;t<this.attributes.length;t++){const n=this.attributes[t];e[n.name]=n.value}return ae.resolve({jsConfig:this.jsConfig,attributes:e})}getAPI(){return{getContent:()=>{var e;return((e=this.contentElement)==null?void 0:e.innerHTML)||""},setContent:e=>{this.contentElement&&(this.contentElement.innerHTML=e)},execCommand:(e,t)=>this.executeCommand(e,t),focus:()=>{var e;(e=this.contentElement)==null||e.focus()},blur:()=>{var e;(e=this.contentElement)==null||e.blur()},destroy:()=>{this.destroy()},on:(e,t)=>(this.addEventListener(e,t),()=>this.removeEventListener(e,t)),getConfig:()=>({...this.config}),setReadonly:e=>{this.setAttribute("readonly",e.toString())}}}destroy(){var e,t,n,i;this.contentChangeDebounceTimer&&(clearTimeout(this.contentChangeDebounceTimer),this.contentChangeDebounceTimer=void 0),this.contentElement&&this.persistAutosave(this.contentElement.innerHTML||""),this.stopAutosave(),this.selectionChangeHandler&&(document.removeEventListener("selectionchange",this.selectionChangeHandler),this.selectionChangeHandler=void 0),(e=this.engine)==null||e.destroy(),(t=this.toolbar)==null||t.destroy(),(n=this.floatingToolbar)==null||n.destroy(),(i=this.statusBar)==null||i.destroy(),this.innerHTML="",this.contentElement=void 0,this.toolbarElement=void 0,this.statusBarElement=void 0,this.loadedPlugins=[],this.isInitialized=!1,le.delete(this),I===this&&(I=null),this.dispatchEvent(new Event("editor-destroy",{bubbles:!0}))}getContent(){var e;return((e=this.contentElement)==null?void 0:e.innerHTML)||""}setContent(e){this.contentElement&&(this.contentElement.innerHTML=e)}execCommand(e,t){return this.executeCommand(e,t)}focus(){var e;(e=this.contentElement)==null||e.focus()}blur(){var e;(e=this.contentElement)==null||e.blur()}}const de=new $;L.__globalPluginLoader=de;const Zt={bold:()=>Promise.resolve().then(()=>en).then(s=>s.BoldPlugin()),italic:()=>Promise.resolve().then(()=>nn).then(s=>s.ItalicPlugin()),underline:()=>Promise.resolve().then(()=>on).then(s=>s.UnderlinePlugin()),strikethrough:()=>Promise.resolve().then(()=>an).then(s=>s.StrikethroughPlugin()),clearFormatting:()=>Promise.resolve().then(()=>xn).then(s=>s.ClearFormattingPlugin()),heading:()=>Promise.resolve().then(()=>Dn).then(s=>s.HeadingPlugin()),blockquote:()=>Promise.resolve().then(()=>qn).then(s=>s.BlockquotePlugin()),code:()=>Promise.resolve().then(()=>hi).then(s=>s.CodePlugin()),list:()=>Promise.resolve().then(()=>gi).then(s=>s.ListPlugin()),history:()=>Promise.resolve().then(()=>bi).then(s=>s.HistoryPlugin())};async function ze(){return Object.entries(Zt).forEach(([s,e])=>{de.register(s,e)}),de}typeof window!="undefined"&&ze().then(s=>{L.__globalPluginLoader=s,customElements.get("editora-editor")||customElements.define("editora-editor",L);const e=document.querySelectorAll("editora-editor:not([data-initial-content])"),t=[];e.forEach(n=>{const i=n.innerHTML.trim();i&&(t.push(i),n.setAttribute("data-initial-content",i),n.innerHTML="")}),e.forEach((n,i)=>{n instanceof L&&!n.isInitialized&&t[i]&&n.setAttribute("content",t[i])})});const Y="data-editora-selection-marker";function Gt(s){return s?s.nodeType===Node.ELEMENT_NODE?s:s.parentElement:null}function _e(s){return s?s.getAttribute("contenteditable")==="true"?s:s.querySelector('[contenteditable="true"]'):null}function Qt(s){var r;if((s==null?void 0:s.contentElement)instanceof HTMLElement)return s.contentElement;const e=_e((r=s==null?void 0:s.editorElement)!=null?r:null);if(e)return e;const t=typeof window!="undefined"?window.__editoraCommandEditorRoot:null,n=t instanceof HTMLElement?_e(t):null;if(n)return n;const i=window.getSelection();if(i&&i.rangeCount>0){const a=Gt(i.getRangeAt(0).startContainer),l=a==null?void 0:a.closest('.rte-content, .editora-content, [contenteditable="true"]');if(l instanceof HTMLElement)return l}const o=document.activeElement;if(o instanceof HTMLElement){const a=o.closest('.rte-content, .editora-content, [contenteditable="true"]');if(a instanceof HTMLElement)return a}return document.querySelector('.rte-content, .editora-content, [contenteditable="true"]')}function Xt(s){const e=window.getSelection();if(!e||e.rangeCount===0)return!1;const t=e.getRangeAt(0);return s.contains(t.startContainer)&&s.contains(t.endContainer)}function je(s){const e=document.createElement("span");return e.setAttribute(Y,s),e.style.display="inline-block",e.style.width="0",e.style.height="0",e.style.overflow="hidden",e.style.lineHeight="0",e.appendChild(document.createTextNode("\uFEFF")),e}function Yt(s){const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0);if(!s.contains(t.startContainer)||!s.contains(t.endContainer))return null;const n=t.collapsed,i=je("start"),o=n?null:je("end"),r=t.cloneRange();if(o){const l=r.cloneRange();l.collapse(!1),l.insertNode(o)}const a=r.cloneRange();return a.collapse(!0),a.insertNode(i),()=>{const l=window.getSelection(),c=document.createRange(),h=s.querySelector(`[${Y}="start"]`),u=s.querySelector(`[${Y}="end"]`);if(!l||!h){s.querySelectorAll(`[${Y}]`).forEach(d=>d.remove());return}n||!u?(c.setStartBefore(h),c.collapse(!0)):(c.setStartAfter(h),c.setEndBefore(u)),l.removeAllRanges(),l.addRange(c),h.remove(),u==null||u.remove()}}function Jt(s,e,t){if(e!==t){if(typeof window.execEditorCommand=="function"){window.execEditorCommand("recordDomTransaction",s,e,t);return}if(typeof window.executeEditorCommand=="function")try{window.executeEditorCommand("recordDomTransaction",{editor:s,beforeHTML:e,afterHTML:t})}catch(n){}}}function J(s){const e=Qt(s.context);if(!e)return!1;const t=e.innerHTML;Xt(e)&&e.focus({preventScroll:!0});let n=!1;try{n=document.execCommand(s.command,!1)}catch(r){n=!1}const i=e.innerHTML;if(s.normalize&&i!==t){const r=Yt(e);s.normalize(e),r==null||r()}const o=e.innerHTML;return t!==o&&(Jt(e,t,o),e.dispatchEvent(new Event("input",{bubbles:!0}))),n!==!1||t!==o}const en=Object.freeze(Object.defineProperty({__proto__:null,BoldPlugin:()=>({name:"bold",marks:{bold:{parseDOM:[{tag:"strong"},{tag:"b"},{style:"font-weight",getAttrs:s=>{const e=typeof s=="string"?s:s.style.fontWeight;return/^(bold(er)?|[5-9]\d{2,})$/.test(e)&&null}}],toDOM:()=>["strong",0]}},toolbar:[{label:"Bold",command:"toggleBold",icon:'<svg width="24" height="24" focusable="false"><path d="M7.8 19c-.3 0-.5 0-.6-.2l-.2-.5V5.7c0-.2 0-.4.2-.5l.6-.2h5c1.5 0 2.7.3 3.5 1 .7.6 1.1 1.4 1.1 2.5a3 3 0 0 1-.6 1.9c-.4.6-1 1-1.6 1.2.4.1.9.3 1.3.6s.8.7 1 1.2c.4.4.5 1 .5 1.6 0 1.3-.4 2.3-1.3 3-.8.7-2.1 1-3.8 1H7.8Zm5-8.3c.6 0 1.2-.1 1.6-.5.4-.3.6-.7.6-1.3 0-1.1-.8-1.7-2.3-1.7H9.3v3.5h3.4Zm.5 6c.7 0 1.3-.1 1.7-.4.4-.4.6-.9.6-1.5s-.2-1-.7-1.4c-.4-.3-1-.4-2-.4H9.4v3.8h4Z" fill-rule="evenodd"></path></svg>',shortcut:"Mod-b"}],commands:{toggleBold:(s,e)=>J({command:"bold",context:e})},keymap:{"Mod-b":"toggleBold","Mod-B":"toggleBold"}})},Symbol.toStringTag,{value:"Module"})),ue=(s,e)=>J({command:"italic",context:e}),tn=(s,e)=>{var t;typeof window!="undefined"&&((t=window.registerEditorCommand)==null||t.call(window,s,e))},Ue=()=>{tn("toggleItalic",ue)};typeof window!="undefined"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Ue):Ue());const nn=Object.freeze(Object.defineProperty({__proto__:null,ItalicPlugin:()=>({name:"italic",marks:{italic:{parseDOM:[{tag:"i"},{tag:"em"},{style:"font-style=italic"}],toDOM:()=>["em",0]}},toolbar:[{label:"Italic",command:"toggleItalic",type:"button",icon:'<svg width="24" height="24" focusable="false"><path d="M16.7 4.7l-.1.9h-.3c-.6 0-1 0-1.4.3-.3.3-.4.6-.5 1.1l-2.1 9.8v.6c0 .5.4.8 1.4.8h.2l-.2.8H8l.2-.8h.2c1.1 0 1.8-.5 2-1.5l2-9.8.1-.5c0-.6-.4-.8-1.4-.8h-.3l.2-.9h5.8Z" fill-rule="evenodd"></path></svg>',shortcut:"Mod-i"}],commands:{toggleItalic:ue},keymap:{"Mod-i":"toggleItalic","Mod-I":"toggleItalic"}}),toggleItalic:ue},Symbol.toStringTag,{value:"Module"})),on=Object.freeze(Object.defineProperty({__proto__:null,UnderlinePlugin:()=>({name:"underline",marks:{underline:{parseDOM:[{tag:"u"}],toDOM:()=>["u",{},0]}},toolbar:[{label:"Underline",command:"toggleUnderline",icon:'<svg width="24" height="24" focusable="false"><path d="M16 5c.6 0 1 .4 1 1v7c0 2.8-2.2 5-5 5s-5-2.2-5-5V6c0-.6.4-1 1-1s1 .4 1 1v7c0 1.7 1.3 3 3 3s3-1.3 3-3V6c0-.6.4-1 1-1ZM4 17h16c.6 0 1 .4 1 1s-.4 1-1 1H4a1 1 0 1 1 0-2Z" fill-rule="evenodd"></path></svg>',shortcut:"Mod-u"}],commands:{toggleUnderline:(s,e)=>J({command:"underline",context:e})},keymap:{"Mod-u":"toggleUnderline","Mod-U":"toggleUnderline"}})},Symbol.toStringTag,{value:"Module"})),rn=()=>({name:"strikethrough",marks:{strikethrough:{parseDOM:[{tag:"s"},{tag:"strike"},{tag:"del"},{style:"text-decoration",getAttrs:s=>(typeof s=="string"?s:s.style.textDecoration)==="line-through"&&null}],toDOM:()=>["s",0]}},toolbar:[{label:"Strikethrough",command:"toggleStrikethrough",icon:'<svg width="24" height="24" focusable="false"><g fill-rule="evenodd"><path d="M15.6 8.5c-.5-.7-1-1.1-1.3-1.3-.6-.4-1.3-.6-2-.6-2.7 0-2.8 1.7-2.8 2.1 0 1.6 1.8 2 3.2 2.3 4.4.9 4.6 2.8 4.6 3.9 0 1.4-.7 4.1-5 4.1A6.2 6.2 0 0 1 7 16.4l1.5-1.1c.4.6 1.6 2 3.7 2 1.6 0 2.5-.4 3-1.2.4-.8.3-2-.8-2.6-.7-.4-1.6-.7-2.9-1-1-.2-3.9-.8-3.9-3.6C7.6 6 10.3 5 12.4 5c2.9 0 4.2 1.6 4.7 2.4l-1.5 1.1Z"></path><path d="M5 11h14a1 1 0 0 1 0 2H5a1 1 0 0 1 0-2Z" fill-rule="nonzero"></path></g></svg>',shortcut:"Mod-Shift-x"}],commands:{toggleStrikethrough:(s,e)=>J({command:"strikeThrough",context:e,normalize:sn})},keymap:{"Mod-Shift-x":"toggleStrikethrough","Mod-Shift-X":"toggleStrikethrough"}});function sn(s){s.querySelectorAll("strike, del").forEach(t=>{var i;const n=document.createElement("s");for(const o of Array.from(t.attributes))o.name!=="style"&&n.setAttribute(o.name,o.value);for(;t.firstChild;)n.appendChild(t.firstChild);(i=t.parentNode)==null||i.replaceChild(n,t)})}const an=Object.freeze(Object.defineProperty({__proto__:null,StrikethroughPlugin:rn},Symbol.toStringTag,{value:"Module"})),ln=()=>({name:"clearFormatting",toolbar:[{label:"Clear Formatting",command:"clearFormatting",icon:'<svg width="24" height="24" focusable="false"><path d="M13.2 6a1 1 0 0 1 0 .2l-2.6 10a1 1 0 0 1-1 .8h-.2a.8.8 0 0 1-.8-1l2.6-10H8a1 1 0 1 1 0-2h9a1 1 0 0 1 0 2h-3.8ZM5 18h7a1 1 0 0 1 0 2H5a1 1 0 0 1 0-2Zm13 1.5L16.5 18 15 19.5a.7.7 0 0 1-1-1l1.5-1.5-1.5-1.5a.7.7 0 0 1 1-1l1.5 1.5 1.5-1.5a.7.7 0 0 1 1 1L17.5 17l1.5 1.5a.7.7 0 0 1-1 1Z" fill-rule="evenodd"></path></svg>',shortcut:"Mod-\\"}],commands:{clearFormatting:()=>{const s=un();if(!s)return!1;const e=window.getSelection();if(!e||e.rangeCount===0)return!1;const t=e.getRangeAt(0);if(!s.contains(t.commonAncestorContainer))return!1;const n=t.cloneRange();return s.focus({preventScroll:!0}),vn(s,n),yn(s,n),s.dispatchEvent(new Event("input",{bubbles:!0})),!0}},keymap:{"Mod-\\":"clearFormatting"}}),cn=new Set(["A","B","STRONG","I","EM","U","S","STRIKE","DEL","FONT","MARK","CODE","SUB","SUP"]),hn=new Set(["H1","H2","H3","H4","H5","H6","BLOCKQUOTE","PRE"]),dn=["color","background-color","font-size","font-family","font-weight","font-style","text-decoration","text-transform","line-height","letter-spacing","word-spacing","vertical-align","text-align","padding-left"];function un(){const s=window.getSelection();if(s&&s.rangeCount>0){const t=s.getRangeAt(0).startContainer,n=t.nodeType===Node.ELEMENT_NODE?t:t.parentElement,i=n==null?void 0:n.closest('[contenteditable="true"], .rte-content, .editora-content');if(i)return i}const e=document.activeElement;return e?e.getAttribute("contenteditable")==="true"?e:e.closest('[contenteditable="true"], .rte-content, .editora-content'):null}function We(s,e){try{if(typeof s.intersectsNode=="function")return s.intersectsNode(e)}catch(n){}const t=document.createRange();return e.nodeType===Node.ELEMENT_NODE?t.selectNodeContents(e):t.selectNode(e),s.compareBoundaryPoints(Range.END_TO_START,t)>0&&s.compareBoundaryPoints(Range.START_TO_END,t)<0}function ee(s){let e=0,t=s;for(;t&&t.parentNode;)e+=1,t=t.parentNode;return e}function gn(s){dn.forEach(e=>{s.style.removeProperty(e)}),(!s.getAttribute("style")||s.style.length===0)&&s.removeAttribute("style"),s.classList.contains("rte-text-color")&&s.classList.remove("rte-text-color"),s.classList.contains("rte-bg-color")&&s.classList.remove("rte-bg-color"),s.classList.contains("rte-format-painted")&&s.classList.remove("rte-format-painted"),s.classList.length===0&&s.removeAttribute("class")}function ge(s){const e=s.parentNode;if(e){for(;s.firstChild;)e.insertBefore(s.firstChild,s);e.removeChild(s)}}function fn(s){return s.tagName!=="P"||s.attributes.length>0||(s.textContent||"").trim()!==""?!1:!s.querySelector("img, video, table, iframe, hr, pre, ul, ol")}function Ve(s){Array.from(s.children).forEach(e=>{fn(e)&&e.remove()})}function Ke(s){Ve(s),ge(s)}function qe(s){var t;const e=document.createElement("p");for(Array.from(s.attributes).forEach(n=>{e.setAttribute(n.name,n.value)});s.firstChild;)e.appendChild(s.firstChild);e.innerHTML.trim()||(e.innerHTML="<br>"),(t=s.parentNode)==null||t.replaceChild(e,s)}function pn(s){return!/^(A|B|STRONG|I|EM|U|S|STRIKE|DEL|FONT|MARK|CODE|SUB|SUP|SPAN)$/.test(s.tagName)||(s.textContent||"").trim()!==""?!1:!s.querySelector("img, video, table, iframe, hr, svg, math")}function mn(s){Array.from(s.querySelectorAll("a,b,strong,i,em,u,s,strike,del,font,mark,code,sub,sup,span")).sort((t,n)=>ee(n)-ee(t)).forEach(t=>{t.isConnected&&pn(t)&&t.remove()})}function bn(s){if(Ve(s),s.parentElement instanceof HTMLLIElement){Ke(s);return}if(Array.from(s.childNodes).filter(i=>i.nodeType!==Node.TEXT_NODE||(i.textContent||"").trim()!=="").some(i=>i instanceof HTMLElement&&/^(P|DIV|H[1-6]|UL|OL|PRE|TABLE|BLOCKQUOTE)$/.test(i.tagName))){Ke(s);return}qe(s)}function yn(s,e){Array.from(s.querySelectorAll("h1,h2,h3,h4,h5,h6,blockquote,pre")).forEach(n=>{if(We(e,n)&&hn.has(n.tagName)){if(n.tagName==="BLOCKQUOTE"){bn(n);return}qe(n)}})}function vn(s,e){const t=Array.from(s.querySelectorAll("a,b,strong,i,em,u,s,strike,del,font,mark,code,sub,sup,span,[style],[class]"));t.sort((n,i)=>ee(i)-ee(n)),t.forEach(n=>{if(n.isConnected&&We(e,n)&&!(n.getAttribute("contenteditable")==="false"||n.closest('[contenteditable="false"]'))){if(gn(n),cn.has(n.tagName)){ge(n);return}n.tagName==="SPAN"&&n.attributes.length===0&&ge(n)}}),mn(s)}const xn=Object.freeze(Object.defineProperty({__proto__:null,ClearFormattingPlugin:ln},Symbol.toStringTag,{value:"Module"})),j='.rte-content, .editora-content, [contenteditable="true"]',Cn="[data-editora-editor], .rte-editor, .editora-editor, editora-editor",Ze=new Set(["P","DIV","H1","H2","H3","H4","H5","H6","PRE"]),Ge="p,div,h1,h2,h3,h4,h5,h6,ul,ol,blockquote,pre,table",wn=new Set(["p","h1","h2","h3","h4","h5","h6"]);function Qe(s){return s?s.nodeType===Node.ELEMENT_NODE?s:s.parentElement:null}function En(s){const e=s==null?void 0:s.contentElement;if(e instanceof HTMLElement)return e;const t=s==null?void 0:s.editorElement;if(t instanceof HTMLElement){const r=t.querySelector(j);if(r instanceof HTMLElement)return r;if(t.getAttribute("contenteditable")==="true")return t}const n=window.getSelection();if(n&&n.rangeCount>0){const r=Qe(n.getRangeAt(0).startContainer),a=r==null?void 0:r.closest(j);if(a instanceof HTMLElement)return a;const l=r==null?void 0:r.closest(Cn),c=l==null?void 0:l.querySelector(j);if(c instanceof HTMLElement)return c}const i=document.activeElement,o=i==null?void 0:i.closest(j);return o instanceof HTMLElement?o:document.querySelector(j)}function Tn(s){const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0);return!s.contains(t.startContainer)||!s.contains(t.endContainer)?null:t}function Xe(s,e){let t=Qe(e);if(!t||t===s||!s.contains(t))return null;for(;t.parentElement&&t.parentElement!==s;)t=t.parentElement;if(t.parentElement!==s)return null;if(t.matches(Ge))return t;const n=t.closest(Ge);return n instanceof HTMLElement&&n.parentElement===s?n:t}function Ye(s,e){if(typeof s.intersectsNode=="function")try{return s.intersectsNode(e)}catch(n){return!1}const t=document.createRange();return t.selectNode(e),s.compareBoundaryPoints(Range.END_TO_START,t)<0&&s.compareBoundaryPoints(Range.START_TO_END,t)>0}function Sn(s,e){const t=Xe(s,e.startContainer),n=Xe(s,e.endContainer);if(!t)return[];if(!n||t===n)return[t];const o=Array.from(s.children).filter(r=>r instanceof HTMLElement).filter(r=>Ye(e,r));return o.length>0?o:[t]}function kn(s,e){Array.from(s.attributes).forEach(t=>{e.setAttribute(t.name,t.value)})}function fe(s,e){for(;s.firstChild;)e.appendChild(s.firstChild)}function Mn(s){return s.tagName!=="P"||s.attributes.length>0||(s.textContent||"").trim()!==""?!1:!s.querySelector("img, video, table, iframe, hr, pre, ul, ol")}function te(s,e){const t=document.createElement(s);return e&&kn(e,t),t}function Je(s,e){const t=te(e,s);return fe(s,t),t.innerHTML.trim()||(t.innerHTML="<br>"),t}function Ln(s){const e=s.cloneNode(!1);return e instanceof HTMLElement?e:document.createElement(s.tagName.toLowerCase())}function et(s,e,t){const n=s.parentNode;if(!n)return[];const i=document.createDocumentFragment(),o=[];let r=null;const a=()=>{r&&r.children.length>0&&i.appendChild(r),r=null};return Array.from(s.children).forEach(l=>{if(l instanceof HTMLLIElement){if(e.has(l)){a();const c=Je(l,t);i.appendChild(c),o.push(c);return}r||(r=Ln(s)),r.appendChild(l)}}),a(),n.insertBefore(i,s),n.removeChild(s),o}function An(s,e){var n;if(s.tagName.toLowerCase()===e)return[s];const t=te(e,s);return fe(s,t),t.innerHTML.trim()||(t.innerHTML="<br>"),(n=s.parentNode)==null||n.replaceChild(t,s),[t]}function Rn(s,e){const t=s.parentNode;if(!t)return[];const n=document.createDocumentFragment(),i=[];return Array.from(s.childNodes).forEach(o=>{if(o instanceof HTMLElement&&Mn(o)){o.remove();return}if(o instanceof HTMLUListElement||o instanceof HTMLOListElement){Array.from(o.children).forEach(a=>{if(!(a instanceof HTMLLIElement))return;const l=Je(a,e);n.appendChild(l),i.push(l)}),o.remove();return}if(o instanceof HTMLElement&&Ze.has(o.tagName)){const a=te(e,o);fe(o,a),n.appendChild(a),i.push(a);return}if(o.nodeType===Node.TEXT_NODE&&(o.textContent||"").trim()===""){o.remove();return}const r=te(e,s);r.appendChild(o),n.appendChild(r),i.push(r)}),t.insertBefore(n,s),t.removeChild(s),i}function In(s){const e=window.getSelection();if(!e)return;const t=document.createRange(),n=s instanceof HTMLElement&&s.querySelector("p,li,h1,h2,h3,h4,h5,h6")||s;t.selectNodeContents(n),t.collapse(!0),e.removeAllRanges(),e.addRange(t)}function Hn(s){s.dispatchEvent(new Event("input",{bubbles:!0}))}function On(s,e,t){const n=window.execEditorCommand;if(typeof n=="function"){n("recordDomTransaction",s,e,t);return}const i=window.executeEditorCommand;typeof i=="function"&&i("recordDomTransaction",{editor:s,beforeHTML:e,afterHTML:t})}function Nn(s,e){const t=new Map;return Array.from(s.querySelectorAll("li")).filter(i=>i instanceof HTMLLIElement&&Ye(e,i)).forEach(i=>{var r;const o=i.parentElement;(o instanceof HTMLUListElement||o instanceof HTMLOListElement)&&o.parentElement===s&&(t.has(o)||t.set(o,new Set),(r=t.get(o))==null||r.add(i))}),t}function U(s,e){const t=s.toLowerCase();if(!wn.has(t))return!1;const n=En(e);if(!n)return!1;const i=Tn(n);if(!i)return!1;const o=n.innerHTML,r=[],a=Nn(n,i);a.size>0?a.forEach((c,h)=>{r.push(...et(h,c,t))}):Sn(n,i).forEach(h=>{if(h instanceof HTMLUListElement||h instanceof HTMLOListElement){const u=new Set(Array.from(h.children).filter(d=>d instanceof HTMLLIElement));r.push(...et(h,u,t));return}if(Ze.has(h.tagName)){const u=h.querySelector(":scope > ul, :scope > ol, :scope > blockquote, :scope > table");r.push(...u?Rn(h,t):An(h,t))}});const l=n.innerHTML;return o===l||r.length===0?!1:(On(n,o,l),Hn(n),In(r[0]),!0)}const Dn=Object.freeze(Object.defineProperty({__proto__:null,HeadingPlugin:()=>({name:"heading",toolbar:[{label:"P",command:"setBlockType",type:"dropdown",options:[{value:"p",label:"P"},{value:"h1",label:"H1"},{value:"h2",label:"H2"},{value:"h3",label:"H3"},{value:"h4",label:"H4"},{value:"h5",label:"H5"},{value:"h6",label:"H6"}],icon:'<svg width="24" height="24" focusable="false"><path d="M16.1 8.6 14.2 4l-1.4.5 2.8 7.4c.1.4.5.6.9.6h.1c.4-.1.6-.5.6-.9l1.8-4.8-1.4-.5-1.5 2.3ZM4 11.5h6V10H4v1.5ZM18.5 3v1L17 7l.9.9L20.7 3h-2.2ZM5.5 12h1v7h1v-7h1v-.5h-3V12Zm4 0h1v7h1v-7h1v-.5h-3V12Zm10 1.5a2 2 0 0 0-2-2h-1v7.5h1v-2.7h1a2 2 0 0 0 2-2v-.8Zm-2 1.3h-1v-2.3h1a.8.8 0 1 1 0 1.6v.7Z" fill-rule="evenodd"></path></svg>'}],commands:{setBlockType:(s,e)=>s?U(s,e):!1,setHeading1:(s,e)=>U("h1",e),setHeading2:(s,e)=>U("h2",e),setHeading3:(s,e)=>U("h3",e),setParagraph:(s,e)=>U("p",e)},keymap:{"Mod-Alt-1":"setHeading1","Mod-Alt-2":"setHeading2","Mod-Alt-3":"setHeading3","Mod-Alt-0":"setParagraph"}})},Symbol.toStringTag,{value:"Module"})),W='.rte-content, .editora-content, [contenteditable="true"]',Pn="[data-editora-editor], .rte-editor, .editora-editor, editora-editor",tt=["p","div","h1","h2","h3","h4","h5","h6","ul","ol","blockquote","pre","table"].join(",");function pe(s){return s?s.nodeType===Node.ELEMENT_NODE?s:s.parentElement:null}function $n(s){const e=s==null?void 0:s.contentElement;if(e instanceof HTMLElement)return e;const t=s==null?void 0:s.editorElement;if(t instanceof HTMLElement){const r=t.querySelector(W);if(r instanceof HTMLElement)return r;if(t.getAttribute("contenteditable")==="true")return t}const n=window.getSelection();if(n&&n.rangeCount>0){const r=pe(n.getRangeAt(0).startContainer),a=r==null?void 0:r.closest(W);if(a instanceof HTMLElement)return a;const l=r==null?void 0:r.closest(Pn),c=l==null?void 0:l.querySelector(W);if(c instanceof HTMLElement)return c}const i=document.activeElement,o=i==null?void 0:i.closest(W);return o instanceof HTMLElement?o:document.querySelector(W)}function Fn(s){const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0);return!s.contains(t.startContainer)||!s.contains(t.endContainer)?null:t}function nt(s,e){let t=pe(e);if(!t||t===s||!s.contains(t))return null;for(;t.parentElement&&t.parentElement!==s;)t=t.parentElement;if(t.parentElement!==s)return null;if(t.matches(tt))return t;const n=t.closest(tt);return n instanceof HTMLElement&&n.parentElement===s?n:t}function it(s,e){if(typeof s.intersectsNode=="function")try{return s.intersectsNode(e)}catch(n){return!1}const t=document.createRange();return t.selectNode(e),s.compareBoundaryPoints(Range.END_TO_START,t)<0&&s.compareBoundaryPoints(Range.START_TO_END,t)>0}function Bn(s,e){const t=nt(s,e.startContainer),n=nt(s,e.endContainer);if(!t)return[];if(!n||t===n)return[t];const o=Array.from(s.children).filter(r=>r instanceof HTMLElement).filter(r=>it(e,r));return o.length>0?o:[t]}function ot(s,e){const t=pe(e),n=t==null?void 0:t.closest("blockquote");return n instanceof HTMLQuoteElement&&s.contains(n)?n:null}function zn(s){return s.tagName!=="P"||s.attributes.length>0||(s.textContent||"").trim()!==""?!1:!s.querySelector("img, video, table, iframe, hr, pre, ul, ol")}function _n(s){Array.from(s.children).forEach(e=>{zn(e)&&e.remove()})}function me(s){_n(s);const e=s.parentNode;if(!e)return;Array.from(s.childNodes).forEach(n=>{e.insertBefore(n,s)}),e.removeChild(s)}function rt(s){return s.nodeType===Node.TEXT_NODE&&(s.textContent||"").trim()===""}function st(s){const e=Array.from(s.childNodes).filter(n=>!rt(n));if(e.length!==1)return null;const t=e[0];return t instanceof HTMLQuoteElement?t:null}function jn(s){const e=document.createElement("blockquote");return Array.from(s.childNodes).filter(n=>!rt(n)).forEach(n=>{e.appendChild(n)}),e.childNodes.length||(e.innerHTML="<br>"),s.appendChild(e),e}function Un(s,e){const t=Array.from(s.querySelectorAll("li")).filter(i=>i instanceof HTMLLIElement&&it(e,i)),n=new Set(t);return t.filter(i=>{var r,a;let o=(r=i.parentElement)==null?void 0:r.closest("li");for(;o;){if(n.has(o))return!1;o=(a=o.parentElement)==null?void 0:a.closest("li")}return!0})}function V(s){const e=window.getSelection();if(!e)return;const t=document.createRange(),n=s instanceof HTMLElement&&s.querySelector("p,li,h1,h2,h3,h4,h5,h6")||s;t.selectNodeContents(n),t.collapse(!0),e.removeAllRanges(),e.addRange(t)}function Wn(s){s.dispatchEvent(new Event("input",{bubbles:!0}))}function Vn(s,e,t){const n=window.execEditorCommand;if(typeof n=="function"){n("recordDomTransaction",s,e,t);return}const i=window.executeEditorCommand;typeof i=="function"&&i("recordDomTransaction",{editor:s,beforeHTML:e,afterHTML:t})}function Kn(s){var h,u;const e=$n(s);if(!e)return!1;const t=Fn(e);if(!t)return!1;const n=e.innerHTML,i=ot(e,t.startContainer),o=ot(e,t.endContainer),r=Un(e,t),a=Bn(e,t),l=a.length>0&&a.every(d=>d.tagName==="BLOCKQUOTE");if(i&&i===o){const d=i.firstChild||i;me(i),V(d)}else if(r.length>0){const d=r.map(st);if(d.every(Boolean)){const f=((h=d[0])==null?void 0:h.firstChild)||r[0];d.forEach(p=>{p&&me(p)}),V(f)}else{const f=r[0];r.forEach(p=>{st(p)||jn(p)}),V(f)}}else if(l){const d=a[0].firstChild||a[0];a.forEach(me),V(d)}else{const d=a.filter(p=>p.tagName!=="BLOCKQUOTE");if(d.length===0)return!1;const g=document.createElement("blockquote"),f=d[0];(u=f.parentNode)==null||u.insertBefore(g,f),d.forEach(p=>{g.appendChild(p)}),V(g)}const c=e.innerHTML;return n===c?!1:(Vn(e,n,c),Wn(e),!0)}const qn=Object.freeze(Object.defineProperty({__proto__:null,BlockquotePlugin:()=>({name:"blockquote",nodes:{blockquote:{content:"block+",group:"block",parseDOM:[{tag:"blockquote"}],toDOM:()=>["blockquote",0]}},toolbar:[{label:"Quote",command:"toggleBlockquote",icon:'<svg fill="#000000" height="24px" width="24px" version="1.1" id="Icons" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 32 32" xml:space="preserve"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <g> <path d="M13,11c0.6,0,1-0.4,1-1s-0.4-1-1-1c-5,0-9,4-9,9c0,2.8,2.2,5,5,5s5-2.2,5-5s-2.2-5-5-5c-0.3,0-0.7,0-1,0.1 C9.3,11.8,11,11,13,11z"></path> <path d="M23,13c-0.3,0-0.7,0-1,0.1c1.3-1.3,3-2.1,5-2.1c0.6,0,1-0.4,1-1s-0.4-1-1-1c-5,0-9,4-9,9c0,2.8,2.2,5,5,5s5-2.2,5-5 S25.8,13,23,13z"></path> </g> </g></svg>',shortcut:"Mod-Shift-9"}],commands:{toggleBlockquote:(s,e)=>Kn(e)},keymap:{"Mod-Shift-9":"toggleBlockquote"}})},Symbol.toStringTag,{value:"Module"}));class be{constructor(e=""){this._lines=[],this._version=0,this.setText(e)}getLine(e){return this._lines[e]||""}getLines(){return[...this._lines]}getLineCount(){return this._lines.length}getText(){return this._lines.join(`
9
+ `}),n}getShortcutCategory(e){return e.includes("toggle")&&(e.includes("Bold")||e.includes("Italic")||e.includes("Underline")||e.includes("Strike")||e.includes("Code")||e.includes("Super")||e.includes("Sub"))?"Text Formatting":e.includes("Heading")||e.includes("Paragraph")?"Block Formatting":e.includes("List")||e.includes("Checklist")?"Lists":e.includes("Alignment")||e.includes("Indent")?"Alignment & Indentation":e.includes("undo")||e.includes("redo")?"History":e.includes("insert")?"Insert":e.includes("find")||e.includes("replace")?"Find & Replace":e.includes("Accessibility")||e.includes("spell")?"Tools":"Other"}}const Dt=["p","br","strong","em","u","s","strike","del","b","i","h1","h2","h3","h4","h5","h6","ul","ol","li","a","img","video","audio","iframe","table","thead","tbody","tr","th","td","blockquote","pre","code","span","div","section","sup","sub","hr"],Pt={"*":["class","style","id","data-*","role","aria-*","tabindex","contenteditable","spellcheck","dir","lang"],a:["href","target","rel","title"],img:["src","alt","width","height","loading"],video:["src","controls","width","height","autoplay","loop","muted"],audio:["src","controls","autoplay","loop","muted"],iframe:["src","width","height","name","title","longdesc","allow","allowfullscreen","frameborder","scrolling","loading","referrerpolicy"],table:["border","cellpadding","cellspacing"],td:["colspan","rowspan","align","valign"],th:["colspan","rowspan","align","valign"]};function $e(s,e,t){if((e==null?void 0:e.sanitize)===!1)return s;const n=e!=null&&e.allowedTags&&e.allowedTags.length>0?e.allowedTags:Dt,o=!!(e!=null&&e.allowedAttributes)&&Object.keys(e.allowedAttributes).length>0?e.allowedAttributes:Pt,r=document.createElement("div");return r.innerHTML=s,Fe(r,n,o),r.innerHTML}function Fe(s,e,t){const n=Array.from(s.childNodes);for(const i of n)if(i.nodeType===Node.ELEMENT_NODE){const o=i,r=o.tagName.toLowerCase();if(!e.includes(r)){for(;o.firstChild;)s.insertBefore(o.firstChild,o);s.removeChild(o);continue}$t(o,t),Fe(o,e,t)}else i.nodeType!==Node.TEXT_NODE&&s.removeChild(i)}function $t(s,e){const t=s.tagName.toLowerCase(),n=Array.from(s.attributes),i=e[t]||[],o=e["*"]||[],r=[...i,...o];for(const a of n){const l=a.name.toLowerCase();let c=!1;r.includes(l)&&(c=!0);for(const h of r)if(h.endsWith("*")){const d=h.slice(0,-1);if(l.startsWith(d)){c=!0;break}}(l.startsWith("on")||l==="javascript:"||l==="href"&&a.value.trim().toLowerCase().startsWith("javascript:")||l==="src"&&a.value.trim().toLowerCase().startsWith("javascript:"))&&(c=!1),l==="dir"&&!["ltr","rtl","auto"].includes(a.value.trim().toLowerCase())&&(c=!1),c||s.removeAttribute(a.name)}s.hasAttribute("href")&&(s.getAttribute("href")||"").trim().toLowerCase().startsWith("javascript:")&&s.removeAttribute("href"),s.hasAttribute("src")&&(s.getAttribute("src")||"").trim().toLowerCase().startsWith("javascript:")&&s.removeAttribute("src")}function Ft(s,e,t){return(t==null?void 0:t.sanitizeOnPaste)===!1?s:$e(s,e)}function Bt(s,e,t){return(t==null?void 0:t.sanitizeOnInput)===!1?s:$e(s,e)}const De=class De{static resolve(e){const t={};if(Object.assign(t,this.EDITOR_DEFAULTS),e.pluginDefaults&&Object.assign(t,e.pluginDefaults),e.attributes){const n=this.parseAttributes(e.attributes);Object.assign(t,n)}return e.jsConfig&&Object.assign(t,e.jsConfig),this.normalizeConfig(t)}static normalizeConfig(e){const t={...e};if(t.toolbarFloating!==void 0||t.toolbarSticky!==void 0){const r=typeof t.toolbar=="object"&&t.toolbar?{...t.toolbar}:typeof t.toolbar=="string"?{items:t.toolbar}:{};t.toolbarFloating!==void 0&&(r.floating=!!t.toolbarFloating),t.toolbarSticky!==void 0&&(r.sticky=!!t.toolbarSticky),t.toolbar=r}if(t.toolbarItems!==void 0&&typeof t.toolbar=="object"&&t.toolbar&&(t.toolbar.items=t.toolbarItems),t.autosaveEnabled!==void 0||t.autosaveIntervalMs!==void 0||t.autosaveStorageKey!==void 0||t.autosaveProvider!==void 0||t.autosaveApiUrl!==void 0){const r=typeof t.autosave=="object"&&t.autosave?{...t.autosave}:{};t.autosaveEnabled!==void 0&&(r.enabled=!!t.autosaveEnabled),t.autosaveIntervalMs!==void 0&&(r.intervalMs=Number(t.autosaveIntervalMs)),t.autosaveStorageKey!==void 0&&(r.storageKey=t.autosaveStorageKey),t.autosaveProvider!==void 0&&(r.provider=t.autosaveProvider),t.autosaveApiUrl!==void 0&&(r.apiUrl=t.autosaveApiUrl),t.autosave=r}const n={enabled:!1,intervalMs:3e4,storageKey:"rte-autosave",provider:"localStorage",apiUrl:""};if(typeof t.autosave=="boolean")t.autosave={...n,enabled:t.autosave};else if(typeof t.autosave=="object"&&t.autosave){const r={...n,...t.autosave};r.intervalMs===void 0&&r.interval!==void 0&&(r.intervalMs=Number(r.interval)),r.enabled===void 0&&(r.enabled=!0),(!Number.isFinite(r.intervalMs)||r.intervalMs<=0)&&(r.intervalMs=n.intervalMs),t.autosave=r}else t.autosave=n;if(t.languageLocale!==void 0||t.languageDirection!==void 0){const r=typeof t.language=="object"&&t.language?{...t.language}:{};t.languageLocale!==void 0&&(r.locale=t.languageLocale),t.languageDirection!==void 0&&(r.direction=t.languageDirection),t.language=r}const i={locale:"en",direction:"ltr"};if(typeof t.language=="string"?t.language={locale:t.language,direction:i.direction}:typeof t.language=="object"&&t.language?t.language={...i,...t.language}:t.language=i,t.spellcheckEnabled!==void 0||t.spellcheckProvider!==void 0||t.spellcheckApiUrl!==void 0){const r=typeof t.spellcheck=="object"&&t.spellcheck?{...t.spellcheck}:{};t.spellcheckEnabled!==void 0&&(r.enabled=!!t.spellcheckEnabled),t.spellcheckProvider!==void 0&&(r.provider=t.spellcheckProvider),t.spellcheckApiUrl!==void 0&&(r.apiUrl=t.spellcheckApiUrl),t.spellcheck=r}const o={enabled:!1,provider:"browser",apiUrl:""};if(typeof t.spellcheck=="boolean")t.spellcheck={...o,enabled:t.spellcheck};else if(typeof t.spellcheck=="object"&&t.spellcheck){const r={...o,...t.spellcheck};!r.provider&&r.mode&&(r.provider=r.mode==="local"?"browser":"api"),r.enabled===void 0&&(r.enabled=!!(r.mode||r.provider||r.apiUrl)),t.spellcheck=r}else t.spellcheck=o;return t.contextMenuEnabled!==void 0&&(t.contextMenu={enabled:!!t.contextMenuEnabled}),typeof t.contextMenu=="boolean"?t.contextMenu={enabled:t.contextMenu}:typeof t.contextMenu=="object"&&t.contextMenu?t.contextMenu={enabled:t.contextMenu.enabled!==!1}:t.contextMenu={enabled:!0},(t.pasteClean!==void 0||t.pasteKeepFormatting!==void 0||t.pasteConvertWord!==void 0)&&(t.paste={...t.paste||{},...t.pasteClean!==void 0?{clean:!!t.pasteClean}:{},...t.pasteKeepFormatting!==void 0?{keepFormatting:!!t.pasteKeepFormatting}:{},...t.pasteConvertWord!==void 0?{convertWord:!!t.pasteConvertWord}:{}}),t.paste={clean:!0,keepFormatting:!1,convertWord:!0,...t.paste||{}},t.contentConfig={allowedTags:[],allowedAttributes:{},sanitize:!0,...t.contentConfig||{}},(t.securitySanitizeOnPaste!==void 0||t.securitySanitizeOnInput!==void 0)&&(t.security={...t.security||{},...t.securitySanitizeOnPaste!==void 0?{sanitizeOnPaste:!!t.securitySanitizeOnPaste}:{},...t.securitySanitizeOnInput!==void 0?{sanitizeOnInput:!!t.securitySanitizeOnInput}:{}}),t.security={sanitizeOnPaste:!0,sanitizeOnInput:!0,...t.security||{}},(t.accessibilityEnableAria!==void 0||t.accessibilityKeyboardNavigation!==void 0||t.accessibilityChecker!==void 0)&&(t.accessibility={...t.accessibility||{},...t.accessibilityEnableAria!==void 0?{enableARIA:!!t.accessibilityEnableAria}:{},...t.accessibilityKeyboardNavigation!==void 0?{keyboardNavigation:!!t.accessibilityKeyboardNavigation}:{},...t.accessibilityChecker!==void 0?{checker:!!t.accessibilityChecker}:{}}),typeof t.accessibility=="boolean"&&(t.accessibility={enableARIA:t.accessibility,keyboardNavigation:t.accessibility,checker:!1}),t.accessibility={enableARIA:!0,keyboardNavigation:!0,checker:!1,...t.accessibility||{}},(t.performanceDebounceInputMs!==void 0||t.performanceViewportOnlyScan!==void 0)&&(t.performance={...t.performance||{},...t.performanceDebounceInputMs!==void 0?{debounceInputMs:Number(t.performanceDebounceInputMs)}:{},...t.performanceViewportOnlyScan!==void 0?{viewportOnlyScan:!!t.performanceViewportOnlyScan}:{}}),typeof t.performance=="boolean"&&(t.performance={debounceInputMs:100,viewportOnlyScan:t.performance}),t.performance={debounceInputMs:100,viewportOnlyScan:!0,...t.performance||{}},(typeof t.performance.debounceInputMs!="number"||!Number.isFinite(t.performance.debounceInputMs)||t.performance.debounceInputMs<0)&&(t.performance.debounceInputMs=100),t}static parseAttributes(e){const t={};for(const[n,i]of Object.entries(e)){const o=this.kebabToCamel(n);t[o]=this.parseAttributeValue(i)}return t}static parseAttributeValue(e){if(e==="true")return!0;if(e==="false")return!1;if(/^\d+$/.test(e))return parseInt(e,10);if(/^\d+\.\d+$/.test(e))return parseFloat(e);if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch(t){return e}return e}static kebabToCamel(e){return e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}static validate(e){const t=[];return e.height!==void 0&&typeof e.height=="number"&&e.height<0&&t.push("height must be a positive number"),e.width!==void 0&&typeof e.width=="number"&&e.width<0&&t.push("width must be a positive number"),e.plugins!==void 0&&!Array.isArray(e.plugins)&&typeof e.plugins!="string"&&t.push("plugins must be an array or string"),e.theme!==void 0&&typeof e.theme!="string"&&t.push("theme must be a string"),{valid:t.length===0,errors:t}}static getDefaults(){return{...this.EDITOR_DEFAULTS}}static merge(...e){const t={};for(const n of e)for(const[i,o]of Object.entries(n))o!=null&&(typeof o=="object"&&!Array.isArray(o)&&t[i]?t[i]=this.merge(t[i],o):t[i]=o);return t}};De.EDITOR_DEFAULTS={height:400,width:"100%",readonly:!1,disabled:!1,menubar:!0,toolbar:!0,plugins:[],theme:"light",content:"",placeholder:"Start typing...",autofocus:!1,autosave:!1,accessibility:{enableARIA:!0,keyboardNavigation:!0,checker:!1},performance:{debounceInputMs:100,viewportOnlyScan:!0},spellcheck:{enabled:!1,provider:"browser",apiUrl:""},language:{locale:"en",direction:"ltr"},contextMenu:{enabled:!0},contentConfig:{allowedTags:[],allowedAttributes:{},sanitize:!0},paste:{clean:!0,keepFormatting:!1,convertWord:!0},security:{sanitizeOnPaste:!0,sanitizeOnInput:!0},statusbar:!1};let le=De;const _t='.editora-editor{display:flex;flex-direction:column;border:1px solid #ddd;border-radius:4px;background:#fff;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,sans-serif;font-size:14px;overflow:hidden}.editora-editor *{box-sizing:border-box}.editora-theme-light{background:#fff;color:#333}.editora-theme-dark{--editora-dark-toolbar-bg-start: #353d48;--editora-dark-toolbar-bg-end: #2d3540;--editora-dark-button-bg-start: #46505f;--editora-dark-button-bg-end: #3b4553;--editora-dark-button-hover-start: #525d6d;--editora-dark-button-hover-end: #465262;--editora-dark-button-active-start: #5eaaf6;--editora-dark-button-active-end: #4a95de;--editora-dark-border: #475263;--editora-dark-border-strong: #566275;--editora-dark-text: #e1e9f5;--editora-dark-text-strong: #f3f7ff;--editora-dark-text-muted: #aeb9cc;--editora-dark-surface: #1d242d;--editora-dark-content: #1f2732;background:linear-gradient(180deg,#1b2330,#1c2430);color:var(--editora-dark-text);border-color:var(--editora-dark-border)}.editora-toolbar{display:flex;align-items:center;gap:4px;padding:8px;background:#f5f5f5;border-bottom:1px solid #ddd;flex-wrap:wrap}.editora-theme-dark .editora-toolbar{background:linear-gradient(180deg,var(--editora-dark-toolbar-bg-start) 0%,var(--editora-dark-toolbar-bg-end) 100%);border-bottom-color:var(--editora-dark-border);box-shadow:inset 0 1px #ffffff0d}.editora-toolbar-sticky{position:sticky;top:0;z-index:100;position:-webkit-sticky}.editora-toolbar-group{display:flex;align-items:center;gap:2px}.editora-toolbar-button{padding:6px 12px;border:1px solid #ccc;background:#fff;cursor:pointer;border-radius:3px;font-weight:600;font-size:14px;height:30px;display:flex;align-items:center;white-space:nowrap}.editora-toolbar-group-button{display:flex;align-items:center}.editora-toolbar-input.font-size{width:40px;padding:.25rem;text-align:center;font-size:14px;background:#fff;border:1px solid var(--rte-color-border-light);border-radius:var(--rte-radius-sm)}.editora-toolbar-group-items{display:flex;align-items:center;border:1px solid #ccc;.editora-toolbar-button{border:none;border-radius:0;&:first-child{border-right:1px solid #ccc;border-top-left-radius:3px;border-bottom-left-radius:3px}&:last-child{border:0px solid #ccc;border-radius:0!important}&:hover{background:#e0e0e0;border-color:#ccc}}}.editora-theme-dark .editora-toolbar-button{background:linear-gradient(180deg,var(--editora-dark-button-bg-start) 0%,var(--editora-dark-button-bg-end) 100%);border-color:var(--editora-dark-border-strong);color:var(--editora-dark-text);box-shadow:inset 0 1px #ffffff14,0 1px 1px #00000059}.editora-theme-dark .editora-toolbar-group-items{border-color:var(--editora-dark-border-strong);background:linear-gradient(180deg,var(--editora-dark-button-bg-start) 0%,var(--editora-dark-button-bg-end) 100%)}.editora-theme-dark .editora-toolbar-group-items .editora-toolbar-button:first-child{border-right-color:#566275}.editora-theme-dark .editora-toolbar-group-items .editora-toolbar-button:last-child{border-left-color:#566275}.editora-theme-dark .editora-toolbar-input.font-size{background-color:#2e3642;color:var(--editora-dark-text-strong);border-color:var(--editora-dark-border-strong);caret-color:var(--editora-dark-text-strong)}.editora-theme-dark .editora-toolbar-input.font-size::placeholder{color:var(--editora-dark-text-strong);opacity:1}.editora-toolbar-button:hover{background:#e0e0e0;border-color:#ccc}.editora-theme-dark .editora-toolbar-button:hover{background:linear-gradient(180deg,var(--editora-dark-button-hover-start) 0%,var(--editora-dark-button-hover-end) 100%);border-color:#66748a;color:var(--editora-dark-text-strong)}.editora-toolbar-button:active,.editora-toolbar-button.active{background:#d0d0d0;border-color:#999}.editora-theme-dark .editora-toolbar-button:active,.editora-theme-dark .editora-toolbar-button.active{background:linear-gradient(180deg,var(--editora-dark-button-active-start) 0%,var(--editora-dark-button-active-end) 100%);border-color:#67adf4;color:#0f1b2a}.editora-theme-dark .editora-toolbar-button:disabled{background:#313946;border-color:#424d5e;color:#7f8ca1}.editora-theme-dark .editora-toolbar-button[data-command=insertTable],.editora-theme-dark .editora-toolbar-button[data-command=print],.editora-theme-dark .editora-toolbar-button[data-command=toggleSpellCheck],.editora-theme-dark .editora-toolbar-button[data-command=toggleA11yChecker],.editora-theme-dark .editora-toolbar-button[data-command=setDirectionLTR],.editora-theme-dark .editora-toolbar-button[data-command=setDirectionRTL]{color:#f1f6ff}.editora-toolbar-button:disabled{opacity:.5;cursor:not-allowed}.editora-toolbar-icon{display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;line-height:1}.editora-toolbar-button svg,.editora-toolbar-icon svg{width:20px;height:20px;display:block;color:currentColor;fill:currentColor}.editora-theme-dark .editora-toolbar-icon,.editora-theme-dark .editora-toolbar-icon *{color:inherit}.editora-theme-dark :is(.editora-toolbar-button,.editora-toolbar-icon) svg :is([stroke="#000" i],[stroke="#000000" i],[stroke=black i],[stroke="#0f0f0f" i],[stroke="#111111" i],[style*="stroke:#000" i],[style*="stroke: #000" i],[style*="stroke:black" i],[style*="stroke: black" i],[style*="stroke:#0f0f0f" i],[style*="stroke: #0f0f0f" i]){stroke:currentColor!important}.editora-theme-dark :is(.editora-toolbar-button,.editora-toolbar-icon) svg :is([fill="#000" i],[fill="#000000" i],[fill=black i],[fill="#0f0f0f" i],[fill="#111111" i],[style*="fill:#000" i],[style*="fill: #000" i],[style*="fill:black" i],[style*="fill: black" i],[style*="fill:#0f0f0f" i],[style*="fill: #0f0f0f" i]){fill:currentColor!important}.editora-toolbar-separator{width:1px;height:24px;background:#ddd;margin:0 4px}.editora-theme-dark .editora-toolbar-separator{background:#4d596b}.editora-toolbar-dropdown{position:relative}.editora-toolbar-dropdown-menu{position:absolute;top:100%;left:0;min-width:150px;margin-top:4px;padding:4px 0;background:#fff;border:1px solid #ddd;border-radius:4px;box-shadow:0 2px 8px #00000026;z-index:1000}.editora-theme-dark .editora-toolbar-dropdown-menu{background:#29323d;border-color:#4d596b;box-shadow:0 8px 20px #00000073}.editora-toolbar-dropdown-item{display:block;width:100%;padding:8px 12px;border:none;background:transparent;color:#333;text-align:left;cursor:pointer;font-size:13px;transition:background .15s ease}.editora-theme-dark .editora-toolbar-dropdown-item{color:#d7deea}.editora-toolbar-dropdown-item:hover{background:#f5f5f5}.editora-theme-dark .editora-toolbar-dropdown-item:hover{background:#3a4554;color:#f0f6ff}.editora-content{flex:1;min-height:200px;padding:16px;outline:none;overflow-y:auto;line-height:1.6}.editora-theme-dark .editora-content{color:#ecf3ff;background:linear-gradient(180deg,var(--editora-dark-content) 0%,#1c232e 100%)}.editora-content:empty:before{content:attr(data-placeholder);color:#999;pointer-events:none}.editora-theme-dark .editora-content:empty:before{color:#8f9bb0}.editora-content h1{font-size:2em;margin:.67em 0;font-weight:600}.editora-content h2{font-size:1.5em;margin:.75em 0;font-weight:600}.editora-content h3{font-size:1.17em;margin:.83em 0;font-weight:600}.editora-content p{margin:1em 0}.editora-theme-dark .editora-content,.editora-theme-dark .editora-content :is(p,span,div,li,ul,ol,td,th,h1,h2,h3,h4,h5,h6,strong,em,u,s,small,sub,sup,blockquote,code,pre,a){color:#ecf3ff}.editora-content ul,.editora-content ol{margin:1em 0;padding-left:2em}.editora-content a{color:#06c;text-decoration:underline}.editora-theme-dark .editora-content a{color:#ecf3ff}.editora-content code{padding:2px 4px;background:#f5f5f5;border-radius:3px;font-family:Monaco,Menlo,Consolas,monospace;font-size:.9em}.editora-theme-dark .editora-content code{background:#1e1e1e}.editora-content pre{padding:12px;background:#f5f5f5;border-radius:4px;overflow-x:auto;margin:1em 0}.editora-theme-dark .editora-content pre{background:#1e1e1e}.editora-theme-dark .rte-code-block{background:linear-gradient(180deg,#212a36,#1b2430)!important;border-color:#4f5b70!important;color:#e7effc!important}.editora-theme-dark .rte-code-block code{color:#e7effc!important}.editora-theme-dark .rte-code-block:before{background:#111927!important;color:#dce8ff!important}.editora-theme-dark .rte-code-block .rte-code-copy{background:#2b3441!important;border-color:#5a667b!important;color:#dce8ff!important}.editora-content blockquote{margin:1em 0;padding-left:1em;border-left:4px solid #ddd;color:#666}.editora-theme-dark .editora-content blockquote{border-left-color:#3c3c3c;color:#ecf3ff}.editora-floating-toolbar{position:absolute;padding:4px;background:#fff;border:1px solid #ddd;border-radius:4px;box-shadow:0 2px 8px #00000026;z-index:1000}.editora-theme-dark .editora-floating-toolbar{background:#29323d;border-color:#4d596b;box-shadow:0 8px 20px #00000073}.editora-statusbar-container{display:flex;flex-direction:column}.editora-statusbar-left{display:flex;align-items:center;gap:8px}.editora-statusbar-right{display:flex;align-items:center;gap:8px;margin-left:auto}.editora-statusbar{display:flex;align-items:center;gap:12px;padding:6px 12px;background:#f5f5f5;border-top:1px solid #ddd;font-size:12px;color:#666}.editora-theme-dark .editora-statusbar{background:linear-gradient(180deg,#2c3440,#252d37);border-top-color:#3f4a5b;color:#d7deea}.editora-statusbar-item{white-space:nowrap}.editora-statusbar-separator{color:#ddd}.editora-theme-dark .editora-statusbar-separator{color:#566275}.editora-editor[readonly] .editora-content{background:#fafafa;cursor:not-allowed}.editora-theme-dark.editora-editor[readonly] .editora-content{background:#1a1a1a}.editora-editor:focus-within{border-color:#06c;box-shadow:0 0 0 3px #0066cc1a}.editora-theme-dark.editora-editor:focus-within{border-color:#4db8ff;box-shadow:0 0 0 3px #4db8ff1a}.editora-editor[disabled]{opacity:.6;pointer-events:none}@media(max-width:768px){.editora-toolbar{padding:4px}.editora-toolbar-button{min-width:28px;min-height:28px;padding:4px 8px;font-size:12px}.editora-content{padding:12px}}.editora-content ::selection{background:#06c3}.editora-theme-dark .editora-content ::selection{background:#4db8ff33}.editora-content table{border-collapse:collapse;width:100%;margin:1em 0}.editora-content th,.editora-content td{border:1px solid #ddd;padding:8px 12px;text-align:left}.editora-theme-dark .editora-content th,.editora-theme-dark .editora-content td{border-color:#3c3c3c}.editora-content th{background:#f5f5f5;font-weight:600}.editora-theme-dark .editora-content th{background:#252526}.editora-content img{max-width:100%;height:auto;border-radius:4px;display:block}.editora-content video{max-width:100%;height:auto;border-radius:4px;display:block}.editora-editor.loading{opacity:.7;pointer-events:none}.editora-editor.loading:after{content:"";position:absolute;top:50%;left:50%;width:24px;height:24px;margin:-12px 0 0 -12px;border:3px solid #ddd;border-top-color:#06c;border-radius:50%;animation:editora-spin .8s linear infinite}@keyframes editora-spin{to{transform:rotate(360deg)}}.toolbar-container-wrapper{display:flex;align-items:center;background:#fff;border-bottom:1px solid #e0e0e0;padding:0;margin:0;width:100%;box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif;font-size:14px;line-height:1.5;position:relative}.toolbar-container-wrapper[data-toolbar-sticky=true]{position:sticky;top:0;z-index:999;box-shadow:0 2px 4px #0000001a}.toolbar-container-wrapper[data-toolbar-floating=true]{position:fixed;top:0;left:0;right:0;z-index:1000;box-shadow:0 4px 12px #00000026}.toolbar-container-wrapper[data-toolbar-position=bottom]{border-bottom:none;border-top:1px solid #e0e0e0}.toolbar-container-wrapper .toolbar-wrapper{display:flex;width:100%;padding:8px;gap:4px;flex-wrap:wrap;align-items:center}.toolbar-container-wrapper .toolbar{display:flex;width:100%;gap:4px;flex-wrap:wrap;align-items:center}.toolbar-container-wrapper .toolbar-container{display:flex;gap:4px;flex-wrap:wrap;align-items:center;flex:1;position:relative}.toolbar-container-wrapper .toolbar-item{display:flex;align-items:center;gap:2px}.toolbar-container-wrapper .toolbar-button{padding:6px 10px;border:1px solid #d1d5db;background:#fff;border-radius:4px;cursor:pointer;font-size:13px;display:flex;align-items:center;justify-content:center;gap:4px;transition:all .15s ease;min-height:32px;white-space:nowrap}.toolbar-container-wrapper .toolbar-button:hover{background-color:#f3f4f6;border-color:#9ca3af}.toolbar-container-wrapper .toolbar-button:active,.toolbar-container-wrapper .toolbar-button[data-active=true]{background-color:#06c;color:#fff;border-color:#0052a3;box-shadow:inset 0 1px 3px #0000001a}.toolbar-container-wrapper .toolbar-button:disabled{opacity:.5;cursor:not-allowed;background-color:#f9fafb}.toolbar-container-wrapper .toolbar-more-button{padding:6px 8px;font-size:16px;font-weight:500;line-height:1}.toolbar-container-wrapper .toolbar-separator{width:1px;height:24px;background-color:#d1d5db;margin:0 4px}.toolbar-container-wrapper .toolbar-icon{display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;flex-shrink:0}.toolbar-container-wrapper .toolbar-icon svg{width:100%;height:100%}.toolbar-container-wrapper .toolbar-dropdown{position:relative;display:flex;align-items:center}.toolbar-container-wrapper .toolbar-dropdown-arrow{font-size:10px;margin-left:2px;line-height:1}.toolbar-container-wrapper .toolbar-dropdown-menu{position:absolute;top:100%;left:0;background:#fff;border:1px solid #d1d5db;border-radius:6px;box-shadow:0 4px 12px #00000026;z-index:1000;min-width:160px;padding:4px 0;margin-top:4px;display:none}.toolbar-container-wrapper .toolbar-dropdown-menu.show{display:block}.toolbar-container-wrapper .toolbar-dropdown-item{display:block;width:100%;padding:8px 12px;border:none;background:transparent;text-align:left;cursor:pointer;font-size:13px;color:#1f2937;transition:background-color .15s ease;font-family:inherit}.toolbar-container-wrapper .toolbar-dropdown-item:hover{background-color:#f3f4f6}.toolbar-container-wrapper .toolbar-dropdown-item:active{background-color:#e5e7eb}.toolbar-container-wrapper .toolbar-input{padding:6px 8px;border:1px solid #d1d5db;border-radius:4px;font-size:13px;font-family:inherit;background-color:#fff;color:#1f2937;transition:all .15s ease}.toolbar-container-wrapper .toolbar-input:focus{outline:none;border-color:#06c;box-shadow:0 0 0 3px #0066cc1a;background-color:#fff}.toolbar-container-wrapper .toolbar-input::placeholder{color:#9ca3af}.toolbar-overflow-menu{animation:slideDown .2s ease-out}@keyframes slideDown{0%{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}.toolbar-overflow-item{transition:background-color .15s ease}.floating-toolbar{user-select:none;-webkit-user-select:none;font-family:system-ui,-apple-system,sans-serif;font-size:14px;animation:fadeInUp .15s ease-out}@keyframes fadeInUp{0%{opacity:0;transform:translate(-50%) translateY(10px)}to{opacity:1;transform:translate(-50%) translateY(0)}}.floating-toolbar-btn{display:flex;align-items:center;justify-content:center;width:32px;height:32px;border:none;background:transparent;border-radius:4px;color:#495057;cursor:pointer;font-size:14px;font-weight:500;transition:all .15s ease;outline:none}.floating-toolbar-btn:hover{background:#f8f9fa;color:#212529}.floating-toolbar-btn:active{background:#e9ecef;transform:scale(.95)}.floating-toolbar-btn.floating-toolbar-toggle{color:#dc3545;font-weight:700}.floating-toolbar-btn.floating-toolbar-toggle:hover{background:#f8d7da;color:#721c24}.floating-toolbar-separator{width:1px;height:20px;background:#e1e5e9;margin:0 2px}@media(max-width:768px){.toolbar-container-wrapper .toolbar-button{padding:5px 8px;font-size:12px;min-height:28px}.toolbar-container-wrapper .toolbar-icon{width:16px;height:16px}.toolbar-container-wrapper .toolbar-dropdown-menu{min-width:140px}.toolbar-container-wrapper .toolbar-dropdown-item{padding:6px 10px;font-size:12px}.floating-toolbar{padding:4px;gap:2px}.floating-toolbar-btn{width:28px;height:28px;font-size:12px}}@media(max-width:480px){.toolbar-container-wrapper{padding:4px}.toolbar-container-wrapper .toolbar-wrapper{padding:4px;gap:2px}.toolbar-container-wrapper .toolbar-button{padding:4px 6px;font-size:11px;min-height:24px}.toolbar-container-wrapper .toolbar-icon{width:14px;height:14px}}.floating-toolbar{pointer-events:auto}.floating-toolbar{max-width:calc(100vw - 20px);overflow-x:auto}@media(prefers-color-scheme:dark){.floating-toolbar{background:#2d3748;border-color:#4a5568;color:#e2e8f0}.floating-toolbar-btn:hover{background:#4a5568;color:#f7fafc}.floating-toolbar-btn:active{background:#718096}.floating-toolbar-separator{background:#4a5568}}';let Y;const zt="__editoraCommandEditorRoot",jt="__editoraLastCommandButton",Be="editora-editor, [data-editora-editor], .rte-editor, .editora-editor",_e=".rte-content, .editora-content",ce=new Set;let I=null,ze=!1,he=null,de=null;function je(s){if(!(s instanceof HTMLElement))return!1;const e=s;return typeof e.execCommand=="function"&&(e.tagName.toLowerCase()==="editora-editor"||e.classList.contains("editora-editor")||e.hasAttribute("data-editora-editor"))}function Ut(s){return s?s.nodeType===Node.ELEMENT_NODE?s:s.parentElement:null}function z(s){if(!s)return null;if(je(s))return s;const e=s.matches(Be)?s:s.closest(Be);return!e||!je(e)?null:e}function Wt(){var i;if(typeof window=="undefined")return null;const s=window[zt];if(s instanceof HTMLElement){const o=z(s);if(o)return o;const r=s.matches(_e)?s:s.querySelector(_e);if(r){const a=z(r);if(a)return a}}const e=window[jt];if(e instanceof HTMLElement){const o=z(e);if(o)return o}const t=document.activeElement;if(t){const o=z(t);if(o)return o}const n=(i=window.getSelection)==null?void 0:i.call(window);if(n&&n.rangeCount>0){const o=z(Ut(n.getRangeAt(0).startContainer));if(o)return o}if(I&&I.isConnected)return I;for(const o of ce)if(o.isConnected)return o;return null}function Vt(){if(typeof window=="undefined"||ze)return;he=typeof window.executeEditorCommand=="function"?window.executeEditorCommand.bind(window):null,de=typeof window.execEditorCommand=="function"?window.execEditorCommand.bind(window):null;const s=(e,...t)=>{const n=Wt();return n?n.execCommand(e,...t):he?he(e,...t):de?de(e,...t):!1};window.executeEditorCommand=s,window.execEditorCommand=s,ze=!0}function Kt(){const s="editora-webcomponent-styles";if(!document.getElementById(s)){const e=document.createElement("style");e.id=s,e.textContent=_t,document.head.appendChild(e)}}function qt(){if(!Y){const s=L.__globalPluginLoader;s?Y=s:Y=new F}return Y}class L extends HTMLElement{constructor(){if(super(),this.pluginLoader=qt(),this.config={},this.isInitialized=!1,this.keyboardShortcutManager=new Nt,this.lastAutosavedContent="",this.loadedPlugins=[],this.lastBeforeInputType=null,Kt(),!this.hasAttribute("data-initial-content")){const e=this.innerHTML.trim();e&&this.setAttribute("data-initial-content",e)}}static get observedAttributes(){return["height","width","menubar","plugins","toolbar","toolbar-items","toolbar-floating","toolbar-sticky","readonly","disabled","theme","placeholder","autofocus","autosave","autosave-enabled","autosave-interval-ms","autosave-storage-key","autosave-provider","autosave-api-url","accessibility","accessibility-enable-aria","accessibility-keyboard-navigation","accessibility-checker","performance","performance-debounce-input-ms","performance-viewport-only-scan","language","language-locale","language-direction","spellcheck","spellcheck-enabled","spellcheck-provider","context-menu","context-menu-enabled","paste","paste-clean","paste-keep-formatting","paste-convert-word","security","security-sanitize-on-paste","security-sanitize-on-input","statusbar"]}connectedCallback(){this.config=this.resolveConfig(),this.waitForPluginLoader().then(()=>{setTimeout(async()=>{await this.initialize()},0)})}async waitForPluginLoader(){if(L.__globalPluginLoader){this.pluginLoader=L.__globalPluginLoader;return}return new Promise(e=>{const t=()=>{L.__globalPluginLoader?(this.pluginLoader=L.__globalPluginLoader,e()):setTimeout(t,0)};t()})}disconnectedCallback(){this.destroy()}attributeChangedCallback(e,t,n){t!==n&&(this.config=this.resolveConfig(),this.handleAttributeChange(e,n))}async setConfig(e){this.jsConfig=e,this.config=this.resolveConfig(),this.isConnected&&(this.destroy(),await this.waitForPluginLoader(),await this.initialize())}async initialize(){var n;if(this.querySelector(".editora-toolbar")||this.isInitialized)return;this.setAttribute("data-editora-editor","true"),ce.add(this),I||(I=this),Vt(),this.config.height&&(this.style.height=typeof this.config.height=="number"?`${this.config.height}px`:this.config.height),this.config.width&&(this.style.width=typeof this.config.width=="number"?`${this.config.width}px`:this.config.width),this.classList.add("editora-editor"),this.config.theme&&this.classList.add(`editora-theme-${this.config.theme}`);const e=await this.loadPlugins();this.loadedPlugins=e,e.forEach(i=>{if(i.init&&typeof i.init=="function")try{i.init({editorElement:this})}catch(o){console.error(`[RichTextEditor] Error initializing plugin ${i.name}:`,o)}});const t=(n=this.restoreAutosavedContent())!=null?n:this.getAttribute("data-initial-content")||"";this.engine=new St({content:t,plugins:e,readonly:this.config.readonly}),this.createUI(e,t),this.setupEventListeners(),this.startAutosave(),this.isInitialized=!0,this.dispatchEvent(new CustomEvent("editor-ready",{detail:{api:this.getAPI()},bubbles:!0}))}getInitialContent(){if(this.config.content)return this.config.content;const e=this.querySelector("[slot]");return e?e.innerHTML:this.hasChildNodes()?Array.from(this.childNodes).map(n=>n.nodeType===Node.TEXT_NODE?n.textContent:n.nodeType===Node.ELEMENT_NODE?n.outerHTML:"").join("").trim():""}async loadPlugins(){this.pluginLoader||await this.waitForPluginLoader();const e=[],t=this.config.plugins&&(typeof this.config.plugins=="string"&&this.config.plugins.length>0||Array.isArray(this.config.plugins)&&this.config.plugins.length>0),i=this.getAccessibilityConfig().checker===!0;if(t){if(typeof this.config.plugins=="string"){const o=this.config.plugins.split(/\s+/).filter(Boolean);i&&!o.includes("a11yChecker")&&o.push("a11yChecker");for(const r of o){const a=await this.pluginLoader.load(r,this.getPluginLoadConfig(r));a&&e.push(a)}}else if(Array.isArray(this.config.plugins)){for(const o of this.config.plugins)if(typeof o=="string"){const r=await this.pluginLoader.load(o,this.getPluginLoadConfig(o));r&&e.push(r)}else e.push(o);if(i&&!e.some(o=>(o==null?void 0:o.name)==="a11yChecker")){const o=await this.pluginLoader.load("a11yChecker",this.getPluginLoadConfig("a11yChecker"));o&&e.push(o)}}}else{const o=this.pluginLoader.getRegisteredPluginNames();for(const r of o){const a=await this.pluginLoader.load(r,this.getPluginLoadConfig(r));a&&e.push(a)}}return e}resolveToolbarItems(){const e=this.config.toolbarItems;if(typeof e=="string")return e;if(Array.isArray(e))return e.join(" ");const t=this.config.toolbar;if(typeof t=="string")return t;if(!t||typeof t!="object")return;const n=t.items;if(typeof n=="string")return n;if(Array.isArray(n))return n.join(" ")}isToolbarStickyEnabled(){const e=this.config.toolbar;return!e||typeof e!="object"?!1:!!e.sticky}isToolbarFloatingEnabled(){const e=this.config.toolbar;return!e||typeof e!="object"?!1:!!e.floating}isStatusbarEnabled(){const e=this.config.statusbar;return typeof e=="boolean"?e:e&&typeof e=="object"?e.enabled!==!1:!1}getStatusbarPosition(){const e=this.config.statusbar;return e&&typeof e=="object"&&e.position==="top"?"top":"bottom"}getLanguageConfig(){const e=this.config.language;return typeof e=="string"?{locale:e,direction:"ltr"}:e&&typeof e=="object"?{locale:e.locale||"en",direction:e.direction==="rtl"?"rtl":"ltr"}:{locale:"en",direction:"ltr"}}getAccessibilityConfig(){const e=this.config.accessibility;return typeof e=="boolean"?{enableARIA:e,keyboardNavigation:e,checker:!1}:e&&typeof e=="object"?{enableARIA:e.enableARIA!==!1,keyboardNavigation:e.keyboardNavigation!==!1,checker:!!e.checker}:{enableARIA:!0,keyboardNavigation:!0,checker:!1}}getPerformanceConfig(){var t;const e=this.config.performance;if(typeof e=="boolean")return{debounceInputMs:100,viewportOnlyScan:e};if(e&&typeof e=="object"){const n=Number((t=e.debounceInputMs)!=null?t:100);return{debounceInputMs:Number.isFinite(n)&&n>=0?n:100,viewportOnlyScan:e.viewportOnlyScan!==!1}}return{debounceInputMs:100,viewportOnlyScan:!0}}isEditorInViewport(){if(!this.contentElement||typeof window=="undefined")return!0;const e=this.contentElement.getBoundingClientRect();return e.bottom>=0&&e.top<=window.innerHeight}applyAccessibilitySettings(){if(!this.contentElement)return;const e=this.getAccessibilityConfig();if(e.enableARIA){this.contentElement.setAttribute("role","textbox"),this.contentElement.setAttribute("aria-multiline","true"),this.contentElement.setAttribute("aria-disabled",this.config.readonly?"true":"false");const t=typeof this.config.placeholder=="string"?this.config.placeholder.trim():"";t?this.contentElement.setAttribute("aria-label",t):this.contentElement.removeAttribute("aria-label")}else this.contentElement.removeAttribute("role"),this.contentElement.removeAttribute("aria-multiline"),this.contentElement.removeAttribute("aria-disabled"),this.contentElement.removeAttribute("aria-label");this.contentElement.tabIndex=e.keyboardNavigation?0:-1}applyLanguageSettings(){if(!this.contentElement)return;const e=this.getLanguageConfig();this.contentElement.setAttribute("lang",e.locale),this.contentElement.setAttribute("dir",e.direction)}getSpellcheckConfig(){const e=this.config.spellcheck;if(typeof e=="boolean")return{enabled:e,provider:"browser"};if(e&&typeof e=="object"){const t=e.provider||"browser";return{enabled:!!e.enabled,provider:t,mode:e.mode}}return{enabled:!1,provider:"browser"}}applySpellcheckSettings(){if(!this.contentElement)return;const e=this.getSpellcheckConfig(),t=e.enabled&&e.provider==="browser";this.contentElement.spellcheck=t,this.contentElement.setAttribute("spellcheck",t?"true":"false")}executeCommand(e,...t){var o;typeof window!="undefined"&&(window.__editoraCommandEditorRoot=this);const n={editorElement:this,contentElement:this.contentElement,toolbarElement:this.toolbarElement},i=this.loadedPlugins.find(r=>r.commands&&r.commands[e]);if(i&&i.commands){const r=i.commands[e];if(typeof r=="function")try{return e==="toggleFullscreen"?r(this,n):r(...t,n),!0}catch(a){return console.error(`[RichTextEditor] Error executing native command ${e}:`,a),!1}}return((o=this.engine)==null?void 0:o.execCommand(e,...t))||!1}getPluginLoadConfig(e){const t=this.config.pluginConfig;if(t&&typeof t=="object"){const o=t[e];if(o&&typeof o=="object")return o}const n={spellCheck:["spellcheck","spellCheck"],trackChanges:["trackchanges","track-changes","trackChanges"],versionDiff:["versiondiff","version-diff","versionDiff"],"version-diff":["versiondiff","version-diff","versionDiff"],conditionalContent:["conditionalcontent","conditional-content","conditionalContent"],"conditional-content":["conditionalcontent","conditional-content","conditionalContent"],dataBinding:["databinding","data-binding","dataBinding"],"data-binding":["databinding","data-binding","dataBinding"],contentRules:["contentrules","content-rules","contentRules"],"content-rules":["contentrules","content-rules","contentRules"],mentions:["mention","mentions"],mention:["mention","mentions"],slashCommands:["slashcommands","slash-commands","slashCommands"],"slash-commands":["slashcommands","slash-commands","slashCommands"],formatPainter:["formatpainter","format-painter","formatPainter"],"format-painter":["formatpainter","format-painter","formatPainter"]},i=[e,e.toLowerCase(),...n[e]||[]];for(const o of i){const r=this.config[o];if(r&&typeof r=="object"&&!Array.isArray(r))return r}}getContentSanitizeConfig(){const e=this.config.contentConfig;return e&&typeof e=="object"?e:{sanitize:!0}}getSecurityConfig(){const e=this.config.security;return e&&typeof e=="object"?e:{sanitizeOnPaste:!0,sanitizeOnInput:!0}}getAutosaveConfig(){var t,n;const e=this.config.autosave;if(typeof e=="boolean")return{enabled:e,intervalMs:3e4,storageKey:"rte-autosave",provider:"localStorage"};if(e&&typeof e=="object"){const i=Number((n=(t=e.intervalMs)!=null?t:e.interval)!=null?n:3e4);return{enabled:!!e.enabled,intervalMs:Number.isFinite(i)&&i>0?i:3e4,storageKey:String(e.storageKey||"rte-autosave"),provider:e.provider||"localStorage",apiUrl:e.apiUrl}}return{enabled:!1,intervalMs:3e4,storageKey:"rte-autosave",provider:"localStorage"}}persistAutosave(e){const t=this.getAutosaveConfig();if(t.enabled&&e!==this.lastAutosavedContent){if(this.lastAutosavedContent=e,t.provider==="localStorage"){try{localStorage.setItem(t.storageKey,e),localStorage.setItem(`${t.storageKey}-timestamp`,Date.now().toString())}catch(n){console.error("[RichTextEditor] Failed to save autosave content to localStorage:",n)}return}t.provider==="api"&&t.apiUrl&&fetch(t.apiUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:e,timestamp:Date.now()})}).catch(n=>{console.error("[RichTextEditor] Failed to save autosave content to API:",n)})}}restoreAutosavedContent(){const e=this.getAutosaveConfig();if(!e.enabled||e.provider!=="localStorage")return null;try{const t=localStorage.getItem(e.storageKey);if(t)return this.lastAutosavedContent=t,t}catch(t){console.error("[RichTextEditor] Failed to restore autosaved content:",t)}return null}stopAutosave(){this.autosaveTimer&&(clearInterval(this.autosaveTimer),this.autosaveTimer=void 0)}startAutosave(){this.stopAutosave();const e=this.getAutosaveConfig();!e.enabled||!this.contentElement||(this.autosaveTimer=setInterval(()=>{var t;this.persistAutosave(((t=this.contentElement)==null?void 0:t.innerHTML)||"")},e.intervalMs))}insertHTMLAtSelection(e){if(!this.contentElement)return;const t=window.getSelection();if(t&&t.rangeCount>0){const n=t.getRangeAt(0);n.deleteContents();const i=document.createElement("div");i.innerHTML=e;const o=document.createDocumentFragment();for(;i.firstChild;)o.appendChild(i.firstChild);n.insertNode(o),n.collapse(!1),t.removeAllRanges(),t.addRange(n)}else this.contentElement.focus(),document.execCommand("insertHTML",!1,e)}createUI(e,t){const n=this.querySelector('[slot="toolbar"]'),i=this.querySelector('[slot="statusbar"]');this.innerHTML="",this.config.toolbar!==!1&&!n?(this.toolbarElement=document.createElement("div"),this.toolbarElement.className="editora-toolbar-container",this.appendChild(this.toolbarElement),this.toolbar=new kt({items:this.resolveToolbarItems(),sticky:this.isToolbarStickyEnabled(),position:"top"},e,this.pluginLoader),this.toolbar.setCommandHandler((o,r)=>{var a;if(this.contentElement){this.contentElement.focus();const l=window.getSelection();if(!l||l.rangeCount===0||!this.contentElement.contains(l.anchorNode)){const c=document.createRange(),h=this.contentElement.lastChild||this.contentElement;h.nodeType===Node.TEXT_NODE?c.setStart(h,((a=h.textContent)==null?void 0:a.length)||0):h.nodeType===Node.ELEMENT_NODE?(c.selectNodeContents(h),c.collapse(!1)):c.setStart(this.contentElement,0),c.collapse(!0),l==null||l.removeAllRanges(),l==null||l.addRange(c)}}return this.executeCommand(o,r)}),this.toolbar.render(this.toolbarElement)):n&&this.appendChild(n),this.contentElement=document.createElement("div"),this.contentElement.className="editora-content rte-content",this.contentElement.contentEditable=this.config.readonly?"false":"true",this.applyLanguageSettings(),this.applyAccessibilitySettings(),this.applySpellcheckSettings(),this.config.placeholder&&this.contentElement.setAttribute("data-placeholder",this.config.placeholder);try{document.execCommand("defaultParagraphSeparator",!1,"p")}catch(o){console.warn("defaultParagraphSeparator not supported:",o)}if(t){const o=document.createElement("div");o.innerHTML=t.trim(),!Array.from(o.childNodes).some(a=>{if(a.nodeType===Node.ELEMENT_NODE){const l=a.tagName;return["P","DIV","H1","H2","H3","H4","H5","H6","UL","OL","BLOCKQUOTE","PRE"].includes(l)}return!1})&&t.trim()?this.contentElement.innerHTML=`<p>${t.trim()}</p>`:this.contentElement.innerHTML=t}else this.config.placeholder?this.contentElement.innerHTML="":this.contentElement.innerHTML="<p><br></p>";this.appendChild(this.contentElement),this.isToolbarFloatingEnabled()&&(this.floatingToolbar=new Mt({enabled:!0}),this.floatingToolbar.create(this)),i?this.appendChild(i):this.isStatusbarEnabled()&&(this.statusBarElement=document.createElement("div"),this.statusBarElement.className="editora-statusbar-container",this.appendChild(this.statusBarElement),this.statusBar=new Lt({position:this.getStatusbarPosition()}),this.statusBar.create(this.statusBarElement)),this.config.autofocus&&setTimeout(()=>{var o;return(o=this.contentElement)==null?void 0:o.focus()},0)}setupEventListeners(){if(!this.contentElement||!this.engine)return;const e=this.keyboardShortcutManager;this.contentElement.addEventListener("beforeinput",n=>{this.lastBeforeInputType=n.inputType||null}),this.contentElement.addEventListener("input",()=>{if(!this.contentElement)return;let n=this.contentElement.innerHTML;const i=this.getPerformanceConfig(),o=this.getContentSanitizeConfig(),r=this.getSecurityConfig(),a=this.lastBeforeInputType;if(this.lastBeforeInputType=null,r.sanitizeOnInput!==!1&&o.sanitize!==!1&&!a){const h=Bt(n,o,r);if(h!==n){const d=window.getSelection(),f=d&&d.rangeCount>0?d.getRangeAt(0):null;if(this.contentElement.innerHTML=h,f&&d)try{d.removeAllRanges(),d.addRange(f)}catch(p){}n=h}}this.contentChangeDebounceTimer&&clearTimeout(this.contentChangeDebounceTimer);const c=()=>{this.dispatchEvent(new CustomEvent("content-change",{detail:{html:n},bubbles:!0}))};i.debounceInputMs>0?this.contentChangeDebounceTimer=setTimeout(c,i.debounceInputMs):c(),this.updateStatusBar()}),this.contentElement.addEventListener("contextmenu",n=>{const i=this.config.contextMenu;(i===!1||typeof i=="object"&&i!==null&&i.enabled===!1)&&n.preventDefault()}),this.contentElement.addEventListener("paste",n=>{var h,d;if(n.__editoraSmartPasteHandled===!0||n.defaultPrevented)return;n.preventDefault();const i=this.config.paste||{};let o=((h=n.clipboardData)==null?void 0:h.getData("text/html"))||"";const r=((d=n.clipboardData)==null?void 0:d.getData("text/plain"))||"",a=this.getContentSanitizeConfig(),l=this.getSecurityConfig(),c=!!o&&/class=["'][^"']*Mso|xmlns:w=|urn:schemas-microsoft-com:office/i.test(o);if((i.clean||!i.keepFormatting)&&r){document.execCommand("insertText",!1,r);return}if(i.convertWord===!1&&c&&r){document.execCommand("insertText",!1,r);return}if(o){l.sanitizeOnPaste!==!1&&a.sanitize!==!1&&(o=Ft(o,a,l)),this.insertHTMLAtSelection(o);return}r&&document.execCommand("insertText",!1,r)}),this.contentElement.addEventListener("focus",()=>{I=this,this.dispatchEvent(new Event("editor-focus",{bubbles:!0})),this.updateStatusBar()}),this.contentElement.addEventListener("blur",()=>{this.contentChangeDebounceTimer&&(clearTimeout(this.contentChangeDebounceTimer),this.contentChangeDebounceTimer=void 0),this.contentElement&&this.dispatchEvent(new CustomEvent("content-change",{detail:{html:this.contentElement.innerHTML},bubbles:!0})),this.dispatchEvent(new Event("editor-blur",{bubbles:!0})),this.updateFloatingToolbar(),this.updateStatusBar()}),this.contentElement.addEventListener("keydown",n=>{this.getAccessibilityConfig().keyboardNavigation&&e.handleKeyDown(n,(o,r)=>{this.executeCommand(o,r)})});const t=()=>{const n=this.getSelectionRangeInEditor(),i=document.activeElement,o=!!i&&!!this.contentElement&&(i===this.contentElement||this.contentElement.contains(i));this.getPerformanceConfig().viewportOnlyScan&&!this.isEditorInViewport()&&!o||!n&&!o||(this.updateFloatingToolbar(),this.updateStatusBar())};this.selectionChangeHandler=t,document.addEventListener("selectionchange",this.selectionChangeHandler)}getSelectionRangeInEditor(){if(!this.contentElement)return null;const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0),n=t.commonAncestorContainer;return this.contentElement.contains(n)?t:null}isSelectionBackward(e){if(!e.anchorNode||!e.focusNode)return!1;try{const t=document.createRange();return t.setStart(e.anchorNode,e.anchorOffset),t.setEnd(e.focusNode,e.focusOffset),t.collapsed}catch(t){return!1}}getSelectionAnchorRect(e,t){const n=Array.from(t.getClientRects()).filter(o=>o.width>0||o.height>0);return n.length===0?t.getBoundingClientRect():this.isSelectionBackward(e)?n[0]:n[n.length-1]}updateFloatingToolbar(){if(!this.floatingToolbar||!this.contentElement)return;if(this.config.readonly||this.contentElement.contentEditable==="false"||this.contentElement.getAttribute("data-readonly")==="true"||this.getAttribute("readonly")==="true"||this.getAttribute("data-readonly")==="true"){this.floatingToolbar.hide();return}const t=this.getPerformanceConfig(),n=document.activeElement===this.contentElement||!!this.contentElement&&this.contentElement.contains(document.activeElement);if(t.viewportOnlyScan&&!this.isEditorInViewport()&&!n){this.floatingToolbar.hide();return}const i=this.getSelectionRangeInEditor();if(!i){this.floatingToolbar.hide();return}if(i.collapsed){this.floatingToolbar.hide();return}const o=window.getSelection();if(!o){this.floatingToolbar.hide();return}const r=this.getSelectionAnchorRect(o,i);if(!r){this.floatingToolbar.hide();return}this.floatingToolbar.show(r.left,r.top-40)}updateStatusBar(){if(!this.statusBar||!this.contentElement)return;const e=this.getPerformanceConfig(),t=document.activeElement===this.contentElement||this.contentElement.contains(document.activeElement);if(e.viewportOnlyScan&&!this.isEditorInViewport()&&!t)return;const n=this.contentElement.textContent||"",{words:i,chars:o}=Ot(n),r=It(this.contentElement);let a,l;const c=this.getSelectionRangeInEditor();c&&(a=Rt(this.contentElement,c),c.collapsed||(l=Ht(c,a),a=void 0)),this.statusBar.update({wordCount:i,charCount:o,lineCount:r,cursorPosition:a,selectionInfo:l})}handleAttributeChange(e,t){switch(e){case"readonly":this.contentElement&&(this.contentElement.contentEditable=t==="true"?"false":"true",this.applyAccessibilitySettings()),this.engine&&this.engine.setReadonly(t==="true");break;case"theme":this.classList.forEach(n=>{n.startsWith("editora-theme-")&&this.classList.remove(n)}),t&&this.classList.add(`editora-theme-${t}`);break;case"placeholder":this.contentElement&&(this.contentElement.setAttribute("data-placeholder",t),this.applyAccessibilitySettings());break;case"accessibility":case"accessibility-enable-aria":case"accessibility-keyboard-navigation":case"accessibility-checker":this.applyAccessibilitySettings();break;case"performance":case"performance-debounce-input-ms":case"performance-viewport-only-scan":break;case"language":case"language-locale":case"language-direction":this.applyLanguageSettings();break;case"spellcheck":case"spellcheck-enabled":case"spellcheck-provider":this.applySpellcheckSettings();break;case"autosave":case"autosave-enabled":case"autosave-interval-ms":case"autosave-storage-key":case"autosave-provider":case"autosave-api-url":this.startAutosave();break;case"security":case"security-sanitize-on-paste":case"security-sanitize-on-input":case"paste":case"paste-clean":case"paste-keep-formatting":case"paste-convert-word":case"context-menu":case"context-menu-enabled":break;case"toolbar":case"toolbar-items":case"toolbar-floating":case"toolbar-sticky":case"plugins":case"statusbar":this.isConnected&&(this.destroy(),this.waitForPluginLoader().then(()=>{this.initialize().catch(n=>{console.error("[RichTextEditor] Error during attribute change re-initialization:",n)})}));break}}resolveConfig(){const e={};for(let t=0;t<this.attributes.length;t++){const n=this.attributes[t];e[n.name]=n.value}return le.resolve({jsConfig:this.jsConfig,attributes:e})}getAPI(){return{getContent:()=>{var e;return((e=this.contentElement)==null?void 0:e.innerHTML)||""},setContent:e=>{this.contentElement&&(this.contentElement.innerHTML=e)},execCommand:(e,t)=>this.executeCommand(e,t),focus:()=>{var e;(e=this.contentElement)==null||e.focus()},blur:()=>{var e;(e=this.contentElement)==null||e.blur()},destroy:()=>{this.destroy()},on:(e,t)=>(this.addEventListener(e,t),()=>this.removeEventListener(e,t)),getConfig:()=>({...this.config}),setReadonly:e=>{this.setAttribute("readonly",e.toString())}}}destroy(){var e,t,n,i;this.contentChangeDebounceTimer&&(clearTimeout(this.contentChangeDebounceTimer),this.contentChangeDebounceTimer=void 0),this.contentElement&&this.persistAutosave(this.contentElement.innerHTML||""),this.stopAutosave(),this.selectionChangeHandler&&(document.removeEventListener("selectionchange",this.selectionChangeHandler),this.selectionChangeHandler=void 0),(e=this.engine)==null||e.destroy(),(t=this.toolbar)==null||t.destroy(),(n=this.floatingToolbar)==null||n.destroy(),(i=this.statusBar)==null||i.destroy(),this.innerHTML="",this.contentElement=void 0,this.toolbarElement=void 0,this.statusBarElement=void 0,this.loadedPlugins=[],this.isInitialized=!1,ce.delete(this),I===this&&(I=null),this.dispatchEvent(new Event("editor-destroy",{bubbles:!0}))}getContent(){var e;return((e=this.contentElement)==null?void 0:e.innerHTML)||""}setContent(e){this.contentElement&&(this.contentElement.innerHTML=e)}execCommand(e,...t){return this.executeCommand(e,...t)}focus(){var e;(e=this.contentElement)==null||e.focus()}blur(){var e;(e=this.contentElement)==null||e.blur()}}const ue=new F;L.__globalPluginLoader=ue;const Zt={bold:()=>Promise.resolve().then(()=>en).then(s=>s.BoldPlugin()),italic:()=>Promise.resolve().then(()=>nn).then(s=>s.ItalicPlugin()),underline:()=>Promise.resolve().then(()=>on).then(s=>s.UnderlinePlugin()),strikethrough:()=>Promise.resolve().then(()=>an).then(s=>s.StrikethroughPlugin()),clearFormatting:()=>Promise.resolve().then(()=>xn).then(s=>s.ClearFormattingPlugin()),heading:()=>Promise.resolve().then(()=>Dn).then(s=>s.HeadingPlugin()),blockquote:()=>Promise.resolve().then(()=>qn).then(s=>s.BlockquotePlugin()),code:()=>Promise.resolve().then(()=>ai).then(s=>s.CodePlugin()),list:()=>Promise.resolve().then(()=>hi).then(s=>s.ListPlugin()),history:()=>Promise.resolve().then(()=>gi).then(s=>s.HistoryPlugin())};async function Ue(){return Object.entries(Zt).forEach(([s,e])=>{ue.register(s,e)}),ue}typeof window!="undefined"&&Ue().then(s=>{L.__globalPluginLoader=s,customElements.get("editora-editor")||customElements.define("editora-editor",L);const e=document.querySelectorAll("editora-editor:not([data-initial-content])"),t=[];e.forEach(n=>{const i=n.innerHTML.trim();i&&(t.push(i),n.setAttribute("data-initial-content",i),n.innerHTML="")}),e.forEach((n,i)=>{n instanceof L&&!n.isInitialized&&t[i]&&n.setAttribute("content",t[i])})});const J="data-editora-selection-marker";function Gt(s){return s?s.nodeType===Node.ELEMENT_NODE?s:s.parentElement:null}function We(s){return s?s.getAttribute("contenteditable")==="true"?s:s.querySelector('[contenteditable="true"]'):null}function Qt(s){var r;if((s==null?void 0:s.contentElement)instanceof HTMLElement)return s.contentElement;const e=We((r=s==null?void 0:s.editorElement)!=null?r:null);if(e)return e;const t=typeof window!="undefined"?window.__editoraCommandEditorRoot:null,n=t instanceof HTMLElement?We(t):null;if(n)return n;const i=window.getSelection();if(i&&i.rangeCount>0){const a=Gt(i.getRangeAt(0).startContainer),l=a==null?void 0:a.closest('.rte-content, .editora-content, [contenteditable="true"]');if(l instanceof HTMLElement)return l}const o=document.activeElement;if(o instanceof HTMLElement){const a=o.closest('.rte-content, .editora-content, [contenteditable="true"]');if(a instanceof HTMLElement)return a}return document.querySelector('.rte-content, .editora-content, [contenteditable="true"]')}function Xt(s){const e=window.getSelection();if(!e||e.rangeCount===0)return!1;const t=e.getRangeAt(0);return s.contains(t.startContainer)&&s.contains(t.endContainer)}function Ve(s){const e=document.createElement("span");return e.setAttribute(J,s),e.style.display="inline-block",e.style.width="0",e.style.height="0",e.style.overflow="hidden",e.style.lineHeight="0",e.appendChild(document.createTextNode("\uFEFF")),e}function Yt(s){const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0);if(!s.contains(t.startContainer)||!s.contains(t.endContainer))return null;const n=t.collapsed,i=Ve("start"),o=n?null:Ve("end"),r=t.cloneRange();if(o){const l=r.cloneRange();l.collapse(!1),l.insertNode(o)}const a=r.cloneRange();return a.collapse(!0),a.insertNode(i),()=>{const l=window.getSelection(),c=document.createRange(),h=s.querySelector(`[${J}="start"]`),d=s.querySelector(`[${J}="end"]`);if(!l||!h){s.querySelectorAll(`[${J}]`).forEach(f=>f.remove());return}n||!d?(c.setStartBefore(h),c.collapse(!0)):(c.setStartAfter(h),c.setEndBefore(d)),l.removeAllRanges(),l.addRange(c),h.remove(),d==null||d.remove()}}function Jt(s,e,t){if(e!==t){if(typeof window.execEditorCommand=="function"){window.execEditorCommand("recordDomTransaction",s,e,t);return}if(typeof window.executeEditorCommand=="function")try{window.executeEditorCommand("recordDomTransaction",{editor:s,beforeHTML:e,afterHTML:t})}catch(n){}}}function ee(s){const e=Qt(s.context);if(!e)return!1;const t=e.innerHTML;Xt(e)&&e.focus({preventScroll:!0});let n=!1;try{n=document.execCommand(s.command,!1)}catch(r){n=!1}const i=e.innerHTML;if(s.normalize&&i!==t){const r=Yt(e);s.normalize(e),r==null||r()}const o=e.innerHTML;return t!==o&&(Jt(e,t,o),e.dispatchEvent(new Event("input",{bubbles:!0}))),n!==!1||t!==o}const en=Object.freeze(Object.defineProperty({__proto__:null,BoldPlugin:()=>({name:"bold",marks:{bold:{parseDOM:[{tag:"strong"},{tag:"b"},{style:"font-weight",getAttrs:s=>{const e=typeof s=="string"?s:s.style.fontWeight;return/^(bold(er)?|[5-9]\d{2,})$/.test(e)&&null}}],toDOM:()=>["strong",0]}},toolbar:[{label:"Bold",command:"toggleBold",icon:'<svg width="24" height="24" focusable="false"><path d="M7.8 19c-.3 0-.5 0-.6-.2l-.2-.5V5.7c0-.2 0-.4.2-.5l.6-.2h5c1.5 0 2.7.3 3.5 1 .7.6 1.1 1.4 1.1 2.5a3 3 0 0 1-.6 1.9c-.4.6-1 1-1.6 1.2.4.1.9.3 1.3.6s.8.7 1 1.2c.4.4.5 1 .5 1.6 0 1.3-.4 2.3-1.3 3-.8.7-2.1 1-3.8 1H7.8Zm5-8.3c.6 0 1.2-.1 1.6-.5.4-.3.6-.7.6-1.3 0-1.1-.8-1.7-2.3-1.7H9.3v3.5h3.4Zm.5 6c.7 0 1.3-.1 1.7-.4.4-.4.6-.9.6-1.5s-.2-1-.7-1.4c-.4-.3-1-.4-2-.4H9.4v3.8h4Z" fill-rule="evenodd"></path></svg>',shortcut:"Mod-b"}],commands:{toggleBold:(s,e)=>ee({command:"bold",context:e})},keymap:{"Mod-b":"toggleBold","Mod-B":"toggleBold"}})},Symbol.toStringTag,{value:"Module"})),fe=(s,e)=>ee({command:"italic",context:e}),tn=(s,e)=>{var t;typeof window!="undefined"&&((t=window.registerEditorCommand)==null||t.call(window,s,e))},Ke=()=>{tn("toggleItalic",fe)};typeof window!="undefined"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Ke):Ke());const nn=Object.freeze(Object.defineProperty({__proto__:null,ItalicPlugin:()=>({name:"italic",marks:{italic:{parseDOM:[{tag:"i"},{tag:"em"},{style:"font-style=italic"}],toDOM:()=>["em",0]}},toolbar:[{label:"Italic",command:"toggleItalic",type:"button",icon:'<svg width="24" height="24" focusable="false"><path d="M16.7 4.7l-.1.9h-.3c-.6 0-1 0-1.4.3-.3.3-.4.6-.5 1.1l-2.1 9.8v.6c0 .5.4.8 1.4.8h.2l-.2.8H8l.2-.8h.2c1.1 0 1.8-.5 2-1.5l2-9.8.1-.5c0-.6-.4-.8-1.4-.8h-.3l.2-.9h5.8Z" fill-rule="evenodd"></path></svg>',shortcut:"Mod-i"}],commands:{toggleItalic:fe},keymap:{"Mod-i":"toggleItalic","Mod-I":"toggleItalic"}}),toggleItalic:fe},Symbol.toStringTag,{value:"Module"})),on=Object.freeze(Object.defineProperty({__proto__:null,UnderlinePlugin:()=>({name:"underline",marks:{underline:{parseDOM:[{tag:"u"}],toDOM:()=>["u",{},0]}},toolbar:[{label:"Underline",command:"toggleUnderline",icon:'<svg width="24" height="24" focusable="false"><path d="M16 5c.6 0 1 .4 1 1v7c0 2.8-2.2 5-5 5s-5-2.2-5-5V6c0-.6.4-1 1-1s1 .4 1 1v7c0 1.7 1.3 3 3 3s3-1.3 3-3V6c0-.6.4-1 1-1ZM4 17h16c.6 0 1 .4 1 1s-.4 1-1 1H4a1 1 0 1 1 0-2Z" fill-rule="evenodd"></path></svg>',shortcut:"Mod-u"}],commands:{toggleUnderline:(s,e)=>ee({command:"underline",context:e})},keymap:{"Mod-u":"toggleUnderline","Mod-U":"toggleUnderline"}})},Symbol.toStringTag,{value:"Module"})),rn=()=>({name:"strikethrough",marks:{strikethrough:{parseDOM:[{tag:"s"},{tag:"strike"},{tag:"del"},{style:"text-decoration",getAttrs:s=>(typeof s=="string"?s:s.style.textDecoration)==="line-through"&&null}],toDOM:()=>["s",0]}},toolbar:[{label:"Strikethrough",command:"toggleStrikethrough",icon:'<svg width="24" height="24" focusable="false"><g fill-rule="evenodd"><path d="M15.6 8.5c-.5-.7-1-1.1-1.3-1.3-.6-.4-1.3-.6-2-.6-2.7 0-2.8 1.7-2.8 2.1 0 1.6 1.8 2 3.2 2.3 4.4.9 4.6 2.8 4.6 3.9 0 1.4-.7 4.1-5 4.1A6.2 6.2 0 0 1 7 16.4l1.5-1.1c.4.6 1.6 2 3.7 2 1.6 0 2.5-.4 3-1.2.4-.8.3-2-.8-2.6-.7-.4-1.6-.7-2.9-1-1-.2-3.9-.8-3.9-3.6C7.6 6 10.3 5 12.4 5c2.9 0 4.2 1.6 4.7 2.4l-1.5 1.1Z"></path><path d="M5 11h14a1 1 0 0 1 0 2H5a1 1 0 0 1 0-2Z" fill-rule="nonzero"></path></g></svg>',shortcut:"Mod-Shift-x"}],commands:{toggleStrikethrough:(s,e)=>ee({command:"strikeThrough",context:e,normalize:sn})},keymap:{"Mod-Shift-x":"toggleStrikethrough","Mod-Shift-X":"toggleStrikethrough"}});function sn(s){s.querySelectorAll("strike, del").forEach(t=>{var i;const n=document.createElement("s");for(const o of Array.from(t.attributes))o.name!=="style"&&n.setAttribute(o.name,o.value);for(;t.firstChild;)n.appendChild(t.firstChild);(i=t.parentNode)==null||i.replaceChild(n,t)})}const an=Object.freeze(Object.defineProperty({__proto__:null,StrikethroughPlugin:rn},Symbol.toStringTag,{value:"Module"})),ln=()=>({name:"clearFormatting",toolbar:[{label:"Clear Formatting",command:"clearFormatting",icon:'<svg width="24" height="24" focusable="false"><path d="M13.2 6a1 1 0 0 1 0 .2l-2.6 10a1 1 0 0 1-1 .8h-.2a.8.8 0 0 1-.8-1l2.6-10H8a1 1 0 1 1 0-2h9a1 1 0 0 1 0 2h-3.8ZM5 18h7a1 1 0 0 1 0 2H5a1 1 0 0 1 0-2Zm13 1.5L16.5 18 15 19.5a.7.7 0 0 1-1-1l1.5-1.5-1.5-1.5a.7.7 0 0 1 1-1l1.5 1.5 1.5-1.5a.7.7 0 0 1 1 1L17.5 17l1.5 1.5a.7.7 0 0 1-1 1Z" fill-rule="evenodd"></path></svg>',shortcut:"Mod-\\"}],commands:{clearFormatting:()=>{const s=un();if(!s)return!1;const e=window.getSelection();if(!e||e.rangeCount===0)return!1;const t=e.getRangeAt(0);if(!s.contains(t.commonAncestorContainer))return!1;const n=t.cloneRange();return s.focus({preventScroll:!0}),vn(s,n),yn(s,n),s.dispatchEvent(new Event("input",{bubbles:!0})),!0}},keymap:{"Mod-\\":"clearFormatting"}}),cn=new Set(["A","B","STRONG","I","EM","U","S","STRIKE","DEL","FONT","MARK","CODE","SUB","SUP"]),hn=new Set(["H1","H2","H3","H4","H5","H6","BLOCKQUOTE","PRE"]),dn=["color","background-color","font-size","font-family","font-weight","font-style","text-decoration","text-transform","line-height","letter-spacing","word-spacing","vertical-align","text-align","padding-left"];function un(){const s=window.getSelection();if(s&&s.rangeCount>0){const t=s.getRangeAt(0).startContainer,n=t.nodeType===Node.ELEMENT_NODE?t:t.parentElement,i=n==null?void 0:n.closest('[contenteditable="true"], .rte-content, .editora-content');if(i)return i}const e=document.activeElement;return e?e.getAttribute("contenteditable")==="true"?e:e.closest('[contenteditable="true"], .rte-content, .editora-content'):null}function qe(s,e){try{if(typeof s.intersectsNode=="function")return s.intersectsNode(e)}catch(n){}const t=document.createRange();return e.nodeType===Node.ELEMENT_NODE?t.selectNodeContents(e):t.selectNode(e),s.compareBoundaryPoints(Range.END_TO_START,t)>0&&s.compareBoundaryPoints(Range.START_TO_END,t)<0}function te(s){let e=0,t=s;for(;t&&t.parentNode;)e+=1,t=t.parentNode;return e}function fn(s){dn.forEach(e=>{s.style.removeProperty(e)}),(!s.getAttribute("style")||s.style.length===0)&&s.removeAttribute("style"),s.classList.contains("rte-text-color")&&s.classList.remove("rte-text-color"),s.classList.contains("rte-bg-color")&&s.classList.remove("rte-bg-color"),s.classList.contains("rte-format-painted")&&s.classList.remove("rte-format-painted"),s.classList.length===0&&s.removeAttribute("class")}function ge(s){const e=s.parentNode;if(e){for(;s.firstChild;)e.insertBefore(s.firstChild,s);e.removeChild(s)}}function gn(s){return s.tagName!=="P"||s.attributes.length>0||(s.textContent||"").trim()!==""?!1:!s.querySelector("img, video, table, iframe, hr, pre, ul, ol")}function Ze(s){Array.from(s.children).forEach(e=>{gn(e)&&e.remove()})}function Ge(s){Ze(s),ge(s)}function Qe(s){var t;const e=document.createElement("p");for(Array.from(s.attributes).forEach(n=>{e.setAttribute(n.name,n.value)});s.firstChild;)e.appendChild(s.firstChild);e.innerHTML.trim()||(e.innerHTML="<br>"),(t=s.parentNode)==null||t.replaceChild(e,s)}function pn(s){return!/^(A|B|STRONG|I|EM|U|S|STRIKE|DEL|FONT|MARK|CODE|SUB|SUP|SPAN)$/.test(s.tagName)||(s.textContent||"").trim()!==""?!1:!s.querySelector("img, video, table, iframe, hr, svg, math")}function mn(s){Array.from(s.querySelectorAll("a,b,strong,i,em,u,s,strike,del,font,mark,code,sub,sup,span")).sort((t,n)=>te(n)-te(t)).forEach(t=>{t.isConnected&&pn(t)&&t.remove()})}function bn(s){if(Ze(s),s.parentElement instanceof HTMLLIElement){Ge(s);return}if(Array.from(s.childNodes).filter(i=>i.nodeType!==Node.TEXT_NODE||(i.textContent||"").trim()!=="").some(i=>i instanceof HTMLElement&&/^(P|DIV|H[1-6]|UL|OL|PRE|TABLE|BLOCKQUOTE)$/.test(i.tagName))){Ge(s);return}Qe(s)}function yn(s,e){Array.from(s.querySelectorAll("h1,h2,h3,h4,h5,h6,blockquote,pre")).forEach(n=>{if(qe(e,n)&&hn.has(n.tagName)){if(n.tagName==="BLOCKQUOTE"){bn(n);return}Qe(n)}})}function vn(s,e){const t=Array.from(s.querySelectorAll("a,b,strong,i,em,u,s,strike,del,font,mark,code,sub,sup,span,[style],[class]"));t.sort((n,i)=>te(i)-te(n)),t.forEach(n=>{if(n.isConnected&&qe(e,n)&&!(n.getAttribute("contenteditable")==="false"||n.closest('[contenteditable="false"]'))){if(fn(n),cn.has(n.tagName)){ge(n);return}n.tagName==="SPAN"&&n.attributes.length===0&&ge(n)}}),mn(s)}const xn=Object.freeze(Object.defineProperty({__proto__:null,ClearFormattingPlugin:ln},Symbol.toStringTag,{value:"Module"})),j='.rte-content, .editora-content, [contenteditable="true"]',wn="[data-editora-editor], .rte-editor, .editora-editor, editora-editor",Xe=new Set(["P","DIV","H1","H2","H3","H4","H5","H6","PRE"]),Ye="p,div,h1,h2,h3,h4,h5,h6,ul,ol,blockquote,pre,table",Cn=new Set(["p","h1","h2","h3","h4","h5","h6"]);function Je(s){return s?s.nodeType===Node.ELEMENT_NODE?s:s.parentElement:null}function En(s){const e=s==null?void 0:s.contentElement;if(e instanceof HTMLElement)return e;const t=s==null?void 0:s.editorElement;if(t instanceof HTMLElement){const r=t.querySelector(j);if(r instanceof HTMLElement)return r;if(t.getAttribute("contenteditable")==="true")return t}const n=window.getSelection();if(n&&n.rangeCount>0){const r=Je(n.getRangeAt(0).startContainer),a=r==null?void 0:r.closest(j);if(a instanceof HTMLElement)return a;const l=r==null?void 0:r.closest(wn),c=l==null?void 0:l.querySelector(j);if(c instanceof HTMLElement)return c}const i=document.activeElement,o=i==null?void 0:i.closest(j);return o instanceof HTMLElement?o:document.querySelector(j)}function Tn(s){const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0);return!s.contains(t.startContainer)||!s.contains(t.endContainer)?null:t}function et(s,e){let t=Je(e);if(!t||t===s||!s.contains(t))return null;for(;t.parentElement&&t.parentElement!==s;)t=t.parentElement;if(t.parentElement!==s)return null;if(t.matches(Ye))return t;const n=t.closest(Ye);return n instanceof HTMLElement&&n.parentElement===s?n:t}function tt(s,e){if(typeof s.intersectsNode=="function")try{return s.intersectsNode(e)}catch(n){return!1}const t=document.createRange();return t.selectNode(e),s.compareBoundaryPoints(Range.END_TO_START,t)<0&&s.compareBoundaryPoints(Range.START_TO_END,t)>0}function Sn(s,e){const t=et(s,e.startContainer),n=et(s,e.endContainer);if(!t)return[];if(!n||t===n)return[t];const o=Array.from(s.children).filter(r=>r instanceof HTMLElement).filter(r=>tt(e,r));return o.length>0?o:[t]}function kn(s,e){Array.from(s.attributes).forEach(t=>{e.setAttribute(t.name,t.value)})}function pe(s,e){for(;s.firstChild;)e.appendChild(s.firstChild)}function Mn(s){return s.tagName!=="P"||s.attributes.length>0||(s.textContent||"").trim()!==""?!1:!s.querySelector("img, video, table, iframe, hr, pre, ul, ol")}function ne(s,e){const t=document.createElement(s);return e&&kn(e,t),t}function nt(s,e){const t=ne(e,s);return pe(s,t),t.innerHTML.trim()||(t.innerHTML="<br>"),t}function Ln(s){const e=s.cloneNode(!1);return e instanceof HTMLElement?e:document.createElement(s.tagName.toLowerCase())}function it(s,e,t){const n=s.parentNode;if(!n)return[];const i=document.createDocumentFragment(),o=[];let r=null;const a=()=>{r&&r.children.length>0&&i.appendChild(r),r=null};return Array.from(s.children).forEach(l=>{if(l instanceof HTMLLIElement){if(e.has(l)){a();const c=nt(l,t);i.appendChild(c),o.push(c);return}r||(r=Ln(s)),r.appendChild(l)}}),a(),n.insertBefore(i,s),n.removeChild(s),o}function Rn(s,e){var n;if(s.tagName.toLowerCase()===e)return[s];const t=ne(e,s);return pe(s,t),t.innerHTML.trim()||(t.innerHTML="<br>"),(n=s.parentNode)==null||n.replaceChild(t,s),[t]}function An(s,e){const t=s.parentNode;if(!t)return[];const n=document.createDocumentFragment(),i=[];return Array.from(s.childNodes).forEach(o=>{if(o instanceof HTMLElement&&Mn(o)){o.remove();return}if(o instanceof HTMLUListElement||o instanceof HTMLOListElement){Array.from(o.children).forEach(a=>{if(!(a instanceof HTMLLIElement))return;const l=nt(a,e);n.appendChild(l),i.push(l)}),o.remove();return}if(o instanceof HTMLElement&&Xe.has(o.tagName)){const a=ne(e,o);pe(o,a),n.appendChild(a),i.push(a);return}if(o.nodeType===Node.TEXT_NODE&&(o.textContent||"").trim()===""){o.remove();return}const r=ne(e,s);r.appendChild(o),n.appendChild(r),i.push(r)}),t.insertBefore(n,s),t.removeChild(s),i}function In(s){const e=window.getSelection();if(!e)return;const t=document.createRange(),n=s instanceof HTMLElement&&s.querySelector("p,li,h1,h2,h3,h4,h5,h6")||s;t.selectNodeContents(n),t.collapse(!0),e.removeAllRanges(),e.addRange(t)}function On(s){s.dispatchEvent(new Event("input",{bubbles:!0}))}function Hn(s,e,t){const n=window.execEditorCommand;if(typeof n=="function"){n("recordDomTransaction",s,e,t);return}const i=window.executeEditorCommand;typeof i=="function"&&i("recordDomTransaction",{editor:s,beforeHTML:e,afterHTML:t})}function Nn(s,e){const t=new Map;return Array.from(s.querySelectorAll("li")).filter(i=>i instanceof HTMLLIElement&&tt(e,i)).forEach(i=>{var r;const o=i.parentElement;(o instanceof HTMLUListElement||o instanceof HTMLOListElement)&&o.parentElement===s&&(t.has(o)||t.set(o,new Set),(r=t.get(o))==null||r.add(i))}),t}function U(s,e){const t=s.toLowerCase();if(!Cn.has(t))return!1;const n=En(e);if(!n)return!1;const i=Tn(n);if(!i)return!1;const o=n.innerHTML,r=[],a=Nn(n,i);a.size>0?a.forEach((c,h)=>{r.push(...it(h,c,t))}):Sn(n,i).forEach(h=>{if(h instanceof HTMLUListElement||h instanceof HTMLOListElement){const d=new Set(Array.from(h.children).filter(f=>f instanceof HTMLLIElement));r.push(...it(h,d,t));return}if(Xe.has(h.tagName)){const d=h.querySelector(":scope > ul, :scope > ol, :scope > blockquote, :scope > table");r.push(...d?An(h,t):Rn(h,t))}});const l=n.innerHTML;return o===l||r.length===0?!1:(Hn(n,o,l),On(n),In(r[0]),!0)}const Dn=Object.freeze(Object.defineProperty({__proto__:null,HeadingPlugin:()=>({name:"heading",toolbar:[{label:"P",command:"setBlockType",type:"dropdown",options:[{value:"p",label:"P"},{value:"h1",label:"H1"},{value:"h2",label:"H2"},{value:"h3",label:"H3"},{value:"h4",label:"H4"},{value:"h5",label:"H5"},{value:"h6",label:"H6"}],icon:'<svg width="24" height="24" focusable="false"><path d="M16.1 8.6 14.2 4l-1.4.5 2.8 7.4c.1.4.5.6.9.6h.1c.4-.1.6-.5.6-.9l1.8-4.8-1.4-.5-1.5 2.3ZM4 11.5h6V10H4v1.5ZM18.5 3v1L17 7l.9.9L20.7 3h-2.2ZM5.5 12h1v7h1v-7h1v-.5h-3V12Zm4 0h1v7h1v-7h1v-.5h-3V12Zm10 1.5a2 2 0 0 0-2-2h-1v7.5h1v-2.7h1a2 2 0 0 0 2-2v-.8Zm-2 1.3h-1v-2.3h1a.8.8 0 1 1 0 1.6v.7Z" fill-rule="evenodd"></path></svg>'}],commands:{setBlockType:(s,e)=>s?U(s,e):!1,setHeading1:(s,e)=>U("h1",e),setHeading2:(s,e)=>U("h2",e),setHeading3:(s,e)=>U("h3",e),setParagraph:(s,e)=>U("p",e)},keymap:{"Mod-Alt-1":"setHeading1","Mod-Alt-2":"setHeading2","Mod-Alt-3":"setHeading3","Mod-Alt-0":"setParagraph"}})},Symbol.toStringTag,{value:"Module"})),W='.rte-content, .editora-content, [contenteditable="true"]',Pn="[data-editora-editor], .rte-editor, .editora-editor, editora-editor",ot=["p","div","h1","h2","h3","h4","h5","h6","ul","ol","blockquote","pre","table"].join(",");function me(s){return s?s.nodeType===Node.ELEMENT_NODE?s:s.parentElement:null}function $n(s){const e=s==null?void 0:s.contentElement;if(e instanceof HTMLElement)return e;const t=s==null?void 0:s.editorElement;if(t instanceof HTMLElement){const r=t.querySelector(W);if(r instanceof HTMLElement)return r;if(t.getAttribute("contenteditable")==="true")return t}const n=window.getSelection();if(n&&n.rangeCount>0){const r=me(n.getRangeAt(0).startContainer),a=r==null?void 0:r.closest(W);if(a instanceof HTMLElement)return a;const l=r==null?void 0:r.closest(Pn),c=l==null?void 0:l.querySelector(W);if(c instanceof HTMLElement)return c}const i=document.activeElement,o=i==null?void 0:i.closest(W);return o instanceof HTMLElement?o:document.querySelector(W)}function Fn(s){const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0);return!s.contains(t.startContainer)||!s.contains(t.endContainer)?null:t}function rt(s,e){let t=me(e);if(!t||t===s||!s.contains(t))return null;for(;t.parentElement&&t.parentElement!==s;)t=t.parentElement;if(t.parentElement!==s)return null;if(t.matches(ot))return t;const n=t.closest(ot);return n instanceof HTMLElement&&n.parentElement===s?n:t}function st(s,e){if(typeof s.intersectsNode=="function")try{return s.intersectsNode(e)}catch(n){return!1}const t=document.createRange();return t.selectNode(e),s.compareBoundaryPoints(Range.END_TO_START,t)<0&&s.compareBoundaryPoints(Range.START_TO_END,t)>0}function Bn(s,e){const t=rt(s,e.startContainer),n=rt(s,e.endContainer);if(!t)return[];if(!n||t===n)return[t];const o=Array.from(s.children).filter(r=>r instanceof HTMLElement).filter(r=>st(e,r));return o.length>0?o:[t]}function at(s,e){const t=me(e),n=t==null?void 0:t.closest("blockquote");return n instanceof HTMLQuoteElement&&s.contains(n)?n:null}function _n(s){return s.tagName!=="P"||s.attributes.length>0||(s.textContent||"").trim()!==""?!1:!s.querySelector("img, video, table, iframe, hr, pre, ul, ol")}function zn(s){Array.from(s.children).forEach(e=>{_n(e)&&e.remove()})}function be(s){zn(s);const e=s.parentNode;if(!e)return;Array.from(s.childNodes).forEach(n=>{e.insertBefore(n,s)}),e.removeChild(s)}function lt(s){return s.nodeType===Node.TEXT_NODE&&(s.textContent||"").trim()===""}function ct(s){const e=Array.from(s.childNodes).filter(n=>!lt(n));if(e.length!==1)return null;const t=e[0];return t instanceof HTMLQuoteElement?t:null}function jn(s){const e=document.createElement("blockquote");return Array.from(s.childNodes).filter(n=>!lt(n)).forEach(n=>{e.appendChild(n)}),e.childNodes.length||(e.innerHTML="<br>"),s.appendChild(e),e}function Un(s,e){const t=Array.from(s.querySelectorAll("li")).filter(i=>i instanceof HTMLLIElement&&st(e,i)),n=new Set(t);return t.filter(i=>{var r,a;let o=(r=i.parentElement)==null?void 0:r.closest("li");for(;o;){if(n.has(o))return!1;o=(a=o.parentElement)==null?void 0:a.closest("li")}return!0})}function V(s){const e=window.getSelection();if(!e)return;const t=document.createRange(),n=s instanceof HTMLElement&&s.querySelector("p,li,h1,h2,h3,h4,h5,h6")||s;t.selectNodeContents(n),t.collapse(!0),e.removeAllRanges(),e.addRange(t)}function Wn(s){s.dispatchEvent(new Event("input",{bubbles:!0}))}function Vn(s,e,t){const n=window.execEditorCommand;if(typeof n=="function"){n("recordDomTransaction",s,e,t);return}const i=window.executeEditorCommand;typeof i=="function"&&i("recordDomTransaction",{editor:s,beforeHTML:e,afterHTML:t})}function Kn(s){var h,d;const e=$n(s);if(!e)return!1;const t=Fn(e);if(!t)return!1;const n=e.innerHTML,i=at(e,t.startContainer),o=at(e,t.endContainer),r=Un(e,t),a=Bn(e,t),l=a.length>0&&a.every(f=>f.tagName==="BLOCKQUOTE");if(i&&i===o){const f=i.firstChild||i;be(i),V(f)}else if(r.length>0){const f=r.map(ct);if(f.every(Boolean)){const u=((h=f[0])==null?void 0:h.firstChild)||r[0];f.forEach(g=>{g&&be(g)}),V(u)}else{const u=r[0];r.forEach(g=>{ct(g)||jn(g)}),V(u)}}else if(l){const f=a[0].firstChild||a[0];a.forEach(be),V(f)}else{const f=a.filter(g=>g.tagName!=="BLOCKQUOTE");if(f.length===0)return!1;const p=document.createElement("blockquote"),u=f[0];(d=u.parentNode)==null||d.insertBefore(p,u),f.forEach(g=>{p.appendChild(g)}),V(p)}const c=e.innerHTML;return n===c?!1:(Vn(e,n,c),Wn(e),!0)}const qn=Object.freeze(Object.defineProperty({__proto__:null,BlockquotePlugin:()=>({name:"blockquote",nodes:{blockquote:{content:"block+",group:"block",parseDOM:[{tag:"blockquote"}],toDOM:()=>["blockquote",0]}},toolbar:[{label:"Quote",command:"toggleBlockquote",icon:'<svg fill="#000000" height="24px" width="24px" version="1.1" id="Icons" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 32 32" xml:space="preserve"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <g> <path d="M13,11c0.6,0,1-0.4,1-1s-0.4-1-1-1c-5,0-9,4-9,9c0,2.8,2.2,5,5,5s5-2.2,5-5s-2.2-5-5-5c-0.3,0-0.7,0-1,0.1 C9.3,11.8,11,11,13,11z"></path> <path d="M23,13c-0.3,0-0.7,0-1,0.1c1.3-1.3,3-2.1,5-2.1c0.6,0,1-0.4,1-1s-0.4-1-1-1c-5,0-9,4-9,9c0,2.8,2.2,5,5,5s5-2.2,5-5 S25.8,13,23,13z"></path> </g> </g></svg>',shortcut:"Mod-Shift-9"}],commands:{toggleBlockquote:(s,e)=>Kn(e)},keymap:{"Mod-Shift-9":"toggleBlockquote"}})},Symbol.toStringTag,{value:"Module"}));class ye{constructor(e=""){this._lines=[],this._version=0,this.setText(e)}getLine(e){return this._lines[e]||""}getLines(){return[...this._lines]}getLineCount(){return this._lines.length}getText(){return this._lines.join(`
10
10
  `)}setText(e){this._lines=e.split(`
11
11
  `),this._version++}getTextInRange(e){if(e.start.line===e.end.line)return this.getLine(e.start.line).substring(e.start.column,e.end.column);const t=[];t.push(this.getLine(e.start.line).substring(e.start.column));for(let n=e.start.line+1;n<e.end.line;n++)t.push(this.getLine(n));return e.end.line<this.getLineCount()&&t.push(this.getLine(e.end.line).substring(0,e.end.column)),t.join(`
12
- `)}replaceRange(e,t){const n=this.normalizeRange(e),i=this.getTextInRange(n),o=this.getText(),r=this.positionToOffset(n.start),a=this.positionToOffset(n.end),l=o.slice(0,r)+t+o.slice(a);return this.setText(l),{range:n,text:t,oldText:i}}insertText(e,t){const n={start:e,end:e};return this.replaceRange(n,t)}deleteRange(e){return this.replaceRange(e,"")}positionToOffset(e){let t=0;for(let n=0;n<e.line;n++)t+=this.getLine(n).length+1;return t+=e.column,t}offsetToPosition(e){let t=e;for(let n=0;n<this.getLineCount();n++){const i=this.getLine(n).length;if(t<=i)return{line:n,column:t};t-=i+1}return{line:this.getLineCount()-1,column:this.getLine(this.getLineCount()-1).length}}isValidPosition(e){return!(e.line<0||e.line>=this.getLineCount()||e.column<0||e.column>this.getLine(e.line).length)}isValidRange(e){return this.isValidPosition(e.start)&&this.isValidPosition(e.end)}getVersion(){return this._version}clone(){const e=new be;return e._lines=[...this._lines],e._version=this._version,e}normalizeRange(e){return this.comparePositions(e.start,e.end)<=0?e:{start:e.end,end:e.start}}comparePositions(e,t){return e.line!==t.line?e.line-t.line:e.column-t.column}}class Zn{constructor(e){this.gutterWidth=50,this.gutterFoldColumnWidth=20,this.gutterFoldColumnGap=4,this.gutterLineNumberPaddingLeft=8,this.gutterLineNumberPaddingRight=4,this.gutterDigitWidth=9,this.lineHeight=21,this.trailingNewlineMarkerAttr="data-lce-trailing-newline-marker",this.foldPlaceholderAttr="data-lce-fold-placeholder",this.virtualMarkerRegex=/[\u200B\uE000]/,this.virtualMarkerGlobalRegex=/[\u200B\uE000]/g,this.lastLineCount=0,this.lastHighlightHTML="",this.highlightOverlayActive=!1,this.lastLineDecorationSnapshot="",this.lastGutterDecorationSnapshot="",this.container=e,this.createDOM()}createDOM(){this.container.innerHTML="";const e=document.createElement("div");this.editorContainer=e,e.setAttribute("data-lce-editor-container","true"),e.style.cssText=`
12
+ `)}replaceRange(e,t){const n=this.normalizeRange(e),i=this.getTextInRange(n),o=this.getText(),r=this.positionToOffset(n.start),a=this.positionToOffset(n.end),l=o.slice(0,r)+t+o.slice(a);return this.setText(l),{range:n,text:t,oldText:i}}insertText(e,t){const n={start:e,end:e};return this.replaceRange(n,t)}deleteRange(e){return this.replaceRange(e,"")}positionToOffset(e){let t=0;for(let n=0;n<e.line;n++)t+=this.getLine(n).length+1;return t+=e.column,t}offsetToPosition(e){let t=e;for(let n=0;n<this.getLineCount();n++){const i=this.getLine(n).length;if(t<=i)return{line:n,column:t};t-=i+1}return{line:this.getLineCount()-1,column:this.getLine(this.getLineCount()-1).length}}isValidPosition(e){return!(e.line<0||e.line>=this.getLineCount()||e.column<0||e.column>this.getLine(e.line).length)}isValidRange(e){return this.isValidPosition(e.start)&&this.isValidPosition(e.end)}getVersion(){return this._version}clone(){const e=new ye;return e._lines=[...this._lines],e._version=this._version,e}normalizeRange(e){return this.comparePositions(e.start,e.end)<=0?e:{start:e.end,end:e.start}}comparePositions(e,t){return e.line!==t.line?e.line-t.line:e.column-t.column}}class Zn{constructor(e){this.gutterWidth=50,this.gutterFoldColumnWidth=20,this.gutterFoldColumnGap=4,this.gutterLineNumberPaddingLeft=8,this.gutterLineNumberPaddingRight=4,this.gutterDigitWidth=9,this.lineHeight=21,this.trailingNewlineMarkerAttr="data-lce-trailing-newline-marker",this.foldPlaceholderAttr="data-lce-fold-placeholder",this.virtualMarkerRegex=/[\u200B\uE000]/,this.virtualMarkerGlobalRegex=/[\u200B\uE000]/g,this.lastLineCount=0,this.lastHighlightHTML="",this.highlightOverlayActive=!1,this.lastLineDecorationSnapshot="",this.lastGutterDecorationSnapshot="",this.container=e,this.createDOM()}createDOM(){this.container.innerHTML="";const e=document.createElement("div");this.editorContainer=e,e.setAttribute("data-lce-editor-container","true"),e.style.cssText=`
13
13
  position: relative;
14
14
  display: flex;
15
15
  width: 100%;
@@ -101,21 +101,21 @@
101
101
  width: 100%;
102
102
  min-width: 100%;
103
103
  height: 100%;
104
- `,this.lineNumbersElement.appendChild(this.lineNumbersContentElement),this.lineNumbersElement.appendChild(this.gutterDecorationsElement),n.appendChild(this.lineNumbersElement),t.appendChild(this.lineDecorationsElement),t.appendChild(this.highlightElement),t.appendChild(this.contentElement),n.appendChild(t),e.appendChild(n),this.container.appendChild(e),this.updateLineNumbers(1)}updateLineNumbers(e){if(this.updateGutterWidth(e),e===this.lastLineCount)return;this.lastLineCount=e;const t=Math.max(e,1),n=Array.from({length:t},(i,o)=>o+1);this.lineNumbersContentElement.innerHTML=n.map(i=>`<div style="height: ${this.lineHeight}px; line-height: ${this.lineHeight}px;">${i}</div>`).join("")}updateGutterWidth(e){const t=String(Math.max(e,1)).length*this.gutterDigitWidth+this.gutterLineNumberPaddingLeft+this.gutterLineNumberPaddingRight,n=Math.ceil(t+this.gutterFoldColumnGap+this.gutterFoldColumnWidth);n!==this.gutterWidth&&(this.gutterWidth=n,this.lineNumbersElement.style.display!=="none"&&(this.lineNumbersElement.style.width=`${this.gutterWidth}px`,this.lineNumbersElement.style.minWidth=`${this.gutterWidth}px`))}setDecorations(e,t){this.renderLineDecorations(e),this.renderGutterDecorations(t)}clearDecorations(){this.lastLineDecorationSnapshot&&(this.lineDecorationsElement.innerHTML="",this.lastLineDecorationSnapshot=""),this.lastGutterDecorationSnapshot&&(this.gutterDecorationsElement.innerHTML="",this.lastGutterDecorationSnapshot="")}getContentElement(){return this.contentElement}getLineNumbersElement(){return this.lineNumbersElement}getText(){return this.serializeContentToSource()}setText(e){this.clearHighlightOverlay(),this.setFoldPlaceholderSources(new Map),this.contentElement.textContent!==e&&(this.contentElement.textContent=e),this.syncTrailingNewlineMarker(e.endsWith(`
104
+ `,this.lineNumbersElement.appendChild(this.lineNumbersContentElement),this.lineNumbersElement.appendChild(this.gutterDecorationsElement),n.appendChild(this.lineNumbersElement),t.appendChild(this.lineDecorationsElement),t.appendChild(this.highlightElement),t.appendChild(this.contentElement),n.appendChild(t),e.appendChild(n),this.container.appendChild(e),this.updateLineNumbers(1)}updateLineNumbers(e){if(this.updateGutterWidth(e),e===this.lastLineCount)return;this.lastLineCount=e;const t=Math.max(e,1),n=Array.from({length:t},(i,o)=>o+1);this.lineNumbersContentElement.innerHTML=n.map(i=>`<div style="height: ${this.lineHeight}px; line-height: ${this.lineHeight}px;">${i}</div>`).join("")}updateGutterWidth(e){const n=String(Math.max(e,1)).length*this.gutterDigitWidth+this.gutterLineNumberPaddingLeft+this.gutterLineNumberPaddingRight,i=Math.ceil(n+this.gutterFoldColumnGap+this.gutterFoldColumnWidth);i!==this.gutterWidth&&(this.gutterWidth=i,this.lineNumbersElement.style.display!=="none"&&(this.lineNumbersElement.style.width=`${this.gutterWidth}px`,this.lineNumbersElement.style.minWidth=`${this.gutterWidth}px`))}setDecorations(e,t){this.renderLineDecorations(e),this.renderGutterDecorations(t)}clearDecorations(){this.lastLineDecorationSnapshot&&(this.lineDecorationsElement.innerHTML="",this.lastLineDecorationSnapshot=""),this.lastGutterDecorationSnapshot&&(this.gutterDecorationsElement.innerHTML="",this.lastGutterDecorationSnapshot="")}getContentElement(){return this.contentElement}getLineNumbersElement(){return this.lineNumbersElement}getText(){return this.serializeContentToSource()}setText(e){this.clearHighlightOverlay(),this.setFoldPlaceholderSources(new Map),this.contentElement.textContent!==e&&(this.contentElement.textContent=e),this.syncTrailingNewlineMarker(e.endsWith(`
105
105
  `));const t=e.split(`
106
- `).length;this.updateLineNumbers(t)}setHTML(e){this.clearHighlightOverlay(),this.setFoldPlaceholderSources(new Map);const t=/\n$/.test(e),n=/&lt;|&gt;/.test(e),i=/<span\b/i.test(e),o=/<[^>]+>/.test(e);n&&i?this.contentElement.innerHTML=e:o&&!n?this.contentElement.textContent=e:this.contentElement.innerHTML=e,this.syncTrailingNewlineMarker(t);const r=(this.contentElement.textContent||"").split(`
107
- `).length;this.updateLineNumbers(r)}setHighlightHTML(e){e!==this.lastHighlightHTML&&(this.highlightElement.innerHTML=e,this.lastHighlightHTML=e),this.highlightElement.style.visibility="visible",this.highlightOverlayActive=!0,this.contentElement.style.color="transparent",this.contentElement.style.WebkitTextFillColor="transparent";const t=(this.contentElement.textContent||"").split(`
108
- `).length;this.updateLineNumbers(t)}setLineWrapping(e){this.contentElement.style.whiteSpace=e?"pre-wrap":"pre",this.contentElement.style.overflow="visible",this.contentElement.style.minWidth=e?"100%":"max-content",this.contentSurface.style.minWidth=e?"100%":"max-content",this.contentElement.style.wordBreak="normal",this.contentElement.style.overflowWrap=e?"anywhere":"normal",this.highlightElement.style.whiteSpace=e?"pre-wrap":"pre",this.highlightElement.style.wordBreak="normal",this.highlightElement.style.overflowWrap=e?"anywhere":"normal"}setLineNumbersVisible(e){this.lineNumbersElement.style.display=e?"table-cell":"none",this.lineNumbersElement.style.width=e?`${this.gutterWidth}px`:"0",this.lineNumbersElement.style.minWidth=e?`${this.gutterWidth}px`:"0",this.lineNumbersElement.style.borderRightWidth=e?"1px":"0",this.scrollWrapper.style.width="100%",this.scrollWrapper.style.minWidth="100%"}setTabSize(e){const t=Math.max(1,Math.floor(e)||2);this.contentElement.style.tabSize=String(t),this.contentElement.style.MozTabSize=String(t),this.highlightElement.style.tabSize=String(t),this.highlightElement.style.MozTabSize=String(t)}syncTrailingNewlineMarkerForText(e){this.syncTrailingNewlineMarker(e.endsWith(`
109
- `))}getCursorPosition(){var e;return(e=this.getSelectionState().cursor)!=null?e:{line:0,column:0}}setCursorPosition(e){const t=this.getText(),n=this.positionToTextOffset(e,t),i=window.getSelection(),o=this.createDomRangeFromOffsets(n);if(o)try{i==null||i.removeAllRanges(),i==null||i.addRange(o),this.ensureCaretVisible()}catch(r){console.warn("Could not set cursor position:",r)}else{const r=this.contentElement.querySelector(`[${this.trailingNewlineMarkerAttr}]`),a=document.createRange();try{r&&r.parentNode===this.contentElement?a.setStartBefore(r):(a.selectNodeContents(this.contentElement),a.collapse(!1)),a.collapse(!0),i==null||i.removeAllRanges(),i==null||i.addRange(a),this.ensureCaretVisible()}catch(l){console.warn("Could not set fallback cursor position:",l)}}}getSelectionRange(){return this.getSelectionState().range}getSelectionOffsets(){const e=window.getSelection();if(!e||e.rangeCount===0)return{isInEditor:!1,isCollapsed:!0,startOffset:0,endOffset:0};const t=e.getRangeAt(0);if(!this.isNodeInsideContent(t.startContainer)||!this.isNodeInsideContent(t.endContainer))return{isInEditor:!1,isCollapsed:e.isCollapsed,startOffset:0,endOffset:0};const n=e.anchorNode&&this.isNodeInsideContent(e.anchorNode)?this.sourceOffsetFromBoundary(e.anchorNode,e.anchorOffset):void 0,i=e.focusNode&&this.isNodeInsideContent(e.focusNode)?this.sourceOffsetFromBoundary(e.focusNode,e.focusOffset):void 0;return{isInEditor:!0,isCollapsed:e.isCollapsed,startOffset:this.sourceOffsetFromBoundary(t.startContainer,t.startOffset),endOffset:this.sourceOffsetFromBoundary(t.endContainer,t.endOffset),anchorOffset:n,focusOffset:i}}getSelectionState(){const e=window.getSelection();if(!e||e.rangeCount===0)return{isInEditor:!1,isCollapsed:!0};const t=e.getRangeAt(0);if(!this.isNodeInsideContent(t.startContainer)||!this.isNodeInsideContent(t.endContainer))return{isInEditor:!1,isCollapsed:e.isCollapsed};const n=this.getText(),i=this.sourceOffsetFromBoundary(t.startContainer,t.startOffset),o=this.sourceOffsetFromBoundary(t.endContainer,t.endOffset),r=e.focusNode&&this.isNodeInsideContent(e.focusNode)?this.sourceOffsetFromBoundary(e.focusNode,e.focusOffset):o,a=this.offsetToPositionInText(i,n),l=this.offsetToPositionInText(o,n),c=this.offsetToPositionInText(r,n);return{isInEditor:!0,isCollapsed:e.isCollapsed,cursor:c,range:e.isCollapsed?void 0:{start:a,end:l}}}setSelectionRange(e){const t=this.createDomRangeFromRange(e);if(t)try{const n=window.getSelection();n==null||n.removeAllRanges(),n==null||n.addRange(t),this.ensureCaretVisible()}catch(n){console.warn("Could not set selection range:",n)}}createDomRangeFromOffsets(e,t=e){const[n,i]=e<=t?[e,t]:[t,e],o=this.resolveOffsetToDomPoint(n),r=this.resolveOffsetToDomPoint(i);if(!o||!r)return null;const a=document.createRange();try{return a.setStart(o.node,o.offset),a.setEnd(r.node,r.offset),a}catch(l){return null}}createDomRangeFromRange(e){const t=this.getText();return this.createDomRangeFromOffsets(this.positionToTextOffset(e.start,t),this.positionToTextOffset(e.end,t))}getPositionFromClientPoint(e,t){const n=this.getDomRangeFromClientPoint(e,t);if(!n||!this.isNodeInsideContent(n.startContainer))return null;const i=this.sourceOffsetFromBoundary(n.startContainer,n.startOffset);return this.offsetToPositionInText(i,this.getText())}setSelectionOffsets(e,t=e){const n=this.createDomRangeFromOffsets(e,t);if(n)try{const i=window.getSelection();i==null||i.removeAllRanges(),i==null||i.addRange(n),this.ensureCaretVisible()}catch(i){console.warn("Could not set selection offsets:",i)}}setSelectionBoundaryOffsets(e,t){const n=this.resolveOffsetToDomPoint(e),i=this.resolveOffsetToDomPoint(t),o=window.getSelection();if(!n||!i||!o){this.setSelectionOffsets(e,t);return}try{if(o.removeAllRanges(),e===t){const a=document.createRange();a.setStart(n.node,n.offset),a.collapse(!0),o.addRange(a),this.ensureCaretVisible();return}if(typeof o.extend=="function"){const a=document.createRange();a.setStart(n.node,n.offset),a.collapse(!0),o.addRange(a),o.extend(i.node,i.offset),this.ensureCaretVisible();return}const r=this.createDomRangeFromOffsets(e,t);if(!r)return;o.addRange(r),this.ensureCaretVisible()}catch(r){console.warn("Could not set selection boundary offsets:",r),this.setSelectionOffsets(e,t)}}focus(){this.contentElement.focus(),this.ensureCaretVisible()}blur(){this.contentElement.blur()}setReadOnly(e){this.contentElement.contentEditable=e?"false":"true"}applyTheme(e){Object.entries(e).forEach(([t,n])=>{this.container.style.setProperty(`--${t}`,n)})}scrollToPosition(e){const t=Math.max(0,Math.floor(e.line)||0)*this.lineHeight-this.editorContainer.clientHeight/2+this.lineHeight/2;this.editorContainer.scrollTop=Math.max(0,t)}getScrollTop(){return this.editorContainer.scrollTop}getScrollElement(){return this.editorContainer}setScrollTop(e){this.editorContainer.scrollTop=e}syncTrailingNewlineMarker(e){if(this.contentElement.querySelectorAll(`[${this.trailingNewlineMarkerAttr}]`).forEach(n=>n.remove()),!e)return;const t=document.createElement("span");t.setAttribute(this.trailingNewlineMarkerAttr,"true"),t.setAttribute("aria-hidden","true"),t.contentEditable="false",t.style.cssText=`
106
+ `).length;this.updateLineNumbers(t)}setHTML(e){this.clearHighlightOverlay(),this.setFoldPlaceholderSources(new Map);const t=/\n$/.test(e),n=/&lt;|&gt;/.test(e),i=/<span\b/i.test(e),o=/<[^>]+>/.test(e);n&&i?this.contentElement.innerHTML=e:o&&!n?this.contentElement.textContent=e:this.contentElement.innerHTML=e,this.syncTrailingNewlineMarker(t);const a=(this.contentElement.textContent||"").split(`
107
+ `).length;this.updateLineNumbers(a)}setHighlightHTML(e){e!==this.lastHighlightHTML&&(this.highlightElement.innerHTML=e,this.lastHighlightHTML=e),this.highlightElement.style.visibility="visible",this.highlightOverlayActive=!0,this.contentElement.style.color="transparent",this.contentElement.style.WebkitTextFillColor="transparent";const n=(this.contentElement.textContent||"").split(`
108
+ `).length;this.updateLineNumbers(n)}setLineWrapping(e){this.contentElement.style.whiteSpace=e?"pre-wrap":"pre",this.contentElement.style.overflow="visible",this.contentElement.style.minWidth=e?"100%":"max-content",this.contentSurface.style.minWidth=e?"100%":"max-content",this.contentElement.style.wordBreak="normal",this.contentElement.style.overflowWrap=e?"anywhere":"normal",this.highlightElement.style.whiteSpace=e?"pre-wrap":"pre",this.highlightElement.style.wordBreak="normal",this.highlightElement.style.overflowWrap=e?"anywhere":"normal"}setLineNumbersVisible(e){this.lineNumbersElement.style.display=e?"table-cell":"none",this.lineNumbersElement.style.width=e?`${this.gutterWidth}px`:"0",this.lineNumbersElement.style.minWidth=e?`${this.gutterWidth}px`:"0",this.lineNumbersElement.style.borderRightWidth=e?"1px":"0",this.scrollWrapper.style.width="100%",this.scrollWrapper.style.minWidth="100%"}setTabSize(e){const t=Math.max(1,Math.floor(e)||2);this.contentElement.style.tabSize=String(t),this.contentElement.style.MozTabSize=String(t),this.highlightElement.style.tabSize=String(t),this.highlightElement.style.MozTabSize=String(t)}syncTrailingNewlineMarkerForText(e){this.syncTrailingNewlineMarker(e.endsWith(`
109
+ `))}getCursorPosition(){var e;return(e=this.getSelectionState().cursor)!=null?e:{line:0,column:0}}setCursorPosition(e){const t=this.getText(),n=this.positionToTextOffset(e,t),i=window.getSelection(),o=this.createDomRangeFromOffsets(n);if(o)try{i==null||i.removeAllRanges(),i==null||i.addRange(o),this.ensureCaretVisible()}catch(r){console.warn("Could not set cursor position:",r)}else{const r=this.contentElement.querySelector(`[${this.trailingNewlineMarkerAttr}]`),a=document.createRange();try{r&&r.parentNode===this.contentElement?a.setStartBefore(r):(a.selectNodeContents(this.contentElement),a.collapse(!1)),a.collapse(!0),i==null||i.removeAllRanges(),i==null||i.addRange(a),this.ensureCaretVisible()}catch(l){console.warn("Could not set fallback cursor position:",l)}}}getSelectionRange(){return this.getSelectionState().range}getSelectionOffsets(){const e=window.getSelection();if(!e||e.rangeCount===0)return{isInEditor:!1,isCollapsed:!0,startOffset:0,endOffset:0};const t=e.getRangeAt(0);if(!this.isNodeInsideContent(t.startContainer)||!this.isNodeInsideContent(t.endContainer))return{isInEditor:!1,isCollapsed:e.isCollapsed,startOffset:0,endOffset:0};const n=e.anchorNode&&this.isNodeInsideContent(e.anchorNode)?this.sourceOffsetFromBoundary(e.anchorNode,e.anchorOffset):void 0,i=e.focusNode&&this.isNodeInsideContent(e.focusNode)?this.sourceOffsetFromBoundary(e.focusNode,e.focusOffset):void 0;return{isInEditor:!0,isCollapsed:e.isCollapsed,startOffset:this.sourceOffsetFromBoundary(t.startContainer,t.startOffset),endOffset:this.sourceOffsetFromBoundary(t.endContainer,t.endOffset),anchorOffset:n,focusOffset:i}}getSelectionState(){const e=window.getSelection();if(!e||e.rangeCount===0)return{isInEditor:!1,isCollapsed:!0};const t=e.getRangeAt(0);if(!this.isNodeInsideContent(t.startContainer)||!this.isNodeInsideContent(t.endContainer))return{isInEditor:!1,isCollapsed:e.isCollapsed};const n=this.getText(),i=this.sourceOffsetFromBoundary(t.startContainer,t.startOffset),o=this.sourceOffsetFromBoundary(t.endContainer,t.endOffset),r=e.focusNode&&this.isNodeInsideContent(e.focusNode)?this.sourceOffsetFromBoundary(e.focusNode,e.focusOffset):o,a=this.offsetToPositionInText(i,n),l=this.offsetToPositionInText(o,n),c=this.offsetToPositionInText(r,n);return{isInEditor:!0,isCollapsed:e.isCollapsed,cursor:c,range:e.isCollapsed?void 0:{start:a,end:l}}}setSelectionRange(e){const t=this.createDomRangeFromRange(e);if(t)try{const n=window.getSelection();n==null||n.removeAllRanges(),n==null||n.addRange(t),this.ensureCaretVisible()}catch(n){console.warn("Could not set selection range:",n)}}createDomRangeFromOffsets(e,t=e){const[n,i]=e<=t?[e,t]:[t,e],o=this.resolveOffsetToDomPoint(n),r=this.resolveOffsetToDomPoint(i);if(!o||!r)return null;const a=document.createRange();try{return a.setStart(o.node,o.offset),a.setEnd(r.node,r.offset),a}catch(l){return null}}createDomRangeFromRange(e){const t=this.getText();return this.createDomRangeFromOffsets(this.positionToTextOffset(e.start,t),this.positionToTextOffset(e.end,t))}getPositionFromClientPoint(e,t){const n=this.getDomRangeFromClientPoint(e,t);if(!n||!this.isNodeInsideContent(n.startContainer))return null;const i=this.sourceOffsetFromBoundary(n.startContainer,n.startOffset);return this.offsetToPositionInText(i,this.getText())}setSelectionOffsets(e,t=e){const n=this.createDomRangeFromOffsets(e,t);if(n)try{const i=window.getSelection();i==null||i.removeAllRanges(),i==null||i.addRange(n),this.ensureCaretVisible()}catch(i){console.warn("Could not set selection offsets:",i)}}setSelectionBoundaryOffsets(e,t){const n=this.resolveOffsetToDomPoint(e),i=this.resolveOffsetToDomPoint(t),o=window.getSelection();if(!n||!i||!o){this.setSelectionOffsets(e,t);return}try{if(o.removeAllRanges(),e===t){const a=document.createRange();a.setStart(n.node,n.offset),a.collapse(!0),o.addRange(a),this.ensureCaretVisible();return}if(typeof o.extend=="function"){const a=document.createRange();a.setStart(n.node,n.offset),a.collapse(!0),o.addRange(a),o.extend(i.node,i.offset),this.ensureCaretVisible();return}const r=this.createDomRangeFromOffsets(e,t);if(!r)return;o.addRange(r),this.ensureCaretVisible()}catch(r){console.warn("Could not set selection boundary offsets:",r),this.setSelectionOffsets(e,t)}}focus(){this.contentElement.focus(),this.ensureCaretVisible()}blur(){this.contentElement.blur()}setReadOnly(e){this.contentElement.contentEditable=e?"false":"true"}applyTheme(e){Object.entries(e).forEach(([t,n])=>{this.container.style.setProperty(`--${t}`,n)})}scrollToPosition(e){const i=Math.max(0,Math.floor(e.line)||0)*this.lineHeight-this.editorContainer.clientHeight/2+this.lineHeight/2;this.editorContainer.scrollTop=Math.max(0,i)}getScrollTop(){return this.editorContainer.scrollTop}getScrollElement(){return this.editorContainer}setScrollTop(e){this.editorContainer.scrollTop=e}syncTrailingNewlineMarker(e){if(this.contentElement.querySelectorAll(`[${this.trailingNewlineMarkerAttr}]`).forEach(n=>n.remove()),!e)return;const t=document.createElement("span");t.setAttribute(this.trailingNewlineMarkerAttr,"true"),t.setAttribute("aria-hidden","true"),t.contentEditable="false",t.style.cssText=`
110
110
  display: inline-block;
111
111
  width: 0;
112
112
  overflow: hidden;
113
113
  pointer-events: none;
114
114
  user-select: none;
115
- `,t.appendChild(document.createTextNode("​")),this.contentElement.appendChild(t)}ensureCaretVisible(){const e=window.getSelection();if(!e||e.rangeCount===0)return;const t=this.getCaretClientRect(e);if(!t)return;const n=this.editorContainer.getBoundingClientRect(),i=12;t.bottom>n.bottom-i?this.editorContainer.scrollTop+=t.bottom-(n.bottom-i):t.top<n.top+i&&(this.editorContainer.scrollTop-=n.top+i-t.top),t.right>n.right-i?this.editorContainer.scrollLeft+=t.right-(n.right-i):t.left<n.left+i&&(this.editorContainer.scrollLeft-=n.left+i-t.left)}destroy(){this.clearDecorations(),this.container&&(this.container.innerHTML=""),this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=void 0)}resolveOffsetToDomPoint(e){var o;const t=Math.max(0,e);let n=0;const i=Array.from(this.contentElement.childNodes);for(let r=0;r<i.length;r++){const a=i[r];if(a instanceof Text){const l=a.textContent||"",c=this.buildVisibleToDomMap(l),h=Math.max(0,c.length-1);if(n+h>=t){const u=Math.max(0,t-n),d=(o=c[u])!=null?o:l.length;return{node:a,offset:d}}n+=h;continue}if(a instanceof HTMLElement&&!a.hasAttribute(this.trailingNewlineMarkerAttr)&&a.hasAttribute(this.foldPlaceholderAttr)){const l=this.getFoldPlaceholderSource(a).length;if(n+l>=t){const c=t-n;return{node:this.contentElement,offset:c<=l/2?r:r+1}}n+=l}}return{node:this.contentElement,offset:this.contentElement.childNodes.length}}getDomRangeFromClientPoint(e,t){const n=document;if(typeof n.caretPositionFromPoint=="function"){const i=n.caretPositionFromPoint(e,t);if(i!=null&&i.offsetNode){const o=document.createRange();try{return o.setStart(i.offsetNode,i.offset),o.collapse(!0),o}catch(r){return null}}}return typeof n.caretRangeFromPoint=="function"?n.caretRangeFromPoint(e,t):null}buildVisibleToDomMap(e){const t=[0];let n=0;for(let i=0;i<e.length;i++){const o=e[i];this.virtualMarkerRegex.test(o)||(n+=1,t[n]=i+1)}return t}isNodeInsideContent(e){return e===this.contentElement||this.contentElement.contains(e)}getCaretClientRect(e){var a,l,c;const t=e.getRangeAt(0).cloneRange();t.collapse(!1);const n=this.getUsableRangeRect(t);if(n)return n;const i=e.focusNode,o=e.focusOffset;if(i instanceof Text){const h=(l=(a=i.textContent)==null?void 0:a.length)!=null?l:0,u=document.createRange();if(o<h){u.setStart(i,o),u.setEnd(i,Math.min(h,o+1));const d=this.getUsableRangeRect(u);if(d)return d}if(o>0){u.setStart(i,o-1),u.setEnd(i,o);const d=this.getUsableRangeRect(u);if(d)return d}}const r=i instanceof Element?i:(c=i==null?void 0:i.parentElement)!=null?c:null;if(r&&r!==this.contentElement&&r!==this.editorContainer&&this.contentElement.contains(r)){const h=r.getBoundingClientRect();if(this.isUsableRect(h))return h}return null}getUsableRangeRect(e){const t=Array.from(e.getClientRects());for(let i=0;i<t.length;i++)if(this.isUsableRect(t[i]))return t[i];const n=e.getBoundingClientRect();return this.isUsableRect(n)?n:null}isUsableRect(e){return!!e&&Number.isFinite(e.top)&&Number.isFinite(e.bottom)&&(e.width>0||e.height>0)}stripVirtualMarkers(e){return e.replace(this.virtualMarkerGlobalRegex,"")}clearHighlightOverlay(){!this.highlightOverlayActive&&!this.lastHighlightHTML||(this.highlightElement.innerHTML="",this.highlightElement.style.visibility="hidden",this.lastHighlightHTML="",this.highlightOverlayActive=!1,this.contentElement.style.color="inherit",this.contentElement.style.WebkitTextFillColor="currentcolor")}serializeContentToSource(){let e="";const t=Array.from(this.contentElement.childNodes);for(const n of t){if(n instanceof Text){e+=this.stripVirtualMarkers(n.textContent||"");continue}if(n instanceof HTMLElement&&!n.hasAttribute(this.trailingNewlineMarkerAttr)){if(n.hasAttribute(this.foldPlaceholderAttr)){e+=this.getFoldPlaceholderSource(n);continue}e+=this.stripVirtualMarkers(n.textContent||"")}}return e}sourceOffsetFromBoundary(e,t){let n=0;const i=Array.from(this.contentElement.childNodes);if(e===this.contentElement){for(let o=0;o<Math.min(t,i.length);o++)n+=this.getSourceLength(i[o]);return n}for(let o=0;o<i.length;o++){const r=i[o];if(r===e){if(r instanceof Text)return n+this.stripVirtualMarkers((r.textContent||"").slice(0,t)).length;if(r instanceof HTMLElement){if(r.hasAttribute(this.foldPlaceholderAttr))return n+this.getFoldPlaceholderBoundaryOffset(r,r,t);const a=Array.from(r.childNodes);for(let l=0;l<Math.min(t,a.length);l++)n+=this.getSourceLength(a[l]);return n}}if(r instanceof HTMLElement&&r.contains(e))return r.hasAttribute(this.foldPlaceholderAttr)?n+this.getFoldPlaceholderBoundaryOffset(r,e,t):n+this.sourceOffsetWithinNode(r,e,t);n+=this.getSourceLength(r)}return n}sourceOffsetWithinNode(e,t,n){let i=0;const o=Array.from(e.childNodes);if(t===e){for(let r=0;r<Math.min(n,o.length);r++)i+=this.getSourceLength(o[r]);return i}for(let r=0;r<o.length;r++){const a=o[r];if(a===t){if(a instanceof Text)return i+this.stripVirtualMarkers((a.textContent||"").slice(0,n)).length;if(a instanceof HTMLElement){if(a.hasAttribute(this.foldPlaceholderAttr))return i+this.getFoldPlaceholderBoundaryOffset(a,a,n);const l=Array.from(a.childNodes);for(let c=0;c<Math.min(n,l.length);c++)i+=this.getSourceLength(l[c]);return i}}if(a instanceof HTMLElement&&a.contains(t))return a.hasAttribute(this.foldPlaceholderAttr)?i+this.getFoldPlaceholderBoundaryOffset(a,t,n):i+this.sourceOffsetWithinNode(a,t,n);i+=this.getSourceLength(a)}return i}getSourceLength(e){if(e instanceof Text)return this.stripVirtualMarkers(e.textContent||"").length;if(!(e instanceof HTMLElement)||e.hasAttribute(this.trailingNewlineMarkerAttr))return 0;if(e.hasAttribute(this.foldPlaceholderAttr))return this.getFoldPlaceholderSource(e).length;let t=0;return e.childNodes.forEach(n=>{t+=this.getSourceLength(n)}),t}renderLineDecorations(e){const t=[...e].filter(o=>Number.isFinite(o.line)&&o.line>=0).sort((o,r)=>o.line-r.line||o.id.localeCompare(r.id)),n=t.map(o=>`${o.id}:${o.line}:${o.className||""}:${this.serializeStyleObject(o.style)}`).join("|");if(n===this.lastLineDecorationSnapshot||(this.lineDecorationsElement.innerHTML="",this.lastLineDecorationSnapshot=n,t.length===0))return;const i=document.createDocumentFragment();for(const o of t){const r=document.createElement("div");r.className=this.joinClassNames("lce-decoration lce-decoration-line",o.className),r.setAttribute("data-decoration-id",o.id),r.setAttribute("data-decoration-line",String(o.line)),r.style.cssText=this.joinStyleFragments(["position: absolute",`top: ${o.line*this.lineHeight}px`,`height: ${this.lineHeight}px`,"left: 12px","right: 12px","border-radius: 3px",this.serializeStyleObject(o.style)]),i.appendChild(r)}this.lineDecorationsElement.appendChild(i)}renderGutterDecorations(e){const t=[...e].filter(o=>Number.isFinite(o.line)&&o.line>=0).sort((o,r)=>o.line-r.line||o.id.localeCompare(r.id)),n=t.map(o=>`${o.id}:${o.line}:${o.label||""}:${o.title||""}:${o.className||""}:${this.serializeStyleObject(o.style)}`).join("|");if(n===this.lastGutterDecorationSnapshot||(this.gutterDecorationsElement.innerHTML="",this.lastGutterDecorationSnapshot=n,t.length===0))return;const i=document.createDocumentFragment();for(const o of t){const r=document.createElement("div");r.className=this.joinClassNames("lce-decoration lce-decoration-gutter",o.className),r.setAttribute("data-decoration-id",o.id),r.setAttribute("data-decoration-line",String(o.line)),r.style.cssText=this.joinStyleFragments(["position: absolute",`top: ${o.line*this.lineHeight}px`,`height: ${this.lineHeight}px`,"left: 0","right: 0","display: flex","align-items: center","justify-content: flex-end","padding-right: 4px","box-sizing: border-box",this.serializeStyleObject(o.style)]),o.title&&(r.title=o.title),r.textContent=o.label||"",i.appendChild(r)}this.gutterDecorationsElement.appendChild(i)}joinClassNames(...e){return e.filter(Boolean).join(" ").trim()}joinStyleFragments(e){return e.filter(t=>!!t&&t.trim().length>0).map(t=>{const n=t.trim();return n.endsWith(";")?n:`${n};`}).join(" ")}serializeStyleObject(e){return e?Object.entries(e).filter(([,t])=>typeof t=="string"&&t.length>0).map(([t,n])=>`${this.toKebabCase(t)}: ${n}`).join("; "):""}toKebabCase(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}offsetToPositionInText(e,t){const n=Math.max(0,Math.min(e,t.length)),i=t.slice(0,n).split(`
116
- `);return{line:i.length-1,column:i[i.length-1].length}}positionToTextOffset(e,t){var a;const n=t.split(`
117
- `),i=Math.max(0,Math.min(e.line,n.length-1)),o=Math.max(0,Math.min(e.column,((a=n[i])==null?void 0:a.length)||0));let r=0;for(let l=0;l<i;l++)r+=n[l].length+1;return r+o}getFoldPlaceholderSource(e){const t=e.getAttribute(this.foldPlaceholderAttr),n=this.getFoldPlaceholderSources();return t&&n.has(t)?n.get(t)||"":e.__lceFoldHiddenText||""}getFoldPlaceholderSources(){return this.contentElement.__lceFoldPlaceholderSources||new Map}getFoldPlaceholderBoundaryOffset(e,t,n){const i=this.getFoldPlaceholderSource(e).length,o=this.stripVirtualMarkers(e.textContent||"").length;if(i===0||o===0)return 0;const r=document.createRange();r.selectNodeContents(e);try{r.setEnd(t,n)}catch(a){return 0}return this.stripVirtualMarkers(r.toString()).length<=o/2?0:i}setFoldPlaceholderSources(e){this.contentElement.__lceFoldPlaceholderSources=e}}let Gn=0;const at=class z{constructor(e,t={}){this.extensions=new Map,this.commands=new Map,this.eventListeners=new Map,this.folds=[],this.currentTheme="default",this.isDestroyed=!1,this.undoStack=[],this.redoStack=[],this.suppressHistory=!1,this.highlightTimeout=null,this.expectingProgrammaticCursor=!1,this.lastKnownCursor={line:0,column:0},this.editorInstanceId=++Gn,this.decorationHighlightStyleId=`editora-decoration-style-${this.editorInstanceId}`,this.decorationHighlightLimit=1e3,this.decorationLayers=new Map,this.inlineDecorationHighlightNames=new Set,this.decorationRenderRaf=null,this.decorationMutationObserver=null,this.hasCustomDecorationHighlightSupport=!1,this.lastProgrammaticClipboardInsertAt=0,this.config={value:"",theme:"default",readOnly:!1,tabSize:2,lineWrapping:!1,lineNumbers:!0,...t},this.textModel=new be(this.config.value),this.view=new Zn(e),this.view.setTabSize(this.config.tabSize||2),this.view.setLineWrapping(!!this.config.lineWrapping),this.view.setLineNumbersVisible(this.config.lineNumbers!==!1),this.hasCustomDecorationHighlightSupport=this.detectCustomHighlightSupport(),this.observeDecorationRelevantMutations(),this.setupEventHandlers(),this.config.extensions&&this.config.extensions.forEach(n=>this.addExtension(n)),this.setTheme(this.config.theme),this.view.setReadOnly(this.config.readOnly||!1),this.renderTextWithHighlight(this.textModel.getText()),this.registerBuiltInCommands()}getTextModel(){return this.textModel}getView(){return this.view}getConfig(){return{...this.config}}registerBuiltInCommands(){this.registerCommand("undo",()=>this.undo()),this.registerCommand("redo",()=>this.redo()),this.registerCommand("insertTab",()=>this.insertTab()),this.registerCommand("save",()=>{this.emit("save")})}getKeymapExtension(){return this.extensions.get("keymap")}setupEventHandlers(){const e=this.view.getContentElement();e.addEventListener("beforeinput",t=>{if(this.suppressHistory||this.config.readOnly){this.pendingInputSnapshot=void 0;return}if(t.inputType==="insertFromPaste"||t.inputType==="insertFromPasteAsQuotation"||t.inputType==="insertFromDrop"){const n=t.dataTransfer,i=this.getPlainTextFromDataTransfer(n);if(i.length===0||(t.preventDefault(),this.pendingInputSnapshot=void 0,Date.now()-this.lastProgrammaticClipboardInsertAt<80))return;this.insertClipboardText(i);return}if(t.inputType==="insertParagraph"||t.inputType==="insertLineBreak"){t.preventDefault(),this.pendingInputSnapshot=void 0,this.insertNewLine();return}if(t.inputType==="deleteContentBackward"||t.inputType==="deleteWordBackward"){t.preventDefault(),this.pendingInputSnapshot=void 0,this.deleteBackward();return}if(t.inputType==="deleteContentForward"||t.inputType==="deleteWordForward"){t.preventDefault(),this.pendingInputSnapshot=void 0,this.deleteForward();return}if(t.inputType==="deleteByCut"){t.preventDefault(),this.pendingInputSnapshot=void 0,this.deleteSelection();return}if(t.inputType==="insertText"&&typeof t.data=="string"&&!t.isComposing){t.preventDefault(),this.pendingInputSnapshot=void 0,this.replaceSelectionWithText(t.data);return}this.pendingInputSnapshot=this.captureHistorySnapshot()}),e.addEventListener("paste",t=>{if(this.config.readOnly){t.preventDefault();return}if(Date.now()-this.lastProgrammaticClipboardInsertAt<80){t.preventDefault();return}const n=this.getPlainTextFromDataTransfer(t.clipboardData);n.length!==0&&(t.preventDefault(),this.insertClipboardText(n))}),e.addEventListener("input",()=>{var i;const t=this.view.getText(),n=this.textModel.getText();t!==n?(this.suppressHistory||this.pushUndoSnapshot((i=this.pendingInputSnapshot)!=null?i:this.captureHistorySnapshot(n)),this.pendingInputSnapshot=void 0,this.textModel.setText(t),this.view.syncTrailingNewlineMarkerForText(t),this.hasRenderedFoldPlaceholders()?this.clearPendingHighlightRender():(this.clearPendingHighlightRender(),this.highlightTimeout=setTimeout(()=>{const o=this.view.getText();o!==this.textModel.getText()&&this.textModel.setText(o),this.renderTextWithHighlight(this.textModel.getText(),!1),this.highlightTimeout=null},300)),this.updateLineNumbers(),this.emit("change",[{range:this.getFullRange(),text:t,oldText:n}])):this.pendingInputSnapshot=void 0}),this.documentSelectionChangeHandler=()=>{var i,o,r;const t=this.syncSelectionCacheFromView();if(!t.isInEditor)return;const n=(i=t.cursor)!=null?i:this.lastKnownCursor;this.emit("cursor",{position:n,anchor:(r=(o=t.range)==null?void 0:o.start)!=null?r:n}),this.emit("selection",t.isCollapsed?void 0:t.range)},document.addEventListener("selectionchange",this.documentSelectionChangeHandler),e.addEventListener("keydown",t=>{this.emit("keydown",t);const n=Array.from(this.extensions.values()).reverse();for(const i of n)if(i.onKeyDown&&i.onKeyDown(t)===!1){t.preventDefault(),t.stopPropagation();return}if(t.key==="Tab"&&!this.config.readOnly){this.insertTab(),t.preventDefault(),t.stopPropagation();return}if(t.key==="Backspace"&&!this.config.readOnly){this.deleteBackward(),t.preventDefault(),t.stopPropagation();return}if(t.key==="Delete"&&!this.config.readOnly){this.deleteForward(),t.preventDefault(),t.stopPropagation();return}if(t.key==="Enter"&&!this.config.readOnly){this.insertNewLine(),t.preventDefault(),t.stopPropagation();return}}),e.addEventListener("mousedown",t=>{this.emit("mousedown",t);const n=Array.from(this.extensions.values()).reverse();for(const i of n)if(i.onMouseDown&&i.onMouseDown(t)===!1){t.preventDefault(),t.stopPropagation();return}}),e.addEventListener("contextmenu",t=>{this.emit("contextmenu",t);const n=Array.from(this.extensions.values()).reverse();for(const i of n)if(i.onContextMenu&&i.onContextMenu(t)===!1){t.preventDefault(),t.stopPropagation();return}}),e.addEventListener("focus",()=>{this.emit("focus")}),e.addEventListener("blur",()=>{this.emit("blur")})}updateLineNumbers(){const e=this.textModel.getLineCount();this.view.updateLineNumbers(e)}getFullRange(){return{start:{line:0,column:0},end:{line:this.textModel.getLineCount()-1,column:this.textModel.getLine(this.textModel.getLineCount()-1).length}}}emit(e,...t){const n=this.eventListeners.get(e);n&&n.forEach(i=>i(...t))}getValue(){return this.textModel.getText()}setValue(e){const t=this.textModel.getText();this.textModel.setText(e),this.renderTextWithHighlight(e,!1),this.updateLineNumbers(),this.emit("change",[{range:this.getFullRange(),text:e,oldText:t}])}getState(){return{text:this.getValue(),cursor:this.getCursor(),selection:this.getSelection(),readOnly:this.config.readOnly||!1,theme:this.currentTheme}}getCursor(){var n,i,o;const e=this.syncSelectionCacheFromView(),t=(n=e.cursor)!=null?n:this.lastKnownCursor;return{position:t,anchor:(o=(i=e.range)==null?void 0:i.start)!=null?o:t}}setCursor(e){const t=this.textModel.getText(),n=this.clampPositionToText(e,t),i=this.positionToOffsetInText(n,t);this.lastKnownCursor=n,this.lastKnownSelection=void 0,this.view.setSelectionOffsets(i),this.emit("cursor",this.getCursor())}getSelection(){const e=this.syncSelectionCacheFromView();if(!(!e.isInEditor||e.isCollapsed))return e.range}setSelection(e){const t=this.textModel.getText(),n=this.normalizeRange({start:this.clampPositionToText(e.start,t),end:this.clampPositionToText(e.end,t)}),i=this.positionToOffsetInText(n.start,t),o=this.positionToOffsetInText(n.end,t);this.lastKnownSelection=n,this.lastKnownCursor=n.end,this.view.setSelectionOffsets(i,o),this.emit("selection",n)}setTheme(e){this.currentTheme=e;const t={"editor-background":e==="dark"?"#1e1e1e":"#ffffff","editor-foreground":e==="dark"?"#f8f9fa":"#1a1a1a","editor-gutter-background":e==="dark"?"#252526":"#f8f9fa","editor-gutter-foreground":e==="dark"?"#858585":"#666666","editor-gutter-border":e==="dark"?"#3e3e42":"#e1e5e9"};this.view.applyTheme(t);const n=this.extensions.get("syntax-highlighting");if(n&&typeof n.setTheme=="function")try{n.setTheme(e==="dark"?"dark":"light"),this.renderTextWithHighlight(this.textModel.getText())}catch(i){console.warn("Error applying theme to syntax-highlighting extension",i)}}setReadOnly(e){this.config.readOnly=e,this.view.setReadOnly(e)}addExtension(e){if(this.extensions.has(e.name))throw new Error(`Extension '${e.name}' already exists`);this.extensions.set(e.name,e),e.setup(this),e.name==="syntax-highlighting"&&typeof e.highlightHTML=="function"&&this.renderTextWithHighlight(this.textModel.getText())}removeExtension(e){const t=this.extensions.get(e);t&&t.destroy&&t.destroy(),this.extensions.delete(e)}executeCommand(e,...t){const n=this.commands.get(e);n?n(...t):console.warn(`Command '${e}' not found`)}registerCommand(e,t){this.commands.set(e,t)}setDecorations(e,t){const n=e.trim();if(!n)throw new Error("Decoration layer name must not be empty");if(!Array.isArray(t)||t.length===0){this.decorationLayers.delete(n),this.scheduleDecorationRender();return}this.decorationLayers.set(n,t.map(i=>this.cloneDecoration(i))),this.scheduleDecorationRender()}clearDecorations(e){typeof e=="string"?this.decorationLayers.delete(e.trim()):this.decorationLayers.clear(),this.scheduleDecorationRender()}getDecorations(e){if(typeof e=="string")return(this.decorationLayers.get(e.trim())||[]).map(n=>this.cloneDecoration(n));const t=[];for(const n of this.decorationLayers.values())t.push(...n.map(i=>this.cloneDecoration(i)));return t}search(e,t={}){var h;if(!e)return[];const n={query:e,caseSensitive:!1,wholeWord:!1,regex:!1,...t},i=[],o=this.textModel.getText(),{normalizedText:r,normalizedToRawOffsets:a}=this.buildSearchTextAndOffsetMap(o),l=n.caseSensitive?r:r.toLowerCase(),c=n.caseSensitive?e:e.toLowerCase();if(n.regex){let u;try{u=new RegExp(e,n.caseSensitive?"g":"gi")}catch(g){return[]}let d;for(;(d=u.exec(r))!==null;){const g=(h=d[0])!=null?h:"";if(g.length===0){u.lastIndex=d.index+1;continue}const f=d.index,p=d.index+g.length;n.wholeWord&&!this.isWholeWordBoundary(r,f,p)||this.pushSearchResultFromOffsets(i,f,p,r,a)}}else{let u=0,d=l.indexOf(c,u);for(;d!==-1;){const g=d+c.length;!n.wholeWord||this.isWholeWordBoundary(r,d,g)?(this.pushSearchResultFromOffsets(i,d,g,r,a),u=g):u=d+1,d=l.indexOf(c,u)}}return i}pushSearchResultFromOffsets(e,t,n,i,o){var h,u;const r=(h=o[t])!=null?h:t,a=(u=o[n])!=null?u:r,l=this.textModel.offsetToPosition(r),c=this.textModel.offsetToPosition(a);e.push({range:{start:l,end:c},match:i.substring(t,n)})}isWholeWordBoundary(e,t,n){const i=t>0?e[t-1]:"",o=n<e.length?e[n]:"";return!this.isWordChar(i)&&!this.isWordChar(o)}isWordChar(e){return/^[A-Za-z0-9_]$/.test(e)}buildSearchTextAndOffsetMap(e){const t=[],n=[0];let i=0;for(let o=0;o<e.length;o++){const r=e[o];r==="​"||r===z.CURSOR_SENTINEL||(t.push(r),i+=1,n[i]=o+1)}return n[i]=e.length,{normalizedText:t.join(""),normalizedToRawOffsets:n}}replace(e,t){const n=this.getValue();this.suppressHistory||this.pushUndoSnapshot(this.captureHistorySnapshot(n));const i=this.textModel.replaceRange(e,t);this.expectingProgrammaticCursor=!0,this.renderTextWithHighlight(this.getValue(),!1),this.expectingProgrammaticCursor=!1,this.emit("change",[i])}replaceAll(e,t,n={}){const i=this.search(e,n);let o=0;for(let r=i.length-1;r>=0;r--)this.replace(i[r].range,t),o++;return o}fold(e){this.clearPendingHighlightRender();const t=this.normalizeRange(e);if(t.start.line===t.end.line&&t.start.column===t.end.column)return;const n=this.folds.findIndex(o=>this.isSameFoldRange(o,t)),i={start:t.start,end:t.end,collapsed:!0,level:0};n!==-1?this.folds[n]=i:(this.folds.push(i),this.folds.sort((o,r)=>this.comparePositions(o.start,r.start)))}unfold(e){this.clearPendingHighlightRender();const t=this.normalizeRange(e);this.folds=this.folds.filter(n=>!this.isSameFoldRange(n,t))}getFolds(){return[...this.folds]}focus(){this.view.focus()}blur(){this.view.blur()}renderTextWithHighlight(e,t=!0){const n=this.extensions.get("syntax-highlighting");if(n&&typeof n.highlightHTML=="function")try{if(typeof this.view.setHighlightHTML=="function"){const f=this.view.getContentElement();(f.querySelector("[data-lce-fold-placeholder]")||f.textContent!==e)&&this.view.setText(e);const p=typeof n.highlight=="function"?n.highlight(e):n.highlightHTML(e);this.view.setHighlightHTML(p),this.view.syncTrailingNewlineMarkerForText(e),this.scheduleDecorationRender();return}const i=!t&&!this.expectingProgrammaticCursor;let o,r,a,l;const c=this.view.getSelectionState(),h=c.isInEditor&&!!c.cursor;(t||i)&&h&&(o=c.isCollapsed?void 0:c.range,r=this.textModel.positionToOffset(c.cursor),o&&(a=this.textModel.positionToOffset(o.start),l=this.textModel.positionToOffset(o.end)));const u=h&&(t||i)&&!o&&r!==void 0&&this.hasCollapsedSelectionInEditor(),d=u?this.insertSentinelAtOffset(e,r):e,g=typeof n.highlight=="function"?n.highlight(d):n.highlightHTML(d);typeof this.view.setHighlightHTML=="function"?this.view.setHighlightHTML(g):this.view.setHTML(g),this.view.syncTrailingNewlineMarkerForText(e),(t||i)&&h&&requestAnimationFrame(()=>{try{if(u&&this.restoreCursorFromSentinel()){this.view.ensureCaretVisible();return}if(o&&(a!==void 0||l!==void 0)){const f=a!==void 0?a:r,p=l!==void 0?l:r,m=Math.min(f,p),b=Math.max(f,p),x=this.textModel.offsetToPosition(m),C=this.textModel.offsetToPosition(b);this.view.setSelectionRange({start:x,end:C})}else if(r!==void 0){const f=this.textModel.offsetToPosition(r);this.view.setCursorPosition(f)}}catch(f){}}),this.scheduleDecorationRender();return}catch(i){console.warn("Syntax highlighting failed, falling back to plain text",i)}this.view.setText(e),this.scheduleDecorationRender()}hasCollapsedSelectionInEditor(){const e=window.getSelection();if(!e||e.rangeCount===0||!e.isCollapsed)return!1;const t=e.getRangeAt(0);return this.view.getContentElement().contains(t.commonAncestorContainer)}getCollapsedSelectionOffsetInEditor(){const e=window.getSelection();if(!e||e.rangeCount===0||!e.isCollapsed)return;const t=e.getRangeAt(0),n=this.view.getContentElement();if(!n.contains(t.commonAncestorContainer))return;const i=t.cloneRange();return i.selectNodeContents(n),i.setEnd(t.endContainer,t.endOffset),this.stripVirtualMarkers(i.toString()).length}stripVirtualMarkers(e){return e.replace(/\u200B/g,"").split(z.CURSOR_SENTINEL).join("")}insertSentinelAtOffset(e,t){const n=Math.max(0,Math.min(t,e.length));return e.slice(0,n)+z.CURSOR_SENTINEL+e.slice(n)}restoreCursorFromSentinel(){var a;const e=this.view.getContentElement(),t=window.getSelection(),n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);let i=n.nextNode(),o=null,r=0;for(;i;){const l=(a=i.textContent)!=null?a:"",c=l.indexOf(z.CURSOR_SENTINEL);c!==-1&&(o||(o=i,r=c),i.textContent=l.split(z.CURSOR_SENTINEL).join("")),i=n.nextNode()}if(!o||!t)return!1;try{const l=document.createRange();return l.setStart(o,r),l.collapse(!0),t.removeAllRanges(),t.addRange(l),!0}catch(l){return!1}}destroy(){var e;if(!this.isDestroyed){this.isDestroyed=!0,this.highlightTimeout&&(clearTimeout(this.highlightTimeout),this.highlightTimeout=null),this.pendingInputSnapshot=void 0,this.documentSelectionChangeHandler&&(document.removeEventListener("selectionchange",this.documentSelectionChangeHandler),this.documentSelectionChangeHandler=void 0),this.decorationRenderRaf!==null&&typeof cancelAnimationFrame=="function"&&(cancelAnimationFrame(this.decorationRenderRaf),this.decorationRenderRaf=null),(e=this.decorationMutationObserver)==null||e.disconnect(),this.decorationMutationObserver=null,this.clearInlineDecorationHighlights(!0),this.decorationLayers.clear(),this.view.clearDecorations();for(const t of this.extensions.values())t.destroy&&t.destroy();this.extensions.clear(),this.view.destroy(),this.commands.clear(),this.eventListeners.clear()}}undo(){if(this.undoStack.length===0)return;const e=this.undoStack.pop(),t=this.captureHistorySnapshot();this.pushSnapshot(this.redoStack,t);try{this.suppressHistory=!0,this.expectingProgrammaticCursor=!0,this.restoreHistorySnapshot(e),setTimeout(()=>{this.expectingProgrammaticCursor=!1},30)}finally{this.suppressHistory=!1}}redo(){if(this.redoStack.length===0)return;const e=this.redoStack.pop(),t=this.captureHistorySnapshot();this.pushSnapshot(this.undoStack,t);try{this.suppressHistory=!0,this.expectingProgrammaticCursor=!0,this.restoreHistorySnapshot(e),setTimeout(()=>{this.expectingProgrammaticCursor=!1},30)}finally{this.suppressHistory=!1}}insertTab(){if(this.config.readOnly)return;const e=" ".repeat(this.config.tabSize||2);this.replaceSelectionWithText(e)}insertNewLine(){this.config.readOnly||this.replaceSelectionWithText(`
118
- `)}deleteBackward(){this.config.readOnly||this.deleteUsingDirection("backward")}deleteForward(){this.config.readOnly||this.deleteUsingDirection("forward")}deleteSelection(){if(this.config.readOnly)return;const e=this.textModel.getText(),{startOffset:t,endOffset:n}=this.getActiveSelectionOffsets(e),i=Math.min(t,n),o=Math.max(t,n);i!==o&&this.replaceOffsetsWithText(i,o,"")}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t)}off(e,t){if(!this.eventListeners.has(e))return;const n=this.eventListeners.get(e);if(t){const i=n.indexOf(t);i!==-1&&n.splice(i,1)}else n.length=0}normalizeRange(e){return this.comparePositions(e.start,e.end)<=0?e:{start:e.end,end:e.start}}comparePositions(e,t){return e.line!==t.line?e.line-t.line:e.column-t.column}captureHistorySnapshot(e=this.textModel.getText()){const t=this.view.getSelectionState(),n=t.isInEditor&&!t.isCollapsed?t.range:void 0,i=t.isInEditor&&t.cursor?t.cursor:void 0,o=n!=null?n:this.lastKnownSelection,r=i!=null?i:this.lastKnownCursor,a=this.clampPositionToText(r,e),l={text:e,cursorOffset:this.positionToOffsetInText(a,e)};if(o){const c=this.clampPositionToText(o.start,e),h=this.clampPositionToText(o.end,e);l.anchorOffset=this.positionToOffsetInText(c,e),l.focusOffset=this.positionToOffsetInText(h,e)}return l}restoreHistorySnapshot(e){this.setValue(e.text),requestAnimationFrame(()=>{try{if(e.anchorOffset!==void 0&&e.focusOffset!==void 0&&e.anchorOffset!==e.focusOffset){const t=Math.min(e.anchorOffset,e.focusOffset),n=Math.max(e.anchorOffset,e.focusOffset);this.setSelection({start:this.textModel.offsetToPosition(t),end:this.textModel.offsetToPosition(n)});return}this.setCursor(this.textModel.offsetToPosition(e.cursorOffset))}catch(t){}})}pushUndoSnapshot(e){this.pushSnapshot(this.undoStack,e),this.redoStack.length=0}pushSnapshot(e,t){e.push(t),e.length>100&&e.shift()}clampPositionToText(e,t){var r,a;const n=t.split(`
115
+ `,t.appendChild(document.createTextNode("​")),this.contentElement.appendChild(t)}ensureCaretVisible(){const e=window.getSelection();if(!e||e.rangeCount===0)return;const t=this.getCaretClientRect(e);if(!t)return;const n=this.editorContainer.getBoundingClientRect(),i=12;t.bottom>n.bottom-i?this.editorContainer.scrollTop+=t.bottom-(n.bottom-i):t.top<n.top+i&&(this.editorContainer.scrollTop-=n.top+i-t.top),t.right>n.right-i?this.editorContainer.scrollLeft+=t.right-(n.right-i):t.left<n.left+i&&(this.editorContainer.scrollLeft-=n.left+i-t.left)}destroy(){this.clearDecorations(),this.container&&(this.container.innerHTML=""),this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=void 0)}resolveOffsetToDomPoint(e){var o;const t=Math.max(0,e);let n=0;const i=Array.from(this.contentElement.childNodes);for(let r=0;r<i.length;r++){const a=i[r];if(a instanceof Text){const l=a.textContent||"",c=this.buildVisibleToDomMap(l),h=Math.max(0,c.length-1);if(n+h>=t){const d=Math.max(0,t-n),f=(o=c[d])!=null?o:l.length;return{node:a,offset:f}}n+=h;continue}if(a instanceof HTMLElement&&!a.hasAttribute(this.trailingNewlineMarkerAttr)&&a.hasAttribute(this.foldPlaceholderAttr)){const c=this.getFoldPlaceholderSource(a).length;if(n+c>=t){const h=t-n;return{node:this.contentElement,offset:h<=c/2?r:r+1}}n+=c}}return{node:this.contentElement,offset:this.contentElement.childNodes.length}}getDomRangeFromClientPoint(e,t){const n=document;if(typeof n.caretPositionFromPoint=="function"){const i=n.caretPositionFromPoint(e,t);if(i!=null&&i.offsetNode){const o=document.createRange();try{return o.setStart(i.offsetNode,i.offset),o.collapse(!0),o}catch(r){return null}}}return typeof n.caretRangeFromPoint=="function"?n.caretRangeFromPoint(e,t):null}buildVisibleToDomMap(e){const t=[0];let n=0;for(let i=0;i<e.length;i++){const o=e[i];this.virtualMarkerRegex.test(o)||(n+=1,t[n]=i+1)}return t}isNodeInsideContent(e){return e===this.contentElement||this.contentElement.contains(e)}getCaretClientRect(e){var a,l,c;const t=e.getRangeAt(0).cloneRange();t.collapse(!1);const n=this.getUsableRangeRect(t);if(n)return n;const i=e.focusNode,o=e.focusOffset;if(i instanceof Text){const h=(l=(a=i.textContent)==null?void 0:a.length)!=null?l:0,d=document.createRange();if(o<h){d.setStart(i,o),d.setEnd(i,Math.min(h,o+1));const f=this.getUsableRangeRect(d);if(f)return f}if(o>0){d.setStart(i,o-1),d.setEnd(i,o);const f=this.getUsableRangeRect(d);if(f)return f}}const r=i instanceof Element?i:(c=i==null?void 0:i.parentElement)!=null?c:null;if(r&&r!==this.contentElement&&r!==this.editorContainer&&this.contentElement.contains(r)){const h=r.getBoundingClientRect();if(this.isUsableRect(h))return h}return null}getUsableRangeRect(e){const t=Array.from(e.getClientRects());for(let i=0;i<t.length;i++)if(this.isUsableRect(t[i]))return t[i];const n=e.getBoundingClientRect();return this.isUsableRect(n)?n:null}isUsableRect(e){return!!e&&Number.isFinite(e.top)&&Number.isFinite(e.bottom)&&(e.width>0||e.height>0)}stripVirtualMarkers(e){return e.replace(this.virtualMarkerGlobalRegex,"")}clearHighlightOverlay(){!this.highlightOverlayActive&&!this.lastHighlightHTML||(this.highlightElement.innerHTML="",this.highlightElement.style.visibility="hidden",this.lastHighlightHTML="",this.highlightOverlayActive=!1,this.contentElement.style.color="inherit",this.contentElement.style.WebkitTextFillColor="currentcolor")}serializeContentToSource(){let e="";const t=Array.from(this.contentElement.childNodes);for(const n of t){if(n instanceof Text){e+=this.stripVirtualMarkers(n.textContent||"");continue}if(n instanceof HTMLElement&&!n.hasAttribute(this.trailingNewlineMarkerAttr)){if(n.hasAttribute(this.foldPlaceholderAttr)){e+=this.getFoldPlaceholderSource(n);continue}e+=this.stripVirtualMarkers(n.textContent||"")}}return e}sourceOffsetFromBoundary(e,t){let n=0;const i=Array.from(this.contentElement.childNodes);if(e===this.contentElement){for(let o=0;o<Math.min(t,i.length);o++)n+=this.getSourceLength(i[o]);return n}for(let o=0;o<i.length;o++){const r=i[o];if(r===e){if(r instanceof Text)return n+this.stripVirtualMarkers((r.textContent||"").slice(0,t)).length;if(r instanceof HTMLElement){if(r.hasAttribute(this.foldPlaceholderAttr))return n+this.getFoldPlaceholderBoundaryOffset(r,r,t);const a=Array.from(r.childNodes);for(let l=0;l<Math.min(t,a.length);l++)n+=this.getSourceLength(a[l]);return n}}if(r instanceof HTMLElement&&r.contains(e))return r.hasAttribute(this.foldPlaceholderAttr)?n+this.getFoldPlaceholderBoundaryOffset(r,e,t):n+this.sourceOffsetWithinNode(r,e,t);n+=this.getSourceLength(r)}return n}sourceOffsetWithinNode(e,t,n){let i=0;const o=Array.from(e.childNodes);if(t===e){for(let r=0;r<Math.min(n,o.length);r++)i+=this.getSourceLength(o[r]);return i}for(let r=0;r<o.length;r++){const a=o[r];if(a===t){if(a instanceof Text)return i+this.stripVirtualMarkers((a.textContent||"").slice(0,n)).length;if(a instanceof HTMLElement){if(a.hasAttribute(this.foldPlaceholderAttr))return i+this.getFoldPlaceholderBoundaryOffset(a,a,n);const l=Array.from(a.childNodes);for(let c=0;c<Math.min(n,l.length);c++)i+=this.getSourceLength(l[c]);return i}}if(a instanceof HTMLElement&&a.contains(t))return a.hasAttribute(this.foldPlaceholderAttr)?i+this.getFoldPlaceholderBoundaryOffset(a,t,n):i+this.sourceOffsetWithinNode(a,t,n);i+=this.getSourceLength(a)}return i}getSourceLength(e){if(e instanceof Text)return this.stripVirtualMarkers(e.textContent||"").length;if(!(e instanceof HTMLElement)||e.hasAttribute(this.trailingNewlineMarkerAttr))return 0;if(e.hasAttribute(this.foldPlaceholderAttr))return this.getFoldPlaceholderSource(e).length;let t=0;return e.childNodes.forEach(n=>{t+=this.getSourceLength(n)}),t}renderLineDecorations(e){const t=[...e].filter(o=>Number.isFinite(o.line)&&o.line>=0).sort((o,r)=>o.line-r.line||o.id.localeCompare(r.id)),n=t.map(o=>`${o.id}:${o.line}:${o.className||""}:${this.serializeStyleObject(o.style)}`).join("|");if(n===this.lastLineDecorationSnapshot||(this.lineDecorationsElement.innerHTML="",this.lastLineDecorationSnapshot=n,t.length===0))return;const i=document.createDocumentFragment();for(const o of t){const r=document.createElement("div");r.className=this.joinClassNames("lce-decoration lce-decoration-line",o.className),r.setAttribute("data-decoration-id",o.id),r.setAttribute("data-decoration-line",String(o.line)),r.style.cssText=this.joinStyleFragments(["position: absolute",`top: ${o.line*this.lineHeight}px`,`height: ${this.lineHeight}px`,"left: 12px","right: 12px","border-radius: 3px",this.serializeStyleObject(o.style)]),i.appendChild(r)}this.lineDecorationsElement.appendChild(i)}renderGutterDecorations(e){const t=[...e].filter(o=>Number.isFinite(o.line)&&o.line>=0).sort((o,r)=>o.line-r.line||o.id.localeCompare(r.id)),n=t.map(o=>`${o.id}:${o.line}:${o.label||""}:${o.title||""}:${o.className||""}:${this.serializeStyleObject(o.style)}`).join("|");if(n===this.lastGutterDecorationSnapshot||(this.gutterDecorationsElement.innerHTML="",this.lastGutterDecorationSnapshot=n,t.length===0))return;const i=document.createDocumentFragment();for(const o of t){const r=document.createElement("div");r.className=this.joinClassNames("lce-decoration lce-decoration-gutter",o.className),r.setAttribute("data-decoration-id",o.id),r.setAttribute("data-decoration-line",String(o.line)),r.style.cssText=this.joinStyleFragments(["position: absolute",`top: ${o.line*this.lineHeight}px`,`height: ${this.lineHeight}px`,"left: 0","right: 0","display: flex","align-items: center","justify-content: flex-end","padding-right: 4px","box-sizing: border-box",this.serializeStyleObject(o.style)]),o.title&&(r.title=o.title),r.textContent=o.label||"",i.appendChild(r)}this.gutterDecorationsElement.appendChild(i)}joinClassNames(...e){return e.filter(Boolean).join(" ").trim()}joinStyleFragments(e){return e.filter(t=>!!t&&t.trim().length>0).map(t=>{const n=t.trim();return n.endsWith(";")?n:`${n};`}).join(" ")}serializeStyleObject(e){return e?Object.entries(e).filter(([,t])=>typeof t=="string"&&t.length>0).map(([t,n])=>`${this.toKebabCase(t)}: ${n}`).join("; "):""}toKebabCase(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}offsetToPositionInText(e,t){const n=Math.max(0,Math.min(e,t.length)),o=t.slice(0,n).split(`
116
+ `);return{line:o.length-1,column:o[o.length-1].length}}positionToTextOffset(e,t){var a;const n=t.split(`
117
+ `),i=Math.max(0,Math.min(e.line,n.length-1)),o=Math.max(0,Math.min(e.column,((a=n[i])==null?void 0:a.length)||0));let r=0;for(let l=0;l<i;l++)r+=n[l].length+1;return r+o}getFoldPlaceholderSource(e){const t=e.getAttribute(this.foldPlaceholderAttr),n=this.getFoldPlaceholderSources();return t&&n.has(t)?n.get(t)||"":e.__lceFoldHiddenText||""}getFoldPlaceholderSources(){return this.contentElement.__lceFoldPlaceholderSources||new Map}getFoldPlaceholderBoundaryOffset(e,t,n){const i=this.getFoldPlaceholderSource(e).length,o=this.stripVirtualMarkers(e.textContent||"").length;if(i===0||o===0)return 0;const r=document.createRange();r.selectNodeContents(e);try{r.setEnd(t,n)}catch(l){return 0}return this.stripVirtualMarkers(r.toString()).length<=o/2?0:i}setFoldPlaceholderSources(e){this.contentElement.__lceFoldPlaceholderSources=e}}let Gn=0;const H=class H{constructor(e,t={}){this.extensions=new Map,this.commands=new Map,this.eventListeners=new Map,this.folds=[],this.currentTheme="default",this.isDestroyed=!1,this.undoStack=[],this.redoStack=[],this.suppressHistory=!1,this.highlightTimeout=null,this.expectingProgrammaticCursor=!1,this.lastKnownCursor={line:0,column:0},this.editorInstanceId=++Gn,this.decorationHighlightStyleId=`editora-decoration-style-${this.editorInstanceId}`,this.decorationHighlightLimit=1e3,this.decorationLayers=new Map,this.inlineDecorationHighlightNames=new Set,this.decorationRenderRaf=null,this.decorationMutationObserver=null,this.hasCustomDecorationHighlightSupport=!1,this.lastProgrammaticClipboardInsertAt=0,this.config={value:"",theme:"default",readOnly:!1,tabSize:2,lineWrapping:!1,lineNumbers:!0,...t},this.textModel=new ye(this.config.value),this.view=new Zn(e),this.view.setTabSize(this.config.tabSize||2),this.view.setLineWrapping(!!this.config.lineWrapping),this.view.setLineNumbersVisible(this.config.lineNumbers!==!1),this.hasCustomDecorationHighlightSupport=this.detectCustomHighlightSupport(),this.observeDecorationRelevantMutations(),this.setupEventHandlers(),this.config.extensions&&this.config.extensions.forEach(n=>this.addExtension(n)),this.setTheme(this.config.theme),this.view.setReadOnly(this.config.readOnly||!1),this.renderTextWithHighlight(this.textModel.getText()),this.registerBuiltInCommands()}getTextModel(){return this.textModel}getView(){return this.view}getConfig(){return{...this.config}}registerBuiltInCommands(){this.registerCommand("undo",()=>this.undo()),this.registerCommand("redo",()=>this.redo()),this.registerCommand("insertTab",()=>this.insertTab()),this.registerCommand("save",()=>{this.emit("save")})}getKeymapExtension(){return this.extensions.get("keymap")}setupEventHandlers(){const e=this.view.getContentElement();e.addEventListener("beforeinput",t=>{if(this.suppressHistory||this.config.readOnly){this.pendingInputSnapshot=void 0;return}if(t.inputType==="insertFromPaste"||t.inputType==="insertFromPasteAsQuotation"||t.inputType==="insertFromDrop"){const n=t.dataTransfer,i=this.getPlainTextFromDataTransfer(n);if(i.length===0||(t.preventDefault(),this.pendingInputSnapshot=void 0,Date.now()-this.lastProgrammaticClipboardInsertAt<80))return;this.insertClipboardText(i);return}if(t.inputType==="insertParagraph"||t.inputType==="insertLineBreak"){t.preventDefault(),this.pendingInputSnapshot=void 0,this.insertNewLine();return}if(t.inputType==="deleteContentBackward"||t.inputType==="deleteWordBackward"){t.preventDefault(),this.pendingInputSnapshot=void 0,this.deleteBackward();return}if(t.inputType==="deleteContentForward"||t.inputType==="deleteWordForward"){t.preventDefault(),this.pendingInputSnapshot=void 0,this.deleteForward();return}if(t.inputType==="deleteByCut"){t.preventDefault(),this.pendingInputSnapshot=void 0,this.deleteSelection();return}if(t.inputType==="insertText"&&typeof t.data=="string"&&!t.isComposing){t.preventDefault(),this.pendingInputSnapshot=void 0,this.replaceSelectionWithText(t.data);return}this.pendingInputSnapshot=this.captureHistorySnapshot()}),e.addEventListener("paste",t=>{if(this.config.readOnly){t.preventDefault();return}if(Date.now()-this.lastProgrammaticClipboardInsertAt<80){t.preventDefault();return}const n=this.getPlainTextFromDataTransfer(t.clipboardData);n.length!==0&&(t.preventDefault(),this.insertClipboardText(n))}),e.addEventListener("input",()=>{var i;const t=this.view.getText(),n=this.textModel.getText();t!==n?(this.suppressHistory||this.pushUndoSnapshot((i=this.pendingInputSnapshot)!=null?i:this.captureHistorySnapshot(n)),this.pendingInputSnapshot=void 0,this.textModel.setText(t),this.view.syncTrailingNewlineMarkerForText(t),this.hasRenderedFoldPlaceholders()?this.clearPendingHighlightRender():(this.clearPendingHighlightRender(),this.highlightTimeout=setTimeout(()=>{const o=this.view.getText();o!==this.textModel.getText()&&this.textModel.setText(o),this.renderTextWithHighlight(this.textModel.getText(),!1),this.highlightTimeout=null},300)),this.updateLineNumbers(),this.emit("change",[{range:this.getFullRange(),text:t,oldText:n}])):this.pendingInputSnapshot=void 0}),this.documentSelectionChangeHandler=()=>{var i,o,r;const t=this.syncSelectionCacheFromView();if(!t.isInEditor)return;const n=(i=t.cursor)!=null?i:this.lastKnownCursor;this.emit("cursor",{position:n,anchor:(r=(o=t.range)==null?void 0:o.start)!=null?r:n}),this.emit("selection",t.isCollapsed?void 0:t.range)},document.addEventListener("selectionchange",this.documentSelectionChangeHandler),e.addEventListener("keydown",t=>{this.emit("keydown",t);const n=Array.from(this.extensions.values()).reverse();for(const i of n)if(i.onKeyDown&&i.onKeyDown(t)===!1){t.preventDefault(),t.stopPropagation();return}if(t.key==="Tab"&&!this.config.readOnly){this.insertTab(),t.preventDefault(),t.stopPropagation();return}if(t.key==="Backspace"&&!this.config.readOnly){this.deleteBackward(),t.preventDefault(),t.stopPropagation();return}if(t.key==="Delete"&&!this.config.readOnly){this.deleteForward(),t.preventDefault(),t.stopPropagation();return}if(t.key==="Enter"&&!this.config.readOnly){this.insertNewLine(),t.preventDefault(),t.stopPropagation();return}}),e.addEventListener("mousedown",t=>{this.emit("mousedown",t);const n=Array.from(this.extensions.values()).reverse();for(const i of n)if(i.onMouseDown&&i.onMouseDown(t)===!1){t.preventDefault(),t.stopPropagation();return}}),e.addEventListener("contextmenu",t=>{this.emit("contextmenu",t);const n=Array.from(this.extensions.values()).reverse();for(const i of n)if(i.onContextMenu&&i.onContextMenu(t)===!1){t.preventDefault(),t.stopPropagation();return}}),e.addEventListener("focus",()=>{this.emit("focus")}),e.addEventListener("blur",()=>{this.emit("blur")})}updateLineNumbers(){const e=this.textModel.getLineCount();this.view.updateLineNumbers(e)}getFullRange(){return{start:{line:0,column:0},end:{line:this.textModel.getLineCount()-1,column:this.textModel.getLine(this.textModel.getLineCount()-1).length}}}emit(e,...t){const n=this.eventListeners.get(e);n&&n.forEach(i=>i(...t))}getValue(){return this.textModel.getText()}setValue(e){const t=this.textModel.getText();this.textModel.setText(e),this.renderTextWithHighlight(e,!1),this.updateLineNumbers(),this.emit("change",[{range:this.getFullRange(),text:e,oldText:t}])}getState(){return{text:this.getValue(),cursor:this.getCursor(),selection:this.getSelection(),readOnly:this.config.readOnly||!1,theme:this.currentTheme}}getCursor(){var n,i,o;const e=this.syncSelectionCacheFromView(),t=(n=e.cursor)!=null?n:this.lastKnownCursor;return{position:t,anchor:(o=(i=e.range)==null?void 0:i.start)!=null?o:t}}setCursor(e){const t=this.textModel.getText(),n=this.clampPositionToText(e,t),i=this.positionToOffsetInText(n,t);this.lastKnownCursor=n,this.lastKnownSelection=void 0,this.view.setSelectionOffsets(i),this.emit("cursor",this.getCursor())}getSelection(){const e=this.syncSelectionCacheFromView();if(!(!e.isInEditor||e.isCollapsed))return e.range}setSelection(e){const t=this.textModel.getText(),n=this.normalizeRange({start:this.clampPositionToText(e.start,t),end:this.clampPositionToText(e.end,t)}),i=this.positionToOffsetInText(n.start,t),o=this.positionToOffsetInText(n.end,t);this.lastKnownSelection=n,this.lastKnownCursor=n.end,this.view.setSelectionOffsets(i,o),this.emit("selection",n)}setTheme(e){this.currentTheme=e;const t={"editor-background":e==="dark"?"#1e1e1e":"#ffffff","editor-foreground":e==="dark"?"#f8f9fa":"#1a1a1a","editor-gutter-background":e==="dark"?"#252526":"#f8f9fa","editor-gutter-foreground":e==="dark"?"#858585":"#666666","editor-gutter-border":e==="dark"?"#3e3e42":"#e1e5e9"};this.view.applyTheme(t);const n=this.extensions.get("syntax-highlighting");if(n&&typeof n.setTheme=="function")try{n.setTheme(e==="dark"?"dark":"light"),this.renderTextWithHighlight(this.textModel.getText())}catch(i){console.warn("Error applying theme to syntax-highlighting extension",i)}}setReadOnly(e){this.config.readOnly=e,this.view.setReadOnly(e)}addExtension(e){if(this.extensions.has(e.name))throw new Error(`Extension '${e.name}' already exists`);this.extensions.set(e.name,e),e.setup(this),e.name==="syntax-highlighting"&&typeof e.highlightHTML=="function"&&this.renderTextWithHighlight(this.textModel.getText())}removeExtension(e){const t=this.extensions.get(e);t&&t.destroy&&t.destroy(),this.extensions.delete(e)}executeCommand(e,...t){const n=this.commands.get(e);n?n(...t):console.warn(`Command '${e}' not found`)}registerCommand(e,t){this.commands.set(e,t)}setDecorations(e,t){const n=e.trim();if(!n)throw new Error("Decoration layer name must not be empty");if(!Array.isArray(t)||t.length===0){this.decorationLayers.delete(n),this.scheduleDecorationRender();return}this.decorationLayers.set(n,t.map(i=>this.cloneDecoration(i))),this.scheduleDecorationRender()}clearDecorations(e){typeof e=="string"?this.decorationLayers.delete(e.trim()):this.decorationLayers.clear(),this.scheduleDecorationRender()}getDecorations(e){if(typeof e=="string")return(this.decorationLayers.get(e.trim())||[]).map(n=>this.cloneDecoration(n));const t=[];for(const n of this.decorationLayers.values())t.push(...n.map(i=>this.cloneDecoration(i)));return t}search(e,t={}){var h;if(!e)return[];const n={query:e,caseSensitive:!1,wholeWord:!1,regex:!1,...t},i=[],o=this.textModel.getText(),{normalizedText:r,normalizedToRawOffsets:a}=this.buildSearchTextAndOffsetMap(o),l=n.caseSensitive?r:r.toLowerCase(),c=n.caseSensitive?e:e.toLowerCase();if(n.regex){let d;try{d=new RegExp(e,n.caseSensitive?"g":"gi")}catch(p){return[]}let f;for(;(f=d.exec(r))!==null;){const p=(h=f[0])!=null?h:"";if(p.length===0){d.lastIndex=f.index+1;continue}const u=f.index,g=f.index+p.length;n.wholeWord&&!this.isWholeWordBoundary(r,u,g)||this.pushSearchResultFromOffsets(i,u,g,r,a)}}else{let d=0,f=l.indexOf(c,d);for(;f!==-1;){const p=f+c.length;!n.wholeWord||this.isWholeWordBoundary(r,f,p)?(this.pushSearchResultFromOffsets(i,f,p,r,a),d=p):d=f+1,f=l.indexOf(c,d)}}return i}pushSearchResultFromOffsets(e,t,n,i,o){var h,d;const r=(h=o[t])!=null?h:t,a=(d=o[n])!=null?d:r,l=this.textModel.offsetToPosition(r),c=this.textModel.offsetToPosition(a);e.push({range:{start:l,end:c},match:i.substring(t,n)})}isWholeWordBoundary(e,t,n){const i=t>0?e[t-1]:"",o=n<e.length?e[n]:"";return!this.isWordChar(i)&&!this.isWordChar(o)}isWordChar(e){return/^[A-Za-z0-9_]$/.test(e)}buildSearchTextAndOffsetMap(e){const t=[],n=[0];let i=0;for(let o=0;o<e.length;o++){const r=e[o];r==="​"||r===H.CURSOR_SENTINEL||(t.push(r),i+=1,n[i]=o+1)}return n[i]=e.length,{normalizedText:t.join(""),normalizedToRawOffsets:n}}replace(e,t){const n=this.getValue();this.suppressHistory||this.pushUndoSnapshot(this.captureHistorySnapshot(n));const i=this.textModel.replaceRange(e,t);this.expectingProgrammaticCursor=!0,this.renderTextWithHighlight(this.getValue(),!1),this.expectingProgrammaticCursor=!1,this.emit("change",[i])}replaceAll(e,t,n={}){const i=this.search(e,n);let o=0;for(let r=i.length-1;r>=0;r--)this.replace(i[r].range,t),o++;return o}fold(e){this.clearPendingHighlightRender();const t=this.normalizeRange(e);if(t.start.line===t.end.line&&t.start.column===t.end.column)return;const n=this.folds.findIndex(o=>this.isSameFoldRange(o,t)),i={start:t.start,end:t.end,collapsed:!0,level:0};n!==-1?this.folds[n]=i:(this.folds.push(i),this.folds.sort((o,r)=>this.comparePositions(o.start,r.start)))}unfold(e){this.clearPendingHighlightRender();const t=this.normalizeRange(e);this.folds=this.folds.filter(n=>!this.isSameFoldRange(n,t))}getFolds(){return[...this.folds]}focus(){this.view.focus()}blur(){this.view.blur()}renderTextWithHighlight(e,t=!0){const n=this.extensions.get("syntax-highlighting");if(n&&typeof n.highlightHTML=="function")try{if(typeof this.view.setHighlightHTML=="function"){const g=this.view.getContentElement();(g.querySelector("[data-lce-fold-placeholder]")||g.textContent!==e)&&this.view.setText(e);const b=typeof n.highlight=="function"?n.highlight(e):n.highlightHTML(e);this.view.setHighlightHTML(b),this.view.syncTrailingNewlineMarkerForText(e),this.scheduleDecorationRender();return}const o=!t&&!this.expectingProgrammaticCursor;let r,a,l,c;const h=this.view.getSelectionState(),d=h.isInEditor&&!!h.cursor;(t||o)&&d&&(r=h.isCollapsed?void 0:h.range,a=this.textModel.positionToOffset(h.cursor),r&&(l=this.textModel.positionToOffset(r.start),c=this.textModel.positionToOffset(r.end)));const f=d&&(t||o)&&!r&&a!==void 0&&this.hasCollapsedSelectionInEditor(),p=f?this.insertSentinelAtOffset(e,a):e,u=typeof n.highlight=="function"?n.highlight(p):n.highlightHTML(p);typeof this.view.setHighlightHTML=="function"?this.view.setHighlightHTML(u):this.view.setHTML(u),this.view.syncTrailingNewlineMarkerForText(e),(t||o)&&d&&requestAnimationFrame(()=>{try{if(f&&this.restoreCursorFromSentinel()){this.view.ensureCaretVisible();return}if(r&&(l!==void 0||c!==void 0)){const g=l!==void 0?l:a,m=c!==void 0?c:a,b=Math.min(g,m),v=Math.max(g,m),C=this.textModel.offsetToPosition(b),w=this.textModel.offsetToPosition(v);this.view.setSelectionRange({start:C,end:w})}else if(a!==void 0){const g=this.textModel.offsetToPosition(a);this.view.setCursorPosition(g)}}catch(g){}}),this.scheduleDecorationRender();return}catch(i){console.warn("Syntax highlighting failed, falling back to plain text",i)}this.view.setText(e),this.scheduleDecorationRender()}hasCollapsedSelectionInEditor(){const e=window.getSelection();if(!e||e.rangeCount===0||!e.isCollapsed)return!1;const t=e.getRangeAt(0);return this.view.getContentElement().contains(t.commonAncestorContainer)}getCollapsedSelectionOffsetInEditor(){const e=window.getSelection();if(!e||e.rangeCount===0||!e.isCollapsed)return;const t=e.getRangeAt(0),n=this.view.getContentElement();if(!n.contains(t.commonAncestorContainer))return;const i=t.cloneRange();return i.selectNodeContents(n),i.setEnd(t.endContainer,t.endOffset),this.stripVirtualMarkers(i.toString()).length}stripVirtualMarkers(e){return e.replace(/\u200B/g,"").split(H.CURSOR_SENTINEL).join("")}insertSentinelAtOffset(e,t){const n=Math.max(0,Math.min(t,e.length));return e.slice(0,n)+H.CURSOR_SENTINEL+e.slice(n)}restoreCursorFromSentinel(){var a;const e=this.view.getContentElement(),t=window.getSelection(),n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);let i=n.nextNode(),o=null,r=0;for(;i;){const l=(a=i.textContent)!=null?a:"",c=l.indexOf(H.CURSOR_SENTINEL);c!==-1&&(o||(o=i,r=c),i.textContent=l.split(H.CURSOR_SENTINEL).join("")),i=n.nextNode()}if(!o||!t)return!1;try{const l=document.createRange();return l.setStart(o,r),l.collapse(!0),t.removeAllRanges(),t.addRange(l),!0}catch(l){return!1}}destroy(){var e;if(!this.isDestroyed){this.isDestroyed=!0,this.highlightTimeout&&(clearTimeout(this.highlightTimeout),this.highlightTimeout=null),this.pendingInputSnapshot=void 0,this.documentSelectionChangeHandler&&(document.removeEventListener("selectionchange",this.documentSelectionChangeHandler),this.documentSelectionChangeHandler=void 0),this.decorationRenderRaf!==null&&typeof cancelAnimationFrame=="function"&&(cancelAnimationFrame(this.decorationRenderRaf),this.decorationRenderRaf=null),(e=this.decorationMutationObserver)==null||e.disconnect(),this.decorationMutationObserver=null,this.clearInlineDecorationHighlights(!0),this.decorationLayers.clear(),this.view.clearDecorations();for(const t of this.extensions.values())t.destroy&&t.destroy();this.extensions.clear(),this.view.destroy(),this.commands.clear(),this.eventListeners.clear()}}undo(){if(this.undoStack.length===0)return;const e=this.undoStack.pop(),t=this.captureHistorySnapshot();this.pushSnapshot(this.redoStack,t);try{this.suppressHistory=!0,this.expectingProgrammaticCursor=!0,this.restoreHistorySnapshot(e),setTimeout(()=>{this.expectingProgrammaticCursor=!1},30)}finally{this.suppressHistory=!1}}redo(){if(this.redoStack.length===0)return;const e=this.redoStack.pop(),t=this.captureHistorySnapshot();this.pushSnapshot(this.undoStack,t);try{this.suppressHistory=!0,this.expectingProgrammaticCursor=!0,this.restoreHistorySnapshot(e),setTimeout(()=>{this.expectingProgrammaticCursor=!1},30)}finally{this.suppressHistory=!1}}insertTab(){if(this.config.readOnly)return;const e=" ".repeat(this.config.tabSize||2);this.replaceSelectionWithText(e)}insertNewLine(){this.config.readOnly||this.replaceSelectionWithText(`
118
+ `)}deleteBackward(){this.config.readOnly||this.deleteUsingDirection("backward")}deleteForward(){this.config.readOnly||this.deleteUsingDirection("forward")}deleteSelection(){if(this.config.readOnly)return;const e=this.textModel.getText(),{startOffset:t,endOffset:n}=this.getActiveSelectionOffsets(e),i=Math.min(t,n),o=Math.max(t,n);i!==o&&this.replaceOffsetsWithText(i,o,"")}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t)}off(e,t){if(!this.eventListeners.has(e))return;const n=this.eventListeners.get(e);if(t){const i=n.indexOf(t);i!==-1&&n.splice(i,1)}else n.length=0}normalizeRange(e){return this.comparePositions(e.start,e.end)<=0?e:{start:e.end,end:e.start}}comparePositions(e,t){return e.line!==t.line?e.line-t.line:e.column-t.column}captureHistorySnapshot(e=this.textModel.getText()){const t=this.view.getSelectionState(),n=t.isInEditor&&!t.isCollapsed?t.range:void 0,i=t.isInEditor&&t.cursor?t.cursor:void 0,o=n!=null?n:this.lastKnownSelection,r=i!=null?i:this.lastKnownCursor,a=this.clampPositionToText(r,e),l={text:e,cursorOffset:this.positionToOffsetInText(a,e)};if(o){const c=this.clampPositionToText(o.start,e),h=this.clampPositionToText(o.end,e);l.anchorOffset=this.positionToOffsetInText(c,e),l.focusOffset=this.positionToOffsetInText(h,e)}return l}restoreHistorySnapshot(e){this.setValue(e.text),requestAnimationFrame(()=>{try{if(e.anchorOffset!==void 0&&e.focusOffset!==void 0&&e.anchorOffset!==e.focusOffset){const n=Math.min(e.anchorOffset,e.focusOffset),i=Math.max(e.anchorOffset,e.focusOffset);this.setSelection({start:this.textModel.offsetToPosition(n),end:this.textModel.offsetToPosition(i)});return}this.setCursor(this.textModel.offsetToPosition(e.cursorOffset))}catch(t){}})}pushUndoSnapshot(e){this.pushSnapshot(this.undoStack,e),this.redoStack.length=0}pushSnapshot(e,t){e.push(t),e.length>100&&e.shift()}clampPositionToText(e,t){var r,a;const n=t.split(`
119
119
  `),i=Math.max(0,Math.min(e.line,n.length-1)),o=Math.max(0,Math.min(e.column,(a=(r=n[i])==null?void 0:r.length)!=null?a:0));return{line:i,column:o}}positionToOffsetInText(e,t){var r,a;const n=t.split(`
120
120
  `),i=this.clampPositionToText(e,t);let o=0;for(let l=0;l<i.line;l++)o+=((a=(r=n[l])==null?void 0:r.length)!=null?a:0)+1;return o+i.column}clearPendingHighlightRender(){this.highlightTimeout&&(clearTimeout(this.highlightTimeout),this.highlightTimeout=null)}hasRenderedFoldPlaceholders(){return!!this.view.getContentElement().querySelector("[data-lce-fold-placeholder]")}replaceSelectionWithText(e){const t=e.replace(/\r\n?/g,`
121
121
  `),n=this.textModel.getText(),{startOffset:i,endOffset:o}=this.getActiveSelectionOffsets(n),r=Math.max(0,Math.min(i,o)),a=Math.max(0,Math.max(i,o));return this.replaceOffsetsWithText(r,a,t)}insertClipboardText(e){this.pendingInputSnapshot=this.captureHistorySnapshot(),this.lastProgrammaticClipboardInsertAt=Date.now(),this.replaceSelectionWithText(this.normalizeClipboardText(e))}normalizeClipboardText(e){return e.replace(/\r\n?/g,`
@@ -126,14 +126,14 @@
126
126
  `)},r=[];return t.body.childNodes.forEach(a=>o(a,r)),r.join("").replace(/\n{3,}/g,`
127
127
 
128
128
  `).replace(/[ \t]+\n/g,`
129
- `).trimEnd()}getActiveSelectionOffsets(e){const t=this.view.getSelectionOffsets();if(t.isInEditor)return{startOffset:t.startOffset,endOffset:t.endOffset};if(this.lastKnownSelection)return{startOffset:this.positionToOffsetInText(this.lastKnownSelection.start,e),endOffset:this.positionToOffsetInText(this.lastKnownSelection.end,e)};const n=this.positionToOffsetInText(this.lastKnownCursor,e);return{startOffset:n,endOffset:n}}deleteUsingDirection(e){const t=this.textModel.getText(),{startOffset:n,endOffset:i}=this.getActiveSelectionOffsets(t),o=Math.min(n,i),r=Math.max(n,i);if(o!==r){this.replaceOffsetsWithText(o,r,"");return}if(e==="backward"){if(o===0)return;this.replaceOffsetsWithText(o-1,o,"");return}r>=t.length||this.replaceOffsetsWithText(r,r+1,"")}replaceOffsetsWithText(e,t,n){var g;this.ensureEditableSurfaceIsUnfolded();const i=n.replace(/\r\n?/g,`
130
- `),o=this.textModel.getText(),r=(g=this.pendingInputSnapshot)!=null?g:this.captureHistorySnapshot(o),a=Math.max(0,Math.min(e,o.length)),l=Math.max(0,Math.min(t,o.length)),c=Math.min(a,l),h=Math.max(a,l),u=this.textModel.replaceRange({start:this.textModel.offsetToPosition(c),end:this.textModel.offsetToPosition(h)},i);this.pendingInputSnapshot=void 0,this.suppressHistory||this.pushUndoSnapshot(r);const d=c+i.length;return this.expectingProgrammaticCursor=!0,this.renderTextWithHighlight(this.textModel.getText(),!1),this.setCursor(this.textModel.offsetToPosition(d)),setTimeout(()=>{this.expectingProgrammaticCursor=!1},20),this.emit("change",[u]),u}ensureEditableSurfaceIsUnfolded(){!this.hasRenderedFoldPlaceholders()&&this.folds.length===0||(this.clearPendingHighlightRender(),this.folds=[],this.expectingProgrammaticCursor=!0,this.renderTextWithHighlight(this.textModel.getText(),!1),setTimeout(()=>{this.expectingProgrammaticCursor=!1},20))}syncSelectionCacheFromView(){const e=this.view.getSelectionState();return e.isInEditor&&e.cursor&&(this.lastKnownCursor=e.cursor,this.lastKnownSelection=e.isCollapsed?void 0:e.range),e}isSameFoldRange(e,t){return e.start.line===t.start.line&&e.start.column===t.start.column&&e.end.line===t.end.line&&e.end.column===t.end.column}scheduleDecorationRender(){if(!this.isDestroyed){if(typeof requestAnimationFrame!="function"){this.applyDecorations();return}this.decorationRenderRaf===null&&(this.decorationRenderRaf=requestAnimationFrame(()=>{this.decorationRenderRaf=null,this.applyDecorations()}))}}applyDecorations(){if(this.isDestroyed)return;if(this.decorationLayers.size===0){this.view.clearDecorations(),this.clearInlineDecorationHighlights();return}const e=[],t=[],n=[];for(const[i,o]of this.decorationLayers.entries())for(const r of o){const a=`${i}::${r.id}`;if(r.type==="line"){e.push({...r,id:a});continue}if(r.type==="gutter"){t.push({...r,id:a});continue}n.push({...r,id:a})}this.view.setDecorations(this.normalizeLineDecorations(e),this.normalizeGutterDecorations(t)),this.renderInlineDecorations(n)}normalizeLineDecorations(e){const t=Math.max(0,this.textModel.getLineCount()-1);return e.filter(n=>Number.isFinite(n.line)).map(n=>({...n,line:Math.max(0,Math.min(t,Math.floor(n.line))),style:n.style?{...n.style}:void 0}))}normalizeGutterDecorations(e){const t=Math.max(0,this.textModel.getLineCount()-1);return e.filter(n=>Number.isFinite(n.line)).map(n=>({...n,line:Math.max(0,Math.min(t,Math.floor(n.line))),style:n.style?{...n.style}:void 0}))}renderInlineDecorations(e){if(!this.hasCustomDecorationHighlightSupport){this.clearInlineDecorationHighlights();return}const t=CSS,n=window.Highlight;if(!t.highlights||!n){this.clearInlineDecorationHighlights();return}if(this.clearInlineDecorationHighlights(),e.length===0)return;const i=this.textModel.getText(),o=[];let r=0;for(const l of e){if(r>=this.decorationHighlightLimit)break;const c=this.normalizeInlineDecoration(l,i);if(!c)continue;const h=this.view.createDomRangeFromRange(c.range);if(!h)continue;const u=this.buildInlineDecorationHighlightName(c.id);t.highlights.set(u,new n(h)),this.inlineDecorationHighlightNames.add(u),o.push(`
131
- ::highlight(${u}) {
129
+ `).trimEnd()}getActiveSelectionOffsets(e){const t=this.view.getSelectionOffsets();if(t.isInEditor)return{startOffset:t.startOffset,endOffset:t.endOffset};if(this.lastKnownSelection)return{startOffset:this.positionToOffsetInText(this.lastKnownSelection.start,e),endOffset:this.positionToOffsetInText(this.lastKnownSelection.end,e)};const n=this.positionToOffsetInText(this.lastKnownCursor,e);return{startOffset:n,endOffset:n}}deleteUsingDirection(e){const t=this.textModel.getText(),{startOffset:n,endOffset:i}=this.getActiveSelectionOffsets(t),o=Math.min(n,i),r=Math.max(n,i);if(o!==r){this.replaceOffsetsWithText(o,r,"");return}if(e==="backward"){if(o===0)return;this.replaceOffsetsWithText(o-1,o,"");return}r>=t.length||this.replaceOffsetsWithText(r,r+1,"")}replaceOffsetsWithText(e,t,n){var p;this.ensureEditableSurfaceIsUnfolded();const i=n.replace(/\r\n?/g,`
130
+ `),o=this.textModel.getText(),r=(p=this.pendingInputSnapshot)!=null?p:this.captureHistorySnapshot(o),a=Math.max(0,Math.min(e,o.length)),l=Math.max(0,Math.min(t,o.length)),c=Math.min(a,l),h=Math.max(a,l),d=this.textModel.replaceRange({start:this.textModel.offsetToPosition(c),end:this.textModel.offsetToPosition(h)},i);this.pendingInputSnapshot=void 0,this.suppressHistory||this.pushUndoSnapshot(r);const f=c+i.length;return this.expectingProgrammaticCursor=!0,this.renderTextWithHighlight(this.textModel.getText(),!1),this.setCursor(this.textModel.offsetToPosition(f)),setTimeout(()=>{this.expectingProgrammaticCursor=!1},20),this.emit("change",[d]),d}ensureEditableSurfaceIsUnfolded(){!this.hasRenderedFoldPlaceholders()&&this.folds.length===0||(this.clearPendingHighlightRender(),this.folds=[],this.expectingProgrammaticCursor=!0,this.renderTextWithHighlight(this.textModel.getText(),!1),setTimeout(()=>{this.expectingProgrammaticCursor=!1},20))}syncSelectionCacheFromView(){const e=this.view.getSelectionState();return e.isInEditor&&e.cursor&&(this.lastKnownCursor=e.cursor,this.lastKnownSelection=e.isCollapsed?void 0:e.range),e}isSameFoldRange(e,t){return e.start.line===t.start.line&&e.start.column===t.start.column&&e.end.line===t.end.line&&e.end.column===t.end.column}scheduleDecorationRender(){if(!this.isDestroyed){if(typeof requestAnimationFrame!="function"){this.applyDecorations();return}this.decorationRenderRaf===null&&(this.decorationRenderRaf=requestAnimationFrame(()=>{this.decorationRenderRaf=null,this.applyDecorations()}))}}applyDecorations(){if(this.isDestroyed)return;if(this.decorationLayers.size===0){this.view.clearDecorations(),this.clearInlineDecorationHighlights();return}const e=[],t=[],n=[];for(const[i,o]of this.decorationLayers.entries())for(const r of o){const a=`${i}::${r.id}`;if(r.type==="line"){e.push({...r,id:a});continue}if(r.type==="gutter"){t.push({...r,id:a});continue}n.push({...r,id:a})}this.view.setDecorations(this.normalizeLineDecorations(e),this.normalizeGutterDecorations(t)),this.renderInlineDecorations(n)}normalizeLineDecorations(e){const t=Math.max(0,this.textModel.getLineCount()-1);return e.filter(n=>Number.isFinite(n.line)).map(n=>({...n,line:Math.max(0,Math.min(t,Math.floor(n.line))),style:n.style?{...n.style}:void 0}))}normalizeGutterDecorations(e){const t=Math.max(0,this.textModel.getLineCount()-1);return e.filter(n=>Number.isFinite(n.line)).map(n=>({...n,line:Math.max(0,Math.min(t,Math.floor(n.line))),style:n.style?{...n.style}:void 0}))}renderInlineDecorations(e){if(!this.hasCustomDecorationHighlightSupport){this.clearInlineDecorationHighlights();return}const t=CSS,n=window.Highlight;if(!t.highlights||!n){this.clearInlineDecorationHighlights();return}if(this.clearInlineDecorationHighlights(),e.length===0)return;const i=this.textModel.getText(),o=[];let r=0;for(const l of e){if(r>=this.decorationHighlightLimit)break;const c=this.normalizeInlineDecoration(l,i);if(!c)continue;const h=this.view.createDomRangeFromRange(c.range);if(!h)continue;const d=this.buildInlineDecorationHighlightName(c.id);t.highlights.set(d,new n(h)),this.inlineDecorationHighlightNames.add(d),o.push(`
131
+ ::highlight(${d}) {
132
132
  ${this.serializeInlineDecorationStyle(c.style)}
133
133
  }
134
134
  `),r+=1}const a=this.ensureDecorationHighlightStyleNode();a.textContent=o.join(`
135
- `)}normalizeInlineDecoration(e,t){const n=this.normalizeRange({start:this.clampPositionToText(e.range.start,t),end:this.clampPositionToText(e.range.end,t)});return n.start.line===n.end.line&&n.start.column===n.end.column?null:{...e,range:n,style:e.style?{...e.style}:void 0}}clearInlineDecorationHighlights(e=!1){try{const n=CSS;if(n.highlights)for(const i of this.inlineDecorationHighlightNames)n.highlights.delete(i)}catch(n){}if(this.inlineDecorationHighlightNames.clear(),typeof document>"u")return;const t=document.getElementById(this.decorationHighlightStyleId);if(e){t!=null&&t.parentNode&&t.parentNode.removeChild(t);return}t&&(t.textContent="")}ensureDecorationHighlightStyleNode(){let e=document.getElementById(this.decorationHighlightStyleId);return e||(e=document.createElement("style"),e.id=this.decorationHighlightStyleId,document.head.appendChild(e),e)}observeDecorationRelevantMutations(){typeof MutationObserver>"u"||(this.decorationMutationObserver=new MutationObserver(()=>{this.decorationLayers.size!==0&&this.scheduleDecorationRender()}),this.decorationMutationObserver.observe(this.view.getContentElement(),{childList:!0,subtree:!0,characterData:!0}))}detectCustomHighlightSupport(){try{if(typeof CSS>"u"||typeof window>"u")return!1;const e=CSS,t=window.Highlight;return!!e.highlights&&!!t}catch(e){return!1}}buildInlineDecorationHighlightName(e){return`editora-decoration-${this.editorInstanceId}-${this.sanitizeHighlightIdentifier(e)}`}sanitizeHighlightIdentifier(e){return e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}serializeInlineDecorationStyle(e){return this.serializeStyleObject(e)||"background-color: var(--lce-inline-decoration-bg, rgba(86, 156, 214, 0.18)); border-radius: 2px;"}serializeStyleObject(e){return e?Object.entries(e).filter(([,t])=>typeof t=="string"&&t.length>0).map(([t,n])=>`${this.toKebabCase(t)}: ${n};`).join(" "):""}toKebabCase(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}cloneDecoration(e){return e.type==="inline"?{...e,range:{start:{...e.range.start},end:{...e.range.end}},style:e.style?{...e.style}:void 0}:{...e,style:e.style?{...e.style}:void 0}}};at.CURSOR_SENTINEL="";let Qn=at;class Xn{constructor(e){this.name="keymap",this.editor=null,this.keymap={},this.isMac=navigator.platform.toUpperCase().indexOf("MAC")>=0,this.keymap=e||this.getDefaultKeymap()}setup(e){this.editor=e}handleKeyDown(e){if(!this.editor)return;const t=this.findMatchingBinding(e);if(t)return this.editor.executeCommand(t.command),e.preventDefault(),e.stopPropagation(),!1}findMatchingBinding(e){const{key:t,ctrlKey:n,altKey:i,shiftKey:o,metaKey:r}=e,a=String(t).toLowerCase(),l=this.keymap[a];if(!l)return null;for(const c of l){const h=c.ctrlKey===void 0||c.ctrlKey===n,u=c.altKey===void 0||c.altKey===i,d=c.shiftKey===void 0||c.shiftKey===o,g=c.metaKey===void 0||c.metaKey===r;if(h&&u&&d&&g)return c}return null}onKeyDown(e){return this.handleKeyDown(e)}getDefaultKeymap(){const e={};return this.addBinding(e,"f",{ctrlKey:!this.isMac,metaKey:this.isMac},"find"),this.addBinding(e,"h",{ctrlKey:!this.isMac,metaKey:this.isMac},"replace"),this.addBinding(e,"f3",{},"findNext"),this.addBinding(e,"f3",{shiftKey:!0},"findPrev"),this.addBinding(e,"g",{ctrlKey:!this.isMac,metaKey:this.isMac},"findNext"),this.addBinding(e,"[",{ctrlKey:!this.isMac,metaKey:this.isMac,shiftKey:!0},"fold"),this.addBinding(e,"]",{ctrlKey:!this.isMac,metaKey:this.isMac,shiftKey:!0},"unfold"),this.addBinding(e,"s",{ctrlKey:!0},"save"),this.addBinding(e,"s",{metaKey:!0},"save"),this.addBinding(e,"z",{ctrlKey:!0},"undo"),this.addBinding(e,"z",{metaKey:!0},"undo"),this.addBinding(e,"y",{ctrlKey:!0},"redo"),this.addBinding(e,"y",{metaKey:!0},"redo"),this.addBinding(e,"z",{ctrlKey:!0,shiftKey:!0},"redo"),this.addBinding(e,"z",{metaKey:!0,shiftKey:!0},"redo"),this.addBinding(e,"tab",{},"insertTab"),this.addBinding(e,"t",{ctrlKey:!this.isMac,metaKey:this.isMac,shiftKey:!0},"toggleTheme"),this.addBinding(e,"f",{altKey:!0,shiftKey:!0},"formatDocument"),e}addBinding(e,t,n,i){const o=t.toLowerCase();e[o]||(e[o]=[]),e[o].push({key:o,command:i,...n})}setKeymap(e){this.keymap={...e}}addKeyBinding(e){const t=e.key.toLowerCase();this.keymap[t]||(this.keymap[t]=[]),this.keymap[t]=this.keymap[t].filter(n=>n.command!==e.command),this.keymap[t].push({...e,key:t})}removeKeyBinding(e,t){const n=e.toLowerCase();t?this.keymap[n]&&(this.keymap[n]=this.keymap[n].filter(i=>i.command!==t),this.keymap[n].length===0&&delete this.keymap[n]):delete this.keymap[n]}getKeymap(){return{...this.keymap}}getBindingsForCommand(e){const t=[];for(const n in this.keymap)for(const i of this.keymap[n])i.command===e&&t.push({...i});return t}getPlatformInfo(){return{isMac:this.isMac,platform:navigator.platform}}destroy(){this.keymap={},this.editor=null}}const lt=class Oe{constructor(){this.name="transaction",this.transactions=[]}setup(e){e.on("change",t=>{const n={changes:t,selection:e.getSelection(),effects:[],annotations:[]};this.transactions.push(n),this.transactions.length>Oe.MAX_TRANSACTIONS&&this.transactions.splice(0,this.transactions.length-Oe.MAX_TRANSACTIONS)})}getTransactions(){return this.transactions}destroy(){this.transactions=[]}};lt.MAX_TRANSACTIONS=200;let Yn=lt;class Jn{constructor(){this.name="line-numbers",this.editor=null,this.lineNumbersElement=null,this.isEnabled=!0}setup(e){this.editor=e,this.isEnabled=e.getConfig().lineNumbers!==!1,this.createLineNumbers(),e.registerCommand("toggleLineNumbers",()=>{this.toggle()}),e.on("change",()=>{this.updateLineNumbers()}),this.updateLineNumbers()}createLineNumbers(){if(!this.editor)return;const e=this.editor.getView(),t=e.getLineNumbersElement();t&&(this.lineNumbersElement=t,e.setLineNumbersVisible(this.isEnabled))}updateLineNumbers(){if(!this.lineNumbersElement||!this.editor||!this.isEnabled)return;const e=this.editor.getValue().split(`
136
- `).length;this.editor.getView().updateLineNumbers(e)}toggle(){this.editor&&(this.isEnabled=!this.isEnabled,this.editor.getView().setLineNumbersVisible(this.isEnabled),this.lineNumbersElement&&(this.lineNumbersElement.style.display=this.isEnabled?"table-cell":"none"),this.updateLineNumbers())}destroy(){this.lineNumbersElement=null,this.editor=null}}class ei{constructor(){this.name="theme",this.editor=null,this.currentTheme="dark"}setup(e){this.editor=e,e.registerCommand("setTheme",t=>{this.setTheme(t)}),e.registerCommand("toggleTheme",()=>{this.toggleTheme()}),this.setTheme(this.currentTheme)}setTheme(e){this.editor&&(this.currentTheme=e,this.editor.setTheme(e))}toggleTheme(){const e=this.currentTheme==="dark"?"light":"dark";this.setTheme(e)}getCurrentTheme(){return this.currentTheme}destroy(){this.editor=null}}class ti{constructor(){this.name="read-only",this.editor=null,this.isReadOnly=!1}setup(e){this.editor=e,e.registerCommand("setReadOnly",t=>{this.setReadOnly(t)}),e.registerCommand("toggleReadOnly",()=>{this.toggleReadOnly()}),e.on("keydown",t=>{if(t.ctrlKey&&t.key==="r")return t.preventDefault(),this.toggleReadOnly(),!1})}setReadOnly(e){this.editor&&(this.isReadOnly=e,this.editor.setReadOnly(e))}toggleReadOnly(){this.setReadOnly(!this.isReadOnly)}isCurrentlyReadOnly(){return this.isReadOnly}destroy(){this.editor=null}}let ni=0;const ct=class y{constructor(e={}){this.name="search",this.editor=null,this.searchUI=null,this.isVisible=!1,this.currentResults=[],this.currentIndex=-1,this.searchDebounceTimer=null,this.liveRefreshTimer=null,this.statusResetTimer=null,this.statusFreezeUntil=0,this.findInput=null,this.replaceInputEl=null,this.statusDiv=null,this.modeDiv=null,this.caseSensitiveInput=null,this.wholeWordInput=null,this.regexInput=null,this.currentQuery="",this.savedCursor=null,this.editorChangeHandler=null,this.searchOptions={caseSensitive:!1,wholeWord:!1,regex:!1},this.trailingMarkerAttr="data-lce-trailing-newline-marker",this.editorContainerSelector='[data-lce-editor-container="true"]',this.highlightId=++ni,this.highlightMatchName=`editora-search-match-${this.highlightId}`,this.highlightActiveName=`editora-search-active-${this.highlightId}`,this.highlightStyleId=`editora-search-highlight-style-${this.highlightId}`,this.maxCustomHighlightRanges=2e3,this.virtualMarkerRegex=/[\u200B\uE000]/,this.hasCustomHighlightSupport=!1,this.config={replaceAndFindNext:!0,...e}}setup(e){this.editor=e,this.hasCustomHighlightSupport=this.detectCustomHighlightSupport(),this.hasCustomHighlightSupport&&this.ensureHighlightStyles(),e.registerCommand("find",()=>{this.showSearch()}),e.registerCommand("findNext",()=>{this.findNext()}),e.registerCommand("findPrev",()=>{this.findPrev()}),e.registerCommand("replace",()=>{this.showReplace()}),e.registerCommand("replaceAll",(t,n)=>{this.replaceAll(t,n)}),this.editorChangeHandler=()=>{!this.isVisible||!this.currentQuery||this.scheduleLiveRefresh(!0)},e.on("change",this.editorChangeHandler)}showSearch(){this.editor&&(this.searchUI||this.createSearchUI(),this.isVisible||this.captureSelectionState(),this.isVisible=!0,this.searchUI&&(this.searchUI.style.display="block",this.updateModeHint(!1),this.findInput&&(this.findInput.focus(),this.findInput.select())),this.currentQuery&&this.performSearch(this.currentQuery,!0,!1))}showReplace(){this.showSearch(),this.replaceInputEl&&(this.replaceInputEl.style.display="block",this.replaceInputEl.focus()),this.updateModeHint(!0),this.currentQuery&&this.performSearch(this.currentQuery,!1,!0)}hideSearch(){this.isVisible=!1,this.searchUI&&(this.searchUI.style.display="none"),this.replaceInputEl&&(this.replaceInputEl.style.display="none",this.replaceInputEl.value=""),this.updateModeHint(!1),this.clearHighlights(),this.restoreSelectionState()}createSearchUI(){if(!this.editor)return;const e=this.editor.getView().getContentElement(),t=e.closest(this.editorContainerSelector),n=t==null?void 0:t.parentElement,i=e.closest(".rte-source-editor-modal")||n||t||e.parentElement;if(!i)return;window.getComputedStyle(i).position==="static"&&(i.style.position="relative"),this.searchUI=document.createElement("div"),this.searchUI.className=y.css.root,this.searchUI.style.display="none",this.searchUI.innerHTML=`
135
+ `)}normalizeInlineDecoration(e,t){const n=this.normalizeRange({start:this.clampPositionToText(e.range.start,t),end:this.clampPositionToText(e.range.end,t)});return n.start.line===n.end.line&&n.start.column===n.end.column?null:{...e,range:n,style:e.style?{...e.style}:void 0}}clearInlineDecorationHighlights(e=!1){try{const n=CSS;if(n.highlights)for(const i of this.inlineDecorationHighlightNames)n.highlights.delete(i)}catch(n){}if(this.inlineDecorationHighlightNames.clear(),typeof document=="undefined")return;const t=document.getElementById(this.decorationHighlightStyleId);if(e){t!=null&&t.parentNode&&t.parentNode.removeChild(t);return}t&&(t.textContent="")}ensureDecorationHighlightStyleNode(){let e=document.getElementById(this.decorationHighlightStyleId);return e||(e=document.createElement("style"),e.id=this.decorationHighlightStyleId,document.head.appendChild(e),e)}observeDecorationRelevantMutations(){typeof MutationObserver!="undefined"&&(this.decorationMutationObserver=new MutationObserver(()=>{this.decorationLayers.size!==0&&this.scheduleDecorationRender()}),this.decorationMutationObserver.observe(this.view.getContentElement(),{childList:!0,subtree:!0,characterData:!0}))}detectCustomHighlightSupport(){try{if(typeof CSS=="undefined"||typeof window=="undefined")return!1;const e=CSS,t=window.Highlight;return!!e.highlights&&!!t}catch(e){return!1}}buildInlineDecorationHighlightName(e){return`editora-decoration-${this.editorInstanceId}-${this.sanitizeHighlightIdentifier(e)}`}sanitizeHighlightIdentifier(e){return e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}serializeInlineDecorationStyle(e){const t=this.serializeStyleObject(e);return t||"background-color: var(--lce-inline-decoration-bg, rgba(86, 156, 214, 0.18)); border-radius: 2px;"}serializeStyleObject(e){return e?Object.entries(e).filter(([,t])=>typeof t=="string"&&t.length>0).map(([t,n])=>`${this.toKebabCase(t)}: ${n};`).join(" "):""}toKebabCase(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}cloneDecoration(e){return e.type==="inline"?{...e,range:{start:{...e.range.start},end:{...e.range.end}},style:e.style?{...e.style}:void 0}:{...e,style:e.style?{...e.style}:void 0}}};H.CURSOR_SENTINEL="";let ve=H;class Qn{constructor(e){this.name="keymap",this.editor=null,this.keymap={},this.isMac=navigator.platform.toUpperCase().indexOf("MAC")>=0,this.keymap=e||this.getDefaultKeymap()}setup(e){this.editor=e}handleKeyDown(e){if(!this.editor)return;const t=this.findMatchingBinding(e);if(t)return this.editor.executeCommand(t.command),e.preventDefault(),e.stopPropagation(),!1}findMatchingBinding(e){const{key:t,ctrlKey:n,altKey:i,shiftKey:o,metaKey:r}=e,a=String(t).toLowerCase(),l=this.keymap[a];if(!l)return null;for(const c of l){const h=c.ctrlKey===void 0||c.ctrlKey===n,d=c.altKey===void 0||c.altKey===i,f=c.shiftKey===void 0||c.shiftKey===o,p=c.metaKey===void 0||c.metaKey===r;if(h&&d&&f&&p)return c}return null}onKeyDown(e){return this.handleKeyDown(e)}getDefaultKeymap(){const e={};return this.addBinding(e,"f",{ctrlKey:!this.isMac,metaKey:this.isMac},"find"),this.addBinding(e,"h",{ctrlKey:!this.isMac,metaKey:this.isMac},"replace"),this.addBinding(e,"f3",{},"findNext"),this.addBinding(e,"f3",{shiftKey:!0},"findPrev"),this.addBinding(e,"g",{ctrlKey:!this.isMac,metaKey:this.isMac},"findNext"),this.addBinding(e,"[",{ctrlKey:!this.isMac,metaKey:this.isMac,shiftKey:!0},"fold"),this.addBinding(e,"]",{ctrlKey:!this.isMac,metaKey:this.isMac,shiftKey:!0},"unfold"),this.addBinding(e,"s",{ctrlKey:!0},"save"),this.addBinding(e,"s",{metaKey:!0},"save"),this.addBinding(e,"z",{ctrlKey:!0},"undo"),this.addBinding(e,"z",{metaKey:!0},"undo"),this.addBinding(e,"y",{ctrlKey:!0},"redo"),this.addBinding(e,"y",{metaKey:!0},"redo"),this.addBinding(e,"z",{ctrlKey:!0,shiftKey:!0},"redo"),this.addBinding(e,"z",{metaKey:!0,shiftKey:!0},"redo"),this.addBinding(e,"tab",{},"insertTab"),this.addBinding(e,"t",{ctrlKey:!this.isMac,metaKey:this.isMac,shiftKey:!0},"toggleTheme"),this.addBinding(e,"f",{altKey:!0,shiftKey:!0},"formatDocument"),e}addBinding(e,t,n,i){const o=t.toLowerCase();e[o]||(e[o]=[]),e[o].push({key:o,command:i,...n})}setKeymap(e){this.keymap={...e}}addKeyBinding(e){const t=e.key.toLowerCase();this.keymap[t]||(this.keymap[t]=[]),this.keymap[t]=this.keymap[t].filter(n=>n.command!==e.command),this.keymap[t].push({...e,key:t})}removeKeyBinding(e,t){const n=e.toLowerCase();t?this.keymap[n]&&(this.keymap[n]=this.keymap[n].filter(i=>i.command!==t),this.keymap[n].length===0&&delete this.keymap[n]):delete this.keymap[n]}getKeymap(){return{...this.keymap}}getBindingsForCommand(e){const t=[];for(const n in this.keymap)for(const i of this.keymap[n])i.command===e&&t.push({...i});return t}getPlatformInfo(){return{isMac:this.isMac,platform:navigator.platform}}destroy(){this.keymap={},this.editor=null}}const Z=class Z{constructor(){this.name="transaction",this.transactions=[]}setup(e){e.on("change",t=>{const n={changes:t,selection:e.getSelection(),effects:[],annotations:[]};this.transactions.push(n),this.transactions.length>Z.MAX_TRANSACTIONS&&this.transactions.splice(0,this.transactions.length-Z.MAX_TRANSACTIONS)})}getTransactions(){return this.transactions}destroy(){this.transactions=[]}};Z.MAX_TRANSACTIONS=200;let xe=Z;class Xn{constructor(){this.name="line-numbers",this.editor=null,this.lineNumbersElement=null,this.isEnabled=!0}setup(e){this.editor=e,this.isEnabled=e.getConfig().lineNumbers!==!1,this.createLineNumbers(),e.registerCommand("toggleLineNumbers",()=>{this.toggle()}),e.on("change",()=>{this.updateLineNumbers()}),this.updateLineNumbers()}createLineNumbers(){if(!this.editor)return;const e=this.editor.getView(),t=e.getLineNumbersElement();t&&(this.lineNumbersElement=t,e.setLineNumbersVisible(this.isEnabled))}updateLineNumbers(){if(!this.lineNumbersElement||!this.editor||!this.isEnabled)return;const e=this.editor.getValue().split(`
136
+ `).length;this.editor.getView().updateLineNumbers(e)}toggle(){this.editor&&(this.isEnabled=!this.isEnabled,this.editor.getView().setLineNumbersVisible(this.isEnabled),this.lineNumbersElement&&(this.lineNumbersElement.style.display=this.isEnabled?"table-cell":"none"),this.updateLineNumbers())}destroy(){this.lineNumbersElement=null,this.editor=null}}class Yn{constructor(){this.name="theme",this.editor=null,this.currentTheme="dark"}setup(e){this.editor=e,e.registerCommand("setTheme",t=>{this.setTheme(t)}),e.registerCommand("toggleTheme",()=>{this.toggleTheme()}),this.setTheme(this.currentTheme)}setTheme(e){this.editor&&(this.currentTheme=e,this.editor.setTheme(e))}toggleTheme(){const e=this.currentTheme==="dark"?"light":"dark";this.setTheme(e)}getCurrentTheme(){return this.currentTheme}destroy(){this.editor=null}}class Jn{constructor(){this.name="read-only",this.editor=null,this.isReadOnly=!1}setup(e){this.editor=e,e.registerCommand("setReadOnly",t=>{this.setReadOnly(t)}),e.registerCommand("toggleReadOnly",()=>{this.toggleReadOnly()}),e.on("keydown",t=>{if(t.ctrlKey&&t.key==="r")return t.preventDefault(),this.toggleReadOnly(),!1})}setReadOnly(e){this.editor&&(this.isReadOnly=e,this.editor.setReadOnly(e))}toggleReadOnly(){this.setReadOnly(!this.isReadOnly)}isCurrentlyReadOnly(){return this.isReadOnly}destroy(){this.editor=null}}let ei=0;const y=class y{constructor(e={}){this.name="search",this.editor=null,this.searchUI=null,this.isVisible=!1,this.currentResults=[],this.currentIndex=-1,this.searchDebounceTimer=null,this.liveRefreshTimer=null,this.statusResetTimer=null,this.statusFreezeUntil=0,this.findInput=null,this.replaceInputEl=null,this.statusDiv=null,this.modeDiv=null,this.caseSensitiveInput=null,this.wholeWordInput=null,this.regexInput=null,this.currentQuery="",this.savedCursor=null,this.editorChangeHandler=null,this.searchOptions={caseSensitive:!1,wholeWord:!1,regex:!1},this.trailingMarkerAttr="data-lce-trailing-newline-marker",this.editorContainerSelector='[data-lce-editor-container="true"]',this.highlightId=++ei,this.highlightMatchName=`editora-search-match-${this.highlightId}`,this.highlightActiveName=`editora-search-active-${this.highlightId}`,this.highlightStyleId=`editora-search-highlight-style-${this.highlightId}`,this.maxCustomHighlightRanges=2e3,this.virtualMarkerRegex=/[\u200B\uE000]/,this.hasCustomHighlightSupport=!1,this.config={replaceAndFindNext:!0,...e}}setup(e){this.editor=e,this.hasCustomHighlightSupport=this.detectCustomHighlightSupport(),this.hasCustomHighlightSupport&&this.ensureHighlightStyles(),e.registerCommand("find",()=>{this.showSearch()}),e.registerCommand("findNext",()=>{this.findNext()}),e.registerCommand("findPrev",()=>{this.findPrev()}),e.registerCommand("replace",()=>{this.showReplace()}),e.registerCommand("replaceAll",(t,n)=>{this.replaceAll(t,n)}),this.editorChangeHandler=()=>{!this.isVisible||!this.currentQuery||this.scheduleLiveRefresh(!0)},e.on("change",this.editorChangeHandler)}showSearch(){this.editor&&(this.searchUI||this.createSearchUI(),this.isVisible||this.captureSelectionState(),this.isVisible=!0,this.searchUI&&(this.searchUI.style.display="block",this.updateModeHint(!1),this.findInput&&(this.findInput.focus(),this.findInput.select())),this.currentQuery&&this.performSearch(this.currentQuery,!0,!1))}showReplace(){this.showSearch(),this.replaceInputEl&&(this.replaceInputEl.style.display="block",this.replaceInputEl.focus()),this.updateModeHint(!0),this.currentQuery&&this.performSearch(this.currentQuery,!1,!0)}hideSearch(){this.isVisible=!1,this.searchUI&&(this.searchUI.style.display="none"),this.replaceInputEl&&(this.replaceInputEl.style.display="none",this.replaceInputEl.value=""),this.updateModeHint(!1),this.clearHighlights(),this.restoreSelectionState()}createSearchUI(){if(!this.editor)return;const e=this.editor.getView().getContentElement(),t=e.closest(this.editorContainerSelector),n=t==null?void 0:t.parentElement,i=e.closest(".rte-source-editor-modal")||n||t||e.parentElement;if(!i)return;window.getComputedStyle(i).position==="static"&&(i.style.position="relative"),this.searchUI=document.createElement("div"),this.searchUI.className=y.css.root,this.searchUI.style.display="none",this.searchUI.innerHTML=`
137
137
  <div class="${y.css.row}">
138
138
  <input type="text" class="${y.css.findInput} ${y.css.inputBase}" placeholder="Find..." />
139
139
  <button class="${y.css.prevButton} ${y.css.buttonBase}" type="button" aria-label="Previous match">↑</button>
@@ -159,11 +159,11 @@
159
159
  <div class="${y.css.mode} ${y.css.modeLayout}" aria-live="polite"></div>
160
160
  </div>
161
161
  <input type="text" class="${y.css.replaceInput} ${y.css.inputBase} ${y.css.replaceInputLayout}" placeholder="Replace with..." />
162
- `;const o=this.searchUI.querySelector(`.${y.css.findInput}`),r=this.searchUI.querySelector(`.${y.css.replaceInput}`),a=this.searchUI.querySelector(`.${y.css.prevButton}`),l=this.searchUI.querySelector(`.${y.css.nextButton}`),c=this.searchUI.querySelector(`.${y.css.closeButton}`),h=this.searchUI.querySelector(`.${y.css.status}`),u=this.searchUI.querySelector(`.${y.css.mode}`),d=this.searchUI.querySelector(`.${y.css.caseSensitive}`),g=this.searchUI.querySelector(`.${y.css.wholeWord}`),f=this.searchUI.querySelector(`.${y.css.regex}`);this.findInput=o,this.replaceInputEl=r,this.statusDiv=h,this.modeDiv=u,this.caseSensitiveInput=d,this.wholeWordInput=g,this.regexInput=f,d.checked=!!this.searchOptions.caseSensitive,g.checked=!!this.searchOptions.wholeWord,f.checked=!!this.searchOptions.regex,o.addEventListener("input",()=>{this.searchDebounceTimer&&clearTimeout(this.searchDebounceTimer);const m=o.value;this.searchDebounceTimer=setTimeout(()=>{this.performSearch(m,!1,!1)},120)});const p=()=>{this.searchOptions.caseSensitive=d.checked,this.searchOptions.wholeWord=g.checked,this.searchOptions.regex=f.checked;const m=o.value;m.trim()?this.performSearch(m,!1,!1):this.performSearch("",!1,!1)};d.addEventListener("change",p),g.addEventListener("change",p),f.addEventListener("change",p),o.addEventListener("keydown",m=>{m.key==="Enter"?(m.preventDefault(),m.shiftKey?this.findPrev():this.findNext()):m.key==="Escape"&&(m.preventDefault(),this.hideSearch())}),r.addEventListener("keydown",m=>{m.key==="Enter"?(m.preventDefault(),m.shiftKey?this.replaceAll(o.value,r.value):this.replaceCurrent(o.value,r.value)):m.key==="Escape"&&(m.preventDefault(),this.hideSearch())}),a.addEventListener("click",()=>this.findPrev()),l.addEventListener("click",()=>this.findNext()),c.addEventListener("click",()=>this.hideSearch()),i.appendChild(this.searchUI)}updateModeHint(e){this.modeDiv&&(this.modeDiv.textContent=e?`Replace: move next ${this.config.replaceAndFindNext?"ON":"OFF"}`:"Find mode")}performSearch(e,t,n){if(!this.editor||!e.trim()){this.currentQuery="",this.currentResults=[],this.currentIndex=-1,this.clearHighlights(),this.updateStatus("");return}if(this.searchOptions.regex&&!this.isValidRegex(e)){this.currentQuery=e,this.currentResults=[],this.currentIndex=-1,this.clearHighlights(),this.updateStatus("Invalid regular expression");return}this.currentQuery=e;const i=this.currentIndex,o=this.editor.search(e,this.searchOptions);if(this.currentResults=o,o.length===0){this.currentIndex=-1,this.clearHighlights(),this.updateStatus("No matches");return}t&&i>=0?this.currentIndex=Math.min(i,o.length-1):this.currentIndex=0,this.updateHighlights(n)}findNext(){if(this.currentResults.length===0){this.currentQuery&&this.performSearch(this.currentQuery,!0,!0);return}this.currentIndex=(this.currentIndex+1)%this.currentResults.length,this.updateHighlights(!0)}findPrev(){if(this.currentResults.length===0){this.currentQuery&&this.performSearch(this.currentQuery,!0,!0);return}this.currentIndex=this.currentIndex<=0?this.currentResults.length-1:this.currentIndex-1,this.updateHighlights(!0)}replaceCurrent(e,t){if(!this.editor||!e.trim()||((this.currentQuery!==e||this.currentResults.length===0)&&this.performSearch(e,!1,!0),this.currentIndex<0||this.currentResults.length===0))return;const n=this.currentResults[this.currentIndex];if(!n)return;const i=this.computeReplacementRange(n.range.start,t);if(this.editor.replace(n.range,t),this.config.replaceAndFindNext){this.currentQuery=e;const o=this.editor.search(e,this.searchOptions);if(this.currentResults=o,o.length===0){this.currentIndex=-1,this.clearHighlights(),this.updateStatus("Replaced current occurrence"),this.restoreReplaceInputFocus();return}this.currentIndex=this.findNextResultIndexAfter(i.end,o),this.updateHighlights(!0)}else this.scrollLogicalRangeIntoView(i,!0),this.performSearch(e,!0,!1);this.currentResults.length>0||this.showTransientStatus("Replaced current occurrence"),this.restoreReplaceInputFocus(),this.revealActiveResultAfterFocusRestore()}replaceAll(e,t){if(!this.editor||!e.trim())return;const n=this.editor.replaceAll(e,t,this.searchOptions);this.performSearch(e,!1,!1),this.showTransientStatus(`Replaced ${n} occurrence${n===1?"":"s"}`),this.restoreReplaceInputFocus(),this.revealActiveResultAfterFocusRestore()}updateHighlights(e){if(this.clearHighlights(),this.currentResults.length===0||this.currentIndex===-1||!this.editor)return;this.applyCustomHighlights();const t=this.currentResults[this.currentIndex];t&&((e||!this.hasCustomHighlightSupport)&&this.navigateToResult(t,!this.hasCustomHighlightSupport),this.updateStatus(`${this.currentResults.length} matches (showing ${this.currentIndex+1}/${this.currentResults.length})`))}navigateToResult(e,t){if(!this.editor)return;const n=document.activeElement,i=!!n&&(n===this.findInput||n===this.replaceInputEl);t?(this.editor.setSelection(e.range),this.centerCurrentSelectionInView()):this.scrollResultIntoView(e);const o=this.editor.getView();t&&typeof o.ensureCaretVisible=="function"&&o.ensureCaretVisible(),t&&i&&n&&requestAnimationFrame(()=>{this.focusWithoutScrolling(n)})}clearHighlights(){var e,t;if(this.hasCustomHighlightSupport)try{const n=CSS;(e=n.highlights)==null||e.delete(this.highlightMatchName),(t=n.highlights)==null||t.delete(this.highlightActiveName)}catch(n){}}scrollResultIntoView(e){this.scrollLogicalRangeIntoView(e.range,!0)}scrollLogicalRangeIntoView(e,t){if(!this.editor)return;const n=this.editor.getView().getContentElement(),i=this.editor.getValue(),{lineStarts:o,lines:r}=this.buildLineStarts(i),a=this.buildTextNodeIndex(n);if(a.length===0)return;const l=this.toDomRange(e,o,r,a);if(!l)return;const c=l.startContainer.nodeType===Node.TEXT_NODE?l.startContainer.parentElement:l.startContainer,h=this.resolveScrollContainer(n);if(h){const u=l.getClientRects()[0]||l.getBoundingClientRect(),d=h.getBoundingClientRect(),g=h.scrollTop+(u.top-d.top)-d.height/2+u.height/2,f=18;let p=t?g:h.scrollTop,m=h.scrollLeft;const b=h.scrollLeft+(u.left-d.left),x=b+u.width;u.right>d.right-f?m=x-d.width+f:u.left<d.left+f&&(m=Math.max(0,b-f));const C=Math.max(0,h.scrollHeight-h.clientHeight),w=Math.max(0,h.scrollWidth-h.clientWidth);if(p=Math.min(C,Math.max(0,p)),m=Math.min(w,Math.max(0,m)),C===0&&w===0){c==null||c.scrollIntoView({block:t?"center":"nearest",inline:"nearest",behavior:"smooth"});return}(p!==h.scrollTop||m!==h.scrollLeft)&&h.scrollTo({top:p,left:m,behavior:"smooth"});return}c==null||c.scrollIntoView({block:t?"center":"nearest",inline:"nearest",behavior:"smooth"})}restoreReplaceInputFocus(){const e=this.replaceInputEl;!e||e.style.display==="none"||requestAnimationFrame(()=>{this.focusWithoutScrolling(e);const t=e.value.length;try{e.setSelectionRange(t,t)}catch(n){}})}centerCurrentSelectionInView(){if(!this.editor)return;const e=this.editor.getView().getContentElement(),t=this.resolveScrollContainer(e);if(!t)return;const n=window.getSelection();if(!n||n.rangeCount===0)return;const i=n.getRangeAt(0).cloneRange(),o=i.getClientRects()[0]||i.getBoundingClientRect();if(!o)return;const r=t.getBoundingClientRect(),a=t.scrollTop+(o.top-r.top)-r.height/2+o.height/2,l=Math.max(0,t.scrollHeight-t.clientHeight),c=Math.min(l,Math.max(0,a));c!==t.scrollTop&&t.scrollTo({top:c,behavior:"smooth"})}computeReplacementRange(e,t){const n=t.replace(/\r\n?/g,`
162
+ `;const o=this.searchUI.querySelector(`.${y.css.findInput}`),r=this.searchUI.querySelector(`.${y.css.replaceInput}`),a=this.searchUI.querySelector(`.${y.css.prevButton}`),l=this.searchUI.querySelector(`.${y.css.nextButton}`),c=this.searchUI.querySelector(`.${y.css.closeButton}`),h=this.searchUI.querySelector(`.${y.css.status}`),d=this.searchUI.querySelector(`.${y.css.mode}`),f=this.searchUI.querySelector(`.${y.css.caseSensitive}`),p=this.searchUI.querySelector(`.${y.css.wholeWord}`),u=this.searchUI.querySelector(`.${y.css.regex}`);this.findInput=o,this.replaceInputEl=r,this.statusDiv=h,this.modeDiv=d,this.caseSensitiveInput=f,this.wholeWordInput=p,this.regexInput=u,f.checked=!!this.searchOptions.caseSensitive,p.checked=!!this.searchOptions.wholeWord,u.checked=!!this.searchOptions.regex,o.addEventListener("input",()=>{this.searchDebounceTimer&&clearTimeout(this.searchDebounceTimer);const m=o.value;this.searchDebounceTimer=setTimeout(()=>{this.performSearch(m,!1,!1)},120)});const g=()=>{this.searchOptions.caseSensitive=f.checked,this.searchOptions.wholeWord=p.checked,this.searchOptions.regex=u.checked;const m=o.value;m.trim()?this.performSearch(m,!1,!1):this.performSearch("",!1,!1)};f.addEventListener("change",g),p.addEventListener("change",g),u.addEventListener("change",g),o.addEventListener("keydown",m=>{m.key==="Enter"?(m.preventDefault(),m.shiftKey?this.findPrev():this.findNext()):m.key==="Escape"&&(m.preventDefault(),this.hideSearch())}),r.addEventListener("keydown",m=>{m.key==="Enter"?(m.preventDefault(),m.shiftKey?this.replaceAll(o.value,r.value):this.replaceCurrent(o.value,r.value)):m.key==="Escape"&&(m.preventDefault(),this.hideSearch())}),a.addEventListener("click",()=>this.findPrev()),l.addEventListener("click",()=>this.findNext()),c.addEventListener("click",()=>this.hideSearch()),i.appendChild(this.searchUI)}updateModeHint(e){this.modeDiv&&(this.modeDiv.textContent=e?`Replace: move next ${this.config.replaceAndFindNext?"ON":"OFF"}`:"Find mode")}performSearch(e,t,n){if(!this.editor||!e.trim()){this.currentQuery="",this.currentResults=[],this.currentIndex=-1,this.clearHighlights(),this.updateStatus("");return}if(this.searchOptions.regex&&!this.isValidRegex(e)){this.currentQuery=e,this.currentResults=[],this.currentIndex=-1,this.clearHighlights(),this.updateStatus("Invalid regular expression");return}this.currentQuery=e;const i=this.currentIndex,o=this.editor.search(e,this.searchOptions);if(this.currentResults=o,o.length===0){this.currentIndex=-1,this.clearHighlights(),this.updateStatus("No matches");return}t&&i>=0?this.currentIndex=Math.min(i,o.length-1):this.currentIndex=0,this.updateHighlights(n)}findNext(){if(this.currentResults.length===0){this.currentQuery&&this.performSearch(this.currentQuery,!0,!0);return}this.currentIndex=(this.currentIndex+1)%this.currentResults.length,this.updateHighlights(!0)}findPrev(){if(this.currentResults.length===0){this.currentQuery&&this.performSearch(this.currentQuery,!0,!0);return}this.currentIndex=this.currentIndex<=0?this.currentResults.length-1:this.currentIndex-1,this.updateHighlights(!0)}replaceCurrent(e,t){if(!this.editor||!e.trim()||((this.currentQuery!==e||this.currentResults.length===0)&&this.performSearch(e,!1,!0),this.currentIndex<0||this.currentResults.length===0))return;const n=this.currentResults[this.currentIndex];if(!n)return;const i=this.computeReplacementRange(n.range.start,t);if(this.editor.replace(n.range,t),this.config.replaceAndFindNext){this.currentQuery=e;const o=this.editor.search(e,this.searchOptions);if(this.currentResults=o,o.length===0){this.currentIndex=-1,this.clearHighlights(),this.updateStatus("Replaced current occurrence"),this.restoreReplaceInputFocus();return}this.currentIndex=this.findNextResultIndexAfter(i.end,o),this.updateHighlights(!0)}else this.scrollLogicalRangeIntoView(i,!0),this.performSearch(e,!0,!1);this.currentResults.length>0||this.showTransientStatus("Replaced current occurrence"),this.restoreReplaceInputFocus(),this.revealActiveResultAfterFocusRestore()}replaceAll(e,t){if(!this.editor||!e.trim())return;const n=this.editor.replaceAll(e,t,this.searchOptions);this.performSearch(e,!1,!1),this.showTransientStatus(`Replaced ${n} occurrence${n===1?"":"s"}`),this.restoreReplaceInputFocus(),this.revealActiveResultAfterFocusRestore()}updateHighlights(e){if(this.clearHighlights(),this.currentResults.length===0||this.currentIndex===-1||!this.editor)return;this.applyCustomHighlights();const t=this.currentResults[this.currentIndex];t&&((e||!this.hasCustomHighlightSupport)&&this.navigateToResult(t,!this.hasCustomHighlightSupport),this.updateStatus(`${this.currentResults.length} matches (showing ${this.currentIndex+1}/${this.currentResults.length})`))}navigateToResult(e,t){if(!this.editor)return;const n=document.activeElement,i=!!n&&(n===this.findInput||n===this.replaceInputEl);t?(this.editor.setSelection(e.range),this.centerCurrentSelectionInView()):this.scrollResultIntoView(e);const o=this.editor.getView();t&&typeof o.ensureCaretVisible=="function"&&o.ensureCaretVisible(),t&&i&&n&&requestAnimationFrame(()=>{this.focusWithoutScrolling(n)})}clearHighlights(){var e,t;if(this.hasCustomHighlightSupport)try{const n=CSS;(e=n.highlights)==null||e.delete(this.highlightMatchName),(t=n.highlights)==null||t.delete(this.highlightActiveName)}catch(n){}}scrollResultIntoView(e){this.scrollLogicalRangeIntoView(e.range,!0)}scrollLogicalRangeIntoView(e,t){if(!this.editor)return;const n=this.editor.getView().getContentElement(),i=this.editor.getValue(),{lineStarts:o,lines:r}=this.buildLineStarts(i),a=this.buildTextNodeIndex(n);if(a.length===0)return;const l=this.toDomRange(e,o,r,a);if(!l)return;const c=l.startContainer.nodeType===Node.TEXT_NODE?l.startContainer.parentElement:l.startContainer,h=this.resolveScrollContainer(n);if(h){const d=l.getClientRects()[0]||l.getBoundingClientRect(),f=h.getBoundingClientRect(),u=h.scrollTop+(d.top-f.top)-f.height/2+d.height/2,g=18;let m=t?u:h.scrollTop,b=h.scrollLeft;const v=h.scrollLeft+(d.left-f.left),C=v+d.width;d.right>f.right-g?b=C-f.width+g:d.left<f.left+g&&(b=Math.max(0,v-g));const w=Math.max(0,h.scrollHeight-h.clientHeight),E=Math.max(0,h.scrollWidth-h.clientWidth);if(m=Math.min(w,Math.max(0,m)),b=Math.min(E,Math.max(0,b)),w===0&&E===0){c==null||c.scrollIntoView({block:t?"center":"nearest",inline:"nearest",behavior:"smooth"});return}(m!==h.scrollTop||b!==h.scrollLeft)&&h.scrollTo({top:m,left:b,behavior:"smooth"});return}c==null||c.scrollIntoView({block:t?"center":"nearest",inline:"nearest",behavior:"smooth"})}restoreReplaceInputFocus(){const e=this.replaceInputEl;!e||e.style.display==="none"||requestAnimationFrame(()=>{this.focusWithoutScrolling(e);const t=e.value.length;try{e.setSelectionRange(t,t)}catch(n){}})}centerCurrentSelectionInView(){if(!this.editor)return;const e=this.editor.getView().getContentElement(),t=this.resolveScrollContainer(e);if(!t)return;const n=window.getSelection();if(!n||n.rangeCount===0)return;const i=n.getRangeAt(0).cloneRange(),o=i.getClientRects()[0]||i.getBoundingClientRect();if(!o)return;const r=t.getBoundingClientRect(),l=t.scrollTop+(o.top-r.top)-r.height/2+o.height/2,c=Math.max(0,t.scrollHeight-t.clientHeight),h=Math.min(c,Math.max(0,l));h!==t.scrollTop&&t.scrollTo({top:h,behavior:"smooth"})}computeReplacementRange(e,t){const n=t.replace(/\r\n?/g,`
163
163
  `),i=n.split(`
164
164
  `);let o;return i.length<=1?(o={start:e,end:{line:e.line,column:e.column+n.length}},this.clampRangeToDocument(o)):(o={start:e,end:{line:e.line+i.length-1,column:i[i.length-1].length}},this.clampRangeToDocument(o))}findNextResultIndexAfter(e,t){for(let n=0;n<t.length;n++)if(this.comparePositions(t[n].range.start,e)>=0)return n;return 0}comparePositions(e,t){return e.line!==t.line?e.line-t.line:e.column-t.column}clampRangeToDocument(e){var c,h;const t=this.editor;if(!t)return e;const n=t.getValue().split(`
165
- `),i=Math.max(0,n.length-1),o=Math.max(0,Math.min(e.start.line,i)),r=Math.max(0,Math.min(e.end.line,i)),a=Math.max(0,Math.min(e.start.column,((c=n[o])==null?void 0:c.length)||0)),l=Math.max(0,Math.min(e.end.column,((h=n[r])==null?void 0:h.length)||0));return{start:{line:o,column:a},end:{line:r,column:l}}}focusWithoutScrolling(e){try{e.focus({preventScroll:!0})}catch(t){const n=[];let i=e.parentElement;for(;i;)this.canScroll(i)&&n.push({el:i,top:i.scrollTop,left:i.scrollLeft}),i=i.parentElement;const o=window.scrollX,r=window.scrollY;e.focus();for(let a=0;a<n.length;a++){const l=n[a];l.el.scrollTop=l.top,l.el.scrollLeft=l.left}window.scrollTo(o,r)}}findScrollContainer(e){let t=e;for(;t;){const n=window.getComputedStyle(t).overflowY;if((n==="auto"||n==="scroll")&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement}return null}resolveScrollContainer(e){var n,i,o;const t=((o=(i=(n=this.editor)==null?void 0:n.getView())==null?void 0:i.getScrollElement)==null?void 0:o.call(i))||null;return t&&this.canScroll(t)?t:this.findScrollContainer(e)}canScroll(e){return e.scrollHeight>e.clientHeight||e.scrollWidth>e.clientWidth}revealActiveResultAfterFocusRestore(){!this.currentResults.length||this.currentIndex<0||requestAnimationFrame(()=>{const e=this.currentResults[this.currentIndex];e&&this.scrollResultIntoView(e)})}applyCustomHighlights(){if(!this.editor||!this.hasCustomHighlightSupport||this.currentResults.length===0)return;const e=this.editor.getView().getContentElement(),t=this.editor.getValue(),{lineStarts:n,lines:i}=this.buildLineStarts(t),o=this.buildTextNodeIndex(e);if(o.length===0)return;const r=this.buildVisibleDocumentText(o),a=[];let l=null;const c=Math.min(this.currentResults.length,this.maxCustomHighlightRanges);for(let h=0;h<c;h++){const u=this.currentResults[h],d=this.searchOptions.regex?u.match||this.currentQuery:this.currentQuery||u.match,g=this.toDomRange(u.range,n,i,o,r,d);g&&(a.push(g),h===this.currentIndex&&(l=g))}if(a.length!==0)try{const h=CSS,u=window.Highlight;if(!h.highlights||!u)return;h.highlights.set(this.highlightMatchName,new u(...a)),l&&h.highlights.set(this.highlightActiveName,new u(l))}catch(h){}}buildLineStarts(e){const t=e.split(`
166
- `),n=new Array(t.length);let i=0;for(let o=0;o<t.length;o++)n[o]=i,i+=t[o].length+1;return{lineStarts:n,lines:t}}positionToOffset(e,t,n){var r;const i=Math.max(0,Math.min(e.line,n.length-1)),o=Math.max(0,Math.min(e.column,((r=n[i])==null?void 0:r.length)||0));return t[i]+o}buildTextNodeIndex(e){var r;const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),n=[];let i=0,o;for(;o=t.nextNode();){const a=o;if((r=a.parentElement)!=null&&r.hasAttribute(this.trailingMarkerAttr))continue;const l=a.textContent||"",c=this.buildVisibleToDomMap(l),h=Math.max(0,c.length-1);h===0&&l.length===0||(n.push({node:a,start:i,end:i+h,visibleToDom:c}),i+=h)}return n}resolveDomPoint(e,t){var o,r,a,l,c,h;const n=Math.max(0,e);for(let u=0;u<t.length;u++){const d=t[u];if(n<=d.end){const g=Math.max(0,n-d.start),f=(a=(r=d.visibleToDom[g])!=null?r:(o=d.node.textContent)==null?void 0:o.length)!=null?a:0;return{node:d.node,offset:f}}}const i=t[t.length-1];return i?{node:i.node,offset:(h=(c=i.visibleToDom[i.visibleToDom.length-1])!=null?c:(l=i.node.textContent)==null?void 0:l.length)!=null?h:0}:null}toDomRange(e,t,n,i,o,r){const a=this.positionToOffset(e.start,t,n),l=this.positionToOffset(e.end,t,n);let c=Math.min(a,l),h=Math.max(a,l);if(o&&r){const f=r,p=o.slice(c,h);if(p.length===f.length&&p.toLowerCase()!==f.toLowerCase()){const m=this.findNearestMatchOffset(o,f,c);m!==-1&&(c=m,h=m+f.length)}}const u=this.resolveDomPoint(c,i),d=this.resolveDomPoint(h,i);if(!u||!d)return null;const g=document.createRange();try{return g.setStart(u.node,u.offset),g.setEnd(d.node,d.offset),g}catch(f){return null}}buildVisibleDocumentText(e){let t="";for(let n=0;n<e.length;n++){const i=e[n].node.textContent||"";for(let o=0;o<i.length;o++){const r=i[o];this.virtualMarkerRegex.test(r)||(t+=r)}}return t}findNearestMatchOffset(e,t,n){const i=t.toLowerCase();let o=e.toLowerCase().indexOf(i);if(o===-1)return-1;let r=o,a=Math.abs(o-n);for(;o!==-1;){const l=Math.abs(o-n);if(l<a&&(a=l,r=o),l===0)return o;o=e.toLowerCase().indexOf(i,o+1)}return r}scheduleLiveRefresh(e){this.liveRefreshTimer&&clearTimeout(this.liveRefreshTimer);const t=this.currentQuery;this.liveRefreshTimer=setTimeout(()=>{!this.isVisible||!t||this.performSearch(t,e,!1)},90)}updateStatus(e,t=!1){if(this.statusDiv){if(!t&&Date.now()<this.statusFreezeUntil)return;this.statusDiv.textContent=e}}showTransientStatus(e,t=900){this.statusFreezeUntil=Date.now()+t,this.updateStatus(e,!0),this.statusResetTimer&&clearTimeout(this.statusResetTimer),this.statusResetTimer=setTimeout(()=>{this.statusFreezeUntil=0,this.syncMatchStatus()},t)}syncMatchStatus(){if(!this.currentQuery){this.updateStatus("",!0);return}if(this.currentResults.length===0||this.currentIndex<0){this.updateStatus("No matches",!0);return}this.updateStatus(`${this.currentResults.length} matches (showing ${this.currentIndex+1}/${this.currentResults.length})`,!0)}isValidRegex(e){try{const t=this.searchOptions.caseSensitive?"g":"gi";return new RegExp(e,t),!0}catch(t){return!1}}captureSelectionState(){this.editor&&(this.savedSelection=this.editor.getSelection(),this.savedCursor=this.editor.getCursor().position)}restoreSelectionState(){this.editor&&(this.savedSelection?this.editor.setSelection(this.savedSelection):this.savedCursor&&this.editor.setCursor(this.savedCursor),this.savedSelection=void 0,this.savedCursor=null)}detectCustomHighlightSupport(){try{const e=CSS,t=window.Highlight;return!!e.highlights&&!!t}catch(e){return!1}}buildVisibleToDomMap(e){const t=[0];let n=0;for(let i=0;i<e.length;i++){const o=e[i];this.virtualMarkerRegex.test(o)||(n+=1,t[n]=i+1)}return t}ensureHighlightStyles(){if(document.getElementById(this.highlightStyleId))return;const e=document.createElement("style");e.id=this.highlightStyleId,e.textContent=`
165
+ `),i=Math.max(0,n.length-1),o=Math.max(0,Math.min(e.start.line,i)),r=Math.max(0,Math.min(e.end.line,i)),a=Math.max(0,Math.min(e.start.column,((c=n[o])==null?void 0:c.length)||0)),l=Math.max(0,Math.min(e.end.column,((h=n[r])==null?void 0:h.length)||0));return{start:{line:o,column:a},end:{line:r,column:l}}}focusWithoutScrolling(e){try{e.focus({preventScroll:!0})}catch(t){const n=[];let i=e.parentElement;for(;i;)this.canScroll(i)&&n.push({el:i,top:i.scrollTop,left:i.scrollLeft}),i=i.parentElement;const o=window.scrollX,r=window.scrollY;e.focus();for(let a=0;a<n.length;a++){const l=n[a];l.el.scrollTop=l.top,l.el.scrollLeft=l.left}window.scrollTo(o,r)}}findScrollContainer(e){let t=e;for(;t;){const i=window.getComputedStyle(t).overflowY;if((i==="auto"||i==="scroll")&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement}return null}resolveScrollContainer(e){var i,o;const t=(i=this.editor)==null?void 0:i.getView(),n=((o=t==null?void 0:t.getScrollElement)==null?void 0:o.call(t))||null;return n&&this.canScroll(n)?n:this.findScrollContainer(e)}canScroll(e){return e.scrollHeight>e.clientHeight||e.scrollWidth>e.clientWidth}revealActiveResultAfterFocusRestore(){!this.currentResults.length||this.currentIndex<0||requestAnimationFrame(()=>{const e=this.currentResults[this.currentIndex];e&&this.scrollResultIntoView(e)})}applyCustomHighlights(){if(!this.editor||!this.hasCustomHighlightSupport||this.currentResults.length===0)return;const e=this.editor.getView().getContentElement(),t=this.editor.getValue(),{lineStarts:n,lines:i}=this.buildLineStarts(t),o=this.buildTextNodeIndex(e);if(o.length===0)return;const r=this.buildVisibleDocumentText(o),a=[];let l=null;const c=Math.min(this.currentResults.length,this.maxCustomHighlightRanges);for(let h=0;h<c;h++){const d=this.currentResults[h],f=this.searchOptions.regex?d.match||this.currentQuery:this.currentQuery||d.match,p=this.toDomRange(d.range,n,i,o,r,f);p&&(a.push(p),h===this.currentIndex&&(l=p))}if(a.length!==0)try{const h=CSS,d=window.Highlight;if(!h.highlights||!d)return;h.highlights.set(this.highlightMatchName,new d(...a)),l&&h.highlights.set(this.highlightActiveName,new d(l))}catch(h){}}buildLineStarts(e){const t=e.split(`
166
+ `),n=new Array(t.length);let i=0;for(let o=0;o<t.length;o++)n[o]=i,i+=t[o].length+1;return{lineStarts:n,lines:t}}positionToOffset(e,t,n){var r;const i=Math.max(0,Math.min(e.line,n.length-1)),o=Math.max(0,Math.min(e.column,((r=n[i])==null?void 0:r.length)||0));return t[i]+o}buildTextNodeIndex(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),n=[];let i=0,o;for(;o=t.nextNode();){const r=o,a=r.parentElement;if(a!=null&&a.hasAttribute(this.trailingMarkerAttr))continue;const l=r.textContent||"",c=this.buildVisibleToDomMap(l),h=Math.max(0,c.length-1);h===0&&l.length===0||(n.push({node:r,start:i,end:i+h,visibleToDom:c}),i+=h)}return n}resolveDomPoint(e,t){var o,r,a,l,c,h;const n=Math.max(0,e);for(let d=0;d<t.length;d++){const f=t[d];if(n<=f.end){const p=Math.max(0,n-f.start),u=(a=(r=f.visibleToDom[p])!=null?r:(o=f.node.textContent)==null?void 0:o.length)!=null?a:0;return{node:f.node,offset:u}}}const i=t[t.length-1];return i?{node:i.node,offset:(h=(c=i.visibleToDom[i.visibleToDom.length-1])!=null?c:(l=i.node.textContent)==null?void 0:l.length)!=null?h:0}:null}toDomRange(e,t,n,i,o,r){const a=this.positionToOffset(e.start,t,n),l=this.positionToOffset(e.end,t,n);let c=Math.min(a,l),h=Math.max(a,l);if(o&&r){const u=r,g=o.slice(c,h);if(g.length===u.length&&g.toLowerCase()!==u.toLowerCase()){const m=this.findNearestMatchOffset(o,u,c);m!==-1&&(c=m,h=m+u.length)}}const d=this.resolveDomPoint(c,i),f=this.resolveDomPoint(h,i);if(!d||!f)return null;const p=document.createRange();try{return p.setStart(d.node,d.offset),p.setEnd(f.node,f.offset),p}catch(u){return null}}buildVisibleDocumentText(e){let t="";for(let n=0;n<e.length;n++){const i=e[n].node.textContent||"";for(let o=0;o<i.length;o++){const r=i[o];this.virtualMarkerRegex.test(r)||(t+=r)}}return t}findNearestMatchOffset(e,t,n){const i=t.toLowerCase();let o=e.toLowerCase().indexOf(i);if(o===-1)return-1;let r=o,a=Math.abs(o-n);for(;o!==-1;){const l=Math.abs(o-n);if(l<a&&(a=l,r=o),l===0)return o;o=e.toLowerCase().indexOf(i,o+1)}return r}scheduleLiveRefresh(e){this.liveRefreshTimer&&clearTimeout(this.liveRefreshTimer);const t=this.currentQuery;this.liveRefreshTimer=setTimeout(()=>{!this.isVisible||!t||this.performSearch(t,e,!1)},90)}updateStatus(e,t=!1){if(this.statusDiv){if(!t&&Date.now()<this.statusFreezeUntil)return;this.statusDiv.textContent=e}}showTransientStatus(e,t=900){this.statusFreezeUntil=Date.now()+t,this.updateStatus(e,!0),this.statusResetTimer&&clearTimeout(this.statusResetTimer),this.statusResetTimer=setTimeout(()=>{this.statusFreezeUntil=0,this.syncMatchStatus()},t)}syncMatchStatus(){if(!this.currentQuery){this.updateStatus("",!0);return}if(this.currentResults.length===0||this.currentIndex<0){this.updateStatus("No matches",!0);return}this.updateStatus(`${this.currentResults.length} matches (showing ${this.currentIndex+1}/${this.currentResults.length})`,!0)}isValidRegex(e){try{const t=this.searchOptions.caseSensitive?"g":"gi";return new RegExp(e,t),!0}catch(t){return!1}}captureSelectionState(){this.editor&&(this.savedSelection=this.editor.getSelection(),this.savedCursor=this.editor.getCursor().position)}restoreSelectionState(){this.editor&&(this.savedSelection?this.editor.setSelection(this.savedSelection):this.savedCursor&&this.editor.setCursor(this.savedCursor),this.savedSelection=void 0,this.savedCursor=null)}detectCustomHighlightSupport(){try{const e=CSS,t=window.Highlight;return!!e.highlights&&!!t}catch(e){return!1}}buildVisibleToDomMap(e){const t=[0];let n=0;for(let i=0;i<e.length;i++){const o=e[i];this.virtualMarkerRegex.test(o)||(n+=1,t[n]=i+1)}return t}ensureHighlightStyles(){if(document.getElementById(this.highlightStyleId))return;const e=document.createElement("style");e.id=this.highlightStyleId,e.textContent=`
167
167
  ::highlight(${this.highlightMatchName}) {
168
168
  background: var(--lce-search-match-bg, rgba(255, 214, 10, 0.34));
169
169
  border-radius: 2px;
@@ -172,14 +172,14 @@
172
172
  background: var(--lce-search-active-bg, rgba(255, 154, 0, 0.45));
173
173
  border-radius: 2px;
174
174
  }
175
- `,document.head.appendChild(e)}destroy(){this.searchDebounceTimer&&(clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=null),this.liveRefreshTimer&&(clearTimeout(this.liveRefreshTimer),this.liveRefreshTimer=null),this.statusResetTimer&&(clearTimeout(this.statusResetTimer),this.statusResetTimer=null),this.clearHighlights(),this.searchUI&&this.searchUI.parentNode&&this.searchUI.parentNode.removeChild(this.searchUI),this.editor&&this.editorChangeHandler&&this.editor.off("change",this.editorChangeHandler),this.editorChangeHandler=null,this.findInput=null,this.replaceInputEl=null,this.statusDiv=null,this.modeDiv=null,this.caseSensitiveInput=null,this.wholeWordInput=null,this.regexInput=null,this.searchUI=null;const e=document.getElementById(this.highlightStyleId);e!=null&&e.parentNode&&e.parentNode.removeChild(e),this.editor=null}};ct.css={root:"lce-search-ui",row:"lce-search-row",options:"lce-search-options",optionLabel:"lce-search-option",optionInput:"lce-search-option-input",caseSensitive:"search-case-sensitive",wholeWord:"search-whole-word",regex:"search-regex",meta:"lce-search-meta",findInput:"search-find-input",replaceInput:"search-replace-input",inputBase:"lce-search-input",replaceInputLayout:"lce-search-replace",prevButton:"search-prev",nextButton:"search-next",closeButton:"search-close",buttonBase:"lce-search-btn",status:"search-status",statusLayout:"lce-search-status",mode:"search-mode",modeLayout:"lce-search-mode"};let ii=ct,oi=0;class ri{constructor(){this.name="bracket-matching",this.editor=null,this.bracketPairs={"(":")","[":"]","{":"}","<":">"},this.reverseBracketPairs={")":"(","]":"[","}":"{",">":"<"},this.highlightId=++oi,this.highlightName=`editora-bracket-match-${this.highlightId}`,this.highlightStyleId=`editora-bracket-match-style-${this.highlightId}`,this.currentMatch=null,this.hasCustomHighlightSupport=!1,this.observer=null,this.pendingUpdateRaf=null,this.updateRequestVersion=0,this.cursorHandler=null,this.changeHandler=null}setup(e){this.editor=e,this.hasCustomHighlightSupport=this.detectCustomHighlightSupport(),this.hasCustomHighlightSupport&&(this.ensureHighlightStyles(),this.observeContentMutations()),this.cursorHandler=()=>{this.scheduleBracketUpdate()},this.changeHandler=()=>{this.scheduleBracketUpdate()},e.on("cursor",this.cursorHandler),e.on("change",this.changeHandler),this.scheduleBracketUpdate()}scheduleBracketUpdate(){this.updateRequestVersion+=1;const e=this.updateRequestVersion;this.pendingUpdateRaf!==null&&typeof cancelAnimationFrame=="function"&&(cancelAnimationFrame(this.pendingUpdateRaf),this.pendingUpdateRaf=null);const t=()=>{e===this.updateRequestVersion&&(this.pendingUpdateRaf=null,this.updateBracketMatching())};if(typeof requestAnimationFrame=="function"){this.pendingUpdateRaf=requestAnimationFrame(()=>{this.pendingUpdateRaf=requestAnimationFrame(t)});return}t()}updateBracketMatching(){if(!this.editor)return;const e=this.editor.getCursor(),t=this.editor.getValue();this.clearBracketHighlighting();const n=this.getBracketNearPosition(t,e.position);if(!n)return;const i=this.findMatchingBracket(t,n);i&&(this.currentMatch=i,this.highlightBrackets(i))}getBracketNearPosition(e,t){const n=e.split(`
175
+ `,document.head.appendChild(e)}destroy(){this.searchDebounceTimer&&(clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=null),this.liveRefreshTimer&&(clearTimeout(this.liveRefreshTimer),this.liveRefreshTimer=null),this.statusResetTimer&&(clearTimeout(this.statusResetTimer),this.statusResetTimer=null),this.clearHighlights(),this.searchUI&&this.searchUI.parentNode&&this.searchUI.parentNode.removeChild(this.searchUI),this.editor&&this.editorChangeHandler&&this.editor.off("change",this.editorChangeHandler),this.editorChangeHandler=null,this.findInput=null,this.replaceInputEl=null,this.statusDiv=null,this.modeDiv=null,this.caseSensitiveInput=null,this.wholeWordInput=null,this.regexInput=null,this.searchUI=null;const e=document.getElementById(this.highlightStyleId);e!=null&&e.parentNode&&e.parentNode.removeChild(e),this.editor=null}};y.css={root:"lce-search-ui",row:"lce-search-row",options:"lce-search-options",optionLabel:"lce-search-option",optionInput:"lce-search-option-input",caseSensitive:"search-case-sensitive",wholeWord:"search-whole-word",regex:"search-regex",meta:"lce-search-meta",findInput:"search-find-input",replaceInput:"search-replace-input",inputBase:"lce-search-input",replaceInputLayout:"lce-search-replace",prevButton:"search-prev",nextButton:"search-next",closeButton:"search-close",buttonBase:"lce-search-btn",status:"search-status",statusLayout:"lce-search-status",mode:"search-mode",modeLayout:"lce-search-mode"};let we=y,ti=0;class ni{constructor(){this.name="bracket-matching",this.editor=null,this.bracketPairs={"(":")","[":"]","{":"}","<":">"},this.reverseBracketPairs={")":"(","]":"[","}":"{",">":"<"},this.highlightId=++ti,this.highlightName=`editora-bracket-match-${this.highlightId}`,this.highlightStyleId=`editora-bracket-match-style-${this.highlightId}`,this.currentMatch=null,this.hasCustomHighlightSupport=!1,this.observer=null,this.pendingUpdateRaf=null,this.updateRequestVersion=0,this.cursorHandler=null,this.changeHandler=null}setup(e){this.editor=e,this.hasCustomHighlightSupport=this.detectCustomHighlightSupport(),this.hasCustomHighlightSupport&&(this.ensureHighlightStyles(),this.observeContentMutations()),this.cursorHandler=()=>{this.scheduleBracketUpdate()},this.changeHandler=()=>{this.scheduleBracketUpdate()},e.on("cursor",this.cursorHandler),e.on("change",this.changeHandler),this.scheduleBracketUpdate()}scheduleBracketUpdate(){this.updateRequestVersion+=1;const e=this.updateRequestVersion;this.pendingUpdateRaf!==null&&typeof cancelAnimationFrame=="function"&&(cancelAnimationFrame(this.pendingUpdateRaf),this.pendingUpdateRaf=null);const t=()=>{e===this.updateRequestVersion&&(this.pendingUpdateRaf=null,this.updateBracketMatching())};if(typeof requestAnimationFrame=="function"){this.pendingUpdateRaf=requestAnimationFrame(()=>{this.pendingUpdateRaf=requestAnimationFrame(t)});return}t()}updateBracketMatching(){if(!this.editor)return;const e=this.editor.getCursor(),t=this.editor.getValue();this.clearBracketHighlighting();const n=this.getBracketNearPosition(t,e.position);if(!n)return;const i=this.findMatchingBracket(t,n);i&&(this.currentMatch=i,this.highlightBrackets(i))}getBracketNearPosition(e,t){const n=e.split(`
176
176
  `);if(t.line<0||t.line>=n.length)return null;const i=[{line:t.line,column:t.column}];t.column>0&&i.push({line:t.line,column:t.column-1});for(const o of i){const r=this.getBracketAtPosition(n,o);if(r)return r}return null}getBracketAtPosition(e,t){if(t.line<0||t.line>=e.length)return null;const n=e[t.line];if(t.column<0||t.column>=n.length)return null;const i=n[t.column];return this.bracketPairs[i]||this.reverseBracketPairs[i]?{char:i,position:t}:null}findMatchingBracket(e,t){const n=e.split(`
177
- `),i=t.position.line,o=t.position.column,r=t.char;return this.bracketPairs[r]?this.findClosingBracket(n,i,o,r):this.reverseBracketPairs[r]?this.findOpeningBracket(n,i,o,r):null}findClosingBracket(e,t,n,i){const o=this.bracketPairs[i];let r=0;for(let a=t;a<e.length;a++){const l=e[a],c=a===t?n:0;for(let h=c;h<l.length;h++){const u=l[h];if(u===i)r++;else if(u===o&&(r--,r===0))return{open:{start:{line:t,column:n},end:{line:t,column:n+1}},close:{start:{line:a,column:h},end:{line:a,column:h+1}},type:i}}}return null}findOpeningBracket(e,t,n,i){const o=this.reverseBracketPairs[i];let r=0;for(let a=t;a>=0;a--){const l=e[a],c=a===t?n:l.length-1;for(let h=c;h>=0;h--){const u=l[h];if(u===i)r++;else if(u===o&&(r--,r===0))return{open:{start:{line:a,column:h},end:{line:a,column:h+1}},close:{start:{line:t,column:n},end:{line:t,column:n+1}},type:o}}}return null}highlightBrackets(e){if(!this.editor||!this.hasCustomHighlightSupport)return;const t=this.editor.getView(),n=t.createDomRangeFromRange(e.open),i=t.createDomRangeFromRange(e.close);if(!(!n||!i))try{const o=CSS,r=window.Highlight;if(!o.highlights||!r)return;o.highlights.set(this.highlightName,new r(n,i))}catch(o){}}clearBracketHighlighting(){var e;if(this.currentMatch=null,!!this.hasCustomHighlightSupport)try{(e=CSS.highlights)==null||e.delete(this.highlightName)}catch(t){}}observeContentMutations(){if(!this.editor||typeof MutationObserver>"u")return;const e=this.editor.getView().getContentElement();this.observer=new MutationObserver(()=>{this.clearBracketHighlighting(),this.scheduleBracketUpdate()}),this.observer.observe(e,{childList:!0,subtree:!0,characterData:!0})}detectCustomHighlightSupport(){try{if(typeof CSS>"u"||typeof window>"u")return!1;const e=CSS,t=window.Highlight;return!!e.highlights&&!!t}catch(e){return!1}}ensureHighlightStyles(){if(typeof document>"u"||document.getElementById(this.highlightStyleId))return;const e=document.createElement("style");e.id=this.highlightStyleId,e.textContent=`
177
+ `),i=t.position.line,o=t.position.column,r=t.char;return this.bracketPairs[r]?this.findClosingBracket(n,i,o,r):this.reverseBracketPairs[r]?this.findOpeningBracket(n,i,o,r):null}findClosingBracket(e,t,n,i){const o=this.bracketPairs[i];let r=0;for(let a=t;a<e.length;a++){const l=e[a],c=a===t?n:0;for(let h=c;h<l.length;h++){const d=l[h];if(d===i)r++;else if(d===o&&(r--,r===0))return{open:{start:{line:t,column:n},end:{line:t,column:n+1}},close:{start:{line:a,column:h},end:{line:a,column:h+1}},type:i}}}return null}findOpeningBracket(e,t,n,i){const o=this.reverseBracketPairs[i];let r=0;for(let a=t;a>=0;a--){const l=e[a],c=a===t?n:l.length-1;for(let h=c;h>=0;h--){const d=l[h];if(d===i)r++;else if(d===o&&(r--,r===0))return{open:{start:{line:a,column:h},end:{line:a,column:h+1}},close:{start:{line:t,column:n},end:{line:t,column:n+1}},type:o}}}return null}highlightBrackets(e){if(!this.editor||!this.hasCustomHighlightSupport)return;const t=this.editor.getView(),n=t.createDomRangeFromRange(e.open),i=t.createDomRangeFromRange(e.close);if(!(!n||!i))try{const o=CSS,r=window.Highlight;if(!o.highlights||!r)return;o.highlights.set(this.highlightName,new r(n,i))}catch(o){}}clearBracketHighlighting(){var e;if(this.currentMatch=null,!!this.hasCustomHighlightSupport)try{(e=CSS.highlights)==null||e.delete(this.highlightName)}catch(t){}}observeContentMutations(){if(!this.editor||typeof MutationObserver=="undefined")return;const e=this.editor.getView().getContentElement();this.observer=new MutationObserver(()=>{this.clearBracketHighlighting(),this.scheduleBracketUpdate()}),this.observer.observe(e,{childList:!0,subtree:!0,characterData:!0})}detectCustomHighlightSupport(){try{if(typeof CSS=="undefined"||typeof window=="undefined")return!1;const e=CSS,t=window.Highlight;return!!e.highlights&&!!t}catch(e){return!1}}ensureHighlightStyles(){if(typeof document=="undefined"||document.getElementById(this.highlightStyleId))return;const e=document.createElement("style");e.id=this.highlightStyleId,e.textContent=`
178
178
  ::highlight(${this.highlightName}) {
179
179
  background-color: var(--lce-bracket-match-bg, rgba(86, 156, 214, 0.4));
180
180
  text-decoration: underline solid var(--lce-bracket-match-border, rgba(156, 220, 254, 0.95)) 2px;
181
181
  }
182
- `,document.head.appendChild(e)}getCurrentMatch(){return this.currentMatch}destroy(){var e;if(this.pendingUpdateRaf!==null&&typeof cancelAnimationFrame=="function"&&(cancelAnimationFrame(this.pendingUpdateRaf),this.pendingUpdateRaf=null),this.clearBracketHighlighting(),(e=this.observer)==null||e.disconnect(),this.observer=null,this.editor&&this.cursorHandler&&this.editor.off("cursor",this.cursorHandler),this.editor&&this.changeHandler&&this.editor.off("change",this.changeHandler),typeof document<"u"){const t=document.getElementById(this.highlightStyleId);t!=null&&t.parentNode&&t.parentNode.removeChild(t)}this.cursorHandler=null,this.changeHandler=null,this.editor=null}}class si{constructor(){this.name="code-folding",this.lineHeight=21,this.voidMarkupTags=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),this.nonFoldableInlineMarkupTags=new Set(["a","abbr","b","bdi","bdo","button","cite","code","data","del","dfn","em","i","ins","kbd","label","mark","output","q","ruby","s","samp","small","span","strong","sub","sup","time","u","var"]),this.rawTextMarkupTags=new Set(["script","style","textarea","title"]),this.editor=null,this.foldingUI=null,this.pendingUpdateRaf=null,this.lastSnapshot="",this.lastParsedText=null,this.changeHandler=null,this.foldRegions=[],this.foldSnapshots=new Map,this.isDisplayingFolded=!1,this.cachedLineInfo=null}setup(e){this.editor=e,e.registerCommand("fold",()=>{this.foldAtCursor()}),e.registerCommand("unfold",()=>{this.unfoldAtCursor()}),e.registerCommand("foldAll",()=>{this.foldAll()}),e.registerCommand("unfoldAll",()=>{this.unfoldAll()}),this.changeHandler=()=>{this.syncFoldingState()},e.on("change",this.changeHandler),this.createFoldingUI(),this.syncFoldingState()}onKeyDown(e){}onMouseDown(e){}createFoldingUI(){if(!this.editor)return;const e=this.editor.getView().getLineNumbersElement();e&&(this.foldingUI=document.createElement("div"),this.foldingUI.setAttribute("data-lce-folding-ui","true"),this.foldingUI.style.cssText=`
182
+ `,document.head.appendChild(e)}getCurrentMatch(){return this.currentMatch}destroy(){var e;if(this.pendingUpdateRaf!==null&&typeof cancelAnimationFrame=="function"&&(cancelAnimationFrame(this.pendingUpdateRaf),this.pendingUpdateRaf=null),this.clearBracketHighlighting(),(e=this.observer)==null||e.disconnect(),this.observer=null,this.editor&&this.cursorHandler&&this.editor.off("cursor",this.cursorHandler),this.editor&&this.changeHandler&&this.editor.off("change",this.changeHandler),typeof document!="undefined"){const t=document.getElementById(this.highlightStyleId);t!=null&&t.parentNode&&t.parentNode.removeChild(t)}this.cursorHandler=null,this.changeHandler=null,this.editor=null}}class ii{constructor(){this.name="code-folding",this.lineHeight=21,this.voidMarkupTags=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),this.nonFoldableInlineMarkupTags=new Set(["a","abbr","b","bdi","bdo","button","cite","code","data","del","dfn","em","i","ins","kbd","label","mark","output","q","ruby","s","samp","small","span","strong","sub","sup","time","u","var"]),this.rawTextMarkupTags=new Set(["script","style","textarea","title"]),this.editor=null,this.foldingUI=null,this.pendingUpdateRaf=null,this.lastSnapshot="",this.lastParsedText=null,this.changeHandler=null,this.foldRegions=[],this.foldSnapshots=new Map,this.isDisplayingFolded=!1,this.cachedLineInfo=null}setup(e){this.editor=e,e.registerCommand("fold",()=>{this.foldAtCursor()}),e.registerCommand("unfold",()=>{this.unfoldAtCursor()}),e.registerCommand("foldAll",()=>{this.foldAll()}),e.registerCommand("unfoldAll",()=>{this.unfoldAll()}),this.changeHandler=()=>{this.syncFoldingState()},e.on("change",this.changeHandler),this.createFoldingUI(),this.syncFoldingState()}onKeyDown(e){}onMouseDown(e){}createFoldingUI(){if(!this.editor)return;const e=this.editor.getView().getLineNumbersElement();e&&(this.foldingUI=document.createElement("div"),this.foldingUI.setAttribute("data-lce-folding-ui","true"),this.foldingUI.style.cssText=`
183
183
  position: absolute;
184
184
  right: 0;
185
185
  top: 0;
@@ -188,7 +188,7 @@
188
188
  pointer-events: none;
189
189
  z-index: 3;
190
190
  `,e.appendChild(this.foldingUI))}syncFoldingState(){if(!this.editor)return;const e=this.editor.getValue(),t=this.foldSnapshots;e!==this.lastParsedText&&(this.foldRegions=this.buildFoldRegions(e),this.pruneInvalidFolds(e,t),this.lastParsedText=e),this.hasActiveFolds()?this.applyFoldedDisplay():this.restoreFullDisplay(),this.rememberActiveFoldSnapshots(e),this.scheduleFoldIndicatorUpdate()}scheduleFoldIndicatorUpdate(){this.pendingUpdateRaf===null&&(this.pendingUpdateRaf=requestAnimationFrame(()=>{this.pendingUpdateRaf=null,this.updateFoldIndicators()}))}updateFoldIndicators(){if(!this.editor||!this.foldingUI)return;const e=this.editor.getValue(),t=this.getActiveFolds().map(r=>this.getFoldKey(r)).join("|"),n=`${e}::${t}`;if(n===this.lastSnapshot)return;this.lastSnapshot=n,this.foldingUI.innerHTML="";const i=this.getRenderableActiveFolds(),o=document.createDocumentFragment();for(const r of this.foldRegions){const a=this.toDisplayLine(r,i);if(a===null)continue;const l=this.isFoldActive(r),c=this.createFoldIndicator(r,a,l);o.appendChild(c)}this.foldingUI.appendChild(o)}buildFoldRegions(e){const t=this.buildBracketFoldRegions(e),n=this.shouldIncludeMarkupFolds(e)?this.buildMarkupFoldRegions(e):[];return this.mergeFoldRegions([...t,...n])}buildBracketFoldRegions(e){var a;const t=e.split(`
191
- `),n=[],i=[],o={"{":"}","[":"]","(":")"},r={"}":"{","]":"[",")":"("};for(let l=0;l<t.length;l++){const c=t[l];for(let h=0;h<c.length;h++){const u=c[h];if(o[u]){n.push({char:u,line:l,column:h});continue}const d=r[u];if(!d)continue;let g=-1;for(let b=n.length-1;b>=0;b--)if(n[b].char===d){g=b;break}if(g===-1)continue;const f=n.splice(g,1)[0];if(f.line>=l)continue;const p=((a=t[f.line])==null?void 0:a.length)||0,m={start:{line:f.line,column:p},end:{line:l,column:0},collapsed:!1,level:g};this.isValidFoldRegion(m)&&i.push(m)}}return i.sort((l,c)=>l.start.line!==c.start.line?l.start.line-c.start.line:l.end.line!==c.end.line?l.end.line-c.end.line:l.start.column-c.start.column),i}shouldIncludeMarkupFolds(e){return/<!DOCTYPE\b/i.test(e)||/<[A-Za-z][\w:-]*(?:\s|>)/.test(e)&&/<\/[A-Za-z][\w:-]*\s*>/.test(e)}buildMarkupFoldRegions(e){const{lineStarts:t,lines:n}=this.buildLineStarts(e),i=[],o=[];let r=0;for(;r<e.length;){if(e[r]!=="<"){r+=1;continue}if(e.startsWith("<!--",r)){const l=e.indexOf("-->",r+4);r=l===-1?e.length:l+3;continue}if(e.startsWith("<![CDATA[",r)){const l=e.indexOf("]]>",r+9);r=l===-1?e.length:l+3;continue}const a=this.parseMarkupTag(e,r,t,n);if(!a){r+=1;continue}if(r=a.endOffset,a.isClosing){const l=o.findIndex(u=>u.name===a.name);if(l===-1)continue;const c=o.splice(l,1)[0],h=this.createMarkupFoldRegion(c.openEndLine,a.startLine,n);h&&i.push(h);continue}if(!(a.isSelfClosing||this.voidMarkupTags.has(a.name))){if(this.rawTextMarkupTags.has(a.name)){const l=this.findClosingMarkupTag(e,a.endOffset,a.name,t,n);if(l){const c=this.createMarkupFoldRegion(a.endLine,l.startLine,n);c&&i.push(c),r=l.endOffset}continue}this.nonFoldableInlineMarkupTags.has(a.name)||o.unshift({name:a.name,openEndLine:a.endLine})}}return i}parseMarkupTag(e,t,n,i){if(e[t]!=="<")return null;const o=e[t+1];if(!o||o!=="/"&&!/[A-Za-z]/.test(o))return null;const r=o==="/";let a=t+(r?2:1);const l=a;for(;a<e.length&&/[A-Za-z0-9:-]/.test(e[a]);)a+=1;const c=a;if(a===l)return null;let h=null;for(;a<e.length;){const p=e[a];if(h){p===h&&(h=null),a+=1;continue}if(p==='"'||p==="'"){h=p,a+=1;continue}if(p===">")break;a+=1}if(a>=e.length||e[a]!==">")return null;const u=e.slice(l,c).toLowerCase();if(!u)return null;const d=e.slice(t,a+1),g=this.offsetToLine(t,n,i),f=this.offsetToLine(a,n,i);return{name:u,isClosing:r,isSelfClosing:!r&&/\/\s*>$/.test(d),startLine:g,endLine:f,endOffset:a+1}}findClosingMarkupTag(e,t,n,i,o){const r=`</${n}`,a=e.toLowerCase();let l=a.indexOf(r,t);for(;l!==-1;){const c=this.parseMarkupTag(e,l,i,o);if(c&&c.isClosing&&c.name===n)return{startLine:c.startLine,endOffset:c.endOffset};l=a.indexOf(r,l+r.length)}return null}createMarkupFoldRegion(e,t,n){var a;if(e>=t)return null;const i=Math.max(0,Math.min(e,n.length-1)),o=Math.max(0,Math.min(t,n.length-1)),r={start:{line:i,column:((a=n[i])==null?void 0:a.length)||0},end:{line:o,column:0},collapsed:!1,level:0};return this.isValidFoldRegion(r)?r:null}mergeFoldRegions(e){const t=new Map;for(const n of e)this.isValidFoldRegion(n)&&t.set(this.getFoldKey(n),n);return[...t.values()].sort((n,i)=>n.start.line!==i.start.line?n.start.line-i.start.line:n.end.line!==i.end.line?n.end.line-i.end.line:n.start.column-i.start.column)}createFoldIndicator(e,t,n){const i=document.createElement("button");return i.type="button",i.style.cssText=`
191
+ `),n=[],i=[],o={"{":"}","[":"]","(":")"},r={"}":"{","]":"[",")":"("};for(let l=0;l<t.length;l++){const c=t[l];for(let h=0;h<c.length;h++){const d=c[h];if(o[d]){n.push({char:d,line:l,column:h});continue}const f=r[d];if(!f)continue;let p=-1;for(let b=n.length-1;b>=0;b--)if(n[b].char===f){p=b;break}if(p===-1)continue;const u=n.splice(p,1)[0];if(u.line>=l)continue;const g=((a=t[u.line])==null?void 0:a.length)||0,m={start:{line:u.line,column:g},end:{line:l,column:0},collapsed:!1,level:p};this.isValidFoldRegion(m)&&i.push(m)}}return i.sort((l,c)=>l.start.line!==c.start.line?l.start.line-c.start.line:l.end.line!==c.end.line?l.end.line-c.end.line:l.start.column-c.start.column),i}shouldIncludeMarkupFolds(e){return/<!DOCTYPE\b/i.test(e)||/<[A-Za-z][\w:-]*(?:\s|>)/.test(e)&&/<\/[A-Za-z][\w:-]*\s*>/.test(e)}buildMarkupFoldRegions(e){const{lineStarts:t,lines:n}=this.buildLineStarts(e),i=[],o=[];let r=0;for(;r<e.length;){if(e[r]!=="<"){r+=1;continue}if(e.startsWith("<!--",r)){const l=e.indexOf("-->",r+4);r=l===-1?e.length:l+3;continue}if(e.startsWith("<![CDATA[",r)){const l=e.indexOf("]]>",r+9);r=l===-1?e.length:l+3;continue}const a=this.parseMarkupTag(e,r,t,n);if(!a){r+=1;continue}if(r=a.endOffset,a.isClosing){const l=o.findIndex(d=>d.name===a.name);if(l===-1)continue;const c=o.splice(l,1)[0],h=this.createMarkupFoldRegion(c.openEndLine,a.startLine,n);h&&i.push(h);continue}if(!(a.isSelfClosing||this.voidMarkupTags.has(a.name))){if(this.rawTextMarkupTags.has(a.name)){const l=this.findClosingMarkupTag(e,a.endOffset,a.name,t,n);if(l){const c=this.createMarkupFoldRegion(a.endLine,l.startLine,n);c&&i.push(c),r=l.endOffset}continue}this.nonFoldableInlineMarkupTags.has(a.name)||o.unshift({name:a.name,openEndLine:a.endLine})}}return i}parseMarkupTag(e,t,n,i){if(e[t]!=="<")return null;const o=e[t+1];if(!o||o!=="/"&&!/[A-Za-z]/.test(o))return null;const r=o==="/";let a=t+(r?2:1);const l=a;for(;a<e.length&&/[A-Za-z0-9:-]/.test(e[a]);)a+=1;const c=a;if(a===l)return null;let h=null;for(;a<e.length;){const g=e[a];if(h){g===h&&(h=null),a+=1;continue}if(g==='"'||g==="'"){h=g,a+=1;continue}if(g===">")break;a+=1}if(a>=e.length||e[a]!==">")return null;const d=e.slice(l,c).toLowerCase();if(!d)return null;const f=e.slice(t,a+1),p=this.offsetToLine(t,n,i),u=this.offsetToLine(a,n,i);return{name:d,isClosing:r,isSelfClosing:!r&&/\/\s*>$/.test(f),startLine:p,endLine:u,endOffset:a+1}}findClosingMarkupTag(e,t,n,i,o){const r=`</${n}`,a=e.toLowerCase();let l=a.indexOf(r,t);for(;l!==-1;){const c=this.parseMarkupTag(e,l,i,o);if(c&&c.isClosing&&c.name===n)return{startLine:c.startLine,endOffset:c.endOffset};l=a.indexOf(r,l+r.length)}return null}createMarkupFoldRegion(e,t,n){var a;if(e>=t)return null;const i=Math.max(0,Math.min(e,n.length-1)),o=Math.max(0,Math.min(t,n.length-1)),r={start:{line:i,column:((a=n[i])==null?void 0:a.length)||0},end:{line:o,column:0},collapsed:!1,level:0};return this.isValidFoldRegion(r)?r:null}mergeFoldRegions(e){const t=new Map;for(const n of e)this.isValidFoldRegion(n)&&t.set(this.getFoldKey(n),n);return[...t.values()].sort((n,i)=>n.start.line!==i.start.line?n.start.line-i.start.line:n.end.line!==i.end.line?n.end.line-i.end.line:n.start.column-i.start.column)}createFoldIndicator(e,t,n){const i=document.createElement("button");return i.type="button",i.style.cssText=`
192
192
  position: absolute;
193
193
  left: 0;
194
194
  top: ${t*this.lineHeight}px;
@@ -205,17 +205,17 @@
205
205
  padding: 0;
206
206
  font-size: 10px;
207
207
  user-select: none;
208
- `,i.textContent=n?"▶":"▼",i.title=n?"Expand folded region":"Collapse region",i.setAttribute("aria-label",i.title),i.addEventListener("mousedown",o=>{o.preventDefault()}),i.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),this.toggleFold(e)}),i}toggleFold(e){this.editor&&(this.isFoldActive(e)?this.editor.unfold(e):this.editor.fold(e),this.syncFoldingStatePreservingScroll())}foldAtCursor(){if(!this.editor)return;const e=this.editor.getCursor().position.line,t=this.findBestRegionForLine(e,!1);t&&(this.editor.fold(t),this.syncFoldingStatePreservingScroll())}unfoldAtCursor(){if(!this.editor)return;const e=this.editor.getCursor().position.line,t=this.findBestRegionForLine(e,!0);t&&(this.editor.unfold(t),this.syncFoldingStatePreservingScroll())}foldAll(){if(!this.editor)return;const e=this.getTopLevelFoldRegions(this.foldRegions);for(const t of e)this.editor.fold(t);this.syncFoldingStatePreservingScroll()}unfoldAll(){if(!this.editor)return;const e=this.getActiveFolds();for(const t of e)this.editor.unfold(t);this.syncFoldingStatePreservingScroll()}syncFoldingStatePreservingScroll(){this.withPreservedScroll(()=>{this.syncFoldingState()})}withPreservedScroll(e){var o;const t=(o=this.editor)==null?void 0:o.getView().getScrollElement();if(!t){e();return}const n=t.scrollLeft,i=t.scrollTop;e(),this.restoreScrollPosition(t,n,i)}restoreScrollPosition(e,t,n){e.scrollLeft=t,e.scrollTop=n,requestAnimationFrame(()=>{e.isConnected&&(e.scrollLeft=t,e.scrollTop=n)})}applyFoldedDisplay(){if(!this.editor)return;const e=this.getRenderableActiveFolds();if(e.length===0){this.restoreFullDisplay();return}const t=this.buildFoldedProjection(this.editor.getValue(),e);this.withPreservedSelection(()=>{this.renderEditorText(t.text),this.renderFoldPlaceholders(t),this.isDisplayingFolded=!0})}restoreFullDisplay(){this.editor&&(this.isDisplayingFolded&&this.withPreservedSelection(()=>{this.renderEditorText(this.editor.getValue())}),this.isDisplayingFolded=!1)}renderEditorText(e){if(!this.editor)return;const t=this.editor;if(typeof t.renderTextWithHighlight=="function"){t.expectingProgrammaticCursor=!0,t.renderTextWithHighlight(e,!1),t.expectingProgrammaticCursor=!1;return}this.editor.getView().setText(e)}buildFoldedProjection(e,t){const{lineStarts:n,lines:i}=this.buildLineStarts(e),o=[...t].sort((h,u)=>this.comparePositions(h.start,u.start));let r="";const a=[];let l=0;for(const h of o){const u=this.positionToOffset(h.start,n,i),d=this.positionToOffset(h.end,n,i),g=e.slice(l,u),f=this.getFoldPlaceholder(h),p=e.slice(u,d);r+=g,r+=f,g&&a.push({type:"text",text:g}),a.push({type:"placeholder",text:f,fold:h,hiddenText:p}),l=d}const c=e.slice(l);return r+=c,c&&a.push({type:"text",text:c}),{text:r,segments:a}}renderFoldPlaceholders(e){if(!this.editor)return;const t=this.editor.getView().getContentElement(),n=new Map,i=document.createDocumentFragment();for(const o of e.segments){if(o.type==="text"){i.appendChild(document.createTextNode(o.text));continue}const r=document.createElement("span"),a=this.getFoldKey(o.fold);r.setAttribute("data-lce-fold-placeholder",a),r.setAttribute("aria-label","Folded region"),r.contentEditable="false",n.set(a,o.hiddenText),r.style.cssText=`
208
+ `,i.textContent=n?"▶":"▼",i.title=n?"Expand folded region":"Collapse region",i.setAttribute("aria-label",i.title),i.addEventListener("mousedown",o=>{o.preventDefault()}),i.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),this.toggleFold(e)}),i}toggleFold(e){this.editor&&(this.isFoldActive(e)?this.editor.unfold(e):this.editor.fold(e),this.syncFoldingStatePreservingScroll())}foldAtCursor(){if(!this.editor)return;const e=this.editor.getCursor().position.line,t=this.findBestRegionForLine(e,!1);t&&(this.editor.fold(t),this.syncFoldingStatePreservingScroll())}unfoldAtCursor(){if(!this.editor)return;const e=this.editor.getCursor().position.line,t=this.findBestRegionForLine(e,!0);t&&(this.editor.unfold(t),this.syncFoldingStatePreservingScroll())}foldAll(){if(!this.editor)return;const e=this.getTopLevelFoldRegions(this.foldRegions);for(const t of e)this.editor.fold(t);this.syncFoldingStatePreservingScroll()}unfoldAll(){if(!this.editor)return;const e=this.getActiveFolds();for(const t of e)this.editor.unfold(t);this.syncFoldingStatePreservingScroll()}syncFoldingStatePreservingScroll(){this.withPreservedScroll(()=>{this.syncFoldingState()})}withPreservedScroll(e){var o;const t=(o=this.editor)==null?void 0:o.getView().getScrollElement();if(!t){e();return}const n=t.scrollLeft,i=t.scrollTop;e(),this.restoreScrollPosition(t,n,i)}restoreScrollPosition(e,t,n){e.scrollLeft=t,e.scrollTop=n,requestAnimationFrame(()=>{e.isConnected&&(e.scrollLeft=t,e.scrollTop=n)})}applyFoldedDisplay(){if(!this.editor)return;const e=this.getRenderableActiveFolds();if(e.length===0){this.restoreFullDisplay();return}const t=this.buildFoldedProjection(this.editor.getValue(),e);this.withPreservedSelection(()=>{this.renderEditorText(t.text),this.renderFoldPlaceholders(t),this.isDisplayingFolded=!0})}restoreFullDisplay(){this.editor&&(this.isDisplayingFolded&&this.withPreservedSelection(()=>{this.renderEditorText(this.editor.getValue())}),this.isDisplayingFolded=!1)}renderEditorText(e){if(!this.editor)return;const t=this.editor;if(typeof t.renderTextWithHighlight=="function"){t.expectingProgrammaticCursor=!0,t.renderTextWithHighlight(e,!1),t.expectingProgrammaticCursor=!1;return}this.editor.getView().setText(e)}buildFoldedProjection(e,t){const{lineStarts:n,lines:i}=this.buildLineStarts(e),o=[...t].sort((h,d)=>this.comparePositions(h.start,d.start));let r="";const a=[];let l=0;for(const h of o){const d=this.positionToOffset(h.start,n,i),f=this.positionToOffset(h.end,n,i),p=e.slice(l,d),u=this.getFoldPlaceholder(h),g=e.slice(d,f);r+=p,r+=u,p&&a.push({type:"text",text:p}),a.push({type:"placeholder",text:u,fold:h,hiddenText:g}),l=f}const c=e.slice(l);return r+=c,c&&a.push({type:"text",text:c}),{text:r,segments:a}}renderFoldPlaceholders(e){if(!this.editor)return;const t=this.editor.getView().getContentElement(),n=new Map,i=document.createDocumentFragment();for(const o of e.segments){if(o.type==="text"){i.appendChild(document.createTextNode(o.text));continue}const r=document.createElement("span"),a=this.getFoldKey(o.fold);r.setAttribute("data-lce-fold-placeholder",a),r.setAttribute("aria-label","Folded region"),r.contentEditable="false",n.set(a,o.hiddenText),r.style.cssText=`
209
209
  cursor: text;
210
210
  user-select: text;
211
211
  pointer-events: auto;
212
212
  white-space: pre;
213
- `,r.textContent=o.text,i.appendChild(r)}t.replaceChildren(i),t.__lceFoldPlaceholderSources=n,this.editor.getView().syncTrailingNewlineMarkerForText(e.text)}getFoldPlaceholder(e){const t=Math.max(1,e.end.line-e.start.line);return` … ${t} ${t===1?"line":"lines"} … `}pruneInvalidFolds(e,t){if(!this.editor)return;const n=this.editor.getFolds().filter(c=>c.collapsed!==!1),i=new Set(n.map(c=>this.getFoldKey(c))),o=[],r=new Set,a=this.getLineInfo(e);for(const c of n){const h=this.findReplacementFold(c,t.get(this.getFoldKey(c)),r,e,a);if(!h)continue;const u=this.getFoldKey(h);o.push(h),r.add(u)}const l=new Set(o.map(c=>this.getFoldKey(c)));for(const c of n)l.has(this.getFoldKey(c))||this.editor.unfold(c);for(const c of o)i.has(this.getFoldKey(c))||this.editor.fold(c)}getActiveFolds(){return this.editor?this.editor.getFolds().filter(e=>e.collapsed!==!1):[]}hasActiveFolds(){return this.getActiveFolds().length>0}getRenderableActiveFolds(){return this.getTopLevelFoldRegions(this.getActiveFolds())}getTopLevelFoldRegions(e){const t=[...e].sort((i,o)=>this.comparePositions(i.start,o.start)),n=[];for(const i of t){const o=n[n.length-1];o&&this.containsRange(o,i)||n.push(i)}return n}toDisplayLine(e,t){let n=0;for(const i of t){if(this.isSameRange(i,e))break;if(this.containsRange(i,e))return null;i.end.line<=e.start.line&&(n+=i.end.line-i.start.line)}return e.start.line-n}findBestRegionForLine(e,t){const n=(t?this.getActiveFolds():this.foldRegions).filter(i=>i.start.line<=e&&i.end.line>=e);return n.length===0?null:(n.sort((i,o)=>{const r=i.end.line-i.start.line,a=o.end.line-o.start.line;return r!==a?r-a:this.comparePositions(i.start,o.start)}),n[0])}findReplacementFold(e,t,n,i,o){const r=this.getFoldKey(e),a=this.foldRegions.find(d=>this.getFoldKey(d)===r&&!n.has(r));if(a)return a;const l=e.end.line-e.start.line,c=t!=null?t:this.createFoldSnapshot(e,i,o),h=this.foldRegions.filter(d=>!n.has(this.getFoldKey(d))).map(d=>{const g=this.createFoldSnapshot(d,i,o),f=c&&(g==null?void 0:g.startLineText)===c.startLineText?1:0,p=c&&(g==null?void 0:g.endLineText)===c.endLineText?1:0,m=c&&(g==null?void 0:g.lineSpan)===c.lineSpan?1:0;return{region:d,overlaps:this.lineRangeOverlap(e,d),lineDistance:Math.abs(d.start.line-e.start.line)+Math.abs(d.end.line-e.end.line),spanDistance:Math.abs(d.end.line-d.start.line-l),columnDistance:Math.abs(d.start.column-e.start.column)+Math.abs(d.end.column-e.end.column),hiddenTextMatch:c&&(g==null?void 0:g.hiddenText)===c.hiddenText?1:0,boundaryMatchScore:f+p+m}}).sort((d,g)=>d.hiddenTextMatch!==g.hiddenTextMatch?g.hiddenTextMatch-d.hiddenTextMatch:d.boundaryMatchScore!==g.boundaryMatchScore?g.boundaryMatchScore-d.boundaryMatchScore:d.overlaps!==g.overlaps?g.overlaps-d.overlaps:d.lineDistance!==g.lineDistance?d.lineDistance-g.lineDistance:d.spanDistance!==g.spanDistance?d.spanDistance-g.spanDistance:d.columnDistance-g.columnDistance)[0];if(!h)return null;const u=h.lineDistance<=2&&h.spanDistance<=1;return!(h.hiddenTextMatch===1||h.boundaryMatchScore>=2)&&!u?null:h.region}lineRangeOverlap(e,t){const n=Math.max(e.start.line,t.start.line),i=Math.min(e.end.line,t.end.line);return Math.max(0,i-n)}rememberActiveFoldSnapshots(e){const t=new Map,n=this.getLineInfo(e);for(const i of this.getActiveFolds()){const o=this.createFoldSnapshot(i,e,n);o&&t.set(this.getFoldKey(i),o)}this.foldSnapshots=t}createFoldSnapshot(e,t,n=this.getLineInfo(t)){var h,u;const{lineStarts:i,lines:o}=n;if(o.length===0)return null;const r=this.positionToOffset(e.start,i,o),a=this.positionToOffset(e.end,i,o),l=Math.max(0,Math.min(e.start.line,o.length-1)),c=Math.max(0,Math.min(e.end.line,o.length-1));return{hiddenText:t.slice(r,a),startLineText:(h=o[l])!=null?h:"",endLineText:(u=o[c])!=null?u:"",lineSpan:e.end.line-e.start.line}}withPreservedSelection(e){var l,c;if(!this.editor){e();return}const t=this.editor.getView(),n=t.getContentElement(),i=document.activeElement===n,o=t.getSelectionOffsets(),r=o.isInEditor;if(e(),!r)return;const a=this.remapSelectionOffsetsForVisibleDisplay((l=o.anchorOffset)!=null?l:o.startOffset,(c=o.focusOffset)!=null?c:o.endOffset);t.setSelectionBoundaryOffsets(a.startOffset,a.endOffset),(i||o.isInEditor)&&this.editor.focus()}remapSelectionOffsetsForVisibleDisplay(e,t){if(!this.editor)return{startOffset:e,endOffset:t};const n=this.editor.getValue(),{lineStarts:i,lines:o}=this.getLineInfo(n),r=this.getRenderableActiveFolds();if(r.length===0){const a=n.length;return{startOffset:Math.max(0,Math.min(e,a)),endOffset:Math.max(0,Math.min(t,a))}}return{startOffset:this.remapOffsetToVisibleBoundary(e,r,i,o,n.length),endOffset:this.remapOffsetToVisibleBoundary(t,r,i,o,n.length)}}remapOffsetToVisibleBoundary(e,t,n,i,o){const r=Math.max(0,Math.min(e,o));for(const a of t){const l=this.positionToOffset(a.start,n,i),c=this.positionToOffset(a.end,n,i);if(r<=l||r>=c)continue;const h=r-l,u=c-r;return h<=u?l:c}return r}buildLineStarts(e){const t=e.split(`
214
- `),n=new Array(t.length);let i=0;for(let o=0;o<t.length;o++)n[o]=i,i+=t[o].length+1;return{lineStarts:n,lines:t}}getLineInfo(e){var n;if(((n=this.cachedLineInfo)==null?void 0:n.text)===e)return this.cachedLineInfo;const t={text:e,...this.buildLineStarts(e)};return this.cachedLineInfo=t,t}offsetToLine(e,t,n){var l;const i=t.length>0?t[t.length-1]+(((l=n[n.length-1])==null?void 0:l.length)||0):0,o=Math.max(0,Math.min(e,i));let r=0,a=t.length-1;for(;r<=a;){const c=Math.floor((r+a)/2),h=t[c],u=c+1<t.length?t[c+1]:Number.POSITIVE_INFINITY;if(o<h){a=c-1;continue}if(o>=u){r=c+1;continue}return c}return Math.max(0,Math.min(r,t.length-1))}positionToOffset(e,t,n){var r;const i=Math.max(0,Math.min(e.line,n.length-1)),o=Math.max(0,Math.min(e.column,((r=n[i])==null?void 0:r.length)||0));return t[i]+o}comparePositions(e,t){return e.line!==t.line?e.line-t.line:e.column-t.column}containsRange(e,t){return this.comparePositions(e.start,t.start)<=0&&this.comparePositions(e.end,t.end)>=0&&!this.isSameRange(e,t)}isSameRange(e,t){return e.start.line===t.start.line&&e.start.column===t.start.column&&e.end.line===t.end.line&&e.end.column===t.end.column}isFoldActive(e){return this.getActiveFolds().some(t=>this.isSameRange(t,e))}isValidFoldRegion(e){return e.start.line<e.end.line&&(e.start.line!==e.end.line||e.start.column!==e.end.column)}getFoldKey(e){return`${e.start.line}:${e.start.column}-${e.end.line}:${e.end.column}`}destroy(){this.pendingUpdateRaf!==null&&(cancelAnimationFrame(this.pendingUpdateRaf),this.pendingUpdateRaf=null),this.editor&&this.changeHandler&&this.editor.off("change",this.changeHandler),this.foldingUI&&this.foldingUI.parentNode&&this.foldingUI.parentNode.removeChild(this.foldingUI),this.restoreFullDisplay(),this.changeHandler=null,this.lastSnapshot="",this.lastParsedText=null,this.foldingUI=null,this.foldRegions=[],this.cachedLineInfo=null,this.editor=null}}class ai{constructor(){this.name="syntax-highlighting",this.editor=null,this.currentTheme="dark",this.currentLanguage=null,this.modes=new Map}setup(e){this.editor=e,this.registerMode("html",{name:"html",highlight:(t,n)=>this._highlightHTML(t,n)}),this.registerMode("css",{name:"css",highlight:(t,n)=>this._highlightCSS(t,n)}),this.registerMode("javascript",{name:"javascript",highlight:(t,n)=>this._highlightJS(t,n)}),this.registerMode("js",{name:"javascript",highlight:(t,n)=>this._highlightJS(t,n)}),this.registerMode("jsx",{name:"jsx",highlight:(t,n)=>this._highlightJSX(t,n)}),this.registerMode("typescript",{name:"typescript",highlight:(t,n)=>this._highlightJS(t,n)}),this.registerMode("ts",{name:"typescript",highlight:(t,n)=>this._highlightJS(t,n)}),this.registerMode("tsx",{name:"tsx",highlight:(t,n)=>this._highlightJSX(t,n)}),this.registerMode("json",{name:"json",highlight:(t,n)=>this._highlightJSON(t,n)}),this.registerMode("markdown",{name:"markdown",highlight:(t,n)=>this._highlightMarkdown(t,n)}),this.registerMode("md",{name:"markdown",highlight:(t,n)=>this._highlightMarkdown(t,n)}),this.registerMode("bash",{name:"bash",highlight:(t,n)=>this._highlightShell(t,n)}),this.registerMode("shell",{name:"bash",highlight:(t,n)=>this._highlightShell(t,n)}),this.registerMode("sh",{name:"bash",highlight:(t,n)=>this._highlightShell(t,n)}),this.registerMode("zsh",{name:"bash",highlight:(t,n)=>this._highlightShell(t,n)}),this.registerMode("python",{name:"python",highlight:(t,n)=>this._highlightGenericCode(t,n,"python")}),this.registerMode("py",{name:"python",highlight:(t,n)=>this._highlightGenericCode(t,n,"python")}),this.registerMode("go",{name:"go",highlight:(t,n)=>this._highlightGenericCode(t,n,"go")}),this.registerMode("golang",{name:"go",highlight:(t,n)=>this._highlightGenericCode(t,n,"go")}),this.registerMode("c",{name:"c",highlight:(t,n)=>this._highlightGenericCode(t,n,"c")}),this.registerMode("cpp",{name:"cpp",highlight:(t,n)=>this._highlightGenericCode(t,n,"cpp")}),this.registerMode("c++",{name:"cpp",highlight:(t,n)=>this._highlightGenericCode(t,n,"cpp")}),this.registerMode("cc",{name:"cpp",highlight:(t,n)=>this._highlightGenericCode(t,n,"cpp")}),this.registerMode("cxx",{name:"cpp",highlight:(t,n)=>this._highlightGenericCode(t,n,"cpp")}),this.registerMode("java",{name:"java",highlight:(t,n)=>this._highlightGenericCode(t,n,"java")}),this.registerMode("csharp",{name:"csharp",highlight:(t,n)=>this._highlightGenericCode(t,n,"csharp")}),this.registerMode("cs",{name:"csharp",highlight:(t,n)=>this._highlightGenericCode(t,n,"csharp")}),this.registerMode("rust",{name:"rust",highlight:(t,n)=>this._highlightGenericCode(t,n,"rust")}),this.registerMode("rs",{name:"rust",highlight:(t,n)=>this._highlightGenericCode(t,n,"rust")}),this.registerMode("ruby",{name:"ruby",highlight:(t,n)=>this._highlightGenericCode(t,n,"ruby")}),this.registerMode("rb",{name:"ruby",highlight:(t,n)=>this._highlightGenericCode(t,n,"ruby")}),this.registerMode("sql",{name:"sql",highlight:(t,n)=>this._highlightGenericCode(t,n,"sql")}),this.registerMode("yaml",{name:"yaml",highlight:(t,n)=>this._highlightYAML(t,n)}),this.registerMode("yml",{name:"yaml",highlight:(t,n)=>this._highlightYAML(t,n)}),this.registerMode("xml",{name:"xml",highlight:(t,n)=>this._highlightXML(t,n)}),this.registerMode("svg",{name:"xml",highlight:(t,n)=>this._highlightXML(t,n)}),this.registerMode("vue",{name:"vue",highlight:(t,n)=>this._highlightHTML(t,n)}),this.registerMode("ejs",{name:"ejs",highlight:(t,n)=>this._highlightEJS(t,n)}),this.registerMode("dockerfile",{name:"dockerfile",highlight:(t,n)=>this._highlightDockerfile(t,n)}),this.registerMode("docker",{name:"dockerfile",highlight:(t,n)=>this._highlightDockerfile(t,n)}),this.registerMode("php",{name:"php",highlight:(t,n)=>this._highlightPHP(t,n)}),e.registerCommand("setSyntaxLanguage",t=>{this.setLanguage(t),this.refreshEditorHighlight()})}setTheme(e){this.currentTheme=e}setLanguage(e){this.currentLanguage=e}registerMode(e,t){this.modes.set(e.toLowerCase(),t)}getSyntaxColors(){return this.currentTheme==="dark"?{tag:"#569cd6",comment:"#6a9955",attrName:"#9cdcfe",attrValue:"#ce9178",styleProp:"#c586c0",styleVal:"#dcdcaa",doctype:"#808080",text:"#d4d4d4",keyword:"#c586c0",string:"#ce9178",number:"#b5cea8",variable:"#9cdcfe"}:{tag:"#0000ff",comment:"#008000",attrName:"#001080",attrValue:"#a31515",styleProp:"#6a00a8",styleVal:"#804000",doctype:"#444444",text:"#000000",keyword:"#000080",string:"#a31515",number:"#0086b3",variable:"#001080"}}highlight(e,t){const n=this.getSyntaxColors(),i=this.normalizeLanguageId(t||this.currentLanguage||this.detectLanguage(e)||"html");return(this.modes.get(i)||this.modes.get("html")).highlight(e,n)}highlightHTML(e){return this.highlight(e,"html")}escapeHTML(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;").replace(/'/g,"&#39;")}normalizeLanguageId(e){const t=e.trim().toLowerCase().replace(/^\./,"");return{cjs:"javascript",js:"javascript",javascriptreact:"javascript",jsx:"jsx",mjs:"javascript",mts:"typescript",ts:"typescript",tsx:"tsx",typescriptreact:"tsx",md:"markdown",mdx:"markdown",shell:"bash",sh:"bash",zsh:"bash",console:"bash",terminal:"bash",docker:"dockerfile",dockerfile:"dockerfile",golang:"go",py:"python",cxx:"cpp",cc:"cpp","c++":"cpp",cs:"csharp",rs:"rust",rb:"ruby",yml:"yaml",svg:"xml",vue:"vue",ejs:"ejs"}[t]||t||"html"}restoreHighlightTokens(e,t){return e.replace(/\u0000([a-z]+)\u0000/g,(n,i)=>{let o=0;for(let r=0;r<i.length;r++)o=o*26+(i.charCodeAt(r)-97+1);return o=o-1,t[o]||""})}createTokenStore(e){const t=n=>{let i="",o=n;do i=String.fromCharCode(97+o%26)+i,o=Math.floor(o/26)-1;while(o>=0);return i||"a"};return n=>{const i=e.length;return e.push(n),`\0${t(i)}\0`}}refreshEditorHighlight(){const e=this.editor;e!=null&&e.renderTextWithHighlight&&e.renderTextWithHighlight(e.getValue(),!0)}unescapeEntitiesRepeated(e){let t=e||"";for(let n=0;n<5;n++){const i=t;if(t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'"),t===i)break}return t}detectLanguage(e){const t=e.trim();if(!t)return null;if(/^<\?(?:php\b|=)/i.test(t)||/^\?php\b/i.test(t))return"php";if(/^[\[{]/.test(t)&&/[\]}]$/.test(t)||/"[^"]+"\s*:/.test(t))try{return JSON.parse(t),"json"}catch(a){}const n=/<\/?[A-Za-z][\w:-]*(?:\s|>|\/>)/.test(t),i=/^<!DOCTYPE\s+html\b/i.test(t)||/<\/?(html|head|body|meta|title|style|script)\b/i.test(t);if([/^---\s*\n[\s\S]*?\n---\s*(?:\n|$)/.test(t),/^#{1,6}\s+\S/m.test(t),/^\s*```/m.test(t),/^\s*~~~/m.test(t),/^\s{0,3}>\s+/m.test(t),/^\s{0,3}(?:[-*+]|\d+\.)\s+\S/m.test(t),/^\s{0,3}[-*+]\s+\[[ xX]\]\s+\S/m.test(t),/\[[^\]\n]+\]\([^)]+\)/.test(t),/!\[[^\]\n]*\]\([^)]+\)/.test(t),/(^|\n)\s*\|.+\|\s*\n\s*\|[\s:-]+\|/m.test(t),/(^|\s)(?:\*\*|__)[^*_]+(?:\*\*|__)(?=\s|$|[.,;:!?])/m.test(t)].filter(Boolean).length>=(n?2:1))return"markdown";if(i)return"html";const o=this.detectProgrammingLanguage(t);if(o)return o;const r=/[{][\s\S]*[}]/.test(t)&&/[A-Za-z_-][\w-]*\s*:\s*[^;{}]+;?/.test(t)&&!/\b(function|const|let|var|return|class|interface|type)\b/.test(t);return!n&&r?"css":null}detectProgrammingLanguage(e){const t={php:0,python:0,go:0,cpp:0,c:0,java:0,csharp:0,rust:0,ruby:0,sql:0,yaml:0,dockerfile:0},n=(r,a,l=1)=>{a.test(e)&&(t[r]+=l)};n("python",/^\s*(from\s+\w+\s+import|import\s+\w+|def\s+\w+\s*\(|class\s+\w+|for\s+\w+\s+in\s+.+:|if\s+.+:|while\s+.+:|print\s*\()/m,2),n("python",/^\s*[A-Za-z_]\w*\s*=\s*(?:\[|\{|\(|["']|\d)/m),n("python",/\b(True|False|None|self|elif|lambda|yield)\b/),n("go",/^\s*package\s+\w+/m,3),n("go",/\bfunc\s+\w+\s*\(/,2),n("go",/\b(import|defer|goroutine|chan|struct|interface)\b/),n("cpp",/^\s*#include\s*<[^>]+>/m,2),n("cpp",/\b(std::|template\s*<|namespace\s+\w+|cout\s*<<|cin\s*>>)\b/,2),n("cpp",/\b(class|public|private|protected|virtual|typename)\b/),n("c",/^\s*#include\s*[<"][^>"]+[>"]/m),n("c",/\b(int|char|float|double|void)\s+\w+\s*\(/),n("c",/\bprintf\s*\(/),n("java",/^\s*(package|import)\s+[\w.]+;/m,2),n("java",/\b(public|private|protected)\s+(class|interface|enum)\s+\w+/,2),n("java",/\bSystem\.out\.println\s*\(/),n("csharp",/^\s*using\s+[\w.]+;/m,2),n("csharp",/\b(namespace|record|var|string|Console\.WriteLine)\b/),n("csharp",/\b(public|private|protected)\s+(class|interface|struct)\s+\w+/),n("rust",/\bfn\s+\w+\s*\(/,2),n("rust",/\b(let\s+mut|impl\s+\w+|use\s+[\w:]+|println!\s*\()/),n("rust",/\b(crate|trait|enum|match|Some|None|Ok|Err)\b/),n("ruby",/^\s*(def|class|module)\s+\w+/m,2),n("ruby",/\b(puts|require|attr_reader|elsif|end)\b/),n("sql",/^\s*(SELECT|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP)\b/im,3),n("sql",/\bFROM\s+\w+|\bWHERE\s+/i),n("yaml",/^---\s*$/m),n("yaml",/^\s*[A-Za-z0-9_.-]+\s*:\s+\S/m,2),n("yaml",/^\s*-\s+[A-Za-z0-9_.-]+\s*:/m),n("dockerfile",/^\s*FROM\s+\S+/im,3),n("dockerfile",/^\s*(RUN|COPY|ADD|CMD|ENTRYPOINT|WORKDIR|ENV|ARG)\b/im,2),n("php",/^<\?(?:php\b|=)/i,3),n("php",/^\?php\b/i,3),n("php",/\$[A-Za-z_\x80-\xff][A-Za-z0-9_\x80-\xff]*\s*=/,2),n("php",/\b(echo|foreach|function|namespace|use|PHP_EOL)\b/,2);const[i,o]=Object.entries(t).sort((r,a)=>a[1]-r[1])[0]||["",0];return o>=2?i:null}_highlightHTML(e,t){const n=t,i=d=>this.escapeHTML(d),o=[],r=this.createTokenStore(o),a=[],l=d=>{const g=a.length;return a.push(d),`ht${g}`};let c=i(e);c=c.replace(/&lt;\/?(?:(?!&gt;)[^\n\r<])*?(?=$|[\n\r])/g,d=>l(d));const h=[];try{e.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,(d,g,f)=>(h.push({attrs:String(g||""),inner:String(f||"")}),d))}catch(d){}let u=0;return c=c.replace(/(&lt;script\b([^&>]*)&gt;)([\s\S]*?)(&lt;\/script&gt;)/gi,(d,g,f,p,m)=>{var C,w,S;const b=(w=(C=h[u++])==null?void 0:C.inner)!=null?w:this.unescapeEntitiesRepeated(p||"");(((S=h[u-1])==null?void 0:S.attrs)||f||"").toLowerCase();const x=this._highlightJS(b,n);return`${g}${x}${m}`}),c=c.replace(/(&lt;style\b[^&]*&gt;)([\s\S]*?)(&lt;\/style&gt;)/gi,(d,g,f,p)=>{const m=this._highlightCSS(this.unescapeEntitiesRepeated(f),n);return`${g}${m}${p}`}),c=c.replace(/(&lt;!--[\s\S]*?--&gt;)/g,d=>r(`<span style="color: ${n.comment};">${d}</span>`)),c=c.replace(/(&lt;!DOCTYPE[\s\S]*?&gt;)/i,d=>r(`<span style="color: ${n.doctype};">${d}</span>`)),c=c.replace(/(&lt;\/?\s*)([^\s&>\/]+)([^<]*?)(\/?&gt;)/g,(d,g,f,p,m)=>{const b=`<span style="color: ${n.tag};">${f}</span>`;let x=p;return x=x.replace(/([\w:-]+)(\s*=\s*)((&quot;[\s\S]*?&quot;|&#39;[\s\S]*?&#39;|[^\s&>]+))/g,(C,w,S,T)=>{const O=String(w).toLowerCase(),B=`<span style="color: ${n.attrName};">${w}</span>`;let N=T,k="";T.startsWith("&quot;")&&T.endsWith("&quot;")?(N=T.slice(6,-6),k="&quot;"):T.startsWith("&#39;")&&T.endsWith("&#39;")&&(N=T.slice(5,-5),k="&#39;");let M=T;if(O==="style"){const Z=N.replace(/([\w-]+)\s*:\s*([^;]+)(;?)/g,(re,A,se,D)=>`<span style="color: ${n.styleProp};">${A}</span>:<span style="color: ${n.styleVal};">${se}</span>${D}`);k?M=`${k}${Z}${k}`:M=Z,M=`<span style="color: ${n.attrValue};">${M}</span>`}else k&&(M=`${k}${N}${k}`),M=`<span style="color: ${n.attrValue};">${M}</span>`;return`${B}${S}${M}`}),`${g}${b}${x}${m}`}),c=c.replace(/\u0002ht(\d+)\u0002/g,(d,g)=>a[Number(g)]||""),this.restoreHighlightTokens(c,o)}_highlightCSS(e,t){const n=this.unescapeEntitiesRepeated(e),i=[],o=this.createTokenStore(i),r=/(\/\*[\s\S]*?\*\/)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g;let a=0,l="",c;for(;c=r.exec(n);){a<c.index&&(l+=this.escapeHTML(n.slice(a,c.index)));const h=c[0],u=h.startsWith("/*")?t.comment:t.string;l+=o(`<span style="color: ${u};">${this.escapeHTML(h)}</span>`),a=r.lastIndex}return a<n.length&&(l+=this.escapeHTML(n.slice(a))),l=l.replace(/(@[\w-]+)/g,h=>o(`<span style="color: ${t.keyword};">${h}</span>`)),l=l.replace(/([A-Za-z_-][\w-]*)(\s*:)/g,(h,u,d)=>`${o(`<span style="color: ${t.styleProp};">${u}</span>`)}${d}`),l=l.replace(/(#(?:[0-9a-fA-F]{3,8})\b)/g,h=>o(`<span style="color: ${t.number};">${h}</span>`)),l=l.replace(/\b(-?\d*\.?\d+(?:px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|turn|fr)?)\b/g,h=>o(`<span style="color: ${t.number};">${h}</span>`)),l=l.replace(/\b(important|inherit|initial|unset|revert|auto|none|block|inline|flex|grid|absolute|relative|fixed|sticky)\b/g,h=>o(`<span style="color: ${t.styleVal};">${h}</span>`)),this.restoreHighlightTokens(l,i)}_highlightJSON(e,t){const n=this.unescapeEntitiesRepeated(e),i=/("(?:\\.|[^"\\])*")(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}\[\],:]/g;let o=0,r="",a;for(;a=i.exec(n);){o<a.index&&(r+=this.escapeHTML(n.slice(o,a.index)));const l=a[0],c=a[1],h=a[2]||"",u=a[3];if(c){const d=h?t.attrName:t.string;r+=`<span style="color: ${d};">${this.escapeHTML(c)}</span>${this.escapeHTML(h)}`}else u?r+=`<span style="color: ${t.keyword};">${l}</span>`:/^-?\d/.test(l)?r+=`<span style="color: ${t.number};">${l}</span>`:r+=`<span style="color: ${t.tag};">${this.escapeHTML(l)}</span>`;o=i.lastIndex}return o<n.length&&(r+=this.escapeHTML(n.slice(o))),r}_highlightMarkdown(e,t){var l;const n=this.unescapeEntitiesRepeated(e).split(`
215
- `);let i=!1,o="",r="",a=((l=n[0])==null?void 0:l.trim())==="---";return n.map((c,h)=>{const u=[],d=this.createTokenStore(u);if(a){const p=c.trim()==="---",m=`<span style="color: ${p?t.keyword:t.attrName};">${this.escapeHTML(c)}</span>`;return h>0&&p&&(a=!1),m}const g=c.match(/^(\s*)(`{3,}|~{3,})(.*)$/);if(g){const p=g[2];return i=!(i&&p[0]===o[0]),o=i?p:"",r=i?this.extractMarkdownFenceLanguage(g[3]||""):"",[this.escapeHTML(g[1]),`<span style="color: ${t.keyword}; font-weight: 700;">${this.escapeHTML(p)}</span>`,`<span style="color: ${t.string};">${this.escapeHTML(g[3]||"")}</span>`].join("")}if(i)return this.highlightMarkdownFenceLine(c,r,t);let f=this.escapeHTML(c).replace(/(`[^`]+`)/g,p=>d(`<span style="color: ${t.string}; background: rgba(148, 163, 184, 0.16); border-radius: 3px;">${p}</span>`)).replace(/(!?\[[^\]\n]*\])(\([^)]+\))/g,(p,m,b)=>d(`<span style="color: ${t.attrName};">${m}</span><span style="color: ${t.attrValue};">${b}</span>`)).replace(/(\*\*|__)(.+?)\1/g,(p,m,b)=>d(`<span style="color: ${t.keyword};">${m}</span><span style="color: ${t.tag}; font-weight: 700;">${b}</span><span style="color: ${t.keyword};">${m}</span>`)).replace(/(~~)(.+?)\1/g,(p,m,b)=>d(`<span style="color: ${t.keyword};">${m}</span><span style="color: ${t.comment}; text-decoration: line-through;">${b}</span><span style="color: ${t.keyword};">${m}</span>`)).replace(/(\*|_)([^*_]+?)\1/g,(p,m,b)=>d(`<span style="color: ${t.keyword};">${m}</span><span style="color: ${t.styleVal}; font-style: italic;">${b}</span><span style="color: ${t.keyword};">${m}</span>`));return f=f.replace(/^(\s{0,3}#{1,6})(\s+.*)?$/,(p,m,b="")=>`<span style="color: ${t.keyword}; font-weight: 700;">${m}</span><span style="color: ${t.tag}; font-weight: 700;">${b}</span>`),f=f.replace(/^(\s{0,3})((?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/,(p,m,b)=>`${m}<span style="color: ${t.comment};">${b}</span>`),f=f.replace(/^(\s{0,3}&gt;)(.*)$/,(p,m,b)=>`<span style="color: ${t.comment};">${m}</span>${b}`),f=f.replace(/^(\s*)([-*+])(\s+\[[ xX]\])(\s+)/,(p,m,b,x,C)=>`${m}<span style="color: ${t.keyword};">${b}</span><span style="color: ${t.attrName};">${x}</span>${C}`),f=f.replace(/^(\s*)([-*+]|\d+\.)(\s+)/,(p,m,b,x)=>`${m}<span style="color: ${t.keyword};">${b}</span>${x}`),f=f.replace(/^(\s*\|.*\|\s*)$/,p=>p.replace(/\|/g,m=>`<span style="color: ${t.keyword};">${m}</span>`)),this.restoreHighlightTokens(f,u)}).join(`
216
- `)}extractMarkdownFenceLanguage(e){var n;const t=((n=e.trim().match(/^([A-Za-z0-9_+.#-]+)/))==null?void 0:n[1])||"";return t?this.normalizeLanguageId(t):""}highlightMarkdownFenceLine(e,t,n){const i=t?this.modes.get(t):void 0;return!i||i.name==="markdown"?`<span style="color: ${n.text};">${this.escapeHTML(e)}</span>`:i.highlight(e,n)}_highlightShell(e,t){const n=this.unescapeEntitiesRepeated(e),i=[],o=this.createTokenStore(i),r=/(#[^\n\r]*)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|(\$\{?[A-Za-z_][\w]*\}?|\$[0-9@#?$*!])/g;let a=0,l="",c;for(;c=r.exec(n);){a<c.index&&(l+=this.escapeHTML(n.slice(a,c.index)));const h=c[0],u=h.startsWith("#")?t.comment:h.startsWith("$")?t.variable:t.string;l+=o(`<span style="color: ${u};">${this.escapeHTML(h)}</span>`),a=r.lastIndex}return a<n.length&&(l+=this.escapeHTML(n.slice(a))),l=l.replace(/(^|\s)(--?[A-Za-z0-9][\w-]*)(?=\s|=|$)/g,(h,u,d)=>`${u}${o(`<span style="color: ${t.attrName};">${d}</span>`)}`),l=l.replace(/\b(if|then|else|elif|fi|for|while|until|do|done|case|esac|function|export|unset|alias|source|return|in)\b/g,h=>o(`<span style="color: ${t.keyword};">${h}</span>`)),l=l.replace(/(^|\s)(npm|npx|pnpm|yarn|bun|node|git|cd|mkdir|touch|cp|mv|rm|cat|grep|rg|find|curl|wget|echo|printf|sudo|chmod|chown|docker|kubectl)(?=\s|$)/g,(h,u,d)=>`${u}${o(`<span style="color: ${t.tag};">${d}</span>`)}`),this.restoreHighlightTokens(l,i)}getLanguageKeywords(e){const t=["true","false","null","nil","none"];return[...{python:["and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","self","True","False","None"],go:["break","case","chan","const","continue","defer","default","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],c:["auto","break","case","char","const","continue","default","do","double","else","enum","extern","float","for","goto","if","inline","int","long","register","restrict","return","short","signed","sizeof","static","struct","switch","typedef","union","unsigned","void","volatile","while"],cpp:["alignas","alignof","auto","bool","break","case","catch","char","class","concept","const","constexpr","continue","decltype","default","delete","do","double","else","enum","explicit","export","extern","false","float","for","friend","if","inline","int","long","namespace","new","noexcept","nullptr","operator","private","protected","public","requires","return","short","signed","sizeof","static","struct","switch","template","this","throw","true","try","typedef","typename","union","unsigned","using","virtual","void","volatile","while"],java:["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","final","finally","float","for","if","implements","import","instanceof","int","interface","long","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","try","void","volatile","while"],csharp:["abstract","as","async","await","base","bool","break","case","catch","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","get","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","out","override","params","private","protected","public","readonly","record","ref","return","sealed","set","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","using","var","virtual","void","volatile","while","yield"],rust:["as","async","await","break","const","continue","crate","dyn","else","enum","extern","false","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","Self","static","struct","super","trait","true","type","unsafe","use","where","while"],ruby:["BEGIN","END","alias","and","begin","break","case","class","def","defined?","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield"],sql:["ADD","ALTER","AND","AS","ASC","BETWEEN","BY","CASE","CREATE","DELETE","DESC","DISTINCT","DROP","ELSE","END","EXISTS","FROM","GROUP","HAVING","IN","INDEX","INNER","INSERT","INTO","IS","JOIN","LEFT","LIKE","LIMIT","NOT","NULL","ON","OR","ORDER","OUTER","PRIMARY","RIGHT","SELECT","SET","TABLE","THEN","UNION","UPDATE","VALUES","WHEN","WHERE"]}[e]||[],...t]}_highlightGenericCode(e,t,n){const i=this.unescapeEntitiesRepeated(e),o=[],r=this.createTokenStore(o),a=n==="python"||n==="ruby"||n==="sql"?"#[^\\n\\r]*|--[^\\n\\r]*":"\\/\\*[\\s\\S]*?\\*\\/|\\/\\/[^\\n\\r]*",l=new RegExp(`(${a})|("(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`)`,"g");let c=0,h="",u;for(;u=l.exec(i);){c<u.index&&(h+=this.escapeHTML(i.slice(c,u.index)));const g=u[0],f=g.startsWith("//")||g.startsWith("/*")||g.startsWith("#")||g.startsWith("--")?t.comment:t.string;h+=r(`<span style="color: ${f};">${this.escapeHTML(g)}</span>`),c=l.lastIndex}c<i.length&&(h+=this.escapeHTML(i.slice(c)));const d=Array.from(new Set(this.getLanguageKeywords(n)));if(d.length>0){const g=new RegExp(`\\b(${d.map(f=>f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")})\\b`,n==="sql"?"gi":"g");h=h.replace(g,f=>r(`<span style="color: ${t.keyword};">${f}</span>`))}return h=h.replace(/\b([A-Z][A-Za-z0-9_]*|[A-Za-z_][\w]*(?=\s*\())\b/g,g=>r(`<span style="color: ${t.tag};">${g}</span>`)),h=h.replace(/\b(-?0x[0-9a-fA-F]+|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)(?:[uUlLfFdD]*)\b/g,g=>r(`<span style="color: ${t.number};">${g}</span>`)),h=h.replace(/(@[A-Za-z_][\w]*|#[A-Za-z_][\w]*|::[A-Za-z_][\w]*)/g,g=>r(`<span style="color: ${t.attrName};">${g}</span>`)),this.restoreHighlightTokens(h,o)}_highlightYAML(e,t){const n=this.unescapeEntitiesRepeated(e),i=[],o=this.createTokenStore(i);let r=this.escapeHTML(n).replace(/(#.*)$/gm,a=>o(`<span style="color: ${t.comment};">${a}</span>`)).replace(/^(\s*[-?]?\s*)([A-Za-z0-9_.-]+)(\s*:)/gm,(a,l,c,h)=>`${l}${o(`<span style="color: ${t.attrName};">${c}</span>`)}${h}`).replace(/\b(true|false|null|yes|no|on|off)\b/gi,a=>o(`<span style="color: ${t.keyword};">${a}</span>`)).replace(/\b(-?\d+(?:\.\d+)?)\b/g,a=>o(`<span style="color: ${t.number};">${a}</span>`));return r=r.replace(/(&quot;[^&]*?&quot;|&#39;[^&]*?&#39;)/g,a=>o(`<span style="color: ${t.string};">${a}</span>`)),this.restoreHighlightTokens(r,i)}_highlightXML(e,t){return this._highlightHTML(e,t)}_highlightJSX(e,t){const n=[],i=e.replace(/<\/?[A-Za-z][\w.:-]*(?:\s+[^<>]*?)?\/?>/g,o=>{const r=n.length,a=this.escapeHTML(o).replace(/(&lt;\/?)([A-Za-z][\w.:-]*)([\s\S]*?)(\/?&gt;)/,(l,c,h,u,d)=>{const g=String(u||"").replace(/([A-Za-z_:][\w:.-]*)(\s*=\s*)/g,`<span style="color: ${t.attrName};">$1</span>$2`);return`${c}<span style="color: ${t.tag};">${h}</span>${g}${d}`});return n.push(a),`jsx${r}`});return this._highlightJS(i,t).replace(/\u0004jsx(\d+)\u0004/g,(o,r)=>n[Number(r)]||"")}_highlightEJS(e,t){const n=[],i=e.replace(/<%[\s\S]*?%>/g,o=>{const r=n.length;return n.push(`<span style="color: ${t.keyword};">${this.escapeHTML(o)}</span>`),`ejs${r}`});return this._highlightHTML(i,t).replace(/\u0003ejs(\d+)\u0003/g,(o,r)=>n[Number(r)]||"")}_highlightDockerfile(e,t){return this.unescapeEntitiesRepeated(e).split(`
217
- `).map(n=>{const i=this.escapeHTML(n);return/^\s*#/.test(n)?`<span style="color: ${t.comment};">${i}</span>`:i.replace(/^(\s*)(FROM|RUN|CMD|LABEL|MAINTAINER|EXPOSE|ENV|ADD|COPY|ENTRYPOINT|VOLUME|USER|WORKDIR|ARG|ONBUILD|STOPSIGNAL|HEALTHCHECK|SHELL)(\b)/i,(o,r,a,l)=>`${r}<span style="color: ${t.keyword};">${a}</span>${l}`)}).join(`
218
- `)}_highlightJS(e,t){const n=this.unescapeEntitiesRepeated(e);this.escapeHTML(n);const i=[],o=d=>{let g="",f=d;do g=String.fromCharCode(97+f%26)+g,f=Math.floor(f/26)-1;while(f>=0);return g||"a"},r=d=>`\0${o(d)}\0`,a=d=>{const g=i.length;return i.push(d),r(g)};let l;const c=/(\/\*[\s\S]*?\*\/)|(\/\/[^\n\r]*)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)/g;let h=0,u="";for(;l=c.exec(n);){const d=l.index;h<d&&(u+=this.escapeHTML(n.slice(h,d)));const g=l[0];/^\/\*/.test(g)||/^\/\//.test(g)?u+=a(`<span style="color: ${t.comment};">${this.escapeHTML(g)}</span>`):u+=a(`<span style="color: ${t.string};">${this.escapeHTML(g)}</span>`),h=c.lastIndex}return h<n.length&&(u+=this.escapeHTML(n.slice(h))),u=u.replace(/\b(0x[0-9a-fA-F]+|\d+\.?\d*|\d*\.\d+)\b/g,(d,g,f)=>{const p=u[f-1]||"",m=u[f+d.length]||"";return p==="&"||p==="#"||m===";"||m==="#"?d:`<span style="color: ${t.number};">${d}</span>`}),u=u.replace(/\b(const|let|var|function|class|if|else|return|for|while|switch|case|break|import|from|export|extends|new|try|catch|finally|throw|await|async|interface|type)\b/g,`<span style="color: ${t.keyword};">$1</span>`),u.replace(/\u0000([a-z]+)\u0000/g,(d,g)=>{let f=0;for(let p=0;p<g.length;p++)f=f*26+(g.charCodeAt(p)-97+1);return f=f-1,i[f]||""})}_highlightPHP(e,t){const n=this.unescapeEntitiesRepeated(e);let i=this.escapeHTML(n);const o=[],r=f=>{let p="",m=f;do p=String.fromCharCode(97+m%26)+p,m=Math.floor(m/26)-1;while(m>=0);return p||"a"},a=f=>{const p=o.length;return o.push(f),`\0${r(p)}\0`},l=(f,p)=>{const m=i.indexOf(f);return m===-1?!1:(i=i.slice(0,m)+p+i.slice(m+f.length),!0)};let c;const h=/\/\*[\s\S]*?\*\//g,u=/\/\/[^\n\r]*/g,d=/\#([^\n\r]*)/g,g=/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g;for(;c=h.exec(n);){const f=c[0];l(this.escapeHTML(f),a(`<span style="color: ${t.comment};">${this.escapeHTML(f)}</span>`))}for(;c=u.exec(n);){const f=c[0];l(this.escapeHTML(f),a(`<span style="color: ${t.comment};">${this.escapeHTML(f)}</span>`))}for(;c=d.exec(n);){const f=c[0];l(this.escapeHTML(f),a(`<span style="color: ${t.comment};">${this.escapeHTML(f)}</span>`))}for(;c=g.exec(n);){const f=c[0];l(this.escapeHTML(f),a(`<span style="color: ${t.string};">${this.escapeHTML(f)}</span>`))}return i=i.replace(/(&lt;\?(?:php\b|=)?|\?&gt;)/gi,f=>a(`<span style="color: ${t.keyword};">${f}</span>`)),i=i.replace(/(\$[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)/g,`<span style="color: ${t.variable};">$1</span>`),i=i.replace(/\b(echo|print|function|class|if|else|elseif|foreach|as|return|namespace|use|new|extends|public|protected|private|static)\b/g,`<span style="color: ${t.keyword};">$1</span>`),i=i.replace(/\u0000([a-z]+)\u0000/g,(f,p)=>{let m=0;for(let b=0;b<p.length;b++)m=m*26+(p.charCodeAt(b)-97+1);return m=m-1,o[m]||""}),i}shouldHighlight(e){return/<\/?[\w:-]+|<!--/.test(e)}destroy(){this.editor=null,this.modes.clear()}}function li(s,e){const t={...e};return t.extensions||(t.extensions=[]),t.extensions.some(n=>n.name==="keymap")||t.extensions.unshift(new Xn(t.keymap)),t.extensions.some(n=>n.name==="transaction")||t.extensions.unshift(new Yn),new Qn(s,t)}const ye='[data-theme="dark"], .dark, .editora-theme-dark',ci=`/* Source Editor Dialog Styles */
213
+ `,r.textContent=o.text,i.appendChild(r)}t.replaceChildren(i),t.__lceFoldPlaceholderSources=n,this.editor.getView().syncTrailingNewlineMarkerForText(e.text)}getFoldPlaceholder(e){const t=Math.max(1,e.end.line-e.start.line);return` … ${t} ${t===1?"line":"lines"} … `}pruneInvalidFolds(e,t){if(!this.editor)return;const n=this.editor.getFolds().filter(c=>c.collapsed!==!1),i=new Set(n.map(c=>this.getFoldKey(c))),o=[],r=new Set,a=this.getLineInfo(e);for(const c of n){const h=this.findReplacementFold(c,t.get(this.getFoldKey(c)),r,e,a);if(!h)continue;const d=this.getFoldKey(h);o.push(h),r.add(d)}const l=new Set(o.map(c=>this.getFoldKey(c)));for(const c of n)l.has(this.getFoldKey(c))||this.editor.unfold(c);for(const c of o)i.has(this.getFoldKey(c))||this.editor.fold(c)}getActiveFolds(){return this.editor?this.editor.getFolds().filter(e=>e.collapsed!==!1):[]}hasActiveFolds(){return this.getActiveFolds().length>0}getRenderableActiveFolds(){return this.getTopLevelFoldRegions(this.getActiveFolds())}getTopLevelFoldRegions(e){const t=[...e].sort((i,o)=>this.comparePositions(i.start,o.start)),n=[];for(const i of t){const o=n[n.length-1];o&&this.containsRange(o,i)||n.push(i)}return n}toDisplayLine(e,t){let n=0;for(const i of t){if(this.isSameRange(i,e))break;if(this.containsRange(i,e))return null;i.end.line<=e.start.line&&(n+=i.end.line-i.start.line)}return e.start.line-n}findBestRegionForLine(e,t){const i=(t?this.getActiveFolds():this.foldRegions).filter(o=>o.start.line<=e&&o.end.line>=e);return i.length===0?null:(i.sort((o,r)=>{const a=o.end.line-o.start.line,l=r.end.line-r.start.line;return a!==l?a-l:this.comparePositions(o.start,r.start)}),i[0])}findReplacementFold(e,t,n,i,o){const r=this.getFoldKey(e),a=this.foldRegions.find(u=>this.getFoldKey(u)===r&&!n.has(r));if(a)return a;const l=e.end.line-e.start.line,c=t!=null?t:this.createFoldSnapshot(e,i,o),d=this.foldRegions.filter(u=>!n.has(this.getFoldKey(u))).map(u=>{const g=this.createFoldSnapshot(u,i,o),m=c&&(g==null?void 0:g.startLineText)===c.startLineText?1:0,b=c&&(g==null?void 0:g.endLineText)===c.endLineText?1:0,v=c&&(g==null?void 0:g.lineSpan)===c.lineSpan?1:0;return{region:u,overlaps:this.lineRangeOverlap(e,u),lineDistance:Math.abs(u.start.line-e.start.line)+Math.abs(u.end.line-e.end.line),spanDistance:Math.abs(u.end.line-u.start.line-l),columnDistance:Math.abs(u.start.column-e.start.column)+Math.abs(u.end.column-e.end.column),hiddenTextMatch:c&&(g==null?void 0:g.hiddenText)===c.hiddenText?1:0,boundaryMatchScore:m+b+v}}).sort((u,g)=>u.hiddenTextMatch!==g.hiddenTextMatch?g.hiddenTextMatch-u.hiddenTextMatch:u.boundaryMatchScore!==g.boundaryMatchScore?g.boundaryMatchScore-u.boundaryMatchScore:u.overlaps!==g.overlaps?g.overlaps-u.overlaps:u.lineDistance!==g.lineDistance?u.lineDistance-g.lineDistance:u.spanDistance!==g.spanDistance?u.spanDistance-g.spanDistance:u.columnDistance-g.columnDistance)[0];if(!d)return null;const f=d.lineDistance<=2&&d.spanDistance<=1;return!(d.hiddenTextMatch===1||d.boundaryMatchScore>=2)&&!f?null:d.region}lineRangeOverlap(e,t){const n=Math.max(e.start.line,t.start.line),i=Math.min(e.end.line,t.end.line);return Math.max(0,i-n)}rememberActiveFoldSnapshots(e){const t=new Map,n=this.getLineInfo(e);for(const i of this.getActiveFolds()){const o=this.createFoldSnapshot(i,e,n);o&&t.set(this.getFoldKey(i),o)}this.foldSnapshots=t}createFoldSnapshot(e,t,n=this.getLineInfo(t)){var h,d;const{lineStarts:i,lines:o}=n;if(o.length===0)return null;const r=this.positionToOffset(e.start,i,o),a=this.positionToOffset(e.end,i,o),l=Math.max(0,Math.min(e.start.line,o.length-1)),c=Math.max(0,Math.min(e.end.line,o.length-1));return{hiddenText:t.slice(r,a),startLineText:(h=o[l])!=null?h:"",endLineText:(d=o[c])!=null?d:"",lineSpan:e.end.line-e.start.line}}withPreservedSelection(e){var l,c;if(!this.editor){e();return}const t=this.editor.getView(),n=t.getContentElement(),i=document.activeElement===n,o=t.getSelectionOffsets(),r=o.isInEditor;if(e(),!r)return;const a=this.remapSelectionOffsetsForVisibleDisplay((l=o.anchorOffset)!=null?l:o.startOffset,(c=o.focusOffset)!=null?c:o.endOffset);t.setSelectionBoundaryOffsets(a.startOffset,a.endOffset),(i||o.isInEditor)&&this.editor.focus()}remapSelectionOffsetsForVisibleDisplay(e,t){if(!this.editor)return{startOffset:e,endOffset:t};const n=this.editor.getValue(),{lineStarts:i,lines:o}=this.getLineInfo(n),r=this.getRenderableActiveFolds();if(r.length===0){const a=n.length;return{startOffset:Math.max(0,Math.min(e,a)),endOffset:Math.max(0,Math.min(t,a))}}return{startOffset:this.remapOffsetToVisibleBoundary(e,r,i,o,n.length),endOffset:this.remapOffsetToVisibleBoundary(t,r,i,o,n.length)}}remapOffsetToVisibleBoundary(e,t,n,i,o){const r=Math.max(0,Math.min(e,o));for(const a of t){const l=this.positionToOffset(a.start,n,i),c=this.positionToOffset(a.end,n,i);if(r<=l||r>=c)continue;const h=r-l,d=c-r;return h<=d?l:c}return r}buildLineStarts(e){const t=e.split(`
214
+ `),n=new Array(t.length);let i=0;for(let o=0;o<t.length;o++)n[o]=i,i+=t[o].length+1;return{lineStarts:n,lines:t}}getLineInfo(e){var n;if(((n=this.cachedLineInfo)==null?void 0:n.text)===e)return this.cachedLineInfo;const t={text:e,...this.buildLineStarts(e)};return this.cachedLineInfo=t,t}offsetToLine(e,t,n){var l;const i=t.length>0?t[t.length-1]+(((l=n[n.length-1])==null?void 0:l.length)||0):0,o=Math.max(0,Math.min(e,i));let r=0,a=t.length-1;for(;r<=a;){const c=Math.floor((r+a)/2),h=t[c],d=c+1<t.length?t[c+1]:Number.POSITIVE_INFINITY;if(o<h){a=c-1;continue}if(o>=d){r=c+1;continue}return c}return Math.max(0,Math.min(r,t.length-1))}positionToOffset(e,t,n){var r;const i=Math.max(0,Math.min(e.line,n.length-1)),o=Math.max(0,Math.min(e.column,((r=n[i])==null?void 0:r.length)||0));return t[i]+o}comparePositions(e,t){return e.line!==t.line?e.line-t.line:e.column-t.column}containsRange(e,t){return this.comparePositions(e.start,t.start)<=0&&this.comparePositions(e.end,t.end)>=0&&!this.isSameRange(e,t)}isSameRange(e,t){return e.start.line===t.start.line&&e.start.column===t.start.column&&e.end.line===t.end.line&&e.end.column===t.end.column}isFoldActive(e){return this.getActiveFolds().some(t=>this.isSameRange(t,e))}isValidFoldRegion(e){return e.start.line<e.end.line&&(e.start.line!==e.end.line||e.start.column!==e.end.column)}getFoldKey(e){return`${e.start.line}:${e.start.column}-${e.end.line}:${e.end.column}`}destroy(){this.pendingUpdateRaf!==null&&(cancelAnimationFrame(this.pendingUpdateRaf),this.pendingUpdateRaf=null),this.editor&&this.changeHandler&&this.editor.off("change",this.changeHandler),this.foldingUI&&this.foldingUI.parentNode&&this.foldingUI.parentNode.removeChild(this.foldingUI),this.restoreFullDisplay(),this.changeHandler=null,this.lastSnapshot="",this.lastParsedText=null,this.foldingUI=null,this.foldRegions=[],this.cachedLineInfo=null,this.editor=null}}class oi{constructor(){this.name="syntax-highlighting",this.editor=null,this.currentTheme="dark",this.currentLanguage=null,this.modes=new Map}setup(e){this.editor=e,this.registerMode("html",{name:"html",highlight:(t,n)=>this._highlightHTML(t,n)}),this.registerMode("css",{name:"css",highlight:(t,n)=>this._highlightCSS(t,n)}),this.registerMode("javascript",{name:"javascript",highlight:(t,n)=>this._highlightJS(t,n)}),this.registerMode("js",{name:"javascript",highlight:(t,n)=>this._highlightJS(t,n)}),this.registerMode("jsx",{name:"jsx",highlight:(t,n)=>this._highlightJSX(t,n)}),this.registerMode("typescript",{name:"typescript",highlight:(t,n)=>this._highlightJS(t,n)}),this.registerMode("ts",{name:"typescript",highlight:(t,n)=>this._highlightJS(t,n)}),this.registerMode("tsx",{name:"tsx",highlight:(t,n)=>this._highlightJSX(t,n)}),this.registerMode("json",{name:"json",highlight:(t,n)=>this._highlightJSON(t,n)}),this.registerMode("markdown",{name:"markdown",highlight:(t,n)=>this._highlightMarkdown(t,n)}),this.registerMode("md",{name:"markdown",highlight:(t,n)=>this._highlightMarkdown(t,n)}),this.registerMode("bash",{name:"bash",highlight:(t,n)=>this._highlightShell(t,n)}),this.registerMode("shell",{name:"bash",highlight:(t,n)=>this._highlightShell(t,n)}),this.registerMode("sh",{name:"bash",highlight:(t,n)=>this._highlightShell(t,n)}),this.registerMode("zsh",{name:"bash",highlight:(t,n)=>this._highlightShell(t,n)}),this.registerMode("python",{name:"python",highlight:(t,n)=>this._highlightGenericCode(t,n,"python")}),this.registerMode("py",{name:"python",highlight:(t,n)=>this._highlightGenericCode(t,n,"python")}),this.registerMode("go",{name:"go",highlight:(t,n)=>this._highlightGenericCode(t,n,"go")}),this.registerMode("golang",{name:"go",highlight:(t,n)=>this._highlightGenericCode(t,n,"go")}),this.registerMode("c",{name:"c",highlight:(t,n)=>this._highlightGenericCode(t,n,"c")}),this.registerMode("cpp",{name:"cpp",highlight:(t,n)=>this._highlightGenericCode(t,n,"cpp")}),this.registerMode("c++",{name:"cpp",highlight:(t,n)=>this._highlightGenericCode(t,n,"cpp")}),this.registerMode("cc",{name:"cpp",highlight:(t,n)=>this._highlightGenericCode(t,n,"cpp")}),this.registerMode("cxx",{name:"cpp",highlight:(t,n)=>this._highlightGenericCode(t,n,"cpp")}),this.registerMode("java",{name:"java",highlight:(t,n)=>this._highlightGenericCode(t,n,"java")}),this.registerMode("csharp",{name:"csharp",highlight:(t,n)=>this._highlightGenericCode(t,n,"csharp")}),this.registerMode("cs",{name:"csharp",highlight:(t,n)=>this._highlightGenericCode(t,n,"csharp")}),this.registerMode("rust",{name:"rust",highlight:(t,n)=>this._highlightGenericCode(t,n,"rust")}),this.registerMode("rs",{name:"rust",highlight:(t,n)=>this._highlightGenericCode(t,n,"rust")}),this.registerMode("ruby",{name:"ruby",highlight:(t,n)=>this._highlightGenericCode(t,n,"ruby")}),this.registerMode("rb",{name:"ruby",highlight:(t,n)=>this._highlightGenericCode(t,n,"ruby")}),this.registerMode("sql",{name:"sql",highlight:(t,n)=>this._highlightGenericCode(t,n,"sql")}),this.registerMode("yaml",{name:"yaml",highlight:(t,n)=>this._highlightYAML(t,n)}),this.registerMode("yml",{name:"yaml",highlight:(t,n)=>this._highlightYAML(t,n)}),this.registerMode("xml",{name:"xml",highlight:(t,n)=>this._highlightXML(t,n)}),this.registerMode("svg",{name:"xml",highlight:(t,n)=>this._highlightXML(t,n)}),this.registerMode("vue",{name:"vue",highlight:(t,n)=>this._highlightHTML(t,n)}),this.registerMode("ejs",{name:"ejs",highlight:(t,n)=>this._highlightEJS(t,n)}),this.registerMode("dockerfile",{name:"dockerfile",highlight:(t,n)=>this._highlightDockerfile(t,n)}),this.registerMode("docker",{name:"dockerfile",highlight:(t,n)=>this._highlightDockerfile(t,n)}),this.registerMode("php",{name:"php",highlight:(t,n)=>this._highlightPHP(t,n)}),e.registerCommand("setSyntaxLanguage",t=>{this.setLanguage(t),this.refreshEditorHighlight()})}setTheme(e){this.currentTheme=e}setLanguage(e){this.currentLanguage=e}registerMode(e,t){this.modes.set(e.toLowerCase(),t)}getSyntaxColors(){return this.currentTheme==="dark"?{tag:"#569cd6",comment:"#6a9955",attrName:"#9cdcfe",attrValue:"#ce9178",styleProp:"#c586c0",styleVal:"#dcdcaa",doctype:"#808080",text:"#d4d4d4",keyword:"#c586c0",string:"#ce9178",number:"#b5cea8",variable:"#9cdcfe"}:{tag:"#0000ff",comment:"#008000",attrName:"#001080",attrValue:"#a31515",styleProp:"#6a00a8",styleVal:"#804000",doctype:"#444444",text:"#000000",keyword:"#000080",string:"#a31515",number:"#0086b3",variable:"#001080"}}highlight(e,t){const n=this.getSyntaxColors(),i=this.normalizeLanguageId(t||this.currentLanguage||this.detectLanguage(e)||"html");return(this.modes.get(i)||this.modes.get("html")).highlight(e,n)}highlightHTML(e){return this.highlight(e,"html")}escapeHTML(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;").replace(/'/g,"&#39;")}normalizeLanguageId(e){const t=e.trim().toLowerCase().replace(/^\./,"");return{cjs:"javascript",js:"javascript",javascriptreact:"javascript",jsx:"jsx",mjs:"javascript",mts:"typescript",ts:"typescript",tsx:"tsx",typescriptreact:"tsx",md:"markdown",mdx:"markdown",shell:"bash",sh:"bash",zsh:"bash",console:"bash",terminal:"bash",docker:"dockerfile",dockerfile:"dockerfile",golang:"go",py:"python",cxx:"cpp",cc:"cpp","c++":"cpp",cs:"csharp",rs:"rust",rb:"ruby",yml:"yaml",svg:"xml",vue:"vue",ejs:"ejs"}[t]||t||"html"}restoreHighlightTokens(e,t){return e.replace(/\u0000([a-z]+)\u0000/g,(n,i)=>{let o=0;for(let r=0;r<i.length;r++)o=o*26+(i.charCodeAt(r)-97+1);return o=o-1,t[o]||""})}createTokenStore(e){const t=n=>{let i="",o=n;do i=String.fromCharCode(97+o%26)+i,o=Math.floor(o/26)-1;while(o>=0);return i||"a"};return n=>{const i=e.length;return e.push(n),`\0${t(i)}\0`}}refreshEditorHighlight(){const e=this.editor;e!=null&&e.renderTextWithHighlight&&e.renderTextWithHighlight(e.getValue(),!0)}unescapeEntitiesRepeated(e){let t=e||"";for(let n=0;n<5;n++){const i=t;if(t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'"),t===i)break}return t}detectLanguage(e){const t=e.trim();if(!t)return null;if(/^<\?(?:php\b|=)/i.test(t)||/^\?php\b/i.test(t))return"php";if(/^[\[{]/.test(t)&&/[\]}]$/.test(t)||/"[^"]+"\s*:/.test(t))try{return JSON.parse(t),"json"}catch(c){}const n=/<\/?[A-Za-z][\w:-]*(?:\s|>|\/>)/.test(t),i=/^<!DOCTYPE\s+html\b/i.test(t)||/<\/?(html|head|body|meta|title|style|script)\b/i.test(t);if([/^---\s*\n[\s\S]*?\n---\s*(?:\n|$)/.test(t),/^#{1,6}\s+\S/m.test(t),/^\s*```/m.test(t),/^\s*~~~/m.test(t),/^\s{0,3}>\s+/m.test(t),/^\s{0,3}(?:[-*+]|\d+\.)\s+\S/m.test(t),/^\s{0,3}[-*+]\s+\[[ xX]\]\s+\S/m.test(t),/\[[^\]\n]+\]\([^)]+\)/.test(t),/!\[[^\]\n]*\]\([^)]+\)/.test(t),/(^|\n)\s*\|.+\|\s*\n\s*\|[\s:-]+\|/m.test(t),/(^|\s)(?:\*\*|__)[^*_]+(?:\*\*|__)(?=\s|$|[.,;:!?])/m.test(t)].filter(Boolean).length>=(n?2:1))return"markdown";if(i)return"html";const a=this.detectProgrammingLanguage(t);if(a)return a;const l=/[{][\s\S]*[}]/.test(t)&&/[A-Za-z_-][\w-]*\s*:\s*[^;{}]+;?/.test(t)&&!/\b(function|const|let|var|return|class|interface|type)\b/.test(t);return!n&&l?"css":null}detectProgrammingLanguage(e){const t={php:0,python:0,go:0,cpp:0,c:0,java:0,csharp:0,rust:0,ruby:0,sql:0,yaml:0,dockerfile:0},n=(r,a,l=1)=>{a.test(e)&&(t[r]+=l)};n("python",/^\s*(from\s+\w+\s+import|import\s+\w+|def\s+\w+\s*\(|class\s+\w+|for\s+\w+\s+in\s+.+:|if\s+.+:|while\s+.+:|print\s*\()/m,2),n("python",/^\s*[A-Za-z_]\w*\s*=\s*(?:\[|\{|\(|["']|\d)/m),n("python",/\b(True|False|None|self|elif|lambda|yield)\b/),n("go",/^\s*package\s+\w+/m,3),n("go",/\bfunc\s+\w+\s*\(/,2),n("go",/\b(import|defer|goroutine|chan|struct|interface)\b/),n("cpp",/^\s*#include\s*<[^>]+>/m,2),n("cpp",/\b(std::|template\s*<|namespace\s+\w+|cout\s*<<|cin\s*>>)\b/,2),n("cpp",/\b(class|public|private|protected|virtual|typename)\b/),n("c",/^\s*#include\s*[<"][^>"]+[>"]/m),n("c",/\b(int|char|float|double|void)\s+\w+\s*\(/),n("c",/\bprintf\s*\(/),n("java",/^\s*(package|import)\s+[\w.]+;/m,2),n("java",/\b(public|private|protected)\s+(class|interface|enum)\s+\w+/,2),n("java",/\bSystem\.out\.println\s*\(/),n("csharp",/^\s*using\s+[\w.]+;/m,2),n("csharp",/\b(namespace|record|var|string|Console\.WriteLine)\b/),n("csharp",/\b(public|private|protected)\s+(class|interface|struct)\s+\w+/),n("rust",/\bfn\s+\w+\s*\(/,2),n("rust",/\b(let\s+mut|impl\s+\w+|use\s+[\w:]+|println!\s*\()/),n("rust",/\b(crate|trait|enum|match|Some|None|Ok|Err)\b/),n("ruby",/^\s*(def|class|module)\s+\w+/m,2),n("ruby",/\b(puts|require|attr_reader|elsif|end)\b/),n("sql",/^\s*(SELECT|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP)\b/im,3),n("sql",/\bFROM\s+\w+|\bWHERE\s+/i),n("yaml",/^---\s*$/m),n("yaml",/^\s*[A-Za-z0-9_.-]+\s*:\s+\S/m,2),n("yaml",/^\s*-\s+[A-Za-z0-9_.-]+\s*:/m),n("dockerfile",/^\s*FROM\s+\S+/im,3),n("dockerfile",/^\s*(RUN|COPY|ADD|CMD|ENTRYPOINT|WORKDIR|ENV|ARG)\b/im,2),n("php",/^<\?(?:php\b|=)/i,3),n("php",/^\?php\b/i,3),n("php",/\$[A-Za-z_\x80-\xff][A-Za-z0-9_\x80-\xff]*\s*=/,2),n("php",/\b(echo|foreach|function|namespace|use|PHP_EOL)\b/,2);const[i,o]=Object.entries(t).sort((r,a)=>a[1]-r[1])[0]||["",0];return o>=2?i:null}_highlightHTML(e,t){const n=t,i=f=>this.escapeHTML(f),o=[],r=this.createTokenStore(o),a=[],l=f=>{const p=a.length;return a.push(f),`ht${p}`};let c=i(e);c=c.replace(/&lt;\/?(?:(?!&gt;)[^\n\r<])*?(?=$|[\n\r])/g,f=>l(f));const h=[];try{e.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,(f,p,u)=>(h.push({attrs:String(p||""),inner:String(u||"")}),f))}catch(f){}let d=0;return c=c.replace(/(&lt;script\b([^&>]*)&gt;)([\s\S]*?)(&lt;\/script&gt;)/gi,(f,p,u,g,m)=>{var C,w,E;const b=(w=(C=h[d++])==null?void 0:C.inner)!=null?w:this.unescapeEntitiesRepeated(g||"");(((E=h[d-1])==null?void 0:E.attrs)||u||"").toLowerCase();const v=this._highlightJS(b,n);return`${p}${v}${m}`}),c=c.replace(/(&lt;style\b[^&]*&gt;)([\s\S]*?)(&lt;\/style&gt;)/gi,(f,p,u,g)=>{const m=this._highlightCSS(this.unescapeEntitiesRepeated(u),n);return`${p}${m}${g}`}),c=c.replace(/(&lt;!--[\s\S]*?--&gt;)/g,f=>r(`<span style="color: ${n.comment};">${f}</span>`)),c=c.replace(/(&lt;!DOCTYPE[\s\S]*?&gt;)/i,f=>r(`<span style="color: ${n.doctype};">${f}</span>`)),c=c.replace(/(&lt;\/?\s*)([^\s&>\/]+)([^<]*?)(\/?&gt;)/g,(f,p,u,g,m)=>{const b=`<span style="color: ${n.tag};">${u}</span>`;let v=g;return v=v.replace(/([\w:-]+)(\s*=\s*)((&quot;[\s\S]*?&quot;|&#39;[\s\S]*?&#39;|[^\s&>]+))/g,(C,w,E,S)=>{const N=String(w).toLowerCase(),_=`<span style="color: ${n.attrName};">${w}</span>`;let D=S,k="";S.startsWith("&quot;")&&S.endsWith("&quot;")?(D=S.slice(6,-6),k="&quot;"):S.startsWith("&#39;")&&S.endsWith("&#39;")&&(D=S.slice(5,-5),k="&#39;");let M=S;if(N==="style"){const G=D.replace(/([\w-]+)\s*:\s*([^;]+)(;?)/g,(se,R,ae,P)=>`<span style="color: ${n.styleProp};">${R}</span>:<span style="color: ${n.styleVal};">${ae}</span>${P}`);k?M=`${k}${G}${k}`:M=G,M=`<span style="color: ${n.attrValue};">${M}</span>`}else k&&(M=`${k}${D}${k}`),M=`<span style="color: ${n.attrValue};">${M}</span>`;return`${_}${E}${M}`}),`${p}${b}${v}${m}`}),c=c.replace(/\u0002ht(\d+)\u0002/g,(f,p)=>a[Number(p)]||""),this.restoreHighlightTokens(c,o)}_highlightCSS(e,t){const n=this.unescapeEntitiesRepeated(e),i=[],o=this.createTokenStore(i),r=/(\/\*[\s\S]*?\*\/)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g;let a=0,l="",c;for(;c=r.exec(n);){a<c.index&&(l+=this.escapeHTML(n.slice(a,c.index)));const h=c[0],d=h.startsWith("/*")?t.comment:t.string;l+=o(`<span style="color: ${d};">${this.escapeHTML(h)}</span>`),a=r.lastIndex}return a<n.length&&(l+=this.escapeHTML(n.slice(a))),l=l.replace(/(@[\w-]+)/g,h=>o(`<span style="color: ${t.keyword};">${h}</span>`)),l=l.replace(/([A-Za-z_-][\w-]*)(\s*:)/g,(h,d,f)=>`${o(`<span style="color: ${t.styleProp};">${d}</span>`)}${f}`),l=l.replace(/(#(?:[0-9a-fA-F]{3,8})\b)/g,h=>o(`<span style="color: ${t.number};">${h}</span>`)),l=l.replace(/\b(-?\d*\.?\d+(?:px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|turn|fr)?)\b/g,h=>o(`<span style="color: ${t.number};">${h}</span>`)),l=l.replace(/\b(important|inherit|initial|unset|revert|auto|none|block|inline|flex|grid|absolute|relative|fixed|sticky)\b/g,h=>o(`<span style="color: ${t.styleVal};">${h}</span>`)),this.restoreHighlightTokens(l,i)}_highlightJSON(e,t){const n=this.unescapeEntitiesRepeated(e),i=/("(?:\\.|[^"\\])*")(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}\[\],:]/g;let o=0,r="",a;for(;a=i.exec(n);){o<a.index&&(r+=this.escapeHTML(n.slice(o,a.index)));const l=a[0],c=a[1],h=a[2]||"",d=a[3];if(c){const f=h?t.attrName:t.string;r+=`<span style="color: ${f};">${this.escapeHTML(c)}</span>${this.escapeHTML(h)}`}else d?r+=`<span style="color: ${t.keyword};">${l}</span>`:/^-?\d/.test(l)?r+=`<span style="color: ${t.number};">${l}</span>`:r+=`<span style="color: ${t.tag};">${this.escapeHTML(l)}</span>`;o=i.lastIndex}return o<n.length&&(r+=this.escapeHTML(n.slice(o))),r}_highlightMarkdown(e,t){var c;const i=this.unescapeEntitiesRepeated(e).split(`
215
+ `);let o=!1,r="",a="",l=((c=i[0])==null?void 0:c.trim())==="---";return i.map((h,d)=>{const f=[],p=this.createTokenStore(f);if(l){const m=h.trim()==="---",v=`<span style="color: ${m?t.keyword:t.attrName};">${this.escapeHTML(h)}</span>`;return d>0&&m&&(l=!1),v}const u=h.match(/^(\s*)(`{3,}|~{3,})(.*)$/);if(u){const m=u[2];return o=!(o&&m[0]===r[0]),r=o?m:"",a=o?this.extractMarkdownFenceLanguage(u[3]||""):"",[this.escapeHTML(u[1]),`<span style="color: ${t.keyword}; font-weight: 700;">${this.escapeHTML(m)}</span>`,`<span style="color: ${t.string};">${this.escapeHTML(u[3]||"")}</span>`].join("")}if(o)return this.highlightMarkdownFenceLine(h,a,t);let g=this.escapeHTML(h).replace(/(`[^`]+`)/g,m=>p(`<span style="color: ${t.string}; background: rgba(148, 163, 184, 0.16); border-radius: 3px;">${m}</span>`)).replace(/(!?\[[^\]\n]*\])(\([^)]+\))/g,(m,b,v)=>p(`<span style="color: ${t.attrName};">${b}</span><span style="color: ${t.attrValue};">${v}</span>`)).replace(/(\*\*|__)(.+?)\1/g,(m,b,v)=>p(`<span style="color: ${t.keyword};">${b}</span><span style="color: ${t.tag}; font-weight: 700;">${v}</span><span style="color: ${t.keyword};">${b}</span>`)).replace(/(~~)(.+?)\1/g,(m,b,v)=>p(`<span style="color: ${t.keyword};">${b}</span><span style="color: ${t.comment}; text-decoration: line-through;">${v}</span><span style="color: ${t.keyword};">${b}</span>`)).replace(/(\*|_)([^*_]+?)\1/g,(m,b,v)=>p(`<span style="color: ${t.keyword};">${b}</span><span style="color: ${t.styleVal}; font-style: italic;">${v}</span><span style="color: ${t.keyword};">${b}</span>`));return g=g.replace(/^(\s{0,3}#{1,6})(\s+.*)?$/,(m,b,v="")=>`<span style="color: ${t.keyword}; font-weight: 700;">${b}</span><span style="color: ${t.tag}; font-weight: 700;">${v}</span>`),g=g.replace(/^(\s{0,3})((?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/,(m,b,v)=>`${b}<span style="color: ${t.comment};">${v}</span>`),g=g.replace(/^(\s{0,3}&gt;)(.*)$/,(m,b,v)=>`<span style="color: ${t.comment};">${b}</span>${v}`),g=g.replace(/^(\s*)([-*+])(\s+\[[ xX]\])(\s+)/,(m,b,v,C,w)=>`${b}<span style="color: ${t.keyword};">${v}</span><span style="color: ${t.attrName};">${C}</span>${w}`),g=g.replace(/^(\s*)([-*+]|\d+\.)(\s+)/,(m,b,v,C)=>`${b}<span style="color: ${t.keyword};">${v}</span>${C}`),g=g.replace(/^(\s*\|.*\|\s*)$/,m=>m.replace(/\|/g,b=>`<span style="color: ${t.keyword};">${b}</span>`)),this.restoreHighlightTokens(g,f)}).join(`
216
+ `)}extractMarkdownFenceLanguage(e){var n;const t=((n=e.trim().match(/^([A-Za-z0-9_+.#-]+)/))==null?void 0:n[1])||"";return t?this.normalizeLanguageId(t):""}highlightMarkdownFenceLine(e,t,n){const i=t?this.modes.get(t):void 0;return!i||i.name==="markdown"?`<span style="color: ${n.text};">${this.escapeHTML(e)}</span>`:i.highlight(e,n)}_highlightShell(e,t){const n=this.unescapeEntitiesRepeated(e),i=[],o=this.createTokenStore(i),r=/(#[^\n\r]*)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|(\$\{?[A-Za-z_][\w]*\}?|\$[0-9@#?$*!])/g;let a=0,l="",c;for(;c=r.exec(n);){a<c.index&&(l+=this.escapeHTML(n.slice(a,c.index)));const h=c[0],d=h.startsWith("#")?t.comment:h.startsWith("$")?t.variable:t.string;l+=o(`<span style="color: ${d};">${this.escapeHTML(h)}</span>`),a=r.lastIndex}return a<n.length&&(l+=this.escapeHTML(n.slice(a))),l=l.replace(/(^|\s)(--?[A-Za-z0-9][\w-]*)(?=\s|=|$)/g,(h,d,f)=>`${d}${o(`<span style="color: ${t.attrName};">${f}</span>`)}`),l=l.replace(/\b(if|then|else|elif|fi|for|while|until|do|done|case|esac|function|export|unset|alias|source|return|in)\b/g,h=>o(`<span style="color: ${t.keyword};">${h}</span>`)),l=l.replace(/(^|\s)(npm|npx|pnpm|yarn|bun|node|git|cd|mkdir|touch|cp|mv|rm|cat|grep|rg|find|curl|wget|echo|printf|sudo|chmod|chown|docker|kubectl)(?=\s|$)/g,(h,d,f)=>`${d}${o(`<span style="color: ${t.tag};">${f}</span>`)}`),this.restoreHighlightTokens(l,i)}getLanguageKeywords(e){const t=["true","false","null","nil","none"];return[...{python:["and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","self","True","False","None"],go:["break","case","chan","const","continue","defer","default","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],c:["auto","break","case","char","const","continue","default","do","double","else","enum","extern","float","for","goto","if","inline","int","long","register","restrict","return","short","signed","sizeof","static","struct","switch","typedef","union","unsigned","void","volatile","while"],cpp:["alignas","alignof","auto","bool","break","case","catch","char","class","concept","const","constexpr","continue","decltype","default","delete","do","double","else","enum","explicit","export","extern","false","float","for","friend","if","inline","int","long","namespace","new","noexcept","nullptr","operator","private","protected","public","requires","return","short","signed","sizeof","static","struct","switch","template","this","throw","true","try","typedef","typename","union","unsigned","using","virtual","void","volatile","while"],java:["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","final","finally","float","for","if","implements","import","instanceof","int","interface","long","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","try","void","volatile","while"],csharp:["abstract","as","async","await","base","bool","break","case","catch","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","get","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","out","override","params","private","protected","public","readonly","record","ref","return","sealed","set","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","using","var","virtual","void","volatile","while","yield"],rust:["as","async","await","break","const","continue","crate","dyn","else","enum","extern","false","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","Self","static","struct","super","trait","true","type","unsafe","use","where","while"],ruby:["BEGIN","END","alias","and","begin","break","case","class","def","defined?","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield"],sql:["ADD","ALTER","AND","AS","ASC","BETWEEN","BY","CASE","CREATE","DELETE","DESC","DISTINCT","DROP","ELSE","END","EXISTS","FROM","GROUP","HAVING","IN","INDEX","INNER","INSERT","INTO","IS","JOIN","LEFT","LIKE","LIMIT","NOT","NULL","ON","OR","ORDER","OUTER","PRIMARY","RIGHT","SELECT","SET","TABLE","THEN","UNION","UPDATE","VALUES","WHEN","WHERE"]}[e]||[],...t]}_highlightGenericCode(e,t,n){const i=this.unescapeEntitiesRepeated(e),o=[],r=this.createTokenStore(o),a=n==="python"||n==="ruby"||n==="sql"?"#[^\\n\\r]*|--[^\\n\\r]*":"\\/\\*[\\s\\S]*?\\*\\/|\\/\\/[^\\n\\r]*",l=new RegExp(`(${a})|("(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`)`,"g");let c=0,h="",d;for(;d=l.exec(i);){c<d.index&&(h+=this.escapeHTML(i.slice(c,d.index)));const p=d[0],u=p.startsWith("//")||p.startsWith("/*")||p.startsWith("#")||p.startsWith("--")?t.comment:t.string;h+=r(`<span style="color: ${u};">${this.escapeHTML(p)}</span>`),c=l.lastIndex}c<i.length&&(h+=this.escapeHTML(i.slice(c)));const f=Array.from(new Set(this.getLanguageKeywords(n)));if(f.length>0){const p=new RegExp(`\\b(${f.map(u=>u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")})\\b`,n==="sql"?"gi":"g");h=h.replace(p,u=>r(`<span style="color: ${t.keyword};">${u}</span>`))}return h=h.replace(/\b([A-Z][A-Za-z0-9_]*|[A-Za-z_][\w]*(?=\s*\())\b/g,p=>r(`<span style="color: ${t.tag};">${p}</span>`)),h=h.replace(/\b(-?0x[0-9a-fA-F]+|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)(?:[uUlLfFdD]*)\b/g,p=>r(`<span style="color: ${t.number};">${p}</span>`)),h=h.replace(/(@[A-Za-z_][\w]*|#[A-Za-z_][\w]*|::[A-Za-z_][\w]*)/g,p=>r(`<span style="color: ${t.attrName};">${p}</span>`)),this.restoreHighlightTokens(h,o)}_highlightYAML(e,t){const n=this.unescapeEntitiesRepeated(e),i=[],o=this.createTokenStore(i);let r=this.escapeHTML(n).replace(/(#.*)$/gm,a=>o(`<span style="color: ${t.comment};">${a}</span>`)).replace(/^(\s*[-?]?\s*)([A-Za-z0-9_.-]+)(\s*:)/gm,(a,l,c,h)=>`${l}${o(`<span style="color: ${t.attrName};">${c}</span>`)}${h}`).replace(/\b(true|false|null|yes|no|on|off)\b/gi,a=>o(`<span style="color: ${t.keyword};">${a}</span>`)).replace(/\b(-?\d+(?:\.\d+)?)\b/g,a=>o(`<span style="color: ${t.number};">${a}</span>`));return r=r.replace(/(&quot;[^&]*?&quot;|&#39;[^&]*?&#39;)/g,a=>o(`<span style="color: ${t.string};">${a}</span>`)),this.restoreHighlightTokens(r,i)}_highlightXML(e,t){return this._highlightHTML(e,t)}_highlightJSX(e,t){const n=[],i=e.replace(/<\/?[A-Za-z][\w.:-]*(?:\s+[^<>]*?)?\/?>/g,o=>{const r=n.length,a=this.escapeHTML(o).replace(/(&lt;\/?)([A-Za-z][\w.:-]*)([\s\S]*?)(\/?&gt;)/,(l,c,h,d,f)=>{const p=String(d||"").replace(/([A-Za-z_:][\w:.-]*)(\s*=\s*)/g,`<span style="color: ${t.attrName};">$1</span>$2`);return`${c}<span style="color: ${t.tag};">${h}</span>${p}${f}`});return n.push(a),`jsx${r}`});return this._highlightJS(i,t).replace(/\u0004jsx(\d+)\u0004/g,(o,r)=>n[Number(r)]||"")}_highlightEJS(e,t){const n=[],i=e.replace(/<%[\s\S]*?%>/g,o=>{const r=n.length;return n.push(`<span style="color: ${t.keyword};">${this.escapeHTML(o)}</span>`),`ejs${r}`});return this._highlightHTML(i,t).replace(/\u0003ejs(\d+)\u0003/g,(o,r)=>n[Number(r)]||"")}_highlightDockerfile(e,t){return this.unescapeEntitiesRepeated(e).split(`
217
+ `).map(i=>{const o=this.escapeHTML(i);return/^\s*#/.test(i)?`<span style="color: ${t.comment};">${o}</span>`:o.replace(/^(\s*)(FROM|RUN|CMD|LABEL|MAINTAINER|EXPOSE|ENV|ADD|COPY|ENTRYPOINT|VOLUME|USER|WORKDIR|ARG|ONBUILD|STOPSIGNAL|HEALTHCHECK|SHELL)(\b)/i,(r,a,l,c)=>`${a}<span style="color: ${t.keyword};">${l}</span>${c}`)}).join(`
218
+ `)}_highlightJS(e,t){const n=this.unescapeEntitiesRepeated(e);this.escapeHTML(n);const i=[],o=p=>{let u="",g=p;do u=String.fromCharCode(97+g%26)+u,g=Math.floor(g/26)-1;while(g>=0);return u||"a"},r=p=>`\0${o(p)}\0`,a=p=>{const u=i.length;return i.push(p),r(u)};let l;const c=/(\/\*[\s\S]*?\*\/)|(\/\/[^\n\r]*)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)/g;let h=0,d="";for(;l=c.exec(n);){const p=l.index;h<p&&(d+=this.escapeHTML(n.slice(h,p)));const u=l[0];/^\/\*/.test(u)||/^\/\//.test(u)?d+=a(`<span style="color: ${t.comment};">${this.escapeHTML(u)}</span>`):d+=a(`<span style="color: ${t.string};">${this.escapeHTML(u)}</span>`),h=c.lastIndex}return h<n.length&&(d+=this.escapeHTML(n.slice(h))),d=d.replace(/\b(0x[0-9a-fA-F]+|\d+\.?\d*|\d*\.\d+)\b/g,(p,u,g)=>{const m=d[g-1]||"",b=d[g+p.length]||"";return m==="&"||m==="#"||b===";"||b==="#"?p:`<span style="color: ${t.number};">${p}</span>`}),d=d.replace(/\b(const|let|var|function|class|if|else|return|for|while|switch|case|break|import|from|export|extends|new|try|catch|finally|throw|await|async|interface|type)\b/g,`<span style="color: ${t.keyword};">$1</span>`),d.replace(/\u0000([a-z]+)\u0000/g,(p,u)=>{let g=0;for(let m=0;m<u.length;m++)g=g*26+(u.charCodeAt(m)-97+1);return g=g-1,i[g]||""})}_highlightPHP(e,t){const n=this.unescapeEntitiesRepeated(e);let i=this.escapeHTML(n);const o=[],r=u=>{let g="",m=u;do g=String.fromCharCode(97+m%26)+g,m=Math.floor(m/26)-1;while(m>=0);return g||"a"},a=u=>{const g=o.length;return o.push(u),`\0${r(g)}\0`},l=(u,g)=>{const m=i.indexOf(u);return m===-1?!1:(i=i.slice(0,m)+g+i.slice(m+u.length),!0)};let c;const h=/\/\*[\s\S]*?\*\//g,d=/\/\/[^\n\r]*/g,f=/\#([^\n\r]*)/g,p=/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g;for(;c=h.exec(n);){const u=c[0];l(this.escapeHTML(u),a(`<span style="color: ${t.comment};">${this.escapeHTML(u)}</span>`))}for(;c=d.exec(n);){const u=c[0];l(this.escapeHTML(u),a(`<span style="color: ${t.comment};">${this.escapeHTML(u)}</span>`))}for(;c=f.exec(n);){const u=c[0];l(this.escapeHTML(u),a(`<span style="color: ${t.comment};">${this.escapeHTML(u)}</span>`))}for(;c=p.exec(n);){const u=c[0];l(this.escapeHTML(u),a(`<span style="color: ${t.string};">${this.escapeHTML(u)}</span>`))}return i=i.replace(/(&lt;\?(?:php\b|=)?|\?&gt;)/gi,u=>a(`<span style="color: ${t.keyword};">${u}</span>`)),i=i.replace(/(\$[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)/g,`<span style="color: ${t.variable};">$1</span>`),i=i.replace(/\b(echo|print|function|class|if|else|elseif|foreach|as|return|namespace|use|new|extends|public|protected|private|static)\b/g,`<span style="color: ${t.keyword};">$1</span>`),i=i.replace(/\u0000([a-z]+)\u0000/g,(u,g)=>{let m=0;for(let b=0;b<g.length;b++)m=m*26+(g.charCodeAt(b)-97+1);return m=m-1,o[m]||""}),i}shouldHighlight(e){return/<\/?[\w:-]+|<!--/.test(e)}destroy(){this.editor=null,this.modes.clear()}}function ri(s,e){const t={...e};return t.extensions||(t.extensions=[]),t.extensions.some(o=>o.name==="keymap")||t.extensions.unshift(new Qn(t.keymap)),t.extensions.some(o=>o.name==="transaction")||t.extensions.unshift(new xe),new ve(s,t)}const Ce='[data-theme="dark"], .dark, .editora-theme-dark',si=`/* Source Editor Dialog Styles */
219
219
  .rte-source-editor-overlay {
220
220
  position: fixed !important;
221
221
  top: 0 !important;
@@ -592,10 +592,10 @@
592
592
  flex: 1;
593
593
  text-align: center;
594
594
  }
595
- }`,hi=Object.freeze(Object.defineProperty({__proto__:null,CodePlugin:()=>({name:"code",toolbar:[{label:"Source",command:"toggleSourceView",icon:'<svg width="24" height="24" focusable="false"><g fill-rule="nonzero"><path d="M9.8 15.7c.3.3.3.8 0 1-.3.4-.9.4-1.2 0l-4.4-4.1a.8.8 0 0 1 0-1.2l4.4-4.2c.3-.3.9-.3 1.2 0 .3.3.3.8 0 1.1L6 12l3.8 3.7ZM14.2 15.7c-.3.3-.3.8 0 1 .4.4.9.4 1.2 0l4.4-4.1c.3-.3.3-.9 0-1.2l-4.4-4.2a.8.8 0 0 0-1.2 0c-.3.3-.3.8 0 1.1L18 12l-3.8 3.7Z"></path></g></svg>',shortcut:"Mod-Shift-S"}],commands:{toggleSourceView:()=>{const e=(()=>{var a,l,c;const o=window.getSelection();if(o&&o.anchorNode){let h=o.anchorNode instanceof HTMLElement?o.anchorNode:o.anchorNode.parentElement;for(;h;){if((a=h.classList)!=null&&a.contains("rte-content"))return h;h=h.parentElement}}if(document.activeElement){let h=document.activeElement;if((l=h.classList)!=null&&l.contains("rte-content"))return h;for(;h&&h!==document.body;){if((c=h.classList)!=null&&c.contains("rte-content"))return h;const u=h.querySelector(".rte-content");if(u)return u;h=h.parentElement}}const r=document.querySelector("[data-editora-editor]");if(r){const h=r.querySelector(".rte-content");if(h)return h}return document.querySelector(".rte-content")})();if(!e)return console.error("[CodePlugin] Editor content area not found"),alert("Editor content area not found. Please click inside the editor first."),!1;const t=e.innerHTML,n=o=>{let r="",a=0;const l=2,c=o.split(/(<\/?[a-zA-Z][^>]*>)/);for(const h of c)h.trim()&&(h.match(/^<\/[a-zA-Z]/)?(a=Math.max(0,a-1),r+=`
595
+ }`,ai=Object.freeze(Object.defineProperty({__proto__:null,CodePlugin:()=>({name:"code",toolbar:[{label:"Source",command:"toggleSourceView",icon:'<svg width="24" height="24" focusable="false"><g fill-rule="nonzero"><path d="M9.8 15.7c.3.3.3.8 0 1-.3.4-.9.4-1.2 0l-4.4-4.1a.8.8 0 0 1 0-1.2l4.4-4.2c.3-.3.9-.3 1.2 0 .3.3.3.8 0 1.1L6 12l3.8 3.7ZM14.2 15.7c-.3.3-.3.8 0 1 .4.4.9.4 1.2 0l4.4-4.1c.3-.3.3-.9 0-1.2l-4.4-4.2a.8.8 0 0 0-1.2 0c-.3.3-.3.8 0 1.1L18 12l-3.8 3.7Z"></path></g></svg>',shortcut:"Mod-Shift-S"}],commands:{toggleSourceView:()=>{const e=(()=>{var a,l,c;const o=window.getSelection();if(o&&o.anchorNode){let h=o.anchorNode instanceof HTMLElement?o.anchorNode:o.anchorNode.parentElement;for(;h;){if((a=h.classList)!=null&&a.contains("rte-content"))return h;h=h.parentElement}}if(document.activeElement){let h=document.activeElement;if((l=h.classList)!=null&&l.contains("rte-content"))return h;for(;h&&h!==document.body;){if((c=h.classList)!=null&&c.contains("rte-content"))return h;const d=h.querySelector(".rte-content");if(d)return d;h=h.parentElement}}const r=document.querySelector("[data-editora-editor]");if(r){const h=r.querySelector(".rte-content");if(h)return h}return document.querySelector(".rte-content")})();if(!e)return console.error("[CodePlugin] Editor content area not found"),alert("Editor content area not found. Please click inside the editor first."),!1;const t=e.innerHTML,n=o=>{let r="",a=0;const l=2,c=o.split(/(<\/?[a-zA-Z][^>]*>)/);for(const h of c)h.trim()&&(h.match(/^<\/[a-zA-Z]/)?(a=Math.max(0,a-1),r+=`
596
596
  `+" ".repeat(a*l)+h):h.match(/^<[a-zA-Z]/)&&!h.match(/\/>$/)?(r+=`
597
597
  `+" ".repeat(a*l)+h,a++):h.match(/^<[a-zA-Z].*\/>$/)?r+=`
598
- `+" ".repeat(a*l)+h:r+=h.trim());return r.trim()};return(()=>{const r=n(t);let a=null,l="dark",c=!1,h=!1,u=!1,d=!1;const g=!!e.closest(ye)||document.body.matches(ye)||document.documentElement.matches(ye),f=document.createElement("div");f.className="rte-source-editor-overlay",g&&f.classList.add("rte-theme-dark");const p=document.createElement("div");p.className="rte-source-editor-modal",p.setAttribute("role","dialog"),p.setAttribute("aria-modal","true"),p.setAttribute("aria-labelledby","source-editor-title");const m=document.createElement("div");m.className="rte-source-editor-header",m.innerHTML=`
598
+ `+" ".repeat(a*l)+h:r+=h.trim());return r.trim()};return(()=>{const r=n(t);let a=null,l="dark",c=!1,h=!1,d=!1,f=!1;const p=!!e.closest(Ce)||document.body.matches(Ce)||document.documentElement.matches(Ce),u=document.createElement("div");u.className="rte-source-editor-overlay",p&&u.classList.add("rte-theme-dark");const g=document.createElement("div");g.className="rte-source-editor-modal",g.setAttribute("role","dialog"),g.setAttribute("aria-modal","true"),g.setAttribute("aria-labelledby","source-editor-title");const m=document.createElement("div");m.className="rte-source-editor-header",m.innerHTML=`
599
599
  <h2 id="source-editor-title">Source Editor</h2>
600
600
  <div class="rte-source-editor-header-toolbar">
601
601
  <button class="rte-source-editor-toolbar-btn theme-toggle-btn" title="Switch theme">
@@ -631,7 +631,7 @@
631
631
  </svg>
632
632
  </button>
633
633
  </div>
634
- `;const b=document.createElement("div");b.className="rte-source-editor-body";const x=document.createElement("div");x.className="rte-source-editor-content";const C=document.createElement("div");C.className="rte-source-editor-warning",C.textContent="⚠️ Advanced users only. Invalid HTML may break the editor.";const w=document.createElement("div");w.className="rte-source-editor-light-editor",w.style.height="400px",x.appendChild(C),x.appendChild(w),b.appendChild(x);const S=document.createElement("div");if(S.className="rte-source-editor-footer",S.innerHTML=`
634
+ `;const b=document.createElement("div");b.className="rte-source-editor-body";const v=document.createElement("div");v.className="rte-source-editor-content";const C=document.createElement("div");C.className="rte-source-editor-warning",C.textContent="⚠️ Advanced users only. Invalid HTML may break the editor.";const w=document.createElement("div");w.className="rte-source-editor-light-editor",w.style.height="400px",v.appendChild(C),v.appendChild(w),b.appendChild(v);const E=document.createElement("div");if(E.className="rte-source-editor-footer",E.innerHTML=`
635
635
  <div class="rte-source-editor-footer-info">
636
636
  <span class="unsaved-changes" style="display: none;">• Unsaved changes</span>
637
637
  </div>
@@ -639,7 +639,7 @@
639
639
  <button class="rte-source-editor-btn rte-source-editor-btn-cancel">Cancel</button>
640
640
  <button class="rte-source-editor-btn rte-source-editor-btn-save">Save</button>
641
641
  </div>
642
- `,p.appendChild(m),p.appendChild(b),p.appendChild(S),f.appendChild(p),!document.getElementById("rte-source-editor-styles")){const v=document.createElement("style");v.id="rte-source-editor-styles",v.textContent=ci,document.head.appendChild(v)}const T=m.querySelector(".theme-toggle-btn"),O=m.querySelector(".readonly-toggle-btn"),B=m.querySelector(".rte-source-editor-fullscreen-btn"),N=m.querySelector(".rte-source-editor-close-btn"),k=S.querySelector(".rte-source-editor-btn-cancel"),M=S.querySelector(".rte-source-editor-btn-save"),Z=S.querySelector(".unsaved-changes"),re=[],A=(v,R,He,G)=>{v.addEventListener(R,He,G),re.push(()=>v.removeEventListener(R,He,G))},se=v=>{u!==v&&(u=v,Z&&(Z.style.display=u?"inline":"none"))},D=()=>{if(!d){for(d=!0;re.length;){const v=re.pop();v==null||v()}a&&(a.destroy(),a=null),f.isConnected&&f.remove()}},yi=()=>{l=l==="dark"?"light":"dark",a==null||a.setTheme(l),T&&(T.innerHTML=l==="light"?`
642
+ `,g.appendChild(m),g.appendChild(b),g.appendChild(E),u.appendChild(g),!document.getElementById("rte-source-editor-styles")){const x=document.createElement("style");x.id="rte-source-editor-styles",x.textContent=si,document.head.appendChild(x)}const S=m.querySelector(".theme-toggle-btn"),N=m.querySelector(".readonly-toggle-btn"),_=m.querySelector(".rte-source-editor-fullscreen-btn"),D=m.querySelector(".rte-source-editor-close-btn"),k=E.querySelector(".rte-source-editor-btn-cancel"),M=E.querySelector(".rte-source-editor-btn-save"),G=E.querySelector(".unsaved-changes"),se=[],R=(x,A,Pe,Q)=>{x.addEventListener(A,Pe,Q),se.push(()=>x.removeEventListener(A,Pe,Q))},ae=x=>{d!==x&&(d=x,G&&(G.style.display=d?"inline":"none"))},P=()=>{if(!f){for(f=!0;se.length;){const x=se.pop();x==null||x()}a&&(a.destroy(),a=null),u.isConnected&&u.remove()}},pi=()=>{l=l==="dark"?"light":"dark",a==null||a.setTheme(l),S&&(S.innerHTML=l==="light"?`
643
643
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
644
644
  <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
645
645
  </svg>
@@ -655,7 +655,7 @@
655
655
  <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/>
656
656
  <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
657
657
  </svg>
658
- `)},vi=()=>{c=!c,a==null||a.setReadOnly(c),O&&(O.classList.toggle("active",c),O.innerHTML=c?`
658
+ `)},mi=()=>{c=!c,a==null||a.setReadOnly(c),N&&(N.classList.toggle("active",c),N.innerHTML=c?`
659
659
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
660
660
  <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
661
661
  <circle cx="12" cy="16" r="1"/>
@@ -666,7 +666,7 @@
666
666
  <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
667
667
  <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
668
668
  </svg>
669
- `)},xi=()=>{h=!h,f.classList.toggle("fullscreen",h),w.style.height=h?"calc(100vh - 200px)":"400px",B&&(B.innerHTML=h?`
669
+ `)},bi=()=>{h=!h,u.classList.toggle("fullscreen",h),w.style.height=h?"calc(100vh - 200px)":"400px",_&&(_.innerHTML=h?`
670
670
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
671
671
  <path d="M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 0 2-2h3M3 16h3a2 2 0 0 0 2 2v3"/>
672
672
  </svg>
@@ -674,5 +674,5 @@
674
674
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
675
675
  <path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/>
676
676
  </svg>
677
- `)},Ci=()=>{u&&!confirm("You have unsaved changes. Are you sure you want to cancel?")||D()},wi=()=>{try{const v=(a==null?void 0:a.getValue())||"",R=document.createElement("div");R.innerHTML=v,R.querySelectorAll('script, iframe[src^="javascript:"], object, embed').forEach(G=>G.remove()),e.innerHTML=R.innerHTML;try{e.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!1,inputType:"insertReplacementText"}))}catch(G){e.dispatchEvent(new Event("input",{bubbles:!0}))}e.dispatchEvent(new Event("change",{bubbles:!0})),se(!1),D()}catch(v){alert("Failed to update HTML. Please check your syntax."),console.error("HTML update error:",v)}};T&&A(T,"click",yi),O&&A(O,"click",vi),B&&A(B,"click",xi),N&&A(N,"click",D),k&&A(k,"click",Ci),M&&A(M,"click",wi),A(f,"click",v=>{v.target===f&&D()}),A(document,"keydown",v=>{const R=v;R.key==="Escape"&&(R.preventDefault(),D())}),document.body.appendChild(f),requestAnimationFrame(()=>{if(!(d||!f.isConnected))try{a=li(w,{value:r,theme:"dark",readOnly:!1,extensions:[new Jn,new ei,new ti,new ri,new ii,new si,new ai]}),a.on("change",()=>{const v=(a==null?void 0:a.getValue())||"";se(v!==r)}),requestAnimationFrame(()=>a==null?void 0:a.focus())}catch(v){console.error("Failed to initialize code editor:",v)}})})(),!0}},keymap:{"Mod-Shift-s":"toggleSourceView","Mod-Shift-S":"toggleSourceView"}})},Symbol.toStringTag,{value:"Module"})),ve=()=>ht("insertUnorderedList"),xe=()=>ht("insertOrderedList");function di(){const s=window.getSelection();if(s&&s.rangeCount>0){const t=s.getRangeAt(0).startContainer,n=t.nodeType===Node.ELEMENT_NODE?t:t.parentElement,i=n==null?void 0:n.closest('[contenteditable="true"], .rte-content, .editora-content');if(i)return i}const e=document.activeElement;return e?e.getAttribute("contenteditable")==="true"?e:e.closest('[contenteditable="true"], .rte-content, .editora-content'):null}function ui(s){s.querySelectorAll('ul:not([data-type="checklist"]), ol').forEach(t=>{Array.from(t.childNodes).forEach(i=>{if(i.nodeType===Node.TEXT_NODE){const r=(i.textContent||"").trim();if(!r){t.removeChild(i);return}const a=document.createElement("li");a.textContent=r,t.replaceChild(a,i);return}if(!(i instanceof HTMLElement)){t.removeChild(i);return}if(i.tagName==="LI")return;const o=document.createElement("li");for(;i.firstChild;)o.appendChild(i.firstChild);t.replaceChild(o,i)})})}function ht(s){const e=di();if(!e)return!1;const t=window.getSelection();if(!t||t.rangeCount===0)return!1;const n=t.getRangeAt(0);if(!e.contains(n.commonAncestorContainer))return!1;e.focus({preventScroll:!0});const i=document.execCommand(s,!1);return ui(e),e.dispatchEvent(new Event("input",{bubbles:!0})),i!==!1}const dt=(s,e)=>{var t;typeof window!="undefined"&&((t=window.registerEditorCommand)==null||t.call(window,s,e))},ut=()=>{dt("toggleBulletList",ve),dt("toggleOrderedList",xe)};typeof window!="undefined"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ut):ut());const gi=Object.freeze(Object.defineProperty({__proto__:null,ListPlugin:()=>({name:"list",nodes:{bulletList:{content:"listItem+",group:"block",parseDOM:[{tag:"ul"}],toDOM:()=>["ul",0]},orderedList:{content:"listItem+",group:"block",parseDOM:[{tag:"ol"}],toDOM:()=>["ol",0]},listItem:{content:"paragraph",parseDOM:[{tag:"li"}],toDOM:()=>["li",0]}},toolbar:[{label:"Bullet List",command:"toggleBulletList",type:"button",icon:'<svg width="24" height="24" focusable="false"><path d="M11 5h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 0 1 0-2Zm0 6h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 0 1 0-2Zm0 6h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 0 1 0-2ZM4.5 6c0 .4.1.8.4 1 .3.4.7.5 1.1.5.4 0 .8-.1 1-.4.4-.3.5-.7.5-1.1 0-.4-.1-.8-.4-1-.3-.4-.7-.5-1.1-.5-.4 0-.8.1-1 .4-.4.3-.5.7-.5 1.1Zm0 6c0 .4.1.8.4 1 .3.4.7.5 1.1.5.4 0 .8-.1 1-.4.4-.3.5-.7.5-1.1 0-.4-.1-.8-.4-1-.3-.4-.7-.5-1.1-.5-.4 0-.8.1-1 .4-.4.3-.5.7-.5 1.1Zm0 6c0 .4.1.8.4 1 .3.4.7.5 1.1.5.4 0 .8-.1 1-.4.4-.3.5-.7.5-1.1 0-.4-.1-.8-.4-1-.3-.4-.7-.5-1.1-.5-.4 0-.8.1-1 .4-.4.3-.5.7-.5 1.1Z" fill-rule="evenodd"></path></svg>',shortcut:"Mod-Shift-8"},{label:"Numbered List",command:"toggleOrderedList",type:"button",icon:'<svg width="24" height="24" focusable="false"><path d="M10 17h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 0 1 0-2Zm0-6h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 0 1 0-2Zm0-6h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 1 1 0-2ZM6 4v3.5c0 .3-.2.5-.5.5a.5.5 0 0 1-.5-.5V5h-.5a.5.5 0 0 1 0-1H6Zm-1 8.8l.2.2h1.3c.3 0 .5.2.5.5s-.2.5-.5.5H4.9a1 1 0 0 1-.9-1V13c0-.4.3-.8.6-1l1.2-.4.2-.3a.2.2 0 0 0 0-.2l-.7.3a.5.5 0 0 1-.7-.3.5.5 0 0 1 .3-.6l.7-.4c.5-.2 1.1 0 1.4.4.3.5.3 1.1-.1 1.5l-1.2.7Zm0 3.7v.5c0 .3.2.5.5.5h1c.3 0 .5.2.5.5s-.2.5-.5.5h-1a1.5 1.5 0 0 1-1.5-1.5v-.5c0-.3.1-.6.3-.8l1.3-1.4c.3-.4.1-.9-.2-1-.1 0-.2 0-.3.2l-.4.5a.5.5 0 0 1-.7.1.5.5 0 0 1-.1-.7l.4-.5c.5-.5 1.2-.6 1.8-.4.6.3 1 .9 1 1.6 0 .4-.2.8-.5 1.1l-1.3 1.4-.3.4Z" fill-rule="evenodd"></path></svg>',shortcut:"Mod-Shift-7"}],commands:{toggleBulletList:ve,toggleOrderedList:xe},keymap:{"Mod-Shift-8":"toggleBulletList","Mod-Shift-7":"toggleOrderedList"}}),toggleBulletList:ve,toggleOrderedList:xe},Symbol.toStringTag,{value:"Module"})),gt=".rte-content, .editora-content",ft=100,pt="__editoraCommandEditorRoot",F=new Map,Ce={};let mt=!1,E=null;function fi(s){if(!s)return null;const e=s.querySelector('[contenteditable="true"]');return e instanceof HTMLElement?e:null}function pi(){if(typeof window=="undefined")return null;const s=window[pt];if(!(s instanceof HTMLElement))return null;window[pt]=null;const e=s.closest("[data-editora-editor], .rte-editor, .editora-editor, editora-editor")||(s.matches("[data-editora-editor], .rte-editor, .editora-editor, editora-editor")?s:null);if(e){const n=fi(e);if(n)return n;if(e.getAttribute("contenteditable")==="true")return e}if(s.getAttribute("contenteditable")==="true")return s;const t=s.closest('[contenteditable="true"]');return t instanceof HTMLElement?t:null}function mi(s){return s?s.nodeType===Node.ELEMENT_NODE?s:s.parentElement:null}function K(s){const e=mi(s);if(!e)return null;const t=e.closest(gt);if(t)return t;const n=e.closest('[contenteditable="true"]');if(!n)return null;let i=n,o=i.parentElement;for(;o;)o.getAttribute("contenteditable")==="true"&&(i=o),o=o.parentElement;return i}function we(){const s=pi();if(s&&document.contains(s))return s;const e=window.getSelection();if(e&&e.rangeCount>0){const o=K(e.getRangeAt(0).startContainer);if(o)return o}const t=document.activeElement;if(t){const o=K(t);if(o)return o}if(E!=null&&E.isConnected)return E;const n=Array.from(F.keys()).find(o=>o.isConnected);if(n)return n;const i=document.querySelector(gt);return i||document.querySelector('[contenteditable="true"]')}function bt(){for(const s of F.keys())s.isConnected||(F.delete(s),E===s&&(E=null))}function Ee(s){bt();let e=F.get(s);return e||(e={undoStack:[],redoStack:[]},F.set(s,e)),e}function q(s){s&&s.dispatchEvent(new Event("input",{bubbles:!0}))}function ne(s,e){if(!s)return;const t=Ee(s);t.undoStack.push(e),t.redoStack.length=0,t.undoStack.length>ft&&t.undoStack.splice(0,t.undoStack.length-ft),E=s}function yt(s,e="undo"){if(bt(),s!=null&&s.isConnected)return s;const t=we();if(t!=null&&t.isConnected)return t;if(E!=null&&E.isConnected)return E;const n=i=>e==="undo"?i.undoStack.length>0:i.redoStack.length>0;for(const[i,o]of F.entries())if(i.isConnected&&n(o))return i;return null}function vt(s){const e={};for(const i of s.getAttributeNames()){const o=s.getAttribute(i);o!==null&&(e[i]=o)}const t=s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement,n=s instanceof HTMLInputElement;return{attributes:e,innerHTML:s.innerHTML,value:t?s.value:null,checked:n?s.checked:null}}function xt(s,e){const t=new Set(s.getAttributeNames());Object.keys(e.attributes).forEach(n=>t.delete(n)),t.forEach(n=>s.removeAttribute(n)),Object.entries(e.attributes).forEach(([n,i])=>{s.setAttribute(n,i)}),s.innerHTML!==e.innerHTML&&(s.innerHTML=e.innerHTML),e.value!==null&&(s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement)&&(s.value=e.value),e.checked!==null&&s instanceof HTMLInputElement&&(s.checked=e.checked)}function H(s,e){if(Ce[s]=e,typeof window=="undefined")return;const t=window.registerEditorCommand;typeof t=="function"?t(s,e):(window.registerEditorCommand=(n,i)=>{Ce[n]=i},window.registerEditorCommand(s,e))}const Ct=(s,...e)=>{const t=Ce[s];return t?t(...e):!1};function Te(){mt||typeof window=="undefined"||(mt=!0,window.execEditorCommand||(window.execEditorCommand=Ct),window.executeEditorCommand||(window.executeEditorCommand=Ct),H("undo",Se),H("redo",ke),H("setAttribute",Me),H("setText",Le),H("autoFixA11y",Ae),H("recordDomTransaction",Re),H("undoDom",ie),H("redoDom",oe))}const Se=()=>{const s=we();return ie(s!=null?s:void 0)},ke=()=>{const s=we();return oe(s!=null?s:void 0)},Me=(s,e,t)=>{if(!(s instanceof HTMLElement))return;const n=K(s),i=s.hasAttribute(e),o=s.getAttribute(e);s.setAttribute(e,t),ne(n,{undo:()=>{s.isConnected&&(i&&o!==null?s.setAttribute(e,o):s.removeAttribute(e))},redo:()=>{s.isConnected&&s.setAttribute(e,t)}}),q(n)},Le=(s,e)=>{var i;if(!(s instanceof HTMLElement))return;const t=K(s),n=(i=s.textContent)!=null?i:"";s.textContent=e,ne(t,{undo:()=>{s.isConnected&&(s.textContent=n)},redo:()=>{s.isConnected&&(s.textContent=e)}}),q(t)},Ae=s=>{var r;const e=s==null?void 0:s.element;if(!(e instanceof HTMLElement))return;const t=K(e),n=(r=window.a11yRuleRegistry)==null?void 0:r.find(a=>a.id===s.rule);if(!n||typeof n.fix!="function")return;const i=vt(e);n.fix(s);const o=vt(e);ne(t,{undo:()=>{e.isConnected&&xt(e,i)},redo:()=>{e.isConnected&&xt(e,o)}}),q(t)},Re=(s,e,t)=>{if(!(s instanceof HTMLElement))return!1;const n=typeof t=="string"?t:s.innerHTML;return e===n?!1:(ne(s,{undo:()=>{s.isConnected&&(s.innerHTML=e)},redo:()=>{s.isConnected&&(s.innerHTML=n)}}),!0)},ie=s=>{const e=yt(s,"undo");if(!e)return!1;const t=Ee(e),n=t.undoStack.pop();return n?(n.undo(),t.redoStack.push(n),E=e,q(e),!0):!1},oe=s=>{const e=yt(s,"redo");if(!e)return!1;const t=Ee(e),n=t.redoStack.pop();return n?(n.redo(),t.undoStack.push(n),E=e,q(e),!0):!1};typeof window!="undefined"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Te,{once:!0}):Te());const bi=Object.freeze(Object.defineProperty({__proto__:null,HistoryPlugin:()=>(Te(),{name:"history",toolbar:[{label:"Undo",command:"undo",type:"button",icon:'<svg width="24" height="24" focusable="false"><path d="M6.4 8H12c3.7 0 6.2 2 6.8 5.1.6 2.7-.4 5.6-2.3 6.8a1 1 0 0 1-1-1.8c1.1-.6 1.8-2.7 1.4-4.6-.5-2.1-2.1-3.5-4.9-3.5H6.4l3.3 3.3a1 1 0 1 1-1.4 1.4l-5-5a1 1 0 0 1 0-1.4l5-5a1 1 0 0 1 1.4 1.4L6.4 8Z" fill-rule="nonzero"></path></svg>',shortcut:"Mod-z"},{label:"Redo",command:"redo",type:"button",icon:'<svg width="24" height="24" focusable="false"><path d="M17.6 10H12c-2.8 0-4.4 1.4-4.9 3.5-.4 2 .3 4 1.4 4.6a1 1 0 1 1-1 1.8c-2-1.2-2.9-4.1-2.3-6.8.6-3 3-5.1 6.8-5.1h5.6l-3.3-3.3a1 1 0 1 1 1.4-1.4l5 5a1 1 0 0 1 0 1.4l-5 5a1 1 0 0 1-1.4-1.4l3.3-3.3Z" fill-rule="nonzero"></path></svg>',shortcut:"Mod-y"}],commands:{undo:Se,redo:ke,setAttribute:Me,setText:Le,autoFixA11y:Ae,recordDomTransaction:Re,undoDom:ie,redoDom:oe},keymap:{"Mod-z":"undo","Mod-Z":"undo","Mod-y":"redo","Mod-Y":"redo","Mod-Shift-z":"redo","Mod-Shift-Z":"redo"}}),autoFixA11y:Ae,recordDomTransaction:Re,redo:ke,redoDom:oe,setAttribute:Me,setText:Le,undo:Se,undoDom:ie},Symbol.toStringTag,{value:"Module"}));P.initWebComponent=ze,Object.defineProperty(P,Symbol.toStringTag,{value:"Module"})}));
677
+ `)},yi=()=>{d&&!confirm("You have unsaved changes. Are you sure you want to cancel?")||P()},vi=()=>{try{const x=(a==null?void 0:a.getValue())||"",A=document.createElement("div");A.innerHTML=x,A.querySelectorAll('script, iframe[src^="javascript:"], object, embed').forEach(Q=>Q.remove()),e.innerHTML=A.innerHTML;try{e.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!1,inputType:"insertReplacementText"}))}catch(Q){e.dispatchEvent(new Event("input",{bubbles:!0}))}e.dispatchEvent(new Event("change",{bubbles:!0})),ae(!1),P()}catch(x){alert("Failed to update HTML. Please check your syntax."),console.error("HTML update error:",x)}};S&&R(S,"click",pi),N&&R(N,"click",mi),_&&R(_,"click",bi),D&&R(D,"click",P),k&&R(k,"click",yi),M&&R(M,"click",vi),R(u,"click",x=>{x.target===u&&P()}),R(document,"keydown",x=>{const A=x;A.key==="Escape"&&(A.preventDefault(),P())}),document.body.appendChild(u),requestAnimationFrame(()=>{if(!(f||!u.isConnected))try{a=ri(w,{value:r,theme:"dark",readOnly:!1,extensions:[new Xn,new Yn,new Jn,new ni,new we,new ii,new oi]}),a.on("change",()=>{const x=(a==null?void 0:a.getValue())||"";ae(x!==r)}),requestAnimationFrame(()=>a==null?void 0:a.focus())}catch(x){console.error("Failed to initialize code editor:",x)}})})(),!0}},keymap:{"Mod-Shift-s":"toggleSourceView","Mod-Shift-S":"toggleSourceView"}})},Symbol.toStringTag,{value:"Module"})),Ee=()=>ht("insertUnorderedList"),Te=()=>ht("insertOrderedList");function li(){const s=window.getSelection();if(s&&s.rangeCount>0){const t=s.getRangeAt(0).startContainer,n=t.nodeType===Node.ELEMENT_NODE?t:t.parentElement,i=n==null?void 0:n.closest('[contenteditable="true"], .rte-content, .editora-content');if(i)return i}const e=document.activeElement;return e?e.getAttribute("contenteditable")==="true"?e:e.closest('[contenteditable="true"], .rte-content, .editora-content'):null}function ci(s){s.querySelectorAll('ul:not([data-type="checklist"]), ol').forEach(t=>{Array.from(t.childNodes).forEach(i=>{if(i.nodeType===Node.TEXT_NODE){const r=(i.textContent||"").trim();if(!r){t.removeChild(i);return}const a=document.createElement("li");a.textContent=r,t.replaceChild(a,i);return}if(!(i instanceof HTMLElement)){t.removeChild(i);return}if(i.tagName==="LI")return;const o=document.createElement("li");for(;i.firstChild;)o.appendChild(i.firstChild);t.replaceChild(o,i)})})}function ht(s){const e=li();if(!e)return!1;const t=window.getSelection();if(!t||t.rangeCount===0)return!1;const n=t.getRangeAt(0);if(!e.contains(n.commonAncestorContainer))return!1;e.focus({preventScroll:!0});const i=document.execCommand(s,!1);return ci(e),e.dispatchEvent(new Event("input",{bubbles:!0})),i!==!1}const dt=(s,e)=>{var t;typeof window!="undefined"&&((t=window.registerEditorCommand)==null||t.call(window,s,e))},ut=()=>{dt("toggleBulletList",Ee),dt("toggleOrderedList",Te)};typeof window!="undefined"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ut):ut());const hi=Object.freeze(Object.defineProperty({__proto__:null,ListPlugin:()=>({name:"list",nodes:{bulletList:{content:"listItem+",group:"block",parseDOM:[{tag:"ul"}],toDOM:()=>["ul",0]},orderedList:{content:"listItem+",group:"block",parseDOM:[{tag:"ol"}],toDOM:()=>["ol",0]},listItem:{content:"paragraph",parseDOM:[{tag:"li"}],toDOM:()=>["li",0]}},toolbar:[{label:"Bullet List",command:"toggleBulletList",type:"button",icon:'<svg width="24" height="24" focusable="false"><path d="M11 5h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 0 1 0-2Zm0 6h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 0 1 0-2Zm0 6h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 0 1 0-2ZM4.5 6c0 .4.1.8.4 1 .3.4.7.5 1.1.5.4 0 .8-.1 1-.4.4-.3.5-.7.5-1.1 0-.4-.1-.8-.4-1-.3-.4-.7-.5-1.1-.5-.4 0-.8.1-1 .4-.4.3-.5.7-.5 1.1Zm0 6c0 .4.1.8.4 1 .3.4.7.5 1.1.5.4 0 .8-.1 1-.4.4-.3.5-.7.5-1.1 0-.4-.1-.8-.4-1-.3-.4-.7-.5-1.1-.5-.4 0-.8.1-1 .4-.4.3-.5.7-.5 1.1Zm0 6c0 .4.1.8.4 1 .3.4.7.5 1.1.5.4 0 .8-.1 1-.4.4-.3.5-.7.5-1.1 0-.4-.1-.8-.4-1-.3-.4-.7-.5-1.1-.5-.4 0-.8.1-1 .4-.4.3-.5.7-.5 1.1Z" fill-rule="evenodd"></path></svg>',shortcut:"Mod-Shift-8"},{label:"Numbered List",command:"toggleOrderedList",type:"button",icon:'<svg width="24" height="24" focusable="false"><path d="M10 17h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 0 1 0-2Zm0-6h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 0 1 0-2Zm0-6h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 1 1 0-2ZM6 4v3.5c0 .3-.2.5-.5.5a.5.5 0 0 1-.5-.5V5h-.5a.5.5 0 0 1 0-1H6Zm-1 8.8l.2.2h1.3c.3 0 .5.2.5.5s-.2.5-.5.5H4.9a1 1 0 0 1-.9-1V13c0-.4.3-.8.6-1l1.2-.4.2-.3a.2.2 0 0 0 0-.2l-.7.3a.5.5 0 0 1-.7-.3.5.5 0 0 1 .3-.6l.7-.4c.5-.2 1.1 0 1.4.4.3.5.3 1.1-.1 1.5l-1.2.7Zm0 3.7v.5c0 .3.2.5.5.5h1c.3 0 .5.2.5.5s-.2.5-.5.5h-1a1.5 1.5 0 0 1-1.5-1.5v-.5c0-.3.1-.6.3-.8l1.3-1.4c.3-.4.1-.9-.2-1-.1 0-.2 0-.3.2l-.4.5a.5.5 0 0 1-.7.1.5.5 0 0 1-.1-.7l.4-.5c.5-.5 1.2-.6 1.8-.4.6.3 1 .9 1 1.6 0 .4-.2.8-.5 1.1l-1.3 1.4-.3.4Z" fill-rule="evenodd"></path></svg>',shortcut:"Mod-Shift-7"}],commands:{toggleBulletList:Ee,toggleOrderedList:Te},keymap:{"Mod-Shift-8":"toggleBulletList","Mod-Shift-7":"toggleOrderedList"}}),toggleBulletList:Ee,toggleOrderedList:Te},Symbol.toStringTag,{value:"Module"})),ft=".rte-content, .editora-content",gt=100,pt="__editoraCommandEditorRoot",B=new Map,Se={};let mt=!1,T=null;function di(s){if(!s)return null;const e=s.querySelector('[contenteditable="true"]');return e instanceof HTMLElement?e:null}function ui(){if(typeof window=="undefined")return null;const s=window[pt];if(!(s instanceof HTMLElement))return null;window[pt]=null;const e=s.closest("[data-editora-editor], .rte-editor, .editora-editor, editora-editor")||(s.matches("[data-editora-editor], .rte-editor, .editora-editor, editora-editor")?s:null);if(e){const n=di(e);if(n)return n;if(e.getAttribute("contenteditable")==="true")return e}if(s.getAttribute("contenteditable")==="true")return s;const t=s.closest('[contenteditable="true"]');return t instanceof HTMLElement?t:null}function fi(s){return s?s.nodeType===Node.ELEMENT_NODE?s:s.parentElement:null}function K(s){const e=fi(s);if(!e)return null;const t=e.closest(ft);if(t)return t;const n=e.closest('[contenteditable="true"]');if(!n)return null;let i=n,o=i.parentElement;for(;o;)o.getAttribute("contenteditable")==="true"&&(i=o),o=o.parentElement;return i}function ke(){const s=ui();if(s&&document.contains(s))return s;const e=window.getSelection();if(e&&e.rangeCount>0){const o=K(e.getRangeAt(0).startContainer);if(o)return o}const t=document.activeElement;if(t){const o=K(t);if(o)return o}if(T!=null&&T.isConnected)return T;const n=Array.from(B.keys()).find(o=>o.isConnected);if(n)return n;const i=document.querySelector(ft);return i||document.querySelector('[contenteditable="true"]')}function bt(){for(const s of B.keys())s.isConnected||(B.delete(s),T===s&&(T=null))}function Me(s){bt();let e=B.get(s);return e||(e={undoStack:[],redoStack:[]},B.set(s,e)),e}function q(s){s&&s.dispatchEvent(new Event("input",{bubbles:!0}))}function ie(s,e){if(!s)return;const t=Me(s);t.undoStack.push(e),t.redoStack.length=0,t.undoStack.length>gt&&t.undoStack.splice(0,t.undoStack.length-gt),T=s}function yt(s,e="undo"){if(bt(),s!=null&&s.isConnected)return s;const t=ke();if(t!=null&&t.isConnected)return t;if(T!=null&&T.isConnected)return T;const n=i=>e==="undo"?i.undoStack.length>0:i.redoStack.length>0;for(const[i,o]of B.entries())if(i.isConnected&&n(o))return i;return null}function vt(s){const e={};for(const i of s.getAttributeNames()){const o=s.getAttribute(i);o!==null&&(e[i]=o)}const t=s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement,n=s instanceof HTMLInputElement;return{attributes:e,innerHTML:s.innerHTML,value:t?s.value:null,checked:n?s.checked:null}}function xt(s,e){const t=new Set(s.getAttributeNames());Object.keys(e.attributes).forEach(n=>t.delete(n)),t.forEach(n=>s.removeAttribute(n)),Object.entries(e.attributes).forEach(([n,i])=>{s.setAttribute(n,i)}),s.innerHTML!==e.innerHTML&&(s.innerHTML=e.innerHTML),e.value!==null&&(s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement)&&(s.value=e.value),e.checked!==null&&s instanceof HTMLInputElement&&(s.checked=e.checked)}function O(s,e){if(Se[s]=e,typeof window=="undefined")return;const t=window.registerEditorCommand;typeof t=="function"?t(s,e):(window.registerEditorCommand=(n,i)=>{Se[n]=i},window.registerEditorCommand(s,e))}const wt=(s,...e)=>{const t=Se[s];return t?t(...e):!1};function Le(){mt||typeof window=="undefined"||(mt=!0,window.execEditorCommand||(window.execEditorCommand=wt),window.executeEditorCommand||(window.executeEditorCommand=wt),O("undo",Re),O("redo",Ae),O("setAttribute",Ie),O("setText",Oe),O("autoFixA11y",He),O("recordDomTransaction",Ne),O("undoDom",oe),O("redoDom",re))}const Re=()=>{const s=ke();return oe(s!=null?s:void 0)},Ae=()=>{const s=ke();return re(s!=null?s:void 0)},Ie=(s,e,t)=>{if(!(s instanceof HTMLElement))return;const n=K(s),i=s.hasAttribute(e),o=s.getAttribute(e);s.setAttribute(e,t),ie(n,{undo:()=>{s.isConnected&&(i&&o!==null?s.setAttribute(e,o):s.removeAttribute(e))},redo:()=>{s.isConnected&&s.setAttribute(e,t)}}),q(n)},Oe=(s,e)=>{var i;if(!(s instanceof HTMLElement))return;const t=K(s),n=(i=s.textContent)!=null?i:"";s.textContent=e,ie(t,{undo:()=>{s.isConnected&&(s.textContent=n)},redo:()=>{s.isConnected&&(s.textContent=e)}}),q(t)},He=s=>{var r;const e=s==null?void 0:s.element;if(!(e instanceof HTMLElement))return;const t=K(e),n=(r=window.a11yRuleRegistry)==null?void 0:r.find(a=>a.id===s.rule);if(!n||typeof n.fix!="function")return;const i=vt(e);n.fix(s);const o=vt(e);ie(t,{undo:()=>{e.isConnected&&xt(e,i)},redo:()=>{e.isConnected&&xt(e,o)}}),q(t)},Ne=(s,e,t)=>{if(!(s instanceof HTMLElement))return!1;const n=typeof t=="string"?t:s.innerHTML;return e===n?!1:(ie(s,{undo:()=>{s.isConnected&&(s.innerHTML=e)},redo:()=>{s.isConnected&&(s.innerHTML=n)}}),!0)},oe=s=>{const e=yt(s,"undo");if(!e)return!1;const t=Me(e),n=t.undoStack.pop();return n?(n.undo(),t.redoStack.push(n),T=e,q(e),!0):!1},re=s=>{const e=yt(s,"redo");if(!e)return!1;const t=Me(e),n=t.redoStack.pop();return n?(n.redo(),t.undoStack.push(n),T=e,q(e),!0):!1};typeof window!="undefined"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Le,{once:!0}):Le());const gi=Object.freeze(Object.defineProperty({__proto__:null,HistoryPlugin:()=>(Le(),{name:"history",toolbar:[{label:"Undo",command:"undo",type:"button",icon:'<svg width="24" height="24" focusable="false"><path d="M6.4 8H12c3.7 0 6.2 2 6.8 5.1.6 2.7-.4 5.6-2.3 6.8a1 1 0 0 1-1-1.8c1.1-.6 1.8-2.7 1.4-4.6-.5-2.1-2.1-3.5-4.9-3.5H6.4l3.3 3.3a1 1 0 1 1-1.4 1.4l-5-5a1 1 0 0 1 0-1.4l5-5a1 1 0 0 1 1.4 1.4L6.4 8Z" fill-rule="nonzero"></path></svg>',shortcut:"Mod-z"},{label:"Redo",command:"redo",type:"button",icon:'<svg width="24" height="24" focusable="false"><path d="M17.6 10H12c-2.8 0-4.4 1.4-4.9 3.5-.4 2 .3 4 1.4 4.6a1 1 0 1 1-1 1.8c-2-1.2-2.9-4.1-2.3-6.8.6-3 3-5.1 6.8-5.1h5.6l-3.3-3.3a1 1 0 1 1 1.4-1.4l5 5a1 1 0 0 1 0 1.4l-5 5a1 1 0 0 1-1.4-1.4l3.3-3.3Z" fill-rule="nonzero"></path></svg>',shortcut:"Mod-y"}],commands:{undo:Re,redo:Ae,setAttribute:Ie,setText:Oe,autoFixA11y:He,recordDomTransaction:Ne,undoDom:oe,redoDom:re},keymap:{"Mod-z":"undo","Mod-Z":"undo","Mod-y":"redo","Mod-Y":"redo","Mod-Shift-z":"redo","Mod-Shift-Z":"redo"}}),autoFixA11y:He,recordDomTransaction:Ne,redo:Ae,redoDom:re,setAttribute:Ie,setText:Oe,undo:Re,undoDom:oe},Symbol.toStringTag,{value:"Module"}));$.initWebComponent=Ue,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})}));
678
678
  //# sourceMappingURL=webcomponent-core.min.js.map