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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: floating outline in run/present (#1845)
Myles Scolnick6c89082fe012
diff --git a/frontend/src/components/editor/chrome/panels/outline-panel.tsx b/frontend/src/components/editor/chrome/panels/outline-panel.tsxindex 9b01536791..204cf15fed 100644--- a/frontend/src/components/editor/chrome/panels/outline-panel.tsx+++ b/frontend/src/components/editor/chrome/panels/outline-panel.tsx@@ -1,20 +1,23 @@/* Copyright 2024 Marimo. All rights reserved. */-import React from "react";+import React, { useMemo } from "react";import { notebookOutline } from "../../../../core/cells/cells";import { useAtomValue } from "jotai";-import { cn } from "@/utils/cn";import { ScrollTextIcon } from "lucide-react";import { PanelEmptyState } from "./empty-state";-import { OutlineItem } from "@/core/cells/outline";-import { Logger } from "@/utils/Logger";-import "./outline-panel.css";+import {+ findOutlineElements,+ useActiveOutline,+} from "./outline/useActiveOutline";+import { OutlineList } from "./outline/floating-outline";export const OutlinePanel: React.FC = () => {- const outline = useAtomValue(notebookOutline);+ const { items } = useAtomValue(notebookOutline);+ const headerElements = useMemo(() => findOutlineElements(items), [items]);+ const { activeHeaderId } = useActiveOutline(headerElements);- if (outline.items.length === 0) {+ if (items.length === 0) {return (<PanelEmptyStatetitle="No outline"@@ -24,66 +27,5 @@ export const OutlinePanel: React.FC = () => {);}- const handleGoToItem = (item: OutlineItem, index: number) => {- let element: HTMLElement | null = null;-- if ("id" in item.by) {- // Selectors may be duplicated, so we need to use querySelectorAll- // IDs that start with a number are invalid, so we need to escape them- const elems = document.querySelectorAll<HTMLElement>(- `[id="${CSS.escape(item.by.id)}"]`,- );- element = elems[index];- } else {- const el = document.evaluate(- item.by.path,- document,- null,- XPathResult.FIRST_ORDERED_NODE_TYPE,- null,- ).singleNodeValue as HTMLElement;- element = el;- }- if (!element) {- Logger.warn("Could not find element for outline item", item);- return;- }-- element.scrollIntoView({ behavior: "smooth", block: "start" });-- // Add underline to the element for a few seconds- element.classList.add("outline-item-highlight");- setTimeout(() => {- element.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, idx) => {- const identifier = "id" in item.by ? item.by.id : item.by.path;- // Keep track of how many times we've seen this selector- const occurrences = seen.get(identifier) ?? 0;- seen.set(identifier, occurrences + 1);-- return (- <div- key={`${identifier}-${idx}`}- 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, occurrences)}- >- {item.name}- </div>- );- })}- </div>- );+ return <OutlineList items={items} activeHeaderId={activeHeaderId} />;};diff --git a/frontend/src/components/editor/chrome/panels/outline/floating-outline.tsx b/frontend/src/components/editor/chrome/panels/outline/floating-outline.tsxnew file mode 100644index 0000000000..229eb55825--- /dev/null+++ b/frontend/src/components/editor/chrome/panels/outline/floating-outline.tsx@@ -0,0 +1,112 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { notebookOutline } from "@/core/cells/cells";+import { cn } from "@/utils/cn";+import { useAtomValue } from "jotai";+import React from "react";+import {+ useActiveOutline,+ scrollToOutlineItem,+ findOutlineElements,+} from "./useActiveOutline";+import { OutlineItem } from "@/core/cells/outline";++export const FloatingOutline: React.FC = () => {+ const { items } = useAtomValue(notebookOutline);+ const { activeHeaderId } = useActiveOutline(findOutlineElements(items));+ const [isHovered, setIsHovered] = React.useState(false);++ if (items.length === 0) {+ return null;+ }++ return (+ <div+ onMouseEnter={() => setIsHovered(true)}+ onMouseLeave={() => setIsHovered(false)}+ className={cn(+ "fixed top-[25vh] right-8 z-[10000]",+ // Hide on small screens+ "hidden md:block",+ )}+ >+ <OutlineList+ className={cn(+ "-top-4 max-h-[70vh] bg-background rounded-lg shadow-lg absolute overflow-auto transition-all duration-300 w-[300px] border",+ isHovered ? "-left-[280px] opacity-100" : "left-[300px] opacity-0",+ )}+ items={items}+ activeHeaderId={activeHeaderId}+ />+ <MiniMap items={items} activeHeaderId={activeHeaderId} />+ </div>+ );+};++export const MiniMap: React.FC<{+ items: OutlineItem[];+ activeHeaderId: string | undefined;+}> = ({ items, activeHeaderId }) => {+ // Map of selector to its occurrences+ const seen = new Map<string, number>();+ return (+ <div className="flex flex-col gap-4 items-end max-h-[70vh] overflow-hidden">+ {items.map((item, idx) => {+ const identifier = "id" in item.by ? item.by.id : item.by.path;+ // Keep track of how many times we've seen this selector+ const occurrences = seen.get(identifier) ?? 0;+ seen.set(identifier, occurrences + 1);++ return (+ <div+ key={`${identifier}-${idx}`}+ className={cn(+ "h-[2px] bg-muted-foreground/60",+ item.level === 1 && "w-5",+ item.level === 2 && "w-4",+ item.level === 3 && "w-3",+ item.level === 4 && "w-2",+ activeHeaderId === identifier && "bg-foreground",+ )}+ onClick={() => scrollToOutlineItem(item, occurrences)}+ />+ );+ })}+ </div>+ );+};++export const OutlineList: React.FC<{+ className?: string;+ items: OutlineItem[];+ activeHeaderId: string | undefined;+}> = ({ items, activeHeaderId, className }) => {+ // Map of selector to its occurrences+ const seen = new Map<string, number>();+ return (+ <div className={cn("flex flex-col overflow-auto py-4 pl-2", className)}>+ {items.map((item, idx) => {+ const identifier = "id" in item.by ? item.by.id : item.by.path;+ // Keep track of how many times we've seen this selector+ const occurrences = seen.get(identifier) ?? 0;+ seen.set(identifier, occurrences + 1);++ return (+ <div+ key={`${identifier}-${idx}`}+ 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",+ activeHeaderId === identifier && "text-accent-foreground",+ )}+ onClick={() => scrollToOutlineItem(item, occurrences)}+ >+ {item.name}+ </div>+ );+ })}+ </div>+ );+};diff --git a/frontend/src/components/editor/chrome/panels/outline/useActiveOutline.tsx b/frontend/src/components/editor/chrome/panels/outline/useActiveOutline.tsxnew file mode 100644index 0000000000..eee666d288--- /dev/null+++ b/frontend/src/components/editor/chrome/panels/outline/useActiveOutline.tsx@@ -0,0 +1,152 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { OutlineItem } from "@/core/cells/outline";+import { headingToIdentifier } from "@/core/dom/outline";+import { initialMode } from "@/core/mode";+import { Logger } from "@/utils/Logger";+import { useEffect, useRef, useState } from "react";++function getRootScrollableElement() {+ // HACK: this is a bit leaky+ // this gets the root element that contains the scrollable content+ return initialMode === "edit" ? document.getElementById("App") : undefined;+}++/**+ * React hook to find the active header in the outline+ */+export function useActiveOutline(+ headerElements: Array<readonly [HTMLElement, string]>,+) {+ const [activeHeaderId, setActiveHeaderId] = useState<string | undefined>(+ undefined,+ );+ const observerRef = useRef<IntersectionObserver | null>(null);+ const topmostHeader = useRef<HTMLElement | null>(null);++ useEffect(() => {+ if (headerElements.length === 0) {+ return;+ }++ const callback: IntersectionObserverCallback = (entries) => {+ let needsUpdate = false;++ entries.forEach((entry) => {+ const element = entry.target as HTMLElement;+ if (entry.isIntersecting) {+ if (+ !topmostHeader.current ||+ element.getBoundingClientRect().top <+ topmostHeader.current.getBoundingClientRect().top+ ) {+ topmostHeader.current = element;+ needsUpdate = true;+ }+ } else if (element === topmostHeader.current) {+ topmostHeader.current = null;+ needsUpdate = true;+ }+ });++ if (needsUpdate && topmostHeader.current) {+ const identifier = headingToIdentifier(topmostHeader.current);+ const id = "id" in identifier ? identifier.id : identifier.path;+ setActiveHeaderId(id);+ }+ };++ observerRef.current = new IntersectionObserver(callback, {+ root: getRootScrollableElement(),+ rootMargin: "0px",+ threshold: 0,+ });++ headerElements.forEach((element) => {+ if (element) {+ observerRef.current?.observe(element[0]);+ }+ });++ return () => {+ if (observerRef.current) {+ observerRef.current.disconnect();+ }+ topmostHeader.current = null;+ };+ }, [headerElements]);++ return { activeHeaderId };+}++/**+ * Finds all the outline elements in the document+ */+export function findOutlineElements(items: OutlineItem[]) {+ if (items.length === 0) {+ return [];+ }++ // Map of selector to its occurrences+ const seen = new Map<string, number>();++ return items+ .map((item) => {+ const identifier = "id" in item.by ? item.by.id : item.by.path;+ // Keep track of how many times we've seen this selector+ const occurrences = seen.get(identifier) ?? 0;+ seen.set(identifier, occurrences + 1);++ const el = findOutlineItem(item, occurrences);+ if (!el) {+ return null;+ }++ return [el, identifier] as const;+ })+ .filter(Boolean);+}++/**+ * Scrolls to the outline item in the document+ */+export function scrollToOutlineItem(item: OutlineItem, index: number) {+ const element = findOutlineItem(item, index);+ if (!element) {+ Logger.warn("Could not find element for outline item", item);+ return;+ }++ element.scrollIntoView({ behavior: "smooth", block: "start" });++ // Add underline to the element for a few seconds+ element.classList.add("outline-item-highlight");+ setTimeout(() => {+ element.classList.remove("outline-item-highlight");+ }, 3000);+}++/**+ * Finds the element in the document that matches the outline item+ */+export function findOutlineItem(+ item: OutlineItem,+ index: number,+): HTMLElement | null {+ if ("id" in item.by) {+ // Selectors may be duplicated, so we need to use querySelectorAll+ // IDs that start with a number are invalid, so we need to escape them+ const elems = document.querySelectorAll<HTMLElement>(+ `[id="${CSS.escape(item.by.id)}"]`,+ );+ return elems[index];+ } else {+ const el = document.evaluate(+ item.by.path,+ document,+ null,+ XPathResult.FIRST_ORDERED_NODE_TYPE,+ null,+ ).singleNodeValue as HTMLElement;+ return el;+ }+}diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsxindex c7456cfb2f..9cbe180b52 100644--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx@@ -11,11 +11,11 @@ import { useDelayVisibility } from "./useDelayVisibility";import { type AppMode, kioskModeAtom } from "@/core/mode";import { ReadonlyPythonCode } from "@/components/editor/code/readonly-python-code";import {- ChevronDown,+ Check,Code2Icon,- Download,FolderDownIcon,ImageIcon,+ MoreHorizontalIcon,} from "lucide-react";import { cn } from "@/utils/cn";import { Button } from "@/components/ui/button";@@ -27,12 +27,14 @@ import {DropdownMenu,DropdownMenuContent,DropdownMenuTrigger,+ DropdownMenuSeparator,} from "@/components/ui/dropdown-menu";import { downloadHTMLAsImage } from "@/utils/download";import { downloadAsHTML } from "@/core/static/download-html";import { isWasm } from "@/core/wasm/utils";import type { CellConfig } from "@/core/network/types";import { useAtomValue } from "jotai";+import { FloatingOutline } from "../../chrome/panels/outline/floating-outline";type VerticalLayout = null;type VerticalLayoutProps = ICellRendererProps<VerticalLayout>;@@ -101,6 +103,8 @@ const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({onToggleShowCode={() => setShowCode((v) => !v)}/>)}+ {/* Shown in read and present */}+ <FloatingOutline /></VerticalLayoutWrapper>);};@@ -136,26 +140,23 @@ const ActionButtons: React.FC<{isStaticNotebook() ? "absolute" : "fixed",)}>- {canShowCode && (- <Button- variant="secondary"- onClick={onToggleShowCode}- size="xs"- data-testid="show-code"- >- <Code2Icon className="w-4 h-4 mr-2" />- {showCode ? "Hide code" : "Show code"}- </Button>- )}<DropdownMenu modal={false}><DropdownMenuTrigger asChild={true}>- <Button variant="secondary" size="xs" data-testid="download-as">- <Download className="w-4 h-4 mr-2" />- Download as- <ChevronDown className="w-4 h-4 ml-2" />+ <Button variant="secondary" size="xs">+ <MoreHorizontalIcon className="w-4 h-4" /></Button></DropdownMenuTrigger><DropdownMenuContent align="end" className="no-print w-[220px]">+ {canShowCode && (+ <>+ <DropdownMenuItem onSelect={onToggleShowCode}>+ <Code2Icon className="mr-2" size={14} strokeWidth={1.5} />+ <span className="flex-1">Show code</span>+ {showCode && <Check className="h-4 w-4" />}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ </>+ )}<DropdownMenuItem onSelect={handleDownloadAsHTML}><FolderDownIcon className="mr-2" size={14} strokeWidth={1.5} />Download as HTMLdiff --git a/frontend/src/core/dom/outline.ts b/frontend/src/core/dom/outline.tsindex e4ac630821..6287374bbf 100644--- a/frontend/src/core/dom/outline.ts+++ b/frontend/src/core/dom/outline.ts@@ -2,7 +2,7 @@import { Logger } from "@/utils/Logger";import type { OutputMessage } from "../kernel/messages";-import type { Outline } from "../cells/outline";+import type { Outline, OutlineItem } from "../cells/outline";import { invariant } from "@/utils/invariant";function getOutline(html: string): Outline {@@ -20,21 +20,21 @@ function getOutline(html: string): Outline {}const level = Number.parseInt(heading.tagName[1], 10);- const id = heading.id;- if (id) {- items.push({ name, level, by: { id } });- } else {- items.push({- name,- level,- by: { path: `//${heading.tagName}[contains(., "${name}")]` },- });- }+ items.push({ name, level, by: headingToIdentifier(heading) });}return { items };}+export function headingToIdentifier(heading: Element): OutlineItem["by"] {+ const id = heading.id;+ if (id) {+ return { id };+ }+ const name = heading.textContent;+ return { path: `//${heading.tagName}[contains(., "${name}")]` };+}+export function mergeOutlines(outlines: Array<Outline | null>): Outline {return {items: outlines.filter(Boolean).flatMap((outline) => outline.items),