Файли
openidea/src/features/database/table-editor.test.tsx
T
akshathayadav378-boopтаakshathayadav378-boop 7ec5080047 fix(database): preserve table horizontal scroll position (#4779)
Database table tabs remember their horizontal scroll offset when the tab is mounted again (more than five kept table tabs, or the table opened in a split pane), alongside the page, sort and filter they already remembered.

The offset lives in a ref and is written straight into the remembered view state, so scrolling sideways doesn't re-render the editor; the grid restores it once on mount, retrying as the columns are measured.

Co-authored-by: akshathayadav378-boop <[email protected]>
2026-11-20 18:21:33 +08:00

263 рядки
11 KiB
TypeScript

import { act, fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { DbDriver, DbTablePage } from "@/platform/ipc";
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
import { activeCellGrid, installCellActions } from "./cellActions";
import { getContext } from "@/platform/context";
import { TableEditor, _resetTableViewStates } from "./TableEditor";
import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus";
import { tableInput } from "./tableInput";
const backend = vi.hoisted(() => ({
driver: "clickhouse" as DbDriver,
page: vi.fn(),
applyEdits: vi.fn(),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/platform/ipc")>();
return { ...actual, commands: { ...actual.commands, dbTablePage: backend.page, dbApplyEdits: backend.applyEdits } };
});
vi.mock("./store", () => ({
sourceById: () => ({ driver: backend.driver, readOnly: false }),
withConnection: (_id: string, run: () => unknown) => run(),
openDialog: vi.fn(),
}));
vi.mock("@tanstack/react-virtual", () => ({
useVirtualizer: ({ count }: { count: number }) => ({
getTotalSize: () => count * 24,
getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 24, key: index })),
scrollToIndex: () => {},
}),
}));
const page: DbTablePage = {
result: {
statement: "select * from users",
columns: [
{ name: "id", typeName: "UInt64" },
{ name: "name", typeName: "String" },
],
rows: [["1", "Ann"]],
affected: null,
hasMore: false,
elapsedMs: 1,
executionMs: 1,
},
details: {
columns: [
{ name: "id", dataType: "UInt64", primaryKey: true, nullable: false, default: null },
{ name: "name", dataType: "String", primaryKey: false, nullable: false, default: null },
],
indexes: [],
foreignKeys: [],
triggers: [],
},
offset: 0,
};
beforeEach(() => {
_resetTableViewStates();
backend.driver = "clickhouse";
backend.page.mockResolvedValue({ status: "ok", data: page });
backend.applyEdits.mockClear();
});
describe("table editor capabilities", () => {
it.each(["clickhouse", "jdbc"] as const)(
"keeps %s rows read-only even when metadata marks a primary key",
async (driver) => {
backend.driver = driver;
await act(async () => {
render(<TableEditor input={tableInput("source", "default", "users")} />);
});
const cell = await screen.findByRole("gridcell", { name: "Ann" });
fireEvent.doubleClick(cell);
expect(screen.queryByRole("textbox", { name: "Edit name" })).toBeNull();
expect(screen.queryByRole("button", { name: "Add Row" })).toBeNull();
expect(screen.queryByRole("button", { name: "Submit" })).toBeNull();
expect(
screen.getByText(
driver === "jdbc"
? "Use the query console to change JDBC data."
: "Use the query console to change ClickHouse data.",
),
).toBeTruthy();
fireEvent.mouseDown(cell, { button: 0 });
fireEvent.paste(screen.getByRole("grid"), { clipboardData: { getData: () => "Changed" } });
expect(screen.getByRole("gridcell", { name: "Ann" })).toBeTruthy();
expect(backend.applyEdits).not.toHaveBeenCalled();
},
);
it("keeps keyed PostgreSQL rows editable", async () => {
backend.driver = "postgres";
await act(async () => {
render(<TableEditor input={tableInput("source", "public", "users")} />);
});
fireEvent.doubleClick(await screen.findByRole("gridcell", { name: "Ann" }));
expect(screen.getByRole("textbox", { name: "Edit name" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Add Row" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Submit" })).toBeTruthy();
});
it("offers Submit and Revert to the keyboard while the grid has focus and edits are pending (#1549)", async () => {
backend.driver = "postgres";
backend.applyEdits.mockResolvedValue({ status: "ok", data: 1 });
const uninstall = installTableEditorFocus();
try {
await act(async () => {
render(<TableEditor input={tableInput("source", "public", "users")} />);
});
const grid = screen.getByRole("grid");
act(() => grid.focus());
expect(getContext()).toMatchObject({ dbTableEditorFocus: true, dbTableEditorChanges: false });
fireEvent.doubleClick(await screen.findByRole("gridcell", { name: "Ann" }));
const input = screen.getByRole("textbox", { name: "Edit name" });
// The inline cell editor still counts as the grid: ⌘↩ confirms the cell, then submits (#2332).
expect(getContext().dbTableEditorFocus).toBe(true);
fireEvent.change(input, { target: { value: "Bob" } });
fireEvent.keyDown(input, { key: "Enter" });
act(() => grid.focus());
expect(getContext()).toMatchObject({ dbTableEditorFocus: true, dbTableEditorChanges: true });
act(() => activeTableEditor()!.revert());
expect(screen.getByRole("gridcell", { name: "Ann" })).toBeTruthy();
expect(getContext().dbTableEditorChanges).toBe(false);
fireEvent.doubleClick(screen.getByRole("gridcell", { name: "Ann" }));
fireEvent.change(screen.getByRole("textbox", { name: "Edit name" }), { target: { value: "Bob" } });
fireEvent.keyDown(screen.getByRole("textbox", { name: "Edit name" }), { key: "Enter" });
act(() => grid.focus());
await act(async () => activeTableEditor()!.submit());
expect(backend.applyEdits).toHaveBeenCalledTimes(1);
} finally {
uninstall();
}
});
it("runs the row and toolbar commands of the db.* actions on the focused grid's selection (#3506)", async () => {
backend.driver = "postgres";
const uninstallFocus = installTableEditorFocus();
const uninstallCells = installCellActions();
try {
await act(async () => {
render(<TableEditor input={tableInput("source", "public", "users")} />);
});
const cell = await screen.findByRole("gridcell", { name: "Ann" });
fireEvent.mouseDown(cell, { button: 0 });
act(() => screen.getByRole("grid").focus());
const rows = activeCellGrid()!.selectedRows();
expect(rows).toEqual([0]);
const commands = activeTableEditor()!.commands!;
expect(commands.nextPage!.enabled(rows)).toBe(false);
expect(commands.previousPage!.enabled(rows)).toBe(false);
expect(commands.exportData!.enabled(rows)).toBe(true);
expect(commands.restoreRows!.enabled(rows)).toBe(false);
act(() => commands.deleteRows!.run(rows));
expect(getContext().dbTableEditorChanges).toBe(true);
expect(activeTableEditor()!.commands!.restoreRows!.enabled(rows)).toBe(true);
act(() => activeTableEditor()!.commands!.restoreRows!.run(rows));
expect(getContext().dbTableEditorChanges).toBe(false);
act(() => activeTableEditor()!.commands!.addRow!.run([]));
expect(screen.getAllByRole("row").length).toBeGreaterThan(2);
expect(getContext().dbTableEditorChanges).toBe(true);
} finally {
uninstallCells();
uninstallFocus();
}
});
it("counts the editor-area host focusing the tab as table-editor focus (#2307)", async () => {
backend.driver = "postgres";
const uninstall = installTableEditorFocus();
try {
let root!: HTMLElement;
await act(async () => {
const r = render(<TableEditor input={tableInput("source", "public", "users")} />);
root = r.container;
});
// Mimic EditorArea wrapping the tab in its focusable host, then focusing the host on open.
const host = root.closest("div")!;
host.setAttribute("data-editor-focus", "");
host.tabIndex = -1;
act(() => host.focus());
expect(getContext()).toMatchObject({ dbTableEditorFocus: true, dbTableEditorChanges: false });
// A later focus inside a text field still turns it off.
const input = document.createElement("input");
root.querySelector("[data-db-table-editor]")!.appendChild(input);
act(() => input.focus());
expect(getContext().dbTableEditorFocus).toBe(false);
} finally {
uninstall();
}
});
});
it("omits a reset inserted cell from Submit instead of writing SQL NULL", async () => {
backend.driver = "postgres";
backend.applyEdits.mockResolvedValue({ status: "ok", data: 1 });
useKeymap.setState({ preset: "intellij-macos", overrides: {} });
const disposeActions = installCellActions();
const disposeKeys = installKeyboardDispatcher();
try {
await act(async () => {
render(<TableEditor input={tableInput("source", "public", "users")} />);
});
fireEvent.click(screen.getByRole("button", { name: "Add Row" }));
const cells = screen.getAllByRole("gridcell");
fireEvent.mouseDown(cells[2]!, { button: 0 });
fireEvent.paste(screen.getByRole("grid"), { clipboardData: { getData: () => "3\tCara" } });
fireEvent.mouseDown(cells[3]!, { button: 0 });
fireEvent.keyDown(screen.getByRole("grid"), { key: "Backspace", metaKey: true, shiftKey: true });
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: "Submit" }));
});
expect(backend.applyEdits.mock.calls[0]?.[3]).toEqual([{ kind: "insert", values: [{ column: "id", value: "3" }] }]);
} finally {
disposeKeys();
disposeActions();
}
});
describe("table editor view state", () => {
it("restores the grid's horizontal scroll position when its tab mounts again (#4775)", async () => {
const input = tableInput("source", "default", "users");
let view!: ReturnType<typeof render>;
await act(async () => {
view = render(<TableEditor input={input} />);
});
const grid = await screen.findByRole("grid");
grid.scrollLeft = 180;
fireEvent.scroll(grid);
view.unmount();
await act(async () => {
render(<TableEditor input={input} />);
});
expect((await screen.findByRole("grid")).scrollLeft).toBe(180);
});
it("queries with the sort it had when its tab mounts again", async () => {
const input = tableInput("source", "default", "users");
let view!: ReturnType<typeof render>;
await act(async () => {
view = render(<TableEditor input={input} />);
});
await screen.findByRole("gridcell", { name: "Ann" });
await act(async () => {
fireEvent.click(screen.getByRole("columnheader", { name: /name/ }));
});
const sorted = backend.page.mock.calls.at(-1)!;
expect(sorted[5]).toEqual([{ column: "name", descending: false }]);
view.unmount();
backend.page.mockClear();
await act(async () => {
render(<TableEditor input={input} />);
});
expect(backend.page.mock.calls[0]![5]).toEqual(sorted[5]);
});
});