@remyxjs/core 1.0.0-beta → 1.0.4

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.
Files changed (113) hide show
  1. package/README.md +902 -578
  2. package/dist/convertCsv-DRxJY6iq.js +2 -0
  3. package/dist/{convertCsv-CKzZjzLJ.js.map → convertCsv-DRxJY6iq.js.map} +1 -1
  4. package/dist/{convertCsv-B8RVtdcs.cjs → convertCsv-_-qbSNir.cjs} +2 -2
  5. package/dist/{convertCsv-B8RVtdcs.cjs.map → convertCsv-_-qbSNir.cjs.map} +1 -1
  6. package/dist/convertDocx-D-V0dfFd.js +2 -0
  7. package/dist/{convertDocx-Dmx88twM.js.map → convertDocx-D-V0dfFd.js.map} +1 -1
  8. package/dist/{convertDocx-4q89XLLv.cjs → convertDocx-Dpd5BG-G.cjs} +2 -2
  9. package/dist/{convertDocx-4q89XLLv.cjs.map → convertDocx-Dpd5BG-G.cjs.map} +1 -1
  10. package/dist/{convertHtml-DbHrdrD3.cjs → convertHtml-DmfodLsz.cjs} +2 -2
  11. package/dist/{convertHtml-DbHrdrD3.cjs.map → convertHtml-DmfodLsz.cjs.map} +1 -1
  12. package/dist/convertHtml-gycStuZn.js +2 -0
  13. package/dist/{convertHtml-CtYVhiTh.js.map → convertHtml-gycStuZn.js.map} +1 -1
  14. package/dist/convertMarkdown-1BmsjWXP.js +2 -0
  15. package/dist/{convertMarkdown-Di239Gtn.js.map → convertMarkdown-1BmsjWXP.js.map} +1 -1
  16. package/dist/{convertMarkdown-eJ9Nkoid.cjs → convertMarkdown-CelFJJT9.cjs} +2 -2
  17. package/dist/{convertMarkdown-eJ9Nkoid.cjs.map → convertMarkdown-CelFJJT9.cjs.map} +1 -1
  18. package/dist/convertPdf-D4SNUyBk.js +2 -0
  19. package/dist/{convertPdf-CFA1eNNH.js.map → convertPdf-D4SNUyBk.js.map} +1 -1
  20. package/dist/{convertPdf-CSLmTrB8.cjs → convertPdf-DSZy--TD.cjs} +2 -2
  21. package/dist/{convertPdf-CSLmTrB8.cjs.map → convertPdf-DSZy--TD.cjs.map} +1 -1
  22. package/dist/{convertRtf-BfiBLMig.cjs → convertRtf-DK-4c2fe.cjs} +2 -2
  23. package/dist/{convertRtf-BfiBLMig.cjs.map → convertRtf-DK-4c2fe.cjs.map} +1 -1
  24. package/dist/convertRtf-JWu514-h.js +2 -0
  25. package/dist/{convertRtf-08CoScGD.js.map → convertRtf-JWu514-h.js.map} +1 -1
  26. package/dist/{convertText-BpgzHRuh.cjs → convertText-BHUD1tLm.cjs} +2 -2
  27. package/dist/{convertText-BpgzHRuh.cjs.map → convertText-BHUD1tLm.cjs.map} +1 -1
  28. package/dist/convertText-DCGItleK.js +2 -0
  29. package/dist/{convertText-sa7PxKTe.js.map → convertText-DCGItleK.js.map} +1 -1
  30. package/dist/index-C3_cH6Zy.cjs +2 -0
  31. package/dist/index-C3_cH6Zy.cjs.map +1 -0
  32. package/dist/index-Cv62E14a.js +2 -0
  33. package/dist/index-Cv62E14a.js.map +1 -0
  34. package/dist/remyx-core.cjs +1 -1
  35. package/dist/remyx-core.css +1 -1
  36. package/dist/remyx-core.js +1 -1
  37. package/package.json +1 -1
  38. package/dist/convertCsv-CKzZjzLJ.js +0 -2
  39. package/dist/convertDocx-Dmx88twM.js +0 -2
  40. package/dist/convertHtml-CtYVhiTh.js +0 -2
  41. package/dist/convertMarkdown-Di239Gtn.js +0 -2
  42. package/dist/convertPdf-CFA1eNNH.js +0 -2
  43. package/dist/convertRtf-08CoScGD.js +0 -2
  44. package/dist/convertText-sa7PxKTe.js +0 -2
  45. package/dist/index-4syk9eEO.js +0 -2
  46. package/dist/index-4syk9eEO.js.map +0 -1
  47. package/dist/index-B25zSs0W.js +0 -2
  48. package/dist/index-B25zSs0W.js.map +0 -1
  49. package/dist/index-B7VT6ZLa.cjs +0 -2
  50. package/dist/index-B7VT6ZLa.cjs.map +0 -1
  51. package/dist/index-BCpytFKJ.js +0 -2
  52. package/dist/index-BCpytFKJ.js.map +0 -1
  53. package/dist/index-BNKANY5i.cjs +0 -2
  54. package/dist/index-BNKANY5i.cjs.map +0 -1
  55. package/dist/index-B_g_579T.cjs +0 -2
  56. package/dist/index-B_g_579T.cjs.map +0 -1
  57. package/dist/index-BvwyeoMb.js +0 -3
  58. package/dist/index-BvwyeoMb.js.map +0 -1
  59. package/dist/index-Bw7mlUQo.js +0 -2
  60. package/dist/index-Bw7mlUQo.js.map +0 -1
  61. package/dist/index-Byatzd-A.js +0 -2
  62. package/dist/index-Byatzd-A.js.map +0 -1
  63. package/dist/index-C0z9eZLm.cjs +0 -2
  64. package/dist/index-C0z9eZLm.cjs.map +0 -1
  65. package/dist/index-C88XPqjX.js +0 -2
  66. package/dist/index-C88XPqjX.js.map +0 -1
  67. package/dist/index-CI6FPF49.cjs +0 -2
  68. package/dist/index-CI6FPF49.cjs.map +0 -1
  69. package/dist/index-CLZF5_GB.cjs +0 -2
  70. package/dist/index-CLZF5_GB.cjs.map +0 -1
  71. package/dist/index-CXSwYlG4.cjs +0 -2
  72. package/dist/index-CXSwYlG4.cjs.map +0 -1
  73. package/dist/index-Ch9gotLk.js +0 -2
  74. package/dist/index-Ch9gotLk.js.map +0 -1
  75. package/dist/index-CifDpN1Y.js +0 -2
  76. package/dist/index-CifDpN1Y.js.map +0 -1
  77. package/dist/index-D5o8VpWJ.cjs +0 -2
  78. package/dist/index-D5o8VpWJ.cjs.map +0 -1
  79. package/dist/index-DKT1bABL.js +0 -2
  80. package/dist/index-DKT1bABL.js.map +0 -1
  81. package/dist/index-DWcn72PW.js +0 -2
  82. package/dist/index-DWcn72PW.js.map +0 -1
  83. package/dist/index-DjCGzPEv.cjs +0 -2
  84. package/dist/index-DjCGzPEv.cjs.map +0 -1
  85. package/dist/index-Dq0Jr1Ae.js +0 -2
  86. package/dist/index-Dq0Jr1Ae.js.map +0 -1
  87. package/dist/index-Dw0MVypb.cjs +0 -2
  88. package/dist/index-Dw0MVypb.cjs.map +0 -1
  89. package/dist/index-FEo3LShh.cjs +0 -2
  90. package/dist/index-FEo3LShh.cjs.map +0 -1
  91. package/dist/index-O1hzAUzi.cjs +0 -2
  92. package/dist/index-O1hzAUzi.cjs.map +0 -1
  93. package/dist/index-T1ZyLzeF.cjs +0 -2
  94. package/dist/index-T1ZyLzeF.cjs.map +0 -1
  95. package/dist/index-iRikoCdK.cjs +0 -2
  96. package/dist/index-iRikoCdK.cjs.map +0 -1
  97. package/dist/index-l6Yddj6x.js +0 -2
  98. package/dist/index-l6Yddj6x.js.map +0 -1
  99. package/dist/index-rD8LZENp.js +0 -2
  100. package/dist/index-rD8LZENp.js.map +0 -1
  101. package/dist/themes/callouts.css +0 -79
  102. package/dist/themes/collaboration.css +0 -117
  103. package/dist/themes/comments.css +0 -198
  104. package/dist/themes/dark.css +0 -109
  105. package/dist/themes/forest.css +0 -109
  106. package/dist/themes/light.css +0 -4
  107. package/dist/themes/links.css +0 -115
  108. package/dist/themes/math-toc-analytics.css +0 -129
  109. package/dist/themes/ocean.css +0 -109
  110. package/dist/themes/rose.css +0 -109
  111. package/dist/themes/spellcheck.css +0 -173
  112. package/dist/themes/sunset.css +0 -109
  113. package/dist/themes/templates.css +0 -87
@@ -0,0 +1,2 @@
1
+ import e from"turndown";import{gfm as t}from"turndown-plugin-gfm";import{marked as n}from"marked";class o{constructor(){this._listeners=/* @__PURE__ */new Map,this._keyedHandlers=/* @__PURE__ */new Map,this._emitDepth=0}on(e,t,n){if(this._listeners.has(e)||this._listeners.set(e,/* @__PURE__ */new Set),n?.key){const o=`${e}:${n.key}`,r=this._keyedHandlers.get(o);r&&this.off(e,r),this._keyedHandlers.set(o,t)}return this._listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){const n=this._listeners.get(e);n&&(n.delete(t),0===n.size&&this._listeners.delete(e))}once(e,t){const n=(...o)=>{this.off(e,n),t(...o)};return this.on(e,n)}emit(e,t){const n=this._listeners.get(e);if(n){this._emitDepth++;try{n.forEach((n=>{try{n(t)}catch(o){"error"!==e&&this._emitDepth<3&&this.emit("error",{event:e,error:o,data:t})}}))}finally{this._emitDepth--}}}removeAllListeners(e){e?this._listeners.delete(e):this._listeners.clear()}}const r=/* @__PURE__ */new Set(["P","H1","H2","H3","H4","H5","H6","DIV","BLOCKQUOTE","PRE","LI","TD","TH"]);function i(e,t){let n=e.nodeType===Node.TEXT_NODE?e.parentElement:e;for(;n&&n!==t;){if(r.has(n.tagName))return n;n=n.parentElement}return null}function s(e,t){return i(e,t)}function a(e,t,n){const o=t.toUpperCase();let r=e.nodeType===Node.TEXT_NODE?e.parentElement:e;for(;r&&r!==n;){if(r.tagName===o)return r;r=r.parentElement}return null}function l(e,t,n={}){const o=document.createElement(t);Object.entries(n).forEach((([e,t])=>o.setAttribute(e,t)));try{e.surroundContents(o)}catch{const t=e.extractContents();o.appendChild(t),e.insertNode(o)}return o}function c(e){const t=e.parentNode;for(;e.firstChild;)t.insertBefore(e.firstChild,e);t.removeChild(e)}function d(){return"rmx-"+Math.random().toString(36).substr(2,9)}function u(e){if(!e)return!0;return""===e.textContent.trim()&&!e.querySelector("img, iframe, hr, input")}const h=/^h[1-6]$/,m={bold:/* @__PURE__ */new Set(["STRONG","B"]),italic:/* @__PURE__ */new Set(["EM","I"]),underline:/* @__PURE__ */new Set(["U"]),strikethrough:/* @__PURE__ */new Set(["S","DEL"]),subscript:/* @__PURE__ */new Set(["SUB"]),superscript:/* @__PURE__ */new Set(["SUP"])};class g{constructor(e){this.editor=e,this._cachedRange=null,this._cacheGeneration=0}invalidateCache(){this._cacheGeneration++,this._cachedRange=null}getSelection(){return window.getSelection()}getRange(){if(null!==this._cachedRange)return this._cachedRange;const e=this.getSelection();if(!e||0===e.rangeCount)return this._cachedRange=null,null;const t=e.getRangeAt(0);if(!this.isWithinEditor(t.commonAncestorContainer))return this._cachedRange=null,null;this._cachedRange=t;const n=++this._cacheGeneration;return Promise.resolve().then((()=>{this._cacheGeneration===n&&(this._cachedRange=null)})),t}setRange(e){this._cachedRange=null;try{const t=this.getSelection();t.removeAllRanges(),t.addRange(e)}catch{}}isWithinEditor(e){if(!e)return!1;const t=e.nodeType===Node.TEXT_NODE?e.parentElement:e;return this.editor.contains(t)}isCollapsed(){const e=this.getSelection();return!e||e.isCollapsed}getSelectedText(){const e=this.getSelection();return e?e.toString():""}getSelectedHTML(){const e=this.getRange();if(!e)return"";const t=e.cloneContents(),n=document.createElement("div");return n.appendChild(t),n.innerHTML}save(){const e=this.getRange();if(!e)return null;const t=document.createRange();t.selectNodeContents(this.editor),t.setEnd(e.startContainer,e.startOffset);const n=t.toString().length;return{startOffset:n,endOffset:n+e.toString().length,collapsed:e.collapsed}}restore(e){if(!e)return;const t=document.createTreeWalker(this.editor,NodeFilter.SHOW_TEXT,null);let n=0,o=null,r=0,i=null,s=0;for(;t.nextNode();){const a=t.currentNode,l=n+a.textContent.length;if(!o&&l>=e.startOffset&&(o=a,r=e.startOffset-n),!i&&l>=e.endOffset){i=a,s=e.endOffset-n;break}n=l}if(o)try{const e=document.createRange();e.setStart(o,Math.min(r,o.textContent.length)),i?e.setEnd(i,Math.min(s,i.textContent.length)):e.collapse(!0),this.setRange(e)}catch{try{const e=document.createRange();e.selectNodeContents(this.editor),e.collapse(!1),this.setRange(e)}catch{}}}collapse(e=!1){const t=this.getSelection();t&&t.rangeCount>0&&(e?t.collapseToEnd():t.collapseToStart())}getParentElement(){const e=this.getRange();if(!e)return null;const t=e.commonAncestorContainer;return t.nodeType===Node.TEXT_NODE?t.parentElement:t}getParentBlock(){const e=this.getParentElement();return e?i(e,this.editor):null}getClosestElement(e){let t=this.getParentElement();const n=e.toUpperCase();for(;t&&t!==this.editor;){if(t.tagName===n)return t;t=t.parentElement}return null}insertHTML(e){const t=this._sanitizer?this._sanitizer.sanitize(e):e,n=this.getSelection();if(!n||0===n.rangeCount)return;const o=n.getRangeAt(0);o.deleteContents();const r=document.createElement("template");r.innerHTML=t;const i=r.content,s=i.lastChild;if(o.insertNode(i),s){const e=document.createRange();e.setStartAfter(s),e.collapse(!0),n.removeAllRanges(),n.addRange(e)}}setSanitizer(e){this._sanitizer=e}insertNode(e){const t=this.getRange();t&&(t.deleteContents(),t.insertNode(e),t.setStartAfter(e),t.collapse(!0),this.setRange(t))}wrapWith(e,t={}){const n=this.getRange();if(!n||n.collapsed)return null;const o=document.createElement(e);Object.entries(t).forEach((([e,t])=>{o.setAttribute(e,t)}));try{n.surroundContents(o)}catch{const e=n.extractContents();o.appendChild(e),n.insertNode(o)}return this.setRange(n),o}unwrap(e){const t=this.getClosestElement(e);if(!t)return;const n=t.parentNode;for(;t.firstChild;)n.insertBefore(t.firstChild,t);n.removeChild(t)}getActiveFormats(){const e={bold:!1,italic:!1,underline:!1,strikethrough:!1,subscript:!1,superscript:!1,heading:null,alignment:"left",orderedList:!1,unorderedList:!1,blockquote:!1,codeBlock:!1,link:null,fontFamily:null,fontSize:null,foreColor:null,backColor:null};try{const t=window.getSelection();if(t&&t.rangeCount>0){let n=t.anchorNode;for(;n&&n!==this.editor;){if(n.nodeType===Node.ELEMENT_NODE){const t=n.tagName;for(const n in m)!e[n]&&m[n].has(t)&&(e[n]=!0)}n=n.parentNode}}}catch{}const t=this.getParentBlock();if(t){const n=t.tagName.toLowerCase();h.test(n)&&(e.heading=n);const o=t.style.textAlign||window.getComputedStyle(t).textAlign;o&&(e.alignment="start"===o?"left":"end"===o?"right":o)}let n=this.getParentElement();for(;n&&n!==this.editor;){const t=n.tagName;"OL"===t&&(e.orderedList=!0),"UL"===t&&(e.unorderedList=!0),"BLOCKQUOTE"===t&&(e.blockquote=!0),"PRE"===t&&(e.codeBlock=!0),"A"===t&&(e.link={href:n.href,text:n.textContent,target:n.target}),n=n.parentElement}try{e.fontFamily=document.queryCommandValue("fontName")||null,e.fontSize=document.queryCommandValue("fontSize")||null,e.foreColor=document.queryCommandValue("foreColor")||null,e.backColor=document.queryCommandValue("backColor")||null}catch{}return e}getBoundingRect(){const e=this.getRange();return e?e.getBoundingClientRect():null}}class p{constructor(e){this.engine=e,this._commands=/* @__PURE__ */new Map}register(e,t){if(this._commands.set(e,{name:e,execute:t.execute,isActive:t.isActive||(()=>!1),isEnabled:t.isEnabled||(()=>!0),shortcut:t.shortcut||null,meta:t.meta||{},skipSnapshot:t.skipSnapshot||!1}),t.shortcut&&this.engine.keyboard.register(t.shortcut,e),t.alternateShortcuts)for(const n of t.alternateShortcuts)this.engine.keyboard.register(n,e)}execute(e,...t){const n=this._commands.get(e);if(!n)return!1;if(!n.isEnabled(this.engine))return!1;n.skipSnapshot||this.engine.history.snapshot();const o=n.execute(this.engine,...t);return this.engine.eventBus.emit("command:executed",{name:e,args:t,result:o}),this.engine.eventBus.emit("content:change"),o}isActive(e){const t=this._commands.get(e);return!!t&&t.isActive(this.engine)}isEnabled(e){const t=this._commands.get(e);return!!t&&t.isEnabled(this.engine)}get(e){return this._commands.get(e)}getAll(){return Array.from(this._commands.keys())}has(e){return this._commands.has(e)}}function f(e){let t=5381;for(let n=0,o=e.length;n<o;n++)t=(t<<5)+t+e.charCodeAt(n)|0;return t}function b(e,t){const{prefixLen:n,suffixLen:o,insert:r}=t;return e.slice(0,n)+r+(o>0?e.slice(e.length-o):"")}class y{constructor(e,t={}){this.engine=e,this.maxSize=t.maxSize||100,this.debounceMs=t.debounceMs||300,this.coalesceMs=t.coalesceMs||1e3,this._undoStack=[],this._redoStack=[],this._observer=null,this._debounceTimer=null,this._coalesceTimer=null,this._isPerformingUndoRedo=!1,this._isCoalescing=!1,this._lastSnapshot=null,this._lastHash=null}init(){this._takeSnapshot(),this._observer=new MutationObserver((()=>{this._isPerformingUndoRedo||this._debouncedSnapshot()})),this._observer.observe(this.engine.element,{childList:!0,characterData:!0,subtree:!0})}destroy(){this._observer&&(this._observer.disconnect(),this._observer=null),this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null),this._coalesceTimer&&(clearTimeout(this._coalesceTimer),this._coalesceTimer=null),this._isCoalescing=!1}snapshot(){this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null),this._takeSnapshot()}_debouncedSnapshot(){this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout((()=>{this._isCoalescing?this._updateTopSnapshot():(this._isCoalescing=!0,this._takeSnapshot(),this._coalesceTimer&&clearTimeout(this._coalesceTimer),this._coalesceTimer=setTimeout((()=>{this._isCoalescing=!1}),this.coalesceMs))}),this.debounceMs)}_createEntry(e,t){if(e.length<5e3||!this._lastSnapshot)return{type:"full",html:e,bookmark:t};const n=function(e,t){const n=Math.min(e.length,t.length);let o=0;for(;o<n&&e[o]===t[o];)o++;let r=0;const i=n-o;for(;r<i&&e[e.length-1-r]===t[t.length-1-r];)r++;return{prefixLen:o,suffixLen:r,insert:t.slice(o,t.length-r||void 0)}}(this._lastSnapshot,e);return n.insert.length>=.8*e.length?{type:"full",html:e,bookmark:t}:{type:"diff",patch:n,bookmark:t}}_resolveEntry(e,t){const n=e[t];if("full"===n.type)return n.html;let o,r=t-1;for(;r>=0&&"full"!==e[r].type;)r--;o=r>=0?e[r].html:this._lastSnapshot||"";for(let i=r+1;i<=t;i++)o="diff"===e[i].type?b(o,e[i].patch):e[i].html;return o}_updateTopSnapshot(){const e=this.engine.element.innerHTML,t=f(e);if(t===this._lastHash&&e===this._lastSnapshot)return;const n=this.engine.selection.save();this._undoStack.length>0?this._undoStack[this._undoStack.length-1]=this._createEntry(e,n):this._undoStack.push({type:"full",html:e,bookmark:n}),this._lastSnapshot=e,this._lastHash=t}_takeSnapshot(){const e=this.engine.element.innerHTML,t=f(e);if(t===this._lastHash&&e===this._lastSnapshot)return;const n=this.engine.selection.save(),o=this._createEntry(e,n);this._undoStack.push(o),this._undoStack.length>this.maxSize&&this._undoStack.shift(),this._redoStack=[],this._lastSnapshot=e,this._lastHash=t}_disconnectObserver(){this._observer&&this._observer.disconnect()}_reconnectObserver(){this._observer&&this._observer.observe(this.engine.element,{childList:!0,characterData:!0,subtree:!0})}undo(){if(!this.canUndo())return;this._isPerformingUndoRedo=!0,this._disconnectObserver();const e=this.engine.element.innerHTML,t=this.engine.selection.save();this._redoStack.push({type:"full",html:e,bookmark:t});const n=this._undoStack.length-1,o=this._resolveEntry(this._undoStack,n),r=this._undoStack[n].bookmark;this._undoStack.pop(),this.engine.element.innerHTML=o,this._lastSnapshot=o,this._lastHash=f(o),r&&this.engine.selection.restore(r),this._reconnectObserver(),this._isPerformingUndoRedo=!1,this.engine.eventBus.emit("history:undo"),this.engine.eventBus.emit("content:change")}redo(){if(!this.canRedo())return;this._isPerformingUndoRedo=!0,this._disconnectObserver();const e=this.engine.element.innerHTML,t=this.engine.selection.save();this._undoStack.push({type:"full",html:e,bookmark:t});const n=this._redoStack.length-1,o=this._resolveEntry(this._redoStack,n),r=this._redoStack[n].bookmark;this._redoStack.pop(),this.engine.element.innerHTML=o,this._lastSnapshot=o,this._lastHash=f(o),r&&this.engine.selection.restore(r),this._reconnectObserver(),this._isPerformingUndoRedo=!1,this.engine.eventBus.emit("history:redo"),this.engine.eventBus.emit("content:change")}canUndo(){return this._undoStack.length>0}canRedo(){return this._redoStack.length>0}clear(){this._undoStack=[],this._redoStack=[],this._lastSnapshot=null,this._lastHash=null}}let v=null;function C(){return null===v&&(v="undefined"!=typeof navigator&&/Mac|iPod|iPhone|iPad/.test(navigator.platform)),v}function x(){return C()?"⌘":"Ctrl"}class _{constructor(e){this.engine=e,this._shortcuts=/* @__PURE__ */new Map,this._normalizeCache=/* @__PURE__ */new Map,this._handleKeyDown=this._handleKeyDown.bind(this)}init(){this.engine.element.addEventListener("keydown",this._handleKeyDown)}destroy(){this.engine.element.removeEventListener("keydown",this._handleKeyDown)}register(e,t){const n=this._normalizeShortcut(e);this._shortcuts.set(n,t)}unregister(e){const t=this._normalizeShortcut(e);this._shortcuts.delete(t)}getShortcutForCommand(e){for(const[t,n]of this._shortcuts)if(n===e)return t;return null}getShortcutLabel(e){if(!e)return"";return e.split("+").map((e=>"mod"===e?C()?"⌘":"Ctrl":"shift"===e?C()?"⇧":"Shift":"alt"===e?C()?"⌥":"Alt":e.toUpperCase())).join(C()?"":"+")}_normalizeShortcut(e){if(this._normalizeCache.has(e))return this._normalizeCache.get(e);const t=e.toLowerCase().split("+").sort().join("+");return this._normalizeCache.set(e,t),t}_handleKeyDown(e){const t=[];(C()?e.metaKey:e.ctrlKey)&&t.push("mod"),e.shiftKey&&t.push("shift"),e.altKey&&t.push("alt");const n=e.key.toLowerCase();["control","meta","shift","alt"].includes(n)||t.push(n);const o=t.sort().join("+"),r=this._shortcuts.get(o);r&&(e.preventDefault(),e.stopPropagation(),this.engine.commands.execute(r))}}const w={p:["class","style"],h1:["class"],h2:["class"],h3:["class"],h4:["class"],h5:["class"],h6:["class"],strong:[],b:[],em:[],i:[],u:[],s:[],del:[],sub:[],sup:[],a:["href","target","rel","title","class","data-attachment","data-filename","data-filesize"],img:["src","alt","width","height","style","class"],ul:["class"],ol:["class","start","type"],li:["class"],table:["class","data-sort-state"],thead:[],tbody:[],tr:["class"],th:["colspan","rowspan","class","style","data-sort-dir","data-sort-priority","data-filter-value","data-cell-format","data-raw-value","data-formula"],td:["colspan","rowspan","class","style","data-cell-format","data-raw-value","data-formula","data-col-width"],blockquote:["class"],pre:["class","data-language"],code:["class","data-language"],hr:[],br:[],div:["class","style","data-embed-url"],span:["style","class"],input:["type","checked","disabled","class"],label:["class"],mark:["class"],iframe:["src","width","height","frameborder","allowfullscreen","sandbox","class","style"]},k=["color","background-color","font-family","font-size","text-align","text-decoration","font-weight","font-style","width","height","max-width","float","margin","margin-left","margin-right","display","padding","border","min-width"],S=/^\s*javascript\s*:/i,I=/expression\s*\(|@import|behavior\s*:|javascript\s*:/i,E=/* @__PURE__ */new Set(["script","style","svg","math","form","object","embed","applet","template"]),A=["www.youtube.com","youtube.com","www.youtube-nocookie.com","player.vimeo.com","www.dailymotion.com","geo.dailymotion.com"];function B(e,t){if(!e)return!1;try{const n=new URL(e);if("https:"!==n.protocol)return!1;const o=n.hostname.toLowerCase();return t.some((e=>{const t=e.toLowerCase();return o===t||o.endsWith("."+t)}))}catch{return!1}}class L{constructor(e={}){this.allowedTags=e.allowedTags||w,this.allowedStyles=e.allowedStyles||k,this.iframeAllowedDomains=e.iframeAllowedDomains||A,this._cache=/* @__PURE__ */new Map,this._parser=new DOMParser}sanitize(e){if(!e)return"";const t=f(e);if(this._cache.has(t)){const n=this._cache.get(t);if(n.input===e)return this._cache.delete(t),this._cache.set(t,n),n.output}const n=this._parser.parseFromString(`<body>${e}</body>`,"text/html");this._cleanNode(n.body);const o=n.body.innerHTML;if(this._cache.size>=50){const e=this._cache.keys().next().value;this._cache.delete(e)}return this._cache.set(t,{input:e,output:o}),o}_cleanNode(e){for(let t=e.childNodes.length-1;t>=0;t--){const n=e.childNodes[t];if(n.nodeType===Node.TEXT_NODE)continue;if(n.nodeType===Node.COMMENT_NODE){e.removeChild(n);continue}if(n.nodeType!==Node.ELEMENT_NODE){e.removeChild(n);continue}const o=n.tagName.toLowerCase(),r=this.allowedTags[o];if(!r){if(E.has(o))e.removeChild(n);else{for(;n.firstChild;)e.insertBefore(n.firstChild,n);e.removeChild(n)}continue}const i=Array.from(n.attributes);for(const e of i)e.name.startsWith("on")?n.removeAttribute(e.name):"style"===e.name?r.includes("style")?this._cleanStyles(n):n.removeAttribute("style"):r.includes(e.name)||n.removeAttribute(e.name);if(n.hasAttribute("href")){const e=n.getAttribute("href");e&&S.test(e)&&n.setAttribute("href","#")}if("input"===o){if("checkbox"!==(n.getAttribute("type")||"").toLowerCase()){e.removeChild(n);continue}}if("iframe"===o){if(!B(n.getAttribute("src"),this.iframeAllowedDomains)){e.removeChild(n);continue}}this._cleanNode(n)}}_cleanStyles(e){const t=e.style,n=[];for(const o of this.allowedStyles){const e=t.getPropertyValue(o);if(e){if(I.test(e))continue;n.push(`${o}: ${e}`)}}n.length>0?e.setAttribute("style",n.join("; ")):e.removeAttribute("style")}}const T="undefined"!=typeof DOMParser?new DOMParser:null,N=/^[\s]*[·•●○◦▪▫–—-]\s*/,R=/^[\s]*\d+[.)]\s*/,H=/^[\s]*[a-zA-Z][.)]\s*/,M=/margin-left|padding-left|text-indent/i,D=/^[\s]*(?:[·•●○◦▪▫–—-]|\d+[.)]|[a-zA-Z][.)])\s*/;function F(e){if(!e)return"";let t=e;t=t.replace(/<meta[^>]*>/gi,""),t=t.replace(/<\/?html[^>]*>/gi,""),t=t.replace(/<head[\s\S]*?<\/head>/gi,""),t=t.replace(/<\/?body[^>]*>/gi,""),t=t.replace(/<style[\s\S]*?<\/style>/gi,""),t=t.replace(/<title[\s\S]*?<\/title>/gi,""),t=t.replace(/<svg[\s\S]*?<\/svg>/gi,""),t=t.replace(/<math[\s\S]*?<\/math>/gi,""),t=t.replace(/<object[\s\S]*?<\/object>/gi,""),t=t.replace(/<link[^>]*>/gi,"");const n=/mso-|class="Mso|<o:p|<w:/.test(e),o=/docs-internal|id="h\.[a-z0-9]+"/.test(e),r=/google-sheets-html-origin/.test(e),i=/<text:|<office:|class="P\d+"/.test(e),s=/apple-content-edited|class="[sp]\d+"/.test(e);return n&&(t=t.replace(/<!--\[if[\s\S]*?endif\]-->/gi,""),t=t.replace(/<!--[\s\S]*?-->/g,""),t=t.replace(/<o:p[\s\S]*?<\/o:p>/gi,""),t=t.replace(/<w:[\s\S]*?<\/w:[\s\S]*?>/gi,""),t=t.replace(/<m:[\s\S]*?<\/m:[\s\S]*?>/gi,""),t=t.replace(/<\/?(xml|st1|v:|o:)[^>]*>/gi,""),t=t.replace(/\s*mso-[^:]+:[^;"]+;?/gi,""),t=t.replace(/\s*class="Mso[^"]*"/gi,""),t=t.replace(/\s*lang="[^"]*"/gi,"")),o&&(t=t.replace(/<b\s+id="docs-internal[^"]*"[^>]*>([\s\S]*?)<\/b>/gi,"$1"),t=t.replace(/\s*id="docs-internal[^"]*"/gi,""),t=t.replace(/\s*id="h\.[a-z0-9]+"/gi,""),t=t.replace(/\s*class="c\d+"/gi,""),t=t.replace(/\s*dir="ltr"/gi,""),t=t.replace(/\s*role="presentation"/gi,""),t=t.replace(/<span\s+style="[^"]*font-weight:\s*(700|bold)[^"]*">([\s\S]*?)<\/span>/gi,"<strong>$2</strong>"),t=t.replace(/<span\s+style="[^"]*font-style:\s*italic[^"]*">([\s\S]*?)<\/span>/gi,"<em>$2</em>"),t=t.replace(/<span\s+style="[^"]*text-decoration:\s*line-through[^"]*">([\s\S]*?)<\/span>/gi,"<s>$2</s>")),i&&(t=t.replace(/<\/?(text|office|table|draw|style|number|fo|svg):[^>]*>/gi,""),t=t.replace(/\s*class="P\d+"/gi,""),t=t.replace(/\s*class="T\d+"/gi,""),t=t.replace(/\s*class="Table\d+"/gi,"")),r&&(t=t.replace(/<google-sheets-html-origin[\s\S]*?\/>/gi,""),t=t.replace(/<\/?google-sheets-html-origin[^>]*>/gi,""),t=t.replace(/<col[^>]*>/gi,""),t=t.replace(/<\/?colgroup[^>]*>/gi,"")),n&&/<table/i.test(e)&&(t=t.replace(/\s*xmlns:[a-z]="[^"]*"/gi,""),t=t.replace(/<col[^>]*>/gi,""),t=t.replace(/<\/?colgroup[^>]*>/gi,"")),s&&(t=t.replace(/\s*class="(s|p)\d+"/gi,""),t=t.replace(/<div\s+apple-content-edited="true"[^>]*>/gi,"<div>")),t=t.replace(/@font-face\s*\{[^}]*\}/gi,""),t=t.replace(/\s*style="\s*"/gi,""),t=t.replace(/\s*class="\s*"/gi,""),t=t.replace(/<span\s*>([\s\S]*?)<\/span>/gi,"$1"),t=t.replace(/<(\w+)\s+>/g,"<$1>"),t=t.replace(/<p[^>]*>\s*<\/p>/gi,""),t=t.replace(/<div[^>]*>\s*<\/div>/gi,""),t=t.replace(/<font\s[^>]*?face="([^"]*)"[^>]*>([\s\S]*?)<\/font>/gi,'<span style="font-family: $1">$2</span>'),t=t.replace(/<font\s[^>]*?color="([^"]*)"[^>]*>([\s\S]*?)<\/font>/gi,'<span style="color: $1">$2</span>'),t=t.replace(/<font\s[^>]*?size="([^"]*)"[^>]*>([\s\S]*?)<\/font>/gi,"$2"),t=t.replace(/<\/?font[^>]*>/gi,""),t=t.replace(/<b(\s|>)/gi,"<strong$1"),t=t.replace(/<\/b>/gi,"</strong>"),t=t.replace(/<i(\s|>)/gi,"<em$1"),t=t.replace(/<\/i>/gi,"</em>"),n&&(t=function(e){if(!T)return e;const t=T.parseFromString(`<body>${e}</body>`,"text/html"),n=t.querySelectorAll("p");let o=!1,r=null,i=null;for(const s of n){const e=s.textContent.trim(),n=s.getAttribute("style")||"",a=M.test(n),l=N.test(e),c=R.test(e)||H.test(e);if((l||c)&&a){const e=l?"ul":"ol";o&&r===e||(i=t.createElement(e),s.parentNode.insertBefore(i,s),o=!0,r=e);const n=t.createElement("li");n.innerHTML=s.innerHTML.replace(D,""),i.appendChild(n),s.parentNode.removeChild(s)}else o=!1,r=null,i=null}return t.body.innerHTML}(t)),t=t.replace(/(<br\s*\/?\s*>){3,}/gi,"<br><br>"),t.trim()}const z=/^#{1,6}\s+\S/,G=/^[-*+]\s+\S/,P=/^\d+[.)]\s+\S/,Z=/^[-*+]\s+\[[ xX]\]\s/,W=/^>\s/,O=/^([-*_])\1{2,}$/,V=/^```/,K=/\*\*[^*]+\*\*/,X=/__[^_]+__/,U=new RegExp("(?<!\\w)\\*[^*\\s][^*]*\\*(?!\\w)"),q=/\[.+\]\(.+\)/,j=/!\[.*\]\(.+\)/,$=/^\|.+\|/,Y=/^\|[\s-:|]+\|$/,J=/`[^`]+`/;function Q(e){if(!e||e.length<3)return!1;const t=e.split("\n");let n=0,o=0;for(const r of t){const e=r.trim();e&&(o++,z.test(e)?n+=2:G.test(e)||P.test(e)?n++:Z.test(e)?n+=2:W.test(e)||O.test(e)?n++:V.test(e)?n+=2:K.test(e)||X.test(e)||U.test(e)||q.test(e)?n++:j.test(e)?n+=2:($.test(e)||Y.test(e)||J.test(e))&&n++)}if(0===o)return!1;return n/o>=.3||n>=2}function ee(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function te(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function ne(e){const t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}function oe(e){return new Promise(((t,n)=>{const o=new FileReader;o.onload=e=>t(e.target.result),o.onerror=()=>n(new Error(`Failed to read file: ${e.name}`)),o.readAsText(e)}))}function re(e){return new Promise(((t,n)=>{const o=new FileReader;o.onload=e=>t(e.target.result),o.onerror=()=>n(new Error(`Failed to read file: ${e.name}`)),o.readAsArrayBuffer(e)}))}function ie(e){return te(e)}const se={"application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/pdf":"pdf","text/markdown":"markdown","text/x-markdown":"markdown","text/html":"html","text/plain":"text","text/csv":"csv","application/csv":"csv","text/rtf":"rtf","application/rtf":"rtf"},ae={".docx":"docx",".pdf":"pdf",".md":"markdown",".markdown":"markdown",".html":"html",".htm":"html",".txt":"text",".csv":"csv",".tsv":"csv",".rtf":"rtf"};function le(e){if(e.type&&se[e.type])return se[e.type];const t=ne(e.name||"");return ae[t]||null}function ce(e){return null!==le(e)}function de(){return Object.keys(ae).join(",")}function ue(){return["PDF","DOCX","Markdown","HTML","TXT","CSV","TSV","RTF"]}async function he(e){const t=le(e);if(!t)throw new Error(`Unsupported file format: ${e.name}`);const n={docx:()=>import("./convertDocx-D-V0dfFd.js"),pdf:()=>import("./convertPdf-D4SNUyBk.js"),markdown:()=>import("./convertMarkdown-1BmsjWXP.js"),html:()=>import("./convertHtml-gycStuZn.js"),text:()=>import("./convertText-DCGItleK.js"),csv:()=>import("./convertCsv-DRxJY6iq.js"),rtf:()=>import("./convertRtf-JWu514-h.js")},o=await n[t](),r=await o.default(e);return"string"==typeof r?F(r):r}const me=[["undo","redo"],["headings","fontFamily","fontSize"],["bold","italic","underline","strikethrough"],["foreColor","backColor"],["alignLeft","alignCenter","alignRight","alignJustify"],["orderedList","unorderedList","taskList"],["outdent","indent"],["link","image","attachment","importDocument","table","embedMedia","blockquote","codeBlock","horizontalRule"],["subscript","superscript","removeFormat"],["insertCallout","insertMath","insertToc","insertBookmark","insertMergeTag"],["findReplace","toggleMarkdown","sourceMode","toggleAnalytics","toggleSpellcheck","distractionFree","toggleSplitView","export","commandPalette","fullscreen"]],ge=["Arial","Arial Black","Courier New","Georgia","Helvetica","Impact","Lucida Console","Palatino Linotype","Tahoma","Times New Roman","Trebuchet MS","Verdana","Comic Sans MS","Segoe UI","Roboto","Open Sans"],pe=[{label:"8px",value:"8px"},{label:"10px",value:"10px"},{label:"12px",value:"12px"},{label:"14px",value:"14px"},{label:"16px",value:"16px"},{label:"18px",value:"18px"},{label:"20px",value:"20px"},{label:"24px",value:"24px"},{label:"28px",value:"28px"},{label:"32px",value:"32px"},{label:"36px",value:"36px"},{label:"48px",value:"48px"},{label:"64px",value:"64px"},{label:"72px",value:"72px"}],fe=["#000000","#434343","#666666","#999999","#b7b7b7","#cccccc","#d9d9d9","#efefef","#f3f3f3","#ffffff","#980000","#ff0000","#ff9900","#ffff00","#00ff00","#00ffff","#4a86e8","#0000ff","#9900ff","#ff00ff","#e6b8af","#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#c9daf8","#cfe2f3","#d9d2e9","#ead1dc","#dd7e6b","#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#a4c2f4","#9fc5e8","#b4a7d6","#d5a6bd","#cc4125","#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6d9eeb","#6fa8dc","#8e7cc3","#c27ba0","#a61c00","#cc0000","#e69138","#f1c232","#6aa84f","#45818e","#3c78d8","#3d85c6","#674ea7","#a64d79","#85200c","#990000","#b45f06","#bf9000","#38761d","#134f5c","#1155cc","#0b5394","#351c75","#741b47","#5b0f00","#660000","#783f04","#7f6000","#274e13","#0c343d","#1c4587","#073763","#20124d","#4c1130"],be=[{label:"File",items:["importDocument","export"]},{label:"Edit",items:["undo","redo","---","findReplace"]},{label:"View",items:["fullscreen","distractionFree","toggleSplitView","---","toggleMarkdown","sourceMode","---","toggleAnalytics","toggleSpellcheck"]},{label:"Insert",items:["link","image","table","attachment","embedMedia","---","blockquote","codeBlock","horizontalRule","---","insertCallout","insertMath","insertToc","insertBookmark","insertMergeTag","---","addComment"]},{label:"Format",items:["bold","italic","underline","strikethrough","---","subscript","superscript","---",{label:"Alignment",items:["alignLeft","alignCenter","alignRight","alignJustify"]},"---","orderedList","unorderedList","taskList","---","foreColor","backColor","---",{label:"Typography",items:["lineHeight","letterSpacing","paragraphSpacing"]},"---","removeFormat"]}],ye=[{label:"Normal",value:"p",tag:"p"},{label:"Heading 1",value:"h1",tag:"h1"},{label:"Heading 2",value:"h2",tag:"h2"},{label:"Heading 3",value:"h3",tag:"h3"},{label:"Heading 4",value:"h4",tag:"h4"},{label:"Heading 5",value:"h5",tag:"h5"},{label:"Heading 6",value:"h6",tag:"h6"}];function ve(e,t,n){const o=t??10485760;if(o>0&&e.size>o){(e.size/1048576).toFixed(1),(o/1048576).toFixed(0);return n?.eventBus&&n.eventBus.emit("file:too-large",{file:e,maxSize:o}),!0}return!1}let Ce=null,xe=!1;const _e=/* @__PURE__ */new Set(["http:","https:","mailto:","tel:"]);function we(e){if(!e)return!1;if(/^(\/|#)/.test(e))return!0;try{const t=decodeURIComponent(e),n=new URL(t,"https://placeholder.invalid");return _e.has(n.protocol)}catch{return!1}}function ke(n){return n&&"<p><br></p>"!==n?(Ce||(Ce=new e({headingStyle:"atx",hr:"---",bulletListMarker:"-",codeBlockStyle:"fenced",fence:"```",emDelimiter:"*",strongDelimiter:"**",linkStyle:"inlined"}),Ce.use(t),Ce.addRule("lineBreak",{filter:"br",replacement:()=>" \n"}),Ce.addRule("taskCheckbox",{filter:e=>"INPUT"===e.nodeName&&"checkbox"===e.type&&e.classList.contains("rmx-task-checkbox"),replacement:(e,t)=>t.checked?"[x] ":"[ ] "}),Ce.addRule("fencedCodeBlockWithLanguage",{filter:e=>"PRE"===e.nodeName&&e.firstChild&&"CODE"===e.firstChild.nodeName,replacement(e,t){const n=t.firstChild;return`\n\n\`\`\`${n.getAttribute("data-language")||""}\n${n.textContent}\n\`\`\`\n\n`}}),Ce.addRule("underline",{filter:["u"],replacement:e=>`<u>${e}</u>`})),Ce).turndown(n):""}function Se(e){return e?(function(){if(!xe){n.setOptions({gfm:!0,breaks:!1});const e=new n.Renderer;e.link=({href:e,title:t,tokens:o})=>{const r=n.Parser.parseInline(o);return e&&!we(e)?r:`<a href="${e}"${t?` title="${t.replace(/"/g,"&quot;")}"`:""}>${r}</a>`},e.image=({href:e,title:t,text:n})=>!e||we(e)||e.startsWith("data:image/")?`<img src="${e}" alt="${n||""}"${t?` title="${t.replace(/"/g,"&quot;")}"`:""} />`:n||"",e.code=({text:e,lang:t})=>{const n=t?` data-language="${t.replace(/"/g,"&quot;")}"`:"";return`<pre${n}><code${n}>${ee(e)}</code></pre>\n`},n.use({renderer:e}),xe=!0}}(),n.parse(e)):""}function Ie(e,t){if("markdown"===e.outputFormat||Q(t)){let n=Se(t);n=e.sanitizer.sanitize(n),e.selection.insertHTML(n)}else{const n=ee(t).split(/\n\n+/).map((e=>`<p>${e.replace(/\n/g,"<br>")}</p>`)).join("");e.selection.insertHTML(n||"<p><br></p>")}}class Ee{constructor(e){this.engine=e,this._handlePaste=this._handlePaste.bind(this),this._handleCopy=this._handleCopy.bind(this),this._handleCut=this._handleCut.bind(this)}init(){this.engine.element.addEventListener("paste",this._handlePaste),this.engine.element.addEventListener("copy",this._handleCopy),this.engine.element.addEventListener("cut",this._handleCut)}destroy(){this.engine.element.removeEventListener("paste",this._handlePaste),this.engine.element.removeEventListener("copy",this._handleCopy),this.engine.element.removeEventListener("cut",this._handleCut)}_handlePaste(e){e.preventDefault(),this.engine.history.snapshot();const t=e.clipboardData||window.clipboardData;let n=t.getData("text/html");const o=t.getData("text/plain"),r=Array.from(t.files||[]),i=r.find((e=>e.type.startsWith("image/")));if(i)return void this._handleImagePaste(i);const s=r.filter((e=>!e.type.startsWith("image/")&&ce(e)));if(s.length>0){const e=s.filter((e=>!this._exceedsMaxFileSize(e)));let t=Promise.resolve();for(const n of e)t=t.then((()=>he(n).then((e=>{const t=this.engine.sanitizer.sanitize(e);this.engine.selection.insertHTML(t),this.engine.eventBus.emit("content:change")})).catch((e=>{}))));return}const a=r.filter((e=>!e.type.startsWith("image/")));if(a.length>0&&this.engine.options.uploadHandler){let e=Promise.resolve();for(const t of a)e=e.then((()=>this.engine.options.uploadHandler(t).then((e=>{this.engine.commands.execute("insertAttachment",{url:e,filename:t.name,filesize:t.size})})).catch((e=>{this.engine.eventBus.emit("upload:error",{file:t,error:e})}))));return}const l=this._getCaretCell();if(l){const e=l.closest("table");if(e){if(o&&this._looksLikeTSV(o))return this._pasteIntoTable(e,l,o),this.engine.eventBus.emit("paste",{html:n,text:o}),void this.engine.eventBus.emit("content:change");if(n&&/<table/i.test(n)){const t=F(n),r=this._htmlTableToTSV(t);if(r)return this._pasteIntoTable(e,l,r),this.engine.eventBus.emit("paste",{html:n,text:o}),void this.engine.eventBus.emit("content:change")}}}n?(n=F(n),n=this.engine.sanitizer.sanitize(n),this.engine.selection.insertHTML(n)):o&&this._handleTextPaste(o),this.engine.eventBus.emit("paste",{html:n,text:o}),this.engine.eventBus.emit("content:change")}_handleTextPaste(e){Ie(this.engine,e)}_handleCopy(e){const t=window.getSelection();if(!t||0===t.rangeCount)return;const n=t.anchorNode?.nodeType===Node.TEXT_NODE?t.anchorNode.parentElement:t.anchorNode,o=t.focusNode?.nodeType===Node.TEXT_NODE?t.focusNode.parentElement:t.focusNode,r=n?.closest?.("table.rmx-table"),i=o?.closest?.("table.rmx-table");if(r&&i&&r===i){const t=r.querySelectorAll("thead tr, tbody tr"),n=[];let o="";for(const e of t){if(e.classList.contains("rmx-row-hidden"))continue;const t=e.querySelectorAll("td, th"),r=[];let i="";for(const e of t){const t=e.textContent.trim();t.includes("\t")||t.includes("\n")||t.includes('"')?r.push('"'+t.replace(/"/g,'""')+'"'):r.push(t);const n=e.tagName.toLowerCase();i+=`<${n}>${e.innerHTML}</${n}>`}n.push(r.join("\t")),o+=`<tr>${i}</tr>`}const i=n.join("\n"),s=`<table><tbody>${o}</tbody></table>`;e.preventDefault(),e.clipboardData.setData("text/plain",i),e.clipboardData.setData("text/html",s)}}_handleCut(){this.engine.history.snapshot(),setTimeout((()=>{this.engine.eventBus.emit("content:change")}),0)}_exceedsMaxFileSize(e){return ve(e,this.engine.options.maxFileSize,{eventBus:this.engine.eventBus})}_getCaretCell(){const e=window.getSelection();if(!e||!e.anchorNode)return null;const t=e.anchorNode.nodeType===Node.TEXT_NODE?e.anchorNode.parentElement:e.anchorNode;return t?.closest?.("td, th")||null}_looksLikeTSV(e){if(!e.includes("\t"))return!1;const t=e.trim().split("\n");return!(t.length<1)&&t[0].includes("\t")}_htmlTableToTSV(e){const t=(new DOMParser).parseFromString(e,"text/html").querySelector("table");if(!t)return null;const n=[],o=t.querySelectorAll("tr");for(const r of o){const e=r.querySelectorAll("td, th");n.push(Array.from(e).map((e=>e.textContent.trim())).join("\t"))}return n.join("\n")}_pasteIntoTable(e,t,n){const o=e.querySelector("tbody")||e,r=n.trim().split("\n").map((e=>e.split("\t"))),i=Array.from(e.querySelectorAll("tbody tr")),s=t.closest("tr");let a=i.indexOf(s);a<0&&(a=0);let l=0,c=t.previousElementSibling;for(;c;)l+=c.colSpan||1,c=c.previousElementSibling;for(let d=0;d<r.length;d++){const e=a+d;for(;i.length<=e;){const e=i[0]||s,t=e?e.cells.length:r[0].length,n=document.createElement("tr");for(let o=0;o<t;o++){const e=document.createElement("td");e.innerHTML="<br>",n.appendChild(e)}o.appendChild(n),i.push(n)}const t=i[e];for(let n=0;n<r[d].length;n++){const o=l+n;for(;t.cells.length<=o;){const n=document.createElement("td");n.innerHTML="<br>",t.appendChild(n),i.forEach(((t,n)=>{if(n!==e&&t.cells.length<=o){const e=document.createElement("td");e.innerHTML="<br>",t.appendChild(e)}}))}const s=t.cells[o];s&&(s.textContent=r[d][n])}}}_handleImagePaste(e){if(!this._exceedsMaxFileSize(e))if(this.engine.options.uploadHandler)this.engine.options.uploadHandler(e).then((t=>{this.engine.commands.execute("insertImage",{src:t,alt:e.name})})).catch((t=>{this.engine.eventBus.emit("upload:error",{file:e,error:t})}));else{const t=new FileReader;t.onprogress=e=>{e.lengthComputable&&this.engine.eventBus.emit("upload:progress",{loaded:e.loaded,total:e.total,percent:Math.round(e.loaded/e.total*100)})},t.onload=t=>{const n=t.target.result;this.engine.commands.execute("insertImage",{src:n,alt:e.name})},t.readAsDataURL(e)}}}const Ae="application/x-remyx-content",Be=/* @__PURE__ */new Set(["P","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","PRE","UL","OL","TABLE","HR","DIV"]),Le=/* @__PURE__ */new Set(["UL","OL","TBODY","TABLE"]),Te=/* @__PURE__ */new WeakMap,Ne=/* @__PURE__ */new Set;class Re{constructor(e){this.engine=e,this._dragSource=null,this._dragSourceEditor=null,this._dropTarget=null,this._dropPosition=null,this._ghostEl=null,this._dropIndicator=null,this._isExternalDrag=!1,this._enterCount=0,this._blockRects=null,this._scrollHandler=null,this._handleDragOver=this._handleDragOver.bind(this),this._handleDrop=this._handleDrop.bind(this),this._handleDragEnter=this._handleDragEnter.bind(this),this._handleDragLeave=this._handleDragLeave.bind(this),this._handleDragStart=this._handleDragStart.bind(this),this._handleDragEnd=this._handleDragEnd.bind(this)}init(){const e=this.engine.element;e.addEventListener("dragover",this._handleDragOver),e.addEventListener("drop",this._handleDrop),e.addEventListener("dragenter",this._handleDragEnter),e.addEventListener("dragleave",this._handleDragLeave),e.addEventListener("dragstart",this._handleDragStart),e.addEventListener("dragend",this._handleDragEnd),Te.set(e,this),Ne.add(this)}destroy(){const e=this.engine.element;e.removeEventListener("dragover",this._handleDragOver),e.removeEventListener("drop",this._handleDrop),e.removeEventListener("dragenter",this._handleDragEnter),e.removeEventListener("dragleave",this._handleDragLeave),e.removeEventListener("dragstart",this._handleDragStart),e.removeEventListener("dragend",this._handleDragEnd),Te.delete(e),Ne.delete(this),this._cleanupDrag()}getDraggableBlock(e){return this._closestDraggableBlock(e)}makeBlockDraggable(e){e&&!e.hasAttribute("draggable")&&e.setAttribute("draggable","true")}unmakeBlockDraggable(e){e&&e.removeAttribute("draggable")}isDragging(){return!!this._dragSource}getDragState(){return{isDragging:!!this._dragSource||this._isExternalDrag,isExternalDrag:this._isExternalDrag,dropTarget:this._dropTarget,dropPosition:this._dropPosition}}_handleDragStart(e){const t=this._getReorderableItem(e.target)||this._closestDraggableBlock(e.target);if(!t)return;this._dragSource=t,this._dragSourceEditor=this;const n=t.outerHTML,o=t.textContent;e.dataTransfer.setData(Ae,n),e.dataTransfer.setData("text/html",n),e.dataTransfer.setData("text/plain",o),e.dataTransfer.effectAllowed="move",this._createGhostPreview(t,e),this._cacheBlockRects(),t.classList.add("rmx-block-dragging");for(const r of Ne)r._dragSourceEditor=this,r._dragSource=t;this.engine.eventBus.emit("drag:start",{block:t})}_handleDragEnd(e){this._dragSource&&this._dragSource.classList.remove("rmx-block-dragging");for(const t of Ne)t._cleanupDrag();this.engine.eventBus.emit("drag:end")}_handleDragOver(e){e.preventDefault(),this._dragSource?e.dataTransfer.dropEffect="move":e.dataTransfer.dropEffect="copy",(this._dragSource||this._isExternalDrag)&&this._updateDropTarget(e)}_handleDragEnter(e){e.preventDefault(),this._enterCount++,1===this._enterCount&&(this._dragSource||(this._isExternalDrag=!0),this.engine.element.classList.add("rmx-drag-over"),this.engine.eventBus.emit("drag:enter",{isExternal:this._isExternalDrag,types:Array.from(e.dataTransfer.types||[])}))}_handleDragLeave(e){this._enterCount--,this._enterCount<=0&&(this._enterCount=0,this.engine.element.classList.remove("rmx-drag-over"),this._removeDropIndicator(),this._dropTarget=null,this._dropPosition=null,this._isExternalDrag&&!this._dragSource&&(this._isExternalDrag=!1),this.engine.eventBus.emit("drag:leave"))}_handleDrop(e){if(e.preventDefault(),this._enterCount=0,this.engine.element.classList.remove("rmx-drag-over"),this._removeDropIndicator(),this._dragSource&&this._dropTarget)return this._handleBlockDrop(e),void this._cleanupDrag();const t=Array.from(e.dataTransfer.files),n=t.filter((e=>e.type.startsWith("image/")));if(n.length>0)return this._handleImageDrop(e,n),void this._cleanupDrag();const o=t.filter((e=>!e.type.startsWith("image/")&&ce(e)));if(o.length>0)return this._handleDocumentDrop(e,o),void this._cleanupDrag();const r=t.filter((e=>!e.type.startsWith("image/")));if(r.length>0&&this.engine.options.uploadHandler)return this._handleFileDrop(e,r),void this._cleanupDrag();const i=e.dataTransfer.getData(Ae);if(i&&!this._dragSource)return this._handleInterEditorDrop(e,i),void this._cleanupDrag();this._setCursorAtDropPoint(e),this.engine.history.snapshot();const s=e.dataTransfer.getData("text/html");if(s){let e=F(s);e=this.engine.sanitizer.sanitize(e),this.engine.selection.insertHTML(e),this.engine.eventBus.emit("content:change")}else{const t=e.dataTransfer.getData("text/plain");t&&(this._handleTextDrop(t),this.engine.eventBus.emit("content:change"))}this.engine.eventBus.emit("drop",{files:t,html:s}),this._cleanupDrag()}_handleBlockDrop(e){const t=this._dragSource,n=this._dropTarget,o=this._dropPosition,r=this._dragSourceEditor;if(!t||!n||!o)return;if(t===n)return;this.engine.history.snapshot(),r&&r!==this&&r.engine.history.snapshot();const i=this._getReorderableItem(t),s=this._getReorderableItem(n);if(i&&s&&i.parentElement===s.parentElement)"before"===o?s.parentElement.insertBefore(i,s):s.parentElement.insertBefore(i,s.nextSibling);else{const e=n.parentElement;if(!e)return;"before"===o?e.insertBefore(t,n):e.insertBefore(t,n.nextSibling)}r&&r!==this&&r.engine.eventBus.emit("content:change"),this.engine.eventBus.emit("content:change"),this.engine.eventBus.emit("drag:reorder",{source:t,target:n,position:o})}_handleInterEditorDrop(e,t){this._setCursorAtDropPoint(e),this.engine.history.snapshot();const n=this.engine.sanitizer.sanitize(t);this.engine.selection.insertHTML(n),this.engine.eventBus.emit("content:change"),this.engine.eventBus.emit("drag:inter-editor",{html:n})}_cacheBlockRects(){this._blockRects=/* @__PURE__ */new Map;const e=this._getTopLevelBlocks();for(const t of e)this._blockRects.set(t,t.getBoundingClientRect());this._scrollHandler=()=>{this._blockRects=null},this.engine.element.addEventListener("scroll",this._scrollHandler,{passive:!0})}_getBlockRect(e){return this._blockRects&&this._blockRects.has(e)?this._blockRects.get(e):e.getBoundingClientRect()}_updateDropTarget(e){this.engine.element;const t=this._dragSource?this._getReorderableItem(this._dragSource):null,n=t&&t.parentElement?Array.from(t.parentElement.children).filter((e=>e.tagName===t.tagName)):this._getTopLevelBlocks();if(0===n.length)return this._dropTarget=null,this._dropPosition=null,void this._removeDropIndicator();const o=e.clientY;let r=null,i=null,s=1/0;for(const a of n){if(a===this._dragSource)continue;const e=this._getBlockRect(a),t=e.top+e.height/2,n=Math.abs(o-e.top),l=Math.abs(o-e.bottom);if(n<s&&(s=n,r=a,i="before"),l<s&&(s=l,r=a,i="after"),o>=e.top&&o<=e.bottom){r=a,i=o<t?"before":"after",s=0;break}}r===this._dropTarget&&i===this._dropPosition||(this._dropTarget=r,this._dropPosition=i,r?this._showDropIndicator(r,i):this._removeDropIndicator())}_getTopLevelBlocks(){const e=[],t=this.engine.element;for(let n=0;n<t.children.length;n++){const o=t.children[n];o.nodeType!==Node.ELEMENT_NODE||o.classList.contains("rmx-drop-indicator")||o.classList.contains("rmx-drag-ghost")||e.push(o)}return e}_showDropIndicator(e,t){this._dropIndicator||(this._dropIndicator=document.createElement("div"),this._dropIndicator.className="rmx-drop-indicator",this._dropIndicator.setAttribute("aria-hidden","true"));const n=this.engine.element,o=n.getBoundingClientRect(),r=e.getBoundingClientRect(),i="before"===t?r.top-o.top+n.scrollTop:r.bottom-o.top+n.scrollTop;this._dropIndicator.style.top=`${i}px`,this._dropIndicator.parentElement||n.appendChild(this._dropIndicator),this.engine.eventBus.emit("drag:indicator",{target:e,position:t,top:i})}_removeDropIndicator(){this._dropIndicator&&this._dropIndicator.parentElement&&this._dropIndicator.parentElement.removeChild(this._dropIndicator),this._dropIndicator=null}_createGhostPreview(e,t){const n=e.cloneNode(!0);n.className="rmx-drag-ghost",n.style.position="absolute",n.style.top="-9999px",n.style.left="-9999px",n.style.width=`${e.offsetWidth}px`,n.style.pointerEvents="none",document.body.appendChild(n),this._ghostEl=n;const o=e.getBoundingClientRect(),r=t.clientX-o.left,i=t.clientY-o.top;t.dataTransfer.setDragImage(n,r,i)}_removeGhostPreview(){this._ghostEl&&this._ghostEl.parentElement&&this._ghostEl.parentElement.removeChild(this._ghostEl),this._ghostEl=null}_closestDraggableBlock(e){let t=e.nodeType===Node.TEXT_NODE?e.parentElement:e;const n=this.engine.element;for(;t&&t!==n;){if(t.parentElement===n&&Be.has(t.tagName))return t;t=t.parentElement}return null}_getReorderableItem(e){let t=e.nodeType===Node.TEXT_NODE?e.parentElement:e;const n=this.engine.element;for(;t&&t!==n;){if(("LI"===t.tagName||"TR"===t.tagName)&&t.parentElement&&Le.has(t.parentElement.tagName))return t;t=t.parentElement}return null}_cleanupDrag(){this._dragSource&&this._dragSource.classList.remove("rmx-block-dragging"),this._dragSource=null,this._dragSourceEditor=null,this._dropTarget=null,this._dropPosition=null,this._isExternalDrag=!1,this._enterCount=0,this._blockRects=null,this._scrollHandler&&(this.engine.element.removeEventListener("scroll",this._scrollHandler),this._scrollHandler=null),this._removeDropIndicator(),this._removeGhostPreview(),this.engine.element.classList.remove("rmx-drag-over")}_exceedsMaxFileSize(e){return ve(e,this.engine.options.maxFileSize,{eventBus:this.engine.eventBus})}_handleImageDrop(e,t){this._setCursorAtDropPoint(e),this.engine.history.snapshot();const n=t.filter((e=>!this._exceedsMaxFileSize(e)));let o=Promise.resolve();for(const r of n)o=o.then((()=>this.engine.options.uploadHandler?this.engine.options.uploadHandler(r).then((e=>{this.engine.commands.execute("insertImage",{src:e,alt:r.name})})).catch((e=>{this.engine.eventBus.emit("upload:error",{file:r,error:e})})):new Promise((e=>{const t=new FileReader;t.onprogress=e=>{e.lengthComputable&&this.engine.eventBus.emit("upload:progress",{loaded:e.loaded,total:e.total,percent:Math.round(e.loaded/e.total*100)})},t.onload=t=>{this.engine.commands.execute("insertImage",{src:t.target.result,alt:r.name}),e()},t.onerror=()=>e(),t.readAsDataURL(r)}))))}_handleDocumentDrop(e,t){this._setCursorAtDropPoint(e),this.engine.history.snapshot(),t.filter((e=>!this._exceedsMaxFileSize(e))).forEach((e=>{he(e).then((e=>{const t=this.engine.sanitizer.sanitize(e);this.engine.selection.insertHTML(t),this.engine.eventBus.emit("content:change")})).catch((e=>{}))}))}_handleFileDrop(e,t){this._setCursorAtDropPoint(e),this.engine.history.snapshot();let n=Promise.resolve();for(const o of t)n=n.then((()=>this.engine.options.uploadHandler(o).then((e=>{this.engine.commands.execute("insertAttachment",{url:e,filename:o.name,filesize:o.size})})).catch((e=>{this.engine.eventBus.emit("upload:error",{file:o,error:e})}))))}_setCursorAtDropPoint(e){const t=document.caretRangeFromPoint?document.caretRangeFromPoint(e.clientX,e.clientY):null;if(t){const e=window.getSelection();e.removeAllRanges(),e.addRange(t)}}_handleTextDrop(e){Ie(this.engine,e)}}function He(e,t,n){return{get element(){return e.element},executeCommand:(t,...n)=>e.commands.execute(t,...n),on:(t,n)=>e.eventBus.on(t,n),off(t,n){e.eventBus.off(t,n)},getSelection:()=>e.selection.getSelection(),getRange:()=>e.selection.getRange(),getActiveFormats:()=>e.selection.getActiveFormats(),getHTML:()=>e.getHTML(),getText:()=>e.getText(),isEmpty:()=>e.isEmpty(),get options(){return{...e.options}},getSetting:e=>n.getPluginSetting(t,e),setSetting(e,o){n.setPluginSetting(t,e,o)}}}Re._getRegistry=()=>Te,Re._getActiveInstances=()=>Ne;const Me=/* @__PURE__ */new Map;function De(e){e&&e.name&&Me.set(e.name,e)}function Fe(e){return Me.delete(e)}function ze(){return Array.from(Me.values())}function Ge(e){if(!e)return ze();const t=e.toLowerCase();return ze().filter((e=>e.name.toLowerCase().includes(t)||(e.description||"").toLowerCase().includes(t)||(e.tags||[]).some((e=>e.toLowerCase().includes(t)))))}class Pe{constructor(e){this.engine=e,this._plugins=/* @__PURE__ */new Map,this._initialized=/* @__PURE__ */new Set,this._commandPluginMap=/* @__PURE__ */new Map,this._settings=/* @__PURE__ */new Map,this._lifecycleUnsubs=/* @__PURE__ */new Map}getPluginSetting(e,t){const n=this._settings.get(e);if(n&&n.has(t))return n.get(t);const o=this._plugins.get(e);return o?.defaultSettings&&t in o.defaultSettings?o.defaultSettings[t]:void 0}setPluginSetting(e,t,n){const o=this._plugins.get(e);if(!o)return!1;if(o.settingsSchema&&o.settingsSchema.length>0){const e=o.settingsSchema.find((e=>e.key===t));if(e){if("boolean"===e.type&&"boolean"!=typeof n)return!1;if("number"===e.type&&"number"!=typeof n)return!1;if("string"===e.type&&"string"!=typeof n)return!1;if("select"===e.type){if(!(e.options||[]).map((e=>e.value)).includes(n))return!1}if(e.validate&&!e.validate(n))return!1}}return this._settings.has(e)||this._settings.set(e,/* @__PURE__ */new Map),this._settings.get(e).set(t,n),this.engine.eventBus.emit("plugin:settingChanged",{pluginName:e,key:t,value:n}),!0}getPluginSettings(e){const t=this._plugins.get(e),n={...t?.defaultSettings||{}},o=this._settings.get(e);if(o)for(const[r,i]of o)n[r]=i;return n}_resolveDependencyOrder(e){const t=new Set(e.map((e=>e.name))),n=/* @__PURE__ */new Map,o=/* @__PURE__ */new Map;for(const l of e){const e=(l.dependencies||[]).filter((e=>t.has(e)));n.set(l.name,e),o.set(l.name,e.length)}const r=[];for(const[l,c]of o)0===c&&r.push(l);const i=[];for(;r.length>0;){const e=r.shift();i.push(e);for(const[t,i]of n)i.includes(e)&&(o.set(t,o.get(t)-1),0===o.get(t)&&r.push(t))}const s=[];if(i.length<e.length){const t=e.filter((e=>!i.includes(e.name))).map((e=>e.name));s.push(t)}const a=new Map(e.map((e=>[e.name,e])));return{sorted:i.map((e=>a.get(e))),circular:s}}register(e){e&&e.name&&(this._plugins.has(e.name)||(this._plugins.set(e.name,e),e.defaultSettings&&(this._settings.has(e.name)||this._settings.set(e.name,/* @__PURE__ */new Map)),e.commands&&e.commands.forEach((t=>{if(e.lazy){this._commandPluginMap.set(t.name,e.name);const n=t.execute,o=this,r={...t,execute(...r){return o.activatePlugin(e.name),o.engine.commands.register(t.name,{...t,execute:n}),n.apply(this,r)}};this.engine.commands.register(t.name,r)}else this.engine.commands.register(t.name,t)})),this.engine.eventBus.emit("plugin:registered",{name:e.name})))}_initPlugin(e){if(!this._initialized.has(e.name))try{const t=e.requiresFullAccess?this.engine:He(this.engine,e.name,this);e.init&&e.init(t);const n=[];if("function"==typeof e.onContentChange){const o=()=>{try{e.onContentChange(t)}catch(n){this.engine.eventBus.emit("plugin:error",{name:e.name,error:n,hook:"onContentChange"})}};n.push(this.engine.eventBus.on("content:change",o))}if("function"==typeof e.onSelectionChange){const o=()=>{try{e.onSelectionChange(t)}catch(n){this.engine.eventBus.emit("plugin:error",{name:e.name,error:n,hook:"onSelectionChange"})}};n.push(this.engine.eventBus.on("selection:change",o))}n.length>0&&this._lifecycleUnsubs.set(e.name,n),this._initialized.add(e.name),this.engine.eventBus.emit("plugin:initialized",{name:e.name})}catch(t){this.engine.eventBus.emit("plugin:error",{name:e.name,error:t})}}activatePlugin(e){const t=this._plugins.get(e);if(t&&!this._initialized.has(e)){for(const e of t.dependencies||[])this._plugins.has(e)&&!this._initialized.has(e)&&this.activatePlugin(e);this._initPlugin(t)}}initAll(){const e=[];this._plugins.forEach((t=>{t.lazy||e.push(t)}));const{sorted:t,circular:n}=this._resolveDependencyOrder(e);if(n.length>0)for(const o of n)this.engine.eventBus.emit("plugin:circularDependency",{plugins:o});for(const o of t)this._initPlugin(o);for(const o of e)this._initialized.has(o.name)||this._initPlugin(o)}destroyAll(){this._plugins.forEach((e=>{try{if((!e.lazy||this._initialized.has(e.name))&&e.destroy){const t=e.requiresFullAccess?this.engine:He(this.engine,e.name,this);e.destroy(t)}const t=this._lifecycleUnsubs.get(e.name);if(t)for(const e of t)e?.()}catch(t){this.engine.eventBus.emit("plugin:error",{name:e.name,error:t})}})),this._plugins.clear(),this._initialized.clear(),this._commandPluginMap.clear(),this._settings.clear(),this._lifecycleUnsubs.clear()}get(e){return this._plugins.get(e)}getAll(){return Array.from(this._plugins.values())}has(e){return this._plugins.has(e)}isInitialized(e){return this._initialized.has(e)}}const Ze=/* @__PURE__ */new WeakMap;let We=!1;function Oe(){const e=document.activeElement;if(e){let t=e;for(;t;){const e=Ze.get(t);if(e)return void e._handleSelectionChange();t=t.parentElement}}const t=window.getSelection();if(t&&t.anchorNode){let e=t.anchorNode;for(;e;){const t=Ze.get(e);if(t)return void t._handleSelectionChange();e=e.parentNode}}}class Ve{constructor(e,t={}){this.element=e,this.options=t,this.outputFormat=t.outputFormat||"html",this.isSourceMode=!1,this.isMarkdownMode=!1,this._isDestroyed=!1,this._htmlDirty=!0,this._lastHTML="",this._textCache=null,this._textCacheDirty=!0,this.eventBus=new o,this.selection=new g(e),this.keyboard=new _(this),this.commands=new p(this),this.history=new y(this,t.history),this.sanitizer=new L(t.sanitize),this.selection.setSanitizer(this.sanitizer),this.clipboard=new Ee(this),this.dragDrop=new Re(this),this.plugins=new Pe(this),this._handleInput=this._handleInput.bind(this),this._handleSelectionChange=this._handleSelectionChange.bind(this),this._handleFocus=this._handleFocus.bind(this),this._handleBlur=this._handleBlur.bind(this),this._handleClick=this._handleClick.bind(this)}init(){try{this.element.setAttribute("contenteditable","true"),this.element.setAttribute("role","textbox"),this.element.setAttribute("aria-multiline","true"),this.element.setAttribute("spellcheck","true"),this.element.innerHTML.trim()||(this.element.innerHTML="<p><br></p>"),this.element.addEventListener("input",this._handleInput),this.element.addEventListener("focus",this._handleFocus),this.element.addEventListener("blur",this._handleBlur),this.element.addEventListener("click",this._handleClick),Ze.set(this.element,this),We||(document.addEventListener("selectionchange",Oe),We=!0),this.keyboard.init(),this.history.init(),this.clipboard.init(),this.dragDrop.init(),this.plugins.initAll()}catch(e){throw this.eventBus.emit("editor:error",{phase:"init",error:e}),e}}destroy(){this._isDestroyed||(this._isDestroyed=!0,this.element.removeEventListener("input",this._handleInput),this.element.removeEventListener("focus",this._handleFocus),this.element.removeEventListener("blur",this._handleBlur),this.element.removeEventListener("click",this._handleClick),Ze.delete(this.element),this.eventBus.emit("destroy"),this.keyboard.destroy(),this.history.destroy(),this.clipboard.destroy(),this.dragDrop.destroy(),this.plugins.destroyAll(),this.eventBus.removeAllListeners(),this.element.removeAttribute("contenteditable"))}getHTML(){return this._htmlDirty?(this._lastHTML=this.sanitizer.sanitize(this.element.innerHTML),this._htmlDirty=!1,this._lastHTML):this._lastHTML}setHTML(e){const t=this.sanitizer.sanitize(e);this.element.innerHTML=t||"<p><br></p>",this._htmlDirty=!0,this._textCacheDirty=!0}getText(){return this._textCacheDirty||null===this._textCache?(this._textCache=this.element.textContent||"",this._textCacheDirty=!1,this._textCache):this._textCache}isEmpty(){const e=this.getText().trim();return""===e||"\n"===e}focus(){this.element.focus()}blur(){this.element.blur()}executeCommand(e,...t){return this.commands.execute(e,...t)}on(e,t){return this.eventBus.on(e,t)}off(e,t){this.eventBus.off(e,t)}getWordCount(){const e=this.getText().trim();return e?e.split(/\s+/).length:0}getCharCount(){return this.getText().length}_handleInput(){if(this._htmlDirty=!0,this._textCacheDirty=!0,""===this.element.innerHTML||"<br>"===this.element.innerHTML){this.element.innerHTML="<p><br></p>";const e=document.createRange();e.setStart(this.element.firstChild,0),e.collapse(!0),this.selection.setRange(e)}this.eventBus.emit("content:change")}_handleSelectionChange(){if(!this.selection.isWithinEditor(document.activeElement))return;if(!this.selection.getRange())return;const e=this.selection.getActiveFormats();this.eventBus.emit("selection:change",e)}_handleFocus(){this.eventBus.emit("focus")}_handleBlur(){this.eventBus.emit("blur")}_handleClick(e){"checkbox"===e.target.type&&e.target.classList.contains("rmx-task-checkbox")&&(e.target.checked=!e.target.checked,this._htmlDirty=!0,this._textCacheDirty=!0,this.eventBus.emit("content:change"))}}const Ke=new class{constructor(){this._bus=new o,this._registry=/* @__PURE__ */new Map}register(e,t){this._registry.set(e,t),this._bus.emit("editor:registered",{id:e,engine:t})}unregister(e){this._registry.delete(e),this._bus.emit("editor:unregistered",{id:e})}getEditor(e){return this._registry.get(e)}getEditorIds(){return[...this._registry.keys()]}get editorCount(){return this._registry.size}on(e,t,n){return this._bus.on(e,t,n)}off(e,t){this._bus.off(e,t)}once(e,t){return this._bus.once(e,t)}emit(e,t){this._bus.emit(e,t)}broadcast(e,t,n){for(const[o,r]of this._registry)n?.exclude&&o===n.exclude||r.eventBus.emit(e,t)}reset(){this._bus.removeAllListeners(),this._registry.clear()}},Xe={full:me,standard:[["undo","redo"],["headings","fontFamily","fontSize"],["bold","italic","underline","strikethrough"],["foreColor","backColor"],["alignLeft","alignCenter","alignRight","alignJustify"],["orderedList","unorderedList","taskList"],["outdent","indent"],["link","image","table","blockquote","codeBlock","horizontalRule"],["fullscreen"]],minimal:[["headings"],["bold","italic","underline"],["orderedList","unorderedList"],["link","image","blockquote"]],bare:[["bold","italic","underline"]],rich:[["undo","redo"],["headings","fontFamily","fontSize","typography"],["bold","italic","underline","strikethrough"],["foreColor","backColor"],["alignLeft","alignCenter","alignRight"],["orderedList","unorderedList","taskList"],["outdent","indent"],["link","image","attachment","table","embedMedia","blockquote","codeBlock","horizontalRule"],["insertCallout","insertMath","insertToc","insertBookmark","insertMergeTag"],["subscript","superscript","removeFormat"],["findReplace","toggleMarkdown","sourceMode","toggleAnalytics","distractionFree","toggleSplitView","export","commandPalette","fullscreen"]]};function Ue(e,t){const n=new Set(t);return e.map((e=>e.filter((e=>!n.has(e))))).filter((e=>e.length>0))}function qe(e,t,n={}){const o=Array.isArray(t)?t:[t],r=e.map((e=>[...e]));if(n.after||n.before){const e=n.after||n.before;for(let t=0;t<r.length;t++){const i=r[t].indexOf(e);if(-1!==i){const e=n.after?i+1:i;return r[t].splice(e,0,...o),r}}}if(void 0!==n.group){const e=n.group<0?r.length+n.group:n.group;if(e>=0&&e<r.length)return r[e].push(...o),r}return r.push(o),r}function je(e){const t=[{commands:["undo","redo"]},{commands:["headings","fontFamily","fontSize"]},{commands:["bold","italic","underline","strikethrough"]},{commands:["foreColor","backColor"]},{commands:["alignLeft","alignCenter","alignRight","alignJustify"]},{commands:["orderedList","unorderedList","taskList"]},{commands:["outdent","indent"]},{commands:["link","image","attachment","importDocument","table","embedMedia","blockquote","codeBlock","horizontalRule"]},{commands:["subscript","superscript"]},{commands:["findReplace","toggleMarkdown","sourceMode","export","fullscreen"]}],n=new Set(e),o=[];for(const r of t){const e=r.commands.filter((e=>n.has(e)));e.length>0&&(o.push(e),e.forEach((e=>n.delete(e))))}return n.size>0&&o.push([...n]),o}const $e=/* @__PURE__ */new Set(["bold","italic","underline","strikethrough","subscript","superscript","alignLeft","alignCenter","alignRight","alignJustify","orderedList","unorderedList","taskList","blockquote","codeBlock","horizontalRule","undo","redo","removeFormat","indent","outdent","fullscreen","sourceMode","toggleMarkdown","distractionFree","toggleSplitView","insertCallout","insertMath","insertToc","insertBookmark","insertMergeTag","toggleAnalytics","toggleSpellcheck","checkGrammar","startCollaboration","stopCollaboration","addComment","removeFormat","lineHeight","letterSpacing","paragraphSpacing"]),Ye={bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",subscript:"Subscript",superscript:"Superscript",alignLeft:"Align Left",alignCenter:"Align Center",alignRight:"Align Right",alignJustify:"Justify",orderedList:"Numbered List",unorderedList:"Bulleted List",taskList:"Task List",blockquote:"Blockquote",codeBlock:"Code Block",horizontalRule:"Horizontal Rule",undo:"Undo",redo:"Redo",removeFormat:"Remove Formatting",indent:"Indent",outdent:"Outdent",link:"Insert Link",image:"Insert Image",attachment:"Attach File",table:"Insert Table",importDocument:"Import Document",embedMedia:"Embed Media",findReplace:"Find & Replace",fullscreen:"Fullscreen",sourceMode:"Source Code",toggleMarkdown:"Toggle Markdown",export:"Export Document",distractionFree:"Distraction-Free Mode",toggleSplitView:"Split View",lineHeight:"Line Height",letterSpacing:"Letter Spacing",paragraphSpacing:"Paragraph Spacing",saveColorPreset:"Save Color Preset",typography:"Typography",foreColor:"Text Color",backColor:"Background Color",headings:"Block Type",fontFamily:"Font Family",fontSize:"Font Size",commandPalette:"Command Palette",insertCallout:"Insert Callout",insertMath:"Insert Math",insertToc:"Insert Table of Contents",insertBookmark:"Insert Bookmark",insertMergeTag:"Insert Merge Tag",addComment:"Add Comment",scanBrokenLinks:"Scan Broken Links",getAnalytics:"Content Analytics",toggleAnalytics:"Toggle Analytics",toggleSpellcheck:"Toggle Spellcheck",checkGrammar:"Check Grammar",startCollaboration:"Start Collaboration",stopCollaboration:"Stop Collaboration"},Je={bold:"mod+B",italic:"mod+I",underline:"mod+U",strikethrough:"mod+Shift+X",undo:"mod+Z",redo:"mod+Shift+Z",insertLink:"mod+K",findReplace:"mod+F",fullscreen:"mod+Shift+F",sourceMode:"mod+Shift+U",commandPalette:"mod+Shift+P",distractionFree:"mod+Shift+D",toggleSplitView:"mod+Shift+V"},Qe={link:"link",image:"image",attachment:"attachment",importDocument:"importDocument",table:"table",embedMedia:"embed",findReplace:"findReplace",export:"export"};function et(e){const t=Je[e];return t?t.replace(/mod/g,C()?"⌘":"Ctrl"):""}function tt(e,t,n){switch(e){case"bold":return t.bold;case"italic":return t.italic;case"underline":return t.underline;case"strikethrough":return t.strikethrough;case"subscript":return t.subscript;case"superscript":return t.superscript;case"alignLeft":return"left"===t.alignment;case"alignCenter":return"center"===t.alignment;case"alignRight":return"right"===t.alignment;case"alignJustify":return"justify"===t.alignment;case"orderedList":return t.orderedList;case"unorderedList":return t.unorderedList;case"blockquote":return t.blockquote;case"codeBlock":return t.codeBlock;case"sourceMode":return n?.isSourceMode;case"toggleMarkdown":return n?.isMarkdownMode;case"fullscreen":return n?.element?.closest(".rmx-editor")?.classList.contains("rmx-fullscreen");case"distractionFree":return n?.element?.closest(".rmx-editor")?.classList.contains("rmx-distraction-free");case"toggleSplitView":return n?.element?.closest(".rmx-editor")?.classList.contains("rmx-split-view");default:return!1}}const nt={bold:"mod+b",italic:"mod+i",underline:"mod+u",strikethrough:"mod+shift+x",undo:"mod+z",redo:"mod+shift+z",selectAll:"mod+a",insertLink:"mod+k",findReplace:"mod+f",orderedList:"mod+shift+7",unorderedList:"mod+shift+8",blockquote:"mod+shift+9",codeBlock:"mod+shift+c",indent:"tab",outdent:"shift+tab",fullscreen:"mod+shift+f",sourceMode:"mod+shift+u",subscript:"mod+,",superscript:"mod+."};const ot=new class{constructor(){this._initialized=!1,this._sanitizerSchema=null,this._toolbarPresets=null,this._defaults=null,this._keybindings=null,this._commands=null,this._icons=/* @__PURE__ */new Map}_ensureInit(){this._initialized||(this._initialized=!0,this._sanitizerSchema=Object.freeze({allowedTags:Object.freeze(Object.fromEntries(Object.entries(w).map((([e,t])=>[e,Object.freeze([...t])])))),allowedStyles:Object.freeze([...k])}),this._toolbarPresets=Object.freeze(Object.fromEntries(Object.entries(Xe).map((([e,t])=>[e,Object.freeze(t.map((e=>Object.freeze([...e]))))])))),this._defaults=Object.freeze({toolbar:Object.freeze(me.map((e=>Object.freeze([...e])))),menuBar:Object.freeze(be),fonts:Object.freeze([...ge]),fontSizes:Object.freeze([...pe]),colors:Object.freeze([...fe]),headingOptions:Object.freeze([...ye])}),this._keybindings=Object.freeze({...nt}),this._commands=Object.freeze({buttons:Object.freeze({...$e}),tooltips:Object.freeze({...Ye}),shortcuts:Object.freeze({...Je}),modals:Object.freeze({...Qe})}))}get sanitizerSchema(){return this._ensureInit(),this._sanitizerSchema}get toolbarPresets(){return this._ensureInit(),this._toolbarPresets}get defaults(){return this._ensureInit(),this._defaults}get keybindings(){return this._ensureInit(),this._keybindings}get commands(){return this._ensureInit(),this._commands}registerIcon(e,t){this._icons.set(e,t)}unregisterIcon(e){this._icons.delete(e)}getIcon(e){return this._icons.get(e)}getIconNames(){return[...this._icons.keys()]}get stats(){return this._ensureInit(),{registeredIcons:this._icons.size,frozenSchemas:!0}}};function rt(e,t){const n=e.selection.getSelection();if(!n||0===n.rangeCount)return;const o=n.getRangeAt(0);if(o.collapsed)return;const r=e.selection.getParentElement();if(r&&r.tagName===t.toUpperCase()){const e=document.createDocumentFragment();for(;r.firstChild;)e.appendChild(r.firstChild);return void r.parentNode.replaceChild(e,r)}let i=r;for(;i&&i!==e.element;){if(i.tagName===t.toUpperCase()){const e=document.createDocumentFragment();for(;i.firstChild;)e.appendChild(i.firstChild);return void i.parentNode.replaceChild(e,i)}i=i.parentNode}const s=document.createElement(t);try{o.surroundContents(s)}catch{const e=o.extractContents();s.appendChild(e),o.insertNode(s)}}function it(e,t){const n=e.selection.getParentElement();if(!n)return!1;let o=n;for(;o&&o!==e.element;){if(o.tagName===t.toUpperCase())return!0;o=o.parentNode}return!1}function st(e){e.commands.register("bold",{execute(e){rt(e,"strong")},isActive:e=>it(e,"STRONG")||it(e,"B"),shortcut:"mod+b",meta:{icon:"bold",tooltip:"Bold"}}),e.commands.register("italic",{execute(e){rt(e,"em")},isActive:e=>it(e,"EM")||it(e,"I"),shortcut:"mod+i",meta:{icon:"italic",tooltip:"Italic"}}),e.commands.register("underline",{execute(e){rt(e,"u")},isActive:e=>it(e,"U"),shortcut:"mod+u",meta:{icon:"underline",tooltip:"Underline"}}),e.commands.register("strikethrough",{execute(e){rt(e,"s")},isActive:e=>it(e,"S")||it(e,"DEL"),shortcut:"mod+shift+x",meta:{icon:"strikethrough",tooltip:"Strikethrough"}}),e.commands.register("subscript",{execute(e){rt(e,"sub")},isActive:e=>it(e,"SUB"),shortcut:"mod+,",alternateShortcuts:["mod+shift+,"],meta:{icon:"subscript",tooltip:"Subscript"}}),e.commands.register("superscript",{execute(e){rt(e,"sup")},isActive:e=>it(e,"SUP"),shortcut:"mod+.",alternateShortcuts:["mod+shift+."],meta:{icon:"superscript",tooltip:"Superscript"}}),e.commands.register("highlight",{execute(e,{color:t="yellow"}={}){const n=e.selection.getSelection();if(!n||0===n.rangeCount)return;const o=n.getRangeAt(0);if(o.collapsed)return;let r=e.selection.getParentElement();for(;r&&r!==e.element;){if("MARK"===r.tagName){const e=document.createDocumentFragment();for(;r.firstChild;)e.appendChild(r.firstChild);return void r.parentNode.replaceChild(e,r)}r=r.parentNode}const i={yellow:"rgba(255, 235, 59, 0.4)",green:"rgba(76, 175, 80, 0.3)",blue:"rgba(33, 150, 243, 0.3)",pink:"rgba(233, 30, 99, 0.3)",orange:"rgba(255, 152, 0, 0.3)",purple:"rgba(156, 39, 176, 0.3)"},s=i[t]||i.yellow,a=document.createElement("mark");a.style.backgroundColor=s,a.setAttribute("data-highlight-color",t);try{o.surroundContents(a)}catch{const e=o.extractContents();a.appendChild(e),o.insertNode(a)}},isActive:e=>it(e,"MARK"),meta:{icon:"highlight",tooltip:"Highlight"}}),e.commands.register("removeFormat",{execute(e){const t=e.selection.getSelection();if(!t||0===t.rangeCount)return;const n=t.getRangeAt(0);if(n.collapsed)return;const o=/* @__PURE__ */new Set(["STRONG","B","EM","I","U","S","DEL","SUB","SUP","MARK","SPAN"]),r=n.commonAncestorContainer,i=r.nodeType===Node.TEXT_NODE?r.parentElement:r,s=document.createTreeWalker(i,NodeFilter.SHOW_ELEMENT),a=[];let l;for(;l=s.nextNode();)o.has(l.tagName)&&n.intersectsNode(l)&&a.push(l);for(let c=a.length-1;c>=0;c--){const e=a[c],t=e.parentNode;for(;e.firstChild;)t.insertBefore(e.firstChild,e);t.removeChild(e)}},shortcut:"mod+\\",meta:{icon:"removeFormat",tooltip:"Remove Formatting"}})}function at(e,t){if(t<=1)return e;const n=t-1;return Math.min(e+n,6)}function lt(e,t){const n=e.selection.getParentBlock();if(!n)return;if(n.tagName===t.toUpperCase())return;const o=document.createElement(t);for(;n.firstChild;)o.appendChild(n.firstChild);n.className&&(o.className=n.className),n.parentNode.replaceChild(o,n);const r=document.createRange();r.selectNodeContents(o),r.collapse(!1),e.selection.setRange(r)}function ct(e){const t=e.options.baseHeadingLevel||1;e.commands.register("heading",{execute(e,n){if("p"===n)lt(e,"p");else{lt(e,`h${at(Number(n),t)}`)}},isActive(e){const t=e.selection.getParentBlock();return!!t&&(!!/^H[1-6]$/.test(t.tagName)&&t.tagName.toLowerCase())},meta:{icon:"heading",tooltip:"Heading"}});for(let n=1;n<=6;n++){const o=at(n,t);e.commands.register(`h${n}`,{execute(e){lt(e,`h${o}`)},isActive(e){const t=e.selection.getParentBlock();return t&&t.tagName===`H${o}`},meta:{tooltip:`Heading ${n}`}})}e.commands.register("paragraph",{execute(e){lt(e,"p")},isActive(e){const t=e.selection.getParentBlock();return t&&"P"===t.tagName},meta:{tooltip:"Normal text"}})}function dt(e){e.commands.register("alignLeft",{execute(e){const t=e.selection.getParentBlock();t&&(t.style.textAlign="left")},isActive(e){const t=e.selection.getParentBlock();if(!t)return!1;const n=t.style.textAlign;return!n||"left"===n||"start"===n},meta:{icon:"alignLeft",tooltip:"Align Left"}}),e.commands.register("alignCenter",{execute(e){const t=e.selection.getParentBlock();t&&(t.style.textAlign="center")},isActive(e){const t=e.selection.getParentBlock();if(!t)return!1;return"center"===t.style.textAlign},meta:{icon:"alignCenter",tooltip:"Align Center"}}),e.commands.register("alignRight",{execute(e){const t=e.selection.getParentBlock();t&&(t.style.textAlign="right")},isActive(e){const t=e.selection.getParentBlock();if(!t)return!1;const n=t.style.textAlign;return"right"===n||"end"===n},meta:{icon:"alignRight",tooltip:"Align Right"}}),e.commands.register("alignJustify",{execute(e){const t=e.selection.getParentBlock();t&&(t.style.textAlign="justify")},isActive(e){const t=e.selection.getParentBlock();if(!t)return!1;return"justify"===t.style.textAlign},meta:{icon:"alignJustify",tooltip:"Justify"}})}function ut(e){e.commands.register("orderedList",{execute(e){const t=e.selection.getClosestElement("ol");if(t)return void mt(t);const n=e.selection.getClosestElement("ul");n?gt(n,"ol"):ht(e,"ol")},isActive:e=>!!e.selection.getClosestElement("ol"),shortcut:"mod+shift+7",meta:{icon:"orderedList",tooltip:"Numbered List"}}),e.commands.register("unorderedList",{execute(e){const t=e.selection.getClosestElement("ul");if(t&&!t.classList.contains("rmx-task-list"))return void mt(t);const n=e.selection.getClosestElement("ol");n?gt(n,"ul"):ht(e,"ul")},isActive(e){const t=e.selection.getClosestElement("ul");return!!t&&!t.classList.contains("rmx-task-list")},shortcut:"mod+shift+8",meta:{icon:"unorderedList",tooltip:"Bulleted List"}}),e.commands.register("taskList",{execute(e){const t=e.selection.getClosestElement("ul");if(t&&t.classList.contains("rmx-task-list"))return t.classList.remove("rmx-task-list"),void t.querySelectorAll(".rmx-task-checkbox").forEach((e=>e.remove()));t||ht(e,"ul");const n=e.selection.getClosestElement("ul");n&&(n.classList.add("rmx-task-list"),n.querySelectorAll("li").forEach((e=>{if(!e.querySelector(".rmx-task-checkbox")){const t=document.createElement("input");t.type="checkbox",t.className="rmx-task-checkbox",t.setAttribute("contenteditable","false"),e.insertBefore(t,e.firstChild)}})))},isActive(e){const t=e.selection.getClosestElement("ul");return t&&t.classList.contains("rmx-task-list")},meta:{icon:"taskList",tooltip:"Task List"}}),e.commands.register("indent",{execute(e){const t=e.selection.getClosestElement("li");if(!t)return;const n=t.previousElementSibling;if(!n)return;const o=e.options?.maxListNestingDepth??5;let r=0,i=t.parentElement;for(;i&&i!==e.element;)"UL"!==i.tagName&&"OL"!==i.tagName||r++,i=i.parentElement;if(r>=o)return;const s=t.parentElement.tagName.toLowerCase();let a=n.querySelector(s);a||(a=document.createElement(s),n.appendChild(a)),a.appendChild(t)},meta:{icon:"indent",tooltip:"Increase Indent"}}),e.commands.register("outdent",{execute(e){const t=e.selection.getClosestElement("li");if(!t)return;const n=t.parentElement;if(!n)return;const o=n.parentElement;if(!o||"LI"!==o.tagName)return;o.parentElement.insertBefore(t,o.nextSibling),0===n.children.length&&n.remove()},meta:{icon:"outdent",tooltip:"Decrease Indent"}})}function ht(e,t){const n=e.selection.getParentBlock();if(!n)return;const o=document.createElement(t),r=document.createElement("li");for(;n.firstChild;)r.appendChild(n.firstChild);o.appendChild(r),n.parentNode.replaceChild(o,n);const i=document.createRange();i.selectNodeContents(r),i.collapse(!1),e.selection.setRange(i)}function mt(e){const t=e.parentNode,n=Array.from(e.querySelectorAll(":scope > li"));for(const o of n){const n=document.createElement("p");for(;o.firstChild;)n.appendChild(o.firstChild);t.insertBefore(n,e)}t.removeChild(e)}function gt(e,t){const n=document.createElement(t);for(const o of e.attributes)n.setAttribute(o.name,o.value);for(;e.firstChild;)n.appendChild(e.firstChild);e.parentNode.replaceChild(n,e)}const pt=/^\s*(javascript|vbscript|data\s*:\s*text\/html)\s*:/i;function ft(e){return e&&pt.test(e)?"#":e}function bt(e){e.commands.register("insertLink",{execute(e,{href:t,text:n,target:o="_blank"}){if(!t)return;const r=e.selection,i=r.getSelectedText();if(i){const e=r.wrapWith("a",{href:t,target:o,rel:"_blank"===o?"noopener noreferrer":void 0});e&&n&&n!==i&&(e.textContent=n)}else{const e=n||t,i=`<a href="${yt(ft(t))}" target="${yt(o)}"${"_blank"===o?' rel="noopener noreferrer"':""}>${te(e)}</a>`;r.insertHTML(i)}},shortcut:"mod+k",meta:{icon:"link",tooltip:"Insert Link"}}),e.commands.register("editLink",{execute(e,{href:t,text:n,target:o}){const r=e.selection.getClosestElement("a");r&&(void 0!==t&&(r.href=ft(t)),void 0!==n&&(r.textContent=n),void 0!==o&&(r.target=o,"_blank"===o?r.rel="noopener noreferrer":r.removeAttribute("rel")))},meta:{tooltip:"Edit Link"}}),e.commands.register("removeLink",{execute(e){e.selection.unwrap("a")},meta:{icon:"unlink",tooltip:"Remove Link"}})}function yt(e){return e.replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function vt(e){e.commands.register("insertImage",{execute(e,{src:t,alt:n="",width:o,height:r}){if(!t)return;if(/^data:image\/svg/i.test(t))return;try{if(new URL(t,window.location.href).pathname.toLowerCase().endsWith(".svg"))return}catch{if(/\.svg(\?|#|$)/i.test(t))return}if(e.element.focus(),!e.selection.getRange()){const t=document.createRange();t.selectNodeContents(e.element),t.collapse(!1),e.selection.setRange(t)}const i=document.createElement("img");if(i.src=t,i.alt=n,o&&(i.style.width="number"==typeof o?`${o}px`:o),r&&(i.style.height="number"==typeof r?`${r}px`:r),i.style.maxWidth="100%",i.className="rmx-image",e.selection.insertNode(i),!i.nextSibling||i.parentElement===e.element){const e=document.createElement("p");e.innerHTML="<br>",i.parentElement.insertBefore(e,i.nextSibling)}},meta:{icon:"image",tooltip:"Insert Image"}}),e.commands.register("resizeImage",{execute(e,{element:t,width:n,height:o}){t&&"IMG"===t.tagName&&(t.style.width="number"==typeof n?`${n}px`:n,t.style.height=o?"number"==typeof o?`${o}px`:o:"auto")},meta:{tooltip:"Resize Image"}}),e.commands.register("alignImage",{execute(e,{element:t,alignment:n}){if(t&&"IMG"===t.tagName)switch(t.style.float="",t.style.margin="",t.style.display="",n){case"left":t.style.float="left",t.style.margin="0 16px 16px 0";break;case"right":t.style.float="right",t.style.margin="0 0 16px 16px";break;case"center":t.style.display="block",t.style.margin="16px auto"}},meta:{tooltip:"Align Image"}}),e.commands.register("removeImage",{execute(e,{element:t}){t&&"IMG"===t.tagName&&t.parentNode.removeChild(t)},meta:{tooltip:"Remove Image"}})}function Ct(e){e.commands.register("insertTable",{execute(e,{rows:t=3,cols:n=3}={}){let o='<table class="rmx-table"><thead><tr>';for(let r=0;r<n;r++)o+="<th><br></th>";o+="</tr></thead><tbody>";for(let r=1;r<t;r++){o+="<tr>";for(let e=0;e<n;e++)o+="<td><br></td>";o+="</tr>"}o+="</tbody></table><p><br></p>",e.selection.insertHTML(o)},meta:{icon:"table",tooltip:"Insert Table"}}),e.commands.register("toggleHeaderRow",{execute(e){const t=e.selection.getClosestElement("table");if(!t)return;const n=t.querySelector("thead");if(n){const e=n.querySelector("tr");if(!e)return;const o=document.createElement("tr");for(const t of Array.from(e.cells)){const e=document.createElement("td");e.innerHTML=t.innerHTML,t.colSpan>1&&(e.colSpan=t.colSpan),t.rowSpan>1&&(e.rowSpan=t.rowSpan),o.appendChild(e)}let r=t.querySelector("tbody");r||(r=document.createElement("tbody"),t.appendChild(r)),r.insertBefore(o,r.firstChild),n.remove()}else{let e=t.querySelector("tbody");if(!e)return;const n=e.querySelector("tr");if(!n)return;const o=document.createElement("thead"),r=document.createElement("tr");for(const t of Array.from(n.cells)){const e=document.createElement("th");e.innerHTML=t.innerHTML,t.colSpan>1&&(e.colSpan=t.colSpan),t.rowSpan>1&&(e.rowSpan=t.rowSpan),r.appendChild(e)}o.appendChild(r),t.insertBefore(o,t.firstChild),n.remove()}},meta:{tooltip:"Toggle Header Row"}}),e.commands.register("alignCell",{execute(e,{direction:t="left"}={}){const n=e.selection.getClosestElement("td")||e.selection.getClosestElement("th");n&&["left","center","right"].includes(t)&&(n.style.textAlign=t)},meta:{tooltip:"Align Cell Content"}}),e.commands.register("addRowBefore",{execute(e){const t=e.selection.getClosestElement("td")||e.selection.getClosestElement("th");if(!t)return;const n=t.parentElement,o=wt(xt(n));n.parentElement.insertBefore(o,n)},meta:{tooltip:"Insert Row Before"}}),e.commands.register("addRowAfter",{execute(e){const t=e.selection.getClosestElement("td")||e.selection.getClosestElement("th");if(!t)return;const n=t.parentElement,o=wt(xt(n));n.parentElement.insertBefore(o,n.nextSibling)},meta:{tooltip:"Insert Row After"}}),e.commands.register("addColBefore",{execute(e){const t=e.selection.getClosestElement("td")||e.selection.getClosestElement("th");if(!t)return;const n=_t(t),o=e.selection.getClosestElement("table");o&&o.querySelectorAll("tr").forEach((e=>{const t=document.createElement("THEAD"===e.parentElement.tagName?"th":"td");t.innerHTML="<br>";const o=e.cells[n];e.insertBefore(t,o)}))},meta:{tooltip:"Insert Column Before"}}),e.commands.register("addColAfter",{execute(e){const t=e.selection.getClosestElement("td")||e.selection.getClosestElement("th");if(!t)return;const n=_t(t),o=e.selection.getClosestElement("table");o&&o.querySelectorAll("tr").forEach((e=>{const t=document.createElement("THEAD"===e.parentElement.tagName?"th":"td");t.innerHTML="<br>";const o=e.cells[n];e.insertBefore(t,o?o.nextSibling:null)}))},meta:{tooltip:"Insert Column After"}}),e.commands.register("deleteRow",{execute(e){const t=e.selection.getClosestElement("td")||e.selection.getClosestElement("th");if(!t)return;const n=t.parentElement;if(n.parentElement.rows.length<=1){const t=e.selection.getClosestElement("table");if(t){const e=document.createElement("p");e.innerHTML="<br>",t.parentElement.replaceChild(e,t)}}else n.remove()},meta:{tooltip:"Delete Row"}}),e.commands.register("deleteCol",{execute(e){const t=e.selection.getClosestElement("td")||e.selection.getClosestElement("th");if(!t)return;const n=_t(t),o=e.selection.getClosestElement("table");if(!o)return;const r=o.querySelector("tr");if(r&&r.cells.length<=1){const e=document.createElement("p");e.innerHTML="<br>",o.parentElement.replaceChild(e,o)}else o.querySelectorAll("tr").forEach((e=>{e.cells[n]&&e.cells[n].remove()}))},meta:{tooltip:"Delete Column"}}),e.commands.register("deleteTable",{execute(e){const t=e.selection.getClosestElement("table");if(!t)return;const n=document.createElement("p");n.innerHTML="<br>",t.parentElement.replaceChild(n,t)},meta:{tooltip:"Delete Table"}}),e.commands.register("mergeCells",{execute(e,{cells:t}){if(!t||t.length<2)return;const n=t[0],o=/* @__PURE__ */new Set,r=/* @__PURE__ */new Set;t.forEach((e=>{o.add(e.parentElement.rowIndex),r.add(_t(e))}));const i=o.size,s=r.size,a=[];t.slice(1).forEach((e=>{e.textContent.trim()&&a.push(e.innerHTML),e.remove()})),a.length>0&&(n.innerHTML+="<br>"+a.join("<br>")),i>1&&(n.rowSpan=i),s>1&&(n.colSpan=s)},meta:{tooltip:"Merge Cells"}}),e.commands.register("sortTable",{execute(e,{columnIndex:t,direction:n,dataType:o,keys:r,comparator:i}={}){const s=e.selection.getClosestElement("table");if(!s)return;const a=s.querySelector("tbody");if(!a)return;const l=Array.from(a.querySelectorAll("tr"));if(0===l.length)return;const c=r||[{columnIndex:t,direction:n||"asc",dataType:o}],d=(e,t)=>{const n=e.querySelectorAll("td, th");return n[t]?.textContent?.trim()||""},u=i||e.options?.tableSortComparator;l.sort(((e,t)=>{for(const n of c){const o=d(e,n.columnIndex),r=d(t,n.columnIndex),i=n.dataType||kt(l,n.columnIndex);let s=0;if(u)s=u(o,r,i,n.columnIndex);else if("numeric"===i){s=(parseFloat(o)||0)-(parseFloat(r)||0)}else if("date"===i){s=(new Date(o).getTime()||0)-(new Date(r).getTime()||0)}else s=o.localeCompare(r,void 0,{sensitivity:"base"});if("desc"===n.direction&&(s=-s),0!==s)return s}return 0})),l.forEach((e=>a.appendChild(e)));const h=s.querySelector("thead");if(h){const e=h.querySelectorAll("th");e.forEach((e=>{e.removeAttribute("data-sort-dir"),e.removeAttribute("data-sort-priority")})),c.forEach(((t,n)=>{e[t.columnIndex]&&(e[t.columnIndex].setAttribute("data-sort-dir",t.direction||"asc"),c.length>1&&e[t.columnIndex].setAttribute("data-sort-priority",String(n+1)))}))}},meta:{tooltip:"Sort Table"}}),e.commands.register("filterTable",{execute(e,{columnIndex:t,filterValue:n}={}){const o=e.selection.getClosestElement("table");if(!o)return;const r=o.querySelector("thead"),i=o.querySelector("tbody");if(!i)return;if(r){const e=r.querySelectorAll("th");e[t]&&(n?e[t].setAttribute("data-filter-value",n):e[t].removeAttribute("data-filter-value"))}const s=[];r&&r.querySelectorAll("th").forEach(((e,t)=>{const n=e.getAttribute("data-filter-value");n&&s.push({columnIndex:t,value:n.toLowerCase()})}));i.querySelectorAll("tr").forEach((e=>{const t=e.querySelectorAll("td, th");s.some((e=>!(t[e.columnIndex]?.textContent||"").toLowerCase().includes(e.value)))?e.classList.add("rmx-row-hidden"):e.classList.remove("rmx-row-hidden")}))},meta:{tooltip:"Filter Table"}}),e.commands.register("clearTableFilters",{execute(e){const t=e.selection.getClosestElement("table");if(!t)return;const n=t.querySelector("thead");n&&n.querySelectorAll("th").forEach((e=>{e.removeAttribute("data-filter-value")}));const o=t.querySelector("tbody");o&&o.querySelectorAll("tr.rmx-row-hidden").forEach((e=>{e.classList.remove("rmx-row-hidden")}))},meta:{tooltip:"Clear Table Filters"}}),e.commands.register("formatCell",{execute(e,{format:t,options:n={}}={}){const o=e.selection.getClosestElement("td")||e.selection.getClosestElement("th");if(!o||!t)return;const r=o.getAttribute("data-raw-value")||o.textContent.trim();o.setAttribute("data-raw-value",r),o.setAttribute("data-cell-format",t);const i=parseFloat(r);if("number"!==t||isNaN(i))if("currency"!==t||isNaN(i))if("percentage"!==t||isNaN(i)){if("date"===t){const e=new Date(r);isNaN(e.getTime())||(o.textContent=new Intl.DateTimeFormat(void 0,{dateStyle:n.dateStyle||"short"}).format(e))}}else{const e=n.decimals??1;o.textContent=(100*i).toFixed(e)+"%"}else o.textContent=new Intl.NumberFormat(void 0,{style:"currency",currency:n.currency||"USD",minimumFractionDigits:n.decimals??2,maximumFractionDigits:n.decimals??2}).format(i);else o.textContent=new Intl.NumberFormat(void 0,{minimumFractionDigits:n.decimals??2,maximumFractionDigits:n.decimals??2}).format(i)},meta:{tooltip:"Format Cell"}}),e.commands.register("evaluateFormulas",{execute(e){const t=e.selection.getClosestElement("table");t&&Bt(t)},meta:{tooltip:"Evaluate Formulas"}}),e.commands.register("splitCell",{execute(e){const t=e.selection.getClosestElement("td")||e.selection.getClosestElement("th");if(!t)return;const n=t.colSpan||1,o=t.rowSpan||1;if(n<=1&&o<=1)return;t.colSpan=1,t.rowSpan=1;const r=t.parentElement,i=r.closest("thead")?"th":t.tagName.toLowerCase();for(let s=1;s<n;s++){const e=document.createElement(i);e.innerHTML="<br>",r.insertBefore(e,t.nextSibling)}if(o>1){const e=_t(t);let i=r.nextElementSibling;for(let t=1;t<o&&i;t++){const t=i.closest("thead")?"th":"td";let o=null,r=0;for(const n of i.cells){if(r>=e){o=n;break}r+=n.colSpan||1}for(let e=0;e<n;e++){const e=document.createElement(t);e.innerHTML="<br>",i.insertBefore(e,o)}i=i.nextElementSibling}}},meta:{tooltip:"Split Cell"}})}function xt(e){let t=0;for(const n of e.cells)t+=n.colSpan||1;return t}function _t(e){let t=0,n=e.previousElementSibling;for(;n;)t+=n.colSpan||1,n=n.previousElementSibling;return t}function wt(e){const t=document.createElement("tr");for(let n=0;n<e;n++){const e=document.createElement("td");e.innerHTML="<br>",t.appendChild(e)}return t}function kt(e,t){let n=0,o=0,r=0;for(const i of e){const e=i.querySelectorAll("td, th"),s=(e[t]?.textContent||"").trim();s&&(r++,!isNaN(parseFloat(s))&&isFinite(s)?n++:!isNaN(new Date(s).getTime())&&s.length>4&&o++)}return 0===r?"alphabetical":n/r>.7?"numeric":o/r>.7?"date":"alphabetical"}const St={SUM:e=>e.flat().reduce(((e,t)=>e+(parseFloat(t)||0)),0),AVERAGE:e=>{const t=e.flat().map((e=>parseFloat(e))).filter((e=>!isNaN(e)));return t.length?t.reduce(((e,t)=>e+t),0)/t.length:0},COUNT:e=>e.flat().filter((e=>""!==e&&null!=e)).length,MIN:e=>Math.min(...e.flat().map((e=>parseFloat(e))).filter((e=>!isNaN(e)))),MAX:e=>Math.max(...e.flat().map((e=>parseFloat(e))).filter((e=>!isNaN(e)))),IF:e=>e[0]?e[1]:e[2]??"",CONCAT:e=>e.flat().join("")};function It(e){const t=e.match(/^([A-Z]+)(\d+)$/);if(!t)return null;let n=0;for(let o=0;o<t[1].length;o++)n=26*n+(t[1].charCodeAt(o)-64);return{col:n-1,row:parseInt(t[2],10)-1}}function Et(e,t,n){const o=e.querySelectorAll("thead tr, tbody tr")[n];if(!o)return"";const r=o.querySelectorAll("td, th");return r[t]?r[t].getAttribute("data-raw-value")||r[t].textContent.trim():""}function At(e,t,n=/* @__PURE__ */new Set){const o=function(e){const t=[];let n=0;for(;n<e.length;){const o=e[n];if(/\s/.test(o))n++;else if("+-*/(),".includes(o))t.push({type:"op",value:o}),n++;else if(">"!==o&&"<"!==o&&"="!==o)if(/\d/.test(o)||"."===o&&/\d/.test(e[n+1])){let o="";for(;n<e.length&&(/\d/.test(e[n])||"."===e[n]);)o+=e[n++];t.push({type:"number",value:parseFloat(o)})}else if('"'!==o)if(/[A-Z]/i.test(o)){let o="";for(;n<e.length&&/[A-Z0-9]/i.test(e[n]);)o+=e[n++];if(":"===e[n]){n++;let r="";for(;n<e.length&&/[A-Z0-9]/i.test(e[n]);)r+=e[n++];t.push({type:"range",value:o.toUpperCase()+":"+r.toUpperCase()})}else/^[A-Z]+\d+$/i.test(o)?t.push({type:"cellref",value:o.toUpperCase()}):t.push({type:"func",value:o.toUpperCase()})}else n++;else{let o="";for(n++;n<e.length&&'"'!==e[n];)o+=e[n++];n++,t.push({type:"string",value:o})}else"="===e[n+1]?(t.push({type:"op",value:o+"="}),n+=2):(t.push({type:"op",value:o}),n++)}return t}(e.startsWith("=")?e.slice(1):e);let r=0;const i=()=>o[r]||null,s=()=>o[r++];function a(){let e=l();for(;i()&&("+"===i().value||"-"===i().value);){const t=s().value,n=l();e="+"===t?e+n:e-n}return e}function l(){let e=c();for(;i()&&("*"===i().value||"/"===i().value);){const t=s().value,n=c();e="*"===t?e*n:0!==n?e/n:NaN}return e}function c(){let e=d();if(i()&&[">","<",">=","<=","=="].includes(i().value)){const t=s().value,n=d();if(">"===t)return e>n?1:0;if("<"===t)return e<n?1:0;if(">="===t)return e>=n?1:0;if("<="===t)return e<=n?1:0;if("=="===t)return e===n?1:0}return e}function d(){const e=i();if(!e)return 0;if("number"===e.type)return s(),e.value;if("string"===e.type)return s(),e.value;if("cellref"===e.type){s();const o=It(e.value);if(!o)return 0;const r=e.value;if(n.has(r))return"#CIRC!";n.add(r);const i=Et(t,o.col,o.row),a=t.querySelectorAll("thead tr, tbody tr"),l=a[o.row]?.querySelectorAll("td, th")[o.col],c=l?.getAttribute("data-formula");let d;return c?d=At(c,t,n):(d=parseFloat(i),isNaN(d)&&(d=i)),n.delete(r),d}if("range"===e.type){s();const n=function(e){const t=e.split(":");if(2!==t.length)return null;const n=It(t[0]),o=It(t[1]);if(!n||!o)return null;const r=[];for(let i=n.row;i<=o.row;i++)for(let e=n.col;e<=o.col;e++)r.push({col:e,row:i});return r}(e.value);return n?n.map((e=>{const n=Et(t,e.col,e.row),o=parseFloat(n);return isNaN(o)?n:o})):[]}if("func"===e.type){const e=s().value,t=St[e];if(!t)return"#NAME!";"("===i()?.value&&s();const n=[];for(;i()&&")"!==i().value;){if(","===i().value){s();continue}const e="range"===i()?.type?d():a();n.push(e)}return")"===i()?.value&&s(),t(n)}if("("===e.value){s();const e=a();return")"===i()?.value&&s(),e}return"-"===e.value?(s(),-d()):(s(),0)}return a()}function Bt(e){const t=e.querySelectorAll("td[data-formula], th[data-formula]");for(const n of t){const t=n.getAttribute("data-formula");if(!t)continue;const o=At(t,e);"string"==typeof o&&o.startsWith("#")?n.textContent=o:n.textContent="number"==typeof o?String(Math.round(1e10*o)/1e10):o}}const Lt=/* @__PURE__ */new Set(["P","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","PRE","UL","OL","TABLE","HR","DIV","DETAILS"]);function Tt(e){const t=e.selection.getParentBlock();if(!t)return null;let n=t;for(;n&&n.parentElement!==e.element;)n=n.parentElement;return n&&Lt.has(n.tagName)?n:null}function Nt(e){e.commands.register("blockquote",{execute(e){const t=e.selection.getClosestElement("blockquote");if(t){const e=t.parentNode;for(;t.firstChild;)e.insertBefore(t.firstChild,t);e.removeChild(t)}else{const t=e.selection.getParentBlock();if(!t)return;const n=document.createElement("blockquote");t.parentNode.replaceChild(n,t),n.appendChild(t)}},isActive:e=>!!e.selection.getClosestElement("blockquote"),shortcut:"mod+shift+9",meta:{icon:"blockquote",tooltip:"Blockquote"}}),e.commands.register("codeBlock",{execute(e,{language:t}={}){const n=e.selection.getClosestElement("pre");if(n){const t=n.textContent,o=document.createElement("p");o.textContent=t,n.parentNode.replaceChild(o,n);const r=document.createRange();r.selectNodeContents(o),r.collapse(!1),e.selection.setRange(r)}else{const n=e.selection.getRange();if(!n)return;const o=n.collapsed?"\n":n.toString(),r=document.createElement("pre"),i=document.createElement("code");if(i.textContent=o,t&&(i.setAttribute("data-language",t),r.setAttribute("data-language",t)),r.appendChild(i),n.collapsed||n.deleteContents(),n.insertNode(r),!r.nextSibling){const e=document.createElement("p");e.innerHTML="<br>",r.parentNode.insertBefore(e,r.nextSibling)}const s=document.createRange();s.selectNodeContents(i),s.collapse(!1),e.selection.setRange(s),e.eventBus.emit("codeblock:created",{element:r,language:t})}},isActive:e=>!!e.selection.getClosestElement("pre"),shortcut:"mod+shift+c",meta:{icon:"codeBlock",tooltip:"Code Block"}}),e.commands.register("horizontalRule",{execute(e){const t=e.selection.getRange();if(!t)return;const n=document.createElement("hr");if(t.deleteContents(),t.insertNode(n),!n.nextSibling||"P"!==n.nextSibling.tagName){const e=document.createElement("p");e.innerHTML="<br>",n.parentNode.insertBefore(e,n.nextSibling)}const o=document.createRange();o.setStartAfter(n),o.collapse(!0),e.selection.setRange(o)},meta:{icon:"horizontalRule",tooltip:"Horizontal Rule"}}),e.commands.register("moveBlockUp",{execute(e){const t=Tt(e);t&&t.previousElementSibling&&(e.history.snapshot(),t.parentNode.insertBefore(t,t.previousElementSibling),e.eventBus.emit("content:change"))},meta:{tooltip:"Move Block Up"}}),e.commands.register("moveBlockDown",{execute(e){const t=Tt(e);t&&t.nextElementSibling&&(e.history.snapshot(),t.parentNode.insertBefore(t,t.nextElementSibling.nextSibling),e.eventBus.emit("content:change"))},meta:{tooltip:"Move Block Down"}}),e.commands.register("duplicateBlock",{execute(e){const t=Tt(e);if(!t)return;e.history.snapshot();const n=t.cloneNode(!0);t.parentNode.insertBefore(n,t.nextSibling);const o=document.createRange();o.selectNodeContents(n),o.collapse(!1),e.selection.setRange(o),e.eventBus.emit("content:change")},meta:{tooltip:"Duplicate Block"}}),e.commands.register("deleteBlock",{execute(e){const t=Tt(e);if(!t)return;e.history.snapshot();const n=t.nextElementSibling,o=t.previousElementSibling;t.parentNode.removeChild(t),function(e){if(0===e.element.children.length){const t=document.createElement("p");t.innerHTML="<br>",e.element.appendChild(t);const n=document.createRange();n.selectNodeContents(t),n.collapse(!0),e.selection.setRange(n)}}(e);const r=n||o||e.element.firstElementChild;if(r){const t=document.createRange();t.selectNodeContents(r),t.collapse(!0),e.selection.setRange(t)}e.eventBus.emit("content:change")},meta:{tooltip:"Delete Block"}}),e.commands.register("selectBlocks",{execute(e,{blocks:t}={}){t&&Array.isArray(t)&&t.forEach((e=>{e&&e.classList&&e.classList.add("rmx-block-selected")}))},meta:{tooltip:"Select Blocks"}}),e.commands.register("clearBlockSelection",{execute(e){e.element.querySelectorAll(".rmx-block-selected").forEach((e=>e.classList.remove("rmx-block-selected")))},meta:{tooltip:"Clear Block Selection"}}),e.commands.register("toggleCollapse",{execute(e){const t=Tt(e);if(t){if(e.history.snapshot(),"DETAILS"===t.tagName){const e=t.parentNode,n=t.querySelector("summary");Array.from(t.childNodes).filter((e=>e!==n)).forEach((n=>e.insertBefore(n,t))),e.removeChild(t)}else{const e=document.createElement("details");e.className="rmx-collapsible",e.setAttribute("open","");const n=document.createElement("summary");n.textContent=t.textContent.slice(0,50)||"Section",t.parentNode.replaceChild(e,t),e.appendChild(n),e.appendChild(t)}e.eventBus.emit("content:change")}},meta:{tooltip:"Toggle Collapsible Section"}}),e.commands.register("groupBlocks",{execute(e){const t=Array.from(e.element.querySelectorAll(".rmx-block-selected"));if(0===t.length)return;e.history.snapshot();const n=document.createElement("div");n.className="rmx-block-group",t[0].parentNode.insertBefore(n,t[0]),t.forEach((e=>{e.classList.remove("rmx-block-selected"),n.appendChild(e)})),e.eventBus.emit("content:change")},meta:{tooltip:"Group Selected Blocks"}}),e.commands.register("ungroupBlocks",{execute(e){const t=Tt(e);if(!t)return;let n=t;if(n.classList.contains("rmx-block-group")||(n=t.closest(".rmx-block-group")),!n||!n.classList.contains("rmx-block-group"))return;e.history.snapshot();const o=n.parentNode;for(;n.firstChild;)o.insertBefore(n.firstChild,n);o.removeChild(n),e.eventBus.emit("content:change")},meta:{tooltip:"Ungroup Blocks"}}),e.commands.register("moveGroup",{execute(e,{direction:t}={}){const n=Tt(e);if(!n)return;let o=n.classList.contains("rmx-block-group")?n:n.closest(".rmx-block-group");if(o&&o.classList.contains("rmx-block-group")){for(;o.parentElement!==e.element;)if(o=o.parentElement,!o)return;e.history.snapshot(),"up"===t&&o.previousElementSibling?o.parentNode.insertBefore(o,o.previousElementSibling):"down"===t&&o.nextElementSibling&&o.parentNode.insertBefore(o,o.nextElementSibling.nextSibling),e.eventBus.emit("content:change")}},meta:{tooltip:"Move Group"}}),e.commands.register("duplicateGroup",{execute(e){const t=Tt(e);if(!t)return;let n=t.classList.contains("rmx-block-group")?t:t.closest(".rmx-block-group");if(!n||!n.classList.contains("rmx-block-group"))return;for(;n.parentElement!==e.element;)if(n=n.parentElement,!n)return;e.history.snapshot();const o=n.cloneNode(!0);n.parentNode.insertBefore(o,n.nextSibling),e.eventBus.emit("content:change")},meta:{tooltip:"Duplicate Group"}})}const Rt={paragraph:{tag:"P"},heading1:{tag:"H1"},heading2:{tag:"H2"},heading3:{tag:"H3"},heading4:{tag:"H4"},heading5:{tag:"H5"},heading6:{tag:"H6"},blockquote:{tag:"BLOCKQUOTE"},codeBlock:{tag:"PRE"},unorderedList:{tag:"UL"},orderedList:{tag:"OL"}};function Ht(e){e.commands.register("convertBlock",{execute(e,{to:t}={}){if(!t||!Rt[t])return;const n=function(e){const t=e.selection.getParentBlock();if(!t)return null;let n=t;for(;n&&n.parentElement!==e.element;)n=n.parentElement;return n||null}(e);if(!n)return;const o=Rt[t].tag;if(n.tagName===o)return;e.history.snapshot();const r=function(e){const t=e.tagName;if("UL"===t||"OL"===t){const t=Array.from(e.querySelectorAll("li"));return 1===t.length?t[0].innerHTML:t.map((e=>e.innerHTML)).join("<br>")}if("PRE"===t){const t=e.querySelector("code");return t?t.textContent:e.textContent}return"BLOCKQUOTE"===t&&1===e.children.length?e.children[0].innerHTML:e.innerHTML}(n),i=function(e,t){const n=Rt[e];if(!n)return null;if("unorderedList"===e||"orderedList"===e){const e=document.createElement(n.tag),o=document.createElement("li");return o.innerHTML=t||"<br>",e.appendChild(o),e}if("codeBlock"===e){const e=document.createElement("pre"),n=document.createElement("code"),o=document.createElement("div");return o.innerHTML=t,n.textContent=o.textContent||"\n",e.appendChild(n),e}if("blockquote"===e){const e=document.createElement("blockquote"),n=document.createElement("p");return n.innerHTML=t||"<br>",e.appendChild(n),e}const o=document.createElement(n.tag);return o.innerHTML=t||"<br>",o}(t,r);if(!i)return;n.parentNode.replaceChild(i,n);const s=document.createRange();let a=i;"unorderedList"===t||"orderedList"===t?a=i.querySelector("li")||i:"codeBlock"===t?a=i.querySelector("code")||i:"blockquote"===t&&(a=i.querySelector("p")||i),s.selectNodeContents(a),s.collapse(!1),e.selection.setRange(s),e.eventBus.emit("content:change")},meta:{tooltip:"Convert Block Type"}})}function Mt(e,t,n){if(!n)return;const o=e.selection.getSelection();if(!o||0===o.rangeCount)return;const r=o.getRangeAt(0);if(r.collapsed)return;const i=e.selection.getParentElement();if(i&&"SPAN"===i.tagName&&i.style[t])return void(i.style[t]=n);const s=document.createElement("span");s.style[t]=n;try{r.surroundContents(s)}catch{const e=r.extractContents();s.appendChild(e),r.insertNode(s)}}function Dt(e,t){const n=e.selection.getParentElement();if(!n)return!1;try{return window.getComputedStyle(n)[t]||!1}catch{return!1}}function Ft(e){e.commands.register("fontFamily",{execute(e,t){Mt(e,"fontFamily",t)},isActive:e=>Dt(e,"fontFamily"),meta:{icon:"fontFamily",tooltip:"Font Family"}}),e.commands.register("fontSize",{execute(e,t){t&&/^\d+(\.\d+)?(px|pt|em|rem|%)$/.test(t)&&Mt(e,"fontSize",t)},meta:{icon:"fontSize",tooltip:"Font Size"}}),e.commands.register("foreColor",{execute(e,t){Mt(e,"color",t)},isActive:e=>Dt(e,"color"),meta:{icon:"foreColor",tooltip:"Text Color"}}),e.commands.register("backColor",{execute(e,t){Mt(e,"backgroundColor",t)},isActive:e=>Dt(e,"backgroundColor"),meta:{icon:"backColor",tooltip:"Background Color"}}),e.commands.register("lineHeight",{execute(e,t){t&&Mt(e,"lineHeight",t)},isActive:e=>Dt(e,"lineHeight"),meta:{icon:"lineHeight",tooltip:"Line Height"}}),e.commands.register("letterSpacing",{execute(e,t){t&&Mt(e,"letterSpacing",t)},isActive:e=>Dt(e,"letterSpacing"),meta:{icon:"letterSpacing",tooltip:"Letter Spacing"}}),e.commands.register("paragraphSpacing",{execute(e,t){if(!t)return;const n=e.selection.getParentElement();if(!n)return;const o=n.closest("p, h1, h2, h3, h4, h5, h6, li, blockquote, pre, div");o&&(o.style.marginBottom=t)},isActive(e){const t=e.selection.getParentElement();if(!t)return!1;const n=t.closest("p, h1, h2, h3, h4, h5, h6, li, blockquote, pre, div");return n&&n.style.marginBottom||!1},meta:{icon:"paragraphSpacing",tooltip:"Paragraph Spacing"}})}function zt(e){e.commands.register("embedMedia",{execute(e,{url:t}){if(!t)return;const n=function(e){let t=e.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(t)return`https://www.youtube.com/embed/${t[1]}`;if(t=e.match(/(?:vimeo\.com\/)(\d+)/),t)return`https://player.vimeo.com/video/${t[1]}`;if(t=e.match(/dailymotion\.com\/video\/([a-zA-Z0-9]+)/),t)return`https://www.dailymotion.com/embed/video/${t[1]}`;return null}(t);if(!n)return;const o=document.createElement("div");o.className="rmx-embed-wrapper",o.setAttribute("contenteditable","false"),o.setAttribute("data-embed-url",t);const r=document.createElement("iframe");r.src=n,r.setAttribute("frameborder","0"),r.setAttribute("allowfullscreen","true"),r.setAttribute("sandbox","allow-scripts allow-same-origin allow-presentation allow-popups"),r.setAttribute("allow","autoplay; picture-in-picture"),r.style.width="100%",r.style.height="100%",o.appendChild(r),e.selection.insertNode(o);const i=document.createElement("p");i.innerHTML="<br>",o.parentNode.insertBefore(i,o.nextSibling)},meta:{icon:"embedMedia",tooltip:"Embed Media"}}),e.commands.register("removeEmbed",{execute(e,{element:t}){if(!t)return;const n=t.closest(".rmx-embed-wrapper")||t,o=document.createElement("p");o.innerHTML="<br>",n.parentNode.replaceChild(o,n)},meta:{tooltip:"Remove Embed"}})}function Gt(e){let t=[],n=-1;function o(e){e.querySelectorAll("mark.rmx-find-highlight").forEach((e=>{const t=e.parentNode;t.replaceChild(document.createTextNode(e.textContent),e),t.normalize()}))}function r(){t=t.filter((e=>e.isConnected)),n>=t.length&&(n=t.length>0?t.length-1:-1)}function i(){r(),t.forEach(((e,t)=>{e.className=t===n?"rmx-find-highlight rmx-find-current":"rmx-find-highlight"})),t[n]&&t[n].scrollIntoView({block:"center",behavior:"smooth"})}e.commands.register("find",{execute:(e,{text:r,caseSensitive:s})=>(t=function(e,t,n=!1){if(o(e),!t)return[];const r=[],i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),s=[];for(;i.nextNode();)s.push(i.currentNode);const a=n?"g":"gi",l=new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a);for(let o=s.length-1;o>=0;o--){const e=s[o],t=e.textContent,n=[];let i;for(;null!==(i=l.exec(t));)n.push({index:i.index,length:i[0].length});for(let o=n.length-1;o>=0;o--){const t=n[o],i=document.createRange();i.setStart(e,t.index),i.setEnd(e,t.index+t.length);const s=document.createElement("mark");s.className="rmx-find-highlight",i.surroundContents(s),r.push(s)}}return r.reverse(),r}(e.element,r,s),n=t.length>0?0:-1,n>=0&&i(),e.eventBus.emit("find:results",{total:t.length,current:n+1}),{total:t.length,current:n+1}),shortcut:"mod+f",meta:{icon:"findReplace",tooltip:"Find & Replace"}}),e.commands.register("findNext",{execute(e){0!==t.length&&(n=(n+1)%t.length,i(),e.eventBus.emit("find:results",{total:t.length,current:n+1}))},meta:{tooltip:"Find Next"}}),e.commands.register("findPrev",{execute(e){0!==t.length&&(n=(n-1+t.length)%t.length,i(),e.eventBus.emit("find:results",{total:t.length,current:n+1}))},meta:{tooltip:"Find Previous"}}),e.commands.register("replace",{execute(e,{replaceText:o}){if(r(),0===t.length||n<0||n>=t.length)return;const s=t[n],a=document.createTextNode(o);s.parentNode.replaceChild(a,s),t.splice(n,1),t.length>0?(n=Math.min(n,t.length-1),i()):n=-1,e.eventBus.emit("find:results",{total:t.length,current:n+1}),e.eventBus.emit("content:change")},meta:{tooltip:"Replace"}}),e.commands.register("replaceAll",{execute(e,{replaceText:o}){r(),t.forEach((e=>{const t=document.createTextNode(o);e.parentNode.replaceChild(t,e)}));const i=t.length;return t=[],n=-1,e.eventBus.emit("find:results",{total:0,current:0}),e.eventBus.emit("content:change"),i},meta:{tooltip:"Replace All"}}),e.commands.register("clearFind",{execute(e){o(e.element),t=[],n=-1},meta:{tooltip:"Clear Find"}})}function Pt(e){e.commands.register("sourceMode",{execute(e){e.isSourceMode=!e.isSourceMode,e.eventBus.emit("mode:change",{sourceMode:e.isSourceMode})},isActive:e=>e.isSourceMode,shortcut:"mod+shift+u",meta:{icon:"sourceMode",tooltip:"Source Code"}})}let Zt=0;function Wt(e){e.commands.register("fullscreen",{execute(e){const t=e.element.closest(".rmx-editor");if(!t)return;const n=t.classList.contains("rmx-fullscreen");n?(t.classList.remove("rmx-fullscreen"),Zt=Math.max(0,Zt-1),0===Zt&&(document.body.style.overflow="")):(t.classList.add("rmx-fullscreen"),Zt++,document.body.style.overflow="hidden"),e.eventBus.emit("fullscreen:toggle",{fullscreen:!n})},isActive(e){const t=e.element.closest(".rmx-editor");return!!t&&t.classList.contains("rmx-fullscreen")},shortcut:"mod+shift+f",meta:{icon:"fullscreen",tooltip:"Fullscreen"}})}let Ot=null;function Vt(e){e.commands.register("distractionFree",{execute(e){const t=e.element.closest(".rmx-editor");if(!t)return;const n=t.classList.contains("rmx-distraction-free");n?(t.classList.remove("rmx-distraction-free"),t.classList.remove("rmx-df-show-chrome"),t.removeEventListener("mousemove",Kt),clearTimeout(Ot)):(t.classList.add("rmx-distraction-free"),t.addEventListener("mousemove",Kt)),e.eventBus.emit("distractionFree:toggle",{active:!n})},isActive(e){const t=e.element.closest(".rmx-editor");return!!t&&t.classList.contains("rmx-distraction-free")},shortcut:"mod+shift+d",meta:{icon:"distractionFree",tooltip:"Distraction-Free Mode"}})}function Kt(e){const t=e.currentTarget;t.classList.contains("rmx-distraction-free")&&(t.classList.add("rmx-df-show-chrome"),clearTimeout(Ot),Ot=setTimeout((()=>{t.classList.remove("rmx-df-show-chrome")}),3e3))}function Xt(e){e.commands.register("toggleSplitView",{execute(e){const t=e.element.closest(".rmx-editor");if(!t)return;const n=t.classList.contains("rmx-split-view");n?t.classList.remove("rmx-split-view"):t.classList.add("rmx-split-view"),e.eventBus.emit("splitView:toggle",{active:!n})},isActive(e){const t=e.element.closest(".rmx-editor");return!!t&&t.classList.contains("rmx-split-view")},shortcut:"mod+shift+v",meta:{icon:"splitView",tooltip:"Split View"}})}const Ut="rmx-color-presets";function qt(){try{const e=localStorage.getItem(Ut);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function jt(e,t){if(e&&Array.isArray(t))try{const n=qt().filter((t=>t.name!==e));n.push({name:e,colors:t}),localStorage.setItem(Ut,JSON.stringify(n))}catch{}}function $t(e){try{const t=qt().filter((t=>t.name!==e));localStorage.setItem(Ut,JSON.stringify(t))}catch{}}function Yt(e){e.commands.register("saveColorPreset",{execute(t,n,o){jt(n,o),e.eventBus.emit("colorPresets:change",{presets:qt()})},meta:{icon:"colorPreset",tooltip:"Save Color Preset"}}),e.commands.register("loadColorPresets",{execute:()=>qt(),meta:{icon:"colorPreset",tooltip:"Load Color Presets"}}),e.commands.register("deleteColorPreset",{execute(t,n){$t(n),e.eventBus.emit("colorPresets:change",{presets:qt()})},meta:{icon:"colorPreset",tooltip:"Delete Color Preset"}})}function Jt(e){e.commands.register("toggleMarkdown",{execute(e){if(e.history.snapshot(),e.isMarkdownMode){const t=Se(e.element.textContent);e.setHTML(t),e.isMarkdownMode=!1}else{const t=ke(e.getHTML());e.element.textContent=t,e.isMarkdownMode=!0}e.element.classList.toggle("rmx-markdown-mode",e.isMarkdownMode),e.eventBus.emit("mode:change:markdown",{markdownMode:e.isMarkdownMode}),e.eventBus.emit("content:change")},isActive:e=>e.isMarkdownMode,meta:{icon:"toggleMarkdown",tooltip:"Toggle Markdown"}})}const Qt=/^\s*(javascript|vbscript|data\s*:\s*text\/html)\s*:/i;function en(e){e.commands.register("insertAttachment",{execute(e,{url:t,filename:n="file",filesize:o}){if(!t)return;if(e.element.focus(),!e.selection.getRange()){const t=document.createRange();t.selectNodeContents(e.element),t.collapse(!1),e.selection.setRange(t)}const r=document.createElement("a");r.href=Qt.test(t)?"#":t,r.className="rmx-attachment",r.setAttribute("data-attachment","true"),r.setAttribute("data-filename",n),o&&r.setAttribute("data-filesize",String(o)),r.target="_blank",r.rel="noopener noreferrer";const i=o?` (${function(e){if(!e||0===e)return"";const t=["B","KB","MB","GB"];let n=e,o=0;for(;n>=1024&&o<t.length-1;)n/=1024,o++;return`${n%1==0?n:n.toFixed(1)} ${t[o]}`}(o)})`:"";if(r.textContent=`📎 ${n}${i}`,e.selection.insertNode(r),!r.nextSibling||r.parentElement===e.element){const e=document.createElement("p");e.innerHTML="<br>",r.parentElement.insertBefore(e,r.nextSibling)}},meta:{icon:"attachment",tooltip:"Insert Attachment"}}),e.commands.register("removeAttachment",{execute(e,{element:t}){t&&t.classList?.contains("rmx-attachment")&&t.parentNode.removeChild(t)},meta:{tooltip:"Remove Attachment"}})}function tn(e){e.commands.register("importDocument",{execute(e,{html:t,mode:n="insert"}){if(t){if(e.element.focus(),"replace"===n)e.setHTML(t);else{if(!e.selection.getRange()){const t=document.createRange();t.selectNodeContents(e.element),t.collapse(!1),e.selection.setRange(t)}e.selection.insertHTML(e.sanitizer.sanitize(t))}e.eventBus.emit("content:change")}},meta:{icon:"importDocument",tooltip:"Import Document"}})}const nn="rmx-recent-commands";function on(){try{const e=localStorage.getItem(nn);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.slice(0,5):[]}catch{return[]}}function rn(e){try{const t=on().filter((t=>t!==e));t.unshift(e),localStorage.setItem(nn,JSON.stringify(t.slice(0,5)))}catch{}}function sn(){try{localStorage.removeItem(nn)}catch{}}const an=[];function ln(e){const t=Array.isArray(e)?e:[e];for(const n of t){const e=an.findIndex((e=>e.id===n.id));e>=0?an[e]=n:an.push(n)}}function cn(e){const t=an.findIndex((t=>t.id===e));return t>=0&&(an.splice(t,1),!0)}function dn(){return[...an]}const un=[{id:"heading1",label:"Heading 1",description:"Large section heading",icon:"H1",keywords:["h1","title","heading","large"],category:"Text",action:e=>e.executeCommand("heading",1)},{id:"heading2",label:"Heading 2",description:"Medium section heading",icon:"H2",keywords:["h2","subtitle","heading","medium"],category:"Text",action:e=>e.executeCommand("heading",2)},{id:"heading3",label:"Heading 3",description:"Small section heading",icon:"H3",keywords:["h3","heading","small"],category:"Text",action:e=>e.executeCommand("heading",3)},{id:"paragraph",label:"Paragraph",description:"Plain text block",icon:"¶",keywords:["text","normal","body","plain"],category:"Text",action:e=>e.executeCommand("heading","p")},{id:"blockquote",label:"Blockquote",description:"Indented quote block",icon:"“",keywords:["quote","citation","indent"],category:"Text",action:e=>e.executeCommand("blockquote")},{id:"codeBlock",label:"Code Block",description:"Monospace code snippet",icon:"<>",keywords:["code","pre","monospace","snippet","programming"],category:"Text",action:e=>e.executeCommand("codeBlock")},{id:"unorderedList",label:"Bulleted List",description:"Unordered bullet list",icon:"•",keywords:["bullet","ul","list","unordered"],category:"Lists",action:e=>e.executeCommand("unorderedList")},{id:"orderedList",label:"Numbered List",description:"Ordered numbered list",icon:"1.",keywords:["number","ol","list","ordered"],category:"Lists",action:e=>e.executeCommand("orderedList")},{id:"taskList",label:"Task List",description:"Checklist with toggleable items",icon:"☑",keywords:["todo","checkbox","checklist","task"],category:"Lists",action:e=>e.executeCommand("taskList")},{id:"image",label:"Image",description:"Insert an image",icon:"🖼",keywords:["img","photo","picture","upload"],category:"Media",action:(e,t)=>t?.("image")},{id:"attachment",label:"Attachment",description:"Attach a file",icon:"📎",keywords:["file","attach","upload","document"],category:"Media",action:(e,t)=>t?.("attachment")},{id:"embedMedia",label:"Embed Media",description:"Embed a YouTube or Vimeo video",icon:"▶",keywords:["video","youtube","vimeo","embed","media"],category:"Media",action:(e,t)=>t?.("embed")},{id:"horizontalRule",label:"Horizontal Rule",description:"Visual divider line",icon:"―",keywords:["hr","divider","line","separator","rule"],category:"Layout",action:e=>e.executeCommand("horizontalRule")},{id:"table",label:"Table",description:"Insert a data table",icon:"☷",keywords:["table","grid","spreadsheet","cells"],category:"Layout",action:(e,t)=>t?.("table")},{id:"insertCallout",label:"Callout",description:"Insert a styled callout block",icon:"ℹ️",keywords:["callout","alert","admonition","info","warning","tip","note"],category:"Insert",action:e=>e.commands.has("insertCallout")&&e.executeCommand("insertCallout")},{id:"insertMath",label:"Math Equation",description:"Insert a LaTeX math expression",icon:"𝑓",keywords:["math","equation","latex","formula","katex"],category:"Insert",action:e=>e.commands.has("insertMath")&&e.executeCommand("insertMath",{latex:"",displayMode:!0})},{id:"insertToc",label:"Table of Contents",description:"Insert an auto-generated table of contents",icon:"📜",keywords:["toc","contents","outline","navigation","index"],category:"Insert",action:e=>e.commands.has("insertToc")&&e.executeCommand("insertToc")},{id:"insertBookmark",label:"Bookmark",description:"Insert a bookmark anchor for linking",icon:"🔖",keywords:["bookmark","anchor","link","target","reference"],category:"Insert",action:e=>e.commands.has("insertBookmark")&&e.executeCommand("insertBookmark",{name:"bookmark"})},{id:"insertMergeTag",label:"Merge Tag",description:"Insert a template merge tag",icon:"🏷️",keywords:["merge","tag","template","variable","placeholder","dynamic"],category:"Insert",action:e=>e.commands.has("insertMergeTag")&&e.executeCommand("insertMergeTag",{tag:"name"})},{id:"addComment",label:"Comment",description:"Add a comment to the selected text",icon:"💬",keywords:["comment","annotate","annotation","note","review","feedback"],category:"Insert",action:e=>e.commands.has("addComment")&&e.executeCommand("addComment")},{id:"findReplace",label:"Find & Replace",description:"Search and replace text",icon:"🔍",keywords:["find","search","replace"],category:"Advanced",action:(e,t)=>t?.("findReplace")},{id:"sourceMode",label:"Source Code",description:"View and edit raw HTML",icon:"</>",keywords:["html","source","code","raw"],category:"Advanced",action:e=>e.executeCommand("sourceMode")},{id:"export",label:"Export",description:"Export as PDF, DOCX, or Markdown",icon:"📤",keywords:["export","download","pdf","docx","save"],category:"Advanced",action:(e,t)=>t?.("export")},{id:"importDocument",label:"Import Document",description:"Import from file",icon:"📥",keywords:["import","upload","open","file"],category:"Advanced",action:(e,t)=>t?.("importDocument")},{id:"toggleAnalytics",label:"Toggle Analytics",description:"Show or hide content analytics panel",icon:"📊",keywords:["analytics","readability","stats","word count","reading time"],category:"Advanced",action:e=>e.commands.has("toggleAnalytics")&&e.executeCommand("toggleAnalytics")},{id:"toggleSpellcheck",label:"Toggle Spellcheck",description:"Enable or disable spelling and grammar checking",icon:"✓",keywords:["spellcheck","spelling","grammar","proofread","writing"],category:"Advanced",action:e=>e.commands.has("toggleSpellcheck")&&e.executeCommand("toggleSpellcheck")},{id:"checkGrammar",label:"Check Grammar",description:"Run grammar and style analysis on content",icon:"Aa",keywords:["grammar","check","proofread","style","writing","passive"],category:"Advanced",action:e=>e.commands.has("checkGrammar")&&e.executeCommand("checkGrammar")},{id:"startCollaboration",label:"Start Collaboration",description:"Connect to collaboration server and start co-editing",icon:"👥",keywords:["collaborate","realtime","share","multiplayer","co-edit"],category:"Advanced",action:e=>e.commands.has("startCollaboration")&&e.executeCommand("startCollaboration")},{id:"stopCollaboration",label:"Stop Collaboration",description:"Disconnect from collaboration session",icon:"🚫",keywords:["disconnect","leave","stop","collaboration"],category:"Advanced",action:e=>e.commands.has("stopCollaboration")&&e.executeCommand("stopCollaboration")},{id:"toggleMarkdown",label:"Toggle Markdown",description:"Switch between WYSIWYG and Markdown editing",icon:"M↓",keywords:["markdown","toggle","wysiwyg","mode"],category:"Advanced",action:e=>e.executeCommand("toggleMarkdown")},{id:"fullscreen",label:"Fullscreen",description:"Enter distraction-free fullscreen mode",icon:"⛶",keywords:["fullscreen","expand","zen","focus","distraction"],category:"Advanced",action:e=>e.executeCommand("fullscreen")},{id:"removeFormat",label:"Clear Formatting",description:"Remove all formatting from selection",icon:"🚫",keywords:["clear","remove","format","plain","reset"],category:"Advanced",action:e=>e.executeCommand("removeFormat")},{id:"distractionFree",label:"Distraction-Free",description:"Hide toolbar and status bar, show on mouse move",icon:"🧘",keywords:["distraction","zen","focus","minimal","clean"],category:"Advanced",action:e=>e.executeCommand("distractionFree")},{id:"toggleSplitView",label:"Split View",description:"Side-by-side edit and preview pane",icon:"◫",keywords:["split","preview","side","dual","pane"],category:"Advanced",action:e=>e.executeCommand("toggleSplitView")}];function hn(e,t,n={}){const{pinRecent:o=!0}=n;if(!t){if(!o)return e;const t=on();if(0===t.length)return e;const n=[];for(const o of t){const t=e.find((e=>e.id===o));t&&n.push({...t,category:"Recent"})}return 0===n.length?e:[...n,...e]}const r=t.toLowerCase(),i=[],s=[];for(const a of e)a.label.toLowerCase().includes(r)?i.push(a):(a.description.toLowerCase().includes(r)||a.keywords.some((e=>e.includes(r))))&&s.push(a);return[...i,...s]}function mn(e){try{const t=new URL(e);if("https:"!==t.protocol&&"http:"!==t.protocol)throw new Error("URL must use http or https protocol");return e}catch(t){throw new Error(`Invalid URL from callback: ${t.message}`)}}function gn(e,t={}){return JSON.stringify({content:e,timestamp:Date.now(),version:1,...t})}function pn(e){if(!e)return null;try{const t=JSON.parse(e);return t&&"string"==typeof t.content?t:null}catch{return null}}class fn{constructor({prefix:e="rmx-autosave"}={}){this.prefix=e}_key(e){return`${this.prefix}:${e}`}async save(e,t,n){try{localStorage.setItem(this._key(e),gn(t,n))}catch(o){throw new Error(`LocalStorage save failed: ${o.message}`)}}async load(e){try{return pn(localStorage.getItem(this._key(e)))}catch{return null}}async clear(e){try{localStorage.removeItem(this._key(e))}catch{}}saveSync(e,t,n){try{return localStorage.setItem(this._key(e),gn(t,n)),!0}catch{return!1}}}class bn{constructor({prefix:e="rmx-autosave"}={}){this.prefix=e}_key(e){return`${this.prefix}:${e}`}async save(e,t,n){try{sessionStorage.setItem(this._key(e),gn(t,n))}catch(o){throw new Error(`SessionStorage save failed: ${o.message}`)}}async load(e){try{return pn(sessionStorage.getItem(this._key(e)))}catch{return null}}async clear(e){try{sessionStorage.removeItem(this._key(e))}catch{}}saveSync(e,t,n){try{return sessionStorage.setItem(this._key(e),gn(t,n)),!0}catch{return!1}}}class yn{constructor({writeFn:e,readFn:t,deleteFn:n}){if("function"!=typeof e)throw new Error("FileSystemProvider requires a writeFn");if("function"!=typeof t)throw new Error("FileSystemProvider requires a readFn");if("function"!=typeof n)throw new Error("FileSystemProvider requires a deleteFn");this.writeFn=e,this.readFn=t,this.deleteFn=n}async save(e,t,n){const o=gn(t,n);await this.writeFn(e,o)}async load(e){return pn(await this.readFn(e))}async clear(e){await this.deleteFn(e)}}class vn{constructor({endpoint:e,headers:t={},method:n="PUT",fetchFn:o,buildUrl:r,buildBody:i,buildLoadUrl:s,buildDeleteUrl:a}){if(!e&&!r)throw new Error("CloudProvider requires an endpoint or buildUrl");if(e)try{const t=new URL(e);if("https:"!==t.protocol&&"http:"!==t.protocol)throw new Error("CloudProvider endpoint must use http or https protocol")}catch(l){if(l.message.includes("protocol"))throw l;throw new Error(`CloudProvider endpoint is not a valid URL: ${e}`)}if(this.endpoint=e,this.headers=t,this.method=n,this._fetch=o||("undefined"!=typeof fetch?fetch.bind(globalThis):null),this.buildUrl=r,this.buildBody=i,this.buildLoadUrl=s||r,this.buildDeleteUrl=a||r,!this._fetch)throw new Error("CloudProvider requires fetch or a custom fetchFn")}_saveUrl(e){return this.buildUrl?mn(this.buildUrl(e)):this.endpoint}_loadUrl(e){if(this.buildLoadUrl)return mn(this.buildLoadUrl(e));const t=this.endpoint.includes("?")?"&":"?";return`${this.endpoint}${t}key=${encodeURIComponent(e)}`}_deleteUrl(e){return this.buildDeleteUrl?mn(this.buildDeleteUrl(e)):this._loadUrl(e)}async _fetchWithRetry(e,t,n=1){try{const n=await this._fetch(e,t);if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);return n}catch(o){if(n>0)return await new Promise((e=>setTimeout(e,1e3))),this._fetchWithRetry(e,t,n-1);throw o}}async save(e,t,n){const o=this.buildBody?this.buildBody(e,t):gn(t,n),r={...this.headers};this.buildBody||r["Content-Type"]||(r["Content-Type"]="application/json"),await this._fetchWithRetry(this._saveUrl(e),{method:this.method,headers:r,body:o})}async load(e){try{const t=await this._fetch(this._loadUrl(e),{method:"GET",headers:this.headers});if(!t.ok){if(404===t.status)return null;throw new Error(`HTTP ${t.status}`)}return pn(await t.text())}catch{return null}}async clear(e){try{await this._fetch(this._deleteUrl(e),{method:"DELETE",headers:this.headers})}catch{}}}class Cn{constructor({save:e,load:t,clear:n}){if("function"!=typeof e)throw new Error("CustomProvider requires a save function");if("function"!=typeof t)throw new Error("CustomProvider requires a load function");if("function"!=typeof n)throw new Error("CustomProvider requires a clear function");this._save=e,this._load=t,this._clear=n}async save(e,t,n){await this._save(e,t,n)}async load(e){return this._load(e)}async clear(e){await this._clear(e)}}function xn(e){if(!e||"localStorage"===e)return new fn;if("sessionStorage"===e)return new bn;if("object"!=typeof e)throw new Error(`Unknown storage provider: ${e}`);if("function"==typeof e.save&&"function"==typeof e.load&&"function"==typeof e.clear)return e.constructor===Object?new Cn(e):e;if(e.endpoint||e.buildUrl)return new vn(e);if(e.writeFn)return new yn(e);if(e.prefix)return new fn(e);throw new Error("Unable to resolve storage provider from config")}const _n=/* @__PURE__ */new Map;class wn{constructor(e,t={}){this.engine=e,this.provider=xn(t.provider),this.key=t.key||"rmx-default";const n=_n.get(this.key);n&&n.destroy(),_n.set(this.key,this),this.interval=t.interval??3e4,this.debounceMs=t.debounce??2e3,this.enabled=!1!==t.enabled,this._debounceTimer=null,this._intervalTimer=null,this._isSaving=!1,this._pendingSave=!1,this._lastSavedContent=null,this._contentChangeHandler=null,this._beforeUnloadHandler=null,this._destroyed=!1,this._consecutiveErrors=0,this._maxRetries=t.maxRetries??5}init(){this.enabled&&!this._destroyed&&(this._contentChangeHandler=()=>{this._scheduleDebouncedSave()},this._unsubContentChange=this.engine.eventBus.on("content:change",this._contentChangeHandler),this.interval>0&&(this._intervalTimer=setInterval((()=>{this.save()}),this.interval)),"undefined"!=typeof window&&(this._beforeUnloadHandler=()=>{this._attemptSyncSave()},window.addEventListener("beforeunload",this._beforeUnloadHandler)))}destroy(){this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null),this._intervalTimer&&(clearInterval(this._intervalTimer),this._intervalTimer=null),this._unsubContentChange&&(this._unsubContentChange(),this._unsubContentChange=null),this._beforeUnloadHandler&&"undefined"!=typeof window&&(window.removeEventListener("beforeunload",this._beforeUnloadHandler),this._beforeUnloadHandler=null),_n.get(this.key)===this&&_n.delete(this.key),this.save().catch((()=>{})).finally((()=>{this._destroyed=!0}))}async save(){if(!this.engine||this._destroyed)return;const e=this.engine.getHTML();if(e!==this._lastSavedContent)if(this._isSaving)this._pendingSave=!0;else{this._isSaving=!0,this.engine.eventBus.emit("autosave:saving");try{await this.provider.save(this.key,e),this._lastSavedContent=e,this._consecutiveErrors=0;const t=Date.now();this.engine.eventBus.emit("autosave:saved",{timestamp:t})}catch(t){this._consecutiveErrors++,this.engine.eventBus.emit("autosave:error",{error:t,retryCount:this._consecutiveErrors})}finally{if(this._isSaving=!1,this._pendingSave)if(this._pendingSave=!1,this._consecutiveErrors>=this._maxRetries)this.engine.eventBus.emit("autosave:error",{error:new Error(`Autosave failed after ${this._maxRetries} consecutive attempts`),fatal:!0});else if(this._consecutiveErrors>0){const e=Math.min(1e3*Math.pow(2,this._consecutiveErrors-1),3e4);setTimeout((()=>this.save()),e)}else this.save()}}}async checkRecovery(e){try{const t=await this.provider.load(this.key);if(!t||!t.content)return null;const n=t.content.trim(),o=(e||"").trim();return n&&n!==o?{recoveredContent:t.content,timestamp:t.timestamp||Date.now()}:null}catch{return null}}async clearRecovery(){try{await this.provider.clear(this.key)}catch{}}_scheduleDebouncedSave(){this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout((()=>{this._debounceTimer=null,this.save()}),this.debounceMs)}_attemptSyncSave(){if(!this.engine||this._destroyed)return;const e=this.engine.getHTML();if(e!==this._lastSavedContent)if("function"!=typeof this.provider.saveSync){if("undefined"!=typeof navigator&&navigator.sendBeacon&&this.provider.endpoint)try{const t=JSON.stringify({key:this.key,content:e,timestamp:Date.now(),version:1});navigator.sendBeacon(this.provider.endpoint,t)}catch{}}else this.provider.saveSync(this.key,e)}}function kn(e){return{name:e.name,version:e.version||"0.0.0",description:e.description||"",author:e.author||"",dependencies:e.dependencies||[],requiresFullAccess:e.requiresFullAccess||!1,lazy:e.lazy||!1,init:e.init||(()=>{}),destroy:e.destroy||(()=>{}),onContentChange:e.onContentChange||null,onSelectionChange:e.onSelectionChange||null,commands:e.commands||[],toolbarItems:e.toolbarItems||[],statusBarItems:e.statusBarItems||[],contextMenuItems:e.contextMenuItems||[],settingsSchema:e.settingsSchema||[],defaultSettings:e.defaultSettings||{}}}function Sn(){let e=null,t=null;return kn({name:"wordCount",requiresFullAccess:!0,init(n){const o=()=>{const e=n.getText().trim(),t={wordCount:e?e.split(/\s+/).length:0,charCount:n.getText().length};n._wordCount=t,n.eventBus.emit("wordcount:update",t)};t=n.eventBus.on("content:change",(()=>{clearTimeout(e),e=setTimeout(o,100)})),o()},destroy(){clearTimeout(e),t&&(t(),t=null)}})}const In=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,WordCountPlugin:Sn},Symbol.toStringTag,{value:"Module"})),En=new RegExp("(?:https?:\\/\\/[^\\s<]{1,2000}[^\\s<.,:;\"')\\]!?])|(?:www\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,62}[a-zA-Z0-9])?(?:\\.[a-zA-Z]{2,20})+(?:\\/[^\\s<]{0,2000}[^\\s<.,:;\"')\\]!?])?)|(?:(?<![a-zA-Z0-9@/:.])(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,62}[a-zA-Z0-9])?\\.){1,10}[a-zA-Z]{2,20}(?:\\/[^\\s<]{0,2000}[^\\s<.,:;\"')\\]!?])?)","g"),An=/https?:\/\/$/,Bn=/https?:\/\/[^\s]*$/,Ln=/* @__PURE__ */new Set(["com","org","net","edu","gov","mil","int","io","co","us","uk","ca","au","de","fr","es","it","nl","be","at","ch","jp","cn","kr","in","br","mx","ru","za","nz","se","no","fi","dk","pl","dev","app","ai","me","tv","cc","info","biz","pro","name","museum","xyz","online","site","tech","store","blog","cloud","design","agency"]);function Tn(e){const t=e.split("/")[0].split(".");return t[t.length-1].toLowerCase()}function Nn(){let e=null;return kn({name:"autolink",requiresFullAccess:!0,init(t){e=e=>{if(" "!==e.key&&"Enter"!==e.key)return;const t=window.getSelection();if(!t||!t.focusNode)return;const n=t.focusNode;if(n.nodeType!==Node.TEXT_NODE)return;if(n.parentElement.closest("a"))return;const o=function(e){if(!e||e.length>4096)return null;const t=Math.max(0,e.length-200);t>0&&(e=e.slice(t));let n=null;for(const o of e.matchAll(En)){const t=o[0],r=t.startsWith("http://")||t.startsWith("https://"),i=!r&&t.startsWith("www."),s=!r&&!i;let a=null;if(r)a={url:t,href:t,startIdx:o.index,endIdx:o.index+t.length};else if(i){const n=e.slice(Math.max(0,o.index-8),o.index);if(An.test(n))continue;a={url:t,href:"https://"+t,startIdx:o.index,endIdx:o.index+t.length}}else if(s){const n=Tn(t);if(!Ln.has(n))continue;const r=e.slice(Math.max(0,o.index-12),o.index);if(Bn.test(r)||/www\.$/.test(r))continue;a={url:t,href:"https://"+t,startIdx:o.index,endIdx:o.index+t.length}}a&&(!n||a.startIdx>=n.startIdx)&&(n=a)}n&&t>0&&(n.startIdx+=t,n.endIdx+=t);return n}(n.textContent);if(!o)return;const{href:r,startIdx:i,endIdx:s}=o;if(s>t.focusOffset)return;const a=document.createRange();a.setStart(n,i),a.setEnd(n,s);const l=document.createElement("a");l.href=r,l.target="_blank",l.rel="noopener noreferrer",a.surroundContents(l);const c=document.createRange();c.setStartAfter(l),c.collapse(!0),t.removeAllRanges(),t.addRange(c)},t.element.addEventListener("keydown",e)},destroy(t){e&&(t.element.removeEventListener("keydown",e),e=null)}})}const Rn=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,AutolinkPlugin:Nn},Symbol.toStringTag,{value:"Module"}));function Hn(e="Start typing..."){return kn({name:"placeholder",requiresFullAccess:!0,init(t){const n=()=>{t.isEmpty()?(t.element.setAttribute("data-placeholder",e),t.element.classList.add("rmx-empty")):t.element.classList.remove("rmx-empty")};t.eventBus.on("content:change",n),t.eventBus.on("focus",n),t.eventBus.on("blur",n),n()}})}const Mn=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,PlaceholderPlugin:Hn},Symbol.toStringTag,{value:"Module"}));class Dn{constructor(e={}){this._maxWorkers=e.maxWorkers||("undefined"!=typeof navigator?navigator.hardwareConcurrency:2)||2,this._workers=[],this._queue=[],this._nextId=1,this._pending=/* @__PURE__ */new Map,this._roundRobin=0,this._enabled="undefined"!=typeof Worker&&!1!==e.enabled,this._workerURL=e.workerURL||null}async execute(e,t){if(!this._enabled)return this._executeFallback(e,t);this._workers.length<this._maxWorkers&&this._spawnWorker();const n=this._nextId++,o=this._workers[this._roundRobin%this._workers.length];return this._roundRobin++,new Promise(((r,i)=>{this._pending.set(n,{resolve:r,reject:i}),o.postMessage({id:n,type:e,data:t})}))}_executeFallback(e,t){switch(e){case"sanitize":return t.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi,"");case"markdown":return t;case"convert":return{format:t.format,html:null,fallback:!0};default:throw new Error(`Unknown task type: ${e}`)}}_spawnWorker(){try{const e=this._workerURL||new URL("data:text/javascript;base64,LyoqCiAqIFdlYiBXb3JrZXIgbW9kdWxlIGZvciBvZmZsb2FkaW5nIGV4cGVuc2l2ZSBlZGl0b3Igb3BlcmF0aW9ucy4KICoKICogSGFuZGxlcyBIVE1MIHNhbml0aXphdGlvbiwgTWFya2Rvd24gcGFyc2luZywgYW5kIGRvY3VtZW50IGNvbnZlcnNpb24KICogZGlzcGF0Y2ggb2ZmIHRoZSBtYWluIHRocmVhZCB0byBrZWVwIHRoZSBlZGl0b3IgcmVzcG9uc2l2ZS4KICoKICogTWVzc2FnZSBwcm90b2NvbDoKICogICBSZXF1ZXN0OiAgeyBpZCwgdHlwZSwgZGF0YSB9CiAqICAgUmVzcG9uc2U6IHsgaWQsIHJlc3VsdCB9IHwgeyBpZCwgZXJyb3IgfQogKi8KCi8qIGVzbGludC1lbnYgd29ya2VyICovCgovKioKICogTWluaW1hbCBIVE1MIHNhbml0aXplciBmb3IgdXNlIGluc2lkZSB0aGUgd29ya2VyLgogKiBTdHJpcHMgc2NyaXB0IHRhZ3MsIGV2ZW50IGhhbmRsZXJzLCBhbmQgZGFuZ2Vyb3VzIGF0dHJpYnV0ZXMuCiAqIEZvciBmdWxsIHNhbml0aXphdGlvbiB0aGUgbWFpbi10aHJlYWQgU2FuaXRpemVyIHNob3VsZCBiZSB1c2VkOwogKiB0aGlzIHByb3ZpZGVzIGEgZmFzdCBmaXJzdCBwYXNzLgogKgogKiBAcGFyYW0ge3N0cmluZ30gaHRtbCAtIFJhdyBIVE1MIHN0cmluZwogKiBAcmV0dXJucyB7c3RyaW5nfSBTYW5pdGl6ZWQgSFRNTCBzdHJpbmcKICovCmZ1bmN0aW9uIHNhbml0aXplSFRNTChodG1sKSB7CiAgLy8gUmVtb3ZlIDxzY3JpcHQ+IGJsb2NrcyAoaW5jbHVkaW5nIGNvbnRlbnQpCiAgbGV0IHJlc3VsdCA9IGh0bWwucmVwbGFjZSgvPHNjcmlwdFxiW148XSooPzooPyE8XC9zY3JpcHQ+KTxbXjxdKikqPFwvc2NyaXB0Pi9naSwgJycpCiAgLy8gUmVtb3ZlIGV2ZW50LWhhbmRsZXIgYXR0cmlidXRlcyAob25jbGljaywgb25sb2FkLCBvbmVycm9yLCBldGMuKQogIHJlc3VsdCA9IHJlc3VsdC5yZXBsYWNlKC9ccytvblx3K1xzKj1ccyooPzoiW14iXSoifCdbXiddKid8W15ccz5dKykvZ2ksICcnKQogIC8vIFJlbW92ZSBqYXZhc2NyaXB0OiBVUkxzCiAgcmVzdWx0ID0gcmVzdWx0LnJlcGxhY2UoL2hyZWZccyo9XHMqWyInXT9ccypqYXZhc2NyaXB0OlteIic+XHNdKi9naSwgJ2hyZWY9IiMiJykKICAvLyBSZW1vdmUgPGlmcmFtZT4sIDxvYmplY3Q+LCA8ZW1iZWQ+IHRhZ3MKICByZXN1bHQgPSByZXN1bHQucmVwbGFjZSgvPChpZnJhbWV8b2JqZWN0fGVtYmVkKVxiW14+XSo+W1xzXFNdKj88XC9cMT4vZ2ksICcnKQogIHJlc3VsdCA9IHJlc3VsdC5yZXBsYWNlKC88KGlmcmFtZXxvYmplY3R8ZW1iZWQpXGJbXj5dKlwvPz4vZ2ksICcnKQogIHJldHVybiByZXN1bHQKfQoKLyoqCiAqIFNpbXBsZSBNYXJrZG93bi10by1IVE1MIGNvbnZlcnRlciBmb3IgdXNlIGluc2lkZSB0aGUgd29ya2VyLgogKiBIYW5kbGVzIGNvbW1vbiBjb25zdHJ1Y3RzOiBoZWFkaW5ncywgYm9sZCwgaXRhbGljLCBjb2RlLCBsaW5rcywKICogdW5vcmRlcmVkL29yZGVyZWQgbGlzdHMsIGJsb2NrcXVvdGVzLCBhbmQgcGFyYWdyYXBocy4KICoKICogQHBhcmFtIHtzdHJpbmd9IG1kIC0gTWFya2Rvd24gc291cmNlCiAqIEByZXR1cm5zIHtzdHJpbmd9IEhUTUwgc3RyaW5nCiAqLwpmdW5jdGlvbiBwYXJzZU1hcmtkb3duKG1kKSB7CiAgY29uc3QgbGluZXMgPSBtZC5zcGxpdCgnXG4nKQogIGNvbnN0IG91dCA9IFtdCiAgbGV0IGluTGlzdCA9IG51bGwgLy8gJ3VsJyB8ICdvbCcgfCBudWxsCgogIGZvciAobGV0IGkgPSAwOyBpIDwgbGluZXMubGVuZ3RoOyBpKyspIHsKICAgIGxldCBsaW5lID0gbGluZXNbaV0KCiAgICAvLyBDbG9zZSBvcGVuIGxpc3QgaWYgdGhlIGN1cnJlbnQgbGluZSBpcyBub3QgYSBsaXN0IGl0ZW0KICAgIGlmIChpbkxpc3QgJiYgIS9eXHMqWy0qXVxzLy50ZXN0KGxpbmUpICYmICEvXlxzKlxkK1wuXHMvLnRlc3QobGluZSkpIHsKICAgICAgb3V0LnB1c2goYDwvJHtpbkxpc3R9PmApCiAgICAgIGluTGlzdCA9IG51bGwKICAgIH0KCiAgICAvLyBIZWFkaW5ncwogICAgY29uc3QgaGVhZGluZ01hdGNoID0gbGluZS5tYXRjaCgvXigjezEsNn0pXHMrKC4qKSQvKQogICAgaWYgKGhlYWRpbmdNYXRjaCkgewogICAgICBjb25zdCBsZXZlbCA9IGhlYWRpbmdNYXRjaFsxXS5sZW5ndGgKICAgICAgb3V0LnB1c2goYDxoJHtsZXZlbH0+JHtpbmxpbmVNYXJrZG93bihoZWFkaW5nTWF0Y2hbMl0pfTwvaCR7bGV2ZWx9PmApCiAgICAgIGNvbnRpbnVlCiAgICB9CgogICAgLy8gQmxvY2txdW90ZQogICAgaWYgKC9ePlxzPy8udGVzdChsaW5lKSkgewogICAgICBvdXQucHVzaChgPGJsb2NrcXVvdGU+JHtpbmxpbmVNYXJrZG93bihsaW5lLnJlcGxhY2UoL14+XHM/LywgJycpKX08L2Jsb2NrcXVvdGU+YCkKICAgICAgY29udGludWUKICAgIH0KCiAgICAvLyBVbm9yZGVyZWQgbGlzdAogICAgY29uc3QgdWxNYXRjaCA9IGxpbmUubWF0Y2goL15ccypbLSpdXHMrKC4qKSQvKQogICAgaWYgKHVsTWF0Y2gpIHsKICAgICAgaWYgKGluTGlzdCAhPT0gJ3VsJykgewogICAgICAgIGlmIChpbkxpc3QpIG91dC5wdXNoKGA8LyR7aW5MaXN0fT5gKQogICAgICAgIG91dC5wdXNoKCc8dWw+JykKICAgICAgICBpbkxpc3QgPSAndWwnCiAgICAgIH0KICAgICAgb3V0LnB1c2goYDxsaT4ke2lubGluZU1hcmtkb3duKHVsTWF0Y2hbMV0pfTwvbGk+YCkKICAgICAgY29udGludWUKICAgIH0KCiAgICAvLyBPcmRlcmVkIGxpc3QKICAgIGNvbnN0IG9sTWF0Y2ggPSBsaW5lLm1hdGNoKC9eXHMqXGQrXC5ccysoLiopJC8pCiAgICBpZiAob2xNYXRjaCkgewogICAgICBpZiAoaW5MaXN0ICE9PSAnb2wnKSB7CiAgICAgICAgaWYgKGluTGlzdCkgb3V0LnB1c2goYDwvJHtpbkxpc3R9PmApCiAgICAgICAgb3V0LnB1c2goJzxvbD4nKQogICAgICAgIGluTGlzdCA9ICdvbCcKICAgICAgfQogICAgICBvdXQucHVzaChgPGxpPiR7aW5saW5lTWFya2Rvd24ob2xNYXRjaFsxXSl9PC9saT5gKQogICAgICBjb250aW51ZQogICAgfQoKICAgIC8vIEJsYW5rIGxpbmUKICAgIGlmIChsaW5lLnRyaW0oKSA9PT0gJycpIHsKICAgICAgY29udGludWUKICAgIH0KCiAgICAvLyBQYXJhZ3JhcGgKICAgIG91dC5wdXNoKGA8cD4ke2lubGluZU1hcmtkb3duKGxpbmUpfTwvcD5gKQogIH0KCiAgaWYgKGluTGlzdCkgb3V0LnB1c2goYDwvJHtpbkxpc3R9PmApCiAgcmV0dXJuIG91dC5qb2luKCdcbicpCn0KCi8qKgogKiBDb252ZXJ0IGlubGluZSBNYXJrZG93biBzeW50YXggdG8gSFRNTC4KICogQHBhcmFtIHtzdHJpbmd9IHRleHQKICogQHJldHVybnMge3N0cmluZ30KICovCmZ1bmN0aW9uIGlubGluZU1hcmtkb3duKHRleHQpIHsKICAvLyBDb2RlIChiYWNrdGljaykKICB0ZXh0ID0gdGV4dC5yZXBsYWNlKC9gKFteYF0rKWAvZywgJzxjb2RlPiQxPC9jb2RlPicpCiAgLy8gQm9sZAogIHRleHQgPSB0ZXh0LnJlcGxhY2UoL1wqXCooLis/KVwqXCovZywgJzxzdHJvbmc+JDE8L3N0cm9uZz4nKQogIHRleHQgPSB0ZXh0LnJlcGxhY2UoL19fKC4rPylfXy9nLCAnPHN0cm9uZz4kMTwvc3Ryb25nPicpCiAgLy8gSXRhbGljCiAgdGV4dCA9IHRleHQucmVwbGFjZSgvXCooLis/KVwqL2csICc8ZW0+JDE8L2VtPicpCiAgdGV4dCA9IHRleHQucmVwbGFjZSgvXyguKz8pXy9nLCAnPGVtPiQxPC9lbT4nKQogIC8vIExpbmtzCiAgdGV4dCA9IHRleHQucmVwbGFjZSgvXFsoW15cXV0rKVxdXCgoW14pXSspXCkvZywgJzxhIGhyZWY9IiQyIj4kMTwvYT4nKQogIHJldHVybiB0ZXh0Cn0KCi8qKgogKiBEaXNwYXRjaCBoYW5kbGVyIGZvciBkb2N1bWVudCBjb252ZXJzaW9uLgogKiBDdXJyZW50bHkgYWN0cyBhcyBhIHBhc3MtdGhyb3VnaCB0aGF0IHZhbGlkYXRlcyB0aGUgcmVxdWVzdDsKICogaGVhdnkgY29udmVyc2lvbiBsb2dpYyBydW5zIG9uIHRoZSBtYWluIHRocmVhZCB3aXRoIGFjY2VzcyB0bwogKiB0aGUgZnVsbCBkb2N1bWVudENvbnZlcnRlciB1dGlsaXRpZXMuCiAqCiAqIEBwYXJhbSB7eyBmb3JtYXQ6IHN0cmluZywgY29udGVudDogc3RyaW5nIH19IGRhdGEKICogQHJldHVybnMge3sgZm9ybWF0OiBzdHJpbmcsIGh0bWw6IHN0cmluZyB9fQogKi8KZnVuY3Rpb24gZGlzcGF0Y2hDb252ZXJzaW9uKGRhdGEpIHsKICBjb25zdCB7IGZvcm1hdCwgY29udGVudCB9ID0gZGF0YQogIC8vIEZvciBmb3JtYXRzIHdlIGNhbiBoYW5kbGUgaW4gdGhlIHdvcmtlciwgZG8gc28gaGVyZS4KICAvLyBPdGhlcndpc2UgcmV0dXJuIGEgbWFya2VyIHRlbGxpbmcgdGhlIG1haW4gdGhyZWFkIHRvIGhhbmRsZSBpdC4KICBpZiAoZm9ybWF0ID09PSAnbWFya2Rvd24nIHx8IGZvcm1hdCA9PT0gJ21kJykgewogICAgcmV0dXJuIHsgZm9ybWF0LCBodG1sOiBwYXJzZU1hcmtkb3duKGNvbnRlbnQpIH0KICB9CiAgcmV0dXJuIHsgZm9ybWF0LCBodG1sOiBudWxsLCBmYWxsYmFjazogdHJ1ZSB9Cn0KCi8vIC0tLSBNZXNzYWdlIGhhbmRsZXIgLS0tCnNlbGYub25tZXNzYWdlID0gZnVuY3Rpb24gKGUpIHsKICBjb25zdCB7IGlkLCB0eXBlLCBkYXRhIH0gPSBlLmRhdGEKICB0cnkgewogICAgbGV0IHJlc3VsdAogICAgc3dpdGNoICh0eXBlKSB7CiAgICAgIGNhc2UgJ3Nhbml0aXplJzoKICAgICAgICByZXN1bHQgPSBzYW5pdGl6ZUhUTUwoZGF0YSkKICAgICAgICBicmVhawogICAgICBjYXNlICdtYXJrZG93bic6CiAgICAgICAgcmVzdWx0ID0gcGFyc2VNYXJrZG93bihkYXRhKQogICAgICAgIGJyZWFrCiAgICAgIGNhc2UgJ2NvbnZlcnQnOgogICAgICAgIHJlc3VsdCA9IGRpc3BhdGNoQ29udmVyc2lvbihkYXRhKQogICAgICAgIGJyZWFrCiAgICAgIGRlZmF1bHQ6CiAgICAgICAgdGhyb3cgbmV3IEVycm9yKGBVbmtub3duIHRhc2sgdHlwZTogJHt0eXBlfWApCiAgICB9CiAgICBzZWxmLnBvc3RNZXNzYWdlKHsgaWQsIHJlc3VsdCB9KQogIH0gY2F0Y2ggKGVycikgewogICAgc2VsZi5wb3N0TWVzc2FnZSh7IGlkLCBlcnJvcjogZXJyLm1lc3NhZ2UgfSkKICB9Cn0K",import.meta.url).href,t=new Worker(e,{type:"module"});t.onmessage=e=>{const{id:t,result:n,error:o}=e.data,r=this._pending.get(t);r&&(this._pending.delete(t),o?r.reject(new Error(o)):r.resolve(n))},t.onerror=e=>{},this._workers.push(t)}catch(e){this._enabled=!1}}get isEnabled(){return this._enabled}get workerCount(){return this._workers.length}destroy(){this._workers.forEach((e=>e.terminate())),this._workers=[],this._pending.forEach((({reject:e})=>{e(new Error("WorkerPool destroyed"))})),this._pending.clear(),this._queue=[]}}const Fn=/* @__PURE__ */new Set(["P","DIV","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","PRE","UL","OL","LI","TABLE","FIGURE","SECTION","ARTICLE","ASIDE","HR","DL","DD","DT","DETAILS","SUMMARY"]);class zn{constructor(e,t={}){this._container=e,this._threshold=t.threshold??200,this._rootMargin=t.rootMargin||"500px",this._observer=null,this._active=!1,this._collapsed=/* @__PURE__ */new Map,this._placeholders=/* @__PURE__ */new Set}init(){0!==this._threshold&&"undefined"!=typeof IntersectionObserver&&(this._observer=new IntersectionObserver((e=>this._handleIntersection(e)),{root:null,rootMargin:this._rootMargin,threshold:0}),this._scan())}_scan(){const e=this._getBlockElements();e.length<this._threshold?this._active=!1:(this._active=!0,e.forEach((e=>{this._observer.observe(e)})))}_getBlockElements(){const e=[],t=this._container.children;for(let n=0;n<t.length;n++){const o=t[n];1===o.nodeType&&Fn.has(o.tagName)&&e.push(o)}return e}_handleIntersection(e){for(const t of e){const e=t.target;t.isIntersecting?this._restore(e):this._collapse(e)}}_collapse(e){if(this._placeholders.has(e))return;if(this._collapsed.has(e))return;const t=e.getBoundingClientRect().height;if(0===t)return;const n=e.innerHTML,o=e.tagName;this._collapsed.set(e,{html:n,height:t,tagName:o}),e.innerHTML="",e.style.minHeight=`${t}px`,e.setAttribute("data-virtualized","true"),this._placeholders.add(e)}_restore(e){const t=this._collapsed.get(e);t&&(e.innerHTML=t.html,e.style.minHeight="",e.removeAttribute("data-virtualized"),this._collapsed.delete(e),this._placeholders.delete(e))}restoreAll(){this._collapsed.forEach(((e,t)=>{this._restore(t)}))}refresh(){this._observer&&(this._observer.disconnect(),this.restoreAll(),this._scan())}get isActive(){return this._active}get collapsedCount(){return this._collapsed.size}destroy(){this.restoreAll(),this._observer&&(this._observer.disconnect(),this._observer=null),this._collapsed.clear(),this._placeholders.clear(),this._active=!1}}const Gn=new L;function Pn(e,t){const n=URL.createObjectURL(e),o=document.createElement("a");o.href=n,o.download=t,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(n)}function Zn(e,t="document.md"){const n=ke(e);Pn(new Blob([n],{type:"text/markdown;charset=utf-8"}),t)}function Wn(e,t="Document"){const n=document.createElement("iframe");n.style.cssText="position:fixed;left:-9999px;top:-9999px;width:0;height:0;",n.setAttribute("sandbox","allow-same-origin allow-modals"),document.body.appendChild(n);const o=Gn.sanitize(e),r=`<!DOCTYPE html>\n<html>\n<head>\n <title>${t.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}</title>\n <style>\n body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #1a1a1a; max-width: 800px; margin: 0 auto; padding: 20px; }\n h1, h2, h3, h4, h5, h6 { margin-top: 1.2em; margin-bottom: 0.4em; }\n img { max-width: 100%; height: auto; }\n table { border-collapse: collapse; width: 100%; }\n th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }\n pre { background: #f5f5f5; padding: 12px; border-radius: 4px; overflow-x: auto; }\n code { font-family: 'SFMono-Regular', Consolas, monospace; font-size: 0.9em; }\n blockquote { border-left: 3px solid #ccc; margin-left: 0; padding-left: 16px; color: #555; }\n @media print { body { padding: 0; } }\n </style>\n</head>\n<body>${o}</body>\n</html>`;n.srcdoc=r;let i=!1;const s=()=>{i||(i=!0,clearTimeout(a),n.parentNode&&document.body.removeChild(n))};n.contentWindow.onafterprint=s;let a=setTimeout(s,6e4);n.onload=()=>{n.contentWindow.focus(),n.contentWindow.print(),clearTimeout(a),a=setTimeout(s,1e3)}}function On(e,t="document.doc"){Pn(new Blob(["\ufeff",`<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">\n<head><meta charset="utf-8"><style>\nbody { font-family: Calibri, sans-serif; line-height: 1.5; color: #1a1a1a; }\nh1, h2, h3, h4, h5, h6 { margin-top: 1em; margin-bottom: 0.4em; }\ntable { border-collapse: collapse; width: 100%; }\nth, td { border: 1px solid #999; padding: 6px 10px; }\npre { background: #f5f5f5; padding: 10px; font-family: Consolas, monospace; font-size: 0.9em; }\ncode { font-family: Consolas, monospace; font-size: 0.9em; }\nblockquote { border-left: 3px solid #ccc; margin-left: 0; padding-left: 14px; color: #555; }\nimg { max-width: 100%; }\n</style></head>\n<body>${e}</body></html>`],{type:"application/msword"}),t)}function Vn(e,t){const n=new Set(t.map((e=>e.toLowerCase())));return e.filter((e=>!n.has(e.toLowerCase())))}function Kn(e,t,n={}){const o=new Set(e.map((e=>e.toLowerCase()))),r=t.filter((e=>!o.has(e.toLowerCase())));return"start"===n.position?[...r,...e]:[...e,...r]}function Xn(e,t={}){if(!e||0===e.length)return null;if("undefined"==typeof document)return null;const n=`https://fonts.googleapis.com/css2?${e.map((e=>(e.includes(":"),`family=${e.replace(/ /g,"+")}`))).join("&")}&display=swap`,o=document.querySelector(`link[href="${n}"]`);if(o)return o;const r=document.createElement("link");return r.rel="stylesheet",r.href=n,r.dataset.remyxFonts="true",t.integrity?(r.integrity=t.integrity,r.crossOrigin=t.crossOrigin||"anonymous"):r.crossOrigin=t.crossOrigin||"anonymous",document.head.appendChild(r),r}const Un=/* @__PURE__ */new Set(["html","head","body","div","section","article","aside","nav","header","footer","main","p","h1","h2","h3","h4","h5","h6","ul","ol","li","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","blockquote","pre","figure","figcaption","form","fieldset","legend","details","summary","hr","br","iframe","video","audio","canvas"]),qn=/* @__PURE__ */new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),jn=/* @__PURE__ */new Set(["pre","code","script","style","textarea"]);function $n(e){if(!e||!e.trim())return"";const t=[];return Yn((new DOMParser).parseFromString(`<body>${e}</body>`,"text/html").body,0,t," "),t.join("\n").trim()}function Yn(e,t,n,o){const r=Array.from(e.childNodes);for(const i of r){if(i.nodeType===Node.COMMENT_NODE){n.push(`${o.repeat(Math.max(0,t))}\x3c!--${i.textContent}--\x3e`);continue}if(i.nodeType===Node.TEXT_NODE){const e=i.textContent;if(!e.trim())continue;const r=e.replace(/\s+/g," ").trim();r&&n.push(`${o.repeat(Math.max(0,t))}${r}`);continue}if(i.nodeType!==Node.ELEMENT_NODE)continue;const e=i.tagName.toLowerCase();if(jn.has(e)){n.push(`${o.repeat(Math.max(0,t))}${i.outerHTML}`);continue}const r=qn.has(e),s=o.repeat(Math.max(0,t)),a=Jn(i,e);if(r){n.push(`${s}${a}`);continue}if(Qn(i)){const t=eo(i);n.push(`${s}${a}${t}</${e}>`)}else n.push(`${s}${a}`),Yn(i,t+1,n,o),n.push(`${s}</${e}>`)}}function Jn(e,t){const n=Array.from(e.attributes);if(0===n.length)return`<${t}>`;return`<${t} ${n.map((e=>{return""===e.value?e.name:`${e.name}="${t=e.value,te(t)}"`;var t})).join(" ")}>`}function Qn(e){for(const t of e.childNodes)if(t.nodeType!==Node.TEXT_NODE&&t.nodeType===Node.ELEMENT_NODE){const e=t.tagName.toLowerCase();if(Un.has(e))return!1;if(!Qn(t))return!1}return!0}function eo(e){let t="";for(const n of e.childNodes)if(n.nodeType===Node.TEXT_NODE)t+=n.textContent.replace(/\s+/g," ");else if(n.nodeType===Node.ELEMENT_NODE){const e=n.tagName.toLowerCase(),o=Jn(n,e);qn.has(e)?t+=o:t+=`${o}${eo(n)}</${e}>`}return t}const to=/[\u0591-\u07FF\u200F\u202B\u202E\uFB1D-\uFDFD\uFE70-\uFEFC]/,no=/[A-Za-z\u00C0-\u00FF\u0100-\u024F\u0400-\u04FF\u1100-\u11FF\u3040-\u309F\u30A0-\u30FF\u3400-\u4DBF\u4E00-\u9FFF]/;function oo(e){if(!e||"string"!=typeof e)return"auto";let t=0,n=0;for(let o=0;o<e.length;o++){const r=e[o];to.test(r)?t++:no.test(r)&&n++}return 0===t&&0===n?"auto":t>n?"rtl":"ltr"}function ro(e){if(!e||!e.textContent)return;const t=oo(e.textContent);"auto"===t?e.removeAttribute("dir"):e.setAttribute("dir",t)}function io(e){if(!e)return;const t=e.querySelectorAll("p, h1, h2, h3, h4, h5, h6, li, blockquote, td, th");for(const n of t)ro(n)}const so={marginStart:"margin-inline-start",marginEnd:"margin-inline-end",paddingStart:"padding-inline-start",paddingEnd:"padding-inline-end",borderStart:"border-inline-start",borderEnd:"border-inline-end",insetStart:"inset-inline-start",insetEnd:"inset-inline-end"},ao={"toolbar.bold":"Bold","toolbar.italic":"Italic","toolbar.underline":"Underline","toolbar.strikethrough":"Strikethrough","toolbar.subscript":"Subscript","toolbar.superscript":"Superscript","toolbar.removeFormat":"Remove Formatting","toolbar.heading":"Heading","toolbar.paragraph":"Normal text","toolbar.orderedList":"Numbered List","toolbar.unorderedList":"Bulleted List","toolbar.taskList":"Task List","toolbar.indent":"Increase Indent","toolbar.outdent":"Decrease Indent","toolbar.alignLeft":"Align Left","toolbar.alignCenter":"Align Center","toolbar.alignRight":"Align Right","toolbar.alignJustify":"Justify","toolbar.blockquote":"Blockquote","toolbar.codeBlock":"Code Block","toolbar.horizontalRule":"Horizontal Rule","toolbar.link":"Insert Link","toolbar.image":"Insert Image","toolbar.table":"Insert Table","toolbar.fontFamily":"Font Family","toolbar.fontSize":"Font Size","toolbar.foreColor":"Text Color","toolbar.backColor":"Background Color","toolbar.undo":"Undo","toolbar.redo":"Redo","toolbar.source":"Source Code","toolbar.markdown":"Markdown","toolbar.fullscreen":"Fullscreen","toolbar.commandPalette":"Command Palette","toolbar.print":"Print","toolbar.findReplace":"Find & Replace","toolbar.lineNumbers":"Toggle Line Numbers","toolbar.copyCode":"Copy Code","menu.file":"File","menu.edit":"Edit","menu.view":"View","menu.insert":"Insert","menu.format":"Format","context.cut":"Cut","context.copy":"Copy","context.paste":"Paste","context.selectAll":"Select All","context.toggleHeaderRow":"Toggle Header Row","context.formatCell":"Format Cell","context.clearFilters":"Clear Filters","modal.link.title":"Insert Link","modal.link.url":"URL","modal.link.text":"Link Text","modal.link.newTab":"Open in new tab","modal.link.insert":"Insert","modal.link.cancel":"Cancel","modal.image.title":"Insert Image","modal.image.url":"Image URL","modal.image.alt":"Alt Text","modal.image.insert":"Insert","modal.image.cancel":"Cancel","modal.source.title":"Edit Source","modal.source.apply":"Apply","modal.source.cancel":"Cancel","modal.table.title":"Insert Table","modal.table.rows":"Rows","modal.table.cols":"Columns","modal.table.insert":"Insert","modal.table.cancel":"Cancel","find.placeholder":"Find...","find.replace":"Replace...","find.replaceAll":"Replace All","find.matchCase":"Match Case","find.noResults":"No results","find.results":"{{current}} of {{total}}","palette.placeholder":"Type a command...","palette.noResults":"No matching commands","autosave.saved":"Saved","autosave.saving":"Saving...","autosave.unsaved":"Unsaved changes","autosave.error":"Save failed","autosave.recovery":"Unsaved content was recovered.","autosave.restore":"Restore","autosave.dismiss":"Dismiss","a11y.skipToEditor":"Skip to editor","a11y.toolbar":"Editor toolbar","a11y.menuBar":"Editor menu bar","a11y.editor":"Rich text editor","heading.h1":"Heading 1","heading.h2":"Heading 2","heading.h3":"Heading 3","heading.h4":"Heading 4","heading.h5":"Heading 5","heading.h6":"Heading 6","heading.paragraph":"Normal text","format.number":"Number","format.currency":"Currency","format.percentage":"Percentage","format.date":"Date","status.words":"{{count}} words","status.chars":"{{count}} characters"};let lo={...ao};const co={en:ao};let uo="en";function ho(e,t){let n=lo[e];if(void 0===n)return e;if(t)for(const[o,r]of Object.entries(t))n=n.replace(new RegExp(`\\{\\{${o}\\}\\}`,"g"),String(r));return n}function mo(e){const t=co[e];if(!t)throw new Error(`Locale "${e}" is not registered. Use registerLocale() first.`);uo=e,lo={...ao,...t}}function go(){return uo}function po(e,t){if(!e||"string"!=typeof e)throw new Error("registerLocale: lang is required");if(!t||"object"!=typeof t)throw new Error("registerLocale: strings object is required");co[e]=t}function fo(e){"en"!==e&&(delete co[e],uo===e&&mo("en"))}function bo(){return Object.keys(co)}function yo(e){return new Promise((t=>{requestAnimationFrame((()=>{for(const t of e)t();t()}))}))}function vo(e,t={}){const n=t.timeout||2e3;return"function"==typeof requestIdleCallback?requestIdleCallback(e,{timeout:n}):setTimeout(e,16)}function Co(e){"function"==typeof cancelIdleCallback?cancelIdleCallback(e):clearTimeout(e)}function xo(e){let t=null;return function(...n){null===t&&(t=requestAnimationFrame((()=>{e.apply(this,n),t=null})))}}function _o(e,t){const n=performance.now(),o=t();performance.now();return"undefined"!=typeof console&&console.debug,o}function wo(e,t,n=100){const o=[];for(let r=0;r<n;r++){const e=performance.now();t(),o.push(performance.now()-e)}o.sort(((e,t)=>e-t));return{label:e,mean:o.reduce(((e,t)=>e+t),0)/o.length,median:o[Math.floor(o.length/2)],min:o[0],max:o[o.length-1],p95:o[Math.floor(.95*o.length)]}}function ko(e,t={}){const n=t.flushMs||16;let o=[],r=null;return{queue(t){o.push(t),r||(r="function"==typeof requestAnimationFrame?requestAnimationFrame((()=>{const t=o;o=[],r=null,e(t)})):setTimeout((()=>{const t=o;o=[],r=null,e(t)}),n))},flush(){if(r&&("function"==typeof cancelAnimationFrame?cancelAnimationFrame(r):clearTimeout(r),r=null),o.length){const t=o;o=[],e(t)}},destroy(){r&&("function"==typeof cancelAnimationFrame?cancelAnimationFrame(r):clearTimeout(r)),o=[],r=null}}}const So={bg:{var:"--rmx-bg",description:"Editor background color"},text:{var:"--rmx-text",description:"Primary text color"},textSecondary:{var:"--rmx-text-secondary",description:"Secondary/muted text color"},border:{var:"--rmx-border",description:"Border color"},borderSubtle:{var:"--rmx-border-subtle",description:"Subtle/light border color"},toolbarBg:{var:"--rmx-toolbar-bg",description:"Toolbar background color"},toolbarBorder:{var:"--rmx-toolbar-border",description:"Toolbar border color"},toolbarButtonHover:{var:"--rmx-toolbar-button-hover",description:"Toolbar button hover background"},toolbarButtonActive:{var:"--rmx-toolbar-button-active",description:"Toolbar button active background"},toolbarIcon:{var:"--rmx-toolbar-icon",description:"Toolbar icon color"},toolbarIconActive:{var:"--rmx-toolbar-icon-active",description:"Toolbar icon active color"},primary:{var:"--rmx-primary",description:"Primary accent color"},primaryHover:{var:"--rmx-primary-hover",description:"Primary color on hover"},primaryLight:{var:"--rmx-primary-light",description:"Light variant of primary (backgrounds)"},focusRing:{var:"--rmx-focus-ring",description:"Focus ring outline color"},selection:{var:"--rmx-selection",description:"Text selection highlight color"},danger:{var:"--rmx-danger",description:"Error/danger color"},dangerLight:{var:"--rmx-danger-light",description:"Light variant of danger"},placeholder:{var:"--rmx-placeholder",description:"Placeholder text color"},modalBg:{var:"--rmx-modal-bg",description:"Modal background color"},modalOverlay:{var:"--rmx-modal-overlay",description:"Modal overlay background"},statusbarBg:{var:"--rmx-statusbar-bg",description:"Status bar background"},statusbarText:{var:"--rmx-statusbar-text",description:"Status bar text color"},hoverBg:{var:"--rmx-hover-bg",description:"Generic hover background"},shadowSm:{var:"--rmx-shadow-sm",description:"Small shadow"},shadowMd:{var:"--rmx-shadow-md",description:"Medium shadow"},shadowLg:{var:"--rmx-shadow-lg",description:"Large shadow"},shadowFloat:{var:"--rmx-shadow-float",description:"Floating element shadow"},fontFamily:{var:"--rmx-font-family",description:"UI font stack"},fontSize:{var:"--rmx-font-size",description:"UI font size"},contentFontSize:{var:"--rmx-content-font-size",description:"Content area font size"},contentLineHeight:{var:"--rmx-content-line-height",description:"Content area line height"},radius:{var:"--rmx-radius",description:"Standard border radius"},radiusSm:{var:"--rmx-radius-sm",description:"Small border radius"},radiusInner:{var:"--rmx-radius-inner",description:"Inner element border radius"},spacingXs:{var:"--rmx-spacing-xs",description:"Extra small spacing (4px)"},spacingSm:{var:"--rmx-spacing-sm",description:"Small spacing (8px)"},spacingMd:{var:"--rmx-spacing-md",description:"Medium spacing (12px)"},transitionFast:{var:"--rmx-transition-fast",description:"Fast transition duration"},transitionNormal:{var:"--rmx-transition-normal",description:"Normal transition duration"}},Io={};for(const[Xo,Uo]of Object.entries(So))Io[Xo]=Uo.var;function Eo(e){const t={};for(const[n,o]of Object.entries(e))n.startsWith("--rmx-")?t[n]=o:Io[n]?t[Io[n]]=o:t[`--rmx-${n.replace(/([A-Z])/g,"-$1").toLowerCase()}`]=o;return t}const Ao={ocean:Eo({bg:"#0f172a",text:"#e2e8f0",textSecondary:"#94a3b8",border:"#1e3a5f",borderSubtle:"#1e3a5f",toolbarBg:"#0c1426",toolbarBorder:"#1e3a5f",toolbarButtonHover:"#1e3a5f",toolbarButtonActive:"#1e4976",toolbarIcon:"#94a3b8",toolbarIconActive:"#38bdf8",primary:"#0ea5e9",primaryHover:"#0284c7",primaryLight:"rgba(14, 165, 233, 0.15)",focusRing:"#0ea5e9",selection:"#0c4a6e",placeholder:"#475569",modalBg:"#0c1426",modalOverlay:"rgba(0, 0, 0, 0.6)",statusbarBg:"#0c1426",statusbarText:"#64748b"}),forest:Eo({bg:"#14201a",text:"#d1e7dd",textSecondary:"#8fbc8f",border:"#2d4a3e",borderSubtle:"#2d4a3e",toolbarBg:"#0f1a14",toolbarBorder:"#2d4a3e",toolbarButtonHover:"#2d4a3e",toolbarButtonActive:"#1a5c3a",toolbarIcon:"#8fbc8f",toolbarIconActive:"#4ade80",primary:"#22c55e",primaryHover:"#16a34a",primaryLight:"rgba(34, 197, 94, 0.15)",focusRing:"#22c55e",selection:"#14532d",placeholder:"#4a7c5f",modalBg:"#0f1a14",modalOverlay:"rgba(0, 0, 0, 0.6)",statusbarBg:"#0f1a14",statusbarText:"#4a7c5f"}),sunset:Eo({bg:"#1c1210",text:"#fde8d0",textSecondary:"#d4a574",border:"#5c3a28",borderSubtle:"#5c3a28",toolbarBg:"#181010",toolbarBorder:"#5c3a28",toolbarButtonHover:"#5c3a28",toolbarButtonActive:"#7c4a2a",toolbarIcon:"#d4a574",toolbarIconActive:"#fb923c",primary:"#f97316",primaryHover:"#ea580c",primaryLight:"rgba(249, 115, 22, 0.15)",focusRing:"#f97316",selection:"#7c2d12",placeholder:"#8b6f47",modalBg:"#181010",modalOverlay:"rgba(0, 0, 0, 0.6)",statusbarBg:"#181010",statusbarText:"#8b6f47"}),rose:Eo({bg:"#1c1018",text:"#fde2ee",textSecondary:"#d4809f",border:"#5c2848",borderSubtle:"#5c2848",toolbarBg:"#18101a",toolbarBorder:"#5c2848",toolbarButtonHover:"#5c2848",toolbarButtonActive:"#7c2858",toolbarIcon:"#d4809f",toolbarIconActive:"#fb7185",primary:"#f43f5e",primaryHover:"#e11d48",primaryLight:"rgba(244, 63, 94, 0.15)",focusRing:"#f43f5e",selection:"#881337",placeholder:"#8b4766",modalBg:"#18101a",modalOverlay:"rgba(0, 0, 0, 0.6)",statusbarBg:"#18101a",statusbarText:"#8b4766"})},Bo={color:{var:"--rmx-tb-color",description:"Icon / text color"},background:{var:"--rmx-tb-bg",description:"Default background"},hoverColor:{var:"--rmx-tb-hover-color",description:"Color on hover"},hoverBackground:{var:"--rmx-tb-hover-bg",description:"Background on hover"},activeColor:{var:"--rmx-tb-active-color",description:"Color when active / pressed"},activeBackground:{var:"--rmx-tb-active-bg",description:"Background when active"},border:{var:"--rmx-tb-border",description:"Border shorthand"},borderRadius:{var:"--rmx-tb-radius",description:"Border radius"},size:{var:"--rmx-tb-size",description:"Button width & height"},iconSize:{var:"--rmx-tb-icon-size",description:"Icon size inside button"},padding:{var:"--rmx-tb-padding",description:"Button padding"},opacity:{var:"--rmx-tb-opacity",description:"Button opacity"}},Lo={};for(const[Xo,Uo]of Object.entries(Bo))Lo[Xo]=Uo.var;const To={color:"--rmx-tb-sep-color",width:"--rmx-tb-sep-width",height:"--rmx-tb-sep-height",margin:"--rmx-tb-sep-margin"};function No(e){if(!e||"object"!=typeof e)return null;const t={};let n=!1;for(const[o,r]of Object.entries(e))o.startsWith("--rmx-")?(t[o]=r,n=!0):Lo[o]&&(t[Lo[o]]=r,n=!0);return n?t:null}function Ro(e){if(!e||"object"!=typeof e)return null;const t={};let n=!1;for(const[o,r]of Object.entries(e))o.startsWith("--rmx-")?(t[o]=r,n=!0):To[o]&&(t[To[o]]=r,n=!0);return n?t:null}function Ho(e){if(!e||"object"!=typeof e)return{};const t={};for(const[n,o]of Object.entries(e))if("_separator"===n)t._separator=Ro(o);else{const e=No(o);e&&(t[n]=e)}return t}function Mo(e){if(!e||"object"!=typeof e)throw new Error("defineConfig expects a configuration object");if(e.editors&&"object"!=typeof e.editors)throw new Error('defineConfig: "editors" must be an object mapping names to editor configurations');return e}async function Do(e,t={}){const{env:n,headers:o,signal:r}=t,i=await fetch(e,{headers:{Accept:"application/json, text/yaml, text/plain",...o},signal:r});if(!i.ok)throw new Error(`loadConfig: Failed to fetch "${e}" (HTTP ${i.status})`);const s=await i.text();let a;if(/\.ya?ml(\?.*)?$/i.test(e))a=zo(s);else try{a=JSON.parse(s)}catch{a=zo(s)}if(!a||"object"!=typeof a)throw new Error("loadConfig: Configuration must be a JSON/YAML object");if(n&&a.env&&"object"==typeof a.env){const e=a.env[n];if(e&&"object"==typeof e){const{env:t,...n}=a;a=Fo(n,e)}else{const{env:e,...t}=a;a=t}}else if(a.env){const{env:e,...t}=a;a=t}return a}function Fo(e,t){const n={...e};for(const o of Object.keys(t))t[o]&&"object"==typeof t[o]&&!Array.isArray(t[o])&&e[o]&&"object"==typeof e[o]&&!Array.isArray(e[o])?n[o]=Fo(e[o],t[o]):n[o]=t[o];return n}function zo(e){const t=e.split("\n"),n={},o=[{obj:n,indent:-1}];for(let r=0;r<t.length;r++){const e=t[r];if(/^\s*(#.*)?$/.test(e))continue;const n=e.match(/^(\s*)(.+)$/);if(!n)continue;const i=n[1].length,s=n[2];for(;o.length>1&&o[o.length-1].indent>=i;)o.pop();const a=o[o.length-1].obj,l=s.match(/^-\s+(.*)$/);if(l){const e=Go(l[1]);Array.isArray(a)&&a.push(e);continue}const c=s.match(/^([^:]+?):\s*(.*)$/);if(c){const e=c[1].trim(),n=c[2].trim();if(""===n||"|"===n||">"===n){const n=t[r+1];if(n&&/^\s+-\s/.test(n)){const t=[];a[e]=t,o.push({obj:t,indent:i})}else{const t={};a[e]=t,o.push({obj:t,indent:i})}}else a[e]=Go(n)}}return n}function Go(e){if("true"===e)return!0;if("false"===e)return!1;if("null"===e||"~"===e)return null;if(e.startsWith("[")&&e.endsWith("]"))return e.slice(1,-1).split(",").map((e=>Go(e.trim())));if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);const t=Number(e);return isNaN(t)||""===e?e:t}const Po=/* @__PURE__ */new Map([["WordCountPlugin",async()=>{const{WordCountPlugin:e}=await Promise.resolve().then((()=>In));return e}],["AutolinkPlugin",async()=>{const{AutolinkPlugin:e}=await Promise.resolve().then((()=>Rn));return e}],["PlaceholderPlugin",async e=>{const{PlaceholderPlugin:t}=await Promise.resolve().then((()=>Mn));return t(e?.placeholder)}]]),Zo=/* @__PURE__ */new Map;function Wo(e,t){if("string"!=typeof e||!e)throw new Error("registerPluginFactory: name must be a non-empty string");if("function"!=typeof t)throw new Error("registerPluginFactory: factory must be a function");Zo.set(e,t)}function Oo(e){Zo.delete(e)}function Vo(e){if(e&&Array.isArray(e))return Promise.all(e.map(((e,t)=>{if("function"==typeof e||"object"==typeof e&&null!==e&&"function"==typeof e.init)return e;if("string"==typeof e)return Ko(e);if("object"==typeof e&&null!==e&&"string"==typeof e.name)return Ko(e.name,e.options);throw new Error(`resolvePlugins: invalid plugin entry at index ${t} -- expected string, { name, options }, or plugin instance`)})))}async function Ko(e,t){const n=Zo.get(e);if(n)return n(t);const o=Po.get(e);if(o)return o(t);throw new Error(`resolvePlugins: unknown plugin "${e}". Register it with registerPluginFactory() or import it directly.`)}export{Co as $,k as A,$e as B,Ee as C,fe as D,Ke as E,yn as F,ot as G,ye as H,So as I,Bo as J,_ as K,so as L,Qe as M,Xe as N,Ye as O,Hn as P,Dn as Q,Kn as R,Je as S,Ao as T,qe as U,zn as V,Sn as W,ro as X,io as Y,yo as Z,wo as _,oe as a,zt as a$,F as a0,sn as a1,s as a2,a as a3,he as a4,ko as a5,kn as a6,xn as a7,Eo as a8,je as a9,C as aA,ze as aB,qt as aC,Do as aD,Xn as aE,Q as aF,_o as aG,xo as aH,rn as aI,dt as aJ,en as aK,Nt as aL,Ht as aM,Yt as aN,ln as aO,Vt as aP,Gt as aQ,Ft as aR,st as aS,Wt as aT,ct as aU,vt as aV,tn as aW,bt as aX,ut as aY,po as aZ,Jt as a_,Ho as aa,Mo as ab,$t as ac,oo as ad,ee as ae,te as af,Bt as ag,On as ah,Zn as ai,Wn as aj,hn as ak,$n as al,d as am,tt as an,dn as ao,go as ap,x as aq,on as ar,bo as as,et as at,de as au,ue as av,ke as aw,Ie as ax,u as ay,ce as az,w as b,Wo as b0,De as b1,Pt as b2,Xt as b3,Ct as b4,Vn as b5,Ue as b6,Vo as b7,Ro as b8,No as b9,jt as ba,vo as bb,Ge as bc,mo as bd,ho as be,cn as bf,fo as bg,Oo as bh,Fe as bi,c as bj,l as bk,Nn as c,wn as d,ie as e,vn as f,ne as g,p as h,Cn as i,ge as j,pe as k,nt as l,Se as m,be as n,me as o,Re as p,Ve as q,re as r,o as s,y as t,fn as u,Pe as v,un as w,L as x,g as y,bn as z};
2
+ //# sourceMappingURL=index-Cv62E14a.js.map