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
improvement: improve download menu nesting and add more actions (#818)
Myles Scolnicke7b0f4957403
diff --git a/.github/renovate.json b/.github/renovate.jsonindex a6806c7bfc..25b7231ffa 100644--- a/.github/renovate.json+++ b/.github/renovate.json@@ -1,6 +1,6 @@{"$schema": "https://docs.renovatebot.com/renovate-schema.json",- "extends": ["config:base", "schedule:weekly"],+ "extends": ["config:base", "schedule:monthly"],"labels": ["dependencies"],"pin": false,"rangeStrategy": "bump",diff --git a/frontend/e2e-tests/cells.spec.ts b/frontend/e2e-tests/cells.spec.tsindex 3f677a9938..28c6b6c8a6 100644--- a/frontend/e2e-tests/cells.spec.ts+++ b/frontend/e2e-tests/cells.spec.ts@@ -135,6 +135,6 @@ test("page renders 2 cells", async ({ page }) => {await expect(page.locator("h1")).toHaveText(["Cell 1", "Cell 2"]);});-test("export as HTML", async ({ page }) => {+test("download as HTML", async ({ page }) => {await exportAsHTMLAndTakeScreenshot(page);});diff --git a/frontend/e2e-tests/helper.ts b/frontend/e2e-tests/helper.tsindex b6340700c8..41d27797c7 100644--- a/frontend/e2e-tests/helper.ts+++ b/frontend/e2e-tests/helper.ts@@ -86,7 +86,7 @@ export async function pressShortcut(page: Page, action: HotkeyAction) {}/**- * Export as HTML+ * Download as HTML** Download HTML of the current notebook and take a screenshot*/@@ -101,7 +101,10 @@ export async function exportAsHTMLAndTakeScreenshot(page: Page) {.getByTestId("notebook-menu-dropdown").click().then(() => {- return page.getByText("Export as HTML").click();+ return page.getByText("Download", { exact: true }).hover();+ })+ .then(() => {+ return page.getByText("Download as HTML", { exact: true }).click();}),]);@@ -137,7 +140,10 @@ export async function exportAsPNG(page: Page) {.getByTestId("notebook-menu-dropdown").click().then(() => {- return page.getByText("Export as PNG").click();+ return page.getByText("Download", { exact: true }).hover();+ })+ .then(() => {+ return page.getByText("Download as PNG", { exact: true }).click();}),]);diff --git a/frontend/e2e-tests/kitchen-sink.spec.ts b/frontend/e2e-tests/kitchen-sink.spec.tsindex 3af4c5477b..5ec54608da 100644--- a/frontend/e2e-tests/kitchen-sink.spec.ts+++ b/frontend/e2e-tests/kitchen-sink.spec.ts@@ -9,14 +9,14 @@ import {const appUrl = getAppUrl("kitchen_sink.py//edit");-test("can screenshot and export as html", async ({ page }) => {+test("can screenshot and download as html", async ({ page }) => {await page.goto(appUrl);await takeScreenshot(page, __filename);await exportAsHTMLAndTakeScreenshot(page);});-test.skip("can screenshot and export as png", async ({ page }) => {+test.skip("can screenshot and download as png", async ({ page }) => {await page.goto(appUrl);await exportAsPNG(page);diff --git a/frontend/src/components/editor/CommandPalette.tsx b/frontend/src/components/editor/CommandPalette.tsxindex 88d79eba16..6c77ef8864 100644--- a/frontend/src/components/editor/CommandPalette.tsx+++ b/frontend/src/components/editor/CommandPalette.tsx@@ -19,13 +19,16 @@ import { atom, useAtom } from "jotai";import { useNotebookActions } from "./actions/useNotebookActions";import { Objects } from "@/utils/objects";import { parseShortcut } from "@/core/hotkeys/shortcuts";+import { isParentAction, flattenActions } from "./actions/types";export const commandPaletteAtom = atom(false);export const CommandPalette = () => {const [open, setOpen] = useAtom(commandPaletteAtom);const registeredActions = useRegisteredActions();- const notebookActions = useNotebookActions();+ let notebookActions = useNotebookActions();+ notebookActions = flattenActions(notebookActions);+const notebookActionsWithoutHotkeys = notebookActions.filter((action) => !action.hotkey,);@@ -113,7 +116,7 @@ export const CommandPalette = () => {}// Other actionconst action = keyedNotebookActions[shortcut];- if (action) {+ if (action && !isParentAction(action)) {return renderCommandItem(action.label, action.handle);}return null;diff --git a/frontend/src/components/editor/actions/types.ts b/frontend/src/components/editor/actions/types.tsindex 1ab11208ed..19144aa9e1 100644--- a/frontend/src/components/editor/actions/types.ts+++ b/frontend/src/components/editor/actions/types.ts@@ -8,10 +8,34 @@ import { HotkeyAction } from "@/core/hotkeys/hotkeys";export interface ActionButton {label: string;variant?: "danger";- hotkey?: HotkeyAction;disableClick?: boolean;icon?: React.ReactNode;hidden?: boolean;rightElement?: React.ReactNode;+ hotkey?: HotkeyAction;handle: (event?: Event) => void;+ divider?: boolean;+ dropdown?: ActionButton[];+}++export function isParentAction(+ action: ActionButton,+): action is ActionButton & { dropdown: ActionButton[] } {+ return action.dropdown !== undefined;+}++/**+ * Flattens all actions into a single array.+ * Any parent actions will be removed, but their labels will be prepended to the child actions.+ */+export function flattenActions(+ actions: ActionButton[],+ prevLabel = "",+): ActionButton[] {+ return actions.flatMap((action) => {+ if (isParentAction(action)) {+ return flattenActions(action.dropdown, `${prevLabel + action.label} > `);+ }+ return { ...action, label: prevLabel + action.label };+ });}diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsxindex 114027170b..c623340e85 100644--- a/frontend/src/components/editor/actions/useNotebookActions.tsx+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx@@ -1,6 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */import { runDuringPresentMode } from "@/core/mode";-import { downloadHTMLAsImage } from "@/utils/download";+import { downloadBlob, downloadHTMLAsImage } from "@/utils/download";import { useSetAtom } from "jotai";import {ImageIcon,@@ -12,6 +12,12 @@ import {ClipboardCopyIcon,Share2Icon,PowerSquareIcon,+ GlobeIcon,+ LinkIcon,+ DownloadIcon,+ CodeIcon,+ PanelLeftIcon,+ CheckIcon,} from "lucide-react";import { commandPaletteAtom } from "../CommandPalette";import {@@ -30,10 +36,21 @@ import { useImperativeModal } from "@/components/modal/ImperativeModal";import { ShareStaticNotebookModal } from "@/components/static-html/share-modal";import { useRestartKernel } from "./useRestartKernel";import { createShareableLink } from "@/core/pyodide/share";+import { Paths } from "@/utils/paths";+import { useChromeActions, useChromeState } from "../chrome/state";+import { PANEL_ICONS, PANEL_TYPES } from "../chrome/types";+import { startCase } from "lodash-es";++const NOOP_HANDLER = (event?: Event) => {+ event?.preventDefault();+ event?.stopPropagation();+};export function useNotebookActions() {const [filename] = useFilename();const { openModal, closeModal } = useImperativeModal();+ const { openApplication } = useChromeActions();+ const { selectedPanel } = useChromeState();const notebook = useNotebook();const { updateCellConfig } = useCellActions();@@ -46,52 +63,112 @@ export function useNotebookActions() {const actions: ActionButton[] = [{icon: <Share2Icon size={14} strokeWidth={1.5} />,- label: "Publish as HTML",- handle: async () => {- openModal(<ShareStaticNotebookModal onClose={closeModal} />);- },+ label: "Share",+ handle: NOOP_HANDLER,+ dropdown: [+ {+ icon: <GlobeIcon size={14} strokeWidth={1.5} />,+ label: "Publish HTML to web",+ handle: async () => {+ openModal(<ShareStaticNotebookModal onClose={closeModal} />);+ },+ },+ {+ icon: <LinkIcon size={14} strokeWidth={1.5} />,+ label: "Create WebAssembly link",+ handle: async () => {+ const code = await readCode();+ const url = createShareableLink({ code: code.contents });+ window.navigator.clipboard.writeText(url);+ toast({+ title: "Copied",+ description: "Link copied to clipboard.",+ });+ },+ },+ ],},{- icon: <Share2Icon size={14} strokeWidth={1.5} />,- label: "Share WebAssembly notebook",- handle: async () => {- const code = await readCode();- const url = createShareableLink({ code: code.contents });- window.navigator.clipboard.writeText(url);- toast({- title: "Copied",- description: "Link copied to clipboard.",- });- },+ icon: <DownloadIcon size={14} strokeWidth={1.5} />,+ label: "Download",+ handle: NOOP_HANDLER,+ dropdown: [+ {+ icon: <FolderDownIcon size={14} strokeWidth={1.5} />,+ label: "Download as HTML",+ handle: async () => {+ if (!filename) {+ toast({+ variant: "danger",+ title: "Error",+ description: "Notebooks must be named to be exported.",+ });+ return;+ }+ await downloadAsHTML({ filename });+ },+ },+ {+ icon: <ImageIcon size={14} strokeWidth={1.5} />,+ label: "Download as PNG",+ handle: async () => {+ await runDuringPresentMode(async () => {+ const app = document.getElementById("App");+ if (!app) {+ return;+ }+ await downloadHTMLAsImage(app, filename || "screenshot.png");+ });+ },+ },+ {+ icon: <CodeIcon size={14} strokeWidth={1.5} />,+ label: "Download Python code",+ handle: async () => {+ const code = await readCode();+ downloadBlob(+ new Blob([code.contents], { type: "text/plain" }),+ Paths.basename(filename || "notebook.py"),+ );+ },+ },+ ],},+{- icon: <FolderDownIcon size={14} strokeWidth={1.5} />,- label: "Export as HTML",- handle: async () => {- if (!filename) {- toast({- variant: "danger",- title: "Error",- description: "Notebooks must be named to be exported.",- });- return;- }- await downloadAsHTML({ filename });- },+ divider: true,+ icon: <PanelLeftIcon size={14} strokeWidth={1.5} />,+ label: "Helper panel",+ handle: NOOP_HANDLER,+ dropdown: PANEL_TYPES.map((type) => {+ const Icon = PANEL_ICONS[type];+ return {+ label: startCase(type),+ rightElement: (+ <div className="w-8 flex justify-end">+ {selectedPanel === type && <CheckIcon size={14} />}+ </div>+ ),+ icon: <Icon size={14} strokeWidth={1.5} />,+ handle: () => openApplication(type),+ };+ }),},+{- icon: <ImageIcon size={14} strokeWidth={1.5} />,- label: "Export as PNG",+ icon: <ClipboardCopyIcon size={14} strokeWidth={1.5} />,+ label: "Copy code to clipboard",+ hidden: !filename,handle: async () => {- await runDuringPresentMode(async () => {- const app = document.getElementById("App");- if (!app) {- return;- }- await downloadHTMLAsImage(app, filename || "screenshot.png");+ const code = await readCode();+ navigator.clipboard.writeText(code.contents);+ toast({+ title: "Copied",+ description: "Code copied to clipboard.",});},},+{icon: <ZapIcon size={14} strokeWidth={1.5} />,label: "Enable all cells",@@ -128,20 +205,7 @@ export function useNotebookActions() {},{- icon: <ClipboardCopyIcon size={14} strokeWidth={1.5} />,- label: "Copy code to clipboard",- hidden: !filename,- handle: async () => {- const code = await readCode();- navigator.clipboard.writeText(code.contents);- toast({- title: "Copied",- description: "Code copied to clipboard.",- });- },- },-- {+ divider: true,icon: <CommandIcon size={14} strokeWidth={1.5} />,label: "Command palette",hotkey: "global.commandPalette",@@ -157,6 +221,7 @@ export function useNotebookActions() {},{+ divider: true,icon: <PowerSquareIcon size={14} strokeWidth={1.5} />,label: "Restart kernel",variant: "danger",diff --git a/frontend/src/components/editor/chrome/types.ts b/frontend/src/components/editor/chrome/types.tsindex cdbfee5a69..73c29d8c33 100644--- a/frontend/src/components/editor/chrome/types.ts+++ b/frontend/src/components/editor/chrome/types.ts@@ -1,4 +1,16 @@/* Copyright 2024 Marimo. All rights reserved. */+import { Objects } from "@/utils/objects";+import {+ XCircleIcon,+ FolderTreeIcon,+ FunctionSquareIcon,+ NetworkIcon,+ ScrollTextIcon,+ BookMarkedIcon,+ FileTextIcon,+ LucideIcon,+} from "lucide-react";+export type PanelType =| "files"| "errors"@@ -7,3 +19,15 @@ export type PanelType =| "dependencies"| "documentation"| "logs";++export const PANEL_ICONS: Record<PanelType, LucideIcon> = {+ errors: XCircleIcon,+ files: FolderTreeIcon,+ variables: FunctionSquareIcon,+ dependencies: NetworkIcon,+ outline: ScrollTextIcon,+ documentation: BookMarkedIcon,+ logs: FileTextIcon,+};++export const PANEL_TYPES: PanelType[] = Objects.keys(PANEL_ICONS);diff --git a/frontend/src/components/editor/chrome/wrapper/footer.tsx b/frontend/src/components/editor/chrome/wrapper/footer.tsxindex 2bcee25058..e51f6c14e5 100644--- a/frontend/src/components/editor/chrome/wrapper/footer.tsx+++ b/frontend/src/components/editor/chrome/wrapper/footer.tsx@@ -1,27 +1,24 @@/* Copyright 2024 Marimo. All rights reserved. */import React, { PropsWithChildren } from "react";-import {- FunctionSquareIcon,- XCircleIcon,- ScrollTextIcon,- NetworkIcon,- FileTextIcon,- MessageCircleQuestionIcon,- BookMarkedIcon,- FolderTreeIcon,-} from "lucide-react";+import { MessageCircleQuestionIcon } from "lucide-react";import { cn } from "@/utils/cn";import { useChromeActions, useChromeState } from "../state";import { Tooltip } from "@/components/ui/tooltip";import { useAtomValue } from "jotai";import { cellErrorCount } from "@/core/cells/cells";import { FeedbackButton } from "../footer/feedback-button";+import { PANEL_ICONS, PanelType } from "../types";export const Footer: React.FC = () => {const { selectedPanel } = useChromeState();const { openApplication } = useChromeActions();const errorCount = useAtomValue(cellErrorCount);+ const renderIcon = (type: PanelType, className?: string) => {+ const Icon = PANEL_ICONS[type];+ return <Icon className={cn("h-5 w-5", className)} />;+ };+return (<footer className="h-10 py-2 bg-background flex items-center text-muted-foreground text-md px-4 border-t border-border select-none no-print text-sm shadow-[0_0_4px_1px_rgba(0,0,0,0.1)] z-50"><FooterItem@@ -29,54 +26,50 @@ export const Footer: React.FC = () => {selected={selectedPanel === "errors"}onClick={() => openApplication("errors")}>- <XCircleIcon- className={cn("h-5 w-5 mr-1", {- "text-destructive": errorCount > 0,- })}- />- <span className="font-mono mt-[0.125rem]">{errorCount}</span>+ {renderIcon("errors", errorCount > 0 ? "text-destructive" : "")}+ <span className="ml-1 font-mono mt-[0.125rem]">{errorCount}</span></FooterItem><FooterItemtooltip="View files"selected={selectedPanel === "files"}onClick={() => openApplication("files")}>- <FolderTreeIcon className={cn("h-5 w-5")} />+ {renderIcon("files")}</FooterItem><FooterItemtooltip="Explore variables"selected={selectedPanel === "variables"}onClick={() => openApplication("variables")}>- <FunctionSquareIcon className={cn("h-5 w-5 ")} />+ {renderIcon("variables")}</FooterItem><FooterItemtooltip="Explore dependencies"selected={selectedPanel === "dependencies"}onClick={() => openApplication("dependencies")}>- <NetworkIcon className={cn("h-5 w-5")} />+ {renderIcon("dependencies")}</FooterItem><FooterItemtooltip="View outline"selected={selectedPanel === "outline"}onClick={() => openApplication("outline")}>- <ScrollTextIcon className={cn("h-5 w-5")} />+ {renderIcon("outline")}</FooterItem><FooterItemtooltip="View documentation"selected={selectedPanel === "documentation"}onClick={() => openApplication("documentation")}>- <BookMarkedIcon className={cn("h-5 w-5")} />+ {renderIcon("documentation")}</FooterItem><FooterItemtooltip="Notebook logs"selected={selectedPanel === "logs"}onClick={() => openApplication("logs")}>- <FileTextIcon className={cn("h-5 w-5")} />+ {renderIcon("logs")}</FooterItem><FeedbackButton>diff --git a/frontend/src/components/editor/notebook-menu-dropdown.tsx b/frontend/src/components/editor/notebook-menu-dropdown.tsxindex 64b89d60c0..d5d97feb3f 100644--- a/frontend/src/components/editor/notebook-menu-dropdown.tsx+++ b/frontend/src/components/editor/notebook-menu-dropdown.tsx@@ -6,10 +6,16 @@ import {DropdownMenu,DropdownMenuContent,DropdownMenuItem,+ DropdownMenuPortal,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import { renderMinimalShortcut } from "../shortcuts/renderShortcut";import { useNotebookActions } from "./actions/useNotebookActions";+import { ActionButton } from "./actions/types";export const NotebookMenuDropdown: React.FC = () => {const actions = useNotebookActions();@@ -27,22 +33,63 @@ export const NotebookMenuDropdown: React.FC = () => {</Button>);+ const renderLabel = (action: ActionButton) => {+ return (+ <>+ {action.icon && <span className="flex-0 mr-2">{action.icon}</span>}+ <span className="flex-1">{action.label}</span>+ {action.hotkey && renderMinimalShortcut(action.hotkey)}+ {action.rightElement}+ </>+ );+ };++ const renderLeafAction = (action: ActionButton) => {+ return (+ <DropdownMenuItem+ key={action.label}+ variant={action.variant}+ onSelect={(evt) => action.handle(evt)}+ data-testid={`notebook-menu-dropdown-${action.label}`}+ >+ {renderLabel(action)}+ </DropdownMenuItem>+ );+ };+return (<DropdownMenu modal={false}><DropdownMenuTrigger asChild={true}>{button}</DropdownMenuTrigger><DropdownMenuContent align="end" className="no-print w-[220px]">- {actions.map((action) => (- <DropdownMenuItem- key={action.label}- variant={action.variant}- onSelect={(evt) => action.handle(evt)}- data-testid={`notebook-menu-dropdown-${action.label}`}- >- {action.icon && <span className="flex-0 mr-2">{action.icon}</span>}- <span className="flex-1">{action.label}</span>- {action.hotkey && renderMinimalShortcut(action.hotkey)}- </DropdownMenuItem>- ))}+ {actions.map((action) => {+ if (action.hidden) {+ return null;+ }++ if (action.dropdown) {+ return (+ <DropdownMenuSub key={action.label}>+ <DropdownMenuSubTrigger+ data-testid={`notebook-menu-dropdown-${action.label}`}+ >+ {renderLabel(action)}+ </DropdownMenuSubTrigger>+ <DropdownMenuPortal>+ <DropdownMenuSubContent>+ {action.dropdown.map(renderLeafAction)}+ </DropdownMenuSubContent>+ </DropdownMenuPortal>+ </DropdownMenuSub>+ );+ }++ return (+ <React.Fragment key={action.label}>+ {action.divider && <DropdownMenuSeparator />}+ {renderLeafAction(action)}+ </React.Fragment>+ );+ })}</DropdownMenuContent></DropdownMenu>);diff --git a/frontend/src/components/ui/context-menu.tsx b/frontend/src/components/ui/context-menu.tsxindex f5ca77ffa7..c3e644f106 100644--- a/frontend/src/components/ui/context-menu.tsx+++ b/frontend/src/components/ui/context-menu.tsx@@ -149,7 +149,7 @@ const ContextMenuSeparator = React.forwardRef<>(({ className, ...props }, ref) => (<ContextMenuPrimitive.Separatorref={ref}- className={cn("my-1", menuSeparatorVariants({ className }))}+ className={cn(menuSeparatorVariants({ className }))}{...props}/>));diff --git a/frontend/src/components/ui/dropdown-menu.tsx b/frontend/src/components/ui/dropdown-menu.tsxindex ff505ada6b..107c0d2c9e 100644--- a/frontend/src/components/ui/dropdown-menu.tsx+++ b/frontend/src/components/ui/dropdown-menu.tsx@@ -149,7 +149,7 @@ const DropdownMenuSeparator = React.forwardRef<>(({ className, ...props }, ref) => (<DropdownMenuPrimitive.Separatorref={ref}- className={cn("mb-1", menuSeparatorVariants({ className }))}+ className={menuSeparatorVariants({ className })}{...props}/>));diff --git a/frontend/src/components/ui/menu-items.tsx b/frontend/src/components/ui/menu-items.tsxindex 7cdf7f7372..26dac616fc 100644--- a/frontend/src/components/ui/menu-items.tsx+++ b/frontend/src/components/ui/menu-items.tsx@@ -63,7 +63,7 @@ export const menuItemVariants = cva(},);-export const menuSeparatorVariants = cva("-mx-1 h-px bg-border", {+export const menuSeparatorVariants = cva("-mx-1 my-1 h-px bg-border", {variants: {},});diff --git a/frontend/src/core/pyodide/bridge.ts b/frontend/src/core/pyodide/bridge.tsindex 5a2b24817c..ebf141c698 100644--- a/frontend/src/core/pyodide/bridge.ts+++ b/frontend/src/core/pyodide/bridge.ts@@ -33,6 +33,7 @@ import InlineWorker from "./worker/worker?worker&inline";import { UserConfigLocalStorage } from "../config/config-schema";import { createShareableLink } from "./share";import { PyodideRouter } from "./router";+import { Paths } from "@/utils/paths";export type BridgeFunctionAndPayload = {[P in keyof RawBridge]: {@@ -233,7 +234,7 @@ export class PyodideBridge implements RunRequests, EditRequests {openFile = async (request: { path: string }): Promise<null> => {// Open the file in a new tab by file path- const filename = request.path.split("/").pop();+ const filename = Paths.basename(request.path);const url = createShareableLink({code: null,baseUrl: window.location.origin,diff --git a/frontend/src/core/static/download-html.ts b/frontend/src/core/static/download-html.tsindex 54d3508908..4bf2f22200 100644--- a/frontend/src/core/static/download-html.ts+++ b/frontend/src/core/static/download-html.ts@@ -8,6 +8,7 @@ import { serializeJsonToBase64 } from "@/utils/json/base64";import { readCode } from "../network/requests";import { downloadBlob } from "@/utils/download";import { toast } from "@/components/ui/use-toast";+import { Paths } from "@/utils/paths";// For Testing:// Flip this to `true` to use local assets instead of CDN@@ -56,7 +57,7 @@ export async function downloadAsHTML(opts: { filename: string }) {const { filename } = opts;const html = await createStaticHTMLNotebook();- const filenameWithoutPath = filename.split("/").pop() ?? "notebook.py";+ const filenameWithoutPath = Paths.basename(filename) ?? "notebook.py";const filenameWithoutExtension =filenameWithoutPath.split(".").shift() ?? "app";diff --git a/frontend/src/utils/download.ts b/frontend/src/utils/download.tsindex aab4dd331f..7abff1b4ed 100644--- a/frontend/src/utils/download.ts+++ b/frontend/src/utils/download.ts@@ -21,7 +21,7 @@ export async function downloadHTMLAsImage(} catch {toast({title: "Error",- description: "Failed to export as PNG.",+ description: "Failed to download as PNG.",variant: "danger",});} finally {