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(sql-editor): upgrade monaco-editor and lsp (WIP) (#9267)
Liu Ji336bf469a1e4
diff --git a/frontend/package.json b/frontend/package.jsonindex 2a236017ec..bcda3df930 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -2,23 +2,24 @@"name": "bytebase","license": "SEE LICENSE IN LICENSE","scripts": {- "dev": "npm run copy-config-file && vite --mode dev-local",- "release": "export NODE_OPTIONS=--max_old_space_size=8000 && npm run copy-config-file && vite build --mode release --outDir=../backend/server/dist --emptyOutDir",- "dev-embed": "export NODE OPTIONS=--max_old_space_size=8000 && npm run copy-config-file && vite build --mode dev --outDir=../backend/server/dist --emptyOutDir",- "dev-docker": "export NODE_OPTIONS=--max_old_space_size=8000 && vite build --mode dev",- "release-docker": "export NODE_OPTIONS=--max_old_space_size=8000 && vite build --mode release",- "release-aws": "export NODE_OPTIONS=--max_old_space_size=8000 && npm run copy-config-file && vite build --mode release-aws --outDir=../backend/server/dist --emptyOutDir",+ "copy:monaco-workers": "sh ./scripts/copy_monaco_workers.sh",+ "copy:config-files": "sh ./scripts/copy_config_files.sh",+ "copy:all": "npm run copy:monaco-workers && npm run copy:config-files",+ "dev": "npm run copy:all && vite --mode dev-local",+ "release": "export NODE_OPTIONS=--max_old_space_size=8000 && npm run copy:all && vite build --mode release --outDir=../backend/server/dist --emptyOutDir",+ "dev-embed": "export NODE OPTIONS=--max_old_space_size=8000 && npm run copy:all && vite build --mode dev --outDir=../backend/server/dist --emptyOutDir",+ "release-docker": "export NODE_OPTIONS=--max_old_space_size=8000 && npm run copy:all && vite build --mode release",+ "release-aws": "export NODE_OPTIONS=--max_old_space_size=8000 && npm run copy:all && vite build --mode release-aws --outDir=../backend/server/dist --emptyOutDir","lint": "eslint --cache --ext .js,.ts,.tsx,.vue src","lint:fix": "eslint --cache --ext .js,.ts,.tsx,.vue --fix src","bundle-visualize": "vite-bundle-visualizer -c vite.config.ts","type-check": "vue-tsc --noEmit --skipLibCheck","test": "vitest run --passWithNoTests","coverage": "vitest --coverage",- "copy-config-file": "sh ./scripts/copy_config_files.sh"+ "postinstall": "npm run copy:monaco-workers && monaco-treemending"},"dependencies": {"@bytebase/vue-kbar": "0.1.8",- "@codingame/monaco-vscode-api": "1.69.12","@joe-re/sql-parser": "^1.7.0","@markdoc/markdoc": "0.3.2","@soerenmartius/vue3-clipboard": "0.1.2",@@ -51,8 +52,9 @@"markdown-it": "^13.0.2","match-sorter": "6.3.1","maz-ui": "^3.17.0",- "monaco-editor": "0.34.1",- "monaco-languageclient": "4.0.1",+ "monaco-editor": "0.44.0",+ "monaco-editor-workers": "0.44.0",+ "monaco-languageclient": "7.0.0","naive-ui": "2.35.0","nice-grpc-common": "^2.0.2","nice-grpc-error-details": "^0.2.2",@@ -75,10 +77,13 @@"sql-formatter": "13.0.0","uuid": "9.0.1","vdirs": "^0.1.8",+ "vscode": "npm:@codingame/[email protected]",+ "vscode-languageclient": "9.0.1","vscode-languageserver": "8.0.2","vscode-languageserver-protocol": "3.17.3","vscode-languageserver-textdocument": "1.0.8","vscode-languageserver-types": "3.17.3",+ "vscode-ws-jsonrpc": "3.0.0","vue": "3.2.47","vuedraggable": "^4.1.0","vueuc": "0.4.51"@@ -112,6 +117,7 @@"@types/slug": "5.0.4","@types/splitpanes": "2.2.1","@types/uuid": "9.0.6",+ "@types/vscode": "1.84.1","@typescript-eslint/eslint-plugin": "6.7.3","@typescript-eslint/parser": "6.7.3","@vicons/ionicons5": "0.12.0",@@ -140,8 +146,6 @@"vite": "4.4.9","vite-bundle-visualizer": "^0.11.0","vitest": "0.34.4",- "vscode-oniguruma": "1.6.2",- "vscode-textmate": "7.0.4","vue-i18n": "9.4.1","vue-router": "4.2.4","vue-tsc": "1.8.11",@@ -152,8 +156,10 @@"events": "^3.3.0","jquery": "1.9.1 - 3","popper.js": "^1.16.1",- "vscode-oniguruma": "^1.6.2 || ^2.0.0",- "vscode-textmate": "^7.0.1","ws": "^8.13.0"+ },+ "overrides": {+ "monaco-editor": "npm:@codingame/monaco-editor-treemended@>=1.83.5 <1.84.0",+ "vscode": "npm:@codingame/monaco-vscode-api@>=1.83.5 <1.84.0"}}diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex ab88ab2c9a..b7ea7ba80d 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -8,9 +8,6 @@ dependencies:'@bytebase/vue-kbar':specifier: 0.1.8version: 0.1.8([email protected])- '@codingame/monaco-vscode-api':- specifier: 1.69.12- version: 1.69.12([email protected])([email protected])'@joe-re/sql-parser':specifier: ^1.7.0version: 1.7.0@@ -108,11 +105,14 @@ dependencies:specifier: ^3.17.0version: 3.17.0([email protected])([email protected])([email protected])([email protected])([email protected])monaco-editor:- specifier: 0.34.1- version: 0.34.1+ specifier: 0.44.0+ version: 0.44.0+ monaco-editor-workers:+ specifier: 0.44.0+ version: 0.44.0([email protected])monaco-languageclient:- specifier: 4.0.1- version: 4.0.1([email protected])([email protected])+ specifier: 7.0.0+ version: 7.0.0(@codingame/[email protected])([email protected])naive-ui:specifier: 2.35.0version: 2.35.0([email protected])@@ -179,6 +179,12 @@ dependencies:vdirs:specifier: ^0.1.8version: 0.1.8([email protected])+ vscode:+ specifier: npm:@codingame/[email protected]+ version: /@codingame/[email protected]+ vscode-languageclient:+ specifier: 9.0.1+ version: 9.0.1vscode-languageserver:specifier: 8.0.2version: 8.0.2@@ -191,6 +197,9 @@ dependencies:vscode-languageserver-types:specifier: 3.17.3version: 3.17.3+ vscode-ws-jsonrpc:+ specifier: 3.0.0+ version: 3.0.0vue:specifier: 3.2.47version: 3.2.47@@ -286,6 +295,9 @@ devDependencies:'@types/uuid':specifier: 9.0.6version: 9.0.6+ '@types/vscode':+ specifier: 1.84.1+ version: 1.84.1'@typescript-eslint/eslint-plugin':specifier: 6.7.3@@ -370,12 +382,6 @@ devDependencies:vitest:specifier: 0.34.4version: 0.34.4- vscode-oniguruma:- specifier: 1.6.2- version: 1.6.2- vscode-textmate:- specifier: 7.0.4- version: 7.0.4vue-i18n:specifier: 9.4.1version: 9.4.1([email protected])@@ -559,15 +565,32 @@ packages:bundledDependencies:- is-unicode-supported- resolution: {integrity: sha512-ES1xRnU232t82tcdM2ImikkjGfAMgJtrF0XkLa4poEnvcUH0SFqUhYvcqk5CFggQWh16jqxifVvozcu0/mbH7A==}- peerDependencies:- vscode-oniguruma: ^1.6.2- vscode-textmate: ^7.0.1+ /@codingame/[email protected]:+ resolution: {integrity: sha512-HWmI3e2LooNkJG7AB5KYkzqkFma6G7tlk8QO6RI54HykazMQEFNpOEkrnS9UJHGsvpT+1hDCtIkufalLdxqMzA==}+ hasBin: true+ dependencies:+ monaco-editor: 0.44.0+ dev: false++ /@codingame/[email protected]:+ resolution: {integrity: sha512-MORmlcfBHmhHmnkXq6jAH9uB4N08RIgFGOC2gpySgCMWpD0dHd/hsJdJNS39FSRpbPj69gbaZvDW4daKvJABrA==}+ dependencies:+ monaco-editor: 0.44.0+ vscode: /@codingame/[email protected]+ dev: false++ /@codingame/[email protected]:+ resolution: {integrity: sha512-8mo9qGEBYl0whFq0PQslLBwFb2zV9asyOJYuR+BIrUyGb73NYJjKd0PghaDi8NBsBS7EBSxx3bugVNs1FXQNYw==}+ dependencies:+ monaco-editor: 0.44.0+ vscode: /@codingame/[email protected]+ dev: false++ /@codingame/[email protected]:+ resolution: {integrity: sha512-/mNyXlBdv+55taMuuCX4mHGwmMqvcNzlatYAX45QPLFW48hyQYUt+xQBYX1jBNcyjcFY4Mx7VzxT6SvNJGJA3A==}dependencies:- monaco-editor: 0.34.1- vscode-oniguruma: 1.6.2- vscode-textmate: 7.0.4+ monaco-editor: 0.44.0+ vscode: /@codingame/[email protected]dev: false/@css-render/[email protected]([email protected]):@@ -1688,6 +1711,10 @@ packages:resolution: {integrity: sha512-BT2Krtx4xaO6iwzwMFUYvWBWkV2pr37zD68Vmp1CDV196MzczBRxuEpD6Pr395HAgebC/co7hOphs53r8V7jew==}dev: true+ /@types/[email protected]:+ resolution: {integrity: sha512-DB10vBRLEPA/us7p3gQilU2Tq5HDu6JWTyCpD9qtb7MKWIvJS5In9HU3YgVGCXf/miwHJiY62aXwjtUSMpT8HA==}+ dev: true+/@types/[email protected]:resolution: {integrity: sha512-4p9vcSmxAayx72yn70joFoL44c9MO/0+iVEBIQXe3v2h2SiAsEIo/G5v6ObFWvNKRFjbrVadNf9LqEEZeQPzdA==}dev: false@@ -2342,12 +2369,12 @@ packages:dependencies:balanced-match: 1.0.2concat-map: 0.0.1+ dev: trueresolution: {integrity: sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==}dependencies:balanced-match: 1.0.2- dev: trueresolution: {integrity: sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==}@@ -2591,6 +2618,7 @@ packages:resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==}+ dev: trueresolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==}@@ -4177,6 +4205,14 @@ packages:resolution: {integrity: sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==}dependencies:brace-expansion: 1.1.11+ dev: true++ resolution: {integrity: sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==}+ engines: {node: '>=10'}+ dependencies:+ brace-expansion: 2.0.1+ dev: falseresolution: {integrity: sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg==}@@ -4205,20 +4241,31 @@ packages:ufo: 1.3.1dev: true- resolution: {integrity: sha512-FKc80TyiMaruhJKKPz5SpJPIjL+dflGvz4CpuThaPMc94AyN7SeC9HQ8hrvaxX7EyHdJcUY5i4D0gNyJj1vSZQ==}+ resolution: {integrity: sha512-rvdO292CMnxs9Y3Hl6nAjVx8d0SjcDgmXmZNVoaOCNJrdnTEEzcWcHJzEQsajTAAq4H2oeBmDZRpDE0US5DhXA==}+ peerDependencies:+ monaco-editor: ~0.44.0+ dependencies:+ monaco-editor: 0.44.0dev: false- resolution: {integrity: sha512-mUIq/7gQM/8CyOBVGv0thLRAR80vk49Ur0ROJveoh6R0/uwaUoyri+5OBslxsa5BICftLTsC8/Y+at6/iW50Ww==}- engines: {node: '>=16.11.0', npm: '>=8.0.0'}+ resolution: {integrity: sha512-5SmjNStN6bSuSE5WPT2ZV+iYn1/yI9sd4Igtk23ChvqB7kDk9lZbB9F5frsuvpB+2njdIeGGFf2G4gbE6rCC9Q==}+ dev: false++ resolution: {integrity: sha512-UuFYGKaZe13HwUfugzRZPTrp9Q95+47g7jGtR7loX5psiuqB/q9H+V5AkBbWfDJ03SOWkw0qPpmJ2ZIomOIvaw==}+ engines: {node: '>=16.11.0', npm: '>=9.0.0'}+ peerDependencies:+ monaco-editor: 0.44.0+ vscode: npm:@codingame/monaco-vscode-api@>=1.83.5 <1.84.0dependencies:- vscode-jsonrpc: 8.0.2- vscode-languageclient: 8.0.2- transitivePeerDependencies:- - vscode-oniguruma- - vscode-textmate+ '@codingame/monaco-vscode-editor-service-override': 1.83.5+ '@codingame/monaco-vscode-languages-service-override': 1.83.5+ '@codingame/monaco-vscode-model-service-override': 1.83.5+ monaco-editor: 0.44.0+ vscode: /@codingame/[email protected]+ vscode-languageclient: 9.0.1dev: false@@ -5773,13 +5820,18 @@ packages:engines: {node: '>=14.0.0'}dev: false- resolution: {integrity: sha512-lHlthJtphG9gibGb/y72CKqQUxwPsMXijJVpHEC2bvbFqxmkj9LwQ3aGU9dwjBLqsX1S4KjShYppLvg1UJDF/Q==}- engines: {vscode: ^1.67.0}+ resolution: {integrity: sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==}+ engines: {node: '>=14.0.0'}+ dev: false++ resolution: {integrity: sha512-JZiimVdvimEuHh5olxhxkht09m3JzUGwggb5eRUkzzJhZ2KjCN0nh55VfiED9oez9DyF8/fz1g1iBV3h+0Z2EA==}+ engines: {vscode: ^1.82.0}dependencies:- minimatch: 3.1.2+ minimatch: 5.1.6semver: 7.5.4- vscode-languageserver-protocol: 3.17.2+ vscode-languageserver-protocol: 3.17.5dev: false@@ -5796,6 +5848,13 @@ packages:vscode-languageserver-types: 3.17.3dev: false+ resolution: {integrity: sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==}+ dependencies:+ vscode-jsonrpc: 8.2.0+ vscode-languageserver-types: 3.17.5+ dev: false+resolution: {integrity: sha512-1bonkGqQs5/fxGT5UchTgjGVnfysL0O8v1AYMBjqTbWQTFn721zaPGDYFkOKtfDgFiSgXM3KwaG3FMGfW4Ed9Q==}dev: false@@ -5808,6 +5867,10 @@ packages:resolution: {integrity: sha512-SYU4z1dL0PyIMd4Vj8YOqFvHu7Hz/enbWtpfnVbJHU4Nd1YNYx8u0ennumc6h48GQNeOLxmwySmnADouT/AuZA==}dev: false+ resolution: {integrity: sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==}+ dev: false+resolution: {integrity: sha512-bpEt2ggPxKzsAOZlXmCJ50bV7VrxwCS5BI4+egUmure/oI/t4OlFzi/YNtVvY24A2UDOZAgwFGgnZPwqSJubkA==}hasBin: true@@ -5815,11 +5878,12 @@ packages:vscode-languageserver-protocol: 3.17.2dev: false- resolution: {integrity: sha512-KH8+KKov5eS/9WhofZR8M8dMHWN2gTxjMsG4jd04YhpbPR91fUj7rYQ2/XjeHCJWbg7X++ApRIU9NUwM2vTvLA==}-- resolution: {integrity: sha512-9hJp0xL7HW1Q5OgGe03NACo7yiCTMEk3WU/rtKXUbncLtdg6rVVNJnHwD88UhbIYU2KoxY0Dih0x+kIsmUKn2A==}+ resolution: {integrity: sha512-22IbVb2K691np9pOubyahNBj1BicsbtlbiaHOJu5/rvyWDqmqPMAqpAfojwGjdBztp8EtO8TAO7lmyY6hnmYAA==}+ engines: {node: '>=16.11.0', npm: '>=8.0.0'}+ dependencies:+ vscode-jsonrpc: 8.1.0+ dev: falseresolution: {integrity: sha512-Q9S7dzWGax7LN5iiSPcu/K1GGm2gcBBlYwmMsUc5/16N6w90cbKow3FnPmPs95sungns4yvd9/+JhbAznECS2A==}diff --git a/frontend/public/monaco-workers/.gitignore b/frontend/public/monaco-workers/.gitignorenew file mode 100644index 0000000000..cf44e148ba--- /dev/null+++ b/frontend/public/monaco-workers/.gitignore@@ -0,0 +1 @@+**/*.js\ No newline at end of filediff --git a/frontend/public/monaco-workers/.gitkeep b/frontend/public/monaco-workers/.gitkeepnew file mode 100644index 0000000000..e69de29bb2diff --git a/frontend/scripts/copy_monaco_workers.sh b/frontend/scripts/copy_monaco_workers.shnew file mode 100644index 0000000000..3d718464ce--- /dev/null+++ b/frontend/scripts/copy_monaco_workers.sh@@ -0,0 +1,3 @@+#!/bin/sh+mkdir -p ./public/monaco-workers+cp -r node_modules/monaco-editor-workers/dist/workers/*.js ./public/monaco-workersdiff --git a/frontend/src/bbkit/BBSwitch.vue b/frontend/src/bbkit/BBSwitch.vueindex a6ca9d8166..b94e43ff96 100644--- a/frontend/src/bbkit/BBSwitch.vue+++ b/frontend/src/bbkit/BBSwitch.vue@@ -44,7 +44,8 @@: '',}">- {{ state.dirtyOn ? $t("common.on") : $t("common.off") }}+ <slot v-if="state.dirtyOn" name="on">{{ $t("common.on") }}</slot>+ <slot v-else name="off">{{ $t("common.off") }}</slot></span></button><spandiff --git a/frontend/src/components/AlterSchemaPrepForm/DatabaseGroupPrevEditorModal.vue b/frontend/src/components/AlterSchemaPrepForm/DatabaseGroupPrevEditorModal.vueindex 6efb31a7a8..1463409403 100644--- a/frontend/src/components/AlterSchemaPrepForm/DatabaseGroupPrevEditorModal.vue+++ b/frontend/src/components/AlterSchemaPrepForm/DatabaseGroupPrevEditorModal.vue@@ -37,10 +37,8 @@</div><div class="relative w-full h-96 border rounded overflow-clip"><MonacoEditor- ref="editorRef"+ v-model:content="state.editStatement"class="w-full min-h-full"- :value="state.editStatement"- @change="handleStatementChange"/></div></div>@@ -75,6 +73,7 @@ import { NButton } from "naive-ui";import { computed, onMounted, PropType, reactive } from "vue";import { useI18n } from "vue-i18n";import { useRouter } from "vue-router";+import { MonacoEditor } from "@/components/MonacoEditor";import ActionConfirmModal from "@/components/SchemaEditorV1/Modals/ActionConfirmModal.vue";import { useDBGroupStore, useNotificationStore } from "@/store";import { ComposedDatabaseGroup, ComposedSchemaGroup } from "@/types";@@ -134,10 +133,6 @@ onMounted(async () => {state.editStatement = generateReferenceStatement(schemaGroupList);});-const handleStatementChange = (value: string) => {- state.editStatement = value;-};-const generateReferenceStatement = (schemaGroupList: ComposedSchemaGroup[]) => {const statementList: string[] = [];for (const schemaGroup of schemaGroupList) {diff --git a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vueindex e06a959245..90cc5b9073 100644--- a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue+++ b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue@@ -87,12 +87,11 @@</div></div><MonacoEditor+ v-model:content="state.editStatement"class="w-full h-full border border-b-0"data-label="bb-schema-editor-sql-editor"- :value="state.editStatement":auto-focus="false":dialect="dialectOfEngineV1(databaseEngine)"- @change="handleStatementChange"/></div></div>@@ -154,7 +153,7 @@ import {import { Engine } from "@/types/proto/v1/common";import { DatabaseMetadata } from "@/types/proto/v1/database_service";import { TenantMode } from "@/types/proto/v1/project_service";-import MonacoEditor from "../MonacoEditor";+import { MonacoEditor } from "../MonacoEditor";import { provideSQLCheckContext } from "../SQLCheck";import {initialSchemaConfigToMetadata,@@ -265,10 +264,6 @@ const handleChangeTab = (tab: TabType) => {state.selectedTab = tab;};-const handleStatementChange = (value: string) => {- state.editStatement = value;-};-const dismissModal = () => {if (allowPreviewIssue.value) {state.showActionConfirmModal = true;@@ -518,7 +513,7 @@ const generateIssueName = (};</script>-<style>+<style lang="postcss">.schema-editor-modal-container > .modal-container {@apply w-full h-[46rem] overflow-auto grid;grid-template-rows: min-content 1fr min-content;diff --git a/frontend/src/components/AnomalyCenter/AnomalyTable.vue b/frontend/src/components/AnomalyCenter/AnomalyTable.vueindex e9e3f3eb75..dd1bbeb07c 100644--- a/frontend/src/components/AnomalyCenter/AnomalyTable.vue+++ b/frontend/src/components/AnomalyCenter/AnomalyTable.vue@@ -63,7 +63,7 @@<DiffEditorclass="flex-1 w-full border rounded-md overflow-clip":original="schemaDriftDetail.payload?.expectedSchema"- :value="schemaDriftDetail.payload?.actualSchema"+ :modified="schemaDriftDetail.payload?.actualSchema":readonly="true"/><div class="flex justify-end">@@ -80,7 +80,6 @@ import { computed, PropType, reactive } from "vue";import { useI18n } from "vue-i18n";import { useRouter } from "vue-router";import { BBTableSectionDataSource } from "@/bbkit/types";-import DiffEditor from "@/components/MonacoEditor/DiffEditor.vue";import { useDatabaseV1Store, useInstanceV1Store } from "@/store";import { useEnvironmentV1Store } from "@/store";import { UNKNOWN_ENVIRONMENT_NAME } from "@/types";@@ -95,6 +94,7 @@ import {humanizeTs,extractDatabaseResourceName,} from "@/utils";+import { DiffEditor } from "../MonacoEditor";type Action = {onClick: () => void;diff --git a/frontend/src/components/Branch/MergeBranchPanel.vue b/frontend/src/components/Branch/MergeBranchPanel.vueindex 8f38229a7f..023bbc17ee 100644--- a/frontend/src/components/Branch/MergeBranchPanel.vue+++ b/frontend/src/components/Branch/MergeBranchPanel.vue@@ -59,8 +59,8 @@:key="state.targetBranchName"class="h-full":original="targetBranch.schema"- :value="state.editingSchema"- @change="state.editingSchema = $event"+ :modified="state.editingSchema"+ @update:modified="state.editingSchema = $event"/><divv-else@@ -81,7 +81,6 @@ import { NButton, NInput, NCheckbox, useDialog } from "naive-ui";import { Status } from "nice-grpc-common";import { computed, reactive, ref, watch } from "vue";import { useI18n } from "vue-i18n";-import DiffEditor from "@/components/MonacoEditor/DiffEditor.vue";import { Drawer, DrawerContent } from "@/components/v2";import { pushNotification, useSheetV1Store } from "@/store";import { useSchemaDesignStore } from "@/store/modules/schemaDesign";@@ -95,6 +94,7 @@ import {Sheet_Type,Sheet_Visibility,} from "@/types/proto/v1/sheet_service";+import { DiffEditor } from "../MonacoEditor";interface LocalState {targetBranchName: string;diff --git a/frontend/src/components/Branch/SchemaDesignEditor.vue b/frontend/src/components/Branch/SchemaDesignEditor.vueindex 281955f2ea..b7d7ca25f2 100644--- a/frontend/src/components/Branch/SchemaDesignEditor.vue+++ b/frontend/src/components/Branch/SchemaDesignEditor.vue@@ -51,7 +51,7 @@<MonacoEditorclass="w-full h-full border rounded-lg overflow-auto"data-label="bb-schema-editor-sql-editor"- :value="rawSQLPreviewState.value"+ :content="rawSQLPreviewState.value":readonly="true":auto-focus="false"/>@@ -70,8 +70,9 @@ import {useDatabaseV1Store,useSchemaEditorV1Store,} from "@/store";+import { ComposedProject } from "@/types";import { SchemaDesign } from "@/types/proto/v1/schema_design_service";-import { ComposedProject } from "@/types/v1";+import { MonacoEditor } from "../MonacoEditor";import {mergeSchemaEditToMetadata,validateDatabaseMetadata,diff --git a/frontend/src/components/Changelist/ChangelistDetail/RawSQLEditor/RawSQLEditor.vue b/frontend/src/components/Changelist/ChangelistDetail/RawSQLEditor/RawSQLEditor.vueindex fb7ec62899..361da09382 100644--- a/frontend/src/components/Changelist/ChangelistDetail/RawSQLEditor/RawSQLEditor.vue+++ b/frontend/src/components/Changelist/ChangelistDetail/RawSQLEditor/RawSQLEditor.vue@@ -12,12 +12,11 @@:data-height="editorWrapperHeight"><MonacoEditor- ref="editorRef"- :value="statement"+ :content="statement":readonly="readonly || isSheetOversize"class="border w-full h-full"- @change="$emit('update:statement', $event)"- @ready="adjustEditorHeight"+ @update:content="$emit('update:statement', $event)"+ @ready="handleEditorReady"/></div></div>@@ -26,7 +25,11 @@<script setup lang="ts">import { useElementSize } from "@vueuse/core";import { ref, watch } from "vue";-import MonacoEditor from "@/components/MonacoEditor";+import {+ type IStandaloneCodeEditor,+ type MonacoModule,+ MonacoEditor,+} from "@/components/MonacoEditor";import UploadProgressButton from "@/components/misc/UploadProgressButton.vue";defineProps<{@@ -41,18 +44,23 @@ const emit = defineEmits<{}>();const editorWrapperRef = ref<HTMLDivElement>();-const editorRef = ref<InstanceType<typeof MonacoEditor>>();const { height: editorWrapperHeight } = useElementSize(editorWrapperRef);const handleUploadFile = async (event: Event) => {emit("upload", event);};-const adjustEditorHeight = () => {- const editor = editorRef.value;- if (!editor) return;- editor.setEditorContentHeight(editorWrapperHeight.value);+const handleEditorReady = (+ monaco: MonacoModule,+ editor: IStandaloneCodeEditor+) => {+ watch(+ editorWrapperHeight,+ () => {+ const container = editor.getContainerDomNode();+ container.style.height = `${editorWrapperHeight.value}px`;+ },+ { immediate: true }+ );};--watch(editorWrapperHeight, adjustEditorHeight);</script>diff --git a/frontend/src/components/Issue/panel/RequestExportPanel/ExportResourceForm/index.vue b/frontend/src/components/Issue/panel/RequestExportPanel/ExportResourceForm/index.vueindex 4f0cc69b95..19d2422abf 100644--- a/frontend/src/components/Issue/panel/RequestExportPanel/ExportResourceForm/index.vue+++ b/frontend/src/components/Issue/panel/RequestExportPanel/ExportResourceForm/index.vue@@ -23,12 +23,11 @@class="w-full h-[300px] border rounded"><MonacoEditor+ v-model:content="state.statement"class="w-full h-full py-2"- :value="state.statement":auto-focus="false":language="'sql'":dialect="dialect"- @change="handleStatementChange"/></div><template v-if="!props.statementOnly">@@ -50,7 +49,7 @@import { isUndefined } from "lodash-es";import { NRadioGroup, NRadio, NTooltip } from "naive-ui";import { computed, onMounted, reactive, watch } from "vue";-import MonacoEditor from "@/components/MonacoEditor/MonacoEditor.vue";+import { MonacoEditor } from "@/components/MonacoEditor";import { useDatabaseV1Store, useProjectV1Store } from "@/store";import {DatabaseResource,@@ -153,10 +152,6 @@ watch(});-const handleStatementChange = (value: string) => {- state.statement = value;-};-const handleTableResourceUpdate = (databaseResourceList: DatabaseResource[]) => {diff --git a/frontend/src/components/Issue/panel/RequestExportPanel/index.vue b/frontend/src/components/Issue/panel/RequestExportPanel/index.vueindex 21e6b6085f..c73d3644b1 100644--- a/frontend/src/components/Issue/panel/RequestExportPanel/index.vue+++ b/frontend/src/components/Issue/panel/RequestExportPanel/index.vue@@ -55,14 +55,12 @@SQL<RequiredStar /></span>- <div class="w-full h-[300px] border rounded">+ <div class="w-full h-[300px]"><MonacoEditor- class="w-full h-full py-2"- :value="state.statement"+ v-model:content="state.statement"+ class="w-full h-full rounded border":auto-focus="false"- :language="'sql'":dialect="dialect"- @change="(value: string) => (state.statement = value)"/></div></div>@@ -142,6 +140,7 @@ import { computed, onMounted, reactive } from "vue";import { useI18n } from "vue-i18n";import { useRouter } from "vue-router";import ExpirationSelector from "@/components/ExpirationSelector.vue";+import { MonacoEditor } from "@/components/MonacoEditor";import RequiredStar from "@/components/RequiredStar.vue";import {ProjectSelect,diff --git a/frontend/src/components/IssueV1/components/ActivitySection/Activity/StatementUpdate.vue b/frontend/src/components/IssueV1/components/ActivitySection/Activity/StatementUpdate.vueindex 36e38e0b13..a92594e9d6 100644--- a/frontend/src/components/IssueV1/components/ActivitySection/Activity/StatementUpdate.vue+++ b/frontend/src/components/IssueV1/components/ActivitySection/Activity/StatementUpdate.vue@@ -18,7 +18,7 @@v-if="!isPreparingOldStatement && !isPreparingNewStatement"class="w-full h-full border rounded-md overflow-clip":original="oldStatement"- :value="newStatement"+ :modified="newStatement":readonly="true"/><div@@ -36,7 +36,7 @@ import { asyncComputed } from "@vueuse/core";import { NButton } from "naive-ui";import { ref } from "vue";import { BBModal, BBSpin } from "@/bbkit";-import DiffEditor from "@/components/MonacoEditor/DiffEditor.vue";+import { DiffEditor } from "@/components/MonacoEditor";import { useSheetV1Store } from "@/store";import { UNKNOWN_ID } from "@/types";import { getSheetStatement } from "@/utils";diff --git a/frontend/src/components/IssueV1/components/GrantRequest/GrantRequestExporterForm.vue b/frontend/src/components/IssueV1/components/GrantRequest/GrantRequestExporterForm.vueindex feb21530f2..e71f1c842b 100644--- a/frontend/src/components/IssueV1/components/GrantRequest/GrantRequestExporterForm.vue+++ b/frontend/src/components/IssueV1/components/GrantRequest/GrantRequestExporterForm.vue@@ -29,11 +29,10 @@<span class="flex items-center textlabel mb-2">SQL</span><div class="w-full border rounded"><MonacoEditor- class="w-full h-[300px] py-2"- readonly- :value="state.statement"+ class="w-full h-[300px]"+ :content="state.statement":auto-focus="false"- :language="'sql'"+ :readonly="true"/></div></div>@@ -59,7 +58,7 @@<script lang="ts" setup>import dayjs from "dayjs";import { computed, onMounted, reactive, ref } from "vue";-import MonacoEditor from "@/components/MonacoEditor";+import { MonacoEditor } from "@/components/MonacoEditor";import { PresetRoleType } from "@/types";import { DatabaseResource } from "@/types";import { convertFromCELString } from "@/utils/issue/cel";diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue b/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vueindex e793565ab3..a3641823fa 100644--- a/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue+++ b/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue@@ -117,19 +117,22 @@</template></BBAttention>- <div class="whitespace-pre-wrap overflow-hidden border">+ <div class="whitespace-pre-wrap overflow-hidden"><MonacoEditor- ref="editorRef"- class="w-full h-auto max-h-[360px] min-h-[120px]"- data-label="bb-issue-sql-editor"- :value="state.statement"- :readonly="isEditorReadonly"+ class="w-full h-auto max-h-[360px] min-h-[120px] border rounded-[3px]"+ :filename="`${selectedTask.name}.sql`"+ :content="state.statement"+ :language="'sql'":auto-focus="false"- :language="language"+ :readonly="isEditorReadonly":dialect="dialect":advices="isEditorReadonly ? markers : []"- @change="handleStatementChange"- @ready="handleMonacoEditorReady"+ :auto-height="{ min: 120, max: 360 }"+ :auto-complete-context="{+ instance: database.instance,+ database: database.name,+ }"+ @update:content="handleStatementChange"/></div></div>@@ -160,7 +163,7 @@import { cloneDeep } from "lodash-es";import Long from "long";import { NButton, NTooltip, useDialog } from "naive-ui";-import { computed, h, reactive, ref, watch } from "vue";+import { computed, h, reactive, watch } from "vue";import { useI18n } from "vue-i18n";import { useRoute } from "vue-router";import { ErrorList } from "@/components/IssueV1/components/common";@@ -176,7 +179,7 @@ import {notifyNotEditableLegacyIssue,isDeploymentConfigChangeTaskV1,} from "@/components/IssueV1/logic";-import MonacoEditor from "@/components/MonacoEditor";+import { MonacoEditor } from "@/components/MonacoEditor";import DownloadSheetButton from "@/components/Sheet/DownloadSheetButton.vue";import UploadProgressButton from "@/components/misc/UploadProgressButton.vue";import { rolloutServiceClient } from "@/grpcweb";@@ -205,8 +208,6 @@ import {import { readFileAsync } from "@/utils";import { useSQLAdviceMarkers } from "../useSQLAdviceMarkers";import FormatOnSaveCheckbox from "./FormatOnSaveCheckbox.vue";-import { useAutoEditorHeight } from "./useAutoEditorHeight";-import { useEditorAutoCompletion } from "./useEditorAutoCompletion";import { EditState, useTempEditState } from "./useTempEditState";type LocalState = EditState & {@@ -229,20 +230,15 @@ const state = reactive<LocalState>({isUploadingFile: false,});-const editorRef = ref<InstanceType<typeof MonacoEditor>>();-const { updateEditorHeight } = useAutoEditorHeight(editorRef);-const { updateEditorAutoCompletionContext } =- useEditorAutoCompletion(editorRef);--const selectedDatabase = computed(() => {+const database = computed(() => {return databaseForTask(issue.value, selectedTask.value);});const language = useInstanceV1EditorLanguage(- computed(() => selectedDatabase.value.instanceEntity)+ computed(() => database.value.instanceEntity));const dialect = computed((): SQLDialect => {- const db = selectedDatabase.value;+ const db = database.value;return dialectOfEngineV1(db.instanceEntity.engine);});const statementTitle = computed(() => {@@ -541,7 +537,6 @@ const handleUploadAndOverwrite = async (event: Event) => {}resetTempEditState();- updateEditorHeight();} finally {state.isUploadingFile = false;}@@ -557,7 +552,6 @@ const handleUploadFile = async (event: Event) => {}resetTempEditState();- updateEditorHeight();} finally {state.isUploadingFile = false;}@@ -660,13 +654,6 @@ const handleStatementChange = (value: string) => {if (!sheet.value) return;setSheetStatement(sheet.value, value);}-- updateEditorHeight();-};--const handleMonacoEditorReady = () => {- updateEditorAutoCompletionContext();- updateEditorHeight();};watch(@@ -681,7 +668,6 @@ watch(isCreating, (curr, prev) => {// Reset the edit state after creating the issue.if (!curr && prev) {state.isEditing = false;- updateEditorHeight();}});</script>diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/useAutoEditorHeight.ts b/frontend/src/components/IssueV1/components/StatementSection/EditorView/useAutoEditorHeight.tsdeleted file mode 100644index 5e8c33ff9b..0000000000--- a/frontend/src/components/IssueV1/components/StatementSection/EditorView/useAutoEditorHeight.ts+++ /dev/null@@ -1,24 +0,0 @@-import { Ref } from "vue";-import MonacoEditor from "@/components/MonacoEditor";--const EDITOR_MIN_HEIGHT = 120; // ~= 6 lines, a reasonable size to start writing SQL--export const useAutoEditorHeight = (- editorRef: Ref<InstanceType<typeof MonacoEditor> | undefined>-) => {- const updateEditorHeight = () => {- requestAnimationFrame(() => {- const contentHeight =- editorRef.value?.editorInstance?.getContentHeight() as number;- let actualHeight = contentHeight;- if (actualHeight < EDITOR_MIN_HEIGHT) {- actualHeight = EDITOR_MIN_HEIGHT;- }- editorRef.value?.setEditorContentHeight(actualHeight);- });- };-- return {- updateEditorHeight,- };-};diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/useEditorAutoCompletion.ts b/frontend/src/components/IssueV1/components/StatementSection/EditorView/useEditorAutoCompletion.tsdeleted file mode 100644index 81d904424d..0000000000--- a/frontend/src/components/IssueV1/components/StatementSection/EditorView/useEditorAutoCompletion.ts+++ /dev/null@@ -1,53 +0,0 @@-import { computed, Ref, watch } from "vue";-import { databaseForTask, useIssueContext } from "@/components/IssueV1/logic";-import MonacoEditor from "@/components/MonacoEditor";-import { useDBSchemaV1Store } from "@/store";-import { ComposedDatabase, UNKNOWN_ID } from "@/types";-import { TableMetadata } from "@/types/proto/v1/database_service";--export const useEditorAutoCompletion = (- editorRef: Ref<InstanceType<typeof MonacoEditor> | undefined>-) => {- const { issue, selectedTask } = useIssueContext();- const dbSchemaStore = useDBSchemaV1Store();- const databaseList = computed(() => {- const db = databaseForTask(issue.value, selectedTask.value);- if (db.uid === String(UNKNOWN_ID)) {- return [];- }- return [db];- });-- watch(- databaseList,- (list) => {- list.forEach((db) => {- if (db.uid !== String(UNKNOWN_ID)) {- dbSchemaStore.getOrFetchDatabaseMetadata({ database: db.name });- }- });- },- { immediate: true }- );-- const tableList = computed(() => {- return databaseList.value- .map((item) => dbSchemaStore.getTableList(item.name))- .flat();- });-- const updateEditorAutoCompletionContext = async () => {- const databaseMap: Map<ComposedDatabase, TableMetadata[]> = new Map();- for (const database of databaseList.value) {- const tableList = await dbSchemaStore.getOrFetchTableList(database.name);- databaseMap.set(database, tableList);- }- editorRef.value?.setEditorAutoCompletionContextV1(databaseMap);- };-- watch([databaseList, tableList], () => {- updateEditorAutoCompletionContext();- });-- return { updateEditorAutoCompletionContext };-};diff --git a/frontend/src/components/IssueV1/components/StatementSection/SDLView/SDLView.vue b/frontend/src/components/IssueV1/components/StatementSection/SDLView/SDLView.vueindex 2a44072869..9274911400 100644--- a/frontend/src/components/IssueV1/components/StatementSection/SDLView/SDLView.vue+++ b/frontend/src/components/IssueV1/components/StatementSection/SDLView/SDLView.vue@@ -54,33 +54,34 @@<DiffEditorv-if="state.tab === 'DIFF'"- class="h-[64rem] max-h-full border rounded-md overflow-clip"+ class="border rounded-[3px] overflow-clip":original="sdlState.detail.previousSDL"- :value="sdlState.detail.prettyExpectedSDL"+ :modified="sdlState.detail.prettyExpectedSDL":readonly="true"+ :auto-height="{+ alignment: 'modified',+ min: 120,+ max: 480,+ }"/><MonacoEditorv-if="state.tab === 'STATEMENT'"- ref="editorRef"- class="w-full border h-auto max-h-[360px]"+ class="w-full h-auto border rounded-[3px] overflow-clip"data-label="bb-issue-sql-editor"- :value="sdlState.detail.diffDDL"+ :content="sdlState.detail.diffDDL":readonly="true":auto-focus="false"- language="sql"- @ready="handleMonacoEditorReady"+ :auto-height="{ min: 120, max: 360 }"/><MonacoEditorv-if="state.tab === 'SCHEMA'"- ref="editorRef"- class="w-full border h-auto max-h-[360px]"+ class="w-full h-auto border rounded-[3px] overflow-clip"data-label="bb-issue-sql-editor"- :value="sdlState.detail.expectedSDL"+ :content="sdlState.detail.expectedSDL":readonly="true":auto-focus="false"+ :auto-height="{ min: 120, max: 360 }":advices="markers"- language="sql"- @ready="handleMonacoEditorReady"/></template></div>@@ -94,10 +95,9 @@<script lang="ts" setup>import { NTabs, NTab, NTooltip } from "naive-ui";-import { reactive, ref } from "vue";+import { reactive } from "vue";import LearnMoreLink from "@/components/LearnMoreLink.vue";-import MonacoEditor from "@/components/MonacoEditor";-import DiffEditor from "@/components/MonacoEditor/DiffEditor.vue";+import { DiffEditor, MonacoEditor } from "@/components/MonacoEditor";import { hasFeature, pushNotification } from "@/store";import { useSQLAdviceMarkers } from "../useSQLAdviceMarkers";import { useSDLState } from "./useSDLState";@@ -113,20 +113,9 @@ const state = reactive<LocalState>({showFeatureModal: false,tab: "DIFF",});-const editorRef = ref<InstanceType<typeof MonacoEditor>>();const { state: sdlState, events: sdlEvents } = useSDLState();-const updateEditorHeight = () => {- const contentHeight =- editorRef.value?.editorInstance?.getContentHeight() as number;- editorRef.value?.setEditorContentHeight(contentHeight);-};--const handleMonacoEditorReady = () => {- updateEditorHeight();-};-const { markers } = useSQLAdviceMarkers();sdlEvents.on("error", ({ message }) => {diff --git a/frontend/src/components/IssueV1/components/StatementSection/SDLView/useSDLState.ts b/frontend/src/components/IssueV1/components/StatementSection/SDLView/useSDLState.tsindex f9cda0cd71..902069d8e7 100644--- a/frontend/src/components/IssueV1/components/StatementSection/SDLView/useSDLState.ts+++ b/frontend/src/components/IssueV1/components/StatementSection/SDLView/useSDLState.ts@@ -3,6 +3,7 @@ import { computed, reactive, watch } from "vue";import { sqlServiceClient } from "@/grpcweb";import { useSilentRequest } from "@/plugins/silent-request";import { useChangeHistoryStore, useDatabaseV1Store } from "@/store";+import { ChangeHistoryView } from "@/types/proto/v1/database_service";import {Task,TaskRun_Status,@@ -123,6 +124,7 @@ export const useSDLState = () => {const history = await useChangeHistoryStore().fetchChangeHistory({name: changeHistoryName,sdlFormat: true,+ view: ChangeHistoryView.CHANGE_HISTORY_VIEW_FULL,});// The latestChangeHistoryName might change during fetching the// ChangeHistory.diff --git a/frontend/src/components/IssueV1/components/StatementSection/useSQLAdviceMarkers.ts b/frontend/src/components/IssueV1/components/StatementSection/useSQLAdviceMarkers.tsindex 85167917fd..717b7ba59f 100644--- a/frontend/src/components/IssueV1/components/StatementSection/useSQLAdviceMarkers.ts+++ b/frontend/src/components/IssueV1/components/StatementSection/useSQLAdviceMarkers.ts@@ -1,6 +1,6 @@import { maxBy } from "lodash-es";import { computed } from "vue";-import { AdviceOption } from "@/components/MonacoEditor";+import type { AdviceOption } from "@/components/MonacoEditor";import {PlanCheckRun,PlanCheckRun_Result_Status,diff --git a/frontend/src/components/MonacoEditor/DiffEditor.vue b/frontend/src/components/MonacoEditor/DiffEditor.vueindex a0bcd9ddbe..4caa3f85e9 100644--- a/frontend/src/components/MonacoEditor/DiffEditor.vue+++ b/frontend/src/components/MonacoEditor/DiffEditor.vue@@ -1,5 +1,5 @@<template>- <div ref="editorContainerRef" v-bind="$attrs" class="relative">+ <div ref="containerRef" class="relative bb-monaco-diff-editor"><divv-if="!isEditorLoaded"class="absolute inset-0 flex flex-col items-center justify-center"@@ -10,7 +10,8 @@</template><script lang="ts" setup>-import type { editor as Editor } from "monaco-editor";+import type monaco from "monaco-editor";+import { v4 as uuidv4 } from "uuid";import {onMounted,ref,@@ -18,134 +19,167 @@ import {nextTick,watch,shallowRef,- PropType,onBeforeUnmount,+ computed,} from "vue";-import { Language } from "@/types";--const props = defineProps({- original: {- type: String,- default: "",- },- value: {- type: String,- default: "",- },- language: {- type: String as PropType<Language>,- default: "sql",- },- readonly: {- type: Boolean,- default: false,- },-});+import type { Language } from "@/types";+import type { AutoHeightOptions } from "./composables";+import type { MonacoModule } from "./types";++const [+ { useMonacoTextModel },+ { useAutoHeight, useOptionByKey },+ { extensionNameOfLanguage },+] = await Promise.all([+ import("./text-model"),+ import("./composables"),+ import("./utils"),+]);++export type DiffEditorAutoHeightOptions = AutoHeightOptions & {+ alignment: "original" | "modified";+};++const props = withDefaults(+ defineProps<{+ original?: string;+ modified?: string;+ language?: Language;+ readonly?: boolean;+ autoHeight?: DiffEditorAutoHeightOptions;+ }>(),+ {+ original: "",+ modified: "",+ language: "sql",+ readonly: false,+ autoHeight: undefined,+ }+);const emit = defineEmits<{- (e: "change", content: string): void;- (e: "ready"): void;+ (e: "update:modified", modified: string): void;+ (+ e: "ready",+ monaco: MonacoModule,+ editor: monaco.editor.IStandaloneDiffEditor+ ): void;}>();-const sqlCode = toRef(props, "value");-const readOnly = toRef(props, "readonly");-const editorContainerRef = ref<HTMLDivElement>();+const containerRef = ref<HTMLDivElement>();// use shallowRef to avoid deep conversion which will cause page crash.-const editorInstanceRef = shallowRef<Editor.IStandaloneDiffEditor>();+const editorRef = shallowRef<monaco.editor.IStandaloneDiffEditor>();const isEditorLoaded = ref(false);-const initEditorInstance = async () => {- const { editor: Editor } = await import("monaco-editor");- if (!editorContainerRef.value) {- // Give up creating monaco editor if the component has been unmounted- // very quickly.- console.debug("<DiffEditor> has been unmounted before useMonaco is ready");- return;- }+const useDiffModels = (+ monaco: MonacoModule,+ editor: monaco.editor.IStandaloneDiffEditor+) => {+ const language = toRef(props, "language");+ const original = useMonacoTextModel(+ computed(() => `${uuidv4()}.${extensionNameOfLanguage(props.language)}`),+ toRef(props, "original"),+ language+ );+ const modified = useMonacoTextModel(+ computed(() => `${uuidv4()}.${extensionNameOfLanguage(props.language)}`),+ toRef(props, "modified"),+ language+ );- const originalModel = Editor.createModel(props.original, props.language);- const modifiedEditor = Editor.createModel(sqlCode.value, props.language);- const editorInstance = Editor.createDiffEditor(editorContainerRef.value!, {- readOnly: readOnly.value,- // Learn more: https://github.com/microsoft/monaco-editor/issues/311- enableSplitViewResizing: false,- renderValidationDecorations: "on",- theme: "bb",- autoClosingQuotes: "always",- folding: false,- automaticLayout: true,- minimap: {- enabled: false,- },- wordWrap: "on",- fixedOverflowWidgets: true,- fontSize: 14,- lineHeight: 24,- scrollBeyondLastLine: false,- padding: {- top: 8,- bottom: 8,- },- renderLineHighlight: "none",- codeLens: false,- scrollbar: {- alwaysConsumeMouseWheel: false,+ watch(+ [original, modified],+ () => {+ if (!original.value) return;+ if (!modified.value) return;+ editor.setModel({+ original: original.value,+ modified: modified.value,+ });},- });+ {+ immediate: true,+ }+ );+};- editorInstance.setModel({- original: originalModel,- modified: modifiedEditor,- });+const useModifiedContent = (+ monaco: MonacoModule,+ editor: monaco.editor.IStandaloneDiffEditor+) => {+ const modified = ref(getModifiedContent(editor));+ const update = () => {+ modified.value = getModifiedContent(editor);+ };- // When typed something, change the text- editorInstance.onDidUpdateDiff(() => {- const value = editorInstance.getModifiedEditor().getValue();- emit("change", value);- });+ editor.onDidChangeModel(update);+ editor.onDidUpdateDiff(update);- return editorInstance;+ return modified;+};++const getModifiedContent = (editor: monaco.editor.IStandaloneDiffEditor) => {+ const model = editor.getModel();+ if (!model) return "";++ return model.modified.getValue();};onMounted(async () => {- const editorInstance = await initEditorInstance();- if (editorInstance) {- editorInstanceRef.value = editorInstance;- isEditorLoaded.value = true;-- nextTick(() => {- emit("ready");- });+ const { default: monaco, createMonacoDiffEditor } = await import("./editor");++ const container = containerRef.value;+ if (!container) {+ // Give up creating monaco editor if the component has been unmounted+ // very quickly.+ console.debug(+ "<MonacoEditor> has been unmounted before monaco-editor initialized"+ );+ return;+ }++ const editor = await createMonacoDiffEditor({ container });+ useDiffModels(monaco, editor);+ // Use "plugin" composable features+ useOptionByKey(monaco, editor, "readOnly", toRef(props, "readonly"));+ const modifiedContent = useModifiedContent(monaco, editor);+ if (props.autoHeight) {+ useAutoHeight(+ monaco,+ props.autoHeight.alignment === "original"+ ? editor.getOriginalEditor()+ : editor.getModifiedEditor(),+ containerRef,+ toRef(props, "autoHeight")+ );}++ editorRef.value = editor;+ isEditorLoaded.value = true;++ await nextTick();+ nextTick(() => {+ emit("ready", monaco, editor);+ });+ watch(modifiedContent, () => {+ emit("update:modified", modifiedContent.value);+ });});onBeforeUnmount(() => {- editorInstanceRef.value?.dispose();+ editorRef.value?.dispose();});--watch(- () => readOnly.value,- (readOnly) => {- editorInstanceRef.value?.updateOptions({- readOnly: readOnly,- });- },- {- deep: true,- immediate: true,- }-);</script>-<style>-.monaco-editor .monaco-mouse-cursor-text {+<style lang="postcss" scoped>+.bb-monaco-diff-editor :deep(.monaco-editor .monaco-mouse-cursor-text) {box-shadow: none !important;}-.monaco-editor .scroll-decoration {+.bb-monaco-diff-editor :deep(.monaco-editor .scroll-decoration) {display: none !important;}-.monaco-editor .line-numbers {+.bb-monaco-diff-editor :deep(.monaco-editor .line-numbers) {@apply pr-2;}</style>diff --git a/frontend/src/components/MonacoEditor/MonacoEditor.vue b/frontend/src/components/MonacoEditor/MonacoEditor.vueindex d73001c893..0fe71b1582 100644--- a/frontend/src/components/MonacoEditor/MonacoEditor.vue+++ b/frontend/src/components/MonacoEditor/MonacoEditor.vue@@ -1,409 +1,66 @@<template>- <div ref="editorContainerRef" v-bind="$attrs" class="relative">- <div- v-if="!isEditorLoaded"- class="absolute inset-0 flex flex-col items-center justify-center"- >- <BBSpin />- </div>- </div>+ <MonacoTextModelEditor+ class="bb-monaco-editor"+ :model="model"+ @update:content="(...args) => $emit('update:content', ...args)"+ /></template>-<script lang="ts" setup>-import type { useLanguageClient } from "@sql-lsp/client";-import type { editor as Editor } from "monaco-editor";-import {- onMounted,- ref,- toRef,- nextTick,- watch,- shallowRef,- PropType,- onBeforeUnmount,- watchEffect,-} from "vue";-import { ComposedDatabase, Language, SQLDialect } from "@/types";-import { TableMetadata } from "@/types/proto/store/database";-import { useLineDecorations } from "./lineDecorations";-import { useAdvices } from "./plugins/useAdvices";-import type { AdviceOption } from "./types";-import { MonacoHelper, useMonaco } from "./useMonaco";--const props = defineProps({- value: {- type: String,- default: "",- },- language: {- type: String as PropType<Language>,- default: "sql",- },- dialect: {- type: String as PropType<SQLDialect>,- default: "MYSQL",- },- readonly: {- type: Boolean,- default: false,- },- autoFocus: {- type: Boolean,- default: true,- },- advices: {- type: Array as PropType<AdviceOption[]>,- default: () => [],- },- options: {- type: Object as PropType<Editor.IStandaloneEditorConstructionOptions>,- default: undefined,- },-});--const emit = defineEmits<{- (e: "change", content: string): void;- (e: "change-selection", content: string): void;- (e: "save", content: string): void;- (e: "ready"): void;-}>();--const sqlCode = toRef(props, "value");-const dialect = toRef(props, "dialect");-const readOnly = toRef(props, "readonly");-const monacoInstanceRef = ref<MonacoHelper>();-const editorContainerRef = ref<HTMLDivElement>();-// use shallowRef to avoid deep conversion which will cause page crash.-const editorInstanceRef = shallowRef<Editor.IStandaloneCodeEditor>();-const languageClientRef = ref<ReturnType<typeof useLanguageClient>>();--const isEditorLoaded = ref(false);--const initEditorInstance = () => {- const { monaco, formatContent, setPositionAtEndOfLine } =- monacoInstanceRef.value!;-- const model = monaco.editor.createModel(sqlCode.value);- const editorInstance = monaco.editor.create(editorContainerRef.value!, {- model,- // Learn more: https://github.com/microsoft/monaco-editor/issues/311- renderValidationDecorations: "on",- theme: "bb",- tabSize: 2,- insertSpaces: true,- autoClosingQuotes: "always",- detectIndentation: false,- folding: false,- automaticLayout: true,- readOnly: readOnly.value,- minimap: {- enabled: false,- },- wordWrap: "on",- fixedOverflowWidgets: true,- fontSize: 14,- lineHeight: 24,- scrollBeyondLastLine: false,- padding: {- top: 8,- bottom: 8,- },- renderLineHighlight: "none",- codeLens: false,- scrollbar: {- alwaysConsumeMouseWheel: false,- },- ...props.options,- });-- const defaultSuggestOption = {- ...editorInstance.getOption(monaco.editor.EditorOption.suggest),- };-- watchEffect((onCleanup) => {- const { language } = props;-- monaco.editor.setModelLanguage(model, language);-- if (props.language === "sql") {- editorInstance.updateOptions({- suggest: defaultSuggestOption,- });-- // add `Format SQL` action into context menu- const action = editorInstance.addAction({- id: "format-sql",- label: "Format SQL",- keybindings: [- monaco.KeyMod.Alt | monaco.KeyMod.Shift | monaco.KeyCode.KeyF,- ],- contextMenuGroupId: "operation",- contextMenuOrder: 1,- run: () => {- if (readOnly.value) {- return;- }- formatContent(editorInstance, dialect.value);- nextTick(() => setPositionAtEndOfLine(editorInstance));- },- });- onCleanup(() => {- action.dispose();- });- } else {- // Disable auto-complete suggestions for javascript language (MongoDB)- editorInstance.updateOptions({- suggest: {- showConstants: false,- showFunctions: false,- showInterfaces: false,- showClasses: false,- showConstructors: false,- showColors: false,- showDeprecated: false,- showEnumMembers: false,- showEnums: false,- showEvents: false,- showFields: false,- showFiles: false,- showFolders: false,- showIcons: false,- showInlineDetails: false,- showIssues: false,- showKeywords: false,- showMethods: false,- showModules: false,- showOperators: false,- showProperties: false,- showReferences: false,- showSnippets: false,- showStatusBar: false,- showStructs: false,- showTypeParameters: false,- showUnits: false,- showUsers: false,- showValues: false,- showVariables: false,- showWords: false,- },- });-- // When the language is "javascript", we can still use Alt+Shift+F to- // format the document (the native feature of monaco-editor).- }- });-- // typed something, change the text- editorInstance.onDidChangeModelContent(() => {- const value = editorInstance.getValue();- emit("change", value);- });-- // when editor change selection, emit change-selection event with selected text- editorInstance.onDidChangeCursorSelection((e: any) => {- const selectedText = editorInstance- .getModel()- ?.getValueInRange(e.selection) as string;- emit("change-selection", selectedText);- });-- editorInstance.onDidChangeCursorPosition(async (e: any) => {- const { defineLineDecorations, disposeLineDecorations } =- await useLineDecorations(editorInstance, e.position);- // clear the old decorations- disposeLineDecorations();-- // define the new decorations- nextTick(async () => {- await defineLineDecorations();- });- });-- editorInstance.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {- const value = editorInstance.getValue();- emit("save", value);- });-- return editorInstance;-};--onMounted(async () => {- // Load monaco-editor and sql-lsp/client asynchronously.- const [monacoHelper, { useLanguageClient }] = await Promise.all([- useMonaco(),- import("@sql-lsp/client"),- ]);-- if (!editorContainerRef.value) {- // Give up creating monaco editor if the component has been unmounted- // very quickly.- console.debug(- "<MonacoEditor> has been unmounted before useMonaco is ready"- );- return;- }-- const { setPositionAtEndOfLine } = monacoHelper;- monacoInstanceRef.value = monacoHelper;-- const editorInstance = initEditorInstance();- editorInstanceRef.value = editorInstance;-- const languageClient = useLanguageClient();- languageClientRef.value = languageClient;- languageClient.start();-- // set the editor focus when the tab is selected- if (!readOnly.value && props.autoFocus) {- editorInstance.focus();- nextTick(() => setPositionAtEndOfLine(editorInstance));- }-- useAdvices(editorInstance, toRef(props, "advices"));-- isEditorLoaded.value = true;-- nextTick(() => {- emit("ready");-- watch(dialect, () => languageClient.changeDialect(dialect.value), {- immediate: true,- // Delay the flush timing to ensure it performs after the language client started.- flush: "post",- });-- watch(- () => props.options,- (opts) => {- if (opts) {- editorInstance.updateOptions(opts);- }- },- { deep: true }- );- });-});--onBeforeUnmount(() => {- editorInstanceRef.value?.dispose();- monacoInstanceRef.value?.dispose();- languageClientRef.value?.stop();-});--watch(- () => readOnly.value,- (readOnly) => {- editorInstanceRef.value?.updateOptions({- readOnly: readOnly,- });- },+<script setup lang="ts">+import { v4 as uuidv4 } from "uuid";+import { computed, toRef } from "vue";+import type { Language } from "@/types";++const [+ { default: MonacoTextModelEditor },+ { useMonacoTextModel },+ { extensionNameOfLanguage },+] = await Promise.all([+ import("./MonacoTextModelEditor.vue"),+ import("./text-model"),+ import("./utils"),+]);++const props = withDefaults(+ defineProps<{+ filename?: string;+ content: string;+ language?: Language;+ }>(),{- deep: true,- immediate: true,- }-);--const getEditorContent = () => {- return editorInstanceRef.value?.getValue();-};--const setEditorContent = (content: string) => {- if (readOnly.value) {- // workaround: setContent doesn't work in readonly mode- // we temporarily set it to false- editorInstanceRef.value?.updateOptions({- readOnly: false,- });- }-- monacoInstanceRef.value?.setContent(editorInstanceRef.value!, content);-- if (readOnly.value) {- // then set it back- editorInstanceRef.value?.updateOptions({- readOnly: true,- });- }-};--watch(- () => props.value,- (value) => {- if (value !== getEditorContent()) {- setEditorContent(value);- }+ filename: undefined,+ language: "sql",});+const emit = defineEmits<{+ (event: "update:content", content: string): void;+}>();-const getEditorContentHeight = () => {- return editorInstanceRef.value?.getContentHeight();-};--const setEditorContentHeight = (height: number) => {- editorContainerRef.value!.style.height = `${- height ?? getEditorContentHeight()- }px`;-};--const formatEditorContent = async () => {- if (readOnly.value) {- return;- }- if (props.language !== "sql") {- return;- }- await monacoInstanceRef.value?.formatContent(- editorInstanceRef.value!,- dialect.value- );- nextTick(() => {- monacoInstanceRef.value?.setPositionAtEndOfLine(editorInstanceRef.value!);- editorInstanceRef.value?.focus();- });-};+const content = computed({+ get() {+ return props.content;+ },+ set(content) {+ emit("update:content", content);+ },+});-const setEditorAutoCompletionContextV1 = (- databaseMap: Map<ComposedDatabase, TableMetadata[]>,- connectionScope: "instance" | "database" = "database"-) => {- const databases = [];- for (const [database, tableList] of databaseMap) {- databases.push({- name: database.databaseName,- tables: tableList.map((table) => ({- database: database.databaseName,- name: table.name,- columns: table.columns.map((column) => ({- name: column.name,- })),- })),- });- }- languageClientRef.value?.changeSchema({- databases: databases,- });- languageClientRef.value?.changeConnectionScope(connectionScope);-};+const filename = computed(() => {+ if (props.filename) return props.filename;-defineExpose({- editorInstance: editorInstanceRef,- formatEditorContent,- getEditorContent,- setEditorContent,- getEditorContentHeight,- setEditorContentHeight,- setEditorAutoCompletionContextV1,+ return `${uuidv4()}.${extensionNameOfLanguage(props.language)}`;});+const model = useMonacoTextModel(filename, content, toRef(props, "language"));</script>-<style>-.monaco-editor .monaco-mouse-cursor-text {+<style lang="postcss" scoped>+.bb-monaco-editor :deep(.monaco-editor .monaco-mouse-cursor-text) {box-shadow: none !important;}-.monaco-editor .scroll-decoration {+.bb-monaco-editor :deep(.monaco-editor .scroll-decoration) {display: none !important;}-.monaco-editor .line-numbers {+.bb-monaco-editor :deep(.monaco-editor .line-numbers) {@apply pr-2;}</style>diff --git a/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue b/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vuenew file mode 100644index 0000000000..cc09ebe0e7--- /dev/null+++ b/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue@@ -0,0 +1,152 @@+<template>+ <div ref="containerRef" v-bind="$attrs" class="relative">+ <div+ v-if="!ready"+ class="absolute inset-0 flex flex-col items-center justify-center"+ >+ <BBSpin />+ </div>+ </div>+</template>++<script lang="ts" setup>+import type monaco from "monaco-editor";+import {+ onMounted,+ ref,+ toRef,+ nextTick,+ shallowRef,+ onBeforeUnmount,+ watch,+ watchEffect,+} from "vue";+import { useLegacyAutoComplete } from "@/plugins/sql-lsp/client";+import type { SQLDialect } from "@/types";+import {+ type AutoCompleteContext,+ type AutoHeightOptions,+ useAdvices,+ useAutoComplete,+ useAutoHeight,+ useContent,+ useFormatContent,+ useModel,+ useOptionByKey,+ useOptions,+ useSelectedContent,+ useSuggestOptionByLanguage,+} from "./composables";+import { shouldUseNewLSP } from "./dev";+import type { AdviceOption, MonacoModule } from "./types";++const props = withDefaults(+ defineProps<{+ model?: monaco.editor.ITextModel;+ sqlDialect?: SQLDialect;+ readonly?: boolean;+ autoFocus?: boolean;+ autoHeight?: AutoHeightOptions;+ autoCompleteContext?: AutoCompleteContext;+ advices?: AdviceOption[];+ options?: monaco.editor.IStandaloneEditorConstructionOptions;+ }>(),+ {+ model: undefined,+ sqlDialect: undefined,+ readonly: false,+ autoFocus: true,+ autoHeight: undefined,+ autoCompleteContext: undefined,+ advices: () => [],+ options: undefined,+ }+);++const emit = defineEmits<{+ (e: "update:content", content: string): void;+ (e: "select-content", content: string): void;+ (+ e: "ready",+ monaco: MonacoModule,+ editor: monaco.editor.IStandaloneCodeEditor+ ): void;+}>();++const containerRef = ref<HTMLDivElement>();+// use shallowRef to avoid deep conversion which will cause page crash.+const editorRef = shallowRef<monaco.editor.IStandaloneCodeEditor>();+const ready = ref(false);++onMounted(async () => {+ const { default: monaco, createMonacoEditor } = await import("./editor");++ const container = containerRef.value;+ if (!container) {+ // Give up creating monaco editor if the component has been unmounted+ // very quickly.+ console.debug(+ "<MonacoEditor> has been unmounted before monaco-editor initialized"+ );+ return;+ }++ try {+ const editor = await createMonacoEditor({+ container,+ options: {+ readOnly: props.readonly,+ ...props.options,+ },+ });+ editorRef.value = editor;++ // Use "plugin" composable features+ useOptionByKey(monaco, editor, "readOnly", toRef(props, "readonly"));+ useOptions(monaco, editor, toRef(props, "options"));+ useModel(monaco, editor, toRef(props, "model"));+ useSuggestOptionByLanguage(monaco, editor);+ useFormatContent(monaco, editor, toRef(props, "sqlDialect"));+ const content = useContent(monaco, editor);+ const selectedContent = useSelectedContent(monaco, editor);+ useAdvices(monaco, editor, toRef(props, "advices"));+ useAutoHeight(monaco, editor, containerRef, toRef(props, "autoHeight"));+ if (shouldUseNewLSP()) {+ useAutoComplete(monaco, editor, toRef(props, "autoCompleteContext"));+ } else {+ useLegacyAutoComplete(+ monaco,+ editor,+ toRef(props, "autoCompleteContext")+ );+ }++ ready.value = true;++ await nextTick();+ emit("ready", monaco, editor);++ // set the editor focus when the tab is selected+ if (!props.readonly && props.autoFocus) {+ editor.focus();+ }++ watch(content, () => {+ emit("update:content", content.value);+ });+ watchEffect(() => {+ emit("select-content", selectedContent.value);+ });+ } catch (ex) {+ console.error("[MonacoEditor] initialize failed", ex);+ }+});++onBeforeUnmount(() => {+ editorRef.value?.dispose();+});++defineExpose({+ editorRef,+});+</script>diff --git a/frontend/src/components/MonacoEditor/WrappedDiffEditor.vue b/frontend/src/components/MonacoEditor/WrappedDiffEditor.vuenew file mode 100644index 0000000000..377bf9d53b--- /dev/null+++ b/frontend/src/components/MonacoEditor/WrappedDiffEditor.vue@@ -0,0 +1,9 @@+<template>+ <Suspense>+ <DiffEditor v-bind="($attrs as any)" />+ </Suspense>+</template>++<script setup lang="ts">+import DiffEditor from "./DiffEditor.vue";+</script>diff --git a/frontend/src/components/MonacoEditor/WrappedMonacoEditor.vue b/frontend/src/components/MonacoEditor/WrappedMonacoEditor.vuenew file mode 100644index 0000000000..a897f05782--- /dev/null+++ b/frontend/src/components/MonacoEditor/WrappedMonacoEditor.vue@@ -0,0 +1,9 @@+<template>+ <Suspense>+ <MonacoEditor v-bind="($attrs as any)" />+ </Suspense>+</template>++<script setup lang="ts">+import MonacoEditor from "./MonacoEditor.vue";+</script>diff --git a/frontend/src/components/MonacoEditor/composables/common.ts b/frontend/src/components/MonacoEditor/composables/common.tsnew file mode 100644index 0000000000..3425c300b3--- /dev/null+++ b/frontend/src/components/MonacoEditor/composables/common.ts@@ -0,0 +1,33 @@+import type monaco from "monaco-editor";+import { ref } from "vue";+import type { Language } from "@/types";+import { SupportedLanguages } from "../types";++export type EditorType =+ | monaco.editor.IStandaloneCodeEditor+ | monaco.editor.IStandaloneDiffEditor;++export const useTextModelLanguage = (+ editor: monaco.editor.IStandaloneCodeEditor+) => {+ const language = ref(normalizeLanguage(editor.getModel()?.getLanguageId()));++ editor.onDidChangeModel(() => {+ language.value = normalizeLanguage(editor.getModel()?.getLanguageId());+ });+ editor.onDidChangeModelLanguage((e) => {+ language.value = normalizeLanguage(e.newLanguage);+ });++ return language;+};++const normalizeLanguage = (lang: string | undefined) => {+ if (!lang) return undefined;+ if (+ SupportedLanguages.findIndex((definition) => definition.id === lang) >= 0+ ) {+ return lang as Language;+ }+ return undefined;+};diff --git a/frontend/src/components/MonacoEditor/composables/index.ts b/frontend/src/components/MonacoEditor/composables/index.tsnew file mode 100644index 0000000000..4ffbf9d57d--- /dev/null+++ b/frontend/src/components/MonacoEditor/composables/index.ts@@ -0,0 +1,9 @@+export * from "./useOptions";+export * from "./useModel";+export * from "./useContent";+export * from "./useSelectedContent";+export * from "./useFormatContent";+export * from "./useSuggestOptionByLanguage";+export * from "./useAdvices";+export * from "./useAutoHeight";+export * from "./useAutoComplete";diff --git a/frontend/src/components/MonacoEditor/plugins/useAdvices.ts b/frontend/src/components/MonacoEditor/composables/useAdvices.tssimilarity index 88%rename from frontend/src/components/MonacoEditor/plugins/useAdvices.tsrename to frontend/src/components/MonacoEditor/composables/useAdvices.tsindex c3853120e0..2b37bf417f 100644--- a/frontend/src/components/MonacoEditor/plugins/useAdvices.ts+++ b/frontend/src/components/MonacoEditor/composables/useAdvices.ts@@ -1,16 +1,15 @@import { maxBy } from "lodash-es";-import type { editor as Editor } from "monaco-editor";+import type monaco from "monaco-editor";import { unref, watchEffect } from "vue";import type { MaybeRef } from "@/types";-import { escapeMarkdown, callCssVariable } from "@/utils";-import type { AdviceOption } from "../types";+import { callCssVariable, escapeMarkdown } from "@/utils";+import type { AdviceOption, MonacoModule } from "../types";-export const useAdvices = async (- editor: Editor.IStandaloneCodeEditor,+export const useAdvices = (+ monaco: MonacoModule,+ editor: monaco.editor.IStandaloneCodeEditor,advices: MaybeRef<AdviceOption[]>) => {- const monaco = await import("monaco-editor");-watchEffect((onCleanup) => {const _advices = unref(advices);const maxSeverity =diff --git a/frontend/src/components/MonacoEditor/composables/useAutoComplete.ts b/frontend/src/components/MonacoEditor/composables/useAutoComplete.tsnew file mode 100644index 0000000000..52c8f84a62--- /dev/null+++ b/frontend/src/components/MonacoEditor/composables/useAutoComplete.ts@@ -0,0 +1,60 @@+import type monaco from "monaco-editor";+import { Ref, computed, watch } from "vue";+import { UNKNOWN_ID } from "@/types";+import {+ extractDatabaseResourceName,+ extractInstanceResourceName,+} from "@/utils";+import type { MonacoModule } from "../types";++export type AutoCompleteContext = {+ instance: string; // instances/{instance}+ database?: string; // instances/{instance}/databases/{database_name}+};++type SetMetadataParams = {+ instanceId: string; // instances/{instance}+ databaseName: string;+};++export const useAutoComplete = async (+ monaco: MonacoModule,+ editor: monaco.editor.IStandaloneCodeEditor,+ context: Ref<AutoCompleteContext | undefined>+) => {+ const { executeCommand, useLSPClient } = await import("../lsp-client");++ const client = useLSPClient();+ const params = computed(() => {+ const p: SetMetadataParams = {+ instanceId: "",+ databaseName: "",+ };+ const ctx = context.value;+ if (ctx) {+ const instance = extractInstanceResourceName(ctx.instance);+ if (instance && instance !== String(UNKNOWN_ID)) {+ p.instanceId = ctx.instance;+ }+ const databaseName = extractDatabaseResourceName(+ ctx.database ?? ""+ ).database;+ if (databaseName && databaseName !== String(UNKNOWN_ID)) {+ p.databaseName = databaseName;+ }+ }+ return p;+ });+ watch(+ () => JSON.stringify(params.value),+ async () => {+ const result = executeCommand(client, "setMetadata", [params.value]);+ console.debug(+ `setMetadata(${JSON.stringify(params.value)}): ${JSON.stringify(+ result+ )}`+ );+ },+ { immediate: true }+ );+};diff --git a/frontend/src/components/MonacoEditor/composables/useAutoHeight.ts b/frontend/src/components/MonacoEditor/composables/useAutoHeight.tsnew file mode 100644index 0000000000..fa5600ef01--- /dev/null+++ b/frontend/src/components/MonacoEditor/composables/useAutoHeight.ts@@ -0,0 +1,53 @@+import type monaco from "monaco-editor";+import { Ref, unref, watch } from "vue";+import type { MaybeRef } from "@/types";+import { minmax } from "@/utils";+import type { MonacoModule } from "../types";+import { useContent } from "./useContent";++export type AutoHeightOptions = {+ min?: number;+ max?: number;+ padding?: number;+};++export const useAutoHeight = (+ monaco: MonacoModule,+ editor: monaco.editor.IStandaloneCodeEditor,+ containerRef: Ref<HTMLElement | undefined>,+ opts: MaybeRef<AutoHeightOptions | undefined>+) => {+ const updateHeight = (height: number | undefined = undefined) => {+ const _opts = unref(opts);+ if (!_opts) return;++ const container = containerRef.value;+ if (!container) return;+ const { min, max, padding } = _opts;++ container.style.height = `${+ height ??+ minmax(+ editor.getContentHeight() + (padding ?? 0),+ min ?? 0,+ max ?? Number.MAX_SAFE_INTEGER+ )+ }px`;+ };++ const content = useContent(monaco, editor);++ watch(+ [content, () => unref(opts)],+ () => {+ if (unref(opts)) {+ updateHeight();+ }+ },+ {+ immediate: true,+ }+ );++ return updateHeight;+};diff --git a/frontend/src/components/MonacoEditor/composables/useContent.ts b/frontend/src/components/MonacoEditor/composables/useContent.tsnew file mode 100644index 0000000000..f01a9b7d46--- /dev/null+++ b/frontend/src/components/MonacoEditor/composables/useContent.ts@@ -0,0 +1,25 @@+import type monaco from "monaco-editor";+import { ref } from "vue";+import type { MonacoModule } from "../types";++export const useContent = (+ monaco: MonacoModule,+ editor: monaco.editor.IStandaloneCodeEditor+) => {+ const content = ref(getContent(editor));+ const update = () => {+ content.value = getContent(editor);+ };++ editor.onDidChangeModel(update);+ editor.onDidChangeModelContent(update);++ return content;+};++const getContent = (editor: monaco.editor.IStandaloneCodeEditor) => {+ const model = editor.getModel();+ if (!model) return "";++ return model.getValue();+};diff --git a/frontend/src/components/MonacoEditor/composables/useFormatContent.ts b/frontend/src/components/MonacoEditor/composables/useFormatContent.tsnew file mode 100644index 0000000000..d12cc03945--- /dev/null+++ b/frontend/src/components/MonacoEditor/composables/useFormatContent.ts@@ -0,0 +1,42 @@+import type monaco from "monaco-editor";+import { Ref, watchEffect } from "vue";+import type { SQLDialect } from "@/types";+import type { MonacoModule } from "../types";+import { formatEditorContent } from "../utils";+import { useTextModelLanguage } from "./common";++export const useFormatContent = async (+ monaco: MonacoModule,+ editor: monaco.editor.IStandaloneCodeEditor,+ dialect: Ref<SQLDialect | undefined>+) => {+ const language = useTextModelLanguage(editor);++ watchEffect((onCleanup) => {+ if (language.value === "sql") {+ // add `Format SQL` action into context menu+ const action = editor.addAction({+ id: "format-sql",+ label: "Format SQL",+ keybindings: [+ monaco.KeyMod.Alt | monaco.KeyMod.Shift | monaco.KeyCode.KeyF,+ ],+ contextMenuGroupId: "operation",+ contextMenuOrder: 1,+ run: async () => {+ const readonly = editor.getOption(+ monaco.editor.EditorOption.readOnly+ );+ if (readonly) return;+ await formatEditorContent(editor, dialect.value);+ },+ });+ onCleanup(() => {+ action.dispose();+ });+ } else {+ // When the language is "javascript", we can still use Alt+Shift+F to+ // format the document (the native feature of monaco-editor).+ }+ });+};diff --git a/frontend/src/components/MonacoEditor/composables/useModel.ts b/frontend/src/components/MonacoEditor/composables/useModel.tsnew file mode 100644index 0000000000..9ff1b288ed--- /dev/null+++ b/frontend/src/components/MonacoEditor/composables/useModel.ts@@ -0,0 +1,37 @@+import type monaco from "monaco-editor";+import { Ref, watch } from "vue";+import type { MonacoModule } from "../types";++// Store ViewState (e.g., selection and scroll position) for each TextModel+export const ViewStateMapByUri = new Map<+ string,+ monaco.editor.ICodeEditorViewState | null+>();++export const useModel = (+ monaco: MonacoModule,+ editor: monaco.editor.IStandaloneCodeEditor,+ model: Ref<monaco.editor.ITextModel | undefined>+) => {+ watch(+ model,+ (newModel, oldModel) => {+ if (oldModel) {+ // Save ViewState for oldModel+ const uri = oldModel.uri.toString();+ const vs = editor.saveViewState();+ ViewStateMapByUri.set(uri, vs);+ }++ editor.setModel(newModel ?? null);++ if (newModel) {+ // Restore ViewState for newModel+ const uri = newModel.uri.toString();+ const vs = ViewStateMapByUri.get(uri);+ editor.restoreViewState(vs ?? null);+ }+ },+ { immediate: true }+ );+};diff --git a/frontend/src/components/MonacoEditor/composables/useOptions.ts b/frontend/src/components/MonacoEditor/composables/useOptions.tsnew file mode 100644index 0000000000..51218100a8--- /dev/null+++ b/frontend/src/components/MonacoEditor/composables/useOptions.ts@@ -0,0 +1,42 @@+import type monaco from "monaco-editor";+import { Ref, unref, watch, watchEffect } from "vue";+import type { MaybeRef } from "@/types";+import type { MonacoModule } from "../types";+import { EditorType } from "./common";++type OptionsType<E> = E extends monaco.editor.IStandaloneCodeEditor+ ? monaco.editor.IEditorOptions+ : E extends monaco.editor.IStandaloneDiffEditor+ ? monaco.editor.IDiffEditorOptions+ : never;++export const useOptions = <E extends EditorType>(+ monaco: MonacoModule,+ editor: E,+ options: Ref<OptionsType<E> | undefined>+) => {+ watch(+ options,+ (opts) => {+ if (!opts) return;+ editor.updateOptions(opts);+ },+ { deep: true, immediate: true }+ );+};++export const useOptionByKey = <+ E extends EditorType,+ K extends keyof OptionsType<E>+>(+ monaco: MonacoModule,+ editor: E,+ key: K,+ value: MaybeRef<OptionsType<E>[K] | undefined>+) => {+ watchEffect(() => {+ editor.updateOptions({+ [key]: unref(value),+ });+ });+};diff --git a/frontend/src/components/MonacoEditor/composables/useSelectedContent.ts b/frontend/src/components/MonacoEditor/composables/useSelectedContent.tsnew file mode 100644index 0000000000..ff5713e361--- /dev/null+++ b/frontend/src/components/MonacoEditor/composables/useSelectedContent.ts@@ -0,0 +1,28 @@+import type monaco from "monaco-editor";+import { ref } from "vue";+import type { MonacoModule } from "../types";++export const useSelectedContent = (+ monaco: MonacoModule,+ editor: monaco.editor.IStandaloneCodeEditor+) => {+ const selectedContent = ref(getSelectedContent(editor));+ const update = () => {+ selectedContent.value = getSelectedContent(editor);+ };++ editor.onDidChangeCursorSelection(update);+ editor.onDidChangeModel(update);+ editor.onDidChangeModelContent(update);++ return selectedContent;+};++const getSelectedContent = (editor: monaco.editor.IStandaloneCodeEditor) => {+ const model = editor.getModel();+ if (!model) return "";+ const selection = editor.getSelection();+ if (!selection) return "";++ return model.getValueInRange(selection);+};diff --git a/frontend/src/components/MonacoEditor/composables/useSuggestOptionByLanguage.ts b/frontend/src/components/MonacoEditor/composables/useSuggestOptionByLanguage.tsnew file mode 100644index 0000000000..26c2979c08--- /dev/null+++ b/frontend/src/components/MonacoEditor/composables/useSuggestOptionByLanguage.ts@@ -0,0 +1,37 @@+import type monaco from "monaco-editor";+import { watchEffect } from "vue";+import type { MonacoModule } from "../types";+import { useTextModelLanguage } from "./common";++export const useSuggestOptionByLanguage = (+ monaco: MonacoModule,+ editor: monaco.editor.IStandaloneCodeEditor+) => {+ const language = useTextModelLanguage(editor);++ const defaultSuggestOption = {+ ...editor.getOption(monaco.editor.EditorOption.suggest),+ };++ watchEffect(() => {+ if (language.value === "javascript") {+ // Disable default auto-complete suggestions for javascript (MongoDB)+ editor.updateOptions({+ suggest: overrideAllFields(defaultSuggestOption, false),+ });+ } else {+ // Enable built-in auto-complete suggestions otherwise+ editor.updateOptions({+ suggest: defaultSuggestOption,+ });+ }+ });+};++const overrideAllFields = (obj: any, value: any) => {+ const updated: any = { ...obj };+ for (const key in updated) {+ updated[key] = value;+ }+ return updated;+};diff --git a/frontend/src/components/MonacoEditor/dev.ts b/frontend/src/components/MonacoEditor/dev.tsnew file mode 100644index 0000000000..2bac150433--- /dev/null+++ b/frontend/src/components/MonacoEditor/dev.ts@@ -0,0 +1,60 @@+import { useLocalStorage } from "@vueuse/core";+import { defineComponent, h } from "vue";+import { BBSwitch } from "@/bbkit";+import { isDev } from "@/utils";++export const SupportedLSPTypes = ["OLD", "NEW"] as const;+export type LSPType = typeof SupportedLSPTypes[number];++export const StoredLSPType = useLocalStorage<LSPType>(+ "bb.sql-editor.dev-lsp-type",+ "OLD",+ {+ serializer: {+ read(raw: LSPType) {+ if (!SupportedLSPTypes.includes(raw)) return "OLD";+ return raw;+ },+ write(value) {+ return value;+ },+ },+ }+);++export const shouldUseNewLSP = () => {+ return isDev() && StoredLSPType.value === "NEW";+};++export const LSPTypeSwitch = defineComponent({+ name: "LSPTypeSwitch",+ render() {+ const label = h("span", {}, "[DEV] LSP Type");+ const switcher = h(+ BBSwitch,+ {+ text: true,+ value: StoredLSPType.value === "NEW",+ onToggle(on: boolean) {+ StoredLSPType.value = on ? "NEW" : "OLD";+ location.reload();+ },+ },+ {+ on: () => h("span", { class: "font-medium scale-x-75" }, "NEW"),+ off: () => h("span", { class: "font-medium scale-x-75" }, "OLD"),+ }+ );+ return h(+ "div",+ {+ class: "flex flex-row items-center gap-x-2 justify-between",+ onClick: (e: MouseEvent) => {+ e.stopPropagation();+ e.preventDefault();+ },+ },+ [label, switcher]+ );+ },+});diff --git a/frontend/src/components/MonacoEditor/editor.ts b/frontend/src/components/MonacoEditor/editor.tsnew file mode 100644index 0000000000..054251a1f7--- /dev/null+++ b/frontend/src/components/MonacoEditor/editor.ts@@ -0,0 +1,150 @@+import { buildWorkerDefinition } from "monaco-editor-workers";+import "monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution.js";+import "monaco-editor/esm/vs/basic-languages/redis/redis.contribution.js";+import "monaco-editor/esm/vs/basic-languages/sql/sql.contribution.js";+import "monaco-editor/esm/vs/basic-languages/typescript/typescript.contribution.js";+import "monaco-editor/esm/vs/editor/editor.all.js";+import * as monaco from "monaco-editor/esm/vs/editor/editor.api.js";+import "monaco-editor/esm/vs/editor/standalone/browser/standaloneCodeEditorService";+import "monaco-editor/esm/vs/language/typescript/monaco.contribution.js";+import { defer } from "@/utils";+import { shouldUseNewLSP } from "./dev";+import { initializeMonacoServices } from "./services";+import { getBBTheme } from "./themes/bb";+import { getBBDarkTheme } from "./themes/bb-dark";+import type { MonacoModule } from "./types";++export default monaco as MonacoModule;++const state = {+ themeInitialized: false,+};++buildWorkerDefinition(+ new URL("@public/monaco-workers", import.meta.url).href,+ import.meta.url,+ true+);++const MonacoEditorReadyDefer = defer<void>();++export const MonacoEditorReady = MonacoEditorReadyDefer.promise;++const initializeTheme = () => {+ if (state.themeInitialized) return;++ monaco.editor.defineTheme("bb", getBBTheme());+ monaco.editor.defineTheme("bb-dark", getBBDarkTheme());++ state.themeInitialized = true;+};++const initialize = async () => {+ await initializeMonacoServices();+ if (shouldUseNewLSP()) {+ const { initializeLSPClient } = await import("./lsp-client");+ await initializeLSPClient();+ } else {+ const { useLanguageClient } = await import("@/plugins/sql-lsp/client");+ const { start } = useLanguageClient();+ start();+ }++ initializeTheme();+};++export const createMonacoEditor = async (config: {+ container: HTMLElement;+ options?: monaco.editor.IStandaloneEditorConstructionOptions;+}): Promise<monaco.editor.IStandaloneCodeEditor> => {+ await initialize();++ // create monaco editor+ const editor = monaco.editor.create(config.container, {+ ...defaultEditorOptions(),+ ...config.options,+ });++ MonacoEditorReadyDefer.resolve(undefined);++ return editor;+};++export const createMonacoDiffEditor = async (config: {+ container: HTMLElement;+ options?: monaco.editor.IStandaloneDiffEditorConstructionOptions;+}): Promise<monaco.editor.IStandaloneDiffEditor> => {+ await initialize();++ // create monaco editor+ const editor = monaco.editor.createDiffEditor(config.container, {+ ...defaultDiffEditorOptions(),+ ...config.options,+ });++ MonacoEditorReadyDefer.resolve();++ return editor;+};++export const defaultEditorOptions =+ (): monaco.editor.IStandaloneEditorConstructionOptions => {+ return {+ // Learn more: https://github.com/microsoft/monaco-editor/issues/311+ renderValidationDecorations: "on",+ theme: "bb",+ tabSize: 2,+ insertSpaces: true,+ autoClosingQuotes: "always",+ detectIndentation: false,+ folding: false,+ automaticLayout: true,+ minimap: {+ enabled: false,+ },+ wordWrap: "on",+ fixedOverflowWidgets: true,+ fontSize: 14,+ lineHeight: 24,+ scrollBeyondLastLine: false,+ padding: {+ top: 8,+ bottom: 8,+ },+ renderLineHighlight: "none",+ codeLens: false,+ scrollbar: {+ alwaysConsumeMouseWheel: false,+ },+ };+ };++export const defaultDiffEditorOptions =+ (): monaco.editor.IStandaloneDiffEditorConstructionOptions => {+ return {+ // Learn more: https://github.com/microsoft/monaco-editor/issues/311+ enableSplitViewResizing: false,+ renderValidationDecorations: "on",+ theme: "bb",+ autoClosingQuotes: "always",+ folding: false,+ automaticLayout: true,+ minimap: {+ enabled: false,+ },+ wordWrap: "on",+ fixedOverflowWidgets: true,+ fontSize: 14,+ lineHeight: 24,+ scrollBeyondLastLine: false,+ padding: {+ top: 8,+ bottom: 8,+ },+ renderLineHighlight: "none",+ codeLens: false,+ scrollbar: {+ alwaysConsumeMouseWheel: false,+ },+ };+ };diff --git a/frontend/src/components/MonacoEditor/index.ts b/frontend/src/components/MonacoEditor/index.tsindex 5d1c4e88bb..625547734e 100644--- a/frontend/src/components/MonacoEditor/index.ts+++ b/frontend/src/components/MonacoEditor/index.ts@@ -1,7 +1,6 @@-import MonacoEditor from "./MonacoEditor.vue";+import WrappedDiffEditor from "./WrappedDiffEditor.vue";+import WrappedMonacoEditor from "./WrappedMonacoEditor.vue";export * from "./types";-export { MonacoEditor };--export default MonacoEditor;+export { WrappedMonacoEditor as MonacoEditor, WrappedDiffEditor as DiffEditor };diff --git a/frontend/src/components/MonacoEditor/lineDecorations.ts b/frontend/src/components/MonacoEditor/lineDecorations.tsdeleted file mode 100644index b86116af03..0000000000--- a/frontend/src/components/MonacoEditor/lineDecorations.ts+++ /dev/null@@ -1,117 +0,0 @@-import type * as monaco from "monaco-editor";-import { ref } from "vue";--const DELIMITER = ";";--type FragmentRange = {- startLineNumber: number;- startColumn: number;- endLineNumber: number;- endColumn: number;-};--/**- * Get the ranges of SQL fragments split by the delimiter- * @param editor monaco.editor.IStandaloneCodeEditor- * @returns fragmentRangeList FragmentRange[]- */-const getSQLFragmentRangeList = async (- editor: monaco.editor.IStandaloneCodeEditor-): Promise<FragmentRange[]> => {- const monaco = await import("monaco-editor");- const model = editor.getModel() as monaco.editor.ITextModel;- const linesContent = model.getLinesContent();- const sqlFragmentRangeList: FragmentRange[] = [];- let startLineNumber = 0;-- for (let i = 0; i < linesContent.length; i++) {- const content = linesContent[i];- const range: FragmentRange = new monaco.Range(0, 0, 0, 0);-- const idx = content.indexOf(DELIMITER);- // whether the content of line is a empty content- const isEmptyContent = monaco.Range.isEmpty(- new monaco.Range(i, 0, i, content.length)- );-- // first non-empty line- if (!isEmptyContent && startLineNumber === 0) {- startLineNumber = i + 1;- }-- // which contains the delimiter- if (idx !== -1) {- range.startLineNumber = startLineNumber;- // startColumn is always first character of line- range.startColumn = 1;- // endLineNumber is the line number contains the delimiter- range.endLineNumber = i + 1;- // keep the last character of the line in the range- range.endColumn = idx + 2;-- // jump to the next line of end line- startLineNumber = range.endLineNumber + 1;-- sqlFragmentRangeList.push(- new monaco.Range(- range.startLineNumber,- range.startColumn,- range.endLineNumber,- range.endColumn- )- );- }-- // continue count the empty content- if (isEmptyContent && startLineNumber > 0) {- startLineNumber += 1;- }- }- return sqlFragmentRangeList;-};--const lineDecorations = ref<string[]>([]);--const useLineDecorations = async (- editor: monaco.editor.IStandaloneCodeEditor,- position: monaco.Position-) => {- const monaco = await import("monaco-editor");- const defineLineDecorations = async () => {- const newDecorations: monaco.editor.IModelDeltaDecoration[] = [];-- const sqlFragmentRangeList = await getSQLFragmentRangeList(editor);-- sqlFragmentRangeList.forEach((range) => {- // if the current position in the range, then highlight the range- if (monaco.Range.containsPosition(range, position)) {- newDecorations.push({- range: range,- options: {- isWholeLine: true,- linesDecorationsClassName: "sql-fragment",- },- });- }- });-- lineDecorations.value = editor.deltaDecorations([], newDecorations);-- return lineDecorations;- };-- const disposeLineDecorations = () => {- if (lineDecorations.value && lineDecorations.value.length > 0) {- editor.deltaDecorations(lineDecorations.value, []);- lineDecorations.value = [];- }- };-- return {- lineDecorations,- defineLineDecorations,- disposeLineDecorations,- };-};--export { useLineDecorations, getSQLFragmentRangeList };diff --git a/frontend/src/components/MonacoEditor/lsp-client.ts b/frontend/src/components/MonacoEditor/lsp-client.tsnew file mode 100644index 0000000000..3cc5ca88ab--- /dev/null+++ b/frontend/src/components/MonacoEditor/lsp-client.ts@@ -0,0 +1,131 @@+import { MonacoLanguageClient } from "monaco-languageclient";+import {+ CloseAction,+ ErrorAction,+ ExecuteCommandParams,+ MessageTransports,+} from "vscode-languageclient";+import {+ WebSocketMessageReader,+ WebSocketMessageWriter,+ toSocket,+} from "vscode-ws-jsonrpc";++export const createLanguageClient = (+ transports: MessageTransports+): MonacoLanguageClient => {+ return new MonacoLanguageClient({+ name: "Bytebase Language Client",+ clientOptions: {+ // use a language id as a document selector+ documentSelector: ["sql"],+ // disable the default error handler+ errorHandler: {+ error: () => ({ action: ErrorAction.Continue }),+ closed: () => ({ action: CloseAction.Restart }),+ },+ },+ // create a language client connection from the JSON RPC connection on demand+ connectionProvider: {+ get: () => {+ return Promise.resolve(transports);+ },+ },+ });+};++export const createUrl = (+ hostname: string,+ port: number,+ path: string,+ searchParams: Record<string, any> = {},+ secure: boolean = location.protocol === "https:"+): string => {+ const protocol = secure ? "wss" : "ws";+ const url = new URL(`${protocol}://${hostname}:${port}${path}`);++ for (const [key, value] of Object.entries(searchParams)) {+ const v = value instanceof Array ? value.join(",") : value;+ if (v) {+ url.searchParams.set(key, v);+ }+ }++ return url.toString();+};++export const createWebSocketAndStartClient = (+ url: string+): {+ webSocket: WebSocket;+ languageClient: Promise<MonacoLanguageClient>;+} => {+ const webSocket = new WebSocket(url);+ const languageClient = new Promise<MonacoLanguageClient>((resolve) => {+ webSocket.onopen = () => {+ const socket = toSocket(webSocket);+ const reader = new WebSocketMessageReader(socket);+ const writer = new WebSocketMessageWriter(socket);+ const languageClient = createLanguageClient({+ reader,+ writer,+ });+ languageClient.start();+ reader.onClose(() => languageClient.stop());+ resolve(languageClient);+ };+ });++ return {+ webSocket,+ languageClient,+ };+};++const state = {+ client: undefined as MonacoLanguageClient | undefined,+ clientInitialized: undefined as Promise<MonacoLanguageClient> | undefined,+};++const initializeRunner = async () => {+ const url = createUrl(location.hostname, parseInt(location.port, 10), "/lsp");+ const client = await createWebSocketAndStartClient(url).languageClient;+ state.client = client;+ return client;+};++export const initializeLSPClient = () => {+ if (state.clientInitialized) {+ return state.clientInitialized;+ }++ const job = initializeRunner();+ state.clientInitialized = job;+ return job;+};++export const useLSPClient = () => {+ const { client } = state;+ if (!client) {+ throw new Error(+ "Unexpected `useLSPClient` call before lsp client initialized"+ );+ }+ return client;+};++export const executeCommand = async (+ client: MonacoLanguageClient,+ command: string,+ args: any[] | undefined+) => {+ const executeCommandParams: ExecuteCommandParams = {+ command,+ arguments: args,+ };+ const result = await client.sendRequest(+ "workspace/executeCommand",+ executeCommandParams+ );+ return result;+};diff --git a/frontend/src/components/MonacoEditor/services.ts b/frontend/src/components/MonacoEditor/services.tsnew file mode 100644index 0000000000..d2b9883dca--- /dev/null+++ b/frontend/src/components/MonacoEditor/services.ts@@ -0,0 +1,25 @@+import { languages } from "monaco-editor";+import { initialize as initializeExtensions } from "vscode/extensions";+import { initialize as initializeServices } from "vscode/services";+import { SupportedLanguages } from "./types";++const state = {+ servicesInitialized: undefined as Promise<void> | undefined,+};++const initializeRunner = async () => {+ await initializeServices({});+ await initializeExtensions();++ SupportedLanguages.forEach((lang) => languages.register(lang));+};++export const initializeMonacoServices = async () => {+ if (state.servicesInitialized) {+ return state.servicesInitialized;+ }++ const job = initializeRunner();+ state.servicesInitialized = job;+ return job;+};diff --git a/frontend/src/components/MonacoEditor/sqlFormatter.ts b/frontend/src/components/MonacoEditor/sqlFormatter.tsindex 2d86758eca..5e6164f704 100644--- a/frontend/src/components/MonacoEditor/sqlFormatter.ts+++ b/frontend/src/components/MonacoEditor/sqlFormatter.ts@@ -1,6 +1,5 @@-// import { format, FormatOptionsWithLanguage } from "sql-formatter";import type { FormatOptionsWithLanguage } from "sql-formatter";-import { SQLDialect } from "../../types";+import type { SQLDialect } from "../../types";type FormatResult = {data: string;@@ -10,7 +9,7 @@ type FormatResult = {type FormatterLanguage = FormatOptionsWithLanguage["language"];const convertDialectToFormatterLanguage = (- dialect: SQLDialect+ dialect: SQLDialect | undefined): FormatterLanguage => {if (dialect === "MYSQL" || dialect === "TIDB" || dialect === "OCEANBASE")return "mysql";@@ -21,10 +20,9 @@ const convertDialectToFormatterLanguage = (const formatSQL = async (sql: string,- dialect: SQLDialect+ dialect: SQLDialect | undefined): Promise<FormatResult> => {const { format } = await import("sql-formatter");-const options: Partial<FormatOptionsWithLanguage> = {language: convertDialectToFormatterLanguage(dialect),};diff --git a/frontend/src/components/MonacoEditor/text-model.ts b/frontend/src/components/MonacoEditor/text-model.tsnew file mode 100644index 0000000000..240e27d355--- /dev/null+++ b/frontend/src/components/MonacoEditor/text-model.ts@@ -0,0 +1,68 @@+import { Uri, editor } from "monaco-editor";+import { isRef, markRaw, ref, shallowRef, unref, watch } from "vue";+import { Language, MaybeRef } from "@/types";+import { MonacoEditorReady } from "./editor";++const ready = ref(false);++MonacoEditorReady.then(() => (ready.value = true));++// Store TextModel uniq by filename+const TextModelMapByFilename = new Map<string, editor.ITextModel>();++export const createTextModel = (+ filename: string,+ content: string,+ language: string+) => {+ if (TextModelMapByFilename.has(filename)) {+ return TextModelMapByFilename.get(filename)!;+ }++ const uri = Uri.parse(`/workspace/${filename}`);+ const model = editor.createModel(content, language, uri);+ TextModelMapByFilename.set(filename, model);+ return model;+};++export const useMonacoTextModel = (+ filename: MaybeRef<string>,+ content: MaybeRef<string>,+ language: MaybeRef<Language>,+ sync: boolean = true+) => {+ const model = shallowRef<editor.ITextModel>();++ watch(+ [ready, () => unref(filename), () => unref(language)],+ ([ready, filename, language]) => {+ if (!ready) return;+ const m = markRaw(createTextModel(filename, unref(content), language));++ if (sync && isRef(content)) {+ m.onDidChangeContent((e) => {+ const c = m.getValue();+ if (c !== content.value) {+ // Write-back edited content to content ref+ content.value = c;+ }+ });+ }++ model.value = m;+ },+ { immediate: true }+ );++ watch(+ [model, () => unref(content)],+ ([model, content]) => {+ if (!model) return;+ if (model.getValue() === content) return;+ model.setValue(content);+ },+ { immediate: true }+ );++ return model;+};diff --git a/frontend/src/components/MonacoEditor/themes/bb.ts b/frontend/src/components/MonacoEditor/themes/bb.tsindex a862459dc9..e9ac9dbc3f 100644--- a/frontend/src/components/MonacoEditor/themes/bb.ts+++ b/frontend/src/components/MonacoEditor/themes/bb.ts@@ -6,6 +6,7 @@ export const getBBTheme = (): Editor.IStandaloneThemeData => ({inherit: true,rules: [],colors: {+ "editor.background": "#fffffe00","editorCursor.foreground": callCssVariable("--color-accent"),"editorLineNumber.foreground": callCssVariable("--color-control-placeholder"diff --git a/frontend/src/components/MonacoEditor/types.ts b/frontend/src/components/MonacoEditor/types.tsindex 0370b9c850..b2af79d0d7 100644--- a/frontend/src/components/MonacoEditor/types.ts+++ b/frontend/src/components/MonacoEditor/types.ts@@ -1,3 +1,10 @@+import type * as monaco from "monaco-editor/esm/vs/editor/editor.api.js";++export type MonacoModule = typeof monaco;++export type IStandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;+export type IStandaloneDiffEditor = monaco.editor.IStandaloneDiffEditor;+export type AdviceOption = {severity: "ERROR" | "WARNING";message: string;@@ -7,3 +14,24 @@ export type AdviceOption = {endLineNumber: number; // starts from 1endColumn: number; // starts from 1};++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"],+ },+];diff --git a/frontend/src/components/MonacoEditor/useMonaco.ts b/frontend/src/components/MonacoEditor/useMonaco.tsdeleted file mode 100644index a90cc78aa0..0000000000--- a/frontend/src/components/MonacoEditor/useMonaco.ts+++ /dev/null@@ -1,99 +0,0 @@-import type { editor as Editor } from "monaco-editor";-import { SQLDialect } from "@/types";-import { ExtractPromiseType } from "@/utils";-import sqlFormatter from "./sqlFormatter";-import { getBBTheme } from "./themes/bb";-import { getBBDarkTheme } from "./themes/bb-dark";--export const useMonaco = async () => {- const [monaco, { default: EditorWorker }, { default: TSWorker }] =- await Promise.all([- import("monaco-editor"),- import("monaco-editor/esm/vs/editor/editor.worker?worker"),- import("monaco-editor/esm/vs/language/typescript/ts.worker?worker"),- ]);-- const bbTheme = getBBTheme();- const bbDarkTheme = getBBDarkTheme();- monaco.editor.defineTheme("bb", bbTheme);- monaco.editor.defineTheme("bb-dark", bbDarkTheme);-- self.MonacoEnvironment = {- getWorker: (workerId, label) => {- console.debug("MonacoEnvironment.getWorker", workerId, label);- if (label === "javascript") {- return new TSWorker();- }- return new EditorWorker();- },- };-- const dispose = () => {- // Nothing todo- };-- /**- * set new content in monaco editor- * use executeEdits API can preserve undo stack, allow user to undo/redo- * @param editorInstance Editor.IStandaloneCodeEditor- * @param content string- */- const setContent = (- editorInstance: Editor.IStandaloneCodeEditor,- content: string- ) => {- const range = editorInstance.getModel()?.getFullModelRange();- // get the current endLineNumber, or use 100000 as the default- const endLineNumber =- range && range?.endLineNumber > 0 ? range.endLineNumber + 1 : 100000;- editorInstance.executeEdits("delete-content", [- {- range: new monaco.Range(1, 1, endLineNumber, 1),- text: "",- forceMoveMarkers: true,- },- ]);- // set the new content- editorInstance.executeEdits("insert-content", [- {- range: new monaco.Range(1, 1, 1, 1),- text: content,- forceMoveMarkers: true,- },- ]);- };-- const formatContent = async (- editorInstance: Editor.IStandaloneCodeEditor,- dialect: SQLDialect- ) => {- const sql = editorInstance.getValue();- const { data, error } = await sqlFormatter(sql, dialect);- if (error) {- return;- }- setContent(editorInstance, data);- };-- const setPositionAtEndOfLine = (- editorInstance: Editor.IStandaloneCodeEditor- ) => {- const range = editorInstance.getModel()?.getFullModelRange();- if (range) {- editorInstance.setPosition({- lineNumber: range?.endLineNumber,- column: range?.endColumn,- });- }- };-- return {- dispose,- monaco,- setContent,- formatContent,- setPositionAtEndOfLine,- };-};--export type MonacoHelper = ExtractPromiseType<ReturnType<typeof useMonaco>>;diff --git a/frontend/src/components/MonacoEditor/utils.ts b/frontend/src/components/MonacoEditor/utils.tsnew file mode 100644index 0000000000..795b1473a4--- /dev/null+++ b/frontend/src/components/MonacoEditor/utils.ts@@ -0,0 +1,72 @@+import { Range } from "monaco-editor";+import { isRef, unref, watch } from "vue";+import type { Language, MaybeRef, SQLDialect } from "@/types";+import sqlFormatter from "./sqlFormatter";+import type { IStandaloneCodeEditor } from "./types";++export const extensionNameOfLanguage = (lang: Language) => {+ switch (lang) {+ case "sql":+ return "sql";+ case "javascript":+ return "js";+ case "redis":+ return "redis";+ }+ // A simple fallback+ return "txt";+};++export const useEditorContextKey = <+ T extends string | number | boolean | null | undefined+>(+ editor: IStandaloneCodeEditor,+ key: string,+ valueOrRef: MaybeRef<T>+) => {+ const contextKey = editor.createContextKey<T>(key, unref(valueOrRef));+ if (isRef(valueOrRef)) {+ watch(valueOrRef, (value) => contextKey?.set(value));+ }+ return contextKey;+};++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 sqlFormatter(sql, dialect);+ if (error) {+ return;+ }+ const pos = editor.getPosition();++ trySetContentWithUndo(editor, data, "Format content");++ if (pos) {+ // Not that smart but best efforts to keep the cursor position+ editor.setPosition(pos);+ }+};diff --git a/frontend/src/components/SyncDatabaseSchema/DiffViewPanel.vue b/frontend/src/components/SyncDatabaseSchema/DiffViewPanel.vueindex e792ab7124..4ecda9b1c5 100644--- a/frontend/src/components/SyncDatabaseSchema/DiffViewPanel.vue+++ b/frontend/src/components/SyncDatabaseSchema/DiffViewPanel.vue@@ -21,7 +21,7 @@<DiffEditorclass="h-full":original="targetDatabaseSchema"- :value="sourceDatabaseSchema"+ :modified="sourceDatabaseSchema":readonly="true"/></div>@@ -52,13 +52,11 @@</div></div><MonacoEditor- ref="editorRef"class="w-full flex-1 border"- :value="statement"+ :content="statement":auto-focus="false":dialect="dialectOfEngineV1(engine)"- @change="onStatementChange"- @ready="updateEditorHeight"+ @update:content="$emit('statement-change', $event)"/></template></div>@@ -68,8 +66,7 @@<script lang="ts" setup>import { NTabs, NTab } from "naive-ui";import { ref } from "vue";-import DiffEditor from "@/components/MonacoEditor/DiffEditor.vue";-import MonacoEditor from "@/components/MonacoEditor/MonacoEditor.vue";+import { DiffEditor, MonacoEditor } from "@/components/MonacoEditor";import { dialectOfEngineV1 } from "@/types";import { Engine } from "@/types/proto/v1/common";@@ -82,27 +79,12 @@ defineProps<{previewSchemaChangeMessage: string;}>();-const $emit = defineEmits<{+defineEmits<{(event: "statement-change", statement: string): void;(event: "copy-statement"): void;}>();const tab = ref<"diff" | "ddl">("diff");-const editorRef = ref<InstanceType<typeof MonacoEditor>>();--const updateEditorHeight = () => {- const contentHeight =- editorRef.value?.editorInstance?.getContentHeight() as number;- const actualHeight = contentHeight;- editorRef.value?.setEditorContentHeight(actualHeight);-};--const onStatementChange = (statement: string) => {- $emit("statement-change", statement);- requestAnimationFrame(() => {- updateEditorHeight();- });-};</script><style lang="postcss">diff --git a/frontend/src/components/SyncDatabaseSchema/RawSQLEditor.vue b/frontend/src/components/SyncDatabaseSchema/RawSQLEditor.vueindex adc0d6b90b..f11839b728 100644--- a/frontend/src/components/SyncDatabaseSchema/RawSQLEditor.vue+++ b/frontend/src/components/SyncDatabaseSchema/RawSQLEditor.vue@@ -63,12 +63,11 @@<div class="mt-4 w-full h-96 overflow-hidden"><MonacoEditorclass="w-full h-full border"- :value="state.editStatement"+ :content="state.editStatement":auto-focus="true"- :language="'sql'":readonly="viewMode":dialect="dialectOfEngineV1(state.engine)"- @change="handleStatementChange"+ @update:content="handleStatementChange"/></div></div>@@ -80,7 +79,7 @@ import Long from "long";import { NSelect } from "naive-ui";import { computed, onMounted, nextTick, reactive } from "vue";import { useI18n } from "vue-i18n";-import MonacoEditor from "@/components/MonacoEditor";+import { MonacoEditor } from "@/components/MonacoEditor";import DownloadSheetButton from "@/components/Sheet/DownloadSheetButton.vue";import { ProjectSelect } from "@/components/v2";import { useNotificationStore, useSheetV1Store } from "@/store";diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.tsindex 0d3c484e20..a36ba39326 100644--- a/frontend/src/composables/useExecuteSQL.ts+++ b/frontend/src/composables/useExecuteSQL.ts@@ -3,6 +3,7 @@ import { Status } from "nice-grpc-common";import { markRaw } from "vue";import { useI18n } from "vue-i18n";import { BBNotificationStyle } from "@/bbkit/types";+import { parseSQL } from "@/components/MonacoEditor/sqlParser";import {pushNotification,useTabStore,@@ -22,7 +23,6 @@ import {advice_StatusToJSON,} from "@/types/proto/v1/sql_service";import { isDatabaseV1Alterable } from "@/utils";-import { parseSQL } from "../components/MonacoEditor/sqlParser";const useExecuteSQL = () => {const { t } = useI18n();diff --git a/frontend/src/plugins/ai/components/ChatView/CodeView.vue b/frontend/src/plugins/ai/components/ChatView/CodeView.vueindex ce497c5c03..d099d8cd9e 100644--- a/frontend/src/plugins/ai/components/ChatView/CodeView.vue+++ b/frontend/src/plugins/ai/components/ChatView/CodeView.vue@@ -2,12 +2,15 @@<div class="flex items-start w-full"><div class="flex-1 overflow-x-hidden"><MonacoEditor- ref="editorRef"+ v-model:content="state.code"class="border h-auto"- language="sql"- :value="state.code":readonly="!state.editing":auto-focus="false"+ :auto-height="{+ min: 48,+ max: 120,+ padding: 2,+ }":options="{automaticLayout: true,fontSize: 12,@@ -23,8 +26,6 @@alwaysConsumeMouseWheel: false,},}"- @ready="handleMonacoEditorReady"- @change="state.code = $event"/></div><div class="flex flex-col gap-y-2 ml-0.5 mt-1">@@ -103,11 +104,11 @@<script lang="ts" setup>import { NTooltip } from "naive-ui";-import { reactive, ref, watch } from "vue";+import { reactive, watch } from "vue";import { useI18n } from "vue-i18n";-import MonacoEditor from "@/components/MonacoEditor";+import { MonacoEditor } from "@/components/MonacoEditor";import { pushNotification } from "@/store";-import { minmax, toClipboard } from "@/utils";+import { toClipboard } from "@/utils";import { useAIContext } from "../../logic";import { useConversationStore } from "../../store";import type { Message } from "../../types";@@ -121,31 +122,12 @@ const props = defineProps<{message: Message;}>();-const EDITOR_HEIGHT = {- min: 48,- max: 120,-};-const state = reactive<LocalState>({code: props.message.content,editing: false,});const { t } = useI18n();const { events, showHistoryDialog } = useAIContext();-const editorRef = ref<InstanceType<typeof MonacoEditor>>();--const updateEditorSize = () => {- const contentHeight =- editorRef.value?.editorInstance?.getContentHeight() as number;- const paddings = 2;- editorRef.value?.setEditorContentHeight(- minmax(contentHeight + paddings, EDITOR_HEIGHT.min, EDITOR_HEIGHT.max)- );-};--const handleMonacoEditorReady = () => {- updateEditorSize();-};const handleExecute = () => {events.emit("apply-statement", {diff --git a/frontend/src/plugins/sql-lsp/client/createLanguageClient.ts b/frontend/src/plugins/sql-lsp/client/createLanguageClient.tsindex cf18bcc4b9..0b84995f1d 100644--- a/frontend/src/plugins/sql-lsp/client/createLanguageClient.ts+++ b/frontend/src/plugins/sql-lsp/client/createLanguageClient.ts@@ -1,8 +1,5 @@-import {- CloseAction,- ErrorAction,- MonacoLanguageClient,-} from "monaco-languageclient";+import { MonacoLanguageClient } from "monaco-languageclient";+import { CloseAction, ErrorAction } from "vscode-languageclient";import {BrowserMessageReader,BrowserMessageWriter,diff --git a/frontend/src/plugins/sql-lsp/client/index.ts b/frontend/src/plugins/sql-lsp/client/index.tsindex 9b7a87c940..ae2bf45279 100644--- a/frontend/src/plugins/sql-lsp/client/index.ts+++ b/frontend/src/plugins/sql-lsp/client/index.ts@@ -1 +1,2 @@export * from "./useLanguageClient";+export * from "./useLegacyAutoComplete";diff --git a/frontend/src/plugins/sql-lsp/client/useLanguageClient.ts b/frontend/src/plugins/sql-lsp/client/useLanguageClient.tsindex 14edf6c646..bf1f5ee8a6 100644--- a/frontend/src/plugins/sql-lsp/client/useLanguageClient.ts+++ b/frontend/src/plugins/sql-lsp/client/useLanguageClient.ts@@ -1,9 +1,8 @@-import getMessageServiceOverride from "@codingame/monaco-vscode-api/service-override/messages";-import { StandaloneServices } from "@codingame/monaco-vscode-api/services";import { createLanguageServerWorker } from "@sql-lsp/server";-import { ConnectionScope, Schema, SQLDialect } from "@sql-lsp/types";-import type { ExecuteCommandParams } from "monaco-languageclient";-import { MonacoLanguageClient, MonacoServices } from "monaco-languageclient";+import type { ConnectionScope, Schema } from "@sql-lsp/types";+import type { MonacoLanguageClient } from "monaco-languageclient";+import type { ExecuteCommandParams } from "vscode-languageclient";+import type { SQLDialect } from "@/types";import { createLanguageClient } from "./createLanguageClient";type LocalStage = {@@ -38,12 +37,6 @@ const getWorker = (): Promise<Worker> => {const initializeLanguageClient = async () => {const worker = await getWorker();- StandaloneServices.initialize({- ...getMessageServiceOverride(document.body),- });- // install Monaco language client services- MonacoServices.install();-const { client } = createLanguageClient(worker);return client;diff --git a/frontend/src/plugins/sql-lsp/client/useLegacyAutoComplete.ts b/frontend/src/plugins/sql-lsp/client/useLegacyAutoComplete.tsnew file mode 100644index 0000000000..b313d44c76--- /dev/null+++ b/frontend/src/plugins/sql-lsp/client/useLegacyAutoComplete.ts@@ -0,0 +1,113 @@+import { computedAsync } from "@vueuse/core";+import type monaco from "monaco-editor";+import { Ref, computed, watch } from "vue";+import { useDBSchemaV1Store, useDatabaseV1Store } from "@/store";+import {+ SQLDialect,+ UNKNOWN_ID,+ dialectOfEngineV1,+ unknownDatabase,+} from "@/types";+import {+ DatabaseMetadata,+ DatabaseMetadataView,+} from "@/types/proto/v1/database_service";+import {+ Table,+ type ConnectionScope,+ type MonacoModule,+ type Schema,+} from "../types";++export type AutoCompleteContext = {+ instance: string; // instances/{instance}+ database?: string; // instances/{instance}/databases/{database_name}+};++export const useLegacyAutoComplete = async (+ monaco: MonacoModule,+ editor: monaco.editor.IStandaloneCodeEditor,+ context: Ref<AutoCompleteContext | undefined>+) => {+ const { useLanguageClient } = await import("./useLanguageClient");++ const { changeConnectionScope, changeDialect, changeSchema } =+ useLanguageClient();+ const database = computed(() => {+ if (!context.value || !context.value.database) {+ return unknownDatabase();+ }+ return useDatabaseV1Store().getDatabaseByName(context.value.database);+ });+ const dialect = computed((): SQLDialect => {+ if (database.value.uid === String(UNKNOWN_ID)) {+ return "MYSQL";+ }+ return dialectOfEngineV1(database.value.instanceEntity.engine);+ });+ const connectionScope = computed((): ConnectionScope => {+ if (database.value.uid !== String(UNKNOWN_ID)) {+ return "database";+ }+ return "instance";+ });+ const metadata = computedAsync(() => {+ if (database.value.uid === String(UNKNOWN_ID)) {+ return DatabaseMetadata.fromPartial({+ name: `${database.value.name}/metadata`,+ });+ }++ return useDBSchemaV1Store().getOrFetchDatabaseMetadata({+ database: database.value.name,+ skipCache: false,+ view: DatabaseMetadataView.DATABASE_METADATA_VIEW_BASIC,+ });+ }, DatabaseMetadata.fromPartial({ name: unknownDatabase().name }));++ watch(+ dialect,+ (dialect) => {+ changeDialect(dialect);+ },+ { immediate: true }+ );+ watch(+ connectionScope,+ (connectionScope) => {+ changeConnectionScope(connectionScope);+ },+ { immediate: true }+ );+ watch(+ [metadata, database],+ ([metadata, database]) => {+ if (`${database.name}/metadata` !== metadata.name) {+ return;+ }+ const schema: Schema = {+ databases: [+ {+ name: database.databaseName,+ tables: metadata.schemas.flatMap((s) =>+ s.tables.map<Table>((t) => ({+ database: database.databaseName,+ name: nameForTable(t.name, s.name),+ columns: t.columns.map((c) => ({+ name: c.name,+ })),+ }))+ ),+ },+ ],+ };+ changeSchema(schema);+ },+ { immediate: true }+ );+};++const nameForTable = (table: string, schema: string = "") => {+ if (schema) return `${schema}.${table}`;+ return table;+};diff --git a/frontend/src/plugins/sql-lsp/server/complete/alias.ts b/frontend/src/plugins/sql-lsp/server/complete/alias.tsindex 2990aae0bc..5636370b7a 100644--- a/frontend/src/plugins/sql-lsp/server/complete/alias.ts+++ b/frontend/src/plugins/sql-lsp/server/complete/alias.ts@@ -1,6 +1,7 @@import type { TableNode } from "@joe-re/sql-parser";-import type { SQLDialect, Table } from "@sql-lsp/types";+import type { Table } from "@sql-lsp/types";import { uniq } from "lodash-es";+import type { SQLDialect } from "@/types";import { createColumnCandidatesByAlias } from "./candidates";import { getTableNameFromTableNode } from "./utils";diff --git a/frontend/src/plugins/sql-lsp/server/complete/candidates/createColumnCandidates.ts b/frontend/src/plugins/sql-lsp/server/complete/candidates/createColumnCandidates.tsindex 63260ab3ec..edaa133fa3 100644--- a/frontend/src/plugins/sql-lsp/server/complete/candidates/createColumnCandidates.ts+++ b/frontend/src/plugins/sql-lsp/server/complete/candidates/createColumnCandidates.ts@@ -1,6 +1,6 @@-import { Table } from "@sql-lsp/types";+import type { Table } from "@sql-lsp/types";import { uniqBy } from "lodash-es";-import { CompletionItem } from "vscode-languageserver-types";+import type { CompletionItem } from "vscode-languageserver-types";import { ICONS, SortText } from "../utils";export const createColumnCandidates = (diff --git a/frontend/src/plugins/sql-lsp/server/complete/candidates/createDatabaseCandidates.ts b/frontend/src/plugins/sql-lsp/server/complete/candidates/createDatabaseCandidates.tsindex d5e5d011bc..bbe40aa929 100644--- a/frontend/src/plugins/sql-lsp/server/complete/candidates/createDatabaseCandidates.ts+++ b/frontend/src/plugins/sql-lsp/server/complete/candidates/createDatabaseCandidates.ts@@ -1,6 +1,6 @@-import { Database } from "@sql-lsp/types";+import type { Database } from "@sql-lsp/types";import { uniqBy } from "lodash-es";-import { CompletionItem } from "vscode-languageserver-types";+import type { CompletionItem } from "vscode-languageserver-types";import { ICONS, SortText } from "../utils";export const createDatabaseCandidates = (diff --git a/frontend/src/plugins/sql-lsp/server/complete/candidates/createKeywordCandidates.ts b/frontend/src/plugins/sql-lsp/server/complete/candidates/createKeywordCandidates.tsindex aab9fb784b..8ae637585e 100644--- a/frontend/src/plugins/sql-lsp/server/complete/candidates/createKeywordCandidates.ts+++ b/frontend/src/plugins/sql-lsp/server/complete/candidates/createKeywordCandidates.ts@@ -3,7 +3,7 @@ import type {CompletionItem,CompletionItemKind,} from "vscode-languageserver-types";-import { SQLDialect } from "@/plugins/sql-lsp/types";+import type { SQLDialect } from "@/types";import { ICONS, SortText } from "../utils";import { keywordGroupsOfDialect } from "./keywords";diff --git a/frontend/src/plugins/sql-lsp/server/complete/candidates/createTableCandidates.ts b/frontend/src/plugins/sql-lsp/server/complete/candidates/createTableCandidates.tsindex a986311a55..3d256dee92 100644--- a/frontend/src/plugins/sql-lsp/server/complete/candidates/createTableCandidates.ts+++ b/frontend/src/plugins/sql-lsp/server/complete/candidates/createTableCandidates.ts@@ -1,6 +1,6 @@+import type { Table } from "@sql-lsp/types";import { uniqBy } from "lodash-es";-import { CompletionItem } from "vscode-languageserver-types";-import { Table } from "../../../types";+import type { CompletionItem } from "vscode-languageserver-types";import { ICONS, SortText } from "../utils";export const createTableCandidates = (diff --git a/frontend/src/plugins/sql-lsp/server/complete/candidates/keywords/index.ts b/frontend/src/plugins/sql-lsp/server/complete/candidates/keywords/index.tsindex 0097eb7ab0..1b36ea152a 100644--- a/frontend/src/plugins/sql-lsp/server/complete/candidates/keywords/index.ts+++ b/frontend/src/plugins/sql-lsp/server/complete/candidates/keywords/index.ts@@ -1,4 +1,4 @@-import { SQLDialect } from "@/plugins/sql-lsp/types";+import type { SQLDialect } from "@/types";import * as common from "./common";export type KeywordGroups = {diff --git a/frontend/src/plugins/sql-lsp/server/complete/sub-query.ts b/frontend/src/plugins/sql-lsp/server/complete/sub-query.tsindex b871d3df99..fdca242618 100644--- a/frontend/src/plugins/sql-lsp/server/complete/sub-query.ts+++ b/frontend/src/plugins/sql-lsp/server/complete/sub-query.ts@@ -1,5 +1,6 @@import type { SubqueryNode } from "@joe-re/sql-parser";-import type { SQLDialect, Table } from "@sql-lsp/types";+import type { Table } from "@sql-lsp/types";+import type { SQLDialect } from "@/types";import { getColumnsFromSelectStatement } from "./utils";export class SubQueryMapping {diff --git a/frontend/src/plugins/sql-lsp/server/complete/utils/common.ts b/frontend/src/plugins/sql-lsp/server/complete/utils/common.tsindex 4a5dd28f64..c65c74df0f 100644--- a/frontend/src/plugins/sql-lsp/server/complete/utils/common.ts+++ b/frontend/src/plugins/sql-lsp/server/complete/utils/common.ts@@ -1,4 +1,4 @@-import { SQLDialect } from "@/plugins/sql-lsp/types";+import type { SQLDialect } from "@/types";export enum SortText {DATABASE = "0",diff --git a/frontend/src/plugins/sql-lsp/server/complete/utils/parser-helper.ts b/frontend/src/plugins/sql-lsp/server/complete/utils/parser-helper.tsindex 6d2bd3cbae..0e90853096 100644--- a/frontend/src/plugins/sql-lsp/server/complete/utils/parser-helper.ts+++ b/frontend/src/plugins/sql-lsp/server/complete/utils/parser-helper.ts@@ -6,7 +6,8 @@ import type {TableNode,} from "@joe-re/sql-parser";import { parseFromClause } from "@joe-re/sql-parser";-import type { Column, SQLDialect, Table } from "@/plugins/sql-lsp/types";+import type { Column, Table } from "@/plugins/sql-lsp/types";+import type { SQLDialect } from "@/types";import { isDialectWithSchema } from "./common";export const getFromClauses = (sql: string) => {diff --git a/frontend/src/plugins/sql-lsp/server/initializeConnection.ts b/frontend/src/plugins/sql-lsp/server/initializeConnection.tsindex 13fda12e52..3d1bb3936e 100644--- a/frontend/src/plugins/sql-lsp/server/initializeConnection.ts+++ b/frontend/src/plugins/sql-lsp/server/initializeConnection.ts@@ -1,9 +1,9 @@+import { TextDocuments } from "vscode-languageserver";import { TextDocument } from "vscode-languageserver-textdocument";import {createConnection,BrowserMessageReader,BrowserMessageWriter,- TextDocuments,} from "vscode-languageserver/browser";export const initializeConnection = (diff --git a/frontend/src/plugins/sql-lsp/server/server.ts b/frontend/src/plugins/sql-lsp/server/server.tsindex fc237061fc..3cd8335b57 100644--- a/frontend/src/plugins/sql-lsp/server/server.ts+++ b/frontend/src/plugins/sql-lsp/server/server.ts@@ -1,10 +1,11 @@-import { EngineTypesUsingSQL, LanguageState } from "@sql-lsp/types";-import {+import type { LanguageState } from "@sql-lsp/types";+import type {InitializeResult,CompletionParams,- CompletionTriggerKind,CompletionItem,} from "vscode-languageserver/browser";+import { CompletionTriggerKind } from "vscode-languageserver/browser";+import { EngineTypesUsingSQL } from "@/types/sqlEditor";import { complete } from "./complete";import { initializeConnection } from "./initializeConnection";diff --git a/frontend/src/plugins/sql-lsp/types/index.ts b/frontend/src/plugins/sql-lsp/types/index.tsindex 062da0aa3c..b8481a10be 100644--- a/frontend/src/plugins/sql-lsp/types/index.ts+++ b/frontend/src/plugins/sql-lsp/types/index.ts@@ -1,8 +1,8 @@-import { Schema } from "./schema";-import { SQLDialect } from "./sql";+import type { SQLDialect } from "@/types";+import type { Schema } from "./schema";+export * from "./monaco-editor";export * from "./schema";-export * from "./sql";export type ConnectionScope = "instance" | "database";diff --git a/frontend/src/plugins/sql-lsp/types/monaco-editor.ts b/frontend/src/plugins/sql-lsp/types/monaco-editor.tsnew file mode 100644index 0000000000..1110f586ba--- /dev/null+++ b/frontend/src/plugins/sql-lsp/types/monaco-editor.ts@@ -0,0 +1,3 @@+import type * as monaco from "monaco-editor/esm/vs/editor/editor.api.js";++export type MonacoModule = typeof monaco;diff --git a/frontend/src/plugins/sql-lsp/types/sql.ts b/frontend/src/plugins/sql-lsp/types/sql.tsdeleted file mode 100644index 10dee8f994..0000000000--- a/frontend/src/plugins/sql-lsp/types/sql.ts+++ /dev/null@@ -1,11 +0,0 @@-export const EngineTypesUsingSQL = [- "MYSQL",- "CLICKHOUSE",- "POSTGRES",- "SNOWFLAKE",- "TIDB",- "SPANNER",- "OCEANBASE",-] as const;--export type SQLDialect = typeof EngineTypesUsingSQL[number];diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.tsindex 720fcb8d97..3f8aff3019 100644--- a/frontend/src/router/index.ts+++ b/frontend/src/router/index.ts@@ -991,6 +991,10 @@ router.beforeEach((to, from, next) => {next();return;}+ if (to.name === "workspace.debug-lsp") {+ next();+ return;+ }if (to.name === SIGNIN_MODULE ||diff --git a/frontend/src/types/sqlEditor.ts b/frontend/src/types/sqlEditor.tsindex 984fb4c290..459a2258f7 100644--- a/frontend/src/types/sqlEditor.ts+++ b/frontend/src/types/sqlEditor.ts@@ -1,5 +1,5 @@import type * as monaco from "monaco-editor";-import { InstanceId, DatabaseId, EngineType } from "../types";+import type { InstanceId, DatabaseId, EngineType } from "../types";import { Engine } from "./proto/v1/common";export type EditorModel = monaco.editor.ITextModel;diff --git a/frontend/src/views/ChangeHistoryDetail.vue b/frontend/src/views/ChangeHistoryDetail.vueindex b768c412a1..cf04cd8b13 100644--- a/frontend/src/views/ChangeHistoryDetail.vue+++ b/frontend/src/views/ChangeHistoryDetail.vue@@ -211,7 +211,7 @@v-if="state.showDiff"class="h-[64rem] max-h-full border rounded-md overflow-clip":original="changeHistory.prevSchema"- :value="changeHistory.schema"+ :modified="changeHistory.schema":readonly="true"/><template v-else>@@ -252,7 +252,7 @@<DiffEditorclass="flex-1 w-full border rounded-md overflow-clip":original="previousHistory.schema"- :value="changeHistory.schema"+ :modified="changeHistory.schema":readonly="true"/><div class="flex justify-end">@@ -281,7 +281,6 @@<script lang="ts" setup>import { computed, reactive, watch, ref } from "vue";import ChangeHistoryStatusIcon from "@/components/ChangeHistory/ChangeHistoryStatusIcon.vue";-import DiffEditor from "@/components/MonacoEditor/DiffEditor.vue";import TableDetailDrawer from "@/components/TableDetailDrawer.vue";import {pushNotification,diff --git a/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue b/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vueindex 07e216146b..8d62f8b419 100644--- a/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue+++ b/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue@@ -7,7 +7,9 @@<SheetForIssueTipsBar />- <SQLEditor @execute="handleExecute" />+ <Suspense>+ <SQLEditor @execute="handleExecute" />+ </Suspense></template><Suspense>diff --git a/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vueindex 05705d22c1..c38a26ba6e 100644--- a/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vue+++ b/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vue@@ -3,46 +3,56 @@class="w-full h-auto flex-grow flex flex-col justify-start items-start overflow-auto"><MonacoEditor- ref="editorRef"- v-model:value="sqlCode"class="w-full h-full"- :language="selectedLanguage"- :dialect="selectedDialect"+ :filename="filename"+ :content="content"+ :language="language"+ :dialect="dialect":readonly="readonly":advices="advices"- @change="handleChange"- @change-selection="handleChangeSelection"- @save="handleSaveSheet"+ :auto-complete-context="{+ instance: instance.name,+ database: database.name,+ }"+ @update:content="handleChange"+ @select-content="handleChangeSelection"@ready="handleEditorReady"/></div></template><script lang="ts" setup>-import { computed, defineEmits, nextTick, ref, watch, watchEffect } from "vue";-import { AdviceOption } from "@/components/MonacoEditor";-import MonacoEditor from "@/components/MonacoEditor/MonacoEditor.vue";+import { computed, nextTick, ref, watch } from "vue";+import type {+ AdviceOption,+ IStandaloneCodeEditor,+ MonacoModule,+} from "@/components/MonacoEditor";import {useTabStore,useSQLEditorStore,- useDBSchemaV1Store,useUIStateStore,- useDatabaseV1Store,useInstanceV1ByUID,useSheetAndTabStore,+ useDatabaseV1ByUID,} from "@/store";import {- ComposedDatabase,dialectOfEngineV1,ExecuteConfig,ExecuteOption,SQLDialect,- UNKNOWN_ID,} from "@/types";-import { TableMetadata } from "@/types/proto/v1/database_service";import { formatEngineV1, useInstanceV1EditorLanguage } from "@/utils";import { useSQLEditorContext } from "../context";+const [+ { default: MonacoEditor },+ { extensionNameOfLanguage, formatEditorContent },+] = await Promise.all([+ import("@/components/MonacoEditor/MonacoEditor.vue"),+ import("@/components/MonacoEditor/utils"),+]);+const emit = defineEmits<{(e: "execute",@@ -53,16 +63,12 @@ const emit = defineEmits<{}>();const tabStore = useTabStore();-const databaseStore = useDatabaseV1Store();-const dbSchemaStore = useDBSchemaV1Store();const sqlEditorStore = useSQLEditorStore();const sheetAndTabStore = useSheetAndTabStore();const uiStateStore = useUIStateStore();const { events: editorEvents } = useSQLEditorContext();-const editorRef = ref<InstanceType<typeof MonacoEditor>>();--const sqlCode = computed(() => tabStore.currentTab.statement);+const content = computed(() => tabStore.currentTab.statement);const advices = computed((): AdviceOption[] => {return (Array.from(tabStore.currentTab?.databaseQueryResultMap?.values() || [])@@ -78,26 +84,28 @@ const advices = computed((): AdviceOption[] => {source: advice.detail,}));});-const { instance: selectedInstance } = useInstanceV1ByUID(+const { instance } = useInstanceV1ByUID(computed(() => tabStore.currentTab.connection.instanceId));-const selectedDatabase = computed(() => {- const uid = tabStore.currentTab.connection.databaseId;- if (uid === String(UNKNOWN_ID)) return undefined;- return databaseStore.getDatabaseByUID(uid);-});-const selectedInstanceEngine = computed(() => {- return formatEngineV1(selectedInstance.value);+const { database } = useDatabaseV1ByUID(+ computed(() => tabStore.currentTab.connection.databaseId)+);+const instanceEngine = computed(() => {+ return formatEngineV1(instance.value);});-const selectedLanguage = useInstanceV1EditorLanguage(selectedInstance);-const selectedDialect = computed((): SQLDialect => {- const engine = selectedInstance.value.engine;+const language = useInstanceV1EditorLanguage(instance);+const dialect = computed((): SQLDialect => {+ const engine = instance.value.engine;return dialectOfEngineV1(engine);});const readonly = computed(() => sheetAndTabStore.isReadOnly);const currentTabId = computed(() => tabStore.currentTabId);const isSwitchingTab = ref(false);+const filename = computed(+ () => `${tabStore.currentTab.id}.${extensionNameOfLanguage(language.value)}`+);+watch(currentTabId, () => {isSwitchingTab.value = true;nextTick(() => {@@ -105,16 +113,6 @@ watch(currentTabId, () => {});});-watch(- () => sqlEditorStore.shouldFormatContent,- async () => {- if (sqlEditorStore.shouldFormatContent) {- await editorRef.value?.formatEditorContent();- sqlEditorStore.setShouldFormatContent(false);- }- }-);-const handleChange = (value: string) => {// When we are switching between tabs, the MonacoEditor emits a 'change'// event, but we shouldn't update the current tab;@@ -144,75 +142,51 @@ const handleSaveSheet = () => {editorEvents.emit("save-sheet", { title: tabStore.currentTab.name });};-const handleEditorReady = async () => {- const monaco = await import("monaco-editor");- editorRef.value?.editorInstance?.addAction({+const runQueryAction = (explain = false) => {+ const tab = tabStore.currentTab;+ const query = tab.selectedStatement || tab.statement || "";+ emit("execute", query, { databaseType: instanceEngine.value }, { explain });+ uiStateStore.saveIntroStateByKey({+ key: "data.query",+ newState: true,+ });+};++const handleEditorReady = (+ monaco: MonacoModule,+ editor: IStandaloneCodeEditor+) => {+ editor.addAction({id: "RunQuery",label: "Run Query",keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter],contextMenuGroupId: "operation",contextMenuOrder: 0,- run: async () => {- const typedValue = editorRef.value?.editorInstance?.getValue();- const selectedValue = editorRef.value?.editorInstance- ?.getModel()- ?.getValueInRange(- editorRef.value?.editorInstance?.getSelection() as any- ) as string;- const query = selectedValue || typedValue || "";- await emit("execute", query, {- databaseType: selectedInstanceEngine.value,- });- uiStateStore.saveIntroStateByKey({- key: "data.query",- newState: true,- });- },+ run: () => runQueryAction(false),});-- editorRef.value?.editorInstance?.addAction({+ editor.addAction({id: "ExplainQuery",label: "Explain Query",keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyE],contextMenuGroupId: "operation",contextMenuOrder: 0,- run: async () => {- const typedValue = editorRef.value?.editorInstance?.getValue();- const selectedValue = editorRef.value?.editorInstance- ?.getModel()- ?.getValueInRange(- editorRef.value?.editorInstance?.getSelection() as any- ) as string;- const query = selectedValue || typedValue || "";- await emit(- "execute",- query,- { databaseType: selectedInstanceEngine.value },- { explain: true }- );- },+ run: () => runQueryAction(true),+ });+ editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {+ handleSaveSheet();});- watchEffect(() => {- if (selectedInstance.value) {- const databaseMap: Map<ComposedDatabase, TableMetadata[]> = new Map();-- const databaseList = selectedDatabase.value- ? [selectedDatabase.value]- : databaseStore.databaseListByInstance(selectedInstance.value.name);- // Only provide auto-complete context for those opened database.- for (const database of databaseList) {- const tableList = dbSchemaStore.getTableList(database.name);- if (tableList.length > 0) {- databaseMap.set(database, tableList);- }+ watch(+ () => sqlEditorStore.shouldFormatContent,+ async (shouldFormat) => {+ if (shouldFormat) {+ await formatEditorContent(editor, dialect.value);+ sqlEditorStore.setShouldFormatContent(false);}- const connectionScope = selectedDatabase.value ? "database" : "instance";- editorRef.value?.setEditorAutoCompletionContextV1(- databaseMap,- connectionScope- );+ },+ {+ immediate: true,}- });+ );};</script>diff --git a/frontend/src/views/sql-editor/ProfileDropdown/ProfileDropdown.vue b/frontend/src/views/sql-editor/ProfileDropdown/ProfileDropdown.vueindex 6d29bcf4c2..88bfff0138 100644--- a/frontend/src/views/sql-editor/ProfileDropdown/ProfileDropdown.vue+++ b/frontend/src/views/sql-editor/ProfileDropdown/ProfileDropdown.vue@@ -98,6 +98,9 @@</a></div><div class="border-t border-gray-100"></div>+ <div v-if="isDev" class="py-1 menu-item">+ <LSPTypeSwitch />+ </div><div v-if="allowToggleDebug" class="py-1 menu-item"><div class="flex flex-row items-center space-x-2 justify-between"><span>Debug</span>@@ -119,6 +122,7 @@ import { storeToRefs } from "pinia";import { computed, ref } from "vue";import { useRouter } from "vue-router";import { BBContextMenu, BBSwitch } from "@/bbkit";+import { LSPTypeSwitch } from "@/components/MonacoEditor/dev";import UserAvatar from "@/components/User/UserAvatar.vue";import { useLanguage } from "@/composables/useLanguage";import {diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/ViewInfo.vue b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/ViewInfo.vueindex 169a4dc250..27947709f2 100644--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/ViewInfo.vue+++ b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/ViewInfo.vue@@ -11,7 +11,7 @@</div></div><MonacoEditor- :value="format ? formatted.data : view.definition"+ :content="format ? formatted.data : view.definition":readonly="true"class="border w-full flex-1"/>@@ -22,7 +22,7 @@import { computedAsync, useLocalStorage } from "@vueuse/core";import { NCheckbox } from "naive-ui";import { computed } from "vue";-import MonacoEditor from "@/components/MonacoEditor";+import { MonacoEditor } from "@/components/MonacoEditor";import formatSQL from "@/components/MonacoEditor/sqlFormatter";import { ComposedDatabase, dialectOfEngineV1 } from "@/types";import { Engine } from "@/types/proto/v1/common";diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/StringifyMetadataButton.vue b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/StringifyMetadataButton.vueindex 992031b609..de04fc0689 100644--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/StringifyMetadataButton.vue+++ b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/StringifyMetadataButton.vue@@ -13,7 +13,7 @@<BBSpin v-if="isFetching" /><MonacoEditorv-else- :value="schemaString || ''"+ :content="schemaString || ''":readonly="true"class="border w-full h-full"/>@@ -26,6 +26,7 @@ import { cloneDeep } from "lodash-es";import { Code } from "lucide-vue-next";import { NButton, NPopover } from "naive-ui";import { onMounted, ref } from "vue";+import { MonacoEditor } from "@/components/MonacoEditor";import { sqlServiceClient } from "@/grpcweb";import { useDBSchemaV1Store } from "@/store";import type { ComposedDatabase } from "@/types";diff --git a/frontend/src/views/sql-editor/TerminalPanel/CompactSQLEditor.vue b/frontend/src/views/sql-editor/TerminalPanel/CompactSQLEditor.vueindex 1ed10497d3..c6c90ca26e 100644--- a/frontend/src/views/sql-editor/TerminalPanel/CompactSQLEditor.vue+++ b/frontend/src/views/sql-editor/TerminalPanel/CompactSQLEditor.vue@@ -1,47 +1,57 @@<template>- <div class="whitespace-pre-wrap w-full overflow-hidden compact-sql-editor">+ <div class="whitespace-pre-wrap w-full overflow-hidden bb-compact-sql-editor"><MonacoEditor- ref="editorRef"- class="w-full h-auto max-h-[360px]"- :value="sql"- :language="selectedLanguage"- :dialect="selectedDialect"+ class="w-full h-auto"+ :style="{+ 'min-height': `${MIN_EDITOR_HEIGHT}px`,+ 'max-height': `${MAX_EDITOR_HEIGHT}px`,+ }"+ :content="sql"+ :language="language"+ :dialect="dialect":readonly="readonly":options="EDITOR_OPTIONS"- @change="handleChange"- @change-selection="handleChangeSelection"+ :auto-height="{+ min: MIN_EDITOR_HEIGHT,+ max: MAX_EDITOR_HEIGHT,+ }"+ @update:content="handleChange"+ @select-content="handleChangeSelection"@ready="handleEditorReady"/></div></template><script lang="ts" setup>-import { editor as Editor } from "monaco-editor";-import { computed, nextTick, ref, watch, watchEffect } from "vue";-import MonacoEditor from "@/components/MonacoEditor/MonacoEditor.vue";+import type { editor as Editor } from "monaco-editor";+import { computed, nextTick, ref, toRef, watch } from "vue";+import type {+ IStandaloneCodeEditor,+ MonacoModule,+} from "@/components/MonacoEditor";+import { useTabStore, useSQLEditorStore, useInstanceV1ByUID } from "@/store";import {- useTabStore,- useSQLEditorStore,- useDBSchemaV1Store,- useDatabaseV1Store,- useInstanceV1ByUID,-} from "@/store";-import {- ComposedDatabase,dialectOfEngineV1,ExecuteConfig,ExecuteOption,SQLDialect,- UNKNOWN_ID,} from "@/types";-import { TableMetadata } from "@/types/proto/v1/database_service";import { formatEngineV1, useInstanceV1EditorLanguage } from "@/utils";-import {- checkCursorAtFirstLine,- checkCursorAtLast,- checkCursorAtLastLine,- checkEndsWithSemicolon,-} from "./utils";++const [+ { default: MonacoEditor },+ { useEditorContextKey, formatEditorContent },+ {+ checkCursorAtFirstLine,+ checkCursorAtLast,+ checkCursorAtLastLine,+ checkEndsWithSemicolon,+ },+] = await Promise.all([+ import("@/components/MonacoEditor/MonacoEditor.vue"),+ import("@/components/MonacoEditor/utils"),+ import("./utils"),+]);const props = defineProps({sql: {@@ -67,28 +77,20 @@ const emit = defineEmits<{}>();const MIN_EDITOR_HEIGHT = 40; // ~= 1 line+const MAX_EDITOR_HEIGHT = 360; // ~= 2 linesconst tabStore = useTabStore();-const databaseStore = useDatabaseV1Store();-const dbSchemaStore = useDBSchemaV1Store();const sqlEditorStore = useSQLEditorStore();-const editorRef = ref<InstanceType<typeof MonacoEditor>>();--const { instance: selectedInstance } = useInstanceV1ByUID(+const { instance } = useInstanceV1ByUID(computed(() => tabStore.currentTab.connection.instanceId));-const selectedDatabase = computed(() => {- const id = tabStore.currentTab.connection.databaseId;- if (id === String(UNKNOWN_ID)) return undefined;- return databaseStore.getDatabaseByUID(id);-});-const selectedInstanceEngine = computed(() => {- return formatEngineV1(selectedInstance.value);+const instanceEngine = computed(() => {+ return formatEngineV1(instance.value);});-const selectedLanguage = useInstanceV1EditorLanguage(selectedInstance);-const selectedDialect = computed((): SQLDialect => {- const engine = selectedInstance.value.engine;+const language = useInstanceV1EditorLanguage(instance);+const dialect = computed((): SQLDialect => {+ const engine = instance.value.engine;return dialectOfEngineV1(engine);});const currentTabId = computed(() => tabStore.currentTabId);@@ -101,18 +103,8 @@ watch(currentTabId, () => {});});-watch(- () => sqlEditorStore.shouldFormatContent,- async () => {- if (sqlEditorStore.shouldFormatContent) {- await editorRef.value?.formatEditorContent();- sqlEditorStore.setShouldFormatContent(false);- }- }-);-const firstLinePrompt = computed(() => {- const lang = selectedLanguage.value;+ const lang = language.value;if (lang === "javascript") return "MONGO>";if (lang === "redis") return "REDIS>";return "SQL>";@@ -143,7 +135,6 @@ const handleChange = (value: string) => {});emit("update:sql", value);- updateEditorHeight();};const handleChangeSelection = (value: string) => {@@ -152,52 +143,42 @@ const handleChangeSelection = (value: string) => {});};-const handleEditorReady = async () => {- const monaco = await import("monaco-editor");- const editor = editorRef.value?.editorInstance;- const readonly = editor?.createContextKey<boolean>(- "readonly",- props.readonly- );- watch(- () => props.readonly,- () => readonly?.set(props.readonly)+const execute = (explain = false) => {+ emit(+ "execute",+ props.sql,+ { databaseType: instanceEngine.value },+ { explain });+};- editor?.addAction({+const handleEditorReady = (+ monaco: MonacoModule,+ editor: IStandaloneCodeEditor+) => {+ useEditorContextKey(editor, "readonly", toRef(props, "readonly"));++ editor.addAction({id: "RunQuery",label: "Run Query",keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter],contextMenuGroupId: "operation",contextMenuOrder: 0,precondition: "!readonly",- run: async () => {- emit("execute", props.sql, {- databaseType: selectedInstanceEngine.value,- });- },+ run: () => execute(false),});- editor?.addAction({+ editor.addAction({id: "ExplainQuery",label: "Explain Query",keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyE],contextMenuGroupId: "operation",contextMenuOrder: 1,precondition: "!readonly",- run: async () => {- emit(- "execute",- props.sql,- {- databaseType: selectedInstanceEngine.value,- },- { explain: true }- );- },+ run: () => execute(true),});- editor?.addAction({+ editor.addAction({id: "ClearScreen",label: "Clear Screen",keybindings: [@@ -206,29 +187,29 @@ const handleEditorReady = async () => {contextMenuGroupId: "operation",contextMenuOrder: 3,precondition: "!readonly",- run: () => {- emit("clear-screen");- },+ run: () => emit("clear-screen"),});// Create an editor context value to check if the SQL ends with semicolon ";"- const endsWithSemicolon = editor?.createContextKey<boolean>(+ const endsWithSemicolon = useEditorContextKey(+ editor,"endsWithSemicolon",checkEndsWithSemicolon(editor));- editor?.onDidChangeModelContent(() => {- endsWithSemicolon?.set(checkEndsWithSemicolon(editor));+ editor.onDidChangeModelContent(() => {+ endsWithSemicolon.set(checkEndsWithSemicolon(editor));});// Another editor context value to check if the cursor is at the end of the// editor.- const cursorAtLast = editor?.createContextKey<boolean>(+ const cursorAtLast = useEditorContextKey(+ editor,"cursorAtLast",checkCursorAtLast(editor));- editor?.onDidChangeCursorPosition(() => {- cursorAtLast?.set(checkCursorAtLast(editor));+ editor.onDidChangeCursorPosition(() => {+ cursorAtLast.set(checkCursorAtLast(editor));});- editor?.addCommand(+ editor.addCommand(monaco.KeyCode.Enter,() => {// When@@ -236,30 +217,30 @@ const handleEditorReady = async () => {// - and the cursor is at the end of the editor// - then press "Enter"// We trigger the "execute" event- emit("execute", props.sql, {- databaseType: selectedInstanceEngine.value,- });+ execute(false);},// Tell the editor this should be only// triggered when both of the two conditions are satisfied."!readonly && endsWithSemicolon && cursorAtLast && editorTextFocus && !suggestWidgetVisible && !renameInputVisible && !inSnippetMode && !quickFixWidgetVisible");- const cursorAtFirstLine = editor?.createContextKey<boolean>(+ const cursorAtFirstLine = useEditorContextKey(+ editor,"cursorAtFirstLine",checkCursorAtFirstLine(editor));- const cursorAtLastLine = editor?.createContextKey<boolean>(+ const cursorAtLastLine = useEditorContextKey(+ editor,"cursorAtLastLine",checkCursorAtLastLine(editor));- editor?.onDidChangeCursorPosition(() => {+ editor.onDidChangeCursorPosition(() => {cursorAtFirstLine?.set(checkCursorAtFirstLine(editor));});- editor?.onDidChangeCursorPosition(() => {+ editor.onDidChangeCursorPosition(() => {cursorAtLastLine?.set(checkCursorAtLastLine(editor));});- editor?.addCommand(+ editor.addCommand(monaco.KeyCode.UpArrow,() => {// When@@ -272,7 +253,7 @@ const handleEditorReady = async () => {// triggered when both of the two conditions are satisfied."!readonly && cursorAtFirstLine && editorTextFocus && !suggestWidgetVisible && !renameInputVisible && !inSnippetMode && !quickFixWidgetVisible");- editor?.addCommand(+ editor.addCommand(monaco.KeyCode.DownArrow,() => {// When@@ -286,38 +267,18 @@ const handleEditorReady = async () => {"!readonly && cursorAtLastLine && editorTextFocus && !suggestWidgetVisible && !renameInputVisible && !inSnippetMode && !quickFixWidgetVisible");- watchEffect(async () => {- if (selectedInstance.value) {- const databaseMap: Map<ComposedDatabase, TableMetadata[]> = new Map();- const databaseList = selectedDatabase.value- ? [selectedDatabase.value]- : databaseStore.databaseListByInstance(selectedInstance.value.name);- // Only provide auto-complete context for those opened database.- for (const database of databaseList) {- const tableList = dbSchemaStore.getTableList(database.name);- if (tableList.length > 0) {- databaseMap.set(database, tableList);- }+ watch(+ () => sqlEditorStore.shouldFormatContent,+ async (shouldFormat) => {+ if (shouldFormat) {+ await formatEditorContent(editor, dialect.value);+ sqlEditorStore.setShouldFormatContent(false);}- const connectionScope = selectedDatabase.value ? "database" : "instance";- editorRef.value?.setEditorAutoCompletionContextV1(- databaseMap,- connectionScope- );+ },+ {+ immediate: true,}- });-- updateEditorHeight();-};--const updateEditorHeight = () => {- const contentHeight =- editorRef.value?.editorInstance?.getContentHeight() as number;- let actualHeight = contentHeight;- if (actualHeight < MIN_EDITOR_HEIGHT) {- actualHeight = MIN_EDITOR_HEIGHT;- }- editorRef.value?.setEditorContentHeight(actualHeight);+ );};const EDITOR_OPTIONS = computed<Editor.IStandaloneEditorConstructionOptions>(@@ -338,14 +299,10 @@ const EDITOR_OPTIONS = computed<Editor.IStandaloneEditorConstructionOptions>(cursorStyle: "block",}));-watch(- firstLinePrompt,- (prompt) => (EDITOR_OPTIONS.value.lineNumbersMinChars = prompt.length + 1)-);</script>-<style lang="postcss">-.compact-sql-editor .monaco-editor .line-numbers {- @apply pr-0;+<style lang="postcss" scoped>+.bb-compact-sql-editor :deep(.monaco-editor .line-numbers) {+ @apply !pr-0;}</style>diff --git a/frontend/src/views/sql-editor/TerminalPanel/TerminalPanelV1.vue b/frontend/src/views/sql-editor/TerminalPanel/TerminalPanelV1.vueindex b355355708..a7debfb04b 100644--- a/frontend/src/views/sql-editor/TerminalPanel/TerminalPanelV1.vue+++ b/frontend/src/views/sql-editor/TerminalPanel/TerminalPanelV1.vue@@ -17,17 +17,21 @@:data-height="queryListHeight"><div v-for="query in queryList" :key="query.id" class="relative">- <CompactSQLEditor- v-model:sql="query.sql"- class="min-h-[2rem]"- :class="[- isEditableQueryItem(query) ? 'active-editor' : 'read-only-editor',- ]"- :readonly="!isEditableQueryItem(query)"- @execute="handleExecute"- @history="handleHistory"- @clear-screen="handleClearScreen"- />+ <Suspense>+ <CompactSQLEditor+ v-model:sql="query.sql"+ class="min-h-[2rem]"+ :class="[+ isEditableQueryItem(query)+ ? 'active-editor'+ : 'read-only-editor',+ ]"+ :readonly="!isEditableQueryItem(query)"+ @execute="handleExecute"+ @history="handleHistory"+ @clear-screen="handleClearScreen"+ />+ </Suspense><ResultViewV1v-if="query.params && query.resultSet"class="max-h-[20rem] flex-1 flex flex-col overflow-hidden"diff --git a/frontend/src/views/sql-editor/TerminalPanel/useAttractFocus.ts b/frontend/src/views/sql-editor/TerminalPanel/useAttractFocus.tsindex 6f17c5c457..5b6f3d45bf 100644--- a/frontend/src/views/sql-editor/TerminalPanel/useAttractFocus.ts+++ b/frontend/src/views/sql-editor/TerminalPanel/useAttractFocus.ts@@ -1,6 +1,6 @@import { useEventListener } from "@vueuse/core";import { unref } from "vue";-import { MaybeRef } from "@/types";+import type { MaybeRef } from "@/types";import { isDescendantOf } from "@/utils";const FOCUS_ATTRACTIVE_KEYS: (RegExp | string)[] = [diff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex 716c0614e3..6b023fc2a9 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -59,6 +59,11 @@ export default defineConfig(() => {changeOrigin: true,ws: true,},+ "/lsp": {+ target: `ws://${extractHostPort(LOCAL_ENDPOINT)}/`,+ changeOrigin: true,+ ws: true,+ },"/api": {target: `${LOCAL_ENDPOINT}/api`,changeOrigin: true,@@ -82,6 +87,7 @@ export default defineConfig(() => {alias: {"@/": `${resolve(__dirname, "src")}/`,"@sql-lsp/": `${resolve(__dirname, "src/plugins/sql-lsp")}/`,+ "@public/": `${resolve(__dirname, "public")}/`,},},test: {