test: drop source-text assertion tests and merge locale checks

This commit is contained in:
t8y2 committed 2026-09-23 22:10:06 +08:00
1 parent 349d77d180
commit 8897e12714
257 files changed
+166 -12815

No files matched your search

@@ -1,7 +1,5 @@
// @vitest-environment happy-dom
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { createApp, defineComponent, h, markRaw, nextTick, type App, type PropType } from "vue";
import { createPinia, setActivePinia } from "pinia";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -493,16 +491,4 @@ describe("DataGrid multi-row paste from a blank cell", () => {
expect(updates).toEqual([{ $set: { status: "{plain text" } }, { $set: { status: "{plain text" } }]);
});
it("routes DOM and canvas cell gestures through the same selection preparation", () => {
const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGrid.vue"), "utf8");
const domGesture = source.slice(source.indexOf('@mousedown="\n prepareDataCellMouseDown'), source.indexOf('@mouseenter="onCellMouseenter'));
const canvasGesture = source.slice(source.indexOf("function onCanvasMouseDown"), source.indexOf("function onCanvasContext"));
expect(domGesture).toContain("prepareDataCellMouseDown(item, col.actualColIdx);");
expect(domGesture).toContain("handleDataCellMousedown(item.displayIndex, col.visibleColIdx, item.id, $event);");
expect(canvasGesture).toContain("prepareDataCellMouseDown(item, actualColIdx)");
expect(canvasGesture).toContain("handleDataCellMousedown(item.displayIndex, hit.visibleColIdx, item.id, event)");
expect(source).toContain("columnIndexes: visibleColumnIndexes.value.slice(range.startCol)");
});
});
@@ -1,62 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
const largeValueSource = readFileSync(new URL("../../../composables/useDataGridLargeValues.ts", import.meta.url), "utf8");
describe("DataGrid cell detail selection", () => {
it("selects the first available cell when opening Mongo JSON preview without a selection", () => {
const togglePreview = dataGridSource.match(/function toggleMongoJsonPreview[\s\S]*?\n\}/)?.[0];
expect(togglePreview).toContain("if (showMongoJsonPreview.value)");
expect(togglePreview).toContain("!currentSelectedCellPosition() && displayItems.value.length > 0 && visibleColumnIndexes.value.length > 0");
expect(togglePreview).toContain("selectSingleCell(0, 0)");
});
it("keeps Canvas hover state while the renderer swaps drawing surfaces", () => {
expect(dataGridSource).toContain("function isCanvasGridInteractionTarget(target: Node): boolean");
expect(dataGridSource).toContain("canvasOverlayRef.value?.contains(target) === true");
expect(dataGridSource).toContain("canvasRef.value?.contains(target) === true");
expect(dataGridSource).toContain("canvasBackRef.value?.contains(target) === true");
const canvasLeave = dataGridSource.match(/function onCanvasMouseLeave[\s\S]*?\n\}/)?.[0];
const detailLeave = dataGridSource.match(/function clearCanvasDetailHover[\s\S]*?\n\}/)?.[0];
expect(canvasLeave).toContain("isCanvasGridInteractionTarget(relatedTarget)");
expect(detailLeave).toContain("isCanvasGridInteractionTarget(relatedTarget)");
});
it("gates only the three hover Info buttons with the visibility setting", () => {
expect(dataGridSource).toContain("const cellDetailButtonEnabled = computed(() => settingsStore.editorSettings.dataGridCellDetailButtonVisible);");
expect(dataGridSource.match(/v-if="cellDetailButtonEnabled"/g)).toHaveLength(3);
expect(dataGridSource.match(/v-if="cellDetailButtonVisible\(/g)).toHaveLength(2);
const hoverVisibility = dataGridSource.match(/function cellDetailButtonVisible[\s\S]*?\n\}/)?.[0];
expect(hoverVisibility).toBeDefined();
expect(hoverVisibility).not.toContain("dataGridCellDetailButtonVisible");
});
it("removes the Canvas action overlay and reservation only when no action remains", () => {
expect(dataGridSource).toContain("if (!cellDetailButtonEnabled.value && !canQuickDownload && !foreignKey && !externalUrl) return null;");
expect(dataGridSource).toContain("canvasDataGridActionOverlayWidth(canQuickDownload, !!foreignKey, cellDetailButtonEnabled.value, !!externalUrl)");
expect(dataGridSource).toContain("canvasDataGridActionOverlayWidth(cell.canQuickDownload, !!cell.foreignKey, cellDetailButtonEnabled.value, !!cell.externalUrl)");
expect(dataGridSource).toContain("canvasDataGridActionReservedWidth(cell.canQuickDownload, !!cell.foreignKey, cellDetailButtonEnabled.value, !!cell.externalUrl)");
expect(dataGridSource).toMatch(/watch\([\s\S]*?cellDetailButtonEnabled,[\s\S]*?scheduleCanvasDraw/);
});
it("keeps context-menu details and refresh restoration independent of the hover setting", () => {
expect(dataGridSource).toContain("cellDetails: openContextCellDetailDialog");
expect(dataGridSource).toContain("if (cellDialog) openCellDetailDialog(cellDialog.rowIndex, cellDialog.col);");
});
it("resynchronizes the open detail after a mouse selection gesture finishes", () => {
expect(dataGridSource).toContain("watch([selectedRange, showCellDetail, isEditingDetail, isSelectingCells]");
expect(dataGridSource).toContain("if (isSelectingCells.value) return;");
expect(dataGridSource).toMatch(/detailCell\.value = target;\s+hydrateCellDetailTarget\(target\);/);
});
it("hydrates bounded large-value previews for every cell detail target", () => {
expect(largeValueSource).toContain("function isLargeValuePreview");
expect(dataGridSource).toContain("function hydrateLargeValueCell");
expect(dataGridSource).toMatch(/showCellDetails[\s\S]*?hydrateCellDetailTarget\(detailCell\.value\)/);
expect(dataGridSource).toMatch(/openCellDetailDialog[\s\S]*?hydrateCellDetailTarget\(cellDetailDialogTarget\.value\)/);
});
});
@@ -1,12 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
describe("DataGrid synchronized column order selection", () => {
it("reconciles the active selection when another grid changes the table order", () => {
expect(dataGridSource).toContain("applyColumnOrderChange(() => onTableDataGridColumnOrderChanged(event));");
expect(dataGridSource).toContain("window.addEventListener(TABLE_DATA_GRID_COLUMN_ORDER_CHANGED_EVENT, onSynchronizedTableDataGridColumnOrderChanged);");
expect(dataGridSource).toContain("window.removeEventListener(TABLE_DATA_GRID_COLUMN_ORDER_CHANGED_EVENT, onSynchronizedTableDataGridColumnOrderChanged);");
});
});
@@ -1,8 +1,6 @@
// @vitest-environment happy-dom
import { createApp, defineComponent, h, nextTick, ref, type App } from "vue";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import DataGridConditionEditor from "@/components/grid/DataGridConditionEditor.vue";
import type { DataGridConditionHistoryKind } from "@/lib/dataGrid/dataGridConditionHistory";
@@ -258,97 +256,6 @@ describe("DataGridConditionEditor quote completion", () => {
expect(document.querySelector('[role="listbox"]')).toBeNull();
});
it("keeps the wrapped input caret aligned with its syntax highlight layer", () => {
const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGridConditionEditor.vue"), "utf8");
const expandedInputCss = source.match(/\.data-grid-topbar-condition-input--expanded\s*\{(?<body>[\s\S]*?)\n\}/)?.groups?.body;
const expandedHighlightCss = source.match(/\.data-grid-condition-highlight--expanded\s*\{(?<body>[\s\S]*?)\n\}/)?.groups?.body;
const prefixPadding = "calc(var(--data-grid-condition-prefix-indent) + 0.125rem)";
expect(expandedInputCss).toContain("padding:");
expect(expandedInputCss).toContain(prefixPadding);
expect(expandedHighlightCss).toContain(prefixPadding);
expect(expandedInputCss).not.toContain("text-indent:");
expect(expandedHighlightCss).not.toContain("text-indent:");
expect(expandedInputCss).toContain("overflow-wrap: anywhere");
expect(source).toContain("white-space:pre-wrap;overflow-wrap:anywhere;");
expect(source).not.toContain("textIndent: rect.prefix");
expect(source).toContain("paddingLeft: rect.prefix + 2");
expect(source).toContain("paddingRight: rect.suffix + 8");
expect(source).toContain("width: Math.max(1, rect.width - 8)");
expect(source).toContain("function fitExpandedHeightToOverlay()");
expect(source).toContain("expandedHeight.value + overflow");
});
it("keeps the expanded condition label readable over wrapped content", () => {
const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGridConditionEditor.vue"), "utf8");
const floatingControls = source.match(/data-grid-topbar-condition-floating-controls[^"]*/)?.[0];
const floatingLabelCss = source.match(/\.data-grid-topbar-condition-label--floating\s*\{(?<body>[\s\S]*?)\n\}/)?.groups?.body;
const compactFloatingLabelCss = source.match(/\.data-grid-topbar-condition-label--floating\.data-grid-topbar-condition-label--compact\s*\{(?<body>[\s\S]*?)\n\}/)?.groups?.body;
expect(floatingControls).toContain("z-[2]");
expect(source).toContain("data-grid-topbar-condition-label--floating");
expect(source).toContain("label.scrollWidth + 4");
expect(floatingLabelCss).toContain("text-shadow:");
expect(floatingLabelCss).not.toContain("padding-right:");
expect(floatingLabelCss).not.toContain("box-shadow:");
expect(compactFloatingLabelCss).toContain("max-width: 5rem");
expect(compactFloatingLabelCss).toContain("opacity: 1");
});
it("keeps dark condition styles scoped to their target elements", () => {
const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGridConditionEditor.vue"), "utf8");
expect(source).not.toContain(":global(.dark) .data-grid");
expect(source).toContain(":global(.dark .data-grid-topbar-condition-label--floating)");
expect(source).toContain(":global(.dark .data-grid-topbar-condition-pane--expanded)");
});
it("scrolls the caret into view after accepting a long completion", () => {
const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGridConditionEditor.vue"), "utf8");
expect(source).toContain("function scrollCaretIntoView()");
expect(source).toContain("const hasVerticalOverflow = target.scrollHeight > target.clientHeight + 4");
expect(source).toContain("const hasHorizontalOverflow = target.scrollWidth > target.clientWidth + 1");
expect(source).toContain("target.scrollTop = 0");
expect(source).toContain("const caretLeft = caretMarker.offsetLeft");
expect(source).toContain("target.scrollLeft");
expect(source).toContain("function scheduleCaretIntoView()");
expect(source).toContain("function focusAfterAccept()");
expect(source).toContain("requestAnimationFrame(() => scrollCaretIntoView())");
expect(source).toContain("scheduleCaretIntoView()");
expect(source).toContain('if (action === "accept") focusAfterAccept()');
});
it("also keeps the caret visible after regular input wraps", () => {
const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGridConditionEditor.vue"), "utf8");
const onInputBody = source.match(/function onInput\(event: Event\) \{(?<body>[\s\S]*?)\n\}/)?.groups?.body;
expect(onInputBody).toContain("resizeEditor(true)");
expect(onInputBody).toContain("updateSuggestionPosition()");
expect(onInputBody).toContain("scheduleCaretIntoView()");
});
it("keeps the caret visible after switching focus into the expanded editor", () => {
const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGridConditionEditor.vue"), "utf8");
const focusTransferBody = source.match(/if \(nextExpanded && document\.activeElement === input && !composing\.value\) \{(?<body>[\s\S]*?)\n \}/)?.groups?.body;
expect(focusTransferBody).toContain("const start = selectionStart.value");
expect(focusTransferBody).toContain("overlay.setSelectionRange(start, end)");
expect(focusTransferBody).toContain("overlay.focus({ preventScroll: true })");
expect(focusTransferBody).toContain("scheduleCaretIntoView()");
});
it("keeps the caret visible after collapsing the expanded editor back to one line", () => {
const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGridConditionEditor.vue"), "utf8");
const collapseTransferBody = source.match(/if \(!nextExpanded && overlayFocused && !composing\.value\) \{(?<body>[\s\S]*?)\n \}/)?.groups?.body;
expect(collapseTransferBody).toContain("const start = selectionStart.value");
expect(collapseTransferBody).toContain("input.setSelectionRange(start, end)");
expect(collapseTransferBody).toContain("input.focus({ preventScroll: true })");
expect(collapseTransferBody!.indexOf("input.focus({ preventScroll: true })")).toBeLessThan(collapseTransferBody!.indexOf("input.setSelectionRange(start, end)"));
expect(collapseTransferBody).toContain("scheduleCaretIntoView()");
});
it("preserves continuous input when the expanded editor collapses", async () => {
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
const textWidth = (this.textContent?.length ?? 0) * 8;
@@ -472,15 +379,6 @@ describe("DataGridConditionEditor quote completion", () => {
expect(expandedHighlight?.style.transform).toBe("translate(0px, 0px)");
vi.unstubAllGlobals();
});
it("positions suggestions below the measured expanded editor height", () => {
const source = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGridConditionEditor.vue"), "utf8");
const expandedPaneCss = source.match(/\.data-grid-topbar-condition-pane--expanded\s*\{(?<body>[\s\S]*?)\n\}/)?.groups?.body;
expect(source).toContain("bottom: expandedRect.value.top + expandedHeight.value");
expect(expandedPaneCss).toContain("transition: box-shadow 150ms ease");
expect(expandedPaneCss).not.toContain("height 150ms");
});
});
describe("DataGridConditionEditor Chinese column matching", () => {
@@ -1,34 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
const metadataLoaderSource = readFileSync(new URL("../../../composables/useDataGridTableMetadataLoaders.ts", import.meta.url), "utf8");
describe("DataGrid DDL search navigation", () => {
it("resets navigation when the raw search query changes", () => {
expect(dataGridSource).toMatch(/watch\(\s*searchQuery,\s*async \(\) => \{\s*ddlSearchMatchIndex\.value = 0;/);
});
it("highlights the DDL once and marks the rendered DOM for the search", () => {
// #9212: re-highlighting (and re-parsing) the whole DDL on every keystroke
// froze the window, so the highlighted HTML only depends on the DDL itself
// and the search marks are applied to the already-rendered <pre>.
expect(dataGridSource).toMatch(/const highlightedDdlContent = computed\(\(\) => \(ddlContent\.value \? highlight\(ddlContent\.value\) : ""\)\);/);
expect(dataGridSource).toContain('v-html="highlightedDdlContent"');
expect(dataGridSource).toContain('import { applyDdlSearchMarks } from "@/lib/sql/ddlSearchMarks"');
expect(dataGridSource).not.toContain("filteredDdlContent");
expect(dataGridSource.match(/applyDdlSearchMarks\(ddlPreRef\.value, searchQuery\.value\)/g) ?? []).toHaveLength(3);
});
it("uses the shared DDL cache policy and exposes refresh controls", () => {
expect(metadataLoaderSource).toContain('from "@/lib/metadata/objectDdlCache"');
expect(metadataLoaderSource).toContain("async function fetchDdl(force = options.settingsStore.editorSettings.refreshDdlOnOpen)");
expect(metadataLoaderSource).toMatch(/objectType: tableObjectSourceKind\(props\.tableMeta\.tableType\)/);
expect(metadataLoaderSource).toContain("loadObjectDdl(request, { force })");
expect(dataGridSource).toMatch(/async function refreshActiveTableInfo\(\)[\s\S]*?fetchDdl\(true\)[\s\S]*?fetchTableInfoColumns\(true\)[\s\S]*?fetchIndexes\(\)[\s\S]*?fetchForeignKeys\(\)[\s\S]*?fetchConstraints\(\)[\s\S]*?fetchTriggers\(\)/);
expect(dataGridSource).toContain('@click="refreshActiveTableInfo"');
expect(metadataLoaderSource).toMatch(/loadObjectMetadataFacet\(request, "columns"/);
expect(dataGridSource).toMatch(/activeTableInfoTab\.value === "constraints"\) return constraintsLoading\.value/);
expect(dataGridSource).not.toContain("setTableInfoRefreshDdlOnOpen");
});
});
@@ -1,10 +1,6 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { adjacentDataGridDetailIndex, detailNavigationDelta, shouldIgnoreDataGridDetailNavigation } from "../../../lib/dataGrid/dataGridDetailNavigation";
const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
const detailDialogsSource = readFileSync(new URL("../DataGridDetailDialogs.vue", import.meta.url), "utf8");
function keyboardEvent(overrides: Partial<KeyboardEvent> = {}): KeyboardEvent {
return {
key: "ArrowDown",
@@ -25,12 +21,6 @@ function targetMatching(selectorPart: string): EventTarget {
return { closest: (selector: string) => (selector.includes(selectorPart) ? {} : null) } as unknown as EventTarget;
}
function functionBody(source: string, name: string, nextName: string): string {
const start = source.indexOf(`function ${name}`);
const end = source.indexOf(`function ${nextName}`, start + 1);
return start >= 0 && end > start ? source.slice(start, end) : "";
}
describe("DataGrid detail navigation index", () => {
it("follows the supplied displayed order instead of deriving neighboring ids", () => {
const displayedRows = [42, 7, 99];
@@ -89,44 +79,4 @@ describe("DataGrid detail keyboard safety", () => {
expect(shouldIgnoreDataGridDetailNavigation(keyboardEvent({ ctrlKey: true }))).toBe(true);
expect(shouldIgnoreDataGridDetailNavigation(keyboardEvent({ defaultPrevented: true }))).toBe(true);
});
it("wires row and column intents to the displayed DataGrid order", () => {
expect(detailDialogsSource).toContain('@keydown="onRowDetailKeydown"');
expect(detailDialogsSource).toContain('@keydown="onColumnDetailKeydown"');
expect(detailDialogsSource).toContain("shouldIgnoreDataGridDetailNavigation(event)");
expect(detailDialogsSource).toContain('detailNavigationDelta(event.key, "row")');
expect(detailDialogsSource).toContain('detailNavigationDelta(event.key, "column")');
expect(detailDialogsSource).toContain('emit("navigateRow", delta)');
expect(detailDialogsSource).toContain('emit("navigateColumn", delta)');
expect(dataGridSource).toContain('@navigate-row="navigateRowDetail"');
expect(dataGridSource).toContain('@navigate-column="navigateColumnDetail"');
const rowNavigation = functionBody(dataGridSource, "navigateRowDetail", "navigateColumnDetail");
const columnNavigation = functionBody(dataGridSource, "navigateColumnDetail", "openContextRowDetailDialog");
expect(rowNavigation).toContain("displayRowIndexById(rowDetailDialogRowId.value)");
expect(rowNavigation).toContain("displayItemAt(nextRowIndex)");
expect(rowNavigation).not.toMatch(/rowDetailDialogRowId\.value\s*[+-]/);
expect(columnNavigation).toContain("visibleColumnIndexes.value.indexOf(columnDetailDialogColumnIndex.value)");
expect(columnNavigation).toContain("visibleColumnIndexes.value[nextColumnPosition]");
expect(columnNavigation).not.toMatch(/columnDetailDialogColumnIndex\.value\s*[+-]/);
});
it("keeps the dialog open while replacing the detail target and guards closed dialogs", () => {
const rowNavigation = functionBody(dataGridSource, "navigateRowDetail", "navigateColumnDetail");
const columnNavigation = functionBody(dataGridSource, "navigateColumnDetail", "openContextRowDetailDialog");
expect(rowNavigation).toContain("if (!rowDetailDialogOpen.value || rowDetailDialogRowId.value === null) return;");
expect(columnNavigation).toContain("if (!columnDetailDialogOpen.value || columnDetailDialogColumnIndex.value === null) return;");
expect(rowNavigation).not.toContain("rowDetailDialogOpen.value = false");
expect(columnNavigation).not.toContain("columnDetailDialogOpen.value = false");
expect(detailDialogsSource).toContain('const rowSearch = ref("");');
expect(detailDialogsSource).toContain('const columnSearch = ref("");');
});
it("focuses the dialog content on open so arrows work immediately", () => {
expect(detailDialogsSource).toContain('@open-auto-focus="focusDetailDialogContentOnOpen"');
expect(detailDialogsSource).toContain('tabindex="-1"');
expect(detailDialogsSource).toContain("function focusDetailDialogContentOnOpen(event: Event) {");
});
});
@@ -1,79 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
function resultWatchSource(): string {
const start = dataGridSource.indexOf("watch(\n () => props.result,\n (result, previousResult) => {");
const end = dataGridSource.indexOf("// --- Context menu handlers ---");
expect(start).toBeGreaterThanOrEqual(0);
expect(end).toBeGreaterThan(start);
return dataGridSource.slice(start, end);
}
function captureViewportAnchorForRefreshSource(): string {
const start = dataGridSource.indexOf("function captureViewportAnchorForRefresh()");
const end = dataGridSource.indexOf("function restoreViewportAnchorAfterRefresh(");
expect(start).toBeGreaterThanOrEqual(0);
expect(end).toBeGreaterThan(start);
return dataGridSource.slice(start, end);
}
describe("DataGrid result-replacement vertical scroll", () => {
it("resets to the first row when the result is replaced without an internal grid action", () => {
const watchSource = resultWatchSource();
expect(watchSource).toContain("} else if (!inPlaceRefreshPending) {");
const externalBranch = watchSource.slice(watchSource.indexOf("} else if (!inPlaceRefreshPending) {"));
expect(externalBranch.indexOf("resetGridVerticalScroll();")).toBeGreaterThanOrEqual(0);
expect(externalBranch).toContain("#7341");
});
it("keeps the internal-action reset flag path unchanged", () => {
const watchSource = resultWatchSource();
expect(watchSource).toContain("if (getResetScrollAfterResult()) {\n clearResetScrollAfterResult();\n resetGridVerticalScroll();");
});
it("treats any pending prepareFullReload marker as an in-place refresh that keeps the viewport", () => {
const watchSource = resultWatchSource();
expect(watchSource).toContain("preservedSelectionOnNextResult !== null || preservedViewportAnchorOnNextResult !== null || preservedDetailsOnNextResult !== null || preserveTransposeOnNextResult.value");
// The pending-marker check must run before the watch consumes the markers.
const pendingCheck = watchSource.indexOf("const inPlaceRefreshPending =");
const selectionConsume = watchSource.indexOf("preservedSelectionOnNextResult = null;");
const anchorConsume = watchSource.indexOf("preservedViewportAnchorOnNextResult = null;");
const detailsConsume = watchSource.indexOf("preservedDetailsOnNextResult = null;");
const transposeConsume = watchSource.indexOf("preserveTransposeOnNextResult.value = false;");
expect(pendingCheck).toBeGreaterThanOrEqual(0);
for (const consume of [selectionConsume, anchorConsume, detailsConsume, transposeConsume]) {
expect(consume).toBeGreaterThan(pendingCheck);
}
});
it("returns before any scroll reset when the replacement completes an infinite-scroll append", () => {
const watchSource = resultWatchSource();
const appendReturn = watchSource.indexOf("if (appendCompletion) {");
const appendEarlyReturn = watchSource.indexOf("return;\n }");
const resetBranch = watchSource.indexOf("if (getResetScrollAfterResult()) {");
expect(appendReturn).toBeGreaterThanOrEqual(0);
expect(appendEarlyReturn).toBeGreaterThan(appendReturn);
expect(resetBranch).toBeGreaterThan(appendEarlyReturn);
});
it("does not anchor a toolbar refresh to the current top row when already scrolled to the top (#8339)", () => {
// Anchoring the row that happens to be at scrollTop 0 would re-pin it to the
// same on-screen offset after refresh, which pushes newly inserted rows
// (e.g. rows prepended by an external insert under a DESC sort) above the
// visible viewport instead of showing them. Skipping the anchor when already
// at the top lets the toolbar-refresh path land on the freshest first row.
const anchorSource = captureViewportAnchorForRefreshSource();
expect(anchorSource).toContain("#8339");
const guard = anchorSource.indexOf("if (scroller.scrollTop <= 0) return null;");
const rowHeightUse = anchorSource.indexOf("const rowHeight =");
expect(guard).toBeGreaterThanOrEqual(0);
expect(rowHeightUse).toBeGreaterThan(guard);
});
});
@@ -1,7 +1,5 @@
// @vitest-environment happy-dom
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { createApp, defineComponent, h, markRaw, nextTick, type App, type PropType } from "vue";
import { createPinia, setActivePinia } from "pinia";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -29,8 +27,6 @@ vi.mock("@/composables/useDataGridColumnResize", async (importOriginal) => {
import DataGrid from "../DataGrid.vue";
import { useSettingsStore } from "@/stores/settingsStore";
const dataGridSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGrid.vue"), "utf8");
const appSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/App.vue"), "utf8");
const mountedApps: Array<{ app: App; host: HTMLElement }> = [];
const RecycleScroller = defineComponent({
@@ -147,12 +143,6 @@ afterEach(() => {
}
});
function functionBody(name: string, nextName: string): string {
const start = dataGridSource.indexOf(`function ${name}`);
const end = dataGridSource.indexOf(`function ${nextName}`, start + 1);
return start >= 0 && end > start ? dataGridSource.slice(start, end) : "";
}
describe("DataGrid go-to-column shortcut", () => {
it("switches between the split and original single-row toolbar layouts", async () => {
const { host, settingsStore } = mountGrid();
@@ -299,61 +289,4 @@ describe("DataGrid go-to-column shortcut", () => {
expect(bubbled).toHaveBeenCalledOnce();
expect(goToColumnButton(host).getAttribute("aria-expanded")).toBe("false");
});
it("opens the existing popover through the shared grid action", () => {
const keydown = functionBody("onGridKeydown", "copyDetailValue");
expect(dataGridSource).toMatch(/<div\b(?=[^>]*\bdata-grid-root)(?=[^>]*\btabindex="0")(?=[^>]*@keydown="onGridKeydown")[^>]*>/);
expect(keydown).toMatch(
/const targetAllowsNativeClipboard = eventTargetAllowsNativeClipboard\(event\);[\s\S]*?if \(!targetAllowsNativeClipboard && isGoToColumnShortcut\(event, settingsStore\.editorSettings\.shortcuts\) && openGoToColumn\(\)\) \{[\s\S]*?event\.preventDefault\(\);[\s\S]*?event\.stopPropagation\(\);[\s\S]*?return;[\s\S]*?\}/,
);
expect(dataGridSource).toContain("function openGoToColumn(): boolean");
expect(dataGridSource).toContain("if (!displayableColumnIndexes.value.length) return false;");
});
it("keeps editable targets available for the application-level fallback", () => {
const keydown = functionBody("onGridKeydown", "copyDetailValue");
const shortcutStart = keydown.indexOf("if (!targetAllowsNativeClipboard && isGoToColumnShortcut");
const shortcutEnd = keydown.indexOf("if (isFocusSearchShortcut", shortcutStart);
const shortcutBranch = keydown.slice(shortcutStart, shortcutEnd);
expect(shortcutStart).toBeGreaterThan(-1);
expect(shortcutBranch).not.toContain("else");
expect(shortcutBranch.match(/preventDefault/g)).toHaveLength(1);
expect(shortcutBranch.match(/stopPropagation/g)).toHaveLength(1);
});
it("gives the data-tab fallback priority over conflicting global shortcuts", () => {
const keydown = functionBody("onGridKeydown", "copyDetailValue");
expect(keydown).toMatch(/if \(isFocusSearchShortcut\(event\) && !isGoToColumnShortcut\(event, settingsStore\.editorSettings\.shortcuts\)\)/);
expect(appSource).toMatch(
/const shortcuts = settingsStore\.editorSettings\.shortcuts;[\s\S]*?if \(showTabSwitcher\.value\) return;[\s\S]*?if \(isGoToColumnShortcut\(e, shortcuts\) && contentAreaRef\.value\?\.openGoToColumn\(\)\) \{[\s\S]*?return;[\s\S]*?const tabSwitcherDirection = tabSwitcherDirectionFromShortcut\(e, shortcuts\);/,
);
});
it("keeps toolbar navigation and adds keyboard selection to the lookup", () => {
const selectColumn = functionBody("scrollToColumn", "onGoToColumnKeydown");
const escape = functionBody("onGoToColumnKeydown", "matchesTableInfoColumn");
const scroll = functionBody("scrollToColumnIndex", "measureColumnHeaderText");
expect(dataGridSource.match(/<Popover v-model:open="goToColumnOpen">/g)).toHaveLength(1);
expect(dataGridSource).toContain('>{{ t("grid.goToColumn") }}</span');
expect(dataGridSource).toContain('v-model="goToColumnSearch"');
expect(dataGridSource).toContain('ref="goToColumnSearchInput"');
expect(dataGridSource).toContain('ref="goToColumnListRef"');
expect(dataGridSource).toContain("filterDataGridColumnLookupItems(goToColumnItems.value, goToColumnSearch.value)");
expect(dataGridSource).toContain("const goToColumnSelectedIndex = ref(0);");
expect(selectColumn).toContain('goToColumnSearch.value = ""');
expect(selectColumn).toContain("scrollToColumnIndex(columnIndex)");
expect(escape).toMatch(/event\.key === "ArrowDown"[\s\S]*?moveGoToColumnSelection\(1\)/);
expect(escape).toMatch(/event\.key === "ArrowUp"[\s\S]*?moveGoToColumnSelection\(-1\)/);
expect(escape).toMatch(/event\.key === "Enter"[\s\S]*?scrollToColumn\(selected\.index\)/);
expect(escape).toMatch(/event\.key === "Escape"[\s\S]*?goToColumnOpen\.value = false;[\s\S]*?goToColumnSearch\.value = ""/);
expect(scroll).toContain("if (hiddenColumnIndexes.value.has(columnIndex))");
expect(scroll).toContain("showColumn(columnIndex)");
expect(scroll).toContain("highlightedColumnIndex.value = columnIndex");
expect(scroll).toContain("scroller.scrollLeft = targetLeft");
expect(scroll).toContain("updateGridHorizontalViewport(scroller)");
});
});
@@ -1,42 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
function functionSource(name: string, nextName: string): string {
const start = dataGridSource.indexOf(`function ${name}`);
const relativeEnd = dataGridSource.slice(start).search(new RegExp(`\\n(?:async\\s+)?function\\s+${nextName}\\b`));
expect(start).toBeGreaterThanOrEqual(0);
expect(relativeEnd).toBeGreaterThan(0);
const end = start + relativeEnd;
return dataGridSource.slice(start, end);
}
describe("DataGrid infinite-scroll sorting", () => {
it("clears completed and pending infinite-scroll state before database sorting", () => {
const sortSource = functionSource("applyColumnSort", "selectHeaderSort");
const resetSource = functionSource("resetInfiniteScrollState", "onToolbarRefresh");
expect(sortSource).toContain('if (mode === "database" && infiniteScrollEnabled.value) {\n resetInfiniteScrollState();');
expect(resetSource).toContain("lastInfiniteScrollPage = 0;");
expect(resetSource).toContain("infiniteScrollAllLoaded = false;");
expect(resetSource).toContain("infiniteScrollRequestedOffset = undefined;");
expect(resetSource).toContain("infiniteScrollRequestedLimit = undefined;");
expect(resetSource).toContain("isInfiniteScrollPaginating.value = false;");
expect(resetSource).toContain("infiniteScrollLoading.value = false;");
});
it("preserves the existing lightweight reset for local sorting", () => {
const sortSource = functionSource("applyColumnSort", "selectHeaderSort");
expect(sortSource).toContain("} else {\n currentPage.value = 1;\n resetGridVerticalScroll(true);\n }");
expect(sortSource.match(/emit\("sort"/g)).toHaveLength(1);
});
it("does not expose an explicit local sort as a database order for refresh or pagination", () => {
const orderSource = functionSource("currentOrderBy", "executeServerPageJump");
expect(orderSource).toContain('sortMode.value === "database"');
expect(orderSource).toContain("return orderByInput.value.trim() || structuredOrderBy;");
});
});
@@ -1,39 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
describe("DataGrid setup initialization order", () => {
it("initializes table column metadata before column width measurement", () => {
const tableColumnMetadataDeclaration = dataGridSource.indexOf("const tableColumnsByResultIndex = computed");
const columnResizeInitialization = dataGridSource.indexOf("useDataGridColumnResize({");
expect(tableColumnMetadataDeclaration).toBeGreaterThanOrEqual(0);
expect(columnResizeInitialization).toBeGreaterThan(tableColumnMetadataDeclaration);
});
it("initializes column formatters before measuring formatted column widths", () => {
const columnFormatterDeclaration = dataGridSource.indexOf("} = useDataGridColumnFormatter({");
const columnWidthInitialization = dataGridSource.lastIndexOf("initColumnWidths();");
expect(columnFormatterDeclaration).toBeGreaterThanOrEqual(0);
expect(columnWidthInitialization).toBeGreaterThan(columnFormatterDeclaration);
expect(dataGridSource).toContain("columnFormatterForWidth?.(columnIndex)");
});
it("initializes where-search capability before the immediate filter preview watcher", () => {
const canUseWhereSearchDeclaration = dataGridSource.indexOf("const canUseWhereSearch = computed");
const filterPreviewDeclaration = dataGridSource.indexOf("const filterPreviewVisible = computed");
const filterPreviewWatcher = dataGridSource.indexOf("[filterPreviewVisible, structuredFilterRules]");
expect(canUseWhereSearchDeclaration).toBeGreaterThanOrEqual(0);
expect(filterPreviewDeclaration).toBeGreaterThan(canUseWhereSearchDeclaration);
expect(filterPreviewWatcher).toBeGreaterThan(filterPreviewDeclaration);
});
it("does not expose an uninitialized large-value runtime to startup callbacks", () => {
expect(dataGridSource).toContain("let largeValueRuntime: ReturnType<typeof useDataGridLargeValues> | undefined;");
expect(dataGridSource).toContain("largeValueRuntime?.scheduleVisibleLargeValuePreviewHydration(delay)");
expect(dataGridSource).toContain("largeValueRuntime?.hydrateLargeValueCell(rowId, columnIndex) ?? false");
});
});
@@ -1,15 +1,6 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { bulkEditInputToSqlValue, dataGridInlineBulkEditValue } from "@/lib/dataGrid/dataGridInlineBulkEdit";
const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
function functionBody(name: string, nextName: string): string {
const start = dataGridSource.indexOf(`function ${name}`);
const end = dataGridSource.indexOf(`function ${nextName}`, start + 1);
return start >= 0 && end > start ? dataGridSource.slice(start, end) : "";
}
describe("DataGrid inline bulk editing", () => {
it.each([
["1", "1"],
@@ -27,18 +18,6 @@ describe("DataGrid inline bulk editing", () => {
it.each([{ key: "v", ctrlKey: true }, { key: "1", altKey: true }, { key: "删", isComposing: true }, { key: "删", keyCode: 229 }, { key: "Process" }])("ignores shortcut, composition, and control keys: %j", (event) => {
expect(dataGridInlineBulkEditValue(event, 2)).toBeUndefined();
});
it("starts a cell editor instead of opening the bulk edit dialog", () => {
const keydown = functionBody("onGridKeydown", "copyDetailValue");
expect(keydown).toContain("beginInlineBulkEdit(inlineBulkEditValue)");
expect(keydown).not.toContain("openBulkEditDialog");
});
it("commits the inline value to the full selection", () => {
const commit = functionBody("commitInlineBulkEdit", "commitBooleanGridEdit");
expect(commit).toContain("fillSelectionWithValue(nextValue, { emptyStringAsNull: true })");
expect(commit).toContain("cancelEdit()");
});
});
describe("bulkEditInputToSqlValue", () => {
@@ -49,10 +28,4 @@ describe("bulkEditInputToSqlValue", () => {
it.each(["0", "false", "NULLL", "NULLX", "'NULL'", "nulls", "NUL", " 1 "])("keeps non-sentinel input %j as typed", (input) => {
expect(bulkEditInputToSqlValue(input)).toBe(input);
});
it("routes applyBulkEditValue through bulkEditInputToSqlValue for both scopes", () => {
const applyBulkEdit = functionBody("applyBulkEditValue", "confirmConditionalBulkEdit");
expect(applyBulkEdit).toContain("bulkEditInputToSqlValue(bulkEditValue.value)");
expect(applyBulkEdit).not.toContain('bulkEditValue.value === "" ? null');
});
});
@@ -1,30 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
const largeValueSource = readFileSync(new URL("../../../composables/useDataGridLargeValues.ts", import.meta.url), "utf8");
function functionSource(name: string, nextName: string): string {
const start = largeValueSource.indexOf(`function ${name}`);
const relativeEnd = largeValueSource.slice(start).search(new RegExp(`\\n\\s*(?:async\\s+)?function\\s+${nextName}\\b`));
expect(start).toBeGreaterThanOrEqual(0);
expect(relativeEnd).toBeGreaterThan(0);
return largeValueSource.slice(start, start + relativeEnd);
}
describe("DataGrid large-value reload SQL", () => {
it("projects the synthetic rowid through the rowid-wrapped select on full-value reloads", () => {
const fetchChunkSource = functionSource("fetchLargeValueRequestChunk", "resolveLargeValueCells");
// Keyless Oracle tables address rows via the hidden __DBX_ROWID alias; the
// reload must opt into the ROWIDTOCHAR inline view so the generated SQL
// never references __DBX_ROWID as a base-table column (ORA-00904).
expect(fetchChunkSource).toContain("includeRowId: shouldIncludeSyntheticRowId(options.databaseType.value, tableMeta.primaryKeys, tableMeta.tableType)");
});
it("keeps the visible-preview hydration consistent with the synthetic key", () => {
const hydrateSource = functionSource("hydrateVisibleLargeValuePreviews", "runVisibleLargeValuePreviewHydration");
expect(hydrateSource).toContain("includeRowId: shouldIncludeSyntheticRowId(options.databaseType.value, tableMeta.primaryKeys, tableMeta.tableType)");
});
});
@@ -1,23 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
function functionSource(name: string, nextName: string): string {
const start = dataGridSource.indexOf(`function ${name}`);
const relativeEnd = dataGridSource.slice(start).search(new RegExp(`\\n(?:async\\s+)?function\\s+${nextName}\\b`));
expect(start).toBeGreaterThanOrEqual(0);
expect(relativeEnd).toBeGreaterThan(0);
return dataGridSource.slice(start, start + relativeEnd);
}
describe("DataGrid large-value replacement", () => {
it("counts preview matches and resolves full values before staging replacements", () => {
const eligibilitySource = functionSource("canReplaceGridCell", "replacementCellInScope");
const replaceSource = functionSource("replaceGridMatches", "fillSelectionWithValue");
expect(eligibilitySource).not.toContain("!isLargeValuePreview");
expect(replaceSource).toContain("await prepareDataGridCellReplacements");
expect(replaceSource).toContain("resolveLargeValueCells");
});
});
@@ -1,7 +1,5 @@
// @vitest-environment happy-dom
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { createApp, defineComponent, h, markRaw, nextTick, type App, type PropType } from "vue";
import { createPinia, setActivePinia } from "pinia";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -30,7 +28,6 @@ vi.mock("@/composables/useDataGridColumnResize", async (importOriginal) => {
import DataGrid from "../DataGrid.vue";
import { useSettingsStore } from "@/stores/settingsStore";
const dataGridSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGrid.vue"), "utf8");
const mountedApps: Array<{ app: App; host: HTMLElement }> = [];
const shortcutCases = [
{ actionId: "goToFirstPage", key: "F1", offset: 0, functionName: "firstPage" },
@@ -300,16 +297,6 @@ describe("DataGrid pagination shortcuts", () => {
expect(paginate).not.toHaveBeenCalled();
});
it("routes shortcuts to the existing pagination functions and preserves PageUp/PageDown navigation", () => {
expect(dataGridSource).toMatch(/if \(!targetAllowsNativeClipboard && handleGridPaginationShortcut\(event\)\) return;/);
for (const { actionId, functionName } of shortcutCases) {
expect(dataGridSource).toContain(`is${actionId[0]!.toUpperCase()}${actionId.slice(1)}Shortcut(event, shortcuts)`);
expect(dataGridSource).toContain(`navigate = ${functionName}`);
}
expect(dataGridSource).toContain('event.key === "PageUp" && navigateSelectedCell("pageUp", event.shiftKey)');
expect(dataGridSource).toContain('event.key === "PageDown" && navigateSelectedCell("pageDown", event.shiftKey)');
});
it("keeps legacy settings without pagination mappings keyboard-neutral", async () => {
const { host, paginate } = mountGrid({ configurePaginationShortcuts: false });
await settle();
@@ -1,13 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
describe("DataGrid pending row visibility under local column filters", () => {
it("keeps pending new rows visible while a local column filter is active", () => {
// The pending-row branch of displayRowRefs must not consult the local
// column filter matchers; only the row status filter applies (#9201).
expect(dataGridSource).toMatch(/const row = newRows\.value\[newIndex\];[\s\S]{0,200}?if \(!row\) continue;/);
expect(dataGridSource).not.toContain("!rowMatchesLocalColumnFilters(row)");
});
});
@@ -1,13 +1,10 @@
// @vitest-environment happy-dom
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { createApp, nextTick } from "vue";
import { afterEach, describe, expect, it, vi } from "vitest";
import DataGridReadonlyTextSelection from "../DataGridReadonlyTextSelection.vue";
const mountedRoots: HTMLDivElement[] = [];
const dataGridSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/grid/DataGrid.vue"), "utf8");
function mountSelection(options: { value?: string; expanded?: boolean } = {}) {
const root = document.createElement("div");
@@ -30,14 +27,6 @@ afterEach(() => {
});
describe("DataGridReadonlyTextSelection", () => {
it("closes a stale read-only selection when a result is replaced", () => {
const resultWatcher = dataGridSource.match(/watch\(\s*\(\) => props\.result,\s*\(result, previousResult\) => \{[\s\S]*?\n\);/)?.[0] ?? "";
expect(resultWatcher).toContain("const appendCompletion = dataGridInfiniteScrollAppendCompletion(previousResult, result");
expect(resultWatcher).toContain("if (appendCompletion) {");
expect(resultWatcher).toContain("closeReadonlyCellTextSelection();");
});
it("focuses and selects the complete read-only value on mount", async () => {
const { root } = mountSelection();
await nextTick();
@@ -1,48 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
function functionSource(name: string, nextName: string): string {
const start = dataGridSource.indexOf(`function ${name}`);
const relativeEnd = dataGridSource.slice(start).search(new RegExp(`\\n(?:async\\s+)?function\\s+${nextName}\\b`));
expect(start).toBeGreaterThanOrEqual(0);
expect(relativeEnd).toBeGreaterThan(0);
return dataGridSource.slice(start, start + relativeEnd);
}
describe("DataGrid save reload integration", () => {
it("shares the toolbar full-reload preparation with editor saves", () => {
const prepareSource = functionSource("prepareFullReload", "onToolbarRefresh");
const toolbarSource = functionSource("onToolbarRefresh", "setAutoRefreshInterval");
const rollbackSource = functionSource("onToolbarRollback", "addRow");
expect(dataGridSource).toContain("prepareFullReload,\n emit,");
expect(dataGridSource).toContain("refreshSavedRows,\n onCellValueChanged");
expect(toolbarSource).toContain("prepareFullReload();");
expect(rollbackSource).toContain("prepareFullReload();");
expect(toolbarSource).toContain("const resetToFirstPage = hasPendingConditionInputs();");
expect(toolbarSource).toContain("resetToFirstPage ? 0 : (currentPage.value - 1) * pageSize.value");
expect(prepareSource).toContain("resetInfiniteScrollState();");
expect(prepareSource).toContain("captureViewportAnchorForRefresh();");
expect(prepareSource).toContain("preservedViewportAnchorOnNextResult = viewportAnchor ? { anchor: viewportAnchor, sourceResult: props.result } : null;");
expect(prepareSource).toContain("captureCurrentSelectionForRefresh();");
expect(prepareSource).toContain("preservedSelectionOnNextResult = selection ? { selection, sourceResult: props.result } : null;");
expect(prepareSource).toContain("preservedDetailsOnNextResult = captureDetailsForRefresh();");
expect(prepareSource).toContain("preserveTransposeOnNextResult.value = showTranspose.value;");
expect(dataGridSource).toContain("if (detailsSnapshot) restoreDetailsAfterRefresh(detailsSnapshot);");
expect(dataGridSource).toContain("if (viewportAnchorSnapshot) restoreViewportAnchorAfterRefresh(viewportAnchorSnapshot);");
});
it("resets accumulated infinite-scroll pagination before reloading from offset zero", () => {
const resetSource = functionSource("resetInfiniteScrollState", "prepareFullReload");
const nextPageSource = functionSource("infiniteScrollNextPage", "checkInfiniteScroll");
expect(resetSource).toContain("currentPage.value = 1;");
expect(resetSource).toContain("lastInfiniteScrollPage = 0;");
expect(resetSource).toContain("infiniteScrollRequestedOffset = undefined;");
expect(resetSource).toContain("infiniteScrollRequestedLimit = undefined;");
expect(nextPageSource).toContain("const nextOffset = props.result.rows.length;");
expect(nextPageSource).toContain('emit("paginate", nextOffset, nextLimit, currentWhereInput(), currentOrderBy());');
});
});
@@ -1,20 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const source = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
describe("DataGrid selection gesture ownership", () => {
it("stops released gestures before DOM hover or canvas movement extends them", () => {
expect(source).toContain("function stopReleasedSelectionGesture(event: MouseEvent)");
expect(source).toContain("if ((event.buttons & 1) !== 0) return false;");
expect(source).toContain("function onCellMouseenter(rowIndex: number, visibleColIdx: number, actualColIdx: number, event: MouseEvent)");
expect(source).toContain('@mouseenter="onCellMouseenter(item.displayIndex, col.visibleColIdx, col.actualColIdx, $event)"');
const canvasMove = source.slice(source.indexOf("function onCanvasMouseMove"), source.indexOf("function onCanvasMouseLeave"));
expect(canvasMove).toContain("stopReleasedSelectionGesture(event);");
});
it("only exposes cell snapshots for selections with a rectangular matrix", () => {
expect(source).toMatch(/contextCell\.value && hasCellSelection\.value && selectedCellMatrix\.value\s*\n?\s*\?\s*"cells"/);
});
});
@@ -115,13 +115,9 @@ import DataGridPagination from "@/components/grid/DataGridPagination.vue";
import DataGridQueryControls from "@/components/grid/DataGridQueryControls.vue";
import DataGridSearchBar from "@/components/grid/DataGridSearchBar.vue";
const dataGridSource = readFileSync("apps/desktop/src/components/grid/DataGrid.vue", "utf8");
const dataGridCellDetailEditSource = readFileSync("apps/desktop/src/composables/useDataGridCellDetailEdit.ts", "utf8");
const cellDetailPanelSource = readFileSync("apps/desktop/src/components/grid/DataGridCellDetailPanel.vue", "utf8");
const cellDetailDialogSource = readFileSync("apps/desktop/src/components/grid/DataGridCellDetailDialog.vue", "utf8");
const binaryTextPreviewSource = readFileSync("apps/desktop/src/components/grid/DataGridCellDetailTextPreview.vue", "utf8");
const cellDetailHeaderSource = readFileSync("apps/desktop/src/components/grid/DataGridCellDetailHeader.vue", "utf8");
const globalsCss = readFileSync("apps/desktop/src/styles/globals.css", "utf8");
function detail(patch: Partial<DataGridCellDetail> = {}): DataGridCellDetail {
return {
@@ -154,55 +150,6 @@ beforeEach(() => {
vi.clearAllMocks();
localStorage.removeItem("dbx-filter-builder-value-shortcut-hint-days");
});
describe("DataGrid canvas surfaces", () => {
it("keeps condition and text filter editors open when persistent expansion is enabled", () => {
expect(dataGridSource).toContain('const isPersistentFilterView = computed(() => filterEditorView.value === "conditions" || filterEditorView.value === "text");');
expect(dataGridSource).toContain("const isFilterEditorPinnedOpen = computed(() => isPersistentFilterView.value && settingsStore.editorSettings.dataGridKeepFilterEditorExpanded);");
expect(dataGridSource).toContain("get: () => isFilterEditorPinnedOpen.value || filterBuilderOpen.value,");
expect(dataGridSource).toContain("if (!isFilterEditorPinnedOpen.value) filterBuilderOpen.value = false;");
expect(dataGridSource).toContain('v-model:filter-builder-open="effectiveFilterBuilderOpen"');
expect(dataGridSource).toContain("filterEditorView === 'conditions' && effectiveFilterBuilderOpen");
expect(dataGridSource).toContain("filterEditorView === 'text' && effectiveFilterBuilderOpen");
});
it("asks before an expensive Elasticsearch cursor jump", () => {
expect(dataGridSource).toContain("requestCount >= ELASTICSEARCH_PAGE_JUMP_WARNING_REQUESTS");
expect(dataGridSource).toContain('t("grid.esDeepPageJumpConfirmMessage"');
expect(dataGridSource).toContain('@click="confirmEsDeepPageJump"');
});
it("shows stable request progress while an Elasticsearch page jump is running", () => {
expect(dataGridSource).toContain('t("grid.pageJumpLoading", { page: pageJumpProgress.targetPage })');
expect(dataGridSource).toContain('t("grid.pageJumpProgress", { current: pageJumpProgress.completedRequests, total: pageJumpProgress.totalRequests })');
expect(dataGridSource).toContain('role="progressbar"');
expect(dataGridSource).toContain(':style="{ width: `${pageJumpProgressPercent}%` }"');
});
it("uses the stable overlay for viewport and device-pixel measurement", () => {
expect(dataGridSource).toContain("function canvasMeasurementSurface(): HTMLElement | null");
expect(dataGridSource).toContain("return canvasOverlayRef.value ?? null;");
expect(dataGridSource).toContain("const measurementSurface = canvasMeasurementSurface();");
expect(dataGridSource).toContain("getSurface: canvasMeasurementSurface,");
expect(dataGridSource).toContain("const canvas = inactiveCanvasSurface();");
expect(dataGridSource).toContain("canvasUsingBackSurface.value = !canvasUsingBackSurface.value;");
});
it("uses the canvas that actually received the event during a surface flip", () => {
expect(dataGridSource).toContain("function canvasEventSurface(event: MouseEvent): HTMLCanvasElement | null");
expect(dataGridSource).toContain("const currentTarget = event.currentTarget;");
expect(dataGridSource).toContain("return currentTarget instanceof HTMLCanvasElement ? currentTarget : activeCanvasSurface();");
expect(dataGridSource).toContain("const canvas = canvasEventSurface(event);");
const canvasMouseMove = dataGridSource.slice(dataGridSource.indexOf("function onCanvasMouseMove"), dataGridSource.indexOf("function onCanvasMouseLeave"));
expect(canvasMouseMove).toContain("const cursorSurface = canvasEventSurface(event);");
});
it("handles double clicks on the stable canvas container", () => {
expect(dataGridSource).toContain('@dblclick="onCanvasDblClick"');
expect(dataGridSource.match(/@dblclick="onCanvasDblClick"/g)).toHaveLength(1);
expect(dataGridSource).toContain("@dblclick.stop");
});
});
describe("DataGridSearchBar", () => {
it("focuses/selects the input and forwards keyboard, navigation, and suggestion interactions", async () => {
@@ -258,18 +205,6 @@ describe("DataGridSearchBar", () => {
});
describe("DataGridPagination", () => {
it("keeps drag summaries count-only and wires the derived average without materializing selected cells", () => {
const summaryStart = dataGridSource.indexOf("const selectionSummary = computed");
const pendingSummary = dataGridSource.indexOf("createPendingSelectionSummary(selectedCellCount.value, multiRowCount.value)", summaryStart);
const materializedSummary = dataGridSource.indexOf("summarizeSelection(selectedCells.value)", summaryStart);
expect(summaryStart).toBeGreaterThan(-1);
expect(pendingSummary).toBeGreaterThan(summaryStart);
expect(materializedSummary).toBeGreaterThan(pendingSummary);
expect(dataGridSource).toContain('const selectionSummaryAverageText = computed(() => {\n if (isSelectingCells.value) return "…";');
expect(dataGridSource).toContain(':selection-summary-average-text="selectionSummaryAverageText"');
});
it("shows average beside the existing selection summary values", () => {
const mounted = mountComponent(DataGridPagination, {
selectionSummary: { cellCount: 4, rowCount: 2 },
@@ -507,8 +442,6 @@ describe("DataGridColumnHeader", () => {
expect(String(tooltipType.props.class ?? "")).toContain("data-grid-type-string");
const headerTypeLine = findOne(mounted.root, (node) => hostText(node) === "varchar(255)" && node.props["data-grid-header-type-line"] === "");
expect(String(headerTypeLine.props.class)).toContain("data-grid-type-string");
// Softer dark-mode palette override for the tooltip container.
expect(globalsCss).toMatch(/\.dark \.dbx-column-info-tooltip \{[^}]*--data-grid-type-string-fg: #4ade80/);
});
it("cancels resize-handle clicks without leaking header click events", () => {
@@ -1423,38 +1356,6 @@ describe("DataGridTextFilterWorkbench", () => {
});
describe("cell detail surfaces", () => {
it("keeps detail tabs and editor actions usable when the panel narrows", () => {
const tabsHeader = cellDetailHeaderSource;
const tabViewport = tabsHeader.match(/<div class="([^"]*overflow-x-auto[^"]*)">\s*<TabsList/);
const tabList = tabsHeader.match(/<TabsList class="([^"]+)">/);
const triggerClasses = Array.from(tabsHeader.matchAll(/<TabsTrigger\b[^>]*class="([^"]+)"/g), ([, classes]) => classes.split(/\s+/));
expect(tabViewport?.[1]?.split(/\s+/)).toEqual(expect.arrayContaining(["min-w-0", "flex-1", "overflow-x-auto"]));
expect(tabList?.[1]?.split(/\s+/)).toEqual(expect.arrayContaining(["flex", "w-max", "min-w-full"]));
expect(triggerClasses).toHaveLength(3);
for (const classes of triggerClasses) {
expect(classes).toEqual(expect.arrayContaining(["min-w-max", "flex-1", "shrink-0"]));
}
expect(dataGridSource).not.toContain("activeCellDetailTabsGridClass");
const valueEditorLifecycleStart = dataGridSource.indexOf("watch(valueEditorContainer");
const valueEditorLifecycleEnd = dataGridSource.indexOf("const detailEdit = useDataGridCellDetailEdit", valueEditorLifecycleStart);
const valueEditorLifecycle = dataGridSource.slice(valueEditorLifecycleStart, valueEditorLifecycleEnd);
expect(valueEditorLifecycle).toContain("const editor = valueDetailEditor;");
expect(valueEditorLifecycle).toContain("if (valueDetailEditor !== editor) return;");
expect(valueEditorLifecycle).toContain("if (editor.getValue() !== detailEditValue.value)");
expect(valueEditorLifecycle).toContain("editor.setValue(detailEditValue.value, activeCellDetail.value?.type);");
const valueEditorStart = dataGridSource.indexOf("<TabsContent v-if=\"activeCellDetailTabs.includes('valueEditor')\"");
const valueEditorEnd = dataGridSource.indexOf("</TabsContent>", valueEditorStart);
const valueEditor = dataGridSource.slice(valueEditorStart, valueEditorEnd);
expect(valueEditor).toMatch(/<TabsContent[^>]*class="[^"]*\bmin-w-0\b[^"]*">/);
expect(valueEditor).toMatch(/<div class="[^"]*\bmin-w-0\b[^"]*\bflex-wrap\b[^"]*">/);
expect(cellDetailPanelSource).toMatch(/<TabsContent value="details" class="[^"]*\bmin-w-0\b[^"]*">/);
expect(cellDetailPanelSource).toMatch(/<div class="[^"]*\bmin-w-0\b[^"]*\bflex-wrap\b[^"]*">/);
});
it("presents printable LONG BLOB bytes as text and copies the presented value", async () => {
const copyText = vi.fn();
const blobDetail = detail({
@@ -1857,14 +1758,6 @@ describe("cell detail surfaces", () => {
expect(compareJson).toHaveBeenCalledOnce();
});
it("snapshots comparison values before opening and suppresses modal-induced blur commits", () => {
expect(dataGridCellDetailEditSource).toContain("detailValueDiffSnapshot.value = snapshot;");
expect(dataGridCellDetailEditSource).toContain("detailValueDiffOpen.value = true;");
expect(dataGridSource).toContain("if (!detailValueDiffOpen.value && !detailTransformOpen.value) commitValueEditorEdit();");
expect(dataGridSource).toContain(':disabled="!canCompareDetailJson" @mousedown.prevent @click="openDetailJsonCompare"');
expect(dataGridSource).toContain('v-model:open="detailValueDiffOpen" :snapshot="detailValueDiffSnapshot"');
});
// issue #9832:编辑中点「压缩 JSON」会把草稿压成单行,此时必须仍能点「格式化 JSON」
// 重新展开,否则 Mongo 这类对象字段的 JSON 一旦压缩就再也无法格式化。
it("keeps the JSON format action reachable while a compacted draft is being edited", async () => {
@@ -1,119 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const dataGridSource = readFileSync(new URL("../DataGrid.vue", import.meta.url), "utf8");
function functionSource(name: string, endMarker: string): string {
const start = dataGridSource.indexOf(`function ${name}(`);
const end = dataGridSource.indexOf(endMarker, start + 1);
expect(start).toBeGreaterThanOrEqual(0);
expect(end).toBeGreaterThan(start);
return dataGridSource.slice(start, end);
}
describe("DataGrid tab-switch view snapshots", () => {
const captureSource = functionSource("captureViewSelection", "function captureTabSwitchViewSnapshot(");
const captureFnSource = functionSource("captureTabSwitchViewSnapshot", "function restoreTabSwitchViewSnapshot(");
const restoreSource = functionSource("restoreTabSwitchViewSnapshot", "const multiRowCount = computed(");
it("captures only with an owner key and a generation, and skips transpose", () => {
expect(captureFnSource).toContain("if (!ownerKey || !props.viewGeneration) return;");
expect(captureFnSource).toContain("if (showTranspose.value) return;");
expect(captureFnSource).toContain("ownerKey,");
expect(captureFnSource).toContain("viewGeneration: props.viewGeneration");
expect(captureFnSource).toContain("probe: currentViewProbe()");
});
it("takes the snapshot owner from viewStateKey, falling back to cacheKey", () => {
// Document tabs need their own owner key: cacheKey also scopes structured
// filters, column widths and pending edits, which they leave untouched.
expect(dataGridSource).toContain("const viewSnapshotOwnerKey = computed(() => props.viewStateKey?.trim() || props.cacheKey?.trim() || undefined);");
expect(captureFnSource).toContain("const ownerKey = viewSnapshotOwnerKey.value;");
expect(restoreSource).toContain("const ownerKey = viewSnapshotOwnerKey.value;");
});
it("captures the selection in O(selection size), never through the refresh identity scan", () => {
// Copies refs directly instead of captureCurrentSelectionForRefresh, which
// builds an identity token for every row (O(row count) on a large result).
expect(captureFnSource).not.toContain("captureCurrentSelectionForRefresh");
// Contiguous/all row selections serialize as a compact range instead of one
// id per row, and the range helpers iterate only the selected ids via the
// O(1) display index lookup — never the full displayItems.
expect(captureSource).toContain("selectedRowCount === displayCount");
expect(captureSource).toContain("selectedRowsContiguous(selectedRowIds.value)");
expect(captureSource).toContain('kind: "all"');
expect(captureSource).toContain("clampDataGridViewSelection(");
const contiguousHelper = dataGridSource.slice(dataGridSource.indexOf("function selectedRowsContiguous("), dataGridSource.indexOf("function minimalRowRange("));
expect(contiguousHelper).toContain("displayRowIndexById(rowId)");
expect(contiguousHelper).toContain("max - min + 1 === count");
expect(contiguousHelper).not.toContain("displayItems");
});
it("gates every restore on identity, renderer, and probe", () => {
expect(restoreSource).toContain("if (!structuredFilterHydrationReady.value) return;");
expect(restoreSource).toContain("if (snapshot.viewGeneration !== props.viewGeneration) return;");
expect(restoreSource).toContain('if (snapshot.renderer !== (useCanvasGridRows.value ? "canvas" : "dom")) return;');
expect(restoreSource).toContain("if (snapshot.probe !== currentViewProbe()) return;");
expect(restoreSource).toContain("if (showTranspose.value) return;");
});
it("applies the index-based selection directly without scrolling it into view", () => {
expect(restoreSource).toContain("restoreCellSelectionState({ cellKeys: new Set(capturedSelection.cellKeys) })");
expect(restoreSource).toContain('selectedRowIds.value = new Set(indexes.map((index) => displayItems.value[index]?.id).filter((id): id is number => typeof id === "number"));');
expect(restoreSource).toContain("selectedColumnIndexes.value = new Set(capturedSelection.columnIndexes);");
expect(restoreSource).toContain("selectedRowIds.value = new Set(displayItems.value.map((item) => item.id));");
expect(restoreSource).toContain("selection.lastClickedRowIndex.value = capturedSelection.anchorRowIndex;");
expect(restoreSource).not.toContain("restoreSelectionAfterRefresh(snapshot");
});
it("clamps the restored viewport and consumes the snapshot after success", () => {
expect(restoreSource).toContain("Math.min(Math.max(0, snapshot.viewport.top), maxTop)");
expect(restoreSource).toContain("Math.min(Math.max(0, snapshot.viewport.left), maxLeft)");
// A replayed snapshot is consumed so a later remount cannot re-apply it.
expect(restoreSource).toContain("consumeDataGridViewSnapshot(ownerKey);");
});
it("settles the viewport over a bounded retry envelope instead of a fixed two frames", () => {
// Immediate attempt, then nextTick, then at most 8 rAFs — mirroring
// restoreScrollAcrossFrames. A fixed two-frame assumption intermittently
// clamps the saved position to the top before virtualization measures.
expect(restoreSource).toContain("if (attempt()) return;");
expect(restoreSource).toContain("nextTick(() => {");
expect(restoreSource).toContain("frames >= MAX_VIEW_SNAPSHOT_RESTORE_FRAMES");
expect(restoreSource).toContain("viewSnapshotRestoreFrame = requestAnimationFrame(onFrame);");
// An unmeasured scroller clamps the target to 0; that must not count as a
// finished restore, or the saved position is lost at the top.
expect(restoreSource).toContain("const roomForSavedTop = maxTop >= snapshot.viewport.top;");
expect(restoreSource).toContain("return accepted && (snapshot.viewport.top === 0 || (roomForSavedTop && stable));");
expect(dataGridSource).toContain("const MAX_VIEW_SNAPSHOT_RESTORE_FRAMES = 8;");
});
it("honours the rollback switch in both directions", () => {
expect(captureFnSource).toContain("if (!DATA_GRID_VIEW_SNAPSHOT_RESTORE) return;");
expect(restoreSource).toContain("if (!DATA_GRID_VIEW_SNAPSHOT_RESTORE) return;");
expect(dataGridSource).toContain("cancelViewSnapshotRestoreFrame();");
});
it("wires capture to unmount and to the pre-tab-switch event", () => {
expect(dataGridSource).toContain('window.addEventListener("dbx:before-tab-switch", captureTabSwitchViewSnapshot)');
expect(dataGridSource).toContain('window.removeEventListener("dbx:before-tab-switch", captureTabSwitchViewSnapshot)');
expect(dataGridSource).toContain("onUnmounted(() => {\n // Capture before teardown");
expect(dataGridSource).toContain("captureTabSwitchViewSnapshot();");
});
it("reports a dropped selection only after a successful restore", () => {
// The capture must not toast while the user is leaving the tab.
expect(captureFnSource).not.toContain("toast(");
expect(restoreSource).toContain("snapshot.selectionDropped && shouldNotifyOverBudgetSelection(ownerKey");
expect(restoreSource).toContain('toast(t("grid.viewSnapshotSelectionNotRestored")');
// The notice stays one-shot per owner+generation.
expect(dataGridSource).toContain("shouldNotifyOverBudgetSelection(ownerKey, props.viewGeneration!)");
});
it("retries after asynchronous structured-filter hydration", () => {
expect(dataGridSource).toContain("structuredFilterHydrationReady.value = false;");
expect(dataGridSource).toContain("structuredFilterHydrationReady.value = true;");
expect(dataGridSource).toContain("nextTick(restoreTabSwitchViewSnapshot);");
expect(dataGridSource).toContain("structuredFilterHydrationRequestId");
});
});
@@ -1,7 +1,5 @@
// @vitest-environment happy-dom
import { readFileSync } from "node:fs";
import path from "node:path";
import { createApp, nextTick, type App } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import i18n from "@/i18n";
@@ -41,8 +39,6 @@ vi.mock("@/components/ui/button", async () => {
import DataGridColumnLayoutPopover from "../DataGridColumnLayoutPopover.vue";
const contentAreaSource = readFileSync(path.resolve(process.cwd(), "apps/desktop/src/components/layout/ContentArea.vue"), "utf8");
const mountedApps: Array<{ app: App; host: HTMLElement }> = [];
function columnLayoutOptions(itemCount: number): DataGridColumnLayoutOption[] {
@@ -175,8 +171,6 @@ afterEach(() => {
describe("data grid column layout popover", () => {
it("is available from the query result toolbar and keeps a labelled compact trigger", async () => {
expect(contentAreaSource).toContain('<DataGridColumnLayoutPopover :grid="dataGridRef" :compact="compact" />');
const gridState = createGrid(4);
const host = document.createElement("div");
document.body.append(host);