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: allow accordion items to start expanded (#10824)

Shahmir Varqhaeea52eabaaca
diff --git a/frontend/plugins.openapi.yaml b/frontend/plugins.openapi.yaml
index 09503a8c05..c61c31f218 100644
--- a/frontend/plugins.openapi.yaml
+++ b/frontend/plugins.openapi.yaml
@@ -2700,6 +2700,11 @@ components:
type: string
multiple:
type: boolean
+ expanded:
+ default: []
+ type: array
+ items:
+ type: string
required:
- labels
- multiple
diff --git a/frontend/src/plugins/layout/AccordionPlugin.tsx b/frontend/src/plugins/layout/AccordionPlugin.tsx
index 1fc18dc431..5374d56f7e 100644
--- a/frontend/src/plugins/layout/AccordionPlugin.tsx
+++ b/frontend/src/plugins/layout/AccordionPlugin.tsx
@@ -23,6 +23,7 @@ interface Data {
* Whether to allow multiple tabs to be open.
*/
multiple: boolean;
+ expanded: string[];
}
export class AccordionPlugin implements IStatelessPlugin<Data> {
@@ -31,6 +32,7 @@ export class AccordionPlugin implements IStatelessPlugin<Data> {
validator = z.object({
labels: z.array(z.string()),
multiple: z.boolean(),
+ expanded: z.array(z.string()).default([]),
});
render(props: IStatelessPluginProps<Data>): JSX.Element {
@@ -43,11 +45,14 @@ export class AccordionPlugin implements IStatelessPlugin<Data> {
const AccordionComponent = ({
labels,
multiple,
+ expanded,
children,
}: PropsWithChildren<Data>): JSX.Element => {
- const type = multiple ? "multiple" : "single";
+ const expansionProps = multiple
+ ? { type: "multiple" as const, defaultValue: expanded }
+ : { type: "single" as const, defaultValue: expanded[0], collapsible: true };
return (
- <Accordion type={type} className="text-muted-foreground" collapsible={true}>
+ <Accordion {...expansionProps} className="text-muted-foreground">
{React.Children.map(children, (child, index) => {
return (
<AccordionItem key={index} value={index.toString()}>
diff --git a/frontend/src/plugins/layout/__test__/AccordionPlugin.test.tsx b/frontend/src/plugins/layout/__test__/AccordionPlugin.test.tsx
new file mode 100644
index 0000000000..4d526b27ed
--- /dev/null
+++ b/frontend/src/plugins/layout/__test__/AccordionPlugin.test.tsx
@@ -0,0 +1,66 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { cleanup, fireEvent, render } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { AccordionPlugin } from "../AccordionPlugin";
+
+const plugin = new AccordionPlugin();
+
+function renderAccordion(multiple: boolean, expanded?: string[]) {
+ return plugin.render({
+ host: document.createElement("marimo-accordion"),
+ data: plugin.validator.parse({
+ labels: ["Summary", "Details"],
+ multiple,
+ expanded,
+ }),
+ children: [
+ <p key="summary">Overview</p>,
+ <p key="details">More information</p>,
+ ],
+ });
+}
+
+describe("AccordionPlugin", () => {
+ afterEach(cleanup);
+
+ it.each([
+ { multiple: false, expanded: undefined, expected: ["false", "false"] },
+ { multiple: true, expanded: [], expected: ["false", "false"] },
+ { multiple: false, expanded: ["0"], expected: ["true", "false"] },
+ { multiple: false, expanded: ["1"], expected: ["false", "true"] },
+ { multiple: true, expanded: ["0", "1"], expected: ["true", "true"] },
+ ])(
+ "sets initial expansion: $multiple, $expanded",
+ ({ multiple, expanded, expected }) => {
+ const { getAllByRole } = render(renderAccordion(multiple, expanded));
+ expect(
+ getAllByRole("button").map((button) =>
+ button.getAttribute("aria-expanded"),
+ ),
+ ).toEqual(expected);
+ },
+ );
+
+ it("lets users collapse and switch the initially expanded item", () => {
+ const { getAllByRole, rerender } = render(renderAccordion(false, ["1"]));
+ const [summary, details] = getAllByRole("button");
+ fireEvent.click(details);
+ expect(details.getAttribute("aria-expanded")).toBe("false");
+ rerender(renderAccordion(false, ["1"]));
+ expect(details.getAttribute("aria-expanded")).toBe("false");
+ fireEvent.click(details);
+ fireEvent.click(summary);
+ expect(
+ [summary, details].map((button) => button.getAttribute("aria-expanded")),
+ ).toEqual(["true", "false"]);
+ });
+
+ it("lets users collapse items independently with multiple enabled", () => {
+ const { getAllByRole } = render(renderAccordion(true, ["0", "1"]));
+ const [summary, details] = getAllByRole("button");
+ fireEvent.click(summary);
+ expect(
+ [summary, details].map((button) => button.getAttribute("aria-expanded")),
+ ).toEqual(["false", "true"]);
+ });
+});
diff --git a/marimo/_plugins/stateless/accordion.py b/marimo/_plugins/stateless/accordion.py
index e706943528..0d8d5ff747 100644
--- a/marimo/_plugins/stateless/accordion.py
+++ b/marimo/_plugins/stateless/accordion.py
@@ -1,6 +1,7 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+from collections.abc import Sequence
from typing import TYPE_CHECKING
from marimo._output.formatting import as_html
@@ -25,6 +26,11 @@ class accordion(ContainerHtml):
lazy: a boolean, whether to lazily load the accordion content.
This is a convenience that wraps each accordion in a `mo.lazy`
component.
+ expanded: the items to expand initially. `True` expands the first
+ item, or all items with `multiple=True`. A list of item names
+ expands the corresponding items. More than one distinct name
+ requires `multiple=True`. Names must match the names in `items`.
+ Users can still open and close items.
Example:
```python3
@@ -41,6 +47,25 @@ class accordion(ContainerHtml):
where `expensive_item` is the item to render, or a callable that
returns the item to render.
+
+ Expand all items initially:
+
+ ```python3
+ mo.accordion(
+ {"Summary": "Overview", "Details": "More information"},
+ multiple=True,
+ expanded=True,
+ )
+ ```
+
+ Expand a specific item initially:
+
+ ```python3
+ mo.accordion(
+ {"Summary": "Overview", "Details": "More information"},
+ expanded=["Details"],
+ )
+ ```
"""
def __init__(
@@ -48,10 +73,32 @@ class accordion(ContainerHtml):
items: Mapping[str, object],
multiple: bool = False,
lazy: bool = False,
+ *,
+ expanded: bool | Sequence[str] = False,
) -> None:
self._multiple = multiple
self._lazy = lazy
+ if isinstance(expanded, bool):
+ count = len(items) if multiple else min(1, len(items))
+ self._expanded = [str(i) for i in range(count)] if expanded else []
+ else:
+ if isinstance(expanded, str) or not isinstance(expanded, Sequence):
+ raise TypeError(
+ "expanded must be a bool or a sequence of item keys. "
+ 'Use ["key"] instead of "key".'
+ )
+ indices = {key: str(i) for i, key in enumerate(items)}
+ keys = dict.fromkeys(expanded)
+ for key in keys:
+ if key not in indices:
+ raise ValueError(f"Unknown expanded item key: {key!r}")
+ if not multiple and len(keys) > 1:
+ raise ValueError(
+ "Expanding more than one item requires multiple=True."
+ )
+ self._expanded = [indices[key] for key in keys]
+
self._tabs: list[Html]
if self._lazy:
self._tabs = [lazy_ui(tab) for tab in items.values()]
@@ -71,6 +118,7 @@ class accordion(ContainerHtml):
args={
"labels": [label.text for label in self._labels],
"multiple": self._multiple,
+ "expanded": self._expanded,
},
slotted_html="".join(
[f"<div>{tab.text}</div>" for tab in self._tabs]
diff --git a/tests/_plugins/stateless/test_accordion.py b/tests/_plugins/stateless/test_accordion.py
index 717e189aec..ea447488dd 100644
--- a/tests/_plugins/stateless/test_accordion.py
+++ b/tests/_plugins/stateless/test_accordion.py
@@ -2,12 +2,21 @@
from __future__ import annotations
import gc
+import html
+import json
+import re
import weakref
+from typing import TYPE_CHECKING
+
+import pytest
import marimo as mo
from marimo._output.hypertext import Html
from marimo._plugins.stateless.accordion import accordion
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
def test_accordion_retains_strong_references() -> None:
# Regression test: accordion() must keep a strong reference to its children
@@ -58,3 +67,69 @@ def test_accordion_child_updates_live() -> None:
spinner.update(title="Done")
assert "Done" in result.text
assert "Loading" not in result.text
+
+
+ ("expanded", "multiple", "expected"),
+ [
+ (False, False, []),
+ (False, True, []),
+ (True, False, ["0"]),
+ (True, True, ["0", "1"]),
+ ([], False, []),
+ (["**Details**"], False, ["1"]),
+ (("**Details**", "Summary"), True, ["1", "0"]),
+ (["Summary", "Summary"], False, ["0"]),
+ ],
+)
[email protected]("lazy", [False, True])
+def test_accordion_expanded(
+ expanded: bool | Sequence[str],
+ multiple: bool,
+ expected: list[str],
+ lazy: bool,
+) -> None:
+ result = accordion(
+ {"Summary": "Overview", "**Details**": "More information"},
+ multiple=multiple,
+ lazy=lazy,
+ expanded=expanded,
+ )
+ match = re.search("data-expanded='(.*?)'", result.text)
+ assert match is not None
+ assert json.loads(html.unescape(match[1])) == expected
+
+
[email protected]("multiple", [False, True])
+def test_empty_accordion_expanded(multiple: bool) -> None:
+ result = accordion({}, multiple=multiple, expanded=True)
+ assert "data-expanded='[]'" in result.text
+
+
+def test_accordion_default_collapsed() -> None:
+ result = accordion({"Summary": "Overview"})
+ assert "data-expanded='[]'" in result.text
+
+
[email protected]("multiple", [False, True])
+def test_accordion_unknown_expanded_key(multiple: bool) -> None:
+ with pytest.raises(
+ ValueError, match="Unknown expanded item key: 'Details'"
+ ):
+ accordion(
+ {"Summary": "Overview"}, multiple=multiple, expanded=["Details"]
+ )
+
+
+def test_accordion_multiple_expanded_requires_multiple() -> None:
+ with pytest.raises(ValueError, match="requires multiple=True"):
+ accordion(
+ {"Summary": "Overview", "Details": "More"},
+ expanded=["Summary", "Details"],
+ )
+
+
[email protected]("expanded", ["Summary", 1, None, {"Summary"}])
+def test_accordion_rejects_invalid_expanded_type(expanded: object) -> None:
+ with pytest.raises(TypeError, match="sequence of item keys"):
+ accordion({"Summary": "Overview"}, expanded=expanded) # type: ignore[arg-type]