stream-monaco 0.0.14 → 0.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.
package/dist/index.js CHANGED
@@ -1,1939 +1,14 @@
1
- import { __export, __reExport } from "./chunk-CHLpw0oG.js";
2
- import * as _monaco from "monaco-editor";
3
- import { computed } from "alien-signals";
4
- import { shikiToMonaco } from "@shikijs/monaco";
5
- import { createHighlighter } from "shiki";
1
+ import { RevealStrategy, clearHighlighterCache, defaultRevealDebounceMs, detectLanguage, editorWorkerPath, getOrCreateHighlighter, registerMonacoThemes, uniqueWorkerPaths, useMonaco, workerPathByLabel } from "./preloadMonacoWorkers.shared-C62vOlc9.js";
6
2
 
7
- //#region src/code.detect.ts
8
- /**
9
- * Language detection definitions
10
- */
11
- const languages = [
12
- [
13
- "bash",
14
- [/#!(\/usr)?\/bin\/bash/g, 500],
15
- [/\b(if|elif|then|fi|echo)\b|\$/g, 10]
16
- ],
17
- [
18
- "html",
19
- [/<\/?[a-z-][^\n>]*>/g, 10],
20
- [/^\s+<!DOCTYPE\s+html/g, 500]
21
- ],
22
- ["http", [/^(GET|HEAD|POST|PUT|DELETE|PATCH|HTTP)\b/g, 500]],
23
- ["js", [/\b(console|await|async|function|export|import|this|class|for|let|const|map|join|require)\b/g, 10]],
24
- ["ts", [/\b(console|await|async|function|export|import|this|class|for|let|const|map|join|require|implements|interface|namespace)\b/g, 10]],
25
- ["py", [/\b(def|print|class|and|or|lambda)\b/g, 10]],
26
- ["sql", [/\b(SELECT|INSERT|FROM)\b/g, 50]],
27
- [
28
- "pl",
29
- [/#!(\/usr)?\/bin\/perl/g, 500],
30
- [/\b(use|print)\b|\$/g, 10]
31
- ],
32
- ["lua", [/#!(\/usr)?\/bin\/lua/g, 500]],
33
- ["make", [/\b(ifneq|endif|if|elif|then|fi|echo|.PHONY|^[a-z]+ ?:$)\b|\$/gm, 10]],
34
- ["uri", [/https?:|mailto:|tel:|ftp:/g, 30]],
35
- ["css", [/^(@import|@page|@media|(\.|#)[a-z]+)/gm, 20]],
36
- [
37
- "diff",
38
- [/^[+><-]/gm, 10],
39
- [/^@@[-+,0-9 ]+@@/gm, 25]
40
- ],
41
- [
42
- "md",
43
- [/^(>|\t\*|\t\d+.|#{1,6} |-\s+|\*\s+)/gm, 25],
44
- [/\[.*\](.*)/g, 10]
45
- ],
46
- ["docker", [/^(FROM|ENTRYPOINT|RUN)/gm, 500]],
47
- [
48
- "xml",
49
- [/<\/?[a-z-][^\n>]*>/g, 10],
50
- [/^<\?xml/g, 500]
51
- ],
52
- ["c", [/#include\b|\bprintf\s+\(/g, 100]],
53
- ["rs", [/^\s+(use|fn|mut|match)\b/gm, 100]],
54
- ["go", [/\b(func|fmt|package)\b/g, 100]],
55
- ["java", [/^import\s+java/gm, 500]],
56
- ["asm", [/^(section|global main|extern|\t(call|mov|ret))/gm, 100]],
57
- ["css", [/^(@import|@page|@media|(\.|#)[a-z]+)/gm, 20]],
58
- ["json", [/\b(true|false|null|\{\})\b|"[^"]+":/g, 10]],
59
- ["yaml", [/^(\s+)?[a-z][a-z0-9]*:/gim, 10]],
60
- [
61
- "toml",
62
- [/^\s*\[.*\]\s*$/gm, 100],
63
- [/^\s*[\w-]+ *= */gm, 20]
64
- ],
65
- [
66
- "mermaid",
67
- [/^(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|mindmap)/gm, 500],
68
- [/\b(-->|--o|--x|=>|\[\]|[{}])\b/g, 10]
69
- ]
70
- ];
71
- /**
72
- * Try to find the language the given code belongs to
73
- *
74
- * @param {string} code The code to analyze
75
- * @param {LanguageDefinition[]} [additionalLanguages] Additional language definitions to supplement the built-in ones
76
- * @returns {CodeLanguage} The detected language of the code
77
- */
78
- function detectLanguage(code, additionalLanguages) {
79
- var _allLanguages$map$fil;
80
- const allLanguages = additionalLanguages ? [...languages, ...additionalLanguages] : languages;
81
- 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";
82
- }
83
- function processedLanguage(language) {
84
- if (/^(?:shellscript|bash|sh|shell|zsh)/i.test(language)) return "shell";
85
- if (/^(?:powershell|ps1?)/i.test(language)) return "powershell";
86
- return language.split(":")[0];
87
- }
88
- /**
89
- * 使用示例:
90
- *
91
- * // 基本用法
92
- * const language1 = detectLanguage('console.log("hello")') // 'js'
93
- *
94
- * // 使用自定义语言检测规则
95
- * const customLanguages: LanguageDefinition[] = [
96
- * ['vue', [/<template>/g, 100], [/<script>/g, 50], [/<style>/g, 50]],
97
- * ['kotlin', [/\b(fun|class|val|var)\b/g, 20]]
98
- * ]
99
- *
100
- * const language2 = detectLanguage(`
101
- * <template>
102
- * <div>Hello Vue</div>
103
- * </template>
104
- * `, customLanguages) // 'vue'
105
- *
106
- * const language3 = detectLanguage(`
107
- * fun main() {
108
- * val name = "Kotlin"
109
- * println("Hello $name")
110
- * }
111
- * `, customLanguages) // 'kotlin'
112
- */
113
-
114
- //#endregion
115
- //#region src/constant.ts
116
- const defaultLanguages = [
117
- "jsx",
118
- "tsx",
119
- "vue",
120
- "csharp",
121
- "python",
122
- "java",
123
- "c",
124
- "cpp",
125
- "rust",
126
- "go",
127
- "powershell",
128
- "sql",
129
- "json",
130
- "html",
131
- "javascript",
132
- "typescript",
133
- "css",
134
- "markdown",
135
- "xml",
136
- "yaml",
137
- "toml",
138
- "dockerfile",
139
- "kotlin",
140
- "objective-c",
141
- "objective-cpp",
142
- "php",
143
- "ruby",
144
- "scala",
145
- "svelte",
146
- "swift",
147
- "erlang",
148
- "angular-html",
149
- "angular-ts",
150
- "dart",
151
- "lua",
152
- "mermaid",
153
- "cmake",
154
- "nginx"
155
- ];
156
- const defaultThemes = ["vitesse-dark", "vitesse-light"];
157
- const defaultScrollbar = {
158
- verticalScrollbarSize: 8,
159
- horizontalScrollbarSize: 8,
160
- handleMouseWheel: true,
161
- alwaysConsumeMouseWheel: false
162
- };
163
- const padding = 16;
164
- const defaultRevealDebounceMs = 75;
165
- const defaultRevealBatchOnIdleMs = 200;
166
- const minimalEditMaxChars = 2e5;
167
- const minimalEditMaxChangeRatio = .5;
168
-
169
- //#endregion
170
- //#region src/minimalEdit.ts
171
- /**
172
- * Compute the minimal middle replacement between two UTF-16 strings.
173
- * Returns null when prev === next (no edits required).
174
- */
175
- function computeMinimalEdit(prev, next) {
176
- if (prev === next) return null;
177
- let start = 0;
178
- const minLen = Math.min(prev.length, next.length);
179
- while (start < minLen && prev.charCodeAt(start) === next.charCodeAt(start)) start++;
180
- let endPrev = prev.length - 1;
181
- let endNext = next.length - 1;
182
- while (endPrev >= start && endNext >= start && prev.charCodeAt(endPrev) === next.charCodeAt(endNext)) {
183
- endPrev--;
184
- endNext--;
185
- }
186
- return {
187
- start,
188
- endPrevIncl: endPrev,
189
- endNextIncl: endNext,
190
- replaceText: next.slice(start, endNext + 1)
191
- };
192
- }
193
-
194
- //#endregion
195
- //#region src/monaco-shim.ts
196
- var monaco_shim_exports = {};
197
- __export(monaco_shim_exports, { default: () => monaco });
198
- import * as import_monaco_editor from "monaco-editor";
199
- __reExport(monaco_shim_exports, import_monaco_editor);
200
- const monaco = _monaco;
201
-
202
- //#endregion
203
- //#region src/utils/logger.ts
204
- let seq = 0;
205
- const DEBUG = (() => {
206
- if (typeof window !== "undefined" && window.__STREAM_MONACO_DEBUG__ !== void 0) return Boolean(window.__STREAM_MONACO_DEBUG__);
207
- return false;
208
- })();
209
- function log(tag, ...args) {
210
- if (!DEBUG) return;
211
- seq += 1;
212
- const id = `#${seq}`;
213
- const ts = typeof performance !== "undefined" && performance.now ? performance.now().toFixed(1) : Date.now();
214
- console.warn(`${id} [${tag}] @${ts}ms`, ...args);
215
- }
216
- function error(tag, ...args) {
217
- if (!DEBUG) return;
218
- console.error(`[${tag}]`, ...args);
219
- }
220
-
221
- //#endregion
222
- //#region src/utils/height.ts
223
- function createHeightManager(container, computeNext) {
224
- let raf = null;
225
- let debounceTimer = null;
226
- let lastApplied = -1;
227
- let suppressed = false;
228
- const HYSTERESIS_PX = 12;
229
- const DEBOUNCE_MS = 0;
230
- function apply() {
231
- const next = computeNext();
232
- if (next == null) return;
233
- log("heightManager", "computeNext ->", {
234
- next,
235
- lastApplied
236
- });
237
- if (!Number.isFinite(next) || next <= 0) {
238
- log("heightManager", "invalid next height, ignoring", next);
239
- return;
240
- }
241
- if (lastApplied !== -1 && Math.abs(next - lastApplied) <= HYSTERESIS_PX) return;
242
- if (next === lastApplied) return;
243
- suppressed = true;
244
- container.style.height = `${next}px`;
245
- lastApplied = next;
246
- log("heightManager", "applied height ->", next);
247
- queueMicrotask(() => {
248
- suppressed = false;
249
- });
250
- }
251
- function scheduleApply() {
252
- if (debounceTimer != null) {
253
- clearTimeout(debounceTimer);
254
- debounceTimer = null;
255
- }
256
- if (DEBOUNCE_MS === 0) {
257
- if (raf != null) return;
258
- raf = requestAnimationFrame(() => {
259
- raf = null;
260
- apply();
261
- });
262
- return;
263
- }
264
- debounceTimer = setTimeout(() => {
265
- debounceTimer = null;
266
- if (raf != null) return;
267
- raf = requestAnimationFrame(() => {
268
- raf = null;
269
- apply();
270
- });
271
- }, DEBOUNCE_MS);
272
- }
273
- function update() {
274
- scheduleApply();
275
- }
276
- function dispose() {
277
- if (raf != null) {
278
- cancelAnimationFrame(raf);
279
- raf = null;
280
- }
281
- if (debounceTimer != null) {
282
- clearTimeout(debounceTimer);
283
- debounceTimer = null;
284
- }
285
- }
286
- function isSuppressed() {
287
- return suppressed;
288
- }
289
- function getLastApplied() {
290
- return lastApplied;
291
- }
292
- return {
293
- update,
294
- dispose,
295
- isSuppressed,
296
- getLastApplied
297
- };
298
- }
299
-
300
- //#endregion
301
- //#region src/utils/raf.ts
302
- /**
303
- * Create a per-instance RAF scheduler that coalesces tasks by "kind" within
304
- * the same instance. Instances are isolated so different editors won't
305
- * cancel each other's scheduled work.
306
- */
307
- function createRafScheduler(timeSource) {
308
- const ids = {};
309
- const ts = timeSource ?? {
310
- requestAnimationFrame: (cb) => requestAnimationFrame(cb),
311
- cancelAnimationFrame: (id) => cancelAnimationFrame(id)
312
- };
313
- function schedule(kind, cb) {
314
- const existing = ids[kind];
315
- if (existing != null) ts.cancelAnimationFrame(existing);
316
- ids[kind] = ts.requestAnimationFrame((t) => {
317
- ids[kind] = null;
318
- cb(t);
319
- });
320
- }
321
- function cancel(kind) {
322
- const id = ids[kind];
323
- if (id != null) {
324
- ts.cancelAnimationFrame(id);
325
- ids[kind] = null;
326
- }
327
- }
328
- return {
329
- schedule,
330
- cancel
331
- };
332
- }
333
-
334
- //#endregion
335
- //#region src/utils/scroll.ts
336
- function createScrollWatcherForEditor(ed, opts) {
337
- var _ed$getScrollTop, _ed$onDidScrollChange;
338
- const initial = ((_ed$getScrollTop = ed.getScrollTop) === null || _ed$getScrollTop === void 0 ? void 0 : _ed$getScrollTop.call(ed)) ?? 0;
339
- opts.setLast(initial);
340
- log("scrollWatcher", "initial scrollTop=", initial);
341
- let suppressedExternally = false;
342
- const THRESHOLD_PX = 6;
343
- let domNode = null;
344
- let interactionListener = null;
345
- const listener = (e) => {
346
- var _ed$getScrollTop2;
347
- if (suppressedExternally) {
348
- log("scrollWatcher", "suppressedExternally, ignoring event");
349
- return;
350
- }
351
- 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;
352
- const delta = currentTop - opts.getLast();
353
- opts.setLast(currentTop);
354
- if (Math.abs(delta) < THRESHOLD_PX) {
355
- log("scrollWatcher", "small delta ignored", delta);
356
- try {
357
- const scrollHeight = typeof ed.getScrollHeight === "function" ? ed.getScrollHeight() : void 0;
358
- const li = typeof ed.getLayoutInfo === "function" ? ed.getLayoutInfo() : void 0;
359
- const viewportH = (li === null || li === void 0 ? void 0 : li.height) ?? void 0;
360
- if (typeof scrollHeight === "number" && typeof viewportH === "number") {
361
- const distance = scrollHeight - (currentTop + viewportH);
362
- if (distance <= Math.max(THRESHOLD_PX, 0)) {
363
- log("scrollWatcher", "small delta but at bottom, maybe resume", { distance });
364
- opts.onMaybeResume();
365
- }
366
- }
367
- } catch {}
368
- return;
369
- }
370
- log("scrollWatcher", "delta=", delta, "currentTop=", currentTop);
371
- if (delta < 0) {
372
- log("scrollWatcher", "pause detected delta=", delta);
373
- opts.onPause();
374
- return;
375
- }
376
- log("scrollWatcher", "maybe resume delta=", delta);
377
- opts.onMaybeResume();
378
- };
379
- const disp = ((_ed$onDidScrollChange = ed.onDidScrollChange) === null || _ed$onDidScrollChange === void 0 ? void 0 : _ed$onDidScrollChange.call(ed, listener)) ?? null;
380
- const api = {
381
- dispose() {
382
- try {
383
- if (disp && typeof disp.dispose === "function") disp.dispose();
384
- else if (typeof disp === "function") disp();
385
- } catch {}
386
- log("scrollWatcher", "dispose");
387
- },
388
- setSuppressed(v) {
389
- const newVal = !!v;
390
- if (newVal === suppressedExternally) return;
391
- suppressedExternally = newVal;
392
- log("scrollWatcher", "setSuppressed =>", suppressedExternally);
393
- try {
394
- if (!domNode && typeof ed.getDomNode === "function") domNode = ed.getDomNode();
395
- if (suppressedExternally && domNode) {
396
- if (!interactionListener) {
397
- interactionListener = () => {
398
- try {
399
- var _ed$getScrollTop3;
400
- log("scrollWatcher", "user interaction detected while suppressed, cancelling suppression");
401
- opts.onPause();
402
- suppressedExternally = false;
403
- const cur = ((_ed$getScrollTop3 = ed.getScrollTop) === null || _ed$getScrollTop3 === void 0 ? void 0 : _ed$getScrollTop3.call(ed)) ?? 0;
404
- opts.setLast(cur);
405
- try {
406
- const scrollHeight = typeof ed.getScrollHeight === "function" ? ed.getScrollHeight() : void 0;
407
- const li = typeof ed.getLayoutInfo === "function" ? ed.getLayoutInfo() : void 0;
408
- const viewportH = (li === null || li === void 0 ? void 0 : li.height) ?? void 0;
409
- if (typeof scrollHeight === "number" && typeof viewportH === "number") {
410
- const distance = scrollHeight - (cur + viewportH);
411
- if (distance <= Math.max(THRESHOLD_PX, 0)) {
412
- log("scrollWatcher", "interaction moved to bottom, maybe resume", { distance });
413
- opts.onMaybeResume();
414
- }
415
- }
416
- } catch {}
417
- if (domNode && interactionListener) {
418
- domNode.removeEventListener("wheel", interactionListener, { passive: true });
419
- domNode.removeEventListener("pointerdown", interactionListener);
420
- domNode.removeEventListener("touchstart", interactionListener);
421
- }
422
- interactionListener = null;
423
- } catch {}
424
- };
425
- domNode.addEventListener("wheel", interactionListener, { passive: true });
426
- domNode.addEventListener("pointerdown", interactionListener);
427
- domNode.addEventListener("touchstart", interactionListener);
428
- }
429
- } else if (domNode && interactionListener) {
430
- domNode.removeEventListener("wheel", interactionListener, { passive: true });
431
- domNode.removeEventListener("pointerdown", interactionListener);
432
- domNode.removeEventListener("touchstart", interactionListener);
433
- interactionListener = null;
434
- }
435
- } catch {}
436
- }
437
- };
438
- return api;
439
- }
440
-
441
- //#endregion
442
- //#region src/core/DiffEditorManager.ts
443
- var DiffEditorManager = class {
444
- diffEditorView = null;
445
- originalModel = null;
446
- modifiedModel = null;
447
- lastContainer = null;
448
- lastKnownOriginalCode = null;
449
- lastKnownModifiedCode = null;
450
- lastKnownModifiedLineCount = null;
451
- pendingDiffUpdate = null;
452
- shouldAutoScrollDiff = true;
453
- diffScrollWatcher = null;
454
- lastScrollTopDiff = 0;
455
- _hasScrollBar = false;
456
- cachedScrollHeightDiff = null;
457
- cachedLineHeightDiff = null;
458
- cachedComputedHeightDiff = null;
459
- lastKnownModifiedDirty = false;
460
- measureViewportDiff() {
461
- var _me$getLayoutInfo, _me$getScrollTop, _me$getScrollHeight;
462
- if (!this.diffEditorView) return null;
463
- const me = this.diffEditorView.getModifiedEditor();
464
- const li = ((_me$getLayoutInfo = me.getLayoutInfo) === null || _me$getLayoutInfo === void 0 ? void 0 : _me$getLayoutInfo.call(me)) ?? null;
465
- const lineHeight = this.cachedLineHeightDiff ?? me.getOption(monaco_shim_exports.editor.EditorOption.lineHeight);
466
- const scrollTop = ((_me$getScrollTop = me.getScrollTop) === null || _me$getScrollTop === void 0 ? void 0 : _me$getScrollTop.call(me)) ?? this.lastScrollTopDiff ?? 0;
467
- 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;
468
- const computedHeight = this.cachedComputedHeightDiff ?? this.computedHeight();
469
- this.cachedLineHeightDiff = lineHeight;
470
- this.cachedScrollHeightDiff = scrollHeight;
471
- this.cachedComputedHeightDiff = computedHeight;
472
- this.lastScrollTopDiff = scrollTop;
473
- return {
474
- me,
475
- li,
476
- lineHeight,
477
- scrollTop,
478
- scrollHeight,
479
- computedHeight
480
- };
481
- }
482
- lastRevealLineDiff = null;
483
- revealTicketDiff = 0;
484
- revealDebounceIdDiff = null;
485
- revealDebounceMs = defaultRevealDebounceMs;
486
- revealIdleTimerIdDiff = null;
487
- revealStrategyOption;
488
- revealBatchOnIdleMsOption;
489
- scrollWatcherSuppressionMs = 500;
490
- diffScrollWatcherSuppressionTimer = null;
491
- appendBufferDiff = [];
492
- appendBufferDiffScheduled = false;
493
- rafScheduler = createRafScheduler();
494
- diffHeightManager = null;
495
- constructor(options, maxHeightValue, maxHeightCSS, autoScrollOnUpdate, autoScrollInitial, autoScrollThresholdPx, autoScrollThresholdLines, diffAutoScroll, revealDebounceMsOption) {
496
- this.options = options;
497
- this.maxHeightValue = maxHeightValue;
498
- this.maxHeightCSS = maxHeightCSS;
499
- this.autoScrollOnUpdate = autoScrollOnUpdate;
500
- this.autoScrollInitial = autoScrollInitial;
501
- this.autoScrollThresholdPx = autoScrollThresholdPx;
502
- this.autoScrollThresholdLines = autoScrollThresholdLines;
503
- this.diffAutoScroll = diffAutoScroll;
504
- this.revealDebounceMsOption = revealDebounceMsOption;
505
- }
506
- computedHeight() {
507
- var _originalEditor$getMo, _modifiedEditor$getMo, _originalEditor$getSc, _modifiedEditor$getSc;
508
- if (!this.diffEditorView) return Math.min(1 * 18 + padding, this.maxHeightValue);
509
- const modifiedEditor = this.diffEditorView.getModifiedEditor();
510
- const originalEditor = this.diffEditorView.getOriginalEditor();
511
- const lineHeight = modifiedEditor.getOption(monaco_shim_exports.editor.EditorOption.lineHeight);
512
- const oCount = ((_originalEditor$getMo = originalEditor.getModel()) === null || _originalEditor$getMo === void 0 ? void 0 : _originalEditor$getMo.getLineCount()) ?? 1;
513
- const mCount = ((_modifiedEditor$getMo = modifiedEditor.getModel()) === null || _modifiedEditor$getMo === void 0 ? void 0 : _modifiedEditor$getMo.getLineCount()) ?? 1;
514
- const lineCount = Math.max(oCount, mCount);
515
- const fromLines = lineCount * lineHeight + padding;
516
- 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);
517
- const desired = Math.max(fromLines, scrollH);
518
- return Math.min(desired, this.maxHeightValue);
519
- }
520
- isOverflowAutoDiff() {
521
- return !!this.lastContainer && this.lastContainer.style.overflow === "auto";
522
- }
523
- shouldPerformImmediateRevealDiff() {
524
- return this.autoScrollOnUpdate && this.shouldAutoScrollDiff && this.hasVerticalScrollbarModified() && this.isOverflowAutoDiff();
525
- }
526
- suppressScrollWatcherDiff(ms) {
527
- if (!this.diffScrollWatcher || typeof this.diffScrollWatcher.setSuppressed !== "function") return;
528
- if (this.diffScrollWatcherSuppressionTimer != null) {
529
- clearTimeout(this.diffScrollWatcherSuppressionTimer);
530
- this.diffScrollWatcherSuppressionTimer = null;
531
- }
532
- this.diffScrollWatcher.setSuppressed(true);
533
- this.diffScrollWatcherSuppressionTimer = setTimeout(() => {
534
- try {
535
- this.diffScrollWatcher.setSuppressed(false);
536
- } catch {}
537
- this.diffScrollWatcherSuppressionTimer = null;
538
- }, ms);
539
- }
540
- hasVerticalScrollbarModified() {
541
- if (!this.diffEditorView) return false;
542
- if (this._hasScrollBar) return true;
543
- const m = this.measureViewportDiff();
544
- if (!m) return false;
545
- const epsilon = Math.max(2, Math.round(m.lineHeight / 8));
546
- return this._hasScrollBar = m.scrollHeight > m.computedHeight + Math.max(padding / 2, epsilon);
547
- }
548
- userIsNearBottomDiff() {
549
- if (!this.diffEditorView) return true;
550
- const m = this.measureViewportDiff();
551
- if (!m || !m.li) return true;
552
- const lineThreshold = (this.autoScrollThresholdLines ?? 0) * m.lineHeight;
553
- const threshold = Math.max(lineThreshold || 0, this.autoScrollThresholdPx || 0);
554
- const distance = m.scrollHeight - (m.scrollTop + m.li.height);
555
- return distance <= threshold;
556
- }
557
- maybeScrollDiffToBottom(targetLine, prevLineOverride) {
558
- this.rafScheduler.schedule("maybe-scroll-diff", () => {
559
- log("diff", "maybeScrollDiffToBottom called", {
560
- targetLine,
561
- prevLineOverride,
562
- diffAutoScroll: this.diffAutoScroll,
563
- autoScrollOnUpdate: this.autoScrollOnUpdate,
564
- shouldAutoScrollDiff: this.shouldAutoScrollDiff
565
- });
566
- if (!this.diffEditorView) return;
567
- const hasV = this.hasVerticalScrollbarModified();
568
- log("diff", "hasVerticalScrollbarModified ->", hasV);
569
- if (!(this.diffAutoScroll && this.autoScrollOnUpdate && this.shouldAutoScrollDiff && hasV)) return;
570
- const me = this.diffEditorView.getModifiedEditor();
571
- const model = me.getModel();
572
- const currentLine = (model === null || model === void 0 ? void 0 : model.getLineCount()) ?? 1;
573
- const line = targetLine ?? currentLine;
574
- const prevLine = typeof prevLineOverride === "number" ? prevLineOverride : this.lastKnownModifiedLineCount ?? -1;
575
- log("diff", "scroll metrics", {
576
- prevLine,
577
- currentLine,
578
- line,
579
- lastRevealLineDiff: this.lastRevealLineDiff
580
- });
581
- if (prevLine !== -1 && prevLine === currentLine && line === currentLine) return;
582
- if (this.lastRevealLineDiff !== null && this.lastRevealLineDiff === line) return;
583
- const batchMs = this.revealBatchOnIdleMsOption ?? this.options.revealBatchOnIdleMs ?? defaultRevealBatchOnIdleMs;
584
- log("diff", "reveal timing", {
585
- batchMs,
586
- revealDebounceMs: this.revealDebounceMs,
587
- revealDebounceMsOption: this.revealDebounceMsOption
588
- });
589
- if (typeof batchMs === "number" && batchMs > 0) {
590
- if (hasV) {
591
- const ticket$1 = ++this.revealTicketDiff;
592
- log("diff", "has scrollbar -> immediate ticketed reveal", {
593
- ticket: ticket$1,
594
- line
595
- });
596
- this.performRevealDiffTicketed(line, ticket$1);
597
- return;
598
- }
599
- if (this.revealIdleTimerIdDiff != null) clearTimeout(this.revealIdleTimerIdDiff);
600
- const ticket = ++this.revealTicketDiff;
601
- log("diff", "scheduling idle reveal", {
602
- ticket,
603
- batchMs,
604
- line
605
- });
606
- this.revealIdleTimerIdDiff = setTimeout(() => {
607
- this.revealIdleTimerIdDiff = null;
608
- this.performRevealDiffTicketed(line, ticket);
609
- }, batchMs);
610
- return;
611
- }
612
- if (this.revealDebounceIdDiff != null) {
613
- clearTimeout(this.revealDebounceIdDiff);
614
- this.revealDebounceIdDiff = null;
615
- }
616
- const ms = typeof this.revealDebounceMs === "number" && this.revealDebounceMs > 0 ? this.revealDebounceMs : typeof this.revealDebounceMsOption === "number" && this.revealDebounceMsOption > 0 ? this.revealDebounceMsOption : this.revealDebounceMs;
617
- this.revealDebounceIdDiff = setTimeout(() => {
618
- this.revealDebounceIdDiff = null;
619
- const ticket = ++this.revealTicketDiff;
620
- log("diff", "debounced reveal firing", {
621
- ticket,
622
- line
623
- });
624
- this.performRevealDiffTicketed(line, ticket);
625
- }, ms);
626
- this.lastKnownModifiedLineCount = currentLine;
627
- });
628
- }
629
- performRevealDiffTicketed(line, ticket) {
630
- this.rafScheduler.schedule("revealDiff", () => {
631
- var _editor;
632
- if (this.diffScrollWatcher) {
633
- log("diff", "performRevealDiffTicketed - suppressing watcher", {
634
- ticket,
635
- line,
636
- ms: this.scrollWatcherSuppressionMs
637
- });
638
- this.suppressScrollWatcherDiff(this.scrollWatcherSuppressionMs);
639
- }
640
- if (ticket !== this.revealTicketDiff) return;
641
- log("diff", "performRevealDiffTicketed - performing reveal", {
642
- ticket,
643
- line
644
- });
645
- const strategy = this.revealStrategyOption ?? this.options.revealStrategy ?? "centerIfOutside";
646
- const ScrollType = monaco_shim_exports.ScrollType || ((_editor = monaco_shim_exports.editor) === null || _editor === void 0 ? void 0 : _editor.ScrollType);
647
- const smooth = ScrollType && typeof ScrollType.Smooth !== "undefined" ? ScrollType.Smooth : void 0;
648
- try {
649
- const me = this.diffEditorView.getModifiedEditor();
650
- if (strategy === "bottom") if (typeof smooth !== "undefined") me.revealLine(line, smooth);
651
- else me.revealLine(line);
652
- else if (strategy === "center") if (typeof smooth !== "undefined") me.revealLineInCenter(line, smooth);
653
- else me.revealLineInCenter(line);
654
- else if (typeof smooth !== "undefined") me.revealLineInCenterIfOutsideViewport(line, smooth);
655
- else me.revealLineInCenterIfOutsideViewport(line);
656
- } catch {
657
- try {
658
- this.diffEditorView.getModifiedEditor().revealLine(line);
659
- } catch {}
660
- }
661
- this.lastRevealLineDiff = line;
662
- log("diff", "performRevealDiffTicketed - revealed", {
663
- line,
664
- lastRevealLineDiff: this.lastRevealLineDiff
665
- });
666
- try {
667
- var _this$diffEditorView, _this$diffEditorView$, _this$diffEditorView$2;
668
- this.shouldAutoScrollDiff = true;
669
- this.lastScrollTopDiff = ((_this$diffEditorView = this.diffEditorView) === null || _this$diffEditorView === void 0 || (_this$diffEditorView$2 = (_this$diffEditorView$ = _this$diffEditorView.getModifiedEditor()).getScrollTop) === null || _this$diffEditorView$2 === void 0 ? void 0 : _this$diffEditorView$2.call(_this$diffEditorView$)) ?? this.lastScrollTopDiff;
670
- } catch {}
671
- });
672
- }
673
- performImmediateRevealDiff(line, ticket) {
674
- var _editor2;
675
- if (!this.diffEditorView) return;
676
- if (ticket !== this.revealTicketDiff) return;
677
- const ScrollType = monaco_shim_exports.ScrollType || ((_editor2 = monaco_shim_exports.editor) === null || _editor2 === void 0 ? void 0 : _editor2.ScrollType);
678
- const immediate = ScrollType && typeof ScrollType.Immediate !== "undefined" ? ScrollType.Immediate : void 0;
679
- const me = this.diffEditorView.getModifiedEditor();
680
- if (typeof immediate !== "undefined") me.revealLine(line, immediate);
681
- else me.revealLine(line);
682
- this.measureViewportDiff();
683
- log("diff", "performImmediateRevealDiff", {
684
- line,
685
- ticket
686
- });
687
- try {
688
- var _this$diffEditorView2, _this$diffEditorView3, _this$diffEditorView4;
689
- this.shouldAutoScrollDiff = true;
690
- this.lastScrollTopDiff = ((_this$diffEditorView2 = this.diffEditorView) === null || _this$diffEditorView2 === void 0 || (_this$diffEditorView4 = (_this$diffEditorView3 = _this$diffEditorView2.getModifiedEditor()).getScrollTop) === null || _this$diffEditorView4 === void 0 ? void 0 : _this$diffEditorView4.call(_this$diffEditorView3)) ?? this.lastScrollTopDiff;
691
- } catch {}
692
- }
693
- scheduleImmediateRevealAfterLayoutDiff(line) {
694
- const ticket = ++this.revealTicketDiff;
695
- this.rafScheduler.schedule("immediate-reveal-diff", async () => {
696
- const target = this.diffEditorView && this.diffHeightManager ? Math.min(this.computedHeight(), this.maxHeightValue) : -1;
697
- if (target !== -1 && this.diffHeightManager) {
698
- if (this.lastContainer) this.lastContainer.style.height = `${target}px`;
699
- await this.waitForHeightAppliedDiff(target);
700
- }
701
- this.performImmediateRevealDiff(line, ticket);
702
- });
703
- }
704
- waitForHeightAppliedDiff(target, timeoutMs = 500) {
705
- return new Promise((resolve) => {
706
- const start = typeof performance !== "undefined" && performance.now ? performance.now() : Date.now();
707
- const check = () => {
708
- const applied = this.lastContainer ? Number.parseFloat((this.lastContainer.style.height || "").replace("px", "")) || 0 : -1;
709
- if (applied >= target - 1) {
710
- resolve();
711
- return;
712
- }
713
- if ((typeof performance !== "undefined" && performance.now ? performance.now() : Date.now()) - start > timeoutMs) {
714
- resolve();
715
- return;
716
- }
717
- requestAnimationFrame(check);
718
- };
719
- check();
720
- });
721
- }
722
- async createDiffEditor(container, originalCode, modifiedCode, language, currentTheme) {
723
- var _me$getScrollHeight2, _me$getOption, _oEditor$onDidContent, _mEditor$onDidContent;
724
- this.cleanup();
725
- this.lastContainer = container;
726
- container.style.overflow = "hidden";
727
- container.style.maxHeight = this.maxHeightCSS;
728
- const lang = processedLanguage(language) || language;
729
- this.originalModel = monaco_shim_exports.editor.createModel(originalCode, lang);
730
- this.modifiedModel = monaco_shim_exports.editor.createModel(modifiedCode, lang);
731
- this.diffEditorView = monaco_shim_exports.editor.createDiffEditor(container, {
732
- automaticLayout: true,
733
- scrollBeyondLastLine: false,
734
- renderSideBySide: true,
735
- originalEditable: false,
736
- readOnly: this.options.readOnly ?? true,
737
- minimap: { enabled: false },
738
- theme: currentTheme,
739
- contextmenu: false,
740
- scrollbar: {
741
- ...defaultScrollbar,
742
- ...this.options.scrollbar || {}
743
- },
744
- ...this.options
745
- });
746
- monaco_shim_exports.editor.setTheme(currentTheme);
747
- this.diffEditorView.setModel({
748
- original: this.originalModel,
749
- modified: this.modifiedModel
750
- });
751
- this.lastKnownOriginalCode = originalCode;
752
- this.lastKnownModifiedCode = modifiedCode;
753
- this.shouldAutoScrollDiff = !!(this.autoScrollInitial && this.diffAutoScroll);
754
- if (this.diffScrollWatcher) {
755
- this.diffScrollWatcher.dispose();
756
- this.diffScrollWatcher = null;
757
- }
758
- if (this.diffAutoScroll) {
759
- const me$1 = this.diffEditorView.getModifiedEditor();
760
- this.diffScrollWatcher = createScrollWatcherForEditor(me$1, {
761
- onPause: () => {
762
- this.shouldAutoScrollDiff = false;
763
- },
764
- onMaybeResume: () => {
765
- this.rafScheduler.schedule("maybe-resume-diff", () => {
766
- this.shouldAutoScrollDiff = this.userIsNearBottomDiff();
767
- });
768
- },
769
- getLast: () => this.lastScrollTopDiff,
770
- setLast: (v) => {
771
- this.lastScrollTopDiff = v;
772
- }
773
- });
774
- }
775
- log("diff", "createDiffEditor", {
776
- autoScrollInitial: this.autoScrollInitial,
777
- diffAutoScroll: this.diffAutoScroll
778
- });
779
- const MIN_VISIBLE_HEIGHT = Math.min(120, this.maxHeightValue);
780
- container.style.minHeight = `${MIN_VISIBLE_HEIGHT}px`;
781
- if (this.diffHeightManager) {
782
- this.diffHeightManager.dispose();
783
- this.diffHeightManager = null;
784
- }
785
- this.diffHeightManager = createHeightManager(container, () => this.computedHeight());
786
- this.diffHeightManager.update();
787
- const initialComputed = this.computedHeight();
788
- if (initialComputed >= this.maxHeightValue - 1) {
789
- container.style.height = `${this.maxHeightValue}px`;
790
- container.style.overflow = "auto";
791
- }
792
- const me = this.diffEditorView.getModifiedEditor();
793
- this.cachedScrollHeightDiff = ((_me$getScrollHeight2 = me.getScrollHeight) === null || _me$getScrollHeight2 === void 0 ? void 0 : _me$getScrollHeight2.call(me)) ?? null;
794
- this.cachedLineHeightDiff = ((_me$getOption = me.getOption) === null || _me$getOption === void 0 ? void 0 : _me$getOption.call(me, monaco_shim_exports.editor.EditorOption.lineHeight)) ?? null;
795
- this.cachedComputedHeightDiff = this.computedHeight();
796
- const oEditor = this.diffEditorView.getOriginalEditor();
797
- const mEditor = this.diffEditorView.getModifiedEditor();
798
- (_oEditor$onDidContent = oEditor.onDidContentSizeChange) === null || _oEditor$onDidContent === void 0 || _oEditor$onDidContent.call(oEditor, () => {
799
- this._hasScrollBar = false;
800
- this.rafScheduler.schedule("content-size-change-diff", () => {
801
- var _oEditor$getScrollHei, _oEditor$getOption, _this$diffHeightManag, _this$diffHeightManag2;
802
- this.cachedScrollHeightDiff = ((_oEditor$getScrollHei = oEditor.getScrollHeight) === null || _oEditor$getScrollHei === void 0 ? void 0 : _oEditor$getScrollHei.call(oEditor)) ?? this.cachedScrollHeightDiff;
803
- 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;
804
- this.cachedComputedHeightDiff = this.computedHeight();
805
- if ((_this$diffHeightManag = this.diffHeightManager) === null || _this$diffHeightManag === void 0 ? void 0 : _this$diffHeightManag.isSuppressed()) return;
806
- (_this$diffHeightManag2 = this.diffHeightManager) === null || _this$diffHeightManag2 === void 0 || _this$diffHeightManag2.update();
807
- const computed$2 = this.computedHeight();
808
- if (this.lastContainer) {
809
- const prevOverflow = this.lastContainer.style.overflow;
810
- const newOverflow = computed$2 >= this.maxHeightValue - 1 ? "auto" : "hidden";
811
- if (prevOverflow !== newOverflow) {
812
- this.lastContainer.style.overflow = newOverflow;
813
- if (newOverflow === "auto" && this.shouldAutoScrollDiff) {
814
- var _this$modifiedModel;
815
- this.maybeScrollDiffToBottom((_this$modifiedModel = this.modifiedModel) === null || _this$modifiedModel === void 0 ? void 0 : _this$modifiedModel.getLineCount());
816
- }
817
- }
818
- }
819
- });
820
- });
821
- (_mEditor$onDidContent = mEditor.onDidContentSizeChange) === null || _mEditor$onDidContent === void 0 || _mEditor$onDidContent.call(mEditor, () => {
822
- this._hasScrollBar = false;
823
- this.rafScheduler.schedule("content-size-change-diff", () => {
824
- var _mEditor$getScrollHei, _mEditor$getOption, _this$diffHeightManag3, _this$diffHeightManag4;
825
- this.cachedScrollHeightDiff = ((_mEditor$getScrollHei = mEditor.getScrollHeight) === null || _mEditor$getScrollHei === void 0 ? void 0 : _mEditor$getScrollHei.call(mEditor)) ?? this.cachedScrollHeightDiff;
826
- 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;
827
- this.cachedComputedHeightDiff = this.computedHeight();
828
- if ((_this$diffHeightManag3 = this.diffHeightManager) === null || _this$diffHeightManag3 === void 0 ? void 0 : _this$diffHeightManag3.isSuppressed()) return;
829
- (_this$diffHeightManag4 = this.diffHeightManager) === null || _this$diffHeightManag4 === void 0 || _this$diffHeightManag4.update();
830
- const computed$2 = this.computedHeight();
831
- if (this.lastContainer) {
832
- const prevOverflow = this.lastContainer.style.overflow;
833
- const newOverflow = computed$2 >= this.maxHeightValue - 1 ? "auto" : "hidden";
834
- if (prevOverflow !== newOverflow) {
835
- this.lastContainer.style.overflow = newOverflow;
836
- if (newOverflow === "auto" && this.shouldAutoScrollDiff) {
837
- var _this$modifiedModel2;
838
- this.maybeScrollDiffToBottom((_this$modifiedModel2 = this.modifiedModel) === null || _this$modifiedModel2 === void 0 ? void 0 : _this$modifiedModel2.getLineCount());
839
- }
840
- }
841
- }
842
- });
843
- });
844
- mEditor.onDidChangeModelContent(() => {
845
- this.lastKnownModifiedDirty = true;
846
- this.rafScheduler.schedule("sync-last-known-modified", () => this.syncLastKnownModified());
847
- });
848
- this.maybeScrollDiffToBottom(this.modifiedModel.getLineCount(), this.lastKnownModifiedLineCount ?? void 0);
849
- return this.diffEditorView;
850
- }
851
- updateDiff(originalCode, modifiedCode, codeLanguage) {
852
- if (!this.diffEditorView || !this.originalModel || !this.modifiedModel) return;
853
- const plang = codeLanguage ? processedLanguage(codeLanguage) : void 0;
854
- if (plang && (this.originalModel.getLanguageId() !== plang || this.modifiedModel.getLanguageId() !== plang)) {
855
- this.pendingDiffUpdate = {
856
- original: originalCode,
857
- modified: modifiedCode,
858
- lang: codeLanguage
859
- };
860
- this.rafScheduler.schedule("diff", () => this.flushPendingDiffUpdate());
861
- return;
862
- }
863
- if (this.lastKnownOriginalCode == null) this.lastKnownOriginalCode = this.originalModel.getValue();
864
- if (this.lastKnownModifiedCode == null) this.lastKnownModifiedCode = this.modifiedModel.getValue();
865
- const prevO = this.lastKnownOriginalCode;
866
- const prevM = this.lastKnownModifiedCode;
867
- let didImmediate = false;
868
- if (originalCode !== prevO && originalCode.startsWith(prevO)) {
869
- this.appendToModel(this.originalModel, originalCode.slice(prevO.length));
870
- this.lastKnownOriginalCode = originalCode;
871
- didImmediate = true;
872
- }
873
- if (modifiedCode !== prevM && modifiedCode.startsWith(prevM)) {
874
- this.appendModified(modifiedCode.slice(prevM.length));
875
- this.lastKnownModifiedCode = modifiedCode;
876
- didImmediate = true;
877
- }
878
- if (originalCode !== this.lastKnownOriginalCode || modifiedCode !== this.lastKnownModifiedCode) {
879
- this.pendingDiffUpdate = {
880
- original: originalCode,
881
- modified: modifiedCode
882
- };
883
- this.rafScheduler.schedule("diff", () => this.flushPendingDiffUpdate());
884
- } else if (didImmediate) {}
885
- }
886
- updateOriginal(newCode, codeLanguage) {
887
- if (!this.diffEditorView || !this.originalModel) return;
888
- if (codeLanguage) {
889
- const lang = processedLanguage(codeLanguage);
890
- if (lang && this.originalModel.getLanguageId() !== lang) monaco_shim_exports.editor.setModelLanguage(this.originalModel, lang);
891
- }
892
- const prev = this.lastKnownOriginalCode ?? this.originalModel.getValue();
893
- if (prev === newCode) return;
894
- if (newCode.startsWith(prev) && prev.length < newCode.length) this.appendToModel(this.originalModel, newCode.slice(prev.length));
895
- else this.applyMinimalEditToModel(this.originalModel, prev, newCode);
896
- this.lastKnownOriginalCode = newCode;
897
- }
898
- updateModified(newCode, codeLanguage) {
899
- if (!this.diffEditorView || !this.modifiedModel) return;
900
- if (codeLanguage) {
901
- const lang = processedLanguage(codeLanguage);
902
- if (lang && this.modifiedModel.getLanguageId() !== lang) monaco_shim_exports.editor.setModelLanguage(this.modifiedModel, lang);
903
- }
904
- const prev = this.lastKnownModifiedCode ?? this.modifiedModel.getValue();
905
- if (prev === newCode) return;
906
- if (newCode.startsWith(prev) && prev.length < newCode.length) this.appendModified(newCode.slice(prev.length), codeLanguage);
907
- else {
908
- this.flushModifiedAppendBufferSync();
909
- const prevAfterFlush = this.modifiedModel.getValue();
910
- const prevLine = this.modifiedModel.getLineCount();
911
- this.applyMinimalEditToModel(this.modifiedModel, prevAfterFlush, newCode);
912
- const newLine = this.modifiedModel.getLineCount();
913
- if (newLine !== prevLine) {
914
- const shouldImmediate = this.shouldPerformImmediateRevealDiff();
915
- if (shouldImmediate) this.suppressScrollWatcherDiff(this.scrollWatcherSuppressionMs + 800);
916
- const computed$2 = this.computedHeight();
917
- if (computed$2 >= this.maxHeightValue - 1 && this.lastContainer) {
918
- this.lastContainer.style.height = `${this.maxHeightValue}px`;
919
- this.lastContainer.style.overflow = "auto";
920
- }
921
- if (shouldImmediate) this.scheduleImmediateRevealAfterLayoutDiff(newLine);
922
- else this.maybeScrollDiffToBottom(newLine, prevLine);
923
- if (this.autoScrollOnUpdate && this.shouldAutoScrollDiff) try {
924
- var _editor3, _me2$getModel, _me2$getScrollTop;
925
- const ScrollType = monaco_shim_exports.ScrollType || ((_editor3 = monaco_shim_exports.editor) === null || _editor3 === void 0 ? void 0 : _editor3.ScrollType);
926
- const immediate = ScrollType && typeof ScrollType.Immediate !== "undefined" ? ScrollType.Immediate : void 0;
927
- const me2 = this.diffEditorView.getModifiedEditor();
928
- const targetLine = ((_me2$getModel = me2.getModel()) === null || _me2$getModel === void 0 ? void 0 : _me2$getModel.getLineCount()) ?? newLine;
929
- if (typeof immediate !== "undefined") me2.revealLine(targetLine, immediate);
930
- else me2.revealLine(targetLine);
931
- this.lastRevealLineDiff = targetLine;
932
- this.shouldAutoScrollDiff = true;
933
- this.lastScrollTopDiff = ((_me2$getScrollTop = me2.getScrollTop) === null || _me2$getScrollTop === void 0 ? void 0 : _me2$getScrollTop.call(me2)) ?? this.lastScrollTopDiff;
934
- } catch {}
935
- }
936
- }
937
- this.lastKnownModifiedCode = newCode;
938
- }
939
- appendOriginal(appendText, codeLanguage) {
940
- if (!this.diffEditorView || !this.originalModel || !appendText) return;
941
- if (codeLanguage) {
942
- const lang = processedLanguage(codeLanguage);
943
- if (lang && this.originalModel.getLanguageId() !== lang) monaco_shim_exports.editor.setModelLanguage(this.originalModel, lang);
944
- }
945
- this.appendToModel(this.originalModel, appendText);
946
- this.lastKnownOriginalCode = this.originalModel.getValue();
947
- }
948
- appendModified(appendText, codeLanguage) {
949
- if (!this.diffEditorView || !this.modifiedModel || !appendText) return;
950
- if (codeLanguage) {
951
- const lang = processedLanguage(codeLanguage);
952
- if (lang && this.modifiedModel.getLanguageId() !== lang) monaco_shim_exports.editor.setModelLanguage(this.modifiedModel, lang);
953
- }
954
- this.appendBufferDiff.push(appendText);
955
- if (!this.appendBufferDiffScheduled) {
956
- this.appendBufferDiffScheduled = true;
957
- this.rafScheduler.schedule("appendDiff", () => this.flushAppendBufferDiff());
958
- }
959
- }
960
- setLanguage(language, languages$1) {
961
- if (!languages$1.includes(language)) {
962
- console.warn(`Language "${language}" is not registered. Available languages: ${languages$1.join(", ")}`);
963
- return;
964
- }
965
- if (this.originalModel && this.originalModel.getLanguageId() !== language) monaco_shim_exports.editor.setModelLanguage(this.originalModel, language);
966
- if (this.modifiedModel && this.modifiedModel.getLanguageId() !== language) monaco_shim_exports.editor.setModelLanguage(this.modifiedModel, language);
967
- }
968
- getDiffEditorView() {
969
- return this.diffEditorView;
970
- }
971
- getDiffModels() {
972
- return {
973
- original: this.originalModel,
974
- modified: this.modifiedModel
975
- };
976
- }
977
- cleanup() {
978
- this.rafScheduler.cancel("diff");
979
- this.pendingDiffUpdate = null;
980
- this.rafScheduler.cancel("appendDiff");
981
- this.appendBufferDiffScheduled = false;
982
- this.appendBufferDiff.length = 0;
983
- this.rafScheduler.cancel("content-size-change-diff");
984
- this.rafScheduler.cancel("sync-last-known-modified");
985
- if (this.diffScrollWatcher) {
986
- this.diffScrollWatcher.dispose();
987
- this.diffScrollWatcher = null;
988
- }
989
- if (this.diffHeightManager) {
990
- this.diffHeightManager.dispose();
991
- this.diffHeightManager = null;
992
- }
993
- if (this.diffEditorView) {
994
- this.diffEditorView.dispose();
995
- this.diffEditorView = null;
996
- }
997
- if (this.originalModel) {
998
- this.originalModel.dispose();
999
- this.originalModel = null;
1000
- }
1001
- if (this.modifiedModel) {
1002
- this.modifiedModel.dispose();
1003
- this.modifiedModel = null;
1004
- }
1005
- this.lastKnownOriginalCode = null;
1006
- this.lastKnownModifiedCode = null;
1007
- if (this.lastContainer) {
1008
- this.lastContainer.innerHTML = "";
1009
- this.lastContainer = null;
1010
- }
1011
- if (this.revealDebounceIdDiff != null) {
1012
- clearTimeout(this.revealDebounceIdDiff);
1013
- this.revealDebounceIdDiff = null;
1014
- }
1015
- if (this.revealIdleTimerIdDiff != null) {
1016
- clearTimeout(this.revealIdleTimerIdDiff);
1017
- this.revealIdleTimerIdDiff = null;
1018
- }
1019
- if (this.diffScrollWatcherSuppressionTimer != null) {
1020
- clearTimeout(this.diffScrollWatcherSuppressionTimer);
1021
- this.diffScrollWatcherSuppressionTimer = null;
1022
- }
1023
- this.revealTicketDiff = 0;
1024
- this.lastRevealLineDiff = null;
1025
- }
1026
- safeClean() {
1027
- this.rafScheduler.cancel("diff");
1028
- this.pendingDiffUpdate = null;
1029
- this.rafScheduler.cancel("appendDiff");
1030
- this.appendBufferDiffScheduled = false;
1031
- this.appendBufferDiff.length = 0;
1032
- if (this.diffScrollWatcher) {
1033
- this.diffScrollWatcher.dispose();
1034
- this.diffScrollWatcher = null;
1035
- }
1036
- this._hasScrollBar = false;
1037
- this.shouldAutoScrollDiff = !!(this.autoScrollInitial && this.diffAutoScroll);
1038
- this.lastScrollTopDiff = 0;
1039
- if (this.diffHeightManager) {
1040
- this.diffHeightManager.dispose();
1041
- this.diffHeightManager = null;
1042
- }
1043
- if (this.revealDebounceIdDiff != null) {
1044
- clearTimeout(this.revealDebounceIdDiff);
1045
- this.revealDebounceIdDiff = null;
1046
- }
1047
- if (this.revealIdleTimerIdDiff != null) {
1048
- clearTimeout(this.revealIdleTimerIdDiff);
1049
- this.revealIdleTimerIdDiff = null;
1050
- }
1051
- if (this.diffScrollWatcherSuppressionTimer != null) {
1052
- clearTimeout(this.diffScrollWatcherSuppressionTimer);
1053
- this.diffScrollWatcherSuppressionTimer = null;
1054
- }
1055
- this.revealTicketDiff = 0;
1056
- this.lastRevealLineDiff = null;
1057
- this.rafScheduler.cancel("content-size-change-diff");
1058
- this.rafScheduler.cancel("sync-last-known-modified");
1059
- }
1060
- syncLastKnownModified() {
1061
- if (!this.diffEditorView || !this.lastKnownModifiedDirty) return;
1062
- try {
1063
- const me = this.diffEditorView.getModifiedEditor();
1064
- const model = me.getModel();
1065
- if (model) {
1066
- this.lastKnownModifiedCode = model.getValue();
1067
- this.lastKnownModifiedLineCount = model.getLineCount();
1068
- }
1069
- } finally {
1070
- this.lastKnownModifiedDirty = false;
1071
- }
1072
- }
1073
- flushPendingDiffUpdate() {
1074
- if (!this.pendingDiffUpdate || !this.diffEditorView) return;
1075
- const o = this.originalModel;
1076
- const m = this.modifiedModel;
1077
- if (!o || !m) {
1078
- this.pendingDiffUpdate = null;
1079
- return;
1080
- }
1081
- const { original, modified, lang } = this.pendingDiffUpdate;
1082
- this.pendingDiffUpdate = null;
1083
- this.flushModifiedAppendBufferSync();
1084
- if (lang) {
1085
- const plang = processedLanguage(lang);
1086
- if (plang) {
1087
- if (o.getLanguageId() !== plang) {
1088
- monaco_shim_exports.editor.setModelLanguage(o, plang);
1089
- monaco_shim_exports.editor.setModelLanguage(m, plang);
1090
- }
1091
- }
1092
- }
1093
- if (this.lastKnownOriginalCode == null) this.lastKnownOriginalCode = o.getValue();
1094
- if (this.lastKnownModifiedCode == null) this.lastKnownModifiedCode = m.getValue();
1095
- const prevO = this.lastKnownOriginalCode;
1096
- if (prevO !== original) {
1097
- if (original.startsWith(prevO) && prevO.length < original.length) this.appendToModel(o, original.slice(prevO.length));
1098
- else this.applyMinimalEditToModel(o, prevO, original);
1099
- this.lastKnownOriginalCode = original;
1100
- }
1101
- const prevM = m.getValue();
1102
- const prevMLineCount = m.getLineCount();
1103
- if (prevM !== modified) {
1104
- if (modified.startsWith(prevM) && prevM.length < modified.length) this.appendToModel(m, modified.slice(prevM.length));
1105
- else this.applyMinimalEditToModel(m, prevM, modified);
1106
- this.lastKnownModifiedCode = modified;
1107
- const newMLineCount = m.getLineCount();
1108
- if (newMLineCount !== prevMLineCount) {
1109
- const shouldImmediate = this.shouldPerformImmediateRevealDiff();
1110
- if (shouldImmediate) this.suppressScrollWatcherDiff(this.scrollWatcherSuppressionMs + 800);
1111
- const computed$2 = this.computedHeight();
1112
- if (computed$2 >= this.maxHeightValue - 1 && this.lastContainer) {
1113
- this.lastContainer.style.height = `${this.maxHeightValue}px`;
1114
- this.lastContainer.style.overflow = "auto";
1115
- }
1116
- if (shouldImmediate) this.scheduleImmediateRevealAfterLayoutDiff(newMLineCount);
1117
- else this.maybeScrollDiffToBottom(newMLineCount, prevMLineCount);
1118
- }
1119
- }
1120
- }
1121
- flushModifiedAppendBufferSync() {
1122
- if (!this.modifiedModel) return;
1123
- if (this.appendBufferDiff.length === 0) return;
1124
- this.rafScheduler.cancel("appendDiff");
1125
- this.appendBufferDiffScheduled = false;
1126
- const text = this.appendBufferDiff.join("");
1127
- this.appendBufferDiff.length = 0;
1128
- if (!text) return;
1129
- this.appendToModel(this.modifiedModel, text);
1130
- }
1131
- async flushAppendBufferDiff() {
1132
- if (!this.diffEditorView) return;
1133
- if (this.appendBufferDiff.length === 0) return;
1134
- this.appendBufferDiffScheduled = false;
1135
- const me = this.diffEditorView.getModifiedEditor();
1136
- const model = me.getModel();
1137
- if (!model) {
1138
- this.appendBufferDiff.length = 0;
1139
- return;
1140
- }
1141
- let parts = this.appendBufferDiff.splice(0);
1142
- const prevLineInit = model.getLineCount();
1143
- const totalText = parts.join("");
1144
- const totalChars = totalText.length;
1145
- if (parts.length === 1 && totalChars > 5e3) {
1146
- const lines = totalText.split(/\r?\n/);
1147
- const chunkSize = 200;
1148
- const chunks = [];
1149
- for (let i = 0; i < lines.length; i += chunkSize) chunks.push(`${lines.slice(i, i + chunkSize).join("\n")}\n`);
1150
- if (chunks.length > 1) parts = chunks;
1151
- }
1152
- const applyChunked = parts.length > 1 && (totalChars > 2e3 || model.getLineCount && model.getLineCount() + 0 - prevLineInit > 50);
1153
- log("diff", "flushAppendBufferDiff start", {
1154
- partsCount: parts.length,
1155
- totalChars,
1156
- applyChunked
1157
- });
1158
- let prevLine = prevLineInit;
1159
- const watcherApi = this.diffScrollWatcher;
1160
- let suppressedByFlush = false;
1161
- if (watcherApi && typeof watcherApi.setSuppressed === "function") try {
1162
- if (this.diffScrollWatcherSuppressionTimer != null) {
1163
- clearTimeout(this.diffScrollWatcherSuppressionTimer);
1164
- this.diffScrollWatcherSuppressionTimer = null;
1165
- }
1166
- watcherApi.setSuppressed(true);
1167
- suppressedByFlush = true;
1168
- } catch {}
1169
- if (applyChunked) {
1170
- log("diff", "flushAppendBufferDiff applying chunked", { partsLen: parts.length });
1171
- let idx = 0;
1172
- for (const part of parts) {
1173
- if (!part) continue;
1174
- idx += 1;
1175
- log("diff", "flushAppendBufferDiff chunk", {
1176
- idx,
1177
- partLen: part.length,
1178
- prevLine
1179
- });
1180
- const lastColumn$1 = model.getLineMaxColumn(prevLine);
1181
- const range$1 = new monaco_shim_exports.Range(prevLine, lastColumn$1, prevLine, lastColumn$1);
1182
- model.applyEdits([{
1183
- range: range$1,
1184
- text: part,
1185
- forceMoveMarkers: true
1186
- }]);
1187
- this.lastKnownModifiedCode = model.getValue();
1188
- const newLine$1 = model.getLineCount();
1189
- this.lastKnownModifiedLineCount = newLine$1;
1190
- await new Promise((resolve) => typeof requestAnimationFrame !== "undefined" ? requestAnimationFrame(resolve) : setTimeout(resolve, 0));
1191
- const shouldImmediate$1 = this.shouldPerformImmediateRevealDiff();
1192
- log("diff", "flushAppendBufferDiff chunk metrics", {
1193
- idx,
1194
- newLine: newLine$1,
1195
- prevLine,
1196
- shouldImmediate: shouldImmediate$1
1197
- });
1198
- if (shouldImmediate$1) this.suppressScrollWatcherDiff(this.scrollWatcherSuppressionMs + 800);
1199
- const computed$3 = this.computedHeight();
1200
- if (computed$3 >= this.maxHeightValue - 1 && this.lastContainer) {
1201
- this.lastContainer.style.height = `${this.maxHeightValue}px`;
1202
- this.lastContainer.style.overflow = "auto";
1203
- }
1204
- if (shouldImmediate$1) this.scheduleImmediateRevealAfterLayoutDiff(newLine$1);
1205
- else this.maybeScrollDiffToBottom(newLine$1, prevLine);
1206
- prevLine = newLine$1;
1207
- log("diff", "flushAppendBufferDiff chunk applied", {
1208
- idx,
1209
- newLine: newLine$1
1210
- });
1211
- }
1212
- if (suppressedByFlush) watcherApi.setSuppressed(false);
1213
- return;
1214
- }
1215
- const text = totalText;
1216
- this.appendBufferDiff.length = 0;
1217
- prevLine = model.getLineCount();
1218
- const lastColumn = model.getLineMaxColumn(prevLine);
1219
- const range = new monaco_shim_exports.Range(prevLine, lastColumn, prevLine, lastColumn);
1220
- model.applyEdits([{
1221
- range,
1222
- text,
1223
- forceMoveMarkers: true
1224
- }]);
1225
- this.lastKnownModifiedCode = model.getValue();
1226
- const newLine = model.getLineCount();
1227
- this.lastKnownModifiedLineCount = newLine;
1228
- const shouldImmediate = this.shouldPerformImmediateRevealDiff();
1229
- if (shouldImmediate) this.suppressScrollWatcherDiff(this.scrollWatcherSuppressionMs + 800);
1230
- const computed$2 = this.computedHeight();
1231
- if (computed$2 >= this.maxHeightValue - 1 && this.lastContainer) this.lastContainer.style.height = `${this.maxHeightValue}px`;
1232
- if (shouldImmediate) this.scheduleImmediateRevealAfterLayoutDiff(newLine);
1233
- else this.maybeScrollDiffToBottom(newLine, prevLine);
1234
- if (this.autoScrollOnUpdate && this.shouldAutoScrollDiff) try {
1235
- var _editor4, _me2$getModel2, _me2$getScrollTop2;
1236
- const ScrollType = monaco_shim_exports.ScrollType || ((_editor4 = monaco_shim_exports.editor) === null || _editor4 === void 0 ? void 0 : _editor4.ScrollType);
1237
- const immediate = ScrollType && typeof ScrollType.Immediate !== "undefined" ? ScrollType.Immediate : void 0;
1238
- const me2 = this.diffEditorView.getModifiedEditor();
1239
- const targetLine = ((_me2$getModel2 = me2.getModel()) === null || _me2$getModel2 === void 0 ? void 0 : _me2$getModel2.getLineCount()) ?? newLine;
1240
- if (typeof immediate !== "undefined") me2.revealLine(targetLine, immediate);
1241
- else me2.revealLine(targetLine);
1242
- this.lastRevealLineDiff = targetLine;
1243
- this.shouldAutoScrollDiff = true;
1244
- this.lastScrollTopDiff = ((_me2$getScrollTop2 = me2.getScrollTop) === null || _me2$getScrollTop2 === void 0 ? void 0 : _me2$getScrollTop2.call(me2)) ?? this.lastScrollTopDiff;
1245
- } catch {}
1246
- if (suppressedByFlush) watcherApi.setSuppressed(false);
1247
- try {
1248
- var _this$diffEditorView5, _this$diffEditorView6, _this$diffEditorView7;
1249
- this.shouldAutoScrollDiff = true;
1250
- this.lastScrollTopDiff = ((_this$diffEditorView5 = this.diffEditorView) === null || _this$diffEditorView5 === void 0 || (_this$diffEditorView7 = (_this$diffEditorView6 = _this$diffEditorView5.getModifiedEditor()).getScrollTop) === null || _this$diffEditorView7 === void 0 ? void 0 : _this$diffEditorView7.call(_this$diffEditorView6)) ?? this.lastScrollTopDiff;
1251
- } catch {}
1252
- }
1253
- applyMinimalEditToModel(model, prev, next) {
1254
- const maxChars = minimalEditMaxChars;
1255
- const ratio = minimalEditMaxChangeRatio;
1256
- const maxLen = Math.max(prev.length, next.length);
1257
- const changeRatio = maxLen > 0 ? Math.abs(next.length - prev.length) / maxLen : 0;
1258
- if (prev.length + next.length > maxChars || changeRatio > ratio) {
1259
- model.setValue(next);
1260
- if (model === this.modifiedModel) this.lastKnownModifiedLineCount = model.getLineCount();
1261
- return;
1262
- }
1263
- const res = computeMinimalEdit(prev, next);
1264
- if (!res) return;
1265
- const { start, endPrevIncl, replaceText } = res;
1266
- const rangeStart = model.getPositionAt(start);
1267
- const rangeEnd = model.getPositionAt(endPrevIncl + 1);
1268
- const range = new monaco_shim_exports.Range(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column);
1269
- model.applyEdits([{
1270
- range,
1271
- text: replaceText,
1272
- forceMoveMarkers: true
1273
- }]);
1274
- if (model === this.modifiedModel) this.lastKnownModifiedLineCount = model.getLineCount();
1275
- }
1276
- appendToModel(model, appendText) {
1277
- if (!appendText) return;
1278
- const lastLine = model.getLineCount();
1279
- const lastColumn = model.getLineMaxColumn(lastLine);
1280
- const range = new monaco_shim_exports.Range(lastLine, lastColumn, lastLine, lastColumn);
1281
- model.applyEdits([{
1282
- range,
1283
- text: appendText,
1284
- forceMoveMarkers: true
1285
- }]);
1286
- if (model === this.modifiedModel) this.lastKnownModifiedLineCount = model.getLineCount();
1287
- }
1288
- };
1289
-
1290
- //#endregion
1291
- //#region src/core/EditorManager.ts
1292
- var EditorManager = class {
1293
- editorView = null;
1294
- lastContainer = null;
1295
- lastKnownCode = null;
1296
- pendingUpdate = null;
1297
- _hasScrollBar = false;
1298
- shouldAutoScroll = true;
1299
- scrollWatcher = null;
1300
- scrollWatcherSuppressionTimer = null;
1301
- lastScrollTop = 0;
1302
- cachedScrollHeight = null;
1303
- cachedLineHeight = null;
1304
- cachedComputedHeight = null;
1305
- cachedLineCount = null;
1306
- lastKnownCodeDirty = false;
1307
- debug = false;
1308
- measureViewport() {
1309
- var _this$editorView$getL, _this$editorView, _this$editorView$getS, _this$editorView2, _this$editorView$getS2, _this$editorView3;
1310
- if (!this.editorView) return null;
1311
- 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;
1312
- const lineHeight = this.cachedLineHeight ?? this.editorView.getOption(monaco_shim_exports.editor.EditorOption.lineHeight);
1313
- 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;
1314
- 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;
1315
- const computedHeight = this.cachedComputedHeight ?? this.computedHeight(this.editorView);
1316
- this.cachedLineHeight = lineHeight;
1317
- this.cachedScrollHeight = scrollHeight;
1318
- this.cachedComputedHeight = computedHeight;
1319
- this.lastScrollTop = scrollTop;
1320
- return {
1321
- li,
1322
- lineHeight,
1323
- scrollTop,
1324
- scrollHeight,
1325
- computedHeight
1326
- };
1327
- }
1328
- appendBuffer = [];
1329
- appendBufferScheduled = false;
1330
- rafScheduler = createRafScheduler();
1331
- editorHeightManager = null;
1332
- revealDebounceId = null;
1333
- revealDebounceMs = defaultRevealDebounceMs;
1334
- revealIdleTimerId = null;
1335
- revealTicket = 0;
1336
- revealStrategyOption;
1337
- revealBatchOnIdleMsOption;
1338
- scrollWatcherSuppressionMs = 500;
1339
- constructor(options, maxHeightValue, maxHeightCSS, autoScrollOnUpdate, autoScrollInitial, autoScrollThresholdPx, autoScrollThresholdLines, revealDebounceMsOption) {
1340
- this.options = options;
1341
- this.maxHeightValue = maxHeightValue;
1342
- this.maxHeightCSS = maxHeightCSS;
1343
- this.autoScrollOnUpdate = autoScrollOnUpdate;
1344
- this.autoScrollInitial = autoScrollInitial;
1345
- this.autoScrollThresholdPx = autoScrollThresholdPx;
1346
- this.autoScrollThresholdLines = autoScrollThresholdLines;
1347
- this.revealDebounceMsOption = revealDebounceMsOption;
1348
- }
1349
- initDebugFlag() {
1350
- if (typeof window !== "undefined" && window.__STREAM_MONACO_DEBUG__ !== void 0) {
1351
- this.debug = Boolean(window.__STREAM_MONACO_DEBUG__);
1352
- return;
1353
- }
1354
- if (this.options && this.options.debug !== void 0) {
1355
- this.debug = Boolean(this.options.debug);
1356
- return;
1357
- }
1358
- this.debug = false;
1359
- }
1360
- dlog(...args) {
1361
- if (!this.debug) return;
1362
- log("EditorManager", ...args);
1363
- }
1364
- hasVerticalScrollbar() {
1365
- if (!this.editorView) return false;
1366
- if (this._hasScrollBar) return true;
1367
- const m = this.measureViewport();
1368
- if (!m) return false;
1369
- return this._hasScrollBar = m.scrollHeight > m.computedHeight + padding / 2;
1370
- }
1371
- userIsNearBottom() {
1372
- if (!this.editorView) return true;
1373
- const m = this.measureViewport();
1374
- if (!m || !m.li) return true;
1375
- const lineThreshold = (this.autoScrollThresholdLines ?? 0) * m.lineHeight;
1376
- const threshold = Math.max(lineThreshold || 0, this.autoScrollThresholdPx || 0);
1377
- const distance = m.scrollHeight - (m.scrollTop + m.li.height);
1378
- return distance <= threshold;
1379
- }
1380
- computedHeight(editorView) {
1381
- var _editorView$getModel;
1382
- const lineCount = this.cachedLineCount ?? ((_editorView$getModel = editorView.getModel()) === null || _editorView$getModel === void 0 ? void 0 : _editorView$getModel.getLineCount()) ?? 1;
1383
- const lineHeight = editorView.getOption(monaco_shim_exports.editor.EditorOption.lineHeight);
1384
- const height = Math.min(lineCount * lineHeight + padding, this.maxHeightValue);
1385
- log("EditorManager.computedHeight", {
1386
- lineCount,
1387
- lineHeight,
1388
- computed: height,
1389
- maxHeightValue: this.maxHeightValue
1390
- });
1391
- return height;
1392
- }
1393
- maybeScrollToBottom(targetLine) {
1394
- this.rafScheduler.schedule("maybe-scroll", () => {
1395
- const hasVS = this.hasVerticalScrollbar();
1396
- this.dlog("maybeScrollToBottom called", {
1397
- autoScrollOnUpdate: this.autoScrollOnUpdate,
1398
- shouldAutoScroll: this.shouldAutoScroll,
1399
- hasVerticalScrollbar: hasVS,
1400
- targetLine
1401
- });
1402
- if (!(this.autoScrollOnUpdate && this.shouldAutoScroll && this.hasVerticalScrollbar())) {
1403
- this.dlog("maybeScrollToBottom skipped (auto-scroll conditions not met)");
1404
- return;
1405
- }
1406
- const model = this.editorView.getModel();
1407
- const line = targetLine ?? (model === null || model === void 0 ? void 0 : model.getLineCount()) ?? 1;
1408
- const batchMs = this.revealBatchOnIdleMsOption ?? this.options.revealBatchOnIdleMs ?? defaultRevealBatchOnIdleMs;
1409
- if (typeof batchMs === "number" && batchMs > 0) {
1410
- if (this.revealIdleTimerId != null) clearTimeout(this.revealIdleTimerId);
1411
- const ticket = ++this.revealTicket;
1412
- this.dlog("scheduled idle reveal ticket=", ticket, "line=", line, "batchMs=", batchMs);
1413
- this.revealIdleTimerId = setTimeout(() => {
1414
- this.revealIdleTimerId = null;
1415
- this.dlog("idle reveal timer firing, ticket=", ticket, "line=", line);
1416
- this.performReveal(line, ticket);
1417
- }, batchMs);
1418
- return;
1419
- }
1420
- if (this.revealDebounceId != null) {
1421
- clearTimeout(this.revealDebounceId);
1422
- this.revealDebounceId = null;
1423
- }
1424
- const ms = typeof this.revealDebounceMs === "number" && this.revealDebounceMs > 0 ? this.revealDebounceMs : typeof this.revealDebounceMsOption === "number" && this.revealDebounceMsOption > 0 ? this.revealDebounceMsOption : this.revealDebounceMs;
1425
- this.revealDebounceId = setTimeout(() => {
1426
- this.revealDebounceId = null;
1427
- const ticket = ++this.revealTicket;
1428
- this.dlog("scheduled debounce reveal ticket=", ticket, "line=", line, "ms=", ms);
1429
- this.performReveal(line, ticket);
1430
- }, ms);
1431
- });
1432
- }
1433
- performReveal(line, ticket) {
1434
- this.rafScheduler.schedule("reveal", () => {
1435
- var _editor;
1436
- if (ticket !== this.revealTicket) {
1437
- this.dlog("performReveal skipped, stale ticket", ticket, "current", this.revealTicket);
1438
- return;
1439
- }
1440
- this.dlog("performReveal executing, ticket=", ticket, "line=", line);
1441
- const strategy = this.revealStrategyOption ?? this.options.revealStrategy ?? "centerIfOutside";
1442
- this.dlog("performReveal strategy=", strategy);
1443
- const ScrollType = monaco_shim_exports.ScrollType || ((_editor = monaco_shim_exports.editor) === null || _editor === void 0 ? void 0 : _editor.ScrollType);
1444
- const smooth = ScrollType && typeof ScrollType.Smooth !== "undefined" ? ScrollType.Smooth : void 0;
1445
- try {
1446
- if (strategy === "bottom") if (typeof smooth !== "undefined") this.editorView.revealLine(line, smooth);
1447
- else this.editorView.revealLine(line);
1448
- else if (strategy === "center") if (typeof smooth !== "undefined") this.editorView.revealLineInCenter(line, smooth);
1449
- else this.editorView.revealLineInCenter(line);
1450
- else if (typeof smooth !== "undefined") this.editorView.revealLineInCenterIfOutsideViewport(line, smooth);
1451
- else this.editorView.revealLineInCenterIfOutsideViewport(line);
1452
- } catch {
1453
- try {
1454
- this.editorView.revealLine(line);
1455
- } catch {}
1456
- }
1457
- });
1458
- }
1459
- performImmediateReveal(line, ticket) {
1460
- this.dlog("performImmediateReveal line=", line, "ticket=", ticket);
1461
- try {
1462
- var _editor2;
1463
- if (!this.editorView) return;
1464
- if (ticket !== this.revealTicket) {
1465
- this.dlog("performImmediateReveal skipped, stale ticket", ticket, "current", this.revealTicket);
1466
- return;
1467
- }
1468
- const ScrollType = monaco_shim_exports.ScrollType || ((_editor2 = monaco_shim_exports.editor) === null || _editor2 === void 0 ? void 0 : _editor2.ScrollType);
1469
- const immediate = ScrollType && typeof ScrollType.Immediate !== "undefined" ? ScrollType.Immediate : void 0;
1470
- if (typeof immediate !== "undefined") this.editorView.revealLine(line, immediate);
1471
- else this.editorView.revealLine(line);
1472
- } catch {}
1473
- try {
1474
- this.measureViewport();
1475
- } catch {}
1476
- }
1477
- forceReveal(line) {
1478
- try {
1479
- var _editor3;
1480
- if (!this.editorView) return;
1481
- const ScrollType = monaco_shim_exports.ScrollType || ((_editor3 = monaco_shim_exports.editor) === null || _editor3 === void 0 ? void 0 : _editor3.ScrollType);
1482
- const immediate = ScrollType && typeof ScrollType.Immediate !== "undefined" ? ScrollType.Immediate : void 0;
1483
- if (typeof immediate !== "undefined") this.editorView.revealLine(line, immediate);
1484
- else this.editorView.revealLine(line);
1485
- } catch {}
1486
- try {
1487
- this.measureViewport();
1488
- } catch {}
1489
- try {
1490
- var _this$editorView4, _this$editorView4$get;
1491
- this.shouldAutoScroll = true;
1492
- this.lastScrollTop = ((_this$editorView4 = this.editorView) === null || _this$editorView4 === void 0 || (_this$editorView4$get = _this$editorView4.getScrollTop) === null || _this$editorView4$get === void 0 ? void 0 : _this$editorView4$get.call(_this$editorView4)) ?? this.lastScrollTop;
1493
- } catch {}
1494
- }
1495
- isOverflowAuto() {
1496
- try {
1497
- return !!this.lastContainer && this.lastContainer.style.overflow === "auto";
1498
- } catch {
1499
- return false;
1500
- }
1501
- }
1502
- shouldPerformImmediateReveal() {
1503
- return this.autoScrollOnUpdate && this.shouldAutoScroll && this.hasVerticalScrollbar() && this.isOverflowAuto();
1504
- }
1505
- async createEditor(container, code, language, currentTheme) {
1506
- var _this$editorView$getS3, _this$editorView5, _this$editorView$getO, _this$editorView6, _this$editorView$getM, _this$editorView$onDi, _this$editorView7;
1507
- this.cleanup();
1508
- this.lastContainer = container;
1509
- this.initDebugFlag();
1510
- this.dlog("createEditor container, maxHeight", this.maxHeightValue);
1511
- container.style.overflow = "hidden";
1512
- container.style.maxHeight = this.maxHeightCSS;
1513
- this.editorView = monaco_shim_exports.editor.create(container, {
1514
- value: code,
1515
- language: processedLanguage(language) || language,
1516
- theme: currentTheme,
1517
- scrollBeyondLastLine: false,
1518
- minimap: { enabled: false },
1519
- automaticLayout: true,
1520
- readOnly: this.options.readOnly ?? true,
1521
- contextmenu: false,
1522
- scrollbar: {
1523
- ...defaultScrollbar,
1524
- ...this.options.scrollbar || {}
1525
- },
1526
- ...this.options
1527
- });
1528
- monaco_shim_exports.editor.setTheme(currentTheme);
1529
- this.lastKnownCode = this.editorView.getValue();
1530
- if (this.editorHeightManager) {
1531
- try {
1532
- this.editorHeightManager.dispose();
1533
- } catch {}
1534
- this.editorHeightManager = null;
1535
- }
1536
- if (this.revealDebounceId != null) {
1537
- clearTimeout(this.revealDebounceId);
1538
- this.revealDebounceId = null;
1539
- }
1540
- if (this.revealIdleTimerId != null) clearTimeout(this.revealIdleTimerId);
1541
- this.revealIdleTimerId = null;
1542
- const MIN_VISIBLE_HEIGHT = Math.min(120, this.maxHeightValue);
1543
- container.style.minHeight = `${MIN_VISIBLE_HEIGHT}px`;
1544
- this.editorHeightManager = createHeightManager(container, () => {
1545
- const computed$2 = this.computedHeight(this.editorView);
1546
- const clamped = Math.min(computed$2, this.maxHeightValue);
1547
- return Math.max(clamped, MIN_VISIBLE_HEIGHT);
1548
- });
1549
- this.editorHeightManager.update();
1550
- const initialComputed = this.computedHeight(this.editorView);
1551
- if (initialComputed >= this.maxHeightValue - 1) {
1552
- container.style.height = `${this.maxHeightValue}px`;
1553
- container.style.overflow = "auto";
1554
- this.dlog("applied immediate maxHeight on createEditor", this.maxHeightValue);
1555
- }
1556
- this.cachedScrollHeight = ((_this$editorView$getS3 = (_this$editorView5 = this.editorView).getScrollHeight) === null || _this$editorView$getS3 === void 0 ? void 0 : _this$editorView$getS3.call(_this$editorView5)) ?? null;
1557
- this.cachedLineHeight = ((_this$editorView$getO = (_this$editorView6 = this.editorView).getOption) === null || _this$editorView$getO === void 0 ? void 0 : _this$editorView$getO.call(_this$editorView6, monaco_shim_exports.editor.EditorOption.lineHeight)) ?? null;
1558
- this.cachedComputedHeight = this.computedHeight(this.editorView);
1559
- this.cachedLineCount = ((_this$editorView$getM = this.editorView.getModel()) === null || _this$editorView$getM === void 0 ? void 0 : _this$editorView$getM.getLineCount()) ?? null;
1560
- (_this$editorView$onDi = (_this$editorView7 = this.editorView).onDidContentSizeChange) === null || _this$editorView$onDi === void 0 || _this$editorView$onDi.call(_this$editorView7, () => {
1561
- this._hasScrollBar = false;
1562
- this.rafScheduler.schedule("content-size-change", () => {
1563
- try {
1564
- var _this$editorView8, _this$editorHeightMan, _this$editorHeightMan2;
1565
- this.dlog("content-size-change frame");
1566
- const m = this.measureViewport();
1567
- this.dlog("content-size-change measure", m);
1568
- this.cachedLineCount = ((_this$editorView8 = this.editorView) === null || _this$editorView8 === void 0 || (_this$editorView8 = _this$editorView8.getModel()) === null || _this$editorView8 === void 0 ? void 0 : _this$editorView8.getLineCount()) ?? this.cachedLineCount;
1569
- if ((_this$editorHeightMan = this.editorHeightManager) === null || _this$editorHeightMan === void 0 ? void 0 : _this$editorHeightMan.isSuppressed()) {
1570
- this.dlog("content-size-change skipped height update (suppressed)");
1571
- return;
1572
- }
1573
- this.dlog("content-size-change calling heightManager.update");
1574
- (_this$editorHeightMan2 = this.editorHeightManager) === null || _this$editorHeightMan2 === void 0 || _this$editorHeightMan2.update();
1575
- const computed$2 = this.computedHeight(this.editorView);
1576
- if (this.lastContainer) {
1577
- const prevOverflow = this.lastContainer.style.overflow;
1578
- const newOverflow = computed$2 >= this.maxHeightValue - 1 ? "auto" : "hidden";
1579
- if (prevOverflow !== newOverflow) {
1580
- this.lastContainer.style.overflow = newOverflow;
1581
- if (newOverflow === "auto" && this.shouldAutoScroll) this.maybeScrollToBottom();
1582
- }
1583
- }
1584
- } catch (err) {
1585
- error("EditorManager", "content-size-change error", err);
1586
- }
1587
- });
1588
- });
1589
- this.editorView.onDidChangeModelContent(() => {
1590
- this.lastKnownCodeDirty = true;
1591
- this.rafScheduler.schedule("sync-last-known", () => this.syncLastKnownCode());
1592
- });
1593
- this.shouldAutoScroll = !!this.autoScrollInitial;
1594
- if (this.scrollWatcher) {
1595
- this.scrollWatcher.dispose();
1596
- this.scrollWatcher = null;
1597
- }
1598
- this.scrollWatcher = createScrollWatcherForEditor(this.editorView, {
1599
- onPause: () => {
1600
- this.shouldAutoScroll = false;
1601
- },
1602
- onMaybeResume: () => {
1603
- this.rafScheduler.schedule("maybe-resume", () => {
1604
- this.shouldAutoScroll = this.userIsNearBottom();
1605
- });
1606
- },
1607
- getLast: () => this.lastScrollTop,
1608
- setLast: (v) => {
1609
- this.lastScrollTop = v;
1610
- }
1611
- });
1612
- this.maybeScrollToBottom();
1613
- return this.editorView;
1614
- }
1615
- syncLastKnownCode() {
1616
- if (!this.editorView || !this.lastKnownCodeDirty) return;
1617
- const model = this.editorView.getModel();
1618
- if (model) {
1619
- this.lastKnownCode = model.getValue();
1620
- this.cachedLineCount = model.getLineCount() ?? this.cachedLineCount;
1621
- }
1622
- this.lastKnownCodeDirty = false;
1623
- }
1624
- suppressScrollWatcher(ms) {
1625
- if (!this.scrollWatcher || typeof this.scrollWatcher.setSuppressed !== "function") return;
1626
- this.dlog("suppressScrollWatcher", ms);
1627
- if (this.scrollWatcherSuppressionTimer != null) {
1628
- clearTimeout(this.scrollWatcherSuppressionTimer);
1629
- this.scrollWatcherSuppressionTimer = null;
1630
- }
1631
- this.scrollWatcher.setSuppressed(true);
1632
- this.scrollWatcherSuppressionTimer = setTimeout(() => {
1633
- if (this.scrollWatcher && typeof this.scrollWatcher.setSuppressed === "function") {
1634
- this.scrollWatcher.setSuppressed(false);
1635
- this.dlog("suppressScrollWatcher cleared");
1636
- }
1637
- this.scrollWatcherSuppressionTimer = null;
1638
- }, ms);
1639
- }
1640
- scheduleImmediateRevealAfterLayout(line) {
1641
- const ticket = ++this.revealTicket;
1642
- this.dlog("scheduleImmediateRevealAfterLayout ticket=", ticket, "line=", line);
1643
- this.rafScheduler.schedule("immediate-reveal", async () => {
1644
- try {
1645
- const target = this.editorView && this.editorHeightManager ? Math.min(this.computedHeight(this.editorView), this.maxHeightValue) : -1;
1646
- if (target !== -1 && this.editorHeightManager) await this.waitForHeightApplied(target, 500);
1647
- else await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r())));
1648
- this.dlog("running delayed immediate reveal", "ticket=", ticket, "line=", line);
1649
- this.performImmediateReveal(line, ticket);
1650
- } catch (err) {
1651
- error("EditorManager", "scheduleImmediateRevealAfterLayout error", err);
1652
- }
1653
- });
1654
- }
1655
- waitForHeightApplied(target, timeoutMs = 500) {
1656
- return new Promise((resolve) => {
1657
- const start = typeof performance !== "undefined" && performance.now ? performance.now() : Date.now();
1658
- const check = () => {
1659
- try {
1660
- var _this$editorHeightMan3, _this$editorHeightMan4;
1661
- const last = ((_this$editorHeightMan3 = this.editorHeightManager) === null || _this$editorHeightMan3 === void 0 || (_this$editorHeightMan4 = _this$editorHeightMan3.getLastApplied) === null || _this$editorHeightMan4 === void 0 ? void 0 : _this$editorHeightMan4.call(_this$editorHeightMan3)) ?? -1;
1662
- if (last !== -1 && Math.abs(last - target) <= 12) {
1663
- this.dlog("waitForHeightApplied satisfied", last, "target=", target);
1664
- resolve();
1665
- return;
1666
- }
1667
- const now = typeof performance !== "undefined" && performance.now ? performance.now() : Date.now();
1668
- if (now - start > timeoutMs) {
1669
- log("EditorManager", "waitForHeightApplied timeout", last, "target=", target);
1670
- resolve();
1671
- return;
1672
- }
1673
- } catch {}
1674
- requestAnimationFrame(check);
1675
- };
1676
- check();
1677
- });
1678
- }
1679
- updateCode(newCode, codeLanguage) {
1680
- this.pendingUpdate = {
1681
- code: newCode,
1682
- lang: codeLanguage
1683
- };
1684
- this.rafScheduler.schedule("update", () => this.flushPendingUpdate());
1685
- }
1686
- flushPendingUpdate() {
1687
- if (!this.pendingUpdate || !this.editorView) return;
1688
- const model = this.editorView.getModel();
1689
- if (!model) return;
1690
- const { code: newCode, lang: codeLanguage } = this.pendingUpdate;
1691
- this.pendingUpdate = null;
1692
- const processedCodeLanguage = processedLanguage(codeLanguage);
1693
- const languageId = model.getLanguageId();
1694
- if (languageId !== processedCodeLanguage) {
1695
- if (processedCodeLanguage) monaco_shim_exports.editor.setModelLanguage(model, processedCodeLanguage);
1696
- const prevLineCount$1 = model.getLineCount();
1697
- model.setValue(newCode);
1698
- this.lastKnownCode = newCode;
1699
- const newLineCount$1 = model.getLineCount();
1700
- this.cachedLineCount = newLineCount$1;
1701
- if (newLineCount$1 !== prevLineCount$1) {
1702
- const shouldImmediate = this.shouldPerformImmediateReveal();
1703
- if (shouldImmediate) this.suppressScrollWatcher(this.scrollWatcherSuppressionMs);
1704
- const computed$2 = this.computedHeight(this.editorView);
1705
- if (computed$2 >= this.maxHeightValue - 1 && this.lastContainer) this.lastContainer.style.height = `${this.maxHeightValue}px`;
1706
- this.forceReveal(newLineCount$1);
1707
- }
1708
- return;
1709
- }
1710
- const buffered = this.appendBuffer.length > 0 ? this.appendBuffer.join("") : "";
1711
- const prevCode = this.appendBuffer.length > 0 ? this.editorView.getValue() + buffered : this.lastKnownCode ?? this.editorView.getValue();
1712
- if (prevCode === newCode) return;
1713
- if (newCode.startsWith(prevCode) && prevCode.length < newCode.length) {
1714
- const suffix = newCode.slice(prevCode.length);
1715
- if (suffix) this.appendCode(suffix, codeLanguage);
1716
- this.lastKnownCode = newCode;
1717
- return;
1718
- }
1719
- const prevLineCount = model.getLineCount();
1720
- this.applyMinimalEdit(prevCode, newCode);
1721
- this.lastKnownCode = newCode;
1722
- const newLineCount = model.getLineCount();
1723
- this.cachedLineCount = newLineCount;
1724
- if (newLineCount !== prevLineCount) {
1725
- const shouldImmediate = this.shouldPerformImmediateReveal();
1726
- if (shouldImmediate) this.suppressScrollWatcher(this.scrollWatcherSuppressionMs);
1727
- if (shouldImmediate) this.scheduleImmediateRevealAfterLayout(newLineCount);
1728
- else this.maybeScrollToBottom(newLineCount);
1729
- }
1730
- }
1731
- appendCode(appendText, codeLanguage) {
1732
- if (!this.editorView) return;
1733
- const model = this.editorView.getModel();
1734
- if (!model) return;
1735
- const processedCodeLanguage = codeLanguage ? processedLanguage(codeLanguage) : model.getLanguageId();
1736
- if (processedCodeLanguage && model.getLanguageId() !== processedCodeLanguage) monaco_shim_exports.editor.setModelLanguage(model, processedCodeLanguage);
1737
- if (appendText) {
1738
- this.appendBuffer.push(appendText);
1739
- if (!this.appendBufferScheduled) {
1740
- this.appendBufferScheduled = true;
1741
- this.rafScheduler.schedule("append", () => this.flushAppendBuffer());
1742
- }
1743
- }
1744
- }
1745
- applyMinimalEdit(prev, next) {
1746
- if (!this.editorView) return;
1747
- const model = this.editorView.getModel();
1748
- if (!model) return;
1749
- const maxChars = minimalEditMaxChars;
1750
- const ratio = minimalEditMaxChangeRatio;
1751
- const maxLen = Math.max(prev.length, next.length);
1752
- const changeRatio = maxLen > 0 ? Math.abs(next.length - prev.length) / maxLen : 0;
1753
- if (prev.length + next.length > maxChars || changeRatio > ratio) {
1754
- const prevLineCount = model.getLineCount();
1755
- model.setValue(next);
1756
- this.lastKnownCode = next;
1757
- const newLineCount = model.getLineCount();
1758
- this.cachedLineCount = newLineCount;
1759
- if (newLineCount !== prevLineCount) this.maybeScrollToBottom(newLineCount);
1760
- return;
1761
- }
1762
- const res = computeMinimalEdit(prev, next);
1763
- if (!res) return;
1764
- const { start, endPrevIncl, replaceText } = res;
1765
- const rangeStart = model.getPositionAt(start);
1766
- const rangeEnd = model.getPositionAt(endPrevIncl + 1);
1767
- const range = new monaco_shim_exports.Range(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column);
1768
- const isReadOnly = this.editorView.getOption(monaco_shim_exports.editor.EditorOption.readOnly);
1769
- const edit = [{
1770
- range,
1771
- text: replaceText,
1772
- forceMoveMarkers: true
1773
- }];
1774
- if (isReadOnly) model.applyEdits(edit);
1775
- else this.editorView.executeEdits("minimal-replace", edit);
1776
- }
1777
- flushAppendBuffer() {
1778
- if (!this.editorView) return;
1779
- if (this.appendBuffer.length === 0) return;
1780
- this.appendBufferScheduled = false;
1781
- const model = this.editorView.getModel();
1782
- if (!model) {
1783
- this.appendBuffer.length = 0;
1784
- return;
1785
- }
1786
- const text = this.appendBuffer.join("");
1787
- this.appendBuffer.length = 0;
1788
- const lastLine = model.getLineCount();
1789
- const lastColumn = model.getLineMaxColumn(lastLine);
1790
- const range = new monaco_shim_exports.Range(lastLine, lastColumn, lastLine, lastColumn);
1791
- const isReadOnly = this.editorView.getOption(monaco_shim_exports.editor.EditorOption.readOnly);
1792
- if (isReadOnly) model.applyEdits([{
1793
- range,
1794
- text,
1795
- forceMoveMarkers: true
1796
- }]);
1797
- else this.editorView.executeEdits("append", [{
1798
- range,
1799
- text,
1800
- forceMoveMarkers: true
1801
- }]);
1802
- try {
1803
- this.lastKnownCode = model.getValue();
1804
- } catch {}
1805
- const newLineCount = model.getLineCount();
1806
- if (lastLine !== newLineCount) {
1807
- this.cachedLineCount = newLineCount;
1808
- const shouldImmediate = this.shouldPerformImmediateReveal();
1809
- if (shouldImmediate) this.suppressScrollWatcher(this.scrollWatcherSuppressionMs);
1810
- const computed$2 = this.computedHeight(this.editorView);
1811
- if (computed$2 >= this.maxHeightValue - 1 && this.lastContainer) this.lastContainer.style.height = `${this.maxHeightValue}px`;
1812
- if (shouldImmediate) try {
1813
- this.forceReveal(newLineCount);
1814
- } catch {}
1815
- else this.maybeScrollToBottom(newLineCount);
1816
- }
1817
- }
1818
- setLanguage(language, languages$1) {
1819
- if (languages$1.includes(language)) {
1820
- if (this.editorView) {
1821
- const model = this.editorView.getModel();
1822
- if (model && model.getLanguageId() !== language) monaco_shim_exports.editor.setModelLanguage(model, language);
1823
- }
1824
- } else console.warn(`Language "${language}" is not registered. Available languages: ${languages$1.join(", ")}`);
1825
- }
1826
- getEditorView() {
1827
- return this.editorView;
1828
- }
1829
- cleanup() {
1830
- this.rafScheduler.cancel("update");
1831
- this.rafScheduler.cancel("sync-last-known");
1832
- this.rafScheduler.cancel("content-size-change");
1833
- this.rafScheduler.cancel("maybe-scroll");
1834
- this.rafScheduler.cancel("reveal");
1835
- this.rafScheduler.cancel("immediate-reveal");
1836
- this.rafScheduler.cancel("maybe-resume");
1837
- this.pendingUpdate = null;
1838
- this.rafScheduler.cancel("append");
1839
- this.appendBufferScheduled = false;
1840
- this.appendBuffer.length = 0;
1841
- if (this.revealDebounceId != null) {
1842
- clearTimeout(this.revealDebounceId);
1843
- this.revealDebounceId = null;
1844
- }
1845
- if (this.revealIdleTimerId != null) {
1846
- clearTimeout(this.revealIdleTimerId);
1847
- this.revealIdleTimerId = null;
1848
- }
1849
- if (this.scrollWatcherSuppressionTimer != null) {
1850
- clearTimeout(this.scrollWatcherSuppressionTimer);
1851
- this.scrollWatcherSuppressionTimer = null;
1852
- }
1853
- if (this.editorView) {
1854
- this.editorView.dispose();
1855
- this.editorView = null;
1856
- }
1857
- this.lastKnownCode = null;
1858
- if (this.lastContainer) {
1859
- this.lastContainer.style.minHeight = "";
1860
- this.lastContainer.innerHTML = "";
1861
- this.lastContainer = null;
1862
- }
1863
- if (this.scrollWatcher) {
1864
- this.scrollWatcher.dispose();
1865
- this.scrollWatcher = null;
1866
- }
1867
- if (this.editorHeightManager) {
1868
- this.editorHeightManager.dispose();
1869
- this.editorHeightManager = null;
1870
- }
1871
- }
1872
- safeClean() {
1873
- this.rafScheduler.cancel("update");
1874
- this.pendingUpdate = null;
1875
- this.rafScheduler.cancel("sync-last-known");
1876
- if (this.scrollWatcher) {
1877
- try {
1878
- this.scrollWatcher.dispose();
1879
- } catch {}
1880
- this.scrollWatcher = null;
1881
- }
1882
- if (this.revealDebounceId != null) {
1883
- clearTimeout(this.revealDebounceId);
1884
- this.revealDebounceId = null;
1885
- }
1886
- if (this.revealIdleTimerId != null) {
1887
- clearTimeout(this.revealIdleTimerId);
1888
- this.revealIdleTimerId = null;
1889
- }
1890
- if (this.scrollWatcherSuppressionTimer != null) {
1891
- clearTimeout(this.scrollWatcherSuppressionTimer);
1892
- this.scrollWatcherSuppressionTimer = null;
1893
- }
1894
- this.rafScheduler.cancel("maybe-scroll");
1895
- this.rafScheduler.cancel("reveal");
1896
- this.rafScheduler.cancel("immediate-reveal");
1897
- this.rafScheduler.cancel("maybe-resume");
1898
- this._hasScrollBar = false;
1899
- this.shouldAutoScroll = !!this.autoScrollInitial;
1900
- this.lastScrollTop = 0;
1901
- if (this.editorHeightManager) {
1902
- this.editorHeightManager.dispose();
1903
- this.editorHeightManager = null;
1904
- }
1905
- }
1906
- };
1907
-
1908
- //#endregion
1909
3
  //#region src/preloadMonacoWorkers.ts
1910
4
  async function preloadMonacoWorkers() {
1911
5
  if (typeof window === "undefined" || typeof document === "undefined") return;
1912
- const workerUrlJson = new URL("monaco-editor/esm/vs/language/json/json.worker.js", import.meta.url);
1913
- const workerUrlCss = new URL("monaco-editor/esm/vs/language/css/css.worker.js", import.meta.url);
1914
- const workerUrlHtml = new URL("monaco-editor/esm/vs/language/html/html.worker.js", import.meta.url);
1915
- const workerUrlTs = new URL("monaco-editor/esm/vs/language/typescript/ts.worker.js", import.meta.url);
1916
- const workerUrlEditor = new URL("monaco-editor/esm/vs/editor/editor.worker.js", import.meta.url);
1917
- const unique = Array.from(new Set([
1918
- String(workerUrlJson),
1919
- String(workerUrlCss),
1920
- String(workerUrlHtml),
1921
- String(workerUrlTs),
1922
- String(workerUrlEditor)
1923
- ]));
1924
- const workerUrlByLabel = {
1925
- json: workerUrlJson,
1926
- css: workerUrlCss,
1927
- scss: workerUrlCss,
1928
- less: workerUrlCss,
1929
- html: workerUrlHtml,
1930
- handlebars: workerUrlHtml,
1931
- razor: workerUrlHtml,
1932
- typescript: workerUrlTs,
1933
- javascript: workerUrlTs
1934
- };
6
+ const workerUrlByLabel = Object.fromEntries(Object.entries(workerPathByLabel).map(([label, path]) => [label, new URL(path, import.meta.url)]));
7
+ const workerUrlEditor = new URL(editorWorkerPath, import.meta.url);
8
+ const unique = uniqueWorkerPaths.map((p) => String(new URL(p, import.meta.url)));
1935
9
  try {
1936
- self.MonacoEnvironment = { getWorker(_, label) {
10
+ const existing = self.MonacoEnvironment;
11
+ if (!(existing === null || existing === void 0 ? void 0 : existing.getWorker) && !(existing === null || existing === void 0 ? void 0 : existing.getWorkerUrl)) self.MonacoEnvironment = { getWorker(_, label) {
1937
12
  const url = workerUrlByLabel[label] ?? workerUrlEditor;
1938
13
  return new Worker(url, { type: "module" });
1939
14
  } };
@@ -1946,815 +21,5 @@ async function preloadMonacoWorkers() {
1946
21
  } catch {}
1947
22
  }
1948
23
 
1949
- //#endregion
1950
- //#region src/reactivity.ts
1951
- function computed$1(getter) {
1952
- const c = computed(() => getter());
1953
- return Object.defineProperty({}, "value", {
1954
- get() {
1955
- return c();
1956
- },
1957
- set(_) {},
1958
- enumerable: true,
1959
- configurable: false
1960
- });
1961
- }
1962
-
1963
- //#endregion
1964
- //#region src/utils/arraysEqual.ts
1965
- function arraysEqual(a, b) {
1966
- if (a === b) return true;
1967
- if (!a || !b) return false;
1968
- if (a.length !== b.length) return false;
1969
- for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
1970
- return true;
1971
- }
1972
-
1973
- //#endregion
1974
- //#region src/utils/registerMonacoThemes.ts
1975
- let languagesRegistered = false;
1976
- let currentLanguages = [];
1977
- let themeRegisterPromise = null;
1978
- let registrationQueue = Promise.resolve();
1979
- function enqueueRegistration(task) {
1980
- const next = registrationQueue.then(task, task);
1981
- registrationQueue = next.then(() => void 0, () => void 0);
1982
- return next;
1983
- }
1984
- function setThemeRegisterPromise(p) {
1985
- return themeRegisterPromise = p;
1986
- }
1987
- const highlighterCache = /* @__PURE__ */ new Map();
1988
- let monacoHighlighterPromise = null;
1989
- let lastPatchedHighlighter = null;
1990
- const monacoThemeByKey = /* @__PURE__ */ new Map();
1991
- const monacoLanguageSet = /* @__PURE__ */ new Set();
1992
- function themeKey(t) {
1993
- return typeof t === "string" ? t : t.name ?? JSON.stringify(t);
1994
- }
1995
- async function ensureMonacoHighlighter(themes, languages$1) {
1996
- for (const t of themes) monacoThemeByKey.set(themeKey(t), t);
1997
- for (const l of languages$1) monacoLanguageSet.add(l);
1998
- if (!monacoHighlighterPromise) {
1999
- const initialThemes = Array.from(monacoThemeByKey.values());
2000
- const initialLangs = Array.from(monacoLanguageSet.values());
2001
- monacoHighlighterPromise = createHighlighter({
2002
- themes: initialThemes,
2003
- langs: initialLangs
2004
- }).then((h$1) => h$1);
2005
- }
2006
- const h = await monacoHighlighterPromise;
2007
- const wantsThemes = Array.from(monacoThemeByKey.values());
2008
- const wantsLangs = Array.from(monacoLanguageSet.values());
2009
- const canLoadTheme = typeof h.loadTheme === "function";
2010
- const canLoadLanguage = typeof h.loadLanguage === "function";
2011
- if (canLoadTheme || canLoadLanguage) {
2012
- if (canLoadTheme) for (const t of themes) {
2013
- const k = themeKey(t);
2014
- if (!h.__streamMonacoLoadedThemes) h.__streamMonacoLoadedThemes = /* @__PURE__ */ new Set();
2015
- const loaded = h.__streamMonacoLoadedThemes;
2016
- if (loaded.has(k)) continue;
2017
- await h.loadTheme(t);
2018
- loaded.add(k);
2019
- }
2020
- if (canLoadLanguage) for (const l of languages$1) {
2021
- if (!h.__streamMonacoLoadedLangs) h.__streamMonacoLoadedLangs = /* @__PURE__ */ new Set();
2022
- const loaded = h.__streamMonacoLoadedLangs;
2023
- if (loaded.has(l)) continue;
2024
- await h.loadLanguage(l);
2025
- loaded.add(l);
2026
- }
2027
- return h;
2028
- }
2029
- const p = createHighlighter({
2030
- themes: wantsThemes,
2031
- langs: wantsLangs
2032
- }).then((hh) => hh);
2033
- monacoHighlighterPromise = p;
2034
- return p;
2035
- }
2036
- /**
2037
- * Clear all cached shiki highlighters.
2038
- *
2039
- * Useful for long-running apps that dynamically create many theme combinations,
2040
- * or in tests to ensure a clean state. Call this when you know the highlighters
2041
- * are no longer needed (for example on app shutdown) to free memory.
2042
- */
2043
- function clearHighlighterCache() {
2044
- highlighterCache.clear();
2045
- }
2046
- function serializeThemes(themes) {
2047
- return JSON.stringify(themes.map((t) => typeof t === "string" ? t : t.name ?? JSON.stringify(t)).sort());
2048
- }
2049
- async function getOrCreateHighlighter(themes, languages$1) {
2050
- const key = serializeThemes(themes);
2051
- const requestedSet = new Set(languages$1);
2052
- let existing = highlighterCache.get(key);
2053
- if (existing) {
2054
- let allIncluded = true;
2055
- for (const l of requestedSet) if (!existing.languages.has(l)) {
2056
- allIncluded = false;
2057
- break;
2058
- }
2059
- if (allIncluded) return existing.promise;
2060
- const prev = existing;
2061
- const current = highlighterCache.get(key);
2062
- if (current && current !== prev) {
2063
- let allIncludedCurrent = true;
2064
- for (const l of requestedSet) if (!current.languages.has(l)) {
2065
- allIncludedCurrent = false;
2066
- break;
2067
- }
2068
- if (allIncludedCurrent) return current.promise;
2069
- existing = current;
2070
- }
2071
- const union = new Set([...existing.languages, ...requestedSet]);
2072
- const langsArray = Array.from(union);
2073
- const p$1 = createHighlighter({
2074
- themes,
2075
- langs: langsArray
2076
- });
2077
- const newEntry = {
2078
- promise: p$1,
2079
- languages: union
2080
- };
2081
- highlighterCache.set(key, newEntry);
2082
- p$1.catch(() => {
2083
- if (highlighterCache.get(key) === newEntry && prev) highlighterCache.set(key, prev);
2084
- });
2085
- return p$1;
2086
- }
2087
- const p = createHighlighter({
2088
- themes,
2089
- langs: Array.from(requestedSet)
2090
- });
2091
- const entry = {
2092
- promise: p,
2093
- languages: requestedSet
2094
- };
2095
- highlighterCache.set(key, entry);
2096
- p.catch(() => {
2097
- if (highlighterCache.get(key) === entry) highlighterCache.delete(key);
2098
- });
2099
- return p;
2100
- }
2101
- /**
2102
- * Update the theme used by the shiki highlighter for a given themes+languages
2103
- * combination. Useful when Monaco themes are already registered (so switching
2104
- * Monaco only requires `monaco.editor.setTheme`) but you also want shiki's
2105
- * standalone renderer to use the new theme without recreating everything.
2106
- */
2107
- async function registerMonacoThemes(themes, languages$1) {
2108
- return enqueueRegistration(async () => {
2109
- registerMonacoLanguages(languages$1);
2110
- const p = (async () => {
2111
- const highlighter = await ensureMonacoHighlighter(themes, languages$1);
2112
- if (lastPatchedHighlighter !== highlighter) {
2113
- shikiToMonaco(highlighter, monaco_shim_exports);
2114
- lastPatchedHighlighter = highlighter;
2115
- }
2116
- currentLanguages = languages$1.slice();
2117
- return highlighter;
2118
- })();
2119
- setThemeRegisterPromise(p);
2120
- try {
2121
- const res = await p;
2122
- return res;
2123
- } catch (e) {
2124
- setThemeRegisterPromise(null);
2125
- throw e;
2126
- }
2127
- });
2128
- }
2129
- function registerMonacoLanguages(languages$1) {
2130
- if (languagesRegistered && arraysEqual(languages$1, currentLanguages)) return;
2131
- const existing = new Set(monaco_shim_exports.languages.getLanguages().map((l) => l.id));
2132
- for (const lang of languages$1) if (!existing.has(lang)) try {
2133
- monaco_shim_exports.languages.register({ id: lang });
2134
- } catch {}
2135
- languagesRegistered = true;
2136
- currentLanguages = languages$1;
2137
- }
2138
-
2139
- //#endregion
2140
- //#region src/type.ts
2141
- let RevealStrategy = /* @__PURE__ */ function(RevealStrategy$1) {
2142
- RevealStrategy$1["Bottom"] = "bottom";
2143
- RevealStrategy$1["CenterIfOutside"] = "centerIfOutside";
2144
- RevealStrategy$1["Center"] = "center";
2145
- return RevealStrategy$1;
2146
- }({});
2147
-
2148
- //#endregion
2149
- //#region src/index.ts
2150
- let globalRequestedThemeName = null;
2151
- let globalThemeRequestSeq = 0;
2152
- let globalAppliedThemeName = null;
2153
- /**
2154
- * useMonaco 组合式函数
2155
- *
2156
- * 提供 Monaco 编辑器的创建、销毁、内容/主题/语言更新等能力。
2157
- * 支持主题自动切换、语言高亮、代码更新等功能。
2158
- *
2159
- * @param {MonacoOptions} [monacoOptions] - 编辑器初始化配置,支持 Monaco 原生配置及扩展项
2160
- * @param {number | string} [monacoOptions.MAX_HEIGHT] - 编辑器最大高度,可以是数字(像素)或 CSS 字符串(如 '100%', 'calc(100vh - 100px)')
2161
- * @param {boolean} [monacoOptions.readOnly] - 是否为只读模式
2162
- * @param {MonacoTheme[]} [monacoOptions.themes] - 主题数组,至少包含两个主题:[暗色主题, 亮色主题]
2163
- * @param {MonacoLanguage[]} [monacoOptions.languages] - 支持的编程语言数组
2164
- * @param {string} [monacoOptions.theme] - 初始主题名称
2165
- * @param {boolean} [monacoOptions.isCleanOnBeforeCreate] - 是否在创建前清理之前注册的资源, 默认为 true
2166
- * @param {(monaco: typeof import('monaco-editor')) => monaco.IDisposable[]} [monacoOptions.onBeforeCreate] - 编辑器创建前的钩子函数
2167
- *
2168
- * @returns {{
2169
- * createEditor: (container: HTMLElement, code: string, language: string) => Promise<monaco.editor.IStandaloneCodeEditor>,
2170
- * createDiffEditor: (
2171
- * container: HTMLElement,
2172
- * originalCode: string,
2173
- * modifiedCode: string,
2174
- * language: string,
2175
- * ) => Promise<monaco.editor.IStandaloneDiffEditor>,
2176
- * cleanupEditor: () => void,
2177
- * updateCode: (newCode: string, codeLanguage: string) => void,
2178
- * appendCode: (appendText: string, codeLanguage?: string) => void,
2179
- * updateDiff: (
2180
- * originalCode: string,
2181
- * modifiedCode: string,
2182
- * codeLanguage?: string,
2183
- * ) => void,
2184
- * updateOriginal: (newCode: string, codeLanguage?: string) => void,
2185
- * updateModified: (newCode: string, codeLanguage?: string) => void,
2186
- * appendOriginal: (appendText: string, codeLanguage?: string) => void,
2187
- * appendModified: (appendText: string, codeLanguage?: string) => void,
2188
- * setTheme: (theme: MonacoTheme) => Promise<void>,
2189
- * setLanguage: (language: MonacoLanguage) => void,
2190
- * getCurrentTheme: () => string,
2191
- * getEditor: () => typeof monaco.editor,
2192
- * getEditorView: () => monaco.editor.IStandaloneCodeEditor | null,
2193
- * getDiffEditorView: () => monaco.editor.IStandaloneDiffEditor | null,
2194
- * getDiffModels: () => { original: monaco.editor.ITextModel | null, modified: monaco.editor.ITextModel | null },
2195
- * getCode: () => string | { original: string, modified: string } | null,
2196
- * }} 返回对象包含以下方法和属性:
2197
- *
2198
- * @property {Function} createEditor - 创建并挂载 Monaco 编辑器到指定容器
2199
- * @property {Function} cleanupEditor - 销毁编辑器并清理容器
2200
- * @property {Function} updateCode - 更新编辑器内容和语言,必要时滚动到底部
2201
- * @property {Function} appendCode - 在编辑器末尾追加文本,必要时滚动到底部
2202
- * @property {Function} createDiffEditor - 创建并挂载 Diff 编辑器
2203
- * @property {Function} updateDiff - 更新 Diff 编辑器的 original/modified 内容(RAF 合并、增量更新)
2204
- * @property {Function} updateOriginal - 仅更新 Diff 的 original 内容(增量更新)
2205
- * @property {Function} updateModified - 仅更新 Diff 的 modified 内容(增量更新)
2206
- * @property {Function} appendOriginal - 在 Diff 的 original 末尾追加(显式流式场景)
2207
- * @property {Function} appendModified - 在 Diff 的 modified 末尾追加(显式流式场景)
2208
- * @property {Function} setTheme - 切换编辑器主题,返回 Promise,在主题应用完成时 resolve
2209
- * @property {Function} setLanguage - 切换编辑器语言
2210
- * @property {Function} getCurrentTheme - 获取当前主题名称
2211
- * @property {Function} getEditor - 获取 Monaco 的静态 editor 对象(用于静态方法调用)
2212
- * @property {Function} getEditorView - 获取当前编辑器实例
2213
- * @property {Function} getDiffEditorView - 获取当前 Diff 编辑器实例
2214
- * @property {Function} getDiffModels - 获取 Diff 的 original/modified 两个模型
2215
- * @property {Function} getCode - 获取当前编辑器或 Diff 编辑器中的代码内容
2216
- *
2217
- * @throws {Error} 当主题数组不是数组或长度小于2时抛出错误
2218
- *
2219
- * @example
2220
- * ```typescript
2221
- * import { useMonaco } from 'stream-monaco'
2222
- *
2223
- * const { createEditor, updateCode, setTheme } = useMonaco({
2224
- * themes: ['vitesse-dark', 'vitesse-light'],
2225
- * languages: ['javascript', 'typescript'],
2226
- * readOnly: false
2227
- * })
2228
- *
2229
- * // 创建编辑器
2230
- * const editor = await createEditor(containerRef.value, 'console.log("hello")', 'javascript')
2231
- *
2232
- * // 更新代码
2233
- * updateCode('console.log("world")', 'javascript')
2234
- *
2235
- * // 切换主题
2236
- * setTheme('vitesse-light')
2237
- * ```
2238
- */
2239
- function useMonaco(monacoOptions = {}) {
2240
- var _monacoOptions$themes;
2241
- const disposals = [];
2242
- if (monacoOptions.isCleanOnBeforeCreate ?? true) disposals.forEach((d) => d.dispose());
2243
- if (monacoOptions.isCleanOnBeforeCreate ?? true) disposals.length = 0;
2244
- let editorView = null;
2245
- let editorMgr = null;
2246
- let diffEditorView = null;
2247
- let diffMgr = null;
2248
- let originalModel = null;
2249
- let modifiedModel = null;
2250
- let _hasScrollBar = false;
2251
- const themes = monacoOptions.themes && ((_monacoOptions$themes = monacoOptions.themes) === null || _monacoOptions$themes === void 0 ? void 0 : _monacoOptions$themes.length) ? monacoOptions.themes : defaultThemes;
2252
- if (!Array.isArray(themes) || themes.length < 2) throw new Error("Monaco themes must be an array with at least two themes: [darkTheme, lightTheme]");
2253
- const languages$1 = monacoOptions.languages ?? defaultLanguages;
2254
- const MAX_HEIGHT = monacoOptions.MAX_HEIGHT ?? 500;
2255
- const autoScrollOnUpdate = monacoOptions.autoScrollOnUpdate ?? true;
2256
- const autoScrollInitial = monacoOptions.autoScrollInitial ?? true;
2257
- const autoScrollThresholdPx = monacoOptions.autoScrollThresholdPx ?? 32;
2258
- const autoScrollThresholdLines = monacoOptions.autoScrollThresholdLines ?? 2;
2259
- const diffAutoScroll = monacoOptions.diffAutoScroll ?? true;
2260
- const getMaxHeightValue = () => {
2261
- if (typeof MAX_HEIGHT === "number") return MAX_HEIGHT;
2262
- const match = MAX_HEIGHT.match(/^(\d+(?:\.\d+)?)/);
2263
- return match ? Number.parseFloat(match[1]) : 500;
2264
- };
2265
- const getMaxHeightCSS = () => {
2266
- if (typeof MAX_HEIGHT === "number") return `${MAX_HEIGHT}px`;
2267
- return MAX_HEIGHT;
2268
- };
2269
- const maxHeightValue = getMaxHeightValue();
2270
- const maxHeightCSS = getMaxHeightCSS();
2271
- let lastContainer = null;
2272
- let lastKnownCode = null;
2273
- const minimalEditMaxCharsLocal = monacoOptions.minimalEditMaxChars ?? minimalEditMaxChars;
2274
- const minimalEditMaxChangeRatioLocal = monacoOptions.minimalEditMaxChangeRatio ?? minimalEditMaxChangeRatio;
2275
- let updateThrottleMs = monacoOptions.updateThrottleMs ?? 50;
2276
- let lastFlushTime = 0;
2277
- let updateThrottleTimer = null;
2278
- let pendingUpdate = null;
2279
- let shouldAutoScroll = true;
2280
- const cachedComputedHeight = null;
2281
- const appendBuffer = [];
2282
- let appendBufferScheduled = false;
2283
- const currentTheme = computed$1(() => monacoOptions.theme ?? (typeof themes[0] === "string" ? themes[0] : themes[0].name));
2284
- let requestedThemeName = monacoOptions.theme ?? globalRequestedThemeName ?? currentTheme.value;
2285
- let themeWatcher = null;
2286
- const rafScheduler = createRafScheduler();
2287
- async function tryLoadAndSetShikiTheme(highlighter, themeName) {
2288
- if (!highlighter || typeof highlighter.setTheme !== "function") return;
2289
- try {
2290
- await highlighter.setTheme(themeName);
2291
- } catch (err) {
2292
- const message = (err === null || err === void 0 ? void 0 : err.message) ? String(err.message) : String(err);
2293
- const lower = message.toLowerCase();
2294
- const looksLikeMissingThemeError = lower.includes("theme") && lower.includes("not found");
2295
- if (typeof highlighter.loadTheme === "function" && looksLikeMissingThemeError) {
2296
- await highlighter.loadTheme(themeName);
2297
- await highlighter.setTheme(themeName);
2298
- return;
2299
- }
2300
- throw err;
2301
- }
2302
- }
2303
- async function setThemeInternal(theme, force = false) {
2304
- const themeName = typeof theme === "string" ? theme : theme.name;
2305
- globalThemeRequestSeq += 1;
2306
- const token = globalThemeRequestSeq;
2307
- requestedThemeName = themeName;
2308
- globalRequestedThemeName = themeName;
2309
- if (!force && themeName === globalAppliedThemeName) return;
2310
- if (token !== globalThemeRequestSeq) return;
2311
- await registerMonacoThemes(themes, languages$1).catch(() => void 0);
2312
- if (token !== globalThemeRequestSeq) return;
2313
- const availableNames = themes.map((t) => typeof t === "string" ? t : t.name);
2314
- if (!availableNames.includes(themeName)) try {
2315
- const extended = availableNames.concat(themeName);
2316
- const maybeHighlighter = await registerMonacoThemes(extended, languages$1);
2317
- await tryLoadAndSetShikiTheme(maybeHighlighter, themeName).catch(() => void 0);
2318
- } catch {
2319
- console.warn(`Theme "${themeName}" is not registered and automatic registration failed. Available themes: ${availableNames.join(", ")}`);
2320
- return;
2321
- }
2322
- if (token !== globalThemeRequestSeq) return;
2323
- try {
2324
- monaco_shim_exports.editor.setTheme(themeName);
2325
- globalAppliedThemeName = themeName;
2326
- } catch {
2327
- try {
2328
- const maybeHighlighter = await registerMonacoThemes(themes, languages$1);
2329
- if (token !== globalThemeRequestSeq) return;
2330
- monaco_shim_exports.editor.setTheme(themeName);
2331
- globalAppliedThemeName = themeName;
2332
- await tryLoadAndSetShikiTheme(maybeHighlighter, themeName).catch(() => void 0);
2333
- } catch (err2) {
2334
- console.warn(`Failed to set theme "${themeName}":`, err2);
2335
- return;
2336
- }
2337
- }
2338
- if (token !== globalThemeRequestSeq) return;
2339
- try {
2340
- if (typeof monacoOptions.onThemeChange === "function") await monacoOptions.onThemeChange(themeName);
2341
- } catch (err) {
2342
- console.warn("onThemeChange callback threw an error:", err);
2343
- }
2344
- }
2345
- async function ensureThemeRegistered(themeName) {
2346
- const availableNames = themes.map((t) => typeof t === "string" ? t : t.name);
2347
- const list = availableNames.includes(themeName) ? themes : themes.concat(themeName);
2348
- await registerMonacoThemes(list, languages$1);
2349
- }
2350
- function hasVerticalScrollbar() {
2351
- if (!editorView) return false;
2352
- if (_hasScrollBar) return true;
2353
- const ch = cachedComputedHeight ?? computedHeight(editorView);
2354
- return _hasScrollBar = editorView.getScrollHeight() > ch + padding / 2;
2355
- }
2356
- let revealDebounceId = null;
2357
- const revealDebounceMs = 75;
2358
- function maybeScrollToBottom(targetLine) {
2359
- if (autoScrollOnUpdate && shouldAutoScroll && hasVerticalScrollbar()) {
2360
- const model = editorView.getModel();
2361
- const line = targetLine ?? (model === null || model === void 0 ? void 0 : model.getLineCount()) ?? 1;
2362
- if (revealDebounceId != null) {
2363
- clearTimeout(revealDebounceId);
2364
- revealDebounceId = null;
2365
- }
2366
- revealDebounceId = setTimeout(() => {
2367
- revealDebounceId = null;
2368
- rafScheduler.schedule("reveal", () => {
2369
- try {
2370
- var _editor;
2371
- const ScrollType = monaco_shim_exports.ScrollType || ((_editor = monaco_shim_exports.editor) === null || _editor === void 0 ? void 0 : _editor.ScrollType);
2372
- if (ScrollType && typeof ScrollType.Smooth !== "undefined") editorView.revealLineInCenterIfOutsideViewport(line, ScrollType.Smooth);
2373
- else editorView.revealLineInCenterIfOutsideViewport(line);
2374
- } catch {}
2375
- });
2376
- }, revealDebounceMs);
2377
- }
2378
- }
2379
- async function createEditor(container, code, language) {
2380
- cleanupEditor();
2381
- lastContainer = container;
2382
- if (monacoOptions.isCleanOnBeforeCreate ?? true) {
2383
- disposals.forEach((d) => d.dispose());
2384
- disposals.length = 0;
2385
- }
2386
- if (monacoOptions.onBeforeCreate) {
2387
- const ds = monacoOptions.onBeforeCreate(monaco_shim_exports);
2388
- if (ds) disposals.push(...ds);
2389
- }
2390
- const initialThemeName = requestedThemeName ?? monacoOptions.theme ?? globalRequestedThemeName ?? currentTheme.value;
2391
- await ensureThemeRegistered(initialThemeName);
2392
- editorMgr = new EditorManager(monacoOptions, maxHeightValue, maxHeightCSS, autoScrollOnUpdate, autoScrollInitial, autoScrollThresholdPx, autoScrollThresholdLines, monacoOptions.revealDebounceMs);
2393
- editorView = await editorMgr.createEditor(container, code, language, initialThemeName);
2394
- if (pendingUpdate && editorMgr) {
2395
- const { code: queuedCode, lang: queuedLang } = pendingUpdate;
2396
- pendingUpdate = null;
2397
- editorMgr.updateCode(queuedCode, queuedLang);
2398
- }
2399
- if (typeof monacoOptions.onThemeChange === "function") monacoOptions.onThemeChange(initialThemeName);
2400
- if (editorView) lastKnownCode = editorView.getValue();
2401
- return editorView;
2402
- }
2403
- function computedHeight(editorView$1) {
2404
- var _getModel;
2405
- const lineCount = ((_getModel = editorView$1.getModel()) === null || _getModel === void 0 ? void 0 : _getModel.getLineCount()) ?? 1;
2406
- const lineHeight = editorView$1.getOption(monaco_shim_exports.editor.EditorOption.lineHeight);
2407
- const height = Math.min(lineCount * lineHeight + padding, maxHeightValue);
2408
- return height;
2409
- }
2410
- async function createDiffEditor(container, originalCode, modifiedCode, language) {
2411
- cleanupEditor();
2412
- lastContainer = container;
2413
- if (monacoOptions.isCleanOnBeforeCreate ?? true) {
2414
- disposals.forEach((d) => d.dispose());
2415
- disposals.length = 0;
2416
- }
2417
- if (monacoOptions.onBeforeCreate) {
2418
- const ds = monacoOptions.onBeforeCreate(monaco_shim_exports);
2419
- if (ds) disposals.push(...ds);
2420
- }
2421
- const initialThemeName = requestedThemeName ?? monacoOptions.theme ?? globalRequestedThemeName ?? currentTheme.value;
2422
- await ensureThemeRegistered(initialThemeName);
2423
- try {
2424
- monaco_shim_exports.editor.setTheme(initialThemeName);
2425
- } catch {}
2426
- diffMgr = new DiffEditorManager(monacoOptions, maxHeightValue, maxHeightCSS, autoScrollOnUpdate, autoScrollInitial, autoScrollThresholdPx, autoScrollThresholdLines, diffAutoScroll, monacoOptions.revealDebounceMs);
2427
- diffEditorView = await diffMgr.createDiffEditor(container, originalCode, modifiedCode, language, initialThemeName);
2428
- if (typeof monacoOptions.onThemeChange === "function") monacoOptions.onThemeChange(initialThemeName);
2429
- const models = diffMgr.getDiffModels();
2430
- originalModel = models.original;
2431
- modifiedModel = models.modified;
2432
- return diffEditorView;
2433
- }
2434
- function cleanupEditor() {
2435
- if (editorMgr) {
2436
- editorMgr.cleanup();
2437
- editorMgr = null;
2438
- }
2439
- if (diffMgr) {
2440
- diffMgr.cleanup();
2441
- diffMgr = null;
2442
- }
2443
- rafScheduler.cancel("update");
2444
- pendingUpdate = null;
2445
- rafScheduler.cancel("append");
2446
- appendBufferScheduled = false;
2447
- appendBuffer.length = 0;
2448
- if (!editorMgr && editorView) {
2449
- editorView.dispose();
2450
- editorView = null;
2451
- }
2452
- lastKnownCode = null;
2453
- if (lastContainer) {
2454
- lastContainer.innerHTML = "";
2455
- lastContainer = null;
2456
- }
2457
- if (themeWatcher) {
2458
- themeWatcher();
2459
- themeWatcher = null;
2460
- }
2461
- if (updateThrottleTimer != null) {
2462
- clearTimeout(updateThrottleTimer);
2463
- updateThrottleTimer = null;
2464
- }
2465
- diffEditorView = null;
2466
- originalModel = null;
2467
- modifiedModel = null;
2468
- }
2469
- function appendCode(appendText, codeLanguage) {
2470
- if (editorMgr) editorMgr.appendCode(appendText, codeLanguage);
2471
- else {
2472
- if (!editorView) return;
2473
- const model = editorView.getModel();
2474
- if (!model) return;
2475
- const processedCodeLanguage = codeLanguage ? processedLanguage(codeLanguage) : model.getLanguageId();
2476
- if (processedCodeLanguage && model.getLanguageId() !== processedCodeLanguage) monaco_shim_exports.editor.setModelLanguage(model, processedCodeLanguage);
2477
- if (appendText && lastKnownCode != null) lastKnownCode = lastKnownCode + appendText;
2478
- if (appendText) {
2479
- appendBuffer.push(appendText);
2480
- if (!appendBufferScheduled) {
2481
- appendBufferScheduled = true;
2482
- rafScheduler.schedule("append", flushAppendBuffer);
2483
- }
2484
- }
2485
- }
2486
- }
2487
- function applyMinimalEdit(prev, next) {
2488
- if (!editorView) return;
2489
- const model = editorView.getModel();
2490
- if (!model) return;
2491
- try {
2492
- const maxChars = minimalEditMaxCharsLocal;
2493
- const ratio = minimalEditMaxChangeRatioLocal;
2494
- const maxLen = Math.max(prev.length, next.length);
2495
- const changeRatio = maxLen > 0 ? Math.abs(next.length - prev.length) / maxLen : 0;
2496
- if (prev.length + next.length > maxChars || changeRatio > ratio) {
2497
- const prevLineCount = model.getLineCount();
2498
- model.setValue(next);
2499
- lastKnownCode = next;
2500
- const newLineCount = model.getLineCount();
2501
- if (newLineCount !== prevLineCount) maybeScrollToBottom(newLineCount);
2502
- return;
2503
- }
2504
- } catch {}
2505
- const res = computeMinimalEdit(prev, next);
2506
- if (!res) return;
2507
- const { start, endPrevIncl, replaceText } = res;
2508
- const rangeStart = model.getPositionAt(start);
2509
- const rangeEnd = model.getPositionAt(endPrevIncl + 1);
2510
- const range = new monaco_shim_exports.Range(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column);
2511
- const isReadOnly = editorView.getOption(monaco_shim_exports.editor.EditorOption.readOnly);
2512
- const edit = [{
2513
- range,
2514
- text: replaceText,
2515
- forceMoveMarkers: true
2516
- }];
2517
- if (isReadOnly) model.applyEdits(edit);
2518
- else editorView.executeEdits("minimal-replace", edit);
2519
- }
2520
- function flushPendingUpdate() {
2521
- if (!pendingUpdate) return;
2522
- lastFlushTime = Date.now();
2523
- if (!editorView) return;
2524
- const model = editorView.getModel();
2525
- if (!model) return;
2526
- const { code: newCode, lang: codeLanguage } = pendingUpdate;
2527
- pendingUpdate = null;
2528
- const processedCodeLanguage = processedLanguage(codeLanguage);
2529
- let prevCode = null;
2530
- if (appendBuffer.length > 0) try {
2531
- prevCode = model.getValue();
2532
- lastKnownCode = prevCode;
2533
- } catch {
2534
- prevCode = "";
2535
- }
2536
- else {
2537
- prevCode = lastKnownCode;
2538
- if (prevCode == null) try {
2539
- prevCode = model.getValue();
2540
- lastKnownCode = prevCode;
2541
- } catch {
2542
- prevCode = "";
2543
- }
2544
- }
2545
- if (prevCode === newCode) return;
2546
- const languageId = model.getLanguageId();
2547
- if (languageId !== processedCodeLanguage) {
2548
- if (processedCodeLanguage) monaco_shim_exports.editor.setModelLanguage(model, processedCodeLanguage);
2549
- const prevLineCount = model.getLineCount();
2550
- model.setValue(newCode);
2551
- lastKnownCode = newCode;
2552
- const newLineCount = model.getLineCount();
2553
- if (newLineCount !== prevLineCount) maybeScrollToBottom(newLineCount);
2554
- return;
2555
- }
2556
- if (newCode.startsWith(prevCode) && prevCode.length < newCode.length) {
2557
- const suffix = newCode.slice(prevCode.length);
2558
- if (suffix) appendCode(suffix, codeLanguage);
2559
- lastKnownCode = newCode;
2560
- return;
2561
- }
2562
- try {
2563
- const maxChars = minimalEditMaxCharsLocal;
2564
- const ratio = minimalEditMaxChangeRatioLocal;
2565
- const maxLen = Math.max(prevCode.length, newCode.length);
2566
- const changeRatio = maxLen > 0 ? Math.abs(newCode.length - prevCode.length) / maxLen : 0;
2567
- if (prevCode.length + newCode.length > maxChars || changeRatio > ratio) {
2568
- const prevLineCount = model.getLineCount();
2569
- model.setValue(newCode);
2570
- lastKnownCode = newCode;
2571
- const newLineCount = model.getLineCount();
2572
- if (newLineCount !== prevLineCount) maybeScrollToBottom(newLineCount);
2573
- return;
2574
- }
2575
- } catch {}
2576
- try {
2577
- applyMinimalEdit(prevCode, newCode);
2578
- lastKnownCode = newCode;
2579
- const newLineCount = model.getLineCount();
2580
- const prevLineCount = (prevCode ? prevCode.split("\n").length : 0) || model.getLineCount();
2581
- if (newLineCount !== prevLineCount) maybeScrollToBottom(newLineCount);
2582
- } catch {
2583
- try {
2584
- const prevLineCount = model.getLineCount();
2585
- model.setValue(newCode);
2586
- lastKnownCode = newCode;
2587
- const newLineCount = model.getLineCount();
2588
- if (newLineCount !== prevLineCount) maybeScrollToBottom(newLineCount);
2589
- } catch {}
2590
- }
2591
- }
2592
- function flushAppendBuffer() {
2593
- if (!editorView) return;
2594
- if (appendBuffer.length === 0) return;
2595
- appendBufferScheduled = false;
2596
- const model = editorView.getModel();
2597
- if (!model) {
2598
- appendBuffer.length = 0;
2599
- return;
2600
- }
2601
- const text = appendBuffer.join("");
2602
- appendBuffer.length = 0;
2603
- try {
2604
- const lastLine = model.getLineCount();
2605
- const lastColumn = model.getLineMaxColumn(lastLine);
2606
- const range = new monaco_shim_exports.Range(lastLine, lastColumn, lastLine, lastColumn);
2607
- const isReadOnly = editorView.getOption(monaco_shim_exports.editor.EditorOption.readOnly);
2608
- if (isReadOnly) model.applyEdits([{
2609
- range,
2610
- text,
2611
- forceMoveMarkers: true
2612
- }]);
2613
- else editorView.executeEdits("append", [{
2614
- range,
2615
- text,
2616
- forceMoveMarkers: true
2617
- }]);
2618
- if (lastKnownCode != null) lastKnownCode = lastKnownCode + text;
2619
- try {
2620
- if (lastLine !== model.getLineCount()) maybeScrollToBottom(model.getLineCount());
2621
- } catch {}
2622
- } catch {}
2623
- }
2624
- function updateCode(newCode, codeLanguage) {
2625
- if (editorMgr) editorMgr.updateCode(newCode, codeLanguage);
2626
- else {
2627
- pendingUpdate = {
2628
- code: newCode,
2629
- lang: codeLanguage
2630
- };
2631
- rafScheduler.schedule("update", () => {
2632
- if (!updateThrottleMs) {
2633
- flushPendingUpdate();
2634
- return;
2635
- }
2636
- const now = Date.now();
2637
- const since = now - lastFlushTime;
2638
- if (since >= updateThrottleMs) {
2639
- flushPendingUpdate();
2640
- return;
2641
- }
2642
- if (updateThrottleTimer != null) return;
2643
- const wait = updateThrottleMs - since;
2644
- updateThrottleTimer = setTimeout(() => {
2645
- updateThrottleTimer = null;
2646
- rafScheduler.schedule("update", () => flushPendingUpdate());
2647
- }, wait);
2648
- });
2649
- }
2650
- }
2651
- function setUpdateThrottleMs(ms) {
2652
- updateThrottleMs = ms;
2653
- }
2654
- function getUpdateThrottleMs() {
2655
- return updateThrottleMs;
2656
- }
2657
- function updateDiff(originalCode, modifiedCode, codeLanguage) {
2658
- if (diffMgr) diffMgr.updateDiff(originalCode, modifiedCode, codeLanguage);
2659
- }
2660
- function updateOriginal(newCode, codeLanguage) {
2661
- if (diffMgr) diffMgr.updateOriginal(newCode, codeLanguage);
2662
- }
2663
- function updateModified(newCode, codeLanguage) {
2664
- if (diffMgr) diffMgr.updateModified(newCode, codeLanguage);
2665
- }
2666
- function appendOriginal(appendText, codeLanguage) {
2667
- if (diffMgr) diffMgr.appendOriginal(appendText, codeLanguage);
2668
- }
2669
- function appendModified(appendText, codeLanguage) {
2670
- if (diffMgr) diffMgr.appendModified(appendText, codeLanguage);
2671
- }
2672
- return {
2673
- createEditor,
2674
- createDiffEditor,
2675
- cleanupEditor,
2676
- safeClean() {
2677
- rafScheduler.cancel("update");
2678
- pendingUpdate = null;
2679
- if (editorMgr) try {
2680
- editorMgr.safeClean();
2681
- } catch {}
2682
- if (diffMgr) try {
2683
- diffMgr.safeClean();
2684
- } catch {}
2685
- _hasScrollBar = false;
2686
- shouldAutoScroll = !!autoScrollInitial;
2687
- },
2688
- updateCode,
2689
- appendCode,
2690
- updateDiff,
2691
- updateOriginal,
2692
- updateModified,
2693
- appendOriginal,
2694
- appendModified,
2695
- setTheme: setThemeInternal,
2696
- setLanguage(language) {
2697
- if (editorMgr) {
2698
- editorMgr.setLanguage(language, languages$1);
2699
- return;
2700
- }
2701
- if (diffMgr) {
2702
- diffMgr.setLanguage(language, languages$1);
2703
- return;
2704
- }
2705
- if (languages$1.includes(language)) {
2706
- if (editorView) {
2707
- const model = editorView.getModel();
2708
- if (model && model.getLanguageId() !== language) monaco_shim_exports.editor.setModelLanguage(model, language);
2709
- }
2710
- if (originalModel && originalModel.getLanguageId() !== language) monaco_shim_exports.editor.setModelLanguage(originalModel, language);
2711
- if (modifiedModel && modifiedModel.getLanguageId() !== language) monaco_shim_exports.editor.setModelLanguage(modifiedModel, language);
2712
- } else console.warn(`Language "${language}" is not registered. Available languages: ${languages$1.join(", ")}`);
2713
- },
2714
- getCurrentTheme() {
2715
- return globalAppliedThemeName ?? requestedThemeName ?? globalRequestedThemeName ?? currentTheme.value;
2716
- },
2717
- getEditor() {
2718
- return monaco_shim_exports.editor;
2719
- },
2720
- getEditorView() {
2721
- return editorView;
2722
- },
2723
- getDiffEditorView() {
2724
- return diffEditorView;
2725
- },
2726
- getDiffModels() {
2727
- return {
2728
- original: originalModel,
2729
- modified: modifiedModel
2730
- };
2731
- },
2732
- getMonacoInstance() {
2733
- return monaco_shim_exports;
2734
- },
2735
- setUpdateThrottleMs,
2736
- getUpdateThrottleMs,
2737
- getCode() {
2738
- if (editorView) try {
2739
- var _editorView$getModel;
2740
- return ((_editorView$getModel = editorView.getModel()) === null || _editorView$getModel === void 0 ? void 0 : _editorView$getModel.getValue()) ?? null;
2741
- } catch {
2742
- return null;
2743
- }
2744
- if (diffEditorView || originalModel && modifiedModel) try {
2745
- const original = (originalModel === null || originalModel === void 0 ? void 0 : originalModel.getValue()) ?? "";
2746
- const modified = (modifiedModel === null || modifiedModel === void 0 ? void 0 : modifiedModel.getValue()) ?? "";
2747
- return {
2748
- original,
2749
- modified
2750
- };
2751
- } catch {
2752
- return null;
2753
- }
2754
- return null;
2755
- }
2756
- };
2757
- }
2758
-
2759
24
  //#endregion
2760
25
  export { RevealStrategy, clearHighlighterCache, defaultRevealDebounceMs, detectLanguage, getOrCreateHighlighter, preloadMonacoWorkers, registerMonacoThemes, useMonaco };