feat(tabs): persist inactive tab UI state

This commit is contained in:
t8y2 committed 2026-09-10 19:45:07 +08:00
1 parent 69098bf0d6
commit 8f3afe0397
39 files changed
+1066 -192

No files matched your search

@@ -21,6 +21,35 @@ function roundTrip(tabs: QueryTab[]) {
}
describe("openTabsPersistence originalSql round-trip", () => {
it("preserves per-tab output view state across a round-trip", () => {
const [restored] = roundTrip([queryTab({ uiState: { activeOutputView: "chart", resultPaneOpen: false } })]);
expect(restored.uiState).toEqual({ activeOutputView: "chart", resultPaneOpen: false });
});
it("preserves namespaced special-page state across a round-trip", () => {
const uiState = {
page: {
etcd: {
EtcdKeyBrowser: { mode: "search", searchQuery: "orders" },
KvKeyBrowser: { selectedKey: "/orders/42", expandedGroupIds: ["group:/orders"] },
},
},
};
const [restored] = roundTrip([queryTab({ mode: "etcd", uiState })]);
expect(restored.uiState).toEqual(uiState);
});
it("drops invalid per-tab output view state while restoring", () => {
const [restored] = restoreOpenTabsPayload({
tabs: [{ id: "t1", title: "query_1", connectionId: "c1", database: "db", mode: "query", sql: "", uiState: { activeOutputView: "invalid", resultPaneOpen: "false" } }],
activeTabId: "t1",
}).tabs;
expect(restored.uiState).toBeUndefined();
});
it("keeps clean saved SQL tabs eligible for file hydration", () => {
const [restored] = roundTrip([queryTab({ savedSqlId: "saved", sql: "SELECT 1", originalSql: "SELECT 1" })]);
expect(restored.sql).toBe("");
+95
View File
@@ -0,0 +1,95 @@
/** @vitest-environment happy-dom */
import { createApp, defineComponent, h, nextTick, ref } from "vue";
import { afterEach, describe, expect, it } from "vitest";
import { MAX_TAB_PAGE_UI_STATE_BYTES, provideTabUiState, sanitizeTabPageUiState, sanitizeTabUiState, useTabUiState } from "@/lib/tabs/tabUiState";
const mounted: Array<{ unmount: () => void; host: HTMLElement }> = [];
afterEach(() => {
for (const { unmount, host } of mounted.splice(0)) {
unmount();
host.remove();
}
});
describe("tabUiState", () => {
it("restores a namespace and flushes its last value before unmount", async () => {
const updates: unknown[] = [];
const trackedValue = ref(0);
let initialValue = 0;
let captureCount = 0;
const Child = defineComponent({
setup() {
const state = useTabUiState<{ value?: number }>({}, "Panel");
initialValue = state.initialState.value ?? 0;
trackedValue.value = initialValue;
state.track(() => ({ value: trackedValue.value }));
return () => h("span", String(trackedValue.value));
},
});
const Parent = defineComponent({
setup() {
provideTabUiState(() => {
captureCount += 1;
return {
snapshot: { Panel: { value: 7 } },
update: (patch) => updates.push(patch),
};
});
return () => h(Child);
},
});
const host = document.createElement("div");
document.body.appendChild(host);
const app = createApp(Parent);
app.mount(host);
mounted.push({ unmount: () => app.unmount(), host });
expect(initialValue).toBe(7);
expect(captureCount).toBe(1);
trackedValue.value = 8;
await nextTick();
expect(updates.at(-1)).toEqual({ Panel: { value: 8 } });
trackedValue.value = 9;
app.unmount();
mounted.length = 0;
host.remove();
expect(updates.at(-1)).toEqual({ Panel: { value: 9 } });
});
it("rejects cyclic, oversized, and non-plain snapshots", () => {
const cyclic: Record<string, unknown> = {};
cyclic.self = cyclic;
expect(sanitizeTabPageUiState(cyclic)).toBeUndefined();
expect(sanitizeTabPageUiState({ value: "x".repeat(MAX_TAB_PAGE_UI_STATE_BYTES + 1) })).toBeUndefined();
expect(sanitizeTabPageUiState({ value: new Date() })).toBeUndefined();
});
it("keeps only supported top-level state and JSON-compatible page values", () => {
const state = sanitizeTabUiState({
activeOutputView: "invalid",
resultPaneOpen: false,
ignored: true,
page: {
query: {
Panel: {
count: 3,
invalidNumber: Number.POSITIVE_INFINITY,
callback: () => undefined,
},
},
},
});
expect(state).toEqual({
resultPaneOpen: false,
page: { query: { Panel: { count: 3 } } },
});
});
});
@@ -1,7 +1,7 @@
import type { QueryTab } from "@/types/database";
import type { QueryTab, TabOutputView } from "@/types/database";
import type { SavedOpenTab } from "@/lib/app/openTabsPersistence";
export type DetachedOutputView = "result" | "summary" | "explain" | "chart" | "messages" | "profile";
export type DetachedOutputView = TabOutputView;
export interface DetachedTabRuntimeState {
editorViewport?: QueryTab["editorViewport"];
@@ -1,4 +1,5 @@
import type { QueryTab } from "@/types/database";
import type { QueryTab, TabOutputView } from "@/types/database";
import { sanitizeTabUiState } from "@/lib/tabs/tabUiState";
export const OPEN_TABS_STORAGE_KEY = "dbx-open-tabs";
export const ACTIVE_TAB_STORAGE_KEY = "dbx-active-tab";
@@ -64,6 +65,7 @@ export interface SavedOpenTab {
resultRuns?: SavedQueryResultRun[];
activeResultRunId?: string;
resultAutoSave?: boolean;
uiState?: QueryTab["uiState"];
}
export interface RestoredOpenTabs {
@@ -129,6 +131,21 @@ function restoredEditorViewport(tab: SavedOpenTab): QueryTab["editorViewport"] {
};
}
const TAB_OUTPUT_VIEWS = new Set<TabOutputView>(["result", "summary", "explain", "chart", "messages", "profile"]);
function restoredTabUiState(tab: SavedOpenTab): QueryTab["uiState"] {
const activeOutputView = tab.uiState?.activeOutputView;
const resultPaneOpen = tab.uiState?.resultPaneOpen;
const restored: NonNullable<QueryTab["uiState"]> = {};
if (activeOutputView && TAB_OUTPUT_VIEWS.has(activeOutputView)) restored.activeOutputView = activeOutputView;
if (typeof resultPaneOpen === "boolean") restored.resultPaneOpen = resultPaneOpen;
if (tab.uiState?.page) {
const sanitized = sanitizeTabUiState({ page: tab.uiState.page });
if (sanitized?.page) restored.page = sanitized.page;
}
return Object.keys(restored).length > 0 ? restored : undefined;
}
export function serializeOpenTabs(tabs: QueryTab[]): SavedOpenTab[] {
return tabs.map((tab) => ({
id: tab.id,
@@ -195,6 +212,7 @@ export function serializeOpenTabs(tabs: QueryTab[]): SavedOpenTab[] {
: {}),
...(tab.mode === "query" && tab.activeResultRunId !== undefined ? { activeResultRunId: tab.activeResultRunId } : {}),
...(tab.mode === "query" && typeof tab.resultAutoSave === "boolean" ? { resultAutoSave: tab.resultAutoSave } : {}),
...(tab.uiState ? { uiState: sanitizeTabUiState(tab.uiState) } : {}),
}));
}
@@ -247,6 +265,7 @@ function restoreOpenTabsArray(parsed: unknown, rawActiveTabId: string | null, op
resultRuns,
activeResultRunId: resultRuns?.some((run) => run.id === tab.activeResultRunId) ? tab.activeResultRunId : resultRuns?.[0]?.id,
resultAutoSave: mode === "query" && typeof tab.resultAutoSave === "boolean" ? tab.resultAutoSave : undefined,
uiState: restoredTabUiState(tab),
};
});
const activeTabId = rawActiveTabId || null;
+101
View File
@@ -0,0 +1,101 @@
import { inject, onBeforeUnmount, provide, watch, type InjectionKey } from "vue";
import type { TabPageUiState, TabUiState } from "@/types/database";
export const MAX_TAB_PAGE_UI_STATE_BYTES = 64 * 1024;
interface TabUiStateContext {
snapshot: TabPageUiState;
update: (patch: TabPageUiState) => void;
}
const TAB_UI_STATE_KEY: InjectionKey<() => TabUiStateContext> = Symbol("dbx-tab-ui-state");
export function provideTabUiState(capture: () => TabUiStateContext): void {
provide(TAB_UI_STATE_KEY, capture);
}
export function useTabUiState<T extends object>(
defaults: T,
namespace?: string,
): {
initialState: T;
update: (patch: Partial<T>) => void;
track: (snapshot: () => Partial<T>) => void;
} {
const context = inject(TAB_UI_STATE_KEY, undefined)?.();
const initialState = { ...defaults, ...sanitizeTabPageUiState(namespace ? context?.snapshot[namespace] : context?.snapshot) } as T;
let active = true;
const update = (patch: Partial<T>) => {
if (active) context?.update(namespace ? { [namespace]: patch } : (patch as TabPageUiState));
};
const track = (snapshot: () => Partial<T>) => {
const stop = watch(snapshot, update, { deep: true, flush: "post" });
onBeforeUnmount(() => {
update(snapshot());
stop();
active = false;
});
};
return { initialState, update, track };
}
export function sanitizeTabPageUiState(value: unknown): TabPageUiState | undefined {
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
try {
const normalized = sanitizeValue(value, 0, new Set(), { remaining: MAX_TAB_PAGE_UI_STATE_BYTES }) as TabPageUiState | undefined;
if (!normalized || !Object.keys(normalized).length) return undefined;
if (new TextEncoder().encode(JSON.stringify(normalized)).byteLength > MAX_TAB_PAGE_UI_STATE_BYTES) return undefined;
return normalized;
} catch {
return undefined;
}
}
function sanitizeValue(value: unknown, depth: number, ancestors: Set<object>, budget: { remaining: number }): unknown {
if (depth > 10) throw new Error("UI state nesting limit");
budget.remaining -= typeof value === "string" ? new TextEncoder().encode(value).byteLength : 8;
if (budget.remaining < 0) throw new Error("UI state size limit");
if (value === null || typeof value === "boolean" || typeof value === "string") return value;
if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
if (typeof value !== "object") return undefined;
if (ancestors.has(value)) throw new Error("Cyclic UI state");
const prototype = Object.getPrototypeOf(value);
if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) return undefined;
ancestors.add(value);
try {
if (Array.isArray(value)) {
if (value.length > 512) throw new Error("UI state array limit");
return value.map((entry) => sanitizeValue(entry, depth + 1, ancestors, budget)).filter((entry) => entry !== undefined);
}
const result: Record<string, unknown> = {};
const entries = Object.entries(value as Record<string, unknown>);
if (entries.length > 128) throw new Error("UI state key limit");
for (const [key, entry] of entries) {
if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
budget.remaining -= new TextEncoder().encode(key).byteLength;
const sanitized = sanitizeValue(entry, depth + 1, ancestors, budget);
if (sanitized !== undefined) result[key] = sanitized;
}
return result;
} finally {
ancestors.delete(value);
}
}
export function sanitizeTabUiState(value: unknown): TabUiState | undefined {
if (!value || typeof value !== "object") return undefined;
const state = value as TabUiState;
const normalized: TabUiState = {};
if (state.activeOutputView && ["result", "summary", "explain", "chart", "messages", "profile"].includes(state.activeOutputView)) normalized.activeOutputView = state.activeOutputView;
if (typeof state.resultPaneOpen === "boolean") normalized.resultPaneOpen = state.resultPaneOpen;
const sanitizedPage = sanitizeTabPageUiState(state.page);
if (sanitizedPage) {
const page: Record<string, TabPageUiState> = {};
for (const [mode, snapshot] of Object.entries(sanitizedPage)) {
const sanitized = sanitizeTabPageUiState(snapshot);
if (sanitized) page[mode] = sanitized;
}
if (Object.keys(page).length) normalized.page = page;
}
return Object.keys(normalized).length ? normalized : undefined;
}