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 configurable width to mo.sidebar() (#3570) (#3591)

devin-ai-integration[bot]ca735fc23cbb
diff --git a/frontend/src/components/editor/renderers/vertical-layout/sidebar/__tests__/sidebar.test.tsx b/frontend/src/components/editor/renderers/vertical-layout/sidebar/__tests__/sidebar.test.tsx
new file mode 100644
index 0000000000..24e513d903
--- /dev/null
+++ b/frontend/src/components/editor/renderers/vertical-layout/sidebar/__tests__/sidebar.test.tsx
@@ -0,0 +1,55 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect } from "vitest";
+import { render } from "@testing-library/react";
+import { Sidebar } from "../sidebar";
+import { normalizeWidth } from "../state";
+import { Functions } from "@/utils/functions";
+import { Provider as SlotzProvider } from "@marimo-team/react-slotz";
+
+describe("Sidebar", () => {
+ it("should use default width when no width is provided", () => {
+ const { container } = render(
+ <SlotzProvider>
+ <Sidebar isOpen={false} toggle={Functions.NOOP} />
+ </SlotzProvider>,
+ );
+ const aside = container.querySelector("aside");
+ expect(aside?.style.width).toBe("68px"); // closed width when not open
+ });
+
+ it("should use provided width when width is specified", () => {
+ const { container } = render(
+ <SlotzProvider>
+ <Sidebar isOpen={true} toggle={Functions.NOOP} width="400px" />
+ </SlotzProvider>,
+ );
+ const aside = container.querySelector("aside");
+ expect(aside?.style.width).toBe("400px"); // open width when isOpen is true
+ });
+
+ it("should convert numeric width to px", () => {
+ const { container } = render(
+ <SlotzProvider>
+ <Sidebar isOpen={true} toggle={Functions.NOOP} width={400} />
+ </SlotzProvider>,
+ );
+ const aside = container.querySelector("aside");
+ expect(aside?.style.width).toBe("400px"); // open width when isOpen is true
+ });
+});
+
+describe("normalizeWidth", () => {
+ it("should return default width when no width is provided", () => {
+ expect(normalizeWidth(undefined)).toBe("288px");
+ });
+
+ it("should add px to numeric values", () => {
+ expect(normalizeWidth("400")).toBe("400px");
+ });
+
+ it("should not modify values with units", () => {
+ expect(normalizeWidth("20rem")).toBe("20rem");
+ expect(normalizeWidth("50%")).toBe("50%");
+ expect(normalizeWidth("100vh")).toBe("100vh");
+ });
+});
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
index 5d6bbd8d66..c5af25044f 100644
--- a/frontend/src/components/editor/renderers/vertical-layout/sidebar/sheet-sidebar.tsx
+++ b/frontend/src/components/editor/renderers/vertical-layout/sidebar/sheet-sidebar.tsx
@@ -5,7 +5,14 @@ import { Button } from "@/components/ui/button";
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
import { SidebarSlot } from "./sidebar-slot";
-export const SheetMenu = () => {
+interface SheetMenuProps {
+ /**
+ * The maximum width of the sidebar when it is open.
+ */
+ openWidth: string;
+}
+
+export const SheetMenu = ({ openWidth }: SheetMenuProps) => {
return (
<Sheet>
<SheetTrigger className="lg:hidden" asChild={true}>
@@ -14,7 +21,8 @@ export const SheetMenu = () => {
</Button>
</SheetTrigger>
<SheetContent
- className="w-full max-w-72 px-3 h-full flex flex-col"
+ className="w-full px-3 h-full flex flex-col overflow-y-auto"
+ style={{ maxWidth: openWidth }}
side="left"
>
<SidebarSlot />
diff --git a/frontend/src/components/editor/renderers/vertical-layout/sidebar/sidebar.tsx b/frontend/src/components/editor/renderers/vertical-layout/sidebar/sidebar.tsx
index 5c6836df6b..5dbced7304 100644
--- a/frontend/src/components/editor/renderers/vertical-layout/sidebar/sidebar.tsx
+++ b/frontend/src/components/editor/renderers/vertical-layout/sidebar/sidebar.tsx
@@ -2,22 +2,23 @@
import { cn } from "@/utils/cn";
import { SidebarToggle } from "./toggle";
import { SidebarSlot } from "./sidebar-slot";
+import { CLOSED_WIDTH } from "./state";
import "./sidebar.css";
interface SidebarProps {
isOpen: boolean;
toggle: () => void;
+ width?: string | number;
}
-export const Sidebar = ({ isOpen, toggle }: SidebarProps) => {
+export const Sidebar = ({ isOpen, toggle, width }: SidebarProps) => {
return (
<aside
data-expanded={isOpen}
+ style={{ width: isOpen ? width : CLOSED_WIDTH }}
className={cn(
"app-sidebar auto-collapse-nav",
- "absolute top-0 left-0 z-20 h-full -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]",
+ "top-0 left-0 z-20 h-full hidden lg:block relative transition-[width] ease-in-out duration-300",
)}
>
<SidebarToggle isOpen={isOpen} toggle={toggle} />
diff --git a/frontend/src/components/editor/renderers/vertical-layout/sidebar/state.ts b/frontend/src/components/editor/renderers/vertical-layout/sidebar/state.ts
index 7f1ece6fec..dfbb91e86b 100644
--- a/frontend/src/components/editor/renderers/vertical-layout/sidebar/state.ts
+++ b/frontend/src/components/editor/renderers/vertical-layout/sidebar/state.ts
@@ -3,13 +3,30 @@ import { atomWithReducer } from "jotai/utils";
interface SidebarState {
isOpen: boolean;
+ width?: string;
}
interface SidebarAction {
- type: "toggle";
- isOpen: boolean;
+ type: "toggle" | "setWidth";
+ isOpen?: boolean;
+ width?: string;
}
+export const CLOSED_WIDTH = "68px";
+const DEFAULT_OPEN_WIDTH = "288px";
+
+// Convert numeric values to px units
+export const normalizeWidth = (width: string | undefined): string => {
+ if (!width) {
+ return DEFAULT_OPEN_WIDTH;
+ }
+ // If it's just a number, assume px
+ if (/^\d+$/.test(width)) {
+ return `${width}px`;
+ }
+ return width;
+};
+
export const sidebarAtom = atomWithReducer<SidebarState, SidebarAction>(
{ isOpen: true },
(prev, action) => {
@@ -19,7 +36,9 @@ export const sidebarAtom = atomWithReducer<SidebarState, SidebarAction>(
switch (action.type) {
case "toggle":
- return { ...prev, isOpen: action.isOpen };
+ return { ...prev, isOpen: action.isOpen ?? prev.isOpen };
+ case "setWidth":
+ return { ...prev, width: action.width };
default:
return prev;
}
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
index 51b6cbd8a6..c4281f91cd 100644
--- 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
@@ -1,9 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { cn } from "@/utils/cn";
+
import type React from "react";
import { SheetMenu } from "./sheet-sidebar";
import { useAtom } from "jotai";
-import { sidebarAtom } from "./state";
+import { normalizeWidth, sidebarAtom } from "./state";
import { Sidebar } from "./sidebar";
import { useSlot } from "@marimo-team/react-slotz";
import { SlotNames } from "@/core/slots/slots";
@@ -13,31 +13,26 @@ interface Props {
}
export const WrappedWithSidebar: React.FC<Props> = ({ children }) => {
- const [{ isOpen }, dispatch] = useAtom(sidebarAtom);
+ const [{ isOpen, width }, dispatch] = useAtom(sidebarAtom);
const elements = useSlot(SlotNames.SIDEBAR);
if (elements.length === 0) {
return children;
}
+ const openWidth = normalizeWidth(width);
+
return (
- <>
+ <div className="inset-0 absolute flex">
<Sidebar
isOpen={isOpen}
+ width={openWidth}
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>
- </>
+ <div className="absolute top-3 left-4 flex items-center z-50">
+ <SheetMenu openWidth={openWidth} />
+ </div>
+ {children}
+ </div>
);
};
diff --git a/frontend/src/plugins/core/sidebar-element.tsx b/frontend/src/plugins/core/sidebar-element.tsx
index 1f9b79fbaf..85e5832197 100644
--- a/frontend/src/plugins/core/sidebar-element.tsx
+++ b/frontend/src/plugins/core/sidebar-element.tsx
@@ -3,6 +3,9 @@ import { defineCustomElement } from "@/core/dom/defineCustomElement";
import { renderHTML } from "./RenderHTML";
import { SlotNames, slotsController } from "@/core/slots/slots";
import { init } from "@paralleldrive/cuid2";
+import { store } from "@/core/state/jotai";
+import { sidebarAtom } from "@/components/editor/renderers/vertical-layout/sidebar/state";
+import { Logger } from "@/utils/Logger";
const createId = init({ length: 6 });
@@ -43,6 +46,7 @@ export function initializeSidebarElement(): void {
}
private mountReactComponent() {
+ this.syncWidth();
slotsController.mount({
name: SlotNames.SIDEBAR,
ref: this.uniqueId,
@@ -58,6 +62,7 @@ export function initializeSidebarElement(): void {
}
private updateReactComponent() {
+ this.syncWidth();
slotsController.update({
name: SlotNames.SIDEBAR,
ref: this.uniqueId,
@@ -65,6 +70,27 @@ export function initializeSidebarElement(): void {
});
}
+ // Grab the data-width attribute from the element and set the width in the store
+ // This is used to set the width of the sidebar when it is opened
+ private syncWidth(): void {
+ try {
+ const width = this.dataset.width;
+ if (width) {
+ store.set(sidebarAtom, {
+ type: "setWidth",
+ width: JSON.parse(width) as string,
+ });
+ } else {
+ store.set(sidebarAtom, {
+ type: "setWidth",
+ width: undefined,
+ });
+ }
+ } catch (error) {
+ Logger.error(error);
+ }
+ }
+
/**
* Get the children of the element as React nodes.
*/
diff --git a/marimo/_plugins/stateless/sidebar.py b/marimo/_plugins/stateless/sidebar.py
index a944b5c4c8..3c1b1be6b7 100644
--- a/marimo/_plugins/stateless/sidebar.py
+++ b/marimo/_plugins/stateless/sidebar.py
@@ -48,12 +48,20 @@ class sidebar(Html):
Args:
item (object): The content to display in the sidebar.
footer (object, optional): The content to display at the bottom of the sidebar.
+ width (str, optional): The width of the sidebar when open. Can be any valid CSS width
+ value (e.g. "300px", "20rem"). If not provided, defaults to the standard width.
Returns:
Html (marimo.Html): An Html object.
"""
- def __init__(self, item: object, footer: Optional[object] = None) -> None:
+ def __init__(
+ self,
+ item: object,
+ footer: Optional[object] = None,
+ *,
+ width: Optional[str | int] = None,
+ ) -> None:
# If its a string, wrap in md
if isinstance(item, str):
item = md.md(item)
@@ -69,10 +77,16 @@ class sidebar(Html):
footer = vstack(footer)
item = vstack([item, footer], justify="space-between")
+ # Build props
+ props: dict[str, Any] = {}
+ if width is not None:
+ # Width must be a string for JSON serialization
+ props["width"] = str(width)
+
super().__init__(
build_stateless_plugin(
"marimo-sidebar",
- {},
+ props,
as_html(item).text,
)
)
diff --git a/marimo/_smoke_tests/sidebar.py b/marimo/_smoke_tests/sidebar.py
index 8eaddf577d..9d9f3ec093 100644
--- a/marimo/_smoke_tests/sidebar.py
+++ b/marimo/_smoke_tests/sidebar.py
@@ -2,12 +2,12 @@
import marimo
-__generated_with = "0.5.2"
-app = marimo.App()
+__generated_with = "0.10.17"
+app = marimo.App(width="full")
@app.cell
-def __(mo):
+def _(mo):
mo.sidebar(
[
mo.md("# marimo"),
@@ -35,12 +35,13 @@ def __(mo):
"""
)
],
+ width="500px",
)
return
@app.cell
-def __(mo):
+def _(mo):
[
mo.ui.button(
label=f"{mo.icon('lucide:home')} Home",
@@ -53,13 +54,13 @@ def __(mo):
@app.cell
-def __():
+def _():
import marimo as mo
- return mo,
+ return (mo,)
@app.cell
-def __(mo):
+def _(mo):
mo.nav_menu(
{
"#home": f"{mo.icon('lucide:home')} Home",
@@ -72,7 +73,7 @@ def __(mo):
@app.cell
-def __(mo):
+def _(mo):
mo.nav_menu(
{
"#home": f"{mo.icon('lucide:home')} Home",
diff --git a/tests/_plugins/stateless/test_sidebar.py b/tests/_plugins/stateless/test_sidebar.py
new file mode 100644
index 0000000000..055e57fd26
--- /dev/null
+++ b/tests/_plugins/stateless/test_sidebar.py
@@ -0,0 +1,58 @@
+from __future__ import annotations
+
+import pytest
+
+from marimo._output.hypertext import Html
+from marimo._plugins.stateless.sidebar import sidebar
+
+
+def test_sidebar_string():
+ """Test sidebar with string input."""
+ result = sidebar("test content")
+ assert isinstance(result, Html)
+ assert "width" not in result._text
+
+
+def test_sidebar_list():
+ """Test sidebar with list input."""
+ result = sidebar(["item1", "item2"])
+ assert isinstance(result, Html)
+ assert "width" not in result._text
+
+
+def test_sidebar_with_footer():
+ """Test sidebar with footer."""
+ result = sidebar("content", footer="footer text")
+ assert isinstance(result, Html)
+ assert "width" not in result._text
+
+
+def test_sidebar_list_both_width_and_footer():
+ """Test sidebar with both width and footer."""
+ result = sidebar(["item1", "item2"], footer=["footer1", "footer2"])
+ assert isinstance(result, Html)
+ assert "width" not in result._text
+
+
+def test_sidebar_with_width():
+ """Test sidebar with custom width."""
+ result = sidebar("content", width="300px")
+ assert isinstance(result, Html)
+ assert "data-width='&quot;300px&quot;'" in result._text
+
+
+def test_sidebar_unsupported_methods():
+ """Test that unsupported methods raise TypeError."""
+ s = sidebar("content")
+ with pytest.raises(TypeError):
+ s.batch()
+ with pytest.raises(TypeError):
+ s.center()
+ with pytest.raises(TypeError):
+ s.right()
+ with pytest.raises(TypeError):
+ s.left()
+ with pytest.raises(TypeError):
+ s.callout()
+ with pytest.raises(TypeError):
+ s.style()