fix(desktop): persist UI state asynchronously
This commit is contained in:
1 parent
693eb0dbb9
commit
6b13564180
14 files changed
+547
-127
No files matched your search
@@ -1,10 +1,16 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createSavedSqlEditorPosition, forgetSavedSqlEditorPosition, restoreSavedSqlEditorPosition, saveSavedSqlEditorPosition, SAVED_SQL_EDITOR_POSITIONS_STORAGE_KEY } from "../app/savedSqlEditorPosition";
|
||||
import { __resetSavedSqlEditorPositionsForTests, createSavedSqlEditorPosition, forgetSavedSqlEditorPosition, restoreSavedSqlEditorPosition, saveSavedSqlEditorPosition } from "../app/savedSqlEditorPosition";
|
||||
|
||||
vi.mock("@/lib/backend/api", () => ({
|
||||
loadSavedSqlEditorPositions: vi.fn().mockResolvedValue(null),
|
||||
saveSavedSqlEditorPositions: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
const storage = new Map<string, string>();
|
||||
|
||||
beforeEach(() => {
|
||||
storage.clear();
|
||||
__resetSavedSqlEditorPositionsForTests();
|
||||
vi.stubGlobal("localStorage", {
|
||||
getItem: (key: string) => storage.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => storage.set(key, value),
|
||||
@@ -100,10 +106,7 @@ describe("savedSqlEditorPosition", () => {
|
||||
);
|
||||
}
|
||||
|
||||
const stored = JSON.parse(storage.get(SAVED_SQL_EDITOR_POSITIONS_STORAGE_KEY) ?? "[]") as Array<{ savedSqlId: string }>;
|
||||
|
||||
expect(stored).toHaveLength(200);
|
||||
expect(stored.some((item) => item.savedSqlId === "file-0")).toBe(false);
|
||||
expect(stored[0]?.savedSqlId).toBe("file-204");
|
||||
expect(restoreSavedSqlEditorPosition("file-0", "select 1;")).toEqual({});
|
||||
expect(restoreSavedSqlEditorPosition("file-204", "select 1;").selection).toEqual({ anchor: 0, head: 0 });
|
||||
});
|
||||
});
|
||||
@@ -132,13 +132,10 @@ function isSavedOpenTab(value: unknown): value is SavedOpenTab {
|
||||
return typeof tab.id === "string" && typeof tab.title === "string" && typeof tab.connectionId === "string" && typeof tab.database === "string" && (typeof tab.sql === "string" || typeof tab.savedSqlId === "string");
|
||||
}
|
||||
|
||||
export function restoreOpenTabsState(rawTabs: string | null, rawActiveTabId: string | null, options: { queryOnly?: boolean; filter?: OpenTabsRestoreFilter } = {}): RestoredOpenTabs {
|
||||
if (!rawTabs) return { tabs: [], activeTabId: null };
|
||||
function restoreOpenTabsArray(parsed: unknown, rawActiveTabId: string | null, options: { queryOnly?: boolean; filter?: OpenTabsRestoreFilter } = {}): RestoredOpenTabs {
|
||||
if (!Array.isArray(parsed)) return { tabs: [], activeTabId: null };
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(rawTabs);
|
||||
if (!Array.isArray(parsed)) return { tabs: [], activeTabId: null };
|
||||
|
||||
const saved = parsed.filter(isSavedOpenTab);
|
||||
const filtered = saved.filter((tab) => {
|
||||
if (options.queryOnly && (tab.mode ?? "query") !== "query") return false;
|
||||
@@ -185,3 +182,18 @@ export function restoreOpenTabsState(rawTabs: string | null, rawActiveTabId: str
|
||||
return { tabs: [], activeTabId: null };
|
||||
}
|
||||
}
|
||||
|
||||
export function restoreOpenTabsPayload(payload: { tabs?: unknown; activeTabId?: unknown } | null | undefined, options: { queryOnly?: boolean; filter?: OpenTabsRestoreFilter } = {}): RestoredOpenTabs {
|
||||
if (!payload) return { tabs: [], activeTabId: null };
|
||||
return restoreOpenTabsArray(payload.tabs, typeof payload.activeTabId === "string" ? payload.activeTabId : null, options);
|
||||
}
|
||||
|
||||
export function restoreOpenTabsState(rawTabs: string | null, rawActiveTabId: string | null, options: { queryOnly?: boolean; filter?: OpenTabsRestoreFilter } = {}): RestoredOpenTabs {
|
||||
if (!rawTabs) return { tabs: [], activeTabId: null };
|
||||
|
||||
try {
|
||||
return restoreOpenTabsArray(JSON.parse(rawTabs), rawActiveTabId, options);
|
||||
} catch {
|
||||
return { tabs: [], activeTabId: null };
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,6 @@
|
||||
import * as api from "@/lib/backend/api";
|
||||
import { safeLocalStorageGet, safeLocalStorageRemove } from "@/lib/backend/safeStorage";
|
||||
|
||||
export const SAVED_SQL_EDITOR_POSITIONS_STORAGE_KEY = "dbx-saved-sql-editor-positions";
|
||||
|
||||
const MAX_SAVED_SQL_EDITOR_POSITIONS = 200;
|
||||
@@ -83,44 +86,82 @@ function restoredHeadFromAnchor(position: SavedSqlEditorPosition, sql: string):
|
||||
return targetHead;
|
||||
}
|
||||
|
||||
function parseSavedPositions(raw: string | null): SavedSqlEditorPosition[] {
|
||||
function normalizeSavedPositions(value: unknown): SavedSqlEditorPosition[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.filter((item): item is SavedSqlEditorPosition => {
|
||||
return (
|
||||
!!item &&
|
||||
typeof item === "object" &&
|
||||
typeof item.savedSqlId === "string" &&
|
||||
!!item.selection &&
|
||||
typeof item.selection.anchor === "number" &&
|
||||
typeof item.selection.head === "number" &&
|
||||
!!item.anchor &&
|
||||
typeof item.anchor.before === "string" &&
|
||||
typeof item.anchor.after === "string" &&
|
||||
typeof item.anchor.head === "number" &&
|
||||
typeof item.anchor.docLength === "number" &&
|
||||
typeof item.updatedAt === "number"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function parseLegacySavedPositions(): SavedSqlEditorPosition[] {
|
||||
const raw = safeLocalStorageGet(SAVED_SQL_EDITOR_POSITIONS_STORAGE_KEY);
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.filter((item): item is SavedSqlEditorPosition => {
|
||||
return (
|
||||
!!item &&
|
||||
typeof item === "object" &&
|
||||
typeof item.savedSqlId === "string" &&
|
||||
!!item.selection &&
|
||||
typeof item.selection.anchor === "number" &&
|
||||
typeof item.selection.head === "number" &&
|
||||
!!item.anchor &&
|
||||
typeof item.anchor.before === "string" &&
|
||||
typeof item.anchor.after === "string" &&
|
||||
typeof item.anchor.head === "number" &&
|
||||
typeof item.anchor.docLength === "number" &&
|
||||
typeof item.updatedAt === "number"
|
||||
);
|
||||
});
|
||||
return normalizeSavedPositions(JSON.parse(raw));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
let savedPositions: SavedSqlEditorPosition[] = [];
|
||||
let savedPositionsLoaded = false;
|
||||
let savedPositionsInitPromise: Promise<void> | undefined;
|
||||
|
||||
export async function initSavedSqlEditorPositions() {
|
||||
if (savedPositionsLoaded) return;
|
||||
if (savedPositionsInitPromise) return savedPositionsInitPromise;
|
||||
|
||||
savedPositionsInitPromise = (async () => {
|
||||
const storedValue = await api.loadSavedSqlEditorPositions().catch(() => null);
|
||||
if (Array.isArray(storedValue)) {
|
||||
savedPositions = normalizeSavedPositions(storedValue);
|
||||
return;
|
||||
}
|
||||
|
||||
const legacy = parseLegacySavedPositions();
|
||||
if (legacy.length > 0) {
|
||||
savedPositions = legacy;
|
||||
try {
|
||||
await api.saveSavedSqlEditorPositions(trimSavedPositions(legacy));
|
||||
// Remove the synchronous startup payload only after the async store
|
||||
// accepts the migrated positions.
|
||||
safeLocalStorageRemove(SAVED_SQL_EDITOR_POSITIONS_STORAGE_KEY);
|
||||
} catch {
|
||||
/* keep legacy values for a later migration attempt */
|
||||
}
|
||||
}
|
||||
})().finally(() => {
|
||||
savedPositionsLoaded = true;
|
||||
savedPositionsInitPromise = undefined;
|
||||
});
|
||||
|
||||
return savedPositionsInitPromise;
|
||||
}
|
||||
|
||||
function readSavedPositions(): SavedSqlEditorPosition[] {
|
||||
try {
|
||||
return parseSavedPositions(localStorage.getItem(SAVED_SQL_EDITOR_POSITIONS_STORAGE_KEY));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return savedPositions;
|
||||
}
|
||||
|
||||
function trimSavedPositions(positions: SavedSqlEditorPosition[]) {
|
||||
return [...positions].sort((a, b) => b.updatedAt - a.updatedAt).slice(0, MAX_SAVED_SQL_EDITOR_POSITIONS);
|
||||
}
|
||||
|
||||
function writeSavedPositions(positions: SavedSqlEditorPosition[]) {
|
||||
try {
|
||||
localStorage.setItem(SAVED_SQL_EDITOR_POSITIONS_STORAGE_KEY, JSON.stringify([...positions].sort((a, b) => b.updatedAt - a.updatedAt).slice(0, MAX_SAVED_SQL_EDITOR_POSITIONS)));
|
||||
} catch {}
|
||||
savedPositions = trimSavedPositions(positions);
|
||||
void api.saveSavedSqlEditorPositions(savedPositions).catch(() => {});
|
||||
}
|
||||
|
||||
export function createSavedSqlEditorPosition(input: { savedSqlId: string; sql: string; selection?: SavedSqlEditorSelection; viewport?: SavedSqlEditorViewport; now?: number }): SavedSqlEditorPosition {
|
||||
@@ -166,3 +207,9 @@ export function restoreSavedSqlEditorPosition(savedSqlId: string, sql: string):
|
||||
export function forgetSavedSqlEditorPosition(savedSqlId: string) {
|
||||
writeSavedPositions(readSavedPositions().filter((item) => item.savedSqlId !== savedSqlId));
|
||||
}
|
||||
|
||||
export function __resetSavedSqlEditorPositionsForTests(positions: SavedSqlEditorPosition[] = []) {
|
||||
savedPositions = trimSavedPositions(positions);
|
||||
savedPositionsLoaded = true;
|
||||
savedPositionsInitPromise = undefined;
|
||||
}
|
||||
@@ -219,6 +219,12 @@ export const setAgentStoreDir = forward("setAgentStoreDir");
|
||||
export const getDriverStorePath = forward("getDriverStorePath");
|
||||
export const loadPinnedTreeNodeIds = forward("loadPinnedTreeNodeIds");
|
||||
export const savePinnedTreeNodeIds = forward("savePinnedTreeNodeIds");
|
||||
export const loadEditorSettings = forward("loadEditorSettings");
|
||||
export const saveEditorSettings = forward("saveEditorSettings");
|
||||
export const loadOpenTabsState = forward("loadOpenTabsState");
|
||||
export const saveOpenTabsState = forward("saveOpenTabsState");
|
||||
export const loadSavedSqlEditorPositions = forward("loadSavedSqlEditorPositions");
|
||||
export const saveSavedSqlEditorPositions = forward("saveSavedSqlEditorPositions");
|
||||
export const webdavSyncTest = forward("webdavSyncTest");
|
||||
export const webdavPasswordStatus = forward("webdavPasswordStatus");
|
||||
export const saveWebdavSavedPassword = forward("saveWebdavSavedPassword");
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";
|
||||
|
||||
const DB_NAME = "dbx-app-state";
|
||||
const DB_VERSION = 1;
|
||||
const STORE_NAME = "state";
|
||||
const LOCAL_STORAGE_PREFIX = "dbx-app-state:";
|
||||
|
||||
function indexedDb(): IDBFactory | undefined {
|
||||
return typeof globalThis.indexedDB === "undefined" ? undefined : globalThis.indexedDB;
|
||||
}
|
||||
|
||||
function requestToPromise<T>(request: IDBRequest<T>): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error ?? new Error("IndexedDB request failed"));
|
||||
});
|
||||
}
|
||||
|
||||
let dbPromise: Promise<IDBDatabase | null> | undefined;
|
||||
|
||||
function openDb(): Promise<IDBDatabase | null> {
|
||||
if (dbPromise) return dbPromise;
|
||||
const idb = indexedDb();
|
||||
if (!idb) return Promise.resolve(null);
|
||||
|
||||
dbPromise = new Promise((resolve) => {
|
||||
const request = idb.open(DB_NAME, DB_VERSION);
|
||||
request.onupgradeneeded = () => {
|
||||
const db = request.result;
|
||||
if (!db.objectStoreNames.contains(STORE_NAME)) db.createObjectStore(STORE_NAME);
|
||||
};
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => resolve(null);
|
||||
request.onblocked = () => resolve(null);
|
||||
});
|
||||
return dbPromise;
|
||||
}
|
||||
|
||||
function fallbackKey(key: string) {
|
||||
return `${LOCAL_STORAGE_PREFIX}${key}`;
|
||||
}
|
||||
|
||||
async function withStore<T>(mode: IDBTransactionMode, run: (store: IDBObjectStore) => IDBRequest<T>): Promise<T | null> {
|
||||
const db = await openDb();
|
||||
if (!db) return null;
|
||||
try {
|
||||
return await requestToPromise(run(db.transaction(STORE_NAME, mode).objectStore(STORE_NAME)));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadBrowserAppState(key: string): Promise<unknown | null> {
|
||||
const value = await withStore("readonly", (store) => store.get(key));
|
||||
if (value !== null && value !== undefined) return value;
|
||||
|
||||
const fallback = safeLocalStorageGet(fallbackKey(key));
|
||||
if (!fallback) return null;
|
||||
try {
|
||||
return JSON.parse(fallback);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveBrowserAppState(key: string, value: unknown): Promise<void> {
|
||||
const result = await withStore("readwrite", (store) => store.put(value, key));
|
||||
if (result !== null) return;
|
||||
safeLocalStorageSet(fallbackKey(key), JSON.stringify(value));
|
||||
}
|
||||
@@ -113,6 +113,7 @@ import type { BuildRenameObjectSqlOptions } from "@/lib/table/objectRenameSql";
|
||||
import type { CreateDatabaseSqlOptions } from "@/lib/database/createDatabaseSql";
|
||||
import type { DatabaseNameSqlOptions, DropTableChildObjectSqlOptions, DropObjectSqlOptions, DuplicateTableStructureSqlOptions, CopyTableDataSqlOptions, SchemaNameSqlOptions, TableAdminSqlOptions } from "@/lib/database/dbAdminSql";
|
||||
import type { BuildDatabaseSqlExportOptions, BuildExportInsertStatementsOptions } from "@/lib/export/databaseExport";
|
||||
import { loadBrowserAppState, saveBrowserAppState } from "@/lib/backend/browserAppStateStorage";
|
||||
import type { DataCompareFromTablesOptions, DataCompareFromTablesPreparation, DataCompareSyncPlan, DataCompareSyncPlanOptions, DataComparePreparation, DataComparePreparationOptions } from "@/lib/dataGrid/dataCompare";
|
||||
import { apiUrl, apiWebSocketUrl } from "@/lib/common/webPath";
|
||||
import type { DataGridSavePreparation } from "@/lib/backend/tauri";
|
||||
@@ -1026,6 +1027,39 @@ export async function saveDesktopSettings(settings: DesktopSettings): Promise<vo
|
||||
safeLocalStorageSet(DESKTOP_SETTINGS_STORAGE_KEY, JSON.stringify({ ...DEFAULT_DESKTOP_SETTINGS, ...settings }));
|
||||
}
|
||||
|
||||
export interface OpenTabsStatePayload {
|
||||
tabs: unknown[];
|
||||
activeTabId: string | null;
|
||||
}
|
||||
|
||||
export async function loadEditorSettings(): Promise<unknown | null> {
|
||||
return loadBrowserAppState("editor_settings");
|
||||
}
|
||||
|
||||
export async function saveEditorSettings(settings: unknown): Promise<void> {
|
||||
await saveBrowserAppState("editor_settings", settings);
|
||||
}
|
||||
|
||||
export async function loadOpenTabsState(): Promise<OpenTabsStatePayload | null> {
|
||||
const value = await loadBrowserAppState("open_tabs");
|
||||
if (!value || typeof value !== "object") return null;
|
||||
const payload = value as Partial<OpenTabsStatePayload>;
|
||||
return Array.isArray(payload.tabs) ? { tabs: payload.tabs, activeTabId: typeof payload.activeTabId === "string" ? payload.activeTabId : null } : null;
|
||||
}
|
||||
|
||||
export async function saveOpenTabsState(payload: OpenTabsStatePayload): Promise<void> {
|
||||
await saveBrowserAppState("open_tabs", payload);
|
||||
}
|
||||
|
||||
export async function loadSavedSqlEditorPositions(): Promise<unknown[] | null> {
|
||||
const value = await loadBrowserAppState("saved_sql_editor_positions");
|
||||
return Array.isArray(value) ? value : null;
|
||||
}
|
||||
|
||||
export async function saveSavedSqlEditorPositions(positions: unknown[]): Promise<void> {
|
||||
await saveBrowserAppState("saved_sql_editor_positions", positions);
|
||||
}
|
||||
|
||||
export async function completeAppClose(_action: "quit" | "hide"): Promise<void> {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -376,6 +376,35 @@ export async function saveDesktopSettings(settings: DesktopSettings): Promise<vo
|
||||
return invoke("save_desktop_settings", { settings });
|
||||
}
|
||||
|
||||
export interface OpenTabsStatePayload {
|
||||
tabs: unknown[];
|
||||
activeTabId: string | null;
|
||||
}
|
||||
|
||||
export async function loadEditorSettings(): Promise<unknown | null> {
|
||||
return invoke("load_editor_settings");
|
||||
}
|
||||
|
||||
export async function saveEditorSettings(settings: unknown): Promise<void> {
|
||||
return invoke("save_editor_settings", { settings });
|
||||
}
|
||||
|
||||
export async function loadOpenTabsState(): Promise<OpenTabsStatePayload | null> {
|
||||
return invoke("load_open_tabs_state");
|
||||
}
|
||||
|
||||
export async function saveOpenTabsState(payload: OpenTabsStatePayload): Promise<void> {
|
||||
return invoke("save_open_tabs_state", { payload });
|
||||
}
|
||||
|
||||
export async function loadSavedSqlEditorPositions(): Promise<unknown[] | null> {
|
||||
return invoke("load_saved_sql_editor_positions");
|
||||
}
|
||||
|
||||
export async function saveSavedSqlEditorPositions(positions: unknown[]): Promise<void> {
|
||||
return invoke("save_saved_sql_editor_positions", { positions });
|
||||
}
|
||||
|
||||
export async function completeAppClose(action: "quit" | "hide"): Promise<void> {
|
||||
return invoke("complete_app_close", { action });
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user