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
add a html slot on the right side of a stat plugin (#7384)
Shahmir Varqha1a490f7d22b9
diff --git a/docs/api/layouts/stat.md b/docs/api/layouts/stat.mdindex 1d2ba34c3a..b292d980bc 100644--- a/docs/api/layouts/stat.md+++ b/docs/api/layouts/stat.md@@ -4,32 +4,69 @@```python@app.cell-def __():+def _():active_users = mo.stat(- value="1.2M",- label="Active Users",- caption="12k from last month",+ value="1.2M",+ label="Active Users",+ caption="12k from last month",direction="increase")revenue = mo.stat(- value="$4.5M",- label="Revenue",- caption="8k from last quarter",+ value="$4.5M",+ label="Revenue",+ caption="8k from last quarter",direction="increase")-+conversion = mo.stat(- value="3.8",- label="Conversion Rate",- caption="0.5 from last week",+ value="3.8",+ label="Conversion Rate",+ caption="0.5 from last week",direction="decrease",)-+mo.hstack([active_users, revenue, conversion], justify="center", gap="2rem")return```+```python+def _():+ import altair as alt+ import polars as pl++ alt.renderers.set_embed_options(actions=False)++ df = pl.DataFrame(+ {+ "revenue": [30, 20, 70, 45],+ "dates": ["01/01/2024", "01/03/2024", "01/06/2024", "01/09/2024"],+ }+ )++ chart = (+ alt.Chart(df)+ .mark_line(interpolate="monotone")+ .encode(+ x=alt.X("dates", axis=None),+ y=alt.Y("revenue", axis=None),+ tooltip=["dates", "revenue"],+ )+ .properties(height=40, width=60, background="transparent")+ .configure_view(strokeWidth=0)+ )++ mo.stat(+ value=df["revenue"][-1],+ label="Revenue",+ caption="QoQ Growth",+ direction="increase",+ bordered=True,+ slot=chart,+ )+ return+```+///::: marimo.statdiff --git a/frontend/src/plugins/impl/vega/vega.css b/frontend/src/plugins/impl/vega/vega.cssindex 5556ea0951..f22eed232e 100644--- a/frontend/src/plugins/impl/vega/vega.css+++ b/frontend/src/plugins/impl/vega/vega.css@@ -8,6 +8,11 @@@media (min-width: 500px) {min-width: 300px;}++ /* For vega embeds in slots, reset the styles to let the user set the width */+ @container style(--slot: true) {+ min-width: unset;+ }}.vega-embed > .chart-wrapper {diff --git a/frontend/src/plugins/layout/StatPlugin.tsx b/frontend/src/plugins/layout/StatPlugin.tsxindex 1fec7b8369..5ad451eb81 100644--- a/frontend/src/plugins/layout/StatPlugin.tsx+++ b/frontend/src/plugins/layout/StatPlugin.tsx@@ -4,8 +4,11 @@ import { TriangleIcon } from "lucide-react";import type { JSX } from "react";import { useLocale } from "react-aria";import { z } from "zod";+import { getMimeValues } from "@/components/data-table/mime-cell";import { cn } from "@/utils/cn";+import { Logger } from "@/utils/Logger";import { prettyNumber } from "@/utils/numbers";+import { renderHTML } from "../core/RenderHTML";import type {IStatelessPlugin,IStatelessPluginProps,@@ -18,6 +21,7 @@ interface Data {bordered?: boolean;direction?: "increase" | "decrease";target_direction?: "increase" | "decrease";+ slot?: object;}export class StatPlugin implements IStatelessPlugin<Data> {@@ -30,6 +34,7 @@ export class StatPlugin implements IStatelessPlugin<Data> {bordered: z.boolean().default(false),direction: z.enum(["increase", "decrease"]).optional(),target_direction: z.enum(["increase", "decrease"]).default("increase"),+ slot: z.any().optional(),});render({ data }: IStatelessPluginProps<Data>): JSX.Element {@@ -44,6 +49,7 @@ export const StatComponent: React.FC<Data> = ({bordered,direction,target_direction,+ slot,}) => {const { locale } = useLocale();@@ -71,39 +77,53 @@ export const StatComponent: React.FC<Data> = ({const fillColor = onTarget ? "var(--grass-8)" : "var(--red-8)";const strokeColor = onTarget ? "var(--grass-9)" : "var(--red-9)";+ const renderSlot = () => {+ const mimeValues = getMimeValues(slot);+ if (mimeValues?.[0]) {+ const { mimetype, data } = mimeValues[0];+ if (mimetype !== "text/html") {+ Logger.warn(`Expected text/html, got ${mimetype}`);+ }+ return renderHTML({ html: data, alwaysSanitizeHtml: true });+ }+ };+return (<divclassName={cn(- "text-card-foreground",+ "text-card-foreground p-6",bordered && "rounded-xl border shadow bg-card",)}>{label && (- <div className="p-6 flex flex-row items-center justify-between space-y-0 pb-2">+ <div className="flex flex-row items-center justify-between space-y-0 pb-2"><h3 className="tracking-tight text-sm font-medium">{label}</h3></div>)}- <div className="p-6 pt-0">- <div className="text-2xl font-bold">{renderPrettyValue()}</div>- {caption && (- <p className="pt-1 text-xs text-muted-foreground flex align-center">- {direction === "increase" && (- <TriangleIcon- className="w-4 h-4 mr-1 p-0.5"- fill={fillColor}- stroke={strokeColor}- />- )}- {direction === "decrease" && (- <TriangleIcon- className="w-4 h-4 mr-1 p-0.5 transform rotate-180"- fill={fillColor}- stroke={strokeColor}- />- )}- {caption}- </p>- )}+ <div className="pt-0 flex flex-row gap-3.5">+ <div>+ <div className="text-2xl font-bold">{renderPrettyValue()}</div>+ {caption && (+ <p className="pt-1 text-xs text-muted-foreground flex align-center whitespace-nowrap">+ {direction === "increase" && (+ <TriangleIcon+ className="w-4 h-4 mr-1 p-0.5"+ fill={fillColor}+ stroke={strokeColor}+ />+ )}+ {direction === "decrease" && (+ <TriangleIcon+ className="w-4 h-4 mr-1 p-0.5 transform rotate-180"+ fill={fillColor}+ stroke={strokeColor}+ />+ )}+ {caption}+ </p>+ )}+ </div>+ {slot && <div className="[--slot:true]">{renderSlot()}</div>}</div></div>);diff --git a/marimo/_plugins/stateless/stat.py b/marimo/_plugins/stateless/stat.pyindex bd9e84b71c..6c95392f2a 100644--- a/marimo/_plugins/stateless/stat.py+++ b/marimo/_plugins/stateless/stat.py@@ -1,13 +1,17 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Literal, Optional, Union+from typing import Any, Literal, Optional, Union+from marimo._loggers import marimo_logger+from marimo._output.formatting import as_htmlfrom marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddocfrom marimo._plugins.core.web_component import build_stateless_pluginfrom marimo._plugins.utils import remove_none_values+Logger = marimo_logger()+@mddocdef stat(@@ -17,6 +21,7 @@ def stat(direction: Optional[Literal["increase", "decrease"]] = None,bordered: bool = False,target_direction: Optional[Literal["increase", "decrease"]] = "increase",+ slot: Optional[Html] = None,) -> Html:"""Display a statistic.@@ -34,6 +39,7 @@ def stat(`increase` when higher values are better, or `decrease`when lower values are better. By default the targetdirection is `increase`.+ slot: an optional Html object to place beside the widgetReturns:@@ -50,7 +56,21 @@ def stat("direction": direction,"bordered": bordered,"target_direction": target_direction,+ "slot": try_convert_to_html(slot),}),))+++def try_convert_to_html(slot: Any) -> Optional[Html]:+ if slot is None:+ return None++ try:+ return as_html(slot)+ except Exception as e:+ Logger.error(+ f"Error converting slot to Html: {e}. Please ensure it is a valid Html object."+ )+ return Nonediff --git a/marimo/_smoke_tests/stats.py b/marimo/_smoke_tests/stats.pyindex f75c810ffa..d054f3b875 100644--- a/marimo/_smoke_tests/stats.py+++ b/marimo/_smoke_tests/stats.py@@ -2,14 +2,16 @@import marimo-__generated_with = "0.15.5"+__generated_with = "0.18.2"app = marimo.App()@app.celldef _():import marimo as mo- return (mo,)+ import polars as pl+ import altair as alt+ return alt, mo, pl@app.cell@@ -74,5 +76,101 @@ def _(mo):return[email protected](hide_code=True)+def _(alt, mo, pl):+ findata = pl.DataFrame(+ {+ "revenue": [30, 20, 70, 45, 68, 34, 87, 100],+ "dates": [+ "01/01/2024",+ "01/03/2024",+ "01/06/2024",+ "01/09/2024",+ "01/12/2024",+ "01/15/2024",+ "01/18/2024",+ "01/21/2024",+ ],+ }+ )++ alt.renderers.set_embed_options(actions=False)+++ def create_chart(mark: str) -> alt.Chart:+ chart = alt.Chart(findata)+ if mark == "line":+ chart = chart.mark_line(interpolate="monotone")+ else:+ chart = chart.mark_bar()+ chart = (+ chart.encode(+ x=alt.X("dates", axis=None),+ y=alt.Y("revenue", axis=None),+ tooltip=["dates", "revenue"],+ )+ .properties(height=40, width=60, background="transparent")+ .configure_view(strokeWidth=0)+ )+ return chart+++ hello_world = mo.Html("<h2><i>Hello, World</i></h2>")++ _stats = [+ mo.stat(+ "$100",+ label="Revenue",+ caption="+ 10%",+ direction="increase",+ bordered=True,+ slot=create_chart("line"),+ ),+ mo.stat(+ "$20",+ label="Marketing spend",+ caption="+ 10%",+ direction="increase",+ target_direction="decrease",+ slot=create_chart("bar"),+ ),+ mo.stat(+ "$80",+ label="Profit",+ caption="- 10%",+ direction="decrease",+ bordered=True,+ slot="🚀🧑🚀💰",+ ),+ ]++ _rich = [+ mo.stat(+ "$20",+ label="Marketing spend",+ caption="+ 10%",+ direction="increase",+ target_direction="decrease",+ slot=hello_world,+ ),+ mo.stat(+ "2%",+ label="Churn",+ caption="- 2%",+ direction="decrease",+ bordered=True,+ target_direction="decrease",+ slot=_stats[0],+ ),+ ]+++ _first = mo.hstack(_stats, widths="equal", gap=1)+ _second = mo.hstack(_rich, widths="equal", gap=1)++ mo.vstack([_first, _second])+ return++if __name__ == "__main__":app.run()diff --git a/tests/_plugins/stateless/test_stat.py b/tests/_plugins/stateless/test_stat.pynew file mode 100644index 0000000000..1c75b7489b--- /dev/null+++ b/tests/_plugins/stateless/test_stat.py@@ -0,0 +1,40 @@+# Copyright 2024 Marimo. All rights reserved.++import pytest++from marimo._dependencies.dependencies import DependencyManager+from marimo._output.hypertext import Html+from marimo._plugins.stateless.stat import try_convert_to_html+++def test_try_convert_to_html_valid_html():+ result = try_convert_to_html("<div>Hello, World!</div>")+ assert result is not None+ assert result.text == "<span><div>Hello, World!</div></span>"+++def test_try_convert_to_html_plain():+ result = try_convert_to_html(123)+ assert isinstance(result, Html)+ assert result.text == "<span>123</span>"+++def test_try_convert_to_html_none():+ result = try_convert_to_html(None)+ assert result is None+++ not DependencyManager.altair.has() or not DependencyManager.pandas.has(),+ reason="optional dependencies not installed",+)+def test_try_convert_to_html_altair_chart():+ import altair as alt+ import pandas as pd++ df = pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})+ chart = alt.Chart(df).mark_point().encode(x="x", y="y")+ result = try_convert_to_html(chart)+ assert isinstance(result, Html)+ assert "<marimo-mime-renderer" in result.text+ assert "application/vnd.vega" in result.text