feat(explain): show JSON plans in a read-only editor with copy
This commit is contained in:
1 parent
c6159213aa
commit
f9ee05fd7d
16 files changed
+207
-6
No files matched your search
@@ -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>
|
||||
+117
@@ -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");
|
||||
});
|
||||
});
|
||||
+5
-2
@@ -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");
|
||||
});
|
||||
|
||||
|
||||
+3
@@ -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"),
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -2894,6 +2894,9 @@ export default withEnglishFallback({
|
||||
apply: "適用",
|
||||
},
|
||||
explain: {
|
||||
copyRaw: "{format} をコピー",
|
||||
copied: "コピーしました",
|
||||
copyFailed: "コピーに失敗しました: {message}",
|
||||
estimatedTime: "推定時間",
|
||||
title: "実行計画",
|
||||
standardTable: "標準テーブル",
|
||||
|
||||
@@ -2822,6 +2822,9 @@ export default withEnglishFallback({
|
||||
apply: "적용",
|
||||
},
|
||||
explain: {
|
||||
copyRaw: "{format} 복사",
|
||||
copied: "복사됨",
|
||||
copyFailed: "복사 실패: {message}",
|
||||
estimatedTime: "예상 시간",
|
||||
title: "실행 계획",
|
||||
standardTable: "표",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -2973,6 +2973,9 @@ export default withEnglishFallback({
|
||||
apply: "Применить",
|
||||
},
|
||||
explain: {
|
||||
copyRaw: "Копировать {format}",
|
||||
copied: "Скопировано",
|
||||
copyFailed: "Не удалось скопировать: {message}",
|
||||
estimatedTime: "Оценочное время",
|
||||
title: "План выполнения",
|
||||
standardTable: "Таблица",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -3050,6 +3050,9 @@ export default withEnglishFallback({
|
||||
apply: "应用",
|
||||
},
|
||||
explain: {
|
||||
copyRaw: "复制 {format}",
|
||||
copied: "已复制",
|
||||
copyFailed: "复制失败:{message}",
|
||||
estimatedTime: "预计耗时",
|
||||
title: "执行计划",
|
||||
standardTable: "标准表格",
|
||||
|
||||
@@ -2876,6 +2876,9 @@ export default withEnglishFallback({
|
||||
apply: "套用",
|
||||
},
|
||||
explain: {
|
||||
copyRaw: "複製 {format}",
|
||||
copied: "已複製",
|
||||
copyFailed: "複製失敗:{message}",
|
||||
estimatedTime: "預估耗時",
|
||||
title: "執行計畫",
|
||||
standardTable: "標準表格",
|
||||
|
||||
Reference in new issue
Block a user