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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
DataTable: add summary statistics for selected cells (#8326)
Andrewacfcd97a3efb
diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsxindex b217dafc8a..b4856d88e6 100644--- a/frontend/src/components/data-table/data-table.tsx+++ b/frontend/src/components/data-table/data-table.tsx@@ -38,6 +38,7 @@ 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 { CellSelectionStats } from "./range-focus/cell-selection-stats";import { CellSelectionProvider } from "./range-focus/provider";import { DataTableBody, renderTableHeader } from "./renderers";import { SearchBar } from "./SearchBar";@@ -298,22 +299,22 @@ const DataTableInternal = <TData,>({return (<div className={cn(wrapperClassName, "flex flex-col space-y-1")}><FilterPills filters={filters} table={table} />- <div className={cn(className || "rounded-md border overflow-hidden")}>- {onSearchQueryChange && enableSearch && (- <SearchBar- value={searchQuery || ""}- onHide={() => setIsSearchEnabled(false)}- handleSearch={onSearchQueryChange}- hidden={!isSearchEnabled}- reloading={reloading}- />- )}- <Table className="relative" ref={tableRef}>- {showLoadingBar && (- <thead className="absolute top-0 left-0 h-[3px] w-1/2 bg-primary animate-slide" />+ <CellSelectionProvider>+ <div className={cn(className || "rounded-md border overflow-hidden")}>+ {onSearchQueryChange && enableSearch && (+ <SearchBar+ value={searchQuery || ""}+ onHide={() => setIsSearchEnabled(false)}+ handleSearch={onSearchQueryChange}+ hidden={!isSearchEnabled}+ reloading={reloading}+ />)}- {renderTableHeader(table, Boolean(maxHeight))}- <CellSelectionProvider>+ <Table className="relative" ref={tableRef}>+ {showLoadingBar && (+ <thead className="absolute top-0 left-0 h-[3px] w-1/2 bg-primary animate-slide" />+ )}+ {renderTableHeader(table, Boolean(maxHeight))}<DataTableBodytable={table}columns={columns}@@ -321,9 +322,10 @@ const DataTableInternal = <TData,>({getRowIndex={getPaginatedRowIndex}viewedRowIdx={viewedRowIdx}/>- </CellSelectionProvider>- </Table>- </div>+ </Table>+ </div>+ <CellSelectionStats table={table} className="px-2 pt-1 ml-auto" />+ </CellSelectionProvider><TableActionsenableSearch={enableSearch}totalColumns={totalColumns}diff --git a/frontend/src/components/data-table/range-focus/__tests__/cell-selection-stats.test.tsx b/frontend/src/components/data-table/range-focus/__tests__/cell-selection-stats.test.tsxnew file mode 100644index 0000000000..d2d6543bde--- /dev/null+++ b/frontend/src/components/data-table/range-focus/__tests__/cell-selection-stats.test.tsx@@ -0,0 +1,365 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type { Table } from "@tanstack/react-table";+import { render, screen } from "@testing-library/react";+import { useEffect } from "react";+import { describe, expect, it } from "vitest";+import { SELECT_COLUMN_ID } from "../../types";+import { useCellSelectionReducerActions } from "../atoms";+import { CellSelectionStats } from "../cell-selection-stats";+import { CellSelectionProvider } from "../provider";+import { createMockCell, createMockRow, createMockTable } from "./test-utils";++const TestHarness = ({+ table,+ selectedCellIds,+}: {+ table: Table<unknown>;+ selectedCellIds: Set<string>;+}) => {+ const actions = useCellSelectionReducerActions();+ useEffect(() => {+ actions.setSelectedCells(selectedCellIds);+ }, [actions, selectedCellIds]);+ return <CellSelectionStats table={table} />;+};++describe("CellSelectionStats", () => {+ it("should return null when fewer than 2 cells are selected", () => {+ const row = createMockRow("0", [+ createMockCell("0_0", 10),+ createMockCell("0_1", 20),+ ]);+ const table = createMockTable([row], []);++ const { container } = render(+ <CellSelectionProvider>+ <TestHarness table={table} selectedCellIds={new Set(["0_0"])} />+ </CellSelectionProvider>,+ );++ expect(container.firstChild).toBeNull();+ });++ it("should display Count stat when 2 or more cells are selected", () => {+ const row = createMockRow("0", [+ createMockCell("0_0", 10),+ createMockCell("0_1", 20),+ ]);+ const table = createMockTable([row], []);++ render(+ <CellSelectionProvider>+ <TestHarness table={table} selectedCellIds={new Set(["0_0", "0_1"])} />+ </CellSelectionProvider>,+ );++ expect(screen.getByText("Count: 2")).toBeInTheDocument();+ });++ it("should display Sum when selection contains numeric values", () => {+ const row = createMockRow("0", [+ createMockCell("0_0", 10),+ createMockCell("0_1", 20),+ ]);+ const table = createMockTable([row], []);++ render(+ <CellSelectionProvider>+ <TestHarness table={table} selectedCellIds={new Set(["0_0", "0_1"])} />+ </CellSelectionProvider>,+ );++ expect(screen.getByText("Sum: 30")).toBeInTheDocument();+ });++ it("should display Average when selection contains numeric values", () => {+ const row = createMockRow("0", [+ createMockCell("0_0", 10),+ createMockCell("0_1", 20),+ ]);+ const table = createMockTable([row], []);++ render(+ <CellSelectionProvider>+ <TestHarness table={table} selectedCellIds={new Set(["0_0", "0_1"])} />+ </CellSelectionProvider>,+ );++ expect(screen.getByText("Average: 15")).toBeInTheDocument();+ });++ it("should not display Sum or Average when selection has no numeric values", () => {+ const row = createMockRow("0", [+ createMockCell("0_0", "a"),+ createMockCell("0_1", "b"),+ ]);+ const table = createMockTable([row], []);++ render(+ <CellSelectionProvider>+ <TestHarness table={table} selectedCellIds={new Set(["0_0", "0_1"])} />+ </CellSelectionProvider>,+ );++ expect(screen.getByText("Count: 2")).toBeInTheDocument();+ expect(screen.queryByText(/Sum:/)).not.toBeInTheDocument();+ expect(screen.queryByText(/Average:/)).not.toBeInTheDocument();+ });++ it("should round sum and average to 8 decimal places", () => {+ const row = createMockRow("0", [+ createMockCell("0_0", 0.112_233_441_1),+ createMockCell("0_1", 0.112_233_441_1),+ ]);+ const table = createMockTable([row], []);++ render(+ <CellSelectionProvider>+ <TestHarness table={table} selectedCellIds={new Set(["0_0", "0_1"])} />+ </CellSelectionProvider>,+ );++ expect(screen.getByText("Sum: 0.22446688")).toBeInTheDocument(); // Round 0.2244668866 to 8 decimal places+ expect(screen.getByText("Average: 0.11223344")).toBeInTheDocument(); // Round 0.1122334411 to 8 decimal places+ });++ it("should correctly round sum and average to 8 decimal places", () => {+ const row = createMockRow("0", [+ createMockCell("0_0", 0.112_233_443_3),+ createMockCell("0_1", 0.112_233_443_3),+ ]);+ const table = createMockTable([row], []);++ render(+ <CellSelectionProvider>+ <TestHarness table={table} selectedCellIds={new Set(["0_0", "0_1"])} />+ </CellSelectionProvider>,+ );++ expect(screen.getByText("Sum: 0.22446689")).toBeInTheDocument(); // Round 0.2244668866 to 8 decimal places+ expect(screen.getByText("Average: 0.11223344")).toBeInTheDocument(); // Round 0.1122334433 to 8 decimal places+ });++ it("should not add extra decimal places to sum and average", () => {+ const row = createMockRow("0", [+ createMockCell("0_0", 0.1),+ createMockCell("0_1", 0.2),+ ]);+ const table = createMockTable([row], []);++ render(+ <CellSelectionProvider>+ <TestHarness table={table} selectedCellIds={new Set(["0_0", "0_1"])} />+ </CellSelectionProvider>,+ );++ expect(screen.getByText("Sum: 0.3")).toBeInTheDocument();+ expect(screen.getByText("Average: 0.15")).toBeInTheDocument();+ });++ it("should display Sum: 0 and Average: 0 when all selected values are zero", () => {+ const row = createMockRow("0", [+ createMockCell("0_0", 0),+ createMockCell("0_1", 0),+ ]);+ const table = createMockTable([row], []);++ render(+ <CellSelectionProvider>+ <TestHarness table={table} selectedCellIds={new Set(["0_0", "0_1"])} />+ </CellSelectionProvider>,+ );++ expect(screen.getByText("Count: 2")).toBeInTheDocument();+ expect(screen.getByText("Sum: 0")).toBeInTheDocument();+ expect(screen.getByText("Average: 0")).toBeInTheDocument();+ });++ it("should not display any stats when exactly one cell is selected", () => {+ const row = createMockRow("0", [+ createMockCell("0_0", 10),+ createMockCell("0_1", 20),+ ]);+ const table = createMockTable([row], []);++ const { container } = render(+ <CellSelectionProvider>+ <TestHarness table={table} selectedCellIds={new Set(["0_0"])} />+ </CellSelectionProvider>,+ );++ expect(container.firstChild).toBeNull();+ expect(screen.queryByText(/Count:/)).not.toBeInTheDocument();+ });++ it("should display Sum and Average for negative numbers", () => {+ const row = createMockRow("0", [+ createMockCell("0_0", -10),+ createMockCell("0_1", -20),+ ]);+ const table = createMockTable([row], []);++ render(+ <CellSelectionProvider>+ <TestHarness table={table} selectedCellIds={new Set(["0_0", "0_1"])} />+ </CellSelectionProvider>,+ );++ expect(screen.getByText("Count: 2")).toBeInTheDocument();+ expect(screen.getByText("Sum: -30")).toBeInTheDocument();+ expect(screen.getByText("Average: -15")).toBeInTheDocument();+ });++ it("should display Sum and Average for number strings", () => {+ const row = createMockRow("0", [+ createMockCell("0_0", "42"),+ createMockCell("0_1", "3.14"),+ ]);+ const table = createMockTable([row], []);++ render(+ <CellSelectionProvider>+ <TestHarness table={table} selectedCellIds={new Set(["0_0", "0_1"])} />+ </CellSelectionProvider>,+ );++ expect(screen.getByText("Count: 2")).toBeInTheDocument();+ expect(screen.getByText("Sum: 45.14")).toBeInTheDocument();+ expect(screen.getByText("Average: 22.57")).toBeInTheDocument();+ });++ it("should skip NaN and Infinity and show stats for finite values only", () => {+ const row = createMockRow("0", [+ createMockCell("0_0", 5),+ createMockCell("0_1", Number.NaN),+ createMockCell("0_2", Infinity),+ ]);+ const table = createMockTable([row], []);++ render(+ <CellSelectionProvider>+ <TestHarness+ table={table}+ selectedCellIds={new Set(["0_0", "0_1", "0_2"])}+ />+ </CellSelectionProvider>,+ );++ expect(screen.getByText("Count: 3")).toBeInTheDocument();+ expect(screen.getByText("Sum: 5")).toBeInTheDocument();+ expect(screen.getByText("Average: 5")).toBeInTheDocument();+ });++ it("should exclude booleans from Sum and Average", () => {+ const row = createMockRow("0", [+ createMockCell("0_0", 10),+ createMockCell("0_1", true),+ createMockCell("0_2", false),+ ]);+ const table = createMockTable([row], []);++ render(+ <CellSelectionProvider>+ <TestHarness+ table={table}+ selectedCellIds={new Set(["0_0", "0_1", "0_2"])}+ />+ </CellSelectionProvider>,+ );++ expect(screen.getByText("Count: 3")).toBeInTheDocument();+ expect(screen.getByText("Sum: 10")).toBeInTheDocument();+ expect(screen.getByText("Average: 10")).toBeInTheDocument();+ });++ it("should ignore select checkbox column for Count, Sum and Average", () => {+ const selectCellId = `0_${SELECT_COLUMN_ID}`;+ const row = createMockRow("0", [+ createMockCell(selectCellId, 10),+ createMockCell("0_0", 20),+ createMockCell("0_1", 30),+ ]);+ const table = createMockTable([row], []);++ render(+ <CellSelectionProvider>+ <TestHarness+ table={table}+ selectedCellIds={new Set([selectCellId, "0_0", "0_1"])}+ />+ </CellSelectionProvider>,+ );++ expect(screen.getByText("Count: 2")).toBeInTheDocument();+ expect(screen.getByText("Sum: 50")).toBeInTheDocument();+ expect(screen.getByText("Average: 25")).toBeInTheDocument();+ });++ it("should not display stats when only checkbox column cells are selected", () => {+ const selectCellId1 = `0_${SELECT_COLUMN_ID}`;+ const selectCellId2 = `1_${SELECT_COLUMN_ID}`;+ const row1 = createMockRow("0", [createMockCell(selectCellId1, true)]);+ const row2 = createMockRow("1", [createMockCell(selectCellId2, false)]);+ const table = createMockTable([row1, row2], []);++ const { container } = render(+ <CellSelectionProvider>+ <TestHarness+ table={table}+ selectedCellIds={new Set([selectCellId1, selectCellId2])}+ />+ </CellSelectionProvider>,+ );++ expect(container.firstChild).toBeNull();+ expect(screen.queryByText(/Count:/)).not.toBeInTheDocument();+ });++ it("should show Sum and Average only for numeric cells when selection has mixed types", () => {+ const row = createMockRow("0", [+ createMockCell("0_0", 10),+ createMockCell("0_1", "abc"),+ createMockCell("0_2", undefined),+ ]);+ const table = createMockTable([row], []);++ render(+ <CellSelectionProvider>+ <TestHarness+ table={table}+ selectedCellIds={new Set(["0_0", "0_1", "0_2"])}+ />+ </CellSelectionProvider>,+ );++ expect(screen.getByText("Count: 3")).toBeInTheDocument();+ expect(screen.getByText("Sum: 10")).toBeInTheDocument();+ expect(screen.getByText("Average: 10")).toBeInTheDocument();+ });++ it("should display stats for multiple numeric cells across rows", () => {+ const row1 = createMockRow("0", [+ createMockCell("0_0", 1),+ createMockCell("0_1", 2),+ ]);+ const row2 = createMockRow("1", [+ createMockCell("1_0", 3),+ createMockCell("1_1", 4),+ ]);+ const table = createMockTable([row1, row2], []);++ render(+ <CellSelectionProvider>+ <TestHarness+ table={table}+ selectedCellIds={new Set(["0_0", "0_1", "1_0", "1_1"])}+ />+ </CellSelectionProvider>,+ );++ expect(screen.getByText("Count: 4")).toBeInTheDocument();+ expect(screen.getByText("Sum: 10")).toBeInTheDocument();+ expect(screen.getByText("Average: 2.5")).toBeInTheDocument();+ });+});diff --git a/frontend/src/components/data-table/range-focus/__tests__/test-utils.ts b/frontend/src/components/data-table/range-focus/__tests__/test-utils.tsnew file mode 100644index 0000000000..6e7fe8d8e4--- /dev/null+++ b/frontend/src/components/data-table/range-focus/__tests__/test-utils.ts@@ -0,0 +1,77 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type { Cell, Column, Row, Table } from "@tanstack/react-table";+import { vi } from "vitest";+import type { SelectedCell } from "../atoms";++export 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>;+}++export function createMockColumn(id: string): Column<unknown> {+ return {+ id: id,+ getIndex: () => Number.parseInt(id, 10),+ } as unknown as Column<unknown>;+}++export function createMockRow(+ id: string,+ cells: Cell<unknown, unknown>[],+): Row<unknown> {+ const cellMap = new Map(cells.map((cell) => [cell.id, cell]));+ return {+ id,+ index: Number.parseInt(id, 10),+ getAllCells: () => cells,+ getValue: (columnId: string) => {+ const cellId = `${id}_${columnId}`;+ if (cellMap.has(cellId)) {+ return cellMap.get(cellId)!.getValue();+ }+ if (cellMap.has(columnId)) {+ return cellMap.get(columnId)!.getValue();+ }+ return undefined;+ },+ original: {},+ depth: 0,+ subRows: [],+ getVisibleCells: vi.fn(),+ getUniqueValues: vi.fn(),+ renderValue: vi.fn(),+ } as unknown as Row<unknown>;+}++export function createMockTable(+ rows: Row<unknown>[],+ columns: 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>;+}++export function createSelectedCell(+ rowId: string,+ columnId: string,+): SelectedCell {+ return {+ rowId,+ columnId,+ cellId: `${rowId}_${columnId}`,+ };+}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.tsindex f9a8a2f6e0..9a9a50e05b 100644--- a/frontend/src/components/data-table/range-focus/__tests__/utils.test.ts+++ b/frontend/src/components/data-table/range-focus/__tests__/utils.test.ts@@ -1,66 +1,20 @@/* Copyright 2026 Marimo. All rights reserved. */-import type { Cell, Column, Row, Table } from "@tanstack/react-table";-import { describe, expect, it, vi } from "vitest";+import { describe, expect, it } from "vitest";import { SELECT_COLUMN_ID } from "../../types";-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, 10),- } as unknown as Column<unknown>;-}--function createMockRow(- id: string,- cells: Cell<unknown, unknown>[],-): Row<unknown> {- return {- id,- index: Number.parseInt(id, 10),- 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: Row<unknown>[],- columns: 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}`,- };-}+import {+ countDataCellsInSelection,+ getCellsBetween,+ getCellValues,+ getNumericValuesFromSelectedCells,+} from "../utils";+import {+ createMockCell,+ createMockColumn,+ createMockRow,+ createMockTable,+ createSelectedCell,+} from "./test-utils";describe("getCellValues", () => {it("should return empty string for empty selection", () => {@@ -108,24 +62,25 @@ describe("getCellValues", () => {expect(result).toBe("row1\nrow2");});- it("should handle missing cells gracefully", () => {+ it("should handle missing rows 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"]));+ // Row "999" doesn't exist and is skipped+ const result = getCellValues(table, new Set(["0_0", "999_0"]));expect(result).toBe("test");});- it("should handle missing cells in existing rows", () => {+ it("should include undefined for missing columns on 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+ // Column "999" doesn't exist but row.getValue() returns undefinedconst result = getCellValues(table, new Set(["0_0", "0_1", "0_999"]));- expect(result).toBe("test1\ttest2");+ expect(result).toBe("test1\ttest2\tundefined");});it("should handle complex data types", () => {@@ -314,3 +269,188 @@ describe("getCellsBetween", () => {expect(result).toEqual([]);});});++describe("getNumericValuesFromSelectedCells", () => {+ it("should return empty array for empty selection", () => {+ const mockTable = createMockTable([], []);+ const result = getNumericValuesFromSelectedCells(mockTable, new Set());+ expect(result).toEqual([]);+ });++ it("should ignore select checkbox in tables", () => {+ const cell = createMockCell(`row_${SELECT_COLUMN_ID}`, 10);+ const row = createMockRow("0", [cell]);+ const table = createMockTable([row], []);+ const result = getNumericValuesFromSelectedCells(+ table,+ new Set([`row_${SELECT_COLUMN_ID}`]),+ );+ expect(result).toEqual([]);+ });++ it("should extract numeric values from number cells", () => {+ const cell1 = createMockCell("0_0", 10);+ const cell2 = createMockCell("0_1", 20);+ const row = createMockRow("0", [cell1, cell2]);+ const table = createMockTable([row], []);+ const result = getNumericValuesFromSelectedCells(+ table,+ new Set(["0_0", "0_1"]),+ );+ expect(result).toEqual([10, 20]);+ });++ it("should parse string numbers to numeric values", () => {+ const cell1 = createMockCell("0_0", "42");+ const cell2 = createMockCell("0_1", "3.14");+ const row = createMockRow("0", [cell1, cell2]);+ const table = createMockTable([row], []);+ const result = getNumericValuesFromSelectedCells(+ table,+ new Set(["0_0", "0_1"]),+ );+ expect(result).toEqual([42, 3.14]);+ });++ it("should skip non-numeric values", () => {+ const cell1 = createMockCell("0_0", 10);+ const cell2 = createMockCell("0_1", "abc");+ const cell3 = createMockCell("0_2", undefined);+ const row = createMockRow("0", [cell1, cell2, cell3]);+ const table = createMockTable([row], []);+ const result = getNumericValuesFromSelectedCells(+ table,+ new Set(["0_0", "0_1", "0_2"]),+ );+ expect(result).toEqual([10]);+ });++ it("should skip NaN and Infinity", () => {+ const cell1 = createMockCell("0_0", 5);+ const cell2 = createMockCell("0_1", Number.NaN);+ const cell3 = createMockCell("0_2", Infinity);+ const row = createMockRow("0", [cell1, cell2, cell3]);+ const table = createMockTable([row], []);+ const result = getNumericValuesFromSelectedCells(+ table,+ new Set(["0_0", "0_1", "0_2"]),+ );+ expect(result).toEqual([5]);+ });++ it("should skip booleans (not treat as 1 or 0)", () => {+ const cell1 = createMockCell("0_0", 10);+ const cell2 = createMockCell("0_1", true);+ const cell3 = createMockCell("0_2", false);+ const row = createMockRow("0", [cell1, cell2, cell3]);+ const table = createMockTable([row], []);+ const result = getNumericValuesFromSelectedCells(+ table,+ new Set(["0_0", "0_1", "0_2"]),+ );+ expect(result).toEqual([10]);+ });++ it("should skip null and empty string (not treat as 0)", () => {+ const cell1 = createMockCell("0_0", 10);+ const cell2 = createMockCell("0_1", null);+ const cell3 = createMockCell("0_2", "");+ const row = createMockRow("0", [cell1, cell2, cell3]);+ const table = createMockTable([row], []);+ const result = getNumericValuesFromSelectedCells(+ table,+ new Set(["0_0", "0_1", "0_2"]),+ );+ expect(result).toEqual([10]);+ });++ it("should include string '0' as numeric zero", () => {+ const cell1 = createMockCell("0_0", "0");+ const cell2 = createMockCell("0_1", 0);+ const row = createMockRow("0", [cell1, cell2]);+ const table = createMockTable([row], []);+ const result = getNumericValuesFromSelectedCells(+ table,+ new Set(["0_0", "0_1"]),+ );+ expect(result).toEqual([0, 0]);+ });++ it("should skip -Infinity", () => {+ const cell1 = createMockCell("0_0", 5);+ const cell2 = createMockCell("0_1", -Infinity);+ const row = createMockRow("0", [cell1, cell2]);+ const table = createMockTable([row], []);+ const result = getNumericValuesFromSelectedCells(+ table,+ new Set(["0_0", "0_1"]),+ );+ expect(result).toEqual([5]);+ });++ it("should skip objects", () => {+ const cell1 = createMockCell("0_0", 5);+ const cell2 = createMockCell("0_1", { x: 1 });+ const cell3 = createMockCell("0_2", [1, 2]);+ const row = createMockRow("0", [cell1, cell2, cell3]);+ const table = createMockTable([row], []);+ const result = getNumericValuesFromSelectedCells(+ table,+ new Set(["0_0", "0_1", "0_2"]),+ );+ expect(result).toEqual([5]);+ });++ it("should handle missing cells gracefully", () => {+ const cell = createMockCell("0_0", 100);+ const row = createMockRow("0", [cell]);+ const table = createMockTable([row], []);+ const result = getNumericValuesFromSelectedCells(+ table,+ new Set(["0_0", "0_999", "999_0"]),+ );+ expect(result).toEqual([100]);+ });++ it("should return multiple numeric cells across rows", () => {+ const row1 = createMockRow("0", [+ createMockCell("0_0", 1),+ createMockCell("0_1", 2),+ ]);+ const row2 = createMockRow("1", [+ createMockCell("1_0", 3),+ createMockCell("1_1", 4),+ ]);+ const table = createMockTable([row1, row2], []);+ const result = getNumericValuesFromSelectedCells(+ table,+ new Set(["0_0", "0_1", "1_0", "1_1"]),+ );+ expect(result).toEqual([1, 2, 3, 4]);+ });+});++describe("countDataCellsInSelection", () => {+ it("should return 0 for empty selection", () => {+ expect(countDataCellsInSelection(new Set())).toBe(0);+ });++ it("should count only non-checkbox cells", () => {+ expect(countDataCellsInSelection(new Set(["0_0", "0_1", "1_0"]))).toBe(3);+ });++ it("should exclude select checkbox column cells", () => {+ const selectCellId = `0_${SELECT_COLUMN_ID}`;+ expect(+ countDataCellsInSelection(new Set([selectCellId, "0_0", "0_1"])),+ ).toBe(2);+ });++ it("should return 0 when only checkbox cells are selected", () => {+ const selectCellId1 = `0_${SELECT_COLUMN_ID}`;+ const selectCellId2 = `1_${SELECT_COLUMN_ID}`;+ expect(+ countDataCellsInSelection(new Set([selectCellId1, selectCellId2])),+ ).toBe(0);+ });+});diff --git a/frontend/src/components/data-table/range-focus/cell-selection-stats.tsx b/frontend/src/components/data-table/range-focus/cell-selection-stats.tsxnew file mode 100644index 0000000000..07d8f7fa7a--- /dev/null+++ b/frontend/src/components/data-table/range-focus/cell-selection-stats.tsx@@ -0,0 +1,79 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type { Table } from "@tanstack/react-table";+import { useAtomValue } from "jotai";+import { cn } from "@/utils/cn";+import { selectedCellsAtom } from "./atoms";+import {+ countDataCellsInSelection,+ getNumericValuesFromSelectedCells,+} from "./utils";++/**+ * Displays summary stats (Count, Sum, Average) for the current cell selection.+ * Renders only when 2+ data cells are selected (checkbox column excluded).+ * Count excludes the checkbox column; Sum and Average are shown only when+ * the selection contains at least one numeric value.+ */+export const CellSelectionStats = <TData,>({+ table,+ className,+}: {+ table: Table<TData>;+ className?: string;+}) => {+ const selectedCells = useAtomValue(selectedCellsAtom);+ const dataCellCount = countDataCellsInSelection(selectedCells);++ if (dataCellCount < 2) {+ return null;+ }++ const numericValues = getNumericValuesFromSelectedCells(table, selectedCells);++ return (+ <div+ className={cn(+ "flex items-center justify-end gap-3 text-xs text-muted-foreground shrink-0",+ className,+ )}+ >+ <CountStat count={dataCellCount} />+ <SumStat numericValues={numericValues} />+ <AverageStat numericValues={numericValues} />+ </div>+ );+};++const StatSpan = (statName: string, statValue: number) => {+ return (+ <span>+ {statName}: {statValue}+ </span>+ );+};++const CountStat = ({ count }: { count: number }) => {+ return StatSpan("Count", count);+};++const SumStat = ({ numericValues }: { numericValues: number[] }) => {+ if (numericValues.length === 0) {+ return null;+ }++ const sum = numericValues.reduce((acc, n) => acc + n, 0);+ const sumRounded = Number(sum.toFixed(8));+ return StatSpan("Sum", sumRounded);+};++const AverageStat = ({ numericValues }: { numericValues: number[] }) => {+ if (numericValues.length === 0) {+ return null;+ }++ const average =+ numericValues.reduce((acc, n) => acc + n, 0) / numericValues.length;+ const averageRounded = Number(average.toFixed(8));+ return StatSpan("Average", averageRounded);+};diff --git a/frontend/src/components/data-table/range-focus/utils.ts b/frontend/src/components/data-table/range-focus/utils.tsindex 0ea08098be..70d9c505b3 100644--- a/frontend/src/components/data-table/range-focus/utils.ts+++ b/frontend/src/components/data-table/range-focus/utils.ts@@ -20,19 +20,15 @@ export function getCellValues<TData>(continue;}- const [rowId] = cellId.split("_"); // CellId is rowId_columnId+ const { rowId, columnId } = getRowAndColumnId(cellId);const row = table.getRow(rowId);if (!row) {continue;}- const tableCell = row.getAllCells().find((c) => c.id === cellId);- if (!tableCell) {- continue;- }-+ const cellValue = row.getValue(columnId);const values = rowValues.get(rowId) ?? [];- values.push(stringifyUnknownValue({ value: tableCell.getValue() }));+ values.push(stringifyUnknownValue({ value: cellValue }));rowValues.set(rowId, values);}@@ -43,6 +39,65 @@ export function getTabSeparatedValues(values: string[][]) {return values.map((row) => row.join("\t")).join("\n");}+/**+ * Count selected cells excluding the select checkbox column.+ */+export function countDataCellsInSelection(+ selectedCellIds: Set<string>,+): number {+ let count = 0;+ for (const cellId of selectedCellIds) {+ if (!cellId.includes(SELECT_COLUMN_ID)) {+ count += 1;+ }+ }+ return count;+}++/**+ * Extract numeric values from the selected cells. Only finite numbers and+ * non-empty numeric strings (e.g. "42", "3.14", "0") are included. Skips select+ * checkbox column, missing cells, and all other types (boolean, null, etc.).+ */+export function getNumericValuesFromSelectedCells<TData>(+ table: Table<TData>,+ selectedCellIds: Set<string>,+): number[] {+ const numericValues: number[] = [];+ for (const cellId of selectedCellIds) {+ if (cellId.includes(SELECT_COLUMN_ID)) {+ continue;+ }+ const { rowId, columnId } = getRowAndColumnId(cellId);+ const row = table.getRow(rowId);+ if (!row) {+ continue;+ }++ const value = row.getValue(columnId);++ // Only accept numbers and strings+ // Skip booleans, null, etc.+ let num: number;+ if (typeof value === "number") {+ num = value;+ } else if (typeof value === "string") {+ if (value.trim() === "") {+ continue;+ }+ num = Number(value);+ } else {+ continue;+ }++ // Skip NaN and Infinity+ if (Number.isFinite(num)) {+ numericValues.push(num);+ }+ }+ return numericValues;+}+/*** Get the cell ids between two cells.*/@@ -103,3 +158,10 @@ export function getCellsBetween<TData>(function getCellId(rowId: string, columnId: string) {return `${rowId}_${columnId}`;}++function getRowAndColumnId(cellId: string) {+ const sepIdx = cellId.indexOf("_");+ const rowId = cellId.slice(0, sepIdx);+ const columnId = cellId.slice(sepIdx + 1);+ return { rowId, columnId };+}