@editora/plugins 1.0.10 → 1.0.12

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 (139) hide show
  1. package/README.md +1 -1
  2. package/dist/_commonjsHelpers-BH3jXuIh.js +1 -0
  3. package/dist/_commonjsHelpers-ByX85dGu.mjs +33 -0
  4. package/dist/a11y-checker.cjs.js +12 -12
  5. package/dist/a11y-checker.esm.js +80 -98
  6. package/dist/anchor.cjs.js +12 -12
  7. package/dist/anchor.esm.js +115 -128
  8. package/dist/anchoredPopover-BzqGPOAE.js +1 -0
  9. package/dist/anchoredPopover-Dts0IrgU.mjs +106 -0
  10. package/dist/approval-workflow.cjs.js +40 -40
  11. package/dist/approval-workflow.esm.js +208 -249
  12. package/dist/background-color.cjs.js +2 -2
  13. package/dist/background-color.esm.js +55 -68
  14. package/dist/blockquote.esm.js +1 -2
  15. package/dist/blocks-library.cjs.js +45 -45
  16. package/dist/blocks-library.esm.js +178 -245
  17. package/dist/capitalization.esm.js +1 -2
  18. package/dist/checklist.cjs.js +1 -1
  19. package/dist/checklist.esm.js +58 -82
  20. package/dist/citations.cjs.js +37 -37
  21. package/dist/citations.esm.js +439 -512
  22. package/dist/clear-formatting.cjs.js +1 -1
  23. package/dist/clear-formatting.esm.js +27 -33
  24. package/dist/code-sample.cjs.js +14 -14
  25. package/dist/code-sample.esm.js +82 -93
  26. package/dist/code.cjs.js +119 -42
  27. package/dist/code.esm.js +2560 -760
  28. package/dist/comments.cjs.js +6 -6
  29. package/dist/comments.esm.js +116 -158
  30. package/dist/conditional-content.cjs.js +90 -90
  31. package/dist/conditional-content.esm.js +371 -432
  32. package/dist/content-rules.cjs.js +7 -7
  33. package/dist/content-rules.esm.js +105 -159
  34. package/dist/data-binding.cjs.js +46 -46
  35. package/dist/data-binding.esm.js +328 -368
  36. package/dist/direction.esm.js +9 -18
  37. package/dist/doc-schema.cjs.js +29 -29
  38. package/dist/doc-schema.esm.js +240 -308
  39. package/dist/document-manager.cjs.js +1 -1
  40. package/dist/document-manager.esm.js +4 -5
  41. package/dist/documentManager-CTqRftU8.mjs +8369 -0
  42. package/dist/documentManager-Jf0RbSks.js +17 -0
  43. package/dist/{editorContainerHelpers-69585c07.mjs → editorContainerHelpers-C7kdWnS0.mjs} +1 -2
  44. package/dist/embed-iframe.cjs.js +4 -4
  45. package/dist/embed-iframe.esm.js +73 -81
  46. package/dist/emojis.cjs.js +8 -8
  47. package/dist/emojis.esm.js +65 -77
  48. package/dist/enterprise.cjs.js +1 -1
  49. package/dist/enterprise.esm.js +54 -56
  50. package/dist/font-family.cjs.js +1 -1
  51. package/dist/font-family.esm.js +39 -47
  52. package/dist/font-size.cjs.js +1 -1
  53. package/dist/font-size.esm.js +37 -53
  54. package/dist/footnote.cjs.js +2 -2
  55. package/dist/footnote.esm.js +76 -117
  56. package/dist/history.cjs.js +1 -1
  57. package/dist/history.esm.js +70 -92
  58. package/dist/html2canvas.esm-B5qzocYs.js +5 -0
  59. package/dist/{html2canvas.esm-1a1724a1.mjs → html2canvas.esm-BWVIUcAF.mjs} +141 -225
  60. package/dist/indent.cjs.js +1 -1
  61. package/dist/indent.esm.js +12 -24
  62. package/dist/{index-f04538f2.mjs → index-BFsKNTTj.mjs} +70 -71
  63. package/dist/index-CvJk4DKa.js +221 -0
  64. package/dist/index-D3CycEFU.mjs +16543 -0
  65. package/dist/index-tqLTHcO6.js +1 -0
  66. package/dist/index.cjs.js +1 -1
  67. package/dist/index.es-CE_A4QSm.js +5 -0
  68. package/dist/index.es-DQ78mYYo.mjs +6665 -0
  69. package/dist/index.esm.js +125 -128
  70. package/dist/italic.cjs.js +1 -1
  71. package/dist/italic.esm.js +8 -9
  72. package/dist/jspdf.es.min-BoS80556.js +77 -0
  73. package/dist/{jspdf.es.min-c36a4fd8.mjs → jspdf.es.min-DQCoX5yh.mjs} +3658 -4682
  74. package/dist/line-height.cjs.js +1 -1
  75. package/dist/line-height.esm.js +11 -24
  76. package/dist/link.cjs.js +5 -5
  77. package/dist/link.esm.js +24 -30
  78. package/dist/list.cjs.js +1 -1
  79. package/dist/list.esm.js +20 -25
  80. package/dist/lite.cjs.js +1 -1
  81. package/dist/lite.esm.js +59 -61
  82. package/dist/math.cjs.js +21 -21
  83. package/dist/math.esm.js +139 -146
  84. package/dist/media-manager.cjs.js +31 -31
  85. package/dist/media-manager.esm.js +285 -300
  86. package/dist/mentions.cjs.js +9 -9
  87. package/dist/mentions.esm.js +238 -286
  88. package/dist/merge-tag.cjs.js +2 -2
  89. package/dist/merge-tag.esm.js +177 -216
  90. package/dist/page-break.cjs.js +2 -2
  91. package/dist/page-break.esm.js +33 -49
  92. package/dist/pii-redaction.cjs.js +19 -19
  93. package/dist/pii-redaction.esm.js +393 -463
  94. package/dist/plugins.css +1 -0
  95. package/dist/preview.esm.js +5 -10
  96. package/dist/print.cjs.js +4 -4
  97. package/dist/print.esm.js +17 -20
  98. package/dist/{purify.es-35a15df8.mjs → purify.es-DHhaBdbu.mjs} +9 -19
  99. package/dist/{purify.es-a8d731c6.js → purify.es-T2a3nLiC.js} +1 -1
  100. package/dist/slash-commands.cjs.js +2 -2
  101. package/dist/slash-commands.esm.js +39 -75
  102. package/dist/smart-paste.cjs.js +27 -27
  103. package/dist/smart-paste.esm.js +280 -336
  104. package/dist/special-characters.cjs.js +7 -7
  105. package/dist/special-characters.esm.js +61 -69
  106. package/dist/spell-check.cjs.js +5 -5
  107. package/dist/spell-check.esm.js +97 -123
  108. package/dist/strikethrough.cjs.js +1 -1
  109. package/dist/strikethrough.esm.js +14 -19
  110. package/dist/table.cjs.js +4 -4
  111. package/dist/table.esm.js +191 -225
  112. package/dist/template.cjs.js +21 -20
  113. package/dist/template.esm.js +715 -196
  114. package/dist/text-alignment.cjs.js +1 -1
  115. package/dist/text-alignment.esm.js +21 -27
  116. package/dist/text-color.cjs.js +3 -3
  117. package/dist/text-color.esm.js +70 -87
  118. package/dist/track-changes.cjs.js +2 -2
  119. package/dist/track-changes.esm.js +100 -162
  120. package/dist/translation-workflow.cjs.js +74 -74
  121. package/dist/translation-workflow.esm.js +602 -678
  122. package/dist/version-diff.cjs.js +14 -14
  123. package/dist/version-diff.esm.js +128 -157
  124. package/package.json +1 -1
  125. package/dist/_commonjsHelpers-6763f629.js +0 -1
  126. package/dist/_commonjsHelpers-c5d32002.mjs +0 -30
  127. package/dist/anchoredPopover-33f1358d.mjs +0 -109
  128. package/dist/anchoredPopover-8151d535.js +0 -1
  129. package/dist/documentManager-25b6203c.mjs +0 -9122
  130. package/dist/documentManager-b69e7054.js +0 -17
  131. package/dist/html2canvas.esm-09133e29.js +0 -22
  132. package/dist/index-656d224b.js +0 -231
  133. package/dist/index-6a8c48bb.js +0 -1
  134. package/dist/index-d027b7e2.mjs +0 -16859
  135. package/dist/index.es-730f2d98.mjs +0 -5775
  136. package/dist/index.es-dd40173b.js +0 -18
  137. package/dist/jspdf.es.min-90db2c97.js +0 -243
  138. package/dist/style.css +0 -1
  139. /package/dist/{editorContainerHelpers-36b8ddf3.js → editorContainerHelpers-CFbfiOJI.js} +0 -0
package/dist/code.cjs.js CHANGED
@@ -1,8 +1,7 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});class D{constructor(e=""){this._lines=[],this._version=0,this.setText(e)}getLine(e){return this._lines[e]||""}getLines(){return[...this._lines]}getLineCount(){return this._lines.length}getText(){return this._lines.join(`
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});class z{constructor(e=""){this._lines=[],this._version=0,this.setText(e)}getLine(e){return this._lines[e]||""}getLines(){return[...this._lines]}getLineCount(){return this._lines.length}getText(){return this._lines.join(`
2
2
  `)}setText(e){this._lines=e.split(`
3
3
  `),this._version++}getTextInRange(e){if(e.start.line===e.end.line)return this.getLine(e.start.line).substring(e.start.column,e.end.column);const t=[];t.push(this.getLine(e.start.line).substring(e.start.column));for(let i=e.start.line+1;i<e.end.line;i++)t.push(this.getLine(i));return e.end.line<this.getLineCount()&&t.push(this.getLine(e.end.line).substring(0,e.end.column)),t.join(`
4
- `)}replaceRange(e,t){const i=this.getTextInRange(e);if(e.start.line===e.end.line){const s=this.getLine(e.start.line),n=s.substring(0,e.start.column)+t+s.substring(e.end.column);this._lines[e.start.line]=n}else{const s=this.getLine(e.start.line),n=this.getLine(e.end.line),r=s.substring(0,e.start.column)+t,o=n.substring(e.end.column),a=t.split(`
5
- `);a[0]=r+a[0],a[a.length-1]=a[a.length-1]+o,this._lines.splice(e.start.line,e.end.line-e.start.line+1,...a)}return this._version++,{range:e,text:t,oldText:i}}insertText(e,t){const i={start:e,end:e};return this.replaceRange(i,t)}deleteRange(e){return this.replaceRange(e,"")}positionToOffset(e){let t=0;for(let i=0;i<e.line;i++)t+=this.getLine(i).length+1;return t+=e.column,t}offsetToPosition(e){let t=e;for(let i=0;i<this.getLineCount();i++){const s=this.getLine(i).length;if(t<=s)return{line:i,column:t};t-=s+1}return{line:this.getLineCount()-1,column:this.getLine(this.getLineCount()-1).length}}isValidPosition(e){return!(e.line<0||e.line>=this.getLineCount()||e.column<0||e.column>this.getLine(e.line).length)}isValidRange(e){return this.isValidPosition(e.start)&&this.isValidPosition(e.end)}getVersion(){return this._version}clone(){const e=new D;return e._lines=[...this._lines],e._version=this._version,e}}class Z{constructor(e){this.gutterWidth=50,this.lineHeight=21,this.trailingNewlineMarkerAttr="data-lce-trailing-newline-marker",this.virtualMarkerRegex=/[\u200B\uE000]/,this.container=e,this.createDOM()}createDOM(){this.container.innerHTML="";const e=document.createElement("div");this.editorContainer=e,e.setAttribute("data-lce-editor-container","true"),e.style.cssText=`
4
+ `)}replaceRange(e,t){const i=this.normalizeRange(e),s=this.getTextInRange(i),n=this.getText(),r=this.positionToOffset(i.start),o=this.positionToOffset(i.end),l=n.slice(0,r)+t+n.slice(o);return this.setText(l),{range:i,text:t,oldText:s}}insertText(e,t){const i={start:e,end:e};return this.replaceRange(i,t)}deleteRange(e){return this.replaceRange(e,"")}positionToOffset(e){let t=0;for(let i=0;i<e.line;i++)t+=this.getLine(i).length+1;return t+=e.column,t}offsetToPosition(e){let t=e;for(let i=0;i<this.getLineCount();i++){const s=this.getLine(i).length;if(t<=s)return{line:i,column:t};t-=s+1}return{line:this.getLineCount()-1,column:this.getLine(this.getLineCount()-1).length}}isValidPosition(e){return!(e.line<0||e.line>=this.getLineCount()||e.column<0||e.column>this.getLine(e.line).length)}isValidRange(e){return this.isValidPosition(e.start)&&this.isValidPosition(e.end)}getVersion(){return this._version}clone(){const e=new z;return e._lines=[...this._lines],e._version=this._version,e}normalizeRange(e){return this.comparePositions(e.start,e.end)<=0?e:{start:e.end,end:e.start}}comparePositions(e,t){return e.line!==t.line?e.line-t.line:e.column-t.column}}class Q{constructor(e){this.gutterWidth=50,this.lineHeight=21,this.trailingNewlineMarkerAttr="data-lce-trailing-newline-marker",this.foldPlaceholderAttr="data-lce-fold-placeholder",this.virtualMarkerRegex=/[\u200B\uE000]/,this.virtualMarkerGlobalRegex=/[\u200B\uE000]/g,this.lastLineCount=0,this.lastHighlightHTML="",this.highlightOverlayActive=!1,this.lastLineDecorationSnapshot="",this.lastGutterDecorationSnapshot="",this.container=e,this.createDOM()}createDOM(){this.container.innerHTML="";const e=document.createElement("div");this.editorContainer=e,e.setAttribute("data-lce-editor-container","true"),e.style.cssText=`
6
5
  position: relative;
7
6
  display: flex;
8
7
  width: 100%;
@@ -12,22 +11,60 @@
12
11
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
13
12
  font-size: 14px;
14
13
  line-height: ${this.lineHeight}px;
15
- /* make the outer container the single scrollable element so gutter and content scroll together */
16
- overflow: auto;
14
+ /* vertical scrolling is shared; horizontal scrolling belongs to the code pane */
15
+ overflow-x: hidden;
16
+ overflow-y: auto;
17
17
  `,this.lineNumbersElement=document.createElement("div"),this.lineNumbersElement.setAttribute("data-editor-gutter","true"),this.lineNumbersElement.style.cssText=`
18
18
  display: table-cell;
19
19
  vertical-align: top;
20
+ position: sticky;
21
+ left: 0;
20
22
  width: ${this.gutterWidth}px;
21
23
  background: var(--editor-gutter-background, #252526);
22
24
  color: var(--editor-gutter-foreground, #858585);
23
25
  padding: 0 8px 0 0;
24
26
  text-align: right;
25
27
  border-right: 1px solid var(--editor-gutter-border, #3e3e42);
28
+ background-clip: padding-box;
26
29
  user-select: none;
30
+ overflow: hidden;
31
+ z-index: 3;
32
+ `,this.lineNumbersContentElement=document.createElement("div"),this.lineNumbersContentElement.setAttribute("data-editor-gutter-content","true"),this.lineNumbersContentElement.style.cssText=`
33
+ position: relative;
27
34
  z-index: 1;
28
- `,this.contentElement=document.createElement("div"),this.contentElement.style.cssText=`
35
+ `,this.gutterDecorationsElement=document.createElement("div"),this.gutterDecorationsElement.setAttribute("data-editor-gutter-decorations","true"),this.gutterDecorationsElement.setAttribute("aria-hidden","true"),this.gutterDecorationsElement.style.cssText=`
36
+ position: absolute;
37
+ inset: 0;
38
+ z-index: 2;
39
+ pointer-events: none;
40
+ `;const t=document.createElement("div");this.contentSurface=t,t.setAttribute("data-editor-content-surface","true"),t.style.cssText=`
29
41
  display: table-cell;
30
42
  vertical-align: top;
43
+ position: relative;
44
+ width: 100%;
45
+ min-height: 400px;
46
+ `,this.highlightElement=document.createElement("div"),this.highlightElement.setAttribute("data-editor-highlight","true"),this.highlightElement.setAttribute("aria-hidden","true"),this.highlightElement.style.cssText=`
47
+ position: absolute;
48
+ inset: 0;
49
+ padding: 0 12px;
50
+ white-space: pre;
51
+ overflow: hidden;
52
+ min-height: 400px;
53
+ font-family: inherit;
54
+ font-size: inherit;
55
+ line-height: inherit;
56
+ pointer-events: none;
57
+ user-select: none;
58
+ background: transparent;
59
+ visibility: hidden;
60
+ `,this.lineDecorationsElement=document.createElement("div"),this.lineDecorationsElement.setAttribute("data-editor-line-decorations","true"),this.lineDecorationsElement.setAttribute("aria-hidden","true"),this.lineDecorationsElement.style.cssText=`
61
+ position: absolute;
62
+ inset: 0;
63
+ pointer-events: none;
64
+ z-index: 0;
65
+ `,this.contentElement=document.createElement("div"),this.contentElement.style.cssText=`
66
+ position: relative;
67
+ z-index: 1;
31
68
  padding: 0 12px;
32
69
  background: transparent;
33
70
  border: none;
@@ -35,32 +72,54 @@
35
72
  white-space: pre;
36
73
  overflow-x: auto;
37
74
  overflow-y: visible;
75
+ width: 100%;
38
76
  min-height: 400px;
39
77
  font-family: inherit;
40
78
  font-size: inherit;
41
79
  line-height: inherit;
42
80
  color: inherit;
81
+ caret-color: var(--editor-foreground, #f8f9fa);
43
82
  tab-size: 2;
44
83
  -moz-tab-size: 2;
45
- `,this.contentElement.contentEditable="true",this.contentElement.spellcheck=!1;const t=document.createElement("div");t.setAttribute("data-editora-editor","true"),t.style.cssText="display: table; table-layout: fixed; width: 100%; height: 100%;",t.appendChild(this.lineNumbersElement),t.appendChild(this.contentElement),e.appendChild(t),this.container.appendChild(e),this.updateLineNumbers(1)}updateLineNumbers(e){const t=Math.max(e,20),i=Array.from({length:t},(s,n)=>n+1);this.lineNumbersElement.innerHTML=i.map(s=>`<div style="height: ${this.lineHeight}px; line-height: ${this.lineHeight}px; padding-right: 12px;">${s}</div>`).join("")}getContentElement(){return this.contentElement}getLineNumbersElement(){return this.lineNumbersElement}getText(){const e=this.contentElement.textContent||"";return this.contentElement.querySelector(`[${this.trailingNewlineMarkerAttr}]`)&&e.endsWith("​")?e.slice(0,-1):e}setText(e){this.contentElement.textContent=e,this.syncTrailingNewlineMarker(e.endsWith(`
84
+ `,this.contentElement.contentEditable="true",this.contentElement.spellcheck=!1,this.contentElement.tabIndex=0;const i=document.createElement("div");this.scrollWrapper=i,i.setAttribute("data-editora-editor","true"),i.style.cssText=`
85
+ position: relative;
86
+ display: table;
87
+ table-layout: fixed;
88
+ width: 100%;
89
+ height: 100%;
90
+ `,this.lineNumbersElement.appendChild(this.lineNumbersContentElement),this.lineNumbersElement.appendChild(this.gutterDecorationsElement),i.appendChild(this.lineNumbersElement),t.appendChild(this.lineDecorationsElement),t.appendChild(this.highlightElement),t.appendChild(this.contentElement),i.appendChild(t),e.appendChild(i),this.container.appendChild(e),this.updateLineNumbers(1)}updateLineNumbers(e){if(e===this.lastLineCount)return;this.lastLineCount=e;const t=Math.max(e,1),i=Array.from({length:t},(s,n)=>n+1);this.lineNumbersContentElement.innerHTML=i.map(s=>`<div style="height: ${this.lineHeight}px; line-height: ${this.lineHeight}px; padding-right: 12px;">${s}</div>`).join("")}setDecorations(e,t){this.renderLineDecorations(e),this.renderGutterDecorations(t)}clearDecorations(){this.lastLineDecorationSnapshot&&(this.lineDecorationsElement.innerHTML="",this.lastLineDecorationSnapshot=""),this.lastGutterDecorationSnapshot&&(this.gutterDecorationsElement.innerHTML="",this.lastGutterDecorationSnapshot="")}getContentElement(){return this.contentElement}getLineNumbersElement(){return this.lineNumbersElement}getText(){return this.serializeContentToSource()}setText(e){this.clearHighlightOverlay(),this.setFoldPlaceholderSources(new Map),this.contentElement.textContent!==e&&(this.contentElement.textContent=e),this.syncTrailingNewlineMarker(e.endsWith(`
46
91
  `));const t=e.split(`
47
- `).length;this.updateLineNumbers(t)}setHTML(e){const t=/\n$/.test(e),i=/&lt;|&gt;/.test(e),s=/<span\b/i.test(e),n=/<[^>]+>/.test(e);i&&s?this.contentElement.innerHTML=e:n&&!i?this.contentElement.textContent=e:this.contentElement.innerHTML=e,this.syncTrailingNewlineMarker(t);const r=(this.contentElement.textContent||"").split(`
48
- `).length;this.updateLineNumbers(r)}syncTrailingNewlineMarkerForText(e){this.syncTrailingNewlineMarker(e.endsWith(`
49
- `))}getCursorPosition(){const e=window.getSelection();if(!e||e.rangeCount===0)return{line:0,column:0};const t=e.getRangeAt(0),i=t.cloneRange();i.selectNodeContents(this.contentElement),i.setEnd(t.endContainer,t.endOffset);const s=i.toString().replace(/\u200B/g,"").split(`
50
- `);return{line:s.length-1,column:s[s.length-1].length}}setCursorPosition(e){var t;const i=this.getText().split(`
51
- `),s=Math.min(e.line,i.length-1),n=Math.min(e.column,((t=i[s])==null?void 0:t.length)||0);let r=0;for(let l=0;l<s;l++)r+=i[l].length+1;r+=n;const o=document.createRange(),a=window.getSelection(),h=this.resolveOffsetToDomPoint(r);if(h)try{o.setStart(h.node,h.offset),o.setEnd(h.node,h.offset),a==null||a.removeAllRanges(),a==null||a.addRange(o),this.ensureCaretVisible()}catch(l){console.warn("Could not set cursor position:",l)}else{const l=this.contentElement.querySelector(`[${this.trailingNewlineMarkerAttr}]`);try{l&&l.parentNode===this.contentElement?o.setStartBefore(l):(o.selectNodeContents(this.contentElement),o.collapse(!1)),o.collapse(!0),a==null||a.removeAllRanges(),a==null||a.addRange(o),this.ensureCaretVisible()}catch(c){console.warn("Could not set fallback cursor position:",c)}}}getSelectionRange(){const e=window.getSelection();if(!e||e.rangeCount===0||e.isCollapsed)return;const t=e.getRangeAt(0),i=t.cloneRange();i.selectNodeContents(this.contentElement),i.setEnd(t.startContainer,t.startOffset);const s=i.toString().replace(/\u200B/g,"").split(`
52
- `),n=t.cloneRange();n.selectNodeContents(this.contentElement),n.setEnd(t.endContainer,t.endOffset);const r=n.toString().replace(/\u200B/g,"").split(`
53
- `);return{start:{line:s.length-1,column:s[s.length-1].length},end:{line:r.length-1,column:r[r.length-1].length}}}setSelectionRange(e){const t=this.getText().split(`
54
- `),i=c=>{const d=Math.max(0,Math.min(c.line,t.length-1)),p=Math.max(0,Math.min(c.column,t[d]?t[d].length:0));let u=0;for(let g=0;g<d;g++)u+=t[g].length+1;return u+p},s=i(e.start),n=i(e.end),[r,o]=s<=n?[s,n]:[n,s],a=this.resolveOffsetToDomPoint(r),h=this.resolveOffsetToDomPoint(o);if(!a||!h)return;const l=document.createRange();try{l.setStart(a.node,a.offset),l.setEnd(h.node,h.offset);const c=window.getSelection();c==null||c.removeAllRanges(),c==null||c.addRange(l),this.ensureCaretVisible()}catch(c){console.warn("Could not set selection range:",c)}}focus(){this.contentElement.focus(),this.ensureCaretVisible()}blur(){this.contentElement.blur()}setReadOnly(e){this.contentElement.contentEditable=e?"false":"true"}applyTheme(e){Object.entries(e).forEach(([t,i])=>{this.container.style.setProperty(`--${t}`,i)})}scrollToPosition(e){const t=this.lineNumbersElement.children[e.line];t&&t.scrollIntoView({block:"center",behavior:"smooth"})}getScrollTop(){return this.editorContainer.scrollTop}getScrollElement(){return this.editorContainer}setScrollTop(e){this.editorContainer.scrollTop=e}syncTrailingNewlineMarker(e){if(this.contentElement.querySelectorAll(`[${this.trailingNewlineMarkerAttr}]`).forEach(i=>i.remove()),!e)return;const t=document.createElement("span");t.setAttribute(this.trailingNewlineMarkerAttr,"true"),t.setAttribute("aria-hidden","true"),t.contentEditable="false",t.style.cssText=`
92
+ `).length;this.updateLineNumbers(t)}setHTML(e){this.clearHighlightOverlay(),this.setFoldPlaceholderSources(new Map);const t=/\n$/.test(e),i=/&lt;|&gt;/.test(e),s=/<span\b/i.test(e),n=/<[^>]+>/.test(e);i&&s?this.contentElement.innerHTML=e:n&&!i?this.contentElement.textContent=e:this.contentElement.innerHTML=e,this.syncTrailingNewlineMarker(t);const r=(this.contentElement.textContent||"").split(`
93
+ `).length;this.updateLineNumbers(r)}setHighlightHTML(e){e!==this.lastHighlightHTML&&(this.highlightElement.innerHTML=e,this.lastHighlightHTML=e),this.highlightElement.style.visibility="visible",this.highlightOverlayActive=!0,this.contentElement.style.color="transparent",this.contentElement.style.WebkitTextFillColor="transparent";const t=(this.contentElement.textContent||"").split(`
94
+ `).length;this.updateLineNumbers(t)}setLineWrapping(e){this.contentElement.style.whiteSpace=e?"pre-wrap":"pre",this.contentElement.style.overflowX=e?"hidden":"auto",this.contentElement.style.overflowY="visible",this.contentElement.style.wordBreak="normal",this.contentElement.style.overflowWrap=e?"anywhere":"normal",this.highlightElement.style.whiteSpace=e?"pre-wrap":"pre",this.highlightElement.style.wordBreak="normal",this.highlightElement.style.overflowWrap=e?"anywhere":"normal"}setLineNumbersVisible(e){this.lineNumbersElement.style.display=e?"table-cell":"none",this.lineNumbersElement.style.width=e?`${this.gutterWidth}px`:"0",this.lineNumbersElement.style.paddingRight=e?"8px":"0",this.lineNumbersElement.style.borderRightWidth=e?"1px":"0",this.scrollWrapper.style.width=e?"100%":"auto"}setTabSize(e){const t=Math.max(1,Math.floor(e)||2);this.contentElement.style.tabSize=String(t),this.contentElement.style.MozTabSize=String(t),this.highlightElement.style.tabSize=String(t),this.highlightElement.style.MozTabSize=String(t)}syncTrailingNewlineMarkerForText(e){this.syncTrailingNewlineMarker(e.endsWith(`
95
+ `))}getCursorPosition(){return this.getSelectionState().cursor??{line:0,column:0}}setCursorPosition(e){const t=this.getText(),i=this.positionToTextOffset(e,t),s=window.getSelection(),n=this.createDomRangeFromOffsets(i);if(n)try{s?.removeAllRanges(),s?.addRange(n),this.ensureCaretVisible()}catch(r){console.warn("Could not set cursor position:",r)}else{const r=this.contentElement.querySelector(`[${this.trailingNewlineMarkerAttr}]`),o=document.createRange();try{r&&r.parentNode===this.contentElement?o.setStartBefore(r):(o.selectNodeContents(this.contentElement),o.collapse(!1)),o.collapse(!0),s?.removeAllRanges(),s?.addRange(o),this.ensureCaretVisible()}catch(l){console.warn("Could not set fallback cursor position:",l)}}}getSelectionRange(){return this.getSelectionState().range}getSelectionOffsets(){const e=window.getSelection();if(!e||e.rangeCount===0)return{isInEditor:!1,isCollapsed:!0,startOffset:0,endOffset:0};const t=e.getRangeAt(0);if(!this.isNodeInsideContent(t.startContainer)||!this.isNodeInsideContent(t.endContainer))return{isInEditor:!1,isCollapsed:e.isCollapsed,startOffset:0,endOffset:0};const i=e.anchorNode&&this.isNodeInsideContent(e.anchorNode)?this.sourceOffsetFromBoundary(e.anchorNode,e.anchorOffset):void 0,s=e.focusNode&&this.isNodeInsideContent(e.focusNode)?this.sourceOffsetFromBoundary(e.focusNode,e.focusOffset):void 0;return{isInEditor:!0,isCollapsed:e.isCollapsed,startOffset:this.sourceOffsetFromBoundary(t.startContainer,t.startOffset),endOffset:this.sourceOffsetFromBoundary(t.endContainer,t.endOffset),anchorOffset:i,focusOffset:s}}getSelectionState(){const e=window.getSelection();if(!e||e.rangeCount===0)return{isInEditor:!1,isCollapsed:!0};const t=e.getRangeAt(0);if(!this.isNodeInsideContent(t.startContainer)||!this.isNodeInsideContent(t.endContainer))return{isInEditor:!1,isCollapsed:e.isCollapsed};const i=this.getText(),s=this.sourceOffsetFromBoundary(t.startContainer,t.startOffset),n=this.sourceOffsetFromBoundary(t.endContainer,t.endOffset),r=e.focusNode&&this.isNodeInsideContent(e.focusNode)?this.sourceOffsetFromBoundary(e.focusNode,e.focusOffset):n,o=this.offsetToPositionInText(s,i),l=this.offsetToPositionInText(n,i),a=this.offsetToPositionInText(r,i);return{isInEditor:!0,isCollapsed:e.isCollapsed,cursor:a,range:e.isCollapsed?void 0:{start:o,end:l}}}setSelectionRange(e){const t=this.createDomRangeFromRange(e);if(t)try{const i=window.getSelection();i?.removeAllRanges(),i?.addRange(t),this.ensureCaretVisible()}catch(i){console.warn("Could not set selection range:",i)}}createDomRangeFromOffsets(e,t=e){const[i,s]=e<=t?[e,t]:[t,e],n=this.resolveOffsetToDomPoint(i),r=this.resolveOffsetToDomPoint(s);if(!n||!r)return null;const o=document.createRange();try{return o.setStart(n.node,n.offset),o.setEnd(r.node,r.offset),o}catch{return null}}createDomRangeFromRange(e){const t=this.getText();return this.createDomRangeFromOffsets(this.positionToTextOffset(e.start,t),this.positionToTextOffset(e.end,t))}getPositionFromClientPoint(e,t){const i=this.getDomRangeFromClientPoint(e,t);if(!i||!this.isNodeInsideContent(i.startContainer))return null;const s=this.sourceOffsetFromBoundary(i.startContainer,i.startOffset);return this.offsetToPositionInText(s,this.getText())}setSelectionOffsets(e,t=e){const i=this.createDomRangeFromOffsets(e,t);if(i)try{const s=window.getSelection();s?.removeAllRanges(),s?.addRange(i),this.ensureCaretVisible()}catch(s){console.warn("Could not set selection offsets:",s)}}setSelectionBoundaryOffsets(e,t){const i=this.resolveOffsetToDomPoint(e),s=this.resolveOffsetToDomPoint(t),n=window.getSelection();if(!i||!s||!n){this.setSelectionOffsets(e,t);return}try{if(n.removeAllRanges(),e===t){const o=document.createRange();o.setStart(i.node,i.offset),o.collapse(!0),n.addRange(o),this.ensureCaretVisible();return}if(typeof n.extend=="function"){const o=document.createRange();o.setStart(i.node,i.offset),o.collapse(!0),n.addRange(o),n.extend(s.node,s.offset),this.ensureCaretVisible();return}const r=this.createDomRangeFromOffsets(e,t);if(!r)return;n.addRange(r),this.ensureCaretVisible()}catch(r){console.warn("Could not set selection boundary offsets:",r),this.setSelectionOffsets(e,t)}}focus(){this.contentElement.focus(),this.ensureCaretVisible()}blur(){this.contentElement.blur()}setReadOnly(e){this.contentElement.contentEditable=e?"false":"true"}applyTheme(e){Object.entries(e).forEach(([t,i])=>{this.container.style.setProperty(`--${t}`,i)})}scrollToPosition(e){const t=this.lineNumbersElement.children[e.line];t&&t.scrollIntoView({block:"center",behavior:"smooth"})}getScrollTop(){return this.editorContainer.scrollTop}getScrollElement(){return this.editorContainer}setScrollTop(e){this.editorContainer.scrollTop=e}syncTrailingNewlineMarker(e){if(this.contentElement.querySelectorAll(`[${this.trailingNewlineMarkerAttr}]`).forEach(i=>i.remove()),!e)return;const t=document.createElement("span");t.setAttribute(this.trailingNewlineMarkerAttr,"true"),t.setAttribute("aria-hidden","true"),t.contentEditable="false",t.style.cssText=`
55
96
  display: inline-block;
56
97
  width: 0;
57
98
  overflow: hidden;
58
99
  pointer-events: none;
59
100
  user-select: none;
60
- `,t.appendChild(document.createTextNode("​")),this.contentElement.appendChild(t)}ensureCaretVisible(){var e;const t=window.getSelection();if(!t||t.rangeCount===0)return;const i=t.getRangeAt(0).cloneRange();i.collapse(!1);let s=i.getClientRects()[0]||i.getBoundingClientRect();if((!s||s.width===0&&s.height===0)&&t.focusNode instanceof Element?s=t.focusNode.getBoundingClientRect():(!s||s.width===0&&s.height===0)&&(e=t.focusNode)!=null&&e.parentElement&&(s=t.focusNode.parentElement.getBoundingClientRect()),!s)return;const n=this.editorContainer.getBoundingClientRect(),r=12;s.bottom>n.bottom-r?this.editorContainer.scrollTop+=s.bottom-(n.bottom-r):s.top<n.top+r&&(this.editorContainer.scrollTop-=n.top+r-s.top)}destroy(){this.container&&this.container.parentNode&&this.container.parentNode.removeChild(this.container),this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=void 0)}resolveOffsetToDomPoint(e){var t;const i=Math.max(0,e);let s=0;const n=document.createTreeWalker(this.contentElement,NodeFilter.SHOW_TEXT,null);let r=null,o;for(;o=n.nextNode();){const a=o.parentElement;if(a!=null&&a.hasAttribute(this.trailingNewlineMarkerAttr))continue;r=o;const h=o.textContent||"",l=this.buildVisibleToDomMap(h),c=Math.max(0,l.length-1);if(s+c>=i){const d=Math.max(0,i-s),p=l[d]??h.length;return{node:o,offset:p}}s+=c}if(r){const a=((t=r.textContent)==null?void 0:t.length)||0;return{node:r,offset:a}}return null}buildVisibleToDomMap(e){const t=[0];let i=0;for(let s=0;s<e.length;s++){const n=e[s];this.virtualMarkerRegex.test(n)||(i+=1,t[i]=s+1)}return t}}const F=class L{constructor(e,t={}){this.extensions=new Map,this.commands=new Map,this.eventListeners=new Map,this.folds=[],this.currentTheme="default",this.isDestroyed=!1,this.undoStack=[],this.redoStack=[],this.suppressHistory=!1,this.highlightTimeout=null,this.expectingProgrammaticCursor=!1,this.config={value:"",theme:"default",readOnly:!1,tabSize:2,lineWrapping:!1,lineNumbers:!0,...t},this.textModel=new D(this.config.value),this.view=new Z(e),this.setupEventHandlers(),this.config.extensions&&this.config.extensions.forEach(i=>this.addExtension(i)),this.setTheme(this.config.theme),this.view.setReadOnly(this.config.readOnly||!1),this.renderTextWithHighlight(this.textModel.getText()),this.registerBuiltInCommands()}getTextModel(){return this.textModel}getView(){return this.view}getConfig(){return{...this.config}}registerBuiltInCommands(){this.registerCommand("undo",()=>this.undo()),this.registerCommand("redo",()=>this.redo()),this.registerCommand("insertTab",()=>this.insertTab()),this.registerCommand("save",()=>{this.emit("save")})}getKeymapExtension(){return this.extensions.get("keymap")}setupEventHandlers(){const e=this.view.getContentElement();e.addEventListener("input",()=>{const t=this.view.getText(),i=this.textModel.getText();if(t!==i){if(!this.suppressHistory){const s=this.getCursor().position,n=this.textModel.positionToOffset(s),r=this.getSelection();let o,a;r&&(o=this.textModel.positionToOffset(r.start),a=this.textModel.positionToOffset(r.end)),this.undoStack.push({text:i,cursorOffset:n,anchorOffset:o,focusOffset:a}),this.undoStack.length>100&&this.undoStack.shift(),this.redoStack.length=0}this.textModel.setText(t),this.view.syncTrailingNewlineMarkerForText(t),this.highlightTimeout&&clearTimeout(this.highlightTimeout),this.highlightTimeout=setTimeout(()=>{const s=this.view.getText();s!==this.textModel.getText()&&this.textModel.setText(s),this.renderTextWithHighlight(this.textModel.getText(),!1),this.highlightTimeout=null},300),this.updateLineNumbers(),this.emit("change",[{range:this.getFullRange(),text:t,oldText:i}])}}),e.addEventListener("selectionchange",()=>{const t=this.getCursor(),i=this.getSelection();this.emit("cursor",t),i&&this.emit("selection",i)}),e.addEventListener("keydown",t=>{if(this.emit("keydown",t),t.key==="Tab"){this.config.readOnly||this.insertTab(),t.preventDefault(),t.stopPropagation();return}if(t.key==="Enter"){if(!this.config.readOnly){const i=window.getSelection();if(i&&i.rangeCount>0){const s=this.getCursor().position,n=this.textModel.positionToOffset(s),r=this.getSelection();let o,a;r&&(o=this.textModel.positionToOffset(r.start),a=this.textModel.positionToOffset(r.end));const h=r&&o!==void 0&&a!==void 0?Math.min(o,a):n;this.suppressHistory||(this.undoStack.push({text:this.textModel.getText(),cursorOffset:n,anchorOffset:o,focusOffset:a}),this.undoStack.length>100&&this.undoStack.shift(),this.redoStack.length=0);const l=i.getRangeAt(0);l.deleteContents();const c=document.createTextNode(`
61
- `);l.insertNode(c),l.setStartAfter(c),l.collapse(!0),i.removeAllRanges(),i.addRange(l),this.view.ensureCaretVisible();const d=this.view.getText();this.textModel.setText(d),this.view.syncTrailingNewlineMarkerForText(d);const p=Math.min(h+1,this.textModel.getText().length);try{const u=this.textModel.offsetToPosition(p);this.setCursor(u),this.view.ensureCaretVisible()}catch{}this.highlightTimeout&&clearTimeout(this.highlightTimeout),this.highlightTimeout=setTimeout(()=>{this.renderTextWithHighlight(this.textModel.getText(),!1),requestAnimationFrame(()=>{try{const u=this.textModel.offsetToPosition(p);this.setCursor(u),this.view.ensureCaretVisible()}catch{}}),this.highlightTimeout=null},300),this.updateLineNumbers(),this.emit("change",[{range:this.getFullRange(),text:this.getValue(),oldText:""}])}}t.preventDefault(),t.stopPropagation();return}for(const i of this.extensions.values())if(i.onKeyDown&&i.onKeyDown(t)===!1){t.preventDefault(),t.stopPropagation();return}}),e.addEventListener("mousedown",t=>{this.emit("mousedown",t);for(const i of this.extensions.values())if(i.onMouseDown&&i.onMouseDown(t)===!1){t.preventDefault(),t.stopPropagation();return}}),e.addEventListener("focus",()=>{this.emit("focus")}),e.addEventListener("blur",()=>{this.emit("blur")})}updateLineNumbers(){const e=this.textModel.getLineCount();this.view.updateLineNumbers(e)}getFullRange(){return{start:{line:0,column:0},end:{line:this.textModel.getLineCount()-1,column:this.textModel.getLine(this.textModel.getLineCount()-1).length}}}emit(e,...t){const i=this.eventListeners.get(e);i&&i.forEach(s=>s(...t))}getValue(){return this.textModel.getText()}setValue(e){const t=this.textModel.getText();this.textModel.setText(e),this.renderTextWithHighlight(e,!1),this.updateLineNumbers(),this.emit("change",[{range:this.getFullRange(),text:e,oldText:t}])}getState(){return{text:this.getValue(),cursor:this.getCursor(),selection:this.getSelection(),readOnly:this.config.readOnly||!1,theme:this.currentTheme}}getCursor(){const e=this.view.getCursorPosition();return{position:e,anchor:e}}setCursor(e){this.view.setCursorPosition(e),this.emit("cursor",this.getCursor())}getSelection(){return this.view.getSelectionRange()}setSelection(e){this.view.setSelectionRange(e),this.emit("selection",e)}setTheme(e){this.currentTheme=e;const t={"editor-background":e==="dark"?"#1e1e1e":"#ffffff","editor-foreground":e==="dark"?"#f8f9fa":"#1a1a1a","editor-gutter-background":e==="dark"?"#252526":"#f8f9fa","editor-gutter-foreground":e==="dark"?"#858585":"#666666","editor-gutter-border":e==="dark"?"#3e3e42":"#e1e5e9"};this.view.applyTheme(t);const i=this.extensions.get("syntax-highlighting");if(i&&typeof i.setTheme=="function")try{i.setTheme(e==="dark"?"dark":"light"),this.renderTextWithHighlight(this.textModel.getText())}catch(s){console.warn("Error applying theme to syntax-highlighting extension",s)}}setReadOnly(e){this.config.readOnly=e,this.view.setReadOnly(e)}addExtension(e){if(this.extensions.has(e.name))throw new Error(`Extension '${e.name}' already exists`);this.extensions.set(e.name,e),e.setup(this),e.name==="syntax-highlighting"&&typeof e.highlightHTML=="function"&&this.renderTextWithHighlight(this.textModel.getText())}removeExtension(e){const t=this.extensions.get(e);t&&t.destroy&&t.destroy(),this.extensions.delete(e)}executeCommand(e,...t){const i=this.commands.get(e);i?i(this,...t):console.warn(`Command '${e}' not found`)}registerCommand(e,t){this.commands.set(e,t)}search(e,t={}){if(!e)return[];const i={query:e,caseSensitive:!1,wholeWord:!1,regex:!1,...t},s=[],n=this.textModel.getText(),{normalizedText:r,normalizedToRawOffsets:o}=this.buildSearchTextAndOffsetMap(n),a=i.caseSensitive?r:r.toLowerCase(),h=i.caseSensitive?e:e.toLowerCase();if(i.regex){let l;try{l=new RegExp(e,i.caseSensitive?"g":"gi")}catch{return[]}let c;for(;(c=l.exec(r))!==null;){const d=c[0]??"";if(d.length===0){l.lastIndex=c.index+1;continue}const p=c.index,u=c.index+d.length;i.wholeWord&&!this.isWholeWordBoundary(r,p,u)||this.pushSearchResultFromOffsets(s,p,u,r,o)}}else{let l=0,c=a.indexOf(h,l);for(;c!==-1;){const d=c+h.length;!i.wholeWord||this.isWholeWordBoundary(r,c,d)?(this.pushSearchResultFromOffsets(s,c,d,r,o),l=d):l=c+1,c=a.indexOf(h,l)}}return s}pushSearchResultFromOffsets(e,t,i,s,n){const r=n[t]??t,o=n[i]??r,a=this.textModel.offsetToPosition(r),h=this.textModel.offsetToPosition(o);e.push({range:{start:a,end:h},match:s.substring(t,i)})}isWholeWordBoundary(e,t,i){const s=t>0?e[t-1]:"",n=i<e.length?e[i]:"";return!this.isWordChar(s)&&!this.isWordChar(n)}isWordChar(e){return/^[A-Za-z0-9_]$/.test(e)}buildSearchTextAndOffsetMap(e){const t=[],i=[0];let s=0;for(let n=0;n<e.length;n++){const r=e[n];r==="​"||r===L.CURSOR_SENTINEL||(t.push(r),s+=1,i[s]=n+1)}return i[s]=e.length,{normalizedText:t.join(""),normalizedToRawOffsets:i}}replace(e,t){const i=this.getValue();if(!this.suppressHistory){const n=this.getCursor().position,r=this.textModel.positionToOffset(n),o=this.getSelection();let a,h;o&&(a=this.textModel.positionToOffset(o.start),h=this.textModel.positionToOffset(o.end)),this.undoStack.push({text:i,cursorOffset:r,anchorOffset:a,focusOffset:h}),this.undoStack.length>100&&this.undoStack.shift(),this.redoStack.length=0}const s=this.textModel.replaceRange(e,t);this.expectingProgrammaticCursor=!0,this.renderTextWithHighlight(this.getValue(),!1),this.expectingProgrammaticCursor=!1,this.emit("change",[s])}replaceAll(e,t,i={}){const s=this.search(e,i);let n=0;for(let r=s.length-1;r>=0;r--)this.replace(s[r].range,t),n++;return n}fold(e){const t={start:e.start,end:e.end,collapsed:!0,level:0};this.folds.push(t)}unfold(e){this.folds=this.folds.filter(t=>!(t.start.line===e.start.line&&t.end.line===e.end.line))}getFolds(){return[...this.folds]}focus(){this.view.focus()}blur(){this.view.blur()}renderTextWithHighlight(e,t=!0){const i=this.extensions.get("syntax-highlighting");if(i&&typeof i.highlightHTML=="function")try{const s=!t&&!this.expectingProgrammaticCursor;let n,r,o,a;if(t||s){n=this.getSelection();const d=this.getCollapsedSelectionOffsetInEditor();if(d!==void 0)r=d;else{const p=this.getCursor().position;r=this.textModel.positionToOffset(p)}n&&(o=this.textModel.positionToOffset(n.start),a=this.textModel.positionToOffset(n.end))}const h=(t||s)&&!n&&r!==void 0&&this.hasCollapsedSelectionInEditor(),l=h?this.insertSentinelAtOffset(e,r):e,c=i.highlightHTML(l);typeof this.view.setHighlightHTML=="function"?this.view.setHighlightHTML(c):this.view.setHTML(c),this.view.syncTrailingNewlineMarkerForText(e),(t||s)&&requestAnimationFrame(()=>{try{if(h&&this.restoreCursorFromSentinel()){this.view.ensureCaretVisible();return}if(n&&(o!==void 0||a!==void 0)){const d=o!==void 0?o:r,p=a!==void 0?a:r,u=Math.min(d,p),g=Math.max(d,p),f=this.textModel.offsetToPosition(u),y=this.textModel.offsetToPosition(g);this.view.setSelectionRange({start:f,end:y})}else if(r!==void 0){const d=this.textModel.offsetToPosition(r);this.view.setCursorPosition(d)}}catch{}});return}catch(s){console.warn("Syntax highlighting failed, falling back to plain text",s)}this.view.setText(e)}hasCollapsedSelectionInEditor(){const e=window.getSelection();if(!e||e.rangeCount===0||!e.isCollapsed)return!1;const t=e.getRangeAt(0);return this.view.getContentElement().contains(t.commonAncestorContainer)}getCollapsedSelectionOffsetInEditor(){const e=window.getSelection();if(!e||e.rangeCount===0||!e.isCollapsed)return;const t=e.getRangeAt(0),i=this.view.getContentElement();if(!i.contains(t.commonAncestorContainer))return;const s=t.cloneRange();return s.selectNodeContents(i),s.setEnd(t.endContainer,t.endOffset),this.stripVirtualMarkers(s.toString()).length}stripVirtualMarkers(e){return e.replace(/\u200B/g,"").split(L.CURSOR_SENTINEL).join("")}insertSentinelAtOffset(e,t){const i=Math.max(0,Math.min(t,e.length));return e.slice(0,i)+L.CURSOR_SENTINEL+e.slice(i)}restoreCursorFromSentinel(){const e=this.view.getContentElement(),t=window.getSelection(),i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);let s=i.nextNode(),n=null,r=0;for(;s;){const o=s.textContent??"",a=o.indexOf(L.CURSOR_SENTINEL);a!==-1&&(n||(n=s,r=a),s.textContent=o.split(L.CURSOR_SENTINEL).join("")),s=i.nextNode()}if(!n||!t)return!1;try{const o=document.createRange();return o.setStart(n,r),o.collapse(!0),t.removeAllRanges(),t.addRange(o),!0}catch{return!1}}destroy(){if(!this.isDestroyed){this.isDestroyed=!0;for(const e of this.extensions.values())e.destroy&&e.destroy();this.extensions.clear(),this.view.destroy(),this.commands.clear(),this.eventListeners.clear()}}undo(){if(this.undoStack.length===0)return;const e=this.undoStack.pop(),t={text:this.getValue(),cursorOffset:this.textModel.positionToOffset(this.getCursor().position)};this.redoStack.push(t);try{this.suppressHistory=!0,this.expectingProgrammaticCursor=!0;let i,s;typeof e=="string"?i=e:(i=e.text,s=e.cursorOffset),this.setValue(i),requestAnimationFrame(()=>{try{if(s!=null)if(typeof e!="string"&&(e.anchorOffset!==void 0||e.focusOffset!==void 0)){const n=e.anchorOffset!==void 0?e.anchorOffset:s,r=e.focusOffset!==void 0?e.focusOffset:s,o=Math.min(n,r),a=Math.max(n,r),h=this.textModel.offsetToPosition(o),l=this.textModel.offsetToPosition(a);this.setSelection({start:h,end:l})}else{const n=this.textModel.offsetToPosition(s);this.setCursor(n)}}catch{}}),setTimeout(()=>{this.expectingProgrammaticCursor=!1},30)}finally{this.suppressHistory=!1}}redo(){if(this.redoStack.length===0)return;const e=this.redoStack.pop(),t={text:this.getValue(),cursorOffset:this.textModel.positionToOffset(this.getCursor().position)};this.undoStack.push(t);try{this.suppressHistory=!0,this.expectingProgrammaticCursor=!0;let i,s;typeof e=="string"?i=e:(i=e.text,s=e.cursorOffset),this.setValue(i),requestAnimationFrame(()=>{try{if(s!=null)if(typeof e!="string"&&(e.anchorOffset!==void 0||e.focusOffset!==void 0)){const n=e.anchorOffset!==void 0?e.anchorOffset:s,r=e.focusOffset!==void 0?e.focusOffset:s,o=Math.min(n,r),a=Math.max(n,r),h=this.textModel.offsetToPosition(o),l=this.textModel.offsetToPosition(a);this.setSelection({start:h,end:l})}else{const n=this.textModel.offsetToPosition(s);this.setCursor(n)}}catch{}}),setTimeout(()=>{this.expectingProgrammaticCursor=!1},30)}finally{this.suppressHistory=!1}}insertTab(){if(this.config.readOnly)return;const e=this.getCursor().position,t=this.textModel.positionToOffset(e),i=" ".repeat(this.config.tabSize||2),s=this.textModel.insertText(e,i),n=this.textModel.offsetToPosition(this.textModel.positionToOffset(e)+i.length);if(!this.suppressHistory){const r=this.getSelection();let o,a;r&&(o=this.textModel.positionToOffset(r.start),a=this.textModel.positionToOffset(r.end)),this.undoStack.push({text:this.getValue(),cursorOffset:t,anchorOffset:o,focusOffset:a}),this.redoStack.length=0}this.expectingProgrammaticCursor=!0,this.renderTextWithHighlight(this.getValue(),!1),this.setCursor(n),setTimeout(()=>{this.expectingProgrammaticCursor=!1},20),this.emit("change",[s])}insertNewLine(){if(this.config.readOnly)return;const e=this.getCursor().position,t=this.textModel.positionToOffset(e),i=this.textModel.insertText(e,`
62
- `),s=this.textModel.offsetToPosition(this.textModel.positionToOffset(e)+1);if(!this.suppressHistory){const n=this.getSelection();let r,o;n&&(r=this.textModel.positionToOffset(n.start),o=this.textModel.positionToOffset(n.end)),this.undoStack.push({text:this.getValue(),cursorOffset:t,anchorOffset:r,focusOffset:o}),this.redoStack.length=0}this.expectingProgrammaticCursor=!0,this.renderTextWithHighlight(this.getValue(),!1),this.setCursor(s),setTimeout(()=>{this.expectingProgrammaticCursor=!1},20),this.emit("change",[i])}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t)}off(e,t){if(!this.eventListeners.has(e))return;const i=this.eventListeners.get(e);if(t){const s=i.indexOf(t);s!==-1&&i.splice(s,1)}else i.length=0}};F.CURSOR_SENTINEL="";let X=F;class J{constructor(e){this.name="keymap",this.editor=null,this.keymap={},this.isMac=navigator.platform.toUpperCase().indexOf("MAC")>=0,this.keymap=e||this.getDefaultKeymap()}setup(e){this.editor=e}handleKeyDown(e){if(!this.editor)return;const t=this.findMatchingBinding(e);if(t)return this.editor.executeCommand(t.command),e.preventDefault(),e.stopPropagation(),!1}findMatchingBinding(e){const{key:t,ctrlKey:i,altKey:s,shiftKey:n,metaKey:r}=e,o=String(t).toLowerCase(),a=this.keymap[o];if(!a)return null;for(const h of a){const l=h.ctrlKey===void 0||h.ctrlKey===i,c=h.altKey===void 0||h.altKey===s,d=h.shiftKey===void 0||h.shiftKey===n,p=h.metaKey===void 0||h.metaKey===r;if(l&&c&&d&&p)return h}return null}onKeyDown(e){return this.handleKeyDown(e)}getDefaultKeymap(){const e={};return this.addBinding(e,"f",{ctrlKey:!this.isMac,metaKey:this.isMac},"find"),this.addBinding(e,"h",{ctrlKey:!this.isMac,metaKey:this.isMac},"replace"),this.addBinding(e,"f3",{},"findNext"),this.addBinding(e,"f3",{shiftKey:!0},"findPrev"),this.addBinding(e,"g",{ctrlKey:!this.isMac,metaKey:this.isMac},"findNext"),this.addBinding(e,"[",{ctrlKey:!this.isMac,metaKey:this.isMac,shiftKey:!0},"fold"),this.addBinding(e,"]",{ctrlKey:!this.isMac,metaKey:this.isMac,shiftKey:!0},"unfold"),this.addBinding(e,"s",{ctrlKey:!0},"save"),this.addBinding(e,"s",{metaKey:!0},"save"),this.addBinding(e,"z",{ctrlKey:!0},"undo"),this.addBinding(e,"z",{metaKey:!0},"undo"),this.addBinding(e,"y",{ctrlKey:!0},"redo"),this.addBinding(e,"y",{metaKey:!0},"redo"),this.addBinding(e,"z",{ctrlKey:!0,shiftKey:!0},"redo"),this.addBinding(e,"z",{metaKey:!0,shiftKey:!0},"redo"),this.addBinding(e,"tab",{},"insertTab"),this.addBinding(e,"t",{ctrlKey:!this.isMac,metaKey:this.isMac,shiftKey:!0},"toggleTheme"),e}addBinding(e,t,i,s){const n=t.toLowerCase();e[n]||(e[n]=[]),e[n].push({key:n,command:s,...i})}setKeymap(e){this.keymap={...e}}addKeyBinding(e){const t=e.key.toLowerCase();this.keymap[t]||(this.keymap[t]=[]),this.keymap[t]=this.keymap[t].filter(i=>i.command!==e.command),this.keymap[t].push({...e,key:t})}removeKeyBinding(e,t){const i=e.toLowerCase();t?this.keymap[i]&&(this.keymap[i]=this.keymap[i].filter(s=>s.command!==t),this.keymap[i].length===0&&delete this.keymap[i]):delete this.keymap[i]}getKeymap(){return{...this.keymap}}getBindingsForCommand(e){const t=[];for(const i in this.keymap)for(const s of this.keymap[i])s.command===e&&t.push({...s});return t}getPlatformInfo(){return{isMac:this.isMac,platform:navigator.platform}}destroy(){this.keymap={},this.editor=null}}class Y{constructor(){this.name="transaction",this.transactions=[]}setup(e){e.on("change",t=>{const i={changes:t,selection:e.getSelection(),effects:[],annotations:[]};this.transactions.push(i)})}getTransactions(){return this.transactions}destroy(){this.transactions=[]}}class _{constructor(){this.name="line-numbers",this.editor=null,this.lineNumbersElement=null,this.isEnabled=!0}setup(e){this.editor=e,this.createLineNumbers(),e.registerCommand("toggleLineNumbers",()=>{this.toggle()}),e.on("change",()=>{this.updateLineNumbers()}),this.updateLineNumbers()}createLineNumbers(){if(!this.editor)return;const e=this.editor.getView().getLineNumbersElement();e&&(this.lineNumbersElement=e)}updateLineNumbers(){if(!this.lineNumbersElement||!this.editor||!this.isEnabled)return;const e=this.editor.getValue().split(`
63
- `).length,t=Array.from({length:Math.max(e,20)},(i,s)=>s+1);this.lineNumbersElement.innerHTML=t.map(i=>`<div style="height: 21px; line-height: 21px; padding-right: 12px;">${i}</div>`).join("")}toggle(){if(!this.editor)return;this.isEnabled=!this.isEnabled,this.lineNumbersElement&&(this.lineNumbersElement.style.display=this.isEnabled?"block":"none");const e=this.editor.getView().getContentElement();e&&(e.style.marginLeft=this.isEnabled?"60px":"0"),this.updateLineNumbers()}destroy(){this.lineNumbersElement=null,this.editor=null}}class G{constructor(){this.name="theme",this.editor=null,this.currentTheme="dark"}setup(e){this.editor=e,e.registerCommand("setTheme",t=>{this.setTheme(t)}),e.registerCommand("toggleTheme",()=>{this.toggleTheme()}),this.setTheme(this.currentTheme)}setTheme(e){this.editor&&(this.currentTheme=e,this.editor.setTheme(e))}toggleTheme(){const e=this.currentTheme==="dark"?"light":"dark";this.setTheme(e)}getCurrentTheme(){return this.currentTheme}destroy(){this.editor=null}}class ee{constructor(){this.name="read-only",this.editor=null,this.isReadOnly=!1}setup(e){this.editor=e,e.registerCommand("setReadOnly",t=>{this.setReadOnly(t)}),e.registerCommand("toggleReadOnly",()=>{this.toggleReadOnly()}),e.on("keydown",t=>{if(t.ctrlKey&&t.key==="r")return t.preventDefault(),this.toggleReadOnly(),!1})}setReadOnly(e){this.editor&&(this.isReadOnly=e,this.editor.setReadOnly(e))}toggleReadOnly(){this.setReadOnly(!this.isReadOnly)}isCurrentlyReadOnly(){return this.isReadOnly}destroy(){this.editor=null}}let te=0;const W=class m{constructor(e={}){this.name="search",this.editor=null,this.searchUI=null,this.isVisible=!1,this.currentResults=[],this.currentIndex=-1,this.searchDebounceTimer=null,this.liveRefreshTimer=null,this.statusResetTimer=null,this.statusFreezeUntil=0,this.findInput=null,this.replaceInputEl=null,this.statusDiv=null,this.modeDiv=null,this.caseSensitiveInput=null,this.wholeWordInput=null,this.regexInput=null,this.currentQuery="",this.savedCursor=null,this.editorChangeHandler=null,this.searchOptions={caseSensitive:!1,wholeWord:!1,regex:!1},this.trailingMarkerAttr="data-lce-trailing-newline-marker",this.editorContainerSelector='[data-lce-editor-container="true"]',this.highlightId=++te,this.highlightMatchName=`editora-search-match-${this.highlightId}`,this.highlightActiveName=`editora-search-active-${this.highlightId}`,this.highlightStyleId=`editora-search-highlight-style-${this.highlightId}`,this.maxCustomHighlightRanges=2e3,this.virtualMarkerRegex=/[\u200B\uE000]/,this.hasCustomHighlightSupport=!1,this.config={replaceAndFindNext:!0,...e}}setup(e){this.editor=e,this.hasCustomHighlightSupport=this.detectCustomHighlightSupport(),this.hasCustomHighlightSupport&&this.ensureHighlightStyles(),e.registerCommand("find",()=>{this.showSearch()}),e.registerCommand("findNext",()=>{this.findNext()}),e.registerCommand("findPrev",()=>{this.findPrev()}),e.registerCommand("replace",()=>{this.showReplace()}),e.registerCommand("replaceAll",(t,i)=>{this.replaceAll(t,i)}),this.editorChangeHandler=()=>{!this.isVisible||!this.currentQuery||this.scheduleLiveRefresh(!0)},e.on("change",this.editorChangeHandler)}showSearch(){this.editor&&(this.searchUI||this.createSearchUI(),this.isVisible||this.captureSelectionState(),this.isVisible=!0,this.searchUI&&(this.searchUI.style.display="block",this.updateModeHint(!1),this.findInput&&(this.findInput.focus(),this.findInput.select())),this.currentQuery&&this.performSearch(this.currentQuery,!0,!1))}showReplace(){this.showSearch(),this.replaceInputEl&&(this.replaceInputEl.style.display="block",this.replaceInputEl.focus()),this.updateModeHint(!0),this.currentQuery&&this.performSearch(this.currentQuery,!1,!0)}hideSearch(){this.isVisible=!1,this.searchUI&&(this.searchUI.style.display="none"),this.replaceInputEl&&(this.replaceInputEl.style.display="none",this.replaceInputEl.value=""),this.updateModeHint(!1),this.clearHighlights(),this.restoreSelectionState()}createSearchUI(){if(!this.editor)return;const e=this.editor.getView().getContentElement(),t=e.closest(this.editorContainerSelector),i=e.closest(".rte-source-editor-modal")||t||e.parentElement;if(!i)return;window.getComputedStyle(i).position==="static"&&(i.style.position="relative"),this.searchUI=document.createElement("div"),this.searchUI.className=m.css.root,this.searchUI.style.display="none",this.searchUI.innerHTML=`
101
+ `,t.appendChild(document.createTextNode("​")),this.contentElement.appendChild(t)}ensureCaretVisible(){const e=window.getSelection();if(!e||e.rangeCount===0)return;const t=this.getCaretClientRect(e);if(!t)return;const i=this.editorContainer.getBoundingClientRect(),s=12;t.bottom>i.bottom-s?this.editorContainer.scrollTop+=t.bottom-(i.bottom-s):t.top<i.top+s&&(this.editorContainer.scrollTop-=i.top+s-t.top)}destroy(){this.clearDecorations(),this.container&&(this.container.innerHTML=""),this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=void 0)}resolveOffsetToDomPoint(e){const t=Math.max(0,e);let i=0;const s=Array.from(this.contentElement.childNodes);for(let n=0;n<s.length;n++){const r=s[n];if(r instanceof Text){const o=r.textContent||"",l=this.buildVisibleToDomMap(o),a=Math.max(0,l.length-1);if(i+a>=t){const h=Math.max(0,t-i),d=l[h]??o.length;return{node:r,offset:d}}i+=a;continue}if(r instanceof HTMLElement&&!r.hasAttribute(this.trailingNewlineMarkerAttr)&&r.hasAttribute(this.foldPlaceholderAttr)){const o=this.getFoldPlaceholderSource(r).length;if(i+o>=t){const l=t-i;return{node:this.contentElement,offset:l<=o/2?n:n+1}}i+=o}}return{node:this.contentElement,offset:this.contentElement.childNodes.length}}getDomRangeFromClientPoint(e,t){const i=document;if(typeof i.caretPositionFromPoint=="function"){const s=i.caretPositionFromPoint(e,t);if(s?.offsetNode){const n=document.createRange();try{return n.setStart(s.offsetNode,s.offset),n.collapse(!0),n}catch{return null}}}return typeof i.caretRangeFromPoint=="function"?i.caretRangeFromPoint(e,t):null}buildVisibleToDomMap(e){const t=[0];let i=0;for(let s=0;s<e.length;s++){const n=e[s];this.virtualMarkerRegex.test(n)||(i+=1,t[i]=s+1)}return t}isNodeInsideContent(e){return e===this.contentElement||this.contentElement.contains(e)}getCaretClientRect(e){const t=e.getRangeAt(0).cloneRange();t.collapse(!1);const i=this.getUsableRangeRect(t);if(i)return i;const s=e.focusNode,n=e.focusOffset;if(s instanceof Text){const o=s.textContent?.length??0,l=document.createRange();if(n<o){l.setStart(s,n),l.setEnd(s,Math.min(o,n+1));const a=this.getUsableRangeRect(l);if(a)return a}if(n>0){l.setStart(s,n-1),l.setEnd(s,n);const a=this.getUsableRangeRect(l);if(a)return a}}const r=s instanceof Element?s:s?.parentElement??null;if(r&&r!==this.contentElement&&r!==this.editorContainer&&this.contentElement.contains(r)){const o=r.getBoundingClientRect();if(this.isUsableRect(o))return o}return null}getUsableRangeRect(e){const t=Array.from(e.getClientRects());for(let s=0;s<t.length;s++)if(this.isUsableRect(t[s]))return t[s];const i=e.getBoundingClientRect();return this.isUsableRect(i)?i:null}isUsableRect(e){return!!e&&Number.isFinite(e.top)&&Number.isFinite(e.bottom)&&(e.width>0||e.height>0)}stripVirtualMarkers(e){return e.replace(this.virtualMarkerGlobalRegex,"")}clearHighlightOverlay(){!this.highlightOverlayActive&&!this.lastHighlightHTML||(this.highlightElement.innerHTML="",this.highlightElement.style.visibility="hidden",this.lastHighlightHTML="",this.highlightOverlayActive=!1,this.contentElement.style.color="inherit",this.contentElement.style.WebkitTextFillColor="currentcolor")}serializeContentToSource(){let e="";const t=Array.from(this.contentElement.childNodes);for(const i of t){if(i instanceof Text){e+=this.stripVirtualMarkers(i.textContent||"");continue}if(i instanceof HTMLElement&&!i.hasAttribute(this.trailingNewlineMarkerAttr)){if(i.hasAttribute(this.foldPlaceholderAttr)){e+=this.getFoldPlaceholderSource(i);continue}e+=this.stripVirtualMarkers(i.textContent||"")}}return e}sourceOffsetFromBoundary(e,t){let i=0;const s=Array.from(this.contentElement.childNodes);if(e===this.contentElement){for(let n=0;n<Math.min(t,s.length);n++)i+=this.getSourceLength(s[n]);return i}for(let n=0;n<s.length;n++){const r=s[n];if(r===e){if(r instanceof Text)return i+this.stripVirtualMarkers((r.textContent||"").slice(0,t)).length;if(r instanceof HTMLElement){if(r.hasAttribute(this.foldPlaceholderAttr))return i+this.getFoldPlaceholderBoundaryOffset(r,r,t);const o=Array.from(r.childNodes);for(let l=0;l<Math.min(t,o.length);l++)i+=this.getSourceLength(o[l]);return i}}if(r instanceof HTMLElement&&r.contains(e))return r.hasAttribute(this.foldPlaceholderAttr)?i+this.getFoldPlaceholderBoundaryOffset(r,e,t):i+this.sourceOffsetWithinNode(r,e,t);i+=this.getSourceLength(r)}return i}sourceOffsetWithinNode(e,t,i){let s=0;const n=Array.from(e.childNodes);if(t===e){for(let r=0;r<Math.min(i,n.length);r++)s+=this.getSourceLength(n[r]);return s}for(let r=0;r<n.length;r++){const o=n[r];if(o===t){if(o instanceof Text)return s+this.stripVirtualMarkers((o.textContent||"").slice(0,i)).length;if(o instanceof HTMLElement){if(o.hasAttribute(this.foldPlaceholderAttr))return s+this.getFoldPlaceholderBoundaryOffset(o,o,i);const l=Array.from(o.childNodes);for(let a=0;a<Math.min(i,l.length);a++)s+=this.getSourceLength(l[a]);return s}}if(o instanceof HTMLElement&&o.contains(t))return o.hasAttribute(this.foldPlaceholderAttr)?s+this.getFoldPlaceholderBoundaryOffset(o,t,i):s+this.sourceOffsetWithinNode(o,t,i);s+=this.getSourceLength(o)}return s}getSourceLength(e){if(e instanceof Text)return this.stripVirtualMarkers(e.textContent||"").length;if(!(e instanceof HTMLElement)||e.hasAttribute(this.trailingNewlineMarkerAttr))return 0;if(e.hasAttribute(this.foldPlaceholderAttr))return this.getFoldPlaceholderSource(e).length;let t=0;return e.childNodes.forEach(i=>{t+=this.getSourceLength(i)}),t}renderLineDecorations(e){const t=[...e].filter(n=>Number.isFinite(n.line)&&n.line>=0).sort((n,r)=>n.line-r.line||n.id.localeCompare(r.id)),i=t.map(n=>`${n.id}:${n.line}:${n.className||""}:${this.serializeStyleObject(n.style)}`).join("|");if(i===this.lastLineDecorationSnapshot||(this.lineDecorationsElement.innerHTML="",this.lastLineDecorationSnapshot=i,t.length===0))return;const s=document.createDocumentFragment();for(const n of t){const r=document.createElement("div");r.className=this.joinClassNames("lce-decoration lce-decoration-line",n.className),r.setAttribute("data-decoration-id",n.id),r.setAttribute("data-decoration-line",String(n.line)),r.style.cssText=this.joinStyleFragments(["position: absolute",`top: ${n.line*this.lineHeight}px`,`height: ${this.lineHeight}px`,"left: 12px","right: 12px","border-radius: 3px",this.serializeStyleObject(n.style)]),s.appendChild(r)}this.lineDecorationsElement.appendChild(s)}renderGutterDecorations(e){const t=[...e].filter(n=>Number.isFinite(n.line)&&n.line>=0).sort((n,r)=>n.line-r.line||n.id.localeCompare(r.id)),i=t.map(n=>`${n.id}:${n.line}:${n.label||""}:${n.title||""}:${n.className||""}:${this.serializeStyleObject(n.style)}`).join("|");if(i===this.lastGutterDecorationSnapshot||(this.gutterDecorationsElement.innerHTML="",this.lastGutterDecorationSnapshot=i,t.length===0))return;const s=document.createDocumentFragment();for(const n of t){const r=document.createElement("div");r.className=this.joinClassNames("lce-decoration lce-decoration-gutter",n.className),r.setAttribute("data-decoration-id",n.id),r.setAttribute("data-decoration-line",String(n.line)),r.style.cssText=this.joinStyleFragments(["position: absolute",`top: ${n.line*this.lineHeight}px`,`height: ${this.lineHeight}px`,"left: 0","right: 0","display: flex","align-items: center","justify-content: flex-end","padding-right: 4px","box-sizing: border-box",this.serializeStyleObject(n.style)]),n.title&&(r.title=n.title),r.textContent=n.label||"",s.appendChild(r)}this.gutterDecorationsElement.appendChild(s)}joinClassNames(...e){return e.filter(Boolean).join(" ").trim()}joinStyleFragments(e){return e.filter(t=>!!t&&t.trim().length>0).map(t=>{const i=t.trim();return i.endsWith(";")?i:`${i};`}).join(" ")}serializeStyleObject(e){return e?Object.entries(e).filter(([,t])=>typeof t=="string"&&t.length>0).map(([t,i])=>`${this.toKebabCase(t)}: ${i}`).join("; "):""}toKebabCase(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}offsetToPositionInText(e,t){const i=Math.max(0,Math.min(e,t.length)),s=t.slice(0,i).split(`
102
+ `);return{line:s.length-1,column:s[s.length-1].length}}positionToTextOffset(e,t){const i=t.split(`
103
+ `),s=Math.max(0,Math.min(e.line,i.length-1)),n=Math.max(0,Math.min(e.column,i[s]?.length||0));let r=0;for(let o=0;o<s;o++)r+=i[o].length+1;return r+n}getFoldPlaceholderSource(e){const t=e.getAttribute(this.foldPlaceholderAttr),i=this.getFoldPlaceholderSources();return t&&i.has(t)?i.get(t)||"":e.__lceFoldHiddenText||""}getFoldPlaceholderSources(){return this.contentElement.__lceFoldPlaceholderSources||new Map}getFoldPlaceholderBoundaryOffset(e,t,i){const s=this.getFoldPlaceholderSource(e).length,n=this.stripVirtualMarkers(e.textContent||"").length;if(s===0||n===0)return 0;const r=document.createRange();r.selectNodeContents(e);try{r.setEnd(t,i)}catch{return 0}return this.stripVirtualMarkers(r.toString()).length<=n/2?0:s}setFoldPlaceholderSources(e){this.contentElement.__lceFoldPlaceholderSources=e}}let X=0;const U=class O{constructor(e,t={}){this.extensions=new Map,this.commands=new Map,this.eventListeners=new Map,this.folds=[],this.currentTheme="default",this.isDestroyed=!1,this.undoStack=[],this.redoStack=[],this.suppressHistory=!1,this.highlightTimeout=null,this.expectingProgrammaticCursor=!1,this.lastKnownCursor={line:0,column:0},this.editorInstanceId=++X,this.decorationHighlightStyleId=`editora-decoration-style-${this.editorInstanceId}`,this.decorationHighlightLimit=1e3,this.decorationLayers=new Map,this.inlineDecorationHighlightNames=new Set,this.decorationRenderRaf=null,this.decorationMutationObserver=null,this.hasCustomDecorationHighlightSupport=!1,this.lastProgrammaticClipboardInsertAt=0,this.config={value:"",theme:"default",readOnly:!1,tabSize:2,lineWrapping:!1,lineNumbers:!0,...t},this.textModel=new z(this.config.value),this.view=new Q(e),this.view.setTabSize(this.config.tabSize||2),this.view.setLineWrapping(!!this.config.lineWrapping),this.view.setLineNumbersVisible(this.config.lineNumbers!==!1),this.hasCustomDecorationHighlightSupport=this.detectCustomHighlightSupport(),this.observeDecorationRelevantMutations(),this.setupEventHandlers(),this.config.extensions&&this.config.extensions.forEach(i=>this.addExtension(i)),this.setTheme(this.config.theme),this.view.setReadOnly(this.config.readOnly||!1),this.renderTextWithHighlight(this.textModel.getText()),this.registerBuiltInCommands()}getTextModel(){return this.textModel}getView(){return this.view}getConfig(){return{...this.config}}registerBuiltInCommands(){this.registerCommand("undo",()=>this.undo()),this.registerCommand("redo",()=>this.redo()),this.registerCommand("insertTab",()=>this.insertTab()),this.registerCommand("save",()=>{this.emit("save")})}getKeymapExtension(){return this.extensions.get("keymap")}setupEventHandlers(){const e=this.view.getContentElement();e.addEventListener("beforeinput",t=>{if(this.suppressHistory||this.config.readOnly){this.pendingInputSnapshot=void 0;return}if(t.inputType==="insertFromPaste"||t.inputType==="insertFromPasteAsQuotation"||t.inputType==="insertFromDrop"){const i=t.dataTransfer,s=this.getPlainTextFromDataTransfer(i);if(s.length===0||(t.preventDefault(),this.pendingInputSnapshot=void 0,Date.now()-this.lastProgrammaticClipboardInsertAt<80))return;this.insertClipboardText(s);return}if(t.inputType==="insertParagraph"||t.inputType==="insertLineBreak"){t.preventDefault(),this.pendingInputSnapshot=void 0,this.insertNewLine();return}if(t.inputType==="deleteContentBackward"||t.inputType==="deleteWordBackward"){t.preventDefault(),this.pendingInputSnapshot=void 0,this.deleteBackward();return}if(t.inputType==="deleteContentForward"||t.inputType==="deleteWordForward"){t.preventDefault(),this.pendingInputSnapshot=void 0,this.deleteForward();return}if(t.inputType==="deleteByCut"){t.preventDefault(),this.pendingInputSnapshot=void 0,this.deleteSelection();return}if(t.inputType==="insertText"&&typeof t.data=="string"&&!t.isComposing){t.preventDefault(),this.pendingInputSnapshot=void 0,this.replaceSelectionWithText(t.data);return}this.pendingInputSnapshot=this.captureHistorySnapshot()}),e.addEventListener("paste",t=>{if(this.config.readOnly){t.preventDefault();return}if(Date.now()-this.lastProgrammaticClipboardInsertAt<80){t.preventDefault();return}const i=this.getPlainTextFromDataTransfer(t.clipboardData);i.length!==0&&(t.preventDefault(),this.insertClipboardText(i))}),e.addEventListener("input",()=>{const t=this.view.getText(),i=this.textModel.getText();t!==i?(this.suppressHistory||this.pushUndoSnapshot(this.pendingInputSnapshot??this.captureHistorySnapshot(i)),this.pendingInputSnapshot=void 0,this.textModel.setText(t),this.view.syncTrailingNewlineMarkerForText(t),this.hasRenderedFoldPlaceholders()?this.clearPendingHighlightRender():(this.clearPendingHighlightRender(),this.highlightTimeout=setTimeout(()=>{const s=this.view.getText();s!==this.textModel.getText()&&this.textModel.setText(s),this.renderTextWithHighlight(this.textModel.getText(),!1),this.highlightTimeout=null},300)),this.updateLineNumbers(),this.emit("change",[{range:this.getFullRange(),text:t,oldText:i}])):this.pendingInputSnapshot=void 0}),this.documentSelectionChangeHandler=()=>{const t=this.syncSelectionCacheFromView();if(!t.isInEditor)return;const i=t.cursor??this.lastKnownCursor;this.emit("cursor",{position:i,anchor:t.range?.start??i}),this.emit("selection",t.isCollapsed?void 0:t.range)},document.addEventListener("selectionchange",this.documentSelectionChangeHandler),e.addEventListener("keydown",t=>{this.emit("keydown",t);const i=Array.from(this.extensions.values()).reverse();for(const s of i)if(s.onKeyDown&&s.onKeyDown(t)===!1){t.preventDefault(),t.stopPropagation();return}if(t.key==="Tab"&&!this.config.readOnly){this.insertTab(),t.preventDefault(),t.stopPropagation();return}if(t.key==="Backspace"&&!this.config.readOnly){this.deleteBackward(),t.preventDefault(),t.stopPropagation();return}if(t.key==="Delete"&&!this.config.readOnly){this.deleteForward(),t.preventDefault(),t.stopPropagation();return}if(t.key==="Enter"&&!this.config.readOnly){this.insertNewLine(),t.preventDefault(),t.stopPropagation();return}}),e.addEventListener("mousedown",t=>{this.emit("mousedown",t);const i=Array.from(this.extensions.values()).reverse();for(const s of i)if(s.onMouseDown&&s.onMouseDown(t)===!1){t.preventDefault(),t.stopPropagation();return}}),e.addEventListener("contextmenu",t=>{this.emit("contextmenu",t);const i=Array.from(this.extensions.values()).reverse();for(const s of i)if(s.onContextMenu&&s.onContextMenu(t)===!1){t.preventDefault(),t.stopPropagation();return}}),e.addEventListener("focus",()=>{this.emit("focus")}),e.addEventListener("blur",()=>{this.emit("blur")})}updateLineNumbers(){const e=this.textModel.getLineCount();this.view.updateLineNumbers(e)}getFullRange(){return{start:{line:0,column:0},end:{line:this.textModel.getLineCount()-1,column:this.textModel.getLine(this.textModel.getLineCount()-1).length}}}emit(e,...t){const i=this.eventListeners.get(e);i&&i.forEach(s=>s(...t))}getValue(){return this.textModel.getText()}setValue(e){const t=this.textModel.getText();this.textModel.setText(e),this.renderTextWithHighlight(e,!1),this.updateLineNumbers(),this.emit("change",[{range:this.getFullRange(),text:e,oldText:t}])}getState(){return{text:this.getValue(),cursor:this.getCursor(),selection:this.getSelection(),readOnly:this.config.readOnly||!1,theme:this.currentTheme}}getCursor(){const e=this.syncSelectionCacheFromView(),t=e.cursor??this.lastKnownCursor;return{position:t,anchor:e.range?.start??t}}setCursor(e){const t=this.textModel.getText(),i=this.clampPositionToText(e,t),s=this.positionToOffsetInText(i,t);this.lastKnownCursor=i,this.lastKnownSelection=void 0,this.view.setSelectionOffsets(s),this.emit("cursor",this.getCursor())}getSelection(){const e=this.syncSelectionCacheFromView();if(!(!e.isInEditor||e.isCollapsed))return e.range}setSelection(e){const t=this.textModel.getText(),i=this.normalizeRange({start:this.clampPositionToText(e.start,t),end:this.clampPositionToText(e.end,t)}),s=this.positionToOffsetInText(i.start,t),n=this.positionToOffsetInText(i.end,t);this.lastKnownSelection=i,this.lastKnownCursor=i.end,this.view.setSelectionOffsets(s,n),this.emit("selection",i)}setTheme(e){this.currentTheme=e;const t={"editor-background":e==="dark"?"#1e1e1e":"#ffffff","editor-foreground":e==="dark"?"#f8f9fa":"#1a1a1a","editor-gutter-background":e==="dark"?"#252526":"#f8f9fa","editor-gutter-foreground":e==="dark"?"#858585":"#666666","editor-gutter-border":e==="dark"?"#3e3e42":"#e1e5e9"};this.view.applyTheme(t);const i=this.extensions.get("syntax-highlighting");if(i&&typeof i.setTheme=="function")try{i.setTheme(e==="dark"?"dark":"light"),this.renderTextWithHighlight(this.textModel.getText())}catch(s){console.warn("Error applying theme to syntax-highlighting extension",s)}}setReadOnly(e){this.config.readOnly=e,this.view.setReadOnly(e)}addExtension(e){if(this.extensions.has(e.name))throw new Error(`Extension '${e.name}' already exists`);this.extensions.set(e.name,e),e.setup(this),e.name==="syntax-highlighting"&&typeof e.highlightHTML=="function"&&this.renderTextWithHighlight(this.textModel.getText())}removeExtension(e){const t=this.extensions.get(e);t&&t.destroy&&t.destroy(),this.extensions.delete(e)}executeCommand(e,...t){const i=this.commands.get(e);i?i(...t):console.warn(`Command '${e}' not found`)}registerCommand(e,t){this.commands.set(e,t)}setDecorations(e,t){const i=e.trim();if(!i)throw new Error("Decoration layer name must not be empty");if(!Array.isArray(t)||t.length===0){this.decorationLayers.delete(i),this.scheduleDecorationRender();return}this.decorationLayers.set(i,t.map(s=>this.cloneDecoration(s))),this.scheduleDecorationRender()}clearDecorations(e){typeof e=="string"?this.decorationLayers.delete(e.trim()):this.decorationLayers.clear(),this.scheduleDecorationRender()}getDecorations(e){if(typeof e=="string")return(this.decorationLayers.get(e.trim())||[]).map(i=>this.cloneDecoration(i));const t=[];for(const i of this.decorationLayers.values())t.push(...i.map(s=>this.cloneDecoration(s)));return t}search(e,t={}){if(!e)return[];const i={query:e,caseSensitive:!1,wholeWord:!1,regex:!1,...t},s=[],n=this.textModel.getText(),{normalizedText:r,normalizedToRawOffsets:o}=this.buildSearchTextAndOffsetMap(n),l=i.caseSensitive?r:r.toLowerCase(),a=i.caseSensitive?e:e.toLowerCase();if(i.regex){let h;try{h=new RegExp(e,i.caseSensitive?"g":"gi")}catch{return[]}let d;for(;(d=h.exec(r))!==null;){const c=d[0]??"";if(c.length===0){h.lastIndex=d.index+1;continue}const g=d.index,u=d.index+c.length;i.wholeWord&&!this.isWholeWordBoundary(r,g,u)||this.pushSearchResultFromOffsets(s,g,u,r,o)}}else{let h=0,d=l.indexOf(a,h);for(;d!==-1;){const c=d+a.length;!i.wholeWord||this.isWholeWordBoundary(r,d,c)?(this.pushSearchResultFromOffsets(s,d,c,r,o),h=c):h=d+1,d=l.indexOf(a,h)}}return s}pushSearchResultFromOffsets(e,t,i,s,n){const r=n[t]??t,o=n[i]??r,l=this.textModel.offsetToPosition(r),a=this.textModel.offsetToPosition(o);e.push({range:{start:l,end:a},match:s.substring(t,i)})}isWholeWordBoundary(e,t,i){const s=t>0?e[t-1]:"",n=i<e.length?e[i]:"";return!this.isWordChar(s)&&!this.isWordChar(n)}isWordChar(e){return/^[A-Za-z0-9_]$/.test(e)}buildSearchTextAndOffsetMap(e){const t=[],i=[0];let s=0;for(let n=0;n<e.length;n++){const r=e[n];r==="​"||r===O.CURSOR_SENTINEL||(t.push(r),s+=1,i[s]=n+1)}return i[s]=e.length,{normalizedText:t.join(""),normalizedToRawOffsets:i}}replace(e,t){const i=this.getValue();this.suppressHistory||this.pushUndoSnapshot(this.captureHistorySnapshot(i));const s=this.textModel.replaceRange(e,t);this.expectingProgrammaticCursor=!0,this.renderTextWithHighlight(this.getValue(),!1),this.expectingProgrammaticCursor=!1,this.emit("change",[s])}replaceAll(e,t,i={}){const s=this.search(e,i);let n=0;for(let r=s.length-1;r>=0;r--)this.replace(s[r].range,t),n++;return n}fold(e){this.clearPendingHighlightRender();const t=this.normalizeRange(e);if(t.start.line===t.end.line&&t.start.column===t.end.column)return;const i=this.folds.findIndex(n=>this.isSameFoldRange(n,t)),s={start:t.start,end:t.end,collapsed:!0,level:0};i!==-1?this.folds[i]=s:(this.folds.push(s),this.folds.sort((n,r)=>this.comparePositions(n.start,r.start)))}unfold(e){this.clearPendingHighlightRender();const t=this.normalizeRange(e);this.folds=this.folds.filter(i=>!this.isSameFoldRange(i,t))}getFolds(){return[...this.folds]}focus(){this.view.focus()}blur(){this.view.blur()}renderTextWithHighlight(e,t=!0){const i=this.extensions.get("syntax-highlighting");if(i&&typeof i.highlightHTML=="function")try{if(typeof this.view.setHighlightHTML=="function"){const u=this.view.getContentElement();(u.querySelector("[data-lce-fold-placeholder]")||u.textContent!==e)&&this.view.setText(e);const p=typeof i.highlight=="function"?i.highlight(e):i.highlightHTML(e);this.view.setHighlightHTML(p),this.view.syncTrailingNewlineMarkerForText(e),this.scheduleDecorationRender();return}const s=!t&&!this.expectingProgrammaticCursor;let n,r,o,l;const a=this.view.getSelectionState(),h=a.isInEditor&&!!a.cursor;(t||s)&&h&&(n=a.isCollapsed?void 0:a.range,r=this.textModel.positionToOffset(a.cursor),n&&(o=this.textModel.positionToOffset(n.start),l=this.textModel.positionToOffset(n.end)));const d=h&&(t||s)&&!n&&r!==void 0&&this.hasCollapsedSelectionInEditor(),c=d?this.insertSentinelAtOffset(e,r):e,g=typeof i.highlight=="function"?i.highlight(c):i.highlightHTML(c);typeof this.view.setHighlightHTML=="function"?this.view.setHighlightHTML(g):this.view.setHTML(g),this.view.syncTrailingNewlineMarkerForText(e),(t||s)&&h&&requestAnimationFrame(()=>{try{if(d&&this.restoreCursorFromSentinel()){this.view.ensureCaretVisible();return}if(n&&(o!==void 0||l!==void 0)){const u=o!==void 0?o:r,p=l!==void 0?l:r,f=Math.min(u,p),b=Math.max(u,p),x=this.textModel.offsetToPosition(f),E=this.textModel.offsetToPosition(b);this.view.setSelectionRange({start:x,end:E})}else if(r!==void 0){const u=this.textModel.offsetToPosition(r);this.view.setCursorPosition(u)}}catch{}}),this.scheduleDecorationRender();return}catch(s){console.warn("Syntax highlighting failed, falling back to plain text",s)}this.view.setText(e),this.scheduleDecorationRender()}hasCollapsedSelectionInEditor(){const e=window.getSelection();if(!e||e.rangeCount===0||!e.isCollapsed)return!1;const t=e.getRangeAt(0);return this.view.getContentElement().contains(t.commonAncestorContainer)}getCollapsedSelectionOffsetInEditor(){const e=window.getSelection();if(!e||e.rangeCount===0||!e.isCollapsed)return;const t=e.getRangeAt(0),i=this.view.getContentElement();if(!i.contains(t.commonAncestorContainer))return;const s=t.cloneRange();return s.selectNodeContents(i),s.setEnd(t.endContainer,t.endOffset),this.stripVirtualMarkers(s.toString()).length}stripVirtualMarkers(e){return e.replace(/\u200B/g,"").split(O.CURSOR_SENTINEL).join("")}insertSentinelAtOffset(e,t){const i=Math.max(0,Math.min(t,e.length));return e.slice(0,i)+O.CURSOR_SENTINEL+e.slice(i)}restoreCursorFromSentinel(){const e=this.view.getContentElement(),t=window.getSelection(),i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);let s=i.nextNode(),n=null,r=0;for(;s;){const o=s.textContent??"",l=o.indexOf(O.CURSOR_SENTINEL);l!==-1&&(n||(n=s,r=l),s.textContent=o.split(O.CURSOR_SENTINEL).join("")),s=i.nextNode()}if(!n||!t)return!1;try{const o=document.createRange();return o.setStart(n,r),o.collapse(!0),t.removeAllRanges(),t.addRange(o),!0}catch{return!1}}destroy(){if(!this.isDestroyed){this.isDestroyed=!0,this.highlightTimeout&&(clearTimeout(this.highlightTimeout),this.highlightTimeout=null),this.pendingInputSnapshot=void 0,this.documentSelectionChangeHandler&&(document.removeEventListener("selectionchange",this.documentSelectionChangeHandler),this.documentSelectionChangeHandler=void 0),this.decorationRenderRaf!==null&&typeof cancelAnimationFrame=="function"&&(cancelAnimationFrame(this.decorationRenderRaf),this.decorationRenderRaf=null),this.decorationMutationObserver?.disconnect(),this.decorationMutationObserver=null,this.clearInlineDecorationHighlights(!0),this.decorationLayers.clear(),this.view.clearDecorations();for(const e of this.extensions.values())e.destroy&&e.destroy();this.extensions.clear(),this.view.destroy(),this.commands.clear(),this.eventListeners.clear()}}undo(){if(this.undoStack.length===0)return;const e=this.undoStack.pop(),t=this.captureHistorySnapshot();this.pushSnapshot(this.redoStack,t);try{this.suppressHistory=!0,this.expectingProgrammaticCursor=!0,this.restoreHistorySnapshot(e),setTimeout(()=>{this.expectingProgrammaticCursor=!1},30)}finally{this.suppressHistory=!1}}redo(){if(this.redoStack.length===0)return;const e=this.redoStack.pop(),t=this.captureHistorySnapshot();this.pushSnapshot(this.undoStack,t);try{this.suppressHistory=!0,this.expectingProgrammaticCursor=!0,this.restoreHistorySnapshot(e),setTimeout(()=>{this.expectingProgrammaticCursor=!1},30)}finally{this.suppressHistory=!1}}insertTab(){if(this.config.readOnly)return;const e=" ".repeat(this.config.tabSize||2);this.replaceSelectionWithText(e)}insertNewLine(){this.config.readOnly||this.replaceSelectionWithText(`
104
+ `)}deleteBackward(){this.config.readOnly||this.deleteUsingDirection("backward")}deleteForward(){this.config.readOnly||this.deleteUsingDirection("forward")}deleteSelection(){if(this.config.readOnly)return;const e=this.textModel.getText(),{startOffset:t,endOffset:i}=this.getActiveSelectionOffsets(e),s=Math.min(t,i),n=Math.max(t,i);s!==n&&this.replaceOffsetsWithText(s,n,"")}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t)}off(e,t){if(!this.eventListeners.has(e))return;const i=this.eventListeners.get(e);if(t){const s=i.indexOf(t);s!==-1&&i.splice(s,1)}else i.length=0}normalizeRange(e){return this.comparePositions(e.start,e.end)<=0?e:{start:e.end,end:e.start}}comparePositions(e,t){return e.line!==t.line?e.line-t.line:e.column-t.column}captureHistorySnapshot(e=this.textModel.getText()){const t=this.view.getSelectionState(),i=t.isInEditor&&!t.isCollapsed?t.range:void 0,s=t.isInEditor&&t.cursor?t.cursor:void 0,n=i??this.lastKnownSelection,r=s??this.lastKnownCursor,o=this.clampPositionToText(r,e),l={text:e,cursorOffset:this.positionToOffsetInText(o,e)};if(n){const a=this.clampPositionToText(n.start,e),h=this.clampPositionToText(n.end,e);l.anchorOffset=this.positionToOffsetInText(a,e),l.focusOffset=this.positionToOffsetInText(h,e)}return l}restoreHistorySnapshot(e){this.setValue(e.text),requestAnimationFrame(()=>{try{if(e.anchorOffset!==void 0&&e.focusOffset!==void 0&&e.anchorOffset!==e.focusOffset){const t=Math.min(e.anchorOffset,e.focusOffset),i=Math.max(e.anchorOffset,e.focusOffset);this.setSelection({start:this.textModel.offsetToPosition(t),end:this.textModel.offsetToPosition(i)});return}this.setCursor(this.textModel.offsetToPosition(e.cursorOffset))}catch{}})}pushUndoSnapshot(e){this.pushSnapshot(this.undoStack,e),this.redoStack.length=0}pushSnapshot(e,t){e.push(t),e.length>100&&e.shift()}clampPositionToText(e,t){const i=t.split(`
105
+ `),s=Math.max(0,Math.min(e.line,i.length-1)),n=Math.max(0,Math.min(e.column,i[s]?.length??0));return{line:s,column:n}}positionToOffsetInText(e,t){const i=t.split(`
106
+ `),s=this.clampPositionToText(e,t);let n=0;for(let r=0;r<s.line;r++)n+=(i[r]?.length??0)+1;return n+s.column}clearPendingHighlightRender(){this.highlightTimeout&&(clearTimeout(this.highlightTimeout),this.highlightTimeout=null)}hasRenderedFoldPlaceholders(){return!!this.view.getContentElement().querySelector("[data-lce-fold-placeholder]")}replaceSelectionWithText(e){const t=e.replace(/\r\n?/g,`
107
+ `),i=this.textModel.getText(),{startOffset:s,endOffset:n}=this.getActiveSelectionOffsets(i),r=Math.max(0,Math.min(s,n)),o=Math.max(0,Math.max(s,n));return this.replaceOffsetsWithText(r,o,t)}insertClipboardText(e){this.pendingInputSnapshot=this.captureHistorySnapshot(),this.lastProgrammaticClipboardInsertAt=Date.now(),this.replaceSelectionWithText(this.normalizeClipboardText(e))}normalizeClipboardText(e){return e.replace(/\r\n?/g,`
108
+ `).replace(/\u00a0/g," ")}getPlainTextFromDataTransfer(e){if(!e)return"";const t=e.getData("text/plain");if(t)return t;const i=e.getData("text/html");return i?this.htmlClipboardToPlainText(i):""}htmlClipboardToPlainText(e){const t=document.implementation.createHTMLDocument("");t.body.innerHTML=e;const i=new Set(["ADDRESS","ARTICLE","ASIDE","BLOCKQUOTE","BR","DD","DIV","DL","DT","FIGCAPTION","FIGURE","FOOTER","H1","H2","H3","H4","H5","H6","HEADER","HR","LI","MAIN","NAV","OL","P","PRE","SECTION","TABLE","TR","UL"]),s=o=>{for(let l=o.length-1;l>=0;l--){const a=o[l]??"";if(a.length!==0)return a.endsWith(`
109
+ `)}return!1},n=(o,l)=>{if(o instanceof Text){l.push(o.data);return}if(!(o instanceof HTMLElement)){o.childNodes.forEach(h=>n(h,l));return}if(o.tagName==="BR"){l.push(`
110
+ `);return}const a=i.has(o.tagName);a&&l.length>0&&!s(l)&&l.push(`
111
+ `),o.childNodes.forEach(h=>n(h,l)),a&&!s(l)&&l.push(`
112
+ `)},r=[];return t.body.childNodes.forEach(o=>n(o,r)),r.join("").replace(/\n{3,}/g,`
113
+
114
+ `).replace(/[ \t]+\n/g,`
115
+ `).trimEnd()}getActiveSelectionOffsets(e){const t=this.view.getSelectionOffsets();if(t.isInEditor)return{startOffset:t.startOffset,endOffset:t.endOffset};if(this.lastKnownSelection)return{startOffset:this.positionToOffsetInText(this.lastKnownSelection.start,e),endOffset:this.positionToOffsetInText(this.lastKnownSelection.end,e)};const i=this.positionToOffsetInText(this.lastKnownCursor,e);return{startOffset:i,endOffset:i}}deleteUsingDirection(e){const t=this.textModel.getText(),{startOffset:i,endOffset:s}=this.getActiveSelectionOffsets(t),n=Math.min(i,s),r=Math.max(i,s);if(n!==r){this.replaceOffsetsWithText(n,r,"");return}if(e==="backward"){if(n===0)return;this.replaceOffsetsWithText(n-1,n,"");return}r>=t.length||this.replaceOffsetsWithText(r,r+1,"")}replaceOffsetsWithText(e,t,i){this.ensureEditableSurfaceIsUnfolded();const s=i.replace(/\r\n?/g,`
116
+ `),n=this.textModel.getText(),r=this.pendingInputSnapshot??this.captureHistorySnapshot(n),o=Math.max(0,Math.min(e,n.length)),l=Math.max(0,Math.min(t,n.length)),a=Math.min(o,l),h=Math.max(o,l),d=this.textModel.replaceRange({start:this.textModel.offsetToPosition(a),end:this.textModel.offsetToPosition(h)},s);this.pendingInputSnapshot=void 0,this.suppressHistory||this.pushUndoSnapshot(r);const c=a+s.length;return this.expectingProgrammaticCursor=!0,this.renderTextWithHighlight(this.textModel.getText(),!1),this.setCursor(this.textModel.offsetToPosition(c)),setTimeout(()=>{this.expectingProgrammaticCursor=!1},20),this.emit("change",[d]),d}ensureEditableSurfaceIsUnfolded(){!this.hasRenderedFoldPlaceholders()&&this.folds.length===0||(this.clearPendingHighlightRender(),this.folds=[],this.expectingProgrammaticCursor=!0,this.renderTextWithHighlight(this.textModel.getText(),!1),setTimeout(()=>{this.expectingProgrammaticCursor=!1},20))}syncSelectionCacheFromView(){const e=this.view.getSelectionState();return e.isInEditor&&e.cursor&&(this.lastKnownCursor=e.cursor,this.lastKnownSelection=e.isCollapsed?void 0:e.range),e}isSameFoldRange(e,t){return e.start.line===t.start.line&&e.start.column===t.start.column&&e.end.line===t.end.line&&e.end.column===t.end.column}scheduleDecorationRender(){if(!this.isDestroyed){if(typeof requestAnimationFrame!="function"){this.applyDecorations();return}this.decorationRenderRaf===null&&(this.decorationRenderRaf=requestAnimationFrame(()=>{this.decorationRenderRaf=null,this.applyDecorations()}))}}applyDecorations(){if(this.isDestroyed)return;if(this.decorationLayers.size===0){this.view.clearDecorations(),this.clearInlineDecorationHighlights();return}const e=[],t=[],i=[];for(const[s,n]of this.decorationLayers.entries())for(const r of n){const o=`${s}::${r.id}`;if(r.type==="line"){e.push({...r,id:o});continue}if(r.type==="gutter"){t.push({...r,id:o});continue}i.push({...r,id:o})}this.view.setDecorations(this.normalizeLineDecorations(e),this.normalizeGutterDecorations(t)),this.renderInlineDecorations(i)}normalizeLineDecorations(e){const t=Math.max(0,this.textModel.getLineCount()-1);return e.filter(i=>Number.isFinite(i.line)).map(i=>({...i,line:Math.max(0,Math.min(t,Math.floor(i.line))),style:i.style?{...i.style}:void 0}))}normalizeGutterDecorations(e){const t=Math.max(0,this.textModel.getLineCount()-1);return e.filter(i=>Number.isFinite(i.line)).map(i=>({...i,line:Math.max(0,Math.min(t,Math.floor(i.line))),style:i.style?{...i.style}:void 0}))}renderInlineDecorations(e){if(!this.hasCustomDecorationHighlightSupport){this.clearInlineDecorationHighlights();return}const t=CSS,i=window.Highlight;if(!t.highlights||!i){this.clearInlineDecorationHighlights();return}if(this.clearInlineDecorationHighlights(),e.length===0)return;const s=this.textModel.getText(),n=[];let r=0;for(const l of e){if(r>=this.decorationHighlightLimit)break;const a=this.normalizeInlineDecoration(l,s);if(!a)continue;const h=this.view.createDomRangeFromRange(a.range);if(!h)continue;const d=this.buildInlineDecorationHighlightName(a.id);t.highlights.set(d,new i(h)),this.inlineDecorationHighlightNames.add(d),n.push(`
117
+ ::highlight(${d}) {
118
+ ${this.serializeInlineDecorationStyle(a.style)}
119
+ }
120
+ `),r+=1}const o=this.ensureDecorationHighlightStyleNode();o.textContent=n.join(`
121
+ `)}normalizeInlineDecoration(e,t){const i=this.normalizeRange({start:this.clampPositionToText(e.range.start,t),end:this.clampPositionToText(e.range.end,t)});return i.start.line===i.end.line&&i.start.column===i.end.column?null:{...e,range:i,style:e.style?{...e.style}:void 0}}clearInlineDecorationHighlights(e=!1){try{const i=CSS;if(i.highlights)for(const s of this.inlineDecorationHighlightNames)i.highlights.delete(s)}catch{}if(this.inlineDecorationHighlightNames.clear(),typeof document>"u")return;const t=document.getElementById(this.decorationHighlightStyleId);if(e){t?.parentNode&&t.parentNode.removeChild(t);return}t&&(t.textContent="")}ensureDecorationHighlightStyleNode(){let e=document.getElementById(this.decorationHighlightStyleId);return e||(e=document.createElement("style"),e.id=this.decorationHighlightStyleId,document.head.appendChild(e),e)}observeDecorationRelevantMutations(){typeof MutationObserver>"u"||(this.decorationMutationObserver=new MutationObserver(()=>{this.decorationLayers.size!==0&&this.scheduleDecorationRender()}),this.decorationMutationObserver.observe(this.view.getContentElement(),{childList:!0,subtree:!0,characterData:!0}))}detectCustomHighlightSupport(){try{if(typeof CSS>"u"||typeof window>"u")return!1;const e=CSS,t=window.Highlight;return!!e.highlights&&!!t}catch{return!1}}buildInlineDecorationHighlightName(e){return`editora-decoration-${this.editorInstanceId}-${this.sanitizeHighlightIdentifier(e)}`}sanitizeHighlightIdentifier(e){return e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}serializeInlineDecorationStyle(e){return this.serializeStyleObject(e)||"background-color: var(--lce-inline-decoration-bg, rgba(86, 156, 214, 0.18)); border-radius: 2px;"}serializeStyleObject(e){return e?Object.entries(e).filter(([,t])=>typeof t=="string"&&t.length>0).map(([t,i])=>`${this.toKebabCase(t)}: ${i};`).join(" "):""}toKebabCase(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}cloneDecoration(e){return e.type==="inline"?{...e,range:{start:{...e.range.start},end:{...e.range.end}},style:e.style?{...e.style}:void 0}:{...e,style:e.style?{...e.style}:void 0}}};U.CURSOR_SENTINEL="";let Y=U;class J{constructor(e){this.name="keymap",this.editor=null,this.keymap={},this.isMac=navigator.platform.toUpperCase().indexOf("MAC")>=0,this.keymap=e||this.getDefaultKeymap()}setup(e){this.editor=e}handleKeyDown(e){if(!this.editor)return;const t=this.findMatchingBinding(e);if(t)return this.editor.executeCommand(t.command),e.preventDefault(),e.stopPropagation(),!1}findMatchingBinding(e){const{key:t,ctrlKey:i,altKey:s,shiftKey:n,metaKey:r}=e,o=String(t).toLowerCase(),l=this.keymap[o];if(!l)return null;for(const a of l){const h=a.ctrlKey===void 0||a.ctrlKey===i,d=a.altKey===void 0||a.altKey===s,c=a.shiftKey===void 0||a.shiftKey===n,g=a.metaKey===void 0||a.metaKey===r;if(h&&d&&c&&g)return a}return null}onKeyDown(e){return this.handleKeyDown(e)}getDefaultKeymap(){const e={};return this.addBinding(e,"f",{ctrlKey:!this.isMac,metaKey:this.isMac},"find"),this.addBinding(e,"h",{ctrlKey:!this.isMac,metaKey:this.isMac},"replace"),this.addBinding(e,"f3",{},"findNext"),this.addBinding(e,"f3",{shiftKey:!0},"findPrev"),this.addBinding(e,"g",{ctrlKey:!this.isMac,metaKey:this.isMac},"findNext"),this.addBinding(e,"[",{ctrlKey:!this.isMac,metaKey:this.isMac,shiftKey:!0},"fold"),this.addBinding(e,"]",{ctrlKey:!this.isMac,metaKey:this.isMac,shiftKey:!0},"unfold"),this.addBinding(e,"s",{ctrlKey:!0},"save"),this.addBinding(e,"s",{metaKey:!0},"save"),this.addBinding(e,"z",{ctrlKey:!0},"undo"),this.addBinding(e,"z",{metaKey:!0},"undo"),this.addBinding(e,"y",{ctrlKey:!0},"redo"),this.addBinding(e,"y",{metaKey:!0},"redo"),this.addBinding(e,"z",{ctrlKey:!0,shiftKey:!0},"redo"),this.addBinding(e,"z",{metaKey:!0,shiftKey:!0},"redo"),this.addBinding(e,"tab",{},"insertTab"),this.addBinding(e,"t",{ctrlKey:!this.isMac,metaKey:this.isMac,shiftKey:!0},"toggleTheme"),this.addBinding(e,"f",{altKey:!0,shiftKey:!0},"formatDocument"),e}addBinding(e,t,i,s){const n=t.toLowerCase();e[n]||(e[n]=[]),e[n].push({key:n,command:s,...i})}setKeymap(e){this.keymap={...e}}addKeyBinding(e){const t=e.key.toLowerCase();this.keymap[t]||(this.keymap[t]=[]),this.keymap[t]=this.keymap[t].filter(i=>i.command!==e.command),this.keymap[t].push({...e,key:t})}removeKeyBinding(e,t){const i=e.toLowerCase();t?this.keymap[i]&&(this.keymap[i]=this.keymap[i].filter(s=>s.command!==t),this.keymap[i].length===0&&delete this.keymap[i]):delete this.keymap[i]}getKeymap(){return{...this.keymap}}getBindingsForCommand(e){const t=[];for(const i in this.keymap)for(const s of this.keymap[i])s.command===e&&t.push({...s});return t}getPlatformInfo(){return{isMac:this.isMac,platform:navigator.platform}}destroy(){this.keymap={},this.editor=null}}const W=class V{constructor(){this.name="transaction",this.transactions=[]}setup(e){e.on("change",t=>{const i={changes:t,selection:e.getSelection(),effects:[],annotations:[]};this.transactions.push(i),this.transactions.length>V.MAX_TRANSACTIONS&&this.transactions.splice(0,this.transactions.length-V.MAX_TRANSACTIONS)})}getTransactions(){return this.transactions}destroy(){this.transactions=[]}};W.MAX_TRANSACTIONS=200;let ee=W;class te{constructor(){this.name="line-numbers",this.editor=null,this.lineNumbersElement=null,this.isEnabled=!0}setup(e){this.editor=e,this.isEnabled=e.getConfig().lineNumbers!==!1,this.createLineNumbers(),e.registerCommand("toggleLineNumbers",()=>{this.toggle()}),e.on("change",()=>{this.updateLineNumbers()}),this.updateLineNumbers()}createLineNumbers(){if(!this.editor)return;const e=this.editor.getView(),t=e.getLineNumbersElement();t&&(this.lineNumbersElement=t,e.setLineNumbersVisible(this.isEnabled))}updateLineNumbers(){if(!this.lineNumbersElement||!this.editor||!this.isEnabled)return;const e=this.editor.getValue().split(`
122
+ `).length;this.editor.getView().updateLineNumbers(e)}toggle(){this.editor&&(this.isEnabled=!this.isEnabled,this.editor.getView().setLineNumbersVisible(this.isEnabled),this.lineNumbersElement&&(this.lineNumbersElement.style.display=this.isEnabled?"table-cell":"none"),this.updateLineNumbers())}destroy(){this.lineNumbersElement=null,this.editor=null}}class ie{constructor(){this.name="theme",this.editor=null,this.currentTheme="dark"}setup(e){this.editor=e,e.registerCommand("setTheme",t=>{this.setTheme(t)}),e.registerCommand("toggleTheme",()=>{this.toggleTheme()}),this.setTheme(this.currentTheme)}setTheme(e){this.editor&&(this.currentTheme=e,this.editor.setTheme(e))}toggleTheme(){const e=this.currentTheme==="dark"?"light":"dark";this.setTheme(e)}getCurrentTheme(){return this.currentTheme}destroy(){this.editor=null}}class se{constructor(){this.name="read-only",this.editor=null,this.isReadOnly=!1}setup(e){this.editor=e,e.registerCommand("setReadOnly",t=>{this.setReadOnly(t)}),e.registerCommand("toggleReadOnly",()=>{this.toggleReadOnly()}),e.on("keydown",t=>{if(t.ctrlKey&&t.key==="r")return t.preventDefault(),this.toggleReadOnly(),!1})}setReadOnly(e){this.editor&&(this.isReadOnly=e,this.editor.setReadOnly(e))}toggleReadOnly(){this.setReadOnly(!this.isReadOnly)}isCurrentlyReadOnly(){return this.isReadOnly}destroy(){this.editor=null}}let ne=0;const K=class m{constructor(e={}){this.name="search",this.editor=null,this.searchUI=null,this.isVisible=!1,this.currentResults=[],this.currentIndex=-1,this.searchDebounceTimer=null,this.liveRefreshTimer=null,this.statusResetTimer=null,this.statusFreezeUntil=0,this.findInput=null,this.replaceInputEl=null,this.statusDiv=null,this.modeDiv=null,this.caseSensitiveInput=null,this.wholeWordInput=null,this.regexInput=null,this.currentQuery="",this.savedCursor=null,this.editorChangeHandler=null,this.searchOptions={caseSensitive:!1,wholeWord:!1,regex:!1},this.trailingMarkerAttr="data-lce-trailing-newline-marker",this.editorContainerSelector='[data-lce-editor-container="true"]',this.highlightId=++ne,this.highlightMatchName=`editora-search-match-${this.highlightId}`,this.highlightActiveName=`editora-search-active-${this.highlightId}`,this.highlightStyleId=`editora-search-highlight-style-${this.highlightId}`,this.maxCustomHighlightRanges=2e3,this.virtualMarkerRegex=/[\u200B\uE000]/,this.hasCustomHighlightSupport=!1,this.config={replaceAndFindNext:!0,...e}}setup(e){this.editor=e,this.hasCustomHighlightSupport=this.detectCustomHighlightSupport(),this.hasCustomHighlightSupport&&this.ensureHighlightStyles(),e.registerCommand("find",()=>{this.showSearch()}),e.registerCommand("findNext",()=>{this.findNext()}),e.registerCommand("findPrev",()=>{this.findPrev()}),e.registerCommand("replace",()=>{this.showReplace()}),e.registerCommand("replaceAll",(t,i)=>{this.replaceAll(t,i)}),this.editorChangeHandler=()=>{!this.isVisible||!this.currentQuery||this.scheduleLiveRefresh(!0)},e.on("change",this.editorChangeHandler)}showSearch(){this.editor&&(this.searchUI||this.createSearchUI(),this.isVisible||this.captureSelectionState(),this.isVisible=!0,this.searchUI&&(this.searchUI.style.display="block",this.updateModeHint(!1),this.findInput&&(this.findInput.focus(),this.findInput.select())),this.currentQuery&&this.performSearch(this.currentQuery,!0,!1))}showReplace(){this.showSearch(),this.replaceInputEl&&(this.replaceInputEl.style.display="block",this.replaceInputEl.focus()),this.updateModeHint(!0),this.currentQuery&&this.performSearch(this.currentQuery,!1,!0)}hideSearch(){this.isVisible=!1,this.searchUI&&(this.searchUI.style.display="none"),this.replaceInputEl&&(this.replaceInputEl.style.display="none",this.replaceInputEl.value=""),this.updateModeHint(!1),this.clearHighlights(),this.restoreSelectionState()}createSearchUI(){if(!this.editor)return;const e=this.editor.getView().getContentElement(),t=e.closest(this.editorContainerSelector),i=t?.parentElement,s=e.closest(".rte-source-editor-modal")||i||t||e.parentElement;if(!s)return;window.getComputedStyle(s).position==="static"&&(s.style.position="relative"),this.searchUI=document.createElement("div"),this.searchUI.className=m.css.root,this.searchUI.style.display="none",this.searchUI.innerHTML=`
64
123
  <div class="${m.css.row}">
65
124
  <input type="text" class="${m.css.findInput} ${m.css.inputBase}" placeholder="Find..." />
66
125
  <button class="${m.css.prevButton} ${m.css.buttonBase}" type="button" aria-label="Previous match">↑</button>
@@ -86,11 +145,11 @@
86
145
  <div class="${m.css.mode} ${m.css.modeLayout}" aria-live="polite"></div>
87
146
  </div>
88
147
  <input type="text" class="${m.css.replaceInput} ${m.css.inputBase} ${m.css.replaceInputLayout}" placeholder="Replace with..." />
89
- `;const s=this.searchUI.querySelector(`.${m.css.findInput}`),n=this.searchUI.querySelector(`.${m.css.replaceInput}`),r=this.searchUI.querySelector(`.${m.css.prevButton}`),o=this.searchUI.querySelector(`.${m.css.nextButton}`),a=this.searchUI.querySelector(`.${m.css.closeButton}`),h=this.searchUI.querySelector(`.${m.css.status}`),l=this.searchUI.querySelector(`.${m.css.mode}`),c=this.searchUI.querySelector(`.${m.css.caseSensitive}`),d=this.searchUI.querySelector(`.${m.css.wholeWord}`),p=this.searchUI.querySelector(`.${m.css.regex}`);this.findInput=s,this.replaceInputEl=n,this.statusDiv=h,this.modeDiv=l,this.caseSensitiveInput=c,this.wholeWordInput=d,this.regexInput=p,c.checked=!!this.searchOptions.caseSensitive,d.checked=!!this.searchOptions.wholeWord,p.checked=!!this.searchOptions.regex,s.addEventListener("input",()=>{this.searchDebounceTimer&&clearTimeout(this.searchDebounceTimer);const g=s.value;this.searchDebounceTimer=setTimeout(()=>{this.performSearch(g,!1,!1)},120)});const u=()=>{this.searchOptions.caseSensitive=c.checked,this.searchOptions.wholeWord=d.checked,this.searchOptions.regex=p.checked;const g=s.value;g.trim()?this.performSearch(g,!1,!1):this.performSearch("",!1,!1)};c.addEventListener("change",u),d.addEventListener("change",u),p.addEventListener("change",u),s.addEventListener("keydown",g=>{g.key==="Enter"?(g.preventDefault(),g.shiftKey?this.findPrev():this.findNext()):g.key==="Escape"&&(g.preventDefault(),this.hideSearch())}),n.addEventListener("keydown",g=>{g.key==="Enter"?(g.preventDefault(),g.shiftKey?this.replaceAll(s.value,n.value):this.replaceCurrent(s.value,n.value)):g.key==="Escape"&&(g.preventDefault(),this.hideSearch())}),r.addEventListener("click",()=>this.findPrev()),o.addEventListener("click",()=>this.findNext()),a.addEventListener("click",()=>this.hideSearch()),i.appendChild(this.searchUI)}updateModeHint(e){this.modeDiv&&(this.modeDiv.textContent=e?`Replace: move next ${this.config.replaceAndFindNext?"ON":"OFF"}`:"Find mode")}performSearch(e,t,i){if(!this.editor||!e.trim()){this.currentQuery="",this.currentResults=[],this.currentIndex=-1,this.clearHighlights(),this.updateStatus("");return}if(this.searchOptions.regex&&!this.isValidRegex(e)){this.currentQuery=e,this.currentResults=[],this.currentIndex=-1,this.clearHighlights(),this.updateStatus("Invalid regular expression");return}this.currentQuery=e;const s=this.currentIndex,n=this.editor.search(e,this.searchOptions);if(this.currentResults=n,n.length===0){this.currentIndex=-1,this.clearHighlights(),this.updateStatus("No matches");return}t&&s>=0?this.currentIndex=Math.min(s,n.length-1):this.currentIndex=0,this.updateHighlights(i)}findNext(){if(this.currentResults.length===0){this.currentQuery&&this.performSearch(this.currentQuery,!0,!0);return}this.currentIndex=(this.currentIndex+1)%this.currentResults.length,this.updateHighlights(!0)}findPrev(){if(this.currentResults.length===0){this.currentQuery&&this.performSearch(this.currentQuery,!0,!0);return}this.currentIndex=this.currentIndex<=0?this.currentResults.length-1:this.currentIndex-1,this.updateHighlights(!0)}replaceCurrent(e,t){if(!this.editor||!e.trim()||((this.currentQuery!==e||this.currentResults.length===0)&&this.performSearch(e,!1,!0),this.currentIndex<0||this.currentResults.length===0))return;const i=this.currentResults[this.currentIndex];if(!i)return;const s=this.computeReplacementRange(i.range.start,t);if(this.editor.replace(i.range,t),this.config.replaceAndFindNext){this.currentQuery=e;const n=this.editor.search(e,this.searchOptions);if(this.currentResults=n,n.length===0){this.currentIndex=-1,this.clearHighlights(),this.updateStatus("Replaced current occurrence"),this.restoreReplaceInputFocus();return}this.currentIndex=this.findNextResultIndexAfter(s.end,n),this.updateHighlights(!0)}else this.scrollLogicalRangeIntoView(s,!0),this.performSearch(e,!0,!1);this.currentResults.length>0||this.showTransientStatus("Replaced current occurrence"),this.restoreReplaceInputFocus(),this.revealActiveResultAfterFocusRestore()}replaceAll(e,t){if(!this.editor||!e.trim())return;const i=this.editor.replaceAll(e,t,this.searchOptions);this.performSearch(e,!1,!1),this.showTransientStatus(`Replaced ${i} occurrence${i===1?"":"s"}`),this.restoreReplaceInputFocus(),this.revealActiveResultAfterFocusRestore()}updateHighlights(e){if(this.clearHighlights(),this.currentResults.length===0||this.currentIndex===-1||!this.editor)return;this.applyCustomHighlights();const t=this.currentResults[this.currentIndex];t&&((e||!this.hasCustomHighlightSupport)&&this.navigateToResult(t,!this.hasCustomHighlightSupport),this.updateStatus(`${this.currentResults.length} matches (showing ${this.currentIndex+1}/${this.currentResults.length})`))}navigateToResult(e,t){if(!this.editor)return;const i=document.activeElement,s=!!i&&(i===this.findInput||i===this.replaceInputEl);t?(this.editor.setSelection(e.range),this.centerCurrentSelectionInView()):this.scrollResultIntoView(e);const n=this.editor.getView();t&&typeof n.ensureCaretVisible=="function"&&n.ensureCaretVisible(),t&&s&&i&&requestAnimationFrame(()=>{this.focusWithoutScrolling(i)})}clearHighlights(){var e,t;if(this.hasCustomHighlightSupport)try{const i=CSS;(e=i.highlights)==null||e.delete(this.highlightMatchName),(t=i.highlights)==null||t.delete(this.highlightActiveName)}catch{}}scrollResultIntoView(e){this.scrollLogicalRangeIntoView(e.range,!0)}scrollLogicalRangeIntoView(e,t){if(!this.editor)return;const i=this.editor.getView().getContentElement(),s=this.editor.getValue(),{lineStarts:n,lines:r}=this.buildLineStarts(s),o=this.buildTextNodeIndex(i);if(o.length===0)return;const a=this.toDomRange(e,n,r,o);if(!a)return;const h=a.startContainer.nodeType===Node.TEXT_NODE?a.startContainer.parentElement:a.startContainer,l=this.resolveScrollContainer(i);if(l){const c=a.getClientRects()[0]||a.getBoundingClientRect(),d=l.getBoundingClientRect(),p=l.scrollTop+(c.top-d.top)-d.height/2+c.height/2,u=18;let g=t?p:l.scrollTop,f=l.scrollLeft;const y=l.scrollLeft+(c.left-d.left),k=y+c.width;c.right>d.right-u?f=k-d.width+u:c.left<d.left+u&&(f=Math.max(0,y-u));const v=Math.max(0,l.scrollHeight-l.clientHeight),C=Math.max(0,l.scrollWidth-l.clientWidth);if(g=Math.min(v,Math.max(0,g)),f=Math.min(C,Math.max(0,f)),v===0&&C===0){h==null||h.scrollIntoView({block:t?"center":"nearest",inline:"nearest",behavior:"smooth"});return}(g!==l.scrollTop||f!==l.scrollLeft)&&l.scrollTo({top:g,left:f,behavior:"smooth"});return}h==null||h.scrollIntoView({block:t?"center":"nearest",inline:"nearest",behavior:"smooth"})}restoreReplaceInputFocus(){const e=this.replaceInputEl;!e||e.style.display==="none"||requestAnimationFrame(()=>{this.focusWithoutScrolling(e);const t=e.value.length;try{e.setSelectionRange(t,t)}catch{}})}centerCurrentSelectionInView(){if(!this.editor)return;const e=this.editor.getView().getContentElement(),t=this.resolveScrollContainer(e);if(!t)return;const i=window.getSelection();if(!i||i.rangeCount===0)return;const s=i.getRangeAt(0).cloneRange(),n=s.getClientRects()[0]||s.getBoundingClientRect();if(!n)return;const r=t.getBoundingClientRect(),o=t.scrollTop+(n.top-r.top)-r.height/2+n.height/2,a=Math.max(0,t.scrollHeight-t.clientHeight),h=Math.min(a,Math.max(0,o));h!==t.scrollTop&&t.scrollTo({top:h,behavior:"smooth"})}computeReplacementRange(e,t){const i=t.replace(/\r\n?/g,`
148
+ `;const n=this.searchUI.querySelector(`.${m.css.findInput}`),r=this.searchUI.querySelector(`.${m.css.replaceInput}`),o=this.searchUI.querySelector(`.${m.css.prevButton}`),l=this.searchUI.querySelector(`.${m.css.nextButton}`),a=this.searchUI.querySelector(`.${m.css.closeButton}`),h=this.searchUI.querySelector(`.${m.css.status}`),d=this.searchUI.querySelector(`.${m.css.mode}`),c=this.searchUI.querySelector(`.${m.css.caseSensitive}`),g=this.searchUI.querySelector(`.${m.css.wholeWord}`),u=this.searchUI.querySelector(`.${m.css.regex}`);this.findInput=n,this.replaceInputEl=r,this.statusDiv=h,this.modeDiv=d,this.caseSensitiveInput=c,this.wholeWordInput=g,this.regexInput=u,c.checked=!!this.searchOptions.caseSensitive,g.checked=!!this.searchOptions.wholeWord,u.checked=!!this.searchOptions.regex,n.addEventListener("input",()=>{this.searchDebounceTimer&&clearTimeout(this.searchDebounceTimer);const f=n.value;this.searchDebounceTimer=setTimeout(()=>{this.performSearch(f,!1,!1)},120)});const p=()=>{this.searchOptions.caseSensitive=c.checked,this.searchOptions.wholeWord=g.checked,this.searchOptions.regex=u.checked;const f=n.value;f.trim()?this.performSearch(f,!1,!1):this.performSearch("",!1,!1)};c.addEventListener("change",p),g.addEventListener("change",p),u.addEventListener("change",p),n.addEventListener("keydown",f=>{f.key==="Enter"?(f.preventDefault(),f.shiftKey?this.findPrev():this.findNext()):f.key==="Escape"&&(f.preventDefault(),this.hideSearch())}),r.addEventListener("keydown",f=>{f.key==="Enter"?(f.preventDefault(),f.shiftKey?this.replaceAll(n.value,r.value):this.replaceCurrent(n.value,r.value)):f.key==="Escape"&&(f.preventDefault(),this.hideSearch())}),o.addEventListener("click",()=>this.findPrev()),l.addEventListener("click",()=>this.findNext()),a.addEventListener("click",()=>this.hideSearch()),s.appendChild(this.searchUI)}updateModeHint(e){this.modeDiv&&(this.modeDiv.textContent=e?`Replace: move next ${this.config.replaceAndFindNext?"ON":"OFF"}`:"Find mode")}performSearch(e,t,i){if(!this.editor||!e.trim()){this.currentQuery="",this.currentResults=[],this.currentIndex=-1,this.clearHighlights(),this.updateStatus("");return}if(this.searchOptions.regex&&!this.isValidRegex(e)){this.currentQuery=e,this.currentResults=[],this.currentIndex=-1,this.clearHighlights(),this.updateStatus("Invalid regular expression");return}this.currentQuery=e;const s=this.currentIndex,n=this.editor.search(e,this.searchOptions);if(this.currentResults=n,n.length===0){this.currentIndex=-1,this.clearHighlights(),this.updateStatus("No matches");return}t&&s>=0?this.currentIndex=Math.min(s,n.length-1):this.currentIndex=0,this.updateHighlights(i)}findNext(){if(this.currentResults.length===0){this.currentQuery&&this.performSearch(this.currentQuery,!0,!0);return}this.currentIndex=(this.currentIndex+1)%this.currentResults.length,this.updateHighlights(!0)}findPrev(){if(this.currentResults.length===0){this.currentQuery&&this.performSearch(this.currentQuery,!0,!0);return}this.currentIndex=this.currentIndex<=0?this.currentResults.length-1:this.currentIndex-1,this.updateHighlights(!0)}replaceCurrent(e,t){if(!this.editor||!e.trim()||((this.currentQuery!==e||this.currentResults.length===0)&&this.performSearch(e,!1,!0),this.currentIndex<0||this.currentResults.length===0))return;const i=this.currentResults[this.currentIndex];if(!i)return;const s=this.computeReplacementRange(i.range.start,t);if(this.editor.replace(i.range,t),this.config.replaceAndFindNext){this.currentQuery=e;const n=this.editor.search(e,this.searchOptions);if(this.currentResults=n,n.length===0){this.currentIndex=-1,this.clearHighlights(),this.updateStatus("Replaced current occurrence"),this.restoreReplaceInputFocus();return}this.currentIndex=this.findNextResultIndexAfter(s.end,n),this.updateHighlights(!0)}else this.scrollLogicalRangeIntoView(s,!0),this.performSearch(e,!0,!1);this.currentResults.length>0||this.showTransientStatus("Replaced current occurrence"),this.restoreReplaceInputFocus(),this.revealActiveResultAfterFocusRestore()}replaceAll(e,t){if(!this.editor||!e.trim())return;const i=this.editor.replaceAll(e,t,this.searchOptions);this.performSearch(e,!1,!1),this.showTransientStatus(`Replaced ${i} occurrence${i===1?"":"s"}`),this.restoreReplaceInputFocus(),this.revealActiveResultAfterFocusRestore()}updateHighlights(e){if(this.clearHighlights(),this.currentResults.length===0||this.currentIndex===-1||!this.editor)return;this.applyCustomHighlights();const t=this.currentResults[this.currentIndex];t&&((e||!this.hasCustomHighlightSupport)&&this.navigateToResult(t,!this.hasCustomHighlightSupport),this.updateStatus(`${this.currentResults.length} matches (showing ${this.currentIndex+1}/${this.currentResults.length})`))}navigateToResult(e,t){if(!this.editor)return;const i=document.activeElement,s=!!i&&(i===this.findInput||i===this.replaceInputEl);t?(this.editor.setSelection(e.range),this.centerCurrentSelectionInView()):this.scrollResultIntoView(e);const n=this.editor.getView();t&&typeof n.ensureCaretVisible=="function"&&n.ensureCaretVisible(),t&&s&&i&&requestAnimationFrame(()=>{this.focusWithoutScrolling(i)})}clearHighlights(){if(this.hasCustomHighlightSupport)try{const e=CSS;e.highlights?.delete(this.highlightMatchName),e.highlights?.delete(this.highlightActiveName)}catch{}}scrollResultIntoView(e){this.scrollLogicalRangeIntoView(e.range,!0)}scrollLogicalRangeIntoView(e,t){if(!this.editor)return;const i=this.editor.getView().getContentElement(),s=this.editor.getValue(),{lineStarts:n,lines:r}=this.buildLineStarts(s),o=this.buildTextNodeIndex(i);if(o.length===0)return;const l=this.toDomRange(e,n,r,o);if(!l)return;const a=l.startContainer.nodeType===Node.TEXT_NODE?l.startContainer.parentElement:l.startContainer,h=this.resolveScrollContainer(i);if(h){const d=l.getClientRects()[0]||l.getBoundingClientRect(),c=h.getBoundingClientRect(),g=h.scrollTop+(d.top-c.top)-c.height/2+d.height/2,u=18;let p=t?g:h.scrollTop,f=h.scrollLeft;const b=h.scrollLeft+(d.left-c.left),x=b+d.width;d.right>c.right-u?f=x-c.width+u:d.left<c.left+u&&(f=Math.max(0,b-u));const E=Math.max(0,h.scrollHeight-h.clientHeight),T=Math.max(0,h.scrollWidth-h.clientWidth);if(p=Math.min(E,Math.max(0,p)),f=Math.min(T,Math.max(0,f)),E===0&&T===0){a?.scrollIntoView({block:t?"center":"nearest",inline:"nearest",behavior:"smooth"});return}(p!==h.scrollTop||f!==h.scrollLeft)&&h.scrollTo({top:p,left:f,behavior:"smooth"});return}a?.scrollIntoView({block:t?"center":"nearest",inline:"nearest",behavior:"smooth"})}restoreReplaceInputFocus(){const e=this.replaceInputEl;!e||e.style.display==="none"||requestAnimationFrame(()=>{this.focusWithoutScrolling(e);const t=e.value.length;try{e.setSelectionRange(t,t)}catch{}})}centerCurrentSelectionInView(){if(!this.editor)return;const e=this.editor.getView().getContentElement(),t=this.resolveScrollContainer(e);if(!t)return;const i=window.getSelection();if(!i||i.rangeCount===0)return;const s=i.getRangeAt(0).cloneRange(),n=s.getClientRects()[0]||s.getBoundingClientRect();if(!n)return;const r=t.getBoundingClientRect(),o=t.scrollTop+(n.top-r.top)-r.height/2+n.height/2,l=Math.max(0,t.scrollHeight-t.clientHeight),a=Math.min(l,Math.max(0,o));a!==t.scrollTop&&t.scrollTo({top:a,behavior:"smooth"})}computeReplacementRange(e,t){const i=t.replace(/\r\n?/g,`
90
149
  `),s=i.split(`
91
- `);let n;return s.length<=1?(n={start:e,end:{line:e.line,column:e.column+i.length}},this.clampRangeToDocument(n)):(n={start:e,end:{line:e.line+s.length-1,column:s[s.length-1].length}},this.clampRangeToDocument(n))}findNextResultIndexAfter(e,t){for(let i=0;i<t.length;i++)if(this.comparePositions(t[i].range.start,e)>=0)return i;return 0}comparePositions(e,t){return e.line!==t.line?e.line-t.line:e.column-t.column}clampRangeToDocument(e){var t,i;const s=this.editor;if(!s)return e;const n=s.getValue().split(`
92
- `),r=Math.max(0,n.length-1),o=Math.max(0,Math.min(e.start.line,r)),a=Math.max(0,Math.min(e.end.line,r)),h=Math.max(0,Math.min(e.start.column,((t=n[o])==null?void 0:t.length)||0)),l=Math.max(0,Math.min(e.end.column,((i=n[a])==null?void 0:i.length)||0));return{start:{line:o,column:h},end:{line:a,column:l}}}focusWithoutScrolling(e){try{e.focus({preventScroll:!0})}catch{const t=[];let i=e.parentElement;for(;i;)this.canScroll(i)&&t.push({el:i,top:i.scrollTop,left:i.scrollLeft}),i=i.parentElement;const s=window.scrollX,n=window.scrollY;e.focus();for(let r=0;r<t.length;r++){const o=t[r];o.el.scrollTop=o.top,o.el.scrollLeft=o.left}window.scrollTo(s,n)}}findScrollContainer(e){let t=e;for(;t;){const i=window.getComputedStyle(t).overflowY;if((i==="auto"||i==="scroll")&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement}return null}resolveScrollContainer(e){var t,i;const s=(t=this.editor)==null?void 0:t.getView(),n=((i=s==null?void 0:s.getScrollElement)==null?void 0:i.call(s))||null;return n&&this.canScroll(n)?n:this.findScrollContainer(e)}canScroll(e){return e.scrollHeight>e.clientHeight||e.scrollWidth>e.clientWidth}revealActiveResultAfterFocusRestore(){!this.currentResults.length||this.currentIndex<0||requestAnimationFrame(()=>{const e=this.currentResults[this.currentIndex];e&&this.scrollResultIntoView(e)})}applyCustomHighlights(){if(!this.editor||!this.hasCustomHighlightSupport||this.currentResults.length===0)return;const e=this.editor.getView().getContentElement(),t=this.editor.getValue(),{lineStarts:i,lines:s}=this.buildLineStarts(t),n=this.buildTextNodeIndex(e);if(n.length===0)return;const r=this.buildVisibleDocumentText(n),o=[];let a=null;const h=Math.min(this.currentResults.length,this.maxCustomHighlightRanges);for(let l=0;l<h;l++){const c=this.currentResults[l],d=this.searchOptions.regex?c.match||this.currentQuery:this.currentQuery||c.match,p=this.toDomRange(c.range,i,s,n,r,d);p&&(o.push(p),l===this.currentIndex&&(a=p))}if(o.length!==0)try{const l=CSS,c=window.Highlight;if(!l.highlights||!c)return;l.highlights.set(this.highlightMatchName,new c(...o)),a&&l.highlights.set(this.highlightActiveName,new c(a))}catch{}}buildLineStarts(e){const t=e.split(`
93
- `),i=new Array(t.length);let s=0;for(let n=0;n<t.length;n++)i[n]=s,s+=t[n].length+1;return{lineStarts:i,lines:t}}positionToOffset(e,t,i){var s;const n=Math.max(0,Math.min(e.line,i.length-1)),r=Math.max(0,Math.min(e.column,((s=i[n])==null?void 0:s.length)||0));return t[n]+r}buildTextNodeIndex(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),i=[];let s=0,n;for(;n=t.nextNode();){const r=n,o=r.parentElement;if(o!=null&&o.hasAttribute(this.trailingMarkerAttr))continue;const a=r.textContent||"",h=this.buildVisibleToDomMap(a),l=Math.max(0,h.length-1);l===0&&a.length===0||(i.push({node:r,start:s,end:s+l,visibleToDom:h}),s+=l)}return i}resolveDomPoint(e,t){var i,s;const n=Math.max(0,e);for(let o=0;o<t.length;o++){const a=t[o];if(n<=a.end){const h=Math.max(0,n-a.start),l=a.visibleToDom[h]??((i=a.node.textContent)==null?void 0:i.length)??0;return{node:a.node,offset:l}}}const r=t[t.length-1];return r?{node:r.node,offset:r.visibleToDom[r.visibleToDom.length-1]??((s=r.node.textContent)==null?void 0:s.length)??0}:null}toDomRange(e,t,i,s,n,r){const o=this.positionToOffset(e.start,t,i),a=this.positionToOffset(e.end,t,i);let h=Math.min(o,a),l=Math.max(o,a);if(n&&r){const u=r,g=n.slice(h,l);if(g.length===u.length&&g.toLowerCase()!==u.toLowerCase()){const f=this.findNearestMatchOffset(n,u,h);f!==-1&&(h=f,l=f+u.length)}}const c=this.resolveDomPoint(h,s),d=this.resolveDomPoint(l,s);if(!c||!d)return null;const p=document.createRange();try{return p.setStart(c.node,c.offset),p.setEnd(d.node,d.offset),p}catch{return null}}buildVisibleDocumentText(e){let t="";for(let i=0;i<e.length;i++){const s=e[i].node.textContent||"";for(let n=0;n<s.length;n++){const r=s[n];this.virtualMarkerRegex.test(r)||(t+=r)}}return t}findNearestMatchOffset(e,t,i){const s=t.toLowerCase();let n=e.toLowerCase().indexOf(s);if(n===-1)return-1;let r=n,o=Math.abs(n-i);for(;n!==-1;){const a=Math.abs(n-i);if(a<o&&(o=a,r=n),a===0)return n;n=e.toLowerCase().indexOf(s,n+1)}return r}scheduleLiveRefresh(e){this.liveRefreshTimer&&clearTimeout(this.liveRefreshTimer);const t=this.currentQuery;this.liveRefreshTimer=setTimeout(()=>{!this.isVisible||!t||this.performSearch(t,e,!1)},90)}updateStatus(e,t=!1){if(this.statusDiv){if(!t&&Date.now()<this.statusFreezeUntil)return;this.statusDiv.textContent=e}}showTransientStatus(e,t=900){this.statusFreezeUntil=Date.now()+t,this.updateStatus(e,!0),this.statusResetTimer&&clearTimeout(this.statusResetTimer),this.statusResetTimer=setTimeout(()=>{this.statusFreezeUntil=0,this.syncMatchStatus()},t)}syncMatchStatus(){if(!this.currentQuery){this.updateStatus("",!0);return}if(this.currentResults.length===0||this.currentIndex<0){this.updateStatus("No matches",!0);return}this.updateStatus(`${this.currentResults.length} matches (showing ${this.currentIndex+1}/${this.currentResults.length})`,!0)}isValidRegex(e){try{const t=this.searchOptions.caseSensitive?"g":"gi";return new RegExp(e,t),!0}catch{return!1}}captureSelectionState(){this.editor&&(this.savedSelection=this.editor.getSelection(),this.savedCursor=this.editor.getCursor().position)}restoreSelectionState(){this.editor&&(this.savedSelection?this.editor.setSelection(this.savedSelection):this.savedCursor&&this.editor.setCursor(this.savedCursor),this.savedSelection=void 0,this.savedCursor=null)}detectCustomHighlightSupport(){try{const e=CSS,t=window.Highlight;return!!e.highlights&&!!t}catch{return!1}}buildVisibleToDomMap(e){const t=[0];let i=0;for(let s=0;s<e.length;s++){const n=e[s];this.virtualMarkerRegex.test(n)||(i+=1,t[i]=s+1)}return t}ensureHighlightStyles(){if(document.getElementById(this.highlightStyleId))return;const e=document.createElement("style");e.id=this.highlightStyleId,e.textContent=`
150
+ `);let n;return s.length<=1?(n={start:e,end:{line:e.line,column:e.column+i.length}},this.clampRangeToDocument(n)):(n={start:e,end:{line:e.line+s.length-1,column:s[s.length-1].length}},this.clampRangeToDocument(n))}findNextResultIndexAfter(e,t){for(let i=0;i<t.length;i++)if(this.comparePositions(t[i].range.start,e)>=0)return i;return 0}comparePositions(e,t){return e.line!==t.line?e.line-t.line:e.column-t.column}clampRangeToDocument(e){const t=this.editor;if(!t)return e;const i=t.getValue().split(`
151
+ `),s=Math.max(0,i.length-1),n=Math.max(0,Math.min(e.start.line,s)),r=Math.max(0,Math.min(e.end.line,s)),o=Math.max(0,Math.min(e.start.column,i[n]?.length||0)),l=Math.max(0,Math.min(e.end.column,i[r]?.length||0));return{start:{line:n,column:o},end:{line:r,column:l}}}focusWithoutScrolling(e){try{e.focus({preventScroll:!0})}catch{const t=[];let i=e.parentElement;for(;i;)this.canScroll(i)&&t.push({el:i,top:i.scrollTop,left:i.scrollLeft}),i=i.parentElement;const s=window.scrollX,n=window.scrollY;e.focus();for(let r=0;r<t.length;r++){const o=t[r];o.el.scrollTop=o.top,o.el.scrollLeft=o.left}window.scrollTo(s,n)}}findScrollContainer(e){let t=e;for(;t;){const i=window.getComputedStyle(t).overflowY;if((i==="auto"||i==="scroll")&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement}return null}resolveScrollContainer(e){const t=this.editor?.getView()?.getScrollElement?.()||null;return t&&this.canScroll(t)?t:this.findScrollContainer(e)}canScroll(e){return e.scrollHeight>e.clientHeight||e.scrollWidth>e.clientWidth}revealActiveResultAfterFocusRestore(){!this.currentResults.length||this.currentIndex<0||requestAnimationFrame(()=>{const e=this.currentResults[this.currentIndex];e&&this.scrollResultIntoView(e)})}applyCustomHighlights(){if(!this.editor||!this.hasCustomHighlightSupport||this.currentResults.length===0)return;const e=this.editor.getView().getContentElement(),t=this.editor.getValue(),{lineStarts:i,lines:s}=this.buildLineStarts(t),n=this.buildTextNodeIndex(e);if(n.length===0)return;const r=this.buildVisibleDocumentText(n),o=[];let l=null;const a=Math.min(this.currentResults.length,this.maxCustomHighlightRanges);for(let h=0;h<a;h++){const d=this.currentResults[h],c=this.searchOptions.regex?d.match||this.currentQuery:this.currentQuery||d.match,g=this.toDomRange(d.range,i,s,n,r,c);g&&(o.push(g),h===this.currentIndex&&(l=g))}if(o.length!==0)try{const h=CSS,d=window.Highlight;if(!h.highlights||!d)return;h.highlights.set(this.highlightMatchName,new d(...o)),l&&h.highlights.set(this.highlightActiveName,new d(l))}catch{}}buildLineStarts(e){const t=e.split(`
152
+ `),i=new Array(t.length);let s=0;for(let n=0;n<t.length;n++)i[n]=s,s+=t[n].length+1;return{lineStarts:i,lines:t}}positionToOffset(e,t,i){const s=Math.max(0,Math.min(e.line,i.length-1)),n=Math.max(0,Math.min(e.column,i[s]?.length||0));return t[s]+n}buildTextNodeIndex(e){const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),i=[];let s=0,n;for(;n=t.nextNode();){const r=n;if(r.parentElement?.hasAttribute(this.trailingMarkerAttr))continue;const o=r.textContent||"",l=this.buildVisibleToDomMap(o),a=Math.max(0,l.length-1);a===0&&o.length===0||(i.push({node:r,start:s,end:s+a,visibleToDom:l}),s+=a)}return i}resolveDomPoint(e,t){const i=Math.max(0,e);for(let n=0;n<t.length;n++){const r=t[n];if(i<=r.end){const o=Math.max(0,i-r.start),l=r.visibleToDom[o]??r.node.textContent?.length??0;return{node:r.node,offset:l}}}const s=t[t.length-1];return s?{node:s.node,offset:s.visibleToDom[s.visibleToDom.length-1]??s.node.textContent?.length??0}:null}toDomRange(e,t,i,s,n,r){const o=this.positionToOffset(e.start,t,i),l=this.positionToOffset(e.end,t,i);let a=Math.min(o,l),h=Math.max(o,l);if(n&&r){const u=r,p=n.slice(a,h);if(p.length===u.length&&p.toLowerCase()!==u.toLowerCase()){const f=this.findNearestMatchOffset(n,u,a);f!==-1&&(a=f,h=f+u.length)}}const d=this.resolveDomPoint(a,s),c=this.resolveDomPoint(h,s);if(!d||!c)return null;const g=document.createRange();try{return g.setStart(d.node,d.offset),g.setEnd(c.node,c.offset),g}catch{return null}}buildVisibleDocumentText(e){let t="";for(let i=0;i<e.length;i++){const s=e[i].node.textContent||"";for(let n=0;n<s.length;n++){const r=s[n];this.virtualMarkerRegex.test(r)||(t+=r)}}return t}findNearestMatchOffset(e,t,i){const s=t.toLowerCase();let n=e.toLowerCase().indexOf(s);if(n===-1)return-1;let r=n,o=Math.abs(n-i);for(;n!==-1;){const l=Math.abs(n-i);if(l<o&&(o=l,r=n),l===0)return n;n=e.toLowerCase().indexOf(s,n+1)}return r}scheduleLiveRefresh(e){this.liveRefreshTimer&&clearTimeout(this.liveRefreshTimer);const t=this.currentQuery;this.liveRefreshTimer=setTimeout(()=>{!this.isVisible||!t||this.performSearch(t,e,!1)},90)}updateStatus(e,t=!1){if(this.statusDiv){if(!t&&Date.now()<this.statusFreezeUntil)return;this.statusDiv.textContent=e}}showTransientStatus(e,t=900){this.statusFreezeUntil=Date.now()+t,this.updateStatus(e,!0),this.statusResetTimer&&clearTimeout(this.statusResetTimer),this.statusResetTimer=setTimeout(()=>{this.statusFreezeUntil=0,this.syncMatchStatus()},t)}syncMatchStatus(){if(!this.currentQuery){this.updateStatus("",!0);return}if(this.currentResults.length===0||this.currentIndex<0){this.updateStatus("No matches",!0);return}this.updateStatus(`${this.currentResults.length} matches (showing ${this.currentIndex+1}/${this.currentResults.length})`,!0)}isValidRegex(e){try{const t=this.searchOptions.caseSensitive?"g":"gi";return new RegExp(e,t),!0}catch{return!1}}captureSelectionState(){this.editor&&(this.savedSelection=this.editor.getSelection(),this.savedCursor=this.editor.getCursor().position)}restoreSelectionState(){this.editor&&(this.savedSelection?this.editor.setSelection(this.savedSelection):this.savedCursor&&this.editor.setCursor(this.savedCursor),this.savedSelection=void 0,this.savedCursor=null)}detectCustomHighlightSupport(){try{const e=CSS,t=window.Highlight;return!!e.highlights&&!!t}catch{return!1}}buildVisibleToDomMap(e){const t=[0];let i=0;for(let s=0;s<e.length;s++){const n=e[s];this.virtualMarkerRegex.test(n)||(i+=1,t[i]=s+1)}return t}ensureHighlightStyles(){if(document.getElementById(this.highlightStyleId))return;const e=document.createElement("style");e.id=this.highlightStyleId,e.textContent=`
94
153
  ::highlight(${this.highlightMatchName}) {
95
154
  background: var(--lce-search-match-bg, rgba(255, 214, 10, 0.34));
96
155
  border-radius: 2px;
@@ -99,32 +158,50 @@
99
158
  background: var(--lce-search-active-bg, rgba(255, 154, 0, 0.45));
100
159
  border-radius: 2px;
101
160
  }
102
- `,document.head.appendChild(e)}destroy(){this.searchDebounceTimer&&(clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=null),this.liveRefreshTimer&&(clearTimeout(this.liveRefreshTimer),this.liveRefreshTimer=null),this.statusResetTimer&&(clearTimeout(this.statusResetTimer),this.statusResetTimer=null),this.clearHighlights(),this.searchUI&&this.searchUI.parentNode&&this.searchUI.parentNode.removeChild(this.searchUI),this.editor&&this.editorChangeHandler&&this.editor.off("change",this.editorChangeHandler),this.editorChangeHandler=null,this.findInput=null,this.replaceInputEl=null,this.statusDiv=null,this.modeDiv=null,this.caseSensitiveInput=null,this.wholeWordInput=null,this.regexInput=null,this.searchUI=null;const e=document.getElementById(this.highlightStyleId);e!=null&&e.parentNode&&e.parentNode.removeChild(e),this.editor=null}};W.css={root:"lce-search-ui",row:"lce-search-row",options:"lce-search-options",optionLabel:"lce-search-option",optionInput:"lce-search-option-input",caseSensitive:"search-case-sensitive",wholeWord:"search-whole-word",regex:"search-regex",meta:"lce-search-meta",findInput:"search-find-input",replaceInput:"search-replace-input",inputBase:"lce-search-input",replaceInputLayout:"lce-search-replace",prevButton:"search-prev",nextButton:"search-next",closeButton:"search-close",buttonBase:"lce-search-btn",status:"search-status",statusLayout:"lce-search-status",mode:"search-mode",modeLayout:"lce-search-mode"};let ie=W;class se{constructor(){this.name="bracket-matching",this.editor=null,this.bracketPairs={"(":")","[":"]","{":"}","<":">"},this.reverseBracketPairs={")":"(","]":"[","}":"{",">":"<"},this.currentMatch=null}setup(e){this.editor=e,e.on("cursor",()=>{this.updateBracketMatching()}),e.on("change",()=>{this.updateBracketMatching()})}updateBracketMatching(){if(!this.editor)return;const e=this.editor.getCursor(),t=this.editor.getValue();this.clearBracketHighlighting();const i=this.getBracketAtPosition(t,e.position);if(!i)return;const s=this.findMatchingBracket(t,i);s&&(this.currentMatch=s,this.highlightBrackets(s))}getBracketAtPosition(e,t){const i=e.split(`
103
- `);if(t.line>=i.length)return null;const s=i[t.line];if(t.column>=s.length)return null;const n=s[t.column];return this.bracketPairs[n]||this.reverseBracketPairs[n]?{char:n,position:t}:null}findMatchingBracket(e,t){const i=e.split(`
104
- `),s=t.position.line,n=t.position.column,r=t.char;return this.bracketPairs[r]?this.findClosingBracket(e,i,s,n,r):this.reverseBracketPairs[r]?this.findOpeningBracket(e,i,s,n,r):null}findClosingBracket(e,t,i,s,n){const r=this.bracketPairs[n];let o=0;for(let a=i;a<t.length;a++){const h=t[a],l=a===i?s:0;for(let c=l;c<h.length;c++){const d=h[c];if(d===n)o++;else if(d===r&&(o--,o===0))return{open:{start:{line:i,column:s},end:{line:i,column:s+1}},close:{start:{line:a,column:c},end:{line:a,column:c+1}},type:n}}}return null}findOpeningBracket(e,t,i,s,n){const r=this.reverseBracketPairs[n];let o=0;for(let a=i;a>=0;a--){const h=t[a],l=a===i?s:h.length-1;for(let c=l;c>=0;c--){const d=h[c];if(d===n)o++;else if(d===r&&(o--,o===0))return{open:{start:{line:a,column:c},end:{line:a,column:c+1}},close:{start:{line:i,column:s},end:{line:i,column:s+1}},type:r}}}return null}highlightBrackets(e){}clearBracketHighlighting(){this.currentMatch=null}getCurrentMatch(){return this.currentMatch}destroy(){this.clearBracketHighlighting(),this.editor=null}}class ne{constructor(){this.name="code-folding",this.editor=null,this.foldIndicators=[],this.foldingUI=null,this.pendingUpdateRaf=null,this.lastSnapshot="",this.changeHandler=null}setup(e){this.editor=e,e.registerCommand("fold",()=>{this.foldAtCursor()}),e.registerCommand("unfold",()=>{this.unfoldAtCursor()}),e.registerCommand("foldAll",()=>{this.foldAll()}),e.registerCommand("unfoldAll",()=>{this.unfoldAll()}),this.changeHandler=()=>{this.scheduleFoldIndicatorUpdate()},e.on("change",this.changeHandler),this.createFoldingUI(),this.scheduleFoldIndicatorUpdate()}createFoldingUI(){if(!this.editor)return;const e=this.editor.getView().getContentElement(),t=e.closest(".rte-source-editor-modal")||e.parentElement;t&&(this.foldingUI=document.createElement("div"),this.foldingUI.style.cssText=`
161
+ `,document.head.appendChild(e)}destroy(){this.searchDebounceTimer&&(clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=null),this.liveRefreshTimer&&(clearTimeout(this.liveRefreshTimer),this.liveRefreshTimer=null),this.statusResetTimer&&(clearTimeout(this.statusResetTimer),this.statusResetTimer=null),this.clearHighlights(),this.searchUI&&this.searchUI.parentNode&&this.searchUI.parentNode.removeChild(this.searchUI),this.editor&&this.editorChangeHandler&&this.editor.off("change",this.editorChangeHandler),this.editorChangeHandler=null,this.findInput=null,this.replaceInputEl=null,this.statusDiv=null,this.modeDiv=null,this.caseSensitiveInput=null,this.wholeWordInput=null,this.regexInput=null,this.searchUI=null;const e=document.getElementById(this.highlightStyleId);e?.parentNode&&e.parentNode.removeChild(e),this.editor=null}};K.css={root:"lce-search-ui",row:"lce-search-row",options:"lce-search-options",optionLabel:"lce-search-option",optionInput:"lce-search-option-input",caseSensitive:"search-case-sensitive",wholeWord:"search-whole-word",regex:"search-regex",meta:"lce-search-meta",findInput:"search-find-input",replaceInput:"search-replace-input",inputBase:"lce-search-input",replaceInputLayout:"lce-search-replace",prevButton:"search-prev",nextButton:"search-next",closeButton:"search-close",buttonBase:"lce-search-btn",status:"search-status",statusLayout:"lce-search-status",mode:"search-mode",modeLayout:"lce-search-mode"};let re=K,oe=0;class le{constructor(){this.name="bracket-matching",this.editor=null,this.bracketPairs={"(":")","[":"]","{":"}","<":">"},this.reverseBracketPairs={")":"(","]":"[","}":"{",">":"<"},this.highlightId=++oe,this.highlightName=`editora-bracket-match-${this.highlightId}`,this.highlightStyleId=`editora-bracket-match-style-${this.highlightId}`,this.currentMatch=null,this.hasCustomHighlightSupport=!1,this.observer=null,this.pendingUpdateRaf=null,this.updateRequestVersion=0,this.cursorHandler=null,this.changeHandler=null}setup(e){this.editor=e,this.hasCustomHighlightSupport=this.detectCustomHighlightSupport(),this.hasCustomHighlightSupport&&(this.ensureHighlightStyles(),this.observeContentMutations()),this.cursorHandler=()=>{this.scheduleBracketUpdate()},this.changeHandler=()=>{this.scheduleBracketUpdate()},e.on("cursor",this.cursorHandler),e.on("change",this.changeHandler),this.scheduleBracketUpdate()}scheduleBracketUpdate(){this.updateRequestVersion+=1;const e=this.updateRequestVersion;this.pendingUpdateRaf!==null&&typeof cancelAnimationFrame=="function"&&(cancelAnimationFrame(this.pendingUpdateRaf),this.pendingUpdateRaf=null);const t=()=>{e===this.updateRequestVersion&&(this.pendingUpdateRaf=null,this.updateBracketMatching())};if(typeof requestAnimationFrame=="function"){this.pendingUpdateRaf=requestAnimationFrame(()=>{this.pendingUpdateRaf=requestAnimationFrame(t)});return}t()}updateBracketMatching(){if(!this.editor)return;const e=this.editor.getCursor(),t=this.editor.getValue();this.clearBracketHighlighting();const i=this.getBracketNearPosition(t,e.position);if(!i)return;const s=this.findMatchingBracket(t,i);s&&(this.currentMatch=s,this.highlightBrackets(s))}getBracketNearPosition(e,t){const i=e.split(`
162
+ `);if(t.line<0||t.line>=i.length)return null;const s=[{line:t.line,column:t.column}];t.column>0&&s.push({line:t.line,column:t.column-1});for(const n of s){const r=this.getBracketAtPosition(i,n);if(r)return r}return null}getBracketAtPosition(e,t){if(t.line<0||t.line>=e.length)return null;const i=e[t.line];if(t.column<0||t.column>=i.length)return null;const s=i[t.column];return this.bracketPairs[s]||this.reverseBracketPairs[s]?{char:s,position:t}:null}findMatchingBracket(e,t){const i=e.split(`
163
+ `),s=t.position.line,n=t.position.column,r=t.char;return this.bracketPairs[r]?this.findClosingBracket(i,s,n,r):this.reverseBracketPairs[r]?this.findOpeningBracket(i,s,n,r):null}findClosingBracket(e,t,i,s){const n=this.bracketPairs[s];let r=0;for(let o=t;o<e.length;o++){const l=e[o],a=o===t?i:0;for(let h=a;h<l.length;h++){const d=l[h];if(d===s)r++;else if(d===n&&(r--,r===0))return{open:{start:{line:t,column:i},end:{line:t,column:i+1}},close:{start:{line:o,column:h},end:{line:o,column:h+1}},type:s}}}return null}findOpeningBracket(e,t,i,s){const n=this.reverseBracketPairs[s];let r=0;for(let o=t;o>=0;o--){const l=e[o],a=o===t?i:l.length-1;for(let h=a;h>=0;h--){const d=l[h];if(d===s)r++;else if(d===n&&(r--,r===0))return{open:{start:{line:o,column:h},end:{line:o,column:h+1}},close:{start:{line:t,column:i},end:{line:t,column:i+1}},type:n}}}return null}highlightBrackets(e){if(!this.editor||!this.hasCustomHighlightSupport)return;const t=this.editor.getView(),i=t.createDomRangeFromRange(e.open),s=t.createDomRangeFromRange(e.close);if(!(!i||!s))try{const n=CSS,r=window.Highlight;if(!n.highlights||!r)return;n.highlights.set(this.highlightName,new r(i,s))}catch{}}clearBracketHighlighting(){if(this.currentMatch=null,!!this.hasCustomHighlightSupport)try{CSS.highlights?.delete(this.highlightName)}catch{}}observeContentMutations(){if(!this.editor||typeof MutationObserver>"u")return;const e=this.editor.getView().getContentElement();this.observer=new MutationObserver(()=>{this.clearBracketHighlighting(),this.scheduleBracketUpdate()}),this.observer.observe(e,{childList:!0,subtree:!0,characterData:!0})}detectCustomHighlightSupport(){try{if(typeof CSS>"u"||typeof window>"u")return!1;const e=CSS,t=window.Highlight;return!!e.highlights&&!!t}catch{return!1}}ensureHighlightStyles(){if(typeof document>"u"||document.getElementById(this.highlightStyleId))return;const e=document.createElement("style");e.id=this.highlightStyleId,e.textContent=`
164
+ ::highlight(${this.highlightName}) {
165
+ background-color: var(--lce-bracket-match-bg, rgba(86, 156, 214, 0.4));
166
+ text-decoration: underline solid var(--lce-bracket-match-border, rgba(156, 220, 254, 0.95)) 2px;
167
+ }
168
+ `,document.head.appendChild(e)}getCurrentMatch(){return this.currentMatch}destroy(){if(this.pendingUpdateRaf!==null&&typeof cancelAnimationFrame=="function"&&(cancelAnimationFrame(this.pendingUpdateRaf),this.pendingUpdateRaf=null),this.clearBracketHighlighting(),this.observer?.disconnect(),this.observer=null,this.editor&&this.cursorHandler&&this.editor.off("cursor",this.cursorHandler),this.editor&&this.changeHandler&&this.editor.off("change",this.changeHandler),typeof document<"u"){const e=document.getElementById(this.highlightStyleId);e?.parentNode&&e.parentNode.removeChild(e)}this.cursorHandler=null,this.changeHandler=null,this.editor=null}}class ae{constructor(){this.name="code-folding",this.lineHeight=21,this.voidMarkupTags=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),this.nonFoldableInlineMarkupTags=new Set(["a","abbr","b","bdi","bdo","button","cite","code","data","del","dfn","em","i","ins","kbd","label","mark","output","q","ruby","s","samp","small","span","strong","sub","sup","time","u","var"]),this.rawTextMarkupTags=new Set(["script","style","textarea","title"]),this.editor=null,this.foldingUI=null,this.pendingUpdateRaf=null,this.lastSnapshot="",this.lastParsedText=null,this.changeHandler=null,this.foldRegions=[],this.foldSnapshots=new Map,this.isDisplayingFolded=!1,this.cachedLineInfo=null}setup(e){this.editor=e,e.registerCommand("fold",()=>{this.foldAtCursor()}),e.registerCommand("unfold",()=>{this.unfoldAtCursor()}),e.registerCommand("foldAll",()=>{this.foldAll()}),e.registerCommand("unfoldAll",()=>{this.unfoldAll()}),this.changeHandler=()=>{this.syncFoldingState()},e.on("change",this.changeHandler),this.createFoldingUI(),this.syncFoldingState()}onKeyDown(e){}onMouseDown(e){}createFoldingUI(){if(!this.editor)return;const e=this.editor.getView().getContentElement().closest('[data-lce-editor-container="true"]');e&&(this.foldingUI=document.createElement("div"),this.foldingUI.setAttribute("data-lce-folding-ui","true"),this.foldingUI.style.cssText=`
105
169
  position: absolute;
106
- left: 40px;
170
+ left: 0;
107
171
  top: 0;
108
172
  bottom: 0;
109
173
  width: 20px;
110
174
  pointer-events: none;
111
- z-index: 2;
112
- `,t.appendChild(this.foldingUI))}scheduleFoldIndicatorUpdate(){this.pendingUpdateRaf===null&&(this.pendingUpdateRaf=requestAnimationFrame(()=>{this.pendingUpdateRaf=null,this.updateFoldIndicators()}))}updateFoldIndicators(){if(!this.editor||!this.foldingUI)return;const e=this.editor.getValue();if(e===this.lastSnapshot)return;this.lastSnapshot=e,this.foldingUI.innerHTML="",this.foldIndicators=[];const t=e.split(`
113
- `),i=this.findFoldableLines(t),s=document.createDocumentFragment();i.forEach(n=>{const r=this.createFoldIndicator(n);s.appendChild(r),this.foldIndicators.push(r)}),this.foldingUI.appendChild(s)}findFoldableLines(e){const t=[];for(let i=0;i<e.length;i++){const s=e[i].trim();(s.startsWith("{")||s.startsWith("function")||s.startsWith("class")||s.startsWith("if")||s.includes("=>")||s.startsWith("for")||s.startsWith("while")||s.startsWith("try"))&&t.push(i)}return t}createFoldIndicator(e){const t=document.createElement("div");return t.style.cssText=`
175
+ z-index: 3;
176
+ `,e.appendChild(this.foldingUI))}syncFoldingState(){if(!this.editor)return;const e=this.editor.getValue(),t=this.foldSnapshots;e!==this.lastParsedText&&(this.foldRegions=this.buildFoldRegions(e),this.pruneInvalidFolds(e,t),this.lastParsedText=e),this.hasActiveFolds()?this.applyFoldedDisplay():this.restoreFullDisplay(),this.rememberActiveFoldSnapshots(e),this.scheduleFoldIndicatorUpdate()}scheduleFoldIndicatorUpdate(){this.pendingUpdateRaf===null&&(this.pendingUpdateRaf=requestAnimationFrame(()=>{this.pendingUpdateRaf=null,this.updateFoldIndicators()}))}updateFoldIndicators(){if(!this.editor||!this.foldingUI)return;const e=this.editor.getValue(),t=this.getActiveFolds().map(r=>this.getFoldKey(r)).join("|"),i=`${e}::${t}`;if(i===this.lastSnapshot)return;this.lastSnapshot=i,this.foldingUI.innerHTML="";const s=this.getRenderableActiveFolds(),n=document.createDocumentFragment();for(const r of this.foldRegions){const o=this.toDisplayLine(r,s);if(o===null)continue;const l=this.isFoldActive(r),a=this.createFoldIndicator(r,o,l);n.appendChild(a)}this.foldingUI.appendChild(n)}buildFoldRegions(e){const t=this.buildBracketFoldRegions(e),i=this.shouldIncludeMarkupFolds(e)?this.buildMarkupFoldRegions(e):[];return this.mergeFoldRegions([...t,...i])}buildBracketFoldRegions(e){const t=e.split(`
177
+ `),i=[],s=[],n={"{":"}","[":"]","(":")"},r={"}":"{","]":"[",")":"("};for(let o=0;o<t.length;o++){const l=t[o];for(let a=0;a<l.length;a++){const h=l[a];if(n[h]){i.push({char:h,line:o,column:a});continue}const d=r[h];if(!d)continue;let c=-1;for(let f=i.length-1;f>=0;f--)if(i[f].char===d){c=f;break}if(c===-1)continue;const g=i.splice(c,1)[0];if(g.line>=o)continue;const u=t[g.line]?.length||0,p={start:{line:g.line,column:u},end:{line:o,column:0},collapsed:!1,level:c};this.isValidFoldRegion(p)&&s.push(p)}}return s.sort((o,l)=>o.start.line!==l.start.line?o.start.line-l.start.line:o.end.line!==l.end.line?o.end.line-l.end.line:o.start.column-l.start.column),s}shouldIncludeMarkupFolds(e){return/<!DOCTYPE\b/i.test(e)||/<[A-Za-z][\w:-]*(?:\s|>)/.test(e)&&/<\/[A-Za-z][\w:-]*\s*>/.test(e)}buildMarkupFoldRegions(e){const{lineStarts:t,lines:i}=this.buildLineStarts(e),s=[],n=[];let r=0;for(;r<e.length;){if(e[r]!=="<"){r+=1;continue}if(e.startsWith("<!--",r)){const l=e.indexOf("-->",r+4);r=l===-1?e.length:l+3;continue}if(e.startsWith("<![CDATA[",r)){const l=e.indexOf("]]>",r+9);r=l===-1?e.length:l+3;continue}const o=this.parseMarkupTag(e,r,t,i);if(!o){r+=1;continue}if(r=o.endOffset,o.isClosing){const l=n.findIndex(d=>d.name===o.name);if(l===-1)continue;const a=n.splice(l,1)[0],h=this.createMarkupFoldRegion(a.openEndLine,o.startLine,i);h&&s.push(h);continue}if(!(o.isSelfClosing||this.voidMarkupTags.has(o.name))){if(this.rawTextMarkupTags.has(o.name)){const l=this.findClosingMarkupTag(e,o.endOffset,o.name,t,i);if(l){const a=this.createMarkupFoldRegion(o.endLine,l.startLine,i);a&&s.push(a),r=l.endOffset}continue}this.nonFoldableInlineMarkupTags.has(o.name)||n.unshift({name:o.name,openEndLine:o.endLine})}}return s}parseMarkupTag(e,t,i,s){if(e[t]!=="<")return null;const n=e[t+1];if(!n||n!=="/"&&!/[A-Za-z]/.test(n))return null;const r=n==="/";let o=t+(r?2:1);const l=o;for(;o<e.length&&/[A-Za-z0-9:-]/.test(e[o]);)o+=1;const a=o;if(o===l)return null;let h=null;for(;o<e.length;){const p=e[o];if(h){p===h&&(h=null),o+=1;continue}if(p==='"'||p==="'"){h=p,o+=1;continue}if(p===">")break;o+=1}if(o>=e.length||e[o]!==">")return null;const d=e.slice(l,a).toLowerCase();if(!d)return null;const c=e.slice(t,o+1),g=this.offsetToLine(t,i,s),u=this.offsetToLine(o,i,s);return{name:d,isClosing:r,isSelfClosing:!r&&/\/\s*>$/.test(c),startLine:g,endLine:u,endOffset:o+1}}findClosingMarkupTag(e,t,i,s,n){const r=`</${i}`,o=e.toLowerCase();let l=o.indexOf(r,t);for(;l!==-1;){const a=this.parseMarkupTag(e,l,s,n);if(a&&a.isClosing&&a.name===i)return{startLine:a.startLine,endOffset:a.endOffset};l=o.indexOf(r,l+r.length)}return null}createMarkupFoldRegion(e,t,i){if(e>=t)return null;const s=Math.max(0,Math.min(e,i.length-1)),n=Math.max(0,Math.min(t,i.length-1)),r={start:{line:s,column:i[s]?.length||0},end:{line:n,column:0},collapsed:!1,level:0};return this.isValidFoldRegion(r)?r:null}mergeFoldRegions(e){const t=new Map;for(const i of e)this.isValidFoldRegion(i)&&t.set(this.getFoldKey(i),i);return[...t.values()].sort((i,s)=>i.start.line!==s.start.line?i.start.line-s.start.line:i.end.line!==s.end.line?i.end.line-s.end.line:i.start.column-s.start.column)}createFoldIndicator(e,t,i){const s=document.createElement("button");return s.type="button",s.style.cssText=`
114
178
  position: absolute;
115
179
  left: 0;
116
- top: ${e*21}px;
180
+ top: ${t*this.lineHeight}px;
117
181
  width: 20px;
118
- height: 21px;
182
+ height: ${this.lineHeight}px;
119
183
  display: flex;
120
184
  align-items: center;
121
185
  justify-content: center;
122
186
  cursor: pointer;
123
187
  pointer-events: auto;
124
188
  color: var(--editor-gutter-foreground, #858585);
189
+ background: transparent;
190
+ border: none;
191
+ padding: 0;
125
192
  font-size: 10px;
126
193
  user-select: none;
127
- `,t.innerHTML="▶",t.title="Code folding not yet implemented - click shows fold indicators",t.addEventListener("click",()=>{}),t}foldAtCursor(){}unfoldAtCursor(){}foldAll(){}unfoldAll(){}destroy(){this.pendingUpdateRaf!==null&&(cancelAnimationFrame(this.pendingUpdateRaf),this.pendingUpdateRaf=null),this.editor&&this.changeHandler&&this.editor.off("change",this.changeHandler),this.foldingUI&&this.foldingUI.parentNode&&this.foldingUI.parentNode.removeChild(this.foldingUI),this.changeHandler=null,this.lastSnapshot="",this.foldingUI=null,this.foldIndicators=[],this.editor=null}}class re{constructor(){this.name="syntax-highlighting",this.editor=null,this.currentTheme="dark",this.currentLanguage=null,this.modes=new Map}setup(e){this.editor=e,this.registerMode("html",{name:"html",highlight:(t,i)=>this._highlightHTML(t,i)}),this.registerMode("javascript",{name:"javascript",highlight:(t,i)=>this._highlightJS(t,i)}),this.registerMode("typescript",{name:"typescript",highlight:(t,i)=>this._highlightJS(t,i)}),this.registerMode("php",{name:"php",highlight:(t,i)=>this._highlightPHP(t,i)})}setTheme(e){this.currentTheme=e}setLanguage(e){this.currentLanguage=e}registerMode(e,t){this.modes.set(e.toLowerCase(),t)}getSyntaxColors(){return this.currentTheme==="dark"?{tag:"#569cd6",comment:"#6a9955",attrName:"#9cdcfe",attrValue:"#ce9178",styleProp:"#c586c0",styleVal:"#dcdcaa",doctype:"#808080",text:"#d4d4d4",keyword:"#c586c0",string:"#ce9178",number:"#b5cea8",variable:"#9cdcfe"}:{tag:"#0000ff",comment:"#008000",attrName:"#001080",attrValue:"#a31515",styleProp:"#6a00a8",styleVal:"#804000",doctype:"#444444",text:"#000000",keyword:"#000080",string:"#a31515",number:"#0086b3",variable:"#001080"}}highlight(e,t){const i=this.getSyntaxColors(),s=(t||this.currentLanguage||"html").toLowerCase();return(this.modes.get(s)||this.modes.get("html")).highlight(e,i)}highlightHTML(e){return this.highlight(e,"html")}escapeHTML(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;").replace(/'/g,"&#39;")}unescapeEntitiesRepeated(e){let t=e||"";for(let i=0;i<5;i++){const s=t;if(t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'"),t===s)break}return t}_highlightHTML(e,t){const i=t,s=h=>this.escapeHTML(h);let n=s(e);const r=h=>{let l=h.replace(/&quot;/g,'"').replace(/&#39;/g,"'");return l=l.replace(/(\/\*[\s\S]*?\*\/)/g,`<span style="color: ${i.comment};">$1</span>`),l=l.replace(/([a-zA-Z-]+)(\s*:\s*)([^;{]+)(;?)/g,(c,d,p,u,g)=>{const f=String(u).trim(),y=s(f);return`<span style="color: ${i.styleProp};">${d}</span>${p}<span style="color: ${i.styleVal};">${y}</span>${g}`}),l},o=[];try{e.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,(h,l,c)=>(o.push({attrs:String(l||""),inner:String(c||"")}),h))}catch{}let a=0;return n=n.replace(/(&lt;script\b([^&>]*)&gt;)([\s\S]*?)(&lt;\/script&gt;)/gi,(h,l,c,d,p)=>{var u,g;const f=((u=o[a++])==null?void 0:u.inner)??this.unescapeEntitiesRepeated(d||"");(((g=o[a-1])==null?void 0:g.attrs)||c||"").toLowerCase();const y=this._highlightJS(f,i);return`${l}${y}${p}`}),n=n.replace(/(&lt;style\b[^&]*&gt;)([\s\S]*?)(&lt;\/style&gt;)/gi,(h,l,c,d)=>{const p=r(c);return`${l}${p}${d}`}),n=n.replace(/(&lt;!--[\s\S]*?--&gt;)/g,`<span style="color: ${i.comment};">$1</span>`),n=n.replace(/(&lt;!DOCTYPE[\s\S]*?&gt;)/i,`<span style="color: ${i.doctype};">$1</span>`),n=n.replace(/(&lt;\/?\s*)([^\s&>\/]+)([\s\S]*?)(\/?&gt;)/g,(h,l,c,d,p)=>{const u=`<span style="color: ${i.tag};">${c}</span>`;let g=d;return g=g.replace(/([\w:-]+)(\s*=\s*)((&quot;[\s\S]*?&quot;|&#39;[\s\S]*?&#39;|[^\s&>]+))/g,(f,y,k,v)=>{const C=String(y).toLowerCase(),E=`<span style="color: ${i.attrName};">${y}</span>`;let S=v,b="";v.startsWith("&quot;")&&v.endsWith("&quot;")?(S=v.slice(6,-6),b="&quot;"):v.startsWith("&#39;")&&v.endsWith("&#39;")&&(S=v.slice(5,-5),b="&#39;");let T=v;if(C==="style"){const I=S.replace(/([\w-]+)\s*:\s*([^;]+)(;?)/g,(B,N,$,O)=>`<span style="color: ${i.styleProp};">${N}</span>:<span style="color: ${i.styleVal};">${$.trim()}</span>${O}`);b?T=`${b}${I}${b}`:T=I,T=`<span style="color: ${i.attrValue};">${T}</span>`}else b&&(T=`${b}${S}${b}`),T=`<span style="color: ${i.attrValue};">${T}</span>`;return`${E}${k}${T}`}),`${l}${u}${g}${p}`}),n}_highlightJS(e,t){const i=this.unescapeEntitiesRepeated(e);this.escapeHTML(i);const s=[],n=d=>{let p="",u=d;do p=String.fromCharCode(97+u%26)+p,u=Math.floor(u/26)-1;while(u>=0);return p||"a"},r=d=>`\0${n(d)}\0`,o=d=>{const p=s.length;return s.push(d),r(p)};let a;const h=/(\/\*[\s\S]*?\*\/)|(\/\/[^\n\r]*)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)/g;let l=0,c="";for(;a=h.exec(i);){const d=a.index;l<d&&(c+=this.escapeHTML(i.slice(l,d)));const p=a[0];/^\/\*/.test(p)||/^\/\//.test(p)?c+=o(`<span style="color: ${t.comment};">${this.escapeHTML(p)}</span>`):c+=o(`<span style="color: ${t.string};">${this.escapeHTML(p)}</span>`),l=h.lastIndex}return l<i.length&&(c+=this.escapeHTML(i.slice(l))),c=c.replace(/\b(0x[0-9a-fA-F]+|\d+\.?\d*|\d*\.\d+)\b/g,(d,p,u)=>{const g=c[u-1]||"",f=c[u+d.length]||"";return g==="&"||g==="#"||f===";"||f==="#"?d:`<span style="color: ${t.number};">${d}</span>`}),c=c.replace(/\b(const|let|var|function|class|if|else|return|for|while|switch|case|break|import|from|export|extends|new|try|catch|finally|throw|await|async|interface|type)\b/g,`<span style="color: ${t.keyword};">$1</span>`),c.replace(/\u0000([a-z]+)\u0000/g,(d,p)=>{let u=0;for(let g=0;g<p.length;g++)u=u*26+(p.charCodeAt(g)-97+1);return u=u-1,s[u]||""})}_highlightPHP(e,t){const i=this.unescapeEntitiesRepeated(e);let s=this.escapeHTML(i);const n=[],r=u=>{let g="",f=u;do g=String.fromCharCode(97+f%26)+g,f=Math.floor(f/26)-1;while(f>=0);return g||"a"},o=u=>{const g=n.length;return n.push(u),`\0${r(g)}\0`},a=(u,g)=>{const f=s.indexOf(u);return f===-1?!1:(s=s.slice(0,f)+g+s.slice(f+u.length),!0)};let h;const l=/\/\*[\s\S]*?\*\//g,c=/\/\/[^\n\r]*/g,d=/\#([^\n\r]*)/g,p=/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g;for(;h=l.exec(i);){const u=h[0];a(this.escapeHTML(u),o(`<span style="color: ${t.comment};">${this.escapeHTML(u)}</span>`))}for(;h=c.exec(i);){const u=h[0];a(this.escapeHTML(u),o(`<span style="color: ${t.comment};">${this.escapeHTML(u)}</span>`))}for(;h=d.exec(i);){const u=h[0];a(this.escapeHTML(u),o(`<span style="color: ${t.comment};">${this.escapeHTML(u)}</span>`))}for(;h=p.exec(i);){const u=h[0];a(this.escapeHTML(u),o(`<span style="color: ${t.string};">${this.escapeHTML(u)}</span>`))}return s=s.replace(/(\$[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)/g,`<span style="color: ${t.variable};">$1</span>`),s=s.replace(/\b(echo|print|function|class|if|else|elseif|foreach|as|return|namespace|use|new|extends|public|protected|private|static)\b/g,`<span style="color: ${t.keyword};">$1</span>`),s=s.replace(/\u0000([a-z]+)\u0000/g,(u,g)=>{let f=0;for(let y=0;y<g.length;y++)f=f*26+(g.charCodeAt(y)-97+1);return f=f-1,n[f]||""}),s}shouldHighlight(e){return/<\/?[\w:-]+|<!--/.test(e)}destroy(){this.editor=null,this.modes.clear()}}function oe(w,e){const t={...e};return t.extensions||(t.extensions=[]),t.extensions.some(i=>i.name==="keymap")||t.extensions.unshift(new J(t.keymap)),t.extensions.some(i=>i.name==="transaction")||t.extensions.unshift(new Y),new X(w,t)}const P='[data-theme="dark"], .dark, .editora-theme-dark',le=`/* Source Editor Dialog Styles */
194
+ `,s.textContent=i?"▶":"▼",s.title=i?"Expand folded region":"Collapse region",s.setAttribute("aria-label",s.title),s.addEventListener("mousedown",n=>{n.preventDefault()}),s.addEventListener("click",n=>{n.preventDefault(),n.stopPropagation(),this.toggleFold(e)}),s}toggleFold(e){this.editor&&(this.isFoldActive(e)?this.editor.unfold(e):this.editor.fold(e),this.syncFoldingState())}foldAtCursor(){if(!this.editor)return;const e=this.editor.getCursor().position.line,t=this.findBestRegionForLine(e,!1);t&&(this.editor.fold(t),this.syncFoldingState())}unfoldAtCursor(){if(!this.editor)return;const e=this.editor.getCursor().position.line,t=this.findBestRegionForLine(e,!0);t&&(this.editor.unfold(t),this.syncFoldingState())}foldAll(){if(!this.editor)return;const e=this.getTopLevelFoldRegions(this.foldRegions);for(const t of e)this.editor.fold(t);this.syncFoldingState()}unfoldAll(){if(!this.editor)return;const e=this.getActiveFolds();for(const t of e)this.editor.unfold(t);this.syncFoldingState()}applyFoldedDisplay(){if(!this.editor)return;const e=this.getRenderableActiveFolds();if(e.length===0){this.restoreFullDisplay();return}const t=this.buildFoldedProjection(this.editor.getValue(),e);this.withPreservedSelection(()=>{this.renderEditorText(t.text),this.renderFoldPlaceholders(t),this.isDisplayingFolded=!0})}restoreFullDisplay(){this.editor&&(this.isDisplayingFolded&&this.withPreservedSelection(()=>{this.renderEditorText(this.editor.getValue())}),this.isDisplayingFolded=!1)}renderEditorText(e){if(!this.editor)return;const t=this.editor;if(typeof t.renderTextWithHighlight=="function"){t.expectingProgrammaticCursor=!0,t.renderTextWithHighlight(e,!1),t.expectingProgrammaticCursor=!1;return}this.editor.getView().setText(e)}buildFoldedProjection(e,t){const{lineStarts:i,lines:s}=this.buildLineStarts(e),n=[...t].sort((h,d)=>this.comparePositions(h.start,d.start));let r="";const o=[];let l=0;for(const h of n){const d=this.positionToOffset(h.start,i,s),c=this.positionToOffset(h.end,i,s),g=e.slice(l,d),u=this.getFoldPlaceholder(h),p=e.slice(d,c);r+=g,r+=u,g&&o.push({type:"text",text:g}),o.push({type:"placeholder",text:u,fold:h,hiddenText:p}),l=c}const a=e.slice(l);return r+=a,a&&o.push({type:"text",text:a}),{text:r,segments:o}}renderFoldPlaceholders(e){if(!this.editor)return;const t=this.editor.getView().getContentElement(),i=new Map,s=document.createDocumentFragment();for(const n of e.segments){if(n.type==="text"){s.appendChild(document.createTextNode(n.text));continue}const r=document.createElement("span"),o=this.getFoldKey(n.fold);r.setAttribute("data-lce-fold-placeholder",o),r.setAttribute("aria-label","Folded region"),r.contentEditable="false",i.set(o,n.hiddenText),r.style.cssText=`
195
+ cursor: text;
196
+ user-select: text;
197
+ pointer-events: auto;
198
+ white-space: pre;
199
+ `,r.textContent=n.text,s.appendChild(r)}t.replaceChildren(s),t.__lceFoldPlaceholderSources=i,this.editor.getView().syncTrailingNewlineMarkerForText(e.text)}getFoldPlaceholder(e){const t=Math.max(1,e.end.line-e.start.line);return` … ${t} ${t===1?"line":"lines"} … `}pruneInvalidFolds(e,t){if(!this.editor)return;const i=this.editor.getFolds().filter(a=>a.collapsed!==!1),s=new Set(i.map(a=>this.getFoldKey(a))),n=[],r=new Set,o=this.getLineInfo(e);for(const a of i){const h=this.findReplacementFold(a,t.get(this.getFoldKey(a)),r,e,o);if(!h)continue;const d=this.getFoldKey(h);n.push(h),r.add(d)}const l=new Set(n.map(a=>this.getFoldKey(a)));for(const a of i)l.has(this.getFoldKey(a))||this.editor.unfold(a);for(const a of n)s.has(this.getFoldKey(a))||this.editor.fold(a)}getActiveFolds(){return this.editor?this.editor.getFolds().filter(e=>e.collapsed!==!1):[]}hasActiveFolds(){return this.getActiveFolds().length>0}getRenderableActiveFolds(){return this.getTopLevelFoldRegions(this.getActiveFolds())}getTopLevelFoldRegions(e){const t=[...e].sort((s,n)=>this.comparePositions(s.start,n.start)),i=[];for(const s of t){const n=i[i.length-1];n&&this.containsRange(n,s)||i.push(s)}return i}toDisplayLine(e,t){let i=0;for(const s of t){if(this.isSameRange(s,e))break;if(this.containsRange(s,e))return null;s.end.line<=e.start.line&&(i+=s.end.line-s.start.line)}return e.start.line-i}findBestRegionForLine(e,t){const i=(t?this.getActiveFolds():this.foldRegions).filter(s=>s.start.line<=e&&s.end.line>=e);return i.length===0?null:(i.sort((s,n)=>{const r=s.end.line-s.start.line,o=n.end.line-n.start.line;return r!==o?r-o:this.comparePositions(s.start,n.start)}),i[0])}findReplacementFold(e,t,i,s,n){const r=this.getFoldKey(e),o=this.foldRegions.find(c=>this.getFoldKey(c)===r&&!i.has(r));if(o)return o;const l=e.end.line-e.start.line,a=t??this.createFoldSnapshot(e,s,n),h=this.foldRegions.filter(c=>!i.has(this.getFoldKey(c))).map(c=>{const g=this.createFoldSnapshot(c,s,n),u=a&&g?.startLineText===a.startLineText?1:0,p=a&&g?.endLineText===a.endLineText?1:0,f=a&&g?.lineSpan===a.lineSpan?1:0;return{region:c,overlaps:this.lineRangeOverlap(e,c),lineDistance:Math.abs(c.start.line-e.start.line)+Math.abs(c.end.line-e.end.line),spanDistance:Math.abs(c.end.line-c.start.line-l),columnDistance:Math.abs(c.start.column-e.start.column)+Math.abs(c.end.column-e.end.column),hiddenTextMatch:a&&g?.hiddenText===a.hiddenText?1:0,boundaryMatchScore:u+p+f}}).sort((c,g)=>c.hiddenTextMatch!==g.hiddenTextMatch?g.hiddenTextMatch-c.hiddenTextMatch:c.boundaryMatchScore!==g.boundaryMatchScore?g.boundaryMatchScore-c.boundaryMatchScore:c.overlaps!==g.overlaps?g.overlaps-c.overlaps:c.lineDistance!==g.lineDistance?c.lineDistance-g.lineDistance:c.spanDistance!==g.spanDistance?c.spanDistance-g.spanDistance:c.columnDistance-g.columnDistance)[0];if(!h)return null;const d=h.lineDistance<=2&&h.spanDistance<=1;return!(h.hiddenTextMatch===1||h.boundaryMatchScore>=2)&&!d?null:h.region}lineRangeOverlap(e,t){const i=Math.max(e.start.line,t.start.line),s=Math.min(e.end.line,t.end.line);return Math.max(0,s-i)}rememberActiveFoldSnapshots(e){const t=new Map,i=this.getLineInfo(e);for(const s of this.getActiveFolds()){const n=this.createFoldSnapshot(s,e,i);n&&t.set(this.getFoldKey(s),n)}this.foldSnapshots=t}createFoldSnapshot(e,t,i=this.getLineInfo(t)){const{lineStarts:s,lines:n}=i;if(n.length===0)return null;const r=this.positionToOffset(e.start,s,n),o=this.positionToOffset(e.end,s,n),l=Math.max(0,Math.min(e.start.line,n.length-1)),a=Math.max(0,Math.min(e.end.line,n.length-1));return{hiddenText:t.slice(r,o),startLineText:n[l]??"",endLineText:n[a]??"",lineSpan:e.end.line-e.start.line}}withPreservedSelection(e){if(!this.editor){e();return}const t=this.editor.getView(),i=t.getContentElement(),s=document.activeElement===i,n=t.getSelectionOffsets(),r=n.isInEditor;if(e(),!r)return;const o=this.remapSelectionOffsetsForVisibleDisplay(n.anchorOffset??n.startOffset,n.focusOffset??n.endOffset);t.setSelectionBoundaryOffsets(o.startOffset,o.endOffset),(s||n.isInEditor)&&this.editor.focus()}remapSelectionOffsetsForVisibleDisplay(e,t){if(!this.editor)return{startOffset:e,endOffset:t};const i=this.editor.getValue(),{lineStarts:s,lines:n}=this.getLineInfo(i),r=this.getRenderableActiveFolds();if(r.length===0){const o=i.length;return{startOffset:Math.max(0,Math.min(e,o)),endOffset:Math.max(0,Math.min(t,o))}}return{startOffset:this.remapOffsetToVisibleBoundary(e,r,s,n,i.length),endOffset:this.remapOffsetToVisibleBoundary(t,r,s,n,i.length)}}remapOffsetToVisibleBoundary(e,t,i,s,n){const r=Math.max(0,Math.min(e,n));for(const o of t){const l=this.positionToOffset(o.start,i,s),a=this.positionToOffset(o.end,i,s);if(r<=l||r>=a)continue;const h=r-l,d=a-r;return h<=d?l:a}return r}buildLineStarts(e){const t=e.split(`
200
+ `),i=new Array(t.length);let s=0;for(let n=0;n<t.length;n++)i[n]=s,s+=t[n].length+1;return{lineStarts:i,lines:t}}getLineInfo(e){if(this.cachedLineInfo?.text===e)return this.cachedLineInfo;const t={text:e,...this.buildLineStarts(e)};return this.cachedLineInfo=t,t}offsetToLine(e,t,i){const s=t.length>0?t[t.length-1]+(i[i.length-1]?.length||0):0,n=Math.max(0,Math.min(e,s));let r=0,o=t.length-1;for(;r<=o;){const l=Math.floor((r+o)/2),a=t[l],h=l+1<t.length?t[l+1]:Number.POSITIVE_INFINITY;if(n<a){o=l-1;continue}if(n>=h){r=l+1;continue}return l}return Math.max(0,Math.min(r,t.length-1))}positionToOffset(e,t,i){const s=Math.max(0,Math.min(e.line,i.length-1)),n=Math.max(0,Math.min(e.column,i[s]?.length||0));return t[s]+n}comparePositions(e,t){return e.line!==t.line?e.line-t.line:e.column-t.column}containsRange(e,t){return this.comparePositions(e.start,t.start)<=0&&this.comparePositions(e.end,t.end)>=0&&!this.isSameRange(e,t)}isSameRange(e,t){return e.start.line===t.start.line&&e.start.column===t.start.column&&e.end.line===t.end.line&&e.end.column===t.end.column}isFoldActive(e){return this.getActiveFolds().some(t=>this.isSameRange(t,e))}isValidFoldRegion(e){return e.start.line<e.end.line&&(e.start.line!==e.end.line||e.start.column!==e.end.column)}getFoldKey(e){return`${e.start.line}:${e.start.column}-${e.end.line}:${e.end.column}`}destroy(){this.pendingUpdateRaf!==null&&(cancelAnimationFrame(this.pendingUpdateRaf),this.pendingUpdateRaf=null),this.editor&&this.changeHandler&&this.editor.off("change",this.changeHandler),this.foldingUI&&this.foldingUI.parentNode&&this.foldingUI.parentNode.removeChild(this.foldingUI),this.restoreFullDisplay(),this.changeHandler=null,this.lastSnapshot="",this.lastParsedText=null,this.foldingUI=null,this.foldRegions=[],this.cachedLineInfo=null,this.editor=null}}class he{constructor(){this.name="syntax-highlighting",this.editor=null,this.currentTheme="dark",this.currentLanguage=null,this.modes=new Map}setup(e){this.editor=e,this.registerMode("html",{name:"html",highlight:(t,i)=>this._highlightHTML(t,i)}),this.registerMode("css",{name:"css",highlight:(t,i)=>this._highlightCSS(t,i)}),this.registerMode("javascript",{name:"javascript",highlight:(t,i)=>this._highlightJS(t,i)}),this.registerMode("js",{name:"javascript",highlight:(t,i)=>this._highlightJS(t,i)}),this.registerMode("jsx",{name:"jsx",highlight:(t,i)=>this._highlightJSX(t,i)}),this.registerMode("typescript",{name:"typescript",highlight:(t,i)=>this._highlightJS(t,i)}),this.registerMode("ts",{name:"typescript",highlight:(t,i)=>this._highlightJS(t,i)}),this.registerMode("tsx",{name:"tsx",highlight:(t,i)=>this._highlightJSX(t,i)}),this.registerMode("json",{name:"json",highlight:(t,i)=>this._highlightJSON(t,i)}),this.registerMode("markdown",{name:"markdown",highlight:(t,i)=>this._highlightMarkdown(t,i)}),this.registerMode("md",{name:"markdown",highlight:(t,i)=>this._highlightMarkdown(t,i)}),this.registerMode("bash",{name:"bash",highlight:(t,i)=>this._highlightShell(t,i)}),this.registerMode("shell",{name:"bash",highlight:(t,i)=>this._highlightShell(t,i)}),this.registerMode("sh",{name:"bash",highlight:(t,i)=>this._highlightShell(t,i)}),this.registerMode("zsh",{name:"bash",highlight:(t,i)=>this._highlightShell(t,i)}),this.registerMode("python",{name:"python",highlight:(t,i)=>this._highlightGenericCode(t,i,"python")}),this.registerMode("py",{name:"python",highlight:(t,i)=>this._highlightGenericCode(t,i,"python")}),this.registerMode("go",{name:"go",highlight:(t,i)=>this._highlightGenericCode(t,i,"go")}),this.registerMode("golang",{name:"go",highlight:(t,i)=>this._highlightGenericCode(t,i,"go")}),this.registerMode("c",{name:"c",highlight:(t,i)=>this._highlightGenericCode(t,i,"c")}),this.registerMode("cpp",{name:"cpp",highlight:(t,i)=>this._highlightGenericCode(t,i,"cpp")}),this.registerMode("c++",{name:"cpp",highlight:(t,i)=>this._highlightGenericCode(t,i,"cpp")}),this.registerMode("cc",{name:"cpp",highlight:(t,i)=>this._highlightGenericCode(t,i,"cpp")}),this.registerMode("cxx",{name:"cpp",highlight:(t,i)=>this._highlightGenericCode(t,i,"cpp")}),this.registerMode("java",{name:"java",highlight:(t,i)=>this._highlightGenericCode(t,i,"java")}),this.registerMode("csharp",{name:"csharp",highlight:(t,i)=>this._highlightGenericCode(t,i,"csharp")}),this.registerMode("cs",{name:"csharp",highlight:(t,i)=>this._highlightGenericCode(t,i,"csharp")}),this.registerMode("rust",{name:"rust",highlight:(t,i)=>this._highlightGenericCode(t,i,"rust")}),this.registerMode("rs",{name:"rust",highlight:(t,i)=>this._highlightGenericCode(t,i,"rust")}),this.registerMode("ruby",{name:"ruby",highlight:(t,i)=>this._highlightGenericCode(t,i,"ruby")}),this.registerMode("rb",{name:"ruby",highlight:(t,i)=>this._highlightGenericCode(t,i,"ruby")}),this.registerMode("sql",{name:"sql",highlight:(t,i)=>this._highlightGenericCode(t,i,"sql")}),this.registerMode("yaml",{name:"yaml",highlight:(t,i)=>this._highlightYAML(t,i)}),this.registerMode("yml",{name:"yaml",highlight:(t,i)=>this._highlightYAML(t,i)}),this.registerMode("xml",{name:"xml",highlight:(t,i)=>this._highlightXML(t,i)}),this.registerMode("svg",{name:"xml",highlight:(t,i)=>this._highlightXML(t,i)}),this.registerMode("vue",{name:"vue",highlight:(t,i)=>this._highlightHTML(t,i)}),this.registerMode("ejs",{name:"ejs",highlight:(t,i)=>this._highlightEJS(t,i)}),this.registerMode("dockerfile",{name:"dockerfile",highlight:(t,i)=>this._highlightDockerfile(t,i)}),this.registerMode("docker",{name:"dockerfile",highlight:(t,i)=>this._highlightDockerfile(t,i)}),this.registerMode("php",{name:"php",highlight:(t,i)=>this._highlightPHP(t,i)}),e.registerCommand("setSyntaxLanguage",t=>{this.setLanguage(t),this.refreshEditorHighlight()})}setTheme(e){this.currentTheme=e}setLanguage(e){this.currentLanguage=e}registerMode(e,t){this.modes.set(e.toLowerCase(),t)}getSyntaxColors(){return this.currentTheme==="dark"?{tag:"#569cd6",comment:"#6a9955",attrName:"#9cdcfe",attrValue:"#ce9178",styleProp:"#c586c0",styleVal:"#dcdcaa",doctype:"#808080",text:"#d4d4d4",keyword:"#c586c0",string:"#ce9178",number:"#b5cea8",variable:"#9cdcfe"}:{tag:"#0000ff",comment:"#008000",attrName:"#001080",attrValue:"#a31515",styleProp:"#6a00a8",styleVal:"#804000",doctype:"#444444",text:"#000000",keyword:"#000080",string:"#a31515",number:"#0086b3",variable:"#001080"}}highlight(e,t){const i=this.getSyntaxColors(),s=this.normalizeLanguageId(t||this.currentLanguage||this.detectLanguage(e)||"html");return(this.modes.get(s)||this.modes.get("html")).highlight(e,i)}highlightHTML(e){return this.highlight(e,"html")}escapeHTML(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;").replace(/'/g,"&#39;")}normalizeLanguageId(e){const t=e.trim().toLowerCase().replace(/^\./,"");return{cjs:"javascript",js:"javascript",javascriptreact:"javascript",jsx:"jsx",mjs:"javascript",mts:"typescript",ts:"typescript",tsx:"tsx",typescriptreact:"tsx",md:"markdown",mdx:"markdown",shell:"bash",sh:"bash",zsh:"bash",console:"bash",terminal:"bash",docker:"dockerfile",dockerfile:"dockerfile",golang:"go",py:"python",cxx:"cpp",cc:"cpp","c++":"cpp",cs:"csharp",rs:"rust",rb:"ruby",yml:"yaml",svg:"xml",vue:"vue",ejs:"ejs"}[t]||t||"html"}restoreHighlightTokens(e,t){return e.replace(/\u0000([a-z]+)\u0000/g,(i,s)=>{let n=0;for(let r=0;r<s.length;r++)n=n*26+(s.charCodeAt(r)-97+1);return n=n-1,t[n]||""})}createTokenStore(e){const t=i=>{let s="",n=i;do s=String.fromCharCode(97+n%26)+s,n=Math.floor(n/26)-1;while(n>=0);return s||"a"};return i=>{const s=e.length;return e.push(i),`\0${t(s)}\0`}}refreshEditorHighlight(){const e=this.editor;e?.renderTextWithHighlight&&e.renderTextWithHighlight(e.getValue(),!0)}unescapeEntitiesRepeated(e){let t=e||"";for(let i=0;i<5;i++){const s=t;if(t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'"),t===s)break}return t}detectLanguage(e){const t=e.trim();if(!t)return null;if(/^<\?(?:php\b|=)/i.test(t)||/^\?php\b/i.test(t))return"php";if(/^[\[{]/.test(t)&&/[\]}]$/.test(t)||/"[^"]+"\s*:/.test(t))try{return JSON.parse(t),"json"}catch{}const i=/<\/?[A-Za-z][\w:-]*(?:\s|>|\/>)/.test(t),s=/^<!DOCTYPE\s+html\b/i.test(t)||/<\/?(html|head|body|meta|title|style|script)\b/i.test(t);if([/^---\s*\n[\s\S]*?\n---\s*(?:\n|$)/.test(t),/^#{1,6}\s+\S/m.test(t),/^\s*```/m.test(t),/^\s*~~~/m.test(t),/^\s{0,3}>\s+/m.test(t),/^\s{0,3}(?:[-*+]|\d+\.)\s+\S/m.test(t),/^\s{0,3}[-*+]\s+\[[ xX]\]\s+\S/m.test(t),/\[[^\]\n]+\]\([^)]+\)/.test(t),/!\[[^\]\n]*\]\([^)]+\)/.test(t),/(^|\n)\s*\|.+\|\s*\n\s*\|[\s:-]+\|/m.test(t),/(^|\s)(?:\*\*|__)[^*_]+(?:\*\*|__)(?=\s|$|[.,;:!?])/m.test(t)].filter(Boolean).length>=(i?2:1))return"markdown";if(s)return"html";const n=this.detectProgrammingLanguage(t);if(n)return n;const r=/[{][\s\S]*[}]/.test(t)&&/[A-Za-z_-][\w-]*\s*:\s*[^;{}]+;?/.test(t)&&!/\b(function|const|let|var|return|class|interface|type)\b/.test(t);return!i&&r?"css":null}detectProgrammingLanguage(e){const t={php:0,python:0,go:0,cpp:0,c:0,java:0,csharp:0,rust:0,ruby:0,sql:0,yaml:0,dockerfile:0},i=(r,o,l=1)=>{o.test(e)&&(t[r]+=l)};i("python",/^\s*(from\s+\w+\s+import|import\s+\w+|def\s+\w+\s*\(|class\s+\w+|for\s+\w+\s+in\s+.+:|if\s+.+:|while\s+.+:|print\s*\()/m,2),i("python",/^\s*[A-Za-z_]\w*\s*=\s*(?:\[|\{|\(|["']|\d)/m),i("python",/\b(True|False|None|self|elif|lambda|yield)\b/),i("go",/^\s*package\s+\w+/m,3),i("go",/\bfunc\s+\w+\s*\(/,2),i("go",/\b(import|defer|goroutine|chan|struct|interface)\b/),i("cpp",/^\s*#include\s*<[^>]+>/m,2),i("cpp",/\b(std::|template\s*<|namespace\s+\w+|cout\s*<<|cin\s*>>)\b/,2),i("cpp",/\b(class|public|private|protected|virtual|typename)\b/),i("c",/^\s*#include\s*[<"][^>"]+[>"]/m),i("c",/\b(int|char|float|double|void)\s+\w+\s*\(/),i("c",/\bprintf\s*\(/),i("java",/^\s*(package|import)\s+[\w.]+;/m,2),i("java",/\b(public|private|protected)\s+(class|interface|enum)\s+\w+/,2),i("java",/\bSystem\.out\.println\s*\(/),i("csharp",/^\s*using\s+[\w.]+;/m,2),i("csharp",/\b(namespace|record|var|string|Console\.WriteLine)\b/),i("csharp",/\b(public|private|protected)\s+(class|interface|struct)\s+\w+/),i("rust",/\bfn\s+\w+\s*\(/,2),i("rust",/\b(let\s+mut|impl\s+\w+|use\s+[\w:]+|println!\s*\()/),i("rust",/\b(crate|trait|enum|match|Some|None|Ok|Err)\b/),i("ruby",/^\s*(def|class|module)\s+\w+/m,2),i("ruby",/\b(puts|require|attr_reader|elsif|end)\b/),i("sql",/^\s*(SELECT|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP)\b/im,3),i("sql",/\bFROM\s+\w+|\bWHERE\s+/i),i("yaml",/^---\s*$/m),i("yaml",/^\s*[A-Za-z0-9_.-]+\s*:\s+\S/m,2),i("yaml",/^\s*-\s+[A-Za-z0-9_.-]+\s*:/m),i("dockerfile",/^\s*FROM\s+\S+/im,3),i("dockerfile",/^\s*(RUN|COPY|ADD|CMD|ENTRYPOINT|WORKDIR|ENV|ARG)\b/im,2),i("php",/^<\?(?:php\b|=)/i,3),i("php",/^\?php\b/i,3),i("php",/\$[A-Za-z_\x80-\xff][A-Za-z0-9_\x80-\xff]*\s*=/,2),i("php",/\b(echo|foreach|function|namespace|use|PHP_EOL)\b/,2);const[s,n]=Object.entries(t).sort((r,o)=>o[1]-r[1])[0]||["",0];return n>=2?s:null}_highlightHTML(e,t){const i=t,s=c=>this.escapeHTML(c),n=[],r=this.createTokenStore(n),o=[],l=c=>{const g=o.length;return o.push(c),`ht${g}`};let a=s(e);a=a.replace(/&lt;\/?(?:(?!&gt;)[^\n\r<])*?(?=$|[\n\r])/g,c=>l(c));const h=[];try{e.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,(c,g,u)=>(h.push({attrs:String(g||""),inner:String(u||"")}),c))}catch{}let d=0;return a=a.replace(/(&lt;script\b([^&>]*)&gt;)([\s\S]*?)(&lt;\/script&gt;)/gi,(c,g,u,p,f)=>{const b=h[d++]?.inner??this.unescapeEntitiesRepeated(p||"");(h[d-1]?.attrs||u||"").toLowerCase();const x=this._highlightJS(b,i);return`${g}${x}${f}`}),a=a.replace(/(&lt;style\b[^&]*&gt;)([\s\S]*?)(&lt;\/style&gt;)/gi,(c,g,u,p)=>{const f=this._highlightCSS(this.unescapeEntitiesRepeated(u),i);return`${g}${f}${p}`}),a=a.replace(/(&lt;!--[\s\S]*?--&gt;)/g,c=>r(`<span style="color: ${i.comment};">${c}</span>`)),a=a.replace(/(&lt;!DOCTYPE[\s\S]*?&gt;)/i,c=>r(`<span style="color: ${i.doctype};">${c}</span>`)),a=a.replace(/(&lt;\/?\s*)([^\s&>\/]+)([^<]*?)(\/?&gt;)/g,(c,g,u,p,f)=>{const b=`<span style="color: ${i.tag};">${u}</span>`;let x=p;return x=x.replace(/([\w:-]+)(\s*=\s*)((&quot;[\s\S]*?&quot;|&#39;[\s\S]*?&#39;|[^\s&>]+))/g,(E,T,R,v)=>{const L=String(T).toLowerCase(),H=`<span style="color: ${i.attrName};">${T}</span>`;let I=v,S="";v.startsWith("&quot;")&&v.endsWith("&quot;")?(I=v.slice(6,-6),S="&quot;"):v.startsWith("&#39;")&&v.endsWith("&#39;")&&(I=v.slice(5,-5),S="&#39;");let w=v;if(L==="style"){const D=I.replace(/([\w-]+)\s*:\s*([^;]+)(;?)/g,(N,M,A,$)=>`<span style="color: ${i.styleProp};">${M}</span>:<span style="color: ${i.styleVal};">${A}</span>${$}`);S?w=`${S}${D}${S}`:w=D,w=`<span style="color: ${i.attrValue};">${w}</span>`}else S&&(w=`${S}${I}${S}`),w=`<span style="color: ${i.attrValue};">${w}</span>`;return`${H}${R}${w}`}),`${g}${b}${x}${f}`}),a=a.replace(/\u0002ht(\d+)\u0002/g,(c,g)=>o[Number(g)]||""),this.restoreHighlightTokens(a,n)}_highlightCSS(e,t){const i=this.unescapeEntitiesRepeated(e),s=[],n=this.createTokenStore(s),r=/(\/\*[\s\S]*?\*\/)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g;let o=0,l="",a;for(;a=r.exec(i);){o<a.index&&(l+=this.escapeHTML(i.slice(o,a.index)));const h=a[0],d=h.startsWith("/*")?t.comment:t.string;l+=n(`<span style="color: ${d};">${this.escapeHTML(h)}</span>`),o=r.lastIndex}return o<i.length&&(l+=this.escapeHTML(i.slice(o))),l=l.replace(/(@[\w-]+)/g,h=>n(`<span style="color: ${t.keyword};">${h}</span>`)),l=l.replace(/([A-Za-z_-][\w-]*)(\s*:)/g,(h,d,c)=>`${n(`<span style="color: ${t.styleProp};">${d}</span>`)}${c}`),l=l.replace(/(#(?:[0-9a-fA-F]{3,8})\b)/g,h=>n(`<span style="color: ${t.number};">${h}</span>`)),l=l.replace(/\b(-?\d*\.?\d+(?:px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|turn|fr)?)\b/g,h=>n(`<span style="color: ${t.number};">${h}</span>`)),l=l.replace(/\b(important|inherit|initial|unset|revert|auto|none|block|inline|flex|grid|absolute|relative|fixed|sticky)\b/g,h=>n(`<span style="color: ${t.styleVal};">${h}</span>`)),this.restoreHighlightTokens(l,s)}_highlightJSON(e,t){const i=this.unescapeEntitiesRepeated(e),s=/("(?:\\.|[^"\\])*")(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}\[\],:]/g;let n=0,r="",o;for(;o=s.exec(i);){n<o.index&&(r+=this.escapeHTML(i.slice(n,o.index)));const l=o[0],a=o[1],h=o[2]||"",d=o[3];if(a){const c=h?t.attrName:t.string;r+=`<span style="color: ${c};">${this.escapeHTML(a)}</span>${this.escapeHTML(h)}`}else d?r+=`<span style="color: ${t.keyword};">${l}</span>`:/^-?\d/.test(l)?r+=`<span style="color: ${t.number};">${l}</span>`:r+=`<span style="color: ${t.tag};">${this.escapeHTML(l)}</span>`;n=s.lastIndex}return n<i.length&&(r+=this.escapeHTML(i.slice(n))),r}_highlightMarkdown(e,t){const i=this.unescapeEntitiesRepeated(e).split(`
201
+ `);let s=!1,n="",r="",o=i[0]?.trim()==="---";return i.map((l,a)=>{const h=[],d=this.createTokenStore(h);if(o){const u=l.trim()==="---",p=`<span style="color: ${u?t.keyword:t.attrName};">${this.escapeHTML(l)}</span>`;return a>0&&u&&(o=!1),p}const c=l.match(/^(\s*)(`{3,}|~{3,})(.*)$/);if(c){const u=c[2];return s=!(s&&u[0]===n[0]),n=s?u:"",r=s?this.extractMarkdownFenceLanguage(c[3]||""):"",[this.escapeHTML(c[1]),`<span style="color: ${t.keyword}; font-weight: 700;">${this.escapeHTML(u)}</span>`,`<span style="color: ${t.string};">${this.escapeHTML(c[3]||"")}</span>`].join("")}if(s)return this.highlightMarkdownFenceLine(l,r,t);let g=this.escapeHTML(l).replace(/(`[^`]+`)/g,u=>d(`<span style="color: ${t.string}; background: rgba(148, 163, 184, 0.16); border-radius: 3px;">${u}</span>`)).replace(/(!?\[[^\]\n]*\])(\([^)]+\))/g,(u,p,f)=>d(`<span style="color: ${t.attrName};">${p}</span><span style="color: ${t.attrValue};">${f}</span>`)).replace(/(\*\*|__)(.+?)\1/g,(u,p,f)=>d(`<span style="color: ${t.keyword};">${p}</span><span style="color: ${t.tag}; font-weight: 700;">${f}</span><span style="color: ${t.keyword};">${p}</span>`)).replace(/(~~)(.+?)\1/g,(u,p,f)=>d(`<span style="color: ${t.keyword};">${p}</span><span style="color: ${t.comment}; text-decoration: line-through;">${f}</span><span style="color: ${t.keyword};">${p}</span>`)).replace(/(\*|_)([^*_]+?)\1/g,(u,p,f)=>d(`<span style="color: ${t.keyword};">${p}</span><span style="color: ${t.styleVal}; font-style: italic;">${f}</span><span style="color: ${t.keyword};">${p}</span>`));return g=g.replace(/^(\s{0,3}#{1,6})(\s+.*)?$/,(u,p,f="")=>`<span style="color: ${t.keyword}; font-weight: 700;">${p}</span><span style="color: ${t.tag}; font-weight: 700;">${f}</span>`),g=g.replace(/^(\s{0,3})((?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/,(u,p,f)=>`${p}<span style="color: ${t.comment};">${f}</span>`),g=g.replace(/^(\s{0,3}&gt;)(.*)$/,(u,p,f)=>`<span style="color: ${t.comment};">${p}</span>${f}`),g=g.replace(/^(\s*)([-*+])(\s+\[[ xX]\])(\s+)/,(u,p,f,b,x)=>`${p}<span style="color: ${t.keyword};">${f}</span><span style="color: ${t.attrName};">${b}</span>${x}`),g=g.replace(/^(\s*)([-*+]|\d+\.)(\s+)/,(u,p,f,b)=>`${p}<span style="color: ${t.keyword};">${f}</span>${b}`),g=g.replace(/^(\s*\|.*\|\s*)$/,u=>u.replace(/\|/g,p=>`<span style="color: ${t.keyword};">${p}</span>`)),this.restoreHighlightTokens(g,h)}).join(`
202
+ `)}extractMarkdownFenceLanguage(e){const t=e.trim().match(/^([A-Za-z0-9_+.#-]+)/)?.[1]||"";return t?this.normalizeLanguageId(t):""}highlightMarkdownFenceLine(e,t,i){const s=t?this.modes.get(t):void 0;return!s||s.name==="markdown"?`<span style="color: ${i.text};">${this.escapeHTML(e)}</span>`:s.highlight(e,i)}_highlightShell(e,t){const i=this.unescapeEntitiesRepeated(e),s=[],n=this.createTokenStore(s),r=/(#[^\n\r]*)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|(\$\{?[A-Za-z_][\w]*\}?|\$[0-9@#?$*!])/g;let o=0,l="",a;for(;a=r.exec(i);){o<a.index&&(l+=this.escapeHTML(i.slice(o,a.index)));const h=a[0],d=h.startsWith("#")?t.comment:h.startsWith("$")?t.variable:t.string;l+=n(`<span style="color: ${d};">${this.escapeHTML(h)}</span>`),o=r.lastIndex}return o<i.length&&(l+=this.escapeHTML(i.slice(o))),l=l.replace(/(^|\s)(--?[A-Za-z0-9][\w-]*)(?=\s|=|$)/g,(h,d,c)=>`${d}${n(`<span style="color: ${t.attrName};">${c}</span>`)}`),l=l.replace(/\b(if|then|else|elif|fi|for|while|until|do|done|case|esac|function|export|unset|alias|source|return|in)\b/g,h=>n(`<span style="color: ${t.keyword};">${h}</span>`)),l=l.replace(/(^|\s)(npm|npx|pnpm|yarn|bun|node|git|cd|mkdir|touch|cp|mv|rm|cat|grep|rg|find|curl|wget|echo|printf|sudo|chmod|chown|docker|kubectl)(?=\s|$)/g,(h,d,c)=>`${d}${n(`<span style="color: ${t.tag};">${c}</span>`)}`),this.restoreHighlightTokens(l,s)}getLanguageKeywords(e){const t=["true","false","null","nil","none"];return[...{python:["and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","self","True","False","None"],go:["break","case","chan","const","continue","defer","default","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],c:["auto","break","case","char","const","continue","default","do","double","else","enum","extern","float","for","goto","if","inline","int","long","register","restrict","return","short","signed","sizeof","static","struct","switch","typedef","union","unsigned","void","volatile","while"],cpp:["alignas","alignof","auto","bool","break","case","catch","char","class","concept","const","constexpr","continue","decltype","default","delete","do","double","else","enum","explicit","export","extern","false","float","for","friend","if","inline","int","long","namespace","new","noexcept","nullptr","operator","private","protected","public","requires","return","short","signed","sizeof","static","struct","switch","template","this","throw","true","try","typedef","typename","union","unsigned","using","virtual","void","volatile","while"],java:["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","final","finally","float","for","if","implements","import","instanceof","int","interface","long","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","try","void","volatile","while"],csharp:["abstract","as","async","await","base","bool","break","case","catch","class","const","continue","decimal","default","delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","get","if","implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","out","override","params","private","protected","public","readonly","record","ref","return","sealed","set","short","sizeof","stackalloc","static","string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","using","var","virtual","void","volatile","while","yield"],rust:["as","async","await","break","const","continue","crate","dyn","else","enum","extern","false","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","Self","static","struct","super","trait","true","type","unsafe","use","where","while"],ruby:["BEGIN","END","alias","and","begin","break","case","class","def","defined?","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield"],sql:["ADD","ALTER","AND","AS","ASC","BETWEEN","BY","CASE","CREATE","DELETE","DESC","DISTINCT","DROP","ELSE","END","EXISTS","FROM","GROUP","HAVING","IN","INDEX","INNER","INSERT","INTO","IS","JOIN","LEFT","LIKE","LIMIT","NOT","NULL","ON","OR","ORDER","OUTER","PRIMARY","RIGHT","SELECT","SET","TABLE","THEN","UNION","UPDATE","VALUES","WHEN","WHERE"]}[e]||[],...t]}_highlightGenericCode(e,t,i){const s=this.unescapeEntitiesRepeated(e),n=[],r=this.createTokenStore(n),o=i==="python"||i==="ruby"||i==="sql"?"#[^\\n\\r]*|--[^\\n\\r]*":"\\/\\*[\\s\\S]*?\\*\\/|\\/\\/[^\\n\\r]*",l=new RegExp(`(${o})|("(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`)`,"g");let a=0,h="",d;for(;d=l.exec(s);){a<d.index&&(h+=this.escapeHTML(s.slice(a,d.index)));const g=d[0],u=g.startsWith("//")||g.startsWith("/*")||g.startsWith("#")||g.startsWith("--")?t.comment:t.string;h+=r(`<span style="color: ${u};">${this.escapeHTML(g)}</span>`),a=l.lastIndex}a<s.length&&(h+=this.escapeHTML(s.slice(a)));const c=Array.from(new Set(this.getLanguageKeywords(i)));if(c.length>0){const g=new RegExp(`\\b(${c.map(u=>u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")})\\b`,i==="sql"?"gi":"g");h=h.replace(g,u=>r(`<span style="color: ${t.keyword};">${u}</span>`))}return h=h.replace(/\b([A-Z][A-Za-z0-9_]*|[A-Za-z_][\w]*(?=\s*\())\b/g,g=>r(`<span style="color: ${t.tag};">${g}</span>`)),h=h.replace(/\b(-?0x[0-9a-fA-F]+|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)(?:[uUlLfFdD]*)\b/g,g=>r(`<span style="color: ${t.number};">${g}</span>`)),h=h.replace(/(@[A-Za-z_][\w]*|#[A-Za-z_][\w]*|::[A-Za-z_][\w]*)/g,g=>r(`<span style="color: ${t.attrName};">${g}</span>`)),this.restoreHighlightTokens(h,n)}_highlightYAML(e,t){const i=this.unescapeEntitiesRepeated(e),s=[],n=this.createTokenStore(s);let r=this.escapeHTML(i).replace(/(#.*)$/gm,o=>n(`<span style="color: ${t.comment};">${o}</span>`)).replace(/^(\s*[-?]?\s*)([A-Za-z0-9_.-]+)(\s*:)/gm,(o,l,a,h)=>`${l}${n(`<span style="color: ${t.attrName};">${a}</span>`)}${h}`).replace(/\b(true|false|null|yes|no|on|off)\b/gi,o=>n(`<span style="color: ${t.keyword};">${o}</span>`)).replace(/\b(-?\d+(?:\.\d+)?)\b/g,o=>n(`<span style="color: ${t.number};">${o}</span>`));return r=r.replace(/(&quot;[^&]*?&quot;|&#39;[^&]*?&#39;)/g,o=>n(`<span style="color: ${t.string};">${o}</span>`)),this.restoreHighlightTokens(r,s)}_highlightXML(e,t){return this._highlightHTML(e,t)}_highlightJSX(e,t){const i=[],s=e.replace(/<\/?[A-Za-z][\w.:-]*(?:\s+[^<>]*?)?\/?>/g,n=>{const r=i.length,o=this.escapeHTML(n).replace(/(&lt;\/?)([A-Za-z][\w.:-]*)([\s\S]*?)(\/?&gt;)/,(l,a,h,d,c)=>{const g=String(d||"").replace(/([A-Za-z_:][\w:.-]*)(\s*=\s*)/g,`<span style="color: ${t.attrName};">$1</span>$2`);return`${a}<span style="color: ${t.tag};">${h}</span>${g}${c}`});return i.push(o),`jsx${r}`});return this._highlightJS(s,t).replace(/\u0004jsx(\d+)\u0004/g,(n,r)=>i[Number(r)]||"")}_highlightEJS(e,t){const i=[],s=e.replace(/<%[\s\S]*?%>/g,n=>{const r=i.length;return i.push(`<span style="color: ${t.keyword};">${this.escapeHTML(n)}</span>`),`ejs${r}`});return this._highlightHTML(s,t).replace(/\u0003ejs(\d+)\u0003/g,(n,r)=>i[Number(r)]||"")}_highlightDockerfile(e,t){return this.unescapeEntitiesRepeated(e).split(`
203
+ `).map(i=>{const s=this.escapeHTML(i);return/^\s*#/.test(i)?`<span style="color: ${t.comment};">${s}</span>`:s.replace(/^(\s*)(FROM|RUN|CMD|LABEL|MAINTAINER|EXPOSE|ENV|ADD|COPY|ENTRYPOINT|VOLUME|USER|WORKDIR|ARG|ONBUILD|STOPSIGNAL|HEALTHCHECK|SHELL)(\b)/i,(n,r,o,l)=>`${r}<span style="color: ${t.keyword};">${o}</span>${l}`)}).join(`
204
+ `)}_highlightJS(e,t){const i=this.unescapeEntitiesRepeated(e);this.escapeHTML(i);const s=[],n=c=>{let g="",u=c;do g=String.fromCharCode(97+u%26)+g,u=Math.floor(u/26)-1;while(u>=0);return g||"a"},r=c=>`\0${n(c)}\0`,o=c=>{const g=s.length;return s.push(c),r(g)};let l;const a=/(\/\*[\s\S]*?\*\/)|(\/\/[^\n\r]*)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)/g;let h=0,d="";for(;l=a.exec(i);){const c=l.index;h<c&&(d+=this.escapeHTML(i.slice(h,c)));const g=l[0];/^\/\*/.test(g)||/^\/\//.test(g)?d+=o(`<span style="color: ${t.comment};">${this.escapeHTML(g)}</span>`):d+=o(`<span style="color: ${t.string};">${this.escapeHTML(g)}</span>`),h=a.lastIndex}return h<i.length&&(d+=this.escapeHTML(i.slice(h))),d=d.replace(/\b(0x[0-9a-fA-F]+|\d+\.?\d*|\d*\.\d+)\b/g,(c,g,u)=>{const p=d[u-1]||"",f=d[u+c.length]||"";return p==="&"||p==="#"||f===";"||f==="#"?c:`<span style="color: ${t.number};">${c}</span>`}),d=d.replace(/\b(const|let|var|function|class|if|else|return|for|while|switch|case|break|import|from|export|extends|new|try|catch|finally|throw|await|async|interface|type)\b/g,`<span style="color: ${t.keyword};">$1</span>`),d.replace(/\u0000([a-z]+)\u0000/g,(c,g)=>{let u=0;for(let p=0;p<g.length;p++)u=u*26+(g.charCodeAt(p)-97+1);return u=u-1,s[u]||""})}_highlightPHP(e,t){const i=this.unescapeEntitiesRepeated(e);let s=this.escapeHTML(i);const n=[],r=u=>{let p="",f=u;do p=String.fromCharCode(97+f%26)+p,f=Math.floor(f/26)-1;while(f>=0);return p||"a"},o=u=>{const p=n.length;return n.push(u),`\0${r(p)}\0`},l=(u,p)=>{const f=s.indexOf(u);return f===-1?!1:(s=s.slice(0,f)+p+s.slice(f+u.length),!0)};let a;const h=/\/\*[\s\S]*?\*\//g,d=/\/\/[^\n\r]*/g,c=/\#([^\n\r]*)/g,g=/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g;for(;a=h.exec(i);){const u=a[0];l(this.escapeHTML(u),o(`<span style="color: ${t.comment};">${this.escapeHTML(u)}</span>`))}for(;a=d.exec(i);){const u=a[0];l(this.escapeHTML(u),o(`<span style="color: ${t.comment};">${this.escapeHTML(u)}</span>`))}for(;a=c.exec(i);){const u=a[0];l(this.escapeHTML(u),o(`<span style="color: ${t.comment};">${this.escapeHTML(u)}</span>`))}for(;a=g.exec(i);){const u=a[0];l(this.escapeHTML(u),o(`<span style="color: ${t.string};">${this.escapeHTML(u)}</span>`))}return s=s.replace(/(&lt;\?(?:php\b|=)?|\?&gt;)/gi,u=>o(`<span style="color: ${t.keyword};">${u}</span>`)),s=s.replace(/(\$[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)/g,`<span style="color: ${t.variable};">$1</span>`),s=s.replace(/\b(echo|print|function|class|if|else|elseif|foreach|as|return|namespace|use|new|extends|public|protected|private|static)\b/g,`<span style="color: ${t.keyword};">$1</span>`),s=s.replace(/\u0000([a-z]+)\u0000/g,(u,p)=>{let f=0;for(let b=0;b<p.length;b++)f=f*26+(p.charCodeAt(b)-97+1);return f=f-1,n[f]||""}),s}shouldHighlight(e){return/<\/?[\w:-]+|<!--/.test(e)}destroy(){this.editor=null,this.modes.clear()}}function ce(C,e){const t={...e};return t.extensions||(t.extensions=[]),t.extensions.some(i=>i.name==="keymap")||t.extensions.unshift(new J(t.keymap)),t.extensions.some(i=>i.name==="transaction")||t.extensions.unshift(new ee),new Y(C,t)}const B='[data-theme="dark"], .dark, .editora-theme-dark',de=`/* Source Editor Dialog Styles */
128
205
  .rte-source-editor-overlay {
129
206
  position: fixed !important;
130
207
  top: 0 !important;
@@ -501,10 +578,10 @@
501
578
  flex: 1;
502
579
  text-align: center;
503
580
  }
504
- }`,ae=()=>({name:"code",toolbar:[{label:"Source",command:"toggleSourceView",icon:'<svg width="24" height="24" focusable="false"><g fill-rule="nonzero"><path d="M9.8 15.7c.3.3.3.8 0 1-.3.4-.9.4-1.2 0l-4.4-4.1a.8.8 0 0 1 0-1.2l4.4-4.2c.3-.3.9-.3 1.2 0 .3.3.3.8 0 1.1L6 12l3.8 3.7ZM14.2 15.7c-.3.3-.3.8 0 1 .4.4.9.4 1.2 0l4.4-4.1c.3-.3.3-.9 0-1.2l-4.4-4.2a.8.8 0 0 0-1.2 0c-.3.3-.3.8 0 1.1L18 12l-3.8 3.7Z"></path></g></svg>',shortcut:"Mod-Shift-S"}],commands:{toggleSourceView:()=>{const e=(()=>{var o,a,h;const n=window.getSelection();if(n&&n.anchorNode){let l=n.anchorNode instanceof HTMLElement?n.anchorNode:n.anchorNode.parentElement;for(;l;){if((o=l.classList)!=null&&o.contains("rte-content"))return l;l=l.parentElement}}if(document.activeElement){let l=document.activeElement;if((a=l.classList)!=null&&a.contains("rte-content"))return l;for(;l&&l!==document.body;){if((h=l.classList)!=null&&h.contains("rte-content"))return l;const c=l.querySelector(".rte-content");if(c)return c;l=l.parentElement}}const r=document.querySelector("[data-editora-editor]");if(r){const l=r.querySelector(".rte-content");if(l)return l}return document.querySelector(".rte-content")})();if(!e)return console.error("[CodePlugin] Editor content area not found"),alert("Editor content area not found. Please click inside the editor first."),!1;const t=e.innerHTML,i=n=>{let r="",o=0;const a=2,h=n.split(/(<\/?[a-zA-Z][^>]*>)/);for(const l of h)l.trim()&&(l.match(/^<\/[a-zA-Z]/)?(o=Math.max(0,o-1),r+=`
505
- `+" ".repeat(o*a)+l):l.match(/^<[a-zA-Z]/)&&!l.match(/\/>$/)?(r+=`
506
- `+" ".repeat(o*a)+l,o++):l.match(/^<[a-zA-Z].*\/>$/)?r+=`
507
- `+" ".repeat(o*a)+l:r+=l.trim());return r.trim()};return(()=>{const r=i(t);let o=null,a="dark",h=!1,l=!1,c=!1,d=!1;const p=!!e.closest(P)||document.body.matches(P)||document.documentElement.matches(P),u=document.createElement("div");u.className="rte-source-editor-overlay",p&&u.classList.add("rte-theme-dark");const g=document.createElement("div");g.className="rte-source-editor-modal",g.setAttribute("role","dialog"),g.setAttribute("aria-modal","true"),g.setAttribute("aria-labelledby","source-editor-title");const f=document.createElement("div");f.className="rte-source-editor-header",f.innerHTML=`
581
+ }`,ue=()=>({name:"code",toolbar:[{label:"Source",command:"toggleSourceView",icon:'<svg width="24" height="24" focusable="false"><g fill-rule="nonzero"><path d="M9.8 15.7c.3.3.3.8 0 1-.3.4-.9.4-1.2 0l-4.4-4.1a.8.8 0 0 1 0-1.2l4.4-4.2c.3-.3.9-.3 1.2 0 .3.3.3.8 0 1.1L6 12l3.8 3.7ZM14.2 15.7c-.3.3-.3.8 0 1 .4.4.9.4 1.2 0l4.4-4.1c.3-.3.3-.9 0-1.2l-4.4-4.2a.8.8 0 0 0-1.2 0c-.3.3-.3.8 0 1.1L18 12l-3.8 3.7Z"></path></g></svg>',shortcut:"Mod-Shift-S"}],commands:{toggleSourceView:()=>{const e=(()=>{const n=window.getSelection();if(n&&n.anchorNode){let o=n.anchorNode instanceof HTMLElement?n.anchorNode:n.anchorNode.parentElement;for(;o;){if(o.classList?.contains("rte-content"))return o;o=o.parentElement}}if(document.activeElement){let o=document.activeElement;if(o.classList?.contains("rte-content"))return o;for(;o&&o!==document.body;){if(o.classList?.contains("rte-content"))return o;const l=o.querySelector(".rte-content");if(l)return l;o=o.parentElement}}const r=document.querySelector("[data-editora-editor]");if(r){const o=r.querySelector(".rte-content");if(o)return o}return document.querySelector(".rte-content")})();if(!e)return console.error("[CodePlugin] Editor content area not found"),alert("Editor content area not found. Please click inside the editor first."),!1;const t=e.innerHTML,i=n=>{let r="",o=0;const l=2,a=n.split(/(<\/?[a-zA-Z][^>]*>)/);for(const h of a)h.trim()&&(h.match(/^<\/[a-zA-Z]/)?(o=Math.max(0,o-1),r+=`
582
+ `+" ".repeat(o*l)+h):h.match(/^<[a-zA-Z]/)&&!h.match(/\/>$/)?(r+=`
583
+ `+" ".repeat(o*l)+h,o++):h.match(/^<[a-zA-Z].*\/>$/)?r+=`
584
+ `+" ".repeat(o*l)+h:r+=h.trim());return r.trim()};return(()=>{const r=i(t);let o=null,l="dark",a=!1,h=!1,d=!1,c=!1;const g=!!e.closest(B)||document.body.matches(B)||document.documentElement.matches(B),u=document.createElement("div");u.className="rte-source-editor-overlay",g&&u.classList.add("rte-theme-dark");const p=document.createElement("div");p.className="rte-source-editor-modal",p.setAttribute("role","dialog"),p.setAttribute("aria-modal","true"),p.setAttribute("aria-labelledby","source-editor-title");const f=document.createElement("div");f.className="rte-source-editor-header",f.innerHTML=`
508
585
  <h2 id="source-editor-title">Source Editor</h2>
509
586
  <div class="rte-source-editor-header-toolbar">
510
587
  <button class="rte-source-editor-toolbar-btn theme-toggle-btn" title="Switch theme">
@@ -540,7 +617,7 @@
540
617
  </svg>
541
618
  </button>
542
619
  </div>
543
- `;const y=document.createElement("div");y.className="rte-source-editor-body";const k=document.createElement("div");k.className="rte-source-editor-content";const v=document.createElement("div");v.className="rte-source-editor-warning",v.textContent="⚠️ Advanced users only. Invalid HTML may break the editor.";const C=document.createElement("div");C.className="rte-source-editor-light-editor",C.style.height="400px",k.appendChild(v),k.appendChild(C),y.appendChild(k);const E=document.createElement("div");if(E.className="rte-source-editor-footer",E.innerHTML=`
620
+ `;const b=document.createElement("div");b.className="rte-source-editor-body";const x=document.createElement("div");x.className="rte-source-editor-content";const E=document.createElement("div");E.className="rte-source-editor-warning",E.textContent="⚠️ Advanced users only. Invalid HTML may break the editor.";const T=document.createElement("div");T.className="rte-source-editor-light-editor",T.style.height="400px",x.appendChild(E),x.appendChild(T),b.appendChild(x);const R=document.createElement("div");if(R.className="rte-source-editor-footer",R.innerHTML=`
544
621
  <div class="rte-source-editor-footer-info">
545
622
  <span class="unsaved-changes" style="display: none;">• Unsaved changes</span>
546
623
  </div>
@@ -548,7 +625,7 @@
548
625
  <button class="rte-source-editor-btn rte-source-editor-btn-cancel">Cancel</button>
549
626
  <button class="rte-source-editor-btn rte-source-editor-btn-save">Save</button>
550
627
  </div>
551
- `,g.appendChild(f),g.appendChild(y),g.appendChild(E),u.appendChild(g),!document.getElementById("rte-source-editor-styles")){const x=document.createElement("style");x.id="rte-source-editor-styles",x.textContent=le,document.head.appendChild(x)}const S=f.querySelector(".theme-toggle-btn"),b=f.querySelector(".readonly-toggle-btn"),T=f.querySelector(".rte-source-editor-fullscreen-btn"),I=f.querySelector(".rte-source-editor-close-btn"),B=E.querySelector(".rte-source-editor-btn-cancel"),N=E.querySelector(".rte-source-editor-btn-save"),$=E.querySelector(".unsaved-changes"),O=[],R=(x,M,V,A)=>{x.addEventListener(M,V,A),O.push(()=>x.removeEventListener(M,V,A))},U=x=>{c!==x&&(c=x,$&&($.style.display=c?"inline":"none"))},H=()=>{if(!d){for(d=!0;O.length;){const x=O.pop();x==null||x()}o&&(o.destroy(),o=null),u.isConnected&&u.remove()}},K=()=>{a=a==="dark"?"light":"dark",o==null||o.setTheme(a),S&&(S.innerHTML=a==="light"?`
628
+ `,p.appendChild(f),p.appendChild(b),p.appendChild(R),u.appendChild(p),!document.getElementById("rte-source-editor-styles")){const y=document.createElement("style");y.id="rte-source-editor-styles",y.textContent=de,document.head.appendChild(y)}const v=f.querySelector(".theme-toggle-btn"),L=f.querySelector(".readonly-toggle-btn"),H=f.querySelector(".rte-source-editor-fullscreen-btn"),I=f.querySelector(".rte-source-editor-close-btn"),S=R.querySelector(".rte-source-editor-btn-cancel"),w=R.querySelector(".rte-source-editor-btn-save"),D=R.querySelector(".unsaved-changes"),N=[],M=(y,k,P,F)=>{y.addEventListener(k,P,F),N.push(()=>y.removeEventListener(k,P,F))},A=y=>{d!==y&&(d=y,D&&(D.style.display=d?"inline":"none"))},$=()=>{if(!c){for(c=!0;N.length;)N.pop()?.();o&&(o.destroy(),o=null),u.isConnected&&u.remove()}},_=()=>{l=l==="dark"?"light":"dark",o?.setTheme(l),v&&(v.innerHTML=l==="light"?`
552
629
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
553
630
  <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
554
631
  </svg>
@@ -564,7 +641,7 @@
564
641
  <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/>
565
642
  <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
566
643
  </svg>
567
- `)},z=()=>{h=!h,o==null||o.setReadOnly(h),b&&(b.classList.toggle("active",h),b.innerHTML=h?`
644
+ `)},j=()=>{a=!a,o?.setReadOnly(a),L&&(L.classList.toggle("active",a),L.innerHTML=a?`
568
645
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
569
646
  <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
570
647
  <circle cx="12" cy="16" r="1"/>
@@ -575,7 +652,7 @@
575
652
  <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
576
653
  <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
577
654
  </svg>
578
- `)},q=()=>{l=!l,u.classList.toggle("fullscreen",l),C.style.height=l?"calc(100vh - 200px)":"400px",T&&(T.innerHTML=l?`
655
+ `)},q=()=>{h=!h,u.classList.toggle("fullscreen",h),T.style.height=h?"calc(100vh - 200px)":"400px",H&&(H.innerHTML=h?`
579
656
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
580
657
  <path d="M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 0 2-2h3M3 16h3a2 2 0 0 0 2 2v3"/>
581
658
  </svg>
@@ -583,4 +660,4 @@
583
660
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
584
661
  <path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/>
585
662
  </svg>
586
- `)},j=()=>{c&&!confirm("You have unsaved changes. Are you sure you want to cancel?")||H()},Q=()=>{try{const x=(o==null?void 0:o.getValue())||"",M=document.createElement("div");M.innerHTML=x,M.querySelectorAll('script, iframe[src^="javascript:"], object, embed').forEach(A=>A.remove()),e.innerHTML=M.innerHTML;try{e.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!1,inputType:"insertReplacementText"}))}catch{e.dispatchEvent(new Event("input",{bubbles:!0}))}e.dispatchEvent(new Event("change",{bubbles:!0})),U(!1),H()}catch(x){alert("Failed to update HTML. Please check your syntax."),console.error("HTML update error:",x)}};S&&R(S,"click",K),b&&R(b,"click",z),T&&R(T,"click",q),I&&R(I,"click",H),B&&R(B,"click",j),N&&R(N,"click",Q),R(u,"click",x=>{x.target===u&&H()}),R(document,"keydown",x=>{const M=x;M.key==="Escape"&&(M.preventDefault(),H())}),document.body.appendChild(u),requestAnimationFrame(()=>{if(!(d||!u.isConnected))try{o=oe(C,{value:r,theme:"dark",readOnly:!1,extensions:[new _,new G,new ee,new se,new ie,new ne,new re]}),o.on("change",()=>{const x=(o==null?void 0:o.getValue())||"";U(x!==r)}),requestAnimationFrame(()=>o==null?void 0:o.focus())}catch(x){console.error("Failed to initialize code editor:",x)}})})(),!0}},keymap:{"Mod-Shift-s":"toggleSourceView","Mod-Shift-S":"toggleSourceView"}});exports.CodePlugin=ae;
663
+ `)},G=()=>{d&&!confirm("You have unsaved changes. Are you sure you want to cancel?")||$()},Z=()=>{try{const y=o?.getValue()||"",k=document.createElement("div");k.innerHTML=y,k.querySelectorAll('script, iframe[src^="javascript:"], object, embed').forEach(F=>F.remove()),e.innerHTML=k.innerHTML;try{e.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!1,inputType:"insertReplacementText"}))}catch{e.dispatchEvent(new Event("input",{bubbles:!0}))}e.dispatchEvent(new Event("change",{bubbles:!0})),A(!1),$()}catch(y){alert("Failed to update HTML. Please check your syntax."),console.error("HTML update error:",y)}};v&&M(v,"click",_),L&&M(L,"click",j),H&&M(H,"click",q),I&&M(I,"click",$),S&&M(S,"click",G),w&&M(w,"click",Z),M(u,"click",y=>{y.target===u&&$()}),M(document,"keydown",y=>{const k=y;k.key==="Escape"&&(k.preventDefault(),$())}),document.body.appendChild(u),requestAnimationFrame(()=>{if(!(c||!u.isConnected))try{o=ce(T,{value:r,theme:"dark",readOnly:!1,extensions:[new te,new ie,new se,new le,new re,new ae,new he]}),o.on("change",()=>{const y=o?.getValue()||"";A(y!==r)}),requestAnimationFrame(()=>o?.focus())}catch(y){console.error("Failed to initialize code editor:",y)}})})(),!0}},keymap:{"Mod-Shift-s":"toggleSourceView","Mod-Shift-S":"toggleSourceView"}});exports.CodePlugin=ue;