diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vue index f9150bf04a..5d7c68f093 100644 --- a/apps/desktop/src/components/grid/DataGrid.vue +++ b/apps/desktop/src/components/grid/DataGrid.vue @@ -102,7 +102,6 @@ import { defaultTransposeRecordWidth, minTransposeFieldWidth, minTransposeRecordWidth, - nextAppendedTransposeState, nextContextTransposeState, nextKeyboardTransposeState, nextTransposeState, @@ -212,7 +211,8 @@ import { useConnectionStore } from "@/stores/connectionStore"; import { useQueryStore } from "@/stores/queryStore"; import { useSettingsStore } from "@/stores/settingsStore"; import { simpleDataGridOrderByMatchesSort, simpleDataGridOrderByReferencesMissingColumn, type DataGridSortDirection, type DataGridSortMode } from "@/lib/dataGrid/dataGridSort"; -import { DATA_GRID_CONDITION_TOOLBAR_MIN_WIDTH, isDataGridToolbarCompact, type DataGridReloadIntent, type DataGridToolbarActionCapability, type DataGridToolbarAutoRefreshCapability, type DataGridToolbarSaveCapability } from "@/lib/dataGrid/dataGridToolbar"; +import { buildOrderedGridRows, type GridInsertRowPosition, type GridNewRowPlacement } from "@/lib/dataGrid/gridNewRowPlacement"; +import { DATA_GRID_CONDITION_TOOLBAR_MIN_WIDTH, isDataGridToolbarCompact, type DataGridReloadIntent, type DataGridToolbarActionCapability, type DataGridToolbarAddRowCapability, type DataGridToolbarAutoRefreshCapability, type DataGridToolbarSaveCapability } from "@/lib/dataGrid/dataGridToolbar"; import { getTableMetadataCapabilities } from "@/lib/table/tableMetadataCapabilities"; import { getTableStructureCapabilities } from "@/lib/table/tableStructureCapabilities"; import { filterObjectBrowserTableColumns } from "@/lib/table/objectBrowserTableInfo"; @@ -244,6 +244,7 @@ const DataGridMongoJsonPreview = defineAsyncComponent(() => import("@/components const DataGridDetailDialogs = defineAsyncComponent(() => import("@/components/grid/DataGridDetailDialogs.vue")); const DataGridBulkEditDialog = defineAsyncComponent(() => import("@/components/grid/DataGridBulkEditDialog.vue")); const DataGridCopyColumnNamesDialog = defineAsyncComponent(() => import("@/components/grid/DataGridCopyColumnNamesDialog.vue")); +const DataGridInsertRowsDialog = defineAsyncComponent(() => import("@/components/grid/DataGridInsertRowsDialog.vue")); const ExportProgressDialog = defineAsyncComponent(() => import("@/components/export/ExportProgressDialog.vue")); const FORMATTED_JSON_EDIT_WARNING_COUNT_STORAGE_KEY = "dbx-cell-detail-formatted-json-edit-warning-count"; const FORMATTED_JSON_EDIT_WARNING_MAX_COUNT = 3; @@ -594,6 +595,10 @@ const bulkEditDialogOpen = ref(false); const bulkEditValue = ref(""); const copyColumnNamesDialogOpen = ref(false); const copyColumnNamesDialogColumns = ref([]); +const insertRowsDialogOpen = ref(false); +// Configured placement for newly inserted rows; the dropdown exposes it as a +// mutually-exclusive radio group and the main "add row" button inserts here. +const insertPosition = ref("below"); const generateIncrementDialogOpen = ref(false); const generateIncrementStartValue = ref("1"); const generateIncrementTarget = ref<"selection" | "detail">("selection"); @@ -616,6 +621,7 @@ const imagePreviewSrc = ref(""); const imagePreviewTitle = ref(""); const bulkEditDialogMounted = useDataGridAsyncSurface(bulkEditDialogOpen); const copyColumnNamesDialogMounted = useDataGridAsyncSurface(copyColumnNamesDialogOpen); +const insertRowsDialogMounted = useDataGridAsyncSurface(insertRowsDialogOpen); const cellDetailDialogMounted = useDataGridAsyncSurface(cellDetailDialogOpen); const detailDialogsMounted = useDataGridAsyncSurface(computed(() => rowDetailDialogOpen.value || columnDetailDialogOpen.value)); const imagePreviewMounted = useDataGridAsyncSurface(imagePreviewOpen); @@ -2922,6 +2928,7 @@ const { scrollerRef, dirtyRows, newRows, + newRowMeta: editorNewRowMeta, deletedRows, quickEntryDraftRow, quickEntryDraftRowId, @@ -2943,7 +2950,7 @@ const { restoreCellValue, cancelEdit, onEditKeydown, - addRow: addEditorRow, + addRows: addEditorRows, appendPastedRowsToNewRow, cloneRow, showDeleteRowConfirm, @@ -3257,8 +3264,7 @@ function onToolbarRollback() { function addRow() { if (!canInsertRows.value) return; - addEditorRow(); - focusAppendedTransposeRecord(); + insertRows(1, insertPosition.value); } const refreshToolbarCapability = computed(() => ({ @@ -3280,11 +3286,72 @@ const autoRefreshToolbarCapability = computed(() => ({ +const canPlaceInsertAtSelection = computed(() => { + if (selectedRowCount.value !== 1) return false; + const selectedId = [...selectedRowIds.value][0]; + if (selectedId === undefined) return false; + const item = getRowItem(selectedId); + if (!item || item.isDraft) return false; + return item.sourceIndex !== undefined || (item.isNew && item.newIndex !== undefined); +}); + +function selectedRowPlacement(position: "above" | "below"): GridNewRowPlacement | null { + if (!canPlaceInsertAtSelection.value) return null; + const selectedId = [...selectedRowIds.value][0]!; + const item = getRowItem(selectedId); + if (!item) return null; + if (item.isNew && item.newIndex !== undefined) { + const meta = editorNewRowMeta.value[item.newIndex]; + if (meta) return { anchorId: -meta.token, position }; + } + if (item.sourceIndex !== undefined) return { anchorId: item.sourceIndex, position }; + return null; +} + +function insertRows(count: number, position: "above" | "below" | "end") { + const placement: GridNewRowPlacement | null = position === "end" ? null : selectedRowPlacement(position); + const firstNewRowId = addEditorRows(count, placement); + if (firstNewRowId !== undefined) { + nextTick(() => { + const displayIndex = displayRowIndexById(firstNewRowId); + if (displayIndex >= 0) scrollGridRowIntoView(displayIndex); + }); + focusInsertedTransposeRecord(firstNewRowId); + } +} + +function handleAddRowMenuSelect(value: string) { + if (value === "insert-multiple") { + insertRowsDialogOpen.value = true; + return; + } + if (value === "position-above") { + insertPosition.value = "above"; + return; + } + if (value === "position-below") { + insertPosition.value = "below"; + return; + } + if (value === "position-end") { + insertPosition.value = "end"; + return; + } + insertRows(1, "end"); +} + +const addRowToolbarCapability = computed(() => ({ label: t("grid.addRow"), tooltip: `${t("grid.addRow")} (${shortcutMod}+N)`, visible: canInsertRows.value, + items: [ + { value: "insert-multiple", label: t("grid.insertMultipleRows") }, + { value: "position-above", label: t("grid.insertPositionAbove"), separatorBefore: true, selected: insertPosition.value === "above", disabled: !canPlaceInsertAtSelection.value }, + { value: "position-below", label: t("grid.insertPositionBelow"), selected: insertPosition.value === "below", disabled: !canPlaceInsertAtSelection.value }, + { value: "position-end", label: t("grid.insertPositionEnd"), selected: insertPosition.value === "end" }, + ], onTrigger: addRow, + onSelect: handleAddRowMenuSelect, })); const previewToolbarCapability = computed(() => ({ label: t(previewLabelKey.value), @@ -3337,28 +3404,34 @@ function dirtyColumnsForRow(dirty: Map | undefined, columnCou const displayRowRefs = computed(() => { const refs: DisplayRowRef[] = []; - for (const sourceIndex of sortedRows.value) { - const dirty = dirtyRows.value.get(sourceIndex); - const isDeleted = deletedRows.value.has(sourceIndex); - const status: RowStatus = isDeleted ? "deleted" : dirty?.size ? "edited" : "clean"; - const isActiveEditingRow = quickEntryEnabled.value && editingCell.value?.rowId === sourceIndex; - if (matchesRowStatusFilter(status, rowStatusFilter.value) || isActiveEditingRow) { - refs.push({ id: sourceIndex, displayIndex: refs.length, sourceIndex, isNew: false, isDeleted, status }); + // Pending rows carry a display placement (anchor row + above/below) so they + // can render interleaved with the loaded rows; unplaced rows stay at the end. + for (const entry of buildOrderedGridRows(sortedRows.value, editorNewRowMeta.value, newRows.value.length)) { + if (entry.kind === "source") { + const sourceIndex = entry.sourceIndex; + const dirty = dirtyRows.value.get(sourceIndex); + const isDeleted = deletedRows.value.has(sourceIndex); + const status: RowStatus = isDeleted ? "deleted" : dirty?.size ? "edited" : "clean"; + const isActiveEditingRow = quickEntryEnabled.value && editingCell.value?.rowId === sourceIndex; + if (matchesRowStatusFilter(status, rowStatusFilter.value) || isActiveEditingRow) { + refs.push({ id: sourceIndex, displayIndex: refs.length, sourceIndex, isNew: false, isDeleted, status }); + } + } else { + const newIndex = entry.newIndex; + const row = newRows.value[newIndex]; + if (!row || !rowMatchesLocalColumnFilters(row)) continue; + const status: RowStatus = "new"; + if (!matchesRowStatusFilter(status, rowStatusFilter.value)) continue; + refs.push({ + id: -(newIndex + 1), + displayIndex: refs.length, + newIndex, + isNew: true, + isDeleted: false, + status, + }); } } - newRows.value.forEach((row, i) => { - if (!rowMatchesLocalColumnFilters(row)) return; - const status: RowStatus = "new"; - if (!matchesRowStatusFilter(status, rowStatusFilter.value)) return; - refs.push({ - id: -(i + 1), - displayIndex: refs.length, - newIndex: i, - isNew: true, - isDeleted: false, - status, - }); - }); if (showQuickEntryDraftRow.value) { ensureQuickEntryDraftRow(); refs.push({ @@ -6676,10 +6749,13 @@ function applyTransposeState(next: { showTranspose: boolean; transposeRowIndex: } } -function focusAppendedTransposeRecord() { +function focusInsertedTransposeRecord(rowId: number) { if (!showTranspose.value) return; nextTick(() => { - applyTransposeState(nextAppendedTransposeState(true, displayRowCount.value)); + const displayIndex = displayRowIndexById(rowId); + if (displayIndex >= 0) { + applyTransposeState(nextTransposeStateForRecordCount(true, displayIndex, displayRowCount.value)); + } }); } @@ -9750,6 +9826,7 @@ const gridContextMenuItems = computed(() => { /> + diff --git a/apps/desktop/src/components/grid/DataGridInsertRowsDialog.vue b/apps/desktop/src/components/grid/DataGridInsertRowsDialog.vue new file mode 100644 index 0000000000..7d709bd8da --- /dev/null +++ b/apps/desktop/src/components/grid/DataGridInsertRowsDialog.vue @@ -0,0 +1,102 @@ + + + diff --git a/apps/desktop/src/components/grid/DataGridToolbar.vue b/apps/desktop/src/components/grid/DataGridToolbar.vue index 90cb12561b..ae9f16ffcb 100644 --- a/apps/desktop/src/components/grid/DataGridToolbar.vue +++ b/apps/desktop/src/components/grid/DataGridToolbar.vue @@ -8,6 +8,7 @@ import { dataGridToolbarIntervalOptions, isDataGridToolbarCapabilityDisabled, isDataGridToolbarCapabilityVisible, + selectDataGridToolbarAddRowItem, selectDataGridToolbarAutoRefreshInterval, selectDataGridToolbarCopyItem, selectDataGridToolbarExportItem, @@ -15,6 +16,7 @@ import { triggerDataGridToolbarCopy, triggerDataGridToolbarAction, type DataGridToolbarActionCapability, + type DataGridToolbarAddRowCapability, type DataGridToolbarAutoRefreshCapability, type DataGridToolbarCopyCapability, type DataGridToolbarExportCapability, @@ -25,7 +27,7 @@ const props = defineProps<{ compact?: boolean; refresh: DataGridToolbarActionCapability; autoRefresh?: DataGridToolbarAutoRefreshCapability; - addRow?: DataGridToolbarActionCapability; + addRow?: DataGridToolbarAddRowCapability; copyData?: DataGridToolbarCopyCapability; exportData?: DataGridToolbarExportCapability; transpose?: DataGridToolbarActionCapability; @@ -117,15 +119,34 @@ function actionLabelClass() { - - - - - {{ addRow?.tooltip ?? addRow?.label }} - +
+ + + + + {{ addRow?.tooltip ?? addRow?.label }} + + + + + + + + + +
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridInsertRowsDialog.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridInsertRowsDialog.spec.ts new file mode 100644 index 0000000000..414676188a --- /dev/null +++ b/apps/desktop/src/components/grid/__tests__/DataGridInsertRowsDialog.spec.ts @@ -0,0 +1,83 @@ +// @vitest-environment happy-dom + +import { createApp, nextTick, type App } from "vue"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import i18n from "@/i18n"; + +vi.mock("@/components/ui/dialog", async () => { + const { defineComponent, h } = await import("vue"); + const passthrough = defineComponent({ + setup(_props, { slots }) { + return () => h("div", slots.default?.()); + }, + }); + return { + Dialog: passthrough, + DialogContent: passthrough, + DialogDescription: passthrough, + DialogFooter: passthrough, + DialogHeader: passthrough, + DialogTitle: passthrough, + }; +}); + +vi.mock("@/components/ui/button", async () => { + const { defineComponent, h } = await import("vue"); + return { + Button: defineComponent({ + inheritAttrs: false, + setup(_props, { attrs, slots }) { + return () => h("button", attrs, slots.default?.()); + }, + }), + }; +}); + +vi.mock("@/components/ui/input", async () => { + const { defineComponent, h } = await import("vue"); + return { + Input: defineComponent({ + inheritAttrs: false, + props: { modelValue: String }, + emits: ["update:modelValue"], + setup(props, { attrs, emit }) { + return () => h("input", { ...attrs, value: props.modelValue, onInput: (event: Event) => emit("update:modelValue", (event.target as HTMLInputElement).value) }); + }, + }), + }; +}); + +import DataGridInsertRowsDialog from "../DataGridInsertRowsDialog.vue"; + +const mountedApps: Array<{ app: App; host: HTMLElement }> = []; + +afterEach(() => { + for (const { app, host } of mountedApps.splice(0)) { + app.unmount(); + host.remove(); + } +}); + +describe("DataGridInsertRowsDialog", () => { + it("uses the configured end position when first mounted open", async () => { + const onInsert = vi.fn(); + const host = document.createElement("div"); + document.body.append(host); + const app = createApp(DataGridInsertRowsDialog, { + open: true, + canPlaceAtSelection: true, + initialPosition: "end", + onInsert, + }); + app.use(i18n); + app.mount(host); + mountedApps.push({ app, host }); + + await nextTick(); + expect((host.querySelector('input[value="end"]') as HTMLInputElement).checked).toBe(true); + + [...host.querySelectorAll("button")].find((button) => button.textContent === "Insert")!.click(); + await nextTick(); + expect(onInsert).toHaveBeenCalledWith(1, "end"); + }); +}); diff --git a/apps/desktop/src/composables/useDataGridEditor.ts b/apps/desktop/src/composables/useDataGridEditor.ts index 4e93626aa3..7f84a7eb1a 100644 --- a/apps/desktop/src/composables/useDataGridEditor.ts +++ b/apps/desktop/src/composables/useDataGridEditor.ts @@ -5,6 +5,7 @@ import { coerceDataGridCellValue, dataGridCellEditorText } from "@/lib/dataGrid/ import { focusDataGridEditorWithoutScrolling, preserveDataGridScrollPosition } from "@/lib/dataGrid/dataGridEditorFocus"; import { normalizeDataGridSaveError } from "@/lib/dataGrid/dataGridSql"; import { rowStatusFilterAfterAddingRow, type RowStatusFilter } from "@/lib/dataGrid/gridRowStatus"; +import { type GridNewRowMeta, type GridNewRowPlacement } from "@/lib/dataGrid/gridNewRowPlacement"; import { supportsDataGridTransaction } from "@/lib/table/tableEditing"; import { useConnectionStore } from "@/stores/connectionStore"; import { useHistoryStore } from "@/stores/historyStore"; @@ -28,6 +29,7 @@ interface RowItem { } export const DATA_GRID_QUICK_ENTRY_DRAFT_ROW_ID = Number.MIN_SAFE_INTEGER; +export const DATA_GRID_MAX_BATCH_INSERT_ROWS = 1000; type RowKind = "none" | "existing" | "new" | "draft"; @@ -108,6 +110,7 @@ export interface UseDataGridEditorOptions { interface PendingChangesSnapshot { newRows: CellValue[][]; + newRowMeta: GridNewRowMeta[]; quickEntryDraftRow?: CellValue[]; dirtyRows: Map>; deletedRows: Set; @@ -136,7 +139,7 @@ interface QueuedAutoSaveChange { value: CellValue; } -type PendingChangesHistorySnapshot = Pick; +type PendingChangesHistorySnapshot = Pick; const pendingChangesCache = new Map(); const closingPendingSnapshotTabs = new Set(); @@ -211,6 +214,27 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { const scrollerRef = ref(null); const dirtyRows = shallowRef>>(new Map()); const newRows = ref([]); + // Parallel to newRows: one stable token + display placement per pending row. + // Kept in lockstep with every structural mutation of newRows. + const newRowMeta = ref([]); + let nextNewRowToken = 1; + function allocateNewRowMeta(placement: GridNewRowPlacement | null): GridNewRowMeta { + return { token: nextNewRowToken++, placement }; + } + function cloneNewRowMeta(meta: readonly GridNewRowMeta[]): GridNewRowMeta[] { + return meta.map((item) => ({ token: item.token, placement: item.placement ? { ...item.placement } : null })); + } + // Restore a metadata snapshot and resume token allocation past its maximum so + // newly created rows never collide with tokens held by restored rows (a fresh + // composable instance starts the counter at 1 again). + function restoreNewRowMeta(meta: readonly GridNewRowMeta[]) { + newRowMeta.value = cloneNewRowMeta(meta); + let maxToken = 0; + for (const item of newRowMeta.value) { + if (item.token > maxToken) maxToken = item.token; + } + nextNewRowToken = maxToken + 1; + } const deletedRows = ref>(new Set()); const quickEntryDraftRow = ref([]); const undoStack = ref([]); @@ -233,6 +257,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { const cached = pendingChangesCache.get(key); if (cached && cached.columnCount === result.value.columns.length && cached.rowCount === result.value.rows.length) { newRows.value = cached.newRows; + restoreNewRowMeta(cached.newRowMeta ?? []); quickEntryDraftRow.value = cached.quickEntryDraftRow ? [...cached.quickEntryDraftRow] : []; dirtyRows.value = cached.dirtyRows; deletedRows.value = cached.deletedRows; @@ -319,6 +344,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { function pendingChangesSnapshot(): PendingChangesHistorySnapshot { return { newRows: newRows.value.map((row) => [...row]), + newRowMeta: cloneNewRowMeta(newRowMeta.value), quickEntryDraftRow: quickEntryDraftRow.value.length > 0 ? [...quickEntryDraftRow.value] : undefined, dirtyRows: new Map([...dirtyRows.value].map(([rowIndex, changes]) => [rowIndex, new Map(changes)])), deletedRows: new Set(deletedRows.value), @@ -328,6 +354,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { function restorePendingChangesSnapshot(snapshot: PendingChangesHistorySnapshot) { newRows.value = snapshot.newRows.map((row) => [...row]); + restoreNewRowMeta(snapshot.newRowMeta ?? []); quickEntryDraftRow.value = snapshot.quickEntryDraftRow ? [...snapshot.quickEntryDraftRow] : emptyDraftRow(); dirtyRows.value = new Map([...snapshot.dirtyRows].map(([rowIndex, changes]) => [rowIndex, new Map(changes)])); deletedRows.value = new Set(snapshot.deletedRows); @@ -630,6 +657,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { } rowStatusFilter.value = rowStatusFilterAfterAddingRow(rowStatusFilter.value); newRows.value = [...newRows.value, [...quickEntryDraftRow.value]]; + newRowMeta.value = [...newRowMeta.value, allocateNewRowMeta(null)]; quickEntryDraftRow.value = emptyDraftRow(); if (useTransaction.value && !transactionActive.value) { enterTransaction(); @@ -696,6 +724,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { } rowStatusFilter.value = rowStatusFilterAfterAddingRow(rowStatusFilter.value); newRows.value = [...newRows.value, nextDraftRow]; + newRowMeta.value = [...newRowMeta.value, allocateNewRowMeta(null)]; quickEntryDraftRow.value = emptyDraftRow(); touchPendingChanges(); if (useTransaction.value && !transactionActive.value) { @@ -933,7 +962,9 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { pushUndoSnapshot(); rowStatusFilter.value = rowStatusFilterAfterAddingRow(rowStatusFilter.value); newRows.value.push(result.value.columns.map(() => null)); + newRowMeta.value.push(allocateNewRowMeta(null)); newRows.value = [...newRows.value]; + newRowMeta.value = [...newRowMeta.value]; touchPendingChanges(); if (useTransaction.value && !transactionActive.value) { enterTransaction(); @@ -946,6 +977,41 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { }); } + // Batch-append N blank draft rows as a single undoable change. Each row is an + // independent clone so later edits to one row never alias another. Editing + // starts on the first inserted row, mirroring addRow. + // + // `placement` is a display-only hint: when set, the grid renders the new rows + // anchored to another row instead of at the end, and the caller is expected + // to scroll to the inserted rows (the composable cannot resolve display + // positions). Returns the first inserted row's id, or undefined when the + // count was rejected. + function addRows(count: number, placement: GridNewRowPlacement | null = null): number | undefined { + if (!Number.isInteger(count) || count <= 0) return undefined; + const clampedCount = Math.min(count, DATA_GRID_MAX_BATCH_INSERT_ROWS); + const firstNewIndex = newRows.value.length; + pushUndoSnapshot(); + rowStatusFilter.value = rowStatusFilterAfterAddingRow(rowStatusFilter.value); + const blankRow = result.value.columns.map(() => null); + for (let i = 0; i < clampedCount; i++) { + newRows.value.push([...blankRow]); + newRowMeta.value.push(allocateNewRowMeta(placement)); + } + newRows.value = [...newRows.value]; + newRowMeta.value = [...newRowMeta.value]; + touchPendingChanges(); + if (useTransaction.value && !transactionActive.value) { + enterTransaction(); + } + const newRowId = -(firstNewIndex + 1); + nextTick(() => { + const el = getScrollerElement(); + if (placement === null && el) el.scrollTop = el.scrollHeight; + startEdit(newRowId, initialEditColumn?.value ?? 0); + }); + return newRowId; + } + function isBlankNewRow(row: readonly CellValue[]): boolean { return row.every((value) => value === null || (typeof value === "string" && value.trim() === "")); } @@ -974,6 +1040,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { if (targetColumns.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) { for (let rowIndex = targetNewIndex!; rowIndex < nextRows.length && reusableNewRowCount < pastedRows.length; rowIndex++) { @@ -994,11 +1061,22 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { pushUndoSnapshot(); if (targetIsDraft) { nextRows.push(...mappedRows); + for (let i = 0; i < mappedRows.length; i++) nextMeta.push(allocateNewRowMeta(null)); 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). + const newMetas = mappedRows.map((_, rowOffset) => { + if (rowOffset < reusableNewRowCount) { + return nextMeta[targetNewIndex! + rowOffset] ?? allocateNewRowMeta(null); + } + return allocateNewRowMeta(null); + }); + nextMeta.splice(targetNewIndex!, reusableNewRowCount, ...newMetas); nextRows.splice(targetNewIndex!, reusableNewRowCount, ...mappedRows); } newRows.value = nextRows; + newRowMeta.value = nextMeta; rowStatusFilter.value = rowStatusFilterAfterAddingRow(rowStatusFilter.value); touchPendingChanges(); if (useTransaction.value && !transactionActive.value) { @@ -1031,7 +1109,9 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { pushUndoSnapshot(); rowStatusFilter.value = rowStatusFilterAfterAddingRow(rowStatusFilter.value); newRows.value.push(clonedData); + newRowMeta.value.push(allocateNewRowMeta(null)); newRows.value = [...newRows.value]; + newRowMeta.value = [...newRowMeta.value]; touchPendingChanges(); if (useTransaction.value && !transactionActive.value) { enterTransaction(); @@ -1052,8 +1132,10 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { for (const item of rowsToClone) { const clonedData = clonedRowData(item); newRows.value.push(clonedData); + newRowMeta.value.push(allocateNewRowMeta(null)); } newRows.value = [...newRows.value]; + newRowMeta.value = [...newRowMeta.value]; touchPendingChanges(); if (useTransaction.value && !transactionActive.value) { enterTransaction(); @@ -1089,8 +1171,10 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { .sort((a, b) => b - a) .forEach((newIndex) => { newRows.value.splice(newIndex, 1); + newRowMeta.value.splice(newIndex, 1); }); newRows.value = [...newRows.value]; + newRowMeta.value = [...newRowMeta.value]; } if (sourceIndexes.size > 0) { for (const sourceIndex of sourceIndexes) { @@ -1205,7 +1289,15 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { if (snapshot.newRows.length > 0) { const savedNewRows = new Set(snapshot.newRowRefs); - newRows.value = newRows.value.filter((row) => !savedNewRows.has(row)); + const keptRows: CellValue[][] = []; + const keptMeta: GridNewRowMeta[] = []; + newRows.value.forEach((row, rowIndex) => { + if (savedNewRows.has(row)) return; + keptRows.push(row); + keptMeta.push(newRowMeta.value[rowIndex] ?? allocateNewRowMeta(null)); + }); + newRows.value = keptRows; + newRowMeta.value = keptMeta; } for (const sourceIndex of snapshot.deletedRows) { @@ -1471,6 +1563,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { function discardChanges() { dirtyRows.value = new Map(); newRows.value = []; + newRowMeta.value = []; deletedRows.value = new Set(); quickEntryDraftRow.value = emptyDraftRow(); queuedAutoSaveChanges.clear(); @@ -1512,6 +1605,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { } pendingChangesCache.set(k, { newRows: newRows.value.map((r) => [...r]), + newRowMeta: cloneNewRowMeta(newRowMeta.value), quickEntryDraftRow: quickEntryDraftRowSnapshot, dirtyRows: new Map([...dirtyRows.value].map(([i, m]) => [i, new Map(m)])), deletedRows: new Set(deletedRows.value), @@ -1603,6 +1697,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { scrollerRef, dirtyRows, newRows, + newRowMeta, deletedRows, quickEntryDraftRow, quickEntryDraftRowId: DATA_GRID_QUICK_ENTRY_DRAFT_ROW_ID, @@ -1629,6 +1724,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) { cancelEdit, onEditKeydown, addRow, + addRows, appendPastedRowsToNewRow, cloneRow, cloneRows, diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts index a197985e06..b58aff6e3b 100644 --- a/apps/desktop/src/i18n/locales/en.ts +++ b/apps/desktop/src/i18n/locales/en.ts @@ -1283,6 +1283,19 @@ export default { discard: "Discard", dismiss: "Dismiss", addRow: "Add Row", + insertMultipleRows: "Insert Multiple 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", + insertRowCountInvalid: "Enter a whole number greater than 0.", + insertRowsMaxHint: "Up to {max} rows.", + insertRowsConfirm: "Insert", + insertAboveSelected: "Insert Above Selected Row", + insertBelowSelected: "Insert Below Selected Row", + insertRowPositionLabel: "Position", + insertPositionAbove: "Above selected row", + insertPositionBelow: "Below selected row", + insertPositionEnd: "At the end of data", quickEntryDraftPlaceholder: "New", cloneRow: "Clone as New Row", deleteRow: "Delete Row", diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts index cc0fae154c..4940690aa3 100644 --- a/apps/desktop/src/i18n/locales/es.ts +++ b/apps/desktop/src/i18n/locales/es.ts @@ -1168,6 +1168,19 @@ export default withEnglishFallback({ dismiss: "Cerrar", quickEntryDraftPlaceholder: "Nueva", addRow: "Agregar fila", + insertMultipleRows: "Insertar varias filas…", + 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", + insertRowCountInvalid: "Introduce un número entero mayor que 0.", + insertRowsMaxHint: "Hasta {max} filas.", + insertRowsConfirm: "Insertar", + insertAboveSelected: "Insertar encima de la fila seleccionada", + insertBelowSelected: "Insertar debajo de la fila seleccionada", + insertRowPositionLabel: "Posición", + insertPositionAbove: "Encima de la fila seleccionada", + insertPositionBelow: "Debajo de la fila seleccionada", + insertPositionEnd: "Al final de los datos", cloneRow: "Clonar como fila nueva", deleteRow: "Eliminar fila", deleteRows: "Eliminar {count} filas", diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts index 14d6dceb09..0cd2856568 100644 --- a/apps/desktop/src/i18n/locales/it.ts +++ b/apps/desktop/src/i18n/locales/it.ts @@ -1165,6 +1165,19 @@ export default withEnglishFallback({ discard: "Scarta", dismiss: "Ignora", addRow: "Aggiungi Riga", + insertMultipleRows: "Inserisci più 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", + insertRowCountInvalid: "Inserisci un numero intero maggiore di 0.", + insertRowsMaxHint: "Fino a {max} righe.", + insertRowsConfirm: "Inserisci", + insertAboveSelected: "Inserisci sopra la riga selezionata", + insertBelowSelected: "Inserisci sotto la riga selezionata", + insertRowPositionLabel: "Posizione", + insertPositionAbove: "Sopra la riga selezionata", + insertPositionBelow: "Sotto la riga selezionata", + insertPositionEnd: "Alla fine dei dati", quickEntryDraftPlaceholder: "Nuova", cloneRow: "Clona come Nuova Riga", deleteRow: "Elimina Riga", diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts index c594b6b8ae..0243f95bea 100644 --- a/apps/desktop/src/i18n/locales/ja.ts +++ b/apps/desktop/src/i18n/locales/ja.ts @@ -1183,6 +1183,19 @@ export default withEnglishFallback({ discard: "破棄", dismiss: "閉じる", addRow: "行を追加", + insertMultipleRows: "複数行を挿入…", + insertRowsTitle: "複数行を挿入", + insertRowsDescription: "未保存の下書き行を指定数作成します。保存時、空の行は無視されます。保存後の表示順は現在のクエリに従います。", + insertRowCountLabel: "行数", + insertRowCountInvalid: "0 より大きい整数を入力してください。", + insertRowsMaxHint: "最大 {max} 行まで。", + insertRowsConfirm: "挿入", + insertAboveSelected: "選択行の上に挿入", + insertBelowSelected: "選択行の下に挿入", + insertRowPositionLabel: "位置", + insertPositionAbove: "選択行の上", + insertPositionBelow: "選択行の下", + insertPositionEnd: "データの末尾", quickEntryDraftPlaceholder: "新規", cloneRow: "新しい行として複製", deleteRow: "行を削除", diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts index 4c1c9e150d..3f54ab7b36 100644 --- a/apps/desktop/src/i18n/locales/ko.ts +++ b/apps/desktop/src/i18n/locales/ko.ts @@ -1261,6 +1261,19 @@ export default withEnglishFallback({ discard: "저장 안 함", dismiss: "닫기", addRow: "행 추가", + insertMultipleRows: "여러 행 삽입…", + insertRowsTitle: "여러 행 삽입", + insertRowsDescription: "저장되지 않은 초안 행을 지정한 개수만큼 만듭니다. 저장 시 비어 있는 행은 무시되며, 저장 후 표시 순서는 현재 쿼리를 따릅니다.", + insertRowCountLabel: "행 수", + insertRowCountInvalid: "0보다 큰 정수를 입력하세요.", + insertRowsMaxHint: "최대 {max}행까지.", + insertRowsConfirm: "삽입", + insertAboveSelected: "선택 행 위에 삽입", + insertBelowSelected: "선택 행 아래에 삽입", + insertRowPositionLabel: "위치", + insertPositionAbove: "선택 행 위", + insertPositionBelow: "선택 행 아래", + insertPositionEnd: "데이터 끝", quickEntryDraftPlaceholder: "새로 만들기", cloneRow: "새 행으로 복제", deleteRow: "행 삭제", diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts index 82faad7bc4..32717933e6 100644 --- a/apps/desktop/src/i18n/locales/pt-BR.ts +++ b/apps/desktop/src/i18n/locales/pt-BR.ts @@ -1167,6 +1167,19 @@ export default withEnglishFallback({ discard: "Descartar", dismiss: "Dispensar", addRow: "Adicionar Linha", + insertMultipleRows: "Inserir várias 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", + insertRowCountInvalid: "Digite um número inteiro maior que 0.", + insertRowsMaxHint: "Até {max} linhas.", + insertRowsConfirm: "Inserir", + insertAboveSelected: "Inserir acima da linha selecionada", + insertBelowSelected: "Inserir abaixo da linha selecionada", + insertRowPositionLabel: "Posição", + insertPositionAbove: "Acima da linha selecionada", + insertPositionBelow: "Abaixo da linha selecionada", + insertPositionEnd: "No final dos dados", quickEntryDraftPlaceholder: "Nova", cloneRow: "Clonar como Nova Linha", deleteRow: "Excluir Linha", diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts index d6851facbe..cb5ff19cb5 100644 --- a/apps/desktop/src/i18n/locales/zh-CN.ts +++ b/apps/desktop/src/i18n/locales/zh-CN.ts @@ -1284,6 +1284,19 @@ export default withEnglishFallback({ discard: "放弃", dismiss: "关闭", addRow: "新增行", + insertMultipleRows: "插入多行…", + insertRowsTitle: "新增多行", + insertRowsDescription: "创建指定数量的未保存草稿行。保存时未填写的空行会被忽略;保存后的显示位置由当前查询排序决定。", + insertRowCountLabel: "行数", + insertRowCountInvalid: "请输入大于 0 的整数。", + insertRowsMaxHint: "最多 {max} 行。", + insertRowsConfirm: "插入", + insertAboveSelected: "在选中行上方插入", + insertBelowSelected: "在选中行下方插入", + insertRowPositionLabel: "位置", + insertPositionAbove: "放置于选中行之上", + insertPositionBelow: "放置于选中行之下", + insertPositionEnd: "放置于数据末尾", quickEntryDraftPlaceholder: "新增", cloneRow: "克隆为新行", deleteRow: "删除行", diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts index 46e6e9a2c8..5aa56eabf1 100644 --- a/apps/desktop/src/i18n/locales/zh-TW.ts +++ b/apps/desktop/src/i18n/locales/zh-TW.ts @@ -1166,6 +1166,19 @@ export default withEnglishFallback({ discard: "放棄", dismiss: "關閉", addRow: "新增資料", + insertMultipleRows: "插入多行…", + insertRowsTitle: "新增多行", + insertRowsDescription: "建立指定數量的未儲存草稿列。儲存時未填寫的空白列會被忽略;儲存後的顯示位置由目前查詢排序決定。", + insertRowCountLabel: "列數", + insertRowCountInvalid: "請輸入大於 0 的整數。", + insertRowsMaxHint: "最多 {max} 列。", + insertRowsConfirm: "插入", + insertAboveSelected: "在所選列上方插入", + insertBelowSelected: "在所選列下方插入", + insertRowPositionLabel: "位置", + insertPositionAbove: "放置於所選列之上", + insertPositionBelow: "放置於所選列之下", + insertPositionEnd: "放置於資料末尾", quickEntryDraftPlaceholder: "新增", cloneRow: "複製為新資料", deleteRow: "刪除資料", diff --git a/apps/desktop/src/lib/__tests__/dataGrid/dataGridToolbar.spec.ts b/apps/desktop/src/lib/__tests__/dataGrid/dataGridToolbar.spec.ts index 7781d9c119..2d85b81948 100644 --- a/apps/desktop/src/lib/__tests__/dataGrid/dataGridToolbar.spec.ts +++ b/apps/desktop/src/lib/__tests__/dataGrid/dataGridToolbar.spec.ts @@ -4,6 +4,7 @@ import { dataGridToolbarCompactBreakpoint, dataGridToolbarIntervalOptions, isDataGridToolbarCompact, + selectDataGridToolbarAddRowItem, selectDataGridToolbarAutoRefreshInterval, selectDataGridToolbarCopyItem, selectDataGridToolbarExportItem, @@ -135,4 +136,25 @@ describe("data grid toolbar capabilities", () => { expect(onCopy).not.toHaveBeenCalled(); expect(onSelect).toHaveBeenCalledWith("tsv"); }); + + it("routes add-row menu selections and rejects disabled or unknown items", async () => { + const onSelect = vi.fn(); + const capability = { + label: "Add Row", + items: [ + { value: "insert-multiple", label: "Insert Multiple Rows" }, + { value: "position-above", label: "Place above selected row", disabled: true }, + { value: "position-below", label: "Place below selected row", selected: true }, + { value: "position-end", label: "Place at the end of data" }, + ], + onTrigger: vi.fn(), + onSelect, + }; + + await expect(selectDataGridToolbarAddRowItem(capability, "position-below")).resolves.toBe(true); + await expect(selectDataGridToolbarAddRowItem(capability, "position-above")).resolves.toBe(false); + await expect(selectDataGridToolbarAddRowItem(capability, "unknown")).resolves.toBe(false); + expect(onSelect).toHaveBeenCalledOnce(); + expect(onSelect).toHaveBeenCalledWith("position-below"); + }); }); diff --git a/apps/desktop/src/lib/dataGrid/__tests__/gridNewRowPlacement.spec.ts b/apps/desktop/src/lib/dataGrid/__tests__/gridNewRowPlacement.spec.ts new file mode 100644 index 0000000000..6ffc6bbe83 --- /dev/null +++ b/apps/desktop/src/lib/dataGrid/__tests__/gridNewRowPlacement.spec.ts @@ -0,0 +1,182 @@ +import { describe, expect, it } from "vitest"; +import { buildOrderedGridRows, type GridNewRowMeta } from "../gridNewRowPlacement"; + +function entries(sourceIndices: number[], meta: GridNewRowMeta[], count = meta.length) { + return buildOrderedGridRows(sourceIndices, meta, count); +} + +describe("buildOrderedGridRows", () => { + it("appends unplaced pending rows after the source rows", () => { + expect( + entries( + [0, 1, 2], + [ + { token: 1, placement: null }, + { token: 2, placement: null }, + ], + ), + ).toEqual([ + { kind: "source", sourceIndex: 0 }, + { kind: "source", sourceIndex: 1 }, + { kind: "source", sourceIndex: 2 }, + { kind: "new", newIndex: 0 }, + { kind: "new", newIndex: 1 }, + ]); + }); + + it("places a row below a source row", () => { + expect(entries([0, 1, 2], [{ token: 1, placement: { anchorId: 1, position: "below" } }])).toEqual([ + { kind: "source", sourceIndex: 0 }, + { kind: "source", sourceIndex: 1 }, + { kind: "new", newIndex: 0 }, + { kind: "source", sourceIndex: 2 }, + ]); + }); + + it("places a row above a source row", () => { + expect(entries([0, 1, 2], [{ token: 1, placement: { anchorId: 1, position: "above" } }])).toEqual([ + { kind: "source", sourceIndex: 0 }, + { kind: "new", newIndex: 0 }, + { kind: "source", sourceIndex: 1 }, + { kind: "source", sourceIndex: 2 }, + ]); + }); + + it("clusters rows inserted below the same anchor in creation order", () => { + expect( + entries( + [0, 1], + [ + { token: 1, placement: { anchorId: 0, position: "below" } }, + { token: 2, placement: { anchorId: 0, position: "below" } }, + { token: 3, placement: { anchorId: 0, position: "below" } }, + ], + ), + ).toEqual([ + { kind: "source", sourceIndex: 0 }, + { kind: "new", newIndex: 0 }, + { kind: "new", newIndex: 1 }, + { kind: "new", newIndex: 2 }, + { kind: "source", sourceIndex: 1 }, + ]); + }); + + it("clusters rows inserted above the same anchor in creation order", () => { + expect( + entries( + [0, 1], + [ + { token: 1, placement: { anchorId: 0, position: "above" } }, + { token: 2, placement: { anchorId: 0, position: "above" } }, + ], + ), + ).toEqual([ + { kind: "new", newIndex: 0 }, + { kind: "new", newIndex: 1 }, + { kind: "source", sourceIndex: 0 }, + { kind: "source", sourceIndex: 1 }, + ]); + }); + + it("places a row below another pending row", () => { + expect( + entries( + [0, 1], + [ + { token: 1, placement: { anchorId: 0, position: "below" } }, + { token: 2, placement: { anchorId: -1, position: "below" } }, + ], + ), + ).toEqual([ + { kind: "source", sourceIndex: 0 }, + { kind: "new", newIndex: 0 }, + { kind: "new", newIndex: 1 }, + { kind: "source", sourceIndex: 1 }, + ]); + }); + + it("keeps below-cluster order when an above insert shifts the anchor", () => { + expect( + entries( + [0, 1], + [ + { token: 1, placement: { anchorId: 0, position: "below" } }, + { token: 2, placement: { anchorId: 0, position: "above" } }, + { token: 3, placement: { anchorId: 0, position: "below" } }, + ], + ), + ).toEqual([ + { kind: "new", newIndex: 1 }, + { kind: "source", sourceIndex: 0 }, + { kind: "new", newIndex: 0 }, + { kind: "new", newIndex: 2 }, + { kind: "source", sourceIndex: 1 }, + ]); + }); + + it("places a row above another pending row", () => { + expect( + entries( + [0, 1], + [ + { token: 1, placement: null }, + { token: 2, placement: { anchorId: -1, position: "above" } }, + ], + ), + ).toEqual([ + { kind: "source", sourceIndex: 0 }, + { kind: "source", sourceIndex: 1 }, + { kind: "new", newIndex: 1 }, + { kind: "new", newIndex: 0 }, + ]); + }); + + it("falls back to the end when the anchor is absent (filtered out or deleted)", () => { + expect( + entries( + [0, 2], + [ + { token: 1, placement: { anchorId: 1, position: "below" } }, + { token: 2, placement: { anchorId: 5, position: "below" } }, + ], + ), + ).toEqual([ + { kind: "source", sourceIndex: 0 }, + { kind: "source", sourceIndex: 2 }, + { kind: "new", newIndex: 0 }, + { kind: "new", newIndex: 1 }, + ]); + }); + + it("tolerates meta shorter than the pending row count (defensive)", () => { + expect(entries([0], [{ token: 1, placement: null }], 3)).toEqual([ + { kind: "source", sourceIndex: 0 }, + { kind: "new", newIndex: 0 }, + { kind: "new", newIndex: 1 }, + { kind: "new", newIndex: 2 }, + ]); + }); + + it("merges the maximum result page without quadratic placement scans", () => { + const sourceIndices = Array.from({ length: 100_000 }, (_, index) => index); + const meta = Array.from( + { length: 1_000 }, + (_, index): GridNewRowMeta => ({ + token: index + 1, + placement: { anchorId: index * 100, position: index % 2 === 0 ? "above" : "below" }, + }), + ); + + const startedAt = performance.now(); + const result = entries(sourceIndices, meta); + const elapsedMs = performance.now() - startedAt; + + expect(result).toHaveLength(101_000); + expect(result.slice(0, 3)).toEqual([ + { kind: "new", newIndex: 0 }, + { kind: "source", sourceIndex: 0 }, + { kind: "source", sourceIndex: 1 }, + ]); + expect(elapsedMs).toBeLessThan(1_500); + }); +}); diff --git a/apps/desktop/src/lib/dataGrid/dataGridToolbar.ts b/apps/desktop/src/lib/dataGrid/dataGridToolbar.ts index 7671b7df50..6b72bd3fd2 100644 --- a/apps/desktop/src/lib/dataGrid/dataGridToolbar.ts +++ b/apps/desktop/src/lib/dataGrid/dataGridToolbar.ts @@ -35,6 +35,8 @@ export interface DataGridToolbarMenuItem { label: string; disabled?: boolean; separatorBefore?: boolean; + /** Marks a menu item as the active choice in a mutually-exclusive group (rendered as a check). */ + selected?: boolean; } export interface DataGridToolbarExportCapability { @@ -56,6 +58,16 @@ export interface DataGridToolbarCopyCapability { onSelect: (value: string) => void | Promise; } +export interface DataGridToolbarAddRowCapability { + label: string; + tooltip?: string; + visible?: boolean; + disabled?: boolean; + items: readonly DataGridToolbarMenuItem[]; + onTrigger: () => void | Promise; + onSelect: (value: string) => void | Promise; +} + export interface DataGridToolbarAutoRefreshCapability { label: string; shortLabel: string; @@ -124,3 +136,11 @@ export async function selectDataGridToolbarCopyItem(capability: DataGridToolbarC await capability.onSelect(value); return true; } + +export async function selectDataGridToolbarAddRowItem(capability: DataGridToolbarAddRowCapability | undefined, value: string): Promise { + if (!capability || !isDataGridToolbarCapabilityVisible(capability) || capability.disabled) return false; + const item = capability.items.find((candidate) => candidate.value === value); + if (!item || item.disabled) return false; + await capability.onSelect(value); + return true; +} diff --git a/apps/desktop/src/lib/dataGrid/gridNewRowPlacement.ts b/apps/desktop/src/lib/dataGrid/gridNewRowPlacement.ts new file mode 100644 index 0000000000..ccb4948e12 --- /dev/null +++ b/apps/desktop/src/lib/dataGrid/gridNewRowPlacement.ts @@ -0,0 +1,134 @@ +/** + * Display placement for pending draft rows in the data grid. + * + * Pending rows live in an append-ordered buffer and the database has no row + * order of its own, so "insert above/below a selected row" is a display-only + * concept that lasts until the pending changes are saved. Each pending row + * carries an optional placement (anchor row + above/below); the anchor is + * resolved at render time by `buildOrderedGridRows`, which merges the pending + * rows into the loaded source rows accordingly. + */ + +export type GridNewRowPosition = "above" | "below"; + +/** User-facing insert position state; `"end"` maps to a null placement. */ +export type GridInsertRowPosition = GridNewRowPosition | "end"; + +export interface GridNewRowPlacement { + /** Row id of the anchor: `>= 0` for a source row (its sourceIndex), `< 0` for another pending row (its stable token negated). */ + anchorId: number; + position: GridNewRowPosition; +} + +export interface GridNewRowMeta { + /** Stable per-row token (> 0) that survives splices of the pending buffer. */ + token: number; + /** Display placement; `null` appends at the end of the result. */ + placement: GridNewRowPlacement | null; +} + +export type GridOrderedRowEntry = { kind: "source"; sourceIndex: number } | { kind: "new"; newIndex: number }; + +interface GridOrderedRowNode { + entry: GridOrderedRowEntry; + previous: GridOrderedRowNode | null; + next: GridOrderedRowNode | null; +} + +/** + * Merge pending rows into the source rows in display order. + * + * `sourceIndices` is the loaded row order (server sort / local filter applied). + * Rows anchored "below" a target cluster in creation order right after it; rows + * anchored "above" cluster immediately before it. An anchor that is absent from + * the current source order (its source row was filtered out, or the anchored + * pending row was deleted) falls back to the end of the list. + * + * Anchors only ever reference rows that already exist, so processing pending + * rows in creation order keeps every anchor placed before it is referenced. + */ +export function buildOrderedGridRows(sourceIndices: readonly number[], newRowMeta: readonly GridNewRowMeta[], newRowCount: number): GridOrderedRowEntry[] { + const list: { head: GridOrderedRowNode | null; tail: GridOrderedRowNode | null } = { + head: null, + tail: null, + }; + const sourceNodes = new Map(); + const pendingTokenNodes = new Map(); + const belowTailNodes = new Map(); + + const append = (node: GridOrderedRowNode) => { + if (!list.tail) { + list.head = node; + list.tail = node; + return; + } + list.tail.next = node; + node.previous = list.tail; + list.tail = node; + }; + + const insertBefore = (anchor: GridOrderedRowNode, node: GridOrderedRowNode) => { + node.previous = anchor.previous; + node.next = anchor; + if (anchor.previous) anchor.previous.next = node; + else list.head = node; + anchor.previous = node; + }; + + const insertAfter = (anchor: GridOrderedRowNode, node: GridOrderedRowNode) => { + node.previous = anchor; + node.next = anchor.next; + if (anchor.next) anchor.next.previous = node; + else list.tail = node; + anchor.next = node; + }; + + for (const sourceIndex of sourceIndices) { + const node: GridOrderedRowNode = { + entry: { kind: "source", sourceIndex }, + previous: null, + next: null, + }; + append(node); + if (!sourceNodes.has(sourceIndex)) sourceNodes.set(sourceIndex, node); + } + + for (let index = 0; index < newRowCount; index++) { + const meta = newRowMeta[index]; + const node: GridOrderedRowNode = { + entry: { kind: "new", newIndex: index }, + previous: null, + next: null, + }; + const anchorId = meta?.placement?.anchorId; + if (anchorId === undefined) { + append(node); + if (meta) pendingTokenNodes.set(meta.token, node); + continue; + } + + const anchorNode = anchorId >= 0 ? sourceNodes.get(anchorId) : pendingTokenNodes.get(-anchorId); + if (!anchorNode) { + append(node); + pendingTokenNodes.set(meta.token, node); + continue; + } + + if (meta.placement!.position === "above") { + insertBefore(anchorNode, node); + } else { + const insertAfterNode = belowTailNodes.get(anchorId) ?? anchorNode; + insertAfter(insertAfterNode, node); + belowTailNodes.set(anchorId, node); + } + pendingTokenNodes.set(meta.token, node); + } + + const order: GridOrderedRowEntry[] = []; + let current = list.head; + while (current) { + order.push(current.entry); + current = current.next; + } + return order; +} diff --git a/packages/app-tests/dataGridEditor.test.ts b/packages/app-tests/dataGridEditor.test.ts index a091e076f8..44392e729d 100644 --- a/packages/app-tests/dataGridEditor.test.ts +++ b/packages/app-tests/dataGridEditor.test.ts @@ -2,7 +2,7 @@ import { strict as assert } from "node:assert"; import { test } from "vitest"; import { computed, nextTick, ref } from "vue"; import { createPinia, setActivePinia } from "pinia"; -import { DATA_GRID_QUICK_ENTRY_DRAFT_ROW_ID, useDataGridEditor } from "../../apps/desktop/src/composables/useDataGridEditor.ts"; +import { DATA_GRID_MAX_BATCH_INSERT_ROWS, DATA_GRID_QUICK_ENTRY_DRAFT_ROW_ID, useDataGridEditor } from "../../apps/desktop/src/composables/useDataGridEditor.ts"; import type { CellValue } from "../../apps/desktop/src/lib/dataGrid/cellValue.ts"; import type { DataGridSaveStatementOptions } from "../../apps/desktop/src/lib/dataGrid/dataGridSql.ts"; import { matchesRowStatusFilter, type RowStatusFilter } from "../../apps/desktop/src/lib/dataGrid/gridRowStatus.ts"; @@ -880,6 +880,141 @@ test("undo and redo cover row add and delete operations", () => { assert.deepEqual([...editor.deletedRows.value], [0]); }); +test("addRows appends the requested number of blank draft rows as one undoable change", () => { + setActivePinia(createPinia()); + installBrowserTestGlobals(); + + const editor = createPeopleGridEditor(); + + editor.addRows(3); + assert.equal(editor.newRows.value.length, 3); + assert.deepEqual(editor.newRows.value, [ + [null, null], + [null, null], + [null, null], + ]); + + editor.undoPendingChange(); + assert.equal(editor.newRows.value.length, 0); + editor.redoPendingChange(); + assert.equal(editor.newRows.value.length, 3); +}); + +test("addRows appends after existing draft rows", () => { + setActivePinia(createPinia()); + installBrowserTestGlobals(); + + const editor = createPeopleGridEditor(); + editor.addRow(); + editor.addRows(2); + assert.equal(editor.newRows.value.length, 3); +}); + +test("addRows ignores invalid counts", () => { + setActivePinia(createPinia()); + installBrowserTestGlobals(); + + const editor = createPeopleGridEditor(); + editor.addRows(0); + editor.addRows(-5); + editor.addRows(1.5); + editor.addRows(Number.NaN); + assert.equal(editor.newRows.value.length, 0); + assert.equal(editor.canUndoPendingChange.value, false); +}); + +test("addRows clamps counts above the batch limit", () => { + setActivePinia(createPinia()); + installBrowserTestGlobals(); + + const editor = createPeopleGridEditor(); + editor.addRows(DATA_GRID_MAX_BATCH_INSERT_ROWS + 100); + assert.equal(editor.newRows.value.length, DATA_GRID_MAX_BATCH_INSERT_ROWS); +}); + +test("addRows records the display placement alongside the pending rows", () => { + setActivePinia(createPinia()); + installBrowserTestGlobals(); + + const editor = createPeopleGridEditor(); + const firstId = editor.addRows(2, { anchorId: 0, position: "below" }); + assert.equal(firstId, -1); + assert.equal(editor.newRowMeta.value.length, 2); + assert.deepEqual(editor.newRowMeta.value.map((meta) => meta.placement), [ + { anchorId: 0, position: "below" }, + { anchorId: 0, position: "below" }, + ]); + // Stable tokens are unique and monotonic. + assert.equal(editor.newRowMeta.value[0].token, 1); + assert.equal(editor.newRowMeta.value[1].token, 2); +}); + +test("addRows with a null placement appends at the end", () => { + setActivePinia(createPinia()); + installBrowserTestGlobals(); + + const editor = createPeopleGridEditor(); + editor.addRows(2, null); + assert.deepEqual(editor.newRowMeta.value.map((meta) => meta.placement), [null, null]); +}); + +test("addRows can anchor to another pending row by its token", () => { + setActivePinia(createPinia()); + installBrowserTestGlobals(); + + const editor = createPeopleGridEditor(); + editor.addRows(1); + const firstToken = editor.newRowMeta.value[0].token; + editor.addRows(1, { anchorId: -firstToken, position: "below" }); + assert.deepEqual(editor.newRowMeta.value[1].placement, { anchorId: -firstToken, position: "below" }); +}); + +test("undo and redo restore the placement metadata", () => { + setActivePinia(createPinia()); + installBrowserTestGlobals(); + + const editor = createPeopleGridEditor(); + editor.addRows(2, { anchorId: 0, position: "above" }); + editor.undoPendingChange(); + assert.equal(editor.newRows.value.length, 0); + assert.equal(editor.newRowMeta.value.length, 0); + editor.redoPendingChange(); + assert.equal(editor.newRows.value.length, 2); + assert.deepEqual(editor.newRowMeta.value.map((meta) => meta.placement), [ + { anchorId: 0, position: "above" }, + { anchorId: 0, position: "above" }, + ]); +}); + +test("deleting a pending row keeps the placement metadata aligned", () => { + setActivePinia(createPinia()); + installBrowserTestGlobals(); + + const editor = createPeopleGridEditor(); + editor.addRows(3); + editor.applyDeleteRow(-1); + assert.equal(editor.newRows.value.length, 2); + assert.equal(editor.newRowMeta.value.length, 2); +}); + +test("restoring a cached snapshot resumes token allocation past restored tokens", () => { + setActivePinia(createPinia()); + installBrowserTestGlobals(); + const firstEditor = createQuickEntryEditor({ quickEntryEnabled: true, cacheKey: "token-restore" }); + + firstEditor.addRows(2); + assert.deepEqual(firstEditor.newRowMeta.value.map((m) => m.token), [1, 2]); + firstEditor.savePendingSnapshot(false, false); + + const restoredEditor = createQuickEntryEditor({ quickEntryEnabled: true, cacheKey: "token-restore" }); + assert.deepEqual(restoredEditor.newRowMeta.value.map((m) => m.token), [1, 2]); + + restoredEditor.addRows(1); + // The fresh instance restarts the allocator at 1; it must resume past the + // restored tokens so a new row never shares a token with a restored row. + assert.deepEqual(restoredEditor.newRowMeta.value.map((m) => m.token), [1, 2, 3]); +}); + test("batch row delete records a single undo snapshot", () => { setActivePinia(createPinia()); installBrowserTestGlobals(); diff --git a/packages/app-tests/dataGridTranspose.test.ts b/packages/app-tests/dataGridTranspose.test.ts index f3efaabd44..6a8264a1e9 100644 --- a/packages/app-tests/dataGridTranspose.test.ts +++ b/packages/app-tests/dataGridTranspose.test.ts @@ -239,6 +239,10 @@ test("transpose state is preserved and clamped after record refresh", () => { showTranspose: true, transposeRowIndex: 2, }); + assert.deepEqual(nextTransposeStateForRecordCount(true, 1, 4), { + showTranspose: true, + transposeRowIndex: 1, + }); assert.deepEqual(nextTransposeStateForRecordCount(true, 1, 0), { showTranspose: false, transposeRowIndex: null,