Skip to content

armgit / dbx

Public Imported from GitHub
0

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。

feat(sql-file): add locate button for the active opened file

ninggc3ad44a181174
diff --git a/apps/desktop/src/components/layout/SqlFilePanel.vue b/apps/desktop/src/components/layout/SqlFilePanel.vue
index 21dd138938..882c5429aa 100644
--- a/apps/desktop/src/components/layout/SqlFilePanel.vue
+++ b/apps/desktop/src/components/layout/SqlFilePanel.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
-import { ref, computed, onMounted } from "vue";
+import { ref, computed, nextTick, onMounted } from "vue";
import { useI18n } from "vue-i18n";
-import { FolderOpen, FileCode, FolderClosed, ChevronRight, ChevronDown, X, Trash2, RefreshCw, FolderSearch, Copy, Play, ChevronsUpDown, ChevronsDownUp, Settings, FilePlus, Pencil } from "@lucide/vue";
+import { FolderOpen, FileCode, FolderClosed, ChevronRight, ChevronDown, X, Trash2, RefreshCw, FolderSearch, Copy, Play, ChevronsUpDown, ChevronsDownUp, Settings, FilePlus, Pencil, LocateFixed } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
@@ -17,7 +17,7 @@ import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { translateBackendError } from "@/i18n/backend-errors";
import { copyToClipboard } from "@/lib/common/clipboard";
import { forgetExternalSqlFileTarget, moveExternalSqlFileTarget, resolveExternalSqlFileTargetForActiveTab } from "@/lib/sql/externalSqlFileTarget";
-import { externalSqlFileOpenErrorMessage, externalSqlEditorMaxBytes, formatSqlFileSize, isExternalSqlFileTooLargeError, isSqlFilePath } from "@/lib/sql/sqlFileOpen";
+import { externalSqlFileOpenErrorMessage, externalSqlEditorMaxBytes, formatSqlFileSize, isExternalSqlFileTooLargeError, isSqlFilePath, normalizeExternalSqlPath } from "@/lib/sql/sqlFileOpen";
import * as api from "@/lib/backend/api";
import type { SqlFileEntry } from "@/lib/backend/api";
import { getSqlFileFilter, getSqlFileFolderPaths, saveSqlFileFilter, saveSqlFileFolderPaths, notifySqlFileFoldersChanged } from "@/lib/sqlFile/sqlFileFolders";
@@ -63,6 +63,46 @@ const showDeleteDialog = ref(false);
const selectedPaths = ref<Set<string>>(new Set());
const activePath = ref<string | null>(null);
const selectionAnchorIndex = ref<number | null>(null);
+const fileTree = ref<HTMLElement | null>(null);
+
+function findFileAncestors(entries: SqlFileEntry[], path: string): string[] | null {
+ for (const entry of entries) {
+ if (!entry.is_dir && normalizeExternalSqlPath(entry.path) === path) return [];
+ if (entry.is_dir) {
+ const ancestors = findFileAncestors(entry.children, path);
+ if (ancestors) return [entry.path, ...ancestors];
+ }
+ }
+ return null;
+}
+
+const activeFileTarget = computed(() => {
+ const tab = queryStore.tabs.find((tab) => tab.id === queryStore.activeTabId);
+ if (!tab?.externalSqlPath) return null;
+ const path = normalizeExternalSqlPath(tab.externalSqlPath);
+ for (const folder of folders.value) {
+ if (folder.loading) continue;
+ const ancestors = findFileAncestors(folder.entries, path);
+ if (ancestors) return { folder, path, ancestors };
+ }
+ return null;
+});
+
+async function locateActiveFile() {
+ const target = activeFileTarget.value;
+ if (!target) return;
+ target.folder.collapsed = false;
+ target.folder.expanded = new Set([...target.folder.expanded, ...target.ancestors]);
+ const itemIndex = visibleItems.value.findIndex((item) => item.type === "file" && normalizeExternalSqlPath(item.id) === target.path);
+ const item = visibleItems.value[itemIndex];
+ if (!item) return;
+ selectedPaths.value = new Set();
+ activePath.value = item.id;
+ selectionAnchorIndex.value = itemIndex;
+ await nextTick();
+ const row = Array.from(fileTree.value?.querySelectorAll<HTMLElement>("[data-sql-file-path]") ?? []).find((row) => normalizeExternalSqlPath(row.dataset.sqlFilePath!) === target.path);
+ row?.scrollIntoView({ block: "center", inline: "nearest" });
+}
function clearSelection() {
selectedPaths.value = new Set();
@@ -547,6 +587,11 @@ function clearContextTarget() {
{{ t("sqlFileTree.storageHelp") }}
</HelpTooltip>
<span class="flex-1" />
+ <LightTooltip :text="t('sidebar.locateActiveTab')" side="bottom" :delay="0" :close-delay="0" nowrap>
+ <Button variant="ghost" size="icon" class="h-5 w-5" :aria-label="t('sidebar.locateActiveTab')" :disabled="!activeFileTarget" @click="locateActiveFile">
+ <LocateFixed class="h-3 w-3" />
+ </Button>
+ </LightTooltip>
<LightTooltip :text="t('sqlFileTree.filterSettings')" side="bottom" :delay="0" :close-delay="0" nowrap>
<Button
variant="ghost"
@@ -580,6 +625,7 @@ function clearContextTarget() {
<CustomContextMenu :items="contextMenuItems" @close="clearContextTarget">
<template #default="{ onContextMenu }">
<div
+ ref="fileTree"
class="flex-1 overflow-y-auto"
@click="handlePanelClick"
@contextmenu.capture="contextTarget = { kind: 'panel' }"
@@ -649,6 +695,7 @@ function clearContextTarget() {
data-sql-file-row="true"
v-for="{ entry, depth } in flatTree(folder.entries, folder.expanded)"
:key="entry.path"
+ :data-sql-file-path="entry.path"
class="flex cursor-default select-none items-center gap-1 px-2 py-1 text-sm"
:class="[entry.is_dir ? 'rounded-sm' : 'rounded-none', isPathHighlighted(entry.path) ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/40']"
:style="{ paddingLeft: depth * 16 + 8 + 'px' }"
diff --git a/apps/desktop/src/components/layout/__tests__/SqlFilePanel.locate.spec.ts b/apps/desktop/src/components/layout/__tests__/SqlFilePanel.locate.spec.ts
new file mode 100644
index 0000000000..6fae2764bf
--- /dev/null
+++ b/apps/desktop/src/components/layout/__tests__/SqlFilePanel.locate.spec.ts
@@ -0,0 +1,120 @@
+// @vitest-environment happy-dom
+
+import { createApp, nextTick, type App } from "vue";
+import { createPinia, setActivePinia } from "pinia";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import i18n from "@/i18n";
+import { useQueryStore } from "@/stores/queryStore";
+
+vi.mock("@/lib/sqlFile/sqlFileFolders", () => ({
+ getSqlFileFilter: () => "*.sql",
+ getSqlFileFolderPaths: () => ["/sql"],
+ saveSqlFileFilter: vi.fn(),
+ saveSqlFileFolderPaths: vi.fn(),
+ notifySqlFileFoldersChanged: vi.fn(),
+}));
+vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
+vi.mock("@/lib/backend/api", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/lib/backend/api")>()),
+ listSqlFilesInFolder: vi.fn(async () => [
+ { name: "nested", path: "/sql/nested", is_dir: true, children: [{ name: "deep", path: "/sql/nested/deep", is_dir: true, children: [{ name: "current.sql", path: "/sql/nested/deep/current.sql", is_dir: false, children: [] }] }] },
+ { name: "other.sql", path: "/sql/other.sql", is_dir: false, children: [] },
+ ]),
+}));
+
+import SqlFilePanel from "../SqlFilePanel.vue";
+
+const mounted: Array<{ app: App; host: HTMLElement }> = [];
+const scrollIntoView = vi.fn();
+
+async function mountPanel(path?: string) {
+ const pinia = createPinia();
+ setActivePinia(pinia);
+ const queryStore = useQueryStore();
+ if (path) queryStore.openExternalSqlFile("", "", path, "SELECT 1");
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ const app = createApp(SqlFilePanel);
+ app.use(pinia);
+ app.use(i18n);
+ app.mount(host);
+ mounted.push({ app, host });
+ await vi.waitFor(() => expect(host.textContent).toContain("other.sql"));
+ const button = host.querySelector<HTMLButtonElement>(`button[aria-label="${i18n.global.t("sidebar.locateActiveTab")}"]`);
+ expect(button).not.toBeNull();
+ return { host, button: button!, queryStore };
+}
+
+beforeEach(() => {
+ vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(scrollIntoView);
+});
+
+afterEach(() => {
+ for (const { app, host } of mounted.splice(0)) {
+ app.unmount();
+ host.remove();
+ }
+ vi.restoreAllMocks();
+ scrollIntoView.mockClear();
+});
+
+describe("SQL file panel locate active file", () => {
+ it("expands collapsed parents, highlights and scrolls without reopening the file", async () => {
+ const { host, button, queryStore } = await mountPanel("/sql/nested/deep/current.sql");
+ const openFile = vi.spyOn(queryStore, "openExternalSqlFile");
+ const tabId = queryStore.activeTabId;
+ const header = host.querySelector<HTMLElement>("[data-sql-file-row='true']")!;
+ header.click();
+ await nextTick();
+ expect(host.textContent).not.toContain("current.sql");
+
+ button.click();
+ await nextTick();
+ await nextTick();
+
+ const row = host.querySelector<HTMLElement>('[data-sql-file-path="/sql/nested/deep/current.sql"]');
+ expect(row).not.toBeNull();
+ expect(row!.classList.contains("bg-accent")).toBe(true);
+ expect(row!.parentElement!.parentElement!.style.display).not.toBe("none");
+ expect(scrollIntoView).toHaveBeenCalledWith({ block: "center", inline: "nearest" });
+ expect(scrollIntoView.mock.contexts[0]).toBe(row);
+ expect(openFile).not.toHaveBeenCalled();
+ expect(queryStore.activeTabId).toBe(tabId);
+ });
+
+ it("follows the current tab and replaces the previous highlight", async () => {
+ const { host, button, queryStore } = await mountPanel("/sql/nested/deep/current.sql");
+ button.click();
+ await nextTick();
+ queryStore.openExternalSqlFile("", "", "/sql/other.sql", "SELECT 2");
+ await nextTick();
+ button.click();
+ await nextTick();
+ expect(host.querySelector('[data-sql-file-path="/sql/other.sql"]')!.classList.contains("bg-accent")).toBe(true);
+ expect(host.querySelector('[data-sql-file-path="/sql/nested/deep/current.sql"]')!.classList.contains("bg-accent")).toBe(false);
+ });
+
+ it.each([undefined, "/outside/current.sql"])("disables locating when the active file is unavailable: %s", async (path) => {
+ const { button } = await mountPanel(path);
+ expect(button.disabled).toBe(true);
+ button.click();
+ await nextTick();
+ expect(scrollIntoView).not.toHaveBeenCalled();
+ });
+
+ it("matches normalized path separators", async () => {
+ const { host, button } = await mountPanel("\\sql\\nested\\deep\\current.sql");
+ expect(button.disabled).toBe(false);
+ button.click();
+ await nextTick();
+ expect(host.querySelector('[data-sql-file-path="/sql/nested/deep/current.sql"]')!.classList.contains("bg-accent")).toBe(true);
+ });
+
+ it("disables locating after switching to an unsaved query", async () => {
+ const { button, queryStore } = await mountPanel("/sql/other.sql");
+ expect(button.disabled).toBe(false);
+ queryStore.createTab("", "");
+ await nextTick();
+ expect(button.disabled).toBe(true);
+ });
+});