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.

chore: cell component refactoring (#4048)

Myles Scolnicke68b32e4272e
diff --git a/frontend/e2e-tests/components.spec.ts b/frontend/e2e-tests/components.spec.ts
index 9f22efc569..da2114959d 100644
--- a/frontend/e2e-tests/components.spec.ts
+++ b/frontend/e2e-tests/components.spec.ts
@@ -20,7 +20,7 @@ test.describe.configure({ mode: "parallel" });
const pageHelper = (page: Page) => {
return {
cell(index: number) {
- return page.locator(".Cell").nth(index);
+ return page.locator(".marimo-cell").nth(index);
},
async selectBasicComponent(type: string) {
const select = await this.cell(1).locator("select");
diff --git a/frontend/e2e-tests/shutdown.spec.ts b/frontend/e2e-tests/shutdown.spec.ts
index 2d0f8657df..aa91585bbc 100644
--- a/frontend/e2e-tests/shutdown.spec.ts
+++ b/frontend/e2e-tests/shutdown.spec.ts
@@ -17,7 +17,7 @@ test("can resume a session", async ({ page }) => {
await page.keyboard.press("Meta+Enter");
// wait for the output to appear
- let secondCell = await page.locator(".Cell").nth(1);
+ let secondCell = await page.locator(".marimo-cell").nth(1);
await expect(secondCell.getByText("12345")).toBeVisible();
await expect(secondCell.getByText("54321")).toBeVisible();
@@ -27,7 +27,7 @@ test("can resume a session", async ({ page }) => {
await expect(
page.getByText("You have reconnected to an existing session."),
).toBeVisible();
- secondCell = await page.locator(".Cell").nth(1);
+ secondCell = await page.locator(".marimo-cell").nth(1);
await expect(page.getByText("12345")).toBeVisible();
await expect(page.getByText("54321")).toBeVisible();
});
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsx
index 24f0614d67..ecc9090d24 100644
--- a/frontend/src/components/editor/Cell.tsx
+++ b/frontend/src/components/editor/Cell.tsx
@@ -11,7 +11,7 @@ import {
useRef,
useState,
} from "react";
-import { saveCellConfig, sendRun, sendStdin } from "@/core/network/requests";
+import { saveCellConfig, sendStdin } from "@/core/network/requests";
import { autocompletionKeymap } from "@/core/codemirror/cm";
import type { UserConfig } from "../../core/config/config-schema";
import type { CellData, CellRuntimeState } from "../../core/cells/types";
@@ -40,7 +40,6 @@ import { CellActionsContextMenu } from "./cell/cell-context-menu";
import type { AppMode } from "@/core/mode";
import useEvent from "react-use-event-hook";
import { CellEditor } from "./cell/code/cell-editor";
-import { getEditorCodeAsPython } from "@/core/codemirror/language/utils";
import { outputIsStale } from "@/core/cells/cell";
import { isOutputEmpty } from "@/core/cells/outputs";
import { useHotkeysOnElement, useKeydownOnElement } from "@/hooks/useHotkey";
@@ -54,12 +53,266 @@ import { MoreHorizontalIcon } from "lucide-react";
import { Toolbar, ToolbarItem } from "@/components/editor/cell/toolbar";
import { cn } from "@/utils/cn";
import { isErrorMime } from "@/core/mime";
-import { getCurrentLanguageAdapter } from "@/core/codemirror/language/commands";
import { HideCodeButton } from "./code/readonly-python-code";
import { useResizeObserver } from "@/hooks/useResizeObserver";
import type { LanguageAdapterType } from "@/core/codemirror/language/types";
import { Events } from "@/utils/events";
import { TooltipProvider } from "@/components/ui/tooltip";
+import { useRunCell } from "./cell/useRunCells";
+
+/**
+ * Hook for handling cell completion logic
+ */
+function useCellCompletion(
+ cellRef: React.RefObject<HTMLDivElement>,
+ editorView: React.RefObject<EditorView>,
+) {
+ // Close completion when focus leaves the cell's subtree.
+ const closeCompletionHandler = useEvent((e: FocusEvent) => {
+ if (
+ cellRef.current !== null &&
+ !cellRef.current.contains(e.relatedTarget) &&
+ editorView.current !== null
+ ) {
+ closeCompletion(editorView.current);
+ }
+ });
+
+ // Clicking on the completion info causes the editor view to lose focus,
+ // because the completion is not a child of the editable editor DOM;
+ // as a workaround, when a completion is active, we refocus the editor
+ // on any keypress.
+ //
+ // See https://discuss.codemirror.net/t/adding-click-event-listener-to-autocomplete-tooltip-info-panel-is-not-working/4741
+ const resumeCompletionHandler = useEvent((e: KeyboardEvent) => {
+ if (
+ cellRef.current !== document.activeElement ||
+ editorView.current === null ||
+ completionStatus(editorView.current.state) !== "active"
+ ) {
+ return;
+ }
+
+ for (const keymap of autocompletionKeymap) {
+ if (e.key === keymap.key && keymap.run) {
+ keymap.run(editorView.current);
+ // preventDefault/stopPropagation: Don't process the keystrokes as
+ // typing into the editor, e.g., Enter should only select the
+ // completion, not also add a newline.
+ e.preventDefault();
+ e.stopPropagation();
+ break;
+ }
+ }
+ editorView.current.focus();
+ return;
+ });
+
+ return {
+ closeCompletionHandler,
+ resumeCompletionHandler,
+ };
+}
+
+/**
+ * Hook for handling cell hotkeys
+ */
+function useCellHotkeys(
+ cellRef: React.RefObject<HTMLDivElement> | null,
+ cellId: CellId,
+ runCell: () => void,
+ actions: CellComponentActions,
+ canMoveX: boolean,
+ cellConfig: CellConfig,
+ editorView: React.RefObject<EditorView | null>,
+ setAiCompletionCell: ReturnType<
+ typeof useSetAtom<typeof aiCompletionCellAtom>
+ >,
+ cellActionDropdownRef: React.RefObject<CellActionsDropdownHandle>,
+) {
+ useHotkeysOnElement(cellRef, {
+ "cell.run": runCell,
+ "cell.runAndNewBelow": () => {
+ runCell();
+ actions.moveToNextCell({ cellId, before: false });
+ },
+ "cell.runAndNewAbove": () => {
+ runCell();
+ actions.moveToNextCell({ cellId, before: true });
+ },
+ "cell.createAbove": () => actions.createNewCell({ cellId, before: true }),
+ "cell.createBelow": () => actions.createNewCell({ cellId, before: false }),
+ "cell.moveUp": () => actions.moveCell({ cellId, before: true }),
+ "cell.moveDown": () => actions.moveCell({ cellId, before: false }),
+ "cell.moveLeft": () =>
+ canMoveX ? actions.moveCell({ cellId, direction: "left" }) : undefined,
+ "cell.moveRight": () =>
+ canMoveX ? actions.moveCell({ cellId, direction: "right" }) : undefined,
+ "cell.hideCode": () => {
+ const nextHideCode = !cellConfig.hide_code;
+ // Fire-and-forget
+ void saveCellConfig({
+ configs: { [cellId]: { hide_code: nextHideCode } },
+ });
+ actions.updateCellConfig({ cellId, config: { hide_code: nextHideCode } });
+ if (nextHideCode) {
+ // Move focus from the editor to the cell
+ editorView.current?.contentDOM.blur();
+ cellRef?.current?.focus();
+ } else {
+ // Focus the editor
+ editorView.current?.focus();
+ }
+ },
+ "cell.focusDown": () => actions.moveToNextCell({ cellId, before: false }),
+ "cell.focusUp": () => actions.moveToNextCell({ cellId, before: true }),
+ "cell.sendToBottom": () => actions.sendToBottom({ cellId }),
+ "cell.sendToTop": () => actions.sendToTop({ cellId }),
+ "cell.aiCompletion": () => {
+ let closed = false;
+ setAiCompletionCell((v) => {
+ // Toggle close
+ if (v?.cellId === cellId) {
+ closed = true;
+ return null;
+ }
+ return { cellId };
+ });
+ if (closed) {
+ derefNotNull(editorView).focus();
+ }
+ },
+ "cell.cellActions": () => {
+ cellActionDropdownRef.current?.toggle();
+ },
+ });
+}
+
+/**
+ * Hook for handling cell keyboard listeners
+ */
+function useCellKeyboardListener(
+ cellRef: React.RefObject<HTMLDivElement> | null,
+ cellId: CellId,
+ actions: CellComponentActions,
+ showHiddenMarkdownCode: () => void,
+ userConfig: UserConfig,
+ isCellCodeShown: boolean,
+) {
+ useKeydownOnElement(cellRef, {
+ ArrowDown: (evt) => {
+ if (evt && Events.fromInput(evt)) {
+ return false;
+ }
+ actions.moveToNextCell({ cellId, before: false, noCreate: true });
+ return true;
+ },
+ ArrowUp: (evt) => {
+ if (evt && Events.fromInput(evt)) {
+ return false;
+ }
+ actions.moveToNextCell({ cellId, before: true, noCreate: true });
+ return true;
+ },
+ Enter: () => {
+ showHiddenMarkdownCode();
+ return false;
+ },
+ // only register j/k movement if the cell is hidden, so as to not
+ // interfere with editing
+ ...(userConfig.keymap.preset === "vim" && !isCellCodeShown
+ ? {
+ j: (evt) => {
+ if (evt && Events.fromInput(evt)) {
+ return false;
+ }
+ actions.moveToNextCell({ cellId, before: false, noCreate: true });
+ return true;
+ },
+ k: (evt) => {
+ if (evt && Events.fromInput(evt)) {
+ return false;
+ }
+ actions.moveToNextCell({ cellId, before: true, noCreate: true });
+ return true;
+ },
+ }
+ : {}),
+ });
+}
+
+/**
+ * Hook for handling hidden cell logic
+ */
+function useCellHiddenLogic(
+ cellConfig: CellConfig,
+ languageAdapter: LanguageAdapterType | undefined,
+ editorView: React.RefObject<EditorView | null>,
+ editorViewParentRef: React.RefObject<HTMLDivElement>,
+) {
+ const [temporarilyVisible, setTemporarilyVisible] = useState(false);
+
+ // The cell code is shown if the cell is not configured to be hidden or if the code is temporarily visible (i.e. when focused).
+ const isCellCodeShown = !cellConfig.hide_code || temporarilyVisible;
+ const isMarkdown = languageAdapter === "markdown";
+ const isMarkdownCodeHidden = isMarkdown && !isCellCodeShown;
+
+ // Callback to show the code editor temporarily
+ const temporarilyShowCode = useCallback(() => {
+ if (!isCellCodeShown) {
+ setTemporarilyVisible(true);
+ editorView.current?.focus();
+ // Reach one parent up
+ const parent = editorViewParentRef.current?.parentElement;
+ if (!parent) {
+ Logger.error("Cell: No parent element found for editor view");
+ return;
+ }
+
+ const handleFocusOut = () => {
+ requestAnimationFrame(() => {
+ if (!parent.contains(document.activeElement)) {
+ // Hide the code editor
+ setTemporarilyVisible(false);
+ editorView.current?.dom.blur();
+ parent.removeEventListener("focusout", handleFocusOut);
+ }
+ });
+ };
+ parent.addEventListener("focusout", handleFocusOut);
+ }
+ }, [isCellCodeShown, editorView, editorViewParentRef, setTemporarilyVisible]);
+
+ const showHiddenMarkdownCode = useCallback(() => {
+ if (isMarkdownCodeHidden) {
+ temporarilyShowCode();
+ }
+ }, [isMarkdownCodeHidden, temporarilyShowCode]);
+
+ return {
+ isCellCodeShown,
+ isMarkdown,
+ isMarkdownCodeHidden,
+ temporarilyShowCode,
+ showHiddenMarkdownCode,
+ };
+}
+
+export type CellComponentActions = Pick<
+ CellActions,
+ | "updateCellCode"
+ | "createNewCell"
+ | "focusCell"
+ | "moveCell"
+ | "collapseCell"
+ | "expandCell"
+ | "moveToNextCell"
+ | "updateCellConfig"
+ | "clearSerializedEditorState"
+ | "setStdinResponse"
+ | "sendToBottom"
+ | "sendToTop"
+>;
/**
* Imperative interface of the cell.
@@ -69,10 +322,6 @@ export interface CellHandle {
* The CodeMirror editor view.
*/
editorView: EditorView;
- /**
- * Register the cell to run.
- */
- registerRun: () => void;
}
export interface CellProps
@@ -94,24 +343,9 @@ export interface CellProps
Pick<
CellData,
"id" | "code" | "edited" | "config" | "name" | "serializedEditorState"
- >,
- Pick<
- CellActions,
- | "updateCellCode"
- | "prepareForRun"
- | "createNewCell"
- | "deleteCell"
- | "focusCell"
- | "moveCell"
- | "collapseCell"
- | "expandCell"
- | "moveToNextCell"
- | "updateCellConfig"
- | "clearSerializedEditorState"
- | "setStdinResponse"
- | "sendToBottom"
- | "sendToTop"
> {
+ actions: CellComponentActions;
+ deleteCell: CellActions["deleteCell"];
theme: Theme;
showPlaceholder: boolean;
mode: AppMode;
@@ -132,57 +366,160 @@ export interface CellProps
}
const CellComponent = (
- {
- theme,
- showPlaceholder,
- allowFocus,
- id: cellId,
- code,
- output,
- consoleOutputs,
+ props: CellProps,
+ ref: React.ForwardedRef<CellHandle>,
+) => {
+ const {
status,
+ output,
runStartTimestamp,
- lastRunStartTimestamp,
- runElapsedTimeMs,
- edited,
interrupted,
- errored,
- stopped,
staleInputs,
- serializedEditorState,
+ edited,
+ id,
mode,
- debuggerActive,
- appClosed,
- canDelete,
- prepareForRun,
- createNewCell,
- deleteCell,
- moveCell,
- setStdinResponse,
- moveToNextCell,
- updateCellConfig,
- sendToBottom,
- sendToTop,
- collapseCell,
- expandCell,
- userConfig,
- outline,
- isCollapsed,
- collapseCount,
- config: cellConfig,
- canMoveX,
- name,
- }: CellProps,
- ref: React.ForwardedRef<CellHandle>,
-) => {
+ } = props;
+
useCellRenderCount().countRender();
- Logger.debug("Rendering Cell", cellId);
+ Logger.debug("Rendering Cell", id);
+ const editorView = useRef<EditorView | null>(null);
+
+ // An imperative interface to the code editor
+ useImperativeHandle(
+ ref,
+ () => ({
+ get editorView() {
+ return derefNotNull(editorView);
+ },
+ }),
+ [editorView],
+ );
+
+ const outputStale = outputIsStale(
+ { status, output, runStartTimestamp, interrupted, staleInputs },
+ edited,
+ );
+
+ if (mode === "edit") {
+ return (
+ <EditableCellComponent
+ {...props}
+ editorView={editorView}
+ setEditorView={(ev) => {
+ editorView.current = ev;
+ }}
+ outputStale={outputStale}
+ />
+ );
+ }
+
+ return <ReadonlyCellComponent {...props} outputStale={outputStale} />;
+};
+
+const ReadonlyCellComponent = forwardRef(
+ (
+ props: Pick<
+ CellProps,
+ "id" | "output" | "interrupted" | "errored" | "stopped" | "name"
+ > & {
+ outputStale: boolean;
+ },
+ ref: React.ForwardedRef<HTMLDivElement>,
+ ) => {
+ const {
+ id: cellId,
+ output,
+ interrupted,
+ errored,
+ stopped,
+ name,
+ outputStale,
+ } = props;
+
+ const className = clsx("marimo-cell", "hover-actions-parent z-10", {
+ published: true,
+ });
+
+ const HTMLId = HTMLCellId.create(cellId);
+
+ const outputIsError = isErrorMime(output?.mimetype);
+
+ // Hide the output if it's an error or stopped.
+ const hidden = errored || interrupted || stopped || outputIsError;
+ if (hidden) {
+ return null;
+ }
+
+ return (
+ <div
+ tabIndex={-1}
+ id={HTMLId}
+ ref={ref}
+ className={className}
+ data-cell-id={cellId}
+ data-cell-name={name}
+ >
+ <OutputArea
+ allowExpand={false}
+ forceExpand={true}
+ output={output}
+ className="output-area"
+ cellId={cellId}
+ stale={outputStale}
+ />
+ </div>
+ );
+ },
+);
+ReadonlyCellComponent.displayName = "ReadonlyCellComponent";
+
+const EditableCellComponent = ({
+ theme,
+ showPlaceholder,
+ allowFocus,
+ id: cellId,
+ code,
+ output,
+ consoleOutputs,
+ status,
+ runStartTimestamp,
+ lastRunStartTimestamp,
+ runElapsedTimeMs,
+ edited,
+ interrupted,
+ errored,
+ stopped,
+ staleInputs,
+ serializedEditorState,
+ debuggerActive,
+ appClosed,
+ canDelete,
+ actions,
+ deleteCell,
+ userConfig,
+ outline,
+ isCollapsed,
+ collapseCount,
+ config: cellConfig,
+ canMoveX,
+ name,
+ editorView,
+ setEditorView,
+ outputStale,
+}: CellProps & {
+ editorView: React.RefObject<EditorView>;
+ setEditorView: (view: EditorView) => void;
+ outputStale: boolean;
+}) => {
const cellRef = useRef<HTMLDivElement>(null);
const cellActionDropdownRef = useRef<CellActionsDropdownHandle>(null);
- const editorView = useRef<EditorView | null>(null);
+ // DOM node where the editorView will be mounted
+ const editorViewParentRef = useRef<HTMLDivElement>(null);
+ const cellContainerRef = useRef<HTMLDivElement>(null);
+
const setAiCompletionCell = useSetAtom(aiCompletionCellAtom);
- const [temporarilyVisible, setTemporarilyVisible] = useState(false);
+ const runCell = useRunCell(cellId);
const [languageAdapter, setLanguageAdapter] = useState<LanguageAdapterType>();
@@ -201,121 +538,70 @@ const CellComponent = (
edited || interrupted || (staleInputs && !disabledOrAncestorDisabled);
const loading = status === "running" || status === "queued";
- const outputStale = outputIsStale(
- { status, output, runStartTimestamp, interrupted, staleInputs },
- edited,
- );
-
// console output is cleared immediately on run, so check for queued instead
// of loading to determine staleness
const consoleOutputStale =
(status === "queued" || edited || staleInputs) && !interrupted;
- const editing = mode === "edit";
-
- // Performs side-effects that must run whenever the cell is run, but doesn't
- // actually run the cell.
- //
- // Returns the code to run.
- const prepareToRunEffects = useCallback(() => {
- const ev = derefNotNull(editorView);
- const code = getEditorCodeAsPython(ev);
- // Skip close on markdown, since we autorun, otherwise we'll close the
- // completion each time.
- if (getCurrentLanguageAdapter(ev) !== "markdown") {
- closeCompletion(ev);
- }
- prepareForRun({ cellId });
- return code;
- }, [cellId, editorView, prepareForRun]);
-
- // An imperative interface to the code editor
- useImperativeHandle(
- ref,
- () => ({
- get editorView() {
- return derefNotNull(editorView);
- },
- registerRun: prepareToRunEffects,
- }),
- [editorView, prepareToRunEffects],
- );
// Callback to get the editor view.
const getEditorView = useCallback(() => editorView.current, [editorView]);
- const handleRun = useEvent(async () => {
- if (loading) {
- return;
- }
-
- const code = prepareToRunEffects();
-
- await sendRun({ cellIds: [cellId], codes: [code] }).catch((error) => {
- Logger.error("Error running cell", error);
- });
- });
-
- const createBelow = useCallback(
- (opts: { code?: string } = {}) =>
- createNewCell({ cellId, before: false, ...opts }),
- [cellId, createNewCell],
+ const createBelow = useEvent((opts: { code?: string } = {}) =>
+ actions.createNewCell({ cellId, before: false, ...opts }),
);
- const createAbove = useCallback(
- (opts: { code?: string } = {}) =>
- createNewCell({ cellId, before: true, ...opts }),
- [cellId, createNewCell],
+ const createAbove = useEvent((opts: { code?: string } = {}) =>
+ actions.createNewCell({ cellId, before: true, ...opts }),
);
- // Close completion when focus leaves the cell's subtree.
- const closeCompletionHandler = useCallback((e: FocusEvent) => {
- if (
- cellRef.current !== null &&
- !cellRef.current.contains(e.relatedTarget) &&
- editorView.current !== null
- ) {
- closeCompletion(editorView.current);
- }
- }, []);
+ // Use the extracted hooks
+ const { closeCompletionHandler, resumeCompletionHandler } = useCellCompletion(
+ cellRef,
+ editorView,
+ );
- // Clicking on the completion info causes the editor view to lose focus,
- // because the completion is not a child of the editable editor DOM;
- // as a workaround, when a completion is active, we refocus the editor
- // on any keypress.
- //
- // See https://discuss.codemirror.net/t/adding-click-event-listener-to-autocomplete-tooltip-info-panel-is-not-working/4741
- const resumeCompletionHandler = useCallback(
- (e: KeyboardEvent) => {
- if (
- cellRef.current !== document.activeElement ||
- editorView.current === null ||
- completionStatus(editorView.current.state) !== "active"
- ) {
- return;
- }
+ const {
+ isCellCodeShown,
+ isMarkdown,
+ isMarkdownCodeHidden,
+ temporarilyShowCode,
+ showHiddenMarkdownCode,
+ } = useCellHiddenLogic(
+ cellConfig,
+ languageAdapter,
+ editorView,
+ editorViewParentRef,
+ );
- for (const keymap of autocompletionKeymap) {
- if (e.key === keymap.key && keymap.run) {
- keymap.run(editorView.current);
- // preventDefault/stopPropagation: Don't process the keystrokes as
- // typing into the editor, e.g., Enter should only select the
- // completion, not also add a newline.
- e.preventDefault();
- e.stopPropagation();
- break;
- }
- }
- editorView.current.focus();
- return;
- },
- [cellRef, editorView],
+ // Hotkey listeners
+ useCellHotkeys(
+ cellRef,
+ cellId,
+ runCell,
+ actions,
+ canMoveX,
+ cellConfig,
+ editorView,
+ setAiCompletionCell,
+ cellActionDropdownRef,
);
- const isCellCodeShown = !cellConfig.hide_code || temporarilyVisible;
- const isMarkdown = languageAdapter === "markdown";
- const isMarkdownCodeHidden = isMarkdown && !isCellCodeShown;
+ // Other keyboard listeners
+ useCellKeyboardListener(
+ cellRef,
+ cellId,
+ actions,
+ showHiddenMarkdownCode,
+ userConfig,
+ isCellCodeShown,
+ );
- const cellContainerRef = useRef<HTMLDivElement>(null);
const canCollapse = canCollapseOutline(outline);
+ const hasOutput = !isOutputEmpty(output);
+ const hasConsoleOutput = consoleOutputs.length > 0;
+ const cellOutput = userConfig.display.cell_output;
+
+ const hasOutputAbove = hasOutput && cellOutput === "above";
+ const hasOutputBelow = hasOutput && cellOutput === "below";
// If the cell is too short, we need to position some icons inline to prevent overlaps.
// This can only happen to markdown cells when the code is hidden completely
@@ -339,45 +625,7 @@ const CellComponent = (
},
});
- // DOM node where the editorView will be mounted
- const editorViewParentRef = useRef<HTMLDivElement>(null);
-
- // if the cell is hidden, show the code editor temporarily
- const temporarilyShowCode = useCallback(() => {
- if (!isCellCodeShown) {
- setTemporarilyVisible(true);
- editorView.current?.focus();
- // Reach one parent up
- const parent = editorViewParentRef.current?.parentElement;
-
- const handleFocusOut = () => {
- requestAnimationFrame(() => {
- if (!parent?.contains(document.activeElement)) {
- // Hide the code editor
- setTemporarilyVisible(false);
- editorView.current?.dom.blur();
- parent?.removeEventListener("focusout", handleFocusOut);
- }
- });
- };
- parent?.addEventListener("focusout", handleFocusOut);
- }
- }, [isCellCodeShown, editorView]);
-
- const showHiddenMarkdownCode = () => {
- if (isMarkdownCodeHidden) {
- temporarilyShowCode();
- }
- };
-
- const hasOutput = !isOutputEmpty(output);
- const hasConsoleOutput = consoleOutputs.length > 0;
- const cellOutput = userConfig.display.cell_output;
-
- const hasOutputAbove = hasOutput && cellOutput === "above";
- const hasOutputBelow = hasOutput && cellOutput === "below";
-
- const hideCodeButton = (className: string) => (
+ const renderHideCodeButton = (className: string) => (
<HideCodeButton
tooltip="Edit markdown"
className={cn("z-20 relative", className)}
@@ -392,18 +640,18 @@ const CellComponent = (
isCollapsed={isCollapsed}
onClick={() => {
if (isCollapsed) {
- expandCell({ cellId });
+ actions.expandCell({ cellId });
} else {
- collapseCell({ cellId });
+ actions.collapseCell({ cellId });
}
}}
canCollapse={canCollapse}
/>
</div>
- {isMarkdownCodeHidden && hasOutputBelow && hideCodeButton("top-3")}
+ {isMarkdownCodeHidden && hasOutputBelow && renderHideCodeButton("top-3")}
<OutputArea
// Only allow expanding in edit mode
- allowExpand={editing}
+ allowExpand={true}
// Force expand when markdown is hidden
forceExpand={isMarkdownCodeHidden}
output={output}
@@ -411,147 +659,28 @@ const CellComponent = (
cellId={cellId}
stale={outputStale}
/>
- {isMarkdownCodeHidden && hasOutputAbove && hideCodeButton("bottom-3")}
+ {isMarkdownCodeHidden &&
+ hasOutputAbove &&
+ renderHideCodeButton("bottom-3")}
</div>
);
- const className = clsx("Cell", "hover-actions-parent z-10", {
- published: !editing,
- interactive: editing,
+ const className = clsx("marimo-cell", "hover-actions-parent z-10", {
+ interactive: true,
"needs-run": needsRun,
"has-error": errored,
stopped: stopped,
disabled: cellConfig.disabled,
stale: status === "disabled-transitively",
- borderless: isMarkdownCodeHidden && hasOutput && editing,
+ borderless: isMarkdownCodeHidden && hasOutput,
});
const HTMLId = HTMLCellId.create(cellId);
- // Register hotkeys on the cell instead of the code editor
- // This is in case the code editor is hidden
- useHotkeysOnElement(editing ? cellRef : null, {
- "cell.run": handleRun,
- "cell.runAndNewBelow": () => {
- handleRun();
- moveToNextCell({ cellId, before: false });
- },
- "cell.runAndNewAbove": () => {
- handleRun();
- moveToNextCell({ cellId, before: true });
- },
- "cell.createAbove": createAbove,
- "cell.createBelow": createBelow,
- "cell.moveUp": () => moveCell({ cellId, before: true }),
- "cell.moveDown": () => moveCell({ cellId, before: false }),
- "cell.moveLeft": () =>
- canMoveX ? moveCell({ cellId, direction: "left" }) : undefined,
- "cell.moveRight": () =>
- canMoveX ? moveCell({ cellId, direction: "right" }) : undefined,
- "cell.hideCode": () => {
- const nextHideCode = !cellConfig.hide_code;
- // Fire-and-forget
- void saveCellConfig({
- configs: { [cellId]: { hide_code: nextHideCode } },
- });
- updateCellConfig({ cellId, config: { hide_code: nextHideCode } });
- if (nextHideCode) {
- // Move focus from the editor to the cell
- editorView.current?.contentDOM.blur();
- cellRef.current?.focus();
- } else {
- // Focus the editor
- editorView.current?.focus();
- }
- },
- "cell.focusDown": () => moveToNextCell({ cellId, before: false }),
- "cell.focusUp": () => moveToNextCell({ cellId, before: true }),
- "cell.sendToBottom": () => sendToBottom({ cellId }),
- "cell.sendToTop": () => sendToTop({ cellId }),
- "cell.aiCompletion": () => {
- let closed = false;
- setAiCompletionCell((v) => {
- // Toggle close
- if (v?.cellId === cellId) {
- closed = true;
- return null;
- }
- return { cellId };
- });
- if (closed) {
- derefNotNull(editorView).focus();
- }
- },
- "cell.cellActions": () => {
- cellActionDropdownRef.current?.toggle();
- },
- });
-
- useKeydownOnElement(editing ? cellRef : null, {
- ArrowDown: (evt) => {
- if (evt && Events.fromInput(evt)) {
- return false;
- }
- moveToNextCell({ cellId, before: false, noCreate: true });
- return true;
- },
- ArrowUp: (evt) => {
- if (evt && Events.fromInput(evt)) {
- return false;
- }
- moveToNextCell({ cellId, before: true, noCreate: true });
- return true;
- },
- Enter: () => {
- showHiddenMarkdownCode();
- return false;
- },
- // only register j/k movement if the cell is hidden, so as to not
- // interfere with editing
- ...(userConfig.keymap.preset === "vim" && !isCellCodeShown
- ? {
- j: (evt) => {
- if (evt && Events.fromInput(evt)) {
- return false;
- }
- moveToNextCell({ cellId, before: false, noCreate: true });
- return true;
- },
- k: (evt) => {
- if (evt && Events.fromInput(evt)) {
- return false;
- }
- moveToNextCell({ cellId, before: true, noCreate: true });
- return true;
- },
- }
- : {}),
- });
-
const handleRefactorWithAI = useEvent((opts: { prompt: string }) => {
setAiCompletionCell({ cellId, initialPrompt: opts.prompt });
});
- if (!editing) {
- const outputIsError = isErrorMime(output?.mimetype);
- const hidden = errored || interrupted || stopped || outputIsError;
- if (hidden) {
- return null;
- }
- return (
- <div
- tabIndex={-1}
- id={HTMLId}
- ref={cellRef}
- className={className}
- data-cell-id={cellId}
- data-cell-name={name}
- >
- {outputArea}
- </div>
- );
- }
-
// TODO(akshayka): Move to our own Tooltip component once it's easier
// to get the tooltip to show next to the cursor ...
// https://github.com/radix-ui/primitives/discussions/1090
@@ -570,7 +699,7 @@ const CellComponent = (
status={status}
staleInputs={staleInputs}
interrupted={interrupted}
- editing={editing}
+ editing={true}
edited={edited}
disabled={cellConfig.disabled ?? false}
elapsedTime={runElapsedTimeMs}
@@ -623,7 +752,7 @@ const CellComponent = (
cellId={cellId}
name={name}
getEditorView={getEditorView}
- onRun={handleRun}
+ onRun={runCell}
/>
</div>
<div
@@ -657,10 +786,8 @@ const CellComponent = (
config={cellConfig}
status={status}
serializedEditorState={serializedEditorState}
- runCell={handleRun}
- setEditorView={(ev) => {
- editorView.current = ev;
- }}
+ runCell={runCell}
+ setEditorView={setEditorView}
userConfig={userConfig}
editorViewRef={editorView}
editorViewParentRef={editorViewParentRef}
@@ -703,7 +830,7 @@ const CellComponent = (
cellName={name}
onRefactorWithAI={handleRefactorWithAI}
onSubmitDebugger={(text, index) => {
- setStdinResponse({
+ actions.setStdinResponse({
cellId,
response: text,
outputIndex: index,
@@ -716,7 +843,7 @@ const CellComponent = (
</div>
{isCollapsed && (
<CollapsedCellBanner
- onClick={() => expandCell({ cellId })}
+ onClick={() => actions.expandCell({ cellId })}
count={collapseCount}
cellId={cellId}
/>
diff --git a/frontend/src/components/editor/__tests__/data-attributes.test.tsx b/frontend/src/components/editor/__tests__/data-attributes.test.tsx
index 6754029dfa..6c9a642778 100644
--- a/frontend/src/components/editor/__tests__/data-attributes.test.tsx
+++ b/frontend/src/components/editor/__tests__/data-attributes.test.tsx
@@ -1,14 +1,14 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { render } from "@testing-library/react";
import { beforeAll, describe, expect, it } from "vitest";
-import { Cell } from "../Cell";
+import { Cell, type CellComponentActions } from "../Cell";
import { OutputArea } from "../Output";
import type { CellId } from "@/core/cells/ids";
import type { OutputMessage } from "@/core/kernel/messages";
-import { Functions } from "@/utils/functions";
import type { UserConfig } from "@/core/config/config-schema";
import { TooltipProvider } from "@/components/ui/tooltip";
import type { AppMode } from "@/core/mode";
+import { Functions } from "@/utils/functions";
beforeAll(() => {
global.ResizeObserver = class ResizeObserver {
@@ -88,24 +88,12 @@ describe("Cell data attributes", () => {
debuggerActive={false}
appClosed={false}
canDelete={true}
- updateCellCode={Functions.NOOP}
- prepareForRun={Functions.NOOP}
- createNewCell={Functions.NOOP}
- deleteCell={Functions.NOOP}
- focusCell={Functions.NOOP}
- moveCell={Functions.NOOP}
- setStdinResponse={Functions.NOOP}
- moveToNextCell={Functions.NOOP}
- updateCellConfig={Functions.NOOP}
- clearSerializedEditorState={Functions.NOOP}
- sendToBottom={Functions.NOOP}
- sendToTop={Functions.NOOP}
- collapseCell={Functions.NOOP}
- expandCell={Functions.NOOP}
+ actions={{} as CellComponentActions}
userConfig={userConfig}
outline={null}
isCollapsed={false}
collapseCount={0}
+ deleteCell={Functions.NOOP}
config={{
disabled: false,
hide_code: false,
diff --git a/frontend/src/components/editor/ai/merge-editor.css b/frontend/src/components/editor/ai/merge-editor.css
index 00aaf72f32..63ec0677a8 100644
--- a/frontend/src/components/editor/ai/merge-editor.css
+++ b/frontend/src/components/editor/ai/merge-editor.css
@@ -1,4 +1,4 @@
-.Cell .cm-mergeViewEditor .cm-editor {
+.marimo-cell .cm-mergeViewEditor .cm-editor {
padding: 0;
}
diff --git a/frontend/src/components/editor/cell/useRunCells.ts b/frontend/src/components/editor/cell/useRunCells.ts
index f8856c9173..d51a79dba7 100644
--- a/frontend/src/components/editor/cell/useRunCells.ts
+++ b/frontend/src/components/editor/cell/useRunCells.ts
@@ -6,6 +6,8 @@ import useEvent from "react-use-event-hook";
import { getEditorCodeAsPython } from "@/core/codemirror/language/utils";
import { Logger } from "@/utils/Logger";
import { enabledCellIds, staleCellIds } from "@/core/cells/utils";
+import { getCurrentLanguageAdapter } from "@/core/codemirror/language/commands";
+import { closeCompletion } from "@codemirror/autocomplete";
/**
* Creates a function that runs all cells that have been edited or interrupted.
@@ -52,15 +54,27 @@ function useRunCells() {
const codes: string[] = [];
for (const cellId of cellIds) {
const ref = cellHandles[cellId];
- if (ref.current) {
- codes.push(getEditorCodeAsPython(ref.current.editorView));
- ref.current.registerRun();
+ const ev = ref.current?.editorView;
+ let code: string;
+ // Performs side-effects that must run whenever the cell is run, but doesn't
+ // actually run the cell.
+ if (ev) {
+ // Skip close on markdown, since we autorun, otherwise we'll close the
+ // completion each time.
+ if (getCurrentLanguageAdapter(ev) !== "markdown") {
+ closeCompletion(ev);
+ }
+ // Prefer code from editor
+ code = getEditorCodeAsPython(ev);
} else {
- prepareForRun({ cellId });
- codes.push(cellData[cellId].code);
+ code = cellData[cellId].code;
}
+
+ codes.push(code);
+ prepareForRun({ cellId });
}
+ // Send the run request to the Kernel
await sendRun({ cellIds: cellIds, codes: codes }).catch((error) => {
Logger.error(error);
});
diff --git a/frontend/src/components/editor/output/Outputs.css b/frontend/src/components/editor/output/Outputs.css
index 3512c1908f..2a18a3d4dd 100644
--- a/frontend/src/components/editor/output/Outputs.css
+++ b/frontend/src/components/editor/output/Outputs.css
@@ -9,7 +9,7 @@
/* No margin in edit mode, where we already have separation
* between cells. */
-.Cell.published .output-area .output {
+.marimo-cell.published .output-area .output {
margin-top: 1rem;
margin-bottom: 1rem;
}
diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsx
index 27ff72a699..30bc972ff6 100644
--- a/frontend/src/components/editor/renderers/CellArray.tsx
+++ b/frontend/src/components/editor/renderers/CellArray.tsx
@@ -244,7 +244,7 @@ const SortableColumn: React.FC<{
isCollapsed={column.isCollapsed(cellId)}
collapseCount={column.getCount(cellId)}
canMoveX={appConfig.width === "columns"}
- {...actions}
+ actions={actions}
deleteCell={onDeleteCell}
/>
);
diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
index 3b408a99ff..dbbd9aee0d 100644
--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
@@ -285,13 +285,17 @@ const VerticalCell = memo(
const isPureMarkdown = new MarkdownLanguageAdapter().isSupported(code);
const published = !showCode && !kioskFull;
- const className = cn("Cell", "hover-actions-parent empty:invisible", {
- published: published,
- interactive: mode === "edit",
- "has-error": errored,
- stopped: stopped,
- borderless: isPureMarkdown && !published,
- });
+ const className = cn(
+ "marimo-cell",
+ "hover-actions-parent empty:invisible",
+ {
+ published: published,
+ interactive: mode === "edit",
+ "has-error": errored,
+ stopped: stopped,
+ borderless: isPureMarkdown && !published,
+ },
+ );
const HTMLId = HTMLCellId.create(cellId);
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.ts
index dc12ba6243..f2fe26602f 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -110,7 +110,6 @@ describe("cell reducer", () => {
if (!handle.current) {
const handle: CellHandle = {
editorView: createEditor(state.cellData[cellId as CellId].code),
- registerRun: vi.fn(),
};
state.cellHandles[cellId as CellId] = { current: handle };
}
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 1627d9e5a7..f6a8f68d7d 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -735,7 +735,6 @@ const {
...cell,
edited: false,
lastCodeRun: cell.code.trim(),
- lastExecutionTime: cell.lastExecutionTime,
};
});
},
diff --git a/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts b/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts
index 703cbd2c32..034b7da228 100644
--- a/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts
+++ b/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { describe, it, expect, vi } from "vitest";
+import { describe, it, expect } from "vitest";
import { getTopologicalCellIds } from "../getCodes";
import { notebookAtom } from "@/core/cells/cells";
import { variablesAtom } from "@/core/variables/state";
@@ -57,7 +57,6 @@ function createMockEditorView(code: string) {
return {
editorView: view,
- registerRun: vi.fn(),
};
}
diff --git a/frontend/src/css/app/Cell.css b/frontend/src/css/app/Cell.css
index da6b31b7f9..ca752de7b9 100644
--- a/frontend/src/css/app/Cell.css
+++ b/frontend/src/css/app/Cell.css
@@ -5,7 +5,7 @@
* - error
* - disabled
* */
-.Cell {
+.marimo-cell {
position: relative;
border-radius: 10px;
max-width: inherit;
@@ -237,7 +237,7 @@
}
}
-.dark .Cell {
+.dark .marimo-cell {
@apply border-border;
&.borderless {
@@ -247,12 +247,12 @@
#App.disconnected {
/* Background determined by disconnected gradient/noise. */
- .Cell,
+ .marimo-cell,
.console-output-area,
.cm .cm-gutters,
- .Cell .cm-editor.cm-focused .cm-activeLineGutter,
- .Cell .cm-editor.cm-focused .cm-activeLine,
- .Cell .shoulder-button {
+ .marimo-cell .cm-editor.cm-focused .cm-activeLineGutter,
+ .marimo-cell .cm-editor.cm-focused .cm-activeLine,
+ .marimo-cell .shoulder-button {
background-color: transparent;
}
@@ -304,7 +304,7 @@
}
/* Hide tray when dragging a cell, to prevent messing up the measurements. */
-.Cell.is-moving {
+.marimo-cell.is-moving {
.tray::before,
.tray::after {
display: none;
@@ -326,8 +326,8 @@
font-size: var(--marimo-code-editor-font-size, 0.9rem);
}
-/* .Cell is needed to take precedence over codemirror's generated class ... */
-.Cell .cm-editor {
+/* .marimo-cell is needed to take precedence over codemirror's generated class ... */
+.marimo-cell .cm-editor {
border: 1px solid transparent;
padding: 3px;
padding-right: 24px;
@@ -359,11 +359,11 @@
}
}
-.dark .Cell .cm-editor.cm-focused .cm-activeLineGutter {
+.dark .marimo-cell .cm-editor.cm-focused .cm-activeLineGutter {
background: #0e1e25;
}
-.dark .Cell .cm-editor.cm-focused .cm-activeLine {
+.dark .marimo-cell .cm-editor.cm-focused .cm-activeLine {
background: hsl(210deg 100% 2% / 20%);
}
@@ -385,8 +385,8 @@
}
.marimo-output-stale,
-.Cell.stale .output-area.marimo-output-stale,
-.Cell.stale .console-output-area.marimo-output-stale {
+.marimo-cell.stale .output-area.marimo-output-stale,
+.marimo-cell.stale .console-output-area.marimo-output-stale {
opacity: 0.8;
filter: grayscale(50%);
transition: 300ms;
diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsx
index 7a680d79d9..3dc7d7f840 100644
--- a/frontend/src/stories/cell.stories.tsx
+++ b/frontend/src/stories/cell.stories.tsx
@@ -29,8 +29,6 @@ const props: CellProps = {
errored: false,
stopped: false,
staleInputs: false,
- updateCellCode: Logger.log,
- prepareForRun: Logger.log,
runStartTimestamp: 0 as Seconds,
runElapsedTimeMs: 10 as Milliseconds,
lastRunStartTimestamp: 0 as Seconds,
@@ -44,18 +42,21 @@ const props: CellProps = {
isCollapsed: false,
collapseCount: 0,
outline: null,
- collapseCell: Logger.log,
- expandCell: Logger.log,
- createNewCell: Logger.log,
deleteCell: Logger.log,
- focusCell: Logger.log,
- moveCell: Logger.log,
- moveToNextCell: Logger.log,
- sendToBottom: Logger.log,
- sendToTop: Logger.log,
- updateCellConfig: Logger.log,
- setStdinResponse: Logger.log,
- clearSerializedEditorState: Logger.log,
+ actions: {
+ updateCellCode: Logger.log,
+ collapseCell: Logger.log,
+ expandCell: Logger.log,
+ createNewCell: Logger.log,
+ focusCell: Logger.log,
+ moveCell: Logger.log,
+ moveToNextCell: Logger.log,
+ sendToBottom: Logger.log,
+ sendToTop: Logger.log,
+ updateCellConfig: Logger.log,
+ setStdinResponse: Logger.log,
+ clearSerializedEditorState: Logger.log,
+ },
canMoveX: false,
config: {
hide_code: false,