Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(sheets): drag a selection to move cells and rewrite references (#8132)

teod1f8cdf80e6e
diff --git a/apps/web/src/features/block-spreadsheet/README.md b/apps/web/src/features/block-spreadsheet/README.md
index 324cfc27be..3216a304eb 100644
--- a/apps/web/src/features/block-spreadsheet/README.md
+++ b/apps/web/src/features/block-spreadsheet/README.md
@@ -2,7 +2,7 @@
A native Macro document with multiple worksheets of up to 100,000 rows and
16,384 columns (A–XFD), Excel-style formulas, keyboard navigation, rectangular selection, formula-aware copying and
-fill, resizable columns, added rows, rich cell formatting, Excel workbook
+fill, dragging a selection to move it, resizable columns, added rows, rich cell formatting, Excel workbook
import/export, CSV import/value export, find and replace, range sorting, local
undo/redo, and live collaboration. Existing uploaded `.xlsx` files are not
automatically converted; open **Import and export** at the bottom right of a native
@@ -131,6 +131,27 @@ collaborators' edits. Rows and columns have no stable identities: an edit that a
collaborator commits to old coordinates after the shift arrives still lands at
those coordinates.
+Dragging the selection's border (`components/SelectionMoveHandle.tsx`, mouse or
+pen only) moves its cells the same way: `moveWorkbookRange` in
+`packages/spreadsheet/src/workbook-structure.ts` runs in the calculation worker,
+and `primitives/create-range-move.ts` commits the result as one revision-checked
+structural change, so it is one undo step, needs a connection in saved
+workbooks, and is cancelled by a collaborator's edit made meanwhile. It follows
+Excel's cut and paste: values, formats, notes, merges, legacy arrays, pivot
+table locations and data validation and conditional formatting ranges go with
+the cells (a rule that only partly moves is split in two), and replace what was
+at the destination after a confirmation when that held values. References to
+the moved cells from every sheet's formulas, names, rules, charts and pivot
+sources follow them; a range follows only when all of it moves, and moving
+whole rows or columns of the sheet also moves references like `1:2` or `A:A`. References
+inside moved formulas keep their cells, and references to replaced cells become
+`#REF!`. Moving part of a merge, array or pivot table is refused. Drawings,
+row heights and column widths stay, and comments stay on their addresses.
+While dragging, the grid scrolls near or past its edges and the cells land at
+the last visible row or column. Each move records a `spreadsheet.move_range`
+span (document, sheet, size, whether it replaced values, and any error) with
+`calculate` (the worker) and `commit` phases.
+
### Workbook sheets
The implicit first sheet has stable ID `sheet1`; existing version-1 documents and
@@ -261,8 +282,8 @@ formula awaits a reference keeps its draft, even when the formula's row is past
the other sheet's last row, and every tab change scrolls to that sheet's own
selection.
-Dragging a range, row or column headers, the fill handle, a formula reference, or
-a touch selection handle scrolls the grid while the pointer is within 24 pixels
+Dragging a range, row or column headers, the fill handle, a selection's move
+border, a formula reference, or a touch selection handle scrolls the grid while the pointer is within 24 pixels
of an edge of the cells or past it, and extends the drag to the cell under the
pointer or the nearest one in view. Speed grows with the pointer's depth into
that edge (20 pixels per second per pixel), and a header drag scrolls only along
@@ -568,7 +589,7 @@ production transport.
The [browser fixture](browser-test/README.md) runs the composed editor with real
calculation and Excel workers. Its Playwright suite covers formula autocomplete
-and range picking, menu/dialog focus, sheet navigation, read-only transitions,
+and range picking, dragging a selection to move it, menu/dialog focus, sheet navigation, read-only transitions,
Excel round trips, imported conditional formatting, data validation and notes,
imported charts and images (following edits, Delete and undo, and download),
radar, bubble, stock and contour charts, shapes, SmartArt and EMF images,
diff --git a/apps/web/src/features/block-spreadsheet/SpreadsheetBlock.tsx b/apps/web/src/features/block-spreadsheet/SpreadsheetBlock.tsx
index 77aab6ee0f..50b27f4c40 100644
--- a/apps/web/src/features/block-spreadsheet/SpreadsheetBlock.tsx
+++ b/apps/web/src/features/block-spreadsheet/SpreadsheetBlock.tsx
@@ -194,6 +194,7 @@ function SpreadsheetBlockContent(props: { share?: string }) {
<SpreadsheetComments documentId={documentId} store={store}>
{(commentLocation, comments) => (
<SpreadsheetEditor
+ documentId={documentId}
autoFocus={canAutofocus && !navigatedFromJK()}
commentLocation={commentLocation()}
comments={comments}
diff --git a/apps/web/src/features/block-spreadsheet/browser-test/README.md b/apps/web/src/features/block-spreadsheet/browser-test/README.md
index 659e6eb68c..114dda8442 100644
--- a/apps/web/src/features/block-spreadsheet/browser-test/README.md
+++ b/apps/web/src/features/block-spreadsheet/browser-test/README.md
@@ -113,4 +113,10 @@ explicit test document/socket query parameters are supplied.
## Editor interaction regressions
+`range-move.browser.e2e.ts` drags a selection by its border: the destination
+outline and label, formulas following the moved cells, a single undo, the
+confirmation before replacing values, auto-scroll past the grid's bottom edge,
+clicks, double-clicks and the cell menu on the border, and Escape cancelling
+a drag.
+
`editor-interactions.browser.e2e.ts` mounts the real global hotkey listener to verify that selected-cell typing and arrows beat app navigation shortcuts. It also exercises multi-header drag/Shift selection, drags that scroll the grid past its bottom and right edges and back over the sticky headers to reach off-screen cells (including a fill-handle drag down to the last row), persistent row resizing and auto-fit, cross-sheet formula reference picking (including after comparison operators, from a row past the other sheet's end), and numeric/month-end date fill with undo. `formatting.browser.e2e.ts` checks mixed whole-column formatting, style persistence, viewport stability, a styled cell's pixels staying the same when selected, in a range and edited, percentage entry through both editors against the real calculation worker, the accounting layout, and indented line items measured from their aligned edge.
diff --git a/apps/web/src/features/block-spreadsheet/browser-test/range-move.browser.e2e.ts b/apps/web/src/features/block-spreadsheet/browser-test/range-move.browser.e2e.ts
new file mode 100644
index 0000000000..941ae93424
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/browser-test/range-move.browser.e2e.ts
@@ -0,0 +1,160 @@
+import { expect, type Page, test } from '@playwright/test';
+
+/** Press a selection border beside a cell's center, ready to drag. */
+async function grabBorder(
+ page: Page,
+ edge: 'top' | 'right' | 'bottom' | 'left',
+ address: string
+) {
+ const border = await page
+ .locator(`[data-selection-move="${edge}"]`)
+ .boundingBox();
+ const cell = await page.locator(`[data-address="${address}"]`).boundingBox();
+ if (!border || !cell) throw new Error('Selection border must be visible');
+ const vertical = edge === 'left' || edge === 'right';
+ await page.mouse.move(
+ vertical ? border.x + border.width / 2 : cell.x + cell.width / 2,
+ vertical ? cell.y + cell.height / 2 : border.y + border.height / 2
+ );
+ await page.mouse.down();
+}
+
+async function moveTo(page: Page, address: string) {
+ const cell = await page.locator(`[data-address="${address}"]`).boundingBox();
+ if (!cell) throw new Error(`${address} must be visible`);
+ await page.mouse.move(cell.x + cell.width / 2, cell.y + cell.height / 2, {
+ steps: 8,
+ });
+}
+
+const cells = (page: Page) =>
+ page.evaluate(() => window.spreadsheetFixture.snapshot()[0].cells);
+
+test.beforeEach(async ({ page }) => {
+ await page.goto('/');
+ await expect(page.locator('[data-address="B4"]')).toHaveText('30');
+});
+
+test('drags a selection by its border and formulas follow the moved cells', async ({
+ page,
+}) => {
+ const address = page.getByRole('textbox', { name: 'Go to cell' });
+ await page.locator('[data-address="B2"]').click();
+ await page.locator('[data-address="B3"]').click({ modifiers: ['Shift'] });
+ await expect(address).toHaveValue('B2:B3');
+ await expect(page.locator('[data-selection-move="right"]')).toHaveCSS(
+ 'cursor',
+ 'move'
+ );
+
+ await grabBorder(page, 'left', 'B2');
+ await moveTo(page, 'D6');
+ await expect(page.locator('[data-move-destination]')).toHaveText('D6:D7');
+ await page.mouse.up();
+
+ await expect(page.locator('[data-address="D6"]')).toHaveText('10');
+ await expect(page.locator('[data-address="D7"]')).toHaveText('20');
+ await expect(page.locator('[data-address="B2"]')).toHaveText('');
+ await expect(page.locator('[data-address="B4"]')).toHaveText('30');
+ await expect(address).toHaveValue('D6:D7');
+ await expect(page.locator('[data-move-destination]')).toHaveCount(0);
+ expect((await cells(page)).B4.value).toBe('=SUM(D6:D7)');
+
+ // One undo puts the cells and the formula back.
+ await page
+ .getByRole('grid', { name: 'Spreadsheet' })
+ .press('ControlOrMeta+z');
+ await expect(page.locator('[data-address="B2"]')).toHaveText('10');
+ await expect(page.locator('[data-address="D6"]')).toHaveText('');
+ expect((await cells(page)).B4.value).toBe('=SUM(B2:B3)');
+});
+
+test('asks before replacing values at the destination', async ({ page }) => {
+ await page.locator('[data-address="A2"]').click();
+ await grabBorder(page, 'bottom', 'A2');
+ await moveTo(page, 'A3');
+ await page.mouse.up();
+ const dialog = page.getByRole('dialog', { name: 'Replace cells?' });
+ await expect(dialog).toBeVisible();
+ await expect(dialog.getByRole('button', { name: 'Cancel' })).toBeFocused();
+ await dialog.getByRole('button', { name: 'Cancel' }).click();
+ await expect(dialog).toBeHidden();
+ await expect(page.locator('[data-address="A2"]')).toHaveText('Design');
+ await expect(page.locator('[data-address="A3"]')).toHaveText('Engineering');
+
+ await grabBorder(page, 'bottom', 'A2');
+ await moveTo(page, 'A3');
+ await page.mouse.up();
+ await dialog.getByRole('button', { name: 'Replace' }).click();
+ await expect(page.locator('[data-address="A3"]')).toHaveText('Design');
+ await expect(page.locator('[data-address="A2"]')).toHaveText('');
+ await expect(page.getByRole('grid', { name: 'Spreadsheet' })).toBeFocused();
+});
+
+test('scrolls the grid while dragging past its bottom edge', async ({
+ page,
+}) => {
+ const grid = page.getByRole('grid', { name: 'Spreadsheet' });
+ await page.locator('[data-address="A2"]').click();
+ await grabBorder(page, 'bottom', 'A2');
+ const box = await grid.boundingBox();
+ if (!box) throw new Error('Grid must be visible');
+ await page.mouse.move(box.x + 60, box.y + box.height + 30, { steps: 8 });
+ await expect
+ .poll(() => grid.evaluate((element) => element.scrollTop))
+ .toBeGreaterThan(1_000);
+ await page.mouse.up();
+ await expect.poll(async () => (await cells(page)).A2).toBeUndefined();
+ const moved = Object.entries(await cells(page)).find(
+ ([, cell]) => cell.value === 'Design'
+ );
+ expect(moved?.[0]).toMatch(/^A\d+$/);
+ expect(Number(moved?.[0].slice(1))).toBeGreaterThan(50);
+ await expect(page.locator(`[data-address="${moved?.[0]}"]`)).toBeInViewport();
+});
+
+test('the border keeps clicks, double-clicks and the cell menu working', async ({
+ page,
+}) => {
+ const address = page.getByRole('textbox', { name: 'Go to cell' });
+ await page.locator('[data-address="B2"]').click();
+ await page.locator('[data-address="B3"]').click({ modifiers: ['Shift'] });
+ const border = await page
+ .locator('[data-selection-move="bottom"]')
+ .boundingBox();
+ const b3 = await page.locator('[data-address="B3"]').boundingBox();
+ if (!border || !b3) throw new Error('Selection border must be visible');
+ const x = b3.x + b3.width / 2;
+ const y = border.y + border.height / 2;
+ await page.mouse.click(x, y, { button: 'right' });
+ await expect(page.getByRole('menu')).toBeVisible();
+ await expect(
+ page.getByRole('menuitem', { name: 'Fill down', exact: true })
+ ).toBeEnabled();
+ await page.keyboard.press('Escape');
+ await expect(page.getByRole('menu')).toHaveCount(0);
+ await expect(address).toHaveValue('B2:B3');
+ await page.mouse.click(x, y);
+ await expect(address).toHaveValue(/^B[34]$/);
+
+ // A double-click on the edge of the selected cell still edits it.
+ await page.locator('[data-address="C5"]').click();
+ const c5 = await page.locator('[data-address="C5"]').boundingBox();
+ if (!c5) throw new Error('C5 must be visible');
+ await page.mouse.dblclick(c5.x + c5.width / 2, c5.y + 1);
+ await expect(
+ page.getByRole('textbox', { name: 'Edit C5', exact: true })
+ ).toBeVisible();
+});
+
+test('Escape cancels a drag without moving cells', async ({ page }) => {
+ await page.locator('[data-address="A3"]').click();
+ await grabBorder(page, 'top', 'A3');
+ await moveTo(page, 'D10');
+ await expect(page.locator('[data-move-destination]')).toHaveText('D10');
+ await page.keyboard.press('Escape');
+ await expect(page.locator('[data-move-destination]')).toHaveCount(0);
+ await page.mouse.up();
+ await expect(page.locator('[data-address="A3"]')).toHaveText('Engineering');
+ await expect(page.locator('[data-address="D10"]')).toHaveText('');
+});
diff --git a/apps/web/src/features/block-spreadsheet/components/SelectionMoveHandle.tsx b/apps/web/src/features/block-spreadsheet/components/SelectionMoveHandle.tsx
new file mode 100644
index 0000000000..79533b8eb0
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/components/SelectionMoveHandle.tsx
@@ -0,0 +1,210 @@
+import type { CellBounds } from '@macro-inc/spreadsheet/sheet-rules';
+import {
+ createEffect,
+ createSignal,
+ For,
+ type JSX,
+ on,
+ onCleanup,
+ Show,
+} from 'solid-js';
+import { type CellPosition, cellAddress } from '../core/grid-selection';
+import { createDragAutoScroll } from './drag-auto-scroll';
+
+/**
+ * The selection's border, which drags the selected cells to another place.
+ * While dragging, an outline shows where they will land, and the grid scrolls
+ * as the pointer nears or passes its edges.
+ */
+export function SelectionMoveHandle(props: {
+ bounds: CellBounds;
+ rowCount: number;
+ columnCount: number;
+ rangeStyle: (area: CellBounds) => JSX.CSSProperties;
+ positionAtPoint: (x: number, y: number) => CellPosition;
+ /** The scrolling grid, whose sticky headers cover its top and left edges. */
+ scroller: HTMLElement;
+ headerWidth: number;
+ headerHeight: number;
+ /** A drag ends without moving when the sheet changes. */
+ sheetId?: string;
+ onClick: (position: CellPosition, extend: boolean) => void;
+ onDblClick: () => void;
+ onMove: (rows: number, columns: number) => void;
+}) {
+ const [offset, setOffset] = createSignal<{ rows: number; columns: number }>();
+ let drag:
+ | {
+ element: HTMLElement;
+ pointerId: number;
+ /** The grabbed cell, from the selection's top-left cell. */
+ grab: CellPosition;
+ }
+ | undefined;
+
+ const destination = () => {
+ const moved = offset();
+ return (
+ moved && {
+ top: props.bounds.top + moved.rows,
+ left: props.bounds.left + moved.columns,
+ bottom: props.bounds.bottom + moved.rows,
+ right: props.bounds.right + moved.columns,
+ }
+ );
+ };
+
+ function follow(x: number, y: number) {
+ if (!drag) return;
+ // Past an edge, the cells land at the last visible row or column.
+ const rect = props.scroller.getBoundingClientRect();
+ const position = props.positionAtPoint(
+ Math.max(
+ rect.left + props.headerWidth,
+ Math.min(rect.left + props.scroller.clientWidth - 1, x)
+ ),
+ Math.max(
+ rect.top + props.headerHeight,
+ Math.min(rect.top + props.scroller.clientHeight - 1, y)
+ )
+ );
+ const { top, left, bottom, right } = props.bounds;
+ const row = Math.max(
+ 0,
+ Math.min(
+ props.rowCount - 1 - (bottom - top),
+ position.row - drag.grab.row
+ )
+ );
+ const column = Math.max(
+ 0,
+ Math.min(
+ props.columnCount - 1 - (right - left),
+ position.column - drag.grab.column
+ )
+ );
+ const moved = { rows: row - top, columns: column - left };
+ // The outline appears once the cells would land somewhere else.
+ if (offset() || moved.rows || moved.columns) setOffset(moved);
+ }
+
+ // Scrolls only once the pointer has moved, so pressing the border near an
+ // edge does not scroll before a drag starts.
+ const autoScroll = createDragAutoScroll({
+ element: () => props.scroller,
+ inset: () => ({ left: props.headerWidth, top: props.headerHeight }),
+ axis: () => undefined,
+ onEdge: follow,
+ onLostRelease: end,
+ });
+
+ function cancelOnEscape(event: KeyboardEvent) {
+ if (event.key !== 'Escape') return;
+ event.preventDefault();
+ event.stopPropagation();
+ end();
+ }
+
+ function end() {
+ const current = drag;
+ drag = undefined;
+ setOffset(undefined);
+ autoScroll.stop();
+ window.removeEventListener('keydown', cancelOnEscape, true);
+ if (current?.element.hasPointerCapture(current.pointerId))
+ current.element.releasePointerCapture(current.pointerId);
+ }
+
+ createEffect(on(() => props.sheetId, end, { defer: true }));
+ onCleanup(end);
+
+ return (
+ <>
+ <div
+ aria-hidden="true"
+ class="pointer-events-none absolute z-[2]"
+ style={props.rangeStyle(props.bounds)}
+ >
+ <For each={['top', 'right', 'bottom', 'left'] as const}>
+ {(edge) => (
+ <div
+ data-selection-move={edge}
+ class="pointer-events-auto absolute cursor-move touch-none"
+ style={{
+ top: edge === 'bottom' ? 'calc(100% - 3px)' : '-3px',
+ left: edge === 'right' ? 'calc(100% - 3px)' : '-3px',
+ width:
+ edge === 'top' || edge === 'bottom'
+ ? 'calc(100% + 6px)'
+ : '6px',
+ height:
+ edge === 'left' || edge === 'right'
+ ? 'calc(100% + 6px)'
+ : '6px',
+ }}
+ onPointerDown={(event) => {
+ if (event.button !== 0 || event.pointerType === 'touch') return;
+ event.preventDefault();
+ event.stopPropagation();
+ const position = props.positionAtPoint(
+ event.clientX,
+ event.clientY
+ );
+ const { top, left, bottom, right } = props.bounds;
+ drag = {
+ element: event.currentTarget,
+ pointerId: event.pointerId,
+ grab: {
+ row: Math.max(top, Math.min(bottom, position.row)) - top,
+ column:
+ Math.max(left, Math.min(right, position.column)) - left,
+ },
+ };
+ event.currentTarget.setPointerCapture(event.pointerId);
+ window.addEventListener('keydown', cancelOnEscape, true);
+ autoScroll.follow(event);
+ }}
+ onPointerMove={(event) => {
+ if (drag?.pointerId !== event.pointerId) return;
+ follow(event.clientX, event.clientY);
+ autoScroll.move(event);
+ }}
+ onPointerUp={(event) => {
+ if (drag?.pointerId !== event.pointerId) return;
+ const moved = offset();
+ end();
+ if (moved && (moved.rows || moved.columns))
+ props.onMove(moved.rows, moved.columns);
+ else if (!moved)
+ props.onClick(
+ props.positionAtPoint(event.clientX, event.clientY),
+ event.shiftKey
+ );
+ }}
+ onPointerCancel={end}
+ onLostPointerCapture={end}
+ onDblClick={() => props.onDblClick()}
+ />
+ )}
+ </For>
+ </div>
+ <Show when={destination()}>
+ {(area) => (
+ <div
+ aria-hidden="true"
+ data-move-destination
+ class="pointer-events-none absolute z-[3] border-2 border-dashed border-accent"
+ style={props.rangeStyle(area())}
+ >
+ <span class="absolute left-[-2px] top-full mt-0.5 whitespace-nowrap rounded-sm bg-accent px-1 text-[11px] font-medium leading-4 text-surface shadow-sm">
+ {cellAddress({ row: area().top, column: area().left })}
+ {area().bottom > area().top || area().right > area().left
+ ? `:${cellAddress({ row: area().bottom, column: area().right })}`
+ : ''}
+ </span>
+ </div>
+ )}
+ </Show>
+ </>
+ );
+}
diff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetDialogs.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetDialogs.tsx
index d14b84e818..dc0e3f7857 100644
--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetDialogs.tsx
+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetDialogs.tsx
@@ -143,3 +143,54 @@ export function SpreadsheetFindDialog(props: {
</Dialog>
);
}
+
+/** Confirms that moved cells replace values already at their destination. */
+export function SpreadsheetMoveDialog(props: {
+ open: boolean;
+ onConfirm: () => void;
+ onClose: () => void;
+ onRestoreFocus?: () => void;
+}) {
+ return (
+ <Dialog
+ onRestoreFocus={props.onRestoreFocus}
+ open={props.open}
+ onOpenChange={(open) => {
+ if (!open) props.onClose();
+ }}
+ position="center"
+ class="w-96"
+ >
+ <form
+ class="p-5 text-ink"
+ onKeyDown={(event) => event.stopPropagation()}
+ onSubmit={(event) => {
+ event.preventDefault();
+ props.onConfirm();
+ }}
+ >
+ <Dialog.Title class="mb-2 text-sm font-semibold">
+ Replace cells?
+ </Dialog.Title>
+ <Dialog.Description class="mb-4 text-sm text-ink-muted">
+ There are already values where you are moving these cells. Moving
+ replaces them, and formulas that refer to them show #REF!. You can
+ undo this change.
+ </Dialog.Description>
+ <div class="mt-5 flex justify-end gap-2">
+ <Button
+ variant="ghost"
+ size="sm"
+ type="button"
+ onClick={props.onClose}
+ >
+ Cancel
+ </Button>
+ <Button size="sm" variant="strong" type="submit">
+ Replace
+ </Button>
+ </div>
+ </form>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx
index a681a84a98..4c825fd774 100644
--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx
+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx
@@ -65,6 +65,7 @@ import {
} from './cell-colors';
import { createDragAutoScroll, DRAG_SLOP } from './drag-auto-scroll';
import { FormulaInput } from './FormulaInput';
+import { SelectionMoveHandle } from './SelectionMoveHandle';
import { type DrawingRect, SheetDrawingLayer } from './SheetDrawingLayer';
import { type CellAction, SpreadsheetCellMenu } from './SpreadsheetCellMenu';
import {
@@ -195,6 +196,12 @@ export function SpreadsheetGrid(props: {
target: CellSelection
) => void | Promise<void>;
onCopyMetadata?: (cut?: boolean) => string;
+ /** Drag the selection's border to move its cells by rows and columns. */
+ onMoveSelection?: (
+ selection: CellSelection,
+ rows: number,
+ columns: number
+ ) => void;
values: Record<string, GridValue>;
/** Excel notes by address, marked in their cells. */
notes?: Record<string, string>;
@@ -1268,8 +1275,13 @@ export function SpreadsheetGrid(props: {
onContextMenu={(event) => {
if (isInput(event.target)) return;
const cell = event.target.closest<HTMLElement>('[data-address]');
- if (!cell || !grid.contains(cell)) return;
- const parsed = parseCellAddress(cell.dataset.address ?? '');
+ // The selection's move border opens the menu for the selection.
+ const parsed =
+ cell && grid.contains(cell)
+ ? parseCellAddress(cell.dataset.address ?? '')
+ : event.target.closest('[data-selection-move]')
+ ? props.selection.anchor
+ : undefined;
if (!parsed) return;
event.preventDefault();
event.stopPropagation();
@@ -2170,6 +2182,38 @@ export function SpreadsheetGrid(props: {
class="pointer-events-none absolute z-[2] border-2 border-accent"
style={activeStyle()}
/>
+ <Show
+ when={
+ !touchMode() &&
+ !props.readonly &&
+ !props.editing &&
+ !props.formulaEditing &&
+ props.onMoveSelection
+ }
+ >
+ {(onMoveSelection) => (
+ <SelectionMoveHandle
+ bounds={selectionBounds(props.selection)}
+ rowCount={rowCount()}
+ columnCount={columnCount()}
+ rangeStyle={rangeStyle}
+ positionAtPoint={positionAtPoint}
+ scroller={grid}
+ headerWidth={headerWidth()}
+ headerHeight={headerHeight()}
+ sheetId={props.sheetId}
+ onClick={(position, extend) => {
+ props.onSelect(position, extend);
+ focusGrid();
+ }}
+ onDblClick={props.onEdit}
+ onMove={(rows, columns) => {
+ focusGrid();
+ onMoveSelection()(props.selection, rows, columns);
+ }}
+ />
+ )}
+ </Show>
<Show when={listButtonShown() && props.listItems}>
{(items) => {
const address = () => cellAddress(props.selection.anchor);
diff --git a/apps/web/src/features/block-spreadsheet/core/calculation-protocol.ts b/apps/web/src/features/block-spreadsheet/core/calculation-protocol.ts
index dfd4ead66e..a196728ea7 100644
--- a/apps/web/src/features/block-spreadsheet/core/calculation-protocol.ts
+++ b/apps/web/src/features/block-spreadsheet/core/calculation-protocol.ts
@@ -5,7 +5,10 @@ import type {
} from '@macro-inc/spreadsheet/goal-seek';
import type { SheetPivotLayout } from '@macro-inc/spreadsheet/pivot-layout';
import type { WorkbookSheetMetadata } from '@macro-inc/spreadsheet/workbook-metadata';
-import type { AxisChange } from '@macro-inc/spreadsheet/workbook-structure';
+import type {
+ AxisChange,
+ RangeMove,
+} from '@macro-inc/spreadsheet/workbook-structure';
import type {
CalculatedCell,
CalculationContext,
@@ -46,6 +49,12 @@ export type CalculationRequest =
sheets: SpreadsheetWorkbookSheet[];
change: AxisChange;
}
+ | {
+ id: number;
+ type: 'move-range';
+ sheets: SpreadsheetWorkbookSheet[];
+ move: RangeMove;
+ }
| { id: number; type: 'calculate'; cells: SpreadsheetCells; rowCount: number }
| { id: number; type: 'calculate-workbook'; sheets: CalculationSheet[] }
| { id: number; type: 'update-workbook'; sheets: CalculationSheetPatch[] }
@@ -72,6 +81,7 @@ export type CalculationRequest =
export type CalculationResponse =
| { id: number; type: 'change-axis'; sheets: SpreadsheetWorkbookSheet[] }
+ | { id: number; type: 'move-range'; sheets: SpreadsheetWorkbookSheet[] }
| { id: number; type: 'started' }
| { id: number; type: 'calculate'; values: SpreadsheetCalculation }
| { id: number; type: 'calculate-workbook'; values: WorkbookCalculation }
@@ -90,6 +100,7 @@ export type CalculationResponse =
export type CalculationOperation =
| Omit<Extract<CalculationRequest, { type: 'change-axis' }>, 'id'>
+ | Omit<Extract<CalculationRequest, { type: 'move-range' }>, 'id'>
| Omit<Extract<CalculationRequest, { type: 'calculate' }>, 'id'>
| Omit<Extract<CalculationRequest, { type: 'calculate-workbook' }>, 'id'>
| Omit<Extract<CalculationRequest, { type: 'update-workbook' }>, 'id'>
diff --git a/apps/web/src/features/block-spreadsheet/core/sheet-operations.ts b/apps/web/src/features/block-spreadsheet/core/sheet-operations.ts
index dd94ac86e5..5e28cc7180 100644
--- a/apps/web/src/features/block-spreadsheet/core/sheet-operations.ts
+++ b/apps/web/src/features/block-spreadsheet/core/sheet-operations.ts
@@ -2,6 +2,7 @@ import {
cellPlainText,
cellTextParts,
} from '@macro-inc/spreadsheet/cell-mentions';
+import type { RangeMove } from '@macro-inc/spreadsheet/workbook-structure';
import type { CellCopy, SpreadsheetCalculation } from './calculation';
import { csvCellValue } from './csv-value';
import {
@@ -96,6 +97,31 @@ export function borderEdits(
);
}
+/** Whether moving cells would replace values that are not among them. */
+export function moveReplacesValues(cells: SpreadsheetCells, move: RangeMove) {
+ const { source, rows, columns } = move;
+ for (const address in cells) {
+ if (!cells[address].value) continue;
+ const position = positionFromAddress(address);
+ if (
+ !position ||
+ position.row < source.top + rows ||
+ position.row > source.bottom + rows ||
+ position.column < source.left + columns ||
+ position.column > source.right + columns
+ )
+ continue;
+ if (
+ position.row < source.top ||
+ position.row > source.bottom ||
+ position.column < source.left ||
+ position.column > source.right
+ )
+ return true;
+ }
+ return false;
+}
+
/** Sort entire selected rows together using the active column as the key. */
export function sortedRangeCopies(
cells: SpreadsheetCells,
diff --git a/apps/web/src/features/block-spreadsheet/core/workbook-structure.test.ts b/apps/web/src/features/block-spreadsheet/core/workbook-structure.test.ts
index dbecde3cd9..8dab11c719 100644
--- a/apps/web/src/features/block-spreadsheet/core/workbook-structure.test.ts
+++ b/apps/web/src/features/block-spreadsheet/core/workbook-structure.test.ts
@@ -1,7 +1,10 @@
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { initSync } from '@ironcalc/wasm';
-import { changeWorkbookAxis } from '@macro-inc/spreadsheet/workbook-structure';
+import {
+ changeWorkbookAxis,
+ moveWorkbookRange,
+} from '@macro-inc/spreadsheet/workbook-structure';
import { beforeAll, describe, expect, it } from 'vitest';
import type { SpreadsheetWorkbookSheet } from './workbook-document';
@@ -360,3 +363,268 @@ it.each([
expect(next[0].cells[axis === 'row' ? 'C2' : 'B3'].value).toBe(expected);
}
);
+
+describe('moving a range of cells', () => {
+ it('moves cells with their formats and points references from every sheet at them', () => {
+ const before = workbook();
+ before[0].cells.D1 = { value: '=A1*2+A3' };
+ before[0].cells.D2 = { value: '=SUM(A1:A3)' };
+ const next = moveWorkbookRange(before, {
+ sheetId: 'one',
+ source: { top: 0, left: 0, bottom: 1, right: 0 },
+ rows: 4,
+ columns: 2,
+ });
+ expect(next[0].cells.A1).toBeUndefined();
+ expect(next[0].cells.A2).toBeUndefined();
+ expect(next[0].cells.C5).toEqual({ value: '10', bold: true });
+ expect(next[0].cells.C6).toEqual({ value: '20' });
+ expect(next[0].cells.B2.value).toBe('=SUM($C$5:C6)');
+ expect(next[0].cells.D1.value).toBe('=C5*2+A3');
+ // A range follows only when all of it moves.
+ expect(next[0].cells.D2.value).toBe('=SUM(A1:A3)');
+ expect(next[0].cells.C1).toEqual({ value: '=A1', format: 'text' });
+ expect(next[1].cells.A1.value).toBe('=Inputs!C6+Inputs!$C$5');
+ expect(next[0].metadata?.definedNames?.[0].formula).toBe(
+ 'Inputs!$C$5:$C$6'
+ );
+ expect(before[0].cells.A1).toEqual({ value: '10', bold: true });
+ });
+
+ it('keeps the references inside moved formulas on the same cells', () => {
+ const before = workbook();
+ before[0].cells.D1 = { value: '=B2*2' };
+ const next = moveWorkbookRange(before, {
+ sheetId: 'one',
+ source: { top: 1, left: 1, bottom: 1, right: 1 },
+ rows: 8,
+ columns: 3,
+ });
+ expect(next[0].cells.B2).toBeUndefined();
+ expect(next[0].cells.E10.value).toBe('=SUM($A$1:A2)');
+ expect(next[0].cells.D1.value).toBe('=E10*2');
+ });
+
+ it('moves a block with formulas that refer within it, preserving sheet names as written', () => {
+ const before: SpreadsheetWorkbookSheet[] = [
+ {
+ id: 'one',
+ name: 'My Data',
+ cells: {
+ A1: { value: '5' },
+ A2: { value: '=A1+1' },
+ A3: { value: "=SUM('My Data'!A1:A2)" },
+ },
+ layout: { rowCount: 200, columnCount: 26, columnWidths: {} },
+ },
+ {
+ id: 'two',
+ name: 'Report',
+ cells: {
+ A1: { value: "= 'my data'!A3 * 'My Data'!$A$1" },
+ A2: { value: '=A3' },
+ },
+ layout: { rowCount: 200, columnCount: 26, columnWidths: {} },
+ },
+ ];
+ const next = moveWorkbookRange(before, {
+ sheetId: 'one',
+ source: { top: 0, left: 0, bottom: 2, right: 0 },
+ rows: 0,
+ columns: 1,
+ });
+ expect(next[0].cells).toEqual({
+ B1: { value: '5' },
+ B2: { value: '=B1+1' },
+ B3: { value: "=SUM('My Data'!B1:B2)" },
+ });
+ expect(next[1].cells.A1.value).toBe("= 'my data'!B3 * 'My Data'!$B$1");
+ // An unqualified reference on another sheet names that sheet.
+ expect(next[1].cells.A2.value).toBe('=A3');
+ });
+
+ it('replaces the destination, and its references become #REF!', () => {
+ const before = workbook();
+ before[0].cells = {
+ A1: { value: '1' },
+ A2: { value: '2' },
+ A3: { value: '3' },
+ C1: { value: 'old', fillColor: '#ff0000' },
+ C2: { value: 'old' },
+ D1: { value: '=C1' },
+ D2: { value: '=SUM(C1:C2)' },
+ D3: { value: '=SUM(C1:C9)' },
+ D4: { value: '=A3' },
+ };
+ const next = moveWorkbookRange(before, {
+ sheetId: 'one',
+ source: { top: 0, left: 0, bottom: 1, right: 0 },
+ rows: 0,
+ columns: 2,
+ });
+ expect(next[0].cells.C1).toEqual({ value: '1' });
+ expect(next[0].cells.C2).toEqual({ value: '2' });
+ expect(next[0].cells.D1.value).toBe('=#REF!');
+ expect(next[0].cells.D2.value).toBe('=SUM(#REF!)');
+ expect(next[0].cells.D3.value).toBe('=SUM(C1:C9)');
+ expect(next[0].cells.D4.value).toBe('=A3');
+ });
+
+ it('moves a range onto part of itself', () => {
+ const before = workbook();
+ before[0].cells = {
+ A1: { value: '1' },
+ A2: { value: '2' },
+ A3: { value: '3' },
+ A4: { value: '4' },
+ B1: { value: '=A2+A4' },
+ B2: { value: '=SUM(A1:A3)' },
+ };
+ const next = moveWorkbookRange(before, {
+ sheetId: 'one',
+ source: { top: 0, left: 0, bottom: 2, right: 0 },
+ rows: 1,
+ columns: 0,
+ });
+ expect(next[0].cells.A1).toBeUndefined();
+ expect(next[0].cells.A2).toEqual({ value: '1' });
+ expect(next[0].cells.A3).toEqual({ value: '2' });
+ expect(next[0].cells.A4).toEqual({ value: '3' });
+ expect(next[0].cells.B1.value).toBe('=A3+#REF!');
+ expect(next[0].cells.B2.value).toBe('=SUM(A2:A4)');
+ });
+
+ it('moves notes, merges, arrays and rules with their cells and splits rules that partly move', () => {
+ const before = workbook();
+ before[0].metadata = {
+ notes: { A1: 'Moves', C1: 'Replaced', E5: 'Stays' },
+ merges: ['A1:B1', 'E7:F7'],
+ arrayFormulas: { A2: 'A2:B2' },
+ validations: [
+ { range: 'A1:A10', type: 'list', formulas: ['"Yes,No"'] },
+ { range: 'C2', type: 'whole', formulas: ['$A$1', '100'] },
+ ],
+ conditionalFormats: [
+ { range: 'B1:B2', type: 'expression', formulas: ['$B1>$A$2'] },
+ ],
+ drawings: [
+ {
+ id: 'chart',
+ type: 'chart',
+ from: { row: 4, column: 2, x: 0, y: 0 },
+ to: { row: 9, column: 6, x: 0, y: 0 },
+ chart: {
+ plots: [{ kind: 'column', series: [{ values: 0 }] }],
+ references: ['Inputs!$A$1:$B$2'],
+ },
+ },
+ ],
+ };
+ const next = moveWorkbookRange(before, {
+ sheetId: 'one',
+ source: { top: 0, left: 0, bottom: 1, right: 1 },
+ rows: 0,
+ columns: 2,
+ });
+ expect(next[0].metadata).toMatchObject({
+ notes: { C1: 'Moves', E5: 'Stays' },
+ merges: ['C1:D1', 'E7:F7'],
+ arrayFormulas: { C2: 'C2:D2' },
+ validations: [
+ { range: 'A3:A10', formulas: ['"Yes,No"'] },
+ { range: 'C1:C2', formulas: ['"Yes,No"'] },
+ ],
+ conditionalFormats: [{ range: 'D1:D2', formulas: ['$D1>$C$2'] }],
+ drawings: [
+ {
+ from: { row: 4, column: 2 },
+ chart: { references: ['Inputs!$C$1:$D$2'] },
+ },
+ ],
+ });
+ // The validation on C2 was replaced by the moved cells' rule.
+ expect(next[0].metadata?.validations).toHaveLength(2);
+ });
+
+ it('refuses to split a merged cell without changing the workbook', () => {
+ const sheets = workbook();
+ const before = JSON.stringify(sheets);
+ expect(() =>
+ moveWorkbookRange(sheets, {
+ sheetId: 'one',
+ source: { top: 2, left: 2, bottom: 2, right: 2 },
+ rows: 3,
+ columns: 0,
+ })
+ ).toThrow('This move would split a merged cell.');
+ expect(() =>
+ moveWorkbookRange(sheets, {
+ sheetId: 'one',
+ source: { top: 0, left: 0, bottom: 0, right: 0 },
+ rows: 2,
+ columns: 3,
+ })
+ ).toThrow('This move would split a merged cell.');
+ expect(JSON.stringify(sheets)).toBe(before);
+ });
+
+ it('moves whole-row references with rows selected by their headers and grows the sheet to fit', () => {
+ const sheets = workbook();
+ sheets[0].cells = {
+ A1: { value: '1' },
+ A10: { value: '=SUM(1:2)+SUM($1:$1)+SUM(A:A)' },
+ };
+ sheets[0].metadata = undefined;
+ const next = moveWorkbookRange(sheets, {
+ sheetId: 'one',
+ source: { top: 0, left: 0, bottom: 1, right: 25 },
+ rows: 250,
+ columns: 0,
+ });
+ expect(next[0].cells.A251).toEqual({ value: '1' });
+ expect(next[0].cells.A10.value).toBe(
+ '=SUM(251:252)+SUM($251:$251)+SUM(A:A)'
+ );
+ expect(next[0].layout).toMatchObject({ rowCount: 252, columnCount: 26 });
+ });
+
+ it('moves whole-column references with columns selected by their headers', () => {
+ const sheets = workbook();
+ sheets[0].cells = {
+ A1: { value: '1' },
+ D1: { value: '=SUM(A:A)+SUM($A:$A)+SUM(1:1)+SUM(A1:B1)' },
+ };
+ sheets[0].metadata = undefined;
+ const next = moveWorkbookRange(sheets, {
+ sheetId: 'one',
+ source: { top: 0, left: 0, bottom: 199, right: 0 },
+ rows: 0,
+ columns: 2,
+ });
+ expect(next[0].cells.C1).toEqual({ value: '1' });
+ expect(next[0].cells.D1.value).toBe(
+ '=SUM(C:C)+SUM($C:$C)+SUM(1:1)+SUM(A1:B1)'
+ );
+ // A column that is not the whole sheet height leaves A:A where it is.
+ const partial = moveWorkbookRange(sheets, {
+ sheetId: 'one',
+ source: { top: 0, left: 0, bottom: 198, right: 0 },
+ rows: 0,
+ columns: 2,
+ });
+ expect(partial[0].cells.D1.value).toBe(
+ '=SUM(A:A)+SUM($A:$A)+SUM(1:1)+SUM(A1:B1)'
+ );
+ });
+
+ it.each([
+ { top: 0, left: 0, bottom: 0, right: 0, rows: 0, columns: 0 },
+ { top: 0, left: 0, bottom: 0, right: 0, rows: -1, columns: 0 },
+ { top: 99_999, left: 0, bottom: 99_999, right: 0, rows: 1, columns: 0 },
+ { top: 1, left: 0, bottom: 0, right: 0, rows: 1, columns: 0 },
+ ])('rejects an invalid move %o', ({ rows, columns, ...source }) => {
+ expect(() =>
+ moveWorkbookRange(workbook(), { sheetId: 'one', source, rows, columns })
+ ).toThrow('Invalid cell range.');
+ });
+});
diff --git a/apps/web/src/features/block-spreadsheet/primitives/create-calculation.ts b/apps/web/src/features/block-spreadsheet/primitives/create-calculation.ts
index 6609c5e225..fb7a625645 100644
--- a/apps/web/src/features/block-spreadsheet/primitives/create-calculation.ts
+++ b/apps/web/src/features/block-spreadsheet/primitives/create-calculation.ts
@@ -3,7 +3,10 @@ import type {
GoalSeekResult,
} from '@macro-inc/spreadsheet/goal-seek';
import { sheetPivotLayouts } from '@macro-inc/spreadsheet/pivot-layout';
-import type { AxisChange } from '@macro-inc/spreadsheet/workbook-structure';
+import type {
+ AxisChange,
+ RangeMove,
+} from '@macro-inc/spreadsheet/workbook-structure';
import {
type Accessor,
createEffect,
@@ -448,6 +451,12 @@ export function createCalculation(
throw new Error('Unable to change sheet structure.');
return result.sheets;
},
+ async moveRange(sheets: SpreadsheetWorkbookSheet[], move: RangeMove) {
+ const result = await copier.run({ type: 'move-range', sheets, move });
+ if (result.type !== 'move-range')
+ throw new Error('Unable to move cells.');
+ return result.sheets;
+ },
async copy(copies: CellCopy[]) {
const result = await copier.run({
type: 'copy',
diff --git a/apps/web/src/features/block-spreadsheet/primitives/create-range-move.test.ts b/apps/web/src/features/block-spreadsheet/primitives/create-range-move.test.ts
new file mode 100644
index 0000000000..609a6ef5f3
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/primitives/create-range-move.test.ts
@@ -0,0 +1,143 @@
+import { readFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { initSync } from '@ironcalc/wasm';
+import { moveWorkbookRange } from '@macro-inc/spreadsheet/workbook-structure';
+import { LoroDoc } from 'loro-crdt';
+import { createRoot } from 'solid-js';
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import {
+ readSpreadsheetCells,
+ writeSpreadsheetCells,
+} from '../core/spreadsheet-document';
+import { createRangeMove } from './create-range-move';
+import { createSpreadsheetStore } from './create-spreadsheet-store';
+
+beforeAll(() =>
+ initSync({
+ module: readFileSync(
+ createRequire(import.meta.url).resolve('@ironcalc/wasm/wasm_bg.wasm')
+ ),
+ })
+);
+const cleanups: Array<() => void> = [];
+afterEach(() => {
+ for (const dispose of cleanups.splice(0)) dispose();
+});
+
+function setup(
+ cells: Parameters<typeof writeSpreadsheetCells>[1] = {
+ A1: { value: '10', bold: true },
+ A2: { value: '20' },
+ B1: { value: '=SUM(A1:A2)' },
+ C1: { value: 'Taken' },
+ }
+) {
+ const doc = new LoroDoc();
+ cleanups.push(() => doc.free());
+ writeSpreadsheetCells(doc, cells);
+ return createRoot((dispose) => {
+ cleanups.unshift(dispose);
+ const store = createSpreadsheetStore({
+ canEdit: () => true,
+ source: {
+ doc: () => doc,
+ ready: () => true,
+ error: () => undefined,
+ status: () => 'connected',
+ peers: () => [],
+ setSelection: () => {},
+ },
+ });
+ const select = vi.fn();
+ const setNotice = vi.fn();
+ const setBusy = vi.fn();
+ const rangeMove = createRangeMove({
+ store,
+ canMove: () => true,
+ moveRange: async (sheets, move) => moveWorkbookRange(sheets, move),
+ setBusy,
+ setNotice,
+ select,
+ });
+ return { doc, store, rangeMove, select, setNotice, setBusy };
+ });
+}
+const firstColumn = {
+ anchor: { row: 0, column: 0 },
+ focus: { row: 1, column: 0 },
+};
+
+describe('moving selected cells', () => {
+ it('moves into empty cells as one undo step and selects them', async () => {
+ const { store, rangeMove, select, setBusy } = setup();
+ await rangeMove.move(firstColumn, 0, 3);
+ expect(store.cells().A1).toBeUndefined();
+ expect(store.cells().D1).toEqual({ value: '10', bold: true });
+ expect(store.cells().D2).toEqual({ value: '20' });
+ expect(store.cells().B1.value).toBe('=SUM(D1:D2)');
+ expect(select).toHaveBeenCalledWith(
+ { row: 0, column: 3 },
+ { row: 1, column: 3 }
+ );
+ expect(setBusy.mock.calls).toEqual([[true], [false]]);
+ store.undo();
+ expect(store.cells().A1).toEqual({ value: '10', bold: true });
+ expect(store.cells().B1.value).toBe('=SUM(A1:A2)');
+ expect(store.cells().D1).toBeUndefined();
+ expect(store.canUndo()).toBe(false);
+ });
+
+ it('asks before replacing values, and cancelling keeps every cell', async () => {
+ const { store, rangeMove } = setup();
+ expect(rangeMove.move(firstColumn, 0, 2)).toBeUndefined();
+ expect(rangeMove.confirming()?.move).toEqual({
+ sheetId: 'sheet1',
+ source: { top: 0, left: 0, bottom: 1, right: 0 },
+ rows: 0,
+ columns: 2,
+ });
+ rangeMove.cancel();
+ expect(rangeMove.confirming()).toBeUndefined();
+ expect(store.cells().A1.value).toBe('10');
+ expect(store.cells().C1.value).toBe('Taken');
+ rangeMove.move(firstColumn, 0, 2);
+ await rangeMove.confirm();
+ expect(store.cells().A1).toBeUndefined();
+ expect(store.cells().C1).toEqual({ value: '10', bold: true });
+ expect(store.cells().B1.value).toBe('=SUM(C1:C2)');
+ });
+
+ it('moves whole-row references with rows selected by their headers', async () => {
+ const { store, rangeMove } = setup({
+ A1: { value: '10' },
+ B2: { value: '20' },
+ A10: { value: '=SUM(1:2)+SUM($1:$2)+SUM(A1:B2)' },
+ });
+ // A row-header selection ends at the sheet's last column.
+ const rows = {
+ anchor: { row: 0, column: 0 },
+ focus: { row: 1, column: store.columnCount() - 1 },
+ };
+ await rangeMove.move(rows, 3, 0);
+ expect(store.cells().A4).toEqual({ value: '10' });
+ expect(store.cells().B5).toEqual({ value: '20' });
+ expect(store.cells().A10.value).toBe('=SUM(4:5)+SUM($4:$5)+SUM(A4:B5)');
+ });
+
+ it("cancels a confirmed move after a collaborator's edit and keeps both", async () => {
+ const { doc, store, rangeMove, setNotice } = setup();
+ rangeMove.move(firstColumn, 0, 2);
+ const peer = new LoroDoc();
+ cleanups.push(() => peer.free());
+ peer.import(doc.export({ mode: 'snapshot' }));
+ writeSpreadsheetCells(peer, { E5: { value: 'From a collaborator' } });
+ doc.import(peer.export({ mode: 'update' }));
+ await rangeMove.confirm();
+ expect(setNotice).toHaveBeenCalledWith(
+ 'The workbook changed while moving cells. No changes were applied; try again.'
+ );
+ expect(readSpreadsheetCells(doc).A1.value).toBe('10');
+ expect(readSpreadsheetCells(doc).C1.value).toBe('Taken');
+ expect(store.cells().E5.value).toBe('From a collaborator');
+ });
+});
diff --git a/apps/web/src/features/block-spreadsheet/primitives/create-range-move.ts b/apps/web/src/features/block-spreadsheet/primitives/create-range-move.ts
new file mode 100644
index 0000000000..86cf8d4a23
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/primitives/create-range-move.ts
@@ -0,0 +1,113 @@
+import { Telemetry } from '@macro-inc/observability';
+import type { RangeMove } from '@macro-inc/spreadsheet/workbook-structure';
+import { type Accessor, createSignal } from 'solid-js';
+import {
+ type CellPosition,
+ type CellSelection,
+ selectionBounds,
+} from '../core/grid-selection';
+import { moveReplacesValues } from '../core/sheet-operations';
+import type { SpreadsheetWorkbookSheet } from '../core/workbook-document';
+import type { SpreadsheetStore } from './create-spreadsheet-store';
+
+type PendingMove = {
+ move: RangeMove;
+ selection: CellSelection;
+ before: SpreadsheetWorkbookSheet[];
+ revision: number;
+ replacesValues: boolean;
+};
+
+/**
+ * Move the selected cells to another place on their sheet. Replacing values
+ * waits for confirmation. The move is one revision-checked structural change,
+ * so a collaborator's edit in the meantime cancels it and undo reverses it.
+ */
+export function createRangeMove(options: {
+ /** A saved workbook's document, recorded on traces. */
+ documentId?: string;
+ store: Pick<
+ SpreadsheetStore,
+ 'workbook' | 'revision' | 'activeSheetId' | 'applyStructure'
+ >;
+ canMove: Accessor<boolean>;
+ moveRange: (
+ sheets: SpreadsheetWorkbookSheet[],
+ move: RangeMove
+ ) => Promise<SpreadsheetWorkbookSheet[]>;
+ setBusy: (busy: boolean) => void;
+ setNotice: (message: string) => void;
+ select: (anchor: CellPosition, focus: CellPosition) => void;
+}) {
+ const [confirming, setConfirming] = createSignal<PendingMove>();
+
+ function apply(pending: PendingMove) {
+ const { move, before } = pending;
+ return Telemetry.span('spreadsheet.move_range', async (span) => {
+ if (options.documentId) span.setAttr('document.id', options.documentId);
+ span.setAttr('spreadsheet.sheet_id', move.sheetId);
+ span.setAttr(
+ 'spreadsheet.move.cells',
+ (move.source.bottom - move.source.top + 1) *
+ (move.source.right - move.source.left + 1)
+ );
+ span.setAttr('spreadsheet.move.rows', move.rows);
+ span.setAttr('spreadsheet.move.columns', move.columns);
+ span.setAttr('spreadsheet.move.replaces_values', pending.replacesValues);
+ options.setBusy(true);
+ try {
+ const next = await span.span('spreadsheet.move_range.calculate', () =>
+ options.moveRange(before, move)
+ );
+ await span.span('spreadsheet.move_range.commit', async () =>
+ options.store.applyStructure(before, next, pending.revision)
+ );
+ if (options.store.activeSheetId() !== move.sheetId) return;
+ const { anchor, focus } = pending.selection;
+ options.select(
+ { row: anchor.row + move.rows, column: anchor.column + move.columns },
+ { row: focus.row + move.rows, column: focus.column + move.columns }
+ );
+ } catch (error) {
+ span.error(error);
+ options.setNotice(
+ error instanceof Error ? error.message : 'Unable to move cells.'
+ );
+ } finally {
+ options.setBusy(false);
+ }
+ });
+ }
+
+ return {
+ /** A move that replaces values, waiting for confirmation. */
+ confirming,
+ move(selection: CellSelection, rows: number, columns: number) {
+ if (!options.canMove() || (!rows && !columns)) return;
+ const before = structuredClone(options.store.workbook());
+ const sheetId = options.store.activeSheetId();
+ const move = {
+ sheetId,
+ source: selectionBounds(selection),
+ rows,
+ columns,
+ };
+ const cells = before.find((sheet) => sheet.id === sheetId)?.cells ?? {};
+ const pending: PendingMove = {
+ move,
+ selection,
+ before,
+ revision: options.store.revision(),
+ replacesValues: moveReplacesValues(cells, move),
+ };
+ if (!pending.replacesValues) return apply(pending);
+ setConfirming(pending);
+ },
+ confirm() {
+ const pending = confirming();
+ setConfirming(undefined);
+ if (pending) return apply(pending);
+ },
+ cancel: () => setConfirming(undefined),
+ };
+}
diff --git a/apps/web/src/features/block-spreadsheet/primitives/create-spreadsheet-store.ts b/apps/web/src/features/block-spreadsheet/primitives/create-spreadsheet-store.ts
index 66a8e5ae2a..f462d70b8d 100644
--- a/apps/web/src/features/block-spreadsheet/primitives/create-spreadsheet-store.ts
+++ b/apps/web/src/features/block-spreadsheet/primitives/create-spreadsheet-store.ts
@@ -676,7 +676,7 @@ export function createSpreadsheetStore(options: {
if (!doc || !editable())
throw new Error('This spreadsheet is view only.');
if (!canShiftCoordinates())
- throw new Error('Reconnect to insert or delete rows or columns.');
+ throw new Error('Reconnect to insert, delete or move cells.');
if (
revision() !== expectedRevision ||
sheetLayoutChanged(workbook(), expected)
diff --git a/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx b/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx
index 06b39d6637..3f0350e840 100644
--- a/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx
+++ b/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx
@@ -30,7 +30,10 @@ import {
} from '../components/DropdownDialog';
import { SpreadsheetFileMenu } from '../components/SpreadsheetActionMenus';
import { SpreadsheetDialog } from '../components/SpreadsheetDialog';
-import { SpreadsheetFindDialog } from '../components/SpreadsheetDialogs';
+import {
+ SpreadsheetFindDialog,
+ SpreadsheetMoveDialog,
+} from '../components/SpreadsheetDialogs';
import { SpreadsheetGoalSeekDialog } from '../components/SpreadsheetGoalSeekDialog';
import {
renderedSelectionCell,
@@ -85,11 +88,14 @@ import { createCalculationStatus } from '../primitives/create-calculation-status
import { createDrawingActions } from '../primitives/create-drawing-actions';
import { createGoalSeek } from '../primitives/create-goal-seek';
import { createGridController } from '../primitives/create-grid-controller';
+import { createRangeMove } from '../primitives/create-range-move';
import { createSheetActions } from '../primitives/create-sheet-actions';
import type { SpreadsheetStore } from '../primitives/create-spreadsheet-store';
import { createWorkbookActions } from '../primitives/create-workbook-actions';
export function SpreadsheetEditor(props: {
+ /** A saved workbook's document, recorded on traces. */
+ documentId?: string;
store: SpreadsheetStore;
mentions?: SpreadsheetMentions;
name: string;
@@ -345,6 +351,16 @@ export function SpreadsheetEditor(props: {
},
grid
);
+ const canMoveCells = () => editable() && props.store.canChangeStructure();
+ const rangeMove = createRangeMove({
+ documentId: props.documentId,
+ store: props.store,
+ canMove: canMoveCells,
+ moveRange: calculation.moveRange,
+ setBusy: setStructureBusy,
+ setNotice: actions.setNotice,
+ select: grid.selectRange,
+ });
const remoteCursors = createMemo(() =>
spreadsheetCursors(props.store.peers(), props.store.rowCount())
);
@@ -1017,6 +1033,15 @@ export function SpreadsheetEditor(props: {
onResizeColumn={props.store.resizeColumn}
onFill={grid.fill}
onCopyMetadata={grid.copyMetadata}
+ onMoveSelection={
+ canMoveCells()
+ ? (selection, rows, columns) => {
+ grid.commit();
+ actions.clearNotice();
+ void rangeMove.move(selection, rows, columns);
+ }
+ : undefined
+ }
values={values()}
notes={props.store.activeSheet().metadata?.notes}
drawings={props.store.activeSheet().metadata?.drawings}
@@ -1327,6 +1352,12 @@ export function SpreadsheetEditor(props: {
else focusGrid();
}}
/>
+ <SpreadsheetMoveDialog
+ open={!!rangeMove.confirming()}
+ onConfirm={() => void rangeMove.confirm()}
+ onClose={rangeMove.cancel}
+ onRestoreFocus={focusGrid}
+ />
<DropdownDialog
dialog={dropdownDialog()}
error={dropdownError()}
diff --git a/apps/web/src/features/block-spreadsheet/workers/calculation.worker.ts b/apps/web/src/features/block-spreadsheet/workers/calculation.worker.ts
index 972937a843..98551033e0 100644
--- a/apps/web/src/features/block-spreadsheet/workers/calculation.worker.ts
+++ b/apps/web/src/features/block-spreadsheet/workers/calculation.worker.ts
@@ -135,6 +135,11 @@ self.onmessage = async (event: MessageEvent<CalculationRequest>) => {
type: 'change-axis',
sheets: engine.changeAxis(operation.sheets, operation.change),
}))
+ .with({ type: 'move-range' }, (operation) => ({
+ id: operation.id,
+ type: 'move-range',
+ sheets: engine.moveRange(operation.sheets, operation.move),
+ }))
.with({ type: 'calculate' }, (operation) => ({
id: operation.id,
type: 'calculate',
diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.md
index 192bb388da..9976106351 100644
--- a/docs/agent-guide/documents.md
+++ b/docs/agent-guide/documents.md
@@ -316,6 +316,19 @@ irregular patterns repeat; relative formula references translate. Keyboard/menu
Fill down/right explicitly copies the starting row/column. Plain-text paste from
other apps keeps formulas as supplied.
+With a mouse, hover the selection's border until the cursor becomes a move
+cursor, then drag it to move the cells; a dashed outline and its address (for
+example `D6:E9`) show where they will land, and the grid scrolls when the pointer
+nears or passes its edge. Escape cancels the drag. Values, formatting, notes and
+validation go with the cells, the moved cells stay selected, and formulas that
+refer to them follow: `=SUM(B2:B3)` becomes `=SUM(D6:D7)` after moving B2:B3 to
+D6. Moving onto cells that hold values asks **Replace cells?** first (Cancel is
+focused); formulas that referred to the replaced cells show `#REF!`. One undo
+reverses the move. Like insert/delete, moving is unavailable while a saved
+workbook is offline, and a collaborator's edit made meanwhile cancels it with a
+footer notice. Moving part of a merged cell is refused. Touch screens keep the
+selection handles instead.
+
Drag a column header's right boundary or row header's bottom boundary to resize;
double-click the boundary to auto-fit. Row separators support Up/Down arrows and
Enter to restore automatic height. Explicit row heights take precedence over wrap.
diff --git a/packages/spreadsheet/src/calculation.ts b/packages/spreadsheet/src/calculation.ts
index dcba7433e2..3b5e532f59 100644
--- a/packages/spreadsheet/src/calculation.ts
+++ b/packages/spreadsheet/src/calculation.ts
@@ -31,7 +31,7 @@ import {
type SpreadsheetCells,
} from './spreadsheet-document';
import type { WorkbookSheetMetadata } from './workbook-metadata';
-import { changeWorkbookAxis } from './workbook-structure';
+import { changeWorkbookAxis, moveWorkbookRange } from './workbook-structure';
export type CalculatedCell = {
display: string;
@@ -84,6 +84,7 @@ export type SpreadsheetCalculator = {
context?: CalculationContext
) => CompletionContext;
changeAxis: typeof changeWorkbookAxis;
+ moveRange: typeof moveWorkbookRange;
/** An incremental calculation for a workbook that is edited repeatedly. */
session: () => WorkbookCalculationSession;
/**
@@ -1540,6 +1541,7 @@ export function createInitializedSpreadsheetCalculator(): SpreadsheetCalculator
return {
changeAxis: changeWorkbookAxis,
+ moveRange: moveWorkbookRange,
session() {
if (disposed) throw new Error('The spreadsheet calculator is disposed.');
return createWorkbookCalculationSession();
diff --git a/packages/spreadsheet/src/data-validation.ts b/packages/spreadsheet/src/data-validation.ts
index 57a42ba9a1..d2f2543513 100644
--- a/packages/spreadsheet/src/data-validation.ts
+++ b/packages/spreadsheet/src/data-validation.ts
@@ -1,11 +1,13 @@
import {
+ boundsSqref,
type DataValidation,
type DropdownColor,
MAX_SHEET_RULES,
sqrefBounds,
+ subtractBounds,
validDataValidation,
} from './sheet-rules';
-import { formatCellAddress, parseCellAddress } from './spreadsheet-document';
+import { parseCellAddress } from './spreadsheet-document';
/** Excel rejects a literal list longer than this, quotes included. */
export const MAX_LIST_FORMULA_LENGTH = 255;
@@ -131,8 +133,6 @@ export function dropdownRule(
};
}
-type Bounds = { top: number; left: number; bottom: number; right: number };
-
/** The rules covering any cell of `range`. */
export function overlappingValidations(
validations: DataValidation[] | undefined,
@@ -152,37 +152,6 @@ export function overlappingValidations(
);
}
-/** The parts of `area` outside `hole`. */
-function subtract(area: Bounds, hole: Bounds): Bounds[] {
- if (
- hole.top > area.bottom ||
- hole.bottom < area.top ||
- hole.left > area.right ||
- hole.right < area.left
- )
- return [area];
- const pieces: Bounds[] = [];
- const top = Math.max(area.top, hole.top);
- const bottom = Math.min(area.bottom, hole.bottom);
- if (area.top < hole.top) pieces.push({ ...area, bottom: hole.top - 1 });
- if (area.bottom > hole.bottom) pieces.push({ ...area, top: hole.bottom + 1 });
- if (area.left < hole.left)
- pieces.push({ top, bottom, left: area.left, right: hole.left - 1 });
- if (area.right > hole.right)
- pieces.push({ top, bottom, left: hole.right + 1, right: area.right });
- return pieces;
-}
-
-function sqrefOf(bounds: Bounds[]) {
- return bounds
- .map((area) => {
- const first = formatCellAddress(area.top, area.left);
- const last = formatCellAddress(area.bottom, area.right);
- return first === last ? first : `${first}:${last}`;
- })
- .join(' ');
-}
-
/**
* Validations with `range` taken out of every rule, then `rule` applied to
* it. A cell has one rule, so a new rule replaces those it overlaps; without
@@ -199,10 +168,10 @@ export function replaceValidations(
for (const existing of validations ?? []) {
let areas = sqrefBounds(existing.range);
for (const hole of holes)
- areas = areas.flatMap((area) => subtract(area, hole));
- if (areas.length) next.push({ ...existing, range: sqrefOf(areas) });
+ areas = areas.flatMap((area) => subtractBounds(area, hole));
+ if (areas.length) next.push({ ...existing, range: boundsSqref(areas) });
}
- if (rule) next.push({ ...rule, range: sqrefOf(holes) });
+ if (rule) next.push({ ...rule, range: boundsSqref(holes) });
if (next.length > MAX_SHEET_RULES)
throw new Error(
`A sheet can have at most ${MAX_SHEET_RULES} data validation rules.`
diff --git a/packages/spreadsheet/src/sheet-rules.ts b/packages/spreadsheet/src/sheet-rules.ts
index 60559c375a..6e2bee121d 100644
--- a/packages/spreadsheet/src/sheet-rules.ts
+++ b/packages/spreadsheet/src/sheet-rules.ts
@@ -1,4 +1,4 @@
-import { parseCellAddress } from './spreadsheet-document';
+import { formatCellAddress, parseCellAddress } from './spreadsheet-document';
/**
* Sheet rules imported from Excel and kept in sheet metadata: notes,
@@ -36,8 +36,47 @@ export function validSqref(value: unknown): value is string {
);
}
+export type CellBounds = {
+ top: number;
+ left: number;
+ bottom: number;
+ right: number;
+};
+
+/** The parts of `area` outside `hole`. */
+export function subtractBounds(area: CellBounds, hole: CellBounds) {
+ if (
+ hole.top > area.bottom ||
+ hole.bottom < area.top ||
+ hole.left > area.right ||
+ hole.right < area.left
+ )
+ return [area];
+ const pieces: CellBounds[] = [];
+ const top = Math.max(area.top, hole.top);
+ const bottom = Math.min(area.bottom, hole.bottom);
+ if (area.top < hole.top) pieces.push({ ...area, bottom: hole.top - 1 });
+ if (area.bottom > hole.bottom) pieces.push({ ...area, top: hole.bottom + 1 });
+ if (area.left < hole.left)
+ pieces.push({ top, bottom, left: area.left, right: hole.left - 1 });
+ if (area.right > hole.right)
+ pieces.push({ top, bottom, left: hole.right + 1, right: area.right });
+ return pieces;
+}
+
+/** A sqref of zero-based bounds. */
+export function boundsSqref(bounds: CellBounds[]) {
+ return bounds
+ .map((area) => {
+ const first = formatCellAddress(area.top, area.left);
+ const last = formatCellAddress(area.bottom, area.right);
+ return first === last ? first : `${first}:${last}`;
+ })
+ .join(' ');
+}
+
/** The ranges of a sqref, as zero-based bounds. */
-export function sqrefBounds(sqref: string) {
+export function sqrefBounds(sqref: string): CellBounds[] {
return sqref.split(' ').flatMap((range) => {
const [first, last = first] = range.split(':').map(parseCellAddress);
return first && last
diff --git a/packages/spreadsheet/src/workbook-structure.ts b/packages/spreadsheet/src/workbook-structure.ts
index f1f1980544..7cd7707f89 100644
--- a/packages/spreadsheet/src/workbook-structure.ts
+++ b/packages/spreadsheet/src/workbook-structure.ts
@@ -1,6 +1,13 @@
import { getTokens, Model } from '@ironcalc/wasm';
import { type DrawingPoint, isChartLiteral } from './sheet-drawings';
import {
+ boundsSqref,
+ type CellBounds,
+ sqrefBounds,
+ subtractBounds,
+} from './sheet-rules';
+import {
+ columnName,
formatCellAddress,
parseCellAddress,
SPREADSHEET_MAX_COLUMNS,
@@ -482,3 +489,277 @@ export function changeWorkbookAxis(
model.free();
}
}
+
+/** Cells dragged to another place on their sheet. */
+export type RangeMove = {
+ sheetId: string;
+ /** The zero-based cells that move. */
+ source: CellBounds;
+ /** How many rows and columns they move by. */
+ rows: number;
+ columns: number;
+};
+
+const containsBounds = (outer: CellBounds, inner: CellBounds) =>
+ inner.top >= outer.top &&
+ inner.bottom <= outer.bottom &&
+ inner.left >= outer.left &&
+ inner.right <= outer.right;
+
+const overlapBounds = (a: CellBounds, b: CellBounds): CellBounds[] => {
+ const overlap = {
+ top: Math.max(a.top, b.top),
+ left: Math.max(a.left, b.left),
+ bottom: Math.min(a.bottom, b.bottom),
+ right: Math.min(a.right, b.right),
+ };
+ return overlap.top <= overlap.bottom && overlap.left <= overlap.right
+ ? [overlap]
+ : [];
+};
+
+/**
+ * A formula whose references to the moved cells point at their new place, as
+ * after Excel's cut and paste. A range follows only when all of it moves;
+ * references to the cells the move replaces become #REF!.
+ */
+function movedReferences(
+ formula: string,
+ currentSheet: string,
+ move: { sheet: string; source: CellBounds; destination: CellBounds },
+ rows: number,
+ columns: number
+): string {
+ const characters = Array.from(formula);
+ let changed = false;
+ for (const { token, start, end } of getTokens(formula).reverse()) {
+ if (typeof token !== 'object') continue;
+ const reference =
+ 'Reference' in token
+ ? {
+ sheet: token.Reference.sheet,
+ left: token.Reference,
+ right: token.Reference,
+ }
+ : 'Range' in token
+ ? token.Range
+ : undefined;
+ if (
+ !reference ||
+ (reference.sheet ?? currentSheet).toLowerCase() !==
+ move.sheet.toLowerCase()
+ )
+ continue;
+ const { left, right } = reference;
+ const area = {
+ top: Math.min(left.row, right.row) - 1,
+ left: Math.min(left.column, right.column) - 1,
+ bottom: Math.max(left.row, right.row) - 1,
+ right: Math.max(left.column, right.column) - 1,
+ };
+ const text = characters.slice(start, end).join('');
+ const leading = text.match(/^\s*/)?.[0] ?? '';
+ const body = text.slice(leading.length);
+ const prefix = body.slice(0, body.lastIndexOf('!') + 1);
+ let replacement: string;
+ if (containsBounds(move.source, area)) {
+ const reference = body.slice(prefix.length);
+ const wholeRows = /^\$?\d+:\$?\d+$/.test(reference);
+ const wholeColumns = /^\$?[A-Z]+:\$?[A-Z]+$/i.test(reference);
+ const bound = (point: typeof left) => {
+ const row = `${point.absolute_row ? '$' : ''}${point.row + rows}`;
+ const column = `${point.absolute_column ? '$' : ''}${columnName(point.column - 1 + columns)}`;
+ return wholeRows ? row : wholeColumns ? column : `${column}${row}`;
+ };
+ replacement = `${prefix}${bound(left)}${'Range' in token ? `:${bound(right)}` : ''}`;
+ } else if (containsBounds(move.destination, area)) replacement = '#REF!';
+ else continue;
+ characters.splice(
+ start,
+ end - start,
+ ...Array.from(`${leading}${replacement}`)
+ );
+ changed = true;
+ }
+ return changed ? characters.join('') : formula;
+}
+
+/**
+ * Move a rectangle of cells to another place on its sheet, as Excel's cut and
+ * paste does. Values, formats, notes and data rules go with the cells and
+ * replace what was at the destination. References to the moved cells, from
+ * any sheet's formulas, rules, names, charts and pivot tables, follow them;
+ * references inside moved formulas keep pointing at the same cells.
+ */
+export function moveWorkbookRange(
+ sheets: SpreadsheetWorkbookSheet[],
+ move: RangeMove
+): SpreadsheetWorkbookSheet[] {
+ const { source, rows, columns } = move;
+ const destination = {
+ top: source.top + rows,
+ left: source.left + columns,
+ bottom: source.bottom + rows,
+ right: source.right + columns,
+ };
+ const target = sheets.findIndex((sheet) => sheet.id === move.sheetId);
+ if (
+ target < 0 ||
+ ![
+ source.top,
+ source.left,
+ source.bottom,
+ source.right,
+ rows,
+ columns,
+ ].every(Number.isInteger) ||
+ (!rows && !columns) ||
+ source.top < 0 ||
+ source.left < 0 ||
+ source.top > source.bottom ||
+ source.left > source.right ||
+ destination.top < 0 ||
+ destination.left < 0 ||
+ destination.bottom >= SPREADSHEET_MAX_ROWS ||
+ destination.right >= SPREADSHEET_MAX_COLUMNS
+ )
+ throw new Error('Invalid cell range.');
+ const { name: sheetName, layout } = sheets[target];
+ // Moving every row or column of the sheet's cells moves whole-row and
+ // whole-column references too.
+ const referenced = (area: CellBounds) => ({
+ ...area,
+ bottom:
+ source.top === 0 && source.bottom >= layout.rowCount - 1
+ ? Number.POSITIVE_INFINITY
+ : area.bottom,
+ right:
+ source.left === 0 && source.right >= layout.columnCount - 1
+ ? Number.POSITIVE_INFINITY
+ : area.right,
+ });
+ const rewrite = (formula: string, currentSheet: string) =>
+ movedReferences(
+ formula,
+ currentSheet,
+ {
+ sheet: sheetName,
+ source: referenced(source),
+ destination: referenced(destination),
+ },
+ rows,
+ columns
+ );
+ const shift = (area: CellBounds) => ({
+ top: area.top + rows,
+ left: area.left + columns,
+ bottom: area.bottom + rows,
+ right: area.right + columns,
+ });
+ /** Where a cell of the moved sheet goes; undefined once replaced. */
+ const place = (address: string) => {
+ const { row, column } = parseCellAddress(address)!;
+ const cell = { top: row, left: column, bottom: row, right: column };
+ if (containsBounds(source, cell))
+ return formatCellAddress(row + rows, column + columns);
+ return containsBounds(destination, cell) ? undefined : address;
+ };
+ /** Merges, arrays and pivot tables move whole or not at all. */
+ const placeRange = (range: string, name: string) => {
+ const [area] = sqrefBounds(range);
+ if (containsBounds(source, area)) return boundsSqref([shift(area)]);
+ if (containsBounds(destination, area)) return;
+ if (
+ overlapBounds(area, source).length ||
+ overlapBounds(area, destination).length
+ )
+ throw new Error(`This move would split ${name}.`);
+ return range;
+ };
+ /** A rule that only partly moves is split in two. */
+ const placeRules = <T extends { range: string }>(rules: T[]) =>
+ rules.flatMap((rule) => {
+ const areas = sqrefBounds(rule.range);
+ if (
+ !areas.some(
+ (area) =>
+ overlapBounds(area, source).length ||
+ overlapBounds(area, destination).length
+ )
+ )
+ return [rule];
+ const kept = areas
+ .flatMap((area) => subtractBounds(area, source))
+ .flatMap((area) => subtractBounds(area, destination));
+ const moved = areas
+ .flatMap((area) => overlapBounds(area, source))
+ .map(shift);
+ return [kept, moved]
+ .filter((part) => part.length)
+ .map((part) => ({ ...rule, range: boundsSqref(part) }));
+ });
+ /** The moved sheet's cell ranges, notes and rules after the move. */
+ const placeMetadata = (metadata: WorkbookSheetMetadata) => {
+ const result = { ...metadata };
+ if (result.merges)
+ result.merges = result.merges.flatMap(
+ (range) => placeRange(range, 'a merged cell') ?? []
+ );
+ if (result.arrayFormulas)
+ result.arrayFormulas = Object.fromEntries(
+ Object.values(result.arrayFormulas).flatMap((range) => {
+ const next = placeRange(range, 'an array formula');
+ return next ? [[next.split(':')[0], next]] : [];
+ })
+ );
+ if (result.pivotTables) {
+ result.pivotTables = result.pivotTables.flatMap((pivot) => {
+ const location = placeRange(pivot.location, 'a pivot table');
+ return location ? [{ ...pivot, location }] : [];
+ });
+ if (!result.pivotTables.length) delete result.pivotTables;
+ }
+ if (result.notes)
+ result.notes = Object.fromEntries(
+ Object.entries(result.notes).flatMap(([address, note]) => {
+ const next = place(address);
+ return next ? [[next, note]] : [];
+ })
+ );
+ if (result.validations) result.validations = placeRules(result.validations);
+ if (result.conditionalFormats)
+ result.conditionalFormats = placeRules(result.conditionalFormats);
+ return result;
+ };
+ return sheets.map((sheet, index) => {
+ const cells: SpreadsheetCells = {};
+ for (const [address, cell] of Object.entries(sheet.cells)) {
+ const next = index === target ? place(address) : address;
+ if (!next) continue;
+ const value =
+ cell.value.startsWith('=') && cell.format !== 'text'
+ ? rewrite(cell.value, sheet.name)
+ : cell.value;
+ cells[next] = value === cell.value ? cell : { ...cell, value };
+ }
+ const metadata =
+ sheet.metadata &&
+ withSheetFormulas(
+ sheet.metadata,
+ sheetFormulas(sheet.metadata).map((formula) =>
+ rewrite(formula, sheet.name)
+ )
+ );
+ if (index !== target) return { ...sheet, cells, metadata };
+ return {
+ ...sheet,
+ cells,
+ metadata: metadata && placeMetadata(metadata),
+ layout: {
+ ...sheet.layout,
+ rowCount: Math.max(sheet.layout.rowCount, destination.bottom + 1),
+ columnCount: Math.max(sheet.layout.columnCount, destination.right + 1),
+ },
+ };
+ });
+}