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: show rich elems in datatables (#4204)

Shahmir Varqhacdbb6b1502f0
diff --git a/frontend/src/components/data-table/__tests__/columns.test.tsx b/frontend/src/components/data-table/__tests__/columns.test.tsx
index 5ab44c02bf..5de9e2ac77 100644
--- a/frontend/src/components/data-table/__tests__/columns.test.tsx
+++ b/frontend/src/components/data-table/__tests__/columns.test.tsx
@@ -5,6 +5,7 @@ import { UrlDetector } from "../url-detector";
import { render } from "@testing-library/react";
import { generateColumns, inferFieldTypes } from "../columns";
import type { FieldTypesWithExternalType } from "../types";
+import { getMimeValues, isMimeValue, MimeCell } from "../mime-cell";
test("uniformSample", () => {
const items = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];
@@ -242,3 +243,84 @@ describe("generateColumns", () => {
expect(columns[1].id).toBe("age");
});
});
+
+describe("MimeCell", () => {
+ it("renders with correct mime data", () => {
+ const value = { mimetype: "text/plain", data: "Hello World" };
+ const { container } = render(<MimeCell value={value} />);
+ expect(container.textContent).toContain("Hello World");
+ });
+});
+
+describe("isMimeValue", () => {
+ it("should return true for valid MimeValue objects", () => {
+ const value = { mimetype: "text/plain", data: "test data" };
+ expect(isMimeValue(value)).toBe(true);
+ });
+
+ it("should return false for null", () => {
+ expect(isMimeValue(null)).toBe(false);
+ });
+
+ it("should return false for primitive values", () => {
+ expect(isMimeValue("string")).toBe(false);
+ expect(isMimeValue(123)).toBe(false);
+ expect(isMimeValue(true)).toBe(false);
+ });
+
+ it("should return false for objects missing required properties", () => {
+ expect(isMimeValue({})).toBe(false);
+ expect(isMimeValue({ mimetype: "text/plain" })).toBe(false);
+ expect(isMimeValue({ data: "test data" })).toBe(false);
+ });
+});
+
+describe("getMimeValues", () => {
+ it("should return array with single MimeValue when input is a MimeValue", () => {
+ const value = { mimetype: "text/plain", data: "test data" };
+ expect(getMimeValues(value)).toEqual([value]);
+ });
+
+ it("should return array with MimeValue when input has serialized_mime_bundle", () => {
+ const mimeValue = { mimetype: "text/plain", data: "test data" };
+ const value = { serialized_mime_bundle: mimeValue };
+ expect(getMimeValues(value)).toEqual([mimeValue]);
+ });
+
+ it("should return array of MimeValues when input is an array of MimeValues", () => {
+ const values = [
+ { mimetype: "text/plain", data: "test data 1" },
+ { mimetype: "text/html", data: "<p>test data 2</p>" },
+ ];
+ expect(getMimeValues(values)).toEqual(values);
+ });
+
+ it("should return undefined for null input", () => {
+ expect(getMimeValues(null)).toBeUndefined();
+ });
+
+ it("should return undefined for primitive values", () => {
+ expect(getMimeValues("string")).toBeUndefined();
+ expect(getMimeValues(123)).toBeUndefined();
+ expect(getMimeValues(true)).toBeUndefined();
+ });
+
+ it("should return undefined for objects that don't match any pattern", () => {
+ expect(getMimeValues({})).toBeUndefined();
+ expect(getMimeValues({ random: "property" })).toBeUndefined();
+ });
+
+ it("should return undefined for invalid serialized_mime_bundle", () => {
+ expect(
+ getMimeValues({ serialized_mime_bundle: "not a mime value" }),
+ ).toBeUndefined();
+ });
+
+ it("should return undefined for array with non-MimeValue items", () => {
+ const values = [
+ { mimetype: "text/plain", data: "test data" },
+ "not a mime value",
+ ];
+ expect(getMimeValues(values)).toBeUndefined();
+ });
+});
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index ff05b45ddb..a5096409f0 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -7,7 +7,7 @@ import {
DataTableColumnHeaderWithSummary,
} from "./column-header";
import { Checkbox } from "../ui/checkbox";
-import { isMimeValue, MimeCell } from "./mime-cell";
+import { getMimeValues, MimeCell } from "./mime-cell";
import type { DataType } from "@/core/kernel/messages";
import { TableColumnSummary } from "./column-summary";
import type { FilterType } from "./filters";
@@ -278,7 +278,8 @@ export function generateColumns<T>({
);
}
- if (isMimeValue(value)) {
+ const mimeValues = getMimeValues(value);
+ if (mimeValues) {
return (
<div
onClick={selectCell}
@@ -289,7 +290,9 @@ export function generateColumns<T>({
isCellSelected,
)}
>
- <MimeCell value={value} />
+ {mimeValues.map((mimeValue, idx) => (
+ <MimeCell key={idx} value={mimeValue} />
+ ))}
</div>
);
}
@@ -297,36 +300,34 @@ export function generateColumns<T>({
if (Array.isArray(value) || typeof value === "object") {
const rawStringValue = renderAny(value);
return (
- <div
- onClick={selectCell}
- className={getCellStyleClass(
- justify,
- wrapped,
- canSelectCell,
- isCellSelected,
- )}
- >
- <EmotionCacheProvider container={null}>
- <Popover>
- <PopoverTrigger>
- <span
- className="cursor-pointer hover:text-link"
- title={rawStringValue}
- >
- {rawStringValue}
- </span>
- </PopoverTrigger>
- <PopoverContent>
- <PopoverClose className="absolute top-2 right-2">
- <Button variant="link" size="xs">
- Close
- </Button>
- </PopoverClose>
- <JsonOutput data={value} format="tree" />
- </PopoverContent>
- </Popover>
- </EmotionCacheProvider>
- </div>
+ <EmotionCacheProvider container={null}>
+ <Popover>
+ <PopoverTrigger
+ className={getCellStyleClass(
+ justify,
+ wrapped,
+ canSelectCell,
+ isCellSelected,
+ )}
+ onClick={selectCell}
+ >
+ <span
+ className="cursor-pointer hover:text-link"
+ title={rawStringValue}
+ >
+ {rawStringValue}
+ </span>
+ </PopoverTrigger>
+ <PopoverContent>
+ <PopoverClose className="absolute top-2 right-2">
+ <Button variant="link" size="xs">
+ Close
+ </Button>
+ </PopoverClose>
+ <JsonOutput data={value} format="tree" className="max-h-64" />
+ </PopoverContent>
+ </Popover>
+ </EmotionCacheProvider>
);
}
diff --git a/frontend/src/components/data-table/mime-cell.tsx b/frontend/src/components/data-table/mime-cell.tsx
index f2c4bd35a1..b08a0c5936 100644
--- a/frontend/src/components/data-table/mime-cell.tsx
+++ b/frontend/src/components/data-table/mime-cell.tsx
@@ -35,3 +35,31 @@ export function isMimeValue(value: unknown): value is MimeValue {
"data" in value
);
}
+
+export function getMimeValues(value: unknown): MimeValue[] | undefined {
+ if (isMimeValue(value)) {
+ return [value];
+ }
+
+ const hasSerializedMimeBundle =
+ typeof value === "object" &&
+ value !== null &&
+ "serialized_mime_bundle" in value;
+
+ if (hasSerializedMimeBundle) {
+ const serializedMimeBundle = value.serialized_mime_bundle;
+ if (isMimeValue(serializedMimeBundle)) {
+ return [serializedMimeBundle];
+ }
+ }
+
+ // can also be a list of mime values
+ // only return if all values are mime values
+ // TODO: Maybe support mixed mime values and non-mime values
+ if (Array.isArray(value)) {
+ const allMimeType = value.every(isMimeValue);
+ if (allMimeType) {
+ return value.map((v) => v);
+ }
+ }
+}
diff --git a/frontend/src/components/editor/output/JsonOutput.tsx b/frontend/src/components/editor/output/JsonOutput.tsx
index a0eaa8c700..65e58f9749 100644
--- a/frontend/src/components/editor/output/JsonOutput.tsx
+++ b/frontend/src/components/editor/output/JsonOutput.tsx
@@ -90,7 +90,7 @@ export const JsonOutput: React.FC<Props> = memo(
case "tree":
return (
<JsonViewer
- className="marimo-json-output"
+ className={cn("marimo-json-output", className)}
rootName={name}
theme={theme}
displayDataTypes={false}
diff --git a/marimo/_output/hypertext.py b/marimo/_output/hypertext.py
index f2b3388140..789f6b89db 100644
--- a/marimo/_output/hypertext.py
+++ b/marimo/_output/hypertext.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import os
import weakref
from contextlib import contextmanager
+from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Literal, Optional, cast, final
from marimo._messaging.mimetypes import KnownMimeType
@@ -37,6 +38,7 @@ def _hypertext_cleanup(virtual_filenames: list[str]) -> None:
@mddoc
+@dataclass
class Html(MIME):
"""A wrapper around HTML text that can be used as an output.
@@ -69,12 +71,24 @@ class Html(MIME):
right: right-justify this element in the output area
"""
+ # Some libraries (e.g. polars) will serialize dataclasses so we add this
+ # field to serialize the mimetype. This is to support rich display in tables/dfs.
+ serialized_mime_bundle: dict[Literal["mimetype", "data"], str] = field(
+ default_factory=dict
+ )
+
def __init__(self, text: str) -> None:
"""Initialize the HTML element.
Subclasses of HTML MUST call this method.
"""
self._text = text
+ mimetype, data = self._mime_()
+ self.serialized_mime_bundle = {
+ "mimetype": mimetype,
+ "data": data,
+ }
+
# A list of the virtual file names referenced by this HTML element.
self._virtual_filenames: list[str] = []
diff --git a/marimo/_smoke_tests/tables/complex_types.py b/marimo/_smoke_tests/tables/complex_types.py
index f3f7bab293..018d92e5d6 100644
--- a/marimo/_smoke_tests/tables/complex_types.py
+++ b/marimo/_smoke_tests/tables/complex_types.py
@@ -1,6 +1,6 @@
import marimo
-__generated_with = "0.11.20"
+__generated_with = "0.11.24"
app = marimo.App(width="medium")
diff --git a/marimo/_smoke_tests/tables/rich_elements.py b/marimo/_smoke_tests/tables/rich_elements.py
new file mode 100644
index 0000000000..2f2eb4b855
--- /dev/null
+++ b/marimo/_smoke_tests/tables/rich_elements.py
@@ -0,0 +1,197 @@
+import marimo
+
+__generated_with = "0.11.24"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+ import pandas as pd
+ import polars as pl
+ import altair as alt
+ return alt, mo, pd, pl
+
+
+def _(mo):
+ mo.md(r"""# Printing Rich Elements""")
+ return
+
+
[email protected](hide_code=True)
+def _(alt, mo, pd):
+ text = mo.ui.text(placeholder="Enter", on_change=lambda x: print("hi"))
+ warn_btn = mo.ui.button(
+ kind="warn", on_click=lambda x: print("button clicked!")
+ )
+ password = mo.ui.text(kind="password", value="secret")
+
+ dictionary = mo.ui.dictionary(
+ {
+ "slider": mo.ui.slider(1, 10),
+ "text": mo.ui.text(),
+ "date": mo.ui.date(),
+ }
+ )
+
+
+ def simple_echo_model(messages, config):
+ return f"You said: {messages[-1].content}"
+
+
+ chat = mo.ui.chat(
+ simple_echo_model,
+ prompts=["Hello", "How are you?"],
+ show_configuration_controls=True,
+ )
+
+ img = mo.image(
+ src="https://marimo.io/logo.png",
+ alt="Marimo logo",
+ width=100,
+ height=100,
+ )
+ html_img = mo.Html(
+ "<img src='https://marimo.io/logo.png' width='100px' height='100px' alt='Marimo logo'>"
+ )
+
+ office_characters = [
+ {"first_name": "Michael", "last_name": "Scott"},
+ {"first_name": "Jenna", "last_name": "Leigh"},
+ ]
+ table = mo.ui.table(office_characters)
+
+ user_info = mo.md(
+ """
+ - What's your name?: {name}
+ - When were you born?: {birthday}
+ """
+ ).batch(name=mo.ui.text(), birthday=mo.ui.date())
+
+ source = pd.DataFrame(
+ {
+ "a": ["A", "B", "C", "D", "E", "F", "G", "H", "I"],
+ "b": [28, 55, 43, 91, 81, 53, 19, 87, 52],
+ }
+ )
+
+ chart = alt.Chart(source).mark_bar().encode(x="a", y="b")
+
+ mermaid = mo.mermaid(
+ "graph TD\n A[Christmas] -->|Get money| B(Go shopping)\n B --> C{Let me think}\n C -->|One| D[Laptop]\n C -->|Two| E[iPhone]\n C -->|Three| F[Car]"
+ )
+
+ tabs = mo.ui.tabs(
+ {
+ "📈 Sales": chart,
+ "📊 Chatbot": chat,
+ "💻 Settings": mo.ui.text(placeholder="Key"),
+ }
+ )
+
+
+ data = {
+ "buttons": [mo.ui.button(kind="warn"), mo.ui.button(kind="invalid")],
+ "mixed": [mo.ui.button(kind="info"), "apples"],
+ "arrays": mo.ui.array([text] * 2),
+ "dictionary": [dictionary, dictionary],
+ "raw_objects": [
+ {"fruits": ["apples", "bananas"]},
+ {"trees": {"plants": "flowers"}},
+ ],
+ "raw_lists": [
+ ["fruits", "trees", "animals"],
+ ["humans", "aliens", "life"],
+ ],
+ "images": [img, html_img],
+ "batch": user_info,
+ "dropdowns": [
+ mo.ui.dropdown(options=["apple", "bananas", "coconut"]),
+ mo.ui.multiselect(options=["apple", "bananas", "coconut"]),
+ ],
+ "markdown": mo.md("## Inputs here"),
+ "chat": chat,
+ "file": mo.ui.file(),
+ "table": table,
+ "chart": mo.ui.altair_chart(chart),
+ "mermaid": mermaid,
+ "tabs": tabs,
+ }
+
+ mo.vstack([mo.md("## Dictionary"), data])
+ return (
+ chart,
+ chat,
+ data,
+ dictionary,
+ html_img,
+ img,
+ mermaid,
+ office_characters,
+ password,
+ simple_echo_model,
+ source,
+ table,
+ tabs,
+ text,
+ user_info,
+ warn_btn,
+ )
+
+
+def _(data, mo):
+ mo.vstack([mo.md("## Table"), mo.ui.table(data, page_size=20)])
+ return
+
+
+def _(data, mo, pd):
+ pandas_rich = pd.DataFrame(data).transpose()
+ mo.vstack([mo.md("## Pandas dataframe"), pandas_rich])
+ return (pandas_rich,)
+
+
+def _(mo, pandas_rich):
+ mo.vstack([mo.md("## Table containing pandas df"), mo.ui.table(pandas_rich)])
+ return
+
+
+def _(data, mo, pl):
+ data.pop("arrays", None)
+ data.pop("batch", None)
+ data.pop("mixed", None)
+
+ pl_df = pl.DataFrame(data)
+ mo.vstack([mo.md("## Polars dataframe"), pl_df])
+ return (pl_df,)
+
+
+def _(mo, password):
+ mo.md(f"### Password value: {password.value}")
+ return
+
+
+def _(mo, pl_df):
+ mo.vstack([mo.md("## Table containing polars dataframe"), mo.ui.table(pl_df)])
+ return
+
+
+def _(mo):
+ mo.md(f"""
+ ## This will crash the kernel (hence not enabled)
+
+ `pl.DataFrame(data).transpose()`
+ """)
+ # pl.DataFrame(data).transpose()
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_output/test_hypertext.py b/tests/_output/test_hypertext.py
index 2dcb7aac68..3e339d3a93 100644
--- a/tests/_output/test_hypertext.py
+++ b/tests/_output/test_hypertext.py
@@ -20,6 +20,11 @@ def test_html_mime():
assert mime_type == "text/html"
assert content == "<p>Test</p>"
+ assert html.serialized_mime_bundle == {
+ "mimetype": "text/html",
+ "data": "<p>Test</p>",
+ }
+
def test_html_format():
html = Html("<p>\n Hello\n</p>")