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: mo.ui.tabs, deprecate mo.tabs (#759)

Myles Scolnick1a8274b884dd
diff --git a/docs/api/inputs/index.md b/docs/api/inputs/index.md
index 58c38f10eb..981b50398c 100644
--- a/docs/api/inputs/index.md
+++ b/docs/api/inputs/index.md
@@ -26,6 +26,7 @@
slider
switch
table
+ tabs
text
text_area
```
@@ -57,6 +58,7 @@ powerful notebooks and apps. These elements are available in `marimo.ui`.
marimo.ui.refresh
marimo.ui.slider
marimo.ui.switch
+ marimo.ui.tabs
marimo.ui.table
marimo.ui.text
marimo.ui.text_area
diff --git a/docs/api/layouts/tabs.md b/docs/api/inputs/tabs.md
similarity index 57%
rename from docs/api/layouts/tabs.md
rename to docs/api/inputs/tabs.md
index cd9a3e0621..eb91bac69a 100644
--- a/docs/api/layouts/tabs.md
+++ b/docs/api/inputs/tabs.md
@@ -3,5 +3,8 @@
<iframe class="demo large" src="https://components.marimo.io/?component=tabs" frameborder="no"></iframe>
```{eval-rst}
-.. autofunction:: marimo.tabs
+.. autoclass:: marimo.ui.tabs
+ :members:
+
+ .. autoclasstoc:: marimo._plugins.ui._impl.tabs.tabs
```
diff --git a/docs/api/layouts/index.md b/docs/api/layouts/index.md
index f3fcaa12d1..9799a6338a 100644
--- a/docs/api/layouts/index.md
+++ b/docs/api/layouts/index.md
@@ -10,7 +10,6 @@
image
justify
stacks
- tabs
tree
```
@@ -28,7 +27,6 @@ certain way.
marimo.hstack
marimo.left
marimo.right
- marimo.tabs
marimo.tree
marimo.vstack
```
diff --git a/docs/apps/output.py b/docs/apps/output.py
index 9b0aa4e866..ddb0176670 100644
--- a/docs/apps/output.py
+++ b/docs/apps/output.py
@@ -12,7 +12,7 @@ def __(tabs):
@app.cell
def __(array, ax, dictionary, mo, plots, table, text):
- tabs = mo.tabs(
+ tabs = mo.ui.tabs(
{
"markdown": mo.md(
r"""
diff --git a/docs/guides/overview.md b/docs/guides/overview.md
index 626c3993d3..c01dab8d8a 100644
--- a/docs/guides/overview.md
+++ b/docs/guides/overview.md
@@ -17,8 +17,8 @@ _When you run a cell, marimo automatically runs all cells that read any global
variables defined by that cell._ This is reactive execution.
> **Reactive execution lets your notebooks double as interactive
-apps**. It also guarantees that your code and program state are
-consistent.
+> apps**. It also guarantees that your code and program state are
+> consistent.
<div align="center">
<figure>
@@ -111,8 +111,8 @@ runs all cells that use the element_, which you can access via its `value`
attribute.
> **This combination of interactivity and reactivity is very powerful**: use it
-to make your data tangible during exploration and to build all kinds of tools
-and apps.
+> to make your data tangible during exploration and to build all kinds of tools
+> and apps.
_marimo can only synchronize UI elements that are assigned to
global variables._ You can use composite elements like `mo.ui.array` and
@@ -141,6 +141,4 @@ collections of elements.
## Layout
The marimo library also comes with layout elements, including `mo.hstack`,
-`mo.vstack`, and `mo.tabs`. See the [API reference](https://docs.marimo.io/api/layouts/index.html) for more info.
-
-
+`mo.vstack`, and `mo.ui.tabs`. See the [API reference](https://docs.marimo.io/api/layouts/index.html) for more info.
diff --git a/examples/dashboards/movies.py b/examples/dashboards/movies.py
index 73cd6d477e..18047fbed1 100644
--- a/examples/dashboards/movies.py
+++ b/examples/dashboards/movies.py
@@ -185,7 +185,7 @@ def __(
@app.cell
def __(filtered_movies, mo):
- mo.tabs(
+ mo.ui.tabs(
{
"📑 Data": mo.ui.table(filtered_movies, selection=None, page_size=5),
"📊 Summary": mo.ui.table(filtered_movies.describe(), selection=None),
diff --git a/examples/embeddings/drawing_graphs.py b/examples/embeddings/drawing_graphs.py
index d94939b41f..b4049ce109 100644
--- a/examples/embeddings/drawing_graphs.py
+++ b/examples/embeddings/drawing_graphs.py
@@ -56,7 +56,7 @@ def __(complete_graph, mo, tree):
def draw_graphs(n_items, penalty, loss):
complete_graph_tab = [penalty, complete_graph(n_items.value, penalty.value)]
tree_tab = [loss, tree(n_items.value, loss.value)]
- return mo.tabs(
+ return mo.ui.tabs(
{
"Complete graph": complete_graph_tab,
"Binary tree": tree_tab,
diff --git a/examples/pokemon_stats/pokemon.py b/examples/pokemon_stats/pokemon.py
index 485cc16fdc..e01f3d560a 100644
--- a/examples/pokemon_stats/pokemon.py
+++ b/examples/pokemon_stats/pokemon.py
@@ -94,7 +94,7 @@ def __(pokemon, pokemon_types):
@app.cell
def __(distribution_plot, drilldown, mo, pokemon_types):
- mo.tabs(
+ mo.ui.tabs(
{
"**Compare distributions**": distribution_plot,
"**Drill down**": drilldown,
diff --git a/examples/table.py b/examples/table.py
index 45d0c3b7b4..6a2ed16f21 100644
--- a/examples/table.py
+++ b/examples/table.py
@@ -39,7 +39,7 @@ def __(mo, office_characters):
@app.cell
def __(mo, single_select_table):
- mo.tabs({"table": single_select_table, "selection": single_select_table.value})
+ mo.ui.tabs({"table": single_select_table, "selection": single_select_table.value})
return
@@ -61,7 +61,7 @@ def __(mo, office_characters):
@app.cell
def __(mo, multi_select_table):
- mo.tabs({"table": multi_select_table, "selection": multi_select_table.value})
+ mo.ui.tabs({"table": multi_select_table, "selection": multi_select_table.value})
return
diff --git a/examples/tabs.py b/examples/tabs.py
index 20cb5efdb3..d032e34235 100644
--- a/examples/tabs.py
+++ b/examples/tabs.py
@@ -12,7 +12,7 @@ def __(mo):
@app.cell
def __(mo):
- mo.md("Use `mo.tabs` to organize outputs.")
+ mo.md("Use `mo.ui.tabs` to organize outputs.")
return
@@ -36,7 +36,7 @@ def __(mo):
]
)
- mo.tabs(
+ mo.ui.tabs(
{
"🧙‍♀ User": settings,
"🏢 Organization": organization,
diff --git a/frontend/e2e-tests/py/kitchen_sink.py b/frontend/e2e-tests/py/kitchen_sink.py
index 47a6a0190f..4ad45507d7 100644
--- a/frontend/e2e-tests/py/kitchen_sink.py
+++ b/frontend/e2e-tests/py/kitchen_sink.py
@@ -429,7 +429,7 @@ def __(create_wrapper, mo):
@app.cell
def __(bar, create_wrapper, mo):
create_wrapper(
- mo.tabs(
+ mo.ui.tabs(
{
"📈 Sales": bar,
"💻 Settings": mo.ui.text(placeholder="Key"),
diff --git a/frontend/src/components/ui/tabs.tsx b/frontend/src/components/ui/tabs.tsx
index 434a8a2263..5f71e34749 100644
--- a/frontend/src/components/ui/tabs.tsx
+++ b/frontend/src/components/ui/tabs.tsx
@@ -13,7 +13,7 @@ const TabsList = React.forwardRef<
<TabsPrimitive.List
ref={ref}
className={cn(
- "inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
+ "inline-flex max-h-14 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
className,
)}
{...props}
@@ -28,7 +28,7 @@ const TabsTrigger = React.forwardRef<
<TabsPrimitive.Trigger
ref={ref}
className={cn(
- "inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
+ "inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
className,
)}
{...props}
diff --git a/frontend/src/plugins/layout/TabsPlugin.tsx b/frontend/src/plugins/impl/TabsPlugin.tsx
similarity index 55%
rename from frontend/src/plugins/layout/TabsPlugin.tsx
rename to frontend/src/plugins/impl/TabsPlugin.tsx
index f14acc5662..2c7eae539a 100644
--- a/frontend/src/plugins/layout/TabsPlugin.tsx
+++ b/frontend/src/plugins/impl/TabsPlugin.tsx
@@ -8,8 +8,8 @@ import {
TabsContent,
} from "../../components/ui/tabs";
import { z } from "zod";
-import { IStatelessPlugin, IStatelessPluginProps } from "../stateless-plugin";
import { renderHTML } from "../core/RenderHTML";
+import { IPlugin, IPluginProps } from "../types";
interface Data {
/**
@@ -18,24 +18,44 @@ interface Data {
tabs: string[];
}
-export class TabsPlugin implements IStatelessPlugin<Data> {
+// Selected tab index
+type T = string;
+
+export class TabsPlugin implements IPlugin<T, Data> {
tagName = "marimo-tabs";
validator = z.object({
tabs: z.array(z.string()),
});
- render(props: IStatelessPluginProps<Data>): JSX.Element {
- return <TabComponent {...props.data}>{props.children}</TabComponent>;
+ render(props: IPluginProps<T, Data>): JSX.Element {
+ return (
+ <TabComponent
+ {...props.data}
+ value={props.value}
+ setValue={props.setValue}
+ >
+ {props.children}
+ </TabComponent>
+ );
}
}
+interface TabComponentProps extends Data {
+ value: T;
+ setValue: (value: T) => void;
+}
+
const TabComponent = ({
tabs,
+ value,
+ setValue,
children,
-}: PropsWithChildren<Data>): JSX.Element => {
+}: PropsWithChildren<TabComponentProps>): JSX.Element => {
+ // We use the index since labels are raw HTML and can't be used as keys
+ const selectedTab = value || "0";
return (
- <Tabs defaultValue="0">
+ <Tabs value={selectedTab} onValueChange={setValue}>
<TabsList>
{tabs.map((tab, index) => (
<TabsTrigger key={index} value={index.toString()}>
diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.ts
index 416c6f7e0f..03c282a70a 100644
--- a/frontend/src/plugins/plugins.ts
+++ b/frontend/src/plugins/plugins.ts
@@ -22,7 +22,7 @@ import { IStatelessPlugin } from "./stateless-plugin";
import { AccordionPlugin } from "./layout/AccordionPlugin";
import { CalloutPlugin } from "./layout/CalloutPlugin";
import { JsonOutputPlugin } from "./layout/JsonOutputPlugin";
-import { TabsPlugin } from "./layout/TabsPlugin";
+import { TabsPlugin } from "./impl/TabsPlugin";
import { TexPlugin } from "./layout/TexPlugin";
import { RefreshPlugin } from "./impl/RefreshPlugin";
import { MicrophonePlugin } from "./impl/MicrophonePlugin";
@@ -54,6 +54,7 @@ export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [
new RefreshPlugin(),
new SliderPlugin(),
new SwitchPlugin(),
+ new TabsPlugin(),
new TextAreaPlugin(),
new TextInputPlugin(),
new VegaPlugin(),
diff --git a/marimo/_plugins/stateless/tabs.py b/marimo/_plugins/stateless/tabs.py
index 0291eeb8df..3a71bdebb9 100644
--- a/marimo/_plugins/stateless/tabs.py
+++ b/marimo/_plugins/stateless/tabs.py
@@ -1,16 +1,18 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from marimo._output.formatting import as_html
from marimo._output.hypertext import Html
-from marimo._output.md import md
from marimo._output.rich_help import mddoc
-from marimo._plugins.core.web_component import build_stateless_plugin
+from marimo._plugins.ui._impl.tabs import tabs as tabs_impl
+from marimo._utils.deprecated import deprecated
@mddoc
+@deprecated("mo.tabs is deprecated. Use mo.ui.tabs instead")
def tabs(tabs: dict[str, object]) -> Html:
"""
+ **Deprecated.**: Use `mo.ui.tabs` instead.
+
Tabs of UI elements.
**Examples.**
@@ -41,19 +43,4 @@ def tabs(tabs: dict[str, object]) -> Html:
- An `Html` object.
"""
- tab_items = "".join(
- [
- "<div data-kind='tab'>"
- + (md(tab).text if isinstance(tab, str) else as_html(tab).text)
- + "</div>"
- for tab in tabs.values()
- ]
- )
- tab_labels = list(md(label).text for label in tabs.keys())
- return Html(
- build_stateless_plugin(
- component_name="marimo-tabs",
- args={"tabs": tab_labels},
- slotted_html=tab_items,
- )
- )
+ return tabs_impl(tabs)
diff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.py
index 9f97c1133a..4926b8b5ce 100644
--- a/marimo/_plugins/ui/__init__.py
+++ b/marimo/_plugins/ui/__init__.py
@@ -27,6 +27,7 @@ __all__ = [
"slider",
"switch",
"table",
+ "tabs",
"text_area",
"text",
]
@@ -58,3 +59,4 @@ from marimo._plugins.ui._impl.plotly import plotly
from marimo._plugins.ui._impl.refresh import refresh
from marimo._plugins.ui._impl.switch import switch
from marimo._plugins.ui._impl.table import table
+from marimo._plugins.ui._impl.tabs import tabs
diff --git a/marimo/_plugins/ui/_impl/tabs.py b/marimo/_plugins/ui/_impl/tabs.py
new file mode 100644
index 0000000000..0315b4a87b
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/tabs.py
@@ -0,0 +1,94 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Callable, Final, Optional
+
+from marimo._output.formatting import as_html
+from marimo._output.md import md
+from marimo._output.rich_help import mddoc
+from marimo._plugins.ui._core.ui_element import UIElement
+
+
+@mddoc
+class tabs(UIElement[str, str]):
+ """Display objects in a tabbed view.
+
+ **Examples.**
+
+ Show content in tabs:
+
+ ```python
+ tab1 = mo.vstack([
+ "slider": mo.ui.slider(1, 10),
+ "text": mo.ui.text(),
+ "date": mo.ui.date()
+ ])
+
+ tab2 = mo.md("You can show arbitrary content in a tab.")
+
+ tabs = mo.ui.tabs({
+ "Heading 1": tab1,
+ "Heading 2": tab2
+ })
+ ```
+
+ Control which tab is selected:
+
+ ```python
+ tabs = mo.ui.tabs({
+ "Heading 1": tab1,
+ "Heading 2": tab2
+ }, value="Heading 2")
+ ```
+
+ **Attributes.**
+
+ - `value`: A string, the name of the selected tab.
+
+ **Initialization Args.**
+
+ - `tabs`: a dictionary of tab names to tab content; strings are interpreted
+ as markdown
+ - `value`: the name of the tab to open; defaults to the first tab
+ """
+
+ _name: Final[str] = "marimo-tabs"
+
+ def __init__(
+ self,
+ tabs: dict[str, object],
+ value: Optional[str] = None,
+ *,
+ label: str = "",
+ on_change: Optional[Callable[[str], None]] = None,
+ ) -> None:
+ tab_items = "".join(
+ [
+ "<div data-kind='tab'>"
+ + (md(tab).text if isinstance(tab, str) else as_html(tab).text)
+ + "</div>"
+ for tab in tabs.values()
+ ]
+ )
+
+ self._tab_keys = list(tabs.keys())
+ tab_labels = list(md(label).text for label in tabs.keys())
+
+ index = (
+ self._tab_keys.index(value)
+ if value in self._tab_keys and tabs
+ else 0
+ )
+
+ super().__init__(
+ component_name=self._name,
+ initial_value=str(index),
+ label=label,
+ args={"tabs": tab_labels},
+ on_change=on_change,
+ slotted_html=tab_items,
+ )
+
+ def _convert_value(self, value: str) -> str:
+ index = int(value)
+ return self._tab_keys[index]
diff --git a/marimo/_tutorials/layout.py b/marimo/_tutorials/layout.py
index 55519b1779..ed813839c5 100644
--- a/marimo/_tutorials/layout.py
+++ b/marimo/_tutorials/layout.py
@@ -240,7 +240,7 @@ def __(mo):
"""
## Tabs
- Use `mo.tabs` to display multiple objects in a single tabbed output:
+ Use `mo.ui.tabs` to display multiple objects in a single tabbed output:
"""
)
return
@@ -264,7 +264,7 @@ def __(mo):
]
)
- mo.tabs(
+ mo.ui.tabs(
{
"🧙‍♀ User": _settings,
"🏢 Organization": _organization,
@@ -275,7 +275,7 @@ def __(mo):
@app.cell(hide_code=True)
def __(mo):
- mo.accordion({"Documentation: `mo.tabs`": mo.doc(mo.tabs)})
+ mo.accordion({"Documentation: `mo.ui.tabs`": mo.doc(mo.ui.tabs)})
return
diff --git a/marimo/_tutorials/ui.py b/marimo/_tutorials/ui.py
index 6cb0d91502..713526ba31 100644
--- a/marimo/_tutorials/ui.py
+++ b/marimo/_tutorials/ui.py
@@ -1,7 +1,8 @@
# Copyright 2024 Marimo. All rights reserved.
+
import marimo
-__generated_with = "0.1.4"
+__generated_with = "0.2.2"
app = marimo.App()
@@ -385,7 +386,11 @@ def __(mo):
@app.cell
def __(get_shared_state, mo, set_shared_state):
x = mo.ui.slider(
- 0, 10, value=get_shared_state(), on_change=set_shared_state, label="$x$:"
+ 0,
+ 10,
+ value=get_shared_state(),
+ on_change=set_shared_state,
+ label="$x$:",
)
return x,
@@ -441,7 +446,6 @@ def __(dataclass, mo):
name: str
done: bool = False
-
get_tasks, set_tasks = mo.state([])
task_list_mutated, set_task_list_mutated = mo.state(False)
return (
@@ -468,12 +472,10 @@ def __(Task, mo, set_task_list_mutated, set_tasks, task_entry_box):
set_tasks(lambda v: v + [Task(task_entry_box.value)])
set_task_list_mutated(True)
-
def clear_tasks():
set_tasks(lambda v: [task for task in v if not task.done])
set_task_list_mutated(True)
-
add_task_button = mo.ui.button(
label="add task",
on_change=lambda _: add_task(),
@@ -488,7 +490,10 @@ def __(Task, mo, set_task_list_mutated, set_tasks, task_entry_box):
@app.cell
def __(Task, get_tasks, mo, set_tasks):
task_list = mo.ui.array(
- [mo.ui.checkbox(value=task.done, label=task.name) for task in get_tasks()],
+ [
+ mo.ui.checkbox(value=task.done, label=task.name)
+ for task in get_tasks()
+ ],
label="tasks",
on_change=lambda v: set_tasks(
lambda tasks: [
@@ -559,6 +564,7 @@ def __(mo):
"radio": mo.ui.radio,
"slider": mo.ui.slider,
"switch": mo.ui.switch,
+ "tabs": mo.ui.tabs,
"table": mo.ui.table,
"text": mo.ui.text,
"text_area": mo.ui.text_area,
@@ -573,7 +579,9 @@ def __(mo):
def __(mo):
def construct_element(value):
if value == mo.ui.array:
- return mo.ui.array([mo.ui.text(), mo.ui.slider(1, 10), mo.ui.date()])
+ return mo.ui.array(
+ [mo.ui.text(), mo.ui.slider(1, 10), mo.ui.date()]
+ )
elif value == mo.ui.batch:
return mo.md(
"""
@@ -619,6 +627,19 @@ def __(mo):
return mo.ui.slider(start=1, stop=10, step=0.5)
elif value == mo.ui.switch:
return mo.ui.switch()
+ elif value == mo.ui.tabs:
+ return mo.ui.tabs(
+ {
+ "Employee #1": {
+ "first_name": "Michael",
+ "last_name": "Scott",
+ },
+ "Employee #2": {
+ "first_name": "Dwight",
+ "last_name": "Schrute",
+ },
+ }
+ )
elif value == mo.ui.table:
return mo.ui.table(
data=[
@@ -665,7 +686,11 @@ def __(mo):
def documentation(element):
if element is not None:
return mo.accordion(
- {f"Documentation on `mo.ui.{element.__name__}`": mo.doc(element)}
+ {
+ f"Documentation on `mo.ui.{element.__name__}`": mo.doc(
+ element
+ )
+ }
)
return documentation,
diff --git a/marimo/_utils/deprecated.py b/marimo/_utils/deprecated.py
new file mode 100644
index 0000000000..4406cf8472
--- /dev/null
+++ b/marimo/_utils/deprecated.py
@@ -0,0 +1,23 @@
+# Copyright 2024 Marimo. All rights reserved.
+import functools
+import warnings
+from typing import Any, Callable
+
+
+def deprecated(reason: str) -> Callable[[Any], Any]:
+ """A decorator that emits a deprecation warning."""
+
+ def decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]:
+ @functools.wraps(func)
+ def wrapper(*args: Any, **kwargs: Any) -> Callable[[Any], Any]:
+ # stacklevel=2 shows the line number in the call site
+ warnings.warn(
+ message=reason,
+ category=DeprecationWarning,
+ stacklevel=2,
+ )
+ return func(*args, **kwargs) # type: ignore[no-any-return]
+
+ return wrapper
+
+ return decorator