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
Initial hover_template function (#6580)
Florian Verdonckce091254cef7
diff --git a/examples/ui/table.py b/examples/ui/table.pyindex bc470d3636..7ca8354548 100644--- a/examples/ui/table.py+++ b/examples/ui/table.py@@ -32,6 +32,20 @@ def _(mo):return (table,)+def _(mo):+ # Per-cell hover: provide a callable for finer control+ def cell_hover(row_id: str, column_name: str, value) -> str:+ return f"{row_id}:{column_name}={value}"++ hover_table = mo.ui.table(+ [{"a": i, "b": i * i} for i in range(8)],+ hover_template=cell_hover,+ )+ hover_table+ return (hover_table,)++@app.celldef _(table):table.valuediff --git a/frontend/src/components/data-table/cell-hover-text/feature.ts b/frontend/src/components/data-table/cell-hover-text/feature.tsnew file mode 100644index 0000000000..b828b9fad8--- /dev/null+++ b/frontend/src/components/data-table/cell-hover-text/feature.ts@@ -0,0 +1,40 @@+/* Copyright 2024 Marimo. All rights reserved. */+"use no memo";++import type {+ Cell,+ Column,+ InitialTableState,+ Row,+ RowData,+ Table,+ TableFeature,+} from "@tanstack/react-table";+import { getStableRowId } from "../utils";+import type { CellHoverTextState, CellHoverTextTableState } from "./types";++function getRowId<TData>(row: Row<TData>): string {+ return getStableRowId(row) ?? row.id;+}++export const CellHoverTextFeature: TableFeature = {+ getInitialState: (state?: InitialTableState): CellHoverTextTableState => {+ return {+ ...state,+ cellHoverTexts: {} as CellHoverTextState,+ };+ },++ createCell: <TData extends RowData>(+ cell: Cell<TData, unknown>,+ column: Column<TData>,+ row: Row<TData>,+ table: Table<TData>,+ ) => {+ cell.getHoverTitle = () => {+ const state = table.getState().cellHoverTexts;+ const rowId = getRowId(row);+ return state?.[rowId]?.[column.id] ?? undefined;+ };+ },+};diff --git a/frontend/src/components/data-table/cell-hover-text/types.ts b/frontend/src/components/data-table/cell-hover-text/types.tsnew file mode 100644index 0000000000..57d0c5a406--- /dev/null+++ b/frontend/src/components/data-table/cell-hover-text/types.ts@@ -0,0 +1,24 @@+/* Copyright 2024 Marimo. All rights reserved. */+/* eslint-disable @typescript-eslint/no-empty-interface */++import type { RowData } from "@tanstack/react-table";++export type CellHoverTextState = Record<string, Record<string, string | null>>;++export interface CellHoverTextTableState {+ cellHoverTexts: CellHoverTextState;+}++export interface CellHoverTextCell {+ /**+ * Returns precomputed hover text for the cell, if any.+ */+ getHoverTitle?: () => string | undefined | null;+}++// Use declaration merging to add our new feature APIs+declare module "@tanstack/react-table" {+ interface TableState extends CellHoverTextTableState {}++ interface Cell<TData extends RowData, TValue> extends CellHoverTextCell {}+}diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsxindex 752ba3fae3..cd01579508 100644--- a/frontend/src/components/data-table/data-table.tsx+++ b/frontend/src/components/data-table/data-table.tsx@@ -26,6 +26,7 @@ import type { GetRowIds } from "@/plugins/impl/DataTablePlugin";import { cn } from "@/utils/cn";import type { PanelType } from "../editor/chrome/panels/context-aware-panel/context-aware-panel";import { CellHoverTemplateFeature } from "./cell-hover-template/feature";+import { CellHoverTextFeature } from "./cell-hover-text/feature";import { CellSelectionFeature } from "./cell-selection/feature";import type { CellSelectionState } from "./cell-selection/types";import { CellStylingFeature } from "./cell-styling/feature";@@ -67,6 +68,7 @@ interface DataTableProps<TData> extends Partial<DownloadActionProps> {cellSelection?: CellSelectionState;cellStyling?: CellStyleState | null;hoverTemplate?: string | null;+ cellHoverTexts?: Record<string, Record<string, string | null>> | null;onRowSelectionChange?: OnChangeFn<RowSelectionState>;onCellSelectionChange?: OnChangeFn<CellSelectionState>;getRowIds?: GetRowIds;@@ -109,6 +111,7 @@ const DataTableInternal = <TData,>({cellSelection,cellStyling,hoverTemplate,+ cellHoverTexts,paginationState,setPaginationState,downloadAs,@@ -183,6 +186,7 @@ const DataTableInternal = <TData,>({ColumnFormattingFeature,CellSelectionFeature,CellStylingFeature,+ CellHoverTextFeature,CellHoverTemplateFeature,CopyColumnFeature,FocusRowFeature,@@ -247,6 +251,7 @@ const DataTableInternal = <TData,>({cellStyling,columnPinning: columnPinning,cellHoverTemplate: hoverTemplate,+ cellHoverTexts: cellHoverTexts ?? {},},});diff --git a/frontend/src/components/data-table/renderers.tsx b/frontend/src/components/data-table/renderers.tsxindex 3a2e276578..65fe9ec56a 100644--- a/frontend/src/components/data-table/renderers.tsx+++ b/frontend/src/components/data-table/renderers.tsx@@ -122,6 +122,7 @@ export const DataTableBody = <TData,>({pinningstyle,);+ const title = cell.getHoverTitle?.() ?? undefined;return (<TableCelltabIndex={0}@@ -135,6 +136,7 @@ export const DataTableBody = <TData,>({className,)}style={style}+ title={title}onMouseDown={(e) => handleCellMouseDown(e, cell)}onMouseUp={handleCellMouseUp}onMouseOver={(e) => handleCellMouseOver(e, cell)}diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex da72834574..8fae124559 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -192,6 +192,7 @@ interface Data<T> {maxColumns: number | "all";hasStableRowId: boolean;lazy: boolean;+ cellHoverTexts?: Record<string, Record<string, string | null>> | null;}// eslint-disable-next-line @typescript-eslint/consistent-type-definitions@@ -214,6 +215,7 @@ type DataTableFunctions = {data: TableData<T>;total_rows: number | TooManyRows;cell_styles?: CellStyleState | null;+ cell_hover_texts?: Record<string, Record<string, string | null>> | null;}>;get_data_url?: GetDataUrl;get_row_ids?: GetRowIds;@@ -265,6 +267,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table").record(z.string(), z.record(z.string(), z.object({}).passthrough())).optional(),hoverTemplate: z.string().optional(),+ cellHoverTexts: z.record(z.record(z.string().nullable())).optional(),// Whether to load the data lazily.lazy: z.boolean().default(false),// If lazy, this will preload the first page of data@@ -310,6 +313,9 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")z.record(z.string(), z.object({}).passthrough()),).nullable(),+ cell_hover_texts: z+ .record(z.record(z.string().nullable()))+ .nullable(),}),),get_row_ids: rpc.input(z.object({}).passthrough()).output(@@ -357,6 +363,12 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")data={props.data.data}value={props.value}setValue={props.setValue}+ cellHoverTexts={+ props.data.cellHoverTexts as Record<+ string,+ Record<string, string | null>+ >+ }/></LazyDataTableComponent></TableProviders>@@ -398,6 +410,7 @@ interface DataTableProps<T> extends Data<T>, DataTableFunctions {enableFilters?: boolean;cellStyles?: CellStyleState | null;hoverTemplate?: string | null;+ cellHoverTexts?: Record<string, Record<string, string | null>> | null;toggleDisplayHeader?: () => void;host: HTMLElement;cellId?: CellId | null;@@ -466,6 +479,7 @@ export const LoadingDataTableComponent = memo(rows: T[];totalRows: number | TooManyRows;cellStyles: CellStyleState | undefined | null;+ cellHoverTexts?: Record<string, Record<string, string | null>> | null;}>(async () => {// If there is no data, return an empty arrayif (props.totalRows === 0) {@@ -476,6 +490,10 @@ export const LoadingDataTableComponent = memo(let tableData = props.data;let totalRows = props.totalRows;let cellStyles = props.cellStyles;+ let cellHoverTexts = props.cellHoverTexts as+ | Record<string, Record<string, string | null>>+ | undefined+ | null;const pageSizeChanged = paginationState.pageSize !== props.pageSize;@@ -526,12 +544,14 @@ export const LoadingDataTableComponent = memo(tableData = searchResults.data;totalRows = searchResults.total_rows;cellStyles = searchResults.cell_styles || {};+ cellHoverTexts = searchResults.cell_hover_texts || {};}tableData = await loadTableData(tableData);return {rows: tableData,totalRows: totalRows,cellStyles,+ cellHoverTexts,};}, [sorting,@@ -542,6 +562,7 @@ export const LoadingDataTableComponent = memo(props.data,props.totalRows,props.lazy,+ props.cellHoverTexts,paginationState.pageSize,paginationState.pageIndex,]);@@ -657,6 +678,12 @@ export const LoadingDataTableComponent = memo(paginationState={paginationState}setPaginationState={setPaginationState}cellStyles={data?.cellStyles ?? props.cellStyles}+ cellHoverTexts={+ (data?.cellHoverTexts ?? props.cellHoverTexts) as Record<+ string,+ Record<string, string | null>+ > | null+ }toggleDisplayHeader={toggleDisplayHeader}getRow={getRow}cellId={cellId}@@ -723,6 +750,7 @@ const DataTableComponent = ({get_row_ids,cellStyles,hoverTemplate,+ cellHoverTexts,toggleDisplayHeader,calculate_top_k_rows,preview_column,@@ -925,6 +953,7 @@ const DataTableComponent = ({cellSelection={cellSelection}cellStyling={cellStyles}hoverTemplate={hoverTemplate}+ cellHoverTexts={cellHoverTexts}downloadAs={showDownload ? downloadAs : undefined}enableSearch={enableSearch}searchQuery={searchQuery}diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex ed375287e7..f6661be4ff 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -137,6 +137,10 @@ class SearchTableResponse:data: strtotal_rows: Union[int, Literal["too_many"]]cell_styles: Optional[CellStyles] = None+ # Mapping of rowId -> columnName -> hover text (plain string or None to suppress)+ cell_hover_texts: Optional[+ dict[RowId, dict[ColumnName, Optional[str]]]+ ] = None@dataclass(frozen=True)@@ -296,6 +300,28 @@ class table(table```+ Create a table with per-cell hover text (plain text only):++ ```python+ import random+++ # rowId and columnName are strings.+ def hover_cell(rowId, columnName, value):+ # Compute a short plain-text title for the visible individual cells.+ return f"Row {rowId} — {columnName}: {value}"+++ table = mo.ui.table(+ data=[random.randint(0, 10) for _ in range(200)],+ hover_template=hover_cell,+ )+ table+ ```++ Note: when sorting is applied, per-cell hover and styling may not be+ correctly aligned with rows, similar to cell styling behavior.+In each case, access the table data with `table.value`.Attributes:@@ -337,7 +363,12 @@ class table(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.- hover_template (str, optional): A template for the hover text of the table.+ hover_template (Union[str, Callable[[str, str, Any], str]], optional):+ Either a string template applied at the row level, or a callable+ that computes plain-text hover titles for individual visible cells.+ When a callable is provided, values are computed per page in Python+ and passed to the frontend; native HTML `title` is used for display.+ Plain text only is supported.max_columns (int, optional): Maximum number of columns to display. Defaults to theconfigured default_table_max_columns (50 by default). Set to None to show all columns.max_height (int, optional): Maximum height of the table body in pixels. When set,@@ -449,7 +480,9 @@ class table(]] = None,style_cell: Optional[Callable[[str, str, Any], dict[str, Any]]] = None,- hover_template: Optional[str] = None,+ hover_template: Optional[+ Union[str, Callable[[str, str, Any], str]]+ ] = None,max_height: Optional[int] = None,# The _internal_* arguments are for overriding and unit tests# table should take the value unconditionally@@ -615,8 +648,18 @@ class table(pagination = Falseself._style_cell = style_cell+ # Store hover callable vs string template separately+ self._hover_cell: Optional[Callable[[str, str, Any], str]] = None+ self._hover_template: Optional[str] = None+ if isinstance(hover_template, str):+ self._hover_template = hover_template+ elif callable(hover_template):+ self._hover_cell = hover_templatesearch_result_styles: Optional[CellStyles] = None+ search_result_hover_texts: Optional[+ dict[RowId, dict[ColumnName, Optional[str]]]+ ] = Nonesearch_result_data: JSONType = []field_types: Optional[FieldTypes] = Nonenum_columns = 0@@ -634,6 +677,7 @@ class table()search_result_styles = search_result.cell_stylessearch_result_data = search_result.data+ search_result_hover_texts = search_result.cell_hover_texts# Validate column configurationscolumn_names_set = set(self._manager.get_column_names())@@ -680,7 +724,8 @@ class table("header-tooltip": header_tooltip,"has-stable-row-id": self._has_stable_row_id,"cell-styles": search_result_styles,- "hover-template": hover_template,+ "hover-template": self._hover_template,+ "cell-hover-texts": search_result_hover_texts,"lazy": _internal_lazy,"preload": _internal_preload,"max-height": int(max_height)@@ -1181,6 +1226,48 @@ class table(for row in row_ids}+ def _hover_cells(+ self, skip: int, take: int, total_rows: Union[int, Literal["too_many"]]+ ) -> Optional[dict[RowId, dict[ColumnName, Optional[str]]]]:+ """Calculate hover text for cells in the table (plain strings or None)."""+ if self._hover_cell is None:+ return None++ def do_hover_cell(row: str, col: str) -> Optional[str]:+ selected_cells = self._searched_manager.select_cells(+ [TableCoordinate(row_id=row, column_name=col)]+ )+ if not selected_cells or self._hover_cell is None:+ return None+ try:+ value = selected_cells[0].value+ result = self._hover_cell(row, col, value)+ return str(result) if result is not None else None+ except BaseException as e:+ LOGGER.warning(+ "Failed to compute hover text for %s:%s: %s", row, col, e+ )+ return None++ columns = self._searched_manager.get_column_names()+ response = self._get_row_ids(EmptyArgs())++ # Clamp the take to the total number of rows+ if total_rows != "too_many" and skip + take > total_rows:+ take = total_rows - skip++ # Determine row range+ row_ids: Union[list[int], range]+ if response.all_rows or response.error:+ row_ids = range(skip, skip + take)+ else:+ row_ids = response.row_ids[skip : skip + take]++ return {+ str(row): {col: do_hover_cell(str(row), col) for col in columns}+ for row in row_ids+ }+def _search(self, args: SearchTableArgs) -> SearchTableResponse:"""Search and filter the table data.@@ -1203,6 +1290,7 @@ class table(- 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+ - cell_hover_texts: User defined hover text for each cell in the page"""offset = args.page_number * args.page_sizemax_columns = args.max_columns@@ -1241,6 +1329,9 @@ class table(cell_styles=self._style_cells(offset, args.page_size, total_rows),+ cell_hover_texts=self._hover_cells(+ offset, args.page_size, total_rows+ ),)filter_function = (@@ -1262,15 +1353,18 @@ class table(else:total_rows = result.get_num_rows(force=True) or 0- if args.sort and self._style_cell:+ if args.sort and (self._style_cell or self._hover_cell):LOGGER.warning(- "Cell styling is not correctly applied when table rows are sorted"+ "Cell styling/hover may not be correctly applied when table rows are sorted")return SearchTableResponse(data=clamp_rows_and_columns(result),total_rows=total_rows,cell_styles=self._style_cells(offset, args.page_size, total_rows),+ cell_hover_texts=self._hover_cells(+ offset, args.page_size, total_rows+ ),)def _get_row_ids(self, args: EmptyArgs) -> GetRowIdsResponse:diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.pyindex dcf6cbcfb1..602d9b1bb1 100644--- a/tests/_plugins/ui/_impl/test_table.py+++ b/tests/_plugins/ui/_impl/test_table.py@@ -2220,3 +2220,144 @@ def test_table_with_timestamp_column_name():# Should use the default max_columns (50)assert table._max_columns == DEFAULT_MAX_COLUMNS+++def test_cell_initial_hover_texts():+ def hover_text(row: str, col: str, value: Any) -> str:+ return f"{row}:{col}={value}"++ table = ui.table([1, 2, 3], hover_template=hover_text)+ assert "cell-hover-texts" in table._args.args+ cell_hover = table._args.args["cell-hover-texts"]+ assert len(cell_hover) == 3+ assert "1" in cell_hover+ assert "value" in cell_hover["1"]+ assert cell_hover["1"]["value"] == "1:value=2"+++def test_hover_template_string_arg():+ table = ui.table([1, 2], hover_template="Value: {{value}}")+ # String template should pass through and per-cell map should be None+ assert table._args.args["hover-template"] == "Value: {{value}}"+ assert "cell-hover-texts" in table._args.args+ assert table._args.args["cell-hover-texts"] is None+++def test_cell_hover_of_next_page():+ def hover_text(row: str, col: str, value: Any) -> str:+ return f"{row}:{col}={value}"++ data = [+ {"a": 1, "b": 2},+ {"a": 3, "b": 4},+ {"a": 5, "b": 6},+ {"a": 7, "b": 8},+ ]++ table = ui.table(data, page_size=2, hover_template=hover_text)+ last_page = table._search(SearchTableArgs(page_size=2, page_number=1))+ cell_hover = last_page.cell_hover_texts+ assert len(cell_hover) == 2+ assert "2" in cell_hover+ assert "a" in cell_hover["2"]+ assert cell_hover["2"]["a"] == "2:a=5"+++def test_cell_hover_last_page():+ def hover_text(row: str, col: str, value: Any) -> str:+ return f"{row}:{col}={value}"++ data = [{"a": 1}, {"a": 2}, {"a": 3}]+ table = ui.table(data, page_size=2, hover_template=hover_text)+ last_page = table._search(SearchTableArgs(page_size=2, page_number=1))+ cell_hover = last_page.cell_hover_texts+ assert len(cell_hover) == 1+ assert "2" in cell_hover+ assert "a" in cell_hover["2"]+ assert cell_hover["2"]["a"] == "2:a=3"+++def test_cell_hover_edge_cases():+ def hover_text(row: str, col: str, value: Any) -> str:+ return f"{row}:{col}={value}"++ # Empty data+ table = ui.table([], hover_template=hover_text)+ response = table._search(SearchTableArgs(page_size=10, page_number=0))+ assert response.cell_hover_texts == {}++ # Single row+ table = ui.table([{"a": 1}], hover_template=hover_text)+ response = table._search(SearchTableArgs(page_size=10, page_number=0))+ assert response.cell_hover_texts == {"0": {"a": "0:a=1"}}++ # Page size larger than total rows+ table = ui.table([{"a": 1}, {"a": 2}], hover_template=hover_text)+ response = table._search(SearchTableArgs(page_size=10, page_number=0))+ assert response.cell_hover_texts == {+ "0": {"a": "0:a=1"},+ "1": {"a": "1:a=2"},+ }++ # Skip beyond total rows+ response = table._search(SearchTableArgs(page_size=10, page_number=1))+ assert response.cell_hover_texts == {}++ # With too_many total rows+ table = ui.table(+ [{"a": 1}, {"a": 2}],+ hover_template=hover_text,+ _internal_total_rows="too_many",+ )+ response = table._search(SearchTableArgs(page_size=10, page_number=0))+ assert response.cell_hover_texts == {+ "0": {"a": "0:a=1"},+ "1": {"a": "1:a=2"},+ }+++ not DependencyManager.polars.has(), reason="Polars not installed"+)+def test_cell_search_df_hover_texts():+ def hover_text(_row: str, _col: str, value: Any) -> str:+ return f"hover:{value}"++ import polars as pl++ data = ["apples", "apples", "bananas", "bananas", "carrots", "carrots"]++ table = ui.table(pl.DataFrame(data), hover_template=hover_text)+ page = table._search(+ SearchTableArgs(page_size=2, page_number=0, query="carrot")+ )+ assert page.cell_hover_texts == {+ "4": {"column_0": "hover:carrots"},+ "5": {"column_0": "hover:carrots"},+ }+++ not DependencyManager.polars.has(), reason="Polars not installed"+)[email protected](reason="Sorted rows are not supported for hover yet")+def test_cell_search_df_hover_texts_sorted():+ def hover_text(_row: str, _col: str, value: Any) -> str:+ return f"hover:{value}"++ import polars as pl++ data = ["apples", "apples", "bananas", "bananas", "carrots", "carrots"]+ table = ui.table(pl.DataFrame(data), hover_template=hover_text)+ page = table._search(+ SearchTableArgs(+ page_size=2,+ page_number=0,+ query="",+ sort=SortArgs(by="column_0", descending=True),+ )+ )+ assert page.cell_hover_texts == {+ "4": {"column_0": "hover:carrots"},+ "5": {"column_0": "hover:carrots"},+ }