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
fix: next page & styling of cells (#4294)
Shahmir Varqha36dd312074b1
diff --git a/frontend/src/components/data-table/cell-styling/types.ts b/frontend/src/components/data-table/cell-styling/types.tsindex 51dd99a343..072e76848b 100644--- a/frontend/src/components/data-table/cell-styling/types.ts+++ b/frontend/src/components/data-table/cell-styling/types.ts@@ -8,7 +8,7 @@ export type CellStyleState = Record<>;export interface CellStylingTableState {- cellStyling: CellStyleState | undefined;+ cellStyling: CellStyleState | undefined | null;}export interface CellStylingCell {diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsxindex ddd36f7139..00191cf59d 100644--- a/frontend/src/components/data-table/data-table.tsx+++ b/frontend/src/components/data-table/data-table.tsx@@ -57,7 +57,7 @@ interface DataTableProps<TData> extends Partial<DownloadActionProps> {selection?: DataTableSelection;rowSelection?: RowSelectionState;cellSelection?: CellSelectionState;- cellStyling?: CellStyleState;+ cellStyling?: CellStyleState | null;onRowSelectionChange?: OnChangeFn<RowSelectionState>;onCellSelectionChange?: OnChangeFn<CellSelectionState>;getRowIds?: GetRowIds;diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex aa32b99942..0d16cfb39b 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -104,7 +104,7 @@ type DataTableFunctions = {}) => Promise<{data: TableData<T>;total_rows: number;- cell_styles?: CellStyleState;+ cell_styles?: CellStyleState | null;}>;get_row_ids?: GetRowIds;};@@ -193,7 +193,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")total_rows: z.number(),cell_styles: z.record(z.record(z.object({}).passthrough()))- .optional(),+ .nullable(),}),),get_row_ids: rpc.input(z.object({}).passthrough()).output(@@ -228,7 +228,7 @@ interface DataTableProps<T> extends Data<T>, DataTableFunctions {enableSearch: boolean;// FiltersenableFilters?: boolean;- cellStyles?: CellStyleState;+ cellStyles?: CellStyleState | null;}interface DataTableSearchProps {@@ -287,7 +287,7 @@ export const LoadingDataTableComponent = memo(const { data, loading, error } = useAsyncData<{rows: T[];totalRows: number | "too_many";- cellStyles: CellStyleState | undefined;+ cellStyles: CellStyleState | undefined | null;}>(async () => {// If there is no data, return an empty arrayif (props.totalRows === 0) {diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex 75facb8a86..1b0c7be9e7 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -739,11 +739,20 @@ class table(return self._style_cell(row, col, selected_cells[0].value)columns = self._searched_manager.get_column_names()+ response = self._get_row_ids(EmptyArgs())++ row_ids: list[int] | range+ if response.all_rows is True or response.error is not None:+ # TODO: Handle sorted rows, they have reverse order of row_ids+ row_ids = range(skip, skip + take)+ else:+ row_ids = response.row_ids[skip : skip + take]+return {str(row): {col: do_style_cell(str(row), col) for col in columns}- for row in range(skip, skip + take)+ for row in row_ids}def _search(self, args: SearchTableArgs) -> SearchTableResponse:@@ -813,7 +822,16 @@ class table()def _get_row_ids(self, args: EmptyArgs) -> GetRowIdsResponse:- """Get row IDs of a table. If searched, return searched rows else all rows."""+ """Get row IDs of a table. If searched, return searched rows else all_rows flag is True.++ Args:+ args (EmptyArgs): Empty arguments++ Returns:+ GetRowIdsResponse: Response containing:+ - row_ids: List of row IDs+ - all_rows: Whether all rows are selected+ """del argstotal_rows = self._manager.get_num_rows()@@ -837,8 +855,8 @@ class table(error="Select all with search is not supported for large datasets. Please filter to less than 1,000,000 rows",)- # For dictionary data, return sequential indices- if isinstance(self.data, dict):+ # For dictionary or list data, return sequential indices+ if isinstance(self.data, dict) or isinstance(self.data, list):return GetRowIdsResponse(row_ids=list(range(num_rows_searched)),all_rows=False,diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.pyindex 7c2aef1c27..4b686a971b 100644--- a/tests/_plugins/ui/_impl/test_table.py+++ b/tests/_plugins/ui/_impl/test_table.py@@ -595,7 +595,7 @@ def test_initial_cell_selection_happy_path() -> None:]-def test_get_row_ids() -> None:+def test_get_row_ids_dict() -> None:data = {"id": [1, 2, 3] * 3,"fruits": ["banana", "apple", "cherry"] * 3,@@ -623,6 +623,26 @@ def test_get_row_ids() -> None:assert response.error is None+def test_get_row_ids_for_lists() -> None:+ table = ui.table(["apples", "bananas", "bananas", "cherries"])+ initial_response = table._get_row_ids(EmptyArgs())+ assert initial_response.all_rows is True+ assert initial_response.row_ids == []+ assert initial_response.error is None++ table._search(+ SearchTableArgs(+ query="banana",+ page_size=10,+ page_number=0,+ )+ )+ response = table._get_row_ids(EmptyArgs())+ assert response.row_ids == [0, 1]+ assert response.all_rows is False+ assert response.error is None++@pytest.mark.parametrize("df",create_dataframes(@@ -1368,3 +1388,51 @@ def test_cell_style_of_next_page():assert "a" in cell_styles["2"]assert "backgroundColor" in cell_styles["2"]["a"]assert "green" in cell_styles["2"]["a"]["backgroundColor"]+++ not DependencyManager.polars.has(), reason="Polars not installed"+)+def test_cell_search_df_styles():+ def always_green(_row, _col, _value):+ return {"backgroundColor": "green"}++ import polars as pl++ data = ["apples", "apples", "bananas", "bananas", "carrots", "carrots"]++ table = ui.table(pl.DataFrame(data), style_cell=always_green)+ page = table._search(+ SearchTableArgs(page_size=2, page_number=0, query="carrot")+ )+ assert page.cell_styles == {+ "4": {"column_0": {"backgroundColor": "green"}},+ "5": {"column_0": {"backgroundColor": "green"}},+ }+++ not DependencyManager.polars.has(), reason="Polars not installed"+)[email protected](reason="Sorted rows are not supported for styling yet")+def test_cell_search_df_styles_sorted():+ def always_green(_row, _col, _value):+ return {"backgroundColor": "green"}++ import polars as pl++ data = ["apples", "apples", "bananas", "bananas", "carrots", "carrots"]+ table = ui.table(pl.DataFrame(data), style_cell=always_green)+ page = table._search(+ SearchTableArgs(+ page_size=2,+ page_number=0,+ query="",+ sort=SortArgs(by="column_0", descending=True),+ )+ )+ # Sorted rows have reverse order of row_ids+ assert page.cell_styles == {+ "4": {"column_0": {"backgroundColor": "green"}},+ "5": {"column_0": {"backgroundColor": "green"}},+ }