import type { ValidationState } from '../../common/static-wrappers/interfaces/validation-interface'; import { markRaw } from 'vue'; import { Prop, toNative, Watch } from 'vue-facing-decorator'; import TsxComponent, { Component } from '../../app/vuetsx'; import { isNullOrEmpty } from '../../common/utils/is-null-or-empty'; import LoadingIndicator from '../loading-indicator'; const MONACO_CDN = 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.20.0/min'; /** * How long the CDN gets before the load is treated as failed. * * Without it, a request that HANGS rather than errors (captive portal, throttled or * half-open connection) never settles: `onerror` never fires, the promise never rejects, * the spinner stays up forever and `loadFailed` is never called, so a host that has a * plain-textarea fallback never gets to use it. */ const MONACO_LOAD_TIMEOUT_MS = 15_000; /** * Re-measure passes after the editor is created, in ms. * * Monaco measures its container AT CREATE time and, on 0.20, `automaticLayout` does not * reliably recover from a zero-size first measurement (its polling implementation predates * the ResizeObserver rewrite). A host that mounts this component inside something still * animating — a Bootstrap modal fade is the common case — therefore gets an editor that * paints nothing until something forces a layout. `layout()` is idempotent, so re-running * it a few times across the animation is cheap and removes the whole class of bug. */ const MONACO_RELAYOUT_DELAYS_MS = [ 0, 150, 450, 900, ]; let monacoLoadPromise: Promise | null = null; const loadMonaco = (): Promise => { if ((window as any).monaco) { return Promise.resolve(); } if (monacoLoadPromise) { return monacoLoadPromise; } monacoLoadPromise = new Promise((resolve, reject) => { let settled = false; // EVERY failure path clears the memo. Previously only `script.onerror` did, so once // the inner `require([...])` rejected, every later mount awaited the same rejected // promise and the editor stayed broken for the rest of the page session — one // transient network blip poisoned the tab. const fail = (error: Error) => { if (settled) { return; } settled = true; clearTimeout(timer); monacoLoadPromise = null; reject(error); }; const succeed = () => { if (settled) { return; } settled = true; clearTimeout(timer); resolve(); }; const timer = setTimeout(() => fail(new Error(`Monaco Editor did not load within ${MONACO_LOAD_TIMEOUT_MS}ms`)), MONACO_LOAD_TIMEOUT_MS); const loaderScript = document.createElement('script'); loaderScript.src = `${MONACO_CDN}/vs/loader.js`; loaderScript.onload = () => { const require = (window as any).require; require.config({ paths: { vs: `${MONACO_CDN}/vs` } }); require( ['vs/editor/editor.main'], () => { succeed(); }, (err: any) => { fail(err instanceof Error ? err : new Error(String(err))); }, ); }; loaderScript.onerror = () => { fail(new Error('Failed to load Monaco Editor')); }; document.head.appendChild(loaderScript); }); return monacoLoadPromise; }; interface MonacoEditorArgs { value?: string; changed?: (v: string) => void; language?: string; height?: string; /** Invoked when the Monaco CDN load fails — callers can fall back to a plain editor. */ loadFailed?: () => void; /** Extra monaco editor options merged into the defaults (e.g. minimap, wordWrap). */ options?: Record; /** Validation state of the bound value (the base TsxComponent prop — declared here so TSX callers can pass it). */ validationState?: ValidationState; } @Component export class MonacoEditorComponent extends TsxComponent implements MonacoEditorArgs { @Prop() value: string; @Prop() language: string; @Prop() height!: string; @Prop() changed: (newValue: string) => void; @Prop() loadFailed: () => void; @Prop() options: Record; editor: any; monacoLoading: boolean = false; /** Pending re-measure timers; cleared on teardown so none fires into a dead component. */ layoutTimers: ReturnType[] = []; /** * Set on teardown. The editor is created a tick after mount, or only once the CDN load * resolves; when the component unmounted in between (e.g. its modal section was swapped for * another one), that late create must not happen — nothing would ever dispose it. */ unmounted: boolean = false; raiseChangeEvent() { this.populateValidationDeclaration(); if (this.changed != null) { // NEVER assign `this.value` here: `value` is a prop and the readonly // proxy trap THROWS in Vue 3, which would kill the relay before // `changed` fires. The parent feeds the new value back via the prop. this.changed(this._getValue()); } } mounted() { if ((window as any).monaco) { // NOT synchronous, deliberately. `mounted()` can run while this component's // container still has no layout — mounting inside a modal that is mid-fade is the // everyday case — and monaco measures the container AT CREATE. Creating here // produced an editor that painted NOTHING: the model held the full text, the // container reported a sane size moments later, and only a viewport resize ever // repainted it. Deferring one tick and laying out afterwards fixes it. this.$nextTick(() => { this.initMonaco(); }); } else { this.monacoLoading = true; loadMonaco().then(() => { this.monacoLoading = false; this.$nextTick(() => { this.initMonaco(); }); }).catch(() => { // CDN unreachable / loader error: stop the spinner and let the // caller degrade (e.g. swap in a plain textarea). this.monacoLoading = false; if (this.loadFailed != null) { this.loadFailed(); } }); } } getOptions() { return { ...(this.options || {}) }; } initMonaco() { // markRaw is MANDATORY: `editor` is a reactive class field, so without it // Vue wraps the monaco instance (and every object reached through it) in // reactive proxies. Monaco's piece-tree walks compare node identity // against sentinels — proxied nodes never match, so the first // `getValue()` inside a change event spins forever and freezes the tab. if (this.editor || this.unmounted) { return; } this.editor = markRaw((window as any).monaco.editor.create((this.$el as HTMLElement), { value: this.value, language: this.language, theme: 'vs', ...this.getOptions(), })); this._editorMounted(this.editor); this.scheduleLayoutPasses(); }; /** * Re-measures the editor across whatever animation the host is running. See * {@link MONACO_RELAYOUT_DELAYS_MS} — the container's final size routinely lands AFTER * creation, and monaco will not notice on its own. */ scheduleLayoutPasses() { for (const delay of MONACO_RELAYOUT_DELAYS_MS) { const timer = setTimeout(() => this.refreshLayout(), delay); this.layoutTimers.push(timer); } }; /** * Disposes the editor AND its model. * * There was no teardown at all, so every mount leaked both — measured 1 model after the * first mount, 2 after the second, 3 after the third, each holding a full copy of the * document. In an SPA where the host is opened repeatedly that grows without bound, and * monaco's own model registry keeps them alive. */ beforeUnmount() { this.unmounted = true; for (const timer of this.layoutTimers) { clearTimeout(timer); } this.layoutTimers = []; const editor = this.editor; if (editor) { this.editor = null; editor.getModel()?.dispose(); editor.dispose(); } }; refreshLayout() { this.editor && this.$nextTick(() => { this.editor.layout(); }); } _getEditor() { if (!this.editor) { return null; } return this.editor; }; _setValue(value) { const editor = this._getEditor(); if (editor) { return editor.setValue(value); } }; _getValue() { const editor = this._getEditor(); if (!editor) { return ''; } return editor.getValue(); }; _editorMounted(editor) { editor.onDidChangeModelContent((event) => { this.raiseChangeEvent(); }); }; @Watch('value') onValueChanged(val: string, oldVal: string) { if (val != oldVal) { const currentVal = this._getValue(); if (currentVal != val) { this._setValue(val); } } } render(h) { return (
{this.monacoLoading && }
); } } const MonacoEditor = toNative(MonacoEditorComponent); export default MonacoEditor;