@editora/core 1.0.15 → 1.0.16

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 (68) hide show
  1. package/dist/{A11yCheckerPlugin.native-BRdGYMju.mjs → A11yCheckerPlugin.native-DIKuCeFw.mjs} +82 -79
  2. package/dist/{AnchorPlugin.native-BcYGEtd9.mjs → AnchorPlugin.native-DXZdK3zr.mjs} +72 -71
  3. package/dist/{ApprovalWorkflowPlugin.native-BZ6jO-Wj.mjs → ApprovalWorkflowPlugin.native-ZsS_2xmn.mjs} +239 -238
  4. package/dist/{BackgroundColorPlugin.native-50iAT9xU.mjs → BackgroundColorPlugin.native-H3XyYD7_.mjs} +2 -2
  5. package/dist/{BlocksLibraryPlugin.native-5sdsXsiE.mjs → BlocksLibraryPlugin.native-CownM6Rk.mjs} +140 -116
  6. package/dist/{CapitalizationPlugin.native-DLV4oPmB.mjs → CapitalizationPlugin.native-C-HRbXGh.mjs} +10 -5
  7. package/dist/{ChecklistPlugin.native-BS-kMz9O.mjs → ChecklistPlugin.native-NVrBUkaL.mjs} +141 -103
  8. package/dist/{CitationsPlugin.native-DQgoCd1B.mjs → CitationsPlugin.native-C_7wWQ-k.mjs} +441 -422
  9. package/dist/{ClearFormattingPlugin.native-B6ro3a1h.mjs → ClearFormattingPlugin.native-Pp0O-SBf.mjs} +24 -23
  10. package/dist/{CodePlugin.native-knhM8NNo.mjs → CodePlugin.native-BH-K4xmW.mjs} +474 -342
  11. package/dist/CodePlugin.native-hNgfXlfS.mjs +4767 -0
  12. package/dist/CodeSamplePlugin.native-svbAFWh_.mjs +501 -0
  13. package/dist/CollaborationPlugin.native-oSybCGPW.mjs +7468 -0
  14. package/dist/{CommentsPlugin.native-DPSqTkiv.mjs → CommentsPlugin.native-CLip9wAO.mjs} +233 -185
  15. package/dist/{ConditionalContentPlugin.native-CfhY46rU.mjs → ConditionalContentPlugin.native-Bf7XgRSW.mjs} +401 -351
  16. package/dist/{DataBindingPlugin.native-BoXwghTz.mjs → DataBindingPlugin.native-B7lpI_0c.mjs} +29 -28
  17. package/dist/{DocumentManagerPlugin.native-D1YHQ2NN.mjs → DocumentManagerPlugin.native-iFip6s4Q.mjs} +94 -45
  18. package/dist/{EmbedIframePlugin.native-BF_-LjTq.mjs → EmbedIframePlugin.native-BfZ_HGlV.mjs} +231 -186
  19. package/dist/{EmojisPlugin.native-CitxxlWX.mjs → EmojisPlugin.native-D92aaOKi.mjs} +288 -76
  20. package/dist/{FontFamilyPlugin.native-j8hMTbg4.mjs → FontFamilyPlugin.native-M3cNQ0KA.mjs} +57 -50
  21. package/dist/{FontSizePlugin.native-B_jCh7dY.mjs → FontSizePlugin.native-DsLrH8eq.mjs} +41 -34
  22. package/dist/{FormatPainterPlugin.native-CsMrKfFU.mjs → FormatPainterPlugin.native-BhjzsiVq.mjs} +3 -2
  23. package/dist/{HistoryPlugin.native-D2wl32jV.mjs → HistoryPlugin.native-DPvhks6h.mjs} +36 -32
  24. package/dist/LinkPlugin.native-BsQXYsK6.mjs +352 -0
  25. package/dist/{ListPlugin.native-V7EZC1lM.mjs → ListPlugin.native-Bt0LANbO.mjs} +68 -35
  26. package/dist/{MathPlugin.native-NwWPHVmj.mjs → MathPlugin.native-Byo3WL0f.mjs} +211 -115
  27. package/dist/{MediaManagerPlugin.native-eOsTJFpw.mjs → MediaManagerPlugin.native-BT1NZIJS.mjs} +139 -134
  28. package/dist/{MentionPlugin.native-BMDlOqur.mjs → MentionPlugin.native-S_lwGZQO.mjs} +23 -18
  29. package/dist/{MergeTagPlugin.native-BzRVoD9-.mjs → MergeTagPlugin.native-7-6F3S1Y.mjs} +44 -43
  30. package/dist/{PreviewPlugin.native-WuIwOAOR.mjs → PreviewPlugin.native-CiR51jql.mjs} +31 -28
  31. package/dist/{SlashCommandsPlugin.native-BiN6ODw5.mjs → SlashCommandsPlugin.native-BDIIwGNs.mjs} +90 -79
  32. package/dist/{SmartPastePlugin.native-CZAEHkyt.mjs → SmartPastePlugin.native-BATLCds5.mjs} +89 -85
  33. package/dist/{SpecialCharactersPlugin.native-DaG4b19I.mjs → SpecialCharactersPlugin.native-CdZoc1GB.mjs} +73 -26
  34. package/dist/SpellCheckPlugin.native-Bef2oTLB.mjs +10935 -0
  35. package/dist/TablePlugin.native-BjIxYZ2X.mjs +772 -0
  36. package/dist/{TemplatePlugin.native-DLjFUaPW.mjs → TemplatePlugin.native-D6n5RUnC.mjs} +288 -262
  37. package/dist/{TextColorPlugin.native-Bwl_bSmc.mjs → TextColorPlugin.native-KMZ2uzlq.mjs} +2 -2
  38. package/dist/{TranslationWorkflowPlugin.native-DdF16tgT.mjs → TranslationWorkflowPlugin.native-CZtG--06.mjs} +67 -65
  39. package/dist/{VersionDiffPlugin.native-Bvxgy--t.mjs → VersionDiffPlugin.native-Ca1fMWUJ.mjs} +42 -42
  40. package/dist/anchoredPopover-DJFD2oAP.mjs +116 -0
  41. package/dist/core.css +1 -1
  42. package/dist/dialogHelpers-DBf7WqYH.mjs +40 -0
  43. package/dist/editora.min.js +26 -24
  44. package/dist/editora.umd.js +26 -24
  45. package/dist/escapeHtml-CX8RelZ1.mjs +7 -0
  46. package/dist/historyHelpers-B0-4mq1E.mjs +15 -0
  47. package/dist/index-B1_vtXRz.mjs +3910 -0
  48. package/dist/index-C6BoNR2t.js +12 -0
  49. package/dist/index.cjs.js +3 -3
  50. package/dist/index.esm.js +17 -14
  51. package/dist/plugin-loader.js +53 -52
  52. package/dist/webcomponent-core.js +2039 -473
  53. package/dist/webcomponent-core.min.css +1 -1
  54. package/dist/webcomponent-core.min.js +96 -66
  55. package/dist/webcomponent.cjs.js +1 -1
  56. package/dist/webcomponent.esm.js +1 -1
  57. package/dist/webcomponent.js +2208 -641
  58. package/dist/webcomponent.min.css +1 -1
  59. package/dist/webcomponent.min.js +1564 -1198
  60. package/index.d.ts +32 -0
  61. package/package.json +10 -3
  62. package/dist/CodeSamplePlugin.native-CgGoH-X4.mjs +0 -384
  63. package/dist/LinkPlugin.native-DYCIcdTm.mjs +0 -283
  64. package/dist/SpellCheckPlugin.native-BZB9AewP.mjs +0 -1039
  65. package/dist/TablePlugin.native-DrHX-efe.mjs +0 -495
  66. package/dist/anchoredPopover-Bxds0VoB.mjs +0 -110
  67. package/dist/index-BLm1MtzH.js +0 -10
  68. package/dist/index-Cd9jEuZP.mjs +0 -2341
@@ -0,0 +1,4767 @@
1
+ function Y(T) {
2
+ let e = !1;
3
+ T.addEventListener(
4
+ "pointerdown",
5
+ (t) => {
6
+ e = t.target !== T;
7
+ },
8
+ !0
9
+ ), T.addEventListener(
10
+ "click",
11
+ (t) => {
12
+ t.target === T && e && t.stopImmediatePropagation(), e = !1;
13
+ },
14
+ !0
15
+ );
16
+ }
17
+ const _ = "rte-dialog-base-styles";
18
+ function X() {
19
+ if (typeof document == "undefined" || document.getElementById(_)) return;
20
+ const T = document.createElement("style");
21
+ T.id = _, T.textContent = `
22
+ [data-rte-dialog] {
23
+ font-family: var(--rte-font-family-base, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif);
24
+ }
25
+
26
+ /* Form controls ignore inherited fonts (browsers default them to Arial /
27
+ system-ui). :where() keeps this at zero specificity so any control a plugin
28
+ styles explicitly - e.g. a monospace formula field - keeps its own font. */
29
+ :where([data-rte-dialog]) :where(button, input, select, textarea) {
30
+ font-family: inherit;
31
+ }
32
+ `, document.head.appendChild(T);
33
+ }
34
+ function J(T) {
35
+ T.setAttribute("data-rte-dialog", ""), X(), Y(T);
36
+ }
37
+ class K {
38
+ constructor(e = "") {
39
+ this._lines = [], this._version = 0, this.setText(e);
40
+ }
41
+ // Get line at index
42
+ getLine(e) {
43
+ return this._lines[e] || "";
44
+ }
45
+ // Get all lines
46
+ getLines() {
47
+ return [...this._lines];
48
+ }
49
+ // Get total number of lines
50
+ getLineCount() {
51
+ return this._lines.length;
52
+ }
53
+ // Get total text content
54
+ getText() {
55
+ return this._lines.join(`
56
+ `);
57
+ }
58
+ // Set entire text content
59
+ setText(e) {
60
+ this._lines = e.split(`
61
+ `), this._version++;
62
+ }
63
+ // Get text in a range
64
+ getTextInRange(e) {
65
+ if (e.start.line === e.end.line)
66
+ return this.getLine(e.start.line).substring(e.start.column, e.end.column);
67
+ const t = [];
68
+ t.push(this.getLine(e.start.line).substring(e.start.column));
69
+ for (let i = e.start.line + 1; i < e.end.line; i++)
70
+ t.push(this.getLine(i));
71
+ return e.end.line < this.getLineCount() && t.push(this.getLine(e.end.line).substring(0, e.end.column)), t.join(`
72
+ `);
73
+ }
74
+ // Replace text in range
75
+ replaceRange(e, t) {
76
+ const i = this.normalizeRange(e), n = this.getTextInRange(i), s = this.getText(), r = this.positionToOffset(i.start), o = this.positionToOffset(i.end), l = s.slice(0, r) + t + s.slice(o);
77
+ return this.setText(l), { range: i, text: t, oldText: n };
78
+ }
79
+ // Insert text at position
80
+ insertText(e, t) {
81
+ const i = { start: e, end: e };
82
+ return this.replaceRange(i, t);
83
+ }
84
+ // Delete text in range
85
+ deleteRange(e) {
86
+ return this.replaceRange(e, "");
87
+ }
88
+ // Convert position to offset
89
+ positionToOffset(e) {
90
+ let t = 0;
91
+ for (let i = 0; i < e.line; i++)
92
+ t += this.getLine(i).length + 1;
93
+ return t += e.column, t;
94
+ }
95
+ // Convert offset to position
96
+ offsetToPosition(e) {
97
+ let t = e;
98
+ for (let i = 0; i < this.getLineCount(); i++) {
99
+ const n = this.getLine(i).length;
100
+ if (t <= n)
101
+ return { line: i, column: t };
102
+ t -= n + 1;
103
+ }
104
+ return {
105
+ line: this.getLineCount() - 1,
106
+ column: this.getLine(this.getLineCount() - 1).length
107
+ };
108
+ }
109
+ // Validate position
110
+ isValidPosition(e) {
111
+ return !(e.line < 0 || e.line >= this.getLineCount() || e.column < 0 || e.column > this.getLine(e.line).length);
112
+ }
113
+ // Validate range
114
+ isValidRange(e) {
115
+ return this.isValidPosition(e.start) && this.isValidPosition(e.end);
116
+ }
117
+ // Get version for change tracking
118
+ getVersion() {
119
+ return this._version;
120
+ }
121
+ // Clone the model
122
+ clone() {
123
+ const e = new K();
124
+ return e._lines = [...this._lines], e._version = this._version, e;
125
+ }
126
+ normalizeRange(e) {
127
+ return this.comparePositions(e.start, e.end) <= 0 ? e : {
128
+ start: e.end,
129
+ end: e.start
130
+ };
131
+ }
132
+ comparePositions(e, t) {
133
+ return e.line !== t.line ? e.line - t.line : e.column - t.column;
134
+ }
135
+ }
136
+ class ee {
137
+ constructor(e) {
138
+ this.gutterWidth = 50, this.gutterFoldColumnWidth = 20, this.gutterFoldColumnGap = 4, this.gutterLineNumberPaddingLeft = 8, this.gutterLineNumberPaddingRight = 4, this.gutterDigitWidth = 9, this.lineHeight = 21, this.trailingNewlineMarkerAttr = "data-lce-trailing-newline-marker", this.foldPlaceholderAttr = "data-lce-fold-placeholder", this.virtualMarkerRegex = /[\u200B\uE000]/, this.virtualMarkerGlobalRegex = /[\u200B\uE000]/g, this.lastLineCount = 0, this.lastHighlightHTML = "", this.highlightOverlayActive = !1, this.lastLineDecorationSnapshot = "", this.lastGutterDecorationSnapshot = "", this.container = e, this.createDOM();
139
+ }
140
+ createDOM() {
141
+ this.container.innerHTML = "";
142
+ const e = document.createElement("div");
143
+ this.editorContainer = e, e.setAttribute("data-lce-editor-container", "true"), e.style.cssText = `
144
+ position: relative;
145
+ display: flex;
146
+ width: 100%;
147
+ height: 100%;
148
+ background: var(--editor-background, #1e1e1e);
149
+ color: var(--editor-foreground, #f8f9fa);
150
+ font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
151
+ font-size: 14px;
152
+ line-height: ${this.lineHeight}px;
153
+ overflow: auto;
154
+ `, this.lineNumbersElement = document.createElement("div"), this.lineNumbersElement.setAttribute("data-editor-gutter", "true"), this.lineNumbersElement.style.cssText = `
155
+ display: table-cell;
156
+ vertical-align: top;
157
+ position: sticky;
158
+ left: 0;
159
+ width: ${this.gutterWidth}px;
160
+ min-width: ${this.gutterWidth}px;
161
+ background: var(--editor-gutter-background, #252526);
162
+ color: var(--editor-gutter-foreground, #858585);
163
+ padding: 0;
164
+ text-align: right;
165
+ border-right: 1px solid var(--editor-gutter-border, #3e3e42);
166
+ box-sizing: border-box;
167
+ background-clip: padding-box;
168
+ user-select: none;
169
+ overflow: hidden;
170
+ z-index: 3;
171
+ `, this.lineNumbersContentElement = document.createElement("div"), this.lineNumbersContentElement.setAttribute("data-editor-gutter-content", "true"), this.lineNumbersContentElement.style.cssText = `
172
+ position: relative;
173
+ z-index: 1;
174
+ box-sizing: border-box;
175
+ padding: 0 ${this.gutterFoldColumnWidth + this.gutterFoldColumnGap}px 0 ${this.gutterLineNumberPaddingLeft}px;
176
+ `, this.gutterDecorationsElement = document.createElement("div"), this.gutterDecorationsElement.setAttribute("data-editor-gutter-decorations", "true"), this.gutterDecorationsElement.setAttribute("aria-hidden", "true"), this.gutterDecorationsElement.style.cssText = `
177
+ position: absolute;
178
+ inset: 0;
179
+ z-index: 2;
180
+ pointer-events: none;
181
+ `;
182
+ const t = document.createElement("div");
183
+ this.contentSurface = t, t.setAttribute("data-editor-content-surface", "true"), t.style.cssText = `
184
+ display: table-cell;
185
+ vertical-align: top;
186
+ position: relative;
187
+ width: 100%;
188
+ min-width: max-content;
189
+ min-height: 400px;
190
+ `, this.highlightElement = document.createElement("div"), this.highlightElement.setAttribute("data-editor-highlight", "true"), this.highlightElement.setAttribute("aria-hidden", "true"), this.highlightElement.style.cssText = `
191
+ position: absolute;
192
+ inset: 0;
193
+ padding: 0 12px;
194
+ white-space: pre;
195
+ overflow: hidden;
196
+ min-height: 400px;
197
+ font-family: inherit;
198
+ font-size: inherit;
199
+ line-height: inherit;
200
+ pointer-events: none;
201
+ user-select: none;
202
+ background: transparent;
203
+ visibility: hidden;
204
+ `, this.lineDecorationsElement = document.createElement("div"), this.lineDecorationsElement.setAttribute("data-editor-line-decorations", "true"), this.lineDecorationsElement.setAttribute("aria-hidden", "true"), this.lineDecorationsElement.style.cssText = `
205
+ position: absolute;
206
+ inset: 0;
207
+ pointer-events: none;
208
+ z-index: 0;
209
+ `, this.contentElement = document.createElement("div"), this.contentElement.style.cssText = `
210
+ position: relative;
211
+ z-index: 1;
212
+ display: block;
213
+ box-sizing: border-box;
214
+ padding: 0 12px;
215
+ background: transparent;
216
+ border: none;
217
+ outline: none;
218
+ white-space: pre;
219
+ overflow: visible;
220
+ width: 100%;
221
+ min-width: max-content;
222
+ min-height: 400px;
223
+ font-family: inherit;
224
+ font-size: inherit;
225
+ line-height: inherit;
226
+ color: inherit;
227
+ caret-color: var(--editor-foreground, #f8f9fa);
228
+ tab-size: 2;
229
+ -moz-tab-size: 2;
230
+ `, this.contentElement.contentEditable = "true", this.contentElement.spellcheck = !1, this.contentElement.tabIndex = 0;
231
+ const i = document.createElement("div");
232
+ this.scrollWrapper = i, i.setAttribute("data-editora-editor", "true"), i.style.cssText = `
233
+ position: relative;
234
+ display: table;
235
+ table-layout: auto;
236
+ width: 100%;
237
+ min-width: 100%;
238
+ height: 100%;
239
+ `, 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);
240
+ }
241
+ // Update line numbers
242
+ updateLineNumbers(e) {
243
+ if (this.updateGutterWidth(e), e === this.lastLineCount)
244
+ return;
245
+ this.lastLineCount = e;
246
+ const t = Math.max(e, 1), i = Array.from({ length: t }, (n, s) => s + 1);
247
+ this.lineNumbersContentElement.innerHTML = i.map((n) => `<div style="height: ${this.lineHeight}px; line-height: ${this.lineHeight}px;">${n}</div>`).join("");
248
+ }
249
+ updateGutterWidth(e) {
250
+ const i = String(Math.max(e, 1)).length * this.gutterDigitWidth + this.gutterLineNumberPaddingLeft + this.gutterLineNumberPaddingRight, n = Math.ceil(
251
+ i + this.gutterFoldColumnGap + this.gutterFoldColumnWidth
252
+ );
253
+ n !== this.gutterWidth && (this.gutterWidth = n, this.lineNumbersElement.style.display !== "none" && (this.lineNumbersElement.style.width = `${this.gutterWidth}px`, this.lineNumbersElement.style.minWidth = `${this.gutterWidth}px`));
254
+ }
255
+ setDecorations(e, t) {
256
+ this.renderLineDecorations(e), this.renderGutterDecorations(t);
257
+ }
258
+ clearDecorations() {
259
+ this.lastLineDecorationSnapshot && (this.lineDecorationsElement.innerHTML = "", this.lastLineDecorationSnapshot = ""), this.lastGutterDecorationSnapshot && (this.gutterDecorationsElement.innerHTML = "", this.lastGutterDecorationSnapshot = "");
260
+ }
261
+ // Get content element
262
+ getContentElement() {
263
+ return this.contentElement;
264
+ }
265
+ // Get line numbers element
266
+ getLineNumbersElement() {
267
+ return this.lineNumbersElement;
268
+ }
269
+ // Get text content
270
+ getText() {
271
+ return this.serializeContentToSource();
272
+ }
273
+ // Set text content
274
+ setText(e) {
275
+ this.clearHighlightOverlay(), this.setFoldPlaceholderSources(/* @__PURE__ */ new Map()), this.contentElement.textContent !== e && (this.contentElement.textContent = e), this.syncTrailingNewlineMarker(e.endsWith(`
276
+ `));
277
+ const t = e.split(`
278
+ `).length;
279
+ this.updateLineNumbers(t);
280
+ }
281
+ // Set inner HTML (used for syntax highlighted content)
282
+ setHTML(e) {
283
+ this.clearHighlightOverlay(), this.setFoldPlaceholderSources(/* @__PURE__ */ new Map());
284
+ const t = /\n$/.test(e), i = /&lt;|&gt;/.test(e), n = /<span\b/i.test(e), s = /<[^>]+>/.test(e);
285
+ i && n ? this.contentElement.innerHTML = e : s && !i ? this.contentElement.textContent = e : this.contentElement.innerHTML = e, this.syncTrailingNewlineMarker(t);
286
+ const o = (this.contentElement.textContent || "").split(`
287
+ `).length;
288
+ this.updateLineNumbers(o);
289
+ }
290
+ setHighlightHTML(e) {
291
+ 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";
292
+ const i = (this.contentElement.textContent || "").split(`
293
+ `).length;
294
+ this.updateLineNumbers(i);
295
+ }
296
+ setLineWrapping(e) {
297
+ this.contentElement.style.whiteSpace = e ? "pre-wrap" : "pre", this.contentElement.style.overflow = "visible", this.contentElement.style.minWidth = e ? "100%" : "max-content", this.contentSurface.style.minWidth = e ? "100%" : "max-content", this.contentElement.style.wordBreak = "normal", this.contentElement.style.overflowWrap = e ? "anywhere" : "normal", this.highlightElement.style.whiteSpace = e ? "pre-wrap" : "pre", this.highlightElement.style.wordBreak = "normal", this.highlightElement.style.overflowWrap = e ? "anywhere" : "normal";
298
+ }
299
+ setLineNumbersVisible(e) {
300
+ this.lineNumbersElement.style.display = e ? "table-cell" : "none", this.lineNumbersElement.style.width = e ? `${this.gutterWidth}px` : "0", this.lineNumbersElement.style.minWidth = e ? `${this.gutterWidth}px` : "0", this.lineNumbersElement.style.borderRightWidth = e ? "1px" : "0", this.scrollWrapper.style.width = "100%", this.scrollWrapper.style.minWidth = "100%";
301
+ }
302
+ setTabSize(e) {
303
+ const t = Math.max(1, Math.floor(e) || 2);
304
+ this.contentElement.style.tabSize = String(t), this.contentElement.style.MozTabSize = String(t), this.highlightElement.style.tabSize = String(t), this.highlightElement.style.MozTabSize = String(t);
305
+ }
306
+ // Keep trailing-newline caret marker in sync for live contenteditable edits
307
+ // (without forcing a full setText/setHTML render).
308
+ syncTrailingNewlineMarkerForText(e) {
309
+ this.syncTrailingNewlineMarker(e.endsWith(`
310
+ `));
311
+ }
312
+ // Get cursor position from DOM selection
313
+ getCursorPosition() {
314
+ var e;
315
+ return (e = this.getSelectionState().cursor) != null ? e : { line: 0, column: 0 };
316
+ }
317
+ // Set cursor position
318
+ setCursorPosition(e) {
319
+ const t = this.getText(), i = this.positionToTextOffset(e, t), n = window.getSelection(), s = this.createDomRangeFromOffsets(i);
320
+ if (s)
321
+ try {
322
+ n == null || n.removeAllRanges(), n == null || n.addRange(s), this.ensureCaretVisible();
323
+ } catch (r) {
324
+ console.warn("Could not set cursor position:", r);
325
+ }
326
+ else {
327
+ const r = this.contentElement.querySelector(
328
+ `[${this.trailingNewlineMarkerAttr}]`
329
+ ), o = document.createRange();
330
+ try {
331
+ r && r.parentNode === this.contentElement ? o.setStartBefore(r) : (o.selectNodeContents(this.contentElement), o.collapse(!1)), o.collapse(!0), n == null || n.removeAllRanges(), n == null || n.addRange(o), this.ensureCaretVisible();
332
+ } catch (l) {
333
+ console.warn("Could not set fallback cursor position:", l);
334
+ }
335
+ }
336
+ }
337
+ // Get selection range
338
+ getSelectionRange() {
339
+ return this.getSelectionState().range;
340
+ }
341
+ getSelectionOffsets() {
342
+ const e = window.getSelection();
343
+ if (!e || e.rangeCount === 0)
344
+ return {
345
+ isInEditor: !1,
346
+ isCollapsed: !0,
347
+ startOffset: 0,
348
+ endOffset: 0
349
+ };
350
+ const t = e.getRangeAt(0);
351
+ if (!this.isNodeInsideContent(t.startContainer) || !this.isNodeInsideContent(t.endContainer))
352
+ return {
353
+ isInEditor: !1,
354
+ isCollapsed: e.isCollapsed,
355
+ startOffset: 0,
356
+ endOffset: 0
357
+ };
358
+ const i = e.anchorNode && this.isNodeInsideContent(e.anchorNode) ? this.sourceOffsetFromBoundary(
359
+ e.anchorNode,
360
+ e.anchorOffset
361
+ ) : void 0, n = e.focusNode && this.isNodeInsideContent(e.focusNode) ? this.sourceOffsetFromBoundary(
362
+ e.focusNode,
363
+ e.focusOffset
364
+ ) : void 0;
365
+ return {
366
+ isInEditor: !0,
367
+ isCollapsed: e.isCollapsed,
368
+ startOffset: this.sourceOffsetFromBoundary(
369
+ t.startContainer,
370
+ t.startOffset
371
+ ),
372
+ endOffset: this.sourceOffsetFromBoundary(
373
+ t.endContainer,
374
+ t.endOffset
375
+ ),
376
+ anchorOffset: i,
377
+ focusOffset: n
378
+ };
379
+ }
380
+ getSelectionState() {
381
+ const e = window.getSelection();
382
+ if (!e || e.rangeCount === 0)
383
+ return {
384
+ isInEditor: !1,
385
+ isCollapsed: !0
386
+ };
387
+ const t = e.getRangeAt(0);
388
+ if (!this.isNodeInsideContent(t.startContainer) || !this.isNodeInsideContent(t.endContainer))
389
+ return {
390
+ isInEditor: !1,
391
+ isCollapsed: e.isCollapsed
392
+ };
393
+ const i = this.getText(), n = this.sourceOffsetFromBoundary(t.startContainer, t.startOffset), s = this.sourceOffsetFromBoundary(t.endContainer, t.endOffset), r = e.focusNode && this.isNodeInsideContent(e.focusNode) ? this.sourceOffsetFromBoundary(
394
+ e.focusNode,
395
+ e.focusOffset
396
+ ) : s, o = this.offsetToPositionInText(n, i), l = this.offsetToPositionInText(s, i), a = this.offsetToPositionInText(r, i);
397
+ return {
398
+ isInEditor: !0,
399
+ isCollapsed: e.isCollapsed,
400
+ cursor: a,
401
+ range: e.isCollapsed ? void 0 : { start: o, end: l }
402
+ };
403
+ }
404
+ // Set selection range
405
+ setSelectionRange(e) {
406
+ const t = this.createDomRangeFromRange(e);
407
+ if (t)
408
+ try {
409
+ const i = window.getSelection();
410
+ i == null || i.removeAllRanges(), i == null || i.addRange(t), this.ensureCaretVisible();
411
+ } catch (i) {
412
+ console.warn("Could not set selection range:", i);
413
+ }
414
+ }
415
+ createDomRangeFromOffsets(e, t = e) {
416
+ const [i, n] = e <= t ? [e, t] : [t, e], s = this.resolveOffsetToDomPoint(i), r = this.resolveOffsetToDomPoint(n);
417
+ if (!s || !r)
418
+ return null;
419
+ const o = document.createRange();
420
+ try {
421
+ return o.setStart(s.node, s.offset), o.setEnd(r.node, r.offset), o;
422
+ } catch (l) {
423
+ return null;
424
+ }
425
+ }
426
+ createDomRangeFromRange(e) {
427
+ const t = this.getText();
428
+ return this.createDomRangeFromOffsets(
429
+ this.positionToTextOffset(e.start, t),
430
+ this.positionToTextOffset(e.end, t)
431
+ );
432
+ }
433
+ getPositionFromClientPoint(e, t) {
434
+ const i = this.getDomRangeFromClientPoint(e, t);
435
+ if (!i || !this.isNodeInsideContent(i.startContainer))
436
+ return null;
437
+ const n = this.sourceOffsetFromBoundary(
438
+ i.startContainer,
439
+ i.startOffset
440
+ );
441
+ return this.offsetToPositionInText(n, this.getText());
442
+ }
443
+ setSelectionOffsets(e, t = e) {
444
+ const i = this.createDomRangeFromOffsets(e, t);
445
+ if (i)
446
+ try {
447
+ const n = window.getSelection();
448
+ n == null || n.removeAllRanges(), n == null || n.addRange(i), this.ensureCaretVisible();
449
+ } catch (n) {
450
+ console.warn("Could not set selection offsets:", n);
451
+ }
452
+ }
453
+ setSelectionBoundaryOffsets(e, t) {
454
+ const i = this.resolveOffsetToDomPoint(e), n = this.resolveOffsetToDomPoint(t), s = window.getSelection();
455
+ if (!i || !n || !s) {
456
+ this.setSelectionOffsets(e, t);
457
+ return;
458
+ }
459
+ try {
460
+ if (s.removeAllRanges(), e === t) {
461
+ const o = document.createRange();
462
+ o.setStart(i.node, i.offset), o.collapse(!0), s.addRange(o), this.ensureCaretVisible();
463
+ return;
464
+ }
465
+ if (typeof s.extend == "function") {
466
+ const o = document.createRange();
467
+ o.setStart(i.node, i.offset), o.collapse(!0), s.addRange(o), s.extend(n.node, n.offset), this.ensureCaretVisible();
468
+ return;
469
+ }
470
+ const r = this.createDomRangeFromOffsets(e, t);
471
+ if (!r)
472
+ return;
473
+ s.addRange(r), this.ensureCaretVisible();
474
+ } catch (r) {
475
+ console.warn("Could not set selection boundary offsets:", r), this.setSelectionOffsets(e, t);
476
+ }
477
+ }
478
+ // Focus the editor
479
+ focus() {
480
+ this.contentElement.focus(), this.ensureCaretVisible();
481
+ }
482
+ // Blur the editor
483
+ blur() {
484
+ this.contentElement.blur();
485
+ }
486
+ // Set read-only mode
487
+ setReadOnly(e) {
488
+ this.contentElement.contentEditable = e ? "false" : "true";
489
+ }
490
+ // Apply theme
491
+ applyTheme(e) {
492
+ Object.entries(e).forEach(([t, i]) => {
493
+ this.container.style.setProperty(`--${t}`, i);
494
+ });
495
+ }
496
+ // Scroll to position
497
+ scrollToPosition(e) {
498
+ const n = Math.max(0, Math.floor(e.line) || 0) * this.lineHeight - this.editorContainer.clientHeight / 2 + this.lineHeight / 2;
499
+ this.editorContainer.scrollTop = Math.max(0, n);
500
+ }
501
+ // Get scroll position
502
+ getScrollTop() {
503
+ return this.editorContainer.scrollTop;
504
+ }
505
+ // Get primary scroll element
506
+ getScrollElement() {
507
+ return this.editorContainer;
508
+ }
509
+ // Set scroll position
510
+ setScrollTop(e) {
511
+ this.editorContainer.scrollTop = e;
512
+ }
513
+ syncTrailingNewlineMarker(e) {
514
+ if (this.contentElement.querySelectorAll(`[${this.trailingNewlineMarkerAttr}]`).forEach((i) => i.remove()), !e) return;
515
+ const t = document.createElement("span");
516
+ t.setAttribute(this.trailingNewlineMarkerAttr, "true"), t.setAttribute("aria-hidden", "true"), t.contentEditable = "false", t.style.cssText = `
517
+ display: inline-block;
518
+ width: 0;
519
+ overflow: hidden;
520
+ pointer-events: none;
521
+ user-select: none;
522
+ `, t.appendChild(document.createTextNode("​")), this.contentElement.appendChild(t);
523
+ }
524
+ // Ensure caret is visible inside the editor scroll container
525
+ ensureCaretVisible() {
526
+ const e = window.getSelection();
527
+ if (!e || e.rangeCount === 0) return;
528
+ const t = this.getCaretClientRect(e);
529
+ if (!t) return;
530
+ const i = this.editorContainer.getBoundingClientRect(), n = 12;
531
+ t.bottom > i.bottom - n ? this.editorContainer.scrollTop += t.bottom - (i.bottom - n) : t.top < i.top + n && (this.editorContainer.scrollTop -= i.top + n - t.top), t.right > i.right - n ? this.editorContainer.scrollLeft += t.right - (i.right - n) : t.left < i.left + n && (this.editorContainer.scrollLeft -= i.left + n - t.left);
532
+ }
533
+ // Destroy the view
534
+ destroy() {
535
+ this.clearDecorations(), this.container && (this.container.innerHTML = ""), this._rafId && (cancelAnimationFrame(this._rafId), this._rafId = void 0);
536
+ }
537
+ resolveOffsetToDomPoint(e) {
538
+ var s;
539
+ const t = Math.max(0, e);
540
+ let i = 0;
541
+ const n = Array.from(this.contentElement.childNodes);
542
+ for (let r = 0; r < n.length; r++) {
543
+ const o = n[r];
544
+ if (o instanceof Text) {
545
+ const l = o.textContent || "", a = this.buildVisibleToDomMap(l), h = Math.max(0, a.length - 1);
546
+ if (i + h >= t) {
547
+ const c = Math.max(0, t - i), d = (s = a[c]) != null ? s : l.length;
548
+ return { node: o, offset: d };
549
+ }
550
+ i += h;
551
+ continue;
552
+ }
553
+ if (o instanceof HTMLElement && !o.hasAttribute(this.trailingNewlineMarkerAttr) && o.hasAttribute(this.foldPlaceholderAttr)) {
554
+ const a = this.getFoldPlaceholderSource(o).length;
555
+ if (i + a >= t) {
556
+ const h = t - i;
557
+ return {
558
+ node: this.contentElement,
559
+ offset: h <= a / 2 ? r : r + 1
560
+ };
561
+ }
562
+ i += a;
563
+ }
564
+ }
565
+ return {
566
+ node: this.contentElement,
567
+ offset: this.contentElement.childNodes.length
568
+ };
569
+ }
570
+ getDomRangeFromClientPoint(e, t) {
571
+ const i = document;
572
+ if (typeof i.caretPositionFromPoint == "function") {
573
+ const n = i.caretPositionFromPoint(
574
+ e,
575
+ t
576
+ );
577
+ if (n != null && n.offsetNode) {
578
+ const s = document.createRange();
579
+ try {
580
+ return s.setStart(n.offsetNode, n.offset), s.collapse(!0), s;
581
+ } catch (r) {
582
+ return null;
583
+ }
584
+ }
585
+ }
586
+ return typeof i.caretRangeFromPoint == "function" ? i.caretRangeFromPoint(e, t) : null;
587
+ }
588
+ buildVisibleToDomMap(e) {
589
+ const t = [0];
590
+ let i = 0;
591
+ for (let n = 0; n < e.length; n++) {
592
+ const s = e[n];
593
+ this.virtualMarkerRegex.test(s) || (i += 1, t[i] = n + 1);
594
+ }
595
+ return t;
596
+ }
597
+ isNodeInsideContent(e) {
598
+ return e === this.contentElement || this.contentElement.contains(e);
599
+ }
600
+ getCaretClientRect(e) {
601
+ var o, l, a;
602
+ const t = e.getRangeAt(0).cloneRange();
603
+ t.collapse(!1);
604
+ const i = this.getUsableRangeRect(t);
605
+ if (i)
606
+ return i;
607
+ const n = e.focusNode, s = e.focusOffset;
608
+ if (n instanceof Text) {
609
+ const h = (l = (o = n.textContent) == null ? void 0 : o.length) != null ? l : 0, c = document.createRange();
610
+ if (s < h) {
611
+ c.setStart(n, s), c.setEnd(n, Math.min(h, s + 1));
612
+ const d = this.getUsableRangeRect(c);
613
+ if (d)
614
+ return d;
615
+ }
616
+ if (s > 0) {
617
+ c.setStart(n, s - 1), c.setEnd(n, s);
618
+ const d = this.getUsableRangeRect(c);
619
+ if (d)
620
+ return d;
621
+ }
622
+ }
623
+ const r = n instanceof Element ? n : (a = n == null ? void 0 : n.parentElement) != null ? a : null;
624
+ if (r && r !== this.contentElement && r !== this.editorContainer && this.contentElement.contains(r)) {
625
+ const h = r.getBoundingClientRect();
626
+ if (this.isUsableRect(h))
627
+ return h;
628
+ }
629
+ return null;
630
+ }
631
+ getUsableRangeRect(e) {
632
+ const t = Array.from(e.getClientRects());
633
+ for (let n = 0; n < t.length; n++)
634
+ if (this.isUsableRect(t[n]))
635
+ return t[n];
636
+ const i = e.getBoundingClientRect();
637
+ return this.isUsableRect(i) ? i : null;
638
+ }
639
+ isUsableRect(e) {
640
+ return !!e && Number.isFinite(e.top) && Number.isFinite(e.bottom) && (e.width > 0 || e.height > 0);
641
+ }
642
+ stripVirtualMarkers(e) {
643
+ return e.replace(this.virtualMarkerGlobalRegex, "");
644
+ }
645
+ clearHighlightOverlay() {
646
+ !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");
647
+ }
648
+ serializeContentToSource() {
649
+ let e = "";
650
+ const t = Array.from(this.contentElement.childNodes);
651
+ for (const i of t) {
652
+ if (i instanceof Text) {
653
+ e += this.stripVirtualMarkers(i.textContent || "");
654
+ continue;
655
+ }
656
+ if (i instanceof HTMLElement && !i.hasAttribute(this.trailingNewlineMarkerAttr)) {
657
+ if (i.hasAttribute(this.foldPlaceholderAttr)) {
658
+ e += this.getFoldPlaceholderSource(i);
659
+ continue;
660
+ }
661
+ e += this.stripVirtualMarkers(i.textContent || "");
662
+ }
663
+ }
664
+ return e;
665
+ }
666
+ sourceOffsetFromBoundary(e, t) {
667
+ let i = 0;
668
+ const n = Array.from(this.contentElement.childNodes);
669
+ if (e === this.contentElement) {
670
+ for (let s = 0; s < Math.min(t, n.length); s++)
671
+ i += this.getSourceLength(n[s]);
672
+ return i;
673
+ }
674
+ for (let s = 0; s < n.length; s++) {
675
+ const r = n[s];
676
+ if (r === e) {
677
+ if (r instanceof Text)
678
+ return i + this.stripVirtualMarkers((r.textContent || "").slice(0, t)).length;
679
+ if (r instanceof HTMLElement) {
680
+ if (r.hasAttribute(this.foldPlaceholderAttr))
681
+ return i + this.getFoldPlaceholderBoundaryOffset(
682
+ r,
683
+ r,
684
+ t
685
+ );
686
+ const o = Array.from(r.childNodes);
687
+ for (let l = 0; l < Math.min(t, o.length); l++)
688
+ i += this.getSourceLength(o[l]);
689
+ return i;
690
+ }
691
+ }
692
+ if (r instanceof HTMLElement && r.contains(e))
693
+ return r.hasAttribute(this.foldPlaceholderAttr) ? i + this.getFoldPlaceholderBoundaryOffset(
694
+ r,
695
+ e,
696
+ t
697
+ ) : i + this.sourceOffsetWithinNode(r, e, t);
698
+ i += this.getSourceLength(r);
699
+ }
700
+ return i;
701
+ }
702
+ sourceOffsetWithinNode(e, t, i) {
703
+ let n = 0;
704
+ const s = Array.from(e.childNodes);
705
+ if (t === e) {
706
+ for (let r = 0; r < Math.min(i, s.length); r++)
707
+ n += this.getSourceLength(s[r]);
708
+ return n;
709
+ }
710
+ for (let r = 0; r < s.length; r++) {
711
+ const o = s[r];
712
+ if (o === t) {
713
+ if (o instanceof Text)
714
+ return n + this.stripVirtualMarkers((o.textContent || "").slice(0, i)).length;
715
+ if (o instanceof HTMLElement) {
716
+ if (o.hasAttribute(this.foldPlaceholderAttr))
717
+ return n + this.getFoldPlaceholderBoundaryOffset(
718
+ o,
719
+ o,
720
+ i
721
+ );
722
+ const l = Array.from(o.childNodes);
723
+ for (let a = 0; a < Math.min(i, l.length); a++)
724
+ n += this.getSourceLength(l[a]);
725
+ return n;
726
+ }
727
+ }
728
+ if (o instanceof HTMLElement && o.contains(t))
729
+ return o.hasAttribute(this.foldPlaceholderAttr) ? n + this.getFoldPlaceholderBoundaryOffset(
730
+ o,
731
+ t,
732
+ i
733
+ ) : n + this.sourceOffsetWithinNode(o, t, i);
734
+ n += this.getSourceLength(o);
735
+ }
736
+ return n;
737
+ }
738
+ getSourceLength(e) {
739
+ if (e instanceof Text)
740
+ return this.stripVirtualMarkers(e.textContent || "").length;
741
+ if (!(e instanceof HTMLElement) || e.hasAttribute(this.trailingNewlineMarkerAttr))
742
+ return 0;
743
+ if (e.hasAttribute(this.foldPlaceholderAttr))
744
+ return this.getFoldPlaceholderSource(e).length;
745
+ let t = 0;
746
+ return e.childNodes.forEach((i) => {
747
+ t += this.getSourceLength(i);
748
+ }), t;
749
+ }
750
+ renderLineDecorations(e) {
751
+ const t = [...e].filter((s) => Number.isFinite(s.line) && s.line >= 0).sort((s, r) => s.line - r.line || s.id.localeCompare(r.id)), i = t.map(
752
+ (s) => `${s.id}:${s.line}:${s.className || ""}:${this.serializeStyleObject(s.style)}`
753
+ ).join("|");
754
+ if (i === this.lastLineDecorationSnapshot || (this.lineDecorationsElement.innerHTML = "", this.lastLineDecorationSnapshot = i, t.length === 0))
755
+ return;
756
+ const n = document.createDocumentFragment();
757
+ for (const s of t) {
758
+ const r = document.createElement("div");
759
+ r.className = this.joinClassNames(
760
+ "lce-decoration lce-decoration-line",
761
+ s.className
762
+ ), r.setAttribute("data-decoration-id", s.id), r.setAttribute("data-decoration-line", String(s.line)), r.style.cssText = this.joinStyleFragments([
763
+ "position: absolute",
764
+ `top: ${s.line * this.lineHeight}px`,
765
+ `height: ${this.lineHeight}px`,
766
+ "left: 12px",
767
+ "right: 12px",
768
+ "border-radius: 3px",
769
+ this.serializeStyleObject(s.style)
770
+ ]), n.appendChild(r);
771
+ }
772
+ this.lineDecorationsElement.appendChild(n);
773
+ }
774
+ renderGutterDecorations(e) {
775
+ const t = [...e].filter((s) => Number.isFinite(s.line) && s.line >= 0).sort((s, r) => s.line - r.line || s.id.localeCompare(r.id)), i = t.map(
776
+ (s) => `${s.id}:${s.line}:${s.label || ""}:${s.title || ""}:${s.className || ""}:${this.serializeStyleObject(s.style)}`
777
+ ).join("|");
778
+ if (i === this.lastGutterDecorationSnapshot || (this.gutterDecorationsElement.innerHTML = "", this.lastGutterDecorationSnapshot = i, t.length === 0))
779
+ return;
780
+ const n = document.createDocumentFragment();
781
+ for (const s of t) {
782
+ const r = document.createElement("div");
783
+ r.className = this.joinClassNames(
784
+ "lce-decoration lce-decoration-gutter",
785
+ s.className
786
+ ), r.setAttribute("data-decoration-id", s.id), r.setAttribute("data-decoration-line", String(s.line)), r.style.cssText = this.joinStyleFragments([
787
+ "position: absolute",
788
+ `top: ${s.line * this.lineHeight}px`,
789
+ `height: ${this.lineHeight}px`,
790
+ "left: 0",
791
+ "right: 0",
792
+ "display: flex",
793
+ "align-items: center",
794
+ "justify-content: flex-end",
795
+ "padding-right: 4px",
796
+ "box-sizing: border-box",
797
+ this.serializeStyleObject(s.style)
798
+ ]), s.title && (r.title = s.title), r.textContent = s.label || "", n.appendChild(r);
799
+ }
800
+ this.gutterDecorationsElement.appendChild(n);
801
+ }
802
+ joinClassNames(...e) {
803
+ return e.filter(Boolean).join(" ").trim();
804
+ }
805
+ joinStyleFragments(e) {
806
+ return e.filter((t) => !!t && t.trim().length > 0).map((t) => {
807
+ const i = t.trim();
808
+ return i.endsWith(";") ? i : `${i};`;
809
+ }).join(" ");
810
+ }
811
+ serializeStyleObject(e) {
812
+ return e ? Object.entries(e).filter(([, t]) => typeof t == "string" && t.length > 0).map(([t, i]) => `${this.toKebabCase(t)}: ${i}`).join("; ") : "";
813
+ }
814
+ toKebabCase(e) {
815
+ return e.replace(/[A-Z]/g, (t) => `-${t.toLowerCase()}`);
816
+ }
817
+ offsetToPositionInText(e, t) {
818
+ const i = Math.max(0, Math.min(e, t.length)), s = t.slice(0, i).split(`
819
+ `);
820
+ return {
821
+ line: s.length - 1,
822
+ column: s[s.length - 1].length
823
+ };
824
+ }
825
+ positionToTextOffset(e, t) {
826
+ var o;
827
+ const i = t.split(`
828
+ `), n = Math.max(0, Math.min(e.line, i.length - 1)), s = Math.max(
829
+ 0,
830
+ Math.min(e.column, ((o = i[n]) == null ? void 0 : o.length) || 0)
831
+ );
832
+ let r = 0;
833
+ for (let l = 0; l < n; l++)
834
+ r += i[l].length + 1;
835
+ return r + s;
836
+ }
837
+ getFoldPlaceholderSource(e) {
838
+ const t = e.getAttribute(this.foldPlaceholderAttr), i = this.getFoldPlaceholderSources();
839
+ return t && i.has(t) ? i.get(t) || "" : e.__lceFoldHiddenText || "";
840
+ }
841
+ getFoldPlaceholderSources() {
842
+ return this.contentElement.__lceFoldPlaceholderSources || /* @__PURE__ */ new Map();
843
+ }
844
+ getFoldPlaceholderBoundaryOffset(e, t, i) {
845
+ const n = this.getFoldPlaceholderSource(e).length, s = this.stripVirtualMarkers(e.textContent || "").length;
846
+ if (n === 0 || s === 0)
847
+ return 0;
848
+ const r = document.createRange();
849
+ r.selectNodeContents(e);
850
+ try {
851
+ r.setEnd(t, i);
852
+ } catch (l) {
853
+ return 0;
854
+ }
855
+ return this.stripVirtualMarkers(r.toString()).length <= s / 2 ? 0 : n;
856
+ }
857
+ setFoldPlaceholderSources(e) {
858
+ this.contentElement.__lceFoldPlaceholderSources = e;
859
+ }
860
+ }
861
+ let te = 0;
862
+ const C = class C {
863
+ constructor(e, t = {}) {
864
+ this.extensions = /* @__PURE__ */ new Map(), this.commands = /* @__PURE__ */ new Map(), this.eventListeners = /* @__PURE__ */ 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 = ++te, this.decorationHighlightStyleId = `editora-decoration-style-${this.editorInstanceId}`, this.decorationHighlightLimit = 1e3, this.decorationLayers = /* @__PURE__ */ new Map(), this.inlineDecorationHighlightNames = /* @__PURE__ */ new Set(), this.decorationRenderRaf = null, this.decorationMutationObserver = null, this.hasCustomDecorationHighlightSupport = !1, this.lastProgrammaticClipboardInsertAt = 0, this.config = {
865
+ value: "",
866
+ theme: "default",
867
+ readOnly: !1,
868
+ tabSize: 2,
869
+ lineWrapping: !1,
870
+ lineNumbers: !0,
871
+ ...t
872
+ }, this.textModel = new K(this.config.value), this.view = new ee(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();
873
+ }
874
+ // Public accessors for extensions
875
+ getTextModel() {
876
+ return this.textModel;
877
+ }
878
+ getView() {
879
+ return this.view;
880
+ }
881
+ getConfig() {
882
+ return { ...this.config };
883
+ }
884
+ // Register built-in editor commands like undo/redo/insertTab
885
+ registerBuiltInCommands() {
886
+ this.registerCommand("undo", () => this.undo()), this.registerCommand("redo", () => this.redo()), this.registerCommand("insertTab", () => this.insertTab()), this.registerCommand("outdent", () => {
887
+ this.shiftSelectedLines(!0);
888
+ }), this.registerCommand("save", () => {
889
+ this.emit("save");
890
+ });
891
+ }
892
+ // Get keymap extension if available
893
+ getKeymapExtension() {
894
+ return this.extensions.get("keymap");
895
+ }
896
+ // Setup DOM event handlers
897
+ setupEventHandlers() {
898
+ const e = this.view.getContentElement();
899
+ e.addEventListener("beforeinput", (t) => {
900
+ if (this.suppressHistory || this.config.readOnly) {
901
+ this.pendingInputSnapshot = void 0;
902
+ return;
903
+ }
904
+ if (t.inputType === "insertFromPaste" || t.inputType === "insertFromPasteAsQuotation" || t.inputType === "insertFromDrop") {
905
+ const i = t.dataTransfer, n = this.getPlainTextFromDataTransfer(i);
906
+ if (n.length === 0 || (t.preventDefault(), this.pendingInputSnapshot = void 0, Date.now() - this.lastProgrammaticClipboardInsertAt < 80))
907
+ return;
908
+ this.insertClipboardText(n);
909
+ return;
910
+ }
911
+ if (t.inputType === "insertParagraph" || t.inputType === "insertLineBreak") {
912
+ t.preventDefault(), this.pendingInputSnapshot = void 0, this.insertNewLine();
913
+ return;
914
+ }
915
+ if (!t.isComposing) {
916
+ const i = C.deletionUnit(t.inputType, "Backward");
917
+ if (i) {
918
+ t.preventDefault(), this.pendingInputSnapshot = void 0, this.deleteBackward(i);
919
+ return;
920
+ }
921
+ const n = C.deletionUnit(t.inputType, "Forward");
922
+ if (n) {
923
+ t.preventDefault(), this.pendingInputSnapshot = void 0, this.deleteForward(n);
924
+ return;
925
+ }
926
+ }
927
+ if (t.inputType === "deleteByCut") {
928
+ t.preventDefault(), this.pendingInputSnapshot = void 0, this.deleteSelection();
929
+ return;
930
+ }
931
+ if (t.inputType === "insertText" && typeof t.data == "string" && !t.isComposing) {
932
+ t.preventDefault(), this.pendingInputSnapshot = void 0, this.replaceSelectionWithText(t.data);
933
+ return;
934
+ }
935
+ this.pendingInputSnapshot = this.captureHistorySnapshot();
936
+ }), e.addEventListener("paste", (t) => {
937
+ if (this.config.readOnly) {
938
+ t.preventDefault();
939
+ return;
940
+ }
941
+ if (Date.now() - this.lastProgrammaticClipboardInsertAt < 80) {
942
+ t.preventDefault();
943
+ return;
944
+ }
945
+ const i = this.getPlainTextFromDataTransfer(t.clipboardData);
946
+ i.length !== 0 && (t.preventDefault(), this.insertClipboardText(i));
947
+ }), e.addEventListener("input", () => {
948
+ var n;
949
+ const t = this.view.getText(), i = this.textModel.getText();
950
+ t !== i ? (this.suppressHistory || this.pushUndoSnapshot(
951
+ (n = this.pendingInputSnapshot) != null ? n : this.captureHistorySnapshot(i)
952
+ ), this.pendingInputSnapshot = void 0, this.textModel.setText(t), this.view.syncTrailingNewlineMarkerForText(t), this.hasRenderedFoldPlaceholders() ? this.clearPendingHighlightRender() : (this.clearPendingHighlightRender(), this.highlightTimeout = setTimeout(() => {
953
+ const s = this.view.getText();
954
+ s !== this.textModel.getText() && this.textModel.setText(s), this.renderTextWithHighlight(this.textModel.getText(), !1), this.highlightTimeout = null;
955
+ }, 300)), this.updateLineNumbers(), this.emit("change", [{ range: this.getFullRange(), text: t, oldText: i }])) : this.pendingInputSnapshot = void 0;
956
+ }), this.documentSelectionChangeHandler = () => {
957
+ var n, s, r;
958
+ const t = this.syncSelectionCacheFromView();
959
+ if (!t.isInEditor)
960
+ return;
961
+ const i = (n = t.cursor) != null ? n : this.lastKnownCursor;
962
+ this.emit("cursor", {
963
+ position: i,
964
+ anchor: (r = (s = t.range) == null ? void 0 : s.start) != null ? r : i
965
+ }), this.emit("selection", t.isCollapsed ? void 0 : t.range);
966
+ }, document.addEventListener("selectionchange", this.documentSelectionChangeHandler), e.addEventListener("keydown", (t) => {
967
+ this.emit("keydown", t);
968
+ const i = Array.from(this.extensions.values()).reverse();
969
+ for (const r of i)
970
+ if (r.onKeyDown && r.onKeyDown(t) === !1) {
971
+ t.preventDefault(), t.stopPropagation();
972
+ return;
973
+ }
974
+ if (t.key === "Tab" && !this.config.readOnly) {
975
+ t.shiftKey ? this.shiftSelectedLines(!0) : this.insertTab(), t.preventDefault(), t.stopPropagation();
976
+ return;
977
+ }
978
+ const n = t.altKey || t.ctrlKey || t.metaKey, s = t.isComposing || t.keyCode === 229;
979
+ if (t.key === "Backspace" && !this.config.readOnly && !n && !s) {
980
+ this.deleteBackward(), t.preventDefault(), t.stopPropagation();
981
+ return;
982
+ }
983
+ if (t.key === "Delete" && !this.config.readOnly && !n && !s) {
984
+ this.deleteForward(), t.preventDefault(), t.stopPropagation();
985
+ return;
986
+ }
987
+ if (t.key === "Enter" && !this.config.readOnly) {
988
+ this.insertNewLine(), t.preventDefault(), t.stopPropagation();
989
+ return;
990
+ }
991
+ }), e.addEventListener("mousedown", (t) => {
992
+ this.emit("mousedown", t);
993
+ const i = Array.from(this.extensions.values()).reverse();
994
+ for (const n of i)
995
+ if (n.onMouseDown && n.onMouseDown(t) === !1) {
996
+ t.preventDefault(), t.stopPropagation();
997
+ return;
998
+ }
999
+ }), e.addEventListener("contextmenu", (t) => {
1000
+ this.emit("contextmenu", t);
1001
+ const i = Array.from(this.extensions.values()).reverse();
1002
+ for (const n of i)
1003
+ if (n.onContextMenu && n.onContextMenu(t) === !1) {
1004
+ t.preventDefault(), t.stopPropagation();
1005
+ return;
1006
+ }
1007
+ }), e.addEventListener("focus", () => {
1008
+ this.emit("focus");
1009
+ }), e.addEventListener("blur", () => {
1010
+ this.emit("blur");
1011
+ });
1012
+ }
1013
+ // Update line numbers display
1014
+ updateLineNumbers() {
1015
+ const e = this.textModel.getLineCount();
1016
+ this.view.updateLineNumbers(e);
1017
+ }
1018
+ // Get full range of document
1019
+ getFullRange() {
1020
+ return {
1021
+ start: { line: 0, column: 0 },
1022
+ end: {
1023
+ line: this.textModel.getLineCount() - 1,
1024
+ column: this.textModel.getLine(this.textModel.getLineCount() - 1).length
1025
+ }
1026
+ };
1027
+ }
1028
+ // Emit events to listeners
1029
+ emit(e, ...t) {
1030
+ const i = this.eventListeners.get(e);
1031
+ i && i.forEach((n) => n(...t));
1032
+ }
1033
+ // State management
1034
+ getValue() {
1035
+ return this.textModel.getText();
1036
+ }
1037
+ setValue(e) {
1038
+ const t = this.textModel.getText();
1039
+ this.textModel.setText(e), this.renderTextWithHighlight(e, !1), this.updateLineNumbers(), this.emit("change", [{ range: this.getFullRange(), text: e, oldText: t }]);
1040
+ }
1041
+ getState() {
1042
+ return {
1043
+ text: this.getValue(),
1044
+ cursor: this.getCursor(),
1045
+ selection: this.getSelection(),
1046
+ readOnly: this.config.readOnly || !1,
1047
+ theme: this.currentTheme
1048
+ };
1049
+ }
1050
+ // Cursor & Selection
1051
+ getCursor() {
1052
+ var i, n, s;
1053
+ const e = this.syncSelectionCacheFromView(), t = (i = e.cursor) != null ? i : this.lastKnownCursor;
1054
+ return {
1055
+ position: t,
1056
+ anchor: (s = (n = e.range) == null ? void 0 : n.start) != null ? s : t
1057
+ };
1058
+ }
1059
+ setCursor(e) {
1060
+ const t = this.textModel.getText(), i = this.clampPositionToText(e, t), n = this.positionToOffsetInText(i, t);
1061
+ this.lastKnownCursor = i, this.lastKnownSelection = void 0, this.view.setSelectionOffsets(n), this.emit("cursor", this.getCursor());
1062
+ }
1063
+ getSelection() {
1064
+ const e = this.syncSelectionCacheFromView();
1065
+ if (!(!e.isInEditor || e.isCollapsed))
1066
+ return e.range;
1067
+ }
1068
+ setSelection(e) {
1069
+ const t = this.textModel.getText(), i = this.normalizeRange({
1070
+ start: this.clampPositionToText(e.start, t),
1071
+ end: this.clampPositionToText(e.end, t)
1072
+ }), n = this.positionToOffsetInText(i.start, t), s = this.positionToOffsetInText(i.end, t);
1073
+ this.lastKnownSelection = i, this.lastKnownCursor = i.end, this.view.setSelectionOffsets(n, s), this.emit("selection", i);
1074
+ }
1075
+ // Configuration
1076
+ setTheme(e) {
1077
+ this.currentTheme = e;
1078
+ const t = {
1079
+ "editor-background": e === "dark" ? "#1e1e1e" : "#ffffff",
1080
+ "editor-foreground": e === "dark" ? "#f8f9fa" : "#1a1a1a",
1081
+ "editor-gutter-background": e === "dark" ? "#252526" : "#f8f9fa",
1082
+ "editor-gutter-foreground": e === "dark" ? "#858585" : "#666666",
1083
+ "editor-gutter-border": e === "dark" ? "#3e3e42" : "#e1e5e9"
1084
+ };
1085
+ this.view.applyTheme(t);
1086
+ const i = this.extensions.get("syntax-highlighting");
1087
+ if (i && typeof i.setTheme == "function")
1088
+ try {
1089
+ i.setTheme(e === "dark" ? "dark" : "light"), this.renderTextWithHighlight(this.textModel.getText());
1090
+ } catch (n) {
1091
+ console.warn("Error applying theme to syntax-highlighting extension", n);
1092
+ }
1093
+ }
1094
+ setReadOnly(e) {
1095
+ this.config.readOnly = e, this.view.setReadOnly(e);
1096
+ }
1097
+ // Extensions & Commands
1098
+ addExtension(e) {
1099
+ if (this.extensions.has(e.name))
1100
+ throw new Error(`Extension '${e.name}' already exists`);
1101
+ this.extensions.set(e.name, e), e.setup(this), e.name === "syntax-highlighting" && typeof e.highlightHTML == "function" && this.renderTextWithHighlight(this.textModel.getText());
1102
+ }
1103
+ removeExtension(e) {
1104
+ const t = this.extensions.get(e);
1105
+ t && t.destroy && t.destroy(), this.extensions.delete(e);
1106
+ }
1107
+ executeCommand(e, ...t) {
1108
+ const i = this.commands.get(e);
1109
+ i ? i(...t) : console.warn(`Command '${e}' not found`);
1110
+ }
1111
+ // Register a command
1112
+ registerCommand(e, t) {
1113
+ this.commands.set(e, t);
1114
+ }
1115
+ setDecorations(e, t) {
1116
+ const i = e.trim();
1117
+ if (!i)
1118
+ throw new Error("Decoration layer name must not be empty");
1119
+ if (!Array.isArray(t) || t.length === 0) {
1120
+ this.decorationLayers.delete(i), this.scheduleDecorationRender();
1121
+ return;
1122
+ }
1123
+ this.decorationLayers.set(
1124
+ i,
1125
+ t.map((n) => this.cloneDecoration(n))
1126
+ ), this.scheduleDecorationRender();
1127
+ }
1128
+ clearDecorations(e) {
1129
+ typeof e == "string" ? this.decorationLayers.delete(e.trim()) : this.decorationLayers.clear(), this.scheduleDecorationRender();
1130
+ }
1131
+ getDecorations(e) {
1132
+ if (typeof e == "string")
1133
+ return (this.decorationLayers.get(e.trim()) || []).map(
1134
+ (i) => this.cloneDecoration(i)
1135
+ );
1136
+ const t = [];
1137
+ for (const i of this.decorationLayers.values())
1138
+ t.push(
1139
+ ...i.map((n) => this.cloneDecoration(n))
1140
+ );
1141
+ return t;
1142
+ }
1143
+ // Search & Navigation
1144
+ search(e, t = {}) {
1145
+ var h;
1146
+ if (!e) return [];
1147
+ const i = {
1148
+ query: e,
1149
+ caseSensitive: !1,
1150
+ wholeWord: !1,
1151
+ regex: !1,
1152
+ ...t
1153
+ }, n = [], s = this.textModel.getText(), { normalizedText: r, normalizedToRawOffsets: o } = this.buildSearchTextAndOffsetMap(s), l = i.caseSensitive ? r : r.toLowerCase(), a = i.caseSensitive ? e : e.toLowerCase();
1154
+ if (i.regex) {
1155
+ let c;
1156
+ try {
1157
+ c = new RegExp(e, i.caseSensitive ? "g" : "gi");
1158
+ } catch (f) {
1159
+ return [];
1160
+ }
1161
+ let d;
1162
+ for (; (d = c.exec(r)) !== null; ) {
1163
+ const f = (h = d[0]) != null ? h : "";
1164
+ if (f.length === 0) {
1165
+ c.lastIndex = d.index + 1;
1166
+ continue;
1167
+ }
1168
+ const u = d.index, g = d.index + f.length;
1169
+ i.wholeWord && !this.isWholeWordBoundary(r, u, g) || this.pushSearchResultFromOffsets(
1170
+ n,
1171
+ u,
1172
+ g,
1173
+ r,
1174
+ o
1175
+ );
1176
+ }
1177
+ } else {
1178
+ let c = 0, d = l.indexOf(a, c);
1179
+ for (; d !== -1; ) {
1180
+ const f = d + a.length;
1181
+ !i.wholeWord || this.isWholeWordBoundary(r, d, f) ? (this.pushSearchResultFromOffsets(
1182
+ n,
1183
+ d,
1184
+ f,
1185
+ r,
1186
+ o
1187
+ ), c = f) : c = d + 1, d = l.indexOf(a, c);
1188
+ }
1189
+ }
1190
+ return n;
1191
+ }
1192
+ pushSearchResultFromOffsets(e, t, i, n, s) {
1193
+ var h, c;
1194
+ const r = (h = s[t]) != null ? h : t, o = (c = s[i]) != null ? c : r, l = this.textModel.offsetToPosition(r), a = this.textModel.offsetToPosition(o);
1195
+ e.push({
1196
+ range: { start: l, end: a },
1197
+ match: n.substring(t, i)
1198
+ });
1199
+ }
1200
+ isWholeWordBoundary(e, t, i) {
1201
+ const n = t > 0 ? e[t - 1] : "", s = i < e.length ? e[i] : "";
1202
+ return !this.isWordChar(n) && !this.isWordChar(s);
1203
+ }
1204
+ isWordChar(e) {
1205
+ return /^[A-Za-z0-9_]$/.test(e);
1206
+ }
1207
+ buildSearchTextAndOffsetMap(e) {
1208
+ const t = [], i = [0];
1209
+ let n = 0;
1210
+ for (let s = 0; s < e.length; s++) {
1211
+ const r = e[s];
1212
+ r === "​" || r === C.CURSOR_SENTINEL || (t.push(r), n += 1, i[n] = s + 1);
1213
+ }
1214
+ return i[n] = e.length, {
1215
+ normalizedText: t.join(""),
1216
+ normalizedToRawOffsets: i
1217
+ };
1218
+ }
1219
+ replace(e, t) {
1220
+ const i = this.getValue();
1221
+ this.suppressHistory || this.pushUndoSnapshot(this.captureHistorySnapshot(i));
1222
+ const n = this.textModel.replaceRange(e, t);
1223
+ this.expectingProgrammaticCursor = !0, this.renderTextWithHighlight(this.getValue(), !1), this.expectingProgrammaticCursor = !1, this.emit("change", [n]);
1224
+ }
1225
+ replaceAll(e, t, i = {}) {
1226
+ const n = this.search(e, i);
1227
+ if (n.length === 0) return 0;
1228
+ this.suppressHistory || this.pushUndoSnapshot(this.captureHistorySnapshot(this.getValue()));
1229
+ const s = [];
1230
+ for (let r = n.length - 1; r >= 0; r--)
1231
+ s.push(this.textModel.replaceRange(n[r].range, t));
1232
+ return this.expectingProgrammaticCursor = !0, this.renderTextWithHighlight(this.getValue(), !1), this.expectingProgrammaticCursor = !1, this.emit("change", s), n.length;
1233
+ }
1234
+ // Folding (basic implementation)
1235
+ fold(e) {
1236
+ this.clearPendingHighlightRender();
1237
+ const t = this.normalizeRange(e);
1238
+ if (t.start.line === t.end.line && t.start.column === t.end.column)
1239
+ return;
1240
+ const i = this.folds.findIndex(
1241
+ (s) => this.isSameFoldRange(s, t)
1242
+ ), n = {
1243
+ start: t.start,
1244
+ end: t.end,
1245
+ collapsed: !0,
1246
+ level: 0
1247
+ };
1248
+ i !== -1 ? this.folds[i] = n : (this.folds.push(n), this.folds.sort((s, r) => this.comparePositions(s.start, r.start)));
1249
+ }
1250
+ unfold(e) {
1251
+ this.clearPendingHighlightRender();
1252
+ const t = this.normalizeRange(e);
1253
+ this.folds = this.folds.filter(
1254
+ (i) => !this.isSameFoldRange(i, t)
1255
+ );
1256
+ }
1257
+ getFolds() {
1258
+ return [...this.folds];
1259
+ }
1260
+ // Utilities
1261
+ focus() {
1262
+ this.view.focus();
1263
+ }
1264
+ blur() {
1265
+ this.view.blur();
1266
+ }
1267
+ // Render text using syntax highlighting extension if available
1268
+ // If `restoreSelection` is true (default), the method captures current selection/caret
1269
+ // and restores it after updating the DOM. Callers that will explicitly set the caret
1270
+ // should pass `false` to avoid stomping programmatic cursor changes.
1271
+ renderTextWithHighlight(e, t = !0) {
1272
+ const i = this.extensions.get("syntax-highlighting");
1273
+ if (i && typeof i.highlightHTML == "function")
1274
+ try {
1275
+ if (typeof this.view.setHighlightHTML == "function") {
1276
+ const g = this.view.getContentElement();
1277
+ (g.querySelector(
1278
+ "[data-lce-fold-placeholder]"
1279
+ ) || g.textContent !== e) && this.view.setText(e);
1280
+ const m = typeof i.highlight == "function" ? i.highlight(e) : i.highlightHTML(e);
1281
+ this.view.setHighlightHTML(m), this.view.syncTrailingNewlineMarkerForText(e), this.scheduleDecorationRender();
1282
+ return;
1283
+ }
1284
+ const s = !t && !this.expectingProgrammaticCursor;
1285
+ let r, o, l, a;
1286
+ const h = this.view.getSelectionState(), c = h.isInEditor && !!h.cursor;
1287
+ (t || s) && c && (r = h.isCollapsed ? void 0 : h.range, o = this.textModel.positionToOffset(h.cursor), r && (l = this.textModel.positionToOffset(r.start), a = this.textModel.positionToOffset(r.end)));
1288
+ const d = c && (t || s) && !r && o !== void 0 && this.hasCollapsedSelectionInEditor(), f = d ? this.insertSentinelAtOffset(e, o) : e, u = typeof i.highlight == "function" ? i.highlight(f) : i.highlightHTML(f);
1289
+ typeof this.view.setHighlightHTML == "function" ? this.view.setHighlightHTML(u) : this.view.setHTML(u), this.view.syncTrailingNewlineMarkerForText(e), (t || s) && c && requestAnimationFrame(() => {
1290
+ try {
1291
+ if (d && this.restoreCursorFromSentinel()) {
1292
+ this.view.ensureCaretVisible();
1293
+ return;
1294
+ }
1295
+ if (r && (l !== void 0 || a !== void 0)) {
1296
+ const g = l !== void 0 ? l : o, p = a !== void 0 ? a : o, m = Math.min(g, p), y = Math.max(g, p), v = this.textModel.offsetToPosition(m), S = this.textModel.offsetToPosition(y);
1297
+ this.view.setSelectionRange({ start: v, end: S });
1298
+ } else if (o !== void 0) {
1299
+ const g = this.textModel.offsetToPosition(o);
1300
+ this.view.setCursorPosition(g);
1301
+ }
1302
+ } catch (g) {
1303
+ }
1304
+ }), this.scheduleDecorationRender();
1305
+ return;
1306
+ } catch (n) {
1307
+ console.warn("Syntax highlighting failed, falling back to plain text", n);
1308
+ }
1309
+ this.view.setText(e), this.scheduleDecorationRender();
1310
+ }
1311
+ hasCollapsedSelectionInEditor() {
1312
+ const e = window.getSelection();
1313
+ if (!e || e.rangeCount === 0 || !e.isCollapsed)
1314
+ return !1;
1315
+ const t = e.getRangeAt(0);
1316
+ return this.view.getContentElement().contains(t.commonAncestorContainer);
1317
+ }
1318
+ getCollapsedSelectionOffsetInEditor() {
1319
+ const e = window.getSelection();
1320
+ if (!e || e.rangeCount === 0 || !e.isCollapsed)
1321
+ return;
1322
+ const t = e.getRangeAt(0), i = this.view.getContentElement();
1323
+ if (!i.contains(t.commonAncestorContainer))
1324
+ return;
1325
+ const n = t.cloneRange();
1326
+ return n.selectNodeContents(i), n.setEnd(t.endContainer, t.endOffset), this.stripVirtualMarkers(n.toString()).length;
1327
+ }
1328
+ stripVirtualMarkers(e) {
1329
+ return e.replace(/\u200B/g, "").split(C.CURSOR_SENTINEL).join("");
1330
+ }
1331
+ insertSentinelAtOffset(e, t) {
1332
+ const i = Math.max(0, Math.min(t, e.length));
1333
+ return e.slice(0, i) + C.CURSOR_SENTINEL + e.slice(i);
1334
+ }
1335
+ restoreCursorFromSentinel() {
1336
+ var o;
1337
+ const e = this.view.getContentElement(), t = window.getSelection(), i = document.createTreeWalker(e, NodeFilter.SHOW_TEXT);
1338
+ let n = i.nextNode(), s = null, r = 0;
1339
+ for (; n; ) {
1340
+ const l = (o = n.textContent) != null ? o : "", a = l.indexOf(C.CURSOR_SENTINEL);
1341
+ a !== -1 && (s || (s = n, r = a), n.textContent = l.split(C.CURSOR_SENTINEL).join("")), n = i.nextNode();
1342
+ }
1343
+ if (!s || !t) return !1;
1344
+ try {
1345
+ const l = document.createRange();
1346
+ return l.setStart(s, r), l.collapse(!0), t.removeAllRanges(), t.addRange(l), !0;
1347
+ } catch (l) {
1348
+ return !1;
1349
+ }
1350
+ }
1351
+ destroy() {
1352
+ var e;
1353
+ if (!this.isDestroyed) {
1354
+ this.isDestroyed = !0, this.highlightTimeout && (clearTimeout(this.highlightTimeout), this.highlightTimeout = null), this.pendingInputSnapshot = void 0, this.documentSelectionChangeHandler && (document.removeEventListener("selectionchange", this.documentSelectionChangeHandler), this.documentSelectionChangeHandler = void 0), this.decorationRenderRaf !== null && typeof cancelAnimationFrame == "function" && (cancelAnimationFrame(this.decorationRenderRaf), this.decorationRenderRaf = null), (e = this.decorationMutationObserver) == null || e.disconnect(), this.decorationMutationObserver = null, this.clearInlineDecorationHighlights(!0), this.decorationLayers.clear(), this.view.clearDecorations();
1355
+ for (const t of this.extensions.values())
1356
+ t.destroy && t.destroy();
1357
+ this.extensions.clear(), this.view.destroy(), this.commands.clear(), this.eventListeners.clear();
1358
+ }
1359
+ }
1360
+ // History: undo/redo
1361
+ undo() {
1362
+ if (this.undoStack.length === 0) return;
1363
+ const e = this.undoStack.pop(), t = this.captureHistorySnapshot();
1364
+ this.pushSnapshot(this.redoStack, t);
1365
+ try {
1366
+ this.suppressHistory = !0, this.expectingProgrammaticCursor = !0, this.restoreHistorySnapshot(e), setTimeout(() => {
1367
+ this.expectingProgrammaticCursor = !1;
1368
+ }, 30);
1369
+ } finally {
1370
+ this.suppressHistory = !1;
1371
+ }
1372
+ }
1373
+ redo() {
1374
+ if (this.redoStack.length === 0) return;
1375
+ const e = this.redoStack.pop(), t = this.captureHistorySnapshot();
1376
+ this.pushSnapshot(this.undoStack, t);
1377
+ try {
1378
+ this.suppressHistory = !0, this.expectingProgrammaticCursor = !0, this.restoreHistorySnapshot(e), setTimeout(() => {
1379
+ this.expectingProgrammaticCursor = !1;
1380
+ }, 30);
1381
+ } finally {
1382
+ this.suppressHistory = !1;
1383
+ }
1384
+ }
1385
+ // Insert a tab character or spaces at current cursor
1386
+ insertTab() {
1387
+ if (this.config.readOnly || this.shiftSelectedLines(!1)) return;
1388
+ const e = " ".repeat(this.config.tabSize || 2);
1389
+ this.replaceSelectionWithText(e);
1390
+ }
1391
+ /**
1392
+ * Tab / Shift+Tab over whole lines. Tab only applies when the selection spans lines (a caret
1393
+ * or single-line selection keeps the plain "insert a tab" behaviour); Shift+Tab always
1394
+ * outdents the line(s) it touches. Returns false when the caller should fall back to inserting.
1395
+ * The edit is one replace, so it is one undo step, and the selection is kept on the same text.
1396
+ */
1397
+ shiftSelectedLines(e) {
1398
+ if (this.config.readOnly) return !1;
1399
+ const t = this.textModel.getText(), { startOffset: i, endOffset: n } = this.getActiveSelectionOffsets(t), s = Math.min(i, n), r = Math.max(i, n);
1400
+ if (!e && !t.slice(s, r).includes(`
1401
+ `)) return !1;
1402
+ const o = " ".repeat(this.config.tabSize || 2), l = t.lastIndexOf(`
1403
+ `, s - 1) + 1, a = r > s && t[r - 1] === `
1404
+ ` ? r - 1 : r, h = t.indexOf(`
1405
+ `, a), c = h === -1 ? t.length : h, d = t.slice(l, c).split(`
1406
+ `);
1407
+ let f = 0, u = 0;
1408
+ const g = d.map((y, v) => {
1409
+ let S = y;
1410
+ if (!e)
1411
+ S = y.length === 0 ? y : o + y;
1412
+ else if (y.startsWith(" "))
1413
+ S = y.slice(1);
1414
+ else {
1415
+ const M = /^ */.exec(y)[0].length;
1416
+ S = y.slice(Math.min(M, o.length));
1417
+ }
1418
+ const w = S.length - y.length;
1419
+ return v === 0 && (f = w), u += w, S;
1420
+ });
1421
+ if (u === 0) return !0;
1422
+ this.replaceOffsetsWithText(l, c, g.join(`
1423
+ `));
1424
+ const p = Math.max(l, s + f), m = Math.max(p, r + u);
1425
+ return s === r ? this.setCursor(this.textModel.offsetToPosition(p)) : this.setSelection({
1426
+ start: this.textModel.offsetToPosition(p),
1427
+ end: this.textModel.offsetToPosition(m)
1428
+ }), !0;
1429
+ }
1430
+ // Insert a newline at current cursor position
1431
+ insertNewLine() {
1432
+ this.config.readOnly || this.replaceSelectionWithText(`
1433
+ `);
1434
+ }
1435
+ deleteBackward(e = "char") {
1436
+ this.config.readOnly || this.deleteUsingDirection("backward", e);
1437
+ }
1438
+ deleteForward(e = "char") {
1439
+ this.config.readOnly || this.deleteUsingDirection("forward", e);
1440
+ }
1441
+ /** Map an InputEvent.inputType to the unit it deletes, or null when it isn't a delete in that direction. */
1442
+ static deletionUnit(e, t) {
1443
+ return e === `deleteContent${t}` ? "char" : e === `deleteWord${t}` ? "word" : e === `deleteSoftLine${t}` || e === `deleteHardLine${t}` ? "line" : null;
1444
+ }
1445
+ deleteSelection() {
1446
+ if (this.config.readOnly) return;
1447
+ const e = this.textModel.getText(), { startOffset: t, endOffset: i } = this.getActiveSelectionOffsets(e), n = Math.min(t, i), s = Math.max(t, i);
1448
+ n !== s && this.replaceOffsetsWithText(n, s, "");
1449
+ }
1450
+ // Events
1451
+ on(e, t) {
1452
+ this.eventListeners.has(e) || this.eventListeners.set(e, []), this.eventListeners.get(e).push(t);
1453
+ }
1454
+ off(e, t) {
1455
+ if (!this.eventListeners.has(e)) return;
1456
+ const i = this.eventListeners.get(e);
1457
+ if (t) {
1458
+ const n = i.indexOf(t);
1459
+ n !== -1 && i.splice(n, 1);
1460
+ } else
1461
+ i.length = 0;
1462
+ }
1463
+ normalizeRange(e) {
1464
+ return this.comparePositions(e.start, e.end) <= 0 ? e : { start: e.end, end: e.start };
1465
+ }
1466
+ comparePositions(e, t) {
1467
+ return e.line !== t.line ? e.line - t.line : e.column - t.column;
1468
+ }
1469
+ captureHistorySnapshot(e = this.textModel.getText()) {
1470
+ const t = this.view.getSelectionState(), i = t.isInEditor && !t.isCollapsed ? t.range : void 0, n = t.isInEditor && t.cursor ? t.cursor : void 0, s = i != null ? i : this.lastKnownSelection, r = n != null ? n : this.lastKnownCursor, o = this.clampPositionToText(r, e), l = {
1471
+ text: e,
1472
+ cursorOffset: this.positionToOffsetInText(o, e)
1473
+ };
1474
+ if (s) {
1475
+ const a = this.clampPositionToText(s.start, e), h = this.clampPositionToText(s.end, e);
1476
+ l.anchorOffset = this.positionToOffsetInText(a, e), l.focusOffset = this.positionToOffsetInText(h, e);
1477
+ }
1478
+ return l;
1479
+ }
1480
+ restoreHistorySnapshot(e) {
1481
+ this.setValue(e.text), requestAnimationFrame(() => {
1482
+ try {
1483
+ if (e.anchorOffset !== void 0 && e.focusOffset !== void 0 && e.anchorOffset !== e.focusOffset) {
1484
+ const i = Math.min(e.anchorOffset, e.focusOffset), n = Math.max(e.anchorOffset, e.focusOffset);
1485
+ this.setSelection({
1486
+ start: this.textModel.offsetToPosition(i),
1487
+ end: this.textModel.offsetToPosition(n)
1488
+ });
1489
+ return;
1490
+ }
1491
+ this.setCursor(this.textModel.offsetToPosition(e.cursorOffset));
1492
+ } catch (t) {
1493
+ }
1494
+ });
1495
+ }
1496
+ pushUndoSnapshot(e) {
1497
+ this.pushSnapshot(this.undoStack, e), this.redoStack.length = 0;
1498
+ }
1499
+ pushSnapshot(e, t) {
1500
+ e.push(t), e.length > 100 && e.shift();
1501
+ }
1502
+ clampPositionToText(e, t) {
1503
+ var r, o;
1504
+ const i = t.split(`
1505
+ `), n = Math.max(0, Math.min(e.line, i.length - 1)), s = Math.max(
1506
+ 0,
1507
+ Math.min(e.column, (o = (r = i[n]) == null ? void 0 : r.length) != null ? o : 0)
1508
+ );
1509
+ return {
1510
+ line: n,
1511
+ column: s
1512
+ };
1513
+ }
1514
+ positionToOffsetInText(e, t) {
1515
+ var r, o;
1516
+ const i = t.split(`
1517
+ `), n = this.clampPositionToText(e, t);
1518
+ let s = 0;
1519
+ for (let l = 0; l < n.line; l++)
1520
+ s += ((o = (r = i[l]) == null ? void 0 : r.length) != null ? o : 0) + 1;
1521
+ return s + n.column;
1522
+ }
1523
+ clearPendingHighlightRender() {
1524
+ this.highlightTimeout && (clearTimeout(this.highlightTimeout), this.highlightTimeout = null);
1525
+ }
1526
+ hasRenderedFoldPlaceholders() {
1527
+ return !!this.view.getContentElement().querySelector("[data-lce-fold-placeholder]");
1528
+ }
1529
+ replaceSelectionWithText(e) {
1530
+ const t = e.replace(/\r\n?/g, `
1531
+ `), i = this.textModel.getText(), { startOffset: n, endOffset: s } = this.getActiveSelectionOffsets(i), r = Math.max(0, Math.min(n, s)), o = Math.max(0, Math.max(n, s));
1532
+ return this.replaceOffsetsWithText(r, o, t);
1533
+ }
1534
+ insertClipboardText(e) {
1535
+ this.pendingInputSnapshot = this.captureHistorySnapshot(), this.lastProgrammaticClipboardInsertAt = Date.now(), this.replaceSelectionWithText(this.normalizeClipboardText(e));
1536
+ }
1537
+ normalizeClipboardText(e) {
1538
+ return e.replace(/\r\n?/g, `
1539
+ `).replace(/\u00a0/g, " ");
1540
+ }
1541
+ getPlainTextFromDataTransfer(e) {
1542
+ if (!e)
1543
+ return "";
1544
+ const t = e.getData("text/plain");
1545
+ if (t)
1546
+ return t;
1547
+ const i = e.getData("text/html");
1548
+ return i ? this.htmlClipboardToPlainText(i) : "";
1549
+ }
1550
+ htmlClipboardToPlainText(e) {
1551
+ const t = document.implementation.createHTMLDocument("");
1552
+ t.body.innerHTML = e;
1553
+ const i = /* @__PURE__ */ new Set([
1554
+ "ADDRESS",
1555
+ "ARTICLE",
1556
+ "ASIDE",
1557
+ "BLOCKQUOTE",
1558
+ "BR",
1559
+ "DD",
1560
+ "DIV",
1561
+ "DL",
1562
+ "DT",
1563
+ "FIGCAPTION",
1564
+ "FIGURE",
1565
+ "FOOTER",
1566
+ "H1",
1567
+ "H2",
1568
+ "H3",
1569
+ "H4",
1570
+ "H5",
1571
+ "H6",
1572
+ "HEADER",
1573
+ "HR",
1574
+ "LI",
1575
+ "MAIN",
1576
+ "NAV",
1577
+ "OL",
1578
+ "P",
1579
+ "PRE",
1580
+ "SECTION",
1581
+ "TABLE",
1582
+ "TR",
1583
+ "UL"
1584
+ ]), n = (o) => {
1585
+ var l;
1586
+ for (let a = o.length - 1; a >= 0; a--) {
1587
+ const h = (l = o[a]) != null ? l : "";
1588
+ if (h.length !== 0)
1589
+ return h.endsWith(`
1590
+ `);
1591
+ }
1592
+ return !1;
1593
+ }, s = (o, l) => {
1594
+ if (o instanceof Text) {
1595
+ l.push(o.data);
1596
+ return;
1597
+ }
1598
+ if (!(o instanceof HTMLElement)) {
1599
+ o.childNodes.forEach((h) => s(h, l));
1600
+ return;
1601
+ }
1602
+ if (o.tagName === "BR") {
1603
+ l.push(`
1604
+ `);
1605
+ return;
1606
+ }
1607
+ const a = i.has(o.tagName);
1608
+ a && l.length > 0 && !n(l) && l.push(`
1609
+ `), o.childNodes.forEach((h) => s(h, l)), a && !n(l) && l.push(`
1610
+ `);
1611
+ }, r = [];
1612
+ return t.body.childNodes.forEach((o) => s(o, r)), r.join("").replace(/\n{3,}/g, `
1613
+
1614
+ `).replace(/[ \t]+\n/g, `
1615
+ `).trimEnd();
1616
+ }
1617
+ getActiveSelectionOffsets(e) {
1618
+ const t = this.view.getSelectionOffsets();
1619
+ if (t.isInEditor)
1620
+ return {
1621
+ startOffset: t.startOffset,
1622
+ endOffset: t.endOffset
1623
+ };
1624
+ if (this.lastKnownSelection)
1625
+ return {
1626
+ startOffset: this.positionToOffsetInText(this.lastKnownSelection.start, e),
1627
+ endOffset: this.positionToOffsetInText(this.lastKnownSelection.end, e)
1628
+ };
1629
+ const i = this.positionToOffsetInText(this.lastKnownCursor, e);
1630
+ return {
1631
+ startOffset: i,
1632
+ endOffset: i
1633
+ };
1634
+ }
1635
+ deleteUsingDirection(e, t = "char") {
1636
+ const i = this.textModel.getText(), { startOffset: n, endOffset: s } = this.getActiveSelectionOffsets(i), r = Math.min(n, s), o = Math.max(n, s);
1637
+ if (r !== o) {
1638
+ this.replaceOffsetsWithText(r, o, "");
1639
+ return;
1640
+ }
1641
+ if (e === "backward") {
1642
+ if (r === 0)
1643
+ return;
1644
+ const a = C.deletionBoundary(i, r, "backward", t);
1645
+ this.replaceOffsetsWithText(a, r, "");
1646
+ return;
1647
+ }
1648
+ if (o >= i.length)
1649
+ return;
1650
+ const l = C.deletionBoundary(i, o, "forward", t);
1651
+ this.replaceOffsetsWithText(o, l, "");
1652
+ }
1653
+ static getGraphemeSegmenter() {
1654
+ if (C.graphemeSegmenter === void 0) {
1655
+ const e = Intl.Segmenter;
1656
+ C.graphemeSegmenter = e ? new e(void 0, { granularity: "grapheme" }) : null;
1657
+ }
1658
+ return C.graphemeSegmenter;
1659
+ }
1660
+ /**
1661
+ * Where a deletion of `unit` starting at `offset` ends. Characters are whole grapheme
1662
+ * clusters (an emoji is two UTF-16 units, a flag or ZWJ sequence several), so Backspace
1663
+ * never leaves half a surrogate pair behind - that used to turn "a😀b" into "a\uD83Db",
1664
+ * which is invalid text once saved.
1665
+ */
1666
+ static deletionBoundary(e, t, i, n) {
1667
+ const s = (d) => /[A-Za-z0-9_]/.test(d), r = (d) => d === " " || d === " ";
1668
+ if (n === "line") {
1669
+ if (i === "backward") {
1670
+ const u = e.lastIndexOf(`
1671
+ `, t - 1) + 1;
1672
+ return u === t ? t - 1 : u;
1673
+ }
1674
+ const d = e.indexOf(`
1675
+ `, t), f = d === -1 ? e.length : d;
1676
+ return f === t ? Math.min(e.length, t + 1) : f;
1677
+ }
1678
+ if (n === "word") {
1679
+ let d = t;
1680
+ if (i === "backward") {
1681
+ if (e[d - 1] === `
1682
+ `) return d - 1;
1683
+ for (; d > 0 && r(e[d - 1]); ) d--;
1684
+ if (d > 0 && e[d - 1] !== `
1685
+ `) {
1686
+ const f = s(e[d - 1]);
1687
+ for (; d > 0 && e[d - 1] !== `
1688
+ ` && !r(e[d - 1]) && s(e[d - 1]) === f; ) d--;
1689
+ }
1690
+ return d;
1691
+ }
1692
+ if (e[d] === `
1693
+ `) return d + 1;
1694
+ for (; d < e.length && r(e[d]); ) d++;
1695
+ if (d < e.length && e[d] !== `
1696
+ `) {
1697
+ const f = s(e[d]);
1698
+ for (; d < e.length && e[d] !== `
1699
+ ` && !r(e[d]) && s(e[d]) === f; ) d++;
1700
+ }
1701
+ return d;
1702
+ }
1703
+ if (i === "backward") {
1704
+ const d = e.lastIndexOf(`
1705
+ `, t - 1) + 1;
1706
+ if (d === t) return t - 1;
1707
+ const f = C.getGraphemeSegmenter();
1708
+ if (f) {
1709
+ let p = 1;
1710
+ for (const { segment: m } of f.segment(e.slice(d, t))) p = m.length;
1711
+ return t - p;
1712
+ }
1713
+ const u = e.charCodeAt(t - 1), g = t >= 2 ? e.charCodeAt(t - 2) : 0;
1714
+ return u >= 56320 && u <= 57343 && g >= 55296 && g <= 56319 ? t - 2 : t - 1;
1715
+ }
1716
+ if (e[t] === `
1717
+ `) return t + 1;
1718
+ const o = e.indexOf(`
1719
+ `, t), l = o === -1 ? e.length : o, a = C.getGraphemeSegmenter();
1720
+ if (a) {
1721
+ for (const { segment: d } of a.segment(e.slice(t, l))) return t + d.length;
1722
+ return t + 1;
1723
+ }
1724
+ const h = e.charCodeAt(t), c = t + 1 < e.length ? e.charCodeAt(t + 1) : 0;
1725
+ return h >= 55296 && h <= 56319 && c >= 56320 && c <= 57343 ? t + 2 : t + 1;
1726
+ }
1727
+ replaceOffsetsWithText(e, t, i) {
1728
+ var f;
1729
+ this.ensureEditableSurfaceIsUnfolded();
1730
+ const n = i.replace(/\r\n?/g, `
1731
+ `), s = this.textModel.getText(), r = (f = this.pendingInputSnapshot) != null ? f : this.captureHistorySnapshot(s), o = Math.max(0, Math.min(e, s.length)), l = Math.max(0, Math.min(t, s.length)), a = Math.min(o, l), h = Math.max(o, l), c = this.textModel.replaceRange(
1732
+ {
1733
+ start: this.textModel.offsetToPosition(a),
1734
+ end: this.textModel.offsetToPosition(h)
1735
+ },
1736
+ n
1737
+ );
1738
+ this.pendingInputSnapshot = void 0, this.suppressHistory || this.pushUndoSnapshot(r);
1739
+ const d = a + n.length;
1740
+ return this.expectingProgrammaticCursor = !0, this.renderTextWithHighlight(this.textModel.getText(), !1), this.setCursor(this.textModel.offsetToPosition(d)), setTimeout(() => {
1741
+ this.expectingProgrammaticCursor = !1;
1742
+ }, 20), this.emit("change", [c]), c;
1743
+ }
1744
+ ensureEditableSurfaceIsUnfolded() {
1745
+ !this.hasRenderedFoldPlaceholders() && this.folds.length === 0 || (this.clearPendingHighlightRender(), this.folds = [], this.expectingProgrammaticCursor = !0, this.renderTextWithHighlight(this.textModel.getText(), !1), setTimeout(() => {
1746
+ this.expectingProgrammaticCursor = !1;
1747
+ }, 20));
1748
+ }
1749
+ syncSelectionCacheFromView() {
1750
+ const e = this.view.getSelectionState();
1751
+ return e.isInEditor && e.cursor && (this.lastKnownCursor = e.cursor, this.lastKnownSelection = e.isCollapsed ? void 0 : e.range), e;
1752
+ }
1753
+ isSameFoldRange(e, t) {
1754
+ 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;
1755
+ }
1756
+ scheduleDecorationRender() {
1757
+ if (!this.isDestroyed) {
1758
+ if (typeof requestAnimationFrame != "function") {
1759
+ this.applyDecorations();
1760
+ return;
1761
+ }
1762
+ this.decorationRenderRaf === null && (this.decorationRenderRaf = requestAnimationFrame(() => {
1763
+ this.decorationRenderRaf = null, this.applyDecorations();
1764
+ }));
1765
+ }
1766
+ }
1767
+ applyDecorations() {
1768
+ if (this.isDestroyed)
1769
+ return;
1770
+ if (this.decorationLayers.size === 0) {
1771
+ this.view.clearDecorations(), this.clearInlineDecorationHighlights();
1772
+ return;
1773
+ }
1774
+ const e = [], t = [], i = [];
1775
+ for (const [n, s] of this.decorationLayers.entries())
1776
+ for (const r of s) {
1777
+ const o = `${n}::${r.id}`;
1778
+ if (r.type === "line") {
1779
+ e.push({
1780
+ ...r,
1781
+ id: o
1782
+ });
1783
+ continue;
1784
+ }
1785
+ if (r.type === "gutter") {
1786
+ t.push({
1787
+ ...r,
1788
+ id: o
1789
+ });
1790
+ continue;
1791
+ }
1792
+ i.push({
1793
+ ...r,
1794
+ id: o
1795
+ });
1796
+ }
1797
+ this.view.setDecorations(
1798
+ this.normalizeLineDecorations(e),
1799
+ this.normalizeGutterDecorations(t)
1800
+ ), this.renderInlineDecorations(i);
1801
+ }
1802
+ normalizeLineDecorations(e) {
1803
+ const t = Math.max(0, this.textModel.getLineCount() - 1);
1804
+ return e.filter((i) => Number.isFinite(i.line)).map((i) => ({
1805
+ ...i,
1806
+ line: Math.max(0, Math.min(t, Math.floor(i.line))),
1807
+ style: i.style ? { ...i.style } : void 0
1808
+ }));
1809
+ }
1810
+ normalizeGutterDecorations(e) {
1811
+ const t = Math.max(0, this.textModel.getLineCount() - 1);
1812
+ return e.filter((i) => Number.isFinite(i.line)).map((i) => ({
1813
+ ...i,
1814
+ line: Math.max(0, Math.min(t, Math.floor(i.line))),
1815
+ style: i.style ? { ...i.style } : void 0
1816
+ }));
1817
+ }
1818
+ renderInlineDecorations(e) {
1819
+ if (!this.hasCustomDecorationHighlightSupport) {
1820
+ this.clearInlineDecorationHighlights();
1821
+ return;
1822
+ }
1823
+ const t = CSS, i = window.Highlight;
1824
+ if (!t.highlights || !i) {
1825
+ this.clearInlineDecorationHighlights();
1826
+ return;
1827
+ }
1828
+ if (this.clearInlineDecorationHighlights(), e.length === 0)
1829
+ return;
1830
+ const n = this.textModel.getText(), s = [];
1831
+ let r = 0;
1832
+ for (const l of e) {
1833
+ if (r >= this.decorationHighlightLimit)
1834
+ break;
1835
+ const a = this.normalizeInlineDecoration(l, n);
1836
+ if (!a)
1837
+ continue;
1838
+ const h = this.view.createDomRangeFromRange(a.range);
1839
+ if (!h)
1840
+ continue;
1841
+ const c = this.buildInlineDecorationHighlightName(
1842
+ a.id
1843
+ );
1844
+ t.highlights.set(c, new i(h)), this.inlineDecorationHighlightNames.add(c), s.push(`
1845
+ ::highlight(${c}) {
1846
+ ${this.serializeInlineDecorationStyle(a.style)}
1847
+ }
1848
+ `), r += 1;
1849
+ }
1850
+ const o = this.ensureDecorationHighlightStyleNode();
1851
+ o.textContent = s.join(`
1852
+ `);
1853
+ }
1854
+ normalizeInlineDecoration(e, t) {
1855
+ const i = this.normalizeRange({
1856
+ start: this.clampPositionToText(e.range.start, t),
1857
+ end: this.clampPositionToText(e.range.end, t)
1858
+ });
1859
+ return i.start.line === i.end.line && i.start.column === i.end.column ? null : {
1860
+ ...e,
1861
+ range: i,
1862
+ style: e.style ? { ...e.style } : void 0
1863
+ };
1864
+ }
1865
+ clearInlineDecorationHighlights(e = !1) {
1866
+ try {
1867
+ const i = CSS;
1868
+ if (i.highlights)
1869
+ for (const n of this.inlineDecorationHighlightNames)
1870
+ i.highlights.delete(n);
1871
+ } catch (i) {
1872
+ }
1873
+ if (this.inlineDecorationHighlightNames.clear(), typeof document == "undefined")
1874
+ return;
1875
+ const t = document.getElementById(this.decorationHighlightStyleId);
1876
+ if (e) {
1877
+ t != null && t.parentNode && t.parentNode.removeChild(t);
1878
+ return;
1879
+ }
1880
+ t && (t.textContent = "");
1881
+ }
1882
+ ensureDecorationHighlightStyleNode() {
1883
+ let e = document.getElementById(
1884
+ this.decorationHighlightStyleId
1885
+ );
1886
+ return e || (e = document.createElement("style"), e.id = this.decorationHighlightStyleId, document.head.appendChild(e), e);
1887
+ }
1888
+ observeDecorationRelevantMutations() {
1889
+ typeof MutationObserver != "undefined" && (this.decorationMutationObserver = new MutationObserver(() => {
1890
+ this.decorationLayers.size !== 0 && this.scheduleDecorationRender();
1891
+ }), this.decorationMutationObserver.observe(this.view.getContentElement(), {
1892
+ childList: !0,
1893
+ subtree: !0,
1894
+ characterData: !0
1895
+ }));
1896
+ }
1897
+ detectCustomHighlightSupport() {
1898
+ try {
1899
+ if (typeof CSS == "undefined" || typeof window == "undefined")
1900
+ return !1;
1901
+ const e = CSS, t = window.Highlight;
1902
+ return !!e.highlights && !!t;
1903
+ } catch (e) {
1904
+ return !1;
1905
+ }
1906
+ }
1907
+ buildInlineDecorationHighlightName(e) {
1908
+ return `editora-decoration-${this.editorInstanceId}-${this.sanitizeHighlightIdentifier(e)}`;
1909
+ }
1910
+ sanitizeHighlightIdentifier(e) {
1911
+ return e.toLowerCase().replace(/[^a-z0-9_-]+/g, "-");
1912
+ }
1913
+ serializeInlineDecorationStyle(e) {
1914
+ const t = this.serializeStyleObject(e);
1915
+ return t || "background-color: var(--lce-inline-decoration-bg, rgba(86, 156, 214, 0.18)); border-radius: 2px;";
1916
+ }
1917
+ serializeStyleObject(e) {
1918
+ return e ? Object.entries(e).filter(([, t]) => typeof t == "string" && t.length > 0).map(([t, i]) => `${this.toKebabCase(t)}: ${i};`).join(" ") : "";
1919
+ }
1920
+ toKebabCase(e) {
1921
+ return e.replace(/[A-Z]/g, (t) => `-${t.toLowerCase()}`);
1922
+ }
1923
+ cloneDecoration(e) {
1924
+ return e.type === "inline" ? {
1925
+ ...e,
1926
+ range: {
1927
+ start: { ...e.range.start },
1928
+ end: { ...e.range.end }
1929
+ },
1930
+ style: e.style ? { ...e.style } : void 0
1931
+ } : {
1932
+ ...e,
1933
+ style: e.style ? { ...e.style } : void 0
1934
+ };
1935
+ }
1936
+ };
1937
+ C.CURSOR_SENTINEL = "";
1938
+ let V = C;
1939
+ class ie {
1940
+ constructor(e) {
1941
+ this.name = "keymap", this.editor = null, this.keymap = {}, this.isMac = navigator.platform.toUpperCase().indexOf("MAC") >= 0, this.keymap = e || this.getDefaultKeymap();
1942
+ }
1943
+ setup(e) {
1944
+ this.editor = e;
1945
+ }
1946
+ handleKeyDown(e) {
1947
+ if (!this.editor) return;
1948
+ const t = this.findMatchingBinding(e);
1949
+ if (t)
1950
+ return this.editor.executeCommand(t.command), e.preventDefault(), e.stopPropagation(), !1;
1951
+ }
1952
+ findMatchingBinding(e) {
1953
+ const { key: t, ctrlKey: i, altKey: n, shiftKey: s, metaKey: r } = e, o = String(t).toLowerCase(), l = this.keymap[o];
1954
+ if (!l) return null;
1955
+ for (const a of l) {
1956
+ const h = a.ctrlKey === void 0 || a.ctrlKey === i, c = a.altKey === void 0 || a.altKey === n, d = a.shiftKey === void 0 || a.shiftKey === s, f = a.metaKey === void 0 || a.metaKey === r;
1957
+ if (h && c && d && f)
1958
+ return a;
1959
+ }
1960
+ return null;
1961
+ }
1962
+ // Allow EditorCore to call this directly when checking extension.onKeyDown
1963
+ onKeyDown(e) {
1964
+ return this.handleKeyDown(e);
1965
+ }
1966
+ getDefaultKeymap() {
1967
+ const e = {};
1968
+ 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", { shiftKey: !0 }, "outdent"), this.addBinding(e, "tab", { shiftKey: !1, ctrlKey: !1, altKey: !1, metaKey: !1 }, "insertTab"), this.addBinding(e, "t", { ctrlKey: !this.isMac, metaKey: this.isMac, shiftKey: !0 }, "toggleTheme"), this.addBinding(e, "f", { altKey: !0, shiftKey: !0 }, "formatDocument"), e;
1969
+ }
1970
+ addBinding(e, t, i, n) {
1971
+ const s = t.toLowerCase();
1972
+ e[s] || (e[s] = []), e[s].push({
1973
+ key: s,
1974
+ command: n,
1975
+ ...i
1976
+ });
1977
+ }
1978
+ // Public API for customizing keymap
1979
+ setKeymap(e) {
1980
+ this.keymap = { ...e };
1981
+ }
1982
+ addKeyBinding(e) {
1983
+ const t = e.key.toLowerCase();
1984
+ this.keymap[t] || (this.keymap[t] = []), this.keymap[t] = this.keymap[t].filter((i) => i.command !== e.command), this.keymap[t].push({
1985
+ ...e,
1986
+ key: t
1987
+ });
1988
+ }
1989
+ removeKeyBinding(e, t) {
1990
+ const i = e.toLowerCase();
1991
+ t ? this.keymap[i] && (this.keymap[i] = this.keymap[i].filter((n) => n.command !== t), this.keymap[i].length === 0 && delete this.keymap[i]) : delete this.keymap[i];
1992
+ }
1993
+ getKeymap() {
1994
+ return { ...this.keymap };
1995
+ }
1996
+ getBindingsForCommand(e) {
1997
+ const t = [];
1998
+ for (const i in this.keymap)
1999
+ for (const n of this.keymap[i])
2000
+ n.command === e && t.push({ ...n });
2001
+ return t;
2002
+ }
2003
+ getPlatformInfo() {
2004
+ return {
2005
+ isMac: this.isMac,
2006
+ platform: navigator.platform
2007
+ };
2008
+ }
2009
+ destroy() {
2010
+ this.keymap = {}, this.editor = null;
2011
+ }
2012
+ }
2013
+ const A = class A {
2014
+ constructor() {
2015
+ this.name = "transaction", this.transactions = [];
2016
+ }
2017
+ setup(e) {
2018
+ e.on("change", (t) => {
2019
+ const i = {
2020
+ changes: t,
2021
+ selection: e.getSelection(),
2022
+ effects: [],
2023
+ annotations: []
2024
+ };
2025
+ this.transactions.push(i), this.transactions.length > A.MAX_TRANSACTIONS && this.transactions.splice(
2026
+ 0,
2027
+ this.transactions.length - A.MAX_TRANSACTIONS
2028
+ );
2029
+ });
2030
+ }
2031
+ getTransactions() {
2032
+ return this.transactions;
2033
+ }
2034
+ destroy() {
2035
+ this.transactions = [];
2036
+ }
2037
+ };
2038
+ A.MAX_TRANSACTIONS = 200;
2039
+ let U = A;
2040
+ class ne {
2041
+ constructor() {
2042
+ this.name = "line-numbers", this.editor = null, this.lineNumbersElement = null, this.isEnabled = !0;
2043
+ }
2044
+ setup(e) {
2045
+ this.editor = e, this.isEnabled = e.getConfig().lineNumbers !== !1, this.createLineNumbers(), e.registerCommand("toggleLineNumbers", () => {
2046
+ this.toggle();
2047
+ }), e.on("change", () => {
2048
+ this.updateLineNumbers();
2049
+ }), this.updateLineNumbers();
2050
+ }
2051
+ createLineNumbers() {
2052
+ if (!this.editor) return;
2053
+ const e = this.editor.getView(), t = e.getLineNumbersElement();
2054
+ t && (this.lineNumbersElement = t, e.setLineNumbersVisible(this.isEnabled));
2055
+ }
2056
+ updateLineNumbers() {
2057
+ if (!this.lineNumbersElement || !this.editor || !this.isEnabled) return;
2058
+ const e = this.editor.getValue().split(`
2059
+ `).length;
2060
+ this.editor.getView().updateLineNumbers(e);
2061
+ }
2062
+ toggle() {
2063
+ 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());
2064
+ }
2065
+ destroy() {
2066
+ this.lineNumbersElement = null, this.editor = null;
2067
+ }
2068
+ }
2069
+ class se {
2070
+ constructor() {
2071
+ this.name = "theme", this.editor = null, this.currentTheme = "dark";
2072
+ }
2073
+ setup(e) {
2074
+ this.editor = e, e.registerCommand("setTheme", (t) => {
2075
+ this.setTheme(t);
2076
+ }), e.registerCommand("toggleTheme", () => {
2077
+ this.toggleTheme();
2078
+ }), this.setTheme(this.currentTheme);
2079
+ }
2080
+ setTheme(e) {
2081
+ this.editor && (this.currentTheme = e, this.editor.setTheme(e));
2082
+ }
2083
+ toggleTheme() {
2084
+ const e = this.currentTheme === "dark" ? "light" : "dark";
2085
+ this.setTheme(e);
2086
+ }
2087
+ getCurrentTheme() {
2088
+ return this.currentTheme;
2089
+ }
2090
+ destroy() {
2091
+ this.editor = null;
2092
+ }
2093
+ }
2094
+ class re {
2095
+ constructor() {
2096
+ this.name = "read-only", this.editor = null, this.isReadOnly = !1;
2097
+ }
2098
+ setup(e) {
2099
+ this.editor = e, e.registerCommand("setReadOnly", (t) => {
2100
+ this.setReadOnly(t);
2101
+ }), e.registerCommand("toggleReadOnly", () => {
2102
+ this.toggleReadOnly();
2103
+ }), e.on("keydown", (t) => {
2104
+ if (t.ctrlKey && t.key === "r")
2105
+ return t.preventDefault(), this.toggleReadOnly(), !1;
2106
+ });
2107
+ }
2108
+ setReadOnly(e) {
2109
+ this.editor && (this.isReadOnly = e, this.editor.setReadOnly(e));
2110
+ }
2111
+ toggleReadOnly() {
2112
+ this.setReadOnly(!this.isReadOnly);
2113
+ }
2114
+ isCurrentlyReadOnly() {
2115
+ return this.isReadOnly;
2116
+ }
2117
+ destroy() {
2118
+ this.editor = null;
2119
+ }
2120
+ }
2121
+ let oe = 0;
2122
+ const x = class x {
2123
+ constructor(e = {}) {
2124
+ 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 = {
2125
+ caseSensitive: !1,
2126
+ wholeWord: !1,
2127
+ regex: !1
2128
+ }, this.trailingMarkerAttr = "data-lce-trailing-newline-marker", this.editorContainerSelector = '[data-lce-editor-container="true"]', this.highlightId = ++oe, 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 = {
2129
+ replaceAndFindNext: !0,
2130
+ ...e
2131
+ };
2132
+ }
2133
+ setup(e) {
2134
+ this.editor = e, this.hasCustomHighlightSupport = this.detectCustomHighlightSupport(), this.hasCustomHighlightSupport && this.ensureHighlightStyles(), e.registerCommand("find", () => {
2135
+ this.showSearch();
2136
+ }), e.registerCommand("findNext", () => {
2137
+ this.findNext();
2138
+ }), e.registerCommand("findPrev", () => {
2139
+ this.findPrev();
2140
+ }), e.registerCommand("replace", () => {
2141
+ this.showReplace();
2142
+ }), e.registerCommand("replaceAll", (t, i) => {
2143
+ this.replaceAll(t, i);
2144
+ }), this.editorChangeHandler = () => {
2145
+ !this.isVisible || !this.currentQuery || this.scheduleLiveRefresh(!0);
2146
+ }, e.on("change", this.editorChangeHandler);
2147
+ }
2148
+ showSearch() {
2149
+ 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));
2150
+ }
2151
+ showReplace() {
2152
+ this.showSearch(), this.replaceInputEl && (this.replaceInputEl.style.display = "block", this.replaceInputEl.focus()), this.updateModeHint(!0), this.currentQuery && this.performSearch(this.currentQuery, !1, !0);
2153
+ }
2154
+ hideSearch() {
2155
+ 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();
2156
+ }
2157
+ createSearchUI() {
2158
+ if (!this.editor) return;
2159
+ const e = this.editor.getView().getContentElement(), t = e.closest(
2160
+ this.editorContainerSelector
2161
+ ), i = t == null ? void 0 : t.parentElement, n = e.closest(".rte-source-editor-modal") || i || t || e.parentElement;
2162
+ if (!n) return;
2163
+ window.getComputedStyle(n).position === "static" && (n.style.position = "relative"), this.searchUI = document.createElement("div"), this.searchUI.className = x.css.root, this.searchUI.style.display = "none", this.searchUI.innerHTML = `
2164
+ <div class="${x.css.row}">
2165
+ <input type="text" class="${x.css.findInput} ${x.css.inputBase}" placeholder="Find..." />
2166
+ <button class="${x.css.prevButton} ${x.css.buttonBase}" type="button" aria-label="Previous match">↑</button>
2167
+ <button class="${x.css.nextButton} ${x.css.buttonBase}" type="button" aria-label="Next match">↓</button>
2168
+ <button class="${x.css.closeButton} ${x.css.buttonBase}" type="button" aria-label="Close search">×</button>
2169
+ </div>
2170
+ <div class="${x.css.options}">
2171
+ <label class="${x.css.optionLabel}" title="Case sensitive">
2172
+ <input type="checkbox" class="${x.css.optionInput} ${x.css.caseSensitive}" />
2173
+ <span>Aa</span>
2174
+ </label>
2175
+ <label class="${x.css.optionLabel}" title="Whole word">
2176
+ <input type="checkbox" class="${x.css.optionInput} ${x.css.wholeWord}" />
2177
+ <span>Whole</span>
2178
+ </label>
2179
+ <label class="${x.css.optionLabel}" title="Regular expression">
2180
+ <input type="checkbox" class="${x.css.optionInput} ${x.css.regex}" />
2181
+ <span>.*</span>
2182
+ </label>
2183
+ </div>
2184
+ <div class="${x.css.meta}">
2185
+ <div class="${x.css.status} ${x.css.statusLayout}"></div>
2186
+ <div class="${x.css.mode} ${x.css.modeLayout}" aria-live="polite"></div>
2187
+ </div>
2188
+ <input type="text" class="${x.css.replaceInput} ${x.css.inputBase} ${x.css.replaceInputLayout}" placeholder="Replace with..." />
2189
+ `;
2190
+ const s = this.searchUI.querySelector(
2191
+ `.${x.css.findInput}`
2192
+ ), r = this.searchUI.querySelector(
2193
+ `.${x.css.replaceInput}`
2194
+ ), o = this.searchUI.querySelector(
2195
+ `.${x.css.prevButton}`
2196
+ ), l = this.searchUI.querySelector(
2197
+ `.${x.css.nextButton}`
2198
+ ), a = this.searchUI.querySelector(
2199
+ `.${x.css.closeButton}`
2200
+ ), h = this.searchUI.querySelector(
2201
+ `.${x.css.status}`
2202
+ ), c = this.searchUI.querySelector(
2203
+ `.${x.css.mode}`
2204
+ ), d = this.searchUI.querySelector(
2205
+ `.${x.css.caseSensitive}`
2206
+ ), f = this.searchUI.querySelector(
2207
+ `.${x.css.wholeWord}`
2208
+ ), u = this.searchUI.querySelector(
2209
+ `.${x.css.regex}`
2210
+ );
2211
+ this.findInput = s, this.replaceInputEl = r, this.statusDiv = h, this.modeDiv = c, this.caseSensitiveInput = d, this.wholeWordInput = f, this.regexInput = u, d.checked = !!this.searchOptions.caseSensitive, f.checked = !!this.searchOptions.wholeWord, u.checked = !!this.searchOptions.regex, s.addEventListener("input", () => {
2212
+ this.searchDebounceTimer && clearTimeout(this.searchDebounceTimer);
2213
+ const p = s.value;
2214
+ this.searchDebounceTimer = setTimeout(() => {
2215
+ this.performSearch(p, !1, !1);
2216
+ }, 120);
2217
+ });
2218
+ const g = () => {
2219
+ this.searchOptions.caseSensitive = d.checked, this.searchOptions.wholeWord = f.checked, this.searchOptions.regex = u.checked;
2220
+ const p = s.value;
2221
+ p.trim() ? this.performSearch(p, !1, !1) : this.performSearch("", !1, !1);
2222
+ };
2223
+ d.addEventListener("change", g), f.addEventListener("change", g), u.addEventListener("change", g), s.addEventListener("keydown", (p) => {
2224
+ p.key === "Enter" ? (p.preventDefault(), p.shiftKey ? this.findPrev() : this.findNext()) : p.key === "Escape" && (p.preventDefault(), this.hideSearch());
2225
+ }), r.addEventListener("keydown", (p) => {
2226
+ p.key === "Enter" ? (p.preventDefault(), p.shiftKey ? this.replaceAll(s.value, r.value) : this.replaceCurrent(s.value, r.value)) : p.key === "Escape" && (p.preventDefault(), this.hideSearch());
2227
+ }), o.addEventListener("click", () => this.findPrev()), l.addEventListener("click", () => this.findNext()), a.addEventListener("click", () => this.hideSearch()), n.appendChild(this.searchUI);
2228
+ }
2229
+ updateModeHint(e) {
2230
+ this.modeDiv && (this.modeDiv.textContent = e ? `Replace: move next ${this.config.replaceAndFindNext ? "ON" : "OFF"}` : "Find mode");
2231
+ }
2232
+ performSearch(e, t, i) {
2233
+ if (!this.editor || !e.trim()) {
2234
+ this.currentQuery = "", this.currentResults = [], this.currentIndex = -1, this.clearHighlights(), this.updateStatus("");
2235
+ return;
2236
+ }
2237
+ if (this.searchOptions.regex && !this.isValidRegex(e)) {
2238
+ this.currentQuery = e, this.currentResults = [], this.currentIndex = -1, this.clearHighlights(), this.updateStatus("Invalid regular expression");
2239
+ return;
2240
+ }
2241
+ this.currentQuery = e;
2242
+ const n = this.currentIndex, s = this.editor.search(e, this.searchOptions);
2243
+ if (this.currentResults = s, s.length === 0) {
2244
+ this.currentIndex = -1, this.clearHighlights(), this.updateStatus("No matches");
2245
+ return;
2246
+ }
2247
+ t && n >= 0 ? this.currentIndex = Math.min(n, s.length - 1) : this.currentIndex = 0, this.updateHighlights(i);
2248
+ }
2249
+ findNext() {
2250
+ if (this.currentResults.length === 0) {
2251
+ this.currentQuery && this.performSearch(this.currentQuery, !0, !0);
2252
+ return;
2253
+ }
2254
+ this.currentIndex = (this.currentIndex + 1) % this.currentResults.length, this.updateHighlights(!0);
2255
+ }
2256
+ findPrev() {
2257
+ if (this.currentResults.length === 0) {
2258
+ this.currentQuery && this.performSearch(this.currentQuery, !0, !0);
2259
+ return;
2260
+ }
2261
+ this.currentIndex = this.currentIndex <= 0 ? this.currentResults.length - 1 : this.currentIndex - 1, this.updateHighlights(!0);
2262
+ }
2263
+ replaceCurrent(e, t) {
2264
+ 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;
2265
+ const i = this.currentResults[this.currentIndex];
2266
+ if (!i) return;
2267
+ const n = this.computeReplacementRange(i.range.start, t);
2268
+ if (this.editor.replace(i.range, t), this.config.replaceAndFindNext) {
2269
+ this.currentQuery = e;
2270
+ const s = this.editor.search(e, this.searchOptions);
2271
+ if (this.currentResults = s, s.length === 0) {
2272
+ this.currentIndex = -1, this.clearHighlights(), this.updateStatus("Replaced current occurrence"), this.restoreReplaceInputFocus();
2273
+ return;
2274
+ }
2275
+ this.currentIndex = this.findNextResultIndexAfter(n.end, s), this.updateHighlights(!0);
2276
+ } else
2277
+ this.scrollLogicalRangeIntoView(n, !0), this.performSearch(e, !0, !1);
2278
+ this.currentResults.length > 0 || this.showTransientStatus("Replaced current occurrence"), this.restoreReplaceInputFocus(), this.revealActiveResultAfterFocusRestore();
2279
+ }
2280
+ replaceAll(e, t) {
2281
+ if (!this.editor || !e.trim()) return;
2282
+ const i = this.editor.replaceAll(e, t, this.searchOptions);
2283
+ this.performSearch(e, !1, !1), this.showTransientStatus(`Replaced ${i} occurrence${i === 1 ? "" : "s"}`), this.restoreReplaceInputFocus(), this.revealActiveResultAfterFocusRestore();
2284
+ }
2285
+ updateHighlights(e) {
2286
+ if (this.clearHighlights(), this.currentResults.length === 0 || this.currentIndex === -1 || !this.editor)
2287
+ return;
2288
+ this.applyCustomHighlights();
2289
+ const t = this.currentResults[this.currentIndex];
2290
+ t && ((e || !this.hasCustomHighlightSupport) && this.navigateToResult(t, !this.hasCustomHighlightSupport), this.updateStatus(
2291
+ `${this.currentResults.length} matches (showing ${this.currentIndex + 1}/${this.currentResults.length})`
2292
+ ));
2293
+ }
2294
+ navigateToResult(e, t) {
2295
+ if (!this.editor) return;
2296
+ const i = document.activeElement, n = !!i && (i === this.findInput || i === this.replaceInputEl);
2297
+ t ? (this.editor.setSelection(e.range), this.centerCurrentSelectionInView()) : this.scrollResultIntoView(e);
2298
+ const s = this.editor.getView();
2299
+ t && typeof s.ensureCaretVisible == "function" && s.ensureCaretVisible(), t && n && i && requestAnimationFrame(() => {
2300
+ this.focusWithoutScrolling(i);
2301
+ });
2302
+ }
2303
+ clearHighlights() {
2304
+ var e, t;
2305
+ if (this.hasCustomHighlightSupport)
2306
+ try {
2307
+ const i = CSS;
2308
+ (e = i.highlights) == null || e.delete(this.highlightMatchName), (t = i.highlights) == null || t.delete(this.highlightActiveName);
2309
+ } catch (i) {
2310
+ }
2311
+ }
2312
+ scrollResultIntoView(e) {
2313
+ this.scrollLogicalRangeIntoView(e.range, !0);
2314
+ }
2315
+ scrollLogicalRangeIntoView(e, t) {
2316
+ if (!this.editor) return;
2317
+ const i = this.editor.getView().getContentElement(), n = this.editor.getValue(), { lineStarts: s, lines: r } = this.buildLineStarts(n), o = this.buildTextNodeIndex(i);
2318
+ if (o.length === 0) return;
2319
+ const l = this.toDomRange(e, s, r, o);
2320
+ if (!l) return;
2321
+ const a = l.startContainer.nodeType === Node.TEXT_NODE ? l.startContainer.parentElement : l.startContainer, h = this.resolveScrollContainer(i);
2322
+ if (h) {
2323
+ const c = l.getClientRects()[0] || l.getBoundingClientRect(), d = h.getBoundingClientRect(), u = h.scrollTop + (c.top - d.top) - d.height / 2 + c.height / 2, g = 18;
2324
+ let p = t ? u : h.scrollTop, m = h.scrollLeft;
2325
+ const y = h.scrollLeft + (c.left - d.left), v = y + c.width;
2326
+ c.right > d.right - g ? m = v - d.width + g : c.left < d.left + g && (m = Math.max(0, y - g));
2327
+ const S = Math.max(0, h.scrollHeight - h.clientHeight), w = Math.max(0, h.scrollWidth - h.clientWidth);
2328
+ if (p = Math.min(S, Math.max(0, p)), m = Math.min(w, Math.max(0, m)), S === 0 && w === 0) {
2329
+ a == null || a.scrollIntoView({
2330
+ block: t ? "center" : "nearest",
2331
+ inline: "nearest",
2332
+ behavior: "smooth"
2333
+ });
2334
+ return;
2335
+ }
2336
+ (p !== h.scrollTop || m !== h.scrollLeft) && h.scrollTo({
2337
+ top: p,
2338
+ left: m,
2339
+ behavior: "smooth"
2340
+ });
2341
+ return;
2342
+ }
2343
+ a == null || a.scrollIntoView({
2344
+ block: t ? "center" : "nearest",
2345
+ inline: "nearest",
2346
+ behavior: "smooth"
2347
+ });
2348
+ }
2349
+ restoreReplaceInputFocus() {
2350
+ const e = this.replaceInputEl;
2351
+ !e || e.style.display === "none" || requestAnimationFrame(() => {
2352
+ this.focusWithoutScrolling(e);
2353
+ const t = e.value.length;
2354
+ try {
2355
+ e.setSelectionRange(t, t);
2356
+ } catch (i) {
2357
+ }
2358
+ });
2359
+ }
2360
+ centerCurrentSelectionInView() {
2361
+ if (!this.editor) return;
2362
+ const e = this.editor.getView().getContentElement(), t = this.resolveScrollContainer(e);
2363
+ if (!t) return;
2364
+ const i = window.getSelection();
2365
+ if (!i || i.rangeCount === 0) return;
2366
+ const n = i.getRangeAt(0).cloneRange(), s = n.getClientRects()[0] || n.getBoundingClientRect();
2367
+ if (!s) return;
2368
+ const r = t.getBoundingClientRect(), l = t.scrollTop + (s.top - r.top) - r.height / 2 + s.height / 2, a = Math.max(0, t.scrollHeight - t.clientHeight), h = Math.min(a, Math.max(0, l));
2369
+ h !== t.scrollTop && t.scrollTo({
2370
+ top: h,
2371
+ behavior: "smooth"
2372
+ });
2373
+ }
2374
+ computeReplacementRange(e, t) {
2375
+ const i = t.replace(/\r\n?/g, `
2376
+ `), n = i.split(`
2377
+ `);
2378
+ let s;
2379
+ return n.length <= 1 ? (s = {
2380
+ start: e,
2381
+ end: {
2382
+ line: e.line,
2383
+ column: e.column + i.length
2384
+ }
2385
+ }, this.clampRangeToDocument(s)) : (s = {
2386
+ start: e,
2387
+ end: {
2388
+ line: e.line + n.length - 1,
2389
+ column: n[n.length - 1].length
2390
+ }
2391
+ }, this.clampRangeToDocument(s));
2392
+ }
2393
+ findNextResultIndexAfter(e, t) {
2394
+ for (let i = 0; i < t.length; i++)
2395
+ if (this.comparePositions(t[i].range.start, e) >= 0)
2396
+ return i;
2397
+ return 0;
2398
+ }
2399
+ comparePositions(e, t) {
2400
+ return e.line !== t.line ? e.line - t.line : e.column - t.column;
2401
+ }
2402
+ clampRangeToDocument(e) {
2403
+ var a, h;
2404
+ const t = this.editor;
2405
+ if (!t) return e;
2406
+ const i = t.getValue().split(`
2407
+ `), n = Math.max(0, i.length - 1), s = Math.max(0, Math.min(e.start.line, n)), r = Math.max(0, Math.min(e.end.line, n)), o = Math.max(
2408
+ 0,
2409
+ Math.min(e.start.column, ((a = i[s]) == null ? void 0 : a.length) || 0)
2410
+ ), l = Math.max(
2411
+ 0,
2412
+ Math.min(e.end.column, ((h = i[r]) == null ? void 0 : h.length) || 0)
2413
+ );
2414
+ return {
2415
+ start: { line: s, column: o },
2416
+ end: { line: r, column: l }
2417
+ };
2418
+ }
2419
+ focusWithoutScrolling(e) {
2420
+ try {
2421
+ e.focus({
2422
+ preventScroll: !0
2423
+ });
2424
+ } catch (t) {
2425
+ const i = [];
2426
+ let n = e.parentElement;
2427
+ for (; n; )
2428
+ this.canScroll(n) && i.push({
2429
+ el: n,
2430
+ top: n.scrollTop,
2431
+ left: n.scrollLeft
2432
+ }), n = n.parentElement;
2433
+ const s = window.scrollX, r = window.scrollY;
2434
+ e.focus();
2435
+ for (let o = 0; o < i.length; o++) {
2436
+ const l = i[o];
2437
+ l.el.scrollTop = l.top, l.el.scrollLeft = l.left;
2438
+ }
2439
+ window.scrollTo(s, r);
2440
+ }
2441
+ }
2442
+ findScrollContainer(e) {
2443
+ let t = e;
2444
+ for (; t; ) {
2445
+ const n = window.getComputedStyle(t).overflowY;
2446
+ if ((n === "auto" || n === "scroll") && t.scrollHeight > t.clientHeight)
2447
+ return t;
2448
+ t = t.parentElement;
2449
+ }
2450
+ return null;
2451
+ }
2452
+ resolveScrollContainer(e) {
2453
+ var n, s;
2454
+ const t = (n = this.editor) == null ? void 0 : n.getView(), i = ((s = t == null ? void 0 : t.getScrollElement) == null ? void 0 : s.call(t)) || null;
2455
+ return i && this.canScroll(i) ? i : this.findScrollContainer(e);
2456
+ }
2457
+ canScroll(e) {
2458
+ return e.scrollHeight > e.clientHeight || e.scrollWidth > e.clientWidth;
2459
+ }
2460
+ revealActiveResultAfterFocusRestore() {
2461
+ !this.currentResults.length || this.currentIndex < 0 || requestAnimationFrame(() => {
2462
+ const e = this.currentResults[this.currentIndex];
2463
+ e && this.scrollResultIntoView(e);
2464
+ });
2465
+ }
2466
+ applyCustomHighlights() {
2467
+ if (!this.editor || !this.hasCustomHighlightSupport || this.currentResults.length === 0)
2468
+ return;
2469
+ const e = this.editor.getView().getContentElement(), t = this.editor.getValue(), { lineStarts: i, lines: n } = this.buildLineStarts(t), s = this.buildTextNodeIndex(e);
2470
+ if (s.length === 0) return;
2471
+ const r = this.buildVisibleDocumentText(s), o = [];
2472
+ let l = null;
2473
+ const a = Math.min(this.currentResults.length, this.maxCustomHighlightRanges);
2474
+ for (let h = 0; h < a; h++) {
2475
+ const c = this.currentResults[h], d = this.searchOptions.regex ? c.match || this.currentQuery : this.currentQuery || c.match, f = this.toDomRange(
2476
+ c.range,
2477
+ i,
2478
+ n,
2479
+ s,
2480
+ r,
2481
+ d
2482
+ );
2483
+ f && (o.push(f), h === this.currentIndex && (l = f));
2484
+ }
2485
+ if (o.length !== 0)
2486
+ try {
2487
+ const h = CSS, c = window.Highlight;
2488
+ if (!h.highlights || !c) return;
2489
+ h.highlights.set(this.highlightMatchName, new c(...o)), l && h.highlights.set(this.highlightActiveName, new c(l));
2490
+ } catch (h) {
2491
+ }
2492
+ }
2493
+ buildLineStarts(e) {
2494
+ const t = e.split(`
2495
+ `), i = new Array(t.length);
2496
+ let n = 0;
2497
+ for (let s = 0; s < t.length; s++)
2498
+ i[s] = n, n += t[s].length + 1;
2499
+ return { lineStarts: i, lines: t };
2500
+ }
2501
+ positionToOffset(e, t, i) {
2502
+ var r;
2503
+ const n = Math.max(0, Math.min(e.line, i.length - 1)), s = Math.max(0, Math.min(e.column, ((r = i[n]) == null ? void 0 : r.length) || 0));
2504
+ return t[n] + s;
2505
+ }
2506
+ buildTextNodeIndex(e) {
2507
+ const t = document.createTreeWalker(e, NodeFilter.SHOW_TEXT, null), i = [];
2508
+ let n = 0, s;
2509
+ for (; s = t.nextNode(); ) {
2510
+ const r = s, o = r.parentElement;
2511
+ if (o != null && o.hasAttribute(this.trailingMarkerAttr))
2512
+ continue;
2513
+ const l = r.textContent || "", a = this.buildVisibleToDomMap(l), h = Math.max(0, a.length - 1);
2514
+ h === 0 && l.length === 0 || (i.push({
2515
+ node: r,
2516
+ start: n,
2517
+ end: n + h,
2518
+ visibleToDom: a
2519
+ }), n += h);
2520
+ }
2521
+ return i;
2522
+ }
2523
+ resolveDomPoint(e, t) {
2524
+ var s, r, o, l, a, h;
2525
+ const i = Math.max(0, e);
2526
+ for (let c = 0; c < t.length; c++) {
2527
+ const d = t[c];
2528
+ if (i <= d.end) {
2529
+ const f = Math.max(0, i - d.start), u = (o = (r = d.visibleToDom[f]) != null ? r : (s = d.node.textContent) == null ? void 0 : s.length) != null ? o : 0;
2530
+ return {
2531
+ node: d.node,
2532
+ offset: u
2533
+ };
2534
+ }
2535
+ }
2536
+ const n = t[t.length - 1];
2537
+ return n ? {
2538
+ node: n.node,
2539
+ offset: (h = (a = n.visibleToDom[n.visibleToDom.length - 1]) != null ? a : (l = n.node.textContent) == null ? void 0 : l.length) != null ? h : 0
2540
+ } : null;
2541
+ }
2542
+ toDomRange(e, t, i, n, s, r) {
2543
+ const o = this.positionToOffset(e.start, t, i), l = this.positionToOffset(e.end, t, i);
2544
+ let a = Math.min(o, l), h = Math.max(o, l);
2545
+ if (s && r) {
2546
+ const u = r, g = s.slice(a, h);
2547
+ if (g.length === u.length && g.toLowerCase() !== u.toLowerCase()) {
2548
+ const p = this.findNearestMatchOffset(
2549
+ s,
2550
+ u,
2551
+ a
2552
+ );
2553
+ p !== -1 && (a = p, h = p + u.length);
2554
+ }
2555
+ }
2556
+ const c = this.resolveDomPoint(a, n), d = this.resolveDomPoint(h, n);
2557
+ if (!c || !d) return null;
2558
+ const f = document.createRange();
2559
+ try {
2560
+ return f.setStart(c.node, c.offset), f.setEnd(d.node, d.offset), f;
2561
+ } catch (u) {
2562
+ return null;
2563
+ }
2564
+ }
2565
+ buildVisibleDocumentText(e) {
2566
+ let t = "";
2567
+ for (let i = 0; i < e.length; i++) {
2568
+ const n = e[i].node.textContent || "";
2569
+ for (let s = 0; s < n.length; s++) {
2570
+ const r = n[s];
2571
+ this.virtualMarkerRegex.test(r) || (t += r);
2572
+ }
2573
+ }
2574
+ return t;
2575
+ }
2576
+ findNearestMatchOffset(e, t, i) {
2577
+ const n = t.toLowerCase();
2578
+ let s = e.toLowerCase().indexOf(n);
2579
+ if (s === -1) return -1;
2580
+ let r = s, o = Math.abs(s - i);
2581
+ for (; s !== -1; ) {
2582
+ const l = Math.abs(s - i);
2583
+ if (l < o && (o = l, r = s), l === 0) return s;
2584
+ s = e.toLowerCase().indexOf(n, s + 1);
2585
+ }
2586
+ return r;
2587
+ }
2588
+ scheduleLiveRefresh(e) {
2589
+ this.liveRefreshTimer && clearTimeout(this.liveRefreshTimer);
2590
+ const t = this.currentQuery;
2591
+ this.liveRefreshTimer = setTimeout(() => {
2592
+ !this.isVisible || !t || this.performSearch(t, e, !1);
2593
+ }, 90);
2594
+ }
2595
+ updateStatus(e, t = !1) {
2596
+ if (this.statusDiv) {
2597
+ if (!t && Date.now() < this.statusFreezeUntil)
2598
+ return;
2599
+ this.statusDiv.textContent = e;
2600
+ }
2601
+ }
2602
+ showTransientStatus(e, t = 900) {
2603
+ this.statusFreezeUntil = Date.now() + t, this.updateStatus(e, !0), this.statusResetTimer && clearTimeout(this.statusResetTimer), this.statusResetTimer = setTimeout(() => {
2604
+ this.statusFreezeUntil = 0, this.syncMatchStatus();
2605
+ }, t);
2606
+ }
2607
+ syncMatchStatus() {
2608
+ if (!this.currentQuery) {
2609
+ this.updateStatus("", !0);
2610
+ return;
2611
+ }
2612
+ if (this.currentResults.length === 0 || this.currentIndex < 0) {
2613
+ this.updateStatus("No matches", !0);
2614
+ return;
2615
+ }
2616
+ this.updateStatus(
2617
+ `${this.currentResults.length} matches (showing ${this.currentIndex + 1}/${this.currentResults.length})`,
2618
+ !0
2619
+ );
2620
+ }
2621
+ isValidRegex(e) {
2622
+ try {
2623
+ const t = this.searchOptions.caseSensitive ? "g" : "gi";
2624
+ return new RegExp(e, t), !0;
2625
+ } catch (t) {
2626
+ return !1;
2627
+ }
2628
+ }
2629
+ captureSelectionState() {
2630
+ this.editor && (this.savedSelection = this.editor.getSelection(), this.savedCursor = this.editor.getCursor().position);
2631
+ }
2632
+ restoreSelectionState() {
2633
+ this.editor && (this.savedSelection ? this.editor.setSelection(this.savedSelection) : this.savedCursor && this.editor.setCursor(this.savedCursor), this.savedSelection = void 0, this.savedCursor = null);
2634
+ }
2635
+ detectCustomHighlightSupport() {
2636
+ try {
2637
+ const e = CSS, t = window.Highlight;
2638
+ return !!e.highlights && !!t;
2639
+ } catch (e) {
2640
+ return !1;
2641
+ }
2642
+ }
2643
+ buildVisibleToDomMap(e) {
2644
+ const t = [0];
2645
+ let i = 0;
2646
+ for (let n = 0; n < e.length; n++) {
2647
+ const s = e[n];
2648
+ this.virtualMarkerRegex.test(s) || (i += 1, t[i] = n + 1);
2649
+ }
2650
+ return t;
2651
+ }
2652
+ ensureHighlightStyles() {
2653
+ if (document.getElementById(this.highlightStyleId)) return;
2654
+ const e = document.createElement("style");
2655
+ e.id = this.highlightStyleId, e.textContent = `
2656
+ ::highlight(${this.highlightMatchName}) {
2657
+ background: var(--lce-search-match-bg, rgba(255, 214, 10, 0.34));
2658
+ border-radius: 2px;
2659
+ }
2660
+ ::highlight(${this.highlightActiveName}) {
2661
+ background: var(--lce-search-active-bg, rgba(255, 154, 0, 0.45));
2662
+ border-radius: 2px;
2663
+ }
2664
+ `, document.head.appendChild(e);
2665
+ }
2666
+ destroy() {
2667
+ 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;
2668
+ const e = document.getElementById(this.highlightStyleId);
2669
+ e != null && e.parentNode && e.parentNode.removeChild(e), this.editor = null;
2670
+ }
2671
+ };
2672
+ x.css = {
2673
+ root: "lce-search-ui",
2674
+ row: "lce-search-row",
2675
+ options: "lce-search-options",
2676
+ optionLabel: "lce-search-option",
2677
+ optionInput: "lce-search-option-input",
2678
+ caseSensitive: "search-case-sensitive",
2679
+ wholeWord: "search-whole-word",
2680
+ regex: "search-regex",
2681
+ meta: "lce-search-meta",
2682
+ findInput: "search-find-input",
2683
+ replaceInput: "search-replace-input",
2684
+ inputBase: "lce-search-input",
2685
+ replaceInputLayout: "lce-search-replace",
2686
+ prevButton: "search-prev",
2687
+ nextButton: "search-next",
2688
+ closeButton: "search-close",
2689
+ buttonBase: "lce-search-btn",
2690
+ status: "search-status",
2691
+ statusLayout: "lce-search-status",
2692
+ mode: "search-mode",
2693
+ modeLayout: "lce-search-mode"
2694
+ };
2695
+ let W = x, le = 0;
2696
+ class ae {
2697
+ constructor() {
2698
+ this.name = "bracket-matching", this.editor = null, this.bracketPairs = {
2699
+ "(": ")",
2700
+ "[": "]",
2701
+ "{": "}",
2702
+ "<": ">"
2703
+ }, this.reverseBracketPairs = {
2704
+ ")": "(",
2705
+ "]": "[",
2706
+ "}": "{",
2707
+ ">": "<"
2708
+ }, this.highlightId = ++le, 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;
2709
+ }
2710
+ setup(e) {
2711
+ this.editor = e, this.hasCustomHighlightSupport = this.detectCustomHighlightSupport(), this.hasCustomHighlightSupport && (this.ensureHighlightStyles(), this.observeContentMutations()), this.cursorHandler = () => {
2712
+ this.scheduleBracketUpdate();
2713
+ }, this.changeHandler = () => {
2714
+ this.scheduleBracketUpdate();
2715
+ }, e.on("cursor", this.cursorHandler), e.on("change", this.changeHandler), this.scheduleBracketUpdate();
2716
+ }
2717
+ scheduleBracketUpdate() {
2718
+ this.updateRequestVersion += 1;
2719
+ const e = this.updateRequestVersion;
2720
+ this.pendingUpdateRaf !== null && typeof cancelAnimationFrame == "function" && (cancelAnimationFrame(this.pendingUpdateRaf), this.pendingUpdateRaf = null);
2721
+ const t = () => {
2722
+ e === this.updateRequestVersion && (this.pendingUpdateRaf = null, this.updateBracketMatching());
2723
+ };
2724
+ if (typeof requestAnimationFrame == "function") {
2725
+ this.pendingUpdateRaf = requestAnimationFrame(() => {
2726
+ this.pendingUpdateRaf = requestAnimationFrame(t);
2727
+ });
2728
+ return;
2729
+ }
2730
+ t();
2731
+ }
2732
+ updateBracketMatching() {
2733
+ if (!this.editor) return;
2734
+ const e = this.editor.getCursor(), t = this.editor.getValue();
2735
+ this.clearBracketHighlighting();
2736
+ const i = this.getBracketNearPosition(t, e.position);
2737
+ if (!i) return;
2738
+ const n = this.findMatchingBracket(t, i);
2739
+ n && (this.currentMatch = n, this.highlightBrackets(n));
2740
+ }
2741
+ getBracketNearPosition(e, t) {
2742
+ const i = e.split(`
2743
+ `);
2744
+ if (t.line < 0 || t.line >= i.length) return null;
2745
+ const n = [{ line: t.line, column: t.column }];
2746
+ t.column > 0 && n.push({ line: t.line, column: t.column - 1 });
2747
+ for (const s of n) {
2748
+ const r = this.getBracketAtPosition(i, s);
2749
+ if (r)
2750
+ return r;
2751
+ }
2752
+ return null;
2753
+ }
2754
+ getBracketAtPosition(e, t) {
2755
+ if (t.line < 0 || t.line >= e.length) return null;
2756
+ const i = e[t.line];
2757
+ if (t.column < 0 || t.column >= i.length) return null;
2758
+ const n = i[t.column];
2759
+ return this.bracketPairs[n] || this.reverseBracketPairs[n] ? { char: n, position: t } : null;
2760
+ }
2761
+ findMatchingBracket(e, t) {
2762
+ const i = e.split(`
2763
+ `), n = t.position.line, s = t.position.column, r = t.char;
2764
+ return this.bracketPairs[r] ? this.findClosingBracket(i, n, s, r) : this.reverseBracketPairs[r] ? this.findOpeningBracket(i, n, s, r) : null;
2765
+ }
2766
+ findClosingBracket(e, t, i, n) {
2767
+ const s = this.bracketPairs[n];
2768
+ let r = 0;
2769
+ for (let o = t; o < e.length; o++) {
2770
+ const l = e[o], a = o === t ? i : 0;
2771
+ for (let h = a; h < l.length; h++) {
2772
+ const c = l[h];
2773
+ if (c === n)
2774
+ r++;
2775
+ else if (c === s && (r--, r === 0))
2776
+ return {
2777
+ open: { start: { line: t, column: i }, end: { line: t, column: i + 1 } },
2778
+ close: { start: { line: o, column: h }, end: { line: o, column: h + 1 } },
2779
+ type: n
2780
+ };
2781
+ }
2782
+ }
2783
+ return null;
2784
+ }
2785
+ findOpeningBracket(e, t, i, n) {
2786
+ const s = this.reverseBracketPairs[n];
2787
+ let r = 0;
2788
+ for (let o = t; o >= 0; o--) {
2789
+ const l = e[o], a = o === t ? i : l.length - 1;
2790
+ for (let h = a; h >= 0; h--) {
2791
+ const c = l[h];
2792
+ if (c === n)
2793
+ r++;
2794
+ else if (c === s && (r--, r === 0))
2795
+ return {
2796
+ open: { start: { line: o, column: h }, end: { line: o, column: h + 1 } },
2797
+ close: { start: { line: t, column: i }, end: { line: t, column: i + 1 } },
2798
+ type: s
2799
+ };
2800
+ }
2801
+ }
2802
+ return null;
2803
+ }
2804
+ highlightBrackets(e) {
2805
+ if (!this.editor || !this.hasCustomHighlightSupport) return;
2806
+ const t = this.editor.getView(), i = t.createDomRangeFromRange(e.open), n = t.createDomRangeFromRange(e.close);
2807
+ if (!(!i || !n))
2808
+ try {
2809
+ const s = CSS, r = window.Highlight;
2810
+ if (!s.highlights || !r) return;
2811
+ s.highlights.set(this.highlightName, new r(i, n));
2812
+ } catch (s) {
2813
+ }
2814
+ }
2815
+ clearBracketHighlighting() {
2816
+ var e;
2817
+ if (this.currentMatch = null, !!this.hasCustomHighlightSupport)
2818
+ try {
2819
+ (e = CSS.highlights) == null || e.delete(this.highlightName);
2820
+ } catch (t) {
2821
+ }
2822
+ }
2823
+ observeContentMutations() {
2824
+ if (!this.editor || typeof MutationObserver == "undefined") return;
2825
+ const e = this.editor.getView().getContentElement();
2826
+ this.observer = new MutationObserver(() => {
2827
+ this.clearBracketHighlighting(), this.scheduleBracketUpdate();
2828
+ }), this.observer.observe(e, {
2829
+ childList: !0,
2830
+ subtree: !0,
2831
+ characterData: !0
2832
+ });
2833
+ }
2834
+ detectCustomHighlightSupport() {
2835
+ try {
2836
+ if (typeof CSS == "undefined" || typeof window == "undefined")
2837
+ return !1;
2838
+ const e = CSS, t = window.Highlight;
2839
+ return !!e.highlights && !!t;
2840
+ } catch (e) {
2841
+ return !1;
2842
+ }
2843
+ }
2844
+ ensureHighlightStyles() {
2845
+ if (typeof document == "undefined" || document.getElementById(this.highlightStyleId)) return;
2846
+ const e = document.createElement("style");
2847
+ e.id = this.highlightStyleId, e.textContent = `
2848
+ ::highlight(${this.highlightName}) {
2849
+ background-color: var(--lce-bracket-match-bg, rgba(86, 156, 214, 0.4));
2850
+ text-decoration: underline solid var(--lce-bracket-match-border, rgba(156, 220, 254, 0.95)) 2px;
2851
+ }
2852
+ `, document.head.appendChild(e);
2853
+ }
2854
+ getCurrentMatch() {
2855
+ return this.currentMatch;
2856
+ }
2857
+ destroy() {
2858
+ var e;
2859
+ if (this.pendingUpdateRaf !== null && typeof cancelAnimationFrame == "function" && (cancelAnimationFrame(this.pendingUpdateRaf), this.pendingUpdateRaf = null), this.clearBracketHighlighting(), (e = this.observer) == null || e.disconnect(), this.observer = null, this.editor && this.cursorHandler && this.editor.off("cursor", this.cursorHandler), this.editor && this.changeHandler && this.editor.off("change", this.changeHandler), typeof document != "undefined") {
2860
+ const t = document.getElementById(this.highlightStyleId);
2861
+ t != null && t.parentNode && t.parentNode.removeChild(t);
2862
+ }
2863
+ this.cursorHandler = null, this.changeHandler = null, this.editor = null;
2864
+ }
2865
+ }
2866
+ class he {
2867
+ constructor() {
2868
+ this.name = "code-folding", this.lineHeight = 21, this.voidMarkupTags = /* @__PURE__ */ new Set([
2869
+ "area",
2870
+ "base",
2871
+ "br",
2872
+ "col",
2873
+ "embed",
2874
+ "hr",
2875
+ "img",
2876
+ "input",
2877
+ "link",
2878
+ "meta",
2879
+ "param",
2880
+ "source",
2881
+ "track",
2882
+ "wbr"
2883
+ ]), this.nonFoldableInlineMarkupTags = /* @__PURE__ */ new Set([
2884
+ "a",
2885
+ "abbr",
2886
+ "b",
2887
+ "bdi",
2888
+ "bdo",
2889
+ "button",
2890
+ "cite",
2891
+ "code",
2892
+ "data",
2893
+ "del",
2894
+ "dfn",
2895
+ "em",
2896
+ "i",
2897
+ "ins",
2898
+ "kbd",
2899
+ "label",
2900
+ "mark",
2901
+ "output",
2902
+ "q",
2903
+ "ruby",
2904
+ "s",
2905
+ "samp",
2906
+ "small",
2907
+ "span",
2908
+ "strong",
2909
+ "sub",
2910
+ "sup",
2911
+ "time",
2912
+ "u",
2913
+ "var"
2914
+ ]), this.rawTextMarkupTags = /* @__PURE__ */ new Set([
2915
+ "script",
2916
+ "style",
2917
+ "textarea",
2918
+ "title"
2919
+ ]), this.editor = null, this.foldingUI = null, this.pendingUpdateRaf = null, this.lastSnapshot = "", this.lastParsedText = null, this.changeHandler = null, this.foldRegions = [], this.foldSnapshots = /* @__PURE__ */ new Map(), this.isDisplayingFolded = !1, this.cachedLineInfo = null;
2920
+ }
2921
+ setup(e) {
2922
+ this.editor = e, e.registerCommand("fold", () => {
2923
+ this.foldAtCursor();
2924
+ }), e.registerCommand("unfold", () => {
2925
+ this.unfoldAtCursor();
2926
+ }), e.registerCommand("foldAll", () => {
2927
+ this.foldAll();
2928
+ }), e.registerCommand("unfoldAll", () => {
2929
+ this.unfoldAll();
2930
+ }), this.changeHandler = () => {
2931
+ this.syncFoldingState();
2932
+ }, e.on("change", this.changeHandler), this.createFoldingUI(), this.syncFoldingState();
2933
+ }
2934
+ onKeyDown(e) {
2935
+ }
2936
+ onMouseDown(e) {
2937
+ }
2938
+ createFoldingUI() {
2939
+ if (!this.editor) return;
2940
+ const e = this.editor.getView().getLineNumbersElement();
2941
+ e && (this.foldingUI = document.createElement("div"), this.foldingUI.setAttribute("data-lce-folding-ui", "true"), this.foldingUI.style.cssText = `
2942
+ position: absolute;
2943
+ right: 0;
2944
+ top: 0;
2945
+ bottom: 0;
2946
+ width: 20px;
2947
+ pointer-events: none;
2948
+ z-index: 3;
2949
+ `, e.appendChild(this.foldingUI));
2950
+ }
2951
+ syncFoldingState() {
2952
+ if (!this.editor) return;
2953
+ const e = this.editor.getValue(), t = this.foldSnapshots;
2954
+ 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();
2955
+ }
2956
+ scheduleFoldIndicatorUpdate() {
2957
+ this.pendingUpdateRaf === null && (this.pendingUpdateRaf = requestAnimationFrame(() => {
2958
+ this.pendingUpdateRaf = null, this.updateFoldIndicators();
2959
+ }));
2960
+ }
2961
+ updateFoldIndicators() {
2962
+ if (!this.editor || !this.foldingUI) return;
2963
+ const e = this.editor.getValue(), t = this.getActiveFolds().map((r) => this.getFoldKey(r)).join("|"), i = `${e}::${t}`;
2964
+ if (i === this.lastSnapshot) return;
2965
+ this.lastSnapshot = i, this.foldingUI.innerHTML = "";
2966
+ const n = this.getRenderableActiveFolds(), s = document.createDocumentFragment();
2967
+ for (const r of this.foldRegions) {
2968
+ const o = this.toDisplayLine(r, n);
2969
+ if (o === null) continue;
2970
+ const l = this.isFoldActive(r), a = this.createFoldIndicator(r, o, l);
2971
+ s.appendChild(a);
2972
+ }
2973
+ this.foldingUI.appendChild(s);
2974
+ }
2975
+ buildFoldRegions(e) {
2976
+ const t = this.buildBracketFoldRegions(e), i = this.shouldIncludeMarkupFolds(e) ? this.buildMarkupFoldRegions(e) : [];
2977
+ return this.mergeFoldRegions([...t, ...i]);
2978
+ }
2979
+ buildBracketFoldRegions(e) {
2980
+ var o;
2981
+ const t = e.split(`
2982
+ `), i = [], n = [], s = {
2983
+ "{": "}",
2984
+ "[": "]",
2985
+ "(": ")"
2986
+ }, r = {
2987
+ "}": "{",
2988
+ "]": "[",
2989
+ ")": "("
2990
+ };
2991
+ for (let l = 0; l < t.length; l++) {
2992
+ const a = t[l];
2993
+ for (let h = 0; h < a.length; h++) {
2994
+ const c = a[h];
2995
+ if (s[c]) {
2996
+ i.push({ char: c, line: l, column: h });
2997
+ continue;
2998
+ }
2999
+ const d = r[c];
3000
+ if (!d) continue;
3001
+ let f = -1;
3002
+ for (let m = i.length - 1; m >= 0; m--)
3003
+ if (i[m].char === d) {
3004
+ f = m;
3005
+ break;
3006
+ }
3007
+ if (f === -1) continue;
3008
+ const u = i.splice(f, 1)[0];
3009
+ if (u.line >= l) continue;
3010
+ const g = ((o = t[u.line]) == null ? void 0 : o.length) || 0, p = {
3011
+ start: { line: u.line, column: g },
3012
+ end: { line: l, column: 0 },
3013
+ collapsed: !1,
3014
+ level: f
3015
+ };
3016
+ this.isValidFoldRegion(p) && n.push(p);
3017
+ }
3018
+ }
3019
+ return n.sort((l, a) => l.start.line !== a.start.line ? l.start.line - a.start.line : l.end.line !== a.end.line ? l.end.line - a.end.line : l.start.column - a.start.column), n;
3020
+ }
3021
+ shouldIncludeMarkupFolds(e) {
3022
+ return /<!DOCTYPE\b/i.test(e) || /<[A-Za-z][\w:-]*(?:\s|>)/.test(e) && /<\/[A-Za-z][\w:-]*\s*>/.test(e);
3023
+ }
3024
+ buildMarkupFoldRegions(e) {
3025
+ const { lineStarts: t, lines: i } = this.buildLineStarts(e), n = [], s = [];
3026
+ let r = 0;
3027
+ for (; r < e.length; ) {
3028
+ if (e[r] !== "<") {
3029
+ r += 1;
3030
+ continue;
3031
+ }
3032
+ if (e.startsWith("<!--", r)) {
3033
+ const l = e.indexOf("-->", r + 4);
3034
+ r = l === -1 ? e.length : l + 3;
3035
+ continue;
3036
+ }
3037
+ if (e.startsWith("<![CDATA[", r)) {
3038
+ const l = e.indexOf("]]>", r + 9);
3039
+ r = l === -1 ? e.length : l + 3;
3040
+ continue;
3041
+ }
3042
+ const o = this.parseMarkupTag(e, r, t, i);
3043
+ if (!o) {
3044
+ r += 1;
3045
+ continue;
3046
+ }
3047
+ if (r = o.endOffset, o.isClosing) {
3048
+ const l = s.findIndex((c) => c.name === o.name);
3049
+ if (l === -1)
3050
+ continue;
3051
+ const a = s.splice(l, 1)[0], h = this.createMarkupFoldRegion(
3052
+ a.openEndLine,
3053
+ o.startLine,
3054
+ i
3055
+ );
3056
+ h && n.push(h);
3057
+ continue;
3058
+ }
3059
+ if (!(o.isSelfClosing || this.voidMarkupTags.has(o.name))) {
3060
+ if (this.rawTextMarkupTags.has(o.name)) {
3061
+ const l = this.findClosingMarkupTag(
3062
+ e,
3063
+ o.endOffset,
3064
+ o.name,
3065
+ t,
3066
+ i
3067
+ );
3068
+ if (l) {
3069
+ const a = this.createMarkupFoldRegion(
3070
+ o.endLine,
3071
+ l.startLine,
3072
+ i
3073
+ );
3074
+ a && n.push(a), r = l.endOffset;
3075
+ }
3076
+ continue;
3077
+ }
3078
+ this.nonFoldableInlineMarkupTags.has(o.name) || s.unshift({
3079
+ name: o.name,
3080
+ openEndLine: o.endLine
3081
+ });
3082
+ }
3083
+ }
3084
+ return n;
3085
+ }
3086
+ parseMarkupTag(e, t, i, n) {
3087
+ if (e[t] !== "<")
3088
+ return null;
3089
+ const s = e[t + 1];
3090
+ if (!s || s !== "/" && !/[A-Za-z]/.test(s))
3091
+ return null;
3092
+ const r = s === "/";
3093
+ let o = t + (r ? 2 : 1);
3094
+ const l = o;
3095
+ for (; o < e.length && /[A-Za-z0-9:-]/.test(e[o]); )
3096
+ o += 1;
3097
+ const a = o;
3098
+ if (o === l)
3099
+ return null;
3100
+ let h = null;
3101
+ for (; o < e.length; ) {
3102
+ const g = e[o];
3103
+ if (h) {
3104
+ g === h && (h = null), o += 1;
3105
+ continue;
3106
+ }
3107
+ if (g === '"' || g === "'") {
3108
+ h = g, o += 1;
3109
+ continue;
3110
+ }
3111
+ if (g === ">")
3112
+ break;
3113
+ o += 1;
3114
+ }
3115
+ if (o >= e.length || e[o] !== ">")
3116
+ return null;
3117
+ const c = e.slice(l, a).toLowerCase();
3118
+ if (!c)
3119
+ return null;
3120
+ const d = e.slice(t, o + 1), f = this.offsetToLine(t, i, n), u = this.offsetToLine(o, i, n);
3121
+ return {
3122
+ name: c,
3123
+ isClosing: r,
3124
+ isSelfClosing: !r && /\/\s*>$/.test(d),
3125
+ startLine: f,
3126
+ endLine: u,
3127
+ endOffset: o + 1
3128
+ };
3129
+ }
3130
+ findClosingMarkupTag(e, t, i, n, s) {
3131
+ const r = `</${i}`, o = e.toLowerCase();
3132
+ let l = o.indexOf(r, t);
3133
+ for (; l !== -1; ) {
3134
+ const a = this.parseMarkupTag(e, l, n, s);
3135
+ if (a && a.isClosing && a.name === i)
3136
+ return {
3137
+ startLine: a.startLine,
3138
+ endOffset: a.endOffset
3139
+ };
3140
+ l = o.indexOf(r, l + r.length);
3141
+ }
3142
+ return null;
3143
+ }
3144
+ createMarkupFoldRegion(e, t, i) {
3145
+ var o;
3146
+ if (e >= t)
3147
+ return null;
3148
+ const n = Math.max(0, Math.min(e, i.length - 1)), s = Math.max(0, Math.min(t, i.length - 1)), r = {
3149
+ start: {
3150
+ line: n,
3151
+ column: ((o = i[n]) == null ? void 0 : o.length) || 0
3152
+ },
3153
+ end: {
3154
+ line: s,
3155
+ column: 0
3156
+ },
3157
+ collapsed: !1,
3158
+ level: 0
3159
+ };
3160
+ return this.isValidFoldRegion(r) ? r : null;
3161
+ }
3162
+ mergeFoldRegions(e) {
3163
+ const t = /* @__PURE__ */ new Map();
3164
+ for (const i of e)
3165
+ this.isValidFoldRegion(i) && t.set(this.getFoldKey(i), i);
3166
+ return [...t.values()].sort((i, n) => i.start.line !== n.start.line ? i.start.line - n.start.line : i.end.line !== n.end.line ? i.end.line - n.end.line : i.start.column - n.start.column);
3167
+ }
3168
+ createFoldIndicator(e, t, i) {
3169
+ const n = document.createElement("button");
3170
+ return n.type = "button", n.style.cssText = `
3171
+ position: absolute;
3172
+ left: 0;
3173
+ top: ${t * this.lineHeight}px;
3174
+ width: 20px;
3175
+ height: ${this.lineHeight}px;
3176
+ display: flex;
3177
+ align-items: center;
3178
+ justify-content: center;
3179
+ cursor: pointer;
3180
+ pointer-events: auto;
3181
+ color: var(--editor-gutter-foreground, #858585);
3182
+ background: transparent;
3183
+ border: none;
3184
+ padding: 0;
3185
+ font-size: 10px;
3186
+ user-select: none;
3187
+ `, n.textContent = i ? "▶" : "▼", n.title = i ? "Expand folded region" : "Collapse region", n.setAttribute("aria-label", n.title), n.addEventListener("mousedown", (s) => {
3188
+ s.preventDefault();
3189
+ }), n.addEventListener("click", (s) => {
3190
+ s.preventDefault(), s.stopPropagation(), this.toggleFold(e);
3191
+ }), n;
3192
+ }
3193
+ toggleFold(e) {
3194
+ this.editor && (this.isFoldActive(e) ? this.editor.unfold(e) : this.editor.fold(e), this.syncFoldingStatePreservingScroll());
3195
+ }
3196
+ foldAtCursor() {
3197
+ if (!this.editor) return;
3198
+ const e = this.editor.getCursor().position.line, t = this.findBestRegionForLine(e, !1);
3199
+ t && (this.editor.fold(t), this.syncFoldingStatePreservingScroll());
3200
+ }
3201
+ unfoldAtCursor() {
3202
+ if (!this.editor) return;
3203
+ const e = this.editor.getCursor().position.line, t = this.findBestRegionForLine(e, !0);
3204
+ t && (this.editor.unfold(t), this.syncFoldingStatePreservingScroll());
3205
+ }
3206
+ foldAll() {
3207
+ if (!this.editor) return;
3208
+ const e = this.getTopLevelFoldRegions(this.foldRegions);
3209
+ for (const t of e)
3210
+ this.editor.fold(t);
3211
+ this.syncFoldingStatePreservingScroll();
3212
+ }
3213
+ unfoldAll() {
3214
+ if (!this.editor) return;
3215
+ const e = this.getActiveFolds();
3216
+ for (const t of e)
3217
+ this.editor.unfold(t);
3218
+ this.syncFoldingStatePreservingScroll();
3219
+ }
3220
+ syncFoldingStatePreservingScroll() {
3221
+ this.withPreservedScroll(() => {
3222
+ this.syncFoldingState();
3223
+ });
3224
+ }
3225
+ withPreservedScroll(e) {
3226
+ var s;
3227
+ const t = (s = this.editor) == null ? void 0 : s.getView().getScrollElement();
3228
+ if (!t) {
3229
+ e();
3230
+ return;
3231
+ }
3232
+ const i = t.scrollLeft, n = t.scrollTop;
3233
+ e(), this.restoreScrollPosition(t, i, n);
3234
+ }
3235
+ restoreScrollPosition(e, t, i) {
3236
+ e.scrollLeft = t, e.scrollTop = i, requestAnimationFrame(() => {
3237
+ e.isConnected && (e.scrollLeft = t, e.scrollTop = i);
3238
+ });
3239
+ }
3240
+ applyFoldedDisplay() {
3241
+ if (!this.editor) return;
3242
+ const e = this.getRenderableActiveFolds();
3243
+ if (e.length === 0) {
3244
+ this.restoreFullDisplay();
3245
+ return;
3246
+ }
3247
+ const t = this.buildFoldedProjection(this.editor.getValue(), e);
3248
+ this.withPreservedSelection(() => {
3249
+ this.renderEditorText(t.text), this.renderFoldPlaceholders(t), this.isDisplayingFolded = !0;
3250
+ });
3251
+ }
3252
+ restoreFullDisplay() {
3253
+ this.editor && (this.isDisplayingFolded && this.withPreservedSelection(() => {
3254
+ this.renderEditorText(this.editor.getValue());
3255
+ }), this.isDisplayingFolded = !1);
3256
+ }
3257
+ renderEditorText(e) {
3258
+ if (!this.editor) return;
3259
+ const t = this.editor;
3260
+ if (typeof t.renderTextWithHighlight == "function") {
3261
+ t.expectingProgrammaticCursor = !0, t.renderTextWithHighlight(e, !1), t.expectingProgrammaticCursor = !1;
3262
+ return;
3263
+ }
3264
+ this.editor.getView().setText(e);
3265
+ }
3266
+ buildFoldedProjection(e, t) {
3267
+ const { lineStarts: i, lines: n } = this.buildLineStarts(e), s = [...t].sort((h, c) => this.comparePositions(h.start, c.start));
3268
+ let r = "";
3269
+ const o = [];
3270
+ let l = 0;
3271
+ for (const h of s) {
3272
+ const c = this.positionToOffset(h.start, i, n), d = this.positionToOffset(h.end, i, n), f = e.slice(l, c), u = this.getFoldPlaceholder(h), g = e.slice(c, d);
3273
+ r += f, r += u, f && o.push({ type: "text", text: f }), o.push({
3274
+ type: "placeholder",
3275
+ text: u,
3276
+ fold: h,
3277
+ hiddenText: g
3278
+ }), l = d;
3279
+ }
3280
+ const a = e.slice(l);
3281
+ return r += a, a && o.push({ type: "text", text: a }), { text: r, segments: o };
3282
+ }
3283
+ renderFoldPlaceholders(e) {
3284
+ if (!this.editor) return;
3285
+ const t = this.editor.getView().getContentElement(), i = /* @__PURE__ */ new Map(), n = document.createDocumentFragment();
3286
+ for (const s of e.segments) {
3287
+ if (s.type === "text") {
3288
+ n.appendChild(document.createTextNode(s.text));
3289
+ continue;
3290
+ }
3291
+ const r = document.createElement("span"), o = this.getFoldKey(s.fold);
3292
+ r.setAttribute("data-lce-fold-placeholder", o), r.setAttribute("aria-label", "Folded region"), r.contentEditable = "false", i.set(o, s.hiddenText), r.style.cssText = `
3293
+ cursor: text;
3294
+ user-select: text;
3295
+ pointer-events: auto;
3296
+ white-space: pre;
3297
+ `, r.textContent = s.text, n.appendChild(r);
3298
+ }
3299
+ t.replaceChildren(n), t.__lceFoldPlaceholderSources = i, this.editor.getView().syncTrailingNewlineMarkerForText(e.text);
3300
+ }
3301
+ getFoldPlaceholder(e) {
3302
+ const t = Math.max(1, e.end.line - e.start.line);
3303
+ return ` … ${t} ${t === 1 ? "line" : "lines"} … `;
3304
+ }
3305
+ pruneInvalidFolds(e, t) {
3306
+ if (!this.editor) return;
3307
+ const i = this.editor.getFolds().filter((a) => a.collapsed !== !1), n = new Set(i.map((a) => this.getFoldKey(a))), s = [], r = /* @__PURE__ */ new Set(), o = this.getLineInfo(e);
3308
+ for (const a of i) {
3309
+ const h = this.findReplacementFold(
3310
+ a,
3311
+ t.get(this.getFoldKey(a)),
3312
+ r,
3313
+ e,
3314
+ o
3315
+ );
3316
+ if (!h)
3317
+ continue;
3318
+ const c = this.getFoldKey(h);
3319
+ s.push(h), r.add(c);
3320
+ }
3321
+ const l = new Set(s.map((a) => this.getFoldKey(a)));
3322
+ for (const a of i)
3323
+ l.has(this.getFoldKey(a)) || this.editor.unfold(a);
3324
+ for (const a of s)
3325
+ n.has(this.getFoldKey(a)) || this.editor.fold(a);
3326
+ }
3327
+ getActiveFolds() {
3328
+ return this.editor ? this.editor.getFolds().filter((e) => e.collapsed !== !1) : [];
3329
+ }
3330
+ hasActiveFolds() {
3331
+ return this.getActiveFolds().length > 0;
3332
+ }
3333
+ getRenderableActiveFolds() {
3334
+ return this.getTopLevelFoldRegions(this.getActiveFolds());
3335
+ }
3336
+ getTopLevelFoldRegions(e) {
3337
+ const t = [...e].sort((n, s) => this.comparePositions(n.start, s.start)), i = [];
3338
+ for (const n of t) {
3339
+ const s = i[i.length - 1];
3340
+ s && this.containsRange(s, n) || i.push(n);
3341
+ }
3342
+ return i;
3343
+ }
3344
+ toDisplayLine(e, t) {
3345
+ let i = 0;
3346
+ for (const n of t) {
3347
+ if (this.isSameRange(n, e))
3348
+ break;
3349
+ if (this.containsRange(n, e))
3350
+ return null;
3351
+ n.end.line <= e.start.line && (i += n.end.line - n.start.line);
3352
+ }
3353
+ return e.start.line - i;
3354
+ }
3355
+ findBestRegionForLine(e, t) {
3356
+ const n = (t ? this.getActiveFolds() : this.foldRegions).filter(
3357
+ (s) => s.start.line <= e && s.end.line >= e
3358
+ );
3359
+ return n.length === 0 ? null : (n.sort((s, r) => {
3360
+ const o = s.end.line - s.start.line, l = r.end.line - r.start.line;
3361
+ return o !== l ? o - l : this.comparePositions(s.start, r.start);
3362
+ }), n[0]);
3363
+ }
3364
+ findReplacementFold(e, t, i, n, s) {
3365
+ const r = this.getFoldKey(e), o = this.foldRegions.find(
3366
+ (u) => this.getFoldKey(u) === r && !i.has(r)
3367
+ );
3368
+ if (o)
3369
+ return o;
3370
+ const l = e.end.line - e.start.line, a = t != null ? t : this.createFoldSnapshot(e, n, s), c = this.foldRegions.filter((u) => !i.has(this.getFoldKey(u))).map((u) => {
3371
+ const g = this.createFoldSnapshot(u, n, s), p = a && (g == null ? void 0 : g.startLineText) === a.startLineText ? 1 : 0, m = a && (g == null ? void 0 : g.endLineText) === a.endLineText ? 1 : 0, y = a && (g == null ? void 0 : g.lineSpan) === a.lineSpan ? 1 : 0;
3372
+ return {
3373
+ region: u,
3374
+ overlaps: this.lineRangeOverlap(e, u),
3375
+ lineDistance: Math.abs(u.start.line - e.start.line) + Math.abs(u.end.line - e.end.line),
3376
+ spanDistance: Math.abs(
3377
+ u.end.line - u.start.line - l
3378
+ ),
3379
+ columnDistance: Math.abs(u.start.column - e.start.column) + Math.abs(u.end.column - e.end.column),
3380
+ hiddenTextMatch: a && (g == null ? void 0 : g.hiddenText) === a.hiddenText ? 1 : 0,
3381
+ boundaryMatchScore: p + m + y
3382
+ };
3383
+ }).sort((u, g) => u.hiddenTextMatch !== g.hiddenTextMatch ? g.hiddenTextMatch - u.hiddenTextMatch : u.boundaryMatchScore !== g.boundaryMatchScore ? g.boundaryMatchScore - u.boundaryMatchScore : u.overlaps !== g.overlaps ? g.overlaps - u.overlaps : u.lineDistance !== g.lineDistance ? u.lineDistance - g.lineDistance : u.spanDistance !== g.spanDistance ? u.spanDistance - g.spanDistance : u.columnDistance - g.columnDistance)[0];
3384
+ if (!c)
3385
+ return null;
3386
+ const d = c.lineDistance <= 2 && c.spanDistance <= 1;
3387
+ return !(c.hiddenTextMatch === 1 || c.boundaryMatchScore >= 2) && !d ? null : c.region;
3388
+ }
3389
+ lineRangeOverlap(e, t) {
3390
+ const i = Math.max(e.start.line, t.start.line), n = Math.min(e.end.line, t.end.line);
3391
+ return Math.max(0, n - i);
3392
+ }
3393
+ rememberActiveFoldSnapshots(e) {
3394
+ const t = /* @__PURE__ */ new Map(), i = this.getLineInfo(e);
3395
+ for (const n of this.getActiveFolds()) {
3396
+ const s = this.createFoldSnapshot(n, e, i);
3397
+ s && t.set(this.getFoldKey(n), s);
3398
+ }
3399
+ this.foldSnapshots = t;
3400
+ }
3401
+ createFoldSnapshot(e, t, i = this.getLineInfo(t)) {
3402
+ var h, c;
3403
+ const { lineStarts: n, lines: s } = i;
3404
+ if (s.length === 0)
3405
+ return null;
3406
+ const r = this.positionToOffset(e.start, n, s), o = this.positionToOffset(e.end, n, s), l = Math.max(0, Math.min(e.start.line, s.length - 1)), a = Math.max(0, Math.min(e.end.line, s.length - 1));
3407
+ return {
3408
+ hiddenText: t.slice(r, o),
3409
+ startLineText: (h = s[l]) != null ? h : "",
3410
+ endLineText: (c = s[a]) != null ? c : "",
3411
+ lineSpan: e.end.line - e.start.line
3412
+ };
3413
+ }
3414
+ withPreservedSelection(e) {
3415
+ var l, a;
3416
+ if (!this.editor) {
3417
+ e();
3418
+ return;
3419
+ }
3420
+ const t = this.editor.getView(), i = t.getContentElement(), n = document.activeElement === i, s = t.getSelectionOffsets(), r = s.isInEditor;
3421
+ if (e(), !r)
3422
+ return;
3423
+ const o = this.remapSelectionOffsetsForVisibleDisplay(
3424
+ (l = s.anchorOffset) != null ? l : s.startOffset,
3425
+ (a = s.focusOffset) != null ? a : s.endOffset
3426
+ );
3427
+ t.setSelectionBoundaryOffsets(
3428
+ o.startOffset,
3429
+ o.endOffset
3430
+ ), (n || s.isInEditor) && this.editor.focus();
3431
+ }
3432
+ remapSelectionOffsetsForVisibleDisplay(e, t) {
3433
+ if (!this.editor)
3434
+ return { startOffset: e, endOffset: t };
3435
+ const i = this.editor.getValue(), { lineStarts: n, lines: s } = this.getLineInfo(i), r = this.getRenderableActiveFolds();
3436
+ if (r.length === 0) {
3437
+ const o = i.length;
3438
+ return {
3439
+ startOffset: Math.max(0, Math.min(e, o)),
3440
+ endOffset: Math.max(0, Math.min(t, o))
3441
+ };
3442
+ }
3443
+ return {
3444
+ startOffset: this.remapOffsetToVisibleBoundary(
3445
+ e,
3446
+ r,
3447
+ n,
3448
+ s,
3449
+ i.length
3450
+ ),
3451
+ endOffset: this.remapOffsetToVisibleBoundary(
3452
+ t,
3453
+ r,
3454
+ n,
3455
+ s,
3456
+ i.length
3457
+ )
3458
+ };
3459
+ }
3460
+ remapOffsetToVisibleBoundary(e, t, i, n, s) {
3461
+ const r = Math.max(0, Math.min(e, s));
3462
+ for (const o of t) {
3463
+ const l = this.positionToOffset(o.start, i, n), a = this.positionToOffset(o.end, i, n);
3464
+ if (r <= l || r >= a)
3465
+ continue;
3466
+ const h = r - l, c = a - r;
3467
+ return h <= c ? l : a;
3468
+ }
3469
+ return r;
3470
+ }
3471
+ buildLineStarts(e) {
3472
+ const t = e.split(`
3473
+ `), i = new Array(t.length);
3474
+ let n = 0;
3475
+ for (let s = 0; s < t.length; s++)
3476
+ i[s] = n, n += t[s].length + 1;
3477
+ return { lineStarts: i, lines: t };
3478
+ }
3479
+ getLineInfo(e) {
3480
+ var i;
3481
+ if (((i = this.cachedLineInfo) == null ? void 0 : i.text) === e)
3482
+ return this.cachedLineInfo;
3483
+ const t = {
3484
+ text: e,
3485
+ ...this.buildLineStarts(e)
3486
+ };
3487
+ return this.cachedLineInfo = t, t;
3488
+ }
3489
+ offsetToLine(e, t, i) {
3490
+ var l;
3491
+ const n = t.length > 0 ? t[t.length - 1] + (((l = i[i.length - 1]) == null ? void 0 : l.length) || 0) : 0, s = Math.max(0, Math.min(e, n));
3492
+ let r = 0, o = t.length - 1;
3493
+ for (; r <= o; ) {
3494
+ const a = Math.floor((r + o) / 2), h = t[a], c = a + 1 < t.length ? t[a + 1] : Number.POSITIVE_INFINITY;
3495
+ if (s < h) {
3496
+ o = a - 1;
3497
+ continue;
3498
+ }
3499
+ if (s >= c) {
3500
+ r = a + 1;
3501
+ continue;
3502
+ }
3503
+ return a;
3504
+ }
3505
+ return Math.max(0, Math.min(r, t.length - 1));
3506
+ }
3507
+ positionToOffset(e, t, i) {
3508
+ var r;
3509
+ const n = Math.max(0, Math.min(e.line, i.length - 1)), s = Math.max(0, Math.min(e.column, ((r = i[n]) == null ? void 0 : r.length) || 0));
3510
+ return t[n] + s;
3511
+ }
3512
+ comparePositions(e, t) {
3513
+ return e.line !== t.line ? e.line - t.line : e.column - t.column;
3514
+ }
3515
+ containsRange(e, t) {
3516
+ return this.comparePositions(e.start, t.start) <= 0 && this.comparePositions(e.end, t.end) >= 0 && !this.isSameRange(e, t);
3517
+ }
3518
+ isSameRange(e, t) {
3519
+ 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;
3520
+ }
3521
+ isFoldActive(e) {
3522
+ return this.getActiveFolds().some((t) => this.isSameRange(t, e));
3523
+ }
3524
+ isValidFoldRegion(e) {
3525
+ return e.start.line < e.end.line && (e.start.line !== e.end.line || e.start.column !== e.end.column);
3526
+ }
3527
+ getFoldKey(e) {
3528
+ return `${e.start.line}:${e.start.column}-${e.end.line}:${e.end.column}`;
3529
+ }
3530
+ destroy() {
3531
+ 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;
3532
+ }
3533
+ }
3534
+ class ce {
3535
+ constructor() {
3536
+ this.name = "syntax-highlighting", this.editor = null, this.currentTheme = "dark", this.currentLanguage = null, this.modes = /* @__PURE__ */ new Map();
3537
+ }
3538
+ setup(e) {
3539
+ 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) => {
3540
+ this.setLanguage(t), this.refreshEditorHighlight();
3541
+ });
3542
+ }
3543
+ // Extension provides methods that can be called by the editor
3544
+ setTheme(e) {
3545
+ this.currentTheme = e;
3546
+ }
3547
+ setLanguage(e) {
3548
+ this.currentLanguage = e;
3549
+ }
3550
+ registerMode(e, t) {
3551
+ this.modes.set(e.toLowerCase(), t);
3552
+ }
3553
+ // Method to get syntax highlighting colors for a given theme
3554
+ getSyntaxColors() {
3555
+ return this.currentTheme === "dark" ? {
3556
+ tag: "#569cd6",
3557
+ // Blue
3558
+ comment: "#6a9955",
3559
+ // Green
3560
+ attrName: "#9cdcfe",
3561
+ // Light blue for attribute names
3562
+ attrValue: "#ce9178",
3563
+ // Orange for attribute values
3564
+ styleProp: "#c586c0",
3565
+ // Purple for CSS property names
3566
+ styleVal: "#dcdcaa",
3567
+ // Yellow-ish for CSS values
3568
+ doctype: "#808080",
3569
+ // Gray for doctype
3570
+ text: "#d4d4d4",
3571
+ // Light gray for normal text
3572
+ keyword: "#c586c0",
3573
+ // JS/PHP keywords (purple)
3574
+ string: "#ce9178",
3575
+ // JS strings
3576
+ number: "#b5cea8",
3577
+ // numbers
3578
+ variable: "#9cdcfe"
3579
+ // php variable color
3580
+ } : {
3581
+ tag: "#0000ff",
3582
+ // Blue
3583
+ comment: "#008000",
3584
+ // Green
3585
+ attrName: "#001080",
3586
+ attrValue: "#a31515",
3587
+ // Red
3588
+ styleProp: "#6a00a8",
3589
+ styleVal: "#804000",
3590
+ doctype: "#444444",
3591
+ text: "#000000",
3592
+ // Black
3593
+ keyword: "#000080",
3594
+ string: "#a31515",
3595
+ number: "#0086b3",
3596
+ variable: "#001080"
3597
+ };
3598
+ }
3599
+ // Public API: highlight a source string using the chosen mode (or detect html)
3600
+ highlight(e, t) {
3601
+ const i = this.getSyntaxColors(), n = this.normalizeLanguageId(
3602
+ t || this.currentLanguage || this.detectLanguage(e) || "html"
3603
+ );
3604
+ return (this.modes.get(n) || this.modes.get("html")).highlight(e, i);
3605
+ }
3606
+ // Backwards-compatible method
3607
+ highlightHTML(e) {
3608
+ return this.highlight(e, "html");
3609
+ }
3610
+ // --- Internal mode implementations ---
3611
+ escapeHTML(e) {
3612
+ return e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\"/g, "&quot;").replace(/'/g, "&#39;");
3613
+ }
3614
+ normalizeLanguageId(e) {
3615
+ const t = e.trim().toLowerCase().replace(/^\./, "");
3616
+ return {
3617
+ cjs: "javascript",
3618
+ js: "javascript",
3619
+ javascriptreact: "javascript",
3620
+ jsx: "jsx",
3621
+ mjs: "javascript",
3622
+ mts: "typescript",
3623
+ ts: "typescript",
3624
+ tsx: "tsx",
3625
+ typescriptreact: "tsx",
3626
+ md: "markdown",
3627
+ mdx: "markdown",
3628
+ shell: "bash",
3629
+ sh: "bash",
3630
+ zsh: "bash",
3631
+ console: "bash",
3632
+ terminal: "bash",
3633
+ docker: "dockerfile",
3634
+ dockerfile: "dockerfile",
3635
+ golang: "go",
3636
+ py: "python",
3637
+ cxx: "cpp",
3638
+ cc: "cpp",
3639
+ "c++": "cpp",
3640
+ cs: "csharp",
3641
+ rs: "rust",
3642
+ rb: "ruby",
3643
+ yml: "yaml",
3644
+ svg: "xml",
3645
+ vue: "vue",
3646
+ ejs: "ejs"
3647
+ }[t] || t || "html";
3648
+ }
3649
+ restoreHighlightTokens(e, t) {
3650
+ return e.replace(/\u0000([a-z]+)\u0000/g, (i, n) => {
3651
+ let s = 0;
3652
+ for (let r = 0; r < n.length; r++)
3653
+ s = s * 26 + (n.charCodeAt(r) - 97 + 1);
3654
+ return s = s - 1, t[s] || "";
3655
+ });
3656
+ }
3657
+ createTokenStore(e) {
3658
+ const t = (i) => {
3659
+ let n = "", s = i;
3660
+ do
3661
+ n = String.fromCharCode(97 + s % 26) + n, s = Math.floor(s / 26) - 1;
3662
+ while (s >= 0);
3663
+ return n || "a";
3664
+ };
3665
+ return (i) => {
3666
+ const n = e.length;
3667
+ return e.push(i), `\0${t(n)}\0`;
3668
+ };
3669
+ }
3670
+ refreshEditorHighlight() {
3671
+ const e = this.editor;
3672
+ e != null && e.renderTextWithHighlight && e.renderTextWithHighlight(e.getValue(), !0);
3673
+ }
3674
+ // Robustly unescape common HTML entities, repeating a few times to handle nested encoding like &amp;amp;...
3675
+ unescapeEntitiesRepeated(e) {
3676
+ let t = e || "";
3677
+ for (let i = 0; i < 5; i++) {
3678
+ const n = t;
3679
+ if (t = t.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'"), t === n) break;
3680
+ }
3681
+ return t;
3682
+ }
3683
+ detectLanguage(e) {
3684
+ const t = e.trim();
3685
+ if (!t)
3686
+ return null;
3687
+ if (/^<\?(?:php\b|=)/i.test(t) || /^\?php\b/i.test(t))
3688
+ return "php";
3689
+ if (/^[\[{]/.test(t) && /[\]}]$/.test(t) || /"[^"]+"\s*:/.test(t))
3690
+ try {
3691
+ return JSON.parse(t), "json";
3692
+ } catch (a) {
3693
+ }
3694
+ const i = /<\/?[A-Za-z][\w:-]*(?:\s|>|\/>)/.test(t), n = /^<!DOCTYPE\s+html\b/i.test(t) || /<\/?(html|head|body|meta|title|style|script)\b/i.test(t);
3695
+ if ([
3696
+ /^---\s*\n[\s\S]*?\n---\s*(?:\n|$)/.test(t),
3697
+ /^#{1,6}\s+\S/m.test(t),
3698
+ /^\s*```/m.test(t),
3699
+ /^\s*~~~/m.test(t),
3700
+ /^\s{0,3}>\s+/m.test(t),
3701
+ /^\s{0,3}(?:[-*+]|\d+\.)\s+\S/m.test(t),
3702
+ /^\s{0,3}[-*+]\s+\[[ xX]\]\s+\S/m.test(t),
3703
+ /\[[^\]\n]+\]\([^)]+\)/.test(t),
3704
+ /!\[[^\]\n]*\]\([^)]+\)/.test(t),
3705
+ /(^|\n)\s*\|.+\|\s*\n\s*\|[\s:-]+\|/m.test(t),
3706
+ /(^|\s)(?:\*\*|__)[^*_]+(?:\*\*|__)(?=\s|$|[.,;:!?])/m.test(t)
3707
+ ].filter(Boolean).length >= (i ? 2 : 1))
3708
+ return "markdown";
3709
+ if (n)
3710
+ return "html";
3711
+ const o = this.detectProgrammingLanguage(t);
3712
+ if (o)
3713
+ return o;
3714
+ const l = /[{][\s\S]*[}]/.test(t) && /[A-Za-z_-][\w-]*\s*:\s*[^;{}]+;?/.test(t) && !/\b(function|const|let|var|return|class|interface|type)\b/.test(t);
3715
+ return !i && l ? "css" : null;
3716
+ }
3717
+ detectProgrammingLanguage(e) {
3718
+ const t = {
3719
+ php: 0,
3720
+ python: 0,
3721
+ go: 0,
3722
+ cpp: 0,
3723
+ c: 0,
3724
+ java: 0,
3725
+ csharp: 0,
3726
+ rust: 0,
3727
+ ruby: 0,
3728
+ sql: 0,
3729
+ yaml: 0,
3730
+ dockerfile: 0
3731
+ }, i = (r, o, l = 1) => {
3732
+ o.test(e) && (t[r] += l);
3733
+ };
3734
+ 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);
3735
+ const [n, s] = Object.entries(t).sort((r, o) => o[1] - r[1])[0] || ["", 0];
3736
+ return s >= 2 ? n : null;
3737
+ }
3738
+ _highlightHTML(e, t) {
3739
+ const i = t, n = (d) => this.escapeHTML(d), s = [], r = this.createTokenStore(s), o = [], l = (d) => {
3740
+ const f = o.length;
3741
+ return o.push(d), `ht${f}`;
3742
+ };
3743
+ let a = n(e);
3744
+ a = a.replace(
3745
+ /&lt;\/?(?:(?!&gt;)[^\n\r<])*?(?=$|[\n\r])/g,
3746
+ (d) => l(d)
3747
+ );
3748
+ const h = [];
3749
+ try {
3750
+ e.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi, (d, f, u) => (h.push({ attrs: String(f || ""), inner: String(u || "") }), d));
3751
+ } catch (d) {
3752
+ }
3753
+ let c = 0;
3754
+ return a = a.replace(/(&lt;script\b([^&>]*)&gt;)([\s\S]*?)(&lt;\/script&gt;)/gi, (d, f, u, g, p) => {
3755
+ var v, S, w;
3756
+ const m = (S = (v = h[c++]) == null ? void 0 : v.inner) != null ? S : this.unescapeEntitiesRepeated(g || "");
3757
+ (((w = h[c - 1]) == null ? void 0 : w.attrs) || u || "").toLowerCase();
3758
+ const y = this._highlightJS(m, i);
3759
+ return `${f}${y}${p}`;
3760
+ }), a = a.replace(/(&lt;style\b[^&]*&gt;)([\s\S]*?)(&lt;\/style&gt;)/gi, (d, f, u, g) => {
3761
+ const p = this._highlightCSS(this.unescapeEntitiesRepeated(u), i);
3762
+ return `${f}${p}${g}`;
3763
+ }), a = a.replace(
3764
+ /(&lt;!--[\s\S]*?--&gt;)/g,
3765
+ (d) => r(`<span style="color: ${i.comment};">${d}</span>`)
3766
+ ), a = a.replace(
3767
+ /(&lt;!DOCTYPE[\s\S]*?&gt;)/i,
3768
+ (d) => r(`<span style="color: ${i.doctype};">${d}</span>`)
3769
+ ), a = a.replace(/(&lt;\/?\s*)([^\s&>\/]+)([^<]*?)(\/?&gt;)/g, (d, f, u, g, p) => {
3770
+ const m = `<span style="color: ${i.tag};">${u}</span>`;
3771
+ let y = g;
3772
+ return y = y.replace(
3773
+ /([\w:-]+)(\s*=\s*)((&quot;[\s\S]*?&quot;|&#39;[\s\S]*?&#39;|[^\s&>]+))/g,
3774
+ (v, S, w, M) => {
3775
+ const O = String(S).toLowerCase(), $ = `<span style="color: ${i.attrName};">${S}</span>`;
3776
+ let I = M, E = "";
3777
+ M.startsWith("&quot;") && M.endsWith("&quot;") ? (I = M.slice(6, -6), E = "&quot;") : M.startsWith("&#39;") && M.endsWith("&#39;") && (I = M.slice(5, -5), E = "&#39;");
3778
+ let R = M;
3779
+ if (O === "style") {
3780
+ const N = I.replace(/([\w-]+)\s*:\s*([^;]+)(;?)/g, (F, k, P, H) => `<span style="color: ${i.styleProp};">${k}</span>:<span style="color: ${i.styleVal};">${P}</span>${H}`);
3781
+ E ? R = `${E}${N}${E}` : R = N, R = `<span style="color: ${i.attrValue};">${R}</span>`;
3782
+ } else
3783
+ E && (R = `${E}${I}${E}`), R = `<span style="color: ${i.attrValue};">${R}</span>`;
3784
+ return `${$}${w}${R}`;
3785
+ }
3786
+ ), `${f}${m}${y}${p}`;
3787
+ }), a = a.replace(/\u0002ht(\d+)\u0002/g, (d, f) => o[Number(f)] || ""), this.restoreHighlightTokens(a, s);
3788
+ }
3789
+ _highlightCSS(e, t) {
3790
+ const i = this.unescapeEntitiesRepeated(e), n = [], s = this.createTokenStore(n), r = /(\/\*[\s\S]*?\*\/)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g;
3791
+ let o = 0, l = "", a;
3792
+ for (; a = r.exec(i); ) {
3793
+ o < a.index && (l += this.escapeHTML(i.slice(o, a.index)));
3794
+ const h = a[0], c = h.startsWith("/*") ? t.comment : t.string;
3795
+ l += s(`<span style="color: ${c};">${this.escapeHTML(h)}</span>`), o = r.lastIndex;
3796
+ }
3797
+ return o < i.length && (l += this.escapeHTML(i.slice(o))), l = l.replace(
3798
+ /(@[\w-]+)/g,
3799
+ (h) => s(`<span style="color: ${t.keyword};">${h}</span>`)
3800
+ ), l = l.replace(
3801
+ /([A-Za-z_-][\w-]*)(\s*:)/g,
3802
+ (h, c, d) => `${s(`<span style="color: ${t.styleProp};">${c}</span>`)}${d}`
3803
+ ), l = l.replace(
3804
+ /(#(?:[0-9a-fA-F]{3,8})\b)/g,
3805
+ (h) => s(`<span style="color: ${t.number};">${h}</span>`)
3806
+ ), l = l.replace(
3807
+ /\b(-?\d*\.?\d+(?:px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|turn|fr)?)\b/g,
3808
+ (h) => s(`<span style="color: ${t.number};">${h}</span>`)
3809
+ ), l = l.replace(
3810
+ /\b(important|inherit|initial|unset|revert|auto|none|block|inline|flex|grid|absolute|relative|fixed|sticky)\b/g,
3811
+ (h) => s(`<span style="color: ${t.styleVal};">${h}</span>`)
3812
+ ), this.restoreHighlightTokens(l, n);
3813
+ }
3814
+ _highlightJSON(e, t) {
3815
+ const i = this.unescapeEntitiesRepeated(e), n = /("(?:\\.|[^"\\])*")(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}\[\],:]/g;
3816
+ let s = 0, r = "", o;
3817
+ for (; o = n.exec(i); ) {
3818
+ s < o.index && (r += this.escapeHTML(i.slice(s, o.index)));
3819
+ const l = o[0], a = o[1], h = o[2] || "", c = o[3];
3820
+ if (a) {
3821
+ const d = h ? t.attrName : t.string;
3822
+ r += `<span style="color: ${d};">${this.escapeHTML(a)}</span>${this.escapeHTML(h)}`;
3823
+ } else c ? 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>`;
3824
+ s = n.lastIndex;
3825
+ }
3826
+ return s < i.length && (r += this.escapeHTML(i.slice(s))), r;
3827
+ }
3828
+ _highlightMarkdown(e, t) {
3829
+ var a;
3830
+ const n = this.unescapeEntitiesRepeated(e).split(`
3831
+ `);
3832
+ let s = !1, r = "", o = "", l = ((a = n[0]) == null ? void 0 : a.trim()) === "---";
3833
+ return n.map((h, c) => {
3834
+ const d = [], f = this.createTokenStore(d);
3835
+ if (l) {
3836
+ const p = h.trim() === "---", y = `<span style="color: ${p ? t.keyword : t.attrName};">${this.escapeHTML(h)}</span>`;
3837
+ return c > 0 && p && (l = !1), y;
3838
+ }
3839
+ const u = h.match(/^(\s*)(`{3,}|~{3,})(.*)$/);
3840
+ if (u) {
3841
+ const p = u[2];
3842
+ return s = !(s && p[0] === r[0]), r = s ? p : "", o = s ? this.extractMarkdownFenceLanguage(u[3] || "") : "", [
3843
+ this.escapeHTML(u[1]),
3844
+ `<span style="color: ${t.keyword}; font-weight: 700;">${this.escapeHTML(p)}</span>`,
3845
+ `<span style="color: ${t.string};">${this.escapeHTML(u[3] || "")}</span>`
3846
+ ].join("");
3847
+ }
3848
+ if (s)
3849
+ return this.highlightMarkdownFenceLine(h, o, t);
3850
+ let g = this.escapeHTML(h).replace(
3851
+ /(`[^`]+`)/g,
3852
+ (p) => f(`<span style="color: ${t.string}; background: rgba(148, 163, 184, 0.16); border-radius: 3px;">${p}</span>`)
3853
+ ).replace(
3854
+ /(!?\[[^\]\n]*\])(\([^)]+\))/g,
3855
+ (p, m, y) => f(`<span style="color: ${t.attrName};">${m}</span><span style="color: ${t.attrValue};">${y}</span>`)
3856
+ ).replace(
3857
+ /(\*\*|__)(.+?)\1/g,
3858
+ (p, m, y) => f(`<span style="color: ${t.keyword};">${m}</span><span style="color: ${t.tag}; font-weight: 700;">${y}</span><span style="color: ${t.keyword};">${m}</span>`)
3859
+ ).replace(
3860
+ /(~~)(.+?)\1/g,
3861
+ (p, m, y) => f(`<span style="color: ${t.keyword};">${m}</span><span style="color: ${t.comment}; text-decoration: line-through;">${y}</span><span style="color: ${t.keyword};">${m}</span>`)
3862
+ ).replace(
3863
+ /(\*|_)([^*_]+?)\1/g,
3864
+ (p, m, y) => f(`<span style="color: ${t.keyword};">${m}</span><span style="color: ${t.styleVal}; font-style: italic;">${y}</span><span style="color: ${t.keyword};">${m}</span>`)
3865
+ );
3866
+ return g = g.replace(
3867
+ /^(\s{0,3}#{1,6})(\s+.*)?$/,
3868
+ (p, m, y = "") => `<span style="color: ${t.keyword}; font-weight: 700;">${m}</span><span style="color: ${t.tag}; font-weight: 700;">${y}</span>`
3869
+ ), g = g.replace(
3870
+ /^(\s{0,3})((?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/,
3871
+ (p, m, y) => `${m}<span style="color: ${t.comment};">${y}</span>`
3872
+ ), g = g.replace(
3873
+ /^(\s{0,3}&gt;)(.*)$/,
3874
+ (p, m, y) => `<span style="color: ${t.comment};">${m}</span>${y}`
3875
+ ), g = g.replace(
3876
+ /^(\s*)([-*+])(\s+\[[ xX]\])(\s+)/,
3877
+ (p, m, y, v, S) => `${m}<span style="color: ${t.keyword};">${y}</span><span style="color: ${t.attrName};">${v}</span>${S}`
3878
+ ), g = g.replace(
3879
+ /^(\s*)([-*+]|\d+\.)(\s+)/,
3880
+ (p, m, y, v) => `${m}<span style="color: ${t.keyword};">${y}</span>${v}`
3881
+ ), g = g.replace(
3882
+ /^(\s*\|.*\|\s*)$/,
3883
+ (p) => p.replace(/\|/g, (m) => `<span style="color: ${t.keyword};">${m}</span>`)
3884
+ ), this.restoreHighlightTokens(g, d);
3885
+ }).join(`
3886
+ `);
3887
+ }
3888
+ extractMarkdownFenceLanguage(e) {
3889
+ var i;
3890
+ const t = ((i = e.trim().match(/^([A-Za-z0-9_+.#-]+)/)) == null ? void 0 : i[1]) || "";
3891
+ return t ? this.normalizeLanguageId(t) : "";
3892
+ }
3893
+ highlightMarkdownFenceLine(e, t, i) {
3894
+ const n = t ? this.modes.get(t) : void 0;
3895
+ return !n || n.name === "markdown" ? `<span style="color: ${i.text};">${this.escapeHTML(e)}</span>` : n.highlight(e, i);
3896
+ }
3897
+ _highlightShell(e, t) {
3898
+ const i = this.unescapeEntitiesRepeated(e), n = [], s = this.createTokenStore(n), r = /(#[^\n\r]*)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|(\$\{?[A-Za-z_][\w]*\}?|\$[0-9@#?$*!])/g;
3899
+ let o = 0, l = "", a;
3900
+ for (; a = r.exec(i); ) {
3901
+ o < a.index && (l += this.escapeHTML(i.slice(o, a.index)));
3902
+ const h = a[0], c = h.startsWith("#") ? t.comment : h.startsWith("$") ? t.variable : t.string;
3903
+ l += s(`<span style="color: ${c};">${this.escapeHTML(h)}</span>`), o = r.lastIndex;
3904
+ }
3905
+ return o < i.length && (l += this.escapeHTML(i.slice(o))), l = l.replace(
3906
+ /(^|\s)(--?[A-Za-z0-9][\w-]*)(?=\s|=|$)/g,
3907
+ (h, c, d) => `${c}${s(`<span style="color: ${t.attrName};">${d}</span>`)}`
3908
+ ), l = l.replace(
3909
+ /\b(if|then|else|elif|fi|for|while|until|do|done|case|esac|function|export|unset|alias|source|return|in)\b/g,
3910
+ (h) => s(`<span style="color: ${t.keyword};">${h}</span>`)
3911
+ ), l = l.replace(
3912
+ /(^|\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,
3913
+ (h, c, d) => `${c}${s(`<span style="color: ${t.tag};">${d}</span>`)}`
3914
+ ), this.restoreHighlightTokens(l, n);
3915
+ }
3916
+ getLanguageKeywords(e) {
3917
+ const t = ["true", "false", "null", "nil", "none"];
3918
+ return [...{
3919
+ 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"],
3920
+ 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"],
3921
+ 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"],
3922
+ 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"],
3923
+ 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"],
3924
+ 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"],
3925
+ 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"],
3926
+ 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"],
3927
+ 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"]
3928
+ }[e] || [], ...t];
3929
+ }
3930
+ _highlightGenericCode(e, t, i) {
3931
+ const n = this.unescapeEntitiesRepeated(e), s = [], r = this.createTokenStore(s), o = i === "python" || i === "ruby" || i === "sql" ? "#[^\\n\\r]*|--[^\\n\\r]*" : "\\/\\*[\\s\\S]*?\\*\\/|\\/\\/[^\\n\\r]*", l = new RegExp(
3932
+ `(${o})|("(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`)`,
3933
+ "g"
3934
+ );
3935
+ let a = 0, h = "", c;
3936
+ for (; c = l.exec(n); ) {
3937
+ a < c.index && (h += this.escapeHTML(n.slice(a, c.index)));
3938
+ const f = c[0], u = f.startsWith("//") || f.startsWith("/*") || f.startsWith("#") || f.startsWith("--") ? t.comment : t.string;
3939
+ h += r(`<span style="color: ${u};">${this.escapeHTML(f)}</span>`), a = l.lastIndex;
3940
+ }
3941
+ a < n.length && (h += this.escapeHTML(n.slice(a)));
3942
+ const d = Array.from(new Set(this.getLanguageKeywords(i)));
3943
+ if (d.length > 0) {
3944
+ const f = new RegExp(
3945
+ `\\b(${d.map((u) => u.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})\\b`,
3946
+ i === "sql" ? "gi" : "g"
3947
+ );
3948
+ h = h.replace(
3949
+ f,
3950
+ (u) => r(`<span style="color: ${t.keyword};">${u}</span>`)
3951
+ );
3952
+ }
3953
+ return h = h.replace(
3954
+ /\b([A-Z][A-Za-z0-9_]*|[A-Za-z_][\w]*(?=\s*\())\b/g,
3955
+ (f) => r(`<span style="color: ${t.tag};">${f}</span>`)
3956
+ ), h = h.replace(
3957
+ /\b(-?0x[0-9a-fA-F]+|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)(?:[uUlLfFdD]*)\b/g,
3958
+ (f) => r(`<span style="color: ${t.number};">${f}</span>`)
3959
+ ), h = h.replace(
3960
+ /(@[A-Za-z_][\w]*|#[A-Za-z_][\w]*|::[A-Za-z_][\w]*)/g,
3961
+ (f) => r(`<span style="color: ${t.attrName};">${f}</span>`)
3962
+ ), this.restoreHighlightTokens(h, s);
3963
+ }
3964
+ _highlightYAML(e, t) {
3965
+ const i = this.unescapeEntitiesRepeated(e), n = [], s = this.createTokenStore(n);
3966
+ let r = this.escapeHTML(i).replace(
3967
+ /(#.*)$/gm,
3968
+ (o) => s(`<span style="color: ${t.comment};">${o}</span>`)
3969
+ ).replace(
3970
+ /^(\s*[-?]?\s*)([A-Za-z0-9_.-]+)(\s*:)/gm,
3971
+ (o, l, a, h) => `${l}${s(`<span style="color: ${t.attrName};">${a}</span>`)}${h}`
3972
+ ).replace(
3973
+ /\b(true|false|null|yes|no|on|off)\b/gi,
3974
+ (o) => s(`<span style="color: ${t.keyword};">${o}</span>`)
3975
+ ).replace(
3976
+ /\b(-?\d+(?:\.\d+)?)\b/g,
3977
+ (o) => s(`<span style="color: ${t.number};">${o}</span>`)
3978
+ );
3979
+ return r = r.replace(
3980
+ /(&quot;[^&]*?&quot;|&#39;[^&]*?&#39;)/g,
3981
+ (o) => s(`<span style="color: ${t.string};">${o}</span>`)
3982
+ ), this.restoreHighlightTokens(r, n);
3983
+ }
3984
+ _highlightXML(e, t) {
3985
+ return this._highlightHTML(e, t);
3986
+ }
3987
+ _highlightJSX(e, t) {
3988
+ const i = [], n = e.replace(
3989
+ /<\/?[A-Za-z][\w.:-]*(?:\s+[^<>]*?)?\/?>/g,
3990
+ (s) => {
3991
+ const r = i.length, o = this.escapeHTML(s).replace(
3992
+ /(&lt;\/?)([A-Za-z][\w.:-]*)([\s\S]*?)(\/?&gt;)/,
3993
+ (l, a, h, c, d) => {
3994
+ const f = String(c || "").replace(
3995
+ /([A-Za-z_:][\w:.-]*)(\s*=\s*)/g,
3996
+ `<span style="color: ${t.attrName};">$1</span>$2`
3997
+ );
3998
+ return `${a}<span style="color: ${t.tag};">${h}</span>${f}${d}`;
3999
+ }
4000
+ );
4001
+ return i.push(o), `jsx${r}`;
4002
+ }
4003
+ );
4004
+ return this._highlightJS(n, t).replace(
4005
+ /\u0004jsx(\d+)\u0004/g,
4006
+ (s, r) => i[Number(r)] || ""
4007
+ );
4008
+ }
4009
+ _highlightEJS(e, t) {
4010
+ const i = [], n = e.replace(/<%[\s\S]*?%>/g, (s) => {
4011
+ const r = i.length;
4012
+ return i.push(`<span style="color: ${t.keyword};">${this.escapeHTML(s)}</span>`), `ejs${r}`;
4013
+ });
4014
+ return this._highlightHTML(n, t).replace(
4015
+ /\u0003ejs(\d+)\u0003/g,
4016
+ (s, r) => i[Number(r)] || ""
4017
+ );
4018
+ }
4019
+ _highlightDockerfile(e, t) {
4020
+ return this.unescapeEntitiesRepeated(e).split(`
4021
+ `).map((n) => {
4022
+ const s = this.escapeHTML(n);
4023
+ return /^\s*#/.test(n) ? `<span style="color: ${t.comment};">${s}</span>` : s.replace(
4024
+ /^(\s*)(FROM|RUN|CMD|LABEL|MAINTAINER|EXPOSE|ENV|ADD|COPY|ENTRYPOINT|VOLUME|USER|WORKDIR|ARG|ONBUILD|STOPSIGNAL|HEALTHCHECK|SHELL)(\b)/i,
4025
+ (r, o, l, a) => `${o}<span style="color: ${t.keyword};">${l}</span>${a}`
4026
+ );
4027
+ }).join(`
4028
+ `);
4029
+ }
4030
+ _highlightJS(e, t) {
4031
+ const i = this.unescapeEntitiesRepeated(e);
4032
+ this.escapeHTML(i);
4033
+ const n = [], s = (f) => {
4034
+ let u = "", g = f;
4035
+ do
4036
+ u = String.fromCharCode(97 + g % 26) + u, g = Math.floor(g / 26) - 1;
4037
+ while (g >= 0);
4038
+ return u || "a";
4039
+ }, r = (f) => `\0${s(f)}\0`, o = (f) => {
4040
+ const u = n.length;
4041
+ return n.push(f), r(u);
4042
+ };
4043
+ let l;
4044
+ const a = /(\/\*[\s\S]*?\*\/)|(\/\/[^\n\r]*)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)/g;
4045
+ let h = 0, c = "";
4046
+ for (; l = a.exec(i); ) {
4047
+ const f = l.index;
4048
+ h < f && (c += this.escapeHTML(i.slice(h, f)));
4049
+ const u = l[0];
4050
+ /^\/\*/.test(u) || /^\/\//.test(u) ? c += o(`<span style="color: ${t.comment};">${this.escapeHTML(u)}</span>`) : c += o(`<span style="color: ${t.string};">${this.escapeHTML(u)}</span>`), h = a.lastIndex;
4051
+ }
4052
+ return h < i.length && (c += this.escapeHTML(i.slice(h))), c = c.replace(/\b(0x[0-9a-fA-F]+|\d+\.?\d*|\d*\.\d+)\b/g, (f, u, g) => {
4053
+ const p = c[g - 1] || "", m = c[g + f.length] || "";
4054
+ return p === "&" || p === "#" || m === ";" || m === "#" ? f : `<span style="color: ${t.number};">${f}</span>`;
4055
+ }), 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, (f, u) => {
4056
+ let g = 0;
4057
+ for (let p = 0; p < u.length; p++)
4058
+ g = g * 26 + (u.charCodeAt(p) - 97 + 1);
4059
+ return g = g - 1, n[g] || "";
4060
+ });
4061
+ }
4062
+ _highlightPHP(e, t) {
4063
+ const i = this.unescapeEntitiesRepeated(e);
4064
+ let n = this.escapeHTML(i);
4065
+ const s = [], r = (u) => {
4066
+ let g = "", p = u;
4067
+ do
4068
+ g = String.fromCharCode(97 + p % 26) + g, p = Math.floor(p / 26) - 1;
4069
+ while (p >= 0);
4070
+ return g || "a";
4071
+ }, o = (u) => {
4072
+ const g = s.length;
4073
+ return s.push(u), `\0${r(g)}\0`;
4074
+ }, l = (u, g) => {
4075
+ const p = n.indexOf(u);
4076
+ return p === -1 ? !1 : (n = n.slice(0, p) + g + n.slice(p + u.length), !0);
4077
+ };
4078
+ let a;
4079
+ const h = /\/\*[\s\S]*?\*\//g, c = /\/\/[^\n\r]*/g, d = /\#([^\n\r]*)/g, f = /("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g;
4080
+ for (; a = h.exec(i); ) {
4081
+ const u = a[0];
4082
+ l(this.escapeHTML(u), o(`<span style="color: ${t.comment};">${this.escapeHTML(u)}</span>`));
4083
+ }
4084
+ for (; a = c.exec(i); ) {
4085
+ const u = a[0];
4086
+ l(this.escapeHTML(u), o(`<span style="color: ${t.comment};">${this.escapeHTML(u)}</span>`));
4087
+ }
4088
+ for (; a = d.exec(i); ) {
4089
+ const u = a[0];
4090
+ l(this.escapeHTML(u), o(`<span style="color: ${t.comment};">${this.escapeHTML(u)}</span>`));
4091
+ }
4092
+ for (; a = f.exec(i); ) {
4093
+ const u = a[0];
4094
+ l(this.escapeHTML(u), o(`<span style="color: ${t.string};">${this.escapeHTML(u)}</span>`));
4095
+ }
4096
+ return n = n.replace(
4097
+ /(&lt;\?(?:php\b|=)?|\?&gt;)/gi,
4098
+ (u) => o(`<span style="color: ${t.keyword};">${u}</span>`)
4099
+ ), n = n.replace(/(\$[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)/g, `<span style="color: ${t.variable};">$1</span>`), n = n.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>`), n = n.replace(/\u0000([a-z]+)\u0000/g, (u, g) => {
4100
+ let p = 0;
4101
+ for (let m = 0; m < g.length; m++)
4102
+ p = p * 26 + (g.charCodeAt(m) - 97 + 1);
4103
+ return p = p - 1, s[p] || "";
4104
+ }), n;
4105
+ }
4106
+ // Method to check if content contains syntax that should be highlighted
4107
+ shouldHighlight(e) {
4108
+ return /<\/?[\w:-]+|<!--/.test(e);
4109
+ }
4110
+ destroy() {
4111
+ this.editor = null, this.modes.clear();
4112
+ }
4113
+ }
4114
+ function de(T, e) {
4115
+ const t = { ...e };
4116
+ return t.extensions || (t.extensions = []), t.extensions.some((s) => s.name === "keymap") || t.extensions.unshift(new ie(t.keymap)), t.extensions.some((s) => s.name === "transaction") || t.extensions.unshift(new U()), new V(T, t);
4117
+ }
4118
+ const z = '[data-theme="dark"], .dark, .editora-theme-dark', ue = `/* Source Editor Dialog Styles */
4119
+ .rte-source-editor-overlay {
4120
+ position: fixed !important;
4121
+ top: 0 !important;
4122
+ left: 0 !important;
4123
+ right: 0 !important;
4124
+ bottom: 0 !important;
4125
+ width: 100vw !important;
4126
+ height: 100vh !important;
4127
+ background-color: rgba(0, 0, 0, 0.6) !important;
4128
+ display: flex !important;
4129
+ align-items: center !important;
4130
+ justify-content: center !important;
4131
+ z-index: 10000 !important;
4132
+ padding: 20px !important;
4133
+ box-sizing: border-box !important;
4134
+ margin: 0 !important;
4135
+ }
4136
+
4137
+ .rte-source-editor-overlay.fullscreen {
4138
+ padding: 0 !important;
4139
+ }
4140
+
4141
+ .rte-source-editor-modal {
4142
+ background: white;
4143
+ border-radius: 8px;
4144
+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
4145
+ width: 100%;
4146
+ max-width: 1200px;
4147
+ max-height: 90vh;
4148
+ display: flex;
4149
+ flex-direction: column;
4150
+ overflow: hidden;
4151
+ position: relative;
4152
+ }
4153
+
4154
+ .rte-source-editor-overlay.fullscreen .rte-source-editor-modal {
4155
+ border-radius: 0;
4156
+ max-width: 100%;
4157
+ max-height: 100vh;
4158
+ width: 100%;
4159
+ height: 100vh;
4160
+ }
4161
+
4162
+ .rte-source-editor-header {
4163
+ display: flex;
4164
+ align-items: center;
4165
+ justify-content: space-between;
4166
+ padding: 16px 20px;
4167
+ border-bottom: 1px solid #e1e5e9;
4168
+ background: #f8f9fa;
4169
+ border-radius: 8px 8px 0 0;
4170
+ }
4171
+
4172
+ .rte-source-editor-overlay.fullscreen .rte-source-editor-header {
4173
+ border-radius: 0;
4174
+ }
4175
+
4176
+ .rte-source-editor-header h2 {
4177
+ margin: 0;
4178
+ font-size: 18px;
4179
+ font-weight: 600;
4180
+ color: #1a1a1a;
4181
+ }
4182
+
4183
+ .rte-source-editor-header-toolbar {
4184
+ display: flex;
4185
+ gap: 8px;
4186
+ margin-left: auto;
4187
+ margin-right: 16px;
4188
+ }
4189
+
4190
+ .rte-source-editor-toolbar-btn {
4191
+ background: none;
4192
+ border: none;
4193
+ cursor: pointer;
4194
+ padding: 6px;
4195
+ border-radius: 4px;
4196
+ font-size: 16px;
4197
+ line-height: 1;
4198
+ transition: all 0.2s ease;
4199
+ color: #666;
4200
+ }
4201
+
4202
+ .rte-source-editor-toolbar-btn:hover:not(:disabled) {
4203
+ background: #e1e5e9;
4204
+ color: #1a1a1a;
4205
+ }
4206
+
4207
+ .rte-source-editor-toolbar-btn:disabled {
4208
+ opacity: 0.5;
4209
+ cursor: not-allowed;
4210
+ }
4211
+
4212
+ .rte-source-editor-toolbar-btn.active {
4213
+ background: #007acc;
4214
+ color: white;
4215
+ }
4216
+
4217
+ .rte-source-editor-toolbar-btn.active:hover {
4218
+ background: #0056b3;
4219
+ }
4220
+
4221
+ .rte-source-editor-header-actions {
4222
+ display: flex;
4223
+ gap: 8px;
4224
+ }
4225
+
4226
+ .rte-source-editor-fullscreen-btn,
4227
+ .rte-source-editor-close-btn {
4228
+ background: none;
4229
+ border: none;
4230
+ cursor: pointer;
4231
+ padding: 4px;
4232
+ border-radius: 4px;
4233
+ color: #666;
4234
+ font-size: 16px;
4235
+ line-height: 1;
4236
+ transition: all 0.2s ease;
4237
+ }
4238
+
4239
+ .rte-source-editor-fullscreen-btn:hover,
4240
+ .rte-source-editor-close-btn:hover {
4241
+ background: #e1e5e9;
4242
+ color: #1a1a1a;
4243
+ }
4244
+
4245
+ .rte-source-editor-body {
4246
+ flex: 1;
4247
+ overflow: hidden;
4248
+ display: flex;
4249
+ flex-direction: column;
4250
+ }
4251
+
4252
+ .rte-source-editor-loading {
4253
+ display: flex;
4254
+ flex-direction: column;
4255
+ align-items: center;
4256
+ justify-content: center;
4257
+ padding: 40px;
4258
+ color: #666;
4259
+ position: absolute;
4260
+ z-index: 9;
4261
+ margin: 0 auto;
4262
+ width: 100%;
4263
+ top: 44%;
4264
+ }
4265
+
4266
+ .rte-source-editor-spinner {
4267
+ width: 32px;
4268
+ height: 32px;
4269
+ border: 3px solid #e1e5e9;
4270
+ border-top: 3px solid #007acc;
4271
+ border-radius: 50%;
4272
+ animation: spin 1s linear infinite;
4273
+ margin-bottom: 16px;
4274
+ }
4275
+
4276
+ @keyframes spin {
4277
+ 0% { transform: rotate(0deg); }
4278
+ 100% { transform: rotate(360deg); }
4279
+ }
4280
+
4281
+ .rte-source-editor-error {
4282
+ background: #fee;
4283
+ color: #c53030;
4284
+ padding: 12px 16px;
4285
+ border-left: 4px solid #c53030;
4286
+ margin: 16px;
4287
+ border-radius: 4px;
4288
+ font-size: 14px;
4289
+ }
4290
+
4291
+ .rte-source-editor-content {
4292
+ flex: 1;
4293
+ display: flex;
4294
+ flex-direction: column;
4295
+ overflow: hidden;
4296
+ }
4297
+
4298
+ .rte-source-editor-warning {
4299
+ background: #fefcbf;
4300
+ color: #744210;
4301
+ padding: 8px 16px;
4302
+ font-size: 12px;
4303
+ font-weight: 500;
4304
+ border-bottom: 1px solid #f6e05e;
4305
+ }
4306
+
4307
+ .rte-source-editor-codemirror {
4308
+ flex: 1;
4309
+ overflow: auto;
4310
+ font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
4311
+ font-size: 14px;
4312
+ line-height: 1.5;
4313
+ }
4314
+
4315
+ .rte-source-editor-codemirror .cm-editor {
4316
+ height: 100%;
4317
+ }
4318
+
4319
+ .rte-source-editor-codemirror .cm-focused {
4320
+ outline: none;
4321
+ }
4322
+
4323
+ .rte-source-editor-footer {
4324
+ display: flex;
4325
+ align-items: center;
4326
+ justify-content: space-between;
4327
+ padding: 16px 20px;
4328
+ border-top: 1px solid #e1e5e9;
4329
+ background: #f8f9fa;
4330
+ border-radius: 0 0 8px 8px;
4331
+ }
4332
+
4333
+ .rte-source-editor-overlay.fullscreen .rte-source-editor-footer {
4334
+ border-radius: 0;
4335
+ }
4336
+
4337
+ .rte-source-editor-footer-info {
4338
+ font-size: 12px;
4339
+ color: #666;
4340
+ }
4341
+
4342
+ .unsaved-changes {
4343
+ color: #d69e2e;
4344
+ font-weight: 500;
4345
+ }
4346
+
4347
+ .rte-source-editor-footer-actions {
4348
+ display: flex;
4349
+ gap: 12px;
4350
+ }
4351
+
4352
+ .rte-source-editor-btn {
4353
+ padding: 8px 16px;
4354
+ border-radius: 4px;
4355
+ font-size: 14px;
4356
+ font-weight: 500;
4357
+ cursor: pointer;
4358
+ border: 1px solid transparent;
4359
+ transition: all 0.2s ease;
4360
+ }
4361
+
4362
+ .rte-source-editor-btn:disabled {
4363
+ opacity: 0.6;
4364
+ cursor: not-allowed;
4365
+ }
4366
+
4367
+ .rte-source-editor-btn-cancel {
4368
+ background: white;
4369
+ border-color: #d1d5db;
4370
+ color: #374151;
4371
+ }
4372
+
4373
+ .rte-source-editor-btn-cancel:hover:not(:disabled) {
4374
+ background: #f9fafb;
4375
+ border-color: #9ca3af;
4376
+ }
4377
+
4378
+ .rte-source-editor-btn-save {
4379
+ background: #007acc;
4380
+ color: white;
4381
+ }
4382
+
4383
+ .rte-source-editor-btn-save:hover:not(:disabled) {
4384
+ background: #0056b3;
4385
+ }
4386
+
4387
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-modal {
4388
+ background: #1e1e1e;
4389
+ color: #f8f9fa;
4390
+ border: 1px solid #434d5f;
4391
+ }
4392
+
4393
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-header,
4394
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-footer {
4395
+ background: #2a3442;
4396
+ border-color: #434d5f;
4397
+ }
4398
+
4399
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-header h2 {
4400
+ color: #f8f9fa;
4401
+ }
4402
+
4403
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-toolbar-btn,
4404
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-fullscreen-btn,
4405
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-close-btn {
4406
+ color: #c1cede;
4407
+ }
4408
+
4409
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-toolbar-btn:hover:not(:disabled),
4410
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-fullscreen-btn:hover,
4411
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-close-btn:hover {
4412
+ background: #404a5a;
4413
+ color: #f8fafc;
4414
+ }
4415
+
4416
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-toolbar-btn.active {
4417
+ background: #3b82f6;
4418
+ color: #ffffff;
4419
+ }
4420
+
4421
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-toolbar-btn.active:hover {
4422
+ background: #2563eb;
4423
+ }
4424
+
4425
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-loading,
4426
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-footer-info {
4427
+ color: #cbd5e1;
4428
+ }
4429
+
4430
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-spinner {
4431
+ border-color: #3f4b60;
4432
+ border-top-color: #58a6ff;
4433
+ }
4434
+
4435
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-error {
4436
+ background: #3f2124;
4437
+ color: #fecaca;
4438
+ border-color: #ef4444;
4439
+ }
4440
+
4441
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-warning {
4442
+ background: #3b3220;
4443
+ color: #fde68a;
4444
+ border-color: #f59e0b;
4445
+ }
4446
+
4447
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-btn-cancel {
4448
+ background: #334155;
4449
+ border-color: #475569;
4450
+ color: #f1f5f9;
4451
+ }
4452
+
4453
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-btn-cancel:hover:not(:disabled) {
4454
+ background: #475569;
4455
+ border-color: #64748b;
4456
+ }
4457
+
4458
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-btn-save {
4459
+ background: #3b82f6;
4460
+ }
4461
+
4462
+ .rte-source-editor-overlay.rte-theme-dark .rte-source-editor-btn-save:hover:not(:disabled) {
4463
+ background: #2563eb;
4464
+ }
4465
+
4466
+ /* Responsive design */
4467
+ @media (max-width: 768px) {
4468
+ .rte-source-editor-overlay {
4469
+ padding: 10px;
4470
+ }
4471
+
4472
+ .rte-source-editor-modal {
4473
+ max-height: 95vh;
4474
+ }
4475
+
4476
+ .rte-source-editor-header {
4477
+ padding: 12px 16px;
4478
+ }
4479
+
4480
+ .rte-source-editor-footer {
4481
+ padding: 12px 16px;
4482
+ flex-direction: column;
4483
+ gap: 12px;
4484
+ align-items: stretch;
4485
+ }
4486
+
4487
+ .rte-source-editor-footer-actions {
4488
+ justify-content: stretch;
4489
+ }
4490
+
4491
+ .rte-source-editor-btn {
4492
+ flex: 1;
4493
+ text-align: center;
4494
+ }
4495
+ }`, ge = () => ({
4496
+ name: "code",
4497
+ // Toolbar button configuration
4498
+ toolbar: [
4499
+ {
4500
+ label: "Source",
4501
+ command: "toggleSourceView",
4502
+ // type: "button",
4503
+ 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>',
4504
+ shortcut: "Mod-Shift-S"
4505
+ }
4506
+ ],
4507
+ // Native command implementations
4508
+ commands: {
4509
+ /**
4510
+ * Toggle HTML source view
4511
+ * Opens a dialog to edit raw HTML
4512
+ */
4513
+ toggleSourceView: () => {
4514
+ const e = (() => {
4515
+ var o, l, a;
4516
+ const s = window.getSelection();
4517
+ if (s && s.anchorNode) {
4518
+ let h = s.anchorNode instanceof HTMLElement ? s.anchorNode : s.anchorNode.parentElement;
4519
+ for (; h; ) {
4520
+ if ((o = h.classList) != null && o.contains("rte-content"))
4521
+ return h;
4522
+ h = h.parentElement;
4523
+ }
4524
+ }
4525
+ if (document.activeElement) {
4526
+ let h = document.activeElement;
4527
+ if ((l = h.classList) != null && l.contains("rte-content"))
4528
+ return h;
4529
+ for (; h && h !== document.body; ) {
4530
+ if ((a = h.classList) != null && a.contains("rte-content"))
4531
+ return h;
4532
+ const c = h.querySelector(
4533
+ ".rte-content"
4534
+ );
4535
+ if (c) return c;
4536
+ h = h.parentElement;
4537
+ }
4538
+ }
4539
+ const r = document.querySelector("[data-editora-editor]");
4540
+ if (r) {
4541
+ const h = r.querySelector(
4542
+ ".rte-content"
4543
+ );
4544
+ if (h) return h;
4545
+ }
4546
+ return document.querySelector(".rte-content");
4547
+ })();
4548
+ if (!e)
4549
+ return console.error("[CodePlugin] Editor content area not found"), alert(
4550
+ "Editor content area not found. Please click inside the editor first."
4551
+ ), !1;
4552
+ const t = e.innerHTML, i = (s) => {
4553
+ let r = "", o = 0;
4554
+ const l = 2, a = s.split(/(<\/?[a-zA-Z][^>]*>)/);
4555
+ for (const h of a)
4556
+ h.trim() && (h.match(/^<\/[a-zA-Z]/) ? (o = Math.max(0, o - 1), r += `
4557
+ ` + " ".repeat(o * l) + h) : h.match(/^<[a-zA-Z]/) && !h.match(/\/>$/) ? (r += `
4558
+ ` + " ".repeat(o * l) + h, o++) : h.match(/^<[a-zA-Z].*\/>$/) ? r += `
4559
+ ` + " ".repeat(o * l) + h : r += h.trim());
4560
+ return r.trim();
4561
+ };
4562
+ return (() => {
4563
+ document.querySelectorAll(".rte-source-editor-overlay").forEach((b) => b.remove());
4564
+ const r = i(t);
4565
+ let o = null, l = "dark", a = !1, h = !1, c = !1, d = !1;
4566
+ const f = !!e.closest(z) || document.body.matches(z) || document.documentElement.matches(z), u = document.createElement("div");
4567
+ J(u), u.className = "rte-source-editor-overlay", f && u.classList.add("rte-theme-dark");
4568
+ const g = document.createElement("div");
4569
+ g.className = "rte-source-editor-modal", g.setAttribute("role", "dialog"), g.setAttribute("aria-modal", "true"), g.setAttribute("aria-labelledby", "source-editor-title");
4570
+ const p = document.createElement("div");
4571
+ p.className = "rte-source-editor-header", p.innerHTML = `
4572
+ <h2 id="source-editor-title">Source Editor</h2>
4573
+ <div class="rte-source-editor-header-toolbar">
4574
+ <button class="rte-source-editor-toolbar-btn theme-toggle-btn" title="Switch theme">
4575
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
4576
+ <circle cx="12" cy="12" r="5"/>
4577
+ <line x1="12" y1="1" x2="12" y2="3"/>
4578
+ <line x1="12" y1="21" x2="12" y2="23"/>
4579
+ <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/>
4580
+ <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/>
4581
+ <line x1="1" y1="12" x2="3" y2="12"/>
4582
+ <line x1="21" y1="12" x2="23" y2="12"/>
4583
+ <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/>
4584
+ <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
4585
+ </svg>
4586
+ </button>
4587
+ <button class="rte-source-editor-toolbar-btn readonly-toggle-btn" title="Toggle read-only">
4588
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
4589
+ <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
4590
+ <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
4591
+ </svg>
4592
+ </button>
4593
+ </div>
4594
+ <div class="rte-source-editor-header-actions">
4595
+ <button class="rte-source-editor-fullscreen-btn" title="Toggle fullscreen">
4596
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
4597
+ <path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/>
4598
+ </svg>
4599
+ </button>
4600
+ <button class="rte-source-editor-close-btn" aria-label="Close source editor">
4601
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
4602
+ <line x1="18" y1="6" x2="6" y2="18"/>
4603
+ <line x1="6" y1="6" x2="18" y2="18"/>
4604
+ </svg>
4605
+ </button>
4606
+ </div>
4607
+ `;
4608
+ const m = document.createElement("div");
4609
+ m.className = "rte-source-editor-body";
4610
+ const y = document.createElement("div");
4611
+ y.className = "rte-source-editor-content";
4612
+ const v = document.createElement("div");
4613
+ v.className = "rte-source-editor-warning", v.textContent = "⚠️ Advanced users only. Invalid HTML may break the editor.";
4614
+ const S = document.createElement("div");
4615
+ S.className = "rte-source-editor-light-editor", S.style.height = "400px", y.appendChild(v), y.appendChild(S), m.appendChild(y);
4616
+ const w = document.createElement("div");
4617
+ if (w.className = "rte-source-editor-footer", w.innerHTML = `
4618
+ <div class="rte-source-editor-footer-info">
4619
+ <span class="unsaved-changes" style="display: none;">• Unsaved changes</span>
4620
+ </div>
4621
+ <div class="rte-source-editor-footer-actions">
4622
+ <button class="rte-source-editor-btn rte-source-editor-btn-cancel">Cancel</button>
4623
+ <button class="rte-source-editor-btn rte-source-editor-btn-save">Save</button>
4624
+ </div>
4625
+ `, g.appendChild(p), g.appendChild(m), g.appendChild(w), u.appendChild(g), !document.getElementById("rte-source-editor-styles")) {
4626
+ const b = document.createElement("style");
4627
+ b.id = "rte-source-editor-styles", b.textContent = ue, document.head.appendChild(b);
4628
+ }
4629
+ const M = p.querySelector(
4630
+ ".theme-toggle-btn"
4631
+ ), O = p.querySelector(
4632
+ ".readonly-toggle-btn"
4633
+ ), $ = p.querySelector(
4634
+ ".rte-source-editor-fullscreen-btn"
4635
+ ), I = p.querySelector(
4636
+ ".rte-source-editor-close-btn"
4637
+ ), E = w.querySelector(
4638
+ ".rte-source-editor-btn-cancel"
4639
+ ), R = w.querySelector(
4640
+ ".rte-source-editor-btn-save"
4641
+ ), N = w.querySelector(
4642
+ ".unsaved-changes"
4643
+ ), F = [], k = (b, L, B, D) => {
4644
+ b.addEventListener(L, B, D), F.push(
4645
+ () => b.removeEventListener(L, B, D)
4646
+ );
4647
+ }, P = (b) => {
4648
+ c !== b && (c = b, N && (N.style.display = c ? "inline" : "none"));
4649
+ }, H = () => {
4650
+ if (!d) {
4651
+ for (d = !0; F.length; ) {
4652
+ const b = F.pop();
4653
+ b == null || b();
4654
+ }
4655
+ o && (o.destroy(), o = null), u.isConnected && u.remove();
4656
+ }
4657
+ }, j = () => {
4658
+ l = l === "dark" ? "light" : "dark", o == null || o.setTheme(l), M && (M.innerHTML = l === "light" ? `
4659
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
4660
+ <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
4661
+ </svg>
4662
+ ` : `
4663
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
4664
+ <circle cx="12" cy="12" r="5"/>
4665
+ <line x1="12" y1="1" x2="12" y2="3"/>
4666
+ <line x1="12" y1="21" x2="12" y2="23"/>
4667
+ <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/>
4668
+ <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/>
4669
+ <line x1="1" y1="12" x2="3" y2="12"/>
4670
+ <line x1="21" y1="12" x2="23" y2="12"/>
4671
+ <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/>
4672
+ <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
4673
+ </svg>
4674
+ `);
4675
+ }, q = () => {
4676
+ a = !a, o == null || o.setReadOnly(a), O && (O.classList.toggle("active", a), O.innerHTML = a ? `
4677
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
4678
+ <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
4679
+ <circle cx="12" cy="16" r="1"/>
4680
+ <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
4681
+ </svg>
4682
+ ` : `
4683
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
4684
+ <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
4685
+ <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
4686
+ </svg>
4687
+ `);
4688
+ }, G = () => {
4689
+ h = !h, u.classList.toggle("fullscreen", h), S.style.height = h ? "calc(100vh - 200px)" : "400px", $ && ($.innerHTML = h ? `
4690
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
4691
+ <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"/>
4692
+ </svg>
4693
+ ` : `
4694
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
4695
+ <path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/>
4696
+ </svg>
4697
+ `);
4698
+ }, Z = () => {
4699
+ c && !confirm("You have unsaved changes. Are you sure you want to cancel?") || H();
4700
+ }, Q = () => {
4701
+ try {
4702
+ const b = (o == null ? void 0 : o.getValue()) || "", L = document.createElement("div");
4703
+ L.innerHTML = b, L.querySelectorAll(
4704
+ 'script, iframe[src^="javascript:"], object, embed'
4705
+ ).forEach((D) => D.remove()), e.innerHTML = L.innerHTML;
4706
+ try {
4707
+ e.dispatchEvent(
4708
+ new InputEvent("input", {
4709
+ bubbles: !0,
4710
+ cancelable: !1,
4711
+ inputType: "insertReplacementText"
4712
+ })
4713
+ );
4714
+ } catch (D) {
4715
+ e.dispatchEvent(
4716
+ new Event("input", { bubbles: !0 })
4717
+ );
4718
+ }
4719
+ e.dispatchEvent(
4720
+ new Event("change", { bubbles: !0 })
4721
+ ), P(!1), H();
4722
+ } catch (b) {
4723
+ alert("Failed to update HTML. Please check your syntax."), console.error("HTML update error:", b);
4724
+ }
4725
+ };
4726
+ M && k(M, "click", j), O && k(O, "click", q), $ && k($, "click", G), I && k(I, "click", H), E && k(E, "click", Z), R && k(R, "click", Q), k(u, "click", (b) => {
4727
+ b.target === u && H();
4728
+ }), k(document, "keydown", (b) => {
4729
+ const L = b;
4730
+ L.key === "Escape" && (L.preventDefault(), H());
4731
+ }), document.body.appendChild(u), requestAnimationFrame(() => {
4732
+ if (!(d || !u.isConnected))
4733
+ try {
4734
+ o = de(S, {
4735
+ value: r,
4736
+ theme: "dark",
4737
+ readOnly: !1,
4738
+ extensions: [
4739
+ new ne(),
4740
+ new se(),
4741
+ new re(),
4742
+ new ae(),
4743
+ new W(),
4744
+ new he(),
4745
+ new ce()
4746
+ ]
4747
+ }), o.on("change", () => {
4748
+ const b = (o == null ? void 0 : o.getValue()) || "";
4749
+ P(b !== r);
4750
+ }), requestAnimationFrame(() => o == null ? void 0 : o.focus());
4751
+ } catch (b) {
4752
+ console.error("Failed to initialize code editor:", b);
4753
+ }
4754
+ });
4755
+ })(), !0;
4756
+ }
4757
+ },
4758
+ // Keyboard shortcuts
4759
+ keymap: {
4760
+ "Mod-Shift-s": "toggleSourceView",
4761
+ "Mod-Shift-S": "toggleSourceView"
4762
+ }
4763
+ });
4764
+ export {
4765
+ ge as CodePlugin
4766
+ };
4767
+ //# sourceMappingURL=CodePlugin.native-hNgfXlfS.mjs.map