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: Download PNG (#65)
Myles Scolnickdf5006fcf1ec
diff --git a/frontend/package.json b/frontend/package.jsonindex fbc687239c..2b3977b23a 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -63,6 +63,7 @@"eslint-plugin-header": "^3.1.1","htm": "^3.1.1","html-react-parser": "^4.2.2",+ "html-to-image": "^1.11.11","jotai": "^2.4.1","katex": "^0.16.8","lucide-react": "^0.274.0",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 0b2314b434..3d02633664 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -161,6 +161,9 @@ dependencies:html-react-parser:specifier: ^4.2.2version: 4.2.2([email protected])+ html-to-image:+ specifier: ^1.11.11+ version: 1.11.11jotai:specifier: ^2.4.1version: 2.4.1(@types/[email protected])([email protected])@@ -9029,6 +9032,10 @@ packages:engines: {node: '>=8'}dev: true+ resolution: {integrity: sha512-9gux8QhvjRO/erSnDPv28noDZcPZmYE7e1vFsBLKLlRlKDSqNJYebj6Qz1TGd5lsRV+X+xYyjCKjuZdABinWjA==}+ dev: false+resolution: {integrity: sha512-uxbSI98wmFT/G4P2zXx4OVx04qWUmyFPrD2/CNepa2Zo3GPNaCaaxElDgwUrwYWkK1nr9fft0Ya8dws8coDLLQ==}dependencies:diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 7a4125e57e..f782a98398 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -23,7 +23,7 @@ import { useCellActions, useCells } from "./core/state/cells";import { Disconnected } from "./editor/Disconnected";import { derefNotNull } from "./utils/dereference";import { AppConfig, UserConfig } from "./core/config";-import { AppMode, toggleAppMode } from "./core/mode";+import { toggleAppMode, viewStateAtom } from "./core/mode";import { useHotkey } from "./hooks/useHotkey";import { Tooltip } from "./components/ui/tooltip";import { useImperativeModal } from "./components/modal/ImperativeModal";@@ -44,39 +44,17 @@ import { CellId, HTMLCellId } from "./core/model/ids";import { getFilenameFromDOM } from "./core/dom/htmlUtils";import { CellArray } from "./editor/renderers/CellArray";import { RuntimeState } from "./core/RuntimeState";+import { useAtom } from "jotai";interface AppProps {- initialMode: AppMode;userConfig: UserConfig;appConfig: AppConfig;}-/**- * View state for the app.- */-interface ViewState {- /**- * The mode of the app: read/edit/present- */- mode: AppMode;- /**- * A cell ID to anchor scrolling to when toggling between presenting and- * editing views- */- cellAnchor: CellId | null;-}--export const App: React.FC<AppProps> = ({- initialMode,- userConfig,- appConfig,-}) => {+export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {const cells = useCells();const { setCells } = useCellActions();- const [viewState, setViewState] = useState<ViewState>({- mode: initialMode,- cellAnchor: null,- });+ const [viewState, setViewState] = useAtom(viewStateAtom);const [filename, setFilename] = useState(getFilenameFromDOM());const [savedCodes, setSavedCodes] = useState<string[]>([""]);const { openModal, closeModal, openAlert } = useImperativeModal();diff --git a/frontend/src/MarimoApp.tsx b/frontend/src/MarimoApp.tsxindex d1a6c8ef7b..838b42d938 100644--- a/frontend/src/MarimoApp.tsx+++ b/frontend/src/MarimoApp.tsx@@ -4,25 +4,18 @@ import "./css/index.css";import { ErrorBoundary } from "./editor/boundary/ErrorBoundary";import { initializePlugins } from "./plugins/plugins";import { App } from "./App";-import { AppMode } from "./core/mode";import { TooltipProvider } from "./components/ui/tooltip";import { Toaster } from "./components/ui/toaster";import { ModalProvider } from "./components/modal/ImperativeModal";import { DayPickerProvider } from "react-day-picker";import { CommandPallette } from "./editor/CommandPallette";import { useAppConfig, useUserConfig } from "@/core/state/config";--interface MarimoAppProps {- /**- * The mode of the Marimo app.- */- initialMode: AppMode;-}+import { initialMode } from "./core/mode";/*** The root component of the Marimo app.*/-export const MarimoApp: React.FC<MarimoAppProps> = ({ initialMode }) => {+export const MarimoApp: React.FC = () => {const [userConfig] = useUserConfig();const [appConfig] = useAppConfig();@@ -35,11 +28,7 @@ export const MarimoApp: React.FC<MarimoAppProps> = ({ initialMode }) => {<TooltipProvider><DayPickerProvider initialProps={{}}><ModalProvider>- <App- initialMode={initialMode}- userConfig={userConfig}- appConfig={appConfig}- />+ <App userConfig={userConfig} appConfig={appConfig} /><Toaster />{initialMode !== "read" && <CommandPallette />}</ModalProvider>diff --git a/frontend/src/components/export/export-output-button.tsx b/frontend/src/components/export/export-output-button.tsxnew file mode 100644index 0000000000..042b649411--- /dev/null+++ b/frontend/src/components/export/export-output-button.tsx@@ -0,0 +1,13 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { downloadHTMLAsImage } from "@/utils/download";+import { CellId } from "@/core/model/ids";++export function downloadCellOutput(cellId: CellId) {+ const output = document.getElementById(`output-${cellId}`);+ if (output) {+ output.classList.add("printing-output");+ downloadHTMLAsImage(output, "result.png").finally(() => {+ output.classList.remove("printing-output");+ });+ }+}diff --git a/frontend/src/components/export/menu-dropdown.tsx b/frontend/src/components/export/menu-dropdown.tsxnew file mode 100644index 0000000000..33582478fc--- /dev/null+++ b/frontend/src/components/export/menu-dropdown.tsx@@ -0,0 +1,76 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { Button } from "@/editor/inputs/Inputs";+import { CommandIcon, ImageIcon, MenuIcon } from "lucide-react";+import React from "react";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { downloadHTMLAsImage } from "@/utils/download";+import { commandPalletteAtom } from "@/editor/CommandPallette";+import { useSetAtom } from "jotai";+import { HotkeyAction } from "@/core/hotkeys/hotkeys";+import { renderMinimalShortcut } from "../shortcuts/renderShortcut";+import { runDuringPresentMode } from "@/core/mode";++interface Props {+ filename: string | null;+}++interface Action {+ label: string;+ hotkey?: HotkeyAction;+ icon?: React.ReactNode;+ handle: () => void;+}++export const MenuDropdown: React.FC<Props> = ({ filename }) => {+ const setCommandPalletteOpen = useSetAtom(commandPalletteAtom);++ const button = (+ <Button+ aria-label="Config"+ shape="circle"+ size="small"+ className="h-[27px] w-[27px]"+ color="hint-green"+ >+ <MenuIcon strokeWidth={1.8} />+ </Button>+ );++ const actions: Action[] = [+ {+ icon: <ImageIcon size={13} strokeWidth={1.5} />,+ label: "Export to PNG",+ handle: async () => {+ await runDuringPresentMode(() => {+ downloadHTMLAsImage(document.body, filename || "screenshot.png");+ });+ },+ },+ {+ icon: <CommandIcon size={13} strokeWidth={1.5} />,+ label: "Command Palette",+ hotkey: "global.commandPalette",+ handle: () => setCommandPalletteOpen((open) => !open),+ },+ ];++ return (+ <DropdownMenu modal={false}>+ <DropdownMenuTrigger asChild={true}>{button}</DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="no-print w-[220px]">+ {actions.map((action) => (+ <DropdownMenuItem key={action.label} onSelect={() => action.handle()}>+ {action.icon && <span className="flex-0 mr-2">{action.icon}</span>}+ <span className="flex-1">{action.label}</span>+ {action.hotkey && renderMinimalShortcut(action.hotkey)}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ );+};diff --git a/frontend/src/components/icons/multi-icon.tsx b/frontend/src/components/icons/multi-icon.tsxnew file mode 100644index 0000000000..8c60a40858--- /dev/null+++ b/frontend/src/components/icons/multi-icon.tsx@@ -0,0 +1,17 @@+/* Copyright 2023 Marimo. All rights reserved. */+import React, { PropsWithChildren } from "react";++/**+ * First icon is left untouched, and second icon is layered to the bottom right/+ */+export const MultiIcon = (props: PropsWithChildren) => {+ const [first, second] = React.Children.toArray(props.children);+ return (+ <div className="relative">+ {first}+ <div className="absolute bottom-0 right-1 transform translate-x-1/2 translate-y-1/2">+ {second}+ </div>+ </div>+ );+};diff --git a/frontend/src/components/shortcuts/renderShortcut.tsx b/frontend/src/components/shortcuts/renderShortcut.tsxindex 60b1dd9648..7e2fbff11f 100644--- a/frontend/src/components/shortcuts/renderShortcut.tsx+++ b/frontend/src/components/shortcuts/renderShortcut.tsx@@ -11,13 +11,25 @@ export function renderShortcut(shortcut: HotkeyAction) {{hotkey.name}{" "}<span className="flex ml-1 gap-1">{prettyPrintHotkey(hotkey.key).map((key) => (- <Kbd key={key}>{key}</Kbd>+ <Kbd key={key}>{capitalize(key)}</Kbd>))}</span></span>);}+export function renderMinimalShortcut(shortcut: HotkeyAction) {+ const hotkey = HOTKEYS.getHotkey(shortcut);++ return (+ <span className="text-xs flex gap-1 text-muted-foreground items-center font-mono">+ {prettyPrintHotkey(hotkey.key).map((key) => (+ <span key={key}>{capitalize(key)}</span>+ ))}+ </span>+ );+}+export function prettyPrintHotkey(keyboard: string) {return keyboard.split("-").map((key) => {switch (key.toLowerCase()) {@@ -37,3 +49,7 @@ export function prettyPrintHotkey(keyboard: string) {}});}++function capitalize(str: string) {+ return str.charAt(0).toUpperCase() + str.slice(1);+}diff --git a/frontend/src/components/sort/SortableCellsProvider.tsx b/frontend/src/components/sort/SortableCellsProvider.tsxindex 3a4c5203dd..70b81dac00 100644--- a/frontend/src/components/sort/SortableCellsProvider.tsx+++ b/frontend/src/components/sort/SortableCellsProvider.tsx@@ -32,7 +32,12 @@ const SortableCellsProviderInternal = ({const { dropCellOver } = useCellActions();const sensors = useSensors(- useSensor(PointerSensor),+ useSensor(PointerSensor, {+ activationConstraint: {+ // to support click and drag on the same element+ distance: 8,+ },+ }),useSensor(KeyboardSensor, {coordinateGetter: sortableKeyboardCoordinates,})diff --git a/frontend/src/components/ui/command.tsx b/frontend/src/components/ui/command.tsxindex 48271b81b2..5a504f67da 100644--- a/frontend/src/components/ui/command.tsx+++ b/frontend/src/components/ui/command.tsx@@ -124,7 +124,7 @@ const CommandItem = React.forwardRef<<CommandPrimitive.Itemref={ref}className={cn(- "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",+ "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-[var(--blue-3)] aria-selected:text-[var(--blue-12)]-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",className)}{...props}diff --git a/frontend/src/components/ui/dropdown-menu.tsx b/frontend/src/components/ui/dropdown-menu.tsxindex 2e1e34769c..aa0015ea0b 100644--- a/frontend/src/components/ui/dropdown-menu.tsx+++ b/frontend/src/components/ui/dropdown-menu.tsx@@ -82,7 +82,7 @@ const DropdownMenuItem = React.forwardRef<<DropdownMenuPrimitive.Itemref={ref}className={cn(- "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",+ "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-[var(--blue-3)] focus:text-[var(--blue-12)]-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",inset && "pl-8",className)}@@ -98,7 +98,7 @@ const DropdownMenuCheckboxItem = React.forwardRef<<DropdownMenuPrimitive.CheckboxItemref={ref}className={cn(- "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",+ "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-[var(--blue-3)] focus:text-[var(--blue-12)]-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",className)}checked={checked}diff --git a/frontend/src/core/mode.ts b/frontend/src/core/mode.tsindex 30ae9339be..9e73a3b546 100644--- a/frontend/src/core/mode.ts+++ b/frontend/src/core/mode.ts@@ -1,4 +1,9 @@/* Copyright 2023 Marimo. All rights reserved. */++import { atom } from "jotai";+import { CellId } from "./model/ids";+import { store } from "./state/jotai";+/*** This is the internal mode.* - `read`: A user is reading the notebook. Cannot switch to edit/present mode.@@ -33,3 +38,40 @@ export function toggleAppMode(mode: AppMode): AppMode {return mode === "edit" ? "present" : "edit";}++/**+ * View state for the app.+ */+interface ViewState {+ /**+ * The mode of the app: read/edit/present+ */+ mode: AppMode;+ /**+ * A cell ID to anchor scrolling to when toggling between presenting and+ * editing views+ */+ cellAnchor: CellId | null;+}++export const initialMode = getInitialAppMode();++export async function runDuringPresentMode(fn: () => void): Promise<void> {+ const state = store.get(viewStateAtom);+ if (state.mode === "present") {+ return fn();+ }++ store.set(viewStateAtom, { ...state, mode: "present" });+ // wait 2 frames+ await new Promise((resolve) => requestAnimationFrame(resolve));+ await new Promise((resolve) => requestAnimationFrame(resolve));+ fn();+ store.set(viewStateAtom, { ...state, mode: "edit" });+ return undefined;+}++export const viewStateAtom = atom<ViewState>({+ mode: initialMode,+ cellAnchor: null,+});diff --git a/frontend/src/core/state/cells.ts b/frontend/src/core/state/cells.tsindex 09147ef38f..4466767841 100644--- a/frontend/src/core/state/cells.ts+++ b/frontend/src/core/state/cells.ts@@ -141,6 +141,7 @@ function reducer(state: CellsAndHistory, action: CellAction): CellsAndHistory {cell,...state.present.slice(insertionIndex),],+ scrollKey: cell.key,};}case "MOVE_CELL": {diff --git a/frontend/src/css/common.css b/frontend/src/css/common.cssindex b13fc7d005..07cdd46416 100644--- a/frontend/src/css/common.css+++ b/frontend/src/css/common.css@@ -10,3 +10,29 @@.hover-actions-parent:hover .hover-action {display: inline-flex !important;}++/* If parent has any children that have an open pop, show hover actions */+.hover-actions-parent:has(button[aria-haspopup][data-state="open"])+ .hover-action {+ display: inline-flex !important;+}++/* Hide on print+To hide an element on print, add the class `no-print` to it.+When printing, the class `printing` is added to the body element to enable this rule. */+body.printing .no-print {+ visibility: hidden !important;+}++body.printing,+body.printing #root {+ /* Full screen print */+ height: 100% !important;+}++/* When printing the output of a cell, this unset the max-height set by the notebook to capture the full output */+.printing-output {+ max-height: none !important;++ @apply bg-background;+}diff --git a/frontend/src/css/globals.css b/frontend/src/css/globals.cssindex 1ffbaddfdf..a4f3986f2e 100644--- a/frontend/src/css/globals.css+++ b/frontend/src/css/globals.css@@ -16,6 +16,8 @@@import url("@radix-ui/colors/amber-dark.css");@import url("@radix-ui/colors/yellow.css");@import url("@radix-ui/colors/yellow-dark.css");+@import url("@radix-ui/colors/blue.css");+@import url("@radix-ui/colors/blue-dark.css");@tailwind base;@tailwind components;@@ -42,9 +44,9 @@/* tailwind blue-500 */--accent: 217 91% 60%;-/* white */--accent-foreground: 100 100% 100%;+--destructive: 0 100% 70%;--destructive-foreground: 210 40% 98%;--error: 0 77% 64%;diff --git a/frontend/src/editor/Cell.tsx b/frontend/src/editor/Cell.tsxindex f849c346b8..84f50f8e8d 100644--- a/frontend/src/editor/Cell.tsx+++ b/frontend/src/editor/Cell.tsx@@ -44,6 +44,7 @@ import { CellId, HTMLCellId } from "../core/model/ids";import { Theme } from "../theme/useTheme";import { HOTKEYS } from "@/core/hotkeys/hotkeys";import { keymapBundle } from "@/core/codemirror/keymaps/keymaps";+import { CellActions } from "./cell/cell-actions";/*** Imperative interface of the cell.@@ -579,7 +580,13 @@ const CellComponent = (status={status}needsRun={needsRun}/>- <CellDragHandle />+ <CellActions+ cellId={cellId}+ editorView={editorView.current}+ hasOutput={!!output}+ >+ <CellDragHandle />+ </CellActions></div></div><div className="shoulder-bottom hover-action">diff --git a/frontend/src/editor/CommandPallette.tsx b/frontend/src/editor/CommandPallette.tsxindex 33903cb890..eb0e06aad9 100644--- a/frontend/src/editor/CommandPallette.tsx+++ b/frontend/src/editor/CommandPallette.tsx@@ -15,9 +15,12 @@ import { useRecentCommands } from "../hooks/useRecentCommands";import { Kbd } from "../components/ui/kbd";import { prettyPrintHotkey } from "../components/shortcuts/renderShortcut";import { HOTKEYS, HotkeyAction } from "@/core/hotkeys/hotkeys";+import { atom, useAtom } from "jotai";++export const commandPalletteAtom = atom(false);export const CommandPallette = () => {- const [open, setOpen] = React.useState(false);+ const [open, setOpen] = useAtom(commandPalletteAtom);const registeredActions = useRegisteredActions();const { recentCommands, addRecentCommand } = useRecentCommands();@@ -30,7 +33,7 @@ export const CommandPallette = () => {};document.addEventListener("keydown", down);return () => document.removeEventListener("keydown", down);- }, []);+ }, [setOpen]);const renderShortcutCommandItemIfNotRecent = (shortcut: HotkeyAction) => {const isRecent = recentCommands.includes(shortcut);@@ -78,12 +81,14 @@ export const CommandPallette = () => {<CommandList><CommandEmpty>No results found.</CommandEmpty>{recentCommands.length > 0 && (- <CommandGroup heading="Recently Used">- {recentCommands.map((shortcut) =>- renderShortcutCommandItem(shortcut)- )}+ <>+ <CommandGroup heading="Recently Used">+ {recentCommands.map((shortcut) =>+ renderShortcutCommandItem(shortcut)+ )}+ </CommandGroup><CommandSeparator />- </CommandGroup>+ </>)}<CommandGroup heading="Commands">{HOTKEYS.iterate().map((shortcut) =>diff --git a/frontend/src/editor/Controls.styles.ts b/frontend/src/editor/Controls.styles.tsindex 32e596742b..2f9cf50ab4 100644--- a/frontend/src/editor/Controls.styles.ts+++ b/frontend/src/editor/Controls.styles.ts@@ -1,9 +1,9 @@/* Copyright 2023 Marimo. All rights reserved. */export const topRightControls =- "fixed top-3 right-3 m-0 flex items-center space-x-3";+ "fixed top-3 right-3 m-0 flex items-center space-x-3 no-print";export const bottomRightControls =- "fixed bottom-4 right-4 flex items-center space-x-3";+ "fixed bottom-4 right-4 flex items-center space-x-3 no-print";export const bottomLeftControls =- "fixed bottom-4 left-4 m-0 flex items-center space-x-3";+ "fixed bottom-4 left-4 m-0 flex items-center space-x-3 no-print";diff --git a/frontend/src/editor/Controls.tsx b/frontend/src/editor/Controls.tsxindex 80e0c8642a..3690370a1c 100644--- a/frontend/src/editor/Controls.tsx+++ b/frontend/src/editor/Controls.tsx@@ -19,6 +19,7 @@ import { renderShortcut } from "../components/shortcuts/renderShortcut";import { useCellActions } from "../core/state/cells";import { AppConfigButton } from "../components/app-config/app-config-button";import { useState, useEffect } from "react";+import { MenuDropdown } from "@/components/export/menu-dropdown";import { FindReplace } from "@/components/find-replace/find-replace";interface ControlsProps {@@ -82,6 +83,7 @@ export const Controls = ({{!closed && (<div className={styles.topRightControls}>+ <MenuDropdown filename={filename} /><AppConfigButton /><ShutdownButton onShutdown={onShutdown} /></div>diff --git a/frontend/src/editor/Output.tsx b/frontend/src/editor/Output.tsxindex 26736271fb..2dfa1aafaf 100644--- a/frontend/src/editor/Output.tsx+++ b/frontend/src/editor/Output.tsx@@ -11,6 +11,7 @@ import { MarimoErrorOutput } from "./output/MarimoErrorOutput";import { TextOutput } from "./output/TextOutput";import { VideoOutput } from "./output/VideoOutput";import { CellId } from "@/core/model/ids";+import { cn } from "@/lib/utils";/*** Renders an output based on an OutputMessage.@@ -82,10 +83,13 @@ export const OutputArea = React.memo(} else if (props.output.channel === "output" && props.output.data === "") {return null;} else {- const cls = `OutputArea${props.stale ? " marimo-output-stale" : ""}`;const title = props.stale ? "This output is stale" : undefined;return (- <div title={title} className={cls}>+ <div+ title={title}+ id={`output-${props.cellId}`}+ className={cn("OutputArea", props.stale && "marimo-output-stale")}+ >{formatOutput({message: props.output,parsedJsonData: parsedJsonData,diff --git a/frontend/src/editor/SortableCell.tsx b/frontend/src/editor/SortableCell.tsxindex 69b0f3b826..7820a7982e 100644--- a/frontend/src/editor/SortableCell.tsx+++ b/frontend/src/editor/SortableCell.tsx@@ -54,7 +54,7 @@ const SortableCellInternal = React.forwardRef({...attributes}{...listeners}data-testid="drag-button"- className="py-[1px] mx-2 cursor-grab opacity-50 hover:opacity-100 hover-action"+ className="py-[1px] mx-2 cursor-grab opacity-50 hover:opacity-100 hover-action hover:bg-muted rounded"><GripVerticalIcon strokeWidth={1} size={20} /></div>diff --git a/frontend/src/editor/cell/cell-actions.tsx b/frontend/src/editor/cell/cell-actions.tsxnew file mode 100644index 0000000000..812b4f0371--- /dev/null+++ b/frontend/src/editor/cell/cell-actions.tsx@@ -0,0 +1,252 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { PropsWithChildren, useState } from "react";++import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandSeparator,+} from "@/components/ui/command";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";+import {+ TooltipContent,+ TooltipRoot,+ TooltipTrigger,+} from "@/components/ui/tooltip";+import { useCellActions } from "@/core/state/cells";+import { CellId } from "@/core/model/ids";+import { MultiIcon } from "@/components/icons/multi-icon";+import {+ ChevronDownIcon,+ ChevronUpIcon,+ ChevronsDownIcon,+ ChevronsUpIcon,+ Code2Icon,+ FocusIcon,+ ImageIcon,+ PlusCircleIcon,+ Trash2Icon,+} from "lucide-react";+import { downloadCellOutput } from "@/components/export/export-output-button";+import { HotkeyAction } from "@/core/hotkeys/hotkeys";+import { EditorView } from "codemirror";+import { formatEditorViews } from "@/core/codemirror/format";+import { cn } from "@/lib/utils";+import { renderMinimalShortcut } from "@/components/shortcuts/renderShortcut";++interface Props {+ editorView: EditorView | null;+ hasOutput: boolean;+ cellId: CellId;+}++interface Action {+ label: string;+ variant?: "danger";+ hotkey?: HotkeyAction;+ icon?: React.ReactNode;+ hidden?: boolean;+ handle: () => void;+}++export const CellActions = ({+ cellId,+ children,+ hasOutput,+ editorView,+}: PropsWithChildren<Props>) => {+ const [open, setOpen] = useState(false);+ const {+ createNewCell,+ updateCellCode,+ deleteCell,+ focusCell,+ moveCell,+ sendToTop,+ sendToBottom,+ } = useCellActions();++ const actions: Action[][] = [+ // Actions+ [+ {+ icon: <ImageIcon size={13} strokeWidth={1.5} />,+ label: "Export to PNG",+ hidden: !hasOutput,+ handle: () => downloadCellOutput(cellId),+ },+ {+ icon: <Code2Icon size={13} strokeWidth={1.5} />,+ label: "Format cell",+ hotkey: "cell.format",+ handle: () => {+ if (!editorView) {+ return;+ }+ formatEditorViews({ [cellId]: editorView }, updateCellCode);+ },+ },+ ],++ // Movement+ [+ {+ icon: (+ <MultiIcon>+ <PlusCircleIcon size={13} strokeWidth={1.5} />+ <ChevronUpIcon size={12} strokeWidth={1.5} />+ </MultiIcon>+ ),+ label: "Create cell above",+ hotkey: "cell.createAbove",+ handle: () => createNewCell(cellId, /*before=*/ true),+ },+ {+ icon: (+ <MultiIcon>+ <PlusCircleIcon size={13} strokeWidth={1.5} />+ <ChevronDownIcon size={12} strokeWidth={1.5} />+ </MultiIcon>+ ),+ label: "Create cell below",+ hotkey: "cell.createBelow",+ handle: () => createNewCell(cellId, /*before=*/ false),+ },+ {+ icon: <ChevronUpIcon size={13} strokeWidth={1.5} />,+ label: "Move cell up",+ hotkey: "cell.moveUp",+ handle: () => moveCell(cellId, /*before=*/ true),+ },+ {+ icon: <ChevronDownIcon size={13} strokeWidth={1.5} />,+ label: "Move cell down",+ hotkey: "cell.moveDown",+ handle: () => moveCell(cellId, /*before=*/ false),+ },+ {+ icon: (+ <MultiIcon>+ <FocusIcon size={13} strokeWidth={1.5} />+ <ChevronUpIcon size={12} strokeWidth={1.5} />+ </MultiIcon>+ ),+ label: "Focus cell above",+ hotkey: "cell.focusUp",+ handle: () => focusCell(cellId, /*before=*/ true),+ },+ {+ icon: (+ <MultiIcon>+ <FocusIcon size={13} strokeWidth={1.5} />+ <ChevronDownIcon size={12} strokeWidth={1.5} />+ </MultiIcon>+ ),+ label: "Focus cell below",+ hotkey: "cell.focusDown",+ handle: () => focusCell(cellId, /*before=*/ false),+ },+ {+ icon: <ChevronsUpIcon size={13} strokeWidth={1.5} />,+ label: "Send to top",+ hotkey: "cell.sendToTop",+ handle: () => sendToTop(cellId),+ },+ {+ icon: <ChevronsDownIcon size={13} strokeWidth={1.5} />,+ label: "Send to bottom",+ hotkey: "cell.sendToBottom",+ handle: () => sendToBottom(cellId),+ },+ ],++ // Delete+ [+ {+ label: "Delete",+ variant: "danger",+ icon: <Trash2Icon size={13} strokeWidth={1.5} />,+ handle: () => deleteCell(cellId),+ },+ ],+ ];++ return (+ <Popover open={open} onOpenChange={setOpen}>+ <TooltipRoot delayDuration={400} disableHoverableContent={true}>+ {!open && (+ <TooltipContent className="w-full bg-card" tabIndex={-1}>+ <div className="text-foreground-muted flex flex-col text-center">+ <span>+ <span className="text-foreground font-semibold">Drag </span>to+ move cell+ </span>+ <span>+ <span className="text-foreground font-semibold">Click </span>to+ open menu+ </span>+ </div>+ </TooltipContent>+ )}+ <TooltipTrigger>+ <PopoverTrigger>{children}</PopoverTrigger>+ </TooltipTrigger>+ </TooltipRoot>+ <PopoverContent+ className="w-[300px] p-0 pt-1"+ onOpenAutoFocus={(e) => e.preventDefault()}+ >+ <Command>+ <CommandInput+ placeholder="Search actions..."+ className="h-6 m-1"+ autoFocus={true}+ />+ <CommandEmpty>No results</CommandEmpty>+ {actions.map((group, i) => (+ <>+ <CommandGroup key={i}>+ {group.map((action) => {+ if (action.hidden) {+ return null;+ }+ return (+ <CommandItem+ key={action.label}+ onSelect={() => {+ action.handle();+ setOpen(false);+ }}+ className={cn(+ action.variant === "danger" &&+ "aria-selected:bg-[var(--red-5)] aria-selected:text-destructive-[var(--red-11)]"+ )}+ >+ <div className="flex items-center flex-1">+ {action.icon && (+ <div className="mr-2 w-5">{action.icon}</div>+ )}+ <div className="flex-1">{action.label}</div>+ <div className="flex-shrink-0 text-sm">+ {action.hotkey &&+ renderMinimalShortcut(action.hotkey)}+ </div>+ </div>+ </CommandItem>+ );+ })}+ </CommandGroup>+ {i < actions.length - 1 && <CommandSeparator />}+ </>+ ))}+ </Command>+ </PopoverContent>+ </Popover>+ );+};diff --git a/frontend/src/editor/inputs/Inputs.styles.ts b/frontend/src/editor/inputs/Inputs.styles.tsindex 6fd4555a26..d01fa60859 100644--- a/frontend/src/editor/inputs/Inputs.styles.ts+++ b/frontend/src/editor/inputs/Inputs.styles.ts@@ -44,7 +44,7 @@ export const button = cva({size: "small",shape: "rectangle",- class: "px-2 py-1",+ class: "px-1 py-1 h-[24px] w-[24px]",},{size: "medium",diff --git a/frontend/src/main.tsx b/frontend/src/main.tsxindex efebea612e..9775c44729 100644--- a/frontend/src/main.tsx+++ b/frontend/src/main.tsx@@ -5,7 +5,6 @@ import { worker } from "./mocks/browser";import { ThemeProvider } from "./theme/ThemeProvider";import { ErrorBoundary } from "./editor/boundary/ErrorBoundary";import { MarimoApp } from "./MarimoApp";-import { getInitialAppMode } from "./core/mode";import { Logger } from "./utils/Logger";import { reportVitals } from "./utils/vitals";import { Provider } from "jotai";@@ -34,12 +33,11 @@ if (import.meta.env.DEV && import.meta.env.VITE_MSW) {const root = ReactDOM.createRoot(document.getElementById("root")!);try {- const initialMode = getInitialAppMode();root.render(<React.StrictMode><Provider store={store}><ThemeProvider>- <MarimoApp initialMode={initialMode} />+ <MarimoApp /></ThemeProvider></Provider></React.StrictMode>diff --git a/frontend/src/utils/download.ts b/frontend/src/utils/download.tsnew file mode 100644index 0000000000..8b43173bc6--- /dev/null+++ b/frontend/src/utils/download.ts@@ -0,0 +1,31 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { toPng } from "html-to-image";+import { toast } from "@/components/ui/use-toast";++export async function downloadHTMLAsImage(+ element: HTMLElement,+ filename: string+) {+ try {+ // Add classnames for printing+ document.body.classList.add("printing");+ // Get screenshot+ const dataUrl = await toPng(element);+ // Create an anchor element+ const a = document.createElement("a");+ // Create a PNG image from the canvas+ a.href = dataUrl;+ a.download = filename.endsWith(".png") ? filename : `${filename}.png`;+ // Download the image+ a.click();+ } catch {+ toast({+ title: "Error",+ description: "Failed to export as PNG.",+ variant: "destructive",+ });+ } finally {+ // Remove classnames for printing+ document.body.classList.remove("printing");+ }+}