fix(mongodb): preserve local column filters across tab switches
This commit is contained in:
6 files changed
+137
-14
No files matched your search
@@ -89,6 +89,7 @@ import { mongoDocumentsToQueryResult } from "@/lib/mongo/mongoShellCommand";
|
||||
import type { GridNewRowMeta } from "@/lib/dataGrid/gridNewRowPlacement";
|
||||
import { normalizeResultPageSize } from "@/lib/dataGrid/paginationPageSize";
|
||||
import { documentDataGridColumnLayoutScopeKey } from "@/lib/dataGrid/dataGridColumnLayoutStorage";
|
||||
import type { SerializedDataGridLocalColumnFilters } from "@/lib/dataGrid/dataGridLocalColumnFilterState";
|
||||
import { documentGridColumnVisibilityScopeKey, migrateDocumentGridColumnVisibilityToLayout } from "@/lib/document/documentGridColumnVisibilityStorage";
|
||||
import { matchesElasticsearchIndexPattern, subscribeElasticsearchIndexCleared, type ElasticsearchIndexClearedDetail } from "@/lib/sidebar/elasticsearchIndexActions";
|
||||
import { TABLE_FONT_SIZE_MAX, TABLE_FONT_SIZE_MIN, useSettingsStore } from "@/stores/settingsStore";
|
||||
@@ -176,6 +177,8 @@ const viewMode = computed<ViewMode>({
|
||||
});
|
||||
const filterInput = ref(restoredDocumentBrowserState?.filterInput ?? "");
|
||||
const sortInput = ref(restoredDocumentBrowserState?.sortInput ?? "");
|
||||
const localColumnFilters = ref<SerializedDataGridLocalColumnFilters>(restoredDocumentBrowserState?.localColumnFilters ?? {});
|
||||
const localColumnFilterColumns = ref<string[] | undefined>(restoredDocumentBrowserState?.localColumnFilterColumns);
|
||||
const filterInputRef = ref<HTMLTextAreaElement>();
|
||||
const sortInputRef = ref<HTMLTextAreaElement>();
|
||||
const dataGridRef = ref<InstanceType<typeof DataGrid>>();
|
||||
@@ -319,6 +322,8 @@ function documentDataSignature(): string | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
const documentLocalColumnFilterRestoreKey = computed(() => documentDataSignature());
|
||||
|
||||
let loadedDocumentDataSignature: string | undefined;
|
||||
|
||||
function captureDocumentBrowserData(): DocumentBrowserDataSnapshot | undefined {
|
||||
@@ -353,13 +358,37 @@ function persistDocumentBrowserState(options: { includeData?: boolean } = {}) {
|
||||
appliedDocumentFilter: appliedDocumentFilter.value,
|
||||
documentFilterRules: documentFilterRules.value,
|
||||
page: page.value,
|
||||
localColumnFilters: localColumnFilters.value,
|
||||
localColumnFilterColumns: localColumnFilterColumns.value,
|
||||
// Any condition change drops the payload; only the unmount capture stores
|
||||
// rows, so a cached page can never outlive the conditions that produced it.
|
||||
data: options.includeData ? captureDocumentBrowserData() : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
watch([filterInput, sortInput, appliedDocumentFilter, documentFilterRules, page], () => persistDocumentBrowserState(), { deep: true });
|
||||
function handleLocalColumnFiltersChange(filters: SerializedDataGridLocalColumnFilters) {
|
||||
localColumnFilters.value = Object.fromEntries(Object.entries(filters).map(([columnIndex, values]) => [columnIndex, [...values]]));
|
||||
localColumnFilterColumns.value = Object.keys(filters).length > 0 ? [...gridResult.value.columns] : undefined;
|
||||
// Local value filters only change the client-side view. Keep the loaded rows
|
||||
// in the tab snapshot so returning to the tab does not trigger a reload.
|
||||
persistDocumentBrowserState({ includeData: true });
|
||||
}
|
||||
|
||||
// Keep these sources in lockstep with documentDataSignature(): every input that
|
||||
// invalidates held rows (including pageSize and the infinite-scroll setting, which
|
||||
// can change mid-session at page 0 without moving `page`) must also drop the
|
||||
// local-filter snapshot, or a tab switch would replay filters the user watched
|
||||
// DataGrid clear on its own restore-key change.
|
||||
watch(
|
||||
[filterInput, sortInput, appliedDocumentFilter, page, pageSize, () => settingsStore.editorSettings.infiniteScroll],
|
||||
() => {
|
||||
localColumnFilters.value = {};
|
||||
localColumnFilterColumns.value = undefined;
|
||||
persistDocumentBrowserState();
|
||||
},
|
||||
{ deep: true },
|
||||
);
|
||||
watch(documentFilterRules, () => persistDocumentBrowserState(), { deep: true });
|
||||
|
||||
// Seed the grid from the cached page so a tab switch costs no round trip
|
||||
// (#8679). The signature guard rejects a snapshot whose identity or conditions
|
||||
@@ -558,6 +587,7 @@ const gridResult = computed<QueryResult>(() => {
|
||||
affected_rows: 0,
|
||||
execution_time_ms: 0,
|
||||
truncated: false,
|
||||
local_column_filters: localColumnFilters.value,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -571,6 +601,7 @@ const gridResult = computed<QueryResult>(() => {
|
||||
execution_time_ms: 0,
|
||||
truncated: false,
|
||||
appended_from_row_count: appendedFromRowCount.value,
|
||||
local_column_filters: localColumnFilters.value,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -2518,6 +2549,8 @@ defineExpose({ focusSearch });
|
||||
:column-layout-scope-key="documentColumnLayoutScopeKey"
|
||||
:view-state-key="props.stateKey"
|
||||
:view-generation="documentViewGeneration"
|
||||
:local-column-filter-restore-key="documentLocalColumnFilterRestoreKey"
|
||||
:local-column-filter-columns="localColumnFilterColumns"
|
||||
context="results"
|
||||
page-size-preference="table-open"
|
||||
:database-type="props.databaseType"
|
||||
@@ -2538,6 +2571,7 @@ defineExpose({ focusSearch });
|
||||
@sort="onSort"
|
||||
@reload="refreshDocuments"
|
||||
@paginate="(offset: number, limit: number) => paginate(offset, limit)"
|
||||
@local-column-filters-change="handleLocalColumnFiltersChange"
|
||||
>
|
||||
<template #search-bar="{ localFilterCount, hasLocalColumnFilters, localFilterSummaries, clearLocalFilter }: { localFilterCount: number; hasLocalColumnFilters: boolean; localFilterSummaries: LocalFilterSummary[]; clearLocalFilter: (columnIndex?: number) => void }">
|
||||
<div ref="tableSearchSplitContainerRef" class="flex flex-1 min-w-0">
|
||||
|
||||
+66
@@ -21,6 +21,9 @@ const dataGrid = vi.hoisted(() => ({
|
||||
pageOffset: undefined as number | undefined,
|
||||
rowCount: undefined as number | undefined,
|
||||
columnCount: undefined as number | undefined,
|
||||
localColumnFilters: undefined as Record<string, string[]> | undefined,
|
||||
localColumnFilterColumns: undefined as string[] | undefined,
|
||||
localFiltersChange: undefined as ((filters: Record<string, string[]>) => void) | undefined,
|
||||
viewStateKey: undefined as string | undefined,
|
||||
viewGeneration: undefined as string | undefined,
|
||||
}));
|
||||
@@ -83,11 +86,13 @@ vi.mock("@/components/grid/DataGrid.vue", () => {
|
||||
pageSizePreference: { type: String, required: false },
|
||||
viewStateKey: { type: String, required: false },
|
||||
viewGeneration: { type: String, required: false },
|
||||
localColumnFilterColumns: { type: Array, required: false },
|
||||
},
|
||||
setup(props, { attrs, expose, slots }) {
|
||||
dataGrid.paginate = attrs.onPaginate as typeof dataGrid.paginate;
|
||||
dataGrid.sort = attrs.onSort as typeof dataGrid.sort;
|
||||
dataGrid.reload = attrs.onReload as typeof dataGrid.reload;
|
||||
dataGrid.localFiltersChange = attrs.onLocalColumnFiltersChange as typeof dataGrid.localFiltersChange;
|
||||
expose({
|
||||
visibleColumnCount: 2,
|
||||
displayableColumnCount: 2,
|
||||
@@ -114,6 +119,8 @@ vi.mock("@/components/grid/DataGrid.vue", () => {
|
||||
dataGrid.viewGeneration = props.viewGeneration;
|
||||
dataGrid.rowCount = (props.result as { rows: unknown[] }).rows.length;
|
||||
dataGrid.columnCount = (props.result as { columns: unknown[] }).columns.length;
|
||||
dataGrid.localColumnFilters = (props.result as { local_column_filters?: Record<string, string[]> }).local_column_filters;
|
||||
dataGrid.localColumnFilterColumns = props.localColumnFilterColumns as string[] | undefined;
|
||||
return h("div", [
|
||||
// Rendering the real search-bar slot exposes the filter/sort inputs
|
||||
// the same way the actual grid toolbar does.
|
||||
@@ -231,6 +238,9 @@ beforeEach(async () => {
|
||||
dataGrid.pageOffset = undefined;
|
||||
dataGrid.rowCount = undefined;
|
||||
dataGrid.columnCount = undefined;
|
||||
dataGrid.localColumnFilters = undefined;
|
||||
dataGrid.localColumnFilterColumns = undefined;
|
||||
dataGrid.localFiltersChange = undefined;
|
||||
dataGrid.viewStateKey = undefined;
|
||||
dataGrid.viewGeneration = undefined;
|
||||
settings.editorSettings.infiniteScroll = false;
|
||||
@@ -354,6 +364,62 @@ describe("DocumentBrowser tab state (tab switch persistence)", () => {
|
||||
expect(dataGrid.rowCount).toBe(2);
|
||||
});
|
||||
|
||||
it("restores mongodb local column filters after a tab switch", async () => {
|
||||
await mountBrowser({ stateKey: "tab-local-filters" });
|
||||
expect(backend.documentFindDocuments).toHaveBeenCalledTimes(1);
|
||||
|
||||
dataGrid.localFiltersChange!({ "1": ["str:OpenGate"] });
|
||||
await flushUi();
|
||||
expect(dataGrid.localColumnFilters).toEqual({ "1": ["str:OpenGate"] });
|
||||
expect(dataGrid.localColumnFilterColumns).toEqual(["_id", "name"]);
|
||||
|
||||
app!.unmount();
|
||||
app = null;
|
||||
root!.replaceChildren();
|
||||
await flushUi();
|
||||
await mountBrowser({ stateKey: "tab-local-filters" });
|
||||
|
||||
expect(backend.documentFindDocuments).toHaveBeenCalledTimes(1);
|
||||
expect(dataGrid.localColumnFilters).toEqual({ "1": ["str:OpenGate"] });
|
||||
expect(dataGrid.localColumnFilterColumns).toEqual(["_id", "name"]);
|
||||
});
|
||||
|
||||
it("clears mongodb local column filters when the query conditions change", async () => {
|
||||
await mountBrowser({ stateKey: "tab-local-filters-query-change" });
|
||||
dataGrid.localFiltersChange!({ "1": ["str:OpenGate"] });
|
||||
await flushUi();
|
||||
|
||||
const [filterTextarea] = queryTextareas();
|
||||
typeInTextarea(filterTextarea, '{"name":"row_1"}');
|
||||
await flushUi();
|
||||
pressEnter(filterTextarea);
|
||||
await flushUi();
|
||||
|
||||
expect(dataGrid.localColumnFilters).toEqual({});
|
||||
expect(dataGrid.localColumnFilterColumns).toBeUndefined();
|
||||
});
|
||||
|
||||
it("clears mongodb local column filters when the page size changes mid-session", async () => {
|
||||
await mountBrowser({ stateKey: "tab-local-filters-page-size" });
|
||||
dataGrid.localFiltersChange!({ "1": ["str:OpenGate"] });
|
||||
await flushUi();
|
||||
expect(dataGrid.localColumnFilters).toEqual({ "1": ["str:OpenGate"] });
|
||||
|
||||
// Page stays at 0 for a page-size change, so only the pageSize input invalidates the snapshot.
|
||||
await dataGrid.paginate!(0, 10);
|
||||
await flushUi();
|
||||
expect(dataGrid.localColumnFilters).toEqual({});
|
||||
|
||||
app!.unmount();
|
||||
app = null;
|
||||
root!.replaceChildren();
|
||||
await flushUi();
|
||||
await mountBrowser({ stateKey: "tab-local-filters-page-size" });
|
||||
|
||||
expect(dataGrid.localColumnFilters).toEqual({});
|
||||
expect(dataGrid.localColumnFilterColumns).toBeUndefined();
|
||||
});
|
||||
|
||||
it("still forces a real reload from the refresh button after a restore", async () => {
|
||||
await mountBrowser({ stateKey: "tab-refresh" });
|
||||
app!.unmount();
|
||||
|
||||
@@ -503,6 +503,10 @@ interface DataGridProps {
|
||||
* adopts a stale viewport or selection (#7341).
|
||||
*/
|
||||
viewGeneration?: string;
|
||||
/** Stable logical query identity used to gate local-filter restoration. */
|
||||
localColumnFilterRestoreKey?: string;
|
||||
/** Column names captured with a document-store local-filter snapshot. */
|
||||
localColumnFilterColumns?: string[];
|
||||
exportSql?: string;
|
||||
onExecuteSql?: (sql: string) => Promise<void>;
|
||||
fullExportResult?: (onProgress?: (info: { rowsExported: number; totalRows: number | null }) => void) => Promise<QueryResult | undefined>;
|
||||
@@ -1075,7 +1079,7 @@ type FilterMode = DataGridContextFilterMode;
|
||||
|
||||
type StructuredFilterRule = DataGridStructuredFilterRule;
|
||||
|
||||
const localColumnFilters = ref<Record<number, Set<string>>>(restoreDataGridLocalColumnFilters(props.result.local_column_filters, props.result.columns.length));
|
||||
const localColumnFilters = ref<Record<number, Set<string>>>(restoreDataGridLocalColumnFilters(props.result.local_column_filters, props.result.columns.length, props.result.columns, props.localColumnFilterColumns));
|
||||
const localFilterOpenColumn = ref<number | null>(null);
|
||||
const headerActionMenuOpenColumn = ref<number | null>(null);
|
||||
const headerSortMenuOpenColumn = ref<number | null>(null);
|
||||
@@ -2859,14 +2863,13 @@ const localFilterScopeKey = computed(() =>
|
||||
(props.sourceColumns ?? []).map((column) => column ?? "").join("\0"),
|
||||
].join("\u0001"),
|
||||
);
|
||||
watch(
|
||||
() => localFilterScopeKey.value,
|
||||
() => {
|
||||
localColumnFilters.value = {};
|
||||
resetColumnVisibility();
|
||||
closeLocalFilter();
|
||||
},
|
||||
);
|
||||
const localFilterRestoreKey = computed(() => props.localColumnFilterRestoreKey);
|
||||
watch([localFilterScopeKey, localFilterRestoreKey], ([, restoreKey], [, previousRestoreKey]) => {
|
||||
const canRestoreForSameQuery = restoreKey !== undefined && restoreKey === previousRestoreKey;
|
||||
localColumnFilters.value = canRestoreForSameQuery ? restoreDataGridLocalColumnFilters(props.result.local_column_filters, props.result.columns.length, props.result.columns, props.localColumnFilterColumns) : {};
|
||||
resetColumnVisibility();
|
||||
closeLocalFilter();
|
||||
});
|
||||
|
||||
// --- Pagination ---
|
||||
const pageSizePreference = computed(() => resolveDataGridPageSizePreference(props.context, props.pageSizePreference));
|
||||
|
||||
+14
@@ -28,6 +28,20 @@ describe("data grid local column filter state", () => {
|
||||
expect(restored).toEqual({});
|
||||
});
|
||||
|
||||
it("maps a saved filter to its current column after a dynamic column reorder", () => {
|
||||
const restored = restoreDataGridLocalColumnFilters(
|
||||
{
|
||||
"1": ["str:open"],
|
||||
"2": ["str:stale"],
|
||||
},
|
||||
3,
|
||||
["id", "name", "status"],
|
||||
["id", "status", "removed"],
|
||||
);
|
||||
|
||||
expect(restored).toEqual({ 2: new Set(["str:open"]) });
|
||||
});
|
||||
|
||||
it("builds stable keys and filters rows across multiple columns", () => {
|
||||
expect(dataGridLocalFilterKey(null)).toBe("__dbx_null__");
|
||||
expect(dataGridLocalFilterKey(true)).toBe("bool:true");
|
||||
|
||||
@@ -72,13 +72,15 @@ export function buildDataGridLocalFilterOptions<TRow>({
|
||||
});
|
||||
}
|
||||
|
||||
export function restoreDataGridLocalColumnFilters(serialized: SerializedDataGridLocalColumnFilters | undefined, columnCount: number): Record<number, Set<string>> {
|
||||
export function restoreDataGridLocalColumnFilters(serialized: SerializedDataGridLocalColumnFilters | undefined, columnCount: number, currentColumns?: readonly string[], serializedColumns?: readonly string[]): Record<number, Set<string>> {
|
||||
if (!serialized || typeof serialized !== "object") return {};
|
||||
|
||||
const restored: Record<number, Set<string>> = {};
|
||||
for (const [columnIndexText, values] of Object.entries(serialized)) {
|
||||
const columnIndex = Number(columnIndexText);
|
||||
if (!Number.isInteger(columnIndex) || columnIndex < 0 || columnIndex >= columnCount || !Array.isArray(values)) continue;
|
||||
for (const [serializedColumnIndexText, values] of Object.entries(serialized)) {
|
||||
const serializedColumnIndex = Number(serializedColumnIndexText);
|
||||
if (!Number.isInteger(serializedColumnIndex) || serializedColumnIndex < 0 || !Array.isArray(values)) continue;
|
||||
const columnIndex = currentColumns && serializedColumns ? currentColumns.indexOf(serializedColumns[serializedColumnIndex] ?? "") : serializedColumnIndex;
|
||||
if (columnIndex < 0 || columnIndex >= columnCount) continue;
|
||||
const filteredValues = values.filter((value): value is string => typeof value === "string");
|
||||
if (filteredValues.length > 0) restored[columnIndex] = new Set(filteredValues);
|
||||
}
|
||||
|
||||
@@ -33,6 +33,10 @@ export interface DocumentBrowserStateSnapshot {
|
||||
documentFilterRules: DocumentFilterRule[];
|
||||
/** Zero-based page position; only meaningful for skip-based stores. */
|
||||
page: number;
|
||||
/** DataGrid local value filters, keyed by column index. */
|
||||
localColumnFilters?: Record<string, string[]>;
|
||||
/** Column names corresponding to the local filter indexes. */
|
||||
localColumnFilterColumns?: string[];
|
||||
/**
|
||||
* Rows from the last completed load. Written only by the unmount capture; a
|
||||
* conditions-only save (the keystroke path) drops it, which is the whole
|
||||
|
||||
Reference in new issue
Block a user