diff --git a/apps/desktop/src/components/export/DatabaseExportDialog.vue b/apps/desktop/src/components/export/DatabaseExportDialog.vue index 6cac0cf238..82458bafe1 100644 --- a/apps/desktop/src/components/export/DatabaseExportDialog.vue +++ b/apps/desktop/src/components/export/DatabaseExportDialog.vue @@ -25,6 +25,7 @@ import type { SqlInsertDialect, SqlInsertMode } from "@/lib/export/sqlInsertMode import { revealExportedPath } from "@/lib/export/exportPath"; import { translateBackendError } from "@/i18n/backend-errors"; import { loadSavedDatabaseExportOptions, MAX_SPLIT_SQL_PART_MB, MIN_SPLIT_SQL_PART_MB, saveDatabaseExportOptions, sortDatabaseTableNames } from "@/lib/export/databaseExportOptions"; +import { notifyExportComplete } from "@/lib/export/exportReveal"; const { t } = useI18n(); const { toast } = useToast(); @@ -228,12 +229,24 @@ function normalizedSplitSqlPartMaxMb(): number { // Lenient exports write per-object failures into the SQL file as `-- ERROR` // comments and still finish; completion must warn instead of reporting plain // success (#8184). -function toastDatabaseExportCompletion(errorCount: number, errorSummary: string | null) { +function toastDatabaseExportCompletion(errorCount: number, errorSummary: string | null, filePath?: string | null) { if (errorCount > 0) { - toast(t("databaseExport.exportSuccessWithErrors", { count: errorCount, firstError: errorSummary ?? "" }), 8000); + notifyExportComplete({ + filePath, + message: t("databaseExport.exportSuccessWithErrors", { count: errorCount, firstError: errorSummary ?? "" }), + openFolderLabel: t("exportProgress.openFolder"), + toast, + duration: 8000, + }); return; } - toast(t("databaseExport.exportSuccess"), 3000); + notifyExportComplete({ + filePath, + message: t("databaseExport.exportSuccess"), + openFolderLabel: t("exportProgress.openFolder"), + toast, + duration: 3000, + }); } const canChangeQueryTimeout = computed(() => !!connectionId.value && !!exportWarning.value && isQueryTimeoutErrorMessage(exportWarning.value)); @@ -469,7 +482,7 @@ async function startExport() { exportDone.value = true; exportWarning.value = progress.errorSummary ?? null; isExporting.value = false; - toastDatabaseExportCompletion(progress.errorCount ?? 0, progress.errorSummary ?? null); + toastDatabaseExportCompletion(progress.errorCount ?? 0, progress.errorSummary ?? null, filePath); } else if (progress.status === "Error") { finishExportTiming(); exportError.value = progress.error; @@ -571,6 +584,8 @@ async function startAllDatabasesExport() { preparing: true, }; + let firstExportedFilePath = ""; + for (let index = 0; index < exportPlan.length; index += 1) { if (exportCancelled.value) break; const item = exportPlan[index]!; @@ -578,6 +593,9 @@ async function startAllDatabasesExport() { const currentExportId = `${batchId}-${index + 1}`; activeDatabaseExportId.value = currentExportId; const filePath = isTauriRuntime() ? joinExportPath(directoryPath, `${sanitizeFileName(item.fileStem)}.${splitSqlOutput.value ? "zip" : "sql"}`) : `__web_export_${currentExportId}.${splitSqlOutput.value ? "zip" : "sql"}`; + if (!firstExportedFilePath && isTauriRuntime()) { + firstExportedFilePath = filePath; + } let currentDatabaseRowsExported = 0; const terminal = await runWithDatabaseBackupSnapshot( @@ -665,10 +683,26 @@ async function startAllDatabasesExport() { }; exportProgress.value = finalProgress; updateDatabaseExportTask(batchId, finalProgress); + // On Linux, revealPathInFileManager on a directory path opens the parent directory + // rather than opening into the directory itself. Revealing the first exported file + // navigates directly into the target export directory across all platforms. + const targetPath = firstExportedFilePath || directoryPath; if (batchLenientErrorCount > 0) { - toast(t("databaseExport.exportAllSuccessWithErrors", { count: dbs.length, errorCount: batchLenientErrorCount, firstError: batchFirstErrorSummary ?? "" }), 8000); + notifyExportComplete({ + filePath: targetPath, + message: t("databaseExport.exportAllSuccessWithErrors", { count: dbs.length, errorCount: batchLenientErrorCount, firstError: batchFirstErrorSummary ?? "" }), + openFolderLabel: t("exportProgress.openFolder"), + toast, + duration: 8000, + }); } else { - toast(t("databaseExport.exportAllSuccess", { count: dbs.length }), 3000); + notifyExportComplete({ + filePath: targetPath, + message: t("databaseExport.exportAllSuccess", { count: dbs.length }), + openFolderLabel: t("exportProgress.openFolder"), + toast, + duration: 3000, + }); } } } catch (e: any) { diff --git a/apps/desktop/src/components/kv/KvKeyBrowser.vue b/apps/desktop/src/components/kv/KvKeyBrowser.vue index 56cdc13b4b..bc04c4b51b 100644 --- a/apps/desktop/src/components/kv/KvKeyBrowser.vue +++ b/apps/desktop/src/components/kv/KvKeyBrowser.vue @@ -1512,7 +1512,7 @@ async function exportSelectedKey(): Promise { null, 2, ); - return saveTextFile(content, filename, "DBX KV Bundle", "json", { operation: "kv-key-export" }); + return Boolean(await saveTextFile(content, filename, "DBX KV Bundle", "json", { operation: "kv-key-export" })); } async function exportNode(node: BrowserTreeNode) { diff --git a/apps/desktop/src/composables/useDataGridExport.ts b/apps/desktop/src/composables/useDataGridExport.ts index bcfaad5024..025ab11c4b 100644 --- a/apps/desktop/src/composables/useDataGridExport.ts +++ b/apps/desktop/src/composables/useDataGridExport.ts @@ -2,8 +2,9 @@ import { computed, type ComputedRef, type Ref, createApp } from "vue"; import { useI18n } from "vue-i18n"; import { useDataGridExtractor } from "@/composables/useDataGridExtractor"; import { isTauriRuntime } from "@/lib/backend/tauriRuntime"; -import { autoRevealExportedPathIfConfigured, promptExportSavePath } from "@/lib/export/exportPath"; +import { promptExportSavePath } from "@/lib/export/exportPath"; import { saveTextFile, sanitizeExportBaseName, compactLocalTimestamp } from "@/lib/export/saveTextFile"; +import { notifyExportComplete } from "@/lib/export/exportReveal"; import { dropsSchemaQualifier } from "@/lib/table/tableSelectSql"; import * as api from "@/lib/backend/api"; import { type CellSelectionMatrix, type CellSelectionRange, type SelectionData } from "@/lib/dataGrid/gridSelection"; @@ -827,6 +828,15 @@ export function useDataGridExport(options: UseDataGridExportOptions) { } // --- Export functions --- + function notifyExportSuccess(outputPath?: string | null) { + notifyExportComplete({ + filePath: outputPath, + message: t("grid.exported"), + openFolderLabel: t("exportProgress.openFolder"), + toast, + }); + } + async function runExclusiveExport(action: () => Promise) { const finish = tryStartExclusiveActivation(exportGuard); if (!finish) return; @@ -850,7 +860,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) { operation: `selection-extractor-${extractor}`, }); if (!saved) return; - toast(t("grid.exported")); + notifyExportSuccess(typeof saved === "string" ? saved : undefined); exported = true; } catch (e: any) { toast(t("grid.exportFailed", { message: translateBackendError(t, e) }), 5000); @@ -927,8 +937,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) { finishedAt: Date.now(), }; } - toast(t("grid.exported")); - void autoRevealExportedPathIfConfigured(outputPath); + notifyExportSuccess(outputPath); } catch (e: any) { if (exportProgressState) { exportProgressState.value = { @@ -957,8 +966,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) { } const result = await resultToExport(undefined, undefined, false); await api.exportQueryResultCsv(outputPath, result.columns, result.rows, useSettingsStore().editorSettings.csvQuoteMode, csvNullLiteralForMode(useSettingsStore().editorSettings.csvNullMode)); - toast(t("grid.exported")); - void autoRevealExportedPathIfConfigured(outputPath); + notifyExportSuccess(outputPath); } catch (e: any) { toast(t("grid.exportFailed", { message: translateBackendError(t, e) }), 5000); } @@ -983,8 +991,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) { } const result = await resultToExport(rowIds, undefined, true, true, "name", true); await api.exportQueryResultJson(outputPath, result.columns, result.rows); - toast(t("grid.exported")); - void autoRevealExportedPathIfConfigured(outputPath); + notifyExportSuccess(outputPath); } catch (e: any) { toast(t("grid.exportFailed", { message: translateBackendError(t, e) }), 5000); } @@ -1006,8 +1013,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) { } const result = await resultToExport(undefined, undefined, false, true, "name", true); await api.exportQueryResultJson(outputPath, result.columns, result.rows); - toast(t("grid.exported")); - void autoRevealExportedPathIfConfigured(outputPath); + notifyExportSuccess(outputPath); } catch (e: any) { toast(t("grid.exportFailed", { message: translateBackendError(t, e) }), 5000); } @@ -1031,8 +1037,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) { } const result = await resultToExport(rowIds); await api.exportQueryResultMarkdown(outputPath, result.columns, result.rows); - toast(t("grid.exported")); - void autoRevealExportedPathIfConfigured(outputPath); + notifyExportSuccess(outputPath); } catch (e: any) { toast(t("grid.exportFailed", { message: translateBackendError(t, e) }), 5000); } @@ -1054,8 +1059,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) { } const result = await resultToExport(undefined, undefined, false); await api.exportQueryResultMarkdown(outputPath, result.columns, result.rows); - toast(t("grid.exported")); - void autoRevealExportedPathIfConfigured(outputPath); + notifyExportSuccess(outputPath); } catch (e: any) { toast(t("grid.exportFailed", { message: translateBackendError(t, e) }), 5000); } @@ -1069,8 +1073,9 @@ export function useDataGridExport(options: UseDataGridExportOptions) { if (await exportFullTableDataViaBackend("txt", rowIds)) return; const result = await resultToExport(rowIds); const content = formatTsv(result.columns, result.rows); - await saveTextFile(content, exportFileName(tableMeta.value?.tableName || "export", "txt", { preferFallback: true }), "Text", "txt", { autoOpenFolder: true }); - toast(t("grid.exported")); + const saved = await saveTextFile(content, exportFileName(tableMeta.value?.tableName || "export", "txt", { preferFallback: true }), "Text", "txt"); + if (!saved) return; + notifyExportSuccess(typeof saved === "string" ? saved : undefined); } catch (e: any) { toast(t("grid.exportFailed", { message: translateBackendError(t, e) }), 5000); } @@ -1095,9 +1100,8 @@ export function useDataGridExport(options: UseDataGridExportOptions) { } const result = await resultToExport(rowIds); await api.exportQueryResultHtml(outputPath, currentExportTitle(), result.columns, result.rows); - toast(t("grid.exported")); + notifyExportSuccess(openAfterExport ? undefined : outputPath); if (openAfterExport && isTauriRuntime()) await api.openQueryResultTempFile(outputPath); - else void autoRevealExportedPathIfConfigured(outputPath); } catch (e: any) { toast(t("grid.exportFailed", { message: translateBackendError(t, e) }), 5000); } @@ -1119,8 +1123,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) { } const result = await resultToExport(undefined, undefined, false); await api.exportQueryResultHtml(outputPath, currentExportTitle(), result.columns, result.rows); - toast(t("grid.exported")); - void autoRevealExportedPathIfConfigured(outputPath); + notifyExportSuccess(outputPath); } catch (e: any) { toast(t("grid.exportFailed", { message: translateBackendError(t, e) }), 5000); } @@ -1132,8 +1135,9 @@ export function useDataGridExport(options: UseDataGridExportOptions) { try { const result = await resultToExport(undefined, undefined, false); const content = formatTsv(result.columns, result.rows); - await saveTextFile(content, exportFileName("export-page", "txt", { page: true }), "Text", "txt", { autoOpenFolder: true }); - toast(t("grid.exported")); + const saved = await saveTextFile(content, exportFileName("export-page", "txt", { page: true }), "Text", "txt"); + if (!saved) return; + notifyExportSuccess(typeof saved === "string" ? saved : undefined); } catch (e: any) { toast(t("grid.exportFailed", { message: translateBackendError(t, e) }), 5000); } @@ -1212,7 +1216,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) { finishedAt: Date.now(), }; } - toast(t("grid.exported")); + notifyExportSuccess(openAfterExport ? undefined : outputPath); if (openAfterExport && isTauriRuntime()) { await api.openQueryResultTempFile(outputPath); } @@ -1263,8 +1267,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) { } const result = await resultToExport(undefined, undefined, false, true, exportOptions.headerMode); await writeXlsxResult(outputPath, result, includeSqlSheet, exportOptions.autoFilter, currentPageExportSql()); - toast(t("grid.exported")); - void autoRevealExportedPathIfConfigured(outputPath); + notifyExportSuccess(outputPath); } catch (e: any) { toast(t("grid.exportFailed", { message: translateBackendError(t, e) }), 5000); } @@ -1312,8 +1315,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) { })); const sqlWorksheet = includeSqlSheet ? buildXlsxSqlWorksheet(sheets.map((sheet) => ({ resultName: sheet.sheetName, sql: sheet.sql || sheet.result.sourceStatement || "" }))) : undefined; await api.exportQueryResultsXlsx(outputPath, sqlWorksheet ? [...worksheets, { ...sqlWorksheet, autoFilter: false }] : worksheets, exportOptions.autoFilter, exportPattern || undefined); - toast(t("grid.exported")); - void autoRevealExportedPathIfConfigured(outputPath); + notifyExportSuccess(outputPath); } catch (e: any) { toast(t("grid.exportFailed", { message: translateBackendError(t, e) }), 5000); } @@ -1461,7 +1463,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) { }, ); if (progress.status === "Done") { - toast(t("grid.exported")); + notifyExportSuccess(openAfterExport ? undefined : outputPath); if (openAfterExport && isTauriRuntime()) await api.openQueryResultTempFile(outputPath); } } finally { @@ -1564,7 +1566,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) { tracker.updateTableExportTask(exportId, progress); }); if (terminalProgress.status === "Done") { - toast(t("grid.exported")); + notifyExportSuccess(openAfterExport ? undefined : outputPath); if (openAfterExport && isTauriRuntime()) { await api.openQueryResultTempFile(outputPath); } @@ -1711,9 +1713,10 @@ export function useDataGridExport(options: UseDataGridExportOptions) { true, ); logExportStage("save-start", { contentChars: content.length }, true); - await saveTextFile(content, exportFileName(tableMeta.value?.tableName || "export", "sql", { preferFallback: true }), "SQL", "sql", { exportId, operation: "sql-insert-all", autoOpenFolder: true }); + const saved = await saveTextFile(content, exportFileName(tableMeta.value?.tableName || "export", "sql", { preferFallback: true }), "SQL", "sql", { exportId, operation: "sql-insert-all" }); + if (!saved) return; logExportStage("done", { contentChars: content.length }); - toast(t("grid.exported")); + notifyExportSuccess(typeof saved === "string" ? saved : undefined); } catch (e: any) { toast(t("grid.exportFailed", { message: translateBackendError(t, e) }), 5000); logExportStage("error", { @@ -1747,8 +1750,9 @@ export function useDataGridExport(options: UseDataGridExportOptions) { insertMode, excludeColumns: sqlExportExcludedColumns(), }); - await saveTextFile(content, exportFileName("export-page", "sql", { page: true }), "SQL", "sql", { autoOpenFolder: true }); - toast(t("grid.exported")); + const saved = await saveTextFile(content, exportFileName("export-page", "sql", { page: true }), "SQL", "sql"); + if (!saved) return; + notifyExportSuccess(typeof saved === "string" ? saved : undefined); } catch (e: any) { toast(t("grid.exportFailed", { message: translateBackendError(t, e) }), 5000); } diff --git a/apps/desktop/src/composables/useSidebarTreeExportRuntime.ts b/apps/desktop/src/composables/useSidebarTreeExportRuntime.ts index 8cd874a2cb..603caa9aa2 100644 --- a/apps/desktop/src/composables/useSidebarTreeExportRuntime.ts +++ b/apps/desktop/src/composables/useSidebarTreeExportRuntime.ts @@ -13,7 +13,8 @@ import { copyToClipboard } from "@/lib/common/clipboard"; import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect"; import { gaussdbMTypeDisplayName } from "@/lib/table/postgresDataTypeHelp"; import { joinExportedDdls } from "@/lib/export/ddlExport"; -import { autoRevealExportedPathIfConfigured, promptExportSavePath } from "@/lib/export/exportPath"; +import { promptExportSavePath } from "@/lib/export/exportPath"; +import { notifyExportComplete } from "@/lib/export/exportReveal"; import { translateBackendError } from "@/i18n/backend-errors"; import { sidebarStructureExportTargets, sidebarTableDataExportTargets } from "@/lib/sidebar/sidebarExportRuntime"; import { fetchTableDataForExport } from "@/lib/table/tableDataExport"; @@ -385,8 +386,14 @@ export function useSidebarTreeExportRuntime(options: SidebarTreeExportRuntimeOpt const outputPath = await resolveTableExportOutputPath(target, "json", outputDirectory); if (!outputPath) return false; await api.exportQueryResultJson(outputPath, result.columns, result.rows); - if (!suppressDoneToast) toast(t("grid.exported")); - void autoRevealExportedPathIfConfigured(outputPath); + if (!suppressDoneToast) { + notifyExportComplete({ + filePath: outputPath, + message: t("grid.exported"), + openFolderLabel: t("exportProgress.openFolder"), + toast, + }); + } return true; } catch (error: any) { toast(t("grid.exportFailed", { message: translateBackendError(t, error) }), 5000); @@ -487,7 +494,14 @@ export function useSidebarTreeExportRuntime(options: SidebarTreeExportRuntimeOpt currentTask.status = "Done"; currentTask.rowsExported = result.rows.length; currentTask.totalRows = result.rows.length; - if (!suppressDoneToast) toast(t("grid.exported")); + if (!suppressDoneToast) { + notifyExportComplete({ + filePath: outputPath, + message: t("grid.exported"), + openFolderLabel: t("exportProgress.openFolder"), + toast, + }); + } return true; } const columnComments = @@ -528,7 +542,14 @@ export function useSidebarTreeExportRuntime(options: SidebarTreeExportRuntimeOpt await api.startTableExport(request, (progress) => { updateTableExportTask(currentTask.exportId, progress); if (progress.status === "Done") { - if (!suppressDoneToast) toast(t("grid.exported")); + if (!suppressDoneToast) { + notifyExportComplete({ + filePath: request.filePath, + message: t("grid.exported"), + openFolderLabel: t("exportProgress.openFolder"), + toast, + }); + } } else if (progress.status === "Error") toast(t("grid.exportFailed", { message: translateBackendError(t, progress.errorMessage || "") }), 5000); }); return true; @@ -584,7 +605,12 @@ export function useSidebarTreeExportRuntime(options: SidebarTreeExportRuntimeOpt } else if (progress.status === "cancelled") currentTask.status = "Cancelled"; }, ); - toast(t("grid.exported")); + notifyExportComplete({ + filePath: outputPath, + message: t("grid.exported"), + openFolderLabel: t("exportProgress.openFolder"), + toast, + }); } catch (error: unknown) { if (task) { task.status = "Error"; diff --git a/apps/desktop/src/lib/export/__tests__/exportReveal.spec.ts b/apps/desktop/src/lib/export/__tests__/exportReveal.spec.ts new file mode 100644 index 0000000000..03d26d1f21 --- /dev/null +++ b/apps/desktop/src/lib/export/__tests__/exportReveal.spec.ts @@ -0,0 +1,193 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { shouldAutoRevealExportedFile, revealExportedFile, notifyExportComplete } from "@/lib/export/exportReveal"; + +const mocks = vi.hoisted(() => ({ + isTauriRuntime: vi.fn(), + revealExportedPath: vi.fn(), + editorSettings: { + autoOpenExportFolder: false, + }, +})); + +vi.mock("@/lib/backend/tauriRuntime", () => ({ + isTauriRuntime: () => mocks.isTauriRuntime(), +})); + +vi.mock("@/lib/export/exportPath", () => ({ + revealExportedPath: (...args: unknown[]) => mocks.revealExportedPath(...args), +})); + +vi.mock("@/stores/settingsStore", () => ({ + useSettingsStore: () => ({ + editorSettings: mocks.editorSettings, + }), +})); + +describe("exportReveal", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.isTauriRuntime.mockReturnValue(true); + mocks.revealExportedPath.mockResolvedValue(undefined); + mocks.editorSettings.autoOpenExportFolder = false; + }); + + describe("shouldAutoRevealExportedFile", () => { + it("returns false when not running under Tauri", () => { + mocks.isTauriRuntime.mockReturnValue(false); + mocks.editorSettings.autoOpenExportFolder = true; + expect(shouldAutoRevealExportedFile()).toBe(false); + }); + + it("returns false when autoOpenExportFolder setting is false", () => { + mocks.isTauriRuntime.mockReturnValue(true); + mocks.editorSettings.autoOpenExportFolder = false; + expect(shouldAutoRevealExportedFile()).toBe(false); + }); + + it("returns true when running under Tauri and autoOpenExportFolder setting is true", () => { + mocks.isTauriRuntime.mockReturnValue(true); + mocks.editorSettings.autoOpenExportFolder = true; + expect(shouldAutoRevealExportedFile()).toBe(true); + }); + }); + + describe("revealExportedFile", () => { + it("returns false when path is empty or whitespace", async () => { + expect(await revealExportedFile("")).toBe(false); + expect(await revealExportedFile(" ")).toBe(false); + expect(mocks.revealExportedPath).not.toHaveBeenCalled(); + }); + + it("returns false when not running under Tauri", async () => { + mocks.isTauriRuntime.mockReturnValue(false); + expect(await revealExportedFile("/tmp/test.csv")).toBe(false); + expect(mocks.revealExportedPath).not.toHaveBeenCalled(); + }); + + it("calls revealExportedPath with trimmed path and returns true", async () => { + mocks.isTauriRuntime.mockReturnValue(true); + const result = await revealExportedFile(" /path/to/exported.xlsx "); + expect(result).toBe(true); + expect(mocks.revealExportedPath).toHaveBeenCalledWith("/path/to/exported.xlsx"); + }); + + it("calls onError callback and returns false when revealExportedPath rejects", async () => { + mocks.isTauriRuntime.mockReturnValue(true); + const err = new Error("File not found"); + mocks.revealExportedPath.mockRejectedValueOnce(err); + const onError = vi.fn(); + + const result = await revealExportedFile("/tmp/file.sql", onError); + expect(result).toBe(false); + expect(onError).toHaveBeenCalledWith(err); + }); + + it("logs warning and returns false when revealExportedPath rejects without onError", async () => { + mocks.isTauriRuntime.mockReturnValue(true); + mocks.revealExportedPath.mockRejectedValueOnce(new Error("Permission denied")); + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); + + const result = await revealExportedFile("/tmp/file.sql"); + expect(result).toBe(false); + expect(warnSpy).toHaveBeenCalledWith("Failed to reveal exported file in file manager:", expect.any(Error)); + warnSpy.mockRestore(); + }); + }); + + describe("notifyExportComplete", () => { + it("shows toast without action when running in web environment", () => { + mocks.isTauriRuntime.mockReturnValue(false); + const toast = vi.fn(); + + notifyExportComplete({ + filePath: "/tmp/exported.csv", + message: "Exported", + openFolderLabel: "Open Folder", + toast, + }); + + expect(toast).toHaveBeenCalledWith("Exported"); + expect(mocks.revealExportedPath).not.toHaveBeenCalled(); + }); + + it("shows toast without action when filePath is omitted or null", () => { + mocks.isTauriRuntime.mockReturnValue(true); + const toast = vi.fn(); + + notifyExportComplete({ + filePath: null, + message: "Exported", + openFolderLabel: "Open Folder", + toast, + }); + + expect(toast).toHaveBeenCalledWith("Exported"); + expect(mocks.revealExportedPath).not.toHaveBeenCalled(); + }); + + it("shows toast with action button in Tauri and does not auto-reveal when setting is off", () => { + mocks.isTauriRuntime.mockReturnValue(true); + mocks.editorSettings.autoOpenExportFolder = false; + const toast = vi.fn(); + + notifyExportComplete({ + filePath: "/path/to/result.csv", + message: "Exported", + openFolderLabel: "Open Containing Folder", + toast, + }); + + expect(mocks.revealExportedPath).not.toHaveBeenCalled(); + expect(toast).toHaveBeenCalledWith( + "Exported", + 4000, + expect.objectContaining({ + label: "Open Containing Folder", + onClick: expect.any(Function), + }), + ); + + // Clicking the action reveals the file + const action = toast.mock.calls[0][2]; + action.onClick(); + expect(mocks.revealExportedPath).toHaveBeenCalledWith("/path/to/result.csv"); + }); + + it("auto-reveals the file when autoOpenExportFolder is enabled", () => { + mocks.isTauriRuntime.mockReturnValue(true); + mocks.editorSettings.autoOpenExportFolder = true; + const toast = vi.fn(); + + notifyExportComplete({ + filePath: "/path/to/result.xlsx", + message: "Exported", + openFolderLabel: "Open Containing Folder", + toast, + }); + + expect(mocks.revealExportedPath).toHaveBeenCalledWith("/path/to/result.xlsx"); + expect(toast).toHaveBeenCalledWith( + "Exported", + 4000, + expect.objectContaining({ + label: "Open Containing Folder", + }), + ); + }); + + it("respects custom duration if provided", () => { + mocks.isTauriRuntime.mockReturnValue(true); + const toast = vi.fn(); + + notifyExportComplete({ + filePath: "/path/to/result.sql", + message: "Exported", + openFolderLabel: "Open Folder", + toast, + duration: 8000, + }); + + expect(toast).toHaveBeenCalledWith("Exported", 8000, expect.any(Object)); + }); + }); +}); diff --git a/apps/desktop/src/lib/export/exportReveal.ts b/apps/desktop/src/lib/export/exportReveal.ts new file mode 100644 index 0000000000..fde42f707f --- /dev/null +++ b/apps/desktop/src/lib/export/exportReveal.ts @@ -0,0 +1,62 @@ +import { isTauriRuntime } from "@/lib/backend/tauriRuntime"; +import { revealExportedPath } from "@/lib/export/exportPath"; +import { useSettingsStore } from "@/stores/settingsStore"; +import type { ToastAction } from "@/composables/useToast"; + +export function shouldAutoRevealExportedFile(): boolean { + if (!isTauriRuntime()) return false; + try { + const settings = useSettingsStore().editorSettings; + return Boolean(settings?.autoOpenExportFolder); + } catch { + return false; + } +} + +export async function revealExportedFile(filePath: string, onError?: (error: unknown) => void): Promise { + const trimmed = filePath?.trim(); + if (!trimmed || !isTauriRuntime()) return false; + try { + await revealExportedPath(trimmed); + return true; + } catch (error) { + if (onError) { + onError(error); + } else { + console.warn("Failed to reveal exported file in file manager:", error); + } + return false; + } +} + +export interface NotifyExportCompleteOptions { + filePath?: string | null; + message: string; + openFolderLabel?: string; + toast: (msg: string, duration?: number, action?: ToastAction) => void; + duration?: number; +} + +export function notifyExportComplete(options: NotifyExportCompleteOptions): void { + const { filePath, message, openFolderLabel, toast } = options; + const trimmed = filePath?.trim(); + const canReveal = Boolean(trimmed && isTauriRuntime()); + + if (canReveal && trimmed && shouldAutoRevealExportedFile()) { + void revealExportedFile(trimmed); + } + + if (canReveal && trimmed && openFolderLabel) { + const action: ToastAction = { + label: openFolderLabel, + onClick: () => { + void revealExportedFile(trimmed); + }, + }; + toast(message, options.duration ?? 4000, action); + } else if (options.duration !== undefined) { + toast(message, options.duration); + } else { + toast(message); + } +} diff --git a/apps/desktop/src/lib/export/saveTextFile.ts b/apps/desktop/src/lib/export/saveTextFile.ts index a8f5b29daa..ddfaf4629c 100644 --- a/apps/desktop/src/lib/export/saveTextFile.ts +++ b/apps/desktop/src/lib/export/saveTextFile.ts @@ -2,7 +2,7 @@ import { isTauriRuntime } from "@/lib/backend/tauriRuntime"; import { appendDebugLog, getBrowserMemorySnapshot, isDebugLoggingEnabled } from "@/lib/backend/debugLog"; import { autoRevealExportedPathIfConfigured, promptExportSavePath } from "./exportPath"; -export async function saveTextFile(content: string, defaultFileName: string, filterName: string, filterExt: string, diagnostics: { exportId?: string; operation?: string; autoOpenFolder?: boolean } = {}): Promise { +export async function saveTextFile(content: string, defaultFileName: string, filterName: string, filterExt: string, diagnostics: { exportId?: string; operation?: string; autoOpenFolder?: boolean } = {}): Promise { const logSaveStage = (stage: string, details: Record = {}) => { if (!isDebugLoggingEnabled()) return; appendDebugLog("info", `[DBX][export:save:${stage}]`, { @@ -28,7 +28,7 @@ export async function saveTextFile(content: string, defaultFileName: string, fil if (path && diagnostics.autoOpenFolder) { void autoRevealExportedPathIfConfigured(path); } - return Boolean(path); + return path || false; } const blob = new Blob([content], { type: "text/plain;charset=utf-8" });