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.sidebar (#1352)

Myles Scolnickbb88bd474dab
diff --git a/docs/api/layouts/index.md b/docs/api/layouts/index.md
index 16f5a7d5e0..3d6a988fd5 100644
--- a/docs/api/layouts/index.md
+++ b/docs/api/layouts/index.md
@@ -11,6 +11,7 @@
justify
lazy
nav_menu
+ sidebar
stacks
tree
```
@@ -36,6 +37,7 @@ them but just render their children in a certain way.
marimo.left
marimo.nav_menu
marimo.right
+ marimo.sidebar
marimo.tree
marimo.vstack
```
diff --git a/docs/api/layouts/sidebar.md b/docs/api/layouts/sidebar.md
new file mode 100644
index 0000000000..c41f6582a1
--- /dev/null
+++ b/docs/api/layouts/sidebar.md
@@ -0,0 +1,31 @@
+# Sidebar
+
+```{eval-rst}
+.. marimo-embed::
+ :size: medium
+
+ @app.cell
+ def __():
+ mo.sidebar(
+ [
+ mo.md("# marimo"),
+ mo.nav_menu(
+ {
+ "#home": f"{mo.icon('lucide:home')} Home",
+ "#about": f"{mo.icon('lucide:user')} About",
+ "#contact": f"{mo.icon('lucide:phone')} Contact",
+ "Links": {
+ "https://twitter.com/marimo_io": "Twitter",
+ "https://github.com/marimo-team/marimo": "GitHub",
+ },
+ },
+ orientation="vertical",
+ ),
+ ]
+ )
+ return
+```
+
+```{eval-rst}
+.. autofunction:: marimo.sidebar
+```
diff --git a/docs/guides/outputs.md b/docs/guides/outputs.md
index f9930df2f9..f62f1e7f4f 100644
--- a/docs/guides/outputs.md
+++ b/docs/guides/outputs.md
@@ -65,7 +65,7 @@ mo.md(
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.accordion`](#marimo.accordion), [`mo.ui.tabs`](#marimo.ui.tabs), [`mo.sidebar`](#marimo.sidebar),
[`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/docs/guides/overview.md b/docs/guides/overview.md
index a1ba36e0be..cc461c95d5 100644
--- a/docs/guides/overview.md
+++ b/docs/guides/overview.md
@@ -155,6 +155,6 @@ collections of elements.
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.accordion`](#marimo.accordion), [`mo.ui.tabs`](#marimo.ui.tabs), [`mo.sidebar`](#marimo.sidebar),
[`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/e2e-tests/cells.spec.ts b/frontend/e2e-tests/cells.spec.ts
index c76e1e3837..d6ef5728de 100644
--- a/frontend/e2e-tests/cells.spec.ts
+++ b/frontend/e2e-tests/cells.spec.ts
@@ -12,8 +12,8 @@ test.beforeEach(async ({ page }, info) => {
await page.goto(appUrl);
if (info.retry) {
await page.reload();
+ await maybeRestartKernel(page);
}
- await maybeRestartKernel(page);
});
test.afterEach(async () => {
diff --git a/frontend/e2e-tests/disabled.spec.ts b/frontend/e2e-tests/disabled.spec.ts
index 41f02aa944..f5699e5f4e 100644
--- a/frontend/e2e-tests/disabled.spec.ts
+++ b/frontend/e2e-tests/disabled.spec.ts
@@ -11,8 +11,8 @@ test.beforeEach(async ({ page }, info) => {
await page.goto(appUrl);
if (info.retry) {
await page.reload();
+ await maybeRestartKernel(page);
}
- await maybeRestartKernel(page);
});
test.afterEach(async () => {
diff --git a/frontend/package.json b/frontend/package.json
index e0dfb13c99..339e082254 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -35,6 +35,7 @@
"@lezer/common": "^1.2.1",
"@lezer/highlight": "^1.2.0",
"@lezer/lr": "^1.4.0",
+ "@marimo-team/react-slotz": "^0.1.8",
"@open-rpc/client-js": "^1.8.1",
"@paralleldrive/cuid2": "^2.2.2",
"@radix-ui/colors": "^3.0.0",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 8d312a1134..bc2fb22e5c 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -71,6 +71,9 @@ dependencies:
'@lezer/lr':
specifier: ^1.4.0
version: 1.4.0
+ '@marimo-team/react-slotz':
+ specifier: ^0.1.8
+ version: 0.1.8([email protected])
'@open-rpc/client-js':
specifier: ^1.8.1
version: 1.8.1
@@ -3189,6 +3192,15 @@ packages:
engines: {node: '>=6.0.0'}
dev: false
+ resolution: {integrity: sha512-Lp3EobxEXKoYBv7jpyv6FwnplYxOQTPAFnAjiAOw4PgwL5DvULLCVpxa5C57AQ06e05Ykz57dUVbBE6iYo5+QA==}
+ peerDependencies:
+ react: ^18
+ dependencies:
+ mitt: 3.0.1
+ react: 18.3.1
+ dev: false
+
resolution: {integrity: sha512-9ZrPIU4MGf6et1m1ov3zKf+q9+deetI51zprKB1D/z3NOb+rUxxtEl3mCjW5wTGh6VhRdwPueh1oRzi6ezkA8A==}
peerDependencies:
@@ -14503,6 +14515,10 @@ packages:
yallist: 4.0.0
dev: true
+ resolution: {integrity: sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==}
+ dev: false
+
resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==}
dev: true
diff --git a/frontend/src/components/editor/app-container.tsx b/frontend/src/components/editor/app-container.tsx
index ccb92fcaff..6d04373f42 100644
--- a/frontend/src/components/editor/app-container.tsx
+++ b/frontend/src/components/editor/app-container.tsx
@@ -5,6 +5,7 @@ import { cn } from "@/utils/cn";
import React, { PropsWithChildren } from "react";
import { StatusOverlay } from "./header/status";
import { AppConfig } from "@/core/config/config-schema";
+import { WrappedWithSidebar } from "./renderers/vertical-layout/sidebar/wrapped-with-sidebar";
interface Props {
connectionState: WebSocketState;
@@ -21,17 +22,19 @@ export const AppContainer: React.FC<PropsWithChildren<Props>> = ({
return (
<>
<StatusOverlay state={connectionState} isRunning={isRunning} />
- <div
- id="App"
- className={cn(
- connectionState === WebSocketState.CLOSED && "disconnected",
- "bg-background w-full h-full text-textColor",
- "flex flex-col overflow-y-auto overflow-x-hidden",
- width === "full" && "config-width-full",
- )}
- >
- {children}
- </div>
+ <WrappedWithSidebar>
+ <div
+ id="App"
+ className={cn(
+ connectionState === WebSocketState.CLOSED && "disconnected",
+ "bg-background w-full h-full text-textColor",
+ "flex flex-col overflow-y-auto overflow-x-hidden",
+ width === "full" && "config-width-full",
+ )}
+ >
+ {children}
+ </div>
+ </WrappedWithSidebar>
</>
);
};
diff --git a/frontend/src/components/editor/controls/Controls.tsx b/frontend/src/components/editor/controls/Controls.tsx
index 1b524d8a9d..c22c09cd5f 100644
--- a/frontend/src/components/editor/controls/Controls.tsx
+++ b/frontend/src/components/editor/controls/Controls.tsx
@@ -221,4 +221,4 @@ const bottomRightControls =
"absolute bottom-5 right-5 flex items-center space-x-3 no-print pointer-events-auto z-30";
const bottomLeftControls =
- "absolute bottom-5 left-4 m-0 flex flex-col-reverse gap-2 items-center no-print pointer-events-auto z-30";
+ "absolute bottom-5 left-3 m-0 flex flex-col-reverse gap-2 items-center no-print pointer-events-auto z-30";
diff --git a/frontend/src/components/editor/renderers/vertical-layout/sidebar/sheet-sidebar.tsx b/frontend/src/components/editor/renderers/vertical-layout/sidebar/sheet-sidebar.tsx
new file mode 100644
index 0000000000..5d6bbd8d66
--- /dev/null
+++ b/frontend/src/components/editor/renderers/vertical-layout/sidebar/sheet-sidebar.tsx
@@ -0,0 +1,24 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { MenuIcon } from "lucide-react";
+
+import { Button } from "@/components/ui/button";
+import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
+import { SidebarSlot } from "./sidebar-slot";
+
+export const SheetMenu = () => {
+ return (
+ <Sheet>
+ <SheetTrigger className="lg:hidden" asChild={true}>
+ <Button variant="ghost" className="bg-background">
+ <MenuIcon className="w-5 h-5" />
+ </Button>
+ </SheetTrigger>
+ <SheetContent
+ className="w-full max-w-72 px-3 h-full flex flex-col"
+ side="left"
+ >
+ <SidebarSlot />
+ </SheetContent>
+ </Sheet>
+ );
+};
diff --git a/frontend/src/components/editor/renderers/vertical-layout/sidebar/sidebar-slot.tsx b/frontend/src/components/editor/renderers/vertical-layout/sidebar/sidebar-slot.tsx
new file mode 100644
index 0000000000..44ad3b7458
--- /dev/null
+++ b/frontend/src/components/editor/renderers/vertical-layout/sidebar/sidebar-slot.tsx
@@ -0,0 +1,9 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React, { memo } from "react";
+import { Slot } from "@marimo-team/react-slotz";
+import { SlotNames } from "@/core/slots/slots";
+
+export const SidebarSlot: React.FC = memo(() => {
+ return <Slot name={SlotNames.SIDEBAR} />;
+});
+SidebarSlot.displayName = "SidebarSlot";
diff --git a/frontend/src/components/editor/renderers/vertical-layout/sidebar/sidebar.css b/frontend/src/components/editor/renderers/vertical-layout/sidebar/sidebar.css
new file mode 100644
index 0000000000..aaac119ace
--- /dev/null
+++ b/frontend/src/components/editor/renderers/vertical-layout/sidebar/sidebar.css
@@ -0,0 +1,18 @@
+/* Improve markdown when in the sidebar */
+.app-sidebar .markdown {
+ display: block;
+ @apply px-5;
+}
+
+/* Add a container media query */
+.app-sidebar {
+ container-type: inline-size;
+ container-name: app-sidebar;
+}
+
+/* When not expanded, hide all markdown */
+@container app-sidebar (max-width: 230px) {
+ .app-sidebar[data-expanded="false"] .markdown {
+ display: none;
+ }
+}
diff --git a/frontend/src/components/editor/renderers/vertical-layout/sidebar/sidebar.tsx b/frontend/src/components/editor/renderers/vertical-layout/sidebar/sidebar.tsx
new file mode 100644
index 0000000000..703b7e7acc
--- /dev/null
+++ b/frontend/src/components/editor/renderers/vertical-layout/sidebar/sidebar.tsx
@@ -0,0 +1,29 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { cn } from "@/utils/cn";
+import { SidebarToggle } from "./toggle";
+import { SidebarSlot } from "./sidebar-slot";
+import "./sidebar.css";
+
+interface SidebarProps {
+ isOpen: boolean;
+ toggle: () => void;
+}
+
+export const Sidebar = ({ isOpen, toggle }: SidebarProps) => {
+ return (
+ <aside
+ data-expanded={isOpen}
+ className={cn(
+ "app-sidebar auto-collapse-nav",
+ "absolute top-0 left-0 z-20 h-screen -translate-x-full lg:translate-x-0 transition-[width] ease-in-out duration-300",
+ // These values need to match wrapped-with-sidebar.tsx
+ isOpen ? "w-72" : "w-[68px]",
+ )}
+ >
+ <SidebarToggle isOpen={isOpen} toggle={toggle} />
+ <div className="relative h-full flex flex-col px-3 pb-4 pt-14 overflow-y-auto shadow-sm border-l">
+ <SidebarSlot />
+ </div>
+ </aside>
+ );
+};
diff --git a/frontend/src/components/editor/renderers/vertical-layout/sidebar/state.ts b/frontend/src/components/editor/renderers/vertical-layout/sidebar/state.ts
new file mode 100644
index 0000000000..7f1ece6fec
--- /dev/null
+++ b/frontend/src/components/editor/renderers/vertical-layout/sidebar/state.ts
@@ -0,0 +1,27 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { atomWithReducer } from "jotai/utils";
+
+interface SidebarState {
+ isOpen: boolean;
+}
+
+interface SidebarAction {
+ type: "toggle";
+ isOpen: boolean;
+}
+
+export const sidebarAtom = atomWithReducer<SidebarState, SidebarAction>(
+ { isOpen: true },
+ (prev, action) => {
+ if (!action) {
+ return prev;
+ }
+
+ switch (action.type) {
+ case "toggle":
+ return { ...prev, isOpen: action.isOpen };
+ default:
+ return prev;
+ }
+ },
+);
diff --git a/frontend/src/components/editor/renderers/vertical-layout/sidebar/toggle.tsx b/frontend/src/components/editor/renderers/vertical-layout/sidebar/toggle.tsx
new file mode 100644
index 0000000000..66ad911bbb
--- /dev/null
+++ b/frontend/src/components/editor/renderers/vertical-layout/sidebar/toggle.tsx
@@ -0,0 +1,25 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { ChevronLeft } from "lucide-react";
+
+import { Button } from "@/components/ui/button";
+import { cn } from "@/utils/cn";
+
+interface SidebarToggleProps {
+ isOpen: boolean;
+ toggle: () => void;
+}
+
+export const SidebarToggle = ({ isOpen, toggle }: SidebarToggleProps) => {
+ return (
+ <div className="invisible lg:visible absolute top-[12px] right-[16px] z-20">
+ <Button onClick={toggle} className="w-10 h-8" variant="ghost" size="icon">
+ <ChevronLeft
+ className={cn(
+ "h-5 w-5 transition-transform ease-in-out duration-700",
+ isOpen ? "rotate-0" : "rotate-180",
+ )}
+ />
+ </Button>
+ </div>
+ );
+};
diff --git a/frontend/src/components/editor/renderers/vertical-layout/sidebar/wrapped-with-sidebar.tsx b/frontend/src/components/editor/renderers/vertical-layout/sidebar/wrapped-with-sidebar.tsx
new file mode 100644
index 0000000000..286645c6ce
--- /dev/null
+++ b/frontend/src/components/editor/renderers/vertical-layout/sidebar/wrapped-with-sidebar.tsx
@@ -0,0 +1,43 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { cn } from "@/utils/cn";
+import React from "react";
+import { SheetMenu } from "./sheet-sidebar";
+import { useAtom } from "jotai";
+import { sidebarAtom } from "./state";
+import { Sidebar } from "./sidebar";
+import { useSlot } from "@marimo-team/react-slotz";
+import { SlotNames } from "@/core/slots/slots";
+
+interface Props {
+ children: React.ReactNode;
+}
+
+export const WrappedWithSidebar: React.FC<Props> = ({ children }) => {
+ const [{ isOpen }, dispatch] = useAtom(sidebarAtom);
+ const elements = useSlot(SlotNames.SIDEBAR);
+
+ if (elements.length === 0) {
+ return children;
+ }
+
+ return (
+ <>
+ <Sidebar
+ isOpen={isOpen}
+ toggle={() => dispatch({ type: "toggle", isOpen: !isOpen })}
+ />
+ <main
+ className={cn(
+ "h-full transition-[margin-left] ease-in-out duration-300 overflow-hidden relative",
+ // These values need to match sidebar.tsx
+ isOpen ? "lg:ml-72" : "lg:ml-[68px]",
+ )}
+ >
+ <div className="absolute top-3 left-4 flex items-center z-50">
+ <SheetMenu />
+ </div>
+ {children}
+ </main>
+ </>
+ );
+};
diff --git a/frontend/src/components/ui/navigation.tsx b/frontend/src/components/ui/navigation.tsx
index 80a2a120ce..1b9089a1a1 100644
--- a/frontend/src/components/ui/navigation.tsx
+++ b/frontend/src/components/ui/navigation.tsx
@@ -8,13 +8,17 @@ import { cn } from "@/utils/cn";
const NavigationMenu = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Root>
->(({ className, children, ...props }, ref) => (
+>(({ className, children, orientation, ...props }, ref) => (
<NavigationMenuPrimitive.Root
ref={ref}
className={cn(
- "relative z-10 flex max-w-max flex-1 items-center justify-center",
+ orientation === "horizontal" &&
+ "max-w-max flex-1 items-center justify-center",
+ orientation === "vertical" && "",
+ "relative z-10",
className,
)}
+ orientation={orientation}
{...props}
>
{children}
@@ -51,7 +55,18 @@ 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",
+ "group inline-flex rounded-md bg-background px-4 py-2 text-lg font-medium text-[var(--slate-12)] 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",
+ {
+ variants: {
+ orientation: {
+ horizontal: "w-max items-center justify-center",
+ vertical: "w-full",
+ },
+ },
+ defaultVariants: {
+ orientation: "horizontal",
+ },
+ },
);
const NavigationMenuTrigger = React.forwardRef<
diff --git a/frontend/src/components/ui/sheet.tsx b/frontend/src/components/ui/sheet.tsx
new file mode 100644
index 0000000000..17b930e53a
--- /dev/null
+++ b/frontend/src/components/ui/sheet.tsx
@@ -0,0 +1,138 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React from "react";
+import * as SheetPrimitive from "@radix-ui/react-dialog";
+import { Cross2Icon } from "@radix-ui/react-icons";
+import { cva, type VariantProps } from "class-variance-authority";
+import { cn } from "@/utils/cn";
+
+const Sheet = SheetPrimitive.Root;
+
+const SheetTrigger = SheetPrimitive.Trigger;
+
+const SheetClose = SheetPrimitive.Close;
+
+const SheetPortal = SheetPrimitive.Portal;
+
+const SheetOverlay = React.forwardRef<
+ React.ElementRef<typeof SheetPrimitive.Overlay>,
+ React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
+>(({ className, ...props }, ref) => (
+ <SheetPrimitive.Overlay
+ className={cn(
+ "fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
+ className,
+ )}
+ {...props}
+ ref={ref}
+ />
+));
+SheetOverlay.displayName = SheetPrimitive.Overlay.displayName;
+
+const sheetVariants = cva(
+ "fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
+ {
+ variants: {
+ side: {
+ top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
+ bottom:
+ "inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
+ left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
+ right:
+ "inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
+ },
+ },
+ defaultVariants: {
+ side: "right",
+ },
+ },
+);
+
+interface SheetContentProps
+ extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
+ VariantProps<typeof sheetVariants> {}
+
+const SheetContent = React.forwardRef<
+ React.ElementRef<typeof SheetPrimitive.Content>,
+ SheetContentProps
+>(({ side = "right", className, children, ...props }, ref) => (
+ <SheetPortal>
+ <SheetOverlay />
+ <SheetPrimitive.Content
+ ref={ref}
+ className={cn(sheetVariants({ side }), className)}
+ {...props}
+ >
+ {children}
+ <SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
+ <Cross2Icon className="h-4 w-4" />
+ <span className="sr-only">Close</span>
+ </SheetPrimitive.Close>
+ </SheetPrimitive.Content>
+ </SheetPortal>
+));
+SheetContent.displayName = SheetPrimitive.Content.displayName;
+
+const SheetHeader = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn(
+ "flex flex-col space-y-2 text-center sm:text-left",
+ className,
+ )}
+ {...props}
+ />
+);
+SheetHeader.displayName = "SheetHeader";
+
+const SheetFooter = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn(
+ "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
+ className,
+ )}
+ {...props}
+ />
+);
+SheetFooter.displayName = "SheetFooter";
+
+const SheetTitle = React.forwardRef<
+ React.ElementRef<typeof SheetPrimitive.Title>,
+ React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
+>(({ className, ...props }, ref) => (
+ <SheetPrimitive.Title
+ ref={ref}
+ className={cn("text-lg font-semibold text-foreground", className)}
+ {...props}
+ />
+));
+SheetTitle.displayName = SheetPrimitive.Title.displayName;
+
+const SheetDescription = React.forwardRef<
+ React.ElementRef<typeof SheetPrimitive.Description>,
+ React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
+>(({ className, ...props }, ref) => (
+ <SheetPrimitive.Description
+ ref={ref}
+ className={cn("text-sm text-muted-foreground", className)}
+ {...props}
+ />
+));
+SheetDescription.displayName = SheetPrimitive.Description.displayName;
+
+export {
+ Sheet,
+ SheetPortal,
+ SheetOverlay,
+ SheetTrigger,
+ SheetClose,
+ SheetContent,
+ SheetHeader,
+ SheetFooter,
+ SheetTitle,
+ SheetDescription,
+};
diff --git a/frontend/src/core/MarimoApp.tsx b/frontend/src/core/MarimoApp.tsx
index 8da4dd885f..faead16d64 100644
--- a/frontend/src/core/MarimoApp.tsx
+++ b/frontend/src/core/MarimoApp.tsx
@@ -17,6 +17,8 @@ import { isPyodide } from "./pyodide/utils";
import { PyodideBridge } from "./pyodide/bridge";
import { LargeSpinner } from "@/components/icons/large-spinner";
import { TailwindIndicator } from "@/components/debug/indicator";
+import { Provider as SlotzProvider } from "@marimo-team/react-slotz";
+import { slotsController } from "./slots/slots";
// Lazy imports
const LazyHomePage = React.lazy(() => import("@/components/pages/home-page"));
@@ -63,11 +65,13 @@ const Providers = memo(({ children }: PropsWithChildren) => {
<TooltipProvider>
<DayPickerProvider initialProps={{}}>
<PyodideLoader>
- <ModalProvider>
- {children}
- <Toaster />
- <TailwindIndicator />
- </ModalProvider>
+ <SlotzProvider controller={slotsController}>
+ <ModalProvider>
+ {children}
+ <Toaster />
+ <TailwindIndicator />
+ </ModalProvider>
+ </SlotzProvider>
</PyodideLoader>
</DayPickerProvider>
</TooltipProvider>
diff --git a/frontend/src/core/dom/UIElement.ts b/frontend/src/core/dom/ui-element.ts
similarity index 100%
rename from frontend/src/core/dom/UIElement.ts
rename to frontend/src/core/dom/ui-element.ts
diff --git a/frontend/src/core/slots/slots.ts b/frontend/src/core/slots/slots.ts
new file mode 100644
index 0000000000..32a1543289
--- /dev/null
+++ b/frontend/src/core/slots/slots.ts
@@ -0,0 +1,8 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { SlotzController } from "@marimo-team/react-slotz";
+
+export const slotsController = new SlotzController();
+
+export const SlotNames = {
+ SIDEBAR: "sidebar",
+};
diff --git a/frontend/src/css/md.css b/frontend/src/css/md.css
index 9f24a97d20..80ea5934bd 100644
--- a/frontend/src/css/md.css
+++ b/frontend/src/css/md.css
@@ -152,3 +152,24 @@
padding: 0;
margin: 0;
}
+
+/* stylelint-disable unit-allowed-list */
+
+/* pad iconify-icon when next to text */
+a .markdown .paragraph:has(iconify-icon),
+button .markdown .paragraph:has(iconify-icon) {
+ gap: 0.4em;
+}
+
+/* pad iconify-icon when in navigation items */
+a .markdown iconify-icon:first-child {
+ margin-inline-end: 0.4em;
+}
+
+/* align icons with buttons better */
+button .markdown .paragraph {
+ display: inline-flex;
+ align-items: center;
+}
+
+/* stylelint-enable unit-allowed-list */
diff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsx
index 9047110725..9bfc08c525 100644
--- a/frontend/src/plugins/core/registerReactComponent.tsx
+++ b/frontend/src/plugins/core/registerReactComponent.tsx
@@ -38,7 +38,7 @@ import { invariant } from "../../utils/invariant";
import { Logger } from "../../utils/Logger";
import { useTheme } from "@/theme/useTheme";
import { FUNCTIONS_REGISTRY } from "@/core/functions/FunctionRegistry";
-import { getUIElementObjectId } from "@/core/dom/UIElement";
+import { getUIElementObjectId } from "@/core/dom/ui-element";
import { PluginFunctions } from "./rpc";
import { ZodSchema } from "zod";
import useEvent from "react-use-event-hook";
diff --git a/frontend/src/plugins/core/sidebar-element.tsx b/frontend/src/plugins/core/sidebar-element.tsx
new file mode 100644
index 0000000000..1f9b79fbaf
--- /dev/null
+++ b/frontend/src/plugins/core/sidebar-element.tsx
@@ -0,0 +1,77 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { defineCustomElement } from "@/core/dom/defineCustomElement";
+import { renderHTML } from "./RenderHTML";
+import { SlotNames, slotsController } from "@/core/slots/slots";
+import { init } from "@paralleldrive/cuid2";
+
+const createId = init({ length: 6 });
+
+/**
+ * This is a custom DOM element that will be used to portal
+ * it's children to a React component sidebar.
+ */
+export function initializeSidebarElement(): void {
+ const SidebarComponent = class extends HTMLElement {
+ private observer?: MutationObserver;
+ private uniqueId = Symbol(createId());
+
+ connectedCallback() {
+ // Render the component for the first time
+ this.mountReactComponent();
+
+ // This observer is used to detect changes to the children and re-render the component
+ this.observer = new MutationObserver(() => {
+ this.updateReactComponent();
+ });
+
+ this.style.display = "none";
+
+ // Listen for DOM changes
+ this.observer.observe(this, {
+ attributes: true,
+ childList: true,
+ subtree: true,
+ characterData: true,
+ });
+ }
+
+ disconnectedCallback() {
+ if (this.observer) {
+ this.observer.disconnect();
+ this.unmountReactComponent();
+ }
+ }
+
+ private mountReactComponent() {
+ slotsController.mount({
+ name: SlotNames.SIDEBAR,
+ ref: this.uniqueId,
+ children: this.getContents(),
+ });
+ }
+
+ private unmountReactComponent() {
+ slotsController.unmount({
+ name: SlotNames.SIDEBAR,
+ ref: this.uniqueId,
+ });
+ }
+
+ private updateReactComponent() {
+ slotsController.update({
+ name: SlotNames.SIDEBAR,
+ ref: this.uniqueId,
+ children: this.getContents(),
+ });
+ }
+
+ /**
+ * Get the children of the element as React nodes.
+ */
+ private getContents(): React.ReactNode {
+ return renderHTML({ html: this.innerHTML });
+ }
+ };
+
+ defineCustomElement("marimo-sidebar", SidebarComponent);
+}
diff --git a/frontend/src/plugins/impl/DictPlugin.tsx b/frontend/src/plugins/impl/DictPlugin.tsx
index b13b691a6d..e15fe02d24 100644
--- a/frontend/src/plugins/impl/DictPlugin.tsx
+++ b/frontend/src/plugins/impl/DictPlugin.tsx
@@ -2,7 +2,7 @@
import { useEffect } from "react";
import { z } from "zod";
-import { getUIElementObjectId } from "../../core/dom/UIElement";
+import { getUIElementObjectId } from "../../core/dom/ui-element";
import {
marimoValueInputEvent,
MarimoValueInputEventType,
diff --git a/frontend/src/plugins/impl/FormPlugin.tsx b/frontend/src/plugins/impl/FormPlugin.tsx
index e330c73bf5..30acc4e951 100644
--- a/frontend/src/plugins/impl/FormPlugin.tsx
+++ b/frontend/src/plugins/impl/FormPlugin.tsx
@@ -2,7 +2,7 @@
import { useEffect, useRef, useState } from "react";
import { z } from "zod";
-import { getUIElementObjectId, isUIElement } from "../../core/dom/UIElement";
+import { getUIElementObjectId, isUIElement } from "../../core/dom/ui-element";
import {
marimoValueInputEvent,
MarimoValueInputEventType,
diff --git a/frontend/src/plugins/layout/NavigationMenuPlugin.tsx b/frontend/src/plugins/layout/NavigationMenuPlugin.tsx
index 35e14bb6de..b0af224a90 100644
--- a/frontend/src/plugins/layout/NavigationMenuPlugin.tsx
+++ b/frontend/src/plugins/layout/NavigationMenuPlugin.tsx
@@ -16,6 +16,7 @@ import { cn } from "@/utils/cn";
import React from "react";
import { renderHTML } from "@/plugins/core/RenderHTML";
import { Tooltip, TooltipProvider } from "@/components/ui/tooltip";
+import "./navigation-menu.css";
interface MenuItem {
label: string;
@@ -89,6 +90,13 @@ const NavMenuComponent = ({
);
};
+ const target = (href: string) => {
+ if (href.startsWith("http")) {
+ return "_blank";
+ }
+ return "_self";
+ };
+
const renderMenuItem = (item: MenuItem | MenuItemGroup) => {
if ("items" in item) {
return orientation === "horizontal" ? (
@@ -104,6 +112,7 @@ const NavMenuComponent = ({
key={subItem.label}
label={subItem.label}
href={subItem.href}
+ target={target(subItem.href)}
>
{subItem.description &&
renderHTML({ html: subItem.description })}
@@ -117,19 +126,25 @@ const NavMenuComponent = ({
<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"
+ "inline-flex h-9 w-max items-center justify-center rounded-md px-4 py-2 text-base font-medium text-muted-foreground/80 tracking-wide font-semibold"
}
>
{renderHTML({ html: item.label })}
</div>
- <NavigationMenuList className="ml-4" orientation={orientation}>
+ <NavigationMenuList
+ className="ml-4 auto-collapse-nav"
+ orientation={orientation}
+ >
{item.items.map((subItem) => (
<React.Fragment key={subItem.label}>
{maybeWithTooltip(
<NavigationMenuLink
key={subItem.label}
href={subItem.href}
- className={navigationMenuTriggerStyle()}
+ target={target(subItem.href)}
+ className={navigationMenuTriggerStyle({
+ orientation: orientation,
+ })}
>
{renderHTML({ html: subItem.label })}
</NavigationMenuLink>,
@@ -146,7 +161,10 @@ const NavMenuComponent = ({
<NavigationMenuItem key={item.label}>
<NavigationMenuLink
href={item.href}
- className={navigationMenuTriggerStyle()}
+ target={target(item.href)}
+ className={navigationMenuTriggerStyle({
+ orientation: orientation,
+ })}
>
{renderHTML({ html: item.label })}
</NavigationMenuLink>
@@ -156,7 +174,10 @@ const NavMenuComponent = ({
return (
<NavigationMenu orientation={orientation}>
- <NavigationMenuList orientation={orientation}>
+ <NavigationMenuList
+ className="auto-collapse-nav"
+ orientation={orientation}
+ >
{items.map((item) => renderMenuItem(item))}
</NavigationMenuList>
</NavigationMenu>
@@ -180,7 +201,7 @@ const ListItem = React.forwardRef<
)}
{...props}
>
- <div className="text-sm font-medium leading-none">
+ <div className="text-base font-medium leading-none">
{renderHTML({ html: label })}
</div>
{children && (
diff --git a/frontend/src/plugins/layout/navigation-menu.css b/frontend/src/plugins/layout/navigation-menu.css
new file mode 100644
index 0000000000..6045e311a3
--- /dev/null
+++ b/frontend/src/plugins/layout/navigation-menu.css
@@ -0,0 +1,35 @@
+/* This will hide text and only show icons when the sidebar is collapsed */
+.auto-collapse-nav[data-orientation="vertical"] {
+ container-type: inline-size;
+}
+
+@container (max-width: 200px) {
+ .auto-collapse-nav .paragraph {
+ visibility: hidden;
+ font-size: 0;
+ line-height: 0 !important;
+ }
+
+ .auto-collapse-nav .paragraph iconify-icon {
+ visibility: visible;
+ @apply text-xl;
+ line-height: 1;
+ margin: 0;
+ margin-inline-end: 0 !important;
+ margin-inline-start: 0 !important;
+ }
+
+ .auto-collapse-nav li > * {
+ width: 100%;
+ align-items: center;
+ justify-content: center;
+ }
+
+ .auto-collapse-nav li:not(:has(iconify-icon)) {
+ display: none;
+ }
+
+ .auto-collapse-nav :is(h1, h2, h3, h4, h5, h6) {
+ display: none;
+ }
+}
diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.ts
index 1c0dddd7e4..7a5fa77a66 100644
--- a/frontend/src/plugins/plugins.ts
+++ b/frontend/src/plugins/plugins.ts
@@ -1,6 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
/* eslint-disable @typescript-eslint/no-explicit-any */
-import { initializeUIElement } from "../core/dom/UIElement";
+import { initializeUIElement } from "../core/dom/ui-element";
import { registerReactComponent } from "./core/registerReactComponent";
import { ButtonPlugin } from "./impl/ButtonPlugin";
import { CheckboxPlugin } from "./impl/CheckboxPlugin";
@@ -41,6 +41,7 @@ import { MermaidPlugin } from "./layout/mermaid/MermaidPlugin";
import { AnyWidgetPlugin } from "./impl/anywidget/AnyWidgetPlugin";
import { LazyPlugin } from "./layout/LazyPlugin";
import { NavigationMenuPlugin } from "@/plugins/layout/NavigationMenuPlugin";
+import { initializeSidebarElement } from "./core/sidebar-element";
// List of UI plugins
export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [
@@ -88,8 +89,9 @@ const LAYOUT_PLUGINS: Array<IStatelessPlugin<unknown>> = [
];
export function initializePlugins() {
- // Initialize UIElement
+ // Initialize custom DOM elements
initializeUIElement();
+ initializeSidebarElement();
// Initialize all the plugins.
UI_PLUGINS.forEach(registerReactComponent);
diff --git a/marimo/__init__.py b/marimo/__init__.py
index 9a907352b5..2d46e43937 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -49,6 +49,7 @@ __all__ = [
"refs",
"right",
"running_in_notebook",
+ "sidebar",
"stat",
"state",
"status",
@@ -85,6 +86,7 @@ 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.sidebar import sidebar
from marimo._plugins.stateless.stat import stat
from marimo._plugins.stateless.style import style
from marimo._plugins.stateless.tabs import tabs
diff --git a/marimo/_plugins/stateless/nav_menu.py b/marimo/_plugins/stateless/nav_menu.py
index 6401c67e44..dcf209af66 100644
--- a/marimo/_plugins/stateless/nav_menu.py
+++ b/marimo/_plugins/stateless/nav_menu.py
@@ -98,7 +98,11 @@ 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("#"):
+ if (
+ href.startswith("/")
+ or href.startswith("#")
+ or href.startswith("http")
+ ):
return href
raise ValueError(f"Invalid href: {href}, must start with / or #")
diff --git a/marimo/_plugins/stateless/sidebar.py b/marimo/_plugins/stateless/sidebar.py
new file mode 100644
index 0000000000..71b575d985
--- /dev/null
+++ b/marimo/_plugins/stateless/sidebar.py
@@ -0,0 +1,71 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from marimo._output import md
+from marimo._output.formatting import as_html
+from marimo._output.hypertext import Html
+from marimo._output.rich_help import mddoc
+from marimo._plugins.core.web_component import build_stateless_plugin
+from marimo._plugins.stateless.flex import vstack
+
+
+@mddoc
+def sidebar(
+ item: object,
+) -> Html:
+ """
+ Displays content in a sidebar. This is a special layout component that
+ will display the content in a sidebar layout, rather than below/above
+ the cell.
+
+ This component still needs to be the last expression in the cell,
+ in order to display correctly.
+
+ You may use more than one `mo.sidebar` - they will be displayed in the
+ order they are called.
+
+ **Examples.**
+
+ ```python
+ mo.sidebar(
+ [
+ mo.md("# marimo"),
+ mo.nav_menu(
+ {
+ "#home": f"{mo.icon('lucide:home')} Home",
+ "#about": f"{mo.icon('lucide:user')} About",
+ "#contact": f"{mo.icon('lucide:phone')} Contact",
+ "Links": {
+ "https://twitter.com/marimo_io": "Twitter",
+ "https://github.com/marimo-team/marimo": "GitHub",
+ },
+ },
+ orientation="vertical",
+ ),
+ ]
+ )
+ ```
+
+ **Args.**
+
+ - `item`: the content to display in the sidebar
+
+ **Returns.**
+
+ - An `Html` object.
+ """
+
+ # If its a string, wrap in md
+ if isinstance(item, str):
+ item = md.md(item)
+ # If its an array, wrap in vstack
+ if isinstance(item, list):
+ item = vstack(item)
+
+ return Html(
+ build_stateless_plugin(
+ "marimo-sidebar",
+ {},
+ as_html(item).text,
+ )
+ )
diff --git a/marimo/_server/file_router.py b/marimo/_server/file_router.py
index f75b8230c3..8b91e8d63e 100644
--- a/marimo/_server/file_router.py
+++ b/marimo/_server/file_router.py
@@ -177,6 +177,7 @@ class LazyListOfFilesAppFileRouter(AppFileRouter):
)
LOGGER.debug("Searching directory %s", directory)
+ cwd = os.getcwd()
for root, dirnames, filenames in os.walk(directory, topdown=True):
# Skip directories that are too deep
depth = root[len(directory) :].count(os.sep)
@@ -196,13 +197,17 @@ class LazyListOfFilesAppFileRouter(AppFileRouter):
):
continue
full_path = os.path.join(root, filename)
- relative_path = os.path.relpath(full_path, directory)
+ shortest_path = (
+ os.path.relpath(full_path, cwd)
+ if full_path.startswith(cwd)
+ else full_path
+ )
# Python files must contain "marimo.App", or markdown files
if self._is_marimo_app(full_path):
files.append(
MarimoFile(
name=filename,
- path=relative_path,
+ path=shortest_path,
last_modified=os.path.getmtime(full_path),
)
)
diff --git a/marimo/_smoke_tests/sidebar.py b/marimo/_smoke_tests/sidebar.py
new file mode 100644
index 0000000000..9a47249ac8
--- /dev/null
+++ b/marimo/_smoke_tests/sidebar.py
@@ -0,0 +1,83 @@
+import marimo
+
+__generated_with = "0.5.1"
+app = marimo.App()
+
+
+def __(mo):
+ mo.sidebar(
+ [
+ mo.md("# marimo"),
+ mo.nav_menu(
+ {
+ "#home": f"{mo.icon('lucide:home')} Home",
+ "#about": f"{mo.icon('lucide:user')} About",
+ "#contact": f"{mo.icon('lucide:phone')} Contact",
+ "Links": {
+ "https://twitter.com/marimo_io": "Twitter",
+ "https://github.com/marimo-team/marimo": "GitHub",
+ },
+ },
+ orientation="vertical",
+ ),
+ mo.md(
+ """
+
+ ### Footer
+
+ - [Twitter](https://twitter.com/marimo_io)
+ - [GitHub](https://github.com/marimo-team/marimo)
+ """
+ ),
+ ]
+ )
+ return
+
+
+def __(mo):
+ [
+ mo.ui.button(
+ label=f"{mo.icon('lucide:home')} Home",
+ ),
+ mo.ui.button(
+ label=f"{mo.icon('lucide:home')} Home {mo.icon('lucide:external-link')}",
+ ),
+ ]
+ return
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+def __(mo):
+ mo.nav_menu(
+ {
+ "#home": f"{mo.icon('lucide:home')} Home",
+ "#about": f"{mo.icon('lucide:user')} About",
+ "#contact": f"{mo.icon('lucide:phone')} Contact",
+ },
+ orientation="vertical",
+ )
+ return
+
+
+def __(mo):
+ mo.nav_menu(
+ {
+ "#home": f"{mo.icon('lucide:home')} Home",
+ "#about": f"{mo.icon('lucide:user')} About",
+ "#contact": f"{mo.icon('lucide:phone')} Contact",
+ }
+ )
+ return
+
+
+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
index 61f7dc1587..d8ac2dda71 100644
--- a/tests/_plugins/ui/_impl/test_nav_menu.py
+++ b/tests/_plugins/ui/_impl/test_nav_menu.py
@@ -21,6 +21,11 @@ def test_build_and_validate_menu():
assert isinstance(result, NavMenu)
assert all(isinstance(item, NavMenuItemLink) for item in result.items)
+ # Test with absolute href
+ menu = {"https://marimo.io": "marimo"}
+ result = _build_and_validate_menu(menu)
+ assert isinstance(result, NavMenu)
+
# Test with a nested menu dictionary
menu: dict[str, dict[str, str]] = {
"Overview": {"/overview": "Overview", "/overview/summary": "Summary"},