Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

29.0 KB
Raw Blame
import './CodeEditorImpl.scss'

import MonacoEditor, { type EditorProps, Monaco, DiffEditor as MonacoDiffEditor } from '@monaco-editor/react'
import { BuiltLogic, useActions, useMountedLogic, useValues } from 'kea'
import * as monacoModule from 'monaco-editor'
import { IDisposable, editor, editor as importedEditor } from 'monaco-editor'
import { useEffect, useMemo, useRef, useState } from 'react'

import { useBodyIsDark } from 'lib/hooks/useBodyIsDark'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { usePageVisibility } from 'lib/hooks/usePageVisibility'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { enableClipboardPaste } from 'lib/monaco/clipboardPaste'
import type { codeEditorLogicType } from 'lib/monaco/codeEditorLogic'
import { codeEditorLogic } from 'lib/monaco/codeEditorLogic'
import { findNextFocusableElement, findPreviousFocusableElement } from 'lib/monaco/domUtils'
import { trackFindWidgetVisibility } from 'lib/monaco/findWidgetBodyClass'
import { initCodeownersLanguage } from 'lib/monaco/languages/codeowners'
import { initHogLanguage } from 'lib/monaco/languages/hog'
import { initHogJsonLanguage } from 'lib/monaco/languages/hogJson'
import { initHogQLLanguage } from 'lib/monaco/languages/hogQL'
import { initHogTemplateLanguage } from 'lib/monaco/languages/hogTemplate'
import { initLiquidLanguage } from 'lib/monaco/languages/liquid'
import { initPromQLLanguage } from 'lib/monaco/languages/promql'
import { clearLogicReference, initModel } from 'lib/monaco/modelLogicReference'
import { registerMountedCodeEditor } from 'lib/monaco/mountedCodeEditors'
import 'lib/monaco/monacoEnvironment'
import { sharedMonacoOverflowRoot } from 'lib/monaco/sharedMonacoOverflowRoot'
import { retriggerSuggestionsAfterDeletion } from 'lib/monaco/suggestionRetrigger'
import { inStorybookTestRunner } from 'lib/utils/dom'

import { AnyDataNode, HogLanguage, HogQLMetadataResponse, NodeKind } from '~/queries/schema/schema-general'

export interface CodeEditorProps extends Omit<EditorProps, 'loading' | 'theme'> {
    queryKey?: string
    autocompleteContext?: string
    onPressCmdEnter?: (value: string, selectionType: 'selection' | 'full') => void
    /** Run the innermost subquery at cursor (Cmd+Shift+Enter) */
    onPressCmdShiftEnter?: () => void
    /** Pressed up in an empty code editor, likely to edit the previous message in a list */
    onPressUpNoValue?: () => void
    autoFocus?: boolean
    sourceQuery?: AnyDataNode
    globals?: Record<string, any>
    schema?: Record<string, any> | null
    /** Ask for per-filter index eligibility. Costs a second resolution pass server-side, so set it only where the result is rendered. */
    indexUsage?: boolean
    onMetadata?: (metadata: HogQLMetadataResponse | null) => void
    onMetadataLoading?: (loading: boolean) => void
    onFixWithAI?: (prompt: string) => void
    onError?: (error: string | null) => void
    /** How long to wait after an edit before validating. Set it higher where an error interrupts the user. */
    metadataDebounceMs?: number
    /** Validate against freshly fetched sources. Set it where the result blocks an action, because it costs a fetch per validation. */
    metadataFreshSources?: boolean
    /** Override the query sent for metadata validation (e.g. active query in multi-query mode) */
    metadataQuery?: string
    /** Character offset of metadataQuery within the full editor text, for correct marker positioning */
    metadataQueryOffset?: number
    /** The original value to compare against - renders it in diff mode */
    originalValue?: string
    /** Enable vim keybindings */
    enableVimMode?: boolean
    /** Vim commands to run when vim mode starts, one per line */
    vimrc?: string
}
let codeEditorIndex = 0

// Monaco measures glyph dimensions when an editor is created. If a web font is still
// loading at that moment it can latch onto stale (oversized) metrics and never relayout,
// surfacing as a giant-font editor (notably in visual snapshots). Remeasure once fonts
// settle so first paint — and the captured snapshot — is deterministic.
function remeasureFontsWhenReady(monaco: Monaco): void {
    if (typeof document === 'undefined' || !document.fonts) {
        return
    }
    void document.fonts.ready.then(() => monaco.editor.remeasureFonts())
}

function initEditor(
    monaco: Monaco,
    editor: importedEditor.IStandaloneCodeEditor,
    editorProps: Omit<CodeEditorProps, 'options' | 'onMount' | 'queryKey' | 'value'>,
    options: editor.IStandaloneEditorConstructionOptions,
    builtCodeEditorLogic: BuiltLogic<codeEditorLogicType>
): void {
    // This gives autocomplete access to the specific editor
    const model = editor.getModel()
    if (model) {
        initModel(model, builtCodeEditorLogic)
    }

    if (editorProps?.language === 'hog') {
        initHogLanguage(monaco)
    }
    if (editorProps?.language === 'hogQL' || editorProps?.language === 'hogQLExpr') {
        initHogQLLanguage(monaco, editorProps.language as HogLanguage)
    }
    if (editorProps?.language === 'hogTemplate') {
        initHogTemplateLanguage(monaco)
    }
    if (editorProps?.language === 'hogJson') {
        initHogJsonLanguage(monaco)
    }
    if (editorProps?.language === 'liquid') {
        initLiquidLanguage(monaco)
    }
    if (editorProps?.language === 'codeowners') {
        initCodeownersLanguage(monaco)
    }
    if (editorProps?.language === 'promql') {
        initPromQLLanguage(monaco)
    }

    editor.onKeyDown((evt) => {
        // Monaco handles Ctrl+Space on a parent DOM listener, including in an empty editor.
        if (evt.keyCode === monaco.KeyCode.Space && !evt.ctrlKey) {
            evt.stopPropagation()
        }

        if (options.tabFocusMode) {
            if (evt.keyCode === monaco.KeyCode.Tab && !evt.metaKey && !evt.ctrlKey) {
                const selection = editor.getSelection()
                if (
                    selection &&
                    (selection.startColumn !== selection.endColumn ||
                        selection.startLineNumber !== selection.endLineNumber)
                ) {
                    return
                }
                evt.preventDefault()
                evt.stopPropagation()

                const element: HTMLElement | null = evt.target?.parentElement?.parentElement?.parentElement ?? null
                if (!element) {
                    return
                }
                const nextElement = evt.shiftKey
                    ? findPreviousFocusableElement(element)
                    : findNextFocusableElement(element)

                if (nextElement && 'focus' in nextElement) {
                    nextElement.focus()
                }
            }
        }
        if (editorProps.onPressUpNoValue) {
            if (evt.keyCode === monaco.KeyCode.UpArrow && !evt.metaKey && !evt.ctrlKey && editor.getValue() === '') {
                evt.preventDefault()
                evt.stopPropagation()
                editorProps.onPressUpNoValue()
            }
        }
    })
}

export function CodeEditor({
    queryKey,
    options,
    onMount,
    value,
    onPressCmdEnter,
    onPressCmdShiftEnter,
    autoFocus,
    globals,
    sourceQuery,
    schema,
    onError,
    indexUsage,
    onMetadata,
    onMetadataLoading,
    onFixWithAI,
    metadataDebounceMs,
    metadataFreshSources,
    metadataQuery,
    metadataQueryOffset,
    originalValue,
    enableVimMode,
    vimrc,
    ...editorProps
}: CodeEditorProps): JSX.Element {
    const isDarkModeOn = useBodyIsDark()
    const scrollbarRendering = !inStorybookTestRunner() ? 'auto' : 'hidden'
    const [monacoAndEditor, setMonacoAndEditor] = useState(
        null as [Monaco, importedEditor.IStandaloneCodeEditor] | null
    )
    const [monaco, editor] = monacoAndEditor ?? []

    // Keep a ref to the editor for cleanup - ensures we can dispose it even if state is stale
    const editorRef = useRef<importedEditor.IStandaloneCodeEditor | null>(null)
    // In diff mode editorRef holds the inner modified sub-editor; this
    // ref holds the parent diff editor so cleanup can dispose the whole
    // diff (original editor, diff widget, decorations, view zones).
    const diffEditorRef = useRef<importedEditor.IStandaloneDiffEditor | null>(null)

    const vimModeRef = useRef<{ dispose: () => void } | null>(null)
    const vimStatusBarRef = useRef<HTMLDivElement | null>(null)

    const [realKey] = useState(() => codeEditorIndex++)
    // Monaco expects a string; a non-string `value` throws `t.create is not a function` deep in
    // its model setup. Serialize objects and arrays as pretty JSON so the content stays visible
    // (not `[object Object]`) and matches CodeEditorResizeable's height calc. Normalize once so
    // the editor and codeEditorLogic (which sends the value in metadata requests) agree on the
    // text. Keep null/undefined as-is so the editor stays uncontrolled.
    const normalizedValue = value == null || typeof value === 'string' ? value : JSON.stringify(value, null, 2)
    const builtCodeEditorLogic = codeEditorLogic({
        key: queryKey ?? `new/${realKey}`,
        query: normalizedValue ?? '',
        metadataQuery: metadataQuery,
        metadataQueryOffset: metadataQueryOffset,
        language: editorProps.language ?? 'text',
        globals,
        sourceQuery,
        monaco: monaco,
        editor: editor,
        onError,
        indexUsage,
        onMetadata,
        onMetadataLoading,
        onFixWithAI,
        metadataDebounceMs,
        metadataFreshSources,
        metadataFilters: sourceQuery?.kind === NodeKind.HogQLQuery ? sourceQuery.filters : undefined,
    })
    useMountedLogic(builtCodeEditorLogic)

    const { vimCommandHistory } = useValues(builtCodeEditorLogic)
    const { appendVimCommand } = useActions(builtCodeEditorLogic)
    // Vim mode reads the history only when it starts. Each ex command appends to the history, so a dependency
    // on it would restart Vim mode after every command and undo `:set` and `:map` changes made in the editor.
    const vimCommandHistoryRef = useRef(vimCommandHistory)
    vimCommandHistoryRef.current = vimCommandHistory

    const { isVisible } = usePageVisibility()

    const monacoRoot = sharedMonacoOverflowRoot()

    // Using useRef, not useState, as we don't want to reload the component when this changes.
    const monacoDisposables = useRef([] as IDisposable[])
    const mutationObserver = useRef<MutationObserver | null>(null)
    // Tracks whether the component is still mounted. Because CodeEditor is loaded
    // through a lazy Suspense facade, Monaco's async `onMount` can fire *after*
    // React has already torn the component down (quick tab switch / unmount).
    // Doing DOM work or state updates then throws "can't access dead object" in
    // Firefox, so `editorOnMount` bails out when this is false.
    const isMountedRef = useRef(true)
    // Track every model this editor instance has been attached to, so we can
    // dispose them on unmount. Monaco models live in a global registry until
    // explicitly disposed; without this, models accumulate forever and retain
    // their attached `codeEditorLogic` BuiltLogic via `(model as any).codeEditorLogic`.
    const editorModelsRef = useRef<Set<editor.ITextModel>>(new Set())
    // Live ref to the Monaco API so the cleanup closure (captured by
    // `useOnMountEffect`'s [] dep) can read the *current* value rather than
    // the `null` it had at mount time. Without this the `stillInUse` guard
    // in `disposeTrackedModels` is dead code: `monaco.editor.getEditors()`
    // returns `[]` and every tracked model is unconditionally disposed.
    const monacoApiRef = useRef<Monaco | null>(null)

    const disposeMonacoDisposables = (): void => {
        monacoDisposables.current.forEach((d) => d?.dispose())
        monacoDisposables.current = []
    }

    const disconnectMutationObserver = (): void => {
        mutationObserver.current?.disconnect()
        mutationObserver.current = null
    }

    const disposeTrackedModels = (): void => {
        const models = editorModelsRef.current
        if (models.size === 0) {
            return
        }
        const monacoApi = monacoApiRef.current
        // Skip a model if any OTHER live editor still holds it as its current
        // model — disposing would break that editor, and nulling its
        // `codeEditorLogic` would silently break HogQL autocomplete /
        // metadata providers in the surviving editor.
        const otherEditors = (monacoApi?.editor.getEditors?.() ?? []).filter(
            (e: importedEditor.ICodeEditor) => e !== editorRef.current
        )
        for (const model of models) {
            if (model.isDisposed()) {
                continue
            }
            const stillInUse = otherEditors.some((e: importedEditor.ICodeEditor) => e.getModel() === model)
            if (stillInUse) {
                continue
            }
            // Null the back-reference only on models we're actually about to
            // dispose. Doing it for shared models would break consumers
            // (e.g. hogQLAutocompleteProvider, hogQLMetadataProvider) that
            // read `model.codeEditorLogic` to look up logic state.
            clearLogicReference(model)
            try {
                model.dispose()
            } catch {
                // already disposed or in invalid state
            }
        }
        models.clear()
    }

    const trackEditorModels = (editorInstance: importedEditor.IStandaloneCodeEditor, monacoApi: Monaco): void => {
        monacoApiRef.current = monacoApi
        const initial = editorInstance.getModel()
        if (initial) {
            editorModelsRef.current.add(initial)
        }
        const disposable = editorInstance.onDidChangeModel((e) => {
            if (!e.newModelUrl) {
                return
            }
            const next = monacoApi.editor.getModel(e.newModelUrl)
            if (next) {
                editorModelsRef.current.add(next)
            }
        })
        monacoDisposables.current.push(disposable)
    }

    const disposeEditor = (): void => {
        try {
            if (diffEditorRef.current) {
                // Detach the models from the DiffEditorWidget before disposing it, so Monaco's
                // internal onWillDispose listeners don't fire against models that are torn down
                // right after ("TextModel got disposed before DiffEditorWidget model got reset").
                try {
                    diffEditorRef.current.setModel(null)
                } catch {
                    // already detached or disposed
                }
                diffEditorRef.current.dispose()
            } else {
                editorRef.current?.dispose()
            }
        } catch {
            // already disposed
        }
        editorRef.current = null
        diffEditorRef.current = null
    }

    useOnMountEffect(() => {
        // Re-arm on (re)mount so a prior cleanup — e.g. React Strict Mode's
        // mount/unmount/remount in dev — doesn't leave the live component
        // permanently flagged as unmounted.
        isMountedRef.current = true

        return () => {
            isMountedRef.current = false
            disposeMonacoDisposables()
            disconnectMutationObserver()

            // Dispose the editor while we still hold a strong reference: Monaco's
            // services (HoverService, ContextView, DomListener) keep refs to the
            // editor's container DOM that survive the library's dispose, so tearing
            // it down here lets Monaco release those DOM refs in the right order.
            // For the diff editor the library's own child cleanup has usually already
            // disposed the widget by now, so this is mostly a no-op guarded by the
            // try/catch in `disposeEditor`; model disposal is owned by
            // `disposeTrackedModels` below (see the `keepCurrent*` props on the widget).
            disposeEditor()

            // Now that our editor is disposed, dispose every model this
            // editor used and was uniquely owned by us. `disposeTrackedModels`
            // also nulls the `codeEditorLogic` back-reference on each
            // disposed model. Models still held by another live editor are
            // skipped on both counts, so HogQL autocomplete/metadata
            // providers (which read `model.codeEditorLogic`) keep working
            // for the surviving editor.
            disposeTrackedModels()

            setMonacoAndEditor(null)

            // Do NOT remove monacoRoot — it's a shared singleton that
            // Monaco's global services have permanent DomListeners on.
        }
    })

    useEffect(() => {
        if (!monaco) {
            return
        }
        monacoModule.typescript.typescriptDefaults.setCompilerOptions({
            jsx: editorProps?.path?.endsWith('.tsx')
                ? monacoModule.typescript.JsxEmit.React
                : monacoModule.typescript.JsxEmit.Preserve,
            esModuleInterop: true,
        })
    }, [monaco, editorProps.path])

    useEffect(() => {
        if (!monaco) {
            return
        }
        monacoModule.json.jsonDefaults.setDiagnosticsOptions({
            validate: true,
            schemas: schema
                ? [
                      {
                          uri: 'http://internal/node-schema.json',
                          fileMatch: ['*'],
                          schema: schema,
                      },
                  ]
                : [],
        })
    }, [monaco, schema])

    useEffect(() => {
        if (!editor) {
            return
        }

        let cancelled = false

        if (enableVimMode && vimStatusBarRef.current) {
            const statusBar = vimStatusBarRef.current
            void import('lib/monaco/vimMode').then(({ setupVimMode }) => {
                if (cancelled) {
                    return
                }
                vimModeRef.current = setupVimMode(editor, statusBar, {
                    initialHistory: vimCommandHistoryRef.current,
                    onCommandExecuted: appendVimCommand,
                    vimrc,
                })
            })
        } else if (vimModeRef.current) {
            vimModeRef.current.dispose()
            vimModeRef.current = null
        }

        return () => {
            cancelled = true
            if (vimModeRef.current) {
                vimModeRef.current.dispose()
                vimModeRef.current = null
            }
        }
    }, [editor, enableVimMode, vimrc, appendVimCommand])

    // The wrapper calls `editor.updateOptions` whenever this object's identity changes, and
    // Monaco revalidates every option on each call, so only rebuild it when an input changes.
    const editorOptions = useMemo<editor.IStandaloneEditorConstructionOptions>(
        () => ({
            minimap: {
                enabled: false,
            },
            scrollBeyondLastLine: false,
            automaticLayout: true,
            fixedOverflowWidgets: true,
            glyphMargin: false,
            folding: true,
            wordWrap: 'off',
            lineNumbers: 'on',
            tabFocusMode: false,
            overviewRulerBorder: true,
            hideCursorInOverviewRuler: false,
            overviewRulerLanes: 3,
            overflowWidgetsDomNode: monacoRoot,
            ...options,
            padding: { bottom: enableVimMode ? 28 : 8, top: 8 },
            scrollbar: {
                vertical: scrollbarRendering,
                horizontal: scrollbarRendering,
                alwaysConsumeMouseWheel: false,
                ...options?.scrollbar,
            },
        }),
        [options, enableVimMode, scrollbarRendering, monacoRoot]
    )
    const diffEditorOptions = useMemo<editor.IStandaloneDiffEditorConstructionOptions>(
        () => ({
            ...editorOptions,
            renderSideBySide: false,
            acceptSuggestionOnEnter: 'on',
            renderGutterMenu: false,
        }),
        [editorOptions]
    )

    const editorOnMount = (editor: importedEditor.IStandaloneCodeEditor, monaco: Monaco): void => {
        // The lazy Suspense facade can resolve after the component has already
        // unmounted (quick tab switch). Monaco still calls onMount, but touching
        // DOM or setting state now throws "can't access dead object" in Firefox.
        // Dispose the orphaned editor and bail before doing any of that.
        if (!isMountedRef.current) {
            try {
                editor.dispose()
            } catch {
                // already disposed
            }
            return
        }

        editorRef.current = editor
        // Perf-benchmark escape hatch. Monaco is otherwise unreachable from the page, so a
        // benchmark can neither time nor stub editor methods to isolate a cost. Inert unless a
        // harness sets the flag before load — see playwright/e2e/sql-editor-typing-perf.spec.ts.
        if ((window as any).__PERF_MONACO_HOOK__) {
            ;((window as any).__monacoEditors ??= []).push(editor)
            ;(window as any).__monaco = monaco
        }
        trackEditorModels(editor, monaco)
        setMonacoAndEditor([monaco, editor])
        initEditor(monaco, editor, editorProps, options ?? {}, builtCodeEditorLogic)
        remeasureFontsWhenReady(monaco)
        monacoDisposables.current.push(trackFindWidgetVisibility(editor))
        monacoDisposables.current.push({ dispose: registerMountedCodeEditor({ editor, monaco }) })

        monacoDisposables.current.push(retriggerSuggestionsAfterDeletion(editor))

        // Override Monaco's suggestion widget styling to prevent truncation
        const styleId = 'monaco-suggestion-widget-fix'
        const overrideSuggestionWidgetStyling = (): void => {
            // Only add style tag if it doesn't already exist
            if (!document.getElementById(styleId)) {
                const style = document.createElement('style')
                style.id = styleId
                style.textContent = `
                .monaco-editor .suggest-widget .monaco-list .monaco-list-row.string-label>.contents>.main>.left>.monaco-icon-label {
                   flex-shrink: 0;
                }
                `
                document.head.appendChild(style)
            }
        }

        // Apply styling immediately
        overrideSuggestionWidgetStyling()

        // Monitor for suggestion widget creation and apply styling
        const observer = new MutationObserver(() => {
            // If the component unmounted after the observer was installed, stop
            // querying the (now reclaimed) DOM — this is the Firefox "can't
            // access dead object" crash. Disconnect defensively and bail.
            if (!isMountedRef.current) {
                observer.disconnect()
                return
            }
            try {
                const suggestWidget = document.querySelector('.monaco-editor .suggest-widget')
                if (suggestWidget) {
                    overrideSuggestionWidgetStyling()
                }
            } catch {
                observer.disconnect()
            }
        })

        mutationObserver.current = observer
        observer.observe(document.body, { childList: true, subtree: true })

        // Clean up observers
        monacoDisposables.current.push({
            dispose: () => observer.disconnect(),
        })

        monacoDisposables.current.push(
            monaco.editor.registerCommand('posthog.hogql.fixWithAI', (_: unknown, prompt: unknown) => {
                if (typeof prompt === 'string' && prompt.length > 0) {
                    onFixWithAI?.(prompt)
                }
            })
        )

        if (onPressCmdEnter) {
            monacoDisposables.current.push(
                editor.addAction({
                    id: 'saveAndRunPostHog',
                    label: 'Save and run query',
                    keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter],
                    run: () => {
                        const selection = editor.getSelection()
                        const model = editor.getModel()
                        if (selection && model) {
                            const highlightedText = model.getValueInRange(selection)
                            onPressCmdEnter(highlightedText, 'selection')
                            return
                        }

                        onPressCmdEnter(editor.getValue(), 'full')
                    },
                })
            )
        }
        if (onPressCmdShiftEnter) {
            monacoDisposables.current.push(
                editor.addAction({
                    id: 'runSubqueryPostHog',
                    label: 'Run subquery at cursor',
                    keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.Enter],
                    run: () => {
                        onPressCmdShiftEnter()
                    },
                })
            )
        }
        // Fix Monaco's broken right-click "Paste" by overriding the command rather than adding a
        // second menu item (see enableClipboardPaste).
        monacoDisposables.current.push(enableClipboardPaste(editor))

        if (autoFocus) {
            editor.focus()
            const model = editor.getModel()
            if (model) {
                editor.setPosition({
                    column: model.getLineContent(model.getLineCount()).length + 1,
                    lineNumber: model.getLineCount(),
                })
            }
        }

        onMount?.(editor, monaco)
    }

    useEffect(() => {
        if (!mutationObserver.current) {
            return
        }

        if (isVisible) {
            mutationObserver.current.observe(document.body, { childList: true, subtree: true })
        } else {
            mutationObserver.current.disconnect()
        }
    }, [isVisible])

    if (originalValue) {
        // If originalValue is provided, we render a diff editor instead
        const diffEditorOnMount = (diff: importedEditor.IStandaloneDiffEditor, monaco: Monaco): void => {
            // Same lazy-facade race as editorOnMount: bail if we already unmounted.
            if (!isMountedRef.current) {
                try {
                    diff.dispose()
                } catch {
                    // already disposed
                }
                return
            }

            const modifiedEditor = diff.getModifiedEditor()
            editorRef.current = modifiedEditor
            diffEditorRef.current = diff
            trackEditorModels(modifiedEditor, monaco)
            monacoDisposables.current.push(trackFindWidgetVisibility(modifiedEditor))
            monacoDisposables.current.push(trackFindWidgetVisibility(diff.getOriginalEditor()))
            const original = diff.getOriginalEditor().getModel()
            if (original) {
                editorModelsRef.current.add(original)
            }
            setMonacoAndEditor([monaco, modifiedEditor])
            remeasureFontsWhenReady(monaco)

            if (editorProps.onChange) {
                const disposable = modifiedEditor.onDidChangeModelContent((event: editor.IModelContentChangedEvent) => {
                    editorProps.onChange?.(modifiedEditor.getValue(), event)
                })
                monacoDisposables.current.push(disposable)
            }
            onMount?.(modifiedEditor, monaco)
        }

        return (
            <div className="CodeEditor relative h-full w-full" data-editor-ready={monacoAndEditor ? 'true' : 'false'}>
                <MonacoDiffEditor
                    key={queryKey}
                    loading={<Spinner />}
                    theme={isDarkModeOn ? 'vs-dark' : 'vs-light'}
                    original={originalValue}
                    modified={value}
                    options={diffEditorOptions}
                    onMount={diffEditorOnMount}
                    {...editorProps}
                    // Own model disposal ourselves via `disposeTrackedModels`. Left to the library,
                    // its unmount disposes the models before resetting the widget's own reference to
                    // them ("TextModel got disposed before DiffEditorWidget model got reset"), and it
                    // fires on teardown paths that don't unmount CodeEditor (diff dismissed, `key`
                    // change), where our `disposeEditor` cleanup never runs.
                    keepCurrentOriginalModel
                    keepCurrentModifiedModel
                />
            </div>
        )
    }

    return (
        <div className="CodeEditor relative h-full w-full" data-editor-ready={monacoAndEditor ? 'true' : 'false'}>
            <MonacoEditor // eslint-disable-line react/forbid-elements
                key={queryKey}
                theme={isDarkModeOn ? 'vs-dark' : 'vs-light'}
                loading={<Spinner />}
                value={normalizedValue}
                options={editorOptions}
                onMount={editorOnMount}
                {...editorProps}
            />
            {enableVimMode && (
                <div
                    ref={vimStatusBarRef}
                    className="CodeEditor__vim-status-bar absolute bottom-0 left-0 right-0 font-mono text-xs px-2 py-0.5 bg-bg-light border-t z-10"
                />
            )}
        </div>
    )
}