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,299 @@
// @vitest-environment happy-dom
import { nextTick } from "vue";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { dispatch, findAll, findOne, hostText, mountComponent } from "./vueHostHarness";
import type { DataGridCellDetail } from "@/lib/dataGrid/dataGridDetail";
const mocks = vi.hoisted(() => ({
editor: { create: vi.fn(), destroy: vi.fn(), setValue: vi.fn(), openSearch: vi.fn() },
updateSettings: vi.fn(),
renderWkt: vi.fn(),
panelCancel: vi.fn(),
panelOpenSearch: vi.fn(),
}));
vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
vi.mock("@lucide/vue", async () => {
const { createPassthroughStub } = await import("./vueHostHarness");
const icon = createPassthroughStub("Icon", "i");
return { Check: icon, ChevronLeft: icon, ChevronRight: icon, ChevronsLeft: icon, ChevronsRight: icon, Loader2: icon, Upload: icon, Search: icon, X: icon, Code2: icon, Copy: icon, Eye: icon, EyeOff: icon, Info: icon, Pencil: icon, Plus: icon, Trash2: icon };
});
vi.mock("@/components/ui/button", async () => ({ Button: (await import("./vueHostHarness")).createPassthroughStub("Button", "button") }));
vi.mock("@/components/ui/input", async () => ({ Input: (await import("./vueHostHarness")).createPassthroughStub("Input", "input") }));
vi.mock("@/components/ui/dialog", async () => {
const { createPassthroughStub } = await import("./vueHostHarness");
return { Dialog: createPassthroughStub("Dialog"), DialogContent: createPassthroughStub("DialogContent"), DialogFooter: createPassthroughStub("DialogFooter"), DialogHeader: createPassthroughStub("DialogHeader"), DialogTitle: createPassthroughStub("DialogTitle") };
});
vi.mock("@/components/ui/dropdown-menu", async () => {
const { createPassthroughStub } = await import("./vueHostHarness");
return { DropdownMenu: createPassthroughStub("DropdownMenu"), DropdownMenuContent: createPassthroughStub("DropdownMenuContent"), DropdownMenuItem: createPassthroughStub("DropdownMenuItem", "button"), DropdownMenuTrigger: createPassthroughStub("DropdownMenuTrigger") };
});
vi.mock("@/components/ui/popover", async () => {
const { createPassthroughStub } = await import("./vueHostHarness");
return { Popover: createPassthroughStub("Popover"), PopoverContent: createPassthroughStub("PopoverContent"), PopoverTrigger: createPassthroughStub("PopoverTrigger") };
});
vi.mock("@/components/ui/tooltip", async () => {
const { createPassthroughStub } = await import("./vueHostHarness");
return { Tooltip: createPassthroughStub("Tooltip"), TooltipContent: createPassthroughStub("TooltipContent"), TooltipTrigger: createPassthroughStub("TooltipTrigger") };
});
vi.mock("@/components/ui/select", async () => {
const { createPassthroughStub } = await import("./vueHostHarness");
return { Select: createPassthroughStub("Select"), SelectContent: createPassthroughStub("SelectContent"), SelectItem: createPassthroughStub("SelectItem"), SelectTrigger: createPassthroughStub("SelectTrigger"), SelectValue: createPassthroughStub("SelectValue") };
});
vi.mock("@/components/ui/tabs", async () => ({ TabsContent: (await import("./vueHostHarness")).createPassthroughStub("TabsContent") }));
vi.mock("@/components/ui/LightDropdown.vue", async () => ({ default: (await import("./vueHostHarness")).createPassthroughStub("LightDropdown") }));
vi.mock("@/components/ui/LightTooltip.vue", async () => ({ default: (await import("./vueHostHarness")).createPassthroughStub("LightTooltip") }));
vi.mock("@/components/grid/TemporalCellEditor.vue", async () => ({ default: (await import("./vueHostHarness")).createPassthroughStub("TemporalCellEditor") }));
vi.mock("@/composables/useCellDetailEditor", () => ({ useCellDetailEditor: () => mocks.editor }));
vi.mock("@/composables/useTheme", () => ({ useTheme: () => ({ isDark: { value: false }, themePalette: { value: {} } }) }));
vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => ({ editorSettings: { cellDetailJsonFormatted: true, theme: "default", fontSize: 13, fontFamily: "monospace" }, updateEditorSettings: mocks.updateSettings }) }));
vi.mock("@/lib/dataGrid/geometryPreview", () => ({ isHexGeometry: () => false, renderWktOnCanvas: mocks.renderWkt }));
vi.mock("@/composables/useDataGridCellDetail", async () => {
const { ref } = await import("vue");
return {
useDataGridCellDetail: ({ onCancel }: { onCancel: () => void }) => {
mocks.panelCancel.mockImplementation(onCancel);
return { geometryPreviewOpen: ref(false), geometryCanvas: ref(), detailsEditorContainer: ref(), sideJsonPreviewContainer: ref(), openSearch: mocks.panelOpenSearch };
},
};
});
import DataGridCellDetailDialog from "@/components/grid/DataGridCellDetailDialog.vue";
import DataGridCellDetailPanel from "@/components/grid/DataGridCellDetailPanel.vue";
import DataGridColumnHeader from "@/components/grid/DataGridColumnHeader.vue";
import DataGridFilterBuilder from "@/components/grid/DataGridFilterBuilder.vue";
import DataGridPagination from "@/components/grid/DataGridPagination.vue";
import DataGridSearchBar from "@/components/grid/DataGridSearchBar.vue";
function detail(patch: Partial<DataGridCellDetail> = {}): DataGridCellDetail {
return {
rowNumber: 1,
rowId: 0,
colIndex: 0,
column: "payload",
type: "JSON",
comment: "",
value: '{"a":1}',
rawValue: '{"a":1}',
rawValuePreview: '{"a":1}',
displayValue: '{"a":1}',
displayValuePreview: '{"a":1}',
isValuePreviewTruncated: false,
imagePreviewUrl: null,
length: 7,
formattedJson: '{\n "a": 1\n}',
isEditable: true,
...patch,
};
}
beforeEach(() => {
vi.clearAllMocks();
});
describe("DataGridSearchBar", () => {
it("focuses/selects the input and forwards keyboard and suggestion interactions", () => {
const keydown = vi.fn();
const acceptSuggestion = vi.fn();
const hoverSuggestion = vi.fn();
const close = vi.fn();
const mounted = mountComponent(DataGridSearchBar, {
open: true,
text: "pay",
suggestions: ["payload"],
suggestionIndex: 0,
matchCount: 2,
currentMatchIndex: 0,
hasDeferredSearchText: false,
onKeydown: keydown,
onAcceptSuggestion: acceptSuggestion,
onHoverSuggestion: hoverSuggestion,
onClose: close,
});
const input = findOne(mounted.root, (node) => node.type === "input");
mounted.exposed.value.focus(true);
expect(input.focused).toBe(true);
expect(input.selected).toBe(true);
dispatch(input, "keydown", { key: "Enter" });
expect(keydown).toHaveBeenCalledWith(expect.objectContaining({ key: "Enter" }));
const suggestion = findOne(mounted.root, (node) => hostText(node) === "payload" && !!node.props.onMousedown);
const mouseDown = dispatch(suggestion, "mousedown");
expect(mouseDown.defaultPrevented).toBe(true);
expect(acceptSuggestion).toHaveBeenCalledWith(0);
dispatch(suggestion, "mouseenter");
expect(hoverSuggestion).toHaveBeenCalledWith(0);
const closeButton = findOne(mounted.root, (node) => node.type === "button");
dispatch(closeButton, "click");
expect(close).toHaveBeenCalledOnce();
});
});
describe("DataGridPagination", () => {
it("enforces first/previous/next/last disabled boundaries", async () => {
const firstPage = vi.fn();
const previousPage = vi.fn();
const nextPage = vi.fn();
const lastPage = vi.fn();
const mounted = mountComponent(DataGridPagination, {
selectionSummary: null,
selectionSummarySumText: "",
loading: false,
infiniteScrollEnabled: false,
infiniteScrollAllLoaded: false,
pageSize: 100,
customPageSizeInput: "",
pageSizeMenuItems: [],
exportMenuItems: [],
currentPage: 1,
canGoNextPage: false,
canJumpLastPage: false,
onFirstPage: firstPage,
onPreviousPage: previousPage,
onNextPage: nextPage,
onLastPage: lastPage,
});
const navigation = findAll(mounted.root, (node) => node.props["data-stub"] === "Button" && node.props.class === "h-5 w-5 shrink-0");
expect(navigation.map((node) => node.props.disabled)).toEqual([true, true, true, true]);
navigation.forEach((node) => dispatch(node, "click"));
expect(firstPage).not.toHaveBeenCalled();
expect(previousPage).not.toHaveBeenCalled();
expect(nextPage).not.toHaveBeenCalled();
expect(lastPage).not.toHaveBeenCalled();
await mounted.setProps({ currentPage: 2, canGoNextPage: true, canJumpLastPage: true });
const enabledNavigation = findAll(mounted.root, (node) => node.props["data-stub"] === "Button" && node.props.class === "h-5 w-5 shrink-0");
expect(enabledNavigation.map((node) => node.props.disabled)).toEqual([false, false, false, false]);
enabledNavigation.forEach((node) => dispatch(node, "click"));
expect(firstPage).toHaveBeenCalledOnce();
expect(previousPage).toHaveBeenCalledOnce();
expect(nextPage).toHaveBeenCalledOnce();
expect(lastPage).toHaveBeenCalledOnce();
});
});
describe("DataGridColumnHeader", () => {
it("cancels resize-handle clicks without leaking header click events", () => {
const click = vi.fn();
const clickCapture = vi.fn();
const resizeStart = vi.fn();
const autoFit = vi.fn();
const mounted = mountComponent(DataGridColumnHeader, {
name: "id",
actualColumnIndex: 0,
visibleColumnIndex: 0,
dark: true,
copyColumnNameLabel: "copy",
columnNameLabel: "name",
columnTypeLabel: "type",
columnCommentLabel: "comment",
onClick: click,
onClickCapture: clickCapture,
onResizeStart: resizeStart,
onAutoFit: autoFit,
});
const handle = findOne(mounted.root, (node) => node.props["data-column-resize-handle"] === "");
const header = findOne(mounted.root, (node) => node.props["data-grid-column-index"] === 0);
expect(String(header.props.class)).toContain("data-grid-header-cell--dark");
const down = dispatch(handle, "mousedown");
expect(down.propagationStopped).toBe(true);
expect(resizeStart).toHaveBeenCalledOnce();
const handleClick = dispatch(handle, "click");
expect(handleClick.propagationStopped).toBe(true);
expect(handleClick.defaultPrevented).toBe(true);
expect(click).not.toHaveBeenCalled();
expect(clickCapture).not.toHaveBeenCalled();
dispatch(handle, "dblclick");
expect(autoFit).toHaveBeenCalledOnce();
});
});
describe("DataGridFilterBuilder", () => {
it("isolates text-entry keys while preserving popup navigation keys", () => {
const mounted = mountComponent(DataGridFilterBuilder, { rules: [{ id: "r1", columnName: "id", mode: "equals", rawValue: "", rawEndValue: "", conjunction: "AND" }], columns: ["id"], filteredColumns: ["id"], modeOptions: [{ value: "equals", labelKey: "equals" }], columnSearch: "" });
const searchInput = findOne(mounted.root, (node) => node.type === "input" && node.props.placeholder === "grid.filterBuilderSearchColumns");
expect(dispatch(searchInput, "keydown", { key: "a" }).propagationStopped).toBe(true);
expect(dispatch(searchInput, "keydown", { key: "Backspace" }).propagationStopped).toBe(true);
expect(dispatch(searchInput, "keydown", { key: "ArrowDown" }).propagationStopped).toBe(false);
expect(dispatch(searchInput, "keydown", { key: "Process", isComposing: true }).propagationStopped).toBe(true);
});
});
describe("cell detail surfaces", () => {
it("copies the presented value, emits edit, closes, and replaces the JSON result", async () => {
const copyText = vi.fn();
const edit = vi.fn();
const updateOpen = vi.fn();
const mounted = mountComponent(DataGridCellDetailDialog, { open: true, detail: detail(), typeColorClass: () => "", openImagePreview: vi.fn(), copyText, canDownloadBinaryValue: () => false, downloadBinaryValue: vi.fn(), onEdit: edit, "onUpdate:open": updateOpen });
await nextTick();
await nextTick();
const copyValue = findOne(mounted.root, (node) => node.props.title === "grid.copyValue");
dispatch(copyValue, "click");
expect(copyText).toHaveBeenCalledWith('{\n "a": 1\n}');
dispatch(
findOne(mounted.root, (node) => node.props.title === "grid.editValue"),
"click",
);
expect(edit).toHaveBeenCalledOnce();
await mounted.setProps({ detail: detail({ rawValue: '{"b":2}', formattedJson: '{\n "b": 2\n}' }) });
expect(mocks.editor.setValue).toHaveBeenCalledWith('{\n "b": 2\n}', "json");
await mounted.setProps({ detail: detail({ value: null, rawValue: "", formattedJson: "" }) });
expect(mocks.editor.destroy).toHaveBeenCalledOnce();
const dialog = findOne(mounted.root, (node) => node.props["data-stub"] === "Dialog");
dialog.props["onUpdate:open"](false);
expect(updateOpen).toHaveBeenCalledWith(false);
});
it("forwards panel edit/copy/cancel actions and exposes search", () => {
const startEdit = vi.fn();
const copyValue = vi.fn();
const cancel = vi.fn();
const mounted = mountComponent(DataGridCellDetailPanel, {
detail: detail({ formattedJson: "" }),
panelIsBottom: false,
metadataCollapsed: false,
valueFillsHeight: false,
editing: false,
sideJsonView: false,
showCompactJson: false,
canCompactJson: false,
typeColorClass: () => "",
canDownloadBinaryValue: () => false,
downloadBinaryValue: vi.fn(),
openImagePreview: vi.fn(),
canCopySqlCondition: () => true,
onStartEdit: startEdit,
onCopyValue: copyValue,
onCancel: cancel,
});
dispatch(
findOne(mounted.root, (node) => node.props.title === "grid.editValue"),
"click",
);
dispatch(
findOne(mounted.root, (node) => node.props.title === "grid.copyValue"),
"click",
);
dispatch(
findOne(mounted.root, (node) => node.type === "pre"),
"dblclick",
);
expect(startEdit).toHaveBeenCalledTimes(2);
expect(copyValue).toHaveBeenCalledOnce();
mocks.panelCancel();
expect(cancel).toHaveBeenCalledOnce();
mounted.exposed.value.openSearch();
expect(mocks.panelOpenSearch).toHaveBeenCalledOnce();
});
});
@@ -0,0 +1,185 @@
import { createRenderer, defineComponent, h, nextTick, reactive, ref, type Component } from "vue";
export interface HostNode {
type: string;
props: Record<string, any>;
children: Array<HostNode | string>;
parent: HostNode | null;
focused: boolean;
selected: boolean;
value?: unknown;
listeners: Map<string, Array<(event: any) => void>>;
focus(): void;
select(): void;
addEventListener(name: string, listener: (event: any) => void): void;
removeEventListener(name: string, listener: (event: any) => void): void;
}
function createHostNode(type: string): HostNode {
const node: HostNode = {
type,
props: {},
children: [],
parent: null,
focused: false,
selected: false,
listeners: new Map(),
focus() {
node.focused = true;
},
select() {
node.selected = true;
},
addEventListener(name, listener) {
const listeners = node.listeners.get(name) ?? [];
listeners.push(listener);
node.listeners.set(name, listeners);
},
removeEventListener(name, listener) {
node.listeners.set(
name,
(node.listeners.get(name) ?? []).filter((candidate) => candidate !== listener),
);
},
};
return node;
}
function insert(child: HostNode, parent: HostNode, anchor?: HostNode | null) {
child.parent = parent;
if (!anchor) {
parent.children.push(child);
return;
}
const index = parent.children.indexOf(anchor);
parent.children.splice(index < 0 ? parent.children.length : index, 0, child);
}
const renderer = createRenderer<HostNode, HostNode>({
patchProp(node, key, _previous, next) {
if (next === null || next === undefined) delete node.props[key];
else node.props[key] = next;
if (key === "value") node.value = next;
},
insert,
remove(node) {
if (!node.parent) return;
const index = node.parent.children.indexOf(node);
if (index >= 0) node.parent.children.splice(index, 1);
node.parent = null;
},
createElement: createHostNode,
createText(text) {
const node = createHostNode("#text");
node.children = [text];
return node;
},
createComment(text) {
const node = createHostNode("#comment");
node.children = [text];
return node;
},
setText(node, text) {
node.children = [text];
},
setElementText(node, text) {
node.children = [text];
},
parentNode: (node) => node.parent,
nextSibling(node) {
if (!node.parent) return null;
const index = node.parent.children.indexOf(node);
return (node.parent.children[index + 1] as HostNode | undefined) ?? null;
},
setScopeId(node, id) {
node.props[id] = "";
},
cloneNode(node) {
return { ...node, props: { ...node.props }, children: [...node.children], parent: null, listeners: new Map(node.listeners) };
},
insertStaticContent(content, parent, anchor) {
const node = createHostNode("#static");
node.children = [content];
insert(node, parent, anchor);
return [node, node];
},
});
export function createPassthroughStub(name: string, tag = "div") {
return defineComponent({
name,
inheritAttrs: false,
setup(_props, { attrs, slots }) {
return () => h(tag, { ...attrs, "data-stub": name }, [slots.default?.(), slots.content?.()]);
},
});
}
export function mountComponent(component: Component, initialProps: Record<string, unknown>) {
const props = reactive({ ...initialProps });
const componentRef = ref<any>();
const root = createHostNode("root");
const wrapper = defineComponent({
setup() {
return () => h(component, { ...props, ref: componentRef });
},
});
const app = renderer.createApp(wrapper);
app.mount(root);
return {
root,
exposed: componentRef,
async setProps(patch: Record<string, unknown>) {
Object.assign(props, patch);
await nextTick();
},
unmount() {
app.unmount();
},
};
}
export function findAll(node: HostNode, predicate: (node: HostNode) => boolean): HostNode[] {
const matches: HostNode[] = [];
if (predicate(node)) matches.push(node);
for (const child of node.children) {
if (typeof child !== "string") matches.push(...findAll(child, predicate));
}
return matches;
}
export function findOne(node: HostNode, predicate: (node: HostNode) => boolean): HostNode {
const match = findAll(node, predicate)[0];
if (!match) throw new Error("Expected host node was not rendered");
return match;
}
export function hostText(node: HostNode): string {
return node.children.map((child) => (typeof child === "string" ? child : hostText(child))).join("");
}
function eventPropName(name: string) {
return `on${name[0].toUpperCase()}${name.slice(1)}`;
}
export function dispatch(node: HostNode, name: string, overrides: Record<string, unknown> = {}) {
const event = {
type: name,
target: node,
currentTarget: node,
defaultPrevented: false,
propagationStopped: false,
preventDefault() {
event.defaultPrevented = true;
},
stopPropagation() {
event.propagationStopped = true;
},
...overrides,
};
if (node.props.disabled) return event;
for (const listener of node.listeners.get(name) ?? []) listener(event);
const handler = node.props[eventPropName(name)];
for (const callback of Array.isArray(handler) ? handler : handler ? [handler] : []) callback(event);
return event;
}