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: cell range selection for tables (v2) (#5296)

Shahmir Varqha9386e68adb78
diff --git a/frontend/package.json b/frontend/package.json
index 218435965d..378eabe687 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -112,6 +112,7 @@
"humanize-duration": "^3.32.1",
"iconify-icon": "^2.3.0",
"jotai": "^2.12.3",
+ "jotai-scope": "^0.7.3",
"js-cookie": "^3.0.5",
"katex": "^0.16.22",
"lodash-es": "^4.17.21",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 459cdf42a8..2fa0d3f8ed 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -312,6 +312,9 @@ importers:
jotai:
specifier: ^2.12.3
version: 2.12.3(@types/[email protected])([email protected])
+ jotai-scope:
+ specifier: ^0.7.3
js-cookie:
specifier: ^3.0.5
version: 3.0.5
@@ -6274,6 +6277,12 @@ packages:
resolution: {integrity: sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==}
hasBin: true
+ resolution: {integrity: sha512-8MSlj62XwWE/AHXU0MKpNjvrl7ZBx38B4p/3474uayljrYIQEHgZDTTjTRZqvPeG/1H+4Owod7l0OTA4ztvA+g==}
+ engines: {node: '>=12.20.0'}
+ peerDependencies:
+ jotai: '>=2.9.3'
+
resolution: {integrity: sha512-DpoddSkmPGXMFtdfnoIHfueFeGP643nqYUWC6REjUcME+PG2UkAtYnLbffRDw3OURI9ZUTcRWkRGLsOvxuWMCg==}
engines: {node: '>=12.20.0'}
@@ -16182,6 +16191,10 @@ snapshots:
+ dependencies:
+ jotai: 2.12.3(@types/[email protected])([email protected])
+
optionalDependencies:
'@types/react': 19.1.7
diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsx
index 31caf06203..7e4b31f712 100644
--- a/frontend/src/components/data-table/data-table.tsx
+++ b/frontend/src/components/data-table/data-table.tsx
@@ -35,7 +35,8 @@ import type { DownloadActionProps } from "./download-actions";
import { FilterPills } from "./filter-pills";
import { FocusRowFeature } from "./focus-row/feature";
import { useColumnPinning } from "./hooks/use-column-pinning";
-import { renderTableBody, renderTableHeader } from "./renderers";
+import { CellSelectionProvider } from "./range-focus/provider";
+import { DataTableBody, renderTableHeader } from "./renderers";
import { SearchBar } from "./SearchBar";
import { TableActions } from "./TableActions";
import type { DataTableSelection, TooManyRows } from "./types";
@@ -232,13 +233,15 @@ const DataTableInternal = <TData,>({
)}
<Table>
{renderTableHeader(table)}
- {renderTableBody(
- table,
- columns,
- rowViewerPanelOpen,
- getPaginatedRowIndex,
- viewedRowIdx,
- )}
+ <CellSelectionProvider>
+ <DataTableBody
+ table={table}
+ columns={columns}
+ rowViewerPanelOpen={rowViewerPanelOpen}
+ getRowIndex={getPaginatedRowIndex}
+ viewedRowIdx={viewedRowIdx}
+ />
+ </CellSelectionProvider>
</Table>
</div>
<TableActions
diff --git a/frontend/src/components/data-table/range-focus/__tests__/atoms.test.ts b/frontend/src/components/data-table/range-focus/__tests__/atoms.test.ts
new file mode 100644
index 0000000000..04c2fbbc82
--- /dev/null
+++ b/frontend/src/components/data-table/range-focus/__tests__/atoms.test.ts
@@ -0,0 +1,789 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import type { Cell, Row, Table } from "@tanstack/react-table";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { visibleForTesting } from "../atoms";
+
+// Mock dependencies
+vi.mock("@/utils/copy", () => ({
+ copyToClipboard: vi.fn(),
+}));
+
+vi.mock("../utils", async (importOriginal) => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const original = (await importOriginal()) as any;
+ return {
+ ...original,
+ getCellsBetween: vi.fn().mockReturnValue(["row1_col1", "row1_col2"]),
+ getCellValues: vi.fn().mockReturnValue("mocked cell values"),
+ };
+});
+
+import { copyToClipboard } from "@/utils/copy";
+import type { CellSelectionState, SelectedCell } from "../atoms";
+import {
+ createCellCopiedAtom,
+ createCellSelectedAtom,
+ createCellStateAtom,
+} from "../atoms";
+import { getCellsBetween, getCellValues } from "../utils";
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+type T = any;
+
+// Create mock table and cells
+function createMockCell(
+ rowId: string,
+ columnId: string,
+ rowIndex = 0,
+ columnIndex = 0,
+): Cell<T, unknown> {
+ const cell = {
+ id: `${rowId}_${columnId}`, // Use underscore to match actual format
+ row: {
+ id: rowId,
+ index: rowIndex,
+ getAllCells: vi.fn(),
+ } as unknown as Row<T>,
+ column: {
+ id: columnId,
+ getIndex: () => columnIndex,
+ },
+ getValue: () => `value-${rowId}-${columnId}`,
+ } as unknown as Cell<T, unknown>;
+
+ return cell;
+}
+
+function createMockTable(): Table<T> {
+ const rows = [
+ {
+ id: "row1",
+ index: 0,
+ getAllCells: () => [
+ createMockCell("row1", "col1", 0, 0),
+ createMockCell("row1", "col2", 0, 1),
+ createMockCell("row1", "col3", 0, 2),
+ ],
+ },
+ {
+ id: "row2",
+ index: 1,
+ getAllCells: () => [
+ createMockCell("row2", "col1", 1, 0),
+ createMockCell("row2", "col2", 1, 1),
+ createMockCell("row2", "col3", 1, 2),
+ ],
+ },
+ {
+ id: "row3",
+ index: 2,
+ getAllCells: () => [
+ createMockCell("row3", "col1", 2, 0),
+ createMockCell("row3", "col2", 2, 1),
+ createMockCell("row3", "col3", 2, 2),
+ ],
+ },
+ ];
+
+ const table = {
+ getRowModel: () => ({ rows }),
+ getRow: (rowId: string) => rows.find((row) => row.id === rowId),
+ } as unknown as Table<T>;
+
+ return table;
+}
+
+describe("cell selection atoms", () => {
+ let state: CellSelectionState;
+ let mockTable: Table<T>;
+ let actions: ReturnType<typeof visibleForTesting.createActions>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockTable = createMockTable();
+
+ actions = visibleForTesting.createActions((action) => {
+ state = visibleForTesting.reducer(state, action);
+ });
+
+ state = visibleForTesting.initialState();
+ });
+
+ describe("initial state", () => {
+ it("should have empty initial state", () => {
+ expect(state.selectedCells).toEqual(new Set());
+ expect(state.copiedCells).toEqual(new Set());
+ expect(state.selectedStartCell).toBeNull();
+ expect(state.focusedCell).toBeNull();
+ expect(state.isSelecting).toBe(false);
+ });
+ });
+
+ describe("basic actions", () => {
+ it("can set selected cells", () => {
+ const selectedCells = new Set(["row1_col1", "row1_col2"]);
+
+ actions.setSelectedCells(selectedCells);
+
+ expect(state.selectedCells).toEqual(selectedCells);
+ });
+
+ it("can set selected start cell", () => {
+ const startCell: SelectedCell = {
+ rowId: "row1",
+ columnId: "col1",
+ cellId: "row1_col1",
+ };
+
+ actions.setSelectedStartCell(startCell);
+
+ expect(state.selectedStartCell).toEqual(startCell);
+ });
+
+ it("can set focused cell", () => {
+ const focusedCell: SelectedCell = {
+ rowId: "row2",
+ columnId: "col2",
+ cellId: "row2_col2",
+ };
+
+ actions.setFocusedCell(focusedCell);
+
+ expect(state.focusedCell).toEqual(focusedCell);
+ });
+
+ it("can set is selecting", () => {
+ actions.setIsSelecting(true);
+ expect(state.isSelecting).toBe(true);
+
+ actions.setIsSelecting(false);
+ expect(state.isSelecting).toBe(false);
+ });
+
+ it("can set copied cells", () => {
+ const copiedCells = new Set(["row1_col1", "row2_col2"]);
+
+ actions.setCopiedCells(copiedCells);
+
+ expect(state.copiedCells).toEqual(copiedCells);
+ });
+
+ it("can clear selection", () => {
+ // Set some initial state
+ actions.setSelectedCells(new Set(["row1_col1"]));
+ actions.setSelectedStartCell({
+ rowId: "row1",
+ columnId: "col1",
+ cellId: "row1_col1",
+ });
+ actions.setFocusedCell({
+ rowId: "row1",
+ columnId: "col1",
+ cellId: "row1_col1",
+ });
+
+ // Clear selection
+ actions.clearSelection();
+
+ expect(state.selectedCells).toEqual(new Set());
+ expect(state.selectedStartCell).toBeNull();
+ expect(state.focusedCell).toBeNull();
+ });
+ });
+
+ describe("updateSelection", () => {
+ beforeEach(() => {
+ // Reset mocks before each test
+ vi.mocked(getCellsBetween).mockClear();
+ vi.mocked(getCellsBetween).mockReturnValue(["row1_col1", "row1_col2"]);
+ });
+
+ it("should update selection without shift key", () => {
+ const newCell: SelectedCell = {
+ rowId: "row1",
+ columnId: "col1",
+ cellId: "row1_col1",
+ };
+
+ actions.updateSelection({
+ newCell,
+ isShiftKey: false,
+ table: mockTable,
+ });
+
+ expect(state.selectedCells).toEqual(new Set(["row1_col1"]));
+ expect(state.selectedStartCell).toEqual(newCell);
+ expect(state.focusedCell).toEqual(newCell);
+ });
+
+ it("should update range selection with shift key", () => {
+ const startCell: SelectedCell = {
+ rowId: "row1",
+ columnId: "col1",
+ cellId: "row1_col1",
+ };
+
+ const newCell: SelectedCell = {
+ rowId: "row2",
+ columnId: "col2",
+ cellId: "row2_col2",
+ };
+
+ // First set a start cell
+ actions.setSelectedStartCell(startCell);
+
+ actions.updateSelection({
+ newCell,
+ isShiftKey: true,
+ table: mockTable,
+ });
+
+ expect(getCellsBetween).toHaveBeenCalledWith(
+ mockTable,
+ startCell,
+ newCell,
+ );
+ expect(state.selectedCells).toEqual(new Set(["row1_col1", "row1_col2"]));
+ expect(state.focusedCell).toEqual(newCell);
+ });
+
+ it("should handle shift selection without start cell", () => {
+ const newCell: SelectedCell = {
+ rowId: "row1",
+ columnId: "col1",
+ cellId: "row1_col1",
+ };
+
+ actions.updateSelection({
+ newCell,
+ isShiftKey: true,
+ table: mockTable,
+ });
+
+ // Should behave like regular selection when no start cell
+ expect(state.selectedCells).toEqual(new Set(["row1_col1"]));
+ });
+ });
+
+ describe("updateRangeSelection", () => {
+ beforeEach(() => {
+ // Reset mocks before each test
+ vi.mocked(getCellsBetween).mockClear();
+ vi.mocked(getCellsBetween).mockReturnValue(["row1_col1", "row1_col2"]);
+ });
+
+ it("should update range selection from existing start cell", () => {
+ const startCell: SelectedCell = {
+ rowId: "row1",
+ columnId: "col1",
+ cellId: "row1_col1",
+ };
+
+ const cell = createMockCell("row2", "col2", 1, 1);
+
+ // Set start cell first
+ actions.setSelectedStartCell(startCell);
+
+ actions.updateRangeSelection({
+ cell,
+ table: mockTable,
+ });
+
+ expect(getCellsBetween).toHaveBeenCalled();
+ expect(state.selectedCells).toEqual(new Set(["row1_col1", "row1_col2"]));
+ });
+
+ it("should do nothing without start cell", () => {
+ const cell = createMockCell("row2", "col2", 1, 1);
+
+ actions.updateRangeSelection({
+ cell,
+ table: mockTable,
+ });
+
+ // Should not call getCellsBetween if no start cell
+ expect(getCellsBetween).not.toHaveBeenCalled();
+ // Selection should remain empty
+ expect(state.selectedCells).toEqual(new Set());
+ });
+ });
+
+ describe("handleCopy", () => {
+ beforeEach(() => {
+ // Reset mocks before each test
+ vi.mocked(getCellValues).mockClear();
+ vi.mocked(getCellValues).mockReturnValue("mocked cell values");
+ });
+
+ it("should copy selected cells and call onCopyComplete", () => {
+ const selectedCells = new Set(["row1_col1", "row1_col2"]);
+ const onCopyComplete = vi.fn();
+
+ // Set some selected cells first
+ actions.setSelectedCells(selectedCells);
+
+ actions.handleCopy({
+ table: mockTable,
+ onCopyComplete,
+ });
+
+ expect(getCellValues).toHaveBeenCalledWith(mockTable, selectedCells);
+ expect(copyToClipboard).toHaveBeenCalledWith("mocked cell values");
+ expect(onCopyComplete).toHaveBeenCalledWith();
+ expect(state.copiedCells).toEqual(selectedCells);
+ });
+ });
+
+ describe("navigate", () => {
+ beforeEach(() => {
+ // Reset mocks before each test
+ vi.mocked(getCellsBetween).mockClear();
+ vi.mocked(getCellsBetween).mockReturnValue(["row1_col1", "row1_col2"]);
+ });
+
+ it("should navigate up", () => {
+ const startCell: SelectedCell = {
+ rowId: "row2",
+ columnId: "col2",
+ cellId: "row2_col2",
+ };
+
+ actions.setFocusedCell(startCell);
+ actions.setSelectedStartCell(startCell);
+
+ actions.navigate({
+ direction: "up",
+ isShiftKey: false,
+ table: mockTable,
+ });
+
+ // Should move to row1, col2
+ expect(state.focusedCell).toEqual({
+ rowId: "row1",
+ columnId: "col2",
+ cellId: "row1_col2",
+ });
+ expect(state.selectedCells).toEqual(new Set(["row1_col2"]));
+ });
+
+ it("should navigate down", () => {
+ const startCell: SelectedCell = {
+ rowId: "row1",
+ columnId: "col1",
+ cellId: "row1_col1",
+ };
+
+ actions.setFocusedCell(startCell);
+ actions.setSelectedStartCell(startCell);
+
+ actions.navigate({
+ direction: "down",
+ isShiftKey: false,
+ table: mockTable,
+ });
+
+ // Should move to row2, col1
+ expect(state.focusedCell).toEqual({
+ rowId: "row2",
+ columnId: "col1",
+ cellId: "row2_col1",
+ });
+ });
+
+ it("should navigate left", () => {
+ const startCell: SelectedCell = {
+ rowId: "row1",
+ columnId: "col2",
+ cellId: "row1_col2",
+ };
+
+ actions.setFocusedCell(startCell);
+ actions.setSelectedStartCell(startCell);
+
+ actions.navigate({
+ direction: "left",
+ isShiftKey: false,
+ table: mockTable,
+ });
+
+ // Should move to row1, col1
+ expect(state.focusedCell).toEqual({
+ rowId: "row1",
+ columnId: "col1",
+ cellId: "row1_col1",
+ });
+ });
+
+ it("should navigate right", () => {
+ const startCell: SelectedCell = {
+ rowId: "row1",
+ columnId: "col1",
+ cellId: "row1_col1",
+ };
+
+ actions.setFocusedCell(startCell);
+ actions.setSelectedStartCell(startCell);
+
+ actions.navigate({
+ direction: "right",
+ isShiftKey: false,
+ table: mockTable,
+ });
+
+ // Should move to row1, col2
+ expect(state.focusedCell).toEqual({
+ rowId: "row1",
+ columnId: "col2",
+ cellId: "row1_col2",
+ });
+ });
+
+ it("should extend selection when shift key is pressed", () => {
+ const startCell: SelectedCell = {
+ rowId: "row1",
+ columnId: "col1",
+ cellId: "row1_col1",
+ };
+
+ actions.setSelectedStartCell(startCell);
+ actions.setFocusedCell(startCell);
+
+ actions.navigate({
+ direction: "down",
+ isShiftKey: true,
+ table: mockTable,
+ });
+
+ expect(getCellsBetween).toHaveBeenCalled();
+ expect(state.selectedCells).toEqual(new Set(["row1_col1", "row1_col2"]));
+ expect(state.focusedCell).toEqual({
+ rowId: "row2",
+ columnId: "col1",
+ cellId: "row2_col1",
+ });
+ });
+
+ it("should do nothing without current cell", () => {
+ actions.setFocusedCell(null);
+ actions.setSelectedStartCell(null);
+
+ actions.navigate({
+ direction: "up",
+ isShiftKey: false,
+ table: mockTable,
+ });
+
+ // Should remain null
+ expect(state.focusedCell).toBeNull();
+ });
+
+ it("should handle navigation at boundaries", () => {
+ // Try to navigate up from first row
+ const firstRowCell: SelectedCell = {
+ rowId: "row1",
+ columnId: "col1",
+ cellId: "row1_col1",
+ };
+
+ actions.setFocusedCell(firstRowCell);
+ actions.setSelectedStartCell(firstRowCell);
+
+ actions.navigate({
+ direction: "up",
+ isShiftKey: false,
+ table: mockTable,
+ });
+
+ // Should stay in the same position
+ expect(state.focusedCell).toEqual(firstRowCell);
+
+ // Try to navigate left from first column
+ actions.navigate({
+ direction: "left",
+ isShiftKey: false,
+ table: mockTable,
+ });
+
+ // Should stay in the same position
+ expect(state.focusedCell).toEqual(firstRowCell);
+ });
+ });
+
+ describe("handleCellMouseDown", () => {
+ const mockCell = createMockCell("row1", "col1");
+
+ beforeEach(() => {
+ // Reset mocks before each test
+ vi.mocked(getCellsBetween).mockClear();
+ vi.mocked(getCellsBetween).mockReturnValue(["row1_col1", "row1_col2"]);
+ });
+
+ it("should handle single cell selection", () => {
+ actions.handleCellMouseDown({
+ cell: mockCell,
+ isShiftKey: false,
+ isCtrlKey: false,
+ table: mockTable,
+ });
+
+ expect(state.selectedCells).toEqual(new Set(["row1_col1"]));
+ expect(state.selectedStartCell).toEqual({
+ rowId: "row1",
+ columnId: "col1",
+ cellId: "row1_col1",
+ });
+ expect(state.focusedCell).toEqual({
+ rowId: "row1",
+ columnId: "col1",
+ cellId: "row1_col1",
+ });
+ expect(state.isSelecting).toBe(true);
+ });
+
+ it("should handle shift+click range selection", () => {
+ const startCell: SelectedCell = {
+ rowId: "row1",
+ columnId: "col1",
+ cellId: "row1_col1",
+ };
+
+ actions.setSelectedStartCell(startCell);
+
+ // Use a different cell for the shift+click
+ const endCell = createMockCell("row2", "col2", 1, 1);
+
+ actions.handleCellMouseDown({
+ cell: endCell,
+ isShiftKey: true,
+ isCtrlKey: false,
+ table: mockTable,
+ });
+
+ expect(getCellsBetween).toHaveBeenCalled();
+ expect(state.selectedCells).toEqual(new Set(["row1_col1", "row1_col2"]));
+ expect(state.isSelecting).toBe(true);
+ });
+
+ it("should deselect when clicking same cell", () => {
+ const selectedCells = new Set(["row1_col1"]);
+ actions.setSelectedCells(selectedCells);
+
+ actions.handleCellMouseDown({
+ cell: mockCell,
+ isShiftKey: false,
+ isCtrlKey: false,
+ table: mockTable,
+ });
+
+ expect(state.selectedCells).toEqual(new Set());
+ expect(state.selectedStartCell).toBeNull();
+ expect(state.focusedCell).toBeNull();
+ });
+ });
+
+ describe("derived atoms", () => {
+ it("should create cell selected atom", () => {
+ createCellSelectedAtom("row1_col1");
+
+ // Initially not selected
+ expect(state.selectedCells.has("row1_col1")).toBe(false);
+
+ // Select the cell
+ actions.setSelectedCells(new Set(["row1_col1"]));
+ expect(state.selectedCells.has("row1_col1")).toBe(true);
+ });
+
+ it("should create cell copied atom", () => {
+ createCellCopiedAtom("row1_col1");
+
+ // Initially not copied
+ expect(state.copiedCells.has("row1_col1")).toBe(false);
+
+ // Copy the cell
+ actions.setCopiedCells(new Set(["row1_col1"]));
+ expect(state.copiedCells.has("row1_col1")).toBe(true);
+ });
+
+ it("should create cell state atom", () => {
+ createCellStateAtom("row1_col1");
+
+ // Initially not selected or copied
+ expect(state.selectedCells.has("row1_col1")).toBe(false);
+ expect(state.copiedCells.has("row1_col1")).toBe(false);
+
+ // Select and copy the cell
+ actions.setSelectedCells(new Set(["row1_col1"]));
+ actions.setCopiedCells(new Set(["row1_col1"]));
+
+ expect(state.selectedCells.has("row1_col1")).toBe(true);
+ expect(state.copiedCells.has("row1_col1")).toBe(true);
+ });
+ });
+
+ describe("edge cases", () => {
+ it("should handle navigation at table boundaries", () => {
+ // Test navigation from first row up
+ const firstRowCell: SelectedCell = {
+ rowId: "row1",
+ columnId: "col1",
+ cellId: "row1_col1",
+ };
+
+ actions.setFocusedCell(firstRowCell);
+ actions.setSelectedStartCell(firstRowCell);
+
+ actions.navigate({
+ direction: "up",
+ isShiftKey: false,
+ table: mockTable,
+ });
+
+ // Should stay in the same position
+ expect(state.focusedCell).toEqual(firstRowCell);
+
+ // Test navigation from last row down
+ const lastRowCell: SelectedCell = {
+ rowId: "row3",
+ columnId: "col3",
+ cellId: "row3_col3",
+ };
+
+ actions.setFocusedCell(lastRowCell);
+ actions.navigate({
+ direction: "down",
+ isShiftKey: false,
+ table: mockTable,
+ });
+
+ // Should stay in the same position
+ expect(state.focusedCell).toEqual(lastRowCell);
+ });
+
+ it("should handle empty table gracefully", () => {
+ const emptyTable = {
+ getRowModel: () => ({ rows: [] }),
+ getRow: () => undefined,
+ } as unknown as Table<T>;
+
+ const currentCell: SelectedCell = {
+ rowId: "nonexistent",
+ columnId: "col1",
+ cellId: "nonexistent_col1",
+ };
+
+ actions.setFocusedCell(currentCell);
+ actions.navigate({
+ direction: "up",
+ isShiftKey: false,
+ table: emptyTable,
+ });
+
+ // Should remain unchanged
+ expect(state.focusedCell).toEqual(currentCell);
+ });
+
+ it("should handle missing cells gracefully", () => {
+ const incompleteTable = {
+ getRowModel: () => ({ rows: [] }),
+ getRow: () => ({
+ getAllCells: () => [],
+ }),
+ } as unknown as Table<T>;
+
+ const cell: SelectedCell = {
+ rowId: "nonexistent",
+ columnId: "col1",
+ cellId: "nonexistent_col1",
+ };
+
+ actions.setFocusedCell(cell);
+ actions.navigate({
+ direction: "right",
+ isShiftKey: false,
+ table: incompleteTable,
+ });
+
+ // Should remain unchanged
+ expect(state.focusedCell).toEqual(cell);
+ });
+ });
+
+ describe("complex interactions", () => {
+ it("should handle multiple selections and copies", () => {
+ const cells = ["row1_col1", "row1_col2", "row2_col1"];
+ const selectedCells = new Set(cells);
+ const onCopyComplete = vi.fn();
+
+ actions.setSelectedCells(selectedCells);
+ actions.handleCopy({
+ table: mockTable,
+ onCopyComplete,
+ });
+
+ expect(copyToClipboard).toHaveBeenCalled();
+ expect(onCopyComplete).toHaveBeenCalledWith();
+ expect(state.copiedCells).toEqual(selectedCells);
+ });
+
+ it("should clear selection and then create new selection", () => {
+ // Start with some selection
+ actions.setSelectedCells(new Set(["row1_col1"]));
+ actions.setSelectedStartCell({
+ rowId: "row1",
+ columnId: "col1",
+ cellId: "row1_col1",
+ });
+
+ // Clear it
+ actions.clearSelection();
+
+ expect(state.selectedCells).toEqual(new Set());
+ expect(state.selectedStartCell).toBeNull();
+
+ // Create new selection
+ const newCell: SelectedCell = {
+ rowId: "row2",
+ columnId: "col2",
+ cellId: "row2_col2",
+ };
+
+ actions.updateSelection({
+ newCell,
+ isShiftKey: false,
+ table: mockTable,
+ });
+
+ expect(state.selectedCells).toEqual(new Set(["row2_col2"]));
+ expect(state.selectedStartCell).toEqual(newCell);
+ });
+
+ it("should handle rapid state changes", () => {
+ const cell1: SelectedCell = {
+ rowId: "row1",
+ columnId: "col1",
+ cellId: "row1_col1",
+ };
+
+ const cell2: SelectedCell = {
+ rowId: "row2",
+ columnId: "col2",
+ cellId: "row2_col2",
+ };
+
+ // Rapid state changes
+ actions.setSelectedStartCell(cell1);
+ actions.setFocusedCell(cell1);
+ actions.setIsSelecting(true);
+ actions.setSelectedStartCell(cell2);
+ actions.setFocusedCell(cell2);
+ actions.setIsSelecting(false);
+ actions.clearSelection();
+
+ expect(state.selectedCells).toEqual(new Set());
+ expect(state.selectedStartCell).toBeNull();
+ expect(state.focusedCell).toBeNull();
+ expect(state.isSelecting).toBe(false);
+ });
+ });
+});
diff --git a/frontend/src/components/data-table/range-focus/__tests__/utils.test.ts b/frontend/src/components/data-table/range-focus/__tests__/utils.test.ts
new file mode 100644
index 0000000000..524a52b2b4
--- /dev/null
+++ b/frontend/src/components/data-table/range-focus/__tests__/utils.test.ts
@@ -0,0 +1,306 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import type { Cell, Column, Row, Table } from "@tanstack/react-table";
+import { describe, expect, it, vi } from "vitest";
+import type { SelectedCell } from "../atoms";
+import { getCellsBetween, getCellValues } from "../utils";
+
+function createMockCell(id: string, value: unknown): Cell<unknown, unknown> {
+ return {
+ id,
+ getValue: () => value,
+ column: {} as Column<unknown>,
+ row: {} as Row<unknown>,
+ getContext: vi.fn(),
+ renderValue: vi.fn(),
+ } as unknown as Cell<unknown, unknown>;
+}
+
+function createMockColumn(id: string): Column<unknown> {
+ return {
+ id: id,
+ getIndex: () => Number.parseInt(id),
+ } as unknown as Column<unknown>;
+}
+
+function createMockRow(
+ id: string,
+ cells: Array<Cell<unknown, unknown>>,
+): Row<unknown> {
+ return {
+ id,
+ index: Number.parseInt(id),
+ getAllCells: () => cells,
+ original: {},
+ depth: 0,
+ subRows: [],
+ getVisibleCells: vi.fn(),
+ getValue: vi.fn(),
+ getUniqueValues: vi.fn(),
+ renderValue: vi.fn(),
+ } as unknown as Row<unknown>;
+}
+
+function createMockTable(
+ rows: Array<Row<unknown>>,
+ columns: Array<Column<unknown>>,
+): Table<unknown> {
+ return {
+ getRow: (id: string) => rows.find((row) => row.id === id),
+ getRowModel: () => ({ rows }),
+ getColumn: (columnId: string) => columns.find((col) => col.id === columnId),
+ getAllColumns: () => columns,
+ } as unknown as Table<unknown>;
+}
+
+function createSelectedCell(rowId: string, columnId: string): SelectedCell {
+ return {
+ rowId,
+ columnId,
+ cellId: `${rowId}_${columnId}`,
+ };
+}
+
+describe("getCellValues", () => {
+ it("should return empty string for empty selection", () => {
+ const mockTable = createMockTable([], []);
+ const result = getCellValues(mockTable, new Set());
+ expect(result).toBe("");
+ });
+
+ it("should return single cell value", () => {
+ const cell = createMockCell("0_0", "test");
+ const row = createMockRow("0", [cell]);
+ const table = createMockTable([row], []);
+
+ const result = getCellValues(table, new Set(["0_0"]));
+ expect(result).toBe("test");
+ });
+
+ it("should return multiple cells from same row separated by tabs", () => {
+ const cell1 = createMockCell("0_0", "value1");
+ const cell2 = createMockCell("0_1", "value2");
+ const row = createMockRow("0", [cell1, cell2]);
+ const table = createMockTable([row], []);
+
+ const result = getCellValues(table, new Set(["0_0", "0_1"]));
+ expect(result).toBe("value1\tvalue2");
+ });
+
+ it("should return multiple rows separated by newlines", () => {
+ const cell1 = createMockCell("0_0", "row1");
+ const cell2 = createMockCell("1_0", "row2");
+ const row1 = createMockRow("0", [cell1]);
+ const row2 = createMockRow("1", [cell2]);
+ const table = createMockTable([row1, row2], []);
+
+ const result = getCellValues(table, new Set(["0_0", "1_0"]));
+ expect(result).toBe("row1\nrow2");
+ });
+
+ it("should handle missing cells gracefully", () => {
+ const cell = createMockCell("0_0", "test");
+ const row = createMockRow("0", [cell]);
+ const table = createMockTable([row], []);
+
+ const result = getCellValues(table, new Set(["0_0", "0_999", "999_0"]));
+ expect(result).toBe("test");
+ });
+
+ it("should handle missing cells in existing rows", () => {
+ const cell1 = createMockCell("0_0", "test1");
+ const cell2 = createMockCell("0_1", "test2");
+ const row = createMockRow("0", [cell1, cell2]);
+ const table = createMockTable([row], []);
+
+ // Should only return values for cells that exist
+ const result = getCellValues(table, new Set(["0_0", "0_1", "0_999"]));
+ expect(result).toBe("test1\ttest2");
+ });
+
+ it("should handle complex data types", () => {
+ const cell1 = createMockCell("0_0", { name: "test" });
+ const cell2 = createMockCell("0_1", null);
+ const cell3 = createMockCell("0_2", undefined);
+ const row = createMockRow("0", [cell1, cell2, cell3]);
+ const table = createMockTable([row], []);
+
+ const result = getCellValues(table, new Set(["0_0", "0_1", "0_2"]));
+ expect(result).toBe('{"name":"test"}\tnull\tundefined');
+ });
+});
+
+describe("getCellsBetween", () => {
+ it("should return empty array when start row is not found", () => {
+ const cell = createMockCell("0_0", "test");
+ const rows = [createMockRow("0", [cell])];
+ const table = createMockTable(rows, []);
+
+ const cellStart = createSelectedCell("999", "0"); // non existent row
+ const cellEnd = createSelectedCell("0", "0");
+
+ const result = getCellsBetween(table, cellStart, cellEnd);
+ expect(result).toEqual([]);
+ });
+
+ it("should return empty array when end row is not found", () => {
+ const cell = createMockCell("0_0", "test");
+ const rows = [createMockRow("0", [cell])];
+ const table = createMockTable(rows, []);
+
+ const cellStart = createSelectedCell("0", "0");
+ const cellEnd = createSelectedCell("999", "0"); // non existent row
+
+ const result = getCellsBetween(table, cellStart, cellEnd);
+ expect(result).toEqual([]);
+ });
+
+ it("should return single cell when start and end are the same", () => {
+ const cell = createMockCell("0_0", "test");
+ const rows = [createMockRow("0", [cell])];
+ const columns = [createMockColumn("0")];
+ const table = createMockTable(rows, columns);
+
+ const cellStart = createSelectedCell("0", "0");
+ const cellEnd = createSelectedCell("0", "0");
+
+ const result = getCellsBetween(table, cellStart, cellEnd);
+ expect(result).toEqual(["0_0"]);
+ });
+
+ it("should return cells in a single row range", () => {
+ const cell1 = createMockCell("0_0", "test1");
+ const cell2 = createMockCell("0_1", "test2");
+ const cell3 = createMockCell("0_2", "test3");
+ const cell4 = createMockCell("0_3", "test4");
+ const cell5 = createMockCell("0_4", "test5");
+ const rows = [createMockRow("0", [cell1, cell2, cell3, cell4, cell5])];
+ const columns = [
+ createMockColumn("0"),
+ createMockColumn("1"),
+ createMockColumn("2"),
+ createMockColumn("3"),
+ createMockColumn("4"),
+ ];
+ const table = createMockTable(rows, columns);
+
+ const startCell = createSelectedCell("0", "1");
+ const endCell = createSelectedCell("0", "3");
+
+ const result = getCellsBetween(table, startCell, endCell);
+ expect(result).toEqual(["0_1", "0_2", "0_3"]);
+ });
+
+ it("should return cells in a single column range", () => {
+ const rows = [
+ createMockRow("0", [
+ createMockCell("0_0", "test1"),
+ createMockCell("0_1", "test2"),
+ createMockCell("0_2", "test3"),
+ ]),
+ createMockRow("1", [
+ createMockCell("1_0", "test4"),
+ createMockCell("1_1", "test5"),
+ createMockCell("1_2", "test6"),
+ ]),
+ createMockRow("2", [
+ createMockCell("2_0", "test7"),
+ createMockCell("2_1", "test8"),
+ createMockCell("2_2", "test9"),
+ ]),
+ ];
+ const columns = [
+ createMockColumn("0"),
+ createMockColumn("1"),
+ createMockColumn("2"),
+ ];
+ const table = createMockTable(rows, columns);
+
+ const cellStart = createSelectedCell("0", "1");
+ const cellEnd = createSelectedCell("2", "1");
+
+ const result = getCellsBetween(table, cellStart, cellEnd);
+ expect(result).toEqual(["0_1", "1_1", "2_1"]);
+ });
+
+ it("should return cells in a rectangular range", () => {
+ const rows = [
+ createMockRow("0", [
+ createMockCell("0_0", "test1"),
+ createMockCell("0_1", "test2"),
+ createMockCell("0_2", "test3"),
+ ]),
+ createMockRow("1", [
+ createMockCell("1_0", "test4"),
+ createMockCell("1_1", "test5"),
+ createMockCell("1_2", "test6"),
+ ]),
+ createMockRow("2", [
+ createMockCell("2_0", "test7"),
+ createMockCell("2_1", "test8"),
+ createMockCell("2_2", "test9"),
+ ]),
+ ];
+ const columns = [
+ createMockColumn("0"),
+ createMockColumn("1"),
+ createMockColumn("2"),
+ ];
+ const table = createMockTable(rows, columns);
+
+ const cellStart = createSelectedCell("0", "1");
+ const cellEnd = createSelectedCell("2", "2");
+
+ const result = getCellsBetween(table, cellStart, cellEnd);
+ expect(result).toEqual(["0_1", "0_2", "1_1", "1_2", "2_1", "2_2"]);
+ });
+
+ it("should work when end is before start (reverse selection)", () => {
+ const rows = [
+ createMockRow("0", [
+ createMockCell("0_0", "test1"),
+ createMockCell("0_1", "test2"),
+ createMockCell("0_2", "test3"),
+ ]),
+ createMockRow("1", [
+ createMockCell("1_0", "test4"),
+ createMockCell("1_1", "test5"),
+ createMockCell("1_2", "test6"),
+ ]),
+ ];
+ const columns = [
+ createMockColumn("0"),
+ createMockColumn("1"),
+ createMockColumn("2"),
+ ];
+ const table = createMockTable(rows, columns);
+
+ const cellStart = createSelectedCell("1", "2");
+ const cellEnd = createSelectedCell("0", "0");
+
+ const result = getCellsBetween(table, cellStart, cellEnd);
+ expect(result).toEqual(["0_0", "0_1", "0_2", "1_0", "1_1", "1_2"]);
+ });
+
+ it("should handle missing cells gracefully", () => {
+ const rows = [
+ createMockRow("0", [
+ createMockCell("0_0", "test1"),
+ createMockCell("0_1", "test2"),
+ createMockCell("0_2", "test3"),
+ ]),
+ ];
+ const columns = [
+ createMockColumn("0"),
+ createMockColumn("1"),
+ createMockColumn("2"),
+ ];
+ const table = createMockTable(rows, columns);
+
+ const cellStart = createSelectedCell("0", "999");
+ const cellEnd = createSelectedCell("0", "0");
+
+ const result = getCellsBetween(table, cellStart, cellEnd);
+ expect(result).toEqual([]);
+ });
+});
diff --git a/frontend/src/components/data-table/range-focus/atoms.ts b/frontend/src/components/data-table/range-focus/atoms.ts
new file mode 100644
index 0000000000..3ba6de0153
--- /dev/null
+++ b/frontend/src/components/data-table/range-focus/atoms.ts
@@ -0,0 +1,345 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import type { Cell, Table } from "@tanstack/react-table";
+import { atom } from "jotai";
+import { copyToClipboard } from "@/utils/copy";
+import { createReducerAndAtoms } from "@/utils/createReducer";
+import { getCellsBetween, getCellValues } from "./utils";
+
+export interface SelectedCell {
+ rowId: string;
+ columnId: string;
+ cellId: string; // unique id for the cell
+}
+
+export type SelectedCells = Set<string>;
+
+export interface CellSelectionState {
+ selectedCells: SelectedCells;
+ copiedCells: SelectedCells;
+ selectedStartCell: SelectedCell | null;
+ focusedCell: SelectedCell | null;
+ isSelecting: boolean;
+}
+
+function initialState(): CellSelectionState {
+ return {
+ selectedCells: new Set<string>(),
+ copiedCells: new Set<string>(),
+ selectedStartCell: null,
+ focusedCell: null,
+ isSelecting: false,
+ };
+}
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+type AnyTable = Table<any>;
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+type AnyCell = Cell<any, unknown>;
+
+const {
+ valueAtom: cellSelectionStateAtom,
+ useActions: useCellSelectionReducerActions,
+ createActions,
+ reducer,
+} = createReducerAndAtoms(initialState, {
+ setSelectedCells: (state, selectedCells: SelectedCells) => {
+ return { ...state, selectedCells };
+ },
+ setSelectedStartCell: (state, selectedStartCell: SelectedCell | null) => {
+ return { ...state, selectedStartCell };
+ },
+ setFocusedCell: (state, focusedCell: SelectedCell | null) => {
+ return { ...state, focusedCell };
+ },
+ setIsSelecting: (state, isSelecting: boolean) => {
+ return { ...state, isSelecting };
+ },
+ setCopiedCells: (state, copiedCells: SelectedCells) => {
+ return { ...state, copiedCells };
+ },
+ clearSelection: (state) => {
+ return {
+ ...state,
+ selectedCells: new Set(),
+ selectedStartCell: null,
+ focusedCell: null,
+ };
+ },
+ updateSelection: (
+ state,
+ {
+ newCell,
+ isShiftKey,
+ table,
+ }: {
+ newCell: SelectedCell;
+ isShiftKey: boolean;
+ table: AnyTable;
+ },
+ ) => {
+ if (isShiftKey && state.selectedStartCell) {
+ const cellsInRange = getCellsBetween(
+ table,
+ state.selectedStartCell,
+ newCell,
+ );
+ return {
+ ...state,
+ selectedCells: new Set(cellsInRange),
+ focusedCell: newCell,
+ };
+ } else {
+ return {
+ ...state,
+ selectedCells: new Set([newCell.cellId]),
+ selectedStartCell: newCell,
+ focusedCell: newCell,
+ };
+ }
+ },
+ updateRangeSelection: (
+ state,
+ {
+ cell,
+ table,
+ }: {
+ cell: AnyCell;
+ table: AnyTable;
+ },
+ ) => {
+ if (!state.selectedStartCell) {
+ return state;
+ }
+
+ const selectedCell = {
+ rowId: cell.row.id,
+ columnId: cell.column.id,
+ cellId: cell.id,
+ };
+
+ const cellsInRange = getCellsBetween(
+ table,
+ state.selectedStartCell,
+ selectedCell,
+ );
+
+ return {
+ ...state,
+ selectedCells: new Set(cellsInRange),
+ };
+ },
+ handleCopy: (
+ state,
+ {
+ table,
+ onCopyComplete,
+ }: {
+ table: AnyTable;
+ onCopyComplete: () => void;
+ },
+ ) => {
+ const text = getCellValues(table, state.selectedCells);
+ copyToClipboard(text);
+ onCopyComplete();
+
+ return {
+ ...state,
+ copiedCells: state.selectedCells,
+ };
+ },
+ navigate: (
+ state,
+ {
+ direction,
+ isShiftKey,
+ table,
+ }: {
+ direction: "up" | "down" | "left" | "right";
+ isShiftKey: boolean;
+ table: AnyTable;
+ },
+ ) => {
+ const currentCell = state.focusedCell ?? state.selectedStartCell;
+ if (!currentCell) {
+ return state;
+ }
+
+ let nextCell: AnyCell | undefined;
+
+ if (direction === "up" || direction === "down") {
+ const rows = table.getRowModel().rows;
+ const selectedRowIndex = rows.findIndex(
+ (row) => row.id === currentCell.rowId,
+ );
+ if (selectedRowIndex < 0) {
+ return state;
+ }
+
+ const nextRow =
+ direction === "up"
+ ? rows[selectedRowIndex - 1]
+ : rows[selectedRowIndex + 1];
+
+ if (!nextRow) {
+ return state;
+ }
+
+ nextCell = nextRow
+ .getAllCells()
+ .find((c) => c.column.id === currentCell.columnId);
+ }
+
+ if (direction === "left" || direction === "right") {
+ const selectedRow = table.getRow(currentCell.rowId);
+ const cells = selectedRow.getAllCells();
+ const selectedColumnIndex = cells.findIndex(
+ (c) => c.id === currentCell.cellId,
+ );
+ if (selectedColumnIndex < 0) {
+ return state;
+ }
+
+ nextCell =
+ direction === "left"
+ ? cells[selectedColumnIndex - 1]
+ : cells[selectedColumnIndex + 1];
+ }
+
+ if (!nextCell) {
+ return state;
+ }
+
+ const newCell = {
+ rowId: nextCell.row.id,
+ columnId: nextCell.column.id,
+ cellId: nextCell.id,
+ };
+
+ if (isShiftKey && state.selectedStartCell) {
+ const cellsInRange = getCellsBetween(
+ table,
+ state.selectedStartCell,
+ newCell,
+ );
+ return {
+ ...state,
+ selectedCells: new Set(cellsInRange),
+ focusedCell: newCell,
+ };
+ } else {
+ return {
+ ...state,
+ selectedCells: new Set([newCell.cellId]),
+ selectedStartCell: newCell,
+ focusedCell: newCell,
+ };
+ }
+ },
+ handleCellMouseDown: (
+ state,
+ {
+ cell,
+ isShiftKey,
+ isCtrlKey,
+ table,
+ }: {
+ cell: AnyCell;
+ isShiftKey: boolean;
+ isCtrlKey: boolean;
+ table: AnyTable;
+ },
+ ) => {
+ const selectedCell = {
+ rowId: cell.row.id,
+ columnId: cell.column.id,
+ cellId: cell.id,
+ };
+
+ if (isShiftKey && state.selectedStartCell) {
+ const cellsInRange = getCellsBetween(
+ table,
+ state.selectedStartCell,
+ selectedCell,
+ );
+ return {
+ ...state,
+ selectedCells: new Set(cellsInRange),
+ isSelecting: true,
+ };
+ }
+
+ if (!isCtrlKey) {
+ const isDeselecting =
+ state.selectedCells.size === 1 &&
+ state.selectedCells.has(selectedCell.cellId);
+
+ if (isDeselecting) {
+ return {
+ ...state,
+ selectedCells: new Set(),
+ selectedStartCell: null,
+ focusedCell: null,
+ };
+ }
+
+ return {
+ ...state,
+ selectedCells: new Set([selectedCell.cellId]),
+ selectedStartCell: selectedCell,
+ focusedCell: selectedCell,
+ isSelecting: true,
+ };
+ }
+
+ return state;
+ },
+});
+
+export { useCellSelectionReducerActions, cellSelectionStateAtom };
+
+export const visibleForTesting = {
+ createActions,
+ reducer,
+ initialState,
+};
+
+// Derived atoms for individual cell state
+export const selectedCellsAtom = atom(
+ (get) => get(cellSelectionStateAtom).selectedCells,
+);
+export const copiedCellsAtom = atom(
+ (get) => get(cellSelectionStateAtom).copiedCells,
+);
+export const selectedStartCellAtom = atom(
+ (get) => get(cellSelectionStateAtom).selectedStartCell,
+);
+export const focusedCellAtom = atom(
+ (get) => get(cellSelectionStateAtom).focusedCell,
+);
+export const isSelectingAtom = atom(
+ (get) => get(cellSelectionStateAtom).isSelecting,
+);
+
+// Optimized derived atoms for individual cell state
+export const createCellSelectedAtom = (cellId: string) =>
+ atom((get) => {
+ const selectedCells = get(selectedCellsAtom);
+ return selectedCells.has(cellId);
+ });
+
+export const createCellCopiedAtom = (cellId: string) =>
+ atom((get) => {
+ const copiedCells = get(copiedCellsAtom);
+ return copiedCells.has(cellId);
+ });
+
+export const createCellStateAtom = (cellId: string) =>
+ atom((get) => {
+ const selectedCells = get(selectedCellsAtom);
+ const copiedCells = get(copiedCellsAtom);
+ return {
+ isSelected: selectedCells.has(cellId),
+ isCopied: copiedCells.has(cellId),
+ };
+ });
diff --git a/frontend/src/components/data-table/range-focus/cell-selection-indicator.tsx b/frontend/src/components/data-table/range-focus/cell-selection-indicator.tsx
new file mode 100644
index 0000000000..90a90d06ce
--- /dev/null
+++ b/frontend/src/components/data-table/range-focus/cell-selection-indicator.tsx
@@ -0,0 +1,36 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { useAtomValue } from "jotai";
+import { memo, useMemo } from "react";
+import { cn } from "@/utils/cn";
+import { createCellStateAtom } from "./atoms";
+
+interface CellSelectionIndicatorProps {
+ cellId: string;
+ className?: string;
+}
+
+export const CellRangeSelectionIndicator = memo<CellSelectionIndicatorProps>(
+ ({ cellId, className }) => {
+ // Create a derived atom that only updates when this specific cell's state changes
+ const cellStateAtom = useMemo(() => createCellStateAtom(cellId), [cellId]);
+ const { isSelected, isCopied } = useAtomValue(cellStateAtom);
+
+ if (!isSelected && !isCopied) {
+ return null;
+ }
+
+ return (
+ <div
+ className={cn(
+ "absolute inset-0 pointer-events-none",
+ isSelected && "bg-[var(--green-3)]",
+ isCopied && "bg-[var(--green-4)] transition-colors duration-150",
+ className,
+ )}
+ />
+ );
+ },
+);
+
+CellRangeSelectionIndicator.displayName = "CellRangeSelectionIndicator";
diff --git a/frontend/src/components/data-table/range-focus/provider.tsx b/frontend/src/components/data-table/range-focus/provider.tsx
new file mode 100644
index 0000000000..bcbdceaf25
--- /dev/null
+++ b/frontend/src/components/data-table/range-focus/provider.tsx
@@ -0,0 +1,13 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { ScopeProvider } from "jotai-scope";
+import { cellSelectionStateAtom } from "./atoms";
+
+export const CellSelectionProvider = ({
+ children,
+}: {
+ children: React.ReactNode;
+}) => {
+ return (
+ <ScopeProvider atoms={[cellSelectionStateAtom]}>{children}</ScopeProvider>
+ );
+};
diff --git a/frontend/src/components/data-table/range-focus/use-cell-range-selection.ts b/frontend/src/components/data-table/range-focus/use-cell-range-selection.ts
new file mode 100644
index 0000000000..4ca5deade2
--- /dev/null
+++ b/frontend/src/components/data-table/range-focus/use-cell-range-selection.ts
@@ -0,0 +1,105 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import type { Cell, Table } from "@tanstack/react-table";
+import useEvent from "react-use-event-hook";
+import { type SelectedCell, useCellSelectionReducerActions } from "./atoms";
+
+export interface UseCellRangeSelectionProps<TData> {
+ table: Table<TData>;
+}
+
+/*
+ * Pure hook that provides only actions without causing re-renders.
+ * Use this in components that only need to trigger actions.
+ */
+export const useCellRangeSelection = <TData>({
+ table,
+}: UseCellRangeSelectionProps<TData>) => {
+ const actions = useCellSelectionReducerActions();
+
+ const handleCopy = useEvent(() => {
+ actions.handleCopy({
+ table,
+ onCopyComplete: () => {
+ // Auto-clear after 500ms
+ setTimeout(() => {
+ actions.setCopiedCells(new Set());
+ }, 500);
+ },
+ });
+ });
+
+ const updateSelection = useEvent(
+ (newCell: SelectedCell, isShiftKey: boolean) => {
+ actions.updateSelection({ newCell, isShiftKey, table });
+ },
+ );
+
+ const navigate = useEvent(
+ (
+ e: React.KeyboardEvent<HTMLElement>,
+ direction: "up" | "down" | "left" | "right",
+ ) => {
+ actions.navigate({ direction, isShiftKey: e.shiftKey, table });
+ },
+ );
+
+ const handleCellsKeyDown = useEvent((e: React.KeyboardEvent<HTMLElement>) => {
+ switch (e.key) {
+ case "c":
+ if (e.metaKey || e.ctrlKey) {
+ handleCopy();
+ }
+ break;
+ case "ArrowDown":
+ e.preventDefault();
+ navigate(e, "down");
+ break;
+ case "ArrowUp":
+ e.preventDefault();
+ navigate(e, "up");
+ break;
+ case "ArrowLeft":
+ e.preventDefault();
+ navigate(e, "left");
+ break;
+ case "ArrowRight":
+ e.preventDefault();
+ navigate(e, "right");
+ break;
+ }
+ });
+
+ const handleCellMouseDown = useEvent(
+ (e: React.MouseEvent, cell: Cell<TData, unknown>) => {
+ actions.handleCellMouseDown({
+ cell,
+ isShiftKey: e.shiftKey,
+ isCtrlKey: e.ctrlKey,
+ table,
+ });
+ },
+ );
+
+ const handleCellMouseUp = useEvent(() => {
+ actions.setIsSelecting(false);
+ });
+
+ const handleCellMouseOver = useEvent(
+ (e: React.MouseEvent, cell: Cell<TData, unknown>) => {
+ if (e.buttons === 1) {
+ actions.updateRangeSelection({ cell, table });
+ }
+ },
+ );
+
+ return {
+ handleCellMouseDown,
+ handleCellMouseUp,
+ handleCellMouseOver,
+ handleCopy,
+ handleCellsKeyDown,
+ updateSelection,
+ clearSelection: actions.clearSelection,
+ };
+};
diff --git a/frontend/src/components/data-table/range-focus/utils.ts b/frontend/src/components/data-table/range-focus/utils.ts
new file mode 100644
index 0000000000..a28863726f
--- /dev/null
+++ b/frontend/src/components/data-table/range-focus/utils.ts
@@ -0,0 +1,95 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import type { Table } from "@tanstack/react-table";
+import { renderUnknownValue } from "../renderers";
+import type { SelectedCell } from "./atoms";
+
+/**
+ * Get the values of the selected cells.
+ */
+export function getCellValues<TData>(
+ table: Table<TData>,
+ selectedCellIds: Set<string>,
+): string {
+ const rowValues = new Map<string, string[]>();
+
+ for (const cellId of selectedCellIds) {
+ const [rowId] = cellId.split("_"); // CellId is rowId_columnId
+ const row = table.getRow(rowId);
+ if (!row) {
+ continue;
+ }
+
+ const tableCell = row.getAllCells().find((c) => c.id === cellId);
+ if (!tableCell) {
+ continue;
+ }
+
+ const values = rowValues.get(rowId) ?? [];
+ values.push(renderUnknownValue({ value: tableCell.getValue() }));
+ rowValues.set(rowId, values);
+ }
+
+ return [...rowValues.values()].map((values) => values.join("\t")).join("\n");
+}
+
+/**
+ * Get the cell ids between two cells.
+ */
+export function getCellsBetween<TData>(
+ table: Table<TData>,
+ startCell: SelectedCell,
+ endCell: SelectedCell,
+): string[] {
+ const startRow = table.getRow(startCell.rowId);
+ const endRow = table.getRow(endCell.rowId);
+
+ if (!startRow || !endRow) {
+ return [];
+ }
+
+ const startRowIdx = startRow.index;
+ const endRowIdx = endRow.index;
+ const startColumnIdx = table.getColumn(startCell.columnId)?.getIndex();
+ const endColumnIdx = table.getColumn(endCell.columnId)?.getIndex();
+
+ if (startColumnIdx === undefined || endColumnIdx === undefined) {
+ return [];
+ }
+
+ const minRow = Math.min(startRowIdx, endRowIdx);
+ const maxRow = Math.max(startRowIdx, endRowIdx);
+ const minCol = Math.min(startColumnIdx, endColumnIdx);
+ const maxCol = Math.max(startColumnIdx, endColumnIdx);
+
+ // Pre-allocate array with known size
+ const result: string[] = [];
+ const totalCells = (maxRow - minRow + 1) * (maxCol - minCol + 1);
+ result.length = totalCells;
+ let resultIndex = 0;
+
+ const columnIds = table.getAllColumns().map((col) => col.id);
+ const rows = table.getRowModel().rows;
+
+ for (let i = minRow; i <= maxRow; i++) {
+ const row = rows[i];
+ const rowId = row.id;
+
+ for (let j = minCol; j <= maxCol; j++) {
+ const columnId = columnIds[j];
+ result[resultIndex++] = getCellId(rowId, columnId);
+ }
+ }
+
+ // Trim any unused slots
+ result.length = resultIndex;
+ return result;
+}
+
+/**
+ * By default, the cell id is the row id and the column id separated by an underscore.
+ * https://tanstack.com/table/latest/docs/guide/cells#cell-ids
+ */
+function getCellId(rowId: string, columnId: string) {
+ return `${rowId}_${columnId}`;
+}
diff --git a/frontend/src/components/data-table/renderers.tsx b/frontend/src/components/data-table/renderers.tsx
index ad4f28e098..9256f9f97e 100644
--- a/frontend/src/components/data-table/renderers.tsx
+++ b/frontend/src/components/data-table/renderers.tsx
@@ -20,6 +20,8 @@ import {
TableRow,
} from "@/components/ui/table";
import { cn } from "@/utils/cn";
+import { CellRangeSelectionIndicator } from "./range-focus/cell-selection-indicator";
+import { useCellRangeSelection } from "./range-focus/use-cell-range-selection";
export function renderTableHeader<TData>(
table: Table<TData>,
@@ -62,14 +64,29 @@ export function renderTableHeader<TData>(
);
}
-export function renderTableBody<TData>(
- table: Table<TData>,
- columns: Array<ColumnDef<TData>>,
- rowViewerPanelOpen: boolean,
- getRowIndex?: (row: TData, idx: number) => number,
- viewedRowIdx?: number,
-): JSX.Element {
- const renderCells = (row: Row<TData>, cells: Array<Cell<TData, unknown>>) => {
+interface DataTableBodyProps<TData> {
+ table: Table<TData>;
+ columns: Array<ColumnDef<TData>>;
+ rowViewerPanelOpen: boolean;
+ getRowIndex?: (row: TData, idx: number) => number;
+ viewedRowIdx?: number;
+}
+
+export const DataTableBody = <TData,>({
+ table,
+ columns,
+ rowViewerPanelOpen,
+ getRowIndex,
+ viewedRowIdx,
+}: DataTableBodyProps<TData>) => {
+ const {
+ handleCellMouseDown,
+ handleCellMouseUp,
+ handleCellMouseOver,
+ handleCellsKeyDown,
+ } = useCellRangeSelection({ table });
+
+ const renderCells = (cells: Array<Cell<TData, unknown>>) => {
return cells.map((cell) => {
const { className, style: pinningstyle } = getPinningStyles(cell.column);
const style = Object.assign(
@@ -79,9 +96,10 @@ export function renderTableBody<TData>(
);
return (
<TableCell
+ tabIndex={0}
key={cell.id}
className={cn(
- "whitespace-pre truncate max-w-[300px]",
+ "whitespace-pre truncate max-w-[300px] select-none outline-none",
cell.column.getColumnWrapping &&
cell.column.getColumnWrapping() === "wrap" &&
"whitespace-pre-wrap min-w-[200px]",
@@ -90,8 +108,14 @@ export function renderTableBody<TData>(
)}
style={style}
title={String(cell.getValue())}
+ onMouseDown={(e) => handleCellMouseDown(e, cell)}
+ onMouseUp={handleCellMouseUp}
+ onMouseOver={(e) => handleCellMouseOver(e, cell)}
>
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ <CellRangeSelectionIndicator cellId={cell.id} />
+ <div className="relative">
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </div>
</TableCell>
);
});
@@ -103,7 +127,7 @@ export function renderTableBody<TData>(
};
return (
- <TableBody>
+ <TableBody onKeyDown={handleCellsKeyDown}>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => {
// Only find the row index if the row viewer panel is open
@@ -126,9 +150,9 @@ export function renderTableBody<TData>(
)}
onClick={() => handleRowClick(row)}
>
- {renderCells(row, row.getLeftVisibleCells())}
- {renderCells(row, row.getCenterVisibleCells())}
- {renderCells(row, row.getRightVisibleCells())}
+ {renderCells(row.getLeftVisibleCells())}
+ {renderCells(row.getCenterVisibleCells())}
+ {renderCells(row.getRightVisibleCells())}
</TableRow>
);
})
@@ -141,7 +165,7 @@ export function renderTableBody<TData>(
)}
</TableBody>
);
-}
+};
function getPinningStyles<TData>(
column: Column<TData>,