fix(grid): preserve data tab scroll and search across switches

This commit is contained in:
onenewcode authored and GitHub committed 2026-09-09 12:01:49 +08:00
1 parent ed29ef9eed
commit 451e50b2fb
11 files changed
+652 -15

No files matched your search

@@ -38,7 +38,7 @@ vi.mock("@/stores/productionSafetyStore", () => ({
useProductionSafetyStore: () => ({}),
}));
function createEditor(
function createEditorWithResult(
sourceColumns?: Array<string | undefined>,
confirmDangerousRowDeletion = true,
cacheKey?: string,
@@ -125,7 +125,33 @@ function createEditor(
});
editor.newRows.value = [[null, null, null]];
return editor;
return { editor, result };
}
function createEditor(...args: Parameters<typeof createEditorWithResult>) {
return createEditorWithResult(...args).editor;
}
function beforeTabSwitchEvent(fromTabId: string, tabId = "next-tab") {
return new CustomEvent("dbx:before-tab-switch", { detail: { tabId, fromTabId } });
}
function setupTabSwitchScrollFixture() {
class TestScroller {
scrollTop = 0;
scrollLeft = 0;
scrollTo({ top, left }: ScrollToOptions) {
if (typeof top === "number") this.scrollTop = top;
if (typeof left === "number") this.scrollLeft = left;
}
}
vi.stubGlobal("HTMLElement", TestScroller);
const rows: CellValue[][] = [
["a", null, 1],
["b", null, 2],
["c", null, 3],
];
return { TestScroller, rows };
}
describe("useDataGridEditor result snapshots", () => {
@@ -200,6 +226,112 @@ describe("useDataGridEditor result snapshots", () => {
expect(remountedScroller.scrollLeft).toBe(0);
});
it("adopts a scroll-only snapshot when the previous instance was torn down by a tab switch (#8524)", () => {
const { TestScroller, rows } = setupTabSwitchScrollFixture();
const key = "table-tab-8524";
const previous = createEditor(undefined, true, key, undefined, rows);
previous.newRows.value = [];
const previousScroller = new TestScroller();
previousScroller.scrollTop = 6_400;
previousScroller.scrollLeft = 24;
previous.scrollerRef.value = previousScroller as unknown as NonNullable<typeof previous.scrollerRef.value>;
previous.onBeforeTabSwitch(beforeTabSwitchEvent(key));
// Unmount path runs right after the switch and must not clobber the provenance.
previous.savePendingSnapshot(true, true);
const remounted = createEditor(undefined, true, key, undefined, rows);
const remountedScroller = new TestScroller();
remounted.scrollerRef.value = remountedScroller as unknown as NonNullable<typeof remounted.scrollerRef.value>;
remounted.restorePendingSnapshotFocus();
expect(remountedScroller.scrollTop).toBe(6_400);
expect(remountedScroller.scrollLeft).toBe(24);
});
it("ignores a tab switch that names a different tab", () => {
const { TestScroller, rows } = setupTabSwitchScrollFixture();
const key = "table-tab-other-group";
const previous = createEditor(undefined, true, key, undefined, rows);
previous.newRows.value = [];
const previousScroller = new TestScroller();
previousScroller.scrollTop = 6_400;
previousScroller.scrollLeft = 24;
previous.scrollerRef.value = previousScroller as unknown as NonNullable<typeof previous.scrollerRef.value>;
// Split groups keep several grids mounted; this one did not change tabs.
previous.onBeforeTabSwitch(beforeTabSwitchEvent("some-other-tab"));
previous.savePendingSnapshot(true, true);
const remounted = createEditor(undefined, true, key, undefined, rows);
const remountedScroller = new TestScroller();
remounted.scrollerRef.value = remountedScroller as unknown as NonNullable<typeof remounted.scrollerRef.value>;
remounted.restorePendingSnapshotFocus();
expect(remountedScroller.scrollTop).toBe(0);
expect(remountedScroller.scrollLeft).toBe(0);
});
it("ignores a tab switch event without a fromTabId", () => {
const { TestScroller, rows } = setupTabSwitchScrollFixture();
const key = "table-tab-no-origin";
const previous = createEditor(undefined, true, key, undefined, rows);
previous.newRows.value = [];
const previousScroller = new TestScroller();
previousScroller.scrollTop = 6_400;
previousScroller.scrollLeft = 24;
previous.scrollerRef.value = previousScroller as unknown as NonNullable<typeof previous.scrollerRef.value>;
previous.onBeforeTabSwitch(new CustomEvent("dbx:before-tab-switch", { detail: { tabId: "next-tab" } }));
previous.savePendingSnapshot(true, true);
const remounted = createEditor(undefined, true, key, undefined, rows);
const remountedScroller = new TestScroller();
remounted.scrollerRef.value = remountedScroller as unknown as NonNullable<typeof remounted.scrollerRef.value>;
remounted.restorePendingSnapshotFocus();
expect(remountedScroller.scrollTop).toBe(0);
});
it("drops the tab-switch scroll once the result identity changes", async () => {
const { TestScroller, rows } = setupTabSwitchScrollFixture();
const key = "table-tab-reloaded";
const { editor: previous, result } = createEditorWithResult(undefined, true, key, undefined, rows);
previous.newRows.value = [];
const previousScroller = new TestScroller();
previousScroller.scrollTop = 6_400;
previousScroller.scrollLeft = 24;
previous.scrollerRef.value = previousScroller as unknown as NonNullable<typeof previous.scrollerRef.value>;
previous.onBeforeTabSwitch(beforeTabSwitchEvent(key));
previous.savePendingSnapshot(true, true);
// A reload lands a new row array: the grid must start at the first row (#7341).
result.value = { columns: ["first", "hidden", "last"], rows: rows.map((row) => [...row]) };
await nextTick();
previous.savePendingSnapshot(true, true);
const remounted = createEditor(undefined, true, key, undefined, rows);
const remountedScroller = new TestScroller();
remounted.scrollerRef.value = remountedScroller as unknown as NonNullable<typeof remounted.scrollerRef.value>;
remounted.restorePendingSnapshotFocus();
expect(remountedScroller.scrollTop).toBe(0);
});
it("clears the tab-switch provenance when the grid is explicitly scrolled to the top", () => {
const { TestScroller, rows } = setupTabSwitchScrollFixture();
const key = "table-tab-reset-scroll";
const previous = createEditor(undefined, true, key, undefined, rows);
previous.newRows.value = [];
const previousScroller = new TestScroller();
previousScroller.scrollTop = 6_400;
previousScroller.scrollLeft = 24;
previous.scrollerRef.value = previousScroller as unknown as NonNullable<typeof previous.scrollerRef.value>;
previous.onBeforeTabSwitch(beforeTabSwitchEvent(key));
// Sort/filter/paginate/refresh all route through here and mean "new viewport".
previous.resetGridVerticalScroll(true);
previous.savePendingSnapshot(true, true);
const remounted = createEditor(undefined, true, key, undefined, rows);
const remountedScroller = new TestScroller();
remounted.scrollerRef.value = remountedScroller as unknown as NonNullable<typeof remounted.scrollerRef.value>;
remounted.restorePendingSnapshotFocus();
expect(remountedScroller.scrollTop).toBe(0);
});
it("still adopts the cached scroll when the snapshot carries pending edits", () => {
class TestScroller {
scrollTop = 0;
@@ -1,6 +1,7 @@
import { nextTick, ref } from "vue";
import { afterEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useDataGridSearch } from "@/composables/useDataGridSearch";
import { clearDataGridSearchStates, createDataGridSearchScopeKey, loadDataGridSearchState, saveDataGridSearchState } from "@/lib/dataGrid/dataGridSearchStatePersistence";
afterEach(() => {
vi.useRealTimers();
@@ -123,3 +124,133 @@ describe("useDataGridSearch", () => {
expect(search.currentMatchIndex.value).toBe(-1);
});
});
describe("useDataGridSearch persistence (#8524)", () => {
const COLUMNS = ["left", "right"];
const SCOPE = createDataGridSearchScopeKey(COLUMNS);
const ROWS = [
["hit", "hit"],
["none", "hit"],
];
function createSearch({ onNavigate = vi.fn(), persistenceKey = "tab-1" as string | undefined } = {}) {
const search = useDataGridSearch({
columns: COLUMNS,
rows: ROWS,
getCellSearchText: (row: string[], column: number) => row[column],
onNavigate,
persistenceKey,
persistenceScopeKey: () => SCOPE,
});
return { search, onNavigate };
}
beforeEach(() => clearDataGridSearchStates());
it("persists the query, overlay and match index as the user searches", async () => {
vi.useFakeTimers();
const { search } = createSearch();
search.overlayVisible.value = true;
search.searchText.value = "hit";
await flushSearchDebounce();
search.navigateMatch(1);
await nextTick();
const saved = loadDataGridSearchState("tab-1", SCOPE);
expect(saved).toMatchObject({ searchText: "hit", deferredSearchText: "hit", overlayVisible: true, currentMatchIndex: 1 });
});
it("restores text, overlay and match index without auto-navigating or debouncing", async () => {
const { search, onNavigate } = createSearch();
saveDataGridSearchState("tab-1", { scopeKey: SCOPE, searchText: "hit", deferredSearchText: "hit", overlayVisible: true, currentMatchIndex: 2 });
expect(search.restorePersistedState()).toBe(true);
// No advanceTimersByTime: the restore bypasses the debounce entirely.
await nextTick();
await nextTick();
expect(search.overlayVisible.value).toBe(true);
expect(search.deferredSearchText.value).toBe("hit");
expect(search.matchCount.value).toBe(3);
expect(search.currentMatchIndex.value).toBe(2);
// The grid's own scroll restore owns the viewport when returning to a tab.
expect(onNavigate).not.toHaveBeenCalled();
});
it("clamps a stale restored match index", async () => {
const { search } = createSearch();
saveDataGridSearchState("tab-1", { scopeKey: SCOPE, searchText: "none", deferredSearchText: "none", overlayVisible: true, currentMatchIndex: 9 });
search.restorePersistedState();
await nextTick();
await nextTick();
expect(search.matchCount.value).toBe(1);
expect(search.currentMatchIndex.value).toBe(0);
});
it("does not reopen the suggestion popup on restore", async () => {
const { search } = createSearch();
saveDataGridSearchState("tab-1", { scopeKey: SCOPE, searchText: "le", deferredSearchText: "le", overlayVisible: true, currentMatchIndex: 0 });
search.restorePersistedState();
await nextTick();
// "le" prefixes the "left" column, so the non-restore path would suggest it.
expect(search.suggestions.value).toEqual([]);
expect(search.suggestionIndex.value).toBe(-1);
});
it("does not restore across a column signature change", () => {
const { search } = createSearch();
saveDataGridSearchState("tab-1", { scopeKey: createDataGridSearchScopeKey(["renamed"]), searchText: "hit", deferredSearchText: "hit", overlayVisible: true, currentMatchIndex: 0 });
expect(search.restorePersistedState()).toBe(false);
expect(search.searchText.value).toBe("");
});
it("lets a keystroke during the restore window cancel the token", async () => {
vi.useFakeTimers();
const { search, onNavigate } = createSearch();
saveDataGridSearchState("tab-1", { scopeKey: SCOPE, searchText: "hit", deferredSearchText: "hit", overlayVisible: true, currentMatchIndex: 2 });
search.restorePersistedState();
search.searchText.value = "none";
await flushSearchDebounce();
// Normal typing behaviour resumes: debounced, auto-navigated, index reset.
expect(search.deferredSearchText.value).toBe("none");
expect(search.currentMatchIndex.value).toBe(0);
expect(onNavigate).toHaveBeenCalled();
});
it("clears the persisted entry when the search bar is closed", async () => {
vi.useFakeTimers();
const { search } = createSearch();
search.overlayVisible.value = true;
search.searchText.value = "hit";
await flushSearchDebounce();
expect(loadDataGridSearchState("tab-1", SCOPE)).toBeDefined();
search.close();
await nextTick();
expect(loadDataGridSearchState("tab-1", SCOPE)).toBeUndefined();
});
it("opts out entirely when the host passes no persistence key", async () => {
vi.useFakeTimers();
// Built without the helper: an explicit `undefined` argument would hit its
// default and silently re-enable persistence.
const search = useDataGridSearch({
columns: COLUMNS,
rows: ROWS,
getCellSearchText: (row: string[], column: number) => row[column],
});
search.overlayVisible.value = true;
search.searchText.value = "hit";
await flushSearchDebounce();
expect(search.restorePersistedState()).toBe(false);
expect(loadDataGridSearchState("tab-1", SCOPE)).toBeUndefined();
});
});