feat(grid): load large-value previews by viewport

This commit is contained in:
zipg authored and GitHub committed 2026-08-21 19:05:44 +08:00
1 parent 31a50fb460
commit e50bd26141
6 files changed
+721 -16

No files matched your search

+277 -4
View File
@@ -181,7 +181,20 @@ import { isCancelSearchShortcut, isCopyCurrentRowShortcut, isDeleteCurrentRowSho
import { dataGridHeaderContentWidth, scrollbarGutterWidth } from "@/lib/dataGrid/dataGridScrollGutter";
import { canFetchNextDataGridSegment, canGoNextDataGridPage, dataGridTotalRowCountLabelKey, dataGridTruncationHintKey, hasCompleteLocalDataGridResult, resolveDataGridPaginationTotal, type DataGridInexactTotalRowCountMode } from "@/lib/dataGrid/dataGridPagination";
import { dataGridCountQueryOptions } from "@/lib/dataGrid/dataGridQueryOptions";
import { createResultScopedPendingRequests, largeValueCellKey, largeValueCellMap, tableDataLargeValuePreviewOptions } from "@/lib/dataGrid/dataGridLargeValues";
import {
createResultScopedPendingRequests,
createResultScopedRowCache,
isTableDataVisiblePreviewColumn,
largeValueCellKey,
largeValueCellMap,
TABLE_DATA_VISIBLE_PREVIEW_CACHE_CONTENT_MAX_BYTES,
TABLE_DATA_VISIBLE_PREVIEW_CACHE_ROWS,
TABLE_DATA_VISIBLE_PREVIEW_SIZE,
tableDataLargeValuePreviewOptions,
tableDataVisiblePreviewContentBytes,
tableDataVisiblePreviewRowRange,
type ResultScopedRowCache,
} from "@/lib/dataGrid/dataGridLargeValues";
import { dataGridBottomScrollTop, dataGridScrollPosition, isDataGridAtScrollBottom, isDataGridNearScrollBottom, isDataGridPrefixAppend, shouldCheckInfiniteScrollAfterScroll, type DataGridScrollPosition } from "@/lib/dataGrid/dataGridInfiniteScroll";
import { CANVAS_DATA_GRID_ROW_HEIGHT, MAX_CANVAS_DATA_GRID_PIXEL_RATIO, canvasDataGridActionOverlayWidth, canvasDataGridActionReservedWidth, dataGridSearchMatchKey, drawCanvasDataGrid, type CanvasDevicePixelSize } from "@/lib/dataGrid/canvasDataGridRenderer";
import { DATA_GRID_DARK_STRIPED_ROW_BG, DATA_GRID_LIGHT_STRIPED_ROW_BG, dataGridActiveRowBackground } from "@/lib/dataGrid/dataGridPaintTheme";
@@ -2899,6 +2912,7 @@ function refreshGridScrollerMetrics() {
headerRef.value.scrollLeft = scrollerEl.scrollLeft;
}
observeGridHorizontalScrollbarScroller();
scheduleVisibleLargeValuePreviewHydration();
}
let columnLayoutRefreshFrame = 0;
@@ -2943,6 +2957,7 @@ function markGridScrolling() {
const scroller = gridScrollerElement();
if (scroller) updateDomGridVisibleItemsDuringScroll(scroller);
isScrolling.value = false;
scheduleVisibleLargeValuePreviewHydration();
}, 120);
}
@@ -3582,6 +3597,7 @@ const editor = useDataGridEditor({
currentPage,
cacheKey: computed(() => props.pendingStateKey ?? props.cacheKey),
onResultPayloadMutated: () => queryStore.invalidateResultEstimateForPayload(props.result),
onCellValueChanged: invalidateVisibleLargeValuePreviewCell,
prepareFullReload,
emit,
});
@@ -4330,7 +4346,7 @@ const displayRowIndexByIdLookup = computed(() => {
});
function rowItemFromDisplayRef(ref: DisplayRowRef): RowItem {
largeValueResolutionVersion.value;
void largeValueResolutionVersion.value;
if (ref.isNew) {
return {
...ref,
@@ -4523,6 +4539,19 @@ const LARGE_VALUE_FETCH_MAX_ROWS = 200;
const LARGE_VALUE_FETCH_TARGET_BYTES = 64 * 1024 * 1024;
const pendingLargeValueHydrations = createResultScopedPendingRequests<boolean>();
const largeValueCellsByKey = computed(() => largeValueCellMap(props.result));
type VisibleLargeValuePreviewRequest = {
item: RowItem;
sourceIndex: number;
initialValues: Map<number, { value: CellValue; revision: number }>;
};
const visibleLargeValuePreviewCaches = new WeakMap<QueryResult, ResultScopedRowCache<CellValue>>();
const visibleLargeValuePreviewCellRevisions = new WeakMap<QueryResult, Map<string, number>>();
const failedVisibleLargeValuePreviewResults = new WeakSet<QueryResult>();
const visibleLargeValuePreviewVersion = ref(0);
let visibleLargeValuePreviewTimer = 0;
let visibleLargeValuePreviewRequestedGeneration = 0;
let visibleLargeValuePreviewActive = true;
const visibleLargeValuePreviewExecutionIds = new Map<number, string>();
function isLargeValuePreview(item: RowItem | undefined, columnIndex: number): boolean {
if (!item || item.isNew || item.isDraft || item.sourceIndex === undefined || item.isDirtyCol[columnIndex]) return false;
@@ -4535,7 +4564,8 @@ function largeValueOriginalBytes(item: Pick<RowItem, "sourceIndex" | "isNew" | "
}
function formatGridItemCell(item: RowItem, columnIndex: number): string {
return formatCellCached(item.data[columnIndex], columnIndex, largeValueOriginalBytes(item, columnIndex));
void visibleLargeValuePreviewVersion.value;
return formatCellCached(visibleLargeValuePreviewValue(item, columnIndex, item.data[columnIndex] ?? null), columnIndex, largeValueOriginalBytes(item, columnIndex));
}
function formatGridItemCellForConfirmation(item: RowItem, columnIndex: number): string {
@@ -4556,6 +4586,248 @@ function largeValueSourceColumnIndex(columnName: string): number {
return resultSourceColumns.value.findIndex((column) => column.toLocaleLowerCase() === normalized);
}
function visibleLargeValuePreviewCache(result: QueryResult): ResultScopedRowCache<CellValue> {
let cache = visibleLargeValuePreviewCaches.get(result);
if (!cache) {
cache = createResultScopedRowCache(TABLE_DATA_VISIBLE_PREVIEW_CACHE_ROWS, {
maxBytes: TABLE_DATA_VISIBLE_PREVIEW_CACHE_CONTENT_MAX_BYTES,
sizeOf: tableDataVisiblePreviewContentBytes,
});
visibleLargeValuePreviewCaches.set(result, cache);
}
return cache;
}
function visibleLargeValuePreviewCellRevisionKey(sourceIndex: number, columnIndex: number): string {
return `${sourceIndex}:${columnIndex}`;
}
function visibleLargeValuePreviewCellRevision(result: QueryResult, sourceIndex: number, columnIndex: number): number {
return visibleLargeValuePreviewCellRevisions.get(result)?.get(visibleLargeValuePreviewCellRevisionKey(sourceIndex, columnIndex)) ?? 0;
}
function bumpVisibleLargeValuePreviewCellRevision(result: QueryResult, sourceIndex: number, columnIndex: number) {
let revisions = visibleLargeValuePreviewCellRevisions.get(result);
if (!revisions) {
revisions = new Map<string, number>();
visibleLargeValuePreviewCellRevisions.set(result, revisions);
}
const key = visibleLargeValuePreviewCellRevisionKey(sourceIndex, columnIndex);
revisions.set(key, (revisions.get(key) ?? 0) + 1);
}
function invalidateVisibleLargeValuePreviewCell(rowId: number, columnIndex: number) {
const item = getRowItem(rowId);
const sourceIndex = item?.sourceIndex ?? (rowId >= 0 ? rowId : undefined);
if (sourceIndex === undefined) return;
bumpVisibleLargeValuePreviewCellRevision(props.result, sourceIndex, columnIndex);
const cache = visibleLargeValuePreviewCaches.get(props.result);
if (!cache?.has(sourceIndex, columnIndex)) return;
cache.forget(sourceIndex, columnIndex);
visibleLargeValuePreviewVersion.value += 1;
scheduleCanvasDraw();
}
function visibleLargeValuePreviewValue(item: Pick<RowItem, "sourceIndex"> | undefined, columnIndex: number, fallback: CellValue): CellValue {
if (item?.sourceIndex === undefined) return fallback;
const preview = visibleLargeValuePreviewCaches.get(props.result)?.get(item.sourceIndex, columnIndex);
return preview === undefined ? fallback : preview;
}
function visibleLargeValuePreviewColumnIndexes(): number[] {
const rendered = renderedGridColumns.value.map((column) => column.actualColIdx);
return [...new Set(rendered)].filter((columnIndex) => {
const dataType = tableColumnForGridColumn(columnIndex)?.data_type ?? allColumnTypes.value[columnIndex] ?? "";
return isTableDataVisiblePreviewColumn(resolvedDatabaseType.value, dataType);
});
}
function evictVisibleLargeValuePreviews(cache: ResultScopedRowCache<CellValue>, protectedRows: ReadonlySet<number>): boolean {
return cache.evict(protectedRows).length > 0;
}
async function hydrateVisibleLargeValuePreviews(generation: number) {
const sourceResult = props.result;
const tableMeta = props.tableMeta;
const scroller = gridScrollerElement();
if (
!visibleLargeValuePreviewActive ||
generation !== visibleLargeValuePreviewRequestedGeneration ||
failedVisibleLargeValuePreviewResults.has(sourceResult) ||
showTranspose.value ||
(resolvedDatabaseType.value !== "mysql" && resolvedDatabaseType.value !== "postgres") ||
!props.connectionId ||
!tableMeta?.tableName ||
tableMeta.primaryKeys.length === 0 ||
!scroller
)
return;
const range = tableDataVisiblePreviewRowRange(scroller.scrollTop, scroller.clientHeight, CANVAS_DATA_GRID_ROW_HEIGHT, displayRowCount.value);
if (!range) return;
const cache = visibleLargeValuePreviewCache(sourceResult);
const activeSourceRows = new Set<number>();
const requests = new Map<number, VisibleLargeValuePreviewRequest>();
const targetColumnIndexes = visibleLargeValuePreviewColumnIndexes();
for (let displayIndex = range.start; displayIndex < range.end; displayIndex++) {
const item = displayItemAt(displayIndex);
if (!item || item.sourceIndex === undefined || item.isNew || item.isDraft) continue;
activeSourceRows.add(item.sourceIndex);
cache.touch(item.sourceIndex);
const initialValues = new Map<number, { value: CellValue; revision: number }>();
for (const columnIndex of targetColumnIndexes) {
if (!isLargeValuePreview(item, columnIndex) || cache.has(item.sourceIndex, columnIndex)) continue;
initialValues.set(columnIndex, {
value: item.data[columnIndex] ?? null,
revision: visibleLargeValuePreviewCellRevision(sourceResult, item.sourceIndex, columnIndex),
});
}
if (initialValues.size > 0) requests.set(item.sourceIndex, { item, sourceIndex: item.sourceIndex, initialValues });
}
if (requests.size === 0) {
if (evictVisibleLargeValuePreviews(cache, activeSourceRows)) {
visibleLargeValuePreviewVersion.value += 1;
scheduleCanvasDraw();
}
return;
}
const primaryKeyIndexes = tableMeta.primaryKeys.map(largeValueSourceColumnIndex);
if (primaryKeyIndexes.some((index) => index < 0)) return;
const requestedColumnIndexes = [...new Set([...requests.values()].flatMap((request) => [...request.initialValues.keys()]))];
const selectedColumns = [...tableMeta.primaryKeys];
for (const columnIndex of requestedColumnIndexes) {
const sourceColumn = resultSourceColumns.value[columnIndex];
if (sourceColumn && !selectedColumns.some((column) => column.toLocaleLowerCase() === sourceColumn.toLocaleLowerCase())) selectedColumns.push(sourceColumn);
}
const selectedColumnTypes = selectedColumns.map((column) => tableMeta.columns.find((candidate) => candidate.name.toLocaleLowerCase() === column.toLocaleLowerCase())?.data_type ?? "");
const predicates = await Promise.all([...requests.values()].map((request) => largeValueRowPredicate(request.item, primaryKeyIndexes)));
if (!visibleLargeValuePreviewActive || generation !== visibleLargeValuePreviewRequestedGeneration || props.result !== sourceResult) return;
const sql = await buildTableSelectSql({
databaseType: resolvedDatabaseType.value,
identifierQuote: connectionStore.connectionIdentifierQuote?.(props.connectionId),
database: tableMeta.database,
schema: tableMeta.schema,
tableName: tableMeta.tableName,
tableType: tableMeta.tableType,
catalog: tableMeta.catalog,
columns: selectedColumns,
columnTypes: selectedColumnTypes,
largeValuePreviewSize: TABLE_DATA_VISIBLE_PREVIEW_SIZE,
primaryKeys: tableMeta.primaryKeys,
whereInput: predicates.map((predicate) => `(${predicate})`).join(" OR "),
limit: requests.size,
offset: 0,
});
if (!visibleLargeValuePreviewActive || generation !== visibleLargeValuePreviewRequestedGeneration || props.result !== sourceResult) return;
const connection = connectionStore.getConfig(props.connectionId);
const executionId = uuid();
visibleLargeValuePreviewExecutionIds.set(generation, executionId);
let results: QueryResult[];
try {
results = await api.executeMulti(props.connectionId, props.executionDatabase ?? props.database ?? "", sql, undefined, executionId, {
maxRows: requests.size,
fetchSize: requests.size,
resultKeyColumns: tableMeta.primaryKeys,
tableDataPreview: true,
timeoutSecs: queryTimeoutSecsForConnection(connection, settingsStore.editorSettings.globalQueryTimeoutSecs),
});
} finally {
if (visibleLargeValuePreviewExecutionIds.get(generation) === executionId) visibleLargeValuePreviewExecutionIds.delete(generation);
}
if (!visibleLargeValuePreviewActive || generation !== visibleLargeValuePreviewRequestedGeneration || props.result !== sourceResult) return;
const result = results[0];
if (!result || result.execution_error) {
throw new Error(result?.error ? translateBackendError(t, result.error) : String(result?.rows?.[0]?.[0] ?? t("grid.largeValueLoadFailed")));
}
const resultColumnIndexes = selectedColumns.map((column) => {
const normalized = column.toLocaleLowerCase();
return result.columns.findIndex((resultColumn) => resultColumn.toLocaleLowerCase() === normalized);
});
if (resultColumnIndexes.some((index) => index < 0)) throw new Error(t("grid.largeValueColumnUnavailable"));
const resultPrimaryKeyIndexes = resultColumnIndexes.slice(0, tableMeta.primaryKeys.length);
const valuesByIdentity = new Map(result.rows.map((row) => [largeValueIdentityKey(row, resultPrimaryKeyIndexes), row]));
const currentLargeValueCells = largeValueCellMap(sourceResult);
let changed = false;
for (const request of requests.values()) {
const currentRow = sourceResult.rows[request.sourceIndex];
if (!currentRow) continue;
const identity = largeValueIdentityKey(currentRow, primaryKeyIndexes);
const resolvedRow = valuesByIdentity.get(identity);
if (!resolvedRow) continue;
for (const [columnIndex, initialValue] of request.initialValues) {
if (!currentLargeValueCells.has(largeValueCellKey(request.sourceIndex, columnIndex)) || currentRow[columnIndex] !== initialValue.value || visibleLargeValuePreviewCellRevision(sourceResult, request.sourceIndex, columnIndex) !== initialValue.revision) continue;
const sourceColumn = resultSourceColumns.value[columnIndex];
const selectedIndex = selectedColumns.findIndex((column) => column.toLocaleLowerCase() === sourceColumn?.toLocaleLowerCase());
const resultIndex = resultColumnIndexes[selectedIndex];
if (resultIndex === undefined || resultIndex < 0) continue;
const previewValue = resolvedRow[resultIndex] ?? null;
cache.remember(request.sourceIndex, columnIndex, previewValue);
changed = true;
}
}
if (evictVisibleLargeValuePreviews(cache, activeSourceRows)) changed = true;
if (!changed) return;
visibleLargeValuePreviewVersion.value += 1;
scheduleCanvasDraw();
}
async function runVisibleLargeValuePreviewHydration(generation: number) {
if (!visibleLargeValuePreviewActive || generation !== visibleLargeValuePreviewRequestedGeneration) return;
const sourceResult = props.result;
try {
await hydrateVisibleLargeValuePreviews(generation);
} catch (error) {
if (props.result === sourceResult && generation === visibleLargeValuePreviewRequestedGeneration && !failedVisibleLargeValuePreviewResults.has(sourceResult)) {
failedVisibleLargeValuePreviewResults.add(sourceResult);
appendDebugLog("warn", "[DBX][DataGrid:visible-large-value-preview] disabled for result", error);
}
}
}
function cancelVisibleLargeValuePreviewHydrations() {
for (const [generation, executionId] of visibleLargeValuePreviewExecutionIds) {
visibleLargeValuePreviewExecutionIds.delete(generation);
void api.cancelQuery(executionId).catch((error) => appendDebugLog("warn", "[DBX][DataGrid:visible-large-value-preview] cancel failed", error));
}
}
function scheduleVisibleLargeValuePreviewHydration(delay = 150) {
if (!visibleLargeValuePreviewActive) return;
const generation = ++visibleLargeValuePreviewRequestedGeneration;
cancelVisibleLargeValuePreviewHydrations();
window.clearTimeout(visibleLargeValuePreviewTimer);
visibleLargeValuePreviewTimer = window.setTimeout(() => {
visibleLargeValuePreviewTimer = 0;
void runVisibleLargeValuePreviewHydration(generation);
}, delay);
}
function pauseVisibleLargeValuePreviewHydration() {
visibleLargeValuePreviewActive = false;
visibleLargeValuePreviewRequestedGeneration += 1;
cancelVisibleLargeValuePreviewHydrations();
window.clearTimeout(visibleLargeValuePreviewTimer);
visibleLargeValuePreviewTimer = 0;
}
function resumeVisibleLargeValuePreviewHydration() {
visibleLargeValuePreviewActive = true;
scheduleVisibleLargeValuePreviewHydration();
}
watch(
() => [props.result, props.result.rows.length, renderedGridColumns.value.map((column) => column.actualColIdx).join(","), showTranspose.value] as const,
() => {
nextTick(() => scheduleVisibleLargeValuePreviewHydration());
},
{ immediate: true },
);
onActivated(resumeVisibleLargeValuePreviewHydration);
onDeactivated(pauseVisibleLargeValuePreviewHydration);
dataGridRuntimeScope.addCleanup(pauseVisibleLargeValuePreviewHydration);
function chunkLargeValueRequests(requests: LargeValueCellRequest[]): LargeValueCellRequest[][] {
const chunks: LargeValueCellRequest[][] = [];
let chunk: LargeValueCellRequest[] = [];
@@ -4717,6 +4989,7 @@ async function hydrateLargeValueCell(rowId: number, columnIndex: number): Promis
const rows = sourceResult.rows.slice();
rows[item.sourceIndex!] = row;
sourceResult.rows = rows;
visibleLargeValuePreviewCaches.get(sourceResult)?.forget(item.sourceIndex!, columnIndex);
sourceResult.large_value_cells = sourceResult.large_value_cells?.filter((cell) => cell.row_index !== item.sourceIndex || cell.column_index !== columnIndex);
largeValueResolutionVersion.value += 1;
clearCellFormatCache();
@@ -6816,7 +7089,7 @@ function drawCanvasGrid() {
editingCell: editingCell.value,
searchMatchKeys: searchMatchSet.value,
currentSearchMatch: currentSearchMatch.value,
formatCell: (value, columnIndex, row) => formatCellCached(value, columnIndex, largeValueOriginalBytes(row, columnIndex)),
formatCell: (value, columnIndex, row) => formatCellCached(visibleLargeValuePreviewValue(row, columnIndex, value), columnIndex, largeValueOriginalBytes(row, columnIndex)),
draftCellPlaceholder: t("grid.quickEntryDraftPlaceholder"),
isRowActive,
rowCellsUseSelectionVisual,
@@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => ({
buildDataGridContextFilterCondition: vi.fn(async ({ columnName, value }: { columnName: string; value: unknown }) => `\`${columnName}\` = '${String(value)}'`),
buildTableSelectSql: vi.fn(async ({ whereInput }: { whereInput?: string }) => `SELECT payload FROM events${whereInput ? ` WHERE ${whereInput}` : ""}`),
executeMulti: vi.fn(),
cancelQuery: vi.fn(),
toast: vi.fn(),
}));
@@ -18,6 +19,7 @@ vi.mock("@/lib/backend/api", () => ({
buildDataGridContextFilterCondition: mocks.buildDataGridContextFilterCondition,
buildTableSelectSql: mocks.buildTableSelectSql,
executeMulti: mocks.executeMulti,
cancelQuery: mocks.cancelQuery,
}));
vi.mock("@/composables/useToast", () => ({
@@ -84,10 +86,44 @@ function hydratedResult(id: number, value: string): QueryResult {
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((resolvePromise) => {
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, resolve };
return { promise, resolve, reject };
}
function mockDeferredFullHydration(hydration: Promise<QueryResult[]>) {
mocks.executeMulti.mockImplementation((...args: unknown[]) => {
const options = args[5] as { tableDataPreview?: boolean } | undefined;
return options?.tableDataPreview ? Promise.resolve([hydratedResult(1, "visible preview")]) : hydration;
});
}
function fullHydrationCallCount() {
return mocks.executeMulti.mock.calls.filter((call) => !(call[5] as { tableDataPreview?: boolean } | undefined)?.tableDataPreview).length;
}
function visibleHydrationCalls() {
return mocks.executeMulti.mock.calls.filter((call) => (call[5] as { tableDataPreview?: boolean } | undefined)?.tableDataPreview);
}
function gridCell(host: HTMLElement): HTMLElement {
const cell = host.querySelector<HTMLElement>('[data-row-index="0"] [data-visible-col-index="1"]');
if (!cell) throw new Error("Large-value grid cell not found");
return cell;
}
function pasteGridCell(host: HTMLElement, value: string) {
const cell = gridCell(host);
cell.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 }));
window.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, cancelable: true, button: 0 }));
const paste = new Event("paste", { bubbles: true, cancelable: true });
Object.defineProperty(paste, "clipboardData", { value: { getData: () => value } });
const gridRoot = host.querySelector<HTMLElement>("[data-grid-root]");
if (!gridRoot) throw new Error("Data grid root not found");
gridRoot.dispatchEvent(paste);
}
function mountGrid(initialResult = largeValueResult()) {
@@ -137,8 +173,19 @@ function mountGrid(initialResult = largeValueResult()) {
// Mount once with the production-default Canvas mode so DataGrid finishes
// setting up its column-width dependencies, then exercise the DOM grid.
settingsStore.updateEditorSettings({ dataGridRenderMode: "dom" });
mountedApps.push({ app, host });
return { host, onExecuteSql, replaceResult: (nextResult: QueryResult) => (result.value = markRaw(nextResult)) };
const mounted = { app, host };
mountedApps.push(mounted);
return {
host,
onExecuteSql,
replaceResult: (nextResult: QueryResult) => (result.value = markRaw(nextResult)),
unmount: () => {
const index = mountedApps.indexOf(mounted);
if (index >= 0) mountedApps.splice(index, 1);
app.unmount();
host.remove();
},
};
}
async function settle() {
@@ -166,6 +213,7 @@ async function startEqualsFilter(host: HTMLElement) {
beforeEach(() => {
vi.clearAllMocks();
mocks.cancelQuery.mockResolvedValue(true);
});
afterEach(() => {
@@ -179,11 +227,11 @@ afterEach(() => {
describe("DataGrid context filter lifecycle", () => {
it("keeps the right-click target through menu close and large-value hydration", async () => {
const hydration = deferred<QueryResult[]>();
mocks.executeMulti.mockReturnValue(hydration.promise);
mockDeferredFullHydration(hydration.promise);
const { host, onExecuteSql } = mountGrid();
await startEqualsFilter(host);
await vi.waitFor(() => expect(mocks.executeMulti).toHaveBeenCalledTimes(1));
await vi.waitFor(() => expect(fullHydrationCallCount()).toBe(1));
expect(document.querySelector("[data-dbx-context-menu]")).toBeNull();
hydration.resolve([hydratedResult(1, "full original value")]);
@@ -196,11 +244,11 @@ describe("DataGrid context filter lifecycle", () => {
it("does not apply a completed hydration from a previous result set", async () => {
const hydration = deferred<QueryResult[]>();
mocks.executeMulti.mockReturnValue(hydration.promise);
mockDeferredFullHydration(hydration.promise);
const { host, onExecuteSql, replaceResult } = mountGrid();
await startEqualsFilter(host);
await vi.waitFor(() => expect(mocks.executeMulti).toHaveBeenCalledTimes(1));
await vi.waitFor(() => expect(fullHydrationCallCount()).toBe(1));
replaceResult(largeValueResult(2, "new preview"));
await settle();
hydration.resolve([hydratedResult(1, "old value")]);
@@ -224,3 +272,127 @@ describe("DataGrid context filter lifecycle", () => {
expect(onExecuteSql).not.toHaveBeenCalled();
});
});
describe("DataGrid visible large-value preview lifecycle", () => {
it("invalidates a hydrated preview when paste edits the selected cell", async () => {
mocks.executeMulti.mockImplementation((...args: unknown[]) => {
const options = args[5] as { tableDataPreview?: boolean } | undefined;
return Promise.resolve([hydratedResult(1, options?.tableDataPreview ? "visible preview" : "full value")]);
});
const { host } = mountGrid();
await vi.waitFor(() => expect(gridCell(host).textContent).toContain("visible preview"));
pasteGridCell(host, "edited value");
await vi.waitFor(() => expect(gridCell(host).textContent).toContain("edited value"));
});
it("cancels a stale viewport request and starts the newest generation", async () => {
const firstHydration = deferred<QueryResult[]>();
let visibleRequestCount = 0;
mocks.executeMulti.mockImplementation((...args: unknown[]) => {
const options = args[5] as { tableDataPreview?: boolean } | undefined;
if (!options?.tableDataPreview) return Promise.resolve([hydratedResult(1, "full value")]);
visibleRequestCount += 1;
return visibleRequestCount === 1 ? firstHydration.promise : Promise.resolve([hydratedResult(1, "latest preview")]);
});
mocks.cancelQuery.mockImplementation(async () => {
firstHydration.reject(new Error("cancelled"));
return true;
});
const { host } = mountGrid();
await vi.waitFor(() => expect(visibleHydrationCalls()).toHaveLength(1));
const firstExecutionId = visibleHydrationCalls()[0]?.[4];
const scroller = host.querySelector<HTMLElement>(".data-grid-scroller");
if (!scroller) throw new Error("Data grid scroller not found");
scroller.scrollTop = 26;
scroller.dispatchEvent(new Event("scroll", { bubbles: true }));
await vi.waitFor(() => expect(mocks.cancelQuery).toHaveBeenCalledWith(firstExecutionId));
await vi.waitFor(() => expect(visibleHydrationCalls()).toHaveLength(2));
expect(visibleHydrationCalls()[1]?.[4]).not.toBe(firstExecutionId);
});
it("does not cache a visible preview completed after the cell is edited", async () => {
const hydration = deferred<QueryResult[]>();
mocks.executeMulti.mockImplementation((...args: unknown[]) => {
const options = args[5] as { tableDataPreview?: boolean } | undefined;
return options?.tableDataPreview ? hydration.promise : Promise.resolve([hydratedResult(1, "full value")]);
});
const { host } = mountGrid();
await vi.waitFor(() => expect(visibleHydrationCalls()).toHaveLength(1));
pasteGridCell(host, "edited during hydration");
await vi.waitFor(() => expect(gridCell(host).textContent).toContain("edited during hydration"));
hydration.resolve([hydratedResult(1, "stale visible preview")]);
await settle();
expect(gridCell(host).textContent).toContain("edited during hydration");
expect(gridCell(host).textContent).not.toContain("stale visible preview");
});
it("invalidates hydrated previews across undo, scroll, and redo", async () => {
let visibleRequestCount = 0;
mocks.executeMulti.mockImplementation((...args: unknown[]) => {
const options = args[5] as { tableDataPreview?: boolean } | undefined;
if (!options?.tableDataPreview) return Promise.resolve([hydratedResult(1, "full value")]);
visibleRequestCount += 1;
return Promise.resolve([hydratedResult(1, visibleRequestCount === 1 ? "initial visible preview" : "undo visible preview")]);
});
const { host } = mountGrid();
await vi.waitFor(() => expect(gridCell(host).textContent).toContain("initial visible preview"));
pasteGridCell(host, "edited value");
await vi.waitFor(() => expect(gridCell(host).textContent).toContain("edited value"));
const gridRoot = host.querySelector<HTMLElement>("[data-grid-root]");
const scroller = host.querySelector<HTMLElement>(".data-grid-scroller");
if (!gridRoot || !scroller) throw new Error("Data grid controls not found");
gridRoot.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ctrlKey: true, key: "z" }));
await settle();
scroller.scrollTop = 26;
scroller.dispatchEvent(new Event("scroll", { bubbles: true }));
await vi.waitFor(() => expect(gridCell(host).textContent).toContain("undo visible preview"));
gridRoot.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ctrlKey: true, shiftKey: true, key: "z" }));
await vi.waitFor(() => expect(gridCell(host).textContent).toContain("edited value"));
expect(gridCell(host).textContent).not.toContain("undo visible preview");
});
it("does not start a stale query after deferred SQL construction and scrolling", async () => {
const firstBuild = deferred<string>();
mocks.buildTableSelectSql.mockImplementationOnce(() => firstBuild.promise).mockResolvedValueOnce("SELECT latest preview");
mocks.executeMulti.mockResolvedValue([hydratedResult(1, "latest visible preview")]);
const { host } = mountGrid();
await vi.waitFor(() => expect(mocks.buildTableSelectSql).toHaveBeenCalledTimes(1));
const scroller = host.querySelector<HTMLElement>(".data-grid-scroller");
if (!scroller) throw new Error("Data grid scroller not found");
scroller.scrollTop = 26;
scroller.dispatchEvent(new Event("scroll", { bubbles: true }));
await vi.waitFor(() => expect(mocks.buildTableSelectSql).toHaveBeenCalledTimes(2));
await vi.waitFor(() => expect(visibleHydrationCalls()).toHaveLength(1));
firstBuild.resolve("SELECT stale preview");
await settle();
expect(visibleHydrationCalls()).toHaveLength(1);
expect(visibleHydrationCalls()[0]?.[2]).toBe("SELECT latest preview");
});
it("does not start a stale query after deferred SQL construction and unmount", async () => {
const build = deferred<string>();
mocks.buildTableSelectSql.mockImplementationOnce(() => build.promise);
const { unmount } = mountGrid();
await vi.waitFor(() => expect(mocks.buildTableSelectSql).toHaveBeenCalledTimes(1));
unmount();
build.resolve("SELECT stale preview");
await settle();
expect(visibleHydrationCalls()).toHaveLength(0);
});
});