Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: cell actions in the command-pallete (#984)

Myles Scolnick760a20c36029
diff --git a/frontend/src/components/editor/actions/name-cell-input.tsx b/frontend/src/components/editor/actions/name-cell-input.tsx
index a9a348d3c2..34d5137bd2 100644
--- a/frontend/src/components/editor/actions/name-cell-input.tsx
+++ b/frontend/src/components/editor/actions/name-cell-input.tsx
@@ -13,8 +13,8 @@ import { cn } from "@/utils/cn";
import { Events } from "@/utils/events";
import React, { useRef, useState } from "react";
-interface Props {
- className?: string;
+interface Props
+ extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "onChange"> {
value: string;
onChange: (newName: string) => void;
placeholder?: string;
@@ -24,6 +24,7 @@ export const NameCellInput: React.FC<Props> = ({
value,
onChange,
placeholder,
+ ...props
}) => {
const ref = useRef<HTMLInputElement>(null);
const inputProps = useCellNameInput(value, onChange);
@@ -52,6 +53,7 @@ export const NameCellInput: React.FC<Props> = ({
placeholder={placeholder}
className="shadow-none! hover:shadow-none focus:shadow-none focus-visible:shadow-none"
onKeyDown={Events.onEnter(Events.stopPropagation())}
+ {...props}
/>
);
};
diff --git a/frontend/src/components/editor/actions/types.ts b/frontend/src/components/editor/actions/types.ts
index 19144aa9e1..fe6305fcc0 100644
--- a/frontend/src/components/editor/actions/types.ts
+++ b/frontend/src/components/editor/actions/types.ts
@@ -14,6 +14,10 @@ export interface ActionButton {
rightElement?: React.ReactNode;
hotkey?: HotkeyAction;
handle: (event?: Event) => void;
+ /**
+ * Special handler for headless contexts: e.g. a command palette.
+ */
+ handleHeadless?: (event?: Event) => void;
divider?: boolean;
dropdown?: ActionButton[];
}
diff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsx
index dc73300095..b44bbc27e9 100644
--- a/frontend/src/components/editor/actions/useCellActionButton.tsx
+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx
@@ -31,6 +31,13 @@ import { NameCellInput } from "./name-cell-input";
import { getFeatureFlag } from "@/core/config/feature-flag";
import { useSetAtom } from "jotai";
import { aiCompletionCellAtom } from "@/core/ai/state";
+import { useImperativeModal } from "@/components/modal/ImperativeModal";
+import {
+ DialogContent,
+ DialogTitle,
+ DialogHeader,
+} from "@/components/ui/dialog";
+import { Label } from "@/components/ui/label";
export interface CellActionButtonProps
extends Pick<CellData, "name" | "config"> {
@@ -40,14 +47,11 @@ export interface CellActionButtonProps
hasOutput: boolean;
}
-export function useCellActionButtons({
- cellId,
- config,
- editorView,
- name,
- hasOutput,
- status,
-}: CellActionButtonProps) {
+interface Props {
+ cell: CellActionButtonProps | null;
+}
+
+export function useCellActionButtons({ cell }: Props) {
const {
createNewCell: createCell,
updateCellConfig,
@@ -58,9 +62,15 @@ export function useCellActionButtons({
sendToTop,
sendToBottom,
} = useCellActions();
- const runCell = useRunCell(cellId);
+ const runCell = useRunCell(cell?.cellId);
+ const { openModal } = useImperativeModal();
const setAiCompletionCell = useSetAtom(aiCompletionCellAtom);
+ if (!cell) {
+ return [];
+ }
+ const { cellId, config, editorView, name, hasOutput, status } = cell;
+
const toggleDisabled = async () => {
const newConfig = { disabled: !config.disabled };
await saveCellConfig({ configs: { [cellId]: newConfig } });
@@ -94,6 +104,32 @@ export function useCellActionButtons({
evt?.stopPropagation();
evt?.preventDefault();
},
+ handleHeadless: () => {
+ openModal(
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Rename cell</DialogTitle>
+ </DialogHeader>
+ <div className="flex items-center justify-between">
+ <Label htmlFor="cell-name">Cell name</Label>
+ <NameCellInput
+ placeholder={`cell_${cellId}`}
+ value={name}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ e.stopPropagation();
+ openModal(null);
+ }
+ }}
+ onChange={(newName) =>
+ updateCellName({ cellId, name: newName })
+ }
+ />
+ </div>
+ </DialogContent>,
+ );
+ },
rightElement: (
<NameCellInput
placeholder={`cell_${cellId}`}
diff --git a/frontend/src/components/editor/cell/cell-actions.tsx b/frontend/src/components/editor/cell/cell-actions.tsx
index 0f12d24c6b..549756afc2 100644
--- a/frontend/src/components/editor/cell/cell-actions.tsx
+++ b/frontend/src/components/editor/cell/cell-actions.tsx
@@ -32,7 +32,7 @@ interface Props extends CellActionButtonProps {
export const CellActionsDropdown = ({ children, ...props }: Props) => {
const [open, setOpen] = useState(false);
- const actions = useCellActionButtons(props);
+ const actions = useCellActionButtons({ cell: props });
return (
<Popover open={open} onOpenChange={setOpen}>
diff --git a/frontend/src/components/editor/cell/cell-context-menu.tsx b/frontend/src/components/editor/cell/cell-context-menu.tsx
index c16a026e69..fe16ee27c7 100644
--- a/frontend/src/components/editor/cell/cell-context-menu.tsx
+++ b/frontend/src/components/editor/cell/cell-context-menu.tsx
@@ -25,7 +25,7 @@ interface Props extends CellActionButtonProps {
}
export const CellActionsContextMenu = ({ children, ...props }: Props) => {
- const actions = useCellActionButtons(props);
+ const actions = useCellActionButtons({ cell: props });
const [imageRightClicked, setImageRightClicked] =
React.useState<HTMLImageElement>();
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
index 3bb70f1f13..61d0a95807 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -28,9 +28,10 @@ import { cn } from "@/utils/cn";
import { saveCellConfig } from "@/core/network/requests";
import { HideCodeButton } from "../../code/readonly-python-code";
import { AiCompletionEditor } from "./ai-completion-editor";
-import { useAtom } from "jotai";
+import { useAtom, useSetAtom } from "jotai";
import { aiCompletionCellAtom } from "@/core/ai/state";
import { mergeRefs } from "@/utils/mergeRefs";
+import { lastFocusedCellIdAtom } from "@/core/cells/focus";
export interface CellEditorProps
extends Pick<CellRuntimeState, "status">,
@@ -82,6 +83,7 @@ const CellEditorInternal = ({
}: CellEditorProps) => {
const [canUseMarkdown, setCanUseMarkdown] = useState(false);
const [aiCompletionCell, setAiCompletionCell] = useAtom(aiCompletionCellAtom);
+ const setLastFocusedCellId = useSetAtom(lastFocusedCellIdAtom);
// DOM node where the editorView will be mounted
const editorViewParentRef = useRef<HTMLDivElement>(null);
@@ -316,7 +318,10 @@ const CellEditorInternal = ({
setAiCompletionCell(null);
}}
>
- <div className="relative w-full">
+ <div
+ className="relative w-full"
+ onFocus={() => setLastFocusedCellId(cellId)}
+ >
{canUseMarkdown && (
<div className="absolute top-1 right-1">
<LanguageToggle
diff --git a/frontend/src/components/editor/cell/useRunCells.ts b/frontend/src/components/editor/cell/useRunCells.ts
index ceea676b3a..4bb0dc9bbb 100644
--- a/frontend/src/components/editor/cell/useRunCells.ts
+++ b/frontend/src/components/editor/cell/useRunCells.ts
@@ -21,9 +21,14 @@ export function useRunStaleCells() {
/**
* Creates a function that runs the cell with the given id.
*/
-export function useRunCell(cellId: CellId) {
+export function useRunCell(cellId: CellId | undefined) {
const runCells = useRunCells();
- const runCell = useEvent(() => runCells([cellId]));
+ const runCell = useEvent(() => {
+ if (cellId === undefined) {
+ return;
+ }
+ runCells([cellId]);
+ });
return runCell;
}
diff --git a/frontend/src/components/editor/controls/command-palette.tsx b/frontend/src/components/editor/controls/command-palette.tsx
index 781a3e7c6f..a72efd79ca 100644
--- a/frontend/src/components/editor/controls/command-palette.tsx
+++ b/frontend/src/components/editor/controls/command-palette.tsx
@@ -14,17 +14,22 @@ import { useRegisteredActions } from "../../../core/hotkeys/actions";
import { useRecentCommands } from "../../../hooks/useRecentCommands";
import { KeyboardHotkeys } from "../../shortcuts/renderShortcut";
import { HOTKEYS, HotkeyAction, isHotkeyAction } from "@/core/hotkeys/hotkeys";
-import { atom, useAtom } from "jotai";
+import { atom, useAtom, useAtomValue } from "jotai";
import { useNotebookActions } from "../actions/useNotebookActions";
import { Objects } from "@/utils/objects";
import { parseShortcut } from "@/core/hotkeys/shortcuts";
import { isParentAction, flattenActions } from "../actions/types";
+import { useCellActionButtons } from "../actions/useCellActionButton";
+import { lastFocusedCellAtom } from "@/core/cells/focus";
export const commandPaletteAtom = atom(false);
export const CommandPalette = () => {
const [open, setOpen] = useAtom(commandPaletteAtom);
const registeredActions = useRegisteredActions();
+ const lastFocusedCell = useAtomValue(lastFocusedCellAtom);
+ let cellActions = useCellActionButtons({ cell: lastFocusedCell }).flat();
+ cellActions = flattenActions(cellActions);
let notebookActions = useNotebookActions();
notebookActions = flattenActions(notebookActions);
@@ -78,7 +83,11 @@ export const CommandPalette = () => {
);
};
- const renderCommandItem = (label: string, handle: () => void) => {
+ const renderCommandItem = (
+ label: string,
+ handle: () => void,
+ hotkey?: HotkeyAction,
+ ) => {
return (
<CommandItem
onSelect={() => {
@@ -92,6 +101,11 @@ export const CommandPalette = () => {
value={label}
>
<span>{label}</span>
+ {hotkey && (
+ <CommandShortcut>
+ <KeyboardHotkeys shortcut={HOTKEYS.getHotkey(hotkey).key} />
+ </CommandShortcut>
+ )}
</CommandItem>
);
};
@@ -112,7 +126,10 @@ export const CommandPalette = () => {
// Other action
const action = keyedNotebookActions[shortcut];
if (action && !isParentAction(action)) {
- return renderCommandItem(action.label, action.handle);
+ return renderCommandItem(
+ action.label,
+ action.handleHeadless || action.handle,
+ );
}
return null;
})}
@@ -131,7 +148,19 @@ export const CommandPalette = () => {
if (recentCommandsSet.has(action.label)) {
return null; // Don't show recent commands in the main list
}
- return renderCommandItem(action.label, action.handle);
+ return renderCommandItem(
+ action.label,
+ action.handleHeadless || action.handle,
+ );
+ })}
+ {cellActions.map((action) => {
+ if (recentCommandsSet.has(action.label)) {
+ return null; // Don't show recent commands in the main list
+ }
+ return renderCommandItem(
+ `Cell > ${action.label}`,
+ action.handleHeadless || action.handle,
+ );
})}
</CommandGroup>
</CommandList>
diff --git a/frontend/src/components/ui/use-restore-focus.ts b/frontend/src/components/ui/use-restore-focus.ts
index 4422263a9c..0f53556ffb 100644
--- a/frontend/src/components/ui/use-restore-focus.ts
+++ b/frontend/src/components/ui/use-restore-focus.ts
@@ -14,6 +14,10 @@ export function useRestoreFocus() {
};
const onCloseAutoFocus = (evt: Event) => {
+ // If the current focus is the body, restore focus to the last focused element
+ if (document.activeElement !== document.body) {
+ return;
+ }
if (lastFocused instanceof HTMLElement) {
lastFocused.focus();
}
diff --git a/frontend/src/core/cells/focus.ts b/frontend/src/core/cells/focus.ts
new file mode 100644
index 0000000000..5884519f33
--- /dev/null
+++ b/frontend/src/core/cells/focus.ts
@@ -0,0 +1,41 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { atom } from "jotai";
+import { CellId } from "./ids";
+import { notebookAtom } from "./cells";
+import { EditorView } from "@codemirror/view";
+import { CellConfig, CellStatus } from "./types";
+
+/**
+ * Holds state for the last focused cell.
+ */
+export const lastFocusedCellIdAtom = atom<CellId | null>(null);
+
+export const lastFocusedCellAtom = atom<{
+ name: string;
+ config: CellConfig;
+ cellId: CellId;
+ status: CellStatus;
+ editorView: EditorView | null;
+ hasOutput: boolean;
+} | null>((get) => {
+ const cellId = get(lastFocusedCellIdAtom);
+ const { cellData, cellHandles, cellRuntime } = get(notebookAtom);
+ if (!cellId) {
+ return null;
+ }
+ const data = cellData[cellId];
+ const runtime = cellRuntime[cellId];
+ const handle = cellHandles[cellId].current;
+ if (!data || !runtime || !handle) {
+ return null;
+ }
+
+ return {
+ cellId,
+ name: data.name,
+ config: data.config,
+ status: runtime.status,
+ editorView: handle.editorView,
+ hasOutput: runtime.output !== null,
+ };
+});
diff --git a/frontend/src/core/vscode/vscode-bindings.ts b/frontend/src/core/vscode/vscode-bindings.ts
index 65384ce94c..30f5197e13 100644
--- a/frontend/src/core/vscode/vscode-bindings.ts
+++ b/frontend/src/core/vscode/vscode-bindings.ts
@@ -2,6 +2,7 @@
import { Logger } from "@/utils/Logger";
import { isPyodide } from "../pyodide/utils";
+import { isPlatformMac } from "../hotkeys/shortcuts";
export const isEmbedded =
// eslint-disable-next-line ssr-friendly/no-dom-globals-in-module-scope
@@ -32,8 +33,11 @@ function registerCopyPaste() {
window.addEventListener("cut", () => {
const selection = window.getSelection()?.toString() ?? "";
- // clear
- document.execCommand("insertText", false, "");
+ // Only run this on mac
+ if (isPlatformMac()) {
+ // clear
+ document.execCommand("insertText", false, "");
+ }
sendToPanelManager({
command: "cut",
text: selection,
@@ -44,7 +48,9 @@ function registerCopyPaste() {
const message = event.data;
switch (message.command) {
case "paste":
- document.execCommand("insertText", false, message.text);
+ if (isPlatformMac()) {
+ document.execCommand("insertText", false, message.text);
+ }
return;
}
});