feat(tabs): detach SQL and data tabs into separate windows

This commit is contained in:
DengQingNian authored and GitHub committed 2026-09-03 01:45:08 +08:00
1 parent 717dcc1294
commit d38be39e03
17 files changed
+957 -21

No files matched your search

+337 -8
View File
@@ -9,6 +9,7 @@ import AppSidebar from "@/components/layout/AppSidebar.vue";
import EditorToolbar from "@/components/layout/EditorToolbar.vue"; import EditorToolbar from "@/components/layout/EditorToolbar.vue";
import ContentArea from "@/components/layout/ContentArea.vue"; import ContentArea from "@/components/layout/ContentArea.vue";
import AppDialogs from "@/components/layout/AppDialogs.vue"; import AppDialogs from "@/components/layout/AppDialogs.vue";
import DetachedTabHeader from "@/components/layout/DetachedTabHeader.vue";
import WelcomeScreen from "@/components/layout/WelcomeScreen.vue"; import WelcomeScreen from "@/components/layout/WelcomeScreen.vue";
import type { ConfigTab } from "@/components/connection/ConnectionDialog.vue"; import type { ConfigTab } from "@/components/connection/ConnectionDialog.vue";
import { useConnectionStore } from "@/stores/connectionStore"; import { useConnectionStore } from "@/stores/connectionStore";
@@ -137,6 +138,8 @@ import { SearchableSelect } from "@/components/ui/searchable-select";
import type { HistoryEntry } from "@/lib/backend/tauri"; import type { HistoryEntry } from "@/lib/backend/tauri";
import { resolveDefaultAiSchema, type AiAction } from "@/lib/ai/ai"; import { resolveDefaultAiSchema, type AiAction } from "@/lib/ai/ai";
import ExternalSqlFileChangeDialog from "@/components/editor/ExternalSqlFileChangeDialog.vue"; import ExternalSqlFileChangeDialog from "@/components/editor/ExternalSqlFileChangeDialog.vue";
import { resolveWindowContext } from "@/lib/app/windowContext";
import { openDetachedTabWindow } from "@/lib/app/detachedTabWindow";
const AiAssistant = defineAsyncComponent(() => import("@/components/editor/AiAssistant.vue")); const AiAssistant = defineAsyncComponent(() => import("@/components/editor/AiAssistant.vue"));
const QueryHistory = defineAsyncComponent(() => import("@/components/editor/QueryHistory.vue")); const QueryHistory = defineAsyncComponent(() => import("@/components/editor/QueryHistory.vue"));
@@ -219,6 +222,9 @@ const {
const { setupFileDrop } = useFileDrop(); const { setupFileDrop } = useFileDrop();
const isDesktop = isTauriRuntime(); const isDesktop = isTauriRuntime();
const windowContext = resolveWindowContext();
const isDetachedWindowContext = windowContext.kind === "detached-tab";
const detachedContextTabId = windowContext.kind === "detached-tab" ? windowContext.tabId : undefined;
const activeAiRunCount = computed(() => (isDesktop ? activeDesktopAiRuns().length : 0)); const activeAiRunCount = computed(() => (isDesktop ? activeDesktopAiRuns().length : 0));
/** Runs waiting for a write confirmation — the panel-entry badge shows these /** Runs waiting for a write confirmation — the panel-entry badge shows these
* with a higher-priority indicator (parent PRD §4 line 71 / §9). */ * with a higher-priority indicator (parent PRD §4 line 71 / §9). */
@@ -328,6 +334,267 @@ let aiRunsQuitConfirmed = false;
const activeTab = computed(() => queryStore.tabs.find((t) => t.id === queryStore.activeTabId)); const activeTab = computed(() => queryStore.tabs.find((t) => t.id === queryStore.activeTabId));
const tabNavigationHistory = ref(createTabNavigationHistory()); const tabNavigationHistory = ref(createTabNavigationHistory());
let pendingTabHistoryNavigationId: string | null = null; let pendingTabHistoryNavigationId: string | null = null;
let detachedEventUnlisteners: Array<() => void> = [];
let detachedCloseInProgress = false;
const detachedDropTargetTabId = ref<string | null>(null);
const showDetachedClosePrompt = ref(false);
function isDetachableTab(tab: QueryTab | undefined): tab is QueryTab {
return !!tab && (tab.mode === "query" || tab.mode === "data");
}
async function emitDetachedEvent(event: string, payload: unknown) {
if (!isDesktop) return;
const { emit } = await import("@tauri-apps/api/event");
await emit(event, payload);
}
async function isPointOverMainTabBar(position: { x: number; y: number }): Promise<boolean> {
if (isDetachedWindowContext) return false;
const tabBar = document.querySelector<HTMLElement>("[data-main-tab-bar]");
if (!tabBar) return false;
try {
const { getCurrentWindow } = await import("@tauri-apps/api/window");
const currentWindow = getCurrentWindow();
const [innerPosition, scaleFactor] = await Promise.all([currentWindow.innerPosition(), currentWindow.scaleFactor()]);
const rect = tabBar.getBoundingClientRect();
const safeScale = Number.isFinite(scaleFactor) && scaleFactor > 0 ? scaleFactor : 1;
const left = innerPosition.x + rect.left * safeScale;
const top = innerPosition.y + rect.top * safeScale;
const right = innerPosition.x + rect.right * safeScale;
const bottom = innerPosition.y + rect.bottom * safeScale;
return position.x >= left && position.x <= right && position.y >= top && position.y <= bottom;
} catch {
return false;
}
}
async function handleDetachedTabDragging(payload: unknown) {
if (isDetachedWindowContext) return;
const data = payload as { tabId?: unknown; x?: unknown; y?: unknown } | null;
if (typeof data?.tabId !== "string" || typeof data.x !== "number" || typeof data.y !== "number") return;
detachedDropTargetTabId.value = (await isPointOverMainTabBar({ x: data.x, y: data.y })) ? data.tabId : null;
}
async function handleDetachedTabDropped(payload: unknown) {
if (isDetachedWindowContext) return;
const data = payload as { tabId?: unknown; x?: unknown; y?: unknown } | null;
const pointerIsOverTabBar = typeof data?.x === "number" && typeof data.y === "number" ? await isPointOverMainTabBar({ x: data.x, y: data.y }) : false;
const shouldReturn = typeof data?.tabId === "string" && (detachedDropTargetTabId.value === data.tabId || pointerIsOverTabBar);
detachedDropTargetTabId.value = null;
if (!shouldReturn) return;
await handleDetachedReturnRequested(payload);
}
async function finishDetachedWindowClose() {
if (!isDetachedWindowContext) return;
detachedCloseInProgress = true;
await api.approveDetachedWindowClose().catch(() => {});
const { getCurrentWindow } = await import("@tauri-apps/api/window");
await getCurrentWindow()
.close()
.catch(() => {});
}
async function requestDetachedReturn(reason: "return" | "close" = "return") {
if (!isDetachedWindowContext || !detachedContextTabId || detachedCloseInProgress) return;
const tab = activeTab.value;
if (!tab) {
if (reason === "close") await closeDetachedTabAndWindow();
return;
}
if (reason === "close" && queryStore.isTabDirty(tab)) {
showDetachedClosePrompt.value = true;
return;
}
if (reason === "close") {
await closeDetachedTabAndWindow();
return;
}
await persistDetachedReturnRequest(reason);
}
async function closeDetachedTabAndWindow() {
if (!detachedContextTabId) return;
try {
// X means explicitly discard this detached tab. Delete the durable
// handoff before closing so a subsequent startup/lost-window recovery
// cannot resurrect a tab the user chose to remove.
await api.deleteDetachedTabHandoff(detachedContextTabId);
showDetachedClosePrompt.value = false;
await finishDetachedWindowClose();
} catch (error: any) {
detachedCloseInProgress = false;
toast(error?.message || String(error), 5000);
}
}
async function persistDetachedReturnRequest(reason: "return" | "close") {
if (!detachedContextTabId) return;
try {
const handoff = await queryStore.prepareDetachedTab(detachedContextTabId, { activeOutputView: activeOutputView.value });
await api.saveDetachedTabHandoff(detachedContextTabId, handoff);
detachedCloseInProgress = true;
await emitDetachedEvent("dbx:detached-tab-return-requested", { tabId: detachedContextTabId, revision: handoff.revision, reason });
} catch (error: any) {
detachedCloseInProgress = false;
toast(error?.message || String(error), 5000);
}
}
async function saveDetachedTabBeforeClose() {
if (!detachedContextTabId) return;
const tab = activeTab.value;
if (!tab) return;
const saved = await saveTabForCloseAll(detachedContextTabId);
if (!saved || queryStore.isTabDirty(tab)) return;
showDetachedClosePrompt.value = false;
await closeDetachedTabAndWindow();
}
async function discardDetachedTabBeforeClose() {
if (!detachedContextTabId) return;
queryStore.discardTabChanges(detachedContextTabId);
showDetachedClosePrompt.value = false;
await closeDetachedTabAndWindow();
}
function cancelDetachedTabClose() {
showDetachedClosePrompt.value = false;
}
async function handleDetachedHeaderDragStart(position: { x: number; y: number }) {
if (!detachedContextTabId) return;
await emitDetachedEvent("dbx:detached-tab-dragging", { tabId: detachedContextTabId, x: position.x, y: position.y });
}
async function handleDetachedHeaderDragging(position: { x: number; y: number }) {
if (!detachedContextTabId) return;
await emitDetachedEvent("dbx:detached-tab-dragging", { tabId: detachedContextTabId, x: position.x, y: position.y });
}
async function handleDetachedHeaderDragEnd(position: { x: number; y: number }) {
if (!detachedContextTabId) return;
try {
const handoff = await queryStore.prepareDetachedTab(detachedContextTabId, { activeOutputView: activeOutputView.value });
await api.saveDetachedTabHandoff(detachedContextTabId, handoff);
await emitDetachedEvent("dbx:detached-tab-dropped", { tabId: detachedContextTabId, revision: handoff.revision, x: position.x, y: position.y });
} catch (error: any) {
toast(error?.message || String(error), 5000);
}
}
async function handleDetachedCloseRequested(payload: unknown) {
const tabId = (payload as { tabId?: unknown } | null)?.tabId;
if (typeof tabId !== "string" || tabId !== detachedContextTabId) return;
await requestDetachedReturn("close");
}
async function handleDetachedReturnComplete(payload: unknown) {
const tabId = (payload as { tabId?: unknown } | null)?.tabId;
if (!isDetachedWindowContext || tabId !== detachedContextTabId) return;
await finishDetachedWindowClose();
}
async function handleDetachedTabReady(payload: unknown) {
if (isDetachedWindowContext) return;
const data = payload as { tabId?: unknown; revision?: unknown } | null;
if (typeof data?.tabId !== "string") return;
const handoff = await api.loadDetachedTabHandoff(data.tabId).catch(() => null);
if (!handoff || handoff.tabId !== data.tabId) return;
if (typeof data.revision === "number" && handoff.revision !== data.revision) return;
queryStore.removeTabAfterDetachedReady(data.tabId);
await queryStore.flushPendingPersist();
}
async function handleDetachedTabLost(payload: unknown) {
if (isDetachedWindowContext) return;
const tabId = (payload as { tabId?: unknown } | null)?.tabId;
if (typeof tabId !== "string") return;
const handoff = await api.loadDetachedTabHandoff(tabId).catch(() => null);
if (!handoff || handoff.tabId !== tabId) return;
try {
await queryStore.adoptDetachedTab(handoff);
// Persist the adopted tab before dropping the durable handoff so an
// interrupted shutdown cannot lose it from both stores.
await queryStore.flushPendingPersist();
await api.deleteDetachedTabHandoff(tabId);
} catch (error) {
console.warn("[DBX][detached-tab:lost-restore:error]", error);
}
}
async function handleDetachedReturnRequested(payload: unknown) {
if (isDetachedWindowContext) return;
const data = payload as { tabId?: unknown; revision?: unknown } | null;
if (typeof data?.tabId !== "string") return;
const handoff = await api.loadDetachedTabHandoff(data.tabId).catch(() => null);
if (!handoff || handoff.tabId !== data.tabId) return;
if (typeof data.revision === "number" && handoff.revision !== data.revision) return;
try {
await queryStore.adoptDetachedTab(handoff);
// Persist before deleting the handoff so the returned tab exists in at
// least one durable store at every point of the flow.
await queryStore.flushPendingPersist();
await api.deleteDetachedTabHandoff(data.tabId);
await emitDetachedEvent("dbx:detached-tab-return-complete", { tabId: data.tabId });
} catch (error: any) {
toast(error?.message || String(error), 5000);
}
}
async function initDetachedWindow() {
if (!isDetachedWindowContext || !detachedContextTabId) return;
await settingsStore.initEditorSettings();
await connectionStore.initFromDisk();
const handoff = await api.loadDetachedTabHandoff(detachedContextTabId);
if (!handoff) {
toast(t("tabs.detachedTabUnavailable"), 5000);
await finishDetachedWindowClose();
return;
}
await queryStore.adoptDetachedTab(handoff);
await queryStore.hydrateSavedSqlTabs();
if (handoff.runtime.activeOutputView) activeOutputView.value = handoff.runtime.activeOutputView;
const { emit } = await import("@tauri-apps/api/event");
await emit("dbx:detached-tab-ready", { tabId: detachedContextTabId, revision: handoff.revision });
}
async function setupDetachedWindowEvents() {
if (!isDesktop) return;
const { listen } = await import("@tauri-apps/api/event");
const events: Array<[string, (payload: unknown) => Promise<void>]> = isDetachedWindowContext
? [
["dbx:detached-tab-close-requested", handleDetachedCloseRequested],
["dbx:detached-tab-return-complete", handleDetachedReturnComplete],
]
: [
["dbx:detached-tab-ready", handleDetachedTabReady],
["dbx:detached-tab-return-requested", handleDetachedReturnRequested],
["dbx:detached-tab-dragging", handleDetachedTabDragging],
["dbx:detached-tab-dropped", handleDetachedTabDropped],
["dbx:detached-tab-lost", handleDetachedTabLost],
];
for (const [event, handler] of events) {
detachedEventUnlisteners.push(await listen(event, (message) => void (handler as (payload: unknown) => Promise<void>)(message.payload)));
}
}
async function detachTab(tab: QueryTab, position?: { x: number; y: number }) {
if (isDetachedWindowContext || !isDetachableTab(tab)) return;
try {
const handoff = await queryStore.prepareDetachedTab(tab.id, { activeOutputView: tab.id === queryStore.activeTabId ? activeOutputView.value : "result" });
await api.saveDetachedTabHandoff(tab.id, handoff);
const result = await openDetachedTabWindow(tab.id, tab.title, position);
if (!result.opened) {
await api.deleteDetachedTabHandoff(tab.id);
toast(result.error ? `${t("tabs.openInNewWindowFailed")} ${result.error}` : t("tabs.openInNewWindowFailed"), 7000);
}
} catch (error: any) {
await api.deleteDetachedTabHandoff(tab.id).catch(() => {});
toast(error?.message || String(error), 5000);
}
}
watch( watch(
() => activeTab.value?.mode, () => activeTab.value?.mode,
@@ -336,6 +603,12 @@ watch(
}, },
); );
watch(activeOutputView, (view) => {
if (isDetachedWindowContext && detachedContextTabId) {
void queryStore.flushDetachedTabPersistence(detachedContextTabId, { activeOutputView: view }).catch(() => {});
}
});
function toggleZenMode() { function toggleZenMode() {
if (activeTab.value?.mode !== "data") return; if (activeTab.value?.mode !== "data") return;
isZenMode.value = !isZenMode.value; isZenMode.value = !isZenMode.value;
@@ -2915,6 +3188,15 @@ watch(updateNotificationsEnabled, (enabled) => {
onMounted(async () => { onMounted(async () => {
console.log("[STARTUP] onMounted begin"); console.log("[STARTUP] onMounted begin");
const mountStart = performance.now(); const mountStart = performance.now();
if (isDetachedWindowContext) {
await setupDetachedWindowEvents();
await initDetachedWindow().catch((error) => {
console.error("[STARTUP] detached window initialization failed", error);
toast(error?.message || String(error), 5000);
void finishDetachedWindowClose();
});
return;
}
requestAnimationFrame(() => { requestAnimationFrame(() => {
aiPanelReady.value = true; aiPanelReady.value = true;
}); });
@@ -2982,6 +3264,7 @@ onMounted(async () => {
.catch(() => {}); .catch(() => {});
setupTauriListeners(); setupTauriListeners();
setupCloseActionPromptListener(); setupCloseActionPromptListener();
void setupDetachedWindowEvents();
void openPendingSqlFiles(); void openPendingSqlFiles();
void openPendingDbFiles(); void openPendingDbFiles();
void openPendingConnectionLinks(); void openPendingConnectionLinks();
@@ -2990,6 +3273,8 @@ onMounted(async () => {
}); });
onUnmounted(() => { onUnmounted(() => {
detachedEventUnlisteners.forEach((unlisten) => unlisten());
detachedEventUnlisteners = [];
cleanupTauriListeners(); cleanupTauriListeners();
cleanupCloseActionPromptListener(); cleanupCloseActionPromptListener();
if (updateCheckTimer) { if (updateCheckTimer) {
@@ -3017,6 +3302,7 @@ onUnmounted(() => {
<TooltipProvider :delay-duration="300"> <TooltipProvider :delay-duration="300">
<div class="h-screen w-screen max-w-full min-w-[760px] min-h-[600px] flex flex-col bg-background text-foreground overflow-hidden" :class="{ 'dbx-desktop-window-frame': drawDesktopWindowFrame }" :style="appUiFontFamilyStyle"> <div class="h-screen w-screen max-w-full min-w-[760px] min-h-[600px] flex flex-col bg-background text-foreground overflow-hidden" :class="{ 'dbx-desktop-window-frame': drawDesktopWindowFrame }" :style="appUiFontFamilyStyle">
<AppToolbar <AppToolbar
v-if="!isDetachedWindowContext"
:is-dark="isDark" :is-dark="isDark"
:theme-mode="themeMode" :theme-mode="themeMode"
:show-ai-panel="showAiPanel" :show-ai-panel="showAiPanel"
@@ -3055,8 +3341,9 @@ onUnmounted(() => {
@open-data-compare="dialogs.showDataCompareDialog.value = true" @open-data-compare="dialogs.showDataCompareDialog.value = true"
/> />
<div :class="isClassicLayout ? 'app-layout-classic flex-1 flex min-h-0' : 'app-panel-gutter flex-1 flex min-h-0 gap-1 p-1'"> <div :class="isDetachedWindowContext ? 'flex-1 flex min-h-0' : isClassicLayout ? 'app-layout-classic flex-1 flex min-h-0' : 'app-panel-gutter flex-1 flex min-h-0 gap-1 p-1'">
<AppSidebar <AppSidebar
v-if="!isDetachedWindowContext"
v-show="sidebarOpen && !isZenMode" v-show="sidebarOpen && !isZenMode"
ref="appSidebarRef" ref="appSidebarRef"
:sidebar-width="sidebarWidth" :sidebar-width="sidebarWidth"
@@ -3068,21 +3355,24 @@ onUnmounted(() => {
@open-settings="(initialTab) => openSettings(initialTab ?? 'appearance')" @open-settings="(initialTab) => openSettings(initialTab ?? 'appearance')"
@add-to-ai="addToAi" @add-to-ai="addToAi"
/> />
<div v-show="!sidebarOpen && !isZenMode" class="flex h-full w-8 shrink-0 items-start justify-center border-r bg-background/80 pt-2" :class="isClassicLayout ? '' : 'rounded-md border border-border/80'"> <div v-if="!isDetachedWindowContext" v-show="!sidebarOpen && !isZenMode" class="flex h-full w-8 shrink-0 items-start justify-center border-r bg-background/80 pt-2" :class="isClassicLayout ? '' : 'rounded-md border border-border/80'">
<Button variant="ghost" size="icon" class="h-7 w-7" :title="t('sidebar.expand')" :aria-label="t('sidebar.expand')" @click="setSidebarOpen(true)"> <Button variant="ghost" size="icon" class="h-7 w-7" :title="t('sidebar.expand')" :aria-label="t('sidebar.expand')" @click="setSidebarOpen(true)">
<ChevronsRight class="h-4 w-4" /> <ChevronsRight class="h-4 w-4" />
</Button> </Button>
</div> </div>
<div v-show="!isAiPanelMaximized || isZenMode" :class="isClassicLayout ? 'flex-1 min-w-0 overflow-hidden' : 'flex-1 min-w-0 overflow-hidden rounded-md border border-border/80 bg-background'"> <div v-show="!isAiPanelMaximized || isZenMode" :class="isDetachedWindowContext ? 'flex-1 min-w-0 overflow-hidden bg-background' : isClassicLayout ? 'flex-1 min-w-0 overflow-hidden' : 'flex-1 min-w-0 overflow-hidden rounded-md border border-border/80 bg-background'">
<div class="h-full flex min-w-0" :class="tabWorkspaceLayoutClass"> <div class="h-full flex min-w-0" :class="isDetachedWindowContext ? 'flex-col' : tabWorkspaceLayoutClass">
<AppTabBar <AppTabBar
v-if="!isDetachedWindowContext"
ref="appTabBarRef" ref="appTabBarRef"
:driver-store-open="driverStoreTabOpen" :driver-store-open="driverStoreTabOpen"
:driver-store-active="driverStoreActive" :driver-store-active="driverStoreActive"
:settings-page-open="settingsPageTabOpen" :settings-page-open="settingsPageTabOpen"
:settings-page-active="settingsStore.settingsPageActive" :settings-page-active="settingsStore.settingsPageActive"
:agent-driver-update-count="toolbarAgentDriverUpdateCount" :agent-driver-update-count="toolbarAgentDriverUpdateCount"
:detached-drop-target="detachedDropTargetTabId !== null"
:can-detach-tabs="isDesktop"
@toggle-zen-mode="toggleZenMode" @toggle-zen-mode="toggleZenMode"
@activate-driver-store="openDriverStorePage" @activate-driver-store="openDriverStorePage"
@activate-settings-page="activateSettingsPage" @activate-settings-page="activateSettingsPage"
@@ -3095,7 +3385,31 @@ onUnmounted(() => {
@save-all-tab-close="handleSaveAllPendingTabClose" @save-all-tab-close="handleSaveAllPendingTabClose"
@discard-all-tab-close="handleDiscardAllPendingTabClose" @discard-all-tab-close="handleDiscardAllPendingTabClose"
@cancel-tab-close="cancelPendingAppClose" @cancel-tab-close="cancelPendingAppClose"
@detach-tab="detachTab"
/> />
<DetachedTabHeader
v-else-if="activeTab"
:title="activeTab.title"
:dirty="queryStore.isTabDirty(activeTab)"
@return="requestDetachedReturn('return')"
@close="requestDetachedReturn('close')"
@drag-start="handleDetachedHeaderDragStart"
@dragging="handleDetachedHeaderDragging"
@drag-end="handleDetachedHeaderDragEnd"
/>
<Dialog v-if="isDetachedWindowContext" :open="showDetachedClosePrompt" @update:open="(open) => (showDetachedClosePrompt = open)">
<DialogContent class="sm:max-w-[420px]">
<DialogHeader>
<DialogTitle>{{ t("tabs.detachedCloseTitle") }}</DialogTitle>
</DialogHeader>
<p class="text-sm text-muted-foreground">{{ t("tabs.detachedCloseMessage") }}</p>
<DialogFooter>
<Button variant="outline" @click="cancelDetachedTabClose">{{ t("common.cancel") }}</Button>
<Button variant="secondary" class="border-border" @click="discardDetachedTabBeforeClose">{{ t("editor.discardChanges") }}</Button>
<Button @click="saveDetachedTabBeforeClose">{{ t("savedSql.save") }}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<div class="flex min-h-0 min-w-0 flex-1 flex-col"> <div class="flex min-h-0 min-w-0 flex-1 flex-col">
<DriverStorePage v-if="driverStoreTabOpen" v-show="driverStoreActive" v-model:active-tab="driverStoreActiveTab" class="flex-1 min-h-0" :update-notifications-enabled="updateNotificationsEnabled" :focus-target="driverStoreFocus" @update-count-change="updateAgentDriverUpdateCount" /> <DriverStorePage v-if="driverStoreTabOpen" v-show="driverStoreActive" v-model:active-tab="driverStoreActiveTab" class="flex-1 min-h-0" :update-notifications-enabled="updateNotificationsEnabled" :focus-target="driverStoreFocus" @update-count-change="updateAgentDriverUpdateCount" />
<EditorSettingsPage <EditorSettingsPage
@@ -3254,7 +3568,7 @@ onUnmounted(() => {
</div> </div>
<div <div
v-if="showAiPanel" v-if="!isDetachedWindowContext && showAiPanel"
v-show="!isZenMode" v-show="!isZenMode"
:class="[isClassicLayout ? 'h-full relative z-30 isolate bg-background' : 'h-full relative z-30 isolate rounded-md border border-border/80 bg-background', isAiPanelMaximized ? 'min-w-0 flex-1' : 'min-w-[180px] max-w-full']" :class="[isClassicLayout ? 'h-full relative z-30 isolate bg-background' : 'h-full relative z-30 isolate rounded-md border border-border/80 bg-background', isAiPanelMaximized ? 'min-w-0 flex-1' : 'min-w-[180px] max-w-full']"
:style="isAiPanelMaximized ? {} : { width: aiPanelWidth + 'px' }" :style="isAiPanelMaximized ? {} : { width: aiPanelWidth + 'px' }"
@@ -3280,21 +3594,36 @@ onUnmounted(() => {
</div> </div>
</div> </div>
<div v-if="showHistory" v-show="!isAiPanelMaximized && !isZenMode" :class="isClassicLayout ? 'h-full shrink-0 relative z-30 isolate bg-background' : 'h-full shrink-0 relative z-30 isolate rounded-md border border-border/80 bg-background'" :style="{ width: historyWidth + 'px' }"> <div
v-if="!isDetachedWindowContext && showHistory"
v-show="!isAiPanelMaximized && !isZenMode"
:class="isClassicLayout ? 'h-full shrink-0 relative z-30 isolate bg-background' : 'h-full shrink-0 relative z-30 isolate rounded-md border border-border/80 bg-background'"
:style="{ width: historyWidth + 'px' }"
>
<div class="panel-resize-handle panel-resize-handle--left" @mousedown="startHistoryResize" /> <div class="panel-resize-handle panel-resize-handle--left" @mousedown="startHistoryResize" />
<div class="h-full min-h-0 overflow-hidden rounded-[inherit]"> <div class="h-full min-h-0 overflow-hidden rounded-[inherit]">
<QueryHistory :current-connection-id="activeTab?.connectionId" :current-database="activeTab?.database" @restore="restoreHistorySql" @analyze-ai="analyzeHistoryWithAi" @close="closeRightSidebarPanel('history')" /> <QueryHistory :current-connection-id="activeTab?.connectionId" :current-database="activeTab?.database" @restore="restoreHistorySql" @analyze-ai="analyzeHistoryWithAi" @close="closeRightSidebarPanel('history')" />
</div> </div>
</div> </div>
<div v-if="showSqlLibraryPanel" v-show="!isAiPanelMaximized && !isZenMode" :class="isClassicLayout ? 'h-full shrink-0 relative z-30 isolate bg-background' : 'h-full shrink-0 relative z-30 isolate rounded-md border border-border/80 bg-background'" :style="{ width: sqlLibraryWidth + 'px' }"> <div
v-if="!isDetachedWindowContext && showSqlLibraryPanel"
v-show="!isAiPanelMaximized && !isZenMode"
:class="isClassicLayout ? 'h-full shrink-0 relative z-30 isolate bg-background' : 'h-full shrink-0 relative z-30 isolate rounded-md border border-border/80 bg-background'"
:style="{ width: sqlLibraryWidth + 'px' }"
>
<div class="panel-resize-handle panel-resize-handle--left" @mousedown="startSqlLibraryResize" /> <div class="panel-resize-handle panel-resize-handle--left" @mousedown="startSqlLibraryResize" />
<div class="h-full min-h-0 overflow-hidden rounded-[inherit]"> <div class="h-full min-h-0 overflow-hidden rounded-[inherit]">
<SqlLibraryPanel @close="closeRightSidebarPanel('sqlLibrary')" /> <SqlLibraryPanel @close="closeRightSidebarPanel('sqlLibrary')" />
</div> </div>
</div> </div>
<div v-if="showSqlFilePanel" v-show="!isAiPanelMaximized && !isZenMode" :class="isClassicLayout ? 'h-full shrink-0 relative z-30 isolate bg-background' : 'h-full shrink-0 relative z-30 isolate rounded-md border border-border/80 bg-background'" :style="{ width: sqlFilePanelWidth + 'px' }"> <div
v-if="!isDetachedWindowContext && showSqlFilePanel"
v-show="!isAiPanelMaximized && !isZenMode"
:class="isClassicLayout ? 'h-full shrink-0 relative z-30 isolate bg-background' : 'h-full shrink-0 relative z-30 isolate rounded-md border border-border/80 bg-background'"
:style="{ width: sqlFilePanelWidth + 'px' }"
>
<div class="panel-resize-handle panel-resize-handle--left" @mousedown="startSqlFilePanelResize" /> <div class="panel-resize-handle panel-resize-handle--left" @mousedown="startSqlFilePanelResize" />
<div class="h-full min-h-0 overflow-hidden rounded-[inherit]"> <div class="h-full min-h-0 overflow-hidden rounded-[inherit]">
<SqlFilePanel @close="closeRightSidebarPanel('sqlFile')" /> <SqlFilePanel @close="closeRightSidebarPanel('sqlFile')" />
@@ -30,6 +30,8 @@ const props = defineProps<{
settingsPageOpen?: boolean; settingsPageOpen?: boolean;
settingsPageActive?: boolean; settingsPageActive?: boolean;
agentDriverUpdateCount?: number; agentDriverUpdateCount?: number;
detachedDropTarget?: boolean;
canDetachTabs?: boolean;
}>(); }>();
const emit = defineEmits<{ const emit = defineEmits<{
@@ -45,6 +47,7 @@ const emit = defineEmits<{
"save-all-tab-close": []; "save-all-tab-close": [];
"discard-all-tab-close": []; "discard-all-tab-close": [];
"cancel-tab-close": []; "cancel-tab-close": [];
"detach-tab": [tab: QueryTab, position?: { x: number; y: number }];
}>(); }>();
const { t } = useI18n(); const { t } = useI18n();
@@ -52,16 +55,25 @@ const connectionStore = useConnectionStore();
const queryStore = useQueryStore(); const queryStore = useQueryStore();
const settingsStore = useSettingsStore(); const settingsStore = useSettingsStore();
const { toast } = useToast(); const { toast } = useToast();
const tabDrag = useTabDrag(
(draggedId, targetId, position) => {
return queryStore.reorderTab(draggedId, targetId, position);
},
(draggedId, position) => {
if (!props.canDetachTabs) return false;
const tab = queryStore.tabs.find((item) => item.id === draggedId);
if (!tab || !isDetachableTab(tab)) return false;
emit("detach-tab", tab, position);
return true;
},
() => (isVerticalLayout.value ? "vertical" : "horizontal"),
);
const editingTabId = ref<string | null>(null); const editingTabId = ref<string | null>(null);
const editingTitle = ref(""); const editingTitle = ref("");
const isClassicLayout = computed(() => settingsStore.editorSettings.appLayout === "classic"); const isClassicLayout = computed(() => settingsStore.editorSettings.appLayout === "classic");
const isVerticalLayout = computed(() => settingsStore.editorSettings.tabPlacement === "left" || settingsStore.editorSettings.tabPlacement === "right"); const isVerticalLayout = computed(() => settingsStore.editorSettings.tabPlacement === "left" || settingsStore.editorSettings.tabPlacement === "right");
const isWrapLayout = computed(() => !isVerticalLayout.value && settingsStore.editorSettings.tabLayout === "wrap"); const isWrapLayout = computed(() => !isVerticalLayout.value && settingsStore.editorSettings.tabLayout === "wrap");
const isManualTabOrder = computed(() => settingsStore.editorSettings.tabSortMode === "manual"); const isManualTabOrder = computed(() => settingsStore.editorSettings.tabSortMode === "manual");
const tabDrag = useTabDrag(
(draggedId, targetId, position) => queryStore.reorderTab(draggedId, targetId, position),
() => (isVerticalLayout.value ? "vertical" : "horizontal"),
);
function tabGroupKey(tab: QueryTab) { function tabGroupKey(tab: QueryTab) {
const connection = connectionStore.getConfig(tab.connectionId); const connection = connectionStore.getConfig(tab.connectionId);
@@ -153,6 +165,7 @@ function scheduleCloseConfirmListClose() {
} }
onUnmounted(() => { onUnmounted(() => {
tabDrag.setDetachBoundsProvider(null);
if (closeConfirmListCloseTimer) { if (closeConfirmListCloseTimer) {
clearTimeout(closeConfirmListCloseTimer); clearTimeout(closeConfirmListCloseTimer);
closeConfirmListCloseTimer = null; closeConfirmListCloseTimer = null;
@@ -174,6 +187,10 @@ function canRenameTab(tab: QueryTab) {
return tab.mode === "query"; return tab.mode === "query";
} }
function isDetachableTab(tab: QueryTab) {
return tab.mode === "query" || tab.mode === "data";
}
function startRenameTab(tab: QueryTab) { function startRenameTab(tab: QueryTab) {
if (!canRenameTab(tab)) return; if (!canRenameTab(tab)) return;
editingTabId.value = tab.id; editingTabId.value = tab.id;
@@ -389,6 +406,12 @@ function getTabMenuItems(tab: QueryTab): ContextMenuItem[] {
}, },
icon: Copy, icon: Copy,
}, },
{
label: t("tabs.openInNewWindow"),
action: () => emit("detach-tab", tab),
icon: Maximize2,
visible: !!props.canDetachTabs && isDetachableTab(tab),
},
{ {
label: t("sidebar.locateActiveTab"), label: t("sidebar.locateActiveTab"),
action: () => emit("locate-tab", tab), action: () => emit("locate-tab", tab),
@@ -468,6 +491,13 @@ const {
onTabsWheel: onFixedTabsWheel, onTabsWheel: onFixedTabsWheel,
startScrollbarDrag: startFixedScrollbarDrag, startScrollbarDrag: startFixedScrollbarDrag,
} = useTabScroll(fixedTabsContainerRef); } = useTabScroll(fixedTabsContainerRef);
tabDrag.setDetachBoundsProvider(() => {
const regular = tabsContainerRef.value?.getBoundingClientRect();
const fixed = fixedTabsContainerRef.value?.getBoundingClientRect();
if (!regular) return fixed;
if (!fixed) return regular;
return new DOMRect(Math.min(regular.left, fixed.left), Math.min(regular.top, fixed.top), Math.max(regular.right, fixed.right) - Math.min(regular.left, fixed.left), Math.max(regular.bottom, fixed.bottom) - Math.min(regular.top, fixed.top));
});
const tabScrollBehavior = ref<ScrollBehavior>("smooth"); const tabScrollBehavior = ref<ScrollBehavior>("smooth");
function updateAllScrollButtons() { function updateAllScrollButtons() {
@@ -773,7 +803,7 @@ function onOverflowItemKeydown(event: KeyboardEvent, tabId: string, kind: "regul
</script> </script>
<template> <template>
<div v-if="queryStore.tabs.length > 0 || driverStoreOpen || settingsPageOpen" class="app-tab-bar relative flex min-w-0 shrink-0 overflow-hidden" :class="tabBarClass"> <div v-if="queryStore.tabs.length > 0 || driverStoreOpen || settingsPageOpen" data-main-tab-bar class="app-tab-bar relative flex w-full min-w-0 shrink-0 overflow-hidden" :class="[tabBarClass, { 'ring-2 ring-primary ring-inset': detachedDropTarget }]">
<div v-if="isVerticalLayout" class="relative shrink-0 border-b p-2"> <div v-if="isVerticalLayout" class="relative shrink-0 border-b p-2">
<Search class="pointer-events-none absolute left-4 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" /> <Search class="pointer-events-none absolute left-4 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
<Input v-model="tabSearchQuery" type="search" :placeholder="t('tabs.searchOpenTabs')" class="h-8 w-full pl-7 text-sm" /> <Input v-model="tabSearchQuery" type="search" :placeholder="t('tabs.searchOpenTabs')" class="h-8 w-full pl-7 text-sm" />
@@ -0,0 +1,83 @@
<script setup lang="ts">
import { ArrowLeft, Minus, Square, Copy, X, Grip } from "@lucide/vue";
import { useI18n } from "vue-i18n";
import { useWindowControls } from "@/composables/useWindowControls";
defineProps<{
title: string;
dirty?: boolean;
}>();
const emit = defineEmits<{
return: [];
close: [];
"drag-start": [position: { x: number; y: number }];
dragging: [position: { x: number; y: number }];
"drag-end": [position: { x: number; y: number }];
}>();
const { t } = useI18n();
const { isMac, isMaximized, minimize, toggleMaximize } = useWindowControls();
let dragging = false;
async function cursorPosition(event: PointerEvent) {
// PointerEvent.screenX/Y are global screen coordinates. Convert the
// browser's logical pixels to physical pixels so they can be compared with
// Tauri's PhysicalPosition on the main window, including mixed-DPI setups.
const scale = typeof window !== "undefined" && Number.isFinite(window.devicePixelRatio) && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1;
return { x: event.screenX * scale, y: event.screenY * scale };
}
async function handleDragStart(event: PointerEvent) {
if (event.button !== 0 || event.pointerType === "touch") return;
event.preventDefault();
event.stopPropagation();
dragging = true;
const target = event.currentTarget as HTMLElement;
target.setPointerCapture?.(event.pointerId);
emit("drag-start", await cursorPosition(event));
}
async function handleDragging(event: PointerEvent) {
if (!dragging) return;
event.preventDefault();
emit("dragging", await cursorPosition(event));
}
async function handleDragEnd(event: PointerEvent) {
if (!dragging) return;
dragging = false;
event.preventDefault();
emit("drag-end", await cursorPosition(event));
}
</script>
<template>
<div class="flex h-10 shrink-0 items-center border-b bg-background/95 text-xs" :class="isMac ? 'pl-20' : ''">
<div class="flex min-w-0 flex-1 items-center gap-2 px-3" data-tauri-drag-region>
<button
type="button"
class="inline-flex h-7 w-6 shrink-0 cursor-grab items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground active:cursor-grabbing"
:title="t('tabs.dragBackToMain')"
@pointerdown.stop="handleDragStart"
@pointermove.stop="handleDragging"
@pointerup.stop="handleDragEnd"
@pointercancel.stop="handleDragEnd"
>
<Grip class="h-3.5 w-3.5" />
</button>
<span class="min-w-0 flex-1 truncate font-medium" data-tauri-drag-region> <span v-if="dirty" class="mr-0.5">*</span>{{ title }} </span>
</div>
<button type="button" class="mr-1 inline-flex h-7 items-center gap-1 rounded px-2 text-muted-foreground hover:bg-accent hover:text-foreground" :title="t('tabs.returnToMainWindow')" @pointerdown.stop @click="emit('return')">
<ArrowLeft class="h-3.5 w-3.5" />
<span>{{ t("tabs.returnToMainWindow") }}</span>
</button>
<template v-if="!isMac">
<button type="button" class="inline-flex h-10 w-10 items-center justify-center hover:bg-foreground/10" :title="t('tabs.minimizeWindow')" @click="minimize"><Minus class="h-4 w-4" /></button>
<button type="button" class="inline-flex h-10 w-10 items-center justify-center hover:bg-foreground/10" :title="t('tabs.maximizeWindow')" @click="toggleMaximize"><Copy v-if="isMaximized" class="h-3.5 w-3.5" /><Square v-else class="h-3.5 w-3.5" /></button>
<button type="button" class="inline-flex h-10 w-10 items-center justify-center hover:bg-red-500 hover:text-white" :title="t('tabs.closeWindow')" @click="emit('close')"><X class="h-4 w-4" /></button>
</template>
<button v-else type="button" class="mr-2 inline-flex h-7 w-7 items-center justify-center rounded hover:bg-red-500 hover:text-white" :title="t('tabs.closeWindow')" @click="emit('close')"><X class="h-4 w-4" /></button>
</div>
</template>
+60 -2
View File
@@ -20,8 +20,12 @@ function movePointer(x: number, y = 20, pointerType = "mouse") {
document.dispatchEvent(new PointerEvent("pointermove", { bubbles: true, clientX: x, clientY: y, pointerType })); document.dispatchEvent(new PointerEvent("pointermove", { bubbles: true, clientX: x, clientY: y, pointerType }));
} }
function releasePointer() { function releasePointer(x = 0, y = 0) {
document.dispatchEvent(new PointerEvent("pointerup", { bubbles: true })); document.dispatchEvent(new PointerEvent("pointerup", { bubbles: true, clientX: x, clientY: y, screenX: x, screenY: y }));
}
function cancelPointer() {
document.dispatchEvent(new PointerEvent("pointercancel", { bubbles: true }));
} }
function enterDropTarget(drag: ReturnType<typeof useTabDrag>, tabId = "target", x = 10) { function enterDropTarget(drag: ReturnType<typeof useTabDrag>, tabId = "target", x = 10) {
@@ -112,4 +116,58 @@ describe("useTabDrag", () => {
expect(drag.state.suppressClick).toBe(false); expect(drag.state.suppressClick).toBe(false);
expect(onDrop).not.toHaveBeenCalled(); expect(onDrop).not.toHaveBeenCalled();
}); });
it("detaches only when an armed drag is released outside the tab strip", () => {
const onDetach = vi.fn(() => true);
const drag = useTabDrag(
vi.fn(() => true),
onDetach,
);
drag.setDetachBoundsProvider(() => ({ left: 0, top: 0, right: 300, bottom: 40 }) as DOMRect);
const source = document.createElement("div");
source.innerHTML = '<span class="truncate">Source</span>';
source.addEventListener("pointerdown", (event) => drag.startDrag(event as PointerEvent, "source"));
document.body.appendChild(source);
beginDrag(source);
movePointer(100 + TAB_DRAG_HORIZONTAL_THRESHOLD);
releasePointer(500, 500);
expect(onDetach).toHaveBeenCalledWith("source", { x: 500, y: 500 });
expect(drag.state.active).toBe(false);
expect(drag.state.suppressClick).toBe(true);
drag.setDetachBoundsProvider(null);
});
it("clears an armed drag when the pointer is cancelled", () => {
const { drag, source } = createDragHarness();
beginDrag(source);
movePointer(100 + TAB_DRAG_HORIZONTAL_THRESHOLD);
expect(drag.state.active).toBe(true);
cancelPointer();
expect(drag.state.active).toBe(false);
expect(drag.state.draggedId).toBe(null);
expect(drag.state.suppressClick).toBe(false);
});
it("does not detach when the pointer is released inside the tab strip", () => {
const onDetach = vi.fn(() => true);
const onDrop = vi.fn(() => false);
const drag = useTabDrag(onDrop, onDetach);
drag.setDetachBoundsProvider(() => ({ left: 0, top: 0, right: 300, bottom: 40 }) as DOMRect);
const source = document.createElement("div");
source.innerHTML = '<span class="truncate">Source</span>';
source.addEventListener("pointerdown", (event) => drag.startDrag(event as PointerEvent, "source"));
document.body.appendChild(source);
beginDrag(source);
movePointer(100 + TAB_DRAG_HORIZONTAL_THRESHOLD);
releasePointer();
expect(onDetach).not.toHaveBeenCalled();
expect(onDrop).not.toHaveBeenCalled();
drag.setDetachBoundsProvider(null);
});
}); });
+26 -3
View File
@@ -35,6 +35,8 @@ let pending: {
sourceEl: HTMLElement | null; sourceEl: HTMLElement | null;
} | null = null; } | null = null;
let onDropCallback: ((draggedId: string, targetId: string, position: TabDropPosition) => boolean) | null = null; let onDropCallback: ((draggedId: string, targetId: string, position: TabDropPosition) => boolean) | null = null;
let onDetachCallback: ((draggedId: string, position: { x: number; y: number }) => boolean) | null = null;
let detachBoundsProvider: (() => DOMRect | undefined) | null = null;
let dragAxis: () => "horizontal" | "vertical" = () => "horizontal"; let dragAxis: () => "horizontal" | "vertical" = () => "horizontal";
let ghostEl: HTMLElement | null = null; let ghostEl: HTMLElement | null = null;
@@ -102,14 +104,27 @@ function onPointerMove(event: PointerEvent) {
} }
} }
function onMouseUp() { function onMouseUp(event: PointerEvent) {
state.suppressClick = false; state.suppressClick = false;
if (state.active && state.draggedId && state.targetId && state.dropPosition && onDropCallback) { if (state.active && state.draggedId && onDetachCallback && isOutsideDetachBounds(event.clientX, event.clientY)) {
const scale = typeof window !== "undefined" && Number.isFinite(window.devicePixelRatio) && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1;
state.suppressClick = onDetachCallback(state.draggedId, { x: event.screenX * scale, y: event.screenY * scale });
} else if (state.active && state.draggedId && state.targetId && state.dropPosition && onDropCallback) {
state.suppressClick = onDropCallback(state.draggedId, state.targetId, state.dropPosition); state.suppressClick = onDropCallback(state.draggedId, state.targetId, state.dropPosition);
} }
reset(); reset();
} }
function onPointerCancel() {
state.suppressClick = false;
reset();
}
function isOutsideDetachBounds(x: number, y: number): boolean {
const bounds = detachBoundsProvider?.();
return !!bounds && (x < bounds.left || x > bounds.right || y < bounds.top || y > bounds.bottom);
}
function reset() { function reset() {
state.active = false; state.active = false;
state.draggedId = null; state.draggedId = null;
@@ -129,14 +144,21 @@ function ensureListeners() {
if (listenersAttached) return; if (listenersAttached) return;
document.addEventListener("pointermove", onPointerMove, true); document.addEventListener("pointermove", onPointerMove, true);
document.addEventListener("pointerup", onMouseUp, true); document.addEventListener("pointerup", onMouseUp, true);
document.addEventListener("pointercancel", onPointerCancel, true);
window.addEventListener("blur", onPointerCancel, true);
listenersAttached = true; listenersAttached = true;
} }
export function useTabDrag(onDrop: (draggedId: string, targetId: string, position: TabDropPosition) => boolean, axis: () => "horizontal" | "vertical" = () => "horizontal") { export function useTabDrag(onDrop: (draggedId: string, targetId: string, position: TabDropPosition) => boolean, onDetach?: (draggedId: string, position: { x: number; y: number }) => boolean, axis: () => "horizontal" | "vertical" = () => "horizontal") {
ensureListeners(); ensureListeners();
onDropCallback = onDrop; onDropCallback = onDrop;
onDetachCallback = onDetach ?? null;
dragAxis = axis; dragAxis = axis;
function setDetachBoundsProvider(provider: (() => DOMRect | undefined) | null) {
detachBoundsProvider = provider;
}
function startDrag(event: PointerEvent, tabId: string) { function startDrag(event: PointerEvent, tabId: string) {
if (event.button !== 0) return; if (event.button !== 0) return;
// Touch input has no reliable equivalent of mouse jitter: a real finger's // Touch input has no reliable equivalent of mouse jitter: a real finger's
@@ -183,5 +205,6 @@ export function useTabDrag(onDrop: (draggedId: string, targetId: string, positio
startDrag, startDrag,
updateTarget, updateTarget,
clearTarget, clearTarget,
setDetachBoundsProvider,
}; };
} }
+10
View File
@@ -1482,6 +1482,16 @@ export default {
scrollLeft: "Scroll tabs left", scrollLeft: "Scroll tabs left",
scrollRight: "Scroll tabs right", scrollRight: "Scroll tabs right",
openTabs: "Open tabs", openTabs: "Open tabs",
openInNewWindow: "Open in new window",
returnToMainWindow: "Return to main window",
dragBackToMain: "Drag this handle to the main window",
detachedCloseTitle: "Close detached window",
detachedCloseMessage: "This SQL tab has unsaved changes. Save them before closing and deleting the detached tab?",
detachedTabUnavailable: "The detached tab is no longer available.",
openInNewWindowFailed: "Could not open a detached window.",
minimizeWindow: "Minimize",
maximizeWindow: "Maximize",
closeWindow: "Close",
searchOpenTabs: "Search open tabs...", searchOpenTabs: "Search open tabs...",
switcherTitle: "Switch Tab", switcherTitle: "Switch Tab",
switcherHint: "keep pressing to move, release to switch", switcherHint: "keep pressing to move, release to switch",
+10
View File
@@ -1406,6 +1406,16 @@ export default withEnglishFallback({
scrollLeft: "向左滚动标签页", scrollLeft: "向左滚动标签页",
scrollRight: "向右滚动标签页", scrollRight: "向右滚动标签页",
openTabs: "已打开的标签页", openTabs: "已打开的标签页",
openInNewWindow: "在新窗口打开",
returnToMainWindow: "返回主窗口",
dragBackToMain: "拖动此手柄可返回主窗口",
detachedCloseTitle: "关闭独立窗口",
detachedCloseMessage: "当前 SQL 标签有未保存修改。关闭并删除该独立标签前是否保存?",
detachedTabUnavailable: "独立标签已不可用。",
openInNewWindowFailed: "无法打开独立窗口。",
minimizeWindow: "最小化",
maximizeWindow: "最大化",
closeWindow: "关闭",
searchOpenTabs: "搜索已打开的标签页...", searchOpenTabs: "搜索已打开的标签页...",
switcherTitle: "切换标签页", switcherTitle: "切换标签页",
switcherHint: "继续按选择,松开修饰键切换", switcherHint: "继续按选择,松开修饰键切换",
@@ -0,0 +1,24 @@
import type { QueryTab } from "@/types/database";
import type { SavedOpenTab } from "@/lib/app/openTabsPersistence";
export type DetachedOutputView = "result" | "summary" | "explain" | "chart" | "messages";
export interface DetachedTabRuntimeState {
editorViewport?: QueryTab["editorViewport"];
editorSelection?: QueryTab["editorSelection"];
txnSessionId?: string;
txnAutoRolledBack?: boolean;
oracleTxnPossiblyDirty?: boolean;
activeOutputView?: DetachedOutputView;
}
export interface DetachedTabHandoff {
schemaVersion: 1;
tabId: string;
sourceWindowLabel: string;
revision: number;
tab: SavedOpenTab;
runtime: DetachedTabRuntimeState;
resultCacheKey?: string;
updatedAt: number;
}
@@ -0,0 +1,77 @@
import { detachedWindowLabel, detachedWindowUrl } from "@/lib/app/windowContext";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
export interface DetachedWindowOpenPosition {
x: number;
y: number;
}
export interface DetachedWindowOpenResult {
opened: boolean;
error?: string;
}
function errorMessage(error: unknown): string {
if (typeof error === "string") return error;
if (error && typeof error === "object" && "message" in error && typeof error.message === "string") return error.message;
return String(error || "Unknown window creation error");
}
export async function openDetachedTabWindow(tabId: string, title: string, position?: DetachedWindowOpenPosition): Promise<DetachedWindowOpenResult> {
if (!isTauriRuntime()) return { opened: false, error: "Detached windows are only available in the desktop app." };
try {
const { WebviewWindow } = await import("@tauri-apps/api/webviewWindow");
const label = detachedWindowLabel(tabId);
const existing = await WebviewWindow.getByLabel(label);
if (existing) {
await existing.show();
await existing.setFocus();
return { opened: true };
}
const child = new WebviewWindow(label, {
url: detachedWindowUrl(tabId),
title,
width: 1100,
height: 720,
minWidth: 760,
minHeight: 600,
resizable: true,
visible: false,
decorations: false,
center: false,
});
return await new Promise((resolve) => {
let settled = false;
const finish = (result: DetachedWindowOpenResult) => {
if (settled) return;
settled = true;
resolve(result);
};
void child.once("tauri://created", async () => {
try {
if (position) {
const { PhysicalPosition } = await import("@tauri-apps/api/dpi");
await child.setPosition(new PhysicalPosition(Math.round(position.x - 120), Math.round(position.y - 20)));
}
await child.show();
await child.setFocus();
finish({ opened: true });
} catch (error) {
finish({ opened: false, error: errorMessage(error) });
}
});
void child.once("tauri://error", (event) => {
const error = errorMessage(event?.payload);
console.error("[DBX][detached-tab:create:error]", error);
finish({ opened: false, error });
});
setTimeout(() => finish({ opened: false, error: "Timed out while creating the detached window." }), 10_000);
});
} catch (error) {
const message = errorMessage(error);
console.error("[DBX][detached-tab:create:error]", error);
return { opened: false, error: message };
}
}
+46
View File
@@ -0,0 +1,46 @@
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
export type WindowContext = { kind: "main"; windowLabel: "main" } | { kind: "detached-tab"; windowLabel: string; tabId: string };
const DETACHED_WINDOW_PARAM = "dbxDetachedTab";
let cachedContext: WindowContext | undefined;
export function detachedWindowLabel(tabId: string): string {
return `detached-tab-${tabId}`;
}
export function resolveWindowContext(): WindowContext {
if (cachedContext) return cachedContext;
if (!isTauriRuntime()) {
cachedContext = { kind: "main", windowLabel: "main" };
return cachedContext;
}
const tabId = new URLSearchParams(window.location.search).get(DETACHED_WINDOW_PARAM)?.trim();
if (tabId) {
// The window label is not available synchronously from the Tauri API. The
// deterministic label is also what the creator uses, so it is sufficient
// for routing and event targeting during bootstrap.
cachedContext = { kind: "detached-tab", windowLabel: detachedWindowLabel(tabId), tabId };
} else {
cachedContext = { kind: "main", windowLabel: "main" };
}
return cachedContext;
}
export function isDetachedWindow(): boolean {
return resolveWindowContext().kind === "detached-tab";
}
export function detachedTabId(): string | undefined {
const context = resolveWindowContext();
return context.kind === "detached-tab" ? context.tabId : undefined;
}
export function detachedWindowUrl(tabId: string): string {
const url = new URL(window.location.href);
url.search = new URLSearchParams({ [DETACHED_WINDOW_PARAM]: tabId }).toString();
url.hash = "";
return url.toString();
}
+5
View File
@@ -328,6 +328,11 @@ export const loadEditorSettings = forward("loadEditorSettings");
export const saveEditorSettings = forward("saveEditorSettings"); export const saveEditorSettings = forward("saveEditorSettings");
export const loadOpenTabsState = forward("loadOpenTabsState"); export const loadOpenTabsState = forward("loadOpenTabsState");
export const saveOpenTabsState = forward("saveOpenTabsState"); export const saveOpenTabsState = forward("saveOpenTabsState");
export const saveDetachedTabHandoff = forward("saveDetachedTabHandoff");
export const loadDetachedTabHandoff = forward("loadDetachedTabHandoff");
export const listDetachedTabHandoffs = forward("listDetachedTabHandoffs");
export const deleteDetachedTabHandoff = forward("deleteDetachedTabHandoff");
export const approveDetachedWindowClose = forward("approveDetachedWindowClose");
export const loadSavedSqlEditorPositions = forward("loadSavedSqlEditorPositions"); export const loadSavedSqlEditorPositions = forward("loadSavedSqlEditorPositions");
export const saveSavedSqlEditorPositions = forward("saveSavedSqlEditorPositions"); export const saveSavedSqlEditorPositions = forward("saveSavedSqlEditorPositions");
export const loadTransferTaskLibrary = forward("loadTransferTaskLibrary"); export const loadTransferTaskLibrary = forward("loadTransferTaskLibrary");
+15
View File
@@ -48,6 +48,7 @@ import type {
SshConfigHostEntry, SshConfigHostEntry,
TunnelProfile, TunnelProfile,
} from "@/types/database"; } from "@/types/database";
import type { DetachedTabHandoff } from "@/lib/app/detachedTabHandoff";
import { normalizeRustMongoCommand, type MongoCommand } from "@/lib/mongo/mongoShellCommand"; import { normalizeRustMongoCommand, type MongoCommand } from "@/lib/mongo/mongoShellCommand";
import { BackendErrorException, type BackendError } from "@/lib/backend/errorUtils"; import { BackendErrorException, type BackendError } from "@/lib/backend/errorUtils";
import { decodeMeilisearchDocumentPage, decodeMeilisearchSearchResult, type MeilisearchDocumentPage, type MeilisearchDocumentPageWire, type MeilisearchSearchResult, type MeilisearchSearchWireResult } from "@/lib/backend/meilisearchTransport"; import { decodeMeilisearchDocumentPage, decodeMeilisearchSearchResult, type MeilisearchDocumentPage, type MeilisearchDocumentPageWire, type MeilisearchSearchResult, type MeilisearchSearchWireResult } from "@/lib/backend/meilisearchTransport";
@@ -1897,6 +1898,20 @@ export async function saveOpenTabsState(payload: OpenTabsStatePayload): Promise<
await saveBrowserAppState("open_tabs", payload); await saveBrowserAppState("open_tabs", payload);
} }
export async function saveDetachedTabHandoff(_tabId: string, _handoff: DetachedTabHandoff): Promise<void> {}
export async function loadDetachedTabHandoff(_tabId: string): Promise<DetachedTabHandoff | null> {
return null;
}
export async function listDetachedTabHandoffs(): Promise<DetachedTabHandoff[]> {
return [];
}
export async function deleteDetachedTabHandoff(_tabId: string): Promise<void> {}
export async function approveDetachedWindowClose(): Promise<void> {}
export async function loadSavedSqlEditorPositions(): Promise<unknown[] | null> { export async function loadSavedSqlEditorPositions(): Promise<unknown[] | null> {
const value = await loadBrowserAppState("saved_sql_editor_positions"); const value = await loadBrowserAppState("saved_sql_editor_positions");
return Array.isArray(value) ? value : null; return Array.isArray(value) ? value : null;
+21
View File
@@ -1,4 +1,5 @@
import { invoke } from "@tauri-apps/api/core"; import { invoke } from "@tauri-apps/api/core";
import type { DetachedTabHandoff } from "@/lib/app/detachedTabHandoff";
import { BackendErrorException, type BackendError } from "@/lib/backend/errorUtils"; import { BackendErrorException, type BackendError } from "@/lib/backend/errorUtils";
import { listen, type UnlistenFn } from "@tauri-apps/api/event"; import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { normalizeRustMongoCommand, type MongoCommand } from "@/lib/mongo/mongoShellCommand"; import { normalizeRustMongoCommand, type MongoCommand } from "@/lib/mongo/mongoShellCommand";
@@ -739,6 +740,26 @@ export async function saveOpenTabsState(payload: OpenTabsStatePayload): Promise<
return invoke("save_open_tabs_state", { payload }); return invoke("save_open_tabs_state", { payload });
} }
export async function saveDetachedTabHandoff(tabId: string, handoff: DetachedTabHandoff): Promise<void> {
return invoke("save_detached_tab_handoff", { tabId, handoff });
}
export async function loadDetachedTabHandoff(tabId: string): Promise<DetachedTabHandoff | null> {
return invoke("load_detached_tab_handoff", { tabId });
}
export async function listDetachedTabHandoffs(): Promise<DetachedTabHandoff[]> {
return invoke("list_detached_tab_handoffs");
}
export async function deleteDetachedTabHandoff(tabId: string): Promise<void> {
return invoke("delete_detached_tab_handoff", { tabId });
}
export async function approveDetachedWindowClose(): Promise<void> {
return invoke("approve_detached_window_close");
}
export async function loadSavedSqlEditorPositions(): Promise<unknown[] | null> { export async function loadSavedSqlEditorPositions(): Promise<unknown[] | null> {
return invoke("load_saved_sql_editor_positions"); return invoke("load_saved_sql_editor_positions");
} }
+107 -1
View File
@@ -75,6 +75,9 @@ import { recordQueryCancellationLatency, resourceLifecycleDiagnostics } from "@/
import { appendDebugLog } from "@/lib/backend/debugLog"; import { appendDebugLog } from "@/lib/backend/debugLog";
import { BackendErrorException, formatError, isManualTransactionSessionExpired, isUnsupportedManualTransactionMethod, normalizeBackendError, type BackendError } from "@/lib/backend/errorUtils"; import { BackendErrorException, formatError, isManualTransactionSessionExpired, isUnsupportedManualTransactionMethod, normalizeBackendError, type BackendError } from "@/lib/backend/errorUtils";
import { createSavedSqlEditorPosition, initSavedSqlEditorPositions, restoreSavedSqlEditorPosition, saveSavedSqlEditorPosition } from "@/lib/app/savedSqlEditorPosition"; import { createSavedSqlEditorPosition, initSavedSqlEditorPositions, restoreSavedSqlEditorPosition, saveSavedSqlEditorPosition } from "@/lib/app/savedSqlEditorPosition";
import { isDetachedWindow, resolveWindowContext } from "@/lib/app/windowContext";
import type { DetachedTabHandoff, DetachedTabRuntimeState } from "@/lib/app/detachedTabHandoff";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { ensureSqlExtension } from "@/lib/savedSql/savedSqlFileName"; import { ensureSqlExtension } from "@/lib/savedSql/savedSqlFileName";
import { resolveSavedSqlExecutionTarget, savedSqlExecutionTargetFromTab, type SavedSqlExecutionTarget, type SavedSqlOpenTargetMode } from "@/lib/savedSql/savedSqlExecutionTarget"; import { resolveSavedSqlExecutionTarget, savedSqlExecutionTargetFromTab, type SavedSqlExecutionTarget, type SavedSqlOpenTargetMode } from "@/lib/savedSql/savedSqlExecutionTarget";
import { safeLocalStorageGet, safeLocalStorageRemove } from "@/lib/backend/safeStorage"; import { safeLocalStorageGet, safeLocalStorageRemove } from "@/lib/backend/safeStorage";
@@ -687,6 +690,7 @@ let persistTimer: ReturnType<typeof setTimeout> | null = null;
let persistGeneration = 0; let persistGeneration = 0;
function saveTabs(tabs: QueryTab[], activeTabId: string | null): Promise<void> { function saveTabs(tabs: QueryTab[], activeTabId: string | null): Promise<void> {
if (isDetachedWindow()) return Promise.resolve();
const payload = { tabs: serializeOpenTabs(tabs), activeTabId }; const payload = { tabs: serializeOpenTabs(tabs), activeTabId };
saveTabsQueue = saveTabsQueue.catch(() => undefined).then(() => api.saveOpenTabsState(payload)); saveTabsQueue = saveTabsQueue.catch(() => undefined).then(() => api.saveOpenTabsState(payload));
return saveTabsQueue; return saveTabsQueue;
@@ -785,6 +789,7 @@ export const useQueryStore = defineStore("query", () => {
let resultCacheTrimScheduled = false; let resultCacheTrimScheduled = false;
let resultCacheTrimRunning = false; let resultCacheTrimRunning = false;
let resultCacheTrimRequested = false; let resultCacheTrimRequested = false;
let detachedHandoffRevision = 0;
function tableStructureKey(connectionId: string, database: string, schema: string | undefined, tableName: string): string { function tableStructureKey(connectionId: string, database: string, schema: string | undefined, tableName: string): string {
return [connectionId, database, schema || "", tableName].map((part) => part.toLowerCase()).join("\u0000"); return [connectionId, database, schema || "", tableName].map((part) => part.toLowerCase()).join("\u0000");
@@ -1684,6 +1689,22 @@ export const useQueryStore = defineStore("query", () => {
} }
} }
async function recoverDetachedTabsToMain(options: { validConnectionIds?: Iterable<string> } = {}) {
if (!isTauriRuntime() || useSettingsStore().editorSettings.openTabsRestoreMode === "none") return;
const validConnectionIds = options.validConnectionIds ? new Set(options.validConnectionIds) : undefined;
const handoffs = await api.listDetachedTabHandoffs().catch(() => []);
for (const handoff of handoffs) {
if (!handoff || handoff.schemaVersion !== 1 || !handoff.tabId || !handoff.tab || typeof handoff.tab.id !== "string" || handoff.tab.id !== handoff.tabId) continue;
if (validConnectionIds && handoff.tab.mode !== "query" && !validConnectionIds.has(handoff.tab.connectionId)) continue;
try {
await adoptDetachedTab(handoff);
await api.deleteDetachedTabHandoff(handoff.tabId);
} catch (error) {
console.warn("[DBX][detached-tab:restore:error]", error);
}
}
}
function scheduleResultCacheMaintenance() { function scheduleResultCacheMaintenance() {
const maintain = () => { const maintain = () => {
const liveKeys = tabs.value.flatMap((tab) => [tab.resultCacheKey, ...(tab.resultRuns?.map((run) => run.resultCacheKey) ?? [])]).filter((key): key is string => !!key); const liveKeys = tabs.value.flatMap((tab) => [tab.resultCacheKey, ...(tab.resultRuns?.map((run) => run.resultCacheKey) ?? [])]).filter((key): key is string => !!key);
@@ -1695,6 +1716,7 @@ export const useQueryStore = defineStore("query", () => {
} }
async function initOpenTabs(options: { validConnectionIds?: Iterable<string> } = {}) { async function initOpenTabs(options: { validConnectionIds?: Iterable<string> } = {}) {
if (isDetachedWindow()) return;
if (isOpenTabsLoaded.value) return; if (isOpenTabsLoaded.value) return;
const saved = await api.loadOpenTabsState().catch(() => null); const saved = await api.loadOpenTabsState().catch(() => null);
if (saved?.tabs && Array.isArray(saved.tabs)) { if (saved?.tabs && Array.isArray(saved.tabs)) {
@@ -1706,6 +1728,8 @@ export const useQueryStore = defineStore("query", () => {
clearLegacySavedTabs(); clearLegacySavedTabs();
await saveTabs(tabs.value, activeTabId.value).catch(() => undefined); await saveTabs(tabs.value, activeTabId.value).catch(() => undefined);
} }
await recoverDetachedTabsToMain(options);
await saveTabs(tabs.value, activeTabId.value).catch(() => undefined);
isOpenTabsLoaded.value = true; isOpenTabsLoaded.value = true;
scheduleResultCacheMaintenance(); scheduleResultCacheMaintenance();
return; return;
@@ -1723,6 +1747,7 @@ export const useQueryStore = defineStore("query", () => {
scheduleResultCacheMaintenance(); scheduleResultCacheMaintenance();
return; return;
} }
await recoverDetachedTabsToMain(options);
try { try {
await saveTabs(tabs.value, activeTabId.value); await saveTabs(tabs.value, activeTabId.value);
// Keep old desktop installs readable until the async store has the // Keep old desktop installs readable until the async store has the
@@ -1732,6 +1757,8 @@ export const useQueryStore = defineStore("query", () => {
/* keep legacy values for a later migration attempt */ /* keep legacy values for a later migration attempt */
} }
} }
await recoverDetachedTabsToMain(options);
await saveTabs(tabs.value, activeTabId.value).catch(() => undefined);
isOpenTabsLoaded.value = true; isOpenTabsLoaded.value = true;
scheduleResultCacheMaintenance(); scheduleResultCacheMaintenance();
} }
@@ -1795,7 +1822,8 @@ export const useQueryStore = defineStore("query", () => {
if (storePersistGeneration !== persistGeneration) return; if (storePersistGeneration !== persistGeneration) return;
if (persistTimer) clearTimeout(persistTimer); if (persistTimer) clearTimeout(persistTimer);
persistTimer = setTimeout(() => { persistTimer = setTimeout(() => {
void saveTabs(tabs.value, activeTabId.value).catch(() => {}); if (isDetachedWindow()) void flushDetachedTabPersistence(activeTabId.value ?? undefined).catch(() => {});
else void saveTabs(tabs.value, activeTabId.value).catch(() => {});
persistTimer = null; persistTimer = null;
}, 300); }, 300);
}, },
@@ -1813,6 +1841,7 @@ export const useQueryStore = defineStore("query", () => {
// Lets callers (e.g. tests that reload the store) read back persisted state // Lets callers (e.g. tests that reload the store) read back persisted state
// deterministically instead of racing the debounce timer. // deterministically instead of racing the debounce timer.
function flushPendingPersist(): Promise<void> { function flushPendingPersist(): Promise<void> {
if (isDetachedWindow()) return flushDetachedTabPersistence(activeTabId.value ?? undefined);
if (storePersistGeneration !== persistGeneration) return Promise.resolve(); if (storePersistGeneration !== persistGeneration) return Promise.resolve();
if (persistTimer) { if (persistTimer) {
clearTimeout(persistTimer); clearTimeout(persistTimer);
@@ -1821,6 +1850,79 @@ export const useQueryStore = defineStore("query", () => {
return saveTabs(tabs.value, activeTabId.value); return saveTabs(tabs.value, activeTabId.value);
} }
async function prepareDetachedTab(tabId: string, runtime: DetachedTabRuntimeState = {}): Promise<DetachedTabHandoff> {
const tab = tabs.value.find((candidate) => candidate.id === tabId);
if (!tab) throw new Error("Tab is no longer open");
if (tab.mode !== "query" && tab.mode !== "data") throw new Error("Only SQL and data tabs can be detached");
if (tab.isExecuting || tab.isCancelling || tab.isExplaining) throw new Error("Wait for the current operation to finish before detaching this tab");
const savedTab = serializeOpenTabs([tab])[0];
if (!savedTab) throw new Error("Unable to serialize tab");
const resultCacheKey = tabResultCacheKey(tab.id);
const snapshot = buildTabResultSnapshot(tab) ?? (tab.resultCacheKey ? await readTabResultSnapshot(tab.resultCacheKey) : undefined);
if (snapshot) {
const cached = await writeTabResultSnapshot(resultCacheKey, snapshot, tab.connectionId);
if (!cached) throw new Error("Unable to cache the tab result for the detached window");
tab.resultCacheKey = resultCacheKey;
tab.resultCacheState = "disk";
}
detachedHandoffRevision += 1;
return {
schemaVersion: 1,
tabId,
sourceWindowLabel: resolveWindowContext().windowLabel,
revision: detachedHandoffRevision,
tab: savedTab,
runtime: {
editorViewport: tab.editorViewport,
editorSelection: tab.editorSelection,
txnSessionId: tab.txnSessionId,
txnAutoRolledBack: tab.txnAutoRolledBack,
oracleTxnPossiblyDirty: tab.oracleTxnPossiblyDirty,
...runtime,
},
...(snapshot ? { resultCacheKey } : {}),
updatedAt: Date.now(),
};
}
async function flushDetachedTabPersistence(tabId?: string, runtime: DetachedTabRuntimeState = {}): Promise<void> {
if (!isDetachedWindow() || !tabId) return;
const handoff = await prepareDetachedTab(tabId, runtime);
await api.saveDetachedTabHandoff(tabId, handoff);
}
async function adoptDetachedTab(handoff: DetachedTabHandoff): Promise<string> {
if (!handoff || handoff.schemaVersion !== 1 || !handoff.tab || typeof handoff.tab.id !== "string" || handoff.tab.id !== handoff.tabId) throw new Error("Unsupported detached tab state");
const restored = restoreOpenTabsPayload({ tabs: [handoff.tab], activeTabId: handoff.tabId });
const restoredTab = restored.tabs[0];
if (!restoredTab) throw new Error("Unable to restore detached tab");
Object.assign(restoredTab, handoff.runtime);
if (handoff.resultCacheKey) {
restoredTab.resultCacheKey = handoff.resultCacheKey;
const restoredResult = restoreCachedResultPayload(restoredTab, await readTabResultSnapshot(handoff.resultCacheKey));
if (!restoredResult) restoredTab.resultCacheState = "missing";
}
const existingIndex = tabs.value.findIndex((tab) => tab.id === handoff.tabId);
if (existingIndex >= 0) {
tabs.value.splice(existingIndex, 1, restoredTab);
} else {
tabs.value.push(restoredTab);
}
activeTabId.value = handoff.tabId;
return handoff.tabId;
}
function removeTabAfterDetachedReady(tabId: string): boolean {
const index = tabs.value.findIndex((tab) => tab.id === tabId);
if (index < 0) return false;
tabs.value.splice(index, 1);
if (activeTabId.value === tabId) activeTabId.value = tabs.value[Math.min(index, tabs.value.length - 1)]?.id ?? null;
return true;
}
function findTabByIdentity(connectionId: string, database: string, title: string, mode: QueryTab["mode"], schema?: string, catalog?: string) { function findTabByIdentity(connectionId: string, database: string, title: string, mode: QueryTab["mode"], schema?: string, catalog?: string) {
if (mode === "meilisearch-system") { if (mode === "meilisearch-system") {
return tabs.value.find((tab) => tab.connectionId === connectionId && tab.mode === mode); return tabs.value.find((tab) => tab.connectionId === connectionId && tab.mode === mode);
@@ -6935,6 +7037,10 @@ export const useQueryStore = defineStore("query", () => {
isOpenTabsLoaded, isOpenTabsLoaded,
recentTabIds, recentTabIds,
initOpenTabs, initOpenTabs,
prepareDetachedTab,
adoptDetachedTab,
removeTabAfterDetachedReady,
flushDetachedTabPersistence,
showCloseConfirm, showCloseConfirm,
pendingCloseTabId, pendingCloseTabId,
closeConfirmContext, closeConfirmContext,
+6 -1
View File
@@ -2,7 +2,7 @@
"$schema": "../gen/schemas/desktop-schema.json", "$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default", "identifier": "default",
"description": "enables the default permissions", "description": "enables the default permissions",
"windows": ["main"], "windows": ["main", "detached-tab-*"],
"permissions": [ "permissions": [
"core:default", "core:default",
"core:window:allow-show", "core:window:allow-show",
@@ -17,6 +17,11 @@
"core:window:allow-set-fullscreen", "core:window:allow-set-fullscreen",
"core:window:allow-close", "core:window:allow-close",
"core:window:allow-start-dragging", "core:window:allow-start-dragging",
"core:window:allow-set-focus",
"core:window:allow-set-position",
"core:window:allow-inner-position",
"core:window:allow-scale-factor",
"core:webview:allow-create-webview-window",
"core:webview:allow-set-webview-zoom", "core:webview:allow-set-webview-zoom",
"clipboard-manager:allow-read-text", "clipboard-manager:allow-read-text",
"clipboard-manager:allow-write-text", "clipboard-manager:allow-write-text",
+73 -1
View File
@@ -1,6 +1,7 @@
use std::{ use std::{
collections::HashSet,
path::{Path, PathBuf}, path::{Path, PathBuf},
sync::Arc, sync::{Arc, Mutex, OnceLock},
}; };
use dbx_core::storage::{DesktopSettings, McpGlobalPolicy, McpGlobalPolicyState}; use dbx_core::storage::{DesktopSettings, McpGlobalPolicy, McpGlobalPolicyState};
@@ -13,6 +14,30 @@ use crate::{
}; };
const DEVELOPMENT_OPEN_TABS_STATE_KEY: &str = "development_open_tabs"; const DEVELOPMENT_OPEN_TABS_STATE_KEY: &str = "development_open_tabs";
const DETACHED_TABS_STATE_KEY: &str = "detached_tabs";
static DETACHED_TABS_LOCK: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();
static APPROVED_DETACHED_CLOSES: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
fn detached_tabs_lock() -> &'static tokio::sync::Mutex<()> {
DETACHED_TABS_LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
}
fn approved_detached_closes() -> &'static Mutex<HashSet<String>> {
APPROVED_DETACHED_CLOSES.get_or_init(|| Mutex::new(HashSet::new()))
}
pub(crate) fn take_approved_detached_window_close(label: &str) -> bool {
approved_detached_closes().lock().map(|mut labels| labels.remove(label)).unwrap_or(false)
}
async fn load_detached_tabs_map(state: &AppState) -> Result<serde_json::Map<String, serde_json::Value>, String> {
Ok(state
.storage
.load_open_tabs_state_with_key(DETACHED_TABS_STATE_KEY)
.await?
.and_then(|value| value.as_object().cloned())
.unwrap_or_default())
}
fn open_tabs_state_key(debug_build: bool) -> &'static str { fn open_tabs_state_key(debug_build: bool) -> &'static str {
if debug_build { if debug_build {
@@ -161,6 +186,53 @@ pub async fn save_open_tabs_state(state: State<'_, Arc<AppState>>, payload: serd
state.storage.save_open_tabs_state_with_key(open_tabs_state_key(cfg!(debug_assertions)), &payload).await state.storage.save_open_tabs_state_with_key(open_tabs_state_key(cfg!(debug_assertions)), &payload).await
} }
#[tauri::command]
pub async fn save_detached_tab_handoff(
state: State<'_, Arc<AppState>>,
tab_id: String,
handoff: serde_json::Value,
) -> Result<(), String> {
let _guard = detached_tabs_lock().lock().await;
let mut tabs = load_detached_tabs_map(state.inner()).await?;
tabs.insert(tab_id, handoff);
state.storage.save_open_tabs_state_with_key(DETACHED_TABS_STATE_KEY, &serde_json::Value::Object(tabs)).await
}
#[tauri::command]
pub async fn load_detached_tab_handoff(
state: State<'_, Arc<AppState>>,
tab_id: String,
) -> Result<Option<serde_json::Value>, String> {
let _guard = detached_tabs_lock().lock().await;
Ok(load_detached_tabs_map(state.inner()).await?.remove(&tab_id))
}
#[tauri::command]
pub async fn list_detached_tab_handoffs(state: State<'_, Arc<AppState>>) -> Result<Vec<serde_json::Value>, String> {
let _guard = detached_tabs_lock().lock().await;
Ok(load_detached_tabs_map(state.inner()).await?.into_values().collect())
}
#[tauri::command]
pub async fn delete_detached_tab_handoff(state: State<'_, Arc<AppState>>, tab_id: String) -> Result<(), String> {
let _guard = detached_tabs_lock().lock().await;
let mut tabs = load_detached_tabs_map(state.inner()).await?;
tabs.remove(&tab_id);
state.storage.save_open_tabs_state_with_key(DETACHED_TABS_STATE_KEY, &serde_json::Value::Object(tabs)).await
}
#[tauri::command]
pub fn approve_detached_window_close(window: Window) -> Result<(), String> {
if !window.label().starts_with("detached-tab-") {
return Err("current window is not a detached tab window".to_string());
}
approved_detached_closes()
.lock()
.map_err(|_| "detached window close state is unavailable".to_string())?
.insert(window.label().to_string());
Ok(())
}
#[tauri::command] #[tauri::command]
pub async fn load_saved_sql_editor_positions( pub async fn load_saved_sql_editor_positions(
state: State<'_, Arc<AppState>>, state: State<'_, Arc<AppState>>,
+22
View File
@@ -1697,7 +1697,24 @@ pub fn run() {
Ok(()) Ok(())
}) })
.on_window_event(|window, event| { .on_window_event(|window, event| {
if let tauri::WindowEvent::Destroyed = event {
if let Some(tab_id) = window.label().strip_prefix("detached-tab-") {
let _ = window.emit("dbx:detached-tab-lost", serde_json::json!({ "tabId": tab_id }));
}
return;
}
if let tauri::WindowEvent::CloseRequested { api, .. } = event { if let tauri::WindowEvent::CloseRequested { api, .. } = event {
if let Some(tab_id) = window.label().strip_prefix("detached-tab-") {
if commands::app_settings::take_approved_detached_window_close(window.label()) {
return;
}
api.prevent_close();
// Broadcast with the tabId payload: JS listeners registered
// with the default `listen()` target receive events emitted
// to any window, so the frontend must filter by tabId.
let _ = window.emit("dbx:detached-tab-close-requested", serde_json::json!({ "tabId": tab_id }));
return;
}
if !should_hide_window_on_close(std::env::consts::OS) { if !should_hide_window_on_close(std::env::consts::OS) {
return; return;
} }
@@ -1768,6 +1785,11 @@ pub fn run() {
commands::app_settings::save_editor_settings, commands::app_settings::save_editor_settings,
commands::app_settings::load_open_tabs_state, commands::app_settings::load_open_tabs_state,
commands::app_settings::save_open_tabs_state, commands::app_settings::save_open_tabs_state,
commands::app_settings::save_detached_tab_handoff,
commands::app_settings::load_detached_tab_handoff,
commands::app_settings::list_detached_tab_handoffs,
commands::app_settings::delete_detached_tab_handoff,
commands::app_settings::approve_detached_window_close,
commands::app_settings::load_saved_sql_editor_positions, commands::app_settings::load_saved_sql_editor_positions,
commands::app_settings::save_saved_sql_editor_positions, commands::app_settings::save_saved_sql_editor_positions,
commands::app_settings::load_transfer_task_library, commands::app_settings::load_transfer_task_library,