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

@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { claimDataGridPaste } from "@/lib/dataGrid/dataGridClipboard";
import { claimDataGridPaste, planDataGridPaste } from "@/lib/dataGrid/dataGridClipboard";
function target(nativeClipboard: boolean): EventTarget {
return {
@@ -49,3 +49,26 @@ describe("claimDataGridPaste", () => {
expect(event.stopPropagation).toHaveBeenCalledOnce();
});
});
describe("planDataGridPaste", () => {
it("flattens a clipboard matrix within grid bounds", () => {
expect(
planDataGridPaste(
[
["a", "b"],
["c", "d"],
],
2,
1,
),
).toEqual([
{ rowOffset: 0, columnOffset: 0, value: "a" },
{ rowOffset: 1, columnOffset: 0, value: "c" },
]);
});
it("returns no cells for empty bounds", () => {
expect(planDataGridPaste([["a"]], 0, 1)).toEqual([]);
expect(planDataGridPaste([["a"]], 1, 0)).toEqual([]);
});
});
@@ -0,0 +1,83 @@
import { describe, expect, it, vi } from "vitest";
import { createDataGridCellContextMenuItems, createDataGridColumnContextMenuItems, createDataGridCompactColumnActionItems, createDataGridFilterSubmenu, createDataGridRowContextMenuItems, createDataGridSortMenuItems, dataGridSelectedSortMenuValue } from "@/lib/dataGrid/dataGridContextMenu";
const icon = {};
describe("dataGridContextMenu", () => {
it("marks only the active sort action and enables clear", () => {
const state = { column: "id", columnIndex: 0, direction: "desc" as const, mode: "local" as const };
const items = createDataGridSortMenuItems({
column: "id",
columnIndex: 0,
state,
labels: { databaseAscending: "db asc", databaseDescending: "db desc", currentPageAscending: "page asc", currentPageDescending: "page desc", clear: "clear" },
icons: { database: icon, ascending: icon, descending: icon, clear: icon },
});
expect(items.map((item) => item.checked)).toEqual([false, false, false, true, undefined]);
expect(items.at(-1)?.disabled).toBe(false);
expect(dataGridSelectedSortMenuValue(state, "id", 0)).toBe("local-desc");
});
it("omits unavailable server actions and disables unavailable formatter", () => {
const items = createDataGridCompactColumnActionItems({
labels: { formatter: "formatter", localFilter: "local", serverFilter: "server" },
icons: { formatter: icon, filter: icon, database: icon },
formatterAvailable: false,
serverFilterAvailable: false,
});
expect(items.map((item) => item.value)).toEqual(["formatter", "localFilter"]);
expect(items[0]?.disabled).toBe(true);
});
it("builds typed column, cell, and row capability groups", () => {
const action = vi.fn();
const filter = createDataGridFilterSubmenu({
label: "filter",
icon,
labels: { equals: "equals", notEquals: "not equals", like: "like", notLike: "not like", lessThan: "less", greaterThan: "greater", isNull: "null", isNotNull: "not null", clear: "clear" },
apply: action,
clear: action,
});
const columnItems = createDataGridColumnContextMenuItems({
headerColumn: true,
contextColumn: true,
canCopyAlterSql: true,
canFilter: true,
hasSort: true,
sortMode: "database",
labels: { copyName: "copy name", copyNames: "copy names", details: "details", copyAlterSql: "alter", databaseAscending: "db asc", databaseDescending: "db desc", localAscending: "local asc", localDescending: "local desc", clearSort: "clear sort" },
icons: { copy: icon, columnDetails: icon, database: icon, ascending: icon, descending: icon, clearSort: icon },
actions: { copyName: action, copyNames: action, details: action, copyAlterSql: action, sort: action },
filterSubmenu: filter,
});
expect(columnItems.map((item) => item.label)).toContain("filter");
const cellItems = createDataGridCellContextMenuItems({
hasCell: true,
hasColumn: true,
headerColumn: false,
editable: true,
hasCellSelection: true,
hasEditableSelection: false,
hasSelection: true,
labels: { cellDetails: "cell", columnDetails: "column", rowDetails: "row", setNull: "null", bulkEdit: "bulk", transpose: "transpose" },
icons: { cellDetails: icon, columnDetails: icon, rowDetails: icon, setNull: icon, bulkEdit: icon, transpose: icon },
actions: { cellDetails: action, columnDetails: action, rowDetails: action, setNull: action, bulkEdit: action, transpose: action },
copySubmenu: { label: "copy" },
selectionSubmenu: { label: "selection" },
});
expect(cellItems.find((item) => item.label === "bulk")?.disabled).toBe(true);
const rowItems = createDataGridRowContextMenuItems({
editable: true,
hasRow: true,
canClone: true,
deleted: false,
canDelete: true,
labels: { clone: "clone", restore: "restore", delete: "delete" },
icons: { clone: icon, restore: icon, delete: icon },
actions: { clone: action, restore: action, delete: action },
});
expect(rowItems.find((item) => item.label === "delete")?.variant).toBe("destructive");
});
});
@@ -0,0 +1,18 @@
import { describe, expect, it } from "vitest";
import { dataGridEditAdapterKind } from "@/lib/dataGrid/dataGridEditAdapter";
describe("dataGridEditAdapter", () => {
it("prioritizes custom save handlers", () => {
expect(dataGridEditAdapterKind({ databaseType: "mongodb", custom: true, editable: true })).toBe("custom");
});
it("distinguishes document and relational editing", () => {
expect(dataGridEditAdapterKind({ databaseType: "mongodb", custom: false, editable: true })).toBe("document");
expect(dataGridEditAdapterKind({ databaseType: "postgresql", custom: false, editable: true })).toBe("relational");
});
it("keeps read-only and unknown contexts unsupported", () => {
expect(dataGridEditAdapterKind({ databaseType: "postgresql", custom: false, editable: false })).toBe("unsupported");
expect(dataGridEditAdapterKind({ custom: false, editable: true })).toBe("unsupported");
});
});
@@ -0,0 +1,24 @@
import { describe, expect, it } from "vitest";
import { loadDataGridStructuredFilterState, saveDataGridStructuredFilterState } from "@/lib/dataGrid/dataGridFilterBuilderPersistence";
describe("data grid filter builder persistence", () => {
it("isolates scopes and returns cloned state", () => {
saveDataGridStructuredFilterState("cache", {
scopeKey: "scope-a",
manualWhereInput: "status = 1",
rules: [{ id: "rule-1", columnName: "status", mode: "equals", rawValue: "1", rawEndValue: "", conjunction: "AND" }],
appliedWhereInput: '"status" = 1',
serverColumnFilters: { 0: { condition: '"status" = 1', keys: ["1"], labels: ["1"] } },
});
expect(loadDataGridStructuredFilterState("cache", "scope-b")).toBeUndefined();
const restored = loadDataGridStructuredFilterState("cache", "scope-a")!;
restored.rules[0].rawValue = "2";
restored.serverColumnFilters[0].keys.push("2");
expect(loadDataGridStructuredFilterState("cache", "scope-a")).toMatchObject({
rules: [{ rawValue: "1" }],
serverColumnFilters: { 0: { keys: ["1"] } },
});
});
});
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import { moveDataGridCell, navigateDataGridCell } from "@/lib/dataGrid/dataGridNavigation";
const bounds = { rowCount: 3, visibleColumnCount: 4 };
describe("dataGridNavigation", () => {
it("clamps directional movement to grid boundaries", () => {
expect(moveDataGridCell({ rowIndex: 0, colIndex: 0 }, -1, -1, bounds)).toEqual({ rowIndex: 0, colIndex: 0 });
expect(moveDataGridCell({ rowIndex: 2, colIndex: 3 }, 1, 1, bounds)).toEqual({ rowIndex: 2, colIndex: 3 });
expect(moveDataGridCell({ rowIndex: 1, colIndex: 2 }, -1, 1, bounds)).toEqual({ rowIndex: 0, colIndex: 3 });
});
it("supports home and end navigation without changing the row", () => {
expect(navigateDataGridCell({ rowIndex: 2, colIndex: 2 }, "home", bounds)).toEqual({ rowIndex: 2, colIndex: 0 });
expect(navigateDataGridCell({ rowIndex: 2, colIndex: 0 }, "end", bounds)).toEqual({ rowIndex: 2, colIndex: 3 });
});
it("returns no target for an empty grid", () => {
expect(navigateDataGridCell({ rowIndex: 0, colIndex: 0 }, "down", { rowCount: 0, visibleColumnCount: 4 })).toBeNull();
});
});
@@ -0,0 +1,46 @@
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it, vi } from "vitest";
import { createDataGridRuntimeScope } from "@/lib/dataGrid/dataGridRuntime";
describe("dataGridRuntime", () => {
it("disposes registered resources in reverse order and only once", () => {
const scope = createDataGridRuntimeScope();
const calls: string[] = [];
const removeFirst = scope.addCleanup(() => calls.push("first"));
scope.addCleanup(() => calls.push("second"));
removeFirst();
scope.dispose();
scope.dispose();
expect(calls).toEqual(["second"]);
expect(scope.disposed).toBe(true);
});
it("runs cleanup immediately when registered after disposal", () => {
const scope = createDataGridRuntimeScope();
const cleanup = vi.fn();
scope.dispose();
const unregister = scope.addCleanup(cleanup);
unregister();
expect(cleanup).toHaveBeenCalledOnce();
});
it("keeps runtime modules independent from the DataGrid component", () => {
const sourceRoots = [join(process.cwd(), "apps/desktop/src/lib/dataGrid"), join(process.cwd(), "apps/desktop/src/composables")];
const sourceFiles: string[] = [];
const visit = (directory: string) => {
for (const entry of readdirSync(directory, { withFileTypes: true })) {
const path = join(directory, entry.name);
if (entry.isDirectory()) visit(path);
else if (entry.name.endsWith(".ts") && (!directory.endsWith("/composables") || entry.name.startsWith("useDataGrid"))) sourceFiles.push(path);
}
};
sourceRoots.forEach(visit);
expect(sourceFiles.filter((path) => readFileSync(path, "utf8").includes("DataGrid.vue"))).toEqual([]);
});
});
@@ -0,0 +1,84 @@
import { describe, expect, it, vi } from "vitest";
import { dataGridToolbarIntervalOptions, selectDataGridToolbarAutoRefreshInterval, selectDataGridToolbarExportItem, toggleDataGridToolbarAutoRefresh, triggerDataGridToolbarAction, type DataGridToolbarAutoRefreshCapability } from "@/lib/dataGrid/dataGridToolbar";
function autoRefreshCapability(overrides: Partial<DataGridToolbarAutoRefreshCapability> = {}): DataGridToolbarAutoRefreshCapability {
return {
label: "Auto-refresh",
shortLabel: "Auto",
startLabel: "Start auto-refresh",
stopLabel: "Stop auto-refresh",
enabled: false,
intervalSeconds: 10,
intervalOptions: [5, 10, 30],
intervalLabel: (seconds) => `${seconds}s`,
onToggle: vi.fn(),
onSelectInterval: vi.fn(),
...overrides,
};
}
describe("data grid toolbar capabilities", () => {
it("does not invoke hidden or disabled actions", async () => {
const onTrigger = vi.fn();
await expect(triggerDataGridToolbarAction({ label: "Save", visible: false, onTrigger })).resolves.toBe(false);
await expect(triggerDataGridToolbarAction({ label: "Save", disabled: true, onTrigger })).resolves.toBe(false);
expect(onTrigger).not.toHaveBeenCalled();
});
it("invokes enabled save and rollback callbacks independently", async () => {
const save = vi.fn();
const rollback = vi.fn();
await expect(triggerDataGridToolbarAction({ label: "Save", onTrigger: save })).resolves.toBe(true);
await expect(triggerDataGridToolbarAction({ label: "Rollback", onTrigger: rollback })).resolves.toBe(true);
expect(save).toHaveBeenCalledOnce();
expect(rollback).toHaveBeenCalledOnce();
});
it("keeps preset intervals ordered and preserves a persisted custom interval", () => {
expect(dataGridToolbarIntervalOptions([30, 5, 10, 10, 0, -1, 2.5], 15)).toEqual([5, 10, 15, 30]);
});
it("toggles auto-refresh and selects valid intervals", async () => {
const onToggle = vi.fn();
const onSelectInterval = vi.fn();
const capability = autoRefreshCapability({ onToggle, onSelectInterval });
await expect(toggleDataGridToolbarAutoRefresh(capability)).resolves.toBe(true);
await expect(selectDataGridToolbarAutoRefreshInterval(capability, 30)).resolves.toBe(true);
await expect(selectDataGridToolbarAutoRefreshInterval(capability, 99)).resolves.toBe(false);
expect(onToggle).toHaveBeenCalledOnce();
expect(onSelectInterval).toHaveBeenCalledOnce();
expect(onSelectInterval).toHaveBeenCalledWith(30);
});
it("blocks auto-refresh changes while the capability is disabled", async () => {
const onToggle = vi.fn();
const onSelectInterval = vi.fn();
const capability = autoRefreshCapability({ disabled: true, onToggle, onSelectInterval });
await expect(toggleDataGridToolbarAutoRefresh(capability)).resolves.toBe(false);
await expect(selectDataGridToolbarAutoRefreshInterval(capability, 10)).resolves.toBe(false);
expect(onToggle).not.toHaveBeenCalled();
expect(onSelectInterval).not.toHaveBeenCalled();
});
it("rejects disabled or unknown export items", async () => {
const onSelect = vi.fn();
const capability = {
label: "Export",
items: [
{ value: "csv", label: "CSV" },
{ value: "sql", label: "SQL", disabled: true },
],
onSelect,
};
await expect(selectDataGridToolbarExportItem(capability, "csv")).resolves.toBe(true);
await expect(selectDataGridToolbarExportItem(capability, "sql")).resolves.toBe(false);
await expect(selectDataGridToolbarExportItem(capability, "xlsx")).resolves.toBe(false);
expect(onSelect).toHaveBeenCalledOnce();
expect(onSelect).toHaveBeenCalledWith("csv");
});
});