fix(editor): prompt before closing unsaved SQL tabs

Co-authored-by: staff <staff@qimaos-MacBook-Pro.local>
This commit is contained in:
zipgandstaff authored and GitHub committed 2026-07-02 16:43:55 +08:00
1 parent 23b9228f82
commit 4efff9a190
26 files changed
+1273 -100

No files matched your search

@@ -214,6 +214,7 @@ const editWordWrap = ref(settingsStore.editorSettings.wordWrap);
const editSqlSemanticDiagnosticsMode = ref<SqlSemanticDiagnosticsMode>(settingsStore.editorSettings.sqlSemanticDiagnosticsMode);
const editSqlSemanticDiagnosticsEnabled = ref(settingsStore.editorSettings.sqlSemanticDiagnosticsEnabled);
const editConfirmDangerousSqlExecution = ref(settingsStore.editorSettings.confirmDangerousSqlExecution);
const editConfirmUnsavedSqlClose = ref(settingsStore.editorSettings.confirmUnsavedSqlClose);
const editAppLayout = ref(settingsStore.editorSettings.appLayout);
const editShowTrayIcon = ref(settingsStore.desktopSettings.show_tray_icon);
const editQuitOnClose = ref(settingsStore.desktopSettings.quit_on_close);
@@ -495,6 +496,7 @@ watch(
editSqlSemanticDiagnosticsMode.value = settingsStore.editorSettings.sqlSemanticDiagnosticsMode;
editSqlSemanticDiagnosticsEnabled.value = settingsStore.editorSettings.sqlSemanticDiagnosticsEnabled;
editConfirmDangerousSqlExecution.value = settingsStore.editorSettings.confirmDangerousSqlExecution;
editConfirmUnsavedSqlClose.value = settingsStore.editorSettings.confirmUnsavedSqlClose;
editAppLayout.value = settingsStore.editorSettings.appLayout;
editShowTrayIcon.value = settingsStore.desktopSettings.show_tray_icon;
editQuitOnClose.value = settingsStore.desktopSettings.quit_on_close;
@@ -562,6 +564,7 @@ function hasChanges(): boolean {
editSqlSemanticDiagnosticsMode.value !== settingsStore.editorSettings.sqlSemanticDiagnosticsMode ||
editSqlSemanticDiagnosticsEnabled.value !== settingsStore.editorSettings.sqlSemanticDiagnosticsEnabled ||
editConfirmDangerousSqlExecution.value !== settingsStore.editorSettings.confirmDangerousSqlExecution ||
editConfirmUnsavedSqlClose.value !== settingsStore.editorSettings.confirmUnsavedSqlClose ||
editAppLayout.value !== settingsStore.editorSettings.appLayout ||
editShowTrayIcon.value !== settingsStore.desktopSettings.show_tray_icon ||
editQuitOnClose.value !== settingsStore.desktopSettings.quit_on_close ||
@@ -614,6 +617,7 @@ async function persistSettings() {
wordWrap: editWordWrap.value,
sqlSemanticDiagnosticsMode: editSqlSemanticDiagnosticsMode.value,
confirmDangerousSqlExecution: editConfirmDangerousSqlExecution.value,
confirmUnsavedSqlClose: editConfirmUnsavedSqlClose.value,
appLayout: editAppLayout.value,
showColumnCommentsInHeader: editShowColumnCommentsInHeader.value,
showColumnTypesInHeader: editShowColumnTypesInHeader.value,
@@ -678,6 +682,7 @@ function resetDefaultsForTab(tab: SettingsCategory) {
editSqlSemanticDiagnosticsMode.value = DEFAULT_EDITOR_SETTINGS.sqlSemanticDiagnosticsMode;
editSqlSemanticDiagnosticsEnabled.value = DEFAULT_EDITOR_SETTINGS.sqlSemanticDiagnosticsEnabled;
editConfirmDangerousSqlExecution.value = DEFAULT_EDITOR_SETTINGS.confirmDangerousSqlExecution;
editConfirmUnsavedSqlClose.value = DEFAULT_EDITOR_SETTINGS.confirmUnsavedSqlClose;
} else if (tab === "formatter") {
editSqlFormatter.value = normalizeSqlFormatterSettings(DEFAULT_EDITOR_SETTINGS.sqlFormatter);
sqlFormatterConfigValid.value = true;
@@ -740,6 +745,7 @@ function resetAllDefaults() {
editSqlSemanticDiagnosticsMode.value = DEFAULT_EDITOR_SETTINGS.sqlSemanticDiagnosticsMode;
editSqlSemanticDiagnosticsEnabled.value = DEFAULT_EDITOR_SETTINGS.sqlSemanticDiagnosticsEnabled;
editConfirmDangerousSqlExecution.value = DEFAULT_EDITOR_SETTINGS.confirmDangerousSqlExecution;
editConfirmUnsavedSqlClose.value = DEFAULT_EDITOR_SETTINGS.confirmUnsavedSqlClose;
editAppLayout.value = DEFAULT_EDITOR_SETTINGS.appLayout;
editShowTrayIcon.value = DEFAULT_DESKTOP_SETTINGS.show_tray_icon;
editQuitOnClose.value = DEFAULT_DESKTOP_SETTINGS.quit_on_close;
@@ -1834,6 +1840,12 @@ async function ensureCodexMcpStatus() {
const previewRef = ref<HTMLDivElement>();
const previewView = shallowRef<EditorViewType | null>(null);
interface PreviewSqlDiagnostic {
from: number;
to: number;
message: string;
}
function getPreviewCustomThemeColors(): CustomThemeColors | undefined {
if (editTheme.value !== "custom") return undefined;
const activeTheme = editCustomThemes.value.find((t) => t.id === editActiveCustomThemeId.value);
@@ -1854,13 +1866,46 @@ const previewSettings = computed<{
customColors: getPreviewCustomThemeColors(),
}));
const previewSql = `SELECT u.id, u.name
const previewSqlNormal = `SELECT u.id, u.name
FROM users u
ORDER BY u.id LIMIT 5;`;
const previewSqlWithSyntaxError = `SELECT u.id, u.name
FOM users u
ORDER BY u.id LIMIT 5;`;
let fontThemeComp: import("@codemirror/state").Compartment | null = null;
let themeComp: import("@codemirror/state").Compartment | null = null;
let diagnosticComp: import("@codemirror/state").Compartment | null = null;
let setPreviewDiagnosticsEffect: import("@codemirror/state").StateEffectType<PreviewSqlDiagnostic[]> | null = null;
let editorViewModule: typeof import("@codemirror/view") | null = null;
let previewSqlDiagnostics: PreviewSqlDiagnostic[] = [];
function currentPreviewSql(): string {
return editSqlSemanticDiagnosticsEnabled.value ? previewSqlWithSyntaxError : previewSqlNormal;
}
function previewDiagnosticsForSql(sql: string): PreviewSqlDiagnostic[] {
if (!editSqlSemanticDiagnosticsEnabled.value) return [];
const from = sql.indexOf("FOM");
return from >= 0 ? [{ from, to: from + 3, message: "Syntax error: expected FROM" }] : [];
}
function updatePreviewSqlDiagnostics() {
const view = previewView.value;
if (!view || !setPreviewDiagnosticsEffect) return;
const nextSql = currentPreviewSql();
const currentSql = view.state.doc.toString();
previewSqlDiagnostics = previewDiagnosticsForSql(nextSql);
const effects = setPreviewDiagnosticsEffect.of(previewSqlDiagnostics);
if (currentSql === nextSql) {
view.dispatch({ effects });
return;
}
view.dispatch({
changes: { from: 0, to: currentSql.length, insert: nextSql },
effects,
});
}
watch(
[previewSettings, editCustomThemes, editActiveCustomThemeId],
@@ -1875,6 +1920,10 @@ watch(
{ deep: true },
);
watch(editSqlSemanticDiagnosticsEnabled, () => {
updatePreviewSqlDiagnostics();
});
let previewInitialized = false;
function cleanupPreviewEditor() {
@@ -1884,7 +1933,10 @@ function cleanupPreviewEditor() {
previewInitialized = false;
fontThemeComp = null;
themeComp = null;
diagnosticComp = null;
setPreviewDiagnosticsEffect = null;
editorViewModule = null;
previewSqlDiagnostics = [];
}
watch(activeSettingsTab, (tab) => {
@@ -1898,18 +1950,51 @@ watch(previewRef, async (el) => {
previewInitialized = true;
if (previewView.value) return;
const [{ EditorView }, { EditorState, Compartment }, { sql, MySQL }, { basicSetup }] = await Promise.all([import("@codemirror/view"), import("@codemirror/state"), import("@codemirror/lang-sql"), import("codemirror")]);
const [{ EditorView, Decoration }, { EditorState, Compartment, StateEffect, StateField }, { sql, MySQL }, { basicSetup }] = await Promise.all([import("@codemirror/view"), import("@codemirror/state"), import("@codemirror/lang-sql"), import("codemirror")]);
editorViewModule = { EditorView } as typeof import("@codemirror/view");
fontThemeComp = new Compartment();
themeComp = new Compartment();
diagnosticComp = new Compartment();
setPreviewDiagnosticsEffect = StateEffect.define<PreviewSqlDiagnostic[]>();
previewSqlDiagnostics = previewDiagnosticsForSql(currentPreviewSql());
const ss = previewSettings.value;
const themeExt = await loadEditorTheme(ss.theme, ss.appAppearance, ss.customColors);
const diagnosticTheme = EditorView.baseTheme({
".cm-settings-preview-sql-error": {
textDecoration: "underline wavy var(--destructive)",
textUnderlineOffset: "3px",
},
});
const buildPreviewDiagnosticExtension = () => {
const diagnosticEffect = setPreviewDiagnosticsEffect;
const buildDecorations = () =>
Decoration.set(
previewSqlDiagnostics.map((diagnostic) =>
Decoration.mark({
class: "cm-settings-preview-sql-error",
attributes: { title: diagnostic.message },
}).range(diagnostic.from, diagnostic.to),
),
true,
);
const field = StateField.define({
create: buildDecorations,
update(value, transaction) {
const diagnosticsChanged = !!diagnosticEffect && transaction.effects.some((effect) => effect.is(diagnosticEffect));
return transaction.docChanged || diagnosticsChanged ? buildDecorations() : value;
},
provide: (field) => EditorView.decorations.from(field),
});
return [field, diagnosticTheme];
};
const state = EditorState.create({
doc: previewSql,
extensions: [basicSetup, sql({ dialect: MySQL }), themeComp.of(themeExt), fontThemeComp.of(editorFontTheme(EditorView, ss.fontSize, ss.fontFamily))],
doc: currentPreviewSql(),
extensions: [basicSetup, sql({ dialect: MySQL }), themeComp.of(themeExt), fontThemeComp.of(editorFontTheme(EditorView, ss.fontSize, ss.fontFamily)), diagnosticComp.of(buildPreviewDiagnosticExtension())],
});
previewView.value = new EditorView({ state, parent: previewRef.value });
@@ -2080,6 +2165,16 @@ onUnmounted(cleanupPreviewEditor);
</div>
<Switch id="editor-confirm-dangerous-sql" v-model="editConfirmDangerousSqlExecution" class="mt-0.5" />
</div>
<div class="flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">
<div class="space-y-1">
<Label for="editor-confirm-unsaved-sql-close">{{ t("settings.confirmUnsavedSqlClose") }}</Label>
<p class="text-xs text-muted-foreground">
{{ t("settings.confirmUnsavedSqlCloseDescription") }}
</p>
</div>
<Switch id="editor-confirm-unsaved-sql-close" v-model="editConfirmUnsavedSqlClose" class="mt-0.5" />
</div>
</div>
<Separator />
@@ -1,10 +1,11 @@
<script setup lang="ts">
import { computed, ref, watch, nextTick } from "vue";
import { computed, ref, watch, nextTick, onUnmounted } from "vue";
import type { CSSProperties } from "vue";
import { useI18n } from "vue-i18n";
import { X, Pin, ChevronDown, Table2, Code2, TableProperties, PencilRuler, KeyRound, Pencil, Package, Lock, Copy, AlertTriangle, Network, Minimize2, Maximize2, Settings } from "@lucide/vue";
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
@@ -33,6 +34,10 @@ const emit = defineEmits<{
"activate-settings-page": [];
"close-settings-page": [];
"save-tab": [tabId: string];
"discard-tab-close": [];
"save-all-tab-close": [];
"discard-all-tab-close": [];
"cancel-tab-close": [];
}>();
const { t } = useI18n();
@@ -48,6 +53,27 @@ const isClassicLayout = computed(() => settingsStore.editorSettings.appLayout ==
const fixedTabs = computed(() => queryStore.tabs.filter((tab) => tab.pinned));
const regularTabs = computed(() => queryStore.tabs.filter((tab) => !tab.pinned));
const hasFixedTabs = computed(() => fixedTabs.value.length > 0);
const closeConfirmDirtyCount = computed(() => queryStore.closeConfirmDirtyTabIds.length);
const showCloseConfirmBulkActions = computed(() => closeConfirmDirtyCount.value > 1);
const closeConfirmDirtyTabs = computed(() => queryStore.closeConfirmDirtyTabIds.map((id) => queryStore.tabs.find((tab) => tab.id === id)).filter((tab): tab is QueryTab => !!tab));
const closeConfirmCurrentTitle = computed(() => {
const focusedTab = closeConfirmDirtyTabs.value.find((tab) => tab.id === queryStore.pendingCloseTabId) ?? closeConfirmDirtyTabs.value[0];
return focusedTab ? tabDisplayTitle(focusedTab, t) : "";
});
const closeConfirmMessage = computed(() => {
const params = {
count: closeConfirmDirtyCount.value,
title: closeConfirmCurrentTitle.value,
};
if (closeConfirmDirtyCount.value > 1) {
if (queryStore.closeConfirmContext === "app") return t("editor.unsavedChangesAppCloseMultipleMessage", params);
return t("editor.unsavedChangesBatchCloseMultipleMessage", params);
}
if (queryStore.closeConfirmContext === "app") return t("editor.unsavedChangesAppCloseMessage", params);
return t("editor.unsavedChangesMessage", params);
});
const closeConfirmListOpen = ref(false);
let closeConfirmListCloseTimer: ReturnType<typeof setTimeout> | null = null;
const compactTabTitle = computed({
get: () => settingsStore.editorSettings.compactTabTitle,
set: (checked: boolean | "indeterminate") => {
@@ -55,6 +81,36 @@ const compactTabTitle = computed({
},
});
function openCloseConfirmList() {
if (closeConfirmListCloseTimer) {
clearTimeout(closeConfirmListCloseTimer);
closeConfirmListCloseTimer = null;
}
closeConfirmListOpen.value = true;
}
function scheduleCloseConfirmListClose() {
if (closeConfirmListCloseTimer) clearTimeout(closeConfirmListCloseTimer);
closeConfirmListCloseTimer = setTimeout(() => {
closeConfirmListOpen.value = false;
closeConfirmListCloseTimer = null;
}, 120);
}
onUnmounted(() => {
if (closeConfirmListCloseTimer) {
clearTimeout(closeConfirmListCloseTimer);
closeConfirmListCloseTimer = null;
}
});
watch(
() => queryStore.showCloseConfirm,
(open) => {
if (!open) closeConfirmListOpen.value = false;
},
);
function toggleCompactTabTitle() {
compactTabTitle.value = !compactTabTitle.value;
}
@@ -86,6 +142,13 @@ function cancelRenameTab() {
}
function getTabMenuItems(tab: QueryTab): ContextMenuItem[] {
const closeCurrentLabel = tab.pinned ? t("contextMenu.closeFixedTab") : t("contextMenu.closeTab");
const closeOtherLabel = tab.pinned ? t("contextMenu.closeOtherFixedTabs") : hasFixedTabs.value ? t("contextMenu.closeOtherRegularTabs") : t("contextMenu.closeOtherTabs");
const closeAllLabel = tab.pinned ? t("contextMenu.closeAllFixedTabs") : hasFixedTabs.value ? t("contextMenu.closeAllRegularTabs") : t("contextMenu.closeAllTabs");
const closeOtherDisabled = tab.pinned ? fixedTabs.value.length <= 1 : regularTabs.value.length <= 1;
const closeOtherAction = tab.pinned ? () => queryStore.closeOtherFixedTabs(tab.id) : () => queryStore.closeOtherRegularTabs(tab.id);
const closeAllAction = tab.pinned ? () => queryStore.closeFixedTabs() : () => queryStore.closeRegularTabs();
return [
{
label: compactTabTitle.value ? t("contextMenu.fullTabTitle") : t("contextMenu.compactTabTitle"),
@@ -124,16 +187,16 @@ function getTabMenuItems(tab: QueryTab): ContextMenuItem[] {
iconClass: tab.pinned ? "fill-current" : "",
},
{ label: "", separator: true },
{ label: t("contextMenu.closeTab"), action: () => queryStore.closeTab(tab.id), icon: X },
{ label: closeCurrentLabel, action: () => queryStore.closeTab(tab.id), icon: X },
{
label: t("contextMenu.closeOtherTabs"),
action: () => queryStore.closeOtherTabs(tab.id),
disabled: queryStore.tabs.length <= 1,
label: closeOtherLabel,
action: closeOtherAction,
disabled: closeOtherDisabled,
icon: X,
},
{
label: t("contextMenu.closeAllTabs"),
action: () => queryStore.closeAllTabs(),
label: closeAllLabel,
action: closeAllAction,
variant: "destructive" as const,
icon: X,
},
@@ -147,10 +210,21 @@ function handleSaveAndClose() {
function handleDiscardAndClose() {
queryStore.forceClosePendingTab();
emit("discard-tab-close");
}
function handleSaveAllAndClose() {
emit("save-all-tab-close");
}
function handleDiscardAllAndClose() {
queryStore.forceCloseAllPendingTabs();
emit("discard-all-tab-close");
}
function handleCancelClose() {
queryStore.cancelClosePendingTab();
emit("cancel-tab-close");
}
const tabsContainerRef = ref<HTMLElement | null>(null);
@@ -680,9 +754,36 @@ function onOverflowItemKeydown(event: KeyboardEvent, tabId: string, kind: "regul
{{ t("editor.unsavedChangesTitle") }}
</DialogTitle>
</DialogHeader>
<p class="text-sm text-muted-foreground">{{ t("editor.unsavedChangesMessage") }}</p>
<div class="space-y-2">
<p class="text-sm text-muted-foreground">{{ closeConfirmMessage }}</p>
<Popover v-if="showCloseConfirmBulkActions" :open="closeConfirmListOpen" @update:open="closeConfirmListOpen = $event">
<PopoverTrigger as-child>
<button
type="button"
class="inline-flex items-center text-sm font-medium text-foreground underline-offset-4 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
@mouseenter="openCloseConfirmList"
@mouseleave="scheduleCloseConfirmListClose"
>
{{ t("editor.unsavedChangesViewList", { count: closeConfirmDirtyCount }) }}
</button>
</PopoverTrigger>
<PopoverContent align="start" side="bottom" class="w-72 max-w-[calc(100vw-2rem)] gap-1 p-2" @mouseenter="openCloseConfirmList" @mouseleave="scheduleCloseConfirmListClose" @pointerdown.stop @click.stop @keydown.stop>
<div class="px-2 pb-1 text-xs font-medium text-muted-foreground">
{{ t("editor.unsavedChangesListTitle", { count: closeConfirmDirtyCount }) }}
</div>
<div class="max-h-48 overflow-y-auto">
<div v-for="tab in closeConfirmDirtyTabs" :key="tab.id" class="flex min-w-0 items-center gap-2 rounded-[6px] px-2 py-1.5 text-sm" :class="tab.id === queryStore.pendingCloseTabId ? 'bg-muted text-foreground' : 'text-muted-foreground'">
<span class="h-1.5 w-1.5 shrink-0 rounded-full" :class="tab.id === queryStore.pendingCloseTabId ? 'bg-foreground' : 'bg-muted-foreground/50'" />
<span class="min-w-0 truncate">{{ tabDisplayTitle(tab, t) }}</span>
</div>
</div>
</PopoverContent>
</Popover>
</div>
<DialogFooter>
<Button variant="outline" @click="handleCancelClose">{{ t("common.cancel") }}</Button>
<Button v-if="showCloseConfirmBulkActions" variant="secondary" @click="handleDiscardAllAndClose">{{ t("editor.discardAllChanges") }}</Button>
<Button v-if="showCloseConfirmBulkActions" @click="handleSaveAllAndClose">{{ t("editor.saveAllChanges") }}</Button>
<Button variant="secondary" @click="handleDiscardAndClose">{{ t("editor.discardChanges") }}</Button>
<Button @click="handleSaveAndClose">{{ t("savedSql.save") }}</Button>
</DialogFooter>