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
start of cell config and disabling auto-run (#78)
Myles Scolnicka59e680bab45
diff --git a/frontend/src/components/sort/SortableCellsProvider.tsx b/frontend/src/components/sort/SortableCellsProvider.tsxindex 70b81dac00..9ca7af5018 100644--- a/frontend/src/components/sort/SortableCellsProvider.tsx+++ b/frontend/src/components/sort/SortableCellsProvider.tsx@@ -53,7 +53,10 @@ const SortableCellsProviderInternal = ({if (active.id === over.id) {return;}- dropCellOver(active.id as CellId, over.id as CellId);+ dropCellOver({+ cellId: active.id as CellId,+ overCellId: over.id as CellId,+ });});return (diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.tsindex 55f9ae07c2..0e19407aca 100644--- a/frontend/src/core/codemirror/cells/extensions.ts+++ b/frontend/src/core/codemirror/cells/extensions.ts@@ -5,8 +5,10 @@ import { EditorView } from "codemirror";import { CellId } from "@/core/model/ids";import { Extension, Prec } from "@codemirror/state";import { formatKeymapExtension } from "../extensions";+import { CellActions } from "@/core/state/cells";-export interface MovementCallbacks {+export interface MovementCallbacks+ extends Pick<CellActions, "sendToTop" | "sendToBottom" | "moveToNextCell"> {onRun: () => void;deleteCell: () => void;createAbove: () => void;@@ -15,9 +17,6 @@ export interface MovementCallbacks {moveDown: () => void;focusUp: () => void;focusDown: () => void;- sendToTop: (cellId: CellId) => void;- sendToBottom: (cellId: CellId) => void;- moveToNextCell: (cellId: CellId, before: boolean) => void;}/**@@ -56,7 +55,7 @@ export function cellMovementBundle(run: (ev) => {onRun();ev.contentDOM.blur();- moveToNextCell(cellId, /*before=*/ false);+ moveToNextCell({ cellId, before: false });return true;},},@@ -66,7 +65,7 @@ export function cellMovementBundle(run: (ev) => {onRun();ev.contentDOM.blur();- moveToNextCell(cellId, /*before=*/ true);+ moveToNextCell({ cellId, before: true });return true;},},@@ -122,7 +121,7 @@ export function cellMovementBundle(key: HOTKEYS.getHotkey("cell.sendToBottom").key,preventDefault: true,run: () => {- sendToBottom(cellId);+ sendToBottom({ cellId });return true;},},@@ -130,7 +129,7 @@ export function cellMovementBundle(key: HOTKEYS.getHotkey("cell.sendToTop").key,preventDefault: true,run: () => {- sendToTop(cellId);+ sendToTop({ cellId });return true;},},@@ -159,7 +158,7 @@ export function cellMovementBundle(}export interface CodeCallbacks {- updateCellCode: (cellId: CellId, code: string) => void;+ updateCellCode: CellActions["updateCellCode"];}/**@@ -174,7 +173,7 @@ export function cellCodeEditingBundle(const onChangePlugin = EditorView.updateListener.of((update) => {if (update.docChanged) {const nextCode = update.state.doc.toString();- updateCellCode(cellId, nextCode);+ updateCellCode({ cellId, code: nextCode, formattingChange: false });}});diff --git a/frontend/src/core/codemirror/extensions.ts b/frontend/src/core/codemirror/extensions.tsindex db398a3723..bda99816b2 100644--- a/frontend/src/core/codemirror/extensions.ts+++ b/frontend/src/core/codemirror/extensions.ts@@ -4,6 +4,7 @@ import { CellId } from "../model/ids";import { formatEditorViews } from "./format";import { smartScrollIntoView } from "../../utils/scroll";import { HOTKEYS } from "@/core/hotkeys/hotkeys";+import { CellActions } from "../state/cells";function acceptPlaceholder(cm: EditorView, text: string) {// if empty, insert the placeholder@@ -54,11 +55,7 @@ export function smartPlaceholderExtension(text: string) {*/export function formatKeymapExtension(cellId: CellId,- updateCellCode: (- cellId: CellId,- code: string,- formattingChange: boolean- ) => void+ updateCellCode: CellActions["updateCellCode"]) {return keymap.of([{diff --git a/frontend/src/core/codemirror/format.ts b/frontend/src/core/codemirror/format.tsindex 304cd6772b..f4d6669864 100644--- a/frontend/src/core/codemirror/format.ts+++ b/frontend/src/core/codemirror/format.ts@@ -3,6 +3,7 @@ import { EditorView } from "@codemirror/view";import { CellId } from "../model/ids";import { Objects } from "../../utils/objects";import { sendFormat } from "../network/requests";+import { CellActions } from "../state/cells";/*** Format the code in the editor views via the marimo server,@@ -10,11 +11,7 @@ import { sendFormat } from "../network/requests";*/export async function formatEditorViews(views: Record<CellId, EditorView>,- updateCellCode: (- cellId: CellId,- code: string,- formattingChange: boolean- ) => void+ updateCellCode: CellActions["updateCellCode"]) {const codes = Objects.mapValues(views, (view) => view.state.doc.toString());@@ -34,7 +31,7 @@ export async function formatEditorViews(continue;}- updateCellCode(cellId, formattedCode, true);+ updateCellCode({ cellId, code: formattedCode, formattingChange: true });view.dispatch({changes: {diff --git a/frontend/src/core/kernel/messages.tsx b/frontend/src/core/kernel/messages.tsxindex 732518fdf6..51b3106de3 100644--- a/frontend/src/core/kernel/messages.tsx+++ b/frontend/src/core/kernel/messages.tsx@@ -70,7 +70,7 @@ export interface CellMessage {* Encodes status transitions. Non-null means a transition happened. Null* means no transition in status.*/- status: "idle" | "queued" | "running" | null;+ status: "idle" | "queued" | "running" | "stale" | null;/*** Timestamp in seconds since epoch, when the message was sent*/diff --git a/frontend/src/core/model/cells.ts b/frontend/src/core/model/cells.tsindex 82c2ba3146..9cbd53039d 100644--- a/frontend/src/core/model/cells.ts+++ b/frontend/src/core/model/cells.ts@@ -13,8 +13,9 @@ export const DEFAULT_CELL_NAME = "__";* queued: queued by the kernel.* running: currently executing.* idle: not running.+ * stale: not run because auto-run is disabled.*/-export type CellStatus = "queued" | "running" | "idle";+export type CellStatus = "queued" | "running" | "idle" | "stale";/*** Create a new cell with default state.@@ -36,10 +37,12 @@ export function createCell({runStartTimestamp = null,lastCodeRun = null,serializedEditorState = null,+ config = {},}: Partial<CellState> & Pick<CellState, "key">): CellState {return {key: key,ref: ref,+ config: config,name: name,initialContents: initialContents,output: output,@@ -94,4 +97,15 @@ export interface CellState {/** handle to access the underlying cell */ref: React.RefObject<CellHandle>;++ /** cell configuration */+ config: CellConfig;+}++export interface CellConfig {+ /**+ * If false, the cell will not be run automatically.+ * Cannot be true, and instead will be set to null.+ */+ autoRun?: false | null;}diff --git a/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snap b/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snapindex d4fd96938f..b32bedabc1 100644--- a/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snap+++ b/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snap@@ -1,8 +1,57 @@// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html+exports[`cell reducer > can run cell a stale cell 1`] = `+{+ "code": "mo.slider()",+ "config": {},+ "consoleOutputs": [],+ "edited": false,+ "errored": false,+ "initialContents": "",+ "interrupted": false,+ "key": "1",+ "lastCodeRun": "mo.slider()",+ "name": "__",+ "output": null,+ "ref": {+ "current": null,+ },+ "runElapsedTimeMs": null,+ "runStartTimestamp": null,+ "serializedEditorState": null,+ "status": "queued",+ "stopped": false,+}+`;++exports[`cell reducer > can run cell a stale cell 2`] = `+{+ "code": "mo.slider()",+ "config": {},+ "consoleOutputs": [],+ "edited": false,+ "errored": false,+ "initialContents": "",+ "interrupted": false,+ "key": "1",+ "lastCodeRun": "mo.slider()",+ "name": "__",+ "output": null,+ "ref": {+ "current": null,+ },+ "runElapsedTimeMs": null,+ "runStartTimestamp": null,+ "serializedEditorState": null,+ "status": "stale",+ "stopped": false,+}+`;+exports[`cell reducer > can run cell and receive cell messages 1`] = `{"code": "",+ "config": {},"consoleOutputs": [],"edited": false,"errored": false,@@ -26,6 +75,7 @@ exports[`cell reducer > can run cell and receive cell messages 1`] = `exports[`cell reducer > can run cell and receive cell messages 2`] = `{"code": "import marimo as mo",+ "config": {},"consoleOutputs": [],"edited": true,"errored": false,@@ -49,6 +99,7 @@ exports[`cell reducer > can run cell and receive cell messages 2`] = `exports[`cell reducer > can run cell and receive cell messages 3`] = `{"code": "import marimo as mo",+ "config": {},"consoleOutputs": [],"edited": false,"errored": false,@@ -72,6 +123,7 @@ exports[`cell reducer > can run cell and receive cell messages 3`] = `exports[`cell reducer > can run cell and receive cell messages 4`] = `{"code": "import marimo as mo",+ "config": {},"consoleOutputs": [],"edited": false,"errored": false,@@ -95,6 +147,7 @@ exports[`cell reducer > can run cell and receive cell messages 4`] = `exports[`cell reducer > can run cell and receive cell messages 5`] = `{"code": "import marimo as mo",+ "config": {},"consoleOutputs": [],"edited": false,"errored": false,@@ -118,6 +171,7 @@ exports[`cell reducer > can run cell and receive cell messages 5`] = `exports[`cell reducer > can run cell and receive cell messages 6`] = `{"code": "import marimo as mo",+ "config": {},"consoleOutputs": [{"channel": "console",@@ -148,6 +202,7 @@ exports[`cell reducer > can run cell and receive cell messages 6`] = `exports[`cell reducer > can run cell and receive cell messages 7`] = `{"code": "import marimo as mo",+ "config": {},"consoleOutputs": [{"channel": "console",@@ -184,6 +239,7 @@ exports[`cell reducer > can run cell and receive cell messages 8`] = `{"code": "import marimo as moimport numpy",+ "config": {},"consoleOutputs": [{"channel": "console",@@ -219,6 +275,7 @@ import numpy",exports[`cell reducer > can run cell and receive cell messages 9`] = `{"code": "import marimo as mo",+ "config": {},"consoleOutputs": [{"channel": "console",@@ -255,6 +312,7 @@ exports[`cell reducer > can run cell and receive cell messages 10`] = `{"code": "import marimo as moimport numpy",+ "config": {},"consoleOutputs": [{"channel": "console",@@ -291,6 +349,7 @@ exports[`cell reducer > can run cell and receive cell messages 11`] = `{"code": "import marimo as moimport numpy",+ "config": {},"consoleOutputs": [{"channel": "console",@@ -334,6 +393,7 @@ exports[`cell reducer > can run cell and receive cell messages 12`] = `{"code": "import marimo as moimport numpy",+ "config": {},"consoleOutputs": [{"channel": "console",diff --git a/frontend/src/core/state/__tests__/cells.test.ts b/frontend/src/core/state/__tests__/cells.test.tsindex 0c43c556e6..d879f7f133 100644--- a/frontend/src/core/state/__tests__/cells.test.ts+++ b/frontend/src/core/state/__tests__/cells.test.ts@@ -4,7 +4,7 @@ import { CellState, createCell } from "../../model/cells";import { CellsAndHistory, exportedForTesting } from "../cells";import { CellId } from "@/core/model/ids";-const { initialCellState, reducer } = exportedForTesting;+const { initialCellState, reducer, createActions } = exportedForTesting;function formatCells(cells: CellState[]) {return `\n${cells@@ -14,20 +14,23 @@ function formatCells(cells: CellState[]) {describe("cell reducer", () => {let state: CellsAndHistory;- let firstCellKey: CellId;+ let firstCellId: CellId;++ const actions = createActions((action) => {+ state = reducer(state, action);+ });beforeEach(() => {CellId.reset();state = initialCellState();state.present = [createCell({ key: CellId.create() })];- firstCellKey = state.present[0].key;+ firstCellId = state.present[0].key;});it("can add a cell after another cell", () => {- state = reducer(state, {- type: "CREATE_CELL",- cellKey: firstCellKey,+ actions.createNewCell({+ cellId: firstCellId,before: false,});expect(formatCells(state.present)).toMatchInlineSnapshot(`@@ -41,9 +44,8 @@ describe("cell reducer", () => {});it("can add a cell before another cell", () => {- state = reducer(state, {- type: "CREATE_CELL",- cellKey: firstCellKey,+ actions.createNewCell({+ cellId: firstCellId,before: true,});expect(formatCells(state.present)).toMatchInlineSnapshot(`@@ -57,14 +59,12 @@ describe("cell reducer", () => {});it("can delete a cell", () => {- state = reducer(state, {- type: "CREATE_CELL",- cellKey: firstCellKey,+ actions.createNewCell({+ cellId: firstCellId,before: false,});- state = reducer(state, {- type: "DELETE_CELL",- cellKey: firstCellKey,+ actions.deleteCell({+ cellId: firstCellId,});expect(formatCells(state.present)).toMatchInlineSnapshot(`"@@ -73,7 +73,7 @@ describe("cell reducer", () => {`);// undo- state = reducer(state, { type: "UNDO_DELETE_CELL" });+ actions.undoDeleteCell();expect(formatCells(state.present)).toMatchInlineSnapshot(`"key: 2@@ -85,9 +85,8 @@ describe("cell reducer", () => {});it("can update a cell", () => {- state = reducer(state, {- type: "UPDATE_CELL_CODE",- cellKey: firstCellKey,+ actions.updateCellCode({+ cellId: firstCellId,code: "import numpy as np",formattingChange: false,});@@ -99,9 +98,8 @@ describe("cell reducer", () => {});it("can move a cell", () => {- state = reducer(state, {- type: "CREATE_CELL",- cellKey: firstCellKey,+ actions.createNewCell({+ cellId: firstCellId,before: false,});expect(formatCells(state.present)).toMatchInlineSnapshot(`@@ -114,9 +112,8 @@ describe("cell reducer", () => {`);// move first cell to the end- state = reducer(state, {- type: "MOVE_CELL",- cellKey: firstCellKey,+ actions.moveCell({+ cellId: firstCellId,before: false,});expect(formatCells(state.present)).toMatchInlineSnapshot(`@@ -129,9 +126,8 @@ describe("cell reducer", () => {`);// move it back- state = reducer(state, {- type: "MOVE_CELL",- cellKey: firstCellKey,+ actions.moveCell({+ cellId: firstCellId,before: true,});expect(formatCells(state.present)).toMatchInlineSnapshot(`@@ -145,14 +141,12 @@ describe("cell reducer", () => {});it("can drag and drop a cell", () => {- state = reducer(state, {- type: "CREATE_CELL",- cellKey: firstCellKey,+ actions.createNewCell({+ cellId: firstCellId,before: false,});- state = reducer(state, {- type: "CREATE_CELL",- cellKey: "1" as CellId,+ actions.createNewCell({+ cellId: "1" as CellId,before: false,});expect(formatCells(state.present)).toMatchInlineSnapshot(`@@ -168,10 +162,9 @@ describe("cell reducer", () => {`);// drag first cell to the end- state = reducer(state, {- type: "DROP_CELL_OVER",- cellKey: firstCellKey,- overCellKey: "2" as CellId,+ actions.dropCellOver({+ cellId: firstCellId,+ overCellId: "2" as CellId,});expect(formatCells(state.present)).toMatchInlineSnapshot(`"@@ -186,10 +179,9 @@ describe("cell reducer", () => {`);// drag it back to the middle- state = reducer(state, {- type: "DROP_CELL_OVER",- cellKey: firstCellKey,- overCellKey: "2" as CellId,+ actions.dropCellOver({+ cellId: firstCellId,+ overCellId: "2" as CellId,});expect(formatCells(state.present)).toMatchInlineSnapshot(`"@@ -215,9 +207,8 @@ describe("cell reducer", () => {expect(cell).toMatchSnapshot(); // snapshot everything as a catch all// Update code- state = reducer(state, {- type: "UPDATE_CELL_CODE",- cellKey: firstCellKey,+ actions.updateCellCode({+ cellId: firstCellId,code: "import marimo as mo",formattingChange: false,});@@ -228,9 +219,8 @@ describe("cell reducer", () => {expect(cell).toMatchSnapshot(); // snapshot everything as a catch all// Prepare for run- state = reducer(state, {- type: "PREPARE_FOR_RUN",- cellKey: firstCellKey,+ actions.prepareForRun({+ cellId: firstCellId,});cell = state.present[0];expect(cell.status).toBe("idle");@@ -239,11 +229,10 @@ describe("cell reducer", () => {expect(cell).toMatchSnapshot(); // snapshot everything as a catch all// Receive queued messages- state = reducer(state, {- type: "HANDLE_CELL_MESSAGE",- cellKey: firstCellKey,+ actions.handleCellMessage({+ cellId: firstCellId,message: {- cell_id: firstCellKey,+ cell_id: firstCellId,output: null,console: null,status: "queued",@@ -259,11 +248,10 @@ describe("cell reducer", () => {expect(cell).toMatchSnapshot(); // snapshot everything as a catch all// Receive running messages- state = reducer(state, {- type: "HANDLE_CELL_MESSAGE",- cellKey: firstCellKey,+ actions.handleCellMessage({+ cellId: firstCellId,message: {- cell_id: firstCellKey,+ cell_id: firstCellId,output: null,console: null,status: "running",@@ -279,11 +267,10 @@ describe("cell reducer", () => {expect(cell).toMatchSnapshot(); // snapshot everything as a catch all// Console messags shouldn't transition status- state = reducer(state, {- type: "HANDLE_CELL_MESSAGE",- cellKey: firstCellKey,+ actions.handleCellMessage({+ cellId: firstCellId,message: {- cell_id: firstCellKey,+ cell_id: firstCellId,output: null,console: {channel: "console",@@ -303,11 +290,10 @@ describe("cell reducer", () => {expect(cell).toMatchSnapshot(); // snapshot everything as a catch all// Receive output messages- state = reducer(state, {- type: "HANDLE_CELL_MESSAGE",- cellKey: firstCellKey,+ actions.handleCellMessage({+ cellId: firstCellId,message: {- cell_id: firstCellKey,+ cell_id: firstCellId,output: {channel: "output",mimetype: "text/plain",@@ -334,9 +320,8 @@ describe("cell reducer", () => {// EDITING BACK AND FORTH/////////////////// Update code again- state = reducer(state, {- type: "UPDATE_CELL_CODE",- cellKey: firstCellKey,+ actions.updateCellCode({+ cellId: firstCellId,code: "import marimo as mo\nimport numpy",formattingChange: false,});@@ -346,9 +331,8 @@ describe("cell reducer", () => {expect(cell).toMatchSnapshot(); // snapshot everything as a catch all// Update code should be unedited- state = reducer(state, {- type: "UPDATE_CELL_CODE",- cellKey: firstCellKey,+ actions.updateCellCode({+ cellId: firstCellId,code: "import marimo as mo",formattingChange: false,});@@ -357,9 +341,8 @@ describe("cell reducer", () => {expect(cell).toMatchSnapshot(); // snapshot everything as a catch all// Update code should be edited again- state = reducer(state, {- type: "UPDATE_CELL_CODE",- cellKey: firstCellKey,+ actions.updateCellCode({+ cellId: firstCellId,code: "import marimo as mo\nimport numpy",formattingChange: false,});@@ -372,18 +355,16 @@ describe("cell reducer", () => {// ERROR RESPONSE/////////////////// Prepare for run- state = reducer(state, {- type: "PREPARE_FOR_RUN",- cellKey: firstCellKey,+ actions.prepareForRun({+ cellId: firstCellId,});cell = state.present[0];expect(cell.output).not.toBe(null); // keep old output// Queue- state = reducer(state, {- type: "HANDLE_CELL_MESSAGE",- cellKey: firstCellKey,+ actions.handleCellMessage({+ cellId: firstCellId,message: {- cell_id: firstCellKey,+ cell_id: firstCellId,output: null,console: null,status: "queued",@@ -393,11 +374,10 @@ describe("cell reducer", () => {cell = state.present[0];expect(cell.output).not.toBe(null); // keep old output// Running- state = reducer(state, {- type: "HANDLE_CELL_MESSAGE",- cellKey: firstCellKey,+ actions.handleCellMessage({+ cellId: firstCellId,message: {- cell_id: firstCellKey,+ cell_id: firstCellId,output: null,console: null,status: "running",@@ -407,11 +387,10 @@ describe("cell reducer", () => {cell = state.present[0];expect(cell.output).not.toBe(null); // keep old output// Receive error- state = reducer(state, {- type: "HANDLE_CELL_MESSAGE",- cellKey: firstCellKey,+ actions.handleCellMessage({+ cellId: firstCellId,message: {- cell_id: firstCellKey,+ cell_id: firstCellId,output: {channel: "marimo-error",mimetype: "application/vnd.marimo+error",@@ -437,18 +416,16 @@ describe("cell reducer", () => {// INTERRUPT RESPONSE/////////////////// Prepare for run- state = reducer(state, {- type: "PREPARE_FOR_RUN",- cellKey: firstCellKey,+ actions.prepareForRun({+ cellId: firstCellId,});cell = state.present[0];expect(cell.output).not.toBe(null); // keep old output// Queue- state = reducer(state, {- type: "HANDLE_CELL_MESSAGE",- cellKey: firstCellKey,+ actions.handleCellMessage({+ cellId: firstCellId,message: {- cell_id: firstCellKey,+ cell_id: firstCellId,output: null,console: null,status: "queued",@@ -458,11 +435,10 @@ describe("cell reducer", () => {cell = state.present[0];expect(cell.output).not.toBe(null); // keep old output// Running- state = reducer(state, {- type: "HANDLE_CELL_MESSAGE",- cellKey: firstCellKey,+ actions.handleCellMessage({+ cellId: firstCellId,message: {- cell_id: firstCellKey,+ cell_id: firstCellId,output: null,console: null,status: "running",@@ -472,11 +448,10 @@ describe("cell reducer", () => {cell = state.present[0];expect(cell.output).not.toBe(null); // keep old output// Receive error- state = reducer(state, {- type: "HANDLE_CELL_MESSAGE",- cellKey: firstCellKey,+ actions.handleCellMessage({+ cellId: firstCellId,message: {- cell_id: firstCellKey,+ cell_id: firstCellId,output: {channel: "marimo-error",mimetype: "application/vnd.marimo+error",@@ -497,11 +472,74 @@ describe("cell reducer", () => {expect(cell).toMatchSnapshot(); // snapshot everything as a catch all});+ it("can run cell a stale cell", () => {+ // Update code of first cell+ actions.updateCellCode({+ cellId: firstCellId,+ code: "import marimo as mo",+ formattingChange: false,+ });+ // Add cell+ actions.createNewCell({+ cellId: firstCellId,+ before: false,+ });+ const secondCell = state.present[1].key;+ // Update code+ actions.updateCellCode({+ code: "mo.slider()",+ cellId: secondCell,+ formattingChange: false,+ });++ // Prepare for run+ actions.prepareForRun({+ cellId: secondCell,+ });++ // Receive queued messages+ actions.handleCellMessage({+ cellId: secondCell,+ message: {+ cell_id: secondCell,+ output: null,+ console: null,+ status: "queued",+ timestamp: new Date(10).getTime(),+ },+ });+ let cell = state.present[1];+ expect(cell.status).toBe("queued");+ expect(cell.lastCodeRun).toBe("mo.slider()");+ expect(cell.edited).toBe(false);+ expect(cell.runElapsedTimeMs).toBe(null);+ expect(cell.runStartTimestamp).toBe(null);+ expect(cell).toMatchSnapshot(); // snapshot everything as a catch all++ // Receive stale message+ actions.handleCellMessage({+ cellId: secondCell,+ message: {+ cell_id: secondCell,+ output: null,+ console: null,+ status: "stale",+ timestamp: new Date(20).getTime(),+ },+ });+ cell = state.present[1];+ expect(cell.status).toBe("stale");+ expect(cell.lastCodeRun).toBe("mo.slider()");+ expect(cell.edited).toBe(false);+ expect(cell.runElapsedTimeMs).toBe(null);+ expect(cell.runStartTimestamp).toBe(null);+ expect(cell).toMatchSnapshot(); // snapshot everything as a catch all+ });+it("can format code and update cell", () => {- const firstCellKey = state.present[0].key;- state = reducer(state, {- type: "UPDATE_CELL_CODE",- cellKey: firstCellKey,+ const firstCellId = state.present[0].key;+ actions.updateCellCode({+ cellId: firstCellId,code: "import marimo as mo",formattingChange: false,});@@ -511,15 +549,13 @@ describe("cell reducer", () => {expect(cell.edited).toBe(true);// Run- state = reducer(state, {- type: "PREPARE_FOR_RUN",- cellKey: firstCellKey,+ actions.prepareForRun({+ cellId: firstCellId,});- state = reducer(state, {- type: "HANDLE_CELL_MESSAGE",- cellKey: firstCellKey,+ actions.handleCellMessage({+ cellId: firstCellId,message: {- cell_id: firstCellKey,+ cell_id: firstCellId,output: {channel: "output",mimetype: "text/plain",@@ -544,9 +580,8 @@ describe("cell reducer", () => {expect(cell.lastCodeRun).toBe("import marimo as mo");// Format code- state = reducer(state, {- type: "UPDATE_CELL_CODE",- cellKey: firstCellKey,+ actions.updateCellCode({+ cellId: firstCellId,code: "import marimo as mo",formattingChange: true,});@@ -555,4 +590,26 @@ describe("cell reducer", () => {expect(cell.lastCodeRun).toBe("import marimo as mo");expect(cell.edited).toBe(false);});++ it("can update a cells config", () => {+ const firstCellId = state.present[0].key;+ let cell = state.present[0];+ // Starts empty+ expect(cell.config).toEqual({});++ actions.updateCellConfig({+ cellId: firstCellId,+ config: { autoRun: false },+ });+ cell = state.present[0];+ expect(cell.config.autoRun).toBe(false);++ // Revert+ actions.updateCellConfig({+ cellId: firstCellId,+ config: { autoRun: null },+ });+ cell = state.present[0];+ expect(cell.config.autoRun).toBe(null);+ });});diff --git a/frontend/src/core/state/cell.ts b/frontend/src/core/state/cell.tsindex 99d319ed22..751587d5f3 100644--- a/frontend/src/core/state/cell.ts+++ b/frontend/src/core/state/cell.ts@@ -1,4 +1,5 @@/* Copyright 2023 Marimo. All rights reserved. */+import { logNever } from "@/utils/assertNever";import { CellMessage } from "../kernel/messages";import { CellState } from "../model/cells";import { collapseConsoleOutputs } from "../model/collapseConsoleOutputs";@@ -31,6 +32,13 @@ export function transitionCell(nextCell.runStartTimestamp = null;}break;+ case null:+ break;+ case "stale":+ // Everything should already be up to date from prepareCellForExecution+ break;+ default:+ logNever(message.status);}nextCell.status = message.status ?? cell.status;diff --git a/frontend/src/core/state/cells.ts b/frontend/src/core/state/cells.tsindex dc1a1f5d2b..4363651385 100644--- a/frontend/src/core/state/cells.ts+++ b/frontend/src/core/state/cells.ts@@ -1,8 +1,8 @@/* Copyright 2023 Marimo. All rights reserved. */import { atom, useAtomValue, useSetAtom } from "jotai";-import { useMemo } from "react";+import { ReducerWithoutAction, useMemo } from "react";import { CellMessage } from "../kernel/messages";-import { CellState, createCell } from "../model/cells";+import { CellConfig, CellState, createCell } from "../model/cells";import {scrollToBottom,scrollToTop,@@ -12,6 +12,8 @@ import { arrayMove } from "@dnd-kit/sortable";import { CellId } from "../model/ids";import { prepareCellForExecution, transitionCell } from "./cell";import { store } from "./jotai";+import { createReducer } from "../../utils/createReducer";+import { arrayInsert, arrayDelete } from "@/utils/arrays";import { foldAllBulk, unfoldAllBulk } from "../codemirror/editing/commands";/* The array of cells on the page, together with a history of@@ -47,429 +49,338 @@ function initialCellState(): CellsAndHistory {};}-export type CellAction =- | {- type: "SET_CELLS";- cells: CellState[];- }- | {- type: "CREATE_CELL";- cellKey: CellId;- before: boolean;- }- | {- type: "MOVE_CELL";- cellKey: CellId;- before: boolean;- }- | {- type: "DROP_CELL_OVER";- cellKey: CellId;- overCellKey: CellId;- }- | {- type: "FOCUS_CELL";- cellKey: CellId;- before: boolean;- }- | {- type: "FOCUS_TOP_CELL";- }- | {- type: "FOCUS_BOTTOM_CELL";- }- | {- type: "SEND_TO_TOP";- cellKey: CellId;- }- | {- type: "SEND_TO_BOTTOM";- cellKey: CellId;- }- | {- type: "MOVE_TO_NEXT_CELL";- cellKey: CellId;- before: boolean;- }- | {- type: "DELETE_CELL";- cellKey: CellId;- }- | {- type: "SCROLL_TO_TARGET";- }- | {- type: "UNDO_DELETE_CELL";- }- | {- type: "HANDLE_CELL_MESSAGE";- cellKey: CellId;- message: CellMessage;- }- | {- type: "UPDATE_CELL_CODE";- cellKey: CellId;- code: string;- /**- * Whether or not the update is a formatting change,- * if so, the 'edited' state will be handled differently.- */- formattingChange: boolean;- }- | {- type: "PREPARE_FOR_RUN";- cellKey: CellId;- }- | {- type: "FOLD_ALL";- }- | {- type: "UNFOLD_ALL";- };--function reducer(state: CellsAndHistory, action: CellAction): CellsAndHistory {- switch (action.type) {- case "CREATE_CELL": {- const { cellKey, before } = action;- const index = state.present.findIndex((cell) => cell.key === cellKey);- const insertionIndex = before ? index : index + 1;- const cell = createCell({ key: CellId.create() });+const { reducer, createActions } = createReducer(initialCellState, {+ createNewCell: (state, action: { cellId: CellId; before: boolean }) => {+ const { cellId, before } = action;+ const index = state.present.findIndex((cell) => cell.key === cellId);+ const insertionIndex = before ? index : index + 1;+ const cell = createCell({ key: CellId.create() });+ return {+ ...state,+ present: arrayInsert(state.present, insertionIndex, cell),+ scrollKey: cell.key,+ };+ },+ moveCell: (state, action: { cellId: CellId; before: boolean }) => {+ const { cellId, before } = action;+ const index = state.present.findIndex((cell) => cell.key === cellId);+ const cell = state.present[index];+ if (before && index === 0) {return {...state,- present: [- ...state.present.slice(0, insertionIndex),- cell,- ...state.present.slice(insertionIndex),- ],- scrollKey: cell.key,+ present: [cell, ...state.present.slice(1)],+ scrollKey: cellId,+ };+ } else if (!before && index === state.present.length - 1) {+ return {+ ...state,+ present: [...state.present.slice(0, -1), cell],+ scrollKey: cellId,};}- case "MOVE_CELL": {- const { cellKey, before } = action;- const index = state.present.findIndex((cell) => cell.key === cellKey);- const cell = state.present[index];- if (before && index === 0) {- return {++ return before+ ? {...state,- present: [cell, ...state.present.slice(1)],- scrollKey: cellKey,- };- } else if (!before && index === state.present.length - 1) {- return {+ present: arrayMove(state.present, index, index - 1),+ scrollKey: cellId,+ }+ : {...state,- present: [...state.present.slice(0, -1), cell],- scrollKey: cellKey,+ present: arrayMove(state.present, index, index + 1),+ scrollKey: cellId,};- }-- return before- ? {- ...state,- present: [- ...state.present.slice(0, index - 1),- cell,- state.present[index - 1],- ...state.present.slice(index + 1),- ],- scrollKey: cellKey,- }- : {- ...state,- present: [- ...state.present.slice(0, index),- state.present[index + 1],- cell,- ...state.present.slice(index + 2),- ],- scrollKey: cellKey,- };- }- case "DROP_CELL_OVER": {- const { cellKey, overCellKey } = action;- const fromIndex = state.present.findIndex((cell) => cell.key === cellKey);- const toIndex = state.present.findIndex(- (cell) => cell.key === overCellKey- );- return {- ...state,- present: arrayMove(state.present, fromIndex, toIndex),- scrollKey: null,- };+ },+ dropCellOver: (state, action: { cellId: CellId; overCellId: CellId }) => {+ const { cellId, overCellId } = action;+ const fromIndex = state.present.findIndex((cell) => cell.key === cellId);+ const toIndex = state.present.findIndex((cell) => cell.key === overCellId);+ return {+ ...state,+ present: arrayMove(state.present, fromIndex, toIndex),+ scrollKey: null,+ };+ },+ focusCell: (state, action: { cellId: CellId; before: boolean }) => {+ if (state.present.length === 0) {+ return state;}- case "FOCUS_CELL": {- if (state.present.length === 0) {- return state;- }+ const { cellId, before } = action;+ const index = state.present.findIndex((cell) => cell.key === cellId);+ let focusIndex = before ? index - 1 : index + 1;+ // clamp+ focusIndex = Math.max(0, Math.min(focusIndex, state.present.length - 1));+ // can scroll immediately, without setting scrollKey in state, because+ // CellArray won't need to re-render+ focusAndScrollCellIntoView(state.present[focusIndex]);+ return state;+ },+ focusTopCell: (state) => {+ if (state.present.length === 0) {+ return state;+ }- const { cellKey, before } = action;- const index = state.present.findIndex((cell) => cell.key === cellKey);- let focusIndex = before ? index - 1 : index + 1;- // clamp- focusIndex = Math.max(0, Math.min(focusIndex, state.present.length - 1));- // can scroll immediately, without setting scrollKey in state, because- // CellArray won't need to re-render- focusAndScrollCellIntoView(state.present[focusIndex]);+ state.present[0].ref.current?.editorView.focus();+ scrollToTop();+ return state;+ },+ focusBottomCell: (state) => {+ if (state.present.length === 0) {return state;}- case "FOCUS_TOP_CELL":- if (state.present.length === 0) {- return state;- }- state.present[0].ref.current?.editorView.focus();- scrollToTop();+ state.present[state.present.length - 1].ref.current?.editorView.focus();+ scrollToBottom();+ return state;+ },+ sendToTop: (state, action: { cellId: CellId }) => {+ if (state.present.length === 0) {return state;+ }- case "FOCUS_BOTTOM_CELL":- if (state.present.length === 0) {- return state;- }+ const { cellId } = action;+ const index = state.present.findIndex((cell) => cell.key === cellId);+ return {+ ...state,+ present: arrayMove(state.present, index, 0),+ scrollKey: cellId,+ };+ },+ sendToBottom: (state, action: { cellId: CellId }) => {+ if (state.present.length === 0) {+ return state;+ }- state.present[state.present.length - 1].ref.current?.editorView.focus();- scrollToBottom();+ const { cellId } = action;+ const index = state.present.findIndex((cell) => cell.key === cellId);+ return {+ ...state,+ present: arrayMove(state.present, index, state.present.length - 1),+ scrollKey: cellId,+ };+ },+ deleteCell: (state, action: { cellId: CellId }) => {+ const cellId = action.cellId;+ if (state.present.length === 1) {return state;+ }- case "SEND_TO_TOP": {- if (state.present.length === 0) {- return state;- }+ const index = state.present.findIndex((cell) => cell.key === cellId);+ const focusIndex = index === 0 ? 1 : index - 1;+ const scrollKey = state.present[focusIndex].key;- const { cellKey } = action;- const index = state.present.findIndex((cell) => cell.key === cellKey);- return {- ...state,- present: [- state.present[index],- ...state.present.slice(0, index),- ...state.present.slice(index + 1),+ return {+ present: arrayDelete(state.present, index),+ history: [+ ...state.history,+ [+ state.present[index].name,+ state.present[index].ref.current?.editorStateJSON(),+ index,],- scrollKey: cellKey,- };- }- case "SEND_TO_BOTTOM": {- if (state.present.length === 0) {- return state;- }+ ],+ scrollKey: scrollKey,+ };+ },+ undoDeleteCell: (state) => {+ if (state.history.length === 0) {+ return state;+ } else {+ const mostRecentlyDeleted = state.history[state.history.length - 1];- const { cellKey } = action;- const index = state.present.findIndex((cell) => cell.key === cellKey);+ const name = mostRecentlyDeleted[0];+ const serializedEditorState = mostRecentlyDeleted[1] || {+ doc: "",+ };+ const index = mostRecentlyDeleted[2];+ const undoCell = createCell({+ key: CellId.create(),+ name,+ initialContents: serializedEditorState.doc,+ code: serializedEditorState.doc,+ edited: serializedEditorState.doc.trim().length > 0,+ serializedEditorState,+ });return {...state,- present: [- ...state.present.slice(0, index),- ...state.present.slice(index + 1),- state.present[index],- ],- scrollKey: cellKey,+ present: arrayInsert(state.present, index, undoCell),+ history: state.history.slice(0, -1),};}- case "DELETE_CELL": {- const cellKey = action.cellKey;- if (state.present.length === 1) {- return state;- }-- const index = state.present.findIndex((cell) => cell.key === cellKey);- const focusIndex = index === 0 ? 1 : index - 1;- const scrollKey = state.present[focusIndex].key;-- return {- present: [- ...state.present.slice(0, index),- ...state.present.slice(index + 1),- ],- history: [- ...state.history,- [- state.present[index].name,- state.present[index].ref.current?.editorStateJSON(),- index,- ],- ],- scrollKey: scrollKey,- };+ },+ updateCellCode: (+ state,+ action: {+ cellId: CellId;+ code: string;+ /**+ * Whether or not the update is a formatting change,+ * if so, the 'edited' state will be handled differently.+ */+ formattingChange: boolean;}- case "UNDO_DELETE_CELL":- if (state.history.length === 0) {- return state;- } else {- const mostRecentlyDeleted = state.history[state.history.length - 1];+ ) => {+ const { cellId, code, formattingChange } = action;+ const cellToUpdate = state.present.find((cell) => cell.key === cellId);- const name = mostRecentlyDeleted[0];- const serializedEditorState = mostRecentlyDeleted[1] || {- doc: "",- };- const index = mostRecentlyDeleted[2];-- const cells = [- ...state.present.slice(0, index),- createCell({- key: CellId.create(),- name,- initialContents: serializedEditorState.doc,- code: serializedEditorState.doc,- edited: serializedEditorState.doc.trim().length > 0,- serializedEditorState,- }),- ...state.present.slice(index),- ];-- return {- ...state,- present: cells,- history: state.history.slice(0, -1),- };- }-- case "UPDATE_CELL_CODE": {- const cellToUpdate = state.present.find(- (cell) => cell.key === action.cellKey- );- if (!cellToUpdate) {- return state;- }- if (cellToUpdate.code === action.code) {- return state;- }+ if (!cellToUpdate || cellToUpdate.code === code) {+ return state;+ }- return {- ...state,- present: state.present.map((cell) => {- if (cell.key === action.cellKey) {- return action.formattingChange- ? // Formatting-only change means we can re-use the last code run- // if it was not previously edited. And we don't change the edited state.- {- ...cell,- code: action.code,- lastCodeRun: cell.edited ? cell.lastCodeRun : action.code,- }- : {- ...cell,- code: action.code,- edited: action.code.trim() !== cell.lastCodeRun,- };+ return updateCell(state, cellId, (cell) => {+ // Formatting-only change means we can re-use the last code run+ // if it was not previously edited. And we don't change the edited state.+ return formattingChange+ ? {+ ...cell,+ code: code,+ lastCodeRun: cell.edited ? cell.lastCodeRun : code,}- return cell;- }),+ : {+ ...cell,+ code: code,+ edited: code.trim() !== cell.lastCodeRun,+ };+ });+ },+ updateCellConfig: (+ state,+ action: { cellId: CellId; config: Partial<CellConfig> }+ ) => {+ const { cellId, config } = action;+ return updateCell(state, cellId, (cell) => {+ return {+ ...cell,+ config: { ...cell.config, ...config },};+ });+ },+ prepareForRun: (state, action: { cellId: CellId }) => {+ const cellToUpdate = state.present.find(+ (cell) => cell.key === action.cellId+ );+ if (!cellToUpdate) {+ return state;}- case "PREPARE_FOR_RUN": {- const cellToUpdate = state.present.find(- (cell) => cell.key === action.cellKey- );- if (!cellToUpdate) {- return state;- }+ return updateCell(state, action.cellId, (cell) => {+ return prepareCellForExecution(cell);+ });+ },+ handleCellMessage: (+ state,+ action: { cellId: CellId; message: CellMessage }+ ) => {+ const { cellId, message } = action;+ return updateCell(state, cellId, (cell) => {+ return transitionCell(cell, message);+ });+ },+ setCells: (state, cells: CellState[]) => {+ return {+ ...state,+ present: cells,+ };+ },+ /**+ * Move focus to next cell+ *+ * Creates a new cell if the current cell is the last one in the array.+ *+ * If needed, scrolls newly created or focused cell into view.+ *+ * Replicates Shift+Enter functionality of Jupyter+ */+ moveToNextCell: (state, action: { cellId: CellId; before: boolean }) => {+ const { cellId, before } = action;+ const index = state.present.findIndex((cell) => cell.key === cellId);+ const nextCellIndex = before ? index - 1 : index + 1;+ // Create a new cell at the end; no need to update scrollKey,+ // because cell will be created with autoScrollIntoView+ if (nextCellIndex === state.present.length) {+ const newCell = createCell({+ key: CellId.create(),+ });return {...state,- present: state.present.map((cell) => {- if (cell.key === action.cellKey) {- return prepareCellForExecution(cellToUpdate);- }- return cell;- }),+ present: [...state.present, newCell],};- }- case "HANDLE_CELL_MESSAGE": {- const { cellKey, message: body } = action;+ // Create a new cell at the beginning; again, no need to update+ // scrollKey+ } else if (nextCellIndex === -1) {+ const newCell = createCell({+ key: CellId.create(),+ });return {...state,- present: state.present.map((cell) => {- return cell.key === cellKey ? transitionCell(cell, body) : cell;- }),+ present: [newCell, ...state.present],};+ } else {+ // Just focus, no state change+ focusAndScrollCellIntoView(state.present[nextCellIndex]);+ return state;}- case "SET_CELLS":+ },+ scrollToTarget: (state) => {+ // Scroll to the specified cell and clear the scroll key.+ const scrollKey = state.scrollKey;+ if (scrollKey === null) {+ return state;+ } else {+ const index = state.present.findIndex((cell) => cell.key === scrollKey);++ // Special-case scrolling to the end of the page: bug in Chrome where+ // browser fails to scrollIntoView an element at the end of a long page+ if (index === state.present.length - 1) {+ state.present[state.present.length - 1].ref.current?.editorView.focus();+ scrollToBottom();+ } else {+ focusAndScrollCellIntoView(state.present[index]);+ }+return {...state,- present: action.cells,+ scrollKey: null,};- /**- * Move focus to next cell- *- * Creates a new cell if the current cell is the last one in the array.- *- * If needed, scrolls newly created or focused cell into view.- *- * Replicates Shift+Enter functionality of Jupyter- */- case "MOVE_TO_NEXT_CELL": {- const { cellKey, before } = action;- const index = state.present.findIndex((cell) => cell.key === cellKey);- const nextCellIndex = before ? index - 1 : index + 1;- // Create a new cell at the end; no need to update scrollKey,- // because cell will be created with autoScrollIntoView- if (nextCellIndex === state.present.length) {- const newCell = createCell({- key: CellId.create(),- });- return {- ...state,- present: [...state.present, newCell],- };- // Create a new cell at the beginning; again, no need to update- // scrollKey- } else if (nextCellIndex === -1) {- const newCell = createCell({- key: CellId.create(),- });- return {- ...state,- present: [newCell, ...state.present],- };- } else {- // Just focus, no state change- focusAndScrollCellIntoView(state.present[nextCellIndex]);- return state;- }}- case "SCROLL_TO_TARGET": {- // Scroll to the specified cell and clear the scroll key.- const scrollKey = state.scrollKey;- if (scrollKey === null) {- return state;- } else {- const index = state.present.findIndex((cell) => cell.key === scrollKey);+ },+ foldAll: (state) => {+ const targets = state.present.map((cell) => cell.ref.current?.editorView);+ foldAllBulk(targets);+ return state;+ },+ unfoldAll: (state) => {+ const targets = state.present.map((cell) => cell.ref.current?.editorView);+ unfoldAllBulk(targets);+ return state;+ },+});- // Special-case scrolling to the end of the page: bug in Chrome where- // browser fails to scrollIntoView an element at the end of a long page- if (index === state.present.length - 1) {- state.present[- state.present.length - 1- ].ref.current?.editorView.focus();- scrollToBottom();- } else {- focusAndScrollCellIntoView(state.present[index]);- }-- return {- ...state,- scrollKey: null,- };- }- }- case "FOLD_ALL": {- const targets = state.present.map((cell) => cell.ref.current?.editorView);- foldAllBulk(targets);- return state;- }- case "UNFOLD_ALL": {- const targets = state.present.map((cell) => cell.ref.current?.editorView);- unfoldAllBulk(targets);- return state;- }- default:- return state;- }+// Helper function to update a cell in the array+function updateCell(+ state: CellsAndHistory,+ cellId: CellId,+ cellReducer: ReducerWithoutAction<CellState>+) {+ return {+ ...state,+ present: state.present.map((cell) =>+ cell.key === cellId ? cellReducer(cell) : cell+ ),+ };}const cellsAtom = atom<CellsAndHistory>(initialCellState());+/**+ * Get the array of cells.+ */export const useCells = () => useAtomValue(cellsAtom);+/**+ * Get the editor views for all cells.+ */export const getAllEditorViews = () => {const cells = store.get(cellsAtom).present;return cells@@ -485,89 +396,20 @@ export function useCellActions() {const setState = useSetAtom(cellsAtom);return useMemo(() => {- const dispatch = (action: CellAction) => {+ const actions = createActions((action) => {setState((state) => reducer(state, action));- };-- return {- updateCellCode: (- cellKey: CellId,- code: string,- formattingChange = false- ) =>- dispatch({- type: "UPDATE_CELL_CODE",- cellKey,- code,- formattingChange,- }),- prepareForRun: (cellKey: CellId) => {- dispatch({ type: "PREPARE_FOR_RUN", cellKey });- },- createNewCell: (cellKey: CellId, before: boolean) => {- dispatch({ type: "CREATE_CELL", cellKey, before });- },- deleteCell: (cellKey: CellId) => {- dispatch({ type: "DELETE_CELL", cellKey });- },- undoDeleteCell: () => {- dispatch({ type: "UNDO_DELETE_CELL" });- },- focusCell: (cellKey: CellId, before: boolean) => {- dispatch({ type: "FOCUS_CELL", cellKey, before });- },- moveCell: (cellKey: CellId, before: boolean) => {- dispatch({ type: "MOVE_CELL", cellKey, before });- },- dropCellOver: (cellKey: CellId, overCellKey: CellId) => {- dispatch({ type: "DROP_CELL_OVER", cellKey, overCellKey });- },- /* Move focus to next cell- *- * Creates a new cell if the current cell is the last one in the array.- *- * If needed, scrolls newly created or focused cell into view.- *- * Replicates Shift+Enter functionality of Jupyter- */- moveToNextCell: (cellKey: CellId, before: boolean) => {- dispatch({ type: "MOVE_TO_NEXT_CELL", cellKey, before });- },- setCells: (cells: CellState[]) => {- dispatch({ type: "SET_CELLS", cells });- },- handleCellMessage: (cellKey: CellId, message: CellMessage) => {- dispatch({ type: "HANDLE_CELL_MESSAGE", cellKey, message });- },- focusTopCell: () => {- dispatch({ type: "FOCUS_TOP_CELL" });- },- focusBottomCell: () => {- dispatch({ type: "FOCUS_BOTTOM_CELL" });- },- sendToTop: (cellKey: CellId) => {- dispatch({ type: "SEND_TO_TOP", cellKey });- },- sendToBottom: (cellKey: CellId) => {- dispatch({ type: "SEND_TO_BOTTOM", cellKey });- },- scrollToTarget: () => {- dispatch({ type: "SCROLL_TO_TARGET" });- },- foldAll: () => {- dispatch({ type: "FOLD_ALL" });- },- unfoldAll: () => {- dispatch({ type: "UNFOLD_ALL" });- },- };+ });+ return actions;}, [setState]);}+export type CellActions = ReturnType<typeof createActions>;+/*** This is exported for testing purposes only.*/export const exportedForTesting = {reducer,+ createActions,initialCellState,};diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex 74c45956bf..b8fb1d9d01 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -116,7 +116,7 @@ export function useMarimoWebSocket(opts: {* affects how the cell should be rendered.*/const body = msg.data;- handleCellMessage(body.cell_id, body);+ handleCellMessage({ cellId: body.cell_id, message: body });return;}default:diff --git a/frontend/src/editor/Cell.tsx b/frontend/src/editor/Cell.tsxindex d3f55d6156..1eabead265 100644--- a/frontend/src/editor/Cell.tsx+++ b/frontend/src/editor/Cell.tsx@@ -20,7 +20,7 @@ import { autocompletionKeymap, setupCodeMirror } from "@/core/codemirror/cm";import { UserConfig } from "../core/config";import { CellState } from "../core/model/cells";-import { useCellActions } from "../core/state/cells";+import { CellActions, useCellActions } from "../core/state/cells";import { derefNotNull } from "../utils/dereference";import { ConsoleOutputArea, OutputArea } from "./Output";import { CreateCellButton } from "./cell/CreateCellButton";@@ -36,7 +36,7 @@ import { SerializedEditorState } from "../core/codemirror/types";import { CellDragHandle, SortableCell } from "./SortableCell";import { CellId, HTMLCellId } from "../core/model/ids";import { Theme } from "../theme/useTheme";-import { CellActions } from "./cell/cell-actions";+import { CellActionsDropdown } from "./cell/cell-actions";/*** Imperative interface of the cell.@@ -58,26 +58,31 @@ export interface CellHandle {export interface CellPropsextends Pick<- CellState,- | "consoleOutputs"- | "status"- | "output"- | "initialContents"- | "edited"- | "errored"- | "interrupted"- | "stopped"- | "runElapsedTimeMs"- > {+ CellState,+ | "consoleOutputs"+ | "status"+ | "output"+ | "initialContents"+ | "edited"+ | "errored"+ | "interrupted"+ | "config"+ | "stopped"+ | "runElapsedTimeMs"+ >,+ Pick<+ CellActions,+ | "updateCellCode"+ | "prepareForRun"+ | "createNewCell"+ | "deleteCell"+ | "focusCell"+ | "moveCell"+ | "moveToNextCell"+ > {theme: Theme;showPlaceholder: boolean;cellId: CellId;- updateCellCode: (- cellId: CellId,- code: string,- formattingChange?: boolean- ) => void;- prepareCellForRun: (cellId: CellId) => void;registerRunStart: () => void;serializedEditorState: SerializedEditorState | null;editing: boolean;@@ -88,11 +93,6 @@ export interface CellProps* This is false when the app is initially loading.*/allowFocus: boolean;- createNewCell: (cellId: CellId, before: boolean) => void;- deleteCell: (cellId: CellId) => void;- focusCell: (cellId: CellId, before: boolean) => void;- moveCell: (cellId: CellId, before: boolean) => void;- moveToNextCell: (cellId: CellId, before: boolean) => void;userConfig: UserConfig;}@@ -118,13 +118,14 @@ const CellComponent = (appClosed,showDeleteButton,updateCellCode,- prepareCellForRun,+ prepareForRun,createNewCell,deleteCell,focusCell,moveCell,moveToNextCell,userConfig,+ config: cellConfig,}: CellProps,ref: React.ForwardedRef<CellHandle>) => {@@ -148,9 +149,9 @@ const CellComponent = (const prepareToRunEffects = useCallback(() => {const code = derefNotNull(editorView).state.doc.toString();closeCompletion(derefNotNull(editorView));- prepareCellForRun(cellId);+ prepareForRun({ cellId });return code;- }, [cellId, editorView, prepareCellForRun]);+ }, [cellId, editorView, prepareForRun]);// An imperative interface to the code editoruseImperativeHandle(@@ -181,27 +182,27 @@ const CellComponent = (}, [cellId, registerRunStart, prepareToRunEffects]);const createBelow = useCallback(- () => createNewCell(cellId, /*before=*/ false),+ () => createNewCell({ cellId, before: false }),[cellId, createNewCell]);const createAbove = useCallback(- () => createNewCell(cellId, /*before=*/ true),+ () => createNewCell({ cellId, before: true }),[cellId, createNewCell]);const moveDown = useCallback(- () => moveCell(cellId, /*before=*/ false),+ () => moveCell({ cellId, before: false }),[cellId, moveCell]);const moveUp = useCallback(- () => moveCell(cellId, /*before=*/ true),+ () => moveCell({ cellId, before: true }),[cellId, moveCell]);const focusDown = useCallback(- () => focusCell(cellId, /*before=*/ false),+ () => focusCell({ cellId, before: false }),[cellId, focusCell]);const focusUp = useCallback(- () => focusCell(cellId, /*before=*/ true),+ () => focusCell({ cellId, before: true }),[cellId, focusCell]);@@ -209,7 +210,7 @@ const CellComponent = (const deleteCellIfNotRunning = () => {// Cannot delete running cells, since we're waiting for their output.if (!runningOrQueuedRef.current) {- deleteCell(cellId);+ deleteCell({ cellId });return true;}return false;@@ -405,7 +406,7 @@ const CellComponent = (className={className}onBlur={closeCompletionHandler}onKeyDown={resumeCompletionHandler}- cellKey={cellId}+ cellId={cellId}>{outputArea}<div className="tray">@@ -441,13 +442,14 @@ const CellComponent = (status={status}needsRun={needsRun}/>- <CellActions+ <CellActionsDropdowncellId={cellId}editorView={editorView.current}+ config={cellConfig}hasOutput={!!output}><CellDragHandle />- </CellActions>+ </CellActionsDropdown></div></div><div className="shoulder-bottom hover-action">@@ -457,7 +459,7 @@ const CellComponent = (status={status}onClick={() => {if (!loading && !appClosed) {- deleteCell(cellId);+ deleteCell({ cellId });}}}/>diff --git a/frontend/src/editor/SortableCell.tsx b/frontend/src/editor/SortableCell.tsxindex 7820a7982e..71f91b5b33 100644--- a/frontend/src/editor/SortableCell.tsx+++ b/frontend/src/editor/SortableCell.tsx@@ -7,7 +7,7 @@ import { GripVerticalIcon } from "lucide-react";import { CellId } from "@/core/model/ids";interface Props extends React.HTMLAttributes<HTMLDivElement> {- cellKey: CellId;+ cellId: CellId;}/**@@ -22,7 +22,7 @@ export const CellDragHandle: React.FC = memo(() => {CellDragHandle.displayName = "DragHandle";const SortableCellInternal = React.forwardRef(- ({ cellKey, ...props }: Props, ref: React.Ref<HTMLDivElement>) => {+ ({ cellId, ...props }: Props, ref: React.Ref<HTMLDivElement>) => {// Sortconst {attributes,@@ -31,7 +31,7 @@ const SortableCellInternal = React.forwardRef(transform,transition,isDragging,- } = useSortable({ id: cellKey.toString() });+ } = useSortable({ id: cellId.toString() });const style: React.CSSProperties = {transform: transformdiff --git a/frontend/src/editor/cell/cell-actions.tsx b/frontend/src/editor/cell/cell-actions.tsxindex 812b4f0371..cdb3adbca6 100644--- a/frontend/src/editor/cell/cell-actions.tsx+++ b/frontend/src/editor/cell/cell-actions.tsx@@ -32,6 +32,7 @@ import {ImageIcon,PlusCircleIcon,Trash2Icon,+ ZapIcon,} from "lucide-react";import { downloadCellOutput } from "@/components/export/export-output-button";import { HotkeyAction } from "@/core/hotkeys/hotkeys";@@ -39,11 +40,14 @@ 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";interface Props {editorView: EditorView | null;hasOutput: boolean;cellId: CellId;+ config: CellConfig;}interface Action {@@ -52,18 +56,21 @@ interface Action {hotkey?: HotkeyAction;icon?: React.ReactNode;hidden?: boolean;+ rightElement?: React.ReactNode;handle: () => void;}-export const CellActions = ({+export const CellActionsDropdown = ({cellId,children,hasOutput,editorView,+ config,}: PropsWithChildren<Props>) => {const [open, setOpen] = useState(false);const {- createNewCell,+ createNewCell: createCell,+ updateCellConfig,updateCellCode,deleteCell,focusCell,@@ -71,6 +78,13 @@ export const CellActions = ({sendToTop,sendToBottom,} = useCellActions();+ const toggleAutoRun = () => {+ if (config.autoRun === false) {+ updateCellConfig({ cellId, config: { autoRun: null } });+ } else {+ updateCellConfig({ cellId, config: { autoRun: false } });+ }+ };const actions: Action[][] = [// Actions@@ -92,6 +106,22 @@ export const CellActions = ({formatEditorViews({ [cellId]: editorView }, updateCellCode);},},+ {+ icon: <ZapIcon size={13} strokeWidth={1.5} />,+ // TODO: this feature is still a WIP+ hidden: true,+ label:+ config.autoRun === false ? "Enable auto-run" : "Disable auto-run",+ rightElement: (+ <Switch+ // null implies true+ checked={config.autoRun === false ? false : true}+ size="sm"+ onCheckedChange={toggleAutoRun}+ />+ ),+ handle: toggleAutoRun,+ },],// Movement@@ -105,7 +135,7 @@ export const CellActions = ({),label: "Create cell above",hotkey: "cell.createAbove",- handle: () => createNewCell(cellId, /*before=*/ true),+ handle: () => createCell({ cellId, before: true }),},{icon: (@@ -116,19 +146,19 @@ export const CellActions = ({),label: "Create cell below",hotkey: "cell.createBelow",- handle: () => createNewCell(cellId, /*before=*/ false),+ handle: () => createCell({ cellId, before: false }),},{icon: <ChevronUpIcon size={13} strokeWidth={1.5} />,label: "Move cell up",hotkey: "cell.moveUp",- handle: () => moveCell(cellId, /*before=*/ true),+ handle: () => moveCell({ cellId, before: true }),},{icon: <ChevronDownIcon size={13} strokeWidth={1.5} />,label: "Move cell down",hotkey: "cell.moveDown",- handle: () => moveCell(cellId, /*before=*/ false),+ handle: () => moveCell({ cellId, before: false }),},{icon: (@@ -139,7 +169,7 @@ export const CellActions = ({),label: "Focus cell above",hotkey: "cell.focusUp",- handle: () => focusCell(cellId, /*before=*/ true),+ handle: () => focusCell({ cellId, before: true }),},{icon: (@@ -150,19 +180,19 @@ export const CellActions = ({),label: "Focus cell below",hotkey: "cell.focusDown",- handle: () => focusCell(cellId, /*before=*/ false),+ handle: () => focusCell({ cellId, before: false }),},{icon: <ChevronsUpIcon size={13} strokeWidth={1.5} />,label: "Send to top",hotkey: "cell.sendToTop",- handle: () => sendToTop(cellId),+ handle: () => sendToTop({ cellId }),},{icon: <ChevronsDownIcon size={13} strokeWidth={1.5} />,label: "Send to bottom",hotkey: "cell.sendToBottom",- handle: () => sendToBottom(cellId),+ handle: () => sendToBottom({ cellId }),},],@@ -172,7 +202,7 @@ export const CellActions = ({label: "Delete",variant: "danger",icon: <Trash2Icon size={13} strokeWidth={1.5} />,- handle: () => deleteCell(cellId),+ handle: () => deleteCell({ cellId }),},],];diff --git a/frontend/src/editor/renderers/CellArray.tsx b/frontend/src/editor/renderers/CellArray.tsxindex 733fb99b30..c893e605a2 100644--- a/frontend/src/editor/renderers/CellArray.tsx+++ b/frontend/src/editor/renderers/CellArray.tsx@@ -85,9 +85,9 @@ export const CellArray: React.FC<CellArrayProps> = ({formatEditorViews(views, updateCellCode);});- const onDeleteCell = useEvent((cellId: CellId) => {- sendDeleteCell(cellId);- deleteCell(cellId);+ const onDeleteCell: typeof deleteCell = useEvent((payload) => {+ sendDeleteCell(payload.cellId);+ deleteCell(payload);});// Scroll to a cell targeted by a previous action@@ -119,7 +119,7 @@ export const CellArray: React.FC<CellArrayProps> = ({consoleOutputs={cell.consoleOutputs}status={cell.status}updateCellCode={updateCellCode}- prepareCellForRun={prepareForRun}+ prepareForRun={prepareForRun}edited={cell.edited}interrupted={cell.interrupted}errored={cell.errored}@@ -137,6 +137,7 @@ export const CellArray: React.FC<CellArrayProps> = ({appClosed={connStatus.state !== WebSocketState.OPEN}ref={cell.ref}userConfig={userConfig}+ config={cell.config}/>))}</div>diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsxindex 252e7820ae..7a79ff9586 100644--- a/frontend/src/stories/cell.stories.tsx+++ b/frontend/src/stories/cell.stories.tsx@@ -26,7 +26,7 @@ const props: CellProps = {errored: false,stopped: false,updateCellCode: console.log,- prepareCellForRun: console.log,+ prepareForRun: console.log,registerRunStart: console.log,runElapsedTimeMs: 10,serializedEditorState: null,@@ -39,6 +39,7 @@ const props: CellProps = {focusCell: console.log,moveCell: console.log,moveToNextCell: console.log,+ config: {},userConfig: {completion: {activate_on_typing: true,diff --git a/frontend/src/utils/arrays.ts b/frontend/src/utils/arrays.tsnew file mode 100644index 0000000000..d21c7c04b3--- /dev/null+++ b/frontend/src/utils/arrays.ts@@ -0,0 +1,8 @@+/* Copyright 2023 Marimo. All rights reserved. */+export function arrayDelete<T>(array: T[], index: number): T[] {+ return [...array.slice(0, index), ...array.slice(index + 1)];+}++export function arrayInsert<T>(array: T[], index: number, value: T): T[] {+ return [...array.slice(0, index), value, ...array.slice(index)];+}diff --git a/frontend/src/utils/createReducer.ts b/frontend/src/utils/createReducer.tsnew file mode 100644index 0000000000..8769c9f119--- /dev/null+++ b/frontend/src/utils/createReducer.ts@@ -0,0 +1,70 @@+/* Copyright 2023 Marimo. All rights reserved. */+/* eslint-disable @typescript-eslint/no-explicit-any */+import { Logger } from "@/utils/Logger";+import { NoInfer } from "@tanstack/react-table";+import { Reducer } from "react";++interface ReducerAction<T> {+ type: string;+ payload: T;+}++type Dispatch = (action: ReducerAction<any>) => void;+type IfUnknown<T, Y, N> = unknown extends T ? Y : N;++interface ReducerHandler<State, Payload> {+ (state: State, payload: Payload): State;+}++interface ReducerHandlers<State> {+ [K: string]: ReducerHandler<State, any>;+}++type ReducerActions<RH extends ReducerHandlers<any>> = {+ [Type in keyof RH]: RH[Type] extends ReducerHandler<any, infer Payload>+ ? IfUnknown<Payload, () => void, (payload: Payload) => void>+ : never;+};++export interface ReducerCreatorResult<+ State,+ RH extends ReducerHandlers<State>+> {+ /**+ * The reducer function.+ */+ reducer: Reducer<State, any>;+ /**+ * Given a dispatch function, returns an object containing all the actions.+ */+ createActions: (dispatch: Dispatch) => ReducerActions<RH>;+}++/**+ * Utility function to create a reducer and its actions.+ */+export function createReducer<+ State,+ RH extends ReducerHandlers<NoInfer<State>>+>(initialState: () => State, reducers: RH): ReducerCreatorResult<State, RH> {+ return {+ reducer: (state, action: ReducerAction<any>) => {+ state = state || initialState();+ if (action.type in reducers) {+ return reducers[action.type](state, action.payload);+ } else {+ Logger.error(`Action type ${action.type} is not defined in reducers.`);+ }+ return state;+ },+ createActions: (dispatch: Dispatch) => {+ const actions = {} as ReducerActions<RH>;+ for (const type in reducers) {+ (actions as any)[type] = (payload: any) => {+ dispatch({ type, payload });+ };+ }+ return actions;+ },+ };+}