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。

73.0 KB
Raw Blame
<script setup lang="ts">
import { ref, computed, nextTick, onMounted, onBeforeUnmount, watch, useId } from "vue";
import { useI18n } from "vue-i18n";
import { FolderOpen, FolderClosed, FileCode, FolderPlus, ChevronRight, ChevronDown, X, Trash2, RefreshCw, FolderSearch, Copy, Play, ChevronsUpDown, ChevronsDownUp, Settings, FilePlus, Pencil, ArrowDownAZ, ArrowUpAZ, GripVertical, Check } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useSqlPanelSearchMode } from "@/composables/useSqlPanelSearchMode";
import SqlPanelSearch from "@/components/layout/SqlPanelSearch.vue";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import LightTooltip from "@/components/ui/LightTooltip.vue";
import HelpTooltip from "@/components/ui/tooltip/HelpTooltip.vue";
import SidebarLocateButton from "@/components/sidebar/SidebarLocateButton.vue";
import SqlSearchMatchSnippet from "@/components/layout/SqlSearchMatchSnippet.vue";
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
import { useQueryStore } from "@/stores/queryStore";
import { useConnectionStore } from "@/stores/connectionStore";
import { useSettingsStore } from "@/stores/settingsStore";
import { useToast } from "@/composables/useToast";
import { useSqlFileContentSearch } from "@/composables/useSqlFileContentSearch";
import type { SavedSqlLineMatch } from "@/lib/savedSql/savedSqlSearch";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { translateBackendError } from "@/i18n/backend-errors";
import { copyToClipboard } from "@/lib/common/clipboard";
import { forgetExternalSqlFileTarget, forgetExternalSqlFolderTargets, moveExternalSqlFileTarget, moveExternalSqlFolderTargets, resolveExternalSqlFileTargetForActiveTab } from "@/lib/sql/externalSqlFileTarget";
import { externalSqlFileOpenErrorMessage, externalSqlEditorMaxBytes, formatSqlFileSize, isExternalSqlFileTooLargeError, isSqlFilePath, normalizeExternalSqlPath, queryTabExternalFilePath, relocateExternalSqlPathWithinFolder } 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";
import { getSqlFileFoldersUiState, saveSqlFileFoldersUiState, type SqlFileFolderUiState } from "@/lib/sqlFile/sqlFileUiState";
import { filterAndSortSqlFileEntries, getSqlFileSortOrder, saveSqlFileSortOrder, type SqlFileSortOrder } from "@/lib/sql/sqlFileTreeFilter";
import { orderedListSelectionIntent, type OrderedListSelectionItem } from "@/lib/selection/orderedListSelection";
import { getSqlFileOpenMode, saveSqlFileOpenMode, type SqlFileOpenMode } from "@/lib/sqlFile/sqlFileInteraction";
import { getSqlFileOrder, saveSqlFileOrder, reorderSqlFiles, remapSqlFileOrder, sqlFileParentPath, type SqlFileOrder } from "@/lib/sqlFile/sqlFileOrder";
import { useSqlFileReorder } from "@/composables/useSqlFileReorder";

const props = defineProps<{ locateRequest?: { id: number; path: string } | null }>();

const emit = defineEmits<{
  "locate-handled": [id: number];
  close: [];
}>();

const { t } = useI18n();
const queryStore = useQueryStore();
const connectionStore = useConnectionStore();
const settingsStore = useSettingsStore();
const { toast } = useToast();

interface FolderState {
  path: string;
  entries: SqlFileEntry[];
  expanded: Set<string>;
  loading: boolean;
  refreshing: boolean;
  collapsed: boolean;
}

const folders = ref<FolderState[]>([]);
let uiStateInitialized = false;

function persistFoldersUiState() {
  if (!uiStateInitialized) return;
  const state: Record<string, SqlFileFolderUiState> = {};
  for (const f of folders.value) {
    state[f.path] = {
      collapsed: f.collapsed,
      expanded: [...f.expanded],
    };
  }
  saveSqlFileFoldersUiState(state);
}
const fileTree = ref<HTMLElement | null>(null);
const locatingFile = ref(false);
const currentFilePath = computed(() => {
  const tab = queryStore.tabs.find((tab) => tab.id === queryStore.activeTabId);
  return queryTabExternalFilePath(tab);
});
const filterSettingsOpen = ref(false);
const fileFilterDraft = ref(getSqlFileFilter());
const openMode = ref<SqlFileOpenMode>(getSqlFileOpenMode());
const openModeDraft = ref<SqlFileOpenMode>(openMode.value);
const foldersRevision = ref(0);
const treeId = useId();
let lastClickedKey: string | null = null;
const fileFilterRegexExample = "(?i)[.](sql|ddl|sh|py)$";

const searchInput = ref<InstanceType<typeof SqlPanelSearch> | null>(null);
const searchInputPending = ref(false);
const searchMode = useSqlPanelSearchMode("file");
const searchQuery = ref("");
const {
  searching: scanning,
  error: searchError,
  matchesByPath,
  matchingPaths,
  incomplete: searchIncomplete,
  skippedCount,
  skippedFiles,
  truncated: searchTruncated,
} = useSqlFileContentSearch(
  () => (searchMode.value === "content" ? searchQuery.value : ""),
  () => folders.value,
  () => searchInputPending.value,
);
const searching = computed(() => searchInputPending.value || scanning.value);
const searchIncompleteHelp = computed(() => {
  const reasonKeys: Record<string, string> = {
    tooLarge: "sqlFileTree.searchSkippedTooLarge",
    unreadable: "sqlFileTree.searchSkippedUnreadable",
    invalidEncoding: "sqlFileTree.searchSkippedInvalidEncoding",
    outsideRoot: "sqlFileTree.searchSkippedOutsideRoot",
    notRegularFile: "sqlFileTree.searchSkippedNotRegularFile",
  };
  const counts = new Map<string, number>();
  for (const file of skippedFiles.value) {
    const key = Object.prototype.hasOwnProperty.call(reasonKeys, file.reason) ? reasonKeys[file.reason] : "sqlFileTree.searchSkippedOther";
    counts.set(key, (counts.get(key) ?? 0) + 1);
  }
  const details = [...counts].map(([key, count]) => t(key, { count }));
  if (searchTruncated.value) details.push(t("sqlFileTree.searchPreviewLimits", { perFile: 100, total: 1000 }));
  return [t("sqlFileTree.searchIncompleteHelp"), ...details].join("\n");
});
const sortOrder = ref<SqlFileSortOrder>(getSqlFileSortOrder ? getSqlFileSortOrder() : "asc");
const manualOrder = ref<SqlFileOrder>(getSqlFileOrder());
const sortOptions = computed(() => [
  { order: "manual" as const, label: t("sqlFileTree.sortManual"), icon: GripVertical },
  { order: "asc" as const, label: t("sqlLibrary.sortNameAsc"), icon: ArrowDownAZ },
  { order: "desc" as const, label: t("sqlLibrary.sortNameDesc"), icon: ArrowUpAZ },
]);
const currentSortOption = computed(() => sortOptions.value.find((option) => option.order === sortOrder.value)!);
const userCollapsedDuringSearch = ref<Set<string>>(new Set());

watch([searchQuery, searchMode], () => {
  userCollapsedDuringSearch.value.clear();
});

function setSortOrder(order: SqlFileSortOrder) {
  if (!saveSqlFileSortOrder(order)) {
    toast(t("sqlFileTree.sortSaveFailed"), 5000);
    return;
  }
  cancelFileDrag();
  sortOrder.value = order;
}

function persistManualOrder(next: SqlFileOrder): boolean {
  if (!saveSqlFileOrder(next)) {
    toast(t("sqlFileTree.sortSaveFailed"), 5000);
    return false;
  }
  manualOrder.value = next;
  return true;
}

function remapManualOrder(previousPath: string, nextPath?: string, directory = false) {
  const next = remapSqlFileOrder(manualOrder.value, previousPath, nextPath, directory);
  if (next === manualOrder.value) return;
  // The filesystem mutation has already succeeded: keep this session consistent
  // even if persisting the updated preference fails.
  if (!persistManualOrder(next)) manualOrder.value = next;
}

// Right-click target. `kind` discriminates between a folder header, a tree
// directory entry, and a tree file entry. `folderPath` is the owning top-level
// folder (for refresh scoping); `entryPath` is the right-clicked node path.
type ContextTarget = { kind: "panel" } | { kind: "folderHeader"; folderPath: string } | { kind: "dir"; folderPath: string; entry: SqlFileEntry } | { kind: "file"; folderPath: string; entry: SqlFileEntry };

const contextTarget = ref<ContextTarget | null>(null);
const createTarget = ref<{ rootPath: string; directoryPath: string } | null>(null);
const renameTarget = ref<Extract<ContextTarget, { kind: "file" }> | null>(null);
const renameFolderTarget = ref<Extract<ContextTarget, { kind: "dir" }> | null>(null);
const deleteTarget = ref<Extract<ContextTarget, { kind: "file" }> | null>(null);
const deleteFolderTarget = ref<Extract<ContextTarget, { kind: "dir" }> | null>(null);
const fileNameInput = ref("");
const showCreateDialog = ref(false);
const showCreateFolderDialog = ref(false);
const folderMutationPending = ref(false);
const showRenameDialog = ref(false);
const showRenameFolderDialog = ref(false);
const showDeleteDialog = ref(false);
const showDeleteFolderDialog = ref(false);

const selectedKeys = ref<Set<string>>(new Set());
const activeKey = ref<string | null>(null);
const selectionAnchorKey = ref<string | 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;
}

function findFileTarget(filePath: string) {
  const path = normalizeExternalSqlPath(filePath);
  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 locateFileTarget(path: string) {
  if (disposed) return;
  const target = findFileTarget(path);
  if (!target) return;
  if (searchInput.value?.text) {
    const isVisibleNow = visibleItems.value.some((item) => item.folder === target.folder && item.type === "file" && normalizeExternalSqlPath(item.path) === target.path);
    if (searchInputPending.value || !isVisibleNow) {
      searchInput.value?.clear();
      await nextTick();
    }
  }
  target.folder.collapsed = false;
  target.folder.expanded = new Set([...target.folder.expanded, ...target.ancestors]);
  persistFoldersUiState();
  const itemIndex = visibleItems.value.findIndex((item) => item.folder === target.folder && item.type === "file" && normalizeExternalSqlPath(item.path) === target.path);
  const item = visibleItems.value[itemIndex];
  if (!item) return;
  selectedKeys.value = new Set();
  activeKey.value = item.id;
  selectionAnchorKey.value = item.id;
  await nextTick();
  const row = document.getElementById(`${treeId}-row-${activeItemIndex.value}`);
  row?.scrollIntoView({ block: "center", inline: "nearest" });
}

function clearSelection() {
  selectedKeys.value = new Set();
  activeKey.value = null;
  selectionAnchorKey.value = null;
}

type NodeKind = "folderHeader" | "dir" | "file";

function nodeKey(rootPath: string, kind: NodeKind, path: string): string {
  // A path may appear under multiple opened roots, or as both a root and a child.
  return JSON.stringify([normalizeExternalSqlPath(rootPath), kind, normalizeExternalSqlPath(path)]);
}

function isPathHighlighted(rootPath: string, kind: NodeKind, path: string) {
  const key = nodeKey(rootPath, kind, path);
  return activeKey.value === key || selectedKeys.value.has(key);
}

function remapSelectionPaths(mapPath: (path: string) => string | null) {
  const remapKey = (key: string): string | null => {
    const [rootPath, kind, path] = JSON.parse(key) as [string, NodeKind, string];
    const root = mapPath(rootPath);
    const mapped = mapPath(path);
    return root !== null && mapped !== null ? nodeKey(root, kind, mapped) : null;
  };
  selectedKeys.value = new Set([...selectedKeys.value].map(remapKey).filter((key): key is string => key !== null));
  activeKey.value = activeKey.value ? remapKey(activeKey.value) : null;
  selectionAnchorKey.value = selectionAnchorKey.value ? remapKey(selectionAnchorKey.value) : null;
}

function loadSavedFolders(): string[] {
  return getSqlFileFolderPaths();
}

function saveFolders() {
  const paths = folders.value.map((f) => f.path);
  saveSqlFileFolderPaths(paths);
  persistFoldersUiState();
}

async function pickFolder() {
  if (!isTauriRuntime()) {
    toast(t("sqlFileTree.desktopOnly"), 3000);
    return;
  }
  try {
    const { open } = await import("@tauri-apps/plugin-dialog");
    const selected = await open({ directory: true, multiple: false });
    if (!selected) return;
    const folderPath = selected as string;
    if (folders.value.some((f) => f.path === folderPath)) {
      toast(t("sqlFileTree.folderAlreadyOpen"), 2000);
      return;
    }
    await addFolder(folderPath);
  } catch (e: any) {
    toast(t("sqlFileTree.openFailed", { message: e?.message || String(e) }), 5000);
  }
}

async function addFolder(folderPath: string) {
  const folder: FolderState = {
    path: folderPath,
    entries: [],
    expanded: new Set(),
    loading: true,
    refreshing: false,
    collapsed: false,
  };
  folders.value.push(folder);
  saveFolders();
  return loadFolderEntries(folderPath);
}

async function locateCurrentFile() {
  const path = currentFilePath.value;
  if (path) await enqueueFileLocate(path);
}

async function locateFile(path: string) {
  if (disposed) return;
  if (findFileTarget(path)) {
    await locateFileTarget(path);
    return;
  }
  if (!isTauriRuntime()) {
    toast(t("sqlFileTree.desktopOnly"), 3000);
    return;
  }
  locatingFile.value = true;
  try {
    const normalizedPath = normalizeExternalSqlPath(path);
    const folder = folders.value.find((folder) => normalizedPath.startsWith(`${normalizeExternalSqlPath(folder.path).replace(/\/$/, "")}/`));
    if (folder) {
      if (await loadFolderEntries(folder.path)) return;
    } else {
      const slashedPath = path.replace(/\\/g, "/");
      const parentPath = slashedPath.slice(0, slashedPath.lastIndexOf("/") + 1);
      if (!parentPath) return;
      if (await addFolder(parentPath)) return;
    }
    if (disposed) return;
    if (!findFileTarget(path)) {
      toast(t("sqlFileTree.activeFileNotFound"), 5000);
      return;
    }
    await locateFileTarget(path);
  } finally {
    locatingFile.value = false;
  }
}

// Re-scan a single top-level folder and replace its entries. Mutated via the
// reactive proxy (folders.value[idx]) so Vue tracks the change — see the note
// in addFolder above.
//
// `loading` only goes true when the folder has nothing to show yet, because it
// swaps the row list for a "loading" line and the list lives inside the panel's
// only scroll container: tearing the rows down resets `scrollTop` to 0, which is
// what made the panel jump back to the top after every add/rename/refresh
// (#13038). A folder that already has entries stays rendered and is swapped in
// place, so the scroll offset survives; `refreshing` only drives the spinner.
async function loadFolderEntries(folderPath: string): Promise<string | null> {
  cancelFileDrag();
  const idx = folders.value.findIndex((f) => f.path === folderPath);
  if (idx === -1) return null;
  folders.value[idx].loading = folders.value[idx].entries.length === 0;
  folders.value[idx].refreshing = true;
  try {
    const entries = await api.listSqlFilesInFolder(folderPath, getSqlFileFilter(), true);
    const target = folders.value.findIndex((f) => f.path === folderPath);
    if (target !== -1) {
      folders.value[target].entries = entries;
      // Drop expand state for paths that no longer exist after the refresh so
      // stale entries don't keep phantom directories open.
      const stillPresent = new Set<string>();
      collectPaths(entries, stillPresent);
      // Mutations compare normalized paths, while the scanner retains native
      // separators. Rebind UI state to the actual returned node identities.
      const displayPaths = new Map([...stillPresent, folderPath].map((path) => [normalizeExternalSqlPath(path), path]));
      const nextExpanded = new Set<string>();
      for (const p of folders.value[target].expanded) {
        const displayPath = displayPaths.get(normalizeExternalSqlPath(p));
        if (displayPath && stillPresent.has(displayPath)) nextExpanded.add(displayPath);
      }
      folders.value[target].expanded = nextExpanded;
      persistFoldersUiState();
      // Selection keys already normalize both root and entry paths.
    }
  } catch (e: any) {
    const message = e?.message || String(e);
    toast(t("sqlFileTree.loadFailed", { message }), 5000);
    return message;
  } finally {
    const target = folders.value.findIndex((f) => f.path === folderPath);
    if (target !== -1) {
      folders.value[target].loading = false;
      folders.value[target].refreshing = false;
    }
    foldersRevision.value++;
  }
  return null;
}

function collectPaths(entries: SqlFileEntry[], into: Set<string>) {
  for (const e of entries) {
    into.add(e.path);
    if (e.is_dir && e.children.length) collectPaths(e.children, into);
  }
}

async function refreshFolder(folderPath: string) {
  await loadFolderEntries(folderPath);
  notifySqlFileFoldersChanged();
  toast(t("sqlFileTree.refreshed"), 1500);
}

async function refreshAll() {
  await Promise.all(folders.value.map((f) => loadFolderEntries(f.path)));
  notifySqlFileFoldersChanged();
  toast(t("sqlFileTree.refreshed"), 1500);
}

async function saveFileFilter() {
  const previousFilter = getSqlFileFilter();
  if (fileFilterDraft.value.trim() === previousFilter) {
    commitInteractionSettings();
    return;
  }
  saveSqlFileFilter(fileFilterDraft.value);
  const errors = await Promise.all(folders.value.map((f) => loadFolderEntries(f.path)));
  // An unparsable pattern must not survive in localStorage: it would fail
  // every later refresh and silently empty Quick Open until it is fixed.
  const invalidFilter = errors.find((message) => message?.startsWith("Invalid file filter"));
  if (invalidFilter) {
    saveSqlFileFilter(previousFilter);
    await Promise.all(folders.value.map((f) => loadFolderEntries(f.path)));
    toast(t("sqlFileTree.filterInvalid", { message: invalidFilter }), 5000);
    return;
  }
  commitInteractionSettings();
  notifySqlFileFoldersChanged();
  toast(t("sqlFileTree.refreshed"), 1500);
}

function commitInteractionSettings() {
  openMode.value = openModeDraft.value;
  saveSqlFileOpenMode(openMode.value);
  filterSettingsOpen.value = false;
}

async function reloadFolderAfterMutation(folderPath: string) {
  await loadFolderEntries(folderPath);
  notifySqlFileFoldersChanged();
}

async function removeFolder(index: number) {
  cancelFileDrag();
  folders.value.splice(index, 1);
  saveFolders();
  foldersRevision.value++;
}

async function revealInFileManager(path: string) {
  if (!isTauriRuntime()) {
    toast(t("sqlFileTree.desktopOnly"), 3000);
    return;
  }
  try {
    await api.revealPathInFileManager(path);
  } catch (e: any) {
    toast(t("sqlFileTree.revealFailed", { message: translateBackendError(t, e) }), 5000);
  }
}

async function copyPath(path: string) {
  try {
    await copyToClipboard(path);
    toast(t("sqlFileTree.pathCopied"), 1500);
  } catch {
    toast(t("sqlFileTree.copyFailed"), 3000);
  }
}

interface ProcessedFolder {
  entries: SqlFileEntry[];
  autoExpanded: Set<string>;
  hasMatches: boolean;
}

const folderProcessedMap = computed<Map<string, ProcessedFolder>>(() => {
  const map = new Map<string, ProcessedFolder>();
  for (const folder of folders.value) {
    const res = filterAndSortSqlFileEntries(folder.entries, searchQuery.value, sortOrder.value, matchingPaths.value, searchMode.value, manualOrder.value);
    map.set(folder.path, {
      entries: res.entries,
      autoExpanded: res.autoExpanded,
      hasMatches: res.matchCount > 0,
    });
  }
  return map;
});

function getProcessedEntries(folderPath: string): SqlFileEntry[] {
  return folderProcessedMap.value.get(folderPath)?.entries ?? [];
}

function isFolderContentVisible(folder: FolderState): boolean {
  if (userCollapsedDuringSearch.value.has(folder.path)) {
    return false;
  }
  if (searchQuery.value) {
    const processed = folderProcessedMap.value.get(folder.path);
    if (processed?.hasMatches) {
      return true;
    }
  }
  return !folder.collapsed;
}

function getEffectiveExpanded(folder: FolderState): Set<string> {
  if (!searchQuery.value) {
    return folder.expanded;
  }
  const processed = folderProcessedMap.value.get(folder.path);
  const auto = processed?.autoExpanded ?? new Set<string>();
  const combined = new Set<string>();
  for (const p of folder.expanded) {
    if (!userCollapsedDuringSearch.value.has(p)) combined.add(p);
  }
  for (const p of auto) {
    if (!userCollapsedDuringSearch.value.has(p)) combined.add(p);
  }
  return combined;
}

function toggleExpand(folder: FolderState, path: string) {
  const effective = getEffectiveExpanded(folder);
  const isExpanded = effective.has(path);
  if (isExpanded) {
    if (searchQuery.value) {
      userCollapsedDuringSearch.value.add(path);
    }
    const next = new Set(folder.expanded);
    next.delete(path);
    folder.expanded = next;
  } else {
    if (searchQuery.value) {
      userCollapsedDuringSearch.value.delete(path);
    }
    const next = new Set(folder.expanded);
    next.add(path);
    folder.expanded = next;
  }
  persistFoldersUiState();
}

function toggleFolderCollapse(folder: FolderState) {
  if (searchQuery.value) {
    const currentlyVisible = isFolderContentVisible(folder);
    if (currentlyVisible) {
      userCollapsedDuringSearch.value.add(folder.path);
    } else {
      userCollapsedDuringSearch.value.delete(folder.path);
      folder.collapsed = false;
    }
  } else {
    folder.collapsed = !folder.collapsed;
  }
  persistFoldersUiState();
}

// Expand/collapse every directory beneath the given top-level folder.
function setAllExpanded(folder: FolderState, expanded: boolean) {
  if (expanded) {
    const next = new Set(folder.expanded);
    collectDirPaths(folder.entries, next);
    folder.expanded = next;
  } else {
    folder.expanded = new Set();
  }
  persistFoldersUiState();
}

function collectDirPaths(entries: SqlFileEntry[], into: Set<string>) {
  for (const e of entries) {
    if (e.is_dir) {
      into.add(e.path);
      collectDirPaths(e.children, into);
    }
  }
}

async function openFile(path: string, reveal?: { line: number; column: number }) {
  if (!isTauriRuntime()) return;
  try {
    const snapshot = await api.readExternalSqlFileSnapshot(path, externalSqlEditorMaxBytes(settingsStore.editorSettings.externalSqlEditorMaxMb));
    const target = resolveExternalSqlFileTargetForActiveTab(path, queryStore.tabs, queryStore.activeTabId, (connectionId) => connectionStore.getConfig(connectionId));
    queryStore.openExternalSqlFile(target.connectionId, target.database, path, snapshot.content, snapshot.version, target.catalog, target.schema, reveal, snapshot.encoding);
  } catch (e: any) {
    if (!reveal && isExternalSqlFileTooLargeError(e) && isSqlFilePath(path)) {
      executeFile(path);
      toast(t("sqlFile.largeFileExecutionOpened", { size: formatSqlFileSize(e.sizeBytes) }), 6000);
      return;
    }
    toast(t("toolbar.sqlOpenFailed", { message: externalSqlFileOpenErrorMessage(e, (key, params) => t(key, params)) }), 5000);
  }
}

function handleSearchMatch(rootPath: string, path: string, match: SavedSqlLineMatch) {
  const key = nodeKey(rootPath, "file", path);
  selectedKeys.value = new Set();
  activeKey.value = key;
  selectionAnchorKey.value = key;
  void openFile(path, { line: match.lineNumber, column: match.column });
}

// Open the App-level SQL file execution dialog with this file pre-selected so
// the user can review its statements and pick a connection/database before run.
function executeFile(path: string) {
  const target = resolveExternalSqlFileTargetForActiveTab(path, queryStore.tabs, queryStore.activeTabId, (connectionId) => connectionStore.getConfig(connectionId));
  connectionStore.sqlFileSource = {
    connectionId: target.connectionId,
    database: target.database,
    ...(target.schema ? { schema: target.schema } : {}),
    filePath: path,
  };
}

function folderName(path: string): string {
  const normalized = path.replace(/\\/g, "/");
  const parts = normalized.split("/").filter(Boolean);
  return parts.pop() || path;
}

let disposed = false;
const foldersInitialized = ref(false);
let locateQueue: Promise<void> = Promise.resolve();

function enqueueFileLocate(path: string): Promise<void> {
  // Keep scans serialized, while retaining the requested path across focus changes.
  locateQueue = locateQueue
    .then(() => locateFile(path))
    .catch((error) => {
      if (!disposed) toast(t("sqlFileTree.loadFailed", { message: translateBackendError(t, error) }), 5000);
    });
  return locateQueue;
}

watch([foldersInitialized, () => props.locateRequest], async ([initialized, request]) => {
  if (!initialized || !request) return;
  await enqueueFileLocate(request.path);
  if (!disposed) emit("locate-handled", request.id);
});

onBeforeUnmount(() => {
  disposed = true;
  persistFoldersUiState();
});

onMounted(async () => {
  // Restoring folders must not persist a partially loaded list. Register all
  // roots before scanning so closing the panel cannot discard saved roots.
  const saved = loadSavedFolders();
  const uiStates = getSqlFileFoldersUiState();
  folders.value = saved.map((path) => {
    const ui = uiStates[path];
    return {
      path,
      entries: [],
      expanded: new Set<string>(ui?.expanded ?? []),
      loading: true,
      refreshing: false,
      collapsed: ui?.collapsed === true,
    };
  });
  uiStateInitialized = true;
  for (const path of saved) {
    if (disposed) return;
    await loadFolderEntries(path);
  }
  if (!disposed) foldersInitialized.value = true;
});

type TreeEntry = { entry: SqlFileEntry; depth: number };
function flatTree(entries: SqlFileEntry[], expanded: Set<string>): TreeEntry[] {
  const result: TreeEntry[] = [];
  function walk(items: SqlFileEntry[], depth: number) {
    for (const item of items) {
      result.push({ entry: item, depth });
      if (item.is_dir && expanded.has(item.path)) {
        walk(item.children, depth + 1);
      }
    }
  }
  walk(entries, 0);
  return result;
}

type VisibleItem = OrderedListSelectionItem & { type: NodeKind; path: string; folder: FolderState; entry?: SqlFileEntry };
const visibleItems = computed<VisibleItem[]>(() => {
  const items: VisibleItem[] = [];
  for (const folder of folders.value) {
    items.push({ type: "folderHeader", id: nodeKey(folder.path, "folderHeader", folder.path), path: folder.path, folder });
    if (folder.loading || !isFolderContentVisible(folder)) continue;
    for (const { entry } of flatTree(getProcessedEntries(folder.path), getEffectiveExpanded(folder))) {
      const type = entry.is_dir ? "dir" : "file";
      items.push({ type, id: nodeKey(folder.path, type, entry.path), path: entry.path, folder, entry });
    }
  }
  return items;
});

const {
  source: draggedFile,
  target: fileDropTarget,
  start: startFileDrag,
  cancel: cancelFileDrag,
} = useSqlFileReorder({
  tree: fileTree,
  enabled: () =>
    !searchQuery.value &&
    selectedKeys.value.size === 0 &&
    !folders.value.some((folder) => folder.loading || folder.refreshing) &&
    !folderMutationPending.value &&
    !contextTarget.value &&
    !filterSettingsOpen.value &&
    !showCreateDialog.value &&
    !showCreateFolderDialog.value &&
    !showRenameDialog.value &&
    !showRenameFolderDialog.value &&
    !showDeleteDialog.value &&
    !showDeleteFolderDialog.value,
  files: () => visibleItems.value.filter((item) => item.type === "file").map((item) => ({ root: item.folder.path, path: item.path, name: item.entry!.name })),
  drop: (source, target) => {
    // Re-check the current tree; a refresh or mutation may have removed a node.
    const siblings = visibleItems.value.filter((item) => item.type === "file" && item.folder.path === source.root && sqlFileParentPath(item.path) === sqlFileParentPath(source.path));
    const next = reorderSqlFiles(
      manualOrder.value,
      siblings.map((item) => item.path),
      source.path,
      target.path,
      target.position,
    );
    if (!next) return;
    if (!saveSqlFileOrder(next)) {
      toast(t("sqlFileTree.sortSaveFailed"), 5000);
      return;
    }
    // A completed drag selects manual ordering; a click or cancelled drag must
    // leave the current name sort and saved manual order untouched.
    if (sortOrder.value !== "manual" && !saveSqlFileSortOrder("manual")) {
      saveSqlFileOrder(manualOrder.value);
      toast(t("sqlFileTree.sortSaveFailed"), 5000);
      return;
    }
    manualOrder.value = next;
    sortOrder.value = "manual";
    activeKey.value = nodeKey(source.root, "file", source.path);
    selectionAnchorKey.value = activeKey.value;
    focusTree();
  },
});

watch(visibleItems, () => cancelFileDrag());

const visibleRowIds = computed(() => {
  const ids = new Map<FolderState, Map<string, string>>();
  visibleItems.value.forEach((item, index) => {
    let folderIds = ids.get(item.folder);
    if (!folderIds) {
      folderIds = new Map();
      ids.set(item.folder, folderIds);
    }
    folderIds.set(item.path, `${treeId}-row-${index}`);
  });
  return ids;
});

const activeItemIndex = computed(() => visibleItems.value.findIndex((item) => item.id === activeKey.value));

function focusTree() {
  fileTree.value?.focus({ preventScroll: true });
}

function restoreTreeFocus(event: Event) {
  event.preventDefault();
  focusTree();
}

async function scrollActiveRow() {
  await nextTick();
  document.getElementById(`${treeId}-row-${activeItemIndex.value}`)?.scrollIntoView({ block: "nearest" });
}

// Preserve selection while content-only hits temporarily disappear during a
// scan. Watching the pending flags also reconciles selection after an error.
watch([visibleItems, searching, () => folders.value.some((folder) => folder.loading || folder.refreshing)], ([items, searchPending, foldersPending], [previous]) => {
  if (searchPending || foldersPending) return;
  const ids = new Set(items.map((item) => item.id));
  selectedKeys.value = new Set([...selectedKeys.value].filter((key) => ids.has(key)));
  if (activeKey.value && !ids.has(activeKey.value)) {
    const oldIndex = previous.findIndex((item) => item.id === activeKey.value);
    activeKey.value = items[Math.min(Math.max(oldIndex, 0), items.length - 1)]?.id ?? null;
  }
  // Resolve the anchor by identity: callers may have already selected a node
  // in the new list before this watcher runs (for example, Locate Current File).
  if (selectionAnchorKey.value && !ids.has(selectionAnchorKey.value)) {
    selectionAnchorKey.value = activeKey.value;
  }
  if (document.activeElement === fileTree.value) void scrollActiveRow();
});

function activateItem(item: VisibleItem) {
  if (item.folder.loading) return;
  if (item.type === "folderHeader") toggleFolderCollapse(item.folder);
  else if (item.type === "dir") toggleExpand(item.folder, item.path);
  else void openFile(item.path);
}

function handleTreeKeydown(event: KeyboardEvent) {
  if (event.target !== fileTree.value || event.isComposing || event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) return;
  if (contextTarget.value || filterSettingsOpen.value || showCreateDialog.value || showCreateFolderDialog.value || showRenameDialog.value || showRenameFolderDialog.value || showDeleteDialog.value || showDeleteFolderDialog.value) return;
  const items = visibleItems.value;
  if (!items.length) return;
  const index = activeItemIndex.value;
  if (event.key === "ArrowUp" || event.key === "ArrowDown") {
    const nextIndex = index < 0 ? (event.key === "ArrowDown" ? 0 : items.length - 1) : Math.max(0, Math.min(items.length - 1, index + (event.key === "ArrowDown" ? 1 : -1)));
    activeKey.value = items[nextIndex].id;
    selectedKeys.value = new Set();
    selectionAnchorKey.value = items[nextIndex].id;
    void scrollActiveRow();
  } else if (event.key === "Enter" || event.key === " " || event.key === "F2") {
    const item = items[index];
    if (!item || [...selectedKeys.value].some((key) => key !== item.id)) return;
    if (event.key === "F2") {
      if (!item.entry || item.folder.loading) return;
      if (!event.repeat) {
        if (item.type === "dir") openRenameFolderDialog({ kind: "dir", folderPath: item.folder.path, entry: item.entry });
        else openRenameDialog({ kind: "file", folderPath: item.folder.path, entry: item.entry });
      }
    } else if (!event.repeat) activateItem(item);
  } else return;
  event.preventDefault();
  event.stopPropagation();
}

function handlePathDoubleClick(rootPath: string, path: string, type: NodeKind, event: MouseEvent) {
  event.stopPropagation();
  if ((event.target as HTMLElement | null)?.closest("button, input, select, textarea, [contenteditable='true']")) return;
  if (openMode.value !== "double" || orderedListSelectionIntent(event) !== "single" || event.altKey) return;
  const key = nodeKey(rootPath, type, path);
  const item = visibleItems.value.find((item) => item.id === key);
  if (item) activateItem(item);
}

function selectedRangeAnchorIndex() {
  const anchorIndex = visibleItems.value.findIndex((item) => item.id === selectionAnchorKey.value);
  if (anchorIndex >= 0) return anchorIndex;
  return activeItemIndex.value >= 0 ? activeItemIndex.value : null;
}

function selectRangeTo(currentIndex: number) {
  const anchorIndex = selectedRangeAnchorIndex();
  if (anchorIndex === null) {
    const current = visibleItems.value[currentIndex];
    selectedKeys.value = new Set(current ? [current.id] : []);
    selectionAnchorKey.value = current?.id ?? null;
    return;
  }

  const start = Math.min(anchorIndex, currentIndex);
  const end = Math.max(anchorIndex, currentIndex);
  const next = new Set(selectedKeys.value);
  for (let i = start; i <= end; i++) {
    const item = visibleItems.value[i];
    if (item) next.add(item.id);
  }
  selectedKeys.value = next;
}

function handlePathClick(rootPath: string, path: string, type: NodeKind, event: MouseEvent) {
  const key = nodeKey(rootPath, type, path);
  const currentIndex = visibleItems.value.findIndex((item) => item.id === key);
  if (currentIndex < 0) return;

  focusTree();
  const repeatedClick = event.detail > 1 && lastClickedKey === key;
  lastClickedKey = key;
  const selectionIntent = orderedListSelectionIntent(event);
  if (selectionIntent === "range") {
    event.preventDefault();
    event.stopPropagation();
    selectRangeTo(currentIndex);
    return;
  }
  if (selectionIntent === "toggle") {
    event.preventDefault();
    event.stopPropagation();
    const next = new Set(selectedKeys.value);
    if (next.has(key)) next.delete(key);
    else next.add(key);
    selectedKeys.value = next;
    selectionAnchorKey.value = key;
    return;
  }

  selectedKeys.value = new Set();
  activeKey.value = key;
  selectionAnchorKey.value = key;
  if (openMode.value === "single" && !repeatedClick) activateItem(visibleItems.value[currentIndex]);
}

function handlePanelClick(event: MouseEvent) {
  const target = event.target as HTMLElement | null;
  if (!target?.closest("[data-sql-file-row='true']")) clearSelection();
}

function normalizedSqlFileName(name: string) {
  const trimmed = name.trim();
  return isSqlFilePath(trimmed) ? trimmed : `${trimmed}.sql`;
}

function normalizedRenamedFileName(name: string, currentName: string) {
  const trimmed = name.trim();
  return isSqlFilePath(currentName) ? normalizedSqlFileName(trimmed) : trimmed;
}

function openCreateDialog(rootPath: string, directoryPath: string) {
  createTarget.value = { rootPath, directoryPath };
  fileNameInput.value = "";
  showCreateDialog.value = true;
}

function isWithinFolder(path: string, folderPath: string) {
  const normalized = normalizeExternalSqlPath(path);
  const root = normalizeExternalSqlPath(folderPath);
  return normalized === root || normalized.startsWith(`${root}/`);
}

function updateFolderPaths(previousPath: string, nextPath?: string) {
  const previous = normalizeExternalSqlPath(previousPath);
  const mapPath = (path: string) => {
    if (!isWithinFolder(path, previous)) return path;
    return nextPath ? (relocateExternalSqlPathWithinFolder(path, previousPath, nextPath) ?? path) : null;
  };
  const mapSet = (paths: Set<string>) => new Set([...paths].map(mapPath).filter((path): path is string => path !== null));
  folders.value = folders.value.filter((folder) => {
    const mapped = mapPath(folder.path);
    if (mapped === null) return false;
    folder.path = mapped;
    folder.expanded = mapSet(folder.expanded);
    return true;
  });
  remapSelectionPaths(mapPath);
  saveFolders();
}

async function refreshMutationFolders() {
  await Promise.all(folders.value.map((folder) => loadFolderEntries(folder.path)));
  notifySqlFileFoldersChanged();
}

function openCreateFolderDialog(rootPath: string, directoryPath: string) {
  if (folderMutationPending.value) return;
  createTarget.value = { rootPath, directoryPath };
  fileNameInput.value = "";
  showCreateFolderDialog.value = true;
}

async function createSqlFolder() {
  const target = createTarget.value;
  if (folderMutationPending.value || !target || !fileNameInput.value.trim()) return;
  folderMutationPending.value = true;
  try {
    const path = await api.createSqlFolderInFolder(target.rootPath, target.directoryPath, fileNameInput.value.trim());
    showCreateFolderDialog.value = false;
    await refreshMutationFolders();
    const folder = folders.value.find((item) => item.path === target.rootPath);
    if (folder) {
      folder.collapsed = false;
      folder.expanded = new Set([...folder.expanded, target.directoryPath, path]);
      persistFoldersUiState();
    }
    activeKey.value = nodeKey(target.rootPath, "dir", path);
    selectedKeys.value = new Set();
    selectionAnchorKey.value = activeKey.value;
    await scrollActiveRow();
    toast(t("sqlFileTree.folderCreated"), 1500);
  } catch (e: any) {
    toast(t("sqlFileTree.createFolderFailed", { message: translateBackendError(t, e) }), 5000);
  } finally {
    folderMutationPending.value = false;
  }
}

async function createSqlFile() {
  const target = createTarget.value;
  if (!target || !fileNameInput.value.trim()) return;
  try {
    const path = await api.createSqlFileInFolder(target.rootPath, target.directoryPath, normalizedSqlFileName(fileNameInput.value));
    showCreateDialog.value = false;
    await reloadFolderAfterMutation(target.rootPath);
    await openFile(path);
    toast(t("sqlFileTree.fileCreated"), 1500);
  } catch (e: any) {
    toast(t("sqlFileTree.createFailed", { message: translateBackendError(t, e) }), 5000);
  }
}

function openRenameDialog(target: Extract<ContextTarget, { kind: "file" }>) {
  renameTarget.value = target;
  fileNameInput.value = target.entry.name.replace(/\.sql$/i, "");
  showRenameDialog.value = true;
}

function openRenameFolderDialog(target: Extract<ContextTarget, { kind: "dir" }>) {
  if (folderMutationPending.value) return;
  renameFolderTarget.value = target;
  fileNameInput.value = target.entry.name;
  showRenameFolderDialog.value = true;
}

async function renameSqlFolder() {
  const target = renameFolderTarget.value;
  if (folderMutationPending.value || !target || !fileNameInput.value.trim()) return;
  folderMutationPending.value = true;
  try {
    const nextPath = await api.renameSqlFolderInFolder(target.folderPath, target.entry.path, fileNameInput.value.trim());
    queryStore.relocateExternalSqlFolderPath(target.entry.path, nextPath);
    moveExternalSqlFolderTargets(target.entry.path, nextPath);
    remapManualOrder(target.entry.path, nextPath, true);
    updateFolderPaths(target.entry.path, nextPath);
    showRenameFolderDialog.value = false;
    await refreshMutationFolders();
    toast(t("sqlFileTree.folderRenamed"), 1500);
  } catch (e: any) {
    toast(t("sqlFileTree.renameFolderFailed", { message: translateBackendError(t, e) }), 5000);
  } finally {
    folderMutationPending.value = false;
  }
}

async function renameSqlFile() {
  const target = renameTarget.value;
  if (!target || !fileNameInput.value.trim()) return;
  try {
    const nextPath = await api.renameSqlFileInFolder(target.folderPath, target.entry.path, normalizedRenamedFileName(fileNameInput.value, target.entry.name));
    // Renaming does not change content, and re-reading here would make a
    // successful rename appear to fail for files too large for the editor.
    queryStore.relocateExternalSqlFilePath(target.entry.path, nextPath);
    moveExternalSqlFileTarget(target.entry.path, nextPath);
    remapManualOrder(target.entry.path, nextPath);
    remapSelectionPaths((path) => (normalizeExternalSqlPath(path) === normalizeExternalSqlPath(target.entry.path) ? nextPath : path));
    showRenameDialog.value = false;
    await reloadFolderAfterMutation(target.folderPath);
    toast(t("sqlFileTree.fileRenamed"), 1500);
  } catch (e: any) {
    toast(t("sqlFileTree.renameFailed", { message: translateBackendError(t, e) }), 5000);
  }
}

function openDeleteDialog(target: Extract<ContextTarget, { kind: "file" }>) {
  deleteTarget.value = target;
  showDeleteDialog.value = true;
}

function openDeleteFolderDialog(target: Extract<ContextTarget, { kind: "dir" }>) {
  if (folderMutationPending.value) return;
  deleteFolderTarget.value = target;
  showDeleteFolderDialog.value = true;
}

async function deleteSqlFolder() {
  const target = deleteFolderTarget.value;
  if (folderMutationPending.value || !target) return;
  folderMutationPending.value = true;
  try {
    await api.deleteSqlFolderInFolder(target.folderPath, target.entry.path);
    queryStore.markExternalSqlFolderMissingForPath(target.entry.path);
    forgetExternalSqlFolderTargets(target.entry.path);
    remapManualOrder(target.entry.path, undefined, true);
    updateFolderPaths(target.entry.path);
    showDeleteFolderDialog.value = false;
    await refreshMutationFolders();
    toast(t("sqlFileTree.folderDeleted"), 1500);
  } catch (e: any) {
    // Recursive deletion can fail after removing some children. Inspect actual
    // disk state, including tabs hidden by the file-name filter.
    // Closed files can also have persisted targets, so the entire subtree is
    // untrusted after a non-atomic delete attempt.
    forgetExternalSqlFolderTargets(target.entry.path);
    await Promise.all(
      queryStore.tabs
        .filter((tab) => tab.externalSqlPath && isWithinFolder(tab.externalSqlPath, target.entry.path))
        .map(async (tab) => {
          const path = tab.externalSqlPath!;
          try {
            if ((await api.inspectExternalSqlFile(path)).kind === "missing") {
              queryStore.markExternalSqlFileMissingForPath(path);
              forgetExternalSqlFileTarget(path);
            }
          } catch {
            // Keep the editor intact when the path cannot be inspected.
          }
        }),
    );
    await refreshMutationFolders();
    toast(t("sqlFileTree.deleteFolderFailed", { message: translateBackendError(t, e) }), 5000);
  } finally {
    folderMutationPending.value = false;
  }
}

async function deleteSqlFile() {
  const target = deleteTarget.value;
  if (!target) return;
  try {
    await api.deleteSqlFileInFolder(target.folderPath, target.entry.path);
    remapManualOrder(target.entry.path);
    queryStore.markExternalSqlFileMissingForPath(target.entry.path);
    forgetExternalSqlFileTarget(target.entry.path);
    showDeleteDialog.value = false;
    await reloadFolderAfterMutation(target.folderPath);
    toast(t("sqlFileTree.fileDeleted"), 1500);
  } catch (e: any) {
    toast(t("sqlFileTree.deleteFailed", { message: translateBackendError(t, e) }), 5000);
  }
}

// ---- context menu ----
const contextMenuItems = computed<ContextMenuItem[]>(() => {
  const target = contextTarget.value;
  if (!target) return [];

  if (target.kind === "panel") {
    const items: ContextMenuItem[] = [{ label: t("sqlFileTree.openFolder"), action: pickFolder, icon: FolderOpen }];
    if (folders.value.length > 0) {
      items.push({ label: "", separator: true });
      items.push({
        label: t("sqlLibrary.sortFiles"),
        icon: ArrowDownAZ,
        children: [
          { label: t("sqlFileTree.sortManual"), action: () => setSortOrder("manual"), icon: GripVertical },
          { label: t("sqlLibrary.sortNameAsc"), action: () => setSortOrder("asc"), icon: ArrowDownAZ },
          { label: t("sqlLibrary.sortNameDesc"), action: () => setSortOrder("desc"), icon: ArrowUpAZ },
        ],
      });
      items.push({ label: "", separator: true });
      items.push({ label: t("sqlFileTree.refreshAll"), action: refreshAll, icon: RefreshCw });
    }
    return items;
  }

  if (target.kind === "folderHeader") {
    const folderIdx = folders.value.findIndex((f) => f.path === target.folderPath);
    const folder = folderIdx !== -1 ? folders.value[folderIdx] : undefined;
    return [
      { label: t("sqlFileTree.newSqlFile"), action: () => openCreateDialog(target.folderPath, target.folderPath), icon: FilePlus },
      { label: t("sqlFileTree.newFolder"), action: () => openCreateFolderDialog(target.folderPath, target.folderPath), icon: FolderPlus },
      { label: "", separator: true },
      { label: t("sqlFileTree.revealInFileManager"), action: () => revealInFileManager(target.folderPath), icon: FolderSearch },
      { label: t("sqlFileTree.copyPath"), action: () => copyPath(target.folderPath), icon: Copy },
      { label: "", separator: true },
      { label: t("sqlFileTree.expandAll"), action: () => folder && setAllExpanded(folder, true), icon: ChevronsUpDown, disabled: !folder },
      { label: t("sqlFileTree.collapseAll"), action: () => folder && setAllExpanded(folder, false), icon: ChevronsDownUp, disabled: !folder },
      { label: "", separator: true },
      {
        label: t("sqlLibrary.sortFiles"),
        icon: ArrowDownAZ,
        children: [
          { label: t("sqlFileTree.sortManual"), action: () => setSortOrder("manual"), icon: GripVertical },
          { label: t("sqlLibrary.sortNameAsc"), action: () => setSortOrder("asc"), icon: ArrowDownAZ },
          { label: t("sqlLibrary.sortNameDesc"), action: () => setSortOrder("desc"), icon: ArrowUpAZ },
        ],
      },
      { label: "", separator: true },
      { label: t("sqlFileTree.refreshFolder"), action: () => refreshFolder(target.folderPath), icon: RefreshCw },
      { label: "", separator: true },
      { label: t("sqlFileTree.removeFolder"), action: () => folderIdx !== -1 && removeFolder(folderIdx), icon: Trash2, variant: "destructive" },
    ];
  }

  if (target.kind === "dir") {
    return [
      { label: t("sqlFileTree.newSqlFile"), action: () => openCreateDialog(target.folderPath, target.entry.path), icon: FilePlus },
      { label: t("sqlFileTree.newFolder"), action: () => openCreateFolderDialog(target.folderPath, target.entry.path), icon: FolderPlus },
      { label: "", separator: true },
      { label: t("sqlFileTree.revealInFileManager"), action: () => revealInFileManager(target.entry.path), icon: FolderSearch },
      { label: t("sqlFileTree.copyPath"), action: () => copyPath(target.entry.path), icon: Copy },
      { label: "", separator: true },
      { label: t("sqlFileTree.expandAll"), action: () => expandSubtree(target), icon: ChevronsUpDown },
      { label: t("sqlFileTree.collapseAll"), action: () => collapseSubtree(target), icon: ChevronsDownUp },
      { label: "", separator: true },
      {
        label: t("sqlLibrary.sortFiles"),
        icon: ArrowDownAZ,
        children: [
          { label: t("sqlFileTree.sortManual"), action: () => setSortOrder("manual"), icon: GripVertical },
          { label: t("sqlLibrary.sortNameAsc"), action: () => setSortOrder("asc"), icon: ArrowDownAZ },
          { label: t("sqlLibrary.sortNameDesc"), action: () => setSortOrder("desc"), icon: ArrowUpAZ },
        ],
      },
      { label: "", separator: true },
      { label: t("sqlFileTree.renameFolder"), action: () => openRenameFolderDialog(target), icon: Pencil },
      { label: t("sqlFileTree.deleteFolder"), action: () => openDeleteFolderDialog(target), icon: Trash2, variant: "destructive" },
    ];
  }

  // file
  const items: ContextMenuItem[] = [{ label: t("sqlFileTree.openFile"), action: () => openFile(target.entry.path), icon: FileCode }];
  if (isSqlFilePath(target.entry.name)) {
    items.push({ label: t("sqlFileTree.executeSqlFile"), action: () => executeFile(target.entry.path), icon: Play });
  }
  items.push(
    { label: "", separator: true },
    { label: t("sqlFileTree.revealInFileManager"), action: () => revealInFileManager(target.entry.path), icon: FolderSearch },
    { label: t("sqlFileTree.copyPath"), action: () => copyPath(target.entry.path), icon: Copy },
    { label: "", separator: true },
    { label: t("sqlFileTree.renameFile"), action: () => openRenameDialog(target), icon: Pencil },
    { label: "", separator: true },
    { label: t("sqlFileTree.deleteFile"), action: () => openDeleteDialog(target), icon: Trash2, variant: "destructive" },
  );
  return items;
});

function expandSubtree(target: Extract<ContextTarget, { kind: "dir" }>) {
  const folder = folders.value.find((f) => f.path === target.folderPath);
  if (!folder) return;
  const next = new Set(folder.expanded);
  next.add(target.entry.path);
  collectDirPaths(target.entry.children, next);
  folder.expanded = next;
  persistFoldersUiState();
}

function collapseSubtree(target: Extract<ContextTarget, { kind: "dir" }>) {
  const folder = folders.value.find((f) => f.path === target.folderPath);
  if (!folder) return;
  const subtree = new Set<string>();
  collectDirPaths(target.entry.children, subtree);
  subtree.add(target.entry.path);
  const next = new Set<string>();
  for (const p of folder.expanded) {
    if (!subtree.has(p)) next.add(p);
  }
  folder.expanded = next;
  persistFoldersUiState();
}

function clearContextTarget() {
  contextTarget.value = null;
}
</script>

<template>
  <div class="h-full flex flex-col overflow-hidden isolate">
    <div class="h-9 flex items-center gap-1 px-2 border-b shrink-0 bg-muted/20">
      <span class="text-[13px] font-medium">{{ t("sqlFileTree.title") }}</span>
      <HelpTooltip :label="t('sqlFileTree.storageHelp')" side="bottom" :side-offset="4" trigger-class="h-4 w-4" content-class="max-w-[320px] whitespace-pre-line">
        {{ t("sqlFileTree.storageHelp") }}
      </HelpTooltip>
      <span class="flex-1" />
      <LightTooltip :text="t('sqlFileTree.locateActiveFile')" side="bottom" :delay="0" :close-delay="0" nowrap>
        <SidebarLocateButton class="disabled:pointer-events-none disabled:opacity-50" :label="t('sqlFileTree.locateActiveFile')" :disabled="!currentFilePath || locatingFile || folders.some((folder) => folder.loading || folder.refreshing)" @locate="locateCurrentFile" />
      </LightTooltip>
      <LightTooltip :text="t('sqlFileTree.panelSettings')" side="bottom" :delay="0" :close-delay="0" nowrap>
        <Button
          variant="ghost"
          size="icon"
          class="h-5 w-5"
          @click="
            fileFilterDraft = getSqlFileFilter();
            openModeDraft = openMode;
            filterSettingsOpen = true;
          "
        >
          <Settings class="h-3 w-3" />
        </Button>
      </LightTooltip>
      <DropdownMenu>
        <LightTooltip :text="sortOrder === 'manual' ? t('sqlFileTree.sortManualHint') : currentSortOption.label" side="bottom" :delay="0" :close-delay="0" nowrap>
          <DropdownMenuTrigger as-child>
            <Button data-sql-file-sort-btn variant="ghost" size="icon" class="h-5 w-5" :aria-label="currentSortOption.label">
              <component :is="currentSortOption.icon" class="h-3 w-3" />
            </Button>
          </DropdownMenuTrigger>
        </LightTooltip>
        <DropdownMenuContent align="end" @close-auto-focus="restoreTreeFocus">
          <DropdownMenuItem v-for="option in sortOptions" :key="option.order" class="gap-2" @select="setSortOrder(option.order)">
            <component :is="option.icon" class="h-3.5 w-3.5" />
            {{ option.label }}
            <Check v-if="sortOrder === option.order" class="ml-auto h-3.5 w-3.5" />
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
      <LightTooltip v-if="folders.length > 0" :text="t('sqlFileTree.refreshAll')" side="bottom" :delay="0" :close-delay="0" nowrap>
        <Button variant="ghost" size="icon" class="h-5 w-5" @click="refreshAll">
          <RefreshCw class="h-3 w-3" />
        </Button>
      </LightTooltip>
      <LightTooltip :text="t('sqlFileTree.openFolder')" side="bottom" :delay="0" :close-delay="0" nowrap>
        <Button variant="ghost" size="icon" class="h-5 w-5" @click="pickFolder">
          <FolderOpen class="h-3 w-3" />
        </Button>
      </LightTooltip>
      <LightTooltip :text="t('sqlFileTree.closePanel')" side="bottom" :delay="0" :close-delay="0" nowrap>
        <Button variant="ghost" size="icon" class="h-5 w-5" @click="emit('close')">
          <X class="h-3 w-3" />
        </Button>
      </LightTooltip>
    </div>

    <div v-if="folders.length > 0" class="border-b shrink-0 px-2 py-1">
      <SqlPanelSearch ref="searchInput" v-model:mode="searchMode" panel="file" @query="searchQuery = $event" @pending="searchInputPending = $event" />
      <p v-if="searching" class="mt-1 text-xs text-muted-foreground" role="status" aria-live="polite">{{ t("sqlFileTree.searching") }}</p>
      <p v-else-if="searchError" class="mt-1 text-xs text-destructive" role="status">{{ t("sqlFileTree.searchFailed", { message: translateBackendError(t, searchError) }) }}</p>
      <p v-else-if="searchIncomplete" class="mt-1 text-xs text-muted-foreground" role="status">
        {{ t("sqlFileTree.searchIncomplete", { skipped: skippedCount }) }}
        <HelpTooltip :label="searchIncompleteHelp" side="bottom" :side-offset="4" trigger-class="ml-1 align-middle" content-class="max-w-[320px] whitespace-pre-line" />
      </p>
    </div>

    <CustomContextMenu :items="contextMenuItems" @close="clearContextTarget">
      <template #default="{ onContextMenu }">
        <div
          ref="fileTree"
          class="flex-1 overflow-y-auto focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring"
          tabindex="0"
          role="tree"
          :aria-label="t('sqlFileTree.title')"
          aria-multiselectable="true"
          :aria-activedescendant="activeItemIndex >= 0 ? `${treeId}-row-${activeItemIndex}` : undefined"
          @keydown="handleTreeKeydown"
          @click="handlePanelClick"
          @contextmenu.capture="contextTarget = { kind: 'panel' }"
          @contextmenu.prevent="
            contextTarget = { kind: 'panel' };
            onContextMenu($event);
          "
        >
          <div v-if="folders.length === 0" class="flex-1 flex flex-col items-center justify-center gap-2 p-4 text-xs text-muted-foreground">
            <FolderOpen class="h-8 w-8 text-muted-foreground/40" />
            <span>{{ t("sqlFileTree.noFolder") }}</span>
            <Button variant="outline" size="sm" class="h-7 text-xs" @click="pickFolder"> <FolderOpen class="h-3.5 w-3.5 mr-1" />{{ t("sqlFileTree.openFolder") }} </Button>
          </div>

          <div v-else>
            <div v-for="(folder, fi) in folders" :key="folder.path" class="border-b last:border-b-0">
              <div
                data-sql-file-row="true"
                class="flex cursor-default items-center gap-1 px-2 py-1.5 text-[11px] font-medium text-muted-foreground bg-[color-mix(in_oklab,var(--muted)_10%,var(--background))] sticky top-0 z-10 select-none"
                :class="isPathHighlighted(folder.path, 'folderHeader', folder.path) ? 'bg-accent text-accent-foreground' : 'hover:bg-[color-mix(in_oklab,var(--accent)_40%,var(--background))]'"
                role="treeitem"
                :id="visibleRowIds.get(folder)?.get(folder.path)"
                :aria-level="1"
                :aria-selected="isPathHighlighted(folder.path, 'folderHeader', folder.path)"
                :aria-expanded="isFolderContentVisible(folder)"
                @click.stop="handlePathClick(folder.path, folder.path, 'folderHeader', $event)"
                @dblclick.stop="handlePathDoubleClick(folder.path, folder.path, 'folderHeader', $event)"
                @contextmenu.capture="
                  contextTarget = { kind: 'folderHeader', folderPath: folder.path };
                  activeKey = nodeKey(folder.path, 'folderHeader', folder.path);
                "
                @contextmenu.prevent="
                  contextTarget = { kind: 'folderHeader', folderPath: folder.path };
                  activeKey = nodeKey(folder.path, 'folderHeader', folder.path);
                  onContextMenu($event);
                "
              >
                <ChevronRight v-if="!isFolderContentVisible(folder)" class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                <ChevronDown v-else class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                <FolderOpen class="h-3.5 w-3.5 shrink-0 text-amber-500" />
                <span class="truncate shrink-0" :title="folder.path">{{ folderName(folder.path) }}</span>
                <span class="truncate flex-1 text-[10px] text-muted-foreground/50" :title="folder.path">{{ folder.path }}</span>
                <LightTooltip :text="t('sqlFileTree.refreshFolder')" side="bottom" :delay="0" :close-delay="0" nowrap>
                  <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" @click.stop="refreshFolder(folder.path)">
                    <RefreshCw class="h-3 w-3" :class="folder.loading || folder.refreshing ? 'animate-spin' : ''" />
                  </Button>
                </LightTooltip>
                <LightTooltip :text="t('sqlFileTree.newSqlFile')" side="bottom" :delay="0" :close-delay="0" nowrap>
                  <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" @click.stop="openCreateDialog(folder.path, folder.path)">
                    <FilePlus class="h-3 w-3" />
                  </Button>
                </LightTooltip>
                <LightTooltip :text="t('sqlFileTree.newFolder')" side="bottom" :delay="0" :close-delay="0" nowrap>
                  <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" @click.stop="openCreateFolderDialog(folder.path, folder.path)">
                    <FolderPlus class="h-3 w-3" />
                  </Button>
                </LightTooltip>
                <LightTooltip :text="t('sqlFileTree.revealInFileManager')" side="bottom" :delay="0" :close-delay="0" nowrap>
                  <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" @click.stop="revealInFileManager(folder.path)">
                    <FolderSearch class="h-3 w-3" />
                  </Button>
                </LightTooltip>
                <LightTooltip :text="t('sqlFileTree.removeFolder')" side="bottom" :delay="0" :close-delay="0" nowrap>
                  <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-destructive" @click.stop="removeFolder(fi)">
                    <Trash2 class="h-3 w-3" />
                  </Button>
                </LightTooltip>
              </div>
              <div v-show="isFolderContentVisible(folder)">
                <div v-if="folder.loading" class="px-3 py-2 text-xs text-muted-foreground">
                  {{ t("sqlFileTree.loading") }}
                </div>
                <div v-else-if="folder.entries.length === 0" class="px-3 py-2 text-xs text-muted-foreground">
                  {{ t("sqlFileTree.noSqlFiles") }}
                </div>
                <div v-else-if="searchQuery && !searching && !searchError && !searchIncomplete && getProcessedEntries(folder.path).length === 0" data-sql-file-empty-search class="px-3 py-2 text-xs text-muted-foreground">
                  {{ t("grid.noSearchResults") }}
                </div>
                <div v-else>
                  <template v-for="{ entry, depth } in flatTree(getProcessedEntries(folder.path), getEffectiveExpanded(folder))" :key="entry.path">
                    <div
                      data-sql-file-row="true"
                      :data-sql-file-path="entry.path"
                      :data-sql-file-root="folder.path"
                      :aria-current="activeKey === nodeKey(folder.path, entry.is_dir ? 'dir' : 'file', entry.path) ? 'true' : undefined"
                      class="relative flex cursor-default select-none items-center gap-1 px-2 py-1 text-sm"
                      :class="[
                        draggedFile?.root === folder.path && draggedFile.path === entry.path ? 'opacity-50' : '',
                        entry.is_dir ? 'rounded-sm' : 'rounded-none',
                        isPathHighlighted(folder.path, entry.is_dir ? 'dir' : 'file', entry.path) ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/40',
                      ]"
                      :style="{ paddingLeft: depth * 16 + 8 + 'px' }"
                      role="treeitem"
                      :id="visibleRowIds.get(folder)?.get(entry.path)"
                      :aria-level="depth + 2"
                      :aria-selected="isPathHighlighted(folder.path, entry.is_dir ? 'dir' : 'file', entry.path)"
                      :aria-expanded="entry.is_dir ? getEffectiveExpanded(folder).has(entry.path) : undefined"
                      @mousedown="startFileDrag($event, folder.path, entry.path)"
                      @dragstart.prevent
                      @click.stop="handlePathClick(folder.path, entry.path, entry.is_dir ? 'dir' : 'file', $event)"
                      @dblclick.stop="handlePathDoubleClick(folder.path, entry.path, entry.is_dir ? 'dir' : 'file', $event)"
                      @contextmenu.capture="
                        contextTarget = entry.is_dir ? { kind: 'dir', folderPath: folder.path, entry } : { kind: 'file', folderPath: folder.path, entry };
                        activeKey = nodeKey(folder.path, entry.is_dir ? 'dir' : 'file', entry.path);
                      "
                      @contextmenu.prevent="
                        contextTarget = entry.is_dir ? { kind: 'dir', folderPath: folder.path, entry } : { kind: 'file', folderPath: folder.path, entry };
                        activeKey = nodeKey(folder.path, entry.is_dir ? 'dir' : 'file', entry.path);
                        onContextMenu($event);
                      "
                    >
                      <div v-if="fileDropTarget?.root === folder.path && fileDropTarget.path === entry.path" class="pointer-events-none absolute left-2 right-2 border-primary" :class="fileDropTarget.position === 'before' ? 'top-0 border-t-2' : 'bottom-0 border-b-2'" />
                      <template v-if="entry.is_dir">
                        <ChevronRight v-if="!getEffectiveExpanded(folder).has(entry.path)" class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                        <ChevronDown v-else class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                        <FolderClosed v-if="!getEffectiveExpanded(folder).has(entry.path)" class="h-4 w-4 shrink-0 text-amber-500" />
                        <FolderOpen v-else class="h-4 w-4 shrink-0 text-amber-500" />
                      </template>
                      <template v-else>
                        <span class="w-3.5 shrink-0" />
                        <FileCode class="h-4 w-4 shrink-0 text-blue-500" />
                      </template>
                      <span class="truncate ml-1 flex-1">{{ entry.name }}</span>
                      <template v-if="entry.is_dir">
                        <LightTooltip :text="t('sqlFileTree.newSqlFile')" side="bottom" :delay="0" :close-delay="0" nowrap>
                          <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" @click.stop="openCreateDialog(folder.path, entry.path)">
                            <FilePlus class="h-3 w-3" />
                          </Button>
                        </LightTooltip>
                        <LightTooltip :text="t('sqlFileTree.newFolder')" side="bottom" :delay="0" :close-delay="0" nowrap>
                          <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" @click.stop="openCreateFolderDialog(folder.path, entry.path)">
                            <FolderPlus class="h-3 w-3" />
                          </Button>
                        </LightTooltip>
                        <LightTooltip :text="t('sqlFileTree.renameFolder')" side="bottom" :delay="0" :close-delay="0" nowrap>
                          <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" @click.stop="openRenameFolderDialog({ kind: 'dir', folderPath: folder.path, entry })">
                            <Pencil class="h-3 w-3" />
                          </Button>
                        </LightTooltip>
                        <LightTooltip :text="t('sqlFileTree.deleteFolder')" side="bottom" :delay="0" :close-delay="0" nowrap>
                          <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-destructive" @click.stop="openDeleteFolderDialog({ kind: 'dir', folderPath: folder.path, entry })">
                            <Trash2 class="h-3 w-3" />
                          </Button>
                        </LightTooltip>
                      </template>
                      <template v-else>
                        <LightTooltip :text="t('sqlFileTree.renameFile')" side="bottom" :delay="0" :close-delay="0" nowrap>
                          <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" @click.stop="openRenameDialog({ kind: 'file', folderPath: folder.path, entry })">
                            <Pencil class="h-3 w-3" />
                          </Button>
                        </LightTooltip>
                        <LightTooltip :text="t('sqlFileTree.deleteFile')" side="bottom" :delay="0" :close-delay="0" nowrap>
                          <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-destructive" @click.stop="openDeleteDialog({ kind: 'file', folderPath: folder.path, entry })">
                            <Trash2 class="h-3 w-3" />
                          </Button>
                        </LightTooltip>
                      </template>
                    </div>
                    <SqlSearchMatchSnippet
                      v-if="searchMode === 'content' && !entry.is_dir && matchesByPath.has(normalizeExternalSqlPath(entry.path))"
                      :data-sql-file-content-snippet="entry.path"
                      :matches="matchesByPath.get(normalizeExternalSqlPath(entry.path))!.matches"
                      :total-matches="matchesByPath.get(normalizeExternalSqlPath(entry.path))!.totalMatches"
                      :preview-limit="matchesByPath.get(normalizeExternalSqlPath(entry.path))!.matches.length"
                      :query="searchQuery"
                      :depth="depth + 1"
                      @select-match="handleSearchMatch(folder.path, entry.path, $event)"
                    />
                  </template>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </CustomContextMenu>

    <Dialog v-model:open="filterSettingsOpen">
      <DialogContent class="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>{{ t("sqlFileTree.panelSettings") }}</DialogTitle>
        </DialogHeader>
        <div class="grid gap-2 py-2">
          <Label for="sql-file-open-mode">{{ t("sqlFileTree.openMode") }}</Label>
          <select id="sql-file-open-mode" v-model="openModeDraft" class="h-8 rounded-md border border-input bg-background px-2 text-sm">
            <option value="single">{{ t("sqlFileTree.openModeSingle") }}</option>
            <option value="double">{{ t("sqlFileTree.openModeDouble") }}</option>
          </select>
          <p class="text-xs text-muted-foreground">{{ t("sqlFileTree.keyboardHelp") }}</p>
          <Label for="sql-file-filter">{{ t("sqlFileTree.fileFilter") }}</Label>
          <Input id="sql-file-filter" v-model="fileFilterDraft" :placeholder="t('sqlFileTree.fileFilterPlaceholder')" @keydown.enter="saveFileFilter" />
          <p class="text-xs text-muted-foreground">{{ t("sqlFileTree.fileFilterHint", { regex: fileFilterRegexExample }) }}</p>
        </div>
        <DialogFooter>
          <Button type="button" variant="outline" @click="filterSettingsOpen = false">{{ t("common.cancel") }}</Button>
          <Button type="button" @click="saveFileFilter">{{ t("common.save") }}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>

    <Dialog :open="showCreateDialog" @update:open="(open) => (showCreateDialog = open)">
      <DialogContent class="sm:max-w-[380px]">
        <DialogHeader>
          <DialogTitle>{{ t("sqlFileTree.newSqlFile") }}</DialogTitle>
          <DialogDescription>{{ t("sqlFileTree.newSqlFileDescription") }}</DialogDescription>
        </DialogHeader>
        <Input v-model="fileNameInput" autofocus @keydown.enter.prevent="createSqlFile" />
        <DialogFooter>
          <Button variant="outline" size="sm" @click="showCreateDialog = false">{{ t("dangerDialog.cancel") }}</Button>
          <Button size="sm" :disabled="!fileNameInput.trim()" @click="createSqlFile">{{ t("sqlFileTree.createFile") }}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>

    <Dialog
      :open="showCreateFolderDialog"
      @update:open="
        (open) => {
          if (!folderMutationPending) showCreateFolderDialog = open;
        }
      "
    >
      <DialogContent class="sm:max-w-[380px]">
        <DialogHeader>
          <DialogTitle>{{ t("sqlFileTree.newFolder") }}</DialogTitle>
          <DialogDescription>{{ t("sqlFileTree.newFolderDescription") }}</DialogDescription>
        </DialogHeader>
        <Input :disabled="folderMutationPending" v-model="fileNameInput" autofocus @keydown.enter.prevent="createSqlFolder" />
        <DialogFooter>
          <Button :disabled="folderMutationPending" variant="outline" size="sm" @click="showCreateFolderDialog = false">{{ t("dangerDialog.cancel") }}</Button>
          <Button size="sm" :disabled="folderMutationPending || !fileNameInput.trim()" @click="createSqlFolder">{{ t("sqlFileTree.createFolder") }}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>

    <Dialog :open="showRenameDialog" @update:open="(open) => (showRenameDialog = open)">
      <DialogContent class="sm:max-w-[380px]" @close-auto-focus="restoreTreeFocus">
        <DialogHeader>
          <DialogTitle>{{ t("sqlFileTree.renameFile") }}</DialogTitle>
          <DialogDescription>{{ t("sqlFileTree.renameFileDescription") }}</DialogDescription>
        </DialogHeader>
        <Input v-model="fileNameInput" autofocus @keydown.enter.prevent="renameSqlFile" />
        <DialogFooter>
          <Button variant="outline" size="sm" @click="showRenameDialog = false">{{ t("dangerDialog.cancel") }}</Button>
          <Button size="sm" :disabled="!fileNameInput.trim()" @click="renameSqlFile">{{ t("sqlFileTree.renameFile") }}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>

    <Dialog
      :open="showRenameFolderDialog"
      @update:open="
        (open) => {
          if (!folderMutationPending) showRenameFolderDialog = open;
        }
      "
    >
      <DialogContent class="sm:max-w-[380px]" @close-auto-focus="restoreTreeFocus">
        <DialogHeader>
          <DialogTitle>{{ t("sqlFileTree.renameFolder") }}</DialogTitle>
          <DialogDescription>{{ t("sqlFileTree.renameFolderDescription") }}</DialogDescription>
        </DialogHeader>
        <Input :disabled="folderMutationPending" v-model="fileNameInput" autofocus @keydown.enter.prevent="renameSqlFolder" />
        <DialogFooter>
          <Button :disabled="folderMutationPending" variant="outline" size="sm" @click="showRenameFolderDialog = false">{{ t("dangerDialog.cancel") }}</Button>
          <Button size="sm" :disabled="folderMutationPending || !fileNameInput.trim()" @click="renameSqlFolder">{{ t("sqlFileTree.renameFolder") }}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>

    <Dialog :open="showDeleteDialog" @update:open="(open) => (showDeleteDialog = open)">
      <DialogContent class="sm:max-w-[380px]">
        <DialogHeader>
          <DialogTitle>{{ t("sqlFileTree.deleteFile") }}</DialogTitle>
          <DialogDescription>{{ t("sqlFileTree.deleteFileConfirm", { name: deleteTarget?.entry.name || "" }) }}</DialogDescription>
        </DialogHeader>
        <DialogFooter>
          <Button variant="outline" size="sm" @click="showDeleteDialog = false">{{ t("dangerDialog.cancel") }}</Button>
          <Button variant="destructive" size="sm" @click="deleteSqlFile">{{ t("dangerDialog.deleteConfirm") }}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>

    <Dialog
      :open="showDeleteFolderDialog"
      @update:open="
        (open) => {
          if (!folderMutationPending) showDeleteFolderDialog = open;
        }
      "
    >
      <DialogContent class="sm:max-w-[380px]">
        <DialogHeader>
          <DialogTitle>{{ t("sqlFileTree.deleteFolder") }}</DialogTitle>
          <DialogDescription>{{ t("sqlFileTree.deleteFolderConfirm", { name: deleteFolderTarget?.entry.name || "" }) }}</DialogDescription>
        </DialogHeader>
        <DialogFooter>
          <Button :disabled="folderMutationPending" variant="outline" size="sm" @click="showDeleteFolderDialog = false">{{ t("dangerDialog.cancel") }}</Button>
          <Button :disabled="folderMutationPending" variant="destructive" size="sm" @click="deleteSqlFolder">{{ t("dangerDialog.deleteConfirm") }}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  </div>
</template>