25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(explain): show JSON plans in a read-only editor with copy
Saeful Rahmanf9ee05fd7da7
diff --git a/apps/desktop/src/components/explain/ExplainPlanViewer.vue b/apps/desktop/src/components/explain/ExplainPlanViewer.vueindex 2904644b9f..7d5a5e6384 100644--- a/apps/desktop/src/components/explain/ExplainPlanViewer.vue+++ b/apps/desktop/src/components/explain/ExplainPlanViewer.vue@@ -1,14 +1,16 @@<script setup lang="ts">-import { computed, ref, watch } from "vue";+import { computed, onUnmounted, ref, watch } from "vue";import { useI18n } from "vue-i18n";-import { AlertCircle, Braces, Download, GitBranch, Table2, FileText, Workflow } from "@lucide/vue";+import { AlertCircle, Braces, Check, Copy, Download, GitBranch, Table2, FileText, Workflow } from "@lucide/vue";import type { ParsedExplainPlan, ExplainPlanNode } from "@/lib/diagram/explainPlan";import { flattenExplainPlanNodes, formatExplainPlanDetails } from "@/lib/diagram/explainPlan";import { extractActualRows } from "@/lib/diagram/planCanvas";import { Button } from "@/components/ui/button";+import RedisJsonEditor from "@/components/redis/RedisJsonEditor.vue";import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";import { useToast } from "@/composables/useToast";import { translateBackendError } from "@/i18n/backend-errors";+import { copyToClipboard, isPlainClipboardShortcut } from "@/lib/common/clipboard";import { EXPLAIN_PLAN_EXPORT_COLUMN_KEYS, saveExplainPlanExport, type ExplainPlanExportFormat } from "@/lib/export/explainPlanExport";import type { QueryResult } from "@/types/database";import type { DefaultExplainView } from "@/stores/settingsStore";@@ -63,7 +65,6 @@ async function exportPlan(format: ExplainPlanExportFormat) {exporting.value = false;}}-const userSelectedView = ref<ExplainView | null>(null);const activeView = ref<ExplainView>("canvas");const hasTableView = computed(() => !!props.tableResult || !!props.tableError);@@ -139,6 +140,39 @@ const measuredRowsLabel = computed(() => {return databaseType === "sqlserver" ? "ACTUAL" : "ANALYZE";});+const copied = ref(false);+let copiedTimer: number | undefined;++async function copyRawContent() {+ if (!rawContent.value) return;+ try {+ await copyToClipboard(rawContent.value);+ copied.value = true;+ window.clearTimeout(copiedTimer);+ copiedTimer = window.setTimeout(() => (copied.value = false), 1600);+ toast(t("explain.copied"), 1500);+ } catch (error) {+ toast(t("explain.copyFailed", { message: error instanceof Error ? error.message : String(error) }), 3000);+ }+}++onUnmounted(() => window.clearTimeout(copiedTimer));++// Ctrl/Cmd+A inside the XML / TEXT block selects only the plan text, so it can be+// copied natively instead of being swallowed by the app-wide select-all guard.+function onRawKeydown(event: KeyboardEvent) {+ if (!isPlainClipboardShortcut(event, "a")) return;+ const el = event.currentTarget as HTMLElement | null;+ const selection = window.getSelection();+ if (!el || !selection) return;+ event.preventDefault();+ event.stopPropagation();+ const range = document.createRange();+ range.selectNodeContents(el);+ selection.removeAllRanges();+ selection.addRange(range);+}+function tableCellText(value: unknown): string {if (value === null) return "NULL";return value === undefined ? "" : String(value);@@ -281,7 +315,15 @@ function tableCellText(value: unknown): string {</div></div>- <pre v-else class="m-3 overflow-auto whitespace-pre rounded border bg-muted/30 p-3 font-mono text-xs leading-relaxed">{{ rawContent }}</pre>+ <div v-else class="relative m-3 rounded border bg-muted/30" :class="rawFormatLabel === 'JSON' ? 'flex h-full min-h-0 flex-col' : ''">+ <Button v-if="rawContent" size="sm" variant="outline" class="absolute right-3 top-2 z-10 h-6 px-2 text-xs gap-1 bg-background/90" data-testid="explain-copy-raw" @click="copyRawContent">+ <Check v-if="copied" class="h-3.5 w-3.5" />+ <Copy v-else class="h-3.5 w-3.5" />+ {{ t("explain.copyRaw", { format: rawFormatLabel }) }}+ </Button>+ <RedisJsonEditor v-if="rawFormatLabel === 'JSON'" :model-value="rawContent" read-only presentation="viewer" class="min-h-0 flex-1" />+ <pre v-else data-native-clipboard tabindex="-1" class="overflow-auto whitespace-pre p-3 font-mono text-xs leading-relaxed select-text outline-none" @keydown="onRawKeydown">{{ rawContent }}</pre>+ </div></div></div></template>diff --git a/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.copy.spec.ts b/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.copy.spec.tsnew file mode 100644index 0000000000..112dfde9dc--- /dev/null+++ b/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.copy.spec.ts@@ -0,0 +1,117 @@+// @vitest-environment happy-dom++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { createApp, defineComponent, h, nextTick, type App } from "vue";+import { createI18n } from "vue-i18n";+import en from "@/i18n/locales/en";+import { parseExplainResult, type ParsedExplainPlan } from "@/lib/diagram/explainPlan";+import ExplainPlanViewer from "@/components/explain/ExplainPlanViewer.vue";++const mocks = vi.hoisted(() => ({+ copyToClipboard: vi.fn().mockResolvedValue(undefined),+ toast: vi.fn(),+}));++vi.mock("@/lib/common/clipboard", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/lib/common/clipboard")>()),+ copyToClipboard: mocks.copyToClipboard,+}));+vi.mock("@/components/redis/RedisJsonEditor.vue", () => ({+ default: defineComponent({+ props: { modelValue: { type: String, required: true }, readOnly: Boolean },+ setup: (props) => () => h("div", { "data-testid": "json-editor", "data-read-only": String(props.readOnly) }, props.modelValue),+ }),+}));+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));++let app: App | undefined;++beforeEach(() => {+ mocks.copyToClipboard.mockClear();+ mocks.toast.mockClear();+});++afterEach(() => {+ app?.unmount();+ app = undefined;+ document.body.innerHTML = "";+});++function mountViewer(defaultView: "tree" | "raw") {+ const plan = parseExplainResult("oceanbase-oracle", {+ columns: ["Query Plan"],+ rows: [[JSON.stringify({ ID: 0, OPERATOR: "TABLE FULL SCAN", NAME: "EXAMPLE_TABLE", filter: "C1 > 4" })]],+ affected_rows: 0,+ execution_time_ms: 1,+ });+ const container = document.createElement("div");+ document.body.append(container);+ app = createApp(ExplainPlanViewer, { plan, defaultView });+ app.use(createI18n({ legacy: false, locale: "en", messages: { en } }));+ app.mount(container);+ return { plan: plan!, container };+}++describe("ExplainPlanViewer copy", () => {+ it("shows the copy button only inside the raw box", async () => {+ const { container } = mountViewer("tree");+ await nextTick();++ expect(container.querySelector("[data-testid='explain-copy-raw']")).toBeNull();+ });++ it("copies the raw plan from the raw box", async () => {+ const { plan, container } = mountViewer("raw");+ await nextTick();++ const button = container.querySelector<HTMLButtonElement>("[data-testid='explain-copy-raw']");+ expect(button?.textContent?.trim()).toBe("Copy JSON");+ button!.click();+ await nextTick();++ expect(mocks.copyToClipboard).toHaveBeenCalledWith(JSON.stringify(plan.raw, null, 2));+ expect(mocks.toast).toHaveBeenCalledWith("Copied", 1500);+ });++ it("renders the JSON plan in the read-only JSON editor", async () => {+ const { plan, container } = mountViewer("raw");+ await nextTick();++ const editor = container.querySelector("[data-testid='json-editor']");+ expect(editor?.getAttribute("data-read-only")).toBe("true");+ expect(editor?.textContent).toBe(JSON.stringify(plan.raw, null, 2));+ expect(container.querySelector("pre")).toBeNull();+ });++ it("leaves Ctrl+A unhandled outside the raw code block", async () => {+ const { container } = mountViewer("tree");+ await nextTick();++ expect(container.querySelector("[data-native-clipboard][tabindex]")).toBeNull();+ });++ it("selects only the TEXT plan block on Ctrl+A", async () => {+ const plan: ParsedExplainPlan = {+ databaseType: "dameng",+ raw: "1 #NSET2: [1, 1, 0]\n2 #CSCN2: [1, 1, 0]; INDEX33555484(EXAMPLE_TABLE)",+ nodes: [{ id: "1", title: "NSET2", nodeType: "NSET2", details: [], children: [] }],+ };+ const container = document.createElement("div");+ document.body.append(container);+ app = createApp(ExplainPlanViewer, { plan, defaultView: "raw" });+ app.use(createI18n({ legacy: false, locale: "en", messages: { en } }));+ app.mount(container);+ await nextTick();++ expect(container.querySelector("[data-testid='json-editor']")).toBeNull();+ const content = container.querySelector<HTMLElement>("pre[data-native-clipboard][tabindex]");+ expect(content).not.toBeNull();+ const event = new KeyboardEvent("keydown", { key: "a", ctrlKey: true, bubbles: true, cancelable: true });+ content!.dispatchEvent(event);++ expect(event.defaultPrevented).toBe(true);+ const selected = window.getSelection()?.toString() ?? "";+ expect(selected).toContain("EXAMPLE_TABLE");+ expect(selected).not.toContain("Copy TEXT");+ });+});diff --git a/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.defaultView.spec.ts b/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.defaultView.spec.tsindex 0fccdddffc..c740d26008 100644--- a/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.defaultView.spec.ts+++ b/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.defaultView.spec.ts@@ -1,6 +1,6 @@// @vitest-environment happy-dom-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { createApp, h, nextTick, ref, type App } from "vue";import { createI18n } from "vue-i18n";import en from "@/i18n/locales/en";@@ -9,6 +9,9 @@ import { parseExplainResult } from "@/lib/diagram/explainPlan";import ExplainPlanViewer from "@/components/explain/ExplainPlanViewer.vue";import type { QueryResult } from "@/types/database";+// The real CodeMirror-backed editor needs Pinia settings; only the view switch is under test here.+vi.mock("@/components/redis/RedisJsonEditor.vue", () => ({ default: { render: () => h("div", { "data-testid": "json-editor" }) } }));+let app: App | undefined;afterEach(() => {@@ -153,7 +156,7 @@ describe("ExplainPlanViewer defaultView prop", () => {app.mount(container);await nextTick();- const rawBtn = [...container.querySelectorAll("button")].find((btn) => btn.textContent?.includes("JSON"));+ const rawBtn = [...container.querySelectorAll("button")].find((btn) => btn.textContent?.trim() === "JSON");expect(rawBtn?.className).toContain("bg-secondary");});diff --git a/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.export.spec.ts b/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.export.spec.tsindex 5791852e0b..52dd7f1bb7 100644--- a/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.export.spec.ts+++ b/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.export.spec.ts@@ -21,6 +21,9 @@ function passthrough(tag: string): Component {vi.mock("vue-i18n", () => ({useI18n: () => ({ t: (key: string) => key }),+ // The viewer's RedisJsonEditor import pulls in the real i18n module, whose+ // import-time createI18n call must survive this mock.+ createI18n: () => ({ global: { t: (key: string) => key }, install: () => {} }),}));vi.mock("@lucide/vue", () => ({AlertCircle: passthrough("span"),diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.tsindex 480fee5508..8fc866673e 100644--- a/apps/desktop/src/i18n/locales/az.ts+++ b/apps/desktop/src/i18n/locales/az.ts@@ -2647,6 +2647,9 @@ export default withEnglishFallback({apply: "Tətbiq et",},explain: {+ copyRaw: "{format} kopyala",+ copied: "Kopyalandı",+ copyFailed: "Kopyalama alınmadı: {message}",estimatedTime: "Təxmini vaxt",title: "İcra planı",standardTable: "Cədvəl",diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex dbb954e06d..fd7bcefe59 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -3116,6 +3116,9 @@ export default {apply: "Apply",},explain: {+ copyRaw: "Copy {format}",+ copied: "Copied",+ copyFailed: "Copy failed: {message}",estimatedTime: "Estimated time",title: "Explain Plan",standardTable: "Table",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 447f56c3fa..eae07d676c 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -3017,6 +3017,9 @@ export default withEnglishFallback({apply: "Aplicar",},explain: {+ copyRaw: "Copiar {format}",+ copied: "Copiado",+ copyFailed: "Error al copiar: {message}",estimatedTime: "Tiempo estimado",title: "Plan de ejecución",standardTable: "Tabla",diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.tsindex 3714d90b5a..7562212410 100644--- a/apps/desktop/src/i18n/locales/id.ts+++ b/apps/desktop/src/i18n/locales/id.ts@@ -2949,6 +2949,9 @@ export default withEnglishFallback({apply: "Terapkan",},explain: {+ copyRaw: "Salin {format}",+ copied: "Disalin",+ copyFailed: "Gagal menyalin: {message}",estimatedTime: "Perkiraan waktu",title: "Explain Plan",standardTable: "Tabel",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 888762d8a0..d40deb3fb9 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -2868,6 +2868,9 @@ export default withEnglishFallback({apply: "Applica",},explain: {+ copyRaw: "Copia {format}",+ copied: "Copiato",+ copyFailed: "Copia non riuscita: {message}",estimatedTime: "Tempo stimato",title: "Piano di Spiegazione",standardTable: "Tabella",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 9652af30ed..ad6a3749c7 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -2894,6 +2894,9 @@ export default withEnglishFallback({apply: "適用",},explain: {+ copyRaw: "{format} をコピー",+ copied: "コピーしました",+ copyFailed: "コピーに失敗しました: {message}",estimatedTime: "推定時間",title: "実行計画",standardTable: "標準テーブル",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 7b4135c47c..0aac038b48 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -2822,6 +2822,9 @@ export default withEnglishFallback({apply: "적용",},explain: {+ copyRaw: "{format} 복사",+ copied: "복사됨",+ copyFailed: "복사 실패: {message}",estimatedTime: "예상 시간",title: "실행 계획",standardTable: "표",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 55fb83b1ed..8c9ae5c0c5 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -2870,6 +2870,9 @@ export default withEnglishFallback({apply: "Aplicar",},explain: {+ copyRaw: "Copiar {format}",+ copied: "Copiado",+ copyFailed: "Falha ao copiar: {message}",estimatedTime: "Tempo estimado",title: "Plano de Execução",standardTable: "Tabela",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex 277c001d7a..a2908b2a8a 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -2973,6 +2973,9 @@ export default withEnglishFallback({apply: "Применить",},explain: {+ copyRaw: "Копировать {format}",+ copied: "Скопировано",+ copyFailed: "Не удалось скопировать: {message}",estimatedTime: "Оценочное время",title: "План выполнения",standardTable: "Таблица",diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.tsindex 56e0932b70..4d3cf134c0 100644--- a/apps/desktop/src/i18n/locales/tr.ts+++ b/apps/desktop/src/i18n/locales/tr.ts@@ -2623,6 +2623,9 @@ export default withEnglishFallback({apply: "Uygula",},explain: {+ copyRaw: "{format} kopyala",+ copied: "Kopyalandı",+ copyFailed: "Kopyalama başarısız: {message}",estimatedTime: "Tahmini süre",title: "Yürütme Planı",standardTable: "Tablo",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 1aca202e29..f5db8b647d 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -3050,6 +3050,9 @@ export default withEnglishFallback({apply: "应用",},explain: {+ copyRaw: "复制 {format}",+ copied: "已复制",+ copyFailed: "复制失败:{message}",estimatedTime: "预计耗时",title: "执行计划",standardTable: "标准表格",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex d635328bfa..95075b15f5 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -2876,6 +2876,9 @@ export default withEnglishFallback({apply: "套用",},explain: {+ copyRaw: "複製 {format}",+ copied: "已複製",+ copyFailed: "複製失敗:{message}",estimatedTime: "預估耗時",title: "執行計畫",standardTable: "標準表格",