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: context menu (#127)
Myles Scolnickdabd2a7f265e
diff --git a/frontend/package.json b/frontend/package.jsonindex ae2a1603ac..b5f6d909bf 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -34,6 +34,7 @@"@radix-ui/react-accordion": "^1.1.2","@radix-ui/react-alert-dialog": "^1.0.4","@radix-ui/react-checkbox": "^1.0.4",+ "@radix-ui/react-context-menu": "^2.1.4","@radix-ui/react-dialog": "^1.0.4","@radix-ui/react-dropdown-menu": "^2.0.5","@radix-ui/react-icons": "^1.3.0",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex fe1fd185cb..ae505c6d58 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -74,6 +74,9 @@ dependencies:'@radix-ui/react-checkbox':specifier: ^1.0.4version: 1.0.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-context-menu':+ specifier: ^2.1.4+ version: 2.1.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@radix-ui/react-dialog':specifier: ^1.0.4version: 1.0.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])@@ -3097,6 +3100,32 @@ packages:'@types/react': 18.2.21react: 18.2.0+ /@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected])([email protected]):+ resolution: {integrity: sha512-HVHLUtZOBiR2Fh5l07qQ9y0IgX4dGZF0S9Gwdk4CVA+DL9afSphvFNa4nRiw6RNgb6quwLV4dLPF/gFDvNaOcQ==}+ peerDependencies:+ '@types/react': '*'+ '@types/react-dom': '*'+ react: ^16.8 || ^17.0 || ^18.0+ react-dom: ^16.8 || ^17.0 || ^18.0+ peerDependenciesMeta:+ '@types/react':+ optional: true+ '@types/react-dom':+ optional: true+ dependencies:+ '@babel/runtime': 7.22.5+ '@radix-ui/primitive': 1.0.1+ '@radix-ui/react-context': 1.0.1(@types/[email protected])([email protected])+ '@radix-ui/react-menu': 2.0.5(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-primitive': 1.0.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-use-callback-ref': 1.0.1(@types/[email protected])([email protected])+ '@radix-ui/react-use-controllable-state': 1.0.1(@types/[email protected])([email protected])+ '@types/react': 18.2.21+ '@types/react-dom': 18.2.7+ react: 18.2.0+ react-dom: 18.2.0([email protected])+ dev: false+/@radix-ui/[email protected]([email protected]):resolution: {integrity: sha512-1pVM9RfOQ+n/N5PJK33kRSKsr1glNxomxONs5c49MliinBY6Yw2Q995qfBUUo0/Mbg05B/sGA0gkgPI7kmSHBg==}peerDependencies:diff --git a/frontend/src/components/ui/command.tsx b/frontend/src/components/ui/command.tsxindex 99ef52dcc0..dd10c3e9a1 100644--- a/frontend/src/components/ui/command.tsx+++ b/frontend/src/components/ui/command.tsx@@ -6,6 +6,12 @@ import { Search } from "lucide-react";import { cn } from "@/lib/utils";import { Dialog, DialogContent } from "@/components/ui/dialog";+import {+ MenuShortcut,+ menuItemVariants,+ menuSeparatorVariants,+} from "./menu-items";+import { VariantProps } from "class-variance-authority";const Command = React.forwardRef<React.ElementRef<typeof CommandPrimitive>,@@ -111,7 +117,7 @@ const CommandSeparator = React.forwardRef<>(({ className, ...props }, ref) => (<CommandPrimitive.Separatorref={ref}- className={cn("-mx-1 h-px bg-border", className)}+ className={menuSeparatorVariants({ className })}{...props}/>));@@ -119,35 +125,19 @@ CommandSeparator.displayName = CommandPrimitive.Separator.displayName;const CommandItem = React.forwardRef<React.ElementRef<typeof CommandPrimitive.Item>,- React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>->(({ className, ...props }, ref) => (+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item> &+ VariantProps<typeof menuItemVariants>+>(({ className, variant, inset, ...props }, ref) => (<CommandPrimitive.Itemref={ref}- className={cn(- "menu-item 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",- className- )}+ className={menuItemVariants({ className, variant, inset })}{...props}/>));CommandItem.displayName = CommandPrimitive.Item.displayName;-const CommandShortcut = ({- className,- ...props-}: React.HTMLAttributes<HTMLSpanElement>) => {- return (- <span- className={cn(- "ml-auto text-xs tracking-widest text-muted-foreground",- className- )}- {...props}- />- );-};-CommandShortcut.displayName = "CommandShortcut";+const CommandShortcut = MenuShortcut;export {Command,diff --git a/frontend/src/components/ui/context-menu.tsx b/frontend/src/components/ui/context-menu.tsxnew file mode 100644index 0000000000..cff3f49b8d--- /dev/null+++ b/frontend/src/components/ui/context-menu.tsx@@ -0,0 +1,176 @@+/* Copyright 2023 Marimo. All rights reserved. */+import * as React from "react";+import * as ContextMenuPrimitive from "@radix-ui/react-context-menu";+import {+ CheckIcon,+ ChevronRightIcon,+ DotFilledIcon,+} from "@radix-ui/react-icons";++import { cn } from "@/lib/utils";+import {+ MenuShortcut,+ menuContentCommon,+ menuControlCheckVariants,+ menuItemVariants,+ menuLabelVariants,+ menuSeparatorVariants,+ menuSubTriggerVariants,+} from "./menu-items";+import { VariantProps } from "class-variance-authority";++const ContextMenu = ContextMenuPrimitive.Root;+const ContextMenuTrigger = ContextMenuPrimitive.Trigger;+const ContextMenuGroup = ContextMenuPrimitive.Group;+const ContextMenuPortal = ContextMenuPrimitive.Portal;+const ContextMenuSub = ContextMenuPrimitive.Sub;+const ContextMenuRadioGroup = ContextMenuPrimitive.RadioGroup;++const ContextMenuSubTrigger = React.forwardRef<+ React.ElementRef<typeof ContextMenuPrimitive.SubTrigger>,+ React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubTrigger> & {+ inset?: boolean;+ }+>(({ className, inset, children, ...props }, ref) => (+ <ContextMenuPrimitive.SubTrigger+ ref={ref}+ className={menuSubTriggerVariants({ className, inset })}+ {...props}+ >+ {children}+ <ChevronRightIcon className="ml-auto h-4 w-4" />+ </ContextMenuPrimitive.SubTrigger>+));+ContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName;++const contentCommon =+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2";++const ContextMenuSubContent = React.forwardRef<+ React.ElementRef<typeof ContextMenuPrimitive.SubContent>,+ React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubContent>+>(({ className, ...props }, ref) => (+ <ContextMenuPrimitive.SubContent+ ref={ref}+ className={cn(+ menuContentCommon({ subcontent: true }),+ contentCommon,+ className+ )}+ {...props}+ />+));+ContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName;++const ContextMenuContent = React.forwardRef<+ React.ElementRef<typeof ContextMenuPrimitive.Content>,+ React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Content>+>(({ className, ...props }, ref) => (+ <ContextMenuPrimitive.Portal>+ <ContextMenuPrimitive.Content+ ref={ref}+ className={cn(menuContentCommon(), contentCommon, className)}+ {...props}+ />+ </ContextMenuPrimitive.Portal>+));+ContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName;++const ContextMenuItem = React.forwardRef<+ React.ElementRef<typeof ContextMenuPrimitive.Item>,+ React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Item> &+ VariantProps<typeof menuItemVariants>+>(({ className, inset, variant, ...props }, ref) => (+ <ContextMenuPrimitive.Item+ ref={ref}+ className={menuItemVariants({ className, inset, variant })}+ {...props}+ />+));+ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName;++const ContextMenuCheckboxItem = React.forwardRef<+ React.ElementRef<typeof ContextMenuPrimitive.CheckboxItem>,+ React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.CheckboxItem>+>(({ className, children, checked, ...props }, ref) => (+ <ContextMenuPrimitive.CheckboxItem+ ref={ref}+ className={menuControlCheckVariants({ className })}+ checked={checked}+ {...props}+ >+ <span className={menuControlCheckVariants()}>+ <ContextMenuPrimitive.ItemIndicator>+ <CheckIcon className="h-4 w-4" />+ </ContextMenuPrimitive.ItemIndicator>+ </span>+ {children}+ </ContextMenuPrimitive.CheckboxItem>+));+ContextMenuCheckboxItem.displayName =+ ContextMenuPrimitive.CheckboxItem.displayName;++const ContextMenuRadioItem = React.forwardRef<+ React.ElementRef<typeof ContextMenuPrimitive.RadioItem>,+ React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.RadioItem>+>(({ className, children, ...props }, ref) => (+ <ContextMenuPrimitive.RadioItem+ ref={ref}+ className={menuControlCheckVariants({ className })}+ {...props}+ >+ <span className={menuControlCheckVariants()}>+ <ContextMenuPrimitive.ItemIndicator>+ <DotFilledIcon className="h-4 w-4 fill-current" />+ </ContextMenuPrimitive.ItemIndicator>+ </span>+ {children}+ </ContextMenuPrimitive.RadioItem>+));+ContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName;++const ContextMenuLabel = React.forwardRef<+ React.ElementRef<typeof ContextMenuPrimitive.Label>,+ React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Label> & {+ inset?: boolean;+ }+>(({ className, inset, ...props }, ref) => (+ <ContextMenuPrimitive.Label+ ref={ref}+ className={menuLabelVariants({ className, inset })}+ {...props}+ />+));+ContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName;++const ContextMenuSeparator = React.forwardRef<+ React.ElementRef<typeof ContextMenuPrimitive.Separator>,+ React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Separator>+>(({ className, ...props }, ref) => (+ <ContextMenuPrimitive.Separator+ ref={ref}+ className={cn("my-1", menuSeparatorVariants({ className }))}+ {...props}+ />+));+ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName;++const ContextMenuShortcut = MenuShortcut;++export {+ ContextMenu,+ ContextMenuTrigger,+ ContextMenuContent,+ ContextMenuItem,+ ContextMenuCheckboxItem,+ ContextMenuRadioItem,+ ContextMenuLabel,+ ContextMenuSeparator,+ ContextMenuShortcut,+ ContextMenuGroup,+ ContextMenuPortal,+ ContextMenuSub,+ ContextMenuSubContent,+ ContextMenuSubTrigger,+ ContextMenuRadioGroup,+};diff --git a/frontend/src/components/ui/dropdown-menu.tsx b/frontend/src/components/ui/dropdown-menu.tsxindex 28ab3d10a2..6bd6f67935 100644--- a/frontend/src/components/ui/dropdown-menu.tsx+++ b/frontend/src/components/ui/dropdown-menu.tsx@@ -1,20 +1,24 @@/* Copyright 2023 Marimo. All rights reserved. */-import * as React from "react";import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";-import { Check, ChevronRight, Circle } from "lucide-react";-+import {+ MenuShortcut,+ menuContentCommon,+ menuControlCheckVariants,+ menuControlVariants,+ menuItemVariants,+ menuLabelVariants,+ menuSeparatorVariants,+ menuSubTriggerVariants,+} from "./menu-items";import { cn } from "@/lib/utils";+import React from "react";+import { Check, ChevronRight, Circle } from "lucide-react";const DropdownMenu = DropdownMenuPrimitive.Root;-const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;-const DropdownMenuGroup = DropdownMenuPrimitive.Group;-const DropdownMenuPortal = DropdownMenuPrimitive.Portal;-const DropdownMenuSub = DropdownMenuPrimitive.Sub;-const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;const DropdownMenuSubTrigger = React.forwardRef<@@ -25,11 +29,7 @@ const DropdownMenuSubTrigger = React.forwardRef<>(({ className, inset, children, ...props }, ref) => (<DropdownMenuPrimitive.SubTriggerref={ref}- className={cn(- "flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",- inset && "pl-8",- className- )}+ className={menuSubTriggerVariants({ className, inset })}{...props}>{children}@@ -46,7 +46,8 @@ const DropdownMenuSubContent = React.forwardRef<<DropdownMenuPrimitive.SubContentref={ref}className={cn(- "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in data-[side=bottom]:slide-in-from-top-1 data-[side=left]:slide-in-from-right-1 data-[side=right]:slide-in-from-left-1 data-[side=top]:slide-in-from-bottom-1",+ menuContentCommon({ subcontent: true }),+ "animate-in data-[side=bottom]:slide-in-from-top-1 data-[side=left]:slide-in-from-right-1 data-[side=right]:slide-in-from-left-1 data-[side=top]:slide-in-from-bottom-1",className)}{...props}@@ -64,7 +65,8 @@ const DropdownMenuContent = React.forwardRef<ref={ref}sideOffset={sideOffset}className={cn(- "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",+ menuContentCommon(),+ "animate-in data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",className)}{...props}@@ -81,11 +83,7 @@ const DropdownMenuItem = React.forwardRef<>(({ className, inset, ...props }, ref) => (<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",- inset && "pl-8",- className- )}+ className={menuItemVariants({ className, inset })}{...props}/>));@@ -97,14 +95,11 @@ const DropdownMenuCheckboxItem = React.forwardRef<>(({ className, children, checked, ...props }, ref) => (<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",- className- )}+ className={menuControlVariants({ className })}checked={checked}{...props}>- <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">+ <span className={menuControlCheckVariants()}><DropdownMenuPrimitive.ItemIndicator><Check className="h-4 w-4" /></DropdownMenuPrimitive.ItemIndicator>@@ -121,13 +116,10 @@ const DropdownMenuRadioItem = React.forwardRef<>(({ className, children, ...props }, ref) => (<DropdownMenuPrimitive.RadioItemref={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-primary focus:text-primary-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",- className- )}+ className={menuControlVariants({ className })}{...props}>- <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">+ <span className={menuControlCheckVariants()}><DropdownMenuPrimitive.ItemIndicator><Circle className="h-2 w-2 fill-current" /></DropdownMenuPrimitive.ItemIndicator>@@ -145,11 +137,7 @@ const DropdownMenuLabel = React.forwardRef<>(({ className, inset, ...props }, ref) => (<DropdownMenuPrimitive.Labelref={ref}- className={cn(- "px-2 py-1.5 text-sm font-semibold",- inset && "pl-8",- className- )}+ className={menuLabelVariants({ className, inset })}{...props}/>));@@ -161,24 +149,13 @@ const DropdownMenuSeparator = React.forwardRef<>(({ className, ...props }, ref) => (<DropdownMenuPrimitive.Separatorref={ref}- className={cn("-mx-1 my-1 h-px bg-muted", className)}+ className={menuSeparatorVariants({ className })}{...props}/>));DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;-const DropdownMenuShortcut = ({- className,- ...props-}: React.HTMLAttributes<HTMLSpanElement>) => {- return (- <span- className={cn("ml-auto text-xs tracking-widest opacity-60", className)}- {...props}- />- );-};-DropdownMenuShortcut.displayName = "DropdownMenuShortcut";+const DropdownMenuShortcut = MenuShortcut;export {DropdownMenu,diff --git a/frontend/src/components/ui/menu-items.tsx b/frontend/src/components/ui/menu-items.tsxnew file mode 100644index 0000000000..7cbfebe332--- /dev/null+++ b/frontend/src/components/ui/menu-items.tsx@@ -0,0 +1,81 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { cn } from "@/lib/utils";+import { cva } from "class-variance-authority";+import React from "react";++export const menuContentCommon = cva(+ "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",+ {+ variants: {+ subcontent: {+ true: "shadow-lg",+ },+ },+ }+);++export const menuSubTriggerVariants = cva(+ "flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",+ {+ variants: {+ inset: {+ true: "pl-8",+ },+ },+ }+);++export const menuControlVariants = cva(+ "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",+ { variants: {} }+);++export const menuControlCheckVariants = cva(+ "absolute left-2 flex h-3.5 w-3.5 items-center justify-center",+ { variants: {} }+);++export const menuLabelVariants = cva("px-2 py-1.5 text-sm font-semibold", {+ variants: {+ inset: {+ true: "pl-8",+ },+ },+});++export const menuItemVariants = cva(+ "menu-item relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50",+ {+ variants: {+ inset: {+ true: "pl-8",+ },+ variant: {+ default:+ "focus:bg-accent focus:text-accent-foreground aria-selected:bg-accent aria-selected:text-accent-foreground",+ danger:+ "focus:bg-[var(--red-5)] focus:text-[var(--red-12)] aria-selected:bg-[var(--red-5)] aria-selected:text-[var(--red-12)]",+ },+ },+ defaultVariants: {+ variant: "default",+ },+ }+);++export const menuSeparatorVariants = cva("-mx-1 h-px bg-border", {+ variants: {},+});++export const MenuShortcut = ({+ className,+ ...props+}: React.HTMLAttributes<HTMLSpanElement>) => {+ return (+ <span+ className={cn("ml-auto text-xs tracking-widest opacity-60", className)}+ {...props}+ />+ );+};+MenuShortcut.displayName = "MenuShortcut";diff --git a/frontend/src/core/vscode/vscode-bindings.ts b/frontend/src/core/vscode/vscode-bindings.tsindex 568eb9eddc..30ff88a978 100644--- a/frontend/src/core/vscode/vscode-bindings.ts+++ b/frontend/src/core/vscode/vscode-bindings.ts@@ -2,8 +2,9 @@import { Logger } from "@/utils/Logger";-// eslint-disable-next-line ssr-friendly/no-dom-globals-in-module-scope-const isEmbedded = typeof window !== "undefined" && window.parent !== window;+export const isEmbedded =+ // eslint-disable-next-line ssr-friendly/no-dom-globals-in-module-scope+ typeof window !== "undefined" && window.parent !== window;// To enable keyboard shortcuts of VS Code when the iframe is focused,// we have to dispatch keyboard events in the parent window.diff --git a/frontend/src/editor/Cell.tsx b/frontend/src/editor/Cell.tsxindex 7708ca3731..57cd9c9d0c 100644--- a/frontend/src/editor/Cell.tsx+++ b/frontend/src/editor/Cell.tsx@@ -38,6 +38,7 @@ import { CellDragHandle, SortableCell } from "./SortableCell";import { CellId, HTMLCellId } from "../core/model/ids";import { Theme } from "../theme/useTheme";import { CellActionsDropdown } from "./cell/cell-actions";+import { CellActionsContextMenu } from "./cell/cell-context-menu";/*** Imperative interface of the cell.@@ -416,85 +417,93 @@ const CellComponent = (const editor = <div className="cm" ref={editorViewParentRef} />;return (- <SortableCell- tabIndex={-1}- id={HTMLId}- ref={cellRef}- className={className}- data-status={status}- onBlur={closeCompletionHandler}- onKeyDown={resumeCompletionHandler}+ <CellActionsContextMenucellId={cellId}- title={cellTitle()}+ config={cellConfig}+ editorView={editorView.current}+ hasOutput={!!output}>- {outputArea}- <div className="tray">- <div className="shoulder-left hover-action">- <div className="shoulder-elem-top">- <CreateCellButton- tooltipContent={renderShortcut("cell.createAbove")}- appClosed={appClosed}- onClick={appClosed ? undefined : createAbove}- />- </div>- <div className="shoulder-elem-bottom">- <CreateCellButton- tooltipContent={renderShortcut("cell.createBelow")}- appClosed={appClosed}- onClick={appClosed ? undefined : createBelow}- />+ <SortableCell+ tabIndex={-1}+ id={HTMLId}+ ref={cellRef}+ className={className}+ data-status={status}+ onBlur={closeCompletionHandler}+ onKeyDown={resumeCompletionHandler}+ cellId={cellId}+ title={cellTitle()}+ >+ {outputArea}+ <div className="tray">+ <div className="shoulder-left hover-action">+ <div className="shoulder-elem-top">+ <CreateCellButton+ tooltipContent={renderShortcut("cell.createAbove")}+ appClosed={appClosed}+ onClick={appClosed ? undefined : createAbove}+ />+ </div>+ <div className="shoulder-elem-bottom">+ <CreateCellButton+ tooltipContent={renderShortcut("cell.createBelow")}+ appClosed={appClosed}+ onClick={appClosed ? undefined : createBelow}+ />+ </div></div>- </div>- {editor}- <div className="shoulder-right">- <CellStatusComponent- status={status}- interrupted={interrupted}- editing={editing}- edited={edited}- disabled={cellConfig.disabled ?? false}- elapsedTime={runElapsedTimeMs}- />- <div className="flex align-bottom">- <RunButton- edited={edited}- onClick={appClosed ? Functions.NOOP : onRun}- appClosed={appClosed}+ {editor}+ <div className="shoulder-right">+ <CellStatusComponentstatus={status}- config={cellConfig}- needsRun={needsRun}+ interrupted={interrupted}+ editing={editing}+ edited={edited}+ disabled={cellConfig.disabled ?? false}+ elapsedTime={runElapsedTimeMs}/>- <CellActionsDropdown- cellId={cellId}- editorView={editorView.current}- config={cellConfig}- hasOutput={!!output}- >- <CellDragHandle />- </CellActionsDropdown>+ <div className="flex align-bottom">+ <RunButton+ edited={edited}+ onClick={appClosed ? Functions.NOOP : onRun}+ appClosed={appClosed}+ status={status}+ config={cellConfig}+ needsRun={needsRun}+ />+ <CellActionsDropdown+ cellId={cellId}+ editorView={editorView.current}+ config={cellConfig}+ hasOutput={!!output}+ >+ <CellDragHandle />+ </CellActionsDropdown>+ </div>+ </div>+ <div className="shoulder-bottom hover-action">+ {showDeleteButton ? (+ <DeleteButton+ appClosed={appClosed}+ status={status}+ onClick={() => {+ if (!loading && !appClosed) {+ deleteCell({ cellId });+ }+ }}+ />+ ) : null}</div></div>- <div className="shoulder-bottom hover-action">- {showDeleteButton ? (- <DeleteButton- appClosed={appClosed}- status={status}- onClick={() => {- if (!loading && !appClosed) {- deleteCell({ cellId });- }- }}- />- ) : null}- </div>- </div>- <ConsoleOutput- consoleOutputs={consoleOutputs}- stale={- (status === "queued" || edited || status === "stale") && !interrupted- }- />- </SortableCell>+ <ConsoleOutput+ consoleOutputs={consoleOutputs}+ stale={+ (status === "queued" || edited || status === "stale") &&+ !interrupted+ }+ />+ </SortableCell>+ </CellActionsContextMenu>);};diff --git a/frontend/src/editor/actions/types.ts b/frontend/src/editor/actions/types.tsnew file mode 100644index 0000000000..595cd19d13--- /dev/null+++ b/frontend/src/editor/actions/types.ts@@ -0,0 +1,16 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { HotkeyAction } from "@/core/hotkeys/hotkeys";++/**+ * Shared interface to render a user action in the editor.+ * This can be in a dropdown menu, context menu, or toolbar.+ */+export interface ActionButton {+ label: string;+ variant?: "danger";+ hotkey?: HotkeyAction;+ icon?: React.ReactNode;+ hidden?: boolean;+ rightElement?: React.ReactNode;+ handle: () => void;+}diff --git a/frontend/src/editor/actions/useCellActionButton.tsx b/frontend/src/editor/actions/useCellActionButton.tsxnew file mode 100644index 0000000000..5da95692e3--- /dev/null+++ b/frontend/src/editor/actions/useCellActionButton.tsx@@ -0,0 +1,160 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { downloadCellOutput } from "@/components/export/export-output-button";+import { Switch } from "@/components/ui/switch";+import { formatEditorViews } from "@/core/codemirror/format";+import { useCellActions } from "@/core/state/cells";+import {+ ImageIcon,+ Code2Icon,+ ZapIcon,+ PlusCircleIcon,+ ChevronUpIcon,+ ChevronDownIcon,+ ChevronsUpIcon,+ ChevronsDownIcon,+ Trash2Icon,+ ZapOffIcon,+} from "lucide-react";+import { ActionButton } from "./types";+import { MultiIcon } from "@/components/icons/multi-icon";+import { CellConfig } from "@/core/model/cells";+import { EditorView } from "codemirror";+import { CellId } from "@/core/model/ids";+import { saveCellConfig } from "@/core/network/requests";++export interface CellActionButtonProps {+ cellId: CellId;+ config: CellConfig;+ editorView: EditorView | null;+ hasOutput: boolean;+}++export function useCellActionButtons({+ cellId,+ config,+ editorView,+ hasOutput,+}: CellActionButtonProps) {+ const {+ createNewCell: createCell,+ updateCellConfig,+ updateCellCode,+ deleteCell,+ moveCell,+ sendToTop,+ sendToBottom,+ } = useCellActions();+ const toggleDisabled = async () => {+ if (config.disabled) {+ await saveCellConfig({ configs: { [cellId]: { disabled: false } } });+ updateCellConfig({ cellId, config: { disabled: false } });+ } else {+ await saveCellConfig({ configs: { [cellId]: { disabled: true } } });+ updateCellConfig({ cellId, config: { disabled: true } });+ }+ };++ // Actions+ const actions: ActionButton[][] = [+ [+ {+ 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);+ },+ },+ {+ icon: config.disabled ? (+ <ZapIcon size={13} strokeWidth={1.5} />+ ) : (+ <ZapOffIcon size={13} strokeWidth={1.5} />+ ),+ label: config.disabled === true ? "Enable cell" : "Disable cell",+ rightElement: (+ <Switch+ checked={!config.disabled}+ size="sm"+ onCheckedChange={toggleDisabled}+ />+ ),+ handle: toggleDisabled,+ },+ ],++ // Movement+ [+ {+ icon: (+ <MultiIcon>+ <PlusCircleIcon size={13} strokeWidth={1.5} />+ <ChevronUpIcon size={8} strokeWidth={2} />+ </MultiIcon>+ ),+ label: "Create cell above",+ hotkey: "cell.createAbove",+ handle: () => createCell({ cellId, before: true }),+ },+ {+ icon: (+ <MultiIcon>+ <PlusCircleIcon size={13} strokeWidth={1.5} />+ <ChevronDownIcon size={8} strokeWidth={2} />+ </MultiIcon>+ ),+ label: "Create cell below",+ hotkey: "cell.createBelow",+ handle: () => createCell({ 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: <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 }),+ },+ ],+ ];++ // remove hidden+ return actions+ .map((group) => group.filter((action) => !action.hidden))+ .filter((group) => group.length > 0);+}diff --git a/frontend/src/editor/actions/useNotebookActions.tsx b/frontend/src/editor/actions/useNotebookActions.tsxindex 140a1191f2..8ce6ce0eec 100644--- a/frontend/src/editor/actions/useNotebookActions.tsx+++ b/frontend/src/editor/actions/useNotebookActions.tsx@@ -1,21 +1,19 @@/* Copyright 2023 Marimo. All rights reserved. */-import { HotkeyAction } from "@/core/hotkeys/hotkeys";import { runDuringPresentMode } from "@/core/mode";import { downloadHTMLAsImage } from "@/utils/download";import { useSetAtom } from "jotai";-import { ImageIcon, CommandIcon, ZapIcon, ZapOffIcon } from "lucide-react";+import {+ ImageIcon,+ CommandIcon,+ ZapIcon,+ ZapOffIcon,+ BookMarkedIcon,+} from "lucide-react";import { commandPalletteAtom } from "../CommandPallette";import { useCellActions, useCells } from "@/core/state/cells";import { saveCellConfig } from "@/core/network/requests";import { Objects } from "@/utils/objects";--interface Action {- label: string;- hotkey?: HotkeyAction;- icon?: React.ReactNode;- hidden?: boolean;- handle: () => void;-}+import { ActionButton } from "./types";export function useNotebookActions(opts: { filename?: string | null }) {const { filename } = opts;@@ -27,10 +25,9 @@ export function useNotebookActions(opts: { filename?: string | null }) {const disabledCells = cells.present.filter((cell) => cell.config.disabled);const enabledCells = cells.present.filter((cell) => !cell.config.disabled);- const actions: Action[] = [- // TODO(akshayka): Add these to the command palette+ const actions: ActionButton[] = [{- icon: <ImageIcon size={13} strokeWidth={1.5} />,+ icon: <ImageIcon size={14} strokeWidth={1.5} />,label: "Export to PNG",handle: async () => {await runDuringPresentMode(() => {@@ -39,7 +36,7 @@ export function useNotebookActions(opts: { filename?: string | null }) {},},{- icon: <ZapIcon size={13} strokeWidth={1.5} />,+ icon: <ZapIcon size={14} strokeWidth={1.5} />,label: "Enable all cells",hidden: disabledCells.length === 0,handle: async () => {@@ -56,7 +53,7 @@ export function useNotebookActions(opts: { filename?: string | null }) {},},{- icon: <ZapOffIcon size={13} strokeWidth={1.5} />,+ icon: <ZapOffIcon size={14} strokeWidth={1.5} />,label: "Disable all cells",hidden: enabledCells.length === 0,handle: async () => {@@ -74,11 +71,19 @@ export function useNotebookActions(opts: { filename?: string | null }) {},{- icon: <CommandIcon size={13} strokeWidth={1.5} />,- label: "Command Palette",+ icon: <CommandIcon size={14} strokeWidth={1.5} />,+ label: "Command palette",hotkey: "global.commandPalette",handle: () => setCommandPalletteOpen((open) => !open),},++ {+ icon: <BookMarkedIcon size={14} strokeWidth={1.5} />,+ label: "Open documentation",+ handle: () => {+ window.open("https://docs.marimo.io", "_blank");+ },+ },];return actions.filter((a) => !a.hidden);diff --git a/frontend/src/editor/cell/cell-actions.tsx b/frontend/src/editor/cell/cell-actions.tsxindex eadfe83663..a134e0d5b0 100644--- a/frontend/src/editor/cell/cell-actions.tsx+++ b/frontend/src/editor/cell/cell-actions.tsx@@ -1,5 +1,5 @@/* Copyright 2023 Marimo. All rights reserved. */-import { Fragment, PropsWithChildren, useState } from "react";+import { Fragment, useState } from "react";import {Command,@@ -19,32 +19,15 @@ import {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,- ZapIcon,- ZapOffIcon,-} 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";-import { CellConfig } from "@/core/model/cells";-import { Switch } from "@/components/ui/switch";import React from "react";-import { saveCellConfig } from "@/core/network/requests";+import {+ CellActionButtonProps,+ useCellActionButtons,+} from "../actions/useCellActionButton";+import { CellConfig } from "@/core/model/cells";+import { CellId } from "@/core/model/ids";+import { EditorView } from "codemirror";interface Props {editorView: EditorView | null;@@ -53,164 +36,13 @@ interface Props {config: CellConfig;}-interface Action {- label: string;- variant?: "danger";- hotkey?: HotkeyAction;- icon?: React.ReactNode;- hidden?: boolean;- rightElement?: React.ReactNode;- handle: () => void;+interface Props extends CellActionButtonProps {+ children: React.ReactNode;}-export const CellActionsDropdown = ({- cellId,- children,- hasOutput,- editorView,- config,-}: PropsWithChildren<Props>) => {+export const CellActionsDropdown = ({ children, ...props }: Props) => {const [open, setOpen] = useState(false);- const {- createNewCell: createCell,- updateCellConfig,- updateCellCode,- deleteCell,- focusCell,- moveCell,- sendToTop,- sendToBottom,- } = useCellActions();- const toggleDisabled = async () => {- if (config.disabled) {- await saveCellConfig({ configs: { [cellId]: { disabled: false } } });- updateCellConfig({ cellId, config: { disabled: false } });- } else {- await saveCellConfig({ configs: { [cellId]: { disabled: true } } });- updateCellConfig({ cellId, config: { disabled: true } });- }- };-- 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);- },- },- {- icon: config.disabled ? (- <ZapIcon size={13} strokeWidth={1.5} />- ) : (- <ZapOffIcon size={13} strokeWidth={1.5} />- ),- label: config.disabled === true ? "Enable cell" : "Disable cell",- rightElement: (- <Switch- checked={!config.disabled}- size="sm"- onCheckedChange={toggleDisabled}- />- ),- handle: toggleDisabled,- },- ],-- // Movement- [- {- icon: (- <MultiIcon>- <PlusCircleIcon size={13} strokeWidth={1.5} />- <ChevronUpIcon size={8} strokeWidth={2} />- </MultiIcon>- ),- label: "Create cell above",- hotkey: "cell.createAbove",- handle: () => createCell({ cellId, before: true }),- },- {- icon: (- <MultiIcon>- <PlusCircleIcon size={13} strokeWidth={1.5} />- <ChevronDownIcon size={8} strokeWidth={2} />- </MultiIcon>- ),- label: "Create cell below",- hotkey: "cell.createBelow",- handle: () => createCell({ 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={8} strokeWidth={2} />- </MultiIcon>- ),- label: "Focus cell above",- hotkey: "cell.focusUp",- handle: () => focusCell({ cellId, before: true }),- },- {- icon: (- <MultiIcon>- <FocusIcon size={13} strokeWidth={1.5} />- <ChevronDownIcon size={8} strokeWidth={2} />- </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 }),- },- ],- ];+ const actions = useCellActionButtons(props);return (<Popover open={open} onOpenChange={setOpen}>@@ -249,9 +81,6 @@ export const CellActionsDropdown = ({<Fragment key={i}><CommandGroup key={i}>{group.map((action) => {- if (action.hidden) {- return null;- }return (<CommandItemkey={action.label}@@ -259,10 +88,7 @@ export const CellActionsDropdown = ({action.handle();setOpen(false);}}- className={cn(- action.variant === "danger" &&- "aria-selected:bg-[var(--red-5)] aria-selected:text-[var(--red-12)]"- )}+ variant={action.variant}><div className="flex items-center flex-1">{action.icon && (diff --git a/frontend/src/editor/cell/cell-context-menu.tsx b/frontend/src/editor/cell/cell-context-menu.tsxnew file mode 100644index 0000000000..e44ce26d1d--- /dev/null+++ b/frontend/src/editor/cell/cell-context-menu.tsx@@ -0,0 +1,98 @@+/* Copyright 2023 Marimo. All rights reserved. */+import React, { Fragment } from "react";+import {+ CellActionButtonProps,+ useCellActionButtons,+} from "../actions/useCellActionButton";+import {+ ContextMenu,+ ContextMenuTrigger,+ ContextMenuContent,+ ContextMenuItem,+ ContextMenuSeparator,+} from "@/components/ui/context-menu";+import { renderMinimalShortcut } from "@/components/shortcuts/renderShortcut";+import { ActionButton } from "../actions/types";+import { ClipboardPasteIcon, CopyIcon, ScissorsIcon } from "lucide-react";++interface Props extends CellActionButtonProps {+ children: React.ReactNode;+}++export const CellActionsContextMenu = ({ children, ...props }: Props) => {+ const actions = useCellActionButtons(props);++ const DEFAULT_CONTEXT_MENU_ITEMS: ActionButton[] = [+ {+ label: "Copy",+ icon: <CopyIcon size={13} strokeWidth={1.5} />,+ handle: () => {+ document.execCommand("copy");+ },+ },+ {+ label: "Cut",+ icon: <ScissorsIcon size={13} strokeWidth={1.5} />,+ handle: () => {+ document.execCommand("cut");+ },+ },+ {+ label: "Paste",+ icon: <ClipboardPasteIcon size={13} strokeWidth={1.5} />,+ handle: async () => {+ const { editorView } = props;+ if (!editorView) {+ return;+ }+ // We can't use the native browser paste since we don't have focus+ // so instead we use the editorViewView+ const clipText = await navigator.clipboard.readText();+ if (clipText) {+ // Get the current selection, or the start of the document if nothing is selected+ const { from, to } = editorView.state.selection.main;+ // Create a new transaction that replaces the selection with the clipboard text+ const tr = editorView.state.update({+ changes: { from, to, insert: clipText },+ });+ // Apply the transaction+ editorView.dispatch(tr);+ }+ },+ },+ ];++ return (+ <ContextMenu>+ <ContextMenuTrigger>{children}</ContextMenuTrigger>+ <ContextMenuContent className="w-[300px]">+ {[DEFAULT_CONTEXT_MENU_ITEMS, ...actions].map((group, i) => (+ <Fragment key={i}>+ {group.map((action) => {+ return (+ <ContextMenuItem+ key={action.label}+ onSelect={() => {+ action.handle();+ }}+ variant={action.variant}+ >+ <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>+ </ContextMenuItem>+ );+ })}+ {i < group.length - 1 && <ContextMenuSeparator />}+ </Fragment>+ ))}+ </ContextMenuContent>+ </ContextMenu>+ );+};diff --git a/frontend/src/stories/context-menu.stories.mdx b/frontend/src/stories/context-menu.stories.mdxnew file mode 100644index 0000000000..43452c5142--- /dev/null+++ b/frontend/src/stories/context-menu.stories.mdx@@ -0,0 +1,22 @@+import { Meta, Story } from "@storybook/addon-docs";++import {+ ContextMenu,+ ContextMenuContent,+ ContextMenuItem,+ ContextMenuTrigger,+} from "@/components/ui/context-menu";++<Meta title="ContextMenu" component={ContextMenu} />++# ContextMenu++<ContextMenu>+ <ContextMenuTrigger>Right click</ContextMenuTrigger>+ <ContextMenuContent>+ <ContextMenuItem>Profile</ContextMenuItem>+ <ContextMenuItem>Billing</ContextMenuItem>+ <ContextMenuItem>Team</ContextMenuItem>+ <ContextMenuItem>Subscription</ContextMenuItem>+ </ContextMenuContent>+</ContextMenu>