feat(grid): decompose data grid interaction surfaces

This commit is contained in:
t8y2 committed 2026-07-16 14:00:02 +08:00
1 parent 71497f0851
commit 8825b6335f
56 files changed
+6446 -4051

No files matched your search

@@ -0,0 +1,31 @@
import { effectScope, nextTick, ref } from "vue";
import { describe, expect, it } from "vitest";
import { useDataGridAsyncSurface } from "@/composables/useDataGridAsyncSurface";
describe("useDataGridAsyncSurface", () => {
it("defers mounting until first open and keeps the surface mounted afterward", async () => {
const open = ref(false);
const scope = effectScope();
const mounted = scope.run(() => useDataGridAsyncSurface(open))!;
expect(mounted.value).toBe(false);
open.value = true;
await nextTick();
expect(mounted.value).toBe(true);
open.value = false;
await nextTick();
expect(mounted.value).toBe(true);
scope.stop();
});
it("mounts immediately when restored with an already-open surface", () => {
const scope = effectScope();
const mounted = scope.run(() => useDataGridAsyncSurface(ref(true)))!;
expect(mounted.value).toBe(true);
scope.stop();
});
});
@@ -0,0 +1,32 @@
import { computed, nextTick } from "vue";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useDataGridAutoRefresh } from "@/composables/useDataGridAutoRefresh";
describe("useDataGridAutoRefresh", () => {
afterEach(() => vi.useRealTimers());
it("refreshes on the configured interval when enabled", async () => {
vi.useFakeTimers();
const refresh = vi.fn();
const autoRefresh = useDataGridAutoRefresh({ canRefresh: computed(() => true), refresh, initialIntervalSeconds: 5 });
autoRefresh.toggle();
vi.advanceTimersByTime(5000);
await nextTick();
expect(refresh).toHaveBeenCalledOnce();
autoRefresh.stop();
});
it("does not refresh while the operation is unavailable", () => {
vi.useFakeTimers();
const refresh = vi.fn();
const autoRefresh = useDataGridAutoRefresh({ canRefresh: computed(() => false), refresh, initialIntervalSeconds: 1 });
autoRefresh.toggle();
vi.advanceTimersByTime(1000);
expect(refresh).not.toHaveBeenCalled();
autoRefresh.stop();
});
});
@@ -0,0 +1,160 @@
import { effectScope } from "vue";
import { describe, expect, it, vi } from "vitest";
import { useDataGridCanvasRuntime, type DataGridAnimationFrameDriver } from "@/composables/useDataGridCanvasRuntime";
import { useDataGridScrollbars } from "@/composables/useDataGridScrollbars";
function createFrameDriver() {
let nextId = 0;
const callbacks = new Map<number, FrameRequestCallback>();
const driver: DataGridAnimationFrameDriver = {
request(callback) {
const id = nextId++;
callbacks.set(id, callback);
return id;
},
cancel(id) {
callbacks.delete(id);
},
};
return { driver, callbacks, run: (id: number) => callbacks.get(id)?.(0) };
}
function createObserver() {
const observe = vi.fn();
const disconnect = vi.fn();
return { observer: { observe, disconnect } as unknown as ResizeObserver, observe, disconnect };
}
describe("data grid visual runtimes", () => {
it("coalesces canvas frames and cancels all resources on dispose", () => {
const frames = createFrameDriver();
const resize = createObserver();
const draw = vi.fn();
const viewport = { children: [] } as unknown as Element;
const runtime = useDataGridCanvasRuntime({
draw,
syncViewport: vi.fn(),
getViewport: () => viewport,
refreshPixelRatio: vi.fn(),
frameDriver: frames.driver,
createResizeObserver: () => resize.observer,
});
runtime.observeViewport();
runtime.scheduleDraw();
runtime.scheduleDraw();
runtime.schedulePixelRatioRefresh();
expect(frames.callbacks.size).toBe(2);
runtime.dispose();
expect(frames.callbacks.size).toBe(0);
expect(resize.disconnect).toHaveBeenCalledOnce();
expect(draw).not.toHaveBeenCalled();
});
it("keeps a large scroll burst within one scheduled draw frame", () => {
const frames = createFrameDriver();
const draw = vi.fn();
const runtime = useDataGridCanvasRuntime({
draw,
syncViewport: vi.fn(),
getViewport: () => ({ children: [] }) as unknown as Element,
frameDriver: frames.driver,
});
for (let index = 0; index < 10_000; index++) runtime.scheduleDraw();
expect(frames.callbacks.size).toBe(1);
const frameId = [...frames.callbacks.keys()][0];
frames.run(frameId);
expect(draw).toHaveBeenCalledOnce();
runtime.dispose();
});
it("keeps the latest drag coordinate and disconnects observed scroll content", () => {
const frames = createFrameDriver();
const resize = createObserver();
const horizontalDrag = vi.fn();
const child = { children: [] } as unknown as Element;
const scroller = { children: [child] } as unknown as Element;
const runtime = useDataGridScrollbars({
update: vi.fn(),
getScroller: () => scroller,
applyHorizontalDrag: horizontalDrag,
applyVerticalDrag: vi.fn(),
frameDriver: frames.driver,
createResizeObserver: () => resize.observer,
});
runtime.observeScroller();
runtime.scheduleHorizontalDrag(10);
runtime.scheduleHorizontalDrag(25);
runtime.flushHorizontalDrag();
expect(horizontalDrag).toHaveBeenCalledWith(25);
expect(resize.observe).toHaveBeenCalledTimes(2);
runtime.dispose();
expect(resize.disconnect).toHaveBeenCalledOnce();
expect(frames.callbacks.size).toBe(0);
});
it("tears down pending canvas work when its Vue scope stops", () => {
const frames = createFrameDriver();
const resize = createObserver();
const draw = vi.fn();
const syncViewport = vi.fn();
const scope = effectScope();
const runtime = scope.run(() =>
useDataGridCanvasRuntime({
draw,
syncViewport,
getViewport: () => ({ children: [] }) as unknown as Element,
frameDriver: frames.driver,
createResizeObserver: () => resize.observer,
}),
)!;
runtime.observeViewport();
runtime.scheduleDraw();
const lateDraw = [...frames.callbacks.values()][0];
scope.stop();
expect(runtime.disposed).toBe(true);
expect(runtime.active).toBe(false);
expect(frames.callbacks.size).toBe(0);
expect(resize.disconnect).toHaveBeenCalledOnce();
lateDraw(0);
expect(draw).not.toHaveBeenCalled();
expect(syncViewport).toHaveBeenCalledOnce();
});
it("does not revive scroll work after disposal", () => {
const frames = createFrameDriver();
const resize = createObserver();
const update = vi.fn();
const verticalDrag = vi.fn();
const runtime = useDataGridScrollbars({
update,
getScroller: () => ({ children: [] }) as unknown as Element,
applyHorizontalDrag: vi.fn(),
applyVerticalDrag: verticalDrag,
frameDriver: frames.driver,
createResizeObserver: () => resize.observer,
});
runtime.observeScroller();
runtime.scheduleVerticalDrag(42);
const lateCallbacks = [...frames.callbacks.values()];
runtime.dispose();
runtime.resume();
runtime.scheduleUpdate();
runtime.flushVerticalDrag();
lateCallbacks.forEach((callback) => callback(0));
expect(runtime.disposed).toBe(true);
expect(runtime.active).toBe(false);
expect(frames.callbacks.size).toBe(0);
expect(update).not.toHaveBeenCalled();
expect(verticalDrag).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,141 @@
// @vitest-environment happy-dom
import { effectScope, ref } from "vue";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { dataGridColumnOffsets, dataGridHorizontalColumnWindow, useDataGridColumnLayout, useDataGridColumnLayoutState } from "@/composables/useDataGridColumnLayout";
describe("useDataGridColumnLayout", () => {
beforeEach(() => localStorage.clear());
it("builds cumulative offsets", () => {
expect(dataGridColumnOffsets([80, 120, 60])).toEqual([0, 80, 200, 260]);
});
it("windows columns while preserving spacer widths", () => {
const widths = [100, 100, 100, 100, 100];
const offsets = dataGridColumnOffsets(widths);
expect(dataGridHorizontalColumnWindow({ widths, offsets, columnCount: 5, scrollLeft: 250, viewportWidth: 100, rowNumberWidth: 40, bufferPx: 0 })).toEqual({ start: 2, end: 4, beforeWidth: 200, afterWidth: 100 });
});
it("returns an empty window without columns", () => {
expect(dataGridHorizontalColumnWindow({ widths: [], offsets: [0], columnCount: 0, scrollLeft: 0, viewportWidth: 0, rowNumberWidth: 40, bufferPx: 900 })).toEqual({
start: 0,
end: 0,
beforeWidth: 0,
afterWidth: 0,
});
});
it("owns visibility, null-column toggles, and persisted ordering", () => {
const scope = effectScope();
const state = scope.run(() =>
useDataGridColumnLayoutState({
columns: ref(["id", "name", "empty"]),
sourceColumns: ref(undefined),
commentByColumn: ref(new Map()),
displayableColumnIndexes: ref([0, 1, 2]),
allNullColumnIndexes: ref([2]),
columnOrderKeys: ref(["id\0\0", "name\0\0", "empty\0\0"]),
layoutScopeKey: ref("test-layout"),
tableScopeKey: ref(""),
}),
)!;
state.toggleColumnVisibility(1);
expect(state.visibleColumnIndexes.value).toEqual([0, 2]);
state.toggleAllNullColumns();
expect(state.visibleColumnIndexes.value).toEqual([0]);
state.showAllColumns();
expect(state.visibleColumnIndexes.value).toEqual([0, 1, 2]);
state.persistColumnOrder([1, 0, 2]);
expect(state.orderedDisplayableColumnIndexes.value).toEqual([1, 0, 2]);
scope.stop();
});
it("keeps a new resize active when the previous resize completion frame is pending", () => {
const frames = new Map<number, FrameRequestCallback>();
let nextFrame = 1;
vi.stubGlobal(
"requestAnimationFrame",
vi.fn((callback: FrameRequestCallback) => {
const frame = nextFrame++;
frames.set(frame, callback);
return frame;
}),
);
vi.stubGlobal(
"cancelAnimationFrame",
vi.fn((frame: number) => frames.delete(frame)),
);
const scope = effectScope();
const layout = scope.run(() =>
useDataGridColumnLayout({
columnNames: ref(["id"]),
visibleColumnIndexes: ref([0]),
renderedColumnWidths: ref([100]),
scrollLeft: ref(0),
viewportWidth: ref(400),
rowNumberWidth: 40,
}),
)!;
layout.startColumnHeaderResize(0, new MouseEvent("mousedown"));
window.dispatchEvent(new MouseEvent("mouseup"));
expect(frames.size).toBe(1);
layout.startColumnHeaderResize(0, new MouseEvent("mousedown"));
expect(frames.size).toBe(0);
expect(layout.columnHeaderResizeActive.value).toBe(true);
scope.stop();
});
it("commits column drag order and removes global interaction state on disposal", () => {
vi.stubGlobal(
"requestAnimationFrame",
vi.fn((callback: FrameRequestCallback) => {
callback(0);
return 1;
}),
);
vi.stubGlobal("cancelAnimationFrame", vi.fn());
const first = document.createElement("div");
first.dataset.visibleColIndex = "0";
first.getBoundingClientRect = () => ({ left: 0, width: 100, right: 100, top: 0, bottom: 20, height: 20, x: 0, y: 0, toJSON: () => ({}) });
const second = document.createElement("div");
second.dataset.visibleColIndex = "1";
second.getBoundingClientRect = () => ({ left: 100, width: 100, right: 200, top: 0, bottom: 20, height: 20, x: 100, y: 0, toJSON: () => ({}) });
const header = document.createElement("div");
header.append(first, second);
const persist = vi.fn();
const scope = effectScope();
const layout = scope.run(() =>
useDataGridColumnLayout({
columnNames: ref(["id", "name"]),
visibleColumnIndexes: ref([0, 1]),
renderedColumnWidths: ref([100, 100]),
scrollLeft: ref(0),
viewportWidth: ref(400),
rowNumberWidth: 40,
headerRef: ref(header),
onPersistColumnOrder: persist,
}),
)!;
layout.startColumnHeaderDrag(0, new PointerEvent("pointerdown", { button: 0, clientX: 20, clientY: 10 }));
window.dispatchEvent(new PointerEvent("pointermove", { clientX: 180, clientY: 10 }));
expect(document.body.style.userSelect).toBe("none");
window.dispatchEvent(new PointerEvent("pointerup", { clientX: 180, clientY: 10 }));
expect(persist).toHaveBeenCalledWith([1, 0]);
expect(document.body.style.userSelect).toBe("");
layout.startColumnHeaderDrag(0, new PointerEvent("pointerdown", { button: 0, clientX: 20, clientY: 10 }));
window.dispatchEvent(new PointerEvent("pointermove", { clientX: 180, clientY: 10 }));
scope.stop();
expect(document.body.style.userSelect).toBe("");
window.dispatchEvent(new PointerEvent("pointerup", { clientX: 180, clientY: 10 }));
expect(persist).toHaveBeenCalledTimes(1);
});
});
@@ -1,6 +1,6 @@
import { computed, nextTick, ref } from "vue";
import { describe, expect, it, vi } from "vitest";
import { DATA_GRID_COL_AUTO_FIT_MAX_WIDTH, DATA_GRID_COL_MAX_WIDTH, DATA_GRID_COL_MIN_WIDTH } from "@/lib/dataGrid/dataGridColumnWidth";
import { describe, expect, it } from "vitest";
import { DATA_GRID_COL_AUTO_FIT_MAX_WIDTH, DATA_GRID_COL_MIN_WIDTH } from "@/lib/dataGrid/dataGridColumnWidth";
import { DATA_GRID_ROW_NUM_WIDTH, resizeDataGridColumnWidth, useDataGridColumnResize } from "@/composables/useDataGridColumnResize";
function createResizeState(options: { columns: string[]; rows: Array<Array<string | number | boolean | null>>; columnIndexes?: number[]; density?: "compact" | "standard" | "comfortable"; compactColumnHeaderActions?: boolean }) {
@@ -0,0 +1,137 @@
import { effectScope, nextTick, ref } from "vue";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { useDataGridConditionEditor } from "@/composables/useDataGridConditionEditor";
import { rememberDataGridConditionHistory } from "@/lib/dataGrid/dataGridConditionHistory";
const storage = new Map<string, string>();
vi.stubGlobal("localStorage", {
getItem: (key: string) => storage.get(key) ?? null,
setItem: (key: string, value: string) => storage.set(key, value),
removeItem: (key: string) => storage.delete(key),
clear: () => storage.clear(),
});
function keyboardEvent(key: string) {
return { key, shiftKey: false, preventDefault: vi.fn() } as unknown as KeyboardEvent;
}
describe("useDataGridConditionEditor", () => {
beforeEach(() => {
localStorage.clear();
vi.useRealTimers();
});
it("replaces the active token and supports clamped keyboard navigation", async () => {
const value = ref("status = cus");
const editor = useDataGridConditionEditor({
kind: "where",
value,
columns: ["customer_id", "customer_name"],
historyScope: {},
});
value.value = "status = cust";
await nextTick();
await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["customer_id", "customer_name"]));
expect(editor.navigate(1)).toBe(true);
expect(editor.highlightedIndex.value).toBe(1);
expect(editor.navigate(1)).toBe(true);
expect(editor.highlightedIndex.value).toBe(1);
expect(editor.accept()).toBe(true);
expect(value.value).toBe("status = customer_name");
});
it("ignores stale asynchronous suggestion responses", async () => {
vi.useFakeTimers();
const value = ref("");
const resolvers = new Map<string, (values: string[]) => void>();
const editor = useDataGridConditionEditor({
kind: "where",
value,
historyScope: {},
suggestionProvider: ({ token }) => new Promise((resolve) => resolvers.set(token, resolve)),
suggestionDebounceMs: 10,
});
value.value = "cus";
await nextTick();
vi.advanceTimersByTime(10);
await nextTick();
value.value = "ord";
await nextTick();
vi.advanceTimersByTime(10);
await nextTick();
resolvers.get("ord")?.(["order_id"]);
await Promise.resolve();
expect(editor.suggestions.value.map((item) => item.value)).toEqual(["order_id"]);
resolvers.get("cus")?.(["customer_id"]);
await Promise.resolve();
expect(editor.suggestions.value.map((item) => item.value)).toEqual(["order_id"]);
});
it("loads, filters, accepts, and deletes scoped history", () => {
const scope = { connectionId: "connection", database: "db", tableName: "users" };
rememberDataGridConditionHistory("where", scope, "status = 'active'");
rememberDataGridConditionHistory("where", scope, "customer_id > 10");
const value = ref("status");
const editor = useDataGridConditionEditor({ kind: "where", value, historyScope: scope });
editor.openHistory();
expect(editor.suggestions.value.map((item) => item.value)).toEqual(["status = 'active'"]);
expect(editor.accept(0)).toBe(true);
expect(value.value).toBe("status = 'active'");
editor.openHistory();
editor.deleteHistory("status = 'active'");
expect(editor.suggestions.value).toEqual([]);
expect(editor.historyOpen.value).toBe(true);
});
it("aborts pending suggestion work when its scope is disposed", async () => {
vi.useFakeTimers();
const value = ref("");
const aborted = vi.fn();
const scope = effectScope();
scope.run(() => {
useDataGridConditionEditor({
kind: "orderBy",
value,
historyScope: {},
suggestionDebounceMs: 10,
suggestionProvider: ({ signal }) => {
signal.addEventListener("abort", aborted);
return new Promise(() => {});
},
});
});
value.value = "created";
await nextTick();
vi.advanceTimersByTime(10);
scope.stop();
expect(aborted).toHaveBeenCalledOnce();
});
it("maps Enter, Tab, arrows, and Escape without applying stale selections", async () => {
const value = ref("");
const editor = useDataGridConditionEditor({ kind: "orderBy", value, columns: ["name"], historyScope: {} });
value.value = "na";
await nextTick();
await vi.waitFor(() => expect(editor.suggestions.value).toHaveLength(1));
const down = keyboardEvent("ArrowDown");
expect(editor.handleKeydown(down)).toBe("navigate");
expect(down.preventDefault).toHaveBeenCalledOnce();
const tab = keyboardEvent("Tab");
expect(editor.handleKeydown(tab)).toBe("accept");
expect(value.value).toBe("name");
const enter = keyboardEvent("Enter");
expect(editor.handleKeydown(enter)).toBe("apply");
editor.openHistory();
const escape = keyboardEvent("Escape");
expect(editor.handleKeydown(escape)).toBe("dismiss");
expect(editor.dropdownOpen.value).toBe(false);
});
});
@@ -0,0 +1,37 @@
import { describe, expect, it } from "vitest";
import { buildDataGridStructuredWhere, useDataGridFilterBuilder, type DataGridStructuredFilterRule } from "@/composables/useDataGridFilterBuilder";
describe("useDataGridFilterBuilder", () => {
it("normalizes values when modes change", () => {
const builder = useDataGridFilterBuilder({ columns: ["id"], createId: () => "rule-1", isComplete: () => true, buildCondition: async () => "id = 1" });
builder.ensureRule();
builder.updateRule("rule-1", { rawValue: "1", rawEndValue: "2", mode: "is-null" });
expect(builder.rules.value[0]).toMatchObject({ rawValue: "", rawEndValue: "" });
});
it("skips disabled rules and applies conjunctions", async () => {
let nextId = 0;
const builder = useDataGridFilterBuilder({
columns: ["id", "name"],
createId: () => `rule-${++nextId}`,
isComplete: (rule) => !!rule.rawValue,
buildCondition: async (rule) => `${rule.columnName} = '${rule.rawValue}'`,
});
builder.ensureRule();
builder.updateRule("rule-1", { rawValue: "1" });
builder.addRule();
builder.updateRule("rule-2", { columnName: "name", rawValue: "Alice", conjunction: "OR" });
expect(await builder.apply()).toBe("(id = '1') OR (name = 'Alice')");
});
it("groups conditions in rule order", () => {
const rule = (id: string, conjunction: "AND" | "OR"): DataGridStructuredFilterRule => ({ id, columnName: id, mode: "equals", rawValue: id, rawEndValue: "", conjunction });
expect(
buildDataGridStructuredWhere([
{ rule: rule("a", "AND"), condition: "a" },
{ rule: rule("b", "AND"), condition: "b" },
{ rule: rule("c", "OR"), condition: "c" },
]),
).toBe("((a) AND (b)) OR (c)");
});
});
@@ -0,0 +1,28 @@
import { nextTick, ref } from "vue";
import { describe, expect, it } from "vitest";
import { useDataGridResultLifecycle } from "@/composables/useDataGridResultLifecycle";
describe("useDataGridResultLifecycle", () => {
it("invalidates operations when the result identity changes", async () => {
const result = ref<object>({ id: 1 });
const lifecycle = useDataGridResultLifecycle({ resultKey: result });
const operation = lifecycle.beginOperation();
result.value = { id: 2 };
await nextTick();
expect(lifecycle.isCurrent(operation)).toBe(false);
lifecycle.cleanup();
});
it("invalidates operations explicitly and cleanup is idempotent", () => {
const lifecycle = useDataGridResultLifecycle({ resultKey: ref({ id: 1 }) });
const operation = lifecycle.beginOperation();
lifecycle.invalidate();
lifecycle.cleanup();
lifecycle.cleanup();
expect(lifecycle.isCurrent(operation)).toBe(false);
});
});
@@ -0,0 +1,27 @@
import { nextTick, ref } from "vue";
import { describe, expect, it, vi } from "vitest";
import { useDataGridSearch } from "@/composables/useDataGridSearch";
describe("useDataGridSearch", () => {
it("debounces matching across columns and cells", async () => {
vi.useFakeTimers();
const search = useDataGridSearch({ columns: ["id", "name"], rows: [[1, "Alice"]], getCellText: (row, column) => String(row[column] ?? "") });
search.searchText.value = "ali";
await nextTick();
expect(search.matches.value).toEqual([]);
vi.advanceTimersByTime(150);
await nextTick();
expect(search.matches.value).toEqual([{ kind: "cell", displayRow: 0, col: 1 }]);
vi.useRealTimers();
});
it("suggests columns and replaces only the active token", async () => {
const columns = ref(["customer_id", "created_at"]);
const search = useDataGridSearch({ columns, rows: [], getCellText: () => "" });
search.searchText.value = "status = cus";
await nextTick();
expect(search.suggestions.value).toEqual(["customer_id"]);
expect(search.acceptSuggestion()).toBe(true);
expect(search.searchText.value).toBe("status = customer_id");
});
});
@@ -0,0 +1,27 @@
import { describe, expect, it } from "vitest";
import { useDataGridSort } from "@/composables/useDataGridSort";
describe("useDataGridSort", () => {
it("stores the selected database or local sort state", () => {
const sort = useDataGridSort();
sort.setSort("name", 2, "desc", "local");
expect(sort.sortColumn.value).toBe("name");
expect(sort.sortColumnIndex.value).toBe(2);
expect(sort.sortDirection.value).toBe("desc");
expect(sort.sortMode.value).toBe("local");
});
it("resets to the default unsorted state", () => {
const sort = useDataGridSort();
sort.setSort("name", 2, "desc", "local");
sort.clearSort();
expect(sort.sortColumn.value).toBeNull();
expect(sort.sortColumnIndex.value).toBeNull();
expect(sort.sortDirection.value).toBe("asc");
expect(sort.sortMode.value).toBe("database");
});
});