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
Styling cells (#4245)
Florian Verdonck560e3c79c15e
diff --git a/examples/ui/table_advanced.py b/examples/ui/table_advanced.pyindex 8d5b79f912..49aa558c57 100644--- a/examples/ui/table_advanced.py+++ b/examples/ui/table_advanced.py@@ -7,7 +7,7 @@import marimo-__generated_with = "0.10.6"+__generated_with = "0.11.26"app = marimo.App()@@ -98,6 +98,51 @@ def _(mo, office_characters):return (table,)[email protected](hide_code=True)+def _(mo):+ mo.md("""**Select individual cells**""")+ return+++def _(mo):+ data = {str(col): [col * 10 + row for row in range(10)] for col in range(10)}+ mo.ui.table(data, selection="multi-cell", initial_selection=[("3", "5"),("9","8")])+ return (data,)+++def _(mo):+ mo.md("""**Style individual cells**""")+ return+++def _(mo):+ def apply_styling(row_id, column_name, value):+ row = int(row_id)+ column = int(column_name)+ r = row / 8 * 12+ g = column / 2 * 32+ b = (row + column) / 10 * 16+ return {+ "backgroundColor": f"rgb({r % 256}, {g % 256}, {b % 256})",+ "color": "white"+ if (r * 0.299 + g * 0.587 + b * 0.114) < 186+ else "black",+ }+++ colors = {+ str(col): [row * 20 + col for row in range(320)] for col in range(10)+ }+ color_table = mo.ui.table(+ data=colors, pagination=True, page_size=16, style_cell=apply_styling+ )+ color_table+ return apply_styling, color_table, colors++@app.celldef _(mo):office_characters = [@@ -225,5 +270,10 @@ def _(mo):return (office_characters,)+def _():+ return++if __name__ == "__main__":app.run()diff --git a/frontend/src/components/data-table/cell-styling/feature.ts b/frontend/src/components/data-table/cell-styling/feature.tsnew file mode 100644index 0000000000..6ac3272cc5--- /dev/null+++ b/frontend/src/components/data-table/cell-styling/feature.ts@@ -0,0 +1,44 @@+/* Copyright 2024 Marimo. All rights reserved. */+"use no memo";++import type {+ Table,+ Cell,+ Column,+ Row,+ RowData,+ TableFeature,+ InitialTableState,+} from "@tanstack/react-table";++import type { CellStyleState, CellStylingTableState } from "./types";+import { INDEX_COLUMN_NAME } from "../types";++function getRowId<TData>(row: Row<TData>): string {+ if (row && typeof row === "object" && INDEX_COLUMN_NAME in row) {+ return String(row[INDEX_COLUMN_NAME]);+ }+ return row.id;+}++export const CellStylingFeature: TableFeature = {+ getInitialState: (state?: InitialTableState): CellStylingTableState => {+ return {+ ...state,+ cellStyling: {} as CellStyleState,+ };+ },++ createCell: <TData extends RowData>(+ cell: Cell<TData, unknown>,+ column: Column<TData>,+ row: Row<TData>,+ table: Table<TData>,+ ) => {+ cell.getUserStyling = () => {+ const state = table.getState().cellStyling;+ const rowId = getRowId(row);+ return state?.[rowId]?.[column.id] || {};+ };+ },+};diff --git a/frontend/src/components/data-table/cell-styling/types.ts b/frontend/src/components/data-table/cell-styling/types.tsnew file mode 100644index 0000000000..51dd99a343--- /dev/null+++ b/frontend/src/components/data-table/cell-styling/types.ts@@ -0,0 +1,26 @@+/* Copyright 2024 Marimo. All rights reserved. */+/* eslint-disable @typescript-eslint/no-empty-interface */+import type { RowData } from "@tanstack/react-table";++export type CellStyleState = Record<+ string,+ Record<string, React.CSSProperties>+>;++export interface CellStylingTableState {+ cellStyling: CellStyleState | undefined;+}++export interface CellStylingCell {+ /**+ * Returns additional styling for the cell.+ */+ getUserStyling?: () => React.CSSProperties;+}++// Use declaration merging to add our new feature APIs+declare module "@tanstack/react-table" {+ interface TableState extends CellStylingTableState {}++ interface Cell<TData extends RowData, TValue> extends CellStylingCell {}+}diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsxindex d7ca6e38b0..ddd36f7139 100644--- a/frontend/src/components/data-table/data-table.tsx+++ b/frontend/src/components/data-table/data-table.tsx@@ -34,6 +34,8 @@ import { INDEX_COLUMN_NAME } from "./types";import { CellSelectionFeature } from "./cell-selection/feature";import type { CellSelectionState } from "./cell-selection/types";import type { GetRowIds } from "@/plugins/impl/DataTablePlugin";+import { CellStylingFeature } from "./cell-styling/feature";+import type { CellStyleState } from "./cell-styling/types";interface DataTableProps<TData> extends Partial<DownloadActionProps> {wrapperClassName?: string;@@ -55,6 +57,7 @@ interface DataTableProps<TData> extends Partial<DownloadActionProps> {selection?: DataTableSelection;rowSelection?: RowSelectionState;cellSelection?: CellSelectionState;+ cellStyling?: CellStyleState;onRowSelectionChange?: OnChangeFn<RowSelectionState>;onCellSelectionChange?: OnChangeFn<CellSelectionState>;getRowIds?: GetRowIds;@@ -84,6 +87,7 @@ const DataTableInternal = <TData,>({setSorting,rowSelection,cellSelection,+ cellStyling,paginationState,setPaginationState,downloadAs,@@ -115,6 +119,7 @@ const DataTableInternal = <TData,>({ColumnWrappingFeature,ColumnFormattingFeature,CellSelectionFeature,+ CellStylingFeature,],data,columns,@@ -172,6 +177,7 @@ const DataTableInternal = <TData,>({{ pagination: { pageIndex: 0, pageSize: data.length } }),rowSelection,cellSelection,+ cellStyling,columnPinning: columnPinning,},onColumnPinningChange: setColumnPinning,diff --git a/frontend/src/components/data-table/renderers.tsx b/frontend/src/components/data-table/renderers.tsxindex 0605b2def2..9875ad15f8 100644--- a/frontend/src/components/data-table/renderers.tsx+++ b/frontend/src/components/data-table/renderers.tsx@@ -65,7 +65,12 @@ export function renderTableBody<TData>(): JSX.Element {const renderCells = (row: Row<TData>, cells: Array<Cell<TData, unknown>>) => {return cells.map((cell) => {- const { className, style } = getPinningStyles(cell.column);+ const { className, style: pinningstyle } = getPinningStyles(cell.column);+ const style = Object.assign(+ {},+ cell.getUserStyling?.() || {},+ pinningstyle,+ );return (<TableCellkey={cell.id}diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex a28c786292..aa32b99942 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -46,6 +46,7 @@ import { DelayMount } from "@/components/utils/delay-mount";import { DATA_TYPES } from "@/core/kernel/messages";import { useEffectSkipFirstRender } from "@/hooks/useEffectSkipFirstRender";import type { CellSelectionState } from "@/components/data-table/cell-selection/types";+import type { CellStyleState } from "@/components/data-table/cell-styling/types";type CsvURL = string;type TableData<T> = T[] | CsvURL;@@ -103,6 +104,7 @@ type DataTableFunctions = {}) => Promise<{data: TableData<T>;total_rows: number;+ cell_styles?: CellStyleState;}>;get_row_ids?: GetRowIds;};@@ -147,6 +149,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table").nullish(),totalColumns: z.number(),hasStableRowId: z.boolean().default(false),+ cellStyles: z.record(z.record(z.object({}).passthrough())).optional(),}),).withFunctions<DataTableFunctions>({@@ -188,6 +191,9 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")z.object({data: z.union([z.string(), z.array(z.object({}).passthrough())]),total_rows: z.number(),+ cell_styles: z+ .record(z.record(z.object({}).passthrough()))+ .optional(),}),),get_row_ids: rpc.input(z.object({}).passthrough()).output(@@ -222,6 +228,7 @@ interface DataTableProps<T> extends Data<T>, DataTableFunctions {enableSearch: boolean;// FiltersenableFilters?: boolean;+ cellStyles?: CellStyleState;}interface DataTableSearchProps {@@ -280,15 +287,17 @@ export const LoadingDataTableComponent = memo(const { data, loading, error } = useAsyncData<{rows: T[];totalRows: number | "too_many";+ cellStyles: CellStyleState | undefined;}>(async () => {// If there is no data, return an empty arrayif (props.totalRows === 0) {- return { rows: Arrays.EMPTY, totalRows: 0 };+ return { rows: Arrays.EMPTY, totalRows: 0, cellStyles: {} };}// Table data is a url string or an array of objectslet tableData = props.data;let totalRows = props.totalRows;+ let cellStyles = props.cellStyles;// If it is just the first page and no search query,// we can show the initial page.@@ -331,6 +340,7 @@ export const LoadingDataTableComponent = memo(const searchResults = await searchResultsPromise;tableData = searchResults.data;totalRows = searchResults.total_rows;+ cellStyles = searchResults.cell_styles || {};}// If we already have the data, return it@@ -338,6 +348,7 @@ export const LoadingDataTableComponent = memo(return {rows: tableData,totalRows: totalRows,+ cellStyles,};}@@ -351,6 +362,7 @@ export const LoadingDataTableComponent = memo(return {rows: tableData,totalRows: totalRows,+ cellStyles,};}, [sorting,@@ -437,6 +449,7 @@ export const LoadingDataTableComponent = memo(totalRows={data?.totalRows ?? props.totalRows}paginationState={paginationState}setPaginationState={setPaginationState}+ cellStyles={data?.cellStyles ?? props.cellStyles}/></>);@@ -475,6 +488,7 @@ const DataTableComponent = ({wrappedColumns,totalColumns,get_row_ids,+ cellStyles,}: DataTableProps<unknown> &DataTableSearchProps & {data: unknown[];@@ -608,6 +622,7 @@ const DataTableComponent = ({setPaginationState={setPaginationState}rowSelection={rowSelection}cellSelection={cellSelection}+ cellStyling={cellStyles}downloadAs={showDownload ? downloadAs : undefined}enableSearch={enableSearch}searchQuery={searchQuery}diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex 2d8062d795..75facb8a86 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -36,6 +36,7 @@ from marimo._plugins.ui._impl.tables.selection import ()from marimo._plugins.ui._impl.tables.table_manager import (ColumnName,+ RowId,TableCell,TableCoordinate,TableManager,@@ -93,10 +94,14 @@ class SearchTableArgs:limit: Optional[int] = None+CellStyles = dict[RowId, dict[ColumnName, dict[str, Any]]]++@dataclass(frozen=True)class SearchTableResponse:data: Union[JSONType, str]total_rows: int+ cell_styles: Optional[CellStyles] = None@dataclass(frozen=True)@@ -189,6 +194,31 @@ class table()```+ Create a table with conditional cell formatting:++ ```python+ import random+++ # rowId and columnName are strings.+ def style_cell(_rowId, _columnName, value):+ # Apply inline styling to the visible individual cells.+ return {+ "backgroundColor": "lightcoral"+ if value < 4+ else "cornflowerblue",+ "color": "white",+ "fontStyle": "italic",+ }+++ table = mo.ui.table(+ data=[random.randint(0, 10) for x in range(200)],+ style_cell=style_cell,+ )+ table+ ```+In each case, access the table data with `table.value`.Attributes:@@ -226,6 +256,7 @@ class table(label (str, optional): Markdown label for the element. Defaults to "".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.+ style_cell (Callable[[str, str, Any], Dict[str, Any]], optional): A function that takes the row id, column name and value and returns a dictionary of CSS styles.max_columns (int, optional): Maximum number of columns to display. Defaults to 50.Set to None to show all columns."""@@ -277,6 +308,7 @@ class table(None,]] = None,+ style_cell: Optional[Callable[[str, str, Any], dict[str, Any]]] = None,# The _internal_* arguments are for overriding and unit tests# table should take the value unconditionally_internal_column_charts_row_limit: Optional[int] = None,@@ -416,6 +448,8 @@ class table(else:pagination = False+ self._style_cell = style_cell+# Search first pagesearch_result = self._search(SearchTableArgs(@@ -465,6 +499,7 @@ class table("text-justify-columns": text_justify_columns,"wrapped-columns": wrapped_columns,"has-stable-row-id": self._has_stable_row_id,+ "cell-styles": search_result.cell_styles,},on_change=on_change,functions=(@@ -688,6 +723,29 @@ class table(return result+ def _style_cells(self, skip: int, take: int) -> Optional[CellStyles]:+ """Calculate the styling of the cells in the table."""+ if self._style_cell is None:+ return None+ else:++ def do_style_cell(row: str, col: str) -> dict[str, Any]:+ selected_cells = self._searched_manager.select_cells(+ [TableCoordinate(row_id=row, column_name=col)]+ )+ if len(selected_cells) == 0 or self._style_cell is None:+ return dict()+ else:+ return self._style_cell(row, col, selected_cells[0].value)++ columns = self._searched_manager.get_column_names()+ return {+ str(row): {+ col: do_style_cell(str(row), col) for col in columns+ }+ for row in range(skip, skip + take)+ }+def _search(self, args: SearchTableArgs) -> SearchTableResponse:"""Search and filter the table data.@@ -707,6 +765,7 @@ class table(SearchTableResponse: Response containing:- data: Filtered and formatted table data for the requested page- total_rows: Total number of rows after applying filters+ - cell_styles: User defined styling information for each cell in the page"""offset = args.page_number * args.page_size@@ -725,9 +784,16 @@ class table(# The frontend will just show the original dataif not args.query and not args.sort and not args.filters:self._searched_manager = self._manager+ total_rows = self._manager.get_num_rows(force=True) or 0return SearchTableResponse(data=clamp_rows_and_columns(self._manager),- total_rows=self._manager.get_num_rows(force=True) or 0,+ total_rows=total_rows,+ # The __init__ will just call this with an arbitrary offset,+ # we need to check this is not larger than our actual number of rows.+ cell_styles=self._style_cells(+ offset,+ min(total_rows, args.page_size),+ ),)# Apply filters, query, and functools.sort using the cached method@@ -743,6 +809,7 @@ class table(return SearchTableResponse(data=clamp_rows_and_columns(result),total_rows=result.get_num_rows(force=True) or 0,+ cell_styles=self._style_cells(offset, args.page_size),)def _get_row_ids(self, args: EmptyArgs) -> GetRowIdsResponse:diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.pyindex efe330d881..8586fea1a7 100644--- a/marimo/_plugins/ui/_impl/tables/default_table.py+++ b/marimo/_plugins/ui/_impl/tables/default_table.py@@ -182,6 +182,10 @@ class DefaultTableManager(TableManager[JsonTableData]):value=row[column_name],))+ elif not isinstance(row, list) and column_name == "value":+ selected_cells.append(+ TableCell(row=row_id, column=column_name, value=row)+ )return selected_cellsdiff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.pyindex 45a0ccf6d5..ad6e0ee73f 100644--- a/marimo/_plugins/ui/_impl/tables/table_manager.py+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py@@ -13,6 +13,7 @@ from marimo._plugins.ui._impl.tables.format import FormatMappingT = TypeVar("T")ColumnName = str+RowId = strFieldType = DataTypeFieldTypes = list[tuple[ColumnName, tuple[FieldType, ExternalDataType]]]diff --git a/tests/_plugins/ui/_impl/tables/test_default_table.py b/tests/_plugins/ui/_impl/tables/test_default_table.pyindex b932b0718a..a657cf581c 100644--- a/tests/_plugins/ui/_impl/tables/test_default_table.py+++ b/tests/_plugins/ui/_impl/tables/test_default_table.py@@ -760,3 +760,18 @@ class TestDictionaryDefaultTable(unittest.TestCase):self.manager.to_json()== b'[{"key":"a","value":1},{"key":"b","value":2}]')+++class TestListDefaultTable(unittest.TestCase):+ def setUp(self) -> None:+ self.manager = DefaultTableManager([4, 5, 6])++ def test_select_cells(self) -> None:+ selected_cells = self.manager.select_cells(+ [+ TableCoordinate(row_id=2, column_name="value"),+ ]+ )+ assert selected_cells == [+ TableCell(row=2, column="value", value=6),+ ]diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.pyindex 77f72a05ae..7c2aef1c27 100644--- a/tests/_plugins/ui/_impl/test_table.py+++ b/tests/_plugins/ui/_impl/test_table.py@@ -1333,3 +1333,38 @@ def test_dataframe_with_int_column_names():# Check that the table handles integer column names correctlyassert table._manager.get_column_names() == [0, 1, 2]assert table._component_args["total-columns"] == 3+++def test_cell_initial_style():+ def always_green(_row, _col, _value):+ return {"backgroundColor": "green"}++ table = ui.table([1, 2, 3], style_cell=always_green)+ assert "cell-styles" in table._args.args+ cell_styles = table._args.args["cell-styles"]+ assert len(cell_styles) == 3+ assert "1" in cell_styles+ assert "value" in cell_styles["1"]+ assert "backgroundColor" in cell_styles["1"]["value"]+ assert "green" == cell_styles["1"]["value"]["backgroundColor"]+++def test_cell_style_of_next_page():+ def always_green(_row, _col, _value):+ return {"backgroundColor": "green"}++ data = [+ {"a": 1, "b": 2},+ {"a": 3, "b": 4},+ {"a": 5, "b": 6},+ {"a": 7, "b": 8},+ ]++ table = ui.table(data, page_size=2, style_cell=always_green)+ last_page = table._search(SearchTableArgs(page_size=2, page_number=1))+ cell_styles = last_page.cell_styles+ assert len(cell_styles) == 2+ assert "2" in cell_styles+ assert "a" in cell_styles["2"]+ assert "backgroundColor" in cell_styles["2"]["a"]+ assert "green" in cell_styles["2"]["a"]["backgroundColor"]