feat(grid): paste clipboard data as new rows

This commit is contained in:
YangJunzhe authored and GitHub committed 2026-10-07 03:15:37 +08:00
1 parent 03b50e167e
commit 3d9e590e94
13 files changed
+214 -15

No files matched your search

+33 -1
View File
@@ -4341,6 +4341,7 @@ const {
onEditKeydown,
addRows: addEditorRows,
appendPastedRowsToNewRow,
appendPastedRowsAsNewRows,
cloneRow: cloneEditorRow,
showDeleteRowConfirm,
requestDeleteRow,
@@ -4929,7 +4930,11 @@ function insertRows(count: number, position: "above" | "below" | "end") {
}
}
function handleAddRowMenuSelect(value: string) {
async function handleAddRowMenuSelect(value: string) {
if (value === "paste-new-rows") {
await pasteClipboardAsNewRows();
return;
}
if (value === "insert-multiple") {
insertRowsDialogOpen.value = true;
return;
@@ -4955,6 +4960,7 @@ const addRowToolbarCapability = computed<DataGridToolbarAddRowCapability>(() =>
visible: canInsertRows.value,
items: [
{ value: "insert-multiple", label: t("grid.insertMultipleRows") },
{ value: "paste-new-rows", label: t("grid.pasteAsNewRows"), disabled: isSaving.value || isConditionalUpdateActive.value },
{
value: "position-above",
label: t("grid.insertPositionAbove"),
@@ -8820,6 +8826,32 @@ async function pasteClipboardIntoSelection() {
pasteTextIntoGrid(text);
}
async function pasteClipboardAsNewRows() {
if (!canInsertRows.value || isSaving.value || isConditionalUpdateActive.value) return;
const operation = dataGridResultLifecycle.beginOperation();
// Capture the column mapping with the result, before the asynchronous read.
const columnIndexes = [...visibleColumnIndexes.value];
try {
const text = await readTextFromClipboard();
if (!dataGridResultLifecycle.isCurrent(operation) || !canInsertRows.value || isSaving.value || isConditionalUpdateActive.value) return;
const insertPaste = parseInsertStatementPaste(text);
const firstNewRowId = -(newRows.value.length + 1);
const result = appendPastedRowsAsNewRows(insertPaste?.rows ?? parseDataGridClipboard(text), columnIndexes, insertPaste?.columnNames);
if (!result.ok) {
toast(batchAppendPasteError(result.reason), 5000);
return;
}
toast(t("grid.pasted"));
nextTick(() => {
const displayIndex = displayRowIndexById(firstNewRowId);
if (displayIndex >= 0) scrollGridRowIntoView(displayIndex);
});
focusInsertedTransposeRecord(firstNewRowId);
} catch (error) {
if (dataGridResultLifecycle.isCurrent(operation)) toast(t("grid.copyFailed", { message: error instanceof Error ? error.message : String(error) }), 5000);
}
}
function batchAppendPasteTargetRowId(): number | null {
const rowId = batchAppendPasteRowId.value;
if (rowId === null) return null;
@@ -1,6 +1,6 @@
// @vitest-environment happy-dom
import { createApp, defineComponent, h, markRaw, nextTick, type App, type PropType } from "vue";
import { createApp, defineComponent, h, markRaw, nextTick, shallowRef, type App, type PropType } from "vue";
import { createPinia, setActivePinia } from "pinia";
import { afterEach, describe, expect, it, vi } from "vitest";
import i18n from "@/i18n";
@@ -8,6 +8,12 @@ import type { QueryResult } from "@/types/database";
import type { CustomSaveHandler } from "@/composables/useDataGridEditor";
import { buildMongoUpdateDocument } from "@/lib/mongo/mongoDocumentValues";
import { TooltipProvider } from "@/components/ui/tooltip";
import { readTextFromClipboard } from "@/lib/common/clipboard";
vi.mock("@/lib/common/clipboard", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/common/clipboard")>()),
readTextFromClipboard: vi.fn(),
}));
// DataGrid.vue imports RecycleScroller directly (no global registration),
// so the module itself must be stubbed for deterministic row rendering.
@@ -88,6 +94,8 @@ interface MountGridOptions {
readonlyColumnIndexes?: number[];
databaseType?: "dameng" | "mongodb";
customSaveHandler?: CustomSaveHandler;
editable?: boolean;
allowInsertRows?: boolean;
}
function mountGrid(options: MountGridOptions = {}) {
@@ -95,7 +103,7 @@ function mountGrid(options: MountGridOptions = {}) {
setActivePinia(pinia);
const settingsStore = useSettingsStore();
settingsStore.updateEditorSettings({ dataGridRenderMode: "canvas", dataGridHideNullColumns: options.hideNullColumns ?? false, dataGridQuickEntry: options.quickEntry ?? false });
const gridResult = markRaw(options.result ?? defaultResult());
const resultRef = shallowRef(markRaw(options.result ?? defaultResult()));
const host = document.createElement("div");
document.body.append(host);
@@ -108,15 +116,16 @@ function mountGrid(options: MountGridOptions = {}) {
{
default: () =>
h(DataGrid, {
result: gridResult,
result: resultRef.value,
databaseType: options.databaseType ?? "dameng",
context: "table-data",
editable: true,
editable: options.editable ?? true,
allowInsertRows: options.allowInsertRows,
customSaveHandler: options.customSaveHandler,
readonlyColumnIndexes: options.readonlyColumnIndexes,
tableMeta: {
tableName: "paste_target",
columns: gridResult.columns.map((name, index) => ({
columns: resultRef.value.columns.map((name, index) => ({
name,
data_type: index === 0 ? "int" : "varchar",
is_nullable: index !== 0,
@@ -139,7 +148,7 @@ function mountGrid(options: MountGridOptions = {}) {
settingsStore.updateEditorSettings({ dataGridRenderMode: "dom" });
const mounted = { app, host };
mountedApps.push(mounted);
return mounted;
return { ...mounted, resultRef };
}
async function settle() {
@@ -211,6 +220,94 @@ afterEach(() => {
app.unmount();
host.remove();
}
vi.mocked(readTextFromClipboard).mockReset();
});
async function pasteAsNewRows(host: HTMLElement) {
const trigger = [...host.querySelectorAll<HTMLElement>("[aria-haspopup='menu']")].find((button) => button.getAttribute("aria-label") === i18n.global.t("grid.addRow"));
if (!trigger) throw new Error("Add row menu trigger not found");
trigger.click();
await settle();
await new Promise((resolve) => setTimeout(resolve, 20));
await settle();
const item = [...document.querySelectorAll<HTMLElement>("[role='menuitem']")].find((item) => item.textContent?.trim() === i18n.global.t("grid.pasteAsNewRows"));
if (!item) throw new Error("Paste as new rows menu item not found");
item.click();
await settle();
}
describe("DataGrid paste as new rows", () => {
it("inserts clipboard rows from the toolbar without preallocated blank rows or a selection", async () => {
const { host } = mountGrid({ hideNullColumns: true });
await settle();
vi.mocked(readTextFromClipboard).mockResolvedValue("2\tAda\tLovelace\n3\tGrace\tHopper");
await pasteAsNewRows(host);
expect(readTextFromClipboard).toHaveBeenCalledOnce();
expect(displayRows(host)).toHaveLength(3);
expect(visibleCellTexts(displayRows(host)[0]!)).toEqual(["1", "seed-2", "seed-3"]);
expect(pendingRows(host).map(visibleCellTexts)).toEqual([
["2", "Ada", "Lovelace"],
["3", "Grace", "Hopper"],
]);
});
it("drops a delayed clipboard read when the result is replaced", async () => {
const { host, resultRef } = mountGrid();
await settle();
let finishRead!: (text: string) => void;
vi.mocked(readTextFromClipboard).mockReturnValue(
new Promise((resolve) => {
finishRead = resolve;
}),
);
await pasteAsNewRows(host);
resultRef.value = markRaw({ ...defaultResult(), rows: [[99, null, "replacement", "result"]] });
await settle();
finishRead("2\tignored\tAda\tLovelace");
await settle();
expect(displayRows(host)).toHaveLength(1);
expect(pendingRows(host)).toHaveLength(0);
expect(visibleCellTexts(displayRows(host)[0]!)[0]).toBe("99");
});
it("passes pasted drafts through the existing save handler without modifying existing rows", async () => {
const save = vi.fn<CustomSaveHandler["save"]>().mockResolvedValue();
const { host } = mountGrid({ customSaveHandler: { canInsert: true, save } });
await settle();
vi.mocked(readTextFromClipboard).mockResolvedValue("2\tkeep\tAda\tLovelace");
await pasteAsNewRows(host);
host.querySelector<HTMLElement>("[data-toolbar-action='save']")!.click();
await settle();
expect(save).toHaveBeenCalledOnce();
expect(save.mock.calls[0]![0].newRows).toEqual([[2, "keep", "Ada", "Lovelace"]]);
expect(save.mock.calls[0]![0].dirtyRows.size).toBe(0);
expect(save.mock.calls[0]![0].rows).toEqual(defaultResult().rows);
});
it.each(["empty", "unavailable"])("leaves no placeholder rows when the clipboard is %s", async (clipboardState) => {
const { host } = mountGrid();
await settle();
if (clipboardState === "empty") vi.mocked(readTextFromClipboard).mockResolvedValue("");
else vi.mocked(readTextFromClipboard).mockRejectedValue(new Error("Clipboard access denied"));
await pasteAsNewRows(host);
expect(pendingRows(host)).toHaveLength(0);
expect(displayRows(host)).toHaveLength(1);
});
it.each([{ editable: false }, { allowInsertRows: false }])("hides insertion actions when unsupported: %j", async (options) => {
const { host } = mountGrid(options);
await settle();
expect(host.querySelector("[data-toolbar-action='addRow']")).toBeNull();
expect(readTextFromClipboard).not.toHaveBeenCalled();
});
});
describe("DataGrid multi-row paste from a blank cell", () => {
@@ -693,6 +693,55 @@ describe("useDataGridEditor appendPastedRowsToNewRow", () => {
mocks.getConfig.mockReturnValue({ id: "connection-1", db_type: "postgres" });
});
it("pastes new rows without preallocating blanks and preserves existing edits in one undo step", () => {
const editor = createEditor(undefined, true, undefined, undefined, [["old", "keep", "last"]]);
editor.newRows.value = [["pending", null, null]];
editor.applyCellValue(0, 0, "edited");
const result = editor.appendPastedRowsAsNewRows(
[
["Ada", "Lovelace"],
["Grace", "Hopper"],
],
[0, 2],
);
expect(result).toEqual({ ok: true, rowCount: 2 });
expect(editor.newRows.value).toEqual([
["pending", null, null],
["Ada", null, "Lovelace"],
["Grace", null, "Hopper"],
]);
expect(editor.dirtyRows.value.get(0)?.get(0)).toBe("edited");
editor.undoPendingChange();
expect(editor.newRows.value).toEqual([["pending", null, null]]);
expect(editor.dirtyRows.value.get(0)?.get(0)).toBe("edited");
editor.redoPendingChange();
expect(editor.newRows.value).toHaveLength(3);
});
it("aligns INSERT columns and clears generated keys without creating a placeholder row", () => {
const editor = createEditor(undefined, true, undefined, undefined, [], undefined, [
{ name: "first", data_type: "integer", extra: "autoincrement" },
{ name: "hidden", data_type: "varchar" },
{ name: "last", data_type: "varchar" },
]);
editor.newRows.value = [];
expect(editor.appendPastedRowsAsNewRows([["Lovelace", "42"]], [0, 2], ["last", "first"])).toEqual({ ok: true, rowCount: 1 });
expect(editor.newRows.value).toEqual([[null, null, "Lovelace"]]);
});
it("rejects empty or read-only pastes without leaving blank rows", () => {
const editor = createEditor(undefined, true, undefined, [0]);
editor.newRows.value = [];
expect(editor.appendPastedRowsAsNewRows([], [0, 2])).toEqual({ ok: false, reason: "empty-paste" });
expect(editor.appendPastedRowsAsNewRows([["Ada"]], [0])).toEqual({ ok: false, reason: "readonly-column" });
expect(editor.newRows.value).toEqual([]);
expect(editor.hasPendingChanges.value).toBe(false);
});
it("fills the selected blank new row and appends remaining rows using visible columns", () => {
const editor = createEditor();
@@ -1240,22 +1240,32 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
return row.every((value) => value === null || (typeof value === "string" && value.trim() === ""));
}
function appendPastedRowsAsNewRows(pastedRows: readonly (readonly (string | null)[])[], columnIndexes: readonly number[], columnNames?: readonly string[] | null): DataGridAppendPastedRowsResult {
return appendPastedRows(null, pastedRows, columnIndexes, columnNames);
}
function appendPastedRowsToNewRow(targetRowId: number, pastedRows: readonly (readonly (string | null)[])[], columnIndexes: readonly number[], columnNames?: readonly string[] | null): DataGridAppendPastedRowsResult {
return appendPastedRows(targetRowId, pastedRows, columnIndexes, columnNames);
}
// A null target appends populated rows directly, without a preparatory blank
// row or a second undo entry. Cell/row paste still validates its blank target.
function appendPastedRows(targetRowId: number | null, pastedRows: readonly (readonly (string | null)[])[], columnIndexes: readonly number[], columnNames?: readonly string[] | null): DataGridAppendPastedRowsResult {
if (!editable.value) return { ok: false, reason: "not-editable" };
if (pastedRows.every((row) => row.every((value) => value === ""))) {
return { ok: false, reason: "empty-paste" };
}
const target = getRowItem(targetRowId);
if ((!target?.isNew && !target?.isDraft) || target.isDeleted || isSavingNewRow(target)) {
const target = targetRowId === null ? undefined : getRowItem(targetRowId);
if (targetRowId !== null && ((!target?.isNew && !target?.isDraft) || target.isDeleted || isSavingNewRow(target))) {
return { ok: false, reason: "invalid-target" };
}
const targetIsDraft = target.isDraft === true;
const targetIsDraft = target?.isDraft === true;
if (targetIsDraft) ensureQuickEntryDraftRow();
const targetNewIndex = target.newIndex;
const targetNewIndex = target?.newIndex;
const targetRow = targetIsDraft ? quickEntryDraftRow.value : targetNewIndex === undefined ? undefined : newRows.value[targetNewIndex];
if (!targetRow || !isBlankNewRow(targetRow)) return { ok: false, reason: "target-not-empty" };
if (targetRowId !== null && (!targetRow || !isBlankNewRow(targetRow))) return { ok: false, reason: "target-not-empty" };
const pastedColumnCount = Math.max(...pastedRows.map((row) => row.length));
if (pastedColumnCount <= 0) return { ok: false, reason: "empty-paste" };
@@ -1279,12 +1289,13 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
} else {
columnIndexes.slice(0, pastedColumnCount).forEach((columnIndex, valueIndex) => valueTargets.push({ columnIndex, valueIndex }));
}
if (valueTargets.length === 0) return { ok: false, reason: "no-matching-columns" };
if (valueTargets.some(({ columnIndex }) => !canEditColumn(columnIndex))) return { ok: false, reason: "readonly-column" };
const nextRows = newRows.value.map((row) => [...row]);
const nextMeta = cloneNewRowMeta(newRowMeta.value);
let reusableNewRowCount = 0;
if (!targetIsDraft) {
if (targetNewIndex !== undefined) {
for (let rowIndex = targetNewIndex!; rowIndex < nextRows.length && reusableNewRowCount < pastedRows.length; rowIndex++) {
if (!isBlankNewRow(nextRows[rowIndex]!)) break;
reusableNewRowCount++;
@@ -1307,10 +1318,10 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
});
pushUndoSnapshot();
if (targetIsDraft) {
if (targetIsDraft || targetRowId === null) {
nextRows.push(...mappedRows);
for (let i = 0; i < mappedRows.length; i++) nextMeta.push(allocateNewRowMeta(null));
quickEntryDraftRow.value = emptyDraftRow();
if (targetIsDraft) quickEntryDraftRow.value = emptyDraftRow();
} else {
// Reused blank rows keep their original placement; rows added beyond the
// reusable count append at the end (preserving existing paste behavior).
@@ -2351,6 +2362,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
addRow,
addRows,
appendPastedRowsToNewRow,
appendPastedRowsAsNewRows,
cloneRow,
cloneRows,
applyDeleteRows,
+1
View File
@@ -2585,6 +2585,7 @@ export default {
dismiss: "Dismiss",
addRow: "Add Row",
insertMultipleRows: "Insert Multiple Rows…",
pasteAsNewRows: "Paste as new rows",
insertRowsTitle: "Insert Multiple Rows",
insertRowsDescription: "Create this many unsaved draft rows. Empty rows are ignored when saving; after saving, the display order follows the current query.",
insertRowCountLabel: "Row count",
+1
View File
@@ -2410,6 +2410,7 @@ export default withEnglishFallback({
quickEntryDraftPlaceholder: "Nueva",
addRow: "Agregar fila",
insertMultipleRows: "Insertar varias filas…",
pasteAsNewRows: "Pegar como filas nuevas",
insertRowsTitle: "Insertar varias filas",
insertRowsDescription: "Crea este número de filas de borrador sin guardar. Las filas vacías se ignoran al guardar; después de guardar, el orden de visualización sigue la consulta actual.",
insertRowCountLabel: "Número de filas",
+1
View File
@@ -2303,6 +2303,7 @@ export default withEnglishFallback({
dismiss: "Ignora",
addRow: "Aggiungi Riga",
insertMultipleRows: "Inserisci più righe…",
pasteAsNewRows: "Incolla come nuove righe",
insertRowsTitle: "Inserisci più righe",
insertRowsDescription: "Crea questo numero di righe di bozza non salvate. Le righe vuote vengono ignorate al salvataggio; dopo il salvataggio, l'ordine di visualizzazione segue la query corrente.",
insertRowCountLabel: "Numero di righe",
+1
View File
@@ -2310,6 +2310,7 @@ export default withEnglishFallback({
dismiss: "閉じる",
addRow: "行を追加",
insertMultipleRows: "複数行を挿入…",
pasteAsNewRows: "新しい行として貼り付け",
insertRowsTitle: "複数行を挿入",
insertRowsDescription: "未保存の下書き行を指定数作成します。保存時、空の行は無視されます。保存後の表示順は現在のクエリに従います。",
insertRowCountLabel: "行数",
+1
View File
@@ -2357,6 +2357,7 @@ export default withEnglishFallback({
dismiss: "닫기",
addRow: "행 추가",
insertMultipleRows: "여러 행 삽입…",
pasteAsNewRows: "새 행으로 붙여넣기",
insertRowsTitle: "여러 행 삽입",
insertRowsDescription: "저장되지 않은 초안 행을 지정한 개수만큼 만듭니다. 저장 시 비어 있는 행은 무시되며, 저장 후 표시 순서는 현재 쿼리를 따릅니다.",
insertRowCountLabel: "행 수",
+1
View File
@@ -2305,6 +2305,7 @@ export default withEnglishFallback({
dismiss: "Dispensar",
addRow: "Adicionar Linha",
insertMultipleRows: "Inserir várias linhas…",
pasteAsNewRows: "Colar como novas linhas",
insertRowsTitle: "Inserir várias linhas",
insertRowsDescription: "Cria este número de linhas de rascunho não salvas. Linhas vazias são ignoradas ao salvar; após salvar, a ordem de exibição segue a consulta atual.",
insertRowCountLabel: "Número de linhas",
+1
View File
@@ -2479,6 +2479,7 @@ export default withEnglishFallback({
dismiss: "Закрыть",
addRow: "Добавить строку",
insertMultipleRows: "Вставить несколько строк…",
pasteAsNewRows: "Вставить как новые строки",
insertRowsTitle: "Вставка нескольких строк",
insertRowsDescription: "Создаёт указанное число несохранённых черновых строк. Пустые строки игнорируются при сохранении; после сохранения порядок отображения соответствует текущему запросу.",
insertRowCountLabel: "Количество строк",
+1
View File
@@ -2520,6 +2520,7 @@ export default withEnglishFallback({
dismiss: "关闭",
addRow: "新增行",
insertMultipleRows: "插入多行…",
pasteAsNewRows: "粘贴为新行",
insertRowsTitle: "新增多行",
insertRowsDescription: "创建指定数量的未保存草稿行。保存时未填写的空行会被忽略;保存后的显示位置由当前查询排序决定。",
insertRowCountLabel: "行数",
+1
View File
@@ -2306,6 +2306,7 @@ export default withEnglishFallback({
dismiss: "關閉",
addRow: "新增資料",
insertMultipleRows: "插入多行…",
pasteAsNewRows: "貼上為新列",
insertRowsTitle: "新增多行",
insertRowsDescription: "建立指定數量的未儲存草稿列。儲存時未填寫的空白列會被忽略;儲存後的顯示位置由目前查詢排序決定。",
insertRowCountLabel: "列數",