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
TabsPlugin: fix overflow and support vertical tabs (#9511)
Shahmir Varqha8977bc5a1288
diff --git a/frontend/src/plugins/impl/TabsPlugin.tsx b/frontend/src/plugins/impl/TabsPlugin.tsxindex 1a2ad2cd7e..d15823028c 100644--- a/frontend/src/plugins/impl/TabsPlugin.tsx+++ b/frontend/src/plugins/impl/TabsPlugin.tsx@@ -7,6 +7,7 @@ import {TabsList,TabsTrigger,} from "../../components/ui/tabs";+import { cn } from "../../utils/cn";import { renderHTML } from "../core/RenderHTML";import type { IPlugin, IPluginProps } from "../types";import { Labeled } from "./common/labeled";@@ -17,6 +18,7 @@ interface Data {*/tabs: string[];label: string | null;+ orientation: "horizontal" | "vertical";}// Selected tab index@@ -28,6 +30,7 @@ export class TabsPlugin implements IPlugin<T, Data> {validator = z.object({tabs: z.array(z.string()),label: z.string().nullable(),+ orientation: z.enum(["horizontal", "vertical"]).default("horizontal"),});render(props: IPluginProps<T, Data>): JSX.Element {@@ -51,6 +54,7 @@ interface TabComponentProps extends Data {const TabComponent = ({tabs,label,+ orientation,value,setValue,children,@@ -70,19 +74,43 @@ const TabComponent = ({setInternalValue(value);}+ const isVertical = orientation === "vertical";+ const childArray =+ children == null ? [] : Array.isArray(children) ? children : [children];+return (- <Labeled label={label} align="top">- <Tabs value={internalValue} onValueChange={handleChange}>- <TabsList>+ <Labeled label={label} align="top" fullWidth={true}>+ <Tabs+ value={internalValue}+ onValueChange={handleChange}+ orientation={orientation}+ className={cn(isVertical && "flex flex-row gap-3")}+ >+ <TabsList+ className={cn(+ "scrollbar-thin",+ isVertical+ ? "flex flex-col items-stretch justify-start h-auto max-h-none shrink-0 min-w-[10rem] overflow-y-auto"+ : "max-w-full overflow-x-auto justify-start",+ )}+ >{tabs.map((tab, index) => (- <TabsTrigger key={index} value={index.toString()}>+ <TabsTrigger+ key={index}+ value={index.toString()}+ className={cn(isVertical && "w-full justify-start")}+ >{renderHTML({ html: tab })}</TabsTrigger>))}</TabsList>- {React.Children.map(children, (child, index) => {- return <TabsContent value={index.toString()}>{child}</TabsContent>;- })}+ <div className={cn(isVertical && "flex-1 min-w-0")}>+ {childArray.map((child, index) => (+ <TabsContent key={index} value={index.toString()}>+ {child}+ </TabsContent>+ ))}+ </div></Tabs></Labeled>);diff --git a/frontend/src/plugins/impl/__tests__/TabsPlugin.test.tsx b/frontend/src/plugins/impl/__tests__/TabsPlugin.test.tsxnew file mode 100644index 0000000000..4013af122c--- /dev/null+++ b/frontend/src/plugins/impl/__tests__/TabsPlugin.test.tsx@@ -0,0 +1,154 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { fireEvent, render, screen } from "@testing-library/react";+import { beforeAll, describe, expect, it, vi } from "vitest";+import type { z } from "zod";+import { initialModeAtom } from "@/core/mode";+import { store } from "@/core/state/jotai";+import type { IPluginProps } from "../../types";+import { TabsPlugin } from "../TabsPlugin";++describe("TabsPlugin", () => {+ beforeAll(() => {+ store.set(initialModeAtom, "edit");+ });++ const renderPlugin = (+ data: z.input<TabsPlugin["validator"]>,+ initialValue = "0",+ ) => {+ const plugin = new TabsPlugin();+ const host = document.createElement("div");+ const setValue = vi.fn();+ const children = [+ <span key="0">Content 0</span>,+ <span key="1">Content 1</span>,+ <span key="2">Content 2</span>,+ ];+ const makeProps = (+ value: string,+ ): IPluginProps<string, z.infer<TabsPlugin["validator"]>> => ({+ data: plugin.validator.parse(data),+ value,+ setValue,+ host,+ functions: {},+ children,+ });+ const result = render(plugin.render(makeProps(initialValue)));+ return {+ ...result,+ setValue,+ rerenderWithValue: (newValue: string) =>+ result.rerender(plugin.render(makeProps(newValue))),+ };+ };++ it("renders all tab triggers", () => {+ renderPlugin({+ tabs: ["First", "Second", "Third"],+ label: null,+ });+ expect(screen.getByRole("tab", { name: "First" })).toBeInTheDocument();+ expect(screen.getByRole("tab", { name: "Second" })).toBeInTheDocument();+ expect(screen.getByRole("tab", { name: "Third" })).toBeInTheDocument();+ });++ it("supports vertical orientation", () => {+ renderPlugin({+ tabs: ["First", "Second"],+ label: null,+ orientation: "vertical",+ });+ const tablist = screen.getByRole("tablist");+ expect(tablist).toHaveAttribute("data-orientation", "vertical");+ expect(tablist.className).toMatch(/flex-col/);+ // Horizontal scroll classes should not be applied in vertical mode.+ expect(tablist.className).not.toMatch(/overflow-x-auto/);+ });++ it("falls back to horizontal when orientation is omitted (back-compat)", () => {+ // Older Python kernels won't send `orientation` — make sure the validator+ // defaults it so the frontend keeps working.+ const plugin = new TabsPlugin();+ const parsed = plugin.validator.parse({+ tabs: ["First"],+ label: null,+ });+ expect(parsed.orientation).toBe("horizontal");+ });++ it("selects the tab matching the initial value", () => {+ renderPlugin({ tabs: ["First", "Second", "Third"], label: null }, "1");+ const tabs = screen.getAllByRole("tab");+ expect(tabs[0]).toHaveAttribute("data-state", "inactive");+ expect(tabs[1]).toHaveAttribute("data-state", "active");+ expect(tabs[2]).toHaveAttribute("data-state", "inactive");+ });++ it("defaults to the first tab when value is empty", () => {+ renderPlugin({ tabs: ["First", "Second"], label: null }, "");+ const tabs = screen.getAllByRole("tab");+ expect(tabs[0]).toHaveAttribute("data-state", "active");+ expect(tabs[1]).toHaveAttribute("data-state", "inactive");+ });++ it("calls setValue with the clicked tab's index", () => {+ const { setValue } = renderPlugin({+ tabs: ["First", "Second", "Third"],+ label: null,+ });+ // Radix Tabs' trigger reacts to mousedown (left button), not click —+ // see https://github.com/radix-ui/primitives/blob/main/packages/react/tabs/src/Tabs.tsx+ fireEvent.mouseDown(screen.getByRole("tab", { name: "Third" }), {+ button: 0,+ });+ expect(setValue).toHaveBeenCalledWith("2");+ });++ it("syncs selection when value is updated externally", () => {+ const { rerenderWithValue } = renderPlugin(+ { tabs: ["First", "Second", "Third"], label: null },+ "0",+ );+ expect(screen.getAllByRole("tab")[0]).toHaveAttribute(+ "data-state",+ "active",+ );++ rerenderWithValue("2");+ const tabs = screen.getAllByRole("tab");+ expect(tabs[0]).toHaveAttribute("data-state", "inactive");+ expect(tabs[2]).toHaveAttribute("data-state", "active");+ });++ it("renders HTML in tab labels via renderHTML", () => {+ renderPlugin({+ tabs: ["<strong>Bold</strong>", "Plain"],+ label: null,+ });+ const boldTab = screen.getByRole("tab", { name: "Bold" });+ // The label markup is preserved (not escaped as text), so the trigger+ // contains a real <strong> element.+ expect(boldTab.querySelector("strong")).not.toBeNull();+ });++ it("renders no tabpanels when tabs and children are empty", () => {+ // When the Python side passes `tabs={}`, slotted HTML is empty and the+ // resulting React children are null/undefined. We should render zero+ // `TabsContent`s — not a stray one paired to a non-existent trigger.+ const plugin = new TabsPlugin();+ const host = document.createElement("div");+ const props: IPluginProps<string, z.infer<TabsPlugin["validator"]>> = {+ data: plugin.validator.parse({ tabs: [], label: null }),+ value: "",+ setValue: vi.fn(),+ host,+ functions: {},+ children: null,+ };+ render(plugin.render(props));+ expect(screen.queryAllByRole("tab")).toHaveLength(0);+ expect(screen.queryAllByRole("tabpanel")).toHaveLength(0);+ });+});diff --git a/marimo/_plugins/ui/_impl/tabs.py b/marimo/_plugins/ui/_impl/tabs.pyindex 5841ce46a8..cb749b3447 100644--- a/marimo/_plugins/ui/_impl/tabs.py+++ b/marimo/_plugins/ui/_impl/tabs.py@@ -1,7 +1,7 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations-from typing import TYPE_CHECKING, Final+from typing import TYPE_CHECKING, Final, Literalfrom marimo._output.formatting import as_htmlfrom marimo._output.md import md@@ -41,6 +41,14 @@ class tabs(UIElement[str, str]):)```+ Stack tabs vertically (useful when there are many tabs or long labels):+ ```python+ tabs = mo.ui.tabs(+ {f"Section {i}": f"Content {i}" for i in range(20)},+ orientation="vertical",+ )+ ```+Attributes:value (str): The name of the selected tab.@@ -51,6 +59,8 @@ class tabs(UIElement[str, str]):lazy (bool, optional): Whether to lazily load the tab content.This is a convenience that wraps each tab in a `mo.lazy`component. Defaults to False.+ orientation ("horizontal" | "vertical", optional): The orientation of+ the tab bar. Use "vertical" to stack the tabs in a side panel. Defaults to "horizontal".label (str, optional): A descriptive name for the tab. Defaults to "".on_change (Callable[[dict[str, object]], None], optional): Optional callbackto run when this element's value changes.@@ -64,6 +74,7 @@ class tabs(UIElement[str, str]):value: str | None = None,lazy: bool = False,*,+ orientation: Literal["horizontal", "vertical"] = "horizontal",label: str = "",on_change: Callable[[str], None] | None = None,) -> None:@@ -94,7 +105,7 @@ class tabs(UIElement[str, str]):component_name=self._name,initial_value=index or "",label=label,- args={"tabs": tab_labels},+ args={"tabs": tab_labels, "orientation": orientation},on_change=on_change,slotted_html=tab_items,)diff --git a/marimo/_smoke_tests/tabs.py b/marimo/_smoke_tests/tabs.pynew file mode 100644index 0000000000..4311d8731e--- /dev/null+++ b/marimo/_smoke_tests/tabs.py@@ -0,0 +1,265 @@+import marimo++__generated_with = "0.23.6"+app = marimo.App(width="medium")+++def _():+ import marimo as mo++ return (mo,)++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""+ ## 1. Baseline: a few horizontal tabs++ Should look identical to pre-fix behavior — no scrollbar shown,+ nothing visually changed.+ """)+ return+++def _(mo):+ mo.ui.tabs(+ {+ "Hello": mo.md("Hello, world! 👋"),+ "Goodbye": mo.md("See you later."),+ }+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""+ ## 2. Many horizontal tabs++ With 100 tabs, the tab bar should be **horizontally scrollable** — every+ tab is reachable. Try scrolling with the trackpad/mouse wheel and using+ the keyboard arrow keys after focusing a tab.+ """)+ return+++def _(mo):+ mo.ui.tabs({f"tab-{i:02d}": mo.md(f"content {i}") for i in range(100)})+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""+ ## 3. Long labels in horizontal tabs++ Long labels should not wrap inside a single trigger; the tab bar+ scrolls horizontally instead.+ """)+ return+++def _(mo):+ mo.ui.tabs(+ {+ "A reasonably descriptive section title": mo.md("A"),+ "Another wordy heading that takes up space": mo.md("B"),+ "Yet another deliberately verbose tab label": mo.md("C"),+ "And one more for good measure to force overflow": mo.md("D"),+ }+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""+ ## 4. Many tabs, **vertical** orientation++ With `orientation="vertical"`, tabs stack on the left and content+ appears on the right.+ """)+ return+++def _(mo):+ mo.ui.tabs(+ {f"Section {i:02d}": mo.md(f"### Content {i}") for i in range(20)},+ orientation="vertical",+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""+ ## 5. Vertical orientation with rich content+ """)+ return+++def _(mo):+ _user = mo.vstack(+ [+ mo.md("**Edit user**"),+ mo.ui.text(label="First name", value="Ada", placeholder="First name"),+ mo.ui.text(+ label="Last name", value="Lovelace", placeholder="Last name"+ ),+ mo.ui.text(+ label="Email",+ value="[email protected]",+ placeholder="[email protected]",+ ),+ mo.ui.text(+ label="Phone",+ value="+1 (555) 123-4567",+ placeholder="+1 (555) ...",+ ),+ mo.ui.dropdown(+ options=[+ "Developer",+ "Designer",+ "Product Manager",+ "Admin",+ "Other",+ ],+ value="Developer",+ label="Role",+ ),+ ]+ )+ _org = mo.vstack(+ [+ mo.md("**Edit organization**"),+ mo.ui.text(+ label="Organization",+ value="marimo",+ placeholder="Organization name",+ ),+ mo.ui.text(+ label="Website",+ value="https://marimo.ai",+ placeholder="https://...",+ ),+ mo.ui.number(label="Employees", start=0, stop=10000, value=42),+ mo.ui.dropdown(+ options=[+ "Software",+ "Healthcare",+ "Finance",+ "Education",+ "Non-profit",+ "Other",+ ],+ value="Software",+ label="Industry",+ ),+ ]+ )+ mo.ui.tabs(+ {"🧙 User": _user, "🏢 Organization": _org},+ orientation="vertical",+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""+ ## 6. Labeled tabs that overflow++ The label is rendered above the (scrollable) tab bar, and the tab bar+ still scrolls horizontally rather than getting clipped.+ """)+ return+++def _(mo):+ mo.ui.tabs(+ {f"option-{i:02d}": mo.md(f"option body {i}") for i in range(30)},+ label="Pick an option",+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""+ ## 7. `lazy=True` + many tabs++ Switching tabs should still work; only the active tab's content gets+ materialized. Inspect the DOM and confirm that `marimo-lazy` placeholders+ are present for inactive tabs.+ """)+ return+++def _(mo):+ mo.ui.tabs(+ {f"lazy-{i:02d}": mo.md(f"lazy content {i}") for i in range(40)},+ lazy=True,+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""+ ## 8. Markdown in tab labels++ Tab labels are interpreted as markdown — bold/inline code/emoji should+ all render in the trigger, and the bar should still scroll.+ """)+ return+++def _(mo):+ mo.ui.tabs(+ {+ "**Bold**": mo.md("Bold tab"),+ "`code`": mo.md("Code tab"),+ "🚀 Launch": mo.md("Launch tab"),+ "🌗 Theme": mo.md("Theme tab"),+ "_italic_": mo.md("Italic tab"),+ "Plain text": mo.md("Plain tab"),+ "More 1": mo.md("..."),+ "More 2": mo.md("..."),+ "More 3": mo.md("..."),+ "More 4": mo.md("..."),+ "More 5": mo.md("..."),+ "More 6": mo.md("..."),+ }+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""+ ## 9. Invalid orientation raises++ Verify that passing a bad `orientation` value raises a clear+ `ValueError`.+ """)+ return+++def _(mo):+ # Expected to fail+ mo.ui.tabs({"a": "1"}, orientation="diagonal")+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_plugins/ui/_impl/test_tabs.py b/tests/_plugins/ui/_impl/test_tabs.pyindex 767e83b030..c3107fcf3d 100644--- a/tests/_plugins/ui/_impl/test_tabs.py+++ b/tests/_plugins/ui/_impl/test_tabs.py@@ -43,3 +43,18 @@ def test_tabs_lazy() -> None:assert tab.value == "Tab 1"# Verify lazy loading is enabled by checking the slotted HTML contains lazyassert "marimo-lazy" in tab.text+++def test_tabs_default_orientation_is_horizontal() -> None:+ tab = ui.tabs({"Tab 1": "Content 1", "Tab 2": "Content 2"})+ assert tab._component_args["orientation"] == "horizontal" # pyright: ignore[reportPrivateUsage]+++def test_tabs_vertical_orientation() -> None:+ tab = ui.tabs(+ {"Tab 1": "Content 1", "Tab 2": "Content 2"},+ orientation="vertical",+ )+ assert tab._component_args["orientation"] == "vertical" # pyright: ignore[reportPrivateUsage]+ # Orientation should not affect selection behavior+ assert tab.value == "Tab 1"