refactor: move to modern monaco (#32966)

This commit is contained in:
Stephen Zhou
2026-03-11 17:44:12 +08:00
committed by GitHub
parent b2df0010ce
commit 5ff7d2c895
112 changed files with 334 additions and 54292 deletions

View File

@ -0,0 +1,25 @@
import type { InitOptions } from 'modern-monaco'
export const LIGHT_THEME_ID = 'light-plus'
export const DARK_THEME_ID = 'dark-plus'
const DEFAULT_INIT_OPTIONS: InitOptions = {
defaultTheme: DARK_THEME_ID,
themes: [
LIGHT_THEME_ID,
DARK_THEME_ID,
],
}
let monacoInitPromise: Promise<typeof import('modern-monaco/editor-core') | null> | null = null
export const initMonaco = async () => {
if (!monacoInitPromise) {
monacoInitPromise = (async () => {
const { init } = await import('modern-monaco')
return init(DEFAULT_INIT_OPTIONS)
})()
}
return monacoInitPromise
}

View File

@ -0,0 +1,250 @@
'use client'
import type { editor as MonacoEditor } from 'modern-monaco/editor-core'
import type { FC } from 'react'
import * as React from 'react'
import { useEffect, useMemo, useRef, useState } from 'react'
import useTheme from '@/hooks/use-theme'
import { Theme } from '@/types/app'
import { cn } from '@/utils/classnames'
import { DARK_THEME_ID, initMonaco, LIGHT_THEME_ID } from './init'
type ModernMonacoEditorProps = {
value: string
language: string
readOnly?: boolean
options?: MonacoEditor.IEditorOptions
onChange?: (value: string) => void
onFocus?: () => void
onBlur?: () => void
onReady?: (editor: MonacoEditor.IStandaloneCodeEditor, monaco: typeof import('modern-monaco/editor-core')) => void
loading?: React.ReactNode
className?: string
style?: React.CSSProperties
}
type MonacoModule = typeof import('modern-monaco/editor-core')
type EditorCallbacks = Pick<ModernMonacoEditorProps, 'onBlur' | 'onChange' | 'onFocus' | 'onReady'>
type EditorSetup = {
editorOptions: MonacoEditor.IEditorOptions
language: string
resolvedTheme: string
}
const syncEditorValue = (
editor: MonacoEditor.IStandaloneCodeEditor,
monaco: MonacoModule,
model: MonacoEditor.ITextModel,
value: string,
preventTriggerChangeEventRef: React.RefObject<boolean>,
) => {
const currentValue = model.getValue()
if (currentValue === value)
return
if (editor.getOption(monaco.editor.EditorOption.readOnly)) {
editor.setValue(value)
return
}
preventTriggerChangeEventRef.current = true
try {
editor.executeEdits('', [{
range: model.getFullModelRange(),
text: value,
forceMoveMarkers: true,
}])
editor.pushUndoStop()
}
finally {
preventTriggerChangeEventRef.current = false
}
}
const bindEditorCallbacks = (
editor: MonacoEditor.IStandaloneCodeEditor,
monaco: MonacoModule,
callbacksRef: React.RefObject<EditorCallbacks>,
preventTriggerChangeEventRef: React.RefObject<boolean>,
) => {
const changeDisposable = editor.onDidChangeModelContent(() => {
if (preventTriggerChangeEventRef.current)
return
callbacksRef.current.onChange?.(editor.getValue())
})
const keydownDisposable = editor.onKeyDown((event) => {
const { key, code } = event.browserEvent
if (key === ' ' || code === 'Space')
event.stopPropagation()
})
const focusDisposable = editor.onDidFocusEditorText(() => {
callbacksRef.current.onFocus?.()
})
const blurDisposable = editor.onDidBlurEditorText(() => {
callbacksRef.current.onBlur?.()
})
return () => {
blurDisposable.dispose()
focusDisposable.dispose()
keydownDisposable.dispose()
changeDisposable.dispose()
}
}
export const ModernMonacoEditor: FC<ModernMonacoEditorProps> = ({
value,
language,
readOnly = false,
options,
onChange,
onFocus,
onBlur,
onReady,
loading,
className,
style,
}) => {
const { theme: appTheme } = useTheme()
const resolvedTheme = appTheme === Theme.light ? LIGHT_THEME_ID : DARK_THEME_ID
const [isEditorReady, setIsEditorReady] = useState(false)
const containerRef = useRef<HTMLDivElement>(null)
const editorRef = useRef<MonacoEditor.IStandaloneCodeEditor | null>(null)
const modelRef = useRef<MonacoEditor.ITextModel | null>(null)
const monacoRef = useRef<MonacoModule | null>(null)
const preventTriggerChangeEventRef = useRef(false)
const valueRef = useRef(value)
const callbacksRef = useRef<EditorCallbacks>({ onChange, onFocus, onBlur, onReady })
const editorOptions = useMemo<MonacoEditor.IEditorOptions>(() => ({
automaticLayout: true,
readOnly,
domReadOnly: true,
minimap: { enabled: false },
wordWrap: 'on',
fixedOverflowWidgets: true,
tabFocusMode: false,
...options,
}), [readOnly, options])
const setupRef = useRef<EditorSetup>({
editorOptions,
language,
resolvedTheme,
})
useEffect(() => {
valueRef.current = value
}, [value])
useEffect(() => {
callbacksRef.current = { onChange, onFocus, onBlur, onReady }
}, [onChange, onFocus, onBlur, onReady])
useEffect(() => {
setupRef.current = {
editorOptions,
language,
resolvedTheme,
}
}, [editorOptions, language, resolvedTheme])
useEffect(() => {
let disposed = false
let cleanup: (() => void) | undefined
const setup = async () => {
const monaco = await initMonaco()
if (!monaco || disposed || !containerRef.current)
return
monacoRef.current = monaco
const editor = monaco.editor.create(containerRef.current, setupRef.current.editorOptions)
editorRef.current = editor
const model = monaco.editor.createModel(valueRef.current, setupRef.current.language)
modelRef.current = model
editor.setModel(model)
monaco.editor.setTheme(setupRef.current.resolvedTheme)
const disposeCallbacks = bindEditorCallbacks(
editor,
monaco,
callbacksRef,
preventTriggerChangeEventRef,
)
const resizeObserver = new ResizeObserver(() => {
editor.layout()
})
resizeObserver.observe(containerRef.current)
callbacksRef.current.onReady?.(editor, monaco)
setIsEditorReady(true)
cleanup = () => {
resizeObserver.disconnect()
disposeCallbacks()
editor.dispose()
model.dispose()
setIsEditorReady(false)
}
}
setup()
return () => {
disposed = true
cleanup?.()
}
}, [])
useEffect(() => {
const editor = editorRef.current
if (!editor)
return
editor.updateOptions(editorOptions)
}, [editorOptions])
useEffect(() => {
const monaco = monacoRef.current
const model = modelRef.current
if (!monaco || !model)
return
monaco.editor.setModelLanguage(model, language)
}, [language])
useEffect(() => {
const monaco = monacoRef.current
if (!monaco)
return
monaco.editor.setTheme(resolvedTheme)
}, [resolvedTheme])
useEffect(() => {
const editor = editorRef.current
const monaco = monacoRef.current
const model = modelRef.current
if (!editor || !monaco || !model)
return
syncEditorValue(editor, monaco, model, value, preventTriggerChangeEventRef)
}, [value])
return (
<div
className={cn('relative h-full w-full', className)}
style={style}
>
<div
ref={containerRef}
className="h-full w-full"
/>
{!isEditorReady && !!loading && (
<div className="absolute inset-0 flex items-center justify-center">
{loading}
</div>
)}
</div>
)
}

View File

@ -1,24 +1,18 @@
'use client'
import type { FC } from 'react'
import Editor, { loader } from '@monaco-editor/react'
import { noop } from 'es-toolkit/function'
import * as React from 'react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
getFilesInLogs,
} from '@/app/components/base/file-uploader/utils'
import { ModernMonacoEditor } from '@/app/components/base/modern-monaco/modern-monaco-editor'
import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
import useTheme from '@/hooks/use-theme'
import { Theme } from '@/types/app'
import { cn } from '@/utils/classnames'
import { basePath } from '@/utils/var'
import Base from '../base'
import './style.css'
// load file from local instead of cdn https://github.com/suren-atoyan/monaco-react/issues/482
if (typeof window !== 'undefined')
loader.config({ paths: { vs: `${window.location.origin}${basePath}/vs` } })
const CODE_EDITOR_LINE_HEIGHT = 18
export type Props = {
@ -72,15 +66,10 @@ const CodeEditor: FC<Props> = ({
tip,
footer,
}) => {
const { t } = useTranslation()
const [isFocus, setIsFocus] = React.useState(false)
const [isMounted, setIsMounted] = React.useState(false)
const minHeight = height || 200
const [editorContentHeight, setEditorContentHeight] = useState(56)
const { theme: appTheme } = useTheme()
const valueRef = useRef(value)
useEffect(() => {
valueRef.current = value
}, [value])
const fileList = useMemo(() => {
if (typeof value === 'object')
@ -106,18 +95,15 @@ const CodeEditor: FC<Props> = ({
const handleEditorDidMount = (editor: any, monaco: any) => {
editorRef.current = editor
resizeEditorToContent()
editor.onDidFocusEditorText(() => {
setIsFocus(true)
})
editor.onDidBlurEditorText(() => {
setIsFocus(false)
})
monaco.editor.setTheme(appTheme === Theme.light ? 'light' : 'vs-dark') // Fix: sometimes not load the default theme
onMount?.(editor, monaco)
setIsMounted(true)
}
const handleEditorFocus = () => {
setIsFocus(true)
}
const handleEditorBlur = () => {
setIsFocus(false)
}
const outPutValue = (() => {
@ -131,31 +117,23 @@ const CodeEditor: FC<Props> = ({
}
})()
const theme = useMemo(() => {
if (appTheme === Theme.light)
return 'light'
return 'vs-dark'
}, [appTheme])
const main = (
<>
{/* https://www.npmjs.com/package/@monaco-editor/react */}
<Editor
<ModernMonacoEditor
// className='min-h-[100%]' // h-full
// language={language === CodeLanguage.javascript ? 'javascript' : 'python'}
language={languageMap[language] || 'javascript'}
theme={isMounted ? theme : 'default-theme'} // sometimes not load the default theme
value={outPutValue}
loading={<span className="text-text-primary">Loading...</span>}
readOnly={readOnly}
onChange={handleEditorChange}
onFocus={handleEditorFocus}
onBlur={handleEditorBlur}
onReady={handleEditorDidMount}
loading={<span className="text-text-primary">{t('loading', { ns: 'common' })}</span>}
// https://microsoft.github.io/monaco-editor/typedoc/interfaces/editor.IEditorOptions.html
options={{
readOnly,
domReadOnly: true,
quickSuggestions: false,
minimap: { enabled: false },
lineNumbersMinChars: 1, // would change line num width
wordWrap: 'on', // auto line wrap
// lineNumbers: (num) => {
// return <div>{num}</div>
// }
@ -165,7 +143,6 @@ const CodeEditor: FC<Props> = ({
},
stickyScroll: { enabled: false },
}}
onMount={handleEditorDidMount}
/>
{!outPutValue && !isFocus && <div className="pointer-events-none absolute left-[36px] top-0 text-[13px] font-normal leading-[18px] text-components-input-text-placeholder">{placeholder}</div>}
</>

View File

@ -1,13 +1,11 @@
import type { FC } from 'react'
import { Editor } from '@monaco-editor/react'
import { RiClipboardLine, RiIndentIncrease } from '@remixicon/react'
import copy from 'copy-to-clipboard'
import * as React from 'react'
import { useCallback, useEffect, useMemo, useRef } from 'react'
import { useCallback, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { ModernMonacoEditor } from '@/app/components/base/modern-monaco/modern-monaco-editor'
import Tooltip from '@/app/components/base/tooltip'
import useTheme from '@/hooks/use-theme'
import { Theme } from '@/types/app'
import { cn } from '@/utils/classnames'
type CodeEditorProps = {
@ -35,54 +33,11 @@ const CodeEditor: FC<CodeEditorProps> = ({
onBlur,
}) => {
const { t } = useTranslation()
const { theme } = useTheme()
const monacoRef = useRef<any>(null)
const editorRef = useRef<any>(null)
const [isMounted, setIsMounted] = React.useState(false)
const containerRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (monacoRef.current) {
if (theme === Theme.light)
monacoRef.current.editor.setTheme('light-theme')
else
monacoRef.current.editor.setTheme('dark-theme')
}
}, [theme])
const handleEditorDidMount = useCallback((editor: any, monaco: any) => {
const handleEditorReady = useCallback((editor: any) => {
editorRef.current = editor
monacoRef.current = monaco
editor.onDidFocusEditorText(() => {
onFocus?.()
})
editor.onDidBlurEditorText(() => {
onBlur?.()
})
monaco.editor.defineTheme('light-theme', {
base: 'vs',
inherit: true,
rules: [],
colors: {
'editor.background': '#00000000',
'editor.lineHighlightBackground': '#00000000',
'focusBorder': '#00000000',
},
})
monaco.editor.defineTheme('dark-theme', {
base: 'vs-dark',
inherit: true,
rules: [],
colors: {
'editor.background': '#00000000',
'editor.lineHighlightBackground': '#00000000',
'focusBorder': '#00000000',
},
})
monaco.editor.setTheme('light-theme')
setIsMounted(true)
editor.getModel()?.updateOptions({ tabSize: 2 })
}, [])
const formatJsonContent = useCallback(() => {
@ -95,29 +50,11 @@ const CodeEditor: FC<CodeEditorProps> = ({
onUpdate?.(value)
}, [onUpdate])
const editorTheme = useMemo(() => {
if (theme === Theme.light)
return 'light-theme'
return 'dark-theme'
}, [theme])
useEffect(() => {
const resizeObserver = new ResizeObserver(() => {
editorRef.current?.layout()
})
if (containerRef.current)
resizeObserver.observe(containerRef.current)
return () => {
resizeObserver.disconnect()
}
}, [])
return (
<div className={cn('flex h-full flex-col overflow-hidden bg-components-input-bg-normal', hideTopMenu && 'pt-2', className)}>
{!hideTopMenu && (
<div className="flex items-center justify-between pl-2 pr-1 pt-1">
<div className="system-xs-semibold-uppercase py-0.5 text-text-secondary">
<div className="py-0.5 text-text-secondary system-xs-semibold-uppercase">
<span className="px-1 py-0.5">JSON</span>
</div>
<div className="flex items-center gap-x-0.5">
@ -146,19 +83,17 @@ const CodeEditor: FC<CodeEditorProps> = ({
)}
{topContent}
<div className={cn('relative overflow-hidden', editorWrapperClassName)}>
<Editor
defaultLanguage="json"
theme={isMounted ? editorTheme : 'default-theme'} // sometimes not load the default theme
<ModernMonacoEditor
language="json"
value={value}
readOnly={readOnly}
onChange={handleEditorChange}
onMount={handleEditorDidMount}
onReady={handleEditorReady}
onFocus={onFocus}
onBlur={onBlur}
loading={<span className="text-text-primary">{t('loading', { ns: 'common' })}</span>}
options={{
readOnly,
domReadOnly: true,
minimap: { enabled: false },
tabSize: 2,
scrollBeyondLastLine: false,
wordWrap: 'on',
wrappingIndent: 'same',
overviewRulerBorder: false,
hideCursorInOverviewRuler: true,

View File

@ -146,6 +146,16 @@ describe('isEventTargetInputArea', () => {
expect(isEventTargetInputArea(el)).toBe(true)
})
it('should return true for monaco editor descendants', () => {
const wrapper = document.createElement('div')
wrapper.className = 'monaco-editor'
const child = document.createElement('div')
wrapper.appendChild(child)
document.body.appendChild(wrapper)
expect(isEventTargetInputArea(child)).toBe(true)
wrapper.remove()
})
it('should return undefined for non-input elements', () => {
const el = document.createElement('div')
expect(isEventTargetInputArea(el)).toBeUndefined()

View File

@ -32,6 +32,9 @@ export const isEventTargetInputArea = (target: HTMLElement) => {
if (target.contentEditable === 'true')
return true
if (target.closest?.('.monaco-editor, .monaco-diff-editor'))
return true
}
/**