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.

feat(table): styled tooltip for mo.ui.table hover_template (#9780)

Kiran Gadhave5207529cc1f6
diff --git a/frontend/src/components/data-table/__tests__/data-table.test.tsx b/frontend/src/components/data-table/__tests__/data-table.test.tsx
index c542987cfa..5322003be9 100644
--- a/frontend/src/components/data-table/__tests__/data-table.test.tsx
+++ b/frontend/src/components/data-table/__tests__/data-table.test.tsx
@@ -5,8 +5,8 @@ import type {
RowSelectionState,
SortingState,
} from "@tanstack/react-table";
-import { fireEvent, render, screen, within } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
+import { act, fireEvent, render, screen, within } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { TooltipProvider } from "@/components/ui/tooltip";
import { DataTable } from "../data-table";
@@ -16,6 +16,12 @@ interface TestData {
}
describe("DataTable", () => {
+ // Restore real timers unconditionally so a failed assertion in a
+ // fake-timer test can't leak fake timers into later tests.
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
it("should maintain selection state when remounted", () => {
const mockOnRowSelectionChange = vi.fn();
const testData: TestData[] = [
@@ -63,17 +69,15 @@ describe("DataTable", () => {
expect(commonProps.rowSelection).toEqual(initialRowSelection);
});
- it("applies hoverTemplate to the row title using row values", () => {
+ it("shows the hoverTemplate text as a styled tooltip on hover", async () => {
+ vi.useFakeTimers();
interface RowData {
id: number;
first: string;
last: string;
}
- const testData: RowData[] = [
- { id: 1, first: "Michael", last: "Scott" },
- { id: 2, first: "Jim", last: "Halpert" },
- ];
+ const testData: RowData[] = [{ id: 1, first: "Michael", last: "Scott" }];
const columns: ColumnDef<RowData>[] = [
{ accessorKey: "first", header: "First" },
@@ -86,7 +90,7 @@ describe("DataTable", () => {
data={testData}
columns={columns}
selection={null}
- totalRows={2}
+ totalRows={1}
totalColumns={2}
pagination={false}
hoverTemplate={"{{first}} {{last}}"}
@@ -94,11 +98,149 @@ describe("DataTable", () => {
</TooltipProvider>,
);
- // Grab all rows and assert title attribute computed from template
const rows = screen.getAllByRole("row");
- // The first row is header; subsequent rows correspond to data
- expect(rows[1]).toHaveAttribute("title", "Michael Scott");
- expect(rows[2]).toHaveAttribute("title", "Jim Halpert");
+ // Native title is gone; hover text now comes from the styled tooltip.
+ expect(rows[1]).not.toHaveAttribute("title");
+
+ const cell = within(rows[1]).getAllByRole("cell")[0];
+ fireEvent.mouseOver(cell, { buttons: 0 });
+ act(() => {
+ vi.advanceTimersByTime(400);
+ });
+
+ // Radix renders the content twice (visible + a11y-hidden), so match all.
+ expect(screen.getAllByText("Michael Scott").length).toBeGreaterThan(0);
+ });
+
+ it("shows per-cell hover text from cellHoverTexts on hover", () => {
+ vi.useFakeTimers();
+ const testData: TestData[] = [{ id: 1, name: "Test 1" }];
+ const columns: ColumnDef<TestData>[] = [
+ { id: "name", accessorKey: "name", header: "Name" },
+ ];
+
+ render(
+ <TooltipProvider>
+ <DataTable
+ data={testData}
+ columns={columns}
+ selection={null}
+ totalRows={1}
+ totalColumns={1}
+ pagination={false}
+ cellHoverTexts={{ "0": { name: "per-cell tip" } }}
+ />
+ </TooltipProvider>,
+ );
+
+ const cell = within(screen.getAllByRole("row")[1]).getByRole("cell");
+ fireEvent.mouseOver(cell, { buttons: 0 });
+ act(() => {
+ vi.advanceTimersByTime(400);
+ });
+
+ expect(screen.getAllByText("per-cell tip").length).toBeGreaterThan(0);
+ });
+
+ it("links the focused cell to the tooltip content for assistive tech", () => {
+ const testData: TestData[] = [{ id: 1, name: "Test 1" }];
+ const columns: ColumnDef<TestData>[] = [
+ { id: "name", accessorKey: "name", header: "Name" },
+ ];
+
+ render(
+ <TooltipProvider>
+ <DataTable
+ data={testData}
+ columns={columns}
+ selection={null}
+ totalRows={1}
+ totalColumns={1}
+ pagination={false}
+ cellHoverTexts={{ "0": { name: "focus tip" } }}
+ />
+ </TooltipProvider>,
+ );
+
+ const cell = within(screen.getAllByRole("row")[1]).getByRole("cell");
+ fireEvent.focus(cell);
+
+ const describedBy = cell.getAttribute("aria-describedby");
+ expect(describedBy).toBeTruthy();
+ expect(document.getElementById(describedBy as string)).toHaveTextContent(
+ "focus tip",
+ );
+
+ fireEvent.blur(cell);
+ expect(cell).not.toHaveAttribute("aria-describedby");
+ });
+
+ it("does not show a tooltip on pointer-induced focus", () => {
+ const testData: TestData[] = [{ id: 1, name: "Test 1" }];
+ const columns: ColumnDef<TestData>[] = [
+ { id: "name", accessorKey: "name", header: "Name" },
+ ];
+
+ render(
+ <TooltipProvider>
+ <DataTable
+ data={testData}
+ columns={columns}
+ selection={null}
+ totalRows={1}
+ totalColumns={1}
+ pagination={false}
+ cellHoverTexts={{ "0": { name: "click tip" } }}
+ />
+ </TooltipProvider>,
+ );
+
+ const cell = within(screen.getAllByRole("row")[1]).getByRole("cell");
+ // A click focuses the cell; the resulting focus must not show a tooltip.
+ fireEvent.mouseDown(cell);
+ fireEvent.focus(cell);
+
+ expect(cell).not.toHaveAttribute("aria-describedby");
+ expect(screen.queryByText("click tip")).toBeNull();
+ });
+
+ it("does not let a pending hover timer overwrite a focus tooltip", () => {
+ vi.useFakeTimers();
+ interface RowData {
+ id: number;
+ a: string;
+ b: string;
+ }
+ const testData: RowData[] = [{ id: 1, a: "a", b: "b" }];
+ const columns: ColumnDef<RowData>[] = [
+ { id: "a", accessorKey: "a", header: "A" },
+ { id: "b", accessorKey: "b", header: "B" },
+ ];
+
+ render(
+ <TooltipProvider>
+ <DataTable
+ data={testData}
+ columns={columns}
+ selection={null}
+ totalRows={1}
+ totalColumns={2}
+ pagination={false}
+ cellHoverTexts={{ "0": { a: "hover A", b: "focus B" } }}
+ />
+ </TooltipProvider>,
+ );
+
+ const cells = within(screen.getAllByRole("row")[1]).getAllByRole("cell");
+ // Start a pending hover-show on cell A, then focus cell B before it fires.
+ fireEvent.mouseOver(cells[0], { buttons: 0 });
+ fireEvent.focus(cells[1]);
+ act(() => {
+ vi.advanceTimersByTime(400);
+ });
+
+ expect(screen.getAllByText("focus B").length).toBeGreaterThan(0);
+ expect(screen.queryByText("hover A")).toBeNull();
});
it("does not virtualize small datasets without pagination", () => {
diff --git a/frontend/src/components/data-table/hover-tooltip/__tests__/content.test.ts b/frontend/src/components/data-table/hover-tooltip/__tests__/content.test.ts
new file mode 100644
index 0000000000..1d70182d1b
--- /dev/null
+++ b/frontend/src/components/data-table/hover-tooltip/__tests__/content.test.ts
@@ -0,0 +1,60 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import type { Cell } from "@tanstack/react-table";
+import { describe, expect, it } from "vitest";
+import { applyHoverTemplate, computeCellTooltipContent } from "../content";
+
+function fakeCell(columnId: string, value: unknown, hoverTitle?: string) {
+ return {
+ column: { id: columnId },
+ getValue: () => value,
+ getHoverTitle: () => hoverTitle,
+ } as unknown as Cell<unknown, unknown>;
+}
+
+describe("applyHoverTemplate", () => {
+ it("substitutes column placeholders", () => {
+ const cells = [fakeCell("first", "Michael"), fakeCell("last", "Scott")];
+ expect(applyHoverTemplate("{{first}} {{last}}", cells)).toBe(
+ "Michael Scott",
+ );
+ });
+
+ it("renders nulls as empty strings", () => {
+ const cells = [fakeCell("a", null)];
+ expect(applyHoverTemplate("[{{a}}]", cells)).toBe("[]");
+ });
+
+ it("leaves unknown placeholders intact", () => {
+ expect(applyHoverTemplate("{{missing}}", [fakeCell("a", 1)])).toBe(
+ "{{missing}}",
+ );
+ });
+});
+
+describe("computeCellTooltipContent", () => {
+ it("prefers cell-level hover title", () => {
+ const cell = fakeCell("a", 1, "cell text");
+ expect(computeCellTooltipContent(cell, "{{a}}")).toBe("cell text");
+ });
+
+ it("falls back to row template when no cell title", () => {
+ const cell = {
+ column: { id: "first" },
+ getValue: () => "X",
+ getHoverTitle: () => undefined,
+ row: {
+ getVisibleCells: () => [
+ fakeCell("first", "Jim"),
+ fakeCell("last", "Halpert"),
+ ],
+ },
+ } as unknown as Cell<unknown, unknown>;
+ expect(computeCellTooltipContent(cell, "{{first}} {{last}}")).toBe(
+ "Jim Halpert",
+ );
+ });
+
+ it("returns undefined with no title and no template", () => {
+ expect(computeCellTooltipContent(fakeCell("a", 1), null)).toBeUndefined();
+ });
+});
diff --git a/frontend/src/components/data-table/hover-tooltip/content.ts b/frontend/src/components/data-table/hover-tooltip/content.ts
new file mode 100644
index 0000000000..425fd47b3c
--- /dev/null
+++ b/frontend/src/components/data-table/hover-tooltip/content.ts
@@ -0,0 +1,44 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import type { Cell, RowData } from "@tanstack/react-table";
+import type { ReactNode } from "react";
+import { stringifyUnknownValue } from "../utils";
+
+export function applyHoverTemplate<TData extends RowData>(
+ template: string,
+ cells: Cell<TData, unknown>[],
+): string {
+ const variableRegex = /{{(\w+)}}/g;
+ const idToValue = new Map<string, string>();
+ for (const c of cells) {
+ const s = stringifyUnknownValue({
+ value: c.getValue(),
+ nullAsEmptyString: true,
+ });
+ idToValue.set(c.column.id, s);
+ }
+ return template.replaceAll(variableRegex, (_substr, varName: string) => {
+ const val = idToValue.get(varName);
+ return val === undefined ? `{{${varName}}}` : val;
+ });
+}
+
+/**
+ * Resolve the tooltip content for a hovered cell.
+ *
+ * Cell-level (callable `hover_template`) takes precedence; otherwise the
+ * row-level string template is rendered against the row's visible cells.
+ * Returns `undefined` when there is nothing to show.
+ */
+export function computeCellTooltipContent<TData extends RowData>(
+ cell: Cell<TData, unknown>,
+ hoverTemplate: string | null,
+): ReactNode {
+ const cellTitle = cell.getHoverTitle?.();
+ if (cellTitle != null && cellTitle !== "") {
+ return cellTitle;
+ }
+ if (hoverTemplate) {
+ return applyHoverTemplate(hoverTemplate, cell.row.getVisibleCells());
+ }
+ return undefined;
+}
diff --git a/frontend/src/components/data-table/hover-tooltip/hover-tooltip.tsx b/frontend/src/components/data-table/hover-tooltip/hover-tooltip.tsx
new file mode 100644
index 0000000000..766d460c3b
--- /dev/null
+++ b/frontend/src/components/data-table/hover-tooltip/hover-tooltip.tsx
@@ -0,0 +1,55 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import {
+ TooltipContent,
+ TooltipPortal,
+ TooltipRoot,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import type { HoverTooltipState } from "./use-table-hover-tooltip";
+
+interface HoverTooltipProps {
+ state: HoverTooltipState | null;
+ contentId: string;
+ onClose: () => void;
+}
+
+/**
+ * A single radix tooltip whose anchor is repositioned to the hovered cell.
+ * Rendering one instance per table (instead of one per cell) keeps the cost
+ * constant regardless of how many cells are on screen.
+ */
+export const HoverTooltip = ({
+ state,
+ contentId,
+ onClose,
+}: HoverTooltipProps) => {
+ return (
+ <TooltipRoot
+ open={state != null}
+ onOpenChange={(open) => {
+ if (!open) {
+ onClose();
+ }
+ }}
+ delayDuration={0}
+ disableHoverableContent={true}
+ >
+ <TooltipTrigger asChild={true}>
+ <div
+ aria-hidden={true}
+ style={{
+ position: "fixed",
+ top: state?.rect.top ?? 0,
+ left: state?.rect.left ?? 0,
+ width: state?.rect.width ?? 0,
+ height: state?.rect.height ?? 0,
+ pointerEvents: "none",
+ }}
+ />
+ </TooltipTrigger>
+ <TooltipPortal>
+ <TooltipContent id={contentId}>{state?.content}</TooltipContent>
+ </TooltipPortal>
+ </TooltipRoot>
+ );
+};
diff --git a/frontend/src/components/data-table/hover-tooltip/use-table-hover-tooltip.ts b/frontend/src/components/data-table/hover-tooltip/use-table-hover-tooltip.ts
new file mode 100644
index 0000000000..baf9489613
--- /dev/null
+++ b/frontend/src/components/data-table/hover-tooltip/use-table-hover-tooltip.ts
@@ -0,0 +1,159 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import type { Cell, RowData, Table } from "@tanstack/react-table";
+import {
+ type ReactNode,
+ useEffect,
+ useId,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "react";
+import useEvent from "react-use-event-hook";
+import { computeCellTooltipContent } from "./content";
+
+// Matches the default TooltipProvider delay (MarimoApp.tsx) for visual parity
+// with the rest of the app's tooltips.
+const TOOLTIP_DELAY_MS = 400;
+
+export interface HoverTooltipState {
+ rect: { top: number; left: number; width: number; height: number };
+ content: ReactNode;
+}
+
+export function useTableHoverTooltip<TData extends RowData>({
+ table,
+}: {
+ table: Table<TData>;
+}) {
+ const hoverTemplate = table.getState().cellHoverTemplate || null;
+ const [tooltipState, setTooltipState] = useState<HoverTooltipState | null>(
+ null,
+ );
+ const timer = useRef<number | null>(null);
+
+ // Stable id linking the focused/hovered cell to the tooltip content for
+ // assistive tech (the radix trigger is an aria-hidden phantom anchor).
+ const tooltipContentId = useId();
+ const anchorCell = useRef<HTMLElement | null>(null);
+ // Focus fires for pointer interactions too; track pointer state so
+ // click/drag-select focus doesn't show a tooltip (keyboard focus still does).
+ const pointerDown = useRef(false);
+
+ const clearTimer = () => {
+ if (timer.current != null) {
+ clearTimeout(timer.current);
+ timer.current = null;
+ }
+ };
+
+ const hideTooltip = useEvent(() => {
+ clearTimer();
+ setTooltipState(null);
+ });
+
+ const showFor = (target: HTMLElement, content: ReactNode) => {
+ anchorCell.current = target;
+ const r = target.getBoundingClientRect();
+ setTooltipState({
+ rect: { top: r.top, left: r.left, width: r.width, height: r.height },
+ content,
+ });
+ };
+
+ // Point the real cell at the tooltip content while it is shown. Done in a
+ // layout effect (after commit) so React's re-render from `setTooltipState`
+ // can't clobber an imperatively set attribute; cleanup unlinks the previous
+ // cell.
+ useLayoutEffect(() => {
+ if (!tooltipState) {
+ return;
+ }
+ const cell = anchorCell.current;
+ cell?.setAttribute("aria-describedby", tooltipContentId);
+ return () => cell?.removeAttribute("aria-describedby");
+ }, [tooltipState, tooltipContentId]);
+
+ useEffect(() => {
+ const onDown = () => {
+ pointerDown.current = true;
+ };
+ const onUp = () => {
+ pointerDown.current = false;
+ };
+ window.addEventListener("mousedown", onDown, { capture: true });
+ window.addEventListener("mouseup", onUp, { capture: true });
+ return () => {
+ window.removeEventListener("mousedown", onDown, { capture: true });
+ window.removeEventListener("mouseup", onUp, { capture: true });
+ };
+ }, []);
+
+ const handleCellMouseOver = useEvent(
+ (e: React.MouseEvent, cell: Cell<TData, unknown>) => {
+ // Suppress while a mouse button is held (range-select drag).
+ if (e.buttons !== 0) {
+ return;
+ }
+ const target = e.currentTarget as HTMLElement;
+ const content = computeCellTooltipContent(cell, hoverTemplate);
+ if (content == null || content === "") {
+ hideTooltip();
+ return;
+ }
+ clearTimer();
+ timer.current = window.setTimeout(
+ () => showFor(target, content),
+ TOOLTIP_DELAY_MS,
+ );
+ },
+ );
+
+ const handleCellMouseLeave = useEvent(() => hideTooltip());
+
+ // Keyboard parity: cells are tabIndex=0, native `title` showed on focus too.
+ const handleCellFocus = useEvent(
+ (e: React.FocusEvent, cell: Cell<TData, unknown>) => {
+ // Cancel any pending hover-show so a stale timer can't overwrite the
+ // focus-triggered tooltip after the delay.
+ clearTimer();
+ // Focus also fires for click/drag-select; only keyboard focus (no pointer
+ // held) should show the tooltip, mirroring the hover drag suppression.
+ if (pointerDown.current) {
+ return;
+ }
+ const content = computeCellTooltipContent(cell, hoverTemplate);
+ if (content == null || content === "") {
+ return;
+ }
+ showFor(e.currentTarget as HTMLElement, content);
+ },
+ );
+
+ const handleCellBlur = useEvent(() => hideTooltip());
+
+ // The anchor rect is captured at hover time, so any scroll or resize leaves
+ // it stale; hide instead of tracking. Capture catches scrolls inside the
+ // table's own container too (scroll events don't bubble but do fire in
+ // capture).
+ useEffect(() => {
+ const opts = { passive: true, capture: true } as const;
+ window.addEventListener("scroll", hideTooltip, opts);
+ window.addEventListener("resize", hideTooltip);
+ return () => {
+ window.removeEventListener("scroll", hideTooltip, { capture: true });
+ window.removeEventListener("resize", hideTooltip);
+ };
+ }, [hideTooltip]);
+
+ useEffect(() => clearTimer, []);
+
+ return {
+ tooltipState,
+ tooltipContentId,
+ hideTooltip,
+ handleCellMouseOver,
+ handleCellMouseLeave,
+ handleCellFocus,
+ handleCellBlur,
+ };
+}
diff --git a/frontend/src/components/data-table/renderers.tsx b/frontend/src/components/data-table/renderers.tsx
index 0d435d6682..7f3f7f475e 100644
--- a/frontend/src/components/data-table/renderers.tsx
+++ b/frontend/src/components/data-table/renderers.tsx
@@ -24,11 +24,12 @@ import { cn } from "@/utils/cn";
import { getCellDomProps } from "./cell-utils";
import { COLUMN_WRAPPING_STYLES } from "./column-wrapping/feature";
import { DataTableContextMenu } from "./context-menu";
+import { HoverTooltip } from "./hover-tooltip/hover-tooltip";
+import { useTableHoverTooltip } from "./hover-tooltip/use-table-hover-tooltip";
import { CellRangeSelectionIndicator } from "./range-focus/cell-selection-indicator";
import { useCellRangeSelection } from "./range-focus/use-cell-range-selection";
import { useScrollIntoViewOnFocus } from "./range-focus/use-scroll-into-view";
import { AUTO_WIDTH_MAX_COLUMNS, TABLE_ROW_HEIGHT_PX } from "./types";
-import { stringifyUnknownValue } from "./utils";
export function renderTableHeader<TData>(
table: Table<TData>,
@@ -135,24 +136,7 @@ export const DataTableBody = <TData,>({
contextMenuCell.current = cell;
});
- function applyHoverTemplate(
- template: string,
- cells: Cell<TData, unknown>[],
- ): string {
- const variableRegex = /{{(\w+)}}/g;
- // Map column id -> stringified value
- const idToValue = new Map<string, string>();
- for (const c of cells) {
- const v = c.getValue();
- // Prefer empty string for nulls to keep tooltip clean
- const s = stringifyUnknownValue({ value: v, nullAsEmptyString: true });
- idToValue.set(c.column.id, s);
- }
- return template.replaceAll(variableRegex, (_substr, varName: string) => {
- const val = idToValue.get(varName);
- return val === undefined ? `{{${varName}}}` : val;
- });
- }
+ const hoverTooltip = useTableHoverTooltip({ table });
const renderCells = (cells: Cell<TData, unknown>[]) => {
return cells.map((cell) => {
@@ -163,7 +147,6 @@ export const DataTableBody = <TData,>({
pinningstyle,
);
- const title = cell.getHoverTitle?.() ?? undefined;
return (
<TableCell
tabIndex={0}
@@ -178,10 +161,18 @@ export const DataTableBody = <TData,>({
className,
)}
style={style}
- title={title}
- onMouseDown={(e) => handleCellMouseDown(e, cell)}
+ onMouseDown={(e) => {
+ handleCellMouseDown(e, cell);
+ hoverTooltip.hideTooltip();
+ }}
onMouseUp={handleCellMouseUp}
- onMouseOver={(e) => handleCellMouseOver(e, cell)}
+ onMouseOver={(e) => {
+ handleCellMouseOver(e, cell);
+ hoverTooltip.handleCellMouseOver(e, cell);
+ }}
+ onMouseLeave={hoverTooltip.handleCellMouseLeave}
+ onFocus={(e) => hoverTooltip.handleCellFocus(e, cell)}
+ onBlur={hoverTooltip.handleCellBlur}
onContextMenu={() => handleContextMenu(cell)}
>
<CellRangeSelectionIndicator cellId={cell.id} />
@@ -200,8 +191,6 @@ export const DataTableBody = <TData,>({
}
};
- const hoverTemplate = table.getState().cellHoverTemplate || null;
-
const renderRow = (row: Row<TData>) => {
// Only find the row index if the row viewer panel is open
const rowIndex = rowViewerPanelOpen
@@ -209,22 +198,10 @@ export const DataTableBody = <TData,>({
: undefined;
const isRowViewedInPanel = rowViewerPanelOpen && viewedRowIdx === rowIndex;
- // Compute hover title once per row using all visible cells
- let rowTitle: string | undefined;
- if (hoverTemplate) {
- const visibleCells = row.getVisibleCells?.() ?? [
- ...row.getLeftVisibleCells(),
- ...row.getCenterVisibleCells(),
- ...row.getRightVisibleCells(),
- ];
- rowTitle = applyHoverTemplate(hoverTemplate, visibleCells);
- }
-
return (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
- title={rowTitle}
// These classes ensure that empty rows (nulls) still render
className={cn(
"border-t h-6",
@@ -296,12 +273,19 @@ export const DataTableBody = <TData,>({
);
return (
- <DataTableContextMenu
- tableBody={tableBody}
- contextMenuRef={contextMenuCell}
- tableRef={tableRef}
- copyAllCells={handleCopyAllCells}
- />
+ <>
+ <DataTableContextMenu
+ tableBody={tableBody}
+ contextMenuRef={contextMenuCell}
+ tableRef={tableRef}
+ copyAllCells={handleCopyAllCells}
+ />
+ <HoverTooltip
+ state={hoverTooltip.tooltipState}
+ contentId={hoverTooltip.tooltipContentId}
+ onClose={hoverTooltip.hideTooltip}
+ />
+ </>
);
};