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 outline as a panel while in edit-mode (#267)

Myles Scolnick7bc5828b16e5
diff --git a/frontend/src/core/dom/__tests__/outline.test.ts b/frontend/src/core/dom/__tests__/outline.test.ts
new file mode 100644
index 0000000000..d259680762
--- /dev/null
+++ b/frontend/src/core/dom/__tests__/outline.test.ts
@@ -0,0 +1,148 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { describe, expect, it } from "vitest";
+import { parseOutline } from "../outline";
+
+describe("parseOutline", () => {
+ it("can parse html outline", () => {
+ const html = `
+ <span class="markdown">
+ <h1 id="welcome-to-marimo">Welcome to marimo! 🌊🍃</h1>
+ <h2 id="what-is-marimo">What is <b>marimo</b>?</h2>
+ <span class="paragraph">marimo is a Python library for creating reactive and interactive notebooks</span>
+ <h2 id="how-do-i-use-marimo">How do I use marimo?</h2>
+ <span class="paragraph">pip install marimo</span>
+ </span>
+ `;
+ const outline = parseOutline({
+ mimetype: "text/html",
+ timestamp: 0,
+ channel: "output",
+ data: html,
+ });
+ expect(outline).toMatchInlineSnapshot(`
+ {
+ "items": [
+ {
+ "id": "welcome-to-marimo",
+ "level": 1,
+ "name": "Welcome to marimo! 🌊🍃",
+ },
+ {
+ "id": "what-is-marimo",
+ "level": 2,
+ "name": "What is marimo?",
+ },
+ {
+ "id": "how-do-i-use-marimo",
+ "level": 2,
+ "name": "How do I use marimo?",
+ },
+ ],
+ }
+ `);
+ });
+
+ it("can parse html outline with duplicate nested headings", () => {
+ const html = `
+ <span class="markdown">
+ <h1 id="experiment-1">Experiment 1</h1>
+ <h2 id="setup">Setup</h2>
+ <h2 id="instructions">Instructions</h2>
+ <h1 id="experiment-2">Experiment 2</h1>
+ <h2 id="setup">Setup</h2>
+ <h2 id="instructions">Instructions</h2>
+ <h1 id="ack">Acknowledgements</h1>
+ <h3 id="marimo">marimo</h1>
+ </span>
+ `;
+ const outline = parseOutline({
+ mimetype: "text/html",
+ timestamp: 0,
+ channel: "output",
+ data: html,
+ });
+ expect(outline).toMatchInlineSnapshot(`
+ {
+ "items": [
+ {
+ "id": "experiment-1",
+ "level": 1,
+ "name": "Experiment 1",
+ },
+ {
+ "id": "setup",
+ "level": 2,
+ "name": "Setup",
+ },
+ {
+ "id": "instructions",
+ "level": 2,
+ "name": "Instructions",
+ },
+ {
+ "id": "experiment-2",
+ "level": 1,
+ "name": "Experiment 2",
+ },
+ {
+ "id": "setup",
+ "level": 2,
+ "name": "Setup",
+ },
+ {
+ "id": "instructions",
+ "level": 2,
+ "name": "Instructions",
+ },
+ {
+ "id": "ack",
+ "level": 1,
+ "name": "Acknowledgements",
+ },
+ {
+ "id": "marimo",
+ "level": 3,
+ "name": "marimo",
+ },
+ ],
+ }
+ `);
+ });
+
+ it("can handle non-html outline", () => {
+ const html = "foo";
+ const outline = parseOutline({
+ mimetype: "text/plain",
+ timestamp: 0,
+ channel: "output",
+ data: html,
+ });
+ expect(outline).toEqual(null);
+ });
+
+ it("can handle empty/null outline", () => {
+ expect(parseOutline(null)).toEqual(null);
+ expect(parseOutline(undefined!)).toEqual(null);
+
+ const html = "";
+ expect(
+ parseOutline({
+ mimetype: "text/html",
+ timestamp: 0,
+ channel: "output",
+ data: html,
+ })
+ ).toEqual({ items: [] });
+ });
+
+ it("can handle invalid outline", () => {
+ const html = "<h1>foo</h1><h2>bar</h2><h3>baz</h3>";
+ const outline = parseOutline({
+ mimetype: "text/html",
+ timestamp: 0,
+ channel: "output",
+ data: html,
+ });
+ expect(outline).toEqual({ items: [] });
+ });
+});
diff --git a/frontend/src/core/dom/outline.ts b/frontend/src/core/dom/outline.ts
new file mode 100644
index 0000000000..56adea871e
--- /dev/null
+++ b/frontend/src/core/dom/outline.ts
@@ -0,0 +1,54 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+
+import { Logger } from "@/utils/Logger";
+import { OutputMessage } from "../kernel/messages";
+import { Outline } from "../model/outline";
+
+function getOutline(html: string): Outline {
+ const items: Outline["items"] = [];
+
+ const parser = new DOMParser();
+ const document = parser.parseFromString(html, "text/html");
+
+ const headings = document.querySelectorAll("h1, h2, h3");
+ // eslint-disable-next-line unicorn/prefer-spread
+ for (const heading of Array.from(headings)) {
+ const name = heading.textContent;
+ if (!name) {
+ continue;
+ }
+
+ const id = heading.id;
+ if (!id) {
+ continue;
+ }
+
+ const level = Number.parseInt(heading.tagName[1], 10);
+ items.push({ name, id, level });
+ }
+
+ return { items };
+}
+
+export function mergeOutlines(outlines: Array<Outline | null>): Outline {
+ return {
+ items: outlines.filter(Boolean).flatMap((outline) => outline.items),
+ };
+}
+
+export function parseOutline(output: OutputMessage | null): Outline | null {
+ if (output == null) {
+ return null;
+ }
+
+ if (output.mimetype !== "text/html") {
+ return null;
+ }
+
+ try {
+ return getOutline(output.data);
+ } catch {
+ Logger.error("Failed to parse outline");
+ return null;
+ }
+}
diff --git a/frontend/src/core/model/cells.ts b/frontend/src/core/model/cells.ts
index ee4e624d4e..d01fc3acb9 100644
--- a/frontend/src/core/model/cells.ts
+++ b/frontend/src/core/model/cells.ts
@@ -4,6 +4,8 @@ import { OutputMessage } from "../kernel/messages";
import { SerializedEditorState } from "../codemirror/types";
import { CellHandle } from "../../editor/Cell";
import { CellId } from "./ids";
+import { Outline } from "./outline";
+import { parseOutline } from "../dom/outline";
export const DEFAULT_CELL_NAME = "__";
@@ -50,6 +52,7 @@ export function createCell({
config: config,
name: name,
output: output,
+ outline: parseOutline(output),
code: code,
status: status,
edited: edited,
@@ -73,6 +76,8 @@ export interface CellState {
code: string;
/** a message encoding the cell's output */
output: OutputMessage | null;
+ /** TOC outline */
+ outline: Outline | null;
/** messages encoding the cell's console outputs. */
consoleOutputs: OutputMessage[];
/** current status of the cell */
diff --git a/frontend/src/core/model/outline.ts b/frontend/src/core/model/outline.ts
new file mode 100644
index 0000000000..10471a4136
--- /dev/null
+++ b/frontend/src/core/model/outline.ts
@@ -0,0 +1,14 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+
+/**
+ * Table of contents outline.
+ */
+export interface OutlineItem {
+ name: string;
+ id: string;
+ level: number;
+}
+
+export interface Outline {
+ items: OutlineItem[];
+}
diff --git a/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snap b/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snap
index 09d19db479..358486662d 100644
--- a/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snap
+++ b/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snap
@@ -11,6 +11,7 @@ exports[`cell reducer > can run a stale cell 1`] = `
"key": "1",
"lastCodeRun": "mo.slider()",
"name": "__",
+ "outline": null,
"output": null,
"ref": {
"current": null,
@@ -34,6 +35,7 @@ exports[`cell reducer > can run a stale cell 2`] = `
"key": "1",
"lastCodeRun": "mo.slider()",
"name": "__",
+ "outline": null,
"output": null,
"ref": {
"current": null,
@@ -57,6 +59,7 @@ exports[`cell reducer > can run a stopped cell 1`] = `
"key": "0",
"lastCodeRun": "mo.md('This has an ancestor that was stopped')",
"name": "__",
+ "outline": null,
"output": null,
"ref": {
"current": null,
@@ -80,6 +83,7 @@ exports[`cell reducer > can run a stopped cell 2`] = `
"key": "0",
"lastCodeRun": "mo.md('This has an ancestor that was stopped')",
"name": "__",
+ "outline": null,
"output": null,
"ref": {
"current": null,
@@ -103,6 +107,7 @@ exports[`cell reducer > can run a stopped cell 3`] = `
"key": "0",
"lastCodeRun": "mo.md('This has an ancestor that was stopped')",
"name": "__",
+ "outline": null,
"output": {
"channel": "marimo-error",
"data": [
@@ -137,6 +142,7 @@ exports[`cell reducer > can run a stopped cell 4`] = `
"key": "0",
"lastCodeRun": "mo.md('This has an ancestor that was stopped')",
"name": "__",
+ "outline": null,
"output": {
"channel": "marimo-error",
"data": [
@@ -171,6 +177,7 @@ exports[`cell reducer > can run a stopped cell 5`] = `
"key": "0",
"lastCodeRun": "mo.md('This has an ancestor that was stopped')",
"name": "__",
+ "outline": null,
"output": null,
"ref": {
"current": null,
@@ -194,6 +201,7 @@ exports[`cell reducer > can run cell and receive cell messages 1`] = `
"key": "0",
"lastCodeRun": null,
"name": "__",
+ "outline": null,
"output": null,
"ref": {
"current": null,
@@ -217,6 +225,7 @@ exports[`cell reducer > can run cell and receive cell messages 2`] = `
"key": "0",
"lastCodeRun": null,
"name": "__",
+ "outline": null,
"output": null,
"ref": {
"current": null,
@@ -240,6 +249,7 @@ exports[`cell reducer > can run cell and receive cell messages 3`] = `
"key": "0",
"lastCodeRun": "import marimo as mo",
"name": "__",
+ "outline": null,
"output": null,
"ref": {
"current": null,
@@ -263,6 +273,7 @@ exports[`cell reducer > can run cell and receive cell messages 4`] = `
"key": "0",
"lastCodeRun": "import marimo as mo",
"name": "__",
+ "outline": null,
"output": null,
"ref": {
"current": null,
@@ -286,6 +297,7 @@ exports[`cell reducer > can run cell and receive cell messages 5`] = `
"key": "0",
"lastCodeRun": "import marimo as mo",
"name": "__",
+ "outline": null,
"output": null,
"ref": {
"current": null,
@@ -316,6 +328,7 @@ exports[`cell reducer > can run cell and receive cell messages 6`] = `
"key": "0",
"lastCodeRun": "import marimo as mo",
"name": "__",
+ "outline": null,
"output": null,
"ref": {
"current": null,
@@ -346,6 +359,7 @@ exports[`cell reducer > can run cell and receive cell messages 7`] = `
"key": "0",
"lastCodeRun": "import marimo as mo",
"name": "__",
+ "outline": null,
"output": {
"channel": "output",
"data": "ok",
@@ -382,6 +396,7 @@ import numpy",
"key": "0",
"lastCodeRun": "import marimo as mo",
"name": "__",
+ "outline": null,
"output": {
"channel": "output",
"data": "ok",
@@ -417,6 +432,7 @@ exports[`cell reducer > can run cell and receive cell messages 9`] = `
"key": "0",
"lastCodeRun": "import marimo as mo",
"name": "__",
+ "outline": null,
"output": {
"channel": "output",
"data": "ok",
@@ -453,6 +469,7 @@ import numpy",
"key": "0",
"lastCodeRun": "import marimo as mo",
"name": "__",
+ "outline": null,
"output": {
"channel": "output",
"data": "ok",
@@ -490,6 +507,7 @@ import numpy",
"lastCodeRun": "import marimo as mo
import numpy",
"name": "__",
+ "outline": null,
"output": {
"channel": "marimo-error",
"data": [
@@ -532,6 +550,7 @@ import numpy",
"key": "0",
"lastCodeRun": null,
"name": "__",
+ "outline": null,
"output": {
"channel": "marimo-error",
"data": [
diff --git a/frontend/src/core/state/cell.ts b/frontend/src/core/state/cell.ts
index 4221dcef5c..0ba1dc3d63 100644
--- a/frontend/src/core/state/cell.ts
+++ b/frontend/src/core/state/cell.ts
@@ -3,6 +3,7 @@ import { logNever } from "@/utils/assertNever";
import { CellMessage } from "../kernel/messages";
import { CellState } from "../model/cells";
import { collapseConsoleOutputs } from "../model/collapseConsoleOutputs";
+import { parseOutline } from "../dom/outline";
export function transitionCell(
cell: CellState,
@@ -86,6 +87,8 @@ export function transitionCell(
: collapseConsoleOutputs([...cell.consoleOutputs, message.console]);
}
nextCell.consoleOutputs = consoleOutputs;
+ // Derive outline from output
+ nextCell.outline = parseOutline(nextCell.output);
return nextCell;
}
diff --git a/frontend/src/core/state/cells.ts b/frontend/src/core/state/cells.ts
index 92be3b515c..eabeb6e3a2 100644
--- a/frontend/src/core/state/cells.ts
+++ b/frontend/src/core/state/cells.ts
@@ -15,6 +15,7 @@ import { store } from "./jotai";
import { createReducer } from "../../utils/createReducer";
import { arrayInsert, arrayDelete } from "@/utils/arrays";
import { foldAllBulk, unfoldAllBulk } from "../codemirror/editing/commands";
+import { mergeOutlines } from "../dom/outline";
/* The array of cells on the page, together with a history of
* deleted cells to implement an "undo delete" action
@@ -424,6 +425,11 @@ export const cellErrors = atom((get) => {
return errors;
});
+export const notebookOutline = atom((get) => {
+ const outlines = get(cellsAtom).present.map((cell) => cell.outline);
+ return mergeOutlines(outlines);
+});
+
export const cellErrorCount = atom((get) => get(cellErrors).length);
/**
diff --git a/frontend/src/editor/chrome/panels/outline-panel.css b/frontend/src/editor/chrome/panels/outline-panel.css
new file mode 100644
index 0000000000..c7250c0f84
--- /dev/null
+++ b/frontend/src/editor/chrome/panels/outline-panel.css
@@ -0,0 +1,4 @@
+.outline-item-highlight {
+ text-decoration: underline;
+ @apply decoration-primary;
+}
diff --git a/frontend/src/editor/chrome/panels/outline-panel.tsx b/frontend/src/editor/chrome/panels/outline-panel.tsx
new file mode 100644
index 0000000000..a0a2477bbc
--- /dev/null
+++ b/frontend/src/editor/chrome/panels/outline-panel.tsx
@@ -0,0 +1,64 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import React from "react";
+import { notebookOutline } from "../../../core/state/cells";
+import { useAtomValue } from "jotai";
+import { cn } from "@/lib/utils";
+import { ScrollTextIcon } from "lucide-react";
+
+import "./outline-panel.css";
+
+export const OutlinePanel: React.FC = () => {
+ const outline = useAtomValue(notebookOutline);
+
+ if (outline.items.length === 0) {
+ return (
+ <div className="mx-6 my-6 flex flex-row gap-2 items-center rounded-lg">
+ <ScrollTextIcon className="text-muted-foreground" />
+ <span className="mt-[0.25rem] text-muted-foreground">No outline</span>
+ </div>
+ );
+ }
+
+ const handleGoToItem = (id: string, index: number) => {
+ // Selectors may be duplicated, so we need to use querySelectorAll
+ const elems = document.querySelectorAll(`#${id}`);
+ const el = elems[index];
+ if (el) {
+ el.scrollIntoView({ behavior: "smooth", block: "start" });
+
+ // Add underline to the element for a few seconds
+ el.classList.add("outline-item-highlight");
+ setTimeout(() => {
+ el.classList.remove("outline-item-highlight");
+ }, 3000);
+ }
+ };
+
+ // Map of selector to its occurrences
+ const seen = new Map<string, number>();
+ return (
+ <div className="flex flex-col overflow-auto py-4 pl-2">
+ {outline.items.map((item) => {
+ // Keep track of how many times we've seen this selector
+ const occurrences = seen.get(item.id) ?? 0;
+ seen.set(item.id, occurrences + 1);
+
+ return (
+ <div
+ key={item.id}
+ className={cn(
+ "px-2 py-1 cursor-pointer hover:bg-accent/50 hover:text-accent-foreground rounded-l",
+ item.level === 1 && "font-semibold",
+ item.level === 2 && "ml-3",
+ item.level === 3 && "ml-6",
+ item.level === 4 && "ml-9"
+ )}
+ onClick={() => handleGoToItem(item.id, occurrences)}
+ >
+ {item.name}
+ </div>
+ );
+ })}
+ </div>
+ );
+};
diff --git a/frontend/src/editor/chrome/types.ts b/frontend/src/editor/chrome/types.ts
index dc7af5dfa9..96bf19ef99 100644
--- a/frontend/src/editor/chrome/types.ts
+++ b/frontend/src/editor/chrome/types.ts
@@ -1,2 +1,2 @@
/* Copyright 2023 Marimo. All rights reserved. */
-export type PanelType = "errors" | "variables";
+export type PanelType = "errors" | "variables" | "outline";
diff --git a/frontend/src/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/editor/chrome/wrapper/app-chrome.tsx
index 8479c0213f..93f885a248 100644
--- a/frontend/src/editor/chrome/wrapper/app-chrome.tsx
+++ b/frontend/src/editor/chrome/wrapper/app-chrome.tsx
@@ -17,6 +17,7 @@ import { useCellIds } from "@/core/state/cells";
import { Button } from "@/components/ui/button";
import { XIcon } from "lucide-react";
import { ErrorsPanel } from "../panels/error-panel";
+import { OutlinePanel } from "../panels/outline-panel";
export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
const { isOpen, selectedPanel, panelLocation } = useChromeState();
@@ -79,6 +80,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
variables={variables}
/>
)}
+ {selectedPanel === "outline" && <OutlinePanel />}
</div>
);
diff --git a/frontend/src/editor/chrome/wrapper/footer.tsx b/frontend/src/editor/chrome/wrapper/footer.tsx
index bef17589a4..f19fcfb94f 100644
--- a/frontend/src/editor/chrome/wrapper/footer.tsx
+++ b/frontend/src/editor/chrome/wrapper/footer.tsx
@@ -5,6 +5,7 @@ import {
PanelLeftIcon,
CircleEqualIcon,
XCircleIcon,
+ ScrollTextIcon,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { useChromeActions, useChromeState } from "../state";
@@ -38,6 +39,13 @@ export const Footer: React.FC = () => {
>
<CircleEqualIcon className={cn("h-4 w-4")} />
</FooterItem>
+ <FooterItem
+ tooltip="View outline"
+ selected={selectedPanel === "outline"}
+ onClick={() => openApplication("outline")}
+ >
+ <ScrollTextIcon className={cn("h-4 w-4")} />
+ </FooterItem>
<div className="mx-auto" />
<FooterItem
tooltip="Move panel to the left"
diff --git a/marimo/_output/md.py b/marimo/_output/md.py
index 073b66f01b..2d4d944b8a 100644
--- a/marimo/_output/md.py
+++ b/marimo/_output/md.py
@@ -44,6 +44,9 @@ def _md(text: str, apply_markdown_class: bool = True) -> Html:
"pymdownx.tilde",
# Better code blocks
"pymdownx.superfences",
+ # Table of contents
+ # This adds ids to the HTML headers
+ "toc",
],
extension_configs=extension_configs,
).strip()