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.

Add support for initial cell selection (#4160)

Florian Verdonck57d374fecf42
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index 182d311013..e7a69662fd 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -113,7 +113,10 @@ type S = Array<number | string | { rowId: string; columnName?: string }>;
export const DataTablePlugin = createPlugin<S>("marimo-table")
.withData(
z.object({
- initialValue: z.array(z.number()),
+ initialValue: z.union([
+ z.array(z.number()),
+ z.array(z.object({ rowId: z.string(), columnName: z.string() })),
+ ]),
label: z.string().nullable(),
data: z.union([z.string(), z.array(z.object({}).passthrough())]),
totalRows: z.union([z.number(), z.literal("too_many")]),
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index b8f920ba1b..c1707c98ac 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -209,7 +209,7 @@ class table(
selection (Literal["single", "multi", "single-cell", "multi-cell"], optional): 'single' or 'multi' to enable row selection,
'single-cell' or 'multi-cell' to enable cell selection
or None to disable. Defaults to "multi".
- initial_selection (List[int], optional): Indices of the rows you want selected by default.
+ initial_selection (Union[List[int], List[tuple[str, str]), optional): Indices of the rows you want selected by default.
page_size (int, optional): The number of rows to show per page. Defaults to 10.
show_column_summaries (Union[bool, Literal["stats", "chart"]], optional): Whether to show column summaries.
Defaults to True when the table has less than 40 columns, False otherwise.
@@ -224,7 +224,7 @@ class table(
Dictionary of column names to text justification options: left, center, right.
wrapped_columns (List[str], optional): List of column names to wrap.
label (str, optional): Markdown label for the element. Defaults to "".
- on_change (Callable[[Union[List[JSONType], Dict[str, List[JSONType]], IntoDataFrame, List[Cell]]], None], optional):
+ on_change (Callable[[Union[List[JSONType], Dict[str, List[JSONType]], IntoDataFrame, List[TableCell]]], None], optional):
Optional callback to run when this element's value changes.
max_columns (int, optional): Maximum number of columns to display. Defaults to 50.
Set to None to show all columns.
@@ -244,7 +244,9 @@ class table(
selection: Optional[
Literal["single", "multi", "single-cell", "multi-cell"]
] = "multi",
- initial_selection: Optional[list[int]] = None,
+ initial_selection: Optional[
+ Union[list[int], list[tuple[str, str]]]
+ ] = None,
page_size: int = 10,
show_column_summaries: Optional[
Union[bool, Literal["stats", "chart"]]
@@ -322,25 +324,66 @@ class table(
# (searching operations include query, sort, filter, etc.)
self._searched_manager = self._manager
# Holds the data after user selecting from the component
- self._selected_manager: Optional[TableManager[Any]] = None
+ self._selected_manager: Optional[
+ Union[TableManager[Any], list[TableCell]]
+ ] = None
self._selection = selection
self._has_any_selection = False
- initial_value = []
+ # Either a list of int (for selection "single" or "multiple")
+ # Or a list of dict (for selection "single-cell" or "multi-cell")
+ initial_value: list[Any] = []
if initial_selection and self._manager.supports_selection():
- if selection == "single" and len(initial_selection) > 1:
+ if (selection in ["single", "single-cell"]) and len(
+ initial_selection
+ ) > 1:
raise ValueError(
"For single selection mode, initial_selection can only contain one row index"
)
try:
- self._selected_manager = self._searched_manager.select_rows(
- initial_selection
- )
+ if selection in ["single-cell", "multi-cell"]:
+ coordinates = []
+ for v in initial_selection:
+ if not isinstance(v, tuple) or len(v) != 2:
+ raise TypeError(
+ "initial_selection must be a list of tuples for cell selection"
+ )
+ else:
+ coordinates.append(
+ TableCoordinate(
+ row_id=v[0],
+ column_name=v[1],
+ )
+ )
+ self._selected_manager = (
+ self._searched_manager.select_cells(coordinates)
+ )
+ else:
+ indexes = []
+ for v in initial_selection:
+ if not isinstance(v, int):
+ raise TypeError(
+ "initial_selection must be a list of integers for row selection"
+ )
+ else:
+ indexes.append(v)
+ self._selected_manager = (
+ self._searched_manager.select_rows(indexes)
+ )
except IndexError as e:
raise IndexError(
"initial_selection contains invalid row indices"
) from e
- initial_value = initial_selection
+
+ initial_value = (
+ initial_selection
+ if all(isinstance(v, int) for v in initial_selection)
+ else [
+ {"rowId": v[0], "columnName": v[1]}
+ for v in initial_selection
+ if isinstance(v, tuple)
+ ]
+ )
self._has_any_selection = True
# We will need this when calling table manager's to_data()
@@ -510,15 +553,23 @@ class table(
)
# Remove the selection column before downloading
- manager = manager.drop_columns([INDEX_COLUMN_NAME])
-
- ext = args.format
- if ext == "csv":
- return mo_data.csv(manager.to_csv()).url
- elif ext == "json":
- return mo_data.json(manager.to_json()).url
+ if isinstance(manager, TableManager) and self._selection in [
+ "single",
+ "multi",
+ ]:
+ manager = manager.drop_columns([INDEX_COLUMN_NAME])
+
+ ext = args.format
+ if ext == "csv":
+ return mo_data.csv(manager.to_csv()).url
+ elif ext == "json":
+ return mo_data.json(manager.to_json()).url
+ else:
+ raise ValueError("format must be one of 'csv' or 'json'.")
else:
- raise ValueError("format must be one of 'csv' or 'json'.")
+ raise NotImplementedError(
+ "Download is not supported for cell selection."
+ )
def _get_column_summaries(self, args: EmptyArgs) -> ColumnSummaries:
"""Get statistical summaries for each column in the table.
diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.py
index c06d629927..bf35f32d29 100644
--- a/tests/_plugins/ui/_impl/test_table.py
+++ b/tests/_plugins/ui/_impl/test_table.py
@@ -554,6 +554,46 @@ def test_search_sort_nonexistent_columns() -> None:
assert table._convert_value(["0"]) == ["banana"]
+def test_invalid_index_in_initial_selection() -> None:
+ """Test that invalid initial selection raises appropriate errors"""
+ with pytest.raises(IndexError):
+ ui.table(
+ data={"a": [1, 2], "b": [3, 4]},
+ initial_selection=[5], # Invalid index
+ )
+
+
+def test_invalid_initial_cell_selection() -> None:
+ """Test that invalid initial selection raises appropriate errors"""
+ with pytest.raises(TypeError):
+ ui.table(
+ data={"a": [1, 2], "b": [3, 4]},
+ selection="single-cell",
+ initial_selection=[(1, 2, 3)], # invalid tulple length
+ )
+
+
+def test_initial_row_selection_happy_path() -> None:
+ """Test that initial row selection works with valid indices"""
+ table = ui.table(
+ data={"a": [1, 2, 3], "b": [4, 5, 6]}, initial_selection=[0, 1]
+ )
+ assert table.value == {"a": [1, 2], "b": [4, 5]}
+
+
+def test_initial_cell_selection_happy_path() -> None:
+ """Test that initial cell selection works with valid coordinates"""
+ table = ui.table(
+ data={"a": [1, 2, 3], "b": [4, 5, 6]},
+ selection="multi-cell",
+ initial_selection=[("0", "a"), ("1", "b")],
+ )
+ assert table.value == [
+ TableCell(row="0", column="a", value=1),
+ TableCell(row="1", column="b", value=5),
+ ]
+
+
def test_get_row_ids() -> None:
data = {
"id": [1, 2, 3] * 3,
@@ -1070,6 +1110,12 @@ def test_download_as_polars() -> None:
assert selected_df["cities"][0] == "New York"
+def test_download_as_for_cell_selection_is_unsupported() -> None:
+ table = ui.table(data=[], selection="single-cell")
+ with pytest.raises(NotImplementedError):
+ table._download_as(DownloadAsArgs(format="csv"))
+
+
def test_pagination_behavior() -> None:
# Test with default page_size=10
data = {"a": list(range(8))}