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: add mo.nav_menu (#1344)

Myles Scolnickeda9523a9639
diff --git a/docs/api/inputs/nav_menu.md b/docs/api/inputs/nav_menu.md
new file mode 100644
index 0000000000..7c0b53e453
--- /dev/null
+++ b/docs/api/inputs/nav_menu.md
@@ -0,0 +1,45 @@
+# Navigation Menu
+
+```{eval-rst}
+.. marimo-embed::
+ :size: large
+
+ @app.cell
+ def __():
+ nav_menu = mo.nav_menu({
+ "/overview": "Overview",
+ "Sales": {
+ "/sales": {
+ "label": "Sales",
+ "description": "View sales and revenue",
+ },
+ "/sales/invoices": {
+ "label": "Invoices",
+ "description": "View invoices and payments",
+ },
+ "/sales/customers": {
+ "label": "Customers",
+ "description": "View customers and subscriptions",
+ },
+ },
+ "Products": {
+ "/products": {
+ "label": "Products",
+ "description": "View and manage products",
+ },
+ "/products/inventory": {
+ "label": "Inventory",
+ "description": "View inventory and stock levels",
+ },
+ "/products/categories": {
+ "label": "Categories",
+ "description": "View categories and products",
+ },
+ },
+ })
+ return
+```
+
+```{eval-rst}
+.. autofunction:: marimo.nav_menu
+```
diff --git a/docs/api/layouts/index.md b/docs/api/layouts/index.md
index d6c8724ddd..16f5a7d5e0 100644
--- a/docs/api/layouts/index.md
+++ b/docs/api/layouts/index.md
@@ -10,6 +10,7 @@
callout
justify
lazy
+ nav_menu
stacks
tree
```
@@ -33,6 +34,7 @@ them but just render their children in a certain way.
marimo.hstack
marimo.lazy
marimo.left
+ marimo.nav_menu
marimo.right
marimo.tree
marimo.vstack
diff --git a/docs/guides/outputs.md b/docs/guides/outputs.md
index a31f66fd37..f9930df2f9 100644
--- a/docs/guides/outputs.md
+++ b/docs/guides/outputs.md
@@ -5,7 +5,6 @@ Outputs are included in the "app" or read-only view of the notebook. marimo
comes out of the box a number of elements to help you make rich outputs,
documented in the [API reference](/api/index/).
-
<div align="center">
<figure>
<img src="/_static/outputs.gif"/>
@@ -62,14 +61,13 @@ mo.md(
)
```
-
## Layout
The marimo library also comes with elements for laying out outputs, including
[`mo.hstack`](#marimo.hstack), [`mo.vstack`](#marimo.vstack),
[`mo.accordion`](#marimo.accordion), [`mo.ui.tabs`](#marimo.ui.tabs),
-[`mo.ui.table`](#marimo.ui.table), and [many
-more](https://docs.marimo.io/api/layouts/index.html).
+[`mo.nav_menu`](#marimo.nav_menu), [`mo.ui.table`](#marimo.ui.table),
+and [many more](https://docs.marimo.io/api/layouts/index.html).
## Media
diff --git a/docs/guides/overview.md b/docs/guides/overview.md
index 0d974782d1..a1ba36e0be 100644
--- a/docs/guides/overview.md
+++ b/docs/guides/overview.md
@@ -18,7 +18,7 @@ _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 guarantees that your code and program state are
-> consistent.** It also gives notebooks a deterministic execution order,
+> consistent.** It also gives notebooks a deterministic execution order,
> letting them double as both reproducible scripts and interactive apps.
<div align="center">
@@ -151,11 +151,10 @@ collections of elements.
</figure>
</div>
-
## Layout
The marimo library also comes with elements for laying out outputs, including
[`mo.hstack`](#marimo.hstack), [`mo.vstack`](#marimo.vstack),
[`mo.accordion`](#marimo.accordion), [`mo.ui.tabs`](#marimo.ui.tabs),
-[`mo.ui.table`](#marimo.ui.table), and [many
-more](https://docs.marimo.io/api/layouts/index.html).
+[`mo.nav_menu`](#marimo.nav_menu), [`mo.ui.table`](#marimo.ui.table),
+and [many more](https://docs.marimo.io/api/layouts/index.html).
diff --git a/frontend/package.json b/frontend/package.json
index cfcb0c832b..e0dfb13c99 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -48,6 +48,7 @@
"@radix-ui/react-dropdown-menu": "^2.0.6",
"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-label": "^2.0.2",
+ "@radix-ui/react-navigation-menu": "^1.1.4",
"@radix-ui/react-popover": "^1.0.7",
"@radix-ui/react-progress": "^1.0.3",
"@radix-ui/react-radio-group": "^1.1.3",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 4bc6fac775..8d312a1134 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -110,6 +110,9 @@ dependencies:
'@radix-ui/react-label':
specifier: ^2.0.2
+ '@radix-ui/react-navigation-menu':
+ specifier: ^1.1.4
'@radix-ui/react-popover':
specifier: ^1.0.7
@@ -4101,6 +4104,40 @@ packages:
react-remove-scroll: 2.5.5(@types/[email protected])([email protected])
dev: false
+ resolution: {integrity: sha512-Cc+seCS3PmWmjI51ufGG7zp1cAAIRqHVw7C9LOA2TZ+R4hG6rDvHcTqIsEEFLmZO3zNVH72jOOE7kKNy8W+RtA==}
+ peerDependencies:
+ '@types/react': '*'
+ '@types/react-dom': '*'
+ react: ^16.8 || ^17.0 || ^18.0
+ react-dom: ^16.8 || ^17.0 || ^18.0
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+ dependencies:
+ '@babel/runtime': 7.24.4
+ '@radix-ui/primitive': 1.0.1
+ '@radix-ui/react-collection': 1.0.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@radix-ui/react-compose-refs': 1.0.1(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.0.1(@types/[email protected])([email protected])
+ '@radix-ui/react-direction': 1.0.1(@types/[email protected])([email protected])
+ '@radix-ui/react-dismissable-layer': 1.0.5(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@radix-ui/react-id': 1.0.1(@types/[email protected])([email protected])
+ '@radix-ui/react-presence': 1.0.1(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@radix-ui/react-primitive': 1.0.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@radix-ui/react-use-callback-ref': 1.0.1(@types/[email protected])([email protected])
+ '@radix-ui/react-use-controllable-state': 1.0.1(@types/[email protected])([email protected])
+ '@radix-ui/react-use-layout-effect': 1.0.1(@types/[email protected])([email protected])
+ '@radix-ui/react-use-previous': 1.0.1(@types/[email protected])([email protected])
+ '@radix-ui/react-visually-hidden': 1.0.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@types/react': 18.3.1
+ '@types/react-dom': 18.3.0
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ dev: false
+
resolution: {integrity: sha512-shtvVnlsxT6faMnK/a7n0wptwBD23xc1Z5mdrtKLwVEfsEMXodS0r5s0/g5P0hX//EKYZS2sxUjqfzlg52ZSnQ==}
peerDependencies:
diff --git a/frontend/src/components/ui/navigation.tsx b/frontend/src/components/ui/navigation.tsx
new file mode 100644
index 0000000000..80a2a120ce
--- /dev/null
+++ b/frontend/src/components/ui/navigation.tsx
@@ -0,0 +1,138 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import * as React from "react";
+import { ChevronDownIcon } from "@radix-ui/react-icons";
+import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu";
+import { VariantProps, cva } from "class-variance-authority";
+import { cn } from "@/utils/cn";
+
+const NavigationMenu = React.forwardRef<
+ React.ElementRef<typeof NavigationMenuPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Root>
+>(({ className, children, ...props }, ref) => (
+ <NavigationMenuPrimitive.Root
+ ref={ref}
+ className={cn(
+ "relative z-10 flex max-w-max flex-1 items-center justify-center",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <NavigationMenuViewport />
+ </NavigationMenuPrimitive.Root>
+));
+NavigationMenu.displayName = NavigationMenuPrimitive.Root.displayName;
+
+const navigationMenuListStyle = cva("group flex list-none gap-1", {
+ variants: {
+ orientation: {
+ horizontal: "flex items-center",
+ vertical: "flex flex-col",
+ },
+ },
+ defaultVariants: {
+ orientation: "horizontal",
+ },
+});
+
+const NavigationMenuList = React.forwardRef<
+ React.ElementRef<typeof NavigationMenuPrimitive.List>,
+ React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.List> &
+ VariantProps<typeof navigationMenuListStyle>
+>(({ className, orientation, ...props }, ref) => (
+ <NavigationMenuPrimitive.List
+ ref={ref}
+ className={cn(navigationMenuListStyle({ orientation }), className)}
+ {...props}
+ />
+));
+NavigationMenuList.displayName = NavigationMenuPrimitive.List.displayName;
+
+const NavigationMenuItem = NavigationMenuPrimitive.Item;
+
+const navigationMenuTriggerStyle = cva(
+ "group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50",
+);
+
+const NavigationMenuTrigger = React.forwardRef<
+ React.ElementRef<typeof NavigationMenuPrimitive.Trigger>,
+ React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Trigger>
+>(({ className, children, ...props }, ref) => (
+ <NavigationMenuPrimitive.Trigger
+ ref={ref}
+ className={cn(navigationMenuTriggerStyle(), "group", className)}
+ {...props}
+ >
+ {children}{" "}
+ <ChevronDownIcon
+ className="relative top-[1px] ml-1 h-3 w-3 transition duration-300 group-data-[state=open]:rotate-180"
+ aria-hidden="true"
+ />
+ </NavigationMenuPrimitive.Trigger>
+));
+NavigationMenuTrigger.displayName = NavigationMenuPrimitive.Trigger.displayName;
+
+const NavigationMenuContent = React.forwardRef<
+ React.ElementRef<typeof NavigationMenuPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Content>
+>(({ className, ...props }, ref) => (
+ <NavigationMenuPrimitive.Content
+ ref={ref}
+ className={cn(
+ "left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto ",
+ className,
+ )}
+ {...props}
+ />
+));
+NavigationMenuContent.displayName = NavigationMenuPrimitive.Content.displayName;
+
+const NavigationMenuLink = NavigationMenuPrimitive.Link;
+
+const NavigationMenuViewport = React.forwardRef<
+ React.ElementRef<typeof NavigationMenuPrimitive.Viewport>,
+ React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Viewport>
+>(({ className, ...props }, ref) => (
+ <div className={cn("absolute left-0 top-full flex justify-center")}>
+ <NavigationMenuPrimitive.Viewport
+ className={cn(
+ "origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",
+ className,
+ )}
+ ref={ref}
+ {...props}
+ />
+ </div>
+));
+NavigationMenuViewport.displayName =
+ NavigationMenuPrimitive.Viewport.displayName;
+
+const NavigationMenuIndicator = React.forwardRef<
+ React.ElementRef<typeof NavigationMenuPrimitive.Indicator>,
+ React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Indicator>
+>(({ className, ...props }, ref) => (
+ <NavigationMenuPrimitive.Indicator
+ ref={ref}
+ className={cn(
+ "top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",
+ className,
+ )}
+ {...props}
+ >
+ <div className="relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md" />
+ </NavigationMenuPrimitive.Indicator>
+));
+NavigationMenuIndicator.displayName =
+ NavigationMenuPrimitive.Indicator.displayName;
+
+export {
+ navigationMenuTriggerStyle,
+ NavigationMenu,
+ NavigationMenuList,
+ NavigationMenuItem,
+ NavigationMenuContent,
+ NavigationMenuTrigger,
+ NavigationMenuLink,
+ NavigationMenuIndicator,
+ NavigationMenuViewport,
+};
diff --git a/frontend/src/plugins/layout/NavigationMenuPlugin.tsx b/frontend/src/plugins/layout/NavigationMenuPlugin.tsx
new file mode 100644
index 0000000000..35e14bb6de
--- /dev/null
+++ b/frontend/src/plugins/layout/NavigationMenuPlugin.tsx
@@ -0,0 +1,196 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { PropsWithChildren } from "react";
+
+import { z } from "zod";
+import { IStatelessPlugin, IStatelessPluginProps } from "../stateless-plugin";
+import {
+ NavigationMenu,
+ NavigationMenuList,
+ NavigationMenuItem,
+ NavigationMenuTrigger,
+ NavigationMenuContent,
+ NavigationMenuLink,
+ navigationMenuTriggerStyle,
+} from "@/components/ui/navigation";
+import { cn } from "@/utils/cn";
+import React from "react";
+import { renderHTML } from "@/plugins/core/RenderHTML";
+import { Tooltip, TooltipProvider } from "@/components/ui/tooltip";
+
+interface MenuItem {
+ label: string;
+ href: string;
+ description?: string | null;
+}
+
+interface MenuItemGroup {
+ label: string;
+ items: MenuItem[];
+}
+
+interface Data {
+ /**
+ * The labels for each item; raw HTML.
+ */
+ items: Array<MenuItem | MenuItemGroup>;
+
+ /**
+ * The orientation of the menu.
+ */
+ orientation: "horizontal" | "vertical";
+}
+
+export class NavigationMenuPlugin implements IStatelessPlugin<Data> {
+ tagName = "marimo-nav-menu";
+
+ private menuItemValidator = z.object({
+ label: z.string(),
+ href: z.string(),
+ description: z.string().nullish(),
+ });
+
+ private menuItemGroupValidator = z.object({
+ label: z.string(),
+ items: z.array(this.menuItemValidator),
+ });
+
+ validator = z.object({
+ items: z.array(
+ z.union([this.menuItemValidator, this.menuItemGroupValidator]),
+ ),
+ orientation: z.enum(["horizontal", "vertical"]),
+ });
+
+ render(props: IStatelessPluginProps<Data>): JSX.Element {
+ return (
+ <TooltipProvider>
+ <NavMenuComponent {...props.data} />
+ </TooltipProvider>
+ );
+ }
+}
+
+type NavMenuComponentProps = Data;
+
+const NavMenuComponent = ({
+ items,
+ orientation,
+}: PropsWithChildren<NavMenuComponentProps>): JSX.Element => {
+ const maybeWithTooltip = (
+ component: JSX.Element,
+ description?: string | null,
+ ) => {
+ return description ? (
+ <Tooltip delayDuration={200} content={renderHTML({ html: description })}>
+ {component}
+ </Tooltip>
+ ) : (
+ component
+ );
+ };
+
+ const renderMenuItem = (item: MenuItem | MenuItemGroup) => {
+ if ("items" in item) {
+ return orientation === "horizontal" ? (
+ <NavigationMenuItem key={item.label}>
+ <NavigationMenuTrigger>
+ {renderHTML({ html: item.label })}
+ </NavigationMenuTrigger>
+ <NavigationMenuContent>
+ <NavigationMenuList>
+ <ul className="grid w-[400px] gap-3 p-4 md:w-[500px] md:grid-cols-2 lg:w-[600px] ">
+ {item.items.map((subItem) => (
+ <ListItem
+ key={subItem.label}
+ label={subItem.label}
+ href={subItem.href}
+ >
+ {subItem.description &&
+ renderHTML({ html: subItem.description })}
+ </ListItem>
+ ))}
+ </ul>
+ </NavigationMenuList>
+ </NavigationMenuContent>
+ </NavigationMenuItem>
+ ) : (
+ <NavigationMenuItem key={item.label}>
+ <div
+ className={
+ "inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium text-muted-foreground/80 tracking-wide font-semibold"
+ }
+ >
+ {renderHTML({ html: item.label })}
+ </div>
+ <NavigationMenuList className="ml-4" orientation={orientation}>
+ {item.items.map((subItem) => (
+ <React.Fragment key={subItem.label}>
+ {maybeWithTooltip(
+ <NavigationMenuLink
+ key={subItem.label}
+ href={subItem.href}
+ className={navigationMenuTriggerStyle()}
+ >
+ {renderHTML({ html: subItem.label })}
+ </NavigationMenuLink>,
+ subItem.description,
+ )}
+ </React.Fragment>
+ ))}
+ </NavigationMenuList>
+ </NavigationMenuItem>
+ );
+ }
+
+ return (
+ <NavigationMenuItem key={item.label}>
+ <NavigationMenuLink
+ href={item.href}
+ className={navigationMenuTriggerStyle()}
+ >
+ {renderHTML({ html: item.label })}
+ </NavigationMenuLink>
+ </NavigationMenuItem>
+ );
+ };
+
+ return (
+ <NavigationMenu orientation={orientation}>
+ <NavigationMenuList orientation={orientation}>
+ {items.map((item) => renderMenuItem(item))}
+ </NavigationMenuList>
+ </NavigationMenu>
+ );
+};
+
+const ListItem = React.forwardRef<
+ React.ElementRef<"a">,
+ React.ComponentPropsWithoutRef<"a"> & {
+ label: string;
+ }
+>(({ className, label, children, ...props }, ref) => {
+ return (
+ <li>
+ <NavigationMenuLink asChild={true}>
+ <a
+ ref={ref}
+ className={cn(
+ "block select-none space-y-1 rounded-md p-3 leading-none no-underline outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground",
+ className,
+ )}
+ {...props}
+ >
+ <div className="text-sm font-medium leading-none">
+ {renderHTML({ html: label })}
+ </div>
+ {children && (
+ <p className="line-clamp-2 text-sm leading-snug text-muted-foreground">
+ {children}
+ </p>
+ )}
+ </a>
+ </NavigationMenuLink>
+ </li>
+ );
+});
+ListItem.displayName = "ListItem";
diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.ts
index 38823f4210..1c0dddd7e4 100644
--- a/frontend/src/plugins/plugins.ts
+++ b/frontend/src/plugins/plugins.ts
@@ -40,6 +40,7 @@ import { DataExplorerPlugin } from "./impl/data-explorer/DataExplorerPlugin";
import { MermaidPlugin } from "./layout/mermaid/MermaidPlugin";
import { AnyWidgetPlugin } from "./impl/anywidget/AnyWidgetPlugin";
import { LazyPlugin } from "./layout/LazyPlugin";
+import { NavigationMenuPlugin } from "@/plugins/layout/NavigationMenuPlugin";
// List of UI plugins
export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [
@@ -83,6 +84,7 @@ const LAYOUT_PLUGINS: Array<IStatelessPlugin<unknown>> = [
new StatPlugin(),
new TexPlugin(),
new MermaidPlugin(),
+ new NavigationMenuPlugin(),
];
export function initializePlugins() {
diff --git a/marimo/__init__.py b/marimo/__init__.py
index 4674ad4ab7..17786dbf41 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -39,6 +39,7 @@ __all__ = [
"md",
"mermaid",
"mpl",
+ "nav_menu",
"output",
"plain_text",
"pdf",
@@ -81,6 +82,7 @@ from marimo._plugins.stateless.icon import icon
from marimo._plugins.stateless.image import image
from marimo._plugins.stateless.lazy import lazy
from marimo._plugins.stateless.mermaid import mermaid
+from marimo._plugins.stateless.nav_menu import nav_menu
from marimo._plugins.stateless.pdf import pdf
from marimo._plugins.stateless.plain_text import plain_text
from marimo._plugins.stateless.stat import stat
diff --git a/marimo/_plugins/stateless/nav_menu.py b/marimo/_plugins/stateless/nav_menu.py
new file mode 100644
index 0000000000..6401c67e44
--- /dev/null
+++ b/marimo/_plugins/stateless/nav_menu.py
@@ -0,0 +1,152 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from dataclasses import asdict, dataclass
+from typing import List, Literal, Optional, Union, cast
+
+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 JSONType, build_stateless_plugin
+
+
+@mddoc
+def nav_menu(
+ menu: dict[str, JSONType],
+ *,
+ orientation: Literal["horizontal", "vertical"] = "horizontal",
+) -> Html:
+ """
+ Navigation menu component.
+
+ This is useful for creating a navigation menu with hyperlinks,
+ most used when creating multi-page applications, with
+ `marimo.create_asgi_app` ([docs](https://docs.marimo.io/guides/deploying/programmatically.html)).
+
+ **Examples.**
+
+ ```python
+ nav_menu = mo.nav_menu(
+ {
+ "/overview": "Overview",
+ "/sales": f"{mo.icon('lucide:shopping-cart')} Sales",
+ "/products": f"{mo.icon('lucide:package')} Products",
+ }
+ )
+ ```
+
+ # You can also nest dictionaries to create submenus
+ ```python
+ nav_menu = mo.nav_menu({
+ "/overview": "Overview",
+ "Sales": {
+ "/sales": "Overview",
+ "/sales/invoices": {
+ "label": "Invoices",
+ "description": "View invoices",
+ },
+ "/sales/customers": {
+ "label": "Customers",
+ "description": "View customers",
+ },
+ },
+ })
+
+ **Args.**
+
+ - `menu`: a dictionary of tab names to tab content;
+ the content can also be nested dictionaries (one level deep)
+ strings are interpreted as markdown
+
+ **Returns.**
+
+ - An `Html` object.
+ """
+
+ menu_items = _build_and_validate_menu(menu)
+
+ return Html(
+ build_stateless_plugin(
+ component_name="marimo-nav-menu",
+ args={
+ "items": asdict(menu_items)["items"],
+ "orientation": orientation,
+ },
+ )
+ )
+
+
+@dataclass
+class NavMenu:
+ items: List[Union[NavMenuItemLink, NavMenuItemGroup]]
+
+
+@dataclass
+class NavMenuItemLink:
+ label: str
+ href: str
+ description: Optional[str] = None
+
+
+@dataclass
+class NavMenuItemGroup:
+ label: str
+ items: List[NavMenuItemLink]
+
+
+def _build_and_validate_menu(menu: dict[str, JSONType]) -> NavMenu:
+ def validate_href(href: str) -> str:
+ if not isinstance(href, str):
+ raise ValueError(f"Invalid href: {href}, expected string")
+ if href.startswith("/") or href.startswith("#"):
+ return href
+ raise ValueError(f"Invalid href: {href}, must start with / or #")
+
+ items: List[Union[NavMenuItemLink, NavMenuItemGroup]] = []
+ for k, v in menu.items():
+ if isinstance(v, str):
+ items.append(
+ NavMenuItemLink(label=md(v).text, href=validate_href(k))
+ )
+ elif isinstance(v, dict):
+ subitems: List[NavMenuItemLink] = []
+ for kk, vv in v.items():
+ if isinstance(vv, str):
+ subitems.append(
+ NavMenuItemLink(
+ label=md(vv).text, href=validate_href(kk)
+ )
+ )
+ elif isinstance(vv, dict):
+ label = vv.get("label")
+ description = vv.get("description", None)
+ if not label or not isinstance(label, str):
+ raise ValueError(
+ f"Invalid submenu item: {vv}, missing label"
+ )
+ if description and not isinstance(description, str):
+ raise ValueError(
+ f"Invalid submenu item: {vv}, expected"
+ " string for description"
+ )
+ subitems.append(
+ NavMenuItemLink(
+ label=md(label).text,
+ href=validate_href(kk),
+ description=(
+ md(cast(str, description)).text
+ if description
+ else None
+ ),
+ )
+ )
+ else:
+ raise ValueError(
+ f"Invalid submenu item: {vv}, expected string, or dict"
+ )
+ items.append(NavMenuItemGroup(label=md(k).text, items=subitems))
+ else:
+ raise ValueError(
+ f"Invalid menu item: {v}, expected string or dict"
+ )
+ return NavMenu(items=items)
diff --git a/marimo/_smoke_tests/nav_menus.py b/marimo/_smoke_tests/nav_menus.py
new file mode 100644
index 0000000000..ef974bb8af
--- /dev/null
+++ b/marimo/_smoke_tests/nav_menus.py
@@ -0,0 +1,118 @@
+# Copyright 2024 Marimo. All rights reserved.
+
+import marimo
+
+__generated_with = "0.5.0"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md("# Horizontal")
+ return
+
+
+def __(mo):
+ mo.nav_menu(
+ {
+ "#overview": "Overview",
+ "#sales": f"{mo.icon('lucide:shopping-cart')} Sales",
+ "#products": f"{mo.icon('lucide:package')} Products",
+ }
+ )
+ return
+
+
+def __(mo):
+ mo.md("-----")
+ return
+
+
+def __(mo):
+ mo.nav_menu(
+ {
+ "#overview": "Overview",
+ f"{mo.icon('lucide:shopping-cart')} Sales": {
+ "/sales-today": "Sales today",
+ "/sales-yesterday": "Sales yesterday",
+ "/sales-custom": {
+ "label": "Custom",
+ "description": "Create custom filters to query sales",
+ },
+ },
+ f"{mo.icon('lucide:package')} Products": {
+ "#products-today": "Products today",
+ "#products-yesterday": "Products yesterday",
+ "#products-custom": {
+ "label": "Custom",
+ "description": "Create custom filters to query products",
+ },
+ },
+ }
+ )
+ return
+
+
+def __(mo):
+ mo.md("# Vertical")
+ return
+
+
+def __(mo):
+ mo.nav_menu(
+ {
+ "#overview": "Overview",
+ "#sales": f"{mo.icon('lucide:shopping-cart')} Sales",
+ "#products": f"{mo.icon('lucide:package')} Products",
+ },
+ orientation="vertical",
+ )
+ return
+
+
+def __(mo):
+ mo.md("-----")
+ return
+
+
+def __(mo):
+ mo.nav_menu(
+ {
+ "#overview": "Overview",
+ "Sales": {
+ "#sales-today": "Sales today",
+ "#sales-yesterday": "Sales yesterday",
+ "#sales-custom": {
+ "label": "Custom",
+ "description": "Create custom filters to query sales",
+ },
+ },
+ "Products": {
+ "#products-today": "Products today",
+ "#products-yesterday": "Products yesterday",
+ "#products-custom": {
+ "label": "Custom",
+ "description": "Create custom filters to query products",
+ },
+ },
+ },
+ orientation="vertical",
+ )
+ return
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_plugins/ui/_impl/test_nav_menu.py b/tests/_plugins/ui/_impl/test_nav_menu.py
new file mode 100644
index 0000000000..61f7dc1587
--- /dev/null
+++ b/tests/_plugins/ui/_impl/test_nav_menu.py
@@ -0,0 +1,52 @@
+from __future__ import annotations
+
+import pytest
+
+from marimo._plugins.stateless.nav_menu import (
+ NavMenu,
+ NavMenuItemGroup,
+ NavMenuItemLink,
+ _build_and_validate_menu,
+)
+
+
+def test_build_and_validate_menu():
+ # Test with a simple menu dictionary
+ menu = {
+ "/overview": "Overview",
+ "/sales": "Sales",
+ "/products": "Products",
+ }
+ result = _build_and_validate_menu(menu)
+ assert isinstance(result, NavMenu)
+ assert all(isinstance(item, NavMenuItemLink) for item in result.items)
+
+ # Test with a nested menu dictionary
+ menu: dict[str, dict[str, str]] = {
+ "Overview": {"/overview": "Overview", "/overview/summary": "Summary"},
+ "Sales": {"/sales": "Sales", "/sales/summary": "Summary"},
+ "Products": {"/products": "Products", "/products/summary": "Summary"},
+ }
+ result = _build_and_validate_menu(menu)
+ assert isinstance(result, NavMenu)
+ assert all(isinstance(item, NavMenuItemGroup) for item in result.items)
+
+ # Test with invalid href
+ menu = {"overview": "Overview"}
+ with pytest.raises(ValueError):
+ _build_and_validate_menu(menu)
+
+ # Test with invalid menu item
+ menu = {"/overview": 123}
+ with pytest.raises(ValueError):
+ _build_and_validate_menu(menu)
+
+ # Test with missing label in submenu item
+ menu = {"/overview": {"description": "Overview"}}
+ with pytest.raises(ValueError):
+ _build_and_validate_menu(menu)
+
+ # Test with non-string description in submenu item
+ menu = {"/overview": {"label": "Overview", "description": 123}}
+ with pytest.raises(ValueError):
+ _build_and_validate_menu(menu)