feat(data-grid): add multi-format copy extractors
This commit is contained in:
1 parent
166027600f
commit
0b7a886cfd
60 files changed
+4615
-1766
No files matched your search
+434
-308
@@ -1,10 +1,13 @@
|
||||
import { computed, ref } from "vue";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useDataGridExport, type UseDataGridExportOptions } from "@/composables/useDataGridExport";
|
||||
import { buildDataGridCopyInsertStatement, buildDataGridCopyUpdateStatements } from "@/lib/dataGrid/dataGridSql";
|
||||
import { buildDataGridCopyUpdateStatements } from "@/lib/dataGrid/dataGridSql";
|
||||
import { copyToClipboard } from "@/lib/common/clipboard";
|
||||
import type { DataGridTableMeta } from "@/lib/dataGrid/dataGridSql";
|
||||
import type { CellSelectionMatrix } from "@/lib/dataGrid/gridSelection";
|
||||
import type { CellSelectionMatrix, SelectionData } from "@/lib/dataGrid/gridSelection";
|
||||
import { extractDataGridSelection } from "@/lib/backend/api";
|
||||
import { DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS } from "@/lib/dataGrid/dataGridCopyExtractor";
|
||||
import { clearDataGridClipboardCopy, parseDataGridClipboard } from "@/lib/dataGrid/dataGridClipboard";
|
||||
|
||||
const toast = vi.fn();
|
||||
|
||||
@@ -16,34 +19,29 @@ vi.mock("@/composables/useToast", () => ({
|
||||
useToast: () => ({ toast }),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/common/clipboard", () => ({
|
||||
copyToClipboard: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/lib/common/clipboard", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("@/lib/common/clipboard")>();
|
||||
return {
|
||||
...original,
|
||||
copyToClipboard: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/lib/dataGrid/dataGridSql", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("@/lib/dataGrid/dataGridSql")>();
|
||||
return {
|
||||
...original,
|
||||
buildDataGridCopyInsertStatement: vi.fn(),
|
||||
buildDataGridCopyUpdateStatements: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
interface Deferred<T> {
|
||||
promise: Promise<T>;
|
||||
resolve: (value: T) => void;
|
||||
reject: (error: unknown) => void;
|
||||
}
|
||||
|
||||
function deferred<T>(): Deferred<T> {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: unknown) => void;
|
||||
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
|
||||
resolve = resolvePromise;
|
||||
reject = rejectPromise;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
vi.mock("@/lib/backend/api", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("@/lib/backend/api")>();
|
||||
return {
|
||||
...original,
|
||||
extractDataGridSelection: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
function row(data: unknown[]) {
|
||||
return {
|
||||
@@ -89,6 +87,7 @@ function createMongoExportState(options: {
|
||||
selectedCellMatrix: computed(() => options.selectedCellMatrix ?? null),
|
||||
selectedRange: computed(() => null),
|
||||
contextCell: ref({ rowId: options.item.id, rowIndex: 0, col: -1 }),
|
||||
contextSelectionIsSynthetic: ref(false),
|
||||
getRowItem: (rowId) => items.find((item) => item.id === rowId),
|
||||
selectedRowIds: ref(selectedRowIds),
|
||||
hasRowSelection: computed(() => selectedRowIds.size > 0),
|
||||
@@ -96,11 +95,25 @@ function createMongoExportState(options: {
|
||||
return useDataGridExport(state);
|
||||
}
|
||||
|
||||
function createExportState(tableMeta: DataGridTableMeta, columns = tableMeta.columns?.map((column) => column.name) ?? ["id", "name"], selectedCellMatrix?: CellSelectionMatrix) {
|
||||
const item = row(columns.map((column, index) => (column === "id" ? 1 : `value-${index}`)));
|
||||
function createExportState(
|
||||
tableMeta: DataGridTableMeta,
|
||||
columns = tableMeta.columns?.map((column) => column.name) ?? ["id", "name"],
|
||||
selectedCellMatrix?: CellSelectionMatrix,
|
||||
rowData?: unknown[],
|
||||
selectedCellsOverride?: SelectionData,
|
||||
rowDataList?: unknown[][],
|
||||
selectedRowIdValues: number[] = [],
|
||||
extractorOptions = DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS,
|
||||
hasColumnSelection = false,
|
||||
visibleColumnIndexes?: number[],
|
||||
isSyntheticContext = false,
|
||||
) {
|
||||
const rows = (rowDataList ?? [rowData ?? columns.map((column, index) => (column === "id" ? 1 : `value-${index}`))]).map((data, index) => ({ ...row(data), id: index + 1 }));
|
||||
const item = rows[0]!;
|
||||
const selectedRowIds = ref(new Set(selectedRowIdValues));
|
||||
const options: UseDataGridExportOptions = {
|
||||
columns: computed(() => columns),
|
||||
displayItems: computed(() => [item]),
|
||||
displayItems: computed(() => rows),
|
||||
sql: computed(() => undefined),
|
||||
tableMeta: computed(() => tableMeta),
|
||||
databaseType: computed(() => "mysql"),
|
||||
@@ -108,18 +121,22 @@ function createExportState(tableMeta: DataGridTableMeta, columns = tableMeta.col
|
||||
database: computed(() => "dbx"),
|
||||
context: computed(() => "table-data"),
|
||||
sourceColumns: computed(() => columns),
|
||||
visibleColumnIndexes: computed(() => visibleColumnIndexes ?? columns.map((_, index) => index)),
|
||||
columnTypes: computed(() => columns.map(() => "varchar")),
|
||||
extractorOptions: computed(() => extractorOptions),
|
||||
whereInput: computed(() => undefined),
|
||||
orderBy: computed(() => undefined),
|
||||
exportBatchSize: computed(() => 1000),
|
||||
hasCellSelection: computed(() => !!selectedCellMatrix),
|
||||
selectedCells: computed(() => selectedCellMatrix ?? { columns: [], rows: [] }),
|
||||
hasCellSelection: computed(() => !!selectedCellMatrix || !!selectedCellsOverride),
|
||||
hasColumnSelection: computed(() => hasColumnSelection),
|
||||
selectedCells: computed(() => selectedCellMatrix ?? selectedCellsOverride ?? { columns: [], rows: [] }),
|
||||
selectedCellMatrix: computed(() => selectedCellMatrix ?? null),
|
||||
selectedRange: computed(() => null),
|
||||
contextCell: ref({ rowId: item.id, rowIndex: 0, col: -1 }),
|
||||
getRowItem: (rowId) => (rowId === item.id ? item : undefined),
|
||||
selectedRowIds: ref(new Set<number>()),
|
||||
hasRowSelection: computed(() => false),
|
||||
contextCell: ref({ rowId: item.id, rowIndex: 0, col: isSyntheticContext ? 0 : -1 }),
|
||||
contextSelectionIsSynthetic: ref(isSyntheticContext),
|
||||
getRowItem: (rowId) => rows.find((candidate) => candidate.id === rowId),
|
||||
selectedRowIds,
|
||||
hasRowSelection: computed(() => selectedRowIds.value.size > 0),
|
||||
};
|
||||
return useDataGridExport(options);
|
||||
}
|
||||
@@ -136,114 +153,24 @@ const editableTable: DataGridTableMeta = {
|
||||
describe("useDataGridExport prepared row statements", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
clearDataGridClipboardCopy();
|
||||
});
|
||||
|
||||
it("reuses an in-flight INSERT prefetch when the copy action runs", async () => {
|
||||
const pending = deferred<string | undefined>();
|
||||
vi.mocked(buildDataGridCopyInsertStatement).mockReturnValueOnce(pending.promise);
|
||||
const state = createExportState(editableTable);
|
||||
|
||||
const prefetch = state.prefetchRowAsInsertStatement(false);
|
||||
const copy = state.copyRowAsInsert();
|
||||
await vi.waitFor(() => expect(buildDataGridCopyInsertStatement).toHaveBeenCalledTimes(1));
|
||||
pending.resolve("INSERT INTO users VALUES (1, 'Alice');");
|
||||
|
||||
await Promise.all([prefetch, copy]);
|
||||
expect(copyToClipboard).toHaveBeenCalledWith("INSERT INTO users VALUES (1, 'Alice');");
|
||||
});
|
||||
|
||||
it("reuses an in-flight UPDATE prefetch on the first copy action", async () => {
|
||||
const pending = deferred<string[]>();
|
||||
vi.mocked(buildDataGridCopyUpdateStatements).mockReturnValueOnce(pending.promise);
|
||||
const state = createExportState(editableTable);
|
||||
|
||||
const prefetch = state.prefetchRowAsUpdateStatement();
|
||||
const copy = state.copyRowAsUpdate();
|
||||
await vi.waitFor(() => expect(buildDataGridCopyUpdateStatements).toHaveBeenCalledTimes(1));
|
||||
pending.resolve(["UPDATE users SET name = 'Alice' WHERE id = 1;"]);
|
||||
|
||||
await Promise.all([prefetch, copy]);
|
||||
expect(copyToClipboard).toHaveBeenCalledWith("UPDATE users SET name = 'Alice' WHERE id = 1;");
|
||||
});
|
||||
|
||||
it.each(["GENERATED ALWAYS AS (1)", "IDENTITY(1, 1)"])("disables copy-as-insert when every result column is non-insertable (%s)", (extra) => {
|
||||
const state = createExportState(
|
||||
{
|
||||
tableName: "generated_values",
|
||||
primaryKeys: [],
|
||||
columns: [{ name: "computed_value", data_type: "int", is_nullable: true, extra }],
|
||||
},
|
||||
["computed_value"],
|
||||
);
|
||||
|
||||
expect(state.canCopyRowAsInsert.value).toBe(false);
|
||||
});
|
||||
|
||||
it("reports a shared builder failure when the user invokes copy", async () => {
|
||||
const pending = deferred<string | undefined>();
|
||||
vi.mocked(buildDataGridCopyInsertStatement).mockReturnValueOnce(pending.promise);
|
||||
const state = createExportState(editableTable);
|
||||
|
||||
const prefetch = state.prefetchRowAsInsertStatement(false);
|
||||
const copy = state.copyRowAsInsert();
|
||||
await vi.waitFor(() => expect(buildDataGridCopyInsertStatement).toHaveBeenCalledTimes(1));
|
||||
pending.reject(new Error("builder unavailable"));
|
||||
|
||||
await Promise.all([prefetch, copy]);
|
||||
expect(toast).toHaveBeenCalledWith("grid.copyFailed: builder unavailable", 5000);
|
||||
expect(copyToClipboard).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports an UPDATE builder failure from the first copy action", async () => {
|
||||
const pending = deferred<string[]>();
|
||||
vi.mocked(buildDataGridCopyUpdateStatements).mockReturnValueOnce(pending.promise);
|
||||
const state = createExportState(editableTable);
|
||||
|
||||
const prefetch = state.prefetchRowAsUpdateStatement();
|
||||
const copy = state.copyRowAsUpdate();
|
||||
await vi.waitFor(() => expect(buildDataGridCopyUpdateStatements).toHaveBeenCalledTimes(1));
|
||||
pending.reject(new Error("update builder unavailable"));
|
||||
|
||||
await Promise.all([prefetch, copy]);
|
||||
expect(toast).toHaveBeenCalledWith("grid.copyFailed: update builder unavailable", 5000);
|
||||
expect(copyToClipboard).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports selection INSERT prefetch failures", async () => {
|
||||
it("builds SQL UPDATE from only selected writable columns while retaining a hidden primary key", async () => {
|
||||
const item = row([7, "Ada", true]);
|
||||
const matrix: CellSelectionMatrix = {
|
||||
rowIndexes: [0],
|
||||
columnIndexes: [1],
|
||||
columns: ["name"],
|
||||
rows: [["value-1"]],
|
||||
};
|
||||
vi.mocked(buildDataGridCopyInsertStatement).mockRejectedValueOnce(new Error("selection builder unavailable"));
|
||||
const state = createExportState(editableTable, ["id", "name"], matrix);
|
||||
|
||||
await state.prefetchSelectionAsInsertStatement();
|
||||
|
||||
expect(toast).toHaveBeenCalledTimes(1);
|
||||
expect(toast).toHaveBeenCalledWith("grid.copyFailed: selection builder unavailable", 5000);
|
||||
expect(state.canCopyPreparedSelectionInsert()).toBe(false);
|
||||
expect(copyToClipboard).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("builds selection INSERT statements from only the selected source columns and rows", async () => {
|
||||
const items = [
|
||||
{ ...row([1, "Ada", true, "math"]), id: 1 },
|
||||
{ ...row([2, "Grace", false, "compiler"]), id: 2 },
|
||||
];
|
||||
const matrix: CellSelectionMatrix = {
|
||||
rowIndexes: [0, 1],
|
||||
columnIndexes: [1, 3],
|
||||
columns: ["display_name", "display_note"],
|
||||
rows: [
|
||||
["Ada", "math"],
|
||||
["Grace", "compiler"],
|
||||
],
|
||||
columns: ["active"],
|
||||
rows: [[true]],
|
||||
};
|
||||
const options: UseDataGridExportOptions = {
|
||||
columns: computed(() => ["id", "display_name", "active", "display_note"]),
|
||||
displayItems: computed(() => items),
|
||||
columns: computed(() => ["display_name", "active"]),
|
||||
displayItems: computed(() => [{ ...item, data: ["Ada", true], isDirtyCol: [false, false] }]),
|
||||
allColumns: computed(() => ["id", "display_name", "active"]),
|
||||
allDisplayItems: computed(() => [item]),
|
||||
allSourceColumns: computed(() => ["id", "name", "active"]),
|
||||
visibleColumnIndexes: computed(() => [1, 2]),
|
||||
sql: computed(() => undefined),
|
||||
tableMeta: computed(() => ({
|
||||
tableName: "users",
|
||||
@@ -252,52 +179,386 @@ describe("useDataGridExport prepared row statements", () => {
|
||||
{ name: "id", data_type: "int", is_nullable: false, is_primary_key: true },
|
||||
{ name: "name", data_type: "varchar", is_nullable: false },
|
||||
{ name: "active", data_type: "boolean", is_nullable: false },
|
||||
{ name: "note", data_type: "text", is_nullable: true },
|
||||
],
|
||||
})),
|
||||
databaseType: computed(() => "mysql"),
|
||||
connectionId: computed(() => "connection-1"),
|
||||
database: computed(() => "dbx"),
|
||||
context: computed(() => "table-data"),
|
||||
sourceColumns: computed(() => ["id", "name", "active", "note"]),
|
||||
columnTypes: computed(() => ["int", "varchar", "boolean", "text"]),
|
||||
sourceColumns: computed(() => ["name", "active"]),
|
||||
columnTypes: computed(() => ["varchar", "boolean"]),
|
||||
whereInput: computed(() => undefined),
|
||||
orderBy: computed(() => undefined),
|
||||
exportBatchSize: computed(() => 1000),
|
||||
hasCellSelection: computed(() => true),
|
||||
selectedCells: computed(() => matrix),
|
||||
selectedCellMatrix: computed(() => matrix),
|
||||
selectedRange: computed(() => ({ startRow: 0, endRow: 1, startCol: 1, endCol: 3 })),
|
||||
contextCell: ref({ rowId: 1, rowIndex: 0, col: 1 }),
|
||||
getRowItem: (rowId) => items.find((item) => item.id === rowId),
|
||||
selectedRange: computed(() => ({ startRow: 0, endRow: 0, startCol: 1, endCol: 1 })),
|
||||
contextCell: ref({ rowId: item.id, rowIndex: 0, col: 1 }),
|
||||
contextSelectionIsSynthetic: ref(false),
|
||||
getRowItem: (rowId) => (rowId === item.id ? item : undefined),
|
||||
selectedRowIds: ref(new Set<number>()),
|
||||
hasRowSelection: computed(() => false),
|
||||
};
|
||||
const pending = deferred<string | undefined>();
|
||||
vi.mocked(buildDataGridCopyInsertStatement).mockReturnValueOnce(pending.promise);
|
||||
vi.mocked(extractDataGridSelection).mockResolvedValueOnce({
|
||||
text: "UPDATE users SET active = TRUE WHERE id = 7;",
|
||||
mimeType: "application/sql",
|
||||
fileExtension: "sql",
|
||||
rowCount: 1,
|
||||
columnCount: 1,
|
||||
});
|
||||
const state = useDataGridExport(options);
|
||||
|
||||
const copy = state.copySelectionAsInsert("merged");
|
||||
await vi.waitFor(() => expect(buildDataGridCopyInsertStatement).toHaveBeenCalledTimes(1));
|
||||
expect(copyToClipboard).not.toHaveBeenCalled();
|
||||
pending.resolve("INSERT INTO users (name, note) VALUES ('Ada', 'math'), ('Grace', 'compiler');");
|
||||
await copy;
|
||||
expect(state.canCopyPreparedSelectionInsert("merged")).toBe(true);
|
||||
expect(state.canCopyWithExtractor("sql-updates")).toBe(true);
|
||||
await state.copyWithExtractor("sql-updates");
|
||||
|
||||
expect(buildDataGridCopyInsertStatement).toHaveBeenCalledWith(
|
||||
expect(extractDataGridSelection).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
columns: ["display_name", "display_note"],
|
||||
sourceColumns: ["name", "note"],
|
||||
columnTypes: ["varchar", "text"],
|
||||
rows: [
|
||||
["Ada", "math"],
|
||||
["Grace", "compiler"],
|
||||
],
|
||||
excludePrimaryKeys: false,
|
||||
insertMode: "merged",
|
||||
extractor: "sql-updates",
|
||||
selectedColumnIndexes: [0],
|
||||
rows: [[true, 7]],
|
||||
selectionKind: "cells",
|
||||
}),
|
||||
);
|
||||
expect(copyToClipboard).toHaveBeenCalledWith("INSERT INTO users (name, note) VALUES ('Ada', 'math'), ('Grace', 'compiler');");
|
||||
expect(copyToClipboard).toHaveBeenCalledWith("UPDATE users SET active = TRUE WHERE id = 7;");
|
||||
});
|
||||
|
||||
it("preserves drag-reordered visible column order when copying", async () => {
|
||||
vi.mocked(extractDataGridSelection).mockResolvedValue({ text: "x", mimeType: "text/csv", fileExtension: "csv", rowCount: 1, columnCount: 3 });
|
||||
const matrix: CellSelectionMatrix = {
|
||||
rowIndexes: [0],
|
||||
columnIndexes: [0, 1, 2],
|
||||
columns: ["id", "name", "note"],
|
||||
rows: [[1, "Ada", "x"]],
|
||||
};
|
||||
// User dragged columns into note, id, name order (source indexes 2, 0, 1).
|
||||
const state = createExportState(editableTable, ["id", "name", "note"], matrix, undefined, undefined, undefined, [], DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS, false, [2, 0, 1]);
|
||||
await state.copyWithExtractor("csv");
|
||||
|
||||
expect(extractDataGridSelection).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
columns: [expect.objectContaining({ displayName: "note" }), expect.objectContaining({ displayName: "id" }), expect.objectContaining({ displayName: "name" })],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("excludes hidden columns and keeps visible order when copying", async () => {
|
||||
vi.mocked(extractDataGridSelection).mockResolvedValue({ text: "x", mimeType: "text/csv", fileExtension: "csv", rowCount: 1, columnCount: 2 });
|
||||
const matrix: CellSelectionMatrix = {
|
||||
rowIndexes: [0],
|
||||
columnIndexes: [0, 1],
|
||||
columns: ["note", "id"],
|
||||
rows: [["x", 1]],
|
||||
};
|
||||
// Columns id/name/note; "name" is hidden, so visible order is note, id (source 2, 0).
|
||||
const state = createExportState(editableTable, ["id", "name", "note"], matrix, undefined, undefined, undefined, [], DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS, false, [2, 0]);
|
||||
await state.copyWithExtractor("csv");
|
||||
|
||||
expect(extractDataGridSelection).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
columns: [expect.objectContaining({ displayName: "note" }), expect.objectContaining({ displayName: "id" })],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("copies the full row when right-clicking a cell with a synthetic single-cell selection", async () => {
|
||||
vi.mocked(extractDataGridSelection).mockResolvedValue({ text: "x", mimeType: "text/csv", fileExtension: "csv", rowCount: 1, columnCount: 3 });
|
||||
// A synthetic 1×1 selection (what right-click creates) — only column 0 of row 0.
|
||||
const matrix: CellSelectionMatrix = {
|
||||
rowIndexes: [0],
|
||||
columnIndexes: [0],
|
||||
columns: ["id"],
|
||||
rows: [[1]],
|
||||
};
|
||||
const state = createExportState(editableTable, ["id", "name", "note"], matrix, undefined, undefined, undefined, [], DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS, false, [0, 1, 2], true);
|
||||
await state.copyWithExtractor("csv");
|
||||
|
||||
// Despite the 1×1 matrix, the context-cell fallback should produce a full-row request (3 columns).
|
||||
expect(extractDataGridSelection).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
columns: [expect.objectContaining({ displayName: "id" }), expect.objectContaining({ displayName: "name" }), expect.objectContaining({ displayName: "note" })],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("copies only the selected cell for a genuine 1×1 selection (not synthetic)", async () => {
|
||||
vi.mocked(extractDataGridSelection).mockResolvedValue({ text: "x", mimeType: "text/csv", fileExtension: "csv", rowCount: 1, columnCount: 1 });
|
||||
// A genuine 1×1 selection (user Ctrl+click) — column 1 of row 0.
|
||||
const matrix: CellSelectionMatrix = {
|
||||
rowIndexes: [0],
|
||||
columnIndexes: [1],
|
||||
columns: ["name"],
|
||||
rows: [["Ada"]],
|
||||
};
|
||||
// isSyntheticContext = false → should NOT use the context-cell full-row fallback.
|
||||
const state = createExportState(editableTable, ["id", "name", "note"], matrix, undefined, undefined, undefined, [], DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS, false, [0, 1, 2], false);
|
||||
await state.copyWithExtractor("csv");
|
||||
|
||||
expect(extractDataGridSelection).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
columns: [expect.objectContaining({ displayName: "name" })],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves the effective row-header TSV matrix across copy and paste", async () => {
|
||||
const rows = [
|
||||
[1, null],
|
||||
[2, "inside\ttab\nnext line"],
|
||||
];
|
||||
const matrix: CellSelectionMatrix = {
|
||||
rowIndexes: [0, 1],
|
||||
columnIndexes: [0, 1],
|
||||
columns: ["id", "name"],
|
||||
rows,
|
||||
};
|
||||
const extractorOptions = {
|
||||
...DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS,
|
||||
dsv: { ...DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS.dsv, includeColumnHeader: true, includeRowHeader: true },
|
||||
};
|
||||
const text = '#\tid\tname\n1\t1\tNULL\n2\t2\t"inside\ttab\nnext line"';
|
||||
vi.mocked(extractDataGridSelection).mockResolvedValueOnce({ text, mimeType: "text/tab-separated-values", fileExtension: "tsv", rowCount: 2, columnCount: 3 });
|
||||
const state = createExportState(editableTable, ["id", "name"], matrix, undefined, undefined, rows, [], extractorOptions);
|
||||
|
||||
await expect(state.copyWithExtractor("tsv-with-headers")).resolves.toBe(true);
|
||||
|
||||
expect(parseDataGridClipboard(text)).toEqual([
|
||||
["#", "id", "name"],
|
||||
["1", "1", null],
|
||||
["2", "2", "inside\ttab\nnext line"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects SQL UPDATE when the selection contains no writable non-key column", () => {
|
||||
const matrix: CellSelectionMatrix = {
|
||||
rowIndexes: [0],
|
||||
columnIndexes: [0],
|
||||
columns: ["id"],
|
||||
rows: [[1]],
|
||||
};
|
||||
const state = createExportState(editableTable, ["id", "name"], matrix);
|
||||
|
||||
expect(state.canCopyWithExtractor("sql-updates")).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects SQL UPDATE when the only selected value is generated", () => {
|
||||
const tableMeta: DataGridTableMeta = {
|
||||
tableName: "users",
|
||||
primaryKeys: ["id"],
|
||||
columns: [
|
||||
{ name: "id", data_type: "int", is_nullable: false, is_primary_key: true },
|
||||
{ name: "search_text", data_type: "text", is_nullable: true, extra: "GENERATED ALWAYS AS" },
|
||||
],
|
||||
};
|
||||
const matrix: CellSelectionMatrix = {
|
||||
rowIndexes: [0],
|
||||
columnIndexes: [1],
|
||||
columns: ["search_text"],
|
||||
rows: [["generated"]],
|
||||
};
|
||||
const state = createExportState(tableMeta, ["id", "search_text"], matrix, [1, "generated"]);
|
||||
|
||||
expect(state.canCopyWithExtractor("sql-updates")).toBe(false);
|
||||
});
|
||||
|
||||
it("allows a computed SQL UPDATE only after the user disables computed-column skipping", () => {
|
||||
const tableMeta: DataGridTableMeta = {
|
||||
tableName: "users",
|
||||
primaryKeys: ["id"],
|
||||
columns: [
|
||||
{ name: "id", data_type: "int", is_nullable: false, is_primary_key: true },
|
||||
{ name: "search_text", data_type: "text", is_nullable: true, extra: "GENERATED ALWAYS AS" },
|
||||
],
|
||||
};
|
||||
const matrix: CellSelectionMatrix = {
|
||||
rowIndexes: [0],
|
||||
columnIndexes: [1],
|
||||
columns: ["search_text"],
|
||||
rows: [["generated"]],
|
||||
};
|
||||
const extractorOptions = {
|
||||
...DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS,
|
||||
sql: { ...DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS.sql, skipComputedColumns: false },
|
||||
};
|
||||
const state = createExportState(tableMeta, ["id", "search_text"], matrix, [1, "generated"], undefined, undefined, [], extractorOptions);
|
||||
|
||||
expect(state.canCopyWithExtractor("sql-updates")).toBe(true);
|
||||
});
|
||||
|
||||
it("uses current SQL options when deciding whether INSERT is available", () => {
|
||||
const computedTable: DataGridTableMeta = {
|
||||
tableName: "users",
|
||||
primaryKeys: [],
|
||||
columns: [{ name: "search_text", data_type: "text", is_nullable: true, extra: "GENERATED ALWAYS AS" }],
|
||||
};
|
||||
const matrix: CellSelectionMatrix = { rowIndexes: [0], columnIndexes: [0], columns: ["search_text"], rows: [["generated"]] };
|
||||
const includeComputed = {
|
||||
...DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS,
|
||||
sql: { ...DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS.sql, skipComputedColumns: false },
|
||||
};
|
||||
|
||||
expect(createExportState(computedTable, ["search_text"], matrix).canCopyWithExtractor("sql-inserts")).toBe(false);
|
||||
expect(createExportState(computedTable, ["search_text"], matrix, undefined, undefined, undefined, [], includeComputed).canCopyWithExtractor("sql-inserts")).toBe(true);
|
||||
});
|
||||
|
||||
it("disables INSERT when primary-key exclusion removes every selected column", () => {
|
||||
const matrix: CellSelectionMatrix = { rowIndexes: [0], columnIndexes: [0], columns: ["id"], rows: [[1]] };
|
||||
const excludePrimaryKeys = {
|
||||
...DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS,
|
||||
sql: { ...DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS.sql, skipGeneratedColumns: false, excludePrimaryKeysFromInsert: true },
|
||||
};
|
||||
|
||||
const state = createExportState(editableTable, ["id"], matrix, [1], undefined, undefined, [], excludePrimaryKeys);
|
||||
|
||||
expect(state.canCopyWithExtractor("sql-inserts")).toBe(false);
|
||||
});
|
||||
|
||||
it("sends only selected values for non-SQL extraction and marks column selections", async () => {
|
||||
const matrix: CellSelectionMatrix = { rowIndexes: [0], columnIndexes: [1], columns: ["name"], rows: [["Ada"]] };
|
||||
vi.mocked(extractDataGridSelection).mockResolvedValueOnce({
|
||||
text: '[{"name":"Ada"}]',
|
||||
mimeType: "application/json",
|
||||
fileExtension: "json",
|
||||
rowCount: 1,
|
||||
columnCount: 1,
|
||||
});
|
||||
const state = createExportState(editableTable, ["id", "name"], matrix, [7, "Ada"], undefined, undefined, [], DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS, true);
|
||||
|
||||
await state.copyWithExtractor("json");
|
||||
|
||||
const request = vi.mocked(extractDataGridSelection).mock.calls[0]?.[0];
|
||||
expect(request).toEqual(
|
||||
expect.objectContaining({
|
||||
columns: [{ displayName: "name", sourceName: "name", sourceIndex: 0 }],
|
||||
selectedColumnIndexes: [0],
|
||||
rows: [["Ada"]],
|
||||
selectionKind: "columns",
|
||||
}),
|
||||
);
|
||||
expect(request?.databaseType).toBeUndefined();
|
||||
expect(request?.tableMeta).toBeUndefined();
|
||||
});
|
||||
|
||||
it("surfaces extractor warnings after copying", async () => {
|
||||
const matrix: CellSelectionMatrix = { rowIndexes: [0], columnIndexes: [0], columns: ["id"], rows: [[1]] };
|
||||
vi.mocked(extractDataGridSelection).mockResolvedValueOnce({
|
||||
text: "1",
|
||||
mimeType: "text/plain",
|
||||
fileExtension: "txt",
|
||||
rowCount: 1,
|
||||
columnCount: 1,
|
||||
warnings: [{ code: "omitted-columns", message: "backend text" }],
|
||||
});
|
||||
const state = createExportState(editableTable, ["id"], matrix, [1]);
|
||||
|
||||
await state.copyWithExtractor("pretty");
|
||||
|
||||
expect(toast).toHaveBeenCalledWith("grid.copyExtractorWarningOmittedColumns", 5000);
|
||||
});
|
||||
|
||||
it("reports extractor copy failure without presenting post-copy warnings", async () => {
|
||||
const matrix: CellSelectionMatrix = { rowIndexes: [0], columnIndexes: [0], columns: ["id"], rows: [[1]] };
|
||||
vi.mocked(extractDataGridSelection).mockResolvedValueOnce({
|
||||
text: "1",
|
||||
mimeType: "text/plain",
|
||||
fileExtension: "txt",
|
||||
rowCount: 1,
|
||||
columnCount: 1,
|
||||
warnings: [{ code: "omitted-columns", message: "backend text" }],
|
||||
});
|
||||
vi.mocked(copyToClipboard).mockRejectedValueOnce(new Error("clipboard unavailable"));
|
||||
const state = createExportState(editableTable, ["id"], matrix, [1]);
|
||||
|
||||
await expect(state.copyWithExtractor("pretty")).resolves.toBe(false);
|
||||
|
||||
expect(toast).toHaveBeenCalledWith("grid.copyFailed: clipboard unavailable", 5000);
|
||||
expect(toast).not.toHaveBeenCalledWith("grid.copyExtractorWarningOmittedColumns", 5000);
|
||||
});
|
||||
|
||||
it("rejects irregular discrete cell selections before building an extractor request", async () => {
|
||||
const state = createExportState(editableTable, ["id", "name"], undefined, undefined, {
|
||||
columns: ["id", "name"],
|
||||
rows: [[1], ["Grace"]],
|
||||
});
|
||||
|
||||
expect(state.canCopyWithExtractor("json")).toBe(false);
|
||||
await expect(state.copyWithExtractor("json")).resolves.toBe(false);
|
||||
expect(extractDataGridSelection).not.toHaveBeenCalled();
|
||||
expect(toast).toHaveBeenCalledWith("grid.copyExtractorUnsupportedSelection", 5000);
|
||||
});
|
||||
|
||||
it("limits live extractor previews to the first 100 selected rows", async () => {
|
||||
const rows = Array.from({ length: 101 }, (_, index) => [index + 1, `name-${index + 1}`]);
|
||||
const matrix: CellSelectionMatrix = {
|
||||
rowIndexes: rows.map((_, index) => index),
|
||||
columnIndexes: [0, 1],
|
||||
columns: ["id", "name"],
|
||||
rows,
|
||||
};
|
||||
vi.mocked(extractDataGridSelection).mockResolvedValueOnce({
|
||||
text: "preview",
|
||||
mimeType: "text/csv",
|
||||
fileExtension: "csv",
|
||||
rowCount: 100,
|
||||
columnCount: 2,
|
||||
});
|
||||
const state = createExportState(editableTable, ["id", "name"], matrix, undefined, undefined, rows);
|
||||
|
||||
const preview = await state.previewWithExtractor("csv", DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS);
|
||||
|
||||
expect(vi.mocked(extractDataGridSelection).mock.calls[0]?.[0].rows).toHaveLength(100);
|
||||
expect(preview).toEqual(expect.objectContaining({ sourceRowCount: 101, truncated: true }));
|
||||
});
|
||||
|
||||
it("builds row extractor requests from selected row ids in display order", async () => {
|
||||
vi.mocked(extractDataGridSelection).mockResolvedValueOnce({
|
||||
text: '[{"id":1,"name":"Ada"},{"id":3,"name":"Linus"}]',
|
||||
mimeType: "application/json",
|
||||
fileExtension: "json",
|
||||
rowCount: 2,
|
||||
columnCount: 2,
|
||||
});
|
||||
const state = createExportState(
|
||||
editableTable,
|
||||
["id", "name"],
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
[
|
||||
[1, "Ada"],
|
||||
[2, "Grace"],
|
||||
[3, "Linus"],
|
||||
],
|
||||
[3, 1],
|
||||
);
|
||||
|
||||
await expect(state.copyWithExtractor("json")).resolves.toBe(true);
|
||||
|
||||
expect(extractDataGridSelection).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
extractor: "json",
|
||||
selectedColumnIndexes: [0, 1],
|
||||
rows: [
|
||||
[1, "Ada"],
|
||||
[3, "Linus"],
|
||||
],
|
||||
selectionKind: "rows",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects SQL UPDATE instead of silently skipping a row with a null primary key", async () => {
|
||||
const matrix: CellSelectionMatrix = {
|
||||
rowIndexes: [0],
|
||||
columnIndexes: [1],
|
||||
columns: ["name"],
|
||||
rows: [["Ada"]],
|
||||
};
|
||||
const state = createExportState(editableTable, ["id", "name"], matrix, [null, "Ada"]);
|
||||
|
||||
expect(state.canCopyWithExtractor("sql-updates")).toBe(false);
|
||||
await expect(state.copyWithExtractor("sql-updates")).resolves.toBe(false);
|
||||
expect(buildDataGridCopyUpdateStatements).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("copies Mongo JSON from the original document using the sorted source index and visible columns", async () => {
|
||||
@@ -316,122 +577,12 @@ describe("useDataGridExport prepared row statements", () => {
|
||||
expect(copyToClipboard).toHaveBeenCalledWith(JSON.stringify({ booleanText: "true", profile: { role: "admin" } }, null, 2));
|
||||
});
|
||||
|
||||
it("preserves original Mongo string types in INSERT and applies explicit edits", async () => {
|
||||
const item = { ...row(["123", "true", '{"kind":"literal"}', "2024-01-01 00:00:00", '{"role":"maintainer"}', 'ISODate("2025-05-06T08:35:32Z")']), sourceIndex: 0 };
|
||||
item.isDirtyCol = [false, false, false, false, true, false];
|
||||
it("uses the Mongo insert formatter for extractor copy and preview", async () => {
|
||||
const item = { ...row(["123", "true"]), sourceIndex: 0 };
|
||||
const state = createMongoExportState({
|
||||
columns: ["numericText", "booleanText", "jsonText", "dateText", "profile", "lastUpdatedDate"],
|
||||
columns: ["numericText", "booleanText"],
|
||||
item,
|
||||
mongoDocuments: [
|
||||
{
|
||||
numericText: "123",
|
||||
booleanText: "true",
|
||||
jsonText: '{"kind":"literal"}',
|
||||
dateText: "2024-01-01 00:00:00",
|
||||
profile: { role: "admin" },
|
||||
lastUpdatedDate: { $date: "2025-05-06T08:35:32Z" },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await state.copyRowAsInsert();
|
||||
|
||||
expect(copyToClipboard).toHaveBeenCalledWith(`db.getCollection("documents").insert({
|
||||
"numericText": "123",
|
||||
"booleanText": "true",
|
||||
"jsonText": "{\\"kind\\":\\"literal\\"}",
|
||||
"dateText": "2024-01-01 00:00:00",
|
||||
"profile": {
|
||||
"role": "maintainer"
|
||||
},
|
||||
"lastUpdatedDate": ISODate("2025-05-06T08:35:32Z")
|
||||
});`);
|
||||
});
|
||||
|
||||
it("copies a Mongo row as updateOne while preserving BSON types and missing fields", async () => {
|
||||
const item = {
|
||||
...row(["507f1f77bcf86cd799439011", "123", 'NumberLong("9007199254740993")', null, null, '{"role":"maintainer"}', "12.34", "AQI="]),
|
||||
sourceIndex: 0,
|
||||
};
|
||||
item.isDirtyCol = [false, false, false, false, false, true, false, false];
|
||||
const state = createMongoExportState({
|
||||
columns: ["_id", "numericText", "counter", "nullable", "missing", "profile", "decimal", "payload"],
|
||||
item,
|
||||
mongoDocuments: [
|
||||
{
|
||||
_id: { $oid: "507f1f77bcf86cd799439011" },
|
||||
numericText: "123",
|
||||
counter: { $numberLong: "9007199254740993" },
|
||||
nullable: null,
|
||||
profile: { role: "admin" },
|
||||
decimal: { $numberDecimal: "12.34" },
|
||||
payload: { $binary: { base64: "AQI=", subType: "00" } },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(state.canCopyRowAsUpdate.value).toBe(true);
|
||||
await state.copyRowAsUpdate();
|
||||
|
||||
expect(buildDataGridCopyUpdateStatements).not.toHaveBeenCalled();
|
||||
const copied = vi.mocked(copyToClipboard).mock.calls[0]?.[0] ?? "";
|
||||
expect(copied).toContain('db.getCollection("documents")');
|
||||
expect(copied).toContain(".updateOne(");
|
||||
expect(copied).toContain('"_id": ObjectId("507f1f77bcf86cd799439011")');
|
||||
expect(copied).toContain('"numericText": "123"');
|
||||
expect(copied).toContain('"counter": NumberLong("9007199254740993")');
|
||||
expect(copied).toContain('"nullable": null');
|
||||
expect(copied).toContain('"profile":');
|
||||
expect(copied).toContain('"role": "maintainer"');
|
||||
expect(copied).toContain('"decimal": EJSON.deserialize(');
|
||||
expect(copied).toContain('"$numberDecimal": "12.34"');
|
||||
expect(copied).toContain('"payload": EJSON.deserialize(');
|
||||
expect(copied).toContain('"$binary":');
|
||||
expect(copied).toContain('"$unset":');
|
||||
expect(copied).toContain('"missing": ""');
|
||||
});
|
||||
|
||||
it("does not expose Mongo UPDATE copy without an explicit data-list target", async () => {
|
||||
const item = { ...row(["507f1f77bcf86cd799439011", "Alice"]), sourceIndex: 0 };
|
||||
const state = createMongoExportState({
|
||||
columns: ["_id", "name"],
|
||||
item,
|
||||
mongoDocuments: [{ _id: { $oid: "507f1f77bcf86cd799439011" }, name: "Alice" }],
|
||||
mongoUpdateTarget: false,
|
||||
});
|
||||
|
||||
expect(state.canCopyRowAsUpdate.value).toBe(false);
|
||||
await state.copyRowAsUpdate();
|
||||
expect(copyToClipboard).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("copies selected Mongo rows as separate updates using each sorted source document", async () => {
|
||||
const first = { ...row(["second-id", "Second"]), id: 1, sourceIndex: 1 };
|
||||
const second = { ...row(["first-id", "First"]), id: 2, sourceIndex: 0 };
|
||||
const state = createMongoExportState({
|
||||
columns: ["_id", "name"],
|
||||
item: first,
|
||||
items: [first, second],
|
||||
mongoDocuments: [
|
||||
{ _id: "first-id", name: "First" },
|
||||
{ _id: "second-id", name: "Second" },
|
||||
],
|
||||
selectedRowIds: new Set([1, 2]),
|
||||
});
|
||||
|
||||
await state.copyRowAsUpdate();
|
||||
|
||||
const copied = vi.mocked(copyToClipboard).mock.calls[0]?.[0] ?? "";
|
||||
expect(copied.match(/\.updateOne\(/g)).toHaveLength(2);
|
||||
expect(copied.indexOf('"_id": "second-id"')).toBeLessThan(copied.indexOf('"_id": "first-id"'));
|
||||
});
|
||||
|
||||
it("preserves original Mongo types while limiting INSERT to the selected fields", async () => {
|
||||
const item = { ...row(["123", "true", '{"kind":"literal"}']), sourceIndex: 0 };
|
||||
const state = createMongoExportState({
|
||||
columns: ["numericText", "booleanText", "jsonText"],
|
||||
item,
|
||||
mongoDocuments: [{ numericText: "123", booleanText: "true", jsonText: '{"kind":"literal"}' }],
|
||||
mongoDocuments: [{ numericText: "123", booleanText: "true" }],
|
||||
selectedCellMatrix: {
|
||||
rowIndexes: [0],
|
||||
columnIndexes: [1],
|
||||
@@ -440,47 +591,22 @@ describe("useDataGridExport prepared row statements", () => {
|
||||
},
|
||||
});
|
||||
|
||||
await state.copySelectionAsInsert();
|
||||
await expect(state.copyWithExtractor("sql-inserts")).resolves.toBe(true);
|
||||
const preview = await state.previewWithExtractor("sql-inserts", DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS);
|
||||
|
||||
expect(copyToClipboard).toHaveBeenCalledWith(`db.getCollection("documents").insert({
|
||||
"booleanText": "true"
|
||||
});`);
|
||||
});
|
||||
|
||||
it("does not traverse Mongo documents while checking copy availability", async () => {
|
||||
let documentReads = 0;
|
||||
const originalDocument = Object.defineProperty({}, "payload", {
|
||||
enumerable: true,
|
||||
get() {
|
||||
documentReads++;
|
||||
return "large-value";
|
||||
},
|
||||
});
|
||||
const item = { ...row(["large-value"]), sourceIndex: 0 };
|
||||
const state = createMongoExportState({ columns: ["payload"], item, mongoDocuments: [originalDocument] });
|
||||
|
||||
expect(state.canCopyRowAsInsert.value).toBe(true);
|
||||
expect(documentReads).toBe(0);
|
||||
|
||||
const copy = state.copyRowAsInsert();
|
||||
expect(documentReads).toBe(0);
|
||||
expect(copyToClipboard).not.toHaveBeenCalled();
|
||||
|
||||
await copy;
|
||||
expect(documentReads).toBeGreaterThan(0);
|
||||
expect(copyToClipboard).toHaveBeenCalledWith(expect.stringContaining('"payload": "large-value"'));
|
||||
});
|
||||
|
||||
it("preserves oversized Mongo documents without running the formatter", async () => {
|
||||
const payload = "x".repeat(1_100_000);
|
||||
const item = { ...row([payload]), sourceIndex: 0 };
|
||||
const state = createMongoExportState({ columns: ["payload"], item, mongoDocuments: [{ payload }] });
|
||||
|
||||
await state.copyRowAsInsert();
|
||||
|
||||
const copied = vi.mocked(copyToClipboard).mock.calls[0]?.[0] ?? "";
|
||||
expect(copied).toHaveLength(payload.length + 'db.getCollection("documents").insert({"payload":""});'.length);
|
||||
expect(copied.startsWith('db.getCollection("documents").insert({"payload":"')).toBe(true);
|
||||
expect(copied.endsWith('"});')).toBe(true);
|
||||
expect(preview).toEqual(
|
||||
expect.objectContaining({
|
||||
text: `db.getCollection("documents").insert({
|
||||
"booleanText": "true"
|
||||
});`,
|
||||
rowCount: 1,
|
||||
sourceRowCount: 1,
|
||||
truncated: false,
|
||||
}),
|
||||
);
|
||||
expect(extractDataGridSelection).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+124
-10
@@ -1,8 +1,8 @@
|
||||
import { computed, ref } from "vue";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { useDataGridSelection } from "@/composables/useDataGridSelection";
|
||||
|
||||
function createSelection(options?: { getScrollElement?: () => HTMLElement | null; cellFromClientPoint?: (clientX: number, clientY: number) => { rowIndex: number; colIndex: number } | null }) {
|
||||
function createSelection(options?: { getScrollElement?: () => HTMLElement | null; cellFromClientPoint?: (clientX: number, clientY: number) => { rowIndex: number; colIndex: number } | null; rowFromClientPoint?: (clientX: number, clientY: number) => number | null; onUserCellSelection?: () => void }) {
|
||||
const columns = computed(() => ["id", "name", "email"]);
|
||||
const displayItems = computed(() =>
|
||||
[1, 2, 3, 4].map((id, index) => ({
|
||||
@@ -26,6 +26,8 @@ function createSelection(options?: { getScrollElement?: () => HTMLElement | null
|
||||
gridRef: ref(undefined),
|
||||
getScrollElement: options?.getScrollElement,
|
||||
cellFromClientPoint: options?.cellFromClientPoint,
|
||||
rowFromClientPoint: options?.rowFromClientPoint,
|
||||
onUserCellSelection: options?.onUserCellSelection,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -38,6 +40,29 @@ function rowEvent(options: { meta?: boolean; shift?: boolean } = {}): MouseEvent
|
||||
}
|
||||
|
||||
describe("useDataGridSelection", () => {
|
||||
it("invalidates synthetic context state for ordinary, Ctrl, and Cmd cell selection", () => {
|
||||
const originalDocument = globalThis.document;
|
||||
const fakeDocument = {
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
} as unknown as Document;
|
||||
Object.defineProperty(globalThis, "document", { configurable: true, value: fakeDocument });
|
||||
const onUserCellSelection = vi.fn();
|
||||
const selection = createSelection({ onUserCellSelection });
|
||||
const event = (options: { ctrlKey?: boolean; metaKey?: boolean } = {}) => ({ button: 0, clientX: 0, clientY: 0, ctrlKey: false, metaKey: false, shiftKey: false, preventDefault: vi.fn(), ...options }) as unknown as MouseEvent;
|
||||
|
||||
try {
|
||||
selection.handleDataCellMousedown(0, 0, 1, event());
|
||||
selection.finishCellSelection();
|
||||
selection.handleDataCellMousedown(0, 1, 1, event({ ctrlKey: true }));
|
||||
selection.handleDataCellMousedown(0, 2, 1, event({ metaKey: true }));
|
||||
|
||||
expect(onUserCellSelection).toHaveBeenCalledTimes(3);
|
||||
} finally {
|
||||
Object.defineProperty(globalThis, "document", { configurable: true, value: originalDocument });
|
||||
}
|
||||
});
|
||||
|
||||
it("describes a rectangular selection with its display row and column indexes", () => {
|
||||
const selection = createSelection();
|
||||
|
||||
@@ -79,7 +104,7 @@ describe("useDataGridSelection", () => {
|
||||
expect(selection.selectedCellMatrix.value).toBeNull();
|
||||
});
|
||||
|
||||
it("creates a whole-row cell range for contiguous meta row selections", () => {
|
||||
it("keeps contiguous row selections separate from cell ranges", () => {
|
||||
const selection = createSelection();
|
||||
|
||||
selection.handleRowClick(1, 2, rowEvent({ meta: true }));
|
||||
@@ -87,13 +112,8 @@ describe("useDataGridSelection", () => {
|
||||
selection.handleRowClick(3, 4, rowEvent({ meta: true }));
|
||||
|
||||
expect(selection.selectedRowIds.value).toEqual(new Set([2, 3, 4]));
|
||||
expect(selection.selectedRange.value).toEqual({
|
||||
startRow: 1,
|
||||
endRow: 3,
|
||||
startCol: 0,
|
||||
endCol: 2,
|
||||
});
|
||||
expect(selection.hasCellSelection.value).toBe(true);
|
||||
expect(selection.selectedRange.value).toBeNull();
|
||||
expect(selection.hasCellSelection.value).toBe(false);
|
||||
});
|
||||
|
||||
it("does not create a rectangular cell range for non-contiguous meta row selections", () => {
|
||||
@@ -107,6 +127,100 @@ describe("useDataGridSelection", () => {
|
||||
expect(selection.hasCellSelection.value).toBe(false);
|
||||
});
|
||||
|
||||
it("replaces disjoint rows with the anchored range on Shift selection", () => {
|
||||
const selection = createSelection();
|
||||
|
||||
selection.handleRowClick(0, 1, rowEvent());
|
||||
selection.handleRowClick(3, 4, rowEvent({ meta: true }));
|
||||
selection.handleRowClick(1, 2, rowEvent({ shift: true }));
|
||||
|
||||
expect(selection.selectedRowIds.value).toEqual(new Set([2, 3, 4]));
|
||||
expect(selection.hasCellSelection.value).toBe(false);
|
||||
});
|
||||
|
||||
it("selects a continuous row range while dragging the row-number gutter", () => {
|
||||
const originalDocument = globalThis.document;
|
||||
const originalRequestAnimationFrame = globalThis.requestAnimationFrame;
|
||||
const originalCancelAnimationFrame = globalThis.cancelAnimationFrame;
|
||||
const listeners = new Map<string, Set<EventListenerOrEventListenerObject>>();
|
||||
const fakeDocument = {
|
||||
addEventListener(type: string, listener: EventListenerOrEventListenerObject) {
|
||||
const handlers = listeners.get(type) ?? new Set();
|
||||
handlers.add(listener);
|
||||
listeners.set(type, handlers);
|
||||
},
|
||||
removeEventListener(type: string, listener: EventListenerOrEventListenerObject) {
|
||||
listeners.get(type)?.delete(listener);
|
||||
},
|
||||
} as Document;
|
||||
Object.defineProperty(globalThis, "document", { configurable: true, value: fakeDocument });
|
||||
const animationFrames: FrameRequestCallback[] = [];
|
||||
globalThis.requestAnimationFrame = ((callback: FrameRequestCallback) => {
|
||||
animationFrames.push(callback);
|
||||
return animationFrames.length;
|
||||
}) as typeof requestAnimationFrame;
|
||||
globalThis.cancelAnimationFrame = (() => undefined) as typeof cancelAnimationFrame;
|
||||
let pointerRow = 1;
|
||||
const selection = createSelection({ rowFromClientPoint: () => pointerRow });
|
||||
|
||||
try {
|
||||
selection.beginRowSelection(1, 2, { button: 0, clientX: 5, clientY: 10, preventDefault() {} } as MouseEvent);
|
||||
pointerRow = 3;
|
||||
listeners.get("mousemove")?.forEach((listener) => {
|
||||
const event = { clientX: 5, clientY: 80 } as MouseEvent;
|
||||
if (typeof listener === "function") listener(event);
|
||||
else listener.handleEvent(event);
|
||||
});
|
||||
animationFrames.shift()?.(0);
|
||||
|
||||
expect(selection.selectedRowIds.value).toEqual(new Set([2, 3, 4]));
|
||||
expect(selection.hasCellSelection.value).toBe(false);
|
||||
} finally {
|
||||
selection.finishRowSelection();
|
||||
Object.defineProperty(globalThis, "document", { configurable: true, value: originalDocument });
|
||||
globalThis.requestAnimationFrame = originalRequestAnimationFrame;
|
||||
globalThis.cancelAnimationFrame = originalCancelAnimationFrame;
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a meta-deselected row removed after pointer movement", () => {
|
||||
const originalDocument = globalThis.document;
|
||||
const originalRequestAnimationFrame = globalThis.requestAnimationFrame;
|
||||
const originalCancelAnimationFrame = globalThis.cancelAnimationFrame;
|
||||
const listeners = new Map<string, Set<EventListenerOrEventListenerObject>>();
|
||||
const fakeDocument = {
|
||||
addEventListener(type: string, listener: EventListenerOrEventListenerObject) {
|
||||
const handlers = listeners.get(type) ?? new Set();
|
||||
handlers.add(listener);
|
||||
listeners.set(type, handlers);
|
||||
},
|
||||
removeEventListener(type: string, listener: EventListenerOrEventListenerObject) {
|
||||
listeners.get(type)?.delete(listener);
|
||||
},
|
||||
} as Document;
|
||||
Object.defineProperty(globalThis, "document", { configurable: true, value: fakeDocument });
|
||||
globalThis.requestAnimationFrame = (() => 1) as typeof requestAnimationFrame;
|
||||
globalThis.cancelAnimationFrame = (() => undefined) as typeof cancelAnimationFrame;
|
||||
const selection = createSelection({ rowFromClientPoint: () => 1 });
|
||||
|
||||
try {
|
||||
selection.selectedRowIds.value = new Set([1, 2, 3]);
|
||||
selection.beginRowSelection(1, 2, { button: 0, clientX: 5, clientY: 10, metaKey: true, preventDefault() {} } as MouseEvent);
|
||||
listeners.get("mousemove")?.forEach((listener) => {
|
||||
const event = { clientX: 6, clientY: 11 } as MouseEvent;
|
||||
if (typeof listener === "function") listener(event);
|
||||
else listener.handleEvent(event);
|
||||
});
|
||||
|
||||
expect(selection.selectedRowIds.value).toEqual(new Set([1, 3]));
|
||||
} finally {
|
||||
selection.finishRowSelection();
|
||||
Object.defineProperty(globalThis, "document", { configurable: true, value: originalDocument });
|
||||
globalThis.requestAnimationFrame = originalRequestAnimationFrame;
|
||||
globalThis.cancelAnimationFrame = originalCancelAnimationFrame;
|
||||
}
|
||||
});
|
||||
|
||||
it("scrolls and extends the selection while dragging near an edge", () => {
|
||||
const animationFrames: FrameRequestCallback[] = [];
|
||||
const originalRequestAnimationFrame = globalThis.requestAnimationFrame;
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import { computed, ref, type ComputedRef, type Ref } from "vue";
|
||||
import { computed, type ComputedRef, type Ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useDataGridExtractor } from "@/composables/useDataGridExtractor";
|
||||
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
|
||||
import * as api from "@/lib/backend/api";
|
||||
import { formatSelectionAsCsv, formatSelectionAsJson, formatSelectionAsSqlInList, formatSelectionAsTsv, type CellSelectionMatrix, type CellSelectionRange, type SelectionData } from "@/lib/dataGrid/gridSelection";
|
||||
import { type CellSelectionMatrix, type CellSelectionRange, type SelectionData } from "@/lib/dataGrid/gridSelection";
|
||||
import type { DataGridExtractorOptions } from "@/lib/dataGrid/dataGridCopyExtractor";
|
||||
import { useToast } from "@/composables/useToast";
|
||||
import { displayCellValue, type CellValue } from "@/lib/dataGrid/cellValue";
|
||||
import { tryStartExclusiveActivation, type ActionActivationGuard } from "@/lib/connection/actionActivation";
|
||||
import { copyToClipboard } from "@/lib/common/clipboard";
|
||||
import { clearDataGridClipboardCopy, rememberDataGridClipboardCopy } from "@/lib/dataGrid/dataGridClipboard";
|
||||
import { buildDataGridCopyInsertStatement, buildDataGridCopyUpdateStatements, type DataGridCopyInsertMode, type DataGridTableMeta } from "@/lib/dataGrid/dataGridSql";
|
||||
import { buildDataGridCopyInsertStatement, type DataGridCopyInsertMode, type DataGridTableMeta } from "@/lib/dataGrid/dataGridSql";
|
||||
import { formatSqlInsert, formatTsv } from "@/lib/export/exportFormats";
|
||||
import { uuid } from "@/lib/common/utils";
|
||||
import { useSettingsStore } from "@/stores/settingsStore";
|
||||
@@ -59,6 +61,11 @@ export interface MongoCopyUpdateTarget {
|
||||
export interface UseDataGridExportOptions {
|
||||
columns: ComputedRef<string[]>;
|
||||
displayItems: ComputedRef<RowItem[]>;
|
||||
allColumns?: ComputedRef<string[]>;
|
||||
allDisplayItems?: ComputedRef<RowItem[]>;
|
||||
allSourceColumns?: ComputedRef<Array<string | undefined> | undefined>;
|
||||
visibleColumnIndexes?: ComputedRef<number[]>;
|
||||
extractorOptions?: ComputedRef<DataGridExtractorOptions>;
|
||||
sql: ComputedRef<string | undefined>;
|
||||
exportSql?: ComputedRef<string | undefined>;
|
||||
tableMeta: ComputedRef<DataGridTableMeta | undefined>;
|
||||
@@ -75,10 +82,12 @@ export interface UseDataGridExportOptions {
|
||||
orderBy: ComputedRef<string | undefined>;
|
||||
exportBatchSize: ComputedRef<number>;
|
||||
hasCellSelection: ComputedRef<boolean>;
|
||||
hasColumnSelection?: ComputedRef<boolean>;
|
||||
selectedCells: ComputedRef<SelectionData>;
|
||||
selectedCellMatrix?: ComputedRef<CellSelectionMatrix | null>;
|
||||
selectedCellMatrix: ComputedRef<CellSelectionMatrix | null>;
|
||||
selectedRange: ComputedRef<CellSelectionRange | null>;
|
||||
contextCell: Ref<{ rowId: number; rowIndex: number; col: number } | null> | ComputedRef<{ rowId: number; rowIndex: number; col: number } | null>;
|
||||
contextSelectionIsSynthetic: Ref<boolean> | ComputedRef<boolean>;
|
||||
getRowItem: (rowId: number) => RowItem | undefined;
|
||||
selectedRowIds: Ref<Set<number>> | ComputedRef<Set<number>>;
|
||||
hasRowSelection: ComputedRef<boolean>;
|
||||
@@ -118,14 +127,6 @@ export interface UseDataGridExportOptions {
|
||||
exportCancelHandler?: Ref<(() => Promise<void>) | null>;
|
||||
}
|
||||
|
||||
interface CopyStatementCache {
|
||||
key: string;
|
||||
text: string;
|
||||
loading: boolean;
|
||||
ready: boolean;
|
||||
promise?: Promise<string | undefined>;
|
||||
}
|
||||
|
||||
interface CopyInsertData {
|
||||
columns: string[];
|
||||
sourceColumns?: Array<string | undefined>;
|
||||
@@ -137,57 +138,19 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
|
||||
const { t } = useI18n();
|
||||
const { toast } = useToast();
|
||||
const exportGuard: ActionActivationGuard = {};
|
||||
const copyRowInsertCache = ref<CopyStatementCache>({
|
||||
key: "",
|
||||
text: "",
|
||||
loading: false,
|
||||
ready: false,
|
||||
});
|
||||
const copyRowInsertRowByRowCache = ref<CopyStatementCache>({
|
||||
key: "",
|
||||
text: "",
|
||||
loading: false,
|
||||
ready: false,
|
||||
});
|
||||
const copyRowInsertWithoutPrimaryKeysCache = ref<CopyStatementCache>({
|
||||
key: "",
|
||||
text: "",
|
||||
loading: false,
|
||||
ready: false,
|
||||
});
|
||||
const copyRowInsertWithoutPrimaryKeysRowByRowCache = ref<CopyStatementCache>({
|
||||
key: "",
|
||||
text: "",
|
||||
loading: false,
|
||||
ready: false,
|
||||
});
|
||||
const copySelectionInsertCache = ref<CopyStatementCache>({
|
||||
key: "",
|
||||
text: "",
|
||||
loading: false,
|
||||
ready: false,
|
||||
});
|
||||
const copySelectionInsertRowByRowCache = ref<CopyStatementCache>({
|
||||
key: "",
|
||||
text: "",
|
||||
loading: false,
|
||||
ready: false,
|
||||
});
|
||||
const copyRowUpdateCache = ref<CopyStatementCache>({
|
||||
key: "",
|
||||
text: "",
|
||||
loading: false,
|
||||
ready: false,
|
||||
});
|
||||
|
||||
const {
|
||||
columns,
|
||||
displayItems,
|
||||
allColumns: allColumnsOption,
|
||||
allDisplayItems: allDisplayItemsOption,
|
||||
allSourceColumns: allSourceColumnsOption,
|
||||
visibleColumnIndexes: visibleColumnIndexesOption,
|
||||
extractorOptions: extractorOptionsOption,
|
||||
sql,
|
||||
exportSql: resultExportSql,
|
||||
tableMeta,
|
||||
copyInsertTargetLabel,
|
||||
mongoUpdateTarget,
|
||||
sourceColumns,
|
||||
databaseType,
|
||||
connectionId,
|
||||
@@ -198,10 +161,12 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
|
||||
columnTypes,
|
||||
exportBatchSize,
|
||||
hasCellSelection,
|
||||
hasColumnSelection: hasColumnSelectionOption,
|
||||
selectedCells,
|
||||
selectedCellMatrix: selectedCellMatrixOption,
|
||||
selectedRange,
|
||||
contextCell,
|
||||
contextSelectionIsSynthetic,
|
||||
getRowItem,
|
||||
selectedRowIds,
|
||||
hasRowSelection,
|
||||
@@ -216,17 +181,25 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
|
||||
exportProgressState,
|
||||
exportCancelHandler,
|
||||
} = options;
|
||||
const selectedCellMatrix = selectedCellMatrixOption ?? computed<CellSelectionMatrix | null>(() => null);
|
||||
const selectedCellMatrix = selectedCellMatrixOption;
|
||||
const allColumns = allColumnsOption ?? columns;
|
||||
const allDisplayItems = allDisplayItemsOption ?? displayItems;
|
||||
const allSourceColumns = allSourceColumnsOption ?? sourceColumns;
|
||||
const visibleColumnIndexes = visibleColumnIndexesOption ?? computed(() => columns.value.map((_, index) => index));
|
||||
const hasColumnSelection = hasColumnSelectionOption ?? computed(() => false);
|
||||
|
||||
async function copyText(text: string, gridCopy?: { rows: readonly (readonly unknown[])[]; includeHeader?: boolean }) {
|
||||
async function copyText(text: string, gridCopy?: { rows: readonly (readonly unknown[])[]; header?: readonly unknown[] }) {
|
||||
const copiedRows = gridCopy?.rows.map((row) => [...row]);
|
||||
const copiedHeader = gridCopy?.header ? [...gridCopy.header] : undefined;
|
||||
clearDataGridClipboardCopy();
|
||||
try {
|
||||
await copyToClipboard(text);
|
||||
if (copiedRows) rememberDataGridClipboardCopy(text, copiedRows, gridCopy?.includeHeader);
|
||||
if (copiedRows) rememberDataGridClipboardCopy(text, copiedRows, copiedHeader);
|
||||
toast(t("grid.copied"));
|
||||
return true;
|
||||
} catch (e: any) {
|
||||
toast(t("grid.copyFailed", { message: e?.message || String(e) }), 5000);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -318,58 +291,6 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
|
||||
return item && !item.isDraft ? [item] : [];
|
||||
}
|
||||
|
||||
function updateEligibleRows(): RowItem[] {
|
||||
return targetedRows().filter((item) => !item.isNew && !item.isDraft && !item.isDeleted);
|
||||
}
|
||||
|
||||
function updateCopyKey(): string {
|
||||
const rows = copyStatementRowsKey(updateEligibleRows());
|
||||
return JSON.stringify({
|
||||
databaseType: databaseType.value ?? null,
|
||||
schema: tableMeta.value?.schema ?? null,
|
||||
tableName: tableMeta.value?.tableName ?? null,
|
||||
primaryKeys: tableMeta.value?.primaryKeys ?? [],
|
||||
columns: columns.value,
|
||||
sourceColumns: sourceColumns.value ?? null,
|
||||
rows,
|
||||
});
|
||||
}
|
||||
|
||||
function buildMongoCopyUpdateStatements(rows: RowItem[], target: MongoCopyUpdateTarget): string[] {
|
||||
const documents = options.mongoDocuments?.value;
|
||||
if (!documents) return [];
|
||||
|
||||
const copyColumns = effectiveColumns(sourceColumns.value, columns.value).map((column) => column ?? "");
|
||||
const statements: string[] = [];
|
||||
for (const item of rows) {
|
||||
if (item.sourceIndex === undefined) continue;
|
||||
const originalDocument = documents[item.sourceIndex];
|
||||
if (!originalDocument || typeof originalDocument !== "object" || Array.isArray(originalDocument)) continue;
|
||||
|
||||
const source = originalDocument as Record<string, unknown>;
|
||||
if (!Object.prototype.hasOwnProperty.call(source, target.idColumn)) continue;
|
||||
const update = buildMongoCopyUpdateDocument(item.data as MongoInputValue[], copyColumns, item.isDirtyCol, originalDocument, target.idColumn);
|
||||
if (!update) continue;
|
||||
|
||||
const statement = `db.getCollection(${JSON.stringify(target.collection)}).updateOne({${JSON.stringify(target.idColumn)}:${formatMongoShellLiteral(source[target.idColumn])}},${formatMongoShellLiteral(update)});`;
|
||||
statements.push(formatMongoCopyStatement(statement) ?? statement);
|
||||
}
|
||||
return statements;
|
||||
}
|
||||
|
||||
function insertCopyKey(excludePrimaryKeys: boolean, insertMode: DataGridCopyInsertMode): string {
|
||||
return copyInsertKey(
|
||||
{
|
||||
columns: columns.value,
|
||||
sourceColumns: sourceColumns.value,
|
||||
columnTypes: columnTypes.value?.map((type) => type ?? undefined),
|
||||
rows: insertEligibleRows(),
|
||||
},
|
||||
excludePrimaryKeys,
|
||||
insertMode,
|
||||
);
|
||||
}
|
||||
|
||||
function selectionInsertData(): CopyInsertData | null {
|
||||
const matrix = selectedCellMatrix.value;
|
||||
if (!matrix) return null;
|
||||
@@ -391,68 +312,6 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
|
||||
};
|
||||
}
|
||||
|
||||
function selectionInsertCopyKey(insertMode: DataGridCopyInsertMode): string {
|
||||
const data = selectionInsertData();
|
||||
return data ? copyInsertKey(data, false, insertMode) : "";
|
||||
}
|
||||
|
||||
function copyInsertKey(data: CopyInsertData, excludePrimaryKeys: boolean, insertMode: DataGridCopyInsertMode): string {
|
||||
const rows = copyStatementRowsKey(data.rows);
|
||||
const originalMongoDocuments = data.rows.map((item) => (item.sourceIndex === undefined ? undefined : options.mongoDocuments?.value?.[item.sourceIndex]));
|
||||
return JSON.stringify({
|
||||
databaseType: databaseType.value ?? null,
|
||||
schema: tableMeta.value?.schema ?? null,
|
||||
tableName: tableMeta.value?.tableName ?? null,
|
||||
copyInsertTargetLabel: copyInsertTargetLabel?.value ?? null,
|
||||
columns: data.columns,
|
||||
columnTypes: data.columnTypes ?? null,
|
||||
sourceColumns: data.sourceColumns ?? null,
|
||||
excludePrimaryKeys,
|
||||
insertMode,
|
||||
rows,
|
||||
originalMongoDocuments,
|
||||
});
|
||||
}
|
||||
|
||||
function copyStatementRowsKey(rows: RowItem[]): Array<{ id: number; sourceIndex?: number; data: CellValue[]; isDirtyCol: boolean[] }> {
|
||||
// Prepared copy SQL depends on current cell values; edited rows keep the same id while their data changes.
|
||||
return rows.map((item) => ({ id: item.id, sourceIndex: item.sourceIndex, data: item.data, isDirtyCol: item.isDirtyCol }));
|
||||
}
|
||||
|
||||
function insertCopyCache(excludePrimaryKeys: boolean, insertMode: DataGridCopyInsertMode): CopyStatementCache {
|
||||
if (excludePrimaryKeys) {
|
||||
return insertMode === "row-by-row" ? copyRowInsertWithoutPrimaryKeysRowByRowCache.value : copyRowInsertWithoutPrimaryKeysCache.value;
|
||||
}
|
||||
return insertMode === "row-by-row" ? copyRowInsertRowByRowCache.value : copyRowInsertCache.value;
|
||||
}
|
||||
|
||||
function setInsertCopyCache(excludePrimaryKeys: boolean, insertMode: DataGridCopyInsertMode, cache: CopyStatementCache) {
|
||||
if (excludePrimaryKeys) {
|
||||
if (insertMode === "row-by-row") {
|
||||
copyRowInsertWithoutPrimaryKeysRowByRowCache.value = cache;
|
||||
} else {
|
||||
copyRowInsertWithoutPrimaryKeysCache.value = cache;
|
||||
}
|
||||
} else if (insertMode === "row-by-row") {
|
||||
copyRowInsertRowByRowCache.value = cache;
|
||||
} else {
|
||||
copyRowInsertCache.value = cache;
|
||||
}
|
||||
}
|
||||
|
||||
function selectionInsertCopyCache(insertMode: DataGridCopyInsertMode): CopyStatementCache {
|
||||
return insertMode === "row-by-row" ? copySelectionInsertRowByRowCache.value : copySelectionInsertCache.value;
|
||||
}
|
||||
|
||||
function setSelectionInsertCopyCache(insertMode: DataGridCopyInsertMode, cache: CopyStatementCache) {
|
||||
if (insertMode === "row-by-row") copySelectionInsertRowByRowCache.value = cache;
|
||||
else copySelectionInsertCache.value = cache;
|
||||
}
|
||||
|
||||
function setUpdateCopyCache(cache: CopyStatementCache) {
|
||||
copyRowUpdateCache.value = cache;
|
||||
}
|
||||
|
||||
async function buildCopyInsertStatement(data: CopyInsertData, excludePrimaryKeys: boolean, insertMode: DataGridCopyInsertMode): Promise<string | undefined> {
|
||||
if (databaseType.value === "mongodb") {
|
||||
return formatMongoCopyStatement(
|
||||
@@ -479,326 +338,6 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
|
||||
});
|
||||
}
|
||||
|
||||
async function prefetchRowAsInsertStatement(excludePrimaryKeys: boolean, insertMode: DataGridCopyInsertMode = "merged") {
|
||||
try {
|
||||
await prepareRowAsInsertStatement(excludePrimaryKeys, insertMode);
|
||||
} catch {
|
||||
// Prefetch failures are reported only if the user invokes the copy action.
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareRowAsInsertStatement(excludePrimaryKeys: boolean, insertMode: DataGridCopyInsertMode = "merged"): Promise<string | undefined> {
|
||||
const rows = insertEligibleRows();
|
||||
if (!rows.length) {
|
||||
setInsertCopyCache(excludePrimaryKeys, insertMode, {
|
||||
key: "",
|
||||
text: "",
|
||||
loading: false,
|
||||
ready: false,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const data: CopyInsertData = {
|
||||
columns: columns.value,
|
||||
sourceColumns: sourceColumns.value,
|
||||
columnTypes: columnTypes.value?.map((type) => type ?? undefined),
|
||||
rows,
|
||||
};
|
||||
if (databaseType.value === "mongodb") {
|
||||
// Mongo documents can approach the 16 MiB BSON limit. Yield before the
|
||||
// synchronous shell serialization so menu close/rendering is never held up.
|
||||
await yieldToMainThread();
|
||||
return buildCopyInsertStatement(data, excludePrimaryKeys, insertMode);
|
||||
}
|
||||
|
||||
const key = insertCopyKey(excludePrimaryKeys, insertMode);
|
||||
const current = insertCopyCache(excludePrimaryKeys, insertMode);
|
||||
if (current.ready && current.key === key) return current.text;
|
||||
if (current.loading && current.key === key && current.promise) return current.promise;
|
||||
const promise = Promise.resolve().then(async () => {
|
||||
const statement = await buildCopyInsertStatement(data, excludePrimaryKeys, insertMode);
|
||||
const latest = insertCopyCache(excludePrimaryKeys, insertMode);
|
||||
if (latest.key !== key || latest.promise !== promise) return undefined;
|
||||
setInsertCopyCache(excludePrimaryKeys, insertMode, {
|
||||
key,
|
||||
text: statement ?? "",
|
||||
loading: false,
|
||||
ready: !!statement,
|
||||
});
|
||||
return statement;
|
||||
});
|
||||
|
||||
setInsertCopyCache(excludePrimaryKeys, insertMode, {
|
||||
key,
|
||||
text: "",
|
||||
loading: true,
|
||||
ready: false,
|
||||
promise,
|
||||
});
|
||||
|
||||
try {
|
||||
return await promise;
|
||||
} catch (error) {
|
||||
const latest = insertCopyCache(excludePrimaryKeys, insertMode);
|
||||
if (latest.key === key && latest.promise === promise) {
|
||||
setInsertCopyCache(excludePrimaryKeys, insertMode, {
|
||||
key,
|
||||
text: "",
|
||||
loading: false,
|
||||
ready: false,
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function canCopyPreparedInsert(excludePrimaryKeys: boolean, insertMode: DataGridCopyInsertMode = "merged"): boolean {
|
||||
const cache = insertCopyCache(excludePrimaryKeys, insertMode);
|
||||
return cache.ready && cache.key === insertCopyKey(excludePrimaryKeys, insertMode);
|
||||
}
|
||||
|
||||
async function copyPreparedRowAsInsert(excludePrimaryKeys: boolean, insertMode: DataGridCopyInsertMode = "merged"): Promise<boolean> {
|
||||
try {
|
||||
const statement = await prepareRowAsInsertStatement(excludePrimaryKeys, insertMode);
|
||||
if (!statement) return false;
|
||||
await copyText(statement);
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
toast(t("grid.copyFailed", { message: error?.message || String(error) }), 5000);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function prefetchSelectionAsInsertStatement(insertMode: DataGridCopyInsertMode = "merged") {
|
||||
try {
|
||||
await prepareSelectionAsInsertStatement(insertMode);
|
||||
} catch (error: any) {
|
||||
toast(t("grid.copyFailed", { message: error?.message || String(error) }), 5000);
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareSelectionAsInsertStatement(insertMode: DataGridCopyInsertMode = "merged"): Promise<string | undefined> {
|
||||
const data = selectionInsertData();
|
||||
if (!data) {
|
||||
setSelectionInsertCopyCache(insertMode, {
|
||||
key: "",
|
||||
text: "",
|
||||
loading: false,
|
||||
ready: false,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (databaseType.value === "mongodb") {
|
||||
// Keep context-menu work bounded; serialize the selected Mongo fields only
|
||||
// after the user explicitly invokes the copy command.
|
||||
await yieldToMainThread();
|
||||
return buildCopyInsertStatement(data, false, insertMode);
|
||||
}
|
||||
const key = selectionInsertCopyKey(insertMode);
|
||||
const current = selectionInsertCopyCache(insertMode);
|
||||
if (current.ready && current.key === key) return current.text;
|
||||
if (current.loading && current.key === key && current.promise) return current.promise;
|
||||
|
||||
const promise = Promise.resolve().then(async () => {
|
||||
const statement = await buildCopyInsertStatement(data, false, insertMode);
|
||||
const latest = selectionInsertCopyCache(insertMode);
|
||||
if (latest.key !== key || latest.promise !== promise) return undefined;
|
||||
setSelectionInsertCopyCache(insertMode, {
|
||||
key,
|
||||
text: statement ?? "",
|
||||
loading: false,
|
||||
ready: !!statement,
|
||||
});
|
||||
return statement;
|
||||
});
|
||||
|
||||
setSelectionInsertCopyCache(insertMode, {
|
||||
key,
|
||||
text: "",
|
||||
loading: true,
|
||||
ready: false,
|
||||
promise,
|
||||
});
|
||||
|
||||
try {
|
||||
return await promise;
|
||||
} catch (error) {
|
||||
const latest = selectionInsertCopyCache(insertMode);
|
||||
if (latest.key === key && latest.promise === promise) {
|
||||
setSelectionInsertCopyCache(insertMode, {
|
||||
key,
|
||||
text: "",
|
||||
loading: false,
|
||||
ready: false,
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function canCopyPreparedSelectionInsert(insertMode: DataGridCopyInsertMode = "merged"): boolean {
|
||||
const cache = selectionInsertCopyCache(insertMode);
|
||||
return cache.ready && cache.key === selectionInsertCopyKey(insertMode);
|
||||
}
|
||||
|
||||
async function copySelectionAsInsert(insertMode: DataGridCopyInsertMode = "merged"): Promise<boolean> {
|
||||
try {
|
||||
const statement = await prepareSelectionAsInsertStatement(insertMode);
|
||||
if (!statement) return false;
|
||||
await copyText(statement);
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
toast(t("grid.copyFailed", { message: error?.message || String(error) }), 5000);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function prefetchRowAsUpdateStatement() {
|
||||
try {
|
||||
await prepareRowAsUpdateStatement();
|
||||
} catch {
|
||||
// Prefetch failures are reported only if the user invokes the copy action.
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareRowAsUpdateStatement(): Promise<string | undefined> {
|
||||
const rows = updateEligibleRows();
|
||||
if (!rows.length) {
|
||||
setUpdateCopyCache({
|
||||
key: "",
|
||||
text: "",
|
||||
loading: false,
|
||||
ready: false,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (databaseType.value === "mongodb") {
|
||||
const target = mongoUpdateTarget?.value;
|
||||
if (!target) return;
|
||||
await yieldToMainThread();
|
||||
const text = buildMongoCopyUpdateStatements(rows, target).join("\n");
|
||||
return text || undefined;
|
||||
}
|
||||
|
||||
const currentTableMeta = tableMeta.value;
|
||||
if (!currentTableMeta?.primaryKeys.length) {
|
||||
setUpdateCopyCache({
|
||||
key: "",
|
||||
text: "",
|
||||
loading: false,
|
||||
ready: false,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const key = updateCopyKey();
|
||||
const current = copyRowUpdateCache.value;
|
||||
if (current.ready && current.key === key) return current.text;
|
||||
if (current.loading && current.key === key && current.promise) return current.promise;
|
||||
|
||||
const promise = Promise.resolve().then(async () => {
|
||||
const statements = await buildDataGridCopyUpdateStatements({
|
||||
databaseType: databaseType.value,
|
||||
tableMeta: currentTableMeta,
|
||||
columns: columns.value,
|
||||
sourceColumns: sourceColumns.value,
|
||||
rows: rows.map((item) => item.data),
|
||||
});
|
||||
const latest = copyRowUpdateCache.value;
|
||||
if (latest.key !== key || latest.promise !== promise) return undefined;
|
||||
const text = statements.join("\n");
|
||||
setUpdateCopyCache({
|
||||
key,
|
||||
text,
|
||||
loading: false,
|
||||
ready: statements.length > 0,
|
||||
});
|
||||
return text || undefined;
|
||||
});
|
||||
|
||||
setUpdateCopyCache({
|
||||
key,
|
||||
text: "",
|
||||
loading: true,
|
||||
ready: false,
|
||||
promise,
|
||||
});
|
||||
|
||||
try {
|
||||
return await promise;
|
||||
} catch (error) {
|
||||
const latest = copyRowUpdateCache.value;
|
||||
if (latest.key === key && latest.promise === promise) {
|
||||
setUpdateCopyCache({
|
||||
key,
|
||||
text: "",
|
||||
loading: false,
|
||||
ready: false,
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function canCopyPreparedUpdate(): boolean {
|
||||
const cache = copyRowUpdateCache.value;
|
||||
return cache.ready && cache.key === updateCopyKey();
|
||||
}
|
||||
|
||||
async function copyPreparedRowAsUpdate(): Promise<boolean> {
|
||||
try {
|
||||
const statement = await prepareRowAsUpdateStatement();
|
||||
if (!statement) return false;
|
||||
await copyText(statement);
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
toast(t("grid.copyFailed", { message: error?.message || String(error) }), 5000);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Selection copy functions ---
|
||||
async function copySelectionTsv() {
|
||||
if (!hasCellSelection.value) return;
|
||||
const selection = selectedCells.value;
|
||||
await copyText(formatSelectionAsTsv(selection), { rows: selection.rows });
|
||||
}
|
||||
|
||||
async function copySelectionTsvWithHeaders() {
|
||||
if (!hasCellSelection.value) return;
|
||||
const selection = selectedCells.value;
|
||||
await copyText(formatSelectionAsTsv(selection, true), { rows: selection.rows, includeHeader: true });
|
||||
}
|
||||
|
||||
async function copySelectionCsv() {
|
||||
if (!hasCellSelection.value) return;
|
||||
await copyText(formatSelectionAsCsv(selectedCells.value));
|
||||
}
|
||||
|
||||
async function copySelectionJson() {
|
||||
if (!hasCellSelection.value) return;
|
||||
await copyText(formatSelectionAsJson(selectedCells.value));
|
||||
}
|
||||
|
||||
async function copySelectionSqlInList() {
|
||||
if (!hasCellSelection.value) return;
|
||||
await copyText(formatSelectionAsSqlInList(selectedCells.value));
|
||||
}
|
||||
|
||||
async function copySelectedRowsTsv() {
|
||||
if (!hasRowSelection.value || selectedRowIds.value.size === 0) return;
|
||||
const rows = displayItems.value.filter((item) => selectedRowIds.value.has(item.id) && !item.isDraft).map((item) => item.data);
|
||||
if (rows.length === 0) return;
|
||||
await copyText(formatSelectionAsTsv({ columns: columns.value, rows }), { rows });
|
||||
}
|
||||
|
||||
async function copySelectedRowsTsvWithHeaders() {
|
||||
if (!hasRowSelection.value || selectedRowIds.value.size === 0) return;
|
||||
const rows = displayItems.value.filter((item) => selectedRowIds.value.has(item.id) && !item.isDraft).map((item) => item.data);
|
||||
if (rows.length === 0) return;
|
||||
await copyText(formatSelectionAsTsv({ columns: columns.value, rows }, true), { rows, includeHeader: true });
|
||||
}
|
||||
|
||||
function rowToJsonObject(item: RowItem): Record<string, unknown> {
|
||||
if (options.databaseType.value === "mongodb" && item.sourceIndex !== undefined) {
|
||||
const original = options.mongoDocuments?.value?.[item.sourceIndex];
|
||||
@@ -851,60 +390,82 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
|
||||
return targetedRows().filter((item) => !item.isDraft);
|
||||
}
|
||||
|
||||
async function copyRowAsInsert(insertMode: DataGridCopyInsertMode = "merged") {
|
||||
await copyPreparedRowAsInsert(false, insertMode);
|
||||
}
|
||||
|
||||
async function copyRowAsInsertWithoutPrimaryKeys(insertMode: DataGridCopyInsertMode = "merged") {
|
||||
await copyPreparedRowAsInsert(true, insertMode);
|
||||
}
|
||||
|
||||
async function copyRowAsUpdate() {
|
||||
await copyPreparedRowAsUpdate();
|
||||
}
|
||||
|
||||
const canCopyRowAsUpdate = computed(() => {
|
||||
const rows = updateEligibleRows();
|
||||
if (!rows.length) return false;
|
||||
const saveColumns = effectiveColumns(sourceColumns.value, columns.value);
|
||||
if (databaseType.value === "mongodb") {
|
||||
const target = mongoUpdateTarget?.value;
|
||||
if (!target || !options.mongoDocuments?.value || rows.some((item) => item.sourceIndex === undefined)) return false;
|
||||
if (findColumnIndex(saveColumns, target.idColumn) === -1) return false;
|
||||
return saveColumns.some((column) => column && normalizeColumnName(column) !== normalizeColumnName(target.idColumn));
|
||||
}
|
||||
if (!tableMeta.value?.primaryKeys.length) return false;
|
||||
if (databaseType.value === "neo4j" || databaseType.value === "tdengine") return false;
|
||||
const primaryKeys = tableMeta.value.primaryKeys;
|
||||
if (primaryKeys.some((primaryKey) => findColumnIndex(saveColumns, primaryKey) === -1)) return false;
|
||||
const primaryKeySet = new Set(primaryKeys.map(normalizeColumnName));
|
||||
return saveColumns.some((column) => column && !primaryKeySet.has(normalizeColumnName(column)));
|
||||
});
|
||||
|
||||
function insertableCopyColumnCount(excludePrimaryKeys: boolean, copyColumns = effectiveColumns(sourceColumns.value, columns.value)): number {
|
||||
function insertableCopyColumnCount(excludePrimaryKeys: boolean, copyColumns = effectiveColumns(sourceColumns.value, columns.value), extractorOptions?: DataGridExtractorOptions): number {
|
||||
const primaryKeySet = new Set((tableMeta.value?.primaryKeys ?? []).map(normalizeColumnName));
|
||||
return copyColumns.filter((column): column is string => !!column && !isCopyInsertOmittedColumn(databaseType.value, column, tableMeta.value) && (!excludePrimaryKeys || !primaryKeySet.has(normalizeColumnName(column)))).length;
|
||||
return copyColumns.filter((column): column is string => !!column && !isCopyInsertOmittedColumn(databaseType.value, column, tableMeta.value, extractorOptions) && (!excludePrimaryKeys || !primaryKeySet.has(normalizeColumnName(column)))).length;
|
||||
}
|
||||
|
||||
const canCopyRowAsInsert = computed(() => insertEligibleRows().length > 0 && insertableCopyColumnCount(false) > 0);
|
||||
const selectionInsertRowCount = computed(() => selectionInsertData()?.rows.length ?? 0);
|
||||
const canCopySelectionAsInsert = computed(() => {
|
||||
const data = selectionInsertData();
|
||||
return !!data?.rows.length && insertableCopyColumnCount(false, effectiveColumns(data.sourceColumns, data.columns)) > 0;
|
||||
});
|
||||
async function buildMongoExtractorInsert(extractorOptions: DataGridExtractorOptions, rowLimit?: number): Promise<string | undefined> {
|
||||
const data: CopyInsertData | null =
|
||||
hasRowSelection.value || !hasCellSelection.value
|
||||
? {
|
||||
columns: columns.value,
|
||||
sourceColumns: sourceColumns.value,
|
||||
columnTypes: columnTypes.value?.map((type) => type ?? undefined),
|
||||
rows: insertEligibleRows(),
|
||||
}
|
||||
: selectionInsertData();
|
||||
if (!data) return undefined;
|
||||
await yieldToMainThread();
|
||||
return buildCopyInsertStatement(rowLimit === undefined ? data : { ...data, rows: data.rows.slice(0, rowLimit) }, extractorOptions.sql.excludePrimaryKeysFromInsert, extractorOptions.sql.insertMode);
|
||||
}
|
||||
|
||||
const canCopyRowAsInsertWithoutPrimaryKeys = computed(() => {
|
||||
if (!tableMeta.value?.primaryKeys.length) return false;
|
||||
async function buildMongoExtractorUpdate(_extractorOptions: DataGridExtractorOptions, rowLimit?: number): Promise<string | undefined> {
|
||||
const target = options.mongoUpdateTarget?.value;
|
||||
const documents = options.mongoDocuments?.value;
|
||||
if (!target || !documents) return undefined;
|
||||
const rows = insertEligibleRows();
|
||||
if (!rows.length) return false;
|
||||
return insertableCopyColumnCount(true) > 0;
|
||||
if (rows.length === 0) return undefined;
|
||||
const limitedRows = rowLimit === undefined ? rows : rows.slice(0, rowLimit);
|
||||
const copyColumns = effectiveColumns(sourceColumns.value, columns.value).map((column) => column ?? "");
|
||||
await yieldToMainThread();
|
||||
const statements: string[] = [];
|
||||
for (const item of limitedRows) {
|
||||
if (item.sourceIndex === undefined) continue;
|
||||
const originalDocument = documents[item.sourceIndex];
|
||||
if (!originalDocument || typeof originalDocument !== "object" || Array.isArray(originalDocument)) continue;
|
||||
const source = originalDocument as Record<string, unknown>;
|
||||
if (!Object.prototype.hasOwnProperty.call(source, target.idColumn)) continue;
|
||||
const update = buildMongoCopyUpdateDocument(item.data as MongoInputValue[], copyColumns, item.isDirtyCol, originalDocument, target.idColumn);
|
||||
if (!update) continue;
|
||||
const statement = `db.getCollection(${JSON.stringify(target.collection)}).updateOne({${JSON.stringify(target.idColumn)}:${formatMongoShellLiteral(source[target.idColumn])}},${formatMongoShellLiteral(update)});`;
|
||||
statements.push(formatMongoCopyStatement(statement) ?? statement);
|
||||
}
|
||||
return statements.length > 0 ? statements.join("\n") : undefined;
|
||||
}
|
||||
|
||||
const { copyWithExtractor, previewWithExtractor, canCopyWithExtractor } = useDataGridExtractor({
|
||||
columns,
|
||||
displayItems,
|
||||
allColumns,
|
||||
allDisplayItems,
|
||||
allSourceColumns,
|
||||
visibleColumnIndexes,
|
||||
extractorOptions: extractorOptionsOption,
|
||||
databaseType,
|
||||
tableMeta,
|
||||
hasCellSelection,
|
||||
selectedCells,
|
||||
selectedCellMatrix,
|
||||
hasRowSelection,
|
||||
hasColumnSelection,
|
||||
selectedRowIds,
|
||||
copyText,
|
||||
canCopySqlInsert: (request) => {
|
||||
const selectedColumns = request.selectedColumnIndexes.map((index) => request.columns[index]?.sourceName ?? request.columns[index]?.displayName).filter((column): column is string => !!column);
|
||||
return request.rows.length > 0 && insertableCopyColumnCount(request.options.sql.excludePrimaryKeysFromInsert, selectedColumns, request.options) > 0;
|
||||
},
|
||||
buildMongoInsert: buildMongoExtractorInsert,
|
||||
buildMongoUpdate: buildMongoExtractorUpdate,
|
||||
contextCell,
|
||||
contextSelectionIsSynthetic,
|
||||
});
|
||||
|
||||
async function copyAll() {
|
||||
const header = columns.value.join("\t");
|
||||
const rows = displayItems.value.filter((item) => !item.isDraft).map((item) => item.data);
|
||||
const body = rows.map((row) => row.map((cell) => displayCellValue(cell)).join("\t")).join("\n");
|
||||
await copyText(`${header}\n${body}`, { rows, includeHeader: true });
|
||||
await copyText(`${header}\n${body}`, { rows, header: columns.value });
|
||||
}
|
||||
|
||||
// --- Export functions ---
|
||||
@@ -1517,31 +1078,10 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
|
||||
copyText,
|
||||
copyCell,
|
||||
copyRow,
|
||||
copyRowAsInsert,
|
||||
copyRowAsInsertWithoutPrimaryKeys,
|
||||
prefetchRowAsInsertStatement,
|
||||
canCopyPreparedInsert,
|
||||
copyPreparedRowAsInsert,
|
||||
canCopyRowAsInsert,
|
||||
prefetchRowAsUpdateStatement,
|
||||
canCopyPreparedUpdate,
|
||||
copyPreparedRowAsUpdate,
|
||||
copyRowAsUpdate,
|
||||
canCopyRowAsInsertWithoutPrimaryKeys,
|
||||
canCopyRowAsUpdate,
|
||||
copyAll,
|
||||
copySelectionTsv,
|
||||
copySelectionTsvWithHeaders,
|
||||
copySelectionCsv,
|
||||
copySelectionJson,
|
||||
copySelectionSqlInList,
|
||||
copySelectionAsInsert,
|
||||
prefetchSelectionAsInsertStatement,
|
||||
canCopyPreparedSelectionInsert,
|
||||
canCopySelectionAsInsert,
|
||||
selectionInsertRowCount,
|
||||
copySelectedRowsTsv,
|
||||
copySelectedRowsTsvWithHeaders,
|
||||
copyWithExtractor,
|
||||
previewWithExtractor,
|
||||
canCopyWithExtractor,
|
||||
exportCsv,
|
||||
exportCurrentPageCsv,
|
||||
exportJson,
|
||||
@@ -1655,18 +1195,15 @@ function effectiveColumns(sourceColumns: Array<string | undefined> | undefined,
|
||||
return sourceColumns;
|
||||
}
|
||||
|
||||
function isCopyInsertOmittedColumn(databaseType: DatabaseType | undefined, column: string, tableMeta: DataGridTableMeta | undefined): boolean {
|
||||
function isCopyInsertOmittedColumn(databaseType: DatabaseType | undefined, column: string, tableMeta: DataGridTableMeta | undefined, extractorOptions?: DataGridExtractorOptions): boolean {
|
||||
if (usesSyntheticRowIdKey(databaseType, [column])) return true;
|
||||
const columnInfo = tableMeta?.columns?.find((item) => normalizeColumnName(item.name) === normalizeColumnName(column));
|
||||
const normalizedType = columnInfo?.data_type.trim().replace(/^"|"$/g, "").toLowerCase();
|
||||
if (databaseType === "postgres" && (normalizedType === "tsvector" || normalizedType?.endsWith(".tsvector"))) return true;
|
||||
const extra = columnInfo?.extra?.toLowerCase() ?? "";
|
||||
return /\b(auto_increment|autoincrement|identity)\b/.test(extra) || (extra.includes("generated always as") && !extra.includes("identity"));
|
||||
}
|
||||
|
||||
function findColumnIndex(columns: Array<string | undefined>, target: string): number {
|
||||
const normalizedTarget = normalizeColumnName(target);
|
||||
return columns.findIndex((column) => (column ? normalizeColumnName(column) : "") === normalizedTarget);
|
||||
const isAutoGenerated = /\b(auto_increment|autoincrement|identity)\b/.test(extra);
|
||||
const isComputed = extra.includes("generated always as") && !extra.includes("identity");
|
||||
return ((extractorOptions?.sql.skipGeneratedColumns ?? true) && isAutoGenerated) || ((extractorOptions?.sql.skipComputedColumns ?? true) && isComputed);
|
||||
}
|
||||
|
||||
function normalizeColumnName(name: string): string {
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
import { computed, type ComputedRef, type Ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import * as api from "@/lib/backend/api";
|
||||
import { useToast } from "@/composables/useToast";
|
||||
import { dedupeColumnIndexes, type CellSelectionMatrix, type SelectionData } from "@/lib/dataGrid/gridSelection";
|
||||
import {
|
||||
DATA_GRID_COPY_EXTRACTOR_DESCRIPTORS,
|
||||
DATA_GRID_EXTRACTOR_CONTRACT_VERSION,
|
||||
DATA_GRID_EXTRACTOR_PREVIEW_MAX_ROWS,
|
||||
DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS,
|
||||
extractorUnavailableForDatabase,
|
||||
normalizeDataGridExtractorOptions,
|
||||
type DataGridCopyExtractorId,
|
||||
type DataGridExtractPreview,
|
||||
type DataGridExtractRequest,
|
||||
type DataGridExtractorOptions,
|
||||
type DataGridExtractWarningCode,
|
||||
} from "@/lib/dataGrid/dataGridCopyExtractor";
|
||||
import type { DataGridTableMeta } from "@/lib/dataGrid/dataGridSql";
|
||||
import type { DatabaseType } from "@/types/database";
|
||||
|
||||
interface ExtractorRowItem {
|
||||
id: number;
|
||||
data: SelectionData["rows"][number];
|
||||
isDraft?: boolean;
|
||||
}
|
||||
|
||||
interface UseDataGridExtractorOptions {
|
||||
columns: ComputedRef<string[]>;
|
||||
displayItems: ComputedRef<ExtractorRowItem[]>;
|
||||
allColumns: ComputedRef<string[]>;
|
||||
allDisplayItems: ComputedRef<ExtractorRowItem[]>;
|
||||
allSourceColumns: ComputedRef<Array<string | undefined> | undefined>;
|
||||
visibleColumnIndexes: ComputedRef<number[]>;
|
||||
extractorOptions?: ComputedRef<DataGridExtractorOptions>;
|
||||
databaseType: ComputedRef<DatabaseType | undefined>;
|
||||
tableMeta: ComputedRef<DataGridTableMeta | undefined>;
|
||||
hasCellSelection: ComputedRef<boolean>;
|
||||
selectedCells: ComputedRef<SelectionData>;
|
||||
selectedCellMatrix: ComputedRef<CellSelectionMatrix | null>;
|
||||
hasRowSelection: ComputedRef<boolean>;
|
||||
hasColumnSelection: ComputedRef<boolean>;
|
||||
selectedRowIds: Ref<Set<number>> | ComputedRef<Set<number>>;
|
||||
contextCell: ComputedRef<{ rowId: number; rowIndex: number; col: number } | null> | Ref<{ rowId: number; rowIndex: number; col: number } | null>;
|
||||
contextSelectionIsSynthetic: ComputedRef<boolean> | Ref<boolean>;
|
||||
copyText: (text: string, gridCopy?: { rows: readonly (readonly unknown[])[]; header?: readonly unknown[] }) => Promise<boolean>;
|
||||
canCopySqlInsert: (request: DataGridExtractRequest) => boolean;
|
||||
buildMongoInsert: (extractorOptions: DataGridExtractorOptions, rowLimit?: number) => Promise<string | undefined>;
|
||||
buildMongoUpdate?: (extractorOptions: DataGridExtractorOptions, rowLimit?: number) => Promise<string | undefined>;
|
||||
}
|
||||
|
||||
export function useDataGridExtractor(options: UseDataGridExtractorOptions) {
|
||||
const { t } = useI18n();
|
||||
const { toast } = useToast();
|
||||
const hasUnsupportedDiscreteSelection = computed(() => options.hasCellSelection.value && options.selectedCellMatrix.value === null);
|
||||
|
||||
function selectionData(): SelectionData | null {
|
||||
if (options.hasRowSelection.value && options.selectedRowIds.value.size > 0) {
|
||||
const rows = options.displayItems.value.filter((item) => options.selectedRowIds.value.has(item.id) && !item.isDraft).map((item) => item.data);
|
||||
return rows.length > 0 ? { columns: options.columns.value, rows } : null;
|
||||
}
|
||||
return options.hasCellSelection.value ? options.selectedCells.value : null;
|
||||
}
|
||||
|
||||
function buildRequest(extractor: DataGridCopyExtractorId, extractorOptions: DataGridExtractorOptions = options.extractorOptions?.value ?? DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS): DataGridExtractRequest | null {
|
||||
const visibleIndexes = options.visibleColumnIndexes.value;
|
||||
const sourceNames = options.allSourceColumns.value;
|
||||
const fullColumns = options.allColumns.value;
|
||||
const fullItemsById = new Map(options.allDisplayItems.value.map((item) => [item.id, item]));
|
||||
let sourceRows: unknown[][] = [];
|
||||
let selectedSourceIndexes: number[] = [];
|
||||
let selectionKind: DataGridExtractRequest["selectionKind"] = "cells";
|
||||
|
||||
const matrix = options.selectedCellMatrix.value;
|
||||
const isMultiCellSelection = !!matrix && (matrix.rowIndexes.length > 1 || matrix.columnIndexes.length > 1);
|
||||
// A right-click sets contextCell.col to the clicked column (≥ 0); the test
|
||||
// harness and non-right-click paths leave it at -1. Only treat a 1×1 matrix
|
||||
// as synthetic when there's a real right-click context.
|
||||
const hasRightClickContext = !!options.contextCell.value && options.contextSelectionIsSynthetic.value;
|
||||
|
||||
if (options.hasRowSelection.value && options.selectedRowIds.value.size > 0) {
|
||||
sourceRows = options.displayItems.value.filter((item) => options.selectedRowIds.value.has(item.id) && !item.isDraft).map((item) => (fullItemsById.get(item.id) ?? item).data);
|
||||
selectedSourceIndexes = dedupeColumnIndexes(visibleIndexes).filter((index) => index < fullColumns.length);
|
||||
selectionKind = "rows";
|
||||
} else if (isMultiCellSelection && matrix) {
|
||||
sourceRows = matrix.rowIndexes
|
||||
.map((rowIndex) => options.displayItems.value[rowIndex])
|
||||
.filter((item): item is ExtractorRowItem => !!item && !item.isDraft)
|
||||
.map((item) => (fullItemsById.get(item.id) ?? item).data);
|
||||
selectedSourceIndexes = dedupeColumnIndexes(matrix.columnIndexes.map((index) => visibleIndexes[index] ?? index)).filter((index) => index < fullColumns.length);
|
||||
if (options.hasColumnSelection.value) selectionKind = "columns";
|
||||
} else if (hasRightClickContext && options.contextCell.value) {
|
||||
// Right-click on a cell with no (or synthetic single-cell) selection: copy the full row.
|
||||
const item = fullItemsById.get(options.contextCell.value.rowId);
|
||||
if (item && !item.isDraft) {
|
||||
sourceRows = [item.data];
|
||||
selectedSourceIndexes = dedupeColumnIndexes(visibleIndexes).filter((index) => index < fullColumns.length);
|
||||
selectionKind = "rows";
|
||||
}
|
||||
} else if (matrix) {
|
||||
// Single-cell matrix without a context cell — still honor the explicit selection.
|
||||
sourceRows = matrix.rowIndexes
|
||||
.map((rowIndex) => options.displayItems.value[rowIndex])
|
||||
.filter((item): item is ExtractorRowItem => !!item && !item.isDraft)
|
||||
.map((item) => (fullItemsById.get(item.id) ?? item).data);
|
||||
selectedSourceIndexes = dedupeColumnIndexes(matrix.columnIndexes.map((index) => visibleIndexes[index] ?? index)).filter((index) => index < fullColumns.length);
|
||||
if (options.hasColumnSelection.value) selectionKind = "columns";
|
||||
}
|
||||
|
||||
if (sourceRows.length === 0 || selectedSourceIndexes.length === 0) return null;
|
||||
const requiredSourceIndexes = [...selectedSourceIndexes];
|
||||
if (extractor === "sql-updates") {
|
||||
for (const primaryKey of options.tableMeta.value?.primaryKeys ?? []) {
|
||||
const primaryKeyIndex = fullColumns.findIndex((displayName, index) => normalizeName(sourceNames?.[index] ?? displayName) === normalizeName(primaryKey));
|
||||
if (primaryKeyIndex >= 0 && !requiredSourceIndexes.includes(primaryKeyIndex)) requiredSourceIndexes.push(primaryKeyIndex);
|
||||
}
|
||||
}
|
||||
const compactIndexBySource = new Map(requiredSourceIndexes.map((sourceIndex, compactIndex) => [sourceIndex, compactIndex]));
|
||||
const columns = requiredSourceIndexes.map((sourceIndex, compactIndex) => ({
|
||||
displayName: fullColumns[sourceIndex],
|
||||
sourceName: sourceNames?.[sourceIndex],
|
||||
sourceIndex: compactIndex,
|
||||
}));
|
||||
const selectedColumnIndexes = selectedSourceIndexes.map((sourceIndex) => compactIndexBySource.get(sourceIndex)).filter((index): index is number => index !== undefined);
|
||||
const rows = sourceRows.map((row) => requiredSourceIndexes.map((sourceIndex) => row[sourceIndex]));
|
||||
const descriptor = DATA_GRID_COPY_EXTRACTOR_DESCRIPTORS[extractor];
|
||||
const tableMeta =
|
||||
descriptor.category === "sql"
|
||||
? compactTableMeta(
|
||||
options.tableMeta.value,
|
||||
columns.map((column) => column.sourceName ?? column.displayName),
|
||||
)
|
||||
: undefined;
|
||||
return {
|
||||
version: DATA_GRID_EXTRACTOR_CONTRACT_VERSION,
|
||||
extractor,
|
||||
databaseType: descriptor.category === "sql" ? options.databaseType.value : undefined,
|
||||
tableMeta,
|
||||
columns,
|
||||
selectedColumnIndexes,
|
||||
rows,
|
||||
selectionKind,
|
||||
options: normalizeDataGridExtractorOptions(extractorOptions),
|
||||
};
|
||||
}
|
||||
|
||||
function canBuildSqlUpdateRequest(): boolean {
|
||||
const request = buildRequest("sql-updates");
|
||||
const primaryKeys = request?.tableMeta?.primaryKeys ?? [];
|
||||
if (!request || primaryKeys.length === 0) return false;
|
||||
const primaryKeyNames = new Set(primaryKeys.map(normalizeName));
|
||||
const hasWritableColumn = request.selectedColumnIndexes.some((index) => {
|
||||
const column = request.columns[index];
|
||||
if (!column) return false;
|
||||
const sourceName = column.sourceName ?? column.displayName;
|
||||
return !primaryKeyNames.has(normalizeName(sourceName)) && (!request.options.sql.skipGeneratedColumns || !isAutoGeneratedColumn(sourceName, request.tableMeta)) && (!request.options.sql.skipComputedColumns || !isComputedColumn(sourceName, request.tableMeta));
|
||||
});
|
||||
if (!hasWritableColumn) return false;
|
||||
return primaryKeys.every((primaryKey) => {
|
||||
const column = request.columns.find((candidate) => normalizeName(candidate.sourceName ?? candidate.displayName) === normalizeName(primaryKey));
|
||||
return !!column && request.rows.every((row) => row[column.sourceIndex] !== null && row[column.sourceIndex] !== undefined);
|
||||
});
|
||||
}
|
||||
|
||||
function canCopyWithExtractor(extractor: DataGridCopyExtractorId): boolean {
|
||||
if (hasUnsupportedDiscreteSelection.value) return false;
|
||||
if (!options.hasRowSelection.value && !options.hasCellSelection.value && !options.contextCell.value) return false;
|
||||
if (extractorUnavailableForDatabase(extractor, options.databaseType.value)) return false;
|
||||
if (extractor === "sql-inserts") {
|
||||
const request = buildRequest(extractor);
|
||||
return request !== null && options.canCopySqlInsert(request);
|
||||
}
|
||||
if (extractor === "sql-updates") {
|
||||
// Mongo has a dedicated updateOne path that doesn't need SQL primary keys.
|
||||
if (options.databaseType.value === "mongodb") return !!options.buildMongoUpdate;
|
||||
return canBuildSqlUpdateRequest();
|
||||
}
|
||||
return selectionData() !== null;
|
||||
}
|
||||
|
||||
async function resolveMongoExtractorResult(extractor: DataGridCopyExtractorId, request: DataGridExtractRequest, rowLimit?: number) {
|
||||
if (options.databaseType.value !== "mongodb") return null;
|
||||
const builder = extractor === "sql-inserts" ? options.buildMongoInsert : extractor === "sql-updates" ? options.buildMongoUpdate : undefined;
|
||||
if (!builder) return null;
|
||||
const text = (await builder(request.options, rowLimit)) ?? "";
|
||||
if (!text) return null;
|
||||
return { text, mimeType: "application/javascript", fileExtension: "js", rowCount: rowLimit ?? request.rows.length, columnCount: request.selectedColumnIndexes.length, warnings: undefined, omittedColumns: undefined };
|
||||
}
|
||||
|
||||
async function copyWithExtractor(extractor: DataGridCopyExtractorId): Promise<boolean> {
|
||||
if (hasUnsupportedDiscreteSelection.value) {
|
||||
toast(t("grid.copyExtractorUnsupportedSelection"), 5000);
|
||||
return false;
|
||||
}
|
||||
if (!canCopyWithExtractor(extractor)) return false;
|
||||
const request = buildRequest(extractor);
|
||||
if (!request) return false;
|
||||
try {
|
||||
const mongoResult = await resolveMongoExtractorResult(extractor, request);
|
||||
const result = mongoResult ?? (await api.extractDataGridSelection(request));
|
||||
if (!result.text) return false;
|
||||
// Derive the grid paste-back payload from the effective request schema so
|
||||
// hidden support columns, row headers, NULLs, tabs, and newlines keep the
|
||||
// same shape and values as the rendered TSV.
|
||||
const isTsv = extractor === "tsv" || extractor === "tsv-with-headers";
|
||||
const gridCopy = isTsv
|
||||
? (() => {
|
||||
const includeRowHeader = request.options.dsv.includeRowHeader;
|
||||
const rows = request.rows.map((row, rowIndex) => {
|
||||
const selectedRow = request.selectedColumnIndexes.map((index) => row[index]);
|
||||
return includeRowHeader ? [rowIndex + 1, ...selectedRow] : selectedRow;
|
||||
});
|
||||
const selectedHeaders = request.selectedColumnIndexes.map((index) => request.columns[index]?.displayName ?? "");
|
||||
const header = extractor === "tsv-with-headers" ? (includeRowHeader ? ["#", ...selectedHeaders] : selectedHeaders) : undefined;
|
||||
return { rows, header };
|
||||
})()
|
||||
: undefined;
|
||||
const copied = await options.copyText(result.text, gridCopy);
|
||||
if (!copied) return false;
|
||||
showWarnings(result.warnings, result.omittedColumns);
|
||||
return true;
|
||||
} catch (error: unknown) {
|
||||
toast(t("grid.copyFailed", { message: errorMessage(error) }), 5000);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function previewWithExtractor(extractor: DataGridCopyExtractorId, extractorOptions: DataGridExtractorOptions): Promise<DataGridExtractPreview> {
|
||||
if (hasUnsupportedDiscreteSelection.value) throw new Error(t("grid.copyExtractorUnsupportedSelection"));
|
||||
const request = buildRequest(extractor, extractorOptions);
|
||||
if (!request) throw new Error(t("grid.copyExtractorEmptySelection"));
|
||||
const sourceRowCount = request.rows.length;
|
||||
const previewRowCount = Math.min(sourceRowCount, DATA_GRID_EXTRACTOR_PREVIEW_MAX_ROWS);
|
||||
const mongoResult = await resolveMongoExtractorResult(extractor, request, previewRowCount);
|
||||
const result = mongoResult ?? (await api.extractDataGridSelection({ ...request, rows: request.rows.slice(0, DATA_GRID_EXTRACTOR_PREVIEW_MAX_ROWS) }));
|
||||
if (!result.text) throw new Error(t("grid.copyExtractorEmptySelection"));
|
||||
return { ...result, sourceRowCount, truncated: sourceRowCount > result.rowCount };
|
||||
}
|
||||
|
||||
function showWarnings(warnings: Array<{ code: DataGridExtractWarningCode; message: string }> | undefined, omittedColumns: string[] | undefined) {
|
||||
if (!warnings?.length) return;
|
||||
for (const warning of warnings) {
|
||||
const message = warning.code === "omitted-columns" ? t("grid.copyExtractorWarningOmittedColumns", { columns: omittedColumns?.join(", ") || "-" }) : t("grid.copyExtractorWarningDuplicateJsonColumns");
|
||||
toast(message, 5000);
|
||||
}
|
||||
}
|
||||
|
||||
return { copyWithExtractor, previewWithExtractor, canCopyWithExtractor };
|
||||
}
|
||||
|
||||
function compactTableMeta(tableMeta: DataGridTableMeta | undefined, requiredColumns: string[]): DataGridTableMeta | undefined {
|
||||
if (!tableMeta?.columns) return tableMeta;
|
||||
const requiredNames = new Set(requiredColumns.map(normalizeName));
|
||||
return { ...tableMeta, columns: tableMeta.columns.filter((column) => requiredNames.has(normalizeName(column.name))) };
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function normalizeName(name: string): string {
|
||||
const trimmed = name.trim();
|
||||
const first = trimmed[0];
|
||||
const last = trimmed[trimmed.length - 1];
|
||||
const unquoted = (first === "`" && last === "`") || (first === '"' && last === '"') || (first === "[" && last === "]") ? trimmed.slice(1, -1) : trimmed;
|
||||
return unquoted.replace(/[a-z]/g, (character) => character.toUpperCase());
|
||||
}
|
||||
|
||||
function columnExtra(column: string, tableMeta: DataGridTableMeta | undefined): string {
|
||||
const columnInfo = tableMeta?.columns?.find((item) => normalizeName(item.name) === normalizeName(column));
|
||||
return columnInfo?.extra?.toLowerCase() ?? "";
|
||||
}
|
||||
|
||||
function isAutoGeneratedColumn(column: string, tableMeta: DataGridTableMeta | undefined): boolean {
|
||||
return /\b(auto_increment|autoincrement|identity)\b/.test(columnExtra(column, tableMeta));
|
||||
}
|
||||
|
||||
function isComputedColumn(column: string, tableMeta: DataGridTableMeta | undefined): boolean {
|
||||
const extra = columnExtra(column, tableMeta);
|
||||
return extra.includes("generated always as") && !extra.includes("identity");
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ref, computed, getCurrentScope, onScopeDispose, type ComputedRef, type Ref } from "vue";
|
||||
import { allCellsSelectionRange, extractColumnsSelection, extractSelection, isCellInSelection, normalizeSelectionRange, normalizeSelectedColumnIndexes, rowSelectionRange, type CellPosition, type CellSelectionMatrix, type CellSelectionRange, type SelectionData } from "@/lib/dataGrid/gridSelection";
|
||||
import { allCellsSelectionRange, extractColumnsSelection, extractSelection, isCellInSelection, normalizeSelectionRange, normalizeSelectedColumnIndexes, type CellPosition, type CellSelectionMatrix, type CellSelectionRange, type SelectionData } from "@/lib/dataGrid/gridSelection";
|
||||
import type { DataGridRuntimeScope } from "@/lib/dataGrid/dataGridRuntime";
|
||||
|
||||
type CellValue = string | number | boolean | null;
|
||||
@@ -25,21 +25,29 @@ export interface UseDataGridSelectionOptions {
|
||||
gridRef: Ref<HTMLDivElement | undefined>;
|
||||
getScrollElement?: () => HTMLElement | null;
|
||||
cellFromClientPoint?: (clientX: number, clientY: number) => CellPosition | null;
|
||||
rowFromClientPoint?: (clientX: number, clientY: number) => number | null;
|
||||
onUserCellSelection?: () => void;
|
||||
runtimeScope?: DataGridRuntimeScope;
|
||||
}
|
||||
|
||||
const AUTO_SCROLL_EDGE_SIZE = 40;
|
||||
const AUTO_SCROLL_MAX_SPEED = 28;
|
||||
type RowSelectionOperation = "replace" | "add" | "remove";
|
||||
|
||||
export function useDataGridSelection(options: UseDataGridSelectionOptions) {
|
||||
const { columns, displayItems, editingCell, showTranspose, transposeRowIndex, gridRef, getScrollElement, cellFromClientPoint } = options;
|
||||
const { columns, displayItems, editingCell, showTranspose, transposeRowIndex, gridRef, getScrollElement, cellFromClientPoint, rowFromClientPoint } = options;
|
||||
|
||||
const selectionAnchor = ref<CellPosition | null>(null);
|
||||
const selectionFocus = ref<CellPosition | null>(null);
|
||||
const isSelectingCells = ref(false);
|
||||
const isSelectingRows = ref(false);
|
||||
let selectionPointerClientX = 0;
|
||||
let selectionPointerClientY = 0;
|
||||
let selectionAutoScrollFrame = 0;
|
||||
let rowSelectionRangeAnchorIndex = -1;
|
||||
let rowSelectionFocusIndex = -1;
|
||||
let rowSelectionBaseIds = new Set<number>();
|
||||
let rowSelectionOperation: RowSelectionOperation = "replace";
|
||||
|
||||
const isSelectingAll = ref(false);
|
||||
const selectedCellKeys = ref<Set<string>>(new Set());
|
||||
@@ -159,19 +167,11 @@ export function useDataGridSelection(options: UseDataGridSelectionOptions) {
|
||||
}
|
||||
|
||||
function selectRow(rowIndex: number) {
|
||||
const range = rowSelectionRange(rowIndex, columns.value.length);
|
||||
if (!range) return;
|
||||
selectedCellKeys.value = new Set();
|
||||
selectionAnchor.value = { rowIndex: range.startRow, colIndex: range.startCol };
|
||||
selectionFocus.value = { rowIndex: range.endRow, colIndex: range.endCol };
|
||||
}
|
||||
|
||||
function selectRows(startRow: number, endRow: number) {
|
||||
const range = rowSelectionRange(startRow, columns.value.length, endRow);
|
||||
if (!range) return;
|
||||
selectedCellKeys.value = new Set();
|
||||
selectionAnchor.value = { rowIndex: range.startRow, colIndex: range.startCol };
|
||||
selectionFocus.value = { rowIndex: range.endRow, colIndex: range.endCol };
|
||||
const item = displayItems.value[rowIndex];
|
||||
if (!item) return;
|
||||
clearCellSelection();
|
||||
selectedRowIds.value = new Set([item.id]);
|
||||
lastClickedRowIndex.value = rowIndex;
|
||||
}
|
||||
|
||||
function selectColumns(startCol: number, endCol: number, options?: { merge?: boolean }) {
|
||||
@@ -270,47 +270,104 @@ export function useDataGridSelection(options: UseDataGridSelectionOptions) {
|
||||
next.add(rowId);
|
||||
}
|
||||
selectedRowIds.value = next;
|
||||
selectContiguousRowIds(next);
|
||||
lastClickedRowIndex.value = rowIndex;
|
||||
} else if (isShift && lastClickedRowIndex.value !== null) {
|
||||
const start = Math.min(lastClickedRowIndex.value, rowIndex);
|
||||
const end = Math.max(lastClickedRowIndex.value, rowIndex);
|
||||
const next = new Set(selectedRowIds.value);
|
||||
for (let i = start; i <= end; i++) {
|
||||
const item = displayItems.value[i];
|
||||
if (item) next.add(item.id);
|
||||
}
|
||||
selectedRowIds.value = next;
|
||||
selectRows(start, end);
|
||||
selectedRowIds.value = rowIdsInRange(lastClickedRowIndex.value, rowIndex);
|
||||
} else {
|
||||
selectedRowIds.value = new Set([rowId]);
|
||||
selectRow(rowIndex);
|
||||
lastClickedRowIndex.value = rowIndex;
|
||||
}
|
||||
}
|
||||
|
||||
function selectContiguousRowIds(rowIds: Set<number>) {
|
||||
if (rowIds.size === 0) {
|
||||
clearCellSelection();
|
||||
return;
|
||||
function rowIdsInRange(startRow: number, endRow: number): Set<number> {
|
||||
const ids = new Set<number>();
|
||||
const start = Math.max(0, Math.min(startRow, endRow));
|
||||
const end = Math.min(displayItems.value.length - 1, Math.max(startRow, endRow));
|
||||
for (let index = start; index <= end; index++) {
|
||||
const item = displayItems.value[index];
|
||||
if (item) ids.add(item.id);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
const indexes = displayItems.value.reduce<number[]>((selectedIndexes, item, index) => {
|
||||
if (rowIds.has(item.id)) selectedIndexes.push(index);
|
||||
return selectedIndexes;
|
||||
}, []);
|
||||
if (indexes.length !== rowIds.size) {
|
||||
clearCellSelection();
|
||||
return;
|
||||
function applyDraggedRowRange(focusRowIndex: number) {
|
||||
if (focusRowIndex === rowSelectionFocusIndex) return;
|
||||
const previousFocusIndex = rowSelectionFocusIndex;
|
||||
const previousStart = previousFocusIndex < 0 ? 0 : Math.min(rowSelectionRangeAnchorIndex, previousFocusIndex);
|
||||
const previousEnd = previousFocusIndex < 0 ? -1 : Math.max(rowSelectionRangeAnchorIndex, previousFocusIndex);
|
||||
const nextStart = Math.min(rowSelectionRangeAnchorIndex, focusRowIndex);
|
||||
const nextEnd = Math.max(rowSelectionRangeAnchorIndex, focusRowIndex);
|
||||
const changedStart = previousFocusIndex < 0 ? nextStart : Math.min(previousStart, nextStart);
|
||||
const changedEnd = Math.max(previousEnd, nextEnd);
|
||||
const selectedIds = selectedRowIds.value;
|
||||
for (let index = changedStart; index <= changedEnd; index++) {
|
||||
const wasInRange = index >= previousStart && index <= previousEnd;
|
||||
const isInRange = index >= nextStart && index <= nextEnd;
|
||||
if (wasInRange === isInRange) continue;
|
||||
const item = displayItems.value[index];
|
||||
if (!item) continue;
|
||||
if (isInRange) {
|
||||
if (rowSelectionOperation === "remove") selectedIds.delete(item.id);
|
||||
else selectedIds.add(item.id);
|
||||
} else if (rowSelectionOperation !== "replace" && rowSelectionBaseIds.has(item.id)) {
|
||||
selectedIds.add(item.id);
|
||||
} else {
|
||||
selectedIds.delete(item.id);
|
||||
}
|
||||
}
|
||||
rowSelectionFocusIndex = focusRowIndex;
|
||||
}
|
||||
|
||||
const start = Math.min(...indexes);
|
||||
const end = Math.max(...indexes);
|
||||
if (end - start + 1 !== indexes.length) {
|
||||
clearCellSelection();
|
||||
return;
|
||||
function updateRowSelectionFromPointer() {
|
||||
const rowIndex = rowFromClientPoint?.(selectionPointerClientX, selectionPointerClientY);
|
||||
if (rowIndex === null || rowIndex === undefined) return;
|
||||
applyDraggedRowRange(rowIndex);
|
||||
}
|
||||
|
||||
function handleRowSelectionPointerMove(event: MouseEvent) {
|
||||
if (!isSelectingRows.value) return;
|
||||
selectionPointerClientX = event.clientX;
|
||||
selectionPointerClientY = event.clientY;
|
||||
if (!selectionAutoScrollFrame) selectionAutoScrollFrame = requestAnimationFrame(runSelectionAutoScroll);
|
||||
}
|
||||
|
||||
function finishRowSelection(event?: MouseEvent) {
|
||||
if (!isSelectingRows.value) return;
|
||||
if (event) {
|
||||
selectionPointerClientX = event.clientX;
|
||||
selectionPointerClientY = event.clientY;
|
||||
}
|
||||
selectRows(start, end);
|
||||
updateRowSelectionFromPointer();
|
||||
isSelectingRows.value = false;
|
||||
// Keep the range origin stable across repeated Shift selections. For a
|
||||
// plain or meta selection this is the row where the gesture started; for
|
||||
// Shift it remains the previous anchor.
|
||||
lastClickedRowIndex.value = rowSelectionRangeAnchorIndex >= 0 ? rowSelectionRangeAnchorIndex : lastClickedRowIndex.value;
|
||||
document.removeEventListener("mouseup", finishRowSelection);
|
||||
document.removeEventListener("mousemove", handleRowSelectionPointerMove);
|
||||
stopSelectionAutoScroll();
|
||||
}
|
||||
|
||||
function beginRowSelection(rowIndex: number, rowId: number, event: MouseEvent) {
|
||||
if (event.button !== 0) return;
|
||||
event.preventDefault();
|
||||
focusGridWithoutScrolling();
|
||||
clearCellSelection();
|
||||
|
||||
const isMeta = event.metaKey || event.ctrlKey;
|
||||
const isShift = event.shiftKey;
|
||||
rowSelectionRangeAnchorIndex = isShift && lastClickedRowIndex.value !== null ? lastClickedRowIndex.value : rowIndex;
|
||||
rowSelectionFocusIndex = -1;
|
||||
rowSelectionBaseIds = new Set(selectedRowIds.value);
|
||||
rowSelectionOperation = isMeta ? (rowSelectionBaseIds.has(rowId) ? "remove" : "add") : "replace";
|
||||
selectedRowIds.value = rowSelectionOperation === "replace" ? new Set() : new Set(rowSelectionBaseIds);
|
||||
applyDraggedRowRange(rowIndex);
|
||||
|
||||
isSelectingRows.value = true;
|
||||
selectionPointerClientX = event.clientX;
|
||||
selectionPointerClientY = event.clientY;
|
||||
document.addEventListener("mouseup", finishRowSelection);
|
||||
document.addEventListener("mousemove", handleRowSelectionPointerMove);
|
||||
}
|
||||
|
||||
function finishCellSelection() {
|
||||
@@ -343,20 +400,24 @@ export function useDataGridSelection(options: UseDataGridSelectionOptions) {
|
||||
|
||||
function runSelectionAutoScroll() {
|
||||
selectionAutoScrollFrame = 0;
|
||||
if (!isSelectingCells.value) return;
|
||||
if (!isSelectingCells.value && !isSelectingRows.value) return;
|
||||
|
||||
const scroller = getScrollElement?.();
|
||||
if (!scroller) return;
|
||||
if (!scroller) {
|
||||
if (isSelectingRows.value) updateRowSelectionFromPointer();
|
||||
else updateSelectionFromPointer();
|
||||
return;
|
||||
}
|
||||
const rect = scroller.getBoundingClientRect();
|
||||
const deltaX = selectionScrollVelocity(selectionPointerClientX, rect.left, rect.right);
|
||||
const deltaX = isSelectingCells.value ? selectionScrollVelocity(selectionPointerClientX, rect.left, rect.right) : 0;
|
||||
const deltaY = selectionScrollVelocity(selectionPointerClientY, rect.top, rect.bottom);
|
||||
const previousLeft = scroller.scrollLeft;
|
||||
const previousTop = scroller.scrollTop;
|
||||
|
||||
scroller.scrollLeft += deltaX;
|
||||
scroller.scrollTop += deltaY;
|
||||
updateSelectionFromPointer();
|
||||
|
||||
if (isSelectingRows.value) updateRowSelectionFromPointer();
|
||||
else updateSelectionFromPointer();
|
||||
if (scroller.scrollLeft !== previousLeft || scroller.scrollTop !== previousTop) {
|
||||
selectionAutoScrollFrame = requestAnimationFrame(runSelectionAutoScroll);
|
||||
}
|
||||
@@ -390,8 +451,13 @@ export function useDataGridSelection(options: UseDataGridSelectionOptions) {
|
||||
document.addEventListener("mousemove", handleSelectionPointerMove);
|
||||
}
|
||||
|
||||
if (options.runtimeScope) options.runtimeScope.addCleanup(finishCellSelection);
|
||||
else if (getCurrentScope()) onScopeDispose(finishCellSelection);
|
||||
function finishSelection() {
|
||||
finishCellSelection();
|
||||
finishRowSelection();
|
||||
}
|
||||
|
||||
if (options.runtimeScope) options.runtimeScope.addCleanup(finishSelection);
|
||||
else if (getCurrentScope()) onScopeDispose(finishSelection);
|
||||
|
||||
function extendCellSelection(rowIndex: number, colIndex: number) {
|
||||
if (!isSelectingCells.value || !selectionAnchor.value) return;
|
||||
@@ -401,6 +467,7 @@ export function useDataGridSelection(options: UseDataGridSelectionOptions) {
|
||||
function handleDataCellMousedown(rowIndex: number, colIndex: number, _rowId: number, event: MouseEvent) {
|
||||
if (event.button !== 0) return;
|
||||
if (editingCell.value) return;
|
||||
options.onUserCellSelection?.();
|
||||
|
||||
const isMeta = event.metaKey || event.ctrlKey;
|
||||
const isShift = event.shiftKey;
|
||||
@@ -452,6 +519,7 @@ export function useDataGridSelection(options: UseDataGridSelectionOptions) {
|
||||
selectionAnchor,
|
||||
selectionFocus,
|
||||
isSelectingCells,
|
||||
isSelectingRows,
|
||||
selectedRange,
|
||||
selectedCells,
|
||||
selectedCellMatrix,
|
||||
@@ -480,6 +548,8 @@ export function useDataGridSelection(options: UseDataGridSelectionOptions) {
|
||||
hasColumnSelection,
|
||||
clearRowSelection,
|
||||
handleRowClick,
|
||||
beginRowSelection,
|
||||
finishRowSelection,
|
||||
handleDataCellMousedown,
|
||||
isRowSelected,
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user