Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(frontend): migrate monaco editor to react (#19951)
boojack66eabb2b98d2
diff --git a/frontend/src/react/components/monaco/DiffMonaco.tsx b/frontend/src/react/components/monaco/DiffMonaco.tsxnew file mode 100644index 0000000000..601d63b8a5--- /dev/null+++ b/frontend/src/react/components/monaco/DiffMonaco.tsx@@ -0,0 +1,169 @@+import { Loader2 } from "lucide-react";+import { useEffect, useMemo, useRef, useState } from "react";+import { cn } from "@/react/lib/utils";+import type { Language } from "@/types";+import {+ createMonacoDiffEditor,+ loadMonacoEditor,+ setMonacoModelLanguage,+} from "./core";+import type {+ IStandaloneDiffEditor,+ IStandaloneDiffEditorConstructionOptions,+ MonacoModule,+} from "./types";++export interface DiffMonacoProps {+ autoHeightAlignment?: "original" | "modified";+ className?: string;+ language?: Language;+ max?: number;+ min?: number;+ modified?: string;+ onModifiedChange?: (modified: string) => void;+ onReady?: (monaco: MonacoModule, editor: IStandaloneDiffEditor) => void;+ options?: IStandaloneDiffEditorConstructionOptions;+ original?: string;+ readOnly?: boolean;+}++export function DiffMonaco({+ autoHeightAlignment = "modified",+ className = "",+ language = "sql",+ max = 600,+ min = 120,+ modified = "",+ onModifiedChange,+ onReady,+ options,+ original = "",+ readOnly = false,+}: DiffMonacoProps) {+ const containerRef = useRef<HTMLDivElement>(null);+ const editorRef = useRef<IStandaloneDiffEditor | null>(null);+ const [contentHeight, setContentHeight] = useState(min);+ const [ready, setReady] = useState(false);++ const normalizedOriginal = useMemo(+ () => original.replace(/\r\n?/g, "\n"),+ [original]+ );+ const normalizedModified = useMemo(+ () => modified.replace(/\r\n?/g, "\n"),+ [modified]+ );++ useEffect(() => {+ let disposed = false;+ let contentSizeSubscription: { dispose(): void } | null = null;+ (async () => {+ if (!containerRef.current) return;+ const editor = await createMonacoDiffEditor({+ container: containerRef.current,+ options: {+ readOnly,+ domReadOnly: readOnly,+ ...options,+ },+ });+ if (disposed) {+ editor.dispose();+ return;+ }+ editorRef.current = editor;+ const monaco = await loadMonacoEditor();+ const originalModel = monaco.editor.createModel(+ normalizedOriginal,+ language+ );+ const modifiedModel = monaco.editor.createModel(+ normalizedModified,+ language+ );+ editor.setModel({+ original: originalModel,+ modified: modifiedModel,+ });+ await setMonacoModelLanguage(originalModel, language);+ await setMonacoModelLanguage(modifiedModel, language);+ const alignedEditor =+ autoHeightAlignment === "original"+ ? editor.getOriginalEditor()+ : editor.getModifiedEditor();+ contentSizeSubscription = alignedEditor.onDidContentSizeChange(+ (event) => {+ if (!event.contentHeightChanged) return;+ setContentHeight(event.contentHeight);+ }+ );+ editor.onDidUpdateDiff(() => {+ onModifiedChange?.(editor.getModel()?.modified.getValue() ?? "");+ });+ setContentHeight(alignedEditor.getContentHeight());+ setReady(true);+ onReady?.(monaco, editor);+ })();++ return () => {+ disposed = true;+ setReady(false);+ contentSizeSubscription?.dispose();+ const model = editorRef.current?.getModel();+ model?.original?.dispose();+ model?.modified?.dispose();+ editorRef.current?.dispose();+ editorRef.current = null;+ };+ }, [+ autoHeightAlignment,+ language,+ normalizedModified,+ normalizedOriginal,+ onModifiedChange,+ onReady,+ options,+ readOnly,+ ]);++ useEffect(() => {+ const model = editorRef.current?.getModel();+ if (!model) return;+ if (model.original.getValue() !== normalizedOriginal) {+ model.original.setValue(normalizedOriginal);+ }+ if (model.modified.getValue() !== normalizedModified) {+ model.modified.setValue(normalizedModified);+ }+ }, [normalizedModified, normalizedOriginal]);++ useEffect(() => {+ const model = editorRef.current?.getModel();+ if (!model) return;+ void setMonacoModelLanguage(model.original, language);+ void setMonacoModelLanguage(model.modified, language);+ }, [language]);++ useEffect(() => {+ const editor = editorRef.current;+ if (!editor || !options) return;+ editor.updateOptions(options);+ }, [options]);++ const height = Math.min(max, Math.max(min, contentHeight));++ return (+ <div className={cn("relative", className)}>+ <div+ ref={containerRef}+ className="w-full overflow-clip rounded-md border text-sm"+ style={{ height }}+ />+ {!ready && (+ <div className="absolute inset-0 flex items-center justify-center rounded-md border bg-background/70">+ <Loader2 className="h-5 w-5 animate-spin text-control-light" />+ </div>+ )}+ </div>+ );+}diff --git a/frontend/src/react/components/monaco/MonacoEditor.tsx b/frontend/src/react/components/monaco/MonacoEditor.tsxnew file mode 100644index 0000000000..b2c06f4a1e--- /dev/null+++ b/frontend/src/react/components/monaco/MonacoEditor.tsx@@ -0,0 +1,642 @@+import { create } from "@bufbuild/protobuf";+import { debounce, orderBy } from "lodash-es";+import { Loader2 } from "lucide-react";+import {+ type MutableRefObject,+ type ReactNode,+ useEffect,+ useMemo,+ useRef,+ useState,+ useSyncExternalStore,+} from "react";+import { useTranslation } from "react-i18next";+import { cn } from "@/react/lib/utils";+import type { Language, SQLDialect } from "@/types";+import { UNKNOWN_ID } from "@/types";+import { PositionSchema } from "@/types/proto-es/v1/common_pb";+import {+ extractDatabaseResourceName,+ extractInstanceResourceName,+} from "@/utils";+import { batchConvertPositionToMonacoPosition } from "@/utils/v1/position";+import {+ createMonacoEditor,+ loadMonacoEditor,+ setMonacoModelLanguage,+} from "./core";+import {+ executeCommand,+ getConnectionStateSnapshot,+ getConnectionWebSocket,+ initializeLSPClient,+ subscribeConnectionState,+} from "./lsp-client";+import { ensureSuggestOverrideStyle } from "./suggest-icons";+import {+ getOrCreateTextModel,+ restoreViewState,+ storeViewState,+} from "./text-model";+import type {+ AdviceOption,+ AutoCompleteContext,+ FormatContentOptions,+ IStandaloneCodeEditor,+ IStandaloneEditorConstructionOptions,+ ITextModel,+ LineHighlightOption,+ MonacoModule,+ Selection,+} from "./types";+import {+ buildAdviceHoverMessage,+ extensionNameOfLanguage,+ formatEditorContent,+ trySetContentWithUndo,+} from "./utils";++export interface MonacoEditorProps {+ advices?: AdviceOption[];+ autoCompleteContext?: AutoCompleteContext;+ autoFocus?: boolean;+ className?: string;+ content: string;+ cornerPrefix?: ReactNode;+ cornerSuffix?: ReactNode;+ dialect?: SQLDialect;+ enableDecorations?: boolean;+ filename?: string;+ language?: Language;+ max?: number;+ min?: number;+ onActiveContentChange?: (value: string) => void;+ onChange?: (value: string) => void;+ onReady?: (monaco: MonacoModule, editor: IStandaloneCodeEditor) => void;+ onSelectContent?: (content: string) => void;+ onSelectionChange?: (selection: Selection | null) => void;+ options?: IStandaloneEditorConstructionOptions;+ placeholder?: string;+ readOnly?: boolean;+ lineHighlights?: LineHighlightOption[];+ formatContentOptions?: FormatContentOptions;+}++export function MonacoEditor({+ advices = [],+ autoCompleteContext,+ autoFocus = false,+ className = "",+ content,+ cornerPrefix,+ cornerSuffix,+ dialect,+ enableDecorations = false,+ filename,+ language = "sql",+ lineHighlights = [],+ max = 600,+ min = 120,+ onActiveContentChange,+ onChange,+ onReady,+ onSelectContent,+ onSelectionChange,+ options,+ placeholder,+ readOnly = false,+ formatContentOptions,+}: MonacoEditorProps) {+ const { t } = useTranslation();+ const containerRef = useRef<HTMLDivElement>(null);+ const editorRef = useRef<IStandaloneCodeEditor | null>(null);+ const modelRef = useRef<ITextModel | null>(null);+ const activeDecorationRef = useRef<{ clear(): void } | null>(null);+ const contentRef = useRef(content);+ const languageRef = useRef(language);+ const readOnlyRef = useRef(readOnly);+ const optionsRef = useRef(options);+ const onChangeRef = useRef(onChange);+ const onSelectContentRef = useRef(onSelectContent);+ const onSelectionChangeRef = useRef(onSelectionChange);+ const onActiveContentChangeRef = useRef(onActiveContentChange);+ const onReadyRef = useRef(onReady);+ const isApplyingExternalChangeRef = useRef(false);+ const activeRangeByUriRef = useRef<Map<string, MonacoTypeRange[]>>(new Map());+ const selectionRef = useRef<Selection | null>(null);+ const generatedFilename = useMemo(() => {+ if (filename) {+ return filename;+ }+ const id =+ typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"+ ? crypto.randomUUID()+ : Math.random().toString(36).slice(2);+ return `${id}.${extensionNameOfLanguage(language)}`;+ }, [filename, language]);+ const [contentHeight, setContentHeight] = useState(min);+ const [ready, setReady] = useState(false);++ contentRef.current = content;+ languageRef.current = language;+ readOnlyRef.current = readOnly;+ optionsRef.current = options;+ onChangeRef.current = onChange;+ onSelectContentRef.current = onSelectContent;+ onSelectionChangeRef.current = onSelectionChange;+ onActiveContentChangeRef.current = onActiveContentChange;+ onReadyRef.current = onReady;++ const connection = useSyncExternalStore(+ subscribeConnectionState,+ getConnectionStateSnapshot,+ getConnectionStateSnapshot+ );++ const clampMeasuredHeight = (height: number): number => {+ return Math.min(max, Math.max(min, height));+ };++ const emitSelectionSideEffects = () => {+ const editor = editorRef.current;+ const model = modelRef.current ?? editor?.getModel();+ if (!editor || !model) return;++ const selection = editor.getSelection();+ selectionRef.current = selection;+ onSelectionChangeRef.current?.(selection);++ const selectedContent =+ selection && !selection.isEmpty() ? model.getValueInRange(selection) : "";+ onSelectContentRef.current?.(selectedContent);++ const cursorPosition = editor.getPosition();+ const ranges = activeRangeByUriRef.current.get(model.uri.toString()) ?? [];+ const activeRange =+ selection && !selection.isEmpty()+ ? selection+ : resolveActiveRangeByCursor(ranges, cursorPosition);++ activeDecorationRef.current?.clear();+ activeDecorationRef.current = null;+ if (+ enableDecorations &&+ activeRange &&+ (!selection || selection.isEmpty())+ ) {+ activeDecorationRef.current = editor.createDecorationsCollection([+ {+ range: activeRange,+ options: {+ isWholeLine: false,+ shouldFillLineOnLineBreak: true,+ className: "bg-gray-200",+ },+ },+ ]);+ }++ onActiveContentChangeRef.current?.(+ activeRange ? model.getValueInRange(activeRange) : ""+ );+ };++ useEffect(() => {+ let disposed = false;+ let contentSizeSubscription: { dispose(): void } | null = null;+ let contentSubscription: { dispose(): void } | null = null;+ let selectionSubscription: { dispose(): void } | null = null;+ let modelSubscription: { dispose(): void } | null = null;+ let cursorSubscription: { dispose(): void } | null = null;+ let formatAction: { dispose(): void } | null = null;+ let suggestStyle: HTMLStyleElement | null = null;+ let messageHandler: ((event: MessageEvent) => void) | null = null;++ (async () => {+ if (!containerRef.current) return;++ const shouldEnableLSP =+ !readOnlyRef.current &&+ (Boolean(autoCompleteContext) ||+ enableDecorations ||+ Boolean(onActiveContentChangeRef.current));+ if (shouldEnableLSP) {+ void initializeLSPClient().catch(() => undefined);+ }++ const editor = await createMonacoEditor({+ container: containerRef.current,+ options: {+ ...optionsRef.current,+ language: languageRef.current,+ value: contentRef.current,+ readOnly: readOnlyRef.current,+ domReadOnly: readOnlyRef.current,+ },+ });++ if (disposed) {+ editor.dispose();+ return;+ }++ editorRef.current = editor;+ const monaco = await loadMonacoEditor();+ const model = await getOrCreateTextModel(+ generatedFilename,+ contentRef.current,+ languageRef.current+ );+ if (disposed) {+ editor.dispose();+ return;+ }+ modelRef.current = model;+ editor.setModel(model);+ restoreViewState(editor, model);+ await setMonacoModelLanguage(model, languageRef.current);++ contentSizeSubscription = editor.onDidContentSizeChange((event) => {+ if (!event.contentHeightChanged) return;+ setContentHeight(event.contentHeight);+ });++ contentSubscription = editor.onDidChangeModelContent(() => {+ if (isApplyingExternalChangeRef.current) {+ return;+ }+ onChangeRef.current?.(editor.getValue());+ emitSelectionSideEffects();+ });++ selectionSubscription = editor.onDidChangeCursorSelection(() => {+ emitSelectionSideEffects();+ });+ modelSubscription = editor.onDidChangeModel(() => {+ modelRef.current = editor.getModel();+ emitSelectionSideEffects();+ });+ cursorSubscription = editor.onDidChangeCursorPosition(() => {+ emitSelectionSideEffects();+ });++ if (editor.getValue() !== contentRef.current) {+ isApplyingExternalChangeRef.current = true;+ editor.setValue(contentRef.current);+ isApplyingExternalChangeRef.current = false;+ }++ setContentHeight(editor.getContentHeight());+ setReady(true);+ onReadyRef.current?.(monaco, editor);+ emitSelectionSideEffects();++ if (!readOnlyRef.current) {+ formatAction = attachFormatAction(+ monaco,+ editor,+ () => dialect,+ () => formatContentOptions ?? { disabled: false },+ t("sql-editor.format-sql")+ );+ suggestStyle = ensureSuggestOverrideStyle();+ }++ if (shouldEnableLSP) {+ const wsPromise = getConnectionWebSocket();+ wsPromise?.then((ws) => {+ if (disposed) return;+ messageHandler = (message: MessageEvent) => {+ processStatementRangeMessage(message, activeRangeByUriRef);+ emitSelectionSideEffects();+ };+ ws.addEventListener("message", messageHandler);+ });+ }++ if (autoFocus) {+ editor.focus();+ }+ })();++ return () => {+ disposed = true;+ setReady(false);+ contentSubscription?.dispose();+ contentSizeSubscription?.dispose();+ selectionSubscription?.dispose();+ modelSubscription?.dispose();+ cursorSubscription?.dispose();+ formatAction?.dispose();+ suggestStyle?.remove();+ const wsPromise = getConnectionWebSocket();+ if (messageHandler) {+ wsPromise?.then((ws) =>+ ws.removeEventListener("message", messageHandler!)+ );+ }+ activeDecorationRef.current?.clear();+ activeDecorationRef.current = null;+ if (editorRef.current) {+ storeViewState(editorRef.current, modelRef.current);+ }+ editorRef.current?.dispose();+ editorRef.current = null;+ modelRef.current = null;+ };+ }, [+ autoCompleteContext,+ autoFocus,+ dialect,+ enableDecorations,+ formatContentOptions,+ generatedFilename,+ ]);++ useEffect(() => {+ const editor = editorRef.current;+ const model = modelRef.current ?? editor?.getModel();+ if (!editor || !model) return;+ if (model.getValue() !== contentRef.current) {+ isApplyingExternalChangeRef.current = true;+ trySetContentWithUndo(editor, contentRef.current, "sync-content");+ isApplyingExternalChangeRef.current = false;+ }+ setContentHeight(editor.getContentHeight());+ }, [content]);++ useEffect(() => {+ const model = modelRef.current ?? editorRef.current?.getModel();+ if (!model) return;++ void setMonacoModelLanguage(model, languageRef.current);+ }, [generatedFilename, language]);++ useEffect(() => {+ const editor = editorRef.current;+ if (!editor) return;+ editor.updateOptions({+ domReadOnly: readOnlyRef.current,+ readOnly: readOnlyRef.current,+ });+ }, [readOnly]);++ useEffect(() => {+ const editor = editorRef.current;+ if (!editor || !options) return;+ editor.updateOptions(options);+ }, [options]);++ useEffect(() => {+ const editor = editorRef.current;+ const model = modelRef.current ?? editor?.getModel();+ if (!editor || !model) return;+ const decorations = editor.createDecorationsCollection(+ buildAdviceDecorations(advices, model.getValue())+ );+ return () => {+ decorations.clear();+ };+ }, [advices]);++ useEffect(() => {+ const editor = editorRef.current;+ if (!editor) return;+ const monacoPromise = loadMonacoEditor();+ let decorations: { clear(): void } | undefined;+ void monacoPromise.then((monaco) => {+ decorations = editor.createDecorationsCollection(+ lineHighlights.map((opt) => ({+ range: new monaco.Range(+ opt.startLineNumber,+ 1,+ opt.endLineNumber,+ Infinity+ ),+ options: {+ ...opt.options,+ blockPadding: [3, 3, 3, 3],+ stickiness:+ monaco.editor.TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges,+ },+ }))+ );+ });+ return () => {+ decorations?.clear();+ };+ }, [lineHighlights]);++ useEffect(() => {+ if (readOnly || !autoCompleteContext) return;+ const ctx = autoCompleteContext;+ const params = {+ instanceId: "",+ databaseName: "",+ scene: ctx.scene,+ schema: ctx.schema,+ };+ const instance = extractInstanceResourceName(ctx.instance);+ if (instance && instance !== String(UNKNOWN_ID)) {+ params.instanceId = ctx.instance;+ }+ const { databaseName } = extractDatabaseResourceName(ctx.database ?? "");+ if (databaseName && databaseName !== String(UNKNOWN_ID)) {+ params.databaseName = databaseName;+ }+ const apply = debounce(async () => {+ const client = await initializeLSPClient();+ await executeCommand(client, "setMetadata", [params]);+ }, 500);+ void apply();+ return () => {+ apply.cancel();+ };+ }, [autoCompleteContext, readOnly]);++ const height = clampMeasuredHeight(contentHeight);++ return (+ <div className={cn("relative", className)}>+ <div+ ref={containerRef}+ className={cn("w-full overflow-clip rounded-md border text-sm")}+ style={{ height }}+ />+ {!ready && (+ <div className="absolute inset-0 flex items-center justify-center rounded-md border bg-background/70">+ <Loader2 className="h-5 w-5 animate-spin text-control-light" />+ </div>+ )}+ {ready && !content && placeholder && (+ <div className="pointer-events-none absolute left-[52px] top-2 font-mono text-sm text-control-placeholder">+ {placeholder}+ </div>+ )}+ <div className="absolute right-[18px] top-[3px] z-30 flex items-center justify-end gap-1">+ {cornerPrefix}+ {ready && !readOnly && (+ <div className="flex h-4 w-4 cursor-default items-center justify-center opacity-60">+ <div+ className={cn(+ "h-3 w-3 rounded-full",+ connection.state === "ready"+ ? "bg-success"+ : connection.state === "initial" ||+ connection.state === "reconnecting"+ ? "bg-warning"+ : "bg-control-placeholder"+ )}+ />+ </div>+ )}+ {cornerSuffix}+ </div>+ </div>+ );+}++export default MonacoEditor;++type MonacoTypeRange = {+ startLineNumber: number;+ endLineNumber: number;+ startColumn: number;+ endColumn: number;+};++const resolveActiveRangeByCursor = (+ ranges: MonacoTypeRange[],+ position:+ | {+ lineNumber: number;+ column: number;+ }+ | null+ | undefined+) => {+ if (!position) return undefined;+ for (const range of ranges) {+ if (range.endLineNumber < position.lineNumber) continue;+ if (+ range.startLineNumber <= position.lineNumber &&+ range.endLineNumber >= position.lineNumber+ ) {+ if (range.endColumn >= position.column) {+ return range;+ }+ }+ if (range.startLineNumber > position.lineNumber) break;+ }+ return undefined;+};++const buildAdviceDecorations = (advices: AdviceOption[], content: string) => {+ const protoStarts = advices.map((advice) =>+ create(PositionSchema, {+ line: advice.startLineNumber,+ column: advice.startColumn,+ })+ );+ const protoEnds = advices.map((advice) =>+ create(PositionSchema, {+ line: advice.endLineNumber,+ column: advice.endColumn,+ })+ );+ const starts = batchConvertPositionToMonacoPosition(protoStarts, content);+ const ends = batchConvertPositionToMonacoPosition(protoEnds, content);+ return advices.map((advice, index) => ({+ range: {+ startLineNumber: starts[index].lineNumber,+ startColumn: starts[index].column,+ endLineNumber: ends[index].lineNumber,+ endColumn: ends[index].column,+ },+ options: {+ className:+ advice.severity === "ERROR" ? "squiggly-error" : "squiggly-warning",+ showIfCollapsed: true,+ hoverMessage: {+ value: buildAdviceHoverMessage(advice),+ isTrusted: true,+ },+ },+ }));+};++const attachFormatAction = (+ monaco: MonacoModule,+ editor: IStandaloneCodeEditor,+ getDialect: () => SQLDialect | undefined,+ getOptions: () => FormatContentOptions | undefined,+ label: string+) => {+ if (editor.getModel()?.getLanguageId() !== "sql") {+ return null;+ }+ const opts = {+ disabled: false,+ ...getOptions(),+ };+ if (opts.disabled) {+ return null;+ }+ return editor.addAction({+ id: "format-sql",+ label,+ keybindings: [+ monaco.KeyMod.Alt | monaco.KeyMod.Shift | monaco.KeyCode.KeyF,+ ],+ contextMenuGroupId: "operation",+ contextMenuOrder: 1,+ run: async () => {+ if (opts.callback) {+ opts.callback(monaco, editor);+ return;+ }+ const readonly = editor.getOption(monaco.editor.EditorOption.readOnly);+ if (readonly) return;+ await formatEditorContent(editor, getDialect());+ },+ });+};++const processStatementRangeMessage = (+ message: MessageEvent,+ ref: MutableRefObject<Map<string, MonacoTypeRange[]>>+) => {+ if (typeof message.data !== "string") return;+ if (!message.data.includes("$/textDocument/statementRanges")) return;+ try {+ const payload = JSON.parse(message.data) as {+ method?: string;+ params?: {+ uri?: string;+ ranges?: {+ start: { line: number; character: number };+ end: { line: number; character: number };+ }[];+ };+ };+ if (+ payload.method !== "$/textDocument/statementRanges" ||+ !payload.params?.uri ||+ !Array.isArray(payload.params.ranges)+ ) {+ return;+ }+ const ranges = orderBy(+ payload.params.ranges,+ (range) => range.start.line+ ).map((range) => ({+ startLineNumber: range.start.line + 1,+ endLineNumber: range.end.line + 1,+ startColumn: range.start.character + 1,+ endColumn: range.end.character + 1,+ }));+ ref.current.set(payload.params.uri, ranges);+ } catch {+ // ignore+ }+};diff --git a/frontend/src/react/components/monaco/ReadonlyDiffMonaco.tsx b/frontend/src/react/components/monaco/ReadonlyDiffMonaco.tsxindex da98c13b30..2e46e664be 100644--- a/frontend/src/react/components/monaco/ReadonlyDiffMonaco.tsx+++ b/frontend/src/react/components/monaco/ReadonlyDiffMonaco.tsx@@ -1,12 +1,5 @@-import { useEffect, useMemo, useRef, useState } from "react";-import {- createMonacoDiffEditor,- setMonacoModelLanguage,-} from "@/components/MonacoEditor/editor";-import { loadMonacoEditor } from "@/components/MonacoEditor/lazy-editor";-import type { IStandaloneDiffEditor } from "@/components/MonacoEditor/types";-import { cn } from "@/react/lib/utils";import type { Language } from "@/types";+import { DiffMonaco } from "./DiffMonaco";export interface ReadonlyDiffMonacoProps {original: string;@@ -25,133 +18,15 @@ export function ReadonlyDiffMonaco({min = 120,max = 600,}: ReadonlyDiffMonacoProps) {- const containerRef = useRef<HTMLDivElement>(null);- const editorRef = useRef<IStandaloneDiffEditor | null>(null);- const originalRef = useRef(original);- const modifiedRef = useRef(modified);- const languageRef = useRef(language);- const [contentHeight, setContentHeight] = useState(min);- const clampMeasuredHeight = (height: number): number => {- return Math.min(max, Math.max(min, height));- };-- originalRef.current = original;- modifiedRef.current = modified;- languageRef.current = language;-- const normalizedOriginal = useMemo(- () => original.replace(/\r\n?/g, "\n"),- [original]- );- const normalizedModified = useMemo(- () => modified.replace(/\r\n?/g, "\n"),- [modified]- );-- useEffect(() => {- let disposed = false;- let contentSizeSubscription: { dispose(): void } | null = null;-- (async () => {- if (!containerRef.current) return;-- const editor = await createMonacoDiffEditor({- container: containerRef.current,- options: {- readOnly: true,- domReadOnly: true,- renderSideBySide: true,- ignoreTrimWhitespace: true,- },- });-- if (disposed) {- editor.dispose();- return;- }-- editorRef.current = editor;-- // Handle height auto-grow by listening to the modified editor's size change.- const modifiedEditor = editor.getModifiedEditor();- contentSizeSubscription = modifiedEditor.onDidContentSizeChange(- (event) => {- if (!event.contentHeightChanged) return;- setContentHeight(event.contentHeight);- }- );-- const monaco = await loadMonacoEditor();-- if (disposed) {- return;- }-- const originalModel = monaco.editor.createModel(- originalRef.current.replace(/\r\n?/g, "\n"),- languageRef.current- );- const modifiedModel = monaco.editor.createModel(- modifiedRef.current.replace(/\r\n?/g, "\n"),- languageRef.current- );-- editor.setModel({- original: originalModel,- modified: modifiedModel,- });-- setContentHeight(modifiedEditor.getContentHeight());- })();-- return () => {- disposed = true;- contentSizeSubscription?.dispose();- const model = editorRef.current?.getModel();- model?.original?.dispose();- model?.modified?.dispose();- editorRef.current?.dispose();- editorRef.current = null;- };- }, []);-- useEffect(() => {- const editor = editorRef.current;- if (!editor) return;- const model = editor.getModel();- if (model) {- if (model.original.getValue() !== normalizedOriginal) {- model.original.setValue(normalizedOriginal);- }- if (model.modified.getValue() !== normalizedModified) {- model.modified.setValue(normalizedModified);- }- }- const modifiedEditor = editor.getModifiedEditor();- setContentHeight(modifiedEditor.getContentHeight());- }, [normalizedOriginal, normalizedModified]);-- useEffect(() => {- const editor = editorRef.current;- const model = editor?.getModel();- if (!model) return;-- (async () => {- await setMonacoModelLanguage(model.original, languageRef.current);- await setMonacoModelLanguage(model.modified, languageRef.current);- })();- }, [language]);-- const height = clampMeasuredHeight(contentHeight);-return (- <div- ref={containerRef}- className={cn(- "w-full overflow-clip rounded-md border text-sm",- className- )}- style={{ height }}+ <DiffMonaco+ className={className}+ language={language}+ max={max}+ min={min}+ modified={modified}+ original={original}+ readOnly/>);}diff --git a/frontend/src/react/components/monaco/ReadonlyMonaco.test.tsx b/frontend/src/react/components/monaco/ReadonlyMonaco.test.tsxindex dec862fcb6..2d371264dd 100644--- a/frontend/src/react/components/monaco/ReadonlyMonaco.test.tsx+++ b/frontend/src/react/components/monaco/ReadonlyMonaco.test.tsx@@ -8,63 +8,21 @@ import { ReadonlyMonaco } from "./ReadonlyMonaco";).IS_REACT_ACT_ENVIRONMENT = true;const mocks = vi.hoisted(() => {- const createMonacoEditor = vi.fn();- const setMonacoModelLanguage = vi.fn();+ const MonacoEditor = vi.fn((props: Record<string, unknown>) =>+ createElement("div", {+ "data-testid": "monaco-editor",+ "data-props": JSON.stringify(props),+ })+ );return {- createMonacoEditor,- setMonacoModelLanguage,+ MonacoEditor,};});-vi.mock("@/components/MonacoEditor/editor", () => ({- createMonacoEditor: mocks.createMonacoEditor,- setMonacoModelLanguage: mocks.setMonacoModelLanguage,+vi.mock("./MonacoEditor", () => ({+ MonacoEditor: mocks.MonacoEditor,}));-const createDeferred = <T,>() => {- let resolve!: (value: T) => void;- const promise = new Promise<T>((res) => {- resolve = res;- });- return { promise, resolve };-};--const flushAsync = () =>- new Promise<void>((resolve) => {- setTimeout(resolve, 0);- });--const createEditor = () => {- let contentHeight = 240;- let contentSizeHandler:- | ((event: {- contentHeight: number;- contentHeightChanged: boolean;- }) => void)- | undefined;- const model = {};-- return {- model,- setValue: vi.fn(),- getValue: vi.fn(() => "first line"),- getModel: vi.fn(() => model),- getContentHeight: vi.fn(() => contentHeight),- onDidContentSizeChange: vi.fn((handler) => {- contentSizeHandler = handler;- return { dispose: vi.fn() };- }),- emitContentHeight(nextHeight: number) {- contentHeight = nextHeight;- contentSizeHandler?.({- contentHeight: nextHeight,- contentHeightChanged: true,- });- },- dispose: vi.fn(),- };-};-const renderIntoContainer = (element: ReturnType<typeof createElement>) => {const container = document.createElement("div");const root = createRoot(container);@@ -75,7 +33,6 @@ const renderIntoContainer = (element: ReturnType<typeof createElement>) => {return {container,- root,rerender: (nextElement: ReturnType<typeof createElement>) => {act(() => {root.render(nextElement);@@ -89,73 +46,97 @@ const renderIntoContainer = (element: ReturnType<typeof createElement>) => {};beforeEach(() => {- mocks.createMonacoEditor.mockReset();- mocks.setMonacoModelLanguage.mockReset();+ mocks.MonacoEditor.mockClear();});describe("ReadonlyMonaco", () => {- test("reconciles the latest props after delayed editor creation", async () => {- const deferred = createDeferred<Awaited<ReturnType<typeof createEditor>>>();- mocks.createMonacoEditor.mockReturnValue(deferred.promise);- const editor = createEditor();-- const { unmount, rerender } = renderIntoContainer(- createElement(ReadonlyMonaco, {- content: "initial",- language: "sql",- })- );-- rerender(+ test("forwards readonly editor props", () => {+ const { container, unmount } = renderIntoContainer(createElement(ReadonlyMonaco, {- content: "updated",+ advices: [+ {+ severity: "WARNING",+ message: "Advice",+ startLineNumber: 1,+ startColumn: 1,+ endLineNumber: 1,+ endColumn: 8,+ },+ ],+ className: "editor-shell",+ content: "select 1",+ filename: "test.sql",language: "json",+ lineHighlights: [+ {+ startLineNumber: 1,+ endLineNumber: 1,+ options: {+ isWholeLine: true,+ },+ },+ ],+ max: 480,+ min: 180,+ options: { wordWrap: "off" },}));- await act(async () => {- deferred.resolve(editor);- await deferred.promise;- await flushAsync();- });-- expect(editor.setValue).toHaveBeenCalledWith("updated");- expect(mocks.setMonacoModelLanguage).toHaveBeenCalledWith(- editor.model,- "json"+ const props = JSON.parse(+ container.firstElementChild?.getAttribute("data-props") ?? "{}");+ expect(props).toMatchObject({+ className: "editor-shell",+ content: "select 1",+ filename: "test.sql",+ language: "json",+ max: 480,+ min: 180,+ readOnly: true,+ });+ expect(props.advices).toEqual([+ {+ severity: "WARNING",+ message: "Advice",+ startLineNumber: 1,+ startColumn: 1,+ endLineNumber: 1,+ endColumn: 8,+ },+ ]);+ expect(props.lineHighlights).toEqual([+ {+ startLineNumber: 1,+ endLineNumber: 1,+ options: { isWholeLine: true },+ },+ ]);+ expect(props.options).toEqual({ wordWrap: "off" });unmount();});- test("sizes from Monaco content height changes", async () => {- const deferred = createDeferred<ReturnType<typeof createEditor>>();- mocks.createMonacoEditor.mockReturnValue(deferred.promise);- const editor = createEditor();-- const { container, unmount } = renderIntoContainer(+ test("updates forwarded props on rerender", () => {+ const { container, rerender, unmount } = renderIntoContainer(createElement(ReadonlyMonaco, {- content: "a very long single line that wraps in Monaco",+ content: "before",+ language: "sql",}));- await act(async () => {- deferred.resolve(editor);- await deferred.promise;- await flushAsync();- });-- expect(- (container.firstElementChild as HTMLElement | null)?.style.height- ).toBe("240px");-- act(() => {- editor.emitContentHeight(480);- });+ rerender(+ createElement(ReadonlyMonaco, {+ content: "after",+ language: "json",+ })+ );- expect(- (container.firstElementChild as HTMLElement | null)?.style.height- ).toBe("480px");+ const props = JSON.parse(+ container.firstElementChild?.getAttribute("data-props") ?? "{}"+ );+ expect(props.content).toBe("after");+ expect(props.language).toBe("json");+ expect(props.readOnly).toBe(true);unmount();});diff --git a/frontend/src/react/components/monaco/ReadonlyMonaco.tsx b/frontend/src/react/components/monaco/ReadonlyMonaco.tsxindex e9f04e6287..6dde1f1a2f 100644--- a/frontend/src/react/components/monaco/ReadonlyMonaco.tsx+++ b/frontend/src/react/components/monaco/ReadonlyMonaco.tsx@@ -1,128 +1,46 @@-import { useEffect, useRef, useState } from "react";-import {- createMonacoEditor,- setMonacoModelLanguage,-} from "@/components/MonacoEditor/editor";-import type { IStandaloneCodeEditor } from "@/components/MonacoEditor/types";-import { cn } from "@/react/lib/utils";import type { Language } from "@/types";+import { MonacoEditor } from "./MonacoEditor";+import type {+ AdviceOption,+ IStandaloneEditorConstructionOptions,+ LineHighlightOption,+} from "./types";export interface ReadonlyMonacoProps {+ advices?: AdviceOption[];content: string;- language?: Language;className?: string;- min?: number;+ filename?: string;+ language?: Language;+ lineHighlights?: LineHighlightOption[];max?: number;+ min?: number;+ options?: IStandaloneEditorConstructionOptions;}export function ReadonlyMonaco({+ advices = [],content,- language = "sql",className = "",- min = 120,+ filename,+ language = "sql",+ lineHighlights = [],max = 600,+ min = 120,+ options,}: ReadonlyMonacoProps) {- const containerRef = useRef<HTMLDivElement>(null);- const editorRef = useRef<IStandaloneCodeEditor | null>(null);- const contentRef = useRef(content);- const languageRef = useRef(language);- const [contentHeight, setContentHeight] = useState(min);- const clampMeasuredHeight = (height: number): number => {- return Math.min(max, Math.max(min, height));- };-- contentRef.current = content;- languageRef.current = language;-- useEffect(() => {- let disposed = false;- let contentSizeSubscription: { dispose(): void } | null = null;-- (async () => {- if (!containerRef.current) return;-- const editor = await createMonacoEditor({- container: containerRef.current,- options: {- language: languageRef.current,- value: contentRef.current,- readOnly: true,- domReadOnly: true,- },- });-- if (disposed) {- editor.dispose();- return;- }-- editorRef.current = editor;-- contentSizeSubscription = editor.onDidContentSizeChange((event) => {- if (!event.contentHeightChanged) return;- setContentHeight(event.contentHeight);- });-- if (editor.getValue() !== contentRef.current) {- editor.setValue(contentRef.current);- }-- setContentHeight(editor.getContentHeight());-- const model = editor.getModel();- if (model) {- await setMonacoModelLanguage(model, languageRef.current);- if (disposed) {- contentSizeSubscription?.dispose();- editor.dispose();- return;- }- }-- if (disposed) {- contentSizeSubscription?.dispose();- editor.dispose();- return;- }- })();-- return () => {- disposed = true;- contentSizeSubscription?.dispose();- editorRef.current?.dispose();- editorRef.current = null;- };- }, []);-- useEffect(() => {- const editor = editorRef.current;- if (!editor) return;- if (editor.getValue() !== contentRef.current) {- editor.setValue(contentRef.current);- }- setContentHeight(editor.getContentHeight());- }, [content]);-- useEffect(() => {- const editor = editorRef.current;- const model = editor?.getModel();- if (!model) return;-- (async () => {- await setMonacoModelLanguage(model, languageRef.current);- })();- }, [language]);-- const height = clampMeasuredHeight(contentHeight);-return (- <div- ref={containerRef}- className={cn(- "w-full overflow-clip rounded-md border text-sm",- className- )}- style={{ height }}+ <MonacoEditor+ advices={advices}+ className={className}+ content={content}+ filename={filename}+ language={language}+ lineHighlights={lineHighlights}+ max={max}+ min={min}+ options={options}+ readOnly/>);}diff --git a/frontend/src/react/components/monaco/core.ts b/frontend/src/react/components/monaco/core.tsnew file mode 100644index 0000000000..bf6d7c2ddf--- /dev/null+++ b/frontend/src/react/components/monaco/core.ts@@ -0,0 +1,174 @@+import type * as MonacoType from "monaco-editor";+import type { Language } from "@/types";+import { defer } from "@/utils";+import { initializeMonacoServices } from "./services";+import { getBBTheme } from "./themes/bb";+import { getBBDarkTheme } from "./themes/bb-dark";++let monacoModule: typeof MonacoType | undefined;+const monacoLoadDefer = defer<typeof MonacoType>();+const monacoEditorReadyDefer = defer<void>();++export const MonacoEditorReady = monacoEditorReadyDefer.promise;++const state = {+ themeInitialized: false,+};++const initializeTheme = () => {+ if (state.themeInitialized) return;+ state.themeInitialized = true;+ if (!monacoModule) return;+ monacoModule.editor.defineTheme("bb", getBBTheme());+ monacoModule.editor.defineTheme("bb-dark", getBBDarkTheme());+};++const initialize = async () => {+ await initializeMonacoServices();+ await loadMonacoEditor();+ initializeTheme();+};++export const loadMonacoEditor = async (): Promise<typeof MonacoType> => {+ if (monacoModule) {+ return monacoModule;+ }++ monacoModule = await import("monaco-editor");+ monacoLoadDefer.resolve(monacoModule);+ return monacoModule;+};++export const getMonacoEditor = async (): Promise<typeof MonacoType> => {+ return monacoLoadDefer.promise;+};++export const isMonacoLoaded = (): boolean => {+ return monacoModule !== undefined;+};++export const createMonacoEditor = async (config: {+ container: HTMLElement;+ options?: MonacoType.editor.IStandaloneEditorConstructionOptions;+}): Promise<MonacoType.editor.IStandaloneCodeEditor> => {+ await initialize();+ const monaco = await loadMonacoEditor();+ const baseOptions = {+ experimentalEditContextEnabled: false,+ } as const;++ const editor = monaco.editor.create(config.container, {+ ...(baseOptions as MonacoType.editor.IStandaloneEditorConstructionOptions),+ ...defaultEditorOptions(),+ ...config.options,+ });++ editor.getContribution("editor.contrib.readOnlyMessageController")?.dispose();+ monacoEditorReadyDefer.resolve();+ return editor;+};++export const createMonacoDiffEditor = async (config: {+ container: HTMLElement;+ options?: MonacoType.editor.IStandaloneDiffEditorConstructionOptions;+}): Promise<MonacoType.editor.IStandaloneDiffEditor> => {+ await initialize();+ const monaco = await loadMonacoEditor();+ const baseOptions = {+ experimentalEditContextEnabled: false,+ } as const;++ const editor = monaco.editor.createDiffEditor(config.container, {+ ...(baseOptions as MonacoType.editor.IStandaloneDiffEditorConstructionOptions),+ ...defaultDiffEditorOptions(),+ ...config.options,+ });++ editor+ .getModifiedEditor()+ .getContribution("editor.contrib.readOnlyMessageController")+ ?.dispose();+ monacoEditorReadyDefer.resolve();+ return editor;+};++export const setMonacoModelLanguage = async (+ model: MonacoType.editor.ITextModel,+ language: Language+): Promise<void> => {+ const monaco = await loadMonacoEditor();+ monaco.editor.setModelLanguage(model, language);+};++export const defaultEditorOptions =+ (): MonacoType.editor.IStandaloneEditorConstructionOptions => {+ return {+ renderValidationDecorations: "on",+ accessibilitySupport: "off",+ theme: "bb",+ tabSize: 2,+ insertSpaces: true,+ autoClosingQuotes: "never",+ detectIndentation: false,+ folding: false,+ automaticLayout: true,+ minimap: {+ enabled: false,+ },+ wordWrap: "on",+ fixedOverflowWidgets: true,+ fontSize: 14,+ lineHeight: 24,+ scrollBeyondLastLine: false,+ suggestFontSize: 12,+ padding: {+ top: 8,+ bottom: 8,+ },+ renderLineHighlight: "none",+ codeLens: false,+ scrollbar: {+ alwaysConsumeMouseWheel: false,+ },+ inlineSuggest: {+ showToolbar: "never",+ },+ wordBasedSuggestions: "currentDocument",+ lineNumbers: "on",+ cursorStyle: "line",+ glyphMargin: false,+ };+ };++export const defaultDiffEditorOptions =+ (): MonacoType.editor.IStandaloneDiffEditorConstructionOptions => {+ return {+ enableSplitViewResizing: false,+ accessibilitySupport: "off",+ renderValidationDecorations: "on",+ theme: "bb",+ autoClosingQuotes: "never",+ folding: false,+ automaticLayout: true,+ minimap: {+ enabled: false,+ },+ wordWrap: "off",+ fixedOverflowWidgets: true,+ fontSize: 14,+ lineHeight: 24,+ scrollBeyondLastLine: false,+ padding: {+ top: 8,+ bottom: 8,+ },+ renderLineHighlight: "none",+ codeLens: false,+ scrollbar: {+ alwaysConsumeMouseWheel: false,+ },+ inlineSuggest: {+ showToolbar: "never",+ },+ };+ };diff --git a/frontend/src/react/components/monaco/index.ts b/frontend/src/react/components/monaco/index.tsindex b12ae602e0..36dc5b4e1f 100644--- a/frontend/src/react/components/monaco/index.ts+++ b/frontend/src/react/components/monaco/index.ts@@ -1,2 +1,7 @@+export * from "./core";+export * from "./DiffMonaco";+export * from "./MonacoEditor";export * from "./ReadonlyMonaco";export * from "./ReadonlyDiffMonaco";+export * from "./types";+export * from "./utils";diff --git a/frontend/src/react/components/monaco/lsp-client.ts b/frontend/src/react/components/monaco/lsp-client.tsnew file mode 100644index 0000000000..5f42f93789--- /dev/null+++ b/frontend/src/react/components/monaco/lsp-client.ts@@ -0,0 +1,303 @@+import { omit, throttle } from "lodash-es";+import { MonacoLanguageClient } from "monaco-languageclient";+import type { ExecuteCommandParams } from "vscode-languageclient";+import { CloseAction, ErrorAction, State } from "vscode-languageclient";+import {+ toSocket,+ WebSocketMessageReader,+ WebSocketMessageWriter,+} from "vscode-ws-jsonrpc";+import { refreshTokens } from "@/connect/refreshToken";+import { sleep } from "@/utils";+import {+ createUrl,+ errorNotification,+ MAX_RETRIES,+ messages,+ progressiveDelay,+ WEBSOCKET_HEARTBEAT_INTERVAL,+ WEBSOCKET_TIMEOUT,+} from "./utils";++export type ConnectionState = {+ heartbeat: {+ counter: number;+ timer: ReturnType<typeof setTimeout> | undefined;+ timestamp: number;+ };+ lastCommand: ExecuteCommandParams | undefined;+ retries: number;+ state: "initial" | "ready" | "closed" | "reconnecting";+ url: string;+ ws: Promise<WebSocket> | undefined;+};++const listeners = new Set<() => void>();++const emit = () => {+ listeners.forEach((listener) => listener());+};++const lspHost = (() => {+ const grpcLocal = import.meta.env.BB_GRPC_LOCAL;+ if (grpcLocal) {+ try {+ return new URL(grpcLocal).host;+ } catch {+ // ignore+ }+ }+ return location.host;+})();++const conn: ConnectionState = {+ url: createUrl(lspHost, "/lsp").toString(),+ state: "initial",+ ws: undefined,+ lastCommand: undefined,+ retries: 0,+ heartbeat: {+ timer: undefined,+ counter: 0,+ timestamp: 0,+ },+};++const state = {+ client: undefined as MonacoLanguageClient | undefined,+ clientInitialized: undefined as Promise<MonacoLanguageClient> | undefined,+};++const setConnState = (patch: Partial<ConnectionState>) => {+ Object.assign(conn, patch);+ emit();+};++const setHeartbeat = (patch: Partial<ConnectionState["heartbeat"]>) => {+ Object.assign(conn.heartbeat, patch);+ emit();+};++const useHeartbeat = (ws: WebSocket) => {+ const cleanup = () => {+ clearTimeout(conn.heartbeat.timer);+ conn.heartbeat = {+ timer: undefined,+ counter: 0,+ timestamp: 0,+ };+ emit();+ };++ ws.addEventListener("error", cleanup);+ ws.addEventListener("close", cleanup);++ const ping = () => {+ setHeartbeat({+ counter: conn.heartbeat.counter + 1,+ timestamp: Date.now(),+ });+ ws.send(+ JSON.stringify({+ jsonrpc: "2.0",+ method: "$ping",+ params: {+ state: omit(conn.heartbeat, "timer"),+ },+ })+ );+ setHeartbeat({+ timer: setTimeout(ping, WEBSOCKET_HEARTBEAT_INTERVAL),+ });+ };++ ping();+};++const connectWebSocket = () => {+ if (conn.ws) {+ return conn.ws;+ }++ const connect = (+ resolve: (value: WebSocket | PromiseLike<WebSocket>) => void,+ reject: (reason?: unknown) => void+ ) => {+ const ws = new WebSocket(conn.url);+ const retries = conn.retries++;+ emit();++ switch (conn.state) {+ case "closed":+ reject("Connection is closed");+ return;+ case "ready":+ case "reconnecting":+ setConnState({ state: "reconnecting" });+ break;+ case "initial":+ break;+ }++ sleep(progressiveDelay(retries)).then(() => {+ const handleError = (code: number, reason: string) => {+ if (conn.state === "closed" || conn.state === "ready") {+ return;+ }+ if (conn.retries >= MAX_RETRIES) {+ setConnState({ state: "closed" });+ reject(+ `${messages.disconnected()}: max retries exceeded (${MAX_RETRIES}). code=${code} reason="${reason}"`+ );+ return;+ }+ connect(resolve, reject);+ };++ const timer = setTimeout(() => {+ handleError(-1, "timeout");+ }, WEBSOCKET_TIMEOUT);++ ws.addEventListener("open", () => {+ clearTimeout(timer);+ if (conn.state === "ready" || conn.state === "closed") {+ return;+ }+ setConnState({ state: "ready", retries: 0 });+ useHeartbeat(ws);+ resolve(ws);+ });++ ws.addEventListener("close", (event) => {+ clearTimeout(timer);+ handleError(event.code, event.reason);+ });+ });+ };++ const promise = new Promise<WebSocket>(connect);+ setConnState({ ws: promise });+ return promise;+};++const reconnect = async () => {+ setConnState({+ ws: undefined,+ state: "initial",+ retries: 0,+ });++ await refreshTokens();++ if (state.client) {+ try {+ state.client.dispose();+ } catch {+ // ignore+ }+ state.client = undefined;+ }+ state.clientInitialized = undefined;+ await initializeLSPClient();+};++const createLanguageClient = async (): Promise<MonacoLanguageClient> => {+ const ws = await connectWebSocket();+ const socket = toSocket(ws);+ const reader = new WebSocketMessageReader(socket);+ const writer = new WebSocketMessageWriter(socket);+ return new MonacoLanguageClient({+ name: "Bytebase Language Client",+ clientOptions: {+ documentSelector: ["sql", "javascript"],+ initializationOptions: {+ performanceMode: true,+ diagnosticDelay: 500,+ disableFeaturesWhileTyping: true,+ },+ middleware: {+ provideHover: throttle(async (document, position, token, next) => {+ return next(document, position, token);+ }, 300),+ provideCompletionItem: throttle(+ async (document, position, context, token, next) => {+ const triggerCharacters = [".", ",", "(", " "];+ if (+ context.triggerKind === 1 &&+ !triggerCharacters.includes(context.triggerCharacter || "")+ ) {+ return { items: [] };+ }+ return next(document, position, context, token);+ },+ 200+ ),+ },+ errorHandler: {+ error: () => ({ action: ErrorAction.Continue }),+ closed: () => {+ reconnect().catch((err) => errorNotification(err));+ return { action: CloseAction.DoNotRestart };+ },+ },+ },+ messageTransports: { reader, writer },+ });+};++const initializeRunner = async () => {+ const client = await createLanguageClient();+ client.onDidChangeState((event) => {+ if (event.newState === State.Running) {+ const { lastCommand } = conn;+ if (lastCommand) {+ void executeCommand(client, lastCommand.command, lastCommand.arguments);+ }+ }+ });++ try {+ await client.start();+ } catch (err) {+ errorNotification(err);+ }++ state.client = client;+ return client;+};++export const initializeLSPClient = () => {+ if (state.clientInitialized) {+ return state.clientInitialized;+ }+ const job = initializeRunner();+ state.clientInitialized = job;+ return job;+};++export const executeCommand = async (+ client: MonacoLanguageClient,+ command: string,+ args: unknown[] | undefined+) => {+ const executeCommandParams: ExecuteCommandParams = {+ command,+ arguments: args,+ };+ setConnState({ lastCommand: executeCommandParams });+ return client.sendRequest("workspace/executeCommand", executeCommandParams);+};++export const subscribeConnectionState = (listener: () => void) => {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+};++export const getConnectionStateSnapshot = () => ({+ state: conn.state,+ heartbeat: conn.heartbeat,+});++export const getConnectionWebSocket = () => conn.ws;diff --git a/frontend/src/react/components/monaco/services.ts b/frontend/src/react/components/monaco/services.tsnew file mode 100644index 0000000000..774f02825b--- /dev/null+++ b/frontend/src/react/components/monaco/services.ts@@ -0,0 +1,60 @@+import "@codingame/monaco-vscode-javascript-default-extension";+import getLanguagesServiceOverride from "@codingame/monaco-vscode-languages-service-override";+import "@codingame/monaco-vscode-sql-default-extension";+import getTextMateServiceOverride from "@codingame/monaco-vscode-textmate-service-override";+import "@codingame/monaco-vscode-theme-defaults-default-extension";+import getThemeServiceOverride from "@codingame/monaco-vscode-theme-service-override";+import "vscode/localExtensionHost";++type WorkerLoader = () => Worker;++const workerLoaders: Partial<Record<string, WorkerLoader>> = {+ TextEditorWorker: () =>+ new Worker(+ new URL("monaco-editor/esm/vs/editor/editor.worker.js", import.meta.url),+ { type: "module" }+ ),+ TextMateWorker: () =>+ new Worker(+ new URL(+ "@codingame/monaco-vscode-textmate-service-override/worker",+ import.meta.url+ ),+ { type: "module" }+ ),+};++window.MonacoEnvironment = {+ getWorker: function (_moduleId, label) {+ const workerFactory = workerLoaders[label];+ if (workerFactory != null) {+ return workerFactory();+ }+ throw new Error(`Worker ${label} not found`);+ },+};++const state = {+ servicesInitialized: undefined as Promise<void> | undefined,+};++const initializeRunner = async () => {+ const { initialize: initializeServices } = await import(+ "@codingame/monaco-vscode-api"+ );+ await initializeServices({+ ...getTextMateServiceOverride(),+ ...getThemeServiceOverride(),+ ...getLanguagesServiceOverride(),+ });+};++export const initializeMonacoServices = async () => {+ if (state.servicesInitialized) {+ return state.servicesInitialized;+ }++ const job = initializeRunner();+ state.servicesInitialized = job;+ return job;+};diff --git a/frontend/src/react/components/monaco/sqlFormatter.ts b/frontend/src/react/components/monaco/sqlFormatter.tsnew file mode 100644index 0000000000..0c0db2098b--- /dev/null+++ b/frontend/src/react/components/monaco/sqlFormatter.ts@@ -0,0 +1,40 @@+import type { FormatOptionsWithLanguage } from "sql-formatter";+import type { SQLDialect } from "@/types";++type FormatResult = {+ data: string;+ error: Error | null;+};++type FormatterLanguage = FormatOptionsWithLanguage["language"];++const convertDialectToFormatterLanguage = (+ dialect: SQLDialect | undefined+): FormatterLanguage => {+ if (dialect === "MYSQL" || dialect === "TIDB" || dialect === "OCEANBASE") {+ return "mysql";+ }+ if (dialect === "POSTGRES") {+ return "postgresql";+ }+ if (dialect === "SNOWFLAKE") {+ return "snowflake";+ }+ return "sql";+};++export const formatSQL = async (+ sql: string,+ dialect: SQLDialect | undefined+): Promise<FormatResult> => {+ const { format } = await import("sql-formatter");+ const options: Partial<FormatOptionsWithLanguage> = {+ language: convertDialectToFormatterLanguage(dialect),+ };++ try {+ return { data: format(sql, options), error: null };+ } catch (error) {+ return { data: "", error: error as Error };+ }+};diff --git a/frontend/src/react/components/monaco/suggest-icons.ts b/frontend/src/react/components/monaco/suggest-icons.tsnew file mode 100644index 0000000000..dc0f7ebdec--- /dev/null+++ b/frontend/src/react/components/monaco/suggest-icons.ts@@ -0,0 +1,108 @@+import SchemaIconSVG from "lucide-static/icons/box.svg?raw";+import FunctionIconSVG from "lucide-static/icons/square-function.svg?raw";+import TableIconSVG from "lucide-static/icons/table.svg?raw";++const DatabaseIconSVG = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">+ <path stroke-linecap="round" stroke-linejoin="round" d="M20.25 6.375c0 2.278-3.694 4.125-8.25 4.125S3.75 8.653 3.75 6.375m16.5 0c0-2.278-3.694-4.125-8.25-4.125S3.75 4.097 3.75 6.375m16.5 0v11.25c0 2.278-3.694 4.125-8.25 4.125s-8.25-1.847-8.25-4.125V6.375m16.5 0v3.75m-16.5-3.75v3.75m16.5 0v3.75C20.25 16.153 16.556 18 12 18s-8.25-1.847-8.25-4.125v-3.75m16.5 0c0 2.278-3.694 4.125-8.25 4.125s-8.25-1.847-8.25-4.125" />+</svg>`;++const ColumnIconSVG = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-columns-3">+ <rect width="18" height="18" x="3" y="3" rx="2"/><path d="M9 3v18"/>+</svg>`;++const ViewIconSVG = {+ normal: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" stroke-linecap="round" stroke-linejoin="round">+ <g stroke="rgb(156 163 175)" stroke-width="2" >+ <path d="M12 3v18"/>+ <rect width="18" height="18" x="3" y="3" rx="2"/>+ <path d="M3 9h18M3 15h18"/>+ </g>+ <g transform="scale(.75)" transform-origin="100% 100%" stroke="rgb(79 70 229)" stroke-width="3.5">+ <circle cx="6" cy="15" r="4"/>+ <circle cx="18" cy="15" r="4"/>+ <path d="M14 15a2 2 0 0 0-2-2 2 2 0 0 0-2 2m-7.5-2L5 7c.7-1.3 1.4-2 3-2m13.5 8L19 7c-.7-1.3-1.5-2-3-2"/>+ </g>+</svg>`,+ active: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" stroke-linecap="round" stroke-linejoin="round">+ <g stroke="#fff" stroke-width="2" >+ <path d="M12 3v18"/>+ <rect width="18" height="18" x="3" y="3" rx="2"/>+ <path d="M3 9h18M3 15h18"/>+ </g>+ <g transform="scale(.75)" transform-origin="100% 100%" stroke="rgb(79 70 229)" stroke-width="3.5">+ <circle cx="6" cy="15" r="4"/>+ <circle cx="18" cy="15" r="4"/>+ <path d="M14 15a2 2 0 0 0-2-2 2 2 0 0 0-2 2m-7.5-2L5 7c.7-1.3 1.4-2 3-2m13.5 8L19 7c-.7-1.3-1.5-2-3-2"/>+ </g>+</svg>`,+};++type MonochromeIconOverride = { css: string; url: string };+type ColoredIconOverride = {+ css: string;+ url: { normal: string; active: string };+};++const contentToDataURL = (content: string, mimeType = "image/svg+xml") => {+ return `data:${mimeType};base64,${btoa(content)}`;+};++const monochromeIconOverrides: MonochromeIconOverride[] = [+ { css: "module", url: contentToDataURL(SchemaIconSVG) },+ { css: "class", url: contentToDataURL(DatabaseIconSVG) },+ { css: "field", url: contentToDataURL(TableIconSVG) },+ { css: "interface", url: contentToDataURL(ColumnIconSVG) },+ { css: "function", url: contentToDataURL(FunctionIconSVG) },+];++const coloredIconOverrides: ColoredIconOverride[] = [+ {+ css: "variable",+ url: {+ normal: contentToDataURL(ViewIconSVG.normal),+ active: contentToDataURL(ViewIconSVG.active),+ },+ },+];++const createMonochromeCSS = (icon: MonochromeIconOverride) => {+ return `.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.codicon.codicon-symbol-${icon.css}:before {+ content: " " !important;+ width: 16px;+ height: 16px;+ background-color: currentColor;+ mask-image: url(${icon.url});+ mask-size: 100% 100%;+}`;+};++const createColoredCSS = (icon: ColoredIconOverride) => {+ return `.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.codicon.codicon-symbol-${icon.css}:before {+ content: " " !important;+ width: 16px;+ height: 16px;+ background-image: url(${icon.url.normal});+ background-size: 100% 100%;+}+.monaco-editor .suggest-widget .monaco-list .monaco-list-row.focused .suggest-icon.codicon.codicon-symbol-${icon.css}:before {+ background-image: url(${icon.url.active});+}`;+};++const STYLE_ID = "bb-react-monaco-suggest-icons";++export const ensureSuggestOverrideStyle = () => {+ const existing = document.getElementById(STYLE_ID) as HTMLStyleElement | null;+ if (existing) {+ return existing;+ }++ const style = document.createElement("style");+ style.id = STYLE_ID;+ style.textContent = [+ ...monochromeIconOverrides.map(createMonochromeCSS),+ ...coloredIconOverrides.map(createColoredCSS),+ ].join("\n");+ document.head.appendChild(style);+ return style;+};diff --git a/frontend/src/react/components/monaco/text-model.ts b/frontend/src/react/components/monaco/text-model.tsnew file mode 100644index 0000000000..abac4ab58c--- /dev/null+++ b/frontend/src/react/components/monaco/text-model.ts@@ -0,0 +1,47 @@+import type * as MonacoType from "monaco-editor";+import type { Language } from "@/types";+import { loadMonacoEditor } from "./core";++const textModelMapByFilename = new Map<string, MonacoType.editor.ITextModel>();+const viewStateMapByUri = new Map<+ string,+ MonacoType.editor.ICodeEditorViewState | null+>();++export const getUriByFilename = async (filename: string) => {+ const monaco = await loadMonacoEditor();+ return monaco.Uri.parse(`file:///workspace/${filename}`);+};++export const getOrCreateTextModel = async (+ filename: string,+ content: string,+ language: Language+) => {+ const existing = textModelMapByFilename.get(filename);+ if (existing) {+ return existing;+ }++ const monaco = await loadMonacoEditor();+ const uri = await getUriByFilename(filename);+ const model = monaco.editor.createModel(content, language, uri);+ textModelMapByFilename.set(filename, model);+ return model;+};++export const storeViewState = (+ editor: MonacoType.editor.IStandaloneCodeEditor,+ model: MonacoType.editor.ITextModel | null | undefined+) => {+ if (!model) return;+ viewStateMapByUri.set(model.uri.toString(), editor.saveViewState());+};++export const restoreViewState = (+ editor: MonacoType.editor.IStandaloneCodeEditor,+ model: MonacoType.editor.ITextModel | null | undefined+) => {+ if (!model) return;+ editor.restoreViewState(viewStateMapByUri.get(model.uri.toString()) ?? null);+};diff --git a/frontend/src/react/components/monaco/themes/bb-dark.ts b/frontend/src/react/components/monaco/themes/bb-dark.tsnew file mode 100644index 0000000000..5b35262e8a--- /dev/null+++ b/frontend/src/react/components/monaco/themes/bb-dark.ts@@ -0,0 +1,23 @@+import type { editor as Editor } from "monaco-editor";+import { callCssVariable } from "@/utils";++export const getBBDarkTheme = (): Editor.IStandaloneThemeData => ({+ base: "vs-dark",+ inherit: true,+ rules: [+ {+ foreground: callCssVariable("--color-matrix-green-hover"),+ token: "keyword",+ },+ ],+ colors: {+ "editor.foreground": callCssVariable("--color-matrix-green"),+ "editorCursor.foreground": callCssVariable("--color-matrix-green-hover"),+ "editorLineNumber.foreground": callCssVariable("--color-matrix-green"),+ "editorLineNumber.activeForeground": callCssVariable(+ "--color-matrix-green-hover"+ ),+ "editor.wordHighlightBackground": "#00000000",+ "editor.wordHighlightStrongBackground": "#00000000",+ },+});diff --git a/frontend/src/react/components/monaco/themes/bb.ts b/frontend/src/react/components/monaco/themes/bb.tsnew file mode 100644index 0000000000..d39bcab798--- /dev/null+++ b/frontend/src/react/components/monaco/themes/bb.ts@@ -0,0 +1,18 @@+import type { editor as Editor } from "monaco-editor";+import { callCssVariable } from "@/utils";++export const getBBTheme = (): Editor.IStandaloneThemeData => ({+ base: "vs",+ inherit: true,+ rules: [],+ colors: {+ "editor.background": "#fffffe00",+ "editorCursor.foreground": callCssVariable("--color-accent"),+ "editorLineNumber.foreground": callCssVariable(+ "--color-control-placeholder"+ ),+ "editorLineNumber.activeForeground": callCssVariable("--color-main"),+ "editor.wordHighlightBackground": "#00000000",+ "editor.wordHighlightStrongBackground": "#00000000",+ },+});diff --git a/frontend/src/react/components/monaco/types.ts b/frontend/src/react/components/monaco/types.tsnew file mode 100644index 0000000000..fbc65d6aa3--- /dev/null+++ b/frontend/src/react/components/monaco/types.ts@@ -0,0 +1,67 @@+import type * as monaco from "monaco-editor";++export type MonacoModule = typeof monaco;++export type IStandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;+export type IStandaloneEditorConstructionOptions =+ monaco.editor.IStandaloneEditorConstructionOptions;+export type IStandaloneDiffEditor = monaco.editor.IStandaloneDiffEditor;+export type IStandaloneDiffEditorConstructionOptions =+ monaco.editor.IStandaloneDiffEditorConstructionOptions;++export type ITextModel = monaco.editor.ITextModel;+export type Selection = monaco.Selection;++export type AdviceOption = {+ severity: "ERROR" | "WARNING";+ message: string;+ source?: string;+ startLineNumber: number;+ startColumn: number;+ endLineNumber: number;+ endColumn: number;+};++export type LineHighlightOption = {+ startLineNumber: number;+ endLineNumber: number;+ options: monaco.editor.IModelDecorationOptions;+};++export const SupportedLanguages: monaco.languages.ILanguageExtensionPoint[] = [+ {+ id: "sql",+ extensions: [".sql"],+ aliases: ["SQL", "sql"],+ mimetypes: ["application/x-sql"],+ },+ {+ id: "javascript",+ extensions: [".js"],+ aliases: ["JS", "js"],+ mimetypes: ["application/javascript"],+ },+ {+ id: "redis",+ extensions: [".redis"],+ aliases: ["REDIS", "redis"],+ mimetypes: ["application/redis"],+ },+];++export type AutoCompleteContextScene = "query" | "all";++export type AutoCompleteContext = {+ instance: string;+ database?: string;+ schema?: string;+ scene?: AutoCompleteContextScene;+};++export type FormatContentOptions = {+ disabled: boolean;+ callback?: (+ monaco: MonacoModule,+ editor: monaco.editor.IStandaloneCodeEditor+ ) => void;+};diff --git a/frontend/src/react/components/monaco/utils.ts b/frontend/src/react/components/monaco/utils.tsnew file mode 100644index 0000000000..433696b56b--- /dev/null+++ b/frontend/src/react/components/monaco/utils.ts@@ -0,0 +1,139 @@+import { Range } from "monaco-editor";+import { t } from "@/plugins/i18n";+import { pushNotification } from "@/store";+import type { Language, SQLDialect } from "@/types";+import { callCssVariable, escapeMarkdown, minmax } from "@/utils";+import { formatSQL } from "./sqlFormatter";+import type { IStandaloneCodeEditor, Selection } from "./types";++export const MAX_RETRIES = 5;+export const RECONNECTION_DELAY = {+ max: 1000,+ min: 100,+ growth: 1.5,+};+export const WEBSOCKET_TIMEOUT = 5000;+export const WEBSOCKET_HEARTBEAT_INTERVAL = 10 * 1000;++export const messages = {+ title: () => t("sql-editor.web-socket.errors.title"),+ description: () => t("sql-editor.web-socket.errors.description"),+ disconnected: () => t("sql-editor.web-socket.errors.disconnected"),+};++export const extensionNameOfLanguage = (lang: Language) => {+ switch (lang) {+ case "sql":+ return "sql";+ case "javascript":+ return "js";+ case "redis":+ return "redis";+ case "json":+ return "json";+ }+ return "sql";+};++export const trySetContentWithUndo = (+ editor: IStandaloneCodeEditor,+ content: string,+ source: string | undefined = undefined+) => {+ editor.executeEdits(source, [+ {+ range: new Range(1, 1, Number.MAX_SAFE_INTEGER, 1),+ text: "",+ forceMoveMarkers: true,+ },+ {+ range: new Range(1, 1, 1, 1),+ text: content,+ forceMoveMarkers: true,+ },+ ]);+};++export const formatEditorContent = async (+ editor: IStandaloneCodeEditor,+ dialect: SQLDialect | undefined+) => {+ const model = editor.getModel();+ if (!model) return;+ const sql = model.getValue();+ const { data, error } = await formatSQL(sql, dialect);+ if (error) return;+ const pos = editor.getPosition();+ trySetContentWithUndo(editor, data, "Format content");+ if (pos) {+ editor.setPosition(pos);+ }+};++export const createUrl = (+ host: string,+ path: string,+ secure: boolean = location.protocol === "https:"+) => {+ const protocol = secure ? "wss" : "ws";+ return new URL(`${protocol}://${host}${path}`);+};++const extractErrorMessage = (err: unknown) => {+ if (typeof err === "string") return err;+ if (typeof (err as Error).message === "string") {+ return (err as Error).message;+ }+ return String(err);+};++export const errorNotification = (err: unknown) => {+ const message = extractErrorMessage(err);+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: messages.title(),+ description: `${messages.description()}${message ? ` ${message}` : ""}`,+ });+};++export const progressiveDelay = (serial: number) => {+ if (serial === 0) return 0;+ return minmax(+ RECONNECTION_DELAY.min * Math.pow(RECONNECTION_DELAY.growth, serial - 1),+ RECONNECTION_DELAY.min,+ RECONNECTION_DELAY.max+ );+};++export const positionWithOffset = (+ line: number,+ column: number,+ selection?: Selection | null+) => {+ if (!selection || selection.isEmpty()) {+ return [line, column];+ }+ const pos = selection.getStartPosition().delta(line - 1, column - 1);+ return [pos.lineNumber, pos.column];+};++export const buildAdviceHoverMessage = (advice: {+ severity: "ERROR" | "WARNING";+ message: string;+ source?: string;+}) => {+ const colors = {+ WARNING: callCssVariable("--color-warning"),+ ERROR: callCssVariable("--color-error"),+ };+ const parts: string[] = [];+ parts.push(+ `<span style="color:${colors[advice.severity]};">[${advice.severity}]</span>`+ );+ if (advice.source) {+ parts.push(` ${escapeMarkdown(advice.source)}`);+ }+ parts.push(`\n${escapeMarkdown(advice.message)}`);+ return parts.join("");+};diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex 46109168d3..4bf4db0692 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -1898,11 +1898,19 @@"activate-access": "Activate","activate-confirm": "Are you sure you want to activate this access grant?","expired": "Expired",+ "format-sql": "Format SQL","grant-type-unmask": "Unmask","revoke-access": "Revoke","revoke-confirm": "Are you sure you want to revoke this access grant?","self": "SQL Editor",- "view-issue": "View Issue"+ "view-issue": "View Issue",+ "web-socket": {+ "errors": {+ "description": "Auto Completion might be limited or disabled.",+ "disconnected": "WebSocket disconnected",+ "title": "WebSocket connection failed"+ }+ }},"sql-review": {"add-or-remove-rules": "Add or remove rules",diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex bb59e6988c..e0d68c229f 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -1898,11 +1898,19 @@"activate-access": "Activate","activate-confirm": "Are you sure you want to activate this access grant?","expired": "Expired",+ "format-sql": "Format SQL","grant-type-unmask": "Unmask","revoke-access": "Revoke","revoke-confirm": "Are you sure you want to revoke this access grant?","self": "Editor de SQL",- "view-issue": "View Issue"+ "view-issue": "View Issue",+ "web-socket": {+ "errors": {+ "description": "Auto Completion might be limited or disabled.",+ "disconnected": "WebSocket disconnected",+ "title": "WebSocket connection failed"+ }+ }},"sql-review": {"add-or-remove-rules": "Agregar o eliminar reglas",diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex 2d50abd40c..afed78f939 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -1898,11 +1898,19 @@"activate-access": "Activate","activate-confirm": "Are you sure you want to activate this access grant?","expired": "Expired",+ "format-sql": "Format SQL","grant-type-unmask": "Unmask","revoke-access": "Revoke","revoke-confirm": "Are you sure you want to revoke this access grant?","self": "SQLエディタ",- "view-issue": "View Issue"+ "view-issue": "View Issue",+ "web-socket": {+ "errors": {+ "description": "Auto Completion might be limited or disabled.",+ "disconnected": "WebSocket disconnected",+ "title": "WebSocket connection failed"+ }+ }},"sql-review": {"add-or-remove-rules": "ルールを追加または削除する",diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex a7f1c6f6cf..5873d1ec64 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -1898,11 +1898,19 @@"activate-access": "Activate","activate-confirm": "Are you sure you want to activate this access grant?","expired": "Expired",+ "format-sql": "Format SQL","grant-type-unmask": "Unmask","revoke-access": "Revoke","revoke-confirm": "Are you sure you want to revoke this access grant?","self": "Trình soạn thảo SQL",- "view-issue": "View Issue"+ "view-issue": "View Issue",+ "web-socket": {+ "errors": {+ "description": "Auto Completion might be limited or disabled.",+ "disconnected": "WebSocket disconnected",+ "title": "WebSocket connection failed"+ }+ }},"sql-review": {"add-or-remove-rules": "Thêm hoặc xóa quy tắc",diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex 9fe310a3c5..e46c911794 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -1898,11 +1898,19 @@"activate-access": "激活","activate-confirm": "确定要激活此访问授权吗?","expired": "已过期",+ "format-sql": "格式化 SQL","grant-type-unmask": "脱敏豁免","revoke-access": "撤销","revoke-confirm": "确定要撤销此访问授权吗?","self": "SQL 编辑器",- "view-issue": "查看工单"+ "view-issue": "查看工单",+ "web-socket": {+ "errors": {+ "description": "Auto Completion might be limited or disabled.",+ "disconnected": "WebSocket disconnected",+ "title": "WebSocket connection failed"+ }+ }},"sql-review": {"add-or-remove-rules": "添加或删除规则",diff --git a/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx b/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsxindex b5ccd04557..bee37b2546 100644--- a/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx+++ b/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx@@ -370,19 +370,16 @@ vi.mock("@/react/components/ui/dialog", () => ({)),}));-vi.mock("@/components/MonacoEditor/editor", () => ({+vi.mock("@/react/components/monaco/core", () => ({createMonacoDiffEditor: vi.fn(),createMonacoEditor: vi.fn(),+ initializeMonacoServices: vi.fn(),}));vi.mock("@/react/components/monaco", () => ({ReadonlyMonaco: vi.fn(() => null),}));-vi.mock("@/components/MonacoEditor/services", () => ({- initializeMonacoServices: vi.fn(),-}));-vi.mock("monaco-editor", () => ({}));vi.mock(diff --git a/frontend/src/react/pages/project/ProjectSyncSchemaPage.tsx b/frontend/src/react/pages/project/ProjectSyncSchemaPage.tsxindex 2d7e4a4474..cf2cff638c 100644--- a/frontend/src/react/pages/project/ProjectSyncSchemaPage.tsx+++ b/frontend/src/react/pages/project/ProjectSyncSchemaPage.tsx@@ -14,13 +14,15 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { v4 as uuidv4 } from "uuid";import { EngineIconPath } from "@/components/InstanceForm/constants";-import {- createMonacoDiffEditor,- createMonacoEditor,-} from "@/components/MonacoEditor/editor";import { DatabaseSelect } from "@/react/components/DatabaseSelect";import { EnvironmentSelect } from "@/react/components/EnvironmentSelect";import { LearnMoreLink } from "@/react/components/LearnMoreLink";+import {+ createMonacoDiffEditor,+ createMonacoEditor,+ loadMonacoEditor,+ setMonacoModelLanguage,+} from "@/react/components/monaco/core";import { Button } from "@/react/components/ui/button";import { Combobox, type ComboboxOption } from "@/react/components/ui/combobox";import {@@ -45,10 +47,10 @@ import {} from "@/store";import { projectNamePrefix } from "@/store/modules/v1/common";import {- dialectOfEngineV1,getDateForPbTimestampProtoEs,isValidDatabaseName,isValidEnvironmentName,+ languageOfEngineV1,} from "@/types";import { Engine } from "@/types/proto-es/v1/common_pb";import type { Database } from "@/types/proto-es/v1/database_service_pb";@@ -965,7 +967,7 @@ function RawSQLEditor({const editor = await createMonacoEditor({container: containerRef.current,options: {- language: dialectOfEngineV1(localEngine),+ language: languageOfEngineV1(localEngine),value: localStatement,},});@@ -992,10 +994,7 @@ function RawSQLEditor({useEffect(() => {const model = editorRef.current?.getModel();if (model) {- (async () => {- const { editor: monacoEditor } = await import("monaco-editor");- monacoEditor.setModelLanguage(model, dialectOfEngineV1(localEngine));- })();+ void setMonacoModelLanguage(model, languageOfEngineV1(localEngine));}}, [localEngine]);@@ -1666,7 +1665,7 @@ function DiffViewPanel({</div><MonacoEditorPanelcontent={statement}- language={dialectOfEngineV1(engine)}+ language={languageOfEngineV1(engine)}onChange={onStatementChange}/></>@@ -1720,10 +1719,10 @@ function SchemaDiffViewer({return;}editorRef.current = editor;- const { editor: monacoEditor } = await import("monaco-editor");+ const monaco = await loadMonacoEditor();editor.setModel({- original: monacoEditor.createModel(normalizedOriginal, "sql"),- modified: monacoEditor.createModel(normalizedModified, "sql"),+ original: monaco.editor.createModel(normalizedOriginal, "sql"),+ modified: monaco.editor.createModel(normalizedModified, "sql"),});})();return () => {diff --git a/frontend/src/react/pages/settings/DataClassificationPage.tsx b/frontend/src/react/pages/settings/DataClassificationPage.tsxindex 2c9f06d7d6..062a7fe434 100644--- a/frontend/src/react/pages/settings/DataClassificationPage.tsx+++ b/frontend/src/react/pages/settings/DataClassificationPage.tsx@@ -90,7 +90,7 @@ function MonacoJSONEditor({let disposed = false;(async () => {const { createMonacoEditor } = await import(- "@/components/MonacoEditor/editor"+ "@/react/components/monaco/core");if (disposed || !containerRef.current) return;const editor = await createMonacoEditor({diff --git a/frontend/src/react/plugins/agent/dom/actions.ts b/frontend/src/react/plugins/agent/dom/actions.tsindex 998d3544c7..28a572682d 100644--- a/frontend/src/react/plugins/agent/dom/actions.ts+++ b/frontend/src/react/plugins/agent/dom/actions.ts@@ -94,7 +94,7 @@ async function findMonacoEditor(try {const { isMonacoLoaded, getMonacoEditor } = await import(- "@/components/MonacoEditor/lazy-editor"+ "@/react/components/monaco/core");if (!isMonacoLoaded()) return null;const monaco = await getMonacoEditor();