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: multi-cell selection (#5633)

Myles Scolnick80da829c9749
diff --git a/frontend/src/__mocks__/notebook.ts b/frontend/src/__mocks__/notebook.ts
index fe1e7b1e5f..b62e119685 100644
--- a/frontend/src/__mocks__/notebook.ts
+++ b/frontend/src/__mocks__/notebook.ts
@@ -1,14 +1,19 @@
/* Copyright 2024 Marimo. All rights reserved. */
+
+import { createRef } from "react";
import { vi } from "vitest";
import type { CellActions, NotebookState } from "@/core/cells/cells";
import { CellId } from "@/core/cells/ids";
-import type { CellData } from "@/core/cells/types";
+import { type CellData, createCellRuntimeState } from "@/core/cells/types";
import { MultiColumn } from "@/utils/id-tree";
import { Objects } from "@/utils/objects";
export const MockNotebook = {
*cellIds() {
- yield CellId.create();
+ // Some large number to prevent freezing when this function is misused.
+ for (let i = 0; i < 10_000; i++) {
+ yield CellId.create();
+ }
},
notebookState: (opts?: {
@@ -33,8 +38,10 @@ export const MockNotebook = {
...data,
})),
cellIds: MultiColumn.from([Object.keys(cellData) as CellId[]]),
- cellRuntime: {},
- cellHandles: {},
+ cellRuntime: Objects.mapValues(cellData, (_data) =>
+ createCellRuntimeState({}),
+ ),
+ cellHandles: Objects.mapValues(cellData, (_data) => createRef()),
cellLogs: [],
history: [],
scrollKey: null,
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsx
index 6453e2c7c7..aeb1146246 100644
--- a/frontend/src/components/editor/Cell.tsx
+++ b/frontend/src/components/editor/Cell.tsx
@@ -73,7 +73,6 @@ import { useRunCell } from "./cell/useRunCells";
import { HideCodeButton } from "./code/readonly-python-code";
import { cellDomProps } from "./common";
import { useCellNavigationProps } from "./navigation/navigation";
-
import { temporarilyShownCodeAtom } from "./navigation/state";
import { OutputArea } from "./Output";
import { ConsoleOutput } from "./output/ConsoleOutput";
@@ -586,7 +585,8 @@ const EditableCellComponent = ({
stopped: stopped,
disabled: cellConfig.disabled,
stale: status === "disabled-transitively",
- borderless: isMarkdownCodeHidden && hasOutput,
+ borderless:
+ isMarkdownCodeHidden && hasOutput && !navigationProps["data-selected"],
});
const handleRefactorWithAI = useEvent((opts: { prompt: string }) => {
@@ -636,6 +636,7 @@ const EditableCellComponent = ({
{...navigationProps}
className={cn(
className,
+ navigationProps.className,
"focus:ring-1 focus:ring-[var(--blue-7)] focus:ring-offset-0",
)}
ref={cellContainerRef}
@@ -1094,10 +1095,10 @@ const SetupCellComponent = ({
name={name}
>
<div
- className={className}
data-status={status}
ref={cellRef}
{...mergeProps(navigationProps, {
+ className,
onBlur: closeCompletionHandler,
onKeyDown: resumeCompletionHandler,
})}
diff --git a/frontend/src/components/editor/cell/useDeleteCell.tsx b/frontend/src/components/editor/cell/useDeleteCell.tsx
index 1411645fbd..bb25cdfd6c 100644
--- a/frontend/src/components/editor/cell/useDeleteCell.tsx
+++ b/frontend/src/components/editor/cell/useDeleteCell.tsx
@@ -50,3 +50,38 @@ export function useDeleteCellCallback() {
}
});
}
+
+export function useDeleteManyCellsCallback() {
+ const { deleteCell, undoDeleteCell } = useCellActions();
+
+ return useEvent(async (opts: { cellIds: CellId[] }) => {
+ // Can't delete the last cell
+ if (store.get(hasOnlyOneCellAtom)) {
+ return;
+ }
+
+ const { cellIds } = opts;
+ for (const cellId of cellIds) {
+ await sendDeleteCell({ cellId }).then(() => {
+ deleteCell({ cellId });
+ });
+ }
+
+ const { dismiss } = toast({
+ title: "Cells deleted",
+ action: (
+ <UndoButton
+ data-testid="undo-delete-button"
+ onClick={() => {
+ for (const _cellId of cellIds) {
+ // This function does not take a cellId,
+ // so we just undo the number of cells that were deleted
+ undoDeleteCell();
+ }
+ dismiss();
+ }}
+ />
+ ),
+ });
+ });
+}
diff --git a/frontend/src/components/editor/cell/useRunCells.ts b/frontend/src/components/editor/cell/useRunCells.ts
index bc6d597555..e41ff9cfb2 100644
--- a/frontend/src/components/editor/cell/useRunCells.ts
+++ b/frontend/src/components/editor/cell/useRunCells.ts
@@ -42,7 +42,7 @@ export function useRunAllCells() {
/**
* Creates a function that runs the given cells.
*/
-function useRunCells() {
+export function useRunCells() {
const { prepareForRun } = useCellActions();
const runCells = useEvent(async (cellIds: CellId[]) => {
diff --git a/frontend/src/components/editor/navigation/__tests__/clipboard.test.ts b/frontend/src/components/editor/navigation/__tests__/clipboard.test.ts
index ed421a9a13..842ee84175 100644
--- a/frontend/src/components/editor/navigation/__tests__/clipboard.test.ts
+++ b/frontend/src/components/editor/navigation/__tests__/clipboard.test.ts
@@ -28,8 +28,9 @@ import { getNotebook, useCellActions } from "@/core/cells/cells";
import { Logger } from "@/utils/Logger";
describe("useCellClipboard", () => {
- const mockCellId = "test-cell-id" as CellId;
- const mockCellCode = "print('hello world')";
+ const [mockCellId1, mockCellId2] = MockNotebook.cellIds();
+ const mockCellCode1 = "print('hello world')";
+ const mockCellCode2 = "x = 42";
const mockCreateNewCell = vi.fn();
const mockClipboard = Mocks.clipboard();
@@ -39,12 +40,22 @@ describe("useCellClipboard", () => {
SetupMocks.clipboard(mockClipboard);
+ // Setup default clipboard mock implementations
+ mockClipboard.write.mockResolvedValue(undefined);
+ mockClipboard.writeText.mockResolvedValue(undefined);
+ mockClipboard.read.mockResolvedValue([]);
+ mockClipboard.readText.mockResolvedValue("");
+
// Setup default mocks
asMock(getNotebook).mockReturnValue({
cellData: {
- [mockCellId]: {
- code: mockCellCode,
- name: "test-cell",
+ [mockCellId1]: {
+ code: mockCellCode1,
+ name: "test-cell-1",
+ },
+ [mockCellId2]: {
+ code: mockCellCode2,
+ name: "test-cell-2",
},
},
} as NotebookState);
@@ -54,12 +65,12 @@ describe("useCellClipboard", () => {
} as unknown as CellActions);
});
- describe("copyCell", () => {
- it("should copy cell to clipboard with custom mimetype and plain text", async () => {
+ describe("copyCells", () => {
+ it("should copy single cell to clipboard with custom mimetype and plain text", async () => {
const { result } = renderHook(() => useCellClipboard());
await act(async () => {
- await result.current.copyCell(mockCellId);
+ await result.current.copyCells([mockCellId1]);
});
expect(mockClipboard.write).toHaveBeenCalledWith([
@@ -74,40 +85,93 @@ describe("useCellClipboard", () => {
});
});
- it("should show error toast when cell not found", async () => {
+ it("should copy multiple cells to clipboard with custom mimetype and plain text", async () => {
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.copyCells([mockCellId1, mockCellId2]);
+ });
+
+ expect(mockClipboard.write).toHaveBeenCalledWith([
+ expect.objectContaining({
+ types: ["application/x-marimo-cell", "text/plain"],
+ }),
+ ]);
+
+ expect(toast).toHaveBeenCalledWith({
+ title: "2 cells copied",
+ description: "2 cells have been copied to clipboard",
+ });
+ });
+
+ it("should show error toast when no cells found", async () => {
asMock(getNotebook).mockReturnValue(MockNotebook.notebookState());
const { result } = renderHook(() => useCellClipboard());
await act(async () => {
- await result.current.copyCell(mockCellId);
+ await result.current.copyCells([mockCellId1]);
});
expect(toast).toHaveBeenCalledWith({
title: "Error",
- description: "Cell not found",
+ description: "No cells found",
variant: "danger",
});
});
- it("should fallback to writeText when clipboard.write fails", async () => {
+ it("should show error toast when empty cell list provided", async () => {
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.copyCells([]);
+ });
+
+ expect(toast).toHaveBeenCalledWith({
+ title: "Error",
+ description: "No cells found",
+ variant: "danger",
+ });
+ });
+
+ it("should fallback to writeText when clipboard.write fails for single cell", async () => {
mockClipboard.write.mockRejectedValue(new Error("Write failed"));
mockClipboard.writeText.mockResolvedValue(undefined);
const { result } = renderHook(() => useCellClipboard());
await act(async () => {
- await result.current.copyCell(mockCellId);
+ await result.current.copyCells([mockCellId1]);
});
expect(mockClipboard.write).toHaveBeenCalled();
- expect(mockClipboard.writeText).toHaveBeenCalledWith(mockCellCode);
+ expect(mockClipboard.writeText).toHaveBeenCalledWith(mockCellCode1);
expect(toast).toHaveBeenCalledWith({
title: "Cell copied",
description: "Cell code has been copied to clipboard",
});
});
+ it("should fallback to writeText when clipboard.write fails for multiple cells", async () => {
+ mockClipboard.write.mockRejectedValue(new Error("Write failed"));
+ mockClipboard.writeText.mockResolvedValue(undefined);
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.copyCells([mockCellId1, mockCellId2]);
+ });
+
+ expect(mockClipboard.write).toHaveBeenCalled();
+ expect(mockClipboard.writeText).toHaveBeenCalledWith(
+ `${mockCellCode1}\n\n${mockCellCode2}`,
+ );
+ expect(toast).toHaveBeenCalledWith({
+ title: "2 cells copied",
+ description: "2 cells code have been copied to clipboard",
+ });
+ });
+
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"));
@@ -115,25 +179,46 @@ describe("useCellClipboard", () => {
const { result } = renderHook(() => useCellClipboard());
await act(async () => {
- await result.current.copyCell(mockCellId);
+ await result.current.copyCells([mockCellId1]);
});
expect(Logger.error).toHaveBeenCalledWith(
- "Failed to copy cell to clipboard",
+ "Failed to copy cells to clipboard",
expect.any(Error),
);
expect(toast).toHaveBeenCalledWith({
title: "Copy failed",
- description: "Failed to copy cell to clipboard",
+ description: "Failed to copy cells to clipboard",
variant: "danger",
});
});
+
+ it("should filter out non-existent cells", async () => {
+ const nonExistentCellId = "non-existent" as CellId;
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.copyCells([mockCellId1, nonExistentCellId]);
+ });
+
+ expect(mockClipboard.write).toHaveBeenCalledWith([
+ expect.objectContaining({
+ types: ["application/x-marimo-cell", "text/plain"],
+ }),
+ ]);
+
+ expect(toast).toHaveBeenCalledWith({
+ title: "Cell copied",
+ description: "Cell has been copied to clipboard",
+ });
+ });
});
describe("pasteCell", () => {
- it("should paste cell from custom mimetype", async () => {
+ it("should paste single cell from custom mimetype", async () => {
const clipboardData = {
- code: "x = 42",
+ cells: [{ code: "x = 42" }],
version: "1.0",
};
@@ -151,14 +236,62 @@ describe("useCellClipboard", () => {
const { result } = renderHook(() => useCellClipboard());
await act(async () => {
- await result.current.pasteCell(mockCellId);
+ await result.current.pasteAtCell(mockCellId1);
});
expect(mockCreateNewCell).toHaveBeenCalledWith({
- cellId: mockCellId,
+ cellId: mockCellId1,
before: false,
code: "x = 42",
- autoFocus: true,
+ autoFocus: false,
+ });
+ });
+
+ it("should paste multiple cells from custom mimetype", async () => {
+ const clipboardData = {
+ cells: [
+ { code: "x = 42" },
+ { code: "y = x * 2" },
+ { code: "print(y)" },
+ ],
+ version: "1.0",
+ };
+
+ const mockItem = {
+ types: ["application/x-marimo-cell"],
+ getType: vi.fn().mockResolvedValue(
+ new Blob([JSON.stringify(clipboardData)], {
+ type: "application/x-marimo-cell",
+ }),
+ ),
+ };
+
+ mockClipboard.read.mockResolvedValue([mockItem]);
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.pasteAtCell(mockCellId1);
+ });
+
+ expect(mockCreateNewCell).toHaveBeenCalledTimes(3);
+ expect(mockCreateNewCell).toHaveBeenNthCalledWith(1, {
+ cellId: mockCellId1,
+ before: false,
+ code: "x = 42",
+ autoFocus: false,
+ });
+ expect(mockCreateNewCell).toHaveBeenNthCalledWith(2, {
+ cellId: mockCellId1,
+ before: false,
+ code: "y = x * 2",
+ autoFocus: false,
+ });
+ expect(mockCreateNewCell).toHaveBeenNthCalledWith(3, {
+ cellId: mockCellId1,
+ before: false,
+ code: "print(y)",
+ autoFocus: false,
});
});
@@ -174,11 +307,11 @@ describe("useCellClipboard", () => {
const { result } = renderHook(() => useCellClipboard());
await act(async () => {
- await result.current.pasteCell(mockCellId);
+ await result.current.pasteAtCell(mockCellId1);
});
expect(mockCreateNewCell).toHaveBeenCalledWith({
- cellId: mockCellId,
+ cellId: mockCellId1,
before: false,
code: "plain text code",
autoFocus: true,
@@ -201,7 +334,7 @@ describe("useCellClipboard", () => {
const { result } = renderHook(() => useCellClipboard());
await act(async () => {
- await result.current.pasteCell(mockCellId);
+ await result.current.pasteAtCell(mockCellId1);
});
expect(Logger.warn).toHaveBeenCalledWith(
@@ -209,7 +342,7 @@ describe("useCellClipboard", () => {
expect.any(Error),
);
expect(mockCreateNewCell).toHaveBeenCalledWith({
- cellId: mockCellId,
+ cellId: mockCellId1,
before: false,
code: "fallback text",
autoFocus: true,
@@ -223,7 +356,7 @@ describe("useCellClipboard", () => {
const { result } = renderHook(() => useCellClipboard());
await act(async () => {
- await result.current.pasteCell(mockCellId);
+ await result.current.pasteAtCell(mockCellId1);
});
expect(toast).toHaveBeenCalledWith({
@@ -239,7 +372,7 @@ describe("useCellClipboard", () => {
const { result } = renderHook(() => useCellClipboard());
await act(async () => {
- await result.current.pasteCell(mockCellId);
+ await result.current.pasteAtCell(mockCellId1);
});
expect(Logger.error).toHaveBeenCalledWith(
@@ -260,7 +393,7 @@ describe("useCellClipboard", () => {
const { result } = renderHook(() => useCellClipboard());
await act(async () => {
- await result.current.pasteCell(mockCellId);
+ await result.current.pasteAtCell(mockCellId1);
});
expect(toast).toHaveBeenCalledWith({
@@ -272,7 +405,7 @@ describe("useCellClipboard", () => {
it("should handle clipboard data with wrong version", async () => {
const clipboardData = {
- code: "x = 42",
+ cells: [{ code: "x = 42" }],
version: "2.0", // Wrong version
};
@@ -291,7 +424,7 @@ describe("useCellClipboard", () => {
const { result } = renderHook(() => useCellClipboard());
await act(async () => {
- await result.current.pasteCell(mockCellId);
+ await result.current.pasteAtCell(mockCellId1);
});
expect(Logger.warn).toHaveBeenCalledWith(
@@ -299,7 +432,39 @@ describe("useCellClipboard", () => {
expect.any(Error),
);
expect(mockCreateNewCell).toHaveBeenCalledWith({
- cellId: mockCellId,
+ cellId: mockCellId1,
+ before: false,
+ code: "fallback text",
+ autoFocus: true,
+ });
+ });
+
+ it("should handle empty cells array", async () => {
+ const clipboardData = {
+ cells: [],
+ version: "1.0",
+ };
+
+ const mockItem = {
+ types: ["application/x-marimo-cell"],
+ getType: vi.fn().mockResolvedValue(
+ new Blob([JSON.stringify(clipboardData)], {
+ type: "application/x-marimo-cell",
+ }),
+ ),
+ };
+
+ mockClipboard.read.mockResolvedValue([mockItem]);
+ mockClipboard.readText.mockResolvedValue("fallback text");
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.pasteAtCell(mockCellId1);
+ });
+
+ expect(mockCreateNewCell).toHaveBeenCalledWith({
+ cellId: mockCellId1,
before: false,
code: "fallback text",
autoFocus: true,
diff --git a/frontend/src/components/editor/navigation/__tests__/navigation.test.ts b/frontend/src/components/editor/navigation/__tests__/navigation.test.ts
index b9046d2613..e263fff5ed 100644
--- a/frontend/src/components/editor/navigation/__tests__/navigation.test.ts
+++ b/frontend/src/components/editor/navigation/__tests__/navigation.test.ts
@@ -3,12 +3,15 @@
import type { EditorView } from "@codemirror/view";
import { act, renderHook } from "@testing-library/react";
-import { createRef } from "react";
+import { Provider } from "jotai";
+import React, { createRef } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { Mocks } from "@/__mocks__/common";
import { MockNotebook } from "@/__mocks__/notebook";
import type { CellActions } from "@/core/cells/cells";
-import type { CellId } from "@/core/cells/ids";
+import { notebookAtom } from "@/core/cells/cells";
+import { configOverridesAtom, userConfigAtom } from "@/core/config/config";
+import { store } from "@/core/state/jotai";
import type { CellActionsDropdownHandle } from "../../cell/cell-actions";
import {
useCellEditorNavigationProps,
@@ -30,7 +33,7 @@ vi.mock("@/core/saving/save-component", () => ({
}));
vi.mock("../../cell/useRunCells", () => ({
- useRunCell: vi.fn(),
+ useRunCells: vi.fn(),
}));
vi.mock("../clipboard", () => ({
@@ -46,43 +49,74 @@ vi.mock("../focus-utils", () => ({
const mockUseCellActions = vi.mocked(
await import("@/core/cells/cells"),
).useCellActions;
-const mockUseSetLastFocusedCellId = vi.mocked(
- await import("@/core/cells/focus"),
-).useSetLastFocusedCellId;
+
const mockUseSaveNotebook = vi.mocked(
await import("@/core/saving/save-component"),
).useSaveNotebook;
-const mockUseRunCell = vi.mocked(
+const mockUseRunCells = vi.mocked(
await import("../../cell/useRunCells"),
-).useRunCell;
+).useRunCells;
const mockUseCellClipboard = vi.mocked(
await import("../clipboard"),
).useCellClipboard;
+import { defaultUserConfig } from "@/core/config/config-schema";
import { focusCell, focusCellEditor } from "../focus-utils";
-
-describe("useCellNavigationProps", () => {
- const mockCellId = "test-cell-id" as CellId;
- const mockSetLastFocusedCellId = vi.fn();
- const mockSaveOrNameNotebook = vi.fn();
- const mockSaveIfNotebookIsPersistent = vi.fn();
- const mockRunCell = vi.fn();
- const mockCopyCell = vi.fn();
- const mockPasteCell = vi.fn();
-
- const mockCellActions = MockNotebook.cellActions({
- focusCell: vi.fn(),
- moveToNextCell: vi.fn(),
- focusTopCell: vi.fn(),
- focusBottomCell: vi.fn(),
- createNewCell: vi.fn(),
+import {
+ type CellSelectionState,
+ exportedForTesting as selectionTesting,
+ useCellSelectionState,
+ useIsCellSelected,
+} from "../selection";
+
+// Shared render helper
+const renderWithProvider = <T>(hook: () => T) => {
+ return renderHook(hook, {
+ wrapper: ({ children }) =>
+ React.createElement(Provider, { store }, children),
});
+};
+
+// Shared mock setup
+const mockSaveOrNameNotebook = vi.fn();
+const mockSaveIfNotebookIsPersistent = vi.fn();
+const mockRunCell = vi.fn();
+const mockCopyCell = vi.fn();
+const mockPasteCell = vi.fn();
+
+const mockCellActions = MockNotebook.cellActions({
+ focusCell: vi.fn(),
+ moveToNextCell: vi.fn(),
+ focusTopCell: vi.fn(),
+ focusBottomCell: vi.fn(),
+ createNewCell: vi.fn(),
+ moveCell: vi.fn(),
+ sendToTop: vi.fn(),
+ sendToBottom: vi.fn(),
+ updateCellConfig: vi.fn(),
+ markTouched: vi.fn(),
+});
+
+// Helper to setup selection
+const setupSelection = () => {
+ const { reducer, cellSelectionAtom } = selectionTesting;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const dispatch = (action: any) => {
+ store.set(cellSelectionAtom, (prev: CellSelectionState) =>
+ reducer(prev, action),
+ );
+ };
+ return selectionTesting.createActions(dispatch);
+};
+const [cellId1, cellId2, cellId3] = MockNotebook.cellIds();
+const mockCellId = cellId1;
+
+describe("useCellNavigationProps", () => {
beforeEach(() => {
vi.clearAllMocks();
// Setup mocks
- mockUseSetLastFocusedCellId.mockReturnValue(mockSetLastFocusedCellId);
mockUseSaveNotebook.mockReturnValue({
saveOrNameNotebook: mockSaveOrNameNotebook,
saveIfNotebookIsPersistent: mockSaveIfNotebookIsPersistent,
@@ -90,11 +124,34 @@ describe("useCellNavigationProps", () => {
mockUseCellActions.mockReturnValue(
mockCellActions as unknown as CellActions,
);
- mockUseRunCell.mockReturnValue(mockRunCell);
+ mockUseRunCells.mockReturnValue(mockRunCell);
mockUseCellClipboard.mockReturnValue({
- copyCell: mockCopyCell,
- pasteCell: mockPasteCell,
+ copyCells: mockCopyCell,
+ pasteAtCell: mockPasteCell,
+ });
+
+ // Setup default config in store
+ store.set(userConfigAtom, {
+ ...defaultUserConfig(),
+ keymap: {
+ preset: "default",
+ overrides: {},
+ },
+ });
+
+ // Setup notebook state with test cells - cellId1 first, cellId3 last for bulk selection tests
+ const notebookState = MockNotebook.notebookState({
+ cellData: {
+ [cellId1]: { id: cellId1 },
+ [cellId2]: { id: cellId2 },
+ [cellId3]: { id: cellId3 },
+ },
});
+ store.set(notebookAtom, notebookState);
+
+ // Clear selection
+ const selectionActions = setupSelection();
+ selectionActions.clear();
});
const options = {
@@ -105,34 +162,29 @@ describe("useCellNavigationProps", () => {
describe("keyboard shortcuts", () => {
it("should copy cell when 'c' key is pressed", () => {
- const { result } = renderHook(() =>
+ const { result } = renderWithProvider(() =>
useCellNavigationProps(mockCellId, options),
);
const mockEvent = Mocks.keyboardEvent({ key: "c" });
act(() => {
- // Simulate the keyboard event
- if (result.current.onKeyDown) {
- result.current.onKeyDown(mockEvent);
- }
+ result.current.onKeyDown?.(mockEvent);
});
- expect(mockCopyCell).toHaveBeenCalledWith(mockCellId);
+ expect(mockCopyCell).toHaveBeenCalledWith([mockCellId]);
expect(mockEvent.preventDefault).toHaveBeenCalled();
});
it("should paste cell when 'v' key is pressed", () => {
- const { result } = renderHook(() =>
+ const { result } = renderWithProvider(() =>
useCellNavigationProps(mockCellId, options),
);
const mockEvent = Mocks.keyboardEvent({ key: "v" });
act(() => {
- if (result.current.onKeyDown) {
- result.current.onKeyDown(mockEvent);
- }
+ result.current.onKeyDown?.(mockEvent);
});
expect(mockPasteCell).toHaveBeenCalledWith(mockCellId);
@@ -140,16 +192,14 @@ describe("useCellNavigationProps", () => {
});
it("should move to next cell when ArrowDown is pressed", () => {
- const { result } = renderHook(() =>
+ const { result } = renderWithProvider(() =>
useCellNavigationProps(mockCellId, options),
);
const mockEvent = Mocks.keyboardEvent({ key: "ArrowDown" });
act(() => {
- if (result.current.onKeyDown) {
- result.current.onKeyDown(mockEvent);
- }
+ result.current.onKeyDown?.(mockEvent);
});
expect(mockCellActions.focusCell).toHaveBeenCalledWith({
@@ -159,16 +209,14 @@ describe("useCellNavigationProps", () => {
});
it("should move to previous cell when ArrowUp is pressed", () => {
- const { result } = renderHook(() =>
+ const { result } = renderWithProvider(() =>
useCellNavigationProps(mockCellId, options),
);
const mockEvent = Mocks.keyboardEvent({ key: "ArrowUp" });
act(() => {
- if (result.current.onKeyDown) {
- result.current.onKeyDown(mockEvent);
- }
+ result.current.onKeyDown?.(mockEvent);
});
expect(mockCellActions.focusCell).toHaveBeenCalledWith({
@@ -178,16 +226,14 @@ describe("useCellNavigationProps", () => {
});
it("should focus cell editor when Enter is pressed", () => {
- const { result } = renderHook(() =>
+ const { result } = renderWithProvider(() =>
useCellNavigationProps(mockCellId, options),
);
const mockEvent = Mocks.keyboardEvent({ key: "Enter", shiftKey: false });
act(() => {
- if (result.current.onKeyDown) {
- result.current.onKeyDown(mockEvent);
- }
+ result.current.onKeyDown?.(mockEvent);
});
expect(focusCellEditor).toHaveBeenCalledWith(
@@ -198,16 +244,14 @@ describe("useCellNavigationProps", () => {
});
it("should run cell and move to next when Shift+Enter is pressed", () => {
- const { result } = renderHook(() =>
+ const { result } = renderWithProvider(() =>
useCellNavigationProps(mockCellId, options),
);
const mockEvent = Mocks.keyboardEvent({ key: "Enter", shiftKey: true });
act(() => {
- if (result.current.onKeyDown) {
- result.current.onKeyDown(mockEvent);
- }
+ result.current.onKeyDown?.(mockEvent);
});
expect(mockRunCell).toHaveBeenCalled();
@@ -219,32 +263,28 @@ describe("useCellNavigationProps", () => {
});
it("should save notebook when 's' key is pressed", () => {
- const { result } = renderHook(() =>
+ const { result } = renderWithProvider(() =>
useCellNavigationProps(mockCellId, options),
);
const mockEvent = Mocks.keyboardEvent({ key: "s" });
act(() => {
- if (result.current.onKeyDown) {
- result.current.onKeyDown(mockEvent);
- }
+ result.current.onKeyDown?.(mockEvent);
});
expect(mockSaveOrNameNotebook).toHaveBeenCalled();
});
it("should create cell before when 'a' key is pressed", () => {
- const { result } = renderHook(() =>
+ const { result } = renderWithProvider(() =>
useCellNavigationProps(mockCellId, options),
);
const mockEvent = Mocks.keyboardEvent({ key: "a" });
act(() => {
- if (result.current.onKeyDown) {
- result.current.onKeyDown(mockEvent);
- }
+ result.current.onKeyDown?.(mockEvent);
});
expect(mockCellActions.createNewCell).toHaveBeenCalledWith({
@@ -255,16 +295,14 @@ describe("useCellNavigationProps", () => {
});
it("should create cell after when 'b' key is pressed", () => {
- const { result } = renderHook(() =>
+ const { result } = renderWithProvider(() =>
useCellNavigationProps(mockCellId, options),
);
const mockEvent = Mocks.keyboardEvent({ key: "b" });
act(() => {
- if (result.current.onKeyDown) {
- result.current.onKeyDown(mockEvent);
- }
+ result.current.onKeyDown?.(mockEvent);
});
expect(mockCellActions.createNewCell).toHaveBeenCalledWith({
@@ -275,23 +313,21 @@ describe("useCellNavigationProps", () => {
});
it("should move to top cell when Cmd+ArrowUp is pressed (or Ctrl)", () => {
- const { result } = renderHook(() =>
+ const { result } = renderWithProvider(() =>
useCellNavigationProps(mockCellId, options),
);
const mockEvent = Mocks.keyboardEvent({ key: "ArrowUp", ctrlKey: true });
act(() => {
- if (result.current.onKeyDown) {
- result.current.onKeyDown(mockEvent);
- }
+ result.current.onKeyDown?.(mockEvent);
});
expect(mockCellActions.focusTopCell).toHaveBeenCalled();
});
it("should move to bottom cell when Cmd+ArrowDown is pressed (or Ctrl)", () => {
- const { result } = renderHook(() =>
+ const { result } = renderWithProvider(() =>
useCellNavigationProps(mockCellId, options),
);
@@ -301,32 +337,28 @@ describe("useCellNavigationProps", () => {
});
act(() => {
- if (result.current.onKeyDown) {
- result.current.onKeyDown(mockEvent);
- }
+ result.current.onKeyDown?.(mockEvent);
});
expect(mockCellActions.focusBottomCell).toHaveBeenCalled();
});
it("should move to top cell when Ctrl+ArrowUp is pressed", () => {
- const { result } = renderHook(() =>
+ const { result } = renderWithProvider(() =>
useCellNavigationProps(mockCellId, options),
);
const mockEvent = Mocks.keyboardEvent({ key: "ArrowUp", ctrlKey: true });
act(() => {
- if (result.current.onKeyDown) {
- result.current.onKeyDown(mockEvent);
- }
+ result.current.onKeyDown?.(mockEvent);
});
expect(mockCellActions.focusTopCell).toHaveBeenCalled();
});
it("should move to bottom cell when Ctrl+ArrowDown is pressed", () => {
- const { result } = renderHook(() =>
+ const { result } = renderWithProvider(() =>
useCellNavigationProps(mockCellId, options),
);
@@ -336,18 +368,171 @@ describe("useCellNavigationProps", () => {
});
act(() => {
- if (result.current.onKeyDown) {
- result.current.onKeyDown(mockEvent);
- }
+ result.current.onKeyDown?.(mockEvent);
});
expect(mockCellActions.focusBottomCell).toHaveBeenCalled();
});
+
+ it("should extend selection up when Shift+ArrowUp is pressed", () => {
+ const { result } = renderWithProvider(() =>
+ useCellNavigationProps(mockCellId, options),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({
+ key: "ArrowUp",
+ shiftKey: true,
+ });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockCellActions.focusCell).toHaveBeenCalledWith({
+ cellId: mockCellId,
+ before: true,
+ });
+ });
+
+ it("should extend selection down when Shift+ArrowDown is pressed", () => {
+ const { result } = renderWithProvider(() =>
+ useCellNavigationProps(mockCellId, options),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({
+ key: "ArrowDown",
+ shiftKey: true,
+ });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockCellActions.focusCell).toHaveBeenCalledWith({
+ cellId: mockCellId,
+ before: false,
+ });
+ });
+
+ it("should clear selection when Escape is pressed", () => {
+ // Add selection
+ const selectionActions = setupSelection();
+ selectionActions.select({ cellId: mockCellId });
+
+ const { result } = renderWithProvider(() =>
+ useCellNavigationProps(mockCellId, options),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({ key: "Escape" });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ });
+
+ it("should set temporarily shown code when Enter is pressed", () => {
+ const { result } = renderWithProvider(() =>
+ useCellNavigationProps(mockCellId, options),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({ key: "Enter" });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(focusCellEditor).toHaveBeenCalledWith(
+ expect.anything(),
+ mockCellId,
+ );
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ });
+ });
+
+ describe("vim mode navigation", () => {
+ beforeEach(() => {
+ // Set up vim mode in store
+ store.set(configOverridesAtom, {
+ keymap: {
+ preset: "vim",
+ },
+ });
+ });
+
+ it("should move down when 'j' key is pressed in vim mode", () => {
+ const { result } = renderWithProvider(() =>
+ useCellNavigationProps(mockCellId, options),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({ key: "j" });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockCellActions.focusCell).toHaveBeenCalledWith({
+ cellId: mockCellId,
+ before: false,
+ });
+ });
+
+ it("should move up when 'k' key is pressed in vim mode", () => {
+ const { result } = renderWithProvider(() =>
+ useCellNavigationProps(mockCellId, options),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({ key: "k" });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockCellActions.focusCell).toHaveBeenCalledWith({
+ cellId: mockCellId,
+ before: true,
+ });
+ });
+
+ it("should extend selection down when 'J' key is pressed in vim mode", () => {
+ const { result } = renderWithProvider(() =>
+ useCellNavigationProps(mockCellId, options),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({ key: "J", shiftKey: true });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockCellActions.focusCell).toHaveBeenCalledWith({
+ cellId: mockCellId,
+ before: false,
+ });
+ });
+
+ it("should extend selection up when 'K' key is pressed in vim mode", () => {
+ const { result } = renderWithProvider(() =>
+ useCellNavigationProps(mockCellId, options),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({ key: "K", shiftKey: true });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockCellActions.focusCell).toHaveBeenCalledWith({
+ cellId: mockCellId,
+ before: true,
+ });
+ });
});
describe("input event handling", () => {
it("should ignore events from input elements", () => {
- const { result } = renderHook(() =>
+ const { result } = renderWithProvider(() =>
useCellNavigationProps(mockCellId, options),
);
@@ -357,9 +542,7 @@ describe("useCellNavigationProps", () => {
});
act(() => {
- if (result.current.onKeyDown) {
- result.current.onKeyDown(mockEvent);
- }
+ result.current.onKeyDown?.(mockEvent);
});
expect(mockCopyCell).not.toHaveBeenCalled();
@@ -369,7 +552,7 @@ describe("useCellNavigationProps", () => {
describe("unknown keys", () => {
it("should continue propagation for unknown keys", () => {
- const { result } = renderHook(() =>
+ const { result } = renderWithProvider(() =>
useCellNavigationProps(mockCellId, options),
);
@@ -379,35 +562,428 @@ describe("useCellNavigationProps", () => {
});
act(() => {
- if (result.current.onKeyDown) {
- result.current.onKeyDown(mockEvent);
- }
+ result.current.onKeyDown?.(mockEvent);
});
expect(mockEvent.continuePropagation).not.toHaveBeenCalled();
});
});
+
+ describe("single cell operations", () => {
+ it("should run single cell when no selection", () => {
+ const { result } = renderWithProvider(() =>
+ useCellNavigationProps(cellId1, options),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({ key: "Enter", ctrlKey: true });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockRunCell).toHaveBeenCalledWith([cellId1]);
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ });
+
+ it("should move single cell when no selection", () => {
+ const { result } = renderWithProvider(() =>
+ useCellNavigationProps(cellId2, options),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({
+ key: "9",
+ ctrlKey: true,
+ shiftKey: true,
+ });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockCellActions.moveCell).toHaveBeenCalledWith({
+ cellId: cellId2,
+ before: true,
+ });
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ });
+
+ it("doesn't move the cell if it's at the top of the notebook", () => {
+ const { result } = renderWithProvider(() =>
+ useCellNavigationProps(cellId1, options),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({
+ key: "9",
+ ctrlKey: true,
+ shiftKey: true,
+ });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockCellActions.moveCell).not.toHaveBeenCalled();
+ expect(mockEvent.preventDefault).not.toHaveBeenCalled();
+ });
+
+ it("doesn't move the cell if it's at the bottom of the notebook", () => {
+ const { result } = renderWithProvider(() =>
+ useCellNavigationProps(cellId3, options),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({
+ key: "0",
+ ctrlKey: true,
+ shiftKey: true,
+ });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockCellActions.moveCell).not.toHaveBeenCalled();
+ expect(mockEvent.preventDefault).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("bulk cell operations", () => {
+ it("should run multiple cells when multiple cells selected", () => {
+ // Set up selection of multiple cells
+ 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: "Enter", ctrlKey: true });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockRunCell).toHaveBeenCalledWith([cellId1, cellId2]);
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ });
+
+ it("should copy 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: "c" });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockCopyCell).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();
+ selectionActions.select({ cellId: cellId2 });
+ selectionActions.extend({
+ cellId: cellId3,
+ allCellIds: store.get(notebookAtom).cellIds,
+ });
+
+ const { result } = renderWithProvider(() =>
+ useCellNavigationProps(cellId2, options),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({
+ key: "9",
+ ctrlKey: true,
+ shiftKey: true,
+ });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockCellActions.moveCell).toHaveBeenCalledWith({
+ cellId: cellId2,
+ before: true,
+ });
+ expect(mockCellActions.moveCell).toHaveBeenCalledWith({
+ cellId: cellId3,
+ before: true,
+ });
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ });
+
+ it("should move multiple cells down when multiple cells selected", () => {
+ // Set up selection of multiple cells
+ 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: "0",
+ ctrlKey: true,
+ shiftKey: true,
+ });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ // For move down, cells should be moved in reverse order
+ expect(mockCellActions.moveCell).toHaveBeenCalledWith({
+ cellId: cellId2,
+ before: false,
+ });
+ expect(mockCellActions.moveCell).toHaveBeenCalledWith({
+ cellId: cellId1,
+ before: false,
+ });
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ });
+
+ it("should send multiple cells to top when multiple cells selected", () => {
+ // Set up selection of multiple cells
+ const selectionActions = setupSelection();
+ selectionActions.select({ cellId: cellId2 });
+ selectionActions.extend({
+ cellId: cellId3,
+ allCellIds: store.get(notebookAtom).cellIds,
+ });
+
+ const { result } = renderWithProvider(() =>
+ useCellNavigationProps(cellId2, options),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({
+ key: "1",
+ ctrlKey: true,
+ shiftKey: true,
+ });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockCellActions.sendToTop).toHaveBeenCalledWith({
+ cellId: cellId2,
+ });
+ expect(mockCellActions.sendToTop).toHaveBeenCalledWith({
+ cellId: cellId3,
+ });
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ });
+
+ it("should send multiple cells to bottom when multiple cells selected", () => {
+ // Set up selection of multiple cells
+ 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: "2",
+ ctrlKey: true,
+ shiftKey: true,
+ });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockCellActions.sendToBottom).toHaveBeenCalledWith({
+ cellId: cellId1,
+ });
+ expect(mockCellActions.sendToBottom).toHaveBeenCalledWith({
+ cellId: cellId2,
+ });
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ });
+
+ it("should run and move to next cell for multiple cells selected", () => {
+ // Set up selection of multiple cells
+ 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: "Enter", shiftKey: true });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockRunCell).toHaveBeenCalledWith([cellId1, cellId2]);
+ // Should move to next cell after the last selected cell
+ expect(mockCellActions.moveToNextCell).toHaveBeenCalledWith({
+ cellId: cellId2,
+ before: false,
+ });
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ });
+
+ it("should run and move to previous cell for multiple cells selected", () => {
+ // Set up selection of multiple cells
+ const selectionActions = setupSelection();
+ selectionActions.select({ cellId: cellId2 });
+ selectionActions.extend({
+ cellId: cellId3,
+ allCellIds: store.get(notebookAtom).cellIds,
+ });
+
+ const { result } = renderWithProvider(() =>
+ useCellNavigationProps(cellId2, options),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({
+ key: "Enter",
+ ctrlKey: true,
+ shiftKey: true,
+ });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockRunCell).toHaveBeenCalledWith([cellId2, cellId3]);
+ // Should move to previous cell before the first selected cell
+ expect(mockCellActions.moveToNextCell).toHaveBeenCalledWith({
+ cellId: cellId2,
+ before: true,
+ });
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ });
+ });
+
+ describe("selection state management", () => {
+ it("should indicate cell is selected when in selection", () => {
+ // Set up selection
+ const selectionActions = setupSelection();
+ selectionActions.select({ cellId: cellId1 });
+
+ const { result } = renderWithProvider(() => useIsCellSelected(cellId1));
+
+ expect(result.current).toBe(true);
+ });
+
+ it("should indicate cell is not selected when not in selection", () => {
+ // Set up selection that doesn't include cellId2
+ const selectionActions = setupSelection();
+ selectionActions.select({ cellId: cellId1 });
+
+ const { result } = renderWithProvider(() => useIsCellSelected(cellId2));
+
+ expect(result.current).toBe(false);
+ });
+
+ it("should clear selection when moving with Ctrl+Up", () => {
+ // Set up selection
+ 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: "ArrowUp", ctrlKey: true });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockCellActions.focusTopCell).toHaveBeenCalled();
+
+ // Check that selection is cleared
+ const { result: selectionResult } = renderWithProvider(() =>
+ useCellSelectionState(),
+ );
+ expect(selectionResult.current.selected.size).toBe(0);
+ });
+
+ it("should clear selection when moving with Ctrl+Down", () => {
+ // Set up selection
+ 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: "ArrowDown",
+ ctrlKey: true,
+ });
+
+ act(() => {
+ result.current.onKeyDown?.(mockEvent);
+ });
+
+ expect(mockCellActions.focusBottomCell).toHaveBeenCalled();
+
+ // Check that selection is cleared
+ const { result: selectionResult } = renderWithProvider(() =>
+ useCellSelectionState(),
+ );
+ expect(selectionResult.current.selected.size).toBe(0);
+ });
+ });
});
describe("useCellEditorNavigationProps", () => {
- const mockCellId = "test-cell-id" as CellId;
-
beforeEach(() => {
vi.clearAllMocks();
});
describe("keyboard shortcuts", () => {
it("should focus cell when Escape is pressed", () => {
- const { result } = renderHook(() =>
+ const { result } = renderWithProvider(() =>
useCellEditorNavigationProps(mockCellId),
);
const mockEvent = Mocks.keyboardEvent({ key: "Escape" });
act(() => {
- if (result.current.onKeyDown) {
- result.current.onKeyDown(mockEvent);
- }
+ result.current.onKeyDown?.(mockEvent);
});
expect(focusCell).toHaveBeenCalledWith(mockCellId);
@@ -415,16 +991,14 @@ describe("useCellEditorNavigationProps", () => {
});
it("should continue propagation for other keys", () => {
- const { result } = renderHook(() =>
+ const { result } = renderWithProvider(() =>
useCellEditorNavigationProps(mockCellId),
);
const mockEvent = Mocks.keyboardEvent({ key: "Enter" });
act(() => {
- if (result.current.onKeyDown) {
- result.current.onKeyDown(mockEvent);
- }
+ result.current.onKeyDown?.(mockEvent);
});
expect(focusCell).not.toHaveBeenCalled();
diff --git a/frontend/src/components/editor/navigation/__tests__/selection.test.ts b/frontend/src/components/editor/navigation/__tests__/selection.test.ts
new file mode 100644
index 0000000000..5991ac2a36
--- /dev/null
+++ b/frontend/src/components/editor/navigation/__tests__/selection.test.ts
@@ -0,0 +1,194 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { beforeEach, describe, expect, it } from "vitest";
+import type { CellId } from "@/core/cells/ids";
+import { MultiColumn } from "@/utils/id-tree";
+import type { CellSelectionState } from "../selection";
+import { exportedForTesting } from "../selection";
+
+const { initialState, reducer, createActions } = exportedForTesting;
+
+const CellIds = {
+ a: "a" as CellId,
+ b: "b" as CellId,
+ c: "c" as CellId,
+ d: "d" as CellId,
+ e: "e" as CellId,
+};
+
+describe("cell selection reducer", () => {
+ let state: CellSelectionState;
+
+ const actions = createActions((action) => {
+ state = reducer(state, action);
+ });
+
+ beforeEach(() => {
+ state = initialState();
+ });
+
+ it("should have initial state", () => {
+ expect(state).toEqual({
+ selectionStart: null,
+ selectionEnd: null,
+ selected: new Set(),
+ });
+ });
+
+ it("should select a single cell", () => {
+ actions.select({ cellId: CellIds.a });
+
+ expect(state).toEqual({
+ selectionStart: CellIds.a,
+ selectionEnd: CellIds.a,
+ selected: new Set([CellIds.a]),
+ });
+ });
+
+ it("should replace selection when selecting a different cell", () => {
+ actions.select({ cellId: CellIds.a });
+ actions.select({ cellId: CellIds.b });
+
+ expect(state).toEqual({
+ selectionStart: CellIds.b,
+ selectionEnd: CellIds.b,
+ selected: new Set([CellIds.b]),
+ });
+ });
+
+ it("should extend selection forward", () => {
+ const allCellIds = MultiColumn.from([
+ [CellIds.a, CellIds.b, CellIds.c, CellIds.d],
+ ]);
+
+ // First select cell a
+ actions.select({ cellId: CellIds.a });
+
+ // Then extend to cell c
+ actions.extend({ cellId: CellIds.c, allCellIds });
+
+ expect(state).toEqual({
+ selectionStart: CellIds.a,
+ selectionEnd: CellIds.c,
+ selected: new Set([CellIds.a, CellIds.b, CellIds.c]),
+ });
+ });
+
+ it("should extend selection backward", () => {
+ const allCellIds = MultiColumn.from([
+ [CellIds.a, CellIds.b, CellIds.c, CellIds.d],
+ ]);
+
+ // First select cell c
+ actions.select({ cellId: CellIds.c });
+
+ // Then extend to cell a (backward)
+ actions.extend({ cellId: CellIds.a, allCellIds });
+
+ expect(state).toEqual({
+ selectionStart: CellIds.c,
+ selectionEnd: CellIds.a,
+ selected: new Set([CellIds.a, CellIds.b, CellIds.c]),
+ });
+ });
+
+ it("should extend selection to same cell", () => {
+ const allCellIds = MultiColumn.from([[CellIds.a, CellIds.b, CellIds.c]]);
+
+ // First select cell b
+ actions.select({ cellId: CellIds.b });
+
+ // Then extend to same cell
+ actions.extend({ cellId: CellIds.b, allCellIds });
+
+ expect(state).toEqual({
+ selectionStart: CellIds.b,
+ selectionEnd: CellIds.b,
+ selected: new Set([CellIds.b]),
+ });
+ });
+
+ it("should fallback to single select when extending without selectionStart", () => {
+ const allCellIds = MultiColumn.from([[CellIds.a, CellIds.b, CellIds.c]]);
+
+ // Try to extend without any previous selection
+ actions.extend({ cellId: CellIds.b, allCellIds });
+
+ expect(state).toEqual({
+ selectionStart: CellIds.b,
+ selectionEnd: CellIds.b,
+ selected: new Set([CellIds.b]),
+ });
+ });
+
+ it("should fallback to single select when extending with invalid cell ids", () => {
+ const allCellIds = MultiColumn.from([[CellIds.a, CellIds.b, CellIds.c]]);
+
+ // Create a state with invalid selection start (not in allCellIds)
+ const invalidState = {
+ selectionStart: CellIds.d, // not in allCellIds
+ selectionEnd: CellIds.d,
+ selected: new Set([CellIds.d]),
+ };
+
+ // Test reducer directly since we need to start with custom state
+ const result = reducer(invalidState, {
+ type: "extend",
+ payload: { cellId: CellIds.b, allCellIds },
+ });
+
+ expect(result).toEqual({
+ selectionStart: CellIds.b,
+ selectionEnd: CellIds.b,
+ selected: new Set([CellIds.b]),
+ });
+ });
+
+ it("should clear selection", () => {
+ // First select some cells
+ actions.select({ cellId: CellIds.a });
+ expect(state.selected.size).toBe(1);
+
+ // Then clear
+ actions.clear();
+
+ expect(state).toEqual({
+ selectionStart: null,
+ selectionEnd: null,
+ selected: new Set(),
+ });
+ });
+
+ it("should handle clearing already empty selection", () => {
+ // Clear when already empty
+ actions.clear();
+
+ expect(state).toEqual({
+ selectionStart: null,
+ selectionEnd: null,
+ selected: new Set(),
+ });
+ });
+
+ it("should handle complex selection scenarios", () => {
+ const allCellIds = MultiColumn.from([
+ [CellIds.a, CellIds.b, CellIds.c, CellIds.d, CellIds.e],
+ ]);
+
+ // Select middle cell
+ actions.select({ cellId: CellIds.c });
+
+ // Extend to end
+ actions.extend({ cellId: CellIds.e, allCellIds });
+ expect(state.selected).toEqual(new Set([CellIds.c, CellIds.d, CellIds.e]));
+
+ // Extend to beginning (should reverse)
+ actions.extend({ cellId: CellIds.a, allCellIds });
+ expect(state.selected).toEqual(new Set([CellIds.a, CellIds.b, CellIds.c]));
+ expect(state.selectionStart).toBe(CellIds.c);
+ expect(state.selectionEnd).toBe(CellIds.a);
+
+ // Clear everything
+ actions.clear();
+ expect(state.selected.size).toBe(0);
+ });
+});
diff --git a/frontend/src/components/editor/navigation/clipboard.ts b/frontend/src/components/editor/navigation/clipboard.ts
index 8aed9479f8..981df74678 100644
--- a/frontend/src/components/editor/navigation/clipboard.ts
+++ b/frontend/src/components/editor/navigation/clipboard.ts
@@ -10,12 +10,18 @@ import { Logger } from "@/utils/Logger";
const MARIMO_CELL_MIMETYPE = "application/x-marimo-cell";
interface ClipboardCellData {
- code: string;
+ cells: Array<{
+ code: string;
+ }>;
version: "1.0";
}
const ClipboardCellDataSchema = z.object({
- code: z.string(),
+ cells: z.array(
+ z.object({
+ code: z.string(),
+ }),
+ ),
version: z.literal("1.0"),
});
@@ -28,12 +34,16 @@ const ClipboardCellDataSchema = z.object({
export function useCellClipboard() {
const actions = useCellActions();
- const copyCell = useEvent(async (cellId: CellId) => {
- const cellData = getNotebook().cellData[cellId];
- if (!cellData) {
+ const copyCells = useEvent(async (cellIds: CellId[]) => {
+ const notebook = getNotebook();
+ const cells = cellIds
+ .map((cellId) => notebook.cellData[cellId])
+ .filter(Boolean);
+
+ if (cells.length === 0) {
toast({
title: "Error",
- description: "Cell not found",
+ description: "No cells found",
variant: "danger",
});
return;
@@ -41,47 +51,55 @@ export function useCellClipboard() {
try {
const clipboardData: ClipboardCellData = {
- code: cellData.code,
+ 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 ClipboardItem({
[MARIMO_CELL_MIMETYPE]: new Blob([JSON.stringify(clipboardData)], {
type: MARIMO_CELL_MIMETYPE,
}),
- "text/plain": new Blob([cellData.code], {
+ "text/plain": new Blob([plainText], {
type: "text/plain",
}),
});
await navigator.clipboard.write([clipboardItem]);
+ const cellText = cells.length === 1 ? "Cell" : `${cells.length} cells`;
toast({
- title: "Cell copied",
- description: "Cell has been copied to clipboard",
+ title: `${cellText} copied`,
+ description: `${cellText} ${cells.length === 1 ? "has" : "have"} been copied to clipboard`,
});
} catch (error) {
- Logger.error("Failed to copy cell to clipboard", error);
+ Logger.error("Failed to copy cells to clipboard", error);
// Fallback to simple text copy
try {
- await navigator.clipboard.writeText(cellData.code);
+ const plainText = cells.map((cell) => cell.code).join("\n\n");
+ await navigator.clipboard.writeText(plainText);
+ const cellText = cells.length === 1 ? "Cell" : `${cells.length} cells`;
toast({
- title: "Cell copied",
- description: "Cell code has been copied to clipboard",
+ title: `${cellText} copied`,
+ description: `${cellText} code ${cells.length === 1 ? "has" : "have"} been copied to clipboard`,
});
} catch {
toast({
title: "Copy failed",
- description: "Failed to copy cell to clipboard",
+ description: "Failed to copy cells to clipboard",
variant: "danger",
});
}
}
});
- const pasteCell = useEvent(async (cellId: CellId) => {
+ const pasteAtCell = useEvent(async (cellId: CellId) => {
try {
const clipboardItems = await navigator.clipboard.read();
@@ -96,14 +114,29 @@ export function useCellClipboard() {
JSON.parse(text),
);
- // Create a new cell with the copied data after the current cell
- // We don't use name or config yet, as it may not be desired or make sense to copy over as well.
- actions.createNewCell({
- cellId,
- before: false,
- code: clipboardData.code,
- autoFocus: true,
- });
+ // If cells array is empty, fall through to plain text
+ if (clipboardData.cells.length === 0) {
+ break;
+ }
+
+ // Create new cells with the copied data after the current cell
+ const currentCellId = cellId;
+ for (const cell of clipboardData.cells) {
+ actions.createNewCell({
+ cellId: currentCellId,
+ before: false,
+ code: cell.code,
+ autoFocus: false,
+ });
+ // Update currentCellId to the newly created cell for chaining
+ // Note: We don't have the new cell ID here, but createNewCell handles the positioning
+ }
+
+ // Focus the last created cell
+ if (clipboardData.cells.length > 0) {
+ // The focus will be handled by the cell creation logic
+ }
+
return;
} catch (parseError) {
Logger.warn("Failed to parse clipboard cell data", parseError);
@@ -138,7 +171,7 @@ export function useCellClipboard() {
});
return {
- copyCell,
- pasteCell,
+ copyCells,
+ pasteAtCell,
};
}
diff --git a/frontend/src/components/editor/navigation/multi-cell-action-toolbar.tsx b/frontend/src/components/editor/navigation/multi-cell-action-toolbar.tsx
new file mode 100644
index 0000000000..3bd44c7232
--- /dev/null
+++ b/frontend/src/components/editor/navigation/multi-cell-action-toolbar.tsx
@@ -0,0 +1,336 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import type { EditorView } from "@codemirror/view";
+import { useAtomValue } from "jotai";
+import {
+ ChevronDownIcon,
+ ChevronUpIcon,
+ Code2Icon,
+ EyeIcon,
+ EyeOffIcon,
+ MoreHorizontalIcon,
+ PlayIcon,
+ Trash2Icon,
+ XCircleIcon,
+ ZapIcon,
+ ZapOffIcon,
+} from "lucide-react";
+import React from "react";
+import useEvent from "react-use-event-hook";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import {
+ getCellEditorView,
+ hasOnlyOneCellAtom,
+ notebookAtom,
+ useCellActions,
+} from "@/core/cells/cells";
+import type { CellId } from "@/core/cells/ids";
+import { formatEditorViews } from "@/core/codemirror/format";
+import { saveCellConfig } from "@/core/network/requests";
+import type { CellConfig } from "@/core/network/types";
+import { store } from "@/core/state/jotai";
+import { useEventListener } from "@/hooks/useEventListener";
+import type { ActionButton } from "../actions/types";
+import { useDeleteManyCellsCallback } from "../cell/useDeleteCell";
+import { useRunCells } from "../cell/useRunCells";
+import { useCellSelectionActions, useCellSelectionState } from "./selection";
+
+interface MultiCellActionButton extends Omit<ActionButton, "handle"> {
+ handle: (selectedCells: CellId[]) => void;
+}
+
+const CellStateDropdown: React.FC<{
+ actions: MultiCellActionButton[][];
+ cellIds: CellId[];
+}> = ({ actions, cellIds }) => {
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild={true}>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-8 px-2 gap-1"
+ title="More actions"
+ >
+ <MoreHorizontalIcon size={13} strokeWidth={1.5} />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" data-keep-cell-selection={true}>
+ {actions.flatMap((group, index) => {
+ const groupItems = group.map((action) => {
+ return (
+ <DropdownMenuItem
+ key={action.label}
+ onSelect={() => action.handle(cellIds)}
+ className="flex items-center gap-2"
+ >
+ <div className="flex items-center gap-2">
+ {action.icon}
+ <span className="text-xs">{action.label}</span>
+ </div>
+ </DropdownMenuItem>
+ );
+ });
+ return (
+ <React.Fragment key={index}>
+ {groupItems}
+ {index < actions.length - 1 && <DropdownMenuSeparator />}
+ </React.Fragment>
+ );
+ })}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+};
+
+export function useMultiCellActionButtons(cellIds: CellId[]) {
+ const { updateCellConfig, moveCell, clearCellOutput } = useCellActions();
+ const deleteCell = useDeleteManyCellsCallback();
+ const hasOnlyOneCell = useAtomValue(hasOnlyOneCellAtom);
+ const selectionActions = useCellSelectionActions();
+ const runCells = useRunCells();
+
+ const selectedCount = cellIds.length;
+
+ const canDelete = !hasOnlyOneCell || selectedCount < cellIds.length;
+
+ const deleteSelectedCells = useEvent((cellIds: CellId[]) => {
+ deleteCell({ cellIds });
+ selectionActions.clear();
+ });
+
+ const moveSelectedCells = useEvent(
+ (cellIds: CellId[], direction: "up" | "down") => {
+ /// If moving down, make sure the last cell is not at the bottom of the notebook
+ if (direction === "down") {
+ const lastCellId = cellIds[cellIds.length - 1];
+ const notebook = store.get(notebookAtom);
+ const isLast =
+ notebook.cellIds.findWithId(lastCellId).last() === lastCellId;
+ if (isLast) {
+ return;
+ }
+ }
+
+ // If moving up, make sure the first cell is not at the top of the notebook
+ if (direction === "up") {
+ const firstCellId = cellIds[0];
+ const notebook = store.get(notebookAtom);
+ const isFirst =
+ notebook.cellIds.findWithId(firstCellId).first() === firstCellId;
+ if (isFirst) {
+ return;
+ }
+ }
+
+ // Move cells in the appropriate order to maintain relative positions
+ const sortedCells = direction === "up" ? cellIds : [...cellIds].reverse();
+ sortedCells.forEach((cellId) => {
+ moveCell({ cellId, before: direction === "up" });
+ });
+ },
+ );
+
+ const formatSelectedCells = useEvent((cellIds: CellId[]) => {
+ const editorViews: Record<CellId, EditorView> = {};
+ cellIds.forEach((cellId) => {
+ const editorView = getCellEditorView(cellId);
+ if (editorView) {
+ editorViews[cellId] = editorView;
+ }
+ });
+ formatEditorViews(editorViews);
+ });
+
+ const clearSelectedCellsOutput = useEvent((cellIds: CellId[]) => {
+ cellIds.forEach((cellId) => {
+ clearCellOutput({ cellId });
+ });
+ });
+
+ const toggleSelectedCellsProperty = useEvent(
+ async (cellIds: CellId[], property: keyof CellConfig, value: boolean) => {
+ const configs: Record<CellId, Partial<CellConfig>> = {};
+ cellIds.forEach((cellId) => {
+ configs[cellId] = { [property]: value };
+ });
+
+ await saveCellConfig({ configs });
+
+ cellIds.forEach((cellId) => {
+ updateCellConfig({ cellId, config: configs[cellId] });
+ });
+ },
+ );
+
+ const actions: MultiCellActionButton[][] = [
+ [
+ {
+ icon: <PlayIcon size={13} strokeWidth={1.5} />,
+ label: "Run cells",
+ handle: (cellIds) => runCells(cellIds),
+ },
+ ],
+ [
+ {
+ icon: <ChevronUpIcon size={13} strokeWidth={1.5} />,
+ label: "Move up",
+ handle: (cellIds) => moveSelectedCells(cellIds, "up"),
+ },
+ {
+ icon: <ChevronDownIcon size={13} strokeWidth={1.5} />,
+ label: "Move down",
+ handle: (cellIds) => moveSelectedCells(cellIds, "down"),
+ },
+ ],
+ [
+ {
+ icon: <Trash2Icon size={13} strokeWidth={1.5} />,
+ label: "Delete cells",
+ variant: "danger",
+ hidden: !canDelete,
+ handle: deleteSelectedCells,
+ },
+ ],
+ ];
+
+ const moreActions: MultiCellActionButton[][] = [
+ [
+ {
+ icon: <Code2Icon size={13} strokeWidth={1.5} />,
+ label: "Format cells",
+ handle: formatSelectedCells,
+ },
+ {
+ icon: <XCircleIcon size={13} strokeWidth={1.5} />,
+ label: "Clear outputs",
+ handle: clearSelectedCellsOutput,
+ },
+ ],
+ [
+ {
+ icon: <EyeOffIcon size={13} strokeWidth={1.5} />,
+ label: "Hide cells",
+ handle: (cellIds) =>
+ toggleSelectedCellsProperty(cellIds, "hide_code", true),
+ },
+ {
+ icon: <EyeIcon size={13} strokeWidth={1.5} />,
+ label: "Show cells",
+ handle: (cellIds) =>
+ toggleSelectedCellsProperty(cellIds, "hide_code", false),
+ },
+ ],
+ [
+ {
+ icon: <ZapOffIcon size={13} strokeWidth={1.5} />,
+ label: "Disable cells",
+ handle: (cellIds) =>
+ toggleSelectedCellsProperty(cellIds, "disabled", true),
+ },
+ {
+ icon: <ZapIcon size={13} strokeWidth={1.5} />,
+ label: "Enable cells",
+ handle: (cellIds) =>
+ toggleSelectedCellsProperty(cellIds, "disabled", false),
+ },
+ ],
+ ];
+
+ // Filter out hidden actions and empty groups
+ return {
+ actions: actions
+ .map((group) => group.filter((action) => !action.hidden))
+ .filter((group) => group.length > 0),
+ moreActions: moreActions
+ .map((group) => group.filter((action) => !action.hidden))
+ .filter((group) => group.length > 0),
+ };
+}
+
+export const MultiCellActionToolbar = () => {
+ const selectionState = useCellSelectionState();
+ const selectedCells = [...selectionState.selected];
+
+ if (selectedCells.length < 2) {
+ return null;
+ }
+
+ return <MultiCellActionToolbarInternal cellIds={selectedCells} />;
+};
+
+const Separator = () => <div className="h-4 w-px bg-border mx-1" />;
+
+const MultiCellActionToolbarInternal = ({ cellIds }: { cellIds: CellId[] }) => {
+ const selectionActions = useCellSelectionActions();
+ const { actions, moreActions } = useMultiCellActionButtons(cellIds);
+
+ const selectedCount = cellIds.length;
+
+ useEventListener(window, "mousedown", (evt) => {
+ // Clear selected, unless clicked inside an element that contains data-keep-cell-selection
+ if (
+ (evt.target instanceof HTMLElement || evt.target instanceof SVGElement) &&
+ evt.target.closest("[data-keep-cell-selection]") !== null
+ ) {
+ return;
+ }
+
+ // HACK: evt.target is the root <html> element
+ // when the DropdownMenu is closed.
+ // This prevents the selection from being cleared when the opens/closes
+ // the DropdownMenu.
+ if (evt.target instanceof HTMLHtmlElement) {
+ return;
+ }
+ selectionActions.clear();
+ });
+
+ return (
+ <div
+ className="fixed top-12 justify-center flex w-full left-0 right-0 z-50"
+ data-keep-cell-selection={true}
+ >
+ <div className="bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 border border-[var(--slate-7)] rounded-lg shadow-lg p-2 overflow-x-auto overflow-y-hidden mx-20 scrollbar-thin">
+ <div className="flex items-center gap-1">
+ <span className="text-sm font-medium text-muted-foreground px-2 flex-shrink-0">
+ {selectedCount} cells selected
+ </span>
+ <Separator />
+ {actions.map((group, groupIndex) => (
+ <div
+ key={groupIndex}
+ className="flex items-center gap-2 flex-shrink-0"
+ >
+ {group.map((action) => (
+ <Button
+ key={action.label}
+ variant={
+ action.variant === "danger" ? "linkDestructive" : "ghost"
+ }
+ size="sm"
+ onClick={() => action.handle(cellIds)}
+ className="h-8 px-2 gap-1 flex-shrink-0"
+ title={action.label}
+ >
+ {action.icon}
+ <span className="text-xs">{action.label}</span>
+ </Button>
+ ))}
+ {groupIndex < actions.length - 1 && <Separator />}
+ </div>
+ ))}
+ <Separator />
+ <CellStateDropdown actions={moreActions} cellIds={cellIds} />
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/editor/navigation/navigation.ts b/frontend/src/components/editor/navigation/navigation.ts
index eabd8bfa88..a48540d462 100644
--- a/frontend/src/components/editor/navigation/navigation.ts
+++ b/frontend/src/components/editor/navigation/navigation.ts
@@ -4,7 +4,7 @@ import type { EditorView } from "@codemirror/view";
import { useAtomValue, useSetAtom, useStore } from "jotai";
import { mergeProps, useFocusWithin, useKeyboard } from "react-aria";
import { aiCompletionCellAtom } from "@/core/ai/state";
-import { notebookAtom, useCellActions } from "@/core/cells/cells";
+import { cellIdsAtom, notebookAtom, useCellActions } from "@/core/cells/cells";
import { useSetLastFocusedCellId } from "@/core/cells/focus";
import type { CellId } from "@/core/cells/ids";
import { hotkeysAtom, keymapPresetAtom } from "@/core/config/config";
@@ -15,9 +15,14 @@ import { useSaveNotebook } from "@/core/saving/save-component";
import { derefNotNull } from "@/utils/dereference";
import { Events } from "@/utils/events";
import type { CellActionsDropdownHandle } from "../cell/cell-actions";
-import { useRunCell } from "../cell/useRunCells";
+import { useRunCells } from "../cell/useRunCells";
import { useCellClipboard } from "./clipboard";
import { focusCell, focusCellEditor } from "./focus-utils";
+import {
+ getSelectedCells,
+ useCellSelectionActions,
+ useIsCellSelected,
+} from "./selection";
import { temporarilyShownCodeAtom } from "./state";
interface HotkeyHandler {
@@ -27,10 +32,11 @@ interface HotkeyHandler {
/**
* Wraps a hotkey handler to support bulk handling.
- *
* If a handler fails mid-way, the bulk handling will stop.
+ *
+ * Use this utility if the bulk handler is the same as handling each cell individually.
*/
-function supportBulkHandle(handler: HotkeyHandler["handle"]): HotkeyHandler {
+function addBulkHandler(handler: HotkeyHandler["handle"]): HotkeyHandler {
return {
handle: (cellId) => {
return handler(cellId);
@@ -49,6 +55,22 @@ function supportBulkHandle(handler: HotkeyHandler["handle"]): HotkeyHandler {
};
}
+/**
+ * Wraps a bulk handler to support single-cell handling.
+ *
+ * Use this utility if the single-cell handler is the same as a single-cell bulk handler.
+ */
+function addSingleHandler(handler: HotkeyHandler["bulkHandle"]): HotkeyHandler {
+ return {
+ handle: (cellId) => {
+ return handler([cellId]);
+ },
+ bulkHandle: (cellIds) => {
+ return handler(cellIds);
+ },
+ };
+}
+
function useCellFocusProps(cellId: CellId) {
const setLastFocusedCellId = useSetLastFocusedCellId();
const actions = useCellActions();
@@ -70,6 +92,8 @@ function useCellFocusProps(cellId: CellId) {
return focusWithinProps;
}
+type KeymapHandlers = Record<string, () => boolean>;
+
/**
* Props for cell keyboard navigation,
* to manage focus and selection.
@@ -96,9 +120,12 @@ export function useCellNavigationProps(
const actions = useCellActions();
const store = useStore();
const setTemporarilyShownCode = useSetAtom(temporarilyShownCodeAtom);
- const runCell = useRunCell(cellId);
+ const runCells = useRunCells();
const keymapPreset = useAtomValue(keymapPresetAtom);
- const { copyCell, pasteCell } = useCellClipboard();
+ const { copyCells, pasteAtCell } = useCellClipboard();
+ const selectionActions = useCellSelectionActions();
+ const isSelected = useIsCellSelected(cellId);
+
const hotkeys = useAtomValue(hotkeysAtom);
const isShortcutPressed = (
@@ -117,42 +144,89 @@ export function useCellNavigationProps(
return;
}
- // Mod+Up/Down moves to the top/bottom of the notebook.
- if (Events.isMetaOrCtrl(evt)) {
- if (evt.key === "ArrowUp") {
+ const keymaps = {
+ // Move to the top of the notebook.
+ "Mod+ArrowUp": () => {
actions.focusTopCell();
- return;
- }
- if (evt.key === "ArrowDown") {
+ selectionActions.clear();
+ return true;
+ },
+ // Move to the bottom of the notebook.
+ "Mod+ArrowDown": () => {
actions.focusBottomCell();
- return;
- }
- }
-
- // Enter will focus the cell editor.
- if (evt.key === "Enter" && !Events.hasModifier(evt)) {
- setTemporarilyShownCode(true);
- focusCellEditor(store, cellId);
- // Prevent default to prevent an new line from being created.
- evt.preventDefault();
- return;
- }
-
- // Saving
- if (evt.key === "s" && !Events.hasModifier(evt)) {
- saveOrNameNotebook();
- return;
- }
-
- // j/k movement in vim mode.
- if (keymapPreset === "vim") {
- if (evt.key === "j" && !Events.hasModifier(evt)) {
+ selectionActions.clear();
+ return true;
+ },
+ // Move up
+ ArrowUp: () => {
+ actions.focusCell({ cellId, before: true });
+ selectionActions.clear();
+ return true;
+ },
+ // Move down
+ ArrowDown: () => {
actions.focusCell({ cellId, before: false });
- return;
- }
- if (evt.key === "k" && !Events.hasModifier(evt)) {
+ selectionActions.clear();
+ return true;
+ },
+ // Select up
+ "Shift+ArrowUp": () => {
+ // Select self
+ const allCellIds = store.get(cellIdsAtom);
+ selectionActions.extend({ cellId, allCellIds });
+ // Select to where focus is going
+ const beforeCellId = allCellIds.findWithId(cellId).before(cellId);
+ if (beforeCellId) {
+ selectionActions.extend({ cellId: beforeCellId, allCellIds });
+ }
+ // Focus the cell
actions.focusCell({ cellId, before: true });
- return;
+ return true;
+ },
+ // Select down
+ "Shift+ArrowDown": () => {
+ // Select self
+ const allCellIds = store.get(cellIdsAtom);
+ selectionActions.extend({ cellId, allCellIds });
+ // Select to where focus is going
+ const afterCellId = allCellIds.findWithId(cellId).after(cellId);
+ if (afterCellId) {
+ selectionActions.extend({ cellId: afterCellId, allCellIds });
+ }
+ // Focus the cell
+ actions.focusCell({ cellId, before: false });
+ return true;
+ },
+ // Clear selection
+ Escape: () => {
+ if (isSelected) {
+ selectionActions.clear();
+ return true;
+ }
+ return false;
+ },
+ // Enter will focus the cell editor.
+ Enter: () => {
+ setTemporarilyShownCode(true);
+ focusCellEditor(store, cellId);
+ selectionActions.clear();
+ return true;
+ },
+ // Command mode: Saving
+ s: () => {
+ saveOrNameNotebook();
+ return true;
+ },
+ } satisfies KeymapHandlers;
+
+ // Handle keymaps.
+ for (const [key, handler] of Object.entries(keymaps)) {
+ if (parseShortcut(key)(evt)) {
+ const success = handler();
+ if (success) {
+ evt.preventDefault();
+ return;
+ }
}
if (evt.key === "i" && !Events.hasModifier(evt)) {
setTemporarilyShownCode(true);
@@ -162,15 +236,24 @@ export function useCellNavigationProps(
}
}
- // Down arrow moves to the next cell.
- if (evt.key === "ArrowDown" && !Events.hasModifier(evt)) {
- actions.focusCell({ cellId, before: false });
- return;
- }
- // Up arrow moves to the previous cell.
- if (evt.key === "ArrowUp" && !Events.hasModifier(evt)) {
- actions.focusCell({ cellId, before: true });
- return;
+ // Keymaps when using vim.
+ if (keymapPreset === "vim") {
+ const vimKeymaps = {
+ j: keymaps.ArrowDown,
+ k: keymaps.ArrowUp,
+ "Shift+j": keymaps["Shift+ArrowDown"],
+ "Shift+k": keymaps["Shift+ArrowUp"],
+ } satisfies KeymapHandlers;
+
+ for (const [key, handler] of Object.entries(vimKeymaps)) {
+ if (parseShortcut(key)(evt)) {
+ const success = handler();
+ if (success) {
+ evt.preventDefault();
+ return;
+ }
+ }
+ }
}
// Shortcuts
@@ -178,20 +261,22 @@ export function useCellNavigationProps(
Record<HotkeyAction, HotkeyHandler["handle"] | HotkeyHandler>
> = {
// Cell actions
- "cell.run": () => {
- runCell();
+ "cell.run": addSingleHandler((cellIds) => {
+ runCells(cellIds);
return true;
- },
- "cell.runAndNewBelow": (cellId) => {
- runCell();
- actions.moveToNextCell({ cellId, before: false });
+ }),
+ "cell.runAndNewBelow": addSingleHandler((cellIds) => {
+ runCells(cellIds);
+ const lastCellId = cellIds[cellIds.length - 1];
+ actions.moveToNextCell({ cellId: lastCellId, before: false });
return true;
- },
- "cell.runAndNewAbove": () => {
- runCell();
- actions.moveToNextCell({ cellId, before: true });
+ }),
+ "cell.runAndNewAbove": addSingleHandler((cellIds) => {
+ runCells(cellIds);
+ const firstCellId = cellIds[0];
+ actions.moveToNextCell({ cellId: firstCellId, before: true });
return true;
- },
+ }),
"cell.createAbove": (cellId) => {
actions.createNewCell({ cellId, before: true });
return true;
@@ -200,50 +285,93 @@ export function useCellNavigationProps(
actions.createNewCell({ cellId, before: false });
return true;
},
- "cell.moveUp": (cellId) => {
- actions.moveCell({ cellId, before: true });
+ "cell.moveUp": addSingleHandler((cellIds) => {
+ // If moving up, make sure the first cell is not at the top of the notebook
+ const firstCellId = cellIds[0];
+ const notebook = store.get(notebookAtom);
+ const isFirst =
+ notebook.cellIds.findWithId(firstCellId).first() === firstCellId;
+ if (isFirst) {
+ return false;
+ }
+
+ cellIds.forEach((cellId) => {
+ actions.moveCell({ cellId, before: true });
+ });
return true;
- },
- "cell.moveDown": (cellId) => {
- actions.moveCell({ cellId, before: false });
+ }),
+ "cell.moveDown": addSingleHandler((cellIds) => {
+ // If moving down, make sure the last cell is not at the bottom of the notebook
+ const lastCellId = cellIds[cellIds.length - 1];
+ const notebook = store.get(notebookAtom);
+ const isLast =
+ notebook.cellIds.findWithId(lastCellId).last() === lastCellId;
+ if (isLast) {
+ return false;
+ }
+
+ // Move cells in the appropriate order to maintain relative positions
+ [...cellIds].reverse().forEach((cellId) => {
+ actions.moveCell({ cellId, before: false });
+ });
return true;
- },
- "cell.moveLeft": (cellId) => {
+ }),
+ "cell.moveLeft": addBulkHandler((cellId) => {
if (canMoveX) {
actions.moveCell({ cellId, direction: "left" });
return true;
}
return false;
- },
- "cell.moveRight": (cellId) => {
+ }),
+ "cell.moveRight": addBulkHandler((cellId) => {
if (canMoveX) {
actions.moveCell({ cellId, direction: "right" });
return true;
}
return false;
- },
- "cell.hideCode": supportBulkHandle((cellId) => {
- const cellConfig = store.get(notebookAtom).cellData[cellId]?.config;
- if (!cellConfig) {
- return false;
- }
- const nextHideCode = !cellConfig.hide_code;
+ }),
+ "cell.hideCode": addSingleHandler((cellIds) => {
+ // Get the cell configs
+ const cellConfigs = cellIds.map((cellId) => {
+ const cellConfig = store.get(notebookAtom).cellData[cellId]?.config;
+ if (!cellConfig) {
+ return null;
+ }
+ return cellConfig;
+ });
+
+ // Toggle to the same value for all cells
+ const nextHideCode = !cellConfigs.every(
+ (config) => config?.hide_code,
+ );
+
// Fire-and-forget
void saveCellConfig({
- configs: { [cellId]: { hide_code: nextHideCode } },
- });
- actions.updateCellConfig({
- cellId,
- config: { hide_code: nextHideCode },
+ configs: Object.fromEntries(
+ cellIds.map((cellId) => [cellId, { hide_code: nextHideCode }]),
+ ),
});
- actions.focusCell({ cellId, before: false });
- if (nextHideCode) {
- // Move focus from the editor to the cell
- editorView.current?.contentDOM.blur();
- focusCell(cellId);
- } else {
- focusCellEditor(store, cellId);
+
+ for (const cellId of cellIds) {
+ actions.updateCellConfig({
+ cellId,
+ config: { hide_code: nextHideCode },
+ });
}
+
+ // Only focus if it is a single cell
+ if (cellIds.length === 1) {
+ const cellId = cellIds[0];
+ actions.focusCell({ cellId, before: false });
+ if (nextHideCode) {
+ // Move focus from the editor to the cell
+ editorView.current?.contentDOM.blur();
+ focusCell(cellId);
+ } else {
+ focusCellEditor(store, cellId);
+ }
+ }
+
return true;
}),
"cell.focusDown": (cellId) => {
@@ -254,14 +382,19 @@ export function useCellNavigationProps(
actions.focusCell({ cellId, before: true });
return true;
},
- "cell.sendToBottom": (cellId) => {
- actions.sendToBottom({ cellId });
+ "cell.sendToBottom": addSingleHandler((cellIds) => {
+ cellIds.forEach((cellId) => {
+ actions.sendToBottom({ cellId });
+ });
return true;
- },
- "cell.sendToTop": (cellId) => {
- actions.sendToTop({ cellId });
+ }),
+ "cell.sendToTop": addSingleHandler((cellIds) => {
+ // Send in reverse order to maintain relative positions
+ [...cellIds].reverse().forEach((cellId) => {
+ actions.sendToTop({ cellId });
+ });
return true;
- },
+ }),
"cell.aiCompletion": (cellId) => {
let closed = false;
setAiCompletionCell((v) => {
@@ -283,12 +416,12 @@ export function useCellNavigationProps(
},
// Command mode
- "command.copyCell": () => {
- copyCell(cellId);
+ "command.copyCell": addSingleHandler((cellIds) => {
+ copyCells(cellIds);
return true;
- },
- "command.pasteCell": () => {
- pasteCell(cellId);
+ }),
+ "command.pasteCell": (cellIds) => {
+ pasteAtCell(cellIds);
return true;
},
"command.createCellBefore": (cellId) => {
@@ -307,9 +440,13 @@ export function useCellNavigationProps(
},
};
+ const selectedCells = getSelectedCells(store);
+
// Handle the shortcut
for (const [shortcut, handler] of Object.entries(shortcuts)) {
if (isShortcutPressed(shortcut as HotkeyAction, evt)) {
+ // If the handler is a function, it's a single-cell handler
+ // and we only operate on the currently focused cell.
if (handler instanceof Function) {
const success = handler(cellId);
if (success) {
@@ -317,8 +454,13 @@ export function useCellNavigationProps(
return;
}
} else {
- // TODO: Support bulk handling once we have multi-select.
- const success = handler.handle(cellId);
+ // If the handler is an object, it's supports bulk handling.
+ // If we have multiple cells selected, use the bulk handler,
+ // otherwise use the single-cell handler on the focused cell.
+ const success =
+ selectedCells.size >= 2
+ ? handler.bulkHandle([...selectedCells])
+ : handler.handle(cellId);
if (success) {
evt.preventDefault();
return;
@@ -332,7 +474,11 @@ export function useCellNavigationProps(
},
});
- return mergeProps(focusWithinProps, keyboardProps);
+ return mergeProps(focusWithinProps, keyboardProps, {
+ "data-selected": isSelected,
+ className:
+ "data-[selected=true]:ring-1 data-[selected=true]:ring-[var(--blue-8)] data-[selected=true]:ring-offset-1",
+ });
}
/**
diff --git a/frontend/src/components/editor/navigation/selection.ts b/frontend/src/components/editor/navigation/selection.ts
new file mode 100644
index 0000000000..647f082749
--- /dev/null
+++ b/frontend/src/components/editor/navigation/selection.ts
@@ -0,0 +1,114 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { atom, type createStore, useAtomValue } from "jotai";
+import { useMemo } from "react";
+import type { CellId } from "@/core/cells/ids";
+import { createReducerAndAtoms } from "@/utils/createReducer";
+import type { MultiColumn } from "@/utils/id-tree";
+
+export interface CellSelectionState {
+ selectionStart: CellId | null;
+ selectionEnd: CellId | null;
+ selected: Set<CellId>;
+}
+
+function initialState(): CellSelectionState {
+ return {
+ selectionStart: null,
+ selectionEnd: null,
+ selected: new Set(),
+ };
+}
+
+const {
+ reducer,
+ createActions,
+ valueAtom: cellSelectionAtom,
+ useActions,
+} = createReducerAndAtoms(initialState, {
+ select: (
+ _state: CellSelectionState,
+ payload: { cellId: CellId },
+ ): CellSelectionState => ({
+ selectionStart: payload.cellId,
+ selectionEnd: payload.cellId,
+ selected: new Set([payload.cellId]),
+ }),
+
+ extend: (
+ state: CellSelectionState,
+ payload: {
+ cellId: CellId;
+ allCellIds: MultiColumn<CellId>;
+ },
+ ): CellSelectionState => {
+ if (!state.selectionStart) {
+ // fallback to single select
+ return {
+ selectionStart: payload.cellId,
+ selectionEnd: payload.cellId,
+ selected: new Set([payload.cellId]),
+ };
+ }
+ const { cellId, allCellIds } = payload;
+
+ try {
+ const column = allCellIds.findWithId(state.selectionStart);
+ const startIdx = column.indexOfOrThrow(state.selectionStart);
+ const endIdx = column.indexOfOrThrow(cellId);
+ const [from, to] =
+ startIdx < endIdx ? [startIdx, endIdx] : [endIdx, startIdx];
+ const selected = column.slice(from, to + 1);
+ return {
+ selectionStart: state.selectionStart,
+ selectionEnd: cellId,
+ selected: new Set(selected),
+ };
+ } catch {
+ // fallback to single select
+ return {
+ selectionStart: cellId,
+ selectionEnd: cellId,
+ selected: new Set([cellId]),
+ };
+ }
+ },
+
+ clear: (state: CellSelectionState): CellSelectionState => {
+ if (state.selected.size === 0) {
+ // Already cleared
+ return state;
+ }
+ return initialState();
+ },
+});
+
+/**
+ * React hook to get the cell selection state.
+ */
+export const useCellSelectionState = () => useAtomValue(cellSelectionAtom);
+
+export function useIsCellSelected(cellId: CellId) {
+ const cellSelectedAtom = useMemo(
+ () => atom((get) => get(cellSelectionAtom).selected.has(cellId)),
+ [cellId],
+ );
+ return useAtomValue(cellSelectedAtom);
+}
+
+/**
+ * React hook to get the cell selection actions.
+ */
+export function useCellSelectionActions() {
+ return useActions();
+}
+
+export function getSelectedCells(store: ReturnType<typeof createStore>) {
+ return store.get(cellSelectionAtom).selected;
+}
+
+export const exportedForTesting = {
+ reducer,
+ createActions,
+ initialState,
+ cellSelectionAtom,
+};
diff --git a/frontend/src/core/edit-app.tsx b/frontend/src/core/edit-app.tsx
index 0f1505fda7..a2fe469c92 100644
--- a/frontend/src/core/edit-app.tsx
+++ b/frontend/src/core/edit-app.tsx
@@ -7,6 +7,7 @@ import { useEffect } from "react";
import { Controls } from "@/components/editor/controls/Controls";
import { AppHeader } from "@/components/editor/header/app-header";
import { FilenameForm } from "@/components/editor/header/filename-form";
+import { MultiCellActionToolbar } from "@/components/editor/navigation/multi-cell-action-toolbar";
import { sendComponentValues, sendInterrupt } from "@/core/network/requests";
import { cn } from "@/utils/cn";
import { Paths } from "@/utils/paths";
@@ -168,6 +169,8 @@ export const EditApp: React.FC<AppProps> = ({
{editableCellsArray}
</CellsRenderer>
)}
+
+ <MultiCellActionToolbar />
</AppContainer>
{!hideControls && (
<TooltipProvider>
diff --git a/frontend/src/core/hotkeys/shortcuts.ts b/frontend/src/core/hotkeys/shortcuts.ts
index 6daa00a27b..6b9ceecd53 100644
--- a/frontend/src/core/hotkeys/shortcuts.ts
+++ b/frontend/src/core/hotkeys/shortcuts.ts
@@ -21,7 +21,12 @@ export function isPlatformMac() {
return /mac/i.test(platform);
}
-function areKeysPressed(keys: string[], e: KeyboardEvent): boolean {
+type IKeyboardEvent = Pick<
+ KeyboardEvent,
+ "key" | "shiftKey" | "ctrlKey" | "metaKey" | "altKey" | "code"
+>;
+
+function areKeysPressed(keys: string[], e: IKeyboardEvent): boolean {
let satisfied = true;
for (const key of keys) {
switch (key) {
@@ -90,7 +95,7 @@ function normalizeKey(key: string): string {
*/
export function parseShortcut(
shortcut: string | typeof NOT_SET,
-): (e: KeyboardEvent) => boolean {
+): (e: IKeyboardEvent) => boolean {
// Handle empty shortcut, e.g. not set
if (shortcut === NOT_SET || shortcut === "") {
return () => false;
@@ -98,5 +103,5 @@ export function parseShortcut(
const separator = shortcut.includes("+") ? "+" : "-";
const keys = shortcut.split(separator).map(normalizeKey);
- return (e: KeyboardEvent) => areKeysPressed(keys, e);
+ return (e: IKeyboardEvent) => areKeysPressed(keys, e);
}
diff --git a/frontend/src/utils/__tests__/id-tree.test.ts b/frontend/src/utils/__tests__/id-tree.test.ts
index e670579e51..b1b4313512 100644
--- a/frontend/src/utils/__tests__/id-tree.test.ts
+++ b/frontend/src/utils/__tests__/id-tree.test.ts
@@ -481,6 +481,109 @@ describe("CollapsibleTree", () => {
expect(tree.getDescendants("three")).toMatchInlineSnapshot("[]");
});
+ it("handles slice correctly", () => {
+ // Normal slice in middle
+ expect(tree.slice(1, 3)).toEqual(["two", "three"]);
+
+ // Slice from beginning
+ expect(tree.slice(0, 2)).toEqual(["one", "two"]);
+
+ // Slice to end
+ expect(tree.slice(2, 4)).toEqual(["three", "four"]);
+
+ // Slice entire array
+ expect(tree.slice(0, 4)).toEqual(["one", "two", "three", "four"]);
+
+ // Slice with out-of-bounds end
+ expect(tree.slice(2, 10)).toEqual(["three", "four"]);
+
+ // Slice with negative start (should work like normal array slice)
+ expect(tree.slice(-2, 4)).toEqual(["three", "four"]);
+
+ // Slice with start > end (should return empty array)
+ expect(tree.slice(3, 1)).toEqual([]);
+
+ // Slice with same start and end
+ expect(tree.slice(2, 2)).toEqual([]);
+
+ // Slice single element
+ expect(tree.slice(1, 2)).toEqual(["two"]);
+ });
+
+ it("handles slice with collapsed nodes", () => {
+ const collapsed = tree.collapse("two", "three");
+
+ // Should only return top-level nodes, not descendants
+ expect(collapsed.slice(0, 2)).toEqual(["one", "two"]);
+ expect(collapsed.slice(1, 3)).toEqual(["two", "four"]);
+ });
+
+ it("handles after correctly", () => {
+ // Normal case - get next node
+ expect(tree.after("one")).toBe("two");
+ expect(tree.after("two")).toBe("three");
+ expect(tree.after("three")).toBe("four");
+
+ // Edge case - last node should return undefined
+ expect(tree.after("four")).toBeUndefined();
+
+ // Edge case - non-existent node should throw
+ expect(() => tree.after("nonexistent")).toThrow(
+ "Node nonexistent not found in tree. Valid ids: one,two,three,four",
+ );
+ });
+
+ it("handles after with collapsed nodes", () => {
+ const collapsed = tree.collapse("two", "three");
+
+ // Should return next top-level node
+ expect(collapsed.after("one")).toBe("two");
+ expect(collapsed.after("two")).toBe("four");
+ expect(collapsed.after("four")).toBeUndefined();
+
+ // Should throw for collapsed children that aren't top-level
+ expect(() => collapsed.after("three")).toThrow();
+ });
+
+ it("handles before correctly", () => {
+ // Normal case - get previous node
+ expect(tree.before("two")).toBe("one");
+ expect(tree.before("three")).toBe("two");
+ expect(tree.before("four")).toBe("three");
+
+ // Edge case - first node should return undefined
+ expect(tree.before("one")).toBeUndefined();
+
+ // Edge case - non-existent node should throw
+ expect(() => tree.before("nonexistent")).toThrow(
+ "Node nonexistent not found in tree. Valid ids: one,two,three,four",
+ );
+ });
+
+ it("handles before with collapsed nodes", () => {
+ const collapsed = tree.collapse("two", "three");
+
+ // Should return previous top-level node
+ expect(collapsed.before("two")).toBe("one");
+ expect(collapsed.before("four")).toBe("two");
+ expect(collapsed.before("one")).toBeUndefined();
+
+ // Should throw for collapsed children that aren't top-level
+ expect(() => collapsed.before("three")).toThrow();
+ });
+
+ it("handles slice on empty tree", () => {
+ const emptyTree = CollapsibleTree.from([]);
+ expect(emptyTree.slice(0, 1)).toEqual([]);
+ expect(emptyTree.slice(0, 0)).toEqual([]);
+ });
+
+ it("handles after/before on single element tree", () => {
+ const singleTree = CollapsibleTree.from(["single"]);
+ expect(singleTree.after("single")).toBeUndefined();
+ expect(singleTree.before("single")).toBeUndefined();
+ });
+
it("handles split correctly", () => {
const [left, right] = tree.split("two");
expect(left.toString()).toMatchInlineSnapshot(`
diff --git a/frontend/src/utils/id-tree.tsx b/frontend/src/utils/id-tree.tsx
index 44fafef11d..c2c6a60e2b 100644
--- a/frontend/src/utils/id-tree.tsx
+++ b/frontend/src/utils/id-tree.tsx
@@ -230,6 +230,14 @@ export class CollapsibleTree<T> {
return index as CellIndex;
}
+ /**
+ * Get the top level nodes in the given range.
+ * This does not include descendants.
+ */
+ slice(start: number, end: number): T[] {
+ return this.nodes.slice(start, end).map((n) => n.value);
+ }
+
/**
* Move the given node to the front
*/
@@ -427,6 +435,28 @@ export class CollapsibleTree<T> {
return this.atOrThrow(this.nodes.length - 1);
}
+ /**
+ * Get the next node after the given node, does not wrap.
+ */
+ after(id: T): T | undefined {
+ const index = this.indexOfOrThrow(id);
+ if (index === this.nodes.length - 1) {
+ return undefined;
+ }
+ return this.at(index + 1);
+ }
+
+ /**
+ * Get the previous node before the given node, does not wrap.
+ */
+ before(id: T): T | undefined {
+ const index = this.indexOfOrThrow(id);
+ if (index === 0) {
+ return undefined;
+ }
+ return this.at(index - 1);
+ }
+
/**
* Insert a node at the given index
*/