Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: add cut cells command (#7423) (#8019)

Charlie Giang08f05aaa2473
diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsx
index 033a238267..0e9db7ce7a 100644
--- a/frontend/src/components/editor/actions/useNotebookActions.tsx
+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx
@@ -53,6 +53,7 @@ import {
canUndoDeletesAtom,
getNotebook,
hasDisabledCellsAtom,
+ undoLabelAtom,
useCellActions,
} from "@/core/cells/cells";
import { disabledCellIds } from "@/core/cells/utils";
@@ -137,6 +138,7 @@ export function useNotebookActions() {
const hasDisabledCells = useAtomValue(hasDisabledCellsAtom);
const canUndoDeletes = useAtomValue(canUndoDeletesAtom);
+ const undoLabel = useAtomValue(undoLabelAtom);
const { selectedLayout } = useLayoutState();
const { setLayoutView } = useLayoutActions();
const togglePresenting = useTogglePresenting();
@@ -525,7 +527,7 @@ export function useNotebookActions() {
},
{
icon: <Undo2Icon size={14} strokeWidth={1.5} />,
- label: "Undo cell deletion",
+ label: undoLabel,
hidden: !canUndoDeletes || kioskMode,
handle: () => {
undoDeleteCell();
diff --git a/frontend/src/components/editor/controls/Controls.tsx b/frontend/src/components/editor/controls/Controls.tsx
index 0ea8219fac..023146bdc2 100644
--- a/frontend/src/components/editor/controls/Controls.tsx
+++ b/frontend/src/components/editor/controls/Controls.tsx
@@ -27,6 +27,7 @@ import { Functions } from "@/utils/functions";
import {
canUndoDeletesAtom,
needsRunAtom,
+ undoLabelAtom,
useCellActions,
} from "../../../core/cells/cells";
import { ConfigButton } from "../../app-config/app-config-button";
@@ -56,6 +57,7 @@ export const Controls = ({
running,
}: ControlsProps): JSX.Element => {
const undoAvailable = useAtomValue(canUndoDeletesAtom);
+ const undoLabel = useAtomValue(undoLabelAtom);
const needsRun = useAtomValue(needsRunAtom);
const { undoDeleteCell } = useCellActions();
const closed = connectionState === WebSocketState.CLOSED;
@@ -63,7 +65,7 @@ export const Controls = ({
let undoControl: JSX.Element | null = null;
if (!closed && undoAvailable) {
undoControl = (
- <Tooltip content="Undo cell deletion">
+ <Tooltip content={undoLabel}>
<Button
data-testid="undo-delete-cell"
size="medium"
diff --git a/frontend/src/components/editor/navigation/__tests__/clipboard.test.ts b/frontend/src/components/editor/navigation/__tests__/clipboard.test.ts
index 560f7f7cbd..7bcba3c114 100644
--- a/frontend/src/components/editor/navigation/__tests__/clipboard.test.ts
+++ b/frontend/src/components/editor/navigation/__tests__/clipboard.test.ts
@@ -20,6 +20,18 @@ vi.mock("@/utils/Logger", () => ({
Logger: Mocks.quietLogger(),
}));
+const mockClearPendingCut = vi.hoisted(() => vi.fn());
+vi.mock("@/core/cells/pending-cut-service", () => ({
+ usePendingCutActions: () => ({
+ markForCut: vi.fn(),
+ clear: mockClearPendingCut,
+ }),
+ usePendingCutState: () => ({
+ cellIds: new Set(),
+ clipboardData: null,
+ }),
+}));
+
import { MockNotebook } from "@/__mocks__/notebook";
import { toast } from "@/components/ui/use-toast";
import { getNotebook, useCellActions } from "@/core/cells/cells";
@@ -198,6 +210,101 @@ describe("useCellClipboard", () => {
description: "Cell has been copied to clipboard.",
});
});
+
+ it("should clear pending cut when copy succeeds", async () => {
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.copyCells([mockCellId1]);
+ });
+
+ expect(mockClearPendingCut).toHaveBeenCalled();
+ });
+
+ it("should clear pending cut when copy falls back to writeText", async () => {
+ mockClipboard.write.mockRejectedValue(new Error("Write failed"));
+ mockClipboard.writeText.mockResolvedValue(undefined);
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.copyCells([mockCellId1]);
+ });
+
+ expect(mockClearPendingCut).toHaveBeenCalled();
+ });
+ });
+
+ describe("cutCells", () => {
+ it("should cut single cell to clipboard with custom mimetype and plain text", async () => {
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.cutCells([mockCellId1]);
+ });
+
+ expect(mockClipboard.write).toHaveBeenCalledWith([
+ expect.objectContaining({
+ types: ["web application/x-marimo-cell", "text/plain"],
+ }),
+ ]);
+ });
+
+ it("should cut multiple cells to clipboard with custom mimetype and plain text", async () => {
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.cutCells([mockCellId1, mockCellId2]);
+ });
+
+ expect(mockClipboard.write).toHaveBeenCalledWith([
+ expect.objectContaining({
+ types: ["web application/x-marimo-cell", "text/plain"],
+ }),
+ ]);
+ });
+
+ it("should not write when no cells found", async () => {
+ asMock(getNotebook).mockReturnValue(MockNotebook.notebookState());
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.cutCells([mockCellId1]);
+ });
+
+ expect(mockClipboard.write).not.toHaveBeenCalled();
+ });
+
+ it("should fallback to writeText when clipboard.write fails", async () => {
+ mockClipboard.write.mockRejectedValue(new Error("Write failed"));
+ mockClipboard.writeText.mockResolvedValue(undefined);
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.cutCells([mockCellId1]);
+ });
+
+ expect(mockClipboard.write).toHaveBeenCalled();
+ expect(mockClipboard.writeText).toHaveBeenCalledWith(mockCellCode1);
+ });
+
+ it("should show error toast when both clipboard methods fail", async () => {
+ mockClipboard.write.mockRejectedValue(new Error("Write failed"));
+ mockClipboard.writeText.mockRejectedValue(new Error("WriteText failed"));
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.cutCells([mockCellId1]);
+ });
+
+ expect(Logger.error).toHaveBeenCalledWith(
+ "Failed to cut cells to clipboard",
+ expect.any(Error),
+ );
+ });
});
describe("pasteCell", () => {
diff --git a/frontend/src/components/editor/navigation/__tests__/navigation.test.ts b/frontend/src/components/editor/navigation/__tests__/navigation.test.ts
index abe8ba6ed1..a2aefb6a61 100644
--- a/frontend/src/components/editor/navigation/__tests__/navigation.test.ts
+++ b/frontend/src/components/editor/navigation/__tests__/navigation.test.ts
@@ -44,6 +44,11 @@ vi.mock("../../cell/useRunCells", () => ({
useRunCells: vi.fn(),
}));
+vi.mock("../../cell/useDeleteCell", () => ({
+ useDeleteCellCallback: vi.fn(),
+ useDeleteManyCellsCallback: vi.fn(),
+}));
+
vi.mock("../clipboard", () => ({
useCellClipboard: vi.fn(),
}));
@@ -112,6 +117,7 @@ const mockSaveIfNotebookIsPersistent = vi.fn();
const mockSaveNotebook = vi.fn();
const mockRunCell = vi.fn();
const mockCopyCell = vi.fn();
+const mockCutCell = vi.fn().mockResolvedValue(undefined);
const mockPasteCell = vi.fn();
const mockCellActions = MockNotebook.cellActions({
@@ -165,7 +171,9 @@ describe("useCellNavigationProps", () => {
mockUseRunCells.mockReturnValue(mockRunCell);
mockUseCellClipboard.mockReturnValue({
copyCells: mockCopyCell,
+ cutCells: mockCutCell,
pasteAtCell: mockPasteCell,
+ clearPendingCut: vi.fn(),
});
// Setup default config in store
@@ -237,6 +245,45 @@ describe("useCellNavigationProps", () => {
expect(mockEvent.preventDefault).toHaveBeenCalled();
});
+ it("should cut cell when 'x' key is pressed", async () => {
+ const { result } = renderWithProvider(() =>
+ useCellNavigationProps(mockCellId, options),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({ key: "x" });
+
+ await act(async () => {
+ result.current.onKeyDown?.(mockEvent);
+ await Promise.resolve();
+ });
+
+ expect(mockCutCell).toHaveBeenCalledWith([mockCellId]);
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ });
+
+ it("should cut multiple selected cells when 'x' key is pressed", async () => {
+ const selectionActions = setupSelection();
+ selectionActions.select({ cellId: cellId1 });
+ selectionActions.extend({
+ cellId: cellId2,
+ allCellIds: store.get(notebookAtom).cellIds,
+ });
+
+ const { result } = renderWithProvider(() =>
+ useCellNavigationProps(cellId1, options),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({ key: "x" });
+
+ await act(async () => {
+ result.current.onKeyDown?.(mockEvent);
+ await Promise.resolve();
+ });
+
+ expect(mockCutCell).toHaveBeenCalledWith([cellId1, cellId2]);
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ });
+
it("should paste cell when 'v' key is pressed", () => {
const { result } = renderWithProvider(() =>
useCellNavigationProps(mockCellId, options),
@@ -775,6 +822,29 @@ describe("useCellNavigationProps", () => {
expect(mockEvent.preventDefault).toHaveBeenCalled();
});
+ it("should cut multiple cells when multiple cells selected", () => {
+ // Set up selection of multiple cells
+ const selectionActions = setupSelection();
+ selectionActions.select({ cellId: cellId1 });
+ selectionActions.extend({
+ cellId: cellId3,
+ allCellIds: store.get(notebookAtom).cellIds,
+ });
+
+ const { result } = renderWithProvider(() =>
+ useCellNavigationProps(cellId2, options),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({ key: "x" });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockCutCell).toHaveBeenCalledWith([cellId1, cellId2, cellId3]);
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ });
+
it("should move multiple cells up when multiple cells selected", () => {
// Set up selection of multiple cells
const selectionActions = setupSelection();
diff --git a/frontend/src/components/editor/navigation/clipboard.ts b/frontend/src/components/editor/navigation/clipboard.ts
index b091a15b36..f49e65903d 100644
--- a/frontend/src/components/editor/navigation/clipboard.ts
+++ b/frontend/src/components/editor/navigation/clipboard.ts
@@ -5,15 +5,22 @@ import { z } from "zod";
import { toast } from "@/components/ui/use-toast";
import { getNotebook, useCellActions } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
+import {
+ usePendingCutActions,
+ usePendingCutState,
+} from "@/core/cells/pending-cut-service";
+import type { CellConfig } from "@/core/network/types";
import { copyToClipboard } from "@/utils/copy";
import { Logger } from "@/utils/Logger";
// According to MDN, custom mimetypes should start with "web "
const MARIMO_CELL_MIMETYPE = "web application/x-marimo-cell";
-interface ClipboardCellData {
+export interface ClipboardCellData {
cells: {
code: string;
+ name?: string;
+ config?: CellConfig;
}[];
version: "1.0";
}
@@ -22,19 +29,49 @@ const ClipboardCellDataSchema = z.object({
cells: z.array(
z.object({
code: z.string(),
+ name: z.string().optional(),
+ config: z
+ .object({
+ column: z.union([z.number(), z.null()]).optional(),
+ disabled: z.boolean().optional(),
+ hide_code: z.boolean().optional(),
+ })
+ .optional(),
}),
),
version: z.literal("1.0"),
});
-// NOTE: We don't support Cut yet. We can wait for feedback before implementing.
-// It is a bit more complex as will need to:
-// - include id, outputs, and name
-// - delete the existing cell, but don't place on the undo stack
-// - don't want to invalidate downstream cells
+function buildClipboardPayload(
+ cells: Array<{ code: string; name?: string; config?: CellConfig }>,
+): { clipboardData: ClipboardCellData; plainText: string } {
+ const clipboardData: ClipboardCellData = {
+ cells: cells.map((cell) => ({
+ code: cell.code,
+ name: cell.name,
+ config: cell.config,
+ })),
+ version: "1.0",
+ };
+ const plainText = cells.map((cell) => cell.code).join("\n\n");
+ return { clipboardData, plainText };
+}
+
+async function writeCellsToClipboard(
+ clipboardData: ClipboardCellData,
+ plainText: string,
+): Promise<void> {
+ const clipboardItem = new ClipboardItemBuilder()
+ .add(MARIMO_CELL_MIMETYPE, clipboardData)
+ .add("text/plain", plainText)
+ .build();
+ await navigator.clipboard.write([clipboardItem]);
+}
export function useCellClipboard() {
const actions = useCellActions();
+ const pendingCutActions = usePendingCutActions();
+ const pendingCutState = usePendingCutState();
const copyCells = useEvent(async (cellIds: CellId[]) => {
const notebook = getNotebook();
@@ -47,31 +84,19 @@ export function useCellClipboard() {
return;
}
- try {
- const clipboardData: ClipboardCellData = {
- cells: cells.map((cell) => ({ code: cell.code })),
- version: "1.0",
- };
-
- // Create plain text representation (joined by newlines)
- const plainText = cells.map((cell) => cell.code).join("\n\n");
-
- // Create clipboard item with both custom mimetype and plain text
- const clipboardItem = new ClipboardItemBuilder()
- .add(MARIMO_CELL_MIMETYPE, clipboardData)
- .add("text/plain", plainText)
- .build();
-
- await navigator.clipboard.write([clipboardItem]);
+ const { clipboardData, plainText } = buildClipboardPayload(cells);
+ try {
+ await writeCellsToClipboard(clipboardData, plainText);
+ pendingCutActions.clear();
toastSuccess(cells.length);
} catch (error) {
Logger.error("Failed to copy cells to clipboard", error);
// Fallback to simple text copy
try {
- const plainText = cells.map((cell) => cell.code).join("\n\n");
await copyToClipboard(plainText);
+ pendingCutActions.clear();
toastSuccess(cells.length);
} catch {
toastError();
@@ -79,12 +104,60 @@ export function useCellClipboard() {
}
});
+ const cutCells = useEvent(async (cellIds: CellId[]) => {
+ const notebook = getNotebook();
+ const validCellIds = cellIds.filter((cellId) => notebook.cellData[cellId]);
+ const cells = validCellIds.map((cellId) => notebook.cellData[cellId]);
+
+ if (cells.length === 0) {
+ // No cells to cut
+ return;
+ }
+
+ const { clipboardData, plainText } = buildClipboardPayload(cells);
+
+ try {
+ await writeCellsToClipboard(clipboardData, plainText);
+ pendingCutActions.markForCut({ cellIds: validCellIds, clipboardData });
+ } catch (error) {
+ Logger.error("Failed to cut cells to clipboard", error);
+ try {
+ await copyToClipboard(plainText);
+ // Mark cells as pending cut instead of deleting immediately
+ pendingCutActions.markForCut({ cellIds: validCellIds, clipboardData });
+ } catch {
+ toastError();
+ }
+ }
+ });
+
interface PasteOptions {
before?: boolean;
}
const pasteAtCell = useEvent(async (cellId: CellId, opts?: PasteOptions) => {
const { before = false } = opts ?? {};
+
+ // Check if we have pending cut cells (internal move)
+ if (pendingCutState.cellIds.size > 0) {
+ const pendingCellIds = [...pendingCutState.cellIds];
+ const notebook = getNotebook();
+ const previousPlacements = pendingCellIds.map((id) => {
+ const column = notebook.cellIds.findWithId(id);
+ return { columnId: column.id, index: column.indexOfOrThrow(id) };
+ });
+
+ actions.moveCellsRelativeTo({
+ cellIds: pendingCellIds,
+ targetCellId: cellId,
+ position: before ? "before" : "after",
+ previousPlacements,
+ });
+
+ pendingCutActions.clear();
+ return;
+ }
+
try {
const clipboardItems = await navigator.clipboard.read();
@@ -112,6 +185,9 @@ export function useCellClipboard() {
cellId: currentCellId,
before,
code: cell.code,
+ name: cell.name,
+ config: cell.config,
+ hideCode: cell.config?.hide_code,
autoFocus: true,
});
}
@@ -143,7 +219,9 @@ export function useCellClipboard() {
return {
copyCells,
+ cutCells,
pasteAtCell,
+ clearPendingCut: pendingCutActions.clear,
};
}
diff --git a/frontend/src/components/editor/navigation/navigation.ts b/frontend/src/components/editor/navigation/navigation.ts
index be8fbb33a2..a9cb330610 100644
--- a/frontend/src/components/editor/navigation/navigation.ts
+++ b/frontend/src/components/editor/navigation/navigation.ts
@@ -16,6 +16,10 @@ import { cellIdsAtom, notebookAtom, useCellActions } from "@/core/cells/cells";
import { useCellFocusActions } from "@/core/cells/focus";
import type { CellId } from "@/core/cells/ids";
import { HTMLCellId } from "@/core/cells/ids";
+import {
+ clearPendingCutAtom,
+ pendingCutCellIdsAtom,
+} from "@/core/cells/pending-cut-service";
import { usePendingDeleteService } from "@/core/cells/pending-delete-service";
import { scrollCellIntoView } from "@/core/cells/scrollCellIntoView";
import {
@@ -185,7 +189,7 @@ export function useCellNavigationProps(
const temporarilyShownCodeActions = useTemporarilyShownCodeActions();
const runCells = useRunCells();
const keymapPreset = useAtomValue(keymapPresetAtom);
- const { copyCells, pasteAtCell } = useCellClipboard();
+ const { copyCells, pasteAtCell, cutCells } = useCellClipboard();
const rawSelectionActions = useCellSelectionActions();
const isSelected = useIsCellSelected(cellId);
const pendingDeleteService = usePendingDeleteService();
@@ -317,6 +321,12 @@ export function useCellNavigationProps(
},
// Clear selection
Escape: () => {
+ // Clear pending cut state if any
+ const pendingCutCellIds = store.get(pendingCutCellIdsAtom);
+ if (pendingCutCellIds.size > 0) {
+ store.set(clearPendingCutAtom);
+ return true;
+ }
if (isSelected) {
selectionActions.clear();
return true;
@@ -510,6 +520,10 @@ export function useCellNavigationProps(
copyCells(cellIds);
return true;
}),
+ "command.cutCell": addSingleHandler((cellIds) => {
+ cutCells(cellIds);
+ return true;
+ }),
"command.pasteCell": (cellIds) => {
pasteAtCell(cellIds);
return true;
diff --git a/frontend/src/components/editor/notebook-cell.tsx b/frontend/src/components/editor/notebook-cell.tsx
index 7767275e17..0c556798bf 100644
--- a/frontend/src/components/editor/notebook-cell.tsx
+++ b/frontend/src/components/editor/notebook-cell.tsx
@@ -27,6 +27,7 @@ import { Tooltip, TooltipProvider } from "@/components/ui/tooltip";
import { aiCompletionCellAtom } from "@/core/ai/state";
import { outputIsLoading, outputIsStale } from "@/core/cells/cell";
import { isOutputEmpty } from "@/core/cells/outputs";
+import { useIsPendingCut } from "@/core/cells/pending-cut-service";
import { autocompletionKeymap } from "@/core/codemirror/cm";
import type { LanguageAdapterType } from "@/core/codemirror/language/types";
import { CSSClasses } from "@/core/constants";
@@ -391,6 +392,7 @@ const EditableCellComponent = ({
const deleteCell = useDeleteCellCallback();
const runCell = useRunCell(cellId);
const { sendStdin } = useRequestClient();
+ const isPendingCut = useIsPendingCut(cellId);
const [languageAdapter, setLanguageAdapter] = useState<LanguageAdapterType>();
@@ -545,6 +547,7 @@ const EditableCellComponent = ({
}),
borderless:
isMarkdownCodeHidden && hasOutput && !navigationProps["data-selected"],
+ "pending-cut": isPendingCut,
});
const handleRefactorWithAI: OnRefactorWithAI = useEvent(
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.ts
index 0b14a6789b..0be339aa95 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -212,6 +212,20 @@ describe("cell reducer", () => {
`);
});
+ it("can add a cell with name and config", () => {
+ actions.createNewCell({
+ cellId: firstCellId,
+ before: false,
+ code: "x = 1",
+ name: "My Cell",
+ config: { hide_code: true, disabled: false },
+ });
+ const newCellId = state.cellIds.inOrderIds[1];
+ expect(state.cellData[newCellId].name).toBe("My Cell");
+ expect(state.cellData[newCellId].config.hide_code).toBe(true);
+ expect(state.cellData[newCellId].config.disabled).toBe(false);
+ });
+
it("can delete a Python cell and undo delete", () => {
actions.createNewCell({
cellId: firstCellId,
@@ -602,6 +616,179 @@ describe("cell reducer", () => {
expect(formatCells(state)).toBe(before);
});
+ it("can move multiple cells relative to target", () => {
+ actions.createNewCell({
+ cellId: firstCellId,
+ before: false,
+ });
+ actions.createNewCell({
+ cellId: "1" as CellId,
+ before: false,
+ });
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ [0] ''
+
+ [1] ''
+
+ [2] ''
+ "
+ `);
+
+ // Move first two cells after the third
+ actions.moveCellsRelativeTo({
+ cellIds: [firstCellId, "1" as CellId],
+ targetCellId: "2" as CellId,
+ position: "after",
+ });
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ [2] ''
+
+ [0] ''
+
+ [1] ''
+ "
+ `);
+ });
+
+ it("can undo cut-paste (move with previousPlacements)", () => {
+ actions.createNewCell({
+ cellId: firstCellId,
+ before: false,
+ });
+ actions.createNewCell({
+ cellId: "1" as CellId,
+ before: false,
+ });
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ [0] ''
+
+ [1] ''
+
+ [2] ''
+ "
+ `);
+
+ const col = state.cellIds.findWithId(firstCellId);
+ const previousPlacements = [
+ {
+ columnId: col.id,
+ index: col.indexOfOrThrow(
+ firstCellId,
+ ) as import("@/utils/id-tree").CellIndex,
+ },
+ {
+ columnId: col.id,
+ index: col.indexOfOrThrow(
+ "1" as CellId,
+ ) as import("@/utils/id-tree").CellIndex,
+ },
+ ];
+
+ actions.moveCellsRelativeTo({
+ cellIds: [firstCellId, "1" as CellId],
+ targetCellId: "2" as CellId,
+ position: "after",
+ previousPlacements,
+ });
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ [2] ''
+
+ [0] ''
+
+ [1] ''
+ "
+ `);
+
+ actions.undoDeleteCell();
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ [0] ''
+
+ [1] ''
+
+ [2] ''
+ "
+ `);
+ });
+
+ it("undo order: cut-paste then delete — first undo restores delete, second undo undoes move", () => {
+ actions.createNewCell({
+ cellId: firstCellId,
+ before: false,
+ });
+ actions.createNewCell({
+ cellId: "1" as CellId,
+ before: false,
+ });
+
+ const col = state.cellIds.findWithId(firstCellId);
+ const previousPlacements = [
+ {
+ columnId: col.id,
+ index: col.indexOfOrThrow(
+ firstCellId,
+ ) as import("@/utils/id-tree").CellIndex,
+ },
+ {
+ columnId: col.id,
+ index: col.indexOfOrThrow(
+ "1" as CellId,
+ ) as import("@/utils/id-tree").CellIndex,
+ },
+ ];
+
+ actions.moveCellsRelativeTo({
+ cellIds: [firstCellId, "1" as CellId],
+ targetCellId: "2" as CellId,
+ position: "after",
+ previousPlacements,
+ });
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ [2] ''
+
+ [0] ''
+
+ [1] ''
+ "
+ `);
+
+ actions.deleteCell({ cellId: "2" as CellId });
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ [0] ''
+
+ [1] ''
+ "
+ `);
+
+ actions.undoDeleteCell();
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ [3] ''
+
+ [0] ''
+
+ [1] ''
+ "
+ `);
+
+ actions.undoDeleteCell();
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ [0] ''
+
+ [1] ''
+
+ [3] ''
+ "
+ `);
+ });
+
it("can run cell and receive cell messages", () => {
// HAPPY PATH
/////////////////
diff --git a/frontend/src/core/cells/__tests__/pending-cut-service.test.tsx b/frontend/src/core/cells/__tests__/pending-cut-service.test.tsx
new file mode 100644
index 0000000000..1d29398990
--- /dev/null
+++ b/frontend/src/core/cells/__tests__/pending-cut-service.test.tsx
@@ -0,0 +1,145 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { act, renderHook } from "@testing-library/react";
+import { createStore, Provider } from "jotai";
+import { describe, expect, it } from "vitest";
+import type { CellId } from "@/core/cells/ids";
+import {
+ pendingCutStateAtom,
+ useHasPendingCut,
+ useIsPendingCut,
+ usePendingCutActions,
+ usePendingCutState,
+} from "../pending-cut-service";
+
+function createTestWrapper() {
+ const store = createStore();
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <Provider store={store}>{children}</Provider>
+ );
+ return { wrapper, store };
+}
+
+const mockClipboardData = {
+ cells: [{ code: "x = 1", name: "cell1" }],
+ version: "1.0" as const,
+};
+
+describe("pending-cut-service", () => {
+ it("markForCut sets cellIds and clipboardData", () => {
+ const { wrapper, store } = createTestWrapper();
+ const cellIds: CellId[] = ["cell-1" as CellId, "cell-2" as CellId];
+
+ const { result } = renderHook(
+ () => ({
+ actions: usePendingCutActions(),
+ state: usePendingCutState(),
+ }),
+ { wrapper },
+ );
+
+ act(() => {
+ result.current.actions.markForCut({
+ cellIds,
+ clipboardData: mockClipboardData,
+ });
+ });
+
+ const state = store.get(pendingCutStateAtom);
+ expect(state.cellIds).toEqual(new Set(cellIds));
+ expect(state.clipboardData).toEqual(mockClipboardData);
+ });
+
+ it("clear resets to initial state", () => {
+ const { wrapper, store } = createTestWrapper();
+ const cellIds: CellId[] = ["cell-1" as CellId];
+
+ const { result } = renderHook(
+ () => ({
+ actions: usePendingCutActions(),
+ state: usePendingCutState(),
+ }),
+ { wrapper },
+ );
+
+ act(() => {
+ result.current.actions.markForCut({
+ cellIds,
+ clipboardData: mockClipboardData,
+ });
+ });
+ expect(store.get(pendingCutStateAtom).cellIds.size).toBe(1);
+
+ act(() => {
+ result.current.actions.clear();
+ });
+ const state = store.get(pendingCutStateAtom);
+ expect(state.cellIds.size).toBe(0);
+ expect(state.clipboardData).toBeNull();
+ });
+
+ it("useIsPendingCut returns true when cellId is marked for cut", () => {
+ const { wrapper } = createTestWrapper();
+ const cellId = "cell-1" as CellId;
+
+ const { result: actionsResult } = renderHook(() => usePendingCutActions(), {
+ wrapper,
+ });
+ const { result: isPendingResult } = renderHook(
+ () => useIsPendingCut(cellId),
+ { wrapper },
+ );
+
+ expect(isPendingResult.current).toBe(false);
+
+ act(() => {
+ actionsResult.current.markForCut({
+ cellIds: [cellId],
+ clipboardData: mockClipboardData,
+ });
+ });
+
+ expect(isPendingResult.current).toBe(true);
+ });
+
+ it("useIsPendingCut returns false when cellId is not marked for cut", () => {
+ const { wrapper } = createTestWrapper();
+ const { result } = renderHook(
+ () => useIsPendingCut("other-cell" as CellId),
+ { wrapper },
+ );
+
+ const { result: actionsResult } = renderHook(() => usePendingCutActions(), {
+ wrapper,
+ });
+ act(() => {
+ actionsResult.current.markForCut({
+ cellIds: ["cell-1" as CellId],
+ clipboardData: mockClipboardData,
+ });
+ });
+
+ expect(result.current).toBe(false);
+ });
+
+ it("useHasPendingCut returns true when any cells are marked for cut", () => {
+ const { wrapper } = createTestWrapper();
+ const { result: hasPendingResult } = renderHook(() => useHasPendingCut(), {
+ wrapper,
+ });
+ const { result: actionsResult } = renderHook(() => usePendingCutActions(), {
+ wrapper,
+ });
+
+ expect(hasPendingResult.current).toBe(false);
+
+ act(() => {
+ actionsResult.current.markForCut({
+ cellIds: ["cell-1" as CellId],
+ clipboardData: mockClipboardData,
+ });
+ });
+
+ expect(hasPendingResult.current).toBe(true);
+ });
+});
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 73f233acb5..cb9e407a15 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -23,6 +23,7 @@ import {
splitEditor,
updateEditorCodeFromPython,
} from "../codemirror/language/utils";
+import type { SerializedEditorState } from "../codemirror/types";
import { findCollapseRange, mergeOutlines } from "../dom/outline";
import type { CellMessage } from "../kernel/messages";
import { isErrorMime } from "../mime";
@@ -50,11 +51,36 @@ import {
canUndoDeletes,
disabledCellIds,
enabledCellIds,
+ getUndoLabel,
notebookIsRunning,
notebookNeedsRun,
notebookQueueOrRunningCount,
} from "./utils";
+/**
+ * History entry for undoing a cell deletion.
+ */
+export interface UndoDeleteEntry {
+ type: "delete";
+ name: string;
+ serializedEditorState: SerializedEditorState;
+ column: CellColumnId;
+ index: CellIndex;
+ isSetupCell: boolean;
+ config: CellConfig;
+}
+
+/**
+ * History entry for undoing a cut-paste (move).
+ */
+export interface UndoMoveEntry {
+ type: "move";
+ cellIds: CellId[];
+ placements: Array<{ columnId: CellColumnId; index: CellIndex }>;
+}
+
+export type HistoryEntry = UndoDeleteEntry | UndoMoveEntry;
+
/**
* The state of the notebook.
*/
@@ -76,19 +102,9 @@ export interface NotebookState {
*/
cellHandles: Record<CellId, React.RefObject<CellHandle | null>>;
/**
- * Array of deleted cells (with their data and index) so that cell deletion can be undone
- *
- * (CodeMirror types the serialized config as any.)
+ * Undo stack: deleted cells and cut-paste moves, in chronological order.
*/
- history: {
- name: string;
- // oxlint-disable-next-line typescript/no-explicit-any
- serializedEditorState: any;
- column: CellColumnId;
- index: CellIndex;
- isSetupCell: boolean;
- config: CellConfig;
- }[];
+ history: HistoryEntry[];
/**
* Key of cell to scroll to; typically set by actions that re-order the cell
* array. Call the SCROLL_TO_TARGET action to scroll to the specified cell
@@ -158,6 +174,10 @@ export interface CreateNewCellAction {
before: boolean;
/** Initial code content for the new cell */
code?: string;
+ /** Optional name for the new cell */
+ name?: string;
+ /** Optional cell configuration */
+ config?: CellConfig;
/** The last executed code for the new cell */
lastCodeRun?: string;
/** Timestamp of the last execution */
@@ -187,11 +207,13 @@ const {
cellId,
before,
code,
+ name,
+ config,
lastCodeRun = null,
lastExecutionTime = null,
autoFocus = true,
skipIfCodeExists = false,
- hideCode = false,
+ hideCode = undefined,
} = action;
let columnId: CellColumnId;
@@ -234,8 +256,12 @@ const {
[newCellId]: createCell({
id: newCellId,
code,
+ name,
lastCodeRun,
- config: createCellConfig({ hide_code: hideCode }),
+ config: createCellConfig({
+ ...config,
+ ...(hideCode != null && { hide_code: hideCode }),
+ }),
lastExecutionTime,
edited: Boolean(code) && code !== lastCodeRun,
}),
@@ -417,6 +443,40 @@ const {
scrollKey: null,
};
},
+ moveCellsRelativeTo: (
+ state,
+ action: {
+ cellIds: CellId[];
+ targetCellId: CellId;
+ position: "before" | "after";
+ previousPlacements?: Array<{ columnId: CellColumnId; index: CellIndex }>;
+ },
+ ) => {
+ const { cellIds, targetCellId, position, previousPlacements } = action;
+ if (cellIds.length === 0) {
+ return state;
+ }
+ const newCellIds = state.cellIds.moveCellsRelativeTo(
+ cellIds,
+ targetCellId,
+ position,
+ );
+ // Only record undo when caller provided full before-state
+ const canUndoMove =
+ previousPlacements && previousPlacements.length === cellIds.length;
+ const history = canUndoMove
+ ? [
+ ...state.history,
+ { type: "move" as const, cellIds, placements: previousPlacements },
+ ]
+ : state.history;
+ return {
+ ...state,
+ cellIds: newCellIds,
+ history,
+ scrollKey: null,
+ };
+ },
dropCellOverColumn: (
state,
action: { cellId: CellId; columnId: CellColumnId },
@@ -659,6 +719,7 @@ const {
history: [
...state.history,
{
+ type: "delete",
name: prevData.name,
serializedEditorState: serializedEditorState,
column: column.id,
@@ -675,7 +736,29 @@ const {
return state;
}
- const mostRecentlyDeleted = state.history[state.history.length - 1];
+ const last = state.history[state.history.length - 1];
+
+ if (last.type === "move") {
+ const { cellIds, placements } = last;
+ if (
+ cellIds.length === 0 ||
+ placements.length !== cellIds.length ||
+ cellIds.some((id) => !state.cellData[id])
+ ) {
+ return { ...state, history: state.history.slice(0, -1) };
+ }
+ const toRestore = cellIds.map((id, i) => ({
+ id,
+ columnId: placements[i].columnId,
+ index: placements[i].index,
+ }));
+ return {
+ ...state,
+ cellIds: state.cellIds.placeCells(toRestore),
+ history: state.history.slice(0, -1),
+ scrollKey: cellIds[0] ?? null,
+ };
+ }
const {
name,
@@ -684,7 +767,7 @@ const {
index,
isSetupCell,
config,
- } = mostRecentlyDeleted;
+ } = last;
const cellId = isSetupCell ? SETUP_CELL_ID : CellId.create();
const undoCell = createCell({
@@ -790,7 +873,7 @@ const {
cellReducer: (cell) => {
return {
...cell,
- config: { ...cell.config, ...config },
+ config: createCellConfig({ ...cell.config, ...config }),
};
},
});
@@ -1633,6 +1716,8 @@ export const canUndoDeletesAtom = atom((get) =>
canUndoDeletes(get(notebookAtom)),
);
+export const undoLabelAtom = atom((get) => getUndoLabel(get(notebookAtom)));
+
export const needsRunAtom = atom((get) => notebookNeedsRun(get(notebookAtom)));
export const cellErrorsAtom = atom((get) => {
diff --git a/frontend/src/core/cells/document-changes.ts b/frontend/src/core/cells/document-changes.ts
index 993b096c5e..dbd79cb26f 100644
--- a/frontend/src/core/cells/document-changes.ts
+++ b/frontend/src/core/cells/document-changes.ts
@@ -218,13 +218,14 @@ export function toDocumentChanges(
];
}
- // dropCellOverCell/dropCellOverColumn/moveCellToIndex → set-config + reorder-cells
+ // dropCellOverCell/dropCellOverColumn/moveCellToIndex/moveCellsRelativeTo → set-config + reorder-cells
// Drag-and-drop reorders can move cells within or across columns.
// We emit config changes for cells whose column changed, then
// the full ordering.
case "dropCellOverCell":
case "dropCellOverColumn":
case "moveCellToIndex":
+ case "moveCellsRelativeTo":
return columnChanges(prevState, newState);
// updateCellCode → set-code
@@ -302,6 +303,10 @@ export function toDocumentChanges(
case "undoDeleteCell": {
const changes = newCellChanges(prevState, newState);
const colChanges = columnChanges(prevState, newState);
+ // Undo-cut has no new cells — always emit reorder to sync the move.
+ if (changes.length === 0) {
+ return colChanges;
+ }
// Only include column changes if layout actually changed
// (colChanges always has at least a reorder-cells change)
return colChanges.length > 1 ? [...changes, ...colChanges] : changes;
diff --git a/frontend/src/core/cells/pending-cut-service.ts b/frontend/src/core/cells/pending-cut-service.ts
new file mode 100644
index 0000000000..90d25209c5
--- /dev/null
+++ b/frontend/src/core/cells/pending-cut-service.ts
@@ -0,0 +1,64 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { atom, useAtomValue } from "jotai";
+import type { ClipboardCellData } from "@/components/editor/navigation/clipboard";
+import type { CellId } from "@/core/cells/ids";
+import { createReducerAndAtoms } from "@/utils/createReducer";
+
+interface PendingCutState {
+ cellIds: Set<CellId>;
+ clipboardData: ClipboardCellData | null;
+}
+
+const initialState = (): PendingCutState => ({
+ cellIds: new Set(),
+ clipboardData: null,
+});
+
+const {
+ valueAtom: pendingCutStateAtom,
+ useActions: usePendingCutActionsInternal,
+} = createReducerAndAtoms(initialState, {
+ markForCut: (
+ _state,
+ action: { cellIds: CellId[]; clipboardData: ClipboardCellData },
+ ) => {
+ return {
+ cellIds: new Set(action.cellIds),
+ clipboardData: action.clipboardData,
+ };
+ },
+ clear: () => {
+ return initialState();
+ },
+});
+
+// Re-export the state atom
+export { pendingCutStateAtom };
+
+// Derived atom just for cell IDs (for easier consumption)
+export const pendingCutCellIdsAtom = atom(
+ (get) => get(pendingCutStateAtom).cellIds,
+);
+
+export const clearPendingCutAtom = atom(null, (_get, set) => {
+ set(pendingCutStateAtom, initialState());
+});
+
+export function usePendingCutActions() {
+ return usePendingCutActionsInternal();
+}
+
+export function useIsPendingCut(cellId: CellId): boolean {
+ const cellIds = useAtomValue(pendingCutCellIdsAtom);
+ return cellIds.has(cellId);
+}
+
+export function usePendingCutState() {
+ return useAtomValue(pendingCutStateAtom);
+}
+
+export function useHasPendingCut(): boolean {
+ const state = useAtomValue(pendingCutStateAtom);
+ return state.cellIds.size > 0;
+}
diff --git a/frontend/src/core/cells/utils.ts b/frontend/src/core/cells/utils.ts
index 699ca5f855..42fb887cb4 100644
--- a/frontend/src/core/cells/utils.ts
+++ b/frontend/src/core/cells/utils.ts
@@ -65,6 +65,17 @@ export function canUndoDeletes(state: NotebookState) {
return state.history.length > 0;
}
+/**
+ * Label for the undo action based on the last history entry type.
+ */
+export function getUndoLabel(state: NotebookState): string {
+ const last = state.history[state.history.length - 1];
+ if (!last) {
+ return "Undo cell deletion";
+ }
+ return last.type === "move" ? "Undo move" : "Undo cell deletion";
+}
+
/**
* Get the status of the descendants of the given cell.
*/
diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.ts
index b4c599bfd7..2ac33eaf69 100644
--- a/frontend/src/core/codemirror/cells/extensions.ts
+++ b/frontend/src/core/codemirror/cells/extensions.ts
@@ -10,6 +10,10 @@ import {
} from "@codemirror/view";
import { createTracebackInfoAtom } from "@/core/cells/cells";
import { type CellId, HTMLCellId, SCRATCH_CELL_ID } from "@/core/cells/ids";
+import {
+ clearPendingCutAtom,
+ pendingCutCellIdsAtom,
+} from "@/core/cells/pending-cut-service";
import { loroSyncAnnotation } from "@/core/codemirror/rtc/loro/sync";
import type { KeymapConfig } from "@/core/config/config-schema";
import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";
@@ -326,6 +330,12 @@ function cellCodeEditing(hotkeys: HotkeyProvider): Extension[] {
code: nextCode,
formattingChange: isFormattingChange,
});
+
+ // Clear pending cut state if this cell was marked for cut
+ const pendingCutCellIds = store.get(pendingCutCellIdsAtom);
+ if (pendingCutCellIds.has(cellId)) {
+ store.set(clearPendingCutAtom);
+ }
}
});
diff --git a/frontend/src/core/hotkeys/hotkeys.ts b/frontend/src/core/hotkeys/hotkeys.ts
index 9e1c9eb03a..6ce822717a 100644
--- a/frontend/src/core/hotkeys/hotkeys.ts
+++ b/frontend/src/core/hotkeys/hotkeys.ts
@@ -442,6 +442,11 @@ const DEFAULT_HOT_KEY = {
group: "Command",
key: "c",
},
+ "command.cutCell": {
+ name: "Cut cell",
+ group: "Command",
+ key: "x",
+ },
"command.pasteCell": {
name: "Paste cell",
group: "Command",
diff --git a/frontend/src/css/app/Cell.css b/frontend/src/css/app/Cell.css
index 56fe52b3fc..e5bd80ab5d 100644
--- a/frontend/src/css/app/Cell.css
+++ b/frontend/src/css/app/Cell.css
@@ -73,6 +73,19 @@
}
}
+ /* Styling for cells marked for cut */
+ &.pending-cut {
+ opacity: 0.6;
+ border-style: dashed;
+ border-color: var(--amber-7);
+
+ .output-area,
+ .cm-gutters,
+ .cm {
+ background-color: var(--amber-2);
+ }
+ }
+
&:focus-within {
z-index: 20;
}
diff --git a/frontend/src/utils/__tests__/id-tree.test.ts b/frontend/src/utils/__tests__/id-tree.test.ts
index 30cf0e8713..9186ca987d 100644
--- a/frontend/src/utils/__tests__/id-tree.test.ts
+++ b/frontend/src/utils/__tests__/id-tree.test.ts
@@ -957,6 +957,77 @@ describe("MultiColumn", () => {
expect(inserted.topLevelIds[1]).toEqual(["B1", "D1", "B2"]);
});
+ describe("moveCellsRelativeTo", () => {
+ it("moves a single cell before target in same column", () => {
+ const moved = multiColumn.moveCellsRelativeTo(["A3"], "A1", "before");
+ expect(moved.topLevelIds).toEqual([
+ ["A3", "A1", "A2"],
+ ["B1", "B2"],
+ ["C1", "C2", "C3", "C4"],
+ ]);
+ });
+
+ it("moves a single cell after target in same column", () => {
+ const moved = multiColumn.moveCellsRelativeTo(["A1"], "A3", "after");
+ expect(moved.topLevelIds).toEqual([
+ ["A2", "A3", "A1"],
+ ["B1", "B2"],
+ ["C1", "C2", "C3", "C4"],
+ ]);
+ });
+
+ it("moves multiple cells before target", () => {
+ const moved = multiColumn.moveCellsRelativeTo(
+ ["A1", "A2"],
+ "B2",
+ "before",
+ );
+ expect(moved.topLevelIds).toEqual([
+ ["A3"],
+ ["B1", "A1", "A2", "B2"],
+ ["C1", "C2", "C3", "C4"],
+ ]);
+ });
+
+ it("moves multiple cells after target", () => {
+ const moved = multiColumn.moveCellsRelativeTo(
+ ["A2", "A3"],
+ "B1",
+ "after",
+ );
+ expect(moved.topLevelIds).toEqual([
+ ["A1"],
+ ["B1", "A2", "A3", "B2"],
+ ["C1", "C2", "C3", "C4"],
+ ]);
+ });
+
+ it("returns same MultiColumn when cellIds is empty", () => {
+ const moved = multiColumn.moveCellsRelativeTo([], "A1", "before");
+ expect(moved).toBe(multiColumn);
+ });
+
+ it("inserts at end when target is among moved cells", () => {
+ const moved = multiColumn.moveCellsRelativeTo(
+ ["A1", "A2"],
+ "A2",
+ "after",
+ );
+ // Target A2 was removed; insert at end of column 0
+ expect(moved.topLevelIds).toEqual([
+ ["A3", "A1", "A2"],
+ ["B1", "B2"],
+ ["C1", "C2", "C3", "C4"],
+ ]);
+ });
+
+ it("throws when node not found", () => {
+ expect(() =>
+ multiColumn.moveCellsRelativeTo(["Z1"], "A1", "before"),
+ ).toThrow("Cell Z1 not found in any column");
+ });
+ });
+
it("deletes by id", () => {
const deleted = multiColumn.deleteById("B1");
expect(deleted.topLevelIds[1]).toEqual(["B2"]);
diff --git a/frontend/src/utils/id-tree.tsx b/frontend/src/utils/id-tree.tsx
index deb979b428..2ef047213e 100644
--- a/frontend/src/utils/id-tree.tsx
+++ b/frontend/src/utils/id-tree.tsx
@@ -861,6 +861,67 @@ export class MultiColumn<T> {
return new MultiColumn(newColumns);
}
+ /**
+ * Move multiple cells to be immediately before (or after) a target cell.
+ * Cells are inserted in their original order.
+ *
+ * @throws Error if any cellId is not found in any column.
+ * If targetId is among the moved cells, cells are inserted at the end of the target column.
+ */
+ moveCellsRelativeTo(
+ cellIds: T[],
+ targetId: T,
+ position: "before" | "after",
+ ): MultiColumn<T> {
+ if (cellIds.length === 0) {
+ return this;
+ }
+
+ const cellIdSet = new Set(cellIds);
+ const targetColumn = this.findWithId(targetId);
+ const targetColIndex = this.indexOfOrThrow(targetColumn.id);
+
+ // Collect nodes to move
+ const nodesToMove: TreeNode<T>[] = [];
+ for (const id of cellIds) {
+ const col = this.findWithId(id);
+ const node = col.nodes.find((n) => n.value === id);
+ if (!node) {
+ throw new Error(`Node ${id} not found in column ${col.id}`);
+ }
+ nodesToMove.push(node);
+ }
+
+ // Remove moved cells from all columns
+ const columnsWithRemovals = this.columns.map((col) =>
+ col.withNodes(col.nodes.filter((n) => !cellIdSet.has(n.value))),
+ );
+
+ // Find target index in the cleaned column
+ const cleanedTargetCol = columnsWithRemovals[targetColIndex];
+ let insertIndex = cleanedTargetCol.nodes.findIndex(
+ (n) => n.value === targetId,
+ );
+
+ // If target was one of the moved cells, insert at end
+ if (insertIndex === -1) {
+ insertIndex = cleanedTargetCol.nodes.length;
+ } else if (position === "after") {
+ insertIndex += 1;
+ }
+
+ // Insert all moved nodes at target position
+ const newTargetNodes = arrayInsertMany(
+ cleanedTargetCol.nodes,
+ insertIndex,
+ nodesToMove,
+ );
+ columnsWithRemovals[targetColIndex] =
+ cleanedTargetCol.withNodes(newTargetNodes);
+
+ return new MultiColumn(columnsWithRemovals);
+ }
+
indexOfOrThrow(id: CellColumnId): number {
const index = this.columns.findIndex((c) => c.id === id);
if (index === -1) {
@@ -963,6 +1024,34 @@ export class MultiColumn<T> {
return this.transformWithCellId(cellId, (c) => c.delete(cellId));
}
+ /**
+ * Remove the given cells from the tree, then re-insert each at its
+ * (columnId, index). Used to undo a move (e.g. cut-paste) by restoring
+ * cells to their previous positions. Placements are sorted by
+ * (columnId, index) so insert order keeps indices valid.
+ */
+ placeCells(
+ placements: Array<{ id: T; columnId: CellColumnId; index: CellIndex }>,
+ ): MultiColumn<T> {
+ if (placements.length === 0) {
+ return this;
+ }
+ let result = this.deleteById(placements[0].id);
+ for (const { id } of placements.slice(1)) {
+ result = result.deleteById(id);
+ }
+ const sorted = [...placements].toSorted((a, b) => {
+ if (a.columnId !== b.columnId) {
+ return a.columnId.localeCompare(b.columnId);
+ }
+ return (a.index as number) - (b.index as number);
+ });
+ for (const { id, columnId, index } of sorted) {
+ result = result.insertId(id, columnId, index);
+ }
+ return result;
+ }
+
compact(): MultiColumn<T> {
// Don't compact if there's only one column
if (this.columns.length === 1) {