stream-monaco 0.0.1

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.
package/dist/index.cjs ADDED
@@ -0,0 +1,2079 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all) __defProp(target, name, {
10
+ get: all[name],
11
+ enumerable: true
12
+ });
13
+ };
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
16
+ key = keys[i];
17
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
18
+ get: ((k) => from[k]).bind(null, key),
19
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
20
+ });
21
+ }
22
+ return to;
23
+ };
24
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
25
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
26
+ value: mod,
27
+ enumerable: true
28
+ }) : target, mod));
29
+
30
+ //#endregion
31
+ const monaco_editor = __toESM(require("monaco-editor"));
32
+ const alien_signals = __toESM(require("alien-signals"));
33
+ const __shikijs_monaco = __toESM(require("@shikijs/monaco"));
34
+ const shiki = __toESM(require("shiki"));
35
+
36
+ //#region src/code.detect.ts
37
+ /**
38
+ * Language detection definitions
39
+ */
40
+ const languages = [
41
+ [
42
+ "bash",
43
+ [/#!(\/usr)?\/bin\/bash/g, 500],
44
+ [/\b(if|elif|then|fi|echo)\b|\$/g, 10]
45
+ ],
46
+ [
47
+ "html",
48
+ [/<\/?[a-z-][^\n>]*>/g, 10],
49
+ [/^\s+<!DOCTYPE\s+html/g, 500]
50
+ ],
51
+ ["http", [/^(GET|HEAD|POST|PUT|DELETE|PATCH|HTTP)\b/g, 500]],
52
+ ["js", [/\b(console|await|async|function|export|import|this|class|for|let|const|map|join|require)\b/g, 10]],
53
+ ["ts", [/\b(console|await|async|function|export|import|this|class|for|let|const|map|join|require|implements|interface|namespace)\b/g, 10]],
54
+ ["py", [/\b(def|print|class|and|or|lambda)\b/g, 10]],
55
+ ["sql", [/\b(SELECT|INSERT|FROM)\b/g, 50]],
56
+ [
57
+ "pl",
58
+ [/#!(\/usr)?\/bin\/perl/g, 500],
59
+ [/\b(use|print)\b|\$/g, 10]
60
+ ],
61
+ ["lua", [/#!(\/usr)?\/bin\/lua/g, 500]],
62
+ ["make", [/\b(ifneq|endif|if|elif|then|fi|echo|.PHONY|^[a-z]+ ?:$)\b|\$/gm, 10]],
63
+ ["uri", [/https?:|mailto:|tel:|ftp:/g, 30]],
64
+ ["css", [/^(@import|@page|@media|(\.|#)[a-z]+)/gm, 20]],
65
+ [
66
+ "diff",
67
+ [/^[+><-]/gm, 10],
68
+ [/^@@[-+,0-9 ]+@@/gm, 25]
69
+ ],
70
+ [
71
+ "md",
72
+ [/^(>|\t\*|\t\d+.|#{1,6} |-\s+|\*\s+)/gm, 25],
73
+ [/\[.*\](.*)/g, 10]
74
+ ],
75
+ ["docker", [/^(FROM|ENTRYPOINT|RUN)/gm, 500]],
76
+ [
77
+ "xml",
78
+ [/<\/?[a-z-][^\n>]*>/g, 10],
79
+ [/^<\?xml/g, 500]
80
+ ],
81
+ ["c", [/#include\b|\bprintf\s+\(/g, 100]],
82
+ ["rs", [/^\s+(use|fn|mut|match)\b/gm, 100]],
83
+ ["go", [/\b(func|fmt|package)\b/g, 100]],
84
+ ["java", [/^import\s+java/gm, 500]],
85
+ ["asm", [/^(section|global main|extern|\t(call|mov|ret))/gm, 100]],
86
+ ["css", [/^(@import|@page|@media|(\.|#)[a-z]+)/gm, 20]],
87
+ ["json", [/\b(true|false|null|\{\})\b|"[^"]+":/g, 10]],
88
+ ["yaml", [/^(\s+)?[a-z][a-z0-9]*:/gim, 10]],
89
+ [
90
+ "toml",
91
+ [/^\s*\[.*\]\s*$/gm, 100],
92
+ [/^\s*[\w-]+ *= */gm, 20]
93
+ ],
94
+ [
95
+ "mermaid",
96
+ [/^(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|mindmap)/gm, 500],
97
+ [/\b(-->|--o|--x|=>|\[\]|[{}])\b/g, 10]
98
+ ]
99
+ ];
100
+ /**
101
+ * Try to find the language the given code belongs to
102
+ *
103
+ * @param {string} code The code to analyze
104
+ * @param {LanguageDefinition[]} [additionalLanguages] Additional language definitions to supplement the built-in ones
105
+ * @returns {CodeLanguage} The detected language of the code
106
+ */
107
+ function detectLanguage(code, additionalLanguages) {
108
+ var _allLanguages$map$fil;
109
+ const allLanguages = additionalLanguages ? [...languages, ...additionalLanguages] : languages;
110
+ return ((_allLanguages$map$fil = allLanguages.map(([lang, ...features]) => [lang, features.reduce((acc, [match, score]) => acc + [...code.matchAll(match)].length * score, 0)]).filter(([, score]) => score > 20).sort((a, b) => b[1] - a[1])[0]) === null || _allLanguages$map$fil === void 0 ? void 0 : _allLanguages$map$fil[0]) || "plain";
111
+ }
112
+ function processedLanguage(language) {
113
+ if (/^(?:shellscript|bash|sh|shell|zsh)/i.test(language)) return "shell";
114
+ if (/^(?:powershell|ps1?)/i.test(language)) return "powershell";
115
+ return language.split(":")[0];
116
+ }
117
+ /**
118
+ * 使用示例:
119
+ *
120
+ * // 基本用法
121
+ * const language1 = detectLanguage('console.log("hello")') // 'js'
122
+ *
123
+ * // 使用自定义语言检测规则
124
+ * const customLanguages: LanguageDefinition[] = [
125
+ * ['vue', [/<template>/g, 100], [/<script>/g, 50], [/<style>/g, 50]],
126
+ * ['kotlin', [/\b(fun|class|val|var)\b/g, 20]]
127
+ * ]
128
+ *
129
+ * const language2 = detectLanguage(`
130
+ * <template>
131
+ * <div>Hello Vue</div>
132
+ * </template>
133
+ * `, customLanguages) // 'vue'
134
+ *
135
+ * const language3 = detectLanguage(`
136
+ * fun main() {
137
+ * val name = "Kotlin"
138
+ * println("Hello $name")
139
+ * }
140
+ * `, customLanguages) // 'kotlin'
141
+ */
142
+
143
+ //#endregion
144
+ //#region src/constant.ts
145
+ const defaultLanguages = [
146
+ "jsx",
147
+ "tsx",
148
+ "vue",
149
+ "csharp",
150
+ "python",
151
+ "java",
152
+ "c",
153
+ "cpp",
154
+ "rust",
155
+ "go",
156
+ "powershell",
157
+ "sql",
158
+ "json",
159
+ "html",
160
+ "javascript",
161
+ "typescript",
162
+ "css",
163
+ "markdown",
164
+ "xml",
165
+ "yaml",
166
+ "toml",
167
+ "dockerfile",
168
+ "kotlin",
169
+ "objective-c",
170
+ "objective-cpp",
171
+ "php",
172
+ "ruby",
173
+ "scala",
174
+ "svelte",
175
+ "swift",
176
+ "erlang",
177
+ "angular-html",
178
+ "angular-ts",
179
+ "dart",
180
+ "lua",
181
+ "mermaid",
182
+ "cmake",
183
+ "nginx"
184
+ ];
185
+ const defaultThemes = ["vitesse-dark", "vitesse-light"];
186
+ const defaultScrollbar = {
187
+ verticalScrollbarSize: 8,
188
+ horizontalScrollbarSize: 8,
189
+ handleMouseWheel: true,
190
+ alwaysConsumeMouseWheel: false
191
+ };
192
+ const padding = 16;
193
+ const defaultRevealDebounceMs = 75;
194
+ const defaultRevealBatchOnIdleMs = 200;
195
+ const minimalEditMaxChars = 2e5;
196
+ const minimalEditMaxChangeRatio = .5;
197
+
198
+ //#endregion
199
+ //#region src/minimalEdit.ts
200
+ /**
201
+ * Compute the minimal middle replacement between two UTF-16 strings.
202
+ * Returns null when prev === next (no edits required).
203
+ */
204
+ function computeMinimalEdit(prev, next) {
205
+ if (prev === next) return null;
206
+ let start = 0;
207
+ const minLen = Math.min(prev.length, next.length);
208
+ while (start < minLen && prev.charCodeAt(start) === next.charCodeAt(start)) start++;
209
+ let endPrev = prev.length - 1;
210
+ let endNext = next.length - 1;
211
+ while (endPrev >= start && endNext >= start && prev.charCodeAt(endPrev) === next.charCodeAt(endNext)) {
212
+ endPrev--;
213
+ endNext--;
214
+ }
215
+ return {
216
+ start,
217
+ endPrevIncl: endPrev,
218
+ endNextIncl: endNext,
219
+ replaceText: next.slice(start, endNext + 1)
220
+ };
221
+ }
222
+
223
+ //#endregion
224
+ //#region src/monaco-shim.ts
225
+ var monaco_shim_exports = {};
226
+ __export(monaco_shim_exports, { default: () => monaco });
227
+ __reExport(monaco_shim_exports, require("monaco-editor"));
228
+ const monaco = monaco_editor;
229
+
230
+ //#endregion
231
+ //#region src/utils/height.ts
232
+ function createHeightManager(container, computeNext) {
233
+ let raf = null;
234
+ let lastApplied = -1;
235
+ let suppressed = false;
236
+ function apply() {
237
+ const next = computeNext();
238
+ if (next === lastApplied) return;
239
+ suppressed = true;
240
+ container.style.height = `${next}px`;
241
+ lastApplied = next;
242
+ queueMicrotask(() => {
243
+ suppressed = false;
244
+ });
245
+ }
246
+ function update() {
247
+ if (raf != null) return;
248
+ raf = requestAnimationFrame(() => {
249
+ raf = null;
250
+ apply();
251
+ });
252
+ }
253
+ function dispose() {
254
+ if (raf != null) {
255
+ cancelAnimationFrame(raf);
256
+ raf = null;
257
+ }
258
+ }
259
+ function isSuppressed() {
260
+ return suppressed;
261
+ }
262
+ function getLastApplied() {
263
+ return lastApplied;
264
+ }
265
+ return {
266
+ update,
267
+ dispose,
268
+ isSuppressed,
269
+ getLastApplied
270
+ };
271
+ }
272
+
273
+ //#endregion
274
+ //#region src/utils/raf.ts
275
+ /**
276
+ * Create a per-instance RAF scheduler that coalesces tasks by "kind" within
277
+ * the same instance. Instances are isolated so different editors won't
278
+ * cancel each other's scheduled work.
279
+ */
280
+ function createRafScheduler(timeSource) {
281
+ const ids = {};
282
+ const ts = timeSource ?? {
283
+ requestAnimationFrame: (cb) => requestAnimationFrame(cb),
284
+ cancelAnimationFrame: (id) => cancelAnimationFrame(id)
285
+ };
286
+ function schedule(kind, cb) {
287
+ const existing = ids[kind];
288
+ if (existing != null) ts.cancelAnimationFrame(existing);
289
+ ids[kind] = ts.requestAnimationFrame((t) => {
290
+ ids[kind] = null;
291
+ cb(t);
292
+ });
293
+ }
294
+ function cancel(kind) {
295
+ const id = ids[kind];
296
+ if (id != null) {
297
+ ts.cancelAnimationFrame(id);
298
+ ids[kind] = null;
299
+ }
300
+ }
301
+ return {
302
+ schedule,
303
+ cancel
304
+ };
305
+ }
306
+
307
+ //#endregion
308
+ //#region src/utils/scroll.ts
309
+ function createScrollWatcherForEditor(ed, opts) {
310
+ var _ed$getScrollTop, _ed$onDidScrollChange;
311
+ const initial = ((_ed$getScrollTop = ed.getScrollTop) === null || _ed$getScrollTop === void 0 ? void 0 : _ed$getScrollTop.call(ed)) ?? 0;
312
+ opts.setLast(initial);
313
+ const disp = ((_ed$onDidScrollChange = ed.onDidScrollChange) === null || _ed$onDidScrollChange === void 0 ? void 0 : _ed$onDidScrollChange.call(ed, (e) => {
314
+ var _ed$getScrollTop2;
315
+ const currentTop = e && typeof e.scrollTop === "number" ? e.scrollTop : ((_ed$getScrollTop2 = ed.getScrollTop) === null || _ed$getScrollTop2 === void 0 ? void 0 : _ed$getScrollTop2.call(ed)) ?? 0;
316
+ const delta = currentTop - opts.getLast();
317
+ opts.setLast(currentTop);
318
+ if (delta < 0) {
319
+ opts.onPause();
320
+ return;
321
+ }
322
+ opts.onMaybeResume();
323
+ })) ?? null;
324
+ return disp;
325
+ }
326
+
327
+ //#endregion
328
+ //#region src/core/DiffEditorManager.ts
329
+ var DiffEditorManager = class {
330
+ diffEditorView = null;
331
+ originalModel = null;
332
+ modifiedModel = null;
333
+ lastContainer = null;
334
+ lastKnownOriginalCode = null;
335
+ lastKnownModifiedCode = null;
336
+ lastKnownModifiedLineCount = null;
337
+ pendingDiffUpdate = null;
338
+ shouldAutoScrollDiff = true;
339
+ diffScrollWatcher = null;
340
+ lastScrollTopDiff = 0;
341
+ _hasScrollBar = false;
342
+ cachedScrollHeightDiff = null;
343
+ cachedLineHeightDiff = null;
344
+ cachedComputedHeightDiff = null;
345
+ lastKnownModifiedDirty = false;
346
+ measureViewportDiff() {
347
+ var _me$getLayoutInfo, _me$getScrollTop, _me$getScrollHeight;
348
+ if (!this.diffEditorView) return null;
349
+ const me = this.diffEditorView.getModifiedEditor();
350
+ const li = ((_me$getLayoutInfo = me.getLayoutInfo) === null || _me$getLayoutInfo === void 0 ? void 0 : _me$getLayoutInfo.call(me)) ?? null;
351
+ const lineHeight = this.cachedLineHeightDiff ?? me.getOption(monaco_shim_exports.editor.EditorOption.lineHeight);
352
+ const scrollTop = ((_me$getScrollTop = me.getScrollTop) === null || _me$getScrollTop === void 0 ? void 0 : _me$getScrollTop.call(me)) ?? this.lastScrollTopDiff ?? 0;
353
+ const scrollHeight = ((_me$getScrollHeight = me.getScrollHeight) === null || _me$getScrollHeight === void 0 ? void 0 : _me$getScrollHeight.call(me)) ?? this.cachedScrollHeightDiff ?? (li === null || li === void 0 ? void 0 : li.height) ?? 0;
354
+ const computedHeight = this.cachedComputedHeightDiff ?? this.computedHeight();
355
+ this.cachedLineHeightDiff = lineHeight;
356
+ this.cachedScrollHeightDiff = scrollHeight;
357
+ this.cachedComputedHeightDiff = computedHeight;
358
+ this.lastScrollTopDiff = scrollTop;
359
+ return {
360
+ me,
361
+ li,
362
+ lineHeight,
363
+ scrollTop,
364
+ scrollHeight,
365
+ computedHeight
366
+ };
367
+ }
368
+ lastRevealLineDiff = null;
369
+ revealDebounceIdDiff = null;
370
+ revealDebounceMs = defaultRevealDebounceMs;
371
+ revealIdleTimerIdDiff = null;
372
+ revealStrategyOption;
373
+ revealBatchOnIdleMsOption;
374
+ appendBufferDiff = [];
375
+ appendBufferDiffScheduled = false;
376
+ rafScheduler = createRafScheduler();
377
+ diffHeightManager = null;
378
+ constructor(options, maxHeightValue, maxHeightCSS, autoScrollOnUpdate, autoScrollInitial, autoScrollThresholdPx, autoScrollThresholdLines, diffAutoScroll, revealDebounceMsOption) {
379
+ this.options = options;
380
+ this.maxHeightValue = maxHeightValue;
381
+ this.maxHeightCSS = maxHeightCSS;
382
+ this.autoScrollOnUpdate = autoScrollOnUpdate;
383
+ this.autoScrollInitial = autoScrollInitial;
384
+ this.autoScrollThresholdPx = autoScrollThresholdPx;
385
+ this.autoScrollThresholdLines = autoScrollThresholdLines;
386
+ this.diffAutoScroll = diffAutoScroll;
387
+ this.revealDebounceMsOption = revealDebounceMsOption;
388
+ }
389
+ computedHeight() {
390
+ var _originalEditor$getMo, _modifiedEditor$getMo, _originalEditor$getSc, _modifiedEditor$getSc;
391
+ if (!this.diffEditorView) return Math.min(1 * 18 + padding, this.maxHeightValue);
392
+ const modifiedEditor = this.diffEditorView.getModifiedEditor();
393
+ const originalEditor = this.diffEditorView.getOriginalEditor();
394
+ const lineHeight = modifiedEditor.getOption(monaco_shim_exports.editor.EditorOption.lineHeight);
395
+ const oCount = ((_originalEditor$getMo = originalEditor.getModel()) === null || _originalEditor$getMo === void 0 ? void 0 : _originalEditor$getMo.getLineCount()) ?? 1;
396
+ const mCount = ((_modifiedEditor$getMo = modifiedEditor.getModel()) === null || _modifiedEditor$getMo === void 0 ? void 0 : _modifiedEditor$getMo.getLineCount()) ?? 1;
397
+ const lineCount = Math.max(oCount, mCount);
398
+ const fromLines = lineCount * lineHeight + padding;
399
+ const scrollH = Math.max(((_originalEditor$getSc = originalEditor.getScrollHeight) === null || _originalEditor$getSc === void 0 ? void 0 : _originalEditor$getSc.call(originalEditor)) ?? 0, ((_modifiedEditor$getSc = modifiedEditor.getScrollHeight) === null || _modifiedEditor$getSc === void 0 ? void 0 : _modifiedEditor$getSc.call(modifiedEditor)) ?? 0);
400
+ const desired = Math.max(fromLines, scrollH);
401
+ return Math.min(desired, this.maxHeightValue);
402
+ }
403
+ hasVerticalScrollbarModified() {
404
+ if (!this.diffEditorView) return false;
405
+ if (this._hasScrollBar) return true;
406
+ const m = this.measureViewportDiff();
407
+ if (!m) return false;
408
+ const epsilon = Math.max(2, Math.round(m.lineHeight / 8));
409
+ return this._hasScrollBar = m.scrollHeight > m.computedHeight + Math.max(padding / 2, epsilon);
410
+ }
411
+ userIsNearBottomDiff() {
412
+ if (!this.diffEditorView) return true;
413
+ const m = this.measureViewportDiff();
414
+ if (!m || !m.li) return true;
415
+ const lineThreshold = (this.autoScrollThresholdLines ?? 0) * m.lineHeight;
416
+ const threshold = Math.max(lineThreshold || 0, this.autoScrollThresholdPx || 0);
417
+ const distance = m.scrollHeight - (m.scrollTop + m.li.height);
418
+ return distance <= threshold;
419
+ }
420
+ maybeScrollDiffToBottom(targetLine, prevLineOverride) {
421
+ this.rafScheduler.schedule("maybe-scroll-diff", () => {
422
+ if (!this.diffEditorView) return;
423
+ if (!(this.diffAutoScroll && this.autoScrollOnUpdate && this.shouldAutoScrollDiff && this.hasVerticalScrollbarModified())) return;
424
+ const me = this.diffEditorView.getModifiedEditor();
425
+ const model = me.getModel();
426
+ const currentLine = (model === null || model === void 0 ? void 0 : model.getLineCount()) ?? 1;
427
+ const line = targetLine ?? currentLine;
428
+ const prevLine = typeof prevLineOverride === "number" ? prevLineOverride : this.lastKnownModifiedLineCount ?? -1;
429
+ if (prevLine !== -1 && prevLine === currentLine && line === currentLine) return;
430
+ if (this.lastRevealLineDiff !== null && this.lastRevealLineDiff === line) return;
431
+ const batchMs = this.revealBatchOnIdleMsOption ?? this.options.revealBatchOnIdleMs ?? defaultRevealBatchOnIdleMs;
432
+ if (typeof batchMs === "number" && batchMs > 0) {
433
+ if (this.revealIdleTimerIdDiff != null) clearTimeout(this.revealIdleTimerIdDiff);
434
+ this.revealIdleTimerIdDiff = setTimeout(() => {
435
+ this.revealIdleTimerIdDiff = null;
436
+ this.performRevealDiff(line);
437
+ }, batchMs);
438
+ return;
439
+ }
440
+ if (this.revealDebounceIdDiff != null) {
441
+ clearTimeout(this.revealDebounceIdDiff);
442
+ this.revealDebounceIdDiff = null;
443
+ }
444
+ const ms = typeof this.revealDebounceMs === "number" && this.revealDebounceMs > 0 ? this.revealDebounceMs : typeof this.revealDebounceMsOption === "number" && this.revealDebounceMsOption > 0 ? this.revealDebounceMsOption : this.revealDebounceMs;
445
+ this.revealDebounceIdDiff = setTimeout(() => {
446
+ this.revealDebounceIdDiff = null;
447
+ this.performRevealDiff(line);
448
+ }, ms);
449
+ this.lastKnownModifiedLineCount = currentLine;
450
+ });
451
+ }
452
+ performRevealDiff(line) {
453
+ this.rafScheduler.schedule("revealDiff", () => {
454
+ var _editor;
455
+ const strategy = this.revealStrategyOption ?? this.options.revealStrategy ?? "centerIfOutside";
456
+ const ScrollType = monaco_shim_exports.ScrollType || ((_editor = monaco_shim_exports.editor) === null || _editor === void 0 ? void 0 : _editor.ScrollType);
457
+ const smooth = ScrollType && typeof ScrollType.Smooth !== "undefined" ? ScrollType.Smooth : void 0;
458
+ try {
459
+ const me = this.diffEditorView.getModifiedEditor();
460
+ if (strategy === "bottom") if (typeof smooth !== "undefined") me.revealLine(line, smooth);
461
+ else me.revealLine(line);
462
+ else if (strategy === "center") if (typeof smooth !== "undefined") me.revealLineInCenter(line, smooth);
463
+ else me.revealLineInCenter(line);
464
+ else if (typeof smooth !== "undefined") me.revealLineInCenterIfOutsideViewport(line, smooth);
465
+ else me.revealLineInCenterIfOutsideViewport(line);
466
+ } catch {
467
+ try {
468
+ this.diffEditorView.getModifiedEditor().revealLine(line);
469
+ } catch {}
470
+ }
471
+ this.lastRevealLineDiff = line;
472
+ });
473
+ }
474
+ async createDiffEditor(container, originalCode, modifiedCode, language, currentTheme) {
475
+ var _me$getScrollHeight2, _me$getOption, _oEditor$onDidContent, _mEditor$onDidContent;
476
+ this.cleanup();
477
+ this.lastContainer = container;
478
+ container.style.overflow = "auto";
479
+ container.style.maxHeight = this.maxHeightCSS;
480
+ const lang = processedLanguage(language) || language;
481
+ this.originalModel = monaco_shim_exports.editor.createModel(originalCode, lang);
482
+ this.modifiedModel = monaco_shim_exports.editor.createModel(modifiedCode, lang);
483
+ this.diffEditorView = monaco_shim_exports.editor.createDiffEditor(container, {
484
+ automaticLayout: true,
485
+ scrollBeyondLastLine: false,
486
+ renderSideBySide: true,
487
+ originalEditable: false,
488
+ readOnly: this.options.readOnly ?? true,
489
+ minimap: { enabled: false },
490
+ theme: currentTheme,
491
+ contextmenu: false,
492
+ scrollbar: {
493
+ ...defaultScrollbar,
494
+ ...this.options.scrollbar || {}
495
+ },
496
+ ...this.options
497
+ });
498
+ monaco_shim_exports.editor.setTheme(currentTheme);
499
+ this.diffEditorView.setModel({
500
+ original: this.originalModel,
501
+ modified: this.modifiedModel
502
+ });
503
+ this.lastKnownOriginalCode = originalCode;
504
+ this.lastKnownModifiedCode = modifiedCode;
505
+ this.shouldAutoScrollDiff = !!(this.autoScrollInitial && this.diffAutoScroll);
506
+ if (this.diffScrollWatcher) {
507
+ this.diffScrollWatcher.dispose();
508
+ this.diffScrollWatcher = null;
509
+ }
510
+ if (this.diffAutoScroll) {
511
+ const me$1 = this.diffEditorView.getModifiedEditor();
512
+ this.diffScrollWatcher = createScrollWatcherForEditor(me$1, {
513
+ onPause: () => {
514
+ this.shouldAutoScrollDiff = false;
515
+ },
516
+ onMaybeResume: () => {
517
+ this.rafScheduler.schedule("maybe-resume-diff", () => {
518
+ this.shouldAutoScrollDiff = this.userIsNearBottomDiff();
519
+ });
520
+ },
521
+ getLast: () => this.lastScrollTopDiff,
522
+ setLast: (v) => {
523
+ this.lastScrollTopDiff = v;
524
+ }
525
+ });
526
+ }
527
+ this.maybeScrollDiffToBottom(this.modifiedModel.getLineCount(), this.lastKnownModifiedLineCount ?? void 0);
528
+ if (this.diffHeightManager) {
529
+ this.diffHeightManager.dispose();
530
+ this.diffHeightManager = null;
531
+ }
532
+ this.diffHeightManager = createHeightManager(container, () => this.computedHeight());
533
+ this.diffHeightManager.update();
534
+ const me = this.diffEditorView.getModifiedEditor();
535
+ this.cachedScrollHeightDiff = ((_me$getScrollHeight2 = me.getScrollHeight) === null || _me$getScrollHeight2 === void 0 ? void 0 : _me$getScrollHeight2.call(me)) ?? null;
536
+ this.cachedLineHeightDiff = ((_me$getOption = me.getOption) === null || _me$getOption === void 0 ? void 0 : _me$getOption.call(me, monaco_shim_exports.editor.EditorOption.lineHeight)) ?? null;
537
+ this.cachedComputedHeightDiff = this.computedHeight();
538
+ const oEditor = this.diffEditorView.getOriginalEditor();
539
+ const mEditor = this.diffEditorView.getModifiedEditor();
540
+ (_oEditor$onDidContent = oEditor.onDidContentSizeChange) === null || _oEditor$onDidContent === void 0 || _oEditor$onDidContent.call(oEditor, () => {
541
+ this._hasScrollBar = false;
542
+ this.rafScheduler.schedule("content-size-change-diff", () => {
543
+ try {
544
+ var _oEditor$getScrollHei, _oEditor$getOption, _this$diffHeightManag, _this$diffHeightManag2;
545
+ this.cachedScrollHeightDiff = ((_oEditor$getScrollHei = oEditor.getScrollHeight) === null || _oEditor$getScrollHei === void 0 ? void 0 : _oEditor$getScrollHei.call(oEditor)) ?? this.cachedScrollHeightDiff;
546
+ this.cachedLineHeightDiff = ((_oEditor$getOption = oEditor.getOption) === null || _oEditor$getOption === void 0 ? void 0 : _oEditor$getOption.call(oEditor, monaco_shim_exports.editor.EditorOption.lineHeight)) ?? this.cachedLineHeightDiff;
547
+ this.cachedComputedHeightDiff = this.computedHeight();
548
+ if ((_this$diffHeightManag = this.diffHeightManager) === null || _this$diffHeightManag === void 0 ? void 0 : _this$diffHeightManag.isSuppressed()) return;
549
+ (_this$diffHeightManag2 = this.diffHeightManager) === null || _this$diffHeightManag2 === void 0 || _this$diffHeightManag2.update();
550
+ } catch {}
551
+ });
552
+ });
553
+ (_mEditor$onDidContent = mEditor.onDidContentSizeChange) === null || _mEditor$onDidContent === void 0 || _mEditor$onDidContent.call(mEditor, () => {
554
+ this._hasScrollBar = false;
555
+ this.rafScheduler.schedule("content-size-change-diff", () => {
556
+ try {
557
+ var _mEditor$getScrollHei, _mEditor$getOption, _this$diffHeightManag3, _this$diffHeightManag4;
558
+ this.cachedScrollHeightDiff = ((_mEditor$getScrollHei = mEditor.getScrollHeight) === null || _mEditor$getScrollHei === void 0 ? void 0 : _mEditor$getScrollHei.call(mEditor)) ?? this.cachedScrollHeightDiff;
559
+ this.cachedLineHeightDiff = ((_mEditor$getOption = mEditor.getOption) === null || _mEditor$getOption === void 0 ? void 0 : _mEditor$getOption.call(mEditor, monaco_shim_exports.editor.EditorOption.lineHeight)) ?? this.cachedLineHeightDiff;
560
+ this.cachedComputedHeightDiff = this.computedHeight();
561
+ if ((_this$diffHeightManag3 = this.diffHeightManager) === null || _this$diffHeightManag3 === void 0 ? void 0 : _this$diffHeightManag3.isSuppressed()) return;
562
+ (_this$diffHeightManag4 = this.diffHeightManager) === null || _this$diffHeightManag4 === void 0 || _this$diffHeightManag4.update();
563
+ } catch {}
564
+ });
565
+ });
566
+ mEditor.onDidChangeModelContent(() => {
567
+ this.lastKnownModifiedDirty = true;
568
+ this.rafScheduler.schedule("sync-last-known-modified", () => this.syncLastKnownModified());
569
+ });
570
+ return this.diffEditorView;
571
+ }
572
+ updateDiff(originalCode, modifiedCode, codeLanguage) {
573
+ if (!this.diffEditorView || !this.originalModel || !this.modifiedModel) return;
574
+ const plang = codeLanguage ? processedLanguage(codeLanguage) : void 0;
575
+ if (plang && (this.originalModel.getLanguageId() !== plang || this.modifiedModel.getLanguageId() !== plang)) {
576
+ this.pendingDiffUpdate = {
577
+ original: originalCode,
578
+ modified: modifiedCode,
579
+ lang: codeLanguage
580
+ };
581
+ this.rafScheduler.schedule("diff", () => this.flushPendingDiffUpdate());
582
+ return;
583
+ }
584
+ if (this.lastKnownOriginalCode == null) this.lastKnownOriginalCode = this.originalModel.getValue();
585
+ if (this.lastKnownModifiedCode == null) this.lastKnownModifiedCode = this.modifiedModel.getValue();
586
+ const prevO = this.lastKnownOriginalCode;
587
+ const prevM = this.lastKnownModifiedCode;
588
+ let didImmediate = false;
589
+ if (originalCode !== prevO && originalCode.startsWith(prevO)) {
590
+ this.appendToModel(this.originalModel, originalCode.slice(prevO.length));
591
+ this.lastKnownOriginalCode = originalCode;
592
+ didImmediate = true;
593
+ }
594
+ if (modifiedCode !== prevM && modifiedCode.startsWith(prevM)) {
595
+ const prevLine = this.modifiedModel.getLineCount();
596
+ this.appendToModel(this.modifiedModel, modifiedCode.slice(prevM.length));
597
+ this.lastKnownModifiedCode = modifiedCode;
598
+ didImmediate = true;
599
+ this.maybeScrollDiffToBottom(this.modifiedModel.getLineCount(), prevLine);
600
+ }
601
+ if (originalCode !== this.lastKnownOriginalCode || modifiedCode !== this.lastKnownModifiedCode) {
602
+ this.pendingDiffUpdate = {
603
+ original: originalCode,
604
+ modified: modifiedCode
605
+ };
606
+ this.rafScheduler.schedule("diff", () => this.flushPendingDiffUpdate());
607
+ } else if (didImmediate) {}
608
+ }
609
+ updateOriginal(newCode, codeLanguage) {
610
+ if (!this.diffEditorView || !this.originalModel) return;
611
+ if (codeLanguage) {
612
+ const lang = processedLanguage(codeLanguage);
613
+ if (lang && this.originalModel.getLanguageId() !== lang) monaco_shim_exports.editor.setModelLanguage(this.originalModel, lang);
614
+ }
615
+ const prev = this.lastKnownOriginalCode ?? this.originalModel.getValue();
616
+ if (prev === newCode) return;
617
+ if (newCode.startsWith(prev) && prev.length < newCode.length) this.appendToModel(this.originalModel, newCode.slice(prev.length));
618
+ else this.applyMinimalEditToModel(this.originalModel, prev, newCode);
619
+ this.lastKnownOriginalCode = newCode;
620
+ }
621
+ updateModified(newCode, codeLanguage) {
622
+ if (!this.diffEditorView || !this.modifiedModel) return;
623
+ if (codeLanguage) {
624
+ const lang = processedLanguage(codeLanguage);
625
+ if (lang && this.modifiedModel.getLanguageId() !== lang) monaco_shim_exports.editor.setModelLanguage(this.modifiedModel, lang);
626
+ }
627
+ const prev = this.lastKnownModifiedCode ?? this.modifiedModel.getValue();
628
+ if (prev === newCode) return;
629
+ if (newCode.startsWith(prev) && prev.length < newCode.length) {
630
+ const prevLine = this.modifiedModel.getLineCount();
631
+ this.appendToModel(this.modifiedModel, newCode.slice(prev.length));
632
+ this.maybeScrollDiffToBottom(this.modifiedModel.getLineCount(), prevLine);
633
+ } else this.applyMinimalEditToModel(this.modifiedModel, prev, newCode);
634
+ this.lastKnownModifiedCode = newCode;
635
+ }
636
+ appendOriginal(appendText, codeLanguage) {
637
+ if (!this.diffEditorView || !this.originalModel || !appendText) return;
638
+ if (codeLanguage) {
639
+ const lang = processedLanguage(codeLanguage);
640
+ if (lang && this.originalModel.getLanguageId() !== lang) monaco_shim_exports.editor.setModelLanguage(this.originalModel, lang);
641
+ }
642
+ this.appendToModel(this.originalModel, appendText);
643
+ try {
644
+ this.lastKnownOriginalCode = this.originalModel.getValue();
645
+ } catch {}
646
+ }
647
+ appendModified(appendText, codeLanguage) {
648
+ if (!this.diffEditorView || !this.modifiedModel || !appendText) return;
649
+ if (codeLanguage) {
650
+ const lang = processedLanguage(codeLanguage);
651
+ if (lang && this.modifiedModel.getLanguageId() !== lang) monaco_shim_exports.editor.setModelLanguage(this.modifiedModel, lang);
652
+ }
653
+ this.appendBufferDiff.push(appendText);
654
+ if (!this.appendBufferDiffScheduled) {
655
+ this.appendBufferDiffScheduled = true;
656
+ this.rafScheduler.schedule("appendDiff", () => this.flushAppendBufferDiff());
657
+ }
658
+ }
659
+ setLanguage(language, languages$1) {
660
+ if (!languages$1.includes(language)) {
661
+ console.warn(`Language "${language}" is not registered. Available languages: ${languages$1.join(", ")}`);
662
+ return;
663
+ }
664
+ if (this.originalModel && this.originalModel.getLanguageId() !== language) monaco_shim_exports.editor.setModelLanguage(this.originalModel, language);
665
+ if (this.modifiedModel && this.modifiedModel.getLanguageId() !== language) monaco_shim_exports.editor.setModelLanguage(this.modifiedModel, language);
666
+ }
667
+ getDiffEditorView() {
668
+ return this.diffEditorView;
669
+ }
670
+ getDiffModels() {
671
+ return {
672
+ original: this.originalModel,
673
+ modified: this.modifiedModel
674
+ };
675
+ }
676
+ cleanup() {
677
+ this.rafScheduler.cancel("diff");
678
+ this.pendingDiffUpdate = null;
679
+ this.rafScheduler.cancel("appendDiff");
680
+ this.appendBufferDiffScheduled = false;
681
+ this.appendBufferDiff.length = 0;
682
+ this.rafScheduler.cancel("content-size-change-diff");
683
+ this.rafScheduler.cancel("sync-last-known-modified");
684
+ if (this.diffScrollWatcher) {
685
+ this.diffScrollWatcher.dispose();
686
+ this.diffScrollWatcher = null;
687
+ }
688
+ if (this.diffHeightManager) {
689
+ this.diffHeightManager.dispose();
690
+ this.diffHeightManager = null;
691
+ }
692
+ if (this.diffEditorView) {
693
+ this.diffEditorView.dispose();
694
+ this.diffEditorView = null;
695
+ }
696
+ if (this.originalModel) {
697
+ this.originalModel.dispose();
698
+ this.originalModel = null;
699
+ }
700
+ if (this.modifiedModel) {
701
+ this.modifiedModel.dispose();
702
+ this.modifiedModel = null;
703
+ }
704
+ this.lastKnownOriginalCode = null;
705
+ this.lastKnownModifiedCode = null;
706
+ if (this.lastContainer) {
707
+ this.lastContainer.innerHTML = "";
708
+ this.lastContainer = null;
709
+ }
710
+ if (this.revealDebounceIdDiff != null) {
711
+ clearTimeout(this.revealDebounceIdDiff);
712
+ this.revealDebounceIdDiff = null;
713
+ }
714
+ this.lastRevealLineDiff = null;
715
+ }
716
+ safeClean() {
717
+ this.rafScheduler.cancel("diff");
718
+ this.pendingDiffUpdate = null;
719
+ if (this.diffScrollWatcher) {
720
+ this.diffScrollWatcher.dispose();
721
+ this.diffScrollWatcher = null;
722
+ }
723
+ this._hasScrollBar = false;
724
+ this.shouldAutoScrollDiff = !!(this.autoScrollInitial && this.diffAutoScroll);
725
+ this.lastScrollTopDiff = 0;
726
+ if (this.diffHeightManager) {
727
+ this.diffHeightManager.dispose();
728
+ this.diffHeightManager = null;
729
+ }
730
+ if (this.revealDebounceIdDiff != null) {
731
+ clearTimeout(this.revealDebounceIdDiff);
732
+ this.revealDebounceIdDiff = null;
733
+ }
734
+ this.lastRevealLineDiff = null;
735
+ this.rafScheduler.cancel("content-size-change-diff");
736
+ this.rafScheduler.cancel("sync-last-known-modified");
737
+ }
738
+ syncLastKnownModified() {
739
+ if (!this.diffEditorView || !this.lastKnownModifiedDirty) return;
740
+ try {
741
+ const me = this.diffEditorView.getModifiedEditor();
742
+ const model = me.getModel();
743
+ if (model) {
744
+ this.lastKnownModifiedCode = model.getValue();
745
+ this.lastKnownModifiedLineCount = model.getLineCount();
746
+ }
747
+ } catch {} finally {
748
+ this.lastKnownModifiedDirty = false;
749
+ }
750
+ }
751
+ flushPendingDiffUpdate() {
752
+ if (!this.pendingDiffUpdate || !this.diffEditorView) return;
753
+ const o = this.originalModel;
754
+ const m = this.modifiedModel;
755
+ if (!o || !m) {
756
+ this.pendingDiffUpdate = null;
757
+ return;
758
+ }
759
+ const { original, modified, lang } = this.pendingDiffUpdate;
760
+ this.pendingDiffUpdate = null;
761
+ if (lang) {
762
+ const plang = processedLanguage(lang);
763
+ if (plang) {
764
+ if (o.getLanguageId() !== plang) {
765
+ monaco_shim_exports.editor.setModelLanguage(o, plang);
766
+ monaco_shim_exports.editor.setModelLanguage(m, plang);
767
+ }
768
+ }
769
+ }
770
+ if (this.lastKnownOriginalCode == null) this.lastKnownOriginalCode = o.getValue();
771
+ if (this.lastKnownModifiedCode == null) this.lastKnownModifiedCode = m.getValue();
772
+ const prevO = this.lastKnownOriginalCode;
773
+ if (prevO !== original) {
774
+ if (original.startsWith(prevO) && prevO.length < original.length) this.appendToModel(o, original.slice(prevO.length));
775
+ else this.applyMinimalEditToModel(o, prevO, original);
776
+ this.lastKnownOriginalCode = original;
777
+ }
778
+ const prevM = this.lastKnownModifiedCode;
779
+ const prevMLineCount = m.getLineCount();
780
+ if (prevM !== modified) {
781
+ if (modified.startsWith(prevM) && prevM.length < modified.length) this.appendToModel(m, modified.slice(prevM.length));
782
+ else this.applyMinimalEditToModel(m, prevM, modified);
783
+ this.lastKnownModifiedCode = modified;
784
+ const newMLineCount = m.getLineCount();
785
+ if (newMLineCount !== prevMLineCount) this.maybeScrollDiffToBottom(newMLineCount, prevMLineCount);
786
+ }
787
+ }
788
+ flushAppendBufferDiff() {
789
+ if (!this.diffEditorView) return;
790
+ if (this.appendBufferDiff.length === 0) return;
791
+ this.appendBufferDiffScheduled = false;
792
+ const me = this.diffEditorView.getModifiedEditor();
793
+ const model = me.getModel();
794
+ if (!model) {
795
+ this.appendBufferDiff.length = 0;
796
+ return;
797
+ }
798
+ const text = this.appendBufferDiff.join("");
799
+ this.appendBufferDiff.length = 0;
800
+ try {
801
+ const prevLine = model.getLineCount();
802
+ const lastColumn = model.getLineMaxColumn(prevLine);
803
+ const range = new monaco_shim_exports.Range(prevLine, lastColumn, prevLine, lastColumn);
804
+ model.applyEdits([{
805
+ range,
806
+ text,
807
+ forceMoveMarkers: true
808
+ }]);
809
+ try {
810
+ this.lastKnownModifiedCode = model.getValue();
811
+ } catch {}
812
+ const newLine = model.getLineCount();
813
+ this.maybeScrollDiffToBottom(newLine, prevLine);
814
+ this.lastKnownModifiedLineCount = newLine;
815
+ } catch {}
816
+ }
817
+ applyMinimalEditToModel(model, prev, next) {
818
+ try {
819
+ const maxChars = minimalEditMaxChars;
820
+ const ratio = minimalEditMaxChangeRatio;
821
+ const maxLen = Math.max(prev.length, next.length);
822
+ const changeRatio = maxLen > 0 ? Math.abs(next.length - prev.length) / maxLen : 0;
823
+ if (prev.length + next.length > maxChars || changeRatio > ratio) {
824
+ model.setValue(next);
825
+ try {
826
+ if (model === this.modifiedModel) this.lastKnownModifiedLineCount = model.getLineCount();
827
+ } catch {}
828
+ return;
829
+ }
830
+ } catch {}
831
+ const res = computeMinimalEdit(prev, next);
832
+ if (!res) return;
833
+ const { start, endPrevIncl, replaceText } = res;
834
+ const rangeStart = model.getPositionAt(start);
835
+ const rangeEnd = model.getPositionAt(endPrevIncl + 1);
836
+ const range = new monaco_shim_exports.Range(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column);
837
+ model.applyEdits([{
838
+ range,
839
+ text: replaceText,
840
+ forceMoveMarkers: true
841
+ }]);
842
+ try {
843
+ if (model === this.modifiedModel) this.lastKnownModifiedLineCount = model.getLineCount();
844
+ } catch {}
845
+ }
846
+ appendToModel(model, appendText) {
847
+ if (!appendText) return;
848
+ const lastLine = model.getLineCount();
849
+ const lastColumn = model.getLineMaxColumn(lastLine);
850
+ const range = new monaco_shim_exports.Range(lastLine, lastColumn, lastLine, lastColumn);
851
+ model.applyEdits([{
852
+ range,
853
+ text: appendText,
854
+ forceMoveMarkers: true
855
+ }]);
856
+ try {
857
+ if (model === this.modifiedModel) this.lastKnownModifiedLineCount = model.getLineCount();
858
+ } catch {}
859
+ }
860
+ };
861
+
862
+ //#endregion
863
+ //#region src/core/EditorManager.ts
864
+ var EditorManager = class {
865
+ editorView = null;
866
+ lastContainer = null;
867
+ lastKnownCode = null;
868
+ pendingUpdate = null;
869
+ _hasScrollBar = false;
870
+ shouldAutoScroll = true;
871
+ scrollWatcher = null;
872
+ lastScrollTop = 0;
873
+ cachedScrollHeight = null;
874
+ cachedLineHeight = null;
875
+ cachedComputedHeight = null;
876
+ cachedLineCount = null;
877
+ lastKnownCodeDirty = false;
878
+ measureViewport() {
879
+ var _this$editorView$getL, _this$editorView, _this$editorView$getS, _this$editorView2, _this$editorView$getS2, _this$editorView3;
880
+ if (!this.editorView) return null;
881
+ const li = ((_this$editorView$getL = (_this$editorView = this.editorView).getLayoutInfo) === null || _this$editorView$getL === void 0 ? void 0 : _this$editorView$getL.call(_this$editorView)) ?? null;
882
+ const lineHeight = this.cachedLineHeight ?? this.editorView.getOption(monaco_shim_exports.editor.EditorOption.lineHeight);
883
+ const scrollTop = ((_this$editorView$getS = (_this$editorView2 = this.editorView).getScrollTop) === null || _this$editorView$getS === void 0 ? void 0 : _this$editorView$getS.call(_this$editorView2)) ?? this.lastScrollTop ?? 0;
884
+ const scrollHeight = ((_this$editorView$getS2 = (_this$editorView3 = this.editorView).getScrollHeight) === null || _this$editorView$getS2 === void 0 ? void 0 : _this$editorView$getS2.call(_this$editorView3)) ?? this.cachedScrollHeight ?? (li === null || li === void 0 ? void 0 : li.height) ?? 0;
885
+ const computedHeight = this.cachedComputedHeight ?? this.computedHeight(this.editorView);
886
+ this.cachedLineHeight = lineHeight;
887
+ this.cachedScrollHeight = scrollHeight;
888
+ this.cachedComputedHeight = computedHeight;
889
+ this.lastScrollTop = scrollTop;
890
+ return {
891
+ li,
892
+ lineHeight,
893
+ scrollTop,
894
+ scrollHeight,
895
+ computedHeight
896
+ };
897
+ }
898
+ appendBuffer = [];
899
+ appendBufferScheduled = false;
900
+ rafScheduler = createRafScheduler();
901
+ editorHeightManager = null;
902
+ revealDebounceId = null;
903
+ revealDebounceMs = defaultRevealDebounceMs;
904
+ revealIdleTimerId = null;
905
+ revealStrategyOption;
906
+ revealBatchOnIdleMsOption;
907
+ constructor(options, maxHeightValue, maxHeightCSS, autoScrollOnUpdate, autoScrollInitial, autoScrollThresholdPx, autoScrollThresholdLines, revealDebounceMsOption) {
908
+ this.options = options;
909
+ this.maxHeightValue = maxHeightValue;
910
+ this.maxHeightCSS = maxHeightCSS;
911
+ this.autoScrollOnUpdate = autoScrollOnUpdate;
912
+ this.autoScrollInitial = autoScrollInitial;
913
+ this.autoScrollThresholdPx = autoScrollThresholdPx;
914
+ this.autoScrollThresholdLines = autoScrollThresholdLines;
915
+ this.revealDebounceMsOption = revealDebounceMsOption;
916
+ }
917
+ hasVerticalScrollbar() {
918
+ if (!this.editorView) return false;
919
+ if (this._hasScrollBar) return true;
920
+ const m = this.measureViewport();
921
+ if (!m) return false;
922
+ return this._hasScrollBar = m.scrollHeight > m.computedHeight + padding / 2;
923
+ }
924
+ userIsNearBottom() {
925
+ if (!this.editorView) return true;
926
+ const m = this.measureViewport();
927
+ if (!m || !m.li) return true;
928
+ const lineThreshold = (this.autoScrollThresholdLines ?? 0) * m.lineHeight;
929
+ const threshold = Math.max(lineThreshold || 0, this.autoScrollThresholdPx || 0);
930
+ const distance = m.scrollHeight - (m.scrollTop + m.li.height);
931
+ return distance <= threshold;
932
+ }
933
+ computedHeight(editorView) {
934
+ var _editorView$getModel;
935
+ const lineCount = this.cachedLineCount ?? ((_editorView$getModel = editorView.getModel()) === null || _editorView$getModel === void 0 ? void 0 : _editorView$getModel.getLineCount()) ?? 1;
936
+ const lineHeight = editorView.getOption(monaco_shim_exports.editor.EditorOption.lineHeight);
937
+ const height = Math.min(lineCount * lineHeight + padding, this.maxHeightValue);
938
+ return height;
939
+ }
940
+ maybeScrollToBottom(targetLine) {
941
+ this.rafScheduler.schedule("maybe-scroll", () => {
942
+ if (!(this.autoScrollOnUpdate && this.shouldAutoScroll && this.hasVerticalScrollbar())) return;
943
+ const model = this.editorView.getModel();
944
+ const line = targetLine ?? (model === null || model === void 0 ? void 0 : model.getLineCount()) ?? 1;
945
+ const batchMs = this.revealBatchOnIdleMsOption ?? this.options.revealBatchOnIdleMs ?? defaultRevealBatchOnIdleMs;
946
+ if (typeof batchMs === "number" && batchMs > 0) {
947
+ if (this.revealIdleTimerId != null) clearTimeout(this.revealIdleTimerId);
948
+ this.revealIdleTimerId = setTimeout(() => {
949
+ this.revealIdleTimerId = null;
950
+ this.performReveal(line);
951
+ }, batchMs);
952
+ return;
953
+ }
954
+ if (this.revealDebounceId != null) {
955
+ clearTimeout(this.revealDebounceId);
956
+ this.revealDebounceId = null;
957
+ }
958
+ const ms = typeof this.revealDebounceMs === "number" && this.revealDebounceMs > 0 ? this.revealDebounceMs : typeof this.revealDebounceMsOption === "number" && this.revealDebounceMsOption > 0 ? this.revealDebounceMsOption : this.revealDebounceMs;
959
+ this.revealDebounceId = setTimeout(() => {
960
+ this.revealDebounceId = null;
961
+ this.performReveal(line);
962
+ }, ms);
963
+ });
964
+ }
965
+ performReveal(line) {
966
+ this.rafScheduler.schedule("reveal", () => {
967
+ var _editor;
968
+ const strategy = this.revealStrategyOption ?? this.options.revealStrategy ?? "centerIfOutside";
969
+ const ScrollType = monaco_shim_exports.ScrollType || ((_editor = monaco_shim_exports.editor) === null || _editor === void 0 ? void 0 : _editor.ScrollType);
970
+ const smooth = ScrollType && typeof ScrollType.Smooth !== "undefined" ? ScrollType.Smooth : void 0;
971
+ try {
972
+ if (strategy === "bottom") if (typeof smooth !== "undefined") this.editorView.revealLine(line, smooth);
973
+ else this.editorView.revealLine(line);
974
+ else if (strategy === "center") if (typeof smooth !== "undefined") this.editorView.revealLineInCenter(line, smooth);
975
+ else this.editorView.revealLineInCenter(line);
976
+ else if (typeof smooth !== "undefined") this.editorView.revealLineInCenterIfOutsideViewport(line, smooth);
977
+ else this.editorView.revealLineInCenterIfOutsideViewport(line);
978
+ } catch {
979
+ try {
980
+ this.editorView.revealLine(line);
981
+ } catch {}
982
+ }
983
+ });
984
+ }
985
+ async createEditor(container, code, language, currentTheme) {
986
+ var _this$editorView$getS3, _this$editorView4, _this$editorView$getO, _this$editorView5, _this$editorView$getM, _this$editorView$onDi, _this$editorView6;
987
+ this.cleanup();
988
+ this.lastContainer = container;
989
+ container.style.overflow = "auto";
990
+ container.style.maxHeight = this.maxHeightCSS;
991
+ this.editorView = monaco_shim_exports.editor.create(container, {
992
+ value: code,
993
+ language: processedLanguage(language) || language,
994
+ theme: currentTheme,
995
+ scrollBeyondLastLine: false,
996
+ minimap: { enabled: false },
997
+ automaticLayout: true,
998
+ readOnly: this.options.readOnly ?? true,
999
+ contextmenu: false,
1000
+ scrollbar: {
1001
+ ...defaultScrollbar,
1002
+ ...this.options.scrollbar || {}
1003
+ },
1004
+ ...this.options
1005
+ });
1006
+ monaco_shim_exports.editor.setTheme(currentTheme);
1007
+ this.lastKnownCode = this.editorView.getValue();
1008
+ if (this.editorHeightManager) {
1009
+ try {
1010
+ this.editorHeightManager.dispose();
1011
+ } catch {}
1012
+ this.editorHeightManager = null;
1013
+ }
1014
+ if (this.revealDebounceId != null) {
1015
+ clearTimeout(this.revealDebounceId);
1016
+ this.revealDebounceId = null;
1017
+ }
1018
+ if (this.revealIdleTimerId != null) clearTimeout(this.revealIdleTimerId);
1019
+ this.revealIdleTimerId = null;
1020
+ this.editorHeightManager = createHeightManager(container, () => this.computedHeight(this.editorView));
1021
+ this.editorHeightManager.update();
1022
+ this.cachedScrollHeight = ((_this$editorView$getS3 = (_this$editorView4 = this.editorView).getScrollHeight) === null || _this$editorView$getS3 === void 0 ? void 0 : _this$editorView$getS3.call(_this$editorView4)) ?? null;
1023
+ this.cachedLineHeight = ((_this$editorView$getO = (_this$editorView5 = this.editorView).getOption) === null || _this$editorView$getO === void 0 ? void 0 : _this$editorView$getO.call(_this$editorView5, monaco_shim_exports.editor.EditorOption.lineHeight)) ?? null;
1024
+ this.cachedComputedHeight = this.computedHeight(this.editorView);
1025
+ this.cachedLineCount = ((_this$editorView$getM = this.editorView.getModel()) === null || _this$editorView$getM === void 0 ? void 0 : _this$editorView$getM.getLineCount()) ?? null;
1026
+ (_this$editorView$onDi = (_this$editorView6 = this.editorView).onDidContentSizeChange) === null || _this$editorView$onDi === void 0 || _this$editorView$onDi.call(_this$editorView6, () => {
1027
+ this._hasScrollBar = false;
1028
+ this.rafScheduler.schedule("content-size-change", () => {
1029
+ try {
1030
+ var _this$editorView7, _this$editorHeightMan, _this$editorHeightMan2;
1031
+ this.measureViewport();
1032
+ this.cachedLineCount = ((_this$editorView7 = this.editorView) === null || _this$editorView7 === void 0 || (_this$editorView7 = _this$editorView7.getModel()) === null || _this$editorView7 === void 0 ? void 0 : _this$editorView7.getLineCount()) ?? this.cachedLineCount;
1033
+ if ((_this$editorHeightMan = this.editorHeightManager) === null || _this$editorHeightMan === void 0 ? void 0 : _this$editorHeightMan.isSuppressed()) return;
1034
+ (_this$editorHeightMan2 = this.editorHeightManager) === null || _this$editorHeightMan2 === void 0 || _this$editorHeightMan2.update();
1035
+ } catch {}
1036
+ });
1037
+ });
1038
+ this.editorView.onDidChangeModelContent(() => {
1039
+ this.lastKnownCodeDirty = true;
1040
+ this.rafScheduler.schedule("sync-last-known", () => this.syncLastKnownCode());
1041
+ });
1042
+ this.shouldAutoScroll = !!this.autoScrollInitial;
1043
+ if (this.scrollWatcher) {
1044
+ this.scrollWatcher.dispose();
1045
+ this.scrollWatcher = null;
1046
+ }
1047
+ this.scrollWatcher = createScrollWatcherForEditor(this.editorView, {
1048
+ onPause: () => {
1049
+ this.shouldAutoScroll = false;
1050
+ },
1051
+ onMaybeResume: () => {
1052
+ this.rafScheduler.schedule("maybe-resume", () => {
1053
+ this.shouldAutoScroll = this.userIsNearBottom();
1054
+ });
1055
+ },
1056
+ getLast: () => this.lastScrollTop,
1057
+ setLast: (v) => {
1058
+ this.lastScrollTop = v;
1059
+ }
1060
+ });
1061
+ this.maybeScrollToBottom();
1062
+ return this.editorView;
1063
+ }
1064
+ syncLastKnownCode() {
1065
+ if (!this.editorView || !this.lastKnownCodeDirty) return;
1066
+ try {
1067
+ const model = this.editorView.getModel();
1068
+ if (model) {
1069
+ this.lastKnownCode = model.getValue();
1070
+ this.cachedLineCount = model.getLineCount() ?? this.cachedLineCount;
1071
+ }
1072
+ } catch {} finally {
1073
+ this.lastKnownCodeDirty = false;
1074
+ }
1075
+ }
1076
+ updateCode(newCode, codeLanguage) {
1077
+ this.pendingUpdate = {
1078
+ code: newCode,
1079
+ lang: codeLanguage
1080
+ };
1081
+ this.rafScheduler.schedule("update", () => this.flushPendingUpdate());
1082
+ }
1083
+ flushPendingUpdate() {
1084
+ if (!this.pendingUpdate || !this.editorView) return;
1085
+ const model = this.editorView.getModel();
1086
+ if (!model) return;
1087
+ const { code: newCode, lang: codeLanguage } = this.pendingUpdate;
1088
+ this.pendingUpdate = null;
1089
+ const processedCodeLanguage = processedLanguage(codeLanguage);
1090
+ const languageId = model.getLanguageId();
1091
+ if (languageId !== processedCodeLanguage) {
1092
+ if (processedCodeLanguage) monaco_shim_exports.editor.setModelLanguage(model, processedCodeLanguage);
1093
+ const prevLineCount$1 = model.getLineCount();
1094
+ model.setValue(newCode);
1095
+ this.lastKnownCode = newCode;
1096
+ const newLineCount$1 = model.getLineCount();
1097
+ this.cachedLineCount = newLineCount$1;
1098
+ if (newLineCount$1 !== prevLineCount$1) this.maybeScrollToBottom(newLineCount$1);
1099
+ return;
1100
+ }
1101
+ const prevCode = this.lastKnownCode ?? this.editorView.getValue();
1102
+ if (prevCode === newCode) return;
1103
+ if (newCode.startsWith(prevCode) && prevCode.length < newCode.length) {
1104
+ const suffix = newCode.slice(prevCode.length);
1105
+ if (suffix) this.appendCode(suffix, codeLanguage);
1106
+ this.lastKnownCode = newCode;
1107
+ return;
1108
+ }
1109
+ const prevLineCount = model.getLineCount();
1110
+ this.applyMinimalEdit(prevCode, newCode);
1111
+ this.lastKnownCode = newCode;
1112
+ const newLineCount = model.getLineCount();
1113
+ this.cachedLineCount = newLineCount;
1114
+ if (newLineCount !== prevLineCount) this.maybeScrollToBottom(newLineCount);
1115
+ }
1116
+ appendCode(appendText, codeLanguage) {
1117
+ if (!this.editorView) return;
1118
+ const model = this.editorView.getModel();
1119
+ if (!model) return;
1120
+ const processedCodeLanguage = codeLanguage ? processedLanguage(codeLanguage) : model.getLanguageId();
1121
+ if (processedCodeLanguage && model.getLanguageId() !== processedCodeLanguage) monaco_shim_exports.editor.setModelLanguage(model, processedCodeLanguage);
1122
+ if (appendText) {
1123
+ this.appendBuffer.push(appendText);
1124
+ if (!this.appendBufferScheduled) {
1125
+ this.appendBufferScheduled = true;
1126
+ this.rafScheduler.schedule("append", () => this.flushAppendBuffer());
1127
+ }
1128
+ }
1129
+ }
1130
+ applyMinimalEdit(prev, next) {
1131
+ if (!this.editorView) return;
1132
+ const model = this.editorView.getModel();
1133
+ if (!model) return;
1134
+ try {
1135
+ const maxChars = minimalEditMaxChars;
1136
+ const ratio = minimalEditMaxChangeRatio;
1137
+ const maxLen = Math.max(prev.length, next.length);
1138
+ const changeRatio = maxLen > 0 ? Math.abs(next.length - prev.length) / maxLen : 0;
1139
+ if (prev.length + next.length > maxChars || changeRatio > ratio) {
1140
+ const prevLineCount = model.getLineCount();
1141
+ model.setValue(next);
1142
+ this.lastKnownCode = next;
1143
+ const newLineCount = model.getLineCount();
1144
+ this.cachedLineCount = newLineCount;
1145
+ if (newLineCount !== prevLineCount) this.maybeScrollToBottom(newLineCount);
1146
+ return;
1147
+ }
1148
+ } catch {}
1149
+ const res = computeMinimalEdit(prev, next);
1150
+ if (!res) return;
1151
+ const { start, endPrevIncl, replaceText } = res;
1152
+ const rangeStart = model.getPositionAt(start);
1153
+ const rangeEnd = model.getPositionAt(endPrevIncl + 1);
1154
+ const range = new monaco_shim_exports.Range(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column);
1155
+ const isReadOnly = this.editorView.getOption(monaco_shim_exports.editor.EditorOption.readOnly);
1156
+ const edit = [{
1157
+ range,
1158
+ text: replaceText,
1159
+ forceMoveMarkers: true
1160
+ }];
1161
+ if (isReadOnly) model.applyEdits(edit);
1162
+ else this.editorView.executeEdits("minimal-replace", edit);
1163
+ }
1164
+ flushAppendBuffer() {
1165
+ if (!this.editorView) return;
1166
+ if (this.appendBuffer.length === 0) return;
1167
+ this.appendBufferScheduled = false;
1168
+ const model = this.editorView.getModel();
1169
+ if (!model) {
1170
+ this.appendBuffer.length = 0;
1171
+ return;
1172
+ }
1173
+ const text = this.appendBuffer.join("");
1174
+ this.appendBuffer.length = 0;
1175
+ const lastLine = model.getLineCount();
1176
+ const lastColumn = model.getLineMaxColumn(lastLine);
1177
+ const range = new monaco_shim_exports.Range(lastLine, lastColumn, lastLine, lastColumn);
1178
+ const isReadOnly = this.editorView.getOption(monaco_shim_exports.editor.EditorOption.readOnly);
1179
+ if (isReadOnly) model.applyEdits([{
1180
+ range,
1181
+ text,
1182
+ forceMoveMarkers: true
1183
+ }]);
1184
+ else this.editorView.executeEdits("append", [{
1185
+ range,
1186
+ text,
1187
+ forceMoveMarkers: true
1188
+ }]);
1189
+ const newLineCount = model.getLineCount();
1190
+ if (lastLine !== newLineCount) {
1191
+ this.cachedLineCount = newLineCount;
1192
+ this.maybeScrollToBottom(newLineCount);
1193
+ }
1194
+ }
1195
+ setLanguage(language, languages$1) {
1196
+ if (languages$1.includes(language)) {
1197
+ if (this.editorView) {
1198
+ const model = this.editorView.getModel();
1199
+ if (model && model.getLanguageId() !== language) monaco_shim_exports.editor.setModelLanguage(model, language);
1200
+ }
1201
+ } else console.warn(`Language "${language}" is not registered. Available languages: ${languages$1.join(", ")}`);
1202
+ }
1203
+ getEditorView() {
1204
+ return this.editorView;
1205
+ }
1206
+ cleanup() {
1207
+ this.rafScheduler.cancel("update");
1208
+ this.rafScheduler.cancel("sync-last-known");
1209
+ this.rafScheduler.cancel("content-size-change");
1210
+ this.pendingUpdate = null;
1211
+ this.rafScheduler.cancel("append");
1212
+ this.appendBufferScheduled = false;
1213
+ this.appendBuffer.length = 0;
1214
+ if (this.editorView) {
1215
+ this.editorView.dispose();
1216
+ this.editorView = null;
1217
+ }
1218
+ this.lastKnownCode = null;
1219
+ if (this.lastContainer) {
1220
+ this.lastContainer.innerHTML = "";
1221
+ this.lastContainer = null;
1222
+ }
1223
+ if (this.scrollWatcher) {
1224
+ this.scrollWatcher.dispose();
1225
+ this.scrollWatcher = null;
1226
+ }
1227
+ if (this.editorHeightManager) {
1228
+ this.editorHeightManager.dispose();
1229
+ this.editorHeightManager = null;
1230
+ }
1231
+ }
1232
+ safeClean() {
1233
+ this.rafScheduler.cancel("update");
1234
+ this.pendingUpdate = null;
1235
+ this.rafScheduler.cancel("sync-last-known");
1236
+ if (this.scrollWatcher) {
1237
+ this.scrollWatcher.dispose();
1238
+ this.scrollWatcher = null;
1239
+ }
1240
+ if (this.revealDebounceId != null) {
1241
+ clearTimeout(this.revealDebounceId);
1242
+ this.revealDebounceId = null;
1243
+ }
1244
+ this._hasScrollBar = false;
1245
+ this.shouldAutoScroll = !!this.autoScrollInitial;
1246
+ this.lastScrollTop = 0;
1247
+ if (this.editorHeightManager) {
1248
+ this.editorHeightManager.dispose();
1249
+ this.editorHeightManager = null;
1250
+ }
1251
+ }
1252
+ };
1253
+
1254
+ //#endregion
1255
+ //#region src/reactivity.ts
1256
+ function ref(initial) {
1257
+ const s = (0, alien_signals.signal)(initial);
1258
+ return Object.defineProperty({}, "value", {
1259
+ get() {
1260
+ return s();
1261
+ },
1262
+ set(v) {
1263
+ s(v);
1264
+ },
1265
+ enumerable: true,
1266
+ configurable: false
1267
+ });
1268
+ }
1269
+ function computed(getter) {
1270
+ const c = (0, alien_signals.computed)(() => getter());
1271
+ return Object.defineProperty({}, "value", {
1272
+ get() {
1273
+ return c();
1274
+ },
1275
+ set(_) {},
1276
+ enumerable: true,
1277
+ configurable: false
1278
+ });
1279
+ }
1280
+ function watch(source, cb, options = {}) {
1281
+ let initialized = false;
1282
+ let oldVal;
1283
+ const stop = (0, alien_signals.effect)(() => {
1284
+ const newVal = source();
1285
+ if (!initialized) {
1286
+ initialized = true;
1287
+ if (options.immediate) if (options.flush === "post") queueMicrotask(() => cb(newVal, oldVal));
1288
+ else cb(newVal, oldVal);
1289
+ } else if (!Object.is(newVal, oldVal)) if (options.flush === "post") queueMicrotask(() => cb(newVal, oldVal));
1290
+ else cb(newVal, oldVal);
1291
+ oldVal = newVal;
1292
+ });
1293
+ return stop;
1294
+ }
1295
+
1296
+ //#endregion
1297
+ //#region src/isDark.ts
1298
+ const isDark = ref(false);
1299
+ function computeIsDark() {
1300
+ var _el$classList, _window$matchMedia, _window;
1301
+ if (typeof window === "undefined" || typeof document === "undefined") return false;
1302
+ const el = document.documentElement;
1303
+ const hasClass = ((_el$classList = el.classList) === null || _el$classList === void 0 ? void 0 : _el$classList.contains("dark")) ?? false;
1304
+ const mql = (_window$matchMedia = (_window = window).matchMedia) === null || _window$matchMedia === void 0 ? void 0 : _window$matchMedia.call(_window, "(prefers-color-scheme: dark)");
1305
+ const prefersDark = !!(mql === null || mql === void 0 ? void 0 : mql.matches);
1306
+ return hasClass || prefersDark;
1307
+ }
1308
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
1309
+ var _window$matchMedia2, _window2;
1310
+ const el = document.documentElement;
1311
+ const mql = (_window$matchMedia2 = (_window2 = window).matchMedia) === null || _window$matchMedia2 === void 0 ? void 0 : _window$matchMedia2.call(_window2, "(prefers-color-scheme: dark)");
1312
+ const update = () => {
1313
+ isDark.value = computeIsDark();
1314
+ };
1315
+ update();
1316
+ const onMqlChange = () => update();
1317
+ if (mql) mql.addEventListener ? mql.addEventListener("change", onMqlChange) : mql.addListener(onMqlChange);
1318
+ const mo = new MutationObserver(update);
1319
+ mo.observe(el, {
1320
+ attributes: true,
1321
+ attributeFilter: ["class"]
1322
+ });
1323
+ const cleanup = () => {
1324
+ if (mql) mql.removeEventListener ? mql.removeEventListener("change", onMqlChange) : mql.removeListener(onMqlChange);
1325
+ mo.disconnect();
1326
+ window.removeEventListener("pagehide", cleanup);
1327
+ window.removeEventListener("beforeunload", cleanup);
1328
+ };
1329
+ window.addEventListener("pagehide", cleanup);
1330
+ window.addEventListener("beforeunload", cleanup);
1331
+ }
1332
+
1333
+ //#endregion
1334
+ //#region src/preloadMonacoWorkers.ts
1335
+ async function preloadMonacoWorkers() {
1336
+ if (typeof window === "undefined" || typeof document === "undefined") return;
1337
+ const workerUrlJson = new URL("monaco-editor/esm/vs/language/json/json.worker.js", require("url").pathToFileURL(__filename).href);
1338
+ const workerUrlCss = new URL("monaco-editor/esm/vs/language/css/css.worker.js", require("url").pathToFileURL(__filename).href);
1339
+ const workerUrlHtml = new URL("monaco-editor/esm/vs/language/html/html.worker.js", require("url").pathToFileURL(__filename).href);
1340
+ const workerUrlTs = new URL("monaco-editor/esm/vs/language/typescript/ts.worker.js", require("url").pathToFileURL(__filename).href);
1341
+ const workerUrlEditor = new URL("monaco-editor/esm/vs/editor/editor.worker.js", require("url").pathToFileURL(__filename).href);
1342
+ const unique = Array.from(new Set([
1343
+ String(workerUrlJson),
1344
+ String(workerUrlCss),
1345
+ String(workerUrlHtml),
1346
+ String(workerUrlTs),
1347
+ String(workerUrlEditor)
1348
+ ]));
1349
+ const workerUrlByLabel = {
1350
+ json: workerUrlJson,
1351
+ css: workerUrlCss,
1352
+ scss: workerUrlCss,
1353
+ less: workerUrlCss,
1354
+ html: workerUrlHtml,
1355
+ handlebars: workerUrlHtml,
1356
+ razor: workerUrlHtml,
1357
+ typescript: workerUrlTs,
1358
+ javascript: workerUrlTs
1359
+ };
1360
+ try {
1361
+ await Promise.all(unique.map((u) => fetch(u, {
1362
+ method: "GET",
1363
+ cache: "force-cache"
1364
+ }).catch(() => void 0)));
1365
+ self.MonacoEnvironment = { getWorker(_, label) {
1366
+ const url = workerUrlByLabel[label] ?? workerUrlEditor;
1367
+ return new Worker(url, { type: "module" });
1368
+ } };
1369
+ } catch {}
1370
+ }
1371
+
1372
+ //#endregion
1373
+ //#region src/utils/arraysEqual.ts
1374
+ function arraysEqual(a, b) {
1375
+ if (a === b) return true;
1376
+ if (!a || !b) return false;
1377
+ if (a.length !== b.length) return false;
1378
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
1379
+ return true;
1380
+ }
1381
+
1382
+ //#endregion
1383
+ //#region src/utils/registerMonacoThemes.ts
1384
+ let themesRegistered = false;
1385
+ let languagesRegistered = false;
1386
+ let currentThemes = [];
1387
+ let currentLanguages = [];
1388
+ let themeRegisterPromise = null;
1389
+ function setThemeRegisterPromise(p) {
1390
+ return themeRegisterPromise = p;
1391
+ }
1392
+ const highlighterCache = /* @__PURE__ */ new Map();
1393
+ /**
1394
+ * Clear all cached shiki highlighters.
1395
+ *
1396
+ * Useful for long-running apps that dynamically create many theme combinations,
1397
+ * or in tests to ensure a clean state. Call this when you know the highlighters
1398
+ * are no longer needed (for example on app shutdown) to free memory.
1399
+ */
1400
+ function clearHighlighterCache() {
1401
+ highlighterCache.clear();
1402
+ }
1403
+ function serializeThemes(themes) {
1404
+ return JSON.stringify(themes.map((t) => typeof t === "string" ? t : t.name ?? JSON.stringify(t)).sort());
1405
+ }
1406
+ async function getOrCreateHighlighter(themes, languages$1) {
1407
+ const key = serializeThemes(themes);
1408
+ const requestedSet = new Set(languages$1);
1409
+ let existing = highlighterCache.get(key);
1410
+ if (existing) {
1411
+ let allIncluded = true;
1412
+ for (const l of requestedSet) if (!existing.languages.has(l)) {
1413
+ allIncluded = false;
1414
+ break;
1415
+ }
1416
+ if (allIncluded) return existing.promise;
1417
+ const prev = existing;
1418
+ const current = highlighterCache.get(key);
1419
+ if (current && current !== prev) {
1420
+ let allIncludedCurrent = true;
1421
+ for (const l of requestedSet) if (!current.languages.has(l)) {
1422
+ allIncludedCurrent = false;
1423
+ break;
1424
+ }
1425
+ if (allIncludedCurrent) return current.promise;
1426
+ existing = current;
1427
+ }
1428
+ const union = new Set([...existing.languages, ...requestedSet]);
1429
+ const langsArray = Array.from(union);
1430
+ const p$1 = (0, shiki.createHighlighter)({
1431
+ themes,
1432
+ langs: langsArray
1433
+ });
1434
+ const newEntry = {
1435
+ promise: p$1,
1436
+ languages: union
1437
+ };
1438
+ highlighterCache.set(key, newEntry);
1439
+ p$1.catch(() => {
1440
+ if (highlighterCache.get(key) === newEntry && prev) highlighterCache.set(key, prev);
1441
+ });
1442
+ return p$1;
1443
+ }
1444
+ const p = (0, shiki.createHighlighter)({
1445
+ themes,
1446
+ langs: Array.from(requestedSet)
1447
+ });
1448
+ const entry = {
1449
+ promise: p,
1450
+ languages: requestedSet
1451
+ };
1452
+ highlighterCache.set(key, entry);
1453
+ p.catch(() => {
1454
+ if (highlighterCache.get(key) === entry) highlighterCache.delete(key);
1455
+ });
1456
+ return p;
1457
+ }
1458
+ /**
1459
+ * Update the theme used by the shiki highlighter for a given themes+languages
1460
+ * combination. Useful when Monaco themes are already registered (so switching
1461
+ * Monaco only requires `monaco.editor.setTheme`) but you also want shiki's
1462
+ * standalone renderer to use the new theme without recreating everything.
1463
+ */
1464
+ async function registerMonacoThemes(themes, languages$1) {
1465
+ registerMonacoLanguages(languages$1);
1466
+ if (themesRegistered && arraysEqual(themes, currentThemes) && arraysEqual(languages$1, currentLanguages)) {
1467
+ const existing = highlighterCache.get(serializeThemes(themes));
1468
+ return existing ? existing.promise : Promise.resolve(null);
1469
+ }
1470
+ const p = (async () => {
1471
+ const highlighter = await getOrCreateHighlighter(themes, languages$1);
1472
+ (0, __shikijs_monaco.shikiToMonaco)(highlighter, monaco_shim_exports);
1473
+ themesRegistered = true;
1474
+ currentThemes = themes;
1475
+ currentLanguages = languages$1;
1476
+ return highlighter;
1477
+ })();
1478
+ setThemeRegisterPromise(p);
1479
+ try {
1480
+ const res = await p;
1481
+ return res;
1482
+ } catch (e) {
1483
+ setThemeRegisterPromise(null);
1484
+ throw e;
1485
+ }
1486
+ }
1487
+ function registerMonacoLanguages(languages$1) {
1488
+ if (languagesRegistered && arraysEqual(languages$1, currentLanguages)) return;
1489
+ const existing = new Set(monaco_shim_exports.languages.getLanguages().map((l) => l.id));
1490
+ for (const lang of languages$1) if (!existing.has(lang)) try {
1491
+ monaco_shim_exports.languages.register({ id: lang });
1492
+ } catch {}
1493
+ languagesRegistered = true;
1494
+ currentLanguages = languages$1;
1495
+ }
1496
+
1497
+ //#endregion
1498
+ //#region src/type.ts
1499
+ let RevealStrategy = /* @__PURE__ */ function(RevealStrategy$1) {
1500
+ RevealStrategy$1["Bottom"] = "bottom";
1501
+ RevealStrategy$1["CenterIfOutside"] = "centerIfOutside";
1502
+ RevealStrategy$1["Center"] = "center";
1503
+ return RevealStrategy$1;
1504
+ }({});
1505
+
1506
+ //#endregion
1507
+ //#region src/index.ts
1508
+ /**
1509
+ * useMonaco 组合式函数
1510
+ *
1511
+ * 提供 Monaco 编辑器的创建、销毁、内容/主题/语言更新等能力。
1512
+ * 支持主题自动切换、语言高亮、代码更新等功能。
1513
+ *
1514
+ * @param {MonacoOptions} [monacoOptions] - 编辑器初始化配置,支持 Monaco 原生配置及扩展项
1515
+ * @param {number | string} [monacoOptions.MAX_HEIGHT] - 编辑器最大高度,可以是数字(像素)或 CSS 字符串(如 '100%', 'calc(100vh - 100px)')
1516
+ * @param {boolean} [monacoOptions.readOnly] - 是否为只读模式
1517
+ * @param {MonacoTheme[]} [monacoOptions.themes] - 主题数组,至少包含两个主题:[暗色主题, 亮色主题]
1518
+ * @param {MonacoLanguage[]} [monacoOptions.languages] - 支持的编程语言数组
1519
+ * @param {string} [monacoOptions.theme] - 初始主题名称
1520
+ * @param {boolean} [monacoOptions.isCleanOnBeforeCreate] - 是否在创建前清理之前注册的资源, 默认为 true
1521
+ * @param {(monaco: typeof import('monaco-editor')) => monaco.IDisposable[]} [monacoOptions.onBeforeCreate] - 编辑器创建前的钩子函数
1522
+ *
1523
+ * @returns {{
1524
+ * createEditor: (container: HTMLElement, code: string, language: string) => Promise<monaco.editor.IStandaloneCodeEditor>,
1525
+ * createDiffEditor: (
1526
+ * container: HTMLElement,
1527
+ * originalCode: string,
1528
+ * modifiedCode: string,
1529
+ * language: string,
1530
+ * ) => Promise<monaco.editor.IStandaloneDiffEditor>,
1531
+ * cleanupEditor: () => void,
1532
+ * updateCode: (newCode: string, codeLanguage: string) => void,
1533
+ * appendCode: (appendText: string, codeLanguage?: string) => void,
1534
+ * updateDiff: (
1535
+ * originalCode: string,
1536
+ * modifiedCode: string,
1537
+ * codeLanguage?: string,
1538
+ * ) => void,
1539
+ * updateOriginal: (newCode: string, codeLanguage?: string) => void,
1540
+ * updateModified: (newCode: string, codeLanguage?: string) => void,
1541
+ * appendOriginal: (appendText: string, codeLanguage?: string) => void,
1542
+ * appendModified: (appendText: string, codeLanguage?: string) => void,
1543
+ * setTheme: (theme: MonacoTheme) => Promise<void>,
1544
+ * setLanguage: (language: MonacoLanguage) => void,
1545
+ * getCurrentTheme: () => string,
1546
+ * getEditor: () => typeof monaco.editor,
1547
+ * getEditorView: () => monaco.editor.IStandaloneCodeEditor | null,
1548
+ * getDiffEditorView: () => monaco.editor.IStandaloneDiffEditor | null,
1549
+ * getDiffModels: () => { original: monaco.editor.ITextModel | null, modified: monaco.editor.ITextModel | null },
1550
+ * }} 返回对象包含以下方法和属性:
1551
+ *
1552
+ * @property {Function} createEditor - 创建并挂载 Monaco 编辑器到指定容器
1553
+ * @property {Function} cleanupEditor - 销毁编辑器并清理容器
1554
+ * @property {Function} updateCode - 更新编辑器内容和语言,必要时滚动到底部
1555
+ * @property {Function} appendCode - 在编辑器末尾追加文本,必要时滚动到底部
1556
+ * @property {Function} createDiffEditor - 创建并挂载 Diff 编辑器
1557
+ * @property {Function} updateDiff - 更新 Diff 编辑器的 original/modified 内容(RAF 合并、增量更新)
1558
+ * @property {Function} updateOriginal - 仅更新 Diff 的 original 内容(增量更新)
1559
+ * @property {Function} updateModified - 仅更新 Diff 的 modified 内容(增量更新)
1560
+ * @property {Function} appendOriginal - 在 Diff 的 original 末尾追加(显式流式场景)
1561
+ * @property {Function} appendModified - 在 Diff 的 modified 末尾追加(显式流式场景)
1562
+ * @property {Function} setTheme - 切换编辑器主题,返回 Promise,在主题应用完成时 resolve
1563
+ * @property {Function} setLanguage - 切换编辑器语言
1564
+ * @property {Function} getCurrentTheme - 获取当前主题名称
1565
+ * @property {Function} getEditor - 获取 Monaco 的静态 editor 对象(用于静态方法调用)
1566
+ * @property {Function} getEditorView - 获取当前编辑器实例
1567
+ * @property {Function} getDiffEditorView - 获取当前 Diff 编辑器实例
1568
+ * @property {Function} getDiffModels - 获取 Diff 的 original/modified 两个模型
1569
+ *
1570
+ * @throws {Error} 当主题数组不是数组或长度小于2时抛出错误
1571
+ *
1572
+ * @example
1573
+ * ```typescript
1574
+ * import { useMonaco } from 'stream-monaco'
1575
+ *
1576
+ * const { createEditor, updateCode, setTheme } = useMonaco({
1577
+ * themes: ['vitesse-dark', 'vitesse-light'],
1578
+ * languages: ['javascript', 'typescript'],
1579
+ * readOnly: false
1580
+ * })
1581
+ *
1582
+ * // 创建编辑器
1583
+ * const editor = await createEditor(containerRef.value, 'console.log("hello")', 'javascript')
1584
+ *
1585
+ * // 更新代码
1586
+ * updateCode('console.log("world")', 'javascript')
1587
+ *
1588
+ * // 切换主题
1589
+ * setTheme('vitesse-light')
1590
+ * ```
1591
+ */
1592
+ function useMonaco(monacoOptions = {}) {
1593
+ var _monacoOptions$themes;
1594
+ const disposals = [];
1595
+ if (monacoOptions.isCleanOnBeforeCreate ?? true) disposals.forEach((d) => d.dispose());
1596
+ if (monacoOptions.isCleanOnBeforeCreate ?? true) disposals.length = 0;
1597
+ let editorView = null;
1598
+ let editorMgr = null;
1599
+ let diffEditorView = null;
1600
+ let diffMgr = null;
1601
+ let originalModel = null;
1602
+ let modifiedModel = null;
1603
+ let _hasScrollBar = false;
1604
+ const themes = monacoOptions.themes && ((_monacoOptions$themes = monacoOptions.themes) === null || _monacoOptions$themes === void 0 ? void 0 : _monacoOptions$themes.length) ? monacoOptions.themes : defaultThemes;
1605
+ if (!Array.isArray(themes) || themes.length < 2) throw new Error("Monaco themes must be an array with at least two themes: [darkTheme, lightTheme]");
1606
+ const languages$1 = monacoOptions.languages ?? defaultLanguages;
1607
+ const MAX_HEIGHT = monacoOptions.MAX_HEIGHT ?? 500;
1608
+ const autoScrollOnUpdate = monacoOptions.autoScrollOnUpdate ?? true;
1609
+ const autoScrollInitial = monacoOptions.autoScrollInitial ?? true;
1610
+ const autoScrollThresholdPx = monacoOptions.autoScrollThresholdPx ?? 32;
1611
+ const autoScrollThresholdLines = monacoOptions.autoScrollThresholdLines ?? 2;
1612
+ const diffAutoScroll = monacoOptions.diffAutoScroll ?? true;
1613
+ const getMaxHeightValue = () => {
1614
+ if (typeof MAX_HEIGHT === "number") return MAX_HEIGHT;
1615
+ const match = MAX_HEIGHT.match(/^(\d+(?:\.\d+)?)/);
1616
+ return match ? Number.parseFloat(match[1]) : 500;
1617
+ };
1618
+ const getMaxHeightCSS = () => {
1619
+ if (typeof MAX_HEIGHT === "number") return `${MAX_HEIGHT}px`;
1620
+ return MAX_HEIGHT;
1621
+ };
1622
+ const maxHeightValue = getMaxHeightValue();
1623
+ const maxHeightCSS = getMaxHeightCSS();
1624
+ let lastContainer = null;
1625
+ let lastKnownCode = null;
1626
+ const minimalEditMaxCharsLocal = monacoOptions.minimalEditMaxChars ?? minimalEditMaxChars;
1627
+ const minimalEditMaxChangeRatioLocal = monacoOptions.minimalEditMaxChangeRatio ?? minimalEditMaxChangeRatio;
1628
+ let updateThrottleMs = monacoOptions.updateThrottleMs ?? 50;
1629
+ let lastFlushTime = 0;
1630
+ let updateThrottleTimer = null;
1631
+ let pendingUpdate = null;
1632
+ let shouldAutoScroll = true;
1633
+ const cachedComputedHeight = null;
1634
+ const appendBuffer = [];
1635
+ let appendBufferScheduled = false;
1636
+ let lastAppliedTheme = null;
1637
+ const currentTheme = computed(() => monacoOptions.theme ?? (isDark.value ? typeof themes[0] === "string" ? themes[0] : themes[0].name : typeof themes[1] === "string" ? themes[1] : themes[1].name));
1638
+ let themeWatcher = null;
1639
+ const rafScheduler = createRafScheduler();
1640
+ async function setThemeInternal(theme, force = false) {
1641
+ const themeName = typeof theme === "string" ? theme : theme.name;
1642
+ if (!force && themeName === lastAppliedTheme) return;
1643
+ const _p = setThemeRegisterPromise(registerMonacoThemes(themes, languages$1));
1644
+ if (_p) await _p.catch(() => void 0);
1645
+ const availableNames = themes.map((t) => typeof t === "string" ? t : t.name);
1646
+ if (!availableNames.includes(themeName)) try {
1647
+ const extended = availableNames.concat(themeName);
1648
+ const maybeHighlighter = await setThemeRegisterPromise(registerMonacoThemes(extended, languages$1));
1649
+ if (maybeHighlighter && typeof maybeHighlighter.setTheme === "function") try {
1650
+ await maybeHighlighter.setTheme(themeName);
1651
+ } catch {}
1652
+ } catch {
1653
+ console.warn(`Theme "${themeName}" is not registered and automatic registration failed. Available themes: ${availableNames.join(", ")}`);
1654
+ return;
1655
+ }
1656
+ try {
1657
+ monaco_shim_exports.editor.setTheme(themeName);
1658
+ lastAppliedTheme = themeName;
1659
+ } catch {
1660
+ try {
1661
+ const maybeHighlighter = await registerMonacoThemes(themes, languages$1);
1662
+ monaco_shim_exports.editor.setTheme(themeName);
1663
+ lastAppliedTheme = themeName;
1664
+ if (maybeHighlighter && typeof maybeHighlighter.setTheme === "function") await maybeHighlighter.setTheme(themeName).catch(() => void 0);
1665
+ } catch (err2) {
1666
+ console.warn(`Failed to set theme "${themeName}":`, err2);
1667
+ return;
1668
+ }
1669
+ }
1670
+ try {
1671
+ if (typeof monacoOptions.onThemeChange === "function") await monacoOptions.onThemeChange(themeName);
1672
+ } catch (err) {
1673
+ console.warn("onThemeChange callback threw an error:", err);
1674
+ }
1675
+ }
1676
+ function hasVerticalScrollbar() {
1677
+ if (!editorView) return false;
1678
+ if (_hasScrollBar) return true;
1679
+ const ch = cachedComputedHeight ?? computedHeight(editorView);
1680
+ return _hasScrollBar = editorView.getScrollHeight() > ch + padding / 2;
1681
+ }
1682
+ let revealDebounceId = null;
1683
+ const revealDebounceMs = 75;
1684
+ function maybeScrollToBottom(targetLine) {
1685
+ if (autoScrollOnUpdate && shouldAutoScroll && hasVerticalScrollbar()) {
1686
+ const model = editorView.getModel();
1687
+ const line = targetLine ?? (model === null || model === void 0 ? void 0 : model.getLineCount()) ?? 1;
1688
+ if (revealDebounceId != null) {
1689
+ clearTimeout(revealDebounceId);
1690
+ revealDebounceId = null;
1691
+ }
1692
+ revealDebounceId = setTimeout(() => {
1693
+ revealDebounceId = null;
1694
+ rafScheduler.schedule("reveal", () => {
1695
+ try {
1696
+ var _editor;
1697
+ const ScrollType = monaco_shim_exports.ScrollType || ((_editor = monaco_shim_exports.editor) === null || _editor === void 0 ? void 0 : _editor.ScrollType);
1698
+ if (ScrollType && typeof ScrollType.Smooth !== "undefined") editorView.revealLineInCenterIfOutsideViewport(line, ScrollType.Smooth);
1699
+ else editorView.revealLineInCenterIfOutsideViewport(line);
1700
+ } catch {}
1701
+ });
1702
+ }, revealDebounceMs);
1703
+ }
1704
+ }
1705
+ async function createEditor(container, code, language) {
1706
+ cleanupEditor();
1707
+ lastContainer = container;
1708
+ if (monacoOptions.isCleanOnBeforeCreate ?? true) {
1709
+ disposals.forEach((d) => d.dispose());
1710
+ disposals.length = 0;
1711
+ }
1712
+ if (monacoOptions.onBeforeCreate) {
1713
+ const ds = monacoOptions.onBeforeCreate(monaco_shim_exports);
1714
+ if (ds) disposals.push(...ds);
1715
+ }
1716
+ await setThemeRegisterPromise(registerMonacoThemes(themes, languages$1));
1717
+ const initialThemeName = monacoOptions.theme ?? currentTheme.value;
1718
+ lastAppliedTheme = initialThemeName;
1719
+ editorMgr = new EditorManager(monacoOptions, maxHeightValue, maxHeightCSS, autoScrollOnUpdate, autoScrollInitial, autoScrollThresholdPx, autoScrollThresholdLines, monacoOptions.revealDebounceMs);
1720
+ editorView = await editorMgr.createEditor(container, code, language, initialThemeName);
1721
+ if (typeof monacoOptions.onThemeChange === "function") monacoOptions.onThemeChange(initialThemeName);
1722
+ if (!monacoOptions.theme) themeWatcher = watch(() => isDark.value, () => {
1723
+ const t = currentTheme.value;
1724
+ if (t !== lastAppliedTheme) setThemeInternal(t);
1725
+ }, {
1726
+ flush: "post",
1727
+ immediate: true
1728
+ });
1729
+ try {
1730
+ if (editorView) lastKnownCode = editorView.getValue();
1731
+ } catch {}
1732
+ return editorView;
1733
+ }
1734
+ function computedHeight(editorView$1) {
1735
+ var _getModel;
1736
+ const lineCount = ((_getModel = editorView$1.getModel()) === null || _getModel === void 0 ? void 0 : _getModel.getLineCount()) ?? 1;
1737
+ const lineHeight = editorView$1.getOption(monaco_shim_exports.editor.EditorOption.lineHeight);
1738
+ const height = Math.min(lineCount * lineHeight + padding, maxHeightValue);
1739
+ return height;
1740
+ }
1741
+ async function createDiffEditor(container, originalCode, modifiedCode, language) {
1742
+ cleanupEditor();
1743
+ lastContainer = container;
1744
+ if (monacoOptions.isCleanOnBeforeCreate ?? true) {
1745
+ disposals.forEach((d) => d.dispose());
1746
+ disposals.length = 0;
1747
+ }
1748
+ if (monacoOptions.onBeforeCreate) {
1749
+ const ds = monacoOptions.onBeforeCreate(monaco_shim_exports);
1750
+ if (ds) disposals.push(...ds);
1751
+ }
1752
+ await setThemeRegisterPromise(registerMonacoThemes(themes, languages$1));
1753
+ const initialThemeName = monacoOptions.theme ?? currentTheme.value;
1754
+ try {
1755
+ monaco_shim_exports.editor.setTheme(initialThemeName);
1756
+ lastAppliedTheme = initialThemeName;
1757
+ } catch {}
1758
+ diffMgr = new DiffEditorManager(monacoOptions, maxHeightValue, maxHeightCSS, autoScrollOnUpdate, autoScrollInitial, autoScrollThresholdPx, autoScrollThresholdLines, diffAutoScroll, monacoOptions.revealDebounceMs);
1759
+ diffEditorView = await diffMgr.createDiffEditor(container, originalCode, modifiedCode, language, initialThemeName);
1760
+ if (typeof monacoOptions.onThemeChange === "function") monacoOptions.onThemeChange(initialThemeName);
1761
+ if (!monacoOptions.theme) themeWatcher = watch(() => isDark.value, () => {
1762
+ const t = currentTheme.value;
1763
+ if (t !== lastAppliedTheme) setThemeInternal(t);
1764
+ }, {
1765
+ flush: "post",
1766
+ immediate: true
1767
+ });
1768
+ const models = diffMgr.getDiffModels();
1769
+ originalModel = models.original;
1770
+ modifiedModel = models.modified;
1771
+ return diffEditorView;
1772
+ }
1773
+ function cleanupEditor() {
1774
+ if (editorMgr) {
1775
+ editorMgr.cleanup();
1776
+ editorMgr = null;
1777
+ }
1778
+ if (diffMgr) {
1779
+ diffMgr.cleanup();
1780
+ diffMgr = null;
1781
+ }
1782
+ rafScheduler.cancel("update");
1783
+ pendingUpdate = null;
1784
+ rafScheduler.cancel("append");
1785
+ appendBufferScheduled = false;
1786
+ appendBuffer.length = 0;
1787
+ if (!editorMgr && editorView) {
1788
+ editorView.dispose();
1789
+ editorView = null;
1790
+ }
1791
+ lastKnownCode = null;
1792
+ if (lastContainer) {
1793
+ lastContainer.innerHTML = "";
1794
+ lastContainer = null;
1795
+ }
1796
+ if (themeWatcher) {
1797
+ themeWatcher();
1798
+ themeWatcher = null;
1799
+ }
1800
+ if (updateThrottleTimer != null) {
1801
+ clearTimeout(updateThrottleTimer);
1802
+ updateThrottleTimer = null;
1803
+ }
1804
+ diffEditorView = null;
1805
+ originalModel = null;
1806
+ modifiedModel = null;
1807
+ }
1808
+ function appendCode(appendText, codeLanguage) {
1809
+ if (editorMgr) editorMgr.appendCode(appendText, codeLanguage);
1810
+ else {
1811
+ if (!editorView) return;
1812
+ const model = editorView.getModel();
1813
+ if (!model) return;
1814
+ const processedCodeLanguage = codeLanguage ? processedLanguage(codeLanguage) : model.getLanguageId();
1815
+ if (processedCodeLanguage && model.getLanguageId() !== processedCodeLanguage) monaco_shim_exports.editor.setModelLanguage(model, processedCodeLanguage);
1816
+ if (appendText && lastKnownCode != null) lastKnownCode = lastKnownCode + appendText;
1817
+ if (appendText) {
1818
+ appendBuffer.push(appendText);
1819
+ if (!appendBufferScheduled) {
1820
+ appendBufferScheduled = true;
1821
+ rafScheduler.schedule("append", flushAppendBuffer);
1822
+ }
1823
+ }
1824
+ }
1825
+ }
1826
+ function applyMinimalEdit(prev, next) {
1827
+ if (!editorView) return;
1828
+ const model = editorView.getModel();
1829
+ if (!model) return;
1830
+ try {
1831
+ const maxChars = minimalEditMaxCharsLocal;
1832
+ const ratio = minimalEditMaxChangeRatioLocal;
1833
+ const maxLen = Math.max(prev.length, next.length);
1834
+ const changeRatio = maxLen > 0 ? Math.abs(next.length - prev.length) / maxLen : 0;
1835
+ if (prev.length + next.length > maxChars || changeRatio > ratio) {
1836
+ const prevLineCount = model.getLineCount();
1837
+ model.setValue(next);
1838
+ lastKnownCode = next;
1839
+ const newLineCount = model.getLineCount();
1840
+ if (newLineCount !== prevLineCount) maybeScrollToBottom(newLineCount);
1841
+ return;
1842
+ }
1843
+ } catch {}
1844
+ const res = computeMinimalEdit(prev, next);
1845
+ if (!res) return;
1846
+ const { start, endPrevIncl, replaceText } = res;
1847
+ const rangeStart = model.getPositionAt(start);
1848
+ const rangeEnd = model.getPositionAt(endPrevIncl + 1);
1849
+ const range = new monaco_shim_exports.Range(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column);
1850
+ const isReadOnly = editorView.getOption(monaco_shim_exports.editor.EditorOption.readOnly);
1851
+ const edit = [{
1852
+ range,
1853
+ text: replaceText,
1854
+ forceMoveMarkers: true
1855
+ }];
1856
+ if (isReadOnly) model.applyEdits(edit);
1857
+ else editorView.executeEdits("minimal-replace", edit);
1858
+ }
1859
+ function flushPendingUpdate() {
1860
+ if (!pendingUpdate) return;
1861
+ lastFlushTime = Date.now();
1862
+ if (!editorView) return;
1863
+ const model = editorView.getModel();
1864
+ if (!model) return;
1865
+ const { code: newCode, lang: codeLanguage } = pendingUpdate;
1866
+ pendingUpdate = null;
1867
+ const processedCodeLanguage = processedLanguage(codeLanguage);
1868
+ let prevCode = lastKnownCode;
1869
+ if (prevCode == null) try {
1870
+ prevCode = model.getValue();
1871
+ lastKnownCode = prevCode;
1872
+ } catch {
1873
+ prevCode = "";
1874
+ }
1875
+ if (prevCode === newCode) return;
1876
+ const languageId = model.getLanguageId();
1877
+ if (languageId !== processedCodeLanguage) {
1878
+ if (processedCodeLanguage) monaco_shim_exports.editor.setModelLanguage(model, processedCodeLanguage);
1879
+ const prevLineCount = model.getLineCount();
1880
+ model.setValue(newCode);
1881
+ lastKnownCode = newCode;
1882
+ const newLineCount = model.getLineCount();
1883
+ if (newLineCount !== prevLineCount) maybeScrollToBottom(newLineCount);
1884
+ return;
1885
+ }
1886
+ if (newCode.startsWith(prevCode) && prevCode.length < newCode.length) {
1887
+ const suffix = newCode.slice(prevCode.length);
1888
+ if (suffix) appendCode(suffix, codeLanguage);
1889
+ lastKnownCode = newCode;
1890
+ return;
1891
+ }
1892
+ try {
1893
+ const maxChars = minimalEditMaxCharsLocal;
1894
+ const ratio = minimalEditMaxChangeRatioLocal;
1895
+ const maxLen = Math.max(prevCode.length, newCode.length);
1896
+ const changeRatio = maxLen > 0 ? Math.abs(newCode.length - prevCode.length) / maxLen : 0;
1897
+ if (prevCode.length + newCode.length > maxChars || changeRatio > ratio) {
1898
+ const prevLineCount = model.getLineCount();
1899
+ model.setValue(newCode);
1900
+ lastKnownCode = newCode;
1901
+ const newLineCount = model.getLineCount();
1902
+ if (newLineCount !== prevLineCount) maybeScrollToBottom(newLineCount);
1903
+ return;
1904
+ }
1905
+ } catch {}
1906
+ try {
1907
+ applyMinimalEdit(prevCode, newCode);
1908
+ lastKnownCode = newCode;
1909
+ const newLineCount = model.getLineCount();
1910
+ const prevLineCount = (prevCode ? prevCode.split("\n").length : 0) || model.getLineCount();
1911
+ if (newLineCount !== prevLineCount) maybeScrollToBottom(newLineCount);
1912
+ } catch {
1913
+ try {
1914
+ const prevLineCount = model.getLineCount();
1915
+ model.setValue(newCode);
1916
+ lastKnownCode = newCode;
1917
+ const newLineCount = model.getLineCount();
1918
+ if (newLineCount !== prevLineCount) maybeScrollToBottom(newLineCount);
1919
+ } catch {}
1920
+ }
1921
+ }
1922
+ function flushAppendBuffer() {
1923
+ if (!editorView) return;
1924
+ if (appendBuffer.length === 0) return;
1925
+ appendBufferScheduled = false;
1926
+ const model = editorView.getModel();
1927
+ if (!model) {
1928
+ appendBuffer.length = 0;
1929
+ return;
1930
+ }
1931
+ const text = appendBuffer.join("");
1932
+ appendBuffer.length = 0;
1933
+ try {
1934
+ const lastLine = model.getLineCount();
1935
+ const lastColumn = model.getLineMaxColumn(lastLine);
1936
+ const range = new monaco_shim_exports.Range(lastLine, lastColumn, lastLine, lastColumn);
1937
+ const isReadOnly = editorView.getOption(monaco_shim_exports.editor.EditorOption.readOnly);
1938
+ if (isReadOnly) model.applyEdits([{
1939
+ range,
1940
+ text,
1941
+ forceMoveMarkers: true
1942
+ }]);
1943
+ else editorView.executeEdits("append", [{
1944
+ range,
1945
+ text,
1946
+ forceMoveMarkers: true
1947
+ }]);
1948
+ if (lastKnownCode != null) lastKnownCode = lastKnownCode + text;
1949
+ try {
1950
+ if (lastLine !== model.getLineCount()) maybeScrollToBottom(model.getLineCount());
1951
+ } catch {}
1952
+ } catch {}
1953
+ }
1954
+ function updateCode(newCode, codeLanguage) {
1955
+ if (editorMgr) editorMgr.updateCode(newCode, codeLanguage);
1956
+ else {
1957
+ pendingUpdate = {
1958
+ code: newCode,
1959
+ lang: codeLanguage
1960
+ };
1961
+ rafScheduler.schedule("update", () => {
1962
+ if (!updateThrottleMs) {
1963
+ flushPendingUpdate();
1964
+ return;
1965
+ }
1966
+ const now = Date.now();
1967
+ const since = now - lastFlushTime;
1968
+ if (since >= updateThrottleMs) {
1969
+ flushPendingUpdate();
1970
+ return;
1971
+ }
1972
+ if (updateThrottleTimer != null) return;
1973
+ const wait = updateThrottleMs - since;
1974
+ updateThrottleTimer = setTimeout(() => {
1975
+ updateThrottleTimer = null;
1976
+ rafScheduler.schedule("update", () => flushPendingUpdate());
1977
+ }, wait);
1978
+ });
1979
+ }
1980
+ }
1981
+ function setUpdateThrottleMs(ms) {
1982
+ updateThrottleMs = ms;
1983
+ }
1984
+ function getUpdateThrottleMs() {
1985
+ return updateThrottleMs;
1986
+ }
1987
+ function updateDiff(originalCode, modifiedCode, codeLanguage) {
1988
+ if (diffMgr) diffMgr.updateDiff(originalCode, modifiedCode, codeLanguage);
1989
+ }
1990
+ function updateOriginal(newCode, codeLanguage) {
1991
+ if (diffMgr) diffMgr.updateOriginal(newCode, codeLanguage);
1992
+ }
1993
+ function updateModified(newCode, codeLanguage) {
1994
+ if (diffMgr) diffMgr.updateModified(newCode, codeLanguage);
1995
+ }
1996
+ function appendOriginal(appendText, codeLanguage) {
1997
+ if (diffMgr) diffMgr.appendOriginal(appendText, codeLanguage);
1998
+ }
1999
+ function appendModified(appendText, codeLanguage) {
2000
+ if (diffMgr) diffMgr.appendModified(appendText, codeLanguage);
2001
+ }
2002
+ return {
2003
+ createEditor,
2004
+ createDiffEditor,
2005
+ cleanupEditor,
2006
+ safeClean() {
2007
+ rafScheduler.cancel("update");
2008
+ pendingUpdate = null;
2009
+ if (editorMgr) try {
2010
+ editorMgr.safeClean();
2011
+ } catch {}
2012
+ if (diffMgr) try {
2013
+ diffMgr.safeClean();
2014
+ } catch {}
2015
+ _hasScrollBar = false;
2016
+ shouldAutoScroll = !!autoScrollInitial;
2017
+ },
2018
+ updateCode,
2019
+ appendCode,
2020
+ updateDiff,
2021
+ updateOriginal,
2022
+ updateModified,
2023
+ appendOriginal,
2024
+ appendModified,
2025
+ setTheme: setThemeInternal,
2026
+ setLanguage(language) {
2027
+ if (editorMgr) {
2028
+ editorMgr.setLanguage(language, languages$1);
2029
+ return;
2030
+ }
2031
+ if (diffMgr) {
2032
+ diffMgr.setLanguage(language, languages$1);
2033
+ return;
2034
+ }
2035
+ if (languages$1.includes(language)) {
2036
+ if (editorView) {
2037
+ const model = editorView.getModel();
2038
+ if (model && model.getLanguageId() !== language) monaco_shim_exports.editor.setModelLanguage(model, language);
2039
+ }
2040
+ if (originalModel && originalModel.getLanguageId() !== language) monaco_shim_exports.editor.setModelLanguage(originalModel, language);
2041
+ if (modifiedModel && modifiedModel.getLanguageId() !== language) monaco_shim_exports.editor.setModelLanguage(modifiedModel, language);
2042
+ } else console.warn(`Language "${language}" is not registered. Available languages: ${languages$1.join(", ")}`);
2043
+ },
2044
+ getCurrentTheme() {
2045
+ return currentTheme.value;
2046
+ },
2047
+ getEditor() {
2048
+ return monaco_shim_exports.editor;
2049
+ },
2050
+ getEditorView() {
2051
+ return editorView;
2052
+ },
2053
+ getDiffEditorView() {
2054
+ return diffEditorView;
2055
+ },
2056
+ getDiffModels() {
2057
+ return {
2058
+ original: originalModel,
2059
+ modified: modifiedModel
2060
+ };
2061
+ },
2062
+ getMonacoInstance() {
2063
+ return monaco_shim_exports;
2064
+ },
2065
+ setUpdateThrottleMs,
2066
+ getUpdateThrottleMs
2067
+ };
2068
+ }
2069
+
2070
+ //#endregion
2071
+ exports.RevealStrategy = RevealStrategy;
2072
+ exports.clearHighlighterCache = clearHighlighterCache;
2073
+ exports.defaultRevealDebounceMs = defaultRevealDebounceMs;
2074
+ exports.detectLanguage = detectLanguage;
2075
+ exports.getOrCreateHighlighter = getOrCreateHighlighter;
2076
+ exports.isDark = isDark;
2077
+ exports.preloadMonacoWorkers = preloadMonacoWorkers;
2078
+ exports.registerMonacoThemes = registerMonacoThemes;
2079
+ exports.useMonaco = useMonaco;